import sys
import wx
import os
import json
import inspect
from pathlib import Path
from .render_frame import RenderFrame
# Path to persistent state file in user home directory
STATE_FILE = Path.home() / ".pyvcad_render_state.json"
def _get_caller_id():
"""Identify the script invoking the render function."""
try:
# Step back through stack: 0=here, 1=renderWrapper, 2=caller
# We look for the first frame outside of this module
for frame_info in inspect.stack():
filename = frame_info.filename
# Ignore calls from within the library itself
if "pyvcad_rendering" in filename:
continue
return os.path.abspath(filename)
except Exception:
pass
return "unknown"
[docs]
def render(vcad_object, materials=None, quality=None, custom_voxel_size=None):
"""Open the interactive 3D viewer for ``vcad_object`` (wx main loop).
Arguments:
vcad_object (Node): The design to show.
materials (MaterialDefs, optional): Material definitions for volume-fraction colouring.
quality (str, optional): Starting sampling quality: "low", "medium", "high", "ultra" or
"custom". The named levels scale with the object (128, 256, 512 and 1024 samples along
its longest side), so a large design with thin walls or struts needs "high" or a
custom voxel size to look right. When given, this is the starting quality every time
the script runs; you can still change it in the viewer. When omitted, the viewer
restores the quality you last used for this script (or "low" the first time).
custom_voxel_size (float, optional): Voxel size in millimetres for quality="custom"
(setting it alone implies quality="custom").
Example:
>>> import pyvcad_rendering as viz
>>> viz.render(liner, quality="high")
>>> viz.render(liner, custom_voxel_size=0.4)
"""
caller_id = _get_caller_id()
# Load state
state = {}
if STATE_FILE.exists():
try:
with open(STATE_FILE, 'r') as f:
state = json.load(f)
except Exception:
state = {} # Corrupt file, reset
last_caller = state.get("last_caller", None)
settings_to_use = {}
# If the caller matches the last run, reuse settings
if last_caller == caller_id and "last_settings" in state:
settings_to_use = state["last_settings"]
else:
# New design context -> reset settings (empty dict uses defaults in RenderFrame)
settings_to_use = {}
# Update state with new caller immediately so if they crash/close, we track it
state["last_caller"] = caller_id
# Clear old settings in file to avoid confusion
state["last_settings"] = {}
try:
with open(STATE_FILE, 'w') as f:
json.dump(state, f, indent=4)
except:
pass
settings_to_use = _apply_quality(settings_to_use, quality, custom_voxel_size)
# Re-initialising wxWidgets after a MainLoop has already torn it down is
# unsupported, so a second render() in the same script reuses the running
# app rather than constructing another one. The frame is deliberately not
# parked on the app: it keeps itself alive until it is closed, and holding
# it here would strand the whole VTK scene for the rest of the process.
with wx.LogNull():
app = wx.GetApp() or wx.App(False)
# Pass state file path so Frame can save on close
RenderFrame(vcad_object, state_file=str(STATE_FILE), initial_settings=settings_to_use, materials=materials)
app.MainLoop()
def _apply_quality(settings, quality, custom_voxel_size):
"""Return ``settings`` with the requested starting quality, validating the arguments."""
if quality is None and custom_voxel_size is None:
return settings
if custom_voxel_size is not None and quality is None:
quality = "custom"
levels = ("low", "medium", "high", "ultra", "custom")
if quality not in levels:
raise ValueError(f"quality must be one of {', '.join(levels)}; got {quality!r}")
settings = dict(settings)
settings["quality"] = quality
if quality == "custom":
if custom_voxel_size is None:
raise ValueError('quality="custom" needs custom_voxel_size (mm)')
if not float(custom_voxel_size) > 0.0:
raise ValueError(f"custom_voxel_size must be positive; got {custom_voxel_size!r}")
settings["custom_voxel_size"] = float(custom_voxel_size)
return settings
[docs]
def Render(vcad_object, materials=None, quality=None, custom_voxel_size=None):
"""Alias for :func:`render`."""
render(vcad_object, materials, quality=quality, custom_voxel_size=custom_voxel_size)
[docs]
def render_image(vcad_object, filepath, settings=None, width=1920, height=1080, materials=None):
"""Render a single frame off-screen and save to ``filepath`` (no GUI).
Arguments:
vcad_object (Node): The design to render.
filepath (str): Image file to write, for example ``"part.png"``.
settings (dict, optional): View options, described below. Defaults to an iso-surface view at
"high" quality.
width (int): Image width in pixels.
height (int): Image height in pixels.
materials (MaterialDefs, optional): Material definitions for volume-fraction colouring.
Defaults to ``pyvcad.default_materials``.
``settings`` is a dict of view options, for example ``visualized_attribute``,
``quality``, ``render_mode``, ``scale_bar_palette`` ("auto" or a palette
name), ``scalar_range_mode`` ("auto" or "fixed") with ``scalar_range_min`` /
``scalar_range_max``, ``colormap_reverse``, camera keys and ``background_color``.
Analysis results can be shown with:
- ``below_range_color``, ``above_range_color``: an RGB colour (0-1 or 0-255) that
paints values outside the colour range, for example walls thinner than a fixed
range minimum in red. Pick a colour that stands out from the palette.
- ``mass_properties``: True to compute pv.mass_properties at the render's voxel
size (with ``materials``), or a pv.MassProperties report; draws the centre of
mass, the principal axes and a caption with the numbers.
- ``mass_properties_density``: uniform density in g/cm^3 for that computation.
- ``mass_properties_axes``, ``mass_properties_caption``: set False to hide the axes
or the caption.
Example:
>>> import pyvcad_rendering as viz
>>> viz.render_image(part, "mass.png", settings={"mass_properties": True}, materials=materials)
"""
# settings can include scale_bar_palette: "auto" or a named palette override.
from .headless_renderer import HeadlessRenderer
renderer = HeadlessRenderer(width=width, height=height)
renderer.render_and_save(vcad_object, filepath, settings=settings, materials=materials)
[docs]
def Render_Image(vcad_object, filepath, settings=None, width=1920, height=1080, materials=None):
"""Alias for :func:`render_image`."""
render_image(vcad_object, filepath, settings, width, height, materials=materials)
[docs]
def render_turntable_animation(vcad_object, output_dir, duration=3.0, fps=30, distance_multiplier=1.5, elevation_angle_deg=30.0, settings=None, width=1920, height=1080, output_format="gif", keep_frames=False, materials=None):
"""Orbit the camera around the design and write an animation under ``output_dir`` (no GUI).
Arguments:
vcad_object (Node): The design to render.
output_dir (str): Directory for the output. It is created if missing. The animation is written
as ``animation.<format>`` and the frames as ``frame_NNN.png``.
duration (float): Length of the orbit in seconds. The animation has ``duration * fps`` frames.
fps (int): Frames per second.
distance_multiplier (float): Camera distance as a multiple of the bounding-box diagonal, or of
the saved camera distance when ``settings`` holds a camera.
elevation_angle_deg (float): Camera elevation above the XY plane in degrees.
settings (dict, optional): View options, as for :func:`render_image`.
width (int): Frame width in pixels.
height (int): Frame height in pixels.
output_format (str): "gif", "webp", "mp4", "webm", or "all" to write every format.
keep_frames (bool): Keep the PNG frames after the animation is written.
materials (MaterialDefs, optional): Material definitions for volume-fraction colouring.
Defaults to ``pyvcad.default_materials``.
Example:
>>> import pyvcad_rendering as viz
>>> viz.render_turntable_animation(part, "turntable", duration=4.0, output_format="mp4")
"""
# settings can include scale_bar_palette: "auto" or a named palette override.
from .headless_renderer import HeadlessRenderer
renderer = HeadlessRenderer(width=width, height=height)
renderer.render_turntable_animation(vcad_object, output_dir, duration=duration, fps=fps, distance_multiplier=distance_multiplier, elevation_angle_deg=elevation_angle_deg, settings=settings, output_format=output_format, keep_frames=keep_frames, materials=materials)
[docs]
def Render_Turntable_Animation(vcad_object, output_dir, duration=3.0, fps=30, distance_multiplier=1.5, elevation_angle_deg=30.0, settings=None, width=1920, height=1080, output_format="gif", keep_frames=False, materials=None):
"""Alias for :func:`render_turntable_animation`."""
render_turntable_animation(vcad_object, output_dir, duration, fps, distance_multiplier, elevation_angle_deg, settings, width, height, output_format, keep_frames, materials=materials)
[docs]
def render_sweep_animation(vcad_object, output_dir, axis="z", duration=3.0, fps=30, loop=False, pause_seconds=0.5, settings=None, width=1920, height=1080, output_format="gif", keep_frames=False, materials=None):
"""Sweep a clipping plane through the design and write an animation under ``output_dir`` (no GUI).
The plane moves from just below the bounding box to just above it along ``axis``, revealing the
interior one section at a time.
Arguments:
vcad_object (Node): The design to render.
output_dir (str): Directory for the output. It is created if missing. The animation is written
as ``animation.<format>`` and the frames as ``frame_NNN.png``.
axis (str): Sweep axis: "x", "y" or "z".
duration (float): Length of one sweep in seconds. The sweep has ``duration * fps`` frames.
fps (int): Frames per second.
loop (bool): Play the sweep forward and then backward.
pause_seconds (float): Hold on the first and last frames for this long.
settings (dict, optional): View options, as for :func:`render_image`.
width (int): Frame width in pixels.
height (int): Frame height in pixels.
output_format (str): "gif", "webp", "mp4", "webm", or "all" to write every format.
keep_frames (bool): Keep the PNG frames after the animation is written.
materials (MaterialDefs, optional): Material definitions for volume-fraction colouring.
Defaults to ``pyvcad.default_materials``.
Example:
>>> import pyvcad_rendering as viz
>>> viz.render_sweep_animation(part, "sweep", axis="z", loop=True)
"""
from .headless_renderer import HeadlessRenderer
renderer = HeadlessRenderer(width=width, height=height)
renderer.render_sweep_animation(vcad_object, output_dir, axis=axis, duration=duration, fps=fps, loop=loop, pause_seconds=pause_seconds, settings=settings, output_format=output_format, keep_frames=keep_frames, materials=materials)
[docs]
def Render_Sweep_Animation(vcad_object, output_dir, axis="z", duration=3.0, fps=30, loop=False, pause_seconds=0.5, settings=None, width=1920, height=1080, output_format="gif", keep_frames=False, materials=None):
"""Alias for :func:`render_sweep_animation`."""
render_sweep_animation(vcad_object, output_dir, axis, duration, fps, loop, pause_seconds, settings, width, height, output_format, keep_frames, materials=materials)
__all__ = ["render", "Render", "render_image", "Render_Image", "render_turntable_animation", "Render_Turntable_Animation", "render_sweep_animation", "Render_Sweep_Animation"]