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