Skip to content

Instantly share code, notes, and snippets.

@noteed
Last active October 8, 2020 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noteed/db47709fe4869139a4a6453c2c9064d8 to your computer and use it in GitHub Desktop.
Save noteed/db47709fe4869139a4a6453c2c9064d8 to your computer and use it in GitHub Desktop.
Learn CadQuery

Learning CadQuery

This directory shows how to achieve the same thing as in the documentation: https://cadquery.readthedocs.io/en/latest/examples.html: i.e. have interactive 3D images done with CadQuery.

Initially I've tried to replicate the example at the top of this question: https://stackoverflow.com/questions/59462182/embed-widgets-with-jupyter-cadquery-threejs-wrong-position-on-load:

from cadquery import Workplane
from ipywidgets import embed
from jupyter_cadquery.cad_view import CadqueryView
from jupyter_cadquery.cadquery import Assembly
from jupyter_cadquery.cadquery import Part

box = Workplane('XY').box(10, 10, 10).translate((0, 0, 5))
assembly = Assembly([Part(box)], "example 1")
shapes = assembly.collect_shapes()
view = CadqueryView()
for shape in shapes:
    view.add_shape(shape["name"], shape["shape"], shape["color"])
renderer = view.render()
embed.embed_minimal_html('export.html', views=renderer, title='Renderer')

But depending on the Docker image I've used, I encountered different problems, detailed below.

Finally I simply used the main repository's Sphinx-based documentation, which includes interactive renderings. This is done with https://github.com/Peque/sphinxcadquery.

Docker

In the Docker images below, run something like

# /opt/miniconda/envs/cq/bin/python

bwalter42/jupyter_cadquery Docker image

  • I can import cadquery
  • I cannot run cq.exporters.export(result,'result.stl')
  • I can import ipywidgets and jupyter_cadquery
  • I'm stuck at renderer = view.render():

The last two imports are supposed to be used to export an HTML viewer but I'm stuck at

view = CadqueryView()
renderer = view.render()

The render() function seems to require a position and a rotation.

The fact that there is no export() function makes me thing that parts of this image are not up-to-date (although cadquery.__version reports 2.0).

kalemena/cadquery Docker image

  • I can import cadquery
  • I can run cadquery.exporters.export(result,'result.stl')
  • I cannot import ipywidgets and jupyter_cadquery

Maybe I should try to add ipywidgets and jupyter_cadquery to this image (instead of trying to update the first image).

The former "This" Docker image

(My attempt is named environment.yml.this.)

I have adapted the kalemena image to use the environment.yml file of the bwalter42 image where I have added/changed:

  - cadquery=master
  - cq-editor=master
  - pythonocc-core
  • I can import cadquery
  • I can run cadquery.exporters.export(result,'result.stl')
  • I can import ipywidgets and jupyter_cadquery
  • I'm still stuck at renderer = view.render() although with a different error.

I don't know why I needed to add pythonocc-core (necessary to import jupyter_cadquery), but it still doesn't work.

This Docker image

Using CadQuery/cadquery's environment.yml and conf.py, and running /opt/miniconda/envs/cq/bin/sphinx-build -b html /source /source/generated within the Docker image works.

So the Dockerfile simply does that.

sphinx-build expects conf.py and index.rst files.

Finally, you need a copy of CadQuery/cadquery's doc/_static directory (Gists cannot contain directories...)

Nix

I've found this repository https://github.com/marcus7070/cq-dev but running nix-shell fails (while compiling some C++ I think).

There is also another flake branch, which is very recent but the commit message makes me think it doesn't work yet.

There is also this repository https://github.com/rowanG077/cadquery-nix. I haven't tried it but it is 16 months old.

#! /usr/bin/env bash
# Build a Docker image that can run sphinx-build to produce HTML pages with
# interactive 3D renderings made with CadQuery, then use it to build index.rst
# to _site/index.html.
docker build -t cadquery-example .
docker run --rm -v $(pwd):/source cadquery-example
if [[ -d ../entrypoint/as-is/cadquery ]] ; then
rsync -aP --delete _site/ ../entrypoint/as-is/cadquery/
cat << EOF > ../entrypoint/as-is/cadquery/README.md
This directory is generated by learn-cadquery/run.sh.
EOF
fi
# -*- coding: utf-8 -*-
#
# This is a copy of CadQuery/cadquery/doc/conf.py.
#
# CadQuery documentation build configuration file, created by
# sphinx-quickstart on Sat Aug 25 21:10:53 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import os.path
# print "working path is %s" % os.getcwd()
# sys.path.append("../cadquery")
import cadquery
# settings._target = None
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx_autodoc_typehints",
"sphinx.ext.viewcode",
"sphinx.ext.autosummary",
"cadquery.cq_directive",
"sphinxcadquery.sphinxcadquery",
]
always_document_param_types = True
# Configure `sphinxcadquery`
sphinxcadquery_include_source = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = u"CadQuery example"
copyright = u"Võ Minh Thu"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "1.0"
# The full version, including alpha/beta/rc tags.
release = "1.0.0"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# html_theme = 'timlinux-linfiniti-sphinx'
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {
# "headerfont": "'Open Sans',Arial,sans-serif",
# #"bodyfont:": "'Open Sans',Arial,sans-serif",
# #"headerbg" : "{image: url('/img/bg/body.jpg');color:#000000;}",
# "headerbg" : "color:black;",
# "footerbg" : "{color:#13171A;}",
# "linkcolor": "#84B51E;",
## "headercolor1": "#13171A;",
# "headercolor2": "#444;",
# "headerlinkcolor" : "#13171A;",
# }
# agogo options
"""
bodyfont (CSS font family): Font for normal text.
headerfont (CSS font family): Font for headings.
pagewidth (CSS length): Width of the page content, default 70em.
documentwidth (CSS length): Width of the document (without sidebar), default 50em.
sidebarwidth (CSS length): Width of the sidebar, default 20em.
bgcolor (CSS color): Background color.
headerbg (CSS value for “background”): background for the header area, default a grayish gradient.
footerbg (CSS value for “background”): background for the footer area, default a light gray gradient.
linkcolor (CSS color): Body link color.
headercolor1, headercolor2 (CSS color): colors for <h1> and <h2> headings.
headerlinkcolor (CSS color): Color for the backreference link in headings.
textalign (CSS text-align value): Text alignment for the body, default is justify.
"""
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "CadQuery Example"
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/cqlogo.png"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "CadQuerydoc"
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
# latex_documents = []
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
# man_pages = []
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
# texinfo_documents = []
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# Adapted from
# https://raw.githubusercontent.com/kalemena/docker-cadquery/master/Dockerfile.
FROM ubuntu:18.04
ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
# Compiler tools
RUN apt-get update -y \
&& apt-get install -qqy \
wget bzip2 ca-certificates software-properties-common \
libglu1-mesa libgl1-mesa-dri mesa-common-dev libglu1-mesa-dev \
libxi6 fonts-freefont-ttf \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
ENV QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb
RUN cd /opt \
&& wget https://repo.anaconda.com/miniconda/Miniconda3-py37_4.8.3-Linux-x86_64.sh -O miniconda.sh \
&& bash miniconda.sh -b -p /opt/miniconda
ENV PATH="/opt/miniconda/bin:/opt/miniconda/lib:$PATH"
COPY environment.yml /tmp/
RUN conda config --set always_yes yes --set changeps1 no \
&& conda env create -f /tmp/environment.yml -n cq \
&& conda clean -a -y
CMD /opt/miniconda/envs/cq/bin/sphinx-build -b html /source /source/_site
name: cadquery
channels:
- cadquery
- conda-forge
- defaults
dependencies:
- python>=3.6
- ipython
- ocp
- pyparsing
- sphinx=3.2.1
- sphinx_rtd_theme
- sphinx-autodoc-typehints
- black
- codecov
- pytest
- pytest-cov
- ezdxf
- ipython
- typing_extensions
- nptyping
- scipy
- pip
- cadquery=master
- pip:
- sphinxcadquery
channels:
- defaults
- cadquery
- conda-forge
dependencies:
- python=3.7
- numpy=1.19.1
- pip=19.3.1
- notebook>=6.1,<6.2
- jupyterlab>=2.2,<3
- sidecar=0.4.0
- ipywidgets=7.5.1
- pythreejs>=2.2,<2.3
- cadquery=master
- cq-editor=master
- pythonocc-core
- pip:
- jupyter_cadquery==1.0.0

Minimal CadQuery example

result = cadquery.Workplane("front").box(2.0, 2.0, 0.5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment