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