-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
1760 lines (1472 loc) · 69.5 KB
/
main.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 sys, shutil, os, random, string, json, re, time, zipfile, io, base64, struct, subprocess, importlib
from tkinter import ttk, messagebox, filedialog, simpledialog
import tkinter as tk
VERSION = 0.7
yxFloatValue = 0.3
zoom_factor = 0
inZoomFactor = 0.9
outZoomFactor = 1.1
azimuth = 30
elevation = 30
global_preview_rotation = True
increaseEandA = 5
try:
import stl, requests, lxml, lxml.etree
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from modules.bjson import BJSONFile
from pygltflib import GLTF2, Scene, Node, Mesh, Primitive, Buffer, BufferView, Accessor, Asset
except ImportError:
answ = messagebox.askyesno("Notice", "The script needs to install some dependancies in order to run correctly.\nMay it install dependancies from 'requirements.txt'?")
if answ:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
messagebox.showinfo("Notice","The script has installed some python Modules.\nIt will now restart.")
time.sleep(1)
os.system(f'python "{__file__}"')
sys.exit(1)
class Object3D:
def __init__(self, name, position, dimensions):
self.name = name
self.position = np.array(position)
self.dimensions = np.array(dimensions)
self.selected = False
self.texture = None
self.texture_coords = None
def get_corners(self):
x, y, z = self.position
dx, dy, dz = self.dimensions
return [
[x, y, z],
[x + dx, y, z],
[x + dx, y + dy, z],
[x, y + dy, z],
[x, y, z + dz],
[x + dx, y, z + dz],
[x + dx, y + dy, z + dz],
[x, y + dy, z + dz],
]
def scale(self, scale_factor):
self.dimensions *= scale_factor
def reset_scale(self):
self.dimensions = self.original_dimensions
def map_texture():
global objects, canvas
selected_name = object_selector.get()
if not selected_name:
messagebox.showerror("No Selection", "Please select an object to map the texture onto.")
return
file_path = filedialog.askopenfilename(
filetypes=[("PNG Image", "*.png")],
title="Select Texture"
)
if not file_path:
return
try:
# Load the texture image and normalize it
texture_img = plt.imread(file_path)
if texture_img.dtype == np.uint8:
texture_img = texture_img.astype(np.float32) / 255.0
for obj in objects:
if obj.name == selected_name:
obj.texture = texture_img
# Create texture coordinates for each face
obj.texture_coords = {
'front': [(0, 0), (1, 0), (1, 1), (0, 1)],
'back': [(0, 0), (1, 0), (1, 1), (0, 1)],
'top': [(0, 0), (1, 0), (1, 1), (0, 1)],
'bottom': [(0, 0), (1, 0), (1, 1), (0, 1)],
'left': [(0, 0), (1, 0), (1, 1), (0, 1)],
'right': [(0, 0), (1, 0), (1, 1), (0, 1)]
}
break
# Update the display
draw_3d_plot(objects, canvas)
except Exception as e:
messagebox.showerror("Texture Error", f"Failed to load texture: {str(e)}")
def draw_3d_plot(objects, canvas):
global azimuth, elevation
ax.clear()
ax.set_facecolor('darkgray')
ax.view_init(elevation, azimuth)
selected_color = 'darkcyan'
default_color = 'cyan'
b_Val = 0.15
tColors = 'black'
tColorSelected = 'red'
selectedaVal = 0.30
light_red = (1, 0.5, 0.5, 0.8)
for obj in objects:
corners = obj.get_corners()
verts = [
[corners[0], corners[1], corners[5], corners[4]],
[corners[7], corners[6], corners[2], corners[3]],
[corners[0], corners[3], corners[7], corners[4]],
[corners[1], corners[2], corners[6], corners[5]],
[corners[0], corners[1], corners[2], corners[3]],
[corners[4], corners[5], corners[6], corners[7]],
]
color = selected_color if obj.selected else default_color
tColor = tColors if obj.selected else tColorSelected
tColor = tColorSelected if obj.selected else tColors
a_val = selectedaVal if obj.selected else b_Val
if obj.texture is not None:
ax.add_collection3d(Poly3DCollection(verts, facecolors=obj.texture, linewidths=1, edgecolors=light_red, alpha=a_val))
else:
ax.add_collection3d(Poly3DCollection(verts, facecolors=color, linewidths=1, edgecolors=light_red, alpha=a_val))
center = obj.position + obj.dimensions / 1.5
if obj.selected:
ax.text(*center+7, obj.name, color=tColor, fontsize=8, fontweight='bold', bbox=dict(alpha=0.7))
else:
ax.text(*center, obj.name, color=tColor)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
all_positions = np.array([obj.position for obj in objects])
all_dimensions = np.array([obj.dimensions for obj in objects])
min_pos = np.min(all_positions, axis=0)
max_pos = np.max(all_positions + all_dimensions, axis=0)
ax.set_xlim(min_pos[0], max_pos[0])
ax.set_ylim(min_pos[1], max_pos[1])
ax.set_zlim(min_pos[2], max_pos[2])
max_range = np.array([max_pos[0] - min_pos[0], max_pos[1] - min_pos[1], max_pos[2] - min_pos[2]])
max_range = max(max_range)
mid_point = (min_pos + max_pos) / 2
ax.set_xlim(mid_point[0] - max_range / 2, mid_point[0] + max_range / 2)
ax.set_ylim(mid_point[1] - max_range / 2, mid_point[1] + max_range / 2)
ax.set_zlim(mid_point[2] - max_range / 2, mid_point[2] + max_range / 2)
canvas.draw()
def zoom(event):
global ax, canvas, current_model_file, zoom_factor
if event.delta > 0:
zoom_factor = inZoomFactor
elif event.delta < 0:
zoom_factor = outZoomFactor
xlim = ax.get_xlim()
ylim = ax.get_ylim()
zlim = ax.get_zlim()
x_center = (xlim[0] + xlim[1]) / 2
y_center = (ylim[0] + ylim[1]) / 2
z_center = (zlim[0] + zlim[1]) / 2
x_range = (xlim[1] - xlim[0]) / 2 * zoom_factor
y_range = (ylim[1] - ylim[0]) / 2 * zoom_factor
z_range = (zlim[1] - zlim[0]) / 2 * zoom_factor
ax.set_xlim([x_center - x_range, x_center + x_range])
ax.set_ylim([y_center - y_range, y_center + y_range])
ax.set_zlim([z_center - z_range, z_center + z_range])
canvas.draw()
def on_model_selected(event):
global current_model_file, objects, model_selector
selected_file = model_selector.get()
current_model_file = os.path.join(os.getcwd(), 'data', selected_file)
objects = read_objects_from_file(current_model_file)
object_selector.config(values=[obj.name for obj in objects])
object_selector.set('')
draw_3d_plot(objects, canvas)
def update_object_data():
selected_name = object_selector.get()
obj = next((o for o in objects if o.name == selected_name), None)
if obj:
try:
new_position = [float(pos_entry_x.get()), float(pos_entry_y.get()), float(pos_entry_z.get())]
new_dimensions = [float(dim_entry_x.get()), float(dim_entry_y.get()), float(dim_entry_z.get())]
obj.position = np.array(new_position)
obj.dimensions = np.array(new_dimensions)
draw_3d_plot(objects, canvas)
save_objects(objects, current_model_file)
except ValueError:
messagebox.showerror("Invalid input", "Please enter valid Ineger/Floating Point Numbers\nUsage for positions and dimensions.\n\nStrings (Non Numerical Numbers) are not Allowed.")
return
def on_object_selected(event):
selected_name = object_selector.get()
for obj in objects:
obj.selected = (obj.name == selected_name)
draw_3d_plot(objects, canvas)
obj = next((o for o in objects if o.name == selected_name), None)
if obj:
pos_entry_x.delete(0, tk.END)
pos_entry_x.insert(0, str(obj.position[0]))
pos_entry_y.delete(0, tk.END)
pos_entry_y.insert(0, str(obj.position[1]))
pos_entry_z.delete(0, tk.END)
pos_entry_z.insert(0, str(obj.position[2]))
dim_entry_x.delete(0, tk.END)
dim_entry_x.insert(0, str(obj.dimensions[0]))
dim_entry_y.delete(0, tk.END)
dim_entry_y.insert(0, str(obj.dimensions[1]))
dim_entry_z.delete(0, tk.END)
dim_entry_z.insert(0, str(obj.dimensions[2]))
def save_objects(objects, filename="modified_data.txt"):
with open(filename, "w") as file:
for obj in objects:
file.write(f"{obj.name}\n")
file.write(f"{', '.join(map(str, obj.position))}\n")
file.write(f"{', '.join(map(str, obj.dimensions))}\n\n")
def read_objects_from_file(filename):
objects0 = []
with open(filename, 'r') as file:
lines = file.readlines()
i = 0
while i < len(lines):
name = lines[i].strip()
position = list(map(float, lines[i + 1].strip().split(',')))
dimensions = list(map(float, lines[i + 2].strip().split(',')))
objects0.append(Object3D(name, position, dimensions))
i += 4
return objects0
def list_model_files(directory):
return [f for f in os.listdir(directory) if f.endswith('.txt') and 'geometry' in f]
def update_model_selector():
global current_model_file
"""Update the model selector dropdown with the latest model files."""
global model_selector
model_directory = os.path.join(os.getcwd(), 'data')
model_files = list_model_files(model_directory)
if not model_files:
model_selector['values'] = []
messagebox.showerror("No Models Found", "No .txt model files found in the 'data' directory.")
sys.exit()
else:
model_selector['values'] = model_files
model_selector.set(model_files[0] if model_files else "")
current_model_file = os.path.join(model_directory, model_files[0])
draw_3d_plot(objects, canvas)
def open_file():
global current_model_file, objects
file_path = filedialog.askopenfilename(
filetypes=[("Text Model Files", "*.txt")],
initialdir=os.path.join(os.getcwd(), 'data')
)
if file_path:
current_model_file = file_path
objects = read_objects_from_file(current_model_file)
object_selector.config(values=[obj.name for obj in objects])
object_selector.set('')
draw_3d_plot(objects, canvas)
def save_file():
global current_model_file, objects
if not current_model_file:
file_path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text Model Files", "*.txt")],
initialdir=os.path.join(os.getcwd(), 'data')
)
if file_path:
current_model_file = file_path
if current_model_file:
save_objects(objects, current_model_file)
def quit_app():
root.quit()
sys.exit(1)
def show_tool_options():
messagebox.showinfo("Tools", "Tool options not yet implemented.")
def show_app_options():
messagebox.showinfo("Options", "Application options not yet implemented.")
def export_as_obj():
global objects
if not objects:
messagebox.showerror("Export Error", "No objects to export.")
return
obj_file_path = filedialog.asksaveasfilename(
defaultextension=".obj",
filetypes=[("OBJ files", "*.obj")],
initialdir=os.getcwd(),
title="Save OBJ File"
)
if not obj_file_path:
return
try:
with open(obj_file_path, 'w') as file:
file.write("# Exported OBJ file\n")
vertex_count = 1
for obj in objects:
vertices = obj.get_corners()
for vertex in vertices:
file.write(f"v {vertex[0]} {vertex[1]} {vertex[2]}\n")
file.write(f"f {vertex_count} {vertex_count+1} {vertex_count+2} {vertex_count+3}\n")
file.write(f"f {vertex_count+4} {vertex_count+5} {vertex_count+6} {vertex_count+7}\n")
file.write(f"f {vertex_count} {vertex_count+3} {vertex_count+7} {vertex_count+4}\n")
file.write(f"f {vertex_count+1} {vertex_count+2} {vertex_count+6} {vertex_count+5}\n")
file.write(f"f {vertex_count} {vertex_count+1} {vertex_count+5} {vertex_count+4}\n")
file.write(f"f {vertex_count+2} {vertex_count+3} {vertex_count+7} {vertex_count+6}\n")
vertex_count += 8
messagebox.showinfo("Export Success", f"Model exported successfully to {obj_file_path}")
except Exception as e:
messagebox.showerror("Export Error", f"Failed to export model: {e}")
def export_as_stl():
if not objects:
messagebox.showerror("Export Error", "No objects to export.")
return
stl_file_path = filedialog.asksaveasfilename(
defaultextension=".stl",
filetypes=[("STL files", "*.stl")],
initialdir=os.getcwd(),
title="Save STL File"
)
if not stl_file_path:
return
try:
faces = []
for obj in objects:
vertices = np.array(obj.get_corners())
faces.extend([
[vertices[0], vertices[1], vertices[5]],
[vertices[5], vertices[4], vertices[0]],
[vertices[1], vertices[2], vertices[6]],
[vertices[6], vertices[5], vertices[1]],
[vertices[2], vertices[3], vertices[7]],
[vertices[7], vertices[6], vertices[2]],
[vertices[3], vertices[0], vertices[4]],
[vertices[4], vertices[7], vertices[3]],
[vertices[4], vertices[5], vertices[6]],
[vertices[6], vertices[7], vertices[4]],
[vertices[0], vertices[1], vertices[2]],
[vertices[2], vertices[3], vertices[0]],
])
faces = np.array(faces)
stl_mesh = stl.mesh.Mesh(np.zeros(faces.shape[0], dtype=stl.mesh.Mesh.dtype))
for i, face in enumerate(faces):
for j in range(3):
stl_mesh.vectors[i][j] = face[j]
stl_mesh.save(stl_file_path)
messagebox.showinfo("Export Success", f"Model exported successfully to {stl_file_path}")
except Exception as e:
messagebox.showerror("Export Error", f"Failed to export model: {e}")
def export_as_text():
global current_model_file, objects
if not objects:
messagebox.showerror("Export Error", "No objects to export.")
return
if current_model_file:
file_path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text Model Files", "*.txt")],
initialdir=os.getcwd()
)
if file_path:
current_model_file = file_path
else:
return
if current_model_file:
save_objects(objects, current_model_file)
messagebox.showinfo("Export Success", f"Model exported successfully to {current_model_file}")
def openJsonFile():
global objects, dim_entry_x, dim_entry_y, dim_entry_z, pos_entry_x, pos_entry_y, pos_entry_z, object_selector
if messagebox.askyesno("WARNING", "All Current Model Data and Information in Cache will be lost!\nAre you sure you want to Load a JSON Model File?"):
messagebox.showinfo("Resetting Model Data", "All Model Information is being deleted now.\nThis might take a few seconds...")
dataFolders = os.listdir(".\\data")
for file in dataFolders:
os.remove(f".\\data\\{file}")
try:
os.rmdir('.\\data')
os.remove('.\\hash_database.json')
except FileNotFoundError:
pass
try:
with open('.\\filename.txt','r') as outf:
data = outf.readline()
os.remove(data.replace("\n",''))
getBaseName = os.path.basename(os.path.dirname(data))
except FileNotFoundError:
pass
try:
os.rmdir(f"{os.path.dirname(__file__)}\\models\\{getBaseName}")
os.rmdir(f"{os.path.dirname(__file__)}\\models")
except FileNotFoundError:
pass
json2modelBase()
update_model_selector()
file_path = os.listdir(".\\data")
current_model_file = f"{os.path.dirname(__file__)}\\data\\{file_path[0]}"
objects = read_objects_from_file(current_model_file)
object_selector.config(values=[obj.name for obj in objects])
object_selector.set('')
draw_3d_plot(objects, canvas)
with open('.\\hash_database.json','w') as f1:
f1.write("JSON File Loaded, DO NOT CONVERT TO BJSON.")
else:
messagebox.showinfo("Data Reset Canceled", "Model Data has not been deleted.\nAll settings untouched.")
return
def openBjsonFile():
global objects, dim_entry_x, dim_entry_y, dim_entry_z, pos_entry_x, pos_entry_y, pos_entry_z, object_selector
if messagebox.askyesno("WARNING", "All Current Model Data and Information in Cache will be lost!\nAre you sure you want to Load another BJSON Model File?"):
messagebox.showinfo("Resetting Model Data", "All Model Information is being deleted now.\nThis might take a few seconds...")
dataFolders = os.listdir(".\\data")
for file in dataFolders:
os.remove(f".\\data\\{file}")
try:
os.rmdir('.\\data')
os.remove('.\\hash_database.json')
except FileNotFoundError:
pass
try:
with open('.\\filename.txt','r') as outf:
data = outf.readline()
os.remove(data.replace("\n",''))
getBaseName = os.path.basename(os.path.dirname(data))
except FileNotFoundError:
pass
try:
os.rmdir(f"{os.path.dirname(__file__)}\\models\\{getBaseName}")
os.rmdir(f"{os.path.dirname(__file__)}\\models")
except FileNotFoundError:
pass
bjson2models()
update_model_selector()
file_path = os.listdir(".\\data")
current_model_file = f"{os.path.dirname(__file__)}\\data\\{file_path[0]}"
objects = read_objects_from_file(current_model_file)
object_selector.config(values=[obj.name for obj in objects])
object_selector.set('')
draw_3d_plot(objects, canvas)
else:
messagebox.showinfo("Data Reset Canceled", "Model Data has not been deleted.\nAll settings untouched.")
return
def scale_model(factor):
global objects, dim_entry_x, dim_entry_y, dim_entry_z, pos_entry_x, pos_entry_y, pos_entry_z, object_selector
for obj in objects:
original_position = obj.position.copy()
obj.scale(factor)
if factor == 2:
obj.position = [coord / 2 for coord in original_position]
elif factor == 0.5:
obj.position = [coord * 2 for coord in original_position]
draw_3d_plot(objects, canvas)
selected_name = object_selector.get()
if selected_name:
obj = next((o for o in objects if o.name == selected_name), None)
if obj:
dim_entry_x.delete(0, tk.END)
dim_entry_x.insert(0, str(obj.dimensions[0]))
dim_entry_y.delete(0, tk.END)
dim_entry_y.insert(0, str(obj.dimensions[1]))
dim_entry_z.delete(0, tk.END)
dim_entry_z.insert(0, str(obj.dimensions[2]))
pos_entry_x.delete(0, tk.END)
pos_entry_x.insert(0, str(obj.position[0]))
pos_entry_y.delete(0, tk.END)
pos_entry_y.insert(0, str(obj.position[1]))
pos_entry_z.delete(0, tk.END)
pos_entry_z.insert(0, str(obj.position[2]))
def models2jsonf(answer='--json'):
with open(".\\filename.txt",'r') as f0:
geoPath = f0.readline()
geoPath = geoPath.replace("\n",'')
with open(geoPath, "r") as f:
data = json.load(f)
directory = ".\\data"
text_files0 = [f for f in os.listdir(directory) if f.startswith("geometry.") and f.endswith(".txt")]
text_files = []
for file0 in text_files0:
with open(f"{directory}\\{file0}", 'r') as f0:
if len(f0.read()) > 4:
text_files.append(file0)
else:
pass
def get_base_name_and_number(name):
match = re.match(r"(\d*)(\D+)", name)
if match:
number = int(match.group(1)) if match.group(1) else 0
base_name = match.group(2)
return base_name, number
for text_file in text_files:
model_name = text_file[len("geometry."):-len(".txt")]
if ":" in model_name:
model_name.replace("_", ":")
with open(os.path.join(directory, text_file), "r") as f:
lines = f.read().strip().splitlines()
parsed_data = {}
current_name = None
for line in lines:
line = line.strip()
if not line:
continue
if re.match(r"^\w+\d*$", line):
current_name = line
parsed_data[current_name] = {}
elif current_name and "origin" not in parsed_data[current_name]:
try:
parsed_data[current_name]["origin"] = list(map(float, line.split(", ")))
except ValueError:
print(f"Skipping invalid origin line: {line}")
elif current_name:
try:
parsed_data[current_name]["size"] = list(map(float, line.split(", ")))
except ValueError:
print(f"Skipping invalid size line: {line}")
grouped_data = {}
for key in parsed_data:
base_name, number = get_base_name_and_number(key)
if base_name not in grouped_data:
grouped_data[base_name] = []
grouped_data[base_name].append((number, parsed_data[key]))
for base_name in grouped_data:
grouped_data[base_name].sort(key=lambda x: x[0])
if f"geometry.{model_name}" in data:
for bone in data[f"geometry.{model_name}"]["bones"]:
name = bone["name"]
if name in grouped_data:
for i, (number, update_data) in enumerate(grouped_data[name]):
if i < len(bone["cubes"]):
bone["cubes"][i]["origin"] = update_data.get("origin", bone["cubes"][i]["origin"])
bone["cubes"][i]["size"] = update_data.get("size", bone["cubes"][i]["size"])
else:
if name in parsed_data:
bone["cubes"][0]["origin"] = parsed_data[name].get("origin", bone["cubes"][0]["origin"])
bone["cubes"][0]["size"] = parsed_data[name].get("size", bone["cubes"][0]["size"])
with open(f"{os.path.dirname(geoPath)}\\geometry_updated.json", "w") as f:
json.dump(data, f, indent=4)
print(f"Updated data saved in {geoPath}")
def convert_floats_to_ints(data):
if isinstance(data, dict):
return {key: convert_floats_to_ints(value) for key, value in data.items()}
elif isinstance(data, list):
return [convert_floats_to_ints(item) for item in data]
elif isinstance(data, float):
if data.is_integer():
return int(data)
else:
return data
else:
return data
def process_json_file(filename):
with open(filename, 'r') as file:
data = json.load(file)
modified_data = convert_floats_to_ints(data)
with open(filename, 'w') as file:
json.dump(modified_data, file, indent=4)
process_json_file(f"{os.path.dirname(geoPath)}\\geometry_updated.json")
time.sleep(0.5)
filename0 = os.path.basename(geoPath)
getbasename = os.path.basename(os.path.dirname(geoPath))
if answer == "--bjson":
if os.path.exists(".\\hash_database.json"):
with open(".\\hash_database.json", 'r') as f01:
if "JSON File Loaded, DO NOT CONVERT TO BJSON." not in f01.read():
with open(f"{os.path.dirname(geoPath)}\\geometry_updated.json", 'r', encoding="utf-8") as f:
json_str = f.read()
bjson_file = BJSONFile()
bjson_file.fromJson(json_str)
with open(filename0.replace('.json','.bjson'), 'wb') as f:
f.write(bjson_file.getData())
else:
messagebox.showerror("Error","BJSON Model Editor ran into an Issue.\nAnd is unable to Process your Current Conversion Request.\n\nJSON Files cannot be converted into BJSON without proper BJSON Hash Keys.\n\nThese are obtained through Legit BJSON Model Files.")
return
messagebox.showinfo("Success!", f"BJSON Model File Saved at: {os.path.dirname(__file__)}\\{filename0.replace('.json','.bjson')}")
elif answer == "--json":
messagebox.showinfo("Success!", f"JSON Model File Saved at: {geoPath}")
pass
else:
messagebox.showerror("Error","BJSON Model Editor ran into an Issue, and is unable to Process your Current Conversion Request.")
return
def bodyAndHeadItterations(mode=0):
global current_model_file
directory = os.path.dirname(__file__)
if mode == 1:
file_path = f"{current_model_file}"
head_counter = 0
body_counter = 0
headOcc = 0
bodyOcc = 0
with open(file_path, 'r') as file:
lines = file.readlines()
file.seek(0x00)
whole_file = file.read()
file.seek(0x00)
headOcc += whole_file.count("head")
file.seek(0x00)
bodyOcc += whole_file.count("body")
print(headOcc, bodyOcc)
new_lines = []
for line in lines:
if "head" in line and headOcc > 1:
new_line = re.sub(r'\bhead\b', f'{head_counter}head', line)
head_counter += 1
elif "body" in line and bodyOcc > 1:
new_line = re.sub(r'\bbody\b', f'{body_counter}body', line)
body_counter += 1
else:
new_line = line
new_lines.append(new_line)
with open(file_path, 'w') as file:
file.writelines(new_lines)
return
else:
for filename in os.listdir(f"{directory}\\data"):
if filename.endswith(".txt") and "geometry." in filename:
file_path = os.path.join(f"{directory}\\data", filename)
head_counter = 0
body_counter = 0
headOcc = 0
bodyOcc = 0
with open(file_path, 'r') as file:
lines = file.readlines()
file.seek(0x00)
whole_file = file.read()
headOcc += whole_file.count("head")
bodyOcc += whole_file.count("body")
print(headOcc, bodyOcc)
new_lines = []
for line in lines:
if "head" in line and headOcc > 1:
new_line = re.sub(r'\bhead\b', f'{head_counter}head', line)
head_counter += 1
elif "body" in line and bodyOcc > 1:
new_line = re.sub(r'\bbody\b', f'{body_counter}body', line)
body_counter += 1
else:
new_line = line
new_lines.append(new_line)
with open(file_path, 'w') as file:
file.writelines(new_lines)
def json2model(main_string, directory_name, random_string, bjsonFile, directory=os.path.dirname(__file__)):
if '"size": [' not in main_string:
messagebox.showerror('Error',"The Provided JSON/BJSON File was Not a Model.")
sys.exit(1)
else:
json_path = f'{directory}\\models\\{directory_name}\\{random_string}.json'
with open(json_path, 'w') as json_file:
json_file.write(main_string)
with open(json_path, "r") as new_json_file:
json_data = json.load(new_json_file)
for key, value in json_data.items():
if key.startswith("geometry.") and "bones" in value:
if ":" in key:
key = key.replace(":", "_")
bones = value["bones"]
output_lines = []
for bone in bones:
if "name" in bone and "cubes" in bone:
name = bone["name"]
cubes = bone["cubes"]
for cube in cubes:
if "origin" in cube and "size" in cube:
origin = cube["origin"]
size = cube["size"]
output_lines.append(f"{name}")
output_lines.append(f"{origin[0]}, {origin[1]}, {origin[2]}")
output_lines.append(f"{size[0]}, {size[1]}, {size[2]}")
output_lines.append("")
output_directory = os.path.join(directory, "data")
os.makedirs(output_directory, exist_ok=True)
output_path = os.path.join(output_directory, f"{key}.txt")
with open(output_path, 'w') as output_file:
output_file.write("\n".join(output_lines))
print(f"Converted BJSON Data Saved: {output_directory}")
with open(f'{directory}\\filename.txt','w') as outf:
outf.write(f'{directory}\\models\\{directory_name}\\{random_string}.json\n')
outf.write(f"{bjsonFile}")
time.sleep(0.5)
bodyAndHeadItterations()
def bjson2models():
if not os.path.exists('.\\filename.txt'):
messagebox.showinfo("Welcome", f"Welcome to the MC3DS BJSON Model Editor!\nYou can now edit MC3DS Models easier than ever.\n\nVersion: v{VERSION}.0\nDeveloped by: Cracko298.")
character = string.ascii_letters + string.digits
random_string = ''.join(random.choice(character) for _ in range(16))
directory = os.path.dirname(__file__)
bjsonFile = filedialog.askopenfilename(initialdir=f"{os.path.dirname(__file__)}", filetypes=[("BJSON Model Files", "*.bjson")])
if not bjsonFile:
bjsonFile = f"{os.path.dirname(__file__)}\\modules\\exampleModel.bjson"
file_name0 = os.path.basename(bjsonFile)
directory_name = file_name0.replace('.bjson','')
os.makedirs(f"{directory}\\models\\{directory_name}", exist_ok=True)
bjsonfileOpen = BJSONFile().open(bjsonFile)
main_string = bjsonfileOpen.toJson(showDebug=False)
json2model(main_string, directory_name, random_string, bjsonFile, directory)
def json2modelBase():
character = string.ascii_letters + string.digits
random_string = ''.join(random.choice(character) for _ in range(16))
directory = os.path.dirname(__file__)
jsonFile = filedialog.askopenfilename(initialdir=f"{os.path.dirname(__file__)}", filetypes=[("JSON Model Files", "*.json")])
if not jsonFile:
messagebox.showerror("Error", "No JSON Model File Selected.")
return
file_name0 = os.path.basename(jsonFile)
directory_name = file_name0.replace('.json','')
os.makedirs(f"{directory}\\models\\{directory_name}",exist_ok=True)
with open(jsonFile,'r') as f0:
main_string = f0.read()
json2model(main_string, directory_name, random_string, jsonFile, directory)
def savetojson():
models2jsonf('--json')
def savetobjson():
models2jsonf('--bjson')
def export_as_gltf():
global objects, current_model_file
if not objects:
messagebox.showerror("Export Error", "No objects to export.")
return
gltf_file_path = filedialog.asksaveasfilename(
defaultextension=".gltf",
filetypes=[("GLTF files", "*.gltf")],
initialdir=os.getcwd(),
title="Save GLTF File"
)
if not gltf_file_path:
return
with open(current_model_file, 'r') as file:
data = file.read()
parts = data.strip().split("\n\n")
vertices = []
indices = []
index_offset = 0
for part in parts:
lines = part.split("\n")
if len(lines) < 3:
continue
position = list(map(float, lines[1].split(", ")))
size = list(map(float, lines[2].split(", ")))
x, y, z = position
w, h, d = size
vertices.extend([
x, y, z,
x + w, y, z,
x + w, y + h, z,
x, y + h, z,
x, y, z + d,
x + w, y, z + d,
x + w, y + h, z + d,
x, y + h, z + d
])
indices.extend([
index_offset, index_offset + 2, index_offset + 1, index_offset, index_offset + 3, index_offset + 2,
index_offset + 4, index_offset + 5, index_offset + 6, index_offset + 4, index_offset + 6, index_offset + 7,
index_offset, index_offset + 4, index_offset + 7, index_offset, index_offset + 7, index_offset + 3,
index_offset + 1, index_offset + 2, index_offset + 6, index_offset + 1, index_offset + 6, index_offset + 5,
index_offset + 2, index_offset + 3, index_offset + 7, index_offset + 2, index_offset + 7, index_offset + 6,
index_offset, index_offset + 1, index_offset + 5, index_offset, index_offset + 5, index_offset + 4
])
index_offset += 8
gltf = GLTF2()
scene = Scene()
gltf.scenes.append(scene)
gltf.scene = 0
node = Node()
gltf.nodes.append(node)
scene.nodes.append(0)
mesh = Mesh()
primitive = Primitive()
mesh.primitives.append(primitive)
gltf.meshes.append(mesh)
node.mesh = 0
vertices_bytes = struct.pack(f'{len(vertices)}f', *vertices)
indices_bytes = struct.pack(f'{len(indices)}I', *indices)
buffer_data = vertices_bytes + indices_bytes
buffer = Buffer()
buffer.uri = "data:application/octet-stream;base64," + base64.b64encode(buffer_data).decode('utf-8')
buffer.byteLength = len(buffer_data)
gltf.buffers.append(buffer)
bufferView_vertices = BufferView()
bufferView_vertices.buffer = 0
bufferView_vertices.byteOffset = 0
bufferView_vertices.byteLength = len(vertices_bytes)
gltf.bufferViews.append(bufferView_vertices)
bufferView_indices = BufferView()
bufferView_indices.buffer = 0
bufferView_indices.byteOffset = len(vertices_bytes)
bufferView_indices.byteLength = len(indices_bytes)
gltf.bufferViews.append(bufferView_indices)
accessor_vertices = Accessor()
accessor_vertices.bufferView = 0
accessor_vertices.byteOffset = 0
accessor_vertices.componentType = 5126
accessor_vertices.count = len(vertices) // 3
accessor_vertices.type = "VEC3"
gltf.accessors.append(accessor_vertices)
accessor_indices = Accessor()
accessor_indices.bufferView = 1
accessor_indices.byteOffset = 0
accessor_indices.componentType = 5125
accessor_indices.count = len(indices)
accessor_indices.type = "SCALAR"
gltf.accessors.append(accessor_indices)
primitive.attributes.POSITION = 0
primitive.indices = 1
gltf.save(gltf_file_path)
def parse_input_file(filename):
with open(filename, 'r') as file:
lines = [line.strip() for line in file.readlines() if line.strip()]
data = []
for i in range(0, len(lines), 3):
name = lines[i].strip()
position = tuple(map(float, lines[i + 1].strip().split(', ')))
size = tuple(map(float, lines[i + 2].strip().split(', ')))
data.append((name, position, size))
return data
def export_as_ply():
global objects, current_model_file
data = parse_input_file(current_model_file)
if not objects:
messagebox.showerror("Export Error", "No objects to export.")
return
ply_file_path = filedialog.asksaveasfilename(
defaultextension=".ply",
filetypes=[("PLY files", "*.ply")],
initialdir=os.getcwd(),
title="Save PLY File"
)
if not ply_file_path:
return
with open(ply_file_path, 'w') as file:
vertex_list = []
face_list = []
for name, position, size in data:
x, y, z = position
w, h, d = size
vertices = [
(x, y, z), (x + w, y, z), (x + w, y + h, z), (x, y + h, z),
(x, y, z + d), (x + w, y, z + d), (x + w, y + h, z + d), (x, y + h, z + d)
]
vertex_list.extend(vertices)
start_index = len(vertex_list) - 8
faces = [
(start_index, start_index + 1, start_index + 2, start_index + 3),
(start_index + 4, start_index + 5, start_index + 6, start_index + 7),