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