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