Remove bl_options from menus which caused tests to fail
[blender-addons.git] / io_scene_fbx / export_fbx_bin.py
bloba6a04a7bbb1cc7eda4e687279d60675ae0662724
1 # SPDX-FileCopyrightText: 2013 Campbell Barton
2 # SPDX-FileCopyrightText: 2014 Bastien Montagne
4 # SPDX-License-Identifier: GPL-2.0-or-later
6 import datetime
7 import math
8 import numpy as np
9 import os
10 import time
12 from itertools import zip_longest
13 from functools import cache
15 if "bpy" in locals():
16 import importlib
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)
24 import bpy
25 import bpy_extras
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 (
32 # Constants.
33 FBX_VERSION, FBX_HEADER_VERSION, FBX_SCENEINFO_VERSION, FBX_TEMPLATES_VERSION,
34 FBX_MODELS_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,
41 FBX_ANIM_KEY_VERSION,
42 FBX_ANIM_PROPSGROUP_NAME,
43 FBX_KTIME,
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.
48 PerfMon,
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,
51 fast_first_axis_flat,
52 # Attribute helpers.
53 MESH_ATTRIBUTE_CORNER_EDGE, MESH_ATTRIBUTE_SHARP_EDGE, MESH_ATTRIBUTE_EDGE_VERTS, MESH_ATTRIBUTE_CORNER_VERT,
54 MESH_ATTRIBUTE_SHARP_FACE, MESH_ATTRIBUTE_POSITION, MESH_ATTRIBUTE_MATERIAL_INDEX,
55 # Mesh transform helpers.
56 vcos_transformed, nors_transformed,
57 # UUID from key.
58 get_fbx_uuid_from_key,
59 # Key generators.
60 get_blenderID_key, get_blenderID_name,
61 get_blender_mesh_shape_key, get_blender_mesh_shape_channel_key,
62 get_blender_empty_key, get_blender_bone_key,
63 get_blender_bindpose_key, get_blender_armature_skin_key, get_blender_bone_cluster_key,
64 get_blender_anim_id_base, get_blender_anim_stack_key, get_blender_anim_layer_key,
65 get_blender_anim_curve_node_key, get_blender_anim_curve_key,
66 get_blender_nodetexture_key,
67 # FBX element data.
68 elem_empty,
69 elem_data_single_bool, elem_data_single_int16, elem_data_single_int32, elem_data_single_int64,
70 elem_data_single_float32, elem_data_single_float64,
71 elem_data_single_bytes, elem_data_single_string, elem_data_single_string_unicode,
72 elem_data_single_bool_array, elem_data_single_int32_array, elem_data_single_int64_array,
73 elem_data_single_float32_array, elem_data_single_float64_array, elem_data_vec_float64,
74 # FBX element properties.
75 elem_properties, elem_props_set, elem_props_compound,
76 # FBX element properties handling templates.
77 elem_props_template_init, elem_props_template_set, elem_props_template_finalize,
78 # Templates.
79 FBXTemplate, fbx_templates_generate,
80 # Animation.
81 AnimationCurveNodeWrapper,
82 # Objects.
83 ObjectWrapper, fbx_name_class, ensure_object_not_in_edit_mode,
84 # Top level.
85 FBXExportSettingsMedia, FBXExportSettings, FBXExportData,
88 # Units converters!
89 convert_sec_to_ktime = units_convertor("second", "ktime")
90 convert_sec_to_ktime_iter = units_convertor_iter("second", "ktime")
92 convert_mm_to_inch = units_convertor("millimeter", "inch")
94 convert_rad_to_deg = units_convertor("radian", "degree")
95 convert_rad_to_deg_iter = units_convertor_iter("radian", "degree")
98 # ##### Templates #####
99 # TODO: check all those "default" values, they should match Blender's default as much as possible, I guess?
101 def fbx_template_def_globalsettings(scene, settings, override_defaults=None, nbr_users=0):
102 props = {}
103 if override_defaults is not None:
104 props.update(override_defaults)
105 return FBXTemplate(b"GlobalSettings", b"", props, nbr_users, [False])
108 def fbx_template_def_model(scene, settings, override_defaults=None, nbr_users=0):
109 gscale = settings.global_scale
110 props = {
111 # Name, Value, Type, Animatable
112 b"QuaternionInterpolate": (0, "p_enum", False), # 0 = no quat interpolation.
113 b"RotationOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
114 b"RotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
115 b"ScalingOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
116 b"ScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
117 b"TranslationActive": (False, "p_bool", False),
118 b"TranslationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
119 b"TranslationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
120 b"TranslationMinX": (False, "p_bool", False),
121 b"TranslationMinY": (False, "p_bool", False),
122 b"TranslationMinZ": (False, "p_bool", False),
123 b"TranslationMaxX": (False, "p_bool", False),
124 b"TranslationMaxY": (False, "p_bool", False),
125 b"TranslationMaxZ": (False, "p_bool", False),
126 b"RotationOrder": (0, "p_enum", False), # we always use 'XYZ' order.
127 b"RotationSpaceForLimitOnly": (False, "p_bool", False),
128 b"RotationStiffnessX": (0.0, "p_double", False),
129 b"RotationStiffnessY": (0.0, "p_double", False),
130 b"RotationStiffnessZ": (0.0, "p_double", False),
131 b"AxisLen": (10.0, "p_double", False),
132 b"PreRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
133 b"PostRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
134 b"RotationActive": (False, "p_bool", False),
135 b"RotationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
136 b"RotationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
137 b"RotationMinX": (False, "p_bool", False),
138 b"RotationMinY": (False, "p_bool", False),
139 b"RotationMinZ": (False, "p_bool", False),
140 b"RotationMaxX": (False, "p_bool", False),
141 b"RotationMaxY": (False, "p_bool", False),
142 b"RotationMaxZ": (False, "p_bool", False),
143 b"InheritType": (0, "p_enum", False), # RrSs
144 b"ScalingActive": (False, "p_bool", False),
145 b"ScalingMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
146 b"ScalingMax": ((1.0, 1.0, 1.0), "p_vector_3d", False),
147 b"ScalingMinX": (False, "p_bool", False),
148 b"ScalingMinY": (False, "p_bool", False),
149 b"ScalingMinZ": (False, "p_bool", False),
150 b"ScalingMaxX": (False, "p_bool", False),
151 b"ScalingMaxY": (False, "p_bool", False),
152 b"ScalingMaxZ": (False, "p_bool", False),
153 b"GeometricTranslation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
154 b"GeometricRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
155 b"GeometricScaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
156 b"MinDampRangeX": (0.0, "p_double", False),
157 b"MinDampRangeY": (0.0, "p_double", False),
158 b"MinDampRangeZ": (0.0, "p_double", False),
159 b"MaxDampRangeX": (0.0, "p_double", False),
160 b"MaxDampRangeY": (0.0, "p_double", False),
161 b"MaxDampRangeZ": (0.0, "p_double", False),
162 b"MinDampStrengthX": (0.0, "p_double", False),
163 b"MinDampStrengthY": (0.0, "p_double", False),
164 b"MinDampStrengthZ": (0.0, "p_double", False),
165 b"MaxDampStrengthX": (0.0, "p_double", False),
166 b"MaxDampStrengthY": (0.0, "p_double", False),
167 b"MaxDampStrengthZ": (0.0, "p_double", False),
168 b"PreferedAngleX": (0.0, "p_double", False),
169 b"PreferedAngleY": (0.0, "p_double", False),
170 b"PreferedAngleZ": (0.0, "p_double", False),
171 b"LookAtProperty": (None, "p_object", False),
172 b"UpVectorProperty": (None, "p_object", False),
173 b"Show": (True, "p_bool", False),
174 b"NegativePercentShapeSupport": (True, "p_bool", False),
175 b"DefaultAttributeIndex": (-1, "p_integer", False),
176 b"Freeze": (False, "p_bool", False),
177 b"LODBox": (False, "p_bool", False),
178 b"Lcl Translation": ((0.0, 0.0, 0.0), "p_lcl_translation", True),
179 b"Lcl Rotation": ((0.0, 0.0, 0.0), "p_lcl_rotation", True),
180 b"Lcl Scaling": ((1.0, 1.0, 1.0), "p_lcl_scaling", True),
181 b"Visibility": (1.0, "p_visibility", True),
182 b"Visibility Inheritance": (1, "p_visibility_inheritance", False),
184 if override_defaults is not None:
185 props.update(override_defaults)
186 return FBXTemplate(b"Model", b"FbxNode", props, nbr_users, [False])
189 def fbx_template_def_null(scene, settings, override_defaults=None, nbr_users=0):
190 props = {
191 b"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
192 b"Size": (100.0, "p_double", False),
193 b"Look": (1, "p_enum", False), # Cross (0 is None, i.e. invisible?).
195 if override_defaults is not None:
196 props.update(override_defaults)
197 return FBXTemplate(b"NodeAttribute", b"FbxNull", props, nbr_users, [False])
200 def fbx_template_def_light(scene, settings, override_defaults=None, nbr_users=0):
201 gscale = settings.global_scale
202 props = {
203 b"LightType": (0, "p_enum", False), # Point light.
204 b"CastLight": (True, "p_bool", False),
205 b"Color": ((1.0, 1.0, 1.0), "p_color", True),
206 b"Intensity": (100.0, "p_number", True), # Times 100 compared to Blender values...
207 b"DecayType": (2, "p_enum", False), # Quadratic.
208 b"DecayStart": (30.0 * gscale, "p_double", False),
209 b"CastShadows": (True, "p_bool", False),
210 b"ShadowColor": ((0.0, 0.0, 0.0), "p_color", True),
211 b"AreaLightShape": (0, "p_enum", False), # Rectangle.
213 if override_defaults is not None:
214 props.update(override_defaults)
215 return FBXTemplate(b"NodeAttribute", b"FbxLight", props, nbr_users, [False])
218 def fbx_template_def_camera(scene, settings, override_defaults=None, nbr_users=0):
219 r = scene.render
220 props = {
221 b"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
222 b"Position": ((0.0, 0.0, -50.0), "p_vector", True),
223 b"UpVector": ((0.0, 1.0, 0.0), "p_vector", True),
224 b"InterestPosition": ((0.0, 0.0, 0.0), "p_vector", True),
225 b"Roll": (0.0, "p_roll", True),
226 b"OpticalCenterX": (0.0, "p_opticalcenterx", True),
227 b"OpticalCenterY": (0.0, "p_opticalcentery", True),
228 b"BackgroundColor": ((0.63, 0.63, 0.63), "p_color", True),
229 b"TurnTable": (0.0, "p_number", True),
230 b"DisplayTurnTableIcon": (False, "p_bool", False),
231 b"UseMotionBlur": (False, "p_bool", False),
232 b"UseRealTimeMotionBlur": (True, "p_bool", False),
233 b"Motion Blur Intensity": (1.0, "p_number", True),
234 b"AspectRatioMode": (0, "p_enum", False), # WindowSize.
235 b"AspectWidth": (320.0, "p_double", False),
236 b"AspectHeight": (200.0, "p_double", False),
237 b"PixelAspectRatio": (1.0, "p_double", False),
238 b"FilmOffsetX": (0.0, "p_number", True),
239 b"FilmOffsetY": (0.0, "p_number", True),
240 b"FilmWidth": (0.816, "p_double", False),
241 b"FilmHeight": (0.612, "p_double", False),
242 b"FilmAspectRatio": (1.3333333333333333, "p_double", False),
243 b"FilmSqueezeRatio": (1.0, "p_double", False),
244 b"FilmFormatIndex": (0, "p_enum", False), # Assuming this is ApertureFormat, 0 = custom.
245 b"PreScale": (1.0, "p_number", True),
246 b"FilmTranslateX": (0.0, "p_number", True),
247 b"FilmTranslateY": (0.0, "p_number", True),
248 b"FilmRollPivotX": (0.0, "p_number", True),
249 b"FilmRollPivotY": (0.0, "p_number", True),
250 b"FilmRollValue": (0.0, "p_number", True),
251 b"FilmRollOrder": (0, "p_enum", False), # 0 = rotate first (default).
252 b"ApertureMode": (2, "p_enum", False), # 2 = Vertical.
253 b"GateFit": (0, "p_enum", False), # 0 = no resolution gate fit.
254 b"FieldOfView": (25.114999771118164, "p_fov", True),
255 b"FieldOfViewX": (40.0, "p_fov_x", True),
256 b"FieldOfViewY": (40.0, "p_fov_y", True),
257 b"FocalLength": (34.89327621672628, "p_number", True),
258 b"CameraFormat": (0, "p_enum", False), # Custom camera format.
259 b"UseFrameColor": (False, "p_bool", False),
260 b"FrameColor": ((0.3, 0.3, 0.3), "p_color_rgb", False),
261 b"ShowName": (True, "p_bool", False),
262 b"ShowInfoOnMoving": (True, "p_bool", False),
263 b"ShowGrid": (True, "p_bool", False),
264 b"ShowOpticalCenter": (False, "p_bool", False),
265 b"ShowAzimut": (True, "p_bool", False),
266 b"ShowTimeCode": (False, "p_bool", False),
267 b"ShowAudio": (False, "p_bool", False),
268 b"AudioColor": ((0.0, 1.0, 0.0), "p_vector_3d", False), # Yep, vector3d, not corlorgb… :cry:
269 b"NearPlane": (10.0, "p_double", False),
270 b"FarPlane": (4000.0, "p_double", False),
271 b"AutoComputeClipPanes": (False, "p_bool", False),
272 b"ViewCameraToLookAt": (True, "p_bool", False),
273 b"ViewFrustumNearFarPlane": (False, "p_bool", False),
274 b"ViewFrustumBackPlaneMode": (2, "p_enum", False), # 2 = show back plane if texture added.
275 b"BackPlaneDistance": (4000.0, "p_number", True),
276 b"BackPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
277 b"ViewFrustumFrontPlaneMode": (2, "p_enum", False), # 2 = show front plane if texture added.
278 b"FrontPlaneDistance": (10.0, "p_number", True),
279 b"FrontPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
280 b"LockMode": (False, "p_bool", False),
281 b"LockInterestNavigation": (False, "p_bool", False),
282 # BackPlate... properties **arggggg!**
283 b"FitImage": (False, "p_bool", False),
284 b"Crop": (False, "p_bool", False),
285 b"Center": (True, "p_bool", False),
286 b"KeepRatio": (True, "p_bool", False),
287 # End of BackPlate...
288 b"BackgroundAlphaTreshold": (0.5, "p_double", False),
289 b"ShowBackplate": (True, "p_bool", False),
290 b"BackPlaneOffsetX": (0.0, "p_number", True),
291 b"BackPlaneOffsetY": (0.0, "p_number", True),
292 b"BackPlaneRotation": (0.0, "p_number", True),
293 b"BackPlaneScaleX": (1.0, "p_number", True),
294 b"BackPlaneScaleY": (1.0, "p_number", True),
295 b"Background Texture": (None, "p_object", False),
296 b"FrontPlateFitImage": (True, "p_bool", False),
297 b"FrontPlateCrop": (False, "p_bool", False),
298 b"FrontPlateCenter": (True, "p_bool", False),
299 b"FrontPlateKeepRatio": (True, "p_bool", False),
300 b"Foreground Opacity": (1.0, "p_double", False),
301 b"ShowFrontplate": (True, "p_bool", False),
302 b"FrontPlaneOffsetX": (0.0, "p_number", True),
303 b"FrontPlaneOffsetY": (0.0, "p_number", True),
304 b"FrontPlaneRotation": (0.0, "p_number", True),
305 b"FrontPlaneScaleX": (1.0, "p_number", True),
306 b"FrontPlaneScaleY": (1.0, "p_number", True),
307 b"Foreground Texture": (None, "p_object", False),
308 b"DisplaySafeArea": (False, "p_bool", False),
309 b"DisplaySafeAreaOnRender": (False, "p_bool", False),
310 b"SafeAreaDisplayStyle": (1, "p_enum", False), # 1 = rounded corners.
311 b"SafeAreaAspectRatio": (1.3333333333333333, "p_double", False),
312 b"Use2DMagnifierZoom": (False, "p_bool", False),
313 b"2D Magnifier Zoom": (100.0, "p_number", True),
314 b"2D Magnifier X": (50.0, "p_number", True),
315 b"2D Magnifier Y": (50.0, "p_number", True),
316 b"CameraProjectionType": (0, "p_enum", False), # 0 = perspective, 1 = orthogonal.
317 b"OrthoZoom": (1.0, "p_double", False),
318 b"UseRealTimeDOFAndAA": (False, "p_bool", False),
319 b"UseDepthOfField": (False, "p_bool", False),
320 b"FocusSource": (0, "p_enum", False), # 0 = camera interest, 1 = distance from camera interest.
321 b"FocusAngle": (3.5, "p_double", False), # ???
322 b"FocusDistance": (200.0, "p_double", False),
323 b"UseAntialiasing": (False, "p_bool", False),
324 b"AntialiasingIntensity": (0.77777, "p_double", False),
325 b"AntialiasingMethod": (0, "p_enum", False), # 0 = oversampling, 1 = hardware.
326 b"UseAccumulationBuffer": (False, "p_bool", False),
327 b"FrameSamplingCount": (7, "p_integer", False),
328 b"FrameSamplingType": (1, "p_enum", False), # 0 = uniform, 1 = stochastic.
330 if override_defaults is not None:
331 props.update(override_defaults)
332 return FBXTemplate(b"NodeAttribute", b"FbxCamera", props, nbr_users, [False])
335 def fbx_template_def_bone(scene, settings, override_defaults=None, nbr_users=0):
336 props = {}
337 if override_defaults is not None:
338 props.update(override_defaults)
339 return FBXTemplate(b"NodeAttribute", b"LimbNode", props, nbr_users, [False])
342 def fbx_template_def_geometry(scene, settings, override_defaults=None, nbr_users=0):
343 props = {
344 b"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
345 b"BBoxMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
346 b"BBoxMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
347 b"Primary Visibility": (True, "p_bool", False),
348 b"Casts Shadows": (True, "p_bool", False),
349 b"Receive Shadows": (True, "p_bool", False),
351 if override_defaults is not None:
352 props.update(override_defaults)
353 return FBXTemplate(b"Geometry", b"FbxMesh", props, nbr_users, [False])
356 def fbx_template_def_material(scene, settings, override_defaults=None, nbr_users=0):
357 # WIP...
358 props = {
359 b"ShadingModel": ("Phong", "p_string", False),
360 b"MultiLayer": (False, "p_bool", False),
361 # Lambert-specific.
362 b"EmissiveColor": ((0.0, 0.0, 0.0), "p_color", True),
363 b"EmissiveFactor": (1.0, "p_number", True),
364 b"AmbientColor": ((0.2, 0.2, 0.2), "p_color", True),
365 b"AmbientFactor": (1.0, "p_number", True),
366 b"DiffuseColor": ((0.8, 0.8, 0.8), "p_color", True),
367 b"DiffuseFactor": (1.0, "p_number", True),
368 b"TransparentColor": ((0.0, 0.0, 0.0), "p_color", True),
369 b"TransparencyFactor": (0.0, "p_number", True),
370 b"Opacity": (1.0, "p_number", True),
371 b"NormalMap": ((0.0, 0.0, 0.0), "p_vector_3d", False),
372 b"Bump": ((0.0, 0.0, 0.0), "p_vector_3d", False),
373 b"BumpFactor": (1.0, "p_double", False),
374 b"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
375 b"DisplacementFactor": (1.0, "p_double", False),
376 b"VectorDisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
377 b"VectorDisplacementFactor": (1.0, "p_double", False),
378 # Phong-specific.
379 b"SpecularColor": ((0.2, 0.2, 0.2), "p_color", True),
380 b"SpecularFactor": (1.0, "p_number", True),
381 # Not sure about the name, importer uses this (but ShininessExponent for tex prop name!)
382 # And in fbx exported by sdk, you have one in template, the other in actual material!!! :/
383 # For now, using both.
384 b"Shininess": (20.0, "p_number", True),
385 b"ShininessExponent": (20.0, "p_number", True),
386 b"ReflectionColor": ((0.0, 0.0, 0.0), "p_color", True),
387 b"ReflectionFactor": (1.0, "p_number", True),
389 if override_defaults is not None:
390 props.update(override_defaults)
391 return FBXTemplate(b"Material", b"FbxSurfacePhong", props, nbr_users, [False])
394 def fbx_template_def_texture_file(scene, settings, override_defaults=None, nbr_users=0):
395 # WIP...
396 # XXX Not sure about all names!
397 props = {
398 b"TextureTypeUse": (0, "p_enum", False), # Standard.
399 b"AlphaSource": (2, "p_enum", False), # Black (i.e. texture's alpha), XXX name guessed!.
400 b"Texture alpha": (1.0, "p_double", False),
401 b"PremultiplyAlpha": (True, "p_bool", False),
402 b"CurrentTextureBlendMode": (1, "p_enum", False), # Additive...
403 b"CurrentMappingType": (0, "p_enum", False), # UV.
404 b"UVSet": ("default", "p_string", False), # UVMap name.
405 b"WrapModeU": (0, "p_enum", False), # Repeat.
406 b"WrapModeV": (0, "p_enum", False), # Repeat.
407 b"UVSwap": (False, "p_bool", False),
408 b"Translation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
409 b"Rotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
410 b"Scaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
411 b"TextureRotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
412 b"TextureScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
413 # Not sure about those two...
414 b"UseMaterial": (False, "p_bool", False),
415 b"UseMipMap": (False, "p_bool", False),
417 if override_defaults is not None:
418 props.update(override_defaults)
419 return FBXTemplate(b"Texture", b"FbxFileTexture", props, nbr_users, [False])
422 def fbx_template_def_video(scene, settings, override_defaults=None, nbr_users=0):
423 # WIP...
424 props = {
425 # All pictures.
426 b"Width": (0, "p_integer", False),
427 b"Height": (0, "p_integer", False),
428 b"Path": ("", "p_string_url", False),
429 b"AccessMode": (0, "p_enum", False), # Disk (0=Disk, 1=Mem, 2=DiskAsync).
430 # All videos.
431 b"StartFrame": (0, "p_integer", False),
432 b"StopFrame": (0, "p_integer", False),
433 b"Offset": (0, "p_timestamp", False),
434 b"PlaySpeed": (0.0, "p_double", False),
435 b"FreeRunning": (False, "p_bool", False),
436 b"Loop": (False, "p_bool", False),
437 b"InterlaceMode": (0, "p_enum", False), # None, i.e. progressive.
438 # Image sequences.
439 b"ImageSequence": (False, "p_bool", False),
440 b"ImageSequenceOffset": (0, "p_integer", False),
441 b"FrameRate": (0.0, "p_double", False),
442 b"LastFrame": (0, "p_integer", False),
444 if override_defaults is not None:
445 props.update(override_defaults)
446 return FBXTemplate(b"Video", b"FbxVideo", props, nbr_users, [False])
449 def fbx_template_def_pose(scene, settings, override_defaults=None, nbr_users=0):
450 props = {}
451 if override_defaults is not None:
452 props.update(override_defaults)
453 return FBXTemplate(b"Pose", b"", props, nbr_users, [False])
456 def fbx_template_def_deformer(scene, settings, override_defaults=None, nbr_users=0):
457 props = {}
458 if override_defaults is not None:
459 props.update(override_defaults)
460 return FBXTemplate(b"Deformer", b"", props, nbr_users, [False])
463 def fbx_template_def_animstack(scene, settings, override_defaults=None, nbr_users=0):
464 props = {
465 b"Description": ("", "p_string", False),
466 b"LocalStart": (0, "p_timestamp", False),
467 b"LocalStop": (0, "p_timestamp", False),
468 b"ReferenceStart": (0, "p_timestamp", False),
469 b"ReferenceStop": (0, "p_timestamp", False),
471 if override_defaults is not None:
472 props.update(override_defaults)
473 return FBXTemplate(b"AnimationStack", b"FbxAnimStack", props, nbr_users, [False])
476 def fbx_template_def_animlayer(scene, settings, override_defaults=None, nbr_users=0):
477 props = {
478 b"Weight": (100.0, "p_number", True),
479 b"Mute": (False, "p_bool", False),
480 b"Solo": (False, "p_bool", False),
481 b"Lock": (False, "p_bool", False),
482 b"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
483 b"BlendMode": (0, "p_enum", False),
484 b"RotationAccumulationMode": (0, "p_enum", False),
485 b"ScaleAccumulationMode": (0, "p_enum", False),
486 b"BlendModeBypass": (0, "p_ulonglong", False),
488 if override_defaults is not None:
489 props.update(override_defaults)
490 return FBXTemplate(b"AnimationLayer", b"FbxAnimLayer", props, nbr_users, [False])
493 def fbx_template_def_animcurvenode(scene, settings, override_defaults=None, nbr_users=0):
494 props = {
495 FBX_ANIM_PROPSGROUP_NAME.encode(): (None, "p_compound", False),
497 if override_defaults is not None:
498 props.update(override_defaults)
499 return FBXTemplate(b"AnimationCurveNode", b"FbxAnimCurveNode", props, nbr_users, [False])
502 def fbx_template_def_animcurve(scene, settings, override_defaults=None, nbr_users=0):
503 props = {}
504 if override_defaults is not None:
505 props.update(override_defaults)
506 return FBXTemplate(b"AnimationCurve", b"", props, nbr_users, [False])
509 # ##### Generators for connection elements. #####
511 def elem_connection(elem, c_type, uid_src, uid_dst, prop_dst=None):
512 e = elem_data_single_string(elem, b"C", c_type)
513 e.add_int64(uid_src)
514 e.add_int64(uid_dst)
515 if prop_dst is not None:
516 e.add_string(prop_dst)
519 # ##### FBX objects generators. #####
521 def fbx_data_element_custom_properties(props, bid):
523 Store custom properties of blender ID bid (any mapping-like object, in fact) into FBX properties props.
525 items = bid.items()
527 if not items:
528 return
530 rna_properties = {prop.identifier for prop in bid.bl_rna.properties if prop.is_runtime}
532 for k, v in items:
533 if k in rna_properties:
534 continue
536 list_val = getattr(v, "to_list", lambda: None)()
538 if isinstance(v, str):
539 elem_props_set(props, "p_string", k.encode(), v, custom=True)
540 elif isinstance(v, int):
541 elem_props_set(props, "p_integer", k.encode(), v, custom=True)
542 elif isinstance(v, float):
543 elem_props_set(props, "p_double", k.encode(), v, custom=True)
544 elif list_val:
545 if len(list_val) == 3:
546 elem_props_set(props, "p_vector", k.encode(), list_val, custom=True)
547 else:
548 elem_props_set(props, "p_string", k.encode(), str(list_val), custom=True)
549 else:
550 elem_props_set(props, "p_string", k.encode(), str(v), custom=True)
553 def fbx_data_empty_elements(root, empty, scene_data):
555 Write the Empty data block (you can control its FBX datatype with the 'fbx_type' string custom property).
557 empty_key = scene_data.data_empties[empty]
559 null = elem_data_single_int64(root, b"NodeAttribute", get_fbx_uuid_from_key(empty_key))
560 null.add_string(fbx_name_class(empty.name.encode(), b"NodeAttribute"))
561 val = empty.bdata.get('fbx_type', None)
562 null.add_string(val.encode() if val and isinstance(val, str) else b"Null")
564 elem_data_single_string(null, b"TypeFlags", b"Null")
566 tmpl = elem_props_template_init(scene_data.templates, b"Null")
567 props = elem_properties(null)
568 elem_props_template_finalize(tmpl, props)
570 # No custom properties, already saved with object (Model).
573 def fbx_data_light_elements(root, lamp, scene_data):
575 Write the Lamp data block.
577 gscale = scene_data.settings.global_scale
579 light_key = scene_data.data_lights[lamp]
580 do_light = True
581 do_shadow = False
582 shadow_color = Vector((0.0, 0.0, 0.0))
583 if lamp.type not in {'HEMI'}:
584 do_light = True
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", FBX_LIGHT_DECAY_TYPES['INVERSE_SQUARE'])
601 elem_props_template_set(tmpl, props, "p_double", b"DecayStart", 25.0 * gscale) # 25 is old Blender default
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)
610 # Custom properties.
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
621 cam = cam_obj.bdata
622 cam_data = cam.data
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))
630 # Render settings.
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
640 # Film offset
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)
692 # Custom properties.
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...
711 if arm_obj is None:
712 arm_obj = me_obj
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!
735 mat_world_bones = {}
736 for bo_obj in bones:
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:
751 return
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]
758 channels = []
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
773 break
774 shape_verts_weights *= 100.0
775 else:
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)
791 if write_normals:
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,
817 animatable=True)
820 def fbx_data_mesh_elements(root, me_obj, scene_data, done_meshes):
822 Write the Mesh (Geometry) data block.
824 # Ugly helper... :/
825 def _infinite_gen(val):
826 while 1:
827 yield 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:
833 return
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)
858 # Custom properties.
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.
865 write_crease = False
866 if scene_data.settings.use_subsurf:
867 last_subsurf = None
868 for mod in me_obj.bdata.modifiers:
869 if not (mod.show_render or mod.show_viewport):
870 continue
871 if mod.type == 'SUBSURF' and mod.subdivision_type == 'CATMULL_CLARK':
872 last_subsurf = mod
874 if last_subsurf:
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
878 else:
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)
891 attributes = me.attributes
893 # Vertex cos.
894 pos_fbx_dtype = np.float64
895 t_pos = MESH_ATTRIBUTE_POSITION.to_ndarray(attributes)
896 elem_data_single_float64_array(geom, b"Vertices", vcos_transformed(t_pos, geom_mat_co, pos_fbx_dtype))
897 del t_pos
899 # Polygon indices.
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
909 # C code.
910 bl_loop_index_dtype = np.uintc
912 # Start vertex indices of loops (corners). May contain elements for loops added for the export of loose edges.
913 t_lvi = MESH_ATTRIBUTE_CORNER_VERT.to_ndarray(attributes)
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
919 # of edges.
920 t_ev = MESH_ATTRIBUTE_EDGE_VERTS.to_ndarray(attributes)
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 (corners). May contain elements for loops added for the export of loose edges.
927 t_lei = MESH_ATTRIBUTE_CORNER_EDGE.to_ndarray(attributes)
929 me.polygons.foreach_get("loop_start", t_ls)
931 # Add "fake" faces for loose edges. Each "fake" face consists of two loops creating a new 2-sided polygon.
932 if scene_data.settings.use_mesh_edges:
933 bl_edge_is_loose_dtype = bool
934 # Get the mask of edges that are loose
935 loose_mask = np.empty(len(me.edges), dtype=bl_edge_is_loose_dtype)
936 me.edges.foreach_get('is_loose', loose_mask)
938 indices_of_loose_edges = np.flatnonzero(loose_mask)
939 # Since we add two loops per loose edge, repeat the indices so that there's one for each new loop
940 new_loop_edge_indices = np.repeat(indices_of_loose_edges, 2)
942 # Get the loose edge vertex index pairs
943 t_le = t_ev_pair_view[loose_mask]
945 # append will automatically flatten the pairs in t_le
946 t_lvi = np.append(t_lvi, t_le)
947 t_lei = np.append(t_lei, new_loop_edge_indices)
948 # Two loops are added per loose edge
949 loop_nbr += 2 * len(t_le)
950 t_ls = np.append(t_ls, np.arange(len(me.loops), loop_nbr, 2, dtype=t_ls.dtype))
951 del t_le
952 del loose_mask
953 del indices_of_loose_edges
954 del new_loop_edge_indices
956 # Edges...
957 # Note: Edges are represented as a loop here: each edge uses a single index, which refers to the polygon array.
958 # The edge is made by the vertex indexed py this polygon's point and the next one on the same polygon.
959 # Advantage: Only one index per edge.
960 # Drawback: Only polygon's edges can be represented (that's why we have to add fake two-verts polygons
961 # for loose edges).
962 # We also have to store a mapping from real edges to their indices in this array, for edge-mapped data
963 # (like e.g. crease).
964 eli_fbx_dtype = np.int32
966 # Edge index of each unique edge-key, used to map per-edge data to unique edge-keys (t_pvi).
967 t_pvi_edge_indices = np.empty(0, dtype=t_lei.dtype)
969 pvi_fbx_dtype = np.int32
970 if t_ls.size and t_lvi.size:
971 # Get unsorted edge keys by indexing the edge->vertex-indices array by the loop->edge-index array.
972 t_pvi_edge_keys = t_ev_pair_view[t_lei]
974 # Sort each [edge_start_n, edge_end_n] pair to get edge keys. Heapsort seems to be the fastest for this specific
975 # use case.
976 t_pvi_edge_keys.sort(axis=1, kind='heapsort')
978 # Note that finding unique edge keys means that if there are multiple edges that share the same vertices (which
979 # shouldn't normally happen), only the first edge found in loops will be exported along with its per-edge data.
980 # To export separate edges that share the same vertices, fast_first_axis_unique can be replaced with np.unique
981 # with t_lei as the first argument, finding unique edges rather than unique edge keys.
983 # Since we want the unique values in their original order, the only part we care about is the indices of the
984 # first occurrence of the unique elements in t_pvi_edge_keys, so we can use our fast uniqueness helper function.
985 t_eli = fast_first_axis_unique(t_pvi_edge_keys, return_unique=False, return_index=True)
987 # To get the indices of the elements in t_pvi_edge_keys that produce unique values, but in the original order of
988 # t_pvi_edge_keys, t_eli must be sorted.
989 # Due to loops and their edge keys tending to have a partial ordering within meshes, sorting with kind='stable'
990 # with radix sort tends to be faster than the default of kind='quicksort' with introsort.
991 t_eli.sort(kind='stable')
993 # Edge index of each element in unique t_pvi_edge_keys, used to map per-edge data such as sharp and creases.
994 t_pvi_edge_indices = t_lei[t_eli]
996 # We have to ^-1 last index of each loop.
997 # Ensure t_pvi is the correct number of bits before inverting.
998 # t_lvi may be used again later, so always create a copy to avoid modifying it in the next step.
999 t_pvi = t_lvi.astype(pvi_fbx_dtype)
1000 # The index of the end of each loop is one before the index of the start of the next loop.
1001 t_pvi[t_ls[1:] - 1] ^= -1
1002 # The index of the end of the last loop will be the very last index.
1003 t_pvi[-1] ^= -1
1004 del t_pvi_edge_keys
1005 else:
1006 # Should be empty, but make sure it's the correct type.
1007 t_pvi = np.empty(0, dtype=pvi_fbx_dtype)
1008 t_eli = np.empty(0, dtype=eli_fbx_dtype)
1010 # And finally we can write data!
1011 t_pvi = astype_view_signedness(t_pvi, pvi_fbx_dtype)
1012 t_eli = astype_view_signedness(t_eli, eli_fbx_dtype)
1013 elem_data_single_int32_array(geom, b"PolygonVertexIndex", t_pvi)
1014 elem_data_single_int32_array(geom, b"Edges", t_eli)
1015 del t_pvi
1016 del t_eli
1017 del t_ev
1018 del t_ev_pair_view
1020 # And now, layers!
1022 # Smoothing.
1023 if smooth_type in {'FACE', 'EDGE'}:
1024 ps_fbx_dtype = np.int32
1025 _map = b""
1026 if smooth_type == 'FACE':
1027 # The FBX integer values are usually interpreted as boolean where 0 is False (sharp) and 1 is True
1028 # (smooth).
1029 # The values may also be used to represent smoothing group bitflags, but this does not seem well-supported.
1030 t_ps = MESH_ATTRIBUTE_SHARP_FACE.get_ndarray(attributes)
1031 if t_ps is not None:
1032 # FBX sharp is False, but Blender sharp is True, so invert.
1033 t_ps = np.logical_not(t_ps)
1034 else:
1035 # The mesh has no "sharp_face" attribute, so every face is smooth.
1036 t_ps = np.ones(len(me.polygons), dtype=ps_fbx_dtype)
1037 _map = b"ByPolygon"
1038 else: # EDGE
1039 _map = b"ByEdge"
1040 if t_pvi_edge_indices.size:
1041 # Write Edge Smoothing.
1042 # Note edge is sharp also if it's used by more than two faces, or one of its faces is flat.
1043 mesh_poly_nbr = len(me.polygons)
1044 mesh_edge_nbr = len(me.edges)
1045 mesh_loop_nbr = len(me.loops)
1046 # t_ls and t_lei may contain extra polygons or loops added for loose edges that are not present in the
1047 # mesh data, so create views that exclude the extra data added for loose edges.
1048 mesh_t_ls_view = t_ls[:mesh_poly_nbr]
1049 mesh_t_lei_view = t_lei[:mesh_loop_nbr]
1051 # - Get sharp edges from edges used by more than two loops (and therefore more than two faces)
1052 e_more_than_two_faces_mask = np.bincount(mesh_t_lei_view, minlength=mesh_edge_nbr) > 2
1054 # - Get sharp edges from the "sharp_edge" attribute. The attribute may not exist, in which case, there
1055 # are no edges marked as sharp.
1056 e_use_sharp_mask = MESH_ATTRIBUTE_SHARP_EDGE.get_ndarray(attributes)
1057 if e_use_sharp_mask is not None:
1058 # - Combine with edges that are sharp because they're in more than two faces
1059 e_use_sharp_mask = np.logical_or(e_use_sharp_mask, e_more_than_two_faces_mask, out=e_use_sharp_mask)
1060 else:
1061 e_use_sharp_mask = e_more_than_two_faces_mask
1063 # - Get sharp edges from flat shaded faces
1064 p_flat_mask = MESH_ATTRIBUTE_SHARP_FACE.get_ndarray(attributes)
1065 if p_flat_mask is not None:
1066 # Convert flat shaded polygons to flat shaded loops by repeating each element by the number of sides
1067 # of that polygon.
1068 # Polygon sides can be calculated from the element-wise difference of loop starts appended by the
1069 # number of loops. Alternatively, polygon sides can be retrieved directly from the 'loop_total'
1070 # attribute of polygons, but since we already have t_ls, it tends to be quicker to calculate from
1071 # t_ls.
1072 polygon_sides = np.diff(mesh_t_ls_view, append=mesh_loop_nbr)
1073 p_flat_loop_mask = np.repeat(p_flat_mask, polygon_sides)
1074 # Convert flat shaded loops to flat shaded (sharp) edge indices.
1075 # Note that if an edge is in multiple loops that are part of flat shaded faces, its edge index will
1076 # end up in sharp_edge_indices_from_polygons multiple times.
1077 sharp_edge_indices_from_polygons = mesh_t_lei_view[p_flat_loop_mask]
1079 # - Combine with edges that are sharp because a polygon they're in has flat shading
1080 e_use_sharp_mask[sharp_edge_indices_from_polygons] = True
1081 del sharp_edge_indices_from_polygons
1082 del p_flat_loop_mask
1083 del polygon_sides
1084 del p_flat_mask
1086 # - Convert sharp edges to sharp edge keys (t_pvi)
1087 ek_use_sharp_mask = e_use_sharp_mask[t_pvi_edge_indices]
1089 # - Sharp edges are indicated in FBX as zero (False), so invert
1090 t_ps = np.invert(ek_use_sharp_mask, out=ek_use_sharp_mask)
1091 del ek_use_sharp_mask
1092 del e_use_sharp_mask
1093 del mesh_t_lei_view
1094 del mesh_t_ls_view
1095 else:
1096 t_ps = np.empty(0, dtype=ps_fbx_dtype)
1097 t_ps = t_ps.astype(ps_fbx_dtype, copy=False)
1098 lay_smooth = elem_data_single_int32(geom, b"LayerElementSmoothing", 0)
1099 elem_data_single_int32(lay_smooth, b"Version", FBX_GEOMETRY_SMOOTHING_VERSION)
1100 elem_data_single_string(lay_smooth, b"Name", b"")
1101 elem_data_single_string(lay_smooth, b"MappingInformationType", _map)
1102 elem_data_single_string(lay_smooth, b"ReferenceInformationType", b"Direct")
1103 elem_data_single_int32_array(lay_smooth, b"Smoothing", t_ps) # Sight, int32 for bool...
1104 del t_ps
1105 del t_ls
1106 del t_lei
1108 # Edge crease for subdivision
1109 if write_crease:
1110 ec_fbx_dtype = np.float64
1111 if t_pvi_edge_indices.size:
1112 ec_bl_dtype = np.single
1113 edge_creases = me.edge_creases
1114 if edge_creases:
1115 t_ec_raw = np.empty(len(me.edges), dtype=ec_bl_dtype)
1116 edge_creases.data.foreach_get("value", t_ec_raw)
1118 # Convert to t_pvi edge-keys.
1119 t_ec_ek_raw = t_ec_raw[t_pvi_edge_indices]
1121 # Blender squares those values before sending them to OpenSubdiv, when other software don't,
1122 # so we need to compensate that to get similar results through FBX...
1123 # Use the precision of the fbx dtype for the calculation since it's usually higher precision.
1124 t_ec_ek_raw = t_ec_ek_raw.astype(ec_fbx_dtype, copy=False)
1125 t_ec = np.square(t_ec_ek_raw, out=t_ec_ek_raw)
1126 del t_ec_ek_raw
1127 del t_ec_raw
1128 else:
1129 # todo: Blender edge creases are optional now, we may be able to avoid writing the array to FBX when
1130 # there are no edge creases.
1131 t_ec = np.zeros(t_pvi_edge_indices.shape, dtype=ec_fbx_dtype)
1132 else:
1133 t_ec = np.empty(0, dtype=ec_fbx_dtype)
1135 lay_crease = elem_data_single_int32(geom, b"LayerElementEdgeCrease", 0)
1136 elem_data_single_int32(lay_crease, b"Version", FBX_GEOMETRY_CREASE_VERSION)
1137 elem_data_single_string(lay_crease, b"Name", b"")
1138 elem_data_single_string(lay_crease, b"MappingInformationType", b"ByEdge")
1139 elem_data_single_string(lay_crease, b"ReferenceInformationType", b"Direct")
1140 elem_data_single_float64_array(lay_crease, b"EdgeCrease", t_ec)
1141 del t_ec
1143 # And we are done with edges!
1144 del t_pvi_edge_indices
1146 # Loop normals.
1147 tspacenumber = 0
1148 if write_normals:
1149 # NOTE: this is not supported by importer currently.
1150 # XXX Official docs says normals should use IndexToDirect,
1151 # but this does not seem well supported by apps currently...
1152 me.calc_normals_split()
1154 ln_bl_dtype = np.single
1155 ln_fbx_dtype = np.float64
1156 t_ln = np.empty(len(me.loops) * 3, dtype=ln_bl_dtype)
1157 me.loops.foreach_get("normal", t_ln)
1158 t_ln = nors_transformed(t_ln, geom_mat_no, ln_fbx_dtype)
1159 if 0:
1160 lnidx_fbx_dtype = np.int32
1161 lay_nor = elem_data_single_int32(geom, b"LayerElementNormal", 0)
1162 elem_data_single_int32(lay_nor, b"Version", FBX_GEOMETRY_NORMAL_VERSION)
1163 elem_data_single_string(lay_nor, b"Name", b"")
1164 elem_data_single_string(lay_nor, b"MappingInformationType", b"ByPolygonVertex")
1165 elem_data_single_string(lay_nor, b"ReferenceInformationType", b"IndexToDirect")
1167 # Tuple of unique sorted normals and then the index in the unique sorted normals of each normal in t_ln.
1168 # Since we don't care about how the normals are sorted, only that they're unique, we can use the fast unique
1169 # helper function.
1170 t_ln, t_lnidx = fast_first_axis_unique(t_ln.reshape(-1, 3), return_inverse=True)
1172 # Convert to the type for fbx
1173 t_lnidx = astype_view_signedness(t_lnidx, lnidx_fbx_dtype)
1175 elem_data_single_float64_array(lay_nor, b"Normals", t_ln)
1176 # Normal weights, no idea what it is.
1177 # t_lnw = np.zeros(len(t_ln), dtype=np.float64)
1178 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_lnw)
1180 elem_data_single_int32_array(lay_nor, b"NormalsIndex", t_lnidx)
1182 del t_lnidx
1183 # del t_lnw
1184 else:
1185 lay_nor = elem_data_single_int32(geom, b"LayerElementNormal", 0)
1186 elem_data_single_int32(lay_nor, b"Version", FBX_GEOMETRY_NORMAL_VERSION)
1187 elem_data_single_string(lay_nor, b"Name", b"")
1188 elem_data_single_string(lay_nor, b"MappingInformationType", b"ByPolygonVertex")
1189 elem_data_single_string(lay_nor, b"ReferenceInformationType", b"Direct")
1190 elem_data_single_float64_array(lay_nor, b"Normals", t_ln)
1191 # Normal weights, no idea what it is.
1192 # t_ln = np.zeros(len(me.loops), dtype=np.float64)
1193 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_ln)
1194 del t_ln
1196 # tspace
1197 if scene_data.settings.use_tspace:
1198 tspacenumber = len(me.uv_layers)
1199 if tspacenumber:
1200 # We can only compute tspace on tessellated meshes, need to check that here...
1201 lt_bl_dtype = np.uintc
1202 t_lt = np.empty(len(me.polygons), dtype=lt_bl_dtype)
1203 me.polygons.foreach_get("loop_total", t_lt)
1204 if (t_lt > 4).any():
1205 del t_lt
1206 scene_data.settings.report(
1207 {'WARNING'},
1208 tip_("Mesh '%s' has polygons with more than 4 vertices, "
1209 "cannot compute/export tangent space for it") % me.name)
1210 else:
1211 del t_lt
1212 num_loops = len(me.loops)
1213 t_ln = np.empty(num_loops * 3, dtype=ln_bl_dtype)
1214 # t_lnw = np.zeros(len(me.loops), dtype=np.float64)
1215 uv_names = [uvlayer.name for uvlayer in me.uv_layers]
1216 # Annoying, `me.calc_tangent` errors in case there is no geometry...
1217 if num_loops > 0:
1218 for name in uv_names:
1219 me.calc_tangents(uvmap=name)
1220 for idx, uvlayer in enumerate(me.uv_layers):
1221 name = uvlayer.name
1222 # Loop bitangents (aka binormals).
1223 # NOTE: this is not supported by importer currently.
1224 me.loops.foreach_get("bitangent", t_ln)
1225 lay_nor = elem_data_single_int32(geom, b"LayerElementBinormal", idx)
1226 elem_data_single_int32(lay_nor, b"Version", FBX_GEOMETRY_BINORMAL_VERSION)
1227 elem_data_single_string_unicode(lay_nor, b"Name", name)
1228 elem_data_single_string(lay_nor, b"MappingInformationType", b"ByPolygonVertex")
1229 elem_data_single_string(lay_nor, b"ReferenceInformationType", b"Direct")
1230 elem_data_single_float64_array(lay_nor, b"Binormals",
1231 nors_transformed(t_ln, geom_mat_no, ln_fbx_dtype))
1232 # Binormal weights, no idea what it is.
1233 # elem_data_single_float64_array(lay_nor, b"BinormalsW", t_lnw)
1235 # Loop tangents.
1236 # NOTE: this is not supported by importer currently.
1237 me.loops.foreach_get("tangent", t_ln)
1238 lay_nor = elem_data_single_int32(geom, b"LayerElementTangent", idx)
1239 elem_data_single_int32(lay_nor, b"Version", FBX_GEOMETRY_TANGENT_VERSION)
1240 elem_data_single_string_unicode(lay_nor, b"Name", name)
1241 elem_data_single_string(lay_nor, b"MappingInformationType", b"ByPolygonVertex")
1242 elem_data_single_string(lay_nor, b"ReferenceInformationType", b"Direct")
1243 elem_data_single_float64_array(lay_nor, b"Tangents",
1244 nors_transformed(t_ln, geom_mat_no, ln_fbx_dtype))
1245 # Tangent weights, no idea what it is.
1246 # elem_data_single_float64_array(lay_nor, b"TangentsW", t_lnw)
1248 del t_ln
1249 # del t_lnw
1250 me.free_tangents()
1252 me.free_normals_split()
1254 # Write VertexColor Layers.
1255 colors_type = scene_data.settings.colors_type
1256 vcolnumber = 0 if colors_type == 'NONE' else len(me.color_attributes)
1257 if vcolnumber:
1258 color_prop_name = "color_srgb" if colors_type == 'SRGB' else "color"
1259 # ByteColorAttribute color also gets returned by the API as single precision float
1260 bl_lc_dtype = np.single
1261 fbx_lc_dtype = np.float64
1262 fbx_lcidx_dtype = np.int32
1264 color_attributes = me.color_attributes
1265 if scene_data.settings.prioritize_active_color:
1266 active_color = me.color_attributes.active_color
1267 color_attributes = sorted(color_attributes, key=lambda x: x == active_color, reverse=True)
1269 for colindex, collayer in enumerate(color_attributes):
1270 is_point = collayer.domain == "POINT"
1271 vcollen = len(me.vertices if is_point else me.loops)
1272 # Each rgba component is flattened in the array
1273 t_lc = np.empty(vcollen * 4, dtype=bl_lc_dtype)
1274 collayer.data.foreach_get(color_prop_name, t_lc)
1275 lay_vcol = elem_data_single_int32(geom, b"LayerElementColor", colindex)
1276 elem_data_single_int32(lay_vcol, b"Version", FBX_GEOMETRY_VCOLOR_VERSION)
1277 elem_data_single_string_unicode(lay_vcol, b"Name", collayer.name)
1278 elem_data_single_string(lay_vcol, b"MappingInformationType", b"ByPolygonVertex")
1279 elem_data_single_string(lay_vcol, b"ReferenceInformationType", b"IndexToDirect")
1281 # Use the fast uniqueness helper function since we don't care about sorting.
1282 t_lc, col_indices = fast_first_axis_unique(t_lc.reshape(-1, 4), return_inverse=True)
1284 if is_point:
1285 # for "point" domain colors, we could directly emit them
1286 # with a "ByVertex" mapping type, but some software does not
1287 # properly understand that. So expand to full "ByPolygonVertex"
1288 # index map.
1289 # Ignore loops added for loose edges.
1290 col_indices = col_indices[t_lvi[:len(me.loops)]]
1292 t_lc = t_lc.astype(fbx_lc_dtype, copy=False)
1293 col_indices = astype_view_signedness(col_indices, fbx_lcidx_dtype)
1295 elem_data_single_float64_array(lay_vcol, b"Colors", t_lc)
1296 elem_data_single_int32_array(lay_vcol, b"ColorIndex", col_indices)
1298 del t_lc
1299 del col_indices
1301 # Write UV layers.
1302 # Note: LayerElementTexture is deprecated since FBX 2011 - luckily!
1303 # Textures are now only related to materials, in FBX!
1304 uvnumber = len(me.uv_layers)
1305 if uvnumber:
1306 luv_bl_dtype = np.single
1307 luv_fbx_dtype = np.float64
1308 lv_idx_fbx_dtype = np.int32
1310 t_luv = np.empty(len(me.loops) * 2, dtype=luv_bl_dtype)
1311 # Fast view for sort-based uniqueness of pairs.
1312 t_luv_fast_pair_view = fast_first_axis_flat(t_luv.reshape(-1, 2))
1313 # It must be a view of t_luv otherwise it won't update when t_luv is updated.
1314 assert(t_luv_fast_pair_view.base is t_luv)
1316 # Looks like this mapping is also expected to convey UV islands (arg..... :((((( ).
1317 # So we need to generate unique triplets (uv, vertex_idx) here, not only just based on UV values.
1318 # Ignore loops added for loose edges.
1319 t_lvidx = t_lvi[:len(me.loops)]
1321 # If we were to create a combined array of (uv, vertex_idx) elements, we could find unique triplets by sorting
1322 # that array by first sorting by the vertex_idx column and then sorting by the uv column using a stable sorting
1323 # algorithm.
1324 # This is exactly what we'll do, but without creating the combined array, because only the uv elements are
1325 # included in the export and the vertex_idx column is the same for every uv layer.
1327 # Because the vertex_idx column is the same for every uv layer, the vertex_idx column can be sorted in advance.
1328 # argsort gets the indices that sort the array, which are needed to be able to sort the array of uv pairs in the
1329 # same way to create the indices that recreate the full uvs from the unique uvs.
1330 # Loops and vertices tend to naturally have a partial ordering, which makes sorting with kind='stable' (radix
1331 # sort) faster than the default of kind='quicksort' (introsort) in most cases.
1332 perm_vidx = t_lvidx.argsort(kind='stable')
1334 # Mask and uv indices arrays will be modified and re-used by each uv layer.
1335 unique_mask = np.empty(len(me.loops), dtype=np.bool_)
1336 unique_mask[:1] = True
1337 uv_indices = np.empty(len(me.loops), dtype=lv_idx_fbx_dtype)
1339 for uvindex, uvlayer in enumerate(me.uv_layers):
1340 lay_uv = elem_data_single_int32(geom, b"LayerElementUV", uvindex)
1341 elem_data_single_int32(lay_uv, b"Version", FBX_GEOMETRY_UV_VERSION)
1342 elem_data_single_string_unicode(lay_uv, b"Name", uvlayer.name)
1343 elem_data_single_string(lay_uv, b"MappingInformationType", b"ByPolygonVertex")
1344 elem_data_single_string(lay_uv, b"ReferenceInformationType", b"IndexToDirect")
1346 uvlayer.uv.foreach_get("vector", t_luv)
1348 # t_luv_fast_pair_view is a view in a dtype that compares elements by individual bytes, but float types have
1349 # separate byte representations of positive and negative zero. For uniqueness, these should be considered
1350 # the same, so replace all -0.0 with 0.0 in advance.
1351 t_luv[t_luv == -0.0] = 0.0
1353 # These steps to create unique_uv_pairs are the same as how np.unique would find unique values by sorting a
1354 # structured array where each element is a triplet of (uv, vertex_idx), except uv and vertex_idx are
1355 # separate arrays here and vertex_idx has already been sorted in advance.
1357 # Sort according to the vertex_idx column, using the precalculated indices that sort it.
1358 sorted_t_luv_fast = t_luv_fast_pair_view[perm_vidx]
1360 # Get the indices that would sort the sorted uv pairs. Stable sorting must be used to maintain the sorting
1361 # of the vertex indices.
1362 perm_uv_pairs = sorted_t_luv_fast.argsort(kind='stable')
1363 # Use the indices to sort both the uv pairs and the vertex_idx columns.
1364 perm_combined = perm_vidx[perm_uv_pairs]
1365 sorted_vidx = t_lvidx[perm_combined]
1366 sorted_t_luv_fast = sorted_t_luv_fast[perm_uv_pairs]
1368 # Create a mask where either the uv pair doesn't equal the previous value in the array, or the vertex index
1369 # doesn't equal the previous value, these will be the unique uv-vidx triplets.
1370 # For an imaginary triplet array:
1371 # ...
1372 # [(0.4, 0.2), 0]
1373 # [(0.4, 0.2), 1] -> Unique because vertex index different from previous
1374 # [(0.4, 0.2), 2] -> Unique because vertex index different from previous
1375 # [(0.7, 0.6), 2] -> Unique because uv different from previous
1376 # [(0.7, 0.6), 2]
1377 # ...
1378 # Output the result into unique_mask.
1379 np.logical_or(sorted_t_luv_fast[1:] != sorted_t_luv_fast[:-1], sorted_vidx[1:] != sorted_vidx[:-1],
1380 out=unique_mask[1:])
1382 # Get each uv pair marked as unique by the unique_mask and then view as the original dtype.
1383 unique_uvs = sorted_t_luv_fast[unique_mask].view(luv_bl_dtype)
1385 # NaN values are considered invalid and indicate a bug somewhere else in Blender or in an addon, we want
1386 # these bugs to be reported instead of hiding them by allowing the export to continue.
1387 if np.isnan(unique_uvs).any():
1388 raise RuntimeError("UV layer %s on %r has invalid UVs containing NaN values" % (uvlayer.name, me))
1390 # Convert to the type needed for fbx
1391 unique_uvs = unique_uvs.astype(luv_fbx_dtype, copy=False)
1393 # Set the indices of pairs in unique_uvs that reconstruct the pairs in t_luv into uv_indices.
1394 # uv_indices will then be the same as an inverse array returned by np.unique with return_inverse=True.
1395 uv_indices[perm_combined] = np.cumsum(unique_mask, dtype=uv_indices.dtype) - 1
1397 elem_data_single_float64_array(lay_uv, b"UV", unique_uvs)
1398 elem_data_single_int32_array(lay_uv, b"UVIndex", uv_indices)
1399 del unique_uvs
1400 del sorted_t_luv_fast
1401 del sorted_vidx
1402 del perm_uv_pairs
1403 del perm_combined
1404 del uv_indices
1405 del unique_mask
1406 del perm_vidx
1407 del t_lvidx
1408 del t_luv
1409 del t_luv_fast_pair_view
1410 del t_lvi
1412 # Face's materials.
1413 me_fbxmaterials_idx = scene_data.mesh_material_indices.get(me)
1414 if me_fbxmaterials_idx is not None:
1415 # We cannot use me.materials here, as this array is filled with None in case materials are linked to object...
1416 me_blmaterials = me_obj.materials
1417 if me_fbxmaterials_idx and me_blmaterials:
1418 lay_ma = elem_data_single_int32(geom, b"LayerElementMaterial", 0)
1419 elem_data_single_int32(lay_ma, b"Version", FBX_GEOMETRY_MATERIAL_VERSION)
1420 elem_data_single_string(lay_ma, b"Name", b"")
1421 nbr_mats = len(me_fbxmaterials_idx)
1422 multiple_fbx_mats = nbr_mats > 1
1423 # If a mesh does not have more than one material its material_index attribute can be ignored.
1424 # If a mesh has multiple materials but all its polygons are assigned to the first material, its
1425 # material_index attribute may not exist.
1426 t_pm = None if not multiple_fbx_mats else MESH_ATTRIBUTE_MATERIAL_INDEX.get_ndarray(attributes)
1427 if t_pm is not None:
1428 fbx_pm_dtype = np.int32
1430 # We have to validate mat indices, and map them to FBX indices.
1431 # Note a mat might not be in me_fbxmaterials_idx (e.g. node mats are ignored).
1433 # The first valid material will be used for materials out of bounds of me_blmaterials or materials not
1434 # in me_fbxmaterials_idx.
1435 def_me_blmaterial_idx, def_ma = next(
1436 (i, me_fbxmaterials_idx[m]) for i, m in enumerate(me_blmaterials) if m in me_fbxmaterials_idx)
1438 # Set material indices that are out of bounds to the default material index
1439 mat_idx_limit = len(me_blmaterials)
1440 # Material indices shouldn't be negative, but they technically could be. Viewing as unsigned before
1441 # checking for indices that are too large means that a single >= check will pick up both negative
1442 # indices and indices that are too large.
1443 t_pm[t_pm.view("u%i" % t_pm.itemsize) >= mat_idx_limit] = def_me_blmaterial_idx
1445 # Map to FBX indices. Materials not in me_fbxmaterials_idx will be set to the default material index.
1446 blmat_fbx_idx = np.fromiter((me_fbxmaterials_idx.get(m, def_ma) for m in me_blmaterials),
1447 dtype=fbx_pm_dtype)
1448 t_pm = blmat_fbx_idx[t_pm]
1450 elem_data_single_string(lay_ma, b"MappingInformationType", b"ByPolygon")
1451 # XXX Logically, should be "Direct" reference type, since we do not have any index array, and have one
1452 # value per polygon...
1453 # But looks like FBX expects it to be IndexToDirect here (maybe because materials are already
1454 # indices??? *sigh*).
1455 elem_data_single_string(lay_ma, b"ReferenceInformationType", b"IndexToDirect")
1456 elem_data_single_int32_array(lay_ma, b"Materials", t_pm)
1457 else:
1458 elem_data_single_string(lay_ma, b"MappingInformationType", b"AllSame")
1459 elem_data_single_string(lay_ma, b"ReferenceInformationType", b"IndexToDirect")
1460 if multiple_fbx_mats:
1461 # There's no material_index attribute, so every material index is effectively zero.
1462 # In the order of the mesh's materials, get the FBX index of the first material that is exported.
1463 all_same_idx = next(me_fbxmaterials_idx[m] for m in me_blmaterials if m in me_fbxmaterials_idx)
1464 else:
1465 # There's only one fbx material, so the index will always be zero.
1466 all_same_idx = 0
1467 elem_data_single_int32_array(lay_ma, b"Materials", [all_same_idx])
1468 del t_pm
1470 # And the "layer TOC"...
1472 layer = elem_data_single_int32(geom, b"Layer", 0)
1473 elem_data_single_int32(layer, b"Version", FBX_GEOMETRY_LAYER_VERSION)
1474 if write_normals:
1475 lay_nor = elem_empty(layer, b"LayerElement")
1476 elem_data_single_string(lay_nor, b"Type", b"LayerElementNormal")
1477 elem_data_single_int32(lay_nor, b"TypedIndex", 0)
1478 if tspacenumber:
1479 lay_binor = elem_empty(layer, b"LayerElement")
1480 elem_data_single_string(lay_binor, b"Type", b"LayerElementBinormal")
1481 elem_data_single_int32(lay_binor, b"TypedIndex", 0)
1482 lay_tan = elem_empty(layer, b"LayerElement")
1483 elem_data_single_string(lay_tan, b"Type", b"LayerElementTangent")
1484 elem_data_single_int32(lay_tan, b"TypedIndex", 0)
1485 if smooth_type in {'FACE', 'EDGE'}:
1486 lay_smooth = elem_empty(layer, b"LayerElement")
1487 elem_data_single_string(lay_smooth, b"Type", b"LayerElementSmoothing")
1488 elem_data_single_int32(lay_smooth, b"TypedIndex", 0)
1489 if write_crease:
1490 lay_smooth = elem_empty(layer, b"LayerElement")
1491 elem_data_single_string(lay_smooth, b"Type", b"LayerElementEdgeCrease")
1492 elem_data_single_int32(lay_smooth, b"TypedIndex", 0)
1493 if vcolnumber:
1494 lay_vcol = elem_empty(layer, b"LayerElement")
1495 elem_data_single_string(lay_vcol, b"Type", b"LayerElementColor")
1496 elem_data_single_int32(lay_vcol, b"TypedIndex", 0)
1497 if uvnumber:
1498 lay_uv = elem_empty(layer, b"LayerElement")
1499 elem_data_single_string(lay_uv, b"Type", b"LayerElementUV")
1500 elem_data_single_int32(lay_uv, b"TypedIndex", 0)
1501 if me_fbxmaterials_idx is not None:
1502 lay_ma = elem_empty(layer, b"LayerElement")
1503 elem_data_single_string(lay_ma, b"Type", b"LayerElementMaterial")
1504 elem_data_single_int32(lay_ma, b"TypedIndex", 0)
1506 # Add other uv and/or vcol layers...
1507 for vcolidx, uvidx, tspaceidx in zip_longest(range(1, vcolnumber), range(1, uvnumber), range(1, tspacenumber),
1508 fillvalue=0):
1509 layer = elem_data_single_int32(geom, b"Layer", max(vcolidx, uvidx))
1510 elem_data_single_int32(layer, b"Version", FBX_GEOMETRY_LAYER_VERSION)
1511 if vcolidx:
1512 lay_vcol = elem_empty(layer, b"LayerElement")
1513 elem_data_single_string(lay_vcol, b"Type", b"LayerElementColor")
1514 elem_data_single_int32(lay_vcol, b"TypedIndex", vcolidx)
1515 if uvidx:
1516 lay_uv = elem_empty(layer, b"LayerElement")
1517 elem_data_single_string(lay_uv, b"Type", b"LayerElementUV")
1518 elem_data_single_int32(lay_uv, b"TypedIndex", uvidx)
1519 if tspaceidx:
1520 lay_binor = elem_empty(layer, b"LayerElement")
1521 elem_data_single_string(lay_binor, b"Type", b"LayerElementBinormal")
1522 elem_data_single_int32(lay_binor, b"TypedIndex", tspaceidx)
1523 lay_tan = elem_empty(layer, b"LayerElement")
1524 elem_data_single_string(lay_tan, b"Type", b"LayerElementTangent")
1525 elem_data_single_int32(lay_tan, b"TypedIndex", tspaceidx)
1527 # Shape keys...
1528 fbx_data_mesh_shapes_elements(root, me_obj, me, scene_data, tmpl, props)
1530 elem_props_template_finalize(tmpl, props)
1531 done_meshes.add(me_key)
1534 def fbx_data_material_elements(root, ma, scene_data):
1536 Write the Material data block.
1539 ambient_color = (0.0, 0.0, 0.0)
1540 if scene_data.data_world:
1541 ambient_color = next(iter(scene_data.data_world.keys())).color
1543 ma_wrap = node_shader_utils.PrincipledBSDFWrapper(ma, is_readonly=True)
1544 ma_key, _objs = scene_data.data_materials[ma]
1545 ma_type = b"Phong"
1547 fbx_ma = elem_data_single_int64(root, b"Material", get_fbx_uuid_from_key(ma_key))
1548 fbx_ma.add_string(fbx_name_class(ma.name.encode(), b"Material"))
1549 fbx_ma.add_string(b"")
1551 elem_data_single_int32(fbx_ma, b"Version", FBX_MATERIAL_VERSION)
1552 # those are not yet properties, it seems...
1553 elem_data_single_string(fbx_ma, b"ShadingModel", ma_type)
1554 elem_data_single_int32(fbx_ma, b"MultiLayer", 0) # Should be bool...
1556 tmpl = elem_props_template_init(scene_data.templates, b"Material")
1557 props = elem_properties(fbx_ma)
1559 elem_props_template_set(tmpl, props, "p_string", b"ShadingModel", ma_type.decode())
1560 elem_props_template_set(tmpl, props, "p_color", b"DiffuseColor", ma_wrap.base_color)
1561 # Not in Principled BSDF, so assuming always 1
1562 elem_props_template_set(tmpl, props, "p_number", b"DiffuseFactor", 1.0)
1563 # Principled BSDF only has an emissive color, so we assume factor to be always 1.0.
1564 elem_props_template_set(tmpl, props, "p_color", b"EmissiveColor", ma_wrap.emission_color)
1565 elem_props_template_set(tmpl, props, "p_number", b"EmissiveFactor", ma_wrap.emission_strength)
1566 # Not in Principled BSDF, so assuming always 0
1567 elem_props_template_set(tmpl, props, "p_color", b"AmbientColor", ambient_color)
1568 elem_props_template_set(tmpl, props, "p_number", b"AmbientFactor", 0.0)
1569 # Sweetness... Looks like we are not the only ones to not know exactly how FBX is supposed to work (see T59850).
1570 # According to one of its developers, Unity uses that formula to extract alpha value:
1572 # alpha = 1 - TransparencyFactor
1573 # if (alpha == 1 or alpha == 0):
1574 # alpha = 1 - TransparentColor.r
1576 # Until further info, let's assume this is correct way to do, hence the following code for TransparentColor.
1577 if ma_wrap.alpha < 1.0e-5 or ma_wrap.alpha > (1.0 - 1.0e-5):
1578 elem_props_template_set(tmpl, props, "p_color", b"TransparentColor", (1.0 - ma_wrap.alpha,) * 3)
1579 else:
1580 elem_props_template_set(tmpl, props, "p_color", b"TransparentColor", ma_wrap.base_color)
1581 elem_props_template_set(tmpl, props, "p_number", b"TransparencyFactor", 1.0 - ma_wrap.alpha)
1582 elem_props_template_set(tmpl, props, "p_number", b"Opacity", ma_wrap.alpha)
1583 elem_props_template_set(tmpl, props, "p_vector_3d", b"NormalMap", (0.0, 0.0, 0.0))
1584 elem_props_template_set(tmpl, props, "p_double", b"BumpFactor", ma_wrap.normalmap_strength)
1585 # Not sure about those...
1587 b"Bump": ((0.0, 0.0, 0.0), "p_vector_3d"),
1588 b"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb"),
1589 b"DisplacementFactor": (0.0, "p_double"),
1591 # TODO: use specular tint?
1592 elem_props_template_set(tmpl, props, "p_color", b"SpecularColor", ma_wrap.base_color)
1593 elem_props_template_set(tmpl, props, "p_number", b"SpecularFactor", ma_wrap.specular / 2.0)
1594 # See Material template about those two!
1595 # XXX Totally empirical conversion, trying to adapt it
1596 # (from 0.0 - 100.0 FBX shininess range to 1.0 - 0.0 Principled BSDF range)...
1597 shininess = (1.0 - ma_wrap.roughness) * 10
1598 shininess *= shininess
1599 elem_props_template_set(tmpl, props, "p_number", b"Shininess", shininess)
1600 elem_props_template_set(tmpl, props, "p_number", b"ShininessExponent", shininess)
1601 elem_props_template_set(tmpl, props, "p_color", b"ReflectionColor", ma_wrap.base_color)
1602 elem_props_template_set(tmpl, props, "p_number", b"ReflectionFactor", ma_wrap.metallic)
1604 elem_props_template_finalize(tmpl, props)
1606 # Custom properties.
1607 if scene_data.settings.use_custom_props:
1608 fbx_data_element_custom_properties(props, ma)
1611 def _gen_vid_path(img, scene_data):
1612 msetts = scene_data.settings.media_settings
1613 fname_rel = bpy_extras.io_utils.path_reference(img.filepath, msetts.base_src, msetts.base_dst, msetts.path_mode,
1614 msetts.subdir, msetts.copy_set, img.library)
1615 fname_abs = os.path.normpath(os.path.abspath(os.path.join(msetts.base_dst, fname_rel)))
1616 return fname_abs, fname_rel
1619 def fbx_data_texture_file_elements(root, blender_tex_key, scene_data):
1621 Write the (file) Texture data block.
1623 # XXX All this is very fuzzy to me currently...
1624 # Textures do not seem to use properties as much as they could.
1625 # For now assuming most logical and simple stuff.
1627 ma, sock_name = blender_tex_key
1628 ma_wrap = node_shader_utils.PrincipledBSDFWrapper(ma, is_readonly=True)
1629 tex_key, _fbx_prop = scene_data.data_textures[blender_tex_key]
1630 tex = getattr(ma_wrap, sock_name)
1631 img = tex.image
1632 fname_abs, fname_rel = _gen_vid_path(img, scene_data)
1634 fbx_tex = elem_data_single_int64(root, b"Texture", get_fbx_uuid_from_key(tex_key))
1635 fbx_tex.add_string(fbx_name_class(sock_name.encode(), b"Texture"))
1636 fbx_tex.add_string(b"")
1638 elem_data_single_string(fbx_tex, b"Type", b"TextureVideoClip")
1639 elem_data_single_int32(fbx_tex, b"Version", FBX_TEXTURE_VERSION)
1640 elem_data_single_string(fbx_tex, b"TextureName", fbx_name_class(sock_name.encode(), b"Texture"))
1641 elem_data_single_string(fbx_tex, b"Media", fbx_name_class(img.name.encode(), b"Video"))
1642 elem_data_single_string_unicode(fbx_tex, b"FileName", fname_abs)
1643 elem_data_single_string_unicode(fbx_tex, b"RelativeFilename", fname_rel)
1645 alpha_source = 0 # None
1646 if img.alpha_mode != 'NONE':
1647 # ~ if tex.texture.use_calculate_alpha:
1648 # ~ alpha_source = 1 # RGBIntensity as alpha.
1649 # ~ else:
1650 # ~ alpha_source = 2 # Black, i.e. alpha channel.
1651 alpha_source = 2 # Black, i.e. alpha channel.
1652 # BlendMode not useful for now, only affects layered textures afaics.
1653 mapping = 0 # UV.
1654 uvset = None
1655 if tex.texcoords == 'ORCO': # XXX Others?
1656 if tex.projection == 'FLAT':
1657 mapping = 1 # Planar
1658 elif tex.projection == 'CUBE':
1659 mapping = 4 # Box
1660 elif tex.projection == 'TUBE':
1661 mapping = 3 # Cylindrical
1662 elif tex.projection == 'SPHERE':
1663 mapping = 2 # Spherical
1664 elif tex.texcoords == 'UV':
1665 mapping = 0 # UV
1666 # Yuck, UVs are linked by mere names it seems... :/
1667 # XXX TODO how to get that now???
1668 # uvset = tex.uv_layer
1669 wrap_mode = 1 # Clamp
1670 if tex.extension == 'REPEAT':
1671 wrap_mode = 0 # Repeat
1673 tmpl = elem_props_template_init(scene_data.templates, b"TextureFile")
1674 props = elem_properties(fbx_tex)
1675 elem_props_template_set(tmpl, props, "p_enum", b"AlphaSource", alpha_source)
1676 elem_props_template_set(tmpl, props, "p_bool", b"PremultiplyAlpha",
1677 img.alpha_mode in {'STRAIGHT'}) # Or is it PREMUL?
1678 elem_props_template_set(tmpl, props, "p_enum", b"CurrentMappingType", mapping)
1679 if uvset is not None:
1680 elem_props_template_set(tmpl, props, "p_string", b"UVSet", uvset)
1681 elem_props_template_set(tmpl, props, "p_enum", b"WrapModeU", wrap_mode)
1682 elem_props_template_set(tmpl, props, "p_enum", b"WrapModeV", wrap_mode)
1683 elem_props_template_set(tmpl, props, "p_vector_3d", b"Translation", tex.translation)
1684 elem_props_template_set(tmpl, props, "p_vector_3d", b"Rotation", (-r for r in tex.rotation))
1685 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))
1686 # UseMaterial should always be ON imho.
1687 elem_props_template_set(tmpl, props, "p_bool", b"UseMaterial", True)
1688 elem_props_template_set(tmpl, props, "p_bool", b"UseMipMap", False)
1689 elem_props_template_finalize(tmpl, props)
1691 # No custom properties, since that's not a data-block anymore.
1694 def fbx_data_video_elements(root, vid, scene_data):
1696 Write the actual image data block.
1698 msetts = scene_data.settings.media_settings
1700 vid_key, _texs = scene_data.data_videos[vid]
1701 fname_abs, fname_rel = _gen_vid_path(vid, scene_data)
1703 fbx_vid = elem_data_single_int64(root, b"Video", get_fbx_uuid_from_key(vid_key))
1704 fbx_vid.add_string(fbx_name_class(vid.name.encode(), b"Video"))
1705 fbx_vid.add_string(b"Clip")
1707 elem_data_single_string(fbx_vid, b"Type", b"Clip")
1708 # XXX No Version???
1710 tmpl = elem_props_template_init(scene_data.templates, b"Video")
1711 props = elem_properties(fbx_vid)
1712 elem_props_template_set(tmpl, props, "p_string_url", b"Path", fname_abs)
1713 elem_props_template_finalize(tmpl, props)
1715 elem_data_single_int32(fbx_vid, b"UseMipMap", 0)
1716 elem_data_single_string_unicode(fbx_vid, b"Filename", fname_abs)
1717 elem_data_single_string_unicode(fbx_vid, b"RelativeFilename", fname_rel)
1719 if scene_data.settings.media_settings.embed_textures:
1720 if vid.packed_file is not None:
1721 # We only ever embed a given file once!
1722 if fname_abs not in msetts.embedded_set:
1723 elem_data_single_bytes(fbx_vid, b"Content", vid.packed_file.data)
1724 msetts.embedded_set.add(fname_abs)
1725 else:
1726 filepath = bpy.path.abspath(vid.filepath)
1727 # We only ever embed a given file once!
1728 if filepath not in msetts.embedded_set:
1729 try:
1730 with open(filepath, 'br') as f:
1731 elem_data_single_bytes(fbx_vid, b"Content", f.read())
1732 except Exception as e:
1733 print("WARNING: embedding file {} failed ({})".format(filepath, e))
1734 elem_data_single_bytes(fbx_vid, b"Content", b"")
1735 msetts.embedded_set.add(filepath)
1736 # Looks like we'd rather not write any 'Content' element in this case (see T44442).
1737 # Sounds suspect, but let's try it!
1738 #~ else:
1739 #~ elem_data_single_bytes(fbx_vid, b"Content", b"")
1741 # Blender currently has no UI for editing custom properties on Images, but the importer will import Image custom
1742 # properties from either a Video Node or a Texture Node, preferring a Video node if one exists. We'll propagate
1743 # these custom properties only to Video Nodes because that is most likely where they were imported from, and Texture
1744 # Nodes are more like Blender's Shader Nodes than Images, which is what we're exporting here.
1745 if scene_data.settings.use_custom_props:
1746 fbx_data_element_custom_properties(props, vid)
1750 def fbx_data_armature_elements(root, arm_obj, scene_data):
1752 Write:
1753 * Bones "data" (NodeAttribute::LimbNode, contains pretty much nothing!).
1754 * Deformers (i.e. Skin), bind between an armature and a mesh.
1755 ** SubDeformers (i.e. Cluster), one per bone/vgroup pair.
1756 * BindPose.
1757 Note armature itself has no data, it is a mere "Null" Model...
1759 mat_world_arm = arm_obj.fbx_object_matrix(scene_data, global_space=True)
1760 bones = tuple(bo_obj for bo_obj in arm_obj.bones if bo_obj in scene_data.objects)
1762 bone_radius_scale = 33.0
1764 # Bones "data".
1765 for bo_obj in bones:
1766 bo = bo_obj.bdata
1767 bo_data_key = scene_data.data_bones[bo_obj]
1768 fbx_bo = elem_data_single_int64(root, b"NodeAttribute", get_fbx_uuid_from_key(bo_data_key))
1769 fbx_bo.add_string(fbx_name_class(bo.name.encode(), b"NodeAttribute"))
1770 fbx_bo.add_string(b"LimbNode")
1771 elem_data_single_string(fbx_bo, b"TypeFlags", b"Skeleton")
1773 tmpl = elem_props_template_init(scene_data.templates, b"Bone")
1774 props = elem_properties(fbx_bo)
1775 elem_props_template_set(tmpl, props, "p_double", b"Size", bo.head_radius * bone_radius_scale)
1776 elem_props_template_finalize(tmpl, props)
1778 # Custom properties.
1779 if scene_data.settings.use_custom_props:
1780 fbx_data_element_custom_properties(props, bo)
1782 # Store Blender bone length - XXX Not much useful actually :/
1783 # (LimbLength can't be used because it is a scale factor 0-1 for the parent-child distance:
1784 # http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/cpp_ref/class_fbx_skeleton.html#a9bbe2a70f4ed82cd162620259e649f0f )
1785 # elem_props_set(props, "p_double", "BlenderBoneLength".encode(), (bo.tail_local - bo.head_local).length, custom=True)
1787 # Skin deformers and BindPoses.
1788 # Note: we might also use Deformers for our "parent to vertex" stuff???
1789 deformer = scene_data.data_deformers_skin.get(arm_obj, None)
1790 if deformer is not None:
1791 for me, (skin_key, ob_obj, clusters) in deformer.items():
1792 # BindPose.
1793 mat_world_obj, mat_world_bones = fbx_data_bindpose_element(root, ob_obj, me, scene_data,
1794 arm_obj, mat_world_arm, bones)
1796 # Deformer.
1797 fbx_skin = elem_data_single_int64(root, b"Deformer", get_fbx_uuid_from_key(skin_key))
1798 fbx_skin.add_string(fbx_name_class(arm_obj.name.encode(), b"Deformer"))
1799 fbx_skin.add_string(b"Skin")
1801 elem_data_single_int32(fbx_skin, b"Version", FBX_DEFORMER_SKIN_VERSION)
1802 elem_data_single_float64(fbx_skin, b"Link_DeformAcuracy", 50.0) # Only vague idea what it is...
1804 # Pre-process vertex weights (also to check vertices assigned to more than four bones).
1805 ob = ob_obj.bdata
1806 bo_vg_idx = {bo_obj.bdata.name: ob.vertex_groups[bo_obj.bdata.name].index
1807 for bo_obj in clusters.keys() if bo_obj.bdata.name in ob.vertex_groups}
1808 valid_idxs = set(bo_vg_idx.values())
1809 vgroups = {vg.index: {} for vg in ob.vertex_groups}
1810 verts_vgroups = (sorted(((vg.group, vg.weight) for vg in v.groups if vg.weight and vg.group in valid_idxs),
1811 key=lambda e: e[1], reverse=True)
1812 for v in me.vertices)
1813 for idx, vgs in enumerate(verts_vgroups):
1814 for vg_idx, w in vgs:
1815 vgroups[vg_idx][idx] = w
1817 for bo_obj, clstr_key in clusters.items():
1818 bo = bo_obj.bdata
1819 # Find which vertices are affected by this bone/vgroup pair, and matching weights.
1820 # Note we still write a cluster for bones not affecting the mesh, to get 'rest pose' data
1821 # (the TransformBlah matrices).
1822 vg_idx = bo_vg_idx.get(bo.name, None)
1823 indices, weights = ((), ()) if vg_idx is None or not vgroups[vg_idx] else zip(*vgroups[vg_idx].items())
1825 # Create the cluster.
1826 fbx_clstr = elem_data_single_int64(root, b"Deformer", get_fbx_uuid_from_key(clstr_key))
1827 fbx_clstr.add_string(fbx_name_class(bo.name.encode(), b"SubDeformer"))
1828 fbx_clstr.add_string(b"Cluster")
1830 elem_data_single_int32(fbx_clstr, b"Version", FBX_DEFORMER_CLUSTER_VERSION)
1831 # No idea what that user data might be...
1832 fbx_userdata = elem_data_single_string(fbx_clstr, b"UserData", b"")
1833 fbx_userdata.add_string(b"")
1834 if indices:
1835 elem_data_single_int32_array(fbx_clstr, b"Indexes", indices)
1836 elem_data_single_float64_array(fbx_clstr, b"Weights", weights)
1837 # Transform, TransformLink and TransformAssociateModel matrices...
1838 # They seem to be doublons of BindPose ones??? Have armature (associatemodel) in addition, though.
1839 # WARNING! Even though official FBX API presents Transform in global space,
1840 # **it is stored in bone space in FBX data!** See:
1841 # http://area.autodesk.com/forum/autodesk-fbx/fbx-sdk/why-the-values-return-
1842 # by-fbxcluster-gettransformmatrix-x-not-same-with-the-value-in-ascii-fbx-file/
1843 elem_data_single_float64_array(fbx_clstr, b"Transform",
1844 matrix4_to_array(mat_world_bones[bo_obj].inverted_safe() @ mat_world_obj))
1845 elem_data_single_float64_array(fbx_clstr, b"TransformLink", matrix4_to_array(mat_world_bones[bo_obj]))
1846 elem_data_single_float64_array(fbx_clstr, b"TransformAssociateModel", matrix4_to_array(mat_world_arm))
1849 def fbx_data_leaf_bone_elements(root, scene_data):
1850 # Write a dummy leaf bone that is used by applications to show the length of the last bone in a chain
1851 for (node_name, _par_uuid, node_uuid, attr_uuid, matrix, hide, size) in scene_data.data_leaf_bones:
1852 # Bone 'data'...
1853 fbx_bo = elem_data_single_int64(root, b"NodeAttribute", attr_uuid)
1854 fbx_bo.add_string(fbx_name_class(node_name.encode(), b"NodeAttribute"))
1855 fbx_bo.add_string(b"LimbNode")
1856 elem_data_single_string(fbx_bo, b"TypeFlags", b"Skeleton")
1858 tmpl = elem_props_template_init(scene_data.templates, b"Bone")
1859 props = elem_properties(fbx_bo)
1860 elem_props_template_set(tmpl, props, "p_double", b"Size", size)
1861 elem_props_template_finalize(tmpl, props)
1863 # And bone object.
1864 model = elem_data_single_int64(root, b"Model", node_uuid)
1865 model.add_string(fbx_name_class(node_name.encode(), b"Model"))
1866 model.add_string(b"LimbNode")
1868 elem_data_single_int32(model, b"Version", FBX_MODELS_VERSION)
1870 # Object transform info.
1871 loc, rot, scale = matrix.decompose()
1872 rot = rot.to_euler('XYZ')
1873 rot = tuple(convert_rad_to_deg_iter(rot))
1875 tmpl = elem_props_template_init(scene_data.templates, b"Model")
1876 # For now add only loc/rot/scale...
1877 props = elem_properties(model)
1878 # Generated leaf bones are obviously never animated!
1879 elem_props_template_set(tmpl, props, "p_lcl_translation", b"Lcl Translation", loc)
1880 elem_props_template_set(tmpl, props, "p_lcl_rotation", b"Lcl Rotation", rot)
1881 elem_props_template_set(tmpl, props, "p_lcl_scaling", b"Lcl Scaling", scale)
1882 elem_props_template_set(tmpl, props, "p_visibility", b"Visibility", float(not hide))
1884 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1885 # invalid -1 value...
1886 elem_props_template_set(tmpl, props, "p_integer", b"DefaultAttributeIndex", 0)
1888 elem_props_template_set(tmpl, props, "p_enum", b"InheritType", 1) # RSrs
1890 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1891 # object type, etc.
1892 elem_data_single_int32(model, b"MultiLayer", 0)
1893 elem_data_single_int32(model, b"MultiTake", 0)
1894 elem_data_single_bool(model, b"Shading", True)
1895 elem_data_single_string(model, b"Culling", b"CullingOff")
1897 elem_props_template_finalize(tmpl, props)
1900 def fbx_data_object_elements(root, ob_obj, scene_data):
1902 Write the Object (Model) data blocks.
1903 Note this "Model" can also be bone or dupli!
1905 obj_type = b"Null" # default, sort of empty...
1906 if ob_obj.is_bone:
1907 obj_type = b"LimbNode"
1908 elif (ob_obj.type == 'ARMATURE'):
1909 if scene_data.settings.armature_nodetype == 'ROOT':
1910 obj_type = b"Root"
1911 elif scene_data.settings.armature_nodetype == 'LIMBNODE':
1912 obj_type = b"LimbNode"
1913 else: # Default, preferred option...
1914 obj_type = b"Null"
1915 elif (ob_obj.type in BLENDER_OBJECT_TYPES_MESHLIKE):
1916 obj_type = b"Mesh"
1917 elif (ob_obj.type == 'LIGHT'):
1918 obj_type = b"Light"
1919 elif (ob_obj.type == 'CAMERA'):
1920 obj_type = b"Camera"
1921 model = elem_data_single_int64(root, b"Model", ob_obj.fbx_uuid)
1922 model.add_string(fbx_name_class(ob_obj.name.encode(), b"Model"))
1923 model.add_string(obj_type)
1925 elem_data_single_int32(model, b"Version", FBX_MODELS_VERSION)
1927 # Object transform info.
1928 loc, rot, scale, matrix, matrix_rot = ob_obj.fbx_object_tx(scene_data)
1929 rot = tuple(convert_rad_to_deg_iter(rot))
1931 tmpl = elem_props_template_init(scene_data.templates, b"Model")
1932 # For now add only loc/rot/scale...
1933 props = elem_properties(model)
1934 elem_props_template_set(tmpl, props, "p_lcl_translation", b"Lcl Translation", loc,
1935 animatable=True, animated=((ob_obj.key, "Lcl Translation") in scene_data.animated))
1936 elem_props_template_set(tmpl, props, "p_lcl_rotation", b"Lcl Rotation", rot,
1937 animatable=True, animated=((ob_obj.key, "Lcl Rotation") in scene_data.animated))
1938 elem_props_template_set(tmpl, props, "p_lcl_scaling", b"Lcl Scaling", scale,
1939 animatable=True, animated=((ob_obj.key, "Lcl Scaling") in scene_data.animated))
1940 elem_props_template_set(tmpl, props, "p_visibility", b"Visibility", float(not ob_obj.hide))
1942 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1943 # invalid -1 value...
1944 elem_props_template_set(tmpl, props, "p_integer", b"DefaultAttributeIndex", 0)
1946 elem_props_template_set(tmpl, props, "p_enum", b"InheritType", 1) # RSrs
1948 # Custom properties.
1949 if scene_data.settings.use_custom_props:
1950 # Here we want customprops from the 'pose' bone, not the 'edit' bone...
1951 bdata = ob_obj.bdata_pose_bone if ob_obj.is_bone else ob_obj.bdata
1952 fbx_data_element_custom_properties(props, bdata)
1954 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1955 # object type, etc.
1956 elem_data_single_int32(model, b"MultiLayer", 0)
1957 elem_data_single_int32(model, b"MultiTake", 0)
1958 elem_data_single_bool(model, b"Shading", True)
1959 elem_data_single_string(model, b"Culling", b"CullingOff")
1961 if obj_type == b"Camera":
1962 # Why, oh why are FBX cameras such a mess???
1963 # And WHY add camera data HERE??? Not even sure this is needed...
1964 render = scene_data.scene.render
1965 width = render.resolution_x * 1.0
1966 height = render.resolution_y * 1.0
1967 elem_props_template_set(tmpl, props, "p_enum", b"ResolutionMode", 0) # Don't know what it means
1968 elem_props_template_set(tmpl, props, "p_double", b"AspectW", width)
1969 elem_props_template_set(tmpl, props, "p_double", b"AspectH", height)
1970 elem_props_template_set(tmpl, props, "p_bool", b"ViewFrustum", True)
1971 elem_props_template_set(tmpl, props, "p_enum", b"BackgroundMode", 0) # Don't know what it means
1972 elem_props_template_set(tmpl, props, "p_bool", b"ForegroundTransparent", True)
1974 elem_props_template_finalize(tmpl, props)
1977 def fbx_data_animation_elements(root, scene_data):
1979 Write animation data.
1981 animations = scene_data.animations
1982 if not animations:
1983 return
1984 scene = scene_data.scene
1986 fps = scene.render.fps / scene.render.fps_base
1988 def keys_to_ktimes(keys):
1989 return (int(v) for v in convert_sec_to_ktime_iter((f / fps for f, _v in keys)))
1991 # Animation stacks.
1992 for astack_key, alayers, alayer_key, name, f_start, f_end in animations:
1993 astack = elem_data_single_int64(root, b"AnimationStack", get_fbx_uuid_from_key(astack_key))
1994 astack.add_string(fbx_name_class(name, b"AnimStack"))
1995 astack.add_string(b"")
1997 astack_tmpl = elem_props_template_init(scene_data.templates, b"AnimationStack")
1998 astack_props = elem_properties(astack)
1999 r = scene_data.scene.render
2000 fps = r.fps / r.fps_base
2001 start = int(convert_sec_to_ktime(f_start / fps))
2002 end = int(convert_sec_to_ktime(f_end / fps))
2003 elem_props_template_set(astack_tmpl, astack_props, "p_timestamp", b"LocalStart", start)
2004 elem_props_template_set(astack_tmpl, astack_props, "p_timestamp", b"LocalStop", end)
2005 elem_props_template_set(astack_tmpl, astack_props, "p_timestamp", b"ReferenceStart", start)
2006 elem_props_template_set(astack_tmpl, astack_props, "p_timestamp", b"ReferenceStop", end)
2007 elem_props_template_finalize(astack_tmpl, astack_props)
2009 # For now, only one layer for all animations.
2010 alayer = elem_data_single_int64(root, b"AnimationLayer", get_fbx_uuid_from_key(alayer_key))
2011 alayer.add_string(fbx_name_class(name, b"AnimLayer"))
2012 alayer.add_string(b"")
2014 for ob_obj, (alayer_key, acurvenodes) in alayers.items():
2015 # Animation layer.
2016 # alayer = elem_data_single_int64(root, b"AnimationLayer", get_fbx_uuid_from_key(alayer_key))
2017 # alayer.add_string(fbx_name_class(ob_obj.name.encode(), b"AnimLayer"))
2018 # alayer.add_string(b"")
2020 for fbx_prop, (acurvenode_key, acurves, acurvenode_name) in acurvenodes.items():
2021 # Animation curve node.
2022 acurvenode = elem_data_single_int64(root, b"AnimationCurveNode", get_fbx_uuid_from_key(acurvenode_key))
2023 acurvenode.add_string(fbx_name_class(acurvenode_name.encode(), b"AnimCurveNode"))
2024 acurvenode.add_string(b"")
2026 acn_tmpl = elem_props_template_init(scene_data.templates, b"AnimationCurveNode")
2027 acn_props = elem_properties(acurvenode)
2029 for fbx_item, (acurve_key, def_value, keys, _acurve_valid) in acurves.items():
2030 elem_props_template_set(acn_tmpl, acn_props, "p_number", fbx_item.encode(),
2031 def_value, animatable=True)
2033 # Only create Animation curve if needed!
2034 if keys:
2035 acurve = elem_data_single_int64(root, b"AnimationCurve", get_fbx_uuid_from_key(acurve_key))
2036 acurve.add_string(fbx_name_class(b"", b"AnimCurve"))
2037 acurve.add_string(b"")
2039 # key attributes...
2040 nbr_keys = len(keys)
2041 # flags...
2042 keyattr_flags = (
2043 1 << 2 | # interpolation mode, 1 = constant, 2 = linear, 3 = cubic.
2044 1 << 8 | # tangent mode, 8 = auto, 9 = TCB, 10 = user, 11 = generic break,
2045 1 << 13 | # tangent mode, 12 = generic clamp, 13 = generic time independent,
2046 1 << 14 | # tangent mode, 13 + 14 = generic clamp progressive.
2049 # Maybe values controlling TCB & co???
2050 keyattr_datafloat = (0.0, 0.0, 9.419963346924634e-30, 0.0)
2052 # And now, the *real* data!
2053 elem_data_single_float64(acurve, b"Default", def_value)
2054 elem_data_single_int32(acurve, b"KeyVer", FBX_ANIM_KEY_VERSION)
2055 elem_data_single_int64_array(acurve, b"KeyTime", keys_to_ktimes(keys))
2056 elem_data_single_float32_array(acurve, b"KeyValueFloat", (v for _f, v in keys))
2057 elem_data_single_int32_array(acurve, b"KeyAttrFlags", keyattr_flags)
2058 elem_data_single_float32_array(acurve, b"KeyAttrDataFloat", keyattr_datafloat)
2059 elem_data_single_int32_array(acurve, b"KeyAttrRefCount", (nbr_keys,))
2061 elem_props_template_finalize(acn_tmpl, acn_props)
2064 # ##### Top-level FBX data container. #####
2066 # Mapping Blender -> FBX (principled_socket_name, fbx_name).
2067 PRINCIPLED_TEXTURE_SOCKETS_TO_FBX = (
2068 # ("diffuse", "diffuse", b"DiffuseFactor"),
2069 ("base_color_texture", b"DiffuseColor"),
2070 ("alpha_texture", b"TransparencyFactor"), # Will be inverted in fact, not much we can do really...
2071 # ("base_color_texture", b"TransparentColor"), # Uses diffuse color in Blender!
2072 ("emission_strength_texture", b"EmissiveFactor"),
2073 ("emission_color_texture", b"EmissiveColor"),
2074 # ("ambient", "ambient", b"AmbientFactor"),
2075 # ("", "", b"AmbientColor"), # World stuff in Blender, for now ignore...
2076 ("normalmap_texture", b"NormalMap"),
2077 # Note: unsure about those... :/
2078 # ("", "", b"Bump"),
2079 # ("", "", b"BumpFactor"),
2080 # ("", "", b"DisplacementColor"),
2081 # ("", "", b"DisplacementFactor"),
2082 ("specular_texture", b"SpecularFactor"),
2083 # ("base_color", b"SpecularColor"), # TODO: use tint?
2084 # See Material template about those two!
2085 ("roughness_texture", b"Shininess"),
2086 ("roughness_texture", b"ShininessExponent"),
2087 # ("mirror", "mirror", b"ReflectionColor"),
2088 ("metallic_texture", b"ReflectionFactor"),
2092 def fbx_skeleton_from_armature(scene, settings, arm_obj, objects, data_meshes,
2093 data_bones, data_deformers_skin, data_empties, arm_parents):
2095 Create skeleton from armature/bones (NodeAttribute/LimbNode and Model/LimbNode), and for each deformed mesh,
2096 create Pose/BindPose(with sub PoseNode) and Deformer/Skin(with Deformer/SubDeformer/Cluster).
2097 Also supports "parent to bone" (simple parent to Model/LimbNode).
2098 arm_parents is a set of tuples (armature, object) for all successful armature bindings.
2100 # We need some data for our armature 'object' too!!!
2101 data_empties[arm_obj] = get_blender_empty_key(arm_obj.bdata)
2103 arm_data = arm_obj.bdata.data
2104 bones = {}
2105 for bo in arm_obj.bones:
2106 if settings.use_armature_deform_only:
2107 if bo.bdata.use_deform:
2108 bones[bo] = True
2109 bo_par = bo.parent
2110 while bo_par.is_bone:
2111 bones[bo_par] = True
2112 bo_par = bo_par.parent
2113 elif bo not in bones: # Do not override if already set in the loop above!
2114 bones[bo] = False
2115 else:
2116 bones[bo] = True
2118 bones = {bo: None for bo, use in bones.items() if use}
2120 if not bones:
2121 return
2123 data_bones.update((bo, get_blender_bone_key(arm_obj.bdata, bo.bdata)) for bo in bones)
2125 for ob_obj in objects:
2126 if not ob_obj.is_deformed_by_armature(arm_obj):
2127 continue
2129 # Always handled by an Armature modifier...
2130 found = False
2131 for mod in ob_obj.bdata.modifiers:
2132 if mod.type not in {'ARMATURE'} or not mod.object:
2133 continue
2134 # We only support vertex groups binding method, not bone envelopes one!
2135 if mod.object == arm_obj.bdata and mod.use_vertex_groups:
2136 found = True
2137 break
2139 if not found:
2140 continue
2142 # Now we have a mesh using this armature.
2143 # Note: bindpose have no relations at all (no connections), so no need for any preprocess for them.
2144 # Create skin & clusters relations (note skins are connected to geometry, *not* model!).
2145 _key, me, _free = data_meshes[ob_obj]
2146 clusters = {bo: get_blender_bone_cluster_key(arm_obj.bdata, me, bo.bdata) for bo in bones}
2147 data_deformers_skin.setdefault(arm_obj, {})[me] = (get_blender_armature_skin_key(arm_obj.bdata, me),
2148 ob_obj, clusters)
2150 # We don't want a regular parent relationship for those in FBX...
2151 arm_parents.add((arm_obj, ob_obj))
2152 # Needed to handle matrices/spaces (since we do not parent them to 'armature' in FBX :/ ).
2153 ob_obj.parented_to_armature = True
2155 objects.update(bones)
2158 def fbx_generate_leaf_bones(settings, data_bones):
2159 # find which bons have no children
2160 child_count = {bo: 0 for bo in data_bones.keys()}
2161 for bo in data_bones.keys():
2162 if bo.parent and bo.parent.is_bone:
2163 child_count[bo.parent] += 1
2165 bone_radius_scale = settings.global_scale * 33.0
2167 # generate bone data
2168 leaf_parents = [bo for bo, count in child_count.items() if count == 0]
2169 leaf_bones = []
2170 for parent in leaf_parents:
2171 node_name = parent.name + "_end"
2172 parent_uuid = parent.fbx_uuid
2173 parent_key = parent.key
2174 node_uuid = get_fbx_uuid_from_key(parent_key + "_end_node")
2175 attr_uuid = get_fbx_uuid_from_key(parent_key + "_end_nodeattr")
2177 hide = parent.hide
2178 size = parent.bdata.head_radius * bone_radius_scale
2179 bone_length = (parent.bdata.tail_local - parent.bdata.head_local).length
2180 matrix = Matrix.Translation((0, bone_length, 0))
2181 if settings.bone_correction_matrix_inv:
2182 matrix = settings.bone_correction_matrix_inv @ matrix
2183 if settings.bone_correction_matrix:
2184 matrix = matrix @ settings.bone_correction_matrix
2185 leaf_bones.append((node_name, parent_uuid, node_uuid, attr_uuid, matrix, hide, size))
2187 return leaf_bones
2190 def fbx_animations_do(scene_data, ref_id, f_start, f_end, start_zero, objects=None, force_keep=False):
2192 Generate animation data (a single AnimStack) from objects, for a given frame range.
2194 bake_step = scene_data.settings.bake_anim_step
2195 simplify_fac = scene_data.settings.bake_anim_simplify_factor
2196 scene = scene_data.scene
2197 depsgraph = scene_data.depsgraph
2198 force_keying = scene_data.settings.bake_anim_use_all_bones
2199 force_sek = scene_data.settings.bake_anim_force_startend_keying
2200 gscale = scene_data.settings.global_scale
2202 if objects is not None:
2203 # Add bones and duplis!
2204 for ob_obj in tuple(objects):
2205 if not ob_obj.is_object:
2206 continue
2207 if ob_obj.type == 'ARMATURE':
2208 objects |= {bo_obj for bo_obj in ob_obj.bones if bo_obj in scene_data.objects}
2209 for dp_obj in ob_obj.dupli_list_gen(depsgraph):
2210 if dp_obj in scene_data.objects:
2211 objects.add(dp_obj)
2212 else:
2213 objects = scene_data.objects
2215 back_currframe = scene.frame_current
2216 animdata_ob = {}
2217 p_rots = {}
2219 for ob_obj in objects:
2220 if ob_obj.parented_to_armature:
2221 continue
2222 ACNW = AnimationCurveNodeWrapper
2223 loc, rot, scale, _m, _mr = ob_obj.fbx_object_tx(scene_data)
2224 rot_deg = tuple(convert_rad_to_deg_iter(rot))
2225 force_key = (simplify_fac == 0.0) or (ob_obj.is_bone and force_keying)
2226 animdata_ob[ob_obj] = (ACNW(ob_obj.key, 'LCL_TRANSLATION', force_key, force_sek, loc),
2227 ACNW(ob_obj.key, 'LCL_ROTATION', force_key, force_sek, rot_deg),
2228 ACNW(ob_obj.key, 'LCL_SCALING', force_key, force_sek, scale))
2229 p_rots[ob_obj] = rot
2231 force_key = (simplify_fac == 0.0)
2232 animdata_shapes = {}
2234 for me, (me_key, _shapes_key, shapes) in scene_data.data_deformers_shape.items():
2235 # Ignore absolute shape keys for now!
2236 if not me.shape_keys.use_relative:
2237 continue
2238 for shape, (channel_key, geom_key, _shape_verts_co, _shape_verts_idx) in shapes.items():
2239 acnode = AnimationCurveNodeWrapper(channel_key, 'SHAPE_KEY', force_key, force_sek, (0.0,))
2240 # Sooooo happy to have to twist again like a mad snake... Yes, we need to write those curves twice. :/
2241 acnode.add_group(me_key, shape.name, shape.name, (shape.name,))
2242 animdata_shapes[channel_key] = (acnode, me, shape)
2244 animdata_cameras = {}
2245 for cam_obj, cam_key in scene_data.data_cameras.items():
2246 cam = cam_obj.bdata.data
2247 acnode_lens = AnimationCurveNodeWrapper(cam_key, 'CAMERA_FOCAL', force_key, force_sek, (cam.lens,))
2248 acnode_focus_distance = AnimationCurveNodeWrapper(cam_key, 'CAMERA_FOCUS_DISTANCE', force_key,
2249 force_sek, (cam.dof.focus_distance,))
2250 animdata_cameras[cam_key] = (acnode_lens, acnode_focus_distance, cam)
2252 currframe = f_start
2253 while currframe <= f_end:
2254 real_currframe = currframe - f_start if start_zero else currframe
2255 scene.frame_set(int(currframe), subframe=currframe - int(currframe))
2257 for dp_obj in ob_obj.dupli_list_gen(depsgraph):
2258 pass # Merely updating dupli matrix of ObjectWrapper...
2259 for ob_obj, (anim_loc, anim_rot, anim_scale) in animdata_ob.items():
2260 # We compute baked loc/rot/scale for all objects (rot being euler-compat with previous value!).
2261 p_rot = p_rots.get(ob_obj, None)
2262 loc, rot, scale, _m, _mr = ob_obj.fbx_object_tx(scene_data, rot_euler_compat=p_rot)
2263 p_rots[ob_obj] = rot
2264 anim_loc.add_keyframe(real_currframe, loc)
2265 anim_rot.add_keyframe(real_currframe, tuple(convert_rad_to_deg_iter(rot)))
2266 anim_scale.add_keyframe(real_currframe, scale)
2267 for anim_shape, me, shape in animdata_shapes.values():
2268 anim_shape.add_keyframe(real_currframe, (shape.value * 100.0,))
2269 for anim_camera_lens, anim_camera_focus_distance, camera in animdata_cameras.values():
2270 anim_camera_lens.add_keyframe(real_currframe, (camera.lens,))
2271 anim_camera_focus_distance.add_keyframe(real_currframe, (camera.dof.focus_distance * 1000 * gscale,))
2272 currframe += bake_step
2274 scene.frame_set(back_currframe, subframe=0.0)
2276 animations = {}
2278 # And now, produce final data (usable by FBX export code)
2279 # Objects-like loc/rot/scale...
2280 for ob_obj, anims in animdata_ob.items():
2281 for anim in anims:
2282 anim.simplify(simplify_fac, bake_step, force_keep)
2283 if not anim:
2284 continue
2285 for obj_key, group_key, group, fbx_group, fbx_gname in anim.get_final_data(scene, ref_id, force_keep):
2286 anim_data = animations.setdefault(obj_key, ("dummy_unused_key", {}))
2287 anim_data[1][fbx_group] = (group_key, group, fbx_gname)
2289 # And meshes' shape keys.
2290 for channel_key, (anim_shape, me, shape) in animdata_shapes.items():
2291 final_keys = {}
2292 anim_shape.simplify(simplify_fac, bake_step, force_keep)
2293 if not anim_shape:
2294 continue
2295 for elem_key, group_key, group, fbx_group, fbx_gname in anim_shape.get_final_data(scene, ref_id, force_keep):
2296 anim_data = animations.setdefault(elem_key, ("dummy_unused_key", {}))
2297 anim_data[1][fbx_group] = (group_key, group, fbx_gname)
2299 # And cameras' lens and focus distance keys.
2300 for cam_key, (anim_camera_lens, anim_camera_focus_distance, camera) in animdata_cameras.items():
2301 final_keys = {}
2302 anim_camera_lens.simplify(simplify_fac, bake_step, force_keep)
2303 anim_camera_focus_distance.simplify(simplify_fac, bake_step, force_keep)
2304 if anim_camera_lens:
2305 for elem_key, group_key, group, fbx_group, fbx_gname in \
2306 anim_camera_lens.get_final_data(scene, ref_id, force_keep):
2307 anim_data = animations.setdefault(elem_key, ("dummy_unused_key", {}))
2308 anim_data[1][fbx_group] = (group_key, group, fbx_gname)
2309 if anim_camera_focus_distance:
2310 for elem_key, group_key, group, fbx_group, fbx_gname in \
2311 anim_camera_focus_distance.get_final_data(scene, ref_id, force_keep):
2312 anim_data = animations.setdefault(elem_key, ("dummy_unused_key", {}))
2313 anim_data[1][fbx_group] = (group_key, group, fbx_gname)
2315 astack_key = get_blender_anim_stack_key(scene, ref_id)
2316 alayer_key = get_blender_anim_layer_key(scene, ref_id)
2317 name = (get_blenderID_name(ref_id) if ref_id else scene.name).encode()
2319 if start_zero:
2320 f_end -= f_start
2321 f_start = 0.0
2323 return (astack_key, animations, alayer_key, name, f_start, f_end) if animations else None
2326 def fbx_animations(scene_data):
2328 Generate global animation data from objects.
2330 scene = scene_data.scene
2331 animations = []
2332 animated = set()
2333 frame_start = 1e100
2334 frame_end = -1e100
2336 def add_anim(animations, animated, anim):
2337 nonlocal frame_start, frame_end
2338 if anim is not None:
2339 animations.append(anim)
2340 f_start, f_end = anim[4:6]
2341 if f_start < frame_start:
2342 frame_start = f_start
2343 if f_end > frame_end:
2344 frame_end = f_end
2346 _astack_key, astack, _alayer_key, _name, _fstart, _fend = anim
2347 for elem_key, (alayer_key, acurvenodes) in astack.items():
2348 for fbx_prop, (acurvenode_key, acurves, acurvenode_name) in acurvenodes.items():
2349 animated.add((elem_key, fbx_prop))
2351 # Per-NLA strip animstacks.
2352 if scene_data.settings.bake_anim_use_nla_strips:
2353 strips = []
2354 ob_actions = []
2355 for ob_obj in scene_data.objects:
2356 # NLA tracks only for objects, not bones!
2357 if not ob_obj.is_object:
2358 continue
2359 ob = ob_obj.bdata # Back to real Blender Object.
2360 if not ob.animation_data:
2361 continue
2363 # Some actions are read-only, one cause is being in NLA tweakmode
2364 restore_use_tweak_mode = ob.animation_data.use_tweak_mode
2365 if ob.animation_data.is_property_readonly('action'):
2366 ob.animation_data.use_tweak_mode = False
2368 # We have to remove active action from objects, it overwrites strips actions otherwise...
2369 ob_actions.append((ob, ob.animation_data.action, restore_use_tweak_mode))
2370 ob.animation_data.action = None
2371 for track in ob.animation_data.nla_tracks:
2372 if track.mute:
2373 continue
2374 for strip in track.strips:
2375 if strip.mute:
2376 continue
2377 strips.append(strip)
2378 strip.mute = True
2380 for strip in strips:
2381 strip.mute = False
2382 add_anim(animations, animated,
2383 fbx_animations_do(scene_data, strip, strip.frame_start, strip.frame_end, True, force_keep=True))
2384 strip.mute = True
2385 scene.frame_set(scene.frame_current, subframe=0.0)
2387 for strip in strips:
2388 strip.mute = False
2390 for ob, ob_act, restore_use_tweak_mode in ob_actions:
2391 ob.animation_data.action = ob_act
2392 ob.animation_data.use_tweak_mode = restore_use_tweak_mode
2394 # All actions.
2395 if scene_data.settings.bake_anim_use_all_actions:
2396 def validate_actions(act, path_resolve):
2397 for fc in act.fcurves:
2398 data_path = fc.data_path
2399 if fc.array_index:
2400 data_path = data_path + "[%d]" % fc.array_index
2401 try:
2402 path_resolve(data_path)
2403 except ValueError:
2404 return False # Invalid.
2405 return True # Valid.
2407 def restore_object(ob_to, ob_from):
2408 # Restore org state of object (ugh :/ ).
2409 props = (
2410 'location', 'rotation_quaternion', 'rotation_axis_angle', 'rotation_euler', 'rotation_mode', 'scale',
2411 'delta_location', 'delta_rotation_euler', 'delta_rotation_quaternion', 'delta_scale',
2412 'lock_location', 'lock_rotation', 'lock_rotation_w', 'lock_rotations_4d', 'lock_scale',
2413 'tag', 'track_axis', 'up_axis', 'active_material', 'active_material_index',
2414 'matrix_parent_inverse', 'empty_display_type', 'empty_display_size', 'empty_image_offset', 'pass_index',
2415 'color', 'hide_viewport', 'hide_select', 'hide_render', 'instance_type',
2416 'use_instance_vertices_rotation', 'use_instance_faces_scale', 'instance_faces_scale',
2417 'display_type', 'show_bounds', 'display_bounds_type', 'show_name', 'show_axis', 'show_texture_space',
2418 'show_wire', 'show_all_edges', 'show_transparent', 'show_in_front',
2419 'show_only_shape_key', 'use_shape_key_edit_mode', 'active_shape_key_index',
2421 for p in props:
2422 if not ob_to.is_property_readonly(p):
2423 setattr(ob_to, p, getattr(ob_from, p))
2425 for ob_obj in scene_data.objects:
2426 # Actions only for objects, not bones!
2427 if not ob_obj.is_object:
2428 continue
2430 ob = ob_obj.bdata # Back to real Blender Object.
2432 if not ob.animation_data:
2433 continue # Do not export animations for objects that are absolutely not animated, see T44386.
2435 if ob.animation_data.is_property_readonly('action'):
2436 continue # Cannot re-assign 'active action' to this object (usually related to NLA usage, see T48089).
2438 # We can't play with animdata and actions and get back to org state easily.
2439 # So we have to add a temp copy of the object to the scene, animate it, and remove it... :/
2440 ob_copy = ob.copy()
2441 # Great, have to handle bones as well if needed...
2442 pbones_matrices = [pbo.matrix_basis.copy() for pbo in ob.pose.bones] if ob.type == 'ARMATURE' else ...
2444 org_act = ob.animation_data.action
2445 path_resolve = ob.path_resolve
2447 for act in bpy.data.actions:
2448 # For now, *all* paths in the action must be valid for the object, to validate the action.
2449 # Unless that action was already assigned to the object!
2450 if act != org_act and not validate_actions(act, path_resolve):
2451 continue
2452 ob.animation_data.action = act
2453 frame_start, frame_end = act.frame_range # sic!
2454 add_anim(animations, animated,
2455 fbx_animations_do(scene_data, (ob, act), frame_start, frame_end, True,
2456 objects={ob_obj}, force_keep=True))
2457 # Ugly! :/
2458 if pbones_matrices is not ...:
2459 for pbo, mat in zip(ob.pose.bones, pbones_matrices):
2460 pbo.matrix_basis = mat.copy()
2461 ob.animation_data.action = org_act
2462 restore_object(ob, ob_copy)
2463 scene.frame_set(scene.frame_current, subframe=0.0)
2465 if pbones_matrices is not ...:
2466 for pbo, mat in zip(ob.pose.bones, pbones_matrices):
2467 pbo.matrix_basis = mat.copy()
2468 ob.animation_data.action = org_act
2470 bpy.data.objects.remove(ob_copy)
2471 scene.frame_set(scene.frame_current, subframe=0.0)
2473 # Global (containing everything) animstack, only if not exporting NLA strips and/or all actions.
2474 if not scene_data.settings.bake_anim_use_nla_strips and not scene_data.settings.bake_anim_use_all_actions:
2475 add_anim(animations, animated, fbx_animations_do(scene_data, None, scene.frame_start, scene.frame_end, False))
2477 # Be sure to update all matrices back to org state!
2478 scene.frame_set(scene.frame_current, subframe=0.0)
2480 return animations, animated, frame_start, frame_end
2483 def fbx_data_from_scene(scene, depsgraph, settings):
2485 Do some pre-processing over scene's data...
2487 objtypes = settings.object_types
2488 dp_objtypes = objtypes - {'ARMATURE'} # Armatures are not supported as dupli instances currently...
2489 perfmon = PerfMon()
2490 perfmon.level_up()
2492 # ##### Gathering data...
2494 perfmon.step("FBX export prepare: Wrapping Objects...")
2496 # This is rather simple for now, maybe we could end generating templates with most-used values
2497 # instead of default ones?
2498 objects = {} # Because we do not have any ordered set...
2499 for ob in settings.context_objects:
2500 if ob.type not in objtypes:
2501 continue
2502 ob_obj = ObjectWrapper(ob)
2503 objects[ob_obj] = None
2504 # Duplis...
2505 for dp_obj in ob_obj.dupli_list_gen(depsgraph):
2506 if dp_obj.type not in dp_objtypes:
2507 continue
2508 objects[dp_obj] = None
2510 perfmon.step("FBX export prepare: Wrapping Data (lamps, cameras, empties)...")
2512 data_lights = {ob_obj.bdata.data: get_blenderID_key(ob_obj.bdata.data)
2513 for ob_obj in objects if ob_obj.type == 'LIGHT'}
2514 # Unfortunately, FBX camera data contains object-level data (like position, orientation, etc.)...
2515 data_cameras = {ob_obj: get_blenderID_key(ob_obj.bdata.data)
2516 for ob_obj in objects if ob_obj.type == 'CAMERA'}
2517 # Yep! Contains nothing, but needed!
2518 data_empties = {ob_obj: get_blender_empty_key(ob_obj.bdata)
2519 for ob_obj in objects if ob_obj.type == 'EMPTY'}
2521 perfmon.step("FBX export prepare: Wrapping Meshes...")
2523 data_meshes = {}
2524 for ob_obj in objects:
2525 if ob_obj.type not in BLENDER_OBJECT_TYPES_MESHLIKE:
2526 continue
2527 ob = ob_obj.bdata
2528 use_org_data = True
2529 org_ob_obj = None
2531 # Do not want to systematically recreate a new mesh for dupliobject instances, kind of break purpose of those.
2532 if ob_obj.is_dupli:
2533 org_ob_obj = ObjectWrapper(ob) # We get the "real" object wrapper from that dupli instance.
2534 if org_ob_obj in data_meshes:
2535 data_meshes[ob_obj] = data_meshes[org_ob_obj]
2536 continue
2538 is_ob_material = any(ms.link == 'OBJECT' for ms in ob.material_slots)
2540 if settings.use_mesh_modifiers or settings.use_triangles or ob.type in BLENDER_OTHER_OBJECT_TYPES or is_ob_material:
2541 # We cannot use default mesh in that case, or material would not be the right ones...
2542 use_org_data = not (is_ob_material or ob.type in BLENDER_OTHER_OBJECT_TYPES)
2543 backup_pose_positions = []
2544 tmp_mods = []
2545 if use_org_data and ob.type == 'MESH':
2546 if settings.use_triangles:
2547 use_org_data = False
2548 # No need to create a new mesh in this case, if no modifier is active!
2549 last_subsurf = None
2550 for mod in ob.modifiers:
2551 # For meshes, when armature export is enabled, disable Armature modifiers here!
2552 # XXX Temp hacks here since currently we only have access to a viewport depsgraph...
2554 # NOTE: We put armature to the rest pose instead of disabling it so we still
2555 # have vertex groups in the evaluated mesh.
2556 if mod.type == 'ARMATURE' and 'ARMATURE' in settings.object_types:
2557 object = mod.object
2558 if object and object.type == 'ARMATURE':
2559 armature = object.data
2560 # If armature is already in REST position, there's nothing to back-up
2561 # This cuts down on export time dramatically, if all armatures are already in REST position
2562 # by not triggering dependency graph update
2563 if armature.pose_position != 'REST':
2564 backup_pose_positions.append((armature, armature.pose_position))
2565 armature.pose_position = 'REST'
2566 elif mod.show_render or mod.show_viewport:
2567 # If exporting with subsurf collect the last Catmull-Clark subsurf modifier
2568 # and disable it. We can use the original data as long as this is the first
2569 # found applicable subsurf modifier.
2570 if settings.use_subsurf and mod.type == 'SUBSURF' and mod.subdivision_type == 'CATMULL_CLARK':
2571 if last_subsurf:
2572 use_org_data = False
2573 last_subsurf = mod
2574 else:
2575 use_org_data = False
2576 if settings.use_subsurf and last_subsurf:
2577 # XXX: When exporting with subsurf information temporarily disable
2578 # the last subsurf modifier.
2579 tmp_mods.append((last_subsurf, last_subsurf.show_render, last_subsurf.show_viewport))
2580 last_subsurf.show_render = False
2581 last_subsurf.show_viewport = False
2582 if not use_org_data:
2583 # If modifiers has been altered need to update dependency graph.
2584 if backup_pose_positions or tmp_mods:
2585 depsgraph.update()
2586 ob_to_convert = ob.evaluated_get(depsgraph) if settings.use_mesh_modifiers else ob
2587 # NOTE: The dependency graph might be re-evaluating multiple times, which could
2588 # potentially free the mesh created early on. So we put those meshes to bmain and
2589 # free them afterwards. Not ideal but ensures correct ownerwhip.
2590 tmp_me = bpy.data.meshes.new_from_object(
2591 ob_to_convert, preserve_all_data_layers=True, depsgraph=depsgraph)
2592 # Triangulate the mesh if requested
2593 if settings.use_triangles:
2594 import bmesh
2595 bm = bmesh.new()
2596 bm.from_mesh(tmp_me)
2597 bmesh.ops.triangulate(bm, faces=bm.faces)
2598 bm.to_mesh(tmp_me)
2599 bm.free()
2600 # Usually the materials of the evaluated object will be the same, but modifiers, such as Geometry Nodes,
2601 # can change the materials.
2602 orig_mats = tuple(slot.material for slot in ob.material_slots)
2603 eval_mats = tuple(slot.material.original if slot.material else None
2604 for slot in ob_to_convert.material_slots)
2605 if orig_mats != eval_mats:
2606 # Override the default behaviour of getting materials from ob_obj.bdata.material_slots.
2607 ob_obj.override_materials = eval_mats
2608 data_meshes[ob_obj] = (get_blenderID_key(tmp_me), tmp_me, True)
2609 # Change armatures back.
2610 for armature, pose_position in backup_pose_positions:
2611 print((armature, pose_position))
2612 armature.pose_position = pose_position
2613 # Update now, so we don't leave modified state after last object was exported.
2614 # Re-enable temporary disabled modifiers.
2615 for mod, show_render, show_viewport in tmp_mods:
2616 mod.show_render = show_render
2617 mod.show_viewport = show_viewport
2618 if backup_pose_positions or tmp_mods:
2619 depsgraph.update()
2620 if use_org_data:
2621 data_meshes[ob_obj] = (get_blenderID_key(ob.data), ob.data, False)
2623 # In case "real" source object of that dupli did not yet still existed in data_meshes, create it now!
2624 if org_ob_obj is not None:
2625 data_meshes[org_ob_obj] = data_meshes[ob_obj]
2627 perfmon.step("FBX export prepare: Wrapping ShapeKeys...")
2629 # ShapeKeys.
2630 data_deformers_shape = {}
2631 geom_mat_co = settings.global_matrix if settings.bake_space_transform else None
2632 co_bl_dtype = np.single
2633 co_fbx_dtype = np.float64
2634 idx_fbx_dtype = np.int32
2636 def empty_verts_fallbacks():
2637 """Create fallback arrays for when there are no verts"""
2638 # FBX does not like empty shapes (makes Unity crash e.g.).
2639 # To prevent this, we add a vertex that does nothing, but it keeps the shape key intact
2640 single_vert_co = np.zeros((1, 3), dtype=co_fbx_dtype)
2641 single_vert_idx = np.zeros(1, dtype=idx_fbx_dtype)
2642 return single_vert_co, single_vert_idx
2644 for me_key, me, _free in data_meshes.values():
2645 if not (me.shape_keys and len(me.shape_keys.key_blocks) > 1): # We do not want basis-only relative skeys...
2646 continue
2647 if me in data_deformers_shape:
2648 continue
2650 shapes_key = get_blender_mesh_shape_key(me)
2652 sk_base = me.shape_keys.key_blocks[0]
2654 # Get and cache only the cos that we need
2655 @cache
2656 def sk_cos(shape_key):
2657 if shape_key == sk_base:
2658 _cos = MESH_ATTRIBUTE_POSITION.to_ndarray(me.attributes)
2659 else:
2660 _cos = np.empty(len(me.vertices) * 3, dtype=co_bl_dtype)
2661 shape_key.data.foreach_get("co", _cos)
2662 return vcos_transformed(_cos, geom_mat_co, co_fbx_dtype)
2664 for shape in me.shape_keys.key_blocks[1:]:
2665 # Only write vertices really different from base coordinates!
2666 relative_key = shape.relative_key
2667 if shape == relative_key:
2668 # Shape is its own relative key, so it does nothing
2669 shape_verts_co, shape_verts_idx = empty_verts_fallbacks()
2670 else:
2671 sv_cos = sk_cos(shape)
2672 ref_cos = sk_cos(shape.relative_key)
2674 # Exclude cos similar to ref_cos and get the indices of the cos that remain
2675 shape_verts_co, shape_verts_idx = shape_difference_exclude_similar(sv_cos, ref_cos)
2677 if not shape_verts_co.size:
2678 shape_verts_co, shape_verts_idx = empty_verts_fallbacks()
2679 else:
2680 # Ensure the indices are of the correct type
2681 shape_verts_idx = astype_view_signedness(shape_verts_idx, idx_fbx_dtype)
2683 channel_key, geom_key = get_blender_mesh_shape_channel_key(me, shape)
2684 data = (channel_key, geom_key, shape_verts_co, shape_verts_idx)
2685 data_deformers_shape.setdefault(me, (me_key, shapes_key, {}))[2][shape] = data
2687 del sk_cos
2689 perfmon.step("FBX export prepare: Wrapping Armatures...")
2691 # Armatures!
2692 data_deformers_skin = {}
2693 data_bones = {}
2694 arm_parents = set()
2695 for ob_obj in tuple(objects):
2696 if not (ob_obj.is_object and ob_obj.type in {'ARMATURE'}):
2697 continue
2698 fbx_skeleton_from_armature(scene, settings, ob_obj, objects, data_meshes,
2699 data_bones, data_deformers_skin, data_empties, arm_parents)
2701 # Generate leaf bones
2702 data_leaf_bones = []
2703 if settings.add_leaf_bones:
2704 data_leaf_bones = fbx_generate_leaf_bones(settings, data_bones)
2706 perfmon.step("FBX export prepare: Wrapping World...")
2708 # Some world settings are embedded in FBX materials...
2709 if scene.world:
2710 data_world = {scene.world: get_blenderID_key(scene.world)}
2711 else:
2712 data_world = {}
2714 perfmon.step("FBX export prepare: Wrapping Materials...")
2716 # TODO: Check all the material stuff works even when they are linked to Objects
2717 # (we can then have the same mesh used with different materials...).
2718 # *Should* work, as FBX always links its materials to Models (i.e. objects).
2719 # XXX However, material indices would probably break...
2720 data_materials = {}
2721 for ob_obj in objects:
2722 # If obj is not a valid object for materials, wrapper will just return an empty tuple...
2723 for ma in ob_obj.materials:
2724 if ma is None:
2725 continue # Empty slots!
2726 # Note theoretically, FBX supports any kind of materials, even GLSL shaders etc.
2727 # However, I doubt anything else than Lambert/Phong is really portable!
2728 # Note we want to keep a 'dummy' empty material even when we can't really support it, see T41396.
2729 ma_data = data_materials.setdefault(ma, (get_blenderID_key(ma), []))
2730 ma_data[1].append(ob_obj)
2732 perfmon.step("FBX export prepare: Wrapping Textures...")
2734 # Note FBX textures also hold their mapping info.
2735 # TODO: Support layers?
2736 data_textures = {}
2737 # FbxVideo also used to store static images...
2738 data_videos = {}
2739 # For now, do not use world textures, don't think they can be linked to anything FBX wise...
2740 for ma in data_materials.keys():
2741 # Note: with nodal shaders, we'll could be generating much more textures, but that's kind of unavoidable,
2742 # given that textures actually do not exist anymore in material context in Blender...
2743 ma_wrap = node_shader_utils.PrincipledBSDFWrapper(ma, is_readonly=True)
2744 for sock_name, fbx_name in PRINCIPLED_TEXTURE_SOCKETS_TO_FBX:
2745 tex = getattr(ma_wrap, sock_name)
2746 if tex is None or tex.image is None:
2747 continue
2748 blender_tex_key = (ma, sock_name)
2749 data_textures[blender_tex_key] = (get_blender_nodetexture_key(*blender_tex_key), fbx_name)
2751 img = tex.image
2752 vid_data = data_videos.setdefault(img, (get_blenderID_key(img), []))
2753 vid_data[1].append(blender_tex_key)
2755 perfmon.step("FBX export prepare: Wrapping Animations...")
2757 # Animation...
2758 animations = ()
2759 animated = set()
2760 frame_start = scene.frame_start
2761 frame_end = scene.frame_end
2762 if settings.bake_anim:
2763 # From objects & bones only for a start.
2764 # Kind of hack, we need a temp scene_data for object's space handling to bake animations...
2765 tmp_scdata = FBXExportData(
2766 None, None, None,
2767 settings, scene, depsgraph, objects, None, None, 0.0, 0.0,
2768 data_empties, data_lights, data_cameras, data_meshes, None,
2769 data_bones, data_leaf_bones, data_deformers_skin, data_deformers_shape,
2770 data_world, data_materials, data_textures, data_videos,
2772 animations, animated, frame_start, frame_end = fbx_animations(tmp_scdata)
2774 # ##### Creation of templates...
2776 perfmon.step("FBX export prepare: Generating templates...")
2778 templates = {}
2779 templates[b"GlobalSettings"] = fbx_template_def_globalsettings(scene, settings, nbr_users=1)
2781 if data_empties:
2782 templates[b"Null"] = fbx_template_def_null(scene, settings, nbr_users=len(data_empties))
2784 if data_lights:
2785 templates[b"Light"] = fbx_template_def_light(scene, settings, nbr_users=len(data_lights))
2787 if data_cameras:
2788 templates[b"Camera"] = fbx_template_def_camera(scene, settings, nbr_users=len(data_cameras))
2790 if data_bones:
2791 templates[b"Bone"] = fbx_template_def_bone(scene, settings, nbr_users=len(data_bones))
2793 if data_meshes:
2794 nbr = len({me_key for me_key, _me, _free in data_meshes.values()})
2795 if data_deformers_shape:
2796 nbr += sum(len(shapes[2]) for shapes in data_deformers_shape.values())
2797 templates[b"Geometry"] = fbx_template_def_geometry(scene, settings, nbr_users=nbr)
2799 if objects:
2800 templates[b"Model"] = fbx_template_def_model(scene, settings, nbr_users=len(objects))
2802 if arm_parents:
2803 # Number of Pose|BindPose elements should be the same as number of meshes-parented-to-armatures
2804 templates[b"BindPose"] = fbx_template_def_pose(scene, settings, nbr_users=len(arm_parents))
2806 if data_deformers_skin or data_deformers_shape:
2807 nbr = 0
2808 if data_deformers_skin:
2809 nbr += len(data_deformers_skin)
2810 nbr += sum(len(clusters) for def_me in data_deformers_skin.values() for a, b, clusters in def_me.values())
2811 if data_deformers_shape:
2812 nbr += len(data_deformers_shape)
2813 nbr += sum(len(shapes[2]) for shapes in data_deformers_shape.values())
2814 assert(nbr != 0)
2815 templates[b"Deformers"] = fbx_template_def_deformer(scene, settings, nbr_users=nbr)
2817 # No world support in FBX...
2819 if data_world:
2820 templates[b"World"] = fbx_template_def_world(scene, settings, nbr_users=len(data_world))
2823 if data_materials:
2824 templates[b"Material"] = fbx_template_def_material(scene, settings, nbr_users=len(data_materials))
2826 if data_textures:
2827 templates[b"TextureFile"] = fbx_template_def_texture_file(scene, settings, nbr_users=len(data_textures))
2829 if data_videos:
2830 templates[b"Video"] = fbx_template_def_video(scene, settings, nbr_users=len(data_videos))
2832 if animations:
2833 nbr_astacks = len(animations)
2834 nbr_acnodes = 0
2835 nbr_acurves = 0
2836 for _astack_key, astack, _al, _n, _fs, _fe in animations:
2837 for _alayer_key, alayer in astack.values():
2838 for _acnode_key, acnode, _acnode_name in alayer.values():
2839 nbr_acnodes += 1
2840 for _acurve_key, _dval, acurve, acurve_valid in acnode.values():
2841 if acurve:
2842 nbr_acurves += 1
2844 templates[b"AnimationStack"] = fbx_template_def_animstack(scene, settings, nbr_users=nbr_astacks)
2845 # Would be nice to have one layer per animated object, but this seems tricky and not that well supported.
2846 # So for now, only one layer per anim stack.
2847 templates[b"AnimationLayer"] = fbx_template_def_animlayer(scene, settings, nbr_users=nbr_astacks)
2848 templates[b"AnimationCurveNode"] = fbx_template_def_animcurvenode(scene, settings, nbr_users=nbr_acnodes)
2849 templates[b"AnimationCurve"] = fbx_template_def_animcurve(scene, settings, nbr_users=nbr_acurves)
2851 templates_users = sum(tmpl.nbr_users for tmpl in templates.values())
2853 # ##### Creation of connections...
2855 perfmon.step("FBX export prepare: Generating Connections...")
2857 connections = []
2859 # Objects (with classical parenting).
2860 for ob_obj in objects:
2861 # Bones are handled later.
2862 if not ob_obj.is_bone:
2863 par_obj = ob_obj.parent
2864 # Meshes parented to armature are handled separately, yet we want the 'no parent' connection (0).
2865 if par_obj and ob_obj.has_valid_parent(objects) and (par_obj, ob_obj) not in arm_parents:
2866 connections.append((b"OO", ob_obj.fbx_uuid, par_obj.fbx_uuid, None))
2867 else:
2868 connections.append((b"OO", ob_obj.fbx_uuid, 0, None))
2870 # Armature & Bone chains.
2871 for bo_obj in data_bones.keys():
2872 par_obj = bo_obj.parent
2873 if par_obj not in objects:
2874 continue
2875 connections.append((b"OO", bo_obj.fbx_uuid, par_obj.fbx_uuid, None))
2877 # Object data.
2878 for ob_obj in objects:
2879 if ob_obj.is_bone:
2880 bo_data_key = data_bones[ob_obj]
2881 connections.append((b"OO", get_fbx_uuid_from_key(bo_data_key), ob_obj.fbx_uuid, None))
2882 else:
2883 if ob_obj.type == 'LIGHT':
2884 light_key = data_lights[ob_obj.bdata.data]
2885 connections.append((b"OO", get_fbx_uuid_from_key(light_key), ob_obj.fbx_uuid, None))
2886 elif ob_obj.type == 'CAMERA':
2887 cam_key = data_cameras[ob_obj]
2888 connections.append((b"OO", get_fbx_uuid_from_key(cam_key), ob_obj.fbx_uuid, None))
2889 elif ob_obj.type == 'EMPTY' or ob_obj.type == 'ARMATURE':
2890 empty_key = data_empties[ob_obj]
2891 connections.append((b"OO", get_fbx_uuid_from_key(empty_key), ob_obj.fbx_uuid, None))
2892 elif ob_obj.type in BLENDER_OBJECT_TYPES_MESHLIKE:
2893 mesh_key, _me, _free = data_meshes[ob_obj]
2894 connections.append((b"OO", get_fbx_uuid_from_key(mesh_key), ob_obj.fbx_uuid, None))
2896 # Leaf Bones
2897 for (_node_name, par_uuid, node_uuid, attr_uuid, _matrix, _hide, _size) in data_leaf_bones:
2898 connections.append((b"OO", node_uuid, par_uuid, None))
2899 connections.append((b"OO", attr_uuid, node_uuid, None))
2901 # 'Shape' deformers (shape keys, only for meshes currently)...
2902 for me_key, shapes_key, shapes in data_deformers_shape.values():
2903 # shape -> geometry
2904 connections.append((b"OO", get_fbx_uuid_from_key(shapes_key), get_fbx_uuid_from_key(me_key), None))
2905 for channel_key, geom_key, _shape_verts_co, _shape_verts_idx in shapes.values():
2906 # shape channel -> shape
2907 connections.append((b"OO", get_fbx_uuid_from_key(channel_key), get_fbx_uuid_from_key(shapes_key), None))
2908 # geometry (keys) -> shape channel
2909 connections.append((b"OO", get_fbx_uuid_from_key(geom_key), get_fbx_uuid_from_key(channel_key), None))
2911 # 'Skin' deformers (armature-to-geometry, only for meshes currently)...
2912 for arm, deformed_meshes in data_deformers_skin.items():
2913 for me, (skin_key, ob_obj, clusters) in deformed_meshes.items():
2914 # skin -> geometry
2915 mesh_key, _me, _free = data_meshes[ob_obj]
2916 assert(me == _me)
2917 connections.append((b"OO", get_fbx_uuid_from_key(skin_key), get_fbx_uuid_from_key(mesh_key), None))
2918 for bo_obj, clstr_key in clusters.items():
2919 # cluster -> skin
2920 connections.append((b"OO", get_fbx_uuid_from_key(clstr_key), get_fbx_uuid_from_key(skin_key), None))
2921 # bone -> cluster
2922 connections.append((b"OO", bo_obj.fbx_uuid, get_fbx_uuid_from_key(clstr_key), None))
2924 # Materials
2925 mesh_material_indices = {}
2926 _objs_indices = {}
2927 for ma, (ma_key, ob_objs) in data_materials.items():
2928 for ob_obj in ob_objs:
2929 connections.append((b"OO", get_fbx_uuid_from_key(ma_key), ob_obj.fbx_uuid, None))
2930 # Get index of this material for this object (or dupliobject).
2931 # Material indices for mesh faces are determined by their order in 'ma to ob' connections.
2932 # Only materials for meshes currently...
2933 # Note in case of dupliobjects a same me/ma idx will be generated several times...
2934 # Should not be an issue in practice, and it's needed in case we export duplis but not the original!
2935 if ob_obj.type not in BLENDER_OBJECT_TYPES_MESHLIKE:
2936 continue
2937 _mesh_key, me, _free = data_meshes[ob_obj]
2938 idx = _objs_indices[ob_obj] = _objs_indices.get(ob_obj, -1) + 1
2939 # XXX If a mesh has multiple material slots with the same material, they are combined into one slot.
2940 # Even if duplicate materials were exported without combining them into one slot, keeping duplicate
2941 # materials separated does not appear to be common behaviour of external software when importing FBX.
2942 mesh_material_indices.setdefault(me, {})[ma] = idx
2943 del _objs_indices
2945 # Textures
2946 for (ma, sock_name), (tex_key, fbx_prop) in data_textures.items():
2947 ma_key, _ob_objs = data_materials[ma]
2948 # texture -> material properties
2949 connections.append((b"OP", get_fbx_uuid_from_key(tex_key), get_fbx_uuid_from_key(ma_key), fbx_prop))
2951 # Images
2952 for vid, (vid_key, blender_tex_keys) in data_videos.items():
2953 for blender_tex_key in blender_tex_keys:
2954 tex_key, _fbx_prop = data_textures[blender_tex_key]
2955 connections.append((b"OO", get_fbx_uuid_from_key(vid_key), get_fbx_uuid_from_key(tex_key), None))
2957 # Animations
2958 for astack_key, astack, alayer_key, _name, _fstart, _fend in animations:
2959 # Animstack itself is linked nowhere!
2960 astack_id = get_fbx_uuid_from_key(astack_key)
2961 # For now, only one layer!
2962 alayer_id = get_fbx_uuid_from_key(alayer_key)
2963 connections.append((b"OO", alayer_id, astack_id, None))
2964 for elem_key, (alayer_key, acurvenodes) in astack.items():
2965 elem_id = get_fbx_uuid_from_key(elem_key)
2966 # Animlayer -> animstack.
2967 # alayer_id = get_fbx_uuid_from_key(alayer_key)
2968 # connections.append((b"OO", alayer_id, astack_id, None))
2969 for fbx_prop, (acurvenode_key, acurves, acurvenode_name) in acurvenodes.items():
2970 # Animcurvenode -> animalayer.
2971 acurvenode_id = get_fbx_uuid_from_key(acurvenode_key)
2972 connections.append((b"OO", acurvenode_id, alayer_id, None))
2973 # Animcurvenode -> object property.
2974 connections.append((b"OP", acurvenode_id, elem_id, fbx_prop.encode()))
2975 for fbx_item, (acurve_key, default_value, acurve, acurve_valid) in acurves.items():
2976 if acurve:
2977 # Animcurve -> Animcurvenode.
2978 connections.append((b"OP", get_fbx_uuid_from_key(acurve_key), acurvenode_id, fbx_item.encode()))
2980 perfmon.level_down()
2982 # ##### And pack all this!
2984 return FBXExportData(
2985 templates, templates_users, connections,
2986 settings, scene, depsgraph, objects, animations, animated, frame_start, frame_end,
2987 data_empties, data_lights, data_cameras, data_meshes, mesh_material_indices,
2988 data_bones, data_leaf_bones, data_deformers_skin, data_deformers_shape,
2989 data_world, data_materials, data_textures, data_videos,
2993 def fbx_scene_data_cleanup(scene_data):
2995 Some final cleanup...
2997 # Delete temp meshes.
2998 done_meshes = set()
2999 for me_key, me, free in scene_data.data_meshes.values():
3000 if free and me_key not in done_meshes:
3001 bpy.data.meshes.remove(me)
3002 done_meshes.add(me_key)
3005 # ##### Top-level FBX elements generators. #####
3007 def fbx_header_elements(root, scene_data, time=None):
3009 Write boiling code of FBX root.
3010 time is expected to be a datetime.datetime object, or None (using now() in this case).
3012 app_vendor = "Blender Foundation"
3013 app_name = "Blender (stable FBX IO)"
3014 app_ver = bpy.app.version_string
3016 import addon_utils
3017 import sys
3018 addon_ver = addon_utils.module_bl_info(sys.modules[__package__])['version']
3020 # ##### Start of FBXHeaderExtension element.
3021 header_ext = elem_empty(root, b"FBXHeaderExtension")
3023 elem_data_single_int32(header_ext, b"FBXHeaderVersion", FBX_HEADER_VERSION)
3025 elem_data_single_int32(header_ext, b"FBXVersion", FBX_VERSION)
3027 # No encryption!
3028 elem_data_single_int32(header_ext, b"EncryptionType", 0)
3030 if time is None:
3031 time = datetime.datetime.now()
3032 elem = elem_empty(header_ext, b"CreationTimeStamp")
3033 elem_data_single_int32(elem, b"Version", 1000)
3034 elem_data_single_int32(elem, b"Year", time.year)
3035 elem_data_single_int32(elem, b"Month", time.month)
3036 elem_data_single_int32(elem, b"Day", time.day)
3037 elem_data_single_int32(elem, b"Hour", time.hour)
3038 elem_data_single_int32(elem, b"Minute", time.minute)
3039 elem_data_single_int32(elem, b"Second", time.second)
3040 elem_data_single_int32(elem, b"Millisecond", time.microsecond // 1000)
3042 elem_data_single_string_unicode(header_ext, b"Creator", "%s - %s - %d.%d.%d"
3043 % (app_name, app_ver, addon_ver[0], addon_ver[1], addon_ver[2]))
3045 # 'SceneInfo' seems mandatory to get a valid FBX file...
3046 # TODO use real values!
3047 # XXX Should we use scene.name.encode() here?
3048 scene_info = elem_data_single_string(header_ext, b"SceneInfo", fbx_name_class(b"GlobalInfo", b"SceneInfo"))
3049 scene_info.add_string(b"UserData")
3050 elem_data_single_string(scene_info, b"Type", b"UserData")
3051 elem_data_single_int32(scene_info, b"Version", FBX_SCENEINFO_VERSION)
3052 meta_data = elem_empty(scene_info, b"MetaData")
3053 elem_data_single_int32(meta_data, b"Version", FBX_SCENEINFO_VERSION)
3054 elem_data_single_string(meta_data, b"Title", b"")
3055 elem_data_single_string(meta_data, b"Subject", b"")
3056 elem_data_single_string(meta_data, b"Author", b"")
3057 elem_data_single_string(meta_data, b"Keywords", b"")
3058 elem_data_single_string(meta_data, b"Revision", b"")
3059 elem_data_single_string(meta_data, b"Comment", b"")
3061 props = elem_properties(scene_info)
3062 elem_props_set(props, "p_string_url", b"DocumentUrl", "/foobar.fbx")
3063 elem_props_set(props, "p_string_url", b"SrcDocumentUrl", "/foobar.fbx")
3064 original = elem_props_compound(props, b"Original")
3065 original("p_string", b"ApplicationVendor", app_vendor)
3066 original("p_string", b"ApplicationName", app_name)
3067 original("p_string", b"ApplicationVersion", app_ver)
3068 original("p_datetime", b"DateTime_GMT", "01/01/1970 00:00:00.000")
3069 original("p_string", b"FileName", "/foobar.fbx")
3070 lastsaved = elem_props_compound(props, b"LastSaved")
3071 lastsaved("p_string", b"ApplicationVendor", app_vendor)
3072 lastsaved("p_string", b"ApplicationName", app_name)
3073 lastsaved("p_string", b"ApplicationVersion", app_ver)
3074 lastsaved("p_datetime", b"DateTime_GMT", "01/01/1970 00:00:00.000")
3075 original("p_string", b"ApplicationNativeFile", bpy.data.filepath)
3077 # ##### End of FBXHeaderExtension element.
3079 # FileID is replaced by dummy value currently...
3080 elem_data_single_bytes(root, b"FileId", b"FooBar")
3082 # CreationTime is replaced by dummy value currently, but anyway...
3083 elem_data_single_string_unicode(root, b"CreationTime",
3084 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}:{:03}"
3085 "".format(time.year, time.month, time.day, time.hour, time.minute, time.second,
3086 time.microsecond * 1000))
3088 elem_data_single_string_unicode(root, b"Creator", "%s - %s - %d.%d.%d"
3089 % (app_name, app_ver, addon_ver[0], addon_ver[1], addon_ver[2]))
3091 # ##### Start of GlobalSettings element.
3092 global_settings = elem_empty(root, b"GlobalSettings")
3093 scene = scene_data.scene
3095 elem_data_single_int32(global_settings, b"Version", 1000)
3097 props = elem_properties(global_settings)
3098 up_axis, front_axis, coord_axis = RIGHT_HAND_AXES[scene_data.settings.to_axes]
3099 #~ # DO NOT take into account global scale here! That setting is applied to object transformations during export
3100 #~ # (in other words, this is pure blender-exporter feature, and has nothing to do with FBX data).
3101 #~ if scene_data.settings.apply_unit_scale:
3102 #~ # Unit scaling is applied to objects' scale, so our unit is effectively FBX one (centimeter).
3103 #~ scale_factor_org = 1.0
3104 #~ scale_factor = 1.0 / units_blender_to_fbx_factor(scene)
3105 #~ else:
3106 #~ scale_factor_org = units_blender_to_fbx_factor(scene)
3107 #~ scale_factor = scale_factor_org
3108 scale_factor = scale_factor_org = scene_data.settings.unit_scale
3109 elem_props_set(props, "p_integer", b"UpAxis", up_axis[0])
3110 elem_props_set(props, "p_integer", b"UpAxisSign", up_axis[1])
3111 elem_props_set(props, "p_integer", b"FrontAxis", front_axis[0])
3112 elem_props_set(props, "p_integer", b"FrontAxisSign", front_axis[1])
3113 elem_props_set(props, "p_integer", b"CoordAxis", coord_axis[0])
3114 elem_props_set(props, "p_integer", b"CoordAxisSign", coord_axis[1])
3115 elem_props_set(props, "p_integer", b"OriginalUpAxis", -1)
3116 elem_props_set(props, "p_integer", b"OriginalUpAxisSign", 1)
3117 elem_props_set(props, "p_double", b"UnitScaleFactor", scale_factor)
3118 elem_props_set(props, "p_double", b"OriginalUnitScaleFactor", scale_factor_org)
3119 elem_props_set(props, "p_color_rgb", b"AmbientColor", (0.0, 0.0, 0.0))
3120 elem_props_set(props, "p_string", b"DefaultCamera", "Producer Perspective")
3122 # Global timing data.
3123 r = scene.render
3124 _, fbx_fps_mode = FBX_FRAMERATES[0] # Custom framerate.
3125 fbx_fps = fps = r.fps / r.fps_base
3126 for ref_fps, fps_mode in FBX_FRAMERATES:
3127 if similar_values(fps, ref_fps):
3128 fbx_fps = ref_fps
3129 fbx_fps_mode = fps_mode
3130 break
3131 elem_props_set(props, "p_enum", b"TimeMode", fbx_fps_mode)
3132 elem_props_set(props, "p_timestamp", b"TimeSpanStart", 0)
3133 elem_props_set(props, "p_timestamp", b"TimeSpanStop", FBX_KTIME)
3134 elem_props_set(props, "p_double", b"CustomFrameRate", fbx_fps)
3136 # ##### End of GlobalSettings element.
3139 def fbx_documents_elements(root, scene_data):
3141 Write 'Document' part of FBX root.
3142 Seems like FBX support multiple documents, but until I find examples of such, we'll stick to single doc!
3143 time is expected to be a datetime.datetime object, or None (using now() in this case).
3145 name = scene_data.scene.name
3147 # ##### Start of Documents element.
3148 docs = elem_empty(root, b"Documents")
3150 elem_data_single_int32(docs, b"Count", 1)
3152 doc_uid = get_fbx_uuid_from_key("__FBX_Document__" + name)
3153 doc = elem_data_single_int64(docs, b"Document", doc_uid)
3154 doc.add_string_unicode(name)
3155 doc.add_string_unicode(name)
3157 props = elem_properties(doc)
3158 elem_props_set(props, "p_object", b"SourceObject")
3159 elem_props_set(props, "p_string", b"ActiveAnimStackName", "")
3161 # XXX Some kind of ID? Offset?
3162 # Anyway, as long as we have only one doc, probably not an issue.
3163 elem_data_single_int64(doc, b"RootNode", 0)
3166 def fbx_references_elements(root, scene_data):
3168 Have no idea what references are in FBX currently... Just writing empty element.
3170 docs = elem_empty(root, b"References")
3173 def fbx_definitions_elements(root, scene_data):
3175 Templates definitions. Only used by Objects data afaik (apart from dummy GlobalSettings one).
3177 definitions = elem_empty(root, b"Definitions")
3179 elem_data_single_int32(definitions, b"Version", FBX_TEMPLATES_VERSION)
3180 elem_data_single_int32(definitions, b"Count", scene_data.templates_users)
3182 fbx_templates_generate(definitions, scene_data.templates)
3185 def fbx_objects_elements(root, scene_data):
3187 Data (objects, geometry, material, textures, armatures, etc.).
3189 perfmon = PerfMon()
3190 perfmon.level_up()
3191 objects = elem_empty(root, b"Objects")
3193 perfmon.step("FBX export fetch empties (%d)..." % len(scene_data.data_empties))
3195 for empty in scene_data.data_empties:
3196 fbx_data_empty_elements(objects, empty, scene_data)
3198 perfmon.step("FBX export fetch lamps (%d)..." % len(scene_data.data_lights))
3200 for lamp in scene_data.data_lights:
3201 fbx_data_light_elements(objects, lamp, scene_data)
3203 perfmon.step("FBX export fetch cameras (%d)..." % len(scene_data.data_cameras))
3205 for cam in scene_data.data_cameras:
3206 fbx_data_camera_elements(objects, cam, scene_data)
3208 perfmon.step("FBX export fetch meshes (%d)..."
3209 % len({me_key for me_key, _me, _free in scene_data.data_meshes.values()}))
3211 done_meshes = set()
3212 for me_obj in scene_data.data_meshes:
3213 fbx_data_mesh_elements(objects, me_obj, scene_data, done_meshes)
3214 del done_meshes
3216 perfmon.step("FBX export fetch objects (%d)..." % len(scene_data.objects))
3218 for ob_obj in scene_data.objects:
3219 if ob_obj.is_dupli:
3220 continue
3221 fbx_data_object_elements(objects, ob_obj, scene_data)
3222 for dp_obj in ob_obj.dupli_list_gen(scene_data.depsgraph):
3223 if dp_obj not in scene_data.objects:
3224 continue
3225 fbx_data_object_elements(objects, dp_obj, scene_data)
3227 perfmon.step("FBX export fetch remaining...")
3229 for ob_obj in scene_data.objects:
3230 if not (ob_obj.is_object and ob_obj.type == 'ARMATURE'):
3231 continue
3232 fbx_data_armature_elements(objects, ob_obj, scene_data)
3234 if scene_data.data_leaf_bones:
3235 fbx_data_leaf_bone_elements(objects, scene_data)
3237 for ma in scene_data.data_materials:
3238 fbx_data_material_elements(objects, ma, scene_data)
3240 for blender_tex_key in scene_data.data_textures:
3241 fbx_data_texture_file_elements(objects, blender_tex_key, scene_data)
3243 for vid in scene_data.data_videos:
3244 fbx_data_video_elements(objects, vid, scene_data)
3246 perfmon.step("FBX export fetch animations...")
3247 start_time = time.process_time()
3249 fbx_data_animation_elements(objects, scene_data)
3251 perfmon.level_down()
3254 def fbx_connections_elements(root, scene_data):
3256 Relations between Objects (which material uses which texture, and so on).
3258 connections = elem_empty(root, b"Connections")
3260 for c in scene_data.connections:
3261 elem_connection(connections, *c)
3264 def fbx_takes_elements(root, scene_data):
3266 Animations.
3268 # XXX Pretty sure takes are no more needed...
3269 takes = elem_empty(root, b"Takes")
3270 elem_data_single_string(takes, b"Current", b"")
3272 animations = scene_data.animations
3273 for astack_key, animations, alayer_key, name, f_start, f_end in animations:
3274 scene = scene_data.scene
3275 fps = scene.render.fps / scene.render.fps_base
3276 start_ktime = int(convert_sec_to_ktime(f_start / fps))
3277 end_ktime = int(convert_sec_to_ktime(f_end / fps))
3279 take = elem_data_single_string(takes, b"Take", name)
3280 elem_data_single_string(take, b"FileName", name + b".tak")
3281 take_loc_time = elem_data_single_int64(take, b"LocalTime", start_ktime)
3282 take_loc_time.add_int64(end_ktime)
3283 take_ref_time = elem_data_single_int64(take, b"ReferenceTime", start_ktime)
3284 take_ref_time.add_int64(end_ktime)
3287 # ##### "Main" functions. #####
3289 # This func can be called with just the filepath
3290 def save_single(operator, scene, depsgraph, filepath="",
3291 global_matrix=Matrix(),
3292 apply_unit_scale=False,
3293 global_scale=1.0,
3294 apply_scale_options='FBX_SCALE_NONE',
3295 axis_up="Z",
3296 axis_forward="Y",
3297 context_objects=None,
3298 object_types=None,
3299 use_mesh_modifiers=True,
3300 use_mesh_modifiers_render=True,
3301 mesh_smooth_type='FACE',
3302 use_subsurf=False,
3303 use_armature_deform_only=False,
3304 bake_anim=True,
3305 bake_anim_use_all_bones=True,
3306 bake_anim_use_nla_strips=True,
3307 bake_anim_use_all_actions=True,
3308 bake_anim_step=1.0,
3309 bake_anim_simplify_factor=1.0,
3310 bake_anim_force_startend_keying=True,
3311 add_leaf_bones=False,
3312 primary_bone_axis='Y',
3313 secondary_bone_axis='X',
3314 use_metadata=True,
3315 path_mode='AUTO',
3316 use_mesh_edges=True,
3317 use_tspace=True,
3318 use_triangles=False,
3319 embed_textures=False,
3320 use_custom_props=False,
3321 bake_space_transform=False,
3322 armature_nodetype='NULL',
3323 colors_type='SRGB',
3324 prioritize_active_color=False,
3325 **kwargs
3328 # Clear cached ObjectWrappers (just in case...).
3329 ObjectWrapper.cache_clear()
3331 if object_types is None:
3332 object_types = {'EMPTY', 'CAMERA', 'LIGHT', 'ARMATURE', 'MESH', 'OTHER'}
3334 if 'OTHER' in object_types:
3335 object_types |= BLENDER_OTHER_OBJECT_TYPES
3337 # Default Blender unit is equivalent to meter, while FBX one is centimeter...
3338 unit_scale = units_blender_to_fbx_factor(scene) if apply_unit_scale else 100.0
3339 if apply_scale_options == 'FBX_SCALE_NONE':
3340 global_matrix = Matrix.Scale(unit_scale * global_scale, 4) @ global_matrix
3341 unit_scale = 1.0
3342 elif apply_scale_options == 'FBX_SCALE_UNITS':
3343 global_matrix = Matrix.Scale(global_scale, 4) @ global_matrix
3344 elif apply_scale_options == 'FBX_SCALE_CUSTOM':
3345 global_matrix = Matrix.Scale(unit_scale, 4) @ global_matrix
3346 unit_scale = global_scale
3347 else: # if apply_scale_options == 'FBX_SCALE_ALL':
3348 unit_scale = global_scale * unit_scale
3350 global_scale = global_matrix.median_scale
3351 global_matrix_inv = global_matrix.inverted()
3352 # For transforming mesh normals.
3353 global_matrix_inv_transposed = global_matrix_inv.transposed()
3355 # Only embed textures in COPY mode!
3356 if embed_textures and path_mode != 'COPY':
3357 embed_textures = False
3359 # Calculate bone correction matrix
3360 bone_correction_matrix = None # Default is None = no change
3361 bone_correction_matrix_inv = None
3362 if (primary_bone_axis, secondary_bone_axis) != ('Y', 'X'):
3363 from bpy_extras.io_utils import axis_conversion
3364 bone_correction_matrix = axis_conversion(from_forward=secondary_bone_axis,
3365 from_up=primary_bone_axis,
3366 to_forward='X',
3367 to_up='Y',
3368 ).to_4x4()
3369 bone_correction_matrix_inv = bone_correction_matrix.inverted()
3372 media_settings = FBXExportSettingsMedia(
3373 path_mode,
3374 os.path.dirname(bpy.data.filepath), # base_src
3375 os.path.dirname(filepath), # base_dst
3376 # Local dir where to put images (media), using FBX conventions.
3377 os.path.splitext(os.path.basename(filepath))[0] + ".fbm", # subdir
3378 embed_textures,
3379 set(), # copy_set
3380 set(), # embedded_set
3383 settings = FBXExportSettings(
3384 operator.report, (axis_up, axis_forward), global_matrix, global_scale, apply_unit_scale, unit_scale,
3385 bake_space_transform, global_matrix_inv, global_matrix_inv_transposed,
3386 context_objects, object_types, use_mesh_modifiers, use_mesh_modifiers_render,
3387 mesh_smooth_type, use_subsurf, use_mesh_edges, use_tspace, use_triangles,
3388 armature_nodetype, use_armature_deform_only,
3389 add_leaf_bones, bone_correction_matrix, bone_correction_matrix_inv,
3390 bake_anim, bake_anim_use_all_bones, bake_anim_use_nla_strips, bake_anim_use_all_actions,
3391 bake_anim_step, bake_anim_simplify_factor, bake_anim_force_startend_keying,
3392 False, media_settings, use_custom_props, colors_type, prioritize_active_color
3395 import bpy_extras.io_utils
3397 print('\nFBX export starting... %r' % filepath)
3398 start_time = time.process_time()
3400 # Generate some data about exported scene...
3401 scene_data = fbx_data_from_scene(scene, depsgraph, settings)
3403 root = elem_empty(None, b"") # Root element has no id, as it is not saved per se!
3405 # Mostly FBXHeaderExtension and GlobalSettings.
3406 fbx_header_elements(root, scene_data)
3408 # Documents and References are pretty much void currently.
3409 fbx_documents_elements(root, scene_data)
3410 fbx_references_elements(root, scene_data)
3412 # Templates definitions.
3413 fbx_definitions_elements(root, scene_data)
3415 # Actual data.
3416 fbx_objects_elements(root, scene_data)
3418 # How data are inter-connected.
3419 fbx_connections_elements(root, scene_data)
3421 # Animation.
3422 fbx_takes_elements(root, scene_data)
3424 # Cleanup!
3425 fbx_scene_data_cleanup(scene_data)
3427 # And we are down, we can write the whole thing!
3428 encode_bin.write(filepath, root, FBX_VERSION)
3430 # Clear cached ObjectWrappers!
3431 ObjectWrapper.cache_clear()
3433 # copy all collected files, if we did not embed them.
3434 if not media_settings.embed_textures:
3435 bpy_extras.io_utils.path_reference_copy(media_settings.copy_set)
3437 print('export finished in %.4f sec.' % (time.process_time() - start_time))
3438 return {'FINISHED'}
3441 # defaults for applications, currently only unity but could add others.
3442 def defaults_unity3d():
3443 return {
3444 # These options seem to produce the same result as the old Ascii exporter in Unity3D:
3445 "axis_up": 'Y',
3446 "axis_forward": '-Z',
3447 "global_matrix": Matrix.Rotation(-math.pi / 2.0, 4, 'X'),
3448 # Should really be True, but it can cause problems if a model is already in a scene or prefab
3449 # with the old transforms.
3450 "bake_space_transform": False,
3452 "use_selection": False,
3454 "object_types": {'ARMATURE', 'EMPTY', 'MESH', 'OTHER'},
3455 "use_mesh_modifiers": True,
3456 "use_mesh_modifiers_render": True,
3457 "use_mesh_edges": False,
3458 "mesh_smooth_type": 'FACE',
3459 "colors_type": 'SRGB',
3460 "use_subsurf": False,
3461 "use_tspace": False, # XXX Why? Unity is expected to support tspace import...
3462 "use_triangles": False,
3464 "use_armature_deform_only": True,
3466 "use_custom_props": True,
3468 "bake_anim": True,
3469 "bake_anim_simplify_factor": 1.0,
3470 "bake_anim_step": 1.0,
3471 "bake_anim_use_nla_strips": True,
3472 "bake_anim_use_all_actions": True,
3473 "add_leaf_bones": False, # Avoid memory/performance cost for something only useful for modelling
3474 "primary_bone_axis": 'Y', # Doesn't really matter for Unity, so leave unchanged
3475 "secondary_bone_axis": 'X',
3477 "path_mode": 'AUTO',
3478 "embed_textures": False,
3479 "batch_mode": 'OFF',
3483 def save(operator, context,
3484 filepath="",
3485 use_selection=False,
3486 use_visible=False,
3487 use_active_collection=False,
3488 batch_mode='OFF',
3489 use_batch_own_dir=False,
3490 **kwargs
3493 This is a wrapper around save_single, which handles multi-scenes (or collections) cases, when batch-exporting
3494 a whole .blend file.
3497 ret = {'FINISHED'}
3499 active_object = context.view_layer.objects.active
3501 org_mode = None
3502 if active_object and active_object.mode != 'OBJECT' and bpy.ops.object.mode_set.poll():
3503 org_mode = active_object.mode
3504 bpy.ops.object.mode_set(mode='OBJECT')
3506 if batch_mode == 'OFF':
3507 kwargs_mod = kwargs.copy()
3508 if use_active_collection:
3509 if use_selection:
3510 ctx_objects = tuple(obj
3511 for obj in context.view_layer.active_layer_collection.collection.all_objects
3512 if obj.select_get())
3513 else:
3514 ctx_objects = context.view_layer.active_layer_collection.collection.all_objects
3515 else:
3516 if use_selection:
3517 ctx_objects = context.selected_objects
3518 else:
3519 ctx_objects = context.view_layer.objects
3520 if use_visible:
3521 ctx_objects = tuple(obj for obj in ctx_objects if obj.visible_get())
3523 # Ensure no Objects are in Edit mode.
3524 # Copy to a tuple for safety, to avoid the risk of modifying ctx_objects while iterating.
3525 for obj in tuple(ctx_objects):
3526 if not ensure_object_not_in_edit_mode(context, obj):
3527 operator.report({'ERROR'}, "%s could not be set out of Edit Mode, so cannot be exported" % obj.name)
3528 return {'CANCELLED'}
3530 kwargs_mod["context_objects"] = ctx_objects
3532 depsgraph = context.evaluated_depsgraph_get()
3533 ret = save_single(operator, context.scene, depsgraph, filepath, **kwargs_mod)
3534 else:
3535 # XXX We need a way to generate a depsgraph for inactive view_layers first...
3536 # XXX Also, what to do in case of batch-exporting scenes, when there is more than one view layer?
3537 # Scenes have no concept of 'active' view layer, that's on window level...
3538 fbxpath = filepath
3540 prefix = os.path.basename(fbxpath)
3541 if prefix:
3542 fbxpath = os.path.dirname(fbxpath)
3544 if batch_mode == 'COLLECTION':
3545 data_seq = tuple((coll, coll.name, 'objects') for coll in bpy.data.collections if coll.objects)
3546 elif batch_mode in {'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3547 scenes = [context.scene] if batch_mode == 'ACTIVE_SCENE_COLLECTION' else bpy.data.scenes
3548 data_seq = []
3549 for scene in scenes:
3550 if not scene.objects:
3551 continue
3552 # Needed to avoid having tens of 'Scene Collection' entries.
3553 todo_collections = [(scene.collection, "_".join((scene.name, scene.collection.name)))]
3554 while todo_collections:
3555 coll, coll_name = todo_collections.pop()
3556 todo_collections.extend(((c, c.name) for c in coll.children if c.all_objects))
3557 data_seq.append((coll, coll_name, 'all_objects'))
3558 else:
3559 data_seq = tuple((scene, scene.name, 'objects') for scene in bpy.data.scenes if scene.objects)
3561 # Ensure no Objects are in Edit mode.
3562 for data, data_name, data_obj_propname in data_seq:
3563 # Copy to a tuple for safety, to avoid the risk of modifying the data prop while iterating it.
3564 for obj in tuple(getattr(data, data_obj_propname)):
3565 if not ensure_object_not_in_edit_mode(context, obj):
3566 operator.report({'ERROR'},
3567 "%s in %s could not be set out of Edit Mode, so cannot be exported"
3568 % (obj.name, data_name))
3569 return {'CANCELLED'}
3571 # call this function within a loop with BATCH_ENABLE == False
3573 new_fbxpath = fbxpath # own dir option modifies, we need to keep an original
3574 for data, data_name, data_obj_propname in data_seq: # scene or collection
3575 newname = "_".join((prefix, bpy.path.clean_name(data_name))) if prefix else bpy.path.clean_name(data_name)
3577 if use_batch_own_dir:
3578 new_fbxpath = os.path.join(fbxpath, newname)
3579 # path may already exist... and be a file.
3580 while os.path.isfile(new_fbxpath):
3581 new_fbxpath = "_".join((new_fbxpath, "dir"))
3582 if not os.path.exists(new_fbxpath):
3583 os.makedirs(new_fbxpath)
3585 filepath = os.path.join(new_fbxpath, newname + '.fbx')
3587 print('\nBatch exporting %s as...\n\t%r' % (data, filepath))
3589 if batch_mode in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3590 # Collection, so that objects update properly, add a dummy scene.
3591 scene = bpy.data.scenes.new(name="FBX_Temp")
3592 src_scenes = {} # Count how much each 'source' scenes are used.
3593 for obj in getattr(data, data_obj_propname):
3594 for src_sce in obj.users_scene:
3595 src_scenes[src_sce] = src_scenes.setdefault(src_sce, 0) + 1
3596 scene.collection.objects.link(obj)
3598 # Find the 'most used' source scene, and use its unit settings. This is somewhat weak, but should work
3599 # fine in most cases, and avoids stupid issues like T41931.
3600 best_src_scene = None
3601 best_src_scene_users = -1
3602 for sce, nbr_users in src_scenes.items():
3603 if (nbr_users) > best_src_scene_users:
3604 best_src_scene_users = nbr_users
3605 best_src_scene = sce
3606 scene.unit_settings.system = best_src_scene.unit_settings.system
3607 scene.unit_settings.system_rotation = best_src_scene.unit_settings.system_rotation
3608 scene.unit_settings.scale_length = best_src_scene.unit_settings.scale_length
3610 # new scene [only one viewlayer to update]
3611 scene.view_layers[0].update()
3612 # TODO - BUMMER! Armatures not in the group wont animate the mesh
3613 else:
3614 scene = data
3616 kwargs_batch = kwargs.copy()
3617 kwargs_batch["context_objects"] = getattr(data, data_obj_propname)
3619 save_single(operator, scene, scene.view_layers[0].depsgraph, filepath, **kwargs_batch)
3621 if batch_mode in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3622 # Remove temp collection scene.
3623 bpy.data.scenes.remove(scene)
3625 if active_object and org_mode:
3626 context.view_layer.objects.active = active_object
3627 if bpy.ops.object.mode_set.poll():
3628 bpy.ops.object.mode_set(mode=org_mode)
3630 return ret