summaryrefslogtreecommitdiffstats
path: root/src/runtime/aping/q3dslayer3dsgnode.cpp
blob: bcb8a9e570474ce5686042975304a5767fc478e4 (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
/****************************************************************************
**
** 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 "q3dslayer3dsgnode_p.h"
#include <QOpenGLContext>
#include <QOpenGLFunctions>

#ifndef GL_TEXTURE_2D_MULTISAMPLE
#define GL_TEXTURE_2D_MULTISAMPLE         0x9100
#endif

QT_BEGIN_NAMESPACE

static QSGMaterialType materialType;
static QSGMaterialType msaa2MaterialType;
static QSGMaterialType msaa4MaterialType;

const char * const *q3ds_sg_vs_attributes()
{
    static char const *const attr[] = { "qt_VertexPosition", "qt_VertexTexCoord", 0 };
    return attr;
}

static inline const char *q3ds_sg_vs()
{
    QOpenGLContext *ctx = QOpenGLContext::currentContext();
    if (ctx->format().version() >= qMakePair(3, 2) && ctx->format().profile() == QSurfaceFormat::CoreProfile) {
        return ""
               "#version 150 core                                   \n"
               "uniform mat4 qt_Matrix;                             \n"
               "in vec4 qt_VertexPosition;                          \n"
               "in vec2 qt_VertexTexCoord;                          \n"
               "out vec2 qt_TexCoord;                               \n"
               "void main() {                                       \n"
               "   qt_TexCoord = qt_VertexTexCoord;                 \n"
               "   gl_Position = qt_Matrix * qt_VertexPosition;     \n"
               "}";
    } else {
        return ""
               "uniform highp mat4 qt_Matrix;                       \n"
               "attribute highp vec4 qt_VertexPosition;             \n"
               "attribute highp vec2 qt_VertexTexCoord;             \n"
               "varying highp vec2 qt_TexCoord;                     \n"
               "void main() {                                       \n"
               "   qt_TexCoord = qt_VertexTexCoord;                 \n"
               "   gl_Position = qt_Matrix * qt_VertexPosition;     \n"
               "}";
    }
}

const char * const *Q3DSLayer3DSGMaterialShader::attributeNames() const
{
    return q3ds_sg_vs_attributes();
}

const char *Q3DSLayer3DSGMaterialShader::vertexShader() const
{
    return q3ds_sg_vs();
}

const char *Q3DSLayer3DSGMaterialShader::fragmentShader() const
{
    // Make the result have pre-multiplied alpha.
    QOpenGLContext *ctx = QOpenGLContext::currentContext();
    if (ctx->format().version() >= qMakePair(3, 2) && ctx->format().profile() == QSurfaceFormat::CoreProfile) {
        return ""
               "#version 150 core                                   \n"
               "uniform sampler2D source;                           \n"
               "uniform float qt_Opacity;                           \n"
               "in vec2 qt_TexCoord;                                \n"
               "out vec4 fragColor;                                 \n"
               "void main() {                                       \n"
               "   vec4 p = texture(source, qt_TexCoord);           \n"
               "   float a = qt_Opacity * p.a;                      \n"
               "   fragColor = vec4(p.rgb * a, a);                  \n"
               "}";
    } else {
        return ""
               "uniform highp sampler2D source;                         \n"
               "uniform highp float qt_Opacity;                         \n"
               "varying highp vec2 qt_TexCoord;                         \n"
               "void main() {                                           \n"
               "   highp vec4 p = texture2D(source, qt_TexCoord);       \n"
               "   highp float a = qt_Opacity * p.a;                    \n"
               "   gl_FragColor = vec4(p.rgb * a, a);                   \n"
               "}";
    }
}

void Q3DSLayer3DSGMaterialShader::initialize()
{
    m_matrixId = program()->uniformLocation("qt_Matrix");
    m_opacityId = program()->uniformLocation("qt_Opacity");
}

static inline bool isPowerOfTwo(int x)
{
    // Assumption: x >= 1
    return x == (x & -x);
}

void Q3DSLayer3DSGMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    Q_ASSERT(!oldEffect || newEffect->type() == oldEffect->type());
    Q3DSLayer3DSGMaterial *tx = static_cast<Q3DSLayer3DSGMaterial *>(newEffect);
    Q3DSLayer3DSGMaterial *oldTx = static_cast<Q3DSLayer3DSGMaterial *>(oldEffect);

    QSGTexture *t = tx->texture();
    if (t) {
        QOpenGLContext *ctx = const_cast<QOpenGLContext *>(state.context());
        if (!ctx->functions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextureRepeat)) {
            const QSize size = t->textureSize();
            const bool isNpot = !isPowerOfTwo(size.width()) || !isPowerOfTwo(size.height());
            if (isNpot) {
                t->setHorizontalWrapMode(QSGTexture::ClampToEdge);
                t->setVerticalWrapMode(QSGTexture::ClampToEdge);
            }
        }
        if (!oldTx || oldTx->texture()->textureId() != t->textureId())
            t->bind();
        else
            t->updateBindOptions();
    }

    if (state.isMatrixDirty())
        program()->setUniformValue(m_matrixId, state.combinedMatrix());

    if (state.isOpacityDirty())
        program()->setUniformValue(m_opacityId, state.opacity());
}

void Q3DSLayer3DSGMaterial::setTexture(QSGTexture *texture)
{
    m_texture = texture;
    setFlag(Blending, m_texture ? m_texture->hasAlphaChannel() : false);
}

QSGMaterialType *Q3DSLayer3DSGMaterial::type() const
{
    return &materialType;
}

QSGMaterialShader *Q3DSLayer3DSGMaterial::createShader() const
{
    return new Q3DSLayer3DSGMaterialShader;
}

const char * const *Q3DSLayer3DSGMsaa2MaterialShader::attributeNames() const
{
    return q3ds_sg_vs_attributes();
}

const char *Q3DSLayer3DSGMsaa2MaterialShader::vertexShader() const
{
    return q3ds_sg_vs();
}

const char *Q3DSLayer3DSGMsaa2MaterialShader::fragmentShader() const
{
    // Make the result have pre-multiplied alpha.

    // Here we have 150 (3.2) core and ES 3.1 shaders only. Multisample
    // textures do not exist in ES < 3.1. This material is never set as the
    // active one with GLES < 3.1 (since the scenemanager takes care of
    // reverting sample count when setting up the scene), but handle all cases
    // gracefully regardless.

    const char prefix150[] =
            "#version 150 core                                                 \n";

    const char prefix310[] =
            "#version 310 es                                                   \n"
            "precision highp float;                                            \n";

    const char body[] =
            "uniform sampler2DMS source;                                       \n"
            "uniform float qt_Opacity;                                         \n"
            "in vec2 qt_TexCoord;                                              \n"
            "out vec4 fragColor;                                               \n"
            "void main() {                                                     \n"
            "   ivec2 tc = ivec2(floor(textureSize(source) * qt_TexCoord));    \n"
            "   vec4 p = texelFetch(source, tc, 0) + texelFetch(source, tc, 1);\n"
            "   p /= 2.0;                                                      \n"
            "   float a = qt_Opacity * p.a;                                    \n"
            "   fragColor = vec4(p.rgb * a, a);                                \n"
            "}";

    QOpenGLContext *ctx = QOpenGLContext::currentContext();
    if (ctx->format().version() >= qMakePair(3, 2) && ctx->format().profile() == QSurfaceFormat::CoreProfile) {
        static char buf[sizeof(prefix150) + sizeof(body)] = "";
        if (buf[0] == '\0') {
            strcpy(buf, prefix150);
            strcat(buf, body);
        }
        return buf;
    } else if (ctx->isOpenGLES() && ctx->format().version() >= qMakePair(3, 1)) {
        static char buf[sizeof(prefix310) + sizeof(body)] = "";
        if (buf[0] == '\0') {
            strcpy(buf, prefix310);
            strcat(buf, body);
        }
        return buf;
    } else {
        return "void main() { gl_FragColor = vec4(0.0); }\n";
    }
}

const char *Q3DSLayer3DSGMsaa4MaterialShader::fragmentShader() const
{
    // almost like Msaa2 but takes 4 samples

    const char prefix150[] =
            "#version 150 core                                                 \n";

    const char prefix310[] =
            "#version 310 es                                                   \n"
            "precision highp float;                                            \n";

    const char body[] =
            "uniform sampler2DMS source;                                       \n"
            "uniform float qt_Opacity;                                         \n"
            "in vec2 qt_TexCoord;                                              \n"
            "out vec4 fragColor;                                               \n"
            "void main() {                                                     \n"
            "   ivec2 tc = ivec2(floor(textureSize(source) * qt_TexCoord));    \n"
            "   vec4 p = texelFetch(source, tc, 0) + texelFetch(source, tc, 1) \n"
            "     + texelFetch(source, tc, 2) + texelFetch(source, tc, 3);     \n"
            "   p /= 4.0;                                                      \n"
            "   float a = qt_Opacity * p.a;                                    \n"
            "   fragColor = vec4(p.rgb * a, a);                                \n"
            "}";

    QOpenGLContext *ctx = QOpenGLContext::currentContext();
    if (ctx->format().version() >= qMakePair(3, 2) && ctx->format().profile() == QSurfaceFormat::CoreProfile) {
        static char buf[sizeof(prefix150) + sizeof(body)] = "";
        if (buf[0] == '\0') {
            strcpy(buf, prefix150);
            strcat(buf, body);
        }
        return buf;
    } else if (ctx->isOpenGLES() && ctx->format().version() >= qMakePair(3, 1)) {
        static char buf[sizeof(prefix310) + sizeof(body)] = "";
        if (buf[0] == '\0') {
            strcpy(buf, prefix310);
            strcat(buf, body);
        }
        return buf;
    } else {
        return "void main() { gl_FragColor = vec4(0.0); }\n";
    }
}

void Q3DSLayer3DSGMsaa2MaterialShader::initialize()
{
    m_matrixId = program()->uniformLocation("qt_Matrix");
    m_opacityId = program()->uniformLocation("qt_Opacity");
}

void Q3DSLayer3DSGMsaa2MaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    Q_ASSERT(!oldEffect || newEffect->type() == oldEffect->type());
    Q3DSLayer3DSGMaterial *tx = static_cast<Q3DSLayer3DSGMaterial *>(newEffect);
    Q3DSLayer3DSGMaterial *oldTx = static_cast<Q3DSLayer3DSGMaterial *>(oldEffect);

    QSGTexture *t = tx->texture();
    if (t) {
        QOpenGLContext *ctx = QOpenGLContext::currentContext();
        QOpenGLFunctions *f = ctx->functions();

        // This below does only the bare minimum, ignoring most of the
        // QSGTexture settings since we know what Studio3D and Studio3DEngine
        // wants. For anything more we should rather have Qt Quick (QSGTexture)
        // upgraded with support for multisample textures.

        f->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, t->textureId());
        if (!oldTx || oldTx->texture()->textureId() != t->textureId()) {
            f->glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            f->glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            f->glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            f->glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        }
    }

    if (state.isMatrixDirty())
        program()->setUniformValue(m_matrixId, state.combinedMatrix());

    if (state.isOpacityDirty())
        program()->setUniformValue(m_opacityId, state.opacity());
}

void Q3DSLayer3DSGMsaa2Material::setTexture(QSGTexture *texture)
{
    m_texture = texture;
    setFlag(Blending, m_texture ? m_texture->hasAlphaChannel() : false);
}

QSGMaterialType *Q3DSLayer3DSGMsaa2Material::type() const
{
    return &msaa2MaterialType;
}

QSGMaterialShader *Q3DSLayer3DSGMsaa2Material::createShader() const
{
    return new Q3DSLayer3DSGMsaa2MaterialShader;
}

QSGMaterialType *Q3DSLayer3DSGMsaa4Material::type() const
{
    return &msaa4MaterialType;
}

QSGMaterialShader *Q3DSLayer3DSGMsaa4Material::createShader() const
{
    return new Q3DSLayer3DSGMsaa4MaterialShader;
}

Q3DSLayer3DSGNode::Q3DSLayer3DSGNode()
    : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
    setMaterial(&m_material);
    setGeometry(&m_geometry);
}

Q3DSLayer3DSGNode::~Q3DSLayer3DSGNode()
{
    if (m_ownsTexture)
        delete m_material.texture();
}

QSGTexture *Q3DSLayer3DSGNode::texture() const
{
    return m_material.texture();
}

int Q3DSLayer3DSGNode::sampleCount() const
{
    return m_sampleCount;
}

void Q3DSLayer3DSGNode::setTexture(QSGTexture *texture, int msaaSampleCount)
{
    if (m_material.texture() == texture)
        return;

    if (m_ownsTexture)
        delete m_material.texture();

    m_material.setTexture(texture);
    m_msaa2Material.setTexture(texture);
    m_msaa4Material.setTexture(texture);

    QSGMaterial *newMaterial = &m_material;
    if (msaaSampleCount > 1) {
        switch (msaaSampleCount) {
        case 2:
            newMaterial = &m_msaa2Material;
            break;
        case 4:
            newMaterial = &m_msaa4Material;
            break;
        default:
            break;
        }
    }
    if (newMaterial != material())
        setMaterial(newMaterial);

    m_sampleCount = msaaSampleCount;

    markDirty(DirtyMaterial);
}

QRectF Q3DSLayer3DSGNode::rect() const
{
    return m_rect;
}

void Q3DSLayer3DSGNode::setRect(const QRectF &rect)
{
    if (rect == m_rect)
        return;

    m_rect = rect;

    const QRectF sourceRect(0.0f, 1.0f, 1.0f, -1.0f); // MirrorVertically
    QSGGeometry::updateTexturedRectGeometry(&m_geometry, m_rect, sourceRect);

    markDirty(DirtyGeometry);
}

bool Q3DSLayer3DSGNode::ownsTexture() const
{
    return m_ownsTexture;
}

void Q3DSLayer3DSGNode::setOwnsTexture(bool owns)
{
    m_ownsTexture = owns;
}

QT_END_NAMESPACE