Coverage for trimesh/visual/color.py: 86%
411 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"""
2color.py
3-------------
5Hold and deal with visual information about meshes.
7There are lots of ways to encode visual information, and the goal of this
8architecture is to make it possible to define one, and then transparently
9get the others. The two general categories are:
111) colors, defined for a face, vertex, or material
122) textures, defined as an image and UV coordinates for each vertex
14This module only implements diffuse colors at the moment.
16Goals
17----------
181) If nothing is defined sane defaults should be returned
192) If a user alters or sets a value, that is considered user data
20 and should be saved and treated as such.
213) Only one 'mode' of visual (vertex or face) is allowed at a time
22 and setting or altering a value should automatically change the mode.
23"""
25import copy
26from typing import Any
28import numpy as np
30from .. import caching, util
31from ..constants import tol
32from ..grouping import unique_rows
33from ..resources import get_json
34from ..typed import (
35 ArrayLike,
36 Callable,
37 ColorMapType,
38 DTypeLike,
39 Hashable,
40 Integer,
41 Iterable,
42 NDArray,
43 Seed,
44)
45from .base import Visuals
47# Save a lookup table for an integer to match the
48# cases for HSV conversion specified on the wikipedia article
49# Where indexes 0=C, 1=X, 2=0.0
50_HSV_LOOKUP = np.array(
51 [[0, 1, 2], [1, 0, 2], [2, 0, 1], [2, 1, 0], [1, 2, 0], [0, 2, 1]], dtype=np.int64
52)
53_HSV_LOOKUP.flags.writeable = False
56class ColorVisuals(Visuals):
57 """
58 Store color information about a mesh.
59 """
61 def __init__(
62 self,
63 mesh=None,
64 face_colors: ArrayLike | None = None,
65 vertex_colors: ArrayLike | None = None,
66 ):
67 """
68 Store color information about a mesh.
70 Parameters
71 ----------
72 mesh : Trimesh
73 Object that these visual properties
74 are associated with
75 face_ colors : (n,3|4) or (3,) or (4,) uint8
76 Colors per-face
77 vertex_colors : (n,3|4) or (3,) or (4,) uint8
78 Colors per-vertex
79 """
80 self.mesh = mesh
81 self._data = caching.DataStore()
82 self._cache = caching.Cache(id_function=self._data.__hash__)
84 try:
85 if face_colors is not None:
86 self.face_colors = face_colors
87 if vertex_colors is not None:
88 self.vertex_colors = vertex_colors
89 except ValueError:
90 util.log.warning("unable to convert colors!")
92 @caching.cache_decorator
93 def transparency(self) -> bool:
94 """
95 Does the current object contain any transparency.
97 Returns
98 ----------
99 transparency: bool, does the current visual contain transparency
100 """
101 if "vertex_colors" in self._data:
102 a_min = self._data["vertex_colors"][:, 3].min()
103 elif "face_colors" in self._data:
104 a_min = self._data["face_colors"][:, 3].min()
105 else:
106 return False
108 return bool(a_min < 255)
110 @property
111 def defined(self) -> bool:
112 """
113 Are any colors defined for the current mesh.
115 Returns
116 ---------
117 defined : bool
118 Are colors defined or not.
119 """
120 return self.kind is not None
122 @property
123 def kind(self) -> str | None:
124 """
125 What color mode has been set.
127 Returns
128 ----------
129 mode : str or None
130 One of ('face', 'vertex', None)
131 """
132 # if nothing is stored anywhere it's a safe bet mode is None
133 if not (len(self._cache.cache) > 0 or len(self._data.data) > 0):
134 return None
136 self._verify_hash()
138 # check modes in data
139 if "vertex_colors" in self._data:
140 return "vertex"
141 elif "face_colors" in self._data:
142 return "face"
144 return None
146 def __hash__(self):
147 return self._data.__hash__()
149 def copy(self) -> "ColorVisuals":
150 """
151 Return a copy of the current ColorVisuals object.
154 Returns
155 ----------
156 copied : ColorVisuals
157 Contains the same information as self
158 """
159 copied = ColorVisuals()
160 # call the literally insane generators to validate
161 self.face_colors # noqa
162 self.vertex_colors # noqa
163 # copy anything that's actually data
164 copied._data.data = copy.deepcopy(self._data.data)
166 return copied
168 @property
169 def face_colors(self) -> NDArray[np.uint8]:
170 """
171 Colors defined for each face of a mesh.
173 If no colors are defined, defaults are returned.
175 Returns
176 ----------
177 colors : (len(mesh.faces), 4) uint8
178 RGBA color for each face
179 """
180 return self._get_colors(name="face")
182 @face_colors.setter
183 def face_colors(self, values: ArrayLike):
184 """
185 Set the colors for each face of a mesh.
187 This will apply these colors and delete any previously specified
188 color information.
190 Parameters
191 ------------
192 colors : (len(mesh.faces), 3), set each face to the specified color
193 (len(mesh.faces), 4), set each face to the specified color
194 (3,) int, set the whole mesh this color
195 (4,) int, set the whole mesh this color
196 """
197 if values is None:
198 if "face_colors" in self._data:
199 self._data.data.pop("face_colors")
200 return
202 colors = to_rgba(values)
204 if self.mesh is not None and colors.shape == (4,):
205 count = len(self.mesh.faces)
206 colors = np.tile(colors, (count, 1))
208 # if we set any color information, clear the others
209 self._data.clear()
210 self._data["face_colors"] = colors
211 self._cache.verify()
213 @property
214 def vertex_colors(self) -> NDArray[np.uint8]:
215 """
216 Return the colors for each vertex of a mesh
218 Returns
219 ------------
220 colors: (len(mesh.vertices), 4) uint8, color for each vertex
221 """
222 return self._get_colors(name="vertex")
224 @vertex_colors.setter
225 def vertex_colors(self, values: ArrayLike):
226 """
227 Set the colors for each vertex of a mesh
229 This will apply these colors and delete any previously specified
230 color information.
232 Parameters
233 ------------
234 colors : (len(mesh.vertices), 3), set each face to the color
235 (len(mesh.vertices), 4), set each face to the color
236 (3,) int, set the whole mesh this color
237 (4,) int, set the whole mesh this color
238 """
239 if values is None:
240 if "vertex_colors" in self._data:
241 self._data.data.pop("vertex_colors")
242 return
244 # make sure passed values are numpy array
245 values = np.asanyarray(values)
246 # Ensure the color shape is sane
247 if self.mesh is not None and not (
248 values.shape == (len(self.mesh.vertices), 3)
249 or values.shape == (len(self.mesh.vertices), 4)
250 or values.shape == (3,)
251 or values.shape == (4,)
252 ):
253 return
255 colors = to_rgba(values)
256 if self.mesh is not None and colors.shape == (4,):
257 count = len(self.mesh.vertices)
258 colors = np.tile(colors, (count, 1))
260 # if we set any color information, clear the others
261 self._data.clear()
262 self._data["vertex_colors"] = colors
263 self._cache.verify()
265 def _get_colors(self, name):
266 """
267 A magical function which maintains the sanity of vertex and face colors.
269 * If colors have been explicitly stored or changed, they are considered
270 user data, stored in self._data (DataStore), and are returned immediately
271 when requested.
272 * If colors have never been set, a (count,4) tiled copy of the default diffuse
273 color will be stored in the cache
274 ** the hash on creation for these cached default colors will also be stored
275 ** if the cached color array is altered (different hash than when it was
276 created) we consider that now to be user data and the array is moved from
277 the cache to the DataStore.
279 Parameters
280 -----------
281 name : str
282 Values 'face' or 'vertex'
284 Returns
285 -----------
286 colors : (count, 4) uint8
287 RGBA colors
288 """
290 count = None
291 try:
292 if name == "face":
293 count = len(self.mesh.faces)
294 elif name == "vertex":
295 count = len(self.mesh.vertices)
296 except BaseException:
297 pass
299 # the face or vertex colors
300 key_colors = str(name) + "_colors"
301 # the initial hash of the colors
302 key_hash = key_colors + "_hash"
304 if key_colors in self._data:
305 # if a user has explicitly stored or changed the color it
306 # will be in data
307 return self._data[key_colors]
309 elif key_colors in self._cache:
310 # if the colors have been autogenerated already they
311 # will be in the cache
312 colors = self._cache[key_colors]
313 # if the cached colors have been changed since creation we move
314 # them to data
315 if hash(colors) != self._cache[key_hash]:
316 # cached colors were mutated — promote to user data via
317 # the appropriate property setter
318 if name == "face":
319 self.face_colors = colors
320 elif name == "vertex":
321 self.vertex_colors = colors
322 else:
323 raise ValueError("unsupported name!!!")
324 self._cache.verify()
325 # return the stored copy of the colors
326 return self._data[key_colors]
327 # hashes match: colors are unmodified, return the cached object directly
328 return colors
329 else:
330 # colors have never been accessed
331 if self.kind is None:
332 # no colors are defined, so create a (count, 4) tiled
333 # copy of the default color
334 colors = np.tile(DEFAULT_MAT["material_diffuse"], (count, 1))
335 elif self.kind == "vertex" and name == "face":
336 colors = vertex_to_face_color(
337 vertex_colors=self.vertex_colors, faces=self.mesh.faces
338 )
339 elif self.kind == "face" and name == "vertex":
340 colors = face_to_vertex_color(
341 mesh=self.mesh, face_colors=self.face_colors
342 )
343 else:
344 raise ValueError("self.kind not accepted values!!")
346 if count is not None and colors.shape != (count, 4):
347 raise ValueError("face colors incorrect shape!")
349 # subclass the array to track for changes using a hash
350 colors = caching.tracked_array(colors)
351 # put the generated colors and their initial checksum into cache
352 self._cache[key_colors] = colors
353 self._cache[key_hash] = hash(colors)
355 return colors
357 def _verify_hash(self):
358 """
359 Verify the checksums of cached face and vertex color, to verify
360 that a user hasn't altered them since they were generated from
361 defaults.
363 If the colors have been altered since creation, move them into
364 the DataStore at self._data since the user action has made them
365 user data.
366 """
367 if not hasattr(self, "_cache") or len(self._cache) == 0:
368 return
370 for name in ["face", "vertex"]:
371 # the face or vertex colors
372 key_colors = str(name) + "_colors"
373 # the initial hash of the colors
374 key_hash = key_colors + "_hash"
376 if key_colors not in self._cache:
377 continue
379 colors = self._cache[key_colors]
380 # if the cached colors have been changed since creation
381 # move them to data
382 if hash(colors) != self._cache[key_hash]:
383 if name == "face":
384 self.face_colors = colors
385 elif name == "vertex":
386 self.vertex_colors = colors
387 else:
388 raise ValueError("unsupported name!!!")
389 self._cache.verify()
391 def update_vertices(self, mask: ArrayLike):
392 """
393 Apply a mask to remove or duplicate vertex properties.
394 """
395 self._update_key(mask, "vertex_colors")
397 def update_faces(self, mask: ArrayLike):
398 """
399 Apply a mask to remove or duplicate face properties
400 """
401 self._update_key(mask, "face_colors")
403 def face_subset(self, face_index: ArrayLike, copy_material: bool = True):
404 """
405 Given a mask of face indices, return a sliced version.
407 Parameters
408 ----------
409 face_index: (n,) int, mask for faces
410 (n,) bool, mask for faces
411 copy_material
412 Unused, accepted so `TextureVisuals` and `ColorVisuals`
413 take the same arguments from `util.submesh`.
415 Returns
416 ----------
417 visual: ColorVisuals object containing a subset of faces.
418 """
419 kwargs = {}
420 if self.defined:
421 if self.face_colors is not None:
422 kwargs.update(face_colors=self.face_colors[face_index])
424 if self.vertex_colors is not None:
425 indices = np.unique(self.mesh.faces[face_index].flatten())
426 vertex_colors = self.vertex_colors[indices]
427 kwargs.update(vertex_colors=vertex_colors)
429 result = ColorVisuals(**kwargs)
431 return result
433 @property
434 def main_color(self) -> NDArray[np.uint8]:
435 """
436 What is the most commonly occurring color.
438 Returns
439 ------------
440 color: (4,) uint8, most common color
441 """
442 if self.kind is None:
443 return DEFAULT_COLOR
444 elif self.kind == "face":
445 colors = self.face_colors
446 elif self.kind == "vertex":
447 colors = self.vertex_colors
448 else:
449 raise ValueError("color kind incorrect!")
451 # find the unique colors
452 unique, inverse = unique_rows(colors)
453 # the most commonly occurring color, or mode
454 # this will be an index of inverse, not colors
455 mode_index = np.bincount(inverse).argmax()
456 color = colors[unique[mode_index]]
458 return color
460 def to_texture(self):
461 """
462 Convert the current ColorVisuals object to a texture
463 with a `SimpleMaterial` defined.
465 Returns
466 ------------
467 visual : trimesh.visual.TextureVisuals
468 Copy of the current visuals as a texture.
469 """
470 from .texture import TextureVisuals
472 mat, uv = color_to_uv(vertex_colors=self.vertex_colors)
473 return TextureVisuals(material=mat, uv=uv)
475 def concatenate(self, other: Iterable[Visuals] | Visuals | ArrayLike, *args):
476 """
477 Concatenate two or more ColorVisuals objects
478 into a single object.
480 Parameters
481 -----------
482 other : ColorVisuals
483 Object to append
484 *args: ColorVisuals objects
486 Returns
487 -----------
488 result : ColorVisuals
489 Containing information from current
490 object and others in the order it was passed.
491 """
492 # avoid a circular import
493 from . import objects
495 result = objects.concatenate(self, other, *args)
496 return result
498 def _update_key(self, mask, key: Hashable):
499 """
500 Mask the value contained in the DataStore at a specified key.
502 Parameters
503 -----------
504 mask: (n,) int
505 (n,) bool
506 key : Hashable
507 Key in self._data
508 """
509 mask = np.asanyarray(mask)
510 if key in self._data:
511 self._data[key] = self._data[key][mask]
514class VertexColor(Visuals):
515 """
516 Create a simple visual object to hold just vertex colors
517 for objects such as PointClouds.
518 """
520 def __init__(self, colors=None, obj=None):
521 """
522 Create a vertex color visual
523 """
524 self.obj = obj
525 self.vertex_colors = colors
527 @property
528 def kind(self):
529 return "vertex"
531 def update_vertices(self, mask):
532 if self._colors is not None:
533 self._colors = self._colors[mask]
535 def update_faces(self, mask):
536 pass
538 @property
539 def vertex_colors(self):
540 return self._colors
542 @vertex_colors.setter
543 def vertex_colors(self, data):
544 if data is None:
545 self._colors = caching.tracked_array(None)
546 else:
547 # tile single color into color array
548 data = np.asanyarray(data)
549 if data.shape in [(3,), (4,)]:
550 data = np.tile(data, (len(self.obj.vertices), 1))
551 # track changes in colors and convert to RGBA
552 self._colors = caching.tracked_array(to_rgba(data))
554 def copy(self):
555 """
556 Return a copy of the current visuals
557 """
558 return copy.deepcopy(self)
560 def concatenate(self, other):
561 """
562 Concatenate this visual object with another
563 VertexVisuals.
565 Parameters
566 -----------
567 other : VertexColors or ColorVisuals
568 Other object to concatenate
570 Returns
571 ------------
572 concate : VertexColor
573 Object with both colors
574 """
575 return VertexColor(colors=np.vstack(self.vertex_colors, other.vertex_colors))
577 def __hash__(self):
578 return self._colors.__hash__()
581def to_rgba(colors: Any, dtype: DTypeLike = np.uint8) -> NDArray:
582 """
583 Convert a single or multiple RGB colors to RGBA colors.
585 Parameters
586 ----------
587 colors : (n, 3) or (n, 4) array
588 RGB or RGBA colors or None
590 Returns
591 ----------
592 colors : (n, 4) list of RGBA colors
593 (4,) single RGBA color
594 """
595 if colors is None:
596 return DEFAULT_COLOR
597 # if MTL uses 0 as None
598 if isinstance(colors, (int, float)) and colors == 0:
599 return DEFAULT_COLOR
601 # colors as numpy array
602 colors = np.asanyarray(colors)
603 dtype = np.dtype(dtype)
605 # what is the output dtype opaque value
606 if dtype.kind in "iu":
607 opaque = np.iinfo(dtype).max
608 elif dtype.kind == "f":
609 opaque = 1.0
610 else:
611 raise ValueError(f"Unknown dtype: `{dtype}`")
613 if colors.dtype.kind == "f":
614 # replace any `nan` or `inf` values with zero
615 colors[~np.isfinite(colors)] = 0.0
617 # multiple the 0.0 - 1.0 colors by the opaque value
618 # to scale them to the output data type's proper range
619 colors = np.clip(colors * opaque, 0.0, opaque)
621 # if the requested output type is integer-like
622 # make sure to round the multiplied floats
623 # before the `astype` on the return
624 if dtype.kind in "iu":
625 colors = colors.round()
626 elif colors.dtype.kind == "u" and dtype != colors.dtype:
627 # unsigned integer colors, but they need to be rescaled
628 # signed integers (i.e. a default `np.array([255, 0, 0])`)
629 # have no normalized range so they are passed through
630 scale = opaque / float(np.iinfo(colors.dtype).max)
632 # do the scaling as floats with rounding
633 # would this be faster with a big integer intermediate
634 # probably but then we'd have to be careful to not
635 # overflow a large intermediate vector
636 colors = (colors.astype(np.float64) * scale).round().astype(dtype)
638 if util.is_shape(colors, (-1, 3)):
639 # add an opaque alpha for RGB colors
640 colors = np.column_stack((colors, opaque * np.ones(len(colors))))
641 elif util.is_shape(colors, (3,)):
642 # if passed a single RGB color add an alpha
643 colors = np.append(colors, opaque)
644 if not (util.is_shape(colors, (4,)) or util.is_shape(colors, (-1, 4))):
645 raise ValueError("Colors not of appropriate shape!")
647 return colors.astype(dtype)
650def to_float(colors: ArrayLike) -> NDArray[np.float64]:
651 """
652 Convert integer colors to 0.0-1.0 floating point colors
654 Parameters
655 -------------
656 colors : (n, d) int
657 Integer colors
659 Returns
660 -------------
661 as_float : (n, d) float
662 Float colors 0.0 - 1.0
663 """
665 # colors as numpy array
666 colors = np.asanyarray(colors)
667 if colors.dtype.kind == "f":
668 return colors.astype(np.float64)
669 elif colors.dtype.kind in "iu":
670 # integer value for opaque alpha given our datatype
671 opaque = np.iinfo(colors.dtype).max
672 return colors.astype(np.float64) / opaque
673 else:
674 raise ValueError("only works on int or float colors!")
677def hex_to_rgba(color: str) -> NDArray[np.uint8]:
678 """
679 Turn a string hex color to a (4,) RGBA color.
681 Parameters
682 -----------
683 color: str, hex color
685 Returns
686 -----------
687 rgba: (4,) np.uint8, RGBA color
688 """
689 value = str(color).lstrip("#").strip()
690 if len(value) == 6:
691 rgb = [int(value[i : i + 2], 16) for i in (0, 2, 4)]
692 rgba = np.append(rgb, 255).astype(np.uint8)
693 else:
694 raise ValueError("Only RGB supported")
696 return rgba
699def hsv_to_rgba(hsv: ArrayLike, dtype: DTypeLike = np.uint8) -> NDArray:
700 """
701 Convert an (n, 3) array of 0.0-1.0 HSV colors into an
702 array of RGBA colors.
704 A vectorized implementation that matches `colorsys.hsv_to_rgb`.
706 Parameters
707 -----------
708 hsv
709 Should be `(n, 3)` array of 0.0-1.0 values.
711 Returns
712 ------------
713 rgba
714 An (n, 4) array of RGBA colors.
715 """
717 hsv = np.asanyarray(hsv, dtype=np.float64)
718 if len(hsv.shape) != 2 or hsv.shape[1] != 3:
719 raise ValueError("(n, 3) values of HSV are required")
720 # clip values in-place to 0.0-1.0 range
721 np.clip(hsv, a_min=0.0, a_max=1.0, out=hsv)
723 # expand into flat arrays for each of
724 # hue, saturation, and value
725 H, S, V = hsv.T
727 # chroma and other values for the equation
728 C = S * V
729 Hi = H * 6.0
730 X = C * (1.0 - np.abs((Hi % 2.0) - 1.0))
732 # stack values we need so we can access them with the lookup table
733 stacked = np.column_stack((C, X, np.zeros_like(X)))
734 # get the indexes per-row and then increment them so we can use them on the stack
735 indexes = _HSV_LOOKUP[Hi.astype(np.int64)] + (np.arange(len(H)) * 3).reshape((-1, 1))
737 # get the intermediate value, described by wikipedia as
738 # the point along the bottom three faces of the RGB cube
739 RGBi = stacked.ravel()[indexes]
741 # stack it into the final RGBA array
742 RGBA = np.column_stack((RGBi + (V - C).reshape((-1, 1)), np.ones(len(H))))
744 # now return the correct type of color
745 dtype = np.dtype(dtype)
746 if dtype.kind == "f":
747 return RGBA.astype(dtype)
748 elif dtype.kind in "iu":
749 return (RGBA * np.iinfo(dtype).max).round().astype(dtype)
751 raise ValueError(f"dtype `{dtype}` not supported")
754def linear_to_srgb(linear: ArrayLike) -> NDArray[np.float64]:
755 """
756 Converts linear color values to sRGB color values.
758 See: https://entropymine.com/imageworsener/srgbformula/
760 Parameters
761 ----------
762 linear
763 Linear color values of any shape since this
764 is a per-element transformation
766 Returns
767 ---------
768 srgb
769 Values scaled to an sRGB scale.
770 """
771 linear = to_float(linear)
773 mask = linear > 0.00313066844250063
774 srgb = np.zeros(linear.shape, dtype=np.float64)
775 srgb[mask] = 1.055 * np.power(linear[mask], (1.0 / 2.4)) - 0.055
776 srgb[~mask] = 12.92 * linear[~mask]
778 return srgb
781def srgb_to_linear(srgb: ArrayLike) -> NDArray[np.float64]:
782 """
783 Converts sRGB color values to linear color values.
784 See: https://entropymine.com/imageworsener/srgbformula/
785 """
787 # make sure the color values are floating point scaled
788 srgb = to_float(srgb)
790 mask = srgb <= 0.0404482362771082
791 linear = np.zeros(srgb.shape, dtype=np.float64)
792 linear[mask] = srgb[mask] / 12.92
793 linear[~mask] = np.power(((srgb[~mask] + 0.055) / 1.055), 2.4)
795 return linear
798def random_color(
799 dtype: DTypeLike = np.uint8,
800 count: Integer | None = None,
801 seed: Seed = None,
802) -> NDArray:
803 """
804 Return a random RGB color using datatype specified.
806 Parameters
807 ----------
808 dtype
809 Color type of result.
810 count
811 If passed return (count, 4) colors instead of
812 a single (4,) color.
813 seed
814 Seed for deterministic results, otherwise OS entropy.
816 Returns
817 ----------
818 color : (4,) or (count, 4)
819 Random color or colors that look "OK"
820 """
821 # generate a random hue
822 hue = (util.random_generator(seed).random(count or 1) + 0.61803) % 1.0
824 # saturation and "value" as constant
825 sv = np.ones_like(hue) * 0.99
826 # convert our random hue to RGBA
827 colors = hsv_to_rgba(np.column_stack((hue, sv, sv)), dtype=dtype)
829 # unspecified count is a single color
830 if count is None:
831 return colors[0]
832 return colors
835def vertex_to_face_color(vertex_colors: ArrayLike, faces: ArrayLike) -> NDArray[np.uint8]:
836 """
837 Convert a list of vertex colors to face colors.
839 Parameters
840 ----------
841 vertex_colors: (n,(3,4)), colors
842 faces: (m,3) int, face indexes
844 Returns
845 -----------
846 face_colors: (m,4) colors
847 """
848 vertex_colors = to_rgba(vertex_colors)
849 face_colors = vertex_colors[faces].mean(axis=1)
850 return face_colors.astype(np.uint8)
853def face_to_vertex_color(
854 mesh, face_colors: ArrayLike, dtype: DTypeLike = np.uint8
855) -> NDArray:
856 """
857 Convert face colors into vertex colors.
859 Parameters
860 -----------
861 mesh : trimesh.Trimesh
862 Mesh to convert colors for
863 face_colors : `(len(mesh.faces), (3 | 4))` int
864 The colors for each face of the mesh
865 dtype
866 What should colors be returned in.
868 Returns
869 -----------
870 vertex_colors : `(len(mesh.vertices), 4)`
871 Color for each vertex
872 """
873 rgba = to_rgba(face_colors)
874 vertex = mesh.faces_sparse.dot(rgba.astype(np.float64))
875 degree = mesh.vertex_degree
877 # normalize color by the number of faces including
878 # the vertex (i.e. the vertex degree)
879 nonzero = degree > 0
880 vertex[nonzero] /= degree[nonzero].reshape((-1, 1))
882 assert vertex.shape == (len(mesh.vertices), 4)
884 return vertex.astype(dtype)
887def colors_to_materials(colors: ArrayLike, count: Integer | None = None):
888 """
889 Convert a list of colors into a list of unique materials
890 and material indexes.
892 Parameters
893 -----------
894 colors : (n, 3) or (n, 4) float
895 RGB or RGBA colors
896 count : int
897 Number of entities to apply color to
899 Returns
900 -----------
901 diffuse : (m, 4) int
902 Colors
903 index : (count,) int
904 Index of each color
905 """
907 # convert RGB to RGBA
908 rgba = to_rgba(colors)
910 # if we were only passed a single color
911 if util.is_shape(rgba, (4,)) and count is not None:
912 diffuse = rgba.reshape((-1, 4))
913 index = np.zeros(count, dtype=np.int64)
914 elif util.is_shape(rgba, (-1, 4)):
915 # we were passed multiple colors
916 # find the unique colors in the list to save as materials
917 unique, index = unique_rows(rgba)
918 diffuse = rgba[unique]
919 else:
920 raise ValueError("Colors not convertible!")
922 return diffuse, index
925def linear_color_map(values: ArrayLike, color_range: ArrayLike | None = None) -> NDArray:
926 """
927 Linearly interpolate a color lookup table from normalized
928 values.
930 For example if `color_range` has two values [`a`, `b`]
931 `values` is `[0.0, 0.5, 1.0]`, this function will return
932 [`a`, `(a+b)/2`, `b`].
934 The default value for `color_range` is red-green, or you
935 can pass in a full lookup table for a color map, i.e. a
936 `(256, 3) float64` array of RGB colors such as our defaults:
937 `trimesh.resources.get_json('color_map.json.gzip')['viridis']`
939 Parameters
940 --------------
941 values : (n, ) float
942 Normalized to 0.0-1.0 values to interpolate
943 color_range : None or (n, 3|4)
944 Evenly spaced colors to interpolate through
945 where `n >= 2`.
947 Returns
948 ---------------
949 colors : (n, 4) color_range.dtype
950 RGBA colors for interpolated values
951 """
953 if color_range is None:
954 # do a very unimaginative "red to green" linear scale
955 color_range = np.array([[255, 0, 0, 255], [0, 255, 0, 255]], dtype=np.uint8)
956 else:
957 # make sure we have a numpy array
958 color_range = np.asanyarray(color_range)
960 # do simple checks on the color range shape
961 if color_range.shape[0] < 2 or color_range.shape[1] < 3:
962 raise ValueError(
963 "color_range must be RGBA convertible and have more than 2 values!"
964 )
966 # float 1D array clamped to 0.0 - 1.0
967 values = np.clip(np.asanyarray(values, dtype=np.float64).ravel(), 0.0, 1.0).reshape(
968 (-1, 1)
969 )
971 # what is the maximum index of our colors
972 max_index = len(color_range) - 1
973 # convert our normalized values into a fractional index
974 index = values.ravel() * max_index
976 # get the left and right indexes
977 # clipping should be a no-op based on above normalization but
978 # be extra sure ceil isn't pushing us out of our array range
979 bounds = np.clip(
980 np.column_stack((np.floor(index), np.ceil(index))), 0.0, max_index
981 ).astype(np.int64)
983 # get the factor of how far each point is between `bounds` pair
984 factor = index - bounds[:, 0]
986 # reshape the factor into an interpolation
987 multiplier = np.column_stack((1.0 - factor, factor)).reshape((-1, 2, 1))
989 # get both colors, multiply them by the interpolation multiplier, and sum
990 interpolated = (color_range.astype(np.float64)[bounds] * multiplier).sum(axis=1)
992 # if we're returning integers make sure to round first
993 if color_range.dtype.kind in "iu":
994 return interpolated.round().astype(color_range.dtype)
996 return interpolated.astype(color_range.dtype)
999def interpolate(
1000 values: ArrayLike,
1001 color_map: ColorMapType | Callable | None = None,
1002 dtype: DTypeLike = np.uint8,
1003) -> NDArray:
1004 """
1005 Given a 1D list of values, return interpolated colors
1006 for the range.
1008 Parameters
1009 ---------------
1010 values : (n, ) float
1011 Values to be interpolated over
1012 color_map
1013 One of the four included color maps:
1014 ("viridis", "inferno", "plasma", "magma")
1015 Or a function, `matplotlib.pyplot.get_cmap
1018 Returns
1019 -------------
1020 interpolated : (n, 4) dtype
1021 Interpolated RGBA colors
1022 """
1024 # make `viridis` the default just like everyone else
1025 if color_map is None:
1026 color_map = "viridis"
1028 if callable(color_map):
1029 # should be a `matplotlib.pyplot.get_cmap` callable
1030 cmap = color_map
1031 elif isinstance(color_map, str):
1032 # color map is a named key in our packaged color maps
1033 available = get_json("color_map.json.gzip")
1034 if color_map not in available:
1035 # we could have added a fallback to matplotlib:
1036 # `from matplotlib.pyplot import get_cmap; cmap = get_cmap(name)`
1037 # but we don't want trimesh to depend on matplotlib as it is quite heavy
1038 raise ValueError(
1039 f"Included color maps are: {available.keys()}.\n\n"
1040 + "If you want to use a `matplotlib` color map you can "
1041 + "pass it as `color_map=matplotlib.pyplot.get_cmap(name)`"
1042 )
1044 # pass in the retrieved color map values to linear_color_map
1045 def cmap(x):
1046 return linear_color_map(x, np.array(available[color_map]))
1047 else:
1048 raise TypeError(f"Unknown color map: `{type(color_map)}`")
1050 # make input always float
1051 values = np.asanyarray(values, dtype=np.float64).ravel()
1053 # get both minumium and maximum values for range normalization
1054 v_min, v_max = values.min(), values.max()
1055 # offset to zero
1056 values -= v_min
1057 # normalize to the 0.0 - 1.0 range
1058 if v_min != v_max:
1059 values /= v_max - v_min
1061 # scale values to 0.0 - 1.0 and get colors
1062 colors = cmap(values)
1064 # convert to 0-255 RGBA
1065 rgba = to_rgba(colors, dtype=dtype)
1067 return rgba
1070def uv_to_color(uv, image) -> NDArray[np.uint8]:
1071 """
1072 Get the color in a texture image.
1074 Parameters
1075 -------------
1076 uv : (n, 2) float
1077 UV coordinates on texture image
1078 image : PIL.Image
1079 Texture image
1081 Returns
1082 ----------
1083 colors : (n, 4) uint4
1084 RGBA color at each of the UV coordinates
1085 """
1086 if image is None or uv is None:
1087 return None
1089 # UV coordinates should be (n, 2) float
1090 uv = np.asanyarray(uv, dtype=np.float64)
1092 # get texture image pixel positions of UV coordinates
1093 x = (uv[:, 0] * (image.width - 1)) % image.width
1094 y = ((1 - uv[:, 1]) * (image.height - 1)) % image.height
1096 # access colors from pixel locations
1097 # make sure image is RGBA before getting values
1098 colors = np.asanyarray(image.convert("RGBA"))[
1099 y.round().astype(np.int64) % image.height,
1100 x.round().astype(np.int64) % image.width,
1101 ]
1103 # conversion to RGBA should have corrected shape
1104 assert colors.ndim == 2 and colors.shape[1] == 4
1105 assert colors.dtype == np.uint8
1107 return colors
1110def uv_to_interpolated_color(uv: ArrayLike, image) -> NDArray[np.uint8]:
1111 """
1112 Get the color from texture image using bilinear sampling.
1114 Parameters
1115 -------------
1116 uv : (n, 2) float
1117 UV coordinates on texture image
1118 image : PIL.Image
1119 Texture image
1121 Returns
1122 ----------
1123 colors : (n, 4) uint8
1124 RGBA color at each of the UV coordinates.
1125 """
1126 if image is None or uv is None:
1127 return None
1129 # UV coordinates should be (n, 2) float
1130 uv = np.asanyarray(uv, dtype=np.float64)
1132 # get texture image pixel positions of UV coordinates
1133 x = uv[:, 0] * (image.width - 1)
1134 y = (1 - uv[:, 1]) * (image.height - 1)
1136 x_floor = np.floor(x).astype(np.int64) % image.width
1137 y_floor = np.floor(y).astype(np.int64) % image.height
1139 x_ceil = np.ceil(x).astype(np.int64) % image.width
1140 y_ceil = np.ceil(y).astype(np.int64) % image.height
1142 dx = x % image.width - x_floor
1143 dy = y % image.height - y_floor
1145 img = np.asanyarray(image.convert("RGBA"))
1147 colors00 = img[y_floor, x_floor]
1148 colors01 = img[y_floor, x_ceil]
1149 colors10 = img[y_ceil, x_floor]
1150 colors11 = img[y_ceil, x_ceil]
1152 a00 = (1 - dx) * (1 - dy)
1153 a01 = dx * (1 - dy)
1154 a10 = (1 - dx) * dy
1155 a11 = dx * dy
1157 a00 = np.repeat(a00[:, None], 4, axis=1)
1158 a01 = np.repeat(a01[:, None], 4, axis=1)
1159 a10 = np.repeat(a10[:, None], 4, axis=1)
1160 a11 = np.repeat(a11[:, None], 4, axis=1)
1162 # interpolated colors as floating point then convert back to uint8
1163 colors = (
1164 (a00 * colors00 + a01 * colors01 + a10 * colors10 + a11 * colors11)
1165 .round()
1166 .astype(np.uint8)
1167 )
1169 # conversion to RGBA should have corrected shape
1170 assert colors.ndim == 2 and colors.shape[1] == 4
1171 assert colors.dtype == np.uint8
1173 return colors
1176def color_to_uv(vertex_colors: ArrayLike):
1177 """
1178 Pack vertex colors into UV coordinates and a simple image material
1180 Parameters
1181 ------------
1182 vertex_colors : (n, 4) float
1183 Array of vertex colors.
1185 Returns
1186 ------------
1187 material : SimpleMaterial
1188 Material containing color information.
1189 uv : (n, 2) float
1190 Normalized UV coordinates
1191 """
1192 from .material import SimpleMaterial, empty_material
1194 # deduplicate the vertex colors
1195 unique, inverse = unique_rows(vertex_colors)
1197 # if there is only one color return a
1198 if len(unique) == 1:
1199 # return a simple single-pixel material
1200 material = empty_material(color=vertex_colors[unique[0]])
1201 uvs = np.zeros((len(vertex_colors), 2)) + 0.5
1202 return material, uvs
1204 from PIL import Image
1206 # return a square image of (size, size)
1207 size = int(np.ceil(np.sqrt(len(unique))))
1208 ctype = vertex_colors.shape[1]
1210 colors = np.zeros((size**2, ctype), dtype=vertex_colors.dtype)
1211 colors[: len(unique)] = vertex_colors[unique]
1213 # PIL has reversed x-y coordinates
1214 image = Image.fromarray(colors.reshape((size, size, ctype))[::-1])
1216 pos = np.arange(len(unique))
1217 # create tiled coordinates for the color pixels
1218 coords = np.column_stack((pos % size, np.floor(pos / size)))
1220 # normalize the index coords into 0.0 - 1.0
1221 # and offset them to be centered on the pixel
1222 coords = (coords / size) + (1.0 / (size * 2.0))
1223 uvs = coords[inverse]
1225 if tol.strict:
1226 # check the packed colors against the image
1227 check = uv_to_color(image=image, uv=uvs)
1228 assert np.all(check == vertex_colors)
1230 return SimpleMaterial(image=image), uvs
1233# set an arbitrary grey as the default color
1234DEFAULT_COLOR = np.array([102, 102, 102, 255], dtype=np.uint8)
1235DEFAULT_MAT = {
1236 "material_diffuse": np.array([102, 102, 102, 255], dtype=np.uint8),
1237 "material_ambient": np.array([64, 64, 64, 255], dtype=np.uint8),
1238 "material_specular": np.array([197, 197, 197, 255], dtype=np.uint8),
1239 "material_shine": 77.0,
1240}