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