forked from Sprytile/Sprytile
/
sprytile_utils.py
1257 lines (1014 loc) · 41.9 KB
/
sprytile_utils.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 bpy
import bgl
import blf
import bmesh
import math
from bpy_extras import view3d_utils
from bmesh.types import BMVert, BMEdge, BMFace
from mathutils import Matrix, Vector, Quaternion
from mathutils.geometry import intersect_line_plane, distance_point_to_plane
from bpy.path import abspath
from datetime import datetime
from os import path
import sprytile_modal
import addon_updater_ops
def get_current_grid_vectors(scene, with_rotation=True):
"""Returns the current grid X/Y/Z vectors from scene data
:param scene: scene data
:param with_rotation: bool, rotate the grid vectors by sprytile_data
:return: up_vector, right_vector, normal_vector
"""
data_normal = scene.sprytile_data.paint_normal_vector
data_up_vector = scene.sprytile_data.paint_up_vector
normal_vector = Vector((data_normal[0], data_normal[1], data_normal[2]))
up_vector = Vector((data_up_vector[0], data_up_vector[1], data_up_vector[2]))
normal_vector.normalize()
up_vector.normalize()
right_vector = up_vector.cross(normal_vector)
if with_rotation:
rotation = Quaternion(-normal_vector, scene.sprytile_data.mesh_rotate)
up_vector = rotation * up_vector
right_vector = rotation * right_vector
return up_vector, right_vector, normal_vector
def snap_vector_to_axis(vector, mirrored=False):
"""Snaps a vector to the closest world axis"""
norm_vector = vector.normalized()
x = Vector((1.0, 0.0, 0.0))
y = Vector((0.0, 1.0, 0.0))
z = Vector((0.0, 0.0, 1.0))
x_dot = 1 - abs(norm_vector.dot(x))
y_dot = 1 - abs(norm_vector.dot(y))
z_dot = 1 - abs(norm_vector.dot(z))
dot_array = [x_dot, y_dot, z_dot]
closest = min(dot_array)
if closest is dot_array[0]:
snapped_vector = x
elif closest is dot_array[1]:
snapped_vector = y
else:
snapped_vector = z
vector_dot = norm_vector.dot(snapped_vector)
if mirrored is False and vector_dot < 0:
snapped_vector *= -1
elif mirrored is True and vector_dot > 0:
snapped_vector *= -1
return snapped_vector
def get_grid_pos(position, grid_center, right_vector, up_vector, world_pixels, grid_x, grid_y, as_coord=False):
"""Snaps a world position to the given grid settings"""
position_vector = position - grid_center
pos_vector_normalized = position.normalized()
if not as_coord:
if right_vector.dot(pos_vector_normalized) < 0:
right_vector *= -1
if up_vector.dot(pos_vector_normalized) < 0:
up_vector *= -1
x_magnitude = position_vector.dot(right_vector)
y_magnitude = position_vector.dot(up_vector)
x_unit = grid_x / world_pixels
y_unit = grid_y / world_pixels
x_snap = math.floor(x_magnitude / x_unit)
y_snap = math.floor(y_magnitude / y_unit)
right_vector *= x_unit
up_vector *= y_unit
if as_coord:
return Vector((x_snap, y_snap)), right_vector, up_vector
grid_pos = grid_center + (right_vector * x_snap) + (up_vector * y_snap)
return grid_pos, right_vector, up_vector
def raycast_grid(scene, context, up_vector, right_vector, plane_normal, ray_origin, ray_vector):
"""
Raycast to a plane on the scene cursor, and return the grid snapped position
:param scene:
:param context:
:param up_vector:
:param right_vector:
:param plane_normal:
:param ray_origin:
:param ray_vector:
:return: grid_position, x_vector, y_vector, plane_pos
"""
plane_pos = intersect_line_plane(ray_origin, ray_origin + ray_vector, scene.cursor_location, plane_normal)
# Didn't hit the plane exit
if plane_pos is None:
return None, None, None, None
world_pixels = scene.sprytile_data.world_pixels
target_grid = get_grid(context, context.object.sprytile_gridid)
grid_x = target_grid.grid[0]
grid_y = target_grid.grid[1]
grid_position, x_vector, y_vector = get_grid_pos(
plane_pos, scene.cursor_location,
right_vector.copy(), up_vector.copy(),
world_pixels, grid_x, grid_y
)
return grid_position, x_vector, y_vector, plane_pos
def get_grid_matrix(sprytile_grid):
"""Returns the transform matrix of a sprytile grid"""
offset_mtx = Matrix.Translation((sprytile_grid.offset[0], sprytile_grid.offset[1], 0))
rotate_mtx = Matrix.Rotation(sprytile_grid.rotate, 4, 'Z')
return offset_mtx * rotate_mtx
def get_grid_texture(obj, sprytile_grid):
"""
Returns the texture applied to an object, given the sprytile_grid
:param obj: the Blender mesh object
:param sprytile_grid: the sprytile grid applied to the object
:return: Texture or None
"""
mat_idx = obj.material_slots.find(sprytile_grid.mat_id)
if mat_idx == -1:
return None
material = obj.material_slots[mat_idx].material
if material is None:
return None
target_img = None
for texture_slot in material.texture_slots:
if texture_slot is None:
continue
if texture_slot.texture is None:
continue
if texture_slot.texture.type == 'NONE':
continue
if texture_slot.texture.image is None:
continue
if texture_slot.texture.type == 'IMAGE':
# Cannot use the texture slot image reference directly
# Have to get it through bpy.data.images to be able to use with BGL
target_img = bpy.data.images.get(texture_slot.texture.image.name)
break
return target_img
def get_selected_grid(context):
"""
Returns the sprytile_grid currently selected
:param context: Blender tool context
:return: sprytile_grid or None
"""
obj = context.object
scene = context.scene
mat_list = scene.sprytile_mats
# The selected mesh object has the current sprytile_grid id
grid_id = obj.sprytile_gridid
return get_grid(context, grid_id)
def get_grid(context, grid_id):
"""
Returns the sprytile_grid with the given id
:param context: Blender tool context
:param grid_id: grid id
:return: sprytile_grid or None
"""
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
for grid in mat_data.grids:
if grid.id == grid_id:
return grid
return None
def get_highest_grid_id(context):
highest_id = -1
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
for grid in mat_data.grids:
highest_id = max(grid.id, highest_id)
return highest_id
def get_mat_data(context, mat_id):
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
if mat_data.mat_id == mat_id:
return mat_data
return None
def get_paint_settings(sprytile_data):
'''
Returns the paint settings bitmask from a sprytile_data instance
:param sprytile_data: sprytile_data instance
:return: A bitmask representing the paint settings in the sprytile_data
'''
# Rotation and UV flip are always included
paint_settings = 0
# Flip x/y are toggles
paint_settings += (1 if sprytile_data.uv_flip_x else 0) << 9
paint_settings += (1 if sprytile_data.uv_flip_y else 0) << 8
# Rotation is encoded as 0-3 clockwise, bit shifted by 10
degree_rotation = round(math.degrees(sprytile_data.mesh_rotate), 0)
if degree_rotation < 0:
degree_rotation += 360
rot_val = 0
if degree_rotation <= 1:
rot_val = 0
elif degree_rotation <= 90:
rot_val = 3
elif degree_rotation <= 180:
rot_val = 2
elif degree_rotation <= 270:
rot_val = 1
paint_settings += rot_val << 10
if sprytile_data.paint_mode == 'MAKE_FACE':
paint_settings += 5 # Default center align
for x in range(4, 8): # All toggles on
paint_settings += 1 << x
if sprytile_data.paint_mode == 'PAINT':
paint_settings += sprytile_data["paint_align"]
paint_settings += (1 if sprytile_data.paint_uv_snap else 0) << 7
paint_settings += (1 if sprytile_data.paint_edge_snap else 0) << 6
paint_settings += (1 if sprytile_data.paint_stretch_x else 0) << 5
paint_settings += (1 if sprytile_data.paint_stretch_y else 0) << 4
return paint_settings
def from_paint_settings(sprytile_data, paint_settings):
"""
Sets the paint settings of a sprytile_data using the paint settings bitmask
:param sprytile_data: sprytile_data instance to set
:param paint_settings: Painting settings bitmask
:return: None
"""
if paint_settings == 0:
return
align_value = paint_settings & 15 # First four bits
rot_value = (paint_settings & 3072) >> 10 # 11th and 12th bit, shifted back
rot_radian = 0
if rot_value == 1:
rot_radian = math.radians(270)
if rot_value == 2:
rot_radian = math.radians(180)
if rot_value == 3:
rot_radian = math.radians(90)
sprytile_data["paint_align"] = align_value
sprytile_data.mesh_rotate = rot_radian
sprytile_data.uv_flip_x = (paint_settings & 1 << 9) > 0
sprytile_data.uv_flip_y = (paint_settings & 1 << 8) > 0
sprytile_data.paint_uv_snap = (paint_settings & 1 << 7) > 0
sprytile_data.paint_edge_snap = (paint_settings & 1 << 6) > 0
sprytile_data.paint_stretch_x = (paint_settings & 1 << 5) > 0
sprytile_data.paint_stretch_y = (paint_settings & 1 << 4) > 0
def label_wrap(col, text, area="VIEW_3D", region_type="TOOL_PROPS", tab_str=" ", scale_y=0.55):
a_id = -1
r_id = -1
new_line = "\n"
tab = "\t"
tabbing = False
n_line = False
col.scale_y = scale_y
areas = bpy.context.screen.areas
for i, a in enumerate(areas):
if a.type == area:
a_id = i
reg = a.regions
for ir, r in enumerate(reg):
if r.type == region_type:
r_id = ir
if a_id < 0 or r_id < 0:
return
p_width = areas[a_id].regions[r_id].width
char_width = 7 # approximate width of each character
line_length = int(p_width / char_width)
last_space = line_length # current position of last space character in text
while last_space > 0:
split_point = line_length # where to split the text
if split_point > len(text):
split_point = len(text) - 1
cr = text.find(new_line, 0, len(text))
if (cr > 0) and (cr <= split_point):
n_line = True
last_space = cr # Position of new line symbol, if found
else:
tabp = text.find("\t", 0, split_point)
if tabp >= 0:
text = text.replace(tab, "", 1)
tabbing = True
n_line = False
last_space = text.rfind(" ", 0, split_point) # Position of last space character in text
if (last_space == -1) or len(text) <= line_length: # No more spaces found, or its the last line of text
last_space = len(text)
line = text[0:last_space]
if tabbing:
line = tab_str + line
col.label(line)
if n_line:
tabbing = False
text = text[last_space + 1:len(text)]
class SprytileAxisUpdate(bpy.types.Operator):
bl_idname = "sprytile.axis_update"
bl_label = "Update Sprytile Axis"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
# Given the normal mode, find the direction of paint_normal_vector, paint_up_vector
data = context.scene.sprytile_data
region = context.region
rv3d = context.region_data
# Get the view ray from center of screen
coord = Vector((int(region.width / 2), int(region.height / 2)))
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
# Get the up vector. The default scene view camera is pointed
# downward, with up on Y axis. Apply view rotation to get current up
view_up_vector = rv3d.view_rotation * Vector((0.0, 1.0, 0.0))
view_vector = snap_vector_to_axis(view_vector, mirrored=True)
view_up_vector = snap_vector_to_axis(view_up_vector)
# implicit X
paint_normal = Vector((1.0, 0.0, 0.0))
if data.normal_mode == 'Y':
paint_normal = Vector((0.0, 1.0, 0.0))
elif data.normal_mode == 'Z':
paint_normal = Vector((0.0, 0.0, 1.0))
view_dot = paint_normal.dot(view_up_vector)
view_dot = abs(view_dot)
paint_up = view_up_vector
if view_dot > 0.9:
paint_up = view_vector
# print("View", view_vector, "View Up", view_up_vector)
# print("Axis update, view dot:", view_dot)
# print("mode", data.normal_mode, "paint normal", paint_normal, "paint up", paint_up)
data.paint_normal_vector = paint_normal
data.paint_up_vector = paint_up
return {'FINISHED'}
class SprytileGridAdd(bpy.types.Operator):
bl_idname = "sprytile.grid_add"
bl_label = "Add New Grid"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.add_new_grid(context)
return {'FINISHED'}
@staticmethod
def add_new_grid(context):
mat_list = context.scene.sprytile_mats
target_mat = None
if len(mat_list) > 0:
target_mat = mat_list[0]
grid_id = context.object.sprytile_gridid
target_grid = get_grid(context, grid_id)
if target_grid is not None:
for mat in mat_list:
if mat.mat_id == target_grid.mat_id:
target_mat = mat
break
if target_mat is None:
return
grid_idx = -1
for idx, grid in enumerate(mat.grids):
if grid.id == grid_id:
grid_idx = idx
break
new_idx = len(target_mat.grids)
new_grid = target_mat.grids.add()
new_grid.mat_id = target_mat.mat_id
new_grid.id = get_highest_grid_id(context) + 1
if grid_idx > -1:
new_grid.grid = target_mat.grids[grid_idx].grid
target_mat.grids.move(new_idx, grid_idx + 1)
bpy.ops.sprytile.build_grid_list()
class SprytileGridRemove(bpy.types.Operator):
bl_idname = "sprytile.grid_remove"
bl_label = "Remove Grid"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.delete_grid(context)
return {'FINISHED'}
@staticmethod
def delete_grid(context):
mat_list = context.scene.sprytile_mats
target_mat = None
if len(mat_list) > 0:
target_mat = mat_list[0]
grid_id = context.object.sprytile_gridid
target_grid = get_grid(context, grid_id)
if target_grid is not None:
for mat in mat_list:
if mat.mat_id == target_grid.mat_id:
target_mat = mat
break
if target_mat is None or len(target_mat.grids) <= 1:
return
grid_idx = -1
for idx, grid in enumerate(target_mat.grids):
if grid.id == grid_id:
grid_idx = idx
break
target_mat.grids.remove(grid_idx)
bpy.ops.sprytile.build_grid_list()
class SprytileGridCycle(bpy.types.Operator):
bl_idname = "sprytile.grid_cycle"
bl_label = "Cycle grid settings"
direction = bpy.props.IntProperty(default=1)
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.cycle_grid(context)
return {'FINISHED'}
def cycle_grid(self, context):
obj = context.object
curr_grid = get_grid(context, obj.sprytile_gridid)
if curr_grid is None:
return
curr_mat = get_mat_data(context, curr_grid.mat_id)
if curr_mat is None:
return
idx = -1
for grid in curr_mat.grids:
idx += 1
if grid.id == curr_grid.id:
break
idx += self.direction
if idx < 0:
idx = len(curr_mat.grids)-1
if idx >= len(curr_mat.grids):
idx = 0
obj.sprytile_gridid = curr_mat.grids[idx].id
bpy.ops.sprytile.build_grid_list()
class SprytileStartTool(bpy.types.Operator):
bl_idname = "sprytile.start_tool"
bl_label = "Start Sprytile Paint"
mode = bpy.props.IntProperty(default=3)
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
if self.mode is 0:
context.scene.sprytile_data.paint_mode = 'SET_NORMAL'
if self.mode is 1:
context.scene.sprytile_data.paint_mode = 'PAINT'
if self.mode is 2:
context.scene.sprytile_data.paint_mode = 'MAKE_FACE'
bpy.ops.sprytile.modal_tool('INVOKE_REGION_WIN')
return {'FINISHED'}
class SprytileGridMove(bpy.types.Operator):
bl_idname = "sprytile.grid_move"
bl_label = "Move Grid"
direction = bpy.props.IntProperty(default=1)
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.move_grid(context)
return {'FINISHED'}
def move_grid(self, context):
obj = context.object
curr_grid = get_grid(context, obj.sprytile_gridid)
if curr_grid is None:
return
curr_mat = get_mat_data(context, curr_grid.mat_id)
if curr_mat is None:
return
idx = -1
for grid in curr_mat.grids:
idx += 1
if grid.id == curr_grid.id:
break
old_idx = idx
idx = old_idx + self.direction
if idx < 0:
idx = len(curr_mat.grids)-1
if idx >= len(curr_mat.grids):
idx = 0
curr_mat.grids.move(old_idx, idx)
obj.sprytile_gridid = curr_mat.grids[idx].id
bpy.ops.sprytile.build_grid_list()
class SprytileNewMaterial(bpy.types.Operator):
bl_idname = "sprytile.add_new_material"
bl_label = "New Shadeless Material"
@classmethod
def poll(cls, context):
return context.object is not None
def invoke(self, context, event):
obj = context.object
mat = bpy.data.materials.new(name="Material")
set_idx = len(obj.data.materials)
obj.data.materials.append(mat)
obj.active_material_index = set_idx
bpy.ops.sprytile.material_setup()
bpy.ops.sprytile.validate_grids()
return {'FINISHED'}
class SprytileSetupMaterial(bpy.types.Operator):
bl_idname = "sprytile.material_setup"
bl_label = "Set Material to Shadeless"
@classmethod
def poll(cls, context):
return context.object is not None
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
mat = bpy.data.materials[context.object.active_material_index]
mat.use_shadeless = True
mat.use_transparency = True
mat.transparency_method = 'Z_TRANSPARENCY'
mat.alpha = 0.0
return {'FINISHED'}
class SprytileSetupTexture(bpy.types.Operator):
bl_idname = "sprytile.texture_setup"
bl_label = "Setup Pixel Texture"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.setup_tex(context)
return {'FINISHED'}
@staticmethod
def setup_tex(context):
""""""
material = bpy.data.materials[context.object.active_material_index]
target_texture = None
target_img = None
target_slot = None
for texture_slot in material.texture_slots:
if texture_slot is None:
continue
if texture_slot.texture is None:
continue
if texture_slot.texture.type == 'NONE':
continue
if texture_slot.texture.type == 'IMAGE':
# Cannot use the texture slot image reference directly
# Have to get it through bpy.data.images to be able to use with BGL
target_texture = bpy.data.textures.get(texture_slot.texture.name)
target_img = bpy.data.images.get(texture_slot.texture.image.name)
target_slot = texture_slot
break
if target_texture is None or target_img is None:
return
target_texture.use_preview_alpha = True
target_texture.use_alpha = True
target_texture.use_interpolation = False
target_texture.use_mipmap = False
target_texture.filter_type = 'BOX'
target_texture.filter_size = 0.10
target_img.use_alpha = True
target_slot.use_map_color_diffuse = True
target_slot.use_map_alpha = True
target_slot.alpha_factor = 1.0
target_slot.diffuse_color_factor = 1.0
class SprytileValidateGridList(bpy.types.Operator):
bl_idname = "sprytile.validate_grids"
bl_label = "Validate Material Grids"
@classmethod
def poll(cls, context):
return True
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.validate_grids(context)
return {'FINISHED'}
@staticmethod
def validate_grids(context):
mat_list = bpy.data.materials
mat_data_list = context.scene.sprytile_mats
# Validate the material IDs in scene.sprytile_mats
for check_mat_data in mat_data_list:
mat_idx = mat_list.find(check_mat_data.mat_id)
if mat_idx > -1:
continue
# This mat data id not found in materials
# Loop through materials looking for one
# that doesn't appear in sprytile_mats list
for check_mat in mat_list:
mat_unused = True
for mat_data in mat_data_list:
if mat_data.mat_id == check_mat.name:
mat_unused = False
break
if mat_unused:
target_mat_id = check_mat_data.mat_id
check_mat_data.mat_id = check_mat.name
for grid in check_mat_data.grids:
grid.mat_id = check_mat.name
for list_display in context.scene.sprytile_list.display:
if list_display.mat_id == target_mat_id:
list_display.mat_id = check_mat.name
break
remove_idx = []
# Filter out mat data with invalid IDs or users
for idx, mat in enumerate(mat_data_list.values()):
mat_idx = mat_list.find(mat.mat_id)
if mat_idx < 0:
remove_idx.append(idx)
continue
if mat_list[mat_idx].users == 0:
remove_idx.append(idx)
for grid in mat.grids:
grid.mat_id = mat.mat_id
remove_idx.reverse()
for idx in remove_idx:
mat_data_list.remove(idx)
# Loop through available materials, checking if mat_data_list has
# at least one entry for each material
for mat in mat_list:
if mat.users == 0:
continue
is_mat_valid = False
for mat_data in mat_data_list:
if mat_data.mat_id == mat.name:
is_mat_valid = True
break
if is_mat_valid is False:
mat_data_entry = mat_data_list.add()
mat_data_entry.mat_id = mat.name
mat_grid = mat_data_entry.grids.add()
mat_grid.mat_id = mat.name
mat_grid.id = get_highest_grid_id(context) + 1
context.object.sprytile_gridid = get_highest_grid_id(context)
bpy.ops.sprytile.build_grid_list()
class SprytileBuildGridList(bpy.types.Operator):
bl_idname = "sprytile.build_grid_list"
bl_label = "Sprytile Build Grid List"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.build_list(context)
return {'FINISHED'}
@staticmethod
def build_list(context):
"""Build the scene.sprytile_list.display from scene.sprytile_mats"""
display_list = context.scene.sprytile_list.display
mat_list = context.scene.sprytile_mats
display_list.clear()
for mat_data in mat_list:
mat_display = display_list.add()
mat_display.mat_id = mat_data.mat_id
if mat_data.is_expanded is False:
continue
for mat_grid in mat_data.grids:
idx = len(display_list)
grid_display = display_list.add()
grid_display.grid_id = mat_grid.id
if context.object.sprytile_gridid == grid_display.grid_id:
context.scene.sprytile_list.idx = idx
class SprytileRotateLeft(bpy.types.Operator):
bl_idname = "sprytile.rotate_left"
bl_label = "Rotate Sprytile Left"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
curr_rotation = context.scene.sprytile_data.mesh_rotate
curr_rotation += 1.5708
if curr_rotation > 6.28319:
curr_rotation = 0
context.scene.sprytile_data.mesh_rotate = curr_rotation
return {'FINISHED'}
class SprytileRotateRight(bpy.types.Operator):
bl_idname = "sprytile.rotate_right"
bl_label = "Rotate Sprytile Right"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
curr_rotation = context.scene.sprytile_data.mesh_rotate
curr_rotation -= 1.5708
if curr_rotation < -6.28319:
curr_rotation = 0
context.scene.sprytile_data.mesh_rotate = curr_rotation
return {'FINISHED'}
class SprytileReloadImages(bpy.types.Operator):
bl_idname = "sprytile.reload_imgs"
bl_label = "Reload All Images"
def invoke(self, context, event):
for img in bpy.data.images:
if img is None:
continue
img.reload()
for window in context.window_manager.windows:
for area in window.screen.areas:
if area.type in {'VIEW_3D', 'IMAGE_EDITOR'}:
area.tag_redraw()
return {'FINISHED'}
class SprytileReloadImagesAuto(bpy.types.Operator):
bl_idname = "sprytile.reload_auto"
bl_label = "Reload All Images (Auto)"
_timer = None
last_check_time = None
def modal(self, context, event):
if event.type == 'TIMER':
if context.scene.sprytile_data.auto_reload is False:
self.cancel(context)
return {'CANCELLED'}
if self.check_files():
for window in context.window_manager.windows:
for area in window.screen.areas:
if area.type in {'VIEW_3D', 'IMAGE_EDITOR'}:
area.tag_redraw()
return {'PASS_THROUGH'}
def check_files(self):
did_reload = False
for img in bpy.data.images:
if img is None:
continue
filepath = abspath(img.filepath)
filetime = datetime.fromtimestamp(path.getmtime(filepath))
if self.last_check_time is None or filetime > self.last_check_time:
print("Reloading", img.filepath)
img.reload()
did_reload = True
self.last_check_time = datetime.now()
return did_reload
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.check_files()
wm = context.window_manager
self._timer = wm.event_timer_add(2, context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
class SprytileUpdateCheck(bpy.types.Operator):
bl_idname = "sprytile.update_check"
bl_label = "Check for Update"
def invoke(self, context, event):
print("Check itch.io API")
import sys
print(sys.modules['sprytile'].bl_info.get('version', (-1, -1, -1)))
import urllib.request
import json
url = "https://itch.io/api/1/x/wharf/latest?game_id=98966&channel_name=addon"
response = urllib.request.urlopen(url)
data = response.read()
encoding = response.info().get_content_charset('utf-8')
json_data = json.loads(data.decode(encoding))
print(json_data)
return {'FINISHED'}
class SprytileMakeDoubleSided(bpy.types.Operator):
bl_idname = "sprytile.make_double_sided"
bl_label = "Make Double Sided (Sprytile)"
bl_description = "Duplicate selected faces and flip normals"
def execute(self, context):
self.invoke(context, None)
def invoke(self, context, event):
print("Invoked make double sided")
if context.object is None or (context.object.type != 'MESH' or context.object.mode != 'EDIT'):
print("Nope")
return {'FINISHED'}
mesh = bmesh.from_edit_mesh(context.object.data)
double_face = []
for face in mesh.faces:
if not face.select:
continue
double_face.append(face)
for face in double_face:
face.copy(True, True)
face.normal_flip()
face.normal_update()
mesh.faces.index_update()
mesh.faces.ensure_lookup_table()
bmesh.update_edit_mesh(context.object.data, True, True)
return {'FINISHED'}
class SprytileGridTranslate(bpy.types.Operator):
bl_idname = "sprytile.translate_grid"
bl_label = "Pixel Translate (Sprytile)"
@staticmethod
def draw_callback(self, context):
if self.exec_counter != -1 or self.ref_pos is None:
return None
check_pos = self.get_ref_pos(context)
measure_vec = check_pos - self.ref_pos
pixel_unit = 1 / context.scene.sprytile_data.world_pixels
for i in range(3):
measure_vec[i] = int(round(measure_vec[i] / pixel_unit))
screen_y = context.region.height - 45
screen_x = 20
padding = 5
font_id = 0
font_size = 16
blf.size(font_id, font_size, 72)
bgl.glColor4f(1, 1, 1, 1)
readout_axis = ['X', 'Y', 'Z']
for i in range(3):
blf.position(font_id, screen_x, screen_y, 0)
blf.draw(font_id, "%s : %d" % (readout_axis[i], measure_vec[i]))
screen_y -= font_size + padding
def modal(self, context, event):
# User cancelled transform
if event.type == 'ESC':
return self.exit_modal(context)
if event.type == 'RIGHTMOUSE' and event.value == 'RELEASE':
return self.exit_modal(context)
# On the timer events, count down the frames and execute the
# translate operator when reach 0
if event.type == 'TIMER':
if self.exec_counter > 0:
self.exec_counter -= 1
if self.exec_counter == 0:
self.exec_counter -= 1
up_vec, right_vec, norm_vec = get_current_grid_vectors(context.scene)
norm_vec = snap_vector_to_axis(norm_vec)
axis_constraint = [
abs(norm_vec.x) == 0,
abs(norm_vec.y) == 0,
abs(norm_vec.z) == 0
]
tool_value = bpy.ops.transform.translate(
'INVOKE_DEFAULT',
constraint_axis=axis_constraint,
snap=self.restore_settings is not None
)
# Translate tool moved nothing, exit
if 'CANCELLED' in tool_value:
return self.exit_modal(context)
# When the active operator changes, we know that translate has been completed
if context.active_operator != self.watch_operator:
return self.exit_modal(context)
return {'PASS_THROUGH'}
def get_ref_pos(self, context):
if context.object.mode != 'EDIT':
return None
if self.bmesh is None:
self.bmesh = bmesh.from_edit_mesh(context.object.data)
if len(self.bmesh.select_history) <= 0: