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