-
Notifications
You must be signed in to change notification settings - Fork 1
/
objectDuplicatorSimple.py
410 lines (316 loc) · 14.5 KB
/
objectDuplicatorSimple.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
import logging
from collections import Counter
import random as r
import time
import math
import os
import functools
from PySide2 import QtGui, QtCore, QtUiTools, QtWidgets
from shiboken2 import wrapInstance
import maya.cmds as mc
import pymel.core as pm
from pymel.core.datatypes import Vector, Matrix, Point
from pymel.all import *
import maya.OpenMayaUI as omui
import maya.api.OpenMaya as om
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.DEBUG)
"""
to add a new path:
import sys
sys.path.append( 'palce path here', Ex: 'C:\Users\yourName\Documents/folderName' )
Otherwise, type this into the Script Editor:
import objectDuplicator as ob
reload(ob)
ob.run()
"""
def getMayaWindow():
""" Pointer to the Maya Main Window
"""
ptr = omui.MQtUtil.mainWindow()
if ptr:
return wrapInstance(long(ptr), QtWidgets.QMainWindow)
def run():
""" Builds the UI. Call This function to run the UI
"""
global win
try:
win.close()
except:
pass
win = ObjectDuplicator(parent=getMayaWindow())
win.show()
def stopwatch(func):
""" Monitors the time it took to run each function
@return: float, total seconds
"""
def timed(*args, **kwargs):
timeStart = time.time()
result = func(*args, **kwargs)
timeEnd = time.time()
elapsedTime = timeEnd - timeStart
_logger.debug("%2.2f sec" % (elapsedTime))
return result
return timed
class ObjectDuplicator(QtWidgets.QMainWindow):
""" Main Class of this Module
"""
def __init__(self, parent=None):
super(ObjectDuplicator, self).__init__(parent)
self.generatedValue = 1.0
self.allDupGroups = []
self.setCentralWidget(QtWidgets.QWidget(self))
self.gridLayout = QtWidgets.QGridLayout()
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setContentsMargins(5, 5, 5, 5)
self.instructionsLabel = QtWidgets.QLabel(
"To use tool, enter name of surface you want objects duplicated on"
" below and then select objects to duplicated."
" A group will be created with all duplicated objects,"
" enter name of group otherwise a default name will be given."
"\nPress button to create geometry.")
self.instructionsLabel.setAlignment(QtCore.Qt.AlignCenter)
self.instructionsLabel.setWordWrap(True)
self.verticalLayout_2.addWidget(self.instructionsLabel)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setContentsMargins(5, 5, 5, 5)
self.nameOfSurfaceLabel = QtWidgets.QLabel("Name of Surface: ")
self.horizontalLayout.addWidget(self.nameOfSurfaceLabel)
self.nameOfSurfaceLineEdit = QtWidgets.QLineEdit()
self.horizontalLayout.addWidget(self.nameOfSurfaceLineEdit)
self.verticalLayout_2.addLayout(self.horizontalLayout)
self.horizontalLayout_11 = QtWidgets.QHBoxLayout()
self.horizontalLayout_11.setContentsMargins(5, 5, 5, 5)
self.nameOfGroupLabel = QtWidgets.QLabel("Name of Group: ")
self.horizontalLayout_11.addWidget(self.nameOfGroupLabel)
self.nameOfGroupLineEdit = QtWidgets.QLineEdit()
self.horizontalLayout_11.addWidget(self.nameOfGroupLineEdit)
self.verticalLayout_2.addLayout(self.horizontalLayout_11)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setContentsMargins(5, 5, 5, 5)
self.percentageGeneratedLabel = QtWidgets.QLabel(
"Percentage Generated: ")
self.horizontalLayout_2.addWidget(self.percentageGeneratedLabel)
self.percentageGeneratedLineEdit = QtWidgets.QLineEdit("1")
self.horizontalLayout_2.addWidget(self.percentageGeneratedLineEdit)
self.percentageGeneratedHorizontalSlider = QtWidgets.QSlider()
self.percentageGeneratedHorizontalSlider.setMinimum(1)
self.percentageGeneratedHorizontalSlider.setMaximum(100)
self.percentageGeneratedHorizontalSlider.setOrientation(
QtCore.Qt.Horizontal)
self.horizontalLayout_2.addWidget(
self.percentageGeneratedHorizontalSlider)
self.setRotationToNormals = QtWidgets.QCheckBox(
"Set Rotation to Surface")
self.horizontalLayout_2.addWidget(
self.setRotationToNormals)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setContentsMargins(5, 5, 5, 5)
self.createGeometryPushButton = QtWidgets.QPushButton("Create Objects")
self.verticalLayout.addWidget(self.createGeometryPushButton)
self.deleteObjectsPushButton = QtWidgets.QPushButton(
"Delete Duplicated Objects Group")
self.verticalLayout.addWidget(self.deleteObjectsPushButton)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.importLabel = QtWidgets.QLabel(
"Import Geometry/Nurbs to be Duplicated:")
self.importLabel.setLayoutDirection(QtCore.Qt.LeftToRight)
self.importLabel.setAlignment(QtCore.Qt.AlignCenter)
self.verticalLayout_3.addWidget(self.importLabel)
self.verticalLayout_2.addLayout(self.verticalLayout_3)
self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
self.horizontalLayout_10.setContentsMargins(5, 5, 5, 5)
self.browsePushButton = QtWidgets.QPushButton("...")
self.horizontalLayout_10.addWidget(self.browsePushButton)
self.fileNameLineEdit = QtWidgets.QLineEdit()
self.horizontalLayout_10.addWidget(self.fileNameLineEdit)
self.importPushButton = QtWidgets.QPushButton("Import")
self.horizontalLayout_10.addWidget(self.importPushButton)
self.verticalLayout_2.addLayout(self.horizontalLayout_10)
self.gridLayout.addLayout(self.verticalLayout_2, 0, 0, 1, 1)
self.initStateOfUI()
self.makeConnections()
self.setWindowTitle("Object Duplicator")
self.centralWidget().setLayout(self.gridLayout)
self.show()
def initStateOfUI(self):
""" Sets the initial state of the UI before anything is done
"""
self.nameOfSurfaceLineEdit.setPlaceholderText("Name of Geometry Here")
self.nameOfGroupLineEdit.setPlaceholderText("Name of Group Here")
self.percentageGeneratedHorizontalSlider.setValue(self.generatedValue)
self.fileNameLineEdit.setPlaceholderText("File Name Here")
def makeConnections(self):
""" All functions to make the UI work
"""
self.percentageGeneratedHorizontalSlider.valueChanged[int].connect(
self.percentageChange)
self.percentageGeneratedLineEdit.editingFinished.connect(
self.manualPercentageEnteredEvent)
self.createGeometryPushButton.clicked.connect(
functools.partial(self.createGeometry))
self.deleteObjectsPushButton.clicked.connect(
functools.partial(self.deleteObjects))
self.browsePushButton.clicked.connect(self.findFile)
self.importPushButton.clicked.connect(self.importFile)
def percentageChange(self, value):
""" Changes the percentage number to mirror the slider
@param value: numbers 1-100
"""
floatValue = int(value)
self.percentageGeneratedLineEdit.setText(str(floatValue))
self.generatedValue = floatValue
def manualPercentageEnteredEvent(self):
""" Forces the slider to mirror the value when a manual percentage is entered
"""
userInputScale = float(self.percentageGeneratedLineEdit.text())
if userInputScale < 1.0:
self.generatedValue = 1.0
elif userInputScale > 100.0:
self.generatedValue = 100.0
else:
self.generatedValue = userInputScale
self.percentageGeneratedHorizontalSlider.setValue(self.generatedValue)
def createGeometry(self):
""" Calls main function to create objects at various vertices and locators
"""
name = self.nameOfSurfaceLineEdit.text()
numberToGenerate = float(self.percentageGeneratedLineEdit.text())/100.0
if self.setRotationToNormals.isChecked():
setToNormals = True
else:
setToNormals = False
if self.nameOfSurfaceLineEdit.text() == "":
_logger.debug(
"Please enter the name of the surface"
" you want objects duplicated on.")
elif len(pm.ls(sl=True)) < 1:
_logger.debug(
"Please select the object you want duplicated.")
else:
self.makeLocators(
numberToGenerate, name, setToNormals)
def deleteObjects(self):
pm.select(cl=True)
pm.delete(self.allDupGroups)
def findFile(self):
""" Opens browser to find a file
"""
fileName = None
dialog = QtWidgets.QFileDialog(directory=os.path.dirname(__file__))
if dialog.exec_():
fileName = dialog.selectedFiles()
if fileName:
self.fileNameLineEdit.setText(fileName[0])
def importFile(self):
""" Imports selected file
"""
fileToImport = self.fileNameLineEdit.text()
mc.file(fileToImport, i=True, iv=True, mnc=False)
@stopwatch
def makeLocators(self, num=None, nameOfSurface=None, setToNormals=None):
""" Populates a given surface with objects.
@param num: int, percentage of geometry to be covered
@param nameOfsurface: str, name of surface
@param nameOfsurface: str, name given by user to determine
the surface
"""
selectedObject = pm.ls(sl=True)
pm.select(nameOfSurface)
pm.select(selectedObject, add=True)
if self.nameOfGroupLineEdit.text() == "":
duplicateGroup = pm.group(n="duplicatedObjectsGrp{0}".format(1), em=True)
else:
duplicateGroup = pm.group(n=self.nameOfGroupLineEdit.text(), em=True)
self.allDupGroups.append(duplicateGroup)
def vertLocators():
""" Iterates through vertices on surface, attaches locators and objects
"""
aimLoc = pm.spaceLocator(n="aimLoc")
# Selects all vertices, puts all vertice coordinates in a list
pm.select(nameOfSurface)
vs = pm.polyEvaluate(v=True)
verts = []
vertLocCount = 0
for i in range(0, vs):
verts += (pm.pointPosition(nameOfSurface + '.vtx[' + str(i) + ']'), )
# Creates locators
for v in verts:
numGen = r.random()
if (numGen <= num):
vertLoc = pm.spaceLocator(
n="vertexLoc{0}".format(1), p=(v[0], v[1], v[2]))
pm.xform(centerPivots=True)
pm.delete(pm.aimConstraint(
aimLoc, vertLoc,
aimVector=[0, -1, 0], upVector=[0, 1, 0],
worldUpVector=[0, 1, 0]))
duplicatedObject = pm.instance(selectedObject, lf=True)
rotVal = pm.getAttr(vertLoc + '.rotate')
pm.setAttr(
duplicatedObject[0] + '.translate', v[0], v[1], v[2])
pm.setAttr(
duplicatedObject[0] + '.rotate', rotVal[0], rotVal[1], rotVal[2])
if setToNormals is False:
pm.setAttr(
duplicatedObject[0] + '.rotate', 0, 0, 0)
pm.setAttr(
vertLoc + '.rotate', 0, 0, 0)
pm.parent(vertLoc, duplicatedObject[0], duplicateGroup)
vertLocCount += 1
pm.delete(aimLoc)
totalVerts = round(float(vertLocCount)/vs*100.0, 2)
_logger.debug("Generated " + str(vertLocCount) + " locators at vertices for " + str(vs) + " possible vertices. (" + str(totalVerts) + "%) ")
def faceLocators():
""" Iterates through faces on surface, attaches locators and objects
"""
aimLoc = pm.spaceLocator(n="aimLoc")
# Selects all faces, puts average center coordinates in a list
pm.select(nameOfSurface)
fc = pm.polyEvaluate(face=True)
faceLocCount = 0
for x in range(0, fc):
numGen = r.random()
bBox = pm.xform(
nameOfSurface + '.f['+str(x)+']',
ws=True, q=True, bb=True)
transX = (bBox[0] + bBox[3])/2
transY = (bBox[1] + bBox[4])/2
transZ = (bBox[2] + bBox[5])/2
# Creates locators
if (numGen <= num):
faceLoc = pm.spaceLocator(
n="faceLoc{0}".format(1), p=(transX, transY, transZ))
pm.xform(centerPivots=True)
pm.delete(pm.aimConstraint(
aimLoc, faceLoc,
aimVector=[0, -1, 0], upVector=[0, 1, 0],
worldUpVector=[0, 1, 0]))
duplicatedObject = pm.instance(selectedObject, lf=True)
rotVal = pm.getAttr(faceLoc + '.rotate')
pm.setAttr(
duplicatedObject[0] + '.translate', transX, transY, transZ)
pm.setAttr(
duplicatedObject[0] + '.rotate', rotVal[0], rotVal[1], rotVal[2])
if setToNormals is False:
pm.setAttr(
duplicatedObject[0] + '.rotate', 0, 0, 0)
pm.setAttr(
faceLoc + '.rotate', 0, 0, 0)
pm.parent(faceLoc, duplicatedObject[0], duplicateGroup)
faceLocCount += 1
pm.delete(aimLoc)
totalFace = round(float(faceLocCount)/fc*100.0, 2)
_logger.debug("Generated " + str(faceLocCount) + " locators at faces for " + str(fc) + " possible surfaces.(" + str(totalFace) + "%) ")
if (num < 0.01 or num > 10.0):
_logger.error("Error. Please input a number between 1 and 100")
elif (pm.objExists(nameOfSurface) is False):
_logger.error(
"Error. Enter a name of a plane that exists in your scene.")
else:
vertLocators()
faceLocators()
pm.select(cl=True)