Coder Social home page Coder Social logo

bernhard-42 / jupyter-cadquery Goto Github PK

View Code? Open in Web Editor NEW
312.0 15.0 44.0 101.03 MB

An extension to render cadquery objects in JupyterLab via pythreejs

License: Apache License 2.0

Jupyter Notebook 19.47% Python 78.51% Dockerfile 0.32% Makefile 0.69% Shell 0.68% Batchfile 0.33%
jupyterlab ipywidgets cadquery pythonocc cad python

jupyter-cadquery's Introduction

Jupyter-CadQuery

View CadQuery objects in JupyterLab or in a standalone viewer for any IDE

Overview

Click on the "launch binder" icon to start Jupyter-CadQuery on binder:

Binder: Latest development version

Overview

Release 3 is a complete rewrite of Jupyter-CadQuery: While the selection of pythreejs and JupyterLab's sidecar looked reasonable in 2019, it turned out they had too many limitations. pythreejs is stuck with an outdated version of threejs and the sidecar project did not improve usability to a level I would have liked to have.

Jupyter-CadQuery is now a 3 layer project:

  1. three-cad-viewer This is the complete CAD viewer written in Javascript with threejs being the only dependency. There is are a bunch of live examples and an API documentation.

  2. cad-view-widget A thin layer on top of cad-viewer-widget that wraps the CAD viewer into an ipywidget. The API documentation can be found here

  3. jupyter-cadquery (this repository) The actual CadQuery viewer, collecting and tessellating CadQuery objects, using cad-view-widget to visualize the objects. It was written with the intent to be as compatible with Jupyter-CadQuery 2.x as reasonable.

    Note: For changes see the migration section at the end of this page.

Key Features

  • CadQuery support
  • STEP files
    • A STEP reader to load STEP files into CadQuery Assemblies preserving hierarchy, names and colors
  • Viewing options:
    • Directly in the JupyterLab output cell
    • In a central Jupyterlab sidecar for any JupyterLab cell
    • As a standalone viewer for use from any IDE
  • Animations (see examples below)
    • Support Manual Assemblies with animation of model
    • Animated explode mode for CadQuery assemblies
  • Debugging
    • Step-by-step in an IDE with the standalone viewer (see example below)
    • Visually
      • by displaying selected CadQuery faces and edges
      • by replaying steps of the rendered object in the Notebook (see example below)
  • Viewer features
    • Toggle visibility of shapes and edges
    • Orthographic and perspective view
    • Clipping with max 3 clipping planes (of free orientation)
    • Transparency mode
    • Double click on shapes shows bounding box info
    • Click on tree labels shows bounding box info and optionally hides or isolates the sub tree

Release v3.5.2 (03.01.2023)

Changes

  • Default python now is 3.10
  • Add support for Compounds with mixed shape types
  • Aligned show_object with CQ-Editor (e.g. support options dict)
  • Improved build123d support
  • Add support for my private Alg123d library (a thin facade on top of build123d to remove all implicit behavior and give control back to the user)

Fixes

  • OCCT bug with helix: If height = 2 * pitch, GCPnts_QuasiUniformDeflection returns 2 points only. Jupyter CadQuery detects this and uses GCPnts_QuasiUniformAbscissa instead

Examples

Animation system in JupyterLab

Debugging

  • In VS Code with Standalone Viewer

    • The top half is the CadQuery code being debugged in VS Code

    • The bottom half is the standalone viewer in a browser window

    • The show command in the code will tessellate the objects and send them via zmq to the standalone viewer

      Debugging in IDE

  • By replaying in the notebook

    Replaying

Installation

Using conda

  1. For using Jupyter-CadQuery in Jupyterlab

    • If you don't have it already, create a new conda environment with the latest CadQuery (e.g. master)

      conda create -n jcq3 -c conda-forge -c cadquery python=3.10 cadquery=master vtk=9.2.2
      conda activate jcq3
    • Install Jupyter-CadQuery (note, matplotlib is only used for the examples)

      pip install jupyter-cadquery==3.5.2 cadquery-massembly==1.0.0 matplotlib

      Windows users should also install pywin32 again with conda to ensure it is configured correctly

      conda install pywin32
    • Start Jupyter-CadQuery

      conda activate jcq3
      jupyter lab
    • If you use the dark theme of JuypterLab, add the following code in the first cell of your notebook:

      [1]: from jupyter_cadquery import set_defaults, open_viewer
           set_defaults(theme="dark")
           open_viewer("CadQuery")
  2. For running Jupyter-CadQuery as standalone viewer

    • Start the browser based viewer

      conda activate jcq3
      jcv [-w width] [-h height]     # light theme
      jcv [-w width] [-h height] -d  # dark theme
    • Use it from an IDE: In your code import the show or show_object function from the viewer:

      import cadquery as cq
      from jupyter_cadquery.viewer.client import show, show_object
      obj = cq. ...
      show(obj) # or show_object(obj)

      show works as in JupyterLab, while show_object views objects incrementally as in CQ-Editor

Using a docker image

  1. For using Jupyter-CadQuery in Jupyterlab

    • Start Jupyter-Cadquery

      WORKDIR=/tmp/jupyter
      mkdir -p "$WORKDIR"  # this has to exist, otherwise an access error will be thrown
      docker run -it --rm -v $WORKDIR:/home/cq -p 8888:8888 bwalter42/jupyter_cadquery:3.5.2

      Jupyter in the container will start in directory /home/cq

    • To start with examples, you can

      • omit the volume mapping and just run docker run -it --rm -p 8888:8888 bwalter42/jupyter_cadquery:3.5.2 or
      • copy the example notebooks to your $WORKDIR. They will be available for Jupyter-CadQuery in the container.
    • If you want to change the Dockerfile, make docker will create a new docker image

  2. For running Jupyter-CadQuery as standalone viewer

    • Start the browser based viewer (eventually add cli options, see notes below):

      docker run -it --rm -p 8888:8888 --name jcq -p 5555:5555 bwalter42/jupyter_cadquery:3.5.2 -v
    • In your code import the show or show_object function from the viewer:

      import cadquery as cq
      from jupyter_cadquery.viewer.client import show, show_object
      obj = cq. ...
      show(obj) # or show_object(obj)

      show works as in JupyterLab, while show_object views objects incrementally as in CQ-Editor

    • Execute your code using the Python interpreter located in the container:

      docker exec -i jcq bash -c ". /opt/conda/bin/activate cq; python" < my_project.py

Notes:

  • To simplify port forwarding, the viewer in the docker container also starts with port 8888 (and not with voila's default port 8866)
  • Port 5555 (the zmq port) needs to be forwarded. The show of the viewer client will send cad objects to this port
  • Use -d for dark mode and -w, -h to set dimensions of the CAD viewer

Demo Notebooks

Usage

a) Show objects

**show(cad_objs, **kwargs)**

Positional arguments args:

  • cad_objs: Comma separated list of cadquery objects;

Keywork arguments kwargs:

  • Display options

    • viewer: Name of the sidecar viewer (default=None)
    • anchor: How to open sidecar: "right", "split-right", "split-bottom", ... (default="right")
    • cad_width: Width of CAD view part of the view (default=800)
    • tree_width: Width of navigation tree part of the view (default=250)
    • height: Height of the CAD view (default=600)
    • theme: Theme "light" or "dark" (default="light")
    • pinning: Allow replacing the CAD View by a canvas screenshot (default=True in cells, else False)
  • Tessellation options

    • angular_tolerance: Shapes: Angular deflection in radians for tessellation (default=0.2)
    • deviation: Shapes: Deviation from linear deflection value (default=0.1)
    • edge_accuracy: Edges: Precision of edge discretization (default=None, i.e. mesh quality / 100)
    • default_color: Default face color (default=(232, 176, 36))
    • default_edge_color: Default edge color (default="#707070")
    • optimal_bb: Use optimal bounding box (default=False)
    • render_normals: Render the vertex normals (default=False)
    • render_edges: Render edges (default=True)
    • render_mates: Render mates (for MAssemblies, default=False)
    • mate_scale: Scale of rendered mates (for MAssemblies, default=1)
  • Viewer options

    • control: Use trackball controls ('trackball') or orbit controls ('orbit') (default='trackball')
    • up: Use z-axis ('Z') or y-axis ('Z') as up direction for the camera, legacy behaviour: 'L' (default='Z')
    • axes: Show axes (default=False)
    • axes0: Show axes at (0,0,0) (default=False)
    • grid: Show grid (default=[False, False, False])
    • ticks: Hint for the number of ticks in both directions (default=10)
    • ortho: Use orthographic projections (default=True)
    • transparent: Show objects transparent (default=False)
    • black_edges: Show edges in black (default=False)
    • position: Absolute camera position that will be scaled (default=None)
    • quaternion: Camera rotation as quaternion (x, y, z, w) (default=None)
    • target: Camera target to look at (default=None)
    • zoom: Zoom factor of view (default=2.5)
    • reset_camera: Reset camera position, rotation and zoom to default (default=True)
    • zoom_speed: Mouse zoom speed (default=1.0)
    • pan_speed: Mouse pan speed (default=1.0)
    • rotate_speed: Mouse rotate speed (default=1.0)
    • ambient_intensity: Intensity of ambient light (default=0.75)
    • direct_intensity: Intensity of direct lights (default=0.15)
    • show_parent: Show the parent for edges, faces and vertices objects
    • tools: Show the viewer tools like the object tree (default=True)
    • timeit: Show rendering times, levels = False, 0,1,2,3,4,5 (default=False)
    • js_debug: Enable debug output in browser console (default=False)
  • Not supported any more:

    • mac_scrollbar: The default now
    • bb_factor: Removed
    • display: Use 'viewer=""' (for sidecar display) or 'viewer=None' (for cell display)
    • quality: Use 'deviation'to control smoothness of rendered edges

b) Manage default values

  • set_defaults(**kwargs): allows to globally set the defaults value so they do not need to be provided with every show call

    kwargs:

    • see show
  • get_default(value): Get the global default for a single value

  • get_defaults(): Get all global defaults

  • reset_defaults(): Reset all defaults back to its initial value

c) Replay objects

Note, this is not supported in the standalone viewer for the time being.

  • replay(args)

    Argument args:

    • cad_obj: cadquery object
    • index (default=0): Element in the fluent API stack to show
    • debug (default=False): Trace building the replay stack
    • cad_width (default=600): Width of the CAD view
    • height (default=600): Height of the CAD view

d) Exports:

  • Export as PNG:

    Display your object via

    cv = show(a1)

    and adapt the cad view as wanted (camera location, axis, transparency, ...).

    Then call

    cv.export_png("example.png")
  • Export as HTML:

    Display your object without using a sidecar (set viewer to None) via

    cv = show(a1, viewer=None)

    and adapt the cad view as wanted (camera location, axis, transparency, ...).

    Then call

    cv.export_html()

    Note: This does not work with viewers in sidecars!

  • Export as STL:

    For CadQuery objects use CadQuery export functions. For PartGroups the following code can be used:

    from jupyter_cadquery.export import exportSTL
    
    exportSTL(
      part_group, "pg.stl", tolerance=quality, angular_tolerance=angular_tolerance
    )

    Smaller linear_deflection and angular_deflection means more details.

Jupyter-CadQuery classes

  • Part: A CadQuery shape plus some attributes for it:

    • shape: CadQuery shape
    • name: Part name in the view
    • color: Part color in the view
    • show_faces: show the faces of this particular part
    • show_edges: show the edges of this particular part
  • Faces: CadQuery faces plus some attributes

    • faces: List of CadQuery faces (shape.faces(selector)))
    • name: Part name in the view
    • color: Part color in the view
    • show_faces: show the faces for these particular faces
    • show_edges: show the edges for these particular faces
  • Edges:

    • edges: List of CadQuery edges (shape.edges(selector)))
    • name: Part name in the view
    • color: Part color in the view
  • Vertices:

    • vertices: List of CadQuery vertices (shape.vertices(selector)))
    • name: Part name in the view
    • color: Part color in the view
  • PartGroup: Basically a list of parts and some attributes for the view:

    • name: PartGroup name in the view
    • objects: all parts and assemblies included in the assembly as a list

Migration from 2.x

Deprecations:

  • Import structure changed:
    • from jupyter_cadquery.cadquery import show, ... will raise a deprecation error: Use from jupyter_cadquery import show, ... instead.
    • from jupyter_cadquery.occ import show, ... will raise a deprecation error: Use from jupyter_cadquery import show, ... instead.
    • from jupyter_cadquery.animation import Animation will raise a deprecation error: Use from jupyter_cadquery.cad_animation import Animation instead.
  • Sidecar handling changed
    • set_sidecar(title, init=True) will raise a deprecation error: Use open_viewer(title) instead.
    • close_sidecar() will raise a deprecation error: Use close_viewer(title) instead.
    • close_sidecars() will raise a deprecation error: Use close_viewers(title) instead.
  • Change parameters:
    • Parameter grid is now a tuple (xy-grid, xz-grid, yz-grid) instead of a boolean. A deprecation warning will be shown and the tuple (grid, False, False) used to invoke the old behavior.

Changed behavior:

  • The replay mode now shows the result's bounding box as top level step by default instead of the result. Use show_result=True for the old behavior.
  • New parameters viewer and anchor of function show set a sidecar (with title ) and anchor to determine location of the sidecar (right, split-right, split-left, split-top, split-bottom).
  • The parameter rotation of function show has been replaced by quaternion, since the new viewer uses quaternions instead of Euler angles.
  • The parameter quality is ignored. Use deviation to control smoothness of rendered edges.
  • In 7.5 of opencascade something changed with color handling, so some colors might be different.
  • The default view does not render the back material, making transparent views brighter. When switching to clipping view, the back material will set to the edge color to give the impression of cut planes. This means that transparent object look darker.

Parameters of function show and set_defaults not supported any more:

  • mac_scrollbar: This is used as default now.
  • bb_factor: Not necessary any more.
  • display: For sidecar display use viewer="<viewer title>" and for cell display use viewer=None.

Credits

  • Thomas Paviot for python-occ. Ideas are derived/taken from his jupyter_renderer.py
  • Dave Cowden for CadQuery
  • Adam Urbańczyk for the OCP version of CadQuery

Known issues

  • z-fighting happens some times, especially when using multiple clip planes (cannot be solved in general)
  • Using more than one clip plane will lead to cut surfaces not being shown as solid. (very hard to solve in general)

jupyter-cadquery's People

Contributors

bernhard-42 avatar bernhardbv avatar bollwyvl avatar dependabot[bot] avatar ilya-epifanov avatar jdegenstein avatar jojain avatar jsirois avatar roipoussiere avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jupyter-cadquery's Issues

Small example crash in jupyter_cadquery.cadquery.show()

This tiny example probably puts jupyter_cadquery.cadquery.show() into an infinite loop.

import cadquery as cq

r = cq.Workplane("XZ", (0,0,0))
r = r.moveTo(0, 0).lineTo(0.570634, 0.082918).lineTo(0.352671, 0.217082).lineTo(-0.352671, 0.217082).close()
r = r.workplane(offset=0.2, centerOption="ProjectedOrigin")
r = r.moveTo(0, 0).lineTo(0.475528, 0.069098).lineTo(0.293893, 0.180902).lineTo(-0.293893, 0.180902).close()
r = r.loft(combine=True)

from jupyter_cadquery.cadquery import show
show(r)   # <--- this now hangs at 100% on all four cores

(I left out the r=r.moveTo() in a previous version of this issue, but that's not the problem.)

The following tweak to the numbers makes it not crash in show(), so it's probably a bad surface that is bringing it down:

r = cq.Workplane("XZ", (0,0,0))
r = r.moveTo(0, 0).lineTo(1, 0).lineTo(1, 1).close()
r = r.workplane(offset=0.2, centerOption="ProjectedOrigin")
r = r.moveTo(0, 0).lineTo(0.4, 0.0).lineTo(0.3, 0.2).close()
r = r.loft(combine=True)

Docker image 2.2.1 out of date

I seems that the latest docker image has an out of date CadQuery version. I tried to run my code with the docker image but got this

AttributeError: module 'cadquery.selectors' has no attribute 'AreaNthSelector'

This works in cq-editor.

Is it possible to update the image with the latest cadquery?

Begginer need help with installation

Hi. I was to belive there is a problem when y try to install, but I really don't know how to install this.

Could anyone explain what to do with this, for example?
I gonna cite the installation instructions for conda

"a) Using conda
Create a conda environment with Jupyterlab:

Download the environment definition files:

wget https://raw.githubusercontent.com/bernhard-42/jupyter-cadquery/v1.0.0/environment.yml
wget https://raw.githubusercontent.com/bernhard-42/jupyter-cadquery/v1.0.0/labextensions.txt
Create the conda environment and install the Jupyter labextensions

conda env create -f ./environment.yml -n cq2-jl
conda activate cq2-jl

jupyter-labextension install --no-build $(cat labextensions.txt)
jupyter lab build --dev-build=True --minimize=False
Note, jupyter-labextension list should now show green "enabled OK" for “@jupyter-widgets/jupyterlab-manager, @jupyter-widgets/jupyterlab-sidecar, jupyter-threejs, jupyter_cadquery and jupyterlab-datawidgets

Run jupyter-cadquery

conda activate cq2-jl
jupyter lab"

I simply cant get it work. I try copy and paste in conda powershell but enviromient is never solved.

I also try Docker, with worst problems.

What is the obvious thing I am doing wrong? I really wanna use cadquery. But I cant install it!

Thanks. And sorry for my English, I am from Argentina.

Permission Denied Error When Running New Docker Image

I get a permission denied error when running the 1.0.0 image published yesterday.

System info:
Ubuntu 18.04
Docker version 19.03.12, build 48a66213fe

I pulled the 1.0.0 image via this command:

docker pull bwalter42/jupyter_cadquery:1.0.0

I then tried to run the following from the readme.

WORKDIR=/tmp/jupyter
docker run -it --rm -v $WORKDIR:/home/cq -p 8888:8888 bwalter42/jupyter_cadquery:1.0.0

And got this error:

PermissionError: [Errno 13] Permission denied: '/home/cq/.local'

Here's the full stack trace.

Traceback (most recent call last):
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/traitlets/traitlets.py", line 528, in get
    value = obj._trait_values[self.name]
KeyError: 'runtime_dir'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/conda/envs/cq/bin/jupyter-lab", line 10, in <module>
    sys.exit(main())
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/jupyter_core/application.py", line 270, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/traitlets/config/application.py", line 663, in launch_instance
    app.initialize(argv)
  File "<decorator-gen-7>", line 2, in initialize
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/traitlets/config/application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/notebook/notebookapp.py", line 2026, in initialize
    self.init_configurables()
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/notebook/notebookapp.py", line 1555, in init_configurables
    connection_dir=self.runtime_dir,
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/traitlets/traitlets.py", line 556, in __get__
    return self.get(obj, cls)
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/traitlets/traitlets.py", line 535, in get
    value = self._validate(obj, dynamic_default())
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/jupyter_core/application.py", line 100, in _runtime_dir_default
    ensure_dir_exists(rd, mode=0o700)
  File "/opt/conda/envs/cq/lib/python3.7/site-packages/jupyter_core/utils/__init__.py", line 13, in ensure_dir_exists
    os.makedirs(path, mode=mode)
  File "/opt/conda/envs/cq/lib/python3.7/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/opt/conda/envs/cq/lib/python3.7/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/opt/conda/envs/cq/lib/python3.7/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/opt/conda/envs/cq/lib/python3.7/os.py", line 223, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/home/cq/.local'

No model rendered

I setup a fresh environment using the instructions in the README, and am trying to render the example there "b) Example: CadQuery using Sidecar". This gives me the sidecar (a new panel on the left-hand side that labeled "CadQuery"), a "Tree" panel and a "Rendering Done" panel. However, no rendering appears. This is in Chrome 86 on Windows, running against jupyter-cadquery on linux.

Sorry for not including versions, but I'm not familiar enough with this distribution system to know what to include.

There are some threejs errors on the console:

  getInverse @ three.module.js:1532
  updateMatrixWorld @ three.module.js:20991
  updateMatrixWorld @ three.module.js:8747
  WebGLRenderer.render @ three.module.js:22946
  renderScene @ Renderable.js:383
  tock @ Renderable.js:268
  requestAnimationFrame (async)    
  tick @ Renderable.js:261
  triggerEvents @ backbone.js:370
  triggerApi @ backbone.js:356
  eventsApi @ backbone.js:155
  Events.trigger @ backbone.js:346
  onChildChanged @ Renderer.js:59
  triggerEvents @ backbone.js:369
  triggerApi @ backbone.js:356
  eventsApi @ backbone.js:155
  Events.trigger @ backbone.js:346
  onChildChanged @ Three.js:359
  triggerEvents @ backbone.js:369
  triggerApi @ backbone.js:356
  eventsApi @ backbone.js:155
  Events.trigger @ backbone.js:346
  onChildChanged @ Three.js:359
  triggerEvents @ backbone.js:370
  triggerApi @ backbone.js:356
  eventsApi @ backbone.js:155
  Events.trigger @ backbone.js:346
  set @ backbone-patch.js:118
  push.rynU.WidgetModel.set @ widget.js:295
  push.rynU.WidgetModel.set_state @ widget.js:229
  (anonymous) @ widget.js:213
  Promise.then (async)    
  push.rynU.WidgetModel._handle_comm_msg @ widget.js:212
  _handleCommMsg @ default.js:1028
  _handleMessage @ default.js:1144
  async function (async)    
  _handleMessage @ default.js:1096
  (anonymous) @ default.js:90
  Promise.then (async)    
  KernelConnection._onWSMessage @ default.js:87

And then this when I try to interact with the empty space that presumably holds the render:

  flatten @ three.module.js:15762
  setValueV4a @ three.module.js:16205
  push.Womt.WebGLUniforms.upload @ three.module.js:16511
  setProgram @ three.module.js:23822
  WebGLRenderer.renderBufferDirect @ three.module.js:22555
  renderObject @ three.module.js:23308
  renderObjects @ three.module.js:23278
  WebGLRenderer.render @ three.module.js:23026
  renderScene @ Renderable.js:383
  tock @ Renderable.js:268
  requestAnimationFrame (async)    
  tick @ Renderable.js:261
  triggerEvents @ backbone.js:370
  triggerApi @ backbone.js:356
  eventsApi @ backbone.js:155
  Events.trigger @ backbone.js:346
  onChildChanged @ Renderer.js:59
  triggerEvents @ backbone.js:369
  triggerApi @ backbone.js:356
  eventsApi @ backbone.js:155
  Events.trigger @ backbone.js:346
  onChildChanged @ Three.js:359
  triggerEvents @ backbone.js:370
  triggerApi @ backbone.js:356
  eventsApi @ backbone.js:155
  Events.trigger @ backbone.js:346
  set @ backbone-patch.js:118
  push.rynU.WidgetModel.set @ widget.js:295
  update_controlled @ OrbitControls.js:32
  (anonymous) @ OrbitControls.js:21
  dispatchEvent @ three.module.js:172
  onMouseUp @ OrbitControls.js:804

Error displaying widget: model not found

Hello,

I just upgraded to jupiter-cadquery 3.0.0rc3 from 3.0.0rc2 and I'm running into the error Error displaying widget: model not found whenever I attempt to call jcq.show(...) (after import jupyter_cadquery as jcq). When I upgraded to rc2, I ran into the same error, and IIRC I resolved it by upgrading various packages via conda and pip. However, I've tried upgrading various packages this time with no luck. Is there a reasonable way to debug this?

Perhaps related, I'm not sure why conda info shows python version : 3.8.12.final.0 when this env was set up with python 3.9.10 as can be seen in the conda list output.

Here is info about my conda and jupyter setup:

(py39) ➜  ~ conda info         

     active environment : py39
    active env location : /Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server/envs/py39
            shell level : 2
       user config file : /Users/xxxxxx/.condarc
 populated config files : /Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server/.condarc
          conda version : 4.11.0
    conda-build version : not installed
         python version : 3.8.12.final.0
       virtual packages : __osx=10.16=0
                          __unix=0=0
                          __archspec=1=x86_64
       base environment : /Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server  (writable)
      conda av data dir : /Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/osx-64
                          https://conda.anaconda.org/conda-forge/noarch
          package cache : /Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server/pkgs
                          /Users/xxxxxx/.conda/pkgs
       envs directories : /Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server/envs
                          /Users/xxxxxx/.conda/envs
               platform : osx-64
             user-agent : conda/4.11.0 requests/2.26.0 CPython/3.8.12 Darwin/21.3.0 OSX/10.16
                UID:GID : 501:20
             netrc file : None
           offline mode : False
(py39) ➜  ~ jupyter labextension list
JupyterLab v3.2.9
/Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server/envs/py39/share/jupyter/labextensions
        cad-viewer-widget v1.0.0 enabled OK (python, cad_viewer_widget)
        @voila-dashboards/jupyterlab-preview v2.1.1 enabled OK (python, voila)
        @jupyter-widgets/jupyterlab-manager v3.0.1 enabled OK (python, jupyterlab_widgets)
(py39) ➜  ~ conda list
# packages in environment at /Users/xxxxxx/Applications/JupyterLab.app/Contents/Resources/jlab_server/envs/py39:
#
# Name                    Version                   Build  Channel
anyio                     3.5.0            py39h6e9494a_0    conda-forge
appnope                   0.1.2            py39h6e9494a_2    conda-forge
argon2-cffi               21.3.0             pyhd8ed1ab_0    conda-forge
argon2-cffi-bindings      21.2.0           py39h89e85a6_1    conda-forge
asttokens                 2.0.5              pyhd8ed1ab_0    conda-forge
attrs                     21.4.0             pyhd8ed1ab_0    conda-forge
babel                     2.9.1              pyh44b312d_0    conda-forge
backcall                  0.2.0              pyh9f0ad1d_0    conda-forge
backports                 1.0                        py_2    conda-forge
backports.functools_lru_cache 1.6.4              pyhd8ed1ab_0    conda-forge
black                     22.1.0             pyhd8ed1ab_0    conda-forge
bleach                    4.1.0              pyhd8ed1ab_0    conda-forge
brotlipy                  0.7.0           py39h89e85a6_1003    conda-forge
bzip2                     1.0.8                h0d85af4_4    conda-forge
c-ares                    1.18.1               h0d85af4_0    conda-forge
ca-certificates           2021.10.8            h033912b_0    conda-forge
cad-viewer-widget         1.0.0                    pypi_0    pypi
cadquery                  master                    py3.9    cadquery
cadquery-massembly        0.9.0                    pypi_0    pypi
certifi                   2021.10.8        py39h6e9494a_1    conda-forge
cffi                      1.15.0           py39he338e87_0    conda-forge
charset-normalizer        2.0.12             pyhd8ed1ab_0    conda-forge
click                     8.0.3            py39h6e9494a_1    conda-forge
cq-warehouse              0.5.1                    pypi_0    pypi
cryptography              36.0.1           py39h209aa08_0    conda-forge
curl                      7.81.0               hf45b732_0    conda-forge
cycler                    0.11.0                   pypi_0    pypi
dataclasses               0.8                pyhc8e2a94_3    conda-forge
debugpy                   1.5.1            py39h9fcab8e_0    conda-forge
decorator                 5.1.1              pyhd8ed1ab_0    conda-forge
defusedxml                0.7.1              pyhd8ed1ab_0    conda-forge
double-conversion         3.1.7                he49afe7_0    conda-forge
eigen                     3.4.0                h940c156_0    conda-forge
entrypoints               0.4                pyhd8ed1ab_0    conda-forge
executing                 0.8.2              pyhd8ed1ab_0    conda-forge
expat                     2.4.4                he49afe7_0    conda-forge
ezdxf                     0.17.2           py39hf018cea_0    conda-forge
ffmpeg                    4.3.2                h4dad6da_1    conda-forge
flit-core                 3.6.0              pyhd8ed1ab_0    conda-forge
font-ttf-dejavu-sans-mono 2.37                 hab24e00_0    conda-forge
font-ttf-inconsolata      3.000                h77eed37_0    conda-forge
font-ttf-source-code-pro  2.038                h77eed37_0    conda-forge
font-ttf-ubuntu           0.83                 hab24e00_0    conda-forge
fontconfig                2.13.96              h10f422b_0    conda-forge
fonts-conda-ecosystem     1                             0    conda-forge
fonts-conda-forge         1                             0    conda-forge
fonttools                 4.29.1                   pypi_0    pypi
freeimage                 3.18.0               h7d96ac2_7    conda-forge
freetype                  2.10.4               h4cff582_1    conda-forge
gettext                   0.19.8.1          hd1a6beb_1008    conda-forge
gl2ps                     1.4.2                h4cff582_0    conda-forge
glew                      2.1.0                h046ec9c_2    conda-forge
gmp                       6.2.1                h2e338ed_0    conda-forge
gmpy2                     2.1.2            py39hab8a6df_0    conda-forge
gnutls                    3.6.13               h756fd2b_1    conda-forge
hdf4                      4.2.15               hefd3b78_3    conda-forge
hdf5                      1.10.6          nompi_hc5d9132_1114    conda-forge
icu                       69.1                 he49afe7_0    conda-forge
idna                      3.3                pyhd8ed1ab_0    conda-forge
ilmbase                   2.5.5                hfab91a5_0    conda-forge
importlib-metadata        4.11.0           py39h6e9494a_0    conda-forge
importlib_resources       5.4.0              pyhd8ed1ab_0    conda-forge
ipykernel                 6.9.0            py39h71a6800_0    conda-forge
ipython                   8.0.1            py39h6e9494a_0    conda-forge
ipython_genutils          0.2.0                      py_1    conda-forge
ipywidgets                7.6.5                    pypi_0    pypi
jbig                      2.1               h0d85af4_2003    conda-forge
jedi                      0.18.1           py39h6e9494a_0    conda-forge
jinja2                    3.0.3              pyhd8ed1ab_0    conda-forge
jpeg                      9e                   h0d85af4_0    conda-forge
json5                     0.9.5              pyh9f0ad1d_0    conda-forge
jsoncpp                   1.9.4                h940c156_3    conda-forge
jsonschema                4.4.0              pyhd8ed1ab_0    conda-forge
jupyter-cadquery          3.0.0rc3                 pypi_0    pypi
jupyter_client            7.1.2              pyhd8ed1ab_0    conda-forge
jupyter_core              4.9.1            py39h6e9494a_1    conda-forge
jupyter_server            1.13.5             pyhd8ed1ab_1    conda-forge
jupyterlab                3.2.9              pyhd8ed1ab_0    conda-forge
jupyterlab-widgets        1.0.2                    pypi_0    pypi
jupyterlab_pygments       0.1.2              pyh9f0ad1d_0    conda-forge
jupyterlab_server         2.10.3             pyhd8ed1ab_0    conda-forge
jxrlib                    1.1                  h35c211d_2    conda-forge
kiwisolver                1.3.2                    pypi_0    pypi
krb5                      1.19.2               hcfbf3a7_3    conda-forge
lame                      3.100             h35c211d_1001    conda-forge
lcms2                     2.12                 h577c468_0    conda-forge
lerc                      3.0                  he49afe7_0    conda-forge
libblas                   3.9.0           13_osx64_openblas    conda-forge
libcblas                  3.9.0           13_osx64_openblas    conda-forge
libclang                  13.0.1          default_he082bbe_0    conda-forge
libcurl                   7.81.0               hf45b732_0    conda-forge
libcxx                    12.0.1               habf9029_1    conda-forge
libdeflate                1.10                 h0d85af4_0    conda-forge
libedit                   3.1.20191231         h0678c8f_2    conda-forge
libev                     4.33                 haf1e3a3_1    conda-forge
libffi                    3.4.2                h0d85af4_5    conda-forge
libgfortran               5.0.0           9_3_0_h6c81a4c_23    conda-forge
libgfortran5              9.3.0               h6c81a4c_23    conda-forge
libiconv                  1.16                 haf1e3a3_0    conda-forge
liblapack                 3.9.0           13_osx64_openblas    conda-forge
libllvm13                 13.0.1               hd011deb_0    conda-forge
libnetcdf                 4.8.1           nompi_hb4d10b0_100    conda-forge
libnghttp2                1.46.0               h6f36284_0    conda-forge
libogg                    1.3.4                h35c211d_1    conda-forge
libopenblas               0.3.18          openmp_h3351f45_0    conda-forge
libpng                    1.6.37               h7cec526_2    conda-forge
libpq                     14.2                 hea3049e_0    conda-forge
libraw                    0.20.2               hefd3b78_1    conda-forge
libsodium                 1.0.18               hbcb3906_1    conda-forge
libssh2                   1.10.0               h52ee1ee_2    conda-forge
libtheora                 1.1.1             h0d85af4_1005    conda-forge
libtiff                   4.3.0                h17f2ce3_3    conda-forge
libvorbis                 1.3.7                h046ec9c_0    conda-forge
libwebp-base              1.2.2                h0d85af4_1    conda-forge
libxml2                   2.9.12               h7e28ab6_1    conda-forge
libzip                    1.8.0                h8b0c345_1    conda-forge
libzlib                   1.2.11            h9173be1_1013    conda-forge
llvm-openmp               13.0.1               hda6cdc1_0    conda-forge
loguru                    0.5.3            py39h6e9494a_3    conda-forge
lz4-c                     1.9.3                he49afe7_1    conda-forge
markupsafe                2.0.1            py39h89e85a6_1    conda-forge
matplotlib                3.5.1                    pypi_0    pypi
matplotlib-inline         0.1.3              pyhd8ed1ab_0    conda-forge
mistune                   0.8.4           py39h89e85a6_1005    conda-forge
mpc                       1.2.1                hbb51d92_0    conda-forge
mpfr                      4.1.0                h0f52abe_1    conda-forge
mpmath                    1.2.1              pyhd8ed1ab_0    conda-forge
multimethod               1.6                pyhd8ed1ab_0    conda-forge
mypy_extensions           0.4.3            py39h6e9494a_4    conda-forge
mysql-common              8.0.28               h694c41f_0    conda-forge
mysql-libs                8.0.28               h115446f_0    conda-forge
nbclassic                 0.3.5              pyhd8ed1ab_0    conda-forge
nbclient                  0.5.10             pyhd8ed1ab_1    conda-forge
nbconvert                 6.4.2            py39h6e9494a_0    conda-forge
nbformat                  5.1.3              pyhd8ed1ab_0    conda-forge
ncurses                   6.3                  he49afe7_0    conda-forge
nest-asyncio              1.5.4              pyhd8ed1ab_0    conda-forge
nettle                    3.6                  hedd7734_0    conda-forge
nlopt                     2.7.1            py39h783de76_0    conda-forge
notebook                  6.4.8              pyha770c72_0    conda-forge
nptyping                  1.4.4              pyhd8ed1ab_0    conda-forge
nspr                      4.32                 hcd9eead_1    conda-forge
nss                       3.74                 h31e2bf1_0    conda-forge
numpy                     1.22.2           py39h9d9ce41_0    conda-forge
occt                      7.5.3                h23a7684_0    conda-forge
ocp                       7.5.3.0                  py39_3    cadquery
openexr                   2.5.5                h7fa7ffa_0    conda-forge
openh264                  2.1.1                hfd3ada9_0    conda-forge
openjpeg                  2.4.0                h6e7aa92_1    conda-forge
openssl                   1.1.1l               h0d85af4_0    conda-forge
packaging                 21.3               pyhd8ed1ab_0    conda-forge
pandoc                    2.17.1.1             h694c41f_0    conda-forge
pandocfilters             1.5.0              pyhd8ed1ab_0    conda-forge
parso                     0.8.3              pyhd8ed1ab_0    conda-forge
pathspec                  0.9.0              pyhd8ed1ab_0    conda-forge
pexpect                   4.8.0              pyh9f0ad1d_2    conda-forge
pickleshare               0.7.5                   py_1003    conda-forge
pillow                    9.0.1                    pypi_0    pypi
pip                       22.0.3             pyhd8ed1ab_0    conda-forge
platformdirs              2.5.0              pyhd8ed1ab_0    conda-forge
proj                      7.2.0                h78d1473_2    conda-forge
prometheus_client         0.13.1             pyhd8ed1ab_0    conda-forge
prompt-toolkit            3.0.27             pyha770c72_0    conda-forge
ptyprocess                0.7.0              pyhd3deb0d_0    conda-forge
pugixml                   1.11.4               he49afe7_0    conda-forge
pure_eval                 0.2.2              pyhd8ed1ab_0    conda-forge
pycparser                 2.21               pyhd8ed1ab_0    conda-forge
pydantic                  1.9.0                    pypi_0    pypi
pygments                  2.11.2             pyhd8ed1ab_0    conda-forge
pyopenssl                 22.0.0             pyhd8ed1ab_0    conda-forge
pyparsing                 3.0.7              pyhd8ed1ab_0    conda-forge
pyquaternion              0.9.9                    pypi_0    pypi
pyrsistent                0.18.1           py39h89e85a6_0    conda-forge
pysocks                   1.7.1            py39h6e9494a_4    conda-forge
python                    3.9.10          h1dd9edd_2_cpython    conda-forge
python-dateutil           2.8.2              pyhd8ed1ab_0    conda-forge
python_abi                3.9                      2_cp39    conda-forge
pytz                      2021.3             pyhd8ed1ab_0    conda-forge
pyzmq                     22.3.0           py39h7fec2f1_1    conda-forge
qt                        5.12.9               h2a607e2_5    conda-forge
rapidjson                 1.1.0             hb1e8313_1002    conda-forge
readline                  8.1                  h05e3726_0    conda-forge
requests                  2.27.1             pyhd8ed1ab_0    conda-forge
send2trash                1.8.0              pyhd8ed1ab_0    conda-forge
setuptools                60.9.0           py39h6e9494a_0    conda-forge
six                       1.16.0             pyh6c4a22f_0    conda-forge
sniffio                   1.2.0            py39h6e9494a_2    conda-forge
sqlite                    3.37.0               h23a322b_0    conda-forge
stack_data                0.2.0              pyhd8ed1ab_0    conda-forge
sympy                     1.9              py39h6e9494a_1    conda-forge
tbb                       2020.2               h940c156_4    conda-forge
tbb-devel                 2020.2               h940c156_4    conda-forge
terminado                 0.13.1           py39h6e9494a_0    conda-forge
testpath                  0.5.0              pyhd8ed1ab_0    conda-forge
tk                        8.6.11               h5dbffcc_1    conda-forge
tomli                     2.0.1              pyhd8ed1ab_0    conda-forge
tornado                   6.1              py39h89e85a6_2    conda-forge
traitlets                 5.1.1              pyhd8ed1ab_0    conda-forge
typed-ast                 1.5.2            py39h89e85a6_0    conda-forge
typing_extensions         4.1.1              pyha770c72_0    conda-forge
typish                    1.9.3              pyhd8ed1ab_0    conda-forge
tzdata                    2021e                he74cb21_0    conda-forge
urllib3                   1.26.8             pyhd8ed1ab_1    conda-forge
utfcpp                    3.2.1                h694c41f_0    conda-forge
voila                     0.3.1              pyhd8ed1ab_0    conda-forge
vtk                       9.0.1           qt_py39h93184f3_210    conda-forge
wcwidth                   0.2.5              pyh9f0ad1d_2    conda-forge
webcolors                 1.11.1                   pypi_0    pypi
webencodings              0.5.1                      py_1    conda-forge
websocket-client          1.2.3              pyhd8ed1ab_0    conda-forge
websockets                10.1             py39h89e85a6_0    conda-forge
wheel                     0.37.1             pyhd8ed1ab_0    conda-forge
widgetsnbextension        3.5.2                    pypi_0    pypi
x264                      1!161.3030           h0d85af4_1    conda-forge
xz                        5.2.5                haf1e3a3_1    conda-forge
zeromq                    4.3.4                he49afe7_1    conda-forge
zipp                      3.7.0              pyhd8ed1ab_1    conda-forge
zlib                      1.2.11            h9173be1_1013    conda-forge
zstd                      1.5.2                h582d3a0_0    conda-forge

jcv - naming items in the tree

I'm sure that it's obvious to some but how do you name items in the tree view, currently mine are named Group, Part_0, Parent_1, Edges_1, Part_2 etc.

Suggestion: make an example with Binder

Binder allows you to run Jupyter Notebooks (or Jupyter Lab) on the cloud.

mybinder.org is a Binder free service, which allows you to run notebooks from any public repository very easily.

It would be great to have an example of jupyter-cadquery that works on mybinder.

It seems you can use Dockerfiles with Binder.

Here is an example of a Binder Dockerfile which is based on a Jupyter DockerStacks image. I guess a jupyter-cadquery Docker file could be based on the base-notebok.

I think it would be a great way to let people try the extension (and CadQuery, too) without the need to setup any environment. Then, once they love it, they can do so locally. 😄

'exportSTL' import error

ImportError: cannot import name 'exportSTL' from 'jupyter_cadquery' (C:\...\Anaconda3\envs\cadquery\lib\site-packages\jupyter_cadquery\__init__.py)

Can someone help me to solve the problem?

MyBinder Broken

I'm on Firefox 81 on Ubuntu 18.04 64-bit.

Is the binder still up to date and maintained? I was trying to help a CadQuery user on Discord get started with jupyter-cadquery, but we can't get the binder to work. The user wants the widgets to dynamically adjust parameters.

https://mybinder.org/v2/gh/bernhard-42/jupyter-cadquery/v1.0.0?urlpath=lab&filepath=examples%2Fcadquery.ipynb

If I navigate to the examples directory and open cadquery-examples.ipynb, then execute the first two code cells, everything seems fine. But then if I try to execute cells further down, the 3D view doesn't update. Trying different combinations of things causes other problems. If I call disable_replay() in the first cell then I start getting errors like this:

---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-9-2df1979a6696> in <module>
     10 result = cq.Workplane("XY").box(length, height, thickness)
     11 
---> 12 replay(result)

/srv/conda/envs/notebook/lib/python3.7/site-packages/jupyter_cadquery/cadquery/replay.py in replay(cad_obj, index, debug, cad_width, height)
    391         description='',
    392         disabled=False,
--> 393         layout=Layout(width="600px"))
    394     r.select_box.add_class("monospace")
    395     r.select_box.observe(r.select_handler)

/srv/conda/envs/notebook/lib/python3.7/site-packages/ipywidgets/widgets/widget_selection.py in __init__(self, *args, **kwargs)
    324         self._options_values = tuple(i[1] for i in options)
    325 
--> 326         super(_MultipleSelection, self).__init__(*args, **kwargs)
    327         self._initializing_traits_ = False
    328 

/srv/conda/envs/notebook/lib/python3.7/site-packages/ipywidgets/widgets/widget.py in __init__(self, **kwargs)
    410         """Public constructor"""
    411         self._model_id = kwargs.pop('model_id', None)
--> 412         super(Widget, self).__init__(**kwargs)
    413 
    414         Widget._call_widget_constructed(self)

/srv/conda/envs/notebook/lib/python3.7/site-packages/traitlets/traitlets.py in __init__(self, *args, **kwargs)
    998                 else:
    999                     # passthrough args that don't set traits to super
-> 1000                     super_kwargs[key] = value
   1001         try:
   1002             super(HasTraits, self).__init__(*super_args, **super_kwargs)

/srv/conda/envs/notebook/lib/python3.7/contextlib.py in __exit__(self, type, value, traceback)
    117         if type is None:
    118             try:
--> 119                 next(self.gen)
    120             except StopIteration:
    121                 return False

/srv/conda/envs/notebook/lib/python3.7/site-packages/traitlets/traitlets.py in hold_trait_notifications(self)
   1120                                 self._trait_values.pop(name)
   1121                 cache = {}
-> 1122                 raise e
   1123             finally:
   1124                 self._cross_validation_lock = False

/srv/conda/envs/notebook/lib/python3.7/site-packages/traitlets/traitlets.py in hold_trait_notifications(self)
   1106                 for name in list(cache.keys()):
   1107                     trait = getattr(self.__class__, name)
-> 1108                     value = trait._cross_validate(self, getattr(self, name))
   1109                     self.set_trait(name, value)
   1110             except TraitError as e:

/srv/conda/envs/notebook/lib/python3.7/site-packages/traitlets/traitlets.py in _cross_validate(self, obj, value)
    597         if self.name in obj._trait_validators:
    598             proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
--> 599             value = obj._trait_validators[self.name](obj, proposal)
    600         elif hasattr(obj, '_%s_validate' % self.name):
    601             meth_name = '_%s_validate' % self.name

/srv/conda/envs/notebook/lib/python3.7/site-packages/traitlets/traitlets.py in __call__(self, *args, **kwargs)
    905         """Pass `*args` and `**kwargs` to the handler's function if it exists."""
    906         if hasattr(self, 'func'):
--> 907             return self.func(*args, **kwargs)
    908         else:
    909             return self._init_call(*args, **kwargs)

/srv/conda/envs/notebook/lib/python3.7/site-packages/ipywidgets/widgets/widget_selection.py in _validate_index(self, proposal)
    350             return proposal.value
    351         else:
--> 352             raise TraitError('Invalid selection: index out of bounds')
    353 
    354     @observe('index')

TraitError: Invalid selection: index out of bounds

Incremental show object not working?

Hi,

If I try to import the functions show and show object as shown in the README:

from jupyter_cadquery.viewer.client import show, show_object

The code prints the following lines in console without displaying anything to the sidecar:

_
. sending ... Reconnecting to server…
Resending ...
Reconnecting to server…
Resending .
_

The show works correctly if imported as follows:
from jupyter_cadquery.viewer.client import show

However, this module has no show_object() function implemented. And this line fails:
from jupyter_cadquery.viewer.client import show, show_object

I really want to use the incremental version of show() which is the mentioned show_object(). What should I do?

massive multi body assembly

I cannot view an entire assembly of 900 elements (see attached image). 400 element assembly is fully viewable. How many elements show up seems indeterminate, as it is different every time I run the script
chainmail-viewer-bug
. Interpreter does not throw error. Here is the code that generates chainmail.

`import cadquery as cq
from jupyter_cadquery.cadquery import (Assembly, Part, Edges, Faces, Vertices, show)
from jupyter_cadquery import set_sidecar

set_sidecar("CadQuery")

ring_od = 5
ring_id = 4
ring_t = 1
clearance = 1
ring_offset = ring_od+clearance
n_x = 30
n_y = 30
x_hat = (1, 0, 0)
y_hat = (0, 1, 0)
z_hat = (0, 0, 1)

ring = cq.Workplane('XY').circle(ring_od).circle(ring_id).extrude(ring_t)
ringx = ring.rotate((0, 0, 0), (1, 0, 0), 90).translate((ring_offset, 0, 0))
ringy = ring.rotate((0, 0, 0), (0, 1, 0), 90).translate((0, ring_offset, 0))
ringy2 = ring.rotate((0, 0, 0), (0, 1, 0), 90).translate((0, 2*ring_offset, 0))
unit_cell = ring.union(ringy).union(ringx)
cells_x = [unit_cell.translate((2 * x * ring_offset, 0, 0)) for x in range(n_x)]
cells_y = [[i.translate((0, 2 * y * ring_offset, 0)) for i in cells_x] for y in range(n_y)]
flattened_list = [y for x in cells_y for y in x]

def assemble(parts=[]):
return Assembly([Part(part, "red box", "#d7191c", show_edges=False) for part in parts],"test")

ring_assembly = assemble(flattened_list)

show(ring_assembly, axes=True)
`

Displaying compounds

Just experimenting with this really nice package and stumbled along this error when trying to show a compound

Wondering if here could be a special case for handling cadquery compounds in this section of the code as I don't think they have a .val() attribute

trying the show() function with pip install jupyter-cadquery==2.0.0-rc1 and also tried adding pip install git+https://github.com/bernhard-42/cadquery-massembly

~/anaconda3/lib/python3.8/site-packages/jupyter_cadquery/cadquery/cad_objects.py in show(render_mates, mate_scale, *cad_objs, **kwargs)
    359     mate_scale = mate_scale or get_default("mate_scale")
    360 
--> 361     assembly = to_assembly(*cad_objs, render_mates=render_mates, mate_scale=mate_scale)
    362 
    363     if assembly is None:

~/anaconda3/lib/python3.8/site-packages/jupyter_cadquery/cadquery/cad_objects.py in to_assembly(render_mates, mate_scale, *cad_objs)
    310             assembly.add_list(_from_vector(cad_obj, obj_id))
    311 
--> 312         elif isinstance(cad_obj.val(), Vector):
    313             assembly.add_list(_from_vectorlist(cad_obj, obj_id))
    314 

AttributeError: 'Compound' object has no attribute 'val'

Preview: Juypter CadQuery now has a Viewer component for debugging in IDEs

This is a beta version (beta1) of the CadQuery viewer for IDEs I talked about earlier.

If you want to give it a try, happy to get feedback.

Installation

It can be installed in an existing conda environment

pip install git+https://github.com/bernhard-42/jupyter-cadquery.git@viewer2

However, since it is quite young, I'd recommend to try it in a fresh conda environment with CadQuery 2.1 being installed:

conda create -n jcv python=3.8
conda activate jcv

conda install pywin32  # Windows users only
conda install -c conda-forge -c cadquery cadquery=2.1

pip install git+https://github.com/bernhard-42/jupyter-cadquery.git@viewer2

pip install git+https://github.com/bernhard-42/cadquery-massembly  # for the animated examples

Test from the terminal

Starting (on Mac, Linux and Windows)

jcv -w 800 -h 600

image

As a simple test add the following code to test.py:

import cadquery as cq
from jupyter_cadquery.viewer.client import show

box = cq.Workplane().box(1, 1, 1).faces(">Z").hole(0.6).edges().fillet(0.05)
cyl = cq.Workplane().circle(0.1).extrude(1)

show(box, cyl, axes=True, transparent=True)

viewer

Debugging session with dark theme

jcv -d -w 650 -h 400

debugging

JupyterLab 3 support?

Hello, and thanks for this marvelous tool.

I'd very much like to see this up and running in JupyterLab 3... it constitutes something of a hard break, as the primary distribution would be via only pip install (though nice devs also continue to publish to npm, so that others can extend their stuff). The benefits for users are very significant: no more runtime nodejs, mysterious downloads of 100s of MiB from npmjs.org, a single source of version truth per package, etc. The development workflow is a little weird, more like the nbextension, as it relies on data_files to put stuff in a place on disk, but being able to build once on linux, and test built wheels/sdist everywhere else is priceless.

Happy to help in any way I can!

Blocked By

cqparts example fails

With the docker image:

import cqparts

Returns:

ModuleNotFoundError: No module named 'cqparts'

cqparts is not listed in environment.yml.

Adding this cell to the top of cqparts.ipynb seems to work:

USER_SITE = __import__("site").USER_SITE
!rm -rf $USER_SITE/cqparts*
!test -d _cqparts_src || git clone https://github.com/CapableRobot/cqparts ./_cqparts_src
!test -d $USER_SITE || mkdir -p $USER_SITE
!ln -s _cqparts_src/src/* $USER_SITE/
# !pip install -r _cqparts_src/src/cqparts/requirements.txt
!pip install tinydb  # everything else is already installed by conda
import cqparts 

Docker image for 3.0.0rc3 crashes on Mac M1

docker run -it --rm  -p 8888:8888 bwalter42/jupyter_cadquery:3.0.0rc3

WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
Starting in JupyterLab mode: http://localhost:8888/lab
[W 2022-02-17 09:47:22.274 LabApp] 'token' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2022-02-17 09:47:22.276 LabApp] 'allow_origin' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[I 2022-02-17 09:47:22.314 ServerApp] jupyterlab | extension was successfully linked.
[I 2022-02-17 09:47:22.368 ServerApp] Writing Jupyter server cookie secret to /home/cq/.local/share/jupyter/runtime/jupyter_cookie_secret
[I 2022-02-17 09:47:24.890 ServerApp] nbclassic | extension was successfully linked.
[I 2022-02-17 09:47:24.891 ServerApp] voila.server_extension | extension was successfully linked.
[W 2022-02-17 09:47:25.118 ServerApp] All authentication is disabled.  Anyone who can connect to this server will be able to run code.
[I 2022-02-17 09:47:25.143 ServerApp] nbclassic | extension was successfully loaded.
[I 2022-02-17 09:47:25.150 LabApp] JupyterLab extension loaded from /opt/conda/envs/cq/lib/python3.8/site-packages/jupyterlab
[I 2022-02-17 09:47:25.150 LabApp] JupyterLab application directory is /opt/conda/envs/cq/share/jupyter/lab
[I 2022-02-17 09:47:25.169 ServerApp] jupyterlab | extension was successfully loaded.
[I 2022-02-17 09:47:25.180 ServerApp] voila.server_extension | extension was successfully loaded.
[I 2022-02-17 09:47:25.182 ServerApp] Serving notebooks from local directory: /home/cq
[I 2022-02-17 09:47:25.182 ServerApp] Jupyter Server 1.13.5 is running at:
[I 2022-02-17 09:47:25.183 ServerApp] http://51d9fbc2f560:8888/lab
[I 2022-02-17 09:47:25.183 ServerApp]  or http://127.0.0.1:8888/lab
[I 2022-02-17 09:47:25.184 ServerApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[W 2022-02-17 09:47:31.342 LabApp] Could not determine jupyterlab build status without nodejs
[I 2022-02-17 09:47:39.776 ServerApp] Writing notebook-signing key to /home/cq/.local/share/jupyter/notebook_secret
[W 2022-02-17 09:47:39.784 ServerApp] Notebook 1-cadquery.ipynb is not trusted
Operation not permitted (src/thread.cpp:309)
Operation not permitted (src/thread.cpp:309)
qemu: uncaught target signal 6 (Aborted) - core dumped
/tmp/run.sh: line 39:    27 Aborted                 jupyter lab --ip=0.0.0.0 --no-browser --NotebookApp.token='' --NotebookApp.allow_origin='*'

Jupyter launches. When I click on one of the notebook it says "Error starting kernel, load failed:.

Missing import for sketches in 3.0rc1

Any attempt to include cq will result in the following log file:
log.txt

I followed the instructions reported on the README for branch 3 on a fresh install of ubuntu 21.
I was not able to find the docker image, so I cannot test if that environment is working properly.

Tesselate small objects

For small objects, Tesselation might run into issues (see e.g. #14)
Todo: Change quality according to the bounding box of the object or change other parameters of OCC

Docker container built as per examples fails to run example notebook

I checked out the container and build it (Ensuring all files are copied from current workdir etc)
It can build and deploy but when running the cadquery_example.ipynb

Here's the first snippet:

import cadquery as cq
from jupyter_cadquery.cadquery import (Assembly, Part, Edges, Faces, Vertices, show, 
                                       replay, enable_replay, disable_replay, reset_replay)
from jupyter_cadquery import set_sidecar

set_sidecar("CadQuery")
enable_replay()
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-dce0531510f8> in <module>
----> 1 import cadquery as cq
      2 from jupyter_cadquery.cadquery import (Assembly, Part, Edges, Faces, Vertices, show, 
      3                                        replay, enable_replay, disable_replay, reset_replay)
      4 from jupyter_cadquery import set_sidecar
      5 

/opt/conda/envs/cq/lib/python3.7/site-packages/cadquery/__init__.py in <module>
      1 # these items point to the OCC implementation
----> 2 from .occ_impl.geom import Plane, BoundBox, Vector, Matrix, Location
      3 from .occ_impl.shapes import (
      4     Shape,
      5     Vertex,

/opt/conda/envs/cq/lib/python3.7/site-packages/cadquery/occ_impl/geom.py in <module>
      3 from typing import overload, Sequence, Union, Tuple, Type, Optional
      4 
----> 5 from OCP.gp import gp_Vec, gp_Ax1, gp_Ax3, gp_Pnt, gp_Dir, gp_Trsf, gp_GTrsf, gp, gp_XYZ
      6 from OCP.Bnd import Bnd_Box
      7 from OCP.BRepBndLib import BRepBndLib

ModuleNotFoundError: No module named 'OCP'

Just wondering if there's something that's changed?

I've actually had alot of issues trying to install this myself, and thought I'd try the Docker container for a bullet proof reference, but out of the box it's got at least this issue.

Did I miss something, or is there a caveat here?
As there aren't any prebuilt images it's possible some package or platform has changed? But they all appear to be locked in the environment.yml

reset_camera = False, still does reset zoom

Hello,

I'm using the voilà viewer and while specifying reset_camera = False the zoom is reset to the defaults (the camera position works as intended though).

Is this a bug ? If yes, is there a workaround ?
Thanks !

Error when trying to export

I have the following cadquery example code:

import cadquery as cq
from jupyter_cadquery.cadquery import Assembly, Part, Edges, Faces, Vertices, show
from jupyter_cadquery import set_sidecar, set_defaults, reset_defaults

set_sidecar("CadQuery")  # force usage of one cad view on the right
set_defaults(axes=False, grid=True, axes0=True, ortho=True, transparent=True) # Set default values


height = 60.0
width = 80.0
thickness = 10.0
diameter = 22.0
padding = 12.0

 # make the base
result = cq.Workplane("XY").box(height, width, thickness)\
 .faces(">Z").workplane().hole(diameter)\
 .faces(">Z").workplane() \
 .rect(height - padding, width - padding, forConstruction=True)\
 .vertices().cboreHole(2.4, 4.4, 2.1)\
 .edges("|Z").fillet(2.0)

show(result)

cq.exporters.export(result,'result.stl')

It all works great for visualizing, but when I try to export (last line) I get the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-09152fc940df> in <module>
     23 show(result)
     24 
---> 25 cq.exporters.export(result,'result.stl')

AttributeError: module 'cadquery.occ_impl.exporters' has no attribute 'export'

As I'm pretty new with all this, I'm sure I'm doing something wrong. But what am I missing?

Cad view controls

Is there a way to modify the controls of the cadviewport ?
By this I mean :

  • Changing the keybinds/mousebinds of translation, rotation and zoom in the view
  • Changing the sensitivity of translation, rotations and zoom

Almost every CAD software use a different set of key/mouse bindings to navigate the 3D view so it's often frustrating when you don't have a consistent set across all of them

Add ability to copy the replay selection as text

I have a complex library (1000+ lines, several modules) that generates CadQuery models from specifications. This lets me write a small class that renders a large model, but sometimes this results in hard-to-debug code. The jupyter-cadquery replay() function is extremely useful for debugging, but it could be more useful if you could click a button and copy the actual calls and turn something like this:

strange-failure-replay

Into the actual code:

import cadquery as cq

part = (cq.Workplane().rect(142.875,213.360)
        .workplane(offset=-30.1625).rect(142.875,213.260)
        .loft()
        .cut(
            cq.Workplane().union(
                cq.Workplane().rect(128.99127,195.66627)
                .workplane(offset=-9.535).rect(127.0,193.675)
                .loft()
                .edges('<Z').fillet(0.4)
                .translate((0,0,0.01)).translate((0,0,0))
            )
        )
        .faces('>Z').moveTo(-62.8625,-96.2).circle(0.875).cutThruAll()
        .faces('>Z').moveTo(-62.8625, 96.2).circle(0.875).cutThruAll()
        .faces('>Z').moveTo( 62.8625,-96.2).circle(0.875).cutThruAll()
        .faces('>Z').moveTo( 62.8625, 96.2).circle(0.875).cutThruAll()        
   )

(It doesn't have to be prettied up -- just extracting the functions and arguments into code would be wonderful.)

Error with: pip3 install .

This is entire error code 👍
ERROR: Command errored out with exit status 1: command: 'c:\users\wolvi\.conda\envs\cd-jl-1.0\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\wolvi\\AppData\\Local\\Temp\\pip-req-build-2p204ejw\\setup.py'"'"'; __file__='"'"'C:\\Users\\wolvi\\AppData\\Local\\Temp\\pip-req-build-2p204ejw\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\ Complete output (113 lines): setup.py entered $PATH=c:\users\wolvi\.conda\envs\cd-jl-1.0\Library\bin;C:\Users\wolvi\.conda\envs\cd-jl-1.0;C:\Users\wolvi\.conda\envs\cd-jl-1.0\Library\mingw-w64\bin;C:\Users\wolvi\.conda\envs\cd-jl-1.0\Library\usr\bin;C:\Users\wolvi\.conda\envs\cd-jl-1.0\Library\bin;C:\Users\wolvi\.conda\envs\cd-jl-1.0\Scripts;C:\Users\wolvi\.conda\envs\cd-jl-1.0\bin;C:\ProgramData\Anaconda3\condabin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin;C:\ProgramData\Anaconda3\Scripts;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\MATLAB\R2018b\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\runtime\win32;C:\Program Files\SlikSvn\bin;C:\Program Files\Git\cmd;C:\Program Files\CMake\bin;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.3.0;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\Blender Foundation\Blender;C:\Program Files\Blender Foundation\Blender\2.80;C:\Program Files\Blender Foundation\Blender\2.80\python\lib;C:\Users\wolvi\AppData\Local\Programs\Python\Python37\Scripts;C:\Users\wolvi\AppData\Local\Programs\Python\Python37;C:\Tcl\bin;C:\Users\wolvi\AppData\Local\Microsoft\WindowsApps;.;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin;C:\ProgramData\Anaconda3\Scripts;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\MATLAB\R2018b\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\runtime\win32;C:\Program Files\SlikSvn\bin;C:\Program Files\Git\cmd;C:\Program Files\CMake\bin;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.3.0;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\Blender Foundation\Blender;C:\Program Files\Blender Foundation\Blender\2.80;C:\Program Files\Blender Foundation\Blender\2.80\python\lib;. running egg_info running jsdeps 6.7.0 6.7.0 Installing build dependencies with npm. This may take a while... npm WARN prepublish-on-install As of npm@5, prepublishscripts are deprecated. npm WARN prepublish-on-install Usepreparefor build steps andprepublishOnlyfor upload-only. npm WARN prepublish-on-install See the deprecation note innpm help scripts` for more information.

> [email protected] prepublish C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\js
> webpack

Hash: ecd4dbb11fa791d6081122e280df66799edb341cb37887592548f5420ba7
Version: webpack 4.39.1
Child
    Hash: ecd4dbb11fa791d60811
    Time: 1082ms
    Built at: 2019-08-09 09:43:02
           Asset      Size  Chunks             Chunk Names
    extension.js  1.19 KiB       0  [emitted]  main
    Entrypoint main = extension.js
    [0] ./lib/extension.js 1.42 KiB {0} [built]

    WARNING in configuration
    The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
    You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
Child
    Hash: 22e280df66799edb341c
    Time: 3798ms
    Built at: 2019-08-09 09:43:04
     2 assets
    Entrypoint main = index.js index.js.map
     [1] ./lib/index.js 895 bytes {0} [built]
     [2] ./lib/image_button.js 1.93 KiB {0} [built]
     [3] (webpack)/buildin/global.js 472 bytes {0} [built]
     [4] (webpack)/buildin/module.js 497 bytes {0} [built]
     [5] ./lib/tree_view.js 8.51 KiB {0} [built]
     [6] ./style/index.css 1.06 KiB {0} [built]
     [7] ./node_modules/css-loader/dist/cjs.js!./style/index.css 3.13 KiB {0} [built]
    [11] ./package.json 983 bytes {0} [built]
        + 4 hidden modules

    WARNING in configuration
    The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
    You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

    ERROR in ./lib/tree_view.js
    Module not found: Error: Can't resolve '@jupyter-widgets/controls' in 'C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\js\lib'
     @ ./lib/tree_view.js 15:0-76 50:16-30 51:19-33 67:15-30 69:4-19
     @ ./lib/index.js

    ERROR in ./lib/image_button.js
    Module not found: Error: Can't resolve '@jupyter-widgets/controls' in 'C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\js\lib'
     @ ./lib/image_button.js 16:0-19:35 27:23-34 28:19-30 41:22-32
     @ ./lib/index.js
Child
    Hash: b37887592548f5420ba7
    Time: 3502ms
    Built at: 2019-08-09 09:43:04
     2 assets
    Entrypoint main = index.js index.js.map
    [1] ./lib/embed.js 1.04 KiB {0} [built]
    [2] ./lib/image_button.js 1.93 KiB {0} [built]
    [3] (webpack)/buildin/global.js 472 bytes {0} [built]
    [4] (webpack)/buildin/module.js 497 bytes {0} [built]
    [5] ./package.json 983 bytes {0} [built]
        + 1 hidden module

    WARNING in configuration
    The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
    You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

    ERROR in ./lib/image_button.js
    Module not found: Error: Can't resolve '@jupyter-widgets/controls' in 'C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\js\lib'
     @ ./lib/image_button.js 16:0-19:35 27:23-34 28:19-30 41:22-32
     @ ./lib/embed.js
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] prepublish: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] prepublish script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\wolvi\AppData\Roaming\npm-cache\_logs\2019-08-09T07_43_04_923Z-debug.log
rebuilding js and css failed
missing files: ['C:\\Users\\wolvi\\AppData\\Local\\Temp\\pip-req-build-2p204ejw\\jupyter_cadquery\\static\\index.js']
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\setup.py", line 177, in <module>
    setup(**setup_args)
  File "c:\users\wolvi\.conda\envs\cd-jl-1.0\lib\site-packages\setuptools\__init__.py", line 145, in setup
    return distutils.core.setup(**attrs)
  File "c:\users\wolvi\.conda\envs\cd-jl-1.0\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "c:\users\wolvi\.conda\envs\cd-jl-1.0\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "c:\users\wolvi\.conda\envs\cd-jl-1.0\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\setup.py", line 46, in run
    raise e
  File "C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\setup.py", line 39, in run
    self.distribution.run_command('jsdeps')
  File "c:\users\wolvi\.conda\envs\cd-jl-1.0\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\wolvi\AppData\Local\Temp\pip-req-build-2p204ejw\setup.py", line 111, in run
    check_call([npmName, 'install'], cwd=node_root, stdout=sys.stdout, stderr=sys.stderr)
  File "c:\users\wolvi\.conda\envs\cd-jl-1.0\lib\subprocess.py", line 311, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['npm.cmd', 'install']' returned non-zero exit status 2.
----------------------------------------

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.`

My version of jupyterlab is 1.0 on windows 1.0 and python 3.7

Inline result cells

The sidecar is very useful for tinkering. But once things are working well, I would prefer to have inline result cells, so I could tell a full story in the notebook, with renderings of specific details as I go. I think that #5 does a lot of the hard parts of this...

Error when starting from conda

I've installed this via miniconda if that's relevant, but I see the following when starting it:

(jcq22) $ jcv -d
[JCV] Creating a Jupyter kernel specification called 'jcv' for this conda environment
[Errno 13] Permission denied: '/usr/local/share/jupyter'
[JCV] Copying the voila notebook to /home/user/etc/.jcv
[JCV] Signing the volia notebook
Notebook already signed: /home/user/etc/.jcv/viewer.ipynb
[JCV] Starting Jupyter CadQuery Viewer
[Voila] Using /tmp to store connection files
[Voila] Storing connection files in /tmp/voila_5q59dnvk.
[Voila] Serving static files from /home/user/etc/.conda/envs/jcq22/lib/python3.8/site-packages/voila/static.
[Voila] Voilà is running at:
http://tight-seat:8866/
[Voila] WARNING | Could not find a kernel named 'jcv', will use  'pypy3'
[Voila] Kernel started: 319c1075-9d09-42b7-9979-9c9e1cbc9367
...
ModuleNotFoundError: No module named 'jupyter_cadquery'

It seems like it's trying to install the thing system-wide, but doing that is bad practice on Linux (and probably other OSes) and requires privilege escalation.

Running python -m ipykernel install --name jcv --display-name jcv --user, which is the same as from the script, but with --user installs the kernel locally for the current user. This ends up working fine, since the launch script never checks for errors when it tries to create it again.

I'd suggest:

Viewer mode from Docker

I'm attempting to run the bwalter42/jupyter_cadquery:2.2.0 docker image, and connect to it in viewer mode from VS Code. I've been attempting to follow along with what's described in #40 and #42, but I'm having trouble determining what is still necessary now that it seems the docker image has been updated to a version which has the viewer mode built in.

When I exec into the container and run python I get the following error.

~$ pythonPython 3.8.5 (default, Sep  4 2020, 07:30:14) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from jupyter_cadquery.viewer.client import show
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'jupyter_cadquery'

Please let me know if there are instructions I missed for starting in viewer mode, and then connecting from my IDE.
Thank you!

Integration with Sphinx

I am considering integrating this with a Sphinx extension I made which allowed you to display 3D renders out of CadQuery code in your documentation:

In order to do so, I need to embed the HTML code in the documentation. Is there any function that outputs the required HTML in this project?

I will have a look myself, but in case you read it before I do... It will be faster. 😜

Installation on ipad using carnets

Hi,
I'm relatively new to pyhton and cadquery, so hopefully this is the right place to ask....
cadquery is the tool of joice to implement program based designs, the ipad my favorite tool for new design ideas.

With the Carnets app (https://github.com/holzschu/Carnets) I can get a Jupyter Notebook on my Ipad pro. I could install Version 3.0.0rc3 of jupyter-cadquery.
But: Carpets does not support conda (only pip) and I don't know how get Jupyterlab up and running in this (or an other?) environment on my ipad. Any idea how to?

BUG,BLD: JupyterLab 1.0

With JupyterLab 1.0 (released about week ago), I'm getting this error when I run the example in the README ( https://github.com/bernhard-42/jupyter-cadquery#b-example-cadquery-using-sidecar )

 Error displaying widget: model not found

It doesn't say which package or jupyterlab extension is throwing this exception in the GUI or in the CLI log.
It looks like some changes were necessary to support JupyterLab 1.0:

With this Makefile build script (on Fedora, though that shouldn't make any difference) that specifies jupyterlab<1.0 I still get Error displaying widget in the sidecar.

_SRC=../
install-gui:
	conda install -y numpy 'jupyterlab<1.0' python=3.6 nodejs
	conda install -y -c conda-forge -c cadquery pyparsing pythonocc-core
	pip install --upgrade git+https://github.com/CadQuery/cadquery
	pip install ipywidgets pythreejs sidecar dataclasses
	jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter-threejs @jupyter-widgets/jupyterlab-sidecar
	#pip install -e git+https://github.com/bernhard-42/jupyter-cadquery.git#egg=jupyter_cadquery
	#cd '${_SRC}/jupyter-cadquery' && \
	#	jupyter-labextension install js
	cd '${_SRC}' && test -d jupyter-cadquery || git clone https://github.com/bernhard-42/jupyter-cadquery.git
	cd '${_SRC}/jupyter-cadquery' && pip install .
	cd '${_SRC}/jupyter-cadquery' && jupyter-labextension install js
$ jupyter-labextension list
JupyterLab v0.35.6
Known labextensions:
   app dir: /venv/share/jupyter/lab
        @jupyter-widgets/jupyterlab-manager v0.38.1  enabled  OK
        @jupyter-widgets/jupyterlab-sidecar v0.3.0  enabled  OK
        jupyter-threejs v2.1.1  enabled  OK
        jupyter_cadquery v0.9.1  enabled  OK*
        jupyterlab-datawidgets v6.1.0  enabled  OK

   local extensions:
        jupyter_cadquery: /venv/src/jupyter-cadquery/js

Workarounds

  • Use the Docker container instead
    • currently installs jupyterlab pkgs/main/linux-64::jupyterlab-0.35.5-py36hf63ae98_
    • #1 (comment)

Module Not Found Error

I tried importing CadQuery in my jupyterlab session and here is the error I get,


ModuleNotFoundError Traceback (most recent call last)
in
----> 1 import cadquery as cq

~/opt/anaconda3/envs/research3/lib/python3.7/site-packages/cadquery/init.py in
1 # these items point to the OCC implementation
----> 2 from .occ_impl.geom import Plane, BoundBox, Vector, Matrix, Location
3 from .occ_impl.shapes import (
4 Shape,
5 Vertex,

~/opt/anaconda3/envs/research3/lib/python3.7/site-packages/cadquery/occ_impl/geom.py in
3 from typing import overload, Sequence, Union, Tuple, Type, Optional
4
----> 5 from OCP.gp import gp_Vec, gp_Ax1, gp_Ax3, gp_Pnt, gp_Dir, gp_Trsf, gp_GTrsf, gp, gp_XYZ
6 from OCP.Bnd import Bnd_Box
7 from OCP.BRepBndLib import BRepBndLib

ModuleNotFoundError: No module named 'OCP'


Do you have any solutions for this?

Jupyterlab is non-responsive for some time after rendering 3D model

Every time I show a model in Jupyter lab the following happens:

  1. The model is rendered part by part until complete
  2. The notebook is then non-responsive while Jupyter lab's bottom bar rapidly flickers between Busy and Idle for some time (maybe 10-20 seconds, more for larger models?)

Step number two seems to take more time the more objects are in the scene. The model is already rendered, so it seems like a bug, but maybe it does something that is necessary? Step two seems to take more time than step 1.

I'm using Firefox on Ubuntu, Jupyterlab 3.0.13 from conda (I followed the description in the jupyter-cadquery readme). I just upgraded to jupyter-cadquery-2.2.0rc0 to see if the problem was fixed.

Minimal example that triggers this in jupyterlab:

from math import sin, cos, pi

import cadquery as cq
import jupyter_cadquery.cadquery as jcq


xy = cq.Workplane("XY")
test = cq.Assembly(name="Test assembly")

r = 3
d = 0.1
for i in range(0, 361, 10):
    x = r * cos(i * 180 / pi)
    y = r * sin(i * 180 / pi)
    box = xy.box(d, d, r/2)
    box = box.translate([x, y, 0])
    test.add(box)

jcq.show(test)

Equivalent Vscode Extension

Hi @bernhard-42 , thanks for this awesome extension. I was just thinking about the possibilities of something like this for VSCode. Please could you tell me if you'd already given it some thought/have ideas about how it could be done?

Resize view

Hello,
I've tried to resize the 3D view in your new viewer that you presented here #42 , but I don't know how to do it.
I tried to change the size width like that :
show(shapes, cad_width = 1000)
But it doesn't do anything, I've also tried it with regular jupyter-cadquery and it doesn't do anything either. Am I doing it wrong ?

Docker instructions incomplete/don't work

I don't get along well with this newfangled docker thing yet, so I don't know my way round it other than typing in exactly the commands I'm told.

It seems I need to check out the repo first to get the Dockerfile.

git clone [email protected]:bernhard-42/jupyter-cadquery.git
cd jupyter-cadquery

And then it get stuck at a stage where files in /var/lib/ don't exist. Am I supposed to run this sudo or something?

cd docker
docker build -t bernard-42/jupyter-cadquery:0.9.5 .

Sending build context to Docker daemon 2.56kB
Step 1/13 : FROM continuumio/miniconda3:4.7.10
---> 4a51de2367be
Step 2/13 : RUN adduser --disabled-password --gecos "Default user" --uid 1000 cq && apt-get update -y && apt-get install --no-install-recommends -y libgl1-mesa-glx libglu1-mesa && rm -rf /var/lib/apt/lists/* && mkdir /data && chown cq:cq /data
---> Using cache
---> e5233e26bfb4
Step 3/13 : ADD --chown=cq:cq examples /home/cq
ADD failed: stat /var/lib/docker/tmp/docker-builder775350372/examples: no such file or directory

How to reset jcv's default startup page to my cadquery page?

Following the issue 42 , I start jcv with jcv -w 1200 -h 800 as shown below:
jcv_window

and return this default startup page:
jcv_default_page

by running this view.ipynb

from jupyter_cadquery.viewer.server import start_viewer
start_viewer() 

How can I replace the view.ipynb with my own cadquery page

for example: (as show in the issue 42 )

import cadquery as cq
from jupyter_cadquery.viewer.client import show

box = cq.Workplane().box(1, 1, 1).faces(">Z").hole(0.6).edges().fillet(0.05)
cyl = cq.Workplane().circle(0.1).extrude(1)

show(box, cyl, axes=True, transparent=True)

As a result, jcv -w 1200 -h 800 will return this page directly with disabled log at bottom:
jcv_new_page

Thanks a lot for any suggestions.

Consider adding to Jupyter Docker Stacks

We learned about your project in a great Open Source Hardware meeting today and we were amazed about the possibilities. I was curious if you'd considered contributing to the Jupyter Docker Stacks to make it easy for those of us that deploy JupyterHub on Kubernetes to make it much simpler to use your project.

https://jupyter-docker-stacks.readthedocs.io/en/latest/index.html

I may look more into what would need to occur to build a specific stack but felt this would be great for easy of operations for many of us that already leverage the environment.

Suggest to increase the function "get_pick_shape" to get object by clicking the model

Code

import cadquery as cq 
from jupyter_cadquery.cadquery import show
from jupyter_cadquery import set_defaults, set_sidecar, get_defaults
from jupyter_cadquery.cadquery import PartGroup as show_PartGroup
from jupyter_cadquery.cadquery import Part as show_Part
from jupyter_cadquery.cadquery import Faces as show_Face
from jupyter_cadquery.cadquery import Edges as show_Edge

set_sidecar("Cadquery", init=True)
set_defaults(axes=True, axes0=True)


result = cq.Workplane().box(2.0, 2.0, 0.5)
show_faces_list = [show_Face(cq.Workplane().add(face),name="Face_"+str(index)+"_"+str(face.hashCode()),color=(180, 180, 180)) for index,face in enumerate(result.faces().vals())]
show_result = show_PartGroup(
    show_faces_list,
    name="HashCode")
d = show(show_result)

Pick/click one face, and then :

pick_name = d.cq_view.pick_last_mesh.name
[i.shape for i in show_result.objects if i.name == pick_name ][0]

But I can only get the "OCP.TopoDS" type object. I need to set the HashCode first to get the "cadquery.occ_impl.shapes" object.
If possible, I want to get it more simply.

Unable to see "cadquery.Assembly" object in viewer

I'm using the standalone viewer by running jcv -d before running my Python files locally. I seem to be unable to show assembly objects. I see the following console output, but no exceptions are thrown:

. sending ... 
 AttributeError: 'NoneType' object has no attribute 'max_dist_from_center'

Here's a minimal repro:

import cadquery as cq
import jupyter_cadquery.viewer.client as j_viewer_client

box = cq.Workplane().rect(20, 20).extrude(40)
assembly = cq.Assembly().add(box)
j_viewer_client.show(assembly)

I've stepped through the code, and it seems like the jcv server is returning the above error message. I found the message by inpecting the reply from the jcv server at this line:

print("\n", reply["msg"])

Am I doing something wrong in my minimal repro? Is there a problem in the jcv server? Or maybe there's a problem in the client's convert() method?

def _convert(*cad_objs, **kwargs):

Nothing displayed when a shape is 800mm wide

If I run the following, I get a short prism drawn, and it works fine.

import cadquery as cq
from jupyter_cadquery.cadquery import show

r = cq.Workplane("XZ", (0,0,0))
r = r.moveTo(0,0)
r = r.lineTo(400,0)  # <--- change to 800 and there is nothing displayed!!!
r = r.lineTo(10,300)
r.close()
r = r.extrude(13)
show(r, axes=True, grid=True, ortho=True, axes0=True)

But if I change the 400 to 800, then nothing is drawn, not even any axes.

I've checked that the same problem occurs in that jupyter-cadquery launch|binder thing linked in the readme.

The exportSTL works when applied to the part, so it is there, but I don't know why the display fails.

Elementary installation error

I am using Windows 10, and following the instructions to the letter. However, the command

jupyter-labextension install --no-build $(cat labextensions.txt)

produces the error

ValueError: "$(cat" is not a valid npm package

I am not very knowledgeable about npm in general; all I want is to be able to use cadquery, and hopefully within jupyter. I ended up going through each of the four lines in labextensions.txt one by one - but is there a better way?

Edges display

It seems that convex edges are displayed/highlighted with a gray line, but concave edges are not.

In example, with this code the edges between the two extrusions are not displayed:

from cadquery import Workplane

Workplane("XY").rect(2, 2).extrude(1).faces(">Z").rect(1, 1).extrude(1)

Screenshot from 2020-01-15 22-33-57

Is that the expected behavior? How could it be fixed?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.