summaryrefslogtreecommitdiffstats
path: root/src/Runtime/Source/stateapplication/Qt3DSStateExecutionContext.cpp
blob: 4516c2f990db97641807321541d7fa7e4cd6cf68 (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
/****************************************************************************
**
** Copyright (C) 2013 NVIDIA Corporation.
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL$
** 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 General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) 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.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-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "Qt3DSStateExecutionContext.h"
#include "Qt3DSStateExecutionTypes.h"
#include "Qt3DSStateInterpreter.h"
#include "foundation/Qt3DSFoundation.h"
#include "foundation/Qt3DSBroadcastingAllocator.h"
#include "foundation/Qt3DSAtomic.h"
#include "foundation/StringConversionImpl.h"
#include "Qt3DSStateScriptContext.h"
#include "foundation/Utils.h"
#include "EASTL/string.h"

using namespace qt3ds::state;

namespace {
struct SExecContext : public IExecutionContext
{
    NVFoundationBase &m_Foundation;
    NVScopedRefCounted<IStringTable> m_StringTable;
    // Referencing this here would create circular references
    IStateInterpreter *m_Interpreter;
    IStateLogger *m_DebugLogger;
    NVScopedRefCounted<IStateLogger> m_Logger;
    NVScopedRefCounted<IScriptContext> m_ScriptContext;
    bool m_Error;
    QT3DSI32 mRefCount;
    eastl::string m_DelayStr;

    SExecContext(NVFoundationBase &inFnd, IStringTable &inStrTable, IStateLogger &inLogger,
                 IScriptContext &inContext)
        : m_Foundation(inFnd)
        , m_StringTable(inStrTable)
        , m_Interpreter(NULL)
        , m_DebugLogger(NULL)
        , m_Logger(inLogger)
        , m_ScriptContext(inContext)
        , m_Error(false)
        , mRefCount(0)
    {
    }

    QT3DS_IMPLEMENT_REF_COUNT_ADDREF_RELEASE(m_Foundation.getAllocator())

    void SetInterpreter(IStateInterpreter &inInterpreter) override
    {
        m_Interpreter = &inInterpreter;
    }

    void SetMachineDebugLogger(IStateLogger &inDebugLogger) override
    {
        m_DebugLogger = &inDebugLogger;
    }

    void SignalError()
    {
        const char8_t *errorInfo = m_ScriptContext->GetErrorInfo();
        if (errorInfo && *errorInfo) {
            m_Interpreter->QueueEvent("error.execution", false);
        }
        m_Error = true;
    }
    void ExecuteContent(SExecutableContent &content)
    {
        switch (content.m_Type) {
        case ExecutableContentTypes::Send: {
            SSend &theSend = *content.CastTo<SSend>();
            CRegisteredString theEvent;
            if (!isTrivial(theSend.m_EventExpr)) {
                SScriptExecutionResult theStr =
                    m_ScriptContext->ExecuteExpressionToString(theSend.m_EventExpr);
                if (theStr.Valid())
                    theEvent = m_StringTable->RegisterStr(theStr.Result());
            } else
                theEvent = theSend.m_Event;

            QT3DSU64 theDelay(0);
            m_DelayStr.clear();
            if (!isTrivial(theSend.m_DelayExpr)) {
                SScriptExecutionResult theStr =
                    m_ScriptContext->ExecuteExpressionToString(theSend.m_DelayExpr);
                if (theStr.Valid())
                    m_DelayStr.assign(nonNull(theStr.Result()));
            } else
                m_DelayStr.assign(nonNull(theSend.m_Delay));
            if (m_DelayStr.size())
                theDelay = ParseTimeStrToMilliseconds(m_DelayStr.c_str());

            if (theEvent.IsValid()) {
                TEventPtr theEventPtr;
                if (theSend.m_Children.empty() == false) {
                    IScriptEvent *theNewEvent = m_ScriptContext->CreateScriptEvent(theEvent);
                    theEventPtr = theNewEvent;
                    for (TExecutableContentList::iterator iter = theSend.m_Children.begin(),
                                                          end = theSend.m_Children.end();
                         iter != end && m_Error == false; ++iter) {
                        if (iter->m_Type == ExecutableContentTypes::Param) {
                            SParam &theParam = static_cast<SParam &>(*iter);
                            if (theParam.m_Location.IsValid() == false) {
                                bool success =
                                    theNewEvent->SetParam(theParam.m_Name, theParam.m_Expr);
                                if (!success)
                                    SignalError();
                            } else {
                                QT3DS_ASSERT(false);
                            }
                        } else if (iter->m_Type == ExecutableContentTypes::Content) {
                            SContent &theContent = static_cast<SContent &>(*iter);
                            if (!isTrivial(theContent.m_Expr)) {
                                bool success = theNewEvent->SetDataExpr(theContent.m_Expr);
                                if (!success)
                                    SignalError();
                            } else if (!isTrivial(theContent.m_ContentValue)) {
                                bool success = theNewEvent->SetDataStr(theContent.m_ContentValue);
                                if (!success)
                                    SignalError();
                            }
                        } else {
                            QT3DS_ASSERT(false);
                        }
                    }
                }
                if (m_Error == false) {
                    bool isExternal = true;
                    if (AreEqual("#_internal", theSend.m_Target))
                        isExternal = false;
                    if (theEventPtr)
                        m_Interpreter->QueueEvent(theEventPtr, theDelay, theSend.m_Id, isExternal);
                    else
                        m_Interpreter->QueueEvent(theEvent, theDelay, theSend.m_Id, isExternal);
                }
            }
        } break;
        case ExecutableContentTypes::Cancel: {
            SCancel &theCancel = *content.CastTo<SCancel>();
            if (theCancel.m_Send) {
                m_Interpreter->CancelEvent(theCancel.m_Send->m_Id);
            } else if (!isTrivial(theCancel.m_IdExpression)) {
                SScriptExecutionResult theStr =
                    m_ScriptContext->ExecuteExpressionToString(theCancel.m_IdExpression);
                if (theStr.Valid()) {
                    const char8_t *theStrVal(theStr.Result());
                    if (!isTrivial(theStrVal))
                        m_Interpreter->CancelEvent(m_StringTable->RegisterStr(theStrVal));
                }
            }
        } break;
        case ExecutableContentTypes::Raise: {
            SRaise &theRaise = *content.CastTo<SRaise>();
            m_Interpreter->QueueEvent(theRaise.m_Event, false);
        } break;
        case ExecutableContentTypes::Log: {
            SLog *theLog = content.CastTo<SLog>();
            SScriptExecutionResult str =
                m_ScriptContext->ExecuteExpressionToString(theLog->m_Expression);
            if (str.Valid()) {
                m_Logger->Log(theLog->m_Label, str.Result());
                if (m_DebugLogger)
                    m_DebugLogger->Log(theLog->m_Label, str.Result());
            } else
                SignalError();
        } break;
        case ExecutableContentTypes::If: {
            SIf &theIf = *content.CastTo<SIf>();
            Option<bool> theCondResult = m_ScriptContext->ExecuteCondition(theIf.m_Cond);
            if (theCondResult.hasValue()) {
                bool currentConditionResult = *theCondResult;
                for (TExecutableContentList::iterator ifIter = theIf.m_Children.begin(),
                                                      ifEnd = theIf.m_Children.end();
                     ifIter != ifEnd && m_Error == false; ++ifIter) {
                    if (currentConditionResult) {
                        switch (ifIter->m_Type) {
                        case ExecutableContentTypes::Else:
                        case ExecutableContentTypes::ElseIf:
                            return;
                        default:
                            ExecuteContent(*ifIter);
                            break;
                        }
                    } else {
                        switch (ifIter->m_Type) {
                        case ExecutableContentTypes::ElseIf: {
                            SElseIf &theElseIf = *ifIter->CastTo<SElseIf>();
                            theCondResult = m_ScriptContext->ExecuteCondition(theElseIf.m_Cond);
                            if (theCondResult.hasValue())
                                currentConditionResult = *theCondResult;
                            else {
                                SignalError();
                                return;
                            }
                        } break;
                        case ExecutableContentTypes::Else:
                            currentConditionResult = true;
                            break;
                        // Ignore all content that isn't if or else if we shouldn't be currently
                        // executing it.
                        default:
                            break;
                        }
                    }
                }
            } else
                SignalError();
        } break;
        case ExecutableContentTypes::Foreach: {
            SForeach &theItem = *content.CastTo<SForeach>();
            Option<bool> success;
            for (success = m_ScriptContext->BeginForeach(theItem.m_Array, theItem.m_Item,
                                                         theItem.m_Index);
                 success.hasValue() && *success && m_Error == false;
                 success = m_ScriptContext->NextForeach(theItem.m_Item, theItem.m_Index)) {
                ExecuteContent(theItem.m_Children);
            }
            if (m_Error) {

            } else if (success.hasValue() == false)
                SignalError();
        } break;
        // We shouldn't get top level else or else if statements, they can only be inside an if
        // statement.
        case ExecutableContentTypes::Else:
        case ExecutableContentTypes::ElseIf:
            QT3DS_ASSERT(false);
            break;

        case ExecutableContentTypes::Assign: {
            SAssign &theAssign = *content.CastTo<SAssign>();
            bool success = m_ScriptContext->Assign(theAssign.m_Location, theAssign.m_Expression);
            if (!success)
                SignalError();
        } break;
        case ExecutableContentTypes::Script: {
            SScript &theScript = *content.CastTo<SScript>();
            if (!isTrivial(theScript.m_Data))
                m_ScriptContext->ExecuteScript(theScript.m_Data);
        } break;
        default:
            qCCritical(INTERNAL_ERROR, "Unimplemented executable content %s",
                ExecutableContentTypes::ToString(content.m_Type));
        }
    }

    void ExecuteContent(TExecutableContentList &inContent)
    {
        for (TExecutableContentList::iterator iter = inContent.begin(), end = inContent.end();
             iter != end && m_Error == false; ++iter) {
            ExecuteContent(*iter);
        }
    }

    void Execute(STransition &inTransaction) override
    {
        m_Error = false;
        ExecuteContent(inTransaction.m_ExecutableContent);
    }

    // These functions take the node as well as the list so a context can cache a fast
    // execution path if necessary.
    void Execute(SStateNode & /*inNode*/, TOnEntryList &inList) override
    {
        for (TOnEntryList::iterator iter = inList.begin(), end = inList.end(); iter != end;
             ++iter) {
            m_Error = false;
            ExecuteContent(iter->m_ExecutableContent);
        }
    }

    void Execute(SStateNode & /*inNode*/, TOnExitList &inList) override
    {
        for (TOnExitList::iterator iter = inList.begin(), end = inList.end(); iter != end; ++iter) {
            m_Error = false;
            ExecuteContent(iter->m_ExecutableContent);
        }
    }
};
}

QT3DSU64 IExecutionContext::ParseTimeStrToMilliseconds(const char8_t *timeStr)
{
    if (isTrivial(timeStr))
        return 0;

    char *endPtr;
    double theData = strtod(timeStr, &endPtr);
    if (!isTrivial(endPtr)) {
        if (AreEqual(endPtr, "s")) {
            theData *= 1000;
        } else if (AreEqual(endPtr, "ms")) {
            // empty intentional
        } else
            theData = 0;
    } else
        theData = 0;
    if (theData < 0)
        theData = 0.0;
    return static_cast<QT3DSU64>(theData);
}

IExecutionContext &IExecutionContext::Create(NVFoundationBase &inFoundation,
                                             IStringTable &inStringTable, IStateLogger &inLogger,
                                             IScriptContext &inScriptContext)
{
    return *QT3DS_NEW(inFoundation.getAllocator(), SExecContext)(inFoundation, inStringTable, inLogger,
                                                              inScriptContext);
}