-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmeshcrawlerDialog.py
492 lines (404 loc) · 14.6 KB
/
meshcrawlerDialog.py
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#import blurdev
#from blurdev.gui import Dialog, loadUi
import os, json
from MeshCrawler.Qt import QtCompat
from MeshCrawler.Qt.QtCore import Qt
from MeshCrawler.Qt.QtWidgets import (QApplication, QProgressDialog, QMessageBox, QFileDialog,
QTableWidgetSelectionRange, QTableWidgetItem, QDialog, QWidget)
from MeshCrawler.meshcrawlerErrors import TopologyMismatch, IslandMismatch
from MeshCrawler.meshcrawlerLib import matchByTopology
from MeshCrawler.meshcrawlerGen import matchGenerator, autoCrawlMeshes, partitionIslands, starMatchGenerator
from MeshCrawler.commands import (getVerts, getFaces, getUVs, selectVerts, getSingleSelection, getObjectName,
getObjectByName, cloneObject, freezeObject, setObjectName, setAllVerts, getVertSelection, createRawObject,
selectAdjacentEdges)
from MeshCrawler.mesh import Mesh
from MeshCrawler.unSubdivide import unSubdivide, getCenters
def getUiFile(fileVar, subFolder="ui", uiName=None):
"""Get the path to the .ui file"""
uiFolder, filename = os.path.split(fileVar)
if uiName is None:
uiName = os.path.splitext(filename)[0]
if subFolder:
uiFile = os.path.join(uiFolder, subFolder, uiName+".ui")
return uiFile
class MatchTopologyWidget(QWidget):
def __init__(self, parent=None):
super(MatchTopologyWidget, self).__init__(parent)
uiPath = getUiFile(__file__, uiName='MatchTopologyWidget')
QtCompat.loadUi(uiPath, self)
self.lastMatch = None
self.uiExportBTN.hide()
self.uiGetOrderBTN.clicked.connect(self.getOrder)
self.uiGetShapeBTN.clicked.connect(self.getShape)
self.uiExportBTN.clicked.connect(self.exportLast)
self.uiPairUpBTN.clicked.connect(self.moveUp)
self.uiPairDownBTN.clicked.connect(self.moveDown)
self.uiPairAddBTN.clicked.connect(self.addPair)
self.uiPairDeleteBTN.clicked.connect(self.deletePair)
self.uiCrawlBTN.clicked.connect(self.crawl)
self.uiGuessBTN.clicked.connect(self.guess)
self.uiGuessNextBTN.clicked.connect(self.guessNext)
self._matchGen = None
self.uiGuessNextBTN.hide()
self.uiGetVertBTN.clicked.connect(self.getVert)
self.uiPairTABLE.itemSelectionChanged.connect(self.selectionChanged)
self._maxHeight = self.uiAdvancedGRP.maximumHeight()
self.uiAdvancedGRP.toggled.connect(self.displayAdvanced)
self.uiAdvancedGRP.setChecked(False)
#self.uiOrderLINE.setText('Order')
#self.uiShapeLINE.setText('Shape')
#self.uiOutputLINE.setText('asdf')
self._orderMesh = None
self._shapeMesh = None
def displayAdvanced(self, shown):
self.uiAdvancedWID.setVisible(shown)
if not shown:
self.uiAdvancedGRP.setFlat(True)
self.uiAdvancedGRP.setMaximumHeight(15)
else:
self.uiAdvancedGRP.setFlat(False)
self.uiAdvancedGRP.setMaximumHeight(self._maxHeight)
def getOrder(self):
sel = getSingleSelection()
if not sel:
return
name = getObjectName(sel)
self.uiOrderLINE.setText(name)
self._orderMesh = None
def getShape(self):
sel = getSingleSelection()
if not sel:
return
name = getObjectName(sel)
self.uiShapeLINE.setText(name)
self._shapeMesh = None
def exportLast(self):
if self.lastMatch is None:
return
d = QFileDialog(self, "Save Last Selection", "", "JSON (*.json);;All Files (*.*)")
d.setAcceptMode(QFileDialog.AcceptSave)
d.setDefaultSuffix('json')
d.exec_()
if d.result():
path = d.selectedFiles()[0]
with open(path, 'w') as f:
json.dump(self.lastMatch, f)
def addPair(self):
rc = self.uiPairTABLE.rowCount()
self.uiPairTABLE.insertRow(rc)
orderObj = QTableWidgetItem()
shapeObj = QTableWidgetItem()
self.uiPairTABLE.setItem(rc, 0, orderObj)
self.uiPairTABLE.setItem(rc, 1, shapeObj)
def deletePair(self):
cur = self.uiPairTABLE.currentRow()
if cur < 0:
return
self.uiPairTABLE.removeRow(cur)
def moveUp(self):
self._move(True)
def moveDown(self):
self._move(False)
def _move(self, goUp):
src = self.uiPairTABLE.currentRow()
col = self.uiPairTABLE.currentColumn()
if goUp and src == 0:
return #cannot move an item at the top up
if not goUp and src == self.uiPairTABLE.rowCount() - 1:
return #cannot move an item at the bottom down
dst = src - 1 if goUp else src + 1
srcItem = self.uiPairTABLE.takeItem(src, col)
dstItem = self.uiPairTABLE.takeItem(dst, col)
self.uiPairTABLE.setItem(src, col, dstItem)
self.uiPairTABLE.setItem(dst, col, srcItem)
unSel = QTableWidgetSelectionRange(src, col, src, col)
toSel = QTableWidgetSelectionRange(dst, col, dst, col)
self.uiPairTABLE.setRangeSelected(unSel, False)
self.uiPairTABLE.setRangeSelected(toSel, True)
self.uiPairTABLE.setCurrentCell(dst, col)
def _orderObject(self):
name = self.uiOrderLINE.text()
return getObjectByName(name)
def _shapeObject(self):
name = self.uiShapeLINE.text()
return getObjectByName(name)
def getVert(self):
col = self.uiPairTABLE.currentColumn()
thing = self._orderObject() if col == 0 else self._shapeObject()
item = self.uiPairTABLE.currentItem()
if getVerts is not None:
val = getVerts(thing)
if val is not None:
item.setData(Qt.EditRole, val)
def loadMeshes(self, step, pBar):
oo = self._orderObject()
so = self._shapeObject()
if oo is None or so is None:
QMessageBox.warning(self, "Get objects", "Must have order and shape loaded")
if self._orderMesh is None:
orderVerts = getVerts(oo)
orderFaces = getFaces(oo)
orderUVs, orderUVFaces = getUVs(oo)
pBar.setLabelText("Loading Order")
QApplication.processEvents()
self._orderMesh = Mesh(orderVerts, orderFaces, uvs=orderUVs, uvFaces=orderUVFaces)
pBar.setValue(pBar.value() + step)
if self._shapeMesh is None:
shapeVerts = getVerts(so)
shapeFaces = getFaces(so)
shapeUVs, shapeUVFaces = getUVs(so)
pBar.setLabelText("Loading Shape")
QApplication.processEvents()
self._shapeMesh = Mesh(shapeVerts, shapeFaces, uvs=shapeUVs, uvFaces=shapeUVFaces)
pBar.setValue(pBar.value() + step)
def guess(self):
oo = self._orderObject()
so = self._shapeObject()
if oo is None or so is None:
QMessageBox.warning(self, "Get objects", "Must have order and shape loaded")
return
pBar = QProgressDialog(self)
pBar.show()
pBar.setValue(0)
self.loadMeshes(33, pBar)
pBar.setLabelText("Partitioning islands")
QApplication.processEvents()
self._matchGen = matchGenerator(self._orderMesh, self._shapeMesh, skipMismatchedIslands=True)
self.uiGuessNextBTN.show()
self.guessNext()
pBar.close()
def guessNext(self):
try:
sm = next(self._matchGen)
except StopIteration:
self._matchGen = None
self.uiGuessNextBTN.hide()
QMessageBox.warning(self, "No more guesses", "No more guesses")
return
for _ in range(self.uiPairTABLE.rowCount()):
self.uiPairTABLE.removeRow(0)
for i, pair in enumerate(sm):
self.uiPairTABLE.insertRow(i)
orderObj = QTableWidgetItem()
shapeObj = QTableWidgetItem()
self.uiPairTABLE.setItem(i, 0, orderObj)
self.uiPairTABLE.setItem(i, 1, shapeObj)
orderObj.setData(Qt.EditRole, pair[0])
shapeObj.setData(Qt.EditRole, pair[1])
def _getItemData(self, item):
if item is None:
return None
data = item.data(Qt.EditRole)
try:
data = int(data)
except (ValueError, TypeError):
return None
return data
def getPairData(self):
pairs = []
for row in range(self.uiPairTABLE.rowCount()):
pair = []
for col in [0, 1]:
item = self.uiPairTABLE.item(row, col)
data = self._getItemData(item)
if data is None:
raise ValueError("All cells must be filled in")
pair.append(data)
pairs.append(tuple(pair))
return pairs
def selectionChanged(self):
sel = self.uiPairTABLE.selectedItems()
row = self.uiPairTABLE.currentRow()
col = self.uiPairTABLE.currentColumn()
if len(sel) > 1:
maxRow = self.uiPairTABLE.rowCount() - 1
maxCol = self.uiPairTABLE.columnCount() - 1
unSel = QTableWidgetSelectionRange(0, 0, maxRow, maxCol)
toSel = QTableWidgetSelectionRange(row, col, row, col)
self.uiPairTABLE.setRangeSelected(unSel, False)
self.uiPairTABLE.setRangeSelected(toSel, True)
if self.uiSelectVertsCHK.isChecked():
curItem = self.uiPairTABLE.currentItem()
if curItem.isSelected():
data = self._getItemData(curItem)
else:
data = None
obj = self._orderObject() if col == 0 else self._shapeObject()
if selectVerts is not None:
selectVerts(obj, data)
def _crawlAdvanced(self, pairs, orderMesh, shapeMesh, pBar):
ois = [frozenset(i) for i in partitionIslands(orderMesh)]
sis = [frozenset(i) for i in partitionIslands(shapeMesh)]
oVals, sVals = zip(*pairs)
oCheck, sCheck = {}, {}
oOnes, sOnes = [], []
orderObj = self.uiOrderLINE.text()
shapeObj = self.uiShapeLINE.text()
for isles, vals, check in ((ois, oVals, oCheck), (sis, sVals, sCheck)):
for i in isles:
for v in vals:
if v in i:
check.setdefault(i, []).append(v)
for check, obj, ones in ((oCheck, orderObj, oOnes), (sCheck, shapeObj, sOnes)):
for val in check.values():
if len(val) not in [1, 3]:
QMessageBox.warning(self, "Selection error",
"Must have exactly 1 or 3 verts on an island. Found on {0} {1}: {2}".format(
obj, len(val), val))
raise TopologyMismatch()
elif len(val) == 1:
ones.append(val[0])
vertNum = len(orderMesh.vertArray)
if not oOnes and not sOnes:
matches = [matchByTopology(orderMesh, shapeMesh, pairs, vertNum=vertNum, pBar=pBar)]
else:
matches = []
pairs = [tuple(i) for i in pairs]
buildPairs = []
for overts in oCheck.itervalues():
for sverts in sCheck.itervalues():
zPairs = zip(overts, sverts)
if all([p in pairs for p in zPairs]):
buildPairs.append(zPairs)
for zPairs in buildPairs:
if len(zPairs) == 1:
for starPairs in starMatchGenerator(orderMesh, shapeMesh, zPairs[0][0], zPairs[0][1]):
try:
match = matchByTopology(orderMesh, shapeMesh, starPairs, vertNum=vertNum, pBar=pBar)
break
except TopologyMismatch:
pass
else:
raise TopologyMismatch("Mismatch found in single-vert pairing: {0}".format(zPairs[0]))
else:
match = matchByTopology(orderMesh, shapeMesh, zPairs, vertNum=vertNum, pBar=pBar)
matches.append(match)
return matches
def crawl(self):
pairs = None
if self.uiAdvancedGRP.isChecked():
try:
pairs = self.getPairData()
except ValueError:
pass
if not pairs:
QMessageBox.warning(self, "Could not get Vert pairs", "All vert pairs must be fully defined")
return
pBar = QProgressDialog(self)
pBar.show()
pBar.setLabelText("Crawling")
pBar.setValue(0)
QApplication.setOverrideCursor(Qt.WaitCursor)
QApplication.processEvents()
self.loadMeshes(33, pBar)
skipMismatchedIslands = False # someday figure out how to make this work
match = None
title = 'No Match Found'
msg = 'No Match Found'
QApplication.processEvents()
try:
if self.uiAdvancedGRP.isChecked():
match = self._crawlAdvanced(pairs, self._orderMesh, self._shapeMesh, pBar)
else:
match = autoCrawlMeshes(self._orderMesh, self._shapeMesh,
skipMismatchedIslands=skipMismatchedIslands, pBar=pBar)
except TopologyMismatch as m:
title = 'Topology Mismatch'
msg = str(m) or title
except IslandMismatch as m:
title = 'Island Mismatch'
msg = str(m) or title
finally:
QApplication.restoreOverrideCursor()
if not match:
pBar.close()
QMessageBox.warning(self, title, msg)
return
pBar.setValue(0)
pBar.setLabelText("Building output")
allMatch = []
for m in match:
allMatch.extend(m)
allMatch = sorted(allMatch)
orderObj = self._orderObject()
shapeObj = self._shapeObject()
shapeVerts = getVerts(shapeObj)
orderVerts = getVerts(orderObj)
nn = str(self.uiOutputLINE.text())
fixitObject = cloneObject(orderObj, nn)
freezeObject(fixitObject)
self.lastMatch = allMatch
for oIdx, sIdx in allMatch:
orderVerts[oIdx] = shapeVerts[sIdx]
setAllVerts(fixitObject, orderVerts)
self.uiExportBTN.show()
pBar.close()
class UnSubdivideWidget(QWidget):
def __init__(self, parent=None):
super(UnSubdivideWidget, self).__init__(parent)
uiPath = getUiFile(__file__, uiName='UnSubdivideWidget')
QtCompat.loadUi(uiPath, self)
self.uiGetUnsubObjBTN.clicked.connect(self.getObjectFromSelection)
self.uiGetHintsBTN.clicked.connect(self.getVertsFromSelection)
self.uiUnSubdivideBTN.clicked.connect(self.doUnsub)
def getObjectFromSelection(self):
obj = getSingleSelection()
if not obj:
return
objName = getObjectName(obj)
self.uiUnsubObjLINE.setText(objName)
def getVertsFromSelection(self):
obj = self._getObject()
if obj is None:
QMessageBox.warning(self, "Get objects", "Must have an object loaded first")
return
sel = getVertSelection(obj)
val = ','.join(map(str, sel)) if sel else ''
self.uiManualHintsLINE.setText(val)
def _getObject(self):
objName = str(self.uiUnsubObjLINE.text())
if not objName:
return None
return getObjectByName(objName)
def _getHints(self):
hints = str(self.uiManualHintsLINE.text())
if not hints:
return None
hints = hints.strip().split(',')
hints = [int(i.strip()) for i in hints]
return hints
def doUnsub(self):
obj = self._getObject()
if obj is None:
QMessageBox.warning(self, "Get objects", "Must have an object loaded first")
return
pBar = QProgressDialog(self)
pBar.setLabelText("Unsubdividing")
pBar.setValue(0)
pBar.setMaximum(100)
hints = self._getHints()
verts = getVerts(obj)
faces = getFaces(obj)
uvs, uvFaces = getUVs(obj)
if self.uiSelectEdgesRDO.isChecked():
centers = getCenters(faces, pBar=pBar)
selectAdjacentEdges(obj, centers)
else:
newName = getObjectName(obj)
newName = newName + "_UNSUB"
repositionVerts = self.uiUpdatePositionsRDO.isChecked()
pinBorders = self.uiPinBordersCHK.isChecked()
rFaces, rVerts, rUVFaces, rUVs = unSubdivide(faces, verts, uvFaces, uvs,
hints=hints, repositionVerts=repositionVerts, pinBorders=pinBorders, pBar=pBar)
createRawObject(newName, rFaces, rVerts, rUVFaces, rUVs)
class MeshCrawlerDialog(QDialog):
def __init__(self, parent=None):
super(MeshCrawlerDialog, self).__init__(parent)
uiPath = getUiFile(__file__)
QtCompat.loadUi(uiPath, self)
self.uiTopologyWID = MatchTopologyWidget(self.uiTopologyParWID)
topoLay = self.uiTopologyParWID.layout()
topoLay.addWidget(self.uiTopologyWID)
self.uiUnSubWID = UnSubdivideWidget(self.uiUnSubParWID)
subLay = self.uiUnSubParWID.layout()
subLay.addWidget(self.uiUnSubWID)