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