summaryrefslogtreecommitdiffstats
path: root/src/runtime/q3dsimagemanager.cpp
blob: 549f9625e1bddb9c50de7245e2a059128f2f7a35 (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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://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 "q3dsimagemanager_p.h"
#include "q3dsimageloaders_p.h"
#include "q3dsprofiler_p.h"
#include "q3dslogging_p.h"
#include <qmath.h>
#include <QFileInfo>
#include <QElapsedTimer>
#include <QLoggingCategory>
#include <Qt3DCore/QEntity>
#include <Qt3DRender/QTextureImageDataGenerator>
#include <Qt3DRender/QTexture>
#include <QtConcurrent>
#include <QFutureSynchronizer>

QT_BEGIN_NAMESPACE

QMutex Q3DSImageManager::s_loadMutex;

static bool isAsyncImageLoadingEnabled()
{
    static bool enabled = (qEnvironmentVariableIntValue("Q3DS_ASYNC_LOADING") & 1) > 0;
    return enabled;
}

static bool isDelayedImageLoadingEnabled()
{
    static bool enabled = (qEnvironmentVariableIntValue("Q3DS_ASYNC_LOADING") & 2) > 0;
    return enabled;
}

Q3DSImageManager::Q3DSImageManager()
{
    m_threadPool.setMaxThreadCount(qMax(2, QThread::idealThreadCount() - 2));
}

Q3DSImageManager &Q3DSImageManager::instance()
{
    static Q3DSImageManager mgr;
    return mgr;
}

void Q3DSImageManager::invalidate()
{
    m_metadata.clear();
    m_cache.clear();
    m_ioTime = 0;
    m_iblTime = 0;
    m_resourceSet.clear();
    m_loadImageDataAsync.clear();
    qDeleteAll(m_pendingSetSource);
    m_pendingSetSource.clear();
    m_reloadableTextures.clear();
}

Qt3DRender::QAbstractTexture *Q3DSImageManager::newTextureForImage(Qt3DCore::QEntity *parent,
                                                                   ImageFlags flags,
                                                                   const QByteArray &id,
                                                                   Q3DSProfiler *profiler,
                                                                   const QString &profilerInfo)
{
    auto tex = new Qt3DRender::QTexture2D(parent);

    TextureInfo info;
    info.flags = flags;
    m_metadata.insert(tex, info);

    if (profiler && !profilerInfo.isNull())
        profiler->trackNewObject(tex, Q3DSProfiler::Texture2DObject, id, profilerInfo);

    return tex;
}

ReloadableTexturePtr Q3DSImageManager::newReloadableTextureForImage(Qt3DCore::QEntity *parent,
                                                                    ImageFlags flags,
                                                                    const QByteArray &id,
                                                                    Q3DSProfiler *profiler,
                                                                    const char *profDesc, ...)
{
    ReloadableTexturePtr texture;
    QString info;
    if (profiler && profDesc) {
        va_list ap;
        va_start(ap, profDesc);
        info = QString::vasprintf(profDesc, ap);
        va_end(ap);
    }
    texture.reset(new ReloadableTexture(parent, flags & GenerateMipMapsForIBL, id, info, profiler));
    m_reloadableTextures.push_back(texture);
    return texture;
}

void ReloadableTexture::setSource(const QUrl &source)
{
    if (m_source.isEmpty() || m_source != source) {
        m_source = source;
        m_loaded = false;
        triggerLoading();
    }
}

void ReloadableTexture::triggerLoading()
{
    if (!m_source.isEmpty() && m_loadFunc && m_unloadFunc)
        reload();
}

void ReloadableTexture::reload()
{
    if (m_loaded)
        return;
    if (isDelayedImageLoadingEnabled() && !Q3DSImageManager::instance().inResourceSet(m_source))
        return;
    Q3DSImageManager::ImageFlags flags;
    if (m_generateIBL)
        flags = Q3DSImageManager::GenerateMipMapsForIBL;
    if (!m_texture) {
        m_texture = Q3DSImageManager::instance().newTextureForImage(m_parent, flags, m_id,
                                                                    m_profiler, m_profileInfo);
    }
    Q3DSImageManager::instance().loadImageData(m_source);
    Q3DSImageManager::instance().setSource(m_texture, m_source);
}

void ReloadableTexture::unload()
{
    if (m_texture) {
        m_unloadFunc();

        const auto texImages = m_texture->textureImages();
        for (Qt3DRender::QAbstractTextureImage *oldImage : texImages) {
            m_texture->removeTextureImage(oldImage);
            delete oldImage;
        }
        Qt3DCore::QNode *nullParent = nullptr;
        m_texture->setParent(nullParent);
        delete m_texture;
        m_texture = nullptr;
        m_loaded = false;
    }
}

void ReloadableTexture::loaded(Qt3DRender::QAbstractTexture *texture)
{
    if (m_texture == texture) {
        m_loaded = true;
        m_loadFunc();
    }
}

class Q3DSTextureImageDataGen : public Qt3DRender::QTextureImageDataGenerator
{
public:
    Q3DSTextureImageDataGen(const QUrl &source, int mipLevel, const Qt3DRender::QTextureImageDataPtr &data)
        : m_source(source),
          m_mipLevel(mipLevel),
          m_data(data)
    { }

    Qt3DRender::QTextureImageDataPtr operator()() override
    {
        return m_data;
    }

    bool operator==(const Qt3DRender::QTextureImageDataGenerator &other) const override
    {
        const Q3DSTextureImageDataGen *otherFunctor = functor_cast<Q3DSTextureImageDataGen>(&other);
        return otherFunctor && otherFunctor->m_source == m_source && otherFunctor->m_mipLevel == m_mipLevel;
    }

    QT3D_FUNCTOR(Q3DSTextureImageDataGen)

private:
    QUrl m_source;
    int m_mipLevel;
    Qt3DRender::QTextureImageDataPtr m_data;
};

class TextureImage : public Qt3DRender::QAbstractTextureImage
{
public:
    TextureImage(const QUrl &source, int mipLevel, const Qt3DRender::QTextureImageDataPtr &data)
    {
        setMipLevel(mipLevel);
        m_gen = QSharedPointer<Q3DSTextureImageDataGen>::create(source, mipLevel, data);
    }

private:
    Qt3DRender::QTextureImageDataGeneratorPtr dataGenerator() const override { return m_gen; }

    Qt3DRender::QTextureImageDataGeneratorPtr m_gen;
};

QVector<Qt3DRender::QTextureImageDataPtr> Q3DSImageManager::load(const QUrl &source)
{
    const QString sourceStr = source.toLocalFile();
    s_loadMutex.lock();
    auto it = m_cache.constFind(sourceStr);
    if (it != m_cache.constEnd()) {
        s_loadMutex.unlock();
        return *it;
    }
    s_loadMutex.unlock();

    QElapsedTimer t;
    t.start();
    qCDebug(lcScene, "Loading image %s", qPrintable(sourceStr));

    // Loaders are expected to provide a separate textureimage per mip level,
    // because individual textureimages added to an abstracttexture via
    // addTextureImage do not support providing a multiple mip level data in
    // one texture image. At the sime time we cannot use QTextureGenerator via
    // the public API so are stuck with individual textureimages.
    QVector<Qt3DRender::QTextureImageDataPtr> result;

    const QString suffix = QFileInfo(sourceStr).suffix().toLower();
    if (suffix == QStringLiteral("hdr")) {
        QFile f(sourceStr);
        if (f.open(QIODevice::ReadOnly)) {
            Qt3DRender::QTextureImageDataPtr data = q3ds_loadHdr(&f);
            result << data;
            f.close();
        }
    } else if (suffix == QStringLiteral("pkm")) {
        QFile f(sourceStr);
        if (f.open(QIODevice::ReadOnly)) {
            Qt3DRender::QTextureImageDataPtr data = q3ds_loadPkm(&f);
            result << data;
            f.close();
        }
    } else if (suffix == QStringLiteral("dds")) {
        QFile f(sourceStr);
        if (f.open(QIODevice::ReadOnly)) {
            Qt3DRender::QTextureImageDataPtr data = q3ds_loadDds(&f);
            result << data;
            f.close();
        }
    } else if (suffix == QStringLiteral("ktx")) {
        QFile f(sourceStr);
        if (f.open(QIODevice::ReadOnly)) {
            result = q3ds_loadKtx(&f);
            f.close();
        }
    }

    if (result.isEmpty()) {
        QImage image(sourceStr);
        if (!image.isNull()) {
            Qt3DRender::QTextureImageDataPtr data = Qt3DRender::QTextureImageDataPtr::create();
            data->setImage(image.mirrored());
            result << data;
        }
    }

    m_ioTime += t.elapsed();

    if (!result.isEmpty()) {
        qCDebug(lcPerf, "Image loaded (%d mip levels) in %lld ms", result.count(), t.elapsed());
        s_loadMutex.lock();
        m_cache.insert(sourceStr, result);
        s_loadMutex.unlock();
    } else {
        qCDebug(lcScene, "Failed to load image");
    }
    return result;
}

QVector<Qt3DRender::QTextureImageDataPtr> Q3DSImageManager::generateIblForImageData(
                                                  QVector<Qt3DRender::QTextureImageDataPtr> result)
{
    if (result.count() == 1) {
        // IBL needs special mipmap generation. This could be done
        // asynchronously but the we rely on the previous level in each step so
        // it's not a good fit unfortunately. So do it all here. Also,
        // QTextureGenerator could provide all mipmaps in one go in one blob,
        // but there's no public API for that, have to stick with
        // QTextureImageDataGenerator.
        QElapsedTimer t;
        t.start();
        Qt3DRender::QTextureImageDataPtr data = result.first();
        int w = data->width();
        int h = data->height();
        const int maxDim = w > h ? w : h;
        const int maxMipLevel = int(qLn(maxDim) / qLn(2.0f));
        // silly QTextureImageData does not expose blockSize
        const int blockSize = blockSizeForFormat(data->format());
        QByteArray prevLevelData = data->data();
        for (int i = 1; i <= maxMipLevel; ++i) {
            int prevW = w;
            int prevH = h;
            w >>= 1;
            h >>= 1;
            w = qMax(1, w);
            h = qMax(1, h);

            auto mipImageData = Qt3DRender::QTextureImageDataPtr::create();
            mipImageData->setTarget(QOpenGLTexture::Target2D);
            mipImageData->setFormat(data->format());
            mipImageData->setWidth(w);
            mipImageData->setHeight(h);
            mipImageData->setLayers(1);
            mipImageData->setDepth(1);
            mipImageData->setFaces(1);
            // again, make no mistake: not setting 1 does not actually
            // allow providing multiple mip level data in one texture image
            // due to the bizarre API design of Qt3D. (the behavior is
            // logical, technically, but the API over all is not) So
            // separate textureimages is the only way to go.
            mipImageData->setMipLevels(1);
            mipImageData->setPixelFormat(data->pixelFormat());
            mipImageData->setPixelType(data->pixelType());

            QByteArray mipData = generateIblMip(w, h, prevW, prevH, mipImageData->format(),
                                                blockSize, prevLevelData);
            mipImageData->setData(mipData, blockSize, false);
            result << mipImageData;
            prevLevelData = mipData;
        }
        m_iblTime += t.elapsed();
        qCDebug(lcPerf, "Generated %d IBL mip levels in %lld ms", maxMipLevel, t.elapsed());
    }
    return result;
}

void Q3DSImageManager::finishAsyncLoad(bool wait)
{
    QMutexLocker lock(&m_finishAsyncLoadLock);
    if (m_loadImageDataAsync.isEmpty() && m_pendingSetSource.isEmpty())
        return;

    if (wait) {
        lock.unlock();
        QElapsedTimer t;
        t.start();
        {
            QFutureSynchronizer<void> sync;
            for (auto &item : qAsConst(m_loadImageDataAsync))
                sync.addFuture(item.future);
        }
        qCDebug(lcPerf, "Finish async image loading took %lld ms", t.elapsed());
        for (auto &item : qAsConst(m_loadImageDataAsync)) {
            if (m_pendingSetSource.contains(item.source)) {
                const auto *pending = m_pendingSetSource[item.source];
                for (const auto &tex : qAsConst(*pending))
                    setSource(tex, QUrl::fromLocalFile(item.source));
                delete pending;
                m_pendingSetSource.remove(item.source);
            }
        }
        m_pendingSetSource.clear();
    } else {
        lock.relock();
        QThread *thread = QThread::currentThread();
        for (auto &item : m_loadImageDataAsync) {
            if (!item.done && item.future.isFinished()) {
                item.done = true;
                if (m_pendingSetSource.contains(item.source)) {
                    const auto pending = *m_pendingSetSource[item.source];
                    for (const auto &tex : pending) {
                        if (tex->thread() == thread) {
                            setSource(tex, QUrl::fromLocalFile(item.source));
                            m_pendingSetSource[item.source]->removeOne(tex);
                        }
                    }
                    if (m_pendingSetSource[item.source]->empty()) {
                        delete m_pendingSetSource[item.source];
                        m_pendingSetSource.remove(item.source);
                    }
                }
            }
        }
    }
}

void Q3DSImageManager::beginImageLoad(const QSet<QUrl> &imageSet)
{
    m_resourceSet.unite(imageSet);
    for (auto url : imageSet) {
        QFileInfo info(url.toLocalFile());
        if (info.exists()) {
            if (!m_loadImageDataAsync.contains(url.toLocalFile()))
                loadImageData(url);
            for (int i = 0; i < m_reloadableTextures.size(); ++i) {
                if (m_reloadableTextures[i]->source() == url)
                    m_reloadableTextures[i]->reload();
            }
        }
    }
}

bool Q3DSImageManager::inResourceSet(const QUrl &url) const
{
    return m_resourceSet.contains(url);
}

void Q3DSImageManager::beginUnload(const QSet<QUrl> &imageSet)
{
    m_resourceSet.subtract(imageSet);
    if (!isDelayedImageLoadingEnabled())
        return;
    for (auto url : imageSet) {
        for (int i = 0; i < m_reloadableTextures.size(); ++i) {
            if (m_reloadableTextures[i]->source() == url) {
                m_metadata.remove(m_reloadableTextures[i]->texture());
                m_reloadableTextures[i]->unload();
            }
        }
        const QString name = url.toLocalFile();
        m_cache.remove(name);
        if (m_loadImageDataAsync.contains(name) && m_loadImageDataAsync[name].done)
            m_loadImageDataAsync.remove(name);
    }
}

void Q3DSImageManager::loadImageData(const QUrl &source, bool async)
{
    auto loadImage = [this](const QUrl &source) {
        QVector<Qt3DRender::QTextureImageDataPtr> imageData;
        // The generator (invoked from some Qt3D job thread later on) will just return the already
        // loaded data.
        imageData = load(source);
    };

    QMutexLocker lock(&s_loadMutex);
    if (m_cache.contains(source.toLocalFile()))
        return;
    lock.unlock();

    const QString src = source.toLocalFile();
    if (async && isAsyncImageLoadingEnabled()) {
        if (!m_loadImageDataAsync.contains(src)) {
            qCDebug(lcScene, "Load image data async %s", qPrintable(src));
            LoadImageDataAsync item;
            item.source = src;
            item.future = QtConcurrent::run(&m_threadPool, loadImage, source);
            m_loadImageDataAsync[src] = item;
        }
    } else {
        loadImage(source);
    }
}

void Q3DSImageManager::setSource(Qt3DRender::QAbstractTexture *tex, const QUrl &source)
{
    TextureInfo info;
    QString src = source.toLocalFile();

    s_loadMutex.lock();
    auto it = m_metadata.find(tex);
    if (it != m_metadata.end()) {
        if (it->source == src) {
            s_loadMutex.unlock();
            return;
        }
        info = *it;
    }

    if (!m_cache.contains(src)) {
        if (!m_pendingSetSource.contains(src))
            m_pendingSetSource[src] = new QVector<Qt3DRender::QAbstractTexture *>();
        m_pendingSetSource[src]->push_back(tex);
        s_loadMutex.unlock();
        return;
    }
    else {
        info.wasCached = true;
    }
    s_loadMutex.unlock();

    auto &imageData = m_cache[src];
    if (info.flags.testFlag(GenerateMipMapsForIBL) && imageData.size() == 1) {
        s_loadMutex.lock();
        m_cache[src] = generateIblForImageData(imageData);
        s_loadMutex.unlock();
    }


    const auto texImages = tex->textureImages();
    for (Qt3DRender::QAbstractTextureImage *oldImage : texImages) {
        tex->removeTextureImage(oldImage);
        delete oldImage;
    }

    if (!imageData.isEmpty()) {
        info.size = QSize(imageData[0]->width(), imageData[0]->height());
        info.format = Qt3DRender::QAbstractTexture::TextureFormat(imageData[0]->format());
        s_loadMutex.lock();
        m_metadata.insert(tex, info);
        s_loadMutex.unlock();
        // Mipmaps are used in three cases: in IBL images (with our own custom
        // mipmap images), when the source provides mipmaps (e.g. a .ktx file
        // with mipmaps in it), or when the custom property metadata (custom
        // materials/effects) says so (mipmaps autogenerated in this case). If
        // none of these holds, linear filtering is used.

        tex->setMagnificationFilter(Qt3DRender::QAbstractTexture::Linear);
        // autogen is only for custom props and that's handled elsewhere
        tex->setGenerateMipMaps(false);

        if (imageData.count() > 1) {
            tex->setMinificationFilter(Qt3DRender::QAbstractTexture::LinearMipMapLinear);
            if (!info.wasCached) {
                qCDebug(lcScene, "%s provided mipmaps, mipmap filtering enabled",
                        qPrintable(source.toLocalFile()));
            }
        } else {
            tex->setMinificationFilter(Qt3DRender::QAbstractTexture::Linear);
        }

        for (int i = 0; i < imageData.count(); ++i)
            tex->addTextureImage(new TextureImage(source, i, imageData[i]));
    } else {
        // Provide a dummy image when failing to load since we want to see
        // something that makes it obvious a texture source file was missing.
        info.size = QSize(64, 64);
        info.format = Qt3DRender::QAbstractTexture::RGBA8_UNorm;
        s_loadMutex.lock();
        m_metadata.insert(tex, info);
        s_loadMutex.unlock();

        QImage dummy(info.size, QImage::Format_ARGB32);
        dummy.fill(Qt::magenta);
        auto dummyData = Qt3DRender::QTextureImageDataPtr::create();
        dummyData->setImage(dummy);

        tex->addTextureImage(new TextureImage(source, 0, dummyData));
        qWarning("Using placeholder texture in place of %s", qPrintable(source.toLocalFile()));
    }
    textureLoaded(tex, source);
}

void Q3DSImageManager::textureLoaded(Qt3DRender::QAbstractTexture *tex, const QUrl &source)
{
    for (auto &reloadable : m_reloadableTextures) {
        if (reloadable->source() == source)
            reloadable->loaded(tex);
    }
}

void Q3DSImageManager::setSource(Qt3DRender::QAbstractTexture *tex, const QImage &image)
{
    auto data = Qt3DRender::QTextureImageDataPtr::create();

    if (!image.isNull()) {
        data->setImage(image.mirrored());
    } else {
        QImage dummy(image.size(), QImage::Format_ARGB32);
        dummy.fill(Qt::magenta);
        data->setImage(dummy);
    }

    for (Qt3DRender::QAbstractTextureImage *oldImage : tex->textureImages()) {
        tex->removeTextureImage(oldImage);
        delete oldImage;
    }

    const QUrl dummySource = QUrl::fromLocalFile(QString::number(image.cacheKey()));
    tex->addTextureImage(new TextureImage(dummySource, 0, data));

    TextureInfo info;
    auto it = m_metadata.find(tex);
    if (it != m_metadata.end())
        info = *it;

    Q_ASSERT(!info.flags.testFlag(GenerateMipMapsForIBL)); // not supported atm

    info.source = dummySource;
    info.size = image.size();
    info.format = Qt3DRender::QAbstractTexture::RGBA8_UNorm; // ### not always true

    m_metadata.insert(tex, info);
}

// The metadata getters must work also with textures not registered to the
// imagemanager. Just fall back to the texture itself then (which is safe for
// textures created with a size, not sourced from a file; for images loaded
// from a file this is not an option due to QTBUG-65775)

QSize Q3DSImageManager::size(Qt3DRender::QAbstractTexture *tex) const
{
    auto it = m_metadata.constFind(tex);
    if (it != m_metadata.cend())
        return it->size;

    return QSize(tex->width(), tex->height());
}

Qt3DRender::QAbstractTexture::TextureFormat Q3DSImageManager::format(Qt3DRender::QAbstractTexture *tex) const
{
    auto it = m_metadata.constFind(tex);
    if (it != m_metadata.cend())
        return it->format;

    return tex->format();
}

bool Q3DSImageManager::wasCached(Qt3DRender::QAbstractTexture *tex) const
{
    auto it = m_metadata.constFind(tex);
    if (it != m_metadata.cend())
        return it->wasCached;

    return false;
}

// IBL mipmap generation (BSDF prefiltering), adapted from 3DS1

int Q3DSImageManager::blockSizeForFormat(QOpenGLTexture::TextureFormat format)
{
    switch (format) {
    case QOpenGLTexture::R8_UNorm:
        return 1;
    case QOpenGLTexture::R16F:
        return 2;
    case QOpenGLTexture::R16_UNorm:
        return 2;
    case QOpenGLTexture::R32I:
        return 4;
    case QOpenGLTexture::R32F:
        return 4;
    case QOpenGLTexture::RGBA8_UNorm:
        return 4;
    case QOpenGLTexture::RGB8_UNorm:
        return 3;
    case QOpenGLTexture::R5G6B5:
        return 2;
    case QOpenGLTexture::RGB5A1:
        return 2;
    case QOpenGLTexture::AlphaFormat:
        return 1;
    case QOpenGLTexture::LuminanceFormat:
        return 1;
    case QOpenGLTexture::LuminanceAlphaFormat:
        return 1;
    case QOpenGLTexture::D16:
        return 2;
    case QOpenGLTexture::D24:
        return 3;
    case QOpenGLTexture::D32:
        return 4;
    case QOpenGLTexture::D24S8:
        return 4;
    case QOpenGLTexture::RGB9E5:
        return 4;
    case QOpenGLTexture::SRGB8:
        return 3;
    case QOpenGLTexture::SRGB8_Alpha8:
        return 4;
    case QOpenGLTexture::RGBA16F:
        return 8;
    case QOpenGLTexture::RG16F:
        return 4;
    case QOpenGLTexture::RG32F:
        return 8;
    case QOpenGLTexture::RGBA32F:
        return 16;
    case QOpenGLTexture::RGB32F:
        return 12;
    case QOpenGLTexture::RG11B10F:
        return 4;
    default:
        break;
    }
    Q_UNREACHABLE();
    return 0;
}

static inline void getWrappedCoords(int &sX, int &sY, int width, int height)
{
    if (sY < 0) {
        sX -= width >> 1;
        sY = -sY;
    }
    if (sY >= height) {
        sX += width >> 1;
        sY = height - sY;
    }
    sX = qAbs(sX) % width;
}

static inline void decodeToFloat(const void *inPtr, int byteOfs, float *outPtr,
                                 QOpenGLTexture::TextureFormat format, int blockSize)
{
    outPtr[0] = 0.0f;
    outPtr[1] = 0.0f;
    outPtr[2] = 0.0f;
    outPtr[3] = 0.0f;
    const uchar *src = reinterpret_cast<const uchar *>(inPtr);
    // float divisor; // If we want to support RGBD?
    switch (format) {
    case QOpenGLTexture::AlphaFormat:
        outPtr[0] = ((float)src[byteOfs]) / 255.0f;
        break;

    case QOpenGLTexture::LuminanceFormat:
    case QOpenGLTexture::LuminanceAlphaFormat:
    case QOpenGLTexture::R8_UNorm:
    case QOpenGLTexture::RG8_UNorm:
    case QOpenGLTexture::RGB8_UNorm:
    case QOpenGLTexture::RGBA8_UNorm:
    case QOpenGLTexture::SRGB8:
    case QOpenGLTexture::SRGB8_Alpha8:
        // NOTE : RGBD Hack here for reference.  Not meant for installation.
        // divisor = (blockSize == 4) ? ((float)src[byteOfs+3]) / 255.0f : 1.0f;
        for (int i = 0; i < blockSize; ++i) {
            float val = ((float)src[byteOfs + i]) / 255.0f;
            outPtr[i] = (i < 3) ? qPow(val, 0.4545454545f) : val;
            // Assuming RGBA8 actually means RGBD (which is stupid, I know)
            // if ( blockSize == 4 ) { outPtr[i] /= divisor; }
        }
        // outPtr[3] = divisor;
        break;

    case QOpenGLTexture::R32F:
        outPtr[0] = reinterpret_cast<const float *>(src + byteOfs)[0];
        break;
    case QOpenGLTexture::RG32F:
        outPtr[0] = reinterpret_cast<const float *>(src + byteOfs)[0];
        outPtr[1] = reinterpret_cast<const float *>(src + byteOfs)[1];
        break;
    case QOpenGLTexture::RGBA32F:
        outPtr[0] = reinterpret_cast<const float *>(src + byteOfs)[0];
        outPtr[1] = reinterpret_cast<const float *>(src + byteOfs)[1];
        outPtr[2] = reinterpret_cast<const float *>(src + byteOfs)[2];
        outPtr[3] = reinterpret_cast<const float *>(src + byteOfs)[3];
        break;
    case QOpenGLTexture::RGB32F:
        outPtr[0] = reinterpret_cast<const float *>(src + byteOfs)[0];
        outPtr[1] = reinterpret_cast<const float *>(src + byteOfs)[1];
        outPtr[2] = reinterpret_cast<const float *>(src + byteOfs)[2];
        break;

    case QOpenGLTexture::R16F:
    case QOpenGLTexture::RG16F:
    case QOpenGLTexture::RGBA16F:
        for (int i = 0; i < (blockSize >> 1); ++i) {
            // NOTE : This only works on the assumption that we don't have any denormals,
            // Infs or NaNs.
            // Every pixel in our source image should be "regular"
            quint16 h = reinterpret_cast<const quint16 *>(src + byteOfs)[i];
            quint32 sign = (h & 0x8000) << 16;
            quint32 exponent = (((((h & 0x7c00) >> 10) - 15) + 127) << 23);
            quint32 mantissa = ((h & 0x3ff) << 13);
            quint32 result = sign | exponent | mantissa;
            // Special case for zero and negative zero
            if (h == 0 || h == 0x8000)
                result = 0;
            memcpy(reinterpret_cast<quint32 *>(outPtr) + i, &result, 4);
        }
        break;

    case QOpenGLTexture::RG11B10F:
        // place holder
        Q_UNREACHABLE();
        break;

    default:
        outPtr[0] = 0.0f;
        outPtr[1] = 0.0f;
        outPtr[2] = 0.0f;
        outPtr[3] = 0.0f;
        break;
    }
}

static inline void encodeToPixel(float *inPtr, void *outPtr, int byteOfs,
                                 QOpenGLTexture::TextureFormat format, int blockSize)
{
    uchar *dest = reinterpret_cast<uchar *>(outPtr);
    switch (format) {
    case QOpenGLTexture::AlphaFormat:
        dest[byteOfs] = uchar(inPtr[0] * 255.0f);
        break;

    case QOpenGLTexture::LuminanceFormat:
    case QOpenGLTexture::LuminanceAlphaFormat:
    case QOpenGLTexture::R8_UNorm:
    case QOpenGLTexture::RG8_UNorm:
    case QOpenGLTexture::RGB8_UNorm:
    case QOpenGLTexture::RGBA8_UNorm:
    case QOpenGLTexture::SRGB8:
    case QOpenGLTexture::SRGB8_Alpha8:
        for (int i = 0; i < blockSize; ++i) {
            inPtr[i] = (inPtr[i] > 1.0f) ? 1.0f : inPtr[i];
            if (i < 3)
                dest[byteOfs + i] = uchar(qPow(inPtr[i], 2.2f) * 255.0f);
            else
                dest[byteOfs + i] = uchar(inPtr[i] * 255.0f);
        }
        break;

    case QOpenGLTexture::R32F:
        reinterpret_cast<float *>(dest + byteOfs)[0] = inPtr[0];
        break;
    case QOpenGLTexture::RG32F:
        reinterpret_cast<float *>(dest + byteOfs)[0] = inPtr[0];
        reinterpret_cast<float *>(dest + byteOfs)[1] = inPtr[1];
        break;
    case QOpenGLTexture::RGBA32F:
        reinterpret_cast<float *>(dest + byteOfs)[0] = inPtr[0];
        reinterpret_cast<float *>(dest + byteOfs)[1] = inPtr[1];
        reinterpret_cast<float *>(dest + byteOfs)[2] = inPtr[2];
        reinterpret_cast<float *>(dest + byteOfs)[3] = inPtr[3];
        break;
    case QOpenGLTexture::RGB32F:
        reinterpret_cast<float *>(dest + byteOfs)[0] = inPtr[0];
        reinterpret_cast<float *>(dest + byteOfs)[1] = inPtr[1];
        reinterpret_cast<float *>(dest + byteOfs)[2] = inPtr[2];
        break;

    case QOpenGLTexture::R16F:
    case QOpenGLTexture::RG16F:
    case QOpenGLTexture::RGBA16F:
        for (int i = 0; i < (blockSize >> 1); ++i) {
            // NOTE : This also has the limitation of not handling  infs, NaNs and
            // denormals, but it should be
            // sufficient for our purposes.
            if (inPtr[i] > 65519.0f)
                inPtr[i] = 65519.0f;
            if (qAbs(inPtr[i]) < 6.10352E-5f)
                inPtr[i] = 0.0f;
            quint32 f = reinterpret_cast<quint32 *>(inPtr)[i];
            quint32 sign = (f & 0x80000000) >> 16;
            qint32 exponent = (f & 0x7f800000) >> 23;
            quint32 mantissa = (f >> 13) & 0x3ff;
            exponent = exponent - 112;
            if (exponent > 31)
                exponent = 31;
            if (exponent < 0)
                exponent = 0;
            exponent = exponent << 10;
            reinterpret_cast<quint16 *>(dest + byteOfs)[i] = quint16(sign | exponent | mantissa);
        }
        break;

    case QOpenGLTexture::RG11B10F:
        // place holder
        Q_UNREACHABLE();
        break;

    default:
        dest[byteOfs] = 0;
        dest[byteOfs + 1] = 0;
        dest[byteOfs + 2] = 0;
        dest[byteOfs + 3] = 0;
        break;
    }
}

QByteArray Q3DSImageManager::generateIblMip(int w, int h, int prevW, int prevH,
                                            QOpenGLTexture::TextureFormat format,
                                            int blockSize, const QByteArray &prevLevelData)
{
    QByteArray data;
    data.resize(w * h * blockSize);
    char *p = data.data();

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            float accumVal[4];
            accumVal[0] = 0;
            accumVal[1] = 0;
            accumVal[2] = 0;
            accumVal[3] = 0;
            for (int sy = -2; sy <= 2; ++sy) {
                for (int sx = -2; sx <= 2; ++sx) {
                    int sampleX = sx + (x << 1);
                    int sampleY = sy + (y << 1);
                    getWrappedCoords(sampleX, sampleY, prevW, prevH);

                    // Cauchy filter (this is simply because it's the easiest to evaluate, and
                    // requires no complex
                    // functions).
                    float filterPdf = 1.f / (1.f + float(sx * sx + sy * sy) * 2.f);
                    // With FP HDR formats, we're not worried about intensity loss so much as
                    // unnecessary energy gain,
                    // whereas with LDR formats, the fear with a continuous normalization factor is
                    // that we'd lose
                    // intensity and saturation as well.
                    filterPdf /= (blockSize >= 8)
                            ? 4.71238898f
                            : 4.5403446f;
                    // filterPdf /= 4.5403446f; // Discrete normalization factor
                    // filterPdf /= 4.71238898f; // Continuous normalization factor
                    float curPix[4];
                    int byteOffset = (sampleY * prevW + sampleX) * blockSize;
                    if (byteOffset < 0) {
                        sampleY = prevH + sampleY;
                        byteOffset = (sampleY * prevW + sampleX) * blockSize;
                    }

                    decodeToFloat(prevLevelData.constData(), byteOffset, curPix, format, blockSize);

                    accumVal[0] += filterPdf * curPix[0];
                    accumVal[1] += filterPdf * curPix[1];
                    accumVal[2] += filterPdf * curPix[2];
                    accumVal[3] += filterPdf * curPix[3];
                }
            }

            int newIdx = (y * w + x) * blockSize;
            encodeToPixel(accumVal, p, newIdx, format, blockSize);
        }
    }

    return data;
}

QT_END_NAMESPACE