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