entities zones
[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
7 bl_info = {
8 "name":"Skaterift .mdl exporter",
9 "author": "Harry Godden (hgn)",
10 "version": (0,2),
11 "blender":(3,1,0),
12 "location":"Export",
13 "description":"",
14 "warning":"",
15 "wiki_url":"",
16 "category":"Import/Export",
17 }
18
19 sr_entity_alias = {
20 'ent_gate': 1,
21 'ent_spawn': 2,
22 'ent_route_node': 3,
23 'ent_route': 4,
24 'ent_water': 5,
25 'ent_volume': 6,
26 'ent_audio': 7
27 }
28
29 class mdl_vert(Structure): # 48 bytes. Quite large. Could compress
30 #{ # the normals and uvs to i16s. Not an
31 _pack_ = 1 # real issue, yet.
32 _fields_ = [("co",c_float*3),
33 ("norm",c_float*3),
34 ("uv",c_float*2),
35 ("colour",c_uint8*4),
36 ("weights",c_uint16*4),
37 ("groups",c_uint8*4)]
38 #}
39
40 class mdl_transform(Structure):
41 #{
42 _fields_ = [("co",c_float*3),
43 ( "s",c_float*3),
44 ( "q",c_float*4)]
45 #}
46
47 class mdl_submesh(Structure):
48 #{
49 _fields_ = [("indice_start",c_uint32),
50 ("indice_count",c_uint32),
51 ("vertex_start",c_uint32),
52 ("vertex_count",c_uint32),
53 ("bbx",(c_float*3)*2),
54 ("material_id",c_uint32)] # index into the material array
55 #}
56
57 class mdl_material(Structure):
58 #{
59 _fields_ = [("pstr_name",c_uint32),
60 ("shader",c_uint32),
61 ("flags",c_uint32),
62 ("surface_prop",c_uint32),
63 ("colour",c_float*4),
64 ("colour1",c_float*4),
65 ("tex_diffuse",c_uint32),
66 ("tex_none0",c_uint32),
67 ("tex_none1",c_uint32)]
68 #}
69
70 class mdl_bone(Structure):
71 #{
72 _fields_ = [("co",c_float*3),("end",c_float*3),
73 ("parent",c_uint32),
74 ("collider",c_uint32),
75 ("ik_target",c_uint32),
76 ("ik_pole",c_uint32),
77 ("flags",c_uint32),
78 ("pstr_name",c_uint32),
79 ("hitbox",(c_float*3)*2),
80 ("conevx",c_float*3),("conevy",c_float*3),("coneva",c_float*3),
81 ("conet",c_float)]
82 #}
83
84 class mdl_armature(Structure):
85 #{
86 _fields_ = [("transform",mdl_transform),
87 ("bone_start",c_uint32),
88 ("bone_count",c_uint32),
89 ("anim_start",c_uint32),
90 ("anim_count",c_uint32)]
91 #}
92
93 class mdl_animation(Structure):
94 #{
95 _fields_ = [("pstr_name",c_uint32),
96 ("length",c_uint32),
97 ("rate",c_float),
98 ("keyframe_start",c_uint32)]
99 #}
100
101 class mdl_mesh(Structure):
102 #{
103 _fields_ = [("transform",mdl_transform),
104 ("submesh_start",c_uint32),
105 ("submesh_count",c_uint32),
106 ("pstr_name",c_uint32),
107 ("flags",c_uint32),
108 ("armature_id",c_uint32)]
109 #}
110
111 class mdl_file(Structure):
112 #{
113 _fields_ = [("path",c_uint32),
114 ("pack_offset",c_uint32),
115 ("pack_size",c_uint32)]
116 #}
117
118 class mdl_texture(Structure):
119 #{
120 _fields_ = [("file",mdl_file),
121 ("type",c_uint32)]
122 #}
123
124 class mdl_array(Structure):
125 #{
126 _fields_ = [("file_offset",c_uint32),
127 ("item_count",c_uint32),
128 ("item_size",c_uint32),
129 ("name",c_byte*16)]
130 #}
131
132 class mdl_header(Structure):
133 #{
134 _fields_ = [("version",c_uint32),
135 ("arrays",mdl_array)]
136 #}
137
138 class ent_spawn(Structure):
139 #{
140 _fields_ = [("transform",mdl_transform),
141 ("pstr_name",c_uint32)]
142 #}
143
144 class ent_light(Structure):
145 #{
146 _fields_ = [("transform",mdl_transform),
147 ("daytime",c_uint32),
148 ("type",c_uint32),
149 ("colour",c_float*4),
150 ("angle",c_float),
151 ("range",c_float),
152 ("inverse_world",(c_float*3)*4), # Runtime
153 ("angle_sin_cos",(c_float*2))] # Runtime
154 #}
155
156 class version_refcount_union(Union):
157 #{
158 _fields_ = [("timing_version",c_uint32),
159 ("ref_count",c_uint8)]
160 #}
161
162 class ent_gate(Structure):
163 #{
164 _fields_ = [("type",c_uint32),
165 ("target", c_uint32),
166 ("dimensions", c_float*3),
167 ("co", (c_float*3)*2),
168 ("q", (c_float*4)*2),
169 ("to_world",(c_float*3)*4),
170 ("transport",(c_float*3)*4),
171 ("_anonymous_union",version_refcount_union),
172 ("timing_time",c_double),
173 ("routes",c_uint16*4)]
174 #}
175
176 class ent_route_node(Structure):
177 #{
178 _fields_ = [("co",c_float*3),
179 ("ref_count",c_uint8),
180 ("ref_total",c_uint8)]
181 #}
182
183 class ent_path_index(Structure):
184 #{
185 _fields_ = [("index",c_uint16)]
186 #}
187
188 class vg_audio_clip(Structure):
189 #{
190 _fields_ = [("path",c_uint64),
191 ("flags",c_uint32),
192 ("size",c_uint32),
193 ("data",c_uint64)]
194 #}
195
196 class union_file_audio_clip(Union):
197 #{
198 _fields_ = [("file",mdl_file),
199 ("reserved",vg_audio_clip)]
200 #}
201
202 class ent_audio_clip(Structure):
203 #{
204 _fields_ = [("_anon",union_file_audio_clip),
205 ("probability",c_float)]
206 #}
207
208 class ent_checkpoint(Structure):
209 #{
210 _fields_ = [("gate_index",c_uint16),
211 ("path_start",c_uint16),
212 ("path_count",c_uint16)]
213 #}
214
215 class ent_route(Structure):
216 #{
217 _fields_ = [("transform",mdl_transform),
218 ("pstr_name",c_uint32),
219 ("checkpoints_start",c_uint16),
220 ("checkpoints_count",c_uint16),
221 ("colour",c_float*4),
222 ("active",c_uint32), #runtime
223 ("factive",c_float),
224 ("board_transform",(c_float*3)*4),
225 ("sm",mdl_submesh),
226 ("latest_pass",c_double)]
227 #}
228
229 class ent_water(Structure):
230 #{
231 _fields_ = [("transform",mdl_transform),
232 ("max_dist",c_float),
233 ("reserved0",c_uint32),
234 ("reserved1",c_uint32)]
235 #}
236
237 class volume_trigger(Structure):
238 #{
239 _fields_ = [("event",c_uint32),
240 ("blank",c_uint32)]
241 #}
242
243 class volume_particles(Structure):
244 #{
245 _fields_ = [("blank",c_uint32),
246 ("blank2",c_uint32)]
247 #}
248
249 class volume_union(Union):
250 #{
251 _fields_ = [("trigger",volume_trigger),
252 ("particles",volume_particles)]
253 #}
254
255 class ent_index(Structure):
256 #{
257 _fields_ = [("type",c_uint32),
258 ("index",c_uint32)]
259 #}
260
261 class ent_volume(Structure):
262 #{
263 _fields_ = [("transform",mdl_transform),
264 ("to_world",(c_float*3)*4),
265 ("to_local",(c_float*3)*4),
266 ("type",c_uint32),
267 ("target",ent_index),
268 ("_anon",volume_union)]
269 #}
270
271 class ent_audio(Structure):
272 #{
273 _fields_ = [("transform",mdl_transform),
274 ("flags",c_uint32),
275 ("clip_start",c_uint32),
276 ("clip_count",c_uint32),
277 ("volume",c_float),
278 ("crossfade",c_float),
279 ("channel_behaviour",c_uint32),
280 ("group",c_uint32),
281 ("probability_curve",c_uint32),
282 ("max_channels",c_uint32)]
283 #}
284
285 def obj_ent_type( obj ):
286 #{
287 if obj.type == 'ARMATURE': return 'mdl_armature'
288 elif obj.type == 'LIGHT': return 'ent_light'
289 else: return obj.SR_data.ent_type
290 #}
291
292 def sr_filter_ent_type( obj, ent_types ):
293 #{
294 if obj == bpy.context.active_object: return False
295
296 for c0 in obj.users_collection:#{
297 for c1 in bpy.context.active_object.users_collection:#{
298 if c0 == c1:#{
299 return obj_ent_type( obj ) in ent_types
300 #}
301 #}
302 #}
303
304 return False
305 #}
306
307 def compile_obj_transform( obj, transform ):
308 #{
309 co = obj.matrix_world @ Vector((0,0,0))
310 q = obj.matrix_local.to_quaternion()
311 s = obj.scale
312
313 # Setup transform
314 #
315 transform.co[0] = co[0]
316 transform.co[1] = co[2]
317 transform.co[2] = -co[1]
318 transform.q[0] = q[1]
319 transform.q[1] = q[3]
320 transform.q[2] = -q[2]
321 transform.q[3] = q[0]
322 transform.s[0] = s[0]
323 transform.s[1] = s[2]
324 transform.s[2] = s[1]
325 #}
326
327 def int_align_to( v, align ):
328 #{
329 while(v%align)!=0: v += 1
330 return v
331 #}
332
333 def bytearray_align_to( buffer, align, w=b'\xaa' ):
334 #{
335 while (len(buffer) % align) != 0: buffer.extend(w)
336 return buffer
337 #}
338
339 def bytearray_print_hex( s, w=16 ):
340 #{
341 for r in range((len(s)+(w-1))//w):#{
342 i0=(r+0)*w
343 i1=min((r+1)*w,len(s))
344 print( F'{r*w:06x}| \x1B[31m', end='')
345 print( F"{' '.join('{:02x}'.format(x) for x in s[i0:i1]):<48}",end='' )
346 print( "\x1B[0m", end='')
347 print( ''.join(chr(x) if (x>=33 and x<=126) else '.' for x in s[i0:i1] ) )
348 #}
349 #}
350
351 def sr_compile_string( s ):
352 #{
353 if s in sr_compile.string_cache: return sr_compile.string_cache[s]
354
355 index = len( sr_compile.string_data )
356 sr_compile.string_cache[s] = index
357 sr_compile.string_data.extend( s.encode('utf-8') )
358 sr_compile.string_data.extend( b'\0' )
359
360 bytearray_align_to( sr_compile.string_data, 4 )
361 return index
362 #}
363
364 def material_tex_image(v):
365 #{
366 return {
367 "Image Texture":
368 {
369 "image": F"{v}"
370 }
371 }
372 #}
373
374 cxr_graph_mapping = \
375 {
376 # Default shader setup
377 "Principled BSDF":
378 {
379 "Base Color":
380 {
381 "Image Texture":
382 {
383 "image": "tex_diffuse"
384 },
385 "Mix":
386 {
387 "A": material_tex_image("tex_diffuse"),
388 "B": material_tex_image("tex_decal")
389 },
390 },
391 "Normal":
392 {
393 "Normal Map":
394 {
395 "Color": material_tex_image("tex_normal")
396 }
397 }
398 }
399 }
400
401 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
402 #
403 def material_info(mat):
404 #{
405 info = {}
406
407 # Using the cxr_graph_mapping as a reference, go through the shader
408 # graph and gather all $props from it.
409 #
410 def _graph_read( node_def, node=None, depth=0 ):#{
411 nonlocal mat
412 nonlocal info
413
414 # Find rootnodes
415 #
416 if node == None:#{
417 _graph_read.extracted = []
418
419 for node_idname in node_def:#{
420 for n in mat.node_tree.nodes:#{
421 if n.name == node_idname:#{
422 node_def = node_def[node_idname]
423 node = n
424 break
425 #}
426 #}
427 #}
428 #}
429
430 for link in node_def:#{
431 link_def = node_def[link]
432
433 if isinstance( link_def, dict ):#{
434 node_link = None
435 for x in node.inputs:#{
436 if isinstance( x, bpy.types.NodeSocketColor ):#{
437 if link == x.name:#{
438 node_link = x
439 break
440 #}
441 #}
442 #}
443
444 if node_link and node_link.is_linked:#{
445 # look for definitions for the connected node type
446 #
447 from_node = node_link.links[0].from_node
448
449 node_name = from_node.name.split('.')[0]
450 if node_name in link_def:#{
451 from_node_def = link_def[ node_name ]
452
453 _graph_read( from_node_def, from_node, depth+1 )
454 #}
455 #}
456 else:#{
457 if "default" in link_def:#{
458 prop = link_def['default']
459 info[prop] = node_link.default_value
460 #}
461 #}
462 #}
463 else:#{
464 prop = link_def
465 info[prop] = getattr( node, link )
466 #}
467 #}
468 #}
469
470 _graph_read( cxr_graph_mapping )
471 return info
472 #}
473
474 def vg_str_bin( s ):
475 #{
476 decoded = bytearray()
477 for i in range(len(s)//2):#{
478 c = (ord(s[i*2+0])-0x41)
479 c |= (ord(s[i*2+1])-0x41)<<4
480 decoded.extend(bytearray(c_uint8(c))) #??
481 #}
482 return decoded
483 #}
484
485 def sr_pack_file( file, path, data ):
486 #{
487 file.path = sr_compile_string( path )
488 file.pack_offset = len( sr_compile.pack_data )
489 file.pack_size = len( data )
490
491 sr_compile.pack_data.extend( data )
492 bytearray_align_to( sr_compile.pack_data, 16 )
493 #}
494
495 def sr_compile_texture( img ):
496 #{
497 if img == None:
498 return 0
499
500 name = os.path.splitext( img.name )[0]
501
502 if name in sr_compile.texture_cache:
503 return sr_compile.texture_cache[name]
504
505 texture_index = (len(sr_compile.texture_data)//sizeof(mdl_texture)) +1
506
507 tex = mdl_texture()
508 tex.type = 0
509
510 if sr_compile.pack_textures:#{
511 filedata = qoi_encode( img )
512 sr_pack_file( tex.file, name, filedata )
513 #}
514
515 sr_compile.texture_cache[name] = texture_index
516 sr_compile.texture_data.extend( bytearray(tex) )
517 return texture_index
518 #}
519
520 def sr_compile_material( mat ):
521 #{
522 if mat == None:
523 return 0
524 if mat.name in sr_compile.material_cache:
525 return sr_compile.material_cache[mat.name]
526
527 index = (len(sr_compile.material_data)//sizeof(mdl_material))+1
528 sr_compile.material_cache[mat.name] = index
529
530 m = mdl_material()
531 m.pstr_name = sr_compile_string( mat.name )
532
533 flags = 0x00
534 if mat.SR_data.collision:#{
535 flags |= 0x2
536 if mat.SR_data.skate_surface: flags |= 0x1
537 if mat.SR_data.grind_surface: flags |= (0x8|0x1)
538 #}
539
540 if mat.SR_data.grow_grass: flags |= 0x4
541 m.flags = flags
542
543 m.surface_prop = int(mat.SR_data.surface_prop)
544
545 if mat.SR_data.shader == 'standard': m.shader = 0
546 if mat.SR_data.shader == 'standard_cutout': m.shader = 1
547 if mat.SR_data.shader == 'terrain_blend':#{
548 m.shader = 2
549
550 m.colour[0] = pow( mat.SR_data.sand_colour[0], 1.0/2.2 )
551 m.colour[1] = pow( mat.SR_data.sand_colour[1], 1.0/2.2 )
552 m.colour[2] = pow( mat.SR_data.sand_colour[2], 1.0/2.2 )
553 m.colour[3] = 1.0
554
555 m.colour1[0] = mat.SR_data.blend_offset[0]
556 m.colour1[1] = mat.SR_data.blend_offset[1]
557 #}
558
559 if mat.SR_data.shader == 'vertex_blend':#{
560 m.shader = 3
561
562 m.colour1[0] = mat.SR_data.blend_offset[0]
563 m.colour1[1] = mat.SR_data.blend_offset[1]
564 #}
565
566 if mat.SR_data.shader == 'water':#{
567 m.shader = 4
568
569 m.colour[0] = pow( mat.SR_data.shore_colour[0], 1.0/2.2 )
570 m.colour[1] = pow( mat.SR_data.shore_colour[1], 1.0/2.2 )
571 m.colour[2] = pow( mat.SR_data.shore_colour[2], 1.0/2.2 )
572 m.colour[3] = 1.0
573 m.colour1[0] = pow( mat.SR_data.ocean_colour[0], 1.0/2.2 )
574 m.colour1[1] = pow( mat.SR_data.ocean_colour[1], 1.0/2.2 )
575 m.colour1[2] = pow( mat.SR_data.ocean_colour[2], 1.0/2.2 )
576 m.colour1[3] = 1.0
577 #}
578
579 inf = material_info( mat )
580
581 if mat.SR_data.shader == 'standard' or \
582 mat.SR_data.shader == 'standard_cutout' or \
583 mat.SR_data.shader == 'terrain_blend' or \
584 mat.SR_data.shader == 'vertex_blend':
585 #{
586 if 'tex_diffuse' in inf:
587 m.tex_diffuse = sr_compile_texture(inf['tex_diffuse'])
588 #}
589
590 sr_compile.material_data.extend( bytearray(m) )
591 return index
592 #}
593
594 def sr_armature_bones( armature ):
595 #{
596 def _recurse_bone( b ):
597 #{
598 yield b
599 for c in b.children: yield from _recurse_bone( c )
600 #}
601
602 for b in armature.data.bones:
603 if not b.parent:
604 yield from _recurse_bone( b )
605 #}
606
607 def sr_compile_mesh( obj ):
608 #{
609 node=mdl_mesh()
610 compile_obj_transform(obj, node.transform)
611 node.pstr_name = sr_compile_string(obj.name)
612 node.flags = 0
613
614 can_use_cache = True
615 armature = None
616
617 for mod in obj.modifiers:#{
618 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
619 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
620 mod.type == 'ARRAY':
621 #{
622 can_use_cache = False
623 #}
624
625 if mod.type == 'ARMATURE': #{
626 node.flags = 1
627 armature = mod.object
628 rig_weight_groups = \
629 ['0 [ROOT]']+[_.name for _ in sr_armature_bones(mod.object)]
630 node.armature_id = sr_compile.entity_ids[armature.name]
631
632 POSE_OR_REST_CACHE = armature.data.pose_position
633 armature.data.pose_position = 'REST'
634 #}
635 #}
636
637 # Check the cache first
638 #
639 if can_use_cache and (obj.data.name in sr_compile.mesh_cache):#{
640 ref = sr_compile.mesh_cache[obj.data.name]
641 node.submesh_start = ref[0]
642 node.submesh_count = ref[1]
643 sr_compile.mesh_data.extend(bytearray(node))
644 return
645 #}
646
647 # Compile a whole new mesh
648 #
649 node.submesh_start = len(sr_compile.submesh_data)//sizeof(mdl_submesh)
650 node.submesh_count = 0
651
652 dgraph = bpy.context.evaluated_depsgraph_get()
653 data = obj.evaluated_get(dgraph).data
654 data.calc_loop_triangles()
655 data.calc_normals_split()
656
657 # Mesh is split into submeshes based on their material
658 #
659 mat_list = data.materials if len(data.materials) > 0 else [None]
660 for material_id, mat in enumerate(mat_list): #{
661 mref = {}
662
663 sm = mdl_submesh()
664 sm.indice_start = len(sr_compile.indice_data)//sizeof(c_uint32)
665 sm.vertex_start = len(sr_compile.vertex_data)//sizeof(mdl_vert)
666 sm.vertex_count = 0
667 sm.indice_count = 0
668 sm.material_id = sr_compile_material( mat )
669
670 INF=99999999.99999999
671 for i in range(3):#{
672 sm.bbx[0][i] = INF
673 sm.bbx[1][i] = -INF
674 #}
675
676 # Keep a reference to very very very similar vertices
677 # i have no idea how to speed it up.
678 #
679 vertex_reference = {}
680
681 # Write the vertex / indice data
682 #
683 for tri_index, tri in enumerate(data.loop_triangles):#{
684 if tri.material_index != material_id:
685 continue
686
687 for j in range(3):#{
688 vert = data.vertices[tri.vertices[j]]
689 li = tri.loops[j]
690 vi = data.loops[li].vertex_index
691
692 # Gather vertex information
693 #
694 co = vert.co
695 norm = data.loops[li].normal
696 uv = (0,0)
697 colour = (255,255,255,255)
698 groups = [0,0,0,0]
699 weights = [0,0,0,0]
700
701 # Uvs
702 #
703 if data.uv_layers:
704 uv = data.uv_layers.active.data[li].uv
705
706 # Vertex Colours
707 #
708 if data.vertex_colors:#{
709 colour = data.vertex_colors.active.data[li].color
710 colour = (int(colour[0]*255.0),\
711 int(colour[1]*255.0),\
712 int(colour[2]*255.0),\
713 int(colour[3]*255.0))
714 #}
715
716 # Weight groups: truncates to the 3 with the most influence. The
717 # fourth bone ID is never used by the shader so it
718 # is always 0
719 #
720 if armature:#{
721 src_groups = [_ for _ in data.vertices[vi].groups \
722 if obj.vertex_groups[_.group].name in \
723 rig_weight_groups ]
724
725 weight_groups = sorted( src_groups, key = \
726 lambda a: a.weight, reverse=True )
727 tot = 0.0
728 for ml in range(3):#{
729 if len(weight_groups) > ml:#{
730 g = weight_groups[ml]
731 name = obj.vertex_groups[g.group].name
732 weight = g.weight
733 weights[ml] = weight
734 groups[ml] = rig_weight_groups.index(name)
735 tot += weight
736 #}
737 #}
738
739 if len(weight_groups) > 0:#{
740 inv_norm = (1.0/tot) * 65535.0
741 for ml in range(3):#{
742 weights[ml] = int( weights[ml] * inv_norm )
743 weights[ml] = min( weights[ml], 65535 )
744 weights[ml] = max( weights[ml], 0 )
745 #}
746 #}
747 #}
748 else:#{
749 li1 = tri.loops[(j+1)%3]
750 vi1 = data.loops[li1].vertex_index
751 e0 = data.edges[ data.loops[li].edge_index ]
752
753 if e0.use_freestyle_mark and \
754 ((e0.vertices[0] == vi and e0.vertices[1] == vi1) or \
755 (e0.vertices[0] == vi1 and e0.vertices[1] == vi)):
756 #{
757 weights[0] = 1
758 #}
759 #}
760
761 TOLERENCE = float(10**4)
762 key = (int(co[0]*TOLERENCE+0.5),
763 int(co[1]*TOLERENCE+0.5),
764 int(co[2]*TOLERENCE+0.5),
765 int(norm[0]*TOLERENCE+0.5),
766 int(norm[1]*TOLERENCE+0.5),
767 int(norm[2]*TOLERENCE+0.5),
768 int(uv[0]*TOLERENCE+0.5),
769 int(uv[1]*TOLERENCE+0.5),
770 colour[0], # these guys are already quantized
771 colour[1], # .
772 colour[2], # .
773 colour[3], # .
774 weights[0], # v
775 weights[1],
776 weights[2],
777 weights[3],
778 groups[0],
779 groups[1],
780 groups[2],
781 groups[3])
782
783 if key in vertex_reference:
784 index = vertex_reference[key]
785 else:#{
786 index = bytearray(c_uint32(sm.vertex_count))
787 sm.vertex_count+=1
788
789 vertex_reference[key] = index
790 v = mdl_vert()
791 v.co[0] = co[0]
792 v.co[1] = co[2]
793 v.co[2] = -co[1]
794 v.norm[0] = norm[0]
795 v.norm[1] = norm[2]
796 v.norm[2] = -norm[1]
797 v.uv[0] = uv[0]
798 v.uv[1] = uv[1]
799 v.colour[0] = colour[0]
800 v.colour[1] = colour[1]
801 v.colour[2] = colour[2]
802 v.colour[3] = colour[3]
803 v.weights[0] = weights[0]
804 v.weights[1] = weights[1]
805 v.weights[2] = weights[2]
806 v.weights[3] = weights[3]
807 v.groups[0] = groups[0]
808 v.groups[1] = groups[1]
809 v.groups[2] = groups[2]
810 v.groups[3] = groups[3]
811
812 for i in range(3):#{
813 sm.bbx[0][i] = min( sm.bbx[0][i], v.co[i] )
814 sm.bbx[1][i] = max( sm.bbx[1][i], v.co[i] )
815 #}
816
817 sr_compile.vertex_data.extend(bytearray(v))
818 #}
819
820 sm.indice_count += 1
821 sr_compile.indice_data.extend( index )
822 #}
823 #}
824
825 # Make sure bounding box isn't -inf -> inf if no vertices
826 #
827 if sm.vertex_count == 0:
828 for j in range(2):
829 for i in range(3):
830 sm.bbx[j][i] = 0
831
832 # Add submesh to encoder
833 #
834 sr_compile.submesh_data.extend( bytearray(sm) )
835 node.submesh_count += 1
836 #}
837
838 if armature:#{
839 armature.data.pose_position = POSE_OR_REST_CACHE
840 #}
841
842 # Save a reference to this node since we want to reuse the submesh indices
843 # later.
844 sr_compile.mesh_cache[obj.data.name]=(node.submesh_start,node.submesh_count)
845 sr_compile.mesh_data.extend(bytearray(node))
846 #}
847
848 def sr_compile_armature( obj ):
849 #{
850 node = mdl_armature()
851 node.bone_start = len(sr_compile.bone_data)//sizeof(mdl_bone)
852 node.bone_count = 0
853 node.anim_start = len(sr_compile.anim_data)//sizeof(mdl_animation)
854 node.anim_count = 0
855
856 bones = [_ for _ in sr_armature_bones(obj)]
857 bones_names = [None]+[_.name for _ in bones]
858
859 for b in bones:#{
860 bone = mdl_bone()
861 if b.use_deform: bone.flags = 0x1
862 if b.parent: bone.parent = bones_names.index(b.parent.name)
863
864 bone.collider = int(b.SR_data.collider)
865
866 if bone.collider>0:#{
867 bone.hitbox[0][0] = b.SR_data.collider_min[0]
868 bone.hitbox[0][1] = b.SR_data.collider_min[2]
869 bone.hitbox[0][2] = -b.SR_data.collider_max[1]
870 bone.hitbox[1][0] = b.SR_data.collider_max[0]
871 bone.hitbox[1][1] = b.SR_data.collider_max[2]
872 bone.hitbox[1][2] = -b.SR_data.collider_min[1]
873 #}
874
875 if b.SR_data.cone_constraint:#{
876 bone.flags |= 0x4
877 bone.conevx[0] = b.SR_data.conevx[0]
878 bone.conevx[1] = b.SR_data.conevx[2]
879 bone.conevx[2] = -b.SR_data.conevx[1]
880 bone.conevy[0] = b.SR_data.conevy[0]
881 bone.conevy[1] = b.SR_data.conevy[2]
882 bone.conevy[2] = -b.SR_data.conevy[1]
883 bone.coneva[0] = b.SR_data.coneva[0]
884 bone.coneva[1] = b.SR_data.coneva[2]
885 bone.coneva[2] = -b.SR_data.coneva[1]
886 bone.conet = b.SR_data.conet
887 #}
888
889 bone.co[0] = b.head_local[0]
890 bone.co[1] = b.head_local[2]
891 bone.co[2] = -b.head_local[1]
892 bone.end[0] = b.tail_local[0] - bone.co[0]
893 bone.end[1] = b.tail_local[2] - bone.co[1]
894 bone.end[2] = -b.tail_local[1] - bone.co[2]
895 bone.pstr_name = sr_compile_string( b.name )
896
897 for c in obj.pose.bones[b.name].constraints:#{
898 if c.type == 'IK':#{
899 bone.flags |= 0x2
900 bone.ik_target = bones_names.index(c.subtarget)
901 bone.ik_pole = bones_names.index(c.pole_subtarget)
902 #}
903 #}
904
905 node.bone_count += 1
906 sr_compile.bone_data.extend(bytearray(bone))
907 #}
908
909 # Compile anims
910 #
911 if obj.animation_data and sr_compile.pack_animations: #{
912 # So we can restore later
913 #
914 previous_frame = bpy.context.scene.frame_current
915 previous_action = obj.animation_data.action
916 POSE_OR_REST_CACHE = obj.data.pose_position
917 obj.data.pose_position = 'POSE'
918
919 for NLALayer in obj.animation_data.nla_tracks:#{
920 for NLAStrip in NLALayer.strips:#{
921 # set active
922 #
923 for a in bpy.data.actions:#{
924 if a.name == NLAStrip.name:#{
925 obj.animation_data.action = a
926 break
927 #}
928 #}
929
930 # Clip to NLA settings
931 #
932 anim_start = int(NLAStrip.action_frame_start)
933 anim_end = int(NLAStrip.action_frame_end)
934
935 # Export strips
936 #
937 anim = mdl_animation()
938 anim.pstr_name = sr_compile_string( NLAStrip.action.name )
939 anim.rate = 30.0
940 anim.keyframe_start = len(sr_compile.keyframe_data)//\
941 sizeof(mdl_transform)
942 anim.length = anim_end-anim_start
943
944 i = 0
945 # Export the keyframes
946 for frame in range(anim_start,anim_end):#{
947 bpy.context.scene.frame_set(frame)
948
949 for rb in bones:#{
950 pb = obj.pose.bones[rb.name]
951
952 # relative bone matrix
953 if rb.parent is not None:#{
954 offset_mtx = rb.parent.matrix_local
955 offset_mtx = offset_mtx.inverted_safe() @ \
956 rb.matrix_local
957
958 inv_parent = pb.parent.matrix @ offset_mtx
959 inv_parent.invert_safe()
960 fpm = inv_parent @ pb.matrix
961 #}
962 else:#{
963 bone_mtx = rb.matrix.to_4x4()
964 local_inv = rb.matrix_local.inverted_safe()
965 fpm = bone_mtx @ local_inv @ pb.matrix
966 #}
967
968 loc, rot, sca = fpm.decompose()
969
970 # rotation
971 lc_m = pb.matrix_channel.to_3x3()
972 if pb.parent is not None:#{
973 smtx = pb.parent.matrix_channel.to_3x3()
974 lc_m = smtx.inverted() @ lc_m
975 #}
976 rq = lc_m.to_quaternion()
977
978 kf = mdl_transform()
979 kf.co[0] = loc[0]
980 kf.co[1] = loc[2]
981 kf.co[2] = -loc[1]
982 kf.q[0] = rq[1]
983 kf.q[1] = rq[3]
984 kf.q[2] = -rq[2]
985 kf.q[3] = rq[0]
986 kf.s[0] = sca[0]
987 kf.s[1] = sca[1]
988 kf.s[2] = sca[2]
989 sr_compile.keyframe_data.extend(bytearray(kf))
990
991 i+=1
992 #}
993 #}
994
995 # Add to animation buffer
996 #
997 sr_compile.anim_data.extend(bytearray(anim))
998 node.anim_count += 1
999
1000 # Report progress
1001 #
1002 print( F"[SR] | anim( {NLAStrip.action.name} )" )
1003 #}
1004 #}
1005
1006 # Restore context to how it was before
1007 #
1008 bpy.context.scene.frame_set( previous_frame )
1009 obj.animation_data.action = previous_action
1010 obj.data.pose_position = POSE_OR_REST_CACHE
1011 #}
1012
1013 sr_compile.armature_data.extend(bytearray(node))
1014 #}
1015
1016 def sr_ent_push( struct ):
1017 #{
1018 clase = type(struct).__name__
1019
1020 if clase not in sr_compile.entity_data:#{
1021 sr_compile.entity_data[ clase ] = bytearray()
1022 sr_compile.entity_info[ clase ] = { 'size': sizeof(struct) }
1023 #}
1024
1025 index = len(sr_compile.entity_data[ clase ])//sizeof(struct)
1026 sr_compile.entity_data[ clase ].extend( bytearray(struct) )
1027 return index
1028 #}
1029
1030 def sr_array_title( arr, name, count, size, offset ):
1031 #{
1032 for i in range(len(name)):#{
1033 arr.name[i] = ord(name[i])
1034 #}
1035 arr.file_offset = offset
1036 arr.item_count = count
1037 arr.item_size = size
1038 #}
1039
1040 def sr_compile( collection ):
1041 #{
1042 print( F"[SR] compiler begin ({collection.name}.mdl)" )
1043
1044 #settings
1045 sr_compile.pack_textures = collection.SR_data.pack_textures
1046 sr_compile.pack_animations = collection.SR_data.animations
1047
1048 # caches
1049 sr_compile.string_cache = {}
1050 sr_compile.mesh_cache = {}
1051 sr_compile.material_cache = {}
1052 sr_compile.texture_cache = {}
1053
1054 # compiled data
1055 sr_compile.mesh_data = bytearray()
1056 sr_compile.submesh_data = bytearray()
1057 sr_compile.vertex_data = bytearray()
1058 sr_compile.indice_data = bytearray()
1059 sr_compile.bone_data = bytearray()
1060 sr_compile.material_data = bytearray()
1061 sr_compile.armature_data = bytearray()
1062 sr_compile.anim_data = bytearray()
1063 sr_compile.keyframe_data = bytearray()
1064 sr_compile.texture_data = bytearray()
1065
1066 # just bytes not structures
1067 sr_compile.string_data = bytearray()
1068 sr_compile.pack_data = bytearray()
1069
1070 # variable
1071 sr_compile.entity_data = {}
1072 sr_compile.entity_info = {}
1073
1074 print( F"[SR] assign entity ID's" )
1075 sr_compile.entities = {}
1076 sr_compile.entity_ids = {}
1077
1078 mesh_count = 0
1079 for obj in collection.all_objects: #{
1080 if obj.type == 'MESH': mesh_count += 1
1081
1082 ent_type = obj_ent_type( obj )
1083 if ent_type == 'none': continue
1084
1085 if ent_type not in sr_compile.entities: sr_compile.entities[ent_type] = []
1086 sr_compile.entity_ids[obj.name] = len( sr_compile.entities[ent_type] )
1087 sr_compile.entities[ent_type] += [obj]
1088 #}
1089
1090 print( F"[SR] Compiling geometry" )
1091 i=0
1092 for obj in collection.all_objects:#{
1093 if obj.type == 'MESH':#{
1094 i+=1
1095 print( F'[SR] {i: 3}/{mesh_count} {obj.name:<40}', end='\r' )
1096 sr_compile_mesh( obj )
1097 #}
1098 #}
1099
1100 checkpoint_count = 0
1101 pathindice_count = 0
1102 audio_clip_count = 0
1103
1104 for ent_type, arr in sr_compile.entities.items():#{
1105 print(F"[SR] Compiling {len(arr)} {ent_type}{'s' if len(arr)>1 else ''}")
1106
1107 for i in range(len(arr)):#{
1108 obj = arr[i]
1109
1110 print( F"[SR] {i+1: 3}/{len(arr)} {obj.name:<40} ",end='\r' )
1111
1112 if ent_type == 'mdl_armature': sr_compile_armature(obj)
1113 elif ent_type == 'ent_light': #{
1114 light = ent_light()
1115 compile_obj_transform( obj, light.transform )
1116 light.daytime = obj.data.SR_data.daytime
1117 if obj.data.type == 'POINT':#{
1118 light.type = 0
1119 #}
1120 elif obj.data.type == 'SPOT':#{
1121 light.type = 1
1122 light.angle = obj.data.spot_size*0.5
1123 #}
1124 light.range = obj.data.cutoff_distance
1125 light.colour[0] = obj.data.color[0]
1126 light.colour[1] = obj.data.color[1]
1127 light.colour[2] = obj.data.color[2]
1128 light.colour[3] = obj.data.energy
1129 sr_ent_push( light )
1130 #}
1131 elif ent_type == 'ent_gate': #{
1132 gate = ent_gate()
1133 gate.type = 0
1134 obj_data = obj.SR_data.ent_gate[0]
1135 mesh_data = obj.data.SR_data.ent_gate[0]
1136 if obj_data.target:#{
1137 gate.target = sr_compile.entity_ids[obj_data.target.name]
1138 gate.type = 1
1139 #}
1140 gate.dimensions[0] = mesh_data.dimensions[0]
1141 gate.dimensions[1] = mesh_data.dimensions[1]
1142 gate.dimensions[2] = mesh_data.dimensions[2]
1143
1144 q = [obj.matrix_local.to_quaternion(), (0,0,0,1)]
1145 co = [obj.matrix_world @ Vector((0,0,0)), (0,0,0)]
1146
1147 if obj_data.target:#{
1148 q[1] = obj_data.target.matrix_local.to_quaternion()
1149 co[1]= obj_data.target.matrix_world @ Vector((0,0,0))
1150 #}
1151
1152 # Setup transform
1153 #
1154 for x in range(2):#{
1155 gate.co[x][0] = co[x][0]
1156 gate.co[x][1] = co[x][2]
1157 gate.co[x][2] = -co[x][1]
1158 gate.q[x][0] = q[x][1]
1159 gate.q[x][1] = q[x][3]
1160 gate.q[x][2] = -q[x][2]
1161 gate.q[x][3] = q[x][0]
1162 #}
1163
1164 sr_ent_push( gate )
1165 #}
1166 elif ent_type == 'ent_spawn': #{
1167 spawn = ent_spawn()
1168 compile_obj_transform( obj, spawn.transform )
1169 obj_data = obj.SR_data.ent_spawn[0]
1170 spawn.pstr_name = sr_compile_string( obj_data.name )
1171 sr_ent_push( spawn )
1172 #}
1173 elif ent_type == 'ent_route': #{
1174 obj_data = obj.SR_data.ent_route[0]
1175 route = ent_route()
1176 route.pstr_name = sr_compile_string( obj_data.alias )
1177 route.checkpoints_start = checkpoint_count
1178 route.checkpoints_count = 0
1179
1180 for ci in range(3):
1181 route.colour[ci] = obj_data.colour[ci]
1182 route.colour[3] = 1.0
1183
1184 compile_obj_transform( obj, route.transform )
1185
1186 checkpoints = obj_data.gates
1187 route_nodes = []
1188
1189 for uc in obj.users_collection[0].objects:#{
1190 uc_type = obj_ent_type( uc )
1191 if uc_type == 'ent_gate' or uc_type == 'ent_route_node':
1192 route_nodes += [uc]
1193 #}
1194 graph = node_graph( route_nodes )
1195
1196 for i in range(len(checkpoints)):#{
1197 gi = checkpoints[i].target
1198 gj = checkpoints[(i+1)%len(checkpoints)].target
1199 gate = gi
1200
1201 if gi:#{
1202 dest = gi.SR_data.ent_gate[0].target
1203 gi = dest
1204 #}
1205
1206 if gi==gj: continue # error?
1207 if not gi or not gj: continue
1208
1209 checkpoint = ent_checkpoint()
1210 checkpoint.gate_index = sr_compile.entity_ids[gate.name]
1211 checkpoint.path_start = pathindice_count
1212 checkpoint.path_count = 0
1213
1214 path = dijkstra( graph, gj.name, gi.name )
1215 if path:#{
1216 for pi in range(1,len(path)-1):#{
1217 pathindice = ent_path_index()
1218 pathindice.index = sr_compile.entity_ids[path[pi]]
1219 sr_ent_push( pathindice )
1220
1221 checkpoint.path_count += 1
1222 pathindice_count += 1
1223 #}
1224 #}
1225
1226 sr_ent_push( checkpoint )
1227 route.checkpoints_count += 1
1228 checkpoint_count += 1
1229 #}
1230
1231 sr_ent_push( route )
1232 #}
1233 elif ent_type == 'ent_route_node':#{
1234 rn = ent_route_node()
1235 rn.co[0] = obj.location[0]
1236 rn.co[1] = obj.location[2]
1237 rn.co[2] = -obj.location[1]
1238 sr_ent_push( rn )
1239 #}
1240 elif ent_type == 'ent_water':#{
1241 water = ent_water()
1242 compile_obj_transform( obj, water.transform )
1243 water.max_dist = 0.0
1244 sr_ent_push( water )
1245 #}
1246 elif ent_type == 'ent_audio':#{
1247 obj_data = obj.SR_data.ent_audio[0]
1248 audio = ent_audio()
1249 compile_obj_transform( obj, audio.transform )
1250 audio.clip_start = audio_clip_count
1251 audio.clip_count = len(obj_data.files)
1252 audio.max_channels = obj_data.max_channels
1253 audio.volume = obj_data.volume
1254
1255 # TODO flags:
1256 # - allow/disable doppler
1257 # - channel group tags with random colours
1258 # - transition properties
1259
1260 if obj_data.flag_loop: audio.flags |= 0x1
1261 if obj_data.flag_nodoppler: audio.flags |= 0x2
1262 if obj_data.flag_3d: audio.flags |= 0x4
1263 if obj_data.flag_auto: audio.flags |= 0x8
1264 if obj_data.formato == '0': audio.flags |= 0x000
1265 elif obj_data.formato == '1': audio.flags |= 0x400
1266 elif obj_data.formato == '2': audio.flags |= 0x1000
1267
1268 for ci in range(audio.clip_count):#{
1269 entry = obj_data.files[ci]
1270 clip = ent_audio_clip()
1271 clip.probability = entry.probability
1272 if obj_data.formato == '2':#{
1273 sr_pack_file( clip._anon.file, '', vg_str_bin(entry.path) )
1274 #}
1275 else:#{
1276 clip._anon.file.path = sr_compile_string( entry.path )
1277 clip._anon.file.pack_offset = 0
1278 clip._anon.file.pack_size = 0
1279 #}
1280 sr_ent_push( clip )
1281 #}
1282 sr_ent_push( audio )
1283 #}
1284 elif ent_type == 'ent_volume':#{
1285 obj_data = obj.SR_data.ent_volume[0]
1286 volume = ent_volume()
1287 volume.type = int(obj_data.subtype)
1288 compile_obj_transform( obj, volume.transform )
1289
1290 if obj_data.target:#{
1291 target = obj_data.target
1292 volume.target.type = sr_entity_alias[obj_ent_type(target)]
1293 volume.target.index = sr_compile.entity_ids[ target.name ]
1294 #}
1295
1296 sr_ent_push(volume)
1297 #}
1298 #}
1299 #}
1300
1301 print( F"[SR] Writing file" )
1302
1303 file_array_instructions = {}
1304 file_offset = 0
1305
1306 def _write_array( name, item_size, data ):#{
1307 nonlocal file_array_instructions, file_offset
1308
1309 count = len(data)//item_size
1310 file_array_instructions[name] = {'count':count, 'size':item_size,\
1311 'data':data, 'offset': file_offset}
1312 file_offset += len(data)
1313 file_offset = int_align_to( file_offset, 8 )
1314 #}
1315
1316 _write_array( 'strings', 1, sr_compile.string_data )
1317 _write_array( 'mdl_mesh', sizeof(mdl_mesh), sr_compile.mesh_data )
1318 _write_array( 'mdl_submesh', sizeof(mdl_submesh), sr_compile.submesh_data )
1319 _write_array( 'mdl_material', sizeof(mdl_material), sr_compile.material_data)
1320 _write_array( 'mdl_texture', sizeof(mdl_texture), sr_compile.texture_data)
1321 _write_array( 'mdl_armature', sizeof(mdl_armature), sr_compile.armature_data)
1322 _write_array( 'mdl_bone', sizeof(mdl_bone), sr_compile.bone_data )
1323
1324 for name, buffer in sr_compile.entity_data.items():#{
1325 _write_array( name, sr_compile.entity_info[name]['size'], buffer )
1326 #}
1327
1328 _write_array( 'mdl_animation', sizeof(mdl_animation), sr_compile.anim_data)
1329 _write_array( 'mdl_keyframe', sizeof(mdl_transform),sr_compile.keyframe_data)
1330 _write_array( 'mdl_vert', sizeof(mdl_vert), sr_compile.vertex_data )
1331 _write_array( 'mdl_indice', sizeof(c_uint32), sr_compile.indice_data )
1332 _write_array( 'pack', 1, sr_compile.pack_data )
1333
1334 header_size = int_align_to( sizeof(mdl_header), 8 )
1335 index_size = int_align_to( sizeof(mdl_array)*len(file_array_instructions),8 )
1336
1337 folder = bpy.path.abspath(bpy.context.scene.SR_data.export_dir)
1338 path = F"{folder}{collection.name}.mdl"
1339 print( path )
1340
1341 fp = open( path, "wb" )
1342 header = mdl_header()
1343 header.version = 40
1344 sr_array_title( header.arrays, \
1345 'index', len(file_array_instructions), \
1346 sizeof(mdl_array), header_size )
1347
1348 fp.write( bytearray_align_to( bytearray(header), 8 ) )
1349
1350 print( F'[SR] {"name":>16}| count | offset' )
1351 index = bytearray()
1352 for name,info in file_array_instructions.items():#{
1353 arr = mdl_array()
1354 offset = info['offset'] + header_size + index_size
1355 sr_array_title( arr, name, info['count'], info['size'], offset )
1356 index.extend( bytearray(arr) )
1357
1358 print( F'[SR] {name:>16}| {info["count"]: 8} '+\
1359 F' 0x{info["offset"]:02x}' )
1360 #}
1361 fp.write( bytearray_align_to( index, 8 ) )
1362 #bytearray_print_hex( index )
1363
1364 for name,info in file_array_instructions.items():#{
1365 fp.write( bytearray_align_to( info['data'], 8 ) )
1366 #}
1367
1368 fp.close()
1369
1370 print( '[SR] done' )
1371 #}
1372
1373 class SR_SCENE_SETTINGS(bpy.types.PropertyGroup):
1374 #{
1375 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
1376 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
1377 gizmos: bpy.props.BoolProperty( name="Draw Gizmos", default=True )
1378
1379 panel: bpy.props.EnumProperty(
1380 name='Panel',
1381 description='',
1382 items=[
1383 ('EXPORT', 'Export', '', 'MOD_BUILD',0),
1384 ('ENTITY', 'Entity', '', 'MONKEY',1),
1385 ('SETTINGS', 'Settings', 'Settings', 'PREFERENCES',2),
1386 ],
1387 )
1388 #}
1389
1390 class SR_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
1391 #{
1392 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
1393 animations: bpy.props.BoolProperty( name="Export animation", default=True)
1394 #}
1395
1396 def sr_get_mirror_bone( bones ):
1397 #{
1398 side = bones.active.name[-1:]
1399 other_name = bones.active.name[:-1]
1400 if side == 'L': other_name += 'R'
1401 elif side == 'R': other_name += 'L'
1402 else: return None
1403
1404 for b in bones:#{
1405 if b.name == other_name:
1406 return b
1407 #}
1408
1409 return None
1410 #}
1411
1412 class SR_MIRROR_BONE_X(bpy.types.Operator):
1413 #{
1414 bl_idname="skaterift.mirror_bone"
1415 bl_label="Mirror bone attributes - SkateRift"
1416
1417 def execute(_,context):
1418 #{
1419 active_object = context.active_object
1420 bones = active_object.data.bones
1421 a = bones.active
1422 b = sr_get_mirror_bone( bones )
1423
1424 if not b: return {'FINISHED'}
1425
1426 b.SR_data.collider = a.SR_data.collider
1427
1428 def _v3copyflipy( a, b ):#{
1429 b[0] = a[0]
1430 b[1] = -a[1]
1431 b[2] = a[2]
1432 #}
1433
1434 _v3copyflipy( a.SR_data.collider_min, b.SR_data.collider_min )
1435 _v3copyflipy( a.SR_data.collider_max, b.SR_data.collider_max )
1436 b.SR_data.collider_min[1] = -a.SR_data.collider_max[1]
1437 b.SR_data.collider_max[1] = -a.SR_data.collider_min[1]
1438
1439 b.SR_data.cone_constraint = a.SR_data.cone_constraint
1440
1441 _v3copyflipy( a.SR_data.conevx, b.SR_data.conevy )
1442 _v3copyflipy( a.SR_data.conevy, b.SR_data.conevx )
1443 _v3copyflipy( a.SR_data.coneva, b.SR_data.coneva )
1444
1445 b.SR_data.conet = a.SR_data.conet
1446
1447 # redraw
1448 ob = bpy.context.scene.objects[0]
1449 ob.hide_render = ob.hide_render
1450 return {'FINISHED'}
1451 #}
1452 #}
1453
1454 class SR_COMPILE(bpy.types.Operator):
1455 #{
1456 bl_idname="skaterift.compile_all"
1457 bl_label="Compile All"
1458
1459 def execute(_,context):
1460 #{
1461 view_layer = bpy.context.view_layer
1462 for col in view_layer.layer_collection.children["export"].children:
1463 if not col.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1464 sr_compile( bpy.data.collections[col.name] )
1465
1466 return {'FINISHED'}
1467 #}
1468 #}
1469
1470 class SR_COMPILE_THIS(bpy.types.Operator):
1471 #{
1472 bl_idname="skaterift.compile_this"
1473 bl_label="Compile This collection"
1474
1475 def execute(_,context):
1476 #{
1477 col = bpy.context.collection
1478 sr_compile( col )
1479
1480 return {'FINISHED'}
1481 #}
1482 #}
1483
1484 class SR_INTERFACE(bpy.types.Panel):
1485 #{
1486 bl_idname = "VIEW3D_PT_skate_rift"
1487 bl_label = "Skate Rift"
1488 bl_space_type = 'VIEW_3D'
1489 bl_region_type = 'UI'
1490 bl_category = "Skate Rift"
1491
1492 def draw(_, context):
1493 #{
1494 # Compiler section
1495
1496 row = _.layout.row()
1497 row.scale_y = 1.75
1498 row.prop( context.scene.SR_data, 'panel', expand=True )
1499
1500 if context.scene.SR_data.panel == 'SETTINGS': #{
1501 _.layout.prop( context.scene.SR_data, 'gizmos' )
1502 #}
1503 elif context.scene.SR_data.panel == 'EXPORT': #{
1504 _.layout.prop( context.scene.SR_data, "export_dir" )
1505 col = bpy.context.collection
1506
1507 found_in_export = False
1508 export_count = 0
1509 view_layer = bpy.context.view_layer
1510 for c1 in view_layer.layer_collection.children["export"].children: #{
1511 if not c1.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1512 export_count += 1
1513
1514 if c1.name == col.name: #{
1515 found_in_export = True
1516 #}
1517 #}
1518
1519 box = _.layout.box()
1520 row = box.row()
1521 row.alignment = 'CENTER'
1522 row.scale_y = 1.5
1523
1524 if found_in_export: #{
1525 row.label( text=col.name + ".mdl" )
1526 box.prop( col.SR_data, "pack_textures" )
1527 box.prop( col.SR_data, "animations" )
1528 box.operator( "skaterift.compile_this" )
1529 #}
1530 else: #{
1531 row.enabled=False
1532 row.label( text=col.name )
1533
1534 row = box.row()
1535 row.enabled=False
1536 row.alignment = 'CENTER'
1537 row.scale_y = 1.5
1538 row.label( text="This collection is not in the export group" )
1539 #}
1540
1541 box = _.layout.box()
1542 row = box.row()
1543
1544 split = row.split( factor=0.3, align=True )
1545 split.prop( context.scene.SR_data, "use_hidden", text="hidden" )
1546
1547 row1 = split.row()
1548 if export_count == 0:
1549 row1.enabled=False
1550 row1.operator( "skaterift.compile_all", \
1551 text=F"Compile all ({export_count} collections)" )
1552 #}
1553 elif context.scene.SR_data.panel == 'ENTITY': #{
1554 active_object = context.active_object
1555 if not active_object: return
1556
1557 box = _.layout.box()
1558 row = box.row()
1559 row.alignment = 'CENTER'
1560 row.label( text=active_object.name )
1561 row.scale_y = 1.5
1562
1563 def _draw_prop_collection( data ): #{
1564 nonlocal box
1565 row = box.row()
1566 row.alignment = 'CENTER'
1567 row.enabled = False
1568 row.scale_y = 1.5
1569 row.label( text=F'{data[0]}' )
1570
1571 if hasattr(type(data[0]),'sr_inspector'):#{
1572 type(data[0]).sr_inspector( box, data )
1573 #}
1574 else:#{
1575 for a in data[0].__annotations__:
1576 box.prop( data[0], a )
1577 #}
1578 #}
1579
1580 if active_object.type == 'ARMATURE': #{
1581 if active_object.mode == 'POSE': #{
1582 bones = active_object.data.bones
1583 mb = sr_get_mirror_bone( bones )
1584 if mb:#{
1585 box.operator( "skaterift.mirror_bone", \
1586 text=F'Mirror attributes to {mb.name}' )
1587 #}
1588
1589 _draw_prop_collection( [bones.active.SR_data ] )
1590 #}
1591 else: #{
1592 row = box.row()
1593 row.alignment='CENTER'
1594 row.scale_y=2.0
1595 row.enabled=False
1596 row.label( text="Enter pose mode to modify bone properties" )
1597 #}
1598 #}
1599 elif active_object.type == 'LIGHT': #{
1600 _draw_prop_collection( [active_object.data.SR_data] )
1601 #}
1602 elif active_object.type == 'EMPTY' or active_object.type == 'MESH': #{
1603 box.prop( active_object.SR_data, "ent_type" )
1604 ent_type = active_object.SR_data.ent_type
1605
1606 col = getattr( active_object.SR_data, ent_type, None )
1607 if col != None and len(col)!=0: _draw_prop_collection( col )
1608
1609 if active_object.type == 'MESH':#{
1610 col = getattr( active_object.data.SR_data, ent_type, None )
1611 if col != None and len(col)!=0: _draw_prop_collection( col )
1612 #}
1613 #}
1614 #}
1615 #}
1616 #}
1617
1618 class SR_MATERIAL_PANEL(bpy.types.Panel):
1619 #{
1620 bl_label="Skate Rift material"
1621 bl_idname="MATERIAL_PT_sr_material"
1622 bl_space_type='PROPERTIES'
1623 bl_region_type='WINDOW'
1624 bl_context="material"
1625
1626 def draw(_,context):
1627 #{
1628 active_object = bpy.context.active_object
1629 if active_object == None: return
1630 active_mat = active_object.active_material
1631 if active_mat == None: return
1632
1633 info = material_info( active_mat )
1634
1635 if 'tex_diffuse' in info:#{
1636 _.layout.label( icon='INFO', \
1637 text=F"{info['tex_diffuse'].name} will be compiled" )
1638 #}
1639
1640 _.layout.prop( active_mat.SR_data, "shader" )
1641 _.layout.prop( active_mat.SR_data, "surface_prop" )
1642 _.layout.prop( active_mat.SR_data, "collision" )
1643
1644 if active_mat.SR_data.collision:#{
1645 _.layout.prop( active_mat.SR_data, "skate_surface" )
1646 _.layout.prop( active_mat.SR_data, "grind_surface" )
1647 _.layout.prop( active_mat.SR_data, "grow_grass" )
1648 #}
1649
1650 if active_mat.SR_data.shader == "terrain_blend":#{
1651 box = _.layout.box()
1652 box.prop( active_mat.SR_data, "blend_offset" )
1653 box.prop( active_mat.SR_data, "sand_colour" )
1654 #}
1655 elif active_mat.SR_data.shader == "vertex_blend":#{
1656 box = _.layout.box()
1657 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
1658 box.prop( active_mat.SR_data, "blend_offset" )
1659 #}
1660 elif active_mat.SR_data.shader == "water":#{
1661 box = _.layout.box()
1662 box.label( icon='INFO', text="Depth scale of 16 meters" )
1663 box.prop( active_mat.SR_data, "shore_colour" )
1664 box.prop( active_mat.SR_data, "ocean_colour" )
1665 #}
1666 #}
1667 #}
1668
1669 def sr_get_type_enum( scene, context ):
1670 #{
1671 items = [('none','None',"")]
1672 mesh_entities=['ent_gate','ent_water']
1673 point_entities=['ent_spawn','ent_route_node','ent_route']
1674
1675 for e in point_entities: items += [(e,e,'')]
1676
1677 if context.scene.SR_data.panel == 'ENTITY': #{
1678 if context.active_object.type == 'MESH': #{
1679 for e in mesh_entities: items += [(e,e,'')]
1680 #}
1681 #}
1682 else: #{
1683 for e in mesh_entities: items += [(e,e,'')]
1684 #}
1685
1686 return items
1687 #}
1688
1689 def sr_on_type_change( _, context ):
1690 #{
1691 obj = context.active_object
1692 ent_type = obj.SR_data.ent_type
1693 if ent_type == 'none': return
1694 if obj.type == 'MESH':#{
1695 col = getattr( obj.data.SR_data, ent_type, None )
1696 if col != None and len(col)==0: col.add()
1697 #}
1698
1699 col = getattr( obj.SR_data, ent_type, None )
1700 if col != None and len(col)==0: col.add()
1701 #}
1702
1703 class SR_OBJECT_ENT_SPAWN(bpy.types.PropertyGroup):
1704 #{
1705 alias: bpy.props.StringProperty( name='alias' )
1706 #}
1707
1708 class SR_OBJECT_ENT_GATE(bpy.types.PropertyGroup):
1709 #{
1710 target: bpy.props.PointerProperty( \
1711 type=bpy.types.Object, name="destination", \
1712 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
1713 #}
1714
1715 class SR_MESH_ENT_GATE(bpy.types.PropertyGroup):
1716 #{
1717 dimensions: bpy.props.FloatVectorProperty(name="dimensions",size=3)
1718 #}
1719
1720 class SR_OBJECT_ENT_ROUTE_ENTRY(bpy.types.PropertyGroup):
1721 #{
1722 target: bpy.props.PointerProperty( \
1723 type=bpy.types.Object, name='target', \
1724 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
1725 #}
1726
1727 class SR_UL_ROUTE_NODE_LIST(bpy.types.UIList):
1728 #{
1729 bl_idname = 'SR_UL_ROUTE_NODE_LIST'
1730
1731 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
1732 #{
1733 layout.prop( item, 'target', text='', emboss=False )
1734 #}
1735 #}
1736
1737 class SR_OT_ROUTE_LIST_NEW_ITEM(bpy.types.Operator):
1738 #{
1739 bl_idname = "skaterift.new_entry"
1740 bl_label = "Add gate"
1741
1742 def execute(self, context):#{
1743 active_object = context.active_object
1744 active_object.SR_data.ent_route[0].gates.add()
1745 return{'FINISHED'}
1746 #}
1747 #}
1748
1749 class SR_OT_ROUTE_LIST_DEL_ITEM(bpy.types.Operator):
1750 #{
1751 bl_idname = "skaterift.del_entry"
1752 bl_label = "Remove gate"
1753
1754 @classmethod
1755 def poll(cls, context):#{
1756 active_object = context.active_object
1757 if obj_ent_type(active_object) == 'ent_gate':#{
1758 return active_object.SR_data.ent_route[0].gates
1759 #}
1760 else: return False
1761 #}
1762
1763 def execute(self, context):#{
1764 active_object = context.active_object
1765 lista = active_object.SR_data.ent_route[0].gates
1766 index = active_object.SR_data.ent_route[0].gates_index
1767 lista.remove(index)
1768 active_object.SR_data.ent_route[0].gates_index = \
1769 min(max(0, index-1), len(lista) - 1)
1770 return{'FINISHED'}
1771 #}
1772 #}
1773
1774 class SR_OT_AUDIO_LIST_NEW_ITEM(bpy.types.Operator):
1775 #{
1776 bl_idname = "skaterift.al_new_entry"
1777 bl_label = "Add file"
1778
1779 def execute(self, context):#{
1780 active_object = context.active_object
1781 active_object.SR_data.ent_audio[0].files.add()
1782 return{'FINISHED'}
1783 #}
1784 #}
1785
1786 class SR_OT_AUDIO_LIST_DEL_ITEM(bpy.types.Operator):
1787 #{
1788 bl_idname = "skaterift.al_del_entry"
1789 bl_label = "Remove file"
1790
1791 @classmethod
1792 def poll(cls, context):#{
1793 active_object = context.active_object
1794 if obj_ent_type(active_object) == 'ent_audio':#{
1795 return active_object.SR_data.ent_audio[0].files
1796 #}
1797 else: return False
1798 #}
1799
1800 def execute(self, context):#{
1801 active_object = context.active_object
1802 lista = active_object.SR_data.ent_audio[0].files
1803 index = active_object.SR_data.ent_audio[0].file_index
1804 lista.remove(index)
1805 active_object.SR_data.ent_audio[0].file_index = \
1806 min(max(0, index-1), len(lista) - 1)
1807 return{'FINISHED'}
1808 #}
1809 #}
1810
1811 class SR_OBJECT_ENT_AUDIO_FILE_ENTRY(bpy.types.PropertyGroup):
1812 #{
1813 path: bpy.props.StringProperty( name="Path" )
1814 probability: bpy.props.FloatProperty( name="Probability",default=100.0 )
1815 #}
1816
1817 class SR_UL_AUDIO_LIST(bpy.types.UIList):
1818 #{
1819 bl_idname = 'SR_UL_AUDIO_LIST'
1820
1821 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
1822 #{
1823 split = layout.split(factor=0.7)
1824 c = split.column()
1825 c.prop( item, 'path', text='', emboss=False )
1826 c = split.column()
1827 c.prop( item, 'probability', text='%', emboss=True )
1828 #}
1829 #}
1830
1831
1832 class SR_OBJECT_ENT_ROUTE(bpy.types.PropertyGroup):
1833 #{
1834 gates: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE_ENTRY)
1835 gates_index: bpy.props.IntProperty()
1836
1837 colour: bpy.props.FloatVectorProperty( \
1838 name="Colour",\
1839 subtype='COLOR',\
1840 min=0.0,max=1.0,\
1841 default=Vector((0.79,0.63,0.48)),\
1842 description="Route colour"\
1843 )
1844
1845 alias: bpy.props.StringProperty(\
1846 name="Alias",\
1847 default="Untitled Course")
1848
1849 @staticmethod
1850 def sr_inspector( layout, data ):
1851 #{
1852 layout.prop( data[0], 'alias' )
1853 layout.prop( data[0], 'colour' )
1854
1855 layout.label( text='Checkpoints' )
1856 layout.template_list('SR_UL_ROUTE_NODE_LIST', 'Checkpoints', \
1857 data[0], 'gates', data[0], 'gates_index', rows=5)
1858
1859 row = layout.row()
1860 row.operator( 'skaterift.new_entry', text='Add' )
1861 row.operator( 'skaterift.del_entry', text='Remove' )
1862 #}
1863 #}
1864
1865 class SR_OBJECT_ENT_VOLUME(bpy.types.PropertyGroup):
1866 #{
1867 subtype: bpy.props.EnumProperty(
1868 name="Subtype",
1869 items=[('0','Trigger',''),
1870 ('1','Particles (0.1s)','')]
1871 )
1872
1873 target: bpy.props.PointerProperty( \
1874 type=bpy.types.Object, name="Target", \
1875 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_audio']))
1876
1877 @staticmethod
1878 def sr_inspector( layout, data ):
1879 #{
1880 data = data[0]
1881 layout.prop( data, 'subtype' )
1882 layout.prop( data, 'target' )
1883 #}
1884 #}
1885
1886 class SR_OBJECT_ENT_AUDIO(bpy.types.PropertyGroup):
1887 #{
1888 files: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO_FILE_ENTRY)
1889 file_index: bpy.props.IntProperty()
1890
1891 flag_3d: bpy.props.BoolProperty( name="3D audio",default=True )
1892 flag_loop: bpy.props.BoolProperty( name="Loop",default=False )
1893 flag_auto: bpy.props.BoolProperty( name="Play at start",default=False )
1894 flag_nodoppler: bpy.props.BoolProperty( name="No Doppler",default=False )
1895 formato: bpy.props.EnumProperty(
1896 name="Format",
1897 items=[('0','Uncompressed Mono',''),
1898 ('1','Compressed Vorbis',''),
1899 ('2','[vg] Bird Synthesis','')]
1900 )
1901 probability_curve: bpy.props.EnumProperty(
1902 name="Probability Curve",
1903 items=[('0','Constant',''),
1904 ('1','Wildlife Daytime',''),
1905 ('2','Wildlife Nighttime','')])
1906 channel_behaviour: bpy.props.EnumProperty(
1907 name="Channel Behaviour",
1908 items=[('0','Unlimited',''),
1909 ('1','Discard if group full', ''),
1910 ('2','Crossfade if group full','')])
1911
1912 transition_duration: bpy.props.FloatProperty(name="Transition Time",\
1913 default=0.2)
1914
1915 max_channels: bpy.props.IntProperty( name="Max Channels", default=1 )
1916 volume: bpy.props.FloatProperty( name="Volume",default=1.0 )
1917
1918 @staticmethod
1919 def sr_inspector( layout, data ):
1920 #{
1921 layout.prop( data[0], 'formato' )
1922 layout.prop( data[0], 'volume' )
1923
1924 box = layout.box()
1925 box.label( text='Channels' )
1926 split = box.split(factor=0.3)
1927 c = split.column()
1928 c.prop( data[0], 'max_channels' )
1929 c = split.column()
1930 c.prop( data[0], 'channel_behaviour', text='Behaviour' )
1931 if data[0].channel_behaviour == '2':
1932 box.prop( data[0], 'transition_duration' )
1933
1934 box = layout.box()
1935 box.label( text='Flags' )
1936 box.prop( data[0], 'flag_3d' )
1937 if data[0].flag_3d: box.prop( data[0], 'flag_nodoppler' )
1938
1939 box.prop( data[0], 'flag_loop' )
1940 box.prop( data[0], 'flag_auto' )
1941
1942 split = layout.split(factor=0.7)
1943 c = split.column()
1944 c.label( text='Filepath' )
1945 c = split.column()
1946 c.label( text='Chance (0.1s)' )
1947
1948 layout.prop( data[0], 'probability_curve' )
1949
1950 layout.template_list('SR_UL_AUDIO_LIST', 'Files', \
1951 data[0], 'files', data[0], 'file_index', rows=5)
1952
1953 row = layout.row()
1954 row.operator( 'skaterift.al_new_entry', text='Add' )
1955 row.operator( 'skaterift.al_del_entry', text='Remove' )
1956 #}
1957 #}
1958
1959 class SR_OBJECT_PROPERTIES(bpy.types.PropertyGroup):
1960 #{
1961 ent_gate: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GATE)
1962 ent_spawn: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SPAWN)
1963 ent_route: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE)
1964 ent_volume: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_VOLUME)
1965 ent_audio: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO)
1966
1967 ent_type: bpy.props.EnumProperty(
1968 name="Type",
1969 items=[('none', 'None', '', 0),
1970 ('ent_gate','Gate','', 1),
1971 ('ent_spawn','Spawn','', 2),
1972 ('ent_route_node', 'Route Node', '', 3 ),
1973 ('ent_route', 'Route', '', 4),
1974 ('ent_water', 'Water Surface', '', 5),
1975 ('ent_volume', 'Volume', '', 6 ),
1976 ('ent_audio', 'Audio Files', '', 7)],
1977 update=sr_on_type_change
1978 )
1979 #}
1980
1981 class SR_MESH_PROPERTIES(bpy.types.PropertyGroup):
1982 #{
1983 ent_gate: bpy.props.CollectionProperty(type=SR_MESH_ENT_GATE)
1984 #}
1985
1986 class SR_LIGHT_PROPERTIES(bpy.types.PropertyGroup):
1987 #{
1988 daytime: bpy.props.BoolProperty( name='Daytime' )
1989 #}
1990
1991 class SR_BONE_PROPERTIES(bpy.types.PropertyGroup):
1992 #{
1993 collider: bpy.props.EnumProperty( name='Collider Type',
1994 items=[('0','none',''),
1995 ('1','box',''),
1996 ('2','capsule','')])
1997
1998 collider_min: bpy.props.FloatVectorProperty( name='Collider Min', size=3 )
1999 collider_max: bpy.props.FloatVectorProperty( name='Collider Max', size=3 )
2000
2001 cone_constraint: bpy.props.BoolProperty( name='Cone constraint' )
2002
2003 conevx: bpy.props.FloatVectorProperty( name='vx' )
2004 conevy: bpy.props.FloatVectorProperty( name='vy' )
2005 coneva: bpy.props.FloatVectorProperty( name='va' )
2006 conet: bpy.props.FloatProperty( name='t' )
2007
2008 @staticmethod
2009 def sr_inspector( layout, data ):
2010 #{
2011 data = data[0]
2012 box = layout.box()
2013 box.prop( data, 'collider' )
2014
2015 if int(data.collider)>0:#{
2016 row = box.row()
2017 row.prop( data, 'collider_min' )
2018 row = box.row()
2019 row.prop( data, 'collider_max' )
2020 #}
2021
2022 box = layout.box()
2023 box.prop( data, 'cone_constraint' )
2024 if data.cone_constraint:#{
2025 row = box.row()
2026 row.prop( data, 'conevx' )
2027 row = box.row()
2028 row.prop( data, 'conevy' )
2029 row = box.row()
2030 row.prop( data, 'coneva' )
2031 box.prop( data, 'conet' )
2032 #}
2033 #}
2034 #}
2035
2036 class SR_MATERIAL_PROPERTIES(bpy.types.PropertyGroup):
2037 #{
2038 shader: bpy.props.EnumProperty(
2039 name="Format",
2040 items = [
2041 ('standard',"standard",''),
2042 ('standard_cutout', "standard_cutout", ''),
2043 ('terrain_blend', "terrain_blend", ''),
2044 ('vertex_blend', "vertex_blend", ''),
2045 ('water',"water",'')
2046 ])
2047
2048 surface_prop: bpy.props.EnumProperty(
2049 name="Surface Property",
2050 items = [
2051 ('0','concrete',''),
2052 ('1','wood',''),
2053 ('2','grass',''),
2054 ('3','tiles',''),
2055 ('4','metal','')
2056 ])
2057
2058 collision: bpy.props.BoolProperty( \
2059 name="Collisions Enabled",\
2060 default=True,\
2061 description = "Can the player collide with this material"\
2062 )
2063 skate_surface: bpy.props.BoolProperty( \
2064 name="Skate Surface", \
2065 default=True,\
2066 description = "Should the game try to target this surface?" \
2067 )
2068 grind_surface: bpy.props.BoolProperty( \
2069 name="Grind Surface", \
2070 default=False,\
2071 description = "Grind face?" \
2072 )
2073 grow_grass: bpy.props.BoolProperty( \
2074 name="Grow Grass", \
2075 default=False,\
2076 description = "Spawn grass sprites on this surface?" \
2077 )
2078 blend_offset: bpy.props.FloatVectorProperty( \
2079 name="Blend Offset", \
2080 size=2, \
2081 default=Vector((0.5,0.0)),\
2082 description="When surface is more than 45 degrees, add this vector " +\
2083 "to the UVs" \
2084 )
2085 sand_colour: bpy.props.FloatVectorProperty( \
2086 name="Sand Colour",\
2087 subtype='COLOR',\
2088 min=0.0,max=1.0,\
2089 default=Vector((0.79,0.63,0.48)),\
2090 description="Blend to this colour near the 0 coordinate on UP axis"\
2091 )
2092 shore_colour: bpy.props.FloatVectorProperty( \
2093 name="Shore Colour",\
2094 subtype='COLOR',\
2095 min=0.0,max=1.0,\
2096 default=Vector((0.03,0.32,0.61)),\
2097 description="Water colour at the shoreline"\
2098 )
2099 ocean_colour: bpy.props.FloatVectorProperty( \
2100 name="Ocean Colour",\
2101 subtype='COLOR',\
2102 min=0.0,max=1.0,\
2103 default=Vector((0.0,0.006,0.03)),\
2104 description="Water colour in the deep bits"\
2105 )
2106 #}
2107
2108 # ---------------------------------------------------------------------------- #
2109 # #
2110 # GUI section #
2111 # #
2112 # ---------------------------------------------------------------------------- #
2113
2114 cv_view_draw_handler = None
2115 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
2116 cv_view_verts = []
2117 cv_view_colours = []
2118 cv_view_course_i = 0
2119
2120 # Draw axis alligned sphere at position with radius
2121 #
2122 def cv_draw_sphere( pos, radius, colour ):
2123 #{
2124 global cv_view_verts, cv_view_colours
2125
2126 ly = pos + Vector((0,0,radius))
2127 lx = pos + Vector((0,radius,0))
2128 lz = pos + Vector((0,0,radius))
2129
2130 pi = 3.14159265358979323846264
2131
2132 for i in range(16):
2133 #{
2134 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
2135 s = math.sin(t)
2136 c = math.cos(t)
2137
2138 py = pos + Vector((s*radius,0.0,c*radius))
2139 px = pos + Vector((s*radius,c*radius,0.0))
2140 pz = pos + Vector((0.0,s*radius,c*radius))
2141
2142 cv_view_verts += [ px, lx ]
2143 cv_view_verts += [ py, ly ]
2144 cv_view_verts += [ pz, lz ]
2145
2146 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2147
2148 ly = py
2149 lx = px
2150 lz = pz
2151 #}
2152 cv_draw_lines()
2153 #}
2154
2155 # Draw axis alligned sphere at position with radius
2156 #
2157 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
2158 #{
2159 global cv_view_verts, cv_view_colours
2160
2161 ly = pos + tz*radius
2162 lx = pos + ty*radius
2163 lz = pos + tz*radius
2164
2165 pi = 3.14159265358979323846264
2166
2167 for i in range(16):
2168 #{
2169 t = ((i+1.0) * 1.0/16.0) * pi
2170 s = math.sin(t)
2171 c = math.cos(t)
2172
2173 s1 = math.sin(t*2.0)
2174 c1 = math.cos(t*2.0)
2175
2176 py = pos + s*tx*radius + c *tz*radius
2177 px = pos + s*tx*radius + c *ty*radius
2178 pz = pos + s1*ty*radius + c1*tz*radius
2179
2180 cv_view_verts += [ px, lx ]
2181 cv_view_verts += [ py, ly ]
2182 cv_view_verts += [ pz, lz ]
2183
2184 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2185
2186 ly = py
2187 lx = px
2188 lz = pz
2189 #}
2190 cv_draw_lines()
2191 #}
2192
2193 # Draw transformed -1 -> 1 cube
2194 #
2195 def cv_draw_ucube( transform, colour, s=Vector((1,1,1)), o=Vector((0,0,0)) ):
2196 #{
2197 global cv_view_verts, cv_view_colours
2198
2199 a = o + -1.0 * s
2200 b = o + 1.0 * s
2201
2202 vs = [None]*8
2203 vs[0] = transform @ Vector((a[0], a[1], a[2]))
2204 vs[1] = transform @ Vector((a[0], b[1], a[2]))
2205 vs[2] = transform @ Vector((b[0], b[1], a[2]))
2206 vs[3] = transform @ Vector((b[0], a[1], a[2]))
2207 vs[4] = transform @ Vector((a[0], a[1], b[2]))
2208 vs[5] = transform @ Vector((a[0], b[1], b[2]))
2209 vs[6] = transform @ Vector((b[0], b[1], b[2]))
2210 vs[7] = transform @ Vector((b[0], a[1], b[2]))
2211
2212 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2213 (0,4),(1,5),(2,6),(3,7)]
2214
2215 for l in indices:
2216 #{
2217 v0 = vs[l[0]]
2218 v1 = vs[l[1]]
2219 cv_view_verts += [(v0[0],v0[1],v0[2])]
2220 cv_view_verts += [(v1[0],v1[1],v1[2])]
2221 cv_view_colours += [colour, colour]
2222 #}
2223 cv_draw_lines()
2224 #}
2225
2226 # Draw line with colour
2227 #
2228 def cv_draw_line( p0, p1, colour ):
2229 #{
2230 global cv_view_verts, cv_view_colours
2231
2232 cv_view_verts += [p0,p1]
2233 cv_view_colours += [colour, colour]
2234 cv_draw_lines()
2235 #}
2236
2237 # Draw line with colour(s)
2238 #
2239 def cv_draw_line2( p0, p1, c0, c1 ):
2240 #{
2241 global cv_view_verts, cv_view_colours
2242
2243 cv_view_verts += [p0,p1]
2244 cv_view_colours += [c0,c1]
2245 cv_draw_lines()
2246 #}
2247
2248 #
2249 #
2250 def cv_tangent_basis( n, tx, ty ):
2251 #{
2252 if abs( n[0] ) >= 0.57735027:
2253 #{
2254 tx[0] = n[1]
2255 tx[1] = -n[0]
2256 tx[2] = 0.0
2257 #}
2258 else:
2259 #{
2260 tx[0] = 0.0
2261 tx[1] = n[2]
2262 tx[2] = -n[1]
2263 #}
2264
2265 tx.normalize()
2266 _ty = n.cross( tx )
2267
2268 ty[0] = _ty[0]
2269 ty[1] = _ty[1]
2270 ty[2] = _ty[2]
2271 #}
2272
2273 # Draw coloured arrow
2274 #
2275 def cv_draw_arrow( p0, p1, c0, size=0.15 ):
2276 #{
2277 global cv_view_verts, cv_view_colours
2278
2279 n = p1-p0
2280 midpt = p0 + n*0.5
2281 n.normalize()
2282
2283 tx = Vector((1,0,0))
2284 ty = Vector((1,0,0))
2285 cv_tangent_basis( n, tx, ty )
2286
2287 cv_view_verts += [p0,p1, midpt+(tx-n)*size,midpt, midpt+(-tx-n)*size,midpt ]
2288 cv_view_colours += [c0,c0,c0,c0,c0,c0]
2289 cv_draw_lines()
2290 #}
2291
2292 def cv_draw_line_dotted( p0, p1, c0, dots=10 ):
2293 #{
2294 global cv_view_verts, cv_view_colours
2295
2296 for i in range(dots):#{
2297 t0 = i/dots
2298 t1 = (i+0.25)/dots
2299
2300 p2 = p0*(1.0-t0)+p1*t0
2301 p3 = p0*(1.0-t1)+p1*t1
2302
2303 cv_view_verts += [p2,p3]
2304 cv_view_colours += [c0,c0]
2305 #}
2306 cv_draw_lines()
2307 #}
2308
2309 # Drawhandles of a bezier control point
2310 #
2311 def cv_draw_bhandle( obj, direction, colour ):
2312 #{
2313 global cv_view_verts, cv_view_colours
2314
2315 p0 = obj.location
2316 h0 = obj.matrix_world @ Vector((0,direction,0))
2317
2318 cv_view_verts += [p0]
2319 cv_view_verts += [h0]
2320 cv_view_colours += [colour,colour]
2321 cv_draw_lines()
2322 #}
2323
2324 # Draw a bezier curve (at fixed resolution 10)
2325 #
2326 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
2327 #{
2328 global cv_view_verts, cv_view_colours
2329
2330 last = p0
2331 for i in range(10):
2332 #{
2333 t = (i+1)/10
2334 a0 = 1-t
2335
2336 tt = t*t
2337 ttt = tt*t
2338 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
2339
2340 cv_view_verts += [(last[0],last[1],last[2])]
2341 cv_view_verts += [(p[0],p[1],p[2])]
2342 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
2343
2344 last = p
2345 #}
2346 cv_draw_lines()
2347 #}
2348
2349 # I think this one extends the handles of the bezier otwards......
2350 #
2351 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
2352 #{
2353 global cv_view_course_i
2354
2355 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
2356
2357 p0 = o0.matrix_world @ Vector((offs, 0,0))
2358 h0 = o0.matrix_world @ Vector((offs, s0,0))
2359 p1 = o1.matrix_world @ Vector((offs, 0,0))
2360 h1 = o1.matrix_world @ Vector((offs,-s1,0))
2361
2362 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
2363 cv_draw_lines()
2364 #}
2365
2366 # Flush the lines buffers. This is called often because god help you if you want
2367 # to do fixed, fast buffers in this catastrophic programming language.
2368 #
2369 def cv_draw_lines():
2370 #{
2371 global cv_view_shader, cv_view_verts, cv_view_colours
2372
2373 if len(cv_view_verts) < 2:
2374 return
2375
2376 lines = batch_for_shader(\
2377 cv_view_shader, 'LINES', \
2378 { "pos":cv_view_verts, "color":cv_view_colours })
2379
2380 lines.draw( cv_view_shader )
2381
2382 cv_view_verts = []
2383 cv_view_colours = []
2384 #}
2385
2386 # I dont remember what this does exactly
2387 #
2388 def cv_draw_bpath( o0,o1,c0,c1 ):
2389 #{
2390 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
2391 #}
2392
2393 # Semi circle to show the limit. and some lines
2394 #
2395 def draw_limit( obj, center, major, minor, amin, amax, colour ):
2396 #{
2397 global cv_view_verts, cv_view_colours
2398 f = 0.05
2399 ay = major*f
2400 ax = minor*f
2401
2402 for x in range(16):#{
2403 t0 = x/16
2404 t1 = (x+1)/16
2405 a0 = amin*(1.0-t0)+amax*t0
2406 a1 = amin*(1.0-t1)+amax*t1
2407
2408 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
2409 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
2410
2411 p0=obj.matrix_world @ p0
2412 p1=obj.matrix_world @ p1
2413 cv_view_verts += [p0,p1]
2414 cv_view_colours += [colour,colour]
2415
2416 if x == 0:#{
2417 cv_view_verts += [p0,center]
2418 cv_view_colours += [colour,colour]
2419 #}
2420 if x == 15:#{
2421 cv_view_verts += [p1,center]
2422 cv_view_colours += [colour,colour]
2423 #}
2424 #}
2425
2426 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
2427 cv_view_colours += [colour,colour]
2428
2429 cv_draw_lines()
2430 #}
2431
2432 # Cone and twist limit
2433 #
2434 def draw_cone_twist( center, vx, vy, va ):
2435 #{
2436 global cv_view_verts, cv_view_colours
2437 axis = vy.cross( vx )
2438 axis.normalize()
2439
2440 size = 0.12
2441
2442 cv_view_verts += [center, center+va*size]
2443 cv_view_colours += [ (1,1,1,1), (1,1,1,1) ]
2444
2445 for x in range(32):#{
2446 t0 = (x/32) * math.tau
2447 t1 = ((x+1)/32) * math.tau
2448
2449 c0 = math.cos(t0)
2450 s0 = math.sin(t0)
2451 c1 = math.cos(t1)
2452 s1 = math.sin(t1)
2453
2454 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
2455 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
2456
2457 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
2458 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
2459
2460 cv_view_verts += [center, p0, p0, p1]
2461 cv_view_colours += [ (0,0,0,0), col0, col0, col1 ]
2462 #}
2463
2464 cv_draw_lines()
2465 #}
2466
2467 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2468 #
2469 def draw_skeleton_helpers( obj ):
2470 #{
2471 global cv_view_verts, cv_view_colours
2472
2473 if obj.data.pose_position != 'REST':#{
2474 return
2475 #}
2476
2477 for bone in obj.data.bones:#{
2478 c = bone.head_local
2479 a = Vector((bone.SR_data.collider_min[0],
2480 bone.SR_data.collider_min[1],
2481 bone.SR_data.collider_min[2]))
2482 b = Vector((bone.SR_data.collider_max[0],
2483 bone.SR_data.collider_max[1],
2484 bone.SR_data.collider_max[2]))
2485
2486 if bone.SR_data.collider == '1':#{
2487 vs = [None]*8
2488 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
2489 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
2490 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
2491 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
2492 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
2493 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
2494 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
2495 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
2496
2497 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2498 (0,4),(1,5),(2,6),(3,7)]
2499
2500 for l in indices:#{
2501 v0 = vs[l[0]]
2502 v1 = vs[l[1]]
2503
2504 cv_view_verts += [(v0[0],v0[1],v0[2])]
2505 cv_view_verts += [(v1[0],v1[1],v1[2])]
2506 cv_view_colours += [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2507 #}
2508 #}
2509 elif bone.SR_data.collider == '2':#{
2510 v0 = b-a
2511 major_axis = 0
2512 largest = -1.0
2513
2514 for i in range(3):#{
2515 if abs(v0[i]) > largest:#{
2516 largest = abs(v0[i])
2517 major_axis = i
2518 #}
2519 #}
2520
2521 v1 = Vector((0,0,0))
2522 v1[major_axis] = 1.0
2523
2524 tx = Vector((0,0,0))
2525 ty = Vector((0,0,0))
2526
2527 cv_tangent_basis( v1, tx, ty )
2528 r = (abs(tx.dot( v0 )) + abs(ty.dot( v0 ))) * 0.25
2529 l = v0[ major_axis ] - r*2
2530
2531 p0 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l*-0.5 )
2532 p1 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l* 0.5 )
2533
2534 colour = [0.2,0.2,0.2,1.0]
2535 colour[major_axis] = 0.5
2536
2537 cv_draw_halfsphere( p0, -v1, ty, tx, r, colour )
2538 cv_draw_halfsphere( p1, v1, ty, tx, r, colour )
2539 cv_draw_line( p0+tx* r, p1+tx* r, colour )
2540 cv_draw_line( p0+tx*-r, p1+tx*-r, colour )
2541 cv_draw_line( p0+ty* r, p1+ty* r, colour )
2542 cv_draw_line( p0+ty*-r, p1+ty*-r, colour )
2543 #}
2544 else:#{
2545 continue
2546 #}
2547
2548 center = obj.matrix_world @ c
2549 if bone.SR_data.cone_constraint:#{
2550 vx = Vector([bone.SR_data.conevx[_] for _ in range(3)])
2551 vy = Vector([bone.SR_data.conevy[_] for _ in range(3)])
2552 va = Vector([bone.SR_data.coneva[_] for _ in range(3)])
2553 draw_cone_twist( center, vx, vy, va )
2554 #}
2555 #}
2556 #}
2557
2558 def cv_ent_gate( obj ):
2559 #{
2560 global cv_view_verts, cv_view_colours
2561
2562 if obj.type != 'MESH': return
2563
2564 mesh_data = obj.data.SR_data.ent_gate[0]
2565 data = obj.SR_data.ent_gate[0]
2566 dims = mesh_data.dimensions
2567
2568 vs = [None]*9
2569 c = Vector((0,0,dims[2]))
2570
2571 vs[0] = obj.matrix_world @ Vector((-dims[0],0.0,-dims[1]+dims[2]))
2572 vs[1] = obj.matrix_world @ Vector((-dims[0],0.0, dims[1]+dims[2]))
2573 vs[2] = obj.matrix_world @ Vector(( dims[0],0.0, dims[1]+dims[2]))
2574 vs[3] = obj.matrix_world @ Vector(( dims[0],0.0,-dims[1]+dims[2]))
2575 vs[4] = obj.matrix_world @ (c+Vector((-1,0,-2)))
2576 vs[5] = obj.matrix_world @ (c+Vector((-1,0, 2)))
2577 vs[6] = obj.matrix_world @ (c+Vector(( 1,0, 2)))
2578 vs[7] = obj.matrix_world @ (c+Vector((-1,0, 0)))
2579 vs[8] = obj.matrix_world @ (c+Vector(( 1,0, 0)))
2580
2581 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
2582
2583 for l in indices:#{
2584 v0 = vs[l[0]]
2585 v1 = vs[l[1]]
2586 cv_view_verts += [(v0[0],v0[1],v0[2])]
2587 cv_view_verts += [(v1[0],v1[1],v1[2])]
2588 cv_view_colours += [(1,1,0,1),(1,1,0,1)]
2589 #}
2590
2591 sw = (0.4,0.4,0.4,0.2)
2592 if data.target != None:
2593 cv_draw_arrow( obj.location, data.target.location, sw )
2594 #}
2595
2596 def cv_ent_volume( obj ):
2597 #{
2598 global cv_view_verts, cv_view_colours
2599
2600 data = obj.SR_data.ent_volume[0]
2601
2602 if data.subtype == '0':#{
2603 cv_draw_ucube( obj.matrix_world, (0,1,0) )
2604
2605 if data.target:#{
2606 cv_draw_line( obj.location, data.target.location, (0,1,0) )
2607 #}
2608 #}
2609 elif data.subtype == '1':#{
2610 cv_draw_ucube( obj.matrix_world, (1,1,0) )
2611
2612 if data.target:#{
2613 cv_draw_line( obj.location, data.target.location, (1,1,0) )
2614 #}
2615 #}
2616 #}
2617
2618 def dijkstra( graph, start_node, target_node ):
2619 #{
2620 unvisited = [_ for _ in graph]
2621 shortest_path = {}
2622 previous_nodes = {}
2623
2624 for n in unvisited:
2625 shortest_path[n] = 9999999.999999
2626 shortest_path[start_node] = 0
2627
2628 while unvisited:#{
2629 current_min_node = None
2630 for n in unvisited:#{
2631 if current_min_node == None:
2632 current_min_node = n
2633 elif shortest_path[n] < shortest_path[current_min_node]:
2634 current_min_node = n
2635 #}
2636
2637 for branch in graph[current_min_node]:#{
2638 tentative_value = shortest_path[current_min_node]
2639 tentative_value += graph[current_min_node][branch]
2640 if tentative_value < shortest_path[branch]:#{
2641 shortest_path[branch] = tentative_value
2642 previous_nodes[branch] = current_min_node
2643 #}
2644 #}
2645
2646 unvisited.remove(current_min_node)
2647 #}
2648
2649 path = []
2650 node = target_node
2651 while node != start_node:#{
2652 path.append(node)
2653
2654 if node not in previous_nodes: return None
2655 node = previous_nodes[node]
2656 #}
2657
2658 # Add the start node manually
2659 path.append(start_node)
2660 return path
2661 #}
2662
2663 def node_graph( route_nodes ):
2664 #{
2665 graph = {}
2666 for n in route_nodes:
2667 graph[n.name] = {}
2668
2669 for i in range(len(route_nodes)-1):#{
2670 for j in range(i+1, len(route_nodes)):#{
2671 ni = route_nodes[i]
2672 nj = route_nodes[j]
2673
2674 v0 = ni.location - nj.location
2675
2676 gate = None
2677
2678 if ni.SR_data.ent_type == 'ent_gate':
2679 gate = ni
2680
2681 if nj.SR_data.ent_type == 'ent_gate':#{
2682 if gate: continue
2683 gate = nj
2684 #}
2685
2686 if gate:#{
2687 v1 = gate.matrix_world.to_3x3() @ Vector((0,-1,0))
2688 if gate.SR_data.ent_gate[0].target:
2689 if v1.dot(v0) > 0.0: continue
2690 else:
2691 if v1.dot(v0) < 0.0: continue
2692 #}
2693
2694 dist = v0.magnitude
2695
2696 if dist > 25.0: continue
2697 graph[route_nodes[i].name][route_nodes[j].name] = dist
2698 graph[route_nodes[j].name][route_nodes[i].name] = dist
2699 #}
2700 #}
2701
2702 return graph
2703 #}
2704
2705 def cv_draw_route( route, route_nodes ):
2706 #{
2707 pole = Vector((0.2,0.2,10))
2708 hat = Vector((1,8,0.2))
2709 cc = route.SR_data.ent_route[0].colour
2710
2711 cv_draw_ucube(route.matrix_world,cc,Vector((0.5,-7.5,6)),\
2712 Vector((0,-6.5,5.5)))
2713 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5, 0.5,0)) )
2714 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5,-13.5,0)) )
2715 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5, 12)) )
2716 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5,-1)) )
2717
2718 checkpoints = route.SR_data.ent_route[0].gates
2719 graph = node_graph( route_nodes )
2720
2721 for i in range(len(checkpoints)):#{
2722 gi = checkpoints[i].target
2723 gj = checkpoints[(i+1)%len(checkpoints)].target
2724
2725 if gi:#{
2726 dest = gi.SR_data.ent_gate[0].target
2727 if dest:
2728 cv_draw_line_dotted( gi.location, dest.location, cc )
2729 gi = dest
2730 #}
2731
2732 if gi==gj: continue # error?
2733 if not gi or not gj: continue
2734
2735 path = dijkstra( graph, gj.name, gi.name )
2736
2737 if path:#{
2738 for sj in range(len(path)-1):#{
2739 o0 = bpy.data.objects[ path[sj] ]
2740 o1 = bpy.data.objects[ path[sj+1] ]
2741 cv_draw_arrow(o0.location,o1.location,cc,1.5)
2742 #}
2743 #}
2744 else:#{
2745 cv_draw_line_dotted( gi.location, gj.location, cc )
2746 #}
2747 #}
2748 #}
2749
2750 def cv_draw():
2751 #{
2752 global cv_view_shader
2753 global cv_view_verts
2754 global cv_view_colours
2755 global cv_view_course_i
2756
2757 cv_view_course_i = 0
2758 cv_view_verts = []
2759 cv_view_colours = []
2760
2761 cv_view_shader.bind()
2762 gpu.state.depth_mask_set(False)
2763 gpu.state.line_width_set(2.0)
2764 gpu.state.face_culling_set('BACK')
2765 gpu.state.depth_test_set('LESS')
2766 gpu.state.blend_set('NONE')
2767
2768 route_nodes = []
2769 routes = []
2770
2771 for obj in bpy.context.collection.objects:#{
2772 if obj.type == 'ARMATURE':#{
2773 if obj.data.pose_position == 'REST':
2774 draw_skeleton_helpers( obj )
2775 #}
2776 else:#{
2777 ent_type = obj_ent_type( obj )
2778
2779 if ent_type == 'ent_gate':#{
2780 cv_ent_gate( obj )
2781 route_nodes += [obj]
2782 #}
2783 elif ent_type == 'ent_route_node':
2784 route_nodes += [obj]
2785 elif ent_type == 'ent_route':
2786 routes += [obj]
2787 elif ent_type == 'ent_volume':#{
2788 cv_ent_volume( obj )
2789 #}
2790 elif ent_type == 'ent_audio':#{
2791 cv_draw_sphere( obj.location, obj.scale[0], (1,1,0) )
2792 #}
2793 #}
2794 #}
2795
2796 #cv_draw_route_map( route_nodes )
2797 for route in routes:#{
2798 cv_draw_route( route, route_nodes )
2799 #}
2800
2801 cv_draw_lines()
2802 return
2803 #}
2804
2805 classes = [ SR_INTERFACE, SR_MATERIAL_PANEL,\
2806 SR_COLLECTION_SETTINGS, SR_SCENE_SETTINGS, \
2807 SR_COMPILE, SR_COMPILE_THIS, SR_MIRROR_BONE_X,\
2808 \
2809 SR_OBJECT_ENT_GATE, SR_MESH_ENT_GATE, SR_OBJECT_ENT_SPAWN, \
2810 SR_OBJECT_ENT_ROUTE_ENTRY, SR_UL_ROUTE_NODE_LIST, \
2811 SR_OBJECT_ENT_ROUTE, SR_OT_ROUTE_LIST_NEW_ITEM,\
2812 SR_OT_AUDIO_LIST_NEW_ITEM,SR_OT_AUDIO_LIST_DEL_ITEM,\
2813 SR_OBJECT_ENT_VOLUME,
2814 SR_UL_AUDIO_LIST, SR_OBJECT_ENT_AUDIO_FILE_ENTRY,\
2815 SR_OT_ROUTE_LIST_DEL_ITEM,\
2816 SR_OBJECT_ENT_AUDIO,\
2817 \
2818 SR_OBJECT_PROPERTIES, SR_LIGHT_PROPERTIES, SR_BONE_PROPERTIES,
2819 SR_MESH_PROPERTIES, SR_MATERIAL_PROPERTIES \
2820 ]
2821
2822 def register():
2823 #{
2824 for c in classes:
2825 bpy.utils.register_class(c)
2826
2827 bpy.types.Scene.SR_data = \
2828 bpy.props.PointerProperty(type=SR_SCENE_SETTINGS)
2829 bpy.types.Collection.SR_data = \
2830 bpy.props.PointerProperty(type=SR_COLLECTION_SETTINGS)
2831
2832 bpy.types.Object.SR_data = \
2833 bpy.props.PointerProperty(type=SR_OBJECT_PROPERTIES)
2834 bpy.types.Light.SR_data = \
2835 bpy.props.PointerProperty(type=SR_LIGHT_PROPERTIES)
2836 bpy.types.Bone.SR_data = \
2837 bpy.props.PointerProperty(type=SR_BONE_PROPERTIES)
2838 bpy.types.Mesh.SR_data = \
2839 bpy.props.PointerProperty(type=SR_MESH_PROPERTIES)
2840 bpy.types.Material.SR_data = \
2841 bpy.props.PointerProperty(type=SR_MATERIAL_PROPERTIES)
2842
2843 global cv_view_draw_handler
2844 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
2845 cv_draw,(),'WINDOW','POST_VIEW')
2846 #}
2847
2848 def unregister():
2849 #{
2850 for c in classes:
2851 bpy.utils.unregister_class(c)
2852
2853 global cv_view_draw_handler
2854 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
2855 #}
2856
2857 # ---------------------------------------------------------------------------- #
2858 # #
2859 # QOI encoder #
2860 # #
2861 # ---------------------------------------------------------------------------- #
2862 # #
2863 # Transliteration of: #
2864 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
2865 # #
2866 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
2867 # SPDX-License-Identifier: MIT #
2868 # QOI - The "Quite OK Image" format for fast, lossless image compression #
2869 # #
2870 # ---------------------------------------------------------------------------- #
2871
2872 class qoi_rgba_t(Structure):
2873 #{
2874 _pack_ = 1
2875 _fields_ = [("r",c_uint8),
2876 ("g",c_uint8),
2877 ("b",c_uint8),
2878 ("a",c_uint8)]
2879 #}
2880
2881 QOI_OP_INDEX = 0x00 # 00xxxxxx
2882 QOI_OP_DIFF = 0x40 # 01xxxxxx
2883 QOI_OP_LUMA = 0x80 # 10xxxxxx
2884 QOI_OP_RUN = 0xc0 # 11xxxxxx
2885 QOI_OP_RGB = 0xfe # 11111110
2886 QOI_OP_RGBA = 0xff # 11111111
2887
2888 QOI_MASK_2 = 0xc0 # 11000000
2889
2890 def qoi_colour_hash( c ):
2891 #{
2892 return c.r*3 + c.g*5 + c.b*7 + c.a*11
2893 #}
2894
2895 def qoi_eq( a, b ):
2896 #{
2897 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
2898 #}
2899
2900 def qoi_32bit( v ):
2901 #{
2902 return bytearray([ (0xff000000 & v) >> 24, \
2903 (0x00ff0000 & v) >> 16, \
2904 (0x0000ff00 & v) >> 8, \
2905 (0x000000ff & v) ])
2906 #}
2907
2908 def qoi_encode( img ):
2909 #{
2910 data = bytearray()
2911
2912 print(F"{' ':<30}",end='\r')
2913 print(F"[QOI] Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]",end='\r')
2914
2915 index = [ qoi_rgba_t() for _ in range(64) ]
2916
2917 # Header
2918 #
2919 data.extend( bytearray(c_uint32(0x66696f71)) )
2920 data.extend( qoi_32bit( img.size[0] ) )
2921 data.extend( qoi_32bit( img.size[1] ) )
2922 data.extend( bytearray(c_uint8(4)) )
2923 data.extend( bytearray(c_uint8(0)) )
2924
2925 run = 0
2926 px_prev = qoi_rgba_t()
2927 px_prev.r = c_uint8(0)
2928 px_prev.g = c_uint8(0)
2929 px_prev.b = c_uint8(0)
2930 px_prev.a = c_uint8(255)
2931
2932 px = qoi_rgba_t()
2933 px.r = c_uint8(0)
2934 px.g = c_uint8(0)
2935 px.b = c_uint8(0)
2936 px.a = c_uint8(255)
2937
2938 px_len = img.size[0] * img.size[1]
2939 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
2940
2941 for px_pos in range( px_len ): #{
2942 idx = px_pos * img.channels
2943 nc = img.channels-1
2944
2945 px.r = paxels[idx+min(0,nc)]
2946 px.g = paxels[idx+min(1,nc)]
2947 px.b = paxels[idx+min(2,nc)]
2948 px.a = paxels[idx+min(3,nc)]
2949
2950 if qoi_eq( px, px_prev ): #{
2951 run += 1
2952
2953 if (run == 62) or (px_pos == px_len-1): #{
2954 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2955 run = 0
2956 #}
2957 #}
2958 else: #{
2959 if run > 0: #{
2960 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2961 run = 0
2962 #}
2963
2964 index_pos = qoi_colour_hash(px) % 64
2965
2966 if qoi_eq( index[index_pos], px ): #{
2967 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
2968 #}
2969 else: #{
2970 index[ index_pos ].r = px.r
2971 index[ index_pos ].g = px.g
2972 index[ index_pos ].b = px.b
2973 index[ index_pos ].a = px.a
2974
2975 if px.a == px_prev.a: #{
2976 vr = int(px.r) - int(px_prev.r)
2977 vg = int(px.g) - int(px_prev.g)
2978 vb = int(px.b) - int(px_prev.b)
2979
2980 vg_r = vr - vg
2981 vg_b = vb - vg
2982
2983 if (vr > -3) and (vr < 2) and\
2984 (vg > -3) and (vg < 2) and\
2985 (vb > -3) and (vb < 2):
2986 #{
2987 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
2988 data.extend( bytearray( c_uint8(op) ))
2989 #}
2990 elif (vg_r > -9) and (vg_r < 8) and\
2991 (vg > -33) and (vg < 32 ) and\
2992 (vg_b > -9) and (vg_b < 8):
2993 #{
2994 op = QOI_OP_LUMA | (vg+32)
2995 delta = (vg_r+8) << 4 | (vg_b + 8)
2996 data.extend( bytearray( c_uint8(op) ) )
2997 data.extend( bytearray( c_uint8(delta) ))
2998 #}
2999 else: #{
3000 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
3001 data.extend( bytearray( c_uint8(px.r) ))
3002 data.extend( bytearray( c_uint8(px.g) ))
3003 data.extend( bytearray( c_uint8(px.b) ))
3004 #}
3005 #}
3006 else: #{
3007 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
3008 data.extend( bytearray( c_uint8(px.r) ))
3009 data.extend( bytearray( c_uint8(px.g) ))
3010 data.extend( bytearray( c_uint8(px.b) ))
3011 data.extend( bytearray( c_uint8(px.a) ))
3012 #}
3013 #}
3014 #}
3015
3016 px_prev.r = px.r
3017 px_prev.g = px.g
3018 px_prev.b = px.b
3019 px_prev.a = px.a
3020 #}
3021
3022 # Padding
3023 for i in range(7):
3024 data.extend( bytearray( c_uint8(0) ))
3025 data.extend( bytearray( c_uint8(1) ))
3026 bytearray_align_to( data, 16, b'\x00' )
3027
3028 return data
3029 #}