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