Coverage for trimesh/visual/texture.py: 99%

104 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-12 17:18 +0000

1import copy 

2 

3import numpy as np 

4 

5from .. import caching, grouping, util 

6from . import color 

7from .base import Visuals 

8from .material import PBRMaterial, SimpleMaterial, empty_material # NOQA 

9 

10 

11class TextureVisuals(Visuals): 

12 def __init__(self, uv=None, material=None, image=None, face_materials=None): 

13 """ 

14 Store a single material and per-vertex UV coordinates 

15 for a mesh. 

16 

17 If passed UV coordinates and a single image it will 

18 create a SimpleMaterial for the image. 

19 

20 Parameters 

21 -------------- 

22 uv : (n, 2) float 

23 UV coordinates for the mesh 

24 material : Material 

25 Store images and properties 

26 image : PIL.Image 

27 Can be passed to automatically create material 

28 """ 

29 

30 # store values we care about enough to hash 

31 self.vertex_attributes = caching.DataStore() 

32 # cache calculated values 

33 self._cache = caching.Cache(self.vertex_attributes.__hash__) 

34 

35 # should be (n, 2) float 

36 self.uv = uv 

37 

38 if material is None: 

39 if image is None: 

40 self.material = empty_material() 

41 else: 

42 # if an image is passed create a SimpleMaterial 

43 self.material = SimpleMaterial(image=image) 

44 else: 

45 # if passed assign 

46 self.material = material 

47 

48 self.face_materials = face_materials 

49 

50 def _verify_hash(self): 

51 """ 

52 Dump the cache if anything in self.vertex_attributes 

53 has changed. 

54 """ 

55 self._cache.verify() 

56 

57 @property 

58 def kind(self): 

59 """ 

60 Return the type of visual data stored 

61 

62 Returns 

63 ---------- 

64 kind : str 

65 What type of visuals are defined 

66 """ 

67 return "texture" 

68 

69 @property 

70 def defined(self): 

71 """ 

72 Check if any data is stored 

73 

74 Returns 

75 ---------- 

76 defined : bool 

77 Are UV coordinates and images set? 

78 """ 

79 ok = self.material is not None 

80 return ok 

81 

82 def __hash__(self): 

83 """ 

84 Get a CRC of the stored data. 

85 

86 Returns 

87 -------------- 

88 crc : int 

89 Hash of items in self.vertex_attributes 

90 """ 

91 return self.vertex_attributes.__hash__() 

92 

93 @property 

94 def uv(self): 

95 """ 

96 Get the stored UV coordinates. 

97 

98 Returns 

99 ------------ 

100 uv : (n, 2) float or None 

101 Pixel position per-vertex. 

102 """ 

103 return self.vertex_attributes.get("uv", None) 

104 

105 @uv.setter 

106 def uv(self, values): 

107 """ 

108 Set the UV coordinates. 

109 

110 Parameters 

111 -------------- 

112 values : (n, 2) float or None 

113 Pixel locations on a texture per- vertex 

114 """ 

115 if values is None: 

116 self.vertex_attributes.pop("uv") 

117 else: 

118 self.vertex_attributes["uv"] = np.asanyarray(values, dtype=np.float64) 

119 

120 def copy(self, uv=None): 

121 """ 

122 Return a copy of the current TextureVisuals object. 

123 

124 Returns 

125 ---------- 

126 copied : TextureVisuals 

127 Contains the same information in a new object 

128 """ 

129 if uv is None: 

130 uv = self.uv 

131 if uv is not None: 

132 uv = uv.copy() 

133 copied = TextureVisuals( 

134 uv=uv, 

135 material=self.material.copy(), 

136 face_materials=copy.copy(self.face_materials), 

137 ) 

138 

139 return copied 

140 

141 def to_color(self): 

142 """ 

143 Convert textured visuals to a ColorVisuals with vertex 

144 color calculated from texture. 

145 

146 Returns 

147 ----------- 

148 vis : trimesh.visuals.ColorVisuals 

149 Contains vertex color from texture 

150 """ 

151 # find the color at each UV coordinate 

152 colors = self.material.to_color(self.uv) 

153 # create ColorVisuals from result 

154 vis = color.ColorVisuals(vertex_colors=colors) 

155 return vis 

156 

157 def face_subset(self, face_index, copy_material: bool = True): 

158 """ 

159 Get the visuals for a subset of faces. 

160 

161 Parameters 

162 ------------ 

163 face_index : (n,) int or (n,) bool 

164 Faces to keep 

165 copy_material 

166 If True the material and its images are copied. If False 

167 the material is shared with the original, which is much 

168 cheaper when `split` produces many pieces of a large 

169 texture but means editing one material edits them all. 

170 

171 Returns 

172 ---------- 

173 visual : TextureVisuals 

174 Visuals for the requested faces 

175 """ 

176 uv = self.uv 

177 if uv is not None: 

178 uv = uv[np.unique(self.mesh.faces[face_index].flatten())] 

179 if copy_material: 

180 return self.copy(uv) 

181 return TextureVisuals( 

182 uv=uv, material=self.material, face_materials=copy.copy(self.face_materials) 

183 ) 

184 

185 def update_vertices(self, mask): 

186 """ 

187 Apply a mask to remove or duplicate vertex properties. 

188 

189 Parameters 

190 ------------ 

191 mask : (len(vertices),) bool or (n,) int 

192 Mask which can be used like: `vertex_attribute[mask]` 

193 """ 

194 # collect updated masked values 

195 updates = {} 

196 for key, value in self.vertex_attributes.items(): 

197 # DataStore will convert None to zero-length array 

198 if len(value) == 0: 

199 continue 

200 try: 

201 # store the update 

202 updates[key] = value[mask] 

203 except BaseException: 

204 # usual reason is an incorrect size or index 

205 util.log.warning(f"failed to update visual: `{key}`") 

206 # clear all values from the vertex attributes 

207 self.vertex_attributes.clear() 

208 # apply the updated values 

209 self.vertex_attributes.update(updates) 

210 

211 def update_faces(self, mask): 

212 """ 

213 Apply a mask to remove or duplicate face properties, 

214 not applicable to texture visuals. 

215 """ 

216 

217 def concatenate(self, others): 

218 """ 

219 Concatenate this TextureVisuals object with others 

220 and return the result without modifying this visual. 

221 

222 Parameters 

223 ----------- 

224 others : (n,) Visuals 

225 Other visual objects to concatenate 

226 

227 Returns 

228 ----------- 

229 concatenated : TextureVisuals 

230 Concatenated visual objects 

231 """ 

232 from .objects import concatenate 

233 

234 return concatenate(self, others) 

235 

236 

237def unmerge_faces(faces, *args, **kwargs): 

238 """ 

239 Textured meshes can come with faces referencing vertex 

240 indices (`v`) and an array the same shape which references 

241 vertex texture indices (`vt`) and sometimes even normal (`vn`). 

242 

243 Vertex locations with different values of any of these can't 

244 be considered the "same" vertex, and for our simple data 

245 model we need to not combine these vertices. 

246 

247 Parameters 

248 ------------- 

249 faces : (n, d) int 

250 References vertex indices 

251 *args : (n, d) int 

252 Various references of corresponding values 

253 This is usually UV coordinates or normal indexes 

254 maintain_faces : bool 

255 Do not alter original faces and return no-op masks. 

256 

257 Returns 

258 ------------- 

259 new_faces : (m, d) int 

260 New faces for masked vertices 

261 mask_v : (p,) int 

262 A mask to apply to vertices 

263 mask_* : (p,) int 

264 A mask to apply to vt array to get matching UV coordinates 

265 Returns as many of these as args were passed 

266 """ 

267 # unfortunately Python2 doesn't let us put named kwargs 

268 # after an `*args` sequence so we have to do this ugly get 

269 maintain_faces = kwargs.get("maintain_faces", False) 

270 

271 # don't alter faces 

272 if maintain_faces: 

273 # start with not altering faces at all 

274 result = [faces] 

275 # find the maximum index referenced by faces 

276 max_idx = faces.max() 

277 # add a vertex mask which is just ordered 

278 result.append(np.arange(max_idx + 1)) 

279 

280 # now given the order is fixed do our best on the rest of the order 

281 for arg in args: 

282 # create a mask of the attribute-vertex mapping 

283 # note that these might conflict since we're not unmerging 

284 masks = np.full((3, max_idx + 1), -1, dtype=np.int64) 

285 # set the mask using the unmodified face indexes 

286 for i, f, a in zip(range(3), faces.T, arg.T): 

287 masks[i][f] = a 

288 # find the most commonly occurring attribute (i.e. UV coordinate) 

289 # and use that index note that this is doing a float conversion 

290 # and then median before converting back to int: could also do this as 

291 # a column diff and sort but this seemed easier and is fast enough 

292 # turn default attribute value of -1 to nan before median computation 

293 # and use nanmedian to compute the median ignoring the nan values 

294 masks_nan = np.where(masks != -1, masks, np.nan) 

295 result.append(np.nanmedian(masks_nan, axis=0).astype(np.int64)) 

296 

297 return result 

298 

299 # stack into pairs of (vertex index, texture index) 

300 stackable = [np.asanyarray(faces).reshape(-1)] 

301 # append multiple args to the correlated stack 

302 # this is usually UV coordinates (vt) and normals (vn) 

303 for arg in args: 

304 stackable.append(np.asanyarray(arg).reshape(-1)) 

305 

306 # unify them into rows of a numpy array 

307 stack = np.column_stack(stackable) 

308 # find unique pairs: we're trying to avoid merging 

309 # vertices that have the same position but different 

310 # texture coordinates 

311 unique, inverse = grouping.unique_rows(stack) 

312 

313 # only take the unique pairs 

314 pairs = stack[unique] 

315 # try to maintain original vertex order 

316 order = pairs[:, 0].argsort() 

317 # apply the order to the pairs 

318 pairs = pairs[order] 

319 

320 # we re-ordered the vertices to try to maintain 

321 # the original vertex order as much as possible 

322 # so to reconstruct the faces we need to remap 

323 remap = np.zeros(len(order), dtype=np.int64) 

324 remap[order] = np.arange(len(order)) 

325 

326 # the faces are just the inverse with the new order 

327 new_faces = remap[inverse].reshape((-1, faces.shape[1])) 

328 

329 # the mask for vertices and masks for other args 

330 result = [new_faces] 

331 result.extend(pairs.T) 

332 

333 return result 

334 

335 

336def power_resize(image, resample=1, square=False): 

337 """ 

338 Resize a PIL image so every dimension is a power of two. 

339 

340 Parameters 

341 ------------ 

342 image : PIL.Image 

343 Input image 

344 resample : int 

345 Passed to Image.resize 

346 square : bool 

347 If True, upsize to a square image 

348 

349 Returns 

350 ------------- 

351 resized : PIL.Image 

352 Input image resized 

353 """ 

354 # what is the current resolution of the image in pixels 

355 size = np.array(image.size, dtype=np.int64) 

356 # what is the resolution of the image upsized to the nearest 

357 # power of two on each axis: allow rectangular textures 

358 new_size = (2 ** np.ceil(np.log2(size))).astype(np.int64) 

359 

360 # make every dimension the largest 

361 if square: 

362 new_size = np.ones(2, dtype=np.int64) * new_size.max() 

363 

364 # if we're not powers of two upsize 

365 if (size != new_size).any(): 

366 return image.resize(tuple(new_size), resample=resample) 

367 

368 return image.copy()