cqparts.display package

Submodules

cqparts.display.cqparts_server module

class cqparts.display.cqparts_server.CQPartsServerDisplayEnv(name=None, order=0, condition=<function <lambda>>)

Bases: cqparts.display.environment.DisplayEnvironment

Display given component in a cqps-server window.

display_callback(component)
Parameters:component (Component) – the component to render

cqparts.display.environment module

cqparts.display.environment.map_environment(**kwargs)

Decorator to map a DisplayEnvironment for displaying components. The decorated environment will be chosen if its condition is True, and its order is the smallest.

Parameters:add_to (dict) – if set to globals(), display environment’s constructor may reference its own type.

Any additional named parameters will be passed to the constructor of the decorated DisplayEnvironment. See DisplayEnvironment for example usage.

NameError on importing

The following code:

@map_environment(
    name='abc', order=10, condition=lambda: True,
)
class SomeDisplayEnv(DisplayEnvironment):
    def __init__(self, *args, **kwargs):
        super(SomeDisplayEnv, self).__init__(*args, **kwargs)

Will raise the Exception:

NameError: global name 'SomeDisplayEnv' is not defined

Because this map_environment decorator attempts to instantiate this class before it’s returned to populate the global() dict.

To cicrumvent this problem, set add_to to globals():

@map_environment(
    name='abc', order=10, condition=lambda: True,
    add_to=globals(),
)
class SomeDisplayEnv(DisplayEnvironment):
    ... as above
class cqparts.display.environment.DisplayEnvironment(name=None, order=0, condition=<function <lambda>>)

Bases: object

display(*args, **kwargs)
display_callback(*args, **kwargs)

Display given component in this environment.

Note

To be overridden by inheriting classes

An example of a introducing a custom display environment.

import cqparts
from cqparts.display.environment import DisplayEnvironment, map_environment

def is_text_env():
    # function that returns True if it's run in the
    # desired environment.
    import sys
    # Python 2.x
    if sys.version_info[0] == 2:
        return isinstance(sys.stdout, file)
    # Python 3.x
    import io
    return isinstance(sys.stdout, io.TextIOWrapper)

@map_environment(
    name="text",
    order=0,  # force display to be first priority
    condition=is_text_env,
)
class TextDisplay(DisplayEnvironment):
    def display_callback(self, component, **kwargs):
        # Print component details to STDOUT
        if isinstance(component, cqparts.Assembly):
            sys.stdout.write(component.tree_str(add_repr=True))
        else:  # assumed to be a cqparts.Part
            sys.stdout.write("%r\n" % (component))

is_text_env() checks if there’s a valid sys.stdout to write to, TextDisplay defines how to display any given component, and the @map_environment decorator adds the display paired with its environment test function.

When using display(), this display will be used if is_text_env() returns True, and no previously mapped environment with a smaller order tested True:

# create component to display
from cqparts_misc.basic.primatives import Cube
cube = Cube()

# display component
from cqparts.display import display
display(cube)

The display_callback will be called via display(). So to call this display method directly:

TextDisplay().display(cube)
Raises:NotImplementedError if not overridden

cqparts.display.freecad module

class cqparts.display.freecad.FreeCADDisplayEnv(name=None, order=0, condition=<function <lambda>>)

Bases: cqparts.display.environment.DisplayEnvironment

Display given component in FreeCAD

Only works from within FreeCAD cadquery script; using this to display a Component will not open FreeCAD.

display_callback(component, **kwargs)

Display given component in FreeCAD

Parameters:component (Component) – the component to render

cqparts.display.material module

class cqparts.display.material.RenderParam(default=None, doc=None)

Bases: cqparts.params.types.NonNullParameter

classmethod serialize(value)
type(selv, value)
class cqparts.display.material.RenderProps(color=(200, 200, 200), alpha=1)

Bases: object

Properties for rendering.

This class provides a RenderParam instance as a Parameter for a ParametricObject.

>>> from cqparts.params import ParametricObject
>>> from cqparts.display.material import RenderParam, TEMPLATE, COLOR
>>> class Thing(ParametricObject):
...     _render = RenderParam(TEMPLATE['red'], doc="render params")
>>> thing = Thing()
>>> thing._render.color
(255, 0, 0)
>>> thing._render.alpha
1.0
>>> thing = Thing(_render={'color': COLOR['green'], 'alpha': 0.5})
>>> thing._render.color
(0, 255, 0)
>>> thing._render.alpha
0.5
>>> thing._render.dict
{'color': (0, 255, 0), 'alpha': 0.5}

The TEMPLATE and COLOR dictionaries provide named templates to display your creations quickly, but you can also provide custom properties.

__init__(color=(200, 200, 200), alpha=1)
Parameters:
  • color (tuple) – 3-tuple of RGB in the bounds: {0 <= val <= 255}
  • alpha (float) – object alpha in the range {0 <= alpha <= 1} where 0 is transparent, and 1 is opaque
dict

Return a dict of this instance. Can be used to set a property based on the property of another.

Returns:dict of render attributes
Return type:dict
gltf_material
Returns:glTF Material
Return type:dict
rgb

Red, Green, Blue

Returns:red, green, blue values
Return type:tuple

synonym for color

rgba

Red, Green, Blue, Alpha

Returns:red, green, blue, alpha values
Return type:tuple
>>> from cqparts.display import RenderProps
>>> r = RenderProps(color=(1,2,3), alpha=0.2)
>>> r.rgba
(1, 2, 3, 0.2)
rgbt

Red, Green, Blue, Transparency

Returns:red, green, blue, transparency values
Return type:tuple
>>> from cqparts.display import RenderProps
>>> r = RenderProps(color=(1,2,3), alpha=0.2)
>>> r.rgbt
(1, 2, 3, 0.8)
transparency
Returns:transparency value, 1 is invisible, 0 is opaque
Return type:float
cqparts.display.material.render_props(**kwargs)

Return a valid property for cleaner referencing in Part child classes.

Parameters:
  • template (str) – name of template to use (any of TEMPLATE.keys())
  • doc (str) – description of parameter for sphinx docs
Returns:

render property instance

Return type:

RenderParam

>>> import cadquery
>>> from cqparts.display import render_props
>>> import cqparts
>>> class Box(cqparts.Part):
...     # let's make semi-transparent aluminium (it's a thing!)
...     _render = render_props(template='aluminium', alpha=0.8)
>>> box = Box()
>>> box._render.rgba
(192, 192, 192, 0.8)

The tools in cqparts.display will use this colour and alpha information to display the part.

cqparts.display.web module

class cqparts.display.web.WebDisplayEnv(name=None, order=0, condition=<function <lambda>>)

Bases: cqparts.display.environment.DisplayEnvironment

Display given component in a browser window

This display exports the model, then exposes a http service on localhost for a browser to use. The http service does not know when the browser window has been closed, so it will continue to serve the model’s data until the user halts the process with a KeyboardInterrupt (by pressing Ctrl+C)

When run, you should see output similar to:

>>> from cqparts.display import WebDisplayEnv
>>> from cqparts_misc.basic.primatives import Cube
>>> WebDisplayEnv().display(Cube())
press [ctrl+c] to stop server
127.0.0.1 - - [27/Dec/2017 16:06:37] "GET / HTTP/1.1" 200 -
Created new window in existing browser session.
127.0.0.1 - - [27/Dec/2017 16:06:39] "GET /model/out.gltf HTTP/1.1" 200 -
127.0.0.1 - - [27/Dec/2017 16:06:39] "GET /model/out.bin HTTP/1.1" 200 -

A new browser window should appear with a render that looks like:

../_images/web_display.cube.png

Then, when you press Ctrl+C, you should see:

^C[server shutdown successfully]

and any further request on the opened browser window will return an errorcode 404 (file not found), because the http service has stopped.

display_callback(component, port=9041, autorotate=False)
Parameters:
  • component (Component) – the component to render
  • port (int) – port to expose http service on
  • autorotate (bool) – if True, rendered component will rotate as if on a turntable.

Module contents

cqparts.display.render_props(**kwargs)

Return a valid property for cleaner referencing in Part child classes.

Parameters:
  • template (str) – name of template to use (any of TEMPLATE.keys())
  • doc (str) – description of parameter for sphinx docs
Returns:

render property instance

Return type:

RenderParam

>>> import cadquery
>>> from cqparts.display import render_props
>>> import cqparts
>>> class Box(cqparts.Part):
...     # let's make semi-transparent aluminium (it's a thing!)
...     _render = render_props(template='aluminium', alpha=0.8)
>>> box = Box()
>>> box._render.rgba
(192, 192, 192, 0.8)

The tools in cqparts.display will use this colour and alpha information to display the part.

class cqparts.display.RenderProps(color=(200, 200, 200), alpha=1)

Bases: object

Properties for rendering.

This class provides a RenderParam instance as a Parameter for a ParametricObject.

>>> from cqparts.params import ParametricObject
>>> from cqparts.display.material import RenderParam, TEMPLATE, COLOR
>>> class Thing(ParametricObject):
...     _render = RenderParam(TEMPLATE['red'], doc="render params")
>>> thing = Thing()
>>> thing._render.color
(255, 0, 0)
>>> thing._render.alpha
1.0
>>> thing = Thing(_render={'color': COLOR['green'], 'alpha': 0.5})
>>> thing._render.color
(0, 255, 0)
>>> thing._render.alpha
0.5
>>> thing._render.dict
{'color': (0, 255, 0), 'alpha': 0.5}

The TEMPLATE and COLOR dictionaries provide named templates to display your creations quickly, but you can also provide custom properties.

__init__(color=(200, 200, 200), alpha=1)
Parameters:
  • color (tuple) – 3-tuple of RGB in the bounds: {0 <= val <= 255}
  • alpha (float) – object alpha in the range {0 <= alpha <= 1} where 0 is transparent, and 1 is opaque
dict

Return a dict of this instance. Can be used to set a property based on the property of another.

Returns:dict of render attributes
Return type:dict
gltf_material
Returns:glTF Material
Return type:dict
rgb

Red, Green, Blue

Returns:red, green, blue values
Return type:tuple

synonym for color

rgba

Red, Green, Blue, Alpha

Returns:red, green, blue, alpha values
Return type:tuple
>>> from cqparts.display import RenderProps
>>> r = RenderProps(color=(1,2,3), alpha=0.2)
>>> r.rgba
(1, 2, 3, 0.2)
rgbt

Red, Green, Blue, Transparency

Returns:red, green, blue, transparency values
Return type:tuple
>>> from cqparts.display import RenderProps
>>> r = RenderProps(color=(1,2,3), alpha=0.2)
>>> r.rgbt
(1, 2, 3, 0.8)
transparency
Returns:transparency value, 1 is invisible, 0 is opaque
Return type:float
class cqparts.display.RenderParam(default=None, doc=None)

Bases: cqparts.params.types.NonNullParameter

classmethod serialize(value)
type(selv, value)
cqparts.display.display(component, **kwargs)

Display the given component based on the environment it’s run from. See DisplayEnvironment documentation for more details.

Parameters:component (Component) – component to display

Additional parameters may be used by the chosen DisplayEnvironment

cqparts.display.get_display_environment()

Get the first qualifying display environment.

Returns:highest priority valid display environment
Return type:DisplayEnvironment

see @map_environment for more information.

This method is a common way to change script behaviour based on the environment it’s running in. For example, if you wish to display a model when run in one environment, but export it to file when run in another, you could:

from cqparts.display import get_display_environment, display
from cqparts_misc.basic.primatives import Cube

obj = Cube()

env_name = get_display_environment().name
if env_name == 'freecad':
    # Render the object in a FreeCAD window
    display(obj)
else:
    # Export the object to a file.
    obj.exporter('gltf')('my_object.gltf')

This is useful when creating a sort of “build environment” for your models.