Coverage for trimesh/exchange/binvox.py: 76%
176 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-22 02:08 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-22 02:08 +0000
1"""
2Parsing functions for Binvox files.
4https://www.patrickmin.com/binvox/binvox.html
6Exporting meshes as binvox files requires the
7`binvox` executable to be in your path.
8"""
10import collections
11import os
12import subprocess
13from tempfile import TemporaryDirectory
15import numpy as np
17from .. import util
18from ..base import Trimesh
19from ..typed import ShapeLike
20from ..util import comment_strip, decode_text
22# find the executable for binvox in PATH
23binvox_encoder = util.which("binvox")
24Binvox = collections.namedtuple("Binvox", ["rle_data", "shape", "translate", "scale"])
27def _parse_binvox_header(file_obj):
28 """
29 Read the header from a binvox file.
30 Spec available:
31 https://www.patrickmin.com/binvox/binvox.html
33 Parameters
34 ------------
35 file_obj: file-object
36 File like object with binvox file
38 Returns
39 ----------
40 shape : tuple
41 Shape of binvox according to binvox spec
42 translate : tuple
43 Translation
44 scale : float
45 Scale of voxels
47 Raises
48 ------------
49 IOError
50 If invalid binvox file.
51 """
53 # check for the magic string in the first line
54 first = decode_text(file_obj.readline()).strip()
55 if "binvox" not in first.lower():
56 raise ValueError("File is not in the binvox format!")
58 header = {}
59 reached_data = False
60 # do a capped iteration
61 for _ in range(100):
62 # get the line as a lower-case, comment-stripped split list
63 line = (
64 comment_strip(decode_text(file_obj.readline()).lower(), "#").strip().split()
65 )
66 # if the line was a comment or whitespace don't include it
67 if len(line) == 0:
68 continue
70 elif line[0] == "data":
71 # we need to read up until we see "data" so the
72 # read-the-rest-of-the-payload operation is correct
73 reached_data = True
74 break
76 # save the keyed header data
77 header[line[0]] = line[1:]
79 if not reached_data:
80 raise ValueError("Didn't reach header termination magic word `data`")
82 if "dim" not in header.keys():
83 raise ValueError(
84 f"Malformed binvox header: `dim` is required, only received `{header.keys()}`"
85 )
87 # dimension of voxel array is required
88 shape = np.array(header["dim"], dtype=np.int64)
90 # provide default values for translation and scale
91 translate = np.array(header.get("translate", [0, 0, 0]), np.float64)
92 scale = np.array(header.get("scale", [1]), dtype=np.float64)
94 return shape, translate, scale[0]
97def parse_binvox(fp, writeable=False):
98 """
99 Read a binvox file, spec at
100 https://www.patrickmin.com/binvox/binvox.html
102 Parameters
103 ------------
104 fp: file-object
105 File like object with binvox file
107 Returns
108 ----------
109 binvox : namedtuple
110 Containing data
111 rle : numpy array
112 Run length encoded data
114 Raises
115 ------------
116 IOError
117 If invalid binvox file
118 """
119 # get the header info
120 shape, translate, scale = _parse_binvox_header(fp)
121 # get the rest of the file
122 data = fp.read()
123 # convert to numpy array
124 rle_data = np.frombuffer(data, dtype=np.uint8)
126 if writeable:
127 rle_data = rle_data.copy()
128 return Binvox(rle_data, shape, translate, scale)
131def binvox_header(shape: ShapeLike, translate, scale):
132 """
133 Get a binvox header string.
135 Parameters
136 --------
137 shape: length 3 iterable of ints denoting shape of voxel grid.
138 translate: length 3 iterable of floats denoting translation.
139 scale: num length of entire voxel grid.
141 Returns
142 --------
143 string including "data\n" line.
144 """
145 sx, sy, sz = np.atleast_1d(shape).astype(np.int64).tolist()
146 tx, ty, tz = translate
148 return f"""#binvox 1
149# generated in `trimesh`
150dim {sx} {sy} {sz}
151translate {tx} {ty} {tz}
152scale {scale}
153data
154"""
157def binvox_bytes(rle_data, shape: ShapeLike, translate=(0, 0, 0), scale=1):
158 """Get a binary representation of binvox data.
160 Parameters
161 --------
162 rle_data : numpy array
163 Run-length encoded numpy array.
164 shape : (3,) int
165 Shape of voxel grid.
166 translate : (3,) float
167 Translation of voxels
168 scale : float
169 Length of entire voxel grid.
171 Returns
172 --------
173 data : bytes
174 Suitable for writing to binary file
175 """
176 if rle_data.dtype != np.uint8:
177 raise ValueError(f"rle_data.dtype must be np.uint8, got {rle_data.dtype}")
179 header = binvox_header(shape, translate, scale).encode()
180 return header + rle_data.tobytes()
183def voxel_from_binvox(
184 rle_data, shape: ShapeLike, translate=None, scale=1.0, axis_order="xzy"
185):
186 """
187 Factory for building from data associated with binvox files.
189 Parameters
190 ---------
191 rle_data : numpy
192 Run-length-encoded of flat voxel
193 values, or a `trimesh.rle.RunLengthEncoding` object.
194 See `trimesh.rle` documentation for description of encoding
195 shape : (3,) int
196 Shape of voxel grid.
197 translate : (3,) float
198 Translation of voxels
199 scale : float
200 Length of entire voxel grid.
201 axis_order : iterable
202 With values in ('x', 'y', 'z', 0, 1, 2),
203 where x => 0, y => 1, z => 2
204 denoting the order of axes in the encoded data. binvox by
205 default saves in xzy order, but using `xyz` (or (0, 1, 2)) will
206 be faster in some circumstances.
208 Returns
209 ---------
210 result : VoxelGrid
211 Loaded voxels
212 """
213 # shape must be uniform else scale is ambiguous
214 from .. import transformations
215 from ..voxel import encoding as enc
216 from ..voxel.base import VoxelGrid
218 shape = tuple(np.atleast_1d(shape).tolist())
219 if isinstance(rle_data, enc.RunLengthEncoding):
220 encoding = rle_data
221 else:
222 encoding = enc.RunLengthEncoding(rle_data, dtype=bool)
224 # translate = np.asanyarray(translate) * scale)
225 # translate = [0, 0, 0]
226 transform = transformations.scale_and_translate(
227 scale=scale / (np.array(shape) - 1), translate=translate
228 )
230 if axis_order == "xzy":
231 # the data is stored in `xzy` order but `shape` is in `xyz`
232 perm = (0, 2, 1)
233 encoding = encoding.reshape(np.take(shape, perm)).transpose(perm)
234 elif axis_order is None or axis_order == "xyz":
235 encoding = encoding.reshape(shape)
236 else:
237 raise ValueError(
238 "Invalid axis_order '%s': must be None, 'xyz' or 'xzy'", axis_order
239 )
241 return VoxelGrid(encoding, transform)
244def load_binvox(file_obj, resolver=None, axis_order="xzy", file_type=None):
245 """
246 Load trimesh `VoxelGrid` instance from file.
248 Parameters
249 -----------
250 file_obj : file-like object
251 Contains binvox data
252 resolver : unused
253 axis_order : str
254 Order of axes in encoded data.
255 Binvox default is 'xzy', but 'xyz' may be faster
256 where this is not relevant.
258 Returns
259 ---------
260 result : trimesh.voxel.VoxelGrid
261 Loaded voxel data
262 """
263 if file_type is not None and file_type != "binvox":
264 raise ValueError(f"file_type must be None or binvox, got {file_type}")
265 data = parse_binvox(file_obj, writeable=True)
266 return voxel_from_binvox(
267 rle_data=data.rle_data,
268 shape=data.shape,
269 translate=data.translate,
270 scale=data.scale,
271 axis_order=axis_order,
272 )
275def export_binvox(voxel, axis_order="xzy"):
276 """
277 Export `trimesh.voxel.VoxelGrid` instance to bytes
279 Parameters
280 ------------
281 voxel : `trimesh.voxel.VoxelGrid`
282 Assumes axis ordering of `xyz` and encodes
283 in binvox default `xzy` ordering.
284 axis_order : str
285 Eements in ('x', 'y', 'z', 0, 1, 2), the order
286 of axes to encode data (standard is 'xzy' for binvox). `voxel`
287 data is assumed to be in order 'xyz'.
289 Returns
290 -----------
291 result : bytes
292 Representation according to binvox spec
293 """
294 translate = voxel.translation
295 scale = voxel.scale * (np.array(voxel.shape) - 1)
296 (neg_scale,) = np.where(scale < 0)
297 encoding = voxel.encoding.flip(neg_scale)
298 scale = np.abs(scale)
299 if not util.allclose(scale[0], scale[1:], 1e-6 * scale[0] + 1e-8):
300 raise ValueError("Can only export binvox with uniform scale")
301 scale = scale[0]
302 if axis_order == "xzy":
303 encoding = encoding.transpose((0, 2, 1))
304 elif axis_order != "xyz":
305 raise ValueError('Invalid axis_order: must be one of ("xyz", "xzy")')
306 rle_data = encoding.flat.run_length_data(dtype=np.uint8)
307 return binvox_bytes(rle_data, shape=voxel.shape, translate=translate, scale=scale)
310class Binvoxer:
311 """
312 Interface for binvox CL tool.
314 This class is responsible purely for making calls to the CL tool. It
315 makes no attempt to integrate with the rest of trimesh at all.
317 Constructor args configure command line options.
319 `Binvoxer.__call__` operates on the path to a mode file.
321 If using this interface in published works, please cite the references
322 below.
324 See CL tool website for further details.
326 https://www.patrickmin.com/binvox/
328 @article{nooruddin03,
329 author = {Fakir S. Nooruddin and Greg Turk},
330 title = {Simplification and Repair of Polygonal Models Using Volumetric
331 Techniques},
332 journal = {IEEE Transactions on Visualization and Computer Graphics},
333 volume = {9},
334 number = {2},
335 pages = {191--205},
336 year = {2003}
337 }
339 @Misc{binvox,
340 author = {Patrick Min},
341 title = {binvox},
342 howpublished = {{\tt http://www.patrickmin.com/binvox} or
343 {\tt https://www.google.com/search?q=binvox}},
344 year = {2004 - 2019},
345 note = {Accessed: yyyy-mm-dd}
346 }
347 """
349 SUPPORTED_INPUT_TYPES = (
350 "ug",
351 "obj",
352 "off",
353 "dfx",
354 "xgl",
355 "pov",
356 "brep",
357 "ply",
358 "jot",
359 )
361 SUPPORTED_OUTPUT_TYPES = (
362 "binvox",
363 "hips",
364 "mira",
365 "vtk",
366 "raw",
367 "schematic",
368 "msh",
369 )
371 def __init__(
372 self,
373 dimension=32,
374 file_type="binvox",
375 z_buffer_carving=True,
376 z_buffer_voting=True,
377 dilated_carving=False,
378 exact=True,
379 bounding_box=None,
380 remove_internal=False,
381 center=False,
382 rotate_x=0,
383 rotate_z=0,
384 wireframe=False,
385 fit=False,
386 block_id=None,
387 use_material_block_id=False,
388 use_offscreen_pbuffer=False,
389 downsample_factor=None,
390 downsample_threshold=None,
391 verbose=False,
392 binvox_path=None,
393 ):
394 """
395 Configure the voxelizer.
397 Parameters
398 ------------
399 dimension: voxel grid size (max 1024 when not using exact)
400 file_type: str
401 Output file type, supported types are:
402 'binvox'
403 'hips'
404 'mira'
405 'vtk'
406 'raw'
407 'schematic'
408 'msh'
409 z_buffer_carving : use z buffer based carving. At least one of
410 `z_buffer_carving` and `z_buffer_voting` must be True.
411 z_buffer_voting: use z-buffer based parity voting method.
412 dilated_carving: stop carving 1 voxel before intersection.
413 exact: any voxel with part of a triangle gets set. Does not use
414 graphics card.
415 bounding_box: 6-element float list/tuple of min, max values,
416 (minx, miny, minz, maxx, maxy, maxz)
417 remove_internal: remove internal voxels if True. Note there is some odd
418 behaviour if boundary voxels are occupied.
419 center: center model inside unit cube.
420 rotate_x: number of 90 degree ccw rotations around x-axis before
421 voxelizing.
422 rotate_z: number of 90 degree cw rotations around z-axis before
423 voxelizing.
424 wireframe: also render the model in wireframe (helps with thin parts).
425 fit: only write voxels in the voxel bounding box.
426 block_id: when converting to schematic, use this as the block ID.
427 use_material_block_id: when converting from obj to schematic, parse
428 block ID from material spec "usemtl blockid_<id>" (ids 1-255 only).
429 use_offscreen_pbuffer: use offscreen pbuffer instead of onscreen
430 window.
431 downsample_factor: downsample voxels by this factor in each dimension.
432 Must be a power of 2 or None. If not None/1 and `core dumped`
433 errors occur, try slightly adjusting dimensions.
434 downsample_threshold: when downsampling, destination voxel is on if
435 more than this number of voxels are on.
436 verbose : bool
437 If False, silences stdout/stderr from subprocess call.
438 binvox_path : str
439 Path to binvox executable. The default looks for an
440 executable called `binvox` on your `PATH`.
441 """
442 if binvox_path is None:
443 encoder = binvox_encoder
444 else:
445 encoder = binvox_path
447 if encoder is None:
448 raise OSError(
449 " ".join(
450 [
451 "No `binvox_path` provided and no binvox executable found",
452 "on PATH, please go to https://www.patrickmin.com/binvox/ and",
453 "download the appropriate version.",
454 ]
455 )
456 )
458 if dimension > 1024 and not exact:
459 raise ValueError("Maximum dimension using exact is 1024, got %d", dimension)
460 if file_type not in Binvoxer.SUPPORTED_OUTPUT_TYPES:
461 raise ValueError(
462 f"file_type {file_type} not in set of supported output types {Binvoxer.SUPPORTED_OUTPUT_TYPES!s}"
463 )
464 args = [encoder, "-d", str(dimension), "-t", file_type]
465 if exact:
466 args.append("-e")
467 if z_buffer_carving:
468 if z_buffer_voting:
469 pass
470 else:
471 args.append("-c")
472 elif z_buffer_voting:
473 args.append("-v")
474 else:
475 raise ValueError(
476 "One of `z_buffer_carving` or `z_buffer_voting` must be True"
477 )
478 if dilated_carving:
479 args.append("-dc")
481 # Additional parameters
482 if bounding_box is not None:
483 if len(bounding_box) != 6:
484 raise ValueError("bounding_box must have 6 elements")
485 args.append("-bb")
486 args.extend(str(b) for b in bounding_box)
487 if remove_internal:
488 args.append("-ri")
489 if center:
490 args.append("-cb")
491 args.extend(("-rotx",) * rotate_x)
492 args.extend(("-rotz",) * rotate_z)
493 if wireframe:
494 args.append("-aw")
495 if fit:
496 args.append("-fit")
497 if block_id is not None:
498 args.extend(("-bi", block_id))
499 if use_material_block_id:
500 args.append("-mb")
501 if use_offscreen_pbuffer:
502 args.append("-pb")
503 if downsample_factor is not None:
504 times = np.log2(downsample_factor)
505 if int(times) != times:
506 raise ValueError(
507 "downsample_factor must be a power of 2, got %d", downsample_factor
508 )
509 args.extend(("-down",) * int(times))
510 if downsample_threshold is not None:
511 args.extend(("-dmin", str(downsample_threshold)))
512 args.append("PATH")
513 self._args = args
514 self._file_type = file_type
516 self.verbose = verbose
518 @property
519 def file_type(self):
520 return self._file_type
522 def __call__(self, path, overwrite=False):
523 """
524 Create an voxel file in the same directory as model at `path`.
526 Parameters
527 ------------
528 path: string path to model file. Supported types:
529 'ug'
530 'obj'
531 'off'
532 'dfx'
533 'xgl'
534 'pov'
535 'brep'
536 'ply'
537 'jot' (polygongs only)
538 overwrite: if False, checks the output path (head.file_type) is empty
539 before running. If True and a file exists, raises an IOError.
541 Returns
542 ------------
543 string path to voxel file. File type give by file_type in constructor.
544 """
545 head, ext = os.path.splitext(path)
546 ext = ext[1:].lower()
547 if ext not in Binvoxer.SUPPORTED_INPUT_TYPES:
548 raise ValueError(
549 f"file_type {ext} not in set of supported input types {Binvoxer.SUPPORTED_INPUT_TYPES!s}"
550 )
551 out_path = f"{head}.{self._file_type}"
552 if os.path.isfile(out_path) and not overwrite:
553 raise OSError("Attempted to voxelize object at existing path")
554 self._args[-1] = path
556 # generalizes to python2 and python3
557 # will capture terminal output into variable rather than printing
558 verbosity = subprocess.check_output(self._args, stderr=subprocess.STDOUT)
560 # if requested print ourselves
561 if self.verbose:
562 util.log.debug(verbosity)
564 return out_path
567def voxelize_mesh(mesh, binvoxer=None, export_type="off", **binvoxer_kwargs):
568 """
569 Interface for voxelizing Trimesh object via the binvox tool.
571 Implementation simply saved the mesh in the specified export_type then
572 runs the `Binvoxer.__call__` (using either the supplied `binvoxer` or
573 creating one via `binvoxer_kwargs`)
575 Parameters
576 ------------
577 mesh: Trimesh object to voxelize.
578 binvoxer: optional Binvoxer instance.
579 export_type: file type to export mesh as temporarily for Binvoxer to
580 operate on.
581 **binvoxer_kwargs: kwargs for creating a new Binvoxer instance. If binvoxer
582 if provided, this must be empty.
584 Returns
585 ------------
586 `VoxelGrid` object resulting.
587 """
588 if not isinstance(mesh, Trimesh):
589 raise ValueError(f"mesh must be Trimesh instance, got {mesh!s}")
590 if binvoxer is None:
591 binvoxer = Binvoxer(**binvoxer_kwargs)
592 elif len(binvoxer_kwargs) > 0:
593 raise ValueError("Cannot provide binvoxer and binvoxer_kwargs")
594 if binvoxer.file_type != "binvox":
595 raise ValueError('Only "binvox" binvoxer `file_type` currently supported')
596 with TemporaryDirectory() as folder:
597 model_path = os.path.join(folder, f"model.{export_type}")
598 with open(model_path, "wb") as fp:
599 mesh.export(fp, file_type=export_type)
600 out_path = binvoxer(model_path)
601 with open(out_path, "rb") as fp:
602 out_model = load_binvox(fp)
604 return out_model
607_binvox_loaders = {"binvox": load_binvox}