Coverage Report

Created: 2026-11-12 07:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/AssetLib/LWS/LWSLoader.cpp
Line
Count
Source
1
/*
2
---------------------------------------------------------------------------
3
Open Asset Import Library (assimp)
4
---------------------------------------------------------------------------
5
6
Copyright (c) 2006-2026, assimp team
7
8
All rights reserved.
9
10
Redistribution and use of this software in source and binary forms,
11
with or without modification, are permitted provided that the following
12
conditions are met:
13
14
* Redistributions of source code must retain the above
15
  copyright notice, this list of conditions and the
16
  following disclaimer.
17
18
* Redistributions in binary form must reproduce the above
19
  copyright notice, this list of conditions and the
20
  following disclaimer in the documentation and/or other
21
  materials provided with the distribution.
22
23
* Neither the name of the assimp team, nor the names of its
24
  contributors may be used to endorse or promote products
25
  derived from this software without specific prior
26
  written permission of the assimp team.
27
28
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
---------------------------------------------------------------------------
40
*/
41
42
/** @file  LWSLoader.cpp
43
 *  @brief Implementation of the LWS importer class
44
 */
45
46
#ifndef ASSIMP_BUILD_NO_LWS_IMPORTER
47
48
#include "LWSLoader.h"
49
#include "Common/Importer.h"
50
#include "PostProcessing/ConvertToLHProcess.h"
51
52
#include <assimp/GenericProperty.h>
53
#include <assimp/ParsingUtils.h>
54
#include <assimp/SceneCombiner.h>
55
#include <assimp/SkeletonMeshBuilder.h>
56
#include <assimp/fast_atof.h>
57
#include <assimp/importerdesc.h>
58
#include <assimp/scene.h>
59
#include <assimp/DefaultLogger.hpp>
60
#include <assimp/IOSystem.hpp>
61
62
#include <memory>
63
64
using namespace Assimp;
65
66
static constexpr aiImporterDesc desc = {
67
    "LightWave Scene Importer",
68
    "",
69
    "",
70
    "http://www.newtek.com/lightwave.html=",
71
    aiImporterFlags_SupportTextFlavour,
72
    0,
73
    0,
74
    0,
75
    0,
76
    "lws mot"
77
};
78
79
// ------------------------------------------------------------------------------------------------
80
// Recursive parsing of LWS files
81
namespace {
82
    constexpr int MAX_DEPTH = 1000; // Define the maximum depth allowed
83
}
84
85
15.2k
void LWS::Element::Parse(const char *&buffer, const char *end, int depth) {
86
15.2k
    if (depth > MAX_DEPTH) {
87
1
        throw std::runtime_error("Maximum recursion depth exceeded in LWS::Element::Parse");
88
1
    }
89
90
423k
    for (; SkipSpacesAndLineEnd(&buffer, end); SkipLine(&buffer, end)) {
91
92
        // begin of a new element with children
93
417k
        bool sub = false;
94
417k
        if (*buffer == '{') {
95
11.9k
            ++buffer;
96
11.9k
            SkipSpaces(&buffer, end);
97
11.9k
            sub = true;
98
405k
        } else if (*buffer == '}')
99
9.40k
            return;
100
101
408k
        children.emplace_back();
102
103
        // copy data line - read token per token
104
105
408k
        const char *cur = buffer;
106
4.59M
        while (!IsSpaceOrNewLine(*buffer))
107
4.18M
            ++buffer;
108
408k
        children.back().tokens[0] = std::string(cur, (size_t)(buffer - cur));
109
408k
        SkipSpaces(&buffer, end);
110
111
408k
        if (children.back().tokens[0] == "Plugin") {
112
1.27k
            ASSIMP_LOG_VERBOSE_DEBUG("LWS: Skipping over plugin-specific data");
113
114
            // strange stuff inside Plugin/Endplugin blocks. Needn't
115
            // follow LWS syntax, so we skip over it
116
4.50k
            for (; SkipSpacesAndLineEnd(&buffer, end); SkipLine(&buffer, end)) {
117
4.42k
                if (!::strncmp(buffer, "EndPlugin", 9)) {
118
1.19k
                    break;
119
1.19k
                }
120
4.42k
            }
121
1.27k
            continue;
122
1.27k
        }
123
124
407k
        cur = buffer;
125
4.30M
        while (!IsLineEnd(*buffer)) {
126
3.89M
            ++buffer;
127
3.89M
        }
128
407k
        children.back().tokens[1] = std::string(cur, (size_t)(buffer - cur));
129
130
        // parse more elements recursively
131
407k
        if (sub) {
132
11.9k
            children.back().Parse(buffer, end, depth + 1);
133
11.9k
        }
134
407k
    }
135
15.2k
}
136
137
// ------------------------------------------------------------------------------------------------
138
// Constructor to be privately used by Importer
139
LWSImporter::LWSImporter() :
140
        configSpeedFlag(),
141
        io(),
142
        first(),
143
        last(),
144
        fps(),
145
165k
        noSkeletonMesh() {
146
    // nothing to do here
147
165k
}
148
149
// ------------------------------------------------------------------------------------------------
150
// Returns whether the class can handle the format of the given file.
151
12.1k
bool LWSImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
152
12.1k
    static constexpr uint32_t tokens[] = {
153
12.1k
        AI_MAKE_MAGIC("LWSC"),
154
12.1k
        AI_MAKE_MAGIC("LWMO")
155
12.1k
    };
156
12.1k
    return CheckMagicToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
157
12.1k
}
158
159
// ------------------------------------------------------------------------------------------------
160
// Get list of file extensions
161
165k
const aiImporterDesc *LWSImporter::GetInfo() const {
162
165k
    return &desc;
163
165k
}
164
165
static constexpr int MagicHackNo = 150392;
166
167
// ------------------------------------------------------------------------------------------------
168
// Setup configuration properties
169
3.31k
void LWSImporter::SetupProperties(const Importer *pImp) {
170
    // AI_CONFIG_FAVOUR_SPEED
171
3.31k
    configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED, 0));
172
173
    // AI_CONFIG_IMPORT_LWS_ANIM_START
174
3.31k
    first = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWS_ANIM_START,
175
3.31k
            MagicHackNo /* magic hack */);
176
177
    // AI_CONFIG_IMPORT_LWS_ANIM_END
178
3.31k
    last = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWS_ANIM_END,
179
3.31k
            MagicHackNo /* magic hack */);
180
181
3.31k
    if (last < first) {
182
0
        std::swap(last, first);
183
0
    }
184
185
3.31k
    noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0;
186
3.31k
}
187
188
// ------------------------------------------------------------------------------------------------
189
// Read an envelope description
190
6.34k
void LWSImporter::ReadEnvelope(const LWS::Element &dad, LWO::Envelope &fill) {
191
6.34k
    if (dad.children.empty()) {
192
11
        ASSIMP_LOG_ERROR("LWS: Envelope descriptions must not be empty");
193
11
        return;
194
11
    }
195
196
    // reserve enough storage
197
6.33k
    std::list<LWS::Element>::const_iterator it = dad.children.begin();
198
199
6.33k
    fill.keys.reserve(strtoul10(it->tokens[1].c_str()));
200
201
29.3k
    for (++it; it != dad.children.end(); ++it) {
202
23.0k
        const char *c = (*it).tokens[1].c_str();
203
23.0k
        const char *end = c + (*it).tokens[1].size();
204
205
23.0k
        if ((*it).tokens[0] == "Key") {
206
8.84k
            fill.keys.emplace_back();
207
8.84k
            LWO::Key &key = fill.keys.back();
208
209
8.84k
            float f;
210
8.84k
            SkipSpaces(&c, end);
211
8.84k
            c = fast_atoreal_move(c, key.value);
212
8.84k
            SkipSpaces(&c, end);
213
8.84k
            c = fast_atoreal_move(c, f);
214
215
8.84k
            key.time = f;
216
217
8.84k
            unsigned int span = strtoul10(c, &c), num = 0;
218
8.84k
            switch (span) {
219
8.78k
                case 0:
220
8.78k
                    key.inter = LWO::IT_TCB;
221
8.78k
                    num = 5;
222
8.78k
                    break;
223
2
                case 1:
224
4
                case 2:
225
4
                    key.inter = LWO::IT_HERM;
226
4
                    num = 5;
227
4
                    break;
228
0
                case 3:
229
0
                    key.inter = LWO::IT_LINE;
230
0
                    num = 0;
231
0
                    break;
232
0
                case 4:
233
0
                    key.inter = LWO::IT_STEP;
234
0
                    num = 0;
235
0
                    break;
236
0
                case 5:
237
0
                    key.inter = LWO::IT_BEZ2;
238
0
                    num = 4;
239
0
                    break;
240
26
                default:
241
26
                    ASSIMP_LOG_ERROR("LWS: Unknown span type");
242
8.84k
            }
243
52.6k
            for (unsigned int i = 0; i < num; ++i) {
244
43.8k
                SkipSpaces(&c, end);
245
43.8k
                c = fast_atoreal_move(c, key.params[i]);
246
43.8k
            }
247
14.2k
        } else if ((*it).tokens[0] == "Behaviors") {
248
4.55k
            SkipSpaces(&c, end);
249
4.55k
            fill.pre = (LWO::PrePostBehaviour)strtoul10(c, &c);
250
4.55k
            SkipSpaces(&c, end);
251
4.55k
            fill.post = (LWO::PrePostBehaviour)strtoul10(c, &c);
252
4.55k
        }
253
23.0k
    }
254
6.33k
}
255
256
// ------------------------------------------------------------------------------------------------
257
// Read animation channels in the old LightWave animation format
258
void LWSImporter::ReadEnvelope_Old(std::list<LWS::Element>::const_iterator &it,const std::list<LWS::Element>::const_iterator &endIt,
259
4.17k
        LWS::NodeDesc &nodes, unsigned int) {
260
4.17k
    if (++it == endIt) {
261
1
        ASSIMP_LOG_ERROR("LWS: Encountered unexpected end of file while parsing object motion");
262
1
        return;
263
1
    }
264
265
4.17k
    const unsigned int num = strtoul10((*it).tokens[0].c_str());
266
33.1k
    for (unsigned int i = 0; i < num; ++i) {
267
28.9k
        nodes.channels.emplace_back();
268
28.9k
        LWO::Envelope &envl = nodes.channels.back();
269
270
28.9k
        envl.index = i;
271
28.9k
        envl.type = (LWO::EnvelopeType)(i + 1);
272
273
28.9k
        if (++it == endIt) {
274
1
            ASSIMP_LOG_ERROR("LWS: Encountered unexpected end of file while parsing object motion");
275
1
            return;
276
1
        }
277
278
28.9k
        const unsigned int sub_num = strtoul10((*it).tokens[0].c_str());
279
60.7k
        for (unsigned int n = 0; n < sub_num; ++n) {
280
31.7k
            if (++it == endIt) {
281
1
                ASSIMP_LOG_ERROR("LWS: Encountered unexpected end of file while parsing object motion");
282
1
                return;
283
1
            }
284
285
            // parse value and time, skip the rest for the moment.
286
31.7k
            LWO::Key key;
287
31.7k
            const char *c = fast_atoreal_move((*it).tokens[0].c_str(), key.value);
288
31.7k
            const char *end = c + (*it).tokens[0].size();
289
31.7k
            SkipSpaces(&c, end);
290
31.7k
            float f;
291
31.7k
            fast_atoreal_move((*it).tokens[0].c_str(), f);
292
31.7k
            key.time = f;
293
294
31.7k
            envl.keys.emplace_back(key);
295
31.7k
        }
296
28.9k
    }
297
4.17k
}
298
299
// ------------------------------------------------------------------------------------------------
300
// Setup a nice name for a node
301
72.2k
void LWSImporter::SetupNodeName(aiNode *nd, LWS::NodeDesc &src) {
302
72.2k
    const unsigned int combined = src.number | ((unsigned int)src.type) << 28u;
303
304
    // the name depends on the type. We break LWS's strange naming convention
305
    // and return human-readable, but still machine-parsable and unique, strings.
306
72.2k
    if (src.type == LWS::NodeDesc::OBJECT) {
307
49.6k
        if (src.path.length()) {
308
49.6k
            std::string::size_type s = src.path.find_last_of("\\/");
309
49.6k
            if (s == std::string::npos) {
310
47.4k
                s = 0;
311
47.4k
            } else {
312
2.19k
                ++s;
313
2.19k
            }
314
49.6k
            std::string::size_type t = src.path.substr(s).find_last_of('.');
315
316
49.6k
            nd->mName.length = ::ai_snprintf(nd->mName.data, AI_MAXLEN, "%s_(%08X)", src.path.substr(s).substr(0, t).c_str(), combined);
317
49.6k
            if (nd->mName.length > AI_MAXLEN) {
318
52
                nd->mName.length = AI_MAXLEN;
319
52
            }
320
49.6k
            return;
321
49.6k
        }
322
49.6k
    }
323
22.6k
    nd->mName.length = ::ai_snprintf(nd->mName.data, AI_MAXLEN, "%s_(%08X)", src.name, combined);
324
22.6k
}
325
326
// ------------------------------------------------------------------------------------------------
327
// Recursively build the scene-graph
328
void LWSImporter::BuildGraph(aiNode *nd, LWS::NodeDesc &src, std::vector<AttachmentInfo> &attach,
329
        BatchLoader &batch,
330
        aiCamera **&camOut,
331
        aiLight **&lightOut,
332
47.4k
        std::vector<aiNodeAnim *> &animOut) {
333
    // Setup a very cryptic name for the node, we want the user to be happy
334
47.4k
    SetupNodeName(nd, src);
335
47.4k
    aiNode *ndAnim = nd;
336
337
    // If the node is an object
338
47.4k
    if (src.type == LWS::NodeDesc::OBJECT) {
339
340
        // If the object is from an external file, get it
341
24.8k
        aiScene *obj = nullptr;
342
24.8k
        if (src.path.length()) {
343
24.8k
            obj = batch.GetImport(src.id);
344
24.8k
            if (!obj) {
345
24.7k
                ASSIMP_LOG_ERROR("LWS: Failed to read external file ", src.path);
346
24.7k
            } else {
347
19
                if (obj->mRootNode->mNumChildren == 1) {
348
349
                    //If the pivot is not set for this layer, get it from the external object
350
0
                    if (!src.isPivotSet) {
351
0
                        src.pivotPos.x = +obj->mRootNode->mTransformation.a4;
352
0
                        src.pivotPos.y = +obj->mRootNode->mTransformation.b4;
353
0
                        src.pivotPos.z = -obj->mRootNode->mTransformation.c4; //The sign is the RH to LH back conversion
354
0
                    }
355
356
                    //Remove first node from obj (the old pivot), reset transform of second node (the mesh node)
357
0
                    aiNode *newRootNode = obj->mRootNode->mChildren[0];
358
0
                    obj->mRootNode->mChildren[0] = nullptr;
359
0
                    delete obj->mRootNode;
360
361
0
                    obj->mRootNode = newRootNode;
362
0
                    obj->mRootNode->mTransformation.a4 = 0.0;
363
0
                    obj->mRootNode->mTransformation.b4 = 0.0;
364
0
                    obj->mRootNode->mTransformation.c4 = 0.0;
365
0
                }
366
19
            }
367
24.8k
        }
368
369
        //Setup the pivot node (also the animation node), the one we received
370
24.8k
        nd->mName = std::string("Pivot:") + nd->mName.data;
371
24.8k
        ndAnim = nd;
372
373
        //Add the attachment node to it
374
24.8k
        nd->mNumChildren = 1;
375
24.8k
        nd->mChildren = new aiNode *[1];
376
24.8k
        nd->mChildren[0] = new aiNode();
377
24.8k
        nd->mChildren[0]->mParent = nd;
378
24.8k
        nd->mChildren[0]->mTransformation.a4 = -src.pivotPos.x;
379
24.8k
        nd->mChildren[0]->mTransformation.b4 = -src.pivotPos.y;
380
24.8k
        nd->mChildren[0]->mTransformation.c4 = -src.pivotPos.z;
381
24.8k
        SetupNodeName(nd->mChildren[0], src);
382
383
        //Update the attachment node
384
24.8k
        nd = nd->mChildren[0];
385
386
        //Push attachment, if the object came from an external file
387
24.8k
        if (obj) {
388
19
            attach.emplace_back(obj, nd);
389
19
        }
390
24.8k
    }
391
392
    // If object is a light source - setup a corresponding ai structure
393
22.5k
    else if (src.type == LWS::NodeDesc::LIGHT) {
394
18.4k
        aiLight *lit = *lightOut++ = new aiLight();
395
396
        // compute final light color
397
18.4k
        lit->mColorDiffuse = lit->mColorSpecular = src.lightColor * src.lightIntensity;
398
399
        // name to attach light to node -> unique due to LWs indexing system
400
18.4k
        lit->mName = nd->mName;
401
402
        // determine light type and setup additional members
403
18.4k
        if (src.lightType == 2) { /* spot light */
404
405
98
            lit->mType = aiLightSource_SPOT;
406
98
            lit->mAngleInnerCone = (float)AI_DEG_TO_RAD(src.lightConeAngle);
407
98
            lit->mAngleOuterCone = lit->mAngleInnerCone + (float)AI_DEG_TO_RAD(src.lightEdgeAngle);
408
409
18.3k
        } else if (src.lightType == 1) { /* directional light source */
410
51
            lit->mType = aiLightSource_DIRECTIONAL;
411
18.2k
        } else {
412
18.2k
            lit->mType = aiLightSource_POINT;
413
18.2k
        }
414
415
        // fixme: no proper handling of light falloffs yet
416
18.4k
        if (src.lightFalloffType == 1) {
417
0
            lit->mAttenuationConstant = 1.f;
418
18.4k
        } else if (src.lightFalloffType == 2) {
419
0
            lit->mAttenuationLinear = 1.f;
420
18.4k
        } else {
421
18.4k
            lit->mAttenuationQuadratic = 1.f;
422
18.4k
        }
423
18.4k
    } else if (src.type == LWS::NodeDesc::CAMERA) { // If object is a camera - setup a corresponding ai structure
424
4.15k
        aiCamera *cam = *camOut++ = new aiCamera();
425
426
        // name to attach cam to node -> unique due to LWs indexing system
427
4.15k
        cam->mName = nd->mName;
428
4.15k
    }
429
430
    // Get the node transformation from the LWO key
431
47.4k
    LWO::AnimResolver resolver(src.channels, fps);
432
47.4k
    resolver.ExtractBindPose(ndAnim->mTransformation);
433
434
    // .. and construct animation channels
435
47.4k
    aiNodeAnim *anim = nullptr;
436
437
47.4k
    if (first != last) {
438
47.1k
        resolver.SetAnimationRange(first, last);
439
47.1k
        resolver.ExtractAnimChannel(&anim, AI_LWO_ANIM_FLAG_SAMPLE_ANIMS | AI_LWO_ANIM_FLAG_START_AT_ZERO);
440
47.1k
        if (anim) {
441
2.87k
            anim->mNodeName = ndAnim->mName;
442
2.87k
            animOut.push_back(anim);
443
2.87k
        }
444
47.1k
    }
445
446
    // Add children
447
47.4k
    if (!src.children.empty()) {
448
2
        nd->mChildren = new aiNode *[src.children.size()];
449
4
        for (std::list<LWS::NodeDesc *>::iterator it = src.children.begin(); it != src.children.end(); ++it) {
450
2
            aiNode *ndd = nd->mChildren[nd->mNumChildren++] = new aiNode();
451
2
            ndd->mParent = nd;
452
453
2
            BuildGraph(ndd, **it, attach, batch, camOut, lightOut, animOut);
454
2
        }
455
2
    }
456
47.4k
}
457
458
// ------------------------------------------------------------------------------------------------
459
// Determine the exact location of a LWO file
460
32.0k
std::string LWSImporter::FindLWOFile(const std::string &in) {
461
    // insert missing directory separator if necessary
462
32.0k
    std::string tmp(in);
463
32.0k
    if (in.length() > 3 && in[1] == ':' && in[2] != '\\' && in[2] != '/') {
464
202
        tmp = in[0] + (std::string(":\\") + in.substr(2));
465
202
    }
466
467
32.0k
    if (io->Exists(tmp)) {
468
2.63k
        return in;
469
2.63k
    }
470
471
    // file is not accessible for us ... maybe it's packed by
472
    // LightWave's 'Package Scene' command?
473
474
    // Relevant for us are the following two directories:
475
    // <folder>\Objects\<hh>\<*>.lwo
476
    // <folder>\Scenes\<hh>\<*>.lws
477
    // where <hh> is optional.
478
479
29.3k
    std::string test = std::string("..") + (io->getOsSeparator() + tmp);
480
29.3k
    if (io->Exists(test)) {
481
4
        return test;
482
4
    }
483
484
29.3k
    test = std::string("..") + (io->getOsSeparator() + test);
485
29.3k
    if (io->Exists(test)) {
486
0
        return test;
487
0
    }
488
489
    // return original path, maybe the IOsystem knows better
490
29.3k
    return tmp;
491
29.3k
}
492
493
// ------------------------------------------------------------------------------------------------
494
// Read file into given scene data structure
495
3.31k
void LWSImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
496
3.31k
    io = pIOHandler;
497
3.31k
    std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
498
499
    // Check whether we can read from the file
500
3.31k
    if (file == nullptr) {
501
0
        throw DeadlyImportError("Failed to open LWS file ", pFile, ".");
502
0
    }
503
504
    // Allocate storage and copy the contents of the file to a memory buffer
505
3.31k
    std::vector<char> mBuffer;
506
3.31k
    TextFileToBuffer(file.get(), mBuffer);
507
508
    // Parse the file structure
509
3.31k
    LWS::Element root;
510
3.31k
    const char *dummy = &mBuffer[0];
511
3.31k
    const char *dummyEnd = dummy + mBuffer.size();
512
3.31k
    root.Parse(dummy, dummyEnd);
513
514
    // Construct a Batch-importer to read more files recursively
515
3.31k
    BatchLoader batch(pIOHandler);
516
517
    // Construct an array to receive the flat output graph
518
3.31k
    std::list<LWS::NodeDesc> nodes;
519
520
3.31k
    unsigned int cur_light = 0, cur_camera = 0, cur_object = 0;
521
3.31k
    unsigned int num_light = 0, num_camera = 0;
522
523
    // check magic identifier, 'LWSC'
524
3.31k
    bool motion_file = false;
525
3.31k
    std::list<LWS::Element>::const_iterator it = root.children.begin();
526
527
3.31k
    if (it == root.children.end()) {
528
0
        throw DeadlyImportError("LWS: Not a LightWave scene, no elements found");
529
0
    }
530
531
3.31k
    if ((*it).tokens[0] == "LWMO") {
532
11
        motion_file = true;
533
11
    }
534
535
3.31k
    if ((*it).tokens[0] != "LWSC" && !motion_file) {
536
62
        throw DeadlyImportError("LWS: Not a LightWave scene, magic tag LWSC not found");
537
62
    }
538
539
    // get file format version and print to log
540
3.25k
    ++it;
541
542
3.25k
    if (it == root.children.end() || (*it).tokens[0].empty()) {
543
6
        throw DeadlyImportError("LWS: Missing file format version");
544
6
    }
545
3.24k
    unsigned int version = strtoul10((*it).tokens[0].c_str());
546
3.24k
    ASSIMP_LOG_INFO("LWS file format version is ", (*it).tokens[0]);
547
3.24k
    first = 0.;
548
3.24k
    last = 60.;
549
3.24k
    fps = 25.; // seems to be a good default frame rate
550
551
    // Now read all elements in a very straightforward manner
552
269k
    for (; it != root.children.end(); ++it) {
553
266k
        const char *c = (*it).tokens[1].c_str();
554
266k
        const char *end = c + (*it).tokens[1].size();
555
556
        // 'FirstFrame': begin of animation slice
557
266k
        if ((*it).tokens[0] == "FirstFrame") {
558
            // see SetupProperties()
559
4.78k
            if (150392. != first ) {
560
4.78k
                first = strtoul10(c, &c) - 1.; // we're zero-based
561
4.78k
            }
562
262k
        } else if ((*it).tokens[0] == "LastFrame") { // 'LastFrame': end of animation slice
563
            // see SetupProperties()
564
2.55k
            if (150392. != last ) {
565
2.55k
                last = strtoul10(c, &c) - 1.; // we're zero-based
566
2.55k
            }
567
259k
        } else if ((*it).tokens[0] == "FramesPerSecond") { // 'FramesPerSecond': frames per second
568
2.97k
            fps = strtoul10(c, &c);
569
256k
        } else if ((*it).tokens[0] == "LoadObjectLayer") { // 'LoadObjectLayer': load a layer of a specific LWO file
570
571
            // get layer index
572
26.8k
            const int layer = strtoul10(c, &c);
573
574
            // setup the layer to be loaded
575
26.8k
            BatchLoader::PropertyMap props;
576
26.8k
            SetGenericProperty(props.ints, AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY, layer);
577
578
            // add node to list
579
26.8k
            LWS::NodeDesc d;
580
26.8k
            d.type = LWS::NodeDesc::OBJECT;
581
26.8k
            if (version >= 4) { // handle LWSC 4 explicit ID
582
9.37k
                SkipSpaces(&c, end);
583
9.37k
                d.number = strtoul16(c, &c) & AI_LWS_MASK;
584
17.4k
            } else {
585
17.4k
                d.number = cur_object++;
586
17.4k
            }
587
588
            // and add the file to the import list
589
26.8k
            SkipSpaces(&c, end);
590
26.8k
            std::string path = FindLWOFile(c);
591
592
26.8k
            if (path.empty()) {
593
60
                throw DeadlyImportError("LWS: Invalid LoadObjectLayer: empty path.");
594
60
            }
595
596
26.7k
            if (path == pFile) {
597
146
                throw DeadlyImportError("LWS: Invalid LoadObjectLayer: self reference.");
598
146
            }
599
600
26.6k
            d.path = path;
601
26.6k
            d.id = batch.AddLoadRequest(path, 0, &props);
602
603
26.6k
            nodes.push_back(d);
604
229k
        } else if ((*it).tokens[0] == "LoadObject") { // 'LoadObject': load a LWO file into the scene-graph
605
606
            // add node to list
607
5.18k
            LWS::NodeDesc d;
608
5.18k
            d.type = LWS::NodeDesc::OBJECT;
609
610
5.18k
            if (version >= 4) { // handle LWSC 4 explicit ID
611
455
                d.number = strtoul16(c, &c) & AI_LWS_MASK;
612
455
                SkipSpaces(&c, end);
613
4.73k
            } else {
614
4.73k
                d.number = cur_object++;
615
4.73k
            }
616
5.18k
            std::string path = FindLWOFile(c);
617
618
5.18k
            if (path.empty()) {
619
17
                throw DeadlyImportError("LWS: Invalid LoadObject: empty path.");
620
17
            }
621
622
5.17k
            if (path == pFile) {
623
342
                throw DeadlyImportError("LWS: Invalid LoadObject: self reference.");
624
342
            }
625
626
4.82k
            d.id = batch.AddLoadRequest(path, 0, nullptr);
627
628
4.82k
            d.path = path;
629
4.82k
            nodes.push_back(d);
630
224k
        } else if ((*it).tokens[0] == "AddNullObject") { // 'AddNullObject': add a dummy node to the hierarchy
631
632
            // add node to list
633
5
            LWS::NodeDesc d;
634
5
            d.type = LWS::NodeDesc::OBJECT;
635
5
            if (version >= 4) { // handle LWSC 4 explicit ID
636
0
                d.number = strtoul16(c, &c) & AI_LWS_MASK;
637
0
                SkipSpaces(&c, end);
638
5
            } else {
639
5
                d.number = cur_object++;
640
5
            }
641
5
            d.name = c;
642
5
            nodes.push_back(d);
643
5
        }
644
        // 'NumChannels': Number of envelope channels assigned to last layer
645
224k
        else if ((*it).tokens[0] == "NumChannels") {
646
            // ignore for now
647
1.30k
        }
648
        // 'Channel': preceedes any envelope description
649
223k
        else if ((*it).tokens[0] == "Channel") {
650
8.03k
            if (nodes.empty()) {
651
481
                if (motion_file) {
652
653
                    // LightWave motion file. Add dummy node
654
1
                    LWS::NodeDesc d;
655
1
                    d.type = LWS::NodeDesc::OBJECT;
656
1
                    d.name = c;
657
1
                    d.number = cur_object++;
658
1
                    nodes.push_back(d);
659
1
                }
660
481
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'Channel\'");
661
7.55k
            } else {
662
                // important: index of channel
663
7.55k
                nodes.back().channels.emplace_back();
664
7.55k
                LWO::Envelope &env = nodes.back().channels.back();
665
666
7.55k
                env.index = strtoul10(c);
667
668
                // currently we can just interpret the standard channels 0...9
669
                // (hack) assume that index-i yields the binary channel type from LWO
670
7.55k
                env.type = (LWO::EnvelopeType)(env.index + 1);
671
7.55k
            }
672
8.03k
        }
673
        // 'Envelope': a single animation channel
674
215k
        else if ((*it).tokens[0] == "Envelope") {
675
6.57k
            if (nodes.empty() || nodes.back().channels.empty())
676
6.57k
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'Envelope\'");
677
6.34k
            else {
678
6.34k
                ReadEnvelope((*it), nodes.back().channels.back());
679
6.34k
            }
680
6.57k
        }
681
        // 'ObjectMotion': animation information for older lightwave formats
682
208k
        else if (version < 3 && ((*it).tokens[0] == "ObjectMotion" ||
683
149k
                                        (*it).tokens[0] == "CameraMotion" ||
684
148k
                                        (*it).tokens[0] == "LightMotion")) {
685
686
4.32k
            if (nodes.empty())
687
4.32k
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'<Light|Object|Camera>Motion\'");
688
4.17k
            else {
689
4.17k
                ReadEnvelope_Old(it, root.children.end(), nodes.back(), version);
690
4.17k
            }
691
4.32k
        }
692
        // 'Pre/PostBehavior': pre/post animation behaviour for LWSC 2
693
204k
        else if (version == 2 && (*it).tokens[0] == "Pre/PostBehavior") {
694
1.53k
            if (nodes.empty())
695
1.53k
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'Pre/PostBehavior'");
696
1.49k
            else {
697
53.1k
                for (std::list<LWO::Envelope>::iterator envelopeIt = nodes.back().channels.begin(); envelopeIt != nodes.back().channels.end(); ++envelopeIt) {
698
                    // two ints per envelope
699
51.6k
                    LWO::Envelope &env = *envelopeIt;
700
51.6k
                    env.pre = (LWO::PrePostBehaviour)strtoul10(c, &c);
701
51.6k
                    SkipSpaces(&c, end);
702
51.6k
                    env.post = (LWO::PrePostBehaviour)strtoul10(c, &c);
703
51.6k
                    SkipSpaces(&c, end);
704
51.6k
                }
705
1.49k
            }
706
1.53k
        }
707
        // 'ParentItem': specifies the parent of the current element
708
202k
        else if ((*it).tokens[0] == "ParentItem") {
709
133
            if (nodes.empty()) {
710
19
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'ParentItem\'");
711
114
            } else {
712
114
                nodes.back().parent = strtoul16(c, &c);
713
114
            }
714
133
        }
715
        // 'ParentObject': deprecated one for older formats
716
202k
        else if (version < 3 && (*it).tokens[0] == "ParentObject") {
717
4
            if (nodes.empty()) {
718
2
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'ParentObject\'");
719
2
            } else {
720
2
                nodes.back().parent = strtoul10(c, &c) | (1u << 28u);
721
2
            }
722
4
        }
723
        // 'AddCamera': add a camera to the scenegraph
724
202k
        else if ((*it).tokens[0] == "AddCamera") {
725
726
            // add node to list
727
4.18k
            LWS::NodeDesc d;
728
4.18k
            d.type = LWS::NodeDesc::CAMERA;
729
730
4.18k
            if (version >= 4) { // handle LWSC 4 explicit ID
731
32
                d.number = strtoul16(c, &c) & AI_LWS_MASK;
732
4.15k
            } else {
733
4.15k
                d.number = cur_camera++;
734
4.15k
            }
735
4.18k
            nodes.push_back(d);
736
737
4.18k
            num_camera++;
738
4.18k
        }
739
        // 'CameraName': set name of currently active camera
740
198k
        else if ((*it).tokens[0] == "CameraName") {
741
1.70k
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::CAMERA) {
742
190
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'CameraName\'");
743
1.51k
            } else {
744
1.51k
                nodes.back().name = c;
745
1.51k
            }
746
1.70k
        }
747
        // 'AddLight': add a light to the scenegraph
748
196k
        else if ((*it).tokens[0] == "AddLight") {
749
750
            // add node to list
751
18.5k
            LWS::NodeDesc d;
752
18.5k
            d.type = LWS::NodeDesc::LIGHT;
753
754
18.5k
            if (version >= 4) { // handle LWSC 4 explicit ID
755
2.68k
                d.number = strtoul16(c, &c) & AI_LWS_MASK;
756
15.8k
            } else {
757
15.8k
                d.number = cur_light++;
758
15.8k
            }
759
18.5k
            nodes.push_back(d);
760
761
18.5k
            num_light++;
762
18.5k
        }
763
        // 'LightName': set name of currently active light
764
178k
        else if ((*it).tokens[0] == "LightName") {
765
2.65k
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) {
766
222
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'LightName\'");
767
2.43k
            } else {
768
2.43k
                nodes.back().name = c;
769
2.43k
            }
770
2.65k
        }
771
        // 'LightIntensity': set intensity of currently active light
772
175k
        else if ((*it).tokens[0] == "LightIntensity" || (*it).tokens[0] == "LgtIntensity") {
773
1.71k
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) {
774
876
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'LightIntensity\'");
775
876
            } else {
776
840
                const std::string env = "(envelope)";
777
840
                if (0 == strncmp(c, env.c_str(), env.size())) {
778
0
                    ASSIMP_LOG_ERROR("LWS: envelopes for  LightIntensity not supported, set to 1.0");
779
0
                    nodes.back().lightIntensity = (ai_real)1.0;
780
840
                } else {
781
840
                    fast_atoreal_move(c, nodes.back().lightIntensity);
782
840
                }
783
840
            }
784
1.71k
        }
785
        // 'LightType': set type of currently active light
786
173k
        else if ((*it).tokens[0] == "LightType") {
787
1.78k
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) {
788
1.23k
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'LightType\'");
789
1.23k
            } else {
790
548
                nodes.back().lightType = strtoul10(c);
791
548
            }
792
1.78k
        }
793
        // 'LightFalloffType': set falloff type of currently active light
794
172k
        else if ((*it).tokens[0] == "LightFalloffType") {
795
56
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) {
796
53
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'LightFalloffType\'");
797
53
            } else {
798
3
                nodes.back().lightFalloffType = strtoul10(c);
799
3
            }
800
56
        }
801
        // 'LightConeAngle': set cone angle of currently active light
802
172k
        else if ((*it).tokens[0] == "LightConeAngle") {
803
13
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) {
804
13
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'LightConeAngle\'");
805
13
            } else {
806
0
                nodes.back().lightConeAngle = fast_atof(c);
807
0
            }
808
13
        }
809
        // 'LightEdgeAngle': set area where we're smoothing from min to max intensity
810
172k
        else if ((*it).tokens[0] == "LightEdgeAngle") {
811
21
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) {
812
21
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'LightEdgeAngle\'");
813
21
            } else {
814
0
                nodes.back().lightEdgeAngle = fast_atof(c);
815
0
            }
816
21
        }
817
        // 'LightColor': set color of currently active light
818
172k
        else if ((*it).tokens[0] == "LightColor") {
819
1.45k
            if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) {
820
884
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'LightColor\'");
821
884
            } else {
822
570
                c = fast_atoreal_move(c, nodes.back().lightColor.r);
823
570
                SkipSpaces(&c, end);
824
570
                c = fast_atoreal_move(c, nodes.back().lightColor.g);
825
570
                SkipSpaces(&c, end);
826
570
                c = fast_atoreal_move(c, nodes.back().lightColor.b);
827
570
            }
828
1.45k
        }
829
830
        // 'PivotPosition': position of local transformation origin
831
170k
        else if ((*it).tokens[0] == "PivotPosition" || (*it).tokens[0] == "PivotPoint") {
832
38
            if (nodes.empty()) {
833
21
                ASSIMP_LOG_ERROR("LWS: Unexpected keyword: \'PivotPosition\'");
834
21
            } else {
835
17
                c = fast_atoreal_move(c, nodes.back().pivotPos.x);
836
17
                SkipSpaces(&c, end);
837
17
                c = fast_atoreal_move(c, nodes.back().pivotPos.y);
838
17
                SkipSpaces(&c, end);
839
17
                c = fast_atoreal_move(c, nodes.back().pivotPos.z);
840
                // Mark pivotPos as set
841
17
                nodes.back().isPivotSet = true;
842
17
            }
843
38
        }
844
266k
    }
845
846
    // resolve parenting
847
50.0k
    for (std::list<LWS::NodeDesc>::iterator ndIt = nodes.begin(); ndIt != nodes.end(); ++ndIt) {
848
        // check whether there is another node which calls us a parent
849
63.4M
        for (std::list<LWS::NodeDesc>::iterator dit = nodes.begin(); dit != nodes.end(); ++dit) {
850
63.4M
            if (dit != ndIt && *ndIt == (*dit).parent) {
851
2
                if ((*dit).parent_resolved) {
852
                    // fixme: it's still possible to produce an overflow due to cross references ..
853
0
                    ASSIMP_LOG_ERROR("LWS: Found cross reference in scene-graph");
854
0
                    continue;
855
0
                }
856
857
2
                ndIt->children.push_back(&*dit);
858
2
                (*dit).parent_resolved = &*ndIt;
859
2
            }
860
63.4M
        }
861
47.4k
    }
862
863
    // find out how many nodes have no parent yet
864
2.68k
    unsigned int no_parent = 0;
865
50.0k
    for (std::list<LWS::NodeDesc>::iterator ndIt = nodes.begin(); ndIt != nodes.end(); ++ndIt) {
866
47.4k
        if (!ndIt->parent_resolved) {
867
47.4k
            ++no_parent;
868
47.4k
        }
869
47.4k
    }
870
2.68k
    if (!no_parent) {
871
628
        throw DeadlyImportError("LWS: Unable to find scene root node");
872
628
    }
873
874
    // Load all subsequent files
875
2.05k
    batch.LoadAll();
876
877
    // and build the final output graph by attaching the loaded external
878
    // files to ourselves. first build a master graph
879
2.05k
    aiScene *master = new aiScene();
880
2.05k
    aiNode *nd = master->mRootNode = new aiNode();
881
882
    // allocate storage for cameras&lights
883
2.05k
    if (num_camera > 0u) {
884
163
        master->mCameras = new aiCamera *[master->mNumCameras = num_camera];
885
163
    }
886
2.05k
    aiCamera **cams = master->mCameras;
887
2.05k
    if (num_light) {
888
336
        master->mLights = new aiLight *[master->mNumLights = num_light];
889
336
    }
890
2.05k
    aiLight **lights = master->mLights;
891
892
2.05k
    std::vector<AttachmentInfo> attach;
893
2.05k
    std::vector<aiNodeAnim *> anims;
894
895
2.05k
    nd->mName.Set("<LWSRoot>");
896
2.05k
    nd->mChildren = new aiNode *[no_parent];
897
49.4k
    for (std::list<LWS::NodeDesc>::iterator ndIt = nodes.begin(); ndIt != nodes.end(); ++ndIt) {
898
47.4k
        if (!ndIt->parent_resolved) {
899
47.4k
            aiNode *ro = nd->mChildren[nd->mNumChildren++] = new aiNode();
900
47.4k
            ro->mParent = nd;
901
902
            // ... and build the scene graph. If we encounter object nodes,
903
            // add then to our attachment table.
904
47.4k
            BuildGraph(ro, *ndIt, attach, batch, cams, lights, anims);
905
47.4k
        }
906
47.4k
    }
907
908
    // create a master animation channel for us
909
2.05k
    if (anims.size()) {
910
640
        master->mAnimations = new aiAnimation *[master->mNumAnimations = 1];
911
640
        aiAnimation *anim = master->mAnimations[0] = new aiAnimation();
912
640
        anim->mName.Set("LWSMasterAnim");
913
914
        // LWS uses seconds as time units, but we convert to frames
915
640
        anim->mTicksPerSecond = fps;
916
640
        anim->mDuration = last - (first - 1); /* fixme ... zero or one-based?*/
917
918
640
        anim->mChannels = new aiNodeAnim *[anim->mNumChannels = static_cast<unsigned int>(anims.size())];
919
640
        std::copy(anims.begin(), anims.end(), anim->mChannels);
920
640
    }
921
922
    // convert the master scene to RH
923
2.05k
    MakeLeftHandedProcess monster_cheat;
924
2.05k
    monster_cheat.Execute(master);
925
926
    // .. ccw
927
2.05k
    FlipWindingOrderProcess flipper;
928
2.05k
    flipper.Execute(master);
929
930
    // OK ... finally build the output graph
931
2.05k
    SceneCombiner::MergeScenes(&pScene, master, attach,
932
2.05k
            AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES | (!configSpeedFlag ? (
933
1.93k
                                                                              AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY | AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) :
934
2.05k
                                                                      0));
935
936
    // Check flags
937
2.05k
    if (!pScene->mNumMeshes || !pScene->mNumMaterials) {
938
1.92k
        pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
939
940
1.92k
        if (pScene->mNumAnimations && !noSkeletonMesh) {
941
            // construct skeleton mesh
942
640
            SkeletonMeshBuilder builder(pScene);
943
640
        }
944
1.92k
    }
945
2.05k
}
946
947
#endif // !! ASSIMP_BUILD_NO_LWS_IMPORTER