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