vscode-ocp-cad-viewer
vscode-ocp-cad-viewer copied to clipboard
A viewer for OCP based Code-CAD (CadQuery, build123d) integrated into VS Code
OCP CAD Viewer for VS Code
OCP CAD Viewer for VS Code is an extension to show CadQuery and build123d objects in VS Code via the three-cad-viewer viewer component.
Installation
Prerequisites
- A fairly recent version of Microsoft VS Code, e.g. 1.85.0 or newer
- The Python extension installed in VS Code
- Necessary tools:
pythonandpipavailable in the Python enviroment that will be used for CAD development- The command
gitneeds to be available - On a Silicon Apple computer the command
mambaneeds to be available. You might want to consider using Mambaforge.
Notes:
- To use OCP CAD Viewer, start VS Code from the commandline in the Python environment you want to use or select the right Python interpreter in VS Code first. OCP CAD Viewer depends on VS Code using the right Python interpreter (i.e. mamba / conda / pyenv / poetry / ... environment).
- For VSCodium, the extension is not available in the VS code market place. You need to download the the vsix file from the release folder and install it manually.
- Currently, on a Silicon Mac (ARM CPU), OCP and CadQuery can only be installed via
mamba, see 3. below.
Installation
-
Open the VS Code Marketplace, and search and install OCP CAD Viewer 2.3.3.
Afterwards the OCP viewer is available in the VS Code sidebar:

-
Clicking on it shows the OCP CAD Viewer UI with the viewer manager and the library manager:

You have 3 options:
-
Prepare OCP CAD Viewer for working with build123d: Presse the Quickstart build123d button.
This will install OCP, build123d, ipykernel (jupyter_client), ocp_tessellate and ocp_vscode via
pip(except for Apple Silicon machines that requiremambaand will also install cadquery)
-
Prepare OCP CAD Viewer for working with CadQuery: Presse the Quickstart CadQuery button.
This will install OCP, CadQuery, ipykernel (jupyter_client), ocp_tessellate and ocp_vscode via
pip(except for Apple Silicon machines that requiremamba)
-
Ignore the quick starts and use the "Library Manager" to install the libraries. Doing so, OCP CAD Viewer let's you select whether to use
pip,mamba,condaorpoetry. Install the needed library by pressing the green down-arrow behind the library name in the "Library Manager" section of the OCP CAD Viewer sidebar. For more details, see here
The Quickstarts will also
- (optionally) install the the Jupyter extension for VS Code from Microsoft
- start the OCP viewer
- create a demo file in a temporary folder to quickly see a simple usage example
-
-
On Silicon Macs (ARM CPU)
- Install Miniforge
- Option 1: Download and install from the Miniforge github page
- Option 2: Use
homebrew:brew install miniforge
- Initialize your shell for
mamba:mamba init $(basename "$SHELL") - Create an environment, e.g named
code_cadwith Python 3.10:mamba create -n code_cad python=3.10 - Activate the environment:
mamba activate code_cad - Start VS Code from your working folder:
code . - Install the Python extension in VS Code
- Continue with 1. above
- Install Miniforge
Usage
Running code using Jupyter
- Start the OCP CAD Viewer by pressing the green box-arrow button in the "Viewer Manager" section of the OCP CAD Viewer sidebar
- Import ocp_vscode and the CAD library by using the paste button behing the library names in the "Viewer Manager" section
- Use the usual Run menu to run the code

Debugging code with visual debugging
After each step, the debugger checks all variables in locals() for being CAD objects and displays them with their variable name.
Note:
- Check that
OCP:onis visible in the status bar - It also shows planes, locations and axis, so name your contexts
- It remembers camera position and unselected variables in the tree
- during debugging,
showandshow_objectare disabled. They interfere with the visual debugging

Library Manager
You can also use "Library Manager" in the OCP CAD Viewer sidebar to manage the Python libraries for build123d, cadquery, ipython and ocp_tessellate (Presse the green arrow whenhovering over a library to install/upgrade it)
Extra topics
- Quickstart experience on Windows
- Use Jupyter to execute code
- Debug code with visual debugging
- Measure mode
- Use the
showcommand - Use the
show_objectcommand - Use the
set_viewer_configcommand - Download examples for build123d or cadquery
- Use the build123d snippets
Best practices
-
Use the Jupyter extension for a more interactive experience. This allows to have one cell (separated by
# %%) at the beginning to import all libraries# %% from build123d import * from ocp_vscode import * # %% b = Box(1,2,3) show(b) # %%and then only execute the code in the cell you are currently working on repeatedly.
-
The config system of OCP CAD Viewer
There are 3 levels:
- Workspace configuration (part of the VS Code settings, you can access them e.g. via the green gear symbol in OCP CAD Viewer's "Viewer Manager")
- Defaults set with the command
set_defaultsper Python file - Parameters in
showorshow_objectper command
set_defaultsoverrides the Workspace settings and parameters inshowandshow_configoverride the other two.Note that not all parameters are available in the global Workspace config, since they don't make sense globally (e.g.
helper_scalewhich depends on the size of the boundary box of the currently shown object)A common setup would be
# %% from build123d import * import cadquery as cq from ocp_vscode import * set_port(3939) set_defaults(reset_camera=False, helper_scale=5) # %% ...Explanation
- The first block imports build123d and CadQuery (omit what you are not interested in).
- The second block imports all commands for OCP CAD Viewer.
set_portis only needed when you have more than one viewer open and can be omitted for the first viewer) - The third block as an example sets helper_scale and reset_camera as defaults. Then every show_object or show command will respect it as the default
-
Debugging build123d with
show_alland the visual debugger-
If you name your contexts (including
Locationcontexts), the visual debugger will show the CAD objects assigned to the context. -
Use
show_allto show all cad objects in the current scope (locals()) of the Python interpreter (btw. the visual debugger usesshow_allat each step)# %% from build123d import * set_defaults(helper_scale=1, transparent=True) with BuildPart() as bp: with PolarLocations(3,8) as locs: Box(1,1,1) show_all() # %%
-
-
Keep camera orientation of an object with
reset_cameraSometimes it is helpful to keep the orientation of an object across code changes. This is what
reset_cameradoes:reset_camera=Camera.Centerwill keep position and rotation, but ignore panning. This means the new object will be repositioned to the center (most robust approach)reset_camera=Camera.KEEPwill keep position, rotation and panning. However, panning can be problematic. When the next object to be shown is much larger or smaller and the object before was panned, it can happen that nothing is visible (the new object at the pan location is outside of the viewer frustum). OCP CAD Viewer checks whether the bounding box of an object is 2x smaller or larger than the one of the last shown object. If so, it falls back toCamera.CENTER. A notification is written to the OCP CAD Viewer output panel.reset_camera=Camera.RESETwill ensure that position, rotation and panning will be reset to the initial default
Development
Testing:
Native tessellator can be set via NATIVE_TESSELLATOR=1and Python tessellator via NATIVE_TESSELLATOR=0.
When OCP_VSCODE_PYTEST=1 is set, show will not send the tessellated results to the viewer, but return it to the caller for inspection.
A full test cycle consist of:
NATIVE_TESSELLATOR=0 OCP_VSCODE_PYTEST=1 pytest -v -s pytests/
NATIVE_TESSELLATOR=1 OCP_VSCODE_PYTEST=1 pytest -v -s pytests/
Troubleshooting
-
CAD Models almost always are invisible in the OCP viewer window
three-cad-viewer.esm.js:20276 THREE.WebGLProgram: Shader Error 0 - VALIDATE_STATUS false Material Name: Material Type: LineBasicMaterial Program Info Log: Program binary could not be loaded. Binary is not compatible with current driver/hardware combination. Driver build date Mar 19 2024. Please check build information of source that generated the binary. Location of variable pc_fragColor conflicts with another variable.VS Code internal browser that renders the viewer component uses a cache for code and other artifacts. This includes WebGL artefacts like compiled shaders. It can happen that e.g. due to a graphic driver update the compiled version in the cache does not fit to the new driver. Then this error message appears.
Solution: Delete the VS Code browser cache on Linux (go to the section for your operating system)
Changes
v2.3.3
- Fix regression that visual debug hangs
- Fix regression that build123d sketches are not draw correctly any more (fix in ocp-tessellate)
v2.3.2
- Fix regression that Python script hang in threading before exit (#73)
v2.3.1
- Add latest ocp-tessellate to fixed regression with handling instances
- Make native default if ocp-addons exists
v2.3.0 Fine tune communication to ensure the memory view of buffers will be passed through to javascript for performance (*) Use of the new protocol v3 of three-cad-viewer Fix show_all regressions https://github.com/bernhard-42/vscode-ocp-cad-viewer/issues/71. It should also properly catch exceptions now to not interrupt viausl debugging Add newest ocp-tessellate to allow using native tessellator from ocp_addons
v2.2.2
- Fix regression in measure tools
v2.2.1
- Fix: Wrong back material color for faces
- Improve parameters of Imageface
- Improve clipping when faces are deselected
v2.2.0
- Clipping now works with caps (default: red, green, blue cap faces). For assemblies the cap faces can use the associated object colors
- Grid now can be centered (parameter:
center_grid=True): With axes0==True centered at the origin(0,0,0), i.e absolute units With axes0==False centered at the center of mass, i.e relative units - Grid now has numbers at the gridlines serving as a ruler (#60)
ocp_vscodenow has a classImageFace. It works like an OCP rectangle, but can get an image path and a location (#28). Usage:plane = ImageFace(image_path, width, location=Location((x, y, z), (ax, ay, az)))- The CAD tree changed behavior: The eye icon toggles both faces and edges. The mesh icon toggles the mesh (edges) only (#56) This can be switched back to old behavior in the VS Code workspace settings "OCP CAD Viewer > View:New_tree_behavior"
- New parameter
show_sketch_local: when set toFalse,build123dlocal sketches will not be shown (works eithset_defaults) (#59) - New parameter "OCP CAD Viewer > Advanced:Autohide Terminal" in the VS Code workspace settings to control whether terminal will be hid when the viewer starts or not (#61)
- Viewer keeps clipping settings when
reset_camerais set toCamera.KEEPorCamera.CENTER(#43) - Material configurator now has a reset button "R" to get back to initial values
show_allnow converts nested dicts and lists into viewer hierarchiesset_viewer_configis documented in README- Fix:
show_parentnow supported byshow_defaults(#64) - Fix:
show_all()now works in non visual debugging mode (removedforceparameter fromshow_all) - Fix:
show_all()now doesn't break when an array ofColorsis in thelocalsvariable list (#45) - Fix:
show_allnow ignores unknown types in lists or dicts without raising an error and only printing a warning (#67) - Fix: The
serializeanddeserializecommands don't crash on Windows any more (#65) - Fix: Status notifications for grid work again (#66)
full change log see CHANGELOG.md