-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path__init__.py
2590 lines (2007 loc) · 90.9 KB
/
__init__.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
import re
import math
import base64
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import pymel.core as pm
import pymel.api as api
import maya.cmds as cmds
from shiboken2 import wrapInstance
mayaMainWindow = wrapInstance(int(api.MQtUtil.mainWindow()), QMainWindow)
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
NiceColors = ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#8B00FF', '#FF00FF', '#FF1493', '#FF69B4', '#FFC0CB', '#FFD700', '#32CD32', '#00FF7F', '#1E90FF', '#8A2BE2']
if sys.version_info.major > 2:
RootDirectory = os.path.dirname(__file__)
else:
RootDirectory = os.path.dirname(__file__.decode(sys.getfilesystemencoding()))
PickerWindows = []
Clipboard = []
def getNodeColor(node):
MayaIndexColors = {
0: '#787878',1: '#000000', 2: '#404040',
3: '#808080', 4: '#9b0028', 5: '#000460',
6: '#0000ff', 7: '#494949',8: '#260043',
9: '#c800c8', 10: '#8a4833',11: '#3f231f',
12: '#992600', 13: '#ff0000',14: '#00ff00',
15: '#004199', 16: '#ffffff', 17: '#ffff00',
18: '#64dcff', 19: '#43ffa3', 20: '#ffb0b0',
21: '#e4ac79', 22: '#ffff63', 23: '#009954',
24: '#a16a30', 25: '#9ea130',26: '#68a130',
27: '#30a15d', 28: '#30a1a1', 29: '#3067a1',
30: '#6f30a1', 31: '#a1306a'}
node = pm.PyNode(node)
if isinstance(node, pm.nt.Transform):
sh = node.getShape()
if sh and sh.overrideEnabled.get():
return MayaIndexColors[sh.overrideColor.get()]
def color2hex(r,g,b):
return "#%0.2x%0.2x%0.2x"%(r,g,b)
def size2scale(s):
return 25 * (s/100.0 - 1.0)
class PickerItem(object):
def __init__(self, svgpath="M 0 0 h 100 v 100 h -100 v -100 Z"):
self.position = [0,0]
self.background = "#eaa763"
self.foreground = "#000000"
self.image = "" # pixmap bytes
self.imageAspectRatio = 0 # 0-IgnoreAspectRatio, 1-KeepAspectRatio, 2-KeepAspectRatioByExpanding
self.control = ""
self.label = ""
self.font = ""
self.script = ""
self.flat = True # draw specular gradient when True
self.flipped = [False, False]
self.rotated = False
self.scale = [-15, -15] # steps of grid size
self.group = "" # used in double clicks
self.svgpath = svgpath
def copy(self, other):
self.position = other.position[:]
self.background = other.background
self.foreground = other.foreground
self.image = other.image
self.imageAspectRatio = other.imageAspectRatio
self.control = other.control
self.label = other.label
self.font = other.font
self.script = other.script
self.flat = other.flat
self.flipped = other.flipped[:]
self.rotated = other.rotated
self.scale = other.scale[:]
self.group = other.group
self.svgpath = other.svgpath
def duplicate(self):
a = PickerItem()
a.copy(self)
return a
def toJson(self):
return {"position":self.position,
"background":self.background,
"foreground":self.foreground,
"image":self.image,
"imageAspectRatio":self.imageAspectRatio,
"control":self.control,
"label": self.label,
"font": self.font,
"script": self.script,
"flat":self.flat,
"flipped":self.flipped,
"rotated":self.rotated,
"scale":self.scale,
"group":self.group,
"svgpath":self.svgpath}
def fromJson(self, data):
self.position = data["position"]
self.background = data["background"]
self.foreground = data["foreground"]
self.image = data["image"]
self.imageAspectRatio = data["imageAspectRatio"]
self.control = data["control"]
self.label = data["label"]
self.font = data.get("font", "")
self.script = data["script"]
self.flat = data["flat"]
self.flipped = data["flipped"]
self.rotated = data["rotated"]
self.scale = data["scale"]
self.group = data["group"]
self.svgpath = data["svgpath"]
class Picker(object):
def __init__(self, name=""):
self.name = name
self.items = []
self.size = [0,0]
self.scale = 1
def copy(self, other):
self.name = other.name
self.items = [item.duplicate() for item in other.items]
self.size = other.size[:]
self.scale = other.scale
def isEmpty(self):
return len(self.items)==0
def duplicate(self):
a = Picker()
a.copy(self)
return a
def toJson(self):
return {"name": self.name, "items": [item.toJson() for item in self.items], "size":self.size, "scale": self.scale}
def fromJson(self, data):
self.name = data["name"]
self.size = data["size"]
self.scale = data.get("scale", 1)
self.items = []
for d in data["items"]:
item = PickerItem()
item.fromJson(d)
self.items.append(item)
def findSymmetricName(name, left=True, right=True):
L_starts = {"L_": "R_", "l_": "r_", "Left":"Right", "left_": "right_"}
L_ends = {"_L": "_R", "_l": "_r", "Left": "Right", "_left":"_right"}
R_starts = {"R_": "L_", "r_": "l_", "Right":"Left", "right_":"left_"}
R_ends = {"_R": "_L", "_r": "_l", "Right":"Left", "_right":"_left"}
for enable, starts, ends in [(left, L_starts, L_ends), (right, R_starts, R_ends)]:
if enable:
for s in starts:
if name.startswith(s):
return starts[s] + name[len(s):]
for s in ends:
if name.endswith(s):
return name[:-len(s)] + ends[s]
return name
def pixmap2str(pixmap):
ba = QByteArray()
buf = QBuffer(ba)
buf.open(QIODevice.WriteOnly)
pixmap.save(buf, "JPG", 100)
buf.close()
return base64.b64encode(ba.data())
def str2pixmap(pixmapStr):
pixmap = QPixmap()
pixmap.loadFromData(base64.b64decode(pixmapStr))
return pixmap
def mayaVisibilityCallback(attr, item, hierarchy):
if not pm.getAttr(attr):
item.isMayaControlHidden = True
else: # check children
item.isMayaControlHidden = False
for ch in hierarchy:
if not ch.v.get():
item.isMayaControlHidden = True
break
item.update()
def mayaSelectionChangedCallback(scene, controlItemDict):
if not controlItemDict:
return
scene.blockSignals(True)
scene.clearSelection()
ls = cmds.ls(sl=True)
for node in ls:
items = controlItemDict.get(node,[]) # found available item for the control
for item in items:
item.setSelected(True)
scene.blockSignals(False)
def splitString(s):
return re.split("[ ,;]+", s)
def roundTo(n, k=5):
_round = lambda num: k * round(float(num) / k, 0)
T = type(n)
if T in [int, float]:
return _round(n)
elif T in [QPoint, QPointF]:
return T(_round(n.x()), _round(n.y()))
elif T in [QRect, QRectF]:
return T(_round(n.x()), _round(n.y()), _round(n.width()), _round(n.height()))
def clamp(val, mn, mx):
if val < mn:
return mn
elif val > mx:
return mx
return val
def enlargeRect(rect, offset):
if isinstance(rect, QRectF):
offsetPoint = QPointF(offset, offset)
else:
offsetPoint = QPoint(offset, offset)
rect.setTopLeft(rect.topLeft() - offsetPoint)
rect.setBottomRight(rect.bottomRight() + offsetPoint)
return rect
def parsePath(path):
commands = []
currentCommand = ""
commandNumbers = []
currentNumber = ""
sign = 1
for c in path+" ":
if c in ["M", "m", "L", "l", "H", "h", "V", "v", "C", "c", "Q", "q", "A", "a", "Z", "z", "T", "t", "S", "s"]:
if currentNumber:
commandNumbers.append(float(currentNumber)*sign)
sign = 1
currentNumber = ""
if currentCommand:
commands.append((currentCommand, commandNumbers))
commandNumbers = []
currentCommand = c
currentNumber = ""
sign = 1
elif c in ["0","1","2","3","4","5","6","7","8","9","."]:
currentNumber += c
else:
if currentNumber:
commandNumbers.append(float(currentNumber)*sign)
currentNumber = ""
sign = -1 if c == "-" else 1
commands.append((currentCommand, commandNumbers))
return commands
def pathArc(path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, x, y, curx, cury):
# translated from https://code.qt.io/cgit/qt/qtsvg.git/tree/src/svg/qsvghandler.cpp
def pathArcSegment(path, xc, yc, th0, th1, rx, ry, xAxisRotation):
sinTh = math.sin(xAxisRotation * (math.pi / 180.0))
cosTh = math.cos(xAxisRotation * (math.pi / 180.0))
a00 = cosTh * rx
a01 = -sinTh * ry
a10 = sinTh * rx
a11 = cosTh * ry
thHalf = 0.5 * (th1 - th0)
t = (8.0 / 3.0) * math.sin(thHalf * 0.5) * math.sin(thHalf * 0.5) / math.sin(thHalf)
x1 = xc + math.cos(th0) - t * math.sin(th0)
y1 = yc + math.sin(th0) + t * math.cos(th0)
x3 = xc + math.cos(th1)
y3 = yc + math.sin(th1)
x2 = x3 + t * math.sin(th1)
y2 = y3 - t * math.cos(th1)
path.cubicTo(a00 * x1 + a01 * y1, a10 * x1 + a11 * y1,
a00 * x2 + a01 * y2, a10 * x2 + a11 * y2,
a00 * x3 + a01 * y3, a10 * x3 + a11 * y3)
Pr1 = rx * rx
Pr2 = ry * ry
if Pr1==0 or Pr2==0:
return
rx = abs(rx)
ry = abs(ry)
sin_th = math.sin(x_axis_rotation * (math.pi / 180.0))
cos_th = math.cos(x_axis_rotation * (math.pi / 180.0))
dx = (curx - x) / 2.0
dy = (cury - y) / 2.0
dx1 = cos_th * dx + sin_th * dy
dy1 = -sin_th * dx + cos_th * dy
Px = dx1 * dx1
Py = dy1 * dy1
# Spec : check if radii are large enough
check = Px / Pr1 + Py / Pr2
if check > 1:
rx = rx * math.sqrt(check)
ry = ry * math.sqrt(check)
a00 = cos_th / rx
a01 = sin_th / rx
a10 = -sin_th / ry
a11 = cos_th / ry
x0 = a00 * curx + a01 * cury
y0 = a10 * curx + a11 * cury
x1 = a00 * x + a01 * y
y1 = a10 * x + a11 * y
# (x0, y0) is current point in transformed coordinate space.
# (x1, y1) is new point in transformed coordinate space.
# The arc fits a unit-radius circle in this space.
d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)
if d == 0:
return
sfactor_sq = 1.0 / d - 0.25
if sfactor_sq < 0: sfactor_sq = 0
sfactor = math.sqrt(sfactor_sq)
if sweep_flag == large_arc_flag: sfactor = -sfactor
xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0)
yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0)
# (xc, yc) is center of the circle.
th0 = math.atan2(y0 - yc, x0 - xc)
th1 = math.atan2(y1 - yc, x1 - xc)
th_arc = th1 - th0
if th_arc < 0 and sweep_flag:
th_arc += 2 * math.pi
elif th_arc > 0 and not sweep_flag:
th_arc -= 2 * math.pi
n_segs = int(math.ceil(abs(th_arc / (math.pi * 0.5 + 0.001))))
for i in range(n_segs):
pathArcSegment(path, xc, yc,
th0 + i * th_arc / n_segs,
th0 + (i + 1) * th_arc / n_segs,
rx, ry, x_axis_rotation)
def getPainterPath(path, scaleX=1, scaleY=1, flipX=False, flipY=False, rotate=False):
# translated from https://code.qt.io/cgit/qt/qtsvg.git/tree/src/svg/qsvghandler.cpp
scaledPointF = lambda p: QPointF(p.x()*scaleX, p.y()*scaleY)
painterPath = QPainterPath()
data = parsePath(path)
if flipX or flipY:
tmp = getPainterPath(path, 1, 1, False, False, rotate)
rect = tmp.boundingRect()
maxX = rect.width()
maxY = rect.height()
x0, y0 = 0, 0 ## starting point
x, y = 0,0 # current point
lastMode = ""
ctrlPt = QPointF()
for cmd, numbers in data:
#cp = painterPath.currentPosition()
offsetX, offsetY = x, y
if rotate:
cmdInversion = {"h":"v", "H":"V", "v":"h", "V": "H"}
cmd = cmdInversion.get(cmd, cmd)
if cmd not in ["h", "H", "v", "V"]:
newNumbers = [0]*len(numbers)
for i in range(0, len(numbers), 2):
newNumbers[i] = numbers[i+1]
newNumbers[i+1] = numbers[i]
numbers = newNumbers
if flipX or flipY:
for i in range(len(numbers)):
if flipX and cmd == "H":
numbers[i] = maxX-numbers[i]
if flipX and cmd == "h":
numbers[i] *= -1
elif flipY and cmd == "V":
numbers[i] = maxY-numbers[i]
elif flipY and cmd == "v":
numbers[i] *= -1
elif cmd in ["M", "m", "L", "l", "C", "c", "Q", "q", "T", "t", "S", "s"]:
if flipX and i%2==0: # x
numbers[i] = maxX-numbers[i]
if flipY and i%2!=0: # y
numbers[i] = maxY-numbers[i]
elif cmd == "A":
if flipX: numbers[5] = maxX-numbers[5]
if flipY: numbers[6] = maxY-numbers[6]
if cmd == "M":
x = x0 = numbers[0]
y = y0 = numbers[1]
painterPath.moveTo(x0*scaleX, y0*scaleY)
elif cmd == "m":
x = x0 = numbers[0] + offsetX
y = y0 = numbers[1] + offsetY
painterPath.moveTo(x0*scaleX, y0*scaleY)
elif cmd == "L":
x = numbers[0]
y = numbers[1]
painterPath.lineTo(x*scaleX, y*scaleY)
elif cmd == "l":
x = numbers[0] + offsetX
y = numbers[1] + offsetY
painterPath.lineTo(x*scaleX, y*scaleY)
elif cmd == "H":
x = numbers[0]
painterPath.lineTo(x*scaleX, y*scaleY)
elif cmd == "h":
x = numbers[0] + offsetX
painterPath.lineTo(x*scaleX, y*scaleY)
elif cmd == "V":
y = numbers[0]
painterPath.lineTo(x*scaleX, y*scaleY)
elif cmd == "v":
y = numbers[0] + offsetY
painterPath.lineTo(x*scaleX, y*scaleY)
elif cmd == "C":
c1 = QPointF(numbers[0], numbers[1])
c2 = QPointF(numbers[2], numbers[3])
e = QPointF(numbers[4], numbers[5])
painterPath.cubicTo(scaledPointF(c1), scaledPointF(c2), scaledPointF(e))
ctrlPt = c2
x = e.x()
y = e.y()
elif cmd == "c":
c1 = QPointF(numbers[0] + offsetX, numbers[1] + offsetY)
c2 = QPointF(numbers[2] + offsetX, numbers[3] + offsetY)
e = QPointF(numbers[4] + offsetX, numbers[5] + offsetY)
painterPath.cubicTo(scaledPointF(c1), scaledPointF(c2), scaledPointF(e))
ctrlPt = c2
x = e.x()
y = e.y()
elif cmd == "S":
c1 = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y()) if lastMode in ["C", "c", "S", "s"] else QPointF(x, y)
c2 = QPointF(numbers[0], numbers[1])
e = QPointF(numbers[2], numbers[3])
path.cubicTo(scaledPointF(c1), scaledPointF(c2), scaledPointF(e))
ctrlPt = c2
x = e.x()
y = e.y()
elif cmd == "s":
c1 = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y()) if lastMode in ["C", "c", "S", "s"] else QPointF(x, y)
c2 = QPointF(numbers[0] + offsetX, numbers[1] + offsetY)
e = QPointF(numbers[2] + offsetX, numbers[3] + offsetY)
path.cubicTo(scaledPointF(c1), scaledPointF(c2), scaledPointF(e))
ctrlPt = c2
x = e.x()
y = e.y()
elif cmd == "Q":
c = QPointF(numbers[0], numbers[1])
e = QPointF(numbers[2], numbers[3])
painterPath.quadTo(scaledPointF(c), scaledPointF(e))
ctrlPt = c
x = e.x()
y = e.y()
elif cmd == "q":
c = QPointF(numbers[0] + offsetX, numbers[1] + offsetY)
e = QPointF(numbers[2] + offsetX, numbers[3] + offsetY)
painterPath.quadTo(scaledPointF(c), scaledPointF(e))
ctrlPt = c
x = e.x()
y = e.y()
elif cmd in ["Z", "z"]:
painterPath.closeSubpath()
x = x0
y = y0
elif cmd == "T":
e = QPointF(numbers[0], numbers[1])
c = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y()) if lastMode in ["Q", "q", "T", "t"] else QPointF(x, y)
painterPath.quadTo(scaledPointF(c), scaledPointF(e))
ctrlPt = c
x = e.x()
y = e.y()
elif cmd == "t":
e = QPointF(numbers[0] + offsetX, numbers[1] + offsetY)
c = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y()) if lastMode in ["Q", "q", "T", "t"] else QPointF(x, y)
painterPath.quadTo(scaledPointF(c), scaledPointF(e))
ctrlPt = c
x = e.x()
y = e.y()
elif cmd == "A":
rx, ry, xAxisRotation, largeArcFlag, sweepFlag, ex, ey = numbers
curx = x
cury = y
pathArc(painterPath, rx, ry, xAxisRotation, int(largeArcFlag), int(sweepFlag), ex*scaleX, ey*scaleY, curx*scaleX, cury*scaleY)
x = ex
y = ey
elif cmd == "a":
rx, ry, xAxisRotation, largeArcFlag, sweepFlag, ex, ey = numbers
ex += offsetX
ey += offsetY
curx = x
cury = y
pathArc(painterPath, rx, ry, xAxisRotation, int(largeArcFlag), int(sweepFlag), ex*scaleX, ey*scaleY, curx*scaleX, cury*scaleY)
x = ex
y = ey
lastMode = cmd
rect = painterPath.boundingRect()
painterPath.translate(-rect.x(), -rect.y())
painterPath.setFillRule(Qt.WindingFill)
return painterPath
def clearLayout(layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.setParent(None)
else:
clearLayout(item.layout())
class ScaleAnchorItem(QGraphicsItem):
Size = 12
def __init__(self, **kwargs):
super(ScaleAnchorItem, self).__init__(**kwargs)
self.setCursor(Qt.CrossCursor)
self.painterPath = getPainterPath("M 0 0 L 0 -{v} L -{v} 0 Z".format(v=ScaleAnchorItem.Size))
self.isDragging = False
self.dragDelta = None
self.dragPos = None
self.dragScales = None
def shape(self):
return self.painterPath
def boundingRect(self):
return self.shape().boundingRect()
def paint(self, painter, option, widget=None):
painter.setPen(Qt.NoPen)
painter.setBrush(QBrush(QColor(255,255,255, 150)))
if self.parentItem().isSelected():
painter.drawPath(self.shape())
def mouseMoveEvent(self, event):
deltaX = int((event.scenePos().x()-self.dragPos.x()) / 5)
deltaY = int((event.scenePos().y()-self.dragPos.y()) / 5)
selection = self.scene().sortedSelection()
for i, item in enumerate(selection):
item.setUnitScale(QVector2D(self.dragScales[i].x()+deltaX, self.dragScales[i].y()+deltaY))
def mousePressEvent(self, event):
if event.buttons() in [Qt.LeftButton,Qt.MiddleButton]:
self.isDragging = True
self.dragPos = event.scenePos()
self.dragScales = []
for item in self.scene().sortedSelection():
self.dragScales.append(item.unitScale())
def mouseReleaseEvent(self, event):
self.isDragging = False
class SceneItem(QGraphicsItem):
ShadowOffset = 5
def __init__(self, pickerItem, **kwargs):
super(SceneItem, self).__init__(**kwargs)
self.isMayaControlHidden = False
self.isMayaControlInvalid = False
self.pickerItem = pickerItem
self.imagePixmap = None
self.painterPath = getPainterPath(pickerItem.svgpath)
self.scaleAnchorItem = ScaleAnchorItem()
self.scaleAnchorItem.setVisible(False)
self.scaleAnchorItem.setParentItem(self)
self.isHover = False
self._isDragging = False
self._startPos = None
self._lastPos = None
self.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemSelectedChange | QGraphicsItem.ItemSendsGeometryChanges | QGraphicsItem.ItemIsMovable)
self.setAcceptHoverEvents(True)
self.updateScaleAnchor()
shadowEffect = QGraphicsDropShadowEffect()
shadowEffect.setOffset(2)
self.setGraphicsEffect(shadowEffect)
self.setUnitScale(QVector2D(self.pickerItem.scale[0],self.pickerItem.scale[1]))
def copy(self, other):
self.pickerItem.copy(other.pickerItem)
self.updateShape()
def unitScale(self):
return QVector2D(self.pickerItem.scale[0], self.pickerItem.scale[1])
def updateShape(self):
scaleX = self.pickerItem.scale[0] / 25 + 1
scaleY = self.pickerItem.scale[1] / 25 + 1
self.prepareGeometryChange()
self.painterPath = getPainterPath(self.pickerItem.svgpath, scaleX, scaleY, self.pickerItem.flipped[0], self.pickerItem.flipped[1], self.pickerItem.rotated)
self.imagePixmap = QPixmap()
pixmap = None
if self.pickerItem.image.startswith("/9j/"): # image bytes
pixmap = str2pixmap(self.pickerItem.image)
else:
imagePath = os.path.expandvars(self.pickerItem.image)
if os.path.exists(imagePath):
pixmap = QPixmap()
pixmap.load(imagePath)
if pixmap:
aspectRatio = {0:Qt.IgnoreAspectRatio, 1:Qt.KeepAspectRatio, 2: Qt.KeepAspectRatioByExpanding}
boundingRect = self.painterPath.boundingRect()
self.imagePixmap = pixmap.scaled(boundingRect.width(), boundingRect.height(), aspectRatio[self.pickerItem.imageAspectRatio], Qt.SmoothTransformation)
self.setZValue(-1)
self.updateScaleAnchor()
def setUnitScale(self, scale):
if self.scene():
self.scene().undoAppendForSelected("scale")
if scale:
self.pickerItem.scale[0] = clamp(scale.x(),-25+2, scale.x())
self.pickerItem.scale[1] = clamp(scale.y(),-25+2, scale.y())
self.updateShape()
def itemChange(self, change, value):
scene = self.scene()
if not scene:
return super(SceneItem, self).itemChange(change, value)
if change == QGraphicsItem.ItemSelectedChange:
self.scaleAnchorItem.setVisible(value and scene.editMode())
if (not scene.editMode() or scene.isImagesLocked) and self.pickerItem.image:
pm.select(cl=True)
value = False
elif change == QGraphicsItem.ItemPositionChange:
scene.undoAppendForSelected("move")
value = roundTo(value)
self.pickerItem.position = [value.x(), value.y()]
scene.mayaParameters.pickerIsModified = True
return super(SceneItem, self).itemChange(change, value)
def updateScaleAnchor(self):
boundingRect = self.boundingRect()
offset = ScaleAnchorItem.Size/2
self.scaleAnchorItem.setPos(boundingRect.width()-offset, boundingRect.height()-offset)
def boundingRect(self):
return self.shape().boundingRect()
def shape(self):
return self.painterPath
def paint(self, painter, option, widget=None):
painter.setRenderHints(QPainter.Antialiasing)
boundingRect = self.boundingRect()
if self.pickerItem.image:
painter.drawPixmap(0,0,self.imagePixmap)
else:
if self.pickerItem.background:
background = self.pickerItem.background if not self.isSelected() else "#eeeeee"
pen = QPen(QColor(background).darker(200))
pen.setCosmetic(True) # don't change line width while scaling
if self.pickerItem.flat:
brushStyle = Qt.SolidPattern
background = QColor(background).lighter(133) if self.isHover else background
gradient = None
else:
brushStyle = Qt.LinearGradientPattern
gradient = QLinearGradient(boundingRect.topLeft(),boundingRect.center())
gradient.setColorAt(0.4, QColor(255,255,255))
gradient.setColorAt(0.8, QColor(background).lighter(133) if self.isHover else background)
if not self.scene().editMode():
if self.isMayaControlHidden:
background = "#666666"
pen.setColor("#333333")
gradient = None
if self.isMayaControlInvalid:
brushStyle = Qt.BDiagPattern
background = "#cc4444"
pen = Qt.NoPen
gradient = None
painter.setPen(pen)
if gradient:
painter.setBrush(gradient)
else:
brush = QBrush(QColor(background))
brush.setStyle(brushStyle)
painter.setBrush(brush)
else:
painter.setPen(Qt.NoPen)
painter.setBrush(Qt.NoBrush)
painter.drawPath(self.shape())
# label
if self.pickerItem.label:
painter.setPen(QColor(self.pickerItem.foreground))
if self.pickerItem.font:
font = QFont()
font.fromString(self.pickerItem.font)
painter.setFont(font)
else:
font = painter.font()
font.setBold(True)
painter.setFont(font)
fontMetrics = QFontMetrics(painter.font())
textSize = fontMetrics.boundingRect(self.pickerItem.label)
painter.drawText(boundingRect.center() - QPoint(textSize.width()/2, -textSize.height()/4), self.pickerItem.label)
if self.isSelected():
painter.setBrush(Qt.NoBrush)
pen = QPen(QColor(0,255,0, 150))
pen.setCosmetic(True)
painter.setPen(pen)
painter.drawRect(boundingRect)
def hoverMoveEvent(self, event):
self.isHover = True
if not self.pickerItem.image:
self.setCursor(Qt.PointingHandCursor)
self.update()
def hoverLeaveEvent(self, event):
self.isHover = False
self.unsetCursor()
self.update()
def mouseDoubleClickEvent(self, event): # select group of controls
super(SceneItem, self).mouseDoubleClickEvent(event)
scene = self.scene()
if not scene.editMode() and self.pickerItem.group:
found = scene.findItemsByProperty("group", self.pickerItem.group)
oldSelection = scene.sortedSelection()
scene.blockSignals(True)
for item in found:
item.setSelected(True)
scene.blockSignals(False)
scene.selectionChangedCallback()
def mousePressEvent(self, event):
alt = event.modifiers() & Qt.AltModifier
shift = event.modifiers() & Qt.ShiftModifier # add to selection
ctrl = event.modifiers() & Qt.ControlModifier # remove from selection
if alt:
return
scene = self.scene()
if event.button() == Qt.LeftButton and not scene.editMode() and self.pickerItem.script: # execute script
pm.undoInfo(ock=True)
try:
exec(self.pickerItem.script.replace("@", scene.mayaParameters.namespace))
finally:
pm.undoInfo(cck=True)
elif event.button() in [Qt.LeftButton, Qt.MiddleButton]: # handle selection
# when we press on a selected item with middle mouse, don't clear selection
if not (event.button() == Qt.MiddleButton and self.isSelected()):
# Deselect all other items in the same scene
if not shift and not ctrl:
scene.blockSignals(True)
for item in scene.selectedItems():
if item != self:
item.setSelected(False)
scene.blockSignals(False)
if ctrl:
self.setSelected(False)
elif ctrl and shift:
self.setSelected(True)
elif shift:
self.setSelected(not self.isSelected())
else:
self.setSelected(True)
if event.button() == Qt.MiddleButton and not ctrl and not shift:
for item in scene.selectedItems():
item._isDragging = True
item._lastPos = event.scenePos()
item._startPos = item.pos()
def mouseMoveEvent(self, event):
if self._isDragging:
scene = self.scene()
for item in scene.items():
if isinstance(item, SceneItem) and item._isDragging:
delta = item._lastPos - event.scenePos()
newPos = item._startPos - delta
item.setPos(newPos)
def mouseReleaseEvent(self, event):
if event.button() == Qt.MiddleButton:
scene = self.scene()
for item in scene.items():
if isinstance(item, SceneItem) and item.isSelected():
item._isDragging = False
if scene.mayaParameters.pickerIsModified:
scene.mayaParameters.pickerWindow.saveToMayaNode()
class Scene(QGraphicsScene):
editModeChanged = Signal(bool)
def __init__(self, propertiesWidget, mayaParameters, **kwargs):
super(Scene, self).__init__(**kwargs)
self.propertiesWidget = propertiesWidget
self.propertiesWidget.somethingChanged.connect(self.updateItemsProperties)
self.mayaParameters = mayaParameters
self.isImagesLocked = False
self._editMode = False
self._sortedSelection = []
self.undoEnabled = True
self._undoDisableOder = 0 # beginEditBlock/endEditBlock inc/dec this
self._undoStack = [] # [(id, function), (id, function)], where id identifies undo operation, function is a recover function
self._undoTempStack = []
self.selectionChanged.connect(self.selectionChangedCallback)
def updateProperties(self):
selection = self.sortedSelection()
self.propertiesWidget.updateProperties(selection[-1].pickerItem if selection else None)
def updateItemsProperties(self):
if not self.editMode():
return
self.undoAppendForSelected("properties")
propItem = self.propertiesWidget.pickerItem.duplicate()
changedProperties = self.propertiesWidget.changedProperties
for item in self.sortedSelection():
if "svgpath" in changedProperties:
item.pickerItem.svgpath = propItem.svgpath
elif "image" in changedProperties:
item.pickerItem.image = propItem.image
elif "background" in changedProperties:
item.pickerItem.background = propItem.background
elif "foreground" in changedProperties:
item.pickerItem.foreground = propItem.foreground
elif "imageAspectRatio" in changedProperties:
item.pickerItem.imageAspectRatio = propItem.imageAspectRatio
elif "control" in changedProperties:
item.pickerItem.control = propItem.control
elif "label" in changedProperties:
item.pickerItem.label = propItem.label
elif "font" in changedProperties:
item.pickerItem.font = propItem.font[:]
elif "group" in changedProperties:
item.pickerItem.group = propItem.group
elif "flat" in changedProperties:
item.pickerItem.flat = propItem.flat
elif "flipped" in changedProperties:
item.pickerItem.flipped = propItem.flipped[:]
elif "rotated" in changedProperties:
item.pickerItem.rotated = propItem.rotated
elif "script" in changedProperties:
item.pickerItem.script = propItem.script
self.propertiesWidget.changedProperties = []
item.updateShape()
def findItemsByProperty(self, propname, propvalue):
found = []
for item in self.items():
if isinstance(item, SceneItem) and item.pickerItem.__getattribute__(propname) == propvalue:
found.append(item)
return found
def updateSortedSelection(self):
# add prev selection into undo stack
undoFunc = lambda items=self.sortedSelection(): (self.clearSelection(), [item.setSelected(True) for item in items])
self.undoAppend("selection", undoFunc, str([id(item) for item in self.sortedSelection()]))
# sort selected items by distance to origin
selectedItems = sorted(self.selectedItems(), key=lambda item: QVector2D(self.sceneRect().topLeft()-item.pos()).length())
if selectedItems:
self._sortedSelection = [item for item in self._sortedSelection if item.isSelected()]
for sel in selectedItems:
if sel not in self._sortedSelection:
self._sortedSelection.append(sel)