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