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