couple fixes
[carveJwlIkooP6JGAAIwe30JlM.git] / blender_export.py
1 #
2 # =============================================================================
3 #
4 # Copyright . . . -----, ,----- ,---. .---.
5 # 2021-2022 |\ /| | / | | | | /|
6 # | \ / | +-- / +----- +---' | / |
7 # | \ / | | / | | \ | / |
8 # | \/ | | / | | \ | / |
9 # ' ' '--' [] '----- '----- ' ' '---' SOFTWARE
10 #
11 # =============================================================================
12 #
13 # Python exporter for Blender, compiles .mdl format for Skate Rift.
14 #
15 # Its really slow, sorry, I don't know how to speed it up.
16 # Also not sure why you need to put # before {} in code blocks, there is errors
17 # otherwise
18 #
19
20 import bpy, math, gpu, os
21 import cProfile
22 from ctypes import *
23 from mathutils import *
24 from gpu_extras.batch import batch_for_shader
25
26 bl_info = {
27 "name":"Skate Rift model compiler",
28 "author": "Harry Godden (hgn)",
29 "version": (0,2),
30 "blender":(3,1,0),
31 "location":"Export",
32 "descriptin":"",
33 "warning":"",
34 "wiki_url":"",
35 "category":"Import/Export",
36 }
37
38 class mdl_vert(Structure): # 48 bytes. Quite large. Could compress
39 #{ # the normals and uvs to i16s. Not an
40 _pack_ = 1 # real issue, yet.
41 _fields_ = [("co",c_float*3),
42 ("norm",c_float*3),
43 ("uv",c_float*2),
44 ("colour",c_uint8*4),
45 ("weights",c_uint16*4),
46 ("groups",c_uint8*4)]
47 #}
48
49 class mdl_submesh(Structure):
50 #{
51 _pack_ = 1
52 _fields_ = [("indice_start",c_uint32),
53 ("indice_count",c_uint32),
54 ("vertex_start",c_uint32),
55 ("vertex_count",c_uint32),
56 ("bbx",(c_float*3)*2),
57 ("material_id",c_uint32)] # index into the material array
58 #}
59
60 class mdl_texture(Structure):
61 #{
62 _pack_ = 1
63 _fields_ = [("pstr_name",c_uint32),
64 ("pack_offset",c_uint32),
65 ("pack_length",c_uint32)]
66 #}
67
68 class mdl_material(Structure):
69 #{
70 _pack_ = 1
71 _fields_ = [("pstr_name",c_uint32),
72 ("shader",c_uint32),
73 ("flags",c_uint32),
74 ("surface_prop",c_uint32),
75 ("colour",c_float*4),
76 ("colour1",c_float*4),
77 ("tex_diffuse",c_uint32),
78 ("tex_decal",c_uint32),
79 ("tex_normal",c_uint32)]
80 #}
81
82 class mdl_node(Structure):
83 #{
84 _pack_ = 1
85 _fields_ = [("co",c_float*3),
86 ( "q",c_float*4),
87 ( "s",c_float*3),
88 ("sub_uid",c_uint32), # dont use
89 ("submesh_start",c_uint32),
90 ("submesh_count",c_uint32),
91 ("classtype",c_uint32),
92 ("offset",c_uint32),
93 ("parent",c_uint32),
94 ("pstr_name",c_uint32)]
95 #}
96
97 class mdl_header(Structure):
98 #{
99 _pack_ = 1
100 _fields_ = [("identifier",c_uint32),
101 ("version",c_uint32),
102 ("file_length",c_uint32),
103 ("pad0",c_uint32),
104
105 ("node_count",c_uint32),
106 ("node_offset",c_uint32),
107
108 ("submesh_count",c_uint32),
109 ("submesh_offset",c_uint32),
110
111 ("material_count",c_uint32),
112 ("material_offset",c_uint32),
113
114 ("texture_count",c_uint32),
115 ("texture_offset",c_uint32),
116
117 ("anim_count",c_uint32),
118 ("anim_offset",c_uint32),
119
120 ("entdata_size",c_uint32),
121 ("entdata_offset",c_uint32),
122
123 ("strings_size",c_uint32),
124 ("strings_offset",c_uint32),
125
126 ("keyframe_count",c_uint32),
127 ("keyframe_offset",c_uint32),
128
129 ("vertex_count",c_uint32),
130 ("vertex_offset",c_uint32),
131
132 ("indice_count",c_uint32),
133 ("indice_offset",c_uint32),
134
135 ("pack_size",c_uint32),
136 ("pack_offset",c_uint32)]
137 #}
138
139 class mdl_animation(Structure):
140 #{
141 _pack_ = 1
142 _fields_ = [("pstr_name",c_uint32),
143 ("length",c_uint32),
144 ("rate",c_float),
145 ("offset",c_uint32)]
146 #}
147
148 class mdl_keyframe(Structure):
149 #{
150 _pack_ = 1
151 _fields_ = [("co",c_float*3),
152 ("q",c_float*4),
153 ("s",c_float*3)]
154 #}
155
156 # ---------------------------------------------------------------------------- #
157 # #
158 # Entity definitions #
159 # #
160 # ---------------------------------------------------------------------------- #
161 #
162 # ctypes _fields_ defines the data which is filled in by:
163 # def encode_obj( _, node, node_def ):
164 #
165 # gizmos get drawn into the viewport via:
166 # @staticmethod
167 # def draw_scene_helpers( obj ):
168 #
169 # editor enterface, simiraliy:
170 # @staticmethod
171 # def editor_interface( layout, obj ):
172 #
173
174 # Classtype 1
175 #
176 # Purpose: A rift. must target another gate, the target gate can not have more
177 # than one target nodes of its own.
178 #
179 class classtype_gate(Structure):
180 #{
181 _pack_ = 1
182 _fields_ = [("target",c_uint32),
183 ("dims",c_float*3)]
184
185 def encode_obj(_, node,node_def):
186 #{
187 node.classtype = 1
188
189 obj = node_def['obj']
190
191 if obj.cv_data.target != None:
192 _.target = obj.cv_data.target.cv_data.uid
193
194 if obj.type == 'MESH':
195 #{
196 _.dims[0] = obj.data.cv_data.v0[0]
197 _.dims[1] = obj.data.cv_data.v0[1]
198 _.dims[2] = obj.data.cv_data.v0[2]
199 #}
200 else:
201 #{
202 _.dims[0] = obj.cv_data.v0[0]
203 _.dims[1] = obj.cv_data.v0[1]
204 _.dims[2] = obj.cv_data.v0[2]
205 #}
206 #}
207
208 @staticmethod
209 def draw_scene_helpers( obj ):
210 #{
211 global cv_view_verts, cv_view_colours
212
213 if obj.type == 'MESH':
214 dims = obj.data.cv_data.v0
215 else:
216 dims = obj.cv_data.v0
217
218 vs = [None]*9
219 c = Vector((0,0,dims[2]))
220
221 vs[0] = obj.matrix_world @ Vector((-dims[0],0.0,-dims[1]+dims[2]))
222 vs[1] = obj.matrix_world @ Vector((-dims[0],0.0, dims[1]+dims[2]))
223 vs[2] = obj.matrix_world @ Vector(( dims[0],0.0, dims[1]+dims[2]))
224 vs[3] = obj.matrix_world @ Vector(( dims[0],0.0,-dims[1]+dims[2]))
225 vs[4] = obj.matrix_world @ (c+Vector((-1,0,-2)))
226 vs[5] = obj.matrix_world @ (c+Vector((-1,0, 2)))
227 vs[6] = obj.matrix_world @ (c+Vector(( 1,0, 2)))
228 vs[7] = obj.matrix_world @ (c+Vector((-1,0, 0)))
229 vs[8] = obj.matrix_world @ (c+Vector(( 1,0, 0)))
230
231 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
232
233 for l in indices:
234 #{
235 v0 = vs[l[0]]
236 v1 = vs[l[1]]
237 cv_view_verts += [(v0[0],v0[1],v0[2])]
238 cv_view_verts += [(v1[0],v1[1],v1[2])]
239 cv_view_colours += [(1,1,0,1),(1,1,0,1)]
240 #}
241
242 sw = (0.4,0.4,0.4,0.2)
243 if obj.cv_data.target != None:
244 cv_draw_arrow( obj.location, obj.cv_data.target.location, sw )
245 #}
246
247 @staticmethod
248 def editor_interface( layout, obj ):
249 #{
250 layout.prop( obj.cv_data, "target" )
251
252 mesh = obj.data
253 layout.label( text=F"(i) Data is stored in {mesh.name}" )
254 layout.prop( mesh.cv_data, "v0", text="Gate dimensions" )
255 #}
256 #}
257
258 # Classtype 3
259 #
260 # Purpose: player can reset here, its a safe place
261 # spawns can share the same name, the closest one will be picked
262 #
263 # when the world loads it will pick the one named 'start' first.
264 #
265 class classtype_spawn(Structure):
266 #{
267 _pack_ = 1
268 _fields_ = [("pstr_alias",c_uint32)]
269
270 def encode_obj(_, node,node_def):
271 #{
272 node.classtype = 3
273 _.pstr_alias = encoder_process_pstr( node_def['obj'].cv_data.strp )
274 #}
275
276 @staticmethod
277 def draw_scene_helpers( obj ):
278 #{
279 global cv_view_verts, cv_view_colours
280
281 vs = [None]*4
282 vs[0] = obj.matrix_world @ Vector((0,0,0))
283 vs[1] = obj.matrix_world @ Vector((0,2,0))
284 vs[2] = obj.matrix_world @ Vector((0.5,1,0))
285 vs[3] = obj.matrix_world @ Vector((-0.5,1,0))
286 indices = [(0,1),(1,2),(1,3)]
287
288 for l in indices:
289 #{
290 v0 = vs[l[0]]
291 v1 = vs[l[1]]
292
293 cv_view_verts += [(v0[0],v0[1],v0[2])]
294 cv_view_verts += [(v1[0],v1[1],v1[2])]
295 cv_view_colours += [(0,1,1,1),(0,1,1,1)]
296 #}
297
298 cv_draw_sphere( obj.location, 20.0, [0.1,0,0.9,0.4] )
299 #}
300
301 @staticmethod
302 def editor_interface( layout, obj ):
303 #{
304 layout.prop( obj.cv_data, "strp", text="Alias" )
305 #}
306 #}
307
308 # Classtype 4
309 #
310 # Purpose: Tells the game to draw water HERE, at this entity.
311 #
312 class classtype_water(Structure):
313 #{
314 _pack_ = 1
315 _fields_ = [("temp",c_uint32)]
316
317 def encode_obj(_, node,node_def):
318 #{
319 node.classtype = 4
320 # no data, spooky
321 #}
322 #}
323
324 # Classtype 8
325 #
326 # Purpose: Defines a route node and links to up to two more nodes
327 #
328 class classtype_route_node(Structure):
329 #{
330 _pack_ = 1
331 _fields_ = [("target",c_uint32),
332 ("target1",c_uint32)]
333
334 def encode_obj(_, node,node_def):
335 #{
336 node.classtype = 8
337 obj = node_def['obj']
338
339 if obj.cv_data.target != None:
340 _.target = obj.cv_data.target.cv_data.uid
341 if obj.cv_data.target1 != None:
342 _.target1 = obj.cv_data.target1.cv_data.uid
343 #}
344
345 @staticmethod
346 def draw_scene_helpers( obj ):
347 #{
348 global cv_view_verts, cv_view_colours
349
350 sw = Vector((0.4,0.4,0.4,0.2))
351 sw2 = Vector((1.5,0.2,0.2,0.0))
352 if obj.cv_data.target != None:
353 cv_draw_bpath( obj, obj.cv_data.target, sw, sw )
354 if obj.cv_data.target1 != None:
355 cv_draw_bpath( obj, obj.cv_data.target1, sw, sw )
356
357 cv_draw_bhandle( obj, 1.0, (0.8,0.8,0.8,1.0) )
358 cv_draw_bhandle( obj, -1.0, (0.4,0.4,0.4,1.0) )
359
360 p1 = obj.location+ \
361 obj.matrix_world.to_quaternion() @ Vector((0,0,-6+1.5))
362 cv_draw_arrow( obj.location, p1, sw )
363 #}
364
365 @staticmethod
366 def editor_interface( layout, obj ):
367 #{
368 layout.prop( obj.cv_data, "target", text="Left" )
369 layout.prop( obj.cv_data, "target1", text="Right" )
370 #}
371 #}
372
373 # Classtype 9
374 #
375 # Purpose: Defines a route, its 'starting' point, and the colour to use for it
376 #
377 class classtype_route(Structure):
378 #{
379 _pack_ = 1
380 _fields_ = [("id_start",c_uint32),
381 ("pstr_name",c_uint32),
382 ("colour",c_float*3)]
383
384 def encode_obj(_, node,node_def):
385 #{
386 node.classtype = 9
387 obj = node_def['obj']
388
389 _.colour[0] = obj.cv_data.colour[0]
390 _.colour[1] = obj.cv_data.colour[1]
391 _.colour[2] = obj.cv_data.colour[2]
392 _.pstr_name = encoder_process_pstr( obj.cv_data.strp )
393
394 if obj.cv_data.target != None:
395 _.id_start = obj.cv_data.target.cv_data.uid
396 #}
397
398 @staticmethod
399 def draw_scene_helpers( obj ):
400 #{
401 global cv_view_verts, cv_view_colours, cv_view_course_i
402
403 if obj.cv_data.target:
404 cv_draw_arrow( obj.location, obj.cv_data.target.location, [1,1,1,1] )
405
406 # Tries to simulate how we do it in the game
407 #
408 stack = [None]*64
409 stack_i = [0]*64
410 stack[0] = obj.cv_data.target
411 si = 1
412 loop_complete = False
413
414 while si > 0:
415 #{
416 if stack_i[si-1] == 2:
417 #{
418 si -= 1
419 continue
420
421 if si == 0: # Loop failed to complete
422 break
423 #}
424
425 node = stack[si-1]
426
427 targets = [None,None]
428 targets[0] = node.cv_data.target
429
430 if node.cv_data.classtype == 'classtype_route_node':
431 #{
432 targets[1] = node.cv_data.target1
433 #}
434
435 nextnode = targets[stack_i[si-1]]
436 stack_i[si-1] += 1
437
438 if nextnode != None: # branch
439 #{
440 if nextnode == stack[0]: # Loop completed
441 #{
442 loop_complete = True
443 break
444 #}
445
446 valid=True
447 for sj in range(si):
448 #{
449 if stack[sj] == nextnode: # invalidated path
450 #{
451 valid=False
452 break
453 #}
454 #}
455
456 if valid:
457 #{
458 stack_i[si] = 0
459 stack[si] = nextnode
460 si += 1
461 continue
462 #}
463 #}
464 #}
465
466 if loop_complete:
467 #{
468 cc = Vector((obj.cv_data.colour[0],\
469 obj.cv_data.colour[1],\
470 obj.cv_data.colour[2],\
471 1.0))
472
473 for sj in range(si):
474 #{
475 sk = (sj+1)%si
476
477 if stack[sj].cv_data.classtype == 'classtype_gate' and \
478 stack[sk].cv_data.classtype == 'classtype_gate':
479 #{
480 dist = (stack[sj].location-stack[sk].location).magnitude
481 cv_draw_sbpath( stack[sj], stack[sk], cc*0.4, cc, dist, dist )
482 #}
483 else:
484 cv_draw_bpath( stack[sj], stack[sk], cc, cc )
485 #}
486
487 cv_view_course_i += 1
488 #}
489 #}
490
491 @staticmethod
492 def editor_interface( layout, obj ):
493 #{
494 layout.prop( obj.cv_data, "target", text="'Start' from" )
495 layout.prop( obj.cv_data, "colour" )
496 layout.prop( obj.cv_data, "strp", text="Name" )
497 #}
498 #}
499
500 # Classtype 12
501 #
502 # Purpose: links an mesh node to a type 11
503 #
504 class classtype_skin(Structure):
505 #{
506 _pack_ = 1
507 _fields_ = [("skeleton",c_uint32)]
508
509 def encode_obj(_, node,node_def):
510 #{
511 node.classtype = 12
512
513 armature_def = node_def['linked_armature']
514 _.skeleton = armature_def['obj'].cv_data.uid
515 #}
516 #}
517
518 # Classtype 11
519 #
520 # Purpose: defines the allocation requirements for a skeleton
521 #
522 class classtype_skeleton(Structure):
523 #{
524 _pack_ = 1
525 _fields_ = [("channels",c_uint32),
526 ("ik_count",c_uint32),
527 ("collider_count",c_uint32),
528 ("anim_start",c_uint32),
529 ("anim_count",c_uint32)]
530
531 def encode_obj(_, node,node_def):
532 #{
533 node.classtype = 11
534
535 _.channels = len( node_def['bones'] )
536 _.ik_count = node_def['ik_count']
537 _.collider_count = node_def['collider_count']
538 _.anim_start = node_def['anim_start']
539 _.anim_count = node_def['anim_count']
540 #}
541 #}
542
543
544 # Classtype 10
545 #
546 # Purpose: intrinsic bone type, stores collision information and limits too
547 #
548 class classtype_bone(Structure):
549 #{
550 _pack_ = 1
551 _fields_ = [("deform",c_uint32),
552 ("ik_target",c_uint32),
553 ("ik_pole",c_uint32),
554 ("collider",c_uint32),
555 ("use_limits",c_uint32),
556 ("angle_limits",(c_float*3)*2),
557 ("hitbox",(c_float*3)*2)]
558
559 def encode_obj(_, node,node_def):
560 #{
561 node.classtype = 10
562
563 armature_def = node_def['linked_armature']
564 obj = node_def['bone']
565
566 _.deform = node_def['deform']
567
568 if 'ik_target' in node_def:
569 #{
570 _.ik_target = armature_def['bones'].index( node_def['ik_target'] )
571 _.ik_pole = armature_def['bones'].index( node_def['ik_pole'] )
572 #}
573
574 # For ragdolls
575 #
576 if obj.cv_data.collider:
577 #{
578 _.collider = 1
579 _.hitbox[0][0] = obj.cv_data.v0[0]
580 _.hitbox[0][1] = obj.cv_data.v0[2]
581 _.hitbox[0][2] = -obj.cv_data.v1[1]
582 _.hitbox[1][0] = obj.cv_data.v1[0]
583 _.hitbox[1][1] = obj.cv_data.v1[2]
584 _.hitbox[1][2] = -obj.cv_data.v0[1]
585 #}
586
587 if obj.cv_data.con0:
588 #{
589 _.use_limits = 1
590 _.angle_limits[0][0] = obj.cv_data.mins[0]
591 _.angle_limits[0][1] = obj.cv_data.mins[2]
592 _.angle_limits[0][2] = -obj.cv_data.maxs[1]
593 _.angle_limits[1][0] = obj.cv_data.maxs[0]
594 _.angle_limits[1][1] = obj.cv_data.maxs[2]
595 _.angle_limits[1][2] = -obj.cv_data.mins[1]
596 #}
597 #}
598 #}
599
600 # Classtype 100
601 #
602 # Purpose: sends a signal to another entity
603 #
604 class classtype_trigger(Structure):
605 #{
606 _pack_ = 1
607 _fields_ = [("target",c_uint32)]
608
609 def encode_obj(_, node,node_def ):
610 #{
611 node.classtype = 100
612 if node_def['obj'].cv_data.target:
613 _.target = node_def['obj'].cv_data.target.cv_data.uid
614 #}
615
616 @staticmethod
617 def draw_scene_helpers( obj ):
618 #{
619 global cv_view_verts, cv_view_colours
620 cv_draw_ucube( obj.matrix_world, [0,1,0,1] )
621
622 if obj.cv_data.target:
623 cv_draw_arrow( obj.location, obj.cv_data.target.location, [1,1,1,1] )
624 #}
625
626 @staticmethod
627 def editor_interface( layout, obj ):
628 #{
629 layout.prop( obj.cv_data, "target", text="Triggers" )
630 #}
631 #}
632
633 # Classtype 101
634 #
635 # Purpose: Gives the player an achievement.
636 # No cheating! You shouldn't use this entity anyway, since only ME can
637 # add achievements to the steam ;)
638 #
639 class classtype_logic_achievement(Structure):
640 #{
641 _pack_ = 1
642 _fields_ = [("pstr_name",c_uint32)]
643
644 def encode_obj(_, node,node_def ):
645 #{
646 node.classtype = 101
647 _.pstr_name = encoder_process_pstr( node_def['obj'].cv_data.strp )
648 #}
649
650 @staticmethod
651 def editor_interface( layout, obj ):
652 #{
653 layout.prop( obj.cv_data, "strp", text="Achievement ID" )
654 #}
655 #}
656
657 # Classtype 102
658 #
659 # Purpose: sends a signal to another entity
660 #
661 class classtype_logic_relay(Structure):
662 #{
663 _pack_ = 1
664 _fields_ = [("targets",c_uint32*4)]
665
666 def encode_obj(_, node,node_def ):
667 #{
668 node.classtype = 102
669 obj = node_def['obj']
670 if obj.cv_data.target:
671 _.targets[0] = obj.cv_data.target.cv_data.uid
672 if obj.cv_data.target1:
673 _.targets[1] = obj.cv_data.target1.cv_data.uid
674 if obj.cv_data.target2:
675 _.targets[2] = obj.cv_data.target2.cv_data.uid
676 if obj.cv_data.target3:
677 _.targets[3] = obj.cv_data.target3.cv_data.uid
678 #}
679
680 @staticmethod
681 def draw_scene_helpers( obj ):
682 #{
683 global cv_view_verts, cv_view_colours
684
685 if obj.cv_data.target:
686 cv_draw_arrow( obj.location, obj.cv_data.target.location, [1,1,1,1] )
687 if obj.cv_data.target1:
688 cv_draw_arrow( obj.location, obj.cv_data.target1.location, [1,1,1,1] )
689 if obj.cv_data.target2:
690 cv_draw_arrow( obj.location, obj.cv_data.target2.location, [1,1,1,1] )
691 if obj.cv_data.target3:
692 cv_draw_arrow( obj.location, obj.cv_data.target3.location, [1,1,1,1] )
693 #}
694
695 @staticmethod
696 def editor_interface( layout, obj ):
697 #{
698 layout.prop( obj.cv_data, "target", text="Triggers" )
699 layout.prop( obj.cv_data, "target1", text="Triggers" )
700 layout.prop( obj.cv_data, "target2", text="Triggers" )
701 layout.prop( obj.cv_data, "target3", text="Triggers" )
702 #}
703 #}
704
705 # Classtype 14
706 #
707 # Purpose: Plays some audio (44100hz .ogg vorbis only)
708 # NOTE: There is a 32mb limit on the audio buffer, world audio is
709 # decompressed and stored in signed 16 bit integers (2 bytes)
710 # per sample.
711 #
712 # volume: not used if has 3D flag
713 # flags:
714 # AUDIO_FLAG_LOOP 0x1
715 # AUDIO_FLAG_ONESHOT 0x2 (DONT USE THIS, it breaks semaphores)
716 # AUDIO_FLAG_SPACIAL_3D 0x4 (Probably what you want)
717 # AUDIO_FLAG_AUTO_START 0x8 (Play when the world starts)
718 # ......
719 # the rest are just internal flags, only use the above 3.
720 #
721 class classtype_audio(Structure):
722 #{
723 _pack_ = 1
724 _fields_ = [("pstr_file",c_uint32),
725 ("flags",c_uint32),
726 ("volume",c_float)]
727
728 def encode_obj(_, node,node_def ):
729 #{
730 node.classtype = 14
731
732 obj = node_def['obj']
733
734 _.pstr_file = encoder_process_pstr( obj.cv_data.strp )
735
736 flags = 0x00
737 if obj.cv_data.bp0: flags |= 0x1
738 if obj.cv_data.bp1: flags |= 0x4
739 if obj.cv_data.bp2: flags |= 0x8
740
741 _.flags = flags
742 _.volume = obj.cv_data.fltp
743 #}
744
745 @staticmethod
746 def editor_interface( layout, obj ):
747 #{
748 layout.prop( obj.cv_data, "strp" )
749
750 layout.prop( obj.cv_data, "bp0", text = "Looping" )
751 layout.prop( obj.cv_data, "bp1", text = "3D Audio" )
752 layout.prop( obj.cv_data, "bp2", text = "Auto Start" )
753 #}
754
755 @staticmethod
756 def draw_scene_helpers( obj ):
757 #{
758 global cv_view_verts, cv_view_colours
759
760 cv_draw_sphere( obj.location, obj.scale[0], [1,1,0,1] )
761 #}
762 #}
763
764 class classtype_spawn_link(Structure):
765 #{
766 _pack_ = 1
767 _fields_ = [("connections",c_uint32*4)]
768
769 def encode_obj(_, node,node_def ):
770 #{
771 node.classtype = 0
772 #}
773
774 @staticmethod
775 def editor_interface( layout, obj ):
776 #{
777 pass
778 #}
779
780 @staticmethod
781 def draw_scene_helpers( obj ):
782 #{
783 global cv_view_verts, cv_view_colours
784
785 count = 0
786
787 for obj1 in bpy.context.collection.objects:
788 #{
789 if (obj1.cv_data.classtype != 'classtype_spawn_link') and \
790 (obj1.cv_data.classtype != 'classtype_spawn') :
791 continue
792
793 if (obj1.location - obj.location).length < 40.0:
794 #{
795 cv_draw_line( obj.location, obj1.location, [1,1,1,1] )
796 count +=1
797 #}
798
799 if count == 4:
800 break
801 #}
802
803 cv_draw_sphere( obj.location, 20.0, [0.5,0,0.2,0.4] )
804 #}
805 #}
806
807 # ---------------------------------------------------------------------------- #
808 # #
809 # Compiler section #
810 # #
811 # ---------------------------------------------------------------------------- #
812
813 # Current encoder state
814 #
815 g_encoder = None
816
817 # Reset encoder
818 #
819 def encoder_init( collection ):
820 #{
821 global g_encoder
822
823 g_encoder = \
824 {
825 # The actual file header
826 #
827 'header': mdl_header(),
828
829 # Options
830 #
831 'pack_textures': collection.cv_data.pack_textures,
832
833 # Compiled data chunks (each can be read optionally by the client)
834 #
835 'data':
836 {
837 #1---------------------------------
838 'node': [], # Metadata 'chunk'
839 'submesh': [],
840 'material': [],
841 'texture': [],
842 'anim': [],
843 'entdata': bytearray(), # variable width
844 'strings': bytearray(), # .
845 #2---------------------------------
846 'keyframe': [], # Animations
847 #3---------------------------------
848 'vertex': [], # Mesh data
849 'indice': [],
850 #4---------------------------------
851 'pack': bytearray() # Other generic packed data
852 },
853
854 # All objects of the model in their final heirachy
855 #
856 "uid_count": 1,
857 "scene_graph":{},
858 "graph_lookup":{},
859
860 # Allows us to reuse definitions
861 #
862 'string_cache':{},
863 'mesh_cache': {},
864 'material_cache': {},
865 'texture_cache': {}
866 }
867
868 g_encoder['header'].identifier = 0xABCD0000
869 g_encoder['header'].version = 1
870
871 # Add fake NoneID material and texture
872 #
873 none_material = mdl_material()
874 none_material.pstr_name = encoder_process_pstr( "" )
875 none_material.texture_id = 0
876
877 none_texture = mdl_texture()
878 none_texture.pstr_name = encoder_process_pstr( "" )
879 none_texture.pack_offset = 0
880 none_texture.pack_length = 0
881
882 g_encoder['data']['material'] += [none_material]
883 g_encoder['data']['texture'] += [none_texture]
884
885 g_encoder['data']['pack'].extend( b'datapack\0\0\0\0\0\0\0\0' )
886
887 # Add root node
888 #
889 root = mdl_node()
890 root.co[0] = 0
891 root.co[1] = 0
892 root.co[2] = 0
893 root.q[0] = 0
894 root.q[1] = 0
895 root.q[2] = 0
896 root.q[3] = 1
897 root.s[0] = 1
898 root.s[1] = 1
899 root.s[2] = 1
900 root.pstr_name = encoder_process_pstr('')
901 root.submesh_start = 0
902 root.submesh_count = 0
903 root.offset = 0
904 root.classtype = 0
905 root.parent = 0xffffffff
906
907 g_encoder['data']['node'] += [root]
908 #}
909
910
911 # fill with 0x00 until a multiple of align. Returns how many bytes it added
912 #
913 def bytearray_align_to( buffer, align, offset=0 ):
914 #{
915 count = 0
916
917 while ((len(buffer)+offset) % align) != 0:
918 #{
919 buffer.extend( b'\0' )
920 count += 1
921 #}
922
923 return count
924 #}
925
926 # Add a string to the string buffer except if it already exists there then we
927 # just return its ID.
928 #
929 def encoder_process_pstr( s ):
930 #{
931 global g_encoder
932
933 cache = g_encoder['string_cache']
934
935 if s in cache:
936 return cache[s]
937
938 cache[s] = len( g_encoder['data']['strings'] )
939
940 buffer = g_encoder['data']['strings']
941 buffer.extend( s.encode('utf-8') )
942 buffer.extend( b'\0' )
943
944 bytearray_align_to( buffer, 4 )
945 return cache[s]
946 #}
947
948 def get_texture_resource_name( img ):
949 #{
950 return os.path.splitext( img.name )[0]
951 #}
952
953 # Pack a texture
954 #
955 def encoder_process_texture( img ):
956 #{
957 global g_encoder
958
959 if img == None:
960 return 0
961
962 cache = g_encoder['texture_cache']
963 buffer = g_encoder['data']['texture']
964 pack = g_encoder['data']['pack']
965
966 name = get_texture_resource_name( img )
967
968 if name in cache:
969 return cache[name]
970
971 cache[name] = len( buffer )
972
973 tex = mdl_texture()
974 tex.pstr_name = encoder_process_pstr( name )
975
976 if g_encoder['pack_textures']:
977 #{
978 tex.pack_offset = len( pack )
979 pack.extend( qoi_encode( img ) )
980 tex.pack_length = len( pack ) - tex.pack_offset
981 #}
982 else:
983 tex.pack_offset = 0
984
985 buffer += [ tex ]
986 return cache[name]
987 #}
988
989 def material_tex_image(v):
990 #{
991 return {
992 "Image Texture":
993 {
994 "image": F"{v}"
995 }
996 }
997 #}
998
999 cxr_graph_mapping = \
1000 {
1001 # Default shader setup
1002 "Principled BSDF":
1003 {
1004 "Base Color":
1005 {
1006 "Image Texture":
1007 {
1008 "image": "tex_diffuse"
1009 },
1010 "Mix":
1011 {
1012 "Color1": material_tex_image("tex_diffuse"),
1013 "Color2": material_tex_image("tex_decal")
1014 },
1015 },
1016 "Normal":
1017 {
1018 "Normal Map":
1019 {
1020 "Color": material_tex_image("tex_normal")
1021 }
1022 }
1023 }
1024 }
1025
1026 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
1027 #
1028 def material_info(mat):
1029 #{
1030 info = {}
1031
1032 # Using the cv_graph_mapping as a reference, go through the shader
1033 # graph and gather all $props from it.
1034 #
1035 def _graph_read( node_def, node=None, depth=0 ):
1036 #{
1037 nonlocal mat
1038 nonlocal info
1039
1040 # Find rootnodes
1041 #
1042 if node == None:
1043 #{
1044 _graph_read.extracted = []
1045
1046 for node_idname in node_def:
1047 #{
1048 for n in mat.node_tree.nodes:
1049 #{
1050 if n.name == node_idname:
1051 #{
1052 node_def = node_def[node_idname]
1053 node = n
1054 break
1055 #}
1056 #}
1057 #}
1058 #}
1059
1060 for link in node_def:
1061 #{
1062 link_def = node_def[link]
1063
1064 if isinstance( link_def, dict ):
1065 #{
1066 node_link = node.inputs[link]
1067
1068 if node_link.is_linked:
1069 #{
1070 # look for definitions for the connected node type
1071 #
1072 from_node = node_link.links[0].from_node
1073
1074 node_name = from_node.name.split('.')[0]
1075 if node_name in link_def:
1076 #{
1077 from_node_def = link_def[ node_name ]
1078
1079 _graph_read( from_node_def, from_node, depth+1 )
1080 #}
1081
1082 # No definition! :(
1083 # TODO: Make a warning for this?
1084 #}
1085 else:
1086 #{
1087 if "default" in link_def:
1088 #{
1089 prop = link_def['default']
1090 info[prop] = node_link.default_value
1091 #}
1092 #}
1093 #}
1094 else:
1095 #{
1096 prop = link_def
1097 info[prop] = getattr( node, link )
1098 #}
1099 #}
1100 #}
1101
1102 _graph_read( cxr_graph_mapping )
1103 return info
1104 #}
1105
1106 # Add a material to the material buffer. Returns 0 (None ID) if invalid
1107 #
1108 def encoder_process_material( mat ):
1109 #{
1110 global g_encoder
1111
1112 if mat == None:
1113 return 0
1114
1115 cache = g_encoder['material_cache']
1116 buffer = g_encoder['data']['material']
1117
1118 if mat.name in cache:
1119 return cache[mat.name]
1120
1121 cache[mat.name] = len( buffer )
1122
1123 dest = mdl_material()
1124 dest.pstr_name = encoder_process_pstr( mat.name )
1125
1126 flags = 0x00
1127 if mat.cv_data.skate_surface: flags |= 0x1
1128 if mat.cv_data.collision: flags |= 0x2
1129 if mat.cv_data.grow_grass: flags |= 0x4
1130 dest.flags = flags
1131
1132 if mat.cv_data.surface_prop == 'concrete': dest.surface_prop = 0
1133 if mat.cv_data.surface_prop == 'wood': dest.surface_prop = 1
1134 if mat.cv_data.surface_prop == 'grass': dest.surface_prop = 2
1135
1136 if mat.cv_data.shader == 'standard': dest.shader = 0
1137 if mat.cv_data.shader == 'standard_cutout': dest.shader = 1
1138 if mat.cv_data.shader == 'terrain_blend':
1139 #{
1140 dest.shader = 2
1141
1142 dest.colour[0] = pow( mat.cv_data.sand_colour[0], 1.0/2.2 )
1143 dest.colour[1] = pow( mat.cv_data.sand_colour[1], 1.0/2.2 )
1144 dest.colour[2] = pow( mat.cv_data.sand_colour[2], 1.0/2.2 )
1145 dest.colour[3] = 1.0
1146
1147 dest.colour1[0] = mat.cv_data.blend_offset[0]
1148 dest.colour1[1] = mat.cv_data.blend_offset[1]
1149 #}
1150
1151 if mat.cv_data.shader == 'vertex_blend':
1152 #{
1153 dest.shader = 3
1154
1155 dest.colour1[0] = mat.cv_data.blend_offset[0]
1156 dest.colour1[1] = mat.cv_data.blend_offset[1]
1157 #}
1158
1159 if mat.cv_data.shader == 'water':
1160 #{
1161 dest.shader = 4
1162
1163 dest.colour[0] = pow( mat.cv_data.shore_colour[0], 1.0/2.2 )
1164 dest.colour[1] = pow( mat.cv_data.shore_colour[1], 1.0/2.2 )
1165 dest.colour[2] = pow( mat.cv_data.shore_colour[2], 1.0/2.2 )
1166 dest.colour[3] = 1.0
1167 dest.colour1[0] = pow( mat.cv_data.ocean_colour[0], 1.0/2.2 )
1168 dest.colour1[1] = pow( mat.cv_data.ocean_colour[1], 1.0/2.2 )
1169 dest.colour1[2] = pow( mat.cv_data.ocean_colour[2], 1.0/2.2 )
1170 dest.colour1[3] = 1.0
1171 #}
1172
1173 inf = material_info( mat )
1174
1175 if mat.cv_data.shader == 'standard' or \
1176 mat.cv_data.shader == 'standard_cutout' or \
1177 mat.cv_data.shader == 'terrain_blend' or \
1178 mat.cv_data.shader == 'vertex_blend':
1179 #{
1180 if 'tex_diffuse' in inf:
1181 dest.tex_diffuse = encoder_process_texture(inf['tex_diffuse'])
1182 #}
1183
1184 buffer += [dest]
1185 return cache[mat.name]
1186 #}
1187
1188 # Create a tree structure containing all the objects in the collection
1189 #
1190 def encoder_build_scene_graph( collection ):
1191 #{
1192 global g_encoder
1193
1194 print( " creating scene graph" )
1195
1196 # initialize root
1197 #
1198 graph = g_encoder['scene_graph']
1199 graph_lookup = g_encoder['graph_lookup']
1200 graph["obj"] = None
1201 graph["depth"] = 0
1202 graph["children"] = []
1203 graph["uid"] = 0
1204 graph["parent"] = None
1205
1206 def _new_uid():
1207 #{
1208 global g_encoder
1209 uid = g_encoder['uid_count']
1210 g_encoder['uid_count'] += 1
1211 return uid
1212 #}
1213
1214 for obj in collection.all_objects:
1215 #{
1216 if obj.parent: continue
1217
1218 def _extend( p, n, d ):
1219 #{
1220 uid = _new_uid()
1221 tree = {}
1222 tree["uid"] = uid
1223 tree["children"] = []
1224 tree["depth"] = d
1225 tree["obj"] = n
1226 tree["parent"] = p
1227 n.cv_data.uid = uid
1228
1229 # Descend into amature
1230 #
1231 if n.type == 'ARMATURE':
1232 #{
1233 tree["bones"] = [None] # None is the root transform
1234 tree["ik_count"] = 0
1235 tree["collider_count"] = 0
1236
1237 # Here also collects some information about constraints, ik and
1238 # counts colliders for the armature.
1239 #
1240 def _extendb( p, n, d ):
1241 #{
1242 nonlocal tree
1243
1244 btree = {}
1245 btree["bone"] = n
1246 btree["linked_armature"] = tree
1247 btree["uid"] = _new_uid()
1248 btree["children"] = []
1249 btree["depth"] = d
1250 btree["parent"] = p
1251 tree["bones"] += [n.name]
1252
1253 for c in n.children:
1254 #{
1255 _extendb( btree, c, d+1 )
1256 #}
1257
1258 for c in tree['obj'].pose.bones[n.name].constraints:
1259 #{
1260 if c.type == 'IK':
1261 #{
1262 btree["ik_target"] = c.subtarget
1263 btree["ik_pole"] = c.pole_subtarget
1264 tree["ik_count"] += 1
1265 #}
1266 #}
1267
1268 if n.cv_data.collider:
1269 tree['collider_count'] += 1
1270
1271 btree['deform'] = n.use_deform
1272 p['children'] += [btree]
1273 #}
1274
1275 for b in n.data.bones:
1276 if not b.parent:
1277 _extendb( tree, b, d+1 )
1278 #}
1279
1280 # Recurse into children of this object
1281 #
1282 for obj1 in n.children:
1283 #{
1284 nonlocal collection
1285 for c1 in obj1.users_collection:
1286 #{
1287 if c1 == collection:
1288 #{
1289 _extend( tree, obj1, d+1 )
1290 break
1291 #}
1292 #}
1293 #}
1294
1295 p["children"] += [tree]
1296 graph_lookup[n] = tree
1297
1298 #}
1299
1300 _extend( graph, obj, 1 )
1301
1302 #}
1303 #}
1304
1305
1306 # Kind of a useless thing i made but it looks cool and adds complexity!!1
1307 #
1308 def encoder_graph_iterator( root ):
1309 #{
1310 for c in root['children']:
1311 #{
1312 yield c
1313 yield from encoder_graph_iterator(c)
1314 #}
1315 #}
1316
1317
1318 # Push a vertex into the model file, or return a cached index (c_uint32)
1319 #
1320 def encoder_vertex_push( vertex_reference, co,norm,uv,colour,groups,weights ):
1321 #{
1322 global g_encoder
1323 buffer = g_encoder['data']['vertex']
1324
1325 TOLERENCE = 4
1326 m = float(10**TOLERENCE)
1327
1328 # Would be nice to know if this can be done faster than it currently runs,
1329 # its quite slow.
1330 #
1331 key = (int(co[0]*m+0.5),
1332 int(co[1]*m+0.5),
1333 int(co[2]*m+0.5),
1334 int(norm[0]*m+0.5),
1335 int(norm[1]*m+0.5),
1336 int(norm[2]*m+0.5),
1337 int(uv[0]*m+0.5),
1338 int(uv[1]*m+0.5),
1339 colour[0]*m+0.5, # these guys are already quantized
1340 colour[1]*m+0.5, # .
1341 colour[2]*m+0.5, # .
1342 colour[3]*m+0.5, # .
1343 weights[0]*m+0.5, # v
1344 weights[1]*m+0.5,
1345 weights[2]*m+0.5,
1346 weights[3]*m+0.5,
1347 groups[0]*m+0.5,
1348 groups[1]*m+0.5,
1349 groups[2]*m+0.5,
1350 groups[3]*m+0.5)
1351
1352 if key in vertex_reference:
1353 return vertex_reference[key]
1354 else:
1355 #{
1356 index = c_uint32( len(vertex_reference) )
1357 vertex_reference[key] = index
1358
1359 v = mdl_vert()
1360 v.co[0] = co[0]
1361 v.co[1] = co[2]
1362 v.co[2] = -co[1]
1363 v.norm[0] = norm[0]
1364 v.norm[1] = norm[2]
1365 v.norm[2] = -norm[1]
1366 v.uv[0] = uv[0]
1367 v.uv[1] = uv[1]
1368 v.colour[0] = colour[0]
1369 v.colour[1] = colour[1]
1370 v.colour[2] = colour[2]
1371 v.colour[3] = colour[3]
1372 v.weights[0] = weights[0]
1373 v.weights[1] = weights[1]
1374 v.weights[2] = weights[2]
1375 v.weights[3] = weights[3]
1376 v.groups[0] = groups[0]
1377 v.groups[1] = groups[1]
1378 v.groups[2] = groups[2]
1379 v.groups[3] = groups[3]
1380
1381 buffer += [v]
1382 return index
1383 #}
1384 #}
1385
1386
1387 # Compile a mesh (or use one from the cache) onto node, based on node_def
1388 # No return value
1389 #
1390 def encoder_compile_mesh( node, node_def ):
1391 #{
1392 global g_encoder
1393
1394 graph = g_encoder['scene_graph']
1395 graph_lookup = g_encoder['graph_lookup']
1396 mesh_cache = g_encoder['mesh_cache']
1397 obj = node_def['obj']
1398 armature_def = None
1399 can_use_cache = True
1400
1401 # Check for modifiers that typically change the data per-instance
1402 # there is no well defined rule for the choices here, its just what i've
1403 # needed while producing the game.
1404 #
1405 # It may be possible to detect these cases automatically.
1406 #
1407 for mod in obj.modifiers:
1408 #{
1409 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
1410 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
1411 mod.type == 'ARRAY':
1412 #{
1413 can_use_cache = False
1414 #}
1415
1416 if mod.type == 'ARMATURE':
1417 armature_def = graph_lookup[mod.object]
1418
1419 # Check the cache first
1420 #
1421 if can_use_cache and (obj.data.name in mesh_cache):
1422 #{
1423 ref = mesh_cache[obj.data.name]
1424 node.submesh_start = ref.submesh_start
1425 node.submesh_count = ref.submesh_count
1426 return
1427 #}
1428
1429 # Compile a whole new mesh
1430 #
1431 node.submesh_start = len( g_encoder['data']['submesh'] )
1432 node.submesh_count = 0
1433
1434 dgraph = bpy.context.evaluated_depsgraph_get()
1435 data = obj.evaluated_get(dgraph).data
1436 data.calc_loop_triangles()
1437 data.calc_normals_split()
1438
1439 # Mesh is split into submeshes based on their material
1440 #
1441 mat_list = data.materials if len(data.materials) > 0 else [None]
1442 for material_id, mat in enumerate(mat_list):
1443 #{
1444 mref = {}
1445
1446 sm = mdl_submesh()
1447 sm.indice_start = len( g_encoder['data']['indice'] )
1448 sm.vertex_start = len( g_encoder['data']['vertex'] )
1449 sm.vertex_count = 0
1450 sm.indice_count = 0
1451 sm.material_id = encoder_process_material( mat )
1452
1453 for i in range(3):
1454 #{
1455 sm.bbx[0][i] = 999999
1456 sm.bbx[1][i] = -999999
1457 #}
1458
1459 # Keep a reference to very very very similar vertices
1460 #
1461 vertex_reference = {}
1462
1463 # Write the vertex / indice data
1464 #
1465 for tri_index, tri in enumerate(data.loop_triangles):
1466 #{
1467 if tri.material_index != material_id:
1468 continue
1469
1470 for j in range(3):
1471 #{
1472 vert = data.vertices[tri.vertices[j]]
1473 li = tri.loops[j]
1474 vi = data.loops[li].vertex_index
1475
1476 # Gather vertex information
1477 #
1478 co = vert.co
1479 norm = data.loops[li].normal
1480 uv = (0,0)
1481 colour = (255,255,255,255)
1482 groups = [0,0,0,0]
1483 weights = [0,0,0,0]
1484
1485 # Uvs
1486 #
1487 if data.uv_layers:
1488 uv = data.uv_layers.active.data[li].uv
1489
1490 # Vertex Colours
1491 #
1492 if data.vertex_colors:
1493 #{
1494 colour = data.vertex_colors.active.data[li].color
1495 colour = (int(colour[0]*255.0),\
1496 int(colour[1]*255.0),\
1497 int(colour[2]*255.0),\
1498 int(colour[3]*255.0))
1499 #}
1500
1501 # Weight groups: truncates to the 3 with the most influence. The
1502 # fourth bone ID is never used by the shader so it is
1503 # always 0
1504 #
1505 if armature_def:
1506 #{
1507 src_groups = [_ for _ in data.vertices[vi].groups \
1508 if obj.vertex_groups[_.group].name in \
1509 armature_def['bones']]
1510
1511 weight_groups = sorted( src_groups, key = \
1512 lambda a: a.weight, reverse=True )
1513 tot = 0.0
1514 for ml in range(3):
1515 #{
1516 if len(weight_groups) > ml:
1517 #{
1518 g = weight_groups[ml]
1519 name = obj.vertex_groups[g.group].name
1520 weight = g.weight
1521
1522 weights[ml] = weight
1523 groups[ml] = armature_def['bones'].index(name)
1524 tot += weight
1525 #}
1526 #}
1527
1528 if len(weight_groups) > 0:
1529 #{
1530 inv_norm = (1.0/tot) * 65535.0
1531 for ml in range(3):
1532 #{
1533 weights[ml] = int( weights[ml] * inv_norm )
1534 weights[ml] = min( weights[ml], 65535 )
1535 weights[ml] = max( weights[ml], 0 )
1536 #}
1537 #}
1538
1539 # Add vertex and expand bound box
1540 #
1541 index = encoder_vertex_push( vertex_reference, co, \
1542 norm, \
1543 uv, \
1544 colour, \
1545 groups, \
1546 weights )
1547 g_encoder['data']['indice'] += [index]
1548 #}
1549 #}
1550
1551 # How many unique verts did we add in total
1552 #
1553 sm.vertex_count = len(g_encoder['data']['vertex']) - sm.vertex_start
1554 sm.indice_count = len(g_encoder['data']['indice']) - sm.indice_start
1555
1556 # Make sure bounding box isn't -inf -> inf if no vertices
1557 #
1558 if sm.vertex_count == 0:
1559 for j in range(2):
1560 for i in range(3):
1561 sm.bbx[j][i] = 0
1562 else:
1563 #{
1564 for j in range(sm.vertex_count):
1565 #{
1566 vert = g_encoder['data']['vertex'][ sm.vertex_start + j ]
1567
1568 for i in range(3):
1569 #{
1570 sm.bbx[0][i] = min( sm.bbx[0][i], vert.co[i] )
1571 sm.bbx[1][i] = max( sm.bbx[1][i], vert.co[i] )
1572 #}
1573 #}
1574 #}
1575
1576 # Add submesh to encoder
1577 #
1578 g_encoder['data']['submesh'] += [sm]
1579 node.submesh_count += 1
1580
1581 #}
1582
1583 # Save a reference to this node since we want to reuse the submesh indices
1584 # later.
1585 g_encoder['mesh_cache'][obj.data.name] = node
1586 #}
1587
1588
1589 def encoder_compile_ent_as( name, node, node_def ):
1590 #{
1591 global g_encoder
1592
1593 if name == 'classtype_none':
1594 #{
1595 node.offset = 0
1596 node.classtype = 0
1597 return
1598 #}
1599 elif name not in globals():
1600 #{
1601 print( "Classtype '" +name + "' is unknown!" )
1602 return
1603 #}
1604
1605 buffer = g_encoder['data']['entdata']
1606 node.offset = len(buffer)
1607
1608 cl = globals()[ name ]
1609 inst = cl()
1610 inst.encode_obj( node, node_def )
1611
1612 buffer.extend( bytearray(inst) )
1613 bytearray_align_to( buffer, 4 )
1614 #}
1615
1616 # Compiles animation data into model and gives us some extra node_def entries
1617 #
1618 def encoder_compile_armature( node, node_def ):
1619 #{
1620 global g_encoder
1621
1622 entdata = g_encoder['data']['entdata']
1623 animdata = g_encoder['data']['anim']
1624 keyframedata = g_encoder['data']['keyframe']
1625 mesh_cache = g_encoder['mesh_cache']
1626 obj = node_def['obj']
1627 bones = node_def['bones']
1628
1629 # extra info
1630 node_def['anim_start'] = len(animdata)
1631 node_def['anim_count'] = 0
1632
1633 # Compile anims
1634 #
1635 if obj.animation_data:
1636 #{
1637 # So we can restore later
1638 #
1639 previous_frame = bpy.context.scene.frame_current
1640 previous_action = obj.animation_data.action
1641 POSE_OR_REST_CACHE = obj.data.pose_position
1642 obj.data.pose_position = 'POSE'
1643
1644 for NLALayer in obj.animation_data.nla_tracks:
1645 #{
1646 for NLAStrip in NLALayer.strips:
1647 #{
1648 # set active
1649 #
1650 for a in bpy.data.actions:
1651 #{
1652 if a.name == NLAStrip.name:
1653 #{
1654 obj.animation_data.action = a
1655 break
1656 #}
1657 #}
1658
1659 # Clip to NLA settings
1660 #
1661 anim_start = int(NLAStrip.action_frame_start)
1662 anim_end = int(NLAStrip.action_frame_end)
1663
1664 # Export strips
1665 #
1666 anim = mdl_animation()
1667 anim.pstr_name = encoder_process_pstr( NLAStrip.action.name )
1668 anim.rate = 30.0
1669 anim.offset = len(keyframedata)
1670 anim.length = anim_end-anim_start
1671
1672 # Export the keyframes
1673 for frame in range(anim_start,anim_end):
1674 #{
1675 bpy.context.scene.frame_set(frame)
1676
1677 for bone_name in bones:
1678 #{
1679 for pb in obj.pose.bones:
1680 #{
1681 if pb.name != bone_name: continue
1682
1683 rb = obj.data.bones[ bone_name ]
1684
1685 # relative bone matrix
1686 if rb.parent is not None:
1687 #{
1688 offset_mtx = rb.parent.matrix_local
1689 offset_mtx = offset_mtx.inverted_safe() @ \
1690 rb.matrix_local
1691
1692 inv_parent = pb.parent.matrix @ offset_mtx
1693 inv_parent.invert_safe()
1694 fpm = inv_parent @ pb.matrix
1695 #}
1696 else:
1697 #{
1698 bone_mtx = rb.matrix.to_4x4()
1699 local_inv = rb.matrix_local.inverted_safe()
1700 fpm = bone_mtx @ local_inv @ pb.matrix
1701 #}
1702
1703 loc, rot, sca = fpm.decompose()
1704
1705 # local position
1706 final_pos = Vector(( loc[0], loc[2], -loc[1] ))
1707
1708 # rotation
1709 lc_m = pb.matrix_channel.to_3x3()
1710 if pb.parent is not None:
1711 #{
1712 smtx = pb.parent.matrix_channel.to_3x3()
1713 lc_m = smtx.inverted() @ lc_m
1714 #}
1715 rq = lc_m.to_quaternion()
1716
1717 kf = mdl_keyframe()
1718 kf.co[0] = final_pos[0]
1719 kf.co[1] = final_pos[1]
1720 kf.co[2] = final_pos[2]
1721
1722 kf.q[0] = rq[1]
1723 kf.q[1] = rq[3]
1724 kf.q[2] = -rq[2]
1725 kf.q[3] = rq[0]
1726
1727 # scale
1728 kf.s[0] = sca[0]
1729 kf.s[1] = sca[2]
1730 kf.s[2] = sca[1]
1731
1732 keyframedata += [kf]
1733 break
1734 #}
1735 #}
1736 #}
1737
1738 # Add to animation buffer
1739 #
1740 animdata += [anim]
1741 node_def['anim_count'] += 1
1742
1743 # Report progress
1744 #
1745 status_name = F" " + " |"*(node_def['depth']-1)
1746 print( F"{status_name} | *anim: {NLAStrip.action.name}" )
1747 #}
1748 #}
1749
1750 # Restore context to how it was before
1751 #
1752 bpy.context.scene.frame_set( previous_frame )
1753 obj.animation_data.action = previous_action
1754 obj.data.pose_position = POSE_OR_REST_CACHE
1755 #}
1756 #}
1757
1758 # We are trying to compile this node_def
1759 #
1760 def encoder_process_definition( node_def ):
1761 #{
1762 global g_encoder
1763
1764 # data sources for object/bone are taken differently
1765 #
1766 if 'obj' in node_def:
1767 #{
1768 obj = node_def['obj']
1769 obj_type = obj.type
1770 obj_co = obj.location
1771
1772 if obj_type == 'ARMATURE':
1773 obj_classtype = 'classtype_skeleton'
1774 else:
1775 #{
1776 obj_classtype = obj.cv_data.classtype
1777
1778 # Check for armature deform
1779 #
1780 for mod in obj.modifiers:
1781 #{
1782 if mod.type == 'ARMATURE':
1783 #{
1784 obj_classtype = 'classtype_skin'
1785
1786 # Make sure to freeze armature in rest while we collect
1787 # vertex information
1788 #
1789 armature_def = g_encoder['graph_lookup'][mod.object]
1790 POSE_OR_REST_CACHE = armature_def['obj'].data.pose_position
1791 armature_def['obj'].data.pose_position = 'REST'
1792 node_def['linked_armature'] = armature_def
1793 break
1794 #}
1795 #}
1796 #}
1797 #}
1798
1799 elif 'bone' in node_def:
1800 #{
1801 obj = node_def['bone']
1802 obj_type = 'BONE'
1803 obj_co = obj.head_local
1804 obj_classtype = 'classtype_bone'
1805 #}
1806
1807 # Create node
1808 #
1809 node = mdl_node()
1810 node.pstr_name = encoder_process_pstr( obj.name )
1811
1812 if node_def["parent"]:
1813 node.parent = node_def["parent"]["uid"]
1814
1815 # Setup transform
1816 #
1817 node.co[0] = obj_co[0]
1818 node.co[1] = obj_co[2]
1819 node.co[2] = -obj_co[1]
1820
1821 # Convert rotation quat to our space type
1822 #
1823 quat = obj.matrix_local.to_quaternion()
1824 node.q[0] = quat[1]
1825 node.q[1] = quat[3]
1826 node.q[2] = -quat[2]
1827 node.q[3] = quat[0]
1828
1829 # Bone scale is just a vector to the tail
1830 #
1831 if obj_type == 'BONE':
1832 #{
1833 node.s[0] = obj.tail_local[0] - node.co[0]
1834 node.s[1] = obj.tail_local[2] - node.co[1]
1835 node.s[2] = -obj.tail_local[1] - node.co[2]
1836 #}
1837 else:
1838 #{
1839 node.s[0] = obj.scale[0]
1840 node.s[1] = obj.scale[2]
1841 node.s[2] = obj.scale[1]
1842 #}
1843
1844 # Report status
1845 #
1846 tot_uid = g_encoder['uid_count']-1
1847 obj_uid = node_def['uid']
1848 obj_depth = node_def['depth']-1
1849
1850 status_id = F" [{obj_uid: 3}/{tot_uid}]" + " |"*obj_depth
1851 status_name = status_id + F" L {obj.name}"
1852
1853 if obj_classtype != 'classtype_none': status_type = obj_classtype
1854 else: status_type = obj_type
1855
1856 status_parent = F"{node.parent: 3}"
1857 status_armref = ""
1858
1859 if obj_classtype == 'classtype_skin':
1860 status_armref = F" [armature -> {armature_def['obj'].cv_data.uid}]"
1861
1862 print(F"{status_name:<32} {status_type:<22} {status_parent} {status_armref}")
1863
1864 # Process mesh if needed
1865 #
1866 if obj_type == 'MESH':
1867 #{
1868 encoder_compile_mesh( node, node_def )
1869 #}
1870 elif obj_type == 'ARMATURE':
1871 #{
1872 encoder_compile_armature( node, node_def )
1873 #}
1874
1875 encoder_compile_ent_as( obj_classtype, node, node_def )
1876
1877 # Make sure to reset the armature we just mucked about with
1878 #
1879 if obj_classtype == 'classtype_skin':
1880 armature_def['obj'].data.pose_position = POSE_OR_REST_CACHE
1881
1882 g_encoder['data']['node'] += [node]
1883 #}
1884
1885 # The post processing step or the pre processing to the writing step
1886 #
1887 def encoder_write_to_file( path ):
1888 #{
1889 global g_encoder
1890
1891 # Compile down to a byte array
1892 #
1893 header = g_encoder['header']
1894 file_pos = sizeof(header)
1895 file_data = bytearray()
1896 print( " Compositing data arrays" )
1897
1898 for array_name in g_encoder['data']:
1899 #{
1900 file_pos += bytearray_align_to( file_data, 16, sizeof(header) )
1901 arr = g_encoder['data'][array_name]
1902
1903 setattr( header, array_name + "_offset", file_pos )
1904
1905 print( F" {array_name:<16} @{file_pos:> 8X}[{len(arr)}]" )
1906
1907 if isinstance( arr, bytearray ):
1908 #{
1909 setattr( header, array_name + "_size", len(arr) )
1910
1911 file_data.extend( arr )
1912 file_pos += len(arr)
1913 #}
1914 else:
1915 #{
1916 setattr( header, array_name + "_count", len(arr) )
1917
1918 for item in arr:
1919 #{
1920 bbytes = bytearray(item)
1921 file_data.extend( bbytes )
1922 file_pos += sizeof(item)
1923 #}
1924 #}
1925 #}
1926
1927 # This imperitive for this field to be santized in the future!
1928 #
1929 header.file_length = file_pos
1930
1931 print( " Writing file" )
1932 # Write header and data chunk to file
1933 #
1934 fp = open( path, "wb" )
1935 fp.write( bytearray( header ) )
1936 fp.write( file_data )
1937 fp.close()
1938 #}
1939
1940 # Main compiler, uses string as the identifier for the collection
1941 #
1942 def write_model(collection_name):
1943 #{
1944 global g_encoder
1945 print( F"Model graph | Create mode '{collection_name}'" )
1946
1947 collection = bpy.data.collections[collection_name]
1948
1949 encoder_init( collection )
1950 encoder_build_scene_graph( collection )
1951
1952 # Compile
1953 #
1954 print( " Comping objects" )
1955 it = encoder_graph_iterator( g_encoder['scene_graph'] )
1956 for node_def in it:
1957 encoder_process_definition( node_def )
1958
1959 # Write
1960 #
1961 # TODO HOLY
1962 path = F"/home/harry/Documents/carve/models_src/{collection_name}.mdl"
1963 encoder_write_to_file( path )
1964
1965 print( F"Completed {collection_name}.mdl" )
1966 #}
1967
1968 # ---------------------------------------------------------------------------- #
1969 # #
1970 # GUI section #
1971 # #
1972 # ---------------------------------------------------------------------------- #
1973
1974 cv_view_draw_handler = None
1975 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
1976 cv_view_verts = []
1977 cv_view_colours = []
1978 cv_view_course_i = 0
1979
1980 # Draw axis alligned sphere at position with radius
1981 #
1982 def cv_draw_sphere( pos, radius, colour ):
1983 #{
1984 global cv_view_verts, cv_view_colours
1985
1986 ly = pos + Vector((0,0,radius))
1987 lx = pos + Vector((0,radius,0))
1988 lz = pos + Vector((0,0,radius))
1989
1990 pi = 3.14159265358979323846264
1991
1992 for i in range(16):
1993 #{
1994 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
1995 s = math.sin(t)
1996 c = math.cos(t)
1997
1998 py = pos + Vector((s*radius,0.0,c*radius))
1999 px = pos + Vector((s*radius,c*radius,0.0))
2000 pz = pos + Vector((0.0,s*radius,c*radius))
2001
2002 cv_view_verts += [ px, lx ]
2003 cv_view_verts += [ py, ly ]
2004 cv_view_verts += [ pz, lz ]
2005
2006 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
2007
2008 ly = py
2009 lx = px
2010 lz = pz
2011 #}
2012 cv_draw_lines()
2013 #}
2014
2015 # Draw transformed -1 -> 1 cube
2016 #
2017 def cv_draw_ucube( transform, colour ):
2018 #{
2019 global cv_view_verts, cv_view_colours
2020
2021 a = Vector((-1,-1,-1))
2022 b = Vector((1,1,1))
2023
2024 vs = [None]*8
2025 vs[0] = transform @ Vector((a[0], a[1], a[2]))
2026 vs[1] = transform @ Vector((a[0], b[1], a[2]))
2027 vs[2] = transform @ Vector((b[0], b[1], a[2]))
2028 vs[3] = transform @ Vector((b[0], a[1], a[2]))
2029 vs[4] = transform @ Vector((a[0], a[1], b[2]))
2030 vs[5] = transform @ Vector((a[0], b[1], b[2]))
2031 vs[6] = transform @ Vector((b[0], b[1], b[2]))
2032 vs[7] = transform @ Vector((b[0], a[1], b[2]))
2033
2034 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2035 (0,4),(1,5),(2,6),(3,7)]
2036
2037 for l in indices:
2038 #{
2039 v0 = vs[l[0]]
2040 v1 = vs[l[1]]
2041 cv_view_verts += [(v0[0],v0[1],v0[2])]
2042 cv_view_verts += [(v1[0],v1[1],v1[2])]
2043 cv_view_colours += [(0,1,0,1),(0,1,0,1)]
2044 #}
2045 cv_draw_lines()
2046 #}
2047
2048 # Draw line with colour
2049 #
2050 def cv_draw_line( p0, p1, colour ):
2051 #{
2052 global cv_view_verts, cv_view_colours
2053
2054 cv_view_verts += [p0,p1]
2055 cv_view_colours += [colour, colour]
2056 cv_draw_lines()
2057 #}
2058
2059 # Draw line with colour(s)
2060 #
2061 def cv_draw_line2( p0, p1, c0, c1 ):
2062 #{
2063 global cv_view_verts, cv_view_colours
2064
2065 cv_view_verts += [p0,p1]
2066 cv_view_colours += [c0,c1]
2067 cv_draw_lines()
2068 #}
2069
2070 # Just the tx because we dont really need ty for this app
2071 #
2072 def cv_tangent_basis_tx( n, tx ):
2073 #{
2074 if abs( n[0] ) >= 0.57735027:
2075 #{
2076 tx[0] = n[1]
2077 tx[1] = -n[0]
2078 tx[2] = 0.0
2079 #}
2080 else:
2081 #{
2082 tx[0] = 0.0
2083 tx[1] = n[2]
2084 tx[2] = -n[1]
2085 #}
2086
2087 tx.normalize()
2088 #}
2089
2090 # Draw coloured arrow
2091 #
2092 def cv_draw_arrow( p0, p1, c0 ):
2093 #{
2094 global cv_view_verts, cv_view_colours
2095
2096 n = p1-p0
2097 midpt = p0 + n*0.5
2098 n.normalize()
2099
2100 tx = Vector((1,0,0))
2101 cv_tangent_basis_tx( n, tx )
2102
2103 cv_view_verts += [p0,p1, midpt+(tx-n)*0.15,midpt, midpt+(-tx-n)*0.15,midpt ]
2104 cv_view_colours += [c0,c0,c0,c0,c0,c0]
2105 cv_draw_lines()
2106 #}
2107
2108 # Drawhandles of a bezier control point
2109 #
2110 def cv_draw_bhandle( obj, direction, colour ):
2111 #{
2112 global cv_view_verts, cv_view_colours
2113
2114 p0 = obj.location
2115 h0 = obj.matrix_world @ Vector((0,direction,0))
2116
2117 cv_view_verts += [p0]
2118 cv_view_verts += [h0]
2119 cv_view_colours += [colour,colour]
2120 cv_draw_lines()
2121 #}
2122
2123 # Draw a bezier curve (at fixed resolution 10)
2124 #
2125 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
2126 #{
2127 global cv_view_verts, cv_view_colours
2128
2129 last = p0
2130 for i in range(10):
2131 #{
2132 t = (i+1)/10
2133 a0 = 1-t
2134
2135 tt = t*t
2136 ttt = tt*t
2137 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
2138
2139 cv_view_verts += [(last[0],last[1],last[2])]
2140 cv_view_verts += [(p[0],p[1],p[2])]
2141 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
2142
2143 last = p
2144 #}
2145 cv_draw_lines()
2146 #}
2147
2148 # I think this one extends the handles of the bezier otwards......
2149 #
2150 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
2151 #{
2152 global cv_view_course_i
2153
2154 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
2155
2156 p0 = o0.matrix_world @ Vector((offs, 0,0))
2157 h0 = o0.matrix_world @ Vector((offs, s0,0))
2158 p1 = o1.matrix_world @ Vector((offs, 0,0))
2159 h1 = o1.matrix_world @ Vector((offs,-s1,0))
2160
2161 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
2162 cv_draw_lines()
2163 #}
2164
2165 # Flush the lines buffers. This is called often because god help you if you want
2166 # to do fixed, fast buffers in this catastrophic programming language.
2167 #
2168 def cv_draw_lines():
2169 #{
2170 global cv_view_shader, cv_view_verts, cv_view_colours
2171
2172 if len(cv_view_verts) < 2:
2173 return
2174
2175 lines = batch_for_shader(\
2176 cv_view_shader, 'LINES', \
2177 { "pos":cv_view_verts, "color":cv_view_colours })
2178
2179 lines.draw( cv_view_shader )
2180
2181 cv_view_verts = []
2182 cv_view_colours = []
2183 #}
2184
2185 # I dont remember what this does exactly
2186 #
2187 def cv_draw_bpath( o0,o1,c0,c1 ):
2188 #{
2189 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
2190 #}
2191
2192 # Semi circle to show the limit. and some lines
2193 #
2194 def draw_limit( obj, center, major, minor, amin, amax, colour ):
2195 #{
2196 global cv_view_verts, cv_view_colours
2197 f = 0.05
2198 ay = major*f
2199 ax = minor*f
2200
2201 for x in range(16):
2202 #{
2203 t0 = x/16
2204 t1 = (x+1)/16
2205 a0 = amin*(1.0-t0)+amax*t0
2206 a1 = amin*(1.0-t1)+amax*t1
2207
2208 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
2209 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
2210
2211 p0=obj.matrix_world @ p0
2212 p1=obj.matrix_world @ p1
2213 cv_view_verts += [p0,p1]
2214 cv_view_colours += [colour,colour]
2215
2216 if x == 0:
2217 #{
2218 cv_view_verts += [p0,center]
2219 cv_view_colours += [colour,colour]
2220 #}
2221 if x == 15:
2222 #{
2223 cv_view_verts += [p1,center]
2224 cv_view_colours += [colour,colour]
2225 #}
2226 #}
2227
2228 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
2229 cv_view_colours += [colour,colour]
2230
2231 cv_draw_lines()
2232 #}
2233
2234 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2235 #
2236 def draw_skeleton_helpers( obj ):
2237 #{
2238 global cv_view_verts, cv_view_colours
2239
2240 for bone in obj.data.bones:
2241 #{
2242 if bone.cv_data.collider and (obj.data.pose_position == 'REST'):
2243 #{
2244 c = bone.head_local
2245 a = bone.cv_data.v0
2246 b = bone.cv_data.v1
2247
2248 vs = [None]*8
2249 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
2250 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
2251 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
2252 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
2253 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
2254 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
2255 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
2256 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
2257
2258 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2259 (0,4),(1,5),(2,6),(3,7)]
2260
2261 for l in indices:
2262 #{
2263 v0 = vs[l[0]]
2264 v1 = vs[l[1]]
2265
2266 cv_view_verts += [(v0[0],v0[1],v0[2])]
2267 cv_view_verts += [(v1[0],v1[1],v1[2])]
2268 cv_view_colours += [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2269 #}
2270
2271 center = obj.matrix_world @ c
2272 if bone.cv_data.con0:
2273 #{
2274 draw_limit( obj, c, Vector((0,1,0)),Vector((0,0,1)), \
2275 bone.cv_data.mins[0], bone.cv_data.maxs[0], \
2276 (1,0,0,1))
2277 draw_limit( obj, c, Vector((0,0,1)),Vector((1,0,0)), \
2278 bone.cv_data.mins[1], bone.cv_data.maxs[1], \
2279 (0,1,0,1))
2280 draw_limit( obj, c, Vector((1,0,0)),Vector((0,1,0)), \
2281 bone.cv_data.mins[2], bone.cv_data.maxs[2], \
2282 (0,0,1,1))
2283 #}
2284 #}
2285 #}
2286 #}
2287
2288 def cv_draw():
2289 #{
2290 global cv_view_shader
2291 global cv_view_verts
2292 global cv_view_colours
2293 global cv_view_course_i
2294
2295 cv_view_course_i = 0
2296 cv_view_verts = []
2297 cv_view_colours = []
2298
2299 cv_view_shader.bind()
2300 gpu.state.depth_mask_set(False)
2301 gpu.state.line_width_set(2.0)
2302 gpu.state.face_culling_set('BACK')
2303 gpu.state.depth_test_set('LESS')
2304 gpu.state.blend_set('NONE')
2305
2306 for obj in bpy.context.collection.objects:
2307 #{
2308 if obj.type == 'ARMATURE':
2309 #{
2310 if obj.data.pose_position == 'REST':
2311 draw_skeleton_helpers( obj )
2312 #}
2313 else:
2314 #{
2315 classtype = obj.cv_data.classtype
2316 if (classtype != 'classtype_none') and (classtype in globals()):
2317 #{
2318 cl = globals()[ classtype ]
2319
2320 if getattr( cl, "draw_scene_helpers", None ):
2321 #{
2322 cl.draw_scene_helpers( obj )
2323 #}
2324 #}
2325 #}
2326 #}
2327
2328 cv_draw_lines()
2329 return
2330 #}
2331
2332
2333 # ---------------------------------------------------------------------------- #
2334 # #
2335 # Blender #
2336 # #
2337 # ---------------------------------------------------------------------------- #
2338
2339 # Checks whether this object has a classtype assigned. we can only target other
2340 # classes
2341 def cv_poll_target(scene, obj):
2342 #{
2343 if obj == bpy.context.active_object:
2344 return False
2345 if obj.cv_data.classtype == 'classtype_none':
2346 return False
2347
2348 return True
2349 #}
2350
2351 class CV_MESH_SETTINGS(bpy.types.PropertyGroup):
2352 #{
2353 v0: bpy.props.FloatVectorProperty(name="v0",size=3)
2354 v1: bpy.props.FloatVectorProperty(name="v1",size=3)
2355 v2: bpy.props.FloatVectorProperty(name="v2",size=3)
2356 v3: bpy.props.FloatVectorProperty(name="v3",size=3)
2357 #}
2358
2359 class CV_OBJ_SETTINGS(bpy.types.PropertyGroup):
2360 #{
2361 uid: bpy.props.IntProperty( name="" )
2362
2363 strp: bpy.props.StringProperty( name="strp" )
2364 intp: bpy.props.IntProperty( name="intp" )
2365 fltp: bpy.props.FloatProperty( name="fltp" )
2366 bp0: bpy.props.BoolProperty( name="bp0" )
2367 bp1: bpy.props.BoolProperty( name="bp1" )
2368 bp2: bpy.props.BoolProperty( name="bp2" )
2369 bp3: bpy.props.BoolProperty( name="bp3" )
2370
2371 target: bpy.props.PointerProperty( type=bpy.types.Object, name="target", \
2372 poll=cv_poll_target )
2373 target1: bpy.props.PointerProperty( type=bpy.types.Object, name="target1", \
2374 poll=cv_poll_target )
2375 target2: bpy.props.PointerProperty( type=bpy.types.Object, name="target2", \
2376 poll=cv_poll_target )
2377 target3: bpy.props.PointerProperty( type=bpy.types.Object, name="target3", \
2378 poll=cv_poll_target )
2379
2380 colour: bpy.props.FloatVectorProperty( name="colour",subtype='COLOR',\
2381 min=0.0,max=1.0)
2382
2383 classtype: bpy.props.EnumProperty(
2384 name="Format",
2385 items = [
2386 ('classtype_none', "classtype_none", "", 0),
2387 ('classtype_gate', "classtype_gate", "", 1),
2388 ('classtype_spawn', "classtype_spawn", "", 3),
2389 ('classtype_water', "classtype_water", "", 4),
2390 ('classtype_route_node', "classtype_route_node", "", 8 ),
2391 ('classtype_route', "classtype_route", "", 9 ),
2392 ('classtype_audio',"classtype_audio","",14),
2393 ('classtype_trigger',"classtype_trigger","",100),
2394 ('classtype_logic_achievement',"classtype_logic_achievement","",101),
2395 ('classtype_logic_relay',"classtype_logic_relay","",102),
2396 ('classtype_spawn_link',"classtype_spawn_link","",150),
2397 ])
2398 #}
2399
2400 class CV_BONE_SETTINGS(bpy.types.PropertyGroup):
2401 #{
2402 collider: bpy.props.BoolProperty(name="Collider",default=False)
2403 v0: bpy.props.FloatVectorProperty(name="v0",size=3)
2404 v1: bpy.props.FloatVectorProperty(name="v1",size=3)
2405
2406 con0: bpy.props.BoolProperty(name="Constriant 0",default=False)
2407 mins: bpy.props.FloatVectorProperty(name="mins",size=3)
2408 maxs: bpy.props.FloatVectorProperty(name="maxs",size=3)
2409 #}
2410
2411 class CV_BONE_PANEL(bpy.types.Panel):
2412 #{
2413 bl_label="Bone Config"
2414 bl_idname="SCENE_PT_cv_bone"
2415 bl_space_type='PROPERTIES'
2416 bl_region_type='WINDOW'
2417 bl_context='bone'
2418
2419 def draw(_,context):
2420 #{
2421 active_object = context.active_object
2422 if active_object == None: return
2423
2424 bone = active_object.data.bones.active
2425 if bone == None: return
2426
2427 _.layout.prop( bone.cv_data, "collider" )
2428 _.layout.prop( bone.cv_data, "v0" )
2429 _.layout.prop( bone.cv_data, "v1" )
2430
2431 _.layout.label( text="Angle Limits" )
2432 _.layout.prop( bone.cv_data, "con0" )
2433 _.layout.prop( bone.cv_data, "mins" )
2434 _.layout.prop( bone.cv_data, "maxs" )
2435 #}
2436 #}
2437
2438 class CV_SCENE_SETTINGS(bpy.types.PropertyGroup):
2439 #{
2440 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
2441 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
2442 #}
2443
2444 class CV_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
2445 #{
2446 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
2447 #}
2448
2449 class CV_MATERIAL_SETTINGS(bpy.types.PropertyGroup):
2450 #{
2451 shader: bpy.props.EnumProperty(
2452 name="Format",
2453 items = [
2454 ('standard',"standard","",0),
2455 ('standard_cutout', "standard_cutout", "", 1),
2456 ('terrain_blend', "terrain_blend", "", 2),
2457 ('vertex_blend', "vertex_blend", "", 3),
2458 ('water',"water","",4),
2459 ])
2460
2461 surface_prop: bpy.props.EnumProperty(
2462 name="Surface Property",
2463 items = [
2464 ('concrete','concrete','',0),
2465 ('wood','wood','',1),
2466 ('grass','grass','',2)
2467 ])
2468
2469 collision: bpy.props.BoolProperty( \
2470 name="Collisions Enabled",\
2471 default=True,\
2472 description = "Can the player collide with this material"\
2473 )
2474 skate_surface: bpy.props.BoolProperty( \
2475 name="Skate Surface", \
2476 default=True,\
2477 description = "Should the game try to target this surface?" \
2478 )
2479 grow_grass: bpy.props.BoolProperty( \
2480 name="Grow Grass", \
2481 default=False,\
2482 description = "Spawn grass sprites on this surface?" \
2483 )
2484 blend_offset: bpy.props.FloatVectorProperty( \
2485 name="Blend Offset", \
2486 size=2, \
2487 default=Vector((0.5,0.0)),\
2488 description="When surface is more than 45 degrees, add this vector " +\
2489 "to the UVs" \
2490 )
2491 sand_colour: bpy.props.FloatVectorProperty( \
2492 name="Sand Colour",\
2493 subtype='COLOR',\
2494 min=0.0,max=1.0,\
2495 default=Vector((0.79,0.63,0.48)),\
2496 description="Blend to this colour near the 0 coordinate on UP axis"\
2497 )
2498 shore_colour: bpy.props.FloatVectorProperty( \
2499 name="Shore Colour",\
2500 subtype='COLOR',\
2501 min=0.0,max=1.0,\
2502 default=Vector((0.03,0.32,0.61)),\
2503 description="Water colour at the shoreline"\
2504 )
2505 ocean_colour: bpy.props.FloatVectorProperty( \
2506 name="Ocean Colour",\
2507 subtype='COLOR',\
2508 min=0.0,max=1.0,\
2509 default=Vector((0.0,0.006,0.03)),\
2510 description="Water colour in the deep bits"\
2511 )
2512 #}
2513
2514 class CV_MATERIAL_PANEL(bpy.types.Panel):
2515 #{
2516 bl_label="Skate Rift material"
2517 bl_idname="MATERIAL_PT_cv_material"
2518 bl_space_type='PROPERTIES'
2519 bl_region_type='WINDOW'
2520 bl_context="material"
2521
2522 def draw(_,context):
2523 #{
2524 active_object = bpy.context.active_object
2525 if active_object == None: return
2526 active_mat = active_object.active_material
2527 if active_mat == None: return
2528
2529 info = material_info( active_mat )
2530
2531 _.layout.prop( active_mat.cv_data, "shader" )
2532 _.layout.prop( active_mat.cv_data, "surface_prop" )
2533 _.layout.prop( active_mat.cv_data, "collision" )
2534
2535 if active_mat.cv_data.collision:
2536 _.layout.prop( active_mat.cv_data, "skate_surface" )
2537 _.layout.prop( active_mat.cv_data, "grow_grass" )
2538
2539 if active_mat.cv_data.shader == "terrain_blend":
2540 #{
2541 box = _.layout.box()
2542 box.prop( active_mat.cv_data, "blend_offset" )
2543 box.prop( active_mat.cv_data, "sand_colour" )
2544 #}
2545 elif active_mat.cv_data.shader == "vertex_blend":
2546 #{
2547 box = _.layout.box()
2548 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
2549 box.prop( active_mat.cv_data, "blend_offset" )
2550 #}
2551 elif active_mat.cv_data.shader == "water":
2552 #{
2553 box = _.layout.box()
2554 box.label( icon='INFO', text="Depth scale of 16 meters" )
2555 box.prop( active_mat.cv_data, "shore_colour" )
2556 box.prop( active_mat.cv_data, "ocean_colour" )
2557 #}
2558 #}
2559 #}
2560
2561 class CV_OBJ_PANEL(bpy.types.Panel):
2562 #{
2563 bl_label="Entity Config"
2564 bl_idname="SCENE_PT_cv_entity"
2565 bl_space_type='PROPERTIES'
2566 bl_region_type='WINDOW'
2567 bl_context="object"
2568
2569 def draw(_,context):
2570 #{
2571 active_object = bpy.context.active_object
2572 if active_object == None: return
2573 if active_object.type == 'ARMATURE':
2574 #{
2575 row = _.layout.row()
2576 row.enabled = False
2577 row.label( text="This object has the intrinsic classtype of skeleton" )
2578 return
2579 #}
2580
2581 _.layout.prop( active_object.cv_data, "classtype" )
2582
2583 classtype = active_object.cv_data.classtype
2584
2585 if (classtype != 'classtype_none') and (classtype in globals()):
2586 #{
2587 cl = globals()[ classtype ]
2588
2589 if getattr( cl, "editor_interface", None ):
2590 #{
2591 cl.editor_interface( _.layout, active_object )
2592 #}
2593 #}
2594 #}
2595 #}
2596
2597 class CV_COMPILE(bpy.types.Operator):
2598 #{
2599 bl_idname="carve.compile_all"
2600 bl_label="Compile All"
2601
2602 def execute(_,context):
2603 #{
2604 view_layer = bpy.context.view_layer
2605 for col in view_layer.layer_collection.children["export"].children:
2606 if not col.hide_viewport or bpy.context.scene.cv_data.use_hidden:
2607 write_model( col.name )
2608
2609 return {'FINISHED'}
2610 #}
2611 #}
2612
2613 class CV_COMPILE_THIS(bpy.types.Operator):
2614 #{
2615 bl_idname="carve.compile_this"
2616 bl_label="Compile This collection"
2617
2618 def execute(_,context):
2619 #{
2620 col = bpy.context.collection
2621 write_model( col.name )
2622
2623 return {'FINISHED'}
2624 #}
2625 #}
2626
2627 class CV_INTERFACE(bpy.types.Panel):
2628 #{
2629 bl_idname = "VIEW3D_PT_carve"
2630 bl_label = "Skate Rift"
2631 bl_space_type = 'VIEW_3D'
2632 bl_region_type = 'UI'
2633 bl_category = "Skate Rift"
2634
2635 def draw(_, context):
2636 #{
2637 layout = _.layout
2638 layout.prop( context.scene.cv_data, "export_dir" )
2639
2640 col = bpy.context.collection
2641
2642 found_in_export = False
2643 export_count = 0
2644 view_layer = bpy.context.view_layer
2645 for c1 in view_layer.layer_collection.children["export"].children:
2646 #{
2647 if not c1.hide_viewport or bpy.context.scene.cv_data.use_hidden:
2648 export_count += 1
2649
2650 if c1.name == col.name:
2651 #{
2652 found_in_export = True
2653 #}
2654 #}
2655
2656 box = layout.box()
2657 if found_in_export:
2658 #{
2659 box.label( text=col.name + ".mdl" )
2660 box.prop( col.cv_data, "pack_textures" )
2661 box.operator( "carve.compile_this" )
2662 #}
2663 else:
2664 #{
2665 row = box.row()
2666 row.enabled=False
2667 row.label( text=col.name )
2668 box.label( text="This collection is not in the export group" )
2669 #}
2670
2671 box = layout.box()
2672 row = box.row()
2673
2674 split = row.split( factor = 0.3, align=True )
2675 split.prop( context.scene.cv_data, "use_hidden", text="hidden" )
2676
2677 row1 = split.row()
2678 if export_count == 0:
2679 row1.enabled=False
2680 row1.operator( "carve.compile_all", \
2681 text=F"Compile all ({export_count} collections)" )
2682 #}
2683 #}
2684
2685
2686 classes = [CV_OBJ_SETTINGS,CV_OBJ_PANEL,CV_COMPILE,CV_INTERFACE,\
2687 CV_MESH_SETTINGS, CV_SCENE_SETTINGS, CV_BONE_SETTINGS,\
2688 CV_BONE_PANEL, CV_COLLECTION_SETTINGS, CV_COMPILE_THIS,\
2689 CV_MATERIAL_SETTINGS, CV_MATERIAL_PANEL ]
2690
2691 def register():
2692 #{
2693 global cv_view_draw_handler
2694
2695 for c in classes:
2696 bpy.utils.register_class(c)
2697
2698 bpy.types.Object.cv_data = bpy.props.PointerProperty(type=CV_OBJ_SETTINGS)
2699 bpy.types.Mesh.cv_data = bpy.props.PointerProperty(type=CV_MESH_SETTINGS)
2700 bpy.types.Scene.cv_data = bpy.props.PointerProperty(type=CV_SCENE_SETTINGS)
2701 bpy.types.Bone.cv_data = bpy.props.PointerProperty(type=CV_BONE_SETTINGS)
2702 bpy.types.Collection.cv_data = \
2703 bpy.props.PointerProperty(type=CV_COLLECTION_SETTINGS)
2704 bpy.types.Material.cv_data = \
2705 bpy.props.PointerProperty(type=CV_MATERIAL_SETTINGS)
2706
2707 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
2708 cv_draw,(),'WINDOW','POST_VIEW')
2709 #}
2710
2711 def unregister():
2712 #{
2713 global cv_view_draw_handler
2714
2715 for c in classes:
2716 bpy.utils.unregister_class(c)
2717
2718 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
2719 #}
2720
2721 # ---------------------------------------------------------------------------- #
2722 # #
2723 # QOI encoder #
2724 # #
2725 # ---------------------------------------------------------------------------- #
2726 # #
2727 # Transliteration of: #
2728 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
2729 # #
2730 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
2731 # SPDX-License-Identifier: MIT #
2732 # QOI - The "Quite OK Image" format for fast, lossless image compression #
2733 # #
2734 # ---------------------------------------------------------------------------- #
2735
2736 class qoi_rgba_t(Structure):
2737 #{
2738 _pack_ = 1
2739 _fields_ = [("r",c_uint8),
2740 ("g",c_uint8),
2741 ("b",c_uint8),
2742 ("a",c_uint8)]
2743 #}
2744
2745 QOI_OP_INDEX = 0x00 # 00xxxxxx
2746 QOI_OP_DIFF = 0x40 # 01xxxxxx
2747 QOI_OP_LUMA = 0x80 # 10xxxxxx
2748 QOI_OP_RUN = 0xc0 # 11xxxxxx
2749 QOI_OP_RGB = 0xfe # 11111110
2750 QOI_OP_RGBA = 0xff # 11111111
2751
2752 QOI_MASK_2 = 0xc0 # 11000000
2753
2754 def qoi_colour_hash( c ):
2755 #{
2756 return c.r*3 + c.g*5 + c.b*7 + c.a*11
2757 #}
2758
2759 def qoi_eq( a, b ):
2760 #{
2761 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
2762 #}
2763
2764 def qoi_32bit( v ):
2765 #{
2766 return bytearray([ (0xff000000 & v) >> 24, \
2767 (0x00ff0000 & v) >> 16, \
2768 (0x0000ff00 & v) >> 8, \
2769 (0x000000ff & v) ])
2770 #}
2771
2772 def qoi_encode( img ):
2773 #{
2774 data = bytearray()
2775
2776 print(F" . Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]")
2777
2778 index = [ qoi_rgba_t() for _ in range(64) ]
2779
2780 # Header
2781 #
2782 data.extend( bytearray(c_uint32(0x66696f71)) )
2783 data.extend( qoi_32bit( img.size[0] ) )
2784 data.extend( qoi_32bit( img.size[1] ) )
2785 data.extend( bytearray(c_uint8(4)) )
2786 data.extend( bytearray(c_uint8(0)) )
2787
2788 run = 0
2789 px_prev = qoi_rgba_t()
2790 px_prev.r = c_uint8(0)
2791 px_prev.g = c_uint8(0)
2792 px_prev.b = c_uint8(0)
2793 px_prev.a = c_uint8(255)
2794
2795 px = qoi_rgba_t()
2796 px.r = c_uint8(0)
2797 px.g = c_uint8(0)
2798 px.b = c_uint8(0)
2799 px.a = c_uint8(255)
2800
2801 px_len = img.size[0] * img.size[1]
2802
2803 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
2804
2805 for px_pos in range( px_len ):
2806 #{
2807 idx = px_pos * img.channels
2808 nc = img.channels-1
2809
2810 px.r = paxels[idx+min(0,nc)]
2811 px.g = paxels[idx+min(1,nc)]
2812 px.b = paxels[idx+min(2,nc)]
2813 px.a = paxels[idx+min(3,nc)]
2814
2815 if qoi_eq( px, px_prev ):
2816 #{
2817 run += 1
2818
2819 if (run == 62) or (px_pos == px_len-1):
2820 #{
2821 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2822 run = 0
2823 #}
2824 #}
2825 else:
2826 #{
2827 if run > 0:
2828 #{
2829 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2830 run = 0
2831 #}
2832
2833 index_pos = qoi_colour_hash(px) % 64
2834
2835 if qoi_eq( index[index_pos], px ):
2836 #{
2837 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
2838 #}
2839 else:
2840 #{
2841 index[ index_pos ].r = px.r
2842 index[ index_pos ].g = px.g
2843 index[ index_pos ].b = px.b
2844 index[ index_pos ].a = px.a
2845
2846 if px.a == px_prev.a:
2847 #{
2848 vr = int(px.r) - int(px_prev.r)
2849 vg = int(px.g) - int(px_prev.g)
2850 vb = int(px.b) - int(px_prev.b)
2851
2852 vg_r = vr - vg
2853 vg_b = vb - vg
2854
2855 if (vr > -3) and (vr < 2) and\
2856 (vg > -3) and (vg < 2) and\
2857 (vb > -3) and (vb < 2):
2858 #{
2859 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
2860 data.extend( bytearray( c_uint8(op) ))
2861 #}
2862 elif (vg_r > -9) and (vg_r < 8) and\
2863 (vg > -33) and (vg < 32 ) and\
2864 (vg_b > -9) and (vg_b < 8):
2865 #{
2866 op = QOI_OP_LUMA | (vg+32)
2867 delta = (vg_r+8) << 4 | (vg_b + 8)
2868 data.extend( bytearray( c_uint8(op) ) )
2869 data.extend( bytearray( c_uint8(delta) ))
2870 #}
2871 else:
2872 #{
2873 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
2874 data.extend( bytearray( c_uint8(px.r) ))
2875 data.extend( bytearray( c_uint8(px.g) ))
2876 data.extend( bytearray( c_uint8(px.b) ))
2877 #}
2878 #}
2879 else:
2880 #{
2881 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
2882 data.extend( bytearray( c_uint8(px.r) ))
2883 data.extend( bytearray( c_uint8(px.g) ))
2884 data.extend( bytearray( c_uint8(px.b) ))
2885 data.extend( bytearray( c_uint8(px.a) ))
2886 #}
2887 #}
2888 #}
2889
2890 px_prev.r = px.r
2891 px_prev.g = px.g
2892 px_prev.b = px.b
2893 px_prev.a = px.a
2894 #}
2895
2896 # Padding
2897 for i in range(7):
2898 data.extend( bytearray( c_uint8(0) ))
2899 data.extend( bytearray( c_uint8(1) ))
2900 bytearray_align_to( data, 16, 0 )
2901
2902 return data
2903 #}