1 # SPDX-License-Identifier: GPL-2.0-or-later
3 # Script copyright (C) Campbell Barton, Bastien Montagne
12 from itertools
import zip_longest
13 from functools
import cache
17 if "encode_bin" in locals():
18 importlib
.reload(encode_bin
)
19 if "data_types" in locals():
20 importlib
.reload(data_types
)
21 if "fbx_utils" in locals():
22 importlib
.reload(fbx_utils
)
26 from bpy_extras
import node_shader_utils
27 from bpy
.app
.translations
import pgettext_tip
as tip_
28 from mathutils
import Vector
, Matrix
30 from . import encode_bin
, data_types
, fbx_utils
31 from .fbx_utils
import (
33 FBX_VERSION
, FBX_HEADER_VERSION
, FBX_SCENEINFO_VERSION
, FBX_TEMPLATES_VERSION
,
35 FBX_GEOMETRY_VERSION
, FBX_GEOMETRY_NORMAL_VERSION
, FBX_GEOMETRY_BINORMAL_VERSION
, FBX_GEOMETRY_TANGENT_VERSION
,
36 FBX_GEOMETRY_SMOOTHING_VERSION
, FBX_GEOMETRY_CREASE_VERSION
, FBX_GEOMETRY_VCOLOR_VERSION
, FBX_GEOMETRY_UV_VERSION
,
37 FBX_GEOMETRY_MATERIAL_VERSION
, FBX_GEOMETRY_LAYER_VERSION
,
38 FBX_GEOMETRY_SHAPE_VERSION
, FBX_DEFORMER_SHAPE_VERSION
, FBX_DEFORMER_SHAPECHANNEL_VERSION
,
39 FBX_POSE_BIND_VERSION
, FBX_DEFORMER_SKIN_VERSION
, FBX_DEFORMER_CLUSTER_VERSION
,
40 FBX_MATERIAL_VERSION
, FBX_TEXTURE_VERSION
,
42 FBX_ANIM_PROPSGROUP_NAME
,
44 BLENDER_OTHER_OBJECT_TYPES
, BLENDER_OBJECT_TYPES_MESHLIKE
,
45 FBX_LIGHT_TYPES
, FBX_LIGHT_DECAY_TYPES
,
46 RIGHT_HAND_AXES
, FBX_FRAMERATES
,
47 # Miscellaneous utils.
49 units_blender_to_fbx_factor
, units_convertor
, units_convertor_iter
,
50 matrix4_to_array
, similar_values
, shape_difference_exclude_similar
, astype_view_signedness
, fast_first_axis_unique
,
52 # Mesh transform helpers.
53 vcos_transformed
, nors_transformed
,
55 get_fbx_uuid_from_key
,
57 get_blenderID_key
, get_blenderID_name
,
58 get_blender_mesh_shape_key
, get_blender_mesh_shape_channel_key
,
59 get_blender_empty_key
, get_blender_bone_key
,
60 get_blender_bindpose_key
, get_blender_armature_skin_key
, get_blender_bone_cluster_key
,
61 get_blender_anim_id_base
, get_blender_anim_stack_key
, get_blender_anim_layer_key
,
62 get_blender_anim_curve_node_key
, get_blender_anim_curve_key
,
63 get_blender_nodetexture_key
,
66 elem_data_single_bool
, elem_data_single_int16
, elem_data_single_int32
, elem_data_single_int64
,
67 elem_data_single_float32
, elem_data_single_float64
,
68 elem_data_single_bytes
, elem_data_single_string
, elem_data_single_string_unicode
,
69 elem_data_single_bool_array
, elem_data_single_int32_array
, elem_data_single_int64_array
,
70 elem_data_single_float32_array
, elem_data_single_float64_array
, elem_data_vec_float64
,
71 # FBX element properties.
72 elem_properties
, elem_props_set
, elem_props_compound
,
73 # FBX element properties handling templates.
74 elem_props_template_init
, elem_props_template_set
, elem_props_template_finalize
,
76 FBXTemplate
, fbx_templates_generate
,
78 AnimationCurveNodeWrapper
,
80 ObjectWrapper
, fbx_name_class
,
82 FBXExportSettingsMedia
, FBXExportSettings
, FBXExportData
,
86 convert_sec_to_ktime
= units_convertor("second", "ktime")
87 convert_sec_to_ktime_iter
= units_convertor_iter("second", "ktime")
89 convert_mm_to_inch
= units_convertor("millimeter", "inch")
91 convert_rad_to_deg
= units_convertor("radian", "degree")
92 convert_rad_to_deg_iter
= units_convertor_iter("radian", "degree")
95 # ##### Templates #####
96 # TODO: check all those "default" values, they should match Blender's default as much as possible, I guess?
98 def fbx_template_def_globalsettings(scene
, settings
, override_defaults
=None, nbr_users
=0):
100 if override_defaults
is not None:
101 props
.update(override_defaults
)
102 return FBXTemplate(b
"GlobalSettings", b
"", props
, nbr_users
, [False])
105 def fbx_template_def_model(scene
, settings
, override_defaults
=None, nbr_users
=0):
106 gscale
= settings
.global_scale
108 # Name, Value, Type, Animatable
109 b
"QuaternionInterpolate": (0, "p_enum", False), # 0 = no quat interpolation.
110 b
"RotationOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
111 b
"RotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
112 b
"ScalingOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
113 b
"ScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
114 b
"TranslationActive": (False, "p_bool", False),
115 b
"TranslationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
116 b
"TranslationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
117 b
"TranslationMinX": (False, "p_bool", False),
118 b
"TranslationMinY": (False, "p_bool", False),
119 b
"TranslationMinZ": (False, "p_bool", False),
120 b
"TranslationMaxX": (False, "p_bool", False),
121 b
"TranslationMaxY": (False, "p_bool", False),
122 b
"TranslationMaxZ": (False, "p_bool", False),
123 b
"RotationOrder": (0, "p_enum", False), # we always use 'XYZ' order.
124 b
"RotationSpaceForLimitOnly": (False, "p_bool", False),
125 b
"RotationStiffnessX": (0.0, "p_double", False),
126 b
"RotationStiffnessY": (0.0, "p_double", False),
127 b
"RotationStiffnessZ": (0.0, "p_double", False),
128 b
"AxisLen": (10.0, "p_double", False),
129 b
"PreRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
130 b
"PostRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
131 b
"RotationActive": (False, "p_bool", False),
132 b
"RotationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
133 b
"RotationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
134 b
"RotationMinX": (False, "p_bool", False),
135 b
"RotationMinY": (False, "p_bool", False),
136 b
"RotationMinZ": (False, "p_bool", False),
137 b
"RotationMaxX": (False, "p_bool", False),
138 b
"RotationMaxY": (False, "p_bool", False),
139 b
"RotationMaxZ": (False, "p_bool", False),
140 b
"InheritType": (0, "p_enum", False), # RrSs
141 b
"ScalingActive": (False, "p_bool", False),
142 b
"ScalingMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
143 b
"ScalingMax": ((1.0, 1.0, 1.0), "p_vector_3d", False),
144 b
"ScalingMinX": (False, "p_bool", False),
145 b
"ScalingMinY": (False, "p_bool", False),
146 b
"ScalingMinZ": (False, "p_bool", False),
147 b
"ScalingMaxX": (False, "p_bool", False),
148 b
"ScalingMaxY": (False, "p_bool", False),
149 b
"ScalingMaxZ": (False, "p_bool", False),
150 b
"GeometricTranslation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
151 b
"GeometricRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
152 b
"GeometricScaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
153 b
"MinDampRangeX": (0.0, "p_double", False),
154 b
"MinDampRangeY": (0.0, "p_double", False),
155 b
"MinDampRangeZ": (0.0, "p_double", False),
156 b
"MaxDampRangeX": (0.0, "p_double", False),
157 b
"MaxDampRangeY": (0.0, "p_double", False),
158 b
"MaxDampRangeZ": (0.0, "p_double", False),
159 b
"MinDampStrengthX": (0.0, "p_double", False),
160 b
"MinDampStrengthY": (0.0, "p_double", False),
161 b
"MinDampStrengthZ": (0.0, "p_double", False),
162 b
"MaxDampStrengthX": (0.0, "p_double", False),
163 b
"MaxDampStrengthY": (0.0, "p_double", False),
164 b
"MaxDampStrengthZ": (0.0, "p_double", False),
165 b
"PreferedAngleX": (0.0, "p_double", False),
166 b
"PreferedAngleY": (0.0, "p_double", False),
167 b
"PreferedAngleZ": (0.0, "p_double", False),
168 b
"LookAtProperty": (None, "p_object", False),
169 b
"UpVectorProperty": (None, "p_object", False),
170 b
"Show": (True, "p_bool", False),
171 b
"NegativePercentShapeSupport": (True, "p_bool", False),
172 b
"DefaultAttributeIndex": (-1, "p_integer", False),
173 b
"Freeze": (False, "p_bool", False),
174 b
"LODBox": (False, "p_bool", False),
175 b
"Lcl Translation": ((0.0, 0.0, 0.0), "p_lcl_translation", True),
176 b
"Lcl Rotation": ((0.0, 0.0, 0.0), "p_lcl_rotation", True),
177 b
"Lcl Scaling": ((1.0, 1.0, 1.0), "p_lcl_scaling", True),
178 b
"Visibility": (1.0, "p_visibility", True),
179 b
"Visibility Inheritance": (1, "p_visibility_inheritance", False),
181 if override_defaults
is not None:
182 props
.update(override_defaults
)
183 return FBXTemplate(b
"Model", b
"FbxNode", props
, nbr_users
, [False])
186 def fbx_template_def_null(scene
, settings
, override_defaults
=None, nbr_users
=0):
188 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
189 b
"Size": (100.0, "p_double", False),
190 b
"Look": (1, "p_enum", False), # Cross (0 is None, i.e. invisible?).
192 if override_defaults
is not None:
193 props
.update(override_defaults
)
194 return FBXTemplate(b
"NodeAttribute", b
"FbxNull", props
, nbr_users
, [False])
197 def fbx_template_def_light(scene
, settings
, override_defaults
=None, nbr_users
=0):
198 gscale
= settings
.global_scale
200 b
"LightType": (0, "p_enum", False), # Point light.
201 b
"CastLight": (True, "p_bool", False),
202 b
"Color": ((1.0, 1.0, 1.0), "p_color", True),
203 b
"Intensity": (100.0, "p_number", True), # Times 100 compared to Blender values...
204 b
"DecayType": (2, "p_enum", False), # Quadratic.
205 b
"DecayStart": (30.0 * gscale
, "p_double", False),
206 b
"CastShadows": (True, "p_bool", False),
207 b
"ShadowColor": ((0.0, 0.0, 0.0), "p_color", True),
208 b
"AreaLightShape": (0, "p_enum", False), # Rectangle.
210 if override_defaults
is not None:
211 props
.update(override_defaults
)
212 return FBXTemplate(b
"NodeAttribute", b
"FbxLight", props
, nbr_users
, [False])
215 def fbx_template_def_camera(scene
, settings
, override_defaults
=None, nbr_users
=0):
218 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
219 b
"Position": ((0.0, 0.0, -50.0), "p_vector", True),
220 b
"UpVector": ((0.0, 1.0, 0.0), "p_vector", True),
221 b
"InterestPosition": ((0.0, 0.0, 0.0), "p_vector", True),
222 b
"Roll": (0.0, "p_roll", True),
223 b
"OpticalCenterX": (0.0, "p_opticalcenterx", True),
224 b
"OpticalCenterY": (0.0, "p_opticalcentery", True),
225 b
"BackgroundColor": ((0.63, 0.63, 0.63), "p_color", True),
226 b
"TurnTable": (0.0, "p_number", True),
227 b
"DisplayTurnTableIcon": (False, "p_bool", False),
228 b
"UseMotionBlur": (False, "p_bool", False),
229 b
"UseRealTimeMotionBlur": (True, "p_bool", False),
230 b
"Motion Blur Intensity": (1.0, "p_number", True),
231 b
"AspectRatioMode": (0, "p_enum", False), # WindowSize.
232 b
"AspectWidth": (320.0, "p_double", False),
233 b
"AspectHeight": (200.0, "p_double", False),
234 b
"PixelAspectRatio": (1.0, "p_double", False),
235 b
"FilmOffsetX": (0.0, "p_number", True),
236 b
"FilmOffsetY": (0.0, "p_number", True),
237 b
"FilmWidth": (0.816, "p_double", False),
238 b
"FilmHeight": (0.612, "p_double", False),
239 b
"FilmAspectRatio": (1.3333333333333333, "p_double", False),
240 b
"FilmSqueezeRatio": (1.0, "p_double", False),
241 b
"FilmFormatIndex": (0, "p_enum", False), # Assuming this is ApertureFormat, 0 = custom.
242 b
"PreScale": (1.0, "p_number", True),
243 b
"FilmTranslateX": (0.0, "p_number", True),
244 b
"FilmTranslateY": (0.0, "p_number", True),
245 b
"FilmRollPivotX": (0.0, "p_number", True),
246 b
"FilmRollPivotY": (0.0, "p_number", True),
247 b
"FilmRollValue": (0.0, "p_number", True),
248 b
"FilmRollOrder": (0, "p_enum", False), # 0 = rotate first (default).
249 b
"ApertureMode": (2, "p_enum", False), # 2 = Vertical.
250 b
"GateFit": (0, "p_enum", False), # 0 = no resolution gate fit.
251 b
"FieldOfView": (25.114999771118164, "p_fov", True),
252 b
"FieldOfViewX": (40.0, "p_fov_x", True),
253 b
"FieldOfViewY": (40.0, "p_fov_y", True),
254 b
"FocalLength": (34.89327621672628, "p_number", True),
255 b
"CameraFormat": (0, "p_enum", False), # Custom camera format.
256 b
"UseFrameColor": (False, "p_bool", False),
257 b
"FrameColor": ((0.3, 0.3, 0.3), "p_color_rgb", False),
258 b
"ShowName": (True, "p_bool", False),
259 b
"ShowInfoOnMoving": (True, "p_bool", False),
260 b
"ShowGrid": (True, "p_bool", False),
261 b
"ShowOpticalCenter": (False, "p_bool", False),
262 b
"ShowAzimut": (True, "p_bool", False),
263 b
"ShowTimeCode": (False, "p_bool", False),
264 b
"ShowAudio": (False, "p_bool", False),
265 b
"AudioColor": ((0.0, 1.0, 0.0), "p_vector_3d", False), # Yep, vector3d, not corlorgb… :cry:
266 b
"NearPlane": (10.0, "p_double", False),
267 b
"FarPlane": (4000.0, "p_double", False),
268 b
"AutoComputeClipPanes": (False, "p_bool", False),
269 b
"ViewCameraToLookAt": (True, "p_bool", False),
270 b
"ViewFrustumNearFarPlane": (False, "p_bool", False),
271 b
"ViewFrustumBackPlaneMode": (2, "p_enum", False), # 2 = show back plane if texture added.
272 b
"BackPlaneDistance": (4000.0, "p_number", True),
273 b
"BackPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
274 b
"ViewFrustumFrontPlaneMode": (2, "p_enum", False), # 2 = show front plane if texture added.
275 b
"FrontPlaneDistance": (10.0, "p_number", True),
276 b
"FrontPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
277 b
"LockMode": (False, "p_bool", False),
278 b
"LockInterestNavigation": (False, "p_bool", False),
279 # BackPlate... properties **arggggg!**
280 b
"FitImage": (False, "p_bool", False),
281 b
"Crop": (False, "p_bool", False),
282 b
"Center": (True, "p_bool", False),
283 b
"KeepRatio": (True, "p_bool", False),
284 # End of BackPlate...
285 b
"BackgroundAlphaTreshold": (0.5, "p_double", False),
286 b
"ShowBackplate": (True, "p_bool", False),
287 b
"BackPlaneOffsetX": (0.0, "p_number", True),
288 b
"BackPlaneOffsetY": (0.0, "p_number", True),
289 b
"BackPlaneRotation": (0.0, "p_number", True),
290 b
"BackPlaneScaleX": (1.0, "p_number", True),
291 b
"BackPlaneScaleY": (1.0, "p_number", True),
292 b
"Background Texture": (None, "p_object", False),
293 b
"FrontPlateFitImage": (True, "p_bool", False),
294 b
"FrontPlateCrop": (False, "p_bool", False),
295 b
"FrontPlateCenter": (True, "p_bool", False),
296 b
"FrontPlateKeepRatio": (True, "p_bool", False),
297 b
"Foreground Opacity": (1.0, "p_double", False),
298 b
"ShowFrontplate": (True, "p_bool", False),
299 b
"FrontPlaneOffsetX": (0.0, "p_number", True),
300 b
"FrontPlaneOffsetY": (0.0, "p_number", True),
301 b
"FrontPlaneRotation": (0.0, "p_number", True),
302 b
"FrontPlaneScaleX": (1.0, "p_number", True),
303 b
"FrontPlaneScaleY": (1.0, "p_number", True),
304 b
"Foreground Texture": (None, "p_object", False),
305 b
"DisplaySafeArea": (False, "p_bool", False),
306 b
"DisplaySafeAreaOnRender": (False, "p_bool", False),
307 b
"SafeAreaDisplayStyle": (1, "p_enum", False), # 1 = rounded corners.
308 b
"SafeAreaAspectRatio": (1.3333333333333333, "p_double", False),
309 b
"Use2DMagnifierZoom": (False, "p_bool", False),
310 b
"2D Magnifier Zoom": (100.0, "p_number", True),
311 b
"2D Magnifier X": (50.0, "p_number", True),
312 b
"2D Magnifier Y": (50.0, "p_number", True),
313 b
"CameraProjectionType": (0, "p_enum", False), # 0 = perspective, 1 = orthogonal.
314 b
"OrthoZoom": (1.0, "p_double", False),
315 b
"UseRealTimeDOFAndAA": (False, "p_bool", False),
316 b
"UseDepthOfField": (False, "p_bool", False),
317 b
"FocusSource": (0, "p_enum", False), # 0 = camera interest, 1 = distance from camera interest.
318 b
"FocusAngle": (3.5, "p_double", False), # ???
319 b
"FocusDistance": (200.0, "p_double", False),
320 b
"UseAntialiasing": (False, "p_bool", False),
321 b
"AntialiasingIntensity": (0.77777, "p_double", False),
322 b
"AntialiasingMethod": (0, "p_enum", False), # 0 = oversampling, 1 = hardware.
323 b
"UseAccumulationBuffer": (False, "p_bool", False),
324 b
"FrameSamplingCount": (7, "p_integer", False),
325 b
"FrameSamplingType": (1, "p_enum", False), # 0 = uniform, 1 = stochastic.
327 if override_defaults
is not None:
328 props
.update(override_defaults
)
329 return FBXTemplate(b
"NodeAttribute", b
"FbxCamera", props
, nbr_users
, [False])
332 def fbx_template_def_bone(scene
, settings
, override_defaults
=None, nbr_users
=0):
334 if override_defaults
is not None:
335 props
.update(override_defaults
)
336 return FBXTemplate(b
"NodeAttribute", b
"LimbNode", props
, nbr_users
, [False])
339 def fbx_template_def_geometry(scene
, settings
, override_defaults
=None, nbr_users
=0):
341 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
342 b
"BBoxMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
343 b
"BBoxMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
344 b
"Primary Visibility": (True, "p_bool", False),
345 b
"Casts Shadows": (True, "p_bool", False),
346 b
"Receive Shadows": (True, "p_bool", False),
348 if override_defaults
is not None:
349 props
.update(override_defaults
)
350 return FBXTemplate(b
"Geometry", b
"FbxMesh", props
, nbr_users
, [False])
353 def fbx_template_def_material(scene
, settings
, override_defaults
=None, nbr_users
=0):
356 b
"ShadingModel": ("Phong", "p_string", False),
357 b
"MultiLayer": (False, "p_bool", False),
359 b
"EmissiveColor": ((0.0, 0.0, 0.0), "p_color", True),
360 b
"EmissiveFactor": (1.0, "p_number", True),
361 b
"AmbientColor": ((0.2, 0.2, 0.2), "p_color", True),
362 b
"AmbientFactor": (1.0, "p_number", True),
363 b
"DiffuseColor": ((0.8, 0.8, 0.8), "p_color", True),
364 b
"DiffuseFactor": (1.0, "p_number", True),
365 b
"TransparentColor": ((0.0, 0.0, 0.0), "p_color", True),
366 b
"TransparencyFactor": (0.0, "p_number", True),
367 b
"Opacity": (1.0, "p_number", True),
368 b
"NormalMap": ((0.0, 0.0, 0.0), "p_vector_3d", False),
369 b
"Bump": ((0.0, 0.0, 0.0), "p_vector_3d", False),
370 b
"BumpFactor": (1.0, "p_double", False),
371 b
"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
372 b
"DisplacementFactor": (1.0, "p_double", False),
373 b
"VectorDisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
374 b
"VectorDisplacementFactor": (1.0, "p_double", False),
376 b
"SpecularColor": ((0.2, 0.2, 0.2), "p_color", True),
377 b
"SpecularFactor": (1.0, "p_number", True),
378 # Not sure about the name, importer uses this (but ShininessExponent for tex prop name!)
379 # And in fbx exported by sdk, you have one in template, the other in actual material!!! :/
380 # For now, using both.
381 b
"Shininess": (20.0, "p_number", True),
382 b
"ShininessExponent": (20.0, "p_number", True),
383 b
"ReflectionColor": ((0.0, 0.0, 0.0), "p_color", True),
384 b
"ReflectionFactor": (1.0, "p_number", True),
386 if override_defaults
is not None:
387 props
.update(override_defaults
)
388 return FBXTemplate(b
"Material", b
"FbxSurfacePhong", props
, nbr_users
, [False])
391 def fbx_template_def_texture_file(scene
, settings
, override_defaults
=None, nbr_users
=0):
393 # XXX Not sure about all names!
395 b
"TextureTypeUse": (0, "p_enum", False), # Standard.
396 b
"AlphaSource": (2, "p_enum", False), # Black (i.e. texture's alpha), XXX name guessed!.
397 b
"Texture alpha": (1.0, "p_double", False),
398 b
"PremultiplyAlpha": (True, "p_bool", False),
399 b
"CurrentTextureBlendMode": (1, "p_enum", False), # Additive...
400 b
"CurrentMappingType": (0, "p_enum", False), # UV.
401 b
"UVSet": ("default", "p_string", False), # UVMap name.
402 b
"WrapModeU": (0, "p_enum", False), # Repeat.
403 b
"WrapModeV": (0, "p_enum", False), # Repeat.
404 b
"UVSwap": (False, "p_bool", False),
405 b
"Translation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
406 b
"Rotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
407 b
"Scaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
408 b
"TextureRotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
409 b
"TextureScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
410 # Not sure about those two...
411 b
"UseMaterial": (False, "p_bool", False),
412 b
"UseMipMap": (False, "p_bool", False),
414 if override_defaults
is not None:
415 props
.update(override_defaults
)
416 return FBXTemplate(b
"Texture", b
"FbxFileTexture", props
, nbr_users
, [False])
419 def fbx_template_def_video(scene
, settings
, override_defaults
=None, nbr_users
=0):
423 b
"Width": (0, "p_integer", False),
424 b
"Height": (0, "p_integer", False),
425 b
"Path": ("", "p_string_url", False),
426 b
"AccessMode": (0, "p_enum", False), # Disk (0=Disk, 1=Mem, 2=DiskAsync).
428 b
"StartFrame": (0, "p_integer", False),
429 b
"StopFrame": (0, "p_integer", False),
430 b
"Offset": (0, "p_timestamp", False),
431 b
"PlaySpeed": (0.0, "p_double", False),
432 b
"FreeRunning": (False, "p_bool", False),
433 b
"Loop": (False, "p_bool", False),
434 b
"InterlaceMode": (0, "p_enum", False), # None, i.e. progressive.
436 b
"ImageSequence": (False, "p_bool", False),
437 b
"ImageSequenceOffset": (0, "p_integer", False),
438 b
"FrameRate": (0.0, "p_double", False),
439 b
"LastFrame": (0, "p_integer", False),
441 if override_defaults
is not None:
442 props
.update(override_defaults
)
443 return FBXTemplate(b
"Video", b
"FbxVideo", props
, nbr_users
, [False])
446 def fbx_template_def_pose(scene
, settings
, override_defaults
=None, nbr_users
=0):
448 if override_defaults
is not None:
449 props
.update(override_defaults
)
450 return FBXTemplate(b
"Pose", b
"", props
, nbr_users
, [False])
453 def fbx_template_def_deformer(scene
, settings
, override_defaults
=None, nbr_users
=0):
455 if override_defaults
is not None:
456 props
.update(override_defaults
)
457 return FBXTemplate(b
"Deformer", b
"", props
, nbr_users
, [False])
460 def fbx_template_def_animstack(scene
, settings
, override_defaults
=None, nbr_users
=0):
462 b
"Description": ("", "p_string", False),
463 b
"LocalStart": (0, "p_timestamp", False),
464 b
"LocalStop": (0, "p_timestamp", False),
465 b
"ReferenceStart": (0, "p_timestamp", False),
466 b
"ReferenceStop": (0, "p_timestamp", False),
468 if override_defaults
is not None:
469 props
.update(override_defaults
)
470 return FBXTemplate(b
"AnimationStack", b
"FbxAnimStack", props
, nbr_users
, [False])
473 def fbx_template_def_animlayer(scene
, settings
, override_defaults
=None, nbr_users
=0):
475 b
"Weight": (100.0, "p_number", True),
476 b
"Mute": (False, "p_bool", False),
477 b
"Solo": (False, "p_bool", False),
478 b
"Lock": (False, "p_bool", False),
479 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
480 b
"BlendMode": (0, "p_enum", False),
481 b
"RotationAccumulationMode": (0, "p_enum", False),
482 b
"ScaleAccumulationMode": (0, "p_enum", False),
483 b
"BlendModeBypass": (0, "p_ulonglong", False),
485 if override_defaults
is not None:
486 props
.update(override_defaults
)
487 return FBXTemplate(b
"AnimationLayer", b
"FbxAnimLayer", props
, nbr_users
, [False])
490 def fbx_template_def_animcurvenode(scene
, settings
, override_defaults
=None, nbr_users
=0):
492 FBX_ANIM_PROPSGROUP_NAME
.encode(): (None, "p_compound", False),
494 if override_defaults
is not None:
495 props
.update(override_defaults
)
496 return FBXTemplate(b
"AnimationCurveNode", b
"FbxAnimCurveNode", props
, nbr_users
, [False])
499 def fbx_template_def_animcurve(scene
, settings
, override_defaults
=None, nbr_users
=0):
501 if override_defaults
is not None:
502 props
.update(override_defaults
)
503 return FBXTemplate(b
"AnimationCurve", b
"", props
, nbr_users
, [False])
506 # ##### Generators for connection elements. #####
508 def elem_connection(elem
, c_type
, uid_src
, uid_dst
, prop_dst
=None):
509 e
= elem_data_single_string(elem
, b
"C", c_type
)
512 if prop_dst
is not None:
513 e
.add_string(prop_dst
)
516 # ##### FBX objects generators. #####
518 def fbx_data_element_custom_properties(props
, bid
):
520 Store custom properties of blender ID bid (any mapping-like object, in fact) into FBX properties props.
527 rna_properties
= {prop
.identifier
for prop
in bid
.bl_rna
.properties
if prop
.is_runtime
}
530 if k
in rna_properties
:
533 list_val
= getattr(v
, "to_list", lambda: None)()
535 if isinstance(v
, str):
536 elem_props_set(props
, "p_string", k
.encode(), v
, custom
=True)
537 elif isinstance(v
, int):
538 elem_props_set(props
, "p_integer", k
.encode(), v
, custom
=True)
539 elif isinstance(v
, float):
540 elem_props_set(props
, "p_double", k
.encode(), v
, custom
=True)
542 if len(list_val
) == 3:
543 elem_props_set(props
, "p_vector", k
.encode(), list_val
, custom
=True)
545 elem_props_set(props
, "p_string", k
.encode(), str(list_val
), custom
=True)
547 elem_props_set(props
, "p_string", k
.encode(), str(v
), custom
=True)
550 def fbx_data_empty_elements(root
, empty
, scene_data
):
552 Write the Empty data block (you can control its FBX datatype with the 'fbx_type' string custom property).
554 empty_key
= scene_data
.data_empties
[empty
]
556 null
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(empty_key
))
557 null
.add_string(fbx_name_class(empty
.name
.encode(), b
"NodeAttribute"))
558 val
= empty
.bdata
.get('fbx_type', None)
559 null
.add_string(val
.encode() if val
and isinstance(val
, str) else b
"Null")
561 elem_data_single_string(null
, b
"TypeFlags", b
"Null")
563 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Null")
564 props
= elem_properties(null
)
565 elem_props_template_finalize(tmpl
, props
)
567 # No custom properties, already saved with object (Model).
570 def fbx_data_light_elements(root
, lamp
, scene_data
):
572 Write the Lamp data block.
574 gscale
= scene_data
.settings
.global_scale
576 light_key
= scene_data
.data_lights
[lamp
]
578 decay_type
= FBX_LIGHT_DECAY_TYPES
['CONSTANT']
580 shadow_color
= Vector((0.0, 0.0, 0.0))
581 if lamp
.type not in {'HEMI'}:
582 if lamp
.type not in {'SUN', 'AREA'}:
583 decay_type
= FBX_LIGHT_DECAY_TYPES
[lamp
.falloff_type
]
585 do_shadow
= lamp
.use_shadow
586 shadow_color
= lamp
.shadow_color
588 light
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(light_key
))
589 light
.add_string(fbx_name_class(lamp
.name
.encode(), b
"NodeAttribute"))
590 light
.add_string(b
"Light")
592 elem_data_single_int32(light
, b
"GeometryVersion", FBX_GEOMETRY_VERSION
) # Sic...
594 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Light")
595 props
= elem_properties(light
)
596 elem_props_template_set(tmpl
, props
, "p_enum", b
"LightType", FBX_LIGHT_TYPES
[lamp
.type])
597 elem_props_template_set(tmpl
, props
, "p_bool", b
"CastLight", do_light
)
598 elem_props_template_set(tmpl
, props
, "p_color", b
"Color", lamp
.color
)
599 elem_props_template_set(tmpl
, props
, "p_number", b
"Intensity", lamp
.energy
* 100.0)
600 elem_props_template_set(tmpl
, props
, "p_enum", b
"DecayType", decay_type
)
601 elem_props_template_set(tmpl
, props
, "p_double", b
"DecayStart", lamp
.distance
* gscale
)
602 elem_props_template_set(tmpl
, props
, "p_bool", b
"CastShadows", do_shadow
)
603 elem_props_template_set(tmpl
, props
, "p_color", b
"ShadowColor", shadow_color
)
604 if lamp
.type in {'SPOT'}:
605 elem_props_template_set(tmpl
, props
, "p_double", b
"OuterAngle", math
.degrees(lamp
.spot_size
))
606 elem_props_template_set(tmpl
, props
, "p_double", b
"InnerAngle",
607 math
.degrees(lamp
.spot_size
* (1.0 - lamp
.spot_blend
)))
608 elem_props_template_finalize(tmpl
, props
)
611 if scene_data
.settings
.use_custom_props
:
612 fbx_data_element_custom_properties(props
, lamp
)
615 def fbx_data_camera_elements(root
, cam_obj
, scene_data
):
617 Write the Camera data blocks.
619 gscale
= scene_data
.settings
.global_scale
623 cam_key
= scene_data
.data_cameras
[cam_obj
]
625 # Real data now, good old camera!
626 # Object transform info.
627 loc
, rot
, scale
, matrix
, matrix_rot
= cam_obj
.fbx_object_tx(scene_data
)
628 up
= matrix_rot
@ Vector((0.0, 1.0, 0.0))
629 to
= matrix_rot
@ Vector((0.0, 0.0, -1.0))
631 # TODO We could export much more...
632 render
= scene_data
.scene
.render
633 width
= render
.resolution_x
634 height
= render
.resolution_y
635 aspect
= width
/ height
636 # Film width & height from mm to inches
637 filmwidth
= convert_mm_to_inch(cam_data
.sensor_width
)
638 filmheight
= convert_mm_to_inch(cam_data
.sensor_height
)
639 filmaspect
= filmwidth
/ filmheight
641 offsetx
= filmwidth
* cam_data
.shift_x
642 offsety
= filmaspect
* filmheight
* cam_data
.shift_y
644 cam
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(cam_key
))
645 cam
.add_string(fbx_name_class(cam_data
.name
.encode(), b
"NodeAttribute"))
646 cam
.add_string(b
"Camera")
648 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Camera")
649 props
= elem_properties(cam
)
651 elem_props_template_set(tmpl
, props
, "p_vector", b
"Position", loc
)
652 elem_props_template_set(tmpl
, props
, "p_vector", b
"UpVector", up
)
653 elem_props_template_set(tmpl
, props
, "p_vector", b
"InterestPosition", loc
+ to
) # Point, not vector!
654 # Should we use world value?
655 elem_props_template_set(tmpl
, props
, "p_color", b
"BackgroundColor", (0.0, 0.0, 0.0))
656 elem_props_template_set(tmpl
, props
, "p_bool", b
"DisplayTurnTableIcon", True)
658 elem_props_template_set(tmpl
, props
, "p_enum", b
"AspectRatioMode", 2) # FixedResolution
659 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectWidth", float(render
.resolution_x
))
660 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectHeight", float(render
.resolution_y
))
661 elem_props_template_set(tmpl
, props
, "p_double", b
"PixelAspectRatio",
662 float(render
.pixel_aspect_x
/ render
.pixel_aspect_y
))
664 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmWidth", filmwidth
)
665 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmHeight", filmheight
)
666 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmAspectRatio", filmaspect
)
667 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmOffsetX", offsetx
)
668 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmOffsetY", offsety
)
670 elem_props_template_set(tmpl
, props
, "p_enum", b
"ApertureMode", 3) # FocalLength.
671 elem_props_template_set(tmpl
, props
, "p_enum", b
"GateFit", 2) # FitHorizontal.
672 elem_props_template_set(tmpl
, props
, "p_fov", b
"FieldOfView", math
.degrees(cam_data
.angle_x
))
673 elem_props_template_set(tmpl
, props
, "p_fov_x", b
"FieldOfViewX", math
.degrees(cam_data
.angle_x
))
674 elem_props_template_set(tmpl
, props
, "p_fov_y", b
"FieldOfViewY", math
.degrees(cam_data
.angle_y
))
675 # No need to convert to inches here...
676 elem_props_template_set(tmpl
, props
, "p_double", b
"FocalLength", cam_data
.lens
)
677 elem_props_template_set(tmpl
, props
, "p_double", b
"SafeAreaAspectRatio", aspect
)
678 # Depth of field and Focus distance.
679 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseDepthOfField", cam_data
.dof
.use_dof
)
680 elem_props_template_set(tmpl
, props
, "p_double", b
"FocusDistance", cam_data
.dof
.focus_distance
* 1000 * gscale
)
681 # Default to perspective camera.
682 elem_props_template_set(tmpl
, props
, "p_enum", b
"CameraProjectionType", 1 if cam_data
.type == 'ORTHO' else 0)
683 elem_props_template_set(tmpl
, props
, "p_double", b
"OrthoZoom", cam_data
.ortho_scale
)
685 elem_props_template_set(tmpl
, props
, "p_double", b
"NearPlane", cam_data
.clip_start
* gscale
)
686 elem_props_template_set(tmpl
, props
, "p_double", b
"FarPlane", cam_data
.clip_end
* gscale
)
687 elem_props_template_set(tmpl
, props
, "p_enum", b
"BackPlaneDistanceMode", 1) # RelativeToCamera.
688 elem_props_template_set(tmpl
, props
, "p_double", b
"BackPlaneDistance", cam_data
.clip_end
* gscale
)
690 elem_props_template_finalize(tmpl
, props
)
693 if scene_data
.settings
.use_custom_props
:
694 fbx_data_element_custom_properties(props
, cam_data
)
696 elem_data_single_string(cam
, b
"TypeFlags", b
"Camera")
697 elem_data_single_int32(cam
, b
"GeometryVersion", 124) # Sic...
698 elem_data_vec_float64(cam
, b
"Position", loc
)
699 elem_data_vec_float64(cam
, b
"Up", up
)
700 elem_data_vec_float64(cam
, b
"LookAt", to
)
701 elem_data_single_int32(cam
, b
"ShowInfoOnMoving", 1)
702 elem_data_single_int32(cam
, b
"ShowAudio", 0)
703 elem_data_vec_float64(cam
, b
"AudioColor", (0.0, 1.0, 0.0))
704 elem_data_single_float64(cam
, b
"CameraOrthoZoom", 1.0)
707 def fbx_data_bindpose_element(root
, me_obj
, me
, scene_data
, arm_obj
=None, mat_world_arm
=None, bones
=[]):
709 Helper, since bindpose are used by both meshes shape keys and armature bones...
713 # We assume bind pose for our bones are their "Editmode" pose...
714 # All matrices are expected in global (world) space.
715 bindpose_key
= get_blender_bindpose_key(arm_obj
.bdata
, me
)
716 fbx_pose
= elem_data_single_int64(root
, b
"Pose", get_fbx_uuid_from_key(bindpose_key
))
717 fbx_pose
.add_string(fbx_name_class(me
.name
.encode(), b
"Pose"))
718 fbx_pose
.add_string(b
"BindPose")
720 elem_data_single_string(fbx_pose
, b
"Type", b
"BindPose")
721 elem_data_single_int32(fbx_pose
, b
"Version", FBX_POSE_BIND_VERSION
)
722 elem_data_single_int32(fbx_pose
, b
"NbPoseNodes", 1 + (1 if (arm_obj
!= me_obj
) else 0) + len(bones
))
724 # First node is mesh/object.
725 mat_world_obj
= me_obj
.fbx_object_matrix(scene_data
, global_space
=True)
726 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
727 elem_data_single_int64(fbx_posenode
, b
"Node", me_obj
.fbx_uuid
)
728 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(mat_world_obj
))
729 # Second node is armature object itself.
730 if arm_obj
!= me_obj
:
731 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
732 elem_data_single_int64(fbx_posenode
, b
"Node", arm_obj
.fbx_uuid
)
733 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(mat_world_arm
))
734 # And all bones of armature!
737 bomat
= bo_obj
.fbx_object_matrix(scene_data
, rest
=True, global_space
=True)
738 mat_world_bones
[bo_obj
] = bomat
739 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
740 elem_data_single_int64(fbx_posenode
, b
"Node", bo_obj
.fbx_uuid
)
741 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(bomat
))
743 return mat_world_obj
, mat_world_bones
746 def fbx_data_mesh_shapes_elements(root
, me_obj
, me
, scene_data
, fbx_me_tmpl
, fbx_me_props
):
748 Write shape keys related data.
750 if me
not in scene_data
.data_deformers_shape
:
753 write_normals
= True # scene_data.settings.mesh_smooth_type in {'OFF'}
755 # First, write the geometry data itself (i.e. shapes).
756 _me_key
, shape_key
, shapes
= scene_data
.data_deformers_shape
[me
]
760 vertices
= me
.vertices
761 for shape
, (channel_key
, geom_key
, shape_verts_co
, shape_verts_idx
) in shapes
.items():
762 # Use vgroups as weights, if defined.
763 if shape
.vertex_group
and shape
.vertex_group
in me_obj
.bdata
.vertex_groups
:
764 shape_verts_weights
= np
.zeros(len(shape_verts_idx
), dtype
=np
.float64
)
765 # It's slightly faster to iterate and index the underlying memoryview objects
766 mv_shape_verts_weights
= shape_verts_weights
.data
767 mv_shape_verts_idx
= shape_verts_idx
.data
768 vg_idx
= me_obj
.bdata
.vertex_groups
[shape
.vertex_group
].index
769 for sk_idx
, v_idx
in enumerate(mv_shape_verts_idx
):
770 for vg
in vertices
[v_idx
].groups
:
771 if vg
.group
== vg_idx
:
772 mv_shape_verts_weights
[sk_idx
] = vg
.weight
774 shape_verts_weights
*= 100.0
776 shape_verts_weights
= np
.full(len(shape_verts_idx
), 100.0, dtype
=np
.float64
)
777 channels
.append((channel_key
, shape
, shape_verts_weights
))
779 geom
= elem_data_single_int64(root
, b
"Geometry", get_fbx_uuid_from_key(geom_key
))
780 geom
.add_string(fbx_name_class(shape
.name
.encode(), b
"Geometry"))
781 geom
.add_string(b
"Shape")
783 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Geometry")
784 props
= elem_properties(geom
)
785 elem_props_template_finalize(tmpl
, props
)
787 elem_data_single_int32(geom
, b
"Version", FBX_GEOMETRY_SHAPE_VERSION
)
789 elem_data_single_int32_array(geom
, b
"Indexes", shape_verts_idx
)
790 elem_data_single_float64_array(geom
, b
"Vertices", shape_verts_co
)
792 elem_data_single_float64_array(geom
, b
"Normals", np
.zeros(len(shape_verts_idx
) * 3, dtype
=np
.float64
))
794 # Yiha! BindPose for shapekeys too! Dodecasigh...
795 # XXX Not sure yet whether several bindposes on same mesh are allowed, or not... :/
796 fbx_data_bindpose_element(root
, me_obj
, me
, scene_data
)
798 # ...and now, the deformers stuff.
799 fbx_shape
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(shape_key
))
800 fbx_shape
.add_string(fbx_name_class(me
.name
.encode(), b
"Deformer"))
801 fbx_shape
.add_string(b
"BlendShape")
803 elem_data_single_int32(fbx_shape
, b
"Version", FBX_DEFORMER_SHAPE_VERSION
)
805 for channel_key
, shape
, shape_verts_weights
in channels
:
806 fbx_channel
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(channel_key
))
807 fbx_channel
.add_string(fbx_name_class(shape
.name
.encode(), b
"SubDeformer"))
808 fbx_channel
.add_string(b
"BlendShapeChannel")
810 elem_data_single_int32(fbx_channel
, b
"Version", FBX_DEFORMER_SHAPECHANNEL_VERSION
)
811 elem_data_single_float64(fbx_channel
, b
"DeformPercent", shape
.value
* 100.0) # Percents...
812 elem_data_single_float64_array(fbx_channel
, b
"FullWeights", shape_verts_weights
)
814 # *WHY* add this in linked mesh properties too? *cry*
815 # No idea whether it’s percent here too, or more usual factor (assume percentage for now) :/
816 elem_props_template_set(fbx_me_tmpl
, fbx_me_props
, "p_number", shape
.name
.encode(), shape
.value
* 100.0,
820 def fbx_data_mesh_elements(root
, me_obj
, scene_data
, done_meshes
):
822 Write the Mesh (Geometry) data block.
825 def _infinite_gen(val
):
829 me_key
, me
, _free
= scene_data
.data_meshes
[me_obj
]
831 # In case of multiple instances of same mesh, only write it once!
832 if me_key
in done_meshes
:
835 # No gscale/gmat here, all data are supposed to be in object space.
836 smooth_type
= scene_data
.settings
.mesh_smooth_type
837 write_normals
= True # smooth_type in {'OFF'}
839 do_bake_space_transform
= me_obj
.use_bake_space_transform(scene_data
)
841 # Vertices are in object space, but we are post-multiplying all transforms with the inverse of the
842 # global matrix, so we need to apply the global matrix to the vertices to get the correct result.
843 geom_mat_co
= scene_data
.settings
.global_matrix
if do_bake_space_transform
else None
844 # We need to apply the inverse transpose of the global matrix when transforming normals.
845 geom_mat_no
= Matrix(scene_data
.settings
.global_matrix_inv_transposed
) if do_bake_space_transform
else None
846 if geom_mat_no
is not None:
847 # Remove translation & scaling!
848 geom_mat_no
.translation
= Vector()
849 geom_mat_no
.normalize()
851 geom
= elem_data_single_int64(root
, b
"Geometry", get_fbx_uuid_from_key(me_key
))
852 geom
.add_string(fbx_name_class(me
.name
.encode(), b
"Geometry"))
853 geom
.add_string(b
"Mesh")
855 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Geometry")
856 props
= elem_properties(geom
)
859 if scene_data
.settings
.use_custom_props
:
860 fbx_data_element_custom_properties(props
, me
)
862 # Subdivision levels. Take them from the first found subsurf modifier from the
863 # first object that has the mesh. Write crease information if the object has
864 # and subsurf modifier.
866 if scene_data
.settings
.use_subsurf
:
868 for mod
in me_obj
.bdata
.modifiers
:
869 if not (mod
.show_render
or mod
.show_viewport
):
871 if mod
.type == 'SUBSURF' and mod
.subdivision_type
== 'CATMULL_CLARK':
875 elem_data_single_int32(geom
, b
"Smoothness", 2) # Display control mesh and smoothed
876 if last_subsurf
.boundary_smooth
== "PRESERVE_CORNERS":
877 elem_data_single_int32(geom
, b
"BoundaryRule", 1) # CreaseAll
879 elem_data_single_int32(geom
, b
"BoundaryRule", 2) # CreaseEdge
880 elem_data_single_int32(geom
, b
"PreviewDivisionLevels", last_subsurf
.levels
)
881 elem_data_single_int32(geom
, b
"RenderDivisionLevels", last_subsurf
.render_levels
)
883 elem_data_single_int32(geom
, b
"PreserveBorders", 0)
884 elem_data_single_int32(geom
, b
"PreserveHardEdges", 0)
885 elem_data_single_int32(geom
, b
"PropagateEdgeHardness", 0)
887 write_crease
= last_subsurf
.use_creases
889 elem_data_single_int32(geom
, b
"GeometryVersion", FBX_GEOMETRY_VERSION
)
892 co_bl_dtype
= np
.single
893 co_fbx_dtype
= np
.float64
894 t_co
= np
.empty(len(me
.vertices
) * 3, dtype
=co_bl_dtype
)
895 me
.vertices
.foreach_get("co", t_co
)
896 elem_data_single_float64_array(geom
, b
"Vertices", vcos_transformed(t_co
, geom_mat_co
, co_fbx_dtype
))
901 # We do loose edges as two-vertices faces, if enabled...
903 # Note we have to process Edges in the same time, as they are based on poly's loops...
905 # Total number of loops, including any extra added for loose edges.
906 loop_nbr
= len(me
.loops
)
908 # dtypes matching the C data. Matching the C datatype avoids iteration and casting of every element in foreach_get's
910 bl_vertex_index_dtype
= bl_edge_index_dtype
= bl_loop_index_dtype
= np
.uintc
912 # Start vertex indices of loops. May contain elements for loops added for the export of loose edges.
913 t_lvi
= np
.empty(len(me
.loops
), dtype
=bl_vertex_index_dtype
)
915 # Loop start indices of polygons. May contain elements for the polygons added for the export of loose edges.
916 t_ls
= np
.empty(len(me
.polygons
), dtype
=bl_loop_index_dtype
)
918 # Vertex indices of edges (unsorted, unlike Mesh.edge_keys), flattened into an array twice the length of the number
920 t_ev
= np
.empty(len(me
.edges
) * 2, dtype
=bl_vertex_index_dtype
)
921 # Each edge has two vertex indices, so it's useful to view the array as 2d where each element on the first axis is a
922 # pair of vertex indices
923 t_ev_pair_view
= t_ev
.view()
924 t_ev_pair_view
.shape
= (-1, 2)
926 # Edge indices of loops. May contain elements for loops added for the export of loose edges.
927 t_lei
= np
.empty(len(me
.loops
), dtype
=bl_edge_index_dtype
)
929 me
.loops
.foreach_get("vertex_index", t_lvi
)
930 me
.polygons
.foreach_get("loop_start", t_ls
)
931 me
.edges
.foreach_get("vertices", t_ev
)
932 me
.loops
.foreach_get("edge_index", t_lei
)
934 # Add "fake" faces for loose edges. Each "fake" face consists of two loops creating a new 2-sided polygon.
935 if scene_data
.settings
.use_mesh_edges
:
936 bl_edge_is_loose_dtype
= bool
937 # Get the mask of edges that are loose
938 loose_mask
= np
.empty(len(me
.edges
), dtype
=bl_edge_is_loose_dtype
)
939 me
.edges
.foreach_get('is_loose', loose_mask
)
941 indices_of_loose_edges
= np
.flatnonzero(loose_mask
)
942 # Since we add two loops per loose edge, repeat the indices so that there's one for each new loop
943 new_loop_edge_indices
= np
.repeat(indices_of_loose_edges
, 2)
945 # Get the loose edge vertex index pairs
946 t_le
= t_ev_pair_view
[loose_mask
]
948 # append will automatically flatten the pairs in t_le
949 t_lvi
= np
.append(t_lvi
, t_le
)
950 t_lei
= np
.append(t_lei
, new_loop_edge_indices
)
951 # Two loops are added per loose edge
952 loop_nbr
+= 2 * len(t_le
)
953 t_ls
= np
.append(t_ls
, np
.arange(len(me
.loops
), loop_nbr
, 2, dtype
=t_ls
.dtype
))
956 del indices_of_loose_edges
957 del new_loop_edge_indices
960 # Note: Edges are represented as a loop here: each edge uses a single index, which refers to the polygon array.
961 # The edge is made by the vertex indexed py this polygon's point and the next one on the same polygon.
962 # Advantage: Only one index per edge.
963 # Drawback: Only polygon's edges can be represented (that's why we have to add fake two-verts polygons
965 # We also have to store a mapping from real edges to their indices in this array, for edge-mapped data
966 # (like e.g. crease).
967 eli_fbx_dtype
= np
.int32
969 # Edge index of each unique edge-key, used to map per-edge data to unique edge-keys (t_pvi).
970 t_pvi_edge_indices
= np
.empty(0, dtype
=t_lei
.dtype
)
972 pvi_fbx_dtype
= np
.int32
973 if t_ls
.size
and t_lvi
.size
:
974 # Get unsorted edge keys by indexing the edge->vertex-indices array by the loop->edge-index array.
975 t_pvi_edge_keys
= t_ev_pair_view
[t_lei
]
977 # Sort each [edge_start_n, edge_end_n] pair to get edge keys. Heapsort seems to be the fastest for this specific
979 t_pvi_edge_keys
.sort(axis
=1, kind
='heapsort')
981 # Note that finding unique edge keys means that if there are multiple edges that share the same vertices (which
982 # shouldn't normally happen), only the first edge found in loops will be exported along with its per-edge data.
983 # To export separate edges that share the same vertices, fast_first_axis_unique can be replaced with np.unique
984 # with t_lei as the first argument, finding unique edges rather than unique edge keys.
986 # Since we want the unique values in their original order, the only part we care about is the indices of the
987 # first occurrence of the unique elements in t_pvi_edge_keys, so we can use our fast uniqueness helper function.
988 t_eli
= fast_first_axis_unique(t_pvi_edge_keys
, return_unique
=False, return_index
=True)
990 # To get the indices of the elements in t_pvi_edge_keys that produce unique values, but in the original order of
991 # t_pvi_edge_keys, t_eli must be sorted.
992 # Due to loops and their edge keys tending to have a partial ordering within meshes, sorting with kind='stable'
993 # with radix sort tends to be faster than the default of kind='quicksort' with introsort.
994 t_eli
.sort(kind
='stable')
996 # Edge index of each element in unique t_pvi_edge_keys, used to map per-edge data such as sharp and creases.
997 t_pvi_edge_indices
= t_lei
[t_eli
]
999 # We have to ^-1 last index of each loop.
1000 # Ensure t_pvi is the correct number of bits before inverting.
1001 # t_lvi may be used again later, so always create a copy to avoid modifying it in the next step.
1002 t_pvi
= t_lvi
.astype(pvi_fbx_dtype
)
1003 # The index of the end of each loop is one before the index of the start of the next loop.
1004 t_pvi
[t_ls
[1:] - 1] ^
= -1
1005 # The index of the end of the last loop will be the very last index.
1009 # Should be empty, but make sure it's the correct type.
1010 t_pvi
= np
.empty(0, dtype
=pvi_fbx_dtype
)
1011 t_eli
= np
.empty(0, dtype
=eli_fbx_dtype
)
1013 # And finally we can write data!
1014 t_pvi
= astype_view_signedness(t_pvi
, pvi_fbx_dtype
)
1015 t_eli
= astype_view_signedness(t_eli
, eli_fbx_dtype
)
1016 elem_data_single_int32_array(geom
, b
"PolygonVertexIndex", t_pvi
)
1017 elem_data_single_int32_array(geom
, b
"Edges", t_eli
)
1026 if smooth_type
in {'FACE', 'EDGE'}:
1027 ps_fbx_dtype
= np
.int32
1028 poly_use_smooth_dtype
= bool
1029 edge_use_sharp_dtype
= bool
1031 if smooth_type
== 'FACE':
1032 t_ps
= np
.empty(len(me
.polygons
), dtype
=poly_use_smooth_dtype
)
1033 me
.polygons
.foreach_get("use_smooth", t_ps
)
1037 if t_pvi_edge_indices
.size
:
1038 # Write Edge Smoothing.
1039 # Note edge is sharp also if it's used by more than two faces, or one of its faces is flat.
1040 mesh_poly_nbr
= len(me
.polygons
)
1041 mesh_edge_nbr
= len(me
.edges
)
1042 mesh_loop_nbr
= len(me
.loops
)
1043 # t_ls and t_lei may contain extra polygons or loops added for loose edges that are not present in the
1044 # mesh data, so create views that exclude the extra data added for loose edges.
1045 mesh_t_ls_view
= t_ls
[:mesh_poly_nbr
]
1046 mesh_t_lei_view
= t_lei
[:mesh_loop_nbr
]
1048 # - Get sharp edges from flat shaded faces
1049 # Get the 'use_smooth' attribute of all polygons.
1050 p_use_smooth_mask
= np
.empty(mesh_poly_nbr
, dtype
=poly_use_smooth_dtype
)
1051 me
.polygons
.foreach_get('use_smooth', p_use_smooth_mask
)
1052 # Invert to get all flat shaded polygons.
1053 p_flat_mask
= np
.invert(p_use_smooth_mask
, out
=p_use_smooth_mask
)
1054 # Convert flat shaded polygons to flat shaded loops by repeating each element by the number of sides of
1056 # Polygon sides can be calculated from the element-wise difference of loop starts appended by the number
1057 # of loops. Alternatively, polygon sides can be retrieved directly from the 'loop_total' attribute of
1058 # polygons, but since we already have t_ls, it tends to be quicker to calculate from t_ls when above
1059 # around 10_000 polygons.
1060 polygon_sides
= np
.diff(mesh_t_ls_view
, append
=mesh_loop_nbr
)
1061 p_flat_loop_mask
= np
.repeat(p_flat_mask
, polygon_sides
)
1062 # Convert flat shaded loops to flat shaded (sharp) edge indices.
1063 # Note that if an edge is in multiple loops that are part of flat shaded faces, its edge index will end
1064 # up in sharp_edge_indices_from_polygons multiple times.
1065 sharp_edge_indices_from_polygons
= mesh_t_lei_view
[p_flat_loop_mask
]
1067 # - Get sharp edges from edges marked as sharp
1068 e_use_sharp_mask
= np
.empty(mesh_edge_nbr
, dtype
=edge_use_sharp_dtype
)
1069 me
.edges
.foreach_get('use_edge_sharp', e_use_sharp_mask
)
1071 # - Get sharp edges from edges used by more than two loops (and therefore more than two faces)
1072 e_more_than_two_faces_mask
= np
.bincount(mesh_t_lei_view
, minlength
=mesh_edge_nbr
) > 2
1074 # - Combine with edges that are sharp because they're in more than two faces
1075 e_use_sharp_mask
= np
.logical_or(e_use_sharp_mask
, e_more_than_two_faces_mask
, out
=e_use_sharp_mask
)
1077 # - Combine with edges that are sharp because a polygon they're in has flat shading
1078 e_use_sharp_mask
[sharp_edge_indices_from_polygons
] = True
1080 # - Convert sharp edges to sharp edge keys (t_pvi)
1081 ek_use_sharp_mask
= e_use_sharp_mask
[t_pvi_edge_indices
]
1083 # - Sharp edges are indicated in FBX as zero (False), so invert
1084 t_ps
= np
.invert(ek_use_sharp_mask
, out
=ek_use_sharp_mask
)
1085 del ek_use_sharp_mask
1086 del e_use_sharp_mask
1087 del sharp_edge_indices_from_polygons
1088 del p_flat_loop_mask
1091 del p_use_smooth_mask
1095 t_ps
= np
.empty(0, dtype
=ps_fbx_dtype
)
1096 t_ps
= t_ps
.astype(ps_fbx_dtype
, copy
=False)
1097 lay_smooth
= elem_data_single_int32(geom
, b
"LayerElementSmoothing", 0)
1098 elem_data_single_int32(lay_smooth
, b
"Version", FBX_GEOMETRY_SMOOTHING_VERSION
)
1099 elem_data_single_string(lay_smooth
, b
"Name", b
"")
1100 elem_data_single_string(lay_smooth
, b
"MappingInformationType", _map
)
1101 elem_data_single_string(lay_smooth
, b
"ReferenceInformationType", b
"Direct")
1102 elem_data_single_int32_array(lay_smooth
, b
"Smoothing", t_ps
) # Sight, int32 for bool...
1107 # Edge crease for subdivision
1109 ec_fbx_dtype
= np
.float64
1110 if t_pvi_edge_indices
.size
:
1111 ec_bl_dtype
= np
.single
1112 t_ec_raw
= np
.empty(len(me
.edges
), dtype
=ec_bl_dtype
)
1113 me
.edges
.foreach_get('crease', t_ec_raw
)
1115 # Convert to t_pvi edge-keys.
1116 t_ec_ek_raw
= t_ec_raw
[t_pvi_edge_indices
]
1118 # Blender squares those values before sending them to OpenSubdiv, when other software don't,
1119 # so we need to compensate that to get similar results through FBX...
1120 # Use the precision of the fbx dtype for the calculation since it's usually higher precision.
1121 t_ec_ek_raw
= t_ec_ek_raw
.astype(ec_fbx_dtype
, copy
=False)
1122 t_ec
= np
.square(t_ec_ek_raw
, out
=t_ec_ek_raw
)
1126 t_ec
= np
.empty(0, dtype
=ec_fbx_dtype
)
1128 lay_crease
= elem_data_single_int32(geom
, b
"LayerElementEdgeCrease", 0)
1129 elem_data_single_int32(lay_crease
, b
"Version", FBX_GEOMETRY_CREASE_VERSION
)
1130 elem_data_single_string(lay_crease
, b
"Name", b
"")
1131 elem_data_single_string(lay_crease
, b
"MappingInformationType", b
"ByEdge")
1132 elem_data_single_string(lay_crease
, b
"ReferenceInformationType", b
"Direct")
1133 elem_data_single_float64_array(lay_crease
, b
"EdgeCrease", t_ec
)
1136 # And we are done with edges!
1137 del t_pvi_edge_indices
1142 # NOTE: this is not supported by importer currently.
1143 # XXX Official docs says normals should use IndexToDirect,
1144 # but this does not seem well supported by apps currently...
1145 me
.calc_normals_split()
1147 ln_bl_dtype
= np
.single
1148 ln_fbx_dtype
= np
.float64
1149 t_ln
= np
.empty(len(me
.loops
) * 3, dtype
=ln_bl_dtype
)
1150 me
.loops
.foreach_get("normal", t_ln
)
1151 t_ln
= nors_transformed(t_ln
, geom_mat_no
, ln_fbx_dtype
)
1153 lnidx_fbx_dtype
= np
.int32
1154 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementNormal", 0)
1155 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_NORMAL_VERSION
)
1156 elem_data_single_string(lay_nor
, b
"Name", b
"")
1157 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1158 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"IndexToDirect")
1160 # Tuple of unique sorted normals and then the index in the unique sorted normals of each normal in t_ln.
1161 # Since we don't care about how the normals are sorted, only that they're unique, we can use the fast unique
1163 t_ln
, t_lnidx
= fast_first_axis_unique(t_ln
.reshape(-1, 3), return_inverse
=True)
1165 # Convert to the type for fbx
1166 t_lnidx
= astype_view_signedness(t_lnidx
, lnidx_fbx_dtype
)
1168 elem_data_single_float64_array(lay_nor
, b
"Normals", t_ln
)
1169 # Normal weights, no idea what it is.
1170 # t_lnw = np.zeros(len(t_ln), dtype=np.float64)
1171 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_lnw)
1173 elem_data_single_int32_array(lay_nor
, b
"NormalsIndex", t_lnidx
)
1178 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementNormal", 0)
1179 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_NORMAL_VERSION
)
1180 elem_data_single_string(lay_nor
, b
"Name", b
"")
1181 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1182 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1183 elem_data_single_float64_array(lay_nor
, b
"Normals", t_ln
)
1184 # Normal weights, no idea what it is.
1185 # t_ln = np.zeros(len(me.loops), dtype=np.float64)
1186 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_ln)
1190 if scene_data
.settings
.use_tspace
:
1191 tspacenumber
= len(me
.uv_layers
)
1193 # We can only compute tspace on tessellated meshes, need to check that here...
1194 lt_bl_dtype
= np
.uintc
1195 t_lt
= np
.empty(len(me
.polygons
), dtype
=lt_bl_dtype
)
1196 me
.polygons
.foreach_get("loop_total", t_lt
)
1197 if (t_lt
> 4).any():
1199 scene_data
.settings
.report(
1201 tip_("Mesh '%s' has polygons with more than 4 vertices, "
1202 "cannot compute/export tangent space for it") % me
.name
)
1205 num_loops
= len(me
.loops
)
1206 t_ln
= np
.empty(num_loops
* 3, dtype
=ln_bl_dtype
)
1207 # t_lnw = np.zeros(len(me.loops), dtype=np.float64)
1208 uv_names
= [uvlayer
.name
for uvlayer
in me
.uv_layers
]
1209 # Annoying, `me.calc_tangent` errors in case there is no geometry...
1211 for name
in uv_names
:
1212 me
.calc_tangents(uvmap
=name
)
1213 for idx
, uvlayer
in enumerate(me
.uv_layers
):
1215 # Loop bitangents (aka binormals).
1216 # NOTE: this is not supported by importer currently.
1217 me
.loops
.foreach_get("bitangent", t_ln
)
1218 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementBinormal", idx
)
1219 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_BINORMAL_VERSION
)
1220 elem_data_single_string_unicode(lay_nor
, b
"Name", name
)
1221 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1222 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1223 elem_data_single_float64_array(lay_nor
, b
"Binormals",
1224 nors_transformed(t_ln
, geom_mat_no
, ln_fbx_dtype
))
1225 # Binormal weights, no idea what it is.
1226 # elem_data_single_float64_array(lay_nor, b"BinormalsW", t_lnw)
1229 # NOTE: this is not supported by importer currently.
1230 me
.loops
.foreach_get("tangent", t_ln
)
1231 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementTangent", idx
)
1232 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_TANGENT_VERSION
)
1233 elem_data_single_string_unicode(lay_nor
, b
"Name", name
)
1234 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1235 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1236 elem_data_single_float64_array(lay_nor
, b
"Tangents",
1237 nors_transformed(t_ln
, geom_mat_no
, ln_fbx_dtype
))
1238 # Tangent weights, no idea what it is.
1239 # elem_data_single_float64_array(lay_nor, b"TangentsW", t_lnw)
1245 me
.free_normals_split()
1247 # Write VertexColor Layers.
1248 colors_type
= scene_data
.settings
.colors_type
1249 vcolnumber
= 0 if colors_type
== 'NONE' else len(me
.color_attributes
)
1251 color_prop_name
= "color_srgb" if colors_type
== 'SRGB' else "color"
1252 # ByteColorAttribute color also gets returned by the API as single precision float
1253 bl_lc_dtype
= np
.single
1254 fbx_lc_dtype
= np
.float64
1255 fbx_lcidx_dtype
= np
.int32
1257 color_attributes
= me
.color_attributes
1258 if scene_data
.settings
.prioritize_active_color
:
1259 active_color
= me
.color_attributes
.active_color
1260 color_attributes
= sorted(color_attributes
, key
=lambda x
: x
== active_color
, reverse
=True)
1262 for colindex
, collayer
in enumerate(color_attributes
):
1263 is_point
= collayer
.domain
== "POINT"
1264 vcollen
= len(me
.vertices
if is_point
else me
.loops
)
1265 # Each rgba component is flattened in the array
1266 t_lc
= np
.empty(vcollen
* 4, dtype
=bl_lc_dtype
)
1267 collayer
.data
.foreach_get(color_prop_name
, t_lc
)
1268 lay_vcol
= elem_data_single_int32(geom
, b
"LayerElementColor", colindex
)
1269 elem_data_single_int32(lay_vcol
, b
"Version", FBX_GEOMETRY_VCOLOR_VERSION
)
1270 elem_data_single_string_unicode(lay_vcol
, b
"Name", collayer
.name
)
1271 elem_data_single_string(lay_vcol
, b
"MappingInformationType", b
"ByPolygonVertex")
1272 elem_data_single_string(lay_vcol
, b
"ReferenceInformationType", b
"IndexToDirect")
1274 # Use the fast uniqueness helper function since we don't care about sorting.
1275 t_lc
, col_indices
= fast_first_axis_unique(t_lc
.reshape(-1, 4), return_inverse
=True)
1278 # for "point" domain colors, we could directly emit them
1279 # with a "ByVertex" mapping type, but some software does not
1280 # properly understand that. So expand to full "ByPolygonVertex"
1282 # Ignore loops added for loose edges.
1283 col_indices
= col_indices
[t_lvi
[:len(me
.loops
)]]
1285 t_lc
= t_lc
.astype(fbx_lc_dtype
, copy
=False)
1286 col_indices
= astype_view_signedness(col_indices
, fbx_lcidx_dtype
)
1288 elem_data_single_float64_array(lay_vcol
, b
"Colors", t_lc
)
1289 elem_data_single_int32_array(lay_vcol
, b
"ColorIndex", col_indices
)
1295 # Note: LayerElementTexture is deprecated since FBX 2011 - luckily!
1296 # Textures are now only related to materials, in FBX!
1297 uvnumber
= len(me
.uv_layers
)
1299 luv_bl_dtype
= np
.single
1300 luv_fbx_dtype
= np
.float64
1301 lv_idx_fbx_dtype
= np
.int32
1303 t_luv
= np
.empty(len(me
.loops
) * 2, dtype
=luv_bl_dtype
)
1304 # Fast view for sort-based uniqueness of pairs.
1305 t_luv_fast_pair_view
= fast_first_axis_flat(t_luv
.reshape(-1, 2))
1306 # It must be a view of t_luv otherwise it won't update when t_luv is updated.
1307 assert(t_luv_fast_pair_view
.base
is t_luv
)
1309 # Looks like this mapping is also expected to convey UV islands (arg..... :((((( ).
1310 # So we need to generate unique triplets (uv, vertex_idx) here, not only just based on UV values.
1311 # Ignore loops added for loose edges.
1312 t_lvidx
= t_lvi
[:len(me
.loops
)]
1314 # If we were to create a combined array of (uv, vertex_idx) elements, we could find unique triplets by sorting
1315 # that array by first sorting by the vertex_idx column and then sorting by the uv column using a stable sorting
1317 # This is exactly what we'll do, but without creating the combined array, because only the uv elements are
1318 # included in the export and the vertex_idx column is the same for every uv layer.
1320 # Because the vertex_idx column is the same for every uv layer, the vertex_idx column can be sorted in advance.
1321 # argsort gets the indices that sort the array, which are needed to be able to sort the array of uv pairs in the
1322 # same way to create the indices that recreate the full uvs from the unique uvs.
1323 # Loops and vertices tend to naturally have a partial ordering, which makes sorting with kind='stable' (radix
1324 # sort) faster than the default of kind='quicksort' (introsort) in most cases.
1325 perm_vidx
= t_lvidx
.argsort(kind
='stable')
1327 # Mask and uv indices arrays will be modified and re-used by each uv layer.
1328 unique_mask
= np
.empty(len(me
.loops
), dtype
=np
.bool_
)
1329 unique_mask
[:1] = True
1330 uv_indices
= np
.empty(len(me
.loops
), dtype
=lv_idx_fbx_dtype
)
1332 for uvindex
, uvlayer
in enumerate(me
.uv_layers
):
1333 lay_uv
= elem_data_single_int32(geom
, b
"LayerElementUV", uvindex
)
1334 elem_data_single_int32(lay_uv
, b
"Version", FBX_GEOMETRY_UV_VERSION
)
1335 elem_data_single_string_unicode(lay_uv
, b
"Name", uvlayer
.name
)
1336 elem_data_single_string(lay_uv
, b
"MappingInformationType", b
"ByPolygonVertex")
1337 elem_data_single_string(lay_uv
, b
"ReferenceInformationType", b
"IndexToDirect")
1339 uvlayer
.data
.foreach_get("uv", t_luv
)
1341 # t_luv_fast_pair_view is a view in a dtype that compares elements by individual bytes, but float types have
1342 # separate byte representations of positive and negative zero. For uniqueness, these should be considered
1343 # the same, so replace all -0.0 with 0.0 in advance.
1344 t_luv
[t_luv
== -0.0] = 0.0
1346 # These steps to create unique_uv_pairs are the same as how np.unique would find unique values by sorting a
1347 # structured array where each element is a triplet of (uv, vertex_idx), except uv and vertex_idx are
1348 # separate arrays here and vertex_idx has already been sorted in advance.
1350 # Sort according to the vertex_idx column, using the precalculated indices that sort it.
1351 sorted_t_luv_fast
= t_luv_fast_pair_view
[perm_vidx
]
1353 # Get the indices that would sort the sorted uv pairs. Stable sorting must be used to maintain the sorting
1354 # of the vertex indices.
1355 perm_uv_pairs
= sorted_t_luv_fast
.argsort(kind
='stable')
1356 # Use the indices to sort both the uv pairs and the vertex_idx columns.
1357 perm_combined
= perm_vidx
[perm_uv_pairs
]
1358 sorted_vidx
= t_lvidx
[perm_combined
]
1359 sorted_t_luv_fast
= sorted_t_luv_fast
[perm_uv_pairs
]
1361 # Create a mask where either the uv pair doesn't equal the previous value in the array, or the vertex index
1362 # doesn't equal the previous value, these will be the unique uv-vidx triplets.
1363 # For an imaginary triplet array:
1366 # [(0.4, 0.2), 1] -> Unique because vertex index different from previous
1367 # [(0.4, 0.2), 2] -> Unique because vertex index different from previous
1368 # [(0.7, 0.6), 2] -> Unique because uv different from previous
1371 # Output the result into unique_mask.
1372 np
.logical_or(sorted_t_luv_fast
[1:] != sorted_t_luv_fast
[:-1], sorted_vidx
[1:] != sorted_vidx
[:-1],
1373 out
=unique_mask
[1:])
1375 # Get each uv pair marked as unique by the unique_mask and then view as the original dtype.
1376 unique_uvs
= sorted_t_luv_fast
[unique_mask
].view(luv_bl_dtype
)
1378 # NaN values are considered invalid and indicate a bug somewhere else in Blender or in an addon, we want
1379 # these bugs to be reported instead of hiding them by allowing the export to continue.
1380 if np
.isnan(unique_uvs
).any():
1381 raise RuntimeError("UV layer %s on %r has invalid UVs containing NaN values" % (uvlayer
.name
, me
))
1383 # Convert to the type needed for fbx
1384 unique_uvs
= unique_uvs
.astype(luv_fbx_dtype
, copy
=False)
1386 # Set the indices of pairs in unique_uvs that reconstruct the pairs in t_luv into uv_indices.
1387 # uv_indices will then be the same as an inverse array returned by np.unique with return_inverse=True.
1388 uv_indices
[perm_combined
] = np
.cumsum(unique_mask
, dtype
=uv_indices
.dtype
) - 1
1390 elem_data_single_float64_array(lay_uv
, b
"UV", unique_uvs
)
1391 elem_data_single_int32_array(lay_uv
, b
"UVIndex", uv_indices
)
1393 del sorted_t_luv_fast
1402 del t_luv_fast_pair_view
1406 me_fbxmaterials_idx
= scene_data
.mesh_material_indices
.get(me
)
1407 if me_fbxmaterials_idx
is not None:
1408 # We cannot use me.materials here, as this array is filled with None in case materials are linked to object...
1409 me_blmaterials
= me_obj
.materials
1410 if me_fbxmaterials_idx
and me_blmaterials
:
1411 lay_ma
= elem_data_single_int32(geom
, b
"LayerElementMaterial", 0)
1412 elem_data_single_int32(lay_ma
, b
"Version", FBX_GEOMETRY_MATERIAL_VERSION
)
1413 elem_data_single_string(lay_ma
, b
"Name", b
"")
1414 nbr_mats
= len(me_fbxmaterials_idx
)
1416 bl_pm_dtype
= np
.uintc
1417 fbx_pm_dtype
= np
.int32
1418 t_pm
= np
.empty(len(me
.polygons
), dtype
=bl_pm_dtype
)
1419 me
.polygons
.foreach_get("material_index", t_pm
)
1421 # We have to validate mat indices, and map them to FBX indices.
1422 # Note a mat might not be in me_fbxmaterials_idx (e.g. node mats are ignored).
1424 # The first valid material will be used for materials out of bounds of me_blmaterials or materials not
1425 # in me_fbxmaterials_idx.
1426 def_me_blmaterial_idx
, def_ma
= next(
1427 (i
, me_fbxmaterials_idx
[m
]) for i
, m
in enumerate(me_blmaterials
) if m
in me_fbxmaterials_idx
)
1429 # Set material indices that are out of bounds to the default material index
1430 mat_idx_limit
= len(me_blmaterials
)
1431 t_pm
[t_pm
>= mat_idx_limit
] = def_me_blmaterial_idx
1433 # Map to FBX indices. Materials not in me_fbxmaterials_idx will be set to the default material index.
1434 blmat_fbx_idx
= np
.fromiter((me_fbxmaterials_idx
.get(m
, def_ma
) for m
in me_blmaterials
),
1436 t_pm
= blmat_fbx_idx
[t_pm
]
1438 elem_data_single_string(lay_ma
, b
"MappingInformationType", b
"ByPolygon")
1439 # XXX Logically, should be "Direct" reference type, since we do not have any index array, and have one
1440 # value per polygon...
1441 # But looks like FBX expects it to be IndexToDirect here (maybe because materials are already
1442 # indices??? *sigh*).
1443 elem_data_single_string(lay_ma
, b
"ReferenceInformationType", b
"IndexToDirect")
1444 elem_data_single_int32_array(lay_ma
, b
"Materials", t_pm
)
1447 elem_data_single_string(lay_ma
, b
"MappingInformationType", b
"AllSame")
1448 elem_data_single_string(lay_ma
, b
"ReferenceInformationType", b
"IndexToDirect")
1449 elem_data_single_int32_array(lay_ma
, b
"Materials", [0])
1451 # And the "layer TOC"...
1453 layer
= elem_data_single_int32(geom
, b
"Layer", 0)
1454 elem_data_single_int32(layer
, b
"Version", FBX_GEOMETRY_LAYER_VERSION
)
1456 lay_nor
= elem_empty(layer
, b
"LayerElement")
1457 elem_data_single_string(lay_nor
, b
"Type", b
"LayerElementNormal")
1458 elem_data_single_int32(lay_nor
, b
"TypedIndex", 0)
1460 lay_binor
= elem_empty(layer
, b
"LayerElement")
1461 elem_data_single_string(lay_binor
, b
"Type", b
"LayerElementBinormal")
1462 elem_data_single_int32(lay_binor
, b
"TypedIndex", 0)
1463 lay_tan
= elem_empty(layer
, b
"LayerElement")
1464 elem_data_single_string(lay_tan
, b
"Type", b
"LayerElementTangent")
1465 elem_data_single_int32(lay_tan
, b
"TypedIndex", 0)
1466 if smooth_type
in {'FACE', 'EDGE'}:
1467 lay_smooth
= elem_empty(layer
, b
"LayerElement")
1468 elem_data_single_string(lay_smooth
, b
"Type", b
"LayerElementSmoothing")
1469 elem_data_single_int32(lay_smooth
, b
"TypedIndex", 0)
1471 lay_smooth
= elem_empty(layer
, b
"LayerElement")
1472 elem_data_single_string(lay_smooth
, b
"Type", b
"LayerElementEdgeCrease")
1473 elem_data_single_int32(lay_smooth
, b
"TypedIndex", 0)
1475 lay_vcol
= elem_empty(layer
, b
"LayerElement")
1476 elem_data_single_string(lay_vcol
, b
"Type", b
"LayerElementColor")
1477 elem_data_single_int32(lay_vcol
, b
"TypedIndex", 0)
1479 lay_uv
= elem_empty(layer
, b
"LayerElement")
1480 elem_data_single_string(lay_uv
, b
"Type", b
"LayerElementUV")
1481 elem_data_single_int32(lay_uv
, b
"TypedIndex", 0)
1482 if me_fbxmaterials_idx
is not None:
1483 lay_ma
= elem_empty(layer
, b
"LayerElement")
1484 elem_data_single_string(lay_ma
, b
"Type", b
"LayerElementMaterial")
1485 elem_data_single_int32(lay_ma
, b
"TypedIndex", 0)
1487 # Add other uv and/or vcol layers...
1488 for vcolidx
, uvidx
, tspaceidx
in zip_longest(range(1, vcolnumber
), range(1, uvnumber
), range(1, tspacenumber
),
1490 layer
= elem_data_single_int32(geom
, b
"Layer", max(vcolidx
, uvidx
))
1491 elem_data_single_int32(layer
, b
"Version", FBX_GEOMETRY_LAYER_VERSION
)
1493 lay_vcol
= elem_empty(layer
, b
"LayerElement")
1494 elem_data_single_string(lay_vcol
, b
"Type", b
"LayerElementColor")
1495 elem_data_single_int32(lay_vcol
, b
"TypedIndex", vcolidx
)
1497 lay_uv
= elem_empty(layer
, b
"LayerElement")
1498 elem_data_single_string(lay_uv
, b
"Type", b
"LayerElementUV")
1499 elem_data_single_int32(lay_uv
, b
"TypedIndex", uvidx
)
1501 lay_binor
= elem_empty(layer
, b
"LayerElement")
1502 elem_data_single_string(lay_binor
, b
"Type", b
"LayerElementBinormal")
1503 elem_data_single_int32(lay_binor
, b
"TypedIndex", tspaceidx
)
1504 lay_tan
= elem_empty(layer
, b
"LayerElement")
1505 elem_data_single_string(lay_tan
, b
"Type", b
"LayerElementTangent")
1506 elem_data_single_int32(lay_tan
, b
"TypedIndex", tspaceidx
)
1509 fbx_data_mesh_shapes_elements(root
, me_obj
, me
, scene_data
, tmpl
, props
)
1511 elem_props_template_finalize(tmpl
, props
)
1512 done_meshes
.add(me_key
)
1515 def fbx_data_material_elements(root
, ma
, scene_data
):
1517 Write the Material data block.
1520 ambient_color
= (0.0, 0.0, 0.0)
1521 if scene_data
.data_world
:
1522 ambient_color
= next(iter(scene_data
.data_world
.keys())).color
1524 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
1525 ma_key
, _objs
= scene_data
.data_materials
[ma
]
1528 fbx_ma
= elem_data_single_int64(root
, b
"Material", get_fbx_uuid_from_key(ma_key
))
1529 fbx_ma
.add_string(fbx_name_class(ma
.name
.encode(), b
"Material"))
1530 fbx_ma
.add_string(b
"")
1532 elem_data_single_int32(fbx_ma
, b
"Version", FBX_MATERIAL_VERSION
)
1533 # those are not yet properties, it seems...
1534 elem_data_single_string(fbx_ma
, b
"ShadingModel", ma_type
)
1535 elem_data_single_int32(fbx_ma
, b
"MultiLayer", 0) # Should be bool...
1537 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Material")
1538 props
= elem_properties(fbx_ma
)
1540 elem_props_template_set(tmpl
, props
, "p_string", b
"ShadingModel", ma_type
.decode())
1541 elem_props_template_set(tmpl
, props
, "p_color", b
"DiffuseColor", ma_wrap
.base_color
)
1542 # Not in Principled BSDF, so assuming always 1
1543 elem_props_template_set(tmpl
, props
, "p_number", b
"DiffuseFactor", 1.0)
1544 # Principled BSDF only has an emissive color, so we assume factor to be always 1.0.
1545 elem_props_template_set(tmpl
, props
, "p_color", b
"EmissiveColor", ma_wrap
.emission_color
)
1546 elem_props_template_set(tmpl
, props
, "p_number", b
"EmissiveFactor", ma_wrap
.emission_strength
)
1547 # Not in Principled BSDF, so assuming always 0
1548 elem_props_template_set(tmpl
, props
, "p_color", b
"AmbientColor", ambient_color
)
1549 elem_props_template_set(tmpl
, props
, "p_number", b
"AmbientFactor", 0.0)
1550 # Sweetness... Looks like we are not the only ones to not know exactly how FBX is supposed to work (see T59850).
1551 # According to one of its developers, Unity uses that formula to extract alpha value:
1553 # alpha = 1 - TransparencyFactor
1554 # if (alpha == 1 or alpha == 0):
1555 # alpha = 1 - TransparentColor.r
1557 # Until further info, let's assume this is correct way to do, hence the following code for TransparentColor.
1558 if ma_wrap
.alpha
< 1.0e-5 or ma_wrap
.alpha
> (1.0 - 1.0e-5):
1559 elem_props_template_set(tmpl
, props
, "p_color", b
"TransparentColor", (1.0 - ma_wrap
.alpha
,) * 3)
1561 elem_props_template_set(tmpl
, props
, "p_color", b
"TransparentColor", ma_wrap
.base_color
)
1562 elem_props_template_set(tmpl
, props
, "p_number", b
"TransparencyFactor", 1.0 - ma_wrap
.alpha
)
1563 elem_props_template_set(tmpl
, props
, "p_number", b
"Opacity", ma_wrap
.alpha
)
1564 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"NormalMap", (0.0, 0.0, 0.0))
1565 elem_props_template_set(tmpl
, props
, "p_double", b
"BumpFactor", ma_wrap
.normalmap_strength
)
1566 # Not sure about those...
1568 b"Bump": ((0.0, 0.0, 0.0), "p_vector_3d"),
1569 b"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb"),
1570 b"DisplacementFactor": (0.0, "p_double"),
1572 # TODO: use specular tint?
1573 elem_props_template_set(tmpl
, props
, "p_color", b
"SpecularColor", ma_wrap
.base_color
)
1574 elem_props_template_set(tmpl
, props
, "p_number", b
"SpecularFactor", ma_wrap
.specular
/ 2.0)
1575 # See Material template about those two!
1576 # XXX Totally empirical conversion, trying to adapt it
1577 # (from 0.0 - 100.0 FBX shininess range to 1.0 - 0.0 Principled BSDF range)...
1578 shininess
= (1.0 - ma_wrap
.roughness
) * 10
1579 shininess
*= shininess
1580 elem_props_template_set(tmpl
, props
, "p_number", b
"Shininess", shininess
)
1581 elem_props_template_set(tmpl
, props
, "p_number", b
"ShininessExponent", shininess
)
1582 elem_props_template_set(tmpl
, props
, "p_color", b
"ReflectionColor", ma_wrap
.base_color
)
1583 elem_props_template_set(tmpl
, props
, "p_number", b
"ReflectionFactor", ma_wrap
.metallic
)
1585 elem_props_template_finalize(tmpl
, props
)
1587 # Custom properties.
1588 if scene_data
.settings
.use_custom_props
:
1589 fbx_data_element_custom_properties(props
, ma
)
1592 def _gen_vid_path(img
, scene_data
):
1593 msetts
= scene_data
.settings
.media_settings
1594 fname_rel
= bpy_extras
.io_utils
.path_reference(img
.filepath
, msetts
.base_src
, msetts
.base_dst
, msetts
.path_mode
,
1595 msetts
.subdir
, msetts
.copy_set
, img
.library
)
1596 fname_abs
= os
.path
.normpath(os
.path
.abspath(os
.path
.join(msetts
.base_dst
, fname_rel
)))
1597 return fname_abs
, fname_rel
1600 def fbx_data_texture_file_elements(root
, blender_tex_key
, scene_data
):
1602 Write the (file) Texture data block.
1604 # XXX All this is very fuzzy to me currently...
1605 # Textures do not seem to use properties as much as they could.
1606 # For now assuming most logical and simple stuff.
1608 ma
, sock_name
= blender_tex_key
1609 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
1610 tex_key
, _fbx_prop
= scene_data
.data_textures
[blender_tex_key
]
1611 tex
= getattr(ma_wrap
, sock_name
)
1613 fname_abs
, fname_rel
= _gen_vid_path(img
, scene_data
)
1615 fbx_tex
= elem_data_single_int64(root
, b
"Texture", get_fbx_uuid_from_key(tex_key
))
1616 fbx_tex
.add_string(fbx_name_class(sock_name
.encode(), b
"Texture"))
1617 fbx_tex
.add_string(b
"")
1619 elem_data_single_string(fbx_tex
, b
"Type", b
"TextureVideoClip")
1620 elem_data_single_int32(fbx_tex
, b
"Version", FBX_TEXTURE_VERSION
)
1621 elem_data_single_string(fbx_tex
, b
"TextureName", fbx_name_class(sock_name
.encode(), b
"Texture"))
1622 elem_data_single_string(fbx_tex
, b
"Media", fbx_name_class(img
.name
.encode(), b
"Video"))
1623 elem_data_single_string_unicode(fbx_tex
, b
"FileName", fname_abs
)
1624 elem_data_single_string_unicode(fbx_tex
, b
"RelativeFilename", fname_rel
)
1626 alpha_source
= 0 # None
1627 if img
.alpha_mode
!= 'NONE':
1628 # ~ if tex.texture.use_calculate_alpha:
1629 # ~ alpha_source = 1 # RGBIntensity as alpha.
1631 # ~ alpha_source = 2 # Black, i.e. alpha channel.
1632 alpha_source
= 2 # Black, i.e. alpha channel.
1633 # BlendMode not useful for now, only affects layered textures afaics.
1636 if tex
.texcoords
== 'ORCO': # XXX Others?
1637 if tex
.projection
== 'FLAT':
1638 mapping
= 1 # Planar
1639 elif tex
.projection
== 'CUBE':
1641 elif tex
.projection
== 'TUBE':
1642 mapping
= 3 # Cylindrical
1643 elif tex
.projection
== 'SPHERE':
1644 mapping
= 2 # Spherical
1645 elif tex
.texcoords
== 'UV':
1647 # Yuck, UVs are linked by mere names it seems... :/
1648 # XXX TODO how to get that now???
1649 # uvset = tex.uv_layer
1650 wrap_mode
= 1 # Clamp
1651 if tex
.extension
== 'REPEAT':
1652 wrap_mode
= 0 # Repeat
1654 tmpl
= elem_props_template_init(scene_data
.templates
, b
"TextureFile")
1655 props
= elem_properties(fbx_tex
)
1656 elem_props_template_set(tmpl
, props
, "p_enum", b
"AlphaSource", alpha_source
)
1657 elem_props_template_set(tmpl
, props
, "p_bool", b
"PremultiplyAlpha",
1658 img
.alpha_mode
in {'STRAIGHT'}) # Or is it PREMUL?
1659 elem_props_template_set(tmpl
, props
, "p_enum", b
"CurrentMappingType", mapping
)
1660 if uvset
is not None:
1661 elem_props_template_set(tmpl
, props
, "p_string", b
"UVSet", uvset
)
1662 elem_props_template_set(tmpl
, props
, "p_enum", b
"WrapModeU", wrap_mode
)
1663 elem_props_template_set(tmpl
, props
, "p_enum", b
"WrapModeV", wrap_mode
)
1664 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Translation", tex
.translation
)
1665 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Rotation", (-r
for r
in tex
.rotation
))
1666 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
))
1667 # UseMaterial should always be ON imho.
1668 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseMaterial", True)
1669 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseMipMap", False)
1670 elem_props_template_finalize(tmpl
, props
)
1672 # No custom properties, since that's not a data-block anymore.
1675 def fbx_data_video_elements(root
, vid
, scene_data
):
1677 Write the actual image data block.
1679 msetts
= scene_data
.settings
.media_settings
1681 vid_key
, _texs
= scene_data
.data_videos
[vid
]
1682 fname_abs
, fname_rel
= _gen_vid_path(vid
, scene_data
)
1684 fbx_vid
= elem_data_single_int64(root
, b
"Video", get_fbx_uuid_from_key(vid_key
))
1685 fbx_vid
.add_string(fbx_name_class(vid
.name
.encode(), b
"Video"))
1686 fbx_vid
.add_string(b
"Clip")
1688 elem_data_single_string(fbx_vid
, b
"Type", b
"Clip")
1691 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Video")
1692 props
= elem_properties(fbx_vid
)
1693 elem_props_template_set(tmpl
, props
, "p_string_url", b
"Path", fname_abs
)
1694 elem_props_template_finalize(tmpl
, props
)
1696 elem_data_single_int32(fbx_vid
, b
"UseMipMap", 0)
1697 elem_data_single_string_unicode(fbx_vid
, b
"Filename", fname_abs
)
1698 elem_data_single_string_unicode(fbx_vid
, b
"RelativeFilename", fname_rel
)
1700 if scene_data
.settings
.media_settings
.embed_textures
:
1701 if vid
.packed_file
is not None:
1702 # We only ever embed a given file once!
1703 if fname_abs
not in msetts
.embedded_set
:
1704 elem_data_single_bytes(fbx_vid
, b
"Content", vid
.packed_file
.data
)
1705 msetts
.embedded_set
.add(fname_abs
)
1707 filepath
= bpy
.path
.abspath(vid
.filepath
)
1708 # We only ever embed a given file once!
1709 if filepath
not in msetts
.embedded_set
:
1711 with
open(filepath
, 'br') as f
:
1712 elem_data_single_bytes(fbx_vid
, b
"Content", f
.read())
1713 except Exception as e
:
1714 print("WARNING: embedding file {} failed ({})".format(filepath
, e
))
1715 elem_data_single_bytes(fbx_vid
, b
"Content", b
"")
1716 msetts
.embedded_set
.add(filepath
)
1717 # Looks like we'd rather not write any 'Content' element in this case (see T44442).
1718 # Sounds suspect, but let's try it!
1720 #~ elem_data_single_bytes(fbx_vid, b"Content", b"")
1723 def fbx_data_armature_elements(root
, arm_obj
, scene_data
):
1726 * Bones "data" (NodeAttribute::LimbNode, contains pretty much nothing!).
1727 * Deformers (i.e. Skin), bind between an armature and a mesh.
1728 ** SubDeformers (i.e. Cluster), one per bone/vgroup pair.
1730 Note armature itself has no data, it is a mere "Null" Model...
1732 mat_world_arm
= arm_obj
.fbx_object_matrix(scene_data
, global_space
=True)
1733 bones
= tuple(bo_obj
for bo_obj
in arm_obj
.bones
if bo_obj
in scene_data
.objects
)
1735 bone_radius_scale
= 33.0
1738 for bo_obj
in bones
:
1740 bo_data_key
= scene_data
.data_bones
[bo_obj
]
1741 fbx_bo
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(bo_data_key
))
1742 fbx_bo
.add_string(fbx_name_class(bo
.name
.encode(), b
"NodeAttribute"))
1743 fbx_bo
.add_string(b
"LimbNode")
1744 elem_data_single_string(fbx_bo
, b
"TypeFlags", b
"Skeleton")
1746 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Bone")
1747 props
= elem_properties(fbx_bo
)
1748 elem_props_template_set(tmpl
, props
, "p_double", b
"Size", bo
.head_radius
* bone_radius_scale
)
1749 elem_props_template_finalize(tmpl
, props
)
1751 # Custom properties.
1752 if scene_data
.settings
.use_custom_props
:
1753 fbx_data_element_custom_properties(props
, bo
)
1755 # Store Blender bone length - XXX Not much useful actually :/
1756 # (LimbLength can't be used because it is a scale factor 0-1 for the parent-child distance:
1757 # http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/cpp_ref/class_fbx_skeleton.html#a9bbe2a70f4ed82cd162620259e649f0f )
1758 # elem_props_set(props, "p_double", "BlenderBoneLength".encode(), (bo.tail_local - bo.head_local).length, custom=True)
1760 # Skin deformers and BindPoses.
1761 # Note: we might also use Deformers for our "parent to vertex" stuff???
1762 deformer
= scene_data
.data_deformers_skin
.get(arm_obj
, None)
1763 if deformer
is not None:
1764 for me
, (skin_key
, ob_obj
, clusters
) in deformer
.items():
1766 mat_world_obj
, mat_world_bones
= fbx_data_bindpose_element(root
, ob_obj
, me
, scene_data
,
1767 arm_obj
, mat_world_arm
, bones
)
1770 fbx_skin
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(skin_key
))
1771 fbx_skin
.add_string(fbx_name_class(arm_obj
.name
.encode(), b
"Deformer"))
1772 fbx_skin
.add_string(b
"Skin")
1774 elem_data_single_int32(fbx_skin
, b
"Version", FBX_DEFORMER_SKIN_VERSION
)
1775 elem_data_single_float64(fbx_skin
, b
"Link_DeformAcuracy", 50.0) # Only vague idea what it is...
1777 # Pre-process vertex weights (also to check vertices assigned to more than four bones).
1779 bo_vg_idx
= {bo_obj
.bdata
.name
: ob
.vertex_groups
[bo_obj
.bdata
.name
].index
1780 for bo_obj
in clusters
.keys() if bo_obj
.bdata
.name
in ob
.vertex_groups
}
1781 valid_idxs
= set(bo_vg_idx
.values())
1782 vgroups
= {vg
.index
: {} for vg
in ob
.vertex_groups
}
1783 verts_vgroups
= (sorted(((vg
.group
, vg
.weight
) for vg
in v
.groups
if vg
.weight
and vg
.group
in valid_idxs
),
1784 key
=lambda e
: e
[1], reverse
=True)
1785 for v
in me
.vertices
)
1786 for idx
, vgs
in enumerate(verts_vgroups
):
1787 for vg_idx
, w
in vgs
:
1788 vgroups
[vg_idx
][idx
] = w
1790 for bo_obj
, clstr_key
in clusters
.items():
1792 # Find which vertices are affected by this bone/vgroup pair, and matching weights.
1793 # Note we still write a cluster for bones not affecting the mesh, to get 'rest pose' data
1794 # (the TransformBlah matrices).
1795 vg_idx
= bo_vg_idx
.get(bo
.name
, None)
1796 indices
, weights
= ((), ()) if vg_idx
is None or not vgroups
[vg_idx
] else zip(*vgroups
[vg_idx
].items())
1798 # Create the cluster.
1799 fbx_clstr
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(clstr_key
))
1800 fbx_clstr
.add_string(fbx_name_class(bo
.name
.encode(), b
"SubDeformer"))
1801 fbx_clstr
.add_string(b
"Cluster")
1803 elem_data_single_int32(fbx_clstr
, b
"Version", FBX_DEFORMER_CLUSTER_VERSION
)
1804 # No idea what that user data might be...
1805 fbx_userdata
= elem_data_single_string(fbx_clstr
, b
"UserData", b
"")
1806 fbx_userdata
.add_string(b
"")
1808 elem_data_single_int32_array(fbx_clstr
, b
"Indexes", indices
)
1809 elem_data_single_float64_array(fbx_clstr
, b
"Weights", weights
)
1810 # Transform, TransformLink and TransformAssociateModel matrices...
1811 # They seem to be doublons of BindPose ones??? Have armature (associatemodel) in addition, though.
1812 # WARNING! Even though official FBX API presents Transform in global space,
1813 # **it is stored in bone space in FBX data!** See:
1814 # http://area.autodesk.com/forum/autodesk-fbx/fbx-sdk/why-the-values-return-
1815 # by-fbxcluster-gettransformmatrix-x-not-same-with-the-value-in-ascii-fbx-file/
1816 elem_data_single_float64_array(fbx_clstr
, b
"Transform",
1817 matrix4_to_array(mat_world_bones
[bo_obj
].inverted_safe() @ mat_world_obj
))
1818 elem_data_single_float64_array(fbx_clstr
, b
"TransformLink", matrix4_to_array(mat_world_bones
[bo_obj
]))
1819 elem_data_single_float64_array(fbx_clstr
, b
"TransformAssociateModel", matrix4_to_array(mat_world_arm
))
1822 def fbx_data_leaf_bone_elements(root
, scene_data
):
1823 # Write a dummy leaf bone that is used by applications to show the length of the last bone in a chain
1824 for (node_name
, _par_uuid
, node_uuid
, attr_uuid
, matrix
, hide
, size
) in scene_data
.data_leaf_bones
:
1826 fbx_bo
= elem_data_single_int64(root
, b
"NodeAttribute", attr_uuid
)
1827 fbx_bo
.add_string(fbx_name_class(node_name
.encode(), b
"NodeAttribute"))
1828 fbx_bo
.add_string(b
"LimbNode")
1829 elem_data_single_string(fbx_bo
, b
"TypeFlags", b
"Skeleton")
1831 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Bone")
1832 props
= elem_properties(fbx_bo
)
1833 elem_props_template_set(tmpl
, props
, "p_double", b
"Size", size
)
1834 elem_props_template_finalize(tmpl
, props
)
1837 model
= elem_data_single_int64(root
, b
"Model", node_uuid
)
1838 model
.add_string(fbx_name_class(node_name
.encode(), b
"Model"))
1839 model
.add_string(b
"LimbNode")
1841 elem_data_single_int32(model
, b
"Version", FBX_MODELS_VERSION
)
1843 # Object transform info.
1844 loc
, rot
, scale
= matrix
.decompose()
1845 rot
= rot
.to_euler('XYZ')
1846 rot
= tuple(convert_rad_to_deg_iter(rot
))
1848 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Model")
1849 # For now add only loc/rot/scale...
1850 props
= elem_properties(model
)
1851 # Generated leaf bones are obviously never animated!
1852 elem_props_template_set(tmpl
, props
, "p_lcl_translation", b
"Lcl Translation", loc
)
1853 elem_props_template_set(tmpl
, props
, "p_lcl_rotation", b
"Lcl Rotation", rot
)
1854 elem_props_template_set(tmpl
, props
, "p_lcl_scaling", b
"Lcl Scaling", scale
)
1855 elem_props_template_set(tmpl
, props
, "p_visibility", b
"Visibility", float(not hide
))
1857 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1858 # invalid -1 value...
1859 elem_props_template_set(tmpl
, props
, "p_integer", b
"DefaultAttributeIndex", 0)
1861 elem_props_template_set(tmpl
, props
, "p_enum", b
"InheritType", 1) # RSrs
1863 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1865 elem_data_single_int32(model
, b
"MultiLayer", 0)
1866 elem_data_single_int32(model
, b
"MultiTake", 0)
1867 elem_data_single_bool(model
, b
"Shading", True)
1868 elem_data_single_string(model
, b
"Culling", b
"CullingOff")
1870 elem_props_template_finalize(tmpl
, props
)
1873 def fbx_data_object_elements(root
, ob_obj
, scene_data
):
1875 Write the Object (Model) data blocks.
1876 Note this "Model" can also be bone or dupli!
1878 obj_type
= b
"Null" # default, sort of empty...
1880 obj_type
= b
"LimbNode"
1881 elif (ob_obj
.type == 'ARMATURE'):
1882 if scene_data
.settings
.armature_nodetype
== 'ROOT':
1884 elif scene_data
.settings
.armature_nodetype
== 'LIMBNODE':
1885 obj_type
= b
"LimbNode"
1886 else: # Default, preferred option...
1888 elif (ob_obj
.type in BLENDER_OBJECT_TYPES_MESHLIKE
):
1890 elif (ob_obj
.type == 'LIGHT'):
1892 elif (ob_obj
.type == 'CAMERA'):
1893 obj_type
= b
"Camera"
1894 model
= elem_data_single_int64(root
, b
"Model", ob_obj
.fbx_uuid
)
1895 model
.add_string(fbx_name_class(ob_obj
.name
.encode(), b
"Model"))
1896 model
.add_string(obj_type
)
1898 elem_data_single_int32(model
, b
"Version", FBX_MODELS_VERSION
)
1900 # Object transform info.
1901 loc
, rot
, scale
, matrix
, matrix_rot
= ob_obj
.fbx_object_tx(scene_data
)
1902 rot
= tuple(convert_rad_to_deg_iter(rot
))
1904 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Model")
1905 # For now add only loc/rot/scale...
1906 props
= elem_properties(model
)
1907 elem_props_template_set(tmpl
, props
, "p_lcl_translation", b
"Lcl Translation", loc
,
1908 animatable
=True, animated
=((ob_obj
.key
, "Lcl Translation") in scene_data
.animated
))
1909 elem_props_template_set(tmpl
, props
, "p_lcl_rotation", b
"Lcl Rotation", rot
,
1910 animatable
=True, animated
=((ob_obj
.key
, "Lcl Rotation") in scene_data
.animated
))
1911 elem_props_template_set(tmpl
, props
, "p_lcl_scaling", b
"Lcl Scaling", scale
,
1912 animatable
=True, animated
=((ob_obj
.key
, "Lcl Scaling") in scene_data
.animated
))
1913 elem_props_template_set(tmpl
, props
, "p_visibility", b
"Visibility", float(not ob_obj
.hide
))
1915 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1916 # invalid -1 value...
1917 elem_props_template_set(tmpl
, props
, "p_integer", b
"DefaultAttributeIndex", 0)
1919 elem_props_template_set(tmpl
, props
, "p_enum", b
"InheritType", 1) # RSrs
1921 # Custom properties.
1922 if scene_data
.settings
.use_custom_props
:
1923 # Here we want customprops from the 'pose' bone, not the 'edit' bone...
1924 bdata
= ob_obj
.bdata_pose_bone
if ob_obj
.is_bone
else ob_obj
.bdata
1925 fbx_data_element_custom_properties(props
, bdata
)
1927 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1929 elem_data_single_int32(model
, b
"MultiLayer", 0)
1930 elem_data_single_int32(model
, b
"MultiTake", 0)
1931 elem_data_single_bool(model
, b
"Shading", True)
1932 elem_data_single_string(model
, b
"Culling", b
"CullingOff")
1934 if obj_type
== b
"Camera":
1935 # Why, oh why are FBX cameras such a mess???
1936 # And WHY add camera data HERE??? Not even sure this is needed...
1937 render
= scene_data
.scene
.render
1938 width
= render
.resolution_x
* 1.0
1939 height
= render
.resolution_y
* 1.0
1940 elem_props_template_set(tmpl
, props
, "p_enum", b
"ResolutionMode", 0) # Don't know what it means
1941 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectW", width
)
1942 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectH", height
)
1943 elem_props_template_set(tmpl
, props
, "p_bool", b
"ViewFrustum", True)
1944 elem_props_template_set(tmpl
, props
, "p_enum", b
"BackgroundMode", 0) # Don't know what it means
1945 elem_props_template_set(tmpl
, props
, "p_bool", b
"ForegroundTransparent", True)
1947 elem_props_template_finalize(tmpl
, props
)
1950 def fbx_data_animation_elements(root
, scene_data
):
1952 Write animation data.
1954 animations
= scene_data
.animations
1957 scene
= scene_data
.scene
1959 fps
= scene
.render
.fps
/ scene
.render
.fps_base
1961 def keys_to_ktimes(keys
):
1962 return (int(v
) for v
in convert_sec_to_ktime_iter((f
/ fps
for f
, _v
in keys
)))
1965 for astack_key
, alayers
, alayer_key
, name
, f_start
, f_end
in animations
:
1966 astack
= elem_data_single_int64(root
, b
"AnimationStack", get_fbx_uuid_from_key(astack_key
))
1967 astack
.add_string(fbx_name_class(name
, b
"AnimStack"))
1968 astack
.add_string(b
"")
1970 astack_tmpl
= elem_props_template_init(scene_data
.templates
, b
"AnimationStack")
1971 astack_props
= elem_properties(astack
)
1972 r
= scene_data
.scene
.render
1973 fps
= r
.fps
/ r
.fps_base
1974 start
= int(convert_sec_to_ktime(f_start
/ fps
))
1975 end
= int(convert_sec_to_ktime(f_end
/ fps
))
1976 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"LocalStart", start
)
1977 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"LocalStop", end
)
1978 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"ReferenceStart", start
)
1979 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"ReferenceStop", end
)
1980 elem_props_template_finalize(astack_tmpl
, astack_props
)
1982 # For now, only one layer for all animations.
1983 alayer
= elem_data_single_int64(root
, b
"AnimationLayer", get_fbx_uuid_from_key(alayer_key
))
1984 alayer
.add_string(fbx_name_class(name
, b
"AnimLayer"))
1985 alayer
.add_string(b
"")
1987 for ob_obj
, (alayer_key
, acurvenodes
) in alayers
.items():
1989 # alayer = elem_data_single_int64(root, b"AnimationLayer", get_fbx_uuid_from_key(alayer_key))
1990 # alayer.add_string(fbx_name_class(ob_obj.name.encode(), b"AnimLayer"))
1991 # alayer.add_string(b"")
1993 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
1994 # Animation curve node.
1995 acurvenode
= elem_data_single_int64(root
, b
"AnimationCurveNode", get_fbx_uuid_from_key(acurvenode_key
))
1996 acurvenode
.add_string(fbx_name_class(acurvenode_name
.encode(), b
"AnimCurveNode"))
1997 acurvenode
.add_string(b
"")
1999 acn_tmpl
= elem_props_template_init(scene_data
.templates
, b
"AnimationCurveNode")
2000 acn_props
= elem_properties(acurvenode
)
2002 for fbx_item
, (acurve_key
, def_value
, keys
, _acurve_valid
) in acurves
.items():
2003 elem_props_template_set(acn_tmpl
, acn_props
, "p_number", fbx_item
.encode(),
2004 def_value
, animatable
=True)
2006 # Only create Animation curve if needed!
2008 acurve
= elem_data_single_int64(root
, b
"AnimationCurve", get_fbx_uuid_from_key(acurve_key
))
2009 acurve
.add_string(fbx_name_class(b
"", b
"AnimCurve"))
2010 acurve
.add_string(b
"")
2013 nbr_keys
= len(keys
)
2016 1 << 2 |
# interpolation mode, 1 = constant, 2 = linear, 3 = cubic.
2017 1 << 8 |
# tangent mode, 8 = auto, 9 = TCB, 10 = user, 11 = generic break,
2018 1 << 13 |
# tangent mode, 12 = generic clamp, 13 = generic time independent,
2019 1 << 14 |
# tangent mode, 13 + 14 = generic clamp progressive.
2022 # Maybe values controlling TCB & co???
2023 keyattr_datafloat
= (0.0, 0.0, 9.419963346924634e-30, 0.0)
2025 # And now, the *real* data!
2026 elem_data_single_float64(acurve
, b
"Default", def_value
)
2027 elem_data_single_int32(acurve
, b
"KeyVer", FBX_ANIM_KEY_VERSION
)
2028 elem_data_single_int64_array(acurve
, b
"KeyTime", keys_to_ktimes(keys
))
2029 elem_data_single_float32_array(acurve
, b
"KeyValueFloat", (v
for _f
, v
in keys
))
2030 elem_data_single_int32_array(acurve
, b
"KeyAttrFlags", keyattr_flags
)
2031 elem_data_single_float32_array(acurve
, b
"KeyAttrDataFloat", keyattr_datafloat
)
2032 elem_data_single_int32_array(acurve
, b
"KeyAttrRefCount", (nbr_keys
,))
2034 elem_props_template_finalize(acn_tmpl
, acn_props
)
2037 # ##### Top-level FBX data container. #####
2039 # Mapping Blender -> FBX (principled_socket_name, fbx_name).
2040 PRINCIPLED_TEXTURE_SOCKETS_TO_FBX
= (
2041 # ("diffuse", "diffuse", b"DiffuseFactor"),
2042 ("base_color_texture", b
"DiffuseColor"),
2043 ("alpha_texture", b
"TransparencyFactor"), # Will be inverted in fact, not much we can do really...
2044 # ("base_color_texture", b"TransparentColor"), # Uses diffuse color in Blender!
2045 ("emission_strength_texture", b
"EmissiveFactor"),
2046 ("emission_color_texture", b
"EmissiveColor"),
2047 # ("ambient", "ambient", b"AmbientFactor"),
2048 # ("", "", b"AmbientColor"), # World stuff in Blender, for now ignore...
2049 ("normalmap_texture", b
"NormalMap"),
2050 # Note: unsure about those... :/
2051 # ("", "", b"Bump"),
2052 # ("", "", b"BumpFactor"),
2053 # ("", "", b"DisplacementColor"),
2054 # ("", "", b"DisplacementFactor"),
2055 ("specular_texture", b
"SpecularFactor"),
2056 # ("base_color", b"SpecularColor"), # TODO: use tint?
2057 # See Material template about those two!
2058 ("roughness_texture", b
"Shininess"),
2059 ("roughness_texture", b
"ShininessExponent"),
2060 # ("mirror", "mirror", b"ReflectionColor"),
2061 ("metallic_texture", b
"ReflectionFactor"),
2065 def fbx_skeleton_from_armature(scene
, settings
, arm_obj
, objects
, data_meshes
,
2066 data_bones
, data_deformers_skin
, data_empties
, arm_parents
):
2068 Create skeleton from armature/bones (NodeAttribute/LimbNode and Model/LimbNode), and for each deformed mesh,
2069 create Pose/BindPose(with sub PoseNode) and Deformer/Skin(with Deformer/SubDeformer/Cluster).
2070 Also supports "parent to bone" (simple parent to Model/LimbNode).
2071 arm_parents is a set of tuples (armature, object) for all successful armature bindings.
2073 # We need some data for our armature 'object' too!!!
2074 data_empties
[arm_obj
] = get_blender_empty_key(arm_obj
.bdata
)
2076 arm_data
= arm_obj
.bdata
.data
2078 for bo
in arm_obj
.bones
:
2079 if settings
.use_armature_deform_only
:
2080 if bo
.bdata
.use_deform
:
2083 while bo_par
.is_bone
:
2084 bones
[bo_par
] = True
2085 bo_par
= bo_par
.parent
2086 elif bo
not in bones
: # Do not override if already set in the loop above!
2091 bones
= {bo
: None for bo
, use
in bones
.items() if use
}
2096 data_bones
.update((bo
, get_blender_bone_key(arm_obj
.bdata
, bo
.bdata
)) for bo
in bones
)
2098 for ob_obj
in objects
:
2099 if not ob_obj
.is_deformed_by_armature(arm_obj
):
2102 # Always handled by an Armature modifier...
2104 for mod
in ob_obj
.bdata
.modifiers
:
2105 if mod
.type not in {'ARMATURE'} or not mod
.object:
2107 # We only support vertex groups binding method, not bone envelopes one!
2108 if mod
.object == arm_obj
.bdata
and mod
.use_vertex_groups
:
2115 # Now we have a mesh using this armature.
2116 # Note: bindpose have no relations at all (no connections), so no need for any preprocess for them.
2117 # Create skin & clusters relations (note skins are connected to geometry, *not* model!).
2118 _key
, me
, _free
= data_meshes
[ob_obj
]
2119 clusters
= {bo
: get_blender_bone_cluster_key(arm_obj
.bdata
, me
, bo
.bdata
) for bo
in bones
}
2120 data_deformers_skin
.setdefault(arm_obj
, {})[me
] = (get_blender_armature_skin_key(arm_obj
.bdata
, me
),
2123 # We don't want a regular parent relationship for those in FBX...
2124 arm_parents
.add((arm_obj
, ob_obj
))
2125 # Needed to handle matrices/spaces (since we do not parent them to 'armature' in FBX :/ ).
2126 ob_obj
.parented_to_armature
= True
2128 objects
.update(bones
)
2131 def fbx_generate_leaf_bones(settings
, data_bones
):
2132 # find which bons have no children
2133 child_count
= {bo
: 0 for bo
in data_bones
.keys()}
2134 for bo
in data_bones
.keys():
2135 if bo
.parent
and bo
.parent
.is_bone
:
2136 child_count
[bo
.parent
] += 1
2138 bone_radius_scale
= settings
.global_scale
* 33.0
2140 # generate bone data
2141 leaf_parents
= [bo
for bo
, count
in child_count
.items() if count
== 0]
2143 for parent
in leaf_parents
:
2144 node_name
= parent
.name
+ "_end"
2145 parent_uuid
= parent
.fbx_uuid
2146 parent_key
= parent
.key
2147 node_uuid
= get_fbx_uuid_from_key(parent_key
+ "_end_node")
2148 attr_uuid
= get_fbx_uuid_from_key(parent_key
+ "_end_nodeattr")
2151 size
= parent
.bdata
.head_radius
* bone_radius_scale
2152 bone_length
= (parent
.bdata
.tail_local
- parent
.bdata
.head_local
).length
2153 matrix
= Matrix
.Translation((0, bone_length
, 0))
2154 if settings
.bone_correction_matrix_inv
:
2155 matrix
= settings
.bone_correction_matrix_inv
@ matrix
2156 if settings
.bone_correction_matrix
:
2157 matrix
= matrix
@ settings
.bone_correction_matrix
2158 leaf_bones
.append((node_name
, parent_uuid
, node_uuid
, attr_uuid
, matrix
, hide
, size
))
2163 def fbx_animations_do(scene_data
, ref_id
, f_start
, f_end
, start_zero
, objects
=None, force_keep
=False):
2165 Generate animation data (a single AnimStack) from objects, for a given frame range.
2167 bake_step
= scene_data
.settings
.bake_anim_step
2168 simplify_fac
= scene_data
.settings
.bake_anim_simplify_factor
2169 scene
= scene_data
.scene
2170 depsgraph
= scene_data
.depsgraph
2171 force_keying
= scene_data
.settings
.bake_anim_use_all_bones
2172 force_sek
= scene_data
.settings
.bake_anim_force_startend_keying
2173 gscale
= scene_data
.settings
.global_scale
2175 if objects
is not None:
2176 # Add bones and duplis!
2177 for ob_obj
in tuple(objects
):
2178 if not ob_obj
.is_object
:
2180 if ob_obj
.type == 'ARMATURE':
2181 objects |
= {bo_obj
for bo_obj
in ob_obj
.bones
if bo_obj
in scene_data
.objects
}
2182 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
2183 if dp_obj
in scene_data
.objects
:
2186 objects
= scene_data
.objects
2188 back_currframe
= scene
.frame_current
2192 for ob_obj
in objects
:
2193 if ob_obj
.parented_to_armature
:
2195 ACNW
= AnimationCurveNodeWrapper
2196 loc
, rot
, scale
, _m
, _mr
= ob_obj
.fbx_object_tx(scene_data
)
2197 rot_deg
= tuple(convert_rad_to_deg_iter(rot
))
2198 force_key
= (simplify_fac
== 0.0) or (ob_obj
.is_bone
and force_keying
)
2199 animdata_ob
[ob_obj
] = (ACNW(ob_obj
.key
, 'LCL_TRANSLATION', force_key
, force_sek
, loc
),
2200 ACNW(ob_obj
.key
, 'LCL_ROTATION', force_key
, force_sek
, rot_deg
),
2201 ACNW(ob_obj
.key
, 'LCL_SCALING', force_key
, force_sek
, scale
))
2202 p_rots
[ob_obj
] = rot
2204 force_key
= (simplify_fac
== 0.0)
2205 animdata_shapes
= {}
2207 for me
, (me_key
, _shapes_key
, shapes
) in scene_data
.data_deformers_shape
.items():
2208 # Ignore absolute shape keys for now!
2209 if not me
.shape_keys
.use_relative
:
2211 for shape
, (channel_key
, geom_key
, _shape_verts_co
, _shape_verts_idx
) in shapes
.items():
2212 acnode
= AnimationCurveNodeWrapper(channel_key
, 'SHAPE_KEY', force_key
, force_sek
, (0.0,))
2213 # Sooooo happy to have to twist again like a mad snake... Yes, we need to write those curves twice. :/
2214 acnode
.add_group(me_key
, shape
.name
, shape
.name
, (shape
.name
,))
2215 animdata_shapes
[channel_key
] = (acnode
, me
, shape
)
2217 animdata_cameras
= {}
2218 for cam_obj
, cam_key
in scene_data
.data_cameras
.items():
2219 cam
= cam_obj
.bdata
.data
2220 acnode_lens
= AnimationCurveNodeWrapper(cam_key
, 'CAMERA_FOCAL', force_key
, force_sek
, (cam
.lens
,))
2221 acnode_focus_distance
= AnimationCurveNodeWrapper(cam_key
, 'CAMERA_FOCUS_DISTANCE', force_key
,
2222 force_sek
, (cam
.dof
.focus_distance
,))
2223 animdata_cameras
[cam_key
] = (acnode_lens
, acnode_focus_distance
, cam
)
2226 while currframe
<= f_end
:
2227 real_currframe
= currframe
- f_start
if start_zero
else currframe
2228 scene
.frame_set(int(currframe
), subframe
=currframe
- int(currframe
))
2230 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
2231 pass # Merely updating dupli matrix of ObjectWrapper...
2232 for ob_obj
, (anim_loc
, anim_rot
, anim_scale
) in animdata_ob
.items():
2233 # We compute baked loc/rot/scale for all objects (rot being euler-compat with previous value!).
2234 p_rot
= p_rots
.get(ob_obj
, None)
2235 loc
, rot
, scale
, _m
, _mr
= ob_obj
.fbx_object_tx(scene_data
, rot_euler_compat
=p_rot
)
2236 p_rots
[ob_obj
] = rot
2237 anim_loc
.add_keyframe(real_currframe
, loc
)
2238 anim_rot
.add_keyframe(real_currframe
, tuple(convert_rad_to_deg_iter(rot
)))
2239 anim_scale
.add_keyframe(real_currframe
, scale
)
2240 for anim_shape
, me
, shape
in animdata_shapes
.values():
2241 anim_shape
.add_keyframe(real_currframe
, (shape
.value
* 100.0,))
2242 for anim_camera_lens
, anim_camera_focus_distance
, camera
in animdata_cameras
.values():
2243 anim_camera_lens
.add_keyframe(real_currframe
, (camera
.lens
,))
2244 anim_camera_focus_distance
.add_keyframe(real_currframe
, (camera
.dof
.focus_distance
* 1000 * gscale
,))
2245 currframe
+= bake_step
2247 scene
.frame_set(back_currframe
, subframe
=0.0)
2251 # And now, produce final data (usable by FBX export code)
2252 # Objects-like loc/rot/scale...
2253 for ob_obj
, anims
in animdata_ob
.items():
2255 anim
.simplify(simplify_fac
, bake_step
, force_keep
)
2258 for obj_key
, group_key
, group
, fbx_group
, fbx_gname
in anim
.get_final_data(scene
, ref_id
, force_keep
):
2259 anim_data
= animations
.setdefault(obj_key
, ("dummy_unused_key", {}))
2260 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2262 # And meshes' shape keys.
2263 for channel_key
, (anim_shape
, me
, shape
) in animdata_shapes
.items():
2265 anim_shape
.simplify(simplify_fac
, bake_step
, force_keep
)
2268 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in anim_shape
.get_final_data(scene
, ref_id
, force_keep
):
2269 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2270 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2272 # And cameras' lens and focus distance keys.
2273 for cam_key
, (anim_camera_lens
, anim_camera_focus_distance
, camera
) in animdata_cameras
.items():
2275 anim_camera_lens
.simplify(simplify_fac
, bake_step
, force_keep
)
2276 anim_camera_focus_distance
.simplify(simplify_fac
, bake_step
, force_keep
)
2277 if anim_camera_lens
:
2278 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in \
2279 anim_camera_lens
.get_final_data(scene
, ref_id
, force_keep
):
2280 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2281 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2282 if anim_camera_focus_distance
:
2283 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in \
2284 anim_camera_focus_distance
.get_final_data(scene
, ref_id
, force_keep
):
2285 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2286 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2288 astack_key
= get_blender_anim_stack_key(scene
, ref_id
)
2289 alayer_key
= get_blender_anim_layer_key(scene
, ref_id
)
2290 name
= (get_blenderID_name(ref_id
) if ref_id
else scene
.name
).encode()
2296 return (astack_key
, animations
, alayer_key
, name
, f_start
, f_end
) if animations
else None
2299 def fbx_animations(scene_data
):
2301 Generate global animation data from objects.
2303 scene
= scene_data
.scene
2309 def add_anim(animations
, animated
, anim
):
2310 nonlocal frame_start
, frame_end
2311 if anim
is not None:
2312 animations
.append(anim
)
2313 f_start
, f_end
= anim
[4:6]
2314 if f_start
< frame_start
:
2315 frame_start
= f_start
2316 if f_end
> frame_end
:
2319 _astack_key
, astack
, _alayer_key
, _name
, _fstart
, _fend
= anim
2320 for elem_key
, (alayer_key
, acurvenodes
) in astack
.items():
2321 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
2322 animated
.add((elem_key
, fbx_prop
))
2324 # Per-NLA strip animstacks.
2325 if scene_data
.settings
.bake_anim_use_nla_strips
:
2328 for ob_obj
in scene_data
.objects
:
2329 # NLA tracks only for objects, not bones!
2330 if not ob_obj
.is_object
:
2332 ob
= ob_obj
.bdata
# Back to real Blender Object.
2333 if not ob
.animation_data
:
2336 # Some actions are read-only, one cause is being in NLA tweakmode
2337 restore_use_tweak_mode
= ob
.animation_data
.use_tweak_mode
2338 if ob
.animation_data
.is_property_readonly('action'):
2339 ob
.animation_data
.use_tweak_mode
= False
2341 # We have to remove active action from objects, it overwrites strips actions otherwise...
2342 ob_actions
.append((ob
, ob
.animation_data
.action
, restore_use_tweak_mode
))
2343 ob
.animation_data
.action
= None
2344 for track
in ob
.animation_data
.nla_tracks
:
2347 for strip
in track
.strips
:
2350 strips
.append(strip
)
2353 for strip
in strips
:
2355 add_anim(animations
, animated
,
2356 fbx_animations_do(scene_data
, strip
, strip
.frame_start
, strip
.frame_end
, True, force_keep
=True))
2358 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2360 for strip
in strips
:
2363 for ob
, ob_act
, restore_use_tweak_mode
in ob_actions
:
2364 ob
.animation_data
.action
= ob_act
2365 ob
.animation_data
.use_tweak_mode
= restore_use_tweak_mode
2368 if scene_data
.settings
.bake_anim_use_all_actions
:
2369 def validate_actions(act
, path_resolve
):
2370 for fc
in act
.fcurves
:
2371 data_path
= fc
.data_path
2373 data_path
= data_path
+ "[%d]" % fc
.array_index
2375 path_resolve(data_path
)
2377 return False # Invalid.
2378 return True # Valid.
2380 def restore_object(ob_to
, ob_from
):
2381 # Restore org state of object (ugh :/ ).
2383 'location', 'rotation_quaternion', 'rotation_axis_angle', 'rotation_euler', 'rotation_mode', 'scale',
2384 'delta_location', 'delta_rotation_euler', 'delta_rotation_quaternion', 'delta_scale',
2385 'lock_location', 'lock_rotation', 'lock_rotation_w', 'lock_rotations_4d', 'lock_scale',
2386 'tag', 'track_axis', 'up_axis', 'active_material', 'active_material_index',
2387 'matrix_parent_inverse', 'empty_display_type', 'empty_display_size', 'empty_image_offset', 'pass_index',
2388 'color', 'hide_viewport', 'hide_select', 'hide_render', 'instance_type',
2389 'use_instance_vertices_rotation', 'use_instance_faces_scale', 'instance_faces_scale',
2390 'display_type', 'show_bounds', 'display_bounds_type', 'show_name', 'show_axis', 'show_texture_space',
2391 'show_wire', 'show_all_edges', 'show_transparent', 'show_in_front',
2392 'show_only_shape_key', 'use_shape_key_edit_mode', 'active_shape_key_index',
2395 if not ob_to
.is_property_readonly(p
):
2396 setattr(ob_to
, p
, getattr(ob_from
, p
))
2398 for ob_obj
in scene_data
.objects
:
2399 # Actions only for objects, not bones!
2400 if not ob_obj
.is_object
:
2403 ob
= ob_obj
.bdata
# Back to real Blender Object.
2405 if not ob
.animation_data
:
2406 continue # Do not export animations for objects that are absolutely not animated, see T44386.
2408 if ob
.animation_data
.is_property_readonly('action'):
2409 continue # Cannot re-assign 'active action' to this object (usually related to NLA usage, see T48089).
2411 # We can't play with animdata and actions and get back to org state easily.
2412 # So we have to add a temp copy of the object to the scene, animate it, and remove it... :/
2414 # Great, have to handle bones as well if needed...
2415 pbones_matrices
= [pbo
.matrix_basis
.copy() for pbo
in ob
.pose
.bones
] if ob
.type == 'ARMATURE' else ...
2417 org_act
= ob
.animation_data
.action
2418 path_resolve
= ob
.path_resolve
2420 for act
in bpy
.data
.actions
:
2421 # For now, *all* paths in the action must be valid for the object, to validate the action.
2422 # Unless that action was already assigned to the object!
2423 if act
!= org_act
and not validate_actions(act
, path_resolve
):
2425 ob
.animation_data
.action
= act
2426 frame_start
, frame_end
= act
.frame_range
# sic!
2427 add_anim(animations
, animated
,
2428 fbx_animations_do(scene_data
, (ob
, act
), frame_start
, frame_end
, True,
2429 objects
={ob_obj}
, force_keep
=True))
2431 if pbones_matrices
is not ...:
2432 for pbo
, mat
in zip(ob
.pose
.bones
, pbones_matrices
):
2433 pbo
.matrix_basis
= mat
.copy()
2434 ob
.animation_data
.action
= org_act
2435 restore_object(ob
, ob_copy
)
2436 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2438 if pbones_matrices
is not ...:
2439 for pbo
, mat
in zip(ob
.pose
.bones
, pbones_matrices
):
2440 pbo
.matrix_basis
= mat
.copy()
2441 ob
.animation_data
.action
= org_act
2443 bpy
.data
.objects
.remove(ob_copy
)
2444 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2446 # Global (containing everything) animstack, only if not exporting NLA strips and/or all actions.
2447 if not scene_data
.settings
.bake_anim_use_nla_strips
and not scene_data
.settings
.bake_anim_use_all_actions
:
2448 add_anim(animations
, animated
, fbx_animations_do(scene_data
, None, scene
.frame_start
, scene
.frame_end
, False))
2450 # Be sure to update all matrices back to org state!
2451 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2453 return animations
, animated
, frame_start
, frame_end
2456 def fbx_data_from_scene(scene
, depsgraph
, settings
):
2458 Do some pre-processing over scene's data...
2460 objtypes
= settings
.object_types
2461 dp_objtypes
= objtypes
- {'ARMATURE'} # Armatures are not supported as dupli instances currently...
2465 # ##### Gathering data...
2467 perfmon
.step("FBX export prepare: Wrapping Objects...")
2469 # This is rather simple for now, maybe we could end generating templates with most-used values
2470 # instead of default ones?
2471 objects
= {} # Because we do not have any ordered set...
2472 for ob
in settings
.context_objects
:
2473 if ob
.type not in objtypes
:
2475 ob_obj
= ObjectWrapper(ob
)
2476 objects
[ob_obj
] = None
2478 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
2479 if dp_obj
.type not in dp_objtypes
:
2481 objects
[dp_obj
] = None
2483 perfmon
.step("FBX export prepare: Wrapping Data (lamps, cameras, empties)...")
2485 data_lights
= {ob_obj
.bdata
.data
: get_blenderID_key(ob_obj
.bdata
.data
)
2486 for ob_obj
in objects
if ob_obj
.type == 'LIGHT'}
2487 # Unfortunately, FBX camera data contains object-level data (like position, orientation, etc.)...
2488 data_cameras
= {ob_obj
: get_blenderID_key(ob_obj
.bdata
.data
)
2489 for ob_obj
in objects
if ob_obj
.type == 'CAMERA'}
2490 # Yep! Contains nothing, but needed!
2491 data_empties
= {ob_obj
: get_blender_empty_key(ob_obj
.bdata
)
2492 for ob_obj
in objects
if ob_obj
.type == 'EMPTY'}
2494 perfmon
.step("FBX export prepare: Wrapping Meshes...")
2497 for ob_obj
in objects
:
2498 if ob_obj
.type not in BLENDER_OBJECT_TYPES_MESHLIKE
:
2504 # Do not want to systematically recreate a new mesh for dupliobject instances, kind of break purpose of those.
2506 org_ob_obj
= ObjectWrapper(ob
) # We get the "real" object wrapper from that dupli instance.
2507 if org_ob_obj
in data_meshes
:
2508 data_meshes
[ob_obj
] = data_meshes
[org_ob_obj
]
2511 is_ob_material
= any(ms
.link
== 'OBJECT' for ms
in ob
.material_slots
)
2513 if settings
.use_mesh_modifiers
or settings
.use_triangles
or ob
.type in BLENDER_OTHER_OBJECT_TYPES
or is_ob_material
:
2514 # We cannot use default mesh in that case, or material would not be the right ones...
2515 use_org_data
= not (is_ob_material
or ob
.type in BLENDER_OTHER_OBJECT_TYPES
)
2516 backup_pose_positions
= []
2518 if use_org_data
and ob
.type == 'MESH':
2519 if settings
.use_triangles
:
2520 use_org_data
= False
2521 # No need to create a new mesh in this case, if no modifier is active!
2523 for mod
in ob
.modifiers
:
2524 # For meshes, when armature export is enabled, disable Armature modifiers here!
2525 # XXX Temp hacks here since currently we only have access to a viewport depsgraph...
2527 # NOTE: We put armature to the rest pose instead of disabling it so we still
2528 # have vertex groups in the evaluated mesh.
2529 if mod
.type == 'ARMATURE' and 'ARMATURE' in settings
.object_types
:
2531 if object and object.type == 'ARMATURE':
2532 armature
= object.data
2533 # If armature is already in REST position, there's nothing to back-up
2534 # This cuts down on export time dramatically, if all armatures are already in REST position
2535 # by not triggering dependency graph update
2536 if armature
.pose_position
!= 'REST':
2537 backup_pose_positions
.append((armature
, armature
.pose_position
))
2538 armature
.pose_position
= 'REST'
2539 elif mod
.show_render
or mod
.show_viewport
:
2540 # If exporting with subsurf collect the last Catmull-Clark subsurf modifier
2541 # and disable it. We can use the original data as long as this is the first
2542 # found applicable subsurf modifier.
2543 if settings
.use_subsurf
and mod
.type == 'SUBSURF' and mod
.subdivision_type
== 'CATMULL_CLARK':
2545 use_org_data
= False
2548 use_org_data
= False
2549 if settings
.use_subsurf
and last_subsurf
:
2550 # XXX: When exporting with subsurf information temporarily disable
2551 # the last subsurf modifier.
2552 tmp_mods
.append((last_subsurf
, last_subsurf
.show_render
, last_subsurf
.show_viewport
))
2553 last_subsurf
.show_render
= False
2554 last_subsurf
.show_viewport
= False
2555 if not use_org_data
:
2556 # If modifiers has been altered need to update dependency graph.
2557 if backup_pose_positions
or tmp_mods
:
2559 ob_to_convert
= ob
.evaluated_get(depsgraph
) if settings
.use_mesh_modifiers
else ob
2560 # NOTE: The dependency graph might be re-evaluating multiple times, which could
2561 # potentially free the mesh created early on. So we put those meshes to bmain and
2562 # free them afterwards. Not ideal but ensures correct ownerwhip.
2563 tmp_me
= bpy
.data
.meshes
.new_from_object(
2564 ob_to_convert
, preserve_all_data_layers
=True, depsgraph
=depsgraph
)
2565 # Triangulate the mesh if requested
2566 if settings
.use_triangles
:
2569 bm
.from_mesh(tmp_me
)
2570 bmesh
.ops
.triangulate(bm
, faces
=bm
.faces
)
2573 # Usually the materials of the evaluated object will be the same, but modifiers, such as Geometry Nodes,
2574 # can change the materials.
2575 orig_mats
= tuple(slot
.material
for slot
in ob
.material_slots
)
2576 eval_mats
= tuple(slot
.material
.original
if slot
.material
else None
2577 for slot
in ob_to_convert
.material_slots
)
2578 if orig_mats
!= eval_mats
:
2579 # Override the default behaviour of getting materials from ob_obj.bdata.material_slots.
2580 ob_obj
.override_materials
= eval_mats
2581 data_meshes
[ob_obj
] = (get_blenderID_key(tmp_me
), tmp_me
, True)
2582 # Change armatures back.
2583 for armature
, pose_position
in backup_pose_positions
:
2584 print((armature
, pose_position
))
2585 armature
.pose_position
= pose_position
2586 # Update now, so we don't leave modified state after last object was exported.
2587 # Re-enable temporary disabled modifiers.
2588 for mod
, show_render
, show_viewport
in tmp_mods
:
2589 mod
.show_render
= show_render
2590 mod
.show_viewport
= show_viewport
2591 if backup_pose_positions
or tmp_mods
:
2594 data_meshes
[ob_obj
] = (get_blenderID_key(ob
.data
), ob
.data
, False)
2596 # In case "real" source object of that dupli did not yet still existed in data_meshes, create it now!
2597 if org_ob_obj
is not None:
2598 data_meshes
[org_ob_obj
] = data_meshes
[ob_obj
]
2600 perfmon
.step("FBX export prepare: Wrapping ShapeKeys...")
2603 data_deformers_shape
= {}
2604 geom_mat_co
= settings
.global_matrix
if settings
.bake_space_transform
else None
2605 co_bl_dtype
= np
.single
2606 co_fbx_dtype
= np
.float64
2607 idx_fbx_dtype
= np
.int32
2609 def empty_verts_fallbacks():
2610 """Create fallback arrays for when there are no verts"""
2611 # FBX does not like empty shapes (makes Unity crash e.g.).
2612 # To prevent this, we add a vertex that does nothing, but it keeps the shape key intact
2613 single_vert_co
= np
.zeros((1, 3), dtype
=co_fbx_dtype
)
2614 single_vert_idx
= np
.zeros(1, dtype
=idx_fbx_dtype
)
2615 return single_vert_co
, single_vert_idx
2617 for me_key
, me
, _free
in data_meshes
.values():
2618 if not (me
.shape_keys
and len(me
.shape_keys
.key_blocks
) > 1): # We do not want basis-only relative skeys...
2620 if me
in data_deformers_shape
:
2623 shapes_key
= get_blender_mesh_shape_key(me
)
2625 sk_base
= me
.shape_keys
.key_blocks
[0]
2627 # Get and cache only the cos that we need
2629 def sk_cos(shape_key
):
2630 _cos
= np
.empty(len(me
.vertices
) * 3, dtype
=co_bl_dtype
)
2631 if shape_key
== sk_base
:
2632 me
.vertices
.foreach_get("co", _cos
)
2634 shape_key
.data
.foreach_get("co", _cos
)
2635 return vcos_transformed(_cos
, geom_mat_co
, co_fbx_dtype
)
2637 for shape
in me
.shape_keys
.key_blocks
[1:]:
2638 # Only write vertices really different from base coordinates!
2639 relative_key
= shape
.relative_key
2640 if shape
== relative_key
:
2641 # Shape is its own relative key, so it does nothing
2642 shape_verts_co
, shape_verts_idx
= empty_verts_fallbacks()
2644 sv_cos
= sk_cos(shape
)
2645 ref_cos
= sk_cos(shape
.relative_key
)
2647 # Exclude cos similar to ref_cos and get the indices of the cos that remain
2648 shape_verts_co
, shape_verts_idx
= shape_difference_exclude_similar(sv_cos
, ref_cos
)
2650 if not shape_verts_co
.size
:
2651 shape_verts_co
, shape_verts_idx
= empty_verts_fallbacks()
2653 # Ensure the indices are of the correct type
2654 shape_verts_idx
= astype_view_signedness(shape_verts_idx
, idx_fbx_dtype
)
2656 channel_key
, geom_key
= get_blender_mesh_shape_channel_key(me
, shape
)
2657 data
= (channel_key
, geom_key
, shape_verts_co
, shape_verts_idx
)
2658 data_deformers_shape
.setdefault(me
, (me_key
, shapes_key
, {}))[2][shape
] = data
2662 perfmon
.step("FBX export prepare: Wrapping Armatures...")
2665 data_deformers_skin
= {}
2668 for ob_obj
in tuple(objects
):
2669 if not (ob_obj
.is_object
and ob_obj
.type in {'ARMATURE'}):
2671 fbx_skeleton_from_armature(scene
, settings
, ob_obj
, objects
, data_meshes
,
2672 data_bones
, data_deformers_skin
, data_empties
, arm_parents
)
2674 # Generate leaf bones
2675 data_leaf_bones
= []
2676 if settings
.add_leaf_bones
:
2677 data_leaf_bones
= fbx_generate_leaf_bones(settings
, data_bones
)
2679 perfmon
.step("FBX export prepare: Wrapping World...")
2681 # Some world settings are embedded in FBX materials...
2683 data_world
= {scene
.world
: get_blenderID_key(scene
.world
)}
2687 perfmon
.step("FBX export prepare: Wrapping Materials...")
2689 # TODO: Check all the material stuff works even when they are linked to Objects
2690 # (we can then have the same mesh used with different materials...).
2691 # *Should* work, as FBX always links its materials to Models (i.e. objects).
2692 # XXX However, material indices would probably break...
2694 for ob_obj
in objects
:
2695 # If obj is not a valid object for materials, wrapper will just return an empty tuple...
2696 for ma
in ob_obj
.materials
:
2698 continue # Empty slots!
2699 # Note theoretically, FBX supports any kind of materials, even GLSL shaders etc.
2700 # However, I doubt anything else than Lambert/Phong is really portable!
2701 # Note we want to keep a 'dummy' empty material even when we can't really support it, see T41396.
2702 ma_data
= data_materials
.setdefault(ma
, (get_blenderID_key(ma
), []))
2703 ma_data
[1].append(ob_obj
)
2705 perfmon
.step("FBX export prepare: Wrapping Textures...")
2707 # Note FBX textures also hold their mapping info.
2708 # TODO: Support layers?
2710 # FbxVideo also used to store static images...
2712 # For now, do not use world textures, don't think they can be linked to anything FBX wise...
2713 for ma
in data_materials
.keys():
2714 # Note: with nodal shaders, we'll could be generating much more textures, but that's kind of unavoidable,
2715 # given that textures actually do not exist anymore in material context in Blender...
2716 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
2717 for sock_name
, fbx_name
in PRINCIPLED_TEXTURE_SOCKETS_TO_FBX
:
2718 tex
= getattr(ma_wrap
, sock_name
)
2719 if tex
is None or tex
.image
is None:
2721 blender_tex_key
= (ma
, sock_name
)
2722 data_textures
[blender_tex_key
] = (get_blender_nodetexture_key(*blender_tex_key
), fbx_name
)
2725 vid_data
= data_videos
.setdefault(img
, (get_blenderID_key(img
), []))
2726 vid_data
[1].append(blender_tex_key
)
2728 perfmon
.step("FBX export prepare: Wrapping Animations...")
2733 frame_start
= scene
.frame_start
2734 frame_end
= scene
.frame_end
2735 if settings
.bake_anim
:
2736 # From objects & bones only for a start.
2737 # Kind of hack, we need a temp scene_data for object's space handling to bake animations...
2738 tmp_scdata
= FBXExportData(
2740 settings
, scene
, depsgraph
, objects
, None, None, 0.0, 0.0,
2741 data_empties
, data_lights
, data_cameras
, data_meshes
, None,
2742 data_bones
, data_leaf_bones
, data_deformers_skin
, data_deformers_shape
,
2743 data_world
, data_materials
, data_textures
, data_videos
,
2745 animations
, animated
, frame_start
, frame_end
= fbx_animations(tmp_scdata
)
2747 # ##### Creation of templates...
2749 perfmon
.step("FBX export prepare: Generating templates...")
2752 templates
[b
"GlobalSettings"] = fbx_template_def_globalsettings(scene
, settings
, nbr_users
=1)
2755 templates
[b
"Null"] = fbx_template_def_null(scene
, settings
, nbr_users
=len(data_empties
))
2758 templates
[b
"Light"] = fbx_template_def_light(scene
, settings
, nbr_users
=len(data_lights
))
2761 templates
[b
"Camera"] = fbx_template_def_camera(scene
, settings
, nbr_users
=len(data_cameras
))
2764 templates
[b
"Bone"] = fbx_template_def_bone(scene
, settings
, nbr_users
=len(data_bones
))
2767 nbr
= len({me_key
for me_key
, _me
, _free
in data_meshes
.values()})
2768 if data_deformers_shape
:
2769 nbr
+= sum(len(shapes
[2]) for shapes
in data_deformers_shape
.values())
2770 templates
[b
"Geometry"] = fbx_template_def_geometry(scene
, settings
, nbr_users
=nbr
)
2773 templates
[b
"Model"] = fbx_template_def_model(scene
, settings
, nbr_users
=len(objects
))
2776 # Number of Pose|BindPose elements should be the same as number of meshes-parented-to-armatures
2777 templates
[b
"BindPose"] = fbx_template_def_pose(scene
, settings
, nbr_users
=len(arm_parents
))
2779 if data_deformers_skin
or data_deformers_shape
:
2781 if data_deformers_skin
:
2782 nbr
+= len(data_deformers_skin
)
2783 nbr
+= sum(len(clusters
) for def_me
in data_deformers_skin
.values() for a
, b
, clusters
in def_me
.values())
2784 if data_deformers_shape
:
2785 nbr
+= len(data_deformers_shape
)
2786 nbr
+= sum(len(shapes
[2]) for shapes
in data_deformers_shape
.values())
2788 templates
[b
"Deformers"] = fbx_template_def_deformer(scene
, settings
, nbr_users
=nbr
)
2790 # No world support in FBX...
2793 templates[b"World"] = fbx_template_def_world(scene, settings, nbr_users=len(data_world))
2797 templates
[b
"Material"] = fbx_template_def_material(scene
, settings
, nbr_users
=len(data_materials
))
2800 templates
[b
"TextureFile"] = fbx_template_def_texture_file(scene
, settings
, nbr_users
=len(data_textures
))
2803 templates
[b
"Video"] = fbx_template_def_video(scene
, settings
, nbr_users
=len(data_videos
))
2806 nbr_astacks
= len(animations
)
2809 for _astack_key
, astack
, _al
, _n
, _fs
, _fe
in animations
:
2810 for _alayer_key
, alayer
in astack
.values():
2811 for _acnode_key
, acnode
, _acnode_name
in alayer
.values():
2813 for _acurve_key
, _dval
, acurve
, acurve_valid
in acnode
.values():
2817 templates
[b
"AnimationStack"] = fbx_template_def_animstack(scene
, settings
, nbr_users
=nbr_astacks
)
2818 # Would be nice to have one layer per animated object, but this seems tricky and not that well supported.
2819 # So for now, only one layer per anim stack.
2820 templates
[b
"AnimationLayer"] = fbx_template_def_animlayer(scene
, settings
, nbr_users
=nbr_astacks
)
2821 templates
[b
"AnimationCurveNode"] = fbx_template_def_animcurvenode(scene
, settings
, nbr_users
=nbr_acnodes
)
2822 templates
[b
"AnimationCurve"] = fbx_template_def_animcurve(scene
, settings
, nbr_users
=nbr_acurves
)
2824 templates_users
= sum(tmpl
.nbr_users
for tmpl
in templates
.values())
2826 # ##### Creation of connections...
2828 perfmon
.step("FBX export prepare: Generating Connections...")
2832 # Objects (with classical parenting).
2833 for ob_obj
in objects
:
2834 # Bones are handled later.
2835 if not ob_obj
.is_bone
:
2836 par_obj
= ob_obj
.parent
2837 # Meshes parented to armature are handled separately, yet we want the 'no parent' connection (0).
2838 if par_obj
and ob_obj
.has_valid_parent(objects
) and (par_obj
, ob_obj
) not in arm_parents
:
2839 connections
.append((b
"OO", ob_obj
.fbx_uuid
, par_obj
.fbx_uuid
, None))
2841 connections
.append((b
"OO", ob_obj
.fbx_uuid
, 0, None))
2843 # Armature & Bone chains.
2844 for bo_obj
in data_bones
.keys():
2845 par_obj
= bo_obj
.parent
2846 if par_obj
not in objects
:
2848 connections
.append((b
"OO", bo_obj
.fbx_uuid
, par_obj
.fbx_uuid
, None))
2851 for ob_obj
in objects
:
2853 bo_data_key
= data_bones
[ob_obj
]
2854 connections
.append((b
"OO", get_fbx_uuid_from_key(bo_data_key
), ob_obj
.fbx_uuid
, None))
2856 if ob_obj
.type == 'LIGHT':
2857 light_key
= data_lights
[ob_obj
.bdata
.data
]
2858 connections
.append((b
"OO", get_fbx_uuid_from_key(light_key
), ob_obj
.fbx_uuid
, None))
2859 elif ob_obj
.type == 'CAMERA':
2860 cam_key
= data_cameras
[ob_obj
]
2861 connections
.append((b
"OO", get_fbx_uuid_from_key(cam_key
), ob_obj
.fbx_uuid
, None))
2862 elif ob_obj
.type == 'EMPTY' or ob_obj
.type == 'ARMATURE':
2863 empty_key
= data_empties
[ob_obj
]
2864 connections
.append((b
"OO", get_fbx_uuid_from_key(empty_key
), ob_obj
.fbx_uuid
, None))
2865 elif ob_obj
.type in BLENDER_OBJECT_TYPES_MESHLIKE
:
2866 mesh_key
, _me
, _free
= data_meshes
[ob_obj
]
2867 connections
.append((b
"OO", get_fbx_uuid_from_key(mesh_key
), ob_obj
.fbx_uuid
, None))
2870 for (_node_name
, par_uuid
, node_uuid
, attr_uuid
, _matrix
, _hide
, _size
) in data_leaf_bones
:
2871 connections
.append((b
"OO", node_uuid
, par_uuid
, None))
2872 connections
.append((b
"OO", attr_uuid
, node_uuid
, None))
2874 # 'Shape' deformers (shape keys, only for meshes currently)...
2875 for me_key
, shapes_key
, shapes
in data_deformers_shape
.values():
2877 connections
.append((b
"OO", get_fbx_uuid_from_key(shapes_key
), get_fbx_uuid_from_key(me_key
), None))
2878 for channel_key
, geom_key
, _shape_verts_co
, _shape_verts_idx
in shapes
.values():
2879 # shape channel -> shape
2880 connections
.append((b
"OO", get_fbx_uuid_from_key(channel_key
), get_fbx_uuid_from_key(shapes_key
), None))
2881 # geometry (keys) -> shape channel
2882 connections
.append((b
"OO", get_fbx_uuid_from_key(geom_key
), get_fbx_uuid_from_key(channel_key
), None))
2884 # 'Skin' deformers (armature-to-geometry, only for meshes currently)...
2885 for arm
, deformed_meshes
in data_deformers_skin
.items():
2886 for me
, (skin_key
, ob_obj
, clusters
) in deformed_meshes
.items():
2888 mesh_key
, _me
, _free
= data_meshes
[ob_obj
]
2890 connections
.append((b
"OO", get_fbx_uuid_from_key(skin_key
), get_fbx_uuid_from_key(mesh_key
), None))
2891 for bo_obj
, clstr_key
in clusters
.items():
2893 connections
.append((b
"OO", get_fbx_uuid_from_key(clstr_key
), get_fbx_uuid_from_key(skin_key
), None))
2895 connections
.append((b
"OO", bo_obj
.fbx_uuid
, get_fbx_uuid_from_key(clstr_key
), None))
2898 mesh_material_indices
= {}
2900 for ma
, (ma_key
, ob_objs
) in data_materials
.items():
2901 for ob_obj
in ob_objs
:
2902 # Get index of this material for this object (or dupliobject).
2903 # Material indices for mesh faces are determined by their order in 'ma to ob' connections.
2904 # Only materials for meshes currently...
2905 # Note in case of dupliobjects a same me/ma idx will be generated several times...
2906 # Should not be an issue in practice, and it's needed in case we export duplis but not the original!
2907 if ob_obj
.type not in BLENDER_OBJECT_TYPES_MESHLIKE
:
2908 connections
.append((b
"OO", get_fbx_uuid_from_key(ma_key
), ob_obj
.fbx_uuid
, None))
2910 _mesh_key
, me
, _free
= data_meshes
[ob_obj
]
2911 material_indices
= mesh_material_indices
.setdefault(me
, {})
2912 if ma
in material_indices
:
2913 # Material has already been found for this mesh.
2914 # XXX If a mesh has multiple material slots with the same material, they are combined into one slot.
2915 # Even if duplicate materials were exported without combining them into one slot, keeping duplicate
2916 # materials separated does not appear to be common behaviour of external software when importing FBX.
2918 connections
.append((b
"OO", get_fbx_uuid_from_key(ma_key
), ob_obj
.fbx_uuid
, None))
2919 idx
= _objs_indices
[ob_obj
] = _objs_indices
.get(ob_obj
, -1) + 1
2920 material_indices
[ma
] = idx
2924 for (ma
, sock_name
), (tex_key
, fbx_prop
) in data_textures
.items():
2925 ma_key
, _ob_objs
= data_materials
[ma
]
2926 # texture -> material properties
2927 connections
.append((b
"OP", get_fbx_uuid_from_key(tex_key
), get_fbx_uuid_from_key(ma_key
), fbx_prop
))
2930 for vid
, (vid_key
, blender_tex_keys
) in data_videos
.items():
2931 for blender_tex_key
in blender_tex_keys
:
2932 tex_key
, _fbx_prop
= data_textures
[blender_tex_key
]
2933 connections
.append((b
"OO", get_fbx_uuid_from_key(vid_key
), get_fbx_uuid_from_key(tex_key
), None))
2936 for astack_key
, astack
, alayer_key
, _name
, _fstart
, _fend
in animations
:
2937 # Animstack itself is linked nowhere!
2938 astack_id
= get_fbx_uuid_from_key(astack_key
)
2939 # For now, only one layer!
2940 alayer_id
= get_fbx_uuid_from_key(alayer_key
)
2941 connections
.append((b
"OO", alayer_id
, astack_id
, None))
2942 for elem_key
, (alayer_key
, acurvenodes
) in astack
.items():
2943 elem_id
= get_fbx_uuid_from_key(elem_key
)
2944 # Animlayer -> animstack.
2945 # alayer_id = get_fbx_uuid_from_key(alayer_key)
2946 # connections.append((b"OO", alayer_id, astack_id, None))
2947 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
2948 # Animcurvenode -> animalayer.
2949 acurvenode_id
= get_fbx_uuid_from_key(acurvenode_key
)
2950 connections
.append((b
"OO", acurvenode_id
, alayer_id
, None))
2951 # Animcurvenode -> object property.
2952 connections
.append((b
"OP", acurvenode_id
, elem_id
, fbx_prop
.encode()))
2953 for fbx_item
, (acurve_key
, default_value
, acurve
, acurve_valid
) in acurves
.items():
2955 # Animcurve -> Animcurvenode.
2956 connections
.append((b
"OP", get_fbx_uuid_from_key(acurve_key
), acurvenode_id
, fbx_item
.encode()))
2958 perfmon
.level_down()
2960 # ##### And pack all this!
2962 return FBXExportData(
2963 templates
, templates_users
, connections
,
2964 settings
, scene
, depsgraph
, objects
, animations
, animated
, frame_start
, frame_end
,
2965 data_empties
, data_lights
, data_cameras
, data_meshes
, mesh_material_indices
,
2966 data_bones
, data_leaf_bones
, data_deformers_skin
, data_deformers_shape
,
2967 data_world
, data_materials
, data_textures
, data_videos
,
2971 def fbx_scene_data_cleanup(scene_data
):
2973 Some final cleanup...
2975 # Delete temp meshes.
2977 for me_key
, me
, free
in scene_data
.data_meshes
.values():
2978 if free
and me_key
not in done_meshes
:
2979 bpy
.data
.meshes
.remove(me
)
2980 done_meshes
.add(me_key
)
2983 # ##### Top-level FBX elements generators. #####
2985 def fbx_header_elements(root
, scene_data
, time
=None):
2987 Write boiling code of FBX root.
2988 time is expected to be a datetime.datetime object, or None (using now() in this case).
2990 app_vendor
= "Blender Foundation"
2991 app_name
= "Blender (stable FBX IO)"
2992 app_ver
= bpy
.app
.version_string
2996 addon_ver
= addon_utils
.module_bl_info(sys
.modules
[__package__
])['version']
2998 # ##### Start of FBXHeaderExtension element.
2999 header_ext
= elem_empty(root
, b
"FBXHeaderExtension")
3001 elem_data_single_int32(header_ext
, b
"FBXHeaderVersion", FBX_HEADER_VERSION
)
3003 elem_data_single_int32(header_ext
, b
"FBXVersion", FBX_VERSION
)
3006 elem_data_single_int32(header_ext
, b
"EncryptionType", 0)
3009 time
= datetime
.datetime
.now()
3010 elem
= elem_empty(header_ext
, b
"CreationTimeStamp")
3011 elem_data_single_int32(elem
, b
"Version", 1000)
3012 elem_data_single_int32(elem
, b
"Year", time
.year
)
3013 elem_data_single_int32(elem
, b
"Month", time
.month
)
3014 elem_data_single_int32(elem
, b
"Day", time
.day
)
3015 elem_data_single_int32(elem
, b
"Hour", time
.hour
)
3016 elem_data_single_int32(elem
, b
"Minute", time
.minute
)
3017 elem_data_single_int32(elem
, b
"Second", time
.second
)
3018 elem_data_single_int32(elem
, b
"Millisecond", time
.microsecond
// 1000)
3020 elem_data_single_string_unicode(header_ext
, b
"Creator", "%s - %s - %d.%d.%d"
3021 % (app_name
, app_ver
, addon_ver
[0], addon_ver
[1], addon_ver
[2]))
3023 # 'SceneInfo' seems mandatory to get a valid FBX file...
3024 # TODO use real values!
3025 # XXX Should we use scene.name.encode() here?
3026 scene_info
= elem_data_single_string(header_ext
, b
"SceneInfo", fbx_name_class(b
"GlobalInfo", b
"SceneInfo"))
3027 scene_info
.add_string(b
"UserData")
3028 elem_data_single_string(scene_info
, b
"Type", b
"UserData")
3029 elem_data_single_int32(scene_info
, b
"Version", FBX_SCENEINFO_VERSION
)
3030 meta_data
= elem_empty(scene_info
, b
"MetaData")
3031 elem_data_single_int32(meta_data
, b
"Version", FBX_SCENEINFO_VERSION
)
3032 elem_data_single_string(meta_data
, b
"Title", b
"")
3033 elem_data_single_string(meta_data
, b
"Subject", b
"")
3034 elem_data_single_string(meta_data
, b
"Author", b
"")
3035 elem_data_single_string(meta_data
, b
"Keywords", b
"")
3036 elem_data_single_string(meta_data
, b
"Revision", b
"")
3037 elem_data_single_string(meta_data
, b
"Comment", b
"")
3039 props
= elem_properties(scene_info
)
3040 elem_props_set(props
, "p_string_url", b
"DocumentUrl", "/foobar.fbx")
3041 elem_props_set(props
, "p_string_url", b
"SrcDocumentUrl", "/foobar.fbx")
3042 original
= elem_props_compound(props
, b
"Original")
3043 original("p_string", b
"ApplicationVendor", app_vendor
)
3044 original("p_string", b
"ApplicationName", app_name
)
3045 original("p_string", b
"ApplicationVersion", app_ver
)
3046 original("p_datetime", b
"DateTime_GMT", "01/01/1970 00:00:00.000")
3047 original("p_string", b
"FileName", "/foobar.fbx")
3048 lastsaved
= elem_props_compound(props
, b
"LastSaved")
3049 lastsaved("p_string", b
"ApplicationVendor", app_vendor
)
3050 lastsaved("p_string", b
"ApplicationName", app_name
)
3051 lastsaved("p_string", b
"ApplicationVersion", app_ver
)
3052 lastsaved("p_datetime", b
"DateTime_GMT", "01/01/1970 00:00:00.000")
3053 original("p_string", b
"ApplicationNativeFile", bpy
.data
.filepath
)
3055 # ##### End of FBXHeaderExtension element.
3057 # FileID is replaced by dummy value currently...
3058 elem_data_single_bytes(root
, b
"FileId", b
"FooBar")
3060 # CreationTime is replaced by dummy value currently, but anyway...
3061 elem_data_single_string_unicode(root
, b
"CreationTime",
3062 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}:{:03}"
3063 "".format(time
.year
, time
.month
, time
.day
, time
.hour
, time
.minute
, time
.second
,
3064 time
.microsecond
* 1000))
3066 elem_data_single_string_unicode(root
, b
"Creator", "%s - %s - %d.%d.%d"
3067 % (app_name
, app_ver
, addon_ver
[0], addon_ver
[1], addon_ver
[2]))
3069 # ##### Start of GlobalSettings element.
3070 global_settings
= elem_empty(root
, b
"GlobalSettings")
3071 scene
= scene_data
.scene
3073 elem_data_single_int32(global_settings
, b
"Version", 1000)
3075 props
= elem_properties(global_settings
)
3076 up_axis
, front_axis
, coord_axis
= RIGHT_HAND_AXES
[scene_data
.settings
.to_axes
]
3077 #~ # DO NOT take into account global scale here! That setting is applied to object transformations during export
3078 #~ # (in other words, this is pure blender-exporter feature, and has nothing to do with FBX data).
3079 #~ if scene_data.settings.apply_unit_scale:
3080 #~ # Unit scaling is applied to objects' scale, so our unit is effectively FBX one (centimeter).
3081 #~ scale_factor_org = 1.0
3082 #~ scale_factor = 1.0 / units_blender_to_fbx_factor(scene)
3084 #~ scale_factor_org = units_blender_to_fbx_factor(scene)
3085 #~ scale_factor = scale_factor_org
3086 scale_factor
= scale_factor_org
= scene_data
.settings
.unit_scale
3087 elem_props_set(props
, "p_integer", b
"UpAxis", up_axis
[0])
3088 elem_props_set(props
, "p_integer", b
"UpAxisSign", up_axis
[1])
3089 elem_props_set(props
, "p_integer", b
"FrontAxis", front_axis
[0])
3090 elem_props_set(props
, "p_integer", b
"FrontAxisSign", front_axis
[1])
3091 elem_props_set(props
, "p_integer", b
"CoordAxis", coord_axis
[0])
3092 elem_props_set(props
, "p_integer", b
"CoordAxisSign", coord_axis
[1])
3093 elem_props_set(props
, "p_integer", b
"OriginalUpAxis", -1)
3094 elem_props_set(props
, "p_integer", b
"OriginalUpAxisSign", 1)
3095 elem_props_set(props
, "p_double", b
"UnitScaleFactor", scale_factor
)
3096 elem_props_set(props
, "p_double", b
"OriginalUnitScaleFactor", scale_factor_org
)
3097 elem_props_set(props
, "p_color_rgb", b
"AmbientColor", (0.0, 0.0, 0.0))
3098 elem_props_set(props
, "p_string", b
"DefaultCamera", "Producer Perspective")
3100 # Global timing data.
3102 _
, fbx_fps_mode
= FBX_FRAMERATES
[0] # Custom framerate.
3103 fbx_fps
= fps
= r
.fps
/ r
.fps_base
3104 for ref_fps
, fps_mode
in FBX_FRAMERATES
:
3105 if similar_values(fps
, ref_fps
):
3107 fbx_fps_mode
= fps_mode
3109 elem_props_set(props
, "p_enum", b
"TimeMode", fbx_fps_mode
)
3110 elem_props_set(props
, "p_timestamp", b
"TimeSpanStart", 0)
3111 elem_props_set(props
, "p_timestamp", b
"TimeSpanStop", FBX_KTIME
)
3112 elem_props_set(props
, "p_double", b
"CustomFrameRate", fbx_fps
)
3114 # ##### End of GlobalSettings element.
3117 def fbx_documents_elements(root
, scene_data
):
3119 Write 'Document' part of FBX root.
3120 Seems like FBX support multiple documents, but until I find examples of such, we'll stick to single doc!
3121 time is expected to be a datetime.datetime object, or None (using now() in this case).
3123 name
= scene_data
.scene
.name
3125 # ##### Start of Documents element.
3126 docs
= elem_empty(root
, b
"Documents")
3128 elem_data_single_int32(docs
, b
"Count", 1)
3130 doc_uid
= get_fbx_uuid_from_key("__FBX_Document__" + name
)
3131 doc
= elem_data_single_int64(docs
, b
"Document", doc_uid
)
3132 doc
.add_string_unicode(name
)
3133 doc
.add_string_unicode(name
)
3135 props
= elem_properties(doc
)
3136 elem_props_set(props
, "p_object", b
"SourceObject")
3137 elem_props_set(props
, "p_string", b
"ActiveAnimStackName", "")
3139 # XXX Some kind of ID? Offset?
3140 # Anyway, as long as we have only one doc, probably not an issue.
3141 elem_data_single_int64(doc
, b
"RootNode", 0)
3144 def fbx_references_elements(root
, scene_data
):
3146 Have no idea what references are in FBX currently... Just writing empty element.
3148 docs
= elem_empty(root
, b
"References")
3151 def fbx_definitions_elements(root
, scene_data
):
3153 Templates definitions. Only used by Objects data afaik (apart from dummy GlobalSettings one).
3155 definitions
= elem_empty(root
, b
"Definitions")
3157 elem_data_single_int32(definitions
, b
"Version", FBX_TEMPLATES_VERSION
)
3158 elem_data_single_int32(definitions
, b
"Count", scene_data
.templates_users
)
3160 fbx_templates_generate(definitions
, scene_data
.templates
)
3163 def fbx_objects_elements(root
, scene_data
):
3165 Data (objects, geometry, material, textures, armatures, etc.).
3169 objects
= elem_empty(root
, b
"Objects")
3171 perfmon
.step("FBX export fetch empties (%d)..." % len(scene_data
.data_empties
))
3173 for empty
in scene_data
.data_empties
:
3174 fbx_data_empty_elements(objects
, empty
, scene_data
)
3176 perfmon
.step("FBX export fetch lamps (%d)..." % len(scene_data
.data_lights
))
3178 for lamp
in scene_data
.data_lights
:
3179 fbx_data_light_elements(objects
, lamp
, scene_data
)
3181 perfmon
.step("FBX export fetch cameras (%d)..." % len(scene_data
.data_cameras
))
3183 for cam
in scene_data
.data_cameras
:
3184 fbx_data_camera_elements(objects
, cam
, scene_data
)
3186 perfmon
.step("FBX export fetch meshes (%d)..."
3187 % len({me_key
for me_key
, _me
, _free
in scene_data
.data_meshes
.values()}))
3190 for me_obj
in scene_data
.data_meshes
:
3191 fbx_data_mesh_elements(objects
, me_obj
, scene_data
, done_meshes
)
3194 perfmon
.step("FBX export fetch objects (%d)..." % len(scene_data
.objects
))
3196 for ob_obj
in scene_data
.objects
:
3199 fbx_data_object_elements(objects
, ob_obj
, scene_data
)
3200 for dp_obj
in ob_obj
.dupli_list_gen(scene_data
.depsgraph
):
3201 if dp_obj
not in scene_data
.objects
:
3203 fbx_data_object_elements(objects
, dp_obj
, scene_data
)
3205 perfmon
.step("FBX export fetch remaining...")
3207 for ob_obj
in scene_data
.objects
:
3208 if not (ob_obj
.is_object
and ob_obj
.type == 'ARMATURE'):
3210 fbx_data_armature_elements(objects
, ob_obj
, scene_data
)
3212 if scene_data
.data_leaf_bones
:
3213 fbx_data_leaf_bone_elements(objects
, scene_data
)
3215 for ma
in scene_data
.data_materials
:
3216 fbx_data_material_elements(objects
, ma
, scene_data
)
3218 for blender_tex_key
in scene_data
.data_textures
:
3219 fbx_data_texture_file_elements(objects
, blender_tex_key
, scene_data
)
3221 for vid
in scene_data
.data_videos
:
3222 fbx_data_video_elements(objects
, vid
, scene_data
)
3224 perfmon
.step("FBX export fetch animations...")
3225 start_time
= time
.process_time()
3227 fbx_data_animation_elements(objects
, scene_data
)
3229 perfmon
.level_down()
3232 def fbx_connections_elements(root
, scene_data
):
3234 Relations between Objects (which material uses which texture, and so on).
3236 connections
= elem_empty(root
, b
"Connections")
3238 for c
in scene_data
.connections
:
3239 elem_connection(connections
, *c
)
3242 def fbx_takes_elements(root
, scene_data
):
3246 # XXX Pretty sure takes are no more needed...
3247 takes
= elem_empty(root
, b
"Takes")
3248 elem_data_single_string(takes
, b
"Current", b
"")
3250 animations
= scene_data
.animations
3251 for astack_key
, animations
, alayer_key
, name
, f_start
, f_end
in animations
:
3252 scene
= scene_data
.scene
3253 fps
= scene
.render
.fps
/ scene
.render
.fps_base
3254 start_ktime
= int(convert_sec_to_ktime(f_start
/ fps
))
3255 end_ktime
= int(convert_sec_to_ktime(f_end
/ fps
))
3257 take
= elem_data_single_string(takes
, b
"Take", name
)
3258 elem_data_single_string(take
, b
"FileName", name
+ b
".tak")
3259 take_loc_time
= elem_data_single_int64(take
, b
"LocalTime", start_ktime
)
3260 take_loc_time
.add_int64(end_ktime
)
3261 take_ref_time
= elem_data_single_int64(take
, b
"ReferenceTime", start_ktime
)
3262 take_ref_time
.add_int64(end_ktime
)
3265 # ##### "Main" functions. #####
3267 # This func can be called with just the filepath
3268 def save_single(operator
, scene
, depsgraph
, filepath
="",
3269 global_matrix
=Matrix(),
3270 apply_unit_scale
=False,
3272 apply_scale_options
='FBX_SCALE_NONE',
3275 context_objects
=None,
3277 use_mesh_modifiers
=True,
3278 use_mesh_modifiers_render
=True,
3279 mesh_smooth_type
='FACE',
3281 use_armature_deform_only
=False,
3283 bake_anim_use_all_bones
=True,
3284 bake_anim_use_nla_strips
=True,
3285 bake_anim_use_all_actions
=True,
3287 bake_anim_simplify_factor
=1.0,
3288 bake_anim_force_startend_keying
=True,
3289 add_leaf_bones
=False,
3290 primary_bone_axis
='Y',
3291 secondary_bone_axis
='X',
3294 use_mesh_edges
=True,
3296 use_triangles
=False,
3297 embed_textures
=False,
3298 use_custom_props
=False,
3299 bake_space_transform
=False,
3300 armature_nodetype
='NULL',
3302 prioritize_active_color
=False,
3306 # Clear cached ObjectWrappers (just in case...).
3307 ObjectWrapper
.cache_clear()
3309 if object_types
is None:
3310 object_types
= {'EMPTY', 'CAMERA', 'LIGHT', 'ARMATURE', 'MESH', 'OTHER'}
3312 if 'OTHER' in object_types
:
3313 object_types |
= BLENDER_OTHER_OBJECT_TYPES
3315 # Default Blender unit is equivalent to meter, while FBX one is centimeter...
3316 unit_scale
= units_blender_to_fbx_factor(scene
) if apply_unit_scale
else 100.0
3317 if apply_scale_options
== 'FBX_SCALE_NONE':
3318 global_matrix
= Matrix
.Scale(unit_scale
* global_scale
, 4) @ global_matrix
3320 elif apply_scale_options
== 'FBX_SCALE_UNITS':
3321 global_matrix
= Matrix
.Scale(global_scale
, 4) @ global_matrix
3322 elif apply_scale_options
== 'FBX_SCALE_CUSTOM':
3323 global_matrix
= Matrix
.Scale(unit_scale
, 4) @ global_matrix
3324 unit_scale
= global_scale
3325 else: # if apply_scale_options == 'FBX_SCALE_ALL':
3326 unit_scale
= global_scale
* unit_scale
3328 global_scale
= global_matrix
.median_scale
3329 global_matrix_inv
= global_matrix
.inverted()
3330 # For transforming mesh normals.
3331 global_matrix_inv_transposed
= global_matrix_inv
.transposed()
3333 # Only embed textures in COPY mode!
3334 if embed_textures
and path_mode
!= 'COPY':
3335 embed_textures
= False
3337 # Calculate bone correction matrix
3338 bone_correction_matrix
= None # Default is None = no change
3339 bone_correction_matrix_inv
= None
3340 if (primary_bone_axis
, secondary_bone_axis
) != ('Y', 'X'):
3341 from bpy_extras
.io_utils
import axis_conversion
3342 bone_correction_matrix
= axis_conversion(from_forward
=secondary_bone_axis
,
3343 from_up
=primary_bone_axis
,
3347 bone_correction_matrix_inv
= bone_correction_matrix
.inverted()
3350 media_settings
= FBXExportSettingsMedia(
3352 os
.path
.dirname(bpy
.data
.filepath
), # base_src
3353 os
.path
.dirname(filepath
), # base_dst
3354 # Local dir where to put images (media), using FBX conventions.
3355 os
.path
.splitext(os
.path
.basename(filepath
))[0] + ".fbm", # subdir
3358 set(), # embedded_set
3361 settings
= FBXExportSettings(
3362 operator
.report
, (axis_up
, axis_forward
), global_matrix
, global_scale
, apply_unit_scale
, unit_scale
,
3363 bake_space_transform
, global_matrix_inv
, global_matrix_inv_transposed
,
3364 context_objects
, object_types
, use_mesh_modifiers
, use_mesh_modifiers_render
,
3365 mesh_smooth_type
, use_subsurf
, use_mesh_edges
, use_tspace
, use_triangles
,
3366 armature_nodetype
, use_armature_deform_only
,
3367 add_leaf_bones
, bone_correction_matrix
, bone_correction_matrix_inv
,
3368 bake_anim
, bake_anim_use_all_bones
, bake_anim_use_nla_strips
, bake_anim_use_all_actions
,
3369 bake_anim_step
, bake_anim_simplify_factor
, bake_anim_force_startend_keying
,
3370 False, media_settings
, use_custom_props
, colors_type
, prioritize_active_color
3373 import bpy_extras
.io_utils
3375 print('\nFBX export starting... %r' % filepath
)
3376 start_time
= time
.process_time()
3378 # Generate some data about exported scene...
3379 scene_data
= fbx_data_from_scene(scene
, depsgraph
, settings
)
3381 root
= elem_empty(None, b
"") # Root element has no id, as it is not saved per se!
3383 # Mostly FBXHeaderExtension and GlobalSettings.
3384 fbx_header_elements(root
, scene_data
)
3386 # Documents and References are pretty much void currently.
3387 fbx_documents_elements(root
, scene_data
)
3388 fbx_references_elements(root
, scene_data
)
3390 # Templates definitions.
3391 fbx_definitions_elements(root
, scene_data
)
3394 fbx_objects_elements(root
, scene_data
)
3396 # How data are inter-connected.
3397 fbx_connections_elements(root
, scene_data
)
3400 fbx_takes_elements(root
, scene_data
)
3403 fbx_scene_data_cleanup(scene_data
)
3405 # And we are down, we can write the whole thing!
3406 encode_bin
.write(filepath
, root
, FBX_VERSION
)
3408 # Clear cached ObjectWrappers!
3409 ObjectWrapper
.cache_clear()
3411 # copy all collected files, if we did not embed them.
3412 if not media_settings
.embed_textures
:
3413 bpy_extras
.io_utils
.path_reference_copy(media_settings
.copy_set
)
3415 print('export finished in %.4f sec.' % (time
.process_time() - start_time
))
3419 # defaults for applications, currently only unity but could add others.
3420 def defaults_unity3d():
3422 # These options seem to produce the same result as the old Ascii exporter in Unity3D:
3424 "axis_forward": '-Z',
3425 "global_matrix": Matrix
.Rotation(-math
.pi
/ 2.0, 4, 'X'),
3426 # Should really be True, but it can cause problems if a model is already in a scene or prefab
3427 # with the old transforms.
3428 "bake_space_transform": False,
3430 "use_selection": False,
3432 "object_types": {'ARMATURE', 'EMPTY', 'MESH', 'OTHER'},
3433 "use_mesh_modifiers": True,
3434 "use_mesh_modifiers_render": True,
3435 "use_mesh_edges": False,
3436 "mesh_smooth_type": 'FACE',
3437 "colors_type": 'SRGB',
3438 "use_subsurf": False,
3439 "use_tspace": False, # XXX Why? Unity is expected to support tspace import...
3440 "use_triangles": False,
3442 "use_armature_deform_only": True,
3444 "use_custom_props": True,
3447 "bake_anim_simplify_factor": 1.0,
3448 "bake_anim_step": 1.0,
3449 "bake_anim_use_nla_strips": True,
3450 "bake_anim_use_all_actions": True,
3451 "add_leaf_bones": False, # Avoid memory/performance cost for something only useful for modelling
3452 "primary_bone_axis": 'Y', # Doesn't really matter for Unity, so leave unchanged
3453 "secondary_bone_axis": 'X',
3455 "path_mode": 'AUTO',
3456 "embed_textures": False,
3457 "batch_mode": 'OFF',
3461 def save(operator
, context
,
3463 use_selection
=False,
3465 use_active_collection
=False,
3467 use_batch_own_dir
=False,
3471 This is a wrapper around save_single, which handles multi-scenes (or collections) cases, when batch-exporting
3472 a whole .blend file.
3477 active_object
= context
.view_layer
.objects
.active
3480 if active_object
and active_object
.mode
!= 'OBJECT' and bpy
.ops
.object.mode_set
.poll():
3481 org_mode
= active_object
.mode
3482 bpy
.ops
.object.mode_set(mode
='OBJECT')
3484 if batch_mode
== 'OFF':
3485 kwargs_mod
= kwargs
.copy()
3486 if use_active_collection
:
3488 ctx_objects
= tuple(obj
3489 for obj
in context
.view_layer
.active_layer_collection
.collection
.all_objects
3490 if obj
.select_get())
3492 ctx_objects
= context
.view_layer
.active_layer_collection
.collection
.all_objects
3495 ctx_objects
= context
.selected_objects
3497 ctx_objects
= context
.view_layer
.objects
3499 ctx_objects
= tuple(obj
for obj
in ctx_objects
if obj
.visible_get())
3500 kwargs_mod
["context_objects"] = ctx_objects
3502 depsgraph
= context
.evaluated_depsgraph_get()
3503 ret
= save_single(operator
, context
.scene
, depsgraph
, filepath
, **kwargs_mod
)
3505 # XXX We need a way to generate a depsgraph for inactive view_layers first...
3506 # XXX Also, what to do in case of batch-exporting scenes, when there is more than one view layer?
3507 # Scenes have no concept of 'active' view layer, that's on window level...
3510 prefix
= os
.path
.basename(fbxpath
)
3512 fbxpath
= os
.path
.dirname(fbxpath
)
3514 if batch_mode
== 'COLLECTION':
3515 data_seq
= tuple((coll
, coll
.name
, 'objects') for coll
in bpy
.data
.collections
if coll
.objects
)
3516 elif batch_mode
in {'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3517 scenes
= [context
.scene
] if batch_mode
== 'ACTIVE_SCENE_COLLECTION' else bpy
.data
.scenes
3519 for scene
in scenes
:
3520 if not scene
.objects
:
3522 # Needed to avoid having tens of 'Scene Collection' entries.
3523 todo_collections
= [(scene
.collection
, "_".join((scene
.name
, scene
.collection
.name
)))]
3524 while todo_collections
:
3525 coll
, coll_name
= todo_collections
.pop()
3526 todo_collections
.extend(((c
, c
.name
) for c
in coll
.children
if c
.all_objects
))
3527 data_seq
.append((coll
, coll_name
, 'all_objects'))
3529 data_seq
= tuple((scene
, scene
.name
, 'objects') for scene
in bpy
.data
.scenes
if scene
.objects
)
3531 # call this function within a loop with BATCH_ENABLE == False
3533 new_fbxpath
= fbxpath
# own dir option modifies, we need to keep an original
3534 for data
, data_name
, data_obj_propname
in data_seq
: # scene or collection
3535 newname
= "_".join((prefix
, bpy
.path
.clean_name(data_name
))) if prefix
else bpy
.path
.clean_name(data_name
)
3537 if use_batch_own_dir
:
3538 new_fbxpath
= os
.path
.join(fbxpath
, newname
)
3539 # path may already exist... and be a file.
3540 while os
.path
.isfile(new_fbxpath
):
3541 new_fbxpath
= "_".join((new_fbxpath
, "dir"))
3542 if not os
.path
.exists(new_fbxpath
):
3543 os
.makedirs(new_fbxpath
)
3545 filepath
= os
.path
.join(new_fbxpath
, newname
+ '.fbx')
3547 print('\nBatch exporting %s as...\n\t%r' % (data
, filepath
))
3549 if batch_mode
in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3550 # Collection, so that objects update properly, add a dummy scene.
3551 scene
= bpy
.data
.scenes
.new(name
="FBX_Temp")
3552 src_scenes
= {} # Count how much each 'source' scenes are used.
3553 for obj
in getattr(data
, data_obj_propname
):
3554 for src_sce
in obj
.users_scene
:
3555 src_scenes
[src_sce
] = src_scenes
.setdefault(src_sce
, 0) + 1
3556 scene
.collection
.objects
.link(obj
)
3558 # Find the 'most used' source scene, and use its unit settings. This is somewhat weak, but should work
3559 # fine in most cases, and avoids stupid issues like T41931.
3560 best_src_scene
= None
3561 best_src_scene_users
= -1
3562 for sce
, nbr_users
in src_scenes
.items():
3563 if (nbr_users
) > best_src_scene_users
:
3564 best_src_scene_users
= nbr_users
3565 best_src_scene
= sce
3566 scene
.unit_settings
.system
= best_src_scene
.unit_settings
.system
3567 scene
.unit_settings
.system_rotation
= best_src_scene
.unit_settings
.system_rotation
3568 scene
.unit_settings
.scale_length
= best_src_scene
.unit_settings
.scale_length
3570 # new scene [only one viewlayer to update]
3571 scene
.view_layers
[0].update()
3572 # TODO - BUMMER! Armatures not in the group wont animate the mesh
3576 kwargs_batch
= kwargs
.copy()
3577 kwargs_batch
["context_objects"] = getattr(data
, data_obj_propname
)
3579 save_single(operator
, scene
, scene
.view_layers
[0].depsgraph
, filepath
, **kwargs_batch
)
3581 if batch_mode
in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3582 # Remove temp collection scene.
3583 bpy
.data
.scenes
.remove(scene
)
3585 if active_object
and org_mode
:
3586 context
.view_layer
.objects
.active
= active_object
3587 if bpy
.ops
.object.mode_set
.poll():
3588 bpy
.ops
.object.mode_set(mode
=org_mode
)