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
|
from common import *
from math import floor, ceil
import weakref
import math
class KPEditorItem(QtGui.QGraphicsItem):
def __init__(self):
QtGui.QGraphicsItem.__init__(self)
self.setFlags(
self.ItemSendsGeometryChanges |
self.ItemIsSelectable |
self.ItemIsMovable
)
self.ignoreMovement = False
self.overrideSnap = False
def itemChange(self, change, value):
if change == self.ItemPositionChange and not self.ignoreMovement:
currentX, currentY = self.x(), self.y()
newpos = value.toPyObject()
x, y = newpos.x(), newpos.y()
if self.overrideSnap:
snapX, snapY = 1, 1
else:
# snap the item
snapX, snapY = self.SNAP_TO
x = int((x + (snapX/2)) / snapX) * snapX
y = int((y + (snapY/2)) / snapY) * snapY
if x < 0: x = 0
if x >= (12288+snapX): x = (12288+snapX-1)
if y < 0: y = 0
if y >= (12288+snapY): y = (12288+snapY-1)
if x != currentX or y != currentY:
self._itemMoved(currentX, currentY, x, y)
newpos.setX(x)
newpos.setY(y)
return newpos
return QtGui.QGraphicsItem.itemChange(self, change, value)
def boundingRect(self):
return self._boundingRect
RESIZER_TOP_LEFT = 1
RESIZER_TOP_RIGHT = 2
RESIZER_BOTTOM_LEFT = 3
RESIZER_BOTTOM_RIGHT = 4
RESIZER_TOP = 5
RESIZER_BOTTOM = 6
RESIZER_LEFT = 7
RESIZER_RIGHT = 8
def resizerPortionAt(self, x, y, originX=0, originY=0):
try:
leftBound, topBound = originX+5, originY+5
rightBound, bottomBound = self._resizerEndXY
except AttributeError:
rect = self._boundingRect
leftBound, topBound = rect.x() + 5, rect.y() + 5
rightBound, bottomBound = rect.right() - 5, rect.bottom() - 5
print "Testing %f,%f against (%f,%f) - (%f,%f)" % (x, y, leftBound, topBound, rightBound, bottomBound)
if y < topBound:
if x < leftBound: return 1 # TOP_LEFT
elif x >= rightBound: return 2 # TOP_RIGHT
else: return 5 # TOP
elif y >= bottomBound:
if x < leftBound: return 3 # BOTTOM_LEFT
elif x >= rightBound: return 4 # BOTTOM_RIGHT
else: return 6 # BOTTOM
else:
if x < leftBound: return 7 # LEFT
elif x >= rightBound: return 8 # RIGHT
else: return None
def _itemMoved(self, oldX, oldY, newX, newY):
pass
class KPEditorObject(KPEditorItem):
SNAP_TO = (24,24)
def __init__(self, obj, layer):
KPEditorItem.__init__(self)
obj.qtItem = self
self._objRef = weakref.ref(obj)
self._layerRef = weakref.ref(layer)
self._updatePosition()
self._updateSize()
self.setAcceptHoverEvents(True)
self.resizing = None
# I don't bother setting the ZValue because it doesn't quite matter:
# only one layer's objects are ever clickable, and drawBackground takes
# care of the layered drawing
def _updatePosition(self):
self.ignoreMovement = True
x,y = self._objRef().position
self.setPos(x*24, y*24)
self.ignoreMovement = False
def _updateSize(self):
self.prepareGeometryChange()
obj = self._objRef()
w,h = obj.size
self._boundingRect = QtCore.QRectF(0, 0, w*24, h*24)
self._selectionRect = QtCore.QRectF(0, 0, w*24-1, h*24-1)
self._resizerEndXY = (w*24-5, h*24-5)
def paint(self, painter, option, widget):
if self.isSelected():
painter.setPen(QtGui.QPen(Qt.white, 1, Qt.DotLine))
painter.drawRect(self._selectionRect)
def hoverMoveEvent(self, event):
if self._layerRef() != KP.mapScene.currentLayer:
self.setCursor(Qt.ArrowCursor)
return
pos = event.pos()
bit = self.resizerPortionAt(pos.x(), pos.y())
if bit == 1 or bit == 4:
self.setCursor(Qt.SizeFDiagCursor)
elif bit == 2 or bit == 3:
self.setCursor(Qt.SizeBDiagCursor)
elif bit == 7 or bit == 8:
self.setCursor(Qt.SizeHorCursor)
elif bit == 5 or bit == 6:
self.setCursor(Qt.SizeVerCursor)
else:
self.setCursor(Qt.ArrowCursor)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
pos = event.pos()
bit = self.resizerPortionAt(pos.x(), pos.y())
if self._layerRef() == KP.mapScene.currentLayer and bit:
event.accept()
x, xSide, y, ySide = False, None, False, None
if bit == 1 or bit == 7 or bit == 3:
x, xSide = True, 1
elif bit == 2 or bit == 4 or bit == 8:
x, xSide = True, 0
if bit == 1 or bit == 2 or bit == 5:
y, ySide = True, 1
elif bit == 3 or bit == 4 or bit == 6:
y, ySide = True, 0
self.resizing = (x, xSide, y, ySide)
return
KPEditorItem.mousePressEvent(self, event)
def _tryAndResize(self, obj, axisIndex, mousePosition, stationarySide):
objPosition = obj.position[axisIndex]
objSize = obj.size[axisIndex]
mousePosition = int(mousePosition / 12) * 12
if stationarySide == 0:
# Resize the right/bottom side
relativeMousePosition = mousePosition - objPosition
newSize = relativeMousePosition + 1
if newSize == objSize or newSize < 1:
return False
if axisIndex == 1:
obj.size = (obj.size[0], newSize)
else:
obj.size = (newSize, obj.size[1])
else:
# Resize the left/top side
rightSide = objPosition + objSize - 1
newLeftSide = mousePosition
newPosition = newLeftSide
newSize = rightSide - newLeftSide + 1
if newSize < 1:
return False
if newPosition == objPosition and newSize == objSize:
return False
if axisIndex == 1:
obj.position = (obj.position[0], newPosition)
obj.size = (obj.size[0], newSize)
else:
obj.position = (newPosition, obj.position[1])
obj.size = (newSize, obj.size[1])
return True
def mouseMoveEvent(self, event):
if self.resizing:
obj = self._objRef()
scenePos = event.scenePos()
hasChanged = False
resizeX, xSide, resizeY, ySide = self.resizing
if resizeX:
hasChanged |= self._tryAndResize(obj, 0, int(scenePos.x() / 24), xSide)
if resizeY:
hasChanged |= self._tryAndResize(obj, 1, int(scenePos.y() / 24), ySide)
if hasChanged:
obj.updateCache()
self._layerRef().updateCache()
self._updatePosition()
self._updateSize()
else:
KPEditorItem.mouseMoveEvent(self, event)
def mouseReleaseEvent(self, event):
if self.resizing and event.button() == Qt.LeftButton:
self.resizing = None
else:
KPEditorItem.mouseReleaseEvent(self, event)
def _itemMoved(self, oldX, oldY, newX, newY):
obj = self._objRef()
obj.position = (newX/24, newY/24)
self._layerRef().updateCache()
def remove(self):
obj = self._objRef()
layer = self._layerRef()
layer.objects.remove(obj)
layer.updateCache()
class KPEditorDoodad(KPEditorItem):
SNAP_TO = (12,12)
def __init__(self, doodad, layer):
KPEditorItem.__init__(self)
self.setFlags(
self.ItemSendsGeometryChanges |
self.ItemIsSelectable |
self.ItemIsMovable
)
doodad.qtItem = self
self._doodadRef = weakref.ref(doodad)
self._layerRef = weakref.ref(layer)
# TODO: refactor this to store source doodad data under KP.map
sourceItem = KP.mainWindow.doodadSelector.getDoodad(doodad.index)
self._sourceRef = weakref.ref(sourceItem)
self.resizing = None
self.rotating = None
self._updatePixmap()
self._updatePosition()
self._updateSize()
self._updateTransform()
global BULLSHIT
BULLSHIT = self.bullshit
self.setAcceptHoverEvents(True)
def _updatePixmap(self):
source = self._sourceRef()
pixmap = source.icon().pixmap(source.icon().availableSizes()[0])
self.prepareGeometryChange()
w, h = pixmap.width(), pixmap.height()
self.pixmap = pixmap
def _updatePosition(self):
# NOTE: EditorDoodads originate at the centre, not the top left like the others
self.ignoreMovement = True
doodad = self._doodadRef()
x,y = doodad.position
w,h = doodad.size
self.setPos(x+floor(w/2.0), y+floor(h/2.0))
self.ignoreMovement = False
def _updateSize(self):
self.prepareGeometryChange()
w,h = self._doodadRef().size
#self.setTransformOriginPoint(w/2, h/2)
self._boundingRect = QtCore.QRectF(-w/2, -h/2, w, h)
self._selectionRect = self._boundingRect.adjusted(0, 0, -1, -1)
def _updateTransform(self):
doodad = self._doodadRef()
transform = QtGui.QTransform()
transform.rotate(doodad.angle)
self.setTransform(transform)
itransform = QtGui.QTransform()
itransform.rotate(-doodad.angle)
self.invertedTransform = itransform
print "----"
self._pt(transform)
print "~~"
self._pt(itransform)
#self.invertedTransform, invertible = transform.inverted()
#self.setRotation(doodad.angle)
#self.invertedTransform, invertible = self.transform().inverted()
def _pt(self, t):
print t.m11(), t.m12(), t.m13()
print t.m21(), t.m22(), t.m23()
print t.m31(), t.m32(), t.m33()
def paint(self, painter, option, widget):
if self.isSelected():
painter.setPen(QtGui.QPen(Qt.white, 1, Qt.DotLine))
painter.drawRect(self._selectionRect)
def _itemMoved(self, oldX, oldY, newX, newY):
doodad = self._doodadRef()
w,h = doodad.size
print "Moved to", newX, newY, "size", w, h
doodad.position = (newX-floor(w/2.0), newY-floor(h/2.0))
def hoverMoveEvent(self, event):
if self._layerRef() != KP.mapScene.currentLayer:
self.setCursor(Qt.ArrowCursor)
return
pos = event.pos()
bit = self.resizerPortionAt(pos.x(), pos.y())
if (event.modifiers() == Qt.ShiftModifier):
if bit:
self.setCursor(Qt.OpenHandCursor)
else:
self.setCursor(Qt.ArrowCursor)
else:
if bit == 1 or bit == 4:
self.setCursor(Qt.SizeFDiagCursor)
elif bit == 2 or bit == 3:
self.setCursor(Qt.SizeBDiagCursor)
elif bit == 7 or bit == 8:
self.setCursor(Qt.SizeHorCursor)
elif bit == 5 or bit == 6:
self.setCursor(Qt.SizeVerCursor)
else:
self.setCursor(Qt.ArrowCursor)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
pos = event.pos()
bit = self.resizerPortionAt(pos.x(), pos.y())
if self._layerRef() == KP.mapScene.currentLayer and bit:
event.accept()
if (event.modifiers() & Qt.ShiftModifier):
self.rotating = self.mapToScene(pos), self._doodadRef().angle
self.setCursor(Qt.ClosedHandCursor)
return
else:
x, xSide, y, ySide = False, None, False, None
if bit == 1 or bit == 7 or bit == 3:
x, xSide = True, 1
elif bit == 2 or bit == 4 or bit == 8:
x, xSide = True, 0
if bit == 1 or bit == 2 or bit == 5:
y, ySide = True, 1
elif bit == 3 or bit == 4 or bit == 6:
y, ySide = True, 0
self.resizing = (x, xSide, y, ySide)
print self.resizing
return
KPEditorItem.mousePressEvent(self, event)
def _tryAndResize(self, obj, axisIndex, mousePosition, stationarySide):
objPosition = obj.position[axisIndex]
objSize = obj.size[axisIndex]
currentCentre = objPosition + (objSize / 2)
lowerSide = objPosition
upperSide = lowerSide + objSize
if stationarySide == 0:
upperSide = mousePosition
else:
lowerSide = mousePosition
newSize = upperSide - lowerSide
newPosition = lowerSide
#newPosition = currentCentre - (newSize / 2)
if newPosition == objPosition and newSize == objSize:
return False
elif newSize < 1:
return False
if axisIndex == 1:
obj.position = (obj.position[0], newPosition)
obj.size = (obj.size[0], newSize)
else:
obj.position = (newPosition, obj.position[1])
obj.size = (newSize, obj.size[1])
return True
def _tryAndRotate(self, obj, mouseX, mouseY, originalPos, oldAngle, modifiers):
center = self.mapToScene(self.boundingRect().center())
objX = center.x()
objY = center.y()
origX = originalPos.x()
origY = originalPos.y()
dy = origY - objY
dx = origX - objX
rads = math.atan2(dy, dx)
origAngle = math.degrees(rads)
dy = mouseY - objY
dx = mouseX - objX
rads = math.atan2(dy, dx)
angle = math.degrees(rads)
# Move this to ItemChange() or something at some point.
finalAngle = angle - origAngle + oldAngle
if (modifiers & Qt.ControlModifier):
finalAngle = int(finalAngle / 45.0) * 45.0
return True, finalAngle
def mouseMoveEvent(self, event):
if self.resizing:
obj = self._doodadRef()
scenePos = event.scenePos()
#mappedPos = self.transform().map(scenePos)
#mappedPos = self.invertedTransform.map(scenePos)
x = event.pos().x() + self.x()
y = event.pos().y() + self.y()
mappedPos = QtCore.QPointF(x, y)
hasChanged = False
resizeX, xSide, resizeY, ySide = self.resizing
print "Scene Position: %f,%f" % (scenePos.x(), scenePos.y())
print "Mapped Position: %f,%f" % (mappedPos.x(), mappedPos.y())
print "Current X/Y: %r; Size: %r" % (obj.position, obj.size)
if resizeX:
hasChanged |= self._tryAndResize(obj, 0, mappedPos.x(), xSide)
if resizeY:
hasChanged |= self._tryAndResize(obj, 1, mappedPos.y(), ySide)
print "New X/Y: %r; Size: %r" % (obj.position, obj.size)
if hasChanged:
# TODO: move overrides into updatePosition?
# TODO: snapping for resizing
self.overrideSnap = True
self._updatePosition()
self._updateSize()
self._updateTransform()
self.overrideSnap = False
print "New Rect: (%f,%f) %f x %f" % (self._boundingRect.x(), self._boundingRect.y(), self._boundingRect.width(), self._boundingRect.height())
elif self.rotating:
obj = self._doodadRef()
scenePos = event.scenePos()
hasChanged = False
hasChanged, angle = self._tryAndRotate(obj, scenePos.x(), scenePos.y(), self.rotating[0], self.rotating[1], event.modifiers())
if hasChanged:
obj.angle = angle
self._updateTransform()
else:
KPEditorItem.mouseMoveEvent(self, event)
def bullshit(self):
obj = self._doodadRef()
print "Current X/Y: %r; Size: %r" % (obj.position, obj.size)
def mouseReleaseEvent(self, event):
if self.resizing and event.button() == Qt.LeftButton:
self.resizing = None
elif self.rotating and event.button() == Qt.LeftButton:
self.rotating = None
else:
KPEditorItem.mouseReleaseEvent(self, event)
def remove(self):
doodad = self._doodadRef()
layer = self._layerRef()
layer.objects.remove(doodad)
del doodad
class KPEditorNode(QtGui.QGraphicsPixmapItem):
def __init__(self, node, layer):
QtGui.QGraphicsPixmapItem.__init__(self)
self.setFlags(
self.ItemSendsGeometryChanges |
self.ItemIsSelectable |
self.ItemIsMovable
)
class KPEditorPathSegment(QtGui.QGraphicsPathItem):
def __init__(self, node, layer):
QtGui.QGraphicsPathItem.__init__(self)
self.setFlags(
self.ItemSendsGeometryChanges |
self.ItemIsSelectable |
self.ItemIsMovable
)
self.path = QtGui.QPainterPath()
self.brush = None
self.pen = None
self.rotation = 0
def makeStraight(self, start, end):
self.path.moveTo(start)
self.path.addPolygon(QtGui.QPolygon([QtCore.QPointF(start.x(), start.y()-5.0),
QtCore.QPointF(end.x(), end.y()-5.0),
QtCore.QPointF(end.x(), end.y()+5.0),
QtCore.QPointF(start.x(), start.y()+5.0),
QtCore.QPointF(start.x(), start.y()-5.0)]))
center = QtCore.QPointF((end.x()/2)-(start.x()/2), (end.y()/2)-((start.y()/2) + 16))
graduate = QtGui.QRadialGradiant(center, float((end.x()/2)-(start.x()/2)))
graduate.setColorA(QtGui.QColor(200, 210, 240))
graduate.setColorB(QtGui.QColor(150, 160, 190))
self.brush = QtGui.QBrush(graduate)
self.pen = QtGui.QPen(QColor(120, 130, 160))
self.pen.setWidth(4)
self.pen.setCapStyle(Qt.RoundCap)
self.pen.setJoinStyle(Qt.RoundJoin)
def makeArc(self, start, end):
self.path.moveTo(start)
self.path.addEllipse(start.x(), start.y(), end.x()-start.x(), end.y()-start.y())
r = QtGui.QPainterPath()
r.addEllipse(start.x(), start.y()-4, end.x()-start.x(), end.y()-start.y()-16)
self.path.subtracted(r)
center = QtCore.QPointF((end.x()/2)-(start.x()/2), (end.y()/2)-((start.y()/2) + 16))
graduate = QtGui.QRadialGradiant(center, float((end.x()/2)-(start.x()/2)))
graduate.setColorA(QtGui.QColor(200, 210, 240))
graduate.setColorB(QtGui.QColor(150, 160, 190))
self.brush = QtGui.QBrush(graduate)
self.pen = QtGui.QPen(QColor(120, 130, 160))
self.pen.setWidth(4)
self.pen.setCapStyle(Qt.RoundCap)
self.pen.setJoinStyle(Qt.RoundJoin)
sX = start.x()
sY = start.y()
eX = end.x()
eY = end.y()
dy = eY - sY
dx = eX - sX
rads = math.atan2(dy, dx)
self.rotate = math.degrees(rads)
class KPMapScene(QtGui.QGraphicsScene):
def __init__(self):
QtGui.QGraphicsScene.__init__(self, 0, 0, 512*24, 512*24)
# todo: handle selectionChanged
# todo: look up why I used setItemIndexMethod(self.NoIndex) in Reggie
self.currentLayer = None
KP.mapScene = self
def drawBackground(self, painter, rect):
painter.fillRect(rect, QtGui.QColor(209, 218, 236))
areaLeft, areaTop = rect.x(), rect.y()
areaWidth, areaHeight = rect.width(), rect.height()
areaRight, areaBottom = areaLeft+areaWidth, areaTop+areaHeight
areaLeftT = floor(areaLeft / 24)
areaTopT = floor(areaTop / 24)
areaRightT = ceil(areaRight / 24)
areaBottomT = ceil(areaBottom / 24)
# compile a list of doodads
visibleDoodadsByLayer = {}
for obj in self.items(rect):
if not isinstance(obj, KPEditorDoodad): continue
layer = obj._layerRef()
try:
doodadList = visibleDoodadsByLayer[layer]
except KeyError:
doodadList = []
visibleDoodadsByLayer[layer] = doodadList
doodadList.append(obj)
# now draw everything!
for layer in reversed(KP.map.layers):
if not layer.visible: continue
if isinstance(layer, KPDoodadLayer):
try:
toDraw = visibleDoodadsByLayer[layer]
except KeyError:
continue
painter.setPen(Qt.red)
for item in reversed(toDraw):
painter.save()
painter.setWorldTransform(item.sceneTransform(), True)
w, h = item._doodadRef().size
painter.drawPixmap(-w/2, -h/2, w, h, item.pixmap)
painter.restore()
x, y = item._doodadRef().position
#painter.drawPoint(x, y)
painter.drawRect(x, y, w, h)
elif isinstance(layer, KPTileLayer):
left, top = layer.cacheBasePos
width, height = layer.cacheSize
right, bottom = left+width, top+height
if width == 0 and height == 0: continue
if right < areaLeftT: continue
if left > areaRightT: continue
if bottom < areaTopT: continue
if top > areaBottomT: continue
# decide how much of the layer we'll actually draw
drawLeft = int(max(areaLeftT, left))
drawRight = int(min(areaRightT, right))
drawTop = int(max(areaTopT, top))
drawBottom = int(min(areaBottomT, bottom))
srcY = drawTop - top
destY = drawTop * 24
baseSrcX = drawLeft - left
baseDestX = drawLeft * 24
rows = layer.cache
tileset = KP.map.loadedTilesets[layer.tileset]
tileList = tileset.tiles
for y in xrange(drawTop, drawBottom):
srcX = baseSrcX
destX = baseDestX
row = rows[srcY]
for x in xrange(drawLeft, drawRight):
tile = row[srcX]
if tile != -1:
painter.drawPixmap(destX, destY, tileList[tile])
srcX += 1
destX += 24
srcY += 1
destY += 24
def setCurrentLayer(self, layer):
if self.currentLayer is not None:
self.setLayerObjectsFlag(self.currentLayer, QtGui.QGraphicsItem.ItemIsSelectable, False)
self.setLayerObjectsFlag(self.currentLayer, QtGui.QGraphicsItem.ItemIsMovable, False)
self.currentLayer = layer
self.setLayerObjectsFlag(layer, QtGui.QGraphicsItem.ItemIsSelectable, True)
self.setLayerObjectsFlag(layer, QtGui.QGraphicsItem.ItemIsMovable, True)
def setLayerObjectsFlag(self, layer, flag, value):
for obj in layer.objects:
item = obj.qtItem
if item:
item.setFlag(flag, value)
class KPEditorWidget(QtGui.QGraphicsView):
def __init__(self, scene, parent=None):
QtGui.QGraphicsView.__init__(self, scene, parent)
self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
self.setDragMode(self.RubberBandDrag)
self.xScrollBar = QtGui.QScrollBar(Qt.Horizontal, parent)
self.setHorizontalScrollBar(self.xScrollBar)
self.yScrollBar = QtGui.QScrollBar(Qt.Vertical, parent)
self.setVerticalScrollBar(self.yScrollBar)
self.centerOn(0,0)
# set up stuff for painting
self.paintNext = None
self.paintNextID = None
self._resetPaintVars()
def _resetPaintVars(self):
self.painting = None
self.paintingItem = None
self.paintBeginPosition = None
def _tryToPaint(self, event):
'''Called when a paint attempt is initiated'''
if self.paintNext is None: return
paint = self.paintNext
if isinstance(paint, KPTileObject):
clicked = self.mapToScene(event.x(), event.y())
x, y = clicked.x(), clicked.y()
if x < 0: x = 0
if y < 0: y = 0
x = int(x / 24)
y = int(y / 24)
layer = self.scene().currentLayer
if not layer.visible: return
if not isinstance(layer, KPTileLayer): return
obj = KPObject()
obj.position = (x,y)
obj.size = (1,1)
obj.tileset = layer.tileset
obj.kind = paint
obj.updateCache()
layer.objects.append(obj)
layer.updateCache()
item = KPEditorObject(obj, layer)
self.scene().addItem(item)
self.painting = obj
self.paintingItem = item
self.paintBeginPosition = (x, y)
if isinstance(paint, QtGui.QListWidgetItem):
clicked = self.mapToScene(event.x(), event.y())
x, y = clicked.x(), clicked.y()
if x < 0: x = 0
if y < 0: y = 0
layer = self.scene().currentLayer
if not layer.visible: return
if not isinstance(layer, KPDoodadLayer): return
obj = KPDoodad()
obj.position = (x,y)
obj.index = self.paintNextID
obj.setDefaultSize()
layer.objects.append(obj)
item = KPEditorDoodad(obj, layer)
self.scene().addItem(item)
self.painting = obj
self.paintingItem = item
self.paintBeginPosition = (x, y)
def _movedWhilePainting(self, event):
'''Called when the mouse is moved while painting something'''
obj = self.painting
item = self.paintingItem
if isinstance(obj, KPObject):
clicked = self.mapToScene(event.x(), event.y())
x, y = clicked.x(), clicked.y()
if x < 0: x = 0
if y < 0: y = 0
x = int(x / 24)
y = int(y / 24)
beginX, beginY = self.paintBeginPosition
if x >= beginX:
objX = beginX
width = x - beginX + 1
else:
objX = x
width = beginX - x + 1
if y >= beginY:
objY = beginY
height = y - beginY + 1
else:
objY = y
height = beginY - y + 1
currentX, currentY = obj.position
currentWidth, currentHeight = obj.size
# update everything if changed
changed = False
if currentX != objX or currentY != objY:
obj.position = (objX, objY)
item._updatePosition()
changed = True
if currentWidth != width or currentHeight != height:
obj.size = (width, height)
obj.updateCache()
item._updateSize()
changed = True
if not changed: return
item._layerRef().updateCache()
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
self._tryToPaint(event)
event.accept()
else:
QtGui.QGraphicsView.mousePressEvent(self, event)
def mouseMoveEvent(self, event):
if event.buttons() == Qt.RightButton and self.painting:
self._movedWhilePainting(event)
event.accept()
else:
QtGui.QGraphicsView.mouseMoveEvent(self, event)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Delete or event.key() == QtCore.Qt.Key_Backspace:
scene = self.scene()
selection = scene.selectedItems()
if len(selection) > 0:
for obj in selection:
obj.remove()
obj.setSelected(False)
scene.removeItem(obj)
scene.update()
self.update()
return
else:
QtGui.QGraphicsView.keyPressEvent(self, event)
|