maths api changes
[carveJwlIkooP6JGAAIwe30JlM.git] / blender_export.py
1 import bpy, math, gpu, os
2 import cProfile
3 from ctypes import *
4 from mathutils import *
5 from gpu_extras.batch import batch_for_shader
6 from bpy_extras import mesh_utils
7
8 bl_info = {
9 "name":"Skaterift .mdl exporter",
10 "author": "Harry Godden (hgn)",
11 "version": (0,2),
12 "blender":(3,1,0),
13 "location":"Export",
14 "description":"",
15 "warning":"",
16 "wiki_url":"",
17 "category":"Import/Export",
18 }
19
20 sr_entity_list = [
21 ('none', 'None', '', 0 ),
22 ('ent_gate', 'Gate', '', 1 ),
23 ('ent_spawn', 'Spawn Point', '', 2 ),
24 ('ent_route_node', 'Routing Path', '', 3 ),
25 ('ent_route', 'Skate Course', '', 4 ),
26 ('ent_water', 'Water Surface', '', 5 ),
27 ('ent_volume', 'Volume/Trigger', '', 6 ),
28 ('ent_audio', 'Audio', '', 7 ),
29 ('ent_marker', 'Marker', '', 8 ),
30 ('ent_font', 'Font', '', 9 ),
31 ('ent_font_variant', 'Font:Variant', '', 10 ),
32 ('ent_traffic', 'Traffic Model', '', 11 ),
33 ('ent_skateshop', 'Skate Shop', '', 12 ),
34 ('ent_camera', 'Camera', '', 13 ),
35 ('ent_swspreview', 'Workshop Preview', '', 14 ),
36 ('ent_menuitem', 'Menu Item', '', 15 )
37 ]
38
39 def get_entity_enum_id( alias ):
40 #{
41 for et in sr_entity_list:#{
42 if et[0] == alias:#{
43 return et[3]
44 #}
45 #}
46
47 return 0
48 #}
49
50 class mdl_vert(Structure): # 48 bytes. Quite large. Could compress
51 #{ # the normals and uvs to i16s. Not an
52 _pack_ = 1 # real issue, yet.
53 _fields_ = [("co",c_float*3),
54 ("norm",c_float*3),
55 ("uv",c_float*2),
56 ("colour",c_uint8*4),
57 ("weights",c_uint16*4),
58 ("groups",c_uint8*4)]
59 #}
60
61 class mdl_transform(Structure):
62 #{
63 _fields_ = [("co",c_float*3),
64 ( "s",c_float*3),
65 ( "q",c_float*4)]
66 #}
67
68 class mdl_submesh(Structure):
69 #{
70 _fields_ = [("indice_start",c_uint32),
71 ("indice_count",c_uint32),
72 ("vertex_start",c_uint32),
73 ("vertex_count",c_uint32),
74 ("bbx",(c_float*3)*2),
75 ("material_id",c_uint16), # index into the material array
76 ("flags",c_uint16)]
77 #}
78
79 class mdl_material(Structure):
80 #{
81 _fields_ = [("pstr_name",c_uint32),
82 ("shader",c_uint32),
83 ("flags",c_uint32),
84 ("surface_prop",c_uint32),
85 ("colour",c_float*4),
86 ("colour1",c_float*4),
87 ("tex_diffuse",c_uint32),
88 ("tex_none0",c_uint32),
89 ("tex_none1",c_uint32)]
90 #}
91
92 class mdl_bone(Structure):
93 #{
94 _fields_ = [("co",c_float*3),("end",c_float*3),
95 ("parent",c_uint32),
96 ("collider",c_uint32),
97 ("ik_target",c_uint32),
98 ("ik_pole",c_uint32),
99 ("flags",c_uint32),
100 ("pstr_name",c_uint32),
101 ("hitbox",(c_float*3)*2),
102 ("conevx",c_float*3),("conevy",c_float*3),("coneva",c_float*3),
103 ("conet",c_float)]
104 #}
105
106 class mdl_armature(Structure):
107 #{
108 _fields_ = [("transform",mdl_transform),
109 ("bone_start",c_uint32),
110 ("bone_count",c_uint32),
111 ("anim_start",c_uint32),
112 ("anim_count",c_uint32)]
113 #}
114
115 class mdl_animation(Structure):
116 #{
117 _fields_ = [("pstr_name",c_uint32),
118 ("length",c_uint32),
119 ("rate",c_float),
120 ("keyframe_start",c_uint32)]
121 #}
122
123 class mdl_mesh(Structure):
124 #{
125 _fields_ = [("transform",mdl_transform),
126 ("submesh_start",c_uint32),
127 ("submesh_count",c_uint32),
128 ("pstr_name",c_uint32),
129 ("entity_id",c_uint32),
130 ("armature_id",c_uint32)]
131 #}
132
133 class mdl_file(Structure):
134 #{
135 _fields_ = [("path",c_uint32),
136 ("pack_offset",c_uint32),
137 ("pack_size",c_uint32)]
138 #}
139
140 class mdl_texture(Structure):
141 #{
142 _fields_ = [("file",mdl_file),
143 ("glname",c_uint32)]
144 #}
145
146 class mdl_array(Structure):
147 #{
148 _fields_ = [("file_offset",c_uint32),
149 ("item_count",c_uint32),
150 ("item_size",c_uint32),
151 ("name",c_byte*16)]
152 #}
153
154 class mdl_header(Structure):
155 #{
156 _fields_ = [("version",c_uint32),
157 ("arrays",mdl_array)]
158 #}
159
160 class ent_spawn(Structure):
161 #{
162 _fields_ = [("transform",mdl_transform),
163 ("pstr_name",c_uint32)]
164 #}
165
166 class ent_light(Structure):
167 #{
168 _fields_ = [("transform",mdl_transform),
169 ("daytime",c_uint32),
170 ("type",c_uint32),
171 ("colour",c_float*4),
172 ("angle",c_float),
173 ("range",c_float),
174 ("inverse_world",(c_float*3)*4), # Runtime
175 ("angle_sin_cos",(c_float*2))] # Runtime
176 #}
177
178 class version_refcount_union(Union):
179 #{
180 _fields_ = [("timing_version",c_uint32),
181 ("ref_count",c_uint8)]
182 #}
183
184 class ent_gate(Structure):
185 #{
186 _fields_ = [("type",c_uint32),
187 ("target", c_uint32),
188 ("dimensions", c_float*3),
189 ("co", (c_float*3)*2),
190 ("q", (c_float*4)*2),
191 ("to_world",(c_float*3)*4),
192 ("transport",(c_float*3)*4),
193 ("_anonymous_union",version_refcount_union),
194 ("timing_time",c_double),
195 ("routes",c_uint16*4),
196 ("route_count",c_uint8)]
197 #}
198
199 class ent_route_node(Structure):
200 #{
201 _fields_ = [("co",c_float*3),
202 ("ref_count",c_uint8),
203 ("ref_total",c_uint8)]
204 #}
205
206 class ent_path_index(Structure):
207 #{
208 _fields_ = [("index",c_uint16)]
209 #}
210
211 class vg_audio_clip(Structure):
212 #{
213 _fields_ = [("path",c_uint64),
214 ("flags",c_uint32),
215 ("size",c_uint32),
216 ("data",c_uint64)]
217 #}
218
219 class union_file_audio_clip(Union):
220 #{
221 _fields_ = [("file",mdl_file),
222 ("reserved",vg_audio_clip)]
223 #}
224
225 class ent_audio_clip(Structure):
226 #{
227 _fields_ = [("_anon",union_file_audio_clip),
228 ("probability",c_float)]
229 #}
230
231 class ent_checkpoint(Structure):
232 #{
233 _fields_ = [("gate_index",c_uint16),
234 ("path_start",c_uint16),
235 ("path_count",c_uint16)]
236 #}
237
238 class ent_route(Structure):
239 #{
240 _fields_ = [("transform",mdl_transform),
241 ("pstr_name",c_uint32),
242 ("checkpoints_start",c_uint16),
243 ("checkpoints_count",c_uint16),
244 ("colour",c_float*4),
245 ("active",c_uint32), #runtime
246 ("factive",c_float),
247 ("board_transform",(c_float*3)*4),
248 ("sm",mdl_submesh),
249 ("latest_pass",c_double)]
250 #}
251
252 class ent_water(Structure):
253 #{
254 _fields_ = [("transform",mdl_transform),
255 ("max_dist",c_float),
256 ("reserved0",c_uint32),
257 ("reserved1",c_uint32)]
258 #}
259
260 class volume_trigger(Structure):
261 #{
262 _fields_ = [("event",c_uint32),
263 ("blank",c_uint32)]
264 #}
265
266 class volume_particles(Structure):
267 #{
268 _fields_ = [("blank",c_uint32),
269 ("blank2",c_uint32)]
270 #}
271
272 class volume_union(Union):
273 #{
274 _fields_ = [("trigger",volume_trigger),
275 ("particles",volume_particles)]
276 #}
277
278 class ent_volume(Structure):
279 #{
280 _fields_ = [("transform",mdl_transform),
281 ("to_world",(c_float*3)*4),
282 ("to_local",(c_float*3)*4),
283 ("type",c_uint32),
284 ("target",c_uint32),
285 ("_anon",volume_union)]
286 #}
287
288 class ent_audio(Structure):
289 #{
290 _fields_ = [("transform",mdl_transform),
291 ("flags",c_uint32),
292 ("clip_start",c_uint32),
293 ("clip_count",c_uint32),
294 ("volume",c_float),
295 ("crossfade",c_float),
296 ("channel_behaviour",c_uint32),
297 ("group",c_uint32),
298 ("probability_curve",c_uint32),
299 ("max_channels",c_uint32)]
300 #}
301
302 class ent_marker(Structure):
303 #{
304 _fields_ = [("transform",mdl_transform),
305 ("name",c_uint32)]
306 #}
307
308 class ent_glyph(Structure):
309 #{
310 _fields_ = [("size",c_float*2),
311 ("indice_start",c_uint32),
312 ("indice_count",c_uint32)]
313 #}
314
315 class ent_font_variant(Structure):
316 #{
317 _fields_ = [("name",c_uint32),
318 ("material_id",c_uint32)]
319 #}
320
321 class ent_font(Structure):
322 #{
323 _fields_ = [("alias",c_uint32),
324 ("variant_start",c_uint32),
325 ("variant_count",c_uint32),
326 ("glyph_start",c_uint32),
327 ("glyph_count",c_uint32),
328 ("glyph_utf32_base",c_uint32)]
329 #}
330
331 class ent_traffic(Structure):
332 #{
333 _fields_ = [("transform",mdl_transform),
334 ("submesh_start",c_uint32),
335 ("submesh_count",c_uint32),
336 ("start_node",c_uint32),
337 ("node_count",c_uint32),
338 ("speed",c_float),
339 ("t",c_float),
340 ("index",c_uint32)]
341 #}
342
343 # Skateshop
344 # ---------------------------------------------------------------
345 class ent_skateshop_characters(Structure):
346 #{
347 _fields_ = [("id_display",c_uint32),
348 ("id_info",c_uint32)]
349 #}
350 class ent_skateshop_boards(Structure):
351 #{
352 _fields_ = [("id_display",c_uint32),
353 ("id_info",c_uint32),
354 ("id_rack",c_uint32)]
355 #}
356 class ent_skateshop_anon_union(Union):
357 #{
358 _fields_ = [("boards",ent_skateshop_boards),
359 ("character",ent_skateshop_characters)]
360 #}
361 class ent_skateshop(Structure):
362 #{
363 _fields_ = [("transform",mdl_transform), ("type",c_uint32),
364 ("id_camera",c_uint32),
365 ("_anonymous_union",ent_skateshop_anon_union)]
366 #}
367
368 class ent_swspreview(Structure):
369 #{
370 _fields_ = [("id_camera",c_uint32),
371 ("id_display",c_uint32),
372 ("id_display1",c_uint32)]
373 #}
374
375 # Menu
376 # -----------------------------------------------------------------
377 class ent_menuitem_slider(Structure):
378 #{
379 _fields_ = [("id_min",c_uint32),
380 ("id_max",c_uint32),
381 ("id_handle",c_uint32),
382 ("pstr_data",c_uint32)]
383 #}
384 class ent_menuitem_button(Structure):
385 #{
386 _fields_ = [("pstr",c_uint32)]
387 #}
388 class ent_menuitem_checkmark(Structure):
389 #{
390 _fields_ = [("id_check",c_uint32),
391 ("pstr_data",c_uint32),
392 ("offset",c_float*3)]
393 #}
394 class ent_menuitem_page(Structure):
395 #{
396 _fields_ = [("pstr_name",c_uint32),
397 ("id_entrypoint",c_uint32),
398 ("id_viewpoint",c_uint32)]
399 #}
400 class ent_menuitem_anon_union(Union):
401 #{
402 _fields_ = [("slider",ent_menuitem_slider),
403 ("button",ent_menuitem_button),
404 ("checkmark",ent_menuitem_checkmark),
405 ("page",ent_menuitem_page)]
406 #}
407 class ent_menuitem(Structure):
408 #{
409 _fields_ = [("type",c_uint32), ("groups",c_uint32),
410 ("id_links",c_uint32*4),
411 ("factive",c_float), ("fvisible",c_float),
412 #-- TODO: Refactor this into a simple mesh structure
413 ("transform",mdl_transform),
414 ("submesh_start",c_uint32),("submesh_count",c_uint32),
415 ("_u64",c_uint64),
416 #-- end
417 ("_anonymous_union", ent_menuitem_anon_union)]
418 #}
419
420 class ent_camera(Structure):
421 #{
422 _fields_ = [("transform",mdl_transform),
423 ("fov",c_float)]
424 #}
425
426 def obj_ent_type( obj ):
427 #{
428 if obj.type == 'ARMATURE': return 'mdl_armature'
429 elif obj.type == 'LIGHT': return 'ent_light'
430 elif obj.type == 'CAMERA': return 'ent_camera'
431 else: return obj.SR_data.ent_type
432 #}
433
434 def sr_filter_ent_type( obj, ent_types ):
435 #{
436 if obj == bpy.context.active_object: return False
437
438 for c0 in obj.users_collection:#{
439 for c1 in bpy.context.active_object.users_collection:#{
440 if c0 == c1:#{
441 return obj_ent_type( obj ) in ent_types
442 #}
443 #}
444 #}
445
446 return False
447 #}
448
449 def compile_obj_transform( obj, transform ):
450 #{
451 co = obj.matrix_world @ Vector((0,0,0))
452
453 # This was changed from matrix_local on 09.05.23
454 q = obj.matrix_world.to_quaternion()
455 s = obj.scale
456
457 # Setup transform
458 #
459 transform.co[0] = co[0]
460 transform.co[1] = co[2]
461 transform.co[2] = -co[1]
462 transform.q[0] = q[1]
463 transform.q[1] = q[3]
464 transform.q[2] = -q[2]
465 transform.q[3] = q[0]
466 transform.s[0] = s[0]
467 transform.s[1] = s[2]
468 transform.s[2] = s[1]
469 #}
470
471 def int_align_to( v, align ):
472 #{
473 while(v%align)!=0: v += 1
474 return v
475 #}
476
477 def bytearray_align_to( buffer, align, w=b'\xaa' ):
478 #{
479 while (len(buffer) % align) != 0: buffer.extend(w)
480 return buffer
481 #}
482
483 def bytearray_print_hex( s, w=16 ):
484 #{
485 for r in range((len(s)+(w-1))//w):#{
486 i0=(r+0)*w
487 i1=min((r+1)*w,len(s))
488 print( F'{r*w:06x}| \x1B[31m', end='')
489 print( F"{' '.join('{:02x}'.format(x) for x in s[i0:i1]):<48}",end='' )
490 print( "\x1B[0m", end='')
491 print( ''.join(chr(x) if (x>=33 and x<=126) else '.' for x in s[i0:i1] ) )
492 #}
493 #}
494
495 def sr_compile_string( s ):
496 #{
497 if s in sr_compile.string_cache: return sr_compile.string_cache[s]
498
499 index = len( sr_compile.string_data )
500 sr_compile.string_cache[s] = index
501 sr_compile.string_data.extend( c_uint32(hash_djb2(s)) )
502 sr_compile.string_data.extend( s.encode('utf-8') )
503 sr_compile.string_data.extend( b'\0' )
504
505 bytearray_align_to( sr_compile.string_data, 4 )
506 return index
507 #}
508
509 def material_tex_image(v):
510 #{
511 return {
512 "Image Texture":
513 {
514 "image": F"{v}"
515 }
516 }
517 #}
518
519 cxr_graph_mapping = \
520 {
521 # Default shader setup
522 "Principled BSDF":
523 {
524 "Base Color":
525 {
526 "Image Texture":
527 {
528 "image": "tex_diffuse"
529 },
530 "Mix":
531 {
532 "A": material_tex_image("tex_diffuse"),
533 "B": material_tex_image("tex_decal")
534 },
535 },
536 "Normal":
537 {
538 "Normal Map":
539 {
540 "Color": material_tex_image("tex_normal")
541 }
542 }
543 },
544 "Emission":
545 {
546 "Color": material_tex_image("tex_diffuse")
547 }
548 }
549
550 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
551 #
552 def material_info(mat):
553 #{
554 info = {}
555
556 # Using the cxr_graph_mapping as a reference, go through the shader
557 # graph and gather all $props from it.
558 #
559 def _graph_read( node_def, node=None, depth=0 ):#{
560 nonlocal mat
561 nonlocal info
562
563 # Find rootnodes
564 #
565 if node == None:#{
566 _graph_read.extracted = []
567
568 for node_idname in node_def:#{
569 for n in mat.node_tree.nodes:#{
570 if n.name == node_idname:#{
571 node_def = node_def[node_idname]
572 node = n
573 break
574 #}
575 #}
576 #}
577 #}
578
579 for link in node_def:#{
580 link_def = node_def[link]
581
582 if isinstance( link_def, dict ):#{
583 node_link = None
584 for x in node.inputs:#{
585 if isinstance( x, bpy.types.NodeSocketColor ):#{
586 if link == x.name:#{
587 node_link = x
588 break
589 #}
590 #}
591 #}
592
593 if node_link and node_link.is_linked:#{
594 # look for definitions for the connected node type
595 #
596 from_node = node_link.links[0].from_node
597
598 node_name = from_node.name.split('.')[0]
599 if node_name in link_def:#{
600 from_node_def = link_def[ node_name ]
601
602 _graph_read( from_node_def, from_node, depth+1 )
603 #}
604 #}
605 else:#{
606 if "default" in link_def:#{
607 prop = link_def['default']
608 info[prop] = node_link.default_value
609 #}
610 #}
611 #}
612 else:#{
613 prop = link_def
614 info[prop] = getattr( node, link )
615 #}
616 #}
617 #}
618
619 _graph_read( cxr_graph_mapping )
620 return info
621 #}
622
623 def vg_str_bin( s ):
624 #{
625 decoded = bytearray()
626 for i in range(len(s)//2):#{
627 c = (ord(s[i*2+0])-0x41)
628 c |= (ord(s[i*2+1])-0x41)<<4
629 decoded.extend(bytearray(c_uint8(c))) #??
630 #}
631 return decoded
632 #}
633
634 def sr_pack_file( file, path, data ):
635 #{
636 file.path = sr_compile_string( path )
637 file.pack_offset = len( sr_compile.pack_data )
638 file.pack_size = len( data )
639
640 sr_compile.pack_data.extend( data )
641 bytearray_align_to( sr_compile.pack_data, 16 )
642 #}
643
644 def sr_compile_texture( img ):
645 #{
646 if img == None:
647 return 0
648
649 name = os.path.splitext( img.name )[0]
650
651 if name in sr_compile.texture_cache:
652 return sr_compile.texture_cache[name]
653
654 texture_index = (len(sr_compile.texture_data)//sizeof(mdl_texture)) +1
655
656 tex = mdl_texture()
657 tex.glname = 0
658
659 if sr_compile.pack_textures:#{
660 filedata = qoi_encode( img )
661 sr_pack_file( tex.file, name, filedata )
662 #}
663
664 sr_compile.texture_cache[name] = texture_index
665 sr_compile.texture_data.extend( bytearray(tex) )
666 return texture_index
667 #}
668
669 def sr_compile_material( mat ):
670 #{
671 if mat == None:
672 return 0
673 if mat.name in sr_compile.material_cache:
674 return sr_compile.material_cache[mat.name]
675
676 index = (len(sr_compile.material_data)//sizeof(mdl_material))+1
677 sr_compile.material_cache[mat.name] = index
678
679 m = mdl_material()
680 m.pstr_name = sr_compile_string( mat.name )
681
682 flags = 0x00
683 if mat.SR_data.collision:#{
684 flags |= 0x2 # collision flag
685 if (mat.SR_data.shader != 'invisible') and \
686 (mat.SR_data.shader != 'boundary'):#{
687 if mat.SR_data.skate_surface: flags |= 0x1
688 if mat.SR_data.grow_grass: flags |= 0x4
689 if mat.SR_data.grind_surface: flags |= 0x8
690 #}
691 if mat.SR_data.shader == 'invisible': flags |= 0x10
692 if mat.SR_data.shader == 'boundary': flags |= (0x10|0x20)
693 #}
694
695 m.flags = flags
696
697 m.surface_prop = int(mat.SR_data.surface_prop)
698
699 if mat.SR_data.shader == 'standard': m.shader = 0
700 if mat.SR_data.shader == 'standard_cutout': m.shader = 1
701 if mat.SR_data.shader == 'terrain_blend':#{
702 m.shader = 2
703
704 m.colour[0] = pow( mat.SR_data.sand_colour[0], 1.0/2.2 )
705 m.colour[1] = pow( mat.SR_data.sand_colour[1], 1.0/2.2 )
706 m.colour[2] = pow( mat.SR_data.sand_colour[2], 1.0/2.2 )
707 m.colour[3] = 1.0
708
709 m.colour1[0] = mat.SR_data.blend_offset[0]
710 m.colour1[1] = mat.SR_data.blend_offset[1]
711 #}
712
713 if mat.SR_data.shader == 'vertex_blend':#{
714 m.shader = 3
715
716 m.colour1[0] = mat.SR_data.blend_offset[0]
717 m.colour1[1] = mat.SR_data.blend_offset[1]
718 #}
719
720 if mat.SR_data.shader == 'water':#{
721 m.shader = 4
722
723 m.colour[0] = pow( mat.SR_data.shore_colour[0], 1.0/2.2 )
724 m.colour[1] = pow( mat.SR_data.shore_colour[1], 1.0/2.2 )
725 m.colour[2] = pow( mat.SR_data.shore_colour[2], 1.0/2.2 )
726 m.colour[3] = 1.0
727 m.colour1[0] = pow( mat.SR_data.ocean_colour[0], 1.0/2.2 )
728 m.colour1[1] = pow( mat.SR_data.ocean_colour[1], 1.0/2.2 )
729 m.colour1[2] = pow( mat.SR_data.ocean_colour[2], 1.0/2.2 )
730 m.colour1[3] = 1.0
731 #}
732
733 if mat.SR_data.shader == 'invisible':#{
734 m.shader = 5
735 #}
736
737 if mat.SR_data.shader == 'boundary':#{
738 m.shader = 6
739 #}
740
741 inf = material_info( mat )
742
743 if mat.SR_data.shader == 'standard' or \
744 mat.SR_data.shader == 'standard_cutout' or \
745 mat.SR_data.shader == 'terrain_blend' or \
746 mat.SR_data.shader == 'vertex_blend':
747 #{
748 if 'tex_diffuse' in inf:
749 m.tex_diffuse = sr_compile_texture(inf['tex_diffuse'])
750 #}
751
752 sr_compile.material_data.extend( bytearray(m) )
753 return index
754 #}
755
756 def sr_armature_bones( armature ):
757 #{
758 def _recurse_bone( b ):
759 #{
760 yield b
761 for c in b.children: yield from _recurse_bone( c )
762 #}
763
764 for b in armature.data.bones:
765 if not b.parent:
766 yield from _recurse_bone( b )
767 #}
768
769 def sr_entity_id( obj ):
770 #{
771 tipo = get_entity_enum_id( obj_ent_type(obj) )
772 index = sr_compile.entity_ids[ obj.name ]
773
774 return (tipo&0xffff)<<16 | (index&0xffff)
775 #}
776
777 # Returns submesh_start,count and armature_id
778 def sr_compile_mesh_internal( obj ):
779 #{
780 can_use_cache = True
781 armature = None
782
783 submesh_start = 0
784 submesh_count = 0
785 armature_id = 0
786
787 for mod in obj.modifiers:#{
788 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
789 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
790 mod.type == 'ARRAY':
791 #{
792 can_use_cache = False
793 #}
794
795 if mod.type == 'ARMATURE': #{
796 armature = mod.object
797 rig_weight_groups = \
798 ['0 [ROOT]']+[_.name for _ in sr_armature_bones(mod.object)]
799 armature_id = sr_compile.entity_ids[armature.name]
800
801 POSE_OR_REST_CACHE = armature.data.pose_position
802 armature.data.pose_position = 'REST'
803 #}
804 #}
805
806 # Check the cache first
807 #
808 if can_use_cache and (obj.data.name in sr_compile.mesh_cache):#{
809 ref = sr_compile.mesh_cache[obj.data.name]
810 submesh_start = ref[0]
811 submesh_count = ref[1]
812 return (submesh_start,submesh_count,armature_id)
813 #}
814
815 # Compile a whole new mesh
816 #
817 submesh_start = len(sr_compile.submesh_data)//sizeof(mdl_submesh)
818 submesh_count = 0
819
820 dgraph = bpy.context.evaluated_depsgraph_get()
821 data = obj.evaluated_get(dgraph).data
822 data.calc_loop_triangles()
823 data.calc_normals_split()
824
825 # Mesh is split into submeshes based on their material
826 #
827 mat_list = data.materials if len(data.materials) > 0 else [None]
828 for material_id, mat in enumerate(mat_list): #{
829 mref = {}
830
831 sm = mdl_submesh()
832 sm.indice_start = len(sr_compile.indice_data)//sizeof(c_uint32)
833 sm.vertex_start = len(sr_compile.vertex_data)//sizeof(mdl_vert)
834 sm.vertex_count = 0
835 sm.indice_count = 0
836 sm.material_id = sr_compile_material( mat )
837
838 INF=99999999.99999999
839 for i in range(3):#{
840 sm.bbx[0][i] = INF
841 sm.bbx[1][i] = -INF
842 #}
843
844 # Keep a reference to very very very similar vertices
845 # i have no idea how to speed it up.
846 #
847 vertex_reference = {}
848
849 # Write the vertex / indice data
850 #
851 for tri_index, tri in enumerate(data.loop_triangles):#{
852 if tri.material_index != material_id: continue
853
854 for j in range(3):#{
855 vert = data.vertices[tri.vertices[j]]
856 li = tri.loops[j]
857 vi = data.loops[li].vertex_index
858
859 # Gather vertex information
860 #
861 co = vert.co
862 norm = data.loops[li].normal
863 uv = (0,0)
864 colour = (255,255,255,255)
865 groups = [0,0,0,0]
866 weights = [0,0,0,0]
867
868 # Uvs
869 #
870 if data.uv_layers:
871 uv = data.uv_layers.active.data[li].uv
872
873 # Vertex Colours
874 #
875 if data.vertex_colors:#{
876 colour = data.vertex_colors.active.data[li].color
877 colour = (int(colour[0]*255.0),\
878 int(colour[1]*255.0),\
879 int(colour[2]*255.0),\
880 int(colour[3]*255.0))
881 #}
882
883 # Weight groups: truncates to the 3 with the most influence. The
884 # fourth bone ID is never used by the shader so it
885 # is always 0
886 #
887 if armature:#{
888 src_groups = [_ for _ in data.vertices[vi].groups \
889 if obj.vertex_groups[_.group].name in \
890 rig_weight_groups ]
891
892 weight_groups = sorted( src_groups, key = \
893 lambda a: a.weight, reverse=True )
894 tot = 0.0
895 for ml in range(3):#{
896 if len(weight_groups) > ml:#{
897 g = weight_groups[ml]
898 name = obj.vertex_groups[g.group].name
899 weight = g.weight
900 weights[ml] = weight
901 groups[ml] = rig_weight_groups.index(name)
902 tot += weight
903 #}
904 #}
905
906 if len(weight_groups) > 0:#{
907 inv_norm = (1.0/tot) * 65535.0
908 for ml in range(3):#{
909 weights[ml] = int( weights[ml] * inv_norm )
910 weights[ml] = min( weights[ml], 65535 )
911 weights[ml] = max( weights[ml], 0 )
912 #}
913 #}
914 #}
915 else:#{
916 li1 = tri.loops[(j+1)%3]
917 vi1 = data.loops[li1].vertex_index
918 e0 = data.edges[ data.loops[li].edge_index ]
919
920 if e0.use_freestyle_mark and \
921 ((e0.vertices[0] == vi and e0.vertices[1] == vi1) or \
922 (e0.vertices[0] == vi1 and e0.vertices[1] == vi)):
923 #{
924 weights[0] = 1
925 #}
926 #}
927
928 TOLERENCE = float(10**4)
929 key = (int(co[0]*TOLERENCE+0.5),
930 int(co[1]*TOLERENCE+0.5),
931 int(co[2]*TOLERENCE+0.5),
932 int(norm[0]*TOLERENCE+0.5),
933 int(norm[1]*TOLERENCE+0.5),
934 int(norm[2]*TOLERENCE+0.5),
935 int(uv[0]*TOLERENCE+0.5),
936 int(uv[1]*TOLERENCE+0.5),
937 colour[0], # these guys are already quantized
938 colour[1], # .
939 colour[2], # .
940 colour[3], # .
941 weights[0], # v
942 weights[1],
943 weights[2],
944 weights[3],
945 groups[0],
946 groups[1],
947 groups[2],
948 groups[3])
949
950 if key in vertex_reference:
951 index = vertex_reference[key]
952 else:#{
953 index = bytearray(c_uint32(sm.vertex_count))
954 sm.vertex_count+=1
955
956 vertex_reference[key] = index
957 v = mdl_vert()
958 v.co[0] = co[0]
959 v.co[1] = co[2]
960 v.co[2] = -co[1]
961 v.norm[0] = norm[0]
962 v.norm[1] = norm[2]
963 v.norm[2] = -norm[1]
964 v.uv[0] = uv[0]
965 v.uv[1] = uv[1]
966 v.colour[0] = colour[0]
967 v.colour[1] = colour[1]
968 v.colour[2] = colour[2]
969 v.colour[3] = colour[3]
970 v.weights[0] = weights[0]
971 v.weights[1] = weights[1]
972 v.weights[2] = weights[2]
973 v.weights[3] = weights[3]
974 v.groups[0] = groups[0]
975 v.groups[1] = groups[1]
976 v.groups[2] = groups[2]
977 v.groups[3] = groups[3]
978
979 for i in range(3):#{
980 sm.bbx[0][i] = min( sm.bbx[0][i], v.co[i] )
981 sm.bbx[1][i] = max( sm.bbx[1][i], v.co[i] )
982 #}
983
984 sr_compile.vertex_data.extend(bytearray(v))
985 #}
986
987 sm.indice_count += 1
988 sr_compile.indice_data.extend( index )
989 #}
990 #}
991
992 # Make sure bounding box isn't -inf -> inf if no vertices
993 #
994 if sm.vertex_count == 0:
995 for j in range(2):
996 for i in range(3):
997 sm.bbx[j][i] = 0
998
999 # Add submesh to encoder
1000 #
1001 sr_compile.submesh_data.extend( bytearray(sm) )
1002 submesh_count += 1
1003 #}
1004
1005 if armature:#{
1006 armature.data.pose_position = POSE_OR_REST_CACHE
1007 #}
1008
1009 # Save a reference to this mesh since we want to reuse the submesh indices
1010 # later.
1011 sr_compile.mesh_cache[obj.data.name]=(submesh_start,submesh_count)
1012 return (submesh_start,submesh_count,armature_id)
1013 #}
1014
1015 def sr_compile_mesh( obj ):
1016 #{
1017 node=mdl_mesh()
1018 compile_obj_transform(obj, node.transform)
1019 node.pstr_name = sr_compile_string(obj.name)
1020 ent_type = obj_ent_type( obj )
1021
1022 node.entity_id = 0
1023
1024 if ent_type != 'none':#{
1025 ent_id_lwr = sr_compile.entity_ids[obj.name]
1026 ent_id_upr = get_entity_enum_id( obj_ent_type(obj) )
1027 node.entity_id = (ent_id_upr << 16) | ent_id_lwr
1028 #}
1029
1030 node.submesh_start, node.submesh_count, node.armature_id = \
1031 sr_compile_mesh_internal( obj )
1032
1033 sr_compile.mesh_data.extend(bytearray(node))
1034 #}
1035
1036 def sr_compile_fonts( collection ):
1037 #{
1038 print( F"[SR] Compiling fonts" )
1039
1040 glyph_count = 0
1041 variant_count = 0
1042
1043 for obj in collection.all_objects:#{
1044 if obj_ent_type(obj) != 'ent_font': continue
1045
1046 data = obj.SR_data.ent_font[0]
1047
1048 font=ent_font()
1049 font.alias = sr_compile_string( data.alias )
1050 font.variant_start = variant_count
1051 font.variant_count = 0
1052 font.glyph_start = glyph_count
1053
1054 glyph_base = data.glyphs[0].utf32
1055 glyph_range = data.glyphs[-1].utf32+1 - glyph_base
1056
1057 font.glyph_utf32_base = glyph_base
1058 font.glyph_count = glyph_range
1059
1060 for i in range(len(data.variants)):#{
1061 data_var = data.variants[i]
1062 if not data_var.mesh: continue
1063
1064 mesh = data_var.mesh.data
1065
1066 variant = ent_font_variant()
1067 variant.name = sr_compile_string( data_var.tipo )
1068
1069 # fonts (variants) only support one material each
1070 mat = None
1071 if len(mesh.materials) != 0:
1072 mat = mesh.materials[0]
1073 variant.material_id = sr_compile_material( mat )
1074
1075 font.variant_count += 1
1076
1077 islands = mesh_utils.mesh_linked_triangles(mesh)
1078 centroids = [Vector((0,0)) for _ in range(len(islands))]
1079
1080 for j in range(len(islands)):#{
1081 for tri in islands[j]:#{
1082 centroids[j].x += tri.center[0]
1083 centroids[j].y += tri.center[2]
1084 #}
1085
1086 centroids[j] /= len(islands[j])
1087 #}
1088
1089 for j in range(glyph_range):#{
1090 data_glyph = data.glyphs[j]
1091 glyph = ent_glyph()
1092 glyph.indice_start = len(sr_compile.indice_data)//sizeof(c_uint32)
1093 glyph.indice_count = 0
1094 glyph.size[0] = data_glyph.bounds[2]
1095 glyph.size[1] = data_glyph.bounds[3]
1096
1097 vertex_reference = {}
1098
1099 for k in range(len(islands)):#{
1100 if centroids[k].x < data_glyph.bounds[0] or \
1101 centroids[k].x > data_glyph.bounds[0]+data_glyph.bounds[2] or\
1102 centroids[k].y < data_glyph.bounds[1] or \
1103 centroids[k].y > data_glyph.bounds[1]+data_glyph.bounds[3]:
1104 #{
1105 continue
1106 #}
1107
1108 for l in range(len(islands[k])):#{
1109 tri = islands[k][l]
1110 for m in range(3):#{
1111 vert = mesh.vertices[tri.vertices[m]]
1112 li = tri.loops[m]
1113 vi = mesh.loops[li].vertex_index
1114
1115 # Gather vertex information
1116 #
1117 co = [vert.co[_] for _ in range(3)]
1118 co[0] -= data_glyph.bounds[0]
1119 co[2] -= data_glyph.bounds[1]
1120 norm = mesh.loops[li].normal
1121 uv = (0,0)
1122 if mesh.uv_layers: uv = mesh.uv_layers.active.data[li].uv
1123
1124 TOLERENCE = float(10**4)
1125 key = (int(co[0]*TOLERENCE+0.5),
1126 int(co[1]*TOLERENCE+0.5),
1127 int(co[2]*TOLERENCE+0.5),
1128 int(norm[0]*TOLERENCE+0.5),
1129 int(norm[1]*TOLERENCE+0.5),
1130 int(norm[2]*TOLERENCE+0.5),
1131 int(uv[0]*TOLERENCE+0.5),
1132 int(uv[1]*TOLERENCE+0.5))
1133
1134 if key in vertex_reference:
1135 index = vertex_reference[key]
1136 else:#{
1137 vindex = len(sr_compile.vertex_data)//sizeof(mdl_vert)
1138 index = bytearray(c_uint32(vindex))
1139 vertex_reference[key] = index
1140 v = mdl_vert()
1141 v.co[0] = co[0]
1142 v.co[1] = co[2]
1143 v.co[2] = -co[1]
1144 v.norm[0] = norm[0]
1145 v.norm[1] = norm[2]
1146 v.norm[2] = -norm[1]
1147 v.uv[0] = uv[0]
1148 v.uv[1] = uv[1]
1149
1150 sr_compile.vertex_data.extend(bytearray(v))
1151 #}
1152
1153 glyph.indice_count += 1
1154 sr_compile.indice_data.extend( index )
1155 #}
1156 #}
1157 #}
1158 sr_ent_push( glyph )
1159 #}
1160 sr_ent_push( variant )
1161 #}
1162 sr_ent_push( font )
1163 #}
1164 #}
1165
1166 def sr_compile_menus( collection ):
1167 #{
1168 print( "[SR1] Compiling menus" )
1169 groups = []
1170
1171 for obj in collection.all_objects:#{
1172 if obj_ent_type(obj) != 'ent_menuitem': continue
1173 obj_data = obj.SR_data.ent_menuitem[0]
1174
1175 bitmask = 0x00000000
1176
1177 for col in obj.users_collection:#{
1178 name = col.name
1179 if name not in groups: groups.append( name )
1180 bitmask |= (0x1 << groups.index(name))
1181 #}
1182
1183 item = ent_menuitem()
1184 item.type = int( obj_data.tipo )
1185 item.groups = bitmask
1186
1187 compile_obj_transform( obj, item.transform )
1188 if obj.type == 'MESH':#{
1189 item.submesh_start, item.submesh_count, _ = \
1190 sr_compile_mesh_internal( obj )
1191 #}
1192
1193 if item.type == 1 or item.type == 2:#{
1194 item_button = item._anonymous_union.button
1195 item_button.pstr = sr_compile_string( obj_data.string )
1196 #}
1197 elif item.type == 3:#{
1198 item_checkmark = item._anonymous_union.checkmark
1199 item_checkmark.pstr_data = sr_compile_string( obj_data.string )
1200 item_checkmark.id_check = sr_entity_id( obj_data.checkmark )
1201 delta = obj_data.checkmark.location - obj.location
1202 item_checkmark.offset[0] = delta[0]
1203 item_checkmark.offset[1] = delta[2]
1204 item_checkmark.offset[2] = -delta[1]
1205 #}
1206 elif item.type == 4:#{
1207 item_slider = item._anonymous_union.slider
1208 item_slider.id_min = sr_entity_id( obj_data.slider_minloc )
1209 item_slider.id_max = sr_entity_id( obj_data.slider_maxloc )
1210 item_slider.id_handle = sr_entity_id( obj_data.slider_handle )
1211 item_slider.pstr_data = sr_compile_string( obj_data.string )
1212 #}
1213 elif item.type == 5:#{
1214 item_page = item._anonymous_union.page
1215 item_page.pstr_name = sr_compile_string( obj_data.string )
1216 item_page.id_entrypoint = sr_entity_id( obj_data.newloc )
1217 item_page.id_viewpoint = sr_entity_id( obj_data.camera )
1218 #}
1219
1220 if obj_data.link0:
1221 item.id_links[0] = sr_entity_id( obj_data.link0 )
1222 if obj_data.link1:
1223 item.id_links[1] = sr_entity_id( obj_data.link1 )
1224 if item.type != 4:#{
1225 if obj_data.link2:
1226 item.id_links[2] = sr_entity_id( obj_data.link2 )
1227 if obj_data.link3:
1228 item.id_links[3] = sr_entity_id( obj_data.link3 )
1229 #}
1230
1231 sr_ent_push( item )
1232 #}
1233 #}
1234
1235 def sr_compile_armature( obj ):
1236 #{
1237 node = mdl_armature()
1238 node.bone_start = len(sr_compile.bone_data)//sizeof(mdl_bone)
1239 node.bone_count = 0
1240 node.anim_start = len(sr_compile.anim_data)//sizeof(mdl_animation)
1241 node.anim_count = 0
1242
1243 bones = [_ for _ in sr_armature_bones(obj)]
1244 bones_names = [None]+[_.name for _ in bones]
1245
1246 for b in bones:#{
1247 bone = mdl_bone()
1248 if b.use_deform: bone.flags = 0x1
1249 if b.parent: bone.parent = bones_names.index(b.parent.name)
1250
1251 bone.collider = int(b.SR_data.collider)
1252
1253 if bone.collider>0:#{
1254 bone.hitbox[0][0] = b.SR_data.collider_min[0]
1255 bone.hitbox[0][1] = b.SR_data.collider_min[2]
1256 bone.hitbox[0][2] = -b.SR_data.collider_max[1]
1257 bone.hitbox[1][0] = b.SR_data.collider_max[0]
1258 bone.hitbox[1][1] = b.SR_data.collider_max[2]
1259 bone.hitbox[1][2] = -b.SR_data.collider_min[1]
1260 #}
1261
1262 if b.SR_data.cone_constraint:#{
1263 bone.flags |= 0x4
1264 bone.conevx[0] = b.SR_data.conevx[0]
1265 bone.conevx[1] = b.SR_data.conevx[2]
1266 bone.conevx[2] = -b.SR_data.conevx[1]
1267 bone.conevy[0] = b.SR_data.conevy[0]
1268 bone.conevy[1] = b.SR_data.conevy[2]
1269 bone.conevy[2] = -b.SR_data.conevy[1]
1270 bone.coneva[0] = b.SR_data.coneva[0]
1271 bone.coneva[1] = b.SR_data.coneva[2]
1272 bone.coneva[2] = -b.SR_data.coneva[1]
1273 bone.conet = b.SR_data.conet
1274 #}
1275
1276 bone.co[0] = b.head_local[0]
1277 bone.co[1] = b.head_local[2]
1278 bone.co[2] = -b.head_local[1]
1279 bone.end[0] = b.tail_local[0] - bone.co[0]
1280 bone.end[1] = b.tail_local[2] - bone.co[1]
1281 bone.end[2] = -b.tail_local[1] - bone.co[2]
1282 bone.pstr_name = sr_compile_string( b.name )
1283
1284 for c in obj.pose.bones[b.name].constraints:#{
1285 if c.type == 'IK':#{
1286 bone.flags |= 0x2
1287 bone.ik_target = bones_names.index(c.subtarget)
1288 bone.ik_pole = bones_names.index(c.pole_subtarget)
1289 #}
1290 #}
1291
1292 node.bone_count += 1
1293 sr_compile.bone_data.extend(bytearray(bone))
1294 #}
1295
1296 # Compile anims
1297 #
1298 if obj.animation_data and sr_compile.pack_animations: #{
1299 # So we can restore later
1300 #
1301 previous_frame = bpy.context.scene.frame_current
1302 previous_action = obj.animation_data.action
1303 POSE_OR_REST_CACHE = obj.data.pose_position
1304 obj.data.pose_position = 'POSE'
1305
1306 for NLALayer in obj.animation_data.nla_tracks:#{
1307 for NLAStrip in NLALayer.strips:#{
1308 # set active
1309 #
1310 for a in bpy.data.actions:#{
1311 if a.name == NLAStrip.name:#{
1312 obj.animation_data.action = a
1313 break
1314 #}
1315 #}
1316
1317 # Clip to NLA settings
1318 #
1319 anim_start = int(NLAStrip.action_frame_start)
1320 anim_end = int(NLAStrip.action_frame_end)
1321
1322 # Export strips
1323 #
1324 anim = mdl_animation()
1325 anim.pstr_name = sr_compile_string( NLAStrip.action.name )
1326 anim.rate = 30.0
1327 anim.keyframe_start = len(sr_compile.keyframe_data)//\
1328 sizeof(mdl_transform)
1329 anim.length = anim_end-anim_start
1330
1331 i = 0
1332 # Export the keyframes
1333 for frame in range(anim_start,anim_end):#{
1334 bpy.context.scene.frame_set(frame)
1335
1336 for rb in bones:#{
1337 pb = obj.pose.bones[rb.name]
1338
1339 # relative bone matrix
1340 if rb.parent is not None:#{
1341 offset_mtx = rb.parent.matrix_local
1342 offset_mtx = offset_mtx.inverted_safe() @ \
1343 rb.matrix_local
1344
1345 inv_parent = pb.parent.matrix @ offset_mtx
1346 inv_parent.invert_safe()
1347 fpm = inv_parent @ pb.matrix
1348 #}
1349 else:#{
1350 bone_mtx = rb.matrix.to_4x4()
1351 local_inv = rb.matrix_local.inverted_safe()
1352 fpm = bone_mtx @ local_inv @ pb.matrix
1353 #}
1354
1355 loc, rot, sca = fpm.decompose()
1356
1357 # rotation
1358 lc_m = pb.matrix_channel.to_3x3()
1359 if pb.parent is not None:#{
1360 smtx = pb.parent.matrix_channel.to_3x3()
1361 lc_m = smtx.inverted() @ lc_m
1362 #}
1363 rq = lc_m.to_quaternion()
1364
1365 kf = mdl_transform()
1366 kf.co[0] = loc[0]
1367 kf.co[1] = loc[2]
1368 kf.co[2] = -loc[1]
1369 kf.q[0] = rq[1]
1370 kf.q[1] = rq[3]
1371 kf.q[2] = -rq[2]
1372 kf.q[3] = rq[0]
1373 kf.s[0] = sca[0]
1374 kf.s[1] = sca[1]
1375 kf.s[2] = sca[2]
1376 sr_compile.keyframe_data.extend(bytearray(kf))
1377
1378 i+=1
1379 #}
1380 #}
1381
1382 # Add to animation buffer
1383 #
1384 sr_compile.anim_data.extend(bytearray(anim))
1385 node.anim_count += 1
1386
1387 # Report progress
1388 #
1389 print( F"[SR] | anim( {NLAStrip.action.name} )" )
1390 #}
1391 #}
1392
1393 # Restore context to how it was before
1394 #
1395 bpy.context.scene.frame_set( previous_frame )
1396 obj.animation_data.action = previous_action
1397 obj.data.pose_position = POSE_OR_REST_CACHE
1398 #}
1399
1400 sr_compile.armature_data.extend(bytearray(node))
1401 #}
1402
1403 def sr_ent_push( struct ):
1404 #{
1405 clase = type(struct).__name__
1406
1407 if clase not in sr_compile.entity_data:#{
1408 sr_compile.entity_data[ clase ] = bytearray()
1409 sr_compile.entity_info[ clase ] = { 'size': sizeof(struct) }
1410 #}
1411
1412 index = len(sr_compile.entity_data[ clase ])//sizeof(struct)
1413 sr_compile.entity_data[ clase ].extend( bytearray(struct) )
1414 return index
1415 #}
1416
1417 def sr_array_title( arr, name, count, size, offset ):
1418 #{
1419 for i in range(len(name)):#{
1420 arr.name[i] = ord(name[i])
1421 #}
1422 arr.file_offset = offset
1423 arr.item_count = count
1424 arr.item_size = size
1425 #}
1426
1427 def hash_djb2(s):
1428 #{
1429 picadillo = 5381
1430 for x in s:#{
1431 picadillo = (((picadillo << 5) + picadillo) + ord(x)) & 0xFFFFFFFF
1432 #}
1433 return picadillo
1434 #}
1435
1436 def sr_compile( collection ):
1437 #{
1438 print( F"[SR] compiler begin ({collection.name}.mdl)" )
1439
1440 #settings
1441 sr_compile.pack_textures = collection.SR_data.pack_textures
1442 sr_compile.pack_animations = collection.SR_data.animations
1443
1444 # caches
1445 sr_compile.string_cache = {}
1446 sr_compile.mesh_cache = {}
1447 sr_compile.material_cache = {}
1448 sr_compile.texture_cache = {}
1449
1450 # compiled data
1451 sr_compile.mesh_data = bytearray()
1452 sr_compile.submesh_data = bytearray()
1453 sr_compile.vertex_data = bytearray()
1454 sr_compile.indice_data = bytearray()
1455 sr_compile.bone_data = bytearray()
1456 sr_compile.material_data = bytearray()
1457 sr_compile.armature_data = bytearray()
1458 sr_compile.anim_data = bytearray()
1459 sr_compile.keyframe_data = bytearray()
1460 sr_compile.texture_data = bytearray()
1461
1462 # just bytes not structures
1463 sr_compile.string_data = bytearray()
1464 sr_compile.pack_data = bytearray()
1465
1466 # variable
1467 sr_compile.entity_data = {}
1468 sr_compile.entity_info = {}
1469
1470 print( F"[SR] assign entity ID's" )
1471 sr_compile.entities = {}
1472 sr_compile.entity_ids = {}
1473
1474 # begin
1475 # -------------------------------------------------------
1476
1477 sr_compile_string( "null" )
1478
1479 mesh_count = 0
1480 for obj in collection.all_objects: #{
1481 if obj.type == 'MESH':#{
1482 mesh_count += 1
1483 #}
1484
1485 ent_type = obj_ent_type( obj )
1486 if ent_type == 'none': continue
1487
1488 if ent_type not in sr_compile.entities: sr_compile.entities[ent_type] = []
1489 sr_compile.entity_ids[obj.name] = len( sr_compile.entities[ent_type] )
1490 sr_compile.entities[ent_type] += [obj]
1491 #}
1492
1493 print( F"[SR] Compiling geometry" )
1494 i=0
1495 for obj in collection.all_objects:#{
1496 if obj.type == 'MESH':#{
1497 i+=1
1498
1499 ent_type = obj_ent_type( obj )
1500
1501 # entity ignore mesh list
1502 #
1503 if ent_type == 'ent_traffic': continue
1504 if ent_type == 'ent_font': continue
1505 if ent_type == 'ent_font_variant': continue
1506 if ent_type == 'ent_menuitem': continue
1507 #--------------------------
1508
1509 print( F'[SR] {i: 3}/{mesh_count} {obj.name:<40}', end='\r' )
1510 sr_compile_mesh( obj )
1511 #}
1512 #}
1513
1514 audio_clip_count = 0
1515
1516 for ent_type, arr in sr_compile.entities.items():#{
1517 print(F"[SR] Compiling {len(arr)} {ent_type}{'s' if len(arr)>1 else ''}")
1518
1519 for i in range(len(arr)):#{
1520 obj = arr[i]
1521
1522 print( F"[SR] {i+1: 3}/{len(arr)} {obj.name:<40} ",end='\r' )
1523
1524 if ent_type == 'mdl_armature': sr_compile_armature(obj)
1525 elif ent_type == 'ent_light': #{
1526 light = ent_light()
1527 compile_obj_transform( obj, light.transform )
1528 light.daytime = obj.data.SR_data.daytime
1529 if obj.data.type == 'POINT':#{
1530 light.type = 0
1531 #}
1532 elif obj.data.type == 'SPOT':#{
1533 light.type = 1
1534 light.angle = obj.data.spot_size*0.5
1535 #}
1536 light.range = obj.data.cutoff_distance
1537 light.colour[0] = obj.data.color[0]
1538 light.colour[1] = obj.data.color[1]
1539 light.colour[2] = obj.data.color[2]
1540 light.colour[3] = obj.data.energy
1541 sr_ent_push( light )
1542 #}
1543 elif ent_type == 'ent_camera': #{
1544 cam = ent_camera()
1545 compile_obj_transform( obj, cam.transform )
1546 cam.fov = obj.data.angle * 45.0
1547 sr_ent_push(cam)
1548 #}
1549 elif ent_type == 'ent_gate': #{
1550 gate = ent_gate()
1551 obj_data = obj.SR_data.ent_gate[0]
1552 mesh_data = obj.data.SR_data.ent_gate[0]
1553
1554 if obj_data.tipo == 'default':#{
1555 if obj_data.target:#{
1556 gate.target = sr_compile.entity_ids[obj_data.target.name]
1557 gate.type = 1
1558 #}
1559 #}
1560 elif obj_data.tipo == 'nonlocal':#{
1561 gate.target = sr_compile_string(obj_data.key)
1562 gate.type = 2
1563 #}
1564 else: gate.type = 0
1565
1566 gate.dimensions[0] = mesh_data.dimensions[0]
1567 gate.dimensions[1] = mesh_data.dimensions[1]
1568 gate.dimensions[2] = mesh_data.dimensions[2]
1569
1570 q = [obj.matrix_local.to_quaternion(), (0,0,0,1)]
1571 co = [obj.matrix_world @ Vector((0,0,0)), (0,0,0)]
1572
1573 if obj_data.target:#{
1574 q[1] = obj_data.target.matrix_local.to_quaternion()
1575 co[1]= obj_data.target.matrix_world @ Vector((0,0,0))
1576 #}
1577
1578 # Setup transform
1579 #
1580 for x in range(2):#{
1581 gate.co[x][0] = co[x][0]
1582 gate.co[x][1] = co[x][2]
1583 gate.co[x][2] = -co[x][1]
1584 gate.q[x][0] = q[x][1]
1585 gate.q[x][1] = q[x][3]
1586 gate.q[x][2] = -q[x][2]
1587 gate.q[x][3] = q[x][0]
1588 #}
1589
1590 sr_ent_push( gate )
1591 #}
1592 elif ent_type == 'ent_spawn': #{
1593 spawn = ent_spawn()
1594 compile_obj_transform( obj, spawn.transform )
1595 obj_data = obj.SR_data.ent_spawn[0]
1596 spawn.pstr_name = sr_compile_string( obj_data.alias )
1597 sr_ent_push( spawn )
1598 #}
1599 elif ent_type == 'ent_water':#{
1600 water = ent_water()
1601 compile_obj_transform( obj, water.transform )
1602 water.max_dist = 0.0
1603 sr_ent_push( water )
1604 #}
1605 elif ent_type == 'ent_audio':#{
1606 obj_data = obj.SR_data.ent_audio[0]
1607 audio = ent_audio()
1608 compile_obj_transform( obj, audio.transform )
1609 audio.clip_start = audio_clip_count
1610 audio.clip_count = len(obj_data.files)
1611 audio_clip_count += audio.clip_count
1612 audio.max_channels = obj_data.max_channels
1613 audio.volume = obj_data.volume
1614
1615 # TODO flags:
1616 # - allow/disable doppler
1617 # - channel group tags with random colours
1618 # - transition properties
1619
1620 if obj_data.flag_loop: audio.flags |= 0x1
1621 if obj_data.flag_nodoppler: audio.flags |= 0x2
1622 if obj_data.flag_3d: audio.flags |= 0x4
1623 if obj_data.flag_auto: audio.flags |= 0x8
1624 if obj_data.formato == '0': audio.flags |= 0x000
1625 elif obj_data.formato == '1': audio.flags |= 0x400
1626 elif obj_data.formato == '2': audio.flags |= 0x1000
1627
1628 audio.channel_behaviour = int(obj_data.channel_behaviour)
1629 if audio.channel_behaviour >= 1:#{
1630 audio.group = obj_data.group
1631 #}
1632 if audio.channel_behaviour == 2:#{
1633 audio.crossfade = obj_data.transition_duration
1634 #}
1635 audio.probability_curve = int(obj_data.probability_curve)
1636
1637 for ci in range(audio.clip_count):#{
1638 entry = obj_data.files[ci]
1639 clip = ent_audio_clip()
1640 clip.probability = entry.probability
1641 if obj_data.formato == '2':#{
1642 sr_pack_file( clip._anon.file, '', vg_str_bin(entry.path) )
1643 #}
1644 else:#{
1645 clip._anon.file.path = sr_compile_string( entry.path )
1646 clip._anon.file.pack_offset = 0
1647 clip._anon.file.pack_size = 0
1648 #}
1649 sr_ent_push( clip )
1650 #}
1651 sr_ent_push( audio )
1652 #}
1653 elif ent_type == 'ent_volume':#{
1654 obj_data = obj.SR_data.ent_volume[0]
1655 volume = ent_volume()
1656 volume.type = int(obj_data.subtype)
1657 compile_obj_transform( obj, volume.transform )
1658
1659 if obj_data.target:#{
1660 volume.target = sr_entity_id( obj_data.target )
1661 #}
1662
1663 sr_ent_push(volume)
1664 #}
1665 elif ent_type == 'ent_marker':#{
1666 marker = ent_marker()
1667 marker.name = sr_compile_string( obj.SR_data.ent_marker[0].alias )
1668 compile_obj_transform( obj, marker.transform )
1669 sr_ent_push(marker)
1670 #}
1671 elif ent_type == 'ent_skateshop':#{
1672 skateshop = ent_skateshop()
1673 obj_data = obj.SR_data.ent_skateshop[0]
1674 skateshop.type = int(obj_data.tipo)
1675 if skateshop.type == 0:#{
1676 boardshop = skateshop._anonymous_union.boards
1677 boardshop.id_display = sr_entity_id( obj_data.mark_display )
1678 boardshop.id_info = sr_entity_id( obj_data.mark_info )
1679 boardshop.id_rack = sr_entity_id( obj_data.mark_rack )
1680 #}
1681 elif skateshop.type == 1:#{
1682 charshop = skateshop._anonymous_union.character
1683 charshop.id_display = sr_entity_id( obj_data.mark_display )
1684 charshop.id_info = sr_entity_id( obj_data.mark_info )
1685 #}
1686 skateshop.id_camera = sr_entity_id( obj_data.cam )
1687 compile_obj_transform( obj, skateshop.transform )
1688 sr_ent_push(skateshop)
1689 #}
1690 elif ent_type == 'ent_swspreview':#{
1691 workshop_preview = ent_swspreview()
1692 obj_data = obj.SR_data.ent_swspreview[0]
1693 workshop_preview.id_display = sr_entity_id( obj_data.mark_display )
1694 workshop_preview.id_display1 = sr_entity_id( obj_data.mark_display1)
1695 workshop_preview.id_camera = sr_entity_id( obj_data.cam )
1696 sr_ent_push( workshop_preview )
1697 #}
1698 #}
1699 #}
1700
1701 sr_compile_menus( collection )
1702 sr_compile_fonts( collection )
1703
1704 def _children( col ):#{
1705 yield col
1706 for c in col.children:#{
1707 yield from _children(c)
1708 #}
1709 #}
1710
1711 checkpoint_count = 0
1712 pathindice_count = 0
1713 routenode_count = 0
1714
1715 for col in _children(collection):#{
1716 print( F"Adding routes for subcollection: {col.name}" )
1717 route_gates = []
1718 route_curves = []
1719 routes = []
1720 traffics = []
1721
1722 for obj in col.objects:#{
1723 if obj.type == 'ARMATURE': pass
1724 else:#{
1725 ent_type = obj_ent_type( obj )
1726
1727 if ent_type == 'ent_gate':
1728 route_gates += [obj]
1729 elif ent_type == 'ent_route_node':#{
1730 if obj.type == 'CURVE':#{
1731 route_curves += [obj]
1732 #}
1733 #}
1734 elif ent_type == 'ent_route':
1735 routes += [obj]
1736 elif ent_type == 'ent_traffic':
1737 traffics += [obj]
1738 #}
1739 #}
1740
1741 dij = create_node_graph( route_curves, route_gates )
1742
1743 for obj in routes:#{
1744 obj_data = obj.SR_data.ent_route[0]
1745 route = ent_route()
1746 route.pstr_name = sr_compile_string( obj_data.alias )
1747 route.checkpoints_start = checkpoint_count
1748 route.checkpoints_count = 0
1749
1750 for ci in range(3):
1751 route.colour[ci] = obj_data.colour[ci]
1752 route.colour[3] = 1.0
1753
1754 compile_obj_transform( obj, route.transform )
1755 checkpoints = obj_data.gates
1756
1757 for i in range(len(checkpoints)):#{
1758 gi = checkpoints[i].target
1759 gj = checkpoints[(i+1)%len(checkpoints)].target
1760 gate = gi
1761
1762 if gi:#{
1763 dest = gi.SR_data.ent_gate[0].target
1764 gi = dest
1765 #}
1766
1767 if gi==gj: continue # error?
1768 if not gi or not gj: continue
1769
1770 checkpoint = ent_checkpoint()
1771 checkpoint.gate_index = sr_compile.entity_ids[gate.name]
1772 checkpoint.path_start = pathindice_count
1773 checkpoint.path_count = 0
1774
1775 path = solve_graph( dij, gi.name, gj.name )
1776
1777 if path:#{
1778 for pi in range(len(path)):#{
1779 pathindice = ent_path_index()
1780 pathindice.index = routenode_count + path[pi]
1781 sr_ent_push( pathindice )
1782
1783 checkpoint.path_count += 1
1784 pathindice_count += 1
1785 #}
1786 #}
1787
1788 sr_ent_push( checkpoint )
1789 route.checkpoints_count += 1
1790 checkpoint_count += 1
1791 #}
1792
1793 sr_ent_push( route )
1794 #}
1795
1796 for obj in traffics:#{
1797 traffic = ent_traffic()
1798 compile_obj_transform( obj, traffic.transform )
1799 traffic.submesh_start, traffic.submesh_count, _ = \
1800 sr_compile_mesh_internal( obj )
1801
1802 # find best subsection
1803
1804 graph_keys = list(dij.graph)
1805 min_dist = 100.0
1806 best_point = 0
1807
1808 for j in range(len(dij.points)):#{
1809 point = dij.points[j]
1810 dist = (point-obj.location).magnitude
1811
1812 if dist < min_dist:#{
1813 min_dist = dist
1814 best_point = j
1815 #}
1816 #}
1817
1818 # scan to each edge
1819 best_begin = best_point
1820 best_end = best_point
1821
1822 while True:#{
1823 map0 = dij.subsections[best_begin]
1824 if map0[1] == -1: break
1825 best_begin = map0[1]
1826 #}
1827 while True:#{
1828 map1 = dij.subsections[best_end]
1829 if map1[2] == -1: break
1830 best_end = map1[2]
1831 #}
1832
1833 traffic.start_node = routenode_count + best_begin
1834 traffic.node_count = best_end - best_begin
1835 traffic.index = best_point - best_begin
1836 traffic.speed = obj.SR_data.ent_traffic[0].speed
1837 traffic.t = 0.0
1838
1839 sr_ent_push(traffic)
1840 #}
1841
1842 for point in dij.points:#{
1843 rn = ent_route_node()
1844 rn.co[0] = point[0]
1845 rn.co[1] = point[2]
1846 rn.co[2] = -point[1]
1847 sr_ent_push( rn )
1848 #}
1849
1850 routenode_count += len(dij.points)
1851 #}
1852
1853 print( F"[SR] Writing file" )
1854
1855 file_array_instructions = {}
1856 file_offset = 0
1857
1858 def _write_array( name, item_size, data ):#{
1859 nonlocal file_array_instructions, file_offset
1860
1861 count = len(data)//item_size
1862 file_array_instructions[name] = {'count':count, 'size':item_size,\
1863 'data':data, 'offset': file_offset}
1864 file_offset += len(data)
1865 file_offset = int_align_to( file_offset, 8 )
1866 #}
1867
1868 _write_array( 'strings', 1, sr_compile.string_data )
1869 _write_array( 'mdl_mesh', sizeof(mdl_mesh), sr_compile.mesh_data )
1870 _write_array( 'mdl_submesh', sizeof(mdl_submesh), sr_compile.submesh_data )
1871 _write_array( 'mdl_material', sizeof(mdl_material), sr_compile.material_data)
1872 _write_array( 'mdl_texture', sizeof(mdl_texture), sr_compile.texture_data)
1873 _write_array( 'mdl_armature', sizeof(mdl_armature), sr_compile.armature_data)
1874 _write_array( 'mdl_bone', sizeof(mdl_bone), sr_compile.bone_data )
1875
1876 for name, buffer in sr_compile.entity_data.items():#{
1877 _write_array( name, sr_compile.entity_info[name]['size'], buffer )
1878 #}
1879
1880 _write_array( 'mdl_animation', sizeof(mdl_animation), sr_compile.anim_data)
1881 _write_array( 'mdl_keyframe', sizeof(mdl_transform),sr_compile.keyframe_data)
1882 _write_array( 'mdl_vert', sizeof(mdl_vert), sr_compile.vertex_data )
1883 _write_array( 'mdl_indice', sizeof(c_uint32), sr_compile.indice_data )
1884 _write_array( 'pack', 1, sr_compile.pack_data )
1885
1886 header_size = int_align_to( sizeof(mdl_header), 8 )
1887 index_size = int_align_to( sizeof(mdl_array)*len(file_array_instructions),8 )
1888
1889 folder = bpy.path.abspath(bpy.context.scene.SR_data.export_dir)
1890 path = F"{folder}{collection.name}.mdl"
1891 print( path )
1892
1893 fp = open( path, "wb" )
1894 header = mdl_header()
1895 header.version = 101
1896 sr_array_title( header.arrays, \
1897 'index', len(file_array_instructions), \
1898 sizeof(mdl_array), header_size )
1899
1900 fp.write( bytearray_align_to( bytearray(header), 8 ) )
1901
1902 print( F'[SR] {"name":>16}| count | offset' )
1903 index = bytearray()
1904 for name,info in file_array_instructions.items():#{
1905 arr = mdl_array()
1906 offset = info['offset'] + header_size + index_size
1907 sr_array_title( arr, name, info['count'], info['size'], offset )
1908 index.extend( bytearray(arr) )
1909
1910 print( F'[SR] {name:>16}| {info["count"]: 8} '+\
1911 F' 0x{info["offset"]:02x}' )
1912 #}
1913 fp.write( bytearray_align_to( index, 8 ) )
1914 #bytearray_print_hex( index )
1915
1916 for name,info in file_array_instructions.items():#{
1917 fp.write( bytearray_align_to( info['data'], 8 ) )
1918 #}
1919
1920 fp.close()
1921
1922 print( '[SR] done' )
1923 #}
1924
1925 class SR_SCENE_SETTINGS(bpy.types.PropertyGroup):
1926 #{
1927 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
1928 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
1929 gizmos: bpy.props.BoolProperty( name="Draw Gizmos", default=True )
1930
1931 panel: bpy.props.EnumProperty(
1932 name='Panel',
1933 description='',
1934 items=[
1935 ('EXPORT', 'Export', '', 'MOD_BUILD',0),
1936 ('ENTITY', 'Entity', '', 'MONKEY',1),
1937 ('SETTINGS', 'Settings', 'Settings', 'PREFERENCES',2),
1938 ],
1939 )
1940 #}
1941
1942 class SR_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
1943 #{
1944 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
1945 animations: bpy.props.BoolProperty( name="Export animation", default=True)
1946 #}
1947
1948 def sr_get_mirror_bone( bones ):
1949 #{
1950 side = bones.active.name[-1:]
1951 other_name = bones.active.name[:-1]
1952 if side == 'L': other_name += 'R'
1953 elif side == 'R': other_name += 'L'
1954 else: return None
1955
1956 for b in bones:#{
1957 if b.name == other_name:
1958 return b
1959 #}
1960
1961 return None
1962 #}
1963
1964 class SR_MIRROR_BONE_X(bpy.types.Operator):
1965 #{
1966 bl_idname="skaterift.mirror_bone"
1967 bl_label="Mirror bone attributes - SkateRift"
1968
1969 def execute(_,context):
1970 #{
1971 active_object = context.active_object
1972 bones = active_object.data.bones
1973 a = bones.active
1974 b = sr_get_mirror_bone( bones )
1975
1976 if not b: return {'FINISHED'}
1977
1978 b.SR_data.collider = a.SR_data.collider
1979
1980 def _v3copyflipy( a, b ):#{
1981 b[0] = a[0]
1982 b[1] = -a[1]
1983 b[2] = a[2]
1984 #}
1985
1986 _v3copyflipy( a.SR_data.collider_min, b.SR_data.collider_min )
1987 _v3copyflipy( a.SR_data.collider_max, b.SR_data.collider_max )
1988 b.SR_data.collider_min[1] = -a.SR_data.collider_max[1]
1989 b.SR_data.collider_max[1] = -a.SR_data.collider_min[1]
1990
1991 b.SR_data.cone_constraint = a.SR_data.cone_constraint
1992
1993 _v3copyflipy( a.SR_data.conevx, b.SR_data.conevy )
1994 _v3copyflipy( a.SR_data.conevy, b.SR_data.conevx )
1995 _v3copyflipy( a.SR_data.coneva, b.SR_data.coneva )
1996
1997 b.SR_data.conet = a.SR_data.conet
1998
1999 # redraw
2000 ob = bpy.context.scene.objects[0]
2001 ob.hide_render = ob.hide_render
2002 return {'FINISHED'}
2003 #}
2004 #}
2005
2006 class SR_COMPILE(bpy.types.Operator):
2007 #{
2008 bl_idname="skaterift.compile_all"
2009 bl_label="Compile All"
2010
2011 def execute(_,context):
2012 #{
2013 view_layer = bpy.context.view_layer
2014 for col in view_layer.layer_collection.children["export"].children:
2015 if not col.hide_viewport or bpy.context.scene.SR_data.use_hidden:
2016 sr_compile( bpy.data.collections[col.name] )
2017
2018 return {'FINISHED'}
2019 #}
2020 #}
2021
2022 class SR_COMPILE_THIS(bpy.types.Operator):
2023 #{
2024 bl_idname="skaterift.compile_this"
2025 bl_label="Compile This collection"
2026
2027 def execute(_,context):
2028 #{
2029 col = bpy.context.collection
2030 sr_compile( col )
2031
2032 return {'FINISHED'}
2033 #}
2034 #}
2035
2036 class SR_INTERFACE(bpy.types.Panel):
2037 #{
2038 bl_idname = "VIEW3D_PT_skate_rift"
2039 bl_label = "Skate Rift"
2040 bl_space_type = 'VIEW_3D'
2041 bl_region_type = 'UI'
2042 bl_category = "Skate Rift"
2043
2044 def draw(_, context):
2045 #{
2046 # Compiler section
2047
2048 row = _.layout.row()
2049 row.scale_y = 1.75
2050 row.prop( context.scene.SR_data, 'panel', expand=True )
2051
2052 if context.scene.SR_data.panel == 'SETTINGS': #{
2053 _.layout.prop( context.scene.SR_data, 'gizmos' )
2054 #}
2055 elif context.scene.SR_data.panel == 'EXPORT': #{
2056 _.layout.prop( context.scene.SR_data, "export_dir" )
2057 col = bpy.context.collection
2058
2059 found_in_export = False
2060 export_count = 0
2061 view_layer = bpy.context.view_layer
2062 for c1 in view_layer.layer_collection.children["export"].children: #{
2063 if not c1.hide_viewport or bpy.context.scene.SR_data.use_hidden:
2064 export_count += 1
2065
2066 if c1.name == col.name: #{
2067 found_in_export = True
2068 #}
2069 #}
2070
2071 box = _.layout.box()
2072 row = box.row()
2073 row.alignment = 'CENTER'
2074 row.scale_y = 1.5
2075
2076 if found_in_export: #{
2077 row.label( text=col.name + ".mdl" )
2078 box.prop( col.SR_data, "pack_textures" )
2079 box.prop( col.SR_data, "animations" )
2080 box.operator( "skaterift.compile_this" )
2081 #}
2082 else: #{
2083 row.enabled=False
2084 row.label( text=col.name )
2085
2086 row = box.row()
2087 row.enabled=False
2088 row.alignment = 'CENTER'
2089 row.scale_y = 1.5
2090 row.label( text="This collection is not in the export group" )
2091 #}
2092
2093 box = _.layout.box()
2094 row = box.row()
2095
2096 split = row.split( factor=0.3, align=True )
2097 split.prop( context.scene.SR_data, "use_hidden", text="hidden" )
2098
2099 row1 = split.row()
2100 if export_count == 0:
2101 row1.enabled=False
2102 row1.operator( "skaterift.compile_all", \
2103 text=F"Compile all ({export_count} collections)" )
2104 #}
2105 elif context.scene.SR_data.panel == 'ENTITY': #{
2106 active_object = context.active_object
2107 if not active_object: return
2108
2109 _.layout.operator( 'skaterift.copy_entity_data', \
2110 text=F'Copy entity data to {len(context.selected_objects)-1} '+\
2111 F'other objects' )
2112
2113 box = _.layout.box()
2114 row = box.row()
2115 row.alignment = 'CENTER'
2116 row.label( text=active_object.name )
2117 row.scale_y = 1.5
2118
2119 def _draw_prop_collection( data ): #{
2120 nonlocal box
2121 row = box.row()
2122 row.alignment = 'CENTER'
2123 row.enabled = False
2124 row.scale_y = 1.5
2125 row.label( text=F'{data[0]}' )
2126
2127 if hasattr(type(data[0]),'sr_inspector'):#{
2128 type(data[0]).sr_inspector( box, data )
2129 #}
2130 else:#{
2131 for a in data[0].__annotations__:
2132 box.prop( data[0], a )
2133 #}
2134 #}
2135
2136 if active_object.type == 'ARMATURE': #{
2137 if active_object.mode == 'POSE': #{
2138 bones = active_object.data.bones
2139 mb = sr_get_mirror_bone( bones )
2140 if mb:#{
2141 box.operator( "skaterift.mirror_bone", \
2142 text=F'Mirror attributes to {mb.name}' )
2143 #}
2144
2145 _draw_prop_collection( [bones.active.SR_data ] )
2146 #}
2147 else: #{
2148 row = box.row()
2149 row.alignment='CENTER'
2150 row.scale_y=2.0
2151 row.enabled=False
2152 row.label( text="Enter pose mode to modify bone properties" )
2153 #}
2154 #}
2155 elif active_object.type == 'LIGHT': #{
2156 _draw_prop_collection( [active_object.data.SR_data] )
2157 #}
2158 elif active_object.type in ['EMPTY','CURVE','MESH']:#{
2159 box.prop( active_object.SR_data, "ent_type" )
2160 ent_type = active_object.SR_data.ent_type
2161
2162 col = getattr( active_object.SR_data, ent_type, None )
2163 if col != None and len(col)!=0: _draw_prop_collection( col )
2164
2165 if active_object.type == 'MESH':#{
2166 col = getattr( active_object.data.SR_data, ent_type, None )
2167 if col != None and len(col)!=0: _draw_prop_collection( col )
2168 #}
2169 #}
2170 #}
2171 #}
2172 #}
2173
2174 class SR_MATERIAL_PANEL(bpy.types.Panel):
2175 #{
2176 bl_label="Skate Rift material"
2177 bl_idname="MATERIAL_PT_sr_material"
2178 bl_space_type='PROPERTIES'
2179 bl_region_type='WINDOW'
2180 bl_context="material"
2181
2182 def draw(_,context):
2183 #{
2184 active_object = bpy.context.active_object
2185 if active_object == None: return
2186 active_mat = active_object.active_material
2187 if active_mat == None: return
2188
2189 info = material_info( active_mat )
2190
2191 if 'tex_diffuse' in info:#{
2192 _.layout.label( icon='INFO', \
2193 text=F"{info['tex_diffuse'].name} will be compiled" )
2194 #}
2195
2196 _.layout.prop( active_mat.SR_data, "shader" )
2197 _.layout.prop( active_mat.SR_data, "surface_prop" )
2198 _.layout.prop( active_mat.SR_data, "collision" )
2199
2200 if active_mat.SR_data.collision:#{
2201 box = _.layout.box()
2202 row = box.row()
2203
2204 if (active_mat.SR_data.shader != 'invisible') and \
2205 (active_mat.SR_data.shader != 'boundary'):#{
2206 row.prop( active_mat.SR_data, "skate_surface" )
2207 row.prop( active_mat.SR_data, "grind_surface" )
2208 row.prop( active_mat.SR_data, "grow_grass" )
2209 #}
2210 #}
2211
2212 if active_mat.SR_data.shader == "terrain_blend":#{
2213 box = _.layout.box()
2214 box.prop( active_mat.SR_data, "blend_offset" )
2215 box.prop( active_mat.SR_data, "sand_colour" )
2216 #}
2217 elif active_mat.SR_data.shader == "vertex_blend":#{
2218 box = _.layout.box()
2219 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
2220 box.prop( active_mat.SR_data, "blend_offset" )
2221 #}
2222 elif active_mat.SR_data.shader == "water":#{
2223 box = _.layout.box()
2224 box.label( icon='INFO', text="Depth scale of 16 meters" )
2225 box.prop( active_mat.SR_data, "shore_colour" )
2226 box.prop( active_mat.SR_data, "ocean_colour" )
2227 #}
2228 #}
2229 #}
2230
2231 def sr_get_type_enum( scene, context ):
2232 #{
2233 items = [('none','None',"")]
2234 mesh_entities=['ent_gate','ent_water']
2235 point_entities=['ent_spawn','ent_route_node','ent_route']
2236
2237 for e in point_entities: items += [(e,e,'')]
2238
2239 if context.scene.SR_data.panel == 'ENTITY': #{
2240 if context.active_object.type == 'MESH': #{
2241 for e in mesh_entities: items += [(e,e,'')]
2242 #}
2243 #}
2244 else: #{
2245 for e in mesh_entities: items += [(e,e,'')]
2246 #}
2247
2248 return items
2249 #}
2250
2251 def sr_on_type_change( _, context ):
2252 #{
2253 obj = context.active_object
2254 ent_type = obj.SR_data.ent_type
2255 if ent_type == 'none': return
2256 if obj.type == 'MESH':#{
2257 col = getattr( obj.data.SR_data, ent_type, None )
2258 if col != None and len(col)==0: col.add()
2259 #}
2260
2261 col = getattr( obj.SR_data, ent_type, None )
2262 if col != None and len(col)==0: col.add()
2263 #}
2264
2265 class SR_OBJECT_ENT_SPAWN(bpy.types.PropertyGroup):
2266 #{
2267 alias: bpy.props.StringProperty( name='alias' )
2268 #}
2269
2270 class SR_OBJECT_ENT_GATE(bpy.types.PropertyGroup):
2271 #{
2272 target: bpy.props.PointerProperty( \
2273 type=bpy.types.Object, name="destination", \
2274 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
2275
2276 key: bpy.props.StringProperty()
2277 tipo: bpy.props.EnumProperty(items=(('default', 'Default', ""),
2278 ('nonlocal', 'Non-Local', ""),))
2279
2280 @staticmethod
2281 def sr_inspector( layout, data ):
2282 #{
2283 box = layout.box()
2284 box.prop( data[0], 'tipo', text="subtype" )
2285
2286 if data[0].tipo == 'default': box.prop( data[0], 'target' )
2287 elif data[0].tipo == 'nonlocal': box.prop( data[0], 'key' )
2288 #}
2289 #}
2290
2291 class SR_MESH_ENT_GATE(bpy.types.PropertyGroup):
2292 #{
2293 dimensions: bpy.props.FloatVectorProperty(name="dimensions",size=3)
2294 #}
2295
2296 class SR_OBJECT_ENT_ROUTE_ENTRY(bpy.types.PropertyGroup):
2297 #{
2298 target: bpy.props.PointerProperty( \
2299 type=bpy.types.Object, name='target', \
2300 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
2301 #}
2302
2303 class SR_UL_ROUTE_NODE_LIST(bpy.types.UIList):
2304 #{
2305 bl_idname = 'SR_UL_ROUTE_NODE_LIST'
2306
2307 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2308 #{
2309 layout.prop( item, 'target', text='', emboss=False )
2310 #}
2311 #}
2312
2313 def internal_listdel_execute(self,context,ent_name,collection_name):
2314 #{
2315 active_object = context.active_object
2316 data = getattr(active_object.SR_data,ent_name)[0]
2317 lista = getattr(data,collection_name)
2318 index = getattr(data,F'{collection_name}_index')
2319
2320 lista.remove(index)
2321
2322 setattr(data,F'{collection_name}_index', min(max(0,index-1), len(lista)-1))
2323 return{'FINISHED'}
2324 #}
2325
2326 def internal_listadd_execute(self,context,ent_name,collection_name):
2327 #{
2328 active_object = context.active_object
2329 getattr(getattr(active_object.SR_data,ent_name)[0],collection_name).add()
2330 return{'FINISHED'}
2331 #}
2332
2333 def copy_propgroup( de, to ):
2334 #{
2335 for a in de.__annotations__:#{
2336 if isinstance(getattr(de,a), bpy.types.bpy_prop_collection):#{
2337 ca = getattr(de,a)
2338 cb = getattr(to,a)
2339
2340 while len(cb) != len(ca):#{
2341 if len(cb) < len(ca): cb.add()
2342 else: cb.remove(0)
2343 #}
2344 for i in range(len(ca)):#{
2345 copy_propgroup(ca[i],cb[i])
2346 #}
2347 #}
2348 else:#{
2349 setattr(to,a,getattr(de,a))
2350 #}
2351 #}
2352 #}
2353
2354 class SR_OT_COPY_ENTITY_DATA(bpy.types.Operator):
2355 #{
2356 bl_idname = "skaterift.copy_entity_data"
2357 bl_label = "Copy entity data"
2358
2359 def execute(self, context):#{
2360 data = context.active_object.SR_data
2361 new_type = data.ent_type
2362 print( F"Copy entity data from: {context.active_object.name}" )
2363
2364 for obj in context.selected_objects:#{
2365 if obj != context.active_object:#{
2366 print( F" To: {obj.name}" )
2367
2368 obj.SR_data.ent_type = new_type
2369
2370 if active_object.type == 'MESH':#{
2371 col = getattr( obj.data.SR_data, new_type, None )
2372 if col != None and len(col)==0: col.add()
2373 mdata = context.active_object.data.SR_data
2374 copy_propgroup( getattr(mdata,new_type)[0], col[0] )
2375 #}
2376
2377 col = getattr( obj.SR_data, new_type, None )
2378 if col != None and len(col)==0: col.add()
2379 copy_propgroup( getattr(data,new_type)[0], col[0] )
2380 #}
2381 #}
2382 return{'FINISHED'}
2383 #}
2384 #}
2385
2386 class SR_OT_ROUTE_LIST_NEW_ITEM(bpy.types.Operator):
2387 #{
2388 bl_idname = "skaterift.new_entry"
2389 bl_label = "Add gate"
2390
2391 def execute(self, context):#{
2392 return internal_listadd_execute(self,context,'ent_route','gates')
2393 #}
2394 #}
2395
2396 class SR_OT_ROUTE_LIST_DEL_ITEM(bpy.types.Operator):
2397 #{
2398 bl_idname = "skaterift.del_entry"
2399 bl_label = "Remove gate"
2400
2401 @classmethod
2402 def poll(cls, context):#{
2403 active_object = context.active_object
2404 if obj_ent_type(active_object) == 'ent_route':#{
2405 return active_object.SR_data.ent_route[0].gates
2406 #}
2407 else: return False
2408 #}
2409
2410 def execute(self, context):#{
2411 return internal_listdel_execute(self,context,'ent_route','gates')
2412 #}
2413 #}
2414
2415 class SR_OT_AUDIO_LIST_NEW_ITEM(bpy.types.Operator):
2416 #{
2417 bl_idname = "skaterift.al_new_entry"
2418 bl_label = "Add file"
2419
2420 def execute(self, context):#{
2421 return internal_listadd_execute(self,context,'ent_audio','files')
2422 #}
2423 #}
2424
2425 class SR_OT_AUDIO_LIST_DEL_ITEM(bpy.types.Operator):
2426 #{
2427 bl_idname = "skaterift.al_del_entry"
2428 bl_label = "Remove file"
2429
2430 @classmethod
2431 def poll(cls, context):#{
2432 active_object = context.active_object
2433 if obj_ent_type(active_object) == 'ent_audio':#{
2434 return active_object.SR_data.ent_audio[0].files
2435 #}
2436 else: return False
2437 #}
2438
2439 def execute(self, context):#{
2440 return internal_listdel_execute(self,context,'ent_audio','files')
2441 return{'FINISHED'}
2442 #}
2443 #}
2444
2445 class SR_OT_GLYPH_LIST_NEW_ITEM(bpy.types.Operator):
2446 #{
2447 bl_idname = "skaterift.gl_new_entry"
2448 bl_label = "Add glyph"
2449
2450 def execute(self, context):#{
2451 active_object = context.active_object
2452
2453 font = active_object.SR_data.ent_font[0]
2454 font.glyphs.add()
2455
2456 if len(font.glyphs) > 1:#{
2457 prev = font.glyphs[-2]
2458 cur = font.glyphs[-1]
2459
2460 cur.bounds = prev.bounds
2461 cur.utf32 = prev.utf32+1
2462 #}
2463
2464 return{'FINISHED'}
2465 #}
2466 #}
2467
2468 class SR_OT_GLYPH_LIST_DEL_ITEM(bpy.types.Operator):
2469 #{
2470 bl_idname = "skaterift.gl_del_entry"
2471 bl_label = "Remove Glyph"
2472
2473 @classmethod
2474 def poll(cls, context):#{
2475 active_object = context.active_object
2476 if obj_ent_type(active_object) == 'ent_font':#{
2477 return active_object.SR_data.ent_font[0].glyphs
2478 #}
2479 else: return False
2480 #}
2481
2482 def execute(self, context):#{
2483 return internal_listdel_execute(self,context,'ent_font','glyphs')
2484 #}
2485 #}
2486
2487 class SR_OT_GLYPH_LIST_MOVE_ITEM(bpy.types.Operator):
2488 #{
2489 bl_idname = "skaterift.gl_move_item"
2490 bl_label = "aa"
2491 direction: bpy.props.EnumProperty(items=(('UP', 'Up', ""),
2492 ('DOWN', 'Down', ""),))
2493
2494 @classmethod
2495 def poll(cls, context):#{
2496 active_object = context.active_object
2497 if obj_ent_type(active_object) == 'ent_font':#{
2498 return active_object.SR_data.ent_font[0].glyphs
2499 #}
2500 else: return False
2501 #}
2502
2503 def execute(_, context):#{
2504 active_object = context.active_object
2505 data = active_object.SR_data.ent_font[0]
2506
2507 index = data.glyphs_index
2508 neighbor = index + (-1 if _.direction == 'UP' else 1)
2509 data.glyphs.move( neighbor, index )
2510
2511 list_length = len(data.glyphs) - 1
2512 new_index = index + (-1 if _.direction == 'UP' else 1)
2513
2514 data.glyphs_index = max(0, min(new_index, list_length))
2515
2516 return{'FINISHED'}
2517 #}
2518 #}
2519
2520 class SR_OT_FONT_VARIANT_LIST_NEW_ITEM(bpy.types.Operator):
2521 #{
2522 bl_idname = "skaterift.fv_new_entry"
2523 bl_label = "Add variant"
2524
2525 def execute(self, context):#{
2526 return internal_listadd_execute(self,context,'ent_font','variants')
2527 #}
2528 #}
2529
2530 class SR_OT_FONT_VARIANT_LIST_DEL_ITEM(bpy.types.Operator):
2531 #{
2532 bl_idname = "skaterift.fv_del_entry"
2533 bl_label = "Remove variant"
2534
2535 @classmethod
2536 def poll(cls, context):#{
2537 active_object = context.active_object
2538 if obj_ent_type(active_object) == 'ent_font':#{
2539 return active_object.SR_data.ent_font[0].variants
2540 #}
2541 else: return False
2542 #}
2543
2544 def execute(self, context):#{
2545 return internal_listdel_execute(self,context,'ent_font','variants')
2546 #}
2547 #}
2548
2549 class SR_OBJECT_ENT_AUDIO_FILE_ENTRY(bpy.types.PropertyGroup):
2550 #{
2551 path: bpy.props.StringProperty( name="Path" )
2552 probability: bpy.props.FloatProperty( name="Probability",default=100.0 )
2553 #}
2554
2555 class SR_UL_AUDIO_LIST(bpy.types.UIList):
2556 #{
2557 bl_idname = 'SR_UL_AUDIO_LIST'
2558
2559 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2560 #{
2561 split = layout.split(factor=0.7)
2562 c = split.column()
2563 c.prop( item, 'path', text='', emboss=False )
2564 c = split.column()
2565 c.prop( item, 'probability', text='%', emboss=True )
2566 #}
2567 #}
2568
2569 class SR_UL_FONT_VARIANT_LIST(bpy.types.UIList):
2570 #{
2571 bl_idname = 'SR_UL_FONT_VARIANT_LIST'
2572
2573 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2574 #{
2575 layout.prop( item, 'mesh', emboss=False )
2576 layout.prop( item, 'tipo' )
2577 #}
2578 #}
2579
2580 class SR_UL_FONT_GLYPH_LIST(bpy.types.UIList):
2581 #{
2582 bl_idname = 'SR_UL_FONT_GLYPH_LIST'
2583
2584 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
2585 #{
2586 s0 = layout.split(factor=0.3)
2587 c = s0.column()
2588 s1 = c.split(factor=0.3)
2589 c = s1.column()
2590 row = c.row()
2591 lbl = chr(item.utf32) if item.utf32 >= 32 and item.utf32 <= 126 else \
2592 f'x{item.utf32:x}'
2593 row.label(text=lbl)
2594 c = s1.column()
2595 c.prop( item, 'utf32', text='', emboss=True )
2596 c = s0.column()
2597 row = c.row()
2598 row.prop( item, 'bounds', text='', emboss=False )
2599 #}
2600 #}
2601
2602 class SR_OBJECT_ENT_ROUTE(bpy.types.PropertyGroup):
2603 #{
2604 gates: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE_ENTRY)
2605 gates_index: bpy.props.IntProperty()
2606
2607 colour: bpy.props.FloatVectorProperty( \
2608 name="Colour",\
2609 subtype='COLOR',\
2610 min=0.0,max=1.0,\
2611 default=Vector((0.79,0.63,0.48)),\
2612 description="Route colour"\
2613 )
2614
2615 alias: bpy.props.StringProperty(\
2616 name="Alias",\
2617 default="Untitled Course")
2618
2619 @staticmethod
2620 def sr_inspector( layout, data ):
2621 #{
2622 layout.prop( data[0], 'alias' )
2623 layout.prop( data[0], 'colour' )
2624
2625 layout.label( text='Checkpoints' )
2626 layout.template_list('SR_UL_ROUTE_NODE_LIST', 'Checkpoints', \
2627 data[0], 'gates', data[0], 'gates_index', rows=5)
2628
2629 row = layout.row()
2630 row.operator( 'skaterift.new_entry', text='Add' )
2631 row.operator( 'skaterift.del_entry', text='Remove' )
2632 #}
2633 #}
2634
2635 class SR_OBJECT_ENT_VOLUME(bpy.types.PropertyGroup):
2636 #{
2637 subtype: bpy.props.EnumProperty(
2638 name="Subtype",
2639 items=[('0','Trigger',''),
2640 ('1','Particles (0.1s)','')]
2641 )
2642
2643 target: bpy.props.PointerProperty( \
2644 type=bpy.types.Object, name="Target", \
2645 poll=lambda self,obj: sr_filter_ent_type(obj,\
2646 ['ent_audio','ent_skateshop']))
2647
2648 @staticmethod
2649 def sr_inspector( layout, data ):
2650 #{
2651 data = data[0]
2652 layout.prop( data, 'subtype' )
2653 layout.prop( data, 'target' )
2654 #}
2655 #}
2656
2657 class SR_OBJECT_ENT_AUDIO(bpy.types.PropertyGroup):
2658 #{
2659 files: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO_FILE_ENTRY)
2660 files_index: bpy.props.IntProperty()
2661
2662 flag_3d: bpy.props.BoolProperty( name="3D audio",default=True )
2663 flag_loop: bpy.props.BoolProperty( name="Loop",default=False )
2664 flag_auto: bpy.props.BoolProperty( name="Play at start",default=False )
2665 flag_nodoppler: bpy.props.BoolProperty( name="No Doppler",default=False )
2666
2667 group: bpy.props.IntProperty( name="Group ID", default=0 )
2668 formato: bpy.props.EnumProperty(
2669 name="Format",
2670 items=[('0','Uncompressed Mono',''),
2671 ('1','Compressed Vorbis',''),
2672 ('2','[vg] Bird Synthesis','')]
2673 )
2674 probability_curve: bpy.props.EnumProperty(
2675 name="Probability Curve",
2676 items=[('0','Constant',''),
2677 ('1','Wildlife Daytime',''),
2678 ('2','Wildlife Nighttime','')])
2679 channel_behaviour: bpy.props.EnumProperty(
2680 name="Channel Behaviour",
2681 items=[('0','Unlimited',''),
2682 ('1','Discard if group full', ''),
2683 ('2','Crossfade if group full','')])
2684
2685 transition_duration: bpy.props.FloatProperty(name="Transition Time",\
2686 default=0.2)
2687
2688 max_channels: bpy.props.IntProperty( name="Max Channels", default=1 )
2689 volume: bpy.props.FloatProperty( name="Volume",default=1.0 )
2690
2691 @staticmethod
2692 def sr_inspector( layout, data ):
2693 #{
2694 layout.prop( data[0], 'formato' )
2695 layout.prop( data[0], 'volume' )
2696
2697 box = layout.box()
2698 box.label( text='Channels' )
2699 split = box.split(factor=0.3)
2700 c = split.column()
2701 c.prop( data[0], 'max_channels' )
2702 c = split.column()
2703 c.prop( data[0], 'channel_behaviour', text='Behaviour' )
2704 if data[0].channel_behaviour >= '1':
2705 box.prop( data[0], 'group' )
2706 if data[0].channel_behaviour == '2':
2707 box.prop( data[0], 'transition_duration' )
2708
2709 box = layout.box()
2710 box.label( text='Flags' )
2711 box.prop( data[0], 'flag_3d' )
2712 if data[0].flag_3d: box.prop( data[0], 'flag_nodoppler' )
2713
2714 box.prop( data[0], 'flag_loop' )
2715 box.prop( data[0], 'flag_auto' )
2716
2717 split = layout.split(factor=0.7)
2718 c = split.column()
2719 c.label( text='Filepath' )
2720 c = split.column()
2721 c.label( text='Chance (0.1s)' )
2722
2723 layout.prop( data[0], 'probability_curve' )
2724
2725 layout.template_list('SR_UL_AUDIO_LIST', 'Files', \
2726 data[0], 'files', data[0], 'file_index', rows=5)
2727
2728 row = layout.row()
2729 row.operator( 'skaterift.al_new_entry', text='Add' )
2730 row.operator( 'skaterift.al_del_entry', text='Remove' )
2731 #}
2732 #}
2733
2734 class SR_OBJECT_ENT_MARKER(bpy.types.PropertyGroup):
2735 #{
2736 alias: bpy.props.StringProperty()
2737 #}
2738
2739 class SR_OBJECT_ENT_GLYPH(bpy.types.PropertyGroup):
2740 #{
2741 mini: bpy.props.FloatVectorProperty(size=2)
2742 maxi: bpy.props.FloatVectorProperty(size=2)
2743 utf32: bpy.props.IntProperty()
2744 #}
2745
2746 class SR_OBJECT_ENT_GLYPH_ENTRY(bpy.types.PropertyGroup):
2747 #{
2748 bounds: bpy.props.FloatVectorProperty(size=4,subtype='NONE')
2749 utf32: bpy.props.IntProperty()
2750 #}
2751
2752 class SR_OBJECT_ENT_FONT_VARIANT(bpy.types.PropertyGroup):
2753 #{
2754 mesh: bpy.props.PointerProperty(type=bpy.types.Object)
2755 tipo: bpy.props.StringProperty()
2756 #}
2757
2758 class SR_OBJECT_ENT_FONT(bpy.types.PropertyGroup):
2759 #{
2760 variants: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_FONT_VARIANT)
2761 glyphs: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GLYPH_ENTRY)
2762 alias: bpy.props.StringProperty()
2763
2764 glyphs_index: bpy.props.IntProperty()
2765 variants_index: bpy.props.IntProperty()
2766
2767 @staticmethod
2768 def sr_inspector( layout, data ):
2769 #{
2770 layout.prop( data[0], 'alias' )
2771
2772 layout.label( text='Variants' )
2773 layout.template_list('SR_UL_FONT_VARIANT_LIST', 'Variants', \
2774 data[0], 'variants', data[0], 'variants_index',\
2775 rows=5 )
2776 row = layout.row()
2777 row.operator( 'skaterift.fv_new_entry', text='Add' )
2778 row.operator( 'skaterift.fv_del_entry', text='Remove' )
2779
2780 layout.label( text='ASCII Glyphs' )
2781 layout.template_list('SR_UL_FONT_GLYPH_LIST', 'Glyphs', \
2782 data[0], 'glyphs', data[0], 'glyphs_index', rows=5)
2783
2784 row = layout.row()
2785 row.operator( 'skaterift.gl_new_entry', text='Add' )
2786 row.operator( 'skaterift.gl_del_entry', text='Remove' )
2787 row.operator( 'skaterift.gl_move_item', text='^' ).direction='UP'
2788 row.operator( 'skaterift.gl_move_item', text='v' ).direction='DOWN'
2789 #}
2790 #}
2791
2792 class SR_OBJECT_ENT_TRAFFIC(bpy.types.PropertyGroup):
2793 #{
2794 speed: bpy.props.FloatProperty(default=1.0)
2795 #}
2796
2797 class SR_OBJECT_ENT_SKATESHOP(bpy.types.PropertyGroup):
2798 #{
2799 tipo: bpy.props.EnumProperty( name='Type',
2800 items=[('0','boards',''),
2801 ('1','character','')] )
2802 mark_rack: bpy.props.PointerProperty( \
2803 type=bpy.types.Object, name="Board Rack", \
2804 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2805 mark_display: bpy.props.PointerProperty( \
2806 type=bpy.types.Object, name="Selected Board Display", \
2807 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2808 mark_info: bpy.props.PointerProperty( \
2809 type=bpy.types.Object, name="Selected Board Info", \
2810 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2811 cam: bpy.props.PointerProperty( \
2812 type=bpy.types.Object, name="Viewpoint", \
2813 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_camera']))
2814 #}
2815
2816 class SR_OBJECT_ENT_WORKSHOP_PREVIEW(bpy.types.PropertyGroup):
2817 #{
2818 mark_display: bpy.props.PointerProperty( \
2819 type=bpy.types.Object, name="Board Display", \
2820 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2821 mark_display1: bpy.props.PointerProperty( \
2822 type=bpy.types.Object, name="Board Display (other side)", \
2823 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2824 cam: bpy.props.PointerProperty( \
2825 type=bpy.types.Object, name="Viewpoint", \
2826 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_camera']))
2827 #}
2828
2829 class SR_OBJECT_ENT_MENU_ITEM(bpy.types.PropertyGroup):
2830 #{
2831 link0: bpy.props.PointerProperty( \
2832 type=bpy.types.Object, name="Link 0", \
2833 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2834 link1: bpy.props.PointerProperty( \
2835 type=bpy.types.Object, name="Link 1", \
2836 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2837 link2: bpy.props.PointerProperty( \
2838 type=bpy.types.Object, name="Link 2", \
2839 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2840 link3: bpy.props.PointerProperty( \
2841 type=bpy.types.Object, name="Link 3", \
2842 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2843
2844 newloc: bpy.props.PointerProperty( \
2845 type=bpy.types.Object, name="New location", \
2846 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2847 camera: bpy.props.PointerProperty( \
2848 type=bpy.types.Object, name="Camera", \
2849 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_camera']))
2850
2851 slider_minloc: bpy.props.PointerProperty( \
2852 type=bpy.types.Object, name="Slider min", \
2853 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2854 slider_maxloc: bpy.props.PointerProperty( \
2855 type=bpy.types.Object, name="Slider max", \
2856 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_marker']))
2857 slider_handle: bpy.props.PointerProperty( \
2858 type=bpy.types.Object, name="Slider handle", \
2859 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2860
2861 checkmark: bpy.props.PointerProperty( \
2862 type=bpy.types.Object, name="Checked", \
2863 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_menuitem']))
2864
2865 string: bpy.props.StringProperty( name="String" )
2866 tipo: bpy.props.EnumProperty( name='Type',
2867 items=[('0','visual',''),
2868 ('1','event button',''),
2869 ('2','page button',''),
2870 ('3','toggle', ''),
2871 ('4','slider',''),
2872 ('5','page','')])
2873
2874 @staticmethod
2875 def sr_inspector( layout, data ):
2876 #{
2877 data = data[0]
2878 box = layout.box()
2879 box.prop( data, 'tipo' )
2880
2881 if data.tipo == '0':#{
2882 return
2883 #}
2884 elif data.tipo == '1':#{
2885 box.prop( data, 'string', text='Event' )
2886 #}
2887 elif data.tipo == '2':#{
2888 box.prop( data, 'string', text='Page' )
2889 box.prop( data, 'newloc' )
2890 #}
2891 elif data.tipo == '3':#{
2892 box.prop( data, 'string', text='Data (i32)' )
2893 box.prop( data, 'checkmark' )
2894 #}
2895 elif data.tipo == '4':#{
2896 box.prop( data, 'string', text='Data (f32)' )
2897 box.prop( data, 'slider_minloc' )
2898 box.prop( data, 'slider_maxloc' )
2899 box.prop( data, 'slider_handle' )
2900 box = box.box()
2901 box.label( text="Links" )
2902 box.prop( data, 'link0', text='v0' )
2903 box.prop( data, 'link1', text='v1' )
2904 return
2905 #}
2906 elif data.tipo == '5':#{
2907 box.prop( data, 'string', text='Page Name' )
2908 box.prop( data, 'newloc', text='Entry Point' )
2909 box.prop( data, 'camera', text='Viewpoint' )
2910 return
2911 #}
2912
2913 box = box.box()
2914 box.label( text="Links" )
2915 box.prop( data, 'link0' )
2916 box.prop( data, 'link1' )
2917 box.prop( data, 'link2' )
2918 box.prop( data, 'link3' )
2919 #}
2920 #}
2921
2922 class SR_OBJECT_PROPERTIES(bpy.types.PropertyGroup):
2923 #{
2924 ent_gate: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GATE)
2925 ent_spawn: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SPAWN)
2926 ent_route: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE)
2927 ent_volume: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_VOLUME)
2928 ent_audio: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO)
2929 ent_marker: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_MARKER)
2930 ent_glyph: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GLYPH)
2931 ent_font: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_FONT)
2932 ent_traffic: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_TRAFFIC)
2933 ent_skateshop: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SKATESHOP)
2934 ent_swspreview: \
2935 bpy.props.CollectionProperty(type=SR_OBJECT_ENT_WORKSHOP_PREVIEW)
2936 ent_menuitem: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_MENU_ITEM)
2937
2938 ent_type: bpy.props.EnumProperty(
2939 name="Type",
2940 items=sr_entity_list,
2941 update=sr_on_type_change
2942 )
2943 #}
2944
2945 class SR_MESH_PROPERTIES(bpy.types.PropertyGroup):
2946 #{
2947 ent_gate: bpy.props.CollectionProperty(type=SR_MESH_ENT_GATE)
2948 #}
2949
2950 class SR_LIGHT_PROPERTIES(bpy.types.PropertyGroup):
2951 #{
2952 daytime: bpy.props.BoolProperty( name='Daytime' )
2953 #}
2954
2955 class SR_BONE_PROPERTIES(bpy.types.PropertyGroup):
2956 #{
2957 collider: bpy.props.EnumProperty( name='Collider Type',
2958 items=[('0','none',''),
2959 ('1','box',''),
2960 ('2','capsule','')])
2961
2962 collider_min: bpy.props.FloatVectorProperty( name='Collider Min', size=3 )
2963 collider_max: bpy.props.FloatVectorProperty( name='Collider Max', size=3 )
2964
2965 cone_constraint: bpy.props.BoolProperty( name='Cone constraint' )
2966
2967 conevx: bpy.props.FloatVectorProperty( name='vx' )
2968 conevy: bpy.props.FloatVectorProperty( name='vy' )
2969 coneva: bpy.props.FloatVectorProperty( name='va' )
2970 conet: bpy.props.FloatProperty( name='t' )
2971
2972 @staticmethod
2973 def sr_inspector( layout, data ):
2974 #{
2975 data = data[0]
2976 box = layout.box()
2977 box.prop( data, 'collider' )
2978
2979 if int(data.collider)>0:#{
2980 row = box.row()
2981 row.prop( data, 'collider_min' )
2982 row = box.row()
2983 row.prop( data, 'collider_max' )
2984 #}
2985
2986 box = layout.box()
2987 box.prop( data, 'cone_constraint' )
2988 if data.cone_constraint:#{
2989 row = box.row()
2990 row.prop( data, 'conevx' )
2991 row = box.row()
2992 row.prop( data, 'conevy' )
2993 row = box.row()
2994 row.prop( data, 'coneva' )
2995 box.prop( data, 'conet' )
2996 #}
2997 #}
2998 #}
2999
3000 class SR_MATERIAL_PROPERTIES(bpy.types.PropertyGroup):
3001 #{
3002 shader: bpy.props.EnumProperty(
3003 name="Format",
3004 items = [
3005 ('standard',"standard",''),
3006 ('standard_cutout', "standard_cutout", ''),
3007 ('terrain_blend', "terrain_blend", ''),
3008 ('vertex_blend', "vertex_blend", ''),
3009 ('water',"water",''),
3010 ('invisible','Invisible',''),
3011 ('boundary','Boundary','')
3012 ])
3013
3014 surface_prop: bpy.props.EnumProperty(
3015 name="Surface Property",
3016 items = [
3017 ('0','concrete',''),
3018 ('1','wood',''),
3019 ('2','grass',''),
3020 ('3','tiles',''),
3021 ('4','metal','')
3022 ])
3023
3024 collision: bpy.props.BoolProperty( \
3025 name="Collisions Enabled",\
3026 default=True,\
3027 description = "Can the player collide with this material?"\
3028 )
3029 skate_surface: bpy.props.BoolProperty( \
3030 name="Skate Target", \
3031 default=True,\
3032 description = "Should the game try to target this surface?" \
3033 )
3034 grind_surface: bpy.props.BoolProperty( \
3035 name="Grindable", \
3036 default=True,\
3037 description = "Can you grind on this surface?" \
3038 )
3039 grow_grass: bpy.props.BoolProperty( \
3040 name="Grow Grass", \
3041 default=False,\
3042 description = "Spawn grass sprites on this surface?" \
3043 )
3044 blend_offset: bpy.props.FloatVectorProperty( \
3045 name="Blend Offset", \
3046 size=2, \
3047 default=Vector((0.5,0.0)),\
3048 description="When surface is more than 45 degrees, add this vector " +\
3049 "to the UVs" \
3050 )
3051 sand_colour: bpy.props.FloatVectorProperty( \
3052 name="Sand Colour",\
3053 subtype='COLOR',\
3054 min=0.0,max=1.0,\
3055 default=Vector((0.79,0.63,0.48)),\
3056 description="Blend to this colour near the 0 coordinate on UP axis"\
3057 )
3058 shore_colour: bpy.props.FloatVectorProperty( \
3059 name="Shore Colour",\
3060 subtype='COLOR',\
3061 min=0.0,max=1.0,\
3062 default=Vector((0.03,0.32,0.61)),\
3063 description="Water colour at the shoreline"\
3064 )
3065 ocean_colour: bpy.props.FloatVectorProperty( \
3066 name="Ocean Colour",\
3067 subtype='COLOR',\
3068 min=0.0,max=1.0,\
3069 default=Vector((0.0,0.006,0.03)),\
3070 description="Water colour in the deep bits"\
3071 )
3072 #}
3073
3074 # ---------------------------------------------------------------------------- #
3075 # #
3076 # GUI section #
3077 # #
3078 # ---------------------------------------------------------------------------- #
3079
3080 cv_view_draw_handler = None
3081 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
3082 cv_view_verts = []
3083 cv_view_colours = []
3084 cv_view_course_i = 0
3085
3086 # Draw axis alligned sphere at position with radius
3087 #
3088 def cv_draw_sphere( pos, radius, colour ):
3089 #{
3090 global cv_view_verts, cv_view_colours
3091
3092 ly = pos + Vector((0,0,radius))
3093 lx = pos + Vector((0,radius,0))
3094 lz = pos + Vector((0,0,radius))
3095
3096 pi = 3.14159265358979323846264
3097
3098 for i in range(16):#{
3099 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
3100 s = math.sin(t)
3101 c = math.cos(t)
3102
3103 py = pos + Vector((s*radius,0.0,c*radius))
3104 px = pos + Vector((s*radius,c*radius,0.0))
3105 pz = pos + Vector((0.0,s*radius,c*radius))
3106
3107 cv_view_verts += [ px, lx ]
3108 cv_view_verts += [ py, ly ]
3109 cv_view_verts += [ pz, lz ]
3110
3111 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
3112
3113 ly = py
3114 lx = px
3115 lz = pz
3116 #}
3117 cv_draw_lines()
3118 #}
3119
3120 # Draw axis alligned sphere at position with radius
3121 #
3122 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
3123 #{
3124 global cv_view_verts, cv_view_colours
3125
3126 ly = pos + tz*radius
3127 lx = pos + ty*radius
3128 lz = pos + tz*radius
3129
3130 pi = 3.14159265358979323846264
3131
3132 for i in range(16):#{
3133 t = ((i+1.0) * 1.0/16.0) * pi
3134 s = math.sin(t)
3135 c = math.cos(t)
3136
3137 s1 = math.sin(t*2.0)
3138 c1 = math.cos(t*2.0)
3139
3140 py = pos + s*tx*radius + c *tz*radius
3141 px = pos + s*tx*radius + c *ty*radius
3142 pz = pos + s1*ty*radius + c1*tz*radius
3143
3144 cv_view_verts += [ px, lx ]
3145 cv_view_verts += [ py, ly ]
3146 cv_view_verts += [ pz, lz ]
3147
3148 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
3149
3150 ly = py
3151 lx = px
3152 lz = pz
3153 #}
3154 cv_draw_lines()
3155 #}
3156
3157 # Draw transformed -1 -> 1 cube
3158 #
3159 def cv_draw_ucube( transform, colour, s=Vector((1,1,1)), o=Vector((0,0,0)) ):
3160 #{
3161 global cv_view_verts, cv_view_colours
3162
3163 a = o + -1.0 * s
3164 b = o + 1.0 * s
3165
3166 vs = [None]*8
3167 vs[0] = transform @ Vector((a[0], a[1], a[2]))
3168 vs[1] = transform @ Vector((a[0], b[1], a[2]))
3169 vs[2] = transform @ Vector((b[0], b[1], a[2]))
3170 vs[3] = transform @ Vector((b[0], a[1], a[2]))
3171 vs[4] = transform @ Vector((a[0], a[1], b[2]))
3172 vs[5] = transform @ Vector((a[0], b[1], b[2]))
3173 vs[6] = transform @ Vector((b[0], b[1], b[2]))
3174 vs[7] = transform @ Vector((b[0], a[1], b[2]))
3175
3176 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
3177 (0,4),(1,5),(2,6),(3,7)]
3178
3179 for l in indices:#{
3180 v0 = vs[l[0]]
3181 v1 = vs[l[1]]
3182 cv_view_verts += [(v0[0],v0[1],v0[2])]
3183 cv_view_verts += [(v1[0],v1[1],v1[2])]
3184 cv_view_colours += [colour, colour]
3185 #}
3186 cv_draw_lines()
3187 #}
3188
3189 # Draw line with colour
3190 #
3191 def cv_draw_line( p0, p1, colour ):
3192 #{
3193 global cv_view_verts, cv_view_colours
3194
3195 cv_view_verts += [p0,p1]
3196 cv_view_colours += [colour, colour]
3197 cv_draw_lines()
3198 #}
3199
3200 # Draw line with colour(s)
3201 #
3202 def cv_draw_line2( p0, p1, c0, c1 ):
3203 #{
3204 global cv_view_verts, cv_view_colours
3205
3206 cv_view_verts += [p0,p1]
3207 cv_view_colours += [c0,c1]
3208 cv_draw_lines()
3209 #}
3210
3211 #
3212 #
3213 def cv_tangent_basis( n, tx, ty ):
3214 #{
3215 if abs( n[0] ) >= 0.57735027:#{
3216 tx[0] = n[1]
3217 tx[1] = -n[0]
3218 tx[2] = 0.0
3219 #}
3220 else:#{
3221 tx[0] = 0.0
3222 tx[1] = n[2]
3223 tx[2] = -n[1]
3224 #}
3225
3226 tx.normalize()
3227 _ty = n.cross( tx )
3228
3229 ty[0] = _ty[0]
3230 ty[1] = _ty[1]
3231 ty[2] = _ty[2]
3232 #}
3233
3234 # Draw coloured arrow
3235 #
3236 def cv_draw_arrow( p0, p1, c0, size=0.15 ):
3237 #{
3238 global cv_view_verts, cv_view_colours
3239
3240 n = p1-p0
3241 midpt = p0 + n*0.5
3242 n.normalize()
3243
3244 tx = Vector((1,0,0))
3245 ty = Vector((1,0,0))
3246 cv_tangent_basis( n, tx, ty )
3247
3248 cv_view_verts += [p0,p1, midpt+(tx-n)*size,midpt, midpt+(-tx-n)*size,midpt ]
3249 cv_view_colours += [c0,c0,c0,c0,c0,c0]
3250 #cv_draw_lines()
3251 #}
3252
3253 def cv_draw_line_dotted( p0, p1, c0, dots=10 ):
3254 #{
3255 global cv_view_verts, cv_view_colours
3256
3257 for i in range(dots):#{
3258 t0 = i/dots
3259 t1 = (i+0.25)/dots
3260
3261 p2 = p0*(1.0-t0)+p1*t0
3262 p3 = p0*(1.0-t1)+p1*t1
3263
3264 cv_view_verts += [p2,p3]
3265 cv_view_colours += [c0,c0]
3266 #}
3267 #cv_draw_lines()
3268 #}
3269
3270 # Drawhandles of a bezier control point
3271 #
3272 def cv_draw_bhandle( obj, direction, colour ):
3273 #{
3274 global cv_view_verts, cv_view_colours
3275
3276 p0 = obj.location
3277 h0 = obj.matrix_world @ Vector((0,direction,0))
3278
3279 cv_view_verts += [p0]
3280 cv_view_verts += [h0]
3281 cv_view_colours += [colour,colour]
3282 cv_draw_lines()
3283 #}
3284
3285 # Draw a bezier curve (at fixed resolution 10)
3286 #
3287 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
3288 #{
3289 global cv_view_verts, cv_view_colours
3290
3291 last = p0
3292 for i in range(10):#{
3293 t = (i+1)/10
3294 a0 = 1-t
3295
3296 tt = t*t
3297 ttt = tt*t
3298 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
3299
3300 cv_view_verts += [(last[0],last[1],last[2])]
3301 cv_view_verts += [(p[0],p[1],p[2])]
3302 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
3303
3304 last = p
3305 #}
3306 cv_draw_lines()
3307 #}
3308
3309 # I think this one extends the handles of the bezier otwards......
3310 #
3311 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
3312 #{
3313 global cv_view_course_i
3314
3315 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
3316
3317 p0 = o0.matrix_world @ Vector((offs, 0,0))
3318 h0 = o0.matrix_world @ Vector((offs, s0,0))
3319 p1 = o1.matrix_world @ Vector((offs, 0,0))
3320 h1 = o1.matrix_world @ Vector((offs,-s1,0))
3321
3322 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
3323 cv_draw_lines()
3324 #}
3325
3326 # Flush the lines buffers. This is called often because god help you if you want
3327 # to do fixed, fast buffers in this catastrophic programming language.
3328 #
3329 def cv_draw_lines():
3330 #{
3331 global cv_view_shader, cv_view_verts, cv_view_colours
3332
3333 if len(cv_view_verts) < 2:
3334 return
3335
3336 lines = batch_for_shader(\
3337 cv_view_shader, 'LINES', \
3338 { "pos":cv_view_verts, "color":cv_view_colours })
3339
3340 lines.draw( cv_view_shader )
3341
3342 cv_view_verts = []
3343 cv_view_colours = []
3344 #}
3345
3346 # I dont remember what this does exactly
3347 #
3348 def cv_draw_bpath( o0,o1,c0,c1 ):
3349 #{
3350 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
3351 #}
3352
3353 # Semi circle to show the limit. and some lines
3354 #
3355 def draw_limit( obj, center, major, minor, amin, amax, colour ):
3356 #{
3357 global cv_view_verts, cv_view_colours
3358 f = 0.05
3359 ay = major*f
3360 ax = minor*f
3361
3362 for x in range(16):#{
3363 t0 = x/16
3364 t1 = (x+1)/16
3365 a0 = amin*(1.0-t0)+amax*t0
3366 a1 = amin*(1.0-t1)+amax*t1
3367
3368 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
3369 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
3370
3371 p0=obj.matrix_world @ p0
3372 p1=obj.matrix_world @ p1
3373 cv_view_verts += [p0,p1]
3374 cv_view_colours += [colour,colour]
3375
3376 if x == 0:#{
3377 cv_view_verts += [p0,center]
3378 cv_view_colours += [colour,colour]
3379 #}
3380 if x == 15:#{
3381 cv_view_verts += [p1,center]
3382 cv_view_colours += [colour,colour]
3383 #}
3384 #}
3385
3386 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
3387 cv_view_colours += [colour,colour]
3388
3389 cv_draw_lines()
3390 #}
3391
3392 # Cone and twist limit
3393 #
3394 def draw_cone_twist( center, vx, vy, va ):
3395 #{
3396 global cv_view_verts, cv_view_colours
3397 axis = vy.cross( vx )
3398 axis.normalize()
3399
3400 size = 0.12
3401
3402 cv_view_verts += [center, center+va*size]
3403 cv_view_colours += [ (1,1,1), (1,1,1) ]
3404
3405 for x in range(32):#{
3406 t0 = (x/32) * math.tau
3407 t1 = ((x+1)/32) * math.tau
3408
3409 c0 = math.cos(t0)
3410 s0 = math.sin(t0)
3411 c1 = math.cos(t1)
3412 s1 = math.sin(t1)
3413
3414 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
3415 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
3416
3417 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
3418 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
3419
3420 cv_view_verts += [center, p0, p0, p1]
3421 cv_view_colours += [ (0,0,0), col0, col0, col1 ]
3422 #}
3423
3424 cv_draw_lines()
3425 #}
3426
3427 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
3428 #
3429 def draw_skeleton_helpers( obj ):
3430 #{
3431 global cv_view_verts, cv_view_colours
3432
3433 if obj.data.pose_position != 'REST':#{
3434 return
3435 #}
3436
3437 for bone in obj.data.bones:#{
3438 c = bone.head_local
3439 a = Vector((bone.SR_data.collider_min[0],
3440 bone.SR_data.collider_min[1],
3441 bone.SR_data.collider_min[2]))
3442 b = Vector((bone.SR_data.collider_max[0],
3443 bone.SR_data.collider_max[1],
3444 bone.SR_data.collider_max[2]))
3445
3446 if bone.SR_data.collider == '1':#{
3447 vs = [None]*8
3448 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
3449 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
3450 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
3451 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
3452 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
3453 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
3454 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
3455 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
3456
3457 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
3458 (0,4),(1,5),(2,6),(3,7)]
3459
3460 for l in indices:#{
3461 v0 = vs[l[0]]
3462 v1 = vs[l[1]]
3463
3464 cv_view_verts += [(v0[0],v0[1],v0[2])]
3465 cv_view_verts += [(v1[0],v1[1],v1[2])]
3466 cv_view_colours += [(0.5,0.5,0.5),(0.5,0.5,0.5)]
3467 #}
3468 #}
3469 elif bone.SR_data.collider == '2':#{
3470 v0 = b-a
3471 major_axis = 0
3472 largest = -1.0
3473
3474 for i in range(3):#{
3475 if abs(v0[i]) > largest:#{
3476 largest = abs(v0[i])
3477 major_axis = i
3478 #}
3479 #}
3480
3481 v1 = Vector((0,0,0))
3482 v1[major_axis] = 1.0
3483
3484 tx = Vector((0,0,0))
3485 ty = Vector((0,0,0))
3486
3487 cv_tangent_basis( v1, tx, ty )
3488 r = (abs(tx.dot( v0 )) + abs(ty.dot( v0 ))) * 0.25
3489 l = v0[ major_axis ] - r*2
3490
3491 p0 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l*-0.5 )
3492 p1 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l* 0.5 )
3493
3494 colour = [0.2,0.2,0.2]
3495 colour[major_axis] = 0.5
3496
3497 cv_draw_halfsphere( p0, -v1, ty, tx, r, colour )
3498 cv_draw_halfsphere( p1, v1, ty, tx, r, colour )
3499 cv_draw_line( p0+tx* r, p1+tx* r, colour )
3500 cv_draw_line( p0+tx*-r, p1+tx*-r, colour )
3501 cv_draw_line( p0+ty* r, p1+ty* r, colour )
3502 cv_draw_line( p0+ty*-r, p1+ty*-r, colour )
3503 #}
3504 else:#{
3505 continue
3506 #}
3507
3508 center = obj.matrix_world @ c
3509 if bone.SR_data.cone_constraint:#{
3510 vx = Vector([bone.SR_data.conevx[_] for _ in range(3)])
3511 vy = Vector([bone.SR_data.conevy[_] for _ in range(3)])
3512 va = Vector([bone.SR_data.coneva[_] for _ in range(3)])
3513 draw_cone_twist( center, vx, vy, va )
3514 #}
3515 #}
3516 #}
3517
3518 def cv_ent_gate( obj ):
3519 #{
3520 global cv_view_verts, cv_view_colours
3521
3522 if obj.type != 'MESH': return
3523
3524 mesh_data = obj.data.SR_data.ent_gate[0]
3525 data = obj.SR_data.ent_gate[0]
3526 dims = mesh_data.dimensions
3527
3528 vs = [None]*9
3529 c = Vector((0,0,dims[2]))
3530
3531 vs[0] = obj.matrix_world @ Vector((-dims[0],0.0,-dims[1]+dims[2]))
3532 vs[1] = obj.matrix_world @ Vector((-dims[0],0.0, dims[1]+dims[2]))
3533 vs[2] = obj.matrix_world @ Vector(( dims[0],0.0, dims[1]+dims[2]))
3534 vs[3] = obj.matrix_world @ Vector(( dims[0],0.0,-dims[1]+dims[2]))
3535 vs[4] = obj.matrix_world @ (c+Vector((-1,0,-2)))
3536 vs[5] = obj.matrix_world @ (c+Vector((-1,0, 2)))
3537 vs[6] = obj.matrix_world @ (c+Vector(( 1,0, 2)))
3538 vs[7] = obj.matrix_world @ (c+Vector((-1,0, 0)))
3539 vs[8] = obj.matrix_world @ (c+Vector(( 1,0, 0)))
3540
3541 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
3542
3543 r3d = bpy.context.area.spaces.active.region_3d
3544
3545 p0 = r3d.view_matrix.inverted().translation
3546 v0 = (obj.matrix_world@Vector((0,0,0))) - p0
3547 v1 = obj.matrix_world.to_3x3() @ Vector((0,1,0))
3548
3549 if v0.dot(v1) > 0.0: cc = (0,1,0)
3550 else: cc = (1,0,0)
3551
3552 for l in indices:#{
3553 v0 = vs[l[0]]
3554 v1 = vs[l[1]]
3555 cv_view_verts += [(v0[0],v0[1],v0[2])]
3556 cv_view_verts += [(v1[0],v1[1],v1[2])]
3557 cv_view_colours += [cc,cc]
3558 #}
3559
3560 sw = (0.4,0.4,0.4)
3561 if data.target != None:
3562 cv_draw_arrow( obj.location, data.target.location, sw )
3563 #}
3564
3565 def cv_ent_volume( obj ):
3566 #{
3567 global cv_view_verts, cv_view_colours
3568
3569 data = obj.SR_data.ent_volume[0]
3570
3571 if data.subtype == '0':#{
3572 cv_draw_ucube( obj.matrix_world, (0,1,0) )
3573
3574 if data.target:#{
3575 cv_draw_line( obj.location, data.target.location, (0,1,0) )
3576 #}
3577 #}
3578 elif data.subtype == '1':#{
3579 cv_draw_ucube( obj.matrix_world, (1,1,0) )
3580
3581 if data.target:#{
3582 cv_draw_line( obj.location, data.target.location, (1,1,0) )
3583 #}
3584 #}
3585 #}
3586
3587 def dijkstra( graph, start_node, target_node ):
3588 #{
3589 unvisited = [_ for _ in graph]
3590 shortest_path = {}
3591 previous_nodes = {}
3592
3593 for n in unvisited:
3594 shortest_path[n] = 9999999.999999
3595 shortest_path[start_node] = 0
3596
3597 while unvisited:#{
3598 current_min_node = None
3599 for n in unvisited:#{
3600 if current_min_node == None:
3601 current_min_node = n
3602 elif shortest_path[n] < shortest_path[current_min_node]:
3603 current_min_node = n
3604 #}
3605
3606 for branch in graph[current_min_node]:#{
3607 tentative_value = shortest_path[current_min_node]
3608 tentative_value += graph[current_min_node][branch]
3609 if tentative_value < shortest_path[branch]:#{
3610 shortest_path[branch] = tentative_value
3611 previous_nodes[branch] = current_min_node
3612 #}
3613 #}
3614
3615 unvisited.remove(current_min_node)
3616 #}
3617
3618 path = []
3619 node = target_node
3620 while node != start_node:#{
3621 path.append(node)
3622
3623 if node not in previous_nodes: return None
3624 node = previous_nodes[node]
3625 #}
3626
3627 # Add the start node manually
3628 path.append(start_node)
3629 return path
3630 #}
3631
3632 class dij_graph():
3633 #{
3634 def __init__(_,points,graph,subsections):#{
3635 _.points = points
3636 _.graph = graph
3637 _.subsections = subsections
3638 #}
3639 #}
3640
3641 def create_node_graph( curves, gates ):
3642 #{
3643 # add endpoints of curves
3644 graph = {}
3645 route_points = []
3646 subsections = []
3647 point_count = 0
3648 spline_count = 0
3649
3650 for c in range(len(curves)):#{
3651 for s in range(len(curves[c].data.splines)):#{
3652 spline = curves[c].data.splines[s]
3653 l = len(spline.points)
3654 if l < 2: continue
3655
3656 dist = round(spline.calc_length(),2)
3657
3658 ia = point_count
3659 ib = point_count+l-1
3660
3661 graph[ia] = { ib: dist }
3662 graph[ib] = { ia: dist }
3663
3664 for i in range(len(spline.points)):#{
3665 wco = curves[c].matrix_world @ spline.points[i].co
3666 route_points.append(Vector((wco[0],wco[1],wco[2]+0.5)))
3667
3668 previous = ia+i-1
3669 proxima = ia+i+1
3670
3671 if i == 0: previous = -1
3672 if i == len(spline.points)-1: proxima = -1
3673
3674 subsections.append((spline_count,previous,proxima))
3675 point_count += 1
3676 #}
3677
3678 spline_count += 1
3679 #}
3680 #}
3681
3682 # link endpoints
3683 graph_keys = list(graph)
3684 for i in range(len(graph_keys)-1):#{
3685 for j in range(i+1, len(graph_keys)):#{
3686 if i%2==0 and i+1==j: continue
3687
3688 ni = graph_keys[i]
3689 nj = graph_keys[j]
3690 pi = route_points[ni]
3691 pj = route_points[nj]
3692
3693 dist = round((pj-pi).magnitude,2)
3694
3695 if dist < 10.0:#{
3696 graph[ni][nj] = dist
3697 graph[nj][ni] = dist
3698 #}
3699 #}
3700 #}
3701
3702 # add and link gates( by name )
3703 for gate in gates:#{
3704 v1 = gate.matrix_world.to_3x3() @ Vector((0,1,0))
3705 if gate.SR_data.ent_gate[0].target:
3706 v1 = v1 * -1.0
3707
3708 graph[ gate.name ] = {}
3709
3710 for i in range(len(graph_keys)):#{
3711 ni = graph_keys[i]
3712 pi = route_points[ni]
3713
3714 v0 = pi-gate.location
3715 if v0.dot(v1) < 0.0: continue
3716
3717 dist = round(v0.magnitude,2)
3718
3719 if dist < 10.0:#{
3720 graph[ gate.name ][ ni ] = dist
3721 graph[ ni ][ gate.name ] = dist
3722 #}
3723 #}
3724 #}
3725
3726 return dij_graph(route_points,graph,subsections)
3727 #}
3728
3729 def solve_graph( dij, start, end ):
3730 #{
3731 path = dijkstra( dij.graph, end, start )
3732 full = []
3733
3734 if path:#{
3735 for sj in range(1,len(path)-2):#{
3736 i0 = path[sj]
3737 i1 = path[sj+1]
3738 map0 = dij.subsections[i0]
3739 map1 = dij.subsections[i1]
3740
3741 if map0[0] == map1[0]:#{
3742 if map0[1] == -1: direction = 2
3743 else: direction = 1
3744 sent = 0
3745
3746 while True:#{
3747 map0 = dij.subsections[i0]
3748 i1 = map0[direction]
3749 if i1 == -1: break
3750
3751 full.append( i0 )
3752 sent += 1
3753 i0 = i1
3754 if sent > 50: break
3755 #}
3756 #}
3757 else:#{
3758 full.append( i0 )
3759 #}
3760 #}
3761
3762 full.append( path[-2] )
3763 #}
3764 return full
3765 #}
3766
3767 def cv_draw_route( route, dij ):
3768 #{
3769 pole = Vector((0.2,0.2,10))
3770 hat = Vector((1,8,0.2))
3771 cc = (route.SR_data.ent_route[0].colour[0],
3772 route.SR_data.ent_route[0].colour[1],
3773 route.SR_data.ent_route[0].colour[2])
3774
3775 cv_draw_ucube(route.matrix_world,cc,Vector((0.5,-7.5,6)),\
3776 Vector((0,-6.5,5.5)))
3777 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5, 0.5,0)) )
3778 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5,-13.5,0)) )
3779 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5, 12)) )
3780 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5,-1)) )
3781
3782 checkpoints = route.SR_data.ent_route[0].gates
3783
3784 for i in range(len(checkpoints)):#{
3785 gi = checkpoints[i].target
3786 gj = checkpoints[(i+1)%len(checkpoints)].target
3787
3788 if gi:#{
3789 dest = gi.SR_data.ent_gate[0].target
3790 if dest:
3791 cv_draw_line_dotted( gi.location, dest.location, cc )
3792 gi = dest
3793 #}
3794
3795 if gi==gj: continue # error?
3796 if not gi or not gj: continue
3797
3798 path = solve_graph( dij, gi.name, gj.name )
3799
3800 if path:#{
3801 cv_draw_arrow(gi.location,dij.points[path[0]],cc,1.5)
3802 cv_draw_arrow(dij.points[path[len(path)-1]],gj.location,cc,1.5)
3803 for j in range(len(path)-1):#{
3804 i0 = path[j]
3805 i1 = path[j+1]
3806 o0 = dij.points[ i0 ]
3807 o1 = dij.points[ i1 ]
3808 cv_draw_arrow(o0,o1,cc,1.5)
3809 #}
3810 #}
3811 else:#{
3812 cv_draw_line_dotted( gi.location, gj.location, cc )
3813 #}
3814 #}
3815 #}
3816
3817 def cv_draw():
3818 #{
3819 global cv_view_shader
3820 global cv_view_verts
3821 global cv_view_colours
3822 global cv_view_course_i
3823
3824 cv_view_course_i = 0
3825 cv_view_verts = []
3826 cv_view_colours = []
3827
3828 cv_view_shader.bind()
3829 gpu.state.depth_mask_set(False)
3830 gpu.state.line_width_set(2.0)
3831 gpu.state.face_culling_set('BACK')
3832 gpu.state.depth_test_set('LESS')
3833 gpu.state.blend_set('NONE')
3834
3835 route_gates = []
3836 route_curves = []
3837 routes = []
3838
3839 for obj in bpy.context.collection.objects:#{
3840 if obj.type == 'ARMATURE':#{
3841 if obj.data.pose_position == 'REST':
3842 draw_skeleton_helpers( obj )
3843 #}
3844 else:#{
3845 ent_type = obj_ent_type( obj )
3846
3847 if ent_type == 'ent_gate':#{
3848 cv_ent_gate( obj )
3849 route_gates += [obj]
3850 #}
3851 elif ent_type == 'ent_route_node':#{
3852 if obj.type == 'CURVE':#{
3853 route_curves += [obj]
3854 #}
3855 #}
3856 elif ent_type == 'ent_route':
3857 routes += [obj]
3858 elif ent_type == 'ent_volume':#{
3859 cv_ent_volume( obj )
3860 #}
3861 elif ent_type == 'ent_audio':#{
3862 if obj.SR_data.ent_audio[0].flag_3d:
3863 cv_draw_sphere( obj.location, obj.scale[0], (1,1,0) )
3864 #}
3865 elif ent_type == 'ent_font':#{
3866 data = obj.SR_data.ent_font[0]
3867
3868 for i in range(len(data.variants)):#{
3869 sub = data.variants[i].mesh
3870 if not sub: continue
3871
3872 for ch in data.glyphs:#{
3873 mini = (ch.bounds[0],ch.bounds[1])
3874 maxi = (ch.bounds[2]+mini[0],ch.bounds[3]+mini[1])
3875 p0 = sub.matrix_world @ Vector((mini[0],0.0,mini[1]))
3876 p1 = sub.matrix_world @ Vector((maxi[0],0.0,mini[1]))
3877 p2 = sub.matrix_world @ Vector((maxi[0],0.0,maxi[1]))
3878 p3 = sub.matrix_world @ Vector((mini[0],0.0,maxi[1]))
3879
3880 if i == data.variants_index: cc = (0.5,0.5,0.5)
3881 else: cc = (0,0,0)
3882
3883 cv_view_verts += [p0,p1,p1,p2,p2,p3,p3,p0]
3884 cv_view_colours += [cc,cc,cc,cc,cc,cc,cc,cc]
3885 #}
3886 #}
3887 #}
3888 elif ent_type == 'ent_skateshop':#{
3889 data = obj.SR_data.ent_skateshop[0]
3890 display = data.mark_display
3891 info = data.mark_info
3892
3893 if data.tipo == '0':#{
3894 cc = (0.0,0.9,0.6)
3895 cc1 = (0.4,0.9,0.2)
3896 cc2 = (0.9,0.6,0.1)
3897
3898 rack = data.mark_rack
3899
3900 rack_cu = Vector((3.15,2.0,0.1))*0.5
3901 rack_co = Vector((0.0,0.0,0.0))
3902 display_cu = Vector((0.3,1.2,0.1))*0.5
3903 display_co = Vector((0.0,0.0,0.1))*0.5
3904 info_cu = Vector((1.2,0.01,0.3))*0.5
3905 info_co = Vector((0.0,0.0,0.0))*0.5
3906 #}
3907 elif data.tipo == '1':#{
3908 rack = None
3909 cc1 = (1.0,0.0,0.0)
3910 cc2 = (1.0,0.5,0.0)
3911 display_cu = Vector((0.4,0.4,2.0))*0.5
3912 display_co = Vector((0.0,0.0,1.0))*0.5
3913 info_cu = Vector((1.2,0.01,0.3))*0.5
3914 info_co = Vector((0.0,0.0,0.0))*0.5
3915 #}
3916
3917 if rack:
3918 cv_draw_ucube( rack.matrix_world, cc, rack_cu, rack_co )
3919 if display:
3920 cv_draw_ucube( display.matrix_world, cc1, display_cu, display_co)
3921 if info:
3922 cv_draw_ucube( info.matrix_world, cc2, info_cu, info_co )
3923 #}
3924 elif ent_type == 'ent_swspreview':#{
3925 cc1 = (0.4,0.9,0.2)
3926 data = obj.SR_data.ent_swspreview[0]
3927 display = data.mark_display
3928 display1 = data.mark_display1
3929 display_cu = Vector((0.3,1.2,0.1))*0.5
3930 display_co = Vector((0.0,0.0,0.1))*0.5
3931 if display:
3932 cv_draw_ucube( display.matrix_world, cc1, display_cu, display_co)
3933 if display1:
3934 cv_draw_ucube(display1.matrix_world, cc1, display_cu, display_co)
3935 #}
3936 elif ent_type == 'ent_menuitem':#{
3937 for i,col in enumerate(obj.users_collection):#{
3938 colour32 = hash_djb2( col.name )
3939 r = pow(((colour32 ) & 0xff) / 255.0, 2.2 )
3940 g = pow(((colour32>>8 ) & 0xff) / 255.0, 2.2 )
3941 b = pow(((colour32>>16) & 0xff) / 255.0, 2.2 )
3942 cc = (r,g,b)
3943 vs = [None for _ in range(8)]
3944 scale = i*0.02
3945 for j in range(8):#{
3946 v0 = Vector([(obj.bound_box[j][z]+\
3947 ((-1.0 if obj.bound_box[j][z]<0.0 else 1.0)*scale)) \
3948 for z in range(3)])
3949 vs[j] = obj.matrix_world @ v0
3950 #}
3951 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
3952 (0,4),(1,5),(2,6),(3,7)]
3953 for l in indices:#{
3954 v0 = vs[l[0]]
3955 v1 = vs[l[1]]
3956 cv_view_verts += [(v0[0],v0[1],v0[2])]
3957 cv_view_verts += [(v1[0],v1[1],v1[2])]
3958 cv_view_colours += [cc,cc]
3959 #}
3960 #}
3961 cv_draw_lines()
3962 cc = (1.0,1.0,1.0)
3963 data = obj.SR_data.ent_menuitem[0]
3964 if data.tipo == '4':#{
3965 if data.slider_minloc and data.slider_maxloc:#{
3966 v0 = data.slider_minloc.location
3967 v1 = data.slider_maxloc.location
3968 cv_draw_line( v0, v1, cc )
3969 #}
3970 #}
3971
3972 colour32 = hash_djb2(obj.name)
3973 r = ((colour32 ) & 0xff) / 255.0
3974 g = ((colour32>>8 ) & 0xff) / 255.0
3975 b = ((colour32>>16) & 0xff) / 255.0
3976 cc = (r,g,b)
3977 origin = obj.location + (Vector((r,g,b))*2.0-Vector((1.0,1.0,1.0)))\
3978 * 0.04
3979
3980 size = 0.01
3981
3982 if data.tipo != '0':#{
3983 if data.tipo == '4':#{
3984 if data.link0:#{
3985 cv_draw_arrow( origin, data.link0.location, cc, size )
3986 #}
3987 if data.link1:#{
3988 cv_draw_arrow( origin, data.link1.location, cc, size )
3989 #}
3990 #}
3991 else:#{
3992 if data.link0:#{
3993 cv_draw_arrow( origin, data.link0.location, cc, size )
3994 #}
3995 if data.link1:#{
3996 cv_draw_arrow( origin, data.link1.location, cc, size )
3997 #}
3998 if data.link2:#{
3999 cv_draw_arrow( origin, data.link2.location, cc, size )
4000 #}
4001 if data.link3:#{
4002 cv_draw_arrow( origin, data.link3.location, cc, size )
4003 #}
4004 #}
4005 #}
4006 #}
4007 #}
4008 #}
4009
4010 dij = create_node_graph( route_curves, route_gates )
4011
4012 #cv_draw_route_map( route_nodes )
4013 for route in routes:#{
4014 cv_draw_route( route, dij )
4015 #}
4016
4017 cv_draw_lines()
4018 return
4019 #}
4020
4021 classes = [ SR_INTERFACE, SR_MATERIAL_PANEL,\
4022 SR_COLLECTION_SETTINGS, SR_SCENE_SETTINGS, \
4023 SR_COMPILE, SR_COMPILE_THIS, SR_MIRROR_BONE_X,\
4024 \
4025 SR_OBJECT_ENT_GATE, SR_MESH_ENT_GATE, SR_OBJECT_ENT_SPAWN, \
4026 SR_OBJECT_ENT_ROUTE_ENTRY, SR_UL_ROUTE_NODE_LIST, \
4027 SR_OBJECT_ENT_ROUTE, SR_OT_ROUTE_LIST_NEW_ITEM,\
4028 SR_OT_GLYPH_LIST_NEW_ITEM, SR_OT_GLYPH_LIST_DEL_ITEM,\
4029 SR_OT_GLYPH_LIST_MOVE_ITEM,\
4030 SR_OT_AUDIO_LIST_NEW_ITEM,SR_OT_AUDIO_LIST_DEL_ITEM,\
4031 SR_OT_FONT_VARIANT_LIST_NEW_ITEM,SR_OT_FONT_VARIANT_LIST_DEL_ITEM,\
4032 SR_OT_COPY_ENTITY_DATA, \
4033 SR_OBJECT_ENT_VOLUME, \
4034 SR_UL_AUDIO_LIST, SR_OBJECT_ENT_AUDIO_FILE_ENTRY,\
4035 SR_OT_ROUTE_LIST_DEL_ITEM,\
4036 SR_OBJECT_ENT_AUDIO,SR_OBJECT_ENT_MARKER,SR_OBJECT_ENT_GLYPH,\
4037 SR_OBJECT_ENT_FONT_VARIANT,
4038 SR_OBJECT_ENT_GLYPH_ENTRY,\
4039 SR_UL_FONT_VARIANT_LIST,SR_UL_FONT_GLYPH_LIST,\
4040 SR_OBJECT_ENT_FONT,SR_OBJECT_ENT_TRAFFIC,SR_OBJECT_ENT_SKATESHOP,\
4041 SR_OBJECT_ENT_WORKSHOP_PREVIEW,SR_OBJECT_ENT_MENU_ITEM,\
4042 \
4043 SR_OBJECT_PROPERTIES, SR_LIGHT_PROPERTIES, SR_BONE_PROPERTIES,
4044 SR_MESH_PROPERTIES, SR_MATERIAL_PROPERTIES \
4045 ]
4046
4047 def register():
4048 #{
4049 for c in classes:
4050 bpy.utils.register_class(c)
4051
4052 bpy.types.Scene.SR_data = \
4053 bpy.props.PointerProperty(type=SR_SCENE_SETTINGS)
4054 bpy.types.Collection.SR_data = \
4055 bpy.props.PointerProperty(type=SR_COLLECTION_SETTINGS)
4056
4057 bpy.types.Object.SR_data = \
4058 bpy.props.PointerProperty(type=SR_OBJECT_PROPERTIES)
4059 bpy.types.Light.SR_data = \
4060 bpy.props.PointerProperty(type=SR_LIGHT_PROPERTIES)
4061 bpy.types.Bone.SR_data = \
4062 bpy.props.PointerProperty(type=SR_BONE_PROPERTIES)
4063 bpy.types.Mesh.SR_data = \
4064 bpy.props.PointerProperty(type=SR_MESH_PROPERTIES)
4065 bpy.types.Material.SR_data = \
4066 bpy.props.PointerProperty(type=SR_MATERIAL_PROPERTIES)
4067
4068 global cv_view_draw_handler
4069 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
4070 cv_draw,(),'WINDOW','POST_VIEW')
4071 #}
4072
4073 def unregister():
4074 #{
4075 for c in classes:
4076 bpy.utils.unregister_class(c)
4077
4078 global cv_view_draw_handler
4079 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
4080 #}
4081
4082 # ---------------------------------------------------------------------------- #
4083 # #
4084 # QOI encoder #
4085 # #
4086 # ---------------------------------------------------------------------------- #
4087 # #
4088 # Transliteration of: #
4089 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
4090 # #
4091 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
4092 # SPDX-License-Identifier: MIT #
4093 # QOI - The "Quite OK Image" format for fast, lossless image compression #
4094 # #
4095 # ---------------------------------------------------------------------------- #
4096
4097 class qoi_rgba_t(Structure):
4098 #{
4099 _pack_ = 1
4100 _fields_ = [("r",c_uint8),
4101 ("g",c_uint8),
4102 ("b",c_uint8),
4103 ("a",c_uint8)]
4104 #}
4105
4106 QOI_OP_INDEX = 0x00 # 00xxxxxx
4107 QOI_OP_DIFF = 0x40 # 01xxxxxx
4108 QOI_OP_LUMA = 0x80 # 10xxxxxx
4109 QOI_OP_RUN = 0xc0 # 11xxxxxx
4110 QOI_OP_RGB = 0xfe # 11111110
4111 QOI_OP_RGBA = 0xff # 11111111
4112
4113 QOI_MASK_2 = 0xc0 # 11000000
4114
4115 def qoi_colour_hash( c ):
4116 #{
4117 return c.r*3 + c.g*5 + c.b*7 + c.a*11
4118 #}
4119
4120 def qoi_eq( a, b ):
4121 #{
4122 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
4123 #}
4124
4125 def qoi_32bit( v ):
4126 #{
4127 return bytearray([ (0xff000000 & v) >> 24, \
4128 (0x00ff0000 & v) >> 16, \
4129 (0x0000ff00 & v) >> 8, \
4130 (0x000000ff & v) ])
4131 #}
4132
4133 def qoi_encode( img ):
4134 #{
4135 data = bytearray()
4136
4137 print(F"{' ':<30}",end='\r')
4138 print(F"[QOI] Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]",end='\r')
4139
4140 index = [ qoi_rgba_t() for _ in range(64) ]
4141
4142 # Header
4143 #
4144 data.extend( bytearray(c_uint32(0x66696f71)) )
4145 data.extend( qoi_32bit( img.size[0] ) )
4146 data.extend( qoi_32bit( img.size[1] ) )
4147 data.extend( bytearray(c_uint8(4)) )
4148 data.extend( bytearray(c_uint8(0)) )
4149
4150 run = 0
4151 px_prev = qoi_rgba_t()
4152 px_prev.r = c_uint8(0)
4153 px_prev.g = c_uint8(0)
4154 px_prev.b = c_uint8(0)
4155 px_prev.a = c_uint8(255)
4156
4157 px = qoi_rgba_t()
4158 px.r = c_uint8(0)
4159 px.g = c_uint8(0)
4160 px.b = c_uint8(0)
4161 px.a = c_uint8(255)
4162
4163 px_len = img.size[0] * img.size[1]
4164 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
4165
4166 for px_pos in range( px_len ): #{
4167 idx = px_pos * img.channels
4168 nc = img.channels-1
4169
4170 px.r = paxels[idx+min(0,nc)]
4171 px.g = paxels[idx+min(1,nc)]
4172 px.b = paxels[idx+min(2,nc)]
4173 px.a = paxels[idx+min(3,nc)]
4174
4175 if qoi_eq( px, px_prev ): #{
4176 run += 1
4177
4178 if (run == 62) or (px_pos == px_len-1): #{
4179 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
4180 run = 0
4181 #}
4182 #}
4183 else: #{
4184 if run > 0: #{
4185 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
4186 run = 0
4187 #}
4188
4189 index_pos = qoi_colour_hash(px) % 64
4190
4191 if qoi_eq( index[index_pos], px ): #{
4192 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
4193 #}
4194 else: #{
4195 index[ index_pos ].r = px.r
4196 index[ index_pos ].g = px.g
4197 index[ index_pos ].b = px.b
4198 index[ index_pos ].a = px.a
4199
4200 if px.a == px_prev.a: #{
4201 vr = int(px.r) - int(px_prev.r)
4202 vg = int(px.g) - int(px_prev.g)
4203 vb = int(px.b) - int(px_prev.b)
4204
4205 vg_r = vr - vg
4206 vg_b = vb - vg
4207
4208 if (vr > -3) and (vr < 2) and\
4209 (vg > -3) and (vg < 2) and\
4210 (vb > -3) and (vb < 2):
4211 #{
4212 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
4213 data.extend( bytearray( c_uint8(op) ))
4214 #}
4215 elif (vg_r > -9) and (vg_r < 8) and\
4216 (vg > -33) and (vg < 32 ) and\
4217 (vg_b > -9) and (vg_b < 8):
4218 #{
4219 op = QOI_OP_LUMA | (vg+32)
4220 delta = (vg_r+8) << 4 | (vg_b + 8)
4221 data.extend( bytearray( c_uint8(op) ) )
4222 data.extend( bytearray( c_uint8(delta) ))
4223 #}
4224 else: #{
4225 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
4226 data.extend( bytearray( c_uint8(px.r) ))
4227 data.extend( bytearray( c_uint8(px.g) ))
4228 data.extend( bytearray( c_uint8(px.b) ))
4229 #}
4230 #}
4231 else: #{
4232 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
4233 data.extend( bytearray( c_uint8(px.r) ))
4234 data.extend( bytearray( c_uint8(px.g) ))
4235 data.extend( bytearray( c_uint8(px.b) ))
4236 data.extend( bytearray( c_uint8(px.a) ))
4237 #}
4238 #}
4239 #}
4240
4241 px_prev.r = px.r
4242 px_prev.g = px.g
4243 px_prev.b = px.b
4244 px_prev.a = px.a
4245 #}
4246
4247 # Padding
4248 for i in range(7):
4249 data.extend( bytearray( c_uint8(0) ))
4250 data.extend( bytearray( c_uint8(1) ))
4251 bytearray_align_to( data, 16, b'\x00' )
4252
4253 return data
4254 #}