null
[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 audio.channel_behaviour = int(obj_data.channel_behaviour)
1269 if audio.channel_behaviour >= 1:#{
1270 audio.group = obj_data.group
1271 #}
1272 if audio.channel_behaviour == 2:#{
1273 audio.crossfade = obj_data.transition_duration
1274 #}
1275 audio.probability_curve = int(obj_data.probability_curve)
1276
1277 for ci in range(audio.clip_count):#{
1278 entry = obj_data.files[ci]
1279 clip = ent_audio_clip()
1280 clip.probability = entry.probability
1281 if obj_data.formato == '2':#{
1282 sr_pack_file( clip._anon.file, '', vg_str_bin(entry.path) )
1283 #}
1284 else:#{
1285 clip._anon.file.path = sr_compile_string( entry.path )
1286 clip._anon.file.pack_offset = 0
1287 clip._anon.file.pack_size = 0
1288 #}
1289 sr_ent_push( clip )
1290 #}
1291 sr_ent_push( audio )
1292 #}
1293 elif ent_type == 'ent_volume':#{
1294 obj_data = obj.SR_data.ent_volume[0]
1295 volume = ent_volume()
1296 volume.type = int(obj_data.subtype)
1297 compile_obj_transform( obj, volume.transform )
1298
1299 if obj_data.target:#{
1300 target = obj_data.target
1301 volume.target.type = sr_entity_alias[obj_ent_type(target)]
1302 volume.target.index = sr_compile.entity_ids[ target.name ]
1303 #}
1304
1305 sr_ent_push(volume)
1306 #}
1307 #}
1308 #}
1309
1310 print( F"[SR] Writing file" )
1311
1312 file_array_instructions = {}
1313 file_offset = 0
1314
1315 def _write_array( name, item_size, data ):#{
1316 nonlocal file_array_instructions, file_offset
1317
1318 count = len(data)//item_size
1319 file_array_instructions[name] = {'count':count, 'size':item_size,\
1320 'data':data, 'offset': file_offset}
1321 file_offset += len(data)
1322 file_offset = int_align_to( file_offset, 8 )
1323 #}
1324
1325 _write_array( 'strings', 1, sr_compile.string_data )
1326 _write_array( 'mdl_mesh', sizeof(mdl_mesh), sr_compile.mesh_data )
1327 _write_array( 'mdl_submesh', sizeof(mdl_submesh), sr_compile.submesh_data )
1328 _write_array( 'mdl_material', sizeof(mdl_material), sr_compile.material_data)
1329 _write_array( 'mdl_texture', sizeof(mdl_texture), sr_compile.texture_data)
1330 _write_array( 'mdl_armature', sizeof(mdl_armature), sr_compile.armature_data)
1331 _write_array( 'mdl_bone', sizeof(mdl_bone), sr_compile.bone_data )
1332
1333 for name, buffer in sr_compile.entity_data.items():#{
1334 _write_array( name, sr_compile.entity_info[name]['size'], buffer )
1335 #}
1336
1337 _write_array( 'mdl_animation', sizeof(mdl_animation), sr_compile.anim_data)
1338 _write_array( 'mdl_keyframe', sizeof(mdl_transform),sr_compile.keyframe_data)
1339 _write_array( 'mdl_vert', sizeof(mdl_vert), sr_compile.vertex_data )
1340 _write_array( 'mdl_indice', sizeof(c_uint32), sr_compile.indice_data )
1341 _write_array( 'pack', 1, sr_compile.pack_data )
1342
1343 header_size = int_align_to( sizeof(mdl_header), 8 )
1344 index_size = int_align_to( sizeof(mdl_array)*len(file_array_instructions),8 )
1345
1346 folder = bpy.path.abspath(bpy.context.scene.SR_data.export_dir)
1347 path = F"{folder}{collection.name}.mdl"
1348 print( path )
1349
1350 fp = open( path, "wb" )
1351 header = mdl_header()
1352 header.version = 40
1353 sr_array_title( header.arrays, \
1354 'index', len(file_array_instructions), \
1355 sizeof(mdl_array), header_size )
1356
1357 fp.write( bytearray_align_to( bytearray(header), 8 ) )
1358
1359 print( F'[SR] {"name":>16}| count | offset' )
1360 index = bytearray()
1361 for name,info in file_array_instructions.items():#{
1362 arr = mdl_array()
1363 offset = info['offset'] + header_size + index_size
1364 sr_array_title( arr, name, info['count'], info['size'], offset )
1365 index.extend( bytearray(arr) )
1366
1367 print( F'[SR] {name:>16}| {info["count"]: 8} '+\
1368 F' 0x{info["offset"]:02x}' )
1369 #}
1370 fp.write( bytearray_align_to( index, 8 ) )
1371 #bytearray_print_hex( index )
1372
1373 for name,info in file_array_instructions.items():#{
1374 fp.write( bytearray_align_to( info['data'], 8 ) )
1375 #}
1376
1377 fp.close()
1378
1379 print( '[SR] done' )
1380 #}
1381
1382 class SR_SCENE_SETTINGS(bpy.types.PropertyGroup):
1383 #{
1384 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
1385 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
1386 gizmos: bpy.props.BoolProperty( name="Draw Gizmos", default=True )
1387
1388 panel: bpy.props.EnumProperty(
1389 name='Panel',
1390 description='',
1391 items=[
1392 ('EXPORT', 'Export', '', 'MOD_BUILD',0),
1393 ('ENTITY', 'Entity', '', 'MONKEY',1),
1394 ('SETTINGS', 'Settings', 'Settings', 'PREFERENCES',2),
1395 ],
1396 )
1397 #}
1398
1399 class SR_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
1400 #{
1401 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
1402 animations: bpy.props.BoolProperty( name="Export animation", default=True)
1403 #}
1404
1405 def sr_get_mirror_bone( bones ):
1406 #{
1407 side = bones.active.name[-1:]
1408 other_name = bones.active.name[:-1]
1409 if side == 'L': other_name += 'R'
1410 elif side == 'R': other_name += 'L'
1411 else: return None
1412
1413 for b in bones:#{
1414 if b.name == other_name:
1415 return b
1416 #}
1417
1418 return None
1419 #}
1420
1421 class SR_MIRROR_BONE_X(bpy.types.Operator):
1422 #{
1423 bl_idname="skaterift.mirror_bone"
1424 bl_label="Mirror bone attributes - SkateRift"
1425
1426 def execute(_,context):
1427 #{
1428 active_object = context.active_object
1429 bones = active_object.data.bones
1430 a = bones.active
1431 b = sr_get_mirror_bone( bones )
1432
1433 if not b: return {'FINISHED'}
1434
1435 b.SR_data.collider = a.SR_data.collider
1436
1437 def _v3copyflipy( a, b ):#{
1438 b[0] = a[0]
1439 b[1] = -a[1]
1440 b[2] = a[2]
1441 #}
1442
1443 _v3copyflipy( a.SR_data.collider_min, b.SR_data.collider_min )
1444 _v3copyflipy( a.SR_data.collider_max, b.SR_data.collider_max )
1445 b.SR_data.collider_min[1] = -a.SR_data.collider_max[1]
1446 b.SR_data.collider_max[1] = -a.SR_data.collider_min[1]
1447
1448 b.SR_data.cone_constraint = a.SR_data.cone_constraint
1449
1450 _v3copyflipy( a.SR_data.conevx, b.SR_data.conevy )
1451 _v3copyflipy( a.SR_data.conevy, b.SR_data.conevx )
1452 _v3copyflipy( a.SR_data.coneva, b.SR_data.coneva )
1453
1454 b.SR_data.conet = a.SR_data.conet
1455
1456 # redraw
1457 ob = bpy.context.scene.objects[0]
1458 ob.hide_render = ob.hide_render
1459 return {'FINISHED'}
1460 #}
1461 #}
1462
1463 class SR_COMPILE(bpy.types.Operator):
1464 #{
1465 bl_idname="skaterift.compile_all"
1466 bl_label="Compile All"
1467
1468 def execute(_,context):
1469 #{
1470 view_layer = bpy.context.view_layer
1471 for col in view_layer.layer_collection.children["export"].children:
1472 if not col.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1473 sr_compile( bpy.data.collections[col.name] )
1474
1475 return {'FINISHED'}
1476 #}
1477 #}
1478
1479 class SR_COMPILE_THIS(bpy.types.Operator):
1480 #{
1481 bl_idname="skaterift.compile_this"
1482 bl_label="Compile This collection"
1483
1484 def execute(_,context):
1485 #{
1486 col = bpy.context.collection
1487 sr_compile( col )
1488
1489 return {'FINISHED'}
1490 #}
1491 #}
1492
1493 class SR_INTERFACE(bpy.types.Panel):
1494 #{
1495 bl_idname = "VIEW3D_PT_skate_rift"
1496 bl_label = "Skate Rift"
1497 bl_space_type = 'VIEW_3D'
1498 bl_region_type = 'UI'
1499 bl_category = "Skate Rift"
1500
1501 def draw(_, context):
1502 #{
1503 # Compiler section
1504
1505 row = _.layout.row()
1506 row.scale_y = 1.75
1507 row.prop( context.scene.SR_data, 'panel', expand=True )
1508
1509 if context.scene.SR_data.panel == 'SETTINGS': #{
1510 _.layout.prop( context.scene.SR_data, 'gizmos' )
1511 #}
1512 elif context.scene.SR_data.panel == 'EXPORT': #{
1513 _.layout.prop( context.scene.SR_data, "export_dir" )
1514 col = bpy.context.collection
1515
1516 found_in_export = False
1517 export_count = 0
1518 view_layer = bpy.context.view_layer
1519 for c1 in view_layer.layer_collection.children["export"].children: #{
1520 if not c1.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1521 export_count += 1
1522
1523 if c1.name == col.name: #{
1524 found_in_export = True
1525 #}
1526 #}
1527
1528 box = _.layout.box()
1529 row = box.row()
1530 row.alignment = 'CENTER'
1531 row.scale_y = 1.5
1532
1533 if found_in_export: #{
1534 row.label( text=col.name + ".mdl" )
1535 box.prop( col.SR_data, "pack_textures" )
1536 box.prop( col.SR_data, "animations" )
1537 box.operator( "skaterift.compile_this" )
1538 #}
1539 else: #{
1540 row.enabled=False
1541 row.label( text=col.name )
1542
1543 row = box.row()
1544 row.enabled=False
1545 row.alignment = 'CENTER'
1546 row.scale_y = 1.5
1547 row.label( text="This collection is not in the export group" )
1548 #}
1549
1550 box = _.layout.box()
1551 row = box.row()
1552
1553 split = row.split( factor=0.3, align=True )
1554 split.prop( context.scene.SR_data, "use_hidden", text="hidden" )
1555
1556 row1 = split.row()
1557 if export_count == 0:
1558 row1.enabled=False
1559 row1.operator( "skaterift.compile_all", \
1560 text=F"Compile all ({export_count} collections)" )
1561 #}
1562 elif context.scene.SR_data.panel == 'ENTITY': #{
1563 active_object = context.active_object
1564 if not active_object: return
1565
1566 box = _.layout.box()
1567 row = box.row()
1568 row.alignment = 'CENTER'
1569 row.label( text=active_object.name )
1570 row.scale_y = 1.5
1571
1572 def _draw_prop_collection( data ): #{
1573 nonlocal box
1574 row = box.row()
1575 row.alignment = 'CENTER'
1576 row.enabled = False
1577 row.scale_y = 1.5
1578 row.label( text=F'{data[0]}' )
1579
1580 if hasattr(type(data[0]),'sr_inspector'):#{
1581 type(data[0]).sr_inspector( box, data )
1582 #}
1583 else:#{
1584 for a in data[0].__annotations__:
1585 box.prop( data[0], a )
1586 #}
1587 #}
1588
1589 if active_object.type == 'ARMATURE': #{
1590 if active_object.mode == 'POSE': #{
1591 bones = active_object.data.bones
1592 mb = sr_get_mirror_bone( bones )
1593 if mb:#{
1594 box.operator( "skaterift.mirror_bone", \
1595 text=F'Mirror attributes to {mb.name}' )
1596 #}
1597
1598 _draw_prop_collection( [bones.active.SR_data ] )
1599 #}
1600 else: #{
1601 row = box.row()
1602 row.alignment='CENTER'
1603 row.scale_y=2.0
1604 row.enabled=False
1605 row.label( text="Enter pose mode to modify bone properties" )
1606 #}
1607 #}
1608 elif active_object.type == 'LIGHT': #{
1609 _draw_prop_collection( [active_object.data.SR_data] )
1610 #}
1611 elif active_object.type == 'EMPTY' or active_object.type == 'MESH': #{
1612 box.prop( active_object.SR_data, "ent_type" )
1613 ent_type = active_object.SR_data.ent_type
1614
1615 col = getattr( active_object.SR_data, ent_type, None )
1616 if col != None and len(col)!=0: _draw_prop_collection( col )
1617
1618 if active_object.type == 'MESH':#{
1619 col = getattr( active_object.data.SR_data, ent_type, None )
1620 if col != None and len(col)!=0: _draw_prop_collection( col )
1621 #}
1622 #}
1623 #}
1624 #}
1625 #}
1626
1627 class SR_MATERIAL_PANEL(bpy.types.Panel):
1628 #{
1629 bl_label="Skate Rift material"
1630 bl_idname="MATERIAL_PT_sr_material"
1631 bl_space_type='PROPERTIES'
1632 bl_region_type='WINDOW'
1633 bl_context="material"
1634
1635 def draw(_,context):
1636 #{
1637 active_object = bpy.context.active_object
1638 if active_object == None: return
1639 active_mat = active_object.active_material
1640 if active_mat == None: return
1641
1642 info = material_info( active_mat )
1643
1644 if 'tex_diffuse' in info:#{
1645 _.layout.label( icon='INFO', \
1646 text=F"{info['tex_diffuse'].name} will be compiled" )
1647 #}
1648
1649 _.layout.prop( active_mat.SR_data, "shader" )
1650 _.layout.prop( active_mat.SR_data, "surface_prop" )
1651 _.layout.prop( active_mat.SR_data, "collision" )
1652
1653 if active_mat.SR_data.collision:#{
1654 _.layout.prop( active_mat.SR_data, "skate_surface" )
1655 _.layout.prop( active_mat.SR_data, "grind_surface" )
1656 _.layout.prop( active_mat.SR_data, "grow_grass" )
1657 #}
1658
1659 if active_mat.SR_data.shader == "terrain_blend":#{
1660 box = _.layout.box()
1661 box.prop( active_mat.SR_data, "blend_offset" )
1662 box.prop( active_mat.SR_data, "sand_colour" )
1663 #}
1664 elif active_mat.SR_data.shader == "vertex_blend":#{
1665 box = _.layout.box()
1666 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
1667 box.prop( active_mat.SR_data, "blend_offset" )
1668 #}
1669 elif active_mat.SR_data.shader == "water":#{
1670 box = _.layout.box()
1671 box.label( icon='INFO', text="Depth scale of 16 meters" )
1672 box.prop( active_mat.SR_data, "shore_colour" )
1673 box.prop( active_mat.SR_data, "ocean_colour" )
1674 #}
1675 #}
1676 #}
1677
1678 def sr_get_type_enum( scene, context ):
1679 #{
1680 items = [('none','None',"")]
1681 mesh_entities=['ent_gate','ent_water']
1682 point_entities=['ent_spawn','ent_route_node','ent_route']
1683
1684 for e in point_entities: items += [(e,e,'')]
1685
1686 if context.scene.SR_data.panel == 'ENTITY': #{
1687 if context.active_object.type == 'MESH': #{
1688 for e in mesh_entities: items += [(e,e,'')]
1689 #}
1690 #}
1691 else: #{
1692 for e in mesh_entities: items += [(e,e,'')]
1693 #}
1694
1695 return items
1696 #}
1697
1698 def sr_on_type_change( _, context ):
1699 #{
1700 obj = context.active_object
1701 ent_type = obj.SR_data.ent_type
1702 if ent_type == 'none': return
1703 if obj.type == 'MESH':#{
1704 col = getattr( obj.data.SR_data, ent_type, None )
1705 if col != None and len(col)==0: col.add()
1706 #}
1707
1708 col = getattr( obj.SR_data, ent_type, None )
1709 if col != None and len(col)==0: col.add()
1710 #}
1711
1712 class SR_OBJECT_ENT_SPAWN(bpy.types.PropertyGroup):
1713 #{
1714 alias: bpy.props.StringProperty( name='alias' )
1715 #}
1716
1717 class SR_OBJECT_ENT_GATE(bpy.types.PropertyGroup):
1718 #{
1719 target: bpy.props.PointerProperty( \
1720 type=bpy.types.Object, name="destination", \
1721 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
1722 #}
1723
1724 class SR_MESH_ENT_GATE(bpy.types.PropertyGroup):
1725 #{
1726 dimensions: bpy.props.FloatVectorProperty(name="dimensions",size=3)
1727 #}
1728
1729 class SR_OBJECT_ENT_ROUTE_ENTRY(bpy.types.PropertyGroup):
1730 #{
1731 target: bpy.props.PointerProperty( \
1732 type=bpy.types.Object, name='target', \
1733 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_gate']))
1734 #}
1735
1736 class SR_UL_ROUTE_NODE_LIST(bpy.types.UIList):
1737 #{
1738 bl_idname = 'SR_UL_ROUTE_NODE_LIST'
1739
1740 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
1741 #{
1742 layout.prop( item, 'target', text='', emboss=False )
1743 #}
1744 #}
1745
1746 class SR_OT_ROUTE_LIST_NEW_ITEM(bpy.types.Operator):
1747 #{
1748 bl_idname = "skaterift.new_entry"
1749 bl_label = "Add gate"
1750
1751 def execute(self, context):#{
1752 active_object = context.active_object
1753 active_object.SR_data.ent_route[0].gates.add()
1754 return{'FINISHED'}
1755 #}
1756 #}
1757
1758 class SR_OT_ROUTE_LIST_DEL_ITEM(bpy.types.Operator):
1759 #{
1760 bl_idname = "skaterift.del_entry"
1761 bl_label = "Remove gate"
1762
1763 @classmethod
1764 def poll(cls, context):#{
1765 active_object = context.active_object
1766 if obj_ent_type(active_object) == 'ent_gate':#{
1767 return active_object.SR_data.ent_route[0].gates
1768 #}
1769 else: return False
1770 #}
1771
1772 def execute(self, context):#{
1773 active_object = context.active_object
1774 lista = active_object.SR_data.ent_route[0].gates
1775 index = active_object.SR_data.ent_route[0].gates_index
1776 lista.remove(index)
1777 active_object.SR_data.ent_route[0].gates_index = \
1778 min(max(0, index-1), len(lista) - 1)
1779 return{'FINISHED'}
1780 #}
1781 #}
1782
1783 class SR_OT_AUDIO_LIST_NEW_ITEM(bpy.types.Operator):
1784 #{
1785 bl_idname = "skaterift.al_new_entry"
1786 bl_label = "Add file"
1787
1788 def execute(self, context):#{
1789 active_object = context.active_object
1790 active_object.SR_data.ent_audio[0].files.add()
1791 return{'FINISHED'}
1792 #}
1793 #}
1794
1795 class SR_OT_AUDIO_LIST_DEL_ITEM(bpy.types.Operator):
1796 #{
1797 bl_idname = "skaterift.al_del_entry"
1798 bl_label = "Remove file"
1799
1800 @classmethod
1801 def poll(cls, context):#{
1802 active_object = context.active_object
1803 if obj_ent_type(active_object) == 'ent_audio':#{
1804 return active_object.SR_data.ent_audio[0].files
1805 #}
1806 else: return False
1807 #}
1808
1809 def execute(self, context):#{
1810 active_object = context.active_object
1811 lista = active_object.SR_data.ent_audio[0].files
1812 index = active_object.SR_data.ent_audio[0].file_index
1813 lista.remove(index)
1814 active_object.SR_data.ent_audio[0].file_index = \
1815 min(max(0, index-1), len(lista) - 1)
1816 return{'FINISHED'}
1817 #}
1818 #}
1819
1820 class SR_OBJECT_ENT_AUDIO_FILE_ENTRY(bpy.types.PropertyGroup):
1821 #{
1822 path: bpy.props.StringProperty( name="Path" )
1823 probability: bpy.props.FloatProperty( name="Probability",default=100.0 )
1824 #}
1825
1826 class SR_UL_AUDIO_LIST(bpy.types.UIList):
1827 #{
1828 bl_idname = 'SR_UL_AUDIO_LIST'
1829
1830 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
1831 #{
1832 split = layout.split(factor=0.7)
1833 c = split.column()
1834 c.prop( item, 'path', text='', emboss=False )
1835 c = split.column()
1836 c.prop( item, 'probability', text='%', emboss=True )
1837 #}
1838 #}
1839
1840
1841 class SR_OBJECT_ENT_ROUTE(bpy.types.PropertyGroup):
1842 #{
1843 gates: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE_ENTRY)
1844 gates_index: bpy.props.IntProperty()
1845
1846 colour: bpy.props.FloatVectorProperty( \
1847 name="Colour",\
1848 subtype='COLOR',\
1849 min=0.0,max=1.0,\
1850 default=Vector((0.79,0.63,0.48)),\
1851 description="Route colour"\
1852 )
1853
1854 alias: bpy.props.StringProperty(\
1855 name="Alias",\
1856 default="Untitled Course")
1857
1858 @staticmethod
1859 def sr_inspector( layout, data ):
1860 #{
1861 layout.prop( data[0], 'alias' )
1862 layout.prop( data[0], 'colour' )
1863
1864 layout.label( text='Checkpoints' )
1865 layout.template_list('SR_UL_ROUTE_NODE_LIST', 'Checkpoints', \
1866 data[0], 'gates', data[0], 'gates_index', rows=5)
1867
1868 row = layout.row()
1869 row.operator( 'skaterift.new_entry', text='Add' )
1870 row.operator( 'skaterift.del_entry', text='Remove' )
1871 #}
1872 #}
1873
1874 class SR_OBJECT_ENT_VOLUME(bpy.types.PropertyGroup):
1875 #{
1876 subtype: bpy.props.EnumProperty(
1877 name="Subtype",
1878 items=[('0','Trigger',''),
1879 ('1','Particles (0.1s)','')]
1880 )
1881
1882 target: bpy.props.PointerProperty( \
1883 type=bpy.types.Object, name="Target", \
1884 poll=lambda self,obj: sr_filter_ent_type(obj,['ent_audio']))
1885
1886 @staticmethod
1887 def sr_inspector( layout, data ):
1888 #{
1889 data = data[0]
1890 layout.prop( data, 'subtype' )
1891 layout.prop( data, 'target' )
1892 #}
1893 #}
1894
1895 class SR_OBJECT_ENT_AUDIO(bpy.types.PropertyGroup):
1896 #{
1897 files: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO_FILE_ENTRY)
1898 file_index: bpy.props.IntProperty()
1899
1900 flag_3d: bpy.props.BoolProperty( name="3D audio",default=True )
1901 flag_loop: bpy.props.BoolProperty( name="Loop",default=False )
1902 flag_auto: bpy.props.BoolProperty( name="Play at start",default=False )
1903 flag_nodoppler: bpy.props.BoolProperty( name="No Doppler",default=False )
1904
1905 group: bpy.props.IntProperty( name="Group ID", default=0 )
1906 formato: bpy.props.EnumProperty(
1907 name="Format",
1908 items=[('0','Uncompressed Mono',''),
1909 ('1','Compressed Vorbis',''),
1910 ('2','[vg] Bird Synthesis','')]
1911 )
1912 probability_curve: bpy.props.EnumProperty(
1913 name="Probability Curve",
1914 items=[('0','Constant',''),
1915 ('1','Wildlife Daytime',''),
1916 ('2','Wildlife Nighttime','')])
1917 channel_behaviour: bpy.props.EnumProperty(
1918 name="Channel Behaviour",
1919 items=[('0','Unlimited',''),
1920 ('1','Discard if group full', ''),
1921 ('2','Crossfade if group full','')])
1922
1923 transition_duration: bpy.props.FloatProperty(name="Transition Time",\
1924 default=0.2)
1925
1926 max_channels: bpy.props.IntProperty( name="Max Channels", default=1 )
1927 volume: bpy.props.FloatProperty( name="Volume",default=1.0 )
1928
1929 @staticmethod
1930 def sr_inspector( layout, data ):
1931 #{
1932 layout.prop( data[0], 'formato' )
1933 layout.prop( data[0], 'volume' )
1934
1935 box = layout.box()
1936 box.label( text='Channels' )
1937 split = box.split(factor=0.3)
1938 c = split.column()
1939 c.prop( data[0], 'max_channels' )
1940 c = split.column()
1941 c.prop( data[0], 'channel_behaviour', text='Behaviour' )
1942 if data[0].channel_behaviour >= '1':
1943 box.prop( data[0], 'group' )
1944 if data[0].channel_behaviour == '2':
1945 box.prop( data[0], 'transition_duration' )
1946
1947 box = layout.box()
1948 box.label( text='Flags' )
1949 box.prop( data[0], 'flag_3d' )
1950 if data[0].flag_3d: box.prop( data[0], 'flag_nodoppler' )
1951
1952 box.prop( data[0], 'flag_loop' )
1953 box.prop( data[0], 'flag_auto' )
1954
1955 split = layout.split(factor=0.7)
1956 c = split.column()
1957 c.label( text='Filepath' )
1958 c = split.column()
1959 c.label( text='Chance (0.1s)' )
1960
1961 layout.prop( data[0], 'probability_curve' )
1962
1963 layout.template_list('SR_UL_AUDIO_LIST', 'Files', \
1964 data[0], 'files', data[0], 'file_index', rows=5)
1965
1966 row = layout.row()
1967 row.operator( 'skaterift.al_new_entry', text='Add' )
1968 row.operator( 'skaterift.al_del_entry', text='Remove' )
1969 #}
1970 #}
1971
1972 class SR_OBJECT_PROPERTIES(bpy.types.PropertyGroup):
1973 #{
1974 ent_gate: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GATE)
1975 ent_spawn: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SPAWN)
1976 ent_route: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE)
1977 ent_volume: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_VOLUME)
1978 ent_audio: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_AUDIO)
1979
1980 ent_type: bpy.props.EnumProperty(
1981 name="Type",
1982 items=[('none', 'None', '', 0),
1983 ('ent_gate','Gate','', 1),
1984 ('ent_spawn','Spawn','', 2),
1985 ('ent_route_node', 'Route Node', '', 3 ),
1986 ('ent_route', 'Route', '', 4),
1987 ('ent_water', 'Water Surface', '', 5),
1988 ('ent_volume', 'Volume', '', 6 ),
1989 ('ent_audio', 'Audio Files', '', 7)],
1990 update=sr_on_type_change
1991 )
1992 #}
1993
1994 class SR_MESH_PROPERTIES(bpy.types.PropertyGroup):
1995 #{
1996 ent_gate: bpy.props.CollectionProperty(type=SR_MESH_ENT_GATE)
1997 #}
1998
1999 class SR_LIGHT_PROPERTIES(bpy.types.PropertyGroup):
2000 #{
2001 daytime: bpy.props.BoolProperty( name='Daytime' )
2002 #}
2003
2004 class SR_BONE_PROPERTIES(bpy.types.PropertyGroup):
2005 #{
2006 collider: bpy.props.EnumProperty( name='Collider Type',
2007 items=[('0','none',''),
2008 ('1','box',''),
2009 ('2','capsule','')])
2010
2011 collider_min: bpy.props.FloatVectorProperty( name='Collider Min', size=3 )
2012 collider_max: bpy.props.FloatVectorProperty( name='Collider Max', size=3 )
2013
2014 cone_constraint: bpy.props.BoolProperty( name='Cone constraint' )
2015
2016 conevx: bpy.props.FloatVectorProperty( name='vx' )
2017 conevy: bpy.props.FloatVectorProperty( name='vy' )
2018 coneva: bpy.props.FloatVectorProperty( name='va' )
2019 conet: bpy.props.FloatProperty( name='t' )
2020
2021 @staticmethod
2022 def sr_inspector( layout, data ):
2023 #{
2024 data = data[0]
2025 box = layout.box()
2026 box.prop( data, 'collider' )
2027
2028 if int(data.collider)>0:#{
2029 row = box.row()
2030 row.prop( data, 'collider_min' )
2031 row = box.row()
2032 row.prop( data, 'collider_max' )
2033 #}
2034
2035 box = layout.box()
2036 box.prop( data, 'cone_constraint' )
2037 if data.cone_constraint:#{
2038 row = box.row()
2039 row.prop( data, 'conevx' )
2040 row = box.row()
2041 row.prop( data, 'conevy' )
2042 row = box.row()
2043 row.prop( data, 'coneva' )
2044 box.prop( data, 'conet' )
2045 #}
2046 #}
2047 #}
2048
2049 class SR_MATERIAL_PROPERTIES(bpy.types.PropertyGroup):
2050 #{
2051 shader: bpy.props.EnumProperty(
2052 name="Format",
2053 items = [
2054 ('standard',"standard",''),
2055 ('standard_cutout', "standard_cutout", ''),
2056 ('terrain_blend', "terrain_blend", ''),
2057 ('vertex_blend', "vertex_blend", ''),
2058 ('water',"water",'')
2059 ])
2060
2061 surface_prop: bpy.props.EnumProperty(
2062 name="Surface Property",
2063 items = [
2064 ('0','concrete',''),
2065 ('1','wood',''),
2066 ('2','grass',''),
2067 ('3','tiles',''),
2068 ('4','metal','')
2069 ])
2070
2071 collision: bpy.props.BoolProperty( \
2072 name="Collisions Enabled",\
2073 default=True,\
2074 description = "Can the player collide with this material"\
2075 )
2076 skate_surface: bpy.props.BoolProperty( \
2077 name="Skate Surface", \
2078 default=True,\
2079 description = "Should the game try to target this surface?" \
2080 )
2081 grind_surface: bpy.props.BoolProperty( \
2082 name="Grind Surface", \
2083 default=False,\
2084 description = "Grind face?" \
2085 )
2086 grow_grass: bpy.props.BoolProperty( \
2087 name="Grow Grass", \
2088 default=False,\
2089 description = "Spawn grass sprites on this surface?" \
2090 )
2091 blend_offset: bpy.props.FloatVectorProperty( \
2092 name="Blend Offset", \
2093 size=2, \
2094 default=Vector((0.5,0.0)),\
2095 description="When surface is more than 45 degrees, add this vector " +\
2096 "to the UVs" \
2097 )
2098 sand_colour: bpy.props.FloatVectorProperty( \
2099 name="Sand Colour",\
2100 subtype='COLOR',\
2101 min=0.0,max=1.0,\
2102 default=Vector((0.79,0.63,0.48)),\
2103 description="Blend to this colour near the 0 coordinate on UP axis"\
2104 )
2105 shore_colour: bpy.props.FloatVectorProperty( \
2106 name="Shore Colour",\
2107 subtype='COLOR',\
2108 min=0.0,max=1.0,\
2109 default=Vector((0.03,0.32,0.61)),\
2110 description="Water colour at the shoreline"\
2111 )
2112 ocean_colour: bpy.props.FloatVectorProperty( \
2113 name="Ocean Colour",\
2114 subtype='COLOR',\
2115 min=0.0,max=1.0,\
2116 default=Vector((0.0,0.006,0.03)),\
2117 description="Water colour in the deep bits"\
2118 )
2119 #}
2120
2121 # ---------------------------------------------------------------------------- #
2122 # #
2123 # GUI section #
2124 # #
2125 # ---------------------------------------------------------------------------- #
2126
2127 cv_view_draw_handler = None
2128 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
2129 cv_view_verts = []
2130 cv_view_colours = []
2131 cv_view_course_i = 0
2132
2133 # Draw axis alligned sphere at position with radius
2134 #
2135 def cv_draw_sphere( pos, radius, colour ):
2136 #{
2137 global cv_view_verts, cv_view_colours
2138
2139 ly = pos + Vector((0,0,radius))
2140 lx = pos + Vector((0,radius,0))
2141 lz = pos + Vector((0,0,radius))
2142
2143 pi = 3.14159265358979323846264
2144
2145 for i in range(16):
2146 #{
2147 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
2148 s = math.sin(t)
2149 c = math.cos(t)
2150
2151 py = pos + Vector((s*radius,0.0,c*radius))
2152 px = pos + Vector((s*radius,c*radius,0.0))
2153 pz = pos + Vector((0.0,s*radius,c*radius))
2154
2155 cv_view_verts += [ px, lx ]
2156 cv_view_verts += [ py, ly ]
2157 cv_view_verts += [ pz, lz ]
2158
2159 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2160
2161 ly = py
2162 lx = px
2163 lz = pz
2164 #}
2165 cv_draw_lines()
2166 #}
2167
2168 # Draw axis alligned sphere at position with radius
2169 #
2170 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
2171 #{
2172 global cv_view_verts, cv_view_colours
2173
2174 ly = pos + tz*radius
2175 lx = pos + ty*radius
2176 lz = pos + tz*radius
2177
2178 pi = 3.14159265358979323846264
2179
2180 for i in range(16):
2181 #{
2182 t = ((i+1.0) * 1.0/16.0) * pi
2183 s = math.sin(t)
2184 c = math.cos(t)
2185
2186 s1 = math.sin(t*2.0)
2187 c1 = math.cos(t*2.0)
2188
2189 py = pos + s*tx*radius + c *tz*radius
2190 px = pos + s*tx*radius + c *ty*radius
2191 pz = pos + s1*ty*radius + c1*tz*radius
2192
2193 cv_view_verts += [ px, lx ]
2194 cv_view_verts += [ py, ly ]
2195 cv_view_verts += [ pz, lz ]
2196
2197 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2198
2199 ly = py
2200 lx = px
2201 lz = pz
2202 #}
2203 cv_draw_lines()
2204 #}
2205
2206 # Draw transformed -1 -> 1 cube
2207 #
2208 def cv_draw_ucube( transform, colour, s=Vector((1,1,1)), o=Vector((0,0,0)) ):
2209 #{
2210 global cv_view_verts, cv_view_colours
2211
2212 a = o + -1.0 * s
2213 b = o + 1.0 * s
2214
2215 vs = [None]*8
2216 vs[0] = transform @ Vector((a[0], a[1], a[2]))
2217 vs[1] = transform @ Vector((a[0], b[1], a[2]))
2218 vs[2] = transform @ Vector((b[0], b[1], a[2]))
2219 vs[3] = transform @ Vector((b[0], a[1], a[2]))
2220 vs[4] = transform @ Vector((a[0], a[1], b[2]))
2221 vs[5] = transform @ Vector((a[0], b[1], b[2]))
2222 vs[6] = transform @ Vector((b[0], b[1], b[2]))
2223 vs[7] = transform @ Vector((b[0], a[1], b[2]))
2224
2225 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2226 (0,4),(1,5),(2,6),(3,7)]
2227
2228 for l in indices:
2229 #{
2230 v0 = vs[l[0]]
2231 v1 = vs[l[1]]
2232 cv_view_verts += [(v0[0],v0[1],v0[2])]
2233 cv_view_verts += [(v1[0],v1[1],v1[2])]
2234 cv_view_colours += [colour, colour]
2235 #}
2236 cv_draw_lines()
2237 #}
2238
2239 # Draw line with colour
2240 #
2241 def cv_draw_line( p0, p1, colour ):
2242 #{
2243 global cv_view_verts, cv_view_colours
2244
2245 cv_view_verts += [p0,p1]
2246 cv_view_colours += [colour, colour]
2247 cv_draw_lines()
2248 #}
2249
2250 # Draw line with colour(s)
2251 #
2252 def cv_draw_line2( p0, p1, c0, c1 ):
2253 #{
2254 global cv_view_verts, cv_view_colours
2255
2256 cv_view_verts += [p0,p1]
2257 cv_view_colours += [c0,c1]
2258 cv_draw_lines()
2259 #}
2260
2261 #
2262 #
2263 def cv_tangent_basis( n, tx, ty ):
2264 #{
2265 if abs( n[0] ) >= 0.57735027:
2266 #{
2267 tx[0] = n[1]
2268 tx[1] = -n[0]
2269 tx[2] = 0.0
2270 #}
2271 else:
2272 #{
2273 tx[0] = 0.0
2274 tx[1] = n[2]
2275 tx[2] = -n[1]
2276 #}
2277
2278 tx.normalize()
2279 _ty = n.cross( tx )
2280
2281 ty[0] = _ty[0]
2282 ty[1] = _ty[1]
2283 ty[2] = _ty[2]
2284 #}
2285
2286 # Draw coloured arrow
2287 #
2288 def cv_draw_arrow( p0, p1, c0, size=0.15 ):
2289 #{
2290 global cv_view_verts, cv_view_colours
2291
2292 n = p1-p0
2293 midpt = p0 + n*0.5
2294 n.normalize()
2295
2296 tx = Vector((1,0,0))
2297 ty = Vector((1,0,0))
2298 cv_tangent_basis( n, tx, ty )
2299
2300 cv_view_verts += [p0,p1, midpt+(tx-n)*size,midpt, midpt+(-tx-n)*size,midpt ]
2301 cv_view_colours += [c0,c0,c0,c0,c0,c0]
2302 cv_draw_lines()
2303 #}
2304
2305 def cv_draw_line_dotted( p0, p1, c0, dots=10 ):
2306 #{
2307 global cv_view_verts, cv_view_colours
2308
2309 for i in range(dots):#{
2310 t0 = i/dots
2311 t1 = (i+0.25)/dots
2312
2313 p2 = p0*(1.0-t0)+p1*t0
2314 p3 = p0*(1.0-t1)+p1*t1
2315
2316 cv_view_verts += [p2,p3]
2317 cv_view_colours += [c0,c0]
2318 #}
2319 cv_draw_lines()
2320 #}
2321
2322 # Drawhandles of a bezier control point
2323 #
2324 def cv_draw_bhandle( obj, direction, colour ):
2325 #{
2326 global cv_view_verts, cv_view_colours
2327
2328 p0 = obj.location
2329 h0 = obj.matrix_world @ Vector((0,direction,0))
2330
2331 cv_view_verts += [p0]
2332 cv_view_verts += [h0]
2333 cv_view_colours += [colour,colour]
2334 cv_draw_lines()
2335 #}
2336
2337 # Draw a bezier curve (at fixed resolution 10)
2338 #
2339 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
2340 #{
2341 global cv_view_verts, cv_view_colours
2342
2343 last = p0
2344 for i in range(10):
2345 #{
2346 t = (i+1)/10
2347 a0 = 1-t
2348
2349 tt = t*t
2350 ttt = tt*t
2351 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
2352
2353 cv_view_verts += [(last[0],last[1],last[2])]
2354 cv_view_verts += [(p[0],p[1],p[2])]
2355 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
2356
2357 last = p
2358 #}
2359 cv_draw_lines()
2360 #}
2361
2362 # I think this one extends the handles of the bezier otwards......
2363 #
2364 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
2365 #{
2366 global cv_view_course_i
2367
2368 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
2369
2370 p0 = o0.matrix_world @ Vector((offs, 0,0))
2371 h0 = o0.matrix_world @ Vector((offs, s0,0))
2372 p1 = o1.matrix_world @ Vector((offs, 0,0))
2373 h1 = o1.matrix_world @ Vector((offs,-s1,0))
2374
2375 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
2376 cv_draw_lines()
2377 #}
2378
2379 # Flush the lines buffers. This is called often because god help you if you want
2380 # to do fixed, fast buffers in this catastrophic programming language.
2381 #
2382 def cv_draw_lines():
2383 #{
2384 global cv_view_shader, cv_view_verts, cv_view_colours
2385
2386 if len(cv_view_verts) < 2:
2387 return
2388
2389 lines = batch_for_shader(\
2390 cv_view_shader, 'LINES', \
2391 { "pos":cv_view_verts, "color":cv_view_colours })
2392
2393 lines.draw( cv_view_shader )
2394
2395 cv_view_verts = []
2396 cv_view_colours = []
2397 #}
2398
2399 # I dont remember what this does exactly
2400 #
2401 def cv_draw_bpath( o0,o1,c0,c1 ):
2402 #{
2403 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
2404 #}
2405
2406 # Semi circle to show the limit. and some lines
2407 #
2408 def draw_limit( obj, center, major, minor, amin, amax, colour ):
2409 #{
2410 global cv_view_verts, cv_view_colours
2411 f = 0.05
2412 ay = major*f
2413 ax = minor*f
2414
2415 for x in range(16):#{
2416 t0 = x/16
2417 t1 = (x+1)/16
2418 a0 = amin*(1.0-t0)+amax*t0
2419 a1 = amin*(1.0-t1)+amax*t1
2420
2421 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
2422 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
2423
2424 p0=obj.matrix_world @ p0
2425 p1=obj.matrix_world @ p1
2426 cv_view_verts += [p0,p1]
2427 cv_view_colours += [colour,colour]
2428
2429 if x == 0:#{
2430 cv_view_verts += [p0,center]
2431 cv_view_colours += [colour,colour]
2432 #}
2433 if x == 15:#{
2434 cv_view_verts += [p1,center]
2435 cv_view_colours += [colour,colour]
2436 #}
2437 #}
2438
2439 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
2440 cv_view_colours += [colour,colour]
2441
2442 cv_draw_lines()
2443 #}
2444
2445 # Cone and twist limit
2446 #
2447 def draw_cone_twist( center, vx, vy, va ):
2448 #{
2449 global cv_view_verts, cv_view_colours
2450 axis = vy.cross( vx )
2451 axis.normalize()
2452
2453 size = 0.12
2454
2455 cv_view_verts += [center, center+va*size]
2456 cv_view_colours += [ (1,1,1,1), (1,1,1,1) ]
2457
2458 for x in range(32):#{
2459 t0 = (x/32) * math.tau
2460 t1 = ((x+1)/32) * math.tau
2461
2462 c0 = math.cos(t0)
2463 s0 = math.sin(t0)
2464 c1 = math.cos(t1)
2465 s1 = math.sin(t1)
2466
2467 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
2468 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
2469
2470 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
2471 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
2472
2473 cv_view_verts += [center, p0, p0, p1]
2474 cv_view_colours += [ (0,0,0,0), col0, col0, col1 ]
2475 #}
2476
2477 cv_draw_lines()
2478 #}
2479
2480 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2481 #
2482 def draw_skeleton_helpers( obj ):
2483 #{
2484 global cv_view_verts, cv_view_colours
2485
2486 if obj.data.pose_position != 'REST':#{
2487 return
2488 #}
2489
2490 for bone in obj.data.bones:#{
2491 c = bone.head_local
2492 a = Vector((bone.SR_data.collider_min[0],
2493 bone.SR_data.collider_min[1],
2494 bone.SR_data.collider_min[2]))
2495 b = Vector((bone.SR_data.collider_max[0],
2496 bone.SR_data.collider_max[1],
2497 bone.SR_data.collider_max[2]))
2498
2499 if bone.SR_data.collider == '1':#{
2500 vs = [None]*8
2501 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
2502 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
2503 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
2504 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
2505 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
2506 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
2507 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
2508 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
2509
2510 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2511 (0,4),(1,5),(2,6),(3,7)]
2512
2513 for l in indices:#{
2514 v0 = vs[l[0]]
2515 v1 = vs[l[1]]
2516
2517 cv_view_verts += [(v0[0],v0[1],v0[2])]
2518 cv_view_verts += [(v1[0],v1[1],v1[2])]
2519 cv_view_colours += [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2520 #}
2521 #}
2522 elif bone.SR_data.collider == '2':#{
2523 v0 = b-a
2524 major_axis = 0
2525 largest = -1.0
2526
2527 for i in range(3):#{
2528 if abs(v0[i]) > largest:#{
2529 largest = abs(v0[i])
2530 major_axis = i
2531 #}
2532 #}
2533
2534 v1 = Vector((0,0,0))
2535 v1[major_axis] = 1.0
2536
2537 tx = Vector((0,0,0))
2538 ty = Vector((0,0,0))
2539
2540 cv_tangent_basis( v1, tx, ty )
2541 r = (abs(tx.dot( v0 )) + abs(ty.dot( v0 ))) * 0.25
2542 l = v0[ major_axis ] - r*2
2543
2544 p0 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l*-0.5 )
2545 p1 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l* 0.5 )
2546
2547 colour = [0.2,0.2,0.2,1.0]
2548 colour[major_axis] = 0.5
2549
2550 cv_draw_halfsphere( p0, -v1, ty, tx, r, colour )
2551 cv_draw_halfsphere( p1, v1, ty, tx, r, colour )
2552 cv_draw_line( p0+tx* r, p1+tx* r, colour )
2553 cv_draw_line( p0+tx*-r, p1+tx*-r, colour )
2554 cv_draw_line( p0+ty* r, p1+ty* r, colour )
2555 cv_draw_line( p0+ty*-r, p1+ty*-r, colour )
2556 #}
2557 else:#{
2558 continue
2559 #}
2560
2561 center = obj.matrix_world @ c
2562 if bone.SR_data.cone_constraint:#{
2563 vx = Vector([bone.SR_data.conevx[_] for _ in range(3)])
2564 vy = Vector([bone.SR_data.conevy[_] for _ in range(3)])
2565 va = Vector([bone.SR_data.coneva[_] for _ in range(3)])
2566 draw_cone_twist( center, vx, vy, va )
2567 #}
2568 #}
2569 #}
2570
2571 def cv_ent_gate( obj ):
2572 #{
2573 global cv_view_verts, cv_view_colours
2574
2575 if obj.type != 'MESH': return
2576
2577 mesh_data = obj.data.SR_data.ent_gate[0]
2578 data = obj.SR_data.ent_gate[0]
2579 dims = mesh_data.dimensions
2580
2581 vs = [None]*9
2582 c = Vector((0,0,dims[2]))
2583
2584 vs[0] = obj.matrix_world @ Vector((-dims[0],0.0,-dims[1]+dims[2]))
2585 vs[1] = obj.matrix_world @ Vector((-dims[0],0.0, dims[1]+dims[2]))
2586 vs[2] = obj.matrix_world @ Vector(( dims[0],0.0, dims[1]+dims[2]))
2587 vs[3] = obj.matrix_world @ Vector(( dims[0],0.0,-dims[1]+dims[2]))
2588 vs[4] = obj.matrix_world @ (c+Vector((-1,0,-2)))
2589 vs[5] = obj.matrix_world @ (c+Vector((-1,0, 2)))
2590 vs[6] = obj.matrix_world @ (c+Vector(( 1,0, 2)))
2591 vs[7] = obj.matrix_world @ (c+Vector((-1,0, 0)))
2592 vs[8] = obj.matrix_world @ (c+Vector(( 1,0, 0)))
2593
2594 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
2595
2596 for l in indices:#{
2597 v0 = vs[l[0]]
2598 v1 = vs[l[1]]
2599 cv_view_verts += [(v0[0],v0[1],v0[2])]
2600 cv_view_verts += [(v1[0],v1[1],v1[2])]
2601 cv_view_colours += [(1,1,0,1),(1,1,0,1)]
2602 #}
2603
2604 sw = (0.4,0.4,0.4,0.2)
2605 if data.target != None:
2606 cv_draw_arrow( obj.location, data.target.location, sw )
2607 #}
2608
2609 def cv_ent_volume( obj ):
2610 #{
2611 global cv_view_verts, cv_view_colours
2612
2613 data = obj.SR_data.ent_volume[0]
2614
2615 if data.subtype == '0':#{
2616 cv_draw_ucube( obj.matrix_world, (0,1,0) )
2617
2618 if data.target:#{
2619 cv_draw_line( obj.location, data.target.location, (0,1,0) )
2620 #}
2621 #}
2622 elif data.subtype == '1':#{
2623 cv_draw_ucube( obj.matrix_world, (1,1,0) )
2624
2625 if data.target:#{
2626 cv_draw_line( obj.location, data.target.location, (1,1,0) )
2627 #}
2628 #}
2629 #}
2630
2631 def dijkstra( graph, start_node, target_node ):
2632 #{
2633 unvisited = [_ for _ in graph]
2634 shortest_path = {}
2635 previous_nodes = {}
2636
2637 for n in unvisited:
2638 shortest_path[n] = 9999999.999999
2639 shortest_path[start_node] = 0
2640
2641 while unvisited:#{
2642 current_min_node = None
2643 for n in unvisited:#{
2644 if current_min_node == None:
2645 current_min_node = n
2646 elif shortest_path[n] < shortest_path[current_min_node]:
2647 current_min_node = n
2648 #}
2649
2650 for branch in graph[current_min_node]:#{
2651 tentative_value = shortest_path[current_min_node]
2652 tentative_value += graph[current_min_node][branch]
2653 if tentative_value < shortest_path[branch]:#{
2654 shortest_path[branch] = tentative_value
2655 previous_nodes[branch] = current_min_node
2656 #}
2657 #}
2658
2659 unvisited.remove(current_min_node)
2660 #}
2661
2662 path = []
2663 node = target_node
2664 while node != start_node:#{
2665 path.append(node)
2666
2667 if node not in previous_nodes: return None
2668 node = previous_nodes[node]
2669 #}
2670
2671 # Add the start node manually
2672 path.append(start_node)
2673 return path
2674 #}
2675
2676 def node_graph( route_nodes ):
2677 #{
2678 graph = {}
2679 for n in route_nodes:
2680 graph[n.name] = {}
2681
2682 for i in range(len(route_nodes)-1):#{
2683 for j in range(i+1, len(route_nodes)):#{
2684 ni = route_nodes[i]
2685 nj = route_nodes[j]
2686
2687 v0 = ni.location - nj.location
2688
2689 gate = None
2690
2691 if ni.SR_data.ent_type == 'ent_gate':
2692 gate = ni
2693
2694 if nj.SR_data.ent_type == 'ent_gate':#{
2695 if gate: continue
2696 gate = nj
2697 #}
2698
2699 if gate:#{
2700 v1 = gate.matrix_world.to_3x3() @ Vector((0,-1,0))
2701 if gate.SR_data.ent_gate[0].target:
2702 if v1.dot(v0) > 0.0: continue
2703 else:
2704 if v1.dot(v0) < 0.0: continue
2705 #}
2706
2707 dist = v0.magnitude
2708
2709 if dist > 25.0: continue
2710 graph[route_nodes[i].name][route_nodes[j].name] = dist
2711 graph[route_nodes[j].name][route_nodes[i].name] = dist
2712 #}
2713 #}
2714
2715 return graph
2716 #}
2717
2718 def cv_draw_route( route, route_nodes ):
2719 #{
2720 pole = Vector((0.2,0.2,10))
2721 hat = Vector((1,8,0.2))
2722 cc = route.SR_data.ent_route[0].colour
2723
2724 cv_draw_ucube(route.matrix_world,cc,Vector((0.5,-7.5,6)),\
2725 Vector((0,-6.5,5.5)))
2726 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5, 0.5,0)) )
2727 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5,-13.5,0)) )
2728 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5, 12)) )
2729 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5,-1)) )
2730
2731 checkpoints = route.SR_data.ent_route[0].gates
2732 graph = node_graph( route_nodes )
2733
2734 for i in range(len(checkpoints)):#{
2735 gi = checkpoints[i].target
2736 gj = checkpoints[(i+1)%len(checkpoints)].target
2737
2738 if gi:#{
2739 dest = gi.SR_data.ent_gate[0].target
2740 if dest:
2741 cv_draw_line_dotted( gi.location, dest.location, cc )
2742 gi = dest
2743 #}
2744
2745 if gi==gj: continue # error?
2746 if not gi or not gj: continue
2747
2748 path = dijkstra( graph, gj.name, gi.name )
2749
2750 if path:#{
2751 for sj in range(len(path)-1):#{
2752 o0 = bpy.data.objects[ path[sj] ]
2753 o1 = bpy.data.objects[ path[sj+1] ]
2754 cv_draw_arrow(o0.location,o1.location,cc,1.5)
2755 #}
2756 #}
2757 else:#{
2758 cv_draw_line_dotted( gi.location, gj.location, cc )
2759 #}
2760 #}
2761 #}
2762
2763 def cv_draw():
2764 #{
2765 global cv_view_shader
2766 global cv_view_verts
2767 global cv_view_colours
2768 global cv_view_course_i
2769
2770 cv_view_course_i = 0
2771 cv_view_verts = []
2772 cv_view_colours = []
2773
2774 cv_view_shader.bind()
2775 gpu.state.depth_mask_set(False)
2776 gpu.state.line_width_set(2.0)
2777 gpu.state.face_culling_set('BACK')
2778 gpu.state.depth_test_set('LESS')
2779 gpu.state.blend_set('NONE')
2780
2781 route_nodes = []
2782 routes = []
2783
2784 for obj in bpy.context.collection.objects:#{
2785 if obj.type == 'ARMATURE':#{
2786 if obj.data.pose_position == 'REST':
2787 draw_skeleton_helpers( obj )
2788 #}
2789 else:#{
2790 ent_type = obj_ent_type( obj )
2791
2792 if ent_type == 'ent_gate':#{
2793 cv_ent_gate( obj )
2794 route_nodes += [obj]
2795 #}
2796 elif ent_type == 'ent_route_node':
2797 route_nodes += [obj]
2798 elif ent_type == 'ent_route':
2799 routes += [obj]
2800 elif ent_type == 'ent_volume':#{
2801 cv_ent_volume( obj )
2802 #}
2803 elif ent_type == 'ent_audio':#{
2804 cv_draw_sphere( obj.location, obj.scale[0], (1,1,0) )
2805 #}
2806 #}
2807 #}
2808
2809 #cv_draw_route_map( route_nodes )
2810 for route in routes:#{
2811 cv_draw_route( route, route_nodes )
2812 #}
2813
2814 cv_draw_lines()
2815 return
2816 #}
2817
2818 classes = [ SR_INTERFACE, SR_MATERIAL_PANEL,\
2819 SR_COLLECTION_SETTINGS, SR_SCENE_SETTINGS, \
2820 SR_COMPILE, SR_COMPILE_THIS, SR_MIRROR_BONE_X,\
2821 \
2822 SR_OBJECT_ENT_GATE, SR_MESH_ENT_GATE, SR_OBJECT_ENT_SPAWN, \
2823 SR_OBJECT_ENT_ROUTE_ENTRY, SR_UL_ROUTE_NODE_LIST, \
2824 SR_OBJECT_ENT_ROUTE, SR_OT_ROUTE_LIST_NEW_ITEM,\
2825 SR_OT_AUDIO_LIST_NEW_ITEM,SR_OT_AUDIO_LIST_DEL_ITEM,\
2826 SR_OBJECT_ENT_VOLUME,
2827 SR_UL_AUDIO_LIST, SR_OBJECT_ENT_AUDIO_FILE_ENTRY,\
2828 SR_OT_ROUTE_LIST_DEL_ITEM,\
2829 SR_OBJECT_ENT_AUDIO,\
2830 \
2831 SR_OBJECT_PROPERTIES, SR_LIGHT_PROPERTIES, SR_BONE_PROPERTIES,
2832 SR_MESH_PROPERTIES, SR_MATERIAL_PROPERTIES \
2833 ]
2834
2835 def register():
2836 #{
2837 for c in classes:
2838 bpy.utils.register_class(c)
2839
2840 bpy.types.Scene.SR_data = \
2841 bpy.props.PointerProperty(type=SR_SCENE_SETTINGS)
2842 bpy.types.Collection.SR_data = \
2843 bpy.props.PointerProperty(type=SR_COLLECTION_SETTINGS)
2844
2845 bpy.types.Object.SR_data = \
2846 bpy.props.PointerProperty(type=SR_OBJECT_PROPERTIES)
2847 bpy.types.Light.SR_data = \
2848 bpy.props.PointerProperty(type=SR_LIGHT_PROPERTIES)
2849 bpy.types.Bone.SR_data = \
2850 bpy.props.PointerProperty(type=SR_BONE_PROPERTIES)
2851 bpy.types.Mesh.SR_data = \
2852 bpy.props.PointerProperty(type=SR_MESH_PROPERTIES)
2853 bpy.types.Material.SR_data = \
2854 bpy.props.PointerProperty(type=SR_MATERIAL_PROPERTIES)
2855
2856 global cv_view_draw_handler
2857 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
2858 cv_draw,(),'WINDOW','POST_VIEW')
2859 #}
2860
2861 def unregister():
2862 #{
2863 for c in classes:
2864 bpy.utils.unregister_class(c)
2865
2866 global cv_view_draw_handler
2867 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
2868 #}
2869
2870 # ---------------------------------------------------------------------------- #
2871 # #
2872 # QOI encoder #
2873 # #
2874 # ---------------------------------------------------------------------------- #
2875 # #
2876 # Transliteration of: #
2877 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
2878 # #
2879 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
2880 # SPDX-License-Identifier: MIT #
2881 # QOI - The "Quite OK Image" format for fast, lossless image compression #
2882 # #
2883 # ---------------------------------------------------------------------------- #
2884
2885 class qoi_rgba_t(Structure):
2886 #{
2887 _pack_ = 1
2888 _fields_ = [("r",c_uint8),
2889 ("g",c_uint8),
2890 ("b",c_uint8),
2891 ("a",c_uint8)]
2892 #}
2893
2894 QOI_OP_INDEX = 0x00 # 00xxxxxx
2895 QOI_OP_DIFF = 0x40 # 01xxxxxx
2896 QOI_OP_LUMA = 0x80 # 10xxxxxx
2897 QOI_OP_RUN = 0xc0 # 11xxxxxx
2898 QOI_OP_RGB = 0xfe # 11111110
2899 QOI_OP_RGBA = 0xff # 11111111
2900
2901 QOI_MASK_2 = 0xc0 # 11000000
2902
2903 def qoi_colour_hash( c ):
2904 #{
2905 return c.r*3 + c.g*5 + c.b*7 + c.a*11
2906 #}
2907
2908 def qoi_eq( a, b ):
2909 #{
2910 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
2911 #}
2912
2913 def qoi_32bit( v ):
2914 #{
2915 return bytearray([ (0xff000000 & v) >> 24, \
2916 (0x00ff0000 & v) >> 16, \
2917 (0x0000ff00 & v) >> 8, \
2918 (0x000000ff & v) ])
2919 #}
2920
2921 def qoi_encode( img ):
2922 #{
2923 data = bytearray()
2924
2925 print(F"{' ':<30}",end='\r')
2926 print(F"[QOI] Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]",end='\r')
2927
2928 index = [ qoi_rgba_t() for _ in range(64) ]
2929
2930 # Header
2931 #
2932 data.extend( bytearray(c_uint32(0x66696f71)) )
2933 data.extend( qoi_32bit( img.size[0] ) )
2934 data.extend( qoi_32bit( img.size[1] ) )
2935 data.extend( bytearray(c_uint8(4)) )
2936 data.extend( bytearray(c_uint8(0)) )
2937
2938 run = 0
2939 px_prev = qoi_rgba_t()
2940 px_prev.r = c_uint8(0)
2941 px_prev.g = c_uint8(0)
2942 px_prev.b = c_uint8(0)
2943 px_prev.a = c_uint8(255)
2944
2945 px = qoi_rgba_t()
2946 px.r = c_uint8(0)
2947 px.g = c_uint8(0)
2948 px.b = c_uint8(0)
2949 px.a = c_uint8(255)
2950
2951 px_len = img.size[0] * img.size[1]
2952 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
2953
2954 for px_pos in range( px_len ): #{
2955 idx = px_pos * img.channels
2956 nc = img.channels-1
2957
2958 px.r = paxels[idx+min(0,nc)]
2959 px.g = paxels[idx+min(1,nc)]
2960 px.b = paxels[idx+min(2,nc)]
2961 px.a = paxels[idx+min(3,nc)]
2962
2963 if qoi_eq( px, px_prev ): #{
2964 run += 1
2965
2966 if (run == 62) or (px_pos == px_len-1): #{
2967 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2968 run = 0
2969 #}
2970 #}
2971 else: #{
2972 if run > 0: #{
2973 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2974 run = 0
2975 #}
2976
2977 index_pos = qoi_colour_hash(px) % 64
2978
2979 if qoi_eq( index[index_pos], px ): #{
2980 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
2981 #}
2982 else: #{
2983 index[ index_pos ].r = px.r
2984 index[ index_pos ].g = px.g
2985 index[ index_pos ].b = px.b
2986 index[ index_pos ].a = px.a
2987
2988 if px.a == px_prev.a: #{
2989 vr = int(px.r) - int(px_prev.r)
2990 vg = int(px.g) - int(px_prev.g)
2991 vb = int(px.b) - int(px_prev.b)
2992
2993 vg_r = vr - vg
2994 vg_b = vb - vg
2995
2996 if (vr > -3) and (vr < 2) and\
2997 (vg > -3) and (vg < 2) and\
2998 (vb > -3) and (vb < 2):
2999 #{
3000 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
3001 data.extend( bytearray( c_uint8(op) ))
3002 #}
3003 elif (vg_r > -9) and (vg_r < 8) and\
3004 (vg > -33) and (vg < 32 ) and\
3005 (vg_b > -9) and (vg_b < 8):
3006 #{
3007 op = QOI_OP_LUMA | (vg+32)
3008 delta = (vg_r+8) << 4 | (vg_b + 8)
3009 data.extend( bytearray( c_uint8(op) ) )
3010 data.extend( bytearray( c_uint8(delta) ))
3011 #}
3012 else: #{
3013 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
3014 data.extend( bytearray( c_uint8(px.r) ))
3015 data.extend( bytearray( c_uint8(px.g) ))
3016 data.extend( bytearray( c_uint8(px.b) ))
3017 #}
3018 #}
3019 else: #{
3020 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
3021 data.extend( bytearray( c_uint8(px.r) ))
3022 data.extend( bytearray( c_uint8(px.g) ))
3023 data.extend( bytearray( c_uint8(px.b) ))
3024 data.extend( bytearray( c_uint8(px.a) ))
3025 #}
3026 #}
3027 #}
3028
3029 px_prev.r = px.r
3030 px_prev.g = px.g
3031 px_prev.b = px.b
3032 px_prev.a = px.a
3033 #}
3034
3035 # Padding
3036 for i in range(7):
3037 data.extend( bytearray( c_uint8(0) ))
3038 data.extend( bytearray( c_uint8(1) ))
3039 bytearray_align_to( data, 16, b'\x00' )
3040
3041 return data
3042 #}