KO
games/alis / src / Hd / HdRenderer.php · commit 9c722cf
<?phpnamespace App\Hd;use App\Alis\Lang\Names;use App\Alis\HdSprites;use App\Alis\SysVars;use JumPHP\Gl\WebGl;use JumPHP\Renderer\Renderer;use JumPHP\Renderer\Sdl;/** * The HD edition's picture: the VM's 320 x 200 frame scaled to the window's pixels by the GPU (OpenGL on the * desktop, WebGL in the browser) as sharp pixels: each pixel of the game a square of its colour, its border mixed * over one screen pixel (an edge-directed filter, xBR, smeared the dithered pictures of the game: the marble, the * landscapes). The 3D and the texts are drawn again at the screen's resolution over it (fn/hd3d.php, fn/hd.php). * * The texts: the characters of the game's font are not in that picture (fn/hd.php takes them out and lists them, * SysVars::$hdShown); they are drawn over it, after the filter, with a real font (assets/fonts/hd.ttf) at the * window's resolution: same place, same height, the font's colour (and its shadow or its paper). */final class HdRenderer{    /**     * GLSL ES 1.00 post shader (JumPHP WebGl): u_frame = the picture scaled to the window, u_src = the size of the     * VM's frame stretched over the whole view (320 x 200 shown in a 320 x 240 view: its own grid, not the view's).     */    public const SHADER = <<<'GLSL'        uniform float u_strength;        uniform vec2 u_src;        vec3 px(vec2 cell) {            // the centre of a pixel of the game's picture (it was scaled to the window by whole or uneven factors)            return texture2D(u_frame, (cell + 0.5) / u_src).rgb;        }        void main() {            // sharp pixels: each pixel of the game is a square of one colour (no blur, nothing smeared), only its            // border is mixed with its neighbour over one screen pixel (even squares at any scale, no jagged rows)            vec2 p = v_uv * u_src;            vec2 cell = floor(p);            vec2 d = p - cell - 0.5;            vec2 side = vec2(d.x < 0.0 ? -1.0 : 1.0, d.y < 0.0 ? -1.0 : 1.0);            vec2 aa = u_src / u_resolution * u_strength;          // one screen pixel, in game pixels            vec2 w = clamp((abs(d) - 0.5 + aa * 0.5) / max(aa, vec2(1e-4)), 0.0, 0.5);            vec3 c = mix(mix(px(cell), px(cell + vec2(side.x, 0.0)), w.x),                         mix(px(cell + vec2(0.0, side.y)), px(cell + side), w.x), w.y);            gl_FragColor = vec4(c, 1.0);        }        GLSL;    private bool $on = false;    private ?int $overlay = null;    private ?Renderer $renderer = null;    /** @var array<int, \TTF_Font> point size => the font */    private array $fonts = [];    /** height of a capital (H) for 1 point of the font */    private float $capRatio = 0.72;    /** @var array<string, array{0: mixed, 1: int, 2: int, 3: float, 4: int}> glyph textures: texture, w, h, ink centre x, ascent (LRU) */    private array $glyphs = [];    /** @var array<int, array{0: int, 1: int}> font of the game => [top, bottom] rows of its capitals */    private array $caps = [];    private const GLYPH_CACHE = 600;    public function __construct(private WebGl $gl, private ?Sdl $sdl = null, private string $fontPath = '')    {    }    /** The texts in a real font (works without OpenGL too): fn/hd.php lists the characters, an overlay draws them. */    public function enableText(): void    {        if ($this->sdl === null || $this->fontPath === '' || !is_file($this->fontPath) || $this->overlay !== null) {            return;        }        if (!\TTF_WasInit()) {            \TTF_Init();        }        $this->renderer = $this->sdl->getRenderer();        SysVars::$hdText = true;        SysVars::$hdGlyphs = SysVars::$hdShown = [];        $this->overlay = $this->renderer->addOverlay(function (Renderer $r): void {            $this->drawLand($r);            $this->drawSprites($r);            $this->drawText($r);        });    }    /** The 3D at twice the resolution too (fn/hd3d.php): the land drawn again by the original renderer. */    public function enable3d(): void    {        \App\Alis\Hd3d::$on = true;        \App\Alis\Hd3d::$land = null;        \App\Alis\Hd3d::$slow = [];        // measured again (App\Alis\Hd3d::spent())        \App\Alis\Hd3d::$pending = null;    }    /** The game's pictures from the sprite pack (App\Alis\HdSprites): bigger versions drawn over the scaled picture. */    public function enableSprites(string $dataDir): void    {        HdSprites::reset();        HdSprites::$pack = null;        HdSprites::$dir = $dataDir;        HdSprites::$on = true;        HdSprites::loadPack();    }    /** @var array<string, mixed> key => texture (false: none) */    private array $spriteTextures = [];    private const SPRITE_TEXTURES = 160;    private function spriteTexture(mixed $sdl, string $key): mixed    {        if (array_key_exists($key, $this->spriteTextures)) {            $t = $this->spriteTextures[$key];            if ($t !== null) {                unset($this->spriteTextures[$key]);     // most recent last                $this->spriteTextures[$key] = $t;                return $t;            }        }        $path = HdSprites::file($key . '.png');        if ($path === null) {            return false;                              // not here yet        }        $surface = \IMG_Load($path);        $texture = $surface ? \SDL_CreateTextureFromSurface($sdl, $surface) : false;        if ($surface) {            \SDL_FreeSurface($surface);        }        if (count($this->spriteTextures) >= self::SPRITE_TEXTURES) {            $old = reset($this->spriteTextures);            if ($old) {                \SDL_DestroyTexture($old);            }            unset($this->spriteTextures[array_key_first($this->spriteTextures)]);        }        $this->spriteTextures[$key] = $texture ?: false;        return $texture ?: false;    }    /** The tiles HdSprites found still on the screen, from the bigger pictures (window pixels). */    private function drawSprites(Renderer $r): void    {        if (!HdSprites::$on) {            return;        }        HdSprites::loadPack();        $fw = SysVars::$frameW;        $fh = SysVars::$frameH;        if (HdSprites::$shown === [] || $fw <= 0 || $fh <= 0) {            return;        }        [$lx, $ly, $lw, $lh] = $r->letterbox();        $sx = $lw / $fw;        $sy = $lh / $fh;        $sdl = $r->getRenderer();        foreach (HdSprites::$shown as $s) {            $t = $this->spriteTexture($sdl, $s['key']);            if (!$t) {                continue;            }            $tw = $th = 0;            $format = $access = 0;            \SDL_QueryTexture($t, $format, $access, $tw, $th);            $kx = $tw / $s['w'];            $ky = $th / $s['h'];            foreach ($s['tiles'] as [$x1, $y1, $x2, $y2]) {                $u1 = $s['flip'] ? $s['x'] + $s['w'] - $x2 : $x1 - $s['x'];                $v1 = $y1 - $s['y'];                $src = new \SDL_Rect((int) round($u1 * $kx), (int) round($v1 * $ky), (int) round(($x2 - $x1) * $kx), (int) round(($y2 - $y1) * $ky));                $dx1 = (int) round($lx + $x1 * $sx);                $dy1 = (int) round($ly + $y1 * $sy);                $dst = new \SDL_Rect($dx1, $dy1, (int) round($lx + $x2 * $sx) - $dx1, (int) round($ly + $y2 * $sy) - $dy1);                if ($s['flip']) {                    \SDL_RenderCopyEx($sdl, $t, $src, $dst, 0.0, null, \SDL_FLIP_HORIZONTAL);                } else {                    \SDL_RenderCopy($sdl, $t, $src, $dst);                }            }        }    }    private mixed $landTexture = null;    private int $landFrame = -1;    /** The HD land over the picture (its pixels the VM drew over are transparent: they stay as they are). */    private function drawLand(Renderer $r): void    {        $land = SysVars::$hdLand;        $fw = SysVars::$frameW;        $fh = SysVars::$frameH;        if ($land === null || $fw <= 0 || $fh <= 0) {            return;        }        $sdl = $r->getRenderer();        if ($this->landFrame !== SysVars::$frameCount || $this->landTexture === null) {            $this->landFrame = SysVars::$frameCount;            if ($this->landTexture !== null) {                \SDL_DestroyTexture($this->landTexture);                $this->landTexture = null;            }            $rw = \SDL_RWFromConstMem($land['bmp'], strlen($land['bmp']));            $surface = \SDL_LoadBMP_RW($rw, 1);            if (!$surface) {                return;            }            if ($land['key'] >= 0) {                \SDL_SetColorKey($surface, 1, $land['key']);            }            $this->landTexture = \SDL_CreateTextureFromSurface($sdl, $surface) ?: null;            \SDL_FreeSurface($surface);        }        if ($this->landTexture === null) {            return;        }        [$lx, $ly, $lw, $lh] = $r->letterbox();        $x1 = (int) round($lx + $land['x'] * $lw / $fw);        $y1 = (int) round($ly + $land['y'] * $lh / $fh);        $x2 = (int) round($lx + ($land['x'] + $land['w']) * $lw / $fw);        $y2 = (int) round($ly + ($land['y'] + $land['h']) * $lh / $fh);        \SDL_RenderCopy($sdl, $this->landTexture, null, new \SDL_Rect($x1, $y1, $x2 - $x1, $y2 - $y1));    }    /** Draws the listed characters over the scaled picture (window pixels: the overlay runs after the filter). */    private function drawText(Renderer $r): void    {        $shown = SysVars::$hdShown;        $fw = SysVars::$frameW;        $fh = SysVars::$frameH;        if ($shown === [] || $fw <= 0 || $fh <= 0) {            return;        }        [$lx, $ly, $lw, $lh] = $r->letterbox();        $sx = $lw / $fw;        $sy = $lh / $fh;        $sdl = $r->getRenderer();        // the capitals of each font: where its letters sit (baseline) and how tall they are        foreach ($shown as $g) {            if ($g['char'] >= 0x41 && $g['char'] <= 0x5a && $g['bottom'] >= $g['top']) {                $c = $this->caps[$g['font']] ?? [$g['top'], $g['bottom']];                $this->caps[$g['font']] = [min($c[0], $g['top']), max($c[1], $g['bottom'])];            }        }        foreach ($shown as $g) {            [$top, $bottom] = $this->caps[$g['font']] ?? [$g['top'], $g['bottom']];            if ($bottom < $top) {                continue;            }            if ($g['paper'] !== null) {                [$pr, $pg, $pb] = $g['paper'];                \SDL_SetRenderDrawColor($sdl, $pr, $pg, $pb, 255);                \SDL_RenderFillRect($sdl, new \SDL_Rect((int) round($lx + $g['x'] * $sx), (int) round($ly + $g['y'] * $sy),                    (int) ceil($g['w'] * $sx), (int) ceil($g['h'] * $sy)));            }            if ($g['char'] === 0x20 || $g['ink'] === null || $g['right'] < $g['left']) {                continue;            }            $text = $g['char'] < 0x80 ? chr($g['char']) : (Names::cp437()[$g['char']] ?? '?');            $pt = max(4, (int) round(($bottom - $top + 1) * $sy / $this->capRatio));            $cx = $lx + ($g['x'] + ($g['left'] + $g['right'] + 1) / 2) * $sx;            $base = $ly + ($g['y'] + $bottom + 1) * $sy;            if ($g['shadow'] !== null) {                $this->glyph($sdl, $text, $pt, $g['shadow'], $cx + $sx, $base + $sy);            }            $this->glyph($sdl, $text, $pt, $g['ink'], $cx, $base);        }    }    /** One character, its ink centred on $cx, its baseline on $base (window pixels). */    private function glyph(mixed $sdl, string $text, int $pt, array $rgb, float $cx, float $base): void    {        $key = $pt . '|' . implode(',', $rgb) . '|' . $text;        $t = $this->glyphs[$key] ?? null;        if ($t === null) {            $font = $this->font($pt);            if ($font === null) {                return;            }            $surface = \TTF_RenderUTF8_Blended($font, $text, new \SDL_Color($rgb[0], $rgb[1], $rgb[2], 255));            if (!$surface) { // @phpstan-ignore booleanNot.alwaysFalse (the binding returns false on failure)                return;            }            $texture = \SDL_CreateTextureFromSurface($sdl, $surface);            $w = (int) $surface->w;            $h = (int) $surface->h;            \SDL_FreeSurface($surface);            if (!$texture) {                return;            }            $minx = $maxx = $miny = $maxy = $adv = 0;            $centre = $w / 2;            if (strlen($text) === 1 && \TTF_GlyphMetrics($font, \ord($text), $minx, $maxx, $miny, $maxy, $adv) === 0) {                $centre = ($minx + $maxx) / 2;            }            if (count($this->glyphs) >= self::GLYPH_CACHE) {                \SDL_DestroyTexture(reset($this->glyphs)[0]);                unset($this->glyphs[array_key_first($this->glyphs)]);            }            $t = [$texture, $w, $h, $centre, \TTF_FontAscent($font)];        } else {            unset($this->glyphs[$key]);       // most recent last        }        $this->glyphs[$key] = $t;        \SDL_RenderCopy($sdl, $t[0], null, new \SDL_Rect((int) round($cx - $t[3]), (int) round($base - $t[4]), $t[1], $t[2]));    }    private function font(int $pt): ?\TTF_Font    {        if (!isset($this->fonts[$pt])) {            if (count($this->fonts) > 12) {                foreach ($this->fonts as $f) {                    \TTF_CloseFont($f);                }                $this->fonts = [];            }            $font = \TTF_OpenFont($this->fontPath, $pt);            if (!$font) { // @phpstan-ignore booleanNot.alwaysFalse (the binding returns false on failure)                return null;            }            if ($this->fonts === [] && $this->capRatio === 0.72) {                $minx = $maxx = $miny = $maxy = $adv = 0;                if (\TTF_GlyphMetrics($font, \ord('H'), $minx, $maxx, $miny, $maxy, $adv) === 0 && $maxy > 0) {                    $this->capRatio = $maxy / $pt;                }            }            $this->fonts[$pt] = $font;        }        return $this->fonts[$pt];    }    public function isAvailable(): bool    {        return $this->gl->isAvailable();    }    /** Turns the HD picture on (the post shader at the window's resolution, over the scaled 2D). */    public function enable(): bool    {        if (!$this->gl->isAvailable()) {            return false;        }        // an empty layer above the 2D, at the window's resolution: the post shader then runs on the window's pixels        $this->gl->setLayer('above', 'native', [255, 0, 255]);   // 'above': the key is not used        $this->gl->setPostShader(self::SHADER, ['u_strength' => 1.0, 'u_src' => [320.0, 200.0]]);        $this->on = true;        return true;    }    /** The size of the VM's frame (it changes with the game: 320 x 200, 320 x 240 films...). */    public function source(int $w, int $h): void    {        if ($this->on && $w > 0 && $h > 0 && [$w, $h] !== $this->size) {            $this->size = [$w, $h];            $this->gl->setUniform('u_src', [(float) $w, (float) $h]);        }    }    /** @var array{0: int, 1: int} */    private array $size = [320, 200];    public function disable(): void    {        if ($this->on) {            $this->gl->disable();            $this->on = false;        }        if ($this->overlay !== null) {            $this->renderer?->removeOverlay($this->overlay);            $this->overlay = null;        }        foreach ($this->glyphs as $t) {            \SDL_DestroyTexture($t[0]);        }        $this->glyphs = [];        if ($this->landTexture !== null) {            \SDL_DestroyTexture($this->landTexture);            $this->landTexture = null;        }        \App\Alis\Hd3d::$on = false;        \App\Alis\Hd3d::$land = null;        HdSprites::$on = false;        HdSprites::reset();        foreach ($this->spriteTextures as $t) {            if ($t) {                \SDL_DestroyTexture($t);            }        }        $this->spriteTextures = [];        SysVars::$hdLand = null;        foreach ($this->fonts as $f) {            \TTF_CloseFont($f);        }        $this->fonts = [];        SysVars::$hdText = false;        SysVars::$hdGlyphs = SysVars::$hdShown = [];    }    public function isOn(): bool    {        return $this->on;    }}