2 # =============================================================================
4 # Copyright . . . -----, ,----- ,---. .---.
5 # 2021-2022 |\ /| | / | | | | /|
6 # | \ / | +-- / +----- +---' | / |
7 # | \ / | | / | | \ | / |
8 # | \/ | | / | | \ | / |
9 # ' ' '--' [] '----- '----- ' ' '---' SOFTWARE
11 # =============================================================================
13 # Python exporter for Blender, compiles .mdl format for Skate Rift.
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
20 import bpy
, math
, gpu
, os
23 from mathutils
import *
24 from gpu_extras
.batch
import batch_for_shader
27 "name":"Skate Rift model compiler",
28 "author": "Harry Godden (hgn)",
35 "category":"Import/Export",
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),
45 ("weights",c_uint16
*4),
49 class mdl_submesh(Structure
):
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
60 class mdl_texture(Structure
):
63 _fields_
= [("pstr_name",c_uint32
),
64 ("pack_offset",c_uint32
),
65 ("pack_length",c_uint32
)]
68 class mdl_material(Structure
):
71 _fields_
= [("pstr_name",c_uint32
),
74 ("surface_prop",c_uint32
),
76 ("colour1",c_float
*4),
77 ("tex_diffuse",c_uint32
),
78 ("tex_decal",c_uint32
),
79 ("tex_normal",c_uint32
)]
82 class mdl_node(Structure
):
85 _fields_
= [("co",c_float
*3),
88 ("sub_uid",c_uint32
), # dont use
89 ("submesh_start",c_uint32
),
90 ("submesh_count",c_uint32
),
91 ("classtype",c_uint32
),
94 ("pstr_name",c_uint32
)]
97 class mdl_header(Structure
):
100 _fields_
= [("identifier",c_uint32
),
101 ("version",c_uint32
),
102 ("file_length",c_uint32
),
105 ("node_count",c_uint32
),
106 ("node_offset",c_uint32
),
108 ("submesh_count",c_uint32
),
109 ("submesh_offset",c_uint32
),
111 ("material_count",c_uint32
),
112 ("material_offset",c_uint32
),
114 ("texture_count",c_uint32
),
115 ("texture_offset",c_uint32
),
117 ("anim_count",c_uint32
),
118 ("anim_offset",c_uint32
),
120 ("entdata_size",c_uint32
),
121 ("entdata_offset",c_uint32
),
123 ("strings_size",c_uint32
),
124 ("strings_offset",c_uint32
),
126 ("keyframe_count",c_uint32
),
127 ("keyframe_offset",c_uint32
),
129 ("vertex_count",c_uint32
),
130 ("vertex_offset",c_uint32
),
132 ("indice_count",c_uint32
),
133 ("indice_offset",c_uint32
),
135 ("pack_size",c_uint32
),
136 ("pack_offset",c_uint32
)]
139 class mdl_animation(Structure
):
142 _fields_
= [("pstr_name",c_uint32
),
148 class mdl_keyframe(Structure
):
151 _fields_
= [("co",c_float
*3),
156 # ---------------------------------------------------------------------------- #
158 # Entity definitions #
160 # ---------------------------------------------------------------------------- #
162 # ctypes _fields_ defines the data which is filled in by:
163 # def encode_obj( _, node, node_def ):
165 # gizmos get drawn into the viewport via:
167 # def draw_scene_helpers( obj ):
169 # editor enterface, simiraliy:
171 # def editor_interface( layout, obj ):
176 # Purpose: A rift. must target another gate, the target gate can not have more
177 # than one target nodes of its own.
179 class classtype_gate(Structure
):
182 _fields_
= [("target",c_uint32
),
185 def encode_obj(_
, node
,node_def
):
189 obj
= node_def
['obj']
191 if obj
.cv_data
.target
!= None:
192 _
.target
= obj
.cv_data
.target
.cv_data
.uid
194 if obj
.type == 'MESH':
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]
202 _
.dims
[0] = obj
.cv_data
.v0
[0]
203 _
.dims
[1] = obj
.cv_data
.v0
[1]
204 _
.dims
[2] = obj
.cv_data
.v0
[2]
209 def draw_scene_helpers( obj
):
211 global cv_view_verts
, cv_view_colours
213 if obj
.type == 'MESH':
214 dims
= obj
.data
.cv_data
.v0
216 dims
= obj
.cv_data
.v0
219 c
= Vector((0,0,dims
[2]))
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)))
231 indices
= [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
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)]
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
)
248 def editor_interface( layout
, obj
):
250 layout
.prop( obj
.cv_data
, "target" )
253 layout
.label( text
=F
"(i) Data is stored in {mesh.name}" )
254 layout
.prop( mesh
.cv_data
, "v0", text
="Gate dimensions" )
260 # Purpose: player can reset here, its a safe place
261 # spawns can share the same name, the closest one will be picked
263 # when the world loads it will pick the one named 'start' first.
265 class classtype_spawn(Structure
):
268 _fields_
= [("pstr_alias",c_uint32
)]
270 def encode_obj(_
, node
,node_def
):
273 _
.pstr_alias
= encoder_process_pstr( node_def
['obj'].cv_data
.strp
)
277 def draw_scene_helpers( obj
):
279 global cv_view_verts
, cv_view_colours
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)]
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)]
300 def editor_interface( layout
, obj
):
302 layout
.prop( obj
.cv_data
, "strp", text
="Alias" )
308 # Purpose: Tells the game to draw water HERE, at this entity.
310 class classtype_water(Structure
):
313 _fields_
= [("temp",c_uint32
)]
315 def encode_obj(_
, node
,node_def
):
324 # Purpose: Defines a route node and links to up to two more nodes
326 class classtype_route_node(Structure
):
329 _fields_
= [("target",c_uint32
),
330 ("target1",c_uint32
)]
332 def encode_obj(_
, node
,node_def
):
335 obj
= node_def
['obj']
337 if obj
.cv_data
.target
!= None:
338 _
.target
= obj
.cv_data
.target
.cv_data
.uid
339 if obj
.cv_data
.target1
!= None:
340 _
.target1
= obj
.cv_data
.target1
.cv_data
.uid
344 def draw_scene_helpers( obj
):
346 global cv_view_verts
, cv_view_colours
348 sw
= Vector((0.4,0.4,0.4,0.2))
349 sw2
= Vector((1.5,0.2,0.2,0.0))
350 if obj
.cv_data
.target
!= None:
351 cv_draw_bpath( obj
, obj
.cv_data
.target
, sw
, sw
)
352 if obj
.cv_data
.target1
!= None:
353 cv_draw_bpath( obj
, obj
.cv_data
.target1
, sw
, sw
)
355 cv_draw_bhandle( obj
, 1.0, (0.8,0.8,0.8,1.0) )
356 cv_draw_bhandle( obj
, -1.0, (0.4,0.4,0.4,1.0) )
359 obj
.matrix_world
.to_quaternion() @ Vector((0,0,-6+1.5))
360 cv_draw_arrow( obj
.location
, p1
, sw
)
364 def editor_interface( layout
, obj
):
366 layout
.prop( obj
.cv_data
, "target", text
="Left" )
367 layout
.prop( obj
.cv_data
, "target1", text
="Right" )
373 # Purpose: Defines a route, its 'starting' point, and the colour to use for it
375 class classtype_route(Structure
):
378 _fields_
= [("id_start",c_uint32
),
379 ("pstr_name",c_uint32
),
380 ("colour",c_float
*3)]
382 def encode_obj(_
, node
,node_def
):
385 obj
= node_def
['obj']
387 _
.colour
[0] = obj
.cv_data
.colour
[0]
388 _
.colour
[1] = obj
.cv_data
.colour
[1]
389 _
.colour
[2] = obj
.cv_data
.colour
[2]
390 _
.pstr_name
= encoder_process_pstr( obj
.cv_data
.strp
)
392 if obj
.cv_data
.target
!= None:
393 _
.id_start
= obj
.cv_data
.target
.cv_data
.uid
397 def draw_scene_helpers( obj
):
399 global cv_view_verts
, cv_view_colours
, cv_view_course_i
401 if obj
.cv_data
.target
:
402 cv_draw_arrow( obj
.location
, obj
.cv_data
.target
.location
, [1,1,1,1] )
404 # Tries to simulate how we do it in the game
408 stack
[0] = obj
.cv_data
.target
410 loop_complete
= False
414 if stack_i
[si
-1] == 2:
419 if si
== 0: # Loop failed to complete
425 targets
= [None,None]
426 targets
[0] = node
.cv_data
.target
428 if node
.cv_data
.classtype
== 'classtype_route_node':
430 targets
[1] = node
.cv_data
.target1
433 nextnode
= targets
[stack_i
[si
-1]]
436 if nextnode
!= None: # branch
438 if nextnode
== stack
[0]: # Loop completed
447 if stack
[sj
] == nextnode
: # invalidated path
466 cc
= Vector((obj
.cv_data
.colour
[0],\
467 obj
.cv_data
.colour
[1],\
468 obj
.cv_data
.colour
[2],\
475 if stack
[sj
].cv_data
.classtype
== 'classtype_gate' and \
476 stack
[sk
].cv_data
.classtype
== 'classtype_gate':
478 dist
= (stack
[sj
].location
-stack
[sk
].location
).magnitude
479 cv_draw_sbpath( stack
[sj
], stack
[sk
], cc
*0.4, cc
, dist
, dist
)
482 cv_draw_bpath( stack
[sj
], stack
[sk
], cc
, cc
)
485 cv_view_course_i
+= 1
490 def editor_interface( layout
, obj
):
492 layout
.prop( obj
.cv_data
, "target", text
="'Start' from" )
493 layout
.prop( obj
.cv_data
, "colour" )
494 layout
.prop( obj
.cv_data
, "strp", text
="Name" )
500 # Purpose: links an mesh node to a type 11
502 class classtype_skin(Structure
):
505 _fields_
= [("skeleton",c_uint32
)]
507 def encode_obj(_
, node
,node_def
):
511 armature_def
= node_def
['linked_armature']
512 _
.skeleton
= armature_def
['obj'].cv_data
.uid
518 # Purpose: defines the allocation requirements for a skeleton
520 class classtype_skeleton(Structure
):
523 _fields_
= [("channels",c_uint32
),
524 ("ik_count",c_uint32
),
525 ("collider_count",c_uint32
),
526 ("anim_start",c_uint32
),
527 ("anim_count",c_uint32
)]
529 def encode_obj(_
, node
,node_def
):
533 _
.channels
= len( node_def
['bones'] )
534 _
.ik_count
= node_def
['ik_count']
535 _
.collider_count
= node_def
['collider_count']
536 _
.anim_start
= node_def
['anim_start']
537 _
.anim_count
= node_def
['anim_count']
544 # Purpose: intrinsic bone type, stores collision information and limits too
546 class classtype_bone(Structure
):
549 _fields_
= [("deform",c_uint32
),
550 ("ik_target",c_uint32
),
551 ("ik_pole",c_uint32
),
552 ("collider",c_uint32
),
553 ("use_limits",c_uint32
),
554 ("angle_limits",(c_float
*3)*2),
555 ("hitbox",(c_float
*3)*2)]
557 def encode_obj(_
, node
,node_def
):
561 armature_def
= node_def
['linked_armature']
562 obj
= node_def
['bone']
564 _
.deform
= node_def
['deform']
566 if 'ik_target' in node_def
:
568 _
.ik_target
= armature_def
['bones'].index( node_def
['ik_target'] )
569 _
.ik_pole
= armature_def
['bones'].index( node_def
['ik_pole'] )
574 if obj
.cv_data
.collider
:
577 _
.hitbox
[0][0] = obj
.cv_data
.v0
[0]
578 _
.hitbox
[0][1] = obj
.cv_data
.v0
[2]
579 _
.hitbox
[0][2] = -obj
.cv_data
.v1
[1]
580 _
.hitbox
[1][0] = obj
.cv_data
.v1
[0]
581 _
.hitbox
[1][1] = obj
.cv_data
.v1
[2]
582 _
.hitbox
[1][2] = -obj
.cv_data
.v0
[1]
588 _
.angle_limits
[0][0] = obj
.cv_data
.mins
[0]
589 _
.angle_limits
[0][1] = obj
.cv_data
.mins
[2]
590 _
.angle_limits
[0][2] = -obj
.cv_data
.maxs
[1]
591 _
.angle_limits
[1][0] = obj
.cv_data
.maxs
[0]
592 _
.angle_limits
[1][1] = obj
.cv_data
.maxs
[2]
593 _
.angle_limits
[1][2] = -obj
.cv_data
.mins
[1]
600 # Purpose: sends a signal to another entity
602 class classtype_trigger(Structure
):
605 _fields_
= [("target",c_uint32
)]
607 def encode_obj(_
, node
,node_def
):
610 if node_def
['obj'].cv_data
.target
:
611 _
.target
= node_def
['obj'].cv_data
.target
.cv_data
.uid
615 def draw_scene_helpers( obj
):
617 global cv_view_verts
, cv_view_colours
618 cv_draw_ucube( obj
.matrix_world
, [0,1,0,1] )
620 if obj
.cv_data
.target
:
621 cv_draw_arrow( obj
.location
, obj
.cv_data
.target
.location
, [1,1,1,1] )
625 def editor_interface( layout
, obj
):
627 layout
.prop( obj
.cv_data
, "target", text
="Triggers" )
633 # Purpose: Gives the player an achievement.
634 # No cheating! You shouldn't use this entity anyway, since only ME can
635 # add achievements to the steam ;)
637 class classtype_logic_achievement(Structure
):
640 _fields_
= [("pstr_name",c_uint32
)]
642 def encode_obj(_
, node
,node_def
):
645 _
.pstr_name
= encoder_process_pstr( node_def
['obj'].cv_data
.strp
)
649 def editor_interface( layout
, obj
):
651 layout
.prop( obj
.cv_data
, "strp", text
="Achievement ID" )
657 # Purpose: sends a signal to another entity
659 class classtype_logic_relay(Structure
):
662 _fields_
= [("targets",c_uint32
*4)]
664 def encode_obj(_
, node
,node_def
):
667 obj
= node_def
['obj']
668 if obj
.cv_data
.target
:
669 _
.targets
[0] = obj
.cv_data
.target
.cv_data
.uid
670 if obj
.cv_data
.target1
:
671 _
.targets
[1] = obj
.cv_data
.target1
.cv_data
.uid
672 if obj
.cv_data
.target2
:
673 _
.targets
[2] = obj
.cv_data
.target2
.cv_data
.uid
674 if obj
.cv_data
.target3
:
675 _
.targets
[3] = obj
.cv_data
.target3
.cv_data
.uid
679 def draw_scene_helpers( obj
):
681 global cv_view_verts
, cv_view_colours
683 if obj
.cv_data
.target
:
684 cv_draw_arrow( obj
.location
, obj
.cv_data
.target
.location
, [1,1,1,1] )
685 if obj
.cv_data
.target1
:
686 cv_draw_arrow( obj
.location
, obj
.cv_data
.target1
.location
, [1,1,1,1] )
687 if obj
.cv_data
.target2
:
688 cv_draw_arrow( obj
.location
, obj
.cv_data
.target2
.location
, [1,1,1,1] )
689 if obj
.cv_data
.target3
:
690 cv_draw_arrow( obj
.location
, obj
.cv_data
.target3
.location
, [1,1,1,1] )
694 def editor_interface( layout
, obj
):
696 layout
.prop( obj
.cv_data
, "target", text
="Triggers" )
697 layout
.prop( obj
.cv_data
, "target1", text
="Triggers" )
698 layout
.prop( obj
.cv_data
, "target2", text
="Triggers" )
699 layout
.prop( obj
.cv_data
, "target3", text
="Triggers" )
705 # Purpose: Plays some audio (44100hz .ogg vorbis only)
706 # NOTE: There is a 32mb limit on the audio buffer, world audio is
707 # decompressed and stored in signed 16 bit integers (2 bytes)
710 # volume: not used if has 3D flag
712 # AUDIO_FLAG_LOOP 0x1
713 # AUDIO_FLAG_ONESHOT 0x2 (DONT USE THIS, it breaks semaphores)
714 # AUDIO_FLAG_SPACIAL_3D 0x4 (Probably what you want)
715 # AUDIO_FLAG_AUTO_START 0x8 (Play when the world starts)
717 # the rest are just internal flags, only use the above 3.
719 class classtype_audio(Structure
):
722 _fields_
= [("pstr_file",c_uint32
),
726 def encode_obj(_
, node
,node_def
):
730 obj
= node_def
['obj']
732 _
.pstr_file
= encoder_process_pstr( obj
.cv_data
.strp
)
735 if obj
.cv_data
.bp0
: flags |
= 0x1
736 if obj
.cv_data
.bp1
: flags |
= 0x4
737 if obj
.cv_data
.bp2
: flags |
= 0x8
740 _
.volume
= obj
.cv_data
.fltp
744 def editor_interface( layout
, obj
):
746 layout
.prop( obj
.cv_data
, "strp" )
748 layout
.prop( obj
.cv_data
, "bp0", text
= "Looping" )
749 layout
.prop( obj
.cv_data
, "bp1", text
= "3D Audio" )
750 layout
.prop( obj
.cv_data
, "bp2", text
= "Auto Start" )
754 def draw_scene_helpers( obj
):
756 global cv_view_verts
, cv_view_colours
758 cv_draw_sphere( obj
.location
, obj
.scale
[0], [1,1,0,1] )
762 # ---------------------------------------------------------------------------- #
766 # ---------------------------------------------------------------------------- #
768 # Current encoder state
774 def encoder_init( collection
):
780 # The actual file header
782 'header': mdl_header(),
786 'pack_textures': collection
.cv_data
.pack_textures
,
788 # Compiled data chunks (each can be read optionally by the client)
792 #1---------------------------------
793 'node': [], # Metadata 'chunk'
798 'entdata': bytearray(), # variable width
799 'strings': bytearray(), # .
800 #2---------------------------------
801 'keyframe': [], # Animations
802 #3---------------------------------
803 'vertex': [], # Mesh data
805 #4---------------------------------
806 'pack': bytearray() # Other generic packed data
809 # All objects of the model in their final heirachy
815 # Allows us to reuse definitions
819 'material_cache': {},
823 g_encoder
['header'].identifier
= 0xABCD0000
824 g_encoder
['header'].version
= 1
826 # Add fake NoneID material and texture
828 none_material
= mdl_material()
829 none_material
.pstr_name
= encoder_process_pstr( "" )
830 none_material
.texture_id
= 0
832 none_texture
= mdl_texture()
833 none_texture
.pstr_name
= encoder_process_pstr( "" )
834 none_texture
.pack_offset
= 0
835 none_texture
.pack_length
= 0
837 g_encoder
['data']['material'] += [none_material
]
838 g_encoder
['data']['texture'] += [none_texture
]
840 g_encoder
['data']['pack'].extend( b
'datapack\0\0\0\0\0\0\0\0' )
855 root
.pstr_name
= encoder_process_pstr('')
856 root
.submesh_start
= 0
857 root
.submesh_count
= 0
860 root
.parent
= 0xffffffff
862 g_encoder
['data']['node'] += [root
]
866 # fill with 0x00 until a multiple of align. Returns how many bytes it added
868 def bytearray_align_to( buffer, align
, offset
=0 ):
872 while ((len(buffer)+offset
) % align
) != 0:
874 buffer.extend( b
'\0' )
881 # Add a string to the string buffer except if it already exists there then we
882 # just return its ID.
884 def encoder_process_pstr( s
):
888 cache
= g_encoder
['string_cache']
893 cache
[s
] = len( g_encoder
['data']['strings'] )
895 buffer = g_encoder
['data']['strings']
896 buffer.extend( s
.encode('utf-8') )
897 buffer.extend( b
'\0' )
899 bytearray_align_to( buffer, 4 )
903 def get_texture_resource_name( img
):
905 return os
.path
.splitext( img
.name
)[0]
910 def encoder_process_texture( img
):
917 cache
= g_encoder
['texture_cache']
918 buffer = g_encoder
['data']['texture']
919 pack
= g_encoder
['data']['pack']
921 name
= get_texture_resource_name( img
)
926 cache
[name
] = len( buffer )
929 tex
.pstr_name
= encoder_process_pstr( name
)
931 if g_encoder
['pack_textures']:
933 tex
.pack_offset
= len( pack
)
934 pack
.extend( qoi_encode( img
) )
935 tex
.pack_length
= len( pack
) - tex
.pack_offset
944 def material_tex_image(v
):
954 cxr_graph_mapping
= \
956 # Default shader setup
963 "image": "tex_diffuse"
967 "Color1": material_tex_image("tex_diffuse"),
968 "Color2": material_tex_image("tex_decal")
975 "Color": material_tex_image("tex_normal")
981 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
983 def material_info(mat
):
987 # Using the cv_graph_mapping as a reference, go through the shader
988 # graph and gather all $props from it.
990 def _graph_read( node_def
, node
=None, depth
=0 ):
999 _graph_read
.extracted
= []
1001 for node_idname
in node_def
:
1003 for n
in mat
.node_tree
.nodes
:
1005 if n
.name
== node_idname
:
1007 node_def
= node_def
[node_idname
]
1015 for link
in node_def
:
1017 link_def
= node_def
[link
]
1019 if isinstance( link_def
, dict ):
1021 node_link
= node
.inputs
[link
]
1023 if node_link
.is_linked
:
1025 # look for definitions for the connected node type
1027 from_node
= node_link
.links
[0].from_node
1029 node_name
= from_node
.name
.split('.')[0]
1030 if node_name
in link_def
:
1032 from_node_def
= link_def
[ node_name
]
1034 _graph_read( from_node_def
, from_node
, depth
+1 )
1038 # TODO: Make a warning for this?
1042 if "default" in link_def
:
1044 prop
= link_def
['default']
1045 info
[prop
] = node_link
.default_value
1052 info
[prop
] = getattr( node
, link
)
1057 _graph_read( cxr_graph_mapping
)
1061 # Add a material to the material buffer. Returns 0 (None ID) if invalid
1063 def encoder_process_material( mat
):
1070 cache
= g_encoder
['material_cache']
1071 buffer = g_encoder
['data']['material']
1073 if mat
.name
in cache
:
1074 return cache
[mat
.name
]
1076 cache
[mat
.name
] = len( buffer )
1078 dest
= mdl_material()
1079 dest
.pstr_name
= encoder_process_pstr( mat
.name
)
1082 if mat
.cv_data
.skate_surface
: flags |
= 0x1
1083 if mat
.cv_data
.collision
: flags |
= 0x2
1084 if mat
.cv_data
.grow_grass
: flags |
= 0x4
1087 if mat
.cv_data
.surface_prop
== 'concrete': dest
.surface_prop
= 0
1088 if mat
.cv_data
.surface_prop
== 'wood': dest
.surface_prop
= 1
1089 if mat
.cv_data
.surface_prop
== 'grass': dest
.surface_prop
= 2
1091 if mat
.cv_data
.shader
== 'standard': dest
.shader
= 0
1092 if mat
.cv_data
.shader
== 'standard_cutout': dest
.shader
= 1
1093 if mat
.cv_data
.shader
== 'terrain_blend':
1097 dest
.colour
[0] = pow( mat
.cv_data
.sand_colour
[0], 1.0/2.2 )
1098 dest
.colour
[1] = pow( mat
.cv_data
.sand_colour
[1], 1.0/2.2 )
1099 dest
.colour
[2] = pow( mat
.cv_data
.sand_colour
[2], 1.0/2.2 )
1100 dest
.colour
[3] = 1.0
1102 dest
.colour1
[0] = mat
.cv_data
.blend_offset
[0]
1103 dest
.colour1
[1] = mat
.cv_data
.blend_offset
[1]
1106 if mat
.cv_data
.shader
== 'vertex_blend':
1110 dest
.colour1
[0] = mat
.cv_data
.blend_offset
[0]
1111 dest
.colour1
[1] = mat
.cv_data
.blend_offset
[1]
1114 if mat
.cv_data
.shader
== 'water':
1118 dest
.colour
[0] = pow( mat
.cv_data
.shore_colour
[0], 1.0/2.2 )
1119 dest
.colour
[1] = pow( mat
.cv_data
.shore_colour
[1], 1.0/2.2 )
1120 dest
.colour
[2] = pow( mat
.cv_data
.shore_colour
[2], 1.0/2.2 )
1121 dest
.colour
[3] = 1.0
1122 dest
.colour1
[0] = pow( mat
.cv_data
.ocean_colour
[0], 1.0/2.2 )
1123 dest
.colour1
[1] = pow( mat
.cv_data
.ocean_colour
[1], 1.0/2.2 )
1124 dest
.colour1
[2] = pow( mat
.cv_data
.ocean_colour
[2], 1.0/2.2 )
1125 dest
.colour1
[3] = 1.0
1128 inf
= material_info( mat
)
1130 if mat
.cv_data
.shader
== 'standard' or \
1131 mat
.cv_data
.shader
== 'standard_cutout' or \
1132 mat
.cv_data
.shader
== 'terrain_blend' or \
1133 mat
.cv_data
.shader
== 'vertex_blend':
1135 if 'tex_diffuse' in inf
:
1136 dest
.tex_diffuse
= encoder_process_texture(inf
['tex_diffuse'])
1140 return cache
[mat
.name
]
1143 # Create a tree structure containing all the objects in the collection
1145 def encoder_build_scene_graph( collection
):
1149 print( " creating scene graph" )
1153 graph
= g_encoder
['scene_graph']
1154 graph_lookup
= g_encoder
['graph_lookup']
1157 graph
["children"] = []
1159 graph
["parent"] = None
1164 uid
= g_encoder
['uid_count']
1165 g_encoder
['uid_count'] += 1
1169 for obj
in collection
.all_objects
:
1171 if obj
.parent
: continue
1173 def _extend( p
, n
, d
):
1178 tree
["children"] = []
1184 # Descend into amature
1186 if n
.type == 'ARMATURE':
1188 tree
["bones"] = [None] # None is the root transform
1189 tree
["ik_count"] = 0
1190 tree
["collider_count"] = 0
1192 # Here also collects some information about constraints, ik and
1193 # counts colliders for the armature.
1195 def _extendb( p
, n
, d
):
1201 btree
["linked_armature"] = tree
1202 btree
["uid"] = _new_uid()
1203 btree
["children"] = []
1206 tree
["bones"] += [n
.name
]
1208 for c
in n
.children
:
1210 _extendb( btree
, c
, d
+1 )
1213 for c
in tree
['obj'].pose
.bones
[n
.name
].constraints
:
1217 btree
["ik_target"] = c
.subtarget
1218 btree
["ik_pole"] = c
.pole_subtarget
1219 tree
["ik_count"] += 1
1223 if n
.cv_data
.collider
:
1224 tree
['collider_count'] += 1
1226 btree
['deform'] = n
.use_deform
1227 p
['children'] += [btree
]
1230 for b
in n
.data
.bones
:
1232 _extendb( tree
, b
, d
+1 )
1235 # Recurse into children of this object
1237 for obj1
in n
.children
:
1240 for c1
in obj1
.users_collection
:
1242 if c1
== collection
:
1244 _extend( tree
, obj1
, d
+1 )
1250 p
["children"] += [tree
]
1251 graph_lookup
[n
] = tree
1255 _extend( graph
, obj
, 1 )
1261 # Kind of a useless thing i made but it looks cool and adds complexity!!1
1263 def encoder_graph_iterator( root
):
1265 for c
in root
['children']:
1268 yield from encoder_graph_iterator(c
)
1273 # Push a vertex into the model file, or return a cached index (c_uint32)
1275 def encoder_vertex_push( vertex_reference
, co
,norm
,uv
,colour
,groups
,weights
):
1278 buffer = g_encoder
['data']['vertex']
1281 m
= float(10**TOLERENCE
)
1283 # Would be nice to know if this can be done faster than it currently runs,
1286 key
= (int(co
[0]*m
+0.5),
1294 colour
[0]*m
+0.5, # these guys are already quantized
1295 colour
[1]*m
+0.5, # .
1296 colour
[2]*m
+0.5, # .
1297 colour
[3]*m
+0.5, # .
1298 weights
[0]*m
+0.5, # v
1307 if key
in vertex_reference
:
1308 return vertex_reference
[key
]
1311 index
= c_uint32( len(vertex_reference
) )
1312 vertex_reference
[key
] = index
1320 v
.norm
[2] = -norm
[1]
1323 v
.colour
[0] = colour
[0]
1324 v
.colour
[1] = colour
[1]
1325 v
.colour
[2] = colour
[2]
1326 v
.colour
[3] = colour
[3]
1327 v
.weights
[0] = weights
[0]
1328 v
.weights
[1] = weights
[1]
1329 v
.weights
[2] = weights
[2]
1330 v
.weights
[3] = weights
[3]
1331 v
.groups
[0] = groups
[0]
1332 v
.groups
[1] = groups
[1]
1333 v
.groups
[2] = groups
[2]
1334 v
.groups
[3] = groups
[3]
1342 # Compile a mesh (or use one from the cache) onto node, based on node_def
1345 def encoder_compile_mesh( node
, node_def
):
1349 graph
= g_encoder
['scene_graph']
1350 graph_lookup
= g_encoder
['graph_lookup']
1351 mesh_cache
= g_encoder
['mesh_cache']
1352 obj
= node_def
['obj']
1354 can_use_cache
= True
1356 # Check for modifiers that typically change the data per-instance
1357 # there is no well defined rule for the choices here, its just what i've
1358 # needed while producing the game.
1360 # It may be possible to detect these cases automatically.
1362 for mod
in obj
.modifiers
:
1364 if mod
.type == 'DATA_TRANSFER' or mod
.type == 'SHRINKWRAP' or \
1365 mod
.type == 'BOOLEAN' or mod
.type == 'CURVE' or \
1366 mod
.type == 'ARRAY':
1368 can_use_cache
= False
1371 if mod
.type == 'ARMATURE':
1372 armature_def
= graph_lookup
[mod
.object]
1374 # Check the cache first
1376 if can_use_cache
and (obj
.data
.name
in mesh_cache
):
1378 ref
= mesh_cache
[obj
.data
.name
]
1379 node
.submesh_start
= ref
.submesh_start
1380 node
.submesh_count
= ref
.submesh_count
1384 # Compile a whole new mesh
1386 node
.submesh_start
= len( g_encoder
['data']['submesh'] )
1387 node
.submesh_count
= 0
1389 dgraph
= bpy
.context
.evaluated_depsgraph_get()
1390 data
= obj
.evaluated_get(dgraph
).data
1391 data
.calc_loop_triangles()
1392 data
.calc_normals_split()
1394 # Mesh is split into submeshes based on their material
1396 mat_list
= data
.materials
if len(data
.materials
) > 0 else [None]
1397 for material_id
, mat
in enumerate(mat_list
):
1402 sm
.indice_start
= len( g_encoder
['data']['indice'] )
1403 sm
.vertex_start
= len( g_encoder
['data']['vertex'] )
1406 sm
.material_id
= encoder_process_material( mat
)
1410 sm
.bbx
[0][i
] = 999999
1411 sm
.bbx
[1][i
] = -999999
1414 # Keep a reference to very very very similar vertices
1416 vertex_reference
= {}
1418 # Write the vertex / indice data
1420 for tri_index
, tri
in enumerate(data
.loop_triangles
):
1422 if tri
.material_index
!= material_id
:
1427 vert
= data
.vertices
[tri
.vertices
[j
]]
1429 vi
= data
.loops
[li
].vertex_index
1431 # Gather vertex information
1434 norm
= data
.loops
[li
].normal
1436 colour
= (255,255,255,255)
1443 uv
= data
.uv_layers
.active
.data
[li
].uv
1447 if data
.vertex_colors
:
1449 colour
= data
.vertex_colors
.active
.data
[li
].color
1450 colour
= (int(colour
[0]*255.0),\
1451 int(colour
[1]*255.0),\
1452 int(colour
[2]*255.0),\
1453 int(colour
[3]*255.0))
1456 # Weight groups: truncates to the 3 with the most influence. The
1457 # fourth bone ID is never used by the shader so it is
1462 src_groups
= [_
for _
in data
.vertices
[vi
].groups \
1463 if obj
.vertex_groups
[_
.group
].name
in \
1464 armature_def
['bones']]
1466 weight_groups
= sorted( src_groups
, key
= \
1467 lambda a
: a
.weight
, reverse
=True )
1471 if len(weight_groups
) > ml
:
1473 g
= weight_groups
[ml
]
1474 name
= obj
.vertex_groups
[g
.group
].name
1477 weights
[ml
] = weight
1478 groups
[ml
] = armature_def
['bones'].index(name
)
1483 if len(weight_groups
) > 0:
1485 inv_norm
= (1.0/tot
) * 65535.0
1488 weights
[ml
] = int( weights
[ml
] * inv_norm
)
1489 weights
[ml
] = min( weights
[ml
], 65535 )
1490 weights
[ml
] = max( weights
[ml
], 0 )
1494 # Add vertex and expand bound box
1496 index
= encoder_vertex_push( vertex_reference
, co
, \
1502 g_encoder
['data']['indice'] += [index
]
1506 # How many unique verts did we add in total
1508 sm
.vertex_count
= len(g_encoder
['data']['vertex']) - sm
.vertex_start
1509 sm
.indice_count
= len(g_encoder
['data']['indice']) - sm
.indice_start
1511 # Make sure bounding box isn't -inf -> inf if no vertices
1513 if sm
.vertex_count
== 0:
1519 for j
in range(sm
.vertex_count
):
1521 vert
= g_encoder
['data']['vertex'][ sm
.vertex_start
+ j
]
1525 sm
.bbx
[0][i
] = min( sm
.bbx
[0][i
], vert
.co
[i
] )
1526 sm
.bbx
[1][i
] = max( sm
.bbx
[1][i
], vert
.co
[i
] )
1531 # Add submesh to encoder
1533 g_encoder
['data']['submesh'] += [sm
]
1534 node
.submesh_count
+= 1
1538 # Save a reference to this node since we want to reuse the submesh indices
1540 g_encoder
['mesh_cache'][obj
.data
.name
] = node
1544 def encoder_compile_ent_as( name
, node
, node_def
):
1548 if name
== 'classtype_none':
1554 elif name
not in globals():
1556 print( "Classtype '" +name
+ "' is unknown!" )
1560 buffer = g_encoder
['data']['entdata']
1561 node
.offset
= len(buffer)
1563 cl
= globals()[ name
]
1565 inst
.encode_obj( node
, node_def
)
1567 buffer.extend( bytearray(inst
) )
1568 bytearray_align_to( buffer, 4 )
1571 # Compiles animation data into model and gives us some extra node_def entries
1573 def encoder_compile_armature( node
, node_def
):
1577 entdata
= g_encoder
['data']['entdata']
1578 animdata
= g_encoder
['data']['anim']
1579 keyframedata
= g_encoder
['data']['keyframe']
1580 mesh_cache
= g_encoder
['mesh_cache']
1581 obj
= node_def
['obj']
1582 bones
= node_def
['bones']
1585 node_def
['anim_start'] = len(animdata
)
1586 node_def
['anim_count'] = 0
1590 if obj
.animation_data
:
1592 # So we can restore later
1594 previous_frame
= bpy
.context
.scene
.frame_current
1595 previous_action
= obj
.animation_data
.action
1596 POSE_OR_REST_CACHE
= obj
.data
.pose_position
1597 obj
.data
.pose_position
= 'POSE'
1599 for NLALayer
in obj
.animation_data
.nla_tracks
:
1601 for NLAStrip
in NLALayer
.strips
:
1605 for a
in bpy
.data
.actions
:
1607 if a
.name
== NLAStrip
.name
:
1609 obj
.animation_data
.action
= a
1614 # Clip to NLA settings
1616 anim_start
= int(NLAStrip
.action_frame_start
)
1617 anim_end
= int(NLAStrip
.action_frame_end
)
1621 anim
= mdl_animation()
1622 anim
.pstr_name
= encoder_process_pstr( NLAStrip
.action
.name
)
1624 anim
.offset
= len(keyframedata
)
1625 anim
.length
= anim_end
-anim_start
1627 # Export the keyframes
1628 for frame
in range(anim_start
,anim_end
):
1630 bpy
.context
.scene
.frame_set(frame
)
1632 for bone_name
in bones
:
1634 for pb
in obj
.pose
.bones
:
1636 if pb
.name
!= bone_name
: continue
1638 rb
= obj
.data
.bones
[ bone_name
]
1640 # relative bone matrix
1641 if rb
.parent
is not None:
1643 offset_mtx
= rb
.parent
.matrix_local
1644 offset_mtx
= offset_mtx
.inverted_safe() @ \
1647 inv_parent
= pb
.parent
.matrix
@ offset_mtx
1648 inv_parent
.invert_safe()
1649 fpm
= inv_parent
@ pb
.matrix
1653 bone_mtx
= rb
.matrix
.to_4x4()
1654 local_inv
= rb
.matrix_local
.inverted_safe()
1655 fpm
= bone_mtx
@ local_inv
@ pb
.matrix
1658 loc
, rot
, sca
= fpm
.decompose()
1661 final_pos
= Vector(( loc
[0], loc
[2], -loc
[1] ))
1664 lc_m
= pb
.matrix_channel
.to_3x3()
1665 if pb
.parent
is not None:
1667 smtx
= pb
.parent
.matrix_channel
.to_3x3()
1668 lc_m
= smtx
.inverted() @ lc_m
1670 rq
= lc_m
.to_quaternion()
1673 kf
.co
[0] = final_pos
[0]
1674 kf
.co
[1] = final_pos
[1]
1675 kf
.co
[2] = final_pos
[2]
1687 keyframedata
+= [kf
]
1693 # Add to animation buffer
1696 node_def
['anim_count'] += 1
1700 status_name
= F
" " + " |"*(node_def
['depth']-1)
1701 print( F
"{status_name} | *anim: {NLAStrip.action.name}" )
1705 # Restore context to how it was before
1707 bpy
.context
.scene
.frame_set( previous_frame
)
1708 obj
.animation_data
.action
= previous_action
1709 obj
.data
.pose_position
= POSE_OR_REST_CACHE
1713 # We are trying to compile this node_def
1715 def encoder_process_definition( node_def
):
1719 # data sources for object/bone are taken differently
1721 if 'obj' in node_def
:
1723 obj
= node_def
['obj']
1725 obj_co
= obj
.location
1727 if obj_type
== 'ARMATURE':
1728 obj_classtype
= 'classtype_skeleton'
1731 obj_classtype
= obj
.cv_data
.classtype
1733 # Check for armature deform
1735 for mod
in obj
.modifiers
:
1737 if mod
.type == 'ARMATURE':
1739 obj_classtype
= 'classtype_skin'
1741 # Make sure to freeze armature in rest while we collect
1742 # vertex information
1744 armature_def
= g_encoder
['graph_lookup'][mod
.object]
1745 POSE_OR_REST_CACHE
= armature_def
['obj'].data
.pose_position
1746 armature_def
['obj'].data
.pose_position
= 'REST'
1747 node_def
['linked_armature'] = armature_def
1754 elif 'bone' in node_def
:
1756 obj
= node_def
['bone']
1758 obj_co
= obj
.head_local
1759 obj_classtype
= 'classtype_bone'
1765 node
.pstr_name
= encoder_process_pstr( obj
.name
)
1767 if node_def
["parent"]:
1768 node
.parent
= node_def
["parent"]["uid"]
1772 node
.co
[0] = obj_co
[0]
1773 node
.co
[1] = obj_co
[2]
1774 node
.co
[2] = -obj_co
[1]
1776 # Convert rotation quat to our space type
1778 quat
= obj
.matrix_local
.to_quaternion()
1781 node
.q
[2] = -quat
[2]
1784 # Bone scale is just a vector to the tail
1786 if obj_type
== 'BONE':
1788 node
.s
[0] = obj
.tail_local
[0] - node
.co
[0]
1789 node
.s
[1] = obj
.tail_local
[2] - node
.co
[1]
1790 node
.s
[2] = -obj
.tail_local
[1] - node
.co
[2]
1794 node
.s
[0] = obj
.scale
[0]
1795 node
.s
[1] = obj
.scale
[2]
1796 node
.s
[2] = obj
.scale
[1]
1801 tot_uid
= g_encoder
['uid_count']-1
1802 obj_uid
= node_def
['uid']
1803 obj_depth
= node_def
['depth']-1
1805 status_id
= F
" [{obj_uid: 3}/{tot_uid}]" + " |"*obj_depth
1806 status_name
= status_id
+ F
" L {obj.name}"
1808 if obj_classtype
!= 'classtype_none': status_type
= obj_classtype
1809 else: status_type
= obj_type
1811 status_parent
= F
"{node.parent: 3}"
1814 if obj_classtype
== 'classtype_skin':
1815 status_armref
= F
" [armature -> {armature_def['obj'].cv_data.uid}]"
1817 print(F
"{status_name:<32} {status_type:<22} {status_parent} {status_armref}")
1819 # Process mesh if needed
1821 if obj_type
== 'MESH':
1823 encoder_compile_mesh( node
, node_def
)
1825 elif obj_type
== 'ARMATURE':
1827 encoder_compile_armature( node
, node_def
)
1830 encoder_compile_ent_as( obj_classtype
, node
, node_def
)
1832 # Make sure to reset the armature we just mucked about with
1834 if obj_classtype
== 'classtype_skin':
1835 armature_def
['obj'].data
.pose_position
= POSE_OR_REST_CACHE
1837 g_encoder
['data']['node'] += [node
]
1840 # The post processing step or the pre processing to the writing step
1842 def encoder_write_to_file( path
):
1846 # Compile down to a byte array
1848 header
= g_encoder
['header']
1849 file_pos
= sizeof(header
)
1850 file_data
= bytearray()
1851 print( " Compositing data arrays" )
1853 for array_name
in g_encoder
['data']:
1855 file_pos
+= bytearray_align_to( file_data
, 16, sizeof(header
) )
1856 arr
= g_encoder
['data'][array_name
]
1858 setattr( header
, array_name
+ "_offset", file_pos
)
1860 print( F
" {array_name:<16} @{file_pos:> 8X}[{len(arr)}]" )
1862 if isinstance( arr
, bytearray
):
1864 setattr( header
, array_name
+ "_size", len(arr
) )
1866 file_data
.extend( arr
)
1867 file_pos
+= len(arr
)
1871 setattr( header
, array_name
+ "_count", len(arr
) )
1875 bbytes
= bytearray(item
)
1876 file_data
.extend( bbytes
)
1877 file_pos
+= sizeof(item
)
1882 # This imperitive for this field to be santized in the future!
1884 header
.file_length
= file_pos
1886 print( " Writing file" )
1887 # Write header and data chunk to file
1889 fp
= open( path
, "wb" )
1890 fp
.write( bytearray( header
) )
1891 fp
.write( file_data
)
1895 # Main compiler, uses string as the identifier for the collection
1897 def write_model(collection_name
):
1900 print( F
"Model graph | Create mode '{collection_name}'" )
1902 collection
= bpy
.data
.collections
[collection_name
]
1904 encoder_init( collection
)
1905 encoder_build_scene_graph( collection
)
1909 print( " Comping objects" )
1910 it
= encoder_graph_iterator( g_encoder
['scene_graph'] )
1912 encoder_process_definition( node_def
)
1917 path
= F
"/home/harry/Documents/carve/models_src/{collection_name}.mdl"
1918 encoder_write_to_file( path
)
1920 print( F
"Completed {collection_name}.mdl" )
1923 # ---------------------------------------------------------------------------- #
1927 # ---------------------------------------------------------------------------- #
1929 cv_view_draw_handler
= None
1930 cv_view_shader
= gpu
.shader
.from_builtin('3D_SMOOTH_COLOR')
1932 cv_view_colours
= []
1933 cv_view_course_i
= 0
1935 # Draw axis alligned sphere at position with radius
1937 def cv_draw_sphere( pos
, radius
, colour
):
1939 global cv_view_verts
, cv_view_colours
1941 ly
= pos
+ Vector((0,0,radius
))
1942 lx
= pos
+ Vector((0,radius
,0))
1943 lz
= pos
+ Vector((0,0,radius
))
1945 pi
= 3.14159265358979323846264
1949 t
= ((i
+1.0) * 1.0/16.0) * pi
* 2.0
1953 py
= pos
+ Vector((s
*radius
,0.0,c
*radius
))
1954 px
= pos
+ Vector((s
*radius
,c
*radius
,0.0))
1955 pz
= pos
+ Vector((0.0,s
*radius
,c
*radius
))
1957 cv_view_verts
+= [ px
, lx
]
1958 cv_view_verts
+= [ py
, ly
]
1959 cv_view_verts
+= [ pz
, lz
]
1961 cv_view_colours
+= [ colour
, colour
, colour
, colour
, colour
, colour
]
1970 # Draw transformed -1 -> 1 cube
1972 def cv_draw_ucube( transform
, colour
):
1974 global cv_view_verts
, cv_view_colours
1976 a
= Vector((-1,-1,-1))
1980 vs
[0] = transform
@ Vector((a
[0], a
[1], a
[2]))
1981 vs
[1] = transform
@ Vector((a
[0], b
[1], a
[2]))
1982 vs
[2] = transform
@ Vector((b
[0], b
[1], a
[2]))
1983 vs
[3] = transform
@ Vector((b
[0], a
[1], a
[2]))
1984 vs
[4] = transform
@ Vector((a
[0], a
[1], b
[2]))
1985 vs
[5] = transform
@ Vector((a
[0], b
[1], b
[2]))
1986 vs
[6] = transform
@ Vector((b
[0], b
[1], b
[2]))
1987 vs
[7] = transform
@ Vector((b
[0], a
[1], b
[2]))
1989 indices
= [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
1990 (0,4),(1,5),(2,6),(3,7)]
1996 cv_view_verts
+= [(v0
[0],v0
[1],v0
[2])]
1997 cv_view_verts
+= [(v1
[0],v1
[1],v1
[2])]
1998 cv_view_colours
+= [(0,1,0,1),(0,1,0,1)]
2003 # Draw line with colour
2005 def cv_draw_line( p0
, p1
, colour
):
2007 global cv_view_verts
, cv_view_colours
2009 cv_view_verts
+= [p0
,p1
]
2010 cv_view_colours
+= [colour
, colour
]
2014 # Draw line with colour(s)
2016 def cv_draw_line2( p0
, p1
, c0
, c1
):
2018 global cv_view_verts
, cv_view_colours
2020 cv_view_verts
+= [p0
,p1
]
2021 cv_view_colours
+= [c0
,c1
]
2025 # Just the tx because we dont really need ty for this app
2027 def cv_tangent_basis_tx( n
, tx
):
2029 if abs( n
[0] ) >= 0.57735027:
2045 # Draw coloured arrow
2047 def cv_draw_arrow( p0
, p1
, c0
):
2049 global cv_view_verts
, cv_view_colours
2055 tx
= Vector((1,0,0))
2056 cv_tangent_basis_tx( n
, tx
)
2058 cv_view_verts
+= [p0
,p1
, midpt
+(tx
-n
)*0.15,midpt
, midpt
+(-tx
-n
)*0.15,midpt
]
2059 cv_view_colours
+= [c0
,c0
,c0
,c0
,c0
,c0
]
2063 # Drawhandles of a bezier control point
2065 def cv_draw_bhandle( obj
, direction
, colour
):
2067 global cv_view_verts
, cv_view_colours
2070 h0
= obj
.matrix_world
@ Vector((0,direction
,0))
2072 cv_view_verts
+= [p0
]
2073 cv_view_verts
+= [h0
]
2074 cv_view_colours
+= [colour
,colour
]
2078 # Draw a bezier curve (at fixed resolution 10)
2080 def cv_draw_bezier( p0
,h0
,p1
,h1
,c0
,c1
):
2082 global cv_view_verts
, cv_view_colours
2092 p
=ttt
*p1
+(3*tt
-3*ttt
)*h1
+(3*ttt
-6*tt
+3*t
)*h0
+(3*tt
-ttt
-3*t
+1)*p0
2094 cv_view_verts
+= [(last
[0],last
[1],last
[2])]
2095 cv_view_verts
+= [(p
[0],p
[1],p
[2])]
2096 cv_view_colours
+= [c0
*a0
+c1
*(1-a0
),c0
*a0
+c1
*(1-a0
)]
2103 # I think this one extends the handles of the bezier otwards......
2105 def cv_draw_sbpath( o0
,o1
,c0
,c1
,s0
,s1
):
2107 global cv_view_course_i
2109 offs
= ((cv_view_course_i
% 2)*2-1) * cv_view_course_i
* 0.02
2111 p0
= o0
.matrix_world
@ Vector((offs
, 0,0))
2112 h0
= o0
.matrix_world
@ Vector((offs
, s0
,0))
2113 p1
= o1
.matrix_world
@ Vector((offs
, 0,0))
2114 h1
= o1
.matrix_world
@ Vector((offs
,-s1
,0))
2116 cv_draw_bezier( p0
,h0
,p1
,h1
,c0
,c1
)
2120 # Flush the lines buffers. This is called often because god help you if you want
2121 # to do fixed, fast buffers in this catastrophic programming language.
2123 def cv_draw_lines():
2125 global cv_view_shader
, cv_view_verts
, cv_view_colours
2127 if len(cv_view_verts
) < 2:
2130 lines
= batch_for_shader(\
2131 cv_view_shader
, 'LINES', \
2132 { "pos":cv_view_verts
, "color":cv_view_colours
})
2134 lines
.draw( cv_view_shader
)
2137 cv_view_colours
= []
2140 # I dont remember what this does exactly
2142 def cv_draw_bpath( o0
,o1
,c0
,c1
):
2144 cv_draw_sbpath( o0
,o1
,c0
,c1
,1.0,1.0 )
2147 # Semi circle to show the limit. and some lines
2149 def draw_limit( obj
, center
, major
, minor
, amin
, amax
, colour
):
2151 global cv_view_verts
, cv_view_colours
2160 a0
= amin
*(1.0-t0
)+amax
*t0
2161 a1
= amin
*(1.0-t1
)+amax
*t1
2163 p0
= center
+ major
*f
*math
.cos(a0
) + minor
*f
*math
.sin(a0
)
2164 p1
= center
+ major
*f
*math
.cos(a1
) + minor
*f
*math
.sin(a1
)
2166 p0
=obj
.matrix_world
@ p0
2167 p1
=obj
.matrix_world
@ p1
2168 cv_view_verts
+= [p0
,p1
]
2169 cv_view_colours
+= [colour
,colour
]
2173 cv_view_verts
+= [p0
,center
]
2174 cv_view_colours
+= [colour
,colour
]
2178 cv_view_verts
+= [p1
,center
]
2179 cv_view_colours
+= [colour
,colour
]
2183 cv_view_verts
+= [center
+major
*1.2*f
,center
+major
*f
*0.8]
2184 cv_view_colours
+= [colour
,colour
]
2189 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2191 def draw_skeleton_helpers( obj
):
2193 global cv_view_verts
, cv_view_colours
2195 for bone
in obj
.data
.bones
:
2197 if bone
.cv_data
.collider
and (obj
.data
.pose_position
== 'REST'):
2204 vs
[0]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+a
[1],c
[2]+a
[2]))
2205 vs
[1]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+b
[1],c
[2]+a
[2]))
2206 vs
[2]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+b
[1],c
[2]+a
[2]))
2207 vs
[3]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+a
[1],c
[2]+a
[2]))
2208 vs
[4]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+a
[1],c
[2]+b
[2]))
2209 vs
[5]=obj
.matrix_world
@Vector((c
[0]+a
[0],c
[1]+b
[1],c
[2]+b
[2]))
2210 vs
[6]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+b
[1],c
[2]+b
[2]))
2211 vs
[7]=obj
.matrix_world
@Vector((c
[0]+b
[0],c
[1]+a
[1],c
[2]+b
[2]))
2213 indices
= [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2214 (0,4),(1,5),(2,6),(3,7)]
2221 cv_view_verts
+= [(v0
[0],v0
[1],v0
[2])]
2222 cv_view_verts
+= [(v1
[0],v1
[1],v1
[2])]
2223 cv_view_colours
+= [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2226 center
= obj
.matrix_world
@ c
2227 if bone
.cv_data
.con0
:
2229 draw_limit( obj
, c
, Vector((0,1,0)),Vector((0,0,1)), \
2230 bone
.cv_data
.mins
[0], bone
.cv_data
.maxs
[0], \
2232 draw_limit( obj
, c
, Vector((0,0,1)),Vector((1,0,0)), \
2233 bone
.cv_data
.mins
[1], bone
.cv_data
.maxs
[1], \
2235 draw_limit( obj
, c
, Vector((1,0,0)),Vector((0,1,0)), \
2236 bone
.cv_data
.mins
[2], bone
.cv_data
.maxs
[2], \
2245 global cv_view_shader
2246 global cv_view_verts
2247 global cv_view_colours
2248 global cv_view_course_i
2250 cv_view_course_i
= 0
2252 cv_view_colours
= []
2254 cv_view_shader
.bind()
2255 gpu
.state
.depth_mask_set(False)
2256 gpu
.state
.line_width_set(2.0)
2257 gpu
.state
.face_culling_set('BACK')
2258 gpu
.state
.depth_test_set('LESS')
2259 gpu
.state
.blend_set('NONE')
2261 for obj
in bpy
.context
.collection
.objects
:
2263 if obj
.type == 'ARMATURE':
2265 if obj
.data
.pose_position
== 'REST':
2266 draw_skeleton_helpers( obj
)
2270 classtype
= obj
.cv_data
.classtype
2271 if (classtype
!= 'classtype_none') and (classtype
in globals()):
2273 cl
= globals()[ classtype
]
2275 if getattr( cl
, "draw_scene_helpers", None ):
2277 cl
.draw_scene_helpers( obj
)
2288 # ---------------------------------------------------------------------------- #
2292 # ---------------------------------------------------------------------------- #
2294 # Checks whether this object has a classtype assigned. we can only target other
2296 def cv_poll_target(scene
, obj
):
2298 if obj
== bpy
.context
.active_object
:
2300 if obj
.cv_data
.classtype
== 'classtype_none':
2306 class CV_MESH_SETTINGS(bpy
.types
.PropertyGroup
):
2308 v0
: bpy
.props
.FloatVectorProperty(name
="v0",size
=3)
2309 v1
: bpy
.props
.FloatVectorProperty(name
="v1",size
=3)
2310 v2
: bpy
.props
.FloatVectorProperty(name
="v2",size
=3)
2311 v3
: bpy
.props
.FloatVectorProperty(name
="v3",size
=3)
2314 class CV_OBJ_SETTINGS(bpy
.types
.PropertyGroup
):
2316 uid
: bpy
.props
.IntProperty( name
="" )
2318 strp
: bpy
.props
.StringProperty( name
="strp" )
2319 intp
: bpy
.props
.IntProperty( name
="intp" )
2320 fltp
: bpy
.props
.FloatProperty( name
="fltp" )
2321 bp0
: bpy
.props
.BoolProperty( name
="bp0" )
2322 bp1
: bpy
.props
.BoolProperty( name
="bp1" )
2323 bp2
: bpy
.props
.BoolProperty( name
="bp2" )
2324 bp3
: bpy
.props
.BoolProperty( name
="bp3" )
2326 target
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target", \
2327 poll
=cv_poll_target
)
2328 target1
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target1", \
2329 poll
=cv_poll_target
)
2330 target2
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target2", \
2331 poll
=cv_poll_target
)
2332 target3
: bpy
.props
.PointerProperty( type=bpy
.types
.Object
, name
="target3", \
2333 poll
=cv_poll_target
)
2335 colour
: bpy
.props
.FloatVectorProperty( name
="colour",subtype
='COLOR',\
2338 classtype
: bpy
.props
.EnumProperty(
2341 ('classtype_none', "classtype_none", "", 0),
2342 ('classtype_gate', "classtype_gate", "", 1),
2343 ('classtype_spawn', "classtype_spawn", "", 3),
2344 ('classtype_water', "classtype_water", "", 4),
2345 ('classtype_route_node', "classtype_route_node", "", 8 ),
2346 ('classtype_route', "classtype_route", "", 9 ),
2347 ('classtype_audio',"classtype_audio","",14),
2348 ('classtype_trigger',"classtype_trigger","",100),
2349 ('classtype_logic_achievement',"classtype_logic_achievement","",101),
2350 ('classtype_logic_relay',"classtype_logic_relay","",102),
2354 class CV_BONE_SETTINGS(bpy
.types
.PropertyGroup
):
2356 collider
: bpy
.props
.BoolProperty(name
="Collider",default
=False)
2357 v0
: bpy
.props
.FloatVectorProperty(name
="v0",size
=3)
2358 v1
: bpy
.props
.FloatVectorProperty(name
="v1",size
=3)
2360 con0
: bpy
.props
.BoolProperty(name
="Constriant 0",default
=False)
2361 mins
: bpy
.props
.FloatVectorProperty(name
="mins",size
=3)
2362 maxs
: bpy
.props
.FloatVectorProperty(name
="maxs",size
=3)
2365 class CV_BONE_PANEL(bpy
.types
.Panel
):
2367 bl_label
="Bone Config"
2368 bl_idname
="SCENE_PT_cv_bone"
2369 bl_space_type
='PROPERTIES'
2370 bl_region_type
='WINDOW'
2373 def draw(_
,context
):
2375 active_object
= context
.active_object
2376 if active_object
== None: return
2378 bone
= active_object
.data
.bones
.active
2379 if bone
== None: return
2381 _
.layout
.prop( bone
.cv_data
, "collider" )
2382 _
.layout
.prop( bone
.cv_data
, "v0" )
2383 _
.layout
.prop( bone
.cv_data
, "v1" )
2385 _
.layout
.label( text
="Angle Limits" )
2386 _
.layout
.prop( bone
.cv_data
, "con0" )
2387 _
.layout
.prop( bone
.cv_data
, "mins" )
2388 _
.layout
.prop( bone
.cv_data
, "maxs" )
2392 class CV_SCENE_SETTINGS(bpy
.types
.PropertyGroup
):
2394 use_hidden
: bpy
.props
.BoolProperty( name
="use hidden", default
=False )
2395 export_dir
: bpy
.props
.StringProperty( name
="Export Dir", subtype
='DIR_PATH' )
2398 class CV_COLLECTION_SETTINGS(bpy
.types
.PropertyGroup
):
2400 pack_textures
: bpy
.props
.BoolProperty( name
="Pack Textures", default
=False )
2403 class CV_MATERIAL_SETTINGS(bpy
.types
.PropertyGroup
):
2405 shader
: bpy
.props
.EnumProperty(
2408 ('standard',"standard","",0),
2409 ('standard_cutout', "standard_cutout", "", 1),
2410 ('terrain_blend', "terrain_blend", "", 2),
2411 ('vertex_blend', "vertex_blend", "", 3),
2412 ('water',"water","",4),
2415 surface_prop
: bpy
.props
.EnumProperty(
2416 name
="Surface Property",
2418 ('concrete','concrete','',0),
2419 ('wood','wood','',1),
2420 ('grass','grass','',2)
2423 collision
: bpy
.props
.BoolProperty( \
2424 name
="Collisions Enabled",\
2426 description
= "Can the player collide with this material"\
2428 skate_surface
: bpy
.props
.BoolProperty( \
2429 name
="Skate Surface", \
2431 description
= "Should the game try to target this surface?" \
2433 grow_grass
: bpy
.props
.BoolProperty( \
2434 name
="Grow Grass", \
2436 description
= "Spawn grass sprites on this surface?" \
2438 blend_offset
: bpy
.props
.FloatVectorProperty( \
2439 name
="Blend Offset", \
2441 default
=Vector((0.5,0.0)),\
2442 description
="When surface is more than 45 degrees, add this vector " +\
2445 sand_colour
: bpy
.props
.FloatVectorProperty( \
2446 name
="Sand Colour",\
2449 default
=Vector((0.79,0.63,0.48)),\
2450 description
="Blend to this colour near the 0 coordinate on UP axis"\
2452 shore_colour
: bpy
.props
.FloatVectorProperty( \
2453 name
="Shore Colour",\
2456 default
=Vector((0.03,0.32,0.61)),\
2457 description
="Water colour at the shoreline"\
2459 ocean_colour
: bpy
.props
.FloatVectorProperty( \
2460 name
="Ocean Colour",\
2463 default
=Vector((0.0,0.006,0.03)),\
2464 description
="Water colour in the deep bits"\
2468 class CV_MATERIAL_PANEL(bpy
.types
.Panel
):
2470 bl_label
="Skate Rift material"
2471 bl_idname
="MATERIAL_PT_cv_material"
2472 bl_space_type
='PROPERTIES'
2473 bl_region_type
='WINDOW'
2474 bl_context
="material"
2476 def draw(_
,context
):
2478 active_object
= bpy
.context
.active_object
2479 if active_object
== None: return
2480 active_mat
= active_object
.active_material
2481 if active_mat
== None: return
2483 info
= material_info( active_mat
)
2485 _
.layout
.prop( active_mat
.cv_data
, "shader" )
2486 _
.layout
.prop( active_mat
.cv_data
, "surface_prop" )
2487 _
.layout
.prop( active_mat
.cv_data
, "collision" )
2489 if active_mat
.cv_data
.collision
:
2490 _
.layout
.prop( active_mat
.cv_data
, "skate_surface" )
2491 _
.layout
.prop( active_mat
.cv_data
, "grow_grass" )
2493 if active_mat
.cv_data
.shader
== "terrain_blend":
2495 box
= _
.layout
.box()
2496 box
.prop( active_mat
.cv_data
, "blend_offset" )
2497 box
.prop( active_mat
.cv_data
, "sand_colour" )
2499 elif active_mat
.cv_data
.shader
== "vertex_blend":
2501 box
= _
.layout
.box()
2502 box
.label( icon
='INFO', text
="Uses vertex colours, the R channel" )
2503 box
.prop( active_mat
.cv_data
, "blend_offset" )
2505 elif active_mat
.cv_data
.shader
== "water":
2507 box
= _
.layout
.box()
2508 box
.label( icon
='INFO', text
="Depth scale of 16 meters" )
2509 box
.prop( active_mat
.cv_data
, "shore_colour" )
2510 box
.prop( active_mat
.cv_data
, "ocean_colour" )
2515 class CV_OBJ_PANEL(bpy
.types
.Panel
):
2517 bl_label
="Entity Config"
2518 bl_idname
="SCENE_PT_cv_entity"
2519 bl_space_type
='PROPERTIES'
2520 bl_region_type
='WINDOW'
2523 def draw(_
,context
):
2525 active_object
= bpy
.context
.active_object
2526 if active_object
== None: return
2527 if active_object
.type == 'ARMATURE':
2529 row
= _
.layout
.row()
2531 row
.label( text
="This object has the intrinsic classtype of skeleton" )
2535 _
.layout
.prop( active_object
.cv_data
, "classtype" )
2537 classtype
= active_object
.cv_data
.classtype
2539 if (classtype
!= 'classtype_none') and (classtype
in globals()):
2541 cl
= globals()[ classtype
]
2543 if getattr( cl
, "editor_interface", None ):
2545 cl
.editor_interface( _
.layout
, active_object
)
2551 class CV_COMPILE(bpy
.types
.Operator
):
2553 bl_idname
="carve.compile_all"
2554 bl_label
="Compile All"
2556 def execute(_
,context
):
2558 view_layer
= bpy
.context
.view_layer
2559 for col
in view_layer
.layer_collection
.children
["export"].children
:
2560 if not col
.hide_viewport
or bpy
.context
.scene
.cv_data
.use_hidden
:
2561 write_model( col
.name
)
2567 class CV_COMPILE_THIS(bpy
.types
.Operator
):
2569 bl_idname
="carve.compile_this"
2570 bl_label
="Compile This collection"
2572 def execute(_
,context
):
2574 col
= bpy
.context
.collection
2575 write_model( col
.name
)
2581 class CV_INTERFACE(bpy
.types
.Panel
):
2583 bl_idname
= "VIEW3D_PT_carve"
2584 bl_label
= "Skate Rift"
2585 bl_space_type
= 'VIEW_3D'
2586 bl_region_type
= 'UI'
2587 bl_category
= "Skate Rift"
2589 def draw(_
, context
):
2592 layout
.prop( context
.scene
.cv_data
, "export_dir" )
2594 col
= bpy
.context
.collection
2596 found_in_export
= False
2598 view_layer
= bpy
.context
.view_layer
2599 for c1
in view_layer
.layer_collection
.children
["export"].children
:
2601 if not c1
.hide_viewport
or bpy
.context
.scene
.cv_data
.use_hidden
:
2604 if c1
.name
== col
.name
:
2606 found_in_export
= True
2613 box
.label( text
=col
.name
+ ".mdl" )
2614 box
.prop( col
.cv_data
, "pack_textures" )
2615 box
.operator( "carve.compile_this" )
2621 row
.label( text
=col
.name
)
2622 box
.label( text
="This collection is not in the export group" )
2628 split
= row
.split( factor
= 0.3, align
=True )
2629 split
.prop( context
.scene
.cv_data
, "use_hidden", text
="hidden" )
2632 if export_count
== 0:
2634 row1
.operator( "carve.compile_all", \
2635 text
=F
"Compile all ({export_count} collections)" )
2640 classes
= [CV_OBJ_SETTINGS
,CV_OBJ_PANEL
,CV_COMPILE
,CV_INTERFACE
,\
2641 CV_MESH_SETTINGS
, CV_SCENE_SETTINGS
, CV_BONE_SETTINGS
,\
2642 CV_BONE_PANEL
, CV_COLLECTION_SETTINGS
, CV_COMPILE_THIS
,\
2643 CV_MATERIAL_SETTINGS
, CV_MATERIAL_PANEL
]
2647 global cv_view_draw_handler
2650 bpy
.utils
.register_class(c
)
2652 bpy
.types
.Object
.cv_data
= bpy
.props
.PointerProperty(type=CV_OBJ_SETTINGS
)
2653 bpy
.types
.Mesh
.cv_data
= bpy
.props
.PointerProperty(type=CV_MESH_SETTINGS
)
2654 bpy
.types
.Scene
.cv_data
= bpy
.props
.PointerProperty(type=CV_SCENE_SETTINGS
)
2655 bpy
.types
.Bone
.cv_data
= bpy
.props
.PointerProperty(type=CV_BONE_SETTINGS
)
2656 bpy
.types
.Collection
.cv_data
= \
2657 bpy
.props
.PointerProperty(type=CV_COLLECTION_SETTINGS
)
2658 bpy
.types
.Material
.cv_data
= \
2659 bpy
.props
.PointerProperty(type=CV_MATERIAL_SETTINGS
)
2661 cv_view_draw_handler
= bpy
.types
.SpaceView3D
.draw_handler_add(\
2662 cv_draw
,(),'WINDOW','POST_VIEW')
2667 global cv_view_draw_handler
2670 bpy
.utils
.unregister_class(c
)
2672 bpy
.types
.SpaceView3D
.draw_handler_remove(cv_view_draw_handler
,'WINDOW')
2675 # ---------------------------------------------------------------------------- #
2679 # ---------------------------------------------------------------------------- #
2681 # Transliteration of: #
2682 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
2684 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
2685 # SPDX-License-Identifier: MIT #
2686 # QOI - The "Quite OK Image" format for fast, lossless image compression #
2688 # ---------------------------------------------------------------------------- #
2690 class qoi_rgba_t(Structure
):
2693 _fields_
= [("r",c_uint8
),
2699 QOI_OP_INDEX
= 0x00 # 00xxxxxx
2700 QOI_OP_DIFF
= 0x40 # 01xxxxxx
2701 QOI_OP_LUMA
= 0x80 # 10xxxxxx
2702 QOI_OP_RUN
= 0xc0 # 11xxxxxx
2703 QOI_OP_RGB
= 0xfe # 11111110
2704 QOI_OP_RGBA
= 0xff # 11111111
2706 QOI_MASK_2
= 0xc0 # 11000000
2708 def qoi_colour_hash( c
):
2710 return c
.r
*3 + c
.g
*5 + c
.b
*7 + c
.a
*11
2715 return (a
.r
==b
.r
) and (a
.g
==b
.g
) and (a
.b
==b
.b
) and (a
.a
==b
.a
)
2720 return bytearray([ (0xff000000 & v
) >> 24, \
2721 (0x00ff0000 & v
) >> 16, \
2722 (0x0000ff00 & v
) >> 8, \
2726 def qoi_encode( img
):
2730 print(F
" . Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]")
2732 index
= [ qoi_rgba_t() for _
in range(64) ]
2736 data
.extend( bytearray(c_uint32(0x66696f71)) )
2737 data
.extend( qoi_32bit( img
.size
[0] ) )
2738 data
.extend( qoi_32bit( img
.size
[1] ) )
2739 data
.extend( bytearray(c_uint8(4)) )
2740 data
.extend( bytearray(c_uint8(0)) )
2743 px_prev
= qoi_rgba_t()
2744 px_prev
.r
= c_uint8(0)
2745 px_prev
.g
= c_uint8(0)
2746 px_prev
.b
= c_uint8(0)
2747 px_prev
.a
= c_uint8(255)
2755 px_len
= img
.size
[0] * img
.size
[1]
2757 paxels
= [ int(min(max(_
,0),1)*255) for _
in img
.pixels
]
2759 for px_pos
in range( px_len
):
2761 idx
= px_pos
* img
.channels
2764 px
.r
= paxels
[idx
+min(0,nc
)]
2765 px
.g
= paxels
[idx
+min(1,nc
)]
2766 px
.b
= paxels
[idx
+min(2,nc
)]
2767 px
.a
= paxels
[idx
+min(3,nc
)]
2769 if qoi_eq( px
, px_prev
):
2773 if (run
== 62) or (px_pos
== px_len
-1):
2775 data
.extend( bytearray( c_uint8(QOI_OP_RUN |
(run
-1))) )
2783 data
.extend( bytearray( c_uint8(QOI_OP_RUN |
(run
-1))) )
2787 index_pos
= qoi_colour_hash(px
) % 64
2789 if qoi_eq( index
[index_pos
], px
):
2791 data
.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos
)) )
2795 index
[ index_pos
].r
= px
.r
2796 index
[ index_pos
].g
= px
.g
2797 index
[ index_pos
].b
= px
.b
2798 index
[ index_pos
].a
= px
.a
2800 if px
.a
== px_prev
.a
:
2802 vr
= int(px
.r
) - int(px_prev
.r
)
2803 vg
= int(px
.g
) - int(px_prev
.g
)
2804 vb
= int(px
.b
) - int(px_prev
.b
)
2809 if (vr
> -3) and (vr
< 2) and\
2810 (vg
> -3) and (vg
< 2) and\
2811 (vb
> -3) and (vb
< 2):
2813 op
= QOI_OP_DIFF |
(vr
+2) << 4 |
(vg
+2) << 2 |
(vb
+2)
2814 data
.extend( bytearray( c_uint8(op
) ))
2816 elif (vg_r
> -9) and (vg_r
< 8) and\
2817 (vg
> -33) and (vg
< 32 ) and\
2818 (vg_b
> -9) and (vg_b
< 8):
2820 op
= QOI_OP_LUMA |
(vg
+32)
2821 delta
= (vg_r
+8) << 4 |
(vg_b
+ 8)
2822 data
.extend( bytearray( c_uint8(op
) ) )
2823 data
.extend( bytearray( c_uint8(delta
) ))
2827 data
.extend( bytearray( c_uint8(QOI_OP_RGB
) ) )
2828 data
.extend( bytearray( c_uint8(px
.r
) ))
2829 data
.extend( bytearray( c_uint8(px
.g
) ))
2830 data
.extend( bytearray( c_uint8(px
.b
) ))
2835 data
.extend( bytearray( c_uint8(QOI_OP_RGBA
) ) )
2836 data
.extend( bytearray( c_uint8(px
.r
) ))
2837 data
.extend( bytearray( c_uint8(px
.g
) ))
2838 data
.extend( bytearray( c_uint8(px
.b
) ))
2839 data
.extend( bytearray( c_uint8(px
.a
) ))
2852 data
.extend( bytearray( c_uint8(0) ))
2853 data
.extend( bytearray( c_uint8(1) ))
2854 bytearray_align_to( data
, 16, 0 )