Spaces:
Runtime error
Runtime error
File size: 11,157 Bytes
8554568 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
"""Meshes, conforming to the glTF 2.0 standards as specified in
https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-mesh
Author: Matthew Matl
"""
import copy
import numpy as np
import trimesh
from .primitive import Primitive
from .constants import GLTF
from .material import MetallicRoughnessMaterial
class Mesh(object):
"""A set of primitives to be rendered.
Parameters
----------
name : str
The user-defined name of this object.
primitives : list of :class:`Primitive`
The primitives associated with this mesh.
weights : (k,) float
Array of weights to be applied to the Morph Targets.
is_visible : bool
If False, the mesh will not be rendered.
"""
def __init__(self, primitives, name=None, weights=None, is_visible=True):
self.primitives = primitives
self.name = name
self.weights = weights
self.is_visible = is_visible
self._bounds = None
@property
def name(self):
"""str : The user-defined name of this object.
"""
return self._name
@name.setter
def name(self, value):
if value is not None:
value = str(value)
self._name = value
@property
def primitives(self):
"""list of :class:`Primitive` : The primitives associated
with this mesh.
"""
return self._primitives
@primitives.setter
def primitives(self, value):
self._primitives = value
@property
def weights(self):
"""(k,) float : Weights to be applied to morph targets.
"""
return self._weights
@weights.setter
def weights(self, value):
self._weights = value
@property
def is_visible(self):
"""bool : Whether the mesh is visible.
"""
return self._is_visible
@is_visible.setter
def is_visible(self, value):
self._is_visible = value
@property
def bounds(self):
"""(2,3) float : The axis-aligned bounds of the mesh.
"""
if self._bounds is None:
bounds = np.array([[np.infty, np.infty, np.infty],
[-np.infty, -np.infty, -np.infty]])
for p in self.primitives:
bounds[0] = np.minimum(bounds[0], p.bounds[0])
bounds[1] = np.maximum(bounds[1], p.bounds[1])
self._bounds = bounds
return self._bounds
@property
def centroid(self):
"""(3,) float : The centroid of the mesh's axis-aligned bounding box
(AABB).
"""
return np.mean(self.bounds, axis=0)
@property
def extents(self):
"""(3,) float : The lengths of the axes of the mesh's AABB.
"""
return np.diff(self.bounds, axis=0).reshape(-1)
@property
def scale(self):
"""(3,) float : The length of the diagonal of the mesh's AABB.
"""
return np.linalg.norm(self.extents)
@property
def is_transparent(self):
"""bool : If True, the mesh is partially-transparent.
"""
for p in self.primitives:
if p.is_transparent:
return True
return False
@staticmethod
def from_points(points, colors=None, normals=None,
is_visible=True, poses=None):
"""Create a Mesh from a set of points.
Parameters
----------
points : (n,3) float
The point positions.
colors : (n,3) or (n,4) float, optional
RGB or RGBA colors for each point.
normals : (n,3) float, optionals
The normal vectors for each point.
is_visible : bool
If False, the points will not be rendered.
poses : (x,4,4)
Array of 4x4 transformation matrices for instancing this object.
Returns
-------
mesh : :class:`Mesh`
The created mesh.
"""
primitive = Primitive(
positions=points,
normals=normals,
color_0=colors,
mode=GLTF.POINTS,
poses=poses
)
mesh = Mesh(primitives=[primitive], is_visible=is_visible)
return mesh
@staticmethod
def from_trimesh(mesh, material=None, is_visible=True,
poses=None, wireframe=False, smooth=True):
"""Create a Mesh from a :class:`~trimesh.base.Trimesh`.
Parameters
----------
mesh : :class:`~trimesh.base.Trimesh` or list of them
A triangular mesh or a list of meshes.
material : :class:`Material`
The material of the object. Overrides any mesh material.
If not specified and the mesh has no material, a default material
will be used.
is_visible : bool
If False, the mesh will not be rendered.
poses : (n,4,4) float
Array of 4x4 transformation matrices for instancing this object.
wireframe : bool
If `True`, the mesh will be rendered as a wireframe object
smooth : bool
If `True`, the mesh will be rendered with interpolated vertex
normals. Otherwise, the mesh edges will stay sharp.
Returns
-------
mesh : :class:`Mesh`
The created mesh.
"""
if isinstance(mesh, (list, tuple, set, np.ndarray)):
meshes = list(mesh)
elif isinstance(mesh, trimesh.Trimesh):
meshes = [mesh]
else:
raise TypeError('Expected a Trimesh or a list, got a {}'
.format(type(mesh)))
primitives = []
for m in meshes:
positions = None
normals = None
indices = None
# Compute positions, normals, and indices
if smooth:
positions = m.vertices.copy()
normals = m.vertex_normals.copy()
indices = m.faces.copy()
else:
positions = m.vertices[m.faces].reshape((3 * len(m.faces), 3))
normals = np.repeat(m.face_normals, 3, axis=0)
# Compute colors, texture coords, and material properties
color_0, texcoord_0, primitive_material = Mesh._get_trimesh_props(m, smooth=smooth, material=material)
# Override if material is given.
if material is not None:
#primitive_material = copy.copy(material)
primitive_material = copy.deepcopy(material) # TODO
if primitive_material is None:
# Replace material with default if needed
primitive_material = MetallicRoughnessMaterial(
alphaMode='BLEND',
baseColorFactor=[0.3, 0.3, 0.3, 1.0],
metallicFactor=0.2,
roughnessFactor=0.8
)
primitive_material.wireframe = wireframe
# Create the primitive
primitives.append(Primitive(
positions=positions,
normals=normals,
texcoord_0=texcoord_0,
color_0=color_0,
indices=indices,
material=primitive_material,
mode=GLTF.TRIANGLES,
poses=poses
))
return Mesh(primitives=primitives, is_visible=is_visible)
@staticmethod
def _get_trimesh_props(mesh, smooth=False, material=None):
"""Gets the vertex colors, texture coordinates, and material properties
from a :class:`~trimesh.base.Trimesh`.
"""
colors = None
texcoords = None
# If the trimesh visual is undefined, return none for both
if not mesh.visual.defined:
return colors, texcoords, material
# Process vertex colors
if material is None:
if mesh.visual.kind == 'vertex':
vc = mesh.visual.vertex_colors.copy()
if smooth:
colors = vc
else:
colors = vc[mesh.faces].reshape(
(3 * len(mesh.faces), vc.shape[1])
)
material = MetallicRoughnessMaterial(
alphaMode='BLEND',
baseColorFactor=[1.0, 1.0, 1.0, 1.0],
metallicFactor=0.2,
roughnessFactor=0.8
)
# Process face colors
elif mesh.visual.kind == 'face':
if smooth:
raise ValueError('Cannot use face colors with a smooth mesh')
else:
colors = np.repeat(mesh.visual.face_colors, 3, axis=0)
material = MetallicRoughnessMaterial(
alphaMode='BLEND',
baseColorFactor=[1.0, 1.0, 1.0, 1.0],
metallicFactor=0.2,
roughnessFactor=0.8
)
# Process texture colors
if mesh.visual.kind == 'texture':
# Configure UV coordinates
if mesh.visual.uv is not None and len(mesh.visual.uv) != 0:
uv = mesh.visual.uv.copy()
if smooth:
texcoords = uv
else:
texcoords = uv[mesh.faces].reshape(
(3 * len(mesh.faces), uv.shape[1])
)
if material is None:
# Configure mesh material
mat = mesh.visual.material
if isinstance(mat, trimesh.visual.texture.PBRMaterial):
material = MetallicRoughnessMaterial(
normalTexture=mat.normalTexture,
occlusionTexture=mat.occlusionTexture,
emissiveTexture=mat.emissiveTexture,
emissiveFactor=mat.emissiveFactor,
alphaMode='BLEND',
baseColorFactor=mat.baseColorFactor,
baseColorTexture=mat.baseColorTexture,
metallicFactor=mat.metallicFactor,
roughnessFactor=mat.roughnessFactor,
metallicRoughnessTexture=mat.metallicRoughnessTexture,
doubleSided=mat.doubleSided,
alphaCutoff=mat.alphaCutoff
)
elif isinstance(mat, trimesh.visual.texture.SimpleMaterial):
glossiness = mat.kwargs.get('Ns', 1.0)
if isinstance(glossiness, list):
glossiness = float(glossiness[0])
roughness = (2 / (glossiness + 2)) ** (1.0 / 4.0)
material = MetallicRoughnessMaterial(
alphaMode='BLEND',
roughnessFactor=roughness,
baseColorFactor=mat.diffuse,
baseColorTexture=mat.image,
)
elif isinstance(mat, MetallicRoughnessMaterial):
material = mat
return colors, texcoords, material
|