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