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