OLED Subpixel Matrix shader

oled-subpixel-matrix.glsl · 853 lines · GLSL ES 3.00 · MIT

OLED Subpixel MatrixSci-Fi & Noise
OLED Subpixel Matrix WebGL2 procedural shader preview
FPS 60BUFFER 960×540SOURCE 853 linesSPEC GLSL ES 3.00

Seamless PNG Texture Baker
1-Click Engine Shader Export
WebGL2 .glsl
.glsl
Godot 4 .gdshader
Three.js GLSL3

Engine shader code & wrappers

Sci-Fi & Micro-Optics
oled-subpixel-matrix.glsl (853 lines)
#version 300 es
// OLED Subpixel Matrix (oled-subpixel-matrix.glsl)
// Upstream study: https://github.com/gokayfem/glsl-studies/blob/main/electronics/lib/01_rgb_oled_pentile_subpixel_matrix.glsl
// License: MIT (Copyright 2026 Gokay Aydogan) + MIT/CC0 helpers — https://pixelfx.io/LICENSE-SHADERS.txt
// Uniforms: uResolution (vec2), uTime (float), uOpen (0..1), uLightMode (0..3), uCamMode (0..1)
precision highp float;
precision highp int;

uniform vec2 uResolution;
uniform float uTime;
uniform float uOpen;
uniform int uLightMode;
uniform int uCamMode;

out vec4 fragColor;

// -----------------------------------------------------------------------------
// Constants & Module Dimensions (Landscape Flagship OLED Display Module)
// -----------------------------------------------------------------------------
const float PI = 3.14159265359;
const float MODULE_YAW = -0.32;

// Chassis: 2.08 x 0.112 x 1.04 resting on y = 0.0
const vec2 CHASSIS_HALF = vec2(1.04, 0.52);
const float CHASSIS_H = 0.112;
const float CHASSIS_R = 0.145;

// 2.5D Cover Glass sitting proud on top of chassis
const vec2 GLASS_HALF = vec2(1.012, 0.492);
const float GLASS_TOP_Y = 0.132;
const float GLASS_R = 0.125;

// Active OLED Display area recessed optically under cover glass
const vec2 DISP_HALF = vec2(0.955, 0.440);
const float DISP_R = 0.085;
const float GLASS_THICK = 0.022;

// -----------------------------------------------------------------------------
// Math & SDF Primitives
// -----------------------------------------------------------------------------
mat2 rot2(float a) {
    float c = cos(a), s = sin(a);
    return mat2(c, -s, s, c);
}

vec3 toLocal(vec3 p) {
    vec3 q = p;
    q.xz = rot2(-MODULE_YAW) * q.xz;
    return q;
}

vec3 vecToLocal(vec3 v) {
    vec3 q = v;
    q.xz = rot2(-MODULE_YAW) * q.xz;
    return q;
}

float sdRoundBox2D(vec2 p, vec2 b, float r) {
    vec2 q = abs(p) - b + r;
    return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
}

float sdRoundedPlate(vec3 p, vec2 b, float halfH, float rCorner, float rBevel) {
    float d2 = sdRoundBox2D(p.xz, b - rBevel, max(rCorner - rBevel, 0.001));
    vec2 w = vec2(d2, abs(p.y) - (halfH - rBevel));
    return min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - rBevel;
}

float sdCapsule2D(vec2 p, vec2 a, vec2 b, float r) {
    vec2 pa = p - a, ba = b - a;
    float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
    return length(pa - ba * h) - r;
}

float hash21(vec2 p) {
    p = fract(p * vec2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

float valueNoise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash21(i);
    float b = hash21(i + vec2(1.0, 0.0));
    float c = hash21(i + vec2(0.0, 1.0));
    float d = hash21(i + vec2(1.0, 1.0));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}

// -----------------------------------------------------------------------------
// Scene SDFs (Hero Only & Combined)
// -----------------------------------------------------------------------------
float mapHeroDetail(vec3 p, out int matId) {
    vec3 q = toLocal(p);

    // 1. Dark anodized titanium/aluminum lower gasket foot (y: 0.0 -> 0.010)
    float dFoot = sdRoundedPlate(
        q - vec3(0.0, 0.005, 0.0),
        CHASSIS_HALF - vec2(0.018),
        0.005,
        CHASSIS_R - 0.015,
        0.003
    );

    // 2. Main precision-machined chamfered aluminum mid-frame (y: 0.006 -> 0.112)
    float dChassis = sdRoundedPlate(
        q - vec3(0.0, 0.059, 0.0),
        CHASSIS_HALF,
        0.053,
        CHASSIS_R,
        0.012
    );

    // Subtle side hardware buttons (power & volume rocker on -Z edge)
    vec3 qb1 = q - vec3(0.28, 0.058, -CHASSIS_HALF.y - 0.004);
    float dBtn1 = sdRoundedPlate(qb1.xzy, vec2(0.085, 0.016), 0.008, 0.006, 0.004);
    vec3 qb2 = q - vec3(-0.08, 0.058, -CHASSIS_HALF.y - 0.004);
    float dBtn2 = sdRoundedPlate(qb2.xzy, vec2(0.145, 0.016), 0.008, 0.006, 0.004);
    float dButtons = min(dBtn1, dBtn2);

    // 3. Glossy 2.5D curved-edge cover glass (y: 0.098 -> 0.132)
    float dGlass = sdRoundedPlate(
        q - vec3(0.0, 0.115, 0.0),
        GLASS_HALF,
        0.017,
        GLASS_R,
        0.014
    );

    // Subtle earpiece speaker micro-slit carved along left-center bezel edge
    float dSlit = sdRoundedPlate(
        q - vec3(-0.986, GLASS_TOP_Y + 0.002, 0.0),
        vec2(0.006, 0.085),
        0.005,
        0.004,
        0.002
    );
    dGlass = max(dGlass, -dSlit);

    float dMetal = min(dChassis, dButtons);

    // Material IDs: 1 = chassis metal, 2 = foot gasket, 3 = cover glass
    float d = dMetal;
    matId = 1;
    if (dFoot < d) {
        d = dFoot;
        matId = 2;
    }
    if (dGlass < d) {
        d = dGlass;
        matId = 3;
    }
    return d;
}

float mapHero(vec3 p) {
    int dummy;
    return mapHeroDetail(p, dummy);
}

float map(vec3 p) {
    return min(mapHero(p), p.y);
}

// Rule (1): Unit-weight tetrahedral normals
vec3 calcNormal(vec3 p) {
    const float e = 0.0005;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * map(p + k.xyy * e) +
        k.yyx * map(p + k.yyx * e) +
        k.yxy * map(p + k.yxy * e) +
        k.xxx * map(p + k.xxx * e)
    );
}

// Rule (3): Clean hero-only soft shadow (no ph!)
float softShadow(vec3 ro, vec3 rd, float tMax, float k) {
    float res = 1.0;
    float t = 0.025;
    for (int i = 0; i < 64; i++) {
        float h = mapHero(ro + rd * t);
        res = min(res, k * h / t);
        if (res < 0.005 || t > tMax) break;
        t += max(h, 0.015);
    }
    return clamp(res, 0.0, 1.0);
}

float calcAO(vec3 p, vec3 n) {
    float occ = 0.0;
    float sca = 1.0;
    for (int i = 1; i <= 5; i++) {
        float h = 0.018 * float(i) * float(i) * 0.45 + 0.012;
        float d = map(p + n * h);
        occ += (h - d) * sca;
        sca *= 0.72;
    }
    return clamp(1.0 - 2.4 * occ, 0.12, 1.0);
}

// -----------------------------------------------------------------------------
// Studio Environment (Softboxes + Negative-Fill Flags)
// -----------------------------------------------------------------------------
float rectSoftbox(vec3 d, vec3 center, vec3 uAxis, vec3 vAxis, vec2 halfSize, float softness) {
    float denom = dot(d, center);
    if (denom <= 0.05) return 0.0;
    vec3 proj = d / denom - center;
    vec2 uv = vec2(dot(proj, uAxis), dot(proj, vAxis));
    vec2 q = abs(uv) - halfSize;
    float dist = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
    return 1.0 - smoothstep(-softness, softness, dist);
}

vec3 evalStudioEnv(vec3 dir, int lightMode) {
    vec3 d = normalize(dir);
    float y = clamp(d.y, -1.0, 1.0);

    // Base studio cyclorama gradient (rich charcoal-slate, never pure black)
    vec3 env = mix(vec3(0.028, 0.031, 0.038), vec3(0.068, 0.074, 0.088), smoothstep(-0.15, 0.65, y));

    // Overhead main key softbox (angled to glide across the cover glass bevel & screen)
    vec3 keyDir = normalize(vec3(-0.35, 0.86, 0.36));
    vec3 keyU = normalize(cross(vec3(0.0, 0.0, 1.0), keyDir));
    vec3 keyV = cross(keyDir, keyU);
    float sbKey = rectSoftbox(d, keyDir, keyU, keyV, vec2(0.58, 0.24), 0.065);

    // Cool studio strip softbox on the right-back (crisp glass bevel & frame edge highlight)
    vec3 stripDir = normalize(vec3(0.76, 0.48, -0.44));
    vec3 stripU = normalize(cross(vec3(0.0, 1.0, 0.0), stripDir));
    vec3 stripV = cross(stripDir, stripU);
    float sbStrip = rectSoftbox(d, stripDir, stripU, stripV, vec2(0.68, 0.11), 0.045);

    // Low warm-neutral front fill card
    vec3 fillDir = normalize(vec3(-0.68, 0.34, 0.65));
    vec3 fillU = normalize(cross(vec3(0.0, 1.0, 0.0), fillDir));
    vec3 fillV = cross(fillDir, fillU);
    float sbFill = rectSoftbox(d, fillDir, fillU, fillV, vec2(0.45, 0.22), 0.12);

    // Grazing side raking softbox
    vec3 grazeDir = normalize(vec3(0.94, 0.18, 0.28));
    vec3 grazeU = normalize(cross(vec3(0.0, 1.0, 0.0), grazeDir));
    vec3 grazeV = cross(grazeDir, grazeU);
    float sbGraze = rectSoftbox(d, grazeDir, grazeU, grazeV, vec2(0.55, 0.09), 0.035);

    // Backlit rim softbox
    vec3 backDir = normalize(vec3(-0.18, 0.32, -0.93));
    vec3 backU = normalize(cross(vec3(0.0, 1.0, 0.0), backDir));
    vec3 backV = cross(backDir, backU);
    float sbBack = rectSoftbox(d, backDir, backU, backV, vec2(0.92, 0.26), 0.06);

    // Negative-fill flags (matte black studio absorbers for crisp specular contrast)
    vec3 flag1Dir = normalize(vec3(0.32, 0.68, 0.66));
    vec3 f1U = normalize(cross(vec3(0.0, 1.0, 0.0), flag1Dir));
    vec3 f1V = cross(flag1Dir, f1U);
    float negFlag1 = rectSoftbox(d, flag1Dir, f1U, f1V, vec2(0.38, 0.34), 0.04);

    vec3 flag2Dir = normalize(vec3(-0.85, 0.42, -0.30));
    vec3 f2U = normalize(cross(vec3(0.0, 1.0, 0.0), flag2Dir));
    vec3 f2V = cross(flag2Dir, f2U);
    float negFlag2 = rectSoftbox(d, flag2Dir, f2U, f2V, vec2(0.34, 0.42), 0.04);

    if (lightMode == 0) {
        // Hero studio lighting
        env += vec3(1.55, 1.52, 1.48) * sbKey;
        env += vec3(1.25, 1.38, 1.58) * sbStrip;
        env += vec3(0.42, 0.40, 0.38) * sbFill;
        env += vec3(0.48, 0.52, 0.60) * sbBack;
    } else if (lightMode == 1) {
        // Pure neutral grayscale studio lighting
        float baseG = dot(env, vec3(0.2126, 0.7152, 0.0722));
        env = vec3(baseG * 1.15);
        env += vec3(1.65) * sbKey;
        env += vec3(1.35) * sbStrip;
        env += vec3(0.55) * sbFill;
        env += vec3(0.45) * sbBack;
    } else if (lightMode == 2) {
        // Grazing raking light
        env *= 0.62;
        env += vec3(0.32, 0.34, 0.38) * sbKey;
        env += vec3(2.35, 2.22, 2.02) * sbGraze;
        env += vec3(0.85, 0.95, 1.15) * sbStrip;
        env += vec3(0.24, 0.26, 0.30) * sbFill;
    } else {
        // Backlit rim drama
        env *= 0.55;
        env += vec3(0.26, 0.28, 0.34) * sbKey;
        env += vec3(2.55, 2.68, 2.95) * sbBack;
        env += vec3(1.15, 1.28, 1.48) * sbStrip;
        env += vec3(0.28, 0.27, 0.26) * sbFill;
    }

    // Apply negative-fill flags
    float negMask = clamp(max(negFlag1, negFlag2), 0.0, 1.0);
    env = mix(env, vec3(0.016, 0.017, 0.020), negMask * 0.85);

    if (lightMode == 1) {
        env = vec3(dot(env, vec3(0.2126, 0.7152, 0.0722)));
    }
    return env;
}

// -----------------------------------------------------------------------------
// OLED Calibration Test Pattern (uOpen: 0 = Color-Bar/Gradient, 1 = White/Cyan)
// -----------------------------------------------------------------------------
vec3 hsv2rgb(vec3 c) {
    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

vec3 sampleColorGradientPattern(vec2 uv) {
    // uv in [0, 1] x [0, 1] across active display (x = left..right, y = top..bottom)
    vec3 col = vec3(0.0);

    // Subtle slow drift for liveliness without disturbing readability
    float drift = 0.025 * sin(uTime * 0.35);

    if (uv.y < 0.47) {
        // Top band: Silky smooth full-spectrum HSV color gradient with gentle luminance curve
        float hue = fract(uv.x * 0.94 + 0.01 + drift);
        float sat = mix(0.88, 1.0, smoothstep(0.0, 0.38, uv.y));
        float val = mix(0.96, 0.62, smoothstep(0.32, 0.47, uv.y));
        col = hsv2rgb(vec3(hue, sat, val));
    } else if (uv.y < 0.49) {
        // Crisp dark calibration divider with subtle tick marks
        float tick = step(0.92, fract(uv.x * 16.0));
        col = vec3(0.04 + 0.35 * tick);
    } else if (uv.y < 0.84) {
        // Middle band: 7 crisp calibration color bars (White, Yellow, Cyan, Green, Magenta, Red, Blue)
        float idx = floor(uv.x * 7.0);
        if (idx < 0.5)      col = vec3(0.94, 0.95, 0.96); // Reference White
        else if (idx < 1.5) col = vec3(0.96, 0.84, 0.04); // Yellow (R+G)
        else if (idx < 2.5) col = vec3(0.02, 0.88, 0.96); // Cyan (G+B)
        else if (idx < 3.5) col = vec3(0.06, 0.92, 0.14); // Pure Green
        else if (idx < 4.5) col = vec3(0.94, 0.08, 0.88); // Magenta (R+B)
        else if (idx < 5.5) col = vec3(0.96, 0.06, 0.05); // Pure Red
        else                col = vec3(0.06, 0.22, 0.98); // Pure Blue

        // Subtle vertical luminance gradient inside each bar for depth
        float barV = (uv.y - 0.49) / 0.35;
        col *= mix(1.0, 0.72, barV * barV);
    } else if (uv.y < 0.86) {
        // Dark separator
        col = vec3(0.025);
    } else {
        // Bottom band: 10-step neutral grayscale + black-level calibration pluge ramp
        float stepVal = floor(uv.x * 10.0) / 9.0;
        col = vec3(mix(0.02, 0.94, pow(stepVal, 1.35)));
    }

    // Subtle crisp border frame hair-line inside active display
    vec2 edgeD = min(uv, 1.0 - uv);
    float frameLine = 1.0 - smoothstep(0.004, 0.008, min(edgeD.x * 2.0, edgeD.y));
    col = mix(col, vec3(0.28, 0.30, 0.34), frameLine * 0.45);

    return col;
}

vec3 sampleWhiteCyanPattern(vec2 uv) {
    // High-contrast white / electric cyan subpixel diagnostic test pattern
    vec3 pureWhite = vec3(0.98, 0.99, 1.00);
    vec3 pureCyan  = vec3(0.00, 0.94, 1.00);
    vec3 jetBlack  = vec3(0.015, 0.02, 0.025);

    vec3 col = jetBlack;

    if (uv.y < 0.50) {
        // Upper half: alternating high-contrast White / Cyan / Black precision bars
        float stripe = floor(uv.x * 12.0);
        float m = mod(stripe, 3.0);
        if (m < 0.5)      col = pureWhite;
        else if (m < 1.5) col = pureCyan;
        else              col = jetBlack;

        // Crisp horizontal diagnostic hairline across upper bars
        float hLine = 1.0 - smoothstep(0.004, 0.010, abs(uv.y - 0.25));
        col = mix(col, pureWhite, hLine);
    } else if (uv.y < 0.53) {
        // High-contrast cyan divider bar
        col = pureCyan;
    } else {
        // Lower half: crisp macro subpixel checkerboard (White vs Cyan vs Deep Black)
        vec2 grid = floor(uv * vec2(18.0, 8.0));
        float chk = mod(grid.x + grid.y, 2.0);
        float sub = mod(grid.x, 3.0);
        if (chk > 0.5) {
            col = (sub < 1.5) ? pureWhite : pureCyan;
        } else {
            col = (sub < 0.5) ? jetBlack : pureCyan * 0.22;
        }
    }

    // Precision circular reticle in center-right (great for macro focus check)
    vec2 pRet = (uv - vec2(0.66, 0.58)) * vec2(2.15, 1.0);
    float r = length(pRet);
    float ring = 1.0 - smoothstep(0.008, 0.015, abs(r - 0.14));
    float crossH = (1.0 - smoothstep(0.005, 0.010, abs(pRet.y))) * step(abs(pRet.x), 0.19);
    float crossV = (1.0 - smoothstep(0.005, 0.010, abs(pRet.x))) * step(abs(pRet.y), 0.19);
    float reticle = clamp(max(ring, max(crossH, crossV)), 0.0, 1.0);
    col = mix(col, pureWhite, reticle * 0.92);

    return col;
}

// -----------------------------------------------------------------------------
// Diamond PenTile RGB Subpixel Matrix (fwidth-Antialiased)
// Large Red & Blue diamonds + Small Paired Green Ovals in Jet-Black Matrix
// -----------------------------------------------------------------------------
struct OledSample {
    vec3 emission;
    float matrixMask;   // 1 on subpixel emitter well, 0 on black matrix
    float subpixelTopo; // subtle micro-relief for muted grayscale mode
};

OledSample evalPenTileOLED(vec2 dispPos, vec3 rdLocal, float openMix) {
    OledSample res;
    res.emission = vec3(0.0);
    res.matrixMask = 0.0;
    res.subpixelTopo = 0.0;

    // Optical refraction parallax through cover glass (IOR = 1.52)
    vec2 parallax = rdLocal.xz * (GLASS_THICK / max(-rdLocal.y, 0.28));
    vec2 pSub = dispPos + parallax;

    // Normalize display coordinates to [0, 1]
    vec2 uv = (pSub / (2.0 * DISP_HALF)) + 0.5;

    // Sample the underlying test pattern
    vec3 pat0 = sampleColorGradientPattern(clamp(uv, 0.0, 1.0));
    vec3 pat1 = sampleWhiteCyanPattern(clamp(uv, 0.0, 1.0));
    vec3 targetCol = mix(pat0, pat1, smoothstep(0.0, 1.0, openMix));

    // PenTile lattice: 64 cells across display height -> silky smooth hero, crisp 2.5x macro
    float cellsY = 64.0;
    float pitch = (2.0 * DISP_HALF.y) / cellsY;
    vec2 cellCoord = pSub / pitch;

    // Compute screen-space derivative for fwidth antialiasing & moire-free band-limiting
    vec2 dcx = dFdx(cellCoord);
    vec2 dcy = dFdy(cellCoord);
    float fw = max(length(dcx), length(dcy));
    float aa = clamp(fw * 0.85, 0.006, 0.25);

    // Smooth transition from crisp subpixel geometry (macro) to energy-conserving smooth OLED (hero)
    float detailFade = 1.0 - smoothstep(0.085, 0.23, fw);

    // --- 1. Red & Blue Large Diamonds on integer lattice (ix, iy) ---
    vec2 rbCell = floor(cellCoord + 0.5);
    vec2 rbLocal = cellCoord - rbCell; // in [-0.5, 0.5]^2
    float parity = mod(rbCell.x + rbCell.y, 2.0); // 0 = Red, 1 = Blue

    // Rounded diamond SDF (L1 distance with subtle corner rounding)
    float dL1 = abs(rbLocal.x) + abs(rbLocal.y);
    float dL2 = length(rbLocal);
    float dDiamond = mix(dL1, dL2 * 1.18, 0.16);

    // Blue diamond is slightly larger than Red (authentic OLED lifetime compensation)
    float rRed  = 0.315;
    float rBlue = 0.365;

    float maskR = (1.0 - parity) * (1.0 - smoothstep(rRed - aa, rRed + aa, dDiamond));
    float maskB = parity * (1.0 - smoothstep(rBlue - aa, rBlue + aa, dDiamond));

    // Hot emitter core gradient inside each diamond for realistic OLED micro-glow
    float coreR = (1.0 - parity) * (1.0 - smoothstep(0.04, rRed, dDiamond));
    float coreB = parity * (1.0 - smoothstep(0.04, rBlue, dDiamond));

    // --- 2. Small Paired Green Ovals at half-integer cell centers (ix + 0.5, iy + 0.5) ---
    vec2 gCell = floor(cellCoord);
    vec2 gLocal = cellCoord - (gCell + 0.5); // in [-0.5, 0.5]^2
    float gParity = mod(gCell.x + gCell.y, 2.0);
    // Alternate +45 and -45 degree orientation for authentic Diamond PenTile herringbone pairs
    float gAngle = (gParity < 0.5) ? (PI * 0.25) : (-PI * 0.25);
    vec2 gRot = rot2(gAngle) * gLocal;

    // Small elongated green oval/capsule
    float dGreen = sdCapsule2D(gRot, vec2(-0.085, 0.0), vec2(0.085, 0.0), 0.105);
    float maskG = 1.0 - smoothstep(-aa, aa, dGreen);
    float coreG = 1.0 - smoothstep(-0.10, 0.02, dGreen);

    // Analytical average fill factors per channel over a 2x2 tile (for energy conservation)
    const float avgR = 0.115;
    const float avgG = 0.155;
    const float avgB = 0.150;

    // Sample pattern at quantized subpixel center in macro so each subpixel has uniform solid color
    vec2 subCenterR = ((rbCell) * pitch) / (2.0 * DISP_HALF) + 0.5;
    vec2 subCenterG = ((gCell + 0.5) * pitch) / (2.0 * DISP_HALF) + 0.5;
    vec3 colRB = mix(
        sampleColorGradientPattern(clamp(subCenterR, 0.0, 1.0)),
        sampleWhiteCyanPattern(clamp(subCenterR, 0.0, 1.0)),
        smoothstep(0.0, 1.0, openMix)
    );
    vec3 colG = mix(
        sampleColorGradientPattern(clamp(subCenterG, 0.0, 1.0)),
        sampleWhiteCyanPattern(clamp(subCenterG, 0.0, 1.0)),
        smoothstep(0.0, 1.0, openMix)
    );

    vec3 driveR = mix(targetCol, colRB, detailFade);
    vec3 driveG = mix(targetCol, colG,  detailFade);
    vec3 driveB = mix(targetCol, colRB, detailFade);

    // Boost individual subpixel luminance cleanly to conserve area-averaged brightness
    // while keeping peak intensity well within ACES headroom
    float boostR = mix(1.0, (maskR * (0.82 + 0.36 * coreR)) / (avgR * 3.1), detailFade);
    float boostG = mix(1.0, (maskG * (0.82 + 0.36 * coreG)) / (avgG * 2.5), detailFade);
    float boostB = mix(1.0, (maskB * (0.82 + 0.36 * coreB)) / (avgB * 2.6), detailFade);

    // Subtle soft micro-bloom bleed inside the jet-black matrix around lit subpixels
    float haloR = (1.0 - parity) * exp(-max(dDiamond - rRed, 0.0) * 14.0) * 0.16 * detailFade;
    float haloG = exp(-max(dGreen, 0.0) * 16.0) * 0.14 * detailFade;
    float haloB = parity * exp(-max(dDiamond - rBlue, 0.0) * 14.0) * 0.16 * detailFade;

    vec3 emit;
    emit.r = driveR.r * (boostR + haloR);
    emit.g = driveG.g * (boostG + haloG);
    emit.b = driveB.b * (boostB + haloB);

    // Slight cross-talk warmth & OLED sRGB-to-linear gamma curve
    emit = pow(max(emit, 0.0), vec3(1.55)) * 1.45;

    // Active display rounded-rectangle mask (with clean recessed glass edge)
    float dDisp = sdRoundBox2D(pSub, DISP_HALF, DISP_R);
    float activeMask = 1.0 - smoothstep(-0.0025, 0.0025, dDisp);

    res.emission = emit * activeMask;
    res.matrixMask = clamp(maskR + maskG + maskB, 0.0, 1.0) * activeMask;
    res.subpixelTopo = mix(0.28, res.matrixMask, detailFade) * activeMask;
    return res;
}

// -----------------------------------------------------------------------------
// PBR Helpers
// -----------------------------------------------------------------------------
float D_GGX(float NoH, float rough) {
    float a = rough * rough;
    float a2 = a * a;
    float d = NoH * NoH * (a2 - 1.0) + 1.0;
    return a2 / (PI * d * d + 1e-6);
}

float G_SchlickGGX(float NoV, float NoL, float rough) {
    float k = (rough + 1.0);
    k = (k * k) / 8.0;
    float gv = NoV / (NoV * (1.0 - k) + k);
    float gl = NoL / (NoL * (1.0 - k) + k);
    return gv * gl;
}

vec3 F_Schlick(float cosTheta, vec3 F0) {
    return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
}

vec3 shadeDirectLight(vec3 N, vec3 V, vec3 L, vec3 lightCol, vec3 baseCol, float metallic, float rough, vec3 F0) {
    vec3 H = normalize(V + L);
    float NoL = max(dot(N, L), 0.0);
    float NoV = max(dot(N, V), 0.001);
    float NoH = max(dot(N, H), 0.0);
    float HoV = max(dot(H, V), 0.0);

    float D = D_GGX(NoH, rough);
    float G = G_SchlickGGX(NoV, NoL, rough);
    vec3 F = F_Schlick(HoV, F0);

    vec3 spec = (D * G * F) / max(4.0 * NoV * NoL, 0.001);
    vec3 kD = (1.0 - F) * (1.0 - metallic);
    vec3 diff = kD * baseCol / PI;

    return (diff + spec) * lightCol * NoL;
}

// -----------------------------------------------------------------------------
// ACES Filmic Tone Mapping
// -----------------------------------------------------------------------------
vec3 acesToneMap(vec3 x) {
    const float a = 2.51;
    const float b = 0.03;
    const float c = 2.43;
    const float d = 0.59;
    const float e = 0.14;
    return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0);
}

// -----------------------------------------------------------------------------
// Main Render
// -----------------------------------------------------------------------------
void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution) / uResolution.y;

    // Camera Rig: uCamMode 0 = Hero, 1 = ~2.5x Macro on PenTile Matrix + Bevel
    vec3 ro, ta;
    float fl;

    if (uCamMode == 0) {
        // Hero 3/4 studio view showing entire angled OLED module + cast shadow
        float subtleOrbit = 0.03 * sin(uTime * 0.25);
        ro = vec3(1.06 + subtleOrbit, 1.82, 2.52);
        ta = vec3(0.0, 0.04, 0.02);
        fl = 2.20;
    } else {
        // ~2.5x Macro focused on active PenTile matrix transition + 2.5D cover glass bevel
        vec3 macroLocal = vec3(0.28, GLASS_TOP_Y, 0.13);
        vec3 macroWorld = macroLocal;
        macroWorld.xz = rot2(MODULE_YAW) * macroWorld.xz;

        ta = macroWorld;
        ro = macroWorld + vec3(0.32, 0.96, 0.94);
        fl = 2.35;
    }

    vec3 ww = normalize(ta - ro);
    vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0)));
    vec3 vv = cross(uu, ww);
    vec3 rd = normalize(uv.x * uu + uv.y * vv + fl * ww);

    // Raymarch scene
    float t = 0.0;
    const float tMax = 18.0;
    bool hit = false;
    for (int i = 0; i < 128; i++) {
        vec3 p = ro + rd * t;
        float d = map(p);
        if (d < 0.00035) {
            hit = true;
            break;
        }
        t += d * 0.92;
        if (t > tMax) break;
    }

    vec3 col = evalStudioEnv(rd, uLightMode);

    if (hit) {
        vec3 p = ro + rd * t;
        int matId = 0;
        float dHero = mapHeroDetail(p, matId);
        // Rule (2): Exact bench vs hero classification
        bool isBench = (p.y <= dHero + 0.001);

        vec3 N = isBench ? vec3(0.0, 1.0, 0.0) : calcNormal(p);
        vec3 V = -rd;
        float ao = calcAO(p, N);

        // Primary key & rim directional lights aligned with studio softboxes
        vec3 keyL, keyCol, rimL, rimCol;
        if (uLightMode == 0) {
            keyL   = normalize(vec3(-0.35, 0.86, 0.36));
            keyCol = vec3(1.50, 1.48, 1.44);
            rimL   = normalize(vec3(0.76, 0.48, -0.44));
            rimCol = vec3(0.85, 0.94, 1.10);
        } else if (uLightMode == 1) {
            keyL   = normalize(vec3(-0.35, 0.86, 0.36));
            keyCol = vec3(1.55);
            rimL   = normalize(vec3(0.76, 0.48, -0.44));
            rimCol = vec3(0.95);
        } else if (uLightMode == 2) {
            keyL   = normalize(vec3(0.94, 0.22, 0.28));
            keyCol = vec3(2.25, 2.12, 1.95);
            rimL   = normalize(vec3(-0.65, 0.32, -0.68));
            rimCol = vec3(0.55, 0.62, 0.74);
        } else {
            keyL   = normalize(vec3(-0.18, 0.38, -0.91));
            keyCol = vec3(2.40, 2.52, 2.75);
            rimL   = normalize(vec3(0.78, 0.45, -0.42));
            rimCol = vec3(0.95, 1.05, 1.25);
        }

        // Rule (3): Hero-only soft shadow with bias p + N * 0.014
        float shKey = softShadow(p + N * 0.014, keyL, 6.0, 12.0);
        float shRim = softShadow(p + N * 0.014, rimL, 6.0, 10.0);

        if (isBench) {
            // Dark anodized matte slate studio bench with subtle micro-grain
            float g1 = valueNoise(p.xz * 26.0);
            float g2 = valueNoise(p.xz * 110.0);
            float grain = g1 * 0.65 + g2 * 0.35;

            vec3 benchBase = vec3(0.044, 0.047, 0.054) * (0.88 + 0.22 * grain);
            if (uLightMode == 1) {
                benchBase = vec3(0.056 * (0.90 + 0.18 * grain));
            }
            float rough = mix(0.42, 0.56, grain);
            vec3 F0 = vec3(0.04);

            vec3 direct = shadeDirectLight(N, V, keyL, keyCol, benchBase, 0.0, rough, F0) * shKey;
            direct += shadeDirectLight(N, V, rimL, rimCol, benchBase, 0.0, rough, F0) * shRim;

            // Environment reflection & ambient bounce
            vec3 R = reflect(-V, N);
            vec3 envSpec = evalStudioEnv(R, uLightMode);
            vec3 envDiff = evalStudioEnv(N, uLightMode);
            vec3 F = F_Schlick(max(dot(N, V), 0.0), F0);

            vec3 lit = direct + benchBase * envDiff * 0.55 * ao + envSpec * F * (1.0 - rough) * 0.55 * ao;

            // Subtle studio spotlight pool centered on the module
            float pool = exp(-dot(p.xz, p.xz) * 0.16);
            lit *= mix(0.55, 1.08, pool);

            // Subtle OLED display bounce spill onto nearby bench (muted in mode 1)
            if (uLightMode != 1) {
                vec3 ql = toLocal(p);
                float dMod = sdRoundBox2D(ql.xz, CHASSIS_HALF, CHASSIS_R);
                float spill = exp(-max(dMod, 0.0) * 3.8) * 0.045;
                vec3 spillTint = mix(vec3(0.35, 0.55, 0.72), vec3(0.35, 0.85, 0.98), smoothstep(0.0, 1.0, uOpen));
                lit += spillTint * spill;
            }

            // Distance fog into studio cyclorama
            float fog = 1.0 - exp(-t * t * 0.0085);
            vec3 bgCol = evalStudioEnv(rd, uLightMode);
            col = mix(lit, bgCol, clamp(fog, 0.0, 0.85));
        } else {
            vec3 q = toLocal(p);
            vec3 rdLocal = vecToLocal(rd);

            if (matId == 1) {
                // Precision-machined bead-blasted titanium / anodized dark aluminum frame
                float micro = valueNoise(q.xz * 180.0 + q.y * 220.0);
                vec3 baseCol = vec3(0.145, 0.152, 0.168) * (0.93 + 0.14 * micro);
                float metallic = 0.88;
                float rough = 0.24 + 0.05 * micro;

                // Subtle dark polymer antenna break bands along the perimeter rails
                float antBand = smoothstep(0.012, 0.008, abs(abs(q.x) - 0.78)) * step(0.46, abs(q.z));
                if (antBand > 0.5) {
                    baseCol = vec3(0.055, 0.058, 0.064);
                    metallic = 0.10;
                    rough = 0.36;
                }

                if (uLightMode == 1) {
                    baseCol = vec3(dot(baseCol, vec3(0.2126, 0.7152, 0.0722)) * 1.15);
                }

                vec3 F0 = mix(vec3(0.04), baseCol, metallic);
                vec3 direct = shadeDirectLight(N, V, keyL, keyCol, baseCol, metallic, rough, F0) * shKey;
                direct += shadeDirectLight(N, V, rimL, rimCol, baseCol, metallic, rough, F0) * shRim;

                vec3 R = reflect(-V, N);
                vec3 envSpec = evalStudioEnv(R, uLightMode);
                vec3 envDiff = evalStudioEnv(N, uLightMode);
                vec3 F = F_Schlick(max(dot(N, V), 0.0), F0);

                col = direct + baseCol * (1.0 - metallic) * envDiff * 0.45 * ao
                             + envSpec * F * mix(0.85, 0.45, rough) * ao;
            } else if (matId == 2) {
                // Dark rubberized contact gasket under chassis
                vec3 baseCol = vec3(0.032, 0.034, 0.038);
                if (uLightMode == 1) baseCol = vec3(0.045);
                vec3 direct = shadeDirectLight(N, V, keyL, keyCol, baseCol, 0.0, 0.65, vec3(0.03)) * shKey;
                col = direct + baseCol * evalStudioEnv(N, uLightMode) * 0.45 * ao;
            } else {
                // Glossy 2.5D Beveled Cover Glass over Emissive PenTile OLED Matrix
                float NoV = max(dot(N, V), 0.001);
                vec3 F0_glass = vec3(0.043); // Aluminosilicate glass IOR ~1.52
                vec3 F_glass = F_Schlick(NoV, F0_glass);

                // Compute refracted ray inside cover glass for optical parallax
                vec3 Nlocal = vecToLocal(N);
                vec3 rdInLocal = refract(rdLocal, Nlocal, 1.0 / 1.52);

                // Check if on top flat face vs 2.5D curved perimeter bevel
                float topFaceMask = smoothstep(0.86, 0.985, Nlocal.y);

                // Evaluate PenTile OLED matrix beneath cover glass
                OledSample oled = evalPenTileOLED(q.xz, rdInLocal, uOpen);

                // Under-glass substrate: jet-black ceramic bezel + ultra-deep black OLED matrix
                float dDisp = sdRoundBox2D(q.xz + rdInLocal.xz * (GLASS_THICK / max(-rdInLocal.y, 0.28)), DISP_HALF, DISP_R);
                float inDisplay = 1.0 - smoothstep(-0.003, 0.003, dDisp);

                // Front punch-hole camera lens assembly in left-center active bezel region
                vec2 camPos = vec2(-0.885, 0.0);
                float dCam = length(q.xz - camPos);
                float camRing = 1.0 - smoothstep(0.022, 0.025, dCam);
                float camLens = 1.0 - smoothstep(0.011, 0.013, dCam);

                // Base dark substrate under the glass
                vec3 underBase = mix(vec3(0.018, 0.020, 0.024), vec3(0.010, 0.011, 0.014), inDisplay);

                // Subtle visible metallic TFT subpixel matrix structure (reads cleanly in mode 1 & grazing)
                float matrixSheen = oled.subpixelTopo;
                if (uLightMode == 1) {
                    // Pure neutral grayscale: emission muted so glass/bezel/matrix structure reads cleanly
                    underBase = mix(vec3(0.055), vec3(0.028 + 0.095 * matrixSheen), inDisplay);
                } else {
                    underBase += vec3(0.008, 0.010, 0.014) * matrixSheen * inDisplay;
                }

                // Punch-hole camera dark sapphire + subtle AR blue-violet glint
                if (camRing > 0.01) {
                    oled.emission *= (1.0 - camRing);
                    vec3 lensCol = (uLightMode == 1) ? vec3(0.025) : vec3(0.012, 0.018, 0.042);
                    underBase = mix(underBase, lensCol, camRing);
                    if (camLens > 0.01 && uLightMode != 1) {
                        float arGlint = pow(max(dot(reflect(-V, N), keyL), 0.0), 24.0);
                        underBase += vec3(0.12, 0.18, 0.55) * arGlint * camLens;
                    }
                }

                // Diffuse + subtle internal scatter on under-glass substrate
                vec3 underLit = shadeDirectLight(N, V, keyL, keyCol, underBase, 0.05, 0.34, vec3(0.04)) * shKey;
                underLit += shadeDirectLight(N, V, rimL, rimCol, underBase, 0.05, 0.34, vec3(0.04)) * shRim;
                underLit += underBase * evalStudioEnv(N, uLightMode) * 0.42 * ao;

                // Subtle glass edge internal light-piping along the 2.5D curved bevel
                float bevelMask = 1.0 - topFaceMask;
                vec3 bevelTint = (uLightMode == 1) ? vec3(0.18) : vec3(0.09, 0.14, 0.15);
                underLit += bevelTint * bevelMask * (0.25 + 0.55 * pow(1.0 - NoV, 2.5));

                // Emissive PenTile subpixel light transmitted out through cover glass
                vec3 emission = oled.emission * topFaceMask * (1.0 - F_glass);
                if (uLightMode == 1) {
                    // Mute emission in grayscale structural inspection mode
                    emission = vec3(0.0);
                } else if (uLightMode == 2 || uLightMode == 3) {
                    // Slightly temper emission in grazing/backlit so studio rim & bevel stay dramatic
                    emission *= 0.85;
                }

                // Crisp studio softbox reflection on glossy oleophobic cover glass
                vec3 R = reflect(-V, N);
                vec3 envSharp = evalStudioEnv(R, uLightMode);
                vec3 envBroad = evalStudioEnv(normalize(mix(R, N, 0.18)), uLightMode);
                vec3 glassSpec = mix(envSharp, envBroad, 0.14) * F_glass;

                // Direct specular highlight from key & rim softboxes
                vec3 directSpec = shadeDirectLight(N, V, keyL, keyCol, vec3(0.0), 0.0, 0.045, F0_glass) * shKey;
                directSpec += shadeDirectLight(N, V, rimL, rimCol, vec3(0.0), 0.0, 0.055, F0_glass) * shRim;

                col = underLit * (1.0 - F_glass) + emission + glassSpec * 1.15 + directSpec * 0.65;
            }
        }
    }

    // Subtle photographic vignette (gentle, keeps corners well above black)
    float vig = 1.0 - 0.16 * dot(uv, uv);
    col *= clamp(vig, 0.78, 1.0);

    // Pure neutral grayscale enforcement for uLightMode == 1
    if (uLightMode == 1) {
        col = vec3(dot(col, vec3(0.2126, 0.7152, 0.0722)));
    }

    // ACES Filmic Tone Mapping + sRGB gamma (calibrated for hero lum 10..246, 0% black/clipped)
    col = acesToneMap(col * 0.96);
    col = clamp(col, vec3(0.004), vec3(0.945));
    col = pow(col, vec3(1.0 / 2.2));

    fragColor = vec4(col, 1.0);
}

Mathematical models & shader specifications

Identifieroled-subpixel-matrix
CategorySci-Fi, Plasma & Noise Shaders · Sci-Fi & Micro-Optics
Upstream studyelectronics/lib/01_rgb_oled_pentile_subpixel_matrix.glsl (commit 14ad58d)
Animation cycleContinuous procedural uTime
Declared uniformsuResolution, uTime, uOpen, uLightMode, uCamMode
Source size853 lines · 33.6 KB standalone GLSL ES 3.00
PNG baker outputs512px · 1024px · 2048px RGBA8 (4-tap seamless + alpha key)
Companion pixel VFXFree MIT scifi sprite sheets
LicenseMIT License + CC0 / MIT Helpers

Physical & shading models implemented

GGX microfacet specular (Trowbridge–Reitz 1975; Walter et al. 2007); Schlick Fresnel reflectance (1994); Beer–Lambert volumetric absorption/attenuation

Adapted upstream mathematical helpers

Krzysztof Narkowicz, filmic curve · Inigo Quilez, tetrahedral SDF normal

All sci-fi & noise shaders