Coverage for trimesh/visual/color.py: 86%
411 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-12 17:18 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-12 17:18 +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 Integer,
40 Iterable,
41 NDArray,
42 Seed,
43)
44from .base import Visuals
46# Save a lookup table for an integer to match the
47# cases for HSV conversion specified on the wikipedia article
48# Where indexes 0=C, 1=X, 2=0.0
49_HSV_LOOKUP = np.array(
50 [[0, 1, 2], [1, 0, 2], [2, 0, 1], [2, 1, 0], [1, 2, 0], [0, 2, 1]], dtype=np.int64
51)
52_HSV_LOOKUP.flags.writeable = False
55class ColorVisuals(Visuals):
56 """
57 Store color information about a mesh.
58 """
60 def __init__(
61 self,
62 mesh=None,
63 face_colors: ArrayLike | None = None,
64 vertex_colors: ArrayLike | None = None,
65 ):
66 """
67 Store color information about a mesh.
69 Parameters
70 ----------
71 mesh : Trimesh
72 Object that these visual properties
73 are associated with
74 face_ colors : (n,3|4) or (3,) or (4,) uint8
75 Colors per-face
76 vertex_colors : (n,3|4) or (3,) or (4,) uint8
77 Colors per-vertex
78 """
79 self.mesh = mesh
80 self._data = caching.DataStore()
81 self._cache = caching.Cache(id_function=self._data.__hash__)
83 try:
84 if face_colors is not None:
85 self.face_colors = face_colors
86 if vertex_colors is not None:
87 self.vertex_colors = vertex_colors
88 except ValueError:
89 util.log.warning("unable to convert colors!")
91 @caching.cache_decorator
92 def transparency(self) -> bool:
93 """
94 Does the current object contain any transparency.
96 Returns
97 ----------
98 transparency: bool, does the current visual contain transparency
99 """
100 if "vertex_colors" in self._data:
101 a_min = self._data["vertex_colors"][:, 3].min()
102 elif "face_colors" in self._data:
103 a_min = self._data["face_colors"][:, 3].min()
104 else:
105 return False
107 return bool(a_min < 255)
109 @property
110 def defined(self) -> bool:
111 """
112 Are any colors defined for the current mesh.
114 Returns
115 ---------
116 defined : bool
117 Are colors defined or not.
118 """
119 return self.kind is not None
121 @property
122 def kind(self) -> str | None:
123 """
124 What color mode has been set.
126 Returns
127 ----------
128 mode : str or None
129 One of ('face', 'vertex', None)
130 """
131 # if nothing is stored anywhere it's a safe bet mode is None
132 if not (len(self._cache.cache) > 0 or len(self._data.data) > 0):
133 return None
135 self._verify_hash()
137 # check modes in data
138 if "vertex_colors" in self._data:
139 return "vertex"
140 elif "face_colors" in self._data:
141 return "face"
143 return None
145 def __hash__(self):
146 return self._data.__hash__()
148 def copy(self) -> "ColorVisuals":
149 """
150 Return a copy of the current ColorVisuals object.
153 Returns
154 ----------
155 copied : ColorVisuals
156 Contains the same information as self
157 """
158 copied = ColorVisuals()
159 # call the literally insane generators to validate
160 self.face_colors # noqa
161 self.vertex_colors # noqa
162 # copy anything that's actually data
163 copied._data.data = copy.deepcopy(self._data.data)
165 return copied
167 @property
168 def face_colors(self) -> NDArray[np.uint8]:
169 """
170 Colors defined for each face of a mesh.
172 If no colors are defined, defaults are returned.
174 Returns
175 ----------
176 colors : (len(mesh.faces), 4) uint8
177 RGBA color for each face
178 """
179 return self._get_colors(name="face")
181 @face_colors.setter
182 def face_colors(self, values: ArrayLike):
183 """
184 Set the colors for each face of a mesh.
186 This will apply these colors and delete any previously specified
187 color information.
189 Parameters
190 ------------
191 colors : (len(mesh.faces), 3), set each face to the specified color
192 (len(mesh.faces), 4), set each face to the specified color
193 (3,) int, set the whole mesh this color
194 (4,) int, set the whole mesh this color
195 """
196 if values is None:
197 if "face_colors" in self._data:
198 self._data.data.pop("face_colors")
199 return
201 colors = to_rgba(values)
203 if self.mesh is not None and colors.shape == (4,):
204 count = len(self.mesh.faces)
205 colors = np.tile(colors, (count, 1))
207 # if we set any color information, clear the others
208 self._data.clear()
209 self._data["face_colors"] = colors
210 self._cache.verify()
212 @property
213 def vertex_colors(self) -> NDArray[np.uint8]:
214 """
215 Return the colors for each vertex of a mesh
217 Returns
218 ------------
219 colors: (len(mesh.vertices), 4) uint8, color for each vertex
220 """
221 return self._get_colors(name="vertex")
223 @vertex_colors.setter
224 def vertex_colors(self, values: ArrayLike):
225 """
226 Set the colors for each vertex of a mesh
228 This will apply these colors and delete any previously specified
229 color information.
231 Parameters
232 ------------
233 colors : (len(mesh.vertices), 3), set each face to the color
234 (len(mesh.vertices), 4), set each face to the color
235 (3,) int, set the whole mesh this color
236 (4,) int, set the whole mesh this color
237 """
238 if values is None:
239 if "vertex_colors" in self._data:
240 self._data.data.pop("vertex_colors")
241 return
243 # make sure passed values are numpy array
244 values = np.asanyarray(values)
245 # Ensure the color shape is sane
246 if self.mesh is not None and not (
247 values.shape == (len(self.mesh.vertices), 3)
248 or values.shape == (len(self.mesh.vertices), 4)
249 or values.shape == (3,)
250 or values.shape == (4,)
251 ):
252 return
254 colors = to_rgba(values)
255 if self.mesh is not None and colors.shape == (4,):
256 count = len(self.mesh.vertices)
257 colors = np.tile(colors, (count, 1))
259 # if we set any color information, clear the others
260 self._data.clear()
261 self._data["vertex_colors"] = colors
262 self._cache.verify()
264 def _get_colors(self, name):
265 """
266 A magical function which maintains the sanity of vertex and face colors.
268 * If colors have been explicitly stored or changed, they are considered
269 user data, stored in self._data (DataStore), and are returned immediately
270 when requested.
271 * If colors have never been set, a (count,4) tiled copy of the default diffuse
272 color will be stored in the cache
273 ** the hash on creation for these cached default colors will also be stored
274 ** if the cached color array is altered (different hash than when it was
275 created) we consider that now to be user data and the array is moved from
276 the cache to the DataStore.
278 Parameters
279 -----------
280 name : str
281 Values 'face' or 'vertex'
283 Returns
284 -----------
285 colors : (count, 4) uint8
286 RGBA colors
287 """
289 count = None
290 try:
291 if name == "face":
292 count = len(self.mesh.faces)
293 elif name == "vertex":
294 count = len(self.mesh.vertices)
295 except BaseException:
296 pass
298 # the face or vertex colors
299 key_colors = str(name) + "_colors"
300 # the initial hash of the colors
301 key_hash = key_colors + "_hash"
303 if key_colors in self._data:
304 # if a user has explicitly stored or changed the color it
305 # will be in data
306 return self._data[key_colors]
308 elif key_colors in self._cache:
309 # if the colors have been autogenerated already they
310 # will be in the cache
311 colors = self._cache[key_colors]
312 # if the cached colors have been changed since creation we move
313 # them to data
314 if hash(colors) != self._cache[key_hash]:
315 # cached colors were mutated — promote to user data via
316 # the appropriate property setter
317 if name == "face":
318 self.face_colors = colors
319 elif name == "vertex":
320 self.vertex_colors = colors
321 else:
322 raise ValueError("unsupported name!!!")
323 self._cache.verify()
324 # return the stored copy of the colors
325 return self._data[key_colors]
326 # hashes match: colors are unmodified, return the cached object directly
327 return colors
328 else:
329 # colors have never been accessed
330 if self.kind is None:
331 # no colors are defined, so create a (count, 4) tiled
332 # copy of the default color
333 colors = np.tile(DEFAULT_MAT["material_diffuse"], (count, 1))
334 elif self.kind == "vertex" and name == "face":
335 colors = vertex_to_face_color(
336 vertex_colors=self.vertex_colors, faces=self.mesh.faces
337 )
338 elif self.kind == "face" and name == "vertex":
339 colors = face_to_vertex_color(
340 mesh=self.mesh, face_colors=self.face_colors
341 )
342 else:
343 raise ValueError("self.kind not accepted values!!")
345 if count is not None and colors.shape != (count, 4):
346 raise ValueError("face colors incorrect shape!")
348 # subclass the array to track for changes using a hash
349 colors = caching.tracked_array(colors)
350 # put the generated colors and their initial checksum into cache
351 self._cache[key_colors] = colors
352 self._cache[key_hash] = hash(colors)
354 return colors
356 def _verify_hash(self):
357 """
358 Verify the checksums of cached face and vertex color, to verify
359 that a user hasn't altered them since they were generated from
360 defaults.
362 If the colors have been altered since creation, move them into
363 the DataStore at self._data since the user action has made them
364 user data.
365 """
366 if not hasattr(self, "_cache") or len(self._cache) == 0:
367 return
369 for name in ["face", "vertex"]:
370 # the face or vertex colors
371 key_colors = str(name) + "_colors"
372 # the initial hash of the colors
373 key_hash = key_colors + "_hash"
375 if key_colors not in self._cache:
376 continue
378 colors = self._cache[key_colors]
379 # if the cached colors have been changed since creation
380 # move them to data
381 if hash(colors) != self._cache[key_hash]:
382 if name == "face":
383 self.face_colors = colors
384 elif name == "vertex":
385 self.vertex_colors = colors
386 else:
387 raise ValueError("unsupported name!!!")
388 self._cache.verify()
390 def update_vertices(self, mask: ArrayLike):
391 """
392 Apply a mask to remove or duplicate vertex properties.
393 """
394 self._update_key(mask, "vertex_colors")
396 def update_faces(self, mask: ArrayLike):
397 """
398 Apply a mask to remove or duplicate face properties
399 """
400 self._update_key(mask, "face_colors")
402 def face_subset(self, face_index: ArrayLike, copy_material: bool = True):
403 """
404 Given a mask of face indices, return a sliced version.
406 Parameters
407 ----------
408 face_index: (n,) int, mask for faces
409 (n,) bool, mask for faces
410 copy_material
411 Unused, accepted so `TextureVisuals` and `ColorVisuals`
412 take the same arguments from `util.submesh`.
414 Returns
415 ----------
416 visual: ColorVisuals object containing a subset of faces.
417 """
418 kwargs = {}
419 if self.defined:
420 if self.face_colors is not None:
421 kwargs.update(face_colors=self.face_colors[face_index])
423 if self.vertex_colors is not None:
424 indices = np.unique(self.mesh.faces[face_index].flatten())
425 vertex_colors = self.vertex_colors[indices]
426 kwargs.update(vertex_colors=vertex_colors)
428 result = ColorVisuals(**kwargs)
430 return result
432 @property
433 def main_color(self) -> NDArray[np.uint8]:
434 """
435 What is the most commonly occurring color.
437 Returns
438 ------------
439 color: (4,) uint8, most common color
440 """
441 if self.kind is None:
442 return DEFAULT_COLOR
443 elif self.kind == "face":
444 colors = self.face_colors
445 elif self.kind == "vertex":
446 colors = self.vertex_colors
447 else:
448 raise ValueError("color kind incorrect!")
450 # find the unique colors
451 unique, inverse = unique_rows(colors)
452 # the most commonly occurring color, or mode
453 # this will be an index of inverse, not colors
454 mode_index = np.bincount(inverse).argmax()
455 color = colors[unique[mode_index]]
457 return color
459 def to_texture(self):
460 """
461 Convert the current ColorVisuals object to a texture
462 with a `SimpleMaterial` defined.
464 Returns
465 ------------
466 visual : trimesh.visual.TextureVisuals
467 Copy of the current visuals as a texture.
468 """
469 from .texture import TextureVisuals
471 mat, uv = color_to_uv(vertex_colors=self.vertex_colors)
472 return TextureVisuals(material=mat, uv=uv)
474 def concatenate(self, other: Iterable[Visuals] | Visuals | ArrayLike, *args):
475 """
476 Concatenate two or more ColorVisuals objects
477 into a single object.
479 Parameters
480 -----------
481 other : ColorVisuals
482 Object to append
483 *args: ColorVisuals objects
485 Returns
486 -----------
487 result : ColorVisuals
488 Containing information from current
489 object and others in the order it was passed.
490 """
491 # avoid a circular import
492 from . import objects
494 result = objects.concatenate(self, other, *args)
495 return result
497 def _update_key(self, mask, key):
498 """
499 Mask the value contained in the DataStore at a specified key.
501 Parameters
502 -----------
503 mask: (n,) int
504 (n,) bool
505 key: hashable object, in self._data
506 """
507 mask = np.asanyarray(mask)
508 if key in self._data:
509 self._data[key] = self._data[key][mask]
512class VertexColor(Visuals):
513 """
514 Create a simple visual object to hold just vertex colors
515 for objects such as PointClouds.
516 """
518 def __init__(self, colors=None, obj=None):
519 """
520 Create a vertex color visual
521 """
522 self.obj = obj
523 self.vertex_colors = colors
525 @property
526 def kind(self):
527 return "vertex"
529 def update_vertices(self, mask):
530 if self._colors is not None:
531 self._colors = self._colors[mask]
533 def update_faces(self, mask):
534 pass
536 @property
537 def vertex_colors(self):
538 return self._colors
540 @vertex_colors.setter
541 def vertex_colors(self, data):
542 if data is None:
543 self._colors = caching.tracked_array(None)
544 else:
545 # tile single color into color array
546 data = np.asanyarray(data)
547 if data.shape in [(3,), (4,)]:
548 data = np.tile(data, (len(self.obj.vertices), 1))
549 # track changes in colors and convert to RGBA
550 self._colors = caching.tracked_array(to_rgba(data))
552 def copy(self):
553 """
554 Return a copy of the current visuals
555 """
556 return copy.deepcopy(self)
558 def concatenate(self, other):
559 """
560 Concatenate this visual object with another
561 VertexVisuals.
563 Parameters
564 -----------
565 other : VertexColors or ColorVisuals
566 Other object to concatenate
568 Returns
569 ------------
570 concate : VertexColor
571 Object with both colors
572 """
573 return VertexColor(colors=np.vstack(self.vertex_colors, other.vertex_colors))
575 def __hash__(self):
576 return self._colors.__hash__()
579def to_rgba(colors: Any, dtype: DTypeLike = np.uint8) -> NDArray:
580 """
581 Convert a single or multiple RGB colors to RGBA colors.
583 Parameters
584 ----------
585 colors : (n, 3) or (n, 4) array
586 RGB or RGBA colors or None
588 Returns
589 ----------
590 colors : (n, 4) list of RGBA colors
591 (4,) single RGBA color
592 """
593 if colors is None:
594 return DEFAULT_COLOR
595 # if MTL uses 0 as None
596 if isinstance(colors, (int, float)) and colors == 0:
597 return DEFAULT_COLOR
599 # colors as numpy array
600 colors = np.asanyarray(colors)
601 dtype = np.dtype(dtype)
603 # what is the output dtype opaque value
604 if dtype.kind in "iu":
605 opaque = np.iinfo(dtype).max
606 elif dtype.kind == "f":
607 opaque = 1.0
608 else:
609 raise ValueError(f"Unknown dtype: `{dtype}`")
611 if colors.dtype.kind == "f":
612 # replace any `nan` or `inf` values with zero
613 colors[~np.isfinite(colors)] = 0.0
615 # multiple the 0.0 - 1.0 colors by the opaque value
616 # to scale them to the output data type's proper range
617 colors = np.clip(colors * opaque, 0.0, opaque)
619 # if the requested output type is integer-like
620 # make sure to round the multiplied floats
621 # before the `astype` on the return
622 if dtype.kind in "iu":
623 colors = colors.round()
624 elif colors.dtype.kind == "u" and dtype != colors.dtype:
625 # unsigned integer colors, but they need to be rescaled
626 # signed integers (i.e. a default `np.array([255, 0, 0])`)
627 # have no normalized range so they are passed through
628 scale = opaque / float(np.iinfo(colors.dtype).max)
630 # do the scaling as floats with rounding
631 # would this be faster with a big integer intermediate
632 # probably but then we'd have to be careful to not
633 # overflow a large intermediate vector
634 colors = (colors.astype(np.float64) * scale).round().astype(dtype)
636 if util.is_shape(colors, (-1, 3)):
637 # add an opaque alpha for RGB colors
638 colors = np.column_stack((colors, opaque * np.ones(len(colors))))
639 elif util.is_shape(colors, (3,)):
640 # if passed a single RGB color add an alpha
641 colors = np.append(colors, opaque)
642 if not (util.is_shape(colors, (4,)) or util.is_shape(colors, (-1, 4))):
643 raise ValueError("Colors not of appropriate shape!")
645 return colors.astype(dtype)
648def to_float(colors: ArrayLike) -> NDArray[np.float64]:
649 """
650 Convert integer colors to 0.0-1.0 floating point colors
652 Parameters
653 -------------
654 colors : (n, d) int
655 Integer colors
657 Returns
658 -------------
659 as_float : (n, d) float
660 Float colors 0.0 - 1.0
661 """
663 # colors as numpy array
664 colors = np.asanyarray(colors)
665 if colors.dtype.kind == "f":
666 return colors.astype(np.float64)
667 elif colors.dtype.kind in "iu":
668 # integer value for opaque alpha given our datatype
669 opaque = np.iinfo(colors.dtype).max
670 return colors.astype(np.float64) / opaque
671 else:
672 raise ValueError("only works on int or float colors!")
675def hex_to_rgba(color: str) -> NDArray[np.uint8]:
676 """
677 Turn a string hex color to a (4,) RGBA color.
679 Parameters
680 -----------
681 color: str, hex color
683 Returns
684 -----------
685 rgba: (4,) np.uint8, RGBA color
686 """
687 value = str(color).lstrip("#").strip()
688 if len(value) == 6:
689 rgb = [int(value[i : i + 2], 16) for i in (0, 2, 4)]
690 rgba = np.append(rgb, 255).astype(np.uint8)
691 else:
692 raise ValueError("Only RGB supported")
694 return rgba
697def hsv_to_rgba(hsv: ArrayLike, dtype: DTypeLike = np.uint8) -> NDArray:
698 """
699 Convert an (n, 3) array of 0.0-1.0 HSV colors into an
700 array of RGBA colors.
702 A vectorized implementation that matches `colorsys.hsv_to_rgb`.
704 Parameters
705 -----------
706 hsv
707 Should be `(n, 3)` array of 0.0-1.0 values.
709 Returns
710 ------------
711 rgba
712 An (n, 4) array of RGBA colors.
713 """
715 hsv = np.asanyarray(hsv, dtype=np.float64)
716 if len(hsv.shape) != 2 or hsv.shape[1] != 3:
717 raise ValueError("(n, 3) values of HSV are required")
718 # clip values in-place to 0.0-1.0 range
719 np.clip(hsv, a_min=0.0, a_max=1.0, out=hsv)
721 # expand into flat arrays for each of
722 # hue, saturation, and value
723 H, S, V = hsv.T
725 # chroma and other values for the equation
726 C = S * V
727 Hi = H * 6.0
728 X = C * (1.0 - np.abs((Hi % 2.0) - 1.0))
730 # stack values we need so we can access them with the lookup table
731 stacked = np.column_stack((C, X, np.zeros_like(X)))
732 # get the indexes per-row and then increment them so we can use them on the stack
733 indexes = _HSV_LOOKUP[Hi.astype(np.int64)] + (np.arange(len(H)) * 3).reshape((-1, 1))
735 # get the intermediate value, described by wikipedia as
736 # the point along the bottom three faces of the RGB cube
737 RGBi = stacked.ravel()[indexes]
739 # stack it into the final RGBA array
740 RGBA = np.column_stack((RGBi + (V - C).reshape((-1, 1)), np.ones(len(H))))
742 # now return the correct type of color
743 dtype = np.dtype(dtype)
744 if dtype.kind == "f":
745 return RGBA.astype(dtype)
746 elif dtype.kind in "iu":
747 return (RGBA * np.iinfo(dtype).max).round().astype(dtype)
749 raise ValueError(f"dtype `{dtype}` not supported")
752def linear_to_srgb(linear: ArrayLike) -> NDArray[np.float64]:
753 """
754 Converts linear color values to sRGB color values.
756 See: https://entropymine.com/imageworsener/srgbformula/
758 Parameters
759 ----------
760 linear
761 Linear color values of any shape since this
762 is a per-element transformation
764 Returns
765 ---------
766 srgb
767 Values scaled to an sRGB scale.
768 """
769 linear = to_float(linear)
771 mask = linear > 0.00313066844250063
772 srgb = np.zeros(linear.shape, dtype=np.float64)
773 srgb[mask] = 1.055 * np.power(linear[mask], (1.0 / 2.4)) - 0.055
774 srgb[~mask] = 12.92 * linear[~mask]
776 return srgb
779def srgb_to_linear(srgb: ArrayLike) -> NDArray[np.float64]:
780 """
781 Converts sRGB color values to linear color values.
782 See: https://entropymine.com/imageworsener/srgbformula/
783 """
785 # make sure the color values are floating point scaled
786 srgb = to_float(srgb)
788 mask = srgb <= 0.0404482362771082
789 linear = np.zeros(srgb.shape, dtype=np.float64)
790 linear[mask] = srgb[mask] / 12.92
791 linear[~mask] = np.power(((srgb[~mask] + 0.055) / 1.055), 2.4)
793 return linear
796def random_color(
797 dtype: DTypeLike = np.uint8,
798 count: Integer | None = None,
799 seed: Seed = None,
800) -> NDArray:
801 """
802 Return a random RGB color using datatype specified.
804 Parameters
805 ----------
806 dtype
807 Color type of result.
808 count
809 If passed return (count, 4) colors instead of
810 a single (4,) color.
811 seed
812 Seed for deterministic results, otherwise OS entropy.
814 Returns
815 ----------
816 color : (4,) or (count, 4)
817 Random color or colors that look "OK"
818 """
819 # generate a random hue
820 hue = (util.random_generator(seed).random(count or 1) + 0.61803) % 1.0
822 # saturation and "value" as constant
823 sv = np.ones_like(hue) * 0.99
824 # convert our random hue to RGBA
825 colors = hsv_to_rgba(np.column_stack((hue, sv, sv)), dtype=dtype)
827 # unspecified count is a single color
828 if count is None:
829 return colors[0]
830 return colors
833def vertex_to_face_color(vertex_colors: ArrayLike, faces: ArrayLike) -> NDArray[np.uint8]:
834 """
835 Convert a list of vertex colors to face colors.
837 Parameters
838 ----------
839 vertex_colors: (n,(3,4)), colors
840 faces: (m,3) int, face indexes
842 Returns
843 -----------
844 face_colors: (m,4) colors
845 """
846 vertex_colors = to_rgba(vertex_colors)
847 face_colors = vertex_colors[faces].mean(axis=1)
848 return face_colors.astype(np.uint8)
851def face_to_vertex_color(
852 mesh, face_colors: ArrayLike, dtype: DTypeLike = np.uint8
853) -> NDArray:
854 """
855 Convert face colors into vertex colors.
857 Parameters
858 -----------
859 mesh : trimesh.Trimesh
860 Mesh to convert colors for
861 face_colors : `(len(mesh.faces), (3 | 4))` int
862 The colors for each face of the mesh
863 dtype
864 What should colors be returned in.
866 Returns
867 -----------
868 vertex_colors : `(len(mesh.vertices), 4)`
869 Color for each vertex
870 """
871 rgba = to_rgba(face_colors)
872 vertex = mesh.faces_sparse.dot(rgba.astype(np.float64))
873 degree = mesh.vertex_degree
875 # normalize color by the number of faces including
876 # the vertex (i.e. the vertex degree)
877 nonzero = degree > 0
878 vertex[nonzero] /= degree[nonzero].reshape((-1, 1))
880 assert vertex.shape == (len(mesh.vertices), 4)
882 return vertex.astype(dtype)
885def colors_to_materials(colors: ArrayLike, count: Integer | None = None):
886 """
887 Convert a list of colors into a list of unique materials
888 and material indexes.
890 Parameters
891 -----------
892 colors : (n, 3) or (n, 4) float
893 RGB or RGBA colors
894 count : int
895 Number of entities to apply color to
897 Returns
898 -----------
899 diffuse : (m, 4) int
900 Colors
901 index : (count,) int
902 Index of each color
903 """
905 # convert RGB to RGBA
906 rgba = to_rgba(colors)
908 # if we were only passed a single color
909 if util.is_shape(rgba, (4,)) and count is not None:
910 diffuse = rgba.reshape((-1, 4))
911 index = np.zeros(count, dtype=np.int64)
912 elif util.is_shape(rgba, (-1, 4)):
913 # we were passed multiple colors
914 # find the unique colors in the list to save as materials
915 unique, index = unique_rows(rgba)
916 diffuse = rgba[unique]
917 else:
918 raise ValueError("Colors not convertible!")
920 return diffuse, index
923def linear_color_map(values: ArrayLike, color_range: ArrayLike | None = None) -> NDArray:
924 """
925 Linearly interpolate a color lookup table from normalized
926 values.
928 For example if `color_range` has two values [`a`, `b`]
929 `values` is `[0.0, 0.5, 1.0]`, this function will return
930 [`a`, `(a+b)/2`, `b`].
932 The default value for `color_range` is red-green, or you
933 can pass in a full lookup table for a color map, i.e. a
934 `(256, 3) float64` array of RGB colors such as our defaults:
935 `trimesh.resources.get_json('color_map.json.gzip')['viridis']`
937 Parameters
938 --------------
939 values : (n, ) float
940 Normalized to 0.0-1.0 values to interpolate
941 color_range : None or (n, 3|4)
942 Evenly spaced colors to interpolate through
943 where `n >= 2`.
945 Returns
946 ---------------
947 colors : (n, 4) color_range.dtype
948 RGBA colors for interpolated values
949 """
951 if color_range is None:
952 # do a very unimaginative "red to green" linear scale
953 color_range = np.array([[255, 0, 0, 255], [0, 255, 0, 255]], dtype=np.uint8)
954 else:
955 # make sure we have a numpy array
956 color_range = np.asanyarray(color_range)
958 # do simple checks on the color range shape
959 if color_range.shape[0] < 2 or color_range.shape[1] < 3:
960 raise ValueError(
961 "color_range must be RGBA convertible and have more than 2 values!"
962 )
964 # float 1D array clamped to 0.0 - 1.0
965 values = np.clip(np.asanyarray(values, dtype=np.float64).ravel(), 0.0, 1.0).reshape(
966 (-1, 1)
967 )
969 # what is the maximum index of our colors
970 max_index = len(color_range) - 1
971 # convert our normalized values into a fractional index
972 index = values.ravel() * max_index
974 # get the left and right indexes
975 # clipping should be a no-op based on above normalization but
976 # be extra sure ceil isn't pushing us out of our array range
977 bounds = np.clip(
978 np.column_stack((np.floor(index), np.ceil(index))), 0.0, max_index
979 ).astype(np.int64)
981 # get the factor of how far each point is between `bounds` pair
982 factor = index - bounds[:, 0]
984 # reshape the factor into an interpolation
985 multiplier = np.column_stack((1.0 - factor, factor)).reshape((-1, 2, 1))
987 # get both colors, multiply them by the interpolation multiplier, and sum
988 interpolated = (color_range.astype(np.float64)[bounds] * multiplier).sum(axis=1)
990 # if we're returning integers make sure to round first
991 if color_range.dtype.kind in "iu":
992 return interpolated.round().astype(color_range.dtype)
994 return interpolated.astype(color_range.dtype)
997def interpolate(
998 values: ArrayLike,
999 color_map: ColorMapType | Callable | None = None,
1000 dtype: DTypeLike = np.uint8,
1001) -> NDArray:
1002 """
1003 Given a 1D list of values, return interpolated colors
1004 for the range.
1006 Parameters
1007 ---------------
1008 values : (n, ) float
1009 Values to be interpolated over
1010 color_map
1011 One of the four included color maps:
1012 ("viridis", "inferno", "plasma", "magma")
1013 Or a function, `matplotlib.pyplot.get_cmap
1016 Returns
1017 -------------
1018 interpolated : (n, 4) dtype
1019 Interpolated RGBA colors
1020 """
1022 # make `viridis` the default just like everyone else
1023 if color_map is None:
1024 color_map = "viridis"
1026 if callable(color_map):
1027 # should be a `matplotlib.pyplot.get_cmap` callable
1028 cmap = color_map
1029 elif isinstance(color_map, str):
1030 # color map is a named key in our packaged color maps
1031 available = get_json("color_map.json.gzip")
1032 if color_map not in available:
1033 # we could have added a fallback to matplotlib:
1034 # `from matplotlib.pyplot import get_cmap; cmap = get_cmap(name)`
1035 # but we don't want trimesh to depend on matplotlib as it is quite heavy
1036 raise ValueError(
1037 f"Included color maps are: {available.keys()}.\n\n"
1038 + "If you want to use a `matplotlib` color map you can "
1039 + "pass it as `color_map=matplotlib.pyplot.get_cmap(name)`"
1040 )
1042 # pass in the retrieved color map values to linear_color_map
1043 def cmap(x):
1044 return linear_color_map(x, np.array(available[color_map]))
1045 else:
1046 raise TypeError(f"Unknown color map: `{type(color_map)}`")
1048 # make input always float
1049 values = np.asanyarray(values, dtype=np.float64).ravel()
1051 # get both minumium and maximum values for range normalization
1052 v_min, v_max = values.min(), values.max()
1053 # offset to zero
1054 values -= v_min
1055 # normalize to the 0.0 - 1.0 range
1056 if v_min != v_max:
1057 values /= v_max - v_min
1059 # scale values to 0.0 - 1.0 and get colors
1060 colors = cmap(values)
1062 # convert to 0-255 RGBA
1063 rgba = to_rgba(colors, dtype=dtype)
1065 return rgba
1068def uv_to_color(uv, image) -> NDArray[np.uint8]:
1069 """
1070 Get the color in a texture image.
1072 Parameters
1073 -------------
1074 uv : (n, 2) float
1075 UV coordinates on texture image
1076 image : PIL.Image
1077 Texture image
1079 Returns
1080 ----------
1081 colors : (n, 4) uint4
1082 RGBA color at each of the UV coordinates
1083 """
1084 if image is None or uv is None:
1085 return None
1087 # UV coordinates should be (n, 2) float
1088 uv = np.asanyarray(uv, dtype=np.float64)
1090 # get texture image pixel positions of UV coordinates
1091 x = (uv[:, 0] * (image.width - 1)) % image.width
1092 y = ((1 - uv[:, 1]) * (image.height - 1)) % image.height
1094 # access colors from pixel locations
1095 # make sure image is RGBA before getting values
1096 colors = np.asanyarray(image.convert("RGBA"))[
1097 y.round().astype(np.int64) % image.height,
1098 x.round().astype(np.int64) % image.width,
1099 ]
1101 # conversion to RGBA should have corrected shape
1102 assert colors.ndim == 2 and colors.shape[1] == 4
1103 assert colors.dtype == np.uint8
1105 return colors
1108def uv_to_interpolated_color(uv: ArrayLike, image) -> NDArray[np.uint8]:
1109 """
1110 Get the color from texture image using bilinear sampling.
1112 Parameters
1113 -------------
1114 uv : (n, 2) float
1115 UV coordinates on texture image
1116 image : PIL.Image
1117 Texture image
1119 Returns
1120 ----------
1121 colors : (n, 4) uint8
1122 RGBA color at each of the UV coordinates.
1123 """
1124 if image is None or uv is None:
1125 return None
1127 # UV coordinates should be (n, 2) float
1128 uv = np.asanyarray(uv, dtype=np.float64)
1130 # get texture image pixel positions of UV coordinates
1131 x = uv[:, 0] * (image.width - 1)
1132 y = (1 - uv[:, 1]) * (image.height - 1)
1134 x_floor = np.floor(x).astype(np.int64) % image.width
1135 y_floor = np.floor(y).astype(np.int64) % image.height
1137 x_ceil = np.ceil(x).astype(np.int64) % image.width
1138 y_ceil = np.ceil(y).astype(np.int64) % image.height
1140 dx = x % image.width - x_floor
1141 dy = y % image.height - y_floor
1143 img = np.asanyarray(image.convert("RGBA"))
1145 colors00 = img[y_floor, x_floor]
1146 colors01 = img[y_floor, x_ceil]
1147 colors10 = img[y_ceil, x_floor]
1148 colors11 = img[y_ceil, x_ceil]
1150 a00 = (1 - dx) * (1 - dy)
1151 a01 = dx * (1 - dy)
1152 a10 = (1 - dx) * dy
1153 a11 = dx * dy
1155 a00 = np.repeat(a00[:, None], 4, axis=1)
1156 a01 = np.repeat(a01[:, None], 4, axis=1)
1157 a10 = np.repeat(a10[:, None], 4, axis=1)
1158 a11 = np.repeat(a11[:, None], 4, axis=1)
1160 # interpolated colors as floating point then convert back to uint8
1161 colors = (
1162 (a00 * colors00 + a01 * colors01 + a10 * colors10 + a11 * colors11)
1163 .round()
1164 .astype(np.uint8)
1165 )
1167 # conversion to RGBA should have corrected shape
1168 assert colors.ndim == 2 and colors.shape[1] == 4
1169 assert colors.dtype == np.uint8
1171 return colors
1174def color_to_uv(vertex_colors: ArrayLike):
1175 """
1176 Pack vertex colors into UV coordinates and a simple image material
1178 Parameters
1179 ------------
1180 vertex_colors : (n, 4) float
1181 Array of vertex colors.
1183 Returns
1184 ------------
1185 material : SimpleMaterial
1186 Material containing color information.
1187 uv : (n, 2) float
1188 Normalized UV coordinates
1189 """
1190 from .material import SimpleMaterial, empty_material
1192 # deduplicate the vertex colors
1193 unique, inverse = unique_rows(vertex_colors)
1195 # if there is only one color return a
1196 if len(unique) == 1:
1197 # return a simple single-pixel material
1198 material = empty_material(color=vertex_colors[unique[0]])
1199 uvs = np.zeros((len(vertex_colors), 2)) + 0.5
1200 return material, uvs
1202 from PIL import Image
1204 # return a square image of (size, size)
1205 size = int(np.ceil(np.sqrt(len(unique))))
1206 ctype = vertex_colors.shape[1]
1208 colors = np.zeros((size**2, ctype), dtype=vertex_colors.dtype)
1209 colors[: len(unique)] = vertex_colors[unique]
1211 # PIL has reversed x-y coordinates
1212 image = Image.fromarray(colors.reshape((size, size, ctype))[::-1])
1214 pos = np.arange(len(unique))
1215 # create tiled coordinates for the color pixels
1216 coords = np.column_stack((pos % size, np.floor(pos / size)))
1218 # normalize the index coords into 0.0 - 1.0
1219 # and offset them to be centered on the pixel
1220 coords = (coords / size) + (1.0 / (size * 2.0))
1221 uvs = coords[inverse]
1223 if tol.strict:
1224 # check the packed colors against the image
1225 check = uv_to_color(image=image, uv=uvs)
1226 assert np.all(check == vertex_colors)
1228 return SimpleMaterial(image=image), uvs
1231# set an arbitrary grey as the default color
1232DEFAULT_COLOR = np.array([102, 102, 102, 255], dtype=np.uint8)
1233DEFAULT_MAT = {
1234 "material_diffuse": np.array([102, 102, 102, 255], dtype=np.uint8),
1235 "material_ambient": np.array([64, 64, 64, 255], dtype=np.uint8),
1236 "material_specular": np.array([197, 197, 197, 255], dtype=np.uint8),
1237 "material_shine": 77.0,
1238}