"""Procedural, seamlessly tiling short-grain rice material. python3 make_rice_texture.py Bakes a texture set out of a 3D-ish model of a rice pile: height (the bump map) -> 16-bit PNG, the displacement source normal -> gradient of height, OpenGL and DirectX ao -> horizon march over the height field albedo -> per-grain tint darkened by AO Seamlessness comes from the source, not from post-processing: every grain is placed on a torus, and grains straddling an edge are wrapped into the opposite edge by index modulo, so the height field is exactly periodic. Filters that must not break that (blur, AO marching) wrap too. Grains are modelled as a superellipse silhouette with an elliptical dome, plus a slight bend along the length and a random tilt, unioned by max(). Shapes and sizes are drawn per grain, so the pile is not a repeated tile of one grain. """ import json import os import numpy as np from PIL import Image from scipy import ndimage as ndi OUT = "tex_proc" SIZE = 2048 # texture resolution PATCH_MM = 60.0 # real rice this square covers; sets texel density SEED = 7 # Short-grain rice: ~5 mm long, aspect ~1.8, ~2.2 mm thick. Distributions are # lognormal/normal around these medians. LENGTH_MM = 5.0 LENGTH_SIGMA = 0.13 # lognormal sigma ASPECT = 1.78 # length / width ASPECT_SIGMA = 0.09 THICKNESS_RATIO = 0.44 # thickness / length THICKNESS_SIGMA = 0.06 # Orientation. Pressed nigiri rice is not a shingled carpet: a good fraction of # grains jut out end-on, which is most of what the reference photograph reads as. FLAT_TILT_DEG = 12.0 # std dev for the grains that lie down UPRIGHT_FRACTION = 0.34 # of grains, tilted this far out of plane UPRIGHT_TILT_DEG = (30.0, 65.0) # (coverage of a monolayer, base height in mm). More layers, spaced closer than # a grain is thick, so upper grains sit on lower ones instead of forming a # second storey: the gaps are then shallow V-crevices between grains rather than # holes down to a floor. That is what keeps peak-to-valley near one grain # thickness even as the pile gets deeper. LAYERS = [(1.20, 0.00), (1.05, 0.38), (0.95, 0.76), (0.80, 1.14), (0.60, 1.50)] PACKING = 0.42 # accepted centre spacing, fraction of semi-length BLUR_TEXELS = 0.5 # soften union creases without erasing grain edges AO_DIRECTIONS = 8 AO_STEPS = 40 AO_MAX_MM = 1.6 BLUR_TEXELS = 0.7 # soften the max() creases between grains def torus_delta(delta, span): delta = np.abs(delta) return np.minimum(delta, span - delta) def scatter(rng, count, min_spacing_mm): """Poisson-disk (blue noise) centres on a torus, so packing wraps too.""" accepted = np.empty((count, 2), dtype=np.float64) found = 0 tries = 0 max_tries = count * 400 while found < count and tries < max_tries: tries += 1 candidate = rng.uniform(0.0, PATCH_MM, 2) if found: dx = torus_delta(candidate[0] - accepted[:found, 0], PATCH_MM) dy = torus_delta(candidate[1] - accepted[:found, 1], PATCH_MM) if np.hypot(dx, dy).min() < min_spacing_mm: continue accepted[found] = candidate found += 1 return accepted[:found] def draw_grain(rng, centre, base_z): """A grain as a rotated ellipsoid: three axes and a centre height. Modelling the body in 3D rather than as a dome plus a slope term is what makes an upright grain possible at all -- laid flat, its footprint is the full grain; stood on end, the footprint is its cross-section and its height is most of a grain length, which is exactly what the reference shows. """ length = LENGTH_MM * rng.lognormal(0.0, LENGTH_SIGMA) aspect = np.clip(ASPECT + rng.normal(0.0, ASPECT_SIGMA), 1.35, 2.4) thickness = length * np.clip( THICKNESS_RATIO + rng.normal(0.0, THICKNESS_SIGMA), 0.30, 0.55) semi_u, semi_v, semi_w = length / 2.0, length / aspect / 2.0, thickness / 2.0 azimuth = rng.uniform(0.0, np.pi) upright = rng.random() < UPRIGHT_FRACTION if upright: tilt = np.deg2rad(rng.uniform(*UPRIGHT_TILT_DEG)) else: tilt = np.deg2rad(abs(rng.normal(0.0, FLAT_TILT_DEG))) long_axis = np.array([np.cos(azimuth) * np.cos(tilt), np.sin(azimuth) * np.cos(tilt), np.sin(tilt)]) mid_axis = np.array([-np.sin(azimuth), np.cos(azimuth), 0.0]) short_axis = np.cross(long_axis, mid_axis) # Centres sit on the layer plane, not bottoms. Seating each grain on its # lowest point instead makes an upright grain stand a full grain-length # proud of its layer, which compounds across layers into a spike field # (peak-to-valley 9.5 mm for a 5 mm grain). Aligning centres is what # compaction does, and it bounds how far a standing grain can protrude. return { "x": centre[0], "y": centre[1], "semi_u": semi_u, "semi_v": semi_v, "semi_w": semi_w, "axes": (long_axis, mid_axis, short_axis), "centre_z": base_z + rng.uniform(-0.12, 0.12), "tilt_deg": float(np.rad2deg(tilt)), "upright": bool(upright), } def rasterise(height, owner, grain, texel_mm, grain_id): """Union one grain's top surface into the height field, wrapping at edges. For a vertical line through a texel, the grain's surface height is where that line leaves the ellipsoid, which is the larger root of a quadratic: with the local axes fixed, each local coordinate is affine in z, so the ellipsoid equation in z is quadratic. That keeps the solve exact for any orientation rather than approximating a tilted grain as a squashed dome. """ n = height.shape[0] long_axis, mid_axis, short_axis = grain["axes"] a, b, c = grain["semi_u"], grain["semi_v"], grain["semi_w"] # Exact projected bounding half-extents of a rotated ellipsoid. reach_x = np.sqrt((a * long_axis[0]) ** 2 + (b * mid_axis[0]) ** 2 + (c * short_axis[0]) ** 2) reach_y = np.sqrt((a * long_axis[1]) ** 2 + (b * mid_axis[1]) ** 2 + (c * short_axis[1]) ** 2) cx = grain["x"] / texel_mm cy = grain["y"] / texel_mm half_x = int(np.ceil(reach_x / texel_mm)) + 1 half_y = int(np.ceil(reach_y / texel_mm)) + 1 columns = np.arange(int(round(cx)) - half_x, int(round(cx)) + half_x + 1) rows = np.arange(int(round(cy)) - half_y, int(round(cy)) + half_y + 1) dx, dy = np.meshgrid((columns - cx) * texel_mm, (rows - cy) * texel_mm) # Local coordinates as (value at z=0) + (rate per unit z). u0 = long_axis[0] * dx + long_axis[1] * dy v0 = mid_axis[0] * dx + mid_axis[1] * dy w0 = short_axis[0] * dx + short_axis[1] * dy uz, vz, wz = long_axis[2], mid_axis[2], short_axis[2] quad_a = (uz / a) ** 2 + (vz / b) ** 2 + (wz / c) ** 2 quad_b = 2.0 * (u0 * uz / a ** 2 + v0 * vz / b ** 2 + w0 * wz / c ** 2) quad_c = (u0 / a) ** 2 + (v0 / b) ** 2 + (w0 / c) ** 2 - 1.0 disc = quad_b ** 2 - 4.0 * quad_a * quad_c inside = disc >= 0.0 surface = grain["centre_z"] + (-quad_b + np.sqrt(np.clip(disc, 0, None))) \ / (2.0 * quad_a) rows, columns = rows % n, columns % n block = height[np.ix_(rows, columns)] taken = inside & (surface > block) height[np.ix_(rows, columns)] = np.where(taken, surface, block) owner[np.ix_(rows, columns)] = np.where(taken, grain_id, owner[np.ix_(rows, columns)]) return grain_id + 1 def place_grains(rng): grains = [] for coverage, base_z in LAYERS: grain_area = LENGTH_MM * (LENGTH_MM / ASPECT) * 0.8 count = int(coverage * PATCH_MM ** 2 / grain_area) spacing = PACKING * LENGTH_MM / 2.0 for centre in scatter(rng, count, spacing): grains.append(draw_grain(rng, centre, base_z)) return grains FLOOR_MM = -1.0 # the un-modelled plate; must never be visible def rasterise_grains(grains, texel_mm): height = np.full((SIZE, SIZE), FLOOR_MM, dtype=np.float32) owner = np.zeros((SIZE, SIZE), dtype=np.int32) for grain_id, grain in enumerate(grains, start=1): rasterise(height, owner, grain, texel_mm, grain_id) return height, owner def uncovered_fraction(height): return float((height <= FLOOR_MM + 1e-6).mean()) def fill_gaps(height, owner, grains, rng, texel_mm, base_z=-0.35, rounds=10): """Drop grains into whatever is still floor. Nominal layer coverage is a poor proxy for whether the surface is closed: an upright grain covers a fifth of what a flat one does, so a pile with a lot of standing grains leaves holes straight down to the plate. Filling the actual remaining holes makes the surface closed by construction instead of by tuning a multiplier. """ next_id = len(grains) + 1 for _ in range(rounds): holes = height <= FLOOR_MM + 1e-6 if holes.mean() < 1e-5: break labels, count = ndi.label(holes) if count == 0: break for row, column in ndi.center_of_mass(holes, labels, np.arange(1, count + 1)): grain = draw_grain(rng, (column * texel_mm, row * texel_mm), base_z) rasterise(height, owner, grain, texel_mm, next_id) grains.append(grain) next_id += 1 return next_id def periodicity_error(grains, texel_mm): """Shift every grain by a quarter patch and require a rolled copy back. Sampling one seam line and comparing it to interior statistics is a weak test: that quantity is heavy-tailed, and across seeds it lands anywhere from the 4th to the 99th percentile even when the field is exactly periodic. Translating the whole scatter on the torus and demanding the same field, rolled, tests the property instead of sampling it. """ baseline, _ = rasterise_grains(grains, texel_mm) shift_px = SIZE // 4 shift_mm = shift_px * texel_mm moved = [dict(grain, x=(grain["x"] + shift_mm) % PATCH_MM, y=(grain["y"] + shift_mm) % PATCH_MM) for grain in grains] shifted, _ = rasterise_grains(moved, texel_mm) expected = np.roll(baseline, (shift_px, shift_px), axis=(0, 1)) return float(np.abs(shifted - expected).max()) def normals(height, texel_mm): grad_row, grad_col = np.gradient(height, texel_mm) # Rows increase downward, so +Y (up) is the negative row gradient. nx = -grad_col ny = grad_row nz = np.ones_like(height) length = np.sqrt(nx ** 2 + ny ** 2 + nz ** 2) return np.stack([nx / length, ny / length, nz / length], axis=-1) def ambient_occlusion(height, texel_mm): """Horizon-based: march each compass direction, keep the steepest slope.""" visibility = np.zeros_like(height) step = AO_MAX_MM / AO_STEPS / texel_mm for index in range(AO_DIRECTIONS): angle = 2 * np.pi * index / AO_DIRECTIONS dx, dy = np.cos(angle), np.sin(angle) steepest = np.zeros_like(height) for k in range(1, AO_STEPS + 1): distance = k * step * texel_mm sampled = np.roll(height, (int(round(dy * k * step)), int(round(dx * k * step))), axis=(0, 1)) steepest = np.maximum(steepest, (sampled - height) / distance) # 1 - sin(atan(slope)) : sky fraction still open along this direction visibility += 1.0 - steepest / np.sqrt(1.0 + steepest ** 2) return visibility / AO_DIRECTIONS def normals_to_rgb(n, directx=False): if directx: n = n * np.array([1.0, -1.0, 1.0]) return np.clip((n * 0.5 + 0.5) * 255.0 + 0.5, 0, 255).astype(np.uint8) def albedo_map(height, owner, ao, grains, rng): """Per-grain tint, so the pile is not one flat colour.""" tints = np.random.default_rng(1234).uniform( -1.0, 1.0, size=len(grains) + 2) per_grain = tints[np.clip(owner, 0, len(tints) - 1)] variation = 1.0 + 0.05 * per_grain # Milled rice is not pure white; the tips read slightly warmer. base = np.array([0.90, 0.885, 0.845]) shade = (0.55 + 0.45 * ao) * variation rgb = base[None, None, :] * shade[..., None] return np.clip(rgb * 255.0 + 0.5, 0, 255).astype(np.uint8) def seam_report(height): """Is the field actually periodic, or does it just look tiled? A ratio against the mean interior step is too crude -- the seam is a single line of pixels, so it has sampling noise of its own. Ranking the seam step within the distribution of every interior step says whether it is statistically ordinary, which is the question that matters. """ col_steps = np.abs(np.diff(height, axis=1)).mean(axis=0) row_steps = np.abs(np.diff(height, axis=0)).mean(axis=1) seam_cols = float(np.abs(height[:, 0] - height[:, -1]).mean()) seam_rows = float(np.abs(height[0, :] - height[-1, :]).mean()) col_pct = float((col_steps < seam_cols).mean() * 100.0) row_pct = float((row_steps < seam_rows).mean() * 100.0) return { "seam_cols_mm": round(seam_cols, 5), "interior_col_step_mm": round(float(col_steps.mean()), 5), "seam_cols_percentile": round(col_pct, 1), "seam_rows_mm": round(seam_rows, 5), "interior_row_step_mm": round(float(row_steps.mean()), 5), "seam_rows_percentile": round(row_pct, 1), } def save_grey16(path, array, lo, hi): scaled = np.clip((array - lo) / (hi - lo), 0.0, 1.0) Image.fromarray((scaled * 65535.0 + 0.5).astype(np.uint16)).save(path) def save_grey8(path, array): Image.fromarray(np.clip(array * 255.0 + 0.5, 0, 255).astype(np.uint8)).save(path) def main(): os.makedirs(OUT, exist_ok=True) rng = np.random.default_rng(SEED) texel_mm = PATCH_MM / SIZE grains = place_grains(rng) height, owner = rasterise_grains(grains, texel_mm) fill_gaps(height, owner, grains, rng, texel_mm) unfilled = uncovered_fraction(height) # Wrap-mode blur: softening the union creases must not create a seam. height = ndi.gaussian_filter(height, BLUR_TEXELS, mode="wrap") periodicity_mm = periodicity_error(grains, texel_mm) lo, hi = float(height.min()), float(height.max()) n = normals(height, texel_mm) ao = ambient_occlusion(height, texel_mm) albedo = albedo_map(height, owner, ao, grains, rng) save_grey16(os.path.join(OUT, "rice_height_16bit.png"), height, lo, hi) save_grey8(os.path.join(OUT, "rice_ao_8bit.png"), ao) Image.fromarray(normals_to_rgb(n)).save( os.path.join(OUT, "rice_normal_opengl.png")) Image.fromarray(normals_to_rgb(n, directx=True)).save( os.path.join(OUT, "rice_normal_directx.png")) Image.fromarray(albedo).save(os.path.join(OUT, "rice_albedo.png")) report = seam_report(height) summary = { "patch_mm": PATCH_MM, "texture_px": SIZE, "texel_mm": round(texel_mm, 6), "grain_mm": LENGTH_MM, "grain_fraction_of_patch": round(LENGTH_MM / PATCH_MM, 6), "grains": len(grains), "layers": len(LAYERS), "upright_fraction": round( sum(g["upright"] for g in grains) / max(len(grains), 1), 3), "uncovered_fraction": round(unfilled, 6), "median_tilt_deg": round(float(np.median([g["tilt_deg"] for g in grains])), 1), "height_mm": [round(lo, 3), round(hi, 3)], "relief_mm": round(hi - lo, 3), "seed": SEED, "tileable": periodicity_mm < 1e-6, "periodicity_error_mm": periodicity_mm, "seam": report, "maps": { "height": "rice_height_16bit.png", "normal_opengl": "rice_normal_opengl.png", "normal_directx": "rice_normal_directx.png", "ao": "rice_ao_8bit.png", "albedo": "rice_albedo.png", }, } with open(os.path.join(OUT, "rice_maps.json"), "w") as f: json.dump(summary, f, indent=2) upright = sum(g["upright"] for g in grains) print(f"[info] {len(grains)} grains in {len(LAYERS)} layers over " f"{PATCH_MM:.0f} mm; {upright} upright " f"({upright / len(grains) * 100:.0f}%)") print(f"[info] uncovered floor after gap fill: {unfilled * 100:.4f}%") print(f"[info] relief {hi - lo:.2f} mm, texel {texel_mm * 1000:.2f} um") print(f"[info] periodicity error {periodicity_mm:.2e} mm (0 = exactly tiles)") print(f"[info] seam diagnostic: {json.dumps(report)}") print("[done]") if __name__ == "__main__": main()