"""Light and materials for the SDF renderer: glass that refracts, metals that mirror the scene, subsurface glow, lighter shadows under glass. Pure numpy; hooks are called from pydraw3d.shade(). Part flags (models may set them; most come from the rules in apply_materials): glass 0..1 transparent: Fresnel reflection + refraction through the body (IOR `ior`), tinted by the part colour ior index of refraction (glass 1.5, water 1.33, ice 1.31, diamond 2.42) frost 0..1 frosted / milky (ice): mixes in a diffuse look metal 0..1 conductor: the reflection takes the albedo's colour, almost no diffuse sss 0..1 subsurface scattering look (skin, fruit, wax, leaves, jade): light wraps past the terminator, shadows fill with saturated colour""" import math import numpy as np from . import sdf as S METAL_COLORS = {"silver": (226, 228, 232), "gold": (255, 196, 86), "golden": (255, 196, 86), "bronze": (212, 140, 80), "copper": (222, 128, 90), "chrome": (230, 232, 236), "metallic": (205, 208, 214)} MATERIALS = { # entity material (pydraw/materials.py words) -> part flags "glass": dict(glass=1.0, ior=1.5, frost=0.0), "ice": dict(glass=1.0, ior=1.31, frost=.3, tint=(214, 236, 250)), "metal": dict(metal=1.0, rough=.18, tint=(205, 208, 214)), "gold": dict(metal=1.0, rough=.15, tint=(255, 196, 86)), "bronze": dict(metal=1.0, rough=.28, tint=(212, 140, 80)), "jade": dict(sss=.9, spec=.7, rough=.12, tint=(45, 125, 75)), "clay": dict(sss=.3), "marble": dict(sss=.5, spec=.5, rough=.2), } GOLDS = ((228, 182, 52), (212, 175, 55), (255, 196, 86), (230, 190, 80), (255, 215, 0)) GLASS_FAMILIES = ("vessel", "crystal", "drink") GLASS_CONCEPTS = ("bottle", "wine glass", "crystal ball", "diamond", "aquarium", "fishbowl", "vase") NOT_GLASS = ("jar",) SSS_CONCEPTS_FAMILY = ("fruit", "bunch", "flower", "leaf", "mushroom") def _sat_val(c): c = np.asarray(c, float) / 255 mx, mn = c.max(), c.min() return (mx - mn) / max(mx, 1e-6), mx def _skin(c): r, g, b = c return r > 150 and r > g > b and 25 < r - b < 130 and g > 90 def apply_materials(parts, fn, concept, ent, cname, inst=None, col=None): """rule: what an object is made of decides how light passes through it or bounces off it. - a named material (a glass sphere, an ice cube, a golden statue, a jade dragon) re-skins the object's main parts; - metal colour words (silver, gold, bronze, copper, chrome) make the coloured parts metal; - glass vessels / gems / bottles: their mirror-glossy shells become real glass; - neutral bright mirror-glossy trims (chrome bumpers, steel appliances) become metal; - skin, fruit, petals, leaves glow a little from inside (subsurface).""" fam = getattr(fn, "family", None) or "" mat = (ent or {}).get("material") # the object's coloured parts: those painted in the object's colour (else the first part's colour) main = ([pt for pt in parts if col is not None and np.allclose(pt.color, col, atol=2)] or [pt for pt in parts if parts and np.allclose(pt.color, parts[0].color)] or parts[:1]) if isinstance(mat, str) and mat in MATERIALS: spec = MATERIALS[mat] explicit = bool((ent or {}).get("color")) and (ent or {}).get("color_explicit", True) # rule: a glass/ice object is glass all through (its detail parts too, so a glass horse is not a glass body # with painted eyes floating in it), metal re-skins every part except tiny dark details targets = parts if spec.get("glass") else [pt for pt in parts if _sat_val(pt.color)[1] > .25] or parts for pt in targets: for k, v in spec.items(): if k == "tint": if not explicit: pt.color = np.asarray(v, float) else: setattr(pt, k, v) if spec.get("glass"): if not explicit: pt.color = np.asarray(spec.get("tint", (238, 244, 250)), float) pt.spec, pt.rough, pt.tex, pt.pat = 1.0, .03, None, None if spec.get("metal"): pt.spec, pt.tex = 1.0, None return mat if cname in METAL_COLORS: for pt in main: pt.metal, pt.spec, pt.rough = 1.0, 1.0, min(getattr(pt, "rough", .3), .22) pt.color = np.asarray(METAL_COLORS[cname], float) pt.tex = None return "metal" glassy = (fam in GLASS_FAMILIES or concept in GLASS_CONCEPTS) and concept not in NOT_GLASS for pt in parts: if getattr(pt, "glass", 0) or getattr(pt, "metal", 0) or getattr(pt, "emit", 0): continue s, v = _sat_val(pt.color) if glassy and pt.spec >= .99 and pt.rough <= .05 and concept != "vase": pt.glass, pt.ior = 1.0, (2.42 if fam == "crystal" else 1.5) elif pt.spec >= .95 and pt.rough <= .12 and s < .08 and .55 < v < .95: pt.metal = .9 # chrome trims, steel appliances elif cname is None and pt.spec >= .85 and pt.rough <= .2 and \ min(np.abs(np.asarray(pt.color, float) - np.asarray(g, float)).sum() for g in GOLDS) < 60: pt.metal, pt.rough = 1.0, min(pt.rough, .15) # glossy gold-coloured parts are gold (crowns, trophies, coins) pt.tex = None elif _skin(tuple(pt.color)) and ("person" in concept or fam in ("primate",) or concept in ("man", "woman", "boy", "girl", "child", "baby")): pt.sss = .6 elif fam in SSS_CONCEPTS_FAMILY or pt.tex in ("leaves", "pores", "speckle") and fam not in ("quadruped", "bird"): pt.sss = max(getattr(pt, "sss", 0), .25) return None class Flags: def __init__(self, n): self.glass = np.zeros(n); self.ior = np.full(n, 1.5); self.frost = np.zeros(n) self.metal = np.zeros(n); self.sss = np.zeros(n); self.any = False def collect(self, pt, idx): g, m, s = getattr(pt, "glass", 0), getattr(pt, "metal", 0), getattr(pt, "sss", 0) if g or m or s: self.any = True if g: self.glass[idx] = g; self.ior[idx] = getattr(pt, "ior", 1.5); self.frost[idx] = getattr(pt, "frost", 0) if m: self.metal[idx] = m if s: self.sss[idx] = s def sss_light(light, fl, N, L, sha, dif, alb, sunc, sun_i, amb_col): """rule (subsurface look): light enters and leaves a little further on: diffuse wraps past the terminator, shadow edges soften, and the light that crosses into shadow comes out saturated in the material's own colour (red under skin, orange in fruit, yellow-green through leaves).""" s = fl.sss i = np.nonzero(s > 0)[0] if not len(i): return light w = .6 nl = N[i] @ L wrap = np.clip((nl + w) / (1 + w), 0, 1) ** 1.5 soft = wrap * (.35 + .65 * sha[i]) extra = np.maximum(soft - dif[i] * sha[i], 0) a = alb[i] tint = (a / np.maximum(a.max(-1, keepdims=True), 1e-4)) ** 1.6 # deep, saturated scatter colour out = light.copy() out[i] = light[i] + (sunc * sun_i)[None, :] * (extra * s[i] * .55)[:, None] * tint + amb_col[None, :] * (.15 * s[i])[:, None] * tint return out def _reflect(I, N): return I - 2 * (I * N).sum(-1)[:, None] * N def _refract(I, N, eta): """I incoming, N against I; returns (T, tir mask)""" cosi = np.clip(-(I * N).sum(-1), -1, 1) k = 1 - eta * eta * (1 - cosi * cosi) tir = k < 0 T = eta[:, None] * I + (eta * cosi - np.sqrt(np.maximum(k, 0)))[:, None] * N T = np.where(tir[:, None], _reflect(I, N), T) return T / np.maximum(S.length(T)[:, None], 1e-9), tir def _obj_normal(o, P, eps): k = np.array([[1, -1, -1], [-1, -1, 1], [-1, 1, -1], [1, 1, 1]], float) n = sum(kk[None, :] * o.dist(P + kk * eps, .05)[:, None] for kk in k) return n / np.maximum(S.length(n)[:, None], 1e-9) def _through(o, P, T, scale, steps=40): """march INSIDE object o from P along T to where it leaves the body: (exit point, path length)""" t = np.full(len(P), 2e-3 * scale) alive = np.ones(len(P), bool) for _ in range(steps): idx = np.nonzero(alive)[0] if not len(idx): break d = -o.dist(P[idx] + T[idx] * t[idx, None], .05) done = d < 1e-4 * scale t[idx] += np.where(done, 0, np.maximum(d * .9, 1e-3 * scale)) alive[idx[done | (t[idx] > 4 * scale)]] = False return P + T * t[:, None], t def ggx_spec(N, V, L, rough, F): """GGX / Trowbridge-Reitz highlight with a Smith-Schlick visibility term (energy-normalised)""" H = L[None, :] + V H /= np.maximum(S.length(H)[:, None], 1e-9) nh = np.clip((N * H).sum(-1), 0, 1) nl = np.clip(N @ L, 0, 1) nv = np.clip((N * V).sum(-1), 1e-3, 1) a2 = np.maximum(rough, .02) ** 4 dd = a2 / (math.pi * (nh * nh * (a2 - 1) + 1) ** 2) kk = np.maximum(rough, .02) ** 2 / 2 vis = 1 / ((nl * (1 - kk) + kk) * (nv * (1 - kk) + kk)) return np.minimum(dd * vis * nl / 4, 60) * F def secondary(c, fl, hi_ids, Ph, N, Dh, alb, rough, sha, ao, objs, trace_fn, bg_fn, xs, ys, depth, sunc, sun_i, L, env_avg, maxdepth=3): """Overwrite the colour of glass and metal hits. rule (glass): Schlick Fresnel splits light between a mirror reflection (the sky/backdrop) and the refracted ray, which bends in (Snell), crosses the body to its far side, bends out and continues into the scene; the colour is tinted by the glass colour more the longer the path inside (Beer-Lambert). A sun glint stays on top. rule (metal): a metal mirrors the scene (traced, one bounce) coloured by its own albedo (Schlick with F0 = albedo), blurred toward the average environment as it gets rougher; a tight GGX sun highlight.""" out = c.copy() V = -Dh gi = np.nonzero(fl.glass > 0)[0] if len(gi): I, Ng = Dh[gi], N[gi] ior = fl.ior[gi] F0 = ((ior - 1) / (ior + 1)) ** 2 cosi = np.clip(-(I * Ng).sum(-1), 0, 1) F = F0 + (1 - F0) * (1 - cosi) ** 5 R = _reflect(I, Ng) refl = bg_fn(R.astype(np.float32), xs[gi], ys[gi]) trans = np.zeros((len(gi), 3)) absorb = np.ones((len(gi), 3)) T1, _ = _refract(I, Ng, 1 / ior) exitP = np.zeros_like(Ph[gi]) exitD = np.zeros_like(I) for k in np.unique(hi_ids[gi]): if k < 0: continue m = hi_ids[gi] == k o = objs[k] P1 = Ph[gi][m] - Ng[m] * 2e-3 * o.scale P2, plen = _through(o, P1, T1[m], o.scale) N2 = _obj_normal(o, P2, 1e-3 * o.scale) T2, tir = _refract(T1[m], -N2, ior[m]) tn = alb[gi][m] / np.maximum(alb[gi][m].max(-1, keepdims=True), 1e-4) absorb[m] = np.clip(tn, 1e-3, 1) ** (.3 + 1.5 * (plen / o.scale))[:, None] exitP[m] = P2 + N2 * 3e-3 * o.scale exitD[m] = T2 if depth < maxdepth: trans = trace_fn(exitD.astype(np.float32), exitP, xs[gi], ys[gi], depth + 1) else: trans = bg_fn(exitD.astype(np.float32), xs[gi], ys[gi]) glint = (sunc * sun_i)[None, :] * ggx_spec(Ng, V[gi], L, np.full(len(gi), .06), F)[:, None] * sha[gi][:, None] g = trans * absorb * (1 - F)[:, None] + refl * F[:, None] + glint fr = fl.frost[gi][:, None] g = g * (1 - fr) + (c[gi] * .6 + trans * absorb * .4) * fr w = fl.glass[gi][:, None] out[gi] = c[gi] * (1 - w) + g * w mi = np.nonzero((fl.metal > 0) & (fl.glass <= 0))[0] if len(mi): I, Nm = Dh[mi], N[mi] R = _reflect(I, Nm) if depth < 1: refl = trace_fn(R.astype(np.float32), Ph[mi] + Nm * 3e-3 * max(np.mean([o.scale for o in objs]), 1e-3), xs[mi], ys[mi], depth + 1) else: refl = bg_fn(R.astype(np.float32), xs[mi], ys[mi]) r_ = np.clip(rough[mi], 0, 1) blur = np.clip((r_ - .05) * 2.2, 0, .85)[:, None] refl = refl * (1 - blur) + env_avg[None, :] * blur F0 = alb[mi] cosi = np.clip(-(I * Nm).sum(-1), 0, 1) F = F0 + (1 - F0) * ((1 - cosi) ** 5)[:, None] hl = (sunc * sun_i)[None, :] * ggx_spec(Nm, V[mi], L, np.maximum(r_, .08), 1.0)[:, None] * F * sha[mi][:, None] mcol = refl * F * (.35 + .65 * ao[mi])[:, None] + hl + c[mi] * .12 w = fl.metal[mi][:, None] out[mi] = c[mi] * (1 - w) + mcol * w return out def glass_shadow(scene, P, L, tmax, scl, k, steps, margin, shadow_fn): """rule: glass casts a light, see-through shadow (most light passes): shadow = opaque objects' shadow times a soft 40% darkening where the glass would block the sun.""" import copy keep = [o for i, o in enumerate(scene.objs) if i not in scene.glassy] s2 = copy.copy(scene) s2.objs = keep s_op = shadow_fn(s2, P, L, tmax, scl, k, steps, margin=margin) s_all = shadow_fn(scene, P, L, tmax, scl, k, steps, margin=margin) ratio = np.clip(s_all / np.maximum(s_op, 1e-3), 0, 1) # rule: a fake caustic: the core of a glass shadow is brighter (the glass focuses the sun into it) return s_op * (.55 + .45 * ratio + .9 * (1 - ratio) ** 6) def studio_env(R, back, L, floor): """rule: what a glossy or glass object sees in a photo studio: a big bright softbox in the key light's direction, a thin strip light opposite, a darker room around and behind the camera, the floor below. Mirror-like materials read as glass/metal mostly through these reflections (bright windows + dark edges).""" up = R[:, 1] grey = np.full(3, float(back @ np.array([.3, .59, .11]))) front = back[None, :] * (.35 + .55 * np.clip(up * .8 + .45, 0, 1))[:, None] # the backdrop room = (back * .35 + grey * .65)[None, :] * (.06 + .3 * np.clip(up * .8 + .4, 0, 1))[:, None] # dim studio behind w = np.clip(R[:, 2] * 1.6 + .45, 0, 1)[:, None] env = room * (1 - w) + front * w Lk = np.array([L[0], L[1] + .25, L[2]], float); Lk /= np.linalg.norm(Lk) s = R @ Lk env = env + np.array([1.0, .98, .95])[None, :] * (np.clip((s - .86) / .03, 0, 1) * 5.0)[:, None] Lf = np.array([-L[0], .35, -.55]); Lf /= np.linalg.norm(Lf) s2 = R @ Lf env = env + np.array([.95, .97, 1.0])[None, :] * (np.clip((s2 - .965) / .01, 0, 1) * 2.0)[:, None] fl = np.clip(-up * 8, 0, 1)[:, None] return env * (1 - fl) + floor[None, :] * .55 * fl # ---------------- emissive objects light their surroundings ---------------- SCREENS = ("tv", "laptop", "cell phone", "monitor", "computer", "television", "tablet", "phone", "smartphone") def night_dress(parts, concept, fn): """rule (night): screens are switched on (glowing a cool blue-white) and house windows glow warm, so a night scene has its own light sources""" fam = getattr(fn, "family", None) or "" for pt in parts: c = np.asarray(pt.color, float) blueish = c[2] > c[0] + 30 and c[2] > 150 if concept in SCREENS and pt.spec >= .99 and pt.rough <= .05 and blueish: pt.emit, pt.color, pt.is_light = .42, np.array([110., 165., 255.]), True elif (concept in ("house", "home", "cabin", "cottage") or fam == "building") and blueish and pt.spec >= .85: pt.emit, pt.color = .8, np.array([255., 196., 110.]) def find_lights(objs, max_lights=4): """rule: every strongly emissive part (lamp bulb, candle flame, fire, lantern glass) is also a point light at the centre of that part, coloured like it, as strong as the object is big. Returns [(pos, colour, power, obj index, radius)] strongest first.""" from . import accel out = [] for k, o in enumerate(objs): if not hasattr(o, "pbox"): accel.compute_bounds(o) for j, pt in enumerate(o.parts): e = float(getattr(pt, "emit", 0) or 0) if (e < .55 and not getattr(pt, "is_light", False)) or getattr(o, "name", "") in ("house",): continue b = o.pbox[j] c = (b[0] + b[1]) * .5 if b is not None else np.array([0, .6, 0], np.float32) size = float(np.max(b[1] - b[0])) if b is not None else .3 pos = o.base + S.rot_y(np.asarray(c, float)[None, :], o.yaw)[0] * o.scale col = (np.asarray(pt.color, float) / 255) ** 2.2 col = col / max(col.max(), 1e-3) out.append((pos, col, e * o.scale ** 2 * (.6 + 2.0 * min(size, .5)), k, max(size * o.scale * .5, .02 * o.scale))) out.sort(key=lambda x: -x[2]) return out[:max_lights] def _shadow_dirs(scene, P, Ld, tmax, scl, k=8.0, steps=36): """soft shadow along per-point directions (towards a point light), stopping at the light""" from . import _ck, _COMPILE ck = _ck(scene) if _COMPILE[0] else None if ck is not None: # night wave: the same loop in the compiled kernel return ck.shadow_dirs(P, Ld, tmax, scl, k, steps, .4) n = len(P) res = np.ones(n) t = np.full(n, .03 * scl) active = t < tmax for _ in range(steps): idx = np.nonzero(active)[0] if not len(idx): break ti = t[idx] d = scene.dist(P[idx] + Ld[idx] * ti[:, None], margin=.4) r = np.minimum(res[idx], np.clip(k * d / ti, 0, 1)) res[idx] = r ti = ti + np.clip(d, .01 * scl, .3 * scl) t[idx] = ti active[idx] = (ti < tmax[idx]) & (r > .003) return res ** 1.5 def point_lights(scene, lights, Ph, N, ids, scl, gain=1.0): """irradiance from the emissive point lights (inverse-square with a soft core, Lambert, soft shadows; the light's own object never shadows it - the bulb sits inside the lampshade)""" import copy add = np.zeros((len(Ph), 3)) for pos, col, power, k, rad in lights: Lv = pos[None, :] - Ph r = S.length(Lv) Ld = Lv / np.maximum(r[:, None], 1e-6) ndl = np.clip(((N * Ld).sum(-1) + .15) / 1.15, 0, 1) att = power * gain / (r * r + rad * rad * 4) lit = (ndl * att > 2e-3) & (ids != k) sh = np.ones(len(Ph)) i = np.nonzero(lit)[0] if len(i): s2 = copy.copy(scene) s2.objs = [o for j, o in enumerate(scene.objs) if j != k] s2.glassy = set() sh[i] = _shadow_dirs(s2, Ph[i] + N[i] * 2e-3 * scl, Ld[i], np.maximum(r[i] - rad, 1e-3), scl) own = ids == k # the lamp's own body glows near the bulb (lampshade, lantern frame) add += col[None, :] * (att * np.where(own, np.clip(ndl + .4, 0, 1), ndl) * sh)[:, None] return add def lens(col, n, tod, bloom=1.0, vignette=1.0, grain=0.0, seed=0): """Camera effects on the linear HDR image (before tone mapping). rule: bloom: light brighter than white bleeds into its surroundings (wide + tight gaussian halos), strongest at night where lamps and windows glow; a gentle vignette darkens the corners like a real lens.""" from scipy.ndimage import gaussian_filter img = col.reshape(n, n, 3) if bloom > 0: lum = img @ np.array([.3, .59, .11]) thr = .6 if tod == "night" else 1.3 br = img * (np.clip(lum - thr, 0, 8) / np.maximum(lum, 1e-6))[..., None] if br.max() > 0: b1 = np.stack([gaussian_filter(br[..., c], n / 160) for c in range(3)], -1) b2 = np.stack([gaussian_filter(br[..., c], n / 35) for c in range(3)], -1) k = (.35 if tod == "night" else .18) * bloom img = img + k * (b1 * .6 + b2 * .9) if vignette > 0: yy, xx = np.mgrid[0:n, 0:n] / (n - 1) - .5 v = 1 - .28 * vignette * (xx * xx + yy * yy) ** 1.2 * 2.2 img = img * v[..., None] if grain > 0: rng = np.random.default_rng(seed) img = img * (1 + grain * rng.standard_normal((n, n, 1))) return img.reshape(-1, 3) def beams(col, D, O, tm, objs, tod, trace, gain=1.0): """night wave rule (knob beam=0): a lighthouse at night / dusk sweeps two light beams through the air - an analytic light shaft per pixel: the closest approach of the camera ray (up to its hit) to each beam axis, a gaussian across the beam that widens with distance, fading along it; plus a halo around the lamp.""" lh = [o for o in objs if o.name == "lighthouse"] if not lh or tod not in ("night", "sunset"): return col D = np.asarray(D, float) T = np.minimum(np.where(np.isfinite(tm), tm, 1e9), 1e9) warm = (np.array([255, 236, 196]) / 255.0) ** 2.2 A = (1.4 if tod == "night" else .6) * gain for o in lh: P = o.base + np.array([0, .9 * o.scale, 0]) for sgn in (1, -1): B = np.array([sgn * 1.0, -.03, -.45 * sgn + .15]) B /= np.linalg.norm(B) w0 = O - P b = D @ B d = D @ w0 e = float(B @ w0) den = np.maximum(1 - b * b, 1e-6) t = np.clip((b * e - d) / den, 0, T) s = np.clip((D * t[:, None] + w0) @ B, 0, 60 * o.scale) # the ray's closest point, projected on the beam q = O + D * t[:, None] - (P + s[:, None] * B) dist = np.linalg.norm(q, axis=1) wid = .03 * o.scale + .065 * s g = np.exp(-(dist / wid) ** 2) * np.exp(-s / (12 * o.scale)) * (s > 0) col = col + A * .35 * g[:, None] * warm # halo around the lamp (only where the ray passes in front of it) w0 = P - O t = np.clip(D @ w0, 0, T) dl = np.linalg.norm(O + D * t[:, None] - P, axis=1) col = col + A * .9 * np.exp(-(dl / (.06 * o.scale)) ** 2)[:, None] * warm trace.append("3d: lighthouse beams at %s" % tod) return col def weather_post(img, weather, seed=0, night=False): """night wave rule (knob wxpost=0): rain / snow particles for outdoor scenes WITHOUT a procedural world (streets, the moon...) - the world draws its own; streets in the rain had no rain at all. Same look as world.post.""" from PIL import Image, ImageDraw, ImageFilter n = img.shape[0] rng = np.random.RandomState(seed + 7) if weather in ("rain", "storm"): ov = Image.new("L", (n, n), 0) dr = ImageDraw.Draw(ov) ang = rng.uniform(-.25, .1) for _ in range(int(n * 1.6)): x, y = rng.uniform(-.1, 1.1) * n, rng.uniform(0, 1) * n ln = rng.uniform(.02, .07) * n dr.line([x, y, x + ang * ln, y + ln], fill=int(rng.uniform(40, 110) * (.7 if night else 1)), width=1) a = np.asarray(ov.filter(ImageFilter.GaussianBlur(.6))).astype(float)[..., None] / 255 lum = img.mean(-1, keepdims=True) img = img * .82 + lum * .18 img = img * (1 - a) + (.6 if night else .85) * a elif weather == "snow": ov = Image.new("L", (n, n), 0) dr = ImageDraw.Draw(ov) for _ in range(int(n * .9)): x, y = rng.uniform(0, 1) * n, rng.uniform(0, 1) * n r = rng.uniform(.6, 1.0) ** 6 * n * .008 + .6 dr.ellipse([x - r, y - r, x + r, y + r], fill=int(rng.uniform(150, 255))) a = np.asarray(ov.filter(ImageFilter.GaussianBlur(.8))).astype(float)[..., None] / 255 img = img * (1 - a) + .97 * a return img