summaryrefslogtreecommitdiffstats
path: root/tools/utils/exporters/blender/qt3d_animation_export.py
blob: b1987ea95b84375573816632ec8d095e4452485f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#############################################################################
##
## Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB).
## Contact: https://www.qt.io/licensing/
##
## This file is part of the Qt3D module of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:LGPL$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and The Qt Company. For licensing terms
## and conditions see https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 3 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL3 included in the
## packaging of this file. Please review the following information to
## ensure the GNU Lesser General Public License version 3 requirements
## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 2.0 or (at your option) the GNU General
## Public license version 3 or any later version approved by the KDE Free
## Qt Foundation. The licenses are as published by the Free Software
## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
## included in the packaging of this file. Please review the following
## information to ensure the GNU General Public License requirements will
## be met: https://www.gnu.org/licenses/gpl-2.0.html and
## https://www.gnu.org/licenses/gpl-3.0.html.
##
## $QT_END_LICENSE$
##
#############################################################################

# Required Blender information.
bl_info = {
           "name": "Qt3D Animation Exporter",
           "author": "Sean Harmer <sean.harmer@kdab.com>, Paul Lemire <paul.lemire@kdab.com>",
           "version": (0, 4),
           "blender": (2, 72, 0),
           "location": "File > Export > Qt3D Animation (.json)",
           "description": "Export animations to json to use with Qt3D",
           "warning": "",
           "wiki_url": "",
           "tracker_url": "",
           "category": "Import-Export"
          }

import bpy
import os
import struct
import mathutils
import math
import json
from array import array
from bpy_extras.io_utils import ExportHelper
from bpy.props import (
        BoolProperty,
        FloatProperty,
        StringProperty,
        EnumProperty,
        )
from collections import defaultdict

def frameToTime(frame):
    # Get the fps to convert from frame number to time in seconds for x values
    fps = bpy.context.scene.render.fps

    # Calculate time, remembering that blender uses 1-based frame numbers
    return (frame - 1) / fps;

def findResolvingObject(rootId):
    if rootId == "OBJECT":
        return bpy.data.objects[0]
    elif rootId == "MATERIAL":
        return bpy.data.materials[0]
    return None

# Note that we swap the Y and Z components because blender uses Z-up
# whereas Qt 3D tends to use Y-Up convention.
def arrayIndexFromTypeAndIndex(dataPath, index):
    if dataPath.startswith("rotation"):
        # Swap Y and Z components of rotations
        if index == 2:
            return 3
        elif index == 3:
            return 2
    elif dataPath.startswith("location"):
        # Swap Y and Z components of locations
        if index == 1:
            return 2
        elif index == 2:
            return 1

    # Otherwise keep the original index
    return index

def componentSuffix(typeName, componentIndex):
    vectorComponents = ["X", "Y", "Z", "W"]
    quaternionComponents = ["W", "X", "Y", "Z"]
    colorComponents = ["R", "G", "B"]

    if typeName == "Vector":
        return vectorComponents[componentIndex]
    elif typeName == "Quaternion":
        return quaternionComponents[componentIndex]
    elif typeName == "Color":
        return colorComponents[componentIndex]
    return "Unknown"

def resolveDataType(object, dataPath):
    value = object.path_resolve(dataPath)
    if isinstance(value, mathutils.Vector):
        return "Vector"
    elif isinstance(value, mathutils.Quaternion):
        return "Quaternion"
    elif isinstance(value, mathutils.Euler):
        return "Euler" + value.order
    elif isinstance(value, mathutils.Color):
        return "Color"
    return "Unknown type"

class PropertyData:
    m_action = None
    m_name = ""
    m_resolverObject = None
    m_dataPath = ""
    m_fcurveIndices = []
    m_componentIndices = []
    m_dataType = ""
    m_outputDataType = ""
    m_outputChannelCount = 0
    m_outputChannelSuffixes = []

    def __init__(self):
        self.m_action = None
        self.m_resolverObject = None
        self.m_dataPath = ""
        self.m_fcurveIndices = []
        self.m_componentIndices = []
        self.m_dataType = ""
        self.m_outputDataType = ""
        self.m_outputChannelCount = 0
        self.m_outputChannelSuffixes = []

    def setDataPath(self, dataPath):
        self.m_dataPath = dataPath
        if dataPath.startswith("rotation"):
            self.m_name = "Rotation"
        else:
            self.m_name = dataPath.title()
        self.m_name = self.m_name.replace("_", " ")

    def print(self):
        print("Action = " + self.m_action.name \
            + "DataPath = " + self.m_dataPath \
            + "Name = " + self.m_name)
            # + "fcurve indices =" + self.m_componentIndices

    def generateKeyframesData(self, outputComponentIndex):
        outputKeyframes = []

        print("generateKeyframesData: fcurveIndices: " + str(self.m_fcurveIndices) + " curve index: " + str(outputComponentIndex))
        # Lookup fcurve index for this component

        # Invert the sign of the 2nd component of quaternions for rotations
        # We already swap the Y and Z components in the componentSuffix function
        axisOrientationfactor = 1.0
        if self.m_name == "Rotation" and outputComponentIndex == 2:
            axisOrientationfactor = -1.0

        if self.m_dataType == self.m_outputDataType:
            fcurveIndex = self.m_fcurveIndices[outputComponentIndex]
            # We can take easy route if no data type conversion is needed
            # Iterate over keyframes
            fcurve = self.m_action.fcurves[fcurveIndex]
            for keyframe in fcurve.keyframe_points:
                outputKeyframe = { \
                    "coords": [frameToTime(keyframe.co.x), axisOrientationfactor * keyframe.co.y], \
                    "leftHandle": [frameToTime(keyframe.handle_left.x), axisOrientationfactor * keyframe.handle_left.y], \
                    "rightHandle": [frameToTime(keyframe.handle_right.x), axisOrientationfactor * keyframe.handle_right.y] }
                outputKeyframes.append(outputKeyframe)
        else:
            # Iterate over keyframes - we assume that all channels were keyed at the same times
            # This is usually the case as blender doesn't support keying individual components
            # but a user could have tweaked the individual channels
            fcurve = self.m_action.fcurves[self.m_fcurveIndices[0]]
            for keyframeIndex, keyframe in enumerate(fcurve.keyframe_points):
                # Get data for this property
                if not self.m_dataType.startswith("Euler"):
                    print("Unhandled data type conversion")
                    return None

                # Convert the control point to a quaternion
                eulerOrder = self.m_dataType[-3:]
                time_co = frameToTime(self.m_action.fcurves[self.m_fcurveIndices[0]].keyframe_points[keyframeIndex].co.x)
                rotX = self.m_action.fcurves[self.m_fcurveIndices[0]].keyframe_points[keyframeIndex].co.y
                rotY = self.m_action.fcurves[self.m_fcurveIndices[1]].keyframe_points[keyframeIndex].co.y
                rotZ = self.m_action.fcurves[self.m_fcurveIndices[2]].keyframe_points[keyframeIndex].co.y
                euler = mathutils.Euler((rotX, rotY, rotZ), eulerOrder)
                q_co = euler.to_quaternion()

                # Convert the left handle to a quaternion
                time_hl = frameToTime(self.m_action.fcurves[self.m_fcurveIndices[0]].keyframe_points[keyframeIndex].handle_left.x)
                rotX = self.m_action.fcurves[self.m_fcurveIndices[0]].keyframe_points[keyframeIndex].handle_left.y
                rotY = self.m_action.fcurves[self.m_fcurveIndices[1]].keyframe_points[keyframeIndex].handle_left.y
                rotZ = self.m_action.fcurves[self.m_fcurveIndices[2]].keyframe_points[keyframeIndex].handle_left.y
                euler = mathutils.Euler((rotX, rotY, rotZ), eulerOrder)
                q_hl = euler.to_quaternion()

                # Convert the right handle to a quaternion
                time_hr = frameToTime(self.m_action.fcurves[self.m_fcurveIndices[0]].keyframe_points[keyframeIndex].handle_left.x)
                rotX = self.m_action.fcurves[self.m_fcurveIndices[0]].keyframe_points[keyframeIndex].handle_left.y
                rotY = self.m_action.fcurves[self.m_fcurveIndices[1]].keyframe_points[keyframeIndex].handle_left.y
                rotZ = self.m_action.fcurves[self.m_fcurveIndices[2]].keyframe_points[keyframeIndex].handle_left.y
                euler = mathutils.Euler((rotX, rotY, rotZ), eulerOrder)
                q_hr = euler.to_quaternion()

                # Extract the corresponding component
                co = []
                handle_left = []
                handle_right = []
                if outputComponentIndex == 0:
                    co = [time_co, axisOrientationfactor * q_co.w]
                    handle_left = [time_hl, axisOrientationfactor * q_hl.w]
                    handle_right = [time_hr, axisOrientationfactor * q_hr.w]
                elif outputComponentIndex == 1:
                    co = [time_co, axisOrientationfactor * q_co.x]
                    handle_left = [time_hl, axisOrientationfactor * q_hl.x]
                    handle_right = [time_hr, axisOrientationfactor * q_hr.x]
                elif outputComponentIndex == 2:
                    co = [time_co, axisOrientationfactor * q_co.y]
                    handle_left = [time_hl, axisOrientationfactor * q_hl.y]
                    handle_right = [time_hr, axisOrientationfactor * q_hr.y]
                elif outputComponentIndex == 3:
                    co = [time_co, axisOrientationfactor * q_co.z]
                    handle_left = [time_hl, axisOrientationfactor * q_hl.z]
                    handle_right = [time_hr, axisOrientationfactor * q_hr.z]

                outputKeyframe = { \
                    "coords": co, \
                    "leftHandle": handle_left, \
                    "rightHandle": handle_right }
                outputKeyframes.append(outputKeyframe)
        return outputKeyframes

    def generateChannelComponentsData(self):
        # First find the data type stored in the blender file
        self.m_dataType = resolveDataType(self.m_resolverObject, self.m_dataPath)

        # Convert this to an output data type - we force rotations as quaternions
        if self.m_dataType.startswith("Euler"):
            self.m_outputDataType = "Quaternion"
            self.m_outputChannelCount = 4
            for i in range(0, 4):
                index = arrayIndexFromTypeAndIndex(self.m_dataPath, i)
                suffix = componentSuffix(self.m_outputDataType, index)
                self.m_outputChannelSuffixes.append(suffix)
        else:
            self.m_outputDataType = self.m_dataType
            self.m_outputChannelCount = len(self.m_componentIndices)
            for i in self.m_componentIndices:
                index = arrayIndexFromTypeAndIndex(self.m_dataPath, i)
                suffix = componentSuffix(self.m_outputDataType, index)
                self.m_outputChannelSuffixes.append(suffix)

        outputChannels = []
        for i in range(0, self.m_outputChannelCount):
            outputChannel = { "channelComponentName": self.m_name + " " + self.m_outputChannelSuffixes[i], "keyFrames": [] }
            keyframes = self.generateKeyframesData(i)
            outputChannel["keyFrames"] = keyframes
            outputChannels.append(outputChannel)

        return outputChannels


class Qt3DAnimationConverter:
    def animationsToJson(self):
        propertyDataMap = defaultdict(list)

        # Pass 1 - collect data we need to produce the output in pass 2
        for action in bpy.data.actions:
            groupCount = len(action.groups)
            #print("    " + action.name + " for type " + action.id_root)

            # We need a datablock of the right type to be able to resolve an fcurve data path to a value.
            # We need the value to be able to determine the type and eventually the correct name for the
            # exported fcurve.
            resolverObject = findResolvingObject(action.id_root)

            fcurveCount = len(action.fcurves)
            #print("    " + action.name + " has " + str(fcurveCount) + " fcurves")

            if fcurveCount == 0:
                break

            lastTitle = ""
            property = PropertyData()
            for fcurveIndex, fcurve in enumerate(action.fcurves):
                title = fcurve.data_path.title()

                # For debugging
                groupName = "<NoGroup>"
                if fcurve.group != None:
                    groupName = fcurve.group.name
                dataPath = fcurve.data_path
                type = resolveDataType(resolverObject, dataPath)
                labelSuffix = componentSuffix("Vector", fcurve.array_index)

                # Create a new PropertyData if this fcurve is for a new property
                if title != lastTitle:
                    property = PropertyData()
                    property.m_action = action
                    property.setDataPath(fcurve.data_path)
                    property.m_resolverObject = resolverObject
                    arrayIndex = arrayIndexFromTypeAndIndex(fcurve.data_path, fcurve.array_index)
                    property.m_componentIndices.append(arrayIndex)
                    #property.m_componentIndices.append(fcurve.array_index)
                    property.m_fcurveIndices.append(fcurveIndex)
                    propertyDataMap[action.name].append(property)
                else:
                    property.m_componentIndices.append(fcurve.array_index)
                    property.m_fcurveIndices.append(fcurveIndex)

                print("        " + str(fcurveIndex) + ": Group: " + groupName \
                    + ", Title = " + title \
                    + ", Component:" + str(fcurve.array_index) \
                    + ", Data Path: " + dataPath \
                    + ", Data Type: " + type \
                    + ", Label: " + labelSuffix \
                    + ", fCurveIndices: " + str(property.m_fcurveIndices))

                lastTitle = title
            print("")

        # For debugging
        print("animationsToJson: Pass 1 - Collected data for " + str(len(propertyDataMap)) + " actions")
        actionIndex = 0
        for key in propertyDataMap:
            print(str(actionIndex) + ": " + key + " has " + str(len(propertyDataMap[key])) + " properties")
            for propertyIndex, property in enumerate(propertyDataMap[key]):
                print("    " + str(propertyIndex) + ": " + property.m_name)
            actionIndex =  actionIndex + 1

        # Pass 2
        print("animationsToJson: Pass 2")

        # The data structure that will be exported
        output = {"animations": []}

        actionIndex = 0
        for key in propertyDataMap:
            #print(str(actionIndex) + ": " + key)

            # Create an output action
            outputAction = { "animationName": key, "channels": []}
            for propertyIndex, property in enumerate(propertyDataMap[key]):
                #print("    " + str(propertyIndex) + ": " + property.m_name)

                # Create an output group and append it to the output action
                outputGroup = { "channelComponents": [], "channelName": property.m_name }

                # Populate the channels list from the property object
                outputChannels = property.generateChannelComponentsData()
                outputGroup["channelComponents"] = outputChannels

                outputAction["channels"].append(outputGroup)

            output["animations"].append(outputAction)
            actionIndex =  actionIndex + 1

        print("animationsToJson: Generating JSON data")
        jsonData = json.dumps(output, indent=2, sort_keys=True, separators=(',', ': '))
        return jsonData


class Qt3DExporter(bpy.types.Operator, ExportHelper):
    """Qt3D Exporter"""
    bl_idname       = "export_scene.qt3d_exporter";
    bl_label        = "Qt3DExporter";
    bl_options      = {'PRESET'};

    filename_ext = ""
    use_filter_folder = True

    # TO DO: Handle properly
    use_mesh_modifiers = BoolProperty(
        name="Apply Modifiers",
        description="Apply modifiers (preview resolution)",
        default=True,
        )

    # TO DO: Handle properly
    use_selection_only = BoolProperty(
        name="Selection Only",
        description="Only export select objects",
        default=False,
        )

    def __init__(self):
        pass

    def execute(self, context):
        print("In Execute" + bpy.context.scene.name)

        self.userpath = self.properties.filepath

        # unselect all
        bpy.ops.object.select_all(action='DESELECT')

        converter = Qt3DAnimationConverter()
        fileContent = converter.animationsToJson()
        with open(self.userpath + ".json", '+w') as f:
            f.write(fileContent)

        return {'FINISHED'}

def createBlenderMenu(self, context):
    self.layout.operator(Qt3DExporter.bl_idname, text="Qt3D Animation(.json)")

# Register against Blender
def register():
    bpy.utils.register_class(Qt3DExporter)
    bpy.types.INFO_MT_file_export.append(createBlenderMenu)

def unregister():
    bpy.utils.unregister_class(Qt3DExporter)
    bpy.types.INFO_MT_file_export.remove(createBlenderMenu)

# Handle running the script from Blender's text editor.
if (__name__ == "__main__"):
   register();
   bpy.ops.export_scene.qt3d_exporter();