### Install Trimesh with 'easy' Dependencies Source: https://github.com/mikedh/trimesh/blob/main/docs/content/install.md Install trimesh with the 'easy' extra to include common soft dependencies. This is recommended for a smoother installation experience on most systems. ```bash pip install trimesh[easy] ``` -------------------------------- ### Basic Trimesh Installation Source: https://github.com/mikedh/trimesh/blob/main/docs/content/install.md Install trimesh with pip for basic functionality. This installs numpy as the only hard dependency. ```bash pip install trimesh ``` -------------------------------- ### Install Trimesh via Pip in Dockerfile Source: https://github.com/mikedh/trimesh/blob/main/docs/content/docker.md Use a first-party Python base image and install Trimesh with optional dependencies using pip. ```dockerfile FROM python:3.11-slim-bullseye RUN pip install trimesh[easy] ``` -------------------------------- ### Install Trimesh using Conda Source: https://github.com/mikedh/trimesh/blob/main/docs/content/install.md Install trimesh from the conda-forge channel. This is an alternative installation method for users who prefer conda environments. ```bash conda install -c conda-forge trimesh ``` -------------------------------- ### Clone Fork and Install Trimesh Editable Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Installs Trimesh in an editable mode after cloning a fork of the repository. This allows for direct modification and testing of the library's code. ```bash # you probably want to clone your fork git clone git@github.com:mikedh/trimesh.git # do an editable install so you can experiment cd trimesh pip install -e .[easy,test] ``` -------------------------------- ### Import Libraries and Create Mesh Source: https://github.com/mikedh/trimesh/blob/main/examples/curvature.ipynb Imports necessary libraries and creates an icosphere mesh for curvature calculations. Ensure trimesh and matplotlib are installed. ```python import matplotlib.pyplot as plt import numpy as np import trimesh from trimesh.curvature import ( discrete_gaussian_curvature_measure, discrete_mean_curvature_measure, sphere_ball_intersection, ) %matplotlib inline mesh = trimesh.creation.icosphere() ``` -------------------------------- ### Define Start and End Vertices Source: https://github.com/mikedh/trimesh/blob/main/examples/shortest.ipynb Selects arbitrary start and end vertex indices for the shortest path calculation. ```python # arbitrary indices of mesh.vertices to test with start = 0 end = int(len(mesh.vertices) / 2.0) ``` -------------------------------- ### Import NumPy and Trimesh Source: https://github.com/mikedh/trimesh/blob/main/examples/nearest.ipynb Imports the necessary libraries, NumPy for numerical operations and Trimesh for 3D mesh processing. This is a standard setup for most Trimesh operations. ```python import numpy as np import trimesh ``` -------------------------------- ### Define Ray Origins and Directions Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Defines the starting points (origins) and directions for the rays that will be used in the intersection query. ```python # create some rays ray_origins = np.array([[0, 0, -3], [2, 2, -3]]) ray_directions = np.array([[0, 0, 1], [0, 0, 1]]) ``` -------------------------------- ### Calculate Shortest Path Source: https://github.com/mikedh/trimesh/blob/main/examples/shortest.ipynb Computes the shortest path between the start and end vertices using the 'length' attribute as the edge weight. ```python # run the shortest path query using length for edge weight path = nx.shortest_path(g, source=start, target=end, weight="length") ``` -------------------------------- ### Get Mesh Moment of Inertia Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Calculate the moment of inertia tensor for the mesh, which describes its resistance to rotational acceleration. ```python # what's the moment of inertia for the mesh? mesh.moment_inertia ``` -------------------------------- ### Get Unique Edges and Lengths Source: https://github.com/mikedh/trimesh/blob/main/examples/shortest.ipynb Extracts the unique edges and their corresponding lengths from the mesh. ```python # edges without duplication edges = mesh.edges_unique ``` ```python # the actual length of each unique edge length = mesh.edges_unique_length ``` -------------------------------- ### Get Scene Bounds Corners Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Retrieve the corner points of the scene's bounding box, used for camera positioning. ```python # Get the bounds corners for the camera transform corners = scene.bounds_corners ``` -------------------------------- ### Get Oriented Bounding Box Extents Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Retrieve the extents of the mesh's minimum volume oriented bounding box. ```python # a minimum volume oriented bounding box is available mesh.bounding_box_oriented.primitive.extents ``` -------------------------------- ### Get Mesh Euler Number Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Retrieve the Euler number (V - E + F) of the mesh, which can indicate topological properties. ```python # what's the euler number for the mesh? mesh.euler_number ``` -------------------------------- ### Get Oriented Bounding Box Transform Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Retrieve the transformation matrix for the mesh's minimum volume oriented bounding box. ```python mesh.bounding_box_oriented.primitive.transform ``` -------------------------------- ### Get Axis-Aligned Bounding Box Extents Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Retrieve the extents (width, height, depth) of the mesh's axis-aligned bounding box. ```python # an axis aligned bounding box is available mesh.bounding_box.primitive.extents ``` -------------------------------- ### Build and Run a Docker Image Source: https://github.com/mikedh/trimesh/blob/main/docs/content/docker.md Commands to build a Docker image from the current directory and run it. ```bash docker build . -t example docker run -t example ``` -------------------------------- ### Fetch Viewer Files Source: https://github.com/mikedh/trimesh/blob/main/helpers/notebook_viewer/README.md Run this bash command to fetch the necessary files for the Trimesh notebook viewer. ```bash bash update.bash ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Sets up a Python virtual environment using the `venv` module. This is a common first step for development to isolate project dependencies. ```bash # create the venv python -m venv ~/venv # on linux this will use this venv # every time you open a new terminal echo "source ~/venv/bin/activate" >> ~/.bashrc ``` -------------------------------- ### Create a Scene Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Initialize a trimesh Scene object to hold and render 3D geometry. ```python # Create a Scene scene = trimesh.Scene() ``` -------------------------------- ### Build Trimesh Docker Image with BuildKit Source: https://github.com/mikedh/trimesh/blob/main/docs/content/docker.md Build a specific target ('output') of the Trimesh Docker image using BuildKit for a cleaner final image. ```bash DOCKER_BUILDKIT=1 docker build --target output -t trimesh/trimesh:latest . ``` -------------------------------- ### Use Prebuilt Trimesh Docker Image Source: https://github.com/mikedh/trimesh/blob/main/docs/content/docker.md Leverage pre-built Trimesh Docker images which include demanding dependencies like embree. The working directory is set to /home/user and runs as a non-root user. ```dockerfile FROM trimesh/trimesh:latest COPY requirements.txt . RUN pip install -r requirements.txt COPY app.py . CMD python app.py ``` -------------------------------- ### Create a Basic Trimesh Object Source: https://github.com/mikedh/trimesh/blob/main/README.md Demonstrates creating a Trimesh object from vertex and face data. By default, Trimesh performs light processing to clean up the mesh. ```python import numpy as np import trimesh # attach to logger so trimesh messages will be printed to console trimesh.util.attach_to_log() # mesh objects can be created from existing faces and vertex data mesh = trimesh.Trimesh(vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]], faces=[[0, 1, 2]]) ``` -------------------------------- ### Import Trimesh and Math Libraries Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Import necessary libraries for mesh manipulation and mathematical operations. ```python import math import trimesh ``` -------------------------------- ### Create Visualization Scene Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Constructs a Trimesh scene containing the mesh and the ray visualization paths. ```python # create a visualization scene with rays, hits, and mesh scene = trimesh.Scene([mesh, ray_visualize]) ``` -------------------------------- ### Import Trimesh Library Source: https://github.com/mikedh/trimesh/blob/main/examples/texture.ipynb Import the trimesh library to access its functionalities. This is a standard first step for using the library. ```python import trimesh ``` -------------------------------- ### Show Visualization Scene Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Displays the created Trimesh scene, allowing interactive viewing of the mesh, rays, and intersection points. ```python # show the visualization scene.show() ``` -------------------------------- ### Build Docker Image Source: https://github.com/mikedh/trimesh/blob/main/examples/docker/render/README.md Build the Docker image using the Dockerfile in the current directory. This image is configured for rendering tasks. ```docker docker build -t renderworker . ``` -------------------------------- ### Import Libraries Source: https://github.com/mikedh/trimesh/blob/main/examples/shortest.ipynb Imports the necessary libraries, NetworkX for graph operations and Trimesh for mesh handling. ```python import networkx as nx import trimesh ``` -------------------------------- ### Create Sphere Mesh Source: https://github.com/mikedh/trimesh/blob/main/examples/shortest.ipynb Initializes a primitive sphere mesh using Trimesh. ```python # test on a sphere mesh mesh = trimesh.primitives.Sphere() ``` -------------------------------- ### Render Scene to PNG Bytes Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Render the configured scene into PNG image data stored as bytes. ```python # Render of scene as a PNG bytes png = scene.save_image() ``` -------------------------------- ### Makefile Targets for Trimesh Docker Images Source: https://github.com/mikedh/trimesh/blob/main/docs/content/docker.md Utilize the Makefile for common Docker image building tasks, including building, testing, and generating documentation. ```makefile # will list the available options make help # will build and tag a `trimesh/trimesh:latest` image # and also tag it with semantic version and git hash make build # will build trimesh images and then in a different # build stage install the testing requirements and # run all of trimesh's unit tests inside the image make test # will build trimesh's docs inside the image and then # eject the results into the `./html` directory make docs ``` -------------------------------- ### Load Mesh from File Source: https://github.com/mikedh/trimesh/blob/main/README.md Loads a mesh from a file. For formats like GLB that can contain multiple meshes and instances, `trimesh.load_mesh` concatenates them. Use `trimesh.load_scene` to preserve instance information. ```python mesh = trimesh.load_mesh('models/CesiumMilkTruck.glb') ``` -------------------------------- ### Display Mesh Preview Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Show a preview of the loaded mesh. This can be used in a terminal or an inline notebook environment. ```python # preview mesh in a pyglet window from a terminal, or inline in a notebook mesh.show() ``` -------------------------------- ### Verify Python and Pip Environment Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Confirms that the correct virtual environment is active by checking the paths for `python` and `pip`. This ensures that development is happening within the isolated environment. ```bash mikedh@orion:trimesh$ which python /home/mikedh/venv/bin/python mikedh@orion:trimesh$ which pip /home/mikedh/venv/bin/pip ``` -------------------------------- ### Run Docker Container for Rendering Source: https://github.com/mikedh/trimesh/blob/main/examples/docker/render/README.md Execute the Docker container to perform rendering. The `-v` flag mounts the current directory to `/output` inside the container, allowing output files to be saved locally. The container will run the rendering process and save the output. ```docker docker run -v `pwd`:/output renderworker ``` -------------------------------- ### Visualize Path and Mesh Source: https://github.com/mikedh/trimesh/blob/main/examples/shortest.ipynb Creates a visual representation of the shortest path on the mesh and displays it. ```python # VISUALIZE RESULT # make the sphere white mesh.visual.face_colors = [255, 255, 255, 255] # Path3D with the path between the points path_visual = trimesh.load_path(mesh.vertices[path]) ``` ```python # create a scene with the mesh, path, and points scene = trimesh.Scene([path_visual, mesh]) ``` ```python scene.show() ``` -------------------------------- ### Compile Viewer Artifacts Source: https://github.com/mikedh/trimesh/blob/main/helpers/notebook_viewer/README.md Execute this Python script after editing the viewer files to create and minify the template JSON blob. ```python python compile.py ``` -------------------------------- ### Compare Bounding Volumes Source: https://github.com/mikedh/trimesh/blob/main/README.md Prints the volumes of the oriented bounding box, oriented bounding cylinder, and bounding sphere for the mesh. ```python print(mesh.bounding_box_oriented.volume, mesh.bounding_cylinder.volume, mesh.bounding_sphere.volume) ``` -------------------------------- ### Visualize Points and Closest Points Source: https://github.com/mikedh/trimesh/blob/main/examples/nearest.ipynb Creates PointCloud objects for the original sampled points and their corresponding closest points on the mesh. Assigns random, unique colors to each point pair for visualization and displays them in a Trimesh scene. ```python # create a PointCloud object out of each (n,3) list of points cloud_original = trimesh.points.PointCloud(points) cloud_close = trimesh.points.PointCloud(closest_points) # create a unique color for each point cloud_colors = np.array([trimesh.visual.random_color() for i in points]) # set the colors on the random point and its nearest point to be the same cloud_original.vertices_color = cloud_colors cloud_close.vertices_color = cloud_colors # create a scene containing the mesh and two sets of points scene = trimesh.Scene([mesh, cloud_original, cloud_close]) # show the scene we are using scene.show() ``` -------------------------------- ### Load Mesh from File Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Load a mesh from a file path. Use `process=False` to disable automatic processing and keep raw data intact. ```python # load a file by name or from a buffer mesh = trimesh.load_mesh("../models/featuretype.STL") # to keep the raw data intact, disable any automatic processing # mesh = trimesh.load_mesh('../models/featuretype.STL', process=False) ``` -------------------------------- ### Load a 3D Mesh File Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Load a 3D model from a specified file path. Ensure the file exists at the given location. ```python # load a file by name mesh = trimesh.load_mesh("../models/featuretype.STL") ``` -------------------------------- ### Load Mesh with Texture Source: https://github.com/mikedh/trimesh/blob/main/examples/texture.ipynb Load a mesh file, such as an OBJ file, which may contain UV coordinates and texture information. Ensure the model path is correct. ```python mesh = trimesh.load("../models/fuze.obj") ``` -------------------------------- ### Efficient Array Formatting with String Joins Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Demonstrates performance differences between using iterator joining with giant format strings versus looping and appending for formatting array data. The giant format string approach is significantly faster. ```python In [15]: %timeit '\n'.join('{}/{}/{}'.format(*row) for row in array) 10 loops, best of 3: 60.3 ms per loop ``` ```python In [16]: %timeit ('{}/{}/{}\n' * len(array))[:-1].format(*array.flatten()) 10 loops, best of 3: 34.3 ms per loop ``` -------------------------------- ### Create Trimesh Without Processing Source: https://github.com/mikedh/trimesh/blob/main/README.md Shows how to create a Trimesh object without applying default processing like NaN removal or vertex merging. Use `process=False` to disable this. ```python mesh = trimesh.Trimesh(vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]], faces=[[0, 1, 2]], process=False) ``` -------------------------------- ### Create Ray Visualization Path Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Generates a `Path3D` object from the ray origins and extended directions for visualization purposes. ```python # stack rays into line segments for visualization as Path3D ray_visualize = trimesh.load_path( np.hstack((ray_origins, ray_origins + ray_directions * 5.0)).reshape(-1, 2, 3) ) ``` -------------------------------- ### Create Icosphere Mesh Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Creates a basic icosphere mesh primitive to be used for ray intersection tests. ```python # test on a sphere primitive mesh = trimesh.creation.icosphere() ``` -------------------------------- ### Run Ruff for Linting and Formatting Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Executes `ruff` commands to check code for linting issues and automatically fix them, as well as format the code according to project standards. ```bash ruff check --fix ruff format ``` -------------------------------- ### Save Rendered Image to File Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Write the generated PNG image bytes to a file. Ensure the directory exists for saving. ```python # Write the bytes to file with open("../models/featuretype.png", "wb") as f: f.write(png) f.close() ``` -------------------------------- ### Load Mesh Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Loads a 3D mesh from a file. Supports various file formats including STL. Ensure the file path is correct. ```python import numpy as np from shapely.geometry import LineString import trimesh %pylab inline %config InlineBackend.figure_format = 'svg' # load the mesh from filename # file objects are also supported mesh = trimesh.load_mesh("../models/featuretype.STL") ``` -------------------------------- ### Compare Bounding Volumes Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Calculate and compare the volumes of the oriented bounding box, bounding cylinder, and bounding sphere for the mesh. These represent the minimum volume versions. ```python # bounding spheres and bounding cylinders of meshes are also # available, and will be the minimum volume version of each # except in certain degenerate cases, where they will be no worse # than a least squares fit version of the primitive. ( mesh.bounding_box_oriented.volume, mesh.bounding_cylinder.volume, mesh.bounding_sphere.volume, ) ``` -------------------------------- ### Optimize Sequence Concatenation with np.concatenate Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Compares the performance of `np.vstack` against `np.concatenate` for combining a sequence of arrays. `np.concatenate` is generally faster. ```python In [7]: %timeit np.vstack(seq) 100 loops, best of 3: 3.48 ms per loop ``` ```python In [8]: %timeit np.concatenate(seq) 100 loops, best of 3: 2.33 ms per loop ``` -------------------------------- ### Optimize Array Summation with Dot Product Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Shows how replacing `array.sum(axis=1)` with a dot product of the array and a vector of ones can yield substantial speed improvements in tight loops. ```python In [3]: %timeit a.sum(axis=1) 10000 loops, best of 3: 157 µs per loop ``` ```python In [4]: %timeit np.dot(a, [1,1,1]) 10000 loops, best of 3: 25.8 µs per loop ``` -------------------------------- ### Optimize String Splitting with NumPy Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Compare the performance of splitting a string into a NumPy array using `str.split` versus `np.fromstring`. `np.fromstring` is generally faster for large datasets. ```python In [6]: %timeit np.array(text.split(), dtype=np.float64) 1000 loops, best of 3: 209 µs per loop ``` ```python In [7]: %timeit np.fromstring(text, sep='\n', dtype=np.float64) 10000 loops, best of 3: 139 µs per loop ``` -------------------------------- ### Show Oriented Bounding Box Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Display a preview of the mesh's minimum volume oriented bounding box. This primitive object subclasses Trimesh. ```python # the bounding box is a trimesh.primitives.Box object, which subclasses # Trimesh and lazily evaluates to fill in vertices and faces when requested mesh.bounding_box_oriented.show() ``` -------------------------------- ### Prepare Mesh for Visualization Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Unmerges mesh vertices to prevent smoothing and sets default face colors, highlighting the intersected triangles in red. ```python # unmerge so viewer doesn't smooth mesh.unmerge_vertices() # make mesh white- ish mesh.visual.face_colors = [255, 255, 255, 255] mesh.visual.face_colors[index_tri] = [255, 0, 0, 255] ``` -------------------------------- ### Interactive Debugging with IPython Embed Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Integrates an IPython embeddable REPL within a Python function for interactive debugging and development. This allows for line-by-line execution and inspection of context. ```python import trimesh import numpy as np def fancy_function(blah): if blah.shape != (3, 3): raise ValueError('this input was goofy!') # do some obvious operations and whatnot dots = np.dot(blah, [1,2,3]) # get a REPL inside my function so I can write each line # with the context of the function, copy paste the lines # in and at the end return the value and remove the embed from IPython import embed embed() if __name__ == '__main__': # print out all the debug messages so we can see # if there's something going on we need to look at trimesh.util.attach_to_log() # I like pyinstrument as it's a relatively low-overhead sampling # profiler and has nice looking nested print statements compared # to cProfile or others. import pyinstrument data = np.random.random((3, 3)) with pyinstrument.Profiler() as pr: result = fancy_function(data) pr.print() ``` -------------------------------- ### Create Weighted Graph Source: https://github.com/mikedh/trimesh/blob/main/examples/shortest.ipynb Constructs a NetworkX graph where nodes are mesh vertices and edges represent mesh edges, weighted by their lengths. ```python # create the graph with edge attributes for length g = nx.Graph() for edge, L in zip(edges, length): g.add_edge(*edge, length=L) ``` -------------------------------- ### Efficiently Find Unique Elements with np.bincount Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Illustrates how `np.bincount` can be used as a faster alternative to `np.unique` for finding unique elements in an array of integers, especially when the range of values is manageable. ```python In [47]: %timeit np.where(np.bincount(a).astype(bool))[0] 100000 loops, best of 3: 5.81 µs per loop ``` ```python In [48]: %timeit np.unique(a) 10000 loops, best of 3: 31.8 µs per loop ``` -------------------------------- ### Sample Volume of Oriented Bounding Box Source: https://github.com/mikedh/trimesh/blob/main/examples/nearest.ipynb Samples points from the volume of the mesh's oriented bounding box. This is useful for generating test points within the approximate bounds of the mesh. ```python # we can sample the volume of Box primitives points = mesh.bounding_box_oriented.sample_volume(count=10) ``` -------------------------------- ### Display Mesh Source: https://github.com/mikedh/trimesh/blob/main/examples/colors.ipynb Renders and displays the loaded mesh. This function opens an interactive viewer if available. ```python m.show() ``` -------------------------------- ### Load Mesh Model Source: https://github.com/mikedh/trimesh/blob/main/examples/nearest.ipynb Loads a PLY model with colors. Ensure the model file path is correct. ```python # load a large- ish PLY model with colors mesh = trimesh.load("../models/cycloidal.ply") ``` -------------------------------- ### Raise DeprecationWarning Source: https://github.com/mikedh/trimesh/blob/main/docs/content/contributing.md Demonstrates how to issue a `DeprecationWarning` with a clear message about the upcoming removal of a feature and suggests a replacement. This is used to inform users of API changes well in advance. ```python warnings.warn( "`remove_duplicate_faces` is deprecated " + "and will be removed in March 2024: " + "replace with `mesh.update_faces(mesh.unique_faces())`", category=DeprecationWarning, stacklevel=2, ) ``` -------------------------------- ### Display Mesh Source: https://github.com/mikedh/trimesh/blob/main/examples/texture.ipynb Display the loaded mesh. This function will render the mesh, including any associated textures if they were loaded correctly. ```python mesh.show() ``` -------------------------------- ### Show Mesh with Oriented Bounding Box Source: https://github.com/mikedh/trimesh/blob/main/README.md Displays the mesh appended with its oriented bounding box. The bounding box is a Trimesh primitive. ```python (mesh + mesh.bounding_box_oriented).show() ``` -------------------------------- ### Set Camera Transform for Isometric View Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Calculate and set the camera's transformation matrix to achieve the desired isometric view of the geometry. ```python # Get camera transform to look at geometry with isometric view t_r = scene.camera.look_at(corners, rotation=r_e) # Set camera transform scene.camera_transform = t_r ``` -------------------------------- ### Split Mesh by Connected Components Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Split the mesh into separate Trimesh objects based on connected components of face adjacency. Returns a list of meshes. ```python # if there are multiple bodies in the mesh we can split the mesh by # connected components of face adjacency # since this example mesh is a single watertight body we get a list of one mesh mesh.split() ``` -------------------------------- ### Access Ray Intersection Documentation Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Retrieves and displays the docstring for the `intersects_location` method, providing details on its usage and parameters. ```python # check out the docstring for intersects_location queries mesh.ray.intersects_location.__doc__ ``` -------------------------------- ### Compare Mesh Volume to Convex Hull Volume Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Calculate the ratio of the mesh's volume to its convex hull's volume. This is useful for understanding the mesh's compactness. ```python # the convex hull is another Trimesh object that is available as a property # lets compare the volume of our mesh with the volume of its convex hull np.divide(mesh.volume, mesh.convex_hull.volume) ``` -------------------------------- ### Apply Transformation Matrix Source: https://github.com/mikedh/trimesh/blob/main/README.md Applies a 4x4 transformation matrix to the mesh. This method cleanly applies the transform. ```python mesh.apply_transform(trimesh.transformations.random_rotation_matrix()) ``` -------------------------------- ### Visualize Curvature Results Source: https://github.com/mikedh/trimesh/blob/main/examples/curvature.ipynb Plots the average Gaussian and Mean curvature values against the radii used for calculation. This helps in understanding how curvature varies with the scale of measurement. ```python plt.figure() plt.plot(radii, gauss.mean(axis=1)) plt.title("Gaussian Curvature") plt.show() plt.figure() plt.plot(radii, mean.mean(axis=1)) plt.title("Mean Curvature") plt.show() ``` -------------------------------- ### Display Mesh Visual Kind Source: https://github.com/mikedh/trimesh/blob/main/examples/colors.ipynb Retrieves and displays the visual kind of the loaded mesh. This indicates how the mesh's visual properties are stored. ```python m.visual.kind ``` -------------------------------- ### Load Mesh Without Processing Source: https://github.com/mikedh/trimesh/blob/main/examples/colors.ipynb Loads a mesh file without applying default processing. This is useful for inspecting the raw mesh data. ```python import trimesh m = trimesh.load("../models/machinist.XAML", process=False) ``` -------------------------------- ### Combine and Display Multiple Slices Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Combines multiple 2D cross-section objects (Path2D) into a single Path2D object by summing them. This allows for easy visualization of all slices together. ```python # summing the array of Path2D objects will put all of the curves # into one Path2D object, which we can plot easily combined = np.sum(sections) combined.show() ``` -------------------------------- ### Add Geometry to Scene Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Add the loaded 3D mesh to the scene for rendering. ```python # Add the chosen geometry to the scene scene.add_geometry(mesh) ``` -------------------------------- ### Apply Random Rotation Transform Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Apply a randomly generated rotation matrix to the mesh. The `apply_transform` method handles matrix transformations cleanly. ```python # transform method can be passed a (4,4) matrix and will cleanly apply the transform mesh.apply_transform(trimesh.transformations.random_rotation_matrix()) ``` -------------------------------- ### Perform Ray-Mesh Intersection Query Source: https://github.com/mikedh/trimesh/blob/main/examples/ray.ipynb Executes the ray-mesh intersection query using the defined origins and directions. This returns the locations of intersections, the ray indices, and the triangle indices. ```python # run the mesh- ray query locations, index_ray, index_tri = mesh.ray.intersects_location( ray_origins=ray_origins, ray_directions=ray_directions ) ``` -------------------------------- ### Find Closest Points on Mesh Surface Source: https://github.com/mikedh/trimesh/blob/main/examples/nearest.ipynb Finds the closest point on the mesh surface for each point in a given set. It returns the closest points, their distances to the surface, and the triangle ID they are closest to. ```python # find the closest point on the mesh to each random point (closest_points, distances, triangle_id) = mesh.nearest.on_surface(points) # distance from point to surface of meshdistances ``` -------------------------------- ### Define Isometric Camera Rotation Source: https://github.com/mikedh/trimesh/blob/main/examples/save_image.ipynb Create a rotation matrix for an isometric camera view using Euler angles. ```python # Get isometric view r_e = trimesh.transformations.euler_matrix( math.radians(45), math.radians(45), math.radians(45), "ryxz", ) ``` -------------------------------- ### Center Mesh at Center of Mass Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Translate the mesh so that its center of mass is at the origin (0,0,0). This is applicable to watertight meshes. ```python # since the mesh is watertight, it means there is a # volumetric center of mass which we can set as the origin for our mesh mesh.vertices -= mesh.center_mass ``` -------------------------------- ### Colorize Mesh Facets Source: https://github.com/mikedh/trimesh/blob/main/README.md Assigns a random color to each facet (group of coplanar adjacent faces) of the mesh. This is a visual aid for understanding mesh structure. ```python # facets are groups of coplanar adjacent faces # set each facet to a random color ``` -------------------------------- ### Generate Multiple Parallel Mesh Slices Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Generates multiple parallel cross-sections of a mesh along a specified axis. This is useful for simulating layered manufacturing processes like 3D printing. Define the slicing levels using an array of heights. ```python # if we wanted to take a bunch of parallel slices, like for a 3D printer # we can do that easily with the section_multiplane method # we're going to slice the mesh into evenly spaced chunks along z # this takes the (2,3) bounding box and slices it into [minz, maxz] z_extents = mesh.bounds[:, 2] # slice every .125 model units (eg, inches) z_levels = np.arange(*z_extents, step=0.125) # find a bunch of parallel cross sections sections = mesh.section_multiplane( plane_origin=mesh.bounds[0], plane_normal=[0, 0, 1], heights=z_levels ) sections ``` -------------------------------- ### Calculate Curvature Measures Source: https://github.com/mikedh/trimesh/blob/main/examples/curvature.ipynb Computes discrete Gaussian and Mean curvature measures for the mesh across a range of radii. The results are normalized by the area of intersection between a sphere and a ball. ```python radii = np.linspace(0.1, 2.0, 10) gauss = np.array( [ discrete_gaussian_curvature_measure(mesh, mesh.vertices, r) / sphere_ball_intersection(1, r) for r in radii ] ) mean = np.array( [ discrete_mean_curvature_measure(mesh, mesh.vertices, r) / sphere_ball_intersection(1, r) for r in radii ] ) ``` -------------------------------- ### Check if Mesh is Watertight Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Determine if the mesh is watertight, which is a prerequisite for certain volumetric calculations. ```python # is the current mesh watertight? mesh.is_watertight ``` -------------------------------- ### Translate Mesh by Center of Mass Source: https://github.com/mikedh/trimesh/blob/main/README.md Applies a translation to the mesh to move its center of mass to the origin (0,0,0). This operation attempts to preserve cached values where possible. ```python # since the mesh is watertight it means there is a volume # with a center of mass calculated from a surface integral approach # which we can set as the origin for our mesh. It's perfectly fine to # alter the vertices directly: # mesh.vertices -= mesh.center_mass # although this will completely clear the cache including face normals # as we don't know that they're still valid. Using the translation # method will try to save cached values that are still valid: mesh.apply_translation(-mesh.center_mass) ``` -------------------------------- ### Plot Intersection of Line and Polygon Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Visualizes the intersection points between a line and a 2D polygon. It plots the original geometry in black and green, and the intersection points in red using Matplotlib. ```python # we can plot the intersection (red) and our original geometry(black and green) import matplotlib.pyplot as plt ax = plt.gca() for h in hits.geoms: ax.plot(*h.xy, color="r") slice_2D.show() ``` -------------------------------- ### Generate Single Mesh Cross-Section Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Creates a single cross-section of the mesh by defining a plane using its origin and normal vector. The resulting slice is in the original mesh's coordinate frame. ```python # get a single cross section of the mesh slice = mesh.section(plane_origin=mesh.centroid, plane_normal=[0, 0, 1]) # the section will be in the original mesh frame slice.show() ``` -------------------------------- ### Color Mesh Facets Randomly Source: https://github.com/mikedh/trimesh/blob/main/examples/quick_start.ipynb Assign a random RGBA color to each facet (group of coplanar adjacent faces) of the mesh. Colors are 8-bit RGBA by default. ```python # facets are groups of coplanar adjacent faces # set each facet to a random color # colors are 8 bit RGBA by default (n,4) np.uint8 for facet in mesh.facets: mesh.visual.face_colors[facet] = trimesh.visual.random_color() ``` -------------------------------- ### Convert Cross-Section to Planar 2D Object Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Converts a 3D mesh cross-section into a 2D planar object (Path2D). This is useful for further 2D geometric operations. The conversion also provides a transformation matrix to map back to 3D. ```python # we can move the 3D curve to a Path2D object easily slice_2D, to_3D = slice.to_planar() slice_2D.show() ``` -------------------------------- ### Inspect UV Coordinate Shape Source: https://github.com/mikedh/trimesh/blob/main/examples/texture.ipynb Check the shape of the UV coordinates associated with the mesh's visual properties. This helps verify if UV data is present and its dimensionality. ```python mesh.visual.uv.shape ``` -------------------------------- ### Display Medial Axis of 2D Polygon Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Calculates and displays the medial axis of a closed 2D polygon. The medial axis is overlaid on the original polygon for visualization. ```python # the medial axis is available for closed Path2D objects (slice_2D + slice_2D.medial_axis()).show() ``` -------------------------------- ### Intersect Line with 2D Polygon Source: https://github.com/mikedh/trimesh/blob/main/examples/section.ipynb Intersects a 2D line segment with a 2D polygon derived from a mesh cross-section using Shapely library methods. This helps in finding points where a line crosses the polygon boundary. ```python # if we want to intersect a line with this 2D polygon, we can use shapely methods polygon = slice_2D.polygons_full[0] # intersect line with one of the polygons hits = polygon.intersection(LineString([[-4, -1], [3, 0]])) # check what class the intersection returned hits.__class__ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.