Caffeine

7.6 — Import PNG (Heightmap Grayscale)

Historical Fase: 12 · **Prioridade:** Média · **Esforço:** Baixo Last updated:
> **Depende de:** Fase 4 (`.cterrain`), opcionalmente 7.4 (undo) > **Biblioteca:** `stb_image` (já usada no projeto)

Objetivo#

Importar imagens grayscale (PNG, JPG) como heightmap — permitir edição externa no GIMP/Krita/World Machine e reimportação para o Caffeine.


Módulo#

cpp
class HeightmapImportModule final : public ITerrainGeneratorModule {
public:
    const char* name() const override { return "Heightmap Import"; }
    void apply(TerrainGeneratorContext& ctx) override;

    std::string sourcePath;   // project-relative ou engine asset
    bool normalizeToFullRange = true;
    bool invert = false;
    f32 heightScale = 1.0f;     // multiplicador após normalizar
    f32 heightOffset = 0.0f;
};

Fluxo#

text
1. Resolver path (MeshCache::buildCandidatePaths + EditorPaths)
2. stbi_load(path) → RGBA ou grayscale
3. Converter para f32 [0,1]:
     - R channel (ou luminância) / 255
     - opcional: invert → 1 - h
     - opcional: normalize min-max para usar range completo
4. Resample se dimensões ≠ terrain.resolutionX/Z
     - bilinear resize
5. Escrever em heightmap.setNormalized(x, z, h)

Resampling#

Se PNG é 1024×1024 e terreno é 65×65:

cpp
for (u32 z = 0; z < resZ; ++z)
    for (u32 x = 0; x < resX; ++x) {
        f32 u = x / (resX - 1);
        f32 v = z / (resZ - 1);
        f32 h = sampleBilinearFromImage(image, u, v);
        heightmap.setNormalized(x, z, h);
    }

Se PNG é menor que resolução do terreno → upscale com aviso no Inspector.


UI#

Inspector — secção Import#

text
[Heightmap Image]  [Browse...]  assets/heightmaps/island.png
[ ] Invert
[ ] Normalize to full range
Height Scale:  1.0
Height Offset: 0.0
[Import Heightmap]

Asset Browser#

  • Drag & drop PNG para entidade Terrain → import automático

Combinadores (7.2)#

  • Layer tipo Imported aponta para ficheiro em vez de sub-gerador

Export (bonus)#

Botão simétrico Export Heightmap PNG — útil para round-trip com ferramentas externas.

cpp
void exportHeightmapPng(const TerrainHeightmap& hm, const std::filesystem::path& out);

Serialização#

cpp
// TerrainGenerationSettings ou campo separado
char importedHeightmapPath[256] = {};
bool useImportedHeightmap = false;

Ao carregar cena, re-importar se ficheiro existir e flag ativa.


Critérios de Aceitação#

  • [ ] Import PNG 16-bit e 8-bit funciona
  • [ ] Resize automático para resolução do terreno
  • [ ] Undo antes de import (7.4)
  • [ ] Path resolve em engine assets e projeto Chair
  • [ ] Export PNG gera imagem coerente com viewport

Formatos Suportados#

Formato Suporte
PNG 8-bit grayscale ✅
PNG 8-bit RGB (usa R) ✅
PNG 16-bit ✅ se stbi com 16-bit
RAW binário 🔜 futuro
EXR 🔜 futuro