### Clone OpenVCAD Examples Repository Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/install.md.txt Clones the public repository containing example scripts and demos for OpenVCAD. Requires git to be installed on the system. ```bash git clone https://github.com/MacCurdyLab/OpenVCAD-Public.git cd OpenVCAD-Public/examples ``` -------------------------------- ### Create and Navigate Project Directory Source: https://matterassembly.org/OpenVCAD-Docs/v2/install.html Creates a new directory for an OpenVCAD project and changes the working directory to it. ```bash mkdir my_openvcad_project cd my_openvcad_project ``` -------------------------------- ### Setup Project Directory and Virtual Environment Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/install.md.txt Commands to create a dedicated project directory and a virtual environment to manage dependencies. Includes platform-specific activation commands for Unix-based systems and Windows. ```bash mkdir my_openvcad_project cd my_openvcad_project # macOS / Linux python3 -m venv venv source venv/bin/activate # Windows python -m venv venv venv\Scripts\activate ``` -------------------------------- ### Manage Python Virtual Environments Source: https://matterassembly.org/OpenVCAD-Docs/v2/install.html Commands to create, activate, and deactivate virtual environments across different operating systems to isolate project dependencies. ```bash # macOS / Linux python3 -m venv venv source venv/bin/activate # Windows python -m venv venv venv\Scripts\activate ``` ```bash deactivate ``` -------------------------------- ### Verify OpenVCAD Installation Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/install.md.txt A Python snippet to verify that the OpenVCAD library is correctly installed by importing the module and printing the current version. ```python import pyvcad as pv print(pv.version()) ``` -------------------------------- ### Create a basic 3D object with OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/getting-started.md.txt Demonstrates the initialization of the pyvcad library and the creation of a simple 10mm cube using RectPrism. It includes rendering the object using the pyvcad_rendering module. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials center_point = pv.Vec3(0, 0, 0) dimensions = pv.Vec3(10, 10, 10) root = pv.RectPrism(center_point, dimensions, materials.id("red")) viz.Render(root, materials) ``` -------------------------------- ### Create a Simple Red Cube with OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html Generates a basic 10mm red cube centered at the origin using pyvcad. It imports necessary libraries, defines materials, and renders the object. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials center_point = pv.Vec3(0, 0, 0) dimensions = pv.Vec3(10, 10, 10) root = pv.RectPrism(center_point, dimensions, materials.id("red")) viz.Render(root, materials) ``` -------------------------------- ### Install OpenVCAD via pip Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/install.md.txt Installs the OpenVCAD package and its core dependencies using the Python package manager. This command is compatible with Windows, Linux, and macOS. ```bash pip install OpenVCAD ``` -------------------------------- ### Python Example: Linear Gradient Along X using FGrade Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/guides/math-expressions.md.txt Demonstrates how to create a linear gradient using the FGrade node in OpenVCAD. This example defines a transition from red to blue based on the x-coordinate, utilizing a math expression. ```python root = pv.FGrade( ["x/100 + 0.5", "-x/100 + 0.5"], [materials.id("red"), materials.id("blue")], False ) ``` -------------------------------- ### Perform CSG operations with OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/getting-started.md.txt Illustrates Constructive Solid Geometry operations including Union, Intersection, and Difference. These operations allow for the combination of basic geometric primitives to form complex shapes. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")) right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("red")) # Union root = pv.Union() root.add_child(left_sphere) root.add_child(right_sphere) # Intersection # root = pv.Intersection(False, [left_sphere, right_sphere]) # Difference # root = pv.Difference(left_sphere, right_sphere) viz.Render(root, materials) ``` -------------------------------- ### Initiate and Manage Export Process (Python) Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/export_frame.html Starts the export process by retrieving export options, validating them, and setting up the progress panel. It handles cases where a progress panel might not be implemented for a specific compiler. ```python def start_export(self): export_options = self.compiler_input_panel.get_export_options() # Check for file_path or output_directory if not export_options.get("file_path") and not export_options.get("output_directory"): wx.MessageBox("File path or output directory cannot be empty.", "Error", wx.OK | wx.ICON_ERROR) return False self.book.RemovePage(2) # Remove old progress panel new_progress_panel = self.compiler_selection_panel.get_selected_progress_panel(self.book, export_options) if new_progress_panel: self.progress_panel = new_progress_panel self.book.InsertPage(2, self.progress_panel, "Progress") self.progress_panel.start_export() return True else: # Fallback for compilers without a progress panel self.book.InsertPage(2, wx.Panel(self.book), "Progress") wx.MessageBox("This compiler does not have a progress panel implemented yet.", "Info", wx.OK | wx.ICON_INFORMATION) return False ``` -------------------------------- ### Basic Multi-material Union in OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html Demonstrates creating a multi-material object by uniting a red sphere and a blue sphere. The overlapping region defaults to the material of the first child added (red). ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")) right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("blue")) root = pv.Union() root.add_child(left_sphere) root.add_child(right_sphere) viz.Render(root, materials) ``` -------------------------------- ### GET /pyvcad_compilers/version Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad_compilers/overview.html Retrieves the current version string of the OpenVCAD software. ```APIDOC ## GET /pyvcad_compilers/version ### Description Returns the current version of the OpenVCAD library as a string. ### Method GET ### Endpoint pyvcad_compilers.version() ### Parameters None ### Request Example N/A ### Response #### Success Response (200) - **version** (string) - The version string of the OpenVCAD installation. #### Response Example { "version": "2.0.0" } ``` -------------------------------- ### Design multi-material 3D objects Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/getting-started.md.txt Shows how to assign different materials to geometric primitives within a single scene. The overlapping regions follow material priority rules based on the child order. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")) right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("blue")) root = pv.Union() root.add_child(left_sphere) root.add_child(right_sphere) viz.Render(root, materials) ``` -------------------------------- ### Define Build and Iso Events using ne.NewEvent() Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/vtk_pipeline_wx.html Defines various event types for build processes (started, finished, failed) and ISO (isoline) sampling and contouring using the ne.NewEvent() function. These events are crucial for asynchronous operations and progress reporting. ```python BuildStartedEvent, EVT_BUILD_STARTED = ne.NewEvent() BuildFinishedEvent, EVT_BUILD_FINISHED = ne.NewEvent() BuildFailedEvent, EVT_BUILD_FAILED = ne.NewEvent() IsoSampleEvent, EVT_ISO_SAMPLE = ne.NewEvent() IsoContourEvent, EVT_ISO_CONTOUR = ne.NewEvent() IsoColorEvent, EVT_ISO_COLOR = ne.NewEvent() VolSampleEvent, EVT_VOL_SAMPLE = ne.NewEvent() ``` -------------------------------- ### Create Blended Intersections with Intersection Node Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/getting-started.md.txt Demonstrates how to combine multiple material distributions using the Intersection node. By setting the first parameter to True, the overlapping regions are normalized into an equal blend of the child materials. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")) right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("blue")) root = pv.Intersection(True, [left_sphere, right_sphere]) viz.Render(root, materials) ``` -------------------------------- ### SurfaceMesh Transformations and Queries Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Illustrates common operations on a SurfaceMesh, including getting its bounding box, centering it, translating it, and retrieving its vertices and triangles. It also shows how to compute the signed distance to the mesh. ```C++ SurfaceMesh mesh("path/to/mesh.stl"); glm::vec3 min_bound, max_bound; std::tie(min_bound, max_bound) = mesh.bounding_box(); mesh.center(); mesh.translate({10.0f, 0.0f, 0.0f}); std::vector verts = mesh.vertices(); std::vector tris = mesh.triangles(); double distance = mesh.signed_distance(1.0, 2.0, 3.0); ``` -------------------------------- ### Initialize and Use MeshCompiler in Python Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad_compilers/brep.html Demonstrates how to instantiate the MeshCompiler with a root node and voxel settings, configure a progress callback, and execute the compilation process. ```python from pyvcad_compilers import MeshCompiler # Initialize the compiler compiler = MeshCompiler(root=my_node, voxel_size=(1.0, 1.0, 1.0), output_directory="./out", file_prefix="mesh_", num_iso_slices=10) # Set a progress callback def my_callback(progress): print(f"Progress: {progress}%") compiler.setProgressCallback(my_callback) # Compile the mesh compiler.compile() ``` -------------------------------- ### Deactivate Virtual Environment Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/install.md.txt Command to exit the active virtual environment and return to the system Python environment. ```bash deactivate ``` -------------------------------- ### Subtract Sphere with Difference in OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html Shows the Difference operation in OpenVCAD to subtract the right sphere from the left sphere. This creates a shape with a void where the second sphere was. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")) right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("red")) root = pv.Difference(left_sphere, right_sphere) viz.Render(root, materials) ``` -------------------------------- ### Intersect Two Spheres with OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html Illustrates the Intersection operation in OpenVCAD to find the shared volume of two overlapping red spheres. The `False` argument indicates a standard intersection. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")) right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("red")) root = pv.Intersection(False, [left_sphere, right_sphere]) viz.Render(root, materials) ``` -------------------------------- ### Initialize and Configure VTKRenderPipeline in Python Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad_rendering/vtk_pipeline_wx.html Demonstrates the instantiation of the VTKRenderPipeline class and basic configuration methods for scene rendering. This class is designed to integrate with wxPython windows for interactive 3D visualization. ```python from pyvcad_rendering.vtk_pipeline_wx import VTKRenderPipeline # Initialize the pipeline with a target window pipeline = VTKRenderPipeline(event_target=my_wx_window) # Configure scene appearance pipeline.set_background_color(0.1, 0.1, 0.1) pipeline.show_bounding_box(True) # Update the rendered object pipeline.update_vcad_object(vcad_obj, materials_list, reset_camera=True) # Capture output pipeline.take_screenshot("output.png") ``` -------------------------------- ### Combine Two Spheres with Union in OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html Demonstrates the Union operation in OpenVCAD to combine two overlapping red spheres into a single object. It sets up materials and renders the resulting shape. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")) right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("red")) root = pv.Union() root.add_child(left_sphere) root.add_child(right_sphere) viz.Render(root, materials) ``` -------------------------------- ### Initialize wxPython Menu and Bind Events Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/render_frame.html This snippet demonstrates the creation of a wxPython menu bar with several submenus (File, View, Object, Help). It also shows how to bind menu item events to corresponding handler functions. The code initializes menu items, sets default states (like checking 'Volumetric Blending'), and binds various actions such as toggling visibility, changing camera views, setting quality, and handling help options. ```python self.item_volumetric_blending = self.volume_menu.AppendCheckItem(wx.ID_ANY, "Volumetric Blending") self.item_volumetric_shading = self.volume_menu.AppendCheckItem(wx.ID_ANY, "Volumetric Shading") self.item_volumetric_blending.Check(True) # default enabled # Keep handle to the submenu item so we can enable/disable self.volume_menu_item = object_menu.AppendSubMenu(self.volume_menu, "Volumetric Options") self.volume_menu_item.Enable(False) menubar.Append(object_menu, "&Object") # ===== Help ===== help_menu = wx.Menu() self.item_about = help_menu.Append(wx.ID_ANY, "About") help_menu.AppendSeparator() self.item_wiki = help_menu.Append(wx.ID_ANY, "Wiki") self.item_docs = help_menu.Append(wx.ID_ANY, "Library Documentation") self.item_getting_started = help_menu.Append(wx.ID_ANY, "Getting Started") help_menu.AppendSeparator() self.item_report_bug = help_menu.Append(wx.ID_ANY, "Report a Bug") menubar.Append(help_menu, "&Help") self.SetMenuBar(menubar) # ----- Bind menu events ----- # File self.Bind(wx.EVT_MENU, self.on_screenshot, self.item_screenshot) # View self.Bind(wx.EVT_MENU, self.on_toggle_show_origin, self.item_show_origin) self.Bind(wx.EVT_MENU, self.on_toggle_ortho_projection, self.item_ortho_proj) self.Bind(wx.EVT_MENU, self.on_reset_camera, self.item_reset_camera) self.Bind(wx.EVT_MENU, self.on_set_top_view, self.item_top_view) self.Bind(wx.EVT_MENU, self.on_set_bottom_view, self.item_bottom_view) self.Bind(wx.EVT_MENU, self.on_set_side_view, self.item_side_view) self.Bind(wx.EVT_MENU, self.on_set_corner_view, self.item_corner_view) # Quality radio group → one handler, read which is checked self.Bind(wx.EVT_MENU, self._on_quality_any, self.item_quality_low) self.Bind(wx.EVT_MENU, self._on_quality_any, self.item_quality_medium) self.Bind(wx.EVT_MENU, self._on_quality_any, self.item_quality_high) self.Bind(wx.EVT_MENU, self._on_quality_any, self.item_quality_ultra) # Object → Mode radios self.Bind(wx.EVT_MENU, self._on_mode_any, self.item_iso_surface) self.Bind(wx.EVT_MENU, self._on_mode_any, self.item_volumetric) # Object toggles self.Bind(wx.EVT_MENU, self.on_toggle_show_bbox, self.item_show_bbox) self.Bind(wx.EVT_MENU, self.on_toggle_volumetric_blending, self.item_volumetric_blending) self.Bind(wx.EVT_MENU, self.on_toggle_volumetric_shading, self.item_volumetric_shading) # Help self.Bind(wx.EVT_MENU, self.on_about, self.item_about) self.Bind(wx.EVT_MENU, self.on_wiki, self.item_wiki) self.Bind(wx.EVT_MENU, self.on_docs, self.item_docs) self.Bind(wx.EVT_MENU, self.on_getting_started, self.item_getting_started) self.Bind(wx.EVT_MENU, self.on_report_bug, self.item_report_bug) self.Centre() self.Show() # Update if the OS theme changes while the app is running self.Bind(wx.EVT_SYS_COLOUR_CHANGED, self._on_sys_colour_changed) # Initial render self.render_pipeline.update_vcad_object(self.vcad_object, self.materials) # Apply background based on current system appearance self._apply_bg_from_system() ``` -------------------------------- ### Initialize and Compile DirectMaterialCompiler Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad_compilers/inkjet.html Shows how to set up the DirectMaterialCompiler to process material definitions and compile them to a specified output directory. ```python from pyvcad_compilers import DirectMaterialCompiler compiler = DirectMaterialCompiler(root, voxel_size, material_defs, "./out", "mat_", False, 0.0) compiler.setProgressCallback(lambda p: print(f"Progress: {p*100}%")) compiler.compile() ``` -------------------------------- ### SurfaceMesh Construction and Loading Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Demonstrates how to construct a SurfaceMesh object either by loading from a file path or by providing vertex and triangle data directly. It also shows the default constructor. ```C++ SurfaceMesh mesh; SurfaceMesh mesh_from_file("path/to/mesh.stl"); std::vector vertices = {{0,0,0}, {1,0,0}, {0,1,0}}; std::vector triangles = {{0,1,2}}; SurfaceMesh mesh_from_data(vertices, triangles); ``` -------------------------------- ### Initialize PolygonExtrude in pyvcad Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/leaves.html Demonstrates how to instantiate a PolygonExtrude object using either the default constructor for a unit square or a custom constructor for defined 3D vertices. ```python from libvcad import pyvcad as pv # Default constructor poly_default = pv.PolygonExtrude() # Custom constructor with vertices verts = [pv.Vec3(0,0,0), pv.Vec3(10,0,0), pv.Vec3(10,10,0), pv.Vec3(0,10,0)] poly_custom = pv.PolygonExtrude(verts, 5.0, False, 1) ``` -------------------------------- ### Blended Intersection with Multi-material in OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html Shows how to achieve a blended intersection of multi-material objects in OpenVCAD by setting the first argument of `Intersection` to `True`. The overlapping region becomes an equal blend of red and blue. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials radius = 5 left_sphere = pv.Sphere(pv.Vec3(-radius/2, 0, 0), radius, materials.id("red")), right_sphere = pv.Sphere(pv.Vec3(+radius/2, 0, 0), radius, materials.id("blue")), root = pv.Intersection(True, [left_sphere, right_sphere]) viz.Render(root, materials) ``` -------------------------------- ### Initialize wxPython Progress Dialog for Build Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/render_frame.html This function initializes and displays a wx.ProgressDialog for the rendering or build process. It dynamically sets the maximum value based on whether volumetric rendering is enabled. It also handles cases where the build might finish before the dialog is fully displayed, ensuring the dialog is properly managed. ```python [docs] def on_build_started(self, _=0): self._stop_finalizing_pulse() is_volumetric = self.render_pipeline.get_render_mode() == "volumetric" base_max = 100 if is_volumetric else 300 tail = max(1, getattr(self, "_progress_tail", 1)) self._progress_tail = tail maximum = base_max + tail # Reserve a slot so wx.PD_AUTO_HIDE waits for explicit finish # Reset monotonic tracker for a new build self._last_progress = 0 self._finalizing_shown = False self._build_finished_early = False # Max=300 for iso-surface (3 phases), 100 for volumetric (1 phase) self.progress_dialog = wx.ProgressDialog( "Rendering…", "Initializing…", maximum=maximum, parent=self, style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT ) # If the build finished while the dialog was being created (e.g. on Windows event loop pumping) if self._build_finished_early: self.progress_dialog.Destroy() self.progress_dialog = None return self.progress_dialog.Update(0, "Initializing…") ``` -------------------------------- ### Create complex geometry with nested CSG operations Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/getting-started.md.txt Demonstrates building a complex object by nesting multiple CSG operations, including rotations and boolean subtractions, to create a rounded cube with cylindrical holes. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials base_cylinder = pv.Cylinder(pv.Vec3(0,0,0), 2, 9, materials.id("gray")) root = pv.Difference( pv.Intersection(False, [ pv.RectPrism(pv.Vec3(0,0,0), pv.Vec3(8,8,8), materials.id("gray")), pv.Sphere(pv.Vec3(0,0,0), 5.5, materials.id("gray")) ]), pv.Union(False, [ base_cylinder, pv.Rotate(90,0,0, pv.Vec3(0,0,0), base_cylinder), pv.Rotate(0,90,0, pv.Vec3(0,0,0), base_cylinder) ]) ) viz.Render(root, materials) ``` -------------------------------- ### Prepare Sphere Node Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/tree.html Prepares a sphere node for evaluation by performing single-run operations. Requires voxel size, interior bandwidth, and exterior bandwidth as parameters. ```python from libvcad import pyvcad as pv sphere = pv.Sphere(pv.Vec3(0,0,0), 2, 2) sphere.prepare(pv.vec3(1, 1, 1), 0.1, 0.1) ``` -------------------------------- ### Initialize FullColorCompiler Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-compilers-inkjet.html Constructor for the FullColorCompiler class, which processes voxel grids into full-color output files. It requires a root node, voxel dimensions, attribute definitions, and palette information. ```cpp FullColorCompiler(const std::shared_ptr &m_root, vec3 voxel_size, const std::string &attribute_def_file_path, const std::string &output_directory, const std::string &file_prefix, const std::vector &color_palette, bool use_transparency); ``` -------------------------------- ### Create Complex CSG Shape in OpenVCAD Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html Combines multiple CSG operations (Difference, Intersection, Union) to create a complex shape: a rounded cube with cylindrical holes. It utilizes various OpenVCAD primitives and transformations. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials base_cylinder = pv.Cylinder(pv.Vec3(0,0,0), 2, 9, materials.id("gray")) root = pv.Difference( pv.Intersection(False, [ pv.RectPrism(pv.Vec3(0,0,0), pv.Vec3(8,8,8), materials.id("gray")), pv.Sphere(pv.Vec3(0,0,0), 5.5, materials.id("gray")) ]), pv.Union(False, [ base_cylinder, pv.Rotate(90,0,0, pv.Vec3(0,0,0), base_cylinder), pv.Rotate(0,90,0, pv.Vec3(0,0,0), base_cylinder) ]) ) viz.Render(root, materials) ``` -------------------------------- ### Compiler Selection UI in Python Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/export_frame.html Implements a panel for selecting different export compilers. It displays a list of available compilers, their descriptions, and allows the user to choose one. Dependencies include wxPython and pyvcad_rendering.compiler_input_ui. ```python import wx import os import sys import subprocess import pyvcad_rendering.compiler_input_ui as compiler_ui [docs] class CompilerSelectionPanel(wx.Panel): [docs] def __init__(self, parent): super().__init__(parent) self.compilers = [ "GCVF Inkjet (.gcvf)", "Direct Material Inkjet (PNG Stack)", # "Color Inkjet (PNG Stack)", "Myerson Inkjet (Bitmap Stack)", "Meshes (.STL)", "Finite Element Mesh (.INP)", "Vat Photo (Bitmap Stack)" ] self.compiler_map = { "GCVF Inkjet (.gcvf)": (compiler_ui.GCVFInkjetPanel, compiler_ui.GCVFInkjetProgressPanel), "Direct Material Inkjet (PNG Stack)": (compiler_ui.DirectMaterialInkjetPanel, compiler_ui.DirectMaterialInkjetProgressPanel), # "Color Inkjet (PNG Stack)": (compiler_ui.ColorInkjetPanel, None), "Myerson Inkjet (Bitmap Stack)": (compiler_ui.MyersonInkjetPanel, compiler_ui.MyersonInkjetProgressPanel), "Meshes (.STL)": (compiler_ui.MeshesPanel, compiler_ui.MeshesProgressPanel), "Finite Element Mesh (.INP)": (compiler_ui.FiniteElementMeshPanel, compiler_ui.FiniteElementMeshProgressPanel), "Vat Photo (Bitmap Stack)": (compiler_ui.VatPhotoPanel, compiler_ui.VatPhotoProgressPanel) } self.compiler_descriptions = { "GCVF Inkjet (.gcvf)": "Description for GCVF Inkjet (.gcvf)", "Direct Material Inkjet (PNG Stack)": "Description for Direct Material Inkjet (PNG Stack)", "Color Inkjet (PNG Stack)": "Description for Color Inkjet (PNG Stack)", "Myerson Inkjet (Bitmap Stack)": "Description for Myerson Inkjet (Bitmap Stack)", "Meshes (.STL)": "Description for Meshes (.STL)", "Finite Element Mesh (.INP)": "Description for Finite Element Mesh (.INP)", "Vat Photo (Bitmap Stack)": "Description for Vat Photo (Bitmap Stack)" } sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(wx.StaticText(self, label="Select a compiler:"), 0, wx.ALL, 5) self.compiler_choice = wx.Choice(self, choices=self.compilers) sizer.Add(self.compiler_choice, 0, wx.ALL | wx.EXPAND, 5) self.description_text = wx.StaticText(self, label="") sizer.Add(self.description_text, 1, wx.ALL | wx.EXPAND, 5) self.SetSizer(sizer) self.compiler_choice.Bind(wx.EVT_CHOICE, self.on_compiler_select) self.compiler_choice.SetSelection(0) self.on_compiler_select(None) [docs] def on_compiler_select(self, event): selection = self.compiler_choice.GetStringSelection() description = self.compiler_descriptions.get(selection, "") self.description_text.SetLabel(description) self.GetParent().Layout() [docs] def get_selected_compiler_panel(self, parent, root, materials): selection = self.compiler_choice.GetStringSelection() panel_classes = self.compiler_map.get(selection) if panel_classes and panel_classes[0]: return panel_classes[0](parent, root, materials) return None [docs] def get_selected_progress_panel(self, parent, export_options): selection = self.compiler_choice.GetStringSelection() panel_classes = self.compiler_map.get(selection) if panel_classes and panel_classes[1]: return panel_classes[1](parent, export_options) return None ``` -------------------------------- ### Implement Spatial Gradients with FGrade Source: https://matterassembly.org/OpenVCAD-Docs/v2/_sources/getting-started.md.txt Uses the FGrade node to create multi-material spatial gradients based on mathematical expressions. The function defines volume fractions for materials that must sum to 1 at any given point. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials bar = pv.RectPrism(pv.Vec3(0,0,0), pv.Vec3(100,50,10), materials.id("gray")) root = pv.FGrade(["x/100 + 0.5", "-x/100 + 0.5"], [materials.id("red"), materials.id("blue")], False) root.set_child(bar) viz.Render(root, materials) # Export the object for 3D printing or simulation viz.Export(root, materials) ``` -------------------------------- ### Initialize RenderFrame GUI with VTK Interactor Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/render_frame.html Initializes the main rendering window, embedding a VTK render window interactor within a wxPython panel. It sets up the rendering pipeline and binds various event listeners for build progress and UI interactions. ```python class RenderFrame(wx.Frame): def __init__(self, vcad_object, materials, parent=None, title="OpenVCAD Renderer"): super().__init__(parent, title=title, size=(1000, 700)) panel = wx.Panel(self) self.vtk_widget = wxVTKRenderWindowInteractor.wxVTKRenderWindowInteractor(panel, -1) self.render_pipeline = VTKRenderPipeline( event_target=self, use_default_interaction=True, render_window=self.vtk_widget.GetRenderWindow(), ) # Event bindings for build progress self.Bind(EVT_BUILD_STARTED, lambda e: self.on_build_started(e.generation)) self.Bind(EVT_ISO_SAMPLE, lambda e: self.on_iso_sample_progress(int(e.progress))) ``` -------------------------------- ### Initialize and Render vcad Objects using wxPython Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/render.html The render function initializes a wx.App instance and launches a RenderFrame with the provided vcad_object and materials. It blocks execution until the main loop is terminated by the user. ```python import sys import wx from .render_frame import RenderFrame def render(vcad_object, materials): app = wx.App(False) app.frame = RenderFrame(vcad_object, materials) app.MainLoop() def Render(vcad_object, materials): render(vcad_object, materials) __all__ = ["render", "Render"] ``` -------------------------------- ### Create Linear Material Gradient with FGrade (Python) Source: https://matterassembly.org/OpenVCAD-Docs/v2/getting-started.html This snippet demonstrates how to create a linear spatial gradient between two materials (red and blue) using the FGrade node in pyvcad. It defines a rectangular bar and applies a gradient based on the 'x' coordinate. The resulting object is then rendered and exported. ```python import pyvcad as pv import pyvcad_rendering as viz materials = pv.default_materials bar = pv.RectPrism(pv.Vec3(0,0,0), pv.Vec3(100,50,10), materials.id("gray")) root = pv.FGrade(["x/100 + 0.5", "-x/100 + 0.5"], [materials.id("red"), materials.id("blue")], False) root.set_child(bar) viz.Render(root, materials) # Export the object for 3D printing or simulation viz.Export(root, materials) ``` -------------------------------- ### Initialize SupportAnalyzer in pyvcad Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/analysis.html Constructs a SupportAnalyzer object to analyze a 3D model for necessary support structures. It requires the input model, voxel size, and an optional material ID for the supports. ```python class pyvcad.SupportAnalyzer: def __init__(self, input_model: pyvcad.pyvcad.Node, voxel_size: pyvcad.pyvcad.Vec3, material_id: int = 1): # Constructor for SupportAnalyzer. # Parameters: # input_model (Node): The input 3D model to analyze. # voxel_size (glm.vec3): The size of each voxel in mm. # material_id (int, optional): The material ID to use for support structures. Default is 1. ``` -------------------------------- ### Create Strut Primitive (Python) Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/leaves.html Constructs a Strut primitive, defined by its start and end points, radius, and material ID. Requires a Vec3 object for both start and end points. ```python from libvcad import pyvcad as pv start = pv.vec3(0, 0, 0) end = pv.vec3(1, 1, 1) strut = pv.Strut(start, end, 0.5, 1) ``` -------------------------------- ### Initialize and Compile GCVFExporter Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad_compilers/inkjet.html Demonstrates the initialization of a GCVFExporter with geometry and material parameters, followed by the compilation process and setting a progress callback. ```python from pyvcad_compilers import GCVFExporter exporter = GCVFExporter(root, voxel_size, material_defs, "output.gcvf", True, 0.5) exporter.setProgressCallback(lambda phase, progress: print(f"Phase: {phase}, Progress: {progress}")) exporter.compile() ``` -------------------------------- ### GET /tetrahedron/volume Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Computes the volume of the tetrahedron in cubic millimeters. ```APIDOC ## GET /tetrahedron/volume ### Description Returns the volume of the tetrahedron. ### Method GET ### Endpoint /tetrahedron/volume ### Response #### Success Response (200) - **volume** (double) - The volume of the tetrahedron in mm^3. #### Response Example { "volume": 12.5 } ``` -------------------------------- ### GET /tetrahedral_mesh/stats Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Retrieves metadata and structural statistics for a tetrahedral mesh. ```APIDOC ## GET /tetrahedral_mesh/stats ### Description Returns the number of nodes, elements, and degrees of freedom for the mesh. ### Method GET ### Endpoint /tetrahedral_mesh/stats ### Response #### Success Response (200) - **number_of_nodes** (size_t) - Total nodes in mesh - **number_of_elements** (size_t) - Total elements in mesh - **degree_of_freedom** (size_t) - Degrees of freedom #### Response Example { "number_of_nodes": 1024, "number_of_elements": 512, "degree_of_freedom": 1024 } ``` -------------------------------- ### Random Number Generation Utility Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-utils.html A singleton-based utility class for generating random integers and doubles, as well as performing weighted sampling from distributions. ```cpp class Random { public: double random_double(double min, double max); int random_int(int min, int max); void reseed(int seed); static Random *getInstance(); static size_t WeightedMaterialSample(const std::unordered_map &materials_with_weights); static size_t WeightedSample(const std::vector &weights); }; ``` -------------------------------- ### GET /tetrahedron/barycentric_coordinates Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Computes the barycentric coordinates of a point within the tetrahedron. ```APIDOC ## GET /tetrahedron/barycentric_coordinates ### Description Calculates the barycentric coordinates of a given point in space relative to the tetrahedron. ### Method GET ### Endpoint /tetrahedron/barycentric_coordinates ### Parameters #### Query Parameters - **point** (glm::vec3) - Required - The point in space to compute coordinates for. ### Request Example { "point": [0.5, 0.5, 0.5] } ### Response #### Success Response (200) - **coordinates** (glm::vec4) - The barycentric coordinates of the point. #### Response Example { "coordinates": [0.25, 0.25, 0.25, 0.25] } ``` -------------------------------- ### Get Tetrahedron Point A Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Retrieves the first vertex (point) of the tetrahedron. ```cpp inline glm::vec3 a() const# ``` -------------------------------- ### Initialize VTKRenderPipeline with Rendering Resources Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/vtk_pipeline_wx.html Initializes the VTKRenderPipeline class, setting up essential rendering resources like the renderer, render window, and interactor style. It also configures various rendering states and initializes variables for asynchronous operations. ```python class VTKRenderPipeline: def __init__(self, event_target: wx.Window, use_default_interaction=True, render_window=None): self.event_target = event_target # Rendering resources self.renderer = vtkRenderer() self.render_window = render_window or vtkRenderWindow() self.render_window.AddRenderer(self.renderer) # Interactor style (GUI thread only) if use_default_interaction: interactor = self.render_window.GetInteractor() if interactor is not None: style = vtkInteractorStyleTrackballCamera() interactor.SetInteractorStyle(style) self.corner_axis_widget = self._create_corner_axis_widget() # Render state self.render_mode = "iso_surface" self.quality_profile = "low" self.use_orthogonal_projection = False self.use_volume_shading = False self.use_volume_blending = True self._show_bounding_box = False self.bbox_actor = None self.min_pt_text = None self.max_pt_text = None self._show_origin = False self.origin_actor = None self.vcad_object = None self.materials = None self.voxel_size = None self.current_volume = None self.current_iso_surface = None # Async build state self._gen = 0 self._pending_reset_camera = False self._worker_thread = None self._worker_lock = threading.Lock() # Default progress callbacks -> post wx events self.iso_surface_sample_progress_callback = lambda p: self._post(IsoSampleEvent, progress=float(p)) self.iso_surface_contouring_progress_callback = lambda p: self._post(IsoContourEvent, progress=float(p)) self.iso_surface_coloring_progress_callback = lambda p: self._post(IsoColorEvent, progress=float(p)) self.volume_sample_progress_callback = lambda p: self._post(VolSampleEvent, progress=float(p)) ``` -------------------------------- ### Get Tetrahedron Point B Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Retrieves the second vertex (point) of the tetrahedron. ```cpp inline glm::vec3 b() const# ``` -------------------------------- ### Populate Voxels with Equation (Python) Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/leaves.html Populates an existing Voxels grid with data generated from a mathematical equation. Requires the equation string, grid boundaries (min and max coordinates), and voxel size. ```python from libvcad import pyvcad as pv voxels.populate_with_equation('x^2 + y^2 + z^2 - 1', pv.vec3(0, 0, 0), pv.vec3(1, 1, 1), pv.vec3(0.1, 0.1, 0.1)) ``` -------------------------------- ### Get Tetrahedron Value A Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Retrieves the value associated with the first vertex of the tetrahedron. ```cpp inline T a_val() const# ``` -------------------------------- ### Manage Render Pipeline Configuration Source: https://matterassembly.org/OpenVCAD-Docs/v2/_modules/pyvcad_rendering/render_frame.html Methods to interface with the render pipeline, allowing users to toggle camera projections, bounding boxes, and quality settings via GUI events. ```python def on_toggle_ortho_projection(self, _evt=None): checked = self.item_ortho_proj.IsChecked() self.render_pipeline.enable_orthogonal_projection(checked) def on_quality_changed(self, quality: str): self.render_pipeline.set_quality_profile(quality) def on_toggle_show_bbox(self, _evt=None): checked = self.item_show_bbox.IsChecked() self.render_pipeline.show_bounding_box(checked) ``` -------------------------------- ### Get Tetrahedron Value B Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-3d.html Retrieves the value associated with the second vertex of the tetrahedron. ```cpp inline T b_val() const# ``` -------------------------------- ### POST /PolygonExtrude Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/leaves.html Initializes a PolygonExtrude object to create extruded 3D geometry from planar vertices. ```APIDOC ## POST /PolygonExtrude ### Description Creates an extruded polygon from a sequence of coplanar 3D vertices. Supports symmetric extrusion and material assignment. ### Method POST ### Endpoint /PolygonExtrude ### Parameters #### Request Body - **vertices** (list[Vec3]) - Required - The vertices of the planar polygon (minimum 3, must be coplanar). - **height** (float) - Required - The extrusion distance along the polygon normal. - **symmetric** (bool) - Optional - If True, extrudes height/2 on each side of the polygon plane. - **material** (int) - Optional - The material id of the PolygonExtrude. ### Request Example { "vertices": [{"x": 0, "y": 0, "z": 0}, {"x": 10, "y": 0, "z": 0}, {"x": 10, "y": 10, "z": 0}, {"x": 0, "y": 10, "z": 0}], "height": 5.0, "symmetric": false, "material": 1 } ### Response #### Success Response (200) - **status** (string) - Confirmation of object initialization. #### Response Example { "status": "success", "object": "PolygonExtrude" } ``` -------------------------------- ### Clone Node Instance (C++) Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-tree-composition.html Clones a node and returns a new instance. It's more efficient to call this after prepare() as it allows copying from memory instead of re-reading from disk. prepare() must be called separately on each clone. ```cpp virtual std::shared_ptr clone() override# Clones the node and returns a new instance of the node. Note This may be called before or after prepare() is called, however it is always more efficient to call it after. This is because the prepare() function must be called on all clones of the node separately. If you call prepare() first and then clone the node, the clone() operation will copy from memory instead of re-reading from disk. Returns: A new instance of the node ``` ```cpp virtual std::shared_ptr clone() override# Clones the node and returns a new instance of the node. Note This may be called before or after prepare() is called, however it is always more efficient to call it after. This is because the prepare() function must be called on all clones of the node separately. If you call prepare() first and then clone the node, the clone() operation will copy from memory instead of re-reading from disk. Returns: A new instance of the node ``` -------------------------------- ### Get Sphere Type Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/tree.html Returns the type of the sphere node as a string. For a basic sphere, this is typically 'leaf'. ```python from libvcad import pyvcad as pv sphere = pv.Sphere() node_type = sphere.type() # Should return 'leaf' ``` -------------------------------- ### Populate Voxel Grid with PNG Stack Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/leaves.html Populates a voxel grid using a sequence of PNG files from a specified directory. It maps pixel values to material definitions based on the provided voxel size and coordinate bounds. ```python from libvcad import pyvcad as pv voxels.populate_with_png_stack('path/to/png_stack', pv.vec3(0, 0, 0), pv.vec3(0.1, 0.1, 0.1)) ``` -------------------------------- ### Polyline2: Get Points Source: https://matterassembly.org/OpenVCAD-Docs/v2/cpp-api/libvcad-geometry-2d.html Retrieves the sequence of points defining the Polyline2 object. Returns a std::vector of Point_2 objects. ```cpp std::vector points() const# Returns the points of the polyline. Returns: The points of the polyline. ``` -------------------------------- ### Strut Constructor Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/leaves.html Constructs a Strut object representing a geometric strut with specified start and end points, radius, and material ID. ```APIDOC ## Strut Constructor ### Description Constructs a Strut object representing a geometric strut with specified start and end points, radius, and material ID. ### Method __init__ ### Parameters - `start` (vec3) - The start point of the strut. - `end` (vec3) - The end point of the strut. - `radius` (double) - The radius of the strut. - `material` (uint8_t) - The material ID for the strut (optional, defaults to 1). ### Request Example ```python >>> from libvcad import pyvcad as pv >>> start = pv.vec3(0, 0, 0) >>> end = pv.vec3(1, 1, 1) >>> strut = pv.Strut(start, end, 0.5, 1) ``` ``` -------------------------------- ### Get Unary Node Child Source: https://matterassembly.org/OpenVCAD-Docs/v2/python-api/pyvcad/tree.html Retrieves the single child node of a Unary node. This is used for nodes that have exactly one child. ```python from libvcad import pyvcad as pv # Assuming 'unary_node' is an instance of pyvcad.Unary child_node = unary_node.child() ```