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