File size: 2,718 Bytes
790d9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Material package caching: key generation, lookup, and build."""

import hashlib
import json
from pathlib import Path

from PIL import Image

from config.paths import MATERIAL_DIR
from services.image.loading import load_tile_image
from services.materials.generator import (
    MATERIAL_GENERATOR_VERSION,
    generate_tile_material_maps,
)


def material_cache_key(contents: bytes, base_roughness: float) -> str:
    digest = hashlib.sha256()
    digest.update(MATERIAL_GENERATOR_VERSION.encode("utf-8"))
    digest.update(f":{float(base_roughness):.4f}:".encode("utf-8"))
    digest.update(contents)
    return digest.hexdigest()[:32]


def material_package_from_cache(cache_key: str) -> dict | None:
    metadata_path = MATERIAL_DIR / cache_key / "metadata.json"
    if not metadata_path.exists():
        return None
    try:
        metadata = json.loads(metadata_path.read_text())
    except Exception:
        return None
    maps = material_map_urls(cache_key)
    if not all((MATERIAL_DIR / cache_key / Path(url).name).exists() for url in maps.values()):
        return None
    return {
        "id": cache_key,
        "cached": True,
        "maps": maps,
        "metadata": metadata,
    }


def build_tile_material_package(contents: bytes, base_roughness: float = 0.42) -> dict:
    cache_key = material_cache_key(contents, base_roughness)
    cached = material_package_from_cache(cache_key)
    if cached is not None:
        return cached

    img_np = load_tile_image(contents)
    maps, metadata = generate_tile_material_maps(img_np, base_roughness)
    package_dir = MATERIAL_DIR / cache_key
    package_dir.mkdir(parents=True, exist_ok=True)
    filenames = {
        "albedoMap": "albedo.png",
        "normalMap": "normal.png",
        "heightMap": "height.png",
        "roughnessMap": "roughness.png",
        "aoMap": "ao.png",
        "specularMap": "specular.png",
    }
    for key, filename in filenames.items():
        Image.fromarray(maps[key]).save(package_dir / filename, format="PNG", optimize=True)
    metadata_path = package_dir / "metadata.json"
    metadata_path.write_text(json.dumps(metadata))
    return {
        "id": cache_key,
        "cached": False,
        "maps": material_map_urls(cache_key),
        "metadata": metadata,
    }


def material_map_urls(cache_key: str) -> dict[str, str]:
    return {
        "albedoMap": f"/materials/{cache_key}/albedo.png",
        "normalMap": f"/materials/{cache_key}/normal.png",
        "heightMap": f"/materials/{cache_key}/height.png",
        "roughnessMap": f"/materials/{cache_key}/roughness.png",
        "aoMap": f"/materials/{cache_key}/ao.png",
        "specularMap": f"/materials/{cache_key}/specular.png",
    }