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