summaryrefslogtreecommitdiffstats
path: root/source/slang/slang-core-module-textures.cpp
blob: f9573a15af40c724a4fc173fca6f41427e9aa577 (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
#include "slang-core-module-textures.h"

#include <spirv/unified1/spirv.h>

#define EMIT_LINE_DIRECTIVE() \
    sb << "#line " << (__LINE__ + 1) << " \"slang-core-module-textures.cpp\"\n"

namespace Slang
{

// Concatenate anything which can be passed to a StringBuilder
template<typename... Ts>
String cat(const Ts&... xs)
{
    return (StringBuilder{} << ... << xs);
};

//
// Utilities
//

const auto indentWidth = 4;
static const char spaces[] = "                    ";
static_assert(SLANG_COUNT_OF(spaces) % indentWidth == 1);

struct BraceScope
{
    BraceScope(const char*& i, StringBuilder& sb, const char* end = "\n")
        : i(i), sb(sb), end(end)
    {
        // If we hit this assert, it means that we are indenting too deep and
        // need more spaces in 'spaces' above.
        SLANG_ASSERT(i != spaces);
        sb << i << "{\n";
        i -= indentWidth;
    }
    ~BraceScope()
    {
        // If we hit this assert, it means that we've got a bug unindenting
        // more than we've indented.
        SLANG_ASSERT(*i != '\0');
        i += indentWidth;
        sb << i << "}" << end;
    }
    const char*& i;
    StringBuilder& sb;
    const char* end;
};

TextureTypeInfo::TextureTypeInfo(
    BaseTextureShapeInfo const& base,
    bool isArray,
    bool isMultisample,
    bool isShadow,
    StringBuilder& inSB,
    String const& inPath)
    : base(base)
    , isArray(isArray)
    , isMultisample(isMultisample)
    , isShadow(isShadow)
    , sb(inSB)
    , path(inPath)
{
    i = spaces + SLANG_COUNT_OF(spaces) - 1;
}

void TextureTypeInfo::writeFuncBody(
    const char* funcName,
    const String& glsl,
    const String& cuda,
    const String& spirvDefault,
    const String& spirvRWDefault,
    const String& spirvCombined,
    const String& metal,
    const String& wgsl)
{
    BraceScope funcScope{i, sb};
    {
        sb << i << "__target_switch\n";
        BraceScope switchScope{i, sb};
        sb << i << "case cpp:\n";
        sb << i << "case hlsl:\n";
        sb << i << "__intrinsic_asm \"." << funcName << "\";\n";
        if (glsl.getLength())
        {
            sb << i << "case glsl:\n";
            if (glsl.startsWith("if"))
                sb << glsl;
            else
                sb << i << "__intrinsic_asm \"" << glsl << "\";\n";
        }
        if (cuda.getLength())
        {
            sb << i << "case cuda:\n";
            sb << i << "__intrinsic_asm \"" << cuda << "\";\n";
        }
        if (metal.getLength())
        {
            sb << i << "case metal:\n";
            sb << i << "__intrinsic_asm \"" << metal << "\";\n";
        }
        if (spirvDefault.getLength() && spirvCombined.getLength())
        {
            sb << i << "case spirv:\n";
            sb << i << "if (access == " << kCoreModule_ResourceAccessReadWrite
               << " || access == " << kCoreModule_ResourceAccessWriteOnly << ")\n";
            sb << i << "return spirv_asm\n";
            {
                BraceScope spirvRWScope{i, sb, ";\n"};
                sb << spirvRWDefault << "\n";
            }
            sb << i << "else if (isCombined != 0)\n";
            sb << i << "{\n";
            {
                sb << i << "return spirv_asm\n";
                BraceScope spirvCombinedScope{i, sb, ";\n"};
                sb << spirvCombined << "\n";
            }
            sb << i << "}\n";
            sb << i << "else\n";
            sb << i << "{\n";
            {
                sb << i << "return spirv_asm\n";
                BraceScope spirvDefaultScope{i, sb, ";\n"};
                sb << spirvDefault << "\n";
            }
            sb << i << "}\n";
        }
        if (wgsl.getLength())
        {
            sb << i << "case wgsl:\n";
            sb << i << "__intrinsic_asm \"" << wgsl << "\";\n";
        }
    }
}

void TextureTypeInfo::writeFuncWithSig(
    const char* funcName,
    const String& sig,
    const String& glsl,
    const String& spirvDefault,
    const String& spirvRWDefault,
    const String& spirvCombined,
    const String& cuda,
    const String& metal,
    const String& wgsl,
    const ReadNoneMode readNoneMode)
{
    if (readNoneMode == ReadNoneMode::Always)
        sb << i << "[__readNone]\n";
    sb << i << "[ForceInline]\n";
    sb << i << sig << "\n";
    writeFuncBody(funcName, glsl, cuda, spirvDefault, spirvRWDefault, spirvCombined, metal, wgsl);
    sb << "\n";
}

void TextureTypeInfo::writeFunc(
    const char* returnType,
    const char* funcName,
    const String& params,
    const String& glsl,
    const String& spirvDefault,
    const String& spirvRWDefault,
    const String& spirvCombined,
    const String& cuda,
    const String& metal,
    const String& wgsl,
    const ReadNoneMode readNoneMode)
{
    writeFuncWithSig(
        funcName,
        cat(returnType, " ", funcName, "(", params, ")"),
        glsl,
        spirvDefault,
        spirvRWDefault,
        spirvCombined,
        cuda,
        metal,
        wgsl,
        readNoneMode);
}

enum class DimType
{
    Float,
    Int,
    UInt,

    Count,
};

// The WGSL texture attribute types for 'expr' are unsigned int, and anything else requires a
// conversion.
template<typename S>
static String wgslTextureAttributeConversion(DimType type, S expr)
{

    switch (type)
    {

    case DimType::UInt:
        return expr;


    case DimType::Float:
        {
            // Conversion to float is exact for values <= 2^24.
            String castExpr("f32(");
            castExpr.append(expr);
            castExpr.append(")");
            return castExpr;
        }
        break;

    case DimType::Int:
        {
            // We can assume two's complement and just do a bitcast, since texture dimensions can't
            // be anywhere near big enough to yield a negative result.
            String castExpr("bitcast<i32>(");
            castExpr.append(expr);
            castExpr.append(")");
            return castExpr;
        }
        break;

    default:
        SLANG_UNREACHABLE("Unexpected DimType enum value");
        break;
    };
}

void TextureTypeInfo::writeGetDimensionFunctions()
{
    static const char* kComponentNames[]{"x", "y", "z", "w"};

    SlangResourceShape baseShape = base.baseShape;

    // `GetDimensions`
    const char* dimParamTypes[int(DimType::Count)] = {"out float ", "out int ", "out uint "};
    const char* dimParamTypesInner[int(DimType::Count)] = {"float", "int", "uint"};
    for (int tid = 0; tid < int(DimType::Count); tid++)
    {
        DimType dimType = DimType(tid);
        auto t = dimParamTypes[tid];
        auto rawT = dimParamTypesInner[tid];

        for (int includeMipInfo = 0; includeMipInfo < 2; ++includeMipInfo)
        {
            if (includeMipInfo && isMultisample)
            {
                continue;
            }

            int sizeDimCount = 0;
            StringBuilder params;
            int paramCount = 0;

            StringBuilder metal;
            const char* metalMipLevel = "0";

            StringBuilder cuda;
            cuda << "{";

            StringBuilder wgsl;
            wgsl << "{";

            if (includeMipInfo)
            {
                ++paramCount;
                params << "uint mipLevel,";

                if (baseShape != SLANG_TEXTURE_1D)
                    metalMipLevel = "$1";
            }

            switch (baseShape)
            {
            case SLANG_TEXTURE_1D:
                ++paramCount;
                params << t << "width";
                metal << "(*($" << String(paramCount) << ") = $0.get_width("
                      << String(metalMipLevel) << ")),";
                cuda << "uint32_t width; asm(\\\"txq.width.b32 %0, [%1];\\\" : \\\"=r\\\"(width) : "
                        "\\\"l\\\"($0)); *($"
                     << String(paramCount) << ") = width;";
                wgsl << "($" << String(paramCount) << ") = "
                     << wgslTextureAttributeConversion(
                            dimType,
                            String("textureDimensions($0") + (includeMipInfo ? ", $1" : "") + ")")
                     << ";";

                sizeDimCount = 1;
                break;

            case SLANG_TEXTURE_2D:
            case SLANG_TEXTURE_CUBE:
                ++paramCount;
                params << t << "width,";
                metal << "(*($" << String(paramCount) << ") = $0.get_width("
                      << String(metalMipLevel) << ")),";
                cuda << "uint32_t w, h; asm(\\\"txq.width.b32 %0, [%2]; txq.height.b32 %1, "
                        "[%2];\\\" : \\\"=r\\\"(w), \\\"=r\\\"(h) : \\\"l\\\"($0)); *($"
                     << String(paramCount) << ") = w;";
                wgsl << "var dim = textureDimensions($0" << (includeMipInfo ? ", $1" : "") << ");";
                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "dim.x") << ";";

                ++paramCount;
                params << t << "height";
                metal << "(*($" << String(paramCount) << ") = $0.get_height("
                      << String(metalMipLevel) << ")),";
                if (cuda.getLength() > 1 && cuda[cuda.getLength() - 1] != ';')
                    cuda << "; ";
                cuda << "*($" << String(paramCount) << ") = h;";
                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "dim.y") << ";";

                sizeDimCount = 2;
                break;

            case SLANG_TEXTURE_3D:
                ++paramCount;
                params << t << "width,";
                metal << "(*($" << String(paramCount) << ") = $0.get_width("
                      << String(metalMipLevel) << ")),";
                cuda << "uint32_t w, h, d; asm(\\\"txq.width.b32 %0, [%3]; txq.height.b32 %1, "
                        "[%3]; txq.depth.b32 %2, [%3];\\\" : \\\"=r\\\"(w), \\\"=r\\\"(h), "
                        "\\\"=r\\\"(d) : \\\"l\\\"($0)); *($"
                     << String(paramCount) << ") = w;";
                wgsl << "var dim = textureDimensions($0" << (includeMipInfo ? ", $1" : "") << ");";
                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "dim.x") << ";";

                ++paramCount;
                params << t << "height,";
                metal << "(*($" << String(paramCount) << ") = $0.get_height("
                      << String(metalMipLevel) << ")),";
                if (cuda.getLength() > 1 && cuda[cuda.getLength() - 1] != ';')
                    cuda << "; ";
                cuda << "*($" << String(paramCount) << ") = h;";
                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "dim.y") << ";";

                ++paramCount;
                params << t << "depth";
                metal << "(*($" << String(paramCount) << ") = $0.get_depth("
                      << String(metalMipLevel) << ")),";
                if (cuda.getLength() > 1 && cuda[cuda.getLength() - 1] != ';')
                    cuda << "; ";
                cuda << "*($" << String(paramCount) << ") = d;";
                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "dim.z") << ";";

                sizeDimCount = 3;
                break;

            default:
                assert(!"unexpected");
                break;
            }

            if (isArray)
            {
                ++sizeDimCount;
                ++paramCount;
                params << ", " << t << "elements";
                metal << "(*($" << String(paramCount) << ") = $0.get_array_size()),";

                // For cube map arrays, CUDA should include all 6 faces in the array size count
                // but we can't currently implement this as txq.array_size isn't supported
                if (cuda.getLength() > 1 && cuda[cuda.getLength() - 1] != ';')
                    cuda << "; ";
                cuda << "/* txq.array_size not available in CUDA */ *($" << String(paramCount)
                     << ") = 0;";

                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "textureNumLayers($0)")
                     << ";";
            }

            if (isMultisample)
            {
                ++paramCount;
                params << ", " << t << "sampleCount";
                metal << "(*($" << String(paramCount) << ") = $0.get_num_samples()),";
                if (cuda.getLength() > 1 && cuda[cuda.getLength() - 1] != ';')
                    cuda << "; ";
                cuda << "/* txq.samples not available in CUDA */ *($" << String(paramCount)
                     << ") = 0;";
                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "textureNumSamples($0)")
                     << ";";
            }

            if (includeMipInfo)
            {
                ++paramCount;
                params << ", " << t << "numberOfLevels";
                metal << "(*($" << String(paramCount) << ") = $0.get_num_mip_levels()),";
                if (cuda.getLength() > 1 && cuda[cuda.getLength() - 1] != ';')
                    cuda << "; ";
                cuda << "/* txq.num_mipmap_levels not available in CUDA */ *($"
                     << String(paramCount) << ") = 0;";
                wgsl << "($" << String(paramCount)
                     << ") = " << wgslTextureAttributeConversion(dimType, "textureNumLevels($0)")
                     << ";";
            }

            metal.reduceLength(metal.getLength() - 1); // drop the last comma
            cuda << "}";
            wgsl << "}";

            StringBuilder glsl;
            {
                auto emitIntrinsic = [&](UnownedStringSlice funcName, bool useLodStr)
                {
                    int aa = 1;
                    StringBuilder opStrSB;
                    opStrSB << " = " << funcName << "($0";
                    if (useLodStr)
                    {
                        String lodStr = ", 0";
                        if (includeMipInfo)
                        {
                            int mipLevelArg = aa++;
                            lodStr = ", int($";
                            lodStr.append(mipLevelArg);
                            lodStr.append(")");
                        }
                        opStrSB << lodStr;
                    }
                    auto opStr = opStrSB.produceString();
                    int cc = 0;
                    switch (baseShape)
                    {
                    case SLANG_TEXTURE_1D:
                        glsl << "($" << aa++ << opStr << ")";
                        if (isArray)
                        {
                            glsl << ".x";
                        }
                        glsl << ")";
                        cc = 1;
                        break;

                    case SLANG_TEXTURE_2D:
                    case SLANG_TEXTURE_CUBE:
                        glsl << "($" << aa++ << opStr << ").x)";
                        glsl << ", ($" << aa++ << opStr << ").y)";
                        cc = 2;
                        break;

                    case SLANG_TEXTURE_3D:
                        glsl << "($" << aa++ << opStr << ").x)";
                        glsl << ", ($" << aa++ << opStr << ").y)";
                        glsl << ", ($" << aa++ << opStr << ").z)";
                        cc = 3;
                        break;

                    default:
                        SLANG_UNEXPECTED("unhandled resource shape");
                        break;
                    }

                    if (isArray)
                    {
                        glsl << ", ($" << aa++ << opStr << ")." << kComponentNames[cc] << ")";
                    }

                    if (isMultisample)
                    {
                        glsl << ", ($" << aa++ << " = textureSamples($0))";
                    }

                    if (includeMipInfo)
                    {
                        glsl << ", ($" << aa++ << " = textureQueryLevels($0))";
                    }
                };
                glsl << "if (isCombined == 0) { "
                        "__requireTargetExtension(\"GL_EXT_samplerless_texture_functions\"); }\n";
                glsl << "if (access == " << kCoreModule_ResourceAccessReadOnly
                     << ") __intrinsic_asm \"";
                emitIntrinsic(toSlice("textureSize"), !isMultisample);
                glsl << "\";\n";
                glsl << "__intrinsic_asm \"";
                emitIntrinsic(toSlice("imageSize"), false);
                glsl << "\";\n";
            }

            // SPIRV ASM generation
            auto generateSpirvAsm =
                [&](StringBuilder& spirv, bool isRW, UnownedStringSlice imageVar)
            {
                spirv << "%vecSize:$$uint";
                if (sizeDimCount > 1)
                    spirv << sizeDimCount;
                spirv << " = ";
                if (isMultisample || isRW)
                    spirv << "OpImageQuerySize " << imageVar << ";";
                else
                    spirv << "OpImageQuerySizeLod " << imageVar
                          << (includeMipInfo ? " $mipLevel;" : " $0;");

                auto convertAndStore = [&](UnownedStringSlice uintSourceVal, const char* destParam)
                {
                    if (UnownedStringSlice(rawT) == "uint")
                    {
                        spirv << "OpStore &" << destParam << " %" << uintSourceVal << ";";
                    }
                    else
                    {
                        if (UnownedStringSlice(rawT) == "int")
                        {
                            spirv << "%c_" << uintSourceVal << " : $$" << rawT << " = OpBitcast %"
                                  << uintSourceVal << "; ";
                        }
                        else
                        {
                            spirv << "%c_" << uintSourceVal << " : $$" << rawT
                                  << " = OpConvertUToF %" << uintSourceVal << "; ";
                        }
                        spirv << "OpStore &" << destParam << "%c_" << uintSourceVal << ";";
                    }
                };
                auto extractSizeComponent = [&](int componentId, const char* destParam)
                {
                    String elementVal = String("_") + destParam;
                    if (sizeDimCount == 1)
                    {
                        spirv << "%" << elementVal << " : $$uint = OpCopyObject %vecSize; ";
                    }
                    else
                    {
                        spirv << "%" << elementVal << " : $$uint = OpCompositeExtract %vecSize "
                              << componentId << "; ";
                    }
                    convertAndStore(elementVal.getUnownedSlice(), destParam);
                };
                switch (baseShape)
                {
                case SLANG_TEXTURE_1D:
                    extractSizeComponent(0, "width");
                    break;

                case SLANG_TEXTURE_2D:
                case SLANG_TEXTURE_CUBE:
                    extractSizeComponent(0, "width");
                    extractSizeComponent(1, "height");
                    break;

                case SLANG_TEXTURE_3D:
                    extractSizeComponent(0, "width");
                    extractSizeComponent(1, "height");
                    extractSizeComponent(2, "depth");
                    break;

                default:
                    assert(!"unexpected");
                    break;
                }

                if (isArray)
                {
                    extractSizeComponent(sizeDimCount - 1, "elements");
                }

                if (isMultisample)
                {
                    spirv << "%_sampleCount : $$uint = OpImageQuerySamples" << imageVar << ";";
                    convertAndStore(UnownedStringSlice("_sampleCount"), "sampleCount");
                }

                if (includeMipInfo)
                {
                    spirv << "%_levelCount : $$uint = OpImageQueryLevels" << imageVar << ";";
                    convertAndStore(UnownedStringSlice("_levelCount"), "numberOfLevels");
                }
            };
            StringBuilder spirvCombined;
            {
                spirvCombined << "OpCapability ImageQuery; ";
                spirvCombined << "%image:__imageType(this) = OpImage $this; ";
                generateSpirvAsm(spirvCombined, false, toSlice("%image"));
            }

            StringBuilder spirvDefault;
            {
                spirvDefault << "OpCapability ImageQuery; ";
                generateSpirvAsm(spirvDefault, false, toSlice("$this"));
            }

            StringBuilder spirvRWDefault;
            {
                spirvRWDefault << "OpCapability ImageQuery; ";
                generateSpirvAsm(spirvRWDefault, true, toSlice("$this"));
            }

            sb << "    __glsl_version(450)\n";

            sb << "    [require(cpp";
            if (cuda.getLength())
                sb << "_cuda";
            if (glsl.getLength())
                sb << "_glsl";
            sb << "_hlsl";
            if (metal.getLength())
                sb << "_metal";
            if (spirvDefault.getLength() && spirvCombined.getLength())
                sb << "_spirv";
            if (wgsl.getLength())
                sb << "_wgsl";
            sb << ", texture_sm_4_1)]\n";

            writeFunc(
                "void",
                "GetDimensions",
                params,
                glsl,
                spirvDefault,
                spirvRWDefault,
                spirvCombined,
                cuda.produceString(),
                metal,
                wgsl,
                ReadNoneMode::Always);
        }
    }
}

} // namespace Slang