voxcity.geoprocessor.mesh ========================= .. py:module:: voxcity.geoprocessor.mesh .. autoapi-nested-parse:: Mesh generation utilities for voxel and 2D grid visualization. Orientation contract: - Mesh builders expect VoxCity uv-layout arrays: axis 0 = u/north-ish, axis 1 = v/east/right, axis 2 = z/up. - Rendered scene coordinates are GIS/CAD local coordinates: X = v/east, Y = u/north, Z = up. - Do not flip arrays at this boundary. Only remap axes from array (u, v, z) to scene (x=v, y=u, z). Functions --------- .. autoapisummary:: voxcity.geoprocessor.mesh.create_voxel_mesh voxcity.geoprocessor.mesh.create_sim_surface_mesh voxcity.geoprocessor.mesh.create_city_meshes voxcity.geoprocessor.mesh.export_meshes voxcity.geoprocessor.mesh.split_vertices_manual voxcity.geoprocessor.mesh.save_obj_from_colored_mesh Module Contents --------------- .. py:function:: create_voxel_mesh(voxel_array, class_id, meshsize=1.0, building_id_grid=None, mesh_type=None) Create a 3D mesh from voxels preserving sharp edges, scaled by meshsize. This function converts a 3D voxel array into a triangulated mesh, where each voxel face is converted into two triangles. The function preserves sharp edges between different classes and handles special cases for buildings. :param voxel_array: The voxel array of shape (X, Y, Z) where each cell contains a class ID. - 0: typically represents void/air - -2: typically represents trees - -3: typically represents buildings Other values can represent different classes as defined by the application. :type voxel_array: np.ndarray (3D) :param class_id: The ID of the class to extract. Only voxels with this ID will be included in the output mesh. :type class_id: int :param meshsize: The real-world size of each voxel in meters, applied uniformly to x, y, and z dimensions. Used to scale the output mesh to real-world coordinates. :type meshsize: float, default=1.0 :param building_id_grid: 2D grid of building IDs with shape (X, Y). Only used when class_id=-3 (buildings). Each cell contains a unique identifier for the building at that location. This allows tracking which faces belong to which building. :type building_id_grid: np.ndarray (2D), optional :param mesh_type: Type of mesh to create, controlling which faces are included: - None (default): create faces at boundaries between different classes - 'building_solar' or 'open_air': only create faces at boundaries between buildings (-3) and either void (0) or trees (-2). Useful for solar analysis where only exposed surfaces matter. :type mesh_type: str, optional :returns: **mesh** -- The resulting triangulated mesh for the given class_id. Returns None if no voxels of the specified class are found. The mesh includes: - vertices: 3D coordinates of each vertex - faces: triangles defined by vertex indices - face_normals: normal vectors for each face - metadata: If class_id=-3, includes 'building_id' mapping faces to buildings :rtype: trimesh.Trimesh or None .. rubric:: Examples Basic usage for a simple voxel array: >>> voxels = np.zeros((10, 10, 10)) >>> voxels[4:7, 4:7, 0:5] = 1 # Create a simple column >>> mesh = create_voxel_mesh(voxels, class_id=1, meshsize=0.5) Creating a building mesh with IDs: >>> building_ids = np.zeros((10, 10)) >>> building_ids[4:7, 4:7] = 1 # Mark building #1 >>> mesh = create_voxel_mesh(voxels, class_id=-3, ... building_id_grid=building_ids, ... meshsize=1.0) .. rubric:: Notes - The function creates faces only at boundaries between different classes or at the edges of the voxel array. - Each face is split into two triangles for compatibility with graphics engines. - Face normals are computed to ensure correct lighting and rendering. - For buildings (class_id=-3), building IDs are tracked to maintain building identity. - The mesh preserves sharp edges, which is important for architectural visualization. .. py:function:: create_sim_surface_mesh(sim_grid, dem_grid, meshsize=1.0, z_offset=1.5, cmap_name='viridis', vmin=None, vmax=None) Create a colored planar surface mesh from simulation data, positioned above a DEM. This function generates a 3D visualization mesh for 2D simulation results (like Green View Index, solar radiation, etc.). The mesh is positioned above the Digital Elevation Model (DEM) by a specified offset, and colored according to the simulation values using a matplotlib colormap. :param sim_grid: 2D array of simulation values (e.g., Green View Index, solar radiation). NaN values in this grid will be skipped in the output mesh. The grid should be oriented with north at the top. :type sim_grid: 2D np.ndarray :param dem_grid: 2D array of ground elevations in meters. Must have the same shape as sim_grid. Used to position the visualization mesh at the correct height above terrain. :type dem_grid: 2D np.ndarray :param meshsize: Size of each cell in meters. Applied uniformly to x and y dimensions. Determines the resolution of the output mesh. :type meshsize: float, default=1.0 :param z_offset: Additional height offset in meters added to dem_grid elevations. Used to position the visualization above ground level for better visibility. :type z_offset: float, default=1.5 :param cmap_name: Matplotlib colormap name used for coloring the mesh based on sim_grid values. Common options: - 'viridis': Default, perceptually uniform, colorblind-friendly - 'RdYlBu': Red-Yellow-Blue, good for diverging data - 'jet': Rainbow colormap (not recommended for scientific visualization) :type cmap_name: str, default='viridis' :param vmin: Minimum value for color mapping. If None, uses min of sim_grid (excluding NaN). Used to control the range of the colormap. :type vmin: float, optional :param vmax: Maximum value for color mapping. If None, uses max of sim_grid (excluding NaN). Used to control the range of the colormap. :type vmax: float, optional :returns: **mesh** -- A single mesh containing one colored square face (two triangles) per non-NaN cell. Returns None if there are no valid (non-NaN) cells in sim_grid. The mesh includes: - vertices: 3D coordinates of each vertex - faces: triangles defined by vertex indices - face_colors: RGBA colors for each face based on sim_grid values - visual: trimesh.visual.ColorVisuals object storing the face colors :rtype: trimesh.Trimesh or None .. rubric:: Examples Basic usage with Green View Index data: >>> gvi = np.array([[0.5, 0.6], [0.4, 0.8]]) # GVI values >>> dem = np.array([[10.0, 10.2], [9.8, 10.1]]) # Ground heights >>> mesh = create_sim_surface_mesh(gvi, dem, meshsize=1.0, z_offset=1.5) Custom color range and colormap: >>> mesh = create_sim_surface_mesh(gvi, dem, ... cmap_name='RdYlBu', ... vmin=0.0, vmax=1.0) .. rubric:: Notes - The function automatically creates a matplotlib colorbar figure for visualization - Input grids are expected in uv layout and are not flipped at this boundary - Each grid cell is converted to two triangles for compatibility with 3D engines - The mesh is positioned at dem_grid + z_offset to float above the terrain - Face colors are interpolated from the colormap based on sim_grid values .. py:function:: create_city_meshes(voxel_array, vox_dict, meshsize=1.0, include_classes=None, exclude_classes=None) Create a collection of colored 3D meshes representing different city elements. This function processes a voxelized city model and creates separate meshes for different urban elements (buildings, trees, etc.), each with its own color. The function preserves sharp edges and applies appropriate colors based on the provided color dictionary. :param voxel_array: 3D array representing the voxelized city model. Each voxel contains a class ID that maps to an urban element type: - 0: Void/air (automatically skipped) - -2: Trees - -3: Buildings Other values can represent different urban elements as defined in vox_dict. :type voxel_array: np.ndarray (3D) :param vox_dict: Dictionary mapping class IDs to RGB colors. Each entry should be: {class_id: [R, G, B]} where R, G, B are 0-255 integer values. Example: {-3: [200, 200, 200], -2: [0, 255, 0]} for grey buildings and green trees. The key 0 (air) is automatically excluded. :type vox_dict: dict :param meshsize: Size of each voxel in meters, applied uniformly to x, y, and z dimensions. Used to scale the output meshes to real-world coordinates. :type meshsize: float, default=1.0 :returns: **meshes** -- Dictionary mapping class IDs to their corresponding trimesh.Trimesh objects. Each mesh includes: - vertices: 3D coordinates scaled by meshsize - faces: triangulated faces preserving sharp edges - face_colors: RGBA colors from vox_dict - visual: trimesh.visual.ColorVisuals object storing the face colors Classes with no voxels are automatically excluded from the output. :rtype: dict .. rubric:: Examples Basic usage with buildings and trees: >>> voxels = np.zeros((10, 10, 10)) >>> voxels[4:7, 4:7, 0:5] = -3 # Add a building >>> voxels[2:4, 2:4, 0:3] = -2 # Add some trees >>> colors = { ... -3: [200, 200, 200], # Grey buildings ... -2: [0, 255, 0] # Green trees ... } >>> meshes = create_city_meshes(voxels, colors, meshsize=1.0) .. rubric:: Notes - The function automatically skips class_id=0 (typically air/void) - Each urban element type gets its own separate mesh for efficient rendering - Colors are converted from RGB [0-255] to RGBA [0-1] format - Sharp edges are preserved to maintain architectural features - Empty classes (no voxels) are automatically excluded from the output - Errors during mesh creation for a class are caught and reported .. py:function:: export_meshes(meshes, output_directory, base_filename) Export a collection of meshes to both OBJ (with MTL) and STL formats. This function exports meshes in two ways: 1. A single combined OBJ file with materials (and associated MTL file) 2. Separate STL files for each mesh, named with their class IDs :param meshes: Dictionary mapping class IDs to trimesh.Trimesh objects. Each mesh should have: - vertices: 3D coordinates - faces: triangulated faces - face_colors: RGBA colors (if using materials) :type meshes: dict :param output_directory: Directory path where the output files will be saved. Will be created if it doesn't exist. :type output_directory: str :param base_filename: Base name for the output files (without extension). Will be used to create: - {base_filename}.obj : Combined mesh with materials - {base_filename}.mtl : Material definitions for OBJ - {base_filename}_{class_id}.stl : Individual STL files :type base_filename: str :returns: Files are written directly to the specified output directory. :rtype: None .. rubric:: Examples >>> meshes = { ... -3: building_mesh, # Building mesh with grey color ... -2: tree_mesh # Tree mesh with green color ... } >>> export_meshes(meshes, 'output/models', 'city_model') This will create: - output/models/city_model.obj - output/models/city_model.mtl - output/models/city_model_-3.stl - output/models/city_model_-2.stl .. rubric:: Notes - OBJ/MTL format preserves colors and materials but is more complex - STL format is simpler but doesn't support colors - STL files are exported separately for each class for easier processing - The OBJ file combines all meshes while preserving their materials - File extensions are automatically added to the base filename .. py:function:: split_vertices_manual(mesh) Split a mesh into independent faces by duplicating shared vertices. This function imitates trimesh's split_vertices() functionality but ensures complete face independence by giving each face its own copy of vertices. This is particularly useful for rendering applications where smooth shading between faces is undesirable, such as architectural visualization in Rhino. :param mesh: Input mesh to split. Should have: - vertices: array of vertex coordinates - faces: array of vertex indices forming triangles - visual: Optional ColorVisuals object with face colors :type mesh: trimesh.Trimesh :returns: **out_mesh** -- New mesh where each face is completely independent, with: - Duplicated vertices for each face - No vertex sharing between faces - Preserved face colors if present in input - Each face as a separate component :rtype: trimesh.Trimesh .. rubric:: Examples Basic usage: >>> vertices = np.array([[0,0,0], [1,0,0], [1,1,0], [0,1,0]]) >>> faces = np.array([[0,1,2], [0,2,3]]) # Two triangles sharing vertices >>> mesh = trimesh.Trimesh(vertices=vertices, faces=faces) >>> split_mesh = split_vertices_manual(mesh) >>> print(f"Original vertices: {len(mesh.vertices)}") # 4 vertices >>> print(f"Split vertices: {len(split_mesh.vertices)}") # 6 vertices With face colors: >>> colors = np.array([[255,0,0,255], [0,255,0,255]]) # Red and green faces >>> mesh.visual = trimesh.visual.ColorVisuals(mesh, face_colors=colors) >>> split_mesh = split_vertices_manual(mesh) # Colors are preserved .. rubric:: Notes - Each output face has exactly 3 unique vertices - Face colors are preserved in the output mesh - Useful for: - Preventing smooth shading artifacts - Ensuring face color independence - Preparing meshes for CAD software - Creating sharp edges in architectural models - Memory usage increases as vertices are duplicated .. py:function:: save_obj_from_colored_mesh(meshes, output_path, base_filename, max_materials=None) Memory-safe OBJ/MTL exporter. - Streams vertices/faces to disk (no concatenate, no per-face mini-meshes). - Uses face colors -> materials (no vertex splitting). - Optional color quantization to reduce material count.