i hope your hapy
[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
7 bl_info = {
8 "name":"Skaterift .mdl exporter",
9 "author": "Harry Godden (hgn)",
10 "version": (0,2),
11 "blender":(3,1,0),
12 "location":"Export",
13 "description":"",
14 "warning":"",
15 "wiki_url":"",
16 "category":"Import/Export",
17 }
18
19 class mdl_vert(Structure): # 48 bytes. Quite large. Could compress
20 #{ # the normals and uvs to i16s. Not an
21 _pack_ = 1 # real issue, yet.
22 _fields_ = [("co",c_float*3),
23 ("norm",c_float*3),
24 ("uv",c_float*2),
25 ("colour",c_uint8*4),
26 ("weights",c_uint16*4),
27 ("groups",c_uint8*4)]
28 #}
29
30 class mdl_transform(Structure):
31 #{
32 _fields_ = [("co",c_float*3),
33 ( "s",c_float*3),
34 ( "q",c_float*4)]
35 #}
36
37 class mdl_submesh(Structure):
38 #{
39 _fields_ = [("indice_start",c_uint32),
40 ("indice_count",c_uint32),
41 ("vertex_start",c_uint32),
42 ("vertex_count",c_uint32),
43 ("bbx",(c_float*3)*2),
44 ("material_id",c_uint32)] # index into the material array
45 #}
46
47 class mdl_material(Structure):
48 #{
49 _fields_ = [("pstr_name",c_uint32),
50 ("shader",c_uint32),
51 ("flags",c_uint32),
52 ("surface_prop",c_uint32),
53 ("colour",c_float*4),
54 ("colour1",c_float*4),
55 ("tex_diffuse",c_uint32),
56 ("tex_none0",c_uint32),
57 ("tex_none1",c_uint32)]
58 #}
59
60 class mdl_bone(Structure):
61 #{
62 _fields_ = [("co",c_float*3),("end",c_float*3),
63 ("parent",c_uint32),
64 ("collider",c_uint32),
65 ("ik_target",c_uint32),
66 ("ik_pole",c_uint32),
67 ("flags",c_uint32),
68 ("pstr_name",c_uint32),
69 ("hitbox",(c_float*3)*2),
70 ("conevx",c_float*3),("conevy",c_float*3),("coneva",c_float*3),
71 ("conet",c_float)]
72 #}
73
74 class mdl_armature(Structure):
75 #{
76 _fields_ = [("transform",mdl_transform),
77 ("bone_start",c_uint32),
78 ("bone_count",c_uint32),
79 ("anim_start",c_uint32),
80 ("anim_count",c_uint32)]
81 #}
82
83 class mdl_animation(Structure):
84 #{
85 _fields_ = [("pstr_name",c_uint32),
86 ("length",c_uint32),
87 ("rate",c_float),
88 ("keyframe_start",c_uint32)]
89 #}
90
91 class mdl_mesh(Structure):
92 #{
93 _fields_ = [("transform",mdl_transform),
94 ("submesh_start",c_uint32),
95 ("submesh_count",c_uint32),
96 ("pstr_name",c_uint32),
97 ("flags",c_uint32),
98 ("armature_id",c_uint32)]
99 #}
100
101 class mdl_file(Structure):
102 #{
103 _fields_ = [("path",c_uint32),
104 ("pack_offset",c_uint32),
105 ("pack_size",c_uint32)]
106 #}
107
108 class mdl_texture(Structure):
109 #{
110 _fields_ = [("file",mdl_file),
111 ("type",c_uint32)]
112 #}
113
114 class mdl_array(Structure):
115 #{
116 _fields_ = [("file_offset",c_uint32),
117 ("item_count",c_uint32),
118 ("item_size",c_uint32),
119 ("name",c_byte*16)]
120 #}
121
122 class mdl_header(Structure):
123 #{
124 _fields_ = [("version",c_uint32),
125 ("arrays",mdl_array)]
126 #}
127
128 class ent_spawn(Structure):
129 #{
130 _fields_ = [("transform",mdl_transform),
131 ("pstr_name",c_uint32)]
132 #}
133
134 class ent_light(Structure):
135 #{
136 _fields_ = [("transform",mdl_transform),
137 ("daytime",c_uint32),
138 ("type",c_uint32),
139 ("colour",c_float*4),
140 ("angle",c_float),
141 ("range",c_float),
142 ("inverse_world",(c_float*3)*4), # Runtime
143 ("angle_sin_cos",(c_float*2))] # Runtime
144 #}
145
146 class version_refcount_union(Union):
147 #{
148 _fields_ = [("timing_version",c_uint32),
149 ("ref_count",c_uint8)]
150 #}
151
152 class ent_gate(Structure):
153 #{
154 _fields_ = [("type",c_uint32),
155 ("target", c_uint32),
156 ("dimensions", c_float*3),
157 ("co", (c_float*3)*2),
158 ("q", (c_float*4)*2),
159 ("to_world",(c_float*3)*4),
160 ("transport",(c_float*3)*4),
161 ("_anonymous_union",version_refcount_union),
162 ("timing_time",c_double),
163 ("routes",c_uint16*4)]
164 #}
165
166 class ent_route_node(Structure):
167 #{
168 _fields_ = [("co",c_float*3),
169 ("ref_count",c_uint8),
170 ("ref_total",c_uint8)]
171 #}
172
173 class ent_path_index(Structure):
174 #{
175 _fields_ = [("index",c_uint16)]
176 #}
177
178 class ent_checkpoint(Structure):
179 #{
180 _fields_ = [("gate_index",c_uint16),
181 ("path_start",c_uint16),
182 ("path_count",c_uint16)]
183 #}
184
185 class ent_route(Structure):
186 #{
187 _fields_ = [("transform",mdl_transform),
188 ("pstr_name",c_uint32),
189 ("checkpoints_start",c_uint16),
190 ("checkpoints_count",c_uint16),
191 ("colour",c_float*4),
192 ("active",c_uint32), #runtime
193 ("factive",c_float),
194 ("board_transform",(c_float*3)*4),
195 ("sm",mdl_submesh),
196 ("latest_pass",c_double)]
197 #}
198
199 def obj_ent_type( obj ):
200 #{
201 if obj.type == 'ARMATURE': return 'mdl_armature'
202 elif obj.type == 'LIGHT': return 'ent_light'
203 else: return obj.SR_data.ent_type
204 #}
205
206 def sr_filter_ent_type( obj, ent_type ):
207 #{
208 if obj == bpy.context.active_object: return False
209
210 for c0 in obj.users_collection:#{
211 for c1 in bpy.context.active_object.users_collection:#{
212 if c0 == c1:#{
213 return ent_type == obj_ent_type( obj )
214 #}
215 #}
216 #}
217
218 return False
219 #}
220
221 def compile_obj_transform( obj, transform ):
222 #{
223 co = obj.matrix_world @ Vector((0,0,0))
224 q = obj.matrix_local.to_quaternion()
225 s = obj.scale
226
227 # Setup transform
228 #
229 transform.co[0] = co[0]
230 transform.co[1] = co[2]
231 transform.co[2] = -co[1]
232 transform.q[0] = q[1]
233 transform.q[1] = q[3]
234 transform.q[2] = -q[2]
235 transform.q[3] = q[0]
236 transform.s[0] = s[0]
237 transform.s[1] = s[2]
238 transform.s[2] = s[1]
239 #}
240
241 def int_align_to( v, align ):
242 #{
243 while(v%align)!=0: v += 1
244 return v
245 #}
246
247 def bytearray_align_to( buffer, align, w=b'\xaa' ):
248 #{
249 while (len(buffer) % align) != 0: buffer.extend(w)
250 return buffer
251 #}
252
253 def bytearray_print_hex( s, w=16 ):
254 #{
255 for r in range((len(s)+(w-1))//w):#{
256 i0=(r+0)*w
257 i1=min((r+1)*w,len(s))
258 print( F'{r*w:06x}| \x1B[31m', end='')
259 print( F"{' '.join('{:02x}'.format(x) for x in s[i0:i1]):<48}",end='' )
260 print( "\x1B[0m", end='')
261 print( ''.join(chr(x) if (x>=33 and x<=126) else '.' for x in s[i0:i1] ) )
262 #}
263 #}
264
265 def sr_compile_string( s ):
266 #{
267 if s in sr_compile.string_cache: return sr_compile.string_cache[s]
268
269 index = len( sr_compile.string_data )
270 sr_compile.string_cache[s] = index
271 sr_compile.string_data.extend( s.encode('utf-8') )
272 sr_compile.string_data.extend( b'\0' )
273
274 bytearray_align_to( sr_compile.string_data, 4 )
275 return index
276 #}
277
278 def material_tex_image(v):
279 #{
280 return {
281 "Image Texture":
282 {
283 "image": F"{v}"
284 }
285 }
286 #}
287
288 cxr_graph_mapping = \
289 {
290 # Default shader setup
291 "Principled BSDF":
292 {
293 "Base Color":
294 {
295 "Image Texture":
296 {
297 "image": "tex_diffuse"
298 },
299 "Mix":
300 {
301 "A": material_tex_image("tex_diffuse"),
302 "B": material_tex_image("tex_decal")
303 },
304 },
305 "Normal":
306 {
307 "Normal Map":
308 {
309 "Color": material_tex_image("tex_normal")
310 }
311 }
312 }
313 }
314
315 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
316 #
317 def material_info(mat):
318 #{
319 info = {}
320
321 # Using the cxr_graph_mapping as a reference, go through the shader
322 # graph and gather all $props from it.
323 #
324 def _graph_read( node_def, node=None, depth=0 ):#{
325 nonlocal mat
326 nonlocal info
327
328 # Find rootnodes
329 #
330 if node == None:#{
331 _graph_read.extracted = []
332
333 for node_idname in node_def:#{
334 for n in mat.node_tree.nodes:#{
335 if n.name == node_idname:#{
336 node_def = node_def[node_idname]
337 node = n
338 break
339 #}
340 #}
341 #}
342 #}
343
344 for link in node_def:#{
345 link_def = node_def[link]
346
347 if isinstance( link_def, dict ):#{
348 node_link = None
349 for x in node.inputs:#{
350 if isinstance( x, bpy.types.NodeSocketColor ):#{
351 if link == x.name:#{
352 node_link = x
353 break
354 #}
355 #}
356 #}
357
358 if node_link and node_link.is_linked:#{
359 # look for definitions for the connected node type
360 #
361 from_node = node_link.links[0].from_node
362
363 node_name = from_node.name.split('.')[0]
364 if node_name in link_def:#{
365 from_node_def = link_def[ node_name ]
366
367 _graph_read( from_node_def, from_node, depth+1 )
368 #}
369
370 # No definition! :(
371 # TODO: Make a warning for this?
372 #}
373 else:#{
374 if "default" in link_def:#{
375 prop = link_def['default']
376 info[prop] = node_link.default_value
377 #}
378 #}
379 #}
380 else:#{
381 prop = link_def
382 info[prop] = getattr( node, link )
383 #}
384 #}
385 #}
386
387 _graph_read( cxr_graph_mapping )
388 return info
389 #}
390
391 def sr_pack_file( file, path, data ):
392 #{
393 file.path = sr_compile_string( path )
394 file.pack_offset = len( sr_compile.pack_data )
395 file.pack_size = len( data )
396
397 sr_compile.pack_data.extend( data )
398 bytearray_align_to( sr_compile.pack_data, 16 )
399 #}
400
401 def sr_compile_texture( img ):
402 #{
403 if img == None:
404 return 0
405
406 name = os.path.splitext( img.name )[0]
407
408 if name in sr_compile.texture_cache:
409 return sr_compile.texture_cache[name]
410
411 texture_index = (len(sr_compile.texture_data)//sizeof(mdl_texture)) +1
412
413 tex = mdl_texture()
414 tex.type = 0
415
416 if sr_compile.pack_textures:#{
417 filedata = qoi_encode( img )
418 sr_pack_file( tex.file, name, filedata )
419 #}
420
421 sr_compile.texture_cache[name] = texture_index
422 sr_compile.texture_data.extend( bytearray(tex) )
423 return texture_index
424 #}
425
426 def sr_compile_material( mat ):
427 #{
428 if mat == None:
429 return 0
430 if mat.name in sr_compile.material_cache:
431 return sr_compile.material_cache[mat.name]
432
433 index = (len(sr_compile.material_data)//sizeof(mdl_material))+1
434 sr_compile.material_cache[mat.name] = index
435
436 m = mdl_material()
437 m.pstr_name = sr_compile_string( mat.name )
438
439 flags = 0x00
440 if mat.SR_data.collision:#{
441 flags |= 0x2
442 if mat.SR_data.skate_surface: flags |= 0x1
443 if mat.SR_data.grind_surface: flags |= (0x8|0x1)
444 #}
445
446 if mat.SR_data.grow_grass: flags |= 0x4
447 m.flags = flags
448
449 m.surface_prop = int(mat.SR_data.surface_prop)
450
451 if mat.SR_data.shader == 'standard': m.shader = 0
452 if mat.SR_data.shader == 'standard_cutout': m.shader = 1
453 if mat.SR_data.shader == 'terrain_blend':#{
454 m.shader = 2
455
456 m.colour[0] = pow( mat.SR_data.sand_colour[0], 1.0/2.2 )
457 m.colour[1] = pow( mat.SR_data.sand_colour[1], 1.0/2.2 )
458 m.colour[2] = pow( mat.SR_data.sand_colour[2], 1.0/2.2 )
459 m.colour[3] = 1.0
460
461 m.colour1[0] = mat.SR_data.blend_offset[0]
462 m.colour1[1] = mat.SR_data.blend_offset[1]
463 #}
464
465 if mat.SR_data.shader == 'vertex_blend':#{
466 m.shader = 3
467
468 m.colour1[0] = mat.SR_data.blend_offset[0]
469 m.colour1[1] = mat.SR_data.blend_offset[1]
470 #}
471
472 if mat.SR_data.shader == 'water':#{
473 m.shader = 4
474
475 m.colour[0] = pow( mat.SR_data.shore_colour[0], 1.0/2.2 )
476 m.colour[1] = pow( mat.SR_data.shore_colour[1], 1.0/2.2 )
477 m.colour[2] = pow( mat.SR_data.shore_colour[2], 1.0/2.2 )
478 m.colour[3] = 1.0
479 m.colour1[0] = pow( mat.SR_data.ocean_colour[0], 1.0/2.2 )
480 m.colour1[1] = pow( mat.SR_data.ocean_colour[1], 1.0/2.2 )
481 m.colour1[2] = pow( mat.SR_data.ocean_colour[2], 1.0/2.2 )
482 m.colour1[3] = 1.0
483 #}
484
485 inf = material_info( mat )
486
487 if mat.SR_data.shader == 'standard' or \
488 mat.SR_data.shader == 'standard_cutout' or \
489 mat.SR_data.shader == 'terrain_blend' or \
490 mat.SR_data.shader == 'vertex_blend':
491 #{
492 if 'tex_diffuse' in inf:
493 m.tex_diffuse = sr_compile_texture(inf['tex_diffuse'])
494 #}
495
496 sr_compile.material_data.extend( bytearray(m) )
497 return index
498 #}
499
500 def sr_armature_bones( armature ):
501 #{
502 def _recurse_bone( b ):
503 #{
504 yield b
505 for c in b.children: yield from _recurse_bone( c )
506 #}
507
508 for b in armature.data.bones:
509 if not b.parent:
510 yield from _recurse_bone( b )
511 #}
512
513 def sr_compile_mesh( obj ):
514 #{
515 node=mdl_mesh()
516 compile_obj_transform(obj, node.transform)
517 node.pstr_name = sr_compile_string(obj.name)
518 node.flags = 0
519
520 can_use_cache = True
521 armature = None
522
523 for mod in obj.modifiers:#{
524 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
525 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
526 mod.type == 'ARRAY':
527 #{
528 can_use_cache = False
529 #}
530
531 if mod.type == 'ARMATURE': #{
532 node.flags = 1
533 armature = mod.object
534 rig_weight_groups = \
535 ['0 [ROOT]']+[_.name for _ in sr_armature_bones(mod.object)]
536 node.armature_id = sr_compile.entity_ids[armature.name]
537
538 POSE_OR_REST_CACHE = armature.data.pose_position
539 armature.data.pose_position = 'REST'
540 #}
541 #}
542
543 # Check the cache first
544 #
545 if can_use_cache and (obj.data.name in sr_compile.mesh_cache):#{
546 ref = sr_compile.mesh_cache[obj.data.name]
547 node.submesh_start = ref[0]
548 node.submesh_count = ref[1]
549 sr_compile.mesh_data.extend(bytearray(node))
550 return
551 #}
552
553 # Compile a whole new mesh
554 #
555 node.submesh_start = len(sr_compile.submesh_data)//sizeof(mdl_submesh)
556 node.submesh_count = 0
557
558 dgraph = bpy.context.evaluated_depsgraph_get()
559 data = obj.evaluated_get(dgraph).data
560 data.calc_loop_triangles()
561 data.calc_normals_split()
562
563 # Mesh is split into submeshes based on their material
564 #
565 mat_list = data.materials if len(data.materials) > 0 else [None]
566 for material_id, mat in enumerate(mat_list): #{
567 mref = {}
568
569 sm = mdl_submesh()
570 sm.indice_start = len(sr_compile.indice_data)//sizeof(c_uint32)
571 sm.vertex_start = len(sr_compile.vertex_data)//sizeof(mdl_vert)
572 sm.vertex_count = 0
573 sm.indice_count = 0
574 sm.material_id = sr_compile_material( mat )
575
576 INF=99999999.99999999
577 for i in range(3):#{
578 sm.bbx[0][i] = INF
579 sm.bbx[1][i] = -INF
580 #}
581
582 # Keep a reference to very very very similar vertices
583 # i have no idea how to speed it up.
584 #
585 vertex_reference = {}
586
587 # Write the vertex / indice data
588 #
589 for tri_index, tri in enumerate(data.loop_triangles):#{
590 if tri.material_index != material_id:
591 continue
592
593 for j in range(3):#{
594 vert = data.vertices[tri.vertices[j]]
595 li = tri.loops[j]
596 vi = data.loops[li].vertex_index
597
598 # Gather vertex information
599 #
600 co = vert.co
601 norm = data.loops[li].normal
602 uv = (0,0)
603 colour = (255,255,255,255)
604 groups = [0,0,0,0]
605 weights = [0,0,0,0]
606
607 # Uvs
608 #
609 if data.uv_layers:
610 uv = data.uv_layers.active.data[li].uv
611
612 # Vertex Colours
613 #
614 if data.vertex_colors:#{
615 colour = data.vertex_colors.active.data[li].color
616 colour = (int(colour[0]*255.0),\
617 int(colour[1]*255.0),\
618 int(colour[2]*255.0),\
619 int(colour[3]*255.0))
620 #}
621
622 # Weight groups: truncates to the 3 with the most influence. The
623 # fourth bone ID is never used by the shader so it
624 # is always 0
625 #
626 if armature:#{
627 src_groups = [_ for _ in data.vertices[vi].groups \
628 if obj.vertex_groups[_.group].name in \
629 rig_weight_groups ]
630
631 weight_groups = sorted( src_groups, key = \
632 lambda a: a.weight, reverse=True )
633 tot = 0.0
634 for ml in range(3):#{
635 if len(weight_groups) > ml:#{
636 g = weight_groups[ml]
637 name = obj.vertex_groups[g.group].name
638 weight = g.weight
639 weights[ml] = weight
640 groups[ml] = rig_weight_groups.index(name)
641 tot += weight
642 #}
643 #}
644
645 if len(weight_groups) > 0:#{
646 inv_norm = (1.0/tot) * 65535.0
647 for ml in range(3):#{
648 weights[ml] = int( weights[ml] * inv_norm )
649 weights[ml] = min( weights[ml], 65535 )
650 weights[ml] = max( weights[ml], 0 )
651 #}
652 #}
653 #}
654 else:#{
655 li1 = tri.loops[(j+1)%3]
656 vi1 = data.loops[li1].vertex_index
657 e0 = data.edges[ data.loops[li].edge_index ]
658
659 if e0.use_freestyle_mark and \
660 ((e0.vertices[0] == vi and e0.vertices[1] == vi1) or \
661 (e0.vertices[0] == vi1 and e0.vertices[1] == vi)):
662 #{
663 weights[0] = 1
664 #}
665 #}
666
667 TOLERENCE = float(10**4)
668 key = (int(co[0]*TOLERENCE+0.5),
669 int(co[1]*TOLERENCE+0.5),
670 int(co[2]*TOLERENCE+0.5),
671 int(norm[0]*TOLERENCE+0.5),
672 int(norm[1]*TOLERENCE+0.5),
673 int(norm[2]*TOLERENCE+0.5),
674 int(uv[0]*TOLERENCE+0.5),
675 int(uv[1]*TOLERENCE+0.5),
676 colour[0], # these guys are already quantized
677 colour[1], # .
678 colour[2], # .
679 colour[3], # .
680 weights[0], # v
681 weights[1],
682 weights[2],
683 weights[3],
684 groups[0],
685 groups[1],
686 groups[2],
687 groups[3])
688
689 if key in vertex_reference:
690 index = vertex_reference[key]
691 else:#{
692 index = bytearray(c_uint32(sm.vertex_count))
693 sm.vertex_count+=1
694
695 vertex_reference[key] = index
696 v = mdl_vert()
697 v.co[0] = co[0]
698 v.co[1] = co[2]
699 v.co[2] = -co[1]
700 v.norm[0] = norm[0]
701 v.norm[1] = norm[2]
702 v.norm[2] = -norm[1]
703 v.uv[0] = uv[0]
704 v.uv[1] = uv[1]
705 v.colour[0] = colour[0]
706 v.colour[1] = colour[1]
707 v.colour[2] = colour[2]
708 v.colour[3] = colour[3]
709 v.weights[0] = weights[0]
710 v.weights[1] = weights[1]
711 v.weights[2] = weights[2]
712 v.weights[3] = weights[3]
713 v.groups[0] = groups[0]
714 v.groups[1] = groups[1]
715 v.groups[2] = groups[2]
716 v.groups[3] = groups[3]
717
718 for i in range(3):#{
719 sm.bbx[0][i] = min( sm.bbx[0][i], v.co[i] )
720 sm.bbx[1][i] = max( sm.bbx[1][i], v.co[i] )
721 #}
722
723 sr_compile.vertex_data.extend(bytearray(v))
724 #}
725
726 sm.indice_count += 1
727 sr_compile.indice_data.extend( index )
728 #}
729 #}
730
731 # Make sure bounding box isn't -inf -> inf if no vertices
732 #
733 if sm.vertex_count == 0:
734 for j in range(2):
735 for i in range(3):
736 sm.bbx[j][i] = 0
737
738 # Add submesh to encoder
739 #
740 sr_compile.submesh_data.extend( bytearray(sm) )
741 node.submesh_count += 1
742 #}
743
744 if armature:#{
745 armature.data.pose_position = POSE_OR_REST_CACHE
746 #}
747
748 # Save a reference to this node since we want to reuse the submesh indices
749 # later.
750 sr_compile.mesh_cache[obj.data.name]=(node.submesh_start,node.submesh_count)
751 sr_compile.mesh_data.extend(bytearray(node))
752 #}
753
754 def sr_compile_armature( obj ):
755 #{
756 node = mdl_armature()
757 node.bone_start = len(sr_compile.bone_data)//sizeof(mdl_bone)
758 node.bone_count = 0
759 node.anim_start = len(sr_compile.anim_data)//sizeof(mdl_animation)
760 node.anim_count = 0
761
762 bones = [_ for _ in sr_armature_bones(obj)]
763 bones_names = [None]+[_.name for _ in bones]
764
765 for b in bones:#{
766 bone = mdl_bone()
767 if b.use_deform: bone.flags = 0x1
768 if b.parent: bone.parent = bones_names.index(b.parent.name)
769
770 bone.collider = int(b.SR_data.collider)
771
772 if bone.collider>0:#{
773 bone.hitbox[0][0] = b.SR_data.collider_min[0]
774 bone.hitbox[0][1] = b.SR_data.collider_min[2]
775 bone.hitbox[0][2] = -b.SR_data.collider_max[1]
776 bone.hitbox[1][0] = b.SR_data.collider_max[0]
777 bone.hitbox[1][1] = b.SR_data.collider_max[2]
778 bone.hitbox[1][2] = -b.SR_data.collider_min[1]
779 #}
780
781 if b.SR_data.cone_constraint:#{
782 bone.flags |= 0x4
783 bone.conevx[0] = b.SR_data.conevx[0]
784 bone.conevx[1] = b.SR_data.conevx[2]
785 bone.conevx[2] = -b.SR_data.conevx[1]
786 bone.conevy[0] = b.SR_data.conevy[0]
787 bone.conevy[1] = b.SR_data.conevy[2]
788 bone.conevy[2] = -b.SR_data.conevy[1]
789 bone.coneva[0] = b.SR_data.coneva[0]
790 bone.coneva[1] = b.SR_data.coneva[2]
791 bone.coneva[2] = -b.SR_data.coneva[1]
792 bone.conet = b.SR_data.conet
793 #}
794
795 bone.co[0] = b.head_local[0]
796 bone.co[1] = b.head_local[2]
797 bone.co[2] = -b.head_local[1]
798 bone.end[0] = b.tail_local[0] - bone.co[0]
799 bone.end[1] = b.tail_local[2] - bone.co[1]
800 bone.end[2] = -b.tail_local[1] - bone.co[2]
801 bone.pstr_name = sr_compile_string( b.name )
802
803 for c in obj.pose.bones[b.name].constraints:#{
804 if c.type == 'IK':#{
805 bone.flags |= 0x2
806 bone.ik_target = bones_names.index(c.subtarget)
807 bone.ik_pole = bones_names.index(c.pole_subtarget)
808 #}
809 #}
810
811 node.bone_count += 1
812 sr_compile.bone_data.extend(bytearray(bone))
813 #}
814
815 # Compile anims
816 #
817 if obj.animation_data and sr_compile.pack_animations: #{
818 # So we can restore later
819 #
820 previous_frame = bpy.context.scene.frame_current
821 previous_action = obj.animation_data.action
822 POSE_OR_REST_CACHE = obj.data.pose_position
823 obj.data.pose_position = 'POSE'
824
825 for NLALayer in obj.animation_data.nla_tracks:#{
826 for NLAStrip in NLALayer.strips:#{
827 # set active
828 #
829 for a in bpy.data.actions:#{
830 if a.name == NLAStrip.name:#{
831 obj.animation_data.action = a
832 break
833 #}
834 #}
835
836 # Clip to NLA settings
837 #
838 anim_start = int(NLAStrip.action_frame_start)
839 anim_end = int(NLAStrip.action_frame_end)
840
841 # Export strips
842 #
843 anim = mdl_animation()
844 anim.pstr_name = sr_compile_string( NLAStrip.action.name )
845 anim.rate = 30.0
846 anim.keyframe_start = len(sr_compile.keyframe_data)//\
847 sizeof(mdl_transform)
848 anim.length = anim_end-anim_start
849
850 i = 0
851 # Export the keyframes
852 for frame in range(anim_start,anim_end):#{
853 bpy.context.scene.frame_set(frame)
854
855 for rb in bones:#{
856 pb = obj.pose.bones[rb.name]
857
858 # relative bone matrix
859 if rb.parent is not None:#{
860 offset_mtx = rb.parent.matrix_local
861 offset_mtx = offset_mtx.inverted_safe() @ \
862 rb.matrix_local
863
864 inv_parent = pb.parent.matrix @ offset_mtx
865 inv_parent.invert_safe()
866 fpm = inv_parent @ pb.matrix
867 #}
868 else:#{
869 bone_mtx = rb.matrix.to_4x4()
870 local_inv = rb.matrix_local.inverted_safe()
871 fpm = bone_mtx @ local_inv @ pb.matrix
872 #}
873
874 loc, rot, sca = fpm.decompose()
875
876 # rotation
877 lc_m = pb.matrix_channel.to_3x3()
878 if pb.parent is not None:#{
879 smtx = pb.parent.matrix_channel.to_3x3()
880 lc_m = smtx.inverted() @ lc_m
881 #}
882 rq = lc_m.to_quaternion()
883
884 kf = mdl_transform()
885 kf.co[0] = loc[0]
886 kf.co[1] = loc[2]
887 kf.co[2] = -loc[1]
888 kf.q[0] = rq[1]
889 kf.q[1] = rq[3]
890 kf.q[2] = -rq[2]
891 kf.q[3] = rq[0]
892 kf.s[0] = sca[0]
893 kf.s[1] = sca[1]
894 kf.s[2] = sca[2]
895 sr_compile.keyframe_data.extend(bytearray(kf))
896
897 i+=1
898 #}
899 #}
900
901 # Add to animation buffer
902 #
903 sr_compile.anim_data.extend(bytearray(anim))
904 node.anim_count += 1
905
906 # Report progress
907 #
908 print( F"[SR] | anim( {NLAStrip.action.name} )" )
909 #}
910 #}
911
912 # Restore context to how it was before
913 #
914 bpy.context.scene.frame_set( previous_frame )
915 obj.animation_data.action = previous_action
916 obj.data.pose_position = POSE_OR_REST_CACHE
917 #}
918
919 sr_compile.armature_data.extend(bytearray(node))
920 #}
921
922 def sr_ent_push( struct ):
923 #{
924 clase = type(struct).__name__
925
926 if clase not in sr_compile.entity_data:#{
927 sr_compile.entity_data[ clase ] = bytearray()
928 sr_compile.entity_info[ clase ] = { 'size': sizeof(struct) }
929 #}
930
931 index = len(sr_compile.entity_data[ clase ])//sizeof(struct)
932 sr_compile.entity_data[ clase ].extend( bytearray(struct) )
933 return index
934 #}
935
936 def sr_array_title( arr, name, count, size, offset ):
937 #{
938 for i in range(len(name)):#{
939 arr.name[i] = ord(name[i])
940 #}
941 arr.file_offset = offset
942 arr.item_count = count
943 arr.item_size = size
944 #}
945
946 def sr_compile( collection ):
947 #{
948 print( F"[SR] compiler begin ({collection.name}.mdl)" )
949
950 #settings
951 sr_compile.pack_textures = collection.SR_data.pack_textures
952 sr_compile.pack_animations = collection.SR_data.animations
953
954 # caches
955 sr_compile.string_cache = {}
956 sr_compile.mesh_cache = {}
957 sr_compile.material_cache = {}
958 sr_compile.texture_cache = {}
959
960 # compiled data
961 sr_compile.mesh_data = bytearray()
962 sr_compile.submesh_data = bytearray()
963 sr_compile.vertex_data = bytearray()
964 sr_compile.indice_data = bytearray()
965 sr_compile.bone_data = bytearray()
966 sr_compile.material_data = bytearray()
967 sr_compile.armature_data = bytearray()
968 sr_compile.anim_data = bytearray()
969 sr_compile.keyframe_data = bytearray()
970 sr_compile.texture_data = bytearray()
971
972 # just bytes not structures
973 sr_compile.string_data = bytearray()
974 sr_compile.pack_data = bytearray()
975
976 # variable
977 sr_compile.entity_data = {}
978 sr_compile.entity_info = {}
979
980 print( F"[SR] assign entity ID's" )
981 sr_compile.entities = {}
982 sr_compile.entity_ids = {}
983
984 mesh_count = 0
985 for obj in collection.all_objects: #{
986 if obj.type == 'MESH': mesh_count += 1
987
988 ent_type = obj_ent_type( obj )
989 if ent_type == 'none': continue
990
991 if ent_type not in sr_compile.entities: sr_compile.entities[ent_type] = []
992 sr_compile.entity_ids[obj.name] = len( sr_compile.entities[ent_type] )
993 sr_compile.entities[ent_type] += [obj]
994 #}
995
996 print( F"[SR] Compiling geometry" )
997 i=0
998 for obj in collection.all_objects:#{
999 if obj.type == 'MESH':#{
1000 i+=1
1001 print( F'[SR] {i: 3}/{mesh_count} {obj.name:<40}', end='\r' )
1002 sr_compile_mesh( obj )
1003 #}
1004 #}
1005
1006 checkpoint_count = 0
1007 pathindice_count = 0
1008
1009 for ent_type, arr in sr_compile.entities.items():#{
1010 print(F"[SR] Compiling {len(arr)} {ent_type}{'s' if len(arr)>1 else ''}")
1011
1012 for i in range(len(arr)):#{
1013 obj = arr[i]
1014
1015 print( F"[SR] {i+1: 3}/{len(arr)} {obj.name:<40} ",end='\r' )
1016
1017 if ent_type == 'mdl_armature': sr_compile_armature(obj)
1018 elif ent_type == 'ent_light': #{
1019 light = ent_light()
1020 compile_obj_transform( obj, light.transform )
1021 light.daytime = obj.data.SR_data.daytime
1022 if obj.data.type == 'POINT':#{
1023 light.type = 0
1024 #}
1025 elif obj.data.type == 'SPOT':#{
1026 light.type = 1
1027 light.angle = obj.data.spot_size*0.5
1028 #}
1029 light.range = obj.data.cutoff_distance
1030 light.colour[0] = obj.data.color[0]
1031 light.colour[1] = obj.data.color[1]
1032 light.colour[2] = obj.data.color[2]
1033 light.colour[3] = obj.data.energy
1034 sr_ent_push( light )
1035 #}
1036 elif ent_type == 'ent_gate': #{
1037 gate = ent_gate()
1038 gate.type = 0
1039 obj_data = obj.SR_data.ent_gate[0]
1040 mesh_data = obj.data.SR_data.ent_gate[0]
1041 if obj_data.target:#{
1042 gate.target = sr_compile.entity_ids[obj_data.target.name]
1043 gate.type = 1
1044 #}
1045 gate.dimensions[0] = mesh_data.dimensions[0]
1046 gate.dimensions[1] = mesh_data.dimensions[1]
1047 gate.dimensions[2] = mesh_data.dimensions[2]
1048
1049 q = [obj.matrix_local.to_quaternion(), (0,0,0,1)]
1050 co = [obj.matrix_world @ Vector((0,0,0)), (0,0,0)]
1051
1052 if obj_data.target:#{
1053 q[1] = obj_data.target.matrix_local.to_quaternion()
1054 co[1]= obj_data.target.matrix_world @ Vector((0,0,0))
1055 #}
1056
1057 # Setup transform
1058 #
1059 for x in range(2):#{
1060 gate.co[x][0] = co[x][0]
1061 gate.co[x][1] = co[x][2]
1062 gate.co[x][2] = -co[x][1]
1063 gate.q[x][0] = q[x][1]
1064 gate.q[x][1] = q[x][3]
1065 gate.q[x][2] = -q[x][2]
1066 gate.q[x][3] = q[x][0]
1067 #}
1068
1069 sr_ent_push( gate )
1070 #}
1071 elif ent_type == 'ent_spawn': #{
1072 spawn = ent_spawn()
1073 compile_obj_transform( obj, spawn.transform )
1074 obj_data = obj.SR_data.ent_spawn[0]
1075 spawn.pstr_name = sr_compile_string( obj_data.name )
1076 sr_ent_push( spawn )
1077 #}
1078 elif ent_type == 'ent_route': #{
1079 obj_data = obj.SR_data.ent_route[0]
1080 route = ent_route()
1081 route.pstr_name = sr_compile_string( obj_data.alias ) #TODO
1082 route.checkpoints_start = checkpoint_count
1083 route.checkpoints_count = 0
1084
1085 for ci in range(3):
1086 route.colour[ci] = obj_data.colour[ci]
1087 route.colour[3] = 1.0
1088
1089 compile_obj_transform( obj, route.transform )
1090
1091 checkpoints = obj_data.gates
1092 route_nodes = []
1093
1094 for uc in obj.users_collection[0].objects:#{
1095 uc_type = obj_ent_type( uc )
1096 if uc_type == 'ent_gate' or uc_type == 'ent_route_node':
1097 route_nodes += [uc]
1098 #}
1099 graph = node_graph( route_nodes )
1100
1101 for i in range(len(checkpoints)):#{
1102 gi = checkpoints[i].target
1103 gj = checkpoints[(i+1)%len(checkpoints)].target
1104 gate = gi
1105
1106 if gi:#{
1107 dest = gi.SR_data.ent_gate[0].target
1108 gi = dest
1109 #}
1110
1111 if gi==gj: continue # error?
1112 if not gi or not gj: continue
1113
1114 checkpoint = ent_checkpoint()
1115 checkpoint.gate_index = sr_compile.entity_ids[gate.name]
1116 checkpoint.path_start = pathindice_count
1117 checkpoint.path_count = 0
1118
1119 path = dijkstra( graph, gj.name, gi.name )
1120 if path:#{
1121 for pi in range(1,len(path)-1):#{
1122 pathindice = ent_path_index()
1123 pathindice.index = sr_compile.entity_ids[path[pi]]
1124 sr_ent_push( pathindice )
1125
1126 checkpoint.path_count += 1
1127 pathindice_count += 1
1128 #}
1129 #}
1130
1131 sr_ent_push( checkpoint )
1132 route.checkpoints_count += 1
1133 checkpoint_count += 1
1134 #}
1135
1136 sr_ent_push( route )
1137 #}
1138 elif ent_type == 'ent_route_node':#{
1139 rn = ent_route_node()
1140 rn.co[0] = obj.location[0]
1141 rn.co[1] = obj.location[2]
1142 rn.co[2] = -obj.location[1]
1143 sr_ent_push( rn )
1144 #}
1145 #}
1146 #}
1147
1148 print( F"[SR] Writing file" )
1149
1150 file_array_instructions = {}
1151 file_offset = 0
1152
1153 def _write_array( name, item_size, data ):#{
1154 nonlocal file_array_instructions, file_offset
1155
1156 count = len(data)//item_size
1157 file_array_instructions[name] = {'count':count, 'size':item_size,\
1158 'data':data, 'offset': file_offset}
1159 file_offset += len(data)
1160 file_offset = int_align_to( file_offset, 8 )
1161 #}
1162
1163 _write_array( 'strings', 1, sr_compile.string_data )
1164 _write_array( 'mdl_mesh', sizeof(mdl_mesh), sr_compile.mesh_data )
1165 _write_array( 'mdl_submesh', sizeof(mdl_submesh), sr_compile.submesh_data )
1166 _write_array( 'mdl_material', sizeof(mdl_material), sr_compile.material_data)
1167 _write_array( 'mdl_texture', sizeof(mdl_texture), sr_compile.texture_data)
1168 _write_array( 'mdl_armature', sizeof(mdl_armature), sr_compile.armature_data)
1169 _write_array( 'mdl_bone', sizeof(mdl_bone), sr_compile.bone_data )
1170
1171 for name, buffer in sr_compile.entity_data.items():#{
1172 _write_array( name, sr_compile.entity_info[name]['size'], buffer )
1173 #}
1174
1175 _write_array( 'mdl_animation', sizeof(mdl_animation), sr_compile.anim_data)
1176 _write_array( 'mdl_keyframe', sizeof(mdl_transform),sr_compile.keyframe_data)
1177 _write_array( 'mdl_vert', sizeof(mdl_vert), sr_compile.vertex_data )
1178 _write_array( 'mdl_indice', sizeof(c_uint32), sr_compile.indice_data )
1179 _write_array( 'pack', 1, sr_compile.pack_data )
1180
1181 header_size = int_align_to( sizeof(mdl_header), 8 )
1182 index_size = int_align_to( sizeof(mdl_array)*len(file_array_instructions),8 )
1183
1184 folder = bpy.path.abspath(bpy.context.scene.SR_data.export_dir)
1185 path = F"{folder}{collection.name}.mdl"
1186 print( path )
1187
1188 fp = open( path, "wb" )
1189 header = mdl_header()
1190 header.version = 40
1191 sr_array_title( header.arrays, \
1192 'index', len(file_array_instructions), \
1193 sizeof(mdl_array), header_size )
1194
1195 fp.write( bytearray_align_to( bytearray(header), 8 ) )
1196
1197 print( F'[SR] {"name":>16}| count | offset' )
1198 index = bytearray()
1199 for name,info in file_array_instructions.items():#{
1200 arr = mdl_array()
1201 offset = info['offset'] + header_size + index_size
1202 sr_array_title( arr, name, info['count'], info['size'], offset )
1203 index.extend( bytearray(arr) )
1204
1205 print( F'[SR] {name:>16}| {info["count"]: 8} '+\
1206 F' 0x{info["offset"]:02x}' )
1207 #}
1208 fp.write( bytearray_align_to( index, 8 ) )
1209 #bytearray_print_hex( index )
1210
1211 for name,info in file_array_instructions.items():#{
1212 fp.write( bytearray_align_to( info['data'], 8 ) )
1213 #}
1214
1215 fp.close()
1216
1217 print( '[SR] done' )
1218 #}
1219
1220 class SR_SCENE_SETTINGS(bpy.types.PropertyGroup):
1221 #{
1222 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
1223 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
1224 gizmos: bpy.props.BoolProperty( name="Draw Gizmos", default=True )
1225
1226 panel: bpy.props.EnumProperty(
1227 name='Panel',
1228 description='',
1229 items=[
1230 ('EXPORT', 'Export', '', 'MOD_BUILD',0),
1231 ('ENTITY', 'Entity', '', 'MONKEY',1),
1232 ('SETTINGS', 'Settings', 'Settings', 'PREFERENCES',2),
1233 ],
1234 )
1235 #}
1236
1237 class SR_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
1238 #{
1239 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
1240 animations: bpy.props.BoolProperty( name="Export animation", default=True)
1241 #}
1242
1243 def sr_get_mirror_bone( bones ):
1244 #{
1245 side = bones.active.name[-1:]
1246 other_name = bones.active.name[:-1]
1247 if side == 'L': other_name += 'R'
1248 elif side == 'R': other_name += 'L'
1249 else: return None
1250
1251 for b in bones:#{
1252 if b.name == other_name:
1253 return b
1254 #}
1255
1256 return None
1257 #}
1258
1259 class SR_MIRROR_BONE_X(bpy.types.Operator):
1260 #{
1261 bl_idname="skaterift.mirror_bone"
1262 bl_label="Mirror bone attributes - SkateRift"
1263
1264 def execute(_,context):
1265 #{
1266 active_object = context.active_object
1267 bones = active_object.data.bones
1268 a = bones.active
1269 b = sr_get_mirror_bone( bones )
1270
1271 if not b: return {'FINISHED'}
1272
1273 b.SR_data.collider = a.SR_data.collider
1274
1275 def _v3copyflipy( a, b ):#{
1276 b[0] = a[0]
1277 b[1] = -a[1]
1278 b[2] = a[2]
1279 #}
1280
1281 _v3copyflipy( a.SR_data.collider_min, b.SR_data.collider_min )
1282 _v3copyflipy( a.SR_data.collider_max, b.SR_data.collider_max )
1283 b.SR_data.collider_min[1] = -a.SR_data.collider_max[1]
1284 b.SR_data.collider_max[1] = -a.SR_data.collider_min[1]
1285
1286 b.SR_data.cone_constraint = a.SR_data.cone_constraint
1287
1288 _v3copyflipy( a.SR_data.conevx, b.SR_data.conevy )
1289 _v3copyflipy( a.SR_data.conevy, b.SR_data.conevx )
1290 _v3copyflipy( a.SR_data.coneva, b.SR_data.coneva )
1291
1292 b.SR_data.conet = a.SR_data.conet
1293
1294 # redraw
1295 ob = bpy.context.scene.objects[0]
1296 ob.hide_render = ob.hide_render
1297 return {'FINISHED'}
1298 #}
1299 #}
1300
1301 class SR_COMPILE(bpy.types.Operator):
1302 #{
1303 bl_idname="skaterift.compile_all"
1304 bl_label="Compile All"
1305
1306 def execute(_,context):
1307 #{
1308 view_layer = bpy.context.view_layer
1309 for col in view_layer.layer_collection.children["export"].children:
1310 if not col.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1311 sr_compile( bpy.data.collections[col.name] )
1312
1313 return {'FINISHED'}
1314 #}
1315 #}
1316
1317 class SR_COMPILE_THIS(bpy.types.Operator):
1318 #{
1319 bl_idname="skaterift.compile_this"
1320 bl_label="Compile This collection"
1321
1322 def execute(_,context):
1323 #{
1324 col = bpy.context.collection
1325 sr_compile( col )
1326
1327 return {'FINISHED'}
1328 #}
1329 #}
1330
1331 class SR_INTERFACE(bpy.types.Panel):
1332 #{
1333 bl_idname = "VIEW3D_PT_skate_rift"
1334 bl_label = "Skate Rift"
1335 bl_space_type = 'VIEW_3D'
1336 bl_region_type = 'UI'
1337 bl_category = "Skate Rift"
1338
1339 def draw(_, context):
1340 #{
1341 # Compiler section
1342
1343 row = _.layout.row()
1344 row.scale_y = 1.75
1345 row.prop( context.scene.SR_data, 'panel', expand=True )
1346
1347 if context.scene.SR_data.panel == 'SETTINGS': #{
1348 _.layout.prop( context.scene.SR_data, 'gizmos' )
1349 #}
1350 elif context.scene.SR_data.panel == 'EXPORT': #{
1351 _.layout.prop( context.scene.SR_data, "export_dir" )
1352 col = bpy.context.collection
1353
1354 found_in_export = False
1355 export_count = 0
1356 view_layer = bpy.context.view_layer
1357 for c1 in view_layer.layer_collection.children["export"].children: #{
1358 if not c1.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1359 export_count += 1
1360
1361 if c1.name == col.name: #{
1362 found_in_export = True
1363 #}
1364 #}
1365
1366 box = _.layout.box()
1367 row = box.row()
1368 row.alignment = 'CENTER'
1369 row.scale_y = 1.5
1370
1371 if found_in_export: #{
1372 row.label( text=col.name + ".mdl" )
1373 box.prop( col.SR_data, "pack_textures" )
1374 box.prop( col.SR_data, "animations" )
1375 box.operator( "skaterift.compile_this" )
1376 #}
1377 else: #{
1378 row.enabled=False
1379 row.label( text=col.name )
1380
1381 row = box.row()
1382 row.enabled=False
1383 row.alignment = 'CENTER'
1384 row.scale_y = 1.5
1385 row.label( text="This collection is not in the export group" )
1386 #}
1387
1388 box = _.layout.box()
1389 row = box.row()
1390
1391 split = row.split( factor=0.3, align=True )
1392 split.prop( context.scene.SR_data, "use_hidden", text="hidden" )
1393
1394 row1 = split.row()
1395 if export_count == 0:
1396 row1.enabled=False
1397 row1.operator( "skaterift.compile_all", \
1398 text=F"Compile all ({export_count} collections)" )
1399 #}
1400 elif context.scene.SR_data.panel == 'ENTITY': #{
1401 active_object = context.active_object
1402 if not active_object: return
1403
1404 box = _.layout.box()
1405 row = box.row()
1406 row.alignment = 'CENTER'
1407 row.label( text=active_object.name )
1408 row.scale_y = 1.5
1409
1410 def _draw_prop_collection( data ): #{
1411 nonlocal box
1412 row = box.row()
1413 row.alignment = 'CENTER'
1414 row.enabled = False
1415 row.scale_y = 1.5
1416 row.label( text=F'{data[0]}' )
1417
1418 if hasattr(type(data[0]),'sr_inspector'):#{
1419 type(data[0]).sr_inspector( box, data )
1420 #}
1421 else:#{
1422 for a in data[0].__annotations__:
1423 box.prop( data[0], a )
1424 #}
1425 #}
1426
1427 if active_object.type == 'ARMATURE': #{
1428 if active_object.mode == 'POSE': #{
1429 bones = active_object.data.bones
1430 mb = sr_get_mirror_bone( bones )
1431 if mb:#{
1432 box.operator( "skaterift.mirror_bone", \
1433 text=F'Mirror attributes to {mb.name}' )
1434 #}
1435
1436 _draw_prop_collection( [bones.active.SR_data ] )
1437 #}
1438 else: #{
1439 row = box.row()
1440 row.alignment='CENTER'
1441 row.scale_y=2.0
1442 row.enabled=False
1443 row.label( text="Enter pose mode to modify bone properties" )
1444 #}
1445 #}
1446 elif active_object.type == 'LIGHT': #{
1447 _draw_prop_collection( [active_object.data.SR_data] )
1448 #}
1449 elif active_object.type == 'EMPTY' or active_object.type == 'MESH': #{
1450 box.prop( active_object.SR_data, "ent_type" )
1451 ent_type = active_object.SR_data.ent_type
1452
1453 col = getattr( active_object.SR_data, ent_type, None )
1454 if col != None and len(col)!=0: _draw_prop_collection( col )
1455
1456 if active_object.type == 'MESH':#{
1457 col = getattr( active_object.data.SR_data, ent_type, None )
1458 if col != None and len(col)!=0: _draw_prop_collection( col )
1459 #}
1460 #}
1461 #}
1462 #}
1463 #}
1464
1465 class SR_MATERIAL_PANEL(bpy.types.Panel):
1466 #{
1467 bl_label="Skate Rift material"
1468 bl_idname="MATERIAL_PT_sr_material"
1469 bl_space_type='PROPERTIES'
1470 bl_region_type='WINDOW'
1471 bl_context="material"
1472
1473 def draw(_,context):
1474 #{
1475 active_object = bpy.context.active_object
1476 if active_object == None: return
1477 active_mat = active_object.active_material
1478 if active_mat == None: return
1479
1480 info = material_info( active_mat )
1481
1482 if 'tex_diffuse' in info:#{
1483 _.layout.label( icon='INFO', \
1484 text=F"{info['tex_diffuse'].name} will be compiled" )
1485 #}
1486
1487 _.layout.prop( active_mat.SR_data, "shader" )
1488 _.layout.prop( active_mat.SR_data, "surface_prop" )
1489 _.layout.prop( active_mat.SR_data, "collision" )
1490
1491 if active_mat.SR_data.collision:#{
1492 _.layout.prop( active_mat.SR_data, "skate_surface" )
1493 _.layout.prop( active_mat.SR_data, "grind_surface" )
1494 _.layout.prop( active_mat.SR_data, "grow_grass" )
1495 #}
1496
1497 if active_mat.SR_data.shader == "terrain_blend":#{
1498 box = _.layout.box()
1499 box.prop( active_mat.SR_data, "blend_offset" )
1500 box.prop( active_mat.SR_data, "sand_colour" )
1501 #}
1502 elif active_mat.SR_data.shader == "vertex_blend":#{
1503 box = _.layout.box()
1504 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
1505 box.prop( active_mat.SR_data, "blend_offset" )
1506 #}
1507 elif active_mat.SR_data.shader == "water":#{
1508 box = _.layout.box()
1509 box.label( icon='INFO', text="Depth scale of 16 meters" )
1510 box.prop( active_mat.SR_data, "shore_colour" )
1511 box.prop( active_mat.SR_data, "ocean_colour" )
1512 #}
1513 #}
1514 #}
1515
1516 def sr_get_type_enum( scene, context ):
1517 #{
1518 items = [('none','None',"")]
1519 mesh_entities=['ent_gate']
1520 point_entities=['ent_spawn','ent_route_node','ent_route']
1521
1522 for e in point_entities: items += [(e,e,'')]
1523
1524 if context.scene.SR_data.panel == 'ENTITY': #{
1525 if context.active_object.type == 'MESH': #{
1526 for e in mesh_entities: items += [(e,e,'')]
1527 #}
1528 #}
1529 else: #{
1530 for e in mesh_entities: items += [(e,e,'')]
1531 #}
1532
1533 return items
1534 #}
1535
1536 def sr_on_type_change( _, context ):
1537 #{
1538 obj = context.active_object
1539 ent_type = obj.SR_data.ent_type
1540 if ent_type == 'none': return
1541 if obj.type == 'MESH':#{
1542 col = getattr( obj.data.SR_data, ent_type, None )
1543 if col != None and len(col)==0: col.add()
1544 #}
1545
1546 col = getattr( obj.SR_data, ent_type, None )
1547 if col != None and len(col)==0: col.add()
1548 #}
1549
1550 class SR_OBJECT_ENT_SPAWN(bpy.types.PropertyGroup):
1551 #{
1552 alias: bpy.props.StringProperty( name='alias' )
1553 #}
1554
1555 class SR_OBJECT_ENT_GATE(bpy.types.PropertyGroup):
1556 #{
1557 target: bpy.props.PointerProperty( \
1558 type=bpy.types.Object, name="destination", \
1559 poll=lambda self,obj: sr_filter_ent_type(obj,'ent_gate'))
1560 #}
1561
1562 class SR_MESH_ENT_GATE(bpy.types.PropertyGroup):
1563 #{
1564 dimensions: bpy.props.FloatVectorProperty(name="dimensions",size=3)
1565 #}
1566
1567 class SR_OBJECT_ENT_ROUTE_ENTRY(bpy.types.PropertyGroup):
1568 #{
1569 target: bpy.props.PointerProperty( \
1570 type=bpy.types.Object, name='target', \
1571 poll=lambda self,obj: sr_filter_ent_type(obj,'ent_gate'))
1572 #}
1573
1574 class SR_UL_ROUTE_NODE_LIST(bpy.types.UIList):
1575 #{
1576 bl_idname = 'SR_UL_ROUTE_NODE_LIST'
1577
1578 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
1579 #{
1580 layout.prop( item, 'target', text='', emboss=False )
1581 #}
1582 #}
1583
1584 class SR_OT_ROUTE_LIST_NEW_ITEM(bpy.types.Operator):
1585 #{
1586 bl_idname = "skaterift.new_entry"
1587 bl_label = "Add gate"
1588
1589 def execute(self, context):#{
1590 active_object = context.active_object
1591 active_object.SR_data.ent_route[0].gates.add()
1592 return{'FINISHED'}
1593 #}
1594 #}
1595
1596 class SR_OT_ROUTE_LIST_DEL_ITEM(bpy.types.Operator):
1597 #{
1598 bl_idname = "skaterift.del_entry"
1599 bl_label = "Remove gate"
1600
1601 @classmethod
1602 def poll(cls, context):#{
1603 active_object = context.active_object
1604 if obj_ent_type == 'ent_gate':#{
1605 return active_object.SR_data.ent_route[0].gates
1606 #}
1607 else: return False
1608 #}
1609
1610 def execute(self, context):#{
1611 active_object = context.active_object
1612 lista = active_object.SR_data.ent_route[0].gates
1613 index = active_object.SR_data.ent_route[0].gates_index
1614 lista.remove(index)
1615 active_object.SR_data.ent_route[0].gates_index = \
1616 min(max(0, index-1), len(lista) - 1)
1617 return{'FINISHED'}
1618 #}
1619 #}
1620
1621 class SR_OBJECT_ENT_ROUTE(bpy.types.PropertyGroup):
1622 #{
1623 gates: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE_ENTRY)
1624 gates_index: bpy.props.IntProperty()
1625
1626 colour: bpy.props.FloatVectorProperty( \
1627 name="Colour",\
1628 subtype='COLOR',\
1629 min=0.0,max=1.0,\
1630 default=Vector((0.79,0.63,0.48)),\
1631 description="Route colour"\
1632 )
1633
1634 alias: bpy.props.StringProperty(\
1635 name="Alias",\
1636 default="Untitled Course")
1637
1638 @staticmethod
1639 def sr_inspector( layout, data ):
1640 #{
1641 layout.prop( data[0], 'alias' )
1642 layout.prop( data[0], 'colour' )
1643
1644 layout.label( text='Checkpoints' )
1645 layout.template_list('SR_UL_ROUTE_NODE_LIST', 'Checkpoints', \
1646 data[0], 'gates', data[0], 'gates_index', rows=5)
1647
1648 row = layout.row()
1649 row.operator( 'skaterift.new_entry', text='Add' )
1650 row.operator( 'skaterift.del_entry', text='Remove' )
1651 #}
1652 #}
1653
1654 class SR_OBJECT_PROPERTIES(bpy.types.PropertyGroup):
1655 #{
1656 ent_gate: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GATE)
1657 ent_spawn: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SPAWN)
1658 ent_route: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE)
1659
1660 ent_type: bpy.props.EnumProperty(
1661 name="Type",
1662 items=[('none', 'None', '', 0),
1663 ('ent_gate','Gate','', 1),
1664 ('ent_spawn','Spawn','', 2),
1665 ('ent_route_node', 'Route Node', '', 3 ),
1666 ('ent_route', 'Route', '', 4)],
1667 update=sr_on_type_change
1668 )
1669 #}
1670
1671 class SR_MESH_PROPERTIES(bpy.types.PropertyGroup):
1672 #{
1673 ent_gate: bpy.props.CollectionProperty(type=SR_MESH_ENT_GATE)
1674 #}
1675
1676 class SR_LIGHT_PROPERTIES(bpy.types.PropertyGroup):
1677 #{
1678 daytime: bpy.props.BoolProperty( name='Daytime' )
1679 #}
1680
1681 class SR_BONE_PROPERTIES(bpy.types.PropertyGroup):
1682 #{
1683 collider: bpy.props.EnumProperty( name='Collider Type',
1684 items=[('0','none',''),
1685 ('1','box',''),
1686 ('2','capsule','')])
1687
1688 collider_min: bpy.props.FloatVectorProperty( name='Collider Min', size=3 )
1689 collider_max: bpy.props.FloatVectorProperty( name='Collider Max', size=3 )
1690
1691 cone_constraint: bpy.props.BoolProperty( name='Cone constraint' )
1692
1693 conevx: bpy.props.FloatVectorProperty( name='vx' )
1694 conevy: bpy.props.FloatVectorProperty( name='vy' )
1695 coneva: bpy.props.FloatVectorProperty( name='va' )
1696 conet: bpy.props.FloatProperty( name='t' )
1697
1698 @staticmethod
1699 def sr_inspector( layout, data ):
1700 #{
1701 data = data[0]
1702 box = layout.box()
1703 box.prop( data, 'collider' )
1704
1705 if int(data.collider)>0:#{
1706 row = box.row()
1707 row.prop( data, 'collider_min' )
1708 row = box.row()
1709 row.prop( data, 'collider_max' )
1710 #}
1711
1712 box = layout.box()
1713 box.prop( data, 'cone_constraint' )
1714 if data.cone_constraint:#{
1715 row = box.row()
1716 row.prop( data, 'conevx' )
1717 row = box.row()
1718 row.prop( data, 'conevy' )
1719 row = box.row()
1720 row.prop( data, 'coneva' )
1721 box.prop( data, 'conet' )
1722 #}
1723 #}
1724 #}
1725
1726 class SR_MATERIAL_PROPERTIES(bpy.types.PropertyGroup):
1727 #{
1728 shader: bpy.props.EnumProperty(
1729 name="Format",
1730 items = [
1731 ('standard',"standard",''),
1732 ('standard_cutout', "standard_cutout", ''),
1733 ('terrain_blend', "terrain_blend", ''),
1734 ('vertex_blend', "vertex_blend", ''),
1735 ('water',"water",'')
1736 ])
1737
1738 surface_prop: bpy.props.EnumProperty(
1739 name="Surface Property",
1740 items = [
1741 ('0','concrete',''),
1742 ('1','wood',''),
1743 ('2','grass',''),
1744 ('3','tiles','')
1745 ])
1746
1747 collision: bpy.props.BoolProperty( \
1748 name="Collisions Enabled",\
1749 default=True,\
1750 description = "Can the player collide with this material"\
1751 )
1752 skate_surface: bpy.props.BoolProperty( \
1753 name="Skate Surface", \
1754 default=True,\
1755 description = "Should the game try to target this surface?" \
1756 )
1757 grind_surface: bpy.props.BoolProperty( \
1758 name="Grind Surface", \
1759 default=False,\
1760 description = "Grind face?" \
1761 )
1762 grow_grass: bpy.props.BoolProperty( \
1763 name="Grow Grass", \
1764 default=False,\
1765 description = "Spawn grass sprites on this surface?" \
1766 )
1767 blend_offset: bpy.props.FloatVectorProperty( \
1768 name="Blend Offset", \
1769 size=2, \
1770 default=Vector((0.5,0.0)),\
1771 description="When surface is more than 45 degrees, add this vector " +\
1772 "to the UVs" \
1773 )
1774 sand_colour: bpy.props.FloatVectorProperty( \
1775 name="Sand Colour",\
1776 subtype='COLOR',\
1777 min=0.0,max=1.0,\
1778 default=Vector((0.79,0.63,0.48)),\
1779 description="Blend to this colour near the 0 coordinate on UP axis"\
1780 )
1781 shore_colour: bpy.props.FloatVectorProperty( \
1782 name="Shore Colour",\
1783 subtype='COLOR',\
1784 min=0.0,max=1.0,\
1785 default=Vector((0.03,0.32,0.61)),\
1786 description="Water colour at the shoreline"\
1787 )
1788 ocean_colour: bpy.props.FloatVectorProperty( \
1789 name="Ocean Colour",\
1790 subtype='COLOR',\
1791 min=0.0,max=1.0,\
1792 default=Vector((0.0,0.006,0.03)),\
1793 description="Water colour in the deep bits"\
1794 )
1795 #}
1796
1797 # ---------------------------------------------------------------------------- #
1798 # #
1799 # GUI section #
1800 # #
1801 # ---------------------------------------------------------------------------- #
1802
1803 cv_view_draw_handler = None
1804 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
1805 cv_view_verts = []
1806 cv_view_colours = []
1807 cv_view_course_i = 0
1808
1809 # Draw axis alligned sphere at position with radius
1810 #
1811 def cv_draw_sphere( pos, radius, colour ):
1812 #{
1813 global cv_view_verts, cv_view_colours
1814
1815 ly = pos + Vector((0,0,radius))
1816 lx = pos + Vector((0,radius,0))
1817 lz = pos + Vector((0,0,radius))
1818
1819 pi = 3.14159265358979323846264
1820
1821 for i in range(16):
1822 #{
1823 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
1824 s = math.sin(t)
1825 c = math.cos(t)
1826
1827 py = pos + Vector((s*radius,0.0,c*radius))
1828 px = pos + Vector((s*radius,c*radius,0.0))
1829 pz = pos + Vector((0.0,s*radius,c*radius))
1830
1831 cv_view_verts += [ px, lx ]
1832 cv_view_verts += [ py, ly ]
1833 cv_view_verts += [ pz, lz ]
1834
1835 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
1836
1837 ly = py
1838 lx = px
1839 lz = pz
1840 #}
1841 cv_draw_lines()
1842 #}
1843
1844 # Draw axis alligned sphere at position with radius
1845 #
1846 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
1847 #{
1848 global cv_view_verts, cv_view_colours
1849
1850 ly = pos + tz*radius
1851 lx = pos + ty*radius
1852 lz = pos + tz*radius
1853
1854 pi = 3.14159265358979323846264
1855
1856 for i in range(16):
1857 #{
1858 t = ((i+1.0) * 1.0/16.0) * pi
1859 s = math.sin(t)
1860 c = math.cos(t)
1861
1862 s1 = math.sin(t*2.0)
1863 c1 = math.cos(t*2.0)
1864
1865 py = pos + s*tx*radius + c *tz*radius
1866 px = pos + s*tx*radius + c *ty*radius
1867 pz = pos + s1*ty*radius + c1*tz*radius
1868
1869 cv_view_verts += [ px, lx ]
1870 cv_view_verts += [ py, ly ]
1871 cv_view_verts += [ pz, lz ]
1872
1873 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
1874
1875 ly = py
1876 lx = px
1877 lz = pz
1878 #}
1879 cv_draw_lines()
1880 #}
1881
1882 # Draw transformed -1 -> 1 cube
1883 #
1884 def cv_draw_ucube( transform, colour, s=Vector((1,1,1)), o=Vector((0,0,0)) ):
1885 #{
1886 global cv_view_verts, cv_view_colours
1887
1888 a = o + -1.0 * s
1889 b = o + 1.0 * s
1890
1891 vs = [None]*8
1892 vs[0] = transform @ Vector((a[0], a[1], a[2]))
1893 vs[1] = transform @ Vector((a[0], b[1], a[2]))
1894 vs[2] = transform @ Vector((b[0], b[1], a[2]))
1895 vs[3] = transform @ Vector((b[0], a[1], a[2]))
1896 vs[4] = transform @ Vector((a[0], a[1], b[2]))
1897 vs[5] = transform @ Vector((a[0], b[1], b[2]))
1898 vs[6] = transform @ Vector((b[0], b[1], b[2]))
1899 vs[7] = transform @ Vector((b[0], a[1], b[2]))
1900
1901 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
1902 (0,4),(1,5),(2,6),(3,7)]
1903
1904 for l in indices:
1905 #{
1906 v0 = vs[l[0]]
1907 v1 = vs[l[1]]
1908 cv_view_verts += [(v0[0],v0[1],v0[2])]
1909 cv_view_verts += [(v1[0],v1[1],v1[2])]
1910 cv_view_colours += [colour, colour]
1911 #}
1912 cv_draw_lines()
1913 #}
1914
1915 # Draw line with colour
1916 #
1917 def cv_draw_line( p0, p1, colour ):
1918 #{
1919 global cv_view_verts, cv_view_colours
1920
1921 cv_view_verts += [p0,p1]
1922 cv_view_colours += [colour, colour]
1923 cv_draw_lines()
1924 #}
1925
1926 # Draw line with colour(s)
1927 #
1928 def cv_draw_line2( p0, p1, c0, c1 ):
1929 #{
1930 global cv_view_verts, cv_view_colours
1931
1932 cv_view_verts += [p0,p1]
1933 cv_view_colours += [c0,c1]
1934 cv_draw_lines()
1935 #}
1936
1937 #
1938 #
1939 def cv_tangent_basis( n, tx, ty ):
1940 #{
1941 if abs( n[0] ) >= 0.57735027:
1942 #{
1943 tx[0] = n[1]
1944 tx[1] = -n[0]
1945 tx[2] = 0.0
1946 #}
1947 else:
1948 #{
1949 tx[0] = 0.0
1950 tx[1] = n[2]
1951 tx[2] = -n[1]
1952 #}
1953
1954 tx.normalize()
1955 _ty = n.cross( tx )
1956
1957 ty[0] = _ty[0]
1958 ty[1] = _ty[1]
1959 ty[2] = _ty[2]
1960 #}
1961
1962 # Draw coloured arrow
1963 #
1964 def cv_draw_arrow( p0, p1, c0, size=0.15 ):
1965 #{
1966 global cv_view_verts, cv_view_colours
1967
1968 n = p1-p0
1969 midpt = p0 + n*0.5
1970 n.normalize()
1971
1972 tx = Vector((1,0,0))
1973 ty = Vector((1,0,0))
1974 cv_tangent_basis( n, tx, ty )
1975
1976 cv_view_verts += [p0,p1, midpt+(tx-n)*size,midpt, midpt+(-tx-n)*size,midpt ]
1977 cv_view_colours += [c0,c0,c0,c0,c0,c0]
1978 cv_draw_lines()
1979 #}
1980
1981 def cv_draw_line_dotted( p0, p1, c0, dots=10 ):
1982 #{
1983 global cv_view_verts, cv_view_colours
1984
1985 for i in range(dots):#{
1986 t0 = i/dots
1987 t1 = (i+0.25)/dots
1988
1989 p2 = p0*(1.0-t0)+p1*t0
1990 p3 = p0*(1.0-t1)+p1*t1
1991
1992 cv_view_verts += [p2,p3]
1993 cv_view_colours += [c0,c0]
1994 #}
1995 cv_draw_lines()
1996 #}
1997
1998 # Drawhandles of a bezier control point
1999 #
2000 def cv_draw_bhandle( obj, direction, colour ):
2001 #{
2002 global cv_view_verts, cv_view_colours
2003
2004 p0 = obj.location
2005 h0 = obj.matrix_world @ Vector((0,direction,0))
2006
2007 cv_view_verts += [p0]
2008 cv_view_verts += [h0]
2009 cv_view_colours += [colour,colour]
2010 cv_draw_lines()
2011 #}
2012
2013 # Draw a bezier curve (at fixed resolution 10)
2014 #
2015 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
2016 #{
2017 global cv_view_verts, cv_view_colours
2018
2019 last = p0
2020 for i in range(10):
2021 #{
2022 t = (i+1)/10
2023 a0 = 1-t
2024
2025 tt = t*t
2026 ttt = tt*t
2027 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
2028
2029 cv_view_verts += [(last[0],last[1],last[2])]
2030 cv_view_verts += [(p[0],p[1],p[2])]
2031 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
2032
2033 last = p
2034 #}
2035 cv_draw_lines()
2036 #}
2037
2038 # I think this one extends the handles of the bezier otwards......
2039 #
2040 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
2041 #{
2042 global cv_view_course_i
2043
2044 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
2045
2046 p0 = o0.matrix_world @ Vector((offs, 0,0))
2047 h0 = o0.matrix_world @ Vector((offs, s0,0))
2048 p1 = o1.matrix_world @ Vector((offs, 0,0))
2049 h1 = o1.matrix_world @ Vector((offs,-s1,0))
2050
2051 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
2052 cv_draw_lines()
2053 #}
2054
2055 # Flush the lines buffers. This is called often because god help you if you want
2056 # to do fixed, fast buffers in this catastrophic programming language.
2057 #
2058 def cv_draw_lines():
2059 #{
2060 global cv_view_shader, cv_view_verts, cv_view_colours
2061
2062 if len(cv_view_verts) < 2:
2063 return
2064
2065 lines = batch_for_shader(\
2066 cv_view_shader, 'LINES', \
2067 { "pos":cv_view_verts, "color":cv_view_colours })
2068
2069 lines.draw( cv_view_shader )
2070
2071 cv_view_verts = []
2072 cv_view_colours = []
2073 #}
2074
2075 # I dont remember what this does exactly
2076 #
2077 def cv_draw_bpath( o0,o1,c0,c1 ):
2078 #{
2079 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
2080 #}
2081
2082 # Semi circle to show the limit. and some lines
2083 #
2084 def draw_limit( obj, center, major, minor, amin, amax, colour ):
2085 #{
2086 global cv_view_verts, cv_view_colours
2087 f = 0.05
2088 ay = major*f
2089 ax = minor*f
2090
2091 for x in range(16):#{
2092 t0 = x/16
2093 t1 = (x+1)/16
2094 a0 = amin*(1.0-t0)+amax*t0
2095 a1 = amin*(1.0-t1)+amax*t1
2096
2097 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
2098 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
2099
2100 p0=obj.matrix_world @ p0
2101 p1=obj.matrix_world @ p1
2102 cv_view_verts += [p0,p1]
2103 cv_view_colours += [colour,colour]
2104
2105 if x == 0:#{
2106 cv_view_verts += [p0,center]
2107 cv_view_colours += [colour,colour]
2108 #}
2109 if x == 15:#{
2110 cv_view_verts += [p1,center]
2111 cv_view_colours += [colour,colour]
2112 #}
2113 #}
2114
2115 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
2116 cv_view_colours += [colour,colour]
2117
2118 cv_draw_lines()
2119 #}
2120
2121 # Cone and twist limit
2122 #
2123 def draw_cone_twist( center, vx, vy, va ):
2124 #{
2125 global cv_view_verts, cv_view_colours
2126 axis = vy.cross( vx )
2127 axis.normalize()
2128
2129 size = 0.12
2130
2131 cv_view_verts += [center, center+va*size]
2132 cv_view_colours += [ (1,1,1,1), (1,1,1,1) ]
2133
2134 for x in range(32):#{
2135 t0 = (x/32) * math.tau
2136 t1 = ((x+1)/32) * math.tau
2137
2138 c0 = math.cos(t0)
2139 s0 = math.sin(t0)
2140 c1 = math.cos(t1)
2141 s1 = math.sin(t1)
2142
2143 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
2144 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
2145
2146 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
2147 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
2148
2149 cv_view_verts += [center, p0, p0, p1]
2150 cv_view_colours += [ (0,0,0,0), col0, col0, col1 ]
2151 #}
2152
2153 cv_draw_lines()
2154 #}
2155
2156 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2157 #
2158 def draw_skeleton_helpers( obj ):
2159 #{
2160 global cv_view_verts, cv_view_colours
2161
2162 if obj.data.pose_position != 'REST':#{
2163 return
2164 #}
2165
2166 for bone in obj.data.bones:#{
2167 c = bone.head_local
2168 a = Vector((bone.SR_data.collider_min[0],
2169 bone.SR_data.collider_min[1],
2170 bone.SR_data.collider_min[2]))
2171 b = Vector((bone.SR_data.collider_max[0],
2172 bone.SR_data.collider_max[1],
2173 bone.SR_data.collider_max[2]))
2174
2175 if bone.SR_data.collider == '1':#{
2176 vs = [None]*8
2177 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
2178 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
2179 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
2180 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
2181 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
2182 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
2183 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
2184 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
2185
2186 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2187 (0,4),(1,5),(2,6),(3,7)]
2188
2189 for l in indices:#{
2190 v0 = vs[l[0]]
2191 v1 = vs[l[1]]
2192
2193 cv_view_verts += [(v0[0],v0[1],v0[2])]
2194 cv_view_verts += [(v1[0],v1[1],v1[2])]
2195 cv_view_colours += [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2196 #}
2197 #}
2198 elif bone.SR_data.collider == '2':#{
2199 v0 = b-a
2200 major_axis = 0
2201 largest = -1.0
2202
2203 for i in range(3):#{
2204 if abs(v0[i]) > largest:#{
2205 largest = abs(v0[i])
2206 major_axis = i
2207 #}
2208 #}
2209
2210 v1 = Vector((0,0,0))
2211 v1[major_axis] = 1.0
2212
2213 tx = Vector((0,0,0))
2214 ty = Vector((0,0,0))
2215
2216 cv_tangent_basis( v1, tx, ty )
2217 r = (abs(tx.dot( v0 )) + abs(ty.dot( v0 ))) * 0.25
2218 l = v0[ major_axis ] - r*2
2219
2220 p0 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l*-0.5 )
2221 p1 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l* 0.5 )
2222
2223 colour = [0.2,0.2,0.2,1.0]
2224 colour[major_axis] = 0.5
2225
2226 cv_draw_halfsphere( p0, -v1, ty, tx, r, colour )
2227 cv_draw_halfsphere( p1, v1, ty, tx, r, colour )
2228 cv_draw_line( p0+tx* r, p1+tx* r, colour )
2229 cv_draw_line( p0+tx*-r, p1+tx*-r, colour )
2230 cv_draw_line( p0+ty* r, p1+ty* r, colour )
2231 cv_draw_line( p0+ty*-r, p1+ty*-r, colour )
2232 #}
2233 else:#{
2234 continue
2235 #}
2236
2237 center = obj.matrix_world @ c
2238 if bone.SR_data.cone_constraint:#{
2239 vx = Vector([bone.SR_data.conevx[_] for _ in range(3)])
2240 vy = Vector([bone.SR_data.conevy[_] for _ in range(3)])
2241 va = Vector([bone.SR_data.coneva[_] for _ in range(3)])
2242 draw_cone_twist( center, vx, vy, va )
2243 #}
2244 #}
2245 #}
2246
2247 def cv_ent_gate( obj ):
2248 #{
2249 global cv_view_verts, cv_view_colours
2250
2251 if obj.type != 'MESH': return
2252
2253 mesh_data = obj.data.SR_data.ent_gate[0]
2254 data = obj.SR_data.ent_gate[0]
2255 dims = mesh_data.dimensions
2256
2257 vs = [None]*9
2258 c = Vector((0,0,dims[2]))
2259
2260 vs[0] = obj.matrix_world @ Vector((-dims[0],0.0,-dims[1]+dims[2]))
2261 vs[1] = obj.matrix_world @ Vector((-dims[0],0.0, dims[1]+dims[2]))
2262 vs[2] = obj.matrix_world @ Vector(( dims[0],0.0, dims[1]+dims[2]))
2263 vs[3] = obj.matrix_world @ Vector(( dims[0],0.0,-dims[1]+dims[2]))
2264 vs[4] = obj.matrix_world @ (c+Vector((-1,0,-2)))
2265 vs[5] = obj.matrix_world @ (c+Vector((-1,0, 2)))
2266 vs[6] = obj.matrix_world @ (c+Vector(( 1,0, 2)))
2267 vs[7] = obj.matrix_world @ (c+Vector((-1,0, 0)))
2268 vs[8] = obj.matrix_world @ (c+Vector(( 1,0, 0)))
2269
2270 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
2271
2272 for l in indices:#{
2273 v0 = vs[l[0]]
2274 v1 = vs[l[1]]
2275 cv_view_verts += [(v0[0],v0[1],v0[2])]
2276 cv_view_verts += [(v1[0],v1[1],v1[2])]
2277 cv_view_colours += [(1,1,0,1),(1,1,0,1)]
2278 #}
2279
2280 sw = (0.4,0.4,0.4,0.2)
2281 if data.target != None:
2282 cv_draw_arrow( obj.location, data.target.location, sw )
2283 #}
2284
2285 def dijkstra( graph, start_node, target_node ):
2286 #{
2287 unvisited = [_ for _ in graph]
2288 shortest_path = {}
2289 previous_nodes = {}
2290
2291 for n in unvisited:
2292 shortest_path[n] = 9999999.999999
2293 shortest_path[start_node] = 0
2294
2295 while unvisited:#{
2296 current_min_node = None
2297 for n in unvisited:#{
2298 if current_min_node == None:
2299 current_min_node = n
2300 elif shortest_path[n] < shortest_path[current_min_node]:
2301 current_min_node = n
2302 #}
2303
2304 for branch in graph[current_min_node]:#{
2305 tentative_value = shortest_path[current_min_node]
2306 tentative_value += graph[current_min_node][branch]
2307 if tentative_value < shortest_path[branch]:#{
2308 shortest_path[branch] = tentative_value
2309 previous_nodes[branch] = current_min_node
2310 #}
2311 #}
2312
2313 unvisited.remove(current_min_node)
2314 #}
2315
2316 path = []
2317 node = target_node
2318 while node != start_node:#{
2319 path.append(node)
2320
2321 if node not in previous_nodes: return None
2322 node = previous_nodes[node]
2323 #}
2324
2325 # Add the start node manually
2326 path.append(start_node)
2327 return path
2328 #}
2329
2330 def node_graph( route_nodes ):
2331 #{
2332 graph = {}
2333 for n in route_nodes:
2334 graph[n.name] = {}
2335
2336 for i in range(len(route_nodes)-1):#{
2337 for j in range(i+1, len(route_nodes)):#{
2338 ni = route_nodes[i]
2339 nj = route_nodes[j]
2340
2341 v0 = ni.location - nj.location
2342
2343 gate = None
2344
2345 if ni.SR_data.ent_type == 'ent_gate':
2346 gate = ni
2347
2348 if nj.SR_data.ent_type == 'ent_gate':#{
2349 if gate: continue
2350 gate = nj
2351 #}
2352
2353 if gate:#{
2354 v1 = gate.matrix_world.to_3x3() @ Vector((0,-1,0))
2355 if gate.SR_data.ent_gate[0].target:
2356 if v1.dot(v0) > 0.0: continue
2357 else:
2358 if v1.dot(v0) < 0.0: continue
2359 #}
2360
2361 dist = v0.magnitude
2362
2363 if dist > 25.0: continue
2364 graph[route_nodes[i].name][route_nodes[j].name] = dist
2365 graph[route_nodes[j].name][route_nodes[i].name] = dist
2366 #}
2367 #}
2368
2369 return graph
2370 #}
2371
2372 def cv_draw_route( route, route_nodes ):
2373 #{
2374 pole = Vector((0.2,0.2,20))
2375 hat = Vector((20,2.0,0.2))
2376 cc = route.SR_data.ent_route[0].colour
2377
2378 cv_draw_ucube( route.matrix_world, cc, Vector((20,1,10)) )
2379 cv_draw_ucube( route.matrix_world, cc, pole, Vector((-20,1,-10)) )
2380 cv_draw_ucube( route.matrix_world, cc, pole, Vector(( 20,1,-10)) )
2381 cv_draw_ucube( route.matrix_world, cc, hat, Vector((0,-1, 10)) )
2382 cv_draw_ucube( route.matrix_world, cc, hat, Vector((0,-1,-10)) )
2383
2384 checkpoints = route.SR_data.ent_route[0].gates
2385 graph = node_graph( route_nodes )
2386
2387 for i in range(len(checkpoints)):#{
2388 gi = checkpoints[i].target
2389 gj = checkpoints[(i+1)%len(checkpoints)].target
2390
2391 if gi:#{
2392 dest = gi.SR_data.ent_gate[0].target
2393 if dest:
2394 cv_draw_line_dotted( gi.location, dest.location, cc )
2395 gi = dest
2396 #}
2397
2398 if gi==gj: continue # error?
2399 if not gi or not gj: continue
2400
2401 path = dijkstra( graph, gj.name, gi.name )
2402
2403 if path:#{
2404 for sj in range(len(path)-1):#{
2405 o0 = bpy.data.objects[ path[sj] ]
2406 o1 = bpy.data.objects[ path[sj+1] ]
2407 cv_draw_arrow(o0.location,o1.location,cc,1.5)
2408 #}
2409 #}
2410 else:#{
2411 cv_draw_line_dotted( gi.location, gj.location, cc )
2412 #}
2413 #}
2414 #}
2415
2416 def cv_draw():
2417 #{
2418 global cv_view_shader
2419 global cv_view_verts
2420 global cv_view_colours
2421 global cv_view_course_i
2422
2423 cv_view_course_i = 0
2424 cv_view_verts = []
2425 cv_view_colours = []
2426
2427 cv_view_shader.bind()
2428 gpu.state.depth_mask_set(False)
2429 gpu.state.line_width_set(2.0)
2430 gpu.state.face_culling_set('BACK')
2431 gpu.state.depth_test_set('LESS')
2432 gpu.state.blend_set('NONE')
2433
2434 route_nodes = []
2435 routes = []
2436
2437 for obj in bpy.context.collection.objects:#{
2438 if obj.type == 'ARMATURE':#{
2439 if obj.data.pose_position == 'REST':
2440 draw_skeleton_helpers( obj )
2441 #}
2442 else:#{
2443 ent_type = obj_ent_type( obj )
2444
2445 if ent_type == 'ent_gate':#{
2446 cv_ent_gate( obj )
2447 route_nodes += [obj]
2448 #}
2449 elif ent_type == 'ent_route_node':
2450 route_nodes += [obj]
2451 elif ent_type == 'ent_route':
2452 routes += [obj]
2453 #}
2454 #}
2455
2456 #cv_draw_route_map( route_nodes )
2457 for route in routes:#{
2458 cv_draw_route( route, route_nodes )
2459 #}
2460
2461 cv_draw_lines()
2462 return
2463 #}
2464
2465 classes = [ SR_INTERFACE, SR_MATERIAL_PANEL,\
2466 SR_COLLECTION_SETTINGS, SR_SCENE_SETTINGS, \
2467 SR_COMPILE, SR_COMPILE_THIS, SR_MIRROR_BONE_X,\
2468 \
2469 SR_OBJECT_ENT_GATE, SR_MESH_ENT_GATE, SR_OBJECT_ENT_SPAWN, \
2470 SR_OBJECT_ENT_ROUTE_ENTRY, SR_UL_ROUTE_NODE_LIST, \
2471 SR_OBJECT_ENT_ROUTE, SR_OT_ROUTE_LIST_NEW_ITEM,
2472 SR_OT_ROUTE_LIST_DEL_ITEM,\
2473 \
2474 SR_OBJECT_PROPERTIES, SR_LIGHT_PROPERTIES, SR_BONE_PROPERTIES,
2475 SR_MESH_PROPERTIES, SR_MATERIAL_PROPERTIES \
2476 ]
2477
2478 def register():
2479 #{
2480 for c in classes:
2481 bpy.utils.register_class(c)
2482
2483 bpy.types.Scene.SR_data = \
2484 bpy.props.PointerProperty(type=SR_SCENE_SETTINGS)
2485 bpy.types.Collection.SR_data = \
2486 bpy.props.PointerProperty(type=SR_COLLECTION_SETTINGS)
2487
2488 bpy.types.Object.SR_data = \
2489 bpy.props.PointerProperty(type=SR_OBJECT_PROPERTIES)
2490 bpy.types.Light.SR_data = \
2491 bpy.props.PointerProperty(type=SR_LIGHT_PROPERTIES)
2492 bpy.types.Bone.SR_data = \
2493 bpy.props.PointerProperty(type=SR_BONE_PROPERTIES)
2494 bpy.types.Mesh.SR_data = \
2495 bpy.props.PointerProperty(type=SR_MESH_PROPERTIES)
2496 bpy.types.Material.SR_data = \
2497 bpy.props.PointerProperty(type=SR_MATERIAL_PROPERTIES)
2498
2499 global cv_view_draw_handler
2500 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
2501 cv_draw,(),'WINDOW','POST_VIEW')
2502 #}
2503
2504 def unregister():
2505 #{
2506 for c in classes:
2507 bpy.utils.unregister_class(c)
2508
2509 global cv_view_draw_handler
2510 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
2511 #}
2512
2513 # ---------------------------------------------------------------------------- #
2514 # #
2515 # QOI encoder #
2516 # #
2517 # ---------------------------------------------------------------------------- #
2518 # #
2519 # Transliteration of: #
2520 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
2521 # #
2522 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
2523 # SPDX-License-Identifier: MIT #
2524 # QOI - The "Quite OK Image" format for fast, lossless image compression #
2525 # #
2526 # ---------------------------------------------------------------------------- #
2527
2528 class qoi_rgba_t(Structure):
2529 #{
2530 _pack_ = 1
2531 _fields_ = [("r",c_uint8),
2532 ("g",c_uint8),
2533 ("b",c_uint8),
2534 ("a",c_uint8)]
2535 #}
2536
2537 QOI_OP_INDEX = 0x00 # 00xxxxxx
2538 QOI_OP_DIFF = 0x40 # 01xxxxxx
2539 QOI_OP_LUMA = 0x80 # 10xxxxxx
2540 QOI_OP_RUN = 0xc0 # 11xxxxxx
2541 QOI_OP_RGB = 0xfe # 11111110
2542 QOI_OP_RGBA = 0xff # 11111111
2543
2544 QOI_MASK_2 = 0xc0 # 11000000
2545
2546 def qoi_colour_hash( c ):
2547 #{
2548 return c.r*3 + c.g*5 + c.b*7 + c.a*11
2549 #}
2550
2551 def qoi_eq( a, b ):
2552 #{
2553 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
2554 #}
2555
2556 def qoi_32bit( v ):
2557 #{
2558 return bytearray([ (0xff000000 & v) >> 24, \
2559 (0x00ff0000 & v) >> 16, \
2560 (0x0000ff00 & v) >> 8, \
2561 (0x000000ff & v) ])
2562 #}
2563
2564 def qoi_encode( img ):
2565 #{
2566 data = bytearray()
2567
2568 print(F"{' ':<30}",end='\r')
2569 print(F"[QOI] Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]",end='\r')
2570
2571 index = [ qoi_rgba_t() for _ in range(64) ]
2572
2573 # Header
2574 #
2575 data.extend( bytearray(c_uint32(0x66696f71)) )
2576 data.extend( qoi_32bit( img.size[0] ) )
2577 data.extend( qoi_32bit( img.size[1] ) )
2578 data.extend( bytearray(c_uint8(4)) )
2579 data.extend( bytearray(c_uint8(0)) )
2580
2581 run = 0
2582 px_prev = qoi_rgba_t()
2583 px_prev.r = c_uint8(0)
2584 px_prev.g = c_uint8(0)
2585 px_prev.b = c_uint8(0)
2586 px_prev.a = c_uint8(255)
2587
2588 px = qoi_rgba_t()
2589 px.r = c_uint8(0)
2590 px.g = c_uint8(0)
2591 px.b = c_uint8(0)
2592 px.a = c_uint8(255)
2593
2594 px_len = img.size[0] * img.size[1]
2595 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
2596
2597 for px_pos in range( px_len ): #{
2598 idx = px_pos * img.channels
2599 nc = img.channels-1
2600
2601 px.r = paxels[idx+min(0,nc)]
2602 px.g = paxels[idx+min(1,nc)]
2603 px.b = paxels[idx+min(2,nc)]
2604 px.a = paxels[idx+min(3,nc)]
2605
2606 if qoi_eq( px, px_prev ): #{
2607 run += 1
2608
2609 if (run == 62) or (px_pos == px_len-1): #{
2610 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2611 run = 0
2612 #}
2613 #}
2614 else: #{
2615 if run > 0: #{
2616 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2617 run = 0
2618 #}
2619
2620 index_pos = qoi_colour_hash(px) % 64
2621
2622 if qoi_eq( index[index_pos], px ): #{
2623 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
2624 #}
2625 else: #{
2626 index[ index_pos ].r = px.r
2627 index[ index_pos ].g = px.g
2628 index[ index_pos ].b = px.b
2629 index[ index_pos ].a = px.a
2630
2631 if px.a == px_prev.a: #{
2632 vr = int(px.r) - int(px_prev.r)
2633 vg = int(px.g) - int(px_prev.g)
2634 vb = int(px.b) - int(px_prev.b)
2635
2636 vg_r = vr - vg
2637 vg_b = vb - vg
2638
2639 if (vr > -3) and (vr < 2) and\
2640 (vg > -3) and (vg < 2) and\
2641 (vb > -3) and (vb < 2):
2642 #{
2643 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
2644 data.extend( bytearray( c_uint8(op) ))
2645 #}
2646 elif (vg_r > -9) and (vg_r < 8) and\
2647 (vg > -33) and (vg < 32 ) and\
2648 (vg_b > -9) and (vg_b < 8):
2649 #{
2650 op = QOI_OP_LUMA | (vg+32)
2651 delta = (vg_r+8) << 4 | (vg_b + 8)
2652 data.extend( bytearray( c_uint8(op) ) )
2653 data.extend( bytearray( c_uint8(delta) ))
2654 #}
2655 else: #{
2656 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
2657 data.extend( bytearray( c_uint8(px.r) ))
2658 data.extend( bytearray( c_uint8(px.g) ))
2659 data.extend( bytearray( c_uint8(px.b) ))
2660 #}
2661 #}
2662 else: #{
2663 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
2664 data.extend( bytearray( c_uint8(px.r) ))
2665 data.extend( bytearray( c_uint8(px.g) ))
2666 data.extend( bytearray( c_uint8(px.b) ))
2667 data.extend( bytearray( c_uint8(px.a) ))
2668 #}
2669 #}
2670 #}
2671
2672 px_prev.r = px.r
2673 px_prev.g = px.g
2674 px_prev.b = px.b
2675 px_prev.a = px.a
2676 #}
2677
2678 # Padding
2679 for i in range(7):
2680 data.extend( bytearray( c_uint8(0) ))
2681 data.extend( bytearray( c_uint8(1) ))
2682 bytearray_align_to( data, 16, b'\x00' )
2683
2684 return data
2685 #}