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