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