<?php

require_once 'vendor/autoload.php';

use Doom\Image\Renderer;
use Doom\Wad\File as WadFile;
use Shufflingpixels\IO\BinaryReader;
use Shufflingpixels\IO\File;
use Shufflingpixels\IO\FileMode;

$file = File::open("./data/test.wad", FileMode::READ);
$wad = WadFile::parse(BinaryReader::stream($file));

$patchNames = $wad->pNames();
if ($patchNames === null) {
    throw new RuntimeException('PNAMES lump was not found in WAD file.');
}

if (!is_dir('output/patches')) {
    mkdir('output/patches', 0o0777, true);
}

if (!is_dir('output/textures')) {
    mkdir('output/textures', 0o0777, true);
}

$renderer = new Renderer();
$pictureRenderer = $renderer->createPicture();

foreach ($patchNames as $patchName) {
    $patch = $wad->firstLumpByName($patchName);
    if ($patch === null) {
        echo sprintf("Skipping patch %s (missing lump)\n", $patchName);
        continue;
    }

    echo sprintf("Rendering patch %s\n", $patchName);
    $pictureRenderer->render($patch->asPicture())->save(sprintf("output/patches/%s.png", $patchName));
}

$textures = $wad->resolveTextures();

foreach ($textures as $texture) {
    $canvas = $renderer->createTexture($texture->width, $texture->height);

    foreach ($texture->patches as $patch) {
        if ($patch->patchName === null) {
            continue;
        }

        $patchPath = sprintf('output/patches/%s.png', $patch->patchName);
        if (!is_file($patchPath)) {
            echo sprintf("Skipping patch %s for texture %s (no PNG)\n", $patch->patchName, $texture->name);
            continue;
        }

        $canvas->blit($patchPath, $patch->originX, $patch->originY);
    }

    echo sprintf("Rendering texture %s\n", $texture->name);
    $canvas->image()->save(sprintf('output/textures/%s.png', $texture->name));
}
