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