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