-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengineUI.py
More file actions
1480 lines (1181 loc) · 59.8 KB
/
engineUI.py
File metadata and controls
1480 lines (1181 loc) · 59.8 KB
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
from UI import (
button,
input,
toggleButton,
conductor,
selector,
console,
progressBar,
message
)
from exporter import build
import engineOUAR as ouar
import UniPy as pe
import settings as st
import pather as pt
import os
import traceback
import shutil
import copy
import re
import sys
import collections
import pygame
import ast
pygame.mixer.init()
# settings
error = False
objComponents = []
compiledTextes_FOC = []
CTFOCXOF = []
CSTN = []
CSTN_POS = []
SISL = None
OPII = 0
# import engine assets
uiEngineImages = {}
imgs = os.listdir("assets")
for img in [file for file in imgs if file.split(".")[-1] not in ["otf", "ttf"]]:
uiEngineImages[img.split(".", 1)[0]] = pygame.image.load(f"assets{pt.s}{img}")#.convert()
uiEngineImages["down"] = pygame.transform.rotozoom(uiEngineImages["up"], 180, 1.0)
uiEngineImages["back"] = pygame.transform.rotozoom(uiEngineImages["up"], 90, 1.0)
uiEngineImages["plus"] = pygame.transform.rotozoom(uiEngineImages["cancel"], 45, 1.0)
uiEngineImages["ENGINE_ICON"] = pygame.transform.smoothscale(uiEngineImages["engineIcon"], (int(st.width / 7.5) if st.width < st.height else st.width // 15, int(st.width / 7.5) if st.width < st.height else st.width // 15))
pygame.display.set_icon(uiEngineImages["engineIcon"])
for i in uiEngineImages:
if i not in st.uiII:
uiEngineImages[i].fill(st.uiEIC, special_flags=pygame.BLEND_RGB_MULT)
# object image in inspector
OIII = None
OIIIW, OIIIH = 0, 0
# object font name in inspector
OFNII = None
OFNIIW, OFNIIH = 0, 0
# load projects
PATH = f'.{pt.s}projects'
st.projects = os.listdir(PATH)
# for export project menu
uiEPMST = ["Export path", "Version"]
uiEPMT = None
uiEPME = None
# to choose project
def toCP():
pygame.display.set_caption(f"UniPy {st.version}")
st.drawingLayer = -1
st.projectIdx = -1
pe.objects = []
pe.objName = []
pe.objClass = []
def loadProjectInfoData(path):
if not os.path.exists(f"{path}{pt.s}project_info.txt"):
with open(f"{path}{pt.s}project_info.txt", "w") as f:
f.write(f"{st.AppWidth} {st.AppHeight}, 0.1")
inf = open(f"{path}{pt.s}project_info.txt", "r").read().split(",")
size = inf[0].split(" ")
vr = inf[1].strip() if len(inf) > 1 else "0.1"
return (int(size[0]), int(size[1])), vr
def loadImage(path):
txs = pygame.image.load(path).convert_alpha()
imgT = txs.copy()
img = pygame.image.load(path).convert()
replacement_color = (1, 1, 1)
for x in range(txs.get_width()):
for y in range(txs.get_height()):
if list(txs.get_at((x, y)))[-1] == 0:
txs.set_at((x, y), replacement_color)
img = pygame.Surface(txs.get_size()).convert()
img.blit(txs, (0, 0))
img.set_colorkey(replacement_color)
return img, imgT
# open project
def openProject(idx):
st.projectIdx = idx
pygame.display.set_caption(f"UniPy {st.version} || {st.projects[st.projectIdx]}")
st.projects = os.listdir(PATH)
st.files, st.dirs = loadAllFilesFromDir(f"{PATH}{pt.s}{st.projects[st.projectIdx]}")
PB.start(PB.title, len(st.files))
# set project size
st.projectSize = loadProjectInfoData(f"{PATH}{pt.s}{st.projects[idx]}")[0]
pe.pWidth, pe.pHeight = st.projectSize
# load all files from project
for i in st.files:
PB.setItemName(i)
drawProjects()
PB.update()
for msg in message.messages:
msg.update()
pygame.display.flip()
if i.split(".")[-1] in pe._imgTypes:
pe.textures[i], pe.texturesTSP[i] = loadImage(f"{st.dirs[st.files.index(i)]}{pt.s}{i}")
elif i.split(".")[-1] in pe._audioTypes:
pe.audios[i] = pygame.mixer.Sound(f"{st.dirs[st.files.index(i)]}{pt.s}{i}")
PB.itemLoaded()
drawProjects()
PB.update()
for msg in message.messages:
msg.update()
pygame.display.flip()
# load game objects
ouar.loadObjs(pe, f"{PATH}{pt.s}{st.projects[idx]}{pt.s}ObjectInfo.txt")
st.drawingLayer = 0
PAC.startPath = f".{pt.s}projects{pt.s}{st.projects[idx]}"
PAC.setPath()
SOHM.oY = 0
SOHM.elements = pe.objName[:]
SOHM.normalize()
# functions
def createMessage(surface, text: str):
oY = None
if message.messages:
oY = message.messages[-1].y - message.messages[-1].image.get_height() - 10
message.Message(surface, message = text, font = st.uiFont, y = oY, **st.UI_Settings["Message"])
# create new project
def createProject():
c = 1
if not os.path.exists(f"{PATH}{pt.s}new project"):
os.makedirs(f"{PATH}{pt.s}new project")
shutil.copytree(f".{pt.s}Built-in_Scripts", f"{PATH}{pt.s}new project{pt.s}Built-in_Scripts")
else:
while 1:
if not os.path.exists(f"{PATH}{pt.s}new project ({c})"):
os.makedirs(f"{PATH}{pt.s}new project ({c})")
shutil.copytree(f".{pt.s}Built-in_Scripts", f"{PATH}{pt.s}new project ({c}){pt.s}Built-in_Scripts")
break
else: c += 1
st.projects = os.listdir(PATH)
PM.elements = st.projects
PM.normalize()
# create new folder in project assets conductor
def createDirectory():
c = 1
if not os.path.exists(f"{PAC.thisPath}{pt.s}new folder"):
os.makedirs(f"{PAC.thisPath}{pt.s}new folder")
else:
while 1:
if not os.path.exists(f"{PAC.thisPath}{pt.s}new folder ({c})"):
os.makedirs(f"{PAC.thisPath}{pt.s}new folder ({c})")
break
else: c += 1
PAC.reOpenPath()
# download new file to project assets conductor from default conductor
def AddFileToPAC(path):
try:
shutil.copy(path, PAC.thisPath)
except: ...
if path.split(".")[-1] in pe._imgTypes:
pe.textures[path.split(pt.s)[-1]], pe.texturesTSP[path.split(pt.s)[-1]] = loadImage(path)
elif path.split(".")[-1] in pe._audioTypes:
pe.audios[path.split(pt.s)[-1]] = pygame.mixer.Sound(path)
PAC.reOpenPath()
startPACR()
btCancelCR.func = closeCR
def loadAllFilesFromDir(directory):
_all = []
DIRS = []
for root, dirs, files in os.walk(directory):
for i in files:
DIRS.append(root)
_all.append(i)
return _all, DIRS
def loadModules(fpm = False):
global error
for script in st.modules:
try: sys.modules.pop(script.__name__)
except: pass
st.modules = []
st.files, st.dirs = loadAllFilesFromDir(f"{PATH}{pt.s}{st.projects[st.projectIdx]}")
for file in st.files:
if file[-3:] == ".py":
if fpm:
PB.setItemName(file)
drawProjects()
PB.update()
for msg in message.messages: msg.update()
pygame.display.flip()
try:
st.modules.append(__import__(f"{st.dirs[st.files.index(file)].replace(pt.s, '.')}.{file[:-3]}"[2:], fromlist=["*"]))
except Exception as e:
error = True
tb = e.__traceback__
filename, line_num, _, _ = traceback.extract_tb(tb)[-1]
_console.Log(f"UniPy Error: in script \"{filename.split(pt.s)[-1]}\": in line [{line_num}]\n{e}", "error")
if fpm:
PB.itemLoaded()
drawProjects()
PB.update()
for msg in message.messages: msg.update()
pygame.display.flip()
# copy project
def copyProject():
shutil.copytree(f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}", f"{PATH}{pt.s}{PM.elements[PM.elem_idx]} (1)")
st.projects = os.listdir(PATH)
PM.elements = st.projects
PM.normalize()
def OpenMenuToExportProject():
vr = loadProjectInfoData(f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}")[1]
InputSetExportProjectVersion.text = vr
InputSetExportProjectVersion.check_text()
AEPME()
st.drawingLayer = 4
def CloseMenuToExportProject():
st.drawingLayer = -1
def ExportProject():
size, vr = loadProjectInfoData(f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}")
build.createProject(st.exportProjectPath, f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}", PM.elements[PM.elem_idx], PM.elements[PM.elem_idx], size, vr)
createMessage(st.win, f'The project was successfully exported to path:\n"{st.exportProjectPath}"')
# delete project
def deleteFolderInPM():
shutil.rmtree(f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}")
st.projects = os.listdir(PATH)
PM.elem_idx = -1
PM.elements = st.projects
PM.normalize()
# delete file from project assets conductor
def deleteFileInPAC():
path = f"{PAC.thisPath}{pt.s}{PAC.elements[PAC.elem_idx]}"
if not os.path.isdir(path):
os.remove(path)
if path in pe.textures:
del pe.textures[path]
del pe.texturesTSP[path]
else:
shutil.rmtree(path)
PAC.reOpenPath()
# close object info
def closeObjectInfo():
st.lastSelectionObject = None
st.isSelector = False
if st.LPBFS != None:
st.LPBFS.func = startSelectorForObjectInspector
st.LPBFS.content = st.lastSelectorContent
# delete game object
def deleteObj():
global OPIE
idx = pe.objName.index(pe.objName[SOHM.elem_idx])
pe.objName.pop(idx)
pe.objClass.pop(idx)
pe.objects.pop(idx)
st.lastSelectionObject = None
ouar.saveObjs(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt")
SOHM.elements = pe.objName[:]
SOHM.elem_idx = -1
SOHM.normalize()
# back path in conductor
def backCR():
if st.drawingLayer == 2: fileConductor.Back()
else: PAC.Back()
# start conductor from project assets conductor
def startCRfromPAC():
st.drawingLayer = 2
btCancelCR.func = closeCRfromPAC
fileConductor.content = ""
fileConductor.func = AddFileToPAC
fileConductor.startPath = pt._defaultPath
fileConductor.setPath(fileConductor.thisPath)
def startCRfromMoveFile():
st.drawingLayer = 2
btDeleteCR.render = False
btDoneCR.render = True
btDoneCR.func = moveFileInPAC
btCancelCR.func = closeCRfromMoveFile
fileConductor.content = ""
fileConductor.func = None
fileConductor.startPath = PAC.startPath
fileConductor.setPath()
def setExportProjectPath():
st.exportProjectPath = fileConductor.thisPath
st.drawingLayer = 4
def startCRfromExportProject():
st.drawingLayer = 2
btDeleteCR.render = False
btDoneCR.render = True
btDoneCR.func = setExportProjectPath
btCancelCR.func = closeCRfromExportProject
fileConductor.content = ""
fileConductor.func = None
fileConductor.startPath = st.exportProjectPath
fileConductor.setPath()
def moveFileInPAC():
try: shutil.move(f"{PAC.thisPath}{pt.s}{PAC.elements[PAC.elem_idx]}", f"{fileConductor.thisPath}")
except: pass
PAC.setPath(fileConductor.thisPath)
startPACR()
btCancelCR.func = closeCR
fileConductor.startPath = pt._defaultPath
fileConductor.setPath()
def startCRfromImportProject():
st.drawingLayer = 2
btDeleteCR.render = False
btDoneCR.render = True
btDoneCR.func = importProjects
btCancelCR.func = closeCRfromImportProject
fileConductor.content = ""
fileConductor.func = None
fileConductor.startPath = pt._defaultPath
fileConductor.setPath()
def importProjects():
if fileConductor.elem_idx != -1:
if os.path.isdir(f"{fileConductor.thisPath}{pt.s}{fileConductor.elements[fileConductor.elem_idx]}"):
try: shutil.copytree(f"{fileConductor.thisPath}{pt.s}{fileConductor.elements[fileConductor.elem_idx]}", f"{PATH}{pt.s}{fileConductor.elements[fileConductor.elem_idx]}")
except Exception as e:
createMessage(st.win, f"Failed to import the project \"{fileConductor.elements[fileConductor.elem_idx]}\"")
else:
fls = os.listdir(fileConductor.thisPath)
for f in fls:
if os.path.isdir(f"{fileConductor.thisPath}{pt.s}{f}"):
try:
shutil.copytree(f"{fileConductor.thisPath}{pt.s}{f}", f"{PATH}{pt.s}{f}")
except Exception as e:
createMessage(st.win, f"Failed to import the project \"{f}\"")
st.drawingLayer = -1
st.projects = os.listdir(PATH)
PM.elements = st.projects
PM.normalize()
# close conductor from project assets conductor
def closeCRfromPAC():
st.drawingLayer = 3
btCancelCR.func = closeCR
def closeCRfromMoveFile():
st.drawingLayer = 3
btCancelCR.func = closeCR
fileConductor.startPath = pt._defaultPath
fileConductor.setPath()
def closeCRfromExportProject():
st.drawingLayer = 4
def closeCRfromImportProject():
st.drawingLayer = -1
btCancelCR.func = closeCR
# start conductor
def startCR():
st.drawingLayer = 2
btDeleteCR.render = True
btDoneCR.render = False
fileConductor.func = changeObjProperty
fileConductor.startPath = f".{pt.s}projects{pt.s}{st.projects[st.projectIdx]}"
fileConductor.setPath()
def startPACR():
st.drawingLayer = 3
PAC.reOpenPath()
btDeleteCR.render = False
btDoneCR.render = False
# close conductor
def closeCR():
st.drawingLayer = 0
# rename file in project assets conductor
def startRenameFilePAC():
st.isRenameFile = True
st.lastPressedInput = IFFIPAC
IFFIPAC.text = PAC.elements[PAC.elem_idx]
IFFIPAC.has_press((-1, -1))
IFFIPAC.check_text()
IFFIPAC.rect.y = PAC.get_idx_pos(PAC.elem_idx)
# rename project
def startRenameProject():
st.isRenameProject = True
st.lastPressedInput = IFRPIPM
IFRPIPM.text = PM.elements[PM.elem_idx]
IFRPIPM.has_press((-1, -1))
IFRPIPM.check_text()
IFRPIPM.rect.y = PM.get_idx_pos(PM.elem_idx)
# end rename project
def endRenameProject():
if IFRPIPM.text != "" and PM.elements[PM.elem_idx] != IFRPIPM.text:
os.rename(f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}", f"{PATH}{pt.s}{IFRPIPM.text}")
st.projects = os.listdir(PATH)
PM.elements = st.projects
PM.normalize()
st.isRenameProject = False
st.lastPressedInput = None
# end rename file in project assets conductor
def endRenameFilePAC():
if IFFIPAC.text != "" and PAC.elements[PAC.elem_idx] != IFFIPAC.text:
os.rename(f"{PAC.thisPath}{pt.s}{PAC.elements[PAC.elem_idx]}", f"{PAC.thisPath}{pt.s}{IFFIPAC.text}")
if PAC.elements[PAC.elem_idx] in pe.textures:
data = pe.textures[PAC.elements[PAC.elem_idx]]
data2 = pe.texturesTSP[PAC.elements[PAC.elem_idx]]
del pe.textures[PAC.elements[PAC.elem_idx]]
del pe.texturesTSP[PAC.elements[PAC.elem_idx]]
pe.textures[IFFIPAC.text] = data
pe.texturesTSP[IFFIPAC.text] = data2
elif PAC.elements[PAC.elem_idx] in pe.audios:
data = pe.audios[PAC.elements[PAC.elem_idx]]
del pe.audios[PAC.elements[PAC.elem_idx]]
pe.audios[IFFIPAC.text] = data
PAC.setPath(PAC.thisPath)
st.isRenameFile = False
st.lastPressedInput = None
def renameExportProjectVersion():
size = loadProjectInfoData(f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}")[0]
with open(f"{PATH}{pt.s}{PM.elements[PM.elem_idx]}{pt.s}project_info.txt", "w") as f:
f.write(f"{size[0]} {size[1]}, {InputSetExportProjectVersion.text.strip()}")
# includes a widget for selecting items in object inspector
def startSelectorForObjectInspector(elems, button, key):
ObjSW.key = key
button.func = closeSelectorForObjectInspector
st.lastSelectorContent = button.content
st.LPBFS = button
button.content = "(self)"
st.isSelector = True
ObjSW.elements = elems
ObjSW.elem_name = elems
ObjSW.normalize()
ObjSW.x = button.rect.x
ObjSW.y = button.rect.y - ObjSW.surface.get_height() - 10
ObjSW.elem_idx = eval(f"ObjSW.elements.index(pe.objects[pe.objName.index(st.lastSelectionObject)].{key})")
# turns off the widget for selecting items in object inspector
def closeSelectorForObjectInspector(button):
st.isSelector = False
button.func = startSelectorForObjectInspector
button.content = st.lastSelectorContent
# includes a object font name in object inspector
def ADP_OFNII(idx):
global OFNII, OFNIIW, OFNIIH
text = str(pe.objects[idx].fontPath).split(pt.s)[-1]
try: f = pygame.font.Font(pe.objects[idx].fontPath, 1)
except: text = "None"
OFNII = st.uiTSFont.render(text, 0, st.uiTColor)
OFNIIW, OFNIIH = OFNII.get_size()
if ObjLoadFont.rect.right + OFNII.get_width() + 50 > st.width:
while 1:
OFNII = st.uiTSFont.render(text, 0, st.uiTColor)
if ObjLoadFont.rect.right + OFNII.get_width() + 50 > st.width:
text = text[:-1]
else:
text = text[:-3] + "..."
OFNII = st.uiTSFont.render(text, 0, st.uiTColor)
OFNIIW, OFNIIH = OFNII.get_size()
break
def ADP_OIII(idx):
global OIII, OIIIW, OIIIH
try: img = pe.textures[pe.objects[idx].imagePath]
except: return 0
if ((img.get_height() - img.get_width()) / img.get_width()) * 100 > 24:
OIII = pygame.transform.scale(img, (int(st.win.get_width() * (st.uiISIOI / st.win.get_height())) if st.win.get_height() > st.win.get_width() else int(st.win.get_height() * (st.uiISIOI / st.win.get_width())), int(st.uiISIOI)))
elif ((img.get_width() - img.get_height()) / img.get_height()) * 100 > 24:
OIII = pygame.transform.scale(img, (int(st.win.get_height() * (st.uiISIOI / st.win.get_width())) if st.win.get_height() > st.win.get_width() else int(st.win.get_width() * (st.uiISIOI / st.win.get_height())) , int(st.uiISIOI)))
else:
OIII = pygame.transform.scale(img, (int(st.uiISIOI), int(st.uiISIOI)))
OIII = pygame.transform.flip(OIII, pe.objects[idx].flipX, pe.objects[idx].flipY)
OIII = pygame.transform.rotate(OIII, pe.objects[idx].angle)
OIIIW = OIII.get_width()
OIIIH = OIII.get_height()
# move up an object in the hierarchy
def objectUp():
idx = pe.objName.index(SOHM.elements[SOHM.elem_idx])
if idx > 0:
pe.objName[idx], pe.objName[idx-1] = pe.objName[idx-1], pe.objName[idx]
pe.objects[idx], pe.objects[idx-1] = pe.objects[idx-1], pe.objects[idx]
pe.objClass[idx], pe.objClass[idx-1] = pe.objClass[idx-1], pe.objClass[idx]
SOHM.elem_idx -= 1
SOHM.elements = pe.objName[:]
SOHM.normalize()
ouar.saveObjs(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt")
# move down an object in the hierarchy
def objectDown():
idx = pe.objName.index(SOHM.elements[SOHM.elem_idx])
if idx != len(SOHM.elements)-1:
pe.objName[idx], pe.objName[idx+1] = pe.objName[idx+1], pe.objName[idx]
pe.objects[idx], pe.objects[idx+1] = pe.objects[idx+1], pe.objects[idx]
pe.objClass[idx], pe.objClass[idx+1] = pe.objClass[idx+1], pe.objClass[idx]
SOHM.elem_idx += 1
SOHM.elements = pe.objName[:]
SOHM.normalize()
ouar.saveObjs(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt")
# copy object
def copyObject():
idx = pe.objName.index(pe.objName[SOHM.elem_idx])
pe.objects.append(copy.copy(pe.objects[idx]))
of = 1
while f"{pe.objName[idx]} ({of})" in pe.objName:
of += 1
pe.objName.append(f"{pe.objName[idx]} ({of})")
pe.objClass.append(pe.objClass[idx])
SOHM.elements = pe.objName[:]
SOHM.elem_idx = len(SOHM.elements)-1
SOHM.normalize()
ouar.saveObjs(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt")
# show console
def showConsole():
st.isConsole = True
btSCC.func = closeConsole
# close console
def closeConsole():
st.isConsole = False
btSCC.func = showConsole
def loadObjectScriptLinks(one = False):
global error
n = 0 if not one else len(pe.objects)-1
mn = [i.__name__.split(".")[-1] for i in st.modules]
for obj in pe.objects[n:]:
if obj.script != "None":
scripts = [i.strip().split(".")[-1] for i in obj.script.split(",")]
ss = [i for i in obj.S_CONTENT]
for s in ss:
if s not in mn:
del obj.S_CONTENT[s]
del obj.SC_CHANGED[s]
for ojj in scripts:
if ojj in mn:
try:
pe.OWS.append(eval(f"st.modules[mn.index(\"{ojj}\")].{ojj}()"))
pe.OWS[-1].this = obj
obj.S_LINKS.append(pe.OWS[-1])
except Exception as e:
_console.Log(f"UniPy Error: in object \"{pe.objName[pe.objects.index(obj)]}\": no class was created in script \"{ojj}\" or it matches the name of the script.", "error")
error = True
continue
else:
_console.Log(f"UniPy Error: in object \"{pe.objName[pe.objects.index(obj)]}\": script \"{ojj}\" is not defined", "error")
error = True
for idx, ojj in enumerate(scripts):
if ojj in mn and ojj in obj.S_CONTENT:
try: _v = [var for var in dir(obj.S_LINKS[idx]) if not callable(getattr(obj.S_LINKS[idx], var)) and not var.startswith("_")]
except: continue
if "this" in _v: _v.remove("this")
for jjj in _v:
if jjj in obj.S_CONTENT[ojj] and obj.SC_CHANGED[ojj][jjj]:
vv = obj.S_CONTENT[ojj][jjj][0]
vvt = obj.S_CONTENT[ojj][jjj][1]
exec(f"obj.S_LINKS[{idx}].{jjj} = vv")
def loadOBJScriptLinks(idx):
obj = pe.objects[idx]
scripts = [script.strip() for script in obj.script.split(",")] if obj.script != "None" else {}
result = {}
if scripts:
for script in scripts:
parsed_ast = None
result[script] = {}
try:
with open(f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}{script.replace('.', pt.s)}.py") as code:
parsed_ast = ast.parse(code.read())
except:
createMessage(st.win, f"Script \"{script}\" was not found")
del result[script]
continue
idx = next((i for i, bd in enumerate(parsed_ast.body) if isinstance(bd, ast.ClassDef)), None)
if idx is not None:
init_body = parsed_ast.body[idx].body[0].body
for statement in init_body:
if isinstance(statement, ast.Assign):
for target in statement.targets:
if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == 'self':
variable_name = target.attr
try: variable_value = ast.literal_eval(statement.value)
except: variable_value = None
if not variable_name.startswith("_") and variable_value != None:
result[script][variable_name] = variable_value
return result
else:
return {}
# start app
def startApp():
global error
pe.objects = []
pe.objClass = []
pe.objName = []
ouar.loadObjs(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt")
pe.OON = pe.objName.copy()
pe.OWS = []
pe.Camera.target = None
pe.Camera.x, pe.Camera.y = 0, 0
pe.GRAVITY = pe.STARTGRAVITY
MHFS = []
st.MHFU = []
st.GBGC = st.GBGSC
_console.textes = []
_console.textes_type = []
_console.tX, _console.tY = (0, 0)
error = False
loadModules()
loadObjectScriptLinks()
for i in st.modules:
if hasattr(i, "Start"): MHFS.append(i)
if hasattr(i, "Update"): st.MHFU.append(i)
for i in pe.OWS:
if hasattr(i, "Start"): MHFS.append(i)
if hasattr(i, "Update"): st.MHFU.append(i)
st.drawingLayer = 1
btStartApp.func = returnToEditor
btStartApp.original_image = uiEngineImages["cancel"]
btStartApp.height = st.height - st.AppHeight - 10
btStartApp.width = btStartApp.height * 2
btStartApp.y = -5
btStartApp.adjust_dimensions_and_positions()
for obj in pe.objects:
obj.setPos()
for obj in pe.objects:
obj.setPosObject()
for script in MHFS:
try:
script.Start()
except Exception as e:
error = True
tb = e.__traceback__
filename, line_num, _, _ = traceback.extract_tb(tb)[-1]
_console.Log(f"UniPy Error: in script \"{filename.split(pt.s)[-1]}\": in line [{line_num}]\n{e}", "error")
# close app
def returnToEditor():
pygame.mixer.stop()
pe.objects = []
pe.objClass = []
pe.objName = []
st.drawingLayer = 0
st.isConsole = False
btSCC.func = showConsole
btStartApp.func = startApp
btStartApp.original_image = uiEngineImages["play"]
btStartApp.height = st.uiBS
btStartApp.width = st.uiBS
btStartApp.y = -10
btStartApp.adjust_dimensions_and_positions()
ouar.loadObjs(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt")
# show objects that can be created
def SOTCBC():
SOHM.scrolling = False
st.isCreateObject = True
btShowPanel.original_image = uiEngineImages["cancel"]
btShowPanel.func = COTCBC
btShowPanel.adjust_dimensions_and_positions()
# close objects that can be created
def COTCBC():
SOHM.scrolling = True
st.isCreateObject = False
btShowPanel.original_image = uiEngineImages["plus"]
btShowPanel.func = SOTCBC
btShowPanel.adjust_dimensions_and_positions()
def createObject(Class):
st.isCreateObject = False
SOHM.scrolling = True
btShowPanel.original_image = uiEngineImages["plus"]
btShowPanel.func = SOTCBC
btShowPanel.adjust_dimensions_and_positions()
ouar.addObj(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt", Class)
SOHM.elements = pe.objName[:]
SOHM.elem_idx = -1
SOHM.normalize()
def isMathOperation(string: str) -> bool:
for s in string:
if s not in pe._mathSybs:
return False
else:
return True
# change object property
def changeObjProperty(key, content = None):
global OIII, OIIIW, OIIIH
if st.LPBFS != None:
st.LPBFS.func = startSelectorForObjectInspector
st.LPBFS.content = st.lastSelectorContent
idx = pe.objName.index(st.lastSelectionObject)
obj = None
for i in objComponents:
if i.key == key:
obj = i
break
if key == "name":
if ObjName.text.strip() not in pe.objName:
pe.objName[idx] = ObjName.text
SOHM.elements = pe.objName[:]
SOHM.normalize()
st.lastSelectionObject = ObjName.text
elif ObjName.text.strip() != pe.objName[idx]:
ObjName.text = pe.objName[idx]
createMessage(st.win, f"Oops, an object with that name already exists.")
elif key == "x":
if isMathOperation(ObjX.text):
try:
pe.objects[idx].sx = int(eval(ObjX.text))
except: ...
ObjX.text = str(pe.objects[idx].sx)
elif key == "y":
if isMathOperation(ObjY.text):
try:
pe.objects[idx].sy = int(eval(ObjY.text))
except: ...
ObjY.text = str(pe.objects[idx].sy)
elif key == "cx":
if ObjCX.text != "":
pe.objects[idx].cx = ObjCX.text
else: ObjCX.text = pe.objects[idx].cx
elif key == "cy":
if ObjCY.text != "":
pe.objects[idx].cy = ObjCY.text
else: ObjCY.text = pe.objects[idx].cy
elif key == "width":
if isMathOperation(ObjWidth.text):
try:
pe.objects[idx].SW = int(eval(ObjWidth.text))
except: ...
ObjWidth.text = str(pe.objects[idx].SW)
elif key == "height":
if isMathOperation(ObjHeight.text):
try:
pe.objects[idx].SH = int(eval(ObjHeight.text))
except: ...
ObjHeight.text = str(pe.objects[idx].SH)
elif key == "angle":
if isMathOperation(ObjAngle.text):
try:
pe.objects[idx].angle = int(eval(ObjAngle.text))
except: ...
ObjAngle.text = str(pe.objects[idx].angle)
setObjProperty(st.lastSelectionObject, False)
elif key == "render":
pe.objects[idx].render = ObjRender.active
elif key == "bodyType":
pe.objects[idx].bodyType = content
st.isSelector = False
elif key == "textCentering":
pe.objects[idx].textCentering = content
st.isSelector = False
elif key == "flipX":
pe.objects[idx].flipX = ObjFlipX.active
try: ADP_OIII(idx)
except: pass
elif key == "flipY":
pe.objects[idx].flipY = ObjFlipY.active
try: ADP_OIII(idx)
except: pass
elif key == "text":
pe.objects[idx].text = ObjText.text
elif key == "fontSize":
if isMathOperation(ObjFontSize.text):
try:
pe.objects[idx].sfs = int(eval(ObjFontSize.text))
except: ...
ObjFontSize.text = str(pe.objects[idx].sfs)
elif key == "layer":
try:
pe.objects[idx].layer = int(ObjLayer.text)
except:
ObjLayer.text = str(pe.objects[idx].layer)
elif key == "tag":
pe.objects[idx].tag = ObjTag.text
elif key == "color":
if pe.__isRGB(ObjColor.text):
try:
pe.objects[idx].color = list(eval(ObjColor.text))
except: ...
ObjColor.text = str(pe.objects[idx].color)
elif key == "transparent":
try:
pe.objects[idx].transparent = max(0, min(255, eval(ObjTSP.text)))
except: ...
ObjTSP.text = str(pe.objects[idx].transparent)
elif key == "richText":
pe.objects[idx].richText = ObjRichText.active
elif key == "useFullAlpha":
pe.objects[idx].useFullAlpha = ObjUseFullAlpha.active
elif key == "smooth":
pe.objects[idx].smooth = ObjSmooth.active
elif key == "useCamera":
pe.objects[idx].useCamera = ObjUseCamera.active
elif key == "script":
if ObjScript.text != "":
l = [i.strip() for i in ObjScript.text.split(",")]
c = 0
for i in l:
if l.count(i) > 1:
c += 1
break
if c == 0:
pe.objects[idx].script = ObjScript.text
setObjProperty(st.lastSelectionObject, False)
ObjScript.text = pe.objects[idx].script
elif key == "font":
st.drawingLayer = 0
fileConductor.thisPath = pt._defaultPath
try:
font = pygame.font.Font(content, 1)
pe.objects[idx].font = content
ADP_OFNII(idx)
except: pass
elif key == "image":
st.drawingLayer = 0
fileConductor.thisPath = pt._defaultPath
if content != None and content.split('.')[-1] in pe._imgTypes:
pe.objects[idx].image = pe.textures[content.split(pt.s)[-1]] if not pe.objects[idx].useFullAlpha else pe.texturesTSP[content.split(pt.s)[-1]]
pe.objects[idx].imagePath = content.split(pt.s)[-1]
ObjWidth.text = str(pe.objects[idx].width)
ObjHeight.text = str(pe.objects[idx].height)
ADP_OIII(idx)
elif content == None:
pe.objects[idx].image = content
pe.objects[idx].imagePath = content
OIII = None
setObjProperty(st.lastSelectionObject, False)
try:
obj.endText = 0
obj.check_text()
except: pass
ouar.saveObjs(pe, f"{PATH}{pt.s}{st.projects[st.projectIdx]}{pt.s}ObjectInfo.txt")
def setScriptVarValue(script, type, var, value, OBJ = None):
idx = pe.objName.index(st.lastSelectionObject)
obj = pe.objects[idx]
# try:
if type == "str":
value = f"\"{value}\""
value = eval(f"{type}({value})")
_val = str(value)
g = loadOBJScriptLinks(idx)
if script.split(".")[-1] in obj.SC_CHANGED:
if g[script][var] == value:
obj.SC_CHANGED[script.split(".")[-1]][var] = False
else:
obj.SC_CHANGED[script.split(".")[-1]][var] = True
else:
obj.S_CONTENT[script.split(".")[-1]] = {}