simplex-solver 3.2.2__cp39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. simplex_solver-3.2.2.dist-info/DELVEWHEEL +2 -0
  2. simplex_solver-3.2.2.dist-info/METADATA +94 -0
  3. simplex_solver-3.2.2.dist-info/RECORD +84 -0
  4. simplex_solver-3.2.2.dist-info/WHEEL +5 -0
  5. simplex_solver.libs/.load-order-simplex_solver-3.2.2 +1 -0
  6. simplex_solver.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll +0 -0
  7. simplexui/__init__.py +86 -0
  8. simplexui/_version.py +1 -0
  9. simplexui/channelBox.py +867 -0
  10. simplexui/comboCheckDialog.py +396 -0
  11. simplexui/commands/__init__.py +16 -0
  12. simplexui/commands/alembicCommon.py +1148 -0
  13. simplexui/commands/alembic_walker.py +299 -0
  14. simplexui/commands/applyCorrectives.py +452 -0
  15. simplexui/commands/correctiveInterface.py +259 -0
  16. simplexui/commands/expandedExport.py +434 -0
  17. simplexui/commands/hdf5Convert.py +62 -0
  18. simplexui/commands/mayaCorrectiveInterface.py +159 -0
  19. simplexui/commands/mayatonumpy.py +416 -0
  20. simplexui/commands/mesh.py +1085 -0
  21. simplexui/commands/poseblendlib.py +168 -0
  22. simplexui/commands/reorderSimplexPoints.py +102 -0
  23. simplexui/commands/replaceDefinitionJson.py +74 -0
  24. simplexui/commands/rigidAlign.py +97 -0
  25. simplexui/commands/unsubdivide.py +1222 -0
  26. simplexui/commands/uvTransfer.py +976 -0
  27. simplexui/dragFilter.py +334 -0
  28. simplexui/falloffDialog.py +504 -0
  29. simplexui/img/ChefHead.png +0 -0
  30. simplexui/img/frozen.png +0 -0
  31. simplexui/interface/__init__.py +30 -0
  32. simplexui/interface/dummyInterface.py +1313 -0
  33. simplexui/interface/mayaInterface.py +2294 -0
  34. simplexui/interfaceModel.py +655 -0
  35. simplexui/interfaceModelTrees.py +456 -0
  36. simplexui/items/__init__.py +50 -0
  37. simplexui/items/accessor.py +145 -0
  38. simplexui/items/combo.py +645 -0
  39. simplexui/items/dragItem.py +44 -0
  40. simplexui/items/falloff.py +748 -0
  41. simplexui/items/group.py +267 -0
  42. simplexui/items/progression.py +613 -0
  43. simplexui/items/shape.py +384 -0
  44. simplexui/items/simplex.py +1734 -0
  45. simplexui/items/slider.py +632 -0
  46. simplexui/items/stack.py +147 -0
  47. simplexui/items/traversal.py +780 -0
  48. simplexui/items/treeItem.py +441 -0
  49. simplexui/main.pyw +22 -0
  50. simplexui/menu/__init__.py +73 -0
  51. simplexui/menu/dummyPlugins/__init__.py +16 -0
  52. simplexui/menu/genericPlugins/__init__.py +16 -0
  53. simplexui/menu/genericPlugins/_builtins.py +270 -0
  54. simplexui/menu/genericPlugins/checkPossibleCombos.py +48 -0
  55. simplexui/menu/genericPlugins/exportSplit.py +67 -0
  56. simplexui/menu/genericPlugins/showFalloffs.py +26 -0
  57. simplexui/menu/genericPlugins/showTraversals.py +26 -0
  58. simplexui/menu/genericPlugins/simplexUvTransfer.py +106 -0
  59. simplexui/menu/genericPlugins/unsubdivide.py +72 -0
  60. simplexui/menu/mayaPlugins/__init__.py +16 -0
  61. simplexui/menu/mayaPlugins/exportOther.py +53 -0
  62. simplexui/menu/mayaPlugins/extractProgressives.py +68 -0
  63. simplexui/menu/mayaPlugins/freezeCombo.py +247 -0
  64. simplexui/menu/mayaPlugins/generateShapeIncrementals.py +99 -0
  65. simplexui/menu/mayaPlugins/importObjs.py +199 -0
  66. simplexui/menu/mayaPlugins/linearizeTraversal.py +60 -0
  67. simplexui/menu/mayaPlugins/makeShelfBtn.py +67 -0
  68. simplexui/menu/mayaPlugins/relaxToSelection.py +76 -0
  69. simplexui/menu/mayaPlugins/reloadDefinition.py +44 -0
  70. simplexui/menu/mayaPlugins/snapToNeutral.py +71 -0
  71. simplexui/menu/mayaPlugins/softSelectToCluster.py +201 -0
  72. simplexui/menu/mayaPlugins/tweakMix.py +136 -0
  73. simplexui/menu/mayaPlugins/updateRestShape.py +113 -0
  74. simplexui/pysimplex.lib +0 -0
  75. simplexui/pysimplex.pyd +0 -0
  76. simplexui/simplexDialog.py +1547 -0
  77. simplexui/travCheckDialog.py +419 -0
  78. simplexui/traversalDialog.py +299 -0
  79. simplexui/ui/comboCheckDialog.ui +475 -0
  80. simplexui/ui/falloffDialog.ui +243 -0
  81. simplexui/ui/simplexDialog.ui +1458 -0
  82. simplexui/ui/travCheckDialog.ui +488 -0
  83. simplexui/ui/traversalDialog.ui +532 -0
  84. simplexui/utils.py +307 -0
@@ -0,0 +1,976 @@
1
+ # Copyright 2016, Blur Studio
2
+ #
3
+ # This file is part of Simplex.
4
+ #
5
+ # Simplex is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU Lesser General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # Simplex is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU Lesser General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU Lesser General Public License
16
+ # along with Simplex. If not, see <http://www.gnu.org/licenses/>.
17
+
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+
22
+ INF = float("inf")
23
+ EPS = 1e-7
24
+
25
+
26
+ ########################
27
+ # Mean Value Coords
28
+ ########################
29
+
30
+
31
+ def _lerp(idx: int, corners, p):
32
+ # If I'm here, I know that p lies on the line
33
+ # between the corners at idx and idx+1.
34
+ # Return the lerp value
35
+ ip = (idx + 1) % len(corners)
36
+ c1 = corners[idx]
37
+ c2 = corners[ip]
38
+ base = c1 - c2
39
+ proj = np.dot(p - c2, base)
40
+ b = proj / (base**2).sum()
41
+ ret = np.zeros(len(corners))
42
+ ret[idx] = b
43
+ ret[ip] = 1.0 - b
44
+ return ret
45
+
46
+
47
+ def mvc(corners, p, tol=EPS):
48
+ """Get the Mean Value Coordinates of a point p in the polygon defined by corners
49
+
50
+ Parameters
51
+ ----------
52
+ corners : [int, ...]
53
+ A list of corner indices
54
+ p : np.array
55
+ The array of points
56
+ tol : float
57
+ A small tolerance value, defaulting to the global EPS
58
+
59
+ Returns
60
+ -------
61
+ : list
62
+ The normalized list of barycentric weights for this point in the polygon
63
+
64
+ """
65
+ spokes = corners - p
66
+ spokeLens = (spokes * spokes).sum(axis=1)
67
+
68
+ # Check if p is on top of a vertex
69
+ for i, v in enumerate(spokeLens):
70
+ if v < tol:
71
+ bary = np.zeros(len(corners))
72
+ bary[i] = 1.0
73
+ return bary
74
+
75
+ rspokes = np.roll(spokes, -1, axis=0)
76
+ areas = np.cross(spokes, rspokes) * 0.5
77
+ dots = (spokes * rspokes).sum(axis=1)
78
+
79
+ for i, v in enumerate(areas):
80
+ if v < tol and dots[i] < 0.0:
81
+ return _lerp(i, corners, p)
82
+
83
+ spokeLens = spokeLens**0.5
84
+ rspokeLens = np.roll(spokeLens, -1)
85
+ t = areas / (spokeLens * rspokeLens + dots)
86
+ rawWeights = (np.roll(t, 1) + t) / spokeLens
87
+ return rawWeights / sum(rawWeights)
88
+
89
+
90
+ def mmvc(rawFaces, points, samples, uvToFace, tol=EPS):
91
+ """Multi-MeanValueCoords
92
+ Get the MVC's of many points over many faces using numpy
93
+
94
+ Parameters
95
+ ----------
96
+ rawFaces : [[int, ...], ...]
97
+ A list of face index lists
98
+ points : np.array
99
+ A numpy array of uv points
100
+ samples : np.array
101
+ A numpy array of points to get the barycentric coords for
102
+ uvToFace : {int: [int, ...], ...}
103
+ A dictionary of UV indices to a list of Face Indices
104
+ tol : float
105
+ A small tolerance value, defaulting to the global EPS
106
+
107
+ Returns
108
+ -------
109
+ : {fc: (wh, barys)}
110
+ A dictionary of face counts to a tuple containing the indices of the face indices
111
+ checked, and the barycentric coords
112
+
113
+ """
114
+ uvIdxs, faceIdxs = sorted(zip(*list(uvToFace.items())))
115
+ uvIdxs = np.array(uvIdxs)
116
+ faces = [rawFaces[fi] for fi in faceIdxs]
117
+ faceLens = np.array([len(i) for i in faces])
118
+ fcs = np.unique(faceLens)
119
+
120
+ out = {}
121
+ for fc in fcs:
122
+ wh = np.where(faceLens == fc)[0]
123
+ cIdxs = np.array([faces[i] for i in wh])
124
+ barys = np.zeros(cIdxs.shape)
125
+ qIdxs = uvIdxs[wh]
126
+ out[fc] = (qIdxs, barys) # edit barys in-place
127
+
128
+ # cornerses is a [f, fc, 2] array
129
+ # where f is num of faces, fc is verts per face, and 2 because uv is 2d
130
+ # pts is [f, 2] array where f is num faces
131
+ cornerses = points[cIdxs]
132
+ pts = samples[qIdxs]
133
+
134
+ # Get the "spokes" from the query point to the face corners
135
+ # and get their squared lengths
136
+ spokes = cornerses - pts[:, None, :]
137
+ spokeLens2 = (spokes * spokes).sum(axis=-1)
138
+
139
+ # Handle any samples that are directly on top of a corner
140
+ # (where the spoke length is zero)
141
+ zeros = np.any(spokeLens2 < tol, axis=1)
142
+ onPoint = np.where(zeros)
143
+ offPoint = np.where(~zeros)
144
+ if onPoint[0].size:
145
+ pIdxs = spokeLens2[onPoint].argmin(axis=1)
146
+ barys[onPoint, pIdxs] = 1.0
147
+
148
+ if not offPoint[0].size:
149
+ continue
150
+
151
+ # Ignore those points that have already been computed
152
+ idxs = offPoint[0]
153
+ spokes = spokes[offPoint]
154
+ spokeLens2 = spokeLens2[offPoint]
155
+
156
+ # Get the signed area of each triangle created by the spokes
157
+ # and the dot product for the angle between each
158
+ rspokes = np.roll(spokes, -1, axis=1)
159
+ areas = np.cross(spokes, rspokes) * 0.5
160
+ dots = (spokes * rspokes).sum(axis=-1)
161
+
162
+ # Handle any samples that are directly on an edge between
163
+ # two corners. (Where the triangle area is 0, and the
164
+ # dot product is negative)
165
+ aareas = abs(areas)
166
+ zeros = aareas < tol
167
+ ndots = dots < 0.0
168
+ zn = zeros & ndots
169
+ toLerp = np.any(zn, axis=-1)
170
+ onEdge = np.where(toLerp)
171
+ offEdge = np.where(~toLerp)
172
+ if onEdge[0].size:
173
+ subIdx = idxs[onEdge]
174
+ pIdxs = zn[onEdge].argmax(axis=-1)
175
+ xIdxs = (pIdxs + 1) % fc
176
+
177
+ ppIdxs = cIdxs[subIdx, pIdxs]
178
+ xpIdxs = cIdxs[subIdx, xIdxs]
179
+
180
+ cp = pts[subIdx]
181
+ pp = points[ppIdxs]
182
+ xp = points[xpIdxs]
183
+
184
+ bases = pp - xp
185
+ diff = cp - xp
186
+ proj = (bases * diff).sum(axis=-1)
187
+ b = proj / (bases**2).sum(axis=1)
188
+ mb = 1.0 - b
189
+ barys[subIdx, pIdxs] = b
190
+ barys[subIdx, xIdxs] = mb
191
+
192
+ if not offEdge[0].size:
193
+ continue
194
+
195
+ idxs = idxs[offEdge]
196
+ dots = dots[offEdge]
197
+ areas = areas[offEdge]
198
+ spokeLens2 = spokeLens2[offEdge]
199
+ spokeLens = spokeLens2**0.5
200
+ rspokeLens = np.roll(spokeLens, -1, axis=1)
201
+
202
+ t = areas / (spokeLens * rspokeLens + dots)
203
+ rawWeights = (np.roll(t, -1, axis=1) + t) / spokeLens
204
+ b = rawWeights / rawWeights.sum(axis=1)[..., None]
205
+ barys[idxs] = b
206
+
207
+ ret = {}
208
+ for qIdxs, barys in out.values():
209
+ for qi, b in zip(qIdxs, barys):
210
+ ret[qi] = (uvToFace[qi], b)
211
+
212
+ return ret
213
+
214
+
215
+ ########################
216
+ # Sweep algorithm
217
+ ########################
218
+
219
+
220
+ def triArea(a, b, c):
221
+ """Use the cross-ish-product to find the area of the triangle
222
+ Depending on the winding, the area could be positive or negative
223
+
224
+ Parameters
225
+ ----------
226
+ a : [float, float, float]
227
+ The first point
228
+ b : [float, float, float]
229
+ The second point
230
+ c : [float, float, float]
231
+ The third point
232
+
233
+ Returns
234
+ -------
235
+ : float
236
+ The area of the triangle
237
+
238
+ """
239
+ return (a[0] * (c[1] - b[1]) + b[0] * (a[1] - c[1]) + c[0] * (b[1] - a[1])) / 2.0
240
+
241
+
242
+ def pointInTri(p, a, b, c, tol=EPS):
243
+ """Check that the point is inside the triangle
244
+
245
+ Parameters
246
+ ----------
247
+ p : [float, float, float]
248
+ The point to check is inside the triangle
249
+ a : [float, float, float]
250
+ The first point of the triangle
251
+ b : [float, float, float]
252
+ The second point of the triangle
253
+ c : [float, float, float]
254
+ The third point of the triangle
255
+ tol : float
256
+ A small tolerance value, defaulting to the global EPS
257
+
258
+ Returns
259
+ -------
260
+ : bool
261
+ Whether the point is inside the given triangle
262
+
263
+ """
264
+ area = abs(triArea(a, b, c))
265
+ chis = abs(triArea(p, b, c)) + abs(triArea(a, p, c)) + abs(triArea(a, b, p))
266
+ return abs(area - chis) < tol
267
+
268
+
269
+ def sweep(qPoints, uvs, tris, pBar=None):
270
+ """Get what triangle each query point is inside
271
+
272
+ Runs a sweep-line algorithm to check for points in triangles.
273
+ Imagine a uv layout, and a bunch of points on the layout.
274
+ Now imagine a vertical line sweeping across the uv plane from the left
275
+ to the right. The sorted u-values of certain properties then handled
276
+ one-by-one.
277
+
278
+ The algorithm keeps track of what triangles the vertical line is currently intersecting.
279
+
280
+ * This is done by storing the min and max u-values for each triangle.
281
+ * If the u-value encountered is the min for a tri, that tri is added to the list
282
+ * If the u-value encountered is the max for a tri, that tri is removed from the list
283
+
284
+ Then, each time a query point is encountered, it only has to check the intersection list
285
+
286
+ Parameters
287
+ ----------
288
+ qPoints : np.array
289
+ The points to get barycentric coordinates of
290
+ uvs : np.array
291
+ The UVs we're searching
292
+ tris : np.array
293
+ The Nx3 array of triangle indices
294
+ pBar : QProgressDialog, optional
295
+ An optional progress dialog
296
+
297
+ Returns
298
+ -------
299
+ : {int: int, ...}
300
+ A dictionary of out[pointIndex] = triIndex
301
+ : set()
302
+ A set containing the pointIndexes that weren't found in a triangle
303
+
304
+ """
305
+ tpts = uvs[tris] # [tIdx, abc, xy]
306
+
307
+ allmxs, allmns = tpts.max(axis=1), tpts.min(axis=1)
308
+ ymxs, ymns = allmxs[:, 1], allmns[:, 1]
309
+ mxs, mns = allmxs[:, 0], allmns[:, 0]
310
+ qpx = qPoints[:, 0]
311
+ qpSIdxs, mxSIdxs, mnSIdxs = np.argsort(qpx), np.argsort(mxs), np.argsort(mns)
312
+ qpSIdx, mxSIdx, mnSIdx = 0, 0, 0
313
+ qpIdx, mxIdx, mnIdx = qpSIdxs[qpSIdx], mxSIdxs[mxSIdx], mnSIdxs[mnSIdx]
314
+ qp, mx, mn = qpx[qpIdx], mxs[mxIdx], mns[mnIdx]
315
+
316
+ out = {}
317
+ missing = set()
318
+
319
+ if pBar is not None:
320
+ pBar.setValue(0)
321
+ allVals = len(qpSIdxs) + len(mxSIdxs) + len(mnSIdxs)
322
+ pBar.setRange(0, allVals)
323
+ pBar.setLabelText("Sweeping ...")
324
+ from Qt.QtWidgets import QApplication
325
+
326
+ QApplication.processEvents()
327
+
328
+ # skip any triangles to the left of the first query point
329
+ # The algorithm will stop once we hit the last query point
330
+ skip = [qp > m for m in mxs]
331
+ activeTris = [False for _ in mxs] # For fast membership testing
332
+ atSet = set() # For fast iteration
333
+
334
+ while True:
335
+ if pBar is not None:
336
+ cVal = qpSIdx + mnSIdx + mxSIdx
337
+ if cVal % 1283 == 0: # Just a random prime
338
+ pBar.setValue(cVal)
339
+ pBar.setLabelText(f"Sweeping ...\n{cVal}/{allVals}")
340
+ QApplication.processEvents()
341
+ if pBar.wasCanceled():
342
+ raise RuntimeError("Cancelled!")
343
+
344
+ if mn <= mx and mn <= qp:
345
+ # Always add triangles first if possible
346
+ aTriIdx = mnSIdxs[mnSIdx]
347
+ if not activeTris[aTriIdx] and not skip[aTriIdx]:
348
+ activeTris[aTriIdx] = True
349
+ atSet.add(aTriIdx)
350
+
351
+ mnSIdx += 1
352
+ if mnSIdx != len(mnSIdxs):
353
+ mnIdx = mnSIdxs[mnSIdx]
354
+ mn = mns[mnIdx]
355
+ else:
356
+ mn = mxs[mxSIdxs[-1]] + 1
357
+
358
+ elif qp <= mx:
359
+ # Check query points between adding and removing
360
+ qPoint = qPoints[qpIdx]
361
+ yv = qPoint[1]
362
+ # A linear search is faster than more complex collections here
363
+ for t in atSet:
364
+ if ymns[t] <= yv <= ymxs[t]:
365
+ a, b, c = uvs[tris[t]]
366
+ if pointInTri(qPoint, a, b, c):
367
+ out[qpIdx] = t
368
+ break
369
+ else:
370
+ missing.add(qpIdx)
371
+
372
+ qpSIdx += 1
373
+ if qpSIdx == len(qpSIdxs):
374
+ break
375
+ qpIdx = qpSIdxs[qpSIdx]
376
+ qp = qpx[qpIdx]
377
+
378
+ else:
379
+ # always remove triangles last
380
+ aTriIdx = mxSIdxs[mxSIdx]
381
+ if activeTris[aTriIdx] and not skip[aTriIdx]:
382
+ activeTris[aTriIdx] = False
383
+ atSet.remove(aTriIdx)
384
+
385
+ mxSIdx += 1
386
+ if mxSIdx != len(mxSIdxs):
387
+ mxIdx = mxSIdxs[mxSIdx]
388
+ mx = mxs[mxIdx]
389
+
390
+ return out, missing
391
+
392
+
393
+ ########################
394
+ # Triangulation
395
+ ########################
396
+
397
+
398
+ def inBox(point, mxs, mns) -> bool:
399
+ """Check if a point is inside the bounding box
400
+
401
+ Parameters
402
+ ----------
403
+ point : np.array
404
+ A 3d point
405
+ mxs : np.array
406
+ The max values of all the coordinates per axis
407
+ mns : np.array
408
+ The min values of all the coordinates per axis
409
+
410
+ Returns
411
+ -------
412
+ : bool
413
+ Whether the point is in the given bounding box
414
+
415
+ """
416
+ return bool(np.all(point <= mxs) and np.all(point >= mns))
417
+
418
+
419
+ def _isEar(a, b, c, polygon, tol=EPS) -> bool:
420
+ """Check if the points a,b,c of the polygon could be their own triangle"""
421
+ signedArea = triArea(a, b, c)
422
+
423
+ # Check that the triange is wound the correct way.
424
+ if signedArea > 0:
425
+ return False
426
+
427
+ # Check that the triangle has non-zero area
428
+ # we already know the area is negative from above
429
+ if -signedArea < tol:
430
+ return False
431
+
432
+ # Check that none of the other points in the polygon are contained in triangle
433
+ for p in polygon:
434
+ if p not in (a, b, c):
435
+ if pointInTri(p, a, b, c, tol=tol):
436
+ return False
437
+ return True
438
+
439
+
440
+ def earclip(idxs, verts):
441
+ """Simple earclipping algorithm
442
+ For a polygon with n points it will return n-2 triangles.
443
+
444
+ Parameters
445
+ ----------
446
+ idxs : [int, ...]
447
+ The indices that make up a polygon
448
+ verts : np.array
449
+ All the UV positions
450
+
451
+ Returns
452
+ -------
453
+ : [[int, int, int], ...]
454
+ A list of triangle indices
455
+
456
+ """
457
+ earVerts = []
458
+ tris = []
459
+ idxs = list(idxs)
460
+ polygon = [tuple(verts[i]) for i in idxs]
461
+
462
+ numPts = len(polygon)
463
+ for i in range(numPts):
464
+ prev = polygon[i - 2]
465
+ cur = polygon[i - 1]
466
+ nxt = polygon[i]
467
+ if _isEar(prev, cur, nxt, polygon):
468
+ earVerts.append(cur)
469
+
470
+ while earVerts and numPts >= 3:
471
+ ear = earVerts.pop()
472
+ i = polygon.index(ear)
473
+ pi, ni = i - 1, (i + 1) % numPts
474
+
475
+ prevPt = polygon[pi]
476
+ nxtPt = polygon[ni]
477
+ tris.append((idxs[pi], idxs[i], idxs[ni]))
478
+
479
+ polygon.pop(i)
480
+ idxs.pop(i)
481
+ numPts -= 1
482
+ if numPts > 3:
483
+ prePrePt = polygon[i - 2]
484
+ nxtNxtPt = polygon[(i + 1) % numPts]
485
+
486
+ groups = [
487
+ (prePrePt, prevPt, nxtPt, polygon),
488
+ (prevPt, nxtPt, nxtNxtPt, polygon),
489
+ ]
490
+
491
+ for group in groups:
492
+ p = group[1]
493
+ if _isEar(*group):
494
+ if p not in earVerts:
495
+ earVerts.append(p)
496
+ elif p in earVerts:
497
+ earVerts.remove(p)
498
+ return tris
499
+
500
+
501
+ def triangulateUVs(faces, uvs):
502
+ """Take a set of uvFaces and uv points, and triangulate it
503
+
504
+ Parameters
505
+ ----------
506
+ faces : [[int, ...], ...]
507
+ A uv face structure
508
+ uvs : np.array
509
+ The uv positions
510
+
511
+ Returns
512
+ -------
513
+ : np.array
514
+ A Nx3 array of uv indexes making triangles
515
+ : [int, ...]
516
+ A list where the index is the triangle index, and the value is the face index
517
+ : {(int, int): int, ...}
518
+ A dictionary of border edge pairs to border faces
519
+
520
+ """
521
+ uvs = np.array(uvs)
522
+ triMap = []
523
+ tris = []
524
+ borderFaceMap = {}
525
+ # Build the naiive triangulation
526
+ # And get the borders while I'm looping
527
+ for f, face in enumerate(faces):
528
+ for i in range(2, len(face)):
529
+ triMap.append(f)
530
+ tris.append((face[0], face[i - 1], face[i]))
531
+
532
+ for i in range(len(face)):
533
+ ep = (face[i - 1], face[i])
534
+ if ep[0] > ep[1]:
535
+ ep = (ep[1], ep[0])
536
+ if ep in borderFaceMap:
537
+ borderFaceMap.pop(ep)
538
+ else:
539
+ borderFaceMap[ep] = f
540
+
541
+ tris = np.array(tris)
542
+ tuvs = uvs[tris]
543
+
544
+ # Get the area using a 2d-pseudo-cross-product
545
+ a = tuvs[:, 0] - tuvs[:, 1]
546
+ b = tuvs[:, 2] - tuvs[:, 1]
547
+ signedAreas = a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0]
548
+
549
+ # Things with negative area are wound backwards in this case
550
+ negArea = np.where(signedAreas < 0)
551
+
552
+ # Do we need to retriangulate any of the polys
553
+ retri = sorted({triMap[i] for i in negArea[0]})
554
+ if retri:
555
+ tris = tris.tolist()
556
+ tmpFaceMap = {}
557
+ # tmpFaceMap is only good while we re-triangulate
558
+ # it has to be re-built after
559
+ for t, f in enumerate(triMap):
560
+ tmpFaceMap.setdefault(f, []).append(t)
561
+
562
+ for f in retri[::-1]:
563
+ good = earclip(faces[f], uvs)
564
+ tidxs = tmpFaceMap[f]
565
+ tris[tidxs[0] : tidxs[-1] + 1] = good
566
+ triMap[tidxs[0] : tidxs[-1] + 1] = [f] * len(good)
567
+ tris = np.array(tris)
568
+
569
+ return tris, triMap, borderFaceMap
570
+
571
+
572
+ ########################
573
+ # UV Transferring
574
+ ########################
575
+
576
+ MISSING = {}
577
+
578
+
579
+ def cooSparseMul(M, v):
580
+ """Multply the sparse matrix by the vector
581
+
582
+ Parameters
583
+ ----------
584
+ M : SparseMatrix
585
+ My own sparse matrix representation
586
+ v : np.array
587
+ A vector
588
+
589
+ Returns
590
+ -------
591
+ : np.array
592
+ The result of the multiplication
593
+ """
594
+ # Using scipy is at least 2x faster than the
595
+ # pure numpy implementation. But even that
596
+ # is about 5x faster than using a dense matrix
597
+ try:
598
+ from scipy import sparse
599
+ except ImportError:
600
+ # No scipy, use numpy
601
+ # The numpy universal function (ufunc) .add.at()
602
+ # makes this possible without any python looping
603
+ row, col, val, shape = M
604
+ v = v.swapaxes(0, -2)
605
+ vshape = val.shape + tuple([1] * (len(v) - 1))
606
+ val = val.reshape(vshape)
607
+ out = np.zeros(shape[:1] + v.shape[1:])
608
+ np.add.at(out, row, val * v[col])
609
+ out = out.swapaxes(0, -2)
610
+ else:
611
+ row, col, val, shape = M
612
+ spM = sparse.coo_matrix((val, (row, col)), shape=shape)
613
+ spM = sparse.csr_matrix(spM)
614
+ if len(v.shape) == 3:
615
+ out = np.array([spM.dot(frm) for frm in v])
616
+ else:
617
+ out = spM.dot(v)
618
+ return out
619
+
620
+
621
+ def getUvCorrelation(samples, points, faces, tol=0.0001, handleMissing=True, pBar=None):
622
+ """Get the per-face correlation of the sample points in uv space.
623
+
624
+ Parameters
625
+ ----------
626
+ samples : np.array
627
+ The sample points
628
+ points : np.array
629
+ The background points
630
+ faces : [[int, ...], ...]
631
+ The Face list
632
+ tol : float
633
+ A small tolerance value, defaulting to the global EPS
634
+ handleMissing :
635
+ (Default value = True)
636
+ pBar : QProgressDialog, optional
637
+ An optional progress dialog
638
+
639
+ Returns
640
+ -------
641
+ : {idx: (idx, [float, ...]), ...}
642
+ A dictionary from the sample index to a faceIdx/cornerWeights pair
643
+
644
+ """
645
+ tris, triMap, borderMap = triangulateUVs(faces, points)
646
+ swept, missing = sweep(samples, points, tris, pBar=pBar)
647
+ uvToFace = {uvI: triMap[tI] for uvI, tI in swept.items()}
648
+ # import __main__
649
+ # __main__.__dict__.update(locals())
650
+ # raise RuntimeError("STOPPIT")
651
+ if pBar is not None:
652
+ pBar.setValue(0)
653
+ pBar.setRange(0, len(uvToFace))
654
+ pBar.setLabelText("Calculate Mean Value Coords")
655
+ from Qt.QtWidgets import QApplication
656
+
657
+ QApplication.processEvents()
658
+
659
+ # mvcDict = {}
660
+ # for i, (uvIdx, faceIdx) in enumerate(uvToFace.iteritems()):
661
+ # if pBar is not None:
662
+ # pBar.setValue(i)
663
+ # pBar.setLabelText("Calculate Mean Value Coords\n{0}/{1}".format(i, len(uvToFace)))
664
+ # QApplication.processEvents()
665
+ # uv = samples[uvIdx]
666
+ # corners = points[faces[faceIdx]]
667
+ # bary = mvc(corners, uv)
668
+ # mvcDict[uvIdx] = (faceIdx, bary)
669
+
670
+ mvcDict = mmvc(faces, points, samples, uvToFace)
671
+
672
+ # find the closest border
673
+ # Just use a brute-force search
674
+ # ... for now
675
+
676
+ if missing and handleMissing:
677
+ if pBar is not None:
678
+ pBar.setValue(0)
679
+ pBar.setLabelText("Handle Missing")
680
+ QApplication.processEvents()
681
+ tol = tol**2
682
+ bk = list(borderMap.keys())
683
+ borders = np.array(bk)
684
+ bStarts = points[borders[:, 0]]
685
+ bEnds = points[borders[:, 1]]
686
+
687
+ bDiff = bEnds - bStarts
688
+ bLens2 = (bDiff * bDiff).sum(axis=1)
689
+ for mIdx in missing:
690
+ mp = samples[mIdx]
691
+ dSquared = _mpCheck(bStarts, bDiff, bLens2, mp)
692
+ minIdx = np.argmin(dSquared)
693
+ if dSquared[mIdx] < tol:
694
+ faceIdx = borderMap[bk[minIdx]]
695
+ corners = points[faces[faceIdx]]
696
+ bary = mvc(corners, mp)
697
+ mvcDict[mIdx] = (faceIdx, bary)
698
+
699
+ return mvcDict
700
+
701
+
702
+ def _mpCheck(a, d, dr2, pt):
703
+ """Point to Multi-segment squared distance. Uses pre-computed values"""
704
+ lerp = ((pt - a) * d).sum(axis=1) / dr2
705
+ lerp = np.clip(lerp, 0, 1)
706
+ xy = (lerp[:, None] * d) + a
707
+ _dxy = xy - pt
708
+ return (_dxy * _dxy).sum(axis=1)
709
+
710
+
711
+ def getVertCorrelation(
712
+ sUvFaces, sUvs, tVertFaces, tUvFaces, tUvs, tol=0.0001, pBar=None
713
+ ):
714
+ """Build the vertex position correlation between two meshes
715
+ by looking through UV-space. Handle combining multiple uvs
716
+ per vertex, and having samples that live outside the coverage
717
+
718
+ Parameters
719
+ ----------
720
+ sUvFaces : [[int, ...], ...]
721
+ The source UVFace list
722
+ sUvs : np.array
723
+ The source UV positions
724
+ tVertFaces : [[int, ...], ...]
725
+ The target vertex face list
726
+ tUvFaces : [[int, ...], ...]
727
+ The target UV face list
728
+ tUvs : np.array
729
+ The target UV positions
730
+ tol : float
731
+ A small tolerance value, defaulting to the global EPS
732
+ pBar : QProgressDialog, optional
733
+ An optional progress dialog
734
+
735
+ Returns
736
+ -------
737
+ : {idx: (idx, [float, ...]), ...}
738
+ A dictionary from the sample index to a faceIdx/cornerWeights pair
739
+ """
740
+ childUvToVert = {}
741
+ cNumVerts = -1
742
+ for vF, uvF in zip(tVertFaces, tUvFaces):
743
+ for vIdx, uvIdx in zip(vF, uvF):
744
+ cNumVerts = max(cNumVerts, vIdx)
745
+ childUvToVert[uvIdx] = vIdx
746
+
747
+ mvcUvDict = getUvCorrelation(tUvs, sUvs, sUvFaces, tol=tol, pBar=pBar)
748
+
749
+ mvcVertDict = {}
750
+ for uvIdx in range(len(tUvs)):
751
+ if uvIdx not in mvcUvDict:
752
+ continue
753
+ mvcVertDict.setdefault(childUvToVert[uvIdx], []).append(mvcUvDict[uvIdx])
754
+
755
+ missing = set(range(cNumVerts)) - mvcVertDict.keys()
756
+ if missing:
757
+ import time
758
+
759
+ v = time.time()
760
+ print(f"Missing correspondences found. Stored in uvTransfer.MISSING[{v}]")
761
+ MISSING[v] = missing
762
+
763
+ return mvcVertDict
764
+
765
+
766
+ def applyTransfer(parVerts, parFaces, correlation, outputSize: int):
767
+ """Given a vertex corelation, a driver, and driven points,
768
+ Apply the driver deformation to the driven. This could be
769
+ for one frame, or many frames
770
+
771
+ Parameters
772
+ ----------
773
+ parVerts : np.array
774
+ The "parent" vertex positions
775
+ parFaces : [[int, ...], ...]
776
+ The "parent" face list
777
+ correlation : {int: [int, ...], ...}
778
+ A dict correlatng the vertIdx to its possible correlations
779
+ outputSize : (int, ...)
780
+ A numpy output size tuple
781
+
782
+ Returns
783
+ -------
784
+ : np.array
785
+ The new vertex positions
786
+
787
+ """
788
+ if len(parVerts.shape) == 2:
789
+ parVerts = parVerts[None, ...]
790
+
791
+ rows, cols, vals = [], [], []
792
+ for cVertIdx, corrPoss in correlation.items():
793
+ if len(corrPoss) == 1:
794
+ pFaceIdx, bary = corrPoss[0]
795
+ else:
796
+ # pick the one with the highest sum-of-squares
797
+ x = [sum(bary * bary) for _, bary in corrPoss]
798
+ idx = x.index(max(x))
799
+ pFaceIdx, bary = corrPoss[idx]
800
+
801
+ rows.extend([cVertIdx] * len(bary))
802
+ vals.extend(bary)
803
+ cols.extend(parFaces[pFaceIdx])
804
+ M = np.array(rows), np.array(cols), np.array(vals), (outputSize, parVerts.shape[-2])
805
+ out = cooSparseMul(M, parVerts)
806
+ return out
807
+
808
+
809
+ def uvTransfer(
810
+ srcFaces,
811
+ srcUvFaces,
812
+ srcVerts,
813
+ srcUvs,
814
+ tarFaces,
815
+ tarUvFaces,
816
+ tarVerts,
817
+ tarUvs,
818
+ tol=0.0001,
819
+ pBar=None,
820
+ ):
821
+ """A helper function that transfers pre-loaded data.
822
+ The source data will be transferred onto the tar data
823
+
824
+ Parameters
825
+ ----------
826
+ srcFaces : [[int, ...], ...]
827
+ The source vertex face list
828
+ srcUvFaces : [[int, ...], ...]
829
+ The source uv face list
830
+ srcUvs : np.array
831
+ The source UV positions
832
+ tarFaces : [[int, ...], ...]
833
+ The target vertex face list
834
+ tarUvFaces : [[int, ...], ...]
835
+ The target uv face list
836
+ tarUvs : np.array
837
+ The Target UV Positions
838
+ srcVerts : np.array
839
+ The source Vertex positions
840
+ tarVerts : np.array
841
+ The target Vertex positions
842
+ tol : float
843
+ A small tolerance value, defaulting to the global EPS
844
+ pBar : QProgressDialog, optional
845
+ An optional progress dialog
846
+
847
+ Returns
848
+ -------
849
+ : np.array
850
+ The new target vert positions
851
+
852
+ """
853
+ corr = getVertCorrelation(
854
+ srcUvFaces, srcUvs, tarFaces, tarUvFaces, tarUvs, tol=tol, pBar=pBar
855
+ )
856
+ if pBar is not None:
857
+ pBar.setValue(0)
858
+ pBar.setLabelText("Apply Transfer")
859
+ from Qt.QtWidgets import QApplication
860
+
861
+ QApplication.processEvents()
862
+
863
+ return applyTransfer(srcVerts, srcFaces, corr, len(tarVerts))
864
+
865
+
866
+ def uvTransferLoad(
867
+ srcPath, tarPath, srcUvSet="default", tarUvSet="default", tol=0.0001, pBar=None
868
+ ):
869
+ """Transfer the shape from the source to the target through uv space
870
+ Return the data needed to write out the result
871
+
872
+ Parameters
873
+ ----------
874
+ srcPath : str
875
+ The source mesh path (obj, abc, or smpx)
876
+ tarPath : str
877
+ The target mesh path (obj, abc, or smpx)
878
+ srcUvSet : str
879
+ The name of the uv set to use on the source
880
+ tarUvSet : str
881
+ The name of the uv set to use on the target
882
+ tol : float
883
+ A small tolerance value, defaulting to the global EPS
884
+ pBar : QProgressDialog, optional
885
+ An optional progress dialog
886
+
887
+ Returns
888
+ -------
889
+ : np.array
890
+ The target vertex positions
891
+ : list
892
+ The target vertex faces
893
+ : np.array
894
+ The target uvs
895
+ : list
896
+ The target uv faces
897
+
898
+ """
899
+ from . import alembicCommon as abc
900
+ from .mesh import Mesh
901
+
902
+ if srcPath.endswith(".abc") or srcPath.endswith(".smpx"):
903
+ src = Mesh.loadAbc(srcPath, ensureWinding=False)
904
+ srcVerts = abc.getSampleArray(abc.getMesh(srcPath))
905
+ elif srcPath.endswith(".obj"):
906
+ src = Mesh.loadObj(srcPath, ensureWinding=False)
907
+ srcVerts = np.array(src.vertArray)
908
+
909
+ if tarPath.endswith(".abc"):
910
+ tar = Mesh.loadAbc(tarPath, ensureWinding=False)
911
+ elif tarPath.endswith(".obj"):
912
+ tar = Mesh.loadObj(tarPath, ensureWinding=False)
913
+
914
+ srcFaces = src.faceVertArray
915
+ srcUvFaces = src.uvFaceMap[srcUvSet]
916
+ srcUvs = np.array(src.uvMap[srcUvSet])
917
+
918
+ tarFaces = tar.faceVertArray
919
+ tarUvFaces = tar.uvFaceMap[tarUvSet]
920
+ tarUvs = np.array(tar.uvMap[tarUvSet])
921
+ oldTarVerts = np.array(tar.vertArray)
922
+ tarVerts = uvTransfer(
923
+ srcFaces,
924
+ srcUvFaces,
925
+ srcVerts,
926
+ srcUvs,
927
+ tarFaces,
928
+ tarUvFaces,
929
+ oldTarVerts,
930
+ tarUvs,
931
+ tol=tol,
932
+ pBar=pBar,
933
+ )
934
+
935
+ return tarVerts, tarFaces, tarUvs, tarUvFaces
936
+
937
+
938
+ def uvTransferFiles(
939
+ srcPath,
940
+ tarPath,
941
+ outAbcPath,
942
+ srcUvSet: str = "default",
943
+ tarUvSet: str = "default",
944
+ tol: float = 0.0001,
945
+ pBar=None,
946
+ ) -> None:
947
+ """Transfer the shape from the source to the target through uv space
948
+ and write out the result
949
+
950
+ Parameters
951
+ ----------
952
+ srcPath : str
953
+ The source mesh path (obj, abc, or smpx)
954
+ tarPath : str
955
+ The target mesh path (obj, abc, or smpx)
956
+ outAbcPath : str
957
+ The path to the output .abc file
958
+ srcUvSet : str
959
+ The name of the uv set to use on the source
960
+ tarUvSet : str
961
+ The name of the uv set to use on the target
962
+ tol : float
963
+ A small tolerance value, defaulting to the global EPS
964
+ pBar : QProgressDialog, optional
965
+ An optional progress dialog
966
+
967
+ Returns
968
+ -------
969
+
970
+ """
971
+ from . import alembicCommon as abc
972
+
973
+ tarVerts, tarFaces, tarUvs, tarUvFaces = uvTransferLoad(
974
+ srcPath, tarPath, srcUvSet=srcUvSet, tarUvSet=tarUvSet, tol=tol, pBar=pBar
975
+ )
976
+ abc.buildAbc(outAbcPath, tarVerts, tarFaces, uvs=tarUvs, uvFaces=tarUvFaces)