1 # SPDX-License-Identifier: GPL-2.0-or-later
3 # Script copyright (C) Campbell Barton, Bastien Montagne
12 from itertools
import zip_longest
, chain
16 if "encode_bin" in locals():
17 importlib
.reload(encode_bin
)
18 if "data_types" in locals():
19 importlib
.reload(data_types
)
20 if "fbx_utils" in locals():
21 importlib
.reload(fbx_utils
)
25 from bpy_extras
import node_shader_utils
26 from bpy
.app
.translations
import pgettext_tip
as tip_
27 from mathutils
import Vector
, Matrix
29 from . import encode_bin
, data_types
, fbx_utils
30 from .fbx_utils
import (
32 FBX_VERSION
, FBX_HEADER_VERSION
, FBX_SCENEINFO_VERSION
, FBX_TEMPLATES_VERSION
,
34 FBX_GEOMETRY_VERSION
, FBX_GEOMETRY_NORMAL_VERSION
, FBX_GEOMETRY_BINORMAL_VERSION
, FBX_GEOMETRY_TANGENT_VERSION
,
35 FBX_GEOMETRY_SMOOTHING_VERSION
, FBX_GEOMETRY_CREASE_VERSION
, FBX_GEOMETRY_VCOLOR_VERSION
, FBX_GEOMETRY_UV_VERSION
,
36 FBX_GEOMETRY_MATERIAL_VERSION
, FBX_GEOMETRY_LAYER_VERSION
,
37 FBX_GEOMETRY_SHAPE_VERSION
, FBX_DEFORMER_SHAPE_VERSION
, FBX_DEFORMER_SHAPECHANNEL_VERSION
,
38 FBX_POSE_BIND_VERSION
, FBX_DEFORMER_SKIN_VERSION
, FBX_DEFORMER_CLUSTER_VERSION
,
39 FBX_MATERIAL_VERSION
, FBX_TEXTURE_VERSION
,
41 FBX_ANIM_PROPSGROUP_NAME
,
43 BLENDER_OTHER_OBJECT_TYPES
, BLENDER_OBJECT_TYPES_MESHLIKE
,
44 FBX_LIGHT_TYPES
, FBX_LIGHT_DECAY_TYPES
,
45 RIGHT_HAND_AXES
, FBX_FRAMERATES
,
46 # Miscellaneous utils.
48 units_blender_to_fbx_factor
, units_convertor
, units_convertor_iter
,
49 matrix4_to_array
, similar_values
, similar_values_iter
,
50 # Mesh transform helpers.
51 vcos_transformed_gen
, nors_transformed_gen
,
53 get_fbx_uuid_from_key
,
55 get_blenderID_key
, get_blenderID_name
,
56 get_blender_mesh_shape_key
, get_blender_mesh_shape_channel_key
,
57 get_blender_empty_key
, get_blender_bone_key
,
58 get_blender_bindpose_key
, get_blender_armature_skin_key
, get_blender_bone_cluster_key
,
59 get_blender_anim_id_base
, get_blender_anim_stack_key
, get_blender_anim_layer_key
,
60 get_blender_anim_curve_node_key
, get_blender_anim_curve_key
,
61 get_blender_nodetexture_key
,
64 elem_data_single_bool
, elem_data_single_int16
, elem_data_single_int32
, elem_data_single_int64
,
65 elem_data_single_float32
, elem_data_single_float64
,
66 elem_data_single_bytes
, elem_data_single_string
, elem_data_single_string_unicode
,
67 elem_data_single_bool_array
, elem_data_single_int32_array
, elem_data_single_int64_array
,
68 elem_data_single_float32_array
, elem_data_single_float64_array
, elem_data_vec_float64
,
69 # FBX element properties.
70 elem_properties
, elem_props_set
, elem_props_compound
,
71 # FBX element properties handling templates.
72 elem_props_template_init
, elem_props_template_set
, elem_props_template_finalize
,
74 FBXTemplate
, fbx_templates_generate
,
76 AnimationCurveNodeWrapper
,
78 ObjectWrapper
, fbx_name_class
,
80 FBXExportSettingsMedia
, FBXExportSettings
, FBXExportData
,
84 convert_sec_to_ktime
= units_convertor("second", "ktime")
85 convert_sec_to_ktime_iter
= units_convertor_iter("second", "ktime")
87 convert_mm_to_inch
= units_convertor("millimeter", "inch")
89 convert_rad_to_deg
= units_convertor("radian", "degree")
90 convert_rad_to_deg_iter
= units_convertor_iter("radian", "degree")
93 # ##### Templates #####
94 # TODO: check all those "default" values, they should match Blender's default as much as possible, I guess?
96 def fbx_template_def_globalsettings(scene
, settings
, override_defaults
=None, nbr_users
=0):
98 if override_defaults
is not None:
99 props
.update(override_defaults
)
100 return FBXTemplate(b
"GlobalSettings", b
"", props
, nbr_users
, [False])
103 def fbx_template_def_model(scene
, settings
, override_defaults
=None, nbr_users
=0):
104 gscale
= settings
.global_scale
106 # Name, Value, Type, Animatable
107 b
"QuaternionInterpolate": (0, "p_enum", False), # 0 = no quat interpolation.
108 b
"RotationOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
109 b
"RotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
110 b
"ScalingOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
111 b
"ScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
112 b
"TranslationActive": (False, "p_bool", False),
113 b
"TranslationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
114 b
"TranslationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
115 b
"TranslationMinX": (False, "p_bool", False),
116 b
"TranslationMinY": (False, "p_bool", False),
117 b
"TranslationMinZ": (False, "p_bool", False),
118 b
"TranslationMaxX": (False, "p_bool", False),
119 b
"TranslationMaxY": (False, "p_bool", False),
120 b
"TranslationMaxZ": (False, "p_bool", False),
121 b
"RotationOrder": (0, "p_enum", False), # we always use 'XYZ' order.
122 b
"RotationSpaceForLimitOnly": (False, "p_bool", False),
123 b
"RotationStiffnessX": (0.0, "p_double", False),
124 b
"RotationStiffnessY": (0.0, "p_double", False),
125 b
"RotationStiffnessZ": (0.0, "p_double", False),
126 b
"AxisLen": (10.0, "p_double", False),
127 b
"PreRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
128 b
"PostRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
129 b
"RotationActive": (False, "p_bool", False),
130 b
"RotationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
131 b
"RotationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
132 b
"RotationMinX": (False, "p_bool", False),
133 b
"RotationMinY": (False, "p_bool", False),
134 b
"RotationMinZ": (False, "p_bool", False),
135 b
"RotationMaxX": (False, "p_bool", False),
136 b
"RotationMaxY": (False, "p_bool", False),
137 b
"RotationMaxZ": (False, "p_bool", False),
138 b
"InheritType": (0, "p_enum", False), # RrSs
139 b
"ScalingActive": (False, "p_bool", False),
140 b
"ScalingMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
141 b
"ScalingMax": ((1.0, 1.0, 1.0), "p_vector_3d", False),
142 b
"ScalingMinX": (False, "p_bool", False),
143 b
"ScalingMinY": (False, "p_bool", False),
144 b
"ScalingMinZ": (False, "p_bool", False),
145 b
"ScalingMaxX": (False, "p_bool", False),
146 b
"ScalingMaxY": (False, "p_bool", False),
147 b
"ScalingMaxZ": (False, "p_bool", False),
148 b
"GeometricTranslation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
149 b
"GeometricRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
150 b
"GeometricScaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
151 b
"MinDampRangeX": (0.0, "p_double", False),
152 b
"MinDampRangeY": (0.0, "p_double", False),
153 b
"MinDampRangeZ": (0.0, "p_double", False),
154 b
"MaxDampRangeX": (0.0, "p_double", False),
155 b
"MaxDampRangeY": (0.0, "p_double", False),
156 b
"MaxDampRangeZ": (0.0, "p_double", False),
157 b
"MinDampStrengthX": (0.0, "p_double", False),
158 b
"MinDampStrengthY": (0.0, "p_double", False),
159 b
"MinDampStrengthZ": (0.0, "p_double", False),
160 b
"MaxDampStrengthX": (0.0, "p_double", False),
161 b
"MaxDampStrengthY": (0.0, "p_double", False),
162 b
"MaxDampStrengthZ": (0.0, "p_double", False),
163 b
"PreferedAngleX": (0.0, "p_double", False),
164 b
"PreferedAngleY": (0.0, "p_double", False),
165 b
"PreferedAngleZ": (0.0, "p_double", False),
166 b
"LookAtProperty": (None, "p_object", False),
167 b
"UpVectorProperty": (None, "p_object", False),
168 b
"Show": (True, "p_bool", False),
169 b
"NegativePercentShapeSupport": (True, "p_bool", False),
170 b
"DefaultAttributeIndex": (-1, "p_integer", False),
171 b
"Freeze": (False, "p_bool", False),
172 b
"LODBox": (False, "p_bool", False),
173 b
"Lcl Translation": ((0.0, 0.0, 0.0), "p_lcl_translation", True),
174 b
"Lcl Rotation": ((0.0, 0.0, 0.0), "p_lcl_rotation", True),
175 b
"Lcl Scaling": ((1.0, 1.0, 1.0), "p_lcl_scaling", True),
176 b
"Visibility": (1.0, "p_visibility", True),
177 b
"Visibility Inheritance": (1, "p_visibility_inheritance", False),
179 if override_defaults
is not None:
180 props
.update(override_defaults
)
181 return FBXTemplate(b
"Model", b
"FbxNode", props
, nbr_users
, [False])
184 def fbx_template_def_null(scene
, settings
, override_defaults
=None, nbr_users
=0):
186 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
187 b
"Size": (100.0, "p_double", False),
188 b
"Look": (1, "p_enum", False), # Cross (0 is None, i.e. invisible?).
190 if override_defaults
is not None:
191 props
.update(override_defaults
)
192 return FBXTemplate(b
"NodeAttribute", b
"FbxNull", props
, nbr_users
, [False])
195 def fbx_template_def_light(scene
, settings
, override_defaults
=None, nbr_users
=0):
196 gscale
= settings
.global_scale
198 b
"LightType": (0, "p_enum", False), # Point light.
199 b
"CastLight": (True, "p_bool", False),
200 b
"Color": ((1.0, 1.0, 1.0), "p_color", True),
201 b
"Intensity": (100.0, "p_number", True), # Times 100 compared to Blender values...
202 b
"DecayType": (2, "p_enum", False), # Quadratic.
203 b
"DecayStart": (30.0 * gscale
, "p_double", False),
204 b
"CastShadows": (True, "p_bool", False),
205 b
"ShadowColor": ((0.0, 0.0, 0.0), "p_color", True),
206 b
"AreaLightShape": (0, "p_enum", False), # Rectangle.
208 if override_defaults
is not None:
209 props
.update(override_defaults
)
210 return FBXTemplate(b
"NodeAttribute", b
"FbxLight", props
, nbr_users
, [False])
213 def fbx_template_def_camera(scene
, settings
, override_defaults
=None, nbr_users
=0):
216 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
217 b
"Position": ((0.0, 0.0, -50.0), "p_vector", True),
218 b
"UpVector": ((0.0, 1.0, 0.0), "p_vector", True),
219 b
"InterestPosition": ((0.0, 0.0, 0.0), "p_vector", True),
220 b
"Roll": (0.0, "p_roll", True),
221 b
"OpticalCenterX": (0.0, "p_opticalcenterx", True),
222 b
"OpticalCenterY": (0.0, "p_opticalcentery", True),
223 b
"BackgroundColor": ((0.63, 0.63, 0.63), "p_color", True),
224 b
"TurnTable": (0.0, "p_number", True),
225 b
"DisplayTurnTableIcon": (False, "p_bool", False),
226 b
"UseMotionBlur": (False, "p_bool", False),
227 b
"UseRealTimeMotionBlur": (True, "p_bool", False),
228 b
"Motion Blur Intensity": (1.0, "p_number", True),
229 b
"AspectRatioMode": (0, "p_enum", False), # WindowSize.
230 b
"AspectWidth": (320.0, "p_double", False),
231 b
"AspectHeight": (200.0, "p_double", False),
232 b
"PixelAspectRatio": (1.0, "p_double", False),
233 b
"FilmOffsetX": (0.0, "p_number", True),
234 b
"FilmOffsetY": (0.0, "p_number", True),
235 b
"FilmWidth": (0.816, "p_double", False),
236 b
"FilmHeight": (0.612, "p_double", False),
237 b
"FilmAspectRatio": (1.3333333333333333, "p_double", False),
238 b
"FilmSqueezeRatio": (1.0, "p_double", False),
239 b
"FilmFormatIndex": (0, "p_enum", False), # Assuming this is ApertureFormat, 0 = custom.
240 b
"PreScale": (1.0, "p_number", True),
241 b
"FilmTranslateX": (0.0, "p_number", True),
242 b
"FilmTranslateY": (0.0, "p_number", True),
243 b
"FilmRollPivotX": (0.0, "p_number", True),
244 b
"FilmRollPivotY": (0.0, "p_number", True),
245 b
"FilmRollValue": (0.0, "p_number", True),
246 b
"FilmRollOrder": (0, "p_enum", False), # 0 = rotate first (default).
247 b
"ApertureMode": (2, "p_enum", False), # 2 = Vertical.
248 b
"GateFit": (0, "p_enum", False), # 0 = no resolution gate fit.
249 b
"FieldOfView": (25.114999771118164, "p_fov", True),
250 b
"FieldOfViewX": (40.0, "p_fov_x", True),
251 b
"FieldOfViewY": (40.0, "p_fov_y", True),
252 b
"FocalLength": (34.89327621672628, "p_number", True),
253 b
"CameraFormat": (0, "p_enum", False), # Custom camera format.
254 b
"UseFrameColor": (False, "p_bool", False),
255 b
"FrameColor": ((0.3, 0.3, 0.3), "p_color_rgb", False),
256 b
"ShowName": (True, "p_bool", False),
257 b
"ShowInfoOnMoving": (True, "p_bool", False),
258 b
"ShowGrid": (True, "p_bool", False),
259 b
"ShowOpticalCenter": (False, "p_bool", False),
260 b
"ShowAzimut": (True, "p_bool", False),
261 b
"ShowTimeCode": (False, "p_bool", False),
262 b
"ShowAudio": (False, "p_bool", False),
263 b
"AudioColor": ((0.0, 1.0, 0.0), "p_vector_3d", False), # Yep, vector3d, not corlorgb… :cry:
264 b
"NearPlane": (10.0, "p_double", False),
265 b
"FarPlane": (4000.0, "p_double", False),
266 b
"AutoComputeClipPanes": (False, "p_bool", False),
267 b
"ViewCameraToLookAt": (True, "p_bool", False),
268 b
"ViewFrustumNearFarPlane": (False, "p_bool", False),
269 b
"ViewFrustumBackPlaneMode": (2, "p_enum", False), # 2 = show back plane if texture added.
270 b
"BackPlaneDistance": (4000.0, "p_number", True),
271 b
"BackPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
272 b
"ViewFrustumFrontPlaneMode": (2, "p_enum", False), # 2 = show front plane if texture added.
273 b
"FrontPlaneDistance": (10.0, "p_number", True),
274 b
"FrontPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
275 b
"LockMode": (False, "p_bool", False),
276 b
"LockInterestNavigation": (False, "p_bool", False),
277 # BackPlate... properties **arggggg!**
278 b
"FitImage": (False, "p_bool", False),
279 b
"Crop": (False, "p_bool", False),
280 b
"Center": (True, "p_bool", False),
281 b
"KeepRatio": (True, "p_bool", False),
282 # End of BackPlate...
283 b
"BackgroundAlphaTreshold": (0.5, "p_double", False),
284 b
"ShowBackplate": (True, "p_bool", False),
285 b
"BackPlaneOffsetX": (0.0, "p_number", True),
286 b
"BackPlaneOffsetY": (0.0, "p_number", True),
287 b
"BackPlaneRotation": (0.0, "p_number", True),
288 b
"BackPlaneScaleX": (1.0, "p_number", True),
289 b
"BackPlaneScaleY": (1.0, "p_number", True),
290 b
"Background Texture": (None, "p_object", False),
291 b
"FrontPlateFitImage": (True, "p_bool", False),
292 b
"FrontPlateCrop": (False, "p_bool", False),
293 b
"FrontPlateCenter": (True, "p_bool", False),
294 b
"FrontPlateKeepRatio": (True, "p_bool", False),
295 b
"Foreground Opacity": (1.0, "p_double", False),
296 b
"ShowFrontplate": (True, "p_bool", False),
297 b
"FrontPlaneOffsetX": (0.0, "p_number", True),
298 b
"FrontPlaneOffsetY": (0.0, "p_number", True),
299 b
"FrontPlaneRotation": (0.0, "p_number", True),
300 b
"FrontPlaneScaleX": (1.0, "p_number", True),
301 b
"FrontPlaneScaleY": (1.0, "p_number", True),
302 b
"Foreground Texture": (None, "p_object", False),
303 b
"DisplaySafeArea": (False, "p_bool", False),
304 b
"DisplaySafeAreaOnRender": (False, "p_bool", False),
305 b
"SafeAreaDisplayStyle": (1, "p_enum", False), # 1 = rounded corners.
306 b
"SafeAreaAspectRatio": (1.3333333333333333, "p_double", False),
307 b
"Use2DMagnifierZoom": (False, "p_bool", False),
308 b
"2D Magnifier Zoom": (100.0, "p_number", True),
309 b
"2D Magnifier X": (50.0, "p_number", True),
310 b
"2D Magnifier Y": (50.0, "p_number", True),
311 b
"CameraProjectionType": (0, "p_enum", False), # 0 = perspective, 1 = orthogonal.
312 b
"OrthoZoom": (1.0, "p_double", False),
313 b
"UseRealTimeDOFAndAA": (False, "p_bool", False),
314 b
"UseDepthOfField": (False, "p_bool", False),
315 b
"FocusSource": (0, "p_enum", False), # 0 = camera interest, 1 = distance from camera interest.
316 b
"FocusAngle": (3.5, "p_double", False), # ???
317 b
"FocusDistance": (200.0, "p_double", False),
318 b
"UseAntialiasing": (False, "p_bool", False),
319 b
"AntialiasingIntensity": (0.77777, "p_double", False),
320 b
"AntialiasingMethod": (0, "p_enum", False), # 0 = oversampling, 1 = hardware.
321 b
"UseAccumulationBuffer": (False, "p_bool", False),
322 b
"FrameSamplingCount": (7, "p_integer", False),
323 b
"FrameSamplingType": (1, "p_enum", False), # 0 = uniform, 1 = stochastic.
325 if override_defaults
is not None:
326 props
.update(override_defaults
)
327 return FBXTemplate(b
"NodeAttribute", b
"FbxCamera", props
, nbr_users
, [False])
330 def fbx_template_def_bone(scene
, settings
, override_defaults
=None, nbr_users
=0):
332 if override_defaults
is not None:
333 props
.update(override_defaults
)
334 return FBXTemplate(b
"NodeAttribute", b
"LimbNode", props
, nbr_users
, [False])
337 def fbx_template_def_geometry(scene
, settings
, override_defaults
=None, nbr_users
=0):
339 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
340 b
"BBoxMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
341 b
"BBoxMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
342 b
"Primary Visibility": (True, "p_bool", False),
343 b
"Casts Shadows": (True, "p_bool", False),
344 b
"Receive Shadows": (True, "p_bool", False),
346 if override_defaults
is not None:
347 props
.update(override_defaults
)
348 return FBXTemplate(b
"Geometry", b
"FbxMesh", props
, nbr_users
, [False])
351 def fbx_template_def_material(scene
, settings
, override_defaults
=None, nbr_users
=0):
354 b
"ShadingModel": ("Phong", "p_string", False),
355 b
"MultiLayer": (False, "p_bool", False),
357 b
"EmissiveColor": ((0.0, 0.0, 0.0), "p_color", True),
358 b
"EmissiveFactor": (1.0, "p_number", True),
359 b
"AmbientColor": ((0.2, 0.2, 0.2), "p_color", True),
360 b
"AmbientFactor": (1.0, "p_number", True),
361 b
"DiffuseColor": ((0.8, 0.8, 0.8), "p_color", True),
362 b
"DiffuseFactor": (1.0, "p_number", True),
363 b
"TransparentColor": ((0.0, 0.0, 0.0), "p_color", True),
364 b
"TransparencyFactor": (0.0, "p_number", True),
365 b
"Opacity": (1.0, "p_number", True),
366 b
"NormalMap": ((0.0, 0.0, 0.0), "p_vector_3d", False),
367 b
"Bump": ((0.0, 0.0, 0.0), "p_vector_3d", False),
368 b
"BumpFactor": (1.0, "p_double", False),
369 b
"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
370 b
"DisplacementFactor": (1.0, "p_double", False),
371 b
"VectorDisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
372 b
"VectorDisplacementFactor": (1.0, "p_double", False),
374 b
"SpecularColor": ((0.2, 0.2, 0.2), "p_color", True),
375 b
"SpecularFactor": (1.0, "p_number", True),
376 # Not sure about the name, importer uses this (but ShininessExponent for tex prop name!)
377 # And in fbx exported by sdk, you have one in template, the other in actual material!!! :/
378 # For now, using both.
379 b
"Shininess": (20.0, "p_number", True),
380 b
"ShininessExponent": (20.0, "p_number", True),
381 b
"ReflectionColor": ((0.0, 0.0, 0.0), "p_color", True),
382 b
"ReflectionFactor": (1.0, "p_number", True),
384 if override_defaults
is not None:
385 props
.update(override_defaults
)
386 return FBXTemplate(b
"Material", b
"FbxSurfacePhong", props
, nbr_users
, [False])
389 def fbx_template_def_texture_file(scene
, settings
, override_defaults
=None, nbr_users
=0):
391 # XXX Not sure about all names!
393 b
"TextureTypeUse": (0, "p_enum", False), # Standard.
394 b
"AlphaSource": (2, "p_enum", False), # Black (i.e. texture's alpha), XXX name guessed!.
395 b
"Texture alpha": (1.0, "p_double", False),
396 b
"PremultiplyAlpha": (True, "p_bool", False),
397 b
"CurrentTextureBlendMode": (1, "p_enum", False), # Additive...
398 b
"CurrentMappingType": (0, "p_enum", False), # UV.
399 b
"UVSet": ("default", "p_string", False), # UVMap name.
400 b
"WrapModeU": (0, "p_enum", False), # Repeat.
401 b
"WrapModeV": (0, "p_enum", False), # Repeat.
402 b
"UVSwap": (False, "p_bool", False),
403 b
"Translation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
404 b
"Rotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
405 b
"Scaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
406 b
"TextureRotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
407 b
"TextureScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
408 # Not sure about those two...
409 b
"UseMaterial": (False, "p_bool", False),
410 b
"UseMipMap": (False, "p_bool", False),
412 if override_defaults
is not None:
413 props
.update(override_defaults
)
414 return FBXTemplate(b
"Texture", b
"FbxFileTexture", props
, nbr_users
, [False])
417 def fbx_template_def_video(scene
, settings
, override_defaults
=None, nbr_users
=0):
421 b
"Width": (0, "p_integer", False),
422 b
"Height": (0, "p_integer", False),
423 b
"Path": ("", "p_string_url", False),
424 b
"AccessMode": (0, "p_enum", False), # Disk (0=Disk, 1=Mem, 2=DiskAsync).
426 b
"StartFrame": (0, "p_integer", False),
427 b
"StopFrame": (0, "p_integer", False),
428 b
"Offset": (0, "p_timestamp", False),
429 b
"PlaySpeed": (0.0, "p_double", False),
430 b
"FreeRunning": (False, "p_bool", False),
431 b
"Loop": (False, "p_bool", False),
432 b
"InterlaceMode": (0, "p_enum", False), # None, i.e. progressive.
434 b
"ImageSequence": (False, "p_bool", False),
435 b
"ImageSequenceOffset": (0, "p_integer", False),
436 b
"FrameRate": (0.0, "p_double", False),
437 b
"LastFrame": (0, "p_integer", False),
439 if override_defaults
is not None:
440 props
.update(override_defaults
)
441 return FBXTemplate(b
"Video", b
"FbxVideo", props
, nbr_users
, [False])
444 def fbx_template_def_pose(scene
, settings
, override_defaults
=None, nbr_users
=0):
446 if override_defaults
is not None:
447 props
.update(override_defaults
)
448 return FBXTemplate(b
"Pose", b
"", props
, nbr_users
, [False])
451 def fbx_template_def_deformer(scene
, settings
, override_defaults
=None, nbr_users
=0):
453 if override_defaults
is not None:
454 props
.update(override_defaults
)
455 return FBXTemplate(b
"Deformer", b
"", props
, nbr_users
, [False])
458 def fbx_template_def_animstack(scene
, settings
, override_defaults
=None, nbr_users
=0):
460 b
"Description": ("", "p_string", False),
461 b
"LocalStart": (0, "p_timestamp", False),
462 b
"LocalStop": (0, "p_timestamp", False),
463 b
"ReferenceStart": (0, "p_timestamp", False),
464 b
"ReferenceStop": (0, "p_timestamp", False),
466 if override_defaults
is not None:
467 props
.update(override_defaults
)
468 return FBXTemplate(b
"AnimationStack", b
"FbxAnimStack", props
, nbr_users
, [False])
471 def fbx_template_def_animlayer(scene
, settings
, override_defaults
=None, nbr_users
=0):
473 b
"Weight": (100.0, "p_number", True),
474 b
"Mute": (False, "p_bool", False),
475 b
"Solo": (False, "p_bool", False),
476 b
"Lock": (False, "p_bool", False),
477 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
478 b
"BlendMode": (0, "p_enum", False),
479 b
"RotationAccumulationMode": (0, "p_enum", False),
480 b
"ScaleAccumulationMode": (0, "p_enum", False),
481 b
"BlendModeBypass": (0, "p_ulonglong", False),
483 if override_defaults
is not None:
484 props
.update(override_defaults
)
485 return FBXTemplate(b
"AnimationLayer", b
"FbxAnimLayer", props
, nbr_users
, [False])
488 def fbx_template_def_animcurvenode(scene
, settings
, override_defaults
=None, nbr_users
=0):
490 FBX_ANIM_PROPSGROUP_NAME
.encode(): (None, "p_compound", False),
492 if override_defaults
is not None:
493 props
.update(override_defaults
)
494 return FBXTemplate(b
"AnimationCurveNode", b
"FbxAnimCurveNode", props
, nbr_users
, [False])
497 def fbx_template_def_animcurve(scene
, settings
, override_defaults
=None, nbr_users
=0):
499 if override_defaults
is not None:
500 props
.update(override_defaults
)
501 return FBXTemplate(b
"AnimationCurve", b
"", props
, nbr_users
, [False])
504 # ##### Generators for connection elements. #####
506 def elem_connection(elem
, c_type
, uid_src
, uid_dst
, prop_dst
=None):
507 e
= elem_data_single_string(elem
, b
"C", c_type
)
510 if prop_dst
is not None:
511 e
.add_string(prop_dst
)
514 # ##### FBX objects generators. #####
516 def fbx_data_element_custom_properties(props
, bid
):
518 Store custom properties of blender ID bid (any mapping-like object, in fact) into FBX properties props.
525 rna_properties
= {prop
.identifier
for prop
in bid
.bl_rna
.properties
if prop
.is_runtime
}
528 if k
in rna_properties
:
531 list_val
= getattr(v
, "to_list", lambda: None)()
533 if isinstance(v
, str):
534 elem_props_set(props
, "p_string", k
.encode(), v
, custom
=True)
535 elif isinstance(v
, int):
536 elem_props_set(props
, "p_integer", k
.encode(), v
, custom
=True)
537 elif isinstance(v
, float):
538 elem_props_set(props
, "p_double", k
.encode(), v
, custom
=True)
540 if len(list_val
) == 3:
541 elem_props_set(props
, "p_vector", k
.encode(), list_val
, custom
=True)
543 elem_props_set(props
, "p_string", k
.encode(), str(list_val
), custom
=True)
545 elem_props_set(props
, "p_string", k
.encode(), str(v
), custom
=True)
548 def fbx_data_empty_elements(root
, empty
, scene_data
):
550 Write the Empty data block (you can control its FBX datatype with the 'fbx_type' string custom property).
552 empty_key
= scene_data
.data_empties
[empty
]
554 null
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(empty_key
))
555 null
.add_string(fbx_name_class(empty
.name
.encode(), b
"NodeAttribute"))
556 val
= empty
.bdata
.get('fbx_type', None)
557 null
.add_string(val
.encode() if val
and isinstance(val
, str) else b
"Null")
559 elem_data_single_string(null
, b
"TypeFlags", b
"Null")
561 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Null")
562 props
= elem_properties(null
)
563 elem_props_template_finalize(tmpl
, props
)
565 # No custom properties, already saved with object (Model).
568 def fbx_data_light_elements(root
, lamp
, scene_data
):
570 Write the Lamp data block.
572 gscale
= scene_data
.settings
.global_scale
574 light_key
= scene_data
.data_lights
[lamp
]
576 decay_type
= FBX_LIGHT_DECAY_TYPES
['CONSTANT']
578 shadow_color
= Vector((0.0, 0.0, 0.0))
579 if lamp
.type not in {'HEMI'}:
580 if lamp
.type not in {'SUN', 'AREA'}:
581 decay_type
= FBX_LIGHT_DECAY_TYPES
[lamp
.falloff_type
]
583 do_shadow
= lamp
.use_shadow
584 shadow_color
= lamp
.shadow_color
586 light
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(light_key
))
587 light
.add_string(fbx_name_class(lamp
.name
.encode(), b
"NodeAttribute"))
588 light
.add_string(b
"Light")
590 elem_data_single_int32(light
, b
"GeometryVersion", FBX_GEOMETRY_VERSION
) # Sic...
592 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Light")
593 props
= elem_properties(light
)
594 elem_props_template_set(tmpl
, props
, "p_enum", b
"LightType", FBX_LIGHT_TYPES
[lamp
.type])
595 elem_props_template_set(tmpl
, props
, "p_bool", b
"CastLight", do_light
)
596 elem_props_template_set(tmpl
, props
, "p_color", b
"Color", lamp
.color
)
597 elem_props_template_set(tmpl
, props
, "p_number", b
"Intensity", lamp
.energy
* 100.0)
598 elem_props_template_set(tmpl
, props
, "p_enum", b
"DecayType", decay_type
)
599 elem_props_template_set(tmpl
, props
, "p_double", b
"DecayStart", lamp
.distance
* gscale
)
600 elem_props_template_set(tmpl
, props
, "p_bool", b
"CastShadows", do_shadow
)
601 elem_props_template_set(tmpl
, props
, "p_color", b
"ShadowColor", shadow_color
)
602 if lamp
.type in {'SPOT'}:
603 elem_props_template_set(tmpl
, props
, "p_double", b
"OuterAngle", math
.degrees(lamp
.spot_size
))
604 elem_props_template_set(tmpl
, props
, "p_double", b
"InnerAngle",
605 math
.degrees(lamp
.spot_size
* (1.0 - lamp
.spot_blend
)))
606 elem_props_template_finalize(tmpl
, props
)
609 if scene_data
.settings
.use_custom_props
:
610 fbx_data_element_custom_properties(props
, lamp
)
613 def fbx_data_camera_elements(root
, cam_obj
, scene_data
):
615 Write the Camera data blocks.
617 gscale
= scene_data
.settings
.global_scale
621 cam_key
= scene_data
.data_cameras
[cam_obj
]
623 # Real data now, good old camera!
624 # Object transform info.
625 loc
, rot
, scale
, matrix
, matrix_rot
= cam_obj
.fbx_object_tx(scene_data
)
626 up
= matrix_rot
@ Vector((0.0, 1.0, 0.0))
627 to
= matrix_rot
@ Vector((0.0, 0.0, -1.0))
629 # TODO We could export much more...
630 render
= scene_data
.scene
.render
631 width
= render
.resolution_x
632 height
= render
.resolution_y
633 aspect
= width
/ height
634 # Film width & height from mm to inches
635 filmwidth
= convert_mm_to_inch(cam_data
.sensor_width
)
636 filmheight
= convert_mm_to_inch(cam_data
.sensor_height
)
637 filmaspect
= filmwidth
/ filmheight
639 offsetx
= filmwidth
* cam_data
.shift_x
640 offsety
= filmaspect
* filmheight
* cam_data
.shift_y
642 cam
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(cam_key
))
643 cam
.add_string(fbx_name_class(cam_data
.name
.encode(), b
"NodeAttribute"))
644 cam
.add_string(b
"Camera")
646 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Camera")
647 props
= elem_properties(cam
)
649 elem_props_template_set(tmpl
, props
, "p_vector", b
"Position", loc
)
650 elem_props_template_set(tmpl
, props
, "p_vector", b
"UpVector", up
)
651 elem_props_template_set(tmpl
, props
, "p_vector", b
"InterestPosition", loc
+ to
) # Point, not vector!
652 # Should we use world value?
653 elem_props_template_set(tmpl
, props
, "p_color", b
"BackgroundColor", (0.0, 0.0, 0.0))
654 elem_props_template_set(tmpl
, props
, "p_bool", b
"DisplayTurnTableIcon", True)
656 elem_props_template_set(tmpl
, props
, "p_enum", b
"AspectRatioMode", 2) # FixedResolution
657 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectWidth", float(render
.resolution_x
))
658 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectHeight", float(render
.resolution_y
))
659 elem_props_template_set(tmpl
, props
, "p_double", b
"PixelAspectRatio",
660 float(render
.pixel_aspect_x
/ render
.pixel_aspect_y
))
662 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmWidth", filmwidth
)
663 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmHeight", filmheight
)
664 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmAspectRatio", filmaspect
)
665 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmOffsetX", offsetx
)
666 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmOffsetY", offsety
)
668 elem_props_template_set(tmpl
, props
, "p_enum", b
"ApertureMode", 3) # FocalLength.
669 elem_props_template_set(tmpl
, props
, "p_enum", b
"GateFit", 2) # FitHorizontal.
670 elem_props_template_set(tmpl
, props
, "p_fov", b
"FieldOfView", math
.degrees(cam_data
.angle_x
))
671 elem_props_template_set(tmpl
, props
, "p_fov_x", b
"FieldOfViewX", math
.degrees(cam_data
.angle_x
))
672 elem_props_template_set(tmpl
, props
, "p_fov_y", b
"FieldOfViewY", math
.degrees(cam_data
.angle_y
))
673 # No need to convert to inches here...
674 elem_props_template_set(tmpl
, props
, "p_double", b
"FocalLength", cam_data
.lens
)
675 elem_props_template_set(tmpl
, props
, "p_double", b
"SafeAreaAspectRatio", aspect
)
676 # Depth of field and Focus distance.
677 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseDepthOfField", cam_data
.dof
.use_dof
)
678 elem_props_template_set(tmpl
, props
, "p_double", b
"FocusDistance", cam_data
.dof
.focus_distance
* 1000 * gscale
)
679 # Default to perspective camera.
680 elem_props_template_set(tmpl
, props
, "p_enum", b
"CameraProjectionType", 1 if cam_data
.type == 'ORTHO' else 0)
681 elem_props_template_set(tmpl
, props
, "p_double", b
"OrthoZoom", cam_data
.ortho_scale
)
683 elem_props_template_set(tmpl
, props
, "p_double", b
"NearPlane", cam_data
.clip_start
* gscale
)
684 elem_props_template_set(tmpl
, props
, "p_double", b
"FarPlane", cam_data
.clip_end
* gscale
)
685 elem_props_template_set(tmpl
, props
, "p_enum", b
"BackPlaneDistanceMode", 1) # RelativeToCamera.
686 elem_props_template_set(tmpl
, props
, "p_double", b
"BackPlaneDistance", cam_data
.clip_end
* gscale
)
688 elem_props_template_finalize(tmpl
, props
)
691 if scene_data
.settings
.use_custom_props
:
692 fbx_data_element_custom_properties(props
, cam_data
)
694 elem_data_single_string(cam
, b
"TypeFlags", b
"Camera")
695 elem_data_single_int32(cam
, b
"GeometryVersion", 124) # Sic...
696 elem_data_vec_float64(cam
, b
"Position", loc
)
697 elem_data_vec_float64(cam
, b
"Up", up
)
698 elem_data_vec_float64(cam
, b
"LookAt", to
)
699 elem_data_single_int32(cam
, b
"ShowInfoOnMoving", 1)
700 elem_data_single_int32(cam
, b
"ShowAudio", 0)
701 elem_data_vec_float64(cam
, b
"AudioColor", (0.0, 1.0, 0.0))
702 elem_data_single_float64(cam
, b
"CameraOrthoZoom", 1.0)
705 def fbx_data_bindpose_element(root
, me_obj
, me
, scene_data
, arm_obj
=None, mat_world_arm
=None, bones
=[]):
707 Helper, since bindpose are used by both meshes shape keys and armature bones...
711 # We assume bind pose for our bones are their "Editmode" pose...
712 # All matrices are expected in global (world) space.
713 bindpose_key
= get_blender_bindpose_key(arm_obj
.bdata
, me
)
714 fbx_pose
= elem_data_single_int64(root
, b
"Pose", get_fbx_uuid_from_key(bindpose_key
))
715 fbx_pose
.add_string(fbx_name_class(me
.name
.encode(), b
"Pose"))
716 fbx_pose
.add_string(b
"BindPose")
718 elem_data_single_string(fbx_pose
, b
"Type", b
"BindPose")
719 elem_data_single_int32(fbx_pose
, b
"Version", FBX_POSE_BIND_VERSION
)
720 elem_data_single_int32(fbx_pose
, b
"NbPoseNodes", 1 + (1 if (arm_obj
!= me_obj
) else 0) + len(bones
))
722 # First node is mesh/object.
723 mat_world_obj
= me_obj
.fbx_object_matrix(scene_data
, global_space
=True)
724 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
725 elem_data_single_int64(fbx_posenode
, b
"Node", me_obj
.fbx_uuid
)
726 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(mat_world_obj
))
727 # Second node is armature object itself.
728 if arm_obj
!= me_obj
:
729 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
730 elem_data_single_int64(fbx_posenode
, b
"Node", arm_obj
.fbx_uuid
)
731 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(mat_world_arm
))
732 # And all bones of armature!
735 bomat
= bo_obj
.fbx_object_matrix(scene_data
, rest
=True, global_space
=True)
736 mat_world_bones
[bo_obj
] = bomat
737 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
738 elem_data_single_int64(fbx_posenode
, b
"Node", bo_obj
.fbx_uuid
)
739 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(bomat
))
741 return mat_world_obj
, mat_world_bones
744 def fbx_data_mesh_shapes_elements(root
, me_obj
, me
, scene_data
, fbx_me_tmpl
, fbx_me_props
):
746 Write shape keys related data.
748 if me
not in scene_data
.data_deformers_shape
:
751 write_normals
= True # scene_data.settings.mesh_smooth_type in {'OFF'}
753 # First, write the geometry data itself (i.e. shapes).
754 _me_key
, shape_key
, shapes
= scene_data
.data_deformers_shape
[me
]
758 for shape
, (channel_key
, geom_key
, shape_verts_co
, shape_verts_idx
) in shapes
.items():
759 # Use vgroups as weights, if defined.
760 if shape
.vertex_group
and shape
.vertex_group
in me_obj
.bdata
.vertex_groups
:
761 shape_verts_weights
= [0.0] * (len(shape_verts_co
) // 3)
762 vg_idx
= me_obj
.bdata
.vertex_groups
[shape
.vertex_group
].index
763 for sk_idx
, v_idx
in enumerate(shape_verts_idx
):
764 for vg
in me
.vertices
[v_idx
].groups
:
765 if vg
.group
== vg_idx
:
766 shape_verts_weights
[sk_idx
] = vg
.weight
* 100.0
768 shape_verts_weights
= [100.0] * (len(shape_verts_co
) // 3)
769 channels
.append((channel_key
, shape
, shape_verts_weights
))
771 geom
= elem_data_single_int64(root
, b
"Geometry", get_fbx_uuid_from_key(geom_key
))
772 geom
.add_string(fbx_name_class(shape
.name
.encode(), b
"Geometry"))
773 geom
.add_string(b
"Shape")
775 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Geometry")
776 props
= elem_properties(geom
)
777 elem_props_template_finalize(tmpl
, props
)
779 elem_data_single_int32(geom
, b
"Version", FBX_GEOMETRY_SHAPE_VERSION
)
781 elem_data_single_int32_array(geom
, b
"Indexes", shape_verts_idx
)
782 elem_data_single_float64_array(geom
, b
"Vertices", shape_verts_co
)
784 elem_data_single_float64_array(geom
, b
"Normals", [0.0] * len(shape_verts_co
))
786 # Yiha! BindPose for shapekeys too! Dodecasigh...
787 # XXX Not sure yet whether several bindposes on same mesh are allowed, or not... :/
788 fbx_data_bindpose_element(root
, me_obj
, me
, scene_data
)
790 # ...and now, the deformers stuff.
791 fbx_shape
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(shape_key
))
792 fbx_shape
.add_string(fbx_name_class(me
.name
.encode(), b
"Deformer"))
793 fbx_shape
.add_string(b
"BlendShape")
795 elem_data_single_int32(fbx_shape
, b
"Version", FBX_DEFORMER_SHAPE_VERSION
)
797 for channel_key
, shape
, shape_verts_weights
in channels
:
798 fbx_channel
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(channel_key
))
799 fbx_channel
.add_string(fbx_name_class(shape
.name
.encode(), b
"SubDeformer"))
800 fbx_channel
.add_string(b
"BlendShapeChannel")
802 elem_data_single_int32(fbx_channel
, b
"Version", FBX_DEFORMER_SHAPECHANNEL_VERSION
)
803 elem_data_single_float64(fbx_channel
, b
"DeformPercent", shape
.value
* 100.0) # Percents...
804 elem_data_single_float64_array(fbx_channel
, b
"FullWeights", shape_verts_weights
)
806 # *WHY* add this in linked mesh properties too? *cry*
807 # No idea whether it’s percent here too, or more usual factor (assume percentage for now) :/
808 elem_props_template_set(fbx_me_tmpl
, fbx_me_props
, "p_number", shape
.name
.encode(), shape
.value
* 100.0,
812 def fbx_data_mesh_elements(root
, me_obj
, scene_data
, done_meshes
):
814 Write the Mesh (Geometry) data block.
817 def _infinite_gen(val
):
821 me_key
, me
, _free
= scene_data
.data_meshes
[me_obj
]
823 # In case of multiple instances of same mesh, only write it once!
824 if me_key
in done_meshes
:
827 # No gscale/gmat here, all data are supposed to be in object space.
828 smooth_type
= scene_data
.settings
.mesh_smooth_type
829 write_normals
= True # smooth_type in {'OFF'}
831 do_bake_space_transform
= me_obj
.use_bake_space_transform(scene_data
)
833 # Vertices are in object space, but we are post-multiplying all transforms with the inverse of the
834 # global matrix, so we need to apply the global matrix to the vertices to get the correct result.
835 geom_mat_co
= scene_data
.settings
.global_matrix
if do_bake_space_transform
else None
836 # We need to apply the inverse transpose of the global matrix when transforming normals.
837 geom_mat_no
= Matrix(scene_data
.settings
.global_matrix_inv_transposed
) if do_bake_space_transform
else None
838 if geom_mat_no
is not None:
839 # Remove translation & scaling!
840 geom_mat_no
.translation
= Vector()
841 geom_mat_no
.normalize()
843 geom
= elem_data_single_int64(root
, b
"Geometry", get_fbx_uuid_from_key(me_key
))
844 geom
.add_string(fbx_name_class(me
.name
.encode(), b
"Geometry"))
845 geom
.add_string(b
"Mesh")
847 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Geometry")
848 props
= elem_properties(geom
)
851 if scene_data
.settings
.use_custom_props
:
852 fbx_data_element_custom_properties(props
, me
)
854 # Subdivision levels. Take them from the first found subsurf modifier from the
855 # first object that has the mesh. Write crease information if the object has
856 # and subsurf modifier.
858 if scene_data
.settings
.use_subsurf
:
860 for mod
in me_obj
.bdata
.modifiers
:
861 if not (mod
.show_render
or mod
.show_viewport
):
863 if mod
.type == 'SUBSURF' and mod
.subdivision_type
== 'CATMULL_CLARK':
867 elem_data_single_int32(geom
, b
"Smoothness", 2) # Display control mesh and smoothed
868 if last_subsurf
.boundary_smooth
== "PRESERVE_CORNERS":
869 elem_data_single_int32(geom
, b
"BoundaryRule", 1) # CreaseAll
871 elem_data_single_int32(geom
, b
"BoundaryRule", 2) # CreaseEdge
872 elem_data_single_int32(geom
, b
"PreviewDivisionLevels", last_subsurf
.levels
)
873 elem_data_single_int32(geom
, b
"RenderDivisionLevels", last_subsurf
.render_levels
)
875 elem_data_single_int32(geom
, b
"PreserveBorders", 0)
876 elem_data_single_int32(geom
, b
"PreserveHardEdges", 0)
877 elem_data_single_int32(geom
, b
"PropagateEdgeHardness", 0)
879 write_crease
= last_subsurf
.use_creases
881 elem_data_single_int32(geom
, b
"GeometryVersion", FBX_GEOMETRY_VERSION
)
884 t_co
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.vertices
) * 3
885 me
.vertices
.foreach_get("co", t_co
)
886 elem_data_single_float64_array(geom
, b
"Vertices", chain(*vcos_transformed_gen(t_co
, geom_mat_co
)))
891 # We do loose edges as two-vertices faces, if enabled...
893 # Note we have to process Edges in the same time, as they are based on poly's loops...
894 loop_nbr
= len(me
.loops
)
895 t_pvi
= array
.array(data_types
.ARRAY_INT32
, (0,)) * loop_nbr
896 t_ls
= [None] * len(me
.polygons
)
898 me
.loops
.foreach_get("vertex_index", t_pvi
)
899 me
.polygons
.foreach_get("loop_start", t_ls
)
901 # Add "fake" faces for loose edges.
902 if scene_data
.settings
.use_mesh_edges
:
903 t_le
= tuple(e
.vertices
for e
in me
.edges
if e
.is_loose
)
904 t_pvi
.extend(chain(*t_le
))
905 t_ls
.extend(range(loop_nbr
, loop_nbr
+ len(t_le
), 2))
909 # Note: Edges are represented as a loop here: each edge uses a single index, which refers to the polygon array.
910 # The edge is made by the vertex indexed py this polygon's point and the next one on the same polygon.
911 # Advantage: Only one index per edge.
912 # Drawback: Only polygon's edges can be represented (that's why we have to add fake two-verts polygons
914 # We also have to store a mapping from real edges to their indices in this array, for edge-mapped data
915 # (like e.g. crease).
916 t_eli
= array
.array(data_types
.ARRAY_INT32
)
921 todo_edges
= [None] * len(me
.edges
) * 2
922 # Sigh, cannot access edge.key through foreach_get... :/
923 me
.edges
.foreach_get("vertices", todo_edges
)
924 todo_edges
= set((v1
, v2
) if v1
< v2
else (v2
, v1
) for v1
, v2
in zip(*(iter(todo_edges
),) * 2))
927 vi
= vi_start
= t_pvi
[0]
928 for li_next
, vi_next
in enumerate(t_pvi
[1:] + t_pvi
[:1], start
=1):
929 if li_next
in t_ls
: # End of a poly's loop.
935 e_key
= (vi
, vi2
) if vi
< vi2
else (vi2
, vi
)
936 if e_key
in todo_edges
:
938 todo_edges
.remove(e_key
)
939 edges_map
[e_key
] = edges_nbr
946 # We have to ^-1 last index of each loop.
950 # And finally we can write data!
951 elem_data_single_int32_array(geom
, b
"PolygonVertexIndex", t_pvi
)
952 elem_data_single_int32_array(geom
, b
"Edges", t_eli
)
960 if smooth_type
in {'FACE', 'EDGE'}:
963 if smooth_type
== 'FACE':
964 t_ps
= array
.array(data_types
.ARRAY_INT32
, (0,)) * len(me
.polygons
)
965 me
.polygons
.foreach_get("use_smooth", t_ps
)
968 # Write Edge Smoothing.
969 # Note edge is sharp also if it's used by more than two faces, or one of its faces is flat.
970 t_ps
= array
.array(data_types
.ARRAY_INT32
, (0,)) * edges_nbr
972 temp_sharp_edges
= {}
973 for p
in me
.polygons
:
975 sharp_edges
.update(p
.edge_keys
)
977 for k
in p
.edge_keys
:
978 if temp_sharp_edges
.setdefault(k
, 0) > 1:
981 temp_sharp_edges
[k
] += 1
984 if e
.key
not in edges_map
:
985 continue # Only loose edges, in theory!
986 t_ps
[edges_map
[e
.key
]] = not (e
.use_edge_sharp
or (e
.key
in sharp_edges
))
988 lay_smooth
= elem_data_single_int32(geom
, b
"LayerElementSmoothing", 0)
989 elem_data_single_int32(lay_smooth
, b
"Version", FBX_GEOMETRY_SMOOTHING_VERSION
)
990 elem_data_single_string(lay_smooth
, b
"Name", b
"")
991 elem_data_single_string(lay_smooth
, b
"MappingInformationType", _map
)
992 elem_data_single_string(lay_smooth
, b
"ReferenceInformationType", b
"Direct")
993 elem_data_single_int32_array(lay_smooth
, b
"Smoothing", t_ps
) # Sight, int32 for bool...
996 # Edge crease for subdivision
998 t_ec
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * edges_nbr
1000 if e
.key
not in edges_map
:
1001 continue # Only loose edges, in theory!
1002 # Blender squares those values before sending them to OpenSubdiv, when other software don't,
1003 # so we need to compensate that to get similar results through FBX...
1004 t_ec
[edges_map
[e
.key
]] = e
.crease
* e
.crease
1006 lay_crease
= elem_data_single_int32(geom
, b
"LayerElementEdgeCrease", 0)
1007 elem_data_single_int32(lay_crease
, b
"Version", FBX_GEOMETRY_CREASE_VERSION
)
1008 elem_data_single_string(lay_crease
, b
"Name", b
"")
1009 elem_data_single_string(lay_crease
, b
"MappingInformationType", b
"ByEdge")
1010 elem_data_single_string(lay_crease
, b
"ReferenceInformationType", b
"Direct")
1011 elem_data_single_float64_array(lay_crease
, b
"EdgeCrease", t_ec
)
1014 # And we are done with edges!
1020 # NOTE: this is not supported by importer currently.
1021 # XXX Official docs says normals should use IndexToDirect,
1022 # but this does not seem well supported by apps currently...
1023 me
.calc_normals_split()
1025 t_ln
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.loops
) * 3
1026 me
.loops
.foreach_get("normal", t_ln
)
1027 t_ln
= nors_transformed_gen(t_ln
, geom_mat_no
)
1029 t_ln
= tuple(t_ln
) # No choice... :/
1031 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementNormal", 0)
1032 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_NORMAL_VERSION
)
1033 elem_data_single_string(lay_nor
, b
"Name", b
"")
1034 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1035 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"IndexToDirect")
1037 ln2idx
= tuple(set(t_ln
))
1038 elem_data_single_float64_array(lay_nor
, b
"Normals", chain(*ln2idx
))
1039 # Normal weights, no idea what it is.
1040 # t_lnw = array.array(data_types.ARRAY_FLOAT64, (0.0,)) * len(ln2idx)
1041 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_lnw)
1043 ln2idx
= {nor
: idx
for idx
, nor
in enumerate(ln2idx
)}
1044 elem_data_single_int32_array(lay_nor
, b
"NormalsIndex", (ln2idx
[n
] for n
in t_ln
))
1049 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementNormal", 0)
1050 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_NORMAL_VERSION
)
1051 elem_data_single_string(lay_nor
, b
"Name", b
"")
1052 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1053 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1054 elem_data_single_float64_array(lay_nor
, b
"Normals", chain(*t_ln
))
1055 # Normal weights, no idea what it is.
1056 # t_ln = array.array(data_types.ARRAY_FLOAT64, (0.0,)) * len(me.loops)
1057 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_ln)
1061 if scene_data
.settings
.use_tspace
:
1062 tspacenumber
= len(me
.uv_layers
)
1064 # We can only compute tspace on tessellated meshes, need to check that here...
1065 t_lt
= [None] * len(me
.polygons
)
1066 me
.polygons
.foreach_get("loop_total", t_lt
)
1067 if any((lt
> 4 for lt
in t_lt
)):
1069 scene_data
.settings
.report(
1071 tip_("Mesh '%s' has polygons with more than 4 vertices, "
1072 "cannot compute/export tangent space for it") % me
.name
)
1075 t_ln
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.loops
) * 3
1076 # t_lnw = array.array(data_types.ARRAY_FLOAT64, (0.0,)) * len(me.loops)
1077 uv_names
= [uvlayer
.name
for uvlayer
in me
.uv_layers
]
1078 for name
in uv_names
:
1079 me
.calc_tangents(uvmap
=name
)
1080 for idx
, uvlayer
in enumerate(me
.uv_layers
):
1082 # Loop bitangents (aka binormals).
1083 # NOTE: this is not supported by importer currently.
1084 me
.loops
.foreach_get("bitangent", t_ln
)
1085 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementBinormal", idx
)
1086 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_BINORMAL_VERSION
)
1087 elem_data_single_string_unicode(lay_nor
, b
"Name", name
)
1088 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1089 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1090 elem_data_single_float64_array(lay_nor
, b
"Binormals",
1091 chain(*nors_transformed_gen(t_ln
, geom_mat_no
)))
1092 # Binormal weights, no idea what it is.
1093 # elem_data_single_float64_array(lay_nor, b"BinormalsW", t_lnw)
1096 # NOTE: this is not supported by importer currently.
1097 me
.loops
.foreach_get("tangent", t_ln
)
1098 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementTangent", idx
)
1099 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_TANGENT_VERSION
)
1100 elem_data_single_string_unicode(lay_nor
, b
"Name", name
)
1101 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1102 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1103 elem_data_single_float64_array(lay_nor
, b
"Tangents",
1104 chain(*nors_transformed_gen(t_ln
, geom_mat_no
)))
1105 # Tangent weights, no idea what it is.
1106 # elem_data_single_float64_array(lay_nor, b"TangentsW", t_lnw)
1112 me
.free_normals_split()
1114 # Write VertexColor Layers.
1115 colors_type
= scene_data
.settings
.colors_type
1116 vcolnumber
= 0 if colors_type
== 'NONE' else len(me
.color_attributes
)
1118 def _coltuples_gen(raw_cols
):
1119 return zip(*(iter(raw_cols
),) * 4)
1121 color_prop_name
= "color_srgb" if colors_type
== 'SRGB' else "color"
1123 for colindex
, collayer
in enumerate(me
.color_attributes
):
1124 is_point
= collayer
.domain
== "POINT"
1125 vcollen
= len(me
.vertices
if is_point
else me
.loops
)
1126 t_lc
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * vcollen
* 4
1127 collayer
.data
.foreach_get(color_prop_name
, t_lc
)
1129 lay_vcol
= elem_data_single_int32(geom
, b
"LayerElementColor", colindex
)
1130 elem_data_single_int32(lay_vcol
, b
"Version", FBX_GEOMETRY_VCOLOR_VERSION
)
1131 elem_data_single_string_unicode(lay_vcol
, b
"Name", collayer
.name
)
1132 elem_data_single_string(lay_vcol
, b
"MappingInformationType", b
"ByPolygonVertex")
1133 elem_data_single_string(lay_vcol
, b
"ReferenceInformationType", b
"IndexToDirect")
1135 col2idx
= tuple(set(_coltuples_gen(t_lc
)))
1136 elem_data_single_float64_array(lay_vcol
, b
"Colors", chain(*col2idx
)) # Flatten again...
1138 col2idx
= {col
: idx
for idx
, col
in enumerate(col2idx
)}
1139 col_indices
= list(col2idx
[c
] for c
in _coltuples_gen(t_lc
))
1141 # for "point" domain colors, we could directly emit them
1142 # with a "ByVertex" mapping type, but some software does not
1143 # properly understand that. So expand to full "ByPolygonVertex"
1145 col_indices
= list((col_indices
[c
.vertex_index
] for c
in me
.loops
))
1146 elem_data_single_int32_array(lay_vcol
, b
"ColorIndex", col_indices
)
1152 # Note: LayerElementTexture is deprecated since FBX 2011 - luckily!
1153 # Textures are now only related to materials, in FBX!
1154 uvnumber
= len(me
.uv_layers
)
1156 # Looks like this mapping is also expected to convey UV islands (arg..... :((((( ).
1157 # So we need to generate unique triplets (uv, vertex_idx) here, not only just based on UV values.
1158 def _uvtuples_gen(raw_uvs
, raw_lvidxs
):
1159 return zip(zip(*(iter(raw_uvs
),) * 2), raw_lvidxs
)
1161 t_luv
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.loops
) * 2
1162 t_lvidx
= array
.array(data_types
.ARRAY_INT32
, (0,)) * len(me
.loops
)
1163 me
.loops
.foreach_get("vertex_index", t_lvidx
)
1164 for uvindex
, uvlayer
in enumerate(me
.uv_layers
):
1165 uvlayer
.data
.foreach_get("uv", t_luv
)
1166 lay_uv
= elem_data_single_int32(geom
, b
"LayerElementUV", uvindex
)
1167 elem_data_single_int32(lay_uv
, b
"Version", FBX_GEOMETRY_UV_VERSION
)
1168 elem_data_single_string_unicode(lay_uv
, b
"Name", uvlayer
.name
)
1169 elem_data_single_string(lay_uv
, b
"MappingInformationType", b
"ByPolygonVertex")
1170 elem_data_single_string(lay_uv
, b
"ReferenceInformationType", b
"IndexToDirect")
1172 uv_ids
= tuple(set(_uvtuples_gen(t_luv
, t_lvidx
)))
1173 elem_data_single_float64_array(lay_uv
, b
"UV", chain(*(uv
for uv
, vidx
in uv_ids
))) # Flatten again...
1175 uv2idx
= {uv_id
: idx
for idx
, uv_id
in enumerate(uv_ids
)}
1176 elem_data_single_int32_array(lay_uv
, b
"UVIndex", (uv2idx
[uv_id
] for uv_id
in _uvtuples_gen(t_luv
, t_lvidx
)))
1184 me_fbxmaterials_idx
= scene_data
.mesh_material_indices
.get(me
)
1185 if me_fbxmaterials_idx
is not None:
1186 # We cannot use me.materials here, as this array is filled with None in case materials are linked to object...
1187 me_blmaterials
= [mat_slot
.material
for mat_slot
in me_obj
.material_slots
]
1188 if me_fbxmaterials_idx
and me_blmaterials
:
1189 lay_ma
= elem_data_single_int32(geom
, b
"LayerElementMaterial", 0)
1190 elem_data_single_int32(lay_ma
, b
"Version", FBX_GEOMETRY_MATERIAL_VERSION
)
1191 elem_data_single_string(lay_ma
, b
"Name", b
"")
1192 nbr_mats
= len(me_fbxmaterials_idx
)
1194 t_pm
= array
.array(data_types
.ARRAY_INT32
, (0,)) * len(me
.polygons
)
1195 me
.polygons
.foreach_get("material_index", t_pm
)
1197 # We have to validate mat indices, and map them to FBX indices.
1198 # Note a mat might not be in me_fbxmats_idx (e.g. node mats are ignored).
1199 blmaterials_to_fbxmaterials_idxs
= [me_fbxmaterials_idx
[m
]
1200 for m
in me_blmaterials
if m
in me_fbxmaterials_idx
]
1201 ma_idx_limit
= len(blmaterials_to_fbxmaterials_idxs
)
1202 def_ma
= blmaterials_to_fbxmaterials_idxs
[0]
1203 _gen
= (blmaterials_to_fbxmaterials_idxs
[m
] if m
< ma_idx_limit
else def_ma
for m
in t_pm
)
1204 t_pm
= array
.array(data_types
.ARRAY_INT32
, _gen
)
1206 elem_data_single_string(lay_ma
, b
"MappingInformationType", b
"ByPolygon")
1207 # XXX Logically, should be "Direct" reference type, since we do not have any index array, and have one
1208 # value per polygon...
1209 # But looks like FBX expects it to be IndexToDirect here (maybe because materials are already
1210 # indices??? *sigh*).
1211 elem_data_single_string(lay_ma
, b
"ReferenceInformationType", b
"IndexToDirect")
1212 elem_data_single_int32_array(lay_ma
, b
"Materials", t_pm
)
1215 elem_data_single_string(lay_ma
, b
"MappingInformationType", b
"AllSame")
1216 elem_data_single_string(lay_ma
, b
"ReferenceInformationType", b
"IndexToDirect")
1217 elem_data_single_int32_array(lay_ma
, b
"Materials", [0])
1219 # And the "layer TOC"...
1221 layer
= elem_data_single_int32(geom
, b
"Layer", 0)
1222 elem_data_single_int32(layer
, b
"Version", FBX_GEOMETRY_LAYER_VERSION
)
1224 lay_nor
= elem_empty(layer
, b
"LayerElement")
1225 elem_data_single_string(lay_nor
, b
"Type", b
"LayerElementNormal")
1226 elem_data_single_int32(lay_nor
, b
"TypedIndex", 0)
1228 lay_binor
= elem_empty(layer
, b
"LayerElement")
1229 elem_data_single_string(lay_binor
, b
"Type", b
"LayerElementBinormal")
1230 elem_data_single_int32(lay_binor
, b
"TypedIndex", 0)
1231 lay_tan
= elem_empty(layer
, b
"LayerElement")
1232 elem_data_single_string(lay_tan
, b
"Type", b
"LayerElementTangent")
1233 elem_data_single_int32(lay_tan
, b
"TypedIndex", 0)
1234 if smooth_type
in {'FACE', 'EDGE'}:
1235 lay_smooth
= elem_empty(layer
, b
"LayerElement")
1236 elem_data_single_string(lay_smooth
, b
"Type", b
"LayerElementSmoothing")
1237 elem_data_single_int32(lay_smooth
, b
"TypedIndex", 0)
1239 lay_smooth
= elem_empty(layer
, b
"LayerElement")
1240 elem_data_single_string(lay_smooth
, b
"Type", b
"LayerElementEdgeCrease")
1241 elem_data_single_int32(lay_smooth
, b
"TypedIndex", 0)
1243 lay_vcol
= elem_empty(layer
, b
"LayerElement")
1244 elem_data_single_string(lay_vcol
, b
"Type", b
"LayerElementColor")
1245 elem_data_single_int32(lay_vcol
, b
"TypedIndex", 0)
1247 lay_uv
= elem_empty(layer
, b
"LayerElement")
1248 elem_data_single_string(lay_uv
, b
"Type", b
"LayerElementUV")
1249 elem_data_single_int32(lay_uv
, b
"TypedIndex", 0)
1250 if me_fbxmaterials_idx
is not None:
1251 lay_ma
= elem_empty(layer
, b
"LayerElement")
1252 elem_data_single_string(lay_ma
, b
"Type", b
"LayerElementMaterial")
1253 elem_data_single_int32(lay_ma
, b
"TypedIndex", 0)
1255 # Add other uv and/or vcol layers...
1256 for vcolidx
, uvidx
, tspaceidx
in zip_longest(range(1, vcolnumber
), range(1, uvnumber
), range(1, tspacenumber
),
1258 layer
= elem_data_single_int32(geom
, b
"Layer", max(vcolidx
, uvidx
))
1259 elem_data_single_int32(layer
, b
"Version", FBX_GEOMETRY_LAYER_VERSION
)
1261 lay_vcol
= elem_empty(layer
, b
"LayerElement")
1262 elem_data_single_string(lay_vcol
, b
"Type", b
"LayerElementColor")
1263 elem_data_single_int32(lay_vcol
, b
"TypedIndex", vcolidx
)
1265 lay_uv
= elem_empty(layer
, b
"LayerElement")
1266 elem_data_single_string(lay_uv
, b
"Type", b
"LayerElementUV")
1267 elem_data_single_int32(lay_uv
, b
"TypedIndex", uvidx
)
1269 lay_binor
= elem_empty(layer
, b
"LayerElement")
1270 elem_data_single_string(lay_binor
, b
"Type", b
"LayerElementBinormal")
1271 elem_data_single_int32(lay_binor
, b
"TypedIndex", tspaceidx
)
1272 lay_tan
= elem_empty(layer
, b
"LayerElement")
1273 elem_data_single_string(lay_tan
, b
"Type", b
"LayerElementTangent")
1274 elem_data_single_int32(lay_tan
, b
"TypedIndex", tspaceidx
)
1277 fbx_data_mesh_shapes_elements(root
, me_obj
, me
, scene_data
, tmpl
, props
)
1279 elem_props_template_finalize(tmpl
, props
)
1280 done_meshes
.add(me_key
)
1283 def fbx_data_material_elements(root
, ma
, scene_data
):
1285 Write the Material data block.
1288 ambient_color
= (0.0, 0.0, 0.0)
1289 if scene_data
.data_world
:
1290 ambient_color
= next(iter(scene_data
.data_world
.keys())).color
1292 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
1293 ma_key
, _objs
= scene_data
.data_materials
[ma
]
1296 fbx_ma
= elem_data_single_int64(root
, b
"Material", get_fbx_uuid_from_key(ma_key
))
1297 fbx_ma
.add_string(fbx_name_class(ma
.name
.encode(), b
"Material"))
1298 fbx_ma
.add_string(b
"")
1300 elem_data_single_int32(fbx_ma
, b
"Version", FBX_MATERIAL_VERSION
)
1301 # those are not yet properties, it seems...
1302 elem_data_single_string(fbx_ma
, b
"ShadingModel", ma_type
)
1303 elem_data_single_int32(fbx_ma
, b
"MultiLayer", 0) # Should be bool...
1305 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Material")
1306 props
= elem_properties(fbx_ma
)
1308 elem_props_template_set(tmpl
, props
, "p_string", b
"ShadingModel", ma_type
.decode())
1309 elem_props_template_set(tmpl
, props
, "p_color", b
"DiffuseColor", ma_wrap
.base_color
)
1310 # Not in Principled BSDF, so assuming always 1
1311 elem_props_template_set(tmpl
, props
, "p_number", b
"DiffuseFactor", 1.0)
1312 # Principled BSDF only has an emissive color, so we assume factor to be always 1.0.
1313 elem_props_template_set(tmpl
, props
, "p_color", b
"EmissiveColor", ma_wrap
.emission_color
)
1314 elem_props_template_set(tmpl
, props
, "p_number", b
"EmissiveFactor", ma_wrap
.emission_strength
)
1315 # Not in Principled BSDF, so assuming always 0
1316 elem_props_template_set(tmpl
, props
, "p_color", b
"AmbientColor", ambient_color
)
1317 elem_props_template_set(tmpl
, props
, "p_number", b
"AmbientFactor", 0.0)
1318 # Sweetness... Looks like we are not the only ones to not know exactly how FBX is supposed to work (see T59850).
1319 # According to one of its developers, Unity uses that formula to extract alpha value:
1321 # alpha = 1 - TransparencyFactor
1322 # if (alpha == 1 or alpha == 0):
1323 # alpha = 1 - TransparentColor.r
1325 # Until further info, let's assume this is correct way to do, hence the following code for TransparentColor.
1326 if ma_wrap
.alpha
< 1.0e-5 or ma_wrap
.alpha
> (1.0 - 1.0e-5):
1327 elem_props_template_set(tmpl
, props
, "p_color", b
"TransparentColor", (1.0 - ma_wrap
.alpha
,) * 3)
1329 elem_props_template_set(tmpl
, props
, "p_color", b
"TransparentColor", ma_wrap
.base_color
)
1330 elem_props_template_set(tmpl
, props
, "p_number", b
"TransparencyFactor", 1.0 - ma_wrap
.alpha
)
1331 elem_props_template_set(tmpl
, props
, "p_number", b
"Opacity", ma_wrap
.alpha
)
1332 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"NormalMap", (0.0, 0.0, 0.0))
1333 elem_props_template_set(tmpl
, props
, "p_double", b
"BumpFactor", ma_wrap
.normalmap_strength
)
1334 # Not sure about those...
1336 b"Bump": ((0.0, 0.0, 0.0), "p_vector_3d"),
1337 b"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb"),
1338 b"DisplacementFactor": (0.0, "p_double"),
1340 # TODO: use specular tint?
1341 elem_props_template_set(tmpl
, props
, "p_color", b
"SpecularColor", ma_wrap
.base_color
)
1342 elem_props_template_set(tmpl
, props
, "p_number", b
"SpecularFactor", ma_wrap
.specular
/ 2.0)
1343 # See Material template about those two!
1344 # XXX Totally empirical conversion, trying to adapt it
1345 # (from 0.0 - 100.0 FBX shininess range to 1.0 - 0.0 Principled BSDF range)...
1346 shininess
= (1.0 - ma_wrap
.roughness
) * 10
1347 shininess
*= shininess
1348 elem_props_template_set(tmpl
, props
, "p_number", b
"Shininess", shininess
)
1349 elem_props_template_set(tmpl
, props
, "p_number", b
"ShininessExponent", shininess
)
1350 elem_props_template_set(tmpl
, props
, "p_color", b
"ReflectionColor", ma_wrap
.base_color
)
1351 elem_props_template_set(tmpl
, props
, "p_number", b
"ReflectionFactor", ma_wrap
.metallic
)
1353 elem_props_template_finalize(tmpl
, props
)
1355 # Custom properties.
1356 if scene_data
.settings
.use_custom_props
:
1357 fbx_data_element_custom_properties(props
, ma
)
1360 def _gen_vid_path(img
, scene_data
):
1361 msetts
= scene_data
.settings
.media_settings
1362 fname_rel
= bpy_extras
.io_utils
.path_reference(img
.filepath
, msetts
.base_src
, msetts
.base_dst
, msetts
.path_mode
,
1363 msetts
.subdir
, msetts
.copy_set
, img
.library
)
1364 fname_abs
= os
.path
.normpath(os
.path
.abspath(os
.path
.join(msetts
.base_dst
, fname_rel
)))
1365 return fname_abs
, fname_rel
1368 def fbx_data_texture_file_elements(root
, blender_tex_key
, scene_data
):
1370 Write the (file) Texture data block.
1372 # XXX All this is very fuzzy to me currently...
1373 # Textures do not seem to use properties as much as they could.
1374 # For now assuming most logical and simple stuff.
1376 ma
, sock_name
= blender_tex_key
1377 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
1378 tex_key
, _fbx_prop
= scene_data
.data_textures
[blender_tex_key
]
1379 tex
= getattr(ma_wrap
, sock_name
)
1381 fname_abs
, fname_rel
= _gen_vid_path(img
, scene_data
)
1383 fbx_tex
= elem_data_single_int64(root
, b
"Texture", get_fbx_uuid_from_key(tex_key
))
1384 fbx_tex
.add_string(fbx_name_class(sock_name
.encode(), b
"Texture"))
1385 fbx_tex
.add_string(b
"")
1387 elem_data_single_string(fbx_tex
, b
"Type", b
"TextureVideoClip")
1388 elem_data_single_int32(fbx_tex
, b
"Version", FBX_TEXTURE_VERSION
)
1389 elem_data_single_string(fbx_tex
, b
"TextureName", fbx_name_class(sock_name
.encode(), b
"Texture"))
1390 elem_data_single_string(fbx_tex
, b
"Media", fbx_name_class(img
.name
.encode(), b
"Video"))
1391 elem_data_single_string_unicode(fbx_tex
, b
"FileName", fname_abs
)
1392 elem_data_single_string_unicode(fbx_tex
, b
"RelativeFilename", fname_rel
)
1394 alpha_source
= 0 # None
1395 if img
.alpha_mode
!= 'NONE':
1396 # ~ if tex.texture.use_calculate_alpha:
1397 # ~ alpha_source = 1 # RGBIntensity as alpha.
1399 # ~ alpha_source = 2 # Black, i.e. alpha channel.
1400 alpha_source
= 2 # Black, i.e. alpha channel.
1401 # BlendMode not useful for now, only affects layered textures afaics.
1404 if tex
.texcoords
== 'ORCO': # XXX Others?
1405 if tex
.projection
== 'FLAT':
1406 mapping
= 1 # Planar
1407 elif tex
.projection
== 'CUBE':
1409 elif tex
.projection
== 'TUBE':
1410 mapping
= 3 # Cylindrical
1411 elif tex
.projection
== 'SPHERE':
1412 mapping
= 2 # Spherical
1413 elif tex
.texcoords
== 'UV':
1415 # Yuck, UVs are linked by mere names it seems... :/
1416 # XXX TODO how to get that now???
1417 # uvset = tex.uv_layer
1418 wrap_mode
= 1 # Clamp
1419 if tex
.extension
== 'REPEAT':
1420 wrap_mode
= 0 # Repeat
1422 tmpl
= elem_props_template_init(scene_data
.templates
, b
"TextureFile")
1423 props
= elem_properties(fbx_tex
)
1424 elem_props_template_set(tmpl
, props
, "p_enum", b
"AlphaSource", alpha_source
)
1425 elem_props_template_set(tmpl
, props
, "p_bool", b
"PremultiplyAlpha",
1426 img
.alpha_mode
in {'STRAIGHT'}) # Or is it PREMUL?
1427 elem_props_template_set(tmpl
, props
, "p_enum", b
"CurrentMappingType", mapping
)
1428 if uvset
is not None:
1429 elem_props_template_set(tmpl
, props
, "p_string", b
"UVSet", uvset
)
1430 elem_props_template_set(tmpl
, props
, "p_enum", b
"WrapModeU", wrap_mode
)
1431 elem_props_template_set(tmpl
, props
, "p_enum", b
"WrapModeV", wrap_mode
)
1432 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Translation", tex
.translation
)
1433 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Rotation", (-r
for r
in tex
.rotation
))
1434 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Scaling", (((1.0 / s
) if s
!= 0.0 else 1.0) for s
in tex
.scale
))
1435 # UseMaterial should always be ON imho.
1436 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseMaterial", True)
1437 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseMipMap", False)
1438 elem_props_template_finalize(tmpl
, props
)
1440 # No custom properties, since that's not a data-block anymore.
1443 def fbx_data_video_elements(root
, vid
, scene_data
):
1445 Write the actual image data block.
1447 msetts
= scene_data
.settings
.media_settings
1449 vid_key
, _texs
= scene_data
.data_videos
[vid
]
1450 fname_abs
, fname_rel
= _gen_vid_path(vid
, scene_data
)
1452 fbx_vid
= elem_data_single_int64(root
, b
"Video", get_fbx_uuid_from_key(vid_key
))
1453 fbx_vid
.add_string(fbx_name_class(vid
.name
.encode(), b
"Video"))
1454 fbx_vid
.add_string(b
"Clip")
1456 elem_data_single_string(fbx_vid
, b
"Type", b
"Clip")
1459 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Video")
1460 props
= elem_properties(fbx_vid
)
1461 elem_props_template_set(tmpl
, props
, "p_string_url", b
"Path", fname_abs
)
1462 elem_props_template_finalize(tmpl
, props
)
1464 elem_data_single_int32(fbx_vid
, b
"UseMipMap", 0)
1465 elem_data_single_string_unicode(fbx_vid
, b
"Filename", fname_abs
)
1466 elem_data_single_string_unicode(fbx_vid
, b
"RelativeFilename", fname_rel
)
1468 if scene_data
.settings
.media_settings
.embed_textures
:
1469 if vid
.packed_file
is not None:
1470 # We only ever embed a given file once!
1471 if fname_abs
not in msetts
.embedded_set
:
1472 elem_data_single_bytes(fbx_vid
, b
"Content", vid
.packed_file
.data
)
1473 msetts
.embedded_set
.add(fname_abs
)
1475 filepath
= bpy
.path
.abspath(vid
.filepath
)
1476 # We only ever embed a given file once!
1477 if filepath
not in msetts
.embedded_set
:
1479 with
open(filepath
, 'br') as f
:
1480 elem_data_single_bytes(fbx_vid
, b
"Content", f
.read())
1481 except Exception as e
:
1482 print("WARNING: embedding file {} failed ({})".format(filepath
, e
))
1483 elem_data_single_bytes(fbx_vid
, b
"Content", b
"")
1484 msetts
.embedded_set
.add(filepath
)
1485 # Looks like we'd rather not write any 'Content' element in this case (see T44442).
1486 # Sounds suspect, but let's try it!
1488 #~ elem_data_single_bytes(fbx_vid, b"Content", b"")
1491 def fbx_data_armature_elements(root
, arm_obj
, scene_data
):
1494 * Bones "data" (NodeAttribute::LimbNode, contains pretty much nothing!).
1495 * Deformers (i.e. Skin), bind between an armature and a mesh.
1496 ** SubDeformers (i.e. Cluster), one per bone/vgroup pair.
1498 Note armature itself has no data, it is a mere "Null" Model...
1500 mat_world_arm
= arm_obj
.fbx_object_matrix(scene_data
, global_space
=True)
1501 bones
= tuple(bo_obj
for bo_obj
in arm_obj
.bones
if bo_obj
in scene_data
.objects
)
1503 bone_radius_scale
= 33.0
1506 for bo_obj
in bones
:
1508 bo_data_key
= scene_data
.data_bones
[bo_obj
]
1509 fbx_bo
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(bo_data_key
))
1510 fbx_bo
.add_string(fbx_name_class(bo
.name
.encode(), b
"NodeAttribute"))
1511 fbx_bo
.add_string(b
"LimbNode")
1512 elem_data_single_string(fbx_bo
, b
"TypeFlags", b
"Skeleton")
1514 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Bone")
1515 props
= elem_properties(fbx_bo
)
1516 elem_props_template_set(tmpl
, props
, "p_double", b
"Size", bo
.head_radius
* bone_radius_scale
)
1517 elem_props_template_finalize(tmpl
, props
)
1519 # Custom properties.
1520 if scene_data
.settings
.use_custom_props
:
1521 fbx_data_element_custom_properties(props
, bo
)
1523 # Store Blender bone length - XXX Not much useful actually :/
1524 # (LimbLength can't be used because it is a scale factor 0-1 for the parent-child distance:
1525 # http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/cpp_ref/class_fbx_skeleton.html#a9bbe2a70f4ed82cd162620259e649f0f )
1526 # elem_props_set(props, "p_double", "BlenderBoneLength".encode(), (bo.tail_local - bo.head_local).length, custom=True)
1528 # Skin deformers and BindPoses.
1529 # Note: we might also use Deformers for our "parent to vertex" stuff???
1530 deformer
= scene_data
.data_deformers_skin
.get(arm_obj
, None)
1531 if deformer
is not None:
1532 for me
, (skin_key
, ob_obj
, clusters
) in deformer
.items():
1534 mat_world_obj
, mat_world_bones
= fbx_data_bindpose_element(root
, ob_obj
, me
, scene_data
,
1535 arm_obj
, mat_world_arm
, bones
)
1538 fbx_skin
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(skin_key
))
1539 fbx_skin
.add_string(fbx_name_class(arm_obj
.name
.encode(), b
"Deformer"))
1540 fbx_skin
.add_string(b
"Skin")
1542 elem_data_single_int32(fbx_skin
, b
"Version", FBX_DEFORMER_SKIN_VERSION
)
1543 elem_data_single_float64(fbx_skin
, b
"Link_DeformAcuracy", 50.0) # Only vague idea what it is...
1545 # Pre-process vertex weights (also to check vertices assigned to more than four bones).
1547 bo_vg_idx
= {bo_obj
.bdata
.name
: ob
.vertex_groups
[bo_obj
.bdata
.name
].index
1548 for bo_obj
in clusters
.keys() if bo_obj
.bdata
.name
in ob
.vertex_groups
}
1549 valid_idxs
= set(bo_vg_idx
.values())
1550 vgroups
= {vg
.index
: {} for vg
in ob
.vertex_groups
}
1551 verts_vgroups
= (sorted(((vg
.group
, vg
.weight
) for vg
in v
.groups
if vg
.weight
and vg
.group
in valid_idxs
),
1552 key
=lambda e
: e
[1], reverse
=True)
1553 for v
in me
.vertices
)
1554 for idx
, vgs
in enumerate(verts_vgroups
):
1555 for vg_idx
, w
in vgs
:
1556 vgroups
[vg_idx
][idx
] = w
1558 for bo_obj
, clstr_key
in clusters
.items():
1560 # Find which vertices are affected by this bone/vgroup pair, and matching weights.
1561 # Note we still write a cluster for bones not affecting the mesh, to get 'rest pose' data
1562 # (the TransformBlah matrices).
1563 vg_idx
= bo_vg_idx
.get(bo
.name
, None)
1564 indices
, weights
= ((), ()) if vg_idx
is None or not vgroups
[vg_idx
] else zip(*vgroups
[vg_idx
].items())
1566 # Create the cluster.
1567 fbx_clstr
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(clstr_key
))
1568 fbx_clstr
.add_string(fbx_name_class(bo
.name
.encode(), b
"SubDeformer"))
1569 fbx_clstr
.add_string(b
"Cluster")
1571 elem_data_single_int32(fbx_clstr
, b
"Version", FBX_DEFORMER_CLUSTER_VERSION
)
1572 # No idea what that user data might be...
1573 fbx_userdata
= elem_data_single_string(fbx_clstr
, b
"UserData", b
"")
1574 fbx_userdata
.add_string(b
"")
1576 elem_data_single_int32_array(fbx_clstr
, b
"Indexes", indices
)
1577 elem_data_single_float64_array(fbx_clstr
, b
"Weights", weights
)
1578 # Transform, TransformLink and TransformAssociateModel matrices...
1579 # They seem to be doublons of BindPose ones??? Have armature (associatemodel) in addition, though.
1580 # WARNING! Even though official FBX API presents Transform in global space,
1581 # **it is stored in bone space in FBX data!** See:
1582 # http://area.autodesk.com/forum/autodesk-fbx/fbx-sdk/why-the-values-return-
1583 # by-fbxcluster-gettransformmatrix-x-not-same-with-the-value-in-ascii-fbx-file/
1584 elem_data_single_float64_array(fbx_clstr
, b
"Transform",
1585 matrix4_to_array(mat_world_bones
[bo_obj
].inverted_safe() @ mat_world_obj
))
1586 elem_data_single_float64_array(fbx_clstr
, b
"TransformLink", matrix4_to_array(mat_world_bones
[bo_obj
]))
1587 elem_data_single_float64_array(fbx_clstr
, b
"TransformAssociateModel", matrix4_to_array(mat_world_arm
))
1590 def fbx_data_leaf_bone_elements(root
, scene_data
):
1591 # Write a dummy leaf bone that is used by applications to show the length of the last bone in a chain
1592 for (node_name
, _par_uuid
, node_uuid
, attr_uuid
, matrix
, hide
, size
) in scene_data
.data_leaf_bones
:
1594 fbx_bo
= elem_data_single_int64(root
, b
"NodeAttribute", attr_uuid
)
1595 fbx_bo
.add_string(fbx_name_class(node_name
.encode(), b
"NodeAttribute"))
1596 fbx_bo
.add_string(b
"LimbNode")
1597 elem_data_single_string(fbx_bo
, b
"TypeFlags", b
"Skeleton")
1599 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Bone")
1600 props
= elem_properties(fbx_bo
)
1601 elem_props_template_set(tmpl
, props
, "p_double", b
"Size", size
)
1602 elem_props_template_finalize(tmpl
, props
)
1605 model
= elem_data_single_int64(root
, b
"Model", node_uuid
)
1606 model
.add_string(fbx_name_class(node_name
.encode(), b
"Model"))
1607 model
.add_string(b
"LimbNode")
1609 elem_data_single_int32(model
, b
"Version", FBX_MODELS_VERSION
)
1611 # Object transform info.
1612 loc
, rot
, scale
= matrix
.decompose()
1613 rot
= rot
.to_euler('XYZ')
1614 rot
= tuple(convert_rad_to_deg_iter(rot
))
1616 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Model")
1617 # For now add only loc/rot/scale...
1618 props
= elem_properties(model
)
1619 # Generated leaf bones are obviously never animated!
1620 elem_props_template_set(tmpl
, props
, "p_lcl_translation", b
"Lcl Translation", loc
)
1621 elem_props_template_set(tmpl
, props
, "p_lcl_rotation", b
"Lcl Rotation", rot
)
1622 elem_props_template_set(tmpl
, props
, "p_lcl_scaling", b
"Lcl Scaling", scale
)
1623 elem_props_template_set(tmpl
, props
, "p_visibility", b
"Visibility", float(not hide
))
1625 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1626 # invalid -1 value...
1627 elem_props_template_set(tmpl
, props
, "p_integer", b
"DefaultAttributeIndex", 0)
1629 elem_props_template_set(tmpl
, props
, "p_enum", b
"InheritType", 1) # RSrs
1631 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1633 elem_data_single_int32(model
, b
"MultiLayer", 0)
1634 elem_data_single_int32(model
, b
"MultiTake", 0)
1635 elem_data_single_bool(model
, b
"Shading", True)
1636 elem_data_single_string(model
, b
"Culling", b
"CullingOff")
1638 elem_props_template_finalize(tmpl
, props
)
1641 def fbx_data_object_elements(root
, ob_obj
, scene_data
):
1643 Write the Object (Model) data blocks.
1644 Note this "Model" can also be bone or dupli!
1646 obj_type
= b
"Null" # default, sort of empty...
1648 obj_type
= b
"LimbNode"
1649 elif (ob_obj
.type == 'ARMATURE'):
1650 if scene_data
.settings
.armature_nodetype
== 'ROOT':
1652 elif scene_data
.settings
.armature_nodetype
== 'LIMBNODE':
1653 obj_type
= b
"LimbNode"
1654 else: # Default, preferred option...
1656 elif (ob_obj
.type in BLENDER_OBJECT_TYPES_MESHLIKE
):
1658 elif (ob_obj
.type == 'LIGHT'):
1660 elif (ob_obj
.type == 'CAMERA'):
1661 obj_type
= b
"Camera"
1662 model
= elem_data_single_int64(root
, b
"Model", ob_obj
.fbx_uuid
)
1663 model
.add_string(fbx_name_class(ob_obj
.name
.encode(), b
"Model"))
1664 model
.add_string(obj_type
)
1666 elem_data_single_int32(model
, b
"Version", FBX_MODELS_VERSION
)
1668 # Object transform info.
1669 loc
, rot
, scale
, matrix
, matrix_rot
= ob_obj
.fbx_object_tx(scene_data
)
1670 rot
= tuple(convert_rad_to_deg_iter(rot
))
1672 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Model")
1673 # For now add only loc/rot/scale...
1674 props
= elem_properties(model
)
1675 elem_props_template_set(tmpl
, props
, "p_lcl_translation", b
"Lcl Translation", loc
,
1676 animatable
=True, animated
=((ob_obj
.key
, "Lcl Translation") in scene_data
.animated
))
1677 elem_props_template_set(tmpl
, props
, "p_lcl_rotation", b
"Lcl Rotation", rot
,
1678 animatable
=True, animated
=((ob_obj
.key
, "Lcl Rotation") in scene_data
.animated
))
1679 elem_props_template_set(tmpl
, props
, "p_lcl_scaling", b
"Lcl Scaling", scale
,
1680 animatable
=True, animated
=((ob_obj
.key
, "Lcl Scaling") in scene_data
.animated
))
1681 elem_props_template_set(tmpl
, props
, "p_visibility", b
"Visibility", float(not ob_obj
.hide
))
1683 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1684 # invalid -1 value...
1685 elem_props_template_set(tmpl
, props
, "p_integer", b
"DefaultAttributeIndex", 0)
1687 elem_props_template_set(tmpl
, props
, "p_enum", b
"InheritType", 1) # RSrs
1689 # Custom properties.
1690 if scene_data
.settings
.use_custom_props
:
1691 # Here we want customprops from the 'pose' bone, not the 'edit' bone...
1692 bdata
= ob_obj
.bdata_pose_bone
if ob_obj
.is_bone
else ob_obj
.bdata
1693 fbx_data_element_custom_properties(props
, bdata
)
1695 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1697 elem_data_single_int32(model
, b
"MultiLayer", 0)
1698 elem_data_single_int32(model
, b
"MultiTake", 0)
1699 elem_data_single_bool(model
, b
"Shading", True)
1700 elem_data_single_string(model
, b
"Culling", b
"CullingOff")
1702 if obj_type
== b
"Camera":
1703 # Why, oh why are FBX cameras such a mess???
1704 # And WHY add camera data HERE??? Not even sure this is needed...
1705 render
= scene_data
.scene
.render
1706 width
= render
.resolution_x
* 1.0
1707 height
= render
.resolution_y
* 1.0
1708 elem_props_template_set(tmpl
, props
, "p_enum", b
"ResolutionMode", 0) # Don't know what it means
1709 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectW", width
)
1710 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectH", height
)
1711 elem_props_template_set(tmpl
, props
, "p_bool", b
"ViewFrustum", True)
1712 elem_props_template_set(tmpl
, props
, "p_enum", b
"BackgroundMode", 0) # Don't know what it means
1713 elem_props_template_set(tmpl
, props
, "p_bool", b
"ForegroundTransparent", True)
1715 elem_props_template_finalize(tmpl
, props
)
1718 def fbx_data_animation_elements(root
, scene_data
):
1720 Write animation data.
1722 animations
= scene_data
.animations
1725 scene
= scene_data
.scene
1727 fps
= scene
.render
.fps
/ scene
.render
.fps_base
1729 def keys_to_ktimes(keys
):
1730 return (int(v
) for v
in convert_sec_to_ktime_iter((f
/ fps
for f
, _v
in keys
)))
1733 for astack_key
, alayers
, alayer_key
, name
, f_start
, f_end
in animations
:
1734 astack
= elem_data_single_int64(root
, b
"AnimationStack", get_fbx_uuid_from_key(astack_key
))
1735 astack
.add_string(fbx_name_class(name
, b
"AnimStack"))
1736 astack
.add_string(b
"")
1738 astack_tmpl
= elem_props_template_init(scene_data
.templates
, b
"AnimationStack")
1739 astack_props
= elem_properties(astack
)
1740 r
= scene_data
.scene
.render
1741 fps
= r
.fps
/ r
.fps_base
1742 start
= int(convert_sec_to_ktime(f_start
/ fps
))
1743 end
= int(convert_sec_to_ktime(f_end
/ fps
))
1744 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"LocalStart", start
)
1745 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"LocalStop", end
)
1746 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"ReferenceStart", start
)
1747 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"ReferenceStop", end
)
1748 elem_props_template_finalize(astack_tmpl
, astack_props
)
1750 # For now, only one layer for all animations.
1751 alayer
= elem_data_single_int64(root
, b
"AnimationLayer", get_fbx_uuid_from_key(alayer_key
))
1752 alayer
.add_string(fbx_name_class(name
, b
"AnimLayer"))
1753 alayer
.add_string(b
"")
1755 for ob_obj
, (alayer_key
, acurvenodes
) in alayers
.items():
1757 # alayer = elem_data_single_int64(root, b"AnimationLayer", get_fbx_uuid_from_key(alayer_key))
1758 # alayer.add_string(fbx_name_class(ob_obj.name.encode(), b"AnimLayer"))
1759 # alayer.add_string(b"")
1761 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
1762 # Animation curve node.
1763 acurvenode
= elem_data_single_int64(root
, b
"AnimationCurveNode", get_fbx_uuid_from_key(acurvenode_key
))
1764 acurvenode
.add_string(fbx_name_class(acurvenode_name
.encode(), b
"AnimCurveNode"))
1765 acurvenode
.add_string(b
"")
1767 acn_tmpl
= elem_props_template_init(scene_data
.templates
, b
"AnimationCurveNode")
1768 acn_props
= elem_properties(acurvenode
)
1770 for fbx_item
, (acurve_key
, def_value
, keys
, _acurve_valid
) in acurves
.items():
1771 elem_props_template_set(acn_tmpl
, acn_props
, "p_number", fbx_item
.encode(),
1772 def_value
, animatable
=True)
1774 # Only create Animation curve if needed!
1776 acurve
= elem_data_single_int64(root
, b
"AnimationCurve", get_fbx_uuid_from_key(acurve_key
))
1777 acurve
.add_string(fbx_name_class(b
"", b
"AnimCurve"))
1778 acurve
.add_string(b
"")
1781 nbr_keys
= len(keys
)
1784 1 << 2 |
# interpolation mode, 1 = constant, 2 = linear, 3 = cubic.
1785 1 << 8 |
# tangent mode, 8 = auto, 9 = TCB, 10 = user, 11 = generic break,
1786 1 << 13 |
# tangent mode, 12 = generic clamp, 13 = generic time independent,
1787 1 << 14 |
# tangent mode, 13 + 14 = generic clamp progressive.
1790 # Maybe values controlling TCB & co???
1791 keyattr_datafloat
= (0.0, 0.0, 9.419963346924634e-30, 0.0)
1793 # And now, the *real* data!
1794 elem_data_single_float64(acurve
, b
"Default", def_value
)
1795 elem_data_single_int32(acurve
, b
"KeyVer", FBX_ANIM_KEY_VERSION
)
1796 elem_data_single_int64_array(acurve
, b
"KeyTime", keys_to_ktimes(keys
))
1797 elem_data_single_float32_array(acurve
, b
"KeyValueFloat", (v
for _f
, v
in keys
))
1798 elem_data_single_int32_array(acurve
, b
"KeyAttrFlags", keyattr_flags
)
1799 elem_data_single_float32_array(acurve
, b
"KeyAttrDataFloat", keyattr_datafloat
)
1800 elem_data_single_int32_array(acurve
, b
"KeyAttrRefCount", (nbr_keys
,))
1802 elem_props_template_finalize(acn_tmpl
, acn_props
)
1805 # ##### Top-level FBX data container. #####
1807 # Mapping Blender -> FBX (principled_socket_name, fbx_name).
1808 PRINCIPLED_TEXTURE_SOCKETS_TO_FBX
= (
1809 # ("diffuse", "diffuse", b"DiffuseFactor"),
1810 ("base_color_texture", b
"DiffuseColor"),
1811 ("alpha_texture", b
"TransparencyFactor"), # Will be inverted in fact, not much we can do really...
1812 # ("base_color_texture", b"TransparentColor"), # Uses diffuse color in Blender!
1813 ("emission_strength_texture", b
"EmissiveFactor"),
1814 ("emission_color_texture", b
"EmissiveColor"),
1815 # ("ambient", "ambient", b"AmbientFactor"),
1816 # ("", "", b"AmbientColor"), # World stuff in Blender, for now ignore...
1817 ("normalmap_texture", b
"NormalMap"),
1818 # Note: unsure about those... :/
1819 # ("", "", b"Bump"),
1820 # ("", "", b"BumpFactor"),
1821 # ("", "", b"DisplacementColor"),
1822 # ("", "", b"DisplacementFactor"),
1823 ("specular_texture", b
"SpecularFactor"),
1824 # ("base_color", b"SpecularColor"), # TODO: use tint?
1825 # See Material template about those two!
1826 ("roughness_texture", b
"Shininess"),
1827 ("roughness_texture", b
"ShininessExponent"),
1828 # ("mirror", "mirror", b"ReflectionColor"),
1829 ("metallic_texture", b
"ReflectionFactor"),
1833 def fbx_skeleton_from_armature(scene
, settings
, arm_obj
, objects
, data_meshes
,
1834 data_bones
, data_deformers_skin
, data_empties
, arm_parents
):
1836 Create skeleton from armature/bones (NodeAttribute/LimbNode and Model/LimbNode), and for each deformed mesh,
1837 create Pose/BindPose(with sub PoseNode) and Deformer/Skin(with Deformer/SubDeformer/Cluster).
1838 Also supports "parent to bone" (simple parent to Model/LimbNode).
1839 arm_parents is a set of tuples (armature, object) for all successful armature bindings.
1841 # We need some data for our armature 'object' too!!!
1842 data_empties
[arm_obj
] = get_blender_empty_key(arm_obj
.bdata
)
1844 arm_data
= arm_obj
.bdata
.data
1846 for bo
in arm_obj
.bones
:
1847 if settings
.use_armature_deform_only
:
1848 if bo
.bdata
.use_deform
:
1851 while bo_par
.is_bone
:
1852 bones
[bo_par
] = True
1853 bo_par
= bo_par
.parent
1854 elif bo
not in bones
: # Do not override if already set in the loop above!
1859 bones
= {bo
: None for bo
, use
in bones
.items() if use
}
1864 data_bones
.update((bo
, get_blender_bone_key(arm_obj
.bdata
, bo
.bdata
)) for bo
in bones
)
1866 for ob_obj
in objects
:
1867 if not ob_obj
.is_deformed_by_armature(arm_obj
):
1870 # Always handled by an Armature modifier...
1872 for mod
in ob_obj
.bdata
.modifiers
:
1873 if mod
.type not in {'ARMATURE'} or not mod
.object:
1875 # We only support vertex groups binding method, not bone envelopes one!
1876 if mod
.object == arm_obj
.bdata
and mod
.use_vertex_groups
:
1883 # Now we have a mesh using this armature.
1884 # Note: bindpose have no relations at all (no connections), so no need for any preprocess for them.
1885 # Create skin & clusters relations (note skins are connected to geometry, *not* model!).
1886 _key
, me
, _free
= data_meshes
[ob_obj
]
1887 clusters
= {bo
: get_blender_bone_cluster_key(arm_obj
.bdata
, me
, bo
.bdata
) for bo
in bones
}
1888 data_deformers_skin
.setdefault(arm_obj
, {})[me
] = (get_blender_armature_skin_key(arm_obj
.bdata
, me
),
1891 # We don't want a regular parent relationship for those in FBX...
1892 arm_parents
.add((arm_obj
, ob_obj
))
1893 # Needed to handle matrices/spaces (since we do not parent them to 'armature' in FBX :/ ).
1894 ob_obj
.parented_to_armature
= True
1896 objects
.update(bones
)
1899 def fbx_generate_leaf_bones(settings
, data_bones
):
1900 # find which bons have no children
1901 child_count
= {bo
: 0 for bo
in data_bones
.keys()}
1902 for bo
in data_bones
.keys():
1903 if bo
.parent
and bo
.parent
.is_bone
:
1904 child_count
[bo
.parent
] += 1
1906 bone_radius_scale
= settings
.global_scale
* 33.0
1908 # generate bone data
1909 leaf_parents
= [bo
for bo
, count
in child_count
.items() if count
== 0]
1911 for parent
in leaf_parents
:
1912 node_name
= parent
.name
+ "_end"
1913 parent_uuid
= parent
.fbx_uuid
1914 parent_key
= parent
.key
1915 node_uuid
= get_fbx_uuid_from_key(parent_key
+ "_end_node")
1916 attr_uuid
= get_fbx_uuid_from_key(parent_key
+ "_end_nodeattr")
1919 size
= parent
.bdata
.head_radius
* bone_radius_scale
1920 bone_length
= (parent
.bdata
.tail_local
- parent
.bdata
.head_local
).length
1921 matrix
= Matrix
.Translation((0, bone_length
, 0))
1922 if settings
.bone_correction_matrix_inv
:
1923 matrix
= settings
.bone_correction_matrix_inv
@ matrix
1924 if settings
.bone_correction_matrix
:
1925 matrix
= matrix
@ settings
.bone_correction_matrix
1926 leaf_bones
.append((node_name
, parent_uuid
, node_uuid
, attr_uuid
, matrix
, hide
, size
))
1931 def fbx_animations_do(scene_data
, ref_id
, f_start
, f_end
, start_zero
, objects
=None, force_keep
=False):
1933 Generate animation data (a single AnimStack) from objects, for a given frame range.
1935 bake_step
= scene_data
.settings
.bake_anim_step
1936 simplify_fac
= scene_data
.settings
.bake_anim_simplify_factor
1937 scene
= scene_data
.scene
1938 depsgraph
= scene_data
.depsgraph
1939 force_keying
= scene_data
.settings
.bake_anim_use_all_bones
1940 force_sek
= scene_data
.settings
.bake_anim_force_startend_keying
1941 gscale
= scene_data
.settings
.global_scale
1943 if objects
is not None:
1944 # Add bones and duplis!
1945 for ob_obj
in tuple(objects
):
1946 if not ob_obj
.is_object
:
1948 if ob_obj
.type == 'ARMATURE':
1949 objects |
= {bo_obj
for bo_obj
in ob_obj
.bones
if bo_obj
in scene_data
.objects
}
1950 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
1951 if dp_obj
in scene_data
.objects
:
1954 objects
= scene_data
.objects
1956 back_currframe
= scene
.frame_current
1960 for ob_obj
in objects
:
1961 if ob_obj
.parented_to_armature
:
1963 ACNW
= AnimationCurveNodeWrapper
1964 loc
, rot
, scale
, _m
, _mr
= ob_obj
.fbx_object_tx(scene_data
)
1965 rot_deg
= tuple(convert_rad_to_deg_iter(rot
))
1966 force_key
= (simplify_fac
== 0.0) or (ob_obj
.is_bone
and force_keying
)
1967 animdata_ob
[ob_obj
] = (ACNW(ob_obj
.key
, 'LCL_TRANSLATION', force_key
, force_sek
, loc
),
1968 ACNW(ob_obj
.key
, 'LCL_ROTATION', force_key
, force_sek
, rot_deg
),
1969 ACNW(ob_obj
.key
, 'LCL_SCALING', force_key
, force_sek
, scale
))
1970 p_rots
[ob_obj
] = rot
1972 force_key
= (simplify_fac
== 0.0)
1973 animdata_shapes
= {}
1975 for me
, (me_key
, _shapes_key
, shapes
) in scene_data
.data_deformers_shape
.items():
1976 # Ignore absolute shape keys for now!
1977 if not me
.shape_keys
.use_relative
:
1979 for shape
, (channel_key
, geom_key
, _shape_verts_co
, _shape_verts_idx
) in shapes
.items():
1980 acnode
= AnimationCurveNodeWrapper(channel_key
, 'SHAPE_KEY', force_key
, force_sek
, (0.0,))
1981 # Sooooo happy to have to twist again like a mad snake... Yes, we need to write those curves twice. :/
1982 acnode
.add_group(me_key
, shape
.name
, shape
.name
, (shape
.name
,))
1983 animdata_shapes
[channel_key
] = (acnode
, me
, shape
)
1985 animdata_cameras
= {}
1986 for cam_obj
, cam_key
in scene_data
.data_cameras
.items():
1987 cam
= cam_obj
.bdata
.data
1988 acnode_lens
= AnimationCurveNodeWrapper(cam_key
, 'CAMERA_FOCAL', force_key
, force_sek
, (cam
.lens
,))
1989 acnode_focus_distance
= AnimationCurveNodeWrapper(cam_key
, 'CAMERA_FOCUS_DISTANCE', force_key
,
1990 force_sek
, (cam
.dof
.focus_distance
,))
1991 animdata_cameras
[cam_key
] = (acnode_lens
, acnode_focus_distance
, cam
)
1994 while currframe
<= f_end
:
1995 real_currframe
= currframe
- f_start
if start_zero
else currframe
1996 scene
.frame_set(int(currframe
), subframe
=currframe
- int(currframe
))
1998 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
1999 pass # Merely updating dupli matrix of ObjectWrapper...
2000 for ob_obj
, (anim_loc
, anim_rot
, anim_scale
) in animdata_ob
.items():
2001 # We compute baked loc/rot/scale for all objects (rot being euler-compat with previous value!).
2002 p_rot
= p_rots
.get(ob_obj
, None)
2003 loc
, rot
, scale
, _m
, _mr
= ob_obj
.fbx_object_tx(scene_data
, rot_euler_compat
=p_rot
)
2004 p_rots
[ob_obj
] = rot
2005 anim_loc
.add_keyframe(real_currframe
, loc
)
2006 anim_rot
.add_keyframe(real_currframe
, tuple(convert_rad_to_deg_iter(rot
)))
2007 anim_scale
.add_keyframe(real_currframe
, scale
)
2008 for anim_shape
, me
, shape
in animdata_shapes
.values():
2009 anim_shape
.add_keyframe(real_currframe
, (shape
.value
* 100.0,))
2010 for anim_camera_lens
, anim_camera_focus_distance
, camera
in animdata_cameras
.values():
2011 anim_camera_lens
.add_keyframe(real_currframe
, (camera
.lens
,))
2012 anim_camera_focus_distance
.add_keyframe(real_currframe
, (camera
.dof
.focus_distance
* 1000 * gscale
,))
2013 currframe
+= bake_step
2015 scene
.frame_set(back_currframe
, subframe
=0.0)
2019 # And now, produce final data (usable by FBX export code)
2020 # Objects-like loc/rot/scale...
2021 for ob_obj
, anims
in animdata_ob
.items():
2023 anim
.simplify(simplify_fac
, bake_step
, force_keep
)
2026 for obj_key
, group_key
, group
, fbx_group
, fbx_gname
in anim
.get_final_data(scene
, ref_id
, force_keep
):
2027 anim_data
= animations
.setdefault(obj_key
, ("dummy_unused_key", {}))
2028 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2030 # And meshes' shape keys.
2031 for channel_key
, (anim_shape
, me
, shape
) in animdata_shapes
.items():
2033 anim_shape
.simplify(simplify_fac
, bake_step
, force_keep
)
2036 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in anim_shape
.get_final_data(scene
, ref_id
, force_keep
):
2037 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2038 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2040 # And cameras' lens and focus distance keys.
2041 for cam_key
, (anim_camera_lens
, anim_camera_focus_distance
, camera
) in animdata_cameras
.items():
2043 anim_camera_lens
.simplify(simplify_fac
, bake_step
, force_keep
)
2044 anim_camera_focus_distance
.simplify(simplify_fac
, bake_step
, force_keep
)
2045 if anim_camera_lens
:
2046 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in \
2047 anim_camera_lens
.get_final_data(scene
, ref_id
, force_keep
):
2048 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2049 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2050 if anim_camera_focus_distance
:
2051 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in \
2052 anim_camera_focus_distance
.get_final_data(scene
, ref_id
, force_keep
):
2053 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2054 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2056 astack_key
= get_blender_anim_stack_key(scene
, ref_id
)
2057 alayer_key
= get_blender_anim_layer_key(scene
, ref_id
)
2058 name
= (get_blenderID_name(ref_id
) if ref_id
else scene
.name
).encode()
2064 return (astack_key
, animations
, alayer_key
, name
, f_start
, f_end
) if animations
else None
2067 def fbx_animations(scene_data
):
2069 Generate global animation data from objects.
2071 scene
= scene_data
.scene
2077 def add_anim(animations
, animated
, anim
):
2078 nonlocal frame_start
, frame_end
2079 if anim
is not None:
2080 animations
.append(anim
)
2081 f_start
, f_end
= anim
[4:6]
2082 if f_start
< frame_start
:
2083 frame_start
= f_start
2084 if f_end
> frame_end
:
2087 _astack_key
, astack
, _alayer_key
, _name
, _fstart
, _fend
= anim
2088 for elem_key
, (alayer_key
, acurvenodes
) in astack
.items():
2089 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
2090 animated
.add((elem_key
, fbx_prop
))
2092 # Per-NLA strip animstacks.
2093 if scene_data
.settings
.bake_anim_use_nla_strips
:
2096 for ob_obj
in scene_data
.objects
:
2097 # NLA tracks only for objects, not bones!
2098 if not ob_obj
.is_object
:
2100 ob
= ob_obj
.bdata
# Back to real Blender Object.
2101 if not ob
.animation_data
:
2104 # Some actions are read-only, one cause is being in NLA tweakmode
2105 restore_use_tweak_mode
= ob
.animation_data
.use_tweak_mode
2106 if ob
.animation_data
.is_property_readonly('action'):
2107 ob
.animation_data
.use_tweak_mode
= False
2109 # We have to remove active action from objects, it overwrites strips actions otherwise...
2110 ob_actions
.append((ob
, ob
.animation_data
.action
, restore_use_tweak_mode
))
2111 ob
.animation_data
.action
= None
2112 for track
in ob
.animation_data
.nla_tracks
:
2115 for strip
in track
.strips
:
2118 strips
.append(strip
)
2121 for strip
in strips
:
2123 add_anim(animations
, animated
,
2124 fbx_animations_do(scene_data
, strip
, strip
.frame_start
, strip
.frame_end
, True, force_keep
=True))
2126 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2128 for strip
in strips
:
2131 for ob
, ob_act
, restore_use_tweak_mode
in ob_actions
:
2132 ob
.animation_data
.action
= ob_act
2133 ob
.animation_data
.use_tweak_mode
= restore_use_tweak_mode
2136 if scene_data
.settings
.bake_anim_use_all_actions
:
2137 def validate_actions(act
, path_resolve
):
2138 for fc
in act
.fcurves
:
2139 data_path
= fc
.data_path
2141 data_path
= data_path
+ "[%d]" % fc
.array_index
2143 path_resolve(data_path
)
2145 return False # Invalid.
2146 return True # Valid.
2148 def restore_object(ob_to
, ob_from
):
2149 # Restore org state of object (ugh :/ ).
2151 'location', 'rotation_quaternion', 'rotation_axis_angle', 'rotation_euler', 'rotation_mode', 'scale',
2152 'delta_location', 'delta_rotation_euler', 'delta_rotation_quaternion', 'delta_scale',
2153 'lock_location', 'lock_rotation', 'lock_rotation_w', 'lock_rotations_4d', 'lock_scale',
2154 'tag', 'track_axis', 'up_axis', 'active_material', 'active_material_index',
2155 'matrix_parent_inverse', 'empty_display_type', 'empty_display_size', 'empty_image_offset', 'pass_index',
2156 'color', 'hide_viewport', 'hide_select', 'hide_render', 'instance_type',
2157 'use_instance_vertices_rotation', 'use_instance_faces_scale', 'instance_faces_scale',
2158 'display_type', 'show_bounds', 'display_bounds_type', 'show_name', 'show_axis', 'show_texture_space',
2159 'show_wire', 'show_all_edges', 'show_transparent', 'show_in_front',
2160 'show_only_shape_key', 'use_shape_key_edit_mode', 'active_shape_key_index',
2163 if not ob_to
.is_property_readonly(p
):
2164 setattr(ob_to
, p
, getattr(ob_from
, p
))
2166 for ob_obj
in scene_data
.objects
:
2167 # Actions only for objects, not bones!
2168 if not ob_obj
.is_object
:
2171 ob
= ob_obj
.bdata
# Back to real Blender Object.
2173 if not ob
.animation_data
:
2174 continue # Do not export animations for objects that are absolutely not animated, see T44386.
2176 if ob
.animation_data
.is_property_readonly('action'):
2177 continue # Cannot re-assign 'active action' to this object (usually related to NLA usage, see T48089).
2179 # We can't play with animdata and actions and get back to org state easily.
2180 # So we have to add a temp copy of the object to the scene, animate it, and remove it... :/
2182 # Great, have to handle bones as well if needed...
2183 pbones_matrices
= [pbo
.matrix_basis
.copy() for pbo
in ob
.pose
.bones
] if ob
.type == 'ARMATURE' else ...
2185 org_act
= ob
.animation_data
.action
2186 path_resolve
= ob
.path_resolve
2188 for act
in bpy
.data
.actions
:
2189 # For now, *all* paths in the action must be valid for the object, to validate the action.
2190 # Unless that action was already assigned to the object!
2191 if act
!= org_act
and not validate_actions(act
, path_resolve
):
2193 ob
.animation_data
.action
= act
2194 frame_start
, frame_end
= act
.frame_range
# sic!
2195 add_anim(animations
, animated
,
2196 fbx_animations_do(scene_data
, (ob
, act
), frame_start
, frame_end
, True,
2197 objects
={ob_obj}
, force_keep
=True))
2199 if pbones_matrices
is not ...:
2200 for pbo
, mat
in zip(ob
.pose
.bones
, pbones_matrices
):
2201 pbo
.matrix_basis
= mat
.copy()
2202 ob
.animation_data
.action
= org_act
2203 restore_object(ob
, ob_copy
)
2204 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2206 if pbones_matrices
is not ...:
2207 for pbo
, mat
in zip(ob
.pose
.bones
, pbones_matrices
):
2208 pbo
.matrix_basis
= mat
.copy()
2209 ob
.animation_data
.action
= org_act
2211 bpy
.data
.objects
.remove(ob_copy
)
2212 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2214 # Global (containing everything) animstack, only if not exporting NLA strips and/or all actions.
2215 if not scene_data
.settings
.bake_anim_use_nla_strips
and not scene_data
.settings
.bake_anim_use_all_actions
:
2216 add_anim(animations
, animated
, fbx_animations_do(scene_data
, None, scene
.frame_start
, scene
.frame_end
, False))
2218 # Be sure to update all matrices back to org state!
2219 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2221 return animations
, animated
, frame_start
, frame_end
2224 def fbx_data_from_scene(scene
, depsgraph
, settings
):
2226 Do some pre-processing over scene's data...
2228 objtypes
= settings
.object_types
2229 dp_objtypes
= objtypes
- {'ARMATURE'} # Armatures are not supported as dupli instances currently...
2233 # ##### Gathering data...
2235 perfmon
.step("FBX export prepare: Wrapping Objects...")
2237 # This is rather simple for now, maybe we could end generating templates with most-used values
2238 # instead of default ones?
2239 objects
= {} # Because we do not have any ordered set...
2240 for ob
in settings
.context_objects
:
2241 if ob
.type not in objtypes
:
2243 ob_obj
= ObjectWrapper(ob
)
2244 objects
[ob_obj
] = None
2246 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
2247 if dp_obj
.type not in dp_objtypes
:
2249 objects
[dp_obj
] = None
2251 perfmon
.step("FBX export prepare: Wrapping Data (lamps, cameras, empties)...")
2253 data_lights
= {ob_obj
.bdata
.data
: get_blenderID_key(ob_obj
.bdata
.data
)
2254 for ob_obj
in objects
if ob_obj
.type == 'LIGHT'}
2255 # Unfortunately, FBX camera data contains object-level data (like position, orientation, etc.)...
2256 data_cameras
= {ob_obj
: get_blenderID_key(ob_obj
.bdata
.data
)
2257 for ob_obj
in objects
if ob_obj
.type == 'CAMERA'}
2258 # Yep! Contains nothing, but needed!
2259 data_empties
= {ob_obj
: get_blender_empty_key(ob_obj
.bdata
)
2260 for ob_obj
in objects
if ob_obj
.type == 'EMPTY'}
2262 perfmon
.step("FBX export prepare: Wrapping Meshes...")
2265 for ob_obj
in objects
:
2266 if ob_obj
.type not in BLENDER_OBJECT_TYPES_MESHLIKE
:
2272 # Do not want to systematically recreate a new mesh for dupliobject instances, kind of break purpose of those.
2274 org_ob_obj
= ObjectWrapper(ob
) # We get the "real" object wrapper from that dupli instance.
2275 if org_ob_obj
in data_meshes
:
2276 data_meshes
[ob_obj
] = data_meshes
[org_ob_obj
]
2279 is_ob_material
= any(ms
.link
== 'OBJECT' for ms
in ob
.material_slots
)
2281 if settings
.use_mesh_modifiers
or settings
.use_triangles
or ob
.type in BLENDER_OTHER_OBJECT_TYPES
or is_ob_material
:
2282 # We cannot use default mesh in that case, or material would not be the right ones...
2283 use_org_data
= not (is_ob_material
or ob
.type in BLENDER_OTHER_OBJECT_TYPES
)
2284 backup_pose_positions
= []
2286 if use_org_data
and ob
.type == 'MESH':
2287 if settings
.use_triangles
:
2288 use_org_data
= False
2289 # No need to create a new mesh in this case, if no modifier is active!
2291 for mod
in ob
.modifiers
:
2292 # For meshes, when armature export is enabled, disable Armature modifiers here!
2293 # XXX Temp hacks here since currently we only have access to a viewport depsgraph...
2295 # NOTE: We put armature to the rest pose instead of disabling it so we still
2296 # have vertex groups in the evaluated mesh.
2297 if mod
.type == 'ARMATURE' and 'ARMATURE' in settings
.object_types
:
2299 if object and object.type == 'ARMATURE':
2300 armature
= object.data
2301 # If armature is already in REST position, there's nothing to back-up
2302 # This cuts down on export time dramatically, if all armatures are already in REST position
2303 # by not triggering dependency graph update
2304 if armature
.pose_position
!= 'REST':
2305 backup_pose_positions
.append((armature
, armature
.pose_position
))
2306 armature
.pose_position
= 'REST'
2307 elif mod
.show_render
or mod
.show_viewport
:
2308 # If exporting with subsurf collect the last Catmull-Clark subsurf modifier
2309 # and disable it. We can use the original data as long as this is the first
2310 # found applicable subsurf modifier.
2311 if settings
.use_subsurf
and mod
.type == 'SUBSURF' and mod
.subdivision_type
== 'CATMULL_CLARK':
2313 use_org_data
= False
2316 use_org_data
= False
2317 if settings
.use_subsurf
and last_subsurf
:
2318 # XXX: When exporting with subsurf information temporarily disable
2319 # the last subsurf modifier.
2320 tmp_mods
.append((last_subsurf
, last_subsurf
.show_render
, last_subsurf
.show_viewport
))
2321 last_subsurf
.show_render
= False
2322 last_subsurf
.show_viewport
= False
2323 if not use_org_data
:
2324 # If modifiers has been altered need to update dependency graph.
2325 if backup_pose_positions
or tmp_mods
:
2327 ob_to_convert
= ob
.evaluated_get(depsgraph
) if settings
.use_mesh_modifiers
else ob
2328 # NOTE: The dependency graph might be re-evaluating multiple times, which could
2329 # potentially free the mesh created early on. So we put those meshes to bmain and
2330 # free them afterwards. Not ideal but ensures correct ownerwhip.
2331 tmp_me
= bpy
.data
.meshes
.new_from_object(
2332 ob_to_convert
, preserve_all_data_layers
=True, depsgraph
=depsgraph
)
2333 # Triangulate the mesh if requested
2334 if settings
.use_triangles
:
2337 bm
.from_mesh(tmp_me
)
2338 bmesh
.ops
.triangulate(bm
, faces
=bm
.faces
)
2341 data_meshes
[ob_obj
] = (get_blenderID_key(tmp_me
), tmp_me
, True)
2342 # Change armatures back.
2343 for armature
, pose_position
in backup_pose_positions
:
2344 print((armature
, pose_position
))
2345 armature
.pose_position
= pose_position
2346 # Update now, so we don't leave modified state after last object was exported.
2347 # Re-enable temporary disabled modifiers.
2348 for mod
, show_render
, show_viewport
in tmp_mods
:
2349 mod
.show_render
= show_render
2350 mod
.show_viewport
= show_viewport
2351 if backup_pose_positions
or tmp_mods
:
2354 data_meshes
[ob_obj
] = (get_blenderID_key(ob
.data
), ob
.data
, False)
2356 # In case "real" source object of that dupli did not yet still existed in data_meshes, create it now!
2357 if org_ob_obj
is not None:
2358 data_meshes
[org_ob_obj
] = data_meshes
[ob_obj
]
2360 perfmon
.step("FBX export prepare: Wrapping ShapeKeys...")
2363 data_deformers_shape
= {}
2364 geom_mat_co
= settings
.global_matrix
if settings
.bake_space_transform
else None
2365 for me_key
, me
, _free
in data_meshes
.values():
2366 if not (me
.shape_keys
and len(me
.shape_keys
.key_blocks
) > 1): # We do not want basis-only relative skeys...
2368 if me
in data_deformers_shape
:
2371 shapes_key
= get_blender_mesh_shape_key(me
)
2372 # We gather all vcos first, since some skeys may be based on others...
2373 _cos
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.vertices
) * 3
2374 me
.vertices
.foreach_get("co", _cos
)
2375 v_cos
= tuple(vcos_transformed_gen(_cos
, geom_mat_co
))
2377 for shape
in me
.shape_keys
.key_blocks
[1:]:
2378 shape
.data
.foreach_get("co", _cos
)
2379 sk_cos
[shape
] = tuple(vcos_transformed_gen(_cos
, geom_mat_co
))
2380 sk_base
= me
.shape_keys
.key_blocks
[0]
2382 for shape
in me
.shape_keys
.key_blocks
[1:]:
2383 # Only write vertices really different from org coordinates!
2385 shape_verts_idx
= []
2387 sv_cos
= sk_cos
[shape
]
2388 ref_cos
= v_cos
if shape
.relative_key
== sk_base
else sk_cos
[shape
.relative_key
]
2389 for idx
, (sv_co
, ref_co
) in enumerate(zip(sv_cos
, ref_cos
)):
2390 if similar_values_iter(sv_co
, ref_co
):
2391 # Note: Maybe this is a bit too simplistic, should we use real shape base here? Though FBX does not
2392 # have this at all... Anyway, this should cover most common cases imho.
2394 shape_verts_co
.extend(Vector(sv_co
) - Vector(ref_co
))
2395 shape_verts_idx
.append(idx
)
2397 # FBX does not like empty shapes (makes Unity crash e.g.).
2398 # To prevent this, we add a vertex that does nothing, but it keeps the shape key intact
2399 if not shape_verts_co
:
2400 shape_verts_co
.extend((0, 0, 0))
2401 shape_verts_idx
.append(0)
2403 channel_key
, geom_key
= get_blender_mesh_shape_channel_key(me
, shape
)
2404 data
= (channel_key
, geom_key
, shape_verts_co
, shape_verts_idx
)
2405 data_deformers_shape
.setdefault(me
, (me_key
, shapes_key
, {}))[2][shape
] = data
2407 perfmon
.step("FBX export prepare: Wrapping Armatures...")
2410 data_deformers_skin
= {}
2413 for ob_obj
in tuple(objects
):
2414 if not (ob_obj
.is_object
and ob_obj
.type in {'ARMATURE'}):
2416 fbx_skeleton_from_armature(scene
, settings
, ob_obj
, objects
, data_meshes
,
2417 data_bones
, data_deformers_skin
, data_empties
, arm_parents
)
2419 # Generate leaf bones
2420 data_leaf_bones
= []
2421 if settings
.add_leaf_bones
:
2422 data_leaf_bones
= fbx_generate_leaf_bones(settings
, data_bones
)
2424 perfmon
.step("FBX export prepare: Wrapping World...")
2426 # Some world settings are embedded in FBX materials...
2428 data_world
= {scene
.world
: get_blenderID_key(scene
.world
)}
2432 perfmon
.step("FBX export prepare: Wrapping Materials...")
2434 # TODO: Check all the material stuff works even when they are linked to Objects
2435 # (we can then have the same mesh used with different materials...).
2436 # *Should* work, as FBX always links its materials to Models (i.e. objects).
2437 # XXX However, material indices would probably break...
2439 for ob_obj
in objects
:
2440 # If obj is not a valid object for materials, wrapper will just return an empty tuple...
2441 for ma_s
in ob_obj
.material_slots
:
2444 continue # Empty slots!
2445 # Note theoretically, FBX supports any kind of materials, even GLSL shaders etc.
2446 # However, I doubt anything else than Lambert/Phong is really portable!
2447 # Note we want to keep a 'dummy' empty material even when we can't really support it, see T41396.
2448 ma_data
= data_materials
.setdefault(ma
, (get_blenderID_key(ma
), []))
2449 ma_data
[1].append(ob_obj
)
2451 perfmon
.step("FBX export prepare: Wrapping Textures...")
2453 # Note FBX textures also hold their mapping info.
2454 # TODO: Support layers?
2456 # FbxVideo also used to store static images...
2458 # For now, do not use world textures, don't think they can be linked to anything FBX wise...
2459 for ma
in data_materials
.keys():
2460 # Note: with nodal shaders, we'll could be generating much more textures, but that's kind of unavoidable,
2461 # given that textures actually do not exist anymore in material context in Blender...
2462 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
2463 for sock_name
, fbx_name
in PRINCIPLED_TEXTURE_SOCKETS_TO_FBX
:
2464 tex
= getattr(ma_wrap
, sock_name
)
2465 if tex
is None or tex
.image
is None:
2467 blender_tex_key
= (ma
, sock_name
)
2468 data_textures
[blender_tex_key
] = (get_blender_nodetexture_key(*blender_tex_key
), fbx_name
)
2471 vid_data
= data_videos
.setdefault(img
, (get_blenderID_key(img
), []))
2472 vid_data
[1].append(blender_tex_key
)
2474 perfmon
.step("FBX export prepare: Wrapping Animations...")
2479 frame_start
= scene
.frame_start
2480 frame_end
= scene
.frame_end
2481 if settings
.bake_anim
:
2482 # From objects & bones only for a start.
2483 # Kind of hack, we need a temp scene_data for object's space handling to bake animations...
2484 tmp_scdata
= FBXExportData(
2486 settings
, scene
, depsgraph
, objects
, None, None, 0.0, 0.0,
2487 data_empties
, data_lights
, data_cameras
, data_meshes
, None,
2488 data_bones
, data_leaf_bones
, data_deformers_skin
, data_deformers_shape
,
2489 data_world
, data_materials
, data_textures
, data_videos
,
2491 animations
, animated
, frame_start
, frame_end
= fbx_animations(tmp_scdata
)
2493 # ##### Creation of templates...
2495 perfmon
.step("FBX export prepare: Generating templates...")
2498 templates
[b
"GlobalSettings"] = fbx_template_def_globalsettings(scene
, settings
, nbr_users
=1)
2501 templates
[b
"Null"] = fbx_template_def_null(scene
, settings
, nbr_users
=len(data_empties
))
2504 templates
[b
"Light"] = fbx_template_def_light(scene
, settings
, nbr_users
=len(data_lights
))
2507 templates
[b
"Camera"] = fbx_template_def_camera(scene
, settings
, nbr_users
=len(data_cameras
))
2510 templates
[b
"Bone"] = fbx_template_def_bone(scene
, settings
, nbr_users
=len(data_bones
))
2513 nbr
= len({me_key
for me_key
, _me
, _free
in data_meshes
.values()})
2514 if data_deformers_shape
:
2515 nbr
+= sum(len(shapes
[2]) for shapes
in data_deformers_shape
.values())
2516 templates
[b
"Geometry"] = fbx_template_def_geometry(scene
, settings
, nbr_users
=nbr
)
2519 templates
[b
"Model"] = fbx_template_def_model(scene
, settings
, nbr_users
=len(objects
))
2522 # Number of Pose|BindPose elements should be the same as number of meshes-parented-to-armatures
2523 templates
[b
"BindPose"] = fbx_template_def_pose(scene
, settings
, nbr_users
=len(arm_parents
))
2525 if data_deformers_skin
or data_deformers_shape
:
2527 if data_deformers_skin
:
2528 nbr
+= len(data_deformers_skin
)
2529 nbr
+= sum(len(clusters
) for def_me
in data_deformers_skin
.values() for a
, b
, clusters
in def_me
.values())
2530 if data_deformers_shape
:
2531 nbr
+= len(data_deformers_shape
)
2532 nbr
+= sum(len(shapes
[2]) for shapes
in data_deformers_shape
.values())
2534 templates
[b
"Deformers"] = fbx_template_def_deformer(scene
, settings
, nbr_users
=nbr
)
2536 # No world support in FBX...
2539 templates[b"World"] = fbx_template_def_world(scene, settings, nbr_users=len(data_world))
2543 templates
[b
"Material"] = fbx_template_def_material(scene
, settings
, nbr_users
=len(data_materials
))
2546 templates
[b
"TextureFile"] = fbx_template_def_texture_file(scene
, settings
, nbr_users
=len(data_textures
))
2549 templates
[b
"Video"] = fbx_template_def_video(scene
, settings
, nbr_users
=len(data_videos
))
2552 nbr_astacks
= len(animations
)
2555 for _astack_key
, astack
, _al
, _n
, _fs
, _fe
in animations
:
2556 for _alayer_key
, alayer
in astack
.values():
2557 for _acnode_key
, acnode
, _acnode_name
in alayer
.values():
2559 for _acurve_key
, _dval
, acurve
, acurve_valid
in acnode
.values():
2563 templates
[b
"AnimationStack"] = fbx_template_def_animstack(scene
, settings
, nbr_users
=nbr_astacks
)
2564 # Would be nice to have one layer per animated object, but this seems tricky and not that well supported.
2565 # So for now, only one layer per anim stack.
2566 templates
[b
"AnimationLayer"] = fbx_template_def_animlayer(scene
, settings
, nbr_users
=nbr_astacks
)
2567 templates
[b
"AnimationCurveNode"] = fbx_template_def_animcurvenode(scene
, settings
, nbr_users
=nbr_acnodes
)
2568 templates
[b
"AnimationCurve"] = fbx_template_def_animcurve(scene
, settings
, nbr_users
=nbr_acurves
)
2570 templates_users
= sum(tmpl
.nbr_users
for tmpl
in templates
.values())
2572 # ##### Creation of connections...
2574 perfmon
.step("FBX export prepare: Generating Connections...")
2578 # Objects (with classical parenting).
2579 for ob_obj
in objects
:
2580 # Bones are handled later.
2581 if not ob_obj
.is_bone
:
2582 par_obj
= ob_obj
.parent
2583 # Meshes parented to armature are handled separately, yet we want the 'no parent' connection (0).
2584 if par_obj
and ob_obj
.has_valid_parent(objects
) and (par_obj
, ob_obj
) not in arm_parents
:
2585 connections
.append((b
"OO", ob_obj
.fbx_uuid
, par_obj
.fbx_uuid
, None))
2587 connections
.append((b
"OO", ob_obj
.fbx_uuid
, 0, None))
2589 # Armature & Bone chains.
2590 for bo_obj
in data_bones
.keys():
2591 par_obj
= bo_obj
.parent
2592 if par_obj
not in objects
:
2594 connections
.append((b
"OO", bo_obj
.fbx_uuid
, par_obj
.fbx_uuid
, None))
2597 for ob_obj
in objects
:
2599 bo_data_key
= data_bones
[ob_obj
]
2600 connections
.append((b
"OO", get_fbx_uuid_from_key(bo_data_key
), ob_obj
.fbx_uuid
, None))
2602 if ob_obj
.type == 'LIGHT':
2603 light_key
= data_lights
[ob_obj
.bdata
.data
]
2604 connections
.append((b
"OO", get_fbx_uuid_from_key(light_key
), ob_obj
.fbx_uuid
, None))
2605 elif ob_obj
.type == 'CAMERA':
2606 cam_key
= data_cameras
[ob_obj
]
2607 connections
.append((b
"OO", get_fbx_uuid_from_key(cam_key
), ob_obj
.fbx_uuid
, None))
2608 elif ob_obj
.type == 'EMPTY' or ob_obj
.type == 'ARMATURE':
2609 empty_key
= data_empties
[ob_obj
]
2610 connections
.append((b
"OO", get_fbx_uuid_from_key(empty_key
), ob_obj
.fbx_uuid
, None))
2611 elif ob_obj
.type in BLENDER_OBJECT_TYPES_MESHLIKE
:
2612 mesh_key
, _me
, _free
= data_meshes
[ob_obj
]
2613 connections
.append((b
"OO", get_fbx_uuid_from_key(mesh_key
), ob_obj
.fbx_uuid
, None))
2616 for (_node_name
, par_uuid
, node_uuid
, attr_uuid
, _matrix
, _hide
, _size
) in data_leaf_bones
:
2617 connections
.append((b
"OO", node_uuid
, par_uuid
, None))
2618 connections
.append((b
"OO", attr_uuid
, node_uuid
, None))
2620 # 'Shape' deformers (shape keys, only for meshes currently)...
2621 for me_key
, shapes_key
, shapes
in data_deformers_shape
.values():
2623 connections
.append((b
"OO", get_fbx_uuid_from_key(shapes_key
), get_fbx_uuid_from_key(me_key
), None))
2624 for channel_key
, geom_key
, _shape_verts_co
, _shape_verts_idx
in shapes
.values():
2625 # shape channel -> shape
2626 connections
.append((b
"OO", get_fbx_uuid_from_key(channel_key
), get_fbx_uuid_from_key(shapes_key
), None))
2627 # geometry (keys) -> shape channel
2628 connections
.append((b
"OO", get_fbx_uuid_from_key(geom_key
), get_fbx_uuid_from_key(channel_key
), None))
2630 # 'Skin' deformers (armature-to-geometry, only for meshes currently)...
2631 for arm
, deformed_meshes
in data_deformers_skin
.items():
2632 for me
, (skin_key
, ob_obj
, clusters
) in deformed_meshes
.items():
2634 mesh_key
, _me
, _free
= data_meshes
[ob_obj
]
2636 connections
.append((b
"OO", get_fbx_uuid_from_key(skin_key
), get_fbx_uuid_from_key(mesh_key
), None))
2637 for bo_obj
, clstr_key
in clusters
.items():
2639 connections
.append((b
"OO", get_fbx_uuid_from_key(clstr_key
), get_fbx_uuid_from_key(skin_key
), None))
2641 connections
.append((b
"OO", bo_obj
.fbx_uuid
, get_fbx_uuid_from_key(clstr_key
), None))
2644 mesh_material_indices
= {}
2646 for ma
, (ma_key
, ob_objs
) in data_materials
.items():
2647 for ob_obj
in ob_objs
:
2648 connections
.append((b
"OO", get_fbx_uuid_from_key(ma_key
), ob_obj
.fbx_uuid
, None))
2649 # Get index of this material for this object (or dupliobject).
2650 # Material indices for mesh faces are determined by their order in 'ma to ob' connections.
2651 # Only materials for meshes currently...
2652 # Note in case of dupliobjects a same me/ma idx will be generated several times...
2653 # Should not be an issue in practice, and it's needed in case we export duplis but not the original!
2654 if ob_obj
.type not in BLENDER_OBJECT_TYPES_MESHLIKE
:
2656 _mesh_key
, me
, _free
= data_meshes
[ob_obj
]
2657 idx
= _objs_indices
[ob_obj
] = _objs_indices
.get(ob_obj
, -1) + 1
2658 mesh_material_indices
.setdefault(me
, {})[ma
] = idx
2662 for (ma
, sock_name
), (tex_key
, fbx_prop
) in data_textures
.items():
2663 ma_key
, _ob_objs
= data_materials
[ma
]
2664 # texture -> material properties
2665 connections
.append((b
"OP", get_fbx_uuid_from_key(tex_key
), get_fbx_uuid_from_key(ma_key
), fbx_prop
))
2668 for vid
, (vid_key
, blender_tex_keys
) in data_videos
.items():
2669 for blender_tex_key
in blender_tex_keys
:
2670 tex_key
, _fbx_prop
= data_textures
[blender_tex_key
]
2671 connections
.append((b
"OO", get_fbx_uuid_from_key(vid_key
), get_fbx_uuid_from_key(tex_key
), None))
2674 for astack_key
, astack
, alayer_key
, _name
, _fstart
, _fend
in animations
:
2675 # Animstack itself is linked nowhere!
2676 astack_id
= get_fbx_uuid_from_key(astack_key
)
2677 # For now, only one layer!
2678 alayer_id
= get_fbx_uuid_from_key(alayer_key
)
2679 connections
.append((b
"OO", alayer_id
, astack_id
, None))
2680 for elem_key
, (alayer_key
, acurvenodes
) in astack
.items():
2681 elem_id
= get_fbx_uuid_from_key(elem_key
)
2682 # Animlayer -> animstack.
2683 # alayer_id = get_fbx_uuid_from_key(alayer_key)
2684 # connections.append((b"OO", alayer_id, astack_id, None))
2685 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
2686 # Animcurvenode -> animalayer.
2687 acurvenode_id
= get_fbx_uuid_from_key(acurvenode_key
)
2688 connections
.append((b
"OO", acurvenode_id
, alayer_id
, None))
2689 # Animcurvenode -> object property.
2690 connections
.append((b
"OP", acurvenode_id
, elem_id
, fbx_prop
.encode()))
2691 for fbx_item
, (acurve_key
, default_value
, acurve
, acurve_valid
) in acurves
.items():
2693 # Animcurve -> Animcurvenode.
2694 connections
.append((b
"OP", get_fbx_uuid_from_key(acurve_key
), acurvenode_id
, fbx_item
.encode()))
2696 perfmon
.level_down()
2698 # ##### And pack all this!
2700 return FBXExportData(
2701 templates
, templates_users
, connections
,
2702 settings
, scene
, depsgraph
, objects
, animations
, animated
, frame_start
, frame_end
,
2703 data_empties
, data_lights
, data_cameras
, data_meshes
, mesh_material_indices
,
2704 data_bones
, data_leaf_bones
, data_deformers_skin
, data_deformers_shape
,
2705 data_world
, data_materials
, data_textures
, data_videos
,
2709 def fbx_scene_data_cleanup(scene_data
):
2711 Some final cleanup...
2713 # Delete temp meshes.
2715 for me_key
, me
, free
in scene_data
.data_meshes
.values():
2716 if free
and me_key
not in done_meshes
:
2717 bpy
.data
.meshes
.remove(me
)
2718 done_meshes
.add(me_key
)
2721 # ##### Top-level FBX elements generators. #####
2723 def fbx_header_elements(root
, scene_data
, time
=None):
2725 Write boiling code of FBX root.
2726 time is expected to be a datetime.datetime object, or None (using now() in this case).
2728 app_vendor
= "Blender Foundation"
2729 app_name
= "Blender (stable FBX IO)"
2730 app_ver
= bpy
.app
.version_string
2734 addon_ver
= addon_utils
.module_bl_info(sys
.modules
[__package__
])['version']
2736 # ##### Start of FBXHeaderExtension element.
2737 header_ext
= elem_empty(root
, b
"FBXHeaderExtension")
2739 elem_data_single_int32(header_ext
, b
"FBXHeaderVersion", FBX_HEADER_VERSION
)
2741 elem_data_single_int32(header_ext
, b
"FBXVersion", FBX_VERSION
)
2744 elem_data_single_int32(header_ext
, b
"EncryptionType", 0)
2747 time
= datetime
.datetime
.now()
2748 elem
= elem_empty(header_ext
, b
"CreationTimeStamp")
2749 elem_data_single_int32(elem
, b
"Version", 1000)
2750 elem_data_single_int32(elem
, b
"Year", time
.year
)
2751 elem_data_single_int32(elem
, b
"Month", time
.month
)
2752 elem_data_single_int32(elem
, b
"Day", time
.day
)
2753 elem_data_single_int32(elem
, b
"Hour", time
.hour
)
2754 elem_data_single_int32(elem
, b
"Minute", time
.minute
)
2755 elem_data_single_int32(elem
, b
"Second", time
.second
)
2756 elem_data_single_int32(elem
, b
"Millisecond", time
.microsecond
// 1000)
2758 elem_data_single_string_unicode(header_ext
, b
"Creator", "%s - %s - %d.%d.%d"
2759 % (app_name
, app_ver
, addon_ver
[0], addon_ver
[1], addon_ver
[2]))
2761 # 'SceneInfo' seems mandatory to get a valid FBX file...
2762 # TODO use real values!
2763 # XXX Should we use scene.name.encode() here?
2764 scene_info
= elem_data_single_string(header_ext
, b
"SceneInfo", fbx_name_class(b
"GlobalInfo", b
"SceneInfo"))
2765 scene_info
.add_string(b
"UserData")
2766 elem_data_single_string(scene_info
, b
"Type", b
"UserData")
2767 elem_data_single_int32(scene_info
, b
"Version", FBX_SCENEINFO_VERSION
)
2768 meta_data
= elem_empty(scene_info
, b
"MetaData")
2769 elem_data_single_int32(meta_data
, b
"Version", FBX_SCENEINFO_VERSION
)
2770 elem_data_single_string(meta_data
, b
"Title", b
"")
2771 elem_data_single_string(meta_data
, b
"Subject", b
"")
2772 elem_data_single_string(meta_data
, b
"Author", b
"")
2773 elem_data_single_string(meta_data
, b
"Keywords", b
"")
2774 elem_data_single_string(meta_data
, b
"Revision", b
"")
2775 elem_data_single_string(meta_data
, b
"Comment", b
"")
2777 props
= elem_properties(scene_info
)
2778 elem_props_set(props
, "p_string_url", b
"DocumentUrl", "/foobar.fbx")
2779 elem_props_set(props
, "p_string_url", b
"SrcDocumentUrl", "/foobar.fbx")
2780 original
= elem_props_compound(props
, b
"Original")
2781 original("p_string", b
"ApplicationVendor", app_vendor
)
2782 original("p_string", b
"ApplicationName", app_name
)
2783 original("p_string", b
"ApplicationVersion", app_ver
)
2784 original("p_datetime", b
"DateTime_GMT", "01/01/1970 00:00:00.000")
2785 original("p_string", b
"FileName", "/foobar.fbx")
2786 lastsaved
= elem_props_compound(props
, b
"LastSaved")
2787 lastsaved("p_string", b
"ApplicationVendor", app_vendor
)
2788 lastsaved("p_string", b
"ApplicationName", app_name
)
2789 lastsaved("p_string", b
"ApplicationVersion", app_ver
)
2790 lastsaved("p_datetime", b
"DateTime_GMT", "01/01/1970 00:00:00.000")
2791 original("p_string", b
"ApplicationNativeFile", bpy
.data
.filepath
)
2793 # ##### End of FBXHeaderExtension element.
2795 # FileID is replaced by dummy value currently...
2796 elem_data_single_bytes(root
, b
"FileId", b
"FooBar")
2798 # CreationTime is replaced by dummy value currently, but anyway...
2799 elem_data_single_string_unicode(root
, b
"CreationTime",
2800 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}:{:03}"
2801 "".format(time
.year
, time
.month
, time
.day
, time
.hour
, time
.minute
, time
.second
,
2802 time
.microsecond
* 1000))
2804 elem_data_single_string_unicode(root
, b
"Creator", "%s - %s - %d.%d.%d"
2805 % (app_name
, app_ver
, addon_ver
[0], addon_ver
[1], addon_ver
[2]))
2807 # ##### Start of GlobalSettings element.
2808 global_settings
= elem_empty(root
, b
"GlobalSettings")
2809 scene
= scene_data
.scene
2811 elem_data_single_int32(global_settings
, b
"Version", 1000)
2813 props
= elem_properties(global_settings
)
2814 up_axis
, front_axis
, coord_axis
= RIGHT_HAND_AXES
[scene_data
.settings
.to_axes
]
2815 #~ # DO NOT take into account global scale here! That setting is applied to object transformations during export
2816 #~ # (in other words, this is pure blender-exporter feature, and has nothing to do with FBX data).
2817 #~ if scene_data.settings.apply_unit_scale:
2818 #~ # Unit scaling is applied to objects' scale, so our unit is effectively FBX one (centimeter).
2819 #~ scale_factor_org = 1.0
2820 #~ scale_factor = 1.0 / units_blender_to_fbx_factor(scene)
2822 #~ scale_factor_org = units_blender_to_fbx_factor(scene)
2823 #~ scale_factor = scale_factor_org
2824 scale_factor
= scale_factor_org
= scene_data
.settings
.unit_scale
2825 elem_props_set(props
, "p_integer", b
"UpAxis", up_axis
[0])
2826 elem_props_set(props
, "p_integer", b
"UpAxisSign", up_axis
[1])
2827 elem_props_set(props
, "p_integer", b
"FrontAxis", front_axis
[0])
2828 elem_props_set(props
, "p_integer", b
"FrontAxisSign", front_axis
[1])
2829 elem_props_set(props
, "p_integer", b
"CoordAxis", coord_axis
[0])
2830 elem_props_set(props
, "p_integer", b
"CoordAxisSign", coord_axis
[1])
2831 elem_props_set(props
, "p_integer", b
"OriginalUpAxis", -1)
2832 elem_props_set(props
, "p_integer", b
"OriginalUpAxisSign", 1)
2833 elem_props_set(props
, "p_double", b
"UnitScaleFactor", scale_factor
)
2834 elem_props_set(props
, "p_double", b
"OriginalUnitScaleFactor", scale_factor_org
)
2835 elem_props_set(props
, "p_color_rgb", b
"AmbientColor", (0.0, 0.0, 0.0))
2836 elem_props_set(props
, "p_string", b
"DefaultCamera", "Producer Perspective")
2838 # Global timing data.
2840 _
, fbx_fps_mode
= FBX_FRAMERATES
[0] # Custom framerate.
2841 fbx_fps
= fps
= r
.fps
/ r
.fps_base
2842 for ref_fps
, fps_mode
in FBX_FRAMERATES
:
2843 if similar_values(fps
, ref_fps
):
2845 fbx_fps_mode
= fps_mode
2847 elem_props_set(props
, "p_enum", b
"TimeMode", fbx_fps_mode
)
2848 elem_props_set(props
, "p_timestamp", b
"TimeSpanStart", 0)
2849 elem_props_set(props
, "p_timestamp", b
"TimeSpanStop", FBX_KTIME
)
2850 elem_props_set(props
, "p_double", b
"CustomFrameRate", fbx_fps
)
2852 # ##### End of GlobalSettings element.
2855 def fbx_documents_elements(root
, scene_data
):
2857 Write 'Document' part of FBX root.
2858 Seems like FBX support multiple documents, but until I find examples of such, we'll stick to single doc!
2859 time is expected to be a datetime.datetime object, or None (using now() in this case).
2861 name
= scene_data
.scene
.name
2863 # ##### Start of Documents element.
2864 docs
= elem_empty(root
, b
"Documents")
2866 elem_data_single_int32(docs
, b
"Count", 1)
2868 doc_uid
= get_fbx_uuid_from_key("__FBX_Document__" + name
)
2869 doc
= elem_data_single_int64(docs
, b
"Document", doc_uid
)
2870 doc
.add_string_unicode(name
)
2871 doc
.add_string_unicode(name
)
2873 props
= elem_properties(doc
)
2874 elem_props_set(props
, "p_object", b
"SourceObject")
2875 elem_props_set(props
, "p_string", b
"ActiveAnimStackName", "")
2877 # XXX Some kind of ID? Offset?
2878 # Anyway, as long as we have only one doc, probably not an issue.
2879 elem_data_single_int64(doc
, b
"RootNode", 0)
2882 def fbx_references_elements(root
, scene_data
):
2884 Have no idea what references are in FBX currently... Just writing empty element.
2886 docs
= elem_empty(root
, b
"References")
2889 def fbx_definitions_elements(root
, scene_data
):
2891 Templates definitions. Only used by Objects data afaik (apart from dummy GlobalSettings one).
2893 definitions
= elem_empty(root
, b
"Definitions")
2895 elem_data_single_int32(definitions
, b
"Version", FBX_TEMPLATES_VERSION
)
2896 elem_data_single_int32(definitions
, b
"Count", scene_data
.templates_users
)
2898 fbx_templates_generate(definitions
, scene_data
.templates
)
2901 def fbx_objects_elements(root
, scene_data
):
2903 Data (objects, geometry, material, textures, armatures, etc.).
2907 objects
= elem_empty(root
, b
"Objects")
2909 perfmon
.step("FBX export fetch empties (%d)..." % len(scene_data
.data_empties
))
2911 for empty
in scene_data
.data_empties
:
2912 fbx_data_empty_elements(objects
, empty
, scene_data
)
2914 perfmon
.step("FBX export fetch lamps (%d)..." % len(scene_data
.data_lights
))
2916 for lamp
in scene_data
.data_lights
:
2917 fbx_data_light_elements(objects
, lamp
, scene_data
)
2919 perfmon
.step("FBX export fetch cameras (%d)..." % len(scene_data
.data_cameras
))
2921 for cam
in scene_data
.data_cameras
:
2922 fbx_data_camera_elements(objects
, cam
, scene_data
)
2924 perfmon
.step("FBX export fetch meshes (%d)..."
2925 % len({me_key
for me_key
, _me
, _free
in scene_data
.data_meshes
.values()}))
2928 for me_obj
in scene_data
.data_meshes
:
2929 fbx_data_mesh_elements(objects
, me_obj
, scene_data
, done_meshes
)
2932 perfmon
.step("FBX export fetch objects (%d)..." % len(scene_data
.objects
))
2934 for ob_obj
in scene_data
.objects
:
2937 fbx_data_object_elements(objects
, ob_obj
, scene_data
)
2938 for dp_obj
in ob_obj
.dupli_list_gen(scene_data
.depsgraph
):
2939 if dp_obj
not in scene_data
.objects
:
2941 fbx_data_object_elements(objects
, dp_obj
, scene_data
)
2943 perfmon
.step("FBX export fetch remaining...")
2945 for ob_obj
in scene_data
.objects
:
2946 if not (ob_obj
.is_object
and ob_obj
.type == 'ARMATURE'):
2948 fbx_data_armature_elements(objects
, ob_obj
, scene_data
)
2950 if scene_data
.data_leaf_bones
:
2951 fbx_data_leaf_bone_elements(objects
, scene_data
)
2953 for ma
in scene_data
.data_materials
:
2954 fbx_data_material_elements(objects
, ma
, scene_data
)
2956 for blender_tex_key
in scene_data
.data_textures
:
2957 fbx_data_texture_file_elements(objects
, blender_tex_key
, scene_data
)
2959 for vid
in scene_data
.data_videos
:
2960 fbx_data_video_elements(objects
, vid
, scene_data
)
2962 perfmon
.step("FBX export fetch animations...")
2963 start_time
= time
.process_time()
2965 fbx_data_animation_elements(objects
, scene_data
)
2967 perfmon
.level_down()
2970 def fbx_connections_elements(root
, scene_data
):
2972 Relations between Objects (which material uses which texture, and so on).
2974 connections
= elem_empty(root
, b
"Connections")
2976 for c
in scene_data
.connections
:
2977 elem_connection(connections
, *c
)
2980 def fbx_takes_elements(root
, scene_data
):
2984 # XXX Pretty sure takes are no more needed...
2985 takes
= elem_empty(root
, b
"Takes")
2986 elem_data_single_string(takes
, b
"Current", b
"")
2988 animations
= scene_data
.animations
2989 for astack_key
, animations
, alayer_key
, name
, f_start
, f_end
in animations
:
2990 scene
= scene_data
.scene
2991 fps
= scene
.render
.fps
/ scene
.render
.fps_base
2992 start_ktime
= int(convert_sec_to_ktime(f_start
/ fps
))
2993 end_ktime
= int(convert_sec_to_ktime(f_end
/ fps
))
2995 take
= elem_data_single_string(takes
, b
"Take", name
)
2996 elem_data_single_string(take
, b
"FileName", name
+ b
".tak")
2997 take_loc_time
= elem_data_single_int64(take
, b
"LocalTime", start_ktime
)
2998 take_loc_time
.add_int64(end_ktime
)
2999 take_ref_time
= elem_data_single_int64(take
, b
"ReferenceTime", start_ktime
)
3000 take_ref_time
.add_int64(end_ktime
)
3003 # ##### "Main" functions. #####
3005 # This func can be called with just the filepath
3006 def save_single(operator
, scene
, depsgraph
, filepath
="",
3007 global_matrix
=Matrix(),
3008 apply_unit_scale
=False,
3010 apply_scale_options
='FBX_SCALE_NONE',
3013 context_objects
=None,
3015 use_mesh_modifiers
=True,
3016 use_mesh_modifiers_render
=True,
3017 mesh_smooth_type
='FACE',
3019 use_armature_deform_only
=False,
3021 bake_anim_use_all_bones
=True,
3022 bake_anim_use_nla_strips
=True,
3023 bake_anim_use_all_actions
=True,
3025 bake_anim_simplify_factor
=1.0,
3026 bake_anim_force_startend_keying
=True,
3027 add_leaf_bones
=False,
3028 primary_bone_axis
='Y',
3029 secondary_bone_axis
='X',
3032 use_mesh_edges
=True,
3034 use_triangles
=False,
3035 embed_textures
=False,
3036 use_custom_props
=False,
3037 bake_space_transform
=False,
3038 armature_nodetype
='NULL',
3043 # Clear cached ObjectWrappers (just in case...).
3044 ObjectWrapper
.cache_clear()
3046 if object_types
is None:
3047 object_types
= {'EMPTY', 'CAMERA', 'LIGHT', 'ARMATURE', 'MESH', 'OTHER'}
3049 if 'OTHER' in object_types
:
3050 object_types |
= BLENDER_OTHER_OBJECT_TYPES
3052 # Default Blender unit is equivalent to meter, while FBX one is centimeter...
3053 unit_scale
= units_blender_to_fbx_factor(scene
) if apply_unit_scale
else 100.0
3054 if apply_scale_options
== 'FBX_SCALE_NONE':
3055 global_matrix
= Matrix
.Scale(unit_scale
* global_scale
, 4) @ global_matrix
3057 elif apply_scale_options
== 'FBX_SCALE_UNITS':
3058 global_matrix
= Matrix
.Scale(global_scale
, 4) @ global_matrix
3059 elif apply_scale_options
== 'FBX_SCALE_CUSTOM':
3060 global_matrix
= Matrix
.Scale(unit_scale
, 4) @ global_matrix
3061 unit_scale
= global_scale
3062 else: # if apply_scale_options == 'FBX_SCALE_ALL':
3063 unit_scale
= global_scale
* unit_scale
3065 global_scale
= global_matrix
.median_scale
3066 global_matrix_inv
= global_matrix
.inverted()
3067 # For transforming mesh normals.
3068 global_matrix_inv_transposed
= global_matrix_inv
.transposed()
3070 # Only embed textures in COPY mode!
3071 if embed_textures
and path_mode
!= 'COPY':
3072 embed_textures
= False
3074 # Calculate bone correction matrix
3075 bone_correction_matrix
= None # Default is None = no change
3076 bone_correction_matrix_inv
= None
3077 if (primary_bone_axis
, secondary_bone_axis
) != ('Y', 'X'):
3078 from bpy_extras
.io_utils
import axis_conversion
3079 bone_correction_matrix
= axis_conversion(from_forward
=secondary_bone_axis
,
3080 from_up
=primary_bone_axis
,
3084 bone_correction_matrix_inv
= bone_correction_matrix
.inverted()
3087 media_settings
= FBXExportSettingsMedia(
3089 os
.path
.dirname(bpy
.data
.filepath
), # base_src
3090 os
.path
.dirname(filepath
), # base_dst
3091 # Local dir where to put images (media), using FBX conventions.
3092 os
.path
.splitext(os
.path
.basename(filepath
))[0] + ".fbm", # subdir
3095 set(), # embedded_set
3098 settings
= FBXExportSettings(
3099 operator
.report
, (axis_up
, axis_forward
), global_matrix
, global_scale
, apply_unit_scale
, unit_scale
,
3100 bake_space_transform
, global_matrix_inv
, global_matrix_inv_transposed
,
3101 context_objects
, object_types
, use_mesh_modifiers
, use_mesh_modifiers_render
,
3102 mesh_smooth_type
, use_subsurf
, use_mesh_edges
, use_tspace
, use_triangles
,
3103 armature_nodetype
, use_armature_deform_only
,
3104 add_leaf_bones
, bone_correction_matrix
, bone_correction_matrix_inv
,
3105 bake_anim
, bake_anim_use_all_bones
, bake_anim_use_nla_strips
, bake_anim_use_all_actions
,
3106 bake_anim_step
, bake_anim_simplify_factor
, bake_anim_force_startend_keying
,
3107 False, media_settings
, use_custom_props
, colors_type
,
3110 import bpy_extras
.io_utils
3112 print('\nFBX export starting... %r' % filepath
)
3113 start_time
= time
.process_time()
3115 # Generate some data about exported scene...
3116 scene_data
= fbx_data_from_scene(scene
, depsgraph
, settings
)
3118 root
= elem_empty(None, b
"") # Root element has no id, as it is not saved per se!
3120 # Mostly FBXHeaderExtension and GlobalSettings.
3121 fbx_header_elements(root
, scene_data
)
3123 # Documents and References are pretty much void currently.
3124 fbx_documents_elements(root
, scene_data
)
3125 fbx_references_elements(root
, scene_data
)
3127 # Templates definitions.
3128 fbx_definitions_elements(root
, scene_data
)
3131 fbx_objects_elements(root
, scene_data
)
3133 # How data are inter-connected.
3134 fbx_connections_elements(root
, scene_data
)
3137 fbx_takes_elements(root
, scene_data
)
3140 fbx_scene_data_cleanup(scene_data
)
3142 # And we are down, we can write the whole thing!
3143 encode_bin
.write(filepath
, root
, FBX_VERSION
)
3145 # Clear cached ObjectWrappers!
3146 ObjectWrapper
.cache_clear()
3148 # copy all collected files, if we did not embed them.
3149 if not media_settings
.embed_textures
:
3150 bpy_extras
.io_utils
.path_reference_copy(media_settings
.copy_set
)
3152 print('export finished in %.4f sec.' % (time
.process_time() - start_time
))
3156 # defaults for applications, currently only unity but could add others.
3157 def defaults_unity3d():
3159 # These options seem to produce the same result as the old Ascii exporter in Unity3D:
3161 "axis_forward": '-Z',
3162 "global_matrix": Matrix
.Rotation(-math
.pi
/ 2.0, 4, 'X'),
3163 # Should really be True, but it can cause problems if a model is already in a scene or prefab
3164 # with the old transforms.
3165 "bake_space_transform": False,
3167 "use_selection": False,
3169 "object_types": {'ARMATURE', 'EMPTY', 'MESH', 'OTHER'},
3170 "use_mesh_modifiers": True,
3171 "use_mesh_modifiers_render": True,
3172 "use_mesh_edges": False,
3173 "mesh_smooth_type": 'FACE',
3174 "colors_type": 'SRGB',
3175 "use_subsurf": False,
3176 "use_tspace": False, # XXX Why? Unity is expected to support tspace import...
3177 "use_triangles": False,
3179 "use_armature_deform_only": True,
3181 "use_custom_props": True,
3184 "bake_anim_simplify_factor": 1.0,
3185 "bake_anim_step": 1.0,
3186 "bake_anim_use_nla_strips": True,
3187 "bake_anim_use_all_actions": True,
3188 "add_leaf_bones": False, # Avoid memory/performance cost for something only useful for modelling
3189 "primary_bone_axis": 'Y', # Doesn't really matter for Unity, so leave unchanged
3190 "secondary_bone_axis": 'X',
3192 "path_mode": 'AUTO',
3193 "embed_textures": False,
3194 "batch_mode": 'OFF',
3198 def save(operator
, context
,
3200 use_selection
=False,
3202 use_active_collection
=False,
3204 use_batch_own_dir
=False,
3208 This is a wrapper around save_single, which handles multi-scenes (or collections) cases, when batch-exporting
3209 a whole .blend file.
3214 active_object
= context
.view_layer
.objects
.active
3217 if active_object
and active_object
.mode
!= 'OBJECT' and bpy
.ops
.object.mode_set
.poll():
3218 org_mode
= active_object
.mode
3219 bpy
.ops
.object.mode_set(mode
='OBJECT')
3221 if batch_mode
== 'OFF':
3222 kwargs_mod
= kwargs
.copy()
3223 if use_active_collection
:
3225 ctx_objects
= tuple(obj
3226 for obj
in context
.view_layer
.active_layer_collection
.collection
.all_objects
3227 if obj
.select_get())
3229 ctx_objects
= context
.view_layer
.active_layer_collection
.collection
.all_objects
3232 ctx_objects
= context
.selected_objects
3234 ctx_objects
= context
.view_layer
.objects
3236 ctx_objects
= tuple(obj
for obj
in ctx_objects
if obj
.visible_get())
3237 kwargs_mod
["context_objects"] = ctx_objects
3239 depsgraph
= context
.evaluated_depsgraph_get()
3240 ret
= save_single(operator
, context
.scene
, depsgraph
, filepath
, **kwargs_mod
)
3242 # XXX We need a way to generate a depsgraph for inactive view_layers first...
3243 # XXX Also, what to do in case of batch-exporting scenes, when there is more than one view layer?
3244 # Scenes have no concept of 'active' view layer, that's on window level...
3247 prefix
= os
.path
.basename(fbxpath
)
3249 fbxpath
= os
.path
.dirname(fbxpath
)
3251 if batch_mode
== 'COLLECTION':
3252 data_seq
= tuple((coll
, coll
.name
, 'objects') for coll
in bpy
.data
.collections
if coll
.objects
)
3253 elif batch_mode
in {'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3254 scenes
= [context
.scene
] if batch_mode
== 'ACTIVE_SCENE_COLLECTION' else bpy
.data
.scenes
3256 for scene
in scenes
:
3257 if not scene
.objects
:
3259 # Needed to avoid having tens of 'Scene Collection' entries.
3260 todo_collections
= [(scene
.collection
, "_".join((scene
.name
, scene
.collection
.name
)))]
3261 while todo_collections
:
3262 coll
, coll_name
= todo_collections
.pop()
3263 todo_collections
.extend(((c
, c
.name
) for c
in coll
.children
if c
.all_objects
))
3264 data_seq
.append((coll
, coll_name
, 'all_objects'))
3266 data_seq
= tuple((scene
, scene
.name
, 'objects') for scene
in bpy
.data
.scenes
if scene
.objects
)
3268 # call this function within a loop with BATCH_ENABLE == False
3270 new_fbxpath
= fbxpath
# own dir option modifies, we need to keep an original
3271 for data
, data_name
, data_obj_propname
in data_seq
: # scene or collection
3272 newname
= "_".join((prefix
, bpy
.path
.clean_name(data_name
))) if prefix
else bpy
.path
.clean_name(data_name
)
3274 if use_batch_own_dir
:
3275 new_fbxpath
= os
.path
.join(fbxpath
, newname
)
3276 # path may already exist... and be a file.
3277 while os
.path
.isfile(new_fbxpath
):
3278 new_fbxpath
= "_".join((new_fbxpath
, "dir"))
3279 if not os
.path
.exists(new_fbxpath
):
3280 os
.makedirs(new_fbxpath
)
3282 filepath
= os
.path
.join(new_fbxpath
, newname
+ '.fbx')
3284 print('\nBatch exporting %s as...\n\t%r' % (data
, filepath
))
3286 if batch_mode
in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3287 # Collection, so that objects update properly, add a dummy scene.
3288 scene
= bpy
.data
.scenes
.new(name
="FBX_Temp")
3289 src_scenes
= {} # Count how much each 'source' scenes are used.
3290 for obj
in getattr(data
, data_obj_propname
):
3291 for src_sce
in obj
.users_scene
:
3292 src_scenes
[src_sce
] = src_scenes
.setdefault(src_sce
, 0) + 1
3293 scene
.collection
.objects
.link(obj
)
3295 # Find the 'most used' source scene, and use its unit settings. This is somewhat weak, but should work
3296 # fine in most cases, and avoids stupid issues like T41931.
3297 best_src_scene
= None
3298 best_src_scene_users
= -1
3299 for sce
, nbr_users
in src_scenes
.items():
3300 if (nbr_users
) > best_src_scene_users
:
3301 best_src_scene_users
= nbr_users
3302 best_src_scene
= sce
3303 scene
.unit_settings
.system
= best_src_scene
.unit_settings
.system
3304 scene
.unit_settings
.system_rotation
= best_src_scene
.unit_settings
.system_rotation
3305 scene
.unit_settings
.scale_length
= best_src_scene
.unit_settings
.scale_length
3307 # new scene [only one viewlayer to update]
3308 scene
.view_layers
[0].update()
3309 # TODO - BUMMER! Armatures not in the group wont animate the mesh
3313 kwargs_batch
= kwargs
.copy()
3314 kwargs_batch
["context_objects"] = getattr(data
, data_obj_propname
)
3316 save_single(operator
, scene
, scene
.view_layers
[0].depsgraph
, filepath
, **kwargs_batch
)
3318 if batch_mode
in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3319 # Remove temp collection scene.
3320 bpy
.data
.scenes
.remove(scene
)
3322 if active_object
and org_mode
:
3323 context
.view_layer
.objects
.active
= active_object
3324 if bpy
.ops
.object.mode_set
.poll():
3325 bpy
.ops
.object.mode_set(mode
=org_mode
)