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