Spaces:
Paused
Paused
File size: 2,882 Bytes
1fe7075 | 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 | """Procedural PBR material map generation from tile images."""
import cv2
import numpy as np
MATERIAL_GENERATOR_VERSION = "opencv-procedural-pbr-v1"
MATERIAL_MAX_DIMENSION = 1024
def limit_material_image_size(img_np: np.ndarray, max_dimension: int = MATERIAL_MAX_DIMENSION) -> np.ndarray:
h, w = img_np.shape[:2]
largest = max(h, w)
if largest <= max_dimension:
return img_np
scale = max_dimension / float(largest)
new_w = max(1, int(round(w * scale)))
new_h = max(1, int(round(h * scale)))
return cv2.resize(img_np, (new_w, new_h), interpolation=cv2.INTER_AREA)
def generate_tile_material_maps(img_np: np.ndarray, base_roughness: float = 0.42) -> tuple[dict[str, np.ndarray], dict]:
albedo = limit_material_image_size(img_np)
rgb = albedo.astype(np.float32) / 255.0
height = (
rgb[:, :, 0] * 0.299 +
rgb[:, :, 1] * 0.587 +
rgb[:, :, 2] * 0.114
).astype(np.float32)
h_min = float(np.min(height))
h_max = float(np.max(height))
height = np.clip((height - h_min) / max(h_max - h_min, 1e-3), 0.0, 1.0)
height_smooth = cv2.GaussianBlur(height, (3, 3), 0)
dx = np.roll(height_smooth, -1, axis=1) - np.roll(height_smooth, 1, axis=1)
dy = np.roll(height_smooth, -1, axis=0) - np.roll(height_smooth, 1, axis=0)
edge = np.clip((np.abs(dx) + np.abs(dy)) * 3.5, 0.0, 1.0)
normal_strength = 3.0
nx = -dx * normal_strength
ny = -dy * normal_strength
nz = np.ones_like(height_smooth)
norm = np.maximum(np.sqrt(nx * nx + ny * ny + nz * nz), 1e-4)
normal = np.dstack((
(nx / norm) * 0.5 + 0.5,
(ny / norm) * 0.5 + 0.5,
(nz / norm) * 0.5 + 0.5,
))
roughness_base = float(np.clip(base_roughness, 0.04, 0.96))
roughness = np.clip(roughness_base + edge * 0.34 + (0.5 - height_smooth) * 0.16, 0.04, 0.98)
ao = np.clip(0.74 + height_smooth * 0.26 - edge * 0.28, 0.45, 1.0)
specular = np.clip((1.0 - roughness) * 0.72 + height_smooth * 0.22, 0.02, 1.0)
maps = {
"albedoMap": albedo,
"normalMap": float_to_rgb8(normal),
"heightMap": gray_to_rgb8(height_smooth),
"roughnessMap": gray_to_rgb8(roughness),
"aoMap": gray_to_rgb8(ao),
"specularMap": gray_to_rgb8(specular),
}
metadata = {
"generator": MATERIAL_GENERATOR_VERSION,
"generatedKinds": ["normalMap", "heightMap", "roughnessMap", "aoMap", "specularMap"],
"width": int(albedo.shape[1]),
"height": int(albedo.shape[0]),
"baseRoughness": roughness_base,
}
return maps, metadata
def float_to_rgb8(values: np.ndarray) -> np.ndarray:
return np.clip(values * 255.0, 0, 255).round().astype(np.uint8)
def gray_to_rgb8(values: np.ndarray) -> np.ndarray:
gray = np.clip(values * 255.0, 0, 255).round().astype(np.uint8)
return np.dstack((gray, gray, gray))
|