summaryrefslogtreecommitdiffstats
path: root/src/render/geometry/qmesh.cpp
blob: 4aa5ae5b5aa036966c67d17eb4ac61e6257ac334 (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
// Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qmesh.h"
#include "qmesh_p.h"

#include <QtCore/private/qfactoryloader_p.h>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QScopedPointer>
#include <QMimeDatabase>
#include <QMimeType>
#include <QtCore/QBuffer>
#include <Qt3DRender/QRenderAspect>
#include <Qt3DCore/QAspectEngine>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/private/qdownloadhelperservice_p.h>
#include <Qt3DCore/private/qurlhelper_p.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/qgeometryloaderinterface_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/qgeometryloaderfactory_p.h>
#include <Qt3DRender/private/geometryrenderermanager_p.h>

#include <algorithm>

QT_BEGIN_NAMESPACE

namespace Qt3DRender {

using namespace Qt3DCore;

Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, geometryLoader, (QGeometryLoaderFactory_iid, QLatin1String("/geometryloaders"), Qt::CaseInsensitive))

QMeshPrivate::QMeshPrivate()
    : QGeometryRendererPrivate()
    , m_status(QMesh::None)
{
}

QMeshPrivate *QMeshPrivate::get(QMesh *q)
{
    return q->d_func();
}

void QMeshPrivate::setScene(Qt3DCore::QScene *scene)
{
    QGeometryRendererPrivate::setScene(scene);
    updateFunctor();
}

void QMeshPrivate::updateFunctor()
{
    Q_Q(QMesh);
    m_geometryFactory = QGeometryFactoryPtr(new MeshLoaderFunctor(q));
    update();
}

void QMeshPrivate::setStatus(QMesh::Status status)
{
    if (m_status != status) {
        Q_Q(QMesh);
        m_status = status;
        const bool wasBlocked = q->blockNotifications(true);
        emit q->statusChanged(status);
        q->blockNotifications(wasBlocked);
    }
}

/*!
 * \qmltype Mesh
 * \instantiates Qt3DRender::QMesh
 * \inqmlmodule Qt3D.Render
 * \brief A custom mesh loader.
 *
 * Loads mesh data from external files in a variety of formats.
 *
 * In Qt3D 5.9, Mesh supports the following formats:
 *
 * \list
 * \li Wavefront OBJ
 * \li Stanford Triangle Format PLY
 * \li STL (STereoLithography)
 * \endlist
 *
 * QMesh will also support the following format if the SDK is installed and the fbx geometry loader plugin is built and found.
 * \list
 * \li Autodesk FBX
 * \endlist
 */

/*!
 * \qmlproperty url Mesh::source
 *
 * Holds the source url to the file containing the custom mesh.
 */

/*!
 * \qmlproperty string Mesh::meshName
 *
 * Filter indicating which part of the mesh should be loaded.
 *
 * If meshName is empty (the default), then the entire mesh is loaded.
 *
 * If meshName is a plain string, then only the sub-mesh matching that name, if present, will be loaded.
 *
 * If meshName is a regular expression, than all sub-meshes matching the expression will be loaded.
 *
 * \note Only Wavefront OBJ files support sub-meshes.
 *
 * \sa QRegularExpression
 */

/*!
    \qmlproperty enumeration Mesh::status

    Holds the status of the mesh loading.
    \sa Qt3DRender::QMesh::Status
    \readonly
 */

/*!
 * \class Qt3DRender::QMesh
 * \inheaderfile Qt3DRender/QMesh
 * \inmodule Qt3DRender
 *
 * \inherits Qt3DRender::QGeometryRenderer
 *
 * \brief A custom mesh loader.
 *
 * Loads mesh data from external files in a variety of formats.
 * Qt3DRender::QMesh loads data into a single mesh.
 *
 * In Qt3D 5.9, QMesh supports the following formats:
 *
 * \list
 * \li Wavefront OBJ
 * \li Stanford Triangle Format PLY
 * \li STL (STereoLithography)
 * \endlist
 *
 * QMesh will also support the following format if the SDK is installed and the fbx geometry loader plugin is built and found:
 * \list
 * \li Autodesk FBX
 * \endlist
 *
 * If you wish to load an entire scene made of several objects, you should rather use the Qt3DRender::QSceneLoader instead.
 *
 * \sa Qt3DRender::QSceneLoader
 */

/*!
    \enum Qt3DRender::QMesh::Status

    This enum identifies the status of shader used.

    \value None              A source mesh hasn't been assigned a source yet
    \value Loading           The mesh geometry is loading
    \value Ready             The mesh geometry was successfully loaded
    \value Error             An error occurred while loading the mesh
*/

/*!
 * Constructs a new QMesh with \a parent.
 */
QMesh::QMesh(QNode *parent)
    : QGeometryRenderer(*new QMeshPrivate, parent)
{
}

/*! \internal */
QMesh::~QMesh()
{
}

/*! \internal */
QMesh::QMesh(QMeshPrivate &dd, QNode *parent)
    : QGeometryRenderer(dd, parent)
{
}

void QMesh::setSource(const QUrl& source)
{
    Q_D(QMesh);
    if (d->m_source == source)
        return;
    d->m_source = source;
    d->updateFunctor();
    const bool blocked = blockNotifications(true);
    emit sourceChanged(source);
    blockNotifications(blocked);
}

/*!
 * \property Qt3DRender::QMesh::source
 *
 * Holds the \a source url to the file containing the custom mesh.
 */
QUrl QMesh::source() const
{
    Q_D(const QMesh);
    return d->m_source;
}

void QMesh::setMeshName(const QString &meshName)
{
    Q_D(QMesh);
    if (d->m_meshName == meshName)
        return;
    d->m_meshName = meshName;
    d->updateFunctor();
    const bool blocked = blockNotifications(true);
    emit meshNameChanged(meshName);
    blockNotifications(blocked);
}

/*!
 * \property Qt3DRender::QMesh::meshName
 *
 * Holds the name of the mesh.
 */
QString QMesh::meshName() const
{
    Q_D(const QMesh);
    return d->m_meshName;
}

/*!
    \property Qt3DRender::QMesh::status

    Holds the status of the mesh loading.
    \sa Qt3DRender::QMesh::Status
 */
QMesh::Status QMesh::status() const
{
    Q_D(const QMesh);
    return d->m_status;
}

/*!
 * \internal
 */
MeshLoaderFunctor::MeshLoaderFunctor(QMesh *mesh, const QByteArray &sourceData)
    : QGeometryFactory()
    , m_mesh(mesh->id())
    , m_sourcePath(mesh->source())
    , m_meshName(mesh->meshName())
    , m_sourceData(sourceData)
    , m_nodeManagers(nullptr)
    , m_downloaderService(nullptr)
    , m_status(QMesh::None)
{
}

/*!
 * \internal
 */
Qt3DCore::QGeometry *MeshLoaderFunctor::operator()()
{
    m_status = QMesh::Loading;

    if (m_sourcePath.isEmpty()) {
        qCWarning(Render::Jobs) << Q_FUNC_INFO << "Mesh is empty, nothing to load";
        m_status = QMesh::Error;
        return nullptr;
    }

    QStringList ext;
    if (!Qt3DCore::QDownloadHelperService::isLocal(m_sourcePath)) {
        if (m_sourceData.isEmpty()) {
            if (m_mesh) {
                // Output a warning in the case a user is calling the functor directly
                // in the frontend
                if (m_nodeManagers == nullptr || m_downloaderService == nullptr) {
                    qWarning() << "Mesh source points to a remote URL. Remotes meshes can only be loaded if the geometry is processed by the Qt3DRender backend";
                    m_status = QMesh::Error;
                    return nullptr;
                }
                Qt3DCore::QDownloadRequestPtr request(new MeshDownloadRequest(m_mesh, m_sourcePath, m_nodeManagers));
                m_downloaderService->submitRequest(request);
            }
            return nullptr;
        }

        QMimeDatabase db;
        QMimeType mtype = db.mimeTypeForData(m_sourceData);
        if (mtype.isValid()) {
            ext = mtype.suffixes();
        }
        QFileInfo finfo(m_sourcePath.path());
        ext << finfo.suffix();
        ext.removeAll(QLatin1String(""));
        if (!ext.contains(QLatin1String("obj")))
            ext << QLatin1String("obj");
    } else {
        QString filePath = Qt3DCore::QUrlHelper::urlToLocalFileOrQrc(m_sourcePath);
        QFileInfo finfo(filePath);
        if (finfo.suffix().isEmpty())
            ext << QLatin1String("obj");
        else
            ext << finfo.suffix();
    }

    QScopedPointer<QGeometryLoaderInterface> loader;
    for (const QString &e: std::as_const(ext)) {
        loader.reset(qLoadPlugin<QGeometryLoaderInterface, QGeometryLoaderFactory>(geometryLoader(), e));
        if (loader)
            break;
    }
    if (!loader) {
        qCWarning(Render::Jobs, "unsupported format encountered (%s)", qPrintable(ext.join(QLatin1String(", "))));
        m_status = QMesh::Error;
        return nullptr;
    }

    if (m_sourceData.isEmpty()) {
        QString filePath = Qt3DCore::QUrlHelper::urlToLocalFileOrQrc(m_sourcePath);
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly)) {
            qCDebug(Render::Jobs) << "Could not open file" << filePath << "for reading";
            m_status = QMesh::Error;
            return nullptr;
        }

        if (loader->load(&file, m_meshName)) {
            Qt3DCore::QGeometry *geometry = loader->geometry();
            m_status = geometry != nullptr ? QMesh::Ready : QMesh::Error;
            return geometry;
        }
        qCWarning(Render::Jobs) << Q_FUNC_INFO << "Mesh loading failure for:" << filePath;
    } else {
        QT_PREPEND_NAMESPACE(QBuffer) buffer(&m_sourceData);
        if (!buffer.open(QIODevice::ReadOnly)) {
            m_status = QMesh::Error;
            return nullptr;
        }

        if (loader->load(&buffer, m_meshName)) {
            Qt3DCore::QGeometry *geometry = loader->geometry();
            m_status = geometry != nullptr ? QMesh::Ready : QMesh::Error;
            return geometry;
        }

        qCWarning(Render::Jobs) << Q_FUNC_INFO << "Mesh loading failure for:" << m_sourcePath;
    }

    return nullptr;
}

/*!
 * \internal
 */
bool MeshLoaderFunctor::equals(const QGeometryFactory &other) const
{
    const MeshLoaderFunctor *otherFunctor = functor_cast<MeshLoaderFunctor>(&other);
    if (otherFunctor != nullptr)
        return (otherFunctor->m_sourcePath == m_sourcePath &&
                otherFunctor->m_sourceData.isEmpty() == m_sourceData.isEmpty() &&
                otherFunctor->m_meshName == m_meshName &&
                otherFunctor->m_downloaderService == m_downloaderService &&
                otherFunctor->m_nodeManagers == m_nodeManagers);
    return false;
}

/*!
 * \internal
 */
MeshDownloadRequest::MeshDownloadRequest(Qt3DCore::QNodeId mesh, QUrl source, Render::NodeManagers *managers)
    : Qt3DCore::QDownloadRequest(source)
    , m_mesh(mesh)
    , m_nodeManagers(managers)
{
}

// Called in Aspect Thread context (not a Qt3D AspectJob)
// We are sure that when this is called, no AspectJob are running
void MeshDownloadRequest::onCompleted()
{
    if (cancelled() || !succeeded())
        return;

    if (!m_nodeManagers)
        return;

    Render::GeometryRenderer *renderer = m_nodeManagers->geometryRendererManager()->lookupResource(m_mesh);
    if (!renderer)
        return;

    QGeometryFactoryPtr geometryFactory = renderer->geometryFactory();
    if (!geometryFactory.isNull() && geometryFactory->id() == Qt3DCore::functorTypeId<MeshLoaderFunctor>()) {
        QSharedPointer<MeshLoaderFunctor> functor = qSharedPointerCast<MeshLoaderFunctor>(geometryFactory);

        // We make sure we are setting the result for the right request
        // (the functor for the mesh could have changed in the meantime)
        if (m_url == functor->sourcePath()) {
            functor->setSourceData(m_data);

            // mark the component as dirty so that the functor runs again in the correct job
            m_nodeManagers->geometryRendererManager()->addDirtyGeometryRenderer(m_mesh);
        }
    }
}

} // namespace Qt3DRender

QT_END_NAMESPACE

#include "moc_qmesh.cpp"