Spaces:
Running
Running
retro 64 renderer (64x64 pixel-art sprites), 3D search option, wave-11 code (worlds, light, poses, imagination, art styles, camera, natural statistics) - pydraw 758e4a7
Browse filesFiles changed (34)
- app.py+17-10
- pydraw/actions.pyAdded+287
- pydraw/derived.pyAdded+125
- pydraw/gloss.pyAdded+1616
- pydraw/imagine.pyAdded+797
- pydraw/layout.py+5-2
- pydraw/open_vocab.py+28-1
- pydraw/understanding.py+163-1
- pydraw3d/MODELS.md+5
- pydraw3d/__init__.py+411-54
- pydraw3d/accel.pyAdded+155
- pydraw3d/camera.pyAdded+559
- pydraw3d/families/animals_other.py+71-11
- pydraw3d/families/animals_other_aquatic.py+19-3
- pydraw3d/families/animals_other_reptiles.py+27-3
- pydraw3d/families/mammals.py+334-15
- pydraw3d/families/z_sense_pins.pyAdded+13
- pydraw3d/imagine.pyAdded+793
- pydraw3d/imagine_creatures.pyAdded+336
- pydraw3d/imagine_kit.pyAdded+737
- pydraw3d/interact.pyAdded+213
- pydraw3d/interior.pyAdded+206
- pydraw3d/light.pyAdded+396
- pydraw3d/models.py+3-1
- pydraw3d/models_animals.py+9-9
- pydraw3d/models_fire.pyAdded+63
- pydraw3d/models_person.pyAdded+555
- pydraw3d/models_sky.pyAdded+37
- pydraw3d/natural.pyAdded+731
- pydraw3d/paint.py+1298-144
- pydraw3d/pose.pyAdded+223
- pydraw3d/retro64.pyAdded+392
- pydraw3d/search.pyAdded+708
- pydraw3d/world.pyAdded+1586
12 unmodified lines131415161718192021222324252627282 unmodified lines313233343536373839404142434445464710 unmodified lines5859606162636465666768697071725 unmodified lines7879808182834 unmodified lines8889909192939412 unmodified linesfrom PIL import Imagefrom pydraw import plot, CONCEPTSfrom pydraw3d import plot3dfrom pydraw3d.families import FAMILIES, TAXAEXAMPLES = ["a narwhal swimming under an iceberg", "a quokka smiling at the camera", "an oil painting of a horse in a field","a red fox in an autumn forest", "a castle on a hill with a dragon flying above it at sunset","a pagoda beside a cherry blossom tree", "a pangolin walking on a dirt path", "a bowl of ramen with chopsticks","three yellow ducks swimming on a lake", "a watercolor painting of a lighthouse at night","a hedgehog curled up next to an acorn", "a violin leaning against a stack of old books","four green apples and a banana on a table", "a pencil sketch of a cat next to a vase"]RENDERERS = ["pixel", "3D", "smooth"]def to_pil(img):2 unmodified linesreturn imdef _draw(prompt, seed, renderer, size, variation):if renderer == "3D":im, tr = plot3d(prompt, seed=seed, size=size, res=min(size, 384), variation=variation, return_trace=True)return im, im.info.get("scene") or {}, trimg = plot(prompt, seed=seed, size=size, style=renderer, variation=variation)return to_pil(img), img.scene, img.tracedef run(prompt, seed, renderer, size, variation):t = time.time()im, sc, tr = _draw(prompt, int(seed), renderer, int(size), float(variation))ents = sc.get("entities", [])fams = []for e in ents:10 unmodified linesreturn im, summary, "\n".join(tr)def run4(prompt, seed, renderer, size, variation):s0 = int(seed)return [(_draw(prompt, s0 + k, renderer, int(size), float(variation))[0], "seed %d" % (s0 + k)) for k in range(4)]with gr.Blocks(title="pydraw") as demo:gr.Markdown("# pydraw\nText to image with rules only: no weights, no training, no image files. ""%d hand-made concepts, plus any common noun through WordNet and %d generator families (%d word entries). ""Renderers: pixel art, a 3D ray-marcher (slower, ~10-40 s on this CPU), or smooth. ""Style words work too: watercolor, pencil sketch, oil painting, comic, black and white, neon, pop art."% (len(CONCEPTS), len(FAMILIES), len(TAXA)))with gr.Row():5 unmodified linessize = gr.Dropdown([256, 384, 512, 768], value=512, label="Size")variation = gr.Slider(0, 1, value=1, step=0.25, label="Variation",info="Varies only what the prompt leaves open (breed, colour of unnamed things, time, setting, framing). 0 = canonical image.")with gr.Row():btn = gr.Button("Draw", variant="primary")btn4 = gr.Button("4 variations")4 unmodified linesgal = gr.Gallery(label="4 variations (seed, seed+1, ...)", columns=2, height="auto")with gr.Accordion("Rules that fired", open=False):trace = gr.Textbox(lines=18, show_label=False)ins = [prompt, seed, style, size, variation]btn.click(run, ins, [out, summary, trace], api_name="run")prompt.submit(run, ins, [out, summary, trace])btn4.click(run4, ins, gal, api_name="run4")12 unmodified lines13141516171819202122232425262728292 unmodified lines323334353637383940414243444546474849505110 unmodified lines626364656667686970717273747576775 unmodified lines83848586878889904 unmodified lines959697989910010112 unmodified linesfrom PIL import Imagefrom pydraw import plot, CONCEPTSfrom pydraw3d import plot3dfrom pydraw3d.retro64 import retro64from pydraw3d.families import FAMILIES, TAXAEXAMPLES = ["an orange cat dressed as a chef", "a frog on a mushroom", "a red hot air balloon", "a narwhal swimming under an iceberg", "a quokka smiling at the camera", "an oil painting of a horse in a field","a red fox in an autumn forest", "a castle on a hill with a dragon flying above it at sunset","a pagoda beside a cherry blossom tree", "a pangolin walking on a dirt path", "a bowl of ramen with chopsticks","three yellow ducks swimming on a lake", "a watercolor painting of a lighthouse at night","a hedgehog curled up next to an acorn", "a violin leaning against a stack of old books","four green apples and a banana on a table", "a pencil sketch of a cat next to a vase"]RENDERERS = ["pixel", "retro 64", "3D", "smooth"]def to_pil(img):2 unmodified linesreturn imdef _draw(prompt, seed, renderer, size, variation, search=False):if renderer == "retro 64":im, tr = retro64(prompt, seed=seed, size=size, variation=variation, return_trace=True)return im, im.info.get("scene") or {}, trif renderer == "3D":im, tr = plot3d(prompt, seed=seed, size=size, res=min(size, 384), variation=variation, return_trace=True, search=search)return im, im.info.get("scene") or {}, trimg = plot(prompt, seed=seed, size=size, style=renderer, variation=variation)return to_pil(img), img.scene, img.tracedef run(prompt, seed, renderer, size, variation, search=False):t = time.time()im, sc, tr = _draw(prompt, int(seed), renderer, int(size), float(variation), bool(search))ents = sc.get("entities", [])fams = []for e in ents:10 unmodified linesreturn im, summary, "\n".join(tr)def run4(prompt, seed, renderer, size, variation, search=False):s0 = int(seed)return [(_draw(prompt, s0 + k, renderer, int(size), float(variation), bool(search))[0], "seed %d" % (s0 + k)) for k in range(4)]with gr.Blocks(title="pydraw") as demo:gr.Markdown("# pydraw\nText to image with rules only: no weights, no training, no image files. ""%d hand-made concepts, plus any common noun through WordNet and %d generator families (%d word entries). ""Renderers: pixel art; retro 64 (real 64 x 64 pixel-art sprites and scenes with a small palette, drawn from the 3D models, ~2 s); ""a 3D ray-marcher (slower, ~10-40 s on this CPU); or smooth. ""Style words work too: watercolor, pencil sketch, oil painting, comic, black and white, neon, pop art."% (len(CONCEPTS), len(FAMILIES), len(TAXA)))with gr.Row():5 unmodified linessize = gr.Dropdown([256, 384, 512, 768], value=512, label="Size")variation = gr.Slider(0, 1, value=1, step=0.25, label="Variation",info="Varies only what the prompt leaves open (breed, colour of unnamed things, time, setting, framing). 0 = canonical image.")search = gr.Checkbox(False, label="Search (3D only, several times slower)",info="Renders cheap previews of different scene layouts, scores them with hand-written rules and keeps the best.")with gr.Row():btn = gr.Button("Draw", variant="primary")btn4 = gr.Button("4 variations")4 unmodified linesgal = gr.Gallery(label="4 variations (seed, seed+1, ...)", columns=2, height="auto")with gr.Accordion("Rules that fired", open=False):trace = gr.Textbox(lines=18, show_label=False)ins = [prompt, seed, style, size, variation, search]btn.click(run, ins, [out, summary, trace], api_name="run")prompt.submit(run, ins, [out, summary, trace])btn4.click(run4, ins, gal, api_name="run4")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""Verbs -> poses and interactions (wave 11). A post-pass over the parsed scene: action words the main parserleft unknown or only half-used ("howling", "racing", "rearing", "grazing", "hanging upside down", "standing on oneleg", "waving", "balancing a ball on its nose", "carrying a key in its beak", "chasing", "sharing") become
entity["pose"] a body pose for the 3D families (pydraw3d.pose canonicalises it) entity["attrs"]["action"] what the hands / mouth do (wave, read, drink, eat, play, balance, carry ...) relations X holding Y (in a hand / mouth / beak), facing each other, fleeing (attrs["flee_from"])
Rules are about verbs and sentence shape, never about particular nouns: a verb belongs to the creature named justbefore it ("a wolf howling"), or to the next one when it is used as an adjective ("a howling wolf")."""import re
# verb -> (pose or None, action or None); poses use the parser's -ing vocabulary (pydraw3d.pose canonicalises)VERBS = {}
def _v(words, pose=None, action=None): for w in words.split(): VERBS[w] = (pose, action)
_v("howling howls howl roaring roars baying crowing", "howling", "howl")_v("racing galloping gallops sprinting sprints charging fleeing flees dashing dashes jogging jogs trotting trots", "running")_v("running runs", "running")_v("rearing rears", "rearing")_v("grazing grazes foraging forages pecking pecks", "grazing", "eat")_v("swimming swims paddling diving", "swimming")_v("crawling crawls creeping creeps slithering slithers stalking sneaking sneaks prowling prowls", "crawling")_v("hanging hangs dangling dangles swinging", "hanging")_v("waving", None, "wave")_v("balancing balances juggling juggles", None, "balance")_v("reading reads", None, "read")_v("drinking drinks sipping sips", None, "drink")_v("eating eats munching munches nibbling nibbles chewing chews", None, "eat")_v("playing plays strumming strums drumming", None, "play")_v("carrying carries holding holds", None, "carry")_v("kneeling kneels praying prays", "kneeling")_v("dancing dances", "dancing", "dance")_v("cheering cheers celebrating", None, "cheer")_v("pointing", None, "point")_v("singing sings", None, "sing")_v("sleeping sleeps snoozing snoozes", "sleeping")_v("sitting sits", "sitting")_v("lying", "lying")_v("walking walks strolling strolls marching marches wandering wanders hiking hikes", "walking")_v("jumping jumps leaping leaps hopping pouncing pounces", "jumping")_v("perching", "perched")_v("flying soaring soars gliding glides hovering hovers", "flying")_v("chasing chases", "running", "chase")_v("coiled coiling", "coiled")
# rule: "drinking from / eating grass / sniffing the ground": a non-person creature eats with its head downHEAD_DOWN = {"drink", "eat"}MOUTH_WORDS = {"mouth", "beak", "bill", "teeth", "jaws", "snout", "trunk"}HAND_WORDS = {"hand", "hands", "paw", "paws", "arms"}FACE_VERBS = {"sharing", "share", "shares", "meeting", "meet", "meets", "greeting", "greets", "talking", "chatting", "kissing", "hugging", "dancing", "arguing", "fighting", "playing"}DET = {"a", "an", "the", "two", "three", "four", "some", "one", "his", "her", "its", "their", "little", "big", "small", "young", "old", "cute", "baby"}
def _toks(text): text = re.sub(r'"[^"]*"', " ", text).lower().replace("-", " ").replace("'s", "") return re.findall(r"[a-z]+|\d+", text)
def _animate(e, CONCEPTS): c = CONCEPTS.get(e["concept"], {}) return e["concept"] in ("person", "robot", "teddy bear", "alien", "astronaut", "snowman") or bool(c.get("animal"))
def _locate(toks, ents): """token position of each entity's word (first match at or after the previous entity)""" pos, at = [], 0 for e in ents: w = (e.get("word") or e["concept"]).split() found = None for i in range(at, len(toks)): if toks[i:i + len(w)] == w or (len(w) == 1 and toks[i].rstrip("s") == w[0].rstrip("s")): found = i + len(w) - 1 break pos.append(found) if found is not None: at = found + 1 return pos
def family_of(concept): """the generator family a concept's 3D model belongs to (None for hand-made non-family models)""" from .registry import CONCEPTS ov = CONCEPTS.get(concept, {}).get("open_vocab") if ov: return ov.get("family") try: from .open_vocab import family_model fm = family_model(concept) return fm[0].family if fm else None except Exception: return None
def _remove(scene, k): ents = scene["entities"] del ents[k] re_ = lambda i: i - 1 if i > k else i scene["relations"] = [(re_(a), r, re_(b)) for a, r, b in scene["relations"] if a != k and b != k] acts = [] for a in scene.get("actions", []): if a["subject"] == k or a.get("object") == k: if a["subject"] == k: continue a = dict(a, object=None) a = dict(a, subject=re_(a["subject"]), object=re_(a["object"]) if a.get("object") is not None else None) acts.append(a) if "actions" in scene: scene["actions"] = acts for e in ents: at = e.get("attrs") or {} if isinstance(at.get("flee_from"), int): at["flee_from"] = re_(at["flee_from"])
def apply(scene, trace): from .registry import CONCEPTS ents = scene["entities"] if not ents: return scene toks = _toks(scene.get("text", "")) text = " " + " ".join(toks) + " " # rule: "on its hind legs" / "on two legs" is a pose, not a thing ("hind" is also a female deer) for k in range(len(ents) - 1, -1, -1): e = ents[k] if e["concept"] in ("hind",) and (" hind legs" in text or " hind leg" in text) and k > 0: _remove(scene, k) ents[k - 1]["pose"] = "upright" trace.append("actions: 'on its hind legs' -> %s stands upright" % ents[k - 1]["concept"]) # rule: an implied prop (a cup for "drinking") belongs to people; an animal drinks from the pond, not a cup for k in range(len(ents) - 1, -1, -1): w = (ents[k].get("word") or ents[k]["concept"]) held_by = [a for a, r, b in scene["relations"] if b == k and r == "holding"] if held_by and w.split()[-1] not in toks and CONCEPTS.get(ents[held_by[0]]["concept"], {}).get("animal") and w.split()[-1] in ("cup", "mug", "glass"): trace.append("actions: no implied %s for an animal" % ents[k]["concept"]) _remove(scene, k) pos = _locate(toks, ents) anim = [k for k, e in enumerate(ents) if _animate(e, CONCEPTS)] if not anim: return scene
def owner(i): """the creature a verb at token i belongs to""" # adjective use: "a howling wolf" (an article / adjective before, a creature right after) nxt = [k for k in anim if pos[k] is not None and i < pos[k] <= i + 3] prv = [k for k in anim if pos[k] is not None and pos[k] < i] if nxt and (i == 0 or toks[i - 1] in DET or toks[i - 1] == "and"): return min(nxt, key=lambda k: pos[k]) if prv: return max(prv, key=lambda k: pos[k]) return nxt[0] if nxt else None
def _verb(k, i, t): e = ents[k] pose, act = VERBS[t] at = e.setdefault("attrs", {}) if e.get("attrs") is not None else e.setdefault("attrs", {}) if act and not at.get("action"): at["action"] = act if pose and e.get("pose") in (None, "standing") and not (pose == "flying" and e["concept"] == "person"): # rule: "hanging" a kite / "flying a kite" are not poses of the person if pose == "flying" and i + 1 < len(toks) and toks[i + 1] in DET: return e["pose"] = pose trace.append("actions: '%s' -> %s pose=%s action=%s" % (t, e["concept"], pose, act)) elif act: trace.append("actions: '%s' -> %s action=%s" % (t, e["concept"], act)) if act in HEAD_DOWN and e["concept"] != "person" and e.get("pose") in (None, "standing"): # rule: an animal eating / drinking (not holding food in its paws or beak) lowers its head to it if not any(w in MOUTH_WORDS | HAND_WORDS for w in toks[i:]): if family_of(e["concept"]) in ("primate",): # rule: apes / monkeys eat from the hand: the food is held up to the mouth for j, (a_, r_, b_) in enumerate(scene["relations"]): if a_ == k and r_ in ("toward", "uses", "next_to") and CONCEPTS.get(ents[b_]["concept"], {}).get("height", 9) < .6: scene["relations"][j] = (a_, "holding", b_) elif not (CONCEPTS.get(e["concept"], {}).get("flying") and "flower" in text): e["pose"] = "grazing" if act == "chase": # rule: the chased one runs too, heading away from the chaser tgt = [b for a, r, b in scene["relations"] if a == k and r in ("toward", "next_to")] for b in tgt: ents[b]["pose"] = ents[b].get("pose") or "running" ents[b].setdefault("attrs", {})["flee_from"] = k if t in ("hanging", "hangs", "dangling") and "upside" in toks[i:i + 4]: at["upside_down"] = True
for i, t in enumerate(toks): if t not in VERBS: continue k0 = owner(i) if k0 is None: continue ks = [k0] # rule: "a man and a woman dancing": a verb after "A and B" belongs to both for j in anim: if pos[j] is not None and pos[k0] is not None and pos[j] < pos[k0] and "and" in toks[pos[j]:pos[k0]] and \ not any(w in VERBS for w in toks[pos[j] + 1:pos[k0]]) and pos[k0] < i: ks.append(j) for k in ks: _verb(k, i, t)
# rule: "hanging from a branch / tree": a hanging creature brings its own branch and trunk (the support is # part of the hanging pose), so the named support is not drawn a second time lying on the ground for k in [k for k in anim if ents[k].get("pose") == "hanging"]: if pos[k] is None: continue for j in range(len(ents) - 1, -1, -1): if j in anim or pos[j] is None or pos[j] <= pos[k]: continue if "from" in toks[pos[k]:pos[j]] and family_of(ents[j]["concept"]) in ("wood", "tree", None) and \ ents[j]["concept"] in ("branch", "tree", "stick", "limb", "bough", "vine", "palm tree", "pine") + tuple( c for c in [ents[j]["concept"]] if family_of(c) in ("wood", "tree")): trace.append("actions: %s hangs from its own branch (drop separate %s)" % (ents[k]["concept"], ents[j]["concept"])) _remove(scene, j) pos = _locate(toks, scene["entities"]) anim = [a for a, e in enumerate(scene["entities"]) if _animate(e, CONCEPTS)] break ents = scene["entities"] # rule: "standing on one leg" (or "on one foot") if re.search(r" on one (leg|foot) ", text): for k in anim: if ents[k].get("pose") in (None, "standing"): ents[k]["pose"] = "one_leg" trace.append("actions: 'on one leg' -> %s" % ents[k]["concept"]) break # rule: "X ... in its mouth / beak / paws" = X holds the thing (it was parsed as 'thing on X') if any((" its %s " % w) in text or (" his %s " % w) in text or (" her %s " % w) in text or (" their %s " % w) in text for w in MOUTH_WORDS | HAND_WORDS): rels = [] for a, r, b in scene["relations"]: if r in ("on", "in", "in_a") and b in anim and a > b: rels.append((b, "holding", a)) ents[b].setdefault("attrs", {}).setdefault("action", "carry") trace.append("actions: %s held in %s's mouth / hands" % (ents[a]["concept"], ents[b]["concept"])) else: rels.append((a, r, b)) scene["relations"] = rels # rule: "balancing X on its nose / head" = holding it there for k in anim: at = ents[k].get("attrs") or {} if at.get("action") == "balance": held = [b for a, r, b in scene["relations"] if a == k and r == "holding"] if not held: cands = [b for b in range(len(ents)) if b not in anim and pos[b] is not None and pos[k] is not None and pos[b] > pos[k]] if cands: b = cands[0] scene["relations"] = [(x, r, y) for x, r, y in scene["relations"] if not ({x, y} == {k, b})] scene["relations"].append((k, "holding", b)) trace.append("actions: %s balances %s" % (ents[k]["concept"], ents[b]["concept"])) if ents[k]["concept"] != "person" and ents[k].get("pose") in (None, "standing"): ents[k]["pose"] = "balancing" # rule: "sharing / meeting / greeting / talking": two creatures (or a pair) face each other if any(t in FACE_VERBS for t in toks) and not scene.get("arrange"): if len(anim) >= 2 or (len(anim) == 1 and ents[anim[0]]["count"] >= 2): if any(t in ("sharing", "share", "shares", "meeting", "meet", "meets", "greeting", "greets", "talking", "chatting", "kissing", "hugging", "arguing", "fighting") for t in toks): scene["arrange"] = "facing" trace.append("actions: a shared action -> the two face each other") # rule: something swimming needs water: a swimming land animal with no place named goes in a lake; "swimming in # the sea" is out at sea, not on the beach swim = [k for k in anim if ents[k].get("pose") == "swimming"] if swim and (scene.get("place") in (None, "field", "beach")): if scene.get("place") is None or " sea " in text or " ocean " in text or " lake " in text: scene["place"] = "water" trace.append("actions: swimming -> water") # rule: "sharing an umbrella / a pizza": the first of them holds the shared thing between them for i, t in enumerate(toks): if t in ("sharing", "share", "shares") and anim: objs = [b for b in range(len(ents)) if b not in anim and pos[b] is not None and pos[b] > i] if objs and not any(r == "holding" and b == objs[0] for a, r, b in scene["relations"]): b = objs[0] scene["relations"] = [(x, r, y) for x, r, y in scene["relations"] if y != b and x != b] scene["relations"].append((anim[0], "holding", b)) trace.append("actions: shared %s held between them" % ents[b]["concept"]) # rule: "walking a dog" = the dog walks too for i, t in enumerate(toks): if t in ("walking", "walks") and i + 2 < len(toks) and toks[i + 1] in DET: for k in anim: if pos[k] is not None and i < pos[k] <= i + 3 and ents[k].get("pose") is None: ents[k]["pose"] = "walking" return scene123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Derived concepts: new drawable concepts built from existing ones on the fly (morphs, chimeras, grafts, thingsgrown on top, floating islands, upside-down / melting things). The model is composed by pydraw3d/imagine.py fromother models; the pixel renderer draws it as a toon-lit sprite of the same model (like open-vocabulary nouns).Facts (height, setting, animal...) come from the base concept unless the recipe says otherwise."""from .registry import CONCEPTS
def _sprite_draw(aspect, animal): def draw(cv, ctx, inst): from pydraw3d.sprite import render_sprite, blit from pydraw3d.models import MODELS from .understanding import COLORS # rule: only a named colour recolours a derived model (its parts keep their own colours otherwise) c = COLORS.get(inst.color) if getattr(inst, "color", None) in COLORS else None fn, asp = MODELS[inst.concept] parts = fn(c, inst) side = asp > 1.05 and animal yaw = (.45 if side else .25) * (-1 if getattr(inst, "facing", None) == "left" else 1) if side and getattr(inst, "facing", None) == "left": yaw += 3.14159 spr, base_row = render_sprite(parts, asp, inst.h, yaw=yaw) blit(cv, spr, base_row, inst.x, inst.y) return draw
def register(name, base, build, trace=None, **facts): """build(col, inst) -> parts in any frame; they are normalised once (base on y=0, height 1, centred) and the same normalisation is reused for every colour / instance.""" if name in CONCEPTS: return name from pydraw3d.models import MODELS from pydraw3d import imagine_kit as I info = dict(CONCEPTS[base]) if base in CONCEPTS else dict(height=1.0, aspect=1.0, row="front", setting="field", animal=False, on_top=1.0, default_color=None, natural_colors={}, flying=False, shadow=True) info.pop("open_vocab", None) col0 = facts.pop("default_color", info.get("default_color")) try: p0 = build(col0, None) _, aspect, xf = I.normalize(p0) except Exception as ex: if trace is not None: trace.append("imagine: could not build %s (%s)" % (name, ex)) import os if os.environ.get("PYDRAW_IMAGINE_DEBUG"): import traceback traceback.print_exc() return None
def model_fn(c, inst=None, _b=build, _x=xf): return I.moved(_b(c if c is not None else col0, inst), **_x) model_fn.family = "imagine" info.update(name=name, aspect=aspect, default_color=col0, plurals={name: name}) info.update(facts) info["draw"] = _sprite_draw(aspect, info.get("animal", False)) CONCEPTS[name] = info MODELS[name] = (model_fn, aspect) if trace is not None: trace.append("imagine: registered %s (aspect %.2f, %.1fm)" % (name, aspect, info["height"])) return name
def _base_of(concept): return concept if concept in CONCEPTS else None
def morph(x, y, trace): from pydraw3d import imagine_kit as I name = "%s shaped like %s" % (x, y) hx = CONCEPTS[x]["height"] return register(name, x, lambda c, inst: I.morph_parts(x, y, c), trace)
def creature(recipe, trace): from pydraw3d import imagine_kit as I from pydraw3d.imagine_creatures import RECIPES r = RECIPES.get(recipe) if not r: return None name = recipe if recipe not in CONCEPTS or CONCEPTS[recipe].get("imagine_recipe") else recipe + " (creature)" if name in CONCEPTS and CONCEPTS[name].get("imagine_recipe"): return name if recipe in CONCEPTS and not CONCEPTS[recipe].get("imagine_recipe"): # rule: an existing pixel concept of the same name keeps its facts; the 3D model comes from the recipe from pydraw3d.models import MODELS built = register("__tmp_" + recipe, r["base"], r["build"], trace, **r.get("facts", {})) if not built: return recipe MODELS[recipe] = MODELS[built] CONCEPTS[recipe]["imagine_recipe"] = True CONCEPTS[recipe]["aspect"] = CONCEPTS[built]["aspect"] return recipe return register(name, r["base"], r["build"], trace, imagine_recipe=True, **r.get("facts", {}))
def graft(x, grafts, trace): from pydraw3d import imagine_kit as I name = x + " with " + " and ".join("%s%s" % ((d + " ") if d else "", p) for p, d, c in grafts) facts = {} if any(p == "wings" for p, d, c in grafts): facts["flying"] = False return register(name, x, lambda c, inst: I.graft_parts(x, grafts, c), trace, **facts)
def on_top(x, top, trace): from pydraw3d import imagine_kit as I name = "%s with %s on top" % (x, top) return register(name, x, lambda c, inst: I.top_parts(x, top, c), trace)
def transform(x, op, trace): from pydraw3d import imagine_kit as I name = "%s %s" % ({"flip": "upside down", "melt": "melting"}[op], x) return register(name, x, lambda c, inst: I.transform_parts(x, op, c), trace)
def island(trace): from pydraw3d import imagine_kit as I return register("floating island", "island" if "island" in CONCEPTS else None, lambda c, inst: I.island_parts(c, tree=True), trace, height=8.0, setting="field", row="sky", flying=True, on_top=.62, default_color=(95, 150, 60), animal=False)
def on_island(x, trace): from pydraw3d import imagine_kit as I h = CONCEPTS[x]["height"] return register("floating " + x, x, lambda c, inst: I.on_island_parts(x, c), trace, height=h * 1.9, flying=True, row="sky")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616"""Dictionary reader: appearance from WordNet's own text (glosses, examples, lemma names, part / substance meronyms).
rule: a word's look today comes from hand-written taxa on its WordNet path; a word with no taxon near it gets only itsancestors' generic shape. But the dictionary already DESCRIBES most things: okapi = "a ruminant mammal ... with a darkchestnut coat and stripes on the hindquarters and upper legs"; "small European warbler"; "a sandal with flat heels andan upper of woven leather straps". This module reads that text with a small hand-written grammar (no learned NLP):
tokens -> chunks : a run of modifiers (colour, size, length, shape, pattern, material, count words) attaches to the next region / part noun ("dark chestnut coat", "long neck", "two handles", "white flowers"); a run that ends at any other word or a clause break describes the whole thing ("small warbler"). compounds : "red-breasted" (colour + region), "long-tailed" (length + part), "three-masted" (count + part), "crimson-and-grey" (two colours), "cream-colored", "eel-shaped" / "dog-like" (borrow a shape), "flat-bottomed", "web-footed", "tailless" / "hornless" / "flightless" (absence). phrases : "with X", "having X", "bearing X" (presence), "without X" / "lacking X" / "no X" (absence), "smaller than a X" / "larger than X" (height from X), "similar to X" / "resembling X" / "like a X" (X's parameters when X is drawn by the same family). clause cuts : text after "feeds on", "used for", "for", "related to", "parasitic on" ... is not about the thing's own looks and is dropped ("feeds on red ants" must not make it red).
The features are then mapped to the family's parameters (per-family tables below): colour per body region, Part pat(stripes / spots / bands / patches / rosettes / scales), part sizes and enums (neck_len, horns, tusks, crest, beakshape, spout, lid, sails, chimney...), proportions (round / flat / elongate / tall / squat), material (wood / metal /glass / stone / leather / fabric / wicker) and setting (aquatic, marine, arboreal, desert, arctic...).Applied in open_vocab as a layer between the ancestors' taxa and the word's own hand-written taxon (hand wins)."""import re
ENABLED = [True]
# ------------------------------------------------------------------ lexiconCOLOURS = { "red": (200, 45, 40), "crimson": (170, 25, 45), "scarlet": (220, 40, 30), "vermilion": (225, 70, 40), "ruby": (175, 20, 55), "maroon": (115, 30, 35), "cherry": (190, 30, 50), "pink": (240, 155, 175), "rose": (230, 110, 140), "rosy": (230, 140, 150), "magenta": (200, 40, 150), "purple": (120, 55, 140), "violet": (140, 90, 200), "lavender": (190, 170, 225), "lilac": (200, 165, 215), "mauve": (190, 140, 180), "plum": (120, 50, 90), "blue": (55, 95, 195), "navy": (30, 40, 90), "azure": (70, 150, 230), "indigo": (60, 50, 130), "turquoise": (60, 190, 190), "cyan": (60, 200, 220), "teal": (40, 130, 130), "aqua": (100, 210, 210), "green": (70, 145, 60), "olive": (120, 120, 55), "emerald": (40, 150, 90), "lime": (160, 210, 60), "yellow": (240, 205, 45), "golden": (222, 172, 60), "gold": (222, 175, 60), "lemon": (245, 230, 80), "cream": (245, 235, 205), "creamy": (245, 235, 205), "ivory": (245, 240, 220), "buff": (222, 196, 150), "tan": (205, 165, 115), "beige": (220, 200, 165), "fawn": (200, 165, 120), "tawny": (196, 142, 75), "orange": (236, 130, 40), "amber": (225, 150, 40), "apricot": (245, 180, 120), "salmon": (240, 140, 115), "coral": (240, 120, 100), "rufous": (180, 85, 45), "russet": (150, 72, 38), "rust": (165, 75, 40), "chestnut": (125, 60, 32), "brown": (120, 80, 50), "bronze": (170, 120, 60), "copper": (185, 110, 60), "coppery": (185, 110, 60), "cinnamon": (170, 100, 55), "chocolate": (80, 50, 32), "sepia": (110, 75, 45), "ochre": (200, 140, 50), "khaki": (185, 175, 120), "sandy": (215, 190, 140), "grey": (138, 138, 136), "gray": (138, 138, 136), "silver": (195, 196, 200), "silvery": (195, 196, 200), "slate": (95, 105, 118), "ash": (170, 168, 160), "ashy": (170, 168, 160), "white": (246, 244, 238), "snowy": (248, 248, 250), "black": (32, 30, 30), "sooty": (55, 50, 50), "ebony": (35, 30, 28), "jet": (25, 25, 28), "dun": (175, 150, 110), "grizzled": (150, 145, 135), "hoary": (200, 200, 195), "straw": (225, 205, 130), "wine": (115, 25, 50), "burgundy": (115, 25, 45), "lemony": (245, 230, 80),}ISH = {"reddish": "red", "pinkish": "pink", "purplish": "purple", "bluish": "blue", "greenish": "green", "yellowish": "yellow", "orangish": "orange", "brownish": "brown", "greyish": "grey", "grayish": "grey", "whitish": "white", "blackish": "black", "tannish": "tan", "silverish": "silver", "violetish": "violet", "rusty": "rust", "golden-yellow": "golden", "dusky": "black"}TONE = {"dark": .62, "deep": .7, "dusky": .6, "light": 1.45, "pale": 1.6, "bright": 1.12, "vivid": 1.1, "brilliant": 1.12, "dull": .85, "rich": .9, "soft": 1.15}
PATTERN_ADJ = {"striped": "stripes", "stripy": "stripes", "streaked": "stripes", "streaky": "stripes", "barred": "stripes", "lined": "stripes", "spotted": "spots", "spotty": "spots", "dotted": "spots", "speckled": "spots", "flecked": "spots", "freckled": "spots", "pied": "patches", "piebald": "patches", "skewbald": "patches", "mottled": "patches", "blotched": "patches", "blotchy": "patches", "dappled": "patches", "patchy": "patches", "variegated": "patches", "marbled": "patches", "banded": "bands", "ringed": "bands", "zoned": "bands", "checkered": "checker", "chequered": "checker", "checked": "checker", "plaid": "checker", "scaly": "scales", "scaled": "scales", "brindled": "stripes", "tabby": "stripes"}PATTERN_NOUN = {"stripe": "stripes", "stripes": "stripes", "streak": "stripes", "streaks": "stripes", "bars": "stripes", "spot": "spots", "spots": "spots", "dots": "spots", "speckles": "spots", "flecks": "spots", "blotches": "patches", "blotch": "patches", "patches": "patches", "patch": "patches", "markings": "patches", "mottling": "patches", "bands": "bands", "band": "bands", "rings": "bands", "rosettes": "rosettes", "checks": "checker", "scales": "scales"}
SIZE = {"tiny": .45, "minute": .4, "miniature": .5, "dwarf": .55, "pygmy": .55, "diminutive": .5, "small": .72, "little": .75, "smallish": .8, "large": 1.38, "big": 1.35, "largish": 1.2, "great": 1.3, "huge": 1.9, "giant": 2.0, "gigantic": 2.1, "enormous": 2.0, "massive": 1.6, "immense": 2.0, "tall": 1.3, "towering": 1.7}LENGTH = {"longer": "long", "shorter": "short", "long": "long", "elongate": "long", "elongated": "long", "lengthy": "long", "extended": "long", "short": "short", "shortened": "short", "stubby": "short", "stumpy": "short", "truncated": "short", "abbreviated": "short"}BULK = {"larger": "big", "bigger": "big", "smaller": "small", "thicker": "thick", "stouter": "thick", "thinner": "thin", "slimmer": "thin", "broader": "broad", "wider": "broad", "narrower": "thin", "large": "big", "big": "big", "great": "big", "huge": "big", "enormous": "big", "prominent": "big", "conspicuous": "big", "massive": "big", "showy": "big", "broad": "broad", "wide": "broad", "small": "small", "tiny": "small", "minute": "small", "reduced": "small", "vestigial": "small", "rudimentary": "small", "inconspicuous": "small", "thick": "thick", "heavy": "thick", "stout": "thick", "robust": "thick", "sturdy": "thick", "thin": "thin", "slender": "thin", "slim": "thin", "narrow": "thin", "fine": "thin", "delicate": "thin"}FORM = {"round": "round", "rounded": "round", "roundish": "round", "globular": "round", "globose": "round", "spherical": "round", "ball-shaped": "round", "plump": "round", "chubby": "round", "rotund": "round", "squat": "squat", "stocky": "thick", "thickset": "thick", "heavyset": "thick", "flat": "flat", "flattened": "flat", "depressed": "flat", "compressed": "deep", "deep-bodied": "deep", "curved": "curved", "curving": "curved", "recurved": "curved", "arched": "curved", "bent": "curved", "hooked": "hooked", "straight": "straight", "pointed": "pointed", "sharp": "pointed", "tapering": "pointed", "conical": "conical", "cone-shaped": "conical", "pyramidal": "conical", "columnar": "columnar", "cylindrical": "cylindrical", "tubular": "tubular", "trumpet-shaped": "tubular", "funnel-shaped": "tubular", "bell-shaped": "bell", "campanulate": "bell", "star-shaped": "star", "forked": "forked", "bifurcate": "forked", "bushy": "bushy", "fluffy": "fluffy", "shaggy": "fluffy", "woolly": "fluffy", "wooly": "fluffy", "long-haired": "fluffy", "hairy": "hairy", "furry": "hairy", "fuzzy": "hairy", "bristly": "hairy", "drooping": "drooping", "pendulous": "drooping", "pendent": "drooping", "floppy": "drooping", "weeping": "drooping", "erect": "erect", "upright": "erect", "spiral": "spiral", "twisted": "spiral", "spirally": "spiral", "spiraled": "spiral", "spiralled": "spiral", "corkscrew": "spiral", "coiled": "spiral", "spreading": "spreading", "umbrella-shaped": "spreading", "flat-topped": "spreading", "branched": "branched", "branching": "branched", "webbed": "webbed", "prehensile": "prehensile", "domed": "domed", "dome-shaped": "domed", "high-domed": "domed", "elongate": "elongate", "elongated": "elongate", "slender": "slender", "spiny": "spiny", "prickly": "spiny", "thorny": "spiny", "armored": "armored", "armoured": "armored", "warty": "warty", "fan-shaped": "fan", "palmate": "palmate", "crested": "crested", "tufted": "crested", "plumed": "crested", "horned": "horned", "winged": "winged", "luminous": "glow", "luminescent": "glow", "phosphorescent": "glow", "glowing": "glow", "bioluminescent": "glow", "wavy": "curved", "oval": "round", "ovoid": "round", "egg-shaped": "round", "disk-shaped": "flat", "disc-shaped": "flat", "saucer-shaped": "flat", "shallow": "flat", "squarish": "boxy", "square": "boxy", "rectangular": "boxy", "boxlike": "boxy", "cubical": "boxy", "upturned": "curved"}MATERIAL = {"wooden": "wood", "wood": "wood", "timber": "wood", "oak": "wood", "pine": "wood", "bamboo": "bamboo", "metal": "metal", "metallic": "metal", "iron": "metal", "steel": "metal", "tin": "metal", "aluminum": "metal", "aluminium": "metal", "brass": "brass", "bronze": "bronze", "copper": "copper", "silver": "silver", "gold": "gold", "golden": "gold", "glass": "glass", "glassy": "glass", "crystal": "glass", "stone": "stone", "marble": "marble", "granite": "stone", "brick": "brick", "concrete": "concrete", "clay": "ceramic", "earthenware": "ceramic", "ceramic": "ceramic", "porcelain": "ceramic", "china": "ceramic", "terracotta": "terracotta", "pottery": "ceramic", "leather": "leather", "fabric": "fabric", "cloth": "fabric", "canvas": "canvas", "cotton": "fabric", "wool": "fabric", "woolen": "fabric", "woollen": "fabric", "silk": "fabric", "silken": "fabric", "linen": "fabric", "felt": "fabric", "velvet": "fabric", "woven": "wicker", "wicker": "wicker", "rattan": "wicker", "straw": "wicker", "plastic": "plastic", "paper": "paper", "cardboard": "paper", "rubber": "rubber", "ivory": "ivory", "bone": "ivory", "thatch": "thatch", "thatched": "thatch", "mud": "mud", "adobe": "mud", "log": "logs", "logs": "logs", "ice": "ice"}# material -> (colour, spec, rough)MAT_LOOK = {"wood": ((150, 100, 60), .25, .6), "bamboo": ((200, 175, 100), .3, .5), "metal": ((180, 184, 190), .85, .22), "brass": ((205, 165, 75), .9, .18), "bronze": ((170, 115, 60), .85, .25), "copper": ((190, 110, 65), .9, .2), "silver": ((200, 202, 208), .95, .12), "gold": ((222, 178, 65), .95, .12), "glass": ((185, 215, 230), 1.0, .05), "stone": ((175, 170, 160), .1, .85), "marble": ((238, 236, 230), .5, .3), "brick": ((168, 82, 62), .1, .85), "concrete": ((190, 190, 186), .1, .8), "ceramic": ((235, 232, 224), .75, .12), "terracotta": ((195, 105, 65), .35, .5), "leather": ((115, 65, 38), .45, .4), "fabric": ((120, 130, 160), .08, .9), "canvas": ((225, 212, 180), .05, .95), "wicker": ((200, 160, 100), .1, .85), "plastic": ((230, 230, 228), .5, .25), "paper": ((240, 236, 225), .05, .95), "rubber": ((45, 45, 48), .3, .7), "ivory": ((240, 232, 210), .5, .3), "thatch": ((196, 164, 96), .05, .95), "mud": ((178, 134, 92), .05, .9), "logs": ((132, 88, 52), .1, .85), "ice": ((215, 235, 245), .9, .1)}NUM = {"one": 1, "single": 1, "two": 2, "double": 2, "twin": 2, "paired": 2, "three": 3, "triple": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "several": 4, "many": 6, "numerous": 6, "multiple": 4}
# region / part nouns -> canonical namePARTS = {}for _canon, _ws in { "body": "body coat fur pelage plumage skin hide feathers hair upperparts upperpart fleece wool", "under": "underparts underpart underside undersides belly bellies abdomen underbody", "breast": "breast breasts chest bib", "throat": "throat throats gorget chin", "head": "head heads crown cap hood nape", "face": "face faces cheeks cheek mask", "back": "back backs mantle", "rump": "rump rumps hindquarters haunches", "wings": "wing wings wingbars", "tail": "tail tails", "legs": "leg legs feet foot paws paw limbs", "bill": "bill bills beak beaks", "neck": "neck necks", "ears": "ear ears", "eyes": "eye eyes", "snout": "snout snouts muzzle muzzles nose noses rostrum", "horns": "horn horns", "antlers": "antler antlers", "tusks": "tusk tusks", "trunk": "trunk trunks proboscis", "mane": "mane manes ruff", "hump": "hump humps", "crest": "crest crests topknot tuft tufts comb plume plumes", "fins": "fin fins", "dorsal": "dorsal", "spines": "spines spine quills quill prickles bristles thorns thorn", "fspike": "spike spikes raceme racemes panicle panicles catkin catkins", "wood": "wood timber", "flesh": "flesh pulp juice sap", "shell": "shell shells carapace", "claws": "claws claw pincers pincer chelae talons", "antennae": "antennae antenna feelers", "stinger": "stinger sting", "beard": "beard", "whiskers": "whiskers barbels barbel", "teeth": "teeth tooth fangs", "hood": "hood", "frill": "frill", "dewlap": "dewlap", "flippers": "flippers flipper", "arms": "arms arm tentacles", # plants "flowers": "flower flowers blossom blossoms bloom blooms florets floret petals petal corolla inflorescence inflorescences flowerheads", "leaves": "leaf leaves foliage fronds frond needles needle leaflets", "fruit": "fruit fruits berry berries drupe drupes", "nuts": "nuts nut pods pod cones acorns seeds capsules", "bark": "bark", "stem": "stem stems stalk stalks", "centre": "center centre disk disc", "branches": "branches branch boughs", # artifacts "handle": "handle handles grip", "spout": "spout spouts nozzle", "lid": "lid lids cover stopper cork", "wheels": "wheel wheels casters", "sails": "sail sails", "masts": "mast masts", "oars": "oar oars paddles", "chimney": "chimney chimneys smokestack smokestacks funnel funnels stack", "tower": "tower towers turret turrets steeple steeples spire spires", "dome": "dome domes cupola", "columns": "column columns pillars pillar colonnade", "roof": "roof roofs", "door": "door doors", "windows": "window windows", "blade": "blade blades", "point": "point tip", "strings": "strings string", "keys": "keys keyboard", "drawers": "drawers drawer", "shelves": "shelves shelf", "backrest": "backrest", "armrests": "armrests", "cushion": "cushion cushions upholstery padding", "engine": "engine engines motor", "propeller": "propeller propellers", "tracks": "tracks treads", "deck": "deck decks", "cabin": "cabin", "barrel": "barrel barrels", "screen": "screen display", "dial": "dial dials", "knobs": "knobs knob buttons", "base": "base pedestal", "neckpart": "",}.items(): for _w in _ws.split(): PARTS[_w] = _canon# compound stems: "red-breasted" -> breastED_STEM = {"breasted": "breast", "chested": "breast", "tailed": "tail", "headed": "head", "billed": "bill", "beaked": "bill", "necked": "neck", "legged": "legs", "footed": "legs", "eared": "ears", "winged": "wings", "horned": "horns", "antlered": "antlers", "tusked": "tusks", "backed": "back", "bellied": "under", "throated": "throat", "crowned": "head", "capped": "head", "hooded": "head", "faced": "face", "toothed": "teeth", "nosed": "snout", "snouted": "snout", "finned": "fins", "crested": "crest", "maned": "mane", "haired": "body", "furred": "body", "coated": "body", "feathered": "body", "skinned": "body", "shelled": "shell", "leaved": "leaves", "leafed": "leaves", "flowered": "flowers", "flowering": "flowers", "fruited": "fruit", "barked": "bark", "rumped": "rump", "eyed": "eyes", "handled": "handle", "wheeled": "wheels", "masted": "masts", "sailed": "sails", "spouted": "spout", "lidded": "lid", "roofed": "roof", "domed": "dome", "towered": "tower", "stringed": "strings", "bladed": "blade", "barreled": "barrel", "barrelled": "barrel", "engined": "engine", "decked": "deck", "armed": "arms", "clawed": "claws", "spined": "spines", "stemmed": "stem", "bodied": "body", "shouldered": "body", "limbed": "legs", "keeled": "deck", "bottomed": "base"}ABSENT = {"tailless": "tail", "hornless": "horns", "wingless": "wings", "flightless": "wings", "legless": "legs", "earless": "ears", "toothless": "teeth", "spineless": "spines", "handleless": "handle", "lidless": "lid", "windowless": "windows", "leafless": "leaves", "stemless": "stem", "finless": "fins", "backless": "backrest", "armless": "armrests", "maneless": "mane", "shell-less": "shell"}HABITAT = [ # (words, setting) first match wins ("marine sea seas ocean oceans oceanic reef reefs coral pelagic offshore deep-sea seawater saltwater", "sea"), ("aquatic freshwater river rivers lake lakes pond ponds stream streams swamp swamps marsh marshes wetland " "wetlands water", "water"), ("coastal shore shores seashore seashores seacoast seacoasts beach beaches seaside littoral dunes", "beach"), ("arboreal forest forests woodland woodlands woods jungle jungles rainforest rainforests", "forest"), ("desert deserts arid", "desert"), ("arctic antarctic polar tundra alpine snowy", "snow"), ("mountain mountains montane cliffs highlands", "mountains"), ("savanna savannas savannah grassland grasslands plains prairie prairies steppe steppes veldt", "savanna"),]HAB = {w: s for ws, s in HABITAT for w in ws.split()}COLOUR_NOUNS = set("orange plum rose cherry olive lime lemon salmon coral wine straw ash rust ivory chocolate cream " "amber ruby emerald jet slate indigo lavender lilac mauve violet tan buff fawn copper gold silver " "bronze cinnamon apricot sepia khaki navy teal aqua turquoise burgundy dun sandy".split())LIKE_SHAPE = {"egg": "round", "ball": "round", "globe": "round", "pear": "round", "barrel": "round", "cone": "conical", "pyramid": "conical", "cylinder": "cylindrical", "tube": "tubular", "trumpet": "tubular", "funnel": "tubular", "bell": "bell", "star": "star", "disk": "flat", "disc": "flat", "saucer": "flat", "plate": "flat", "cup": "bell", "bowl": "round", "spindle": "elongate", "cigar": "elongate", "torpedo": "elongate", "rod": "elongate", "needle": "elongate", "thread": "elongate", "box": "boxy", "brick": "boxy", "umbrella": "spreading", "fan": "fan", "heart": "round", "button": "flat", "worm": "elongate", "snake": "elongate", "sausage": "elongate", "ribbon": "elongate", "daisy": "ray", "aster": "ray", "lily": "tubular", "whip": "elongate", "sword": "elongate", "dagger": "pointed"}NEG = {"without", "lacking", "no", "lacks", "not", "never", "less", "non", "barely", "hardly"}STOPW = set("of with having has have bearing bears in on at to from by that which who whose where when as or the a an " "its their his her is are was were be being been it this these those than also usually often sometimes " "chiefly mainly mostly especially typically very more most less somewhat rather into over under".split())# words that start a clause about something elseCUTS = re.compile(r"\b(feeds? on|feeding on|preys? on|prey of|eats?|eating|parasitic on|parasite of|used (?:for|to|in|as|by)|" r"for (?:\w+ing|use|the purpose)|related to|closely related|named (?:for|after)|in which|" r"valued for|source of|yields?|producing|whose larvae|larvae of|host of|" r"pollinated by|hunted for|kept as|not(?:ed|able) for|known for|famous for|resembles? that of|for (?:the|a|an|making|holding|carrying|storing|serving)|" r"(?:that|which|who) (?!has|have|is|are|bears?|resembles?|looks?|grows? to)\w+|whose|where)\b[^;:.]*")REF = re.compile(r"\b(?:similar to|resembling|resembles|resemble|like|related to|looks like)\s+(?:a |an |the )?([a-z][a-z\-]+(?: [a-z][a-z\-]+)?)")CMP = re.compile(r"\b(smaller|larger|bigger|taller|shorter)\s+than\s+(?:a |an |the |most |other )?([a-z][a-z\-]+(?: [a-z][a-z\-]+)?)")ALT = re.compile(r"\b(?:(\w+)ed|(\w+))-(and|or)-(\w+)\b")
def _tone(c, k): if k >= 1: t = min(1.0, k - 1.0) return tuple(int(v + (255 - v) * t * .55) for v in c) return tuple(int(v * k) for v in c)
def _mix(a, b, t=.5): return tuple(int(x * (1 - t) + y * t) for x, y in zip(a, b))
def _colour_word(w): """one colour word (incl. -ish, -colored) -> rgb or None""" w = w.replace("colored", "").replace("coloured", "").strip("-") if w in COLOURS: return COLOURS[w] if w in ISH: return COLOURS[ISH[w]] if "-" in w: # reddish-brown, blue-grey, golden-yellow: mix, weighted to the last (head) colour cs = [_colour_word(x) for x in w.split("-")] if all(cs): c = cs[-1] for x in cs[:-1][::-1]: c = _mix(c, x, .38) return c return None
class Feats(dict): def __init__(self): super().__init__(size=1.0, sizes={}, cmp=[], like=[], col=[], pat=None, parts={}, form=set(), mat=None, hab=None, trace=[], src="gloss")
def _note(F, s): if s not in F["trace"]: F["trace"].append(s)
def _part(F, part, mods): d = F["parts"].setdefault(part, set()) d.update(mods) d.add("present")
def _tokens(text): # rule: a capitalised colour / size word inside a gloss is part of a proper name ("Black and Caspian seas", # "Red Sea", "Great Lakes", "White Nile"), not a description text = re.sub(r"(?<=\w[ (])([A-Z][a-z]+)\b", lambda m: "propername" if (m.group(1).lower() in COLOURS or m.group(1).lower() in SIZE) else m.group(1), text) text = text.lower().replace("’", "'") text = CUTS.sub(" ; ", text) toks = re.findall(r"[a-z][a-z\-']*[a-z]|[a-z]|\d+|[;,.():]", text) return [t[:-4] + "-like" if t.endswith("like") and "-" not in t and t[:-4] in LIKE_SHAPE else t for t in toks]
def _flush(F, run, target): """attach a run of modifiers to a region / part (target) or to the whole thing (target None)""" cols, tone, mods, num = [], 1.0, set(), None pat, mat = None, None tint = None for w in run: if w in TONE: tone *= TONE[w] continue c = _colour_word(w) if c is not None: if w in ISH and w != "dusky": # rule: "brownish grey", "reddish brown": an -ish colour tints the next colour (one colour, not two) tint = c if tint is None else _mix(tint, c) continue if tint is not None: c, tint = _mix(c, tint, .38), None cols.append(_tone(c, tone) if tone != 1.0 else c) tone = 1.0 continue if w in PATTERN_ADJ: pat = PATTERN_ADJ[w] if w in LENGTH: mods.add(LENGTH[w]) if w in BULK: mods.add(BULK[w]) if w in FORM: mods.add(FORM[w]) if w in NUM: num = NUM[w] if w.isdigit(): num = int(w) if w in MATERIAL: mat = MATERIAL[w] if w in SIZE and target is None: # rule: one size word per text (the strongest), not a product ("large ... large leaves") old = F["sizes"].get(F["src"], 1.0) if abs(SIZE[w] - 1) > abs(old - 1): F["sizes"][F["src"]] = SIZE[w] _note(F, "size:" + w) if tint is not None: cols.append(_tone(tint, tone) if tone != 1.0 else tint) if num is not None: mods.add("n=%d" % num) if target is None: if F["src"] == "name" and cols: # rule: a colour in the NAME with no region ("white oak", "black bear") is used only when the gloss names # no body colour; for trees it is the bark ("red pine", "white birch", "black walnut") F["col"].append(("namecol", cols[0])) cols = [] if mat: _set_mat(F, mat) for c in cols: F["col"].append((None, c)) if cols: _note(F, "colour:" + "/".join(w for w in run if _colour_word(w))) if pat: F["pat"] = (pat, None) _note(F, "pattern:" + pat) for m in mods & {"round", "flat", "deep", "elongate", "slender", "thick", "squat", "conical", "columnar", "cylindrical", "tubular", "bell", "star", "spreading", "drooping", "fluffy", "hairy", "spiny", "armored", "warty", "crested", "horned", "winged", "glow", "boxy", "domed", "branched", "spiral", "long", "short", "thin", "broad"}: F["form"].add(m) _note(F, "form:" + m) return if target in ("pattern",): return if target.startswith("pat:"): F["pat"] = (target[4:], cols[0] if cols else None) _note(F, "pattern:%s%s" % (target[4:], " coloured" if cols else "")) return if cols: F["col"].append((target, cols[0])) _note(F, "colour:%s" % target) if len(cols) > 1 and target in ("body", "flowers"): F["col"].append(("second", cols[1])) if pat and target in ("body", "flowers", "tail", "wings", "legs", "shell"): F["pat"] = (pat, None) if target != "tail" else F["pat"] if target == "tail": mods.add("ringed") _note(F, "pattern:" + pat) if target == "wood": _set_mat(F, "wood") if mat and target in ("body", "handle", "blade", "base", "roof", "lid"): if target == "body": _set_mat(F, mat) mods.add("mat=" + mat) _part(F, target, mods) _note(F, "part:%s%s" % (target, ("(" + ",".join(sorted(m for m in mods if m != "present")) + ")") if mods else ""))
MAT_RANK = {"gloss": 3, "name": 2, "anc": 1, "parts": 0}
def _set_mat(F, mat): """rule: the first material word of a text wins within it; the word's own gloss beats its name, which beats an ancestor's gloss ("sabot: a shoe carved from a single block of wood" over footwear's leather)""" r = MAT_RANK.get(F["src"], 0) if F["mat"] is None or r > F.get("mat_rank", -1): F["mat"], F["mat_rank"] = mat, r _note(F, "material:" + mat)
def read(text, F=None, src="gloss"): """Parse one piece of dictionary text into appearance features (Feats). src: gloss (the word's own gloss), anc (a gloss of an ancestor below the nearest taxon), name (the lemma names), parts (meronyms).""" F = F if F is not None else Feats() F["src"] = src low = text.lower() for m in CMP.finditer(low): ws = m.group(2).split(" ") if len(ws) > 1 and (ws[1] in STOPW or ws[1] in ("but", "and", "with")): ws = ws[:1] F["cmp"].append((m.group(1), " ".join(ws))) _note(F, "%s than %s" % m.groups()) for m in REF.finditer(CUTS.sub(lambda mm: mm.group(0) if mm.group(0).startswith("related") else " ; ", low)): ws = m.group(1).split(" ") while ws and (ws[-1] in STOPW or ws[-1] in ("but", "and", "in", "with", "except")): ws.pop() if ws: F["like"].append(" ".join(ws)) # "similar to the giraffe but smaller": a comparison against the referent tail = low[m.end():m.end() + 40] mc = re.match(r"[^;.]*?\b(smaller|larger|bigger|taller)\b", tail) if mc and " than " not in tail[:mc.end() + 6]: F["cmp"].append((mc.group(1), ws[-1])) _note(F, "%s than %s" % (mc.group(1), ws[-1])) toks = _tokens(text) run, neg = [], False i = 0 while i < len(toks): w = toks[i] nxt = toks[i + 1] if i + 1 < len(toks) else "" # ---- compounds if "-" in w and w not in FORM and w not in PATTERN_ADJ: ps = w.split("-") last = ps[-1] if last in ("shaped", "like", "form", "formed", "shape"): ref = "-".join(ps[:-1]) if ref in LIKE_SHAPE: F["form"].add(LIKE_SHAPE[ref]) _note(F, "form:%s(%s-%s)" % (LIKE_SHAPE[ref], ref, last)) elif ref in FORM: F["form"].add(FORM[ref]) else: F["like"].append(ref) i += 1 continue if last in ED_STEM or last.rstrip("s") in PARTS and len(ps) == 2 and ps[0] in COLOURS: part = ED_STEM.get(last) or PARTS[last.rstrip("s")] head = ps[:-1] if "and" in head or "or" in head: head = [h for h in head if h not in ("and", "or")] if part == "legs" and head == ["web"]: _part(F, "legs", {"webbed"}) i += 1 continue if part == "base" and head == ["flat"]: F["form"].add("flat_bottom") i += 1 continue _flush(F, [h for h in head], part) i += 1 continue if last in ("colored", "coloured", "tinted", "toned", "hued"): c = _colour_word("-".join(ps[:-1])) if c: run.append("-".join(ps[:-1])) i += 1 continue if "and" in ps or "or" in ps: # crimson-and-grey, black-and-white cs = [x for x in ps if x not in ("and", "or")] if all(_colour_word(x) for x in cs): run.extend(cs) i += 1 continue if _colour_word(w): run.append(w) i += 1 continue if ps[0] in NUM and last in PARTS: _flush(F, run + [ps[0]], PARTS[last]) run = [] i += 1 continue # any other compound ("backward-curving", "much-branched", "slender-bodied"): its known pieces modify for x in ps: if x in TONE or x in PATTERN_ADJ or x in LENGTH or x in BULK or x in FORM or x in NUM or x in SIZE: run.append(x) i += 1 continue if w in ABSENT: F["parts"].setdefault(ABSENT[w], set()).add("absent") _note(F, "absent:" + ABSENT[w]) i += 1 continue if w in NEG: neg = True if run: _flush(F, run, None) run = [] i += 1 continue # ---- pattern nouns: "stripes", "black spots" if w in PATTERN_NOUN and not (w in ("band", "bands") and nxt in PARTS): _flush(F, run, "pat:" + PATTERN_NOUN[w]) run = [] i += 1 continue if w in PARTS: # "tail feathers", "tail fin": the first part noun of a pair names the region part = PARTS[w] if neg: F["parts"].setdefault(part, set()).add("absent") _note(F, "absent:" + part) neg = False run = [] else: if part == "body" and w in ("feathers", "hair") and i > 0 and toks[i - 1] in PARTS: run = [] i += 1 continue _flush(F, run, part) run = [] i += 1 continue if w in HAB and F["src"] in ("gloss", "name") and (F["hab"] is None or F["src"] == "name"): F["hab"] = HAB[w] _note(F, "habitat:" + w) if w in (";", ",", ".", "(", ")", ":") or (w in STOPW and not (w in ("and", "or", "to") and run and _colour_word(run[-1]))): if run: _flush(F, run, None) run = [] if w in (";", ".", ",", "(", ")", ":", "with", "having", "but", "has", "have", "bearing"): neg = False i += 1 continue if w in ("and", "or", "to"): if w in ("or", "to") and run and _colour_word(run[-1]): # rule: "orange to scarlet", "blue or violet": alternatives, keep the first colour only j = i + 1 while j < len(toks) and (toks[j] in TONE or _colour_word(toks[j]) or toks[j] in ( "or", "to", "sometimes", "occasionally", "often", "rarely", "usually", "else", "even")): j += 1 i = j continue i += 1 continue if w in COLOUR_NOUNS and not (nxt in PARTS or nxt in PATTERN_NOUN or _colour_word(nxt) or nxt in ("and", "or")): # rule: orange / plum / rose / cherry / olive... are colours only right before a part, a pattern or another # colour ("olive back", "rose petals"); otherwise they name the fruit / flower ("osage orange") i += 1 continue if F["src"] == "name" and i == len(toks) - 1 or F["src"] == "name" and nxt == ";": i += 1 # rule: the last word of a name is the thing itself ("ground cherry", "sea lavender") continue known = (w in TONE or _colour_word(w) or w in PATTERN_ADJ or w in LENGTH or w in BULK or w in FORM or w in NUM or w.isdigit() or w in MATERIAL or w in SIZE) if known and neg: pass # rule: "less prickly", "not spotted", "no long tail": negated modifiers are dropped elif known: run.append(w) elif run and len(run) > 6: _flush(F, run, None) run = [] i += 1 if run: _flush(F, run, None) return F
# ------------------------------------------------------------------ gathering text from WordNetdef texts_for(s, names, TAXA, lemma): """The dictionary text that describes the word beyond its nearest hand-written ancestor: the lemma names, and the gloss + examples + part / substance meronyms of every synset on the path below the deepest ancestor taxon.""" from nltk.corpus import wordnet as wn deep = 0 for i, n in enumerate(names[:-1]): if n in TAXA: deep = i out = [] for n in names[deep + 1:]: try: syn = wn.synset(n) except Exception: continue own = n == names[-1] out.append(("gloss" if own else "anc", syn.definition())) if own: for e in syn.examples()[:2]: out.append(("example", e)) mer = [m.lemma_names()[0].replace("_", " ") for m in syn.part_meronyms()] if mer: out.append(("parts", "with " + ", ".join(mer))) sub = [m.lemma_names()[0].replace("_", " ") for m in syn.substance_meronyms()] if sub: out.append(("made of", " ".join(x for x in sub if x in MATERIAL))) # rule: only the word's own name is read (synonyms such as "yellow locust" / "giant granadilla" contradict it) out.append(("name", (lemma or s.lemma_names()[0]).replace("_", " "))) return out
def features(s, names, TAXA, lemma): F = Feats() for src, t in texts_for(s, names, TAXA, lemma): if not t: continue if src == "example": # rule: example sentences only contribute what is attached to the word's own name ("the okapi's ...") continue read(t, F, src if src in ("gloss", "anc", "name") else "parts") return F
# ------------------------------------------------------------------ features -> family parametersREGION = { "quadruped": dict(body="color", under="belly", breast="bib", throat="bib", head="mask", face="mask", snout="muzzle", legs="sock", tail="tail_col", ears="ear_col", mane="mane_col", back="back_stripe", horns="horn_col", antlers="horn_col", tusks="tusk_col", spines="spike_col", rump="back_stripe"), "primate": dict(body="color", face="face", head="face", under="belly", breast="belly", throat="belly", tail="tail_col", ears="ear_col", mane="mane_col", snout="muzzle", second="belly"), "bat": dict(body="color", wings="wing_col", face="face", under="belly"), "bird": dict(body="color", back="color", under="color2", breast="color2", throat="color2", head="head_col", face="mask_col", wings="wing_col", tail="tail_col", bill="beak_col", legs="leg_col", crest="crest_col", second="color2", rump="tail_col"), "fish": dict(body="color", back="color", under="color2", fins="fin_col", tail="fin_col", second="color2"), "pinniped": dict(body="color", under="color2", second="color2"), "arthropod": dict(body="color", wings="wing_col", second="color2", under="color2", eyes="eye_col"), "mollusc": dict(body="color", shell="shell_col", second="color2"), "radial": dict(body="color", second="color2"), "worm": dict(body="color", second="color2"), "snake": dict(body="color", under="color2", second="color2", back="color"), "lizard": dict(body="color", under="color2", second="color2", back="color"), "frog": dict(body="color", under="color2", second="color2", back="color", eyes="eye_col"), "turtle": dict(body="shell_col", shell="shell_col", head="skin_col", legs="skin_col"), "dinosaur": dict(body="color", second="color2", under="color2"), "tree": dict(body="color", leaves="color", flowers="flowers", fruit="fruit", nuts="fruit", bark="bark", stem="bark"), "shrub": dict(body="color", leaves="color", fruit="berries", nuts="berries", flowers="berries"), "flower": dict(body="color", flowers="color", centre="centre", stem="stem_col", second="color2"), "cactus": dict(body="color", flowers="flower", spines="spines"), "vine": dict(body="color", leaves="color", fruit="fruit"), "mushroom": dict(body="color", head="color", stem="stem_col"), "grass": dict(body="color", leaves="color", flowers="head_col", fruit="head_col", head="head_col"), "rosette": dict(body="color", leaves="color", flowers="centre", centre="centre"), "building": dict(body="wall_col", roof="roof_col", door="door_col", tower="tower_col", dome="roof_col"), "vessel": dict(body="color", second="color2", base="base_col"), "vehicle": dict(body="color", roof="roof_col", second="stripe"), "boat": dict(body="color", deck="deck_col", sails="sail_col", second="hull2", chimney="funnel_col"), "aircraft": dict(body="color", second="accent"), "rocket": dict(body="color", second="body2"), "cycle": dict(body="color"), "furniture": dict(body="color", cushion="fabric_col"), "tool": dict(body="color", blade="head_col", handle="handle_col"), "instrument": dict(body="color"),}PATTERNED = {"turtle", "quadruped", "primate", "bird", "fish", "arthropod", "lizard", "snake", "frog", "worm", "mollusc", "radial", "dinosaur", "pinniped", "vessel"}GREENISH = lambda c: c[1] > c[0] * 1.05 and c[1] > c[2] * 1.05
def _num(mods, default): for m in mods: if m.startswith("n="): return int(m[2:]) return default
def _contrast(c): lum = .3 * c[0] + .59 * c[1] + .11 * c[2] return (35, 30, 28) if lum > 120 else (238, 232, 220)
def apply(fam, base, F, defaults, ref_params=None): """Map features to parameter overrides for family `fam`. base: merged ancestor parameters (incl. META facts). defaults: the family's defaults. Returns (overrides dict, notes list).""" cur = dict(defaults) cur.update({k: v for k, v in base.items()}) out, notes = {}, []
def g(k): return out.get(k, cur.get(k))
def setp(k, v, why): if k in defaults or k in ("color", "height", "setting", "flying", "natural_colors"): if g(k) != v: out[k] = v notes.append("%s=%s (%s)" % (k, _short(v), why))
def mul(k, f, why, lo=None, hi=None): v = g(k) if isinstance(v, (int, float)) and not isinstance(v, bool) and k in defaults: nv = v * f if lo is not None: nv = max(lo, nv) if hi is not None: nv = min(hi, nv) setp(k, round(nv, 4), why)
# 0. resemblance: "similar to a Pekingese", "eel-shaped": the referent's own parameters (same family only) if ref_params: for k, v in ref_params.items(): if k in defaults or k == "color": setp(k, v, "like " + ref_params.get("_ref", "?")) parts, form = F["parts"], F["form"] animalish = fam in ("quadruped", "primate", "bat", "bird", "fish", "pinniped", "arthropod", "mollusc", "radial", "worm", "snake", "lizard", "frog", "turtle", "dinosaur", "creature") plant = fam in ("tree", "shrub", "flower", "grass", "rosette", "cactus", "vine", "mushroom", "leaf", "bunch", "fruit")
# 1. size / comparisons -> height h = float(base.get("height", 1.0)) sz = F["sizes"] k = sz.get("gloss", sz.get("name", sz.get("anc", 1.0))) * F["size"] for d, ref in F["cmp"]: rh = _ref_height(ref) if rh: k_ = {"smaller": .6, "shorter": .6, "larger": 1.4, "bigger": 1.4, "taller": 1.4}[d] * rh / max(h, 1e-3) k = max(.2, min(5.0, k_)) notes.append("height from '%s than %s'" % (d, ref)) if abs(k - 1.0) > .03: k = max(.25, min(3.0, k)) setp("height", round(h * k, 3), "size words x%.2f" % k)
# 2. colours per region; first unregioned colour = main, second = 'second' regmap = REGION.get(fam, dict(body="color")) seen_main = False has_body = any(r in (None, "body") for r, c in F["col"]) main_c = None best_pr = {} for reg, c in F["col"]: if reg == "namecol": if has_body: continue reg = "bark" if fam == "tree" else "body" if reg is None: reg = "second" if seen_main else "body" if reg == "second" and c == main_c: continue if reg in ("body",): seen_main, main_c = True, c key = regmap.get(reg) if key is None and reg in ("second",) and fam in PATTERNED and F["pat"] is None: F["pat"] = ("patches", c) continue if key is None: continue if plant and key == "color" and fam in ("tree", "shrub", "vine") and not GREENISH(c) and reg != "leaves": # rule: a tree's / shrub's leaves are green; a colour said of the whole plant ("bright red in autumn", # "black pulp") is too vague to place, except a name colour, which is the bark (handled above) continue if key in ("mask", "sock", "back_stripe", "bib", "belly", "muzzle", "ear_col", "tail_col", "horn_col", "mane_col", "tusk_col", "spike_col", "face", "wing_col", "head_col", "color2", "tip_col", "beak_col", "leg_col", "crest_col", "mask_col", "fin_col", "shell_col", "skin_col", "flowers", "fruit", "bark", "berries", "centre", "stem_col", "head_col", "wall_col", "roof_col", "door_col", "tower_col", "base_col", "deck_col", "sail_col", "hull2", "funnel_col", "accent", "body2", "fabric_col", "handle_col", "eye_col", "flower", "stripe", "spines") or key == "color": if key in defaults or key == "color": # rule: a colour said of the named region ("white flowers") beats one said of the whole ("pink shading") pr = 2 if reg not in ("body", "second") else 1 if pr >= best_pr.get(key, 0): best_pr[key] = pr setp(key, tuple(c), "colour of " + reg) if F["pat"] and fam in PATTERNED and "pat" in defaults: kind, c2 = F["pat"] main = g("color") or (150, 120, 90) sc = {"stripes": 1.5, "spots": 2.0, "patches": 1.2, "bands": 1.6, "rosettes": 1.5, "checker": 1.5, "scales": 2.0}[kind] setp("pat", (kind, tuple(c2) if c2 else _contrast(main), sc), "pattern words")
# 3. habitat -> setting (animals and plants only; a hand setting is kept when it is already specific) if F["hab"] and (animalish or plant): st = F["hab"] if st == "sea": st = "underwater" if fam in ("fish", "radial", "mollusc", "worm") else "water" if fam in ("pinniped", "turtle") else "beach" if st == "water" and fam in ("fish",): st = "underwater" if st == "savanna" and plant: st = "field" if st == "forest" and fam in ("fish",): st = None if st and base.get("setting") in (None, "field", "garden", "table", "room", "savanna", "forest"): setp("setting", st, "habitat")
# 4. material mat = F["mat"] if mat and not animalish and not plant: col0, spec, rough = MAT_LOOK.get(mat, (None, None, None)) explicit_col = any(r in (None, "body") for r, c in F["col"]) if fam == "building": m2 = {"wood": "wood", "logs": "logs", "stone": "stone", "marble": "marble", "brick": "brick", "concrete": "concrete", "glass": "glass", "metal": "metal", "canvas": "canvas", "fabric": "canvas", "thatch": "thatch", "mud": "mud", "gold": "gold", "bronze": "bronze", "ice": "snow"}.get(mat) if m2: setp("material", m2, "material word") if mat == "thatch": setp("roof", "thatch", "thatched") elif fam == "furniture": m2 = {"wood": "wood", "metal": "metal", "brass": "gold", "gold": "gold", "glass": "glass", "leather": "leather", "fabric": "fabric", "wicker": "wicker", "bamboo": "wicker", "plastic": "plastic", "stone": "stone", "marble": "stone"}.get(mat) if m2: setp("material", m2, "material word") if m2 in ("fabric", "leather"): setp("upholstered", 1, "material word") elif fam in ("vehicle", "boat", "aircraft", "rocket"): m2 = {"wood": "wood", "bamboo": "wood", "metal": "metal", "brass": "metal", "copper": "metal", "silver": "metal", "gold": "metal", "canvas": "matte", "fabric": "matte", "leather": "matte", "rubber": "matte", "wicker": "wood", "paper": "matte"}.get(mat) if m2: setp("mat", m2, "material word") elif fam == "tool": m2 = {"wood": "wood", "bamboo": "wood", "metal": "metal", "leather": "leather", "plastic": "plastic"}.get(mat) if m2: setp("handle_mat", m2, "material word") elif fam == "vessel": if mat == "glass": setp("glass", 1, "glass") elif mat == "wicker": setp("weave", 1, "woven") elif "glass" in defaults and g("glass"): setp("glass", 0, "not glass") if spec is not None: if "spec" in defaults: setp("spec", spec, "material " + mat) setp("rough", rough, "material " + mat) if not explicit_col and fam not in ("building",) and col0: setp("color", col0, "material " + mat)
# 5. parts and shape words, per family fn = PART_RULES.get(fam) if fn: fn(parts, form, g, setp, mul, defaults) return out, notes
def _short(v): if isinstance(v, tuple) and len(v) == 3 and all(isinstance(x, int) for x in v): return "#%02x%02x%02x" % v s = repr(v) return s if len(s) < 40 else s[:37] + "..."
def has(parts, p, *mods): m = parts.get(p) if not m or "absent" in m: return False return all(x in m for x in mods) if mods else True
def absent(parts, p): return "absent" in parts.get(p, ())
def _quad_rules(parts, form, g, setp, mul, D): if has(parts, "neck", "long"): mul("neck_len", 2.4, "long neck", hi=.5) setp("neck_ang", 68, "long neck") elif has(parts, "neck", "short"): mul("neck_len", .5, "short neck") if has(parts, "legs", "long"): mul("leg_len", 1.4, "long legs", hi=.6) elif has(parts, "legs", "short"): mul("leg_len", .6, "short legs") if "slender" in form or "thin" in form or "elongate" in form: mul("girth", .85, "slender") if "elongate" in form or ("long" in form and "body" not in parts): mul("body_len", 1.25, "elongate") if "thick" in form or "round" in form or has(parts, "body", "thick"): mul("girth", 1.18, "stout") if absent(parts, "tail"): setp("tail", 0.0, "tailless") setp("tail_kind", "stub", "tailless") elif parts.get("tail"): m = parts["tail"] if "long" in m: mul("tail", 1.7, "long tail", hi=.9) if g("tail_kind") == "stub": setp("tail_kind", "thin", "long tail") elif "short" in m or "small" in m: mul("tail", .4, "short tail") if "bushy" in m or "fluffy" in m or "thick" in m: setp("tail_kind", "bushy", "bushy tail") if "crested" in m: setp("tail_kind", "tufted", "tufted tail") if "ringed" in m: setp("tail_rings", (40, 35, 32), "ringed tail") if "prehensile" in m: setp("tail_curl", 60, "prehensile tail") if parts.get("ears"): m = parts["ears"] if "long" in m: setp("ears", "long", "long ears") elif "drooping" in m: setp("ears", "floppy", "drooping ears") elif "round" in m: setp("ears", "round", "rounded ears") elif "pointed" in m or "erect" in m: setp("ears", "pointed", "pointed ears") if "big" in m or "broad" in m: mul("ear_size", 1.5, "large ears") elif "small" in m or "short" in m: mul("ear_size", .6, "small ears") if parts.get("snout"): m = parts["snout"] if "long" in m or "elongate" in m or "pointed" in m: mul("snout", 1.6, "long snout", hi=.25) setp("snout_r", .42, "long snout") elif "short" in m or "flat" in m or "broad" in m: mul("snout", .5, "short snout") if has(parts, "antlers"): setp("horns", "palmate" if "palmate" in parts["antlers"] or "broad" in parts["antlers"] else "antlers", "antlers") elif has(parts, "horns") or "horned" in form: m = parts.get("horns", set()) kind = "ram" if "spiral" in m else g("horns") if kind in (None, "none"): kind = "curved" if "curved" in m else "straight" setp("horns", kind, "horns") if "long" in m or "big" in m: mul("horn_len", 1.5, "long horns") elif "short" in m or "small" in m: mul("horn_len", .6, "short horns") elif absent(parts, "horns"): setp("horns", "none", "hornless") if has(parts, "tusks"): setp("tusks", max(.5, g("tusks") or 0), "tusks") if has(parts, "trunk") and not has(parts, "trunk", "small"): setp("trunk", max(.4, g("trunk") or 0), "trunk / proboscis") if has(parts, "hump"): setp("hump", max(.6, g("hump") or 0), "hump") if _num(parts["hump"], 1) == 2: setp("humps", 2, "two humps") if has(parts, "mane"): setp("mane", g("mane") or "neck", "mane") if has(parts, "crest"): setp("mane", g("mane") or "crest", "crest") if has(parts, "beard"): setp("beard", max(.5, g("beard") or 0), "beard") if has(parts, "spines") or "spiny" in form: setp("spikes", max(1.0, g("spikes") or 0), "spines / quills") if "armored" in form or has(parts, "shell"): setp("armor", max(1.0, g("armor") or 0), "armour") if "fluffy" in form or "hairy" in form and "fluffy" in form: setp("fluffy", max(.6, g("fluffy") or 0), "shaggy / woolly") if has(parts, "legs", "webbed"): setp("feet", "paws", "webbed")
def _prim_rules(parts, form, g, setp, mul, D): if parts.get("arms") and "long" in parts["arms"]: mul("arm_len", 1.3, "long arms", hi=.6) if absent(parts, "tail"): setp("tail", 0.0, "tailless") elif parts.get("tail"): m = parts["tail"] if "long" in m or "prehensile" in m: setp("tail", max(.6, g("tail") or 0), "long tail") elif "short" in m: setp("tail", .15, "short tail") if "bushy" in m: setp("tail_kind", "bushy", "bushy tail") if "ringed" in m: setp("tail_rings", (40, 35, 32), "ringed tail") if has(parts, "mane") or has(parts, "beard"): setp("mane", g("mane") or "cape", "mane / ruff") if has(parts, "snout", "long"): mul("snout", 3.0, "long muzzle", hi=.12) if parts.get("ears"): if "big" in parts["ears"] or "long" in parts["ears"]: mul("ear_size", 1.5, "large ears") if "crested" in parts["ears"]: setp("ears", "tufts", "ear tufts") if has(parts, "head", "big"): mul("head", 1.25, "large head")
def _bird_rules(parts, form, g, setp, mul, D): if has(parts, "neck", "long"): setp("neck", max(.3, g("neck") or 0), "long neck") setp("neck_s", .5, "long neck") if has(parts, "legs", "long"): mul("leg", 2.2, "long legs", hi=.6) elif has(parts, "legs", "short"): mul("leg", .6, "short legs") if has(parts, "legs", "webbed"): setp("feet", "webbed", "webbed feet") if parts.get("bill"): m = parts["bill"] if "hooked" in m or "curved" in m and "long" not in m: setp("beak_shape", "hook", "hooked bill") elif "flat" in m or "broad" in m: setp("beak_shape", "flat", "flat bill") elif "big" in m or "thick" in m: setp("beak_shape", "big", "heavy bill") if "long" in m: mul("beak", 1.9, "long bill", hi=.45) setp("beak_w", .045, "long bill") if "curved" in m: setp("droop", .5, "decurved bill") elif "short" in m or "small" in m: mul("beak", .6, "short bill") if "thick" in m or "big" in m: mul("beak_w", 1.4, "stout bill") if has(parts, "crest") or "crested" in form: setp("crest", max(.2, g("crest") or 0), "crest") if absent(parts, "wings"): setp("can_fly", 0, "flightless") if parts.get("tail"): m = parts["tail"] if "forked" in m: setp("tail_kind", "fork", "forked tail") elif "fan" in m or "round" in m and "long" not in m: setp("tail_kind", "fan", "fan / rounded tail") if "long" in m: mul("tail", 1.9, "long tail", hi=.7) if "crested" in m or "drooping" in m: setp("tail_kind", "streamers", "plumes") elif "short" in m: mul("tail", .5, "short tail") if "round" in form or "thick" in form: b = g("body") if isinstance(b, (tuple, list)): setp("body", (b[0], b[1] * 1.12, b[2] * 1.12), "plump") if "slender" in form or "elongate" in form: b = g("body") if isinstance(b, (tuple, list)): setp("body", (b[0] * 1.12, b[1] * .88, b[2] * .88), "slender") if "fluffy" in form: setp("fluffy", .6, "downy")
def _fish_rules(parts, form, g, setp, mul, D): if "elongate" in form or "slender" in form or "long" in form and "thin" in form: setp("shape", "eel" if "slender" in form and "elongate" in form else g("shape"), "eel-like") mul("depth", .7, "elongate", lo=.1) if "deep" in form: setp("shape", "deep", "compressed / deep-bodied") elif "flat" in form: setp("shape", "flat", "flattened") elif "round" in form: setp("shape", "round", "rounded / globular") if parts.get("snout"): m = parts["snout"] if "long" in m or "pointed" in m: setp("snout", "beak", "long snout") elif "flat" in m or "broad" in m or "short" in m: setp("snout", "blunt", "blunt snout") if has(parts, "bill"): setp("snout", "bill", "bill / beak") if has(parts, "whiskers"): setp("barbels", 1, "barbels") if has(parts, "spines") or "spiny" in form: setp("spikes", max(.5, g("spikes") or 0), "spines") if parts.get("dorsal") or parts.get("fins"): m = parts.get("dorsal", set()) | parts.get("fins", set()) if "long" in m: setp("dorsal", "long", "long dorsal fin") elif "big" in m: setp("dorsal", "tall", "large fin") if parts.get("tail"): m = parts["tail"] if "forked" in m: setp("tail", "fork", "forked tail") elif "round" in m: setp("tail", "round", "rounded tail") elif "long" in m or "thin" in m: setp("tail", "whip", "whiplike tail") if has(parts, "teeth", "big"): setp("mouth", 1, "large teeth") if has(parts, "tusks"): setp("tusk", .5, "tusk") if "glow" in form: pass
def _lizard_rules(parts, form, g, setp, mul, D): if has(parts, "crest") or "crested" in form: setp("crest", max(.5, g("crest") or 0), "crest") if has(parts, "frill"): setp("frill", .6, "frill") if has(parts, "dewlap"): setp("dewlap", .6, "dewlap") if has(parts, "horns") or "horned" in form: setp("horns", max(.5, g("horns") or 0), "horns") if has(parts, "tail", "long"): mul("tail", 1.4, "long tail") elif has(parts, "tail", "short"): mul("tail", .5, "short tail") if has(parts, "tail", "prehensile"): setp("tail_curl", .6, "prehensile tail") if "spiny" in form or has(parts, "spines"): setp("scutes", 1, "spiny") if has(parts, "legs", "short"): mul("leg", .6, "short legs") elif has(parts, "legs", "long"): mul("leg", 1.4, "long legs") if "slender" in form or "elongate" in form: mul("girth", .8, "slender") if "thick" in form or "round" in form: mul("girth", 1.25, "stout")
def _snake_rules(parts, form, g, setp, mul, D): if has(parts, "hood") or has(parts, "head", "hood"): setp("hood", .6, "hood") if "thick" in form or has(parts, "body", "thick"): mul("thick", 1.35, "heavy-bodied") if "slender" in form or "thin" in form: mul("thick", .7, "slender")
def _arth_rules(parts, form, g, setp, mul, D): if has(parts, "wings") or "winged" in form: if g("wings") in (None, "none"): setp("wings", "clear", "winged") m = parts.get("wings", set()) if "long" in m or "big" in m: mul("wing_size", 1.3, "large wings") elif absent(parts, "wings"): setp("wings", "none", "wingless") if parts.get("antennae"): m = parts["antennae"] if "long" in m: setp("antennae", "long", "long antennae") mul("ant_len", 1.8, "long antennae", hi=.6) elif "short" in m: mul("ant_len", .5, "short antennae") if "crested" in m or "branched" in m: setp("antennae", "feather", "feathery antennae") if has(parts, "horns") or "horned" in form: setp("horn", max(.3, g("horn") or 0), "horn") if has(parts, "claws"): mul("claws", 1.5, "pincers", hi=2.5) if has(parts, "stinger"): setp("stinger", 1, "sting") if has(parts, "trunk") or has(parts, "snout", "long"): setp("proboscis", max(.3, g("proboscis") or 0), "snout / proboscis") if has(parts, "legs", "long"): mul("leg", 1.6, "long legs", hi=.6) if "hairy" in form or "fluffy" in form: setp("fuzzy", 1, "hairy") if "glow" in form: setp("glow", .7, "luminous")
def _turtle_rules(parts, form, g, setp, mul, D): if has(parts, "flippers"): setp("flippers", 1, "flippers") if "domed" in form or has(parts, "shell", "domed"): mul("dome", 1.3, "domed shell", hi=1.0) if "flat" in form or has(parts, "shell", "flat"): mul("dome", .55, "flat shell") if has(parts, "neck", "long"): mul("neck", 2.0, "long neck") if "spiny" in form or has(parts, "spines"): setp("spikes", 1, "spiny")
def _frog_rules(parts, form, g, setp, mul, D): if "warty" in form: setp("warts", 1, "warty")
def _worm_rules(parts, form, g, setp, mul, D): if has(parts, "legs"): setp("legs", 1, "legs") if "hairy" in form or has(parts, "spines"): setp("hairs", 1, "bristles")
def _dino_rules(parts, form, g, setp, mul, D): if has(parts, "neck", "long"): mul("neck", 1.6, "long neck") if has(parts, "horns") or "horned" in form: setp("horns", max(1.2, g("horns") or 0), "horns") if has(parts, "tail", "long"): mul("tail", 1.4, "long tail") if has(parts, "body") and "feathers" in parts.get("body", ()): setp("feathers", 1, "feathered")
def _tree_rules(parts, form, g, setp, mul, D): if "conical" in form or "columnar" in form and g("shape") not in ("conifer", "spire"): setp("shape", "conifer" if "conical" in form else "oval", "conical / columnar") if "columnar" in form: mul("crown_w", .65, "columnar") elif "spreading" in form or has(parts, "branches", "spreading"): setp("shape", "umbrella" if g("shape") != "conifer" else "conifer", "spreading crown") mul("crown_w", 1.2, "spreading crown") elif "drooping" in form or has(parts, "branches", "drooping"): setp("shape", "weeping", "weeping / drooping branches") elif "round" in form and g("shape") not in ("conifer", "palm"): setp("shape", "round", "rounded crown") if parts.get("leaves") and ("needles" in parts["leaves"] or "thin" in parts["leaves"]) and g("shape") == "round": setp("shape", "conifer", "needles") if has(parts, "bark") or has(parts, "stem"): pass if "slender" in form or "thin" in form: mul("trunk_r", .75, "slender trunk") if "thick" in form: mul("trunk_r", 1.4, "stout trunk") if has(parts, "fruit") and not g("fruit"): setp("fruit", (200, 60, 40), "bears fruit") elif has(parts, "nuts") and not g("fruit"): setp("fruit", (125, 85, 45), "bears nuts / pods / cones") if has(parts, "flowers") and not g("flowers") and not g("fruit") and not has(parts, "flowers", "small"): m = parts["flowers"] if "big" in m or "showy" in m: setp("flowers", (250, 245, 240), "showy flowers")
def _shrub_rules(parts, form, g, setp, mul, D): if "spiny" in form or has(parts, "spines"): setp("thorny", 1, "spiny / thorny") if "drooping" in form: setp("shape", "spray", "arching branches") if "erect" in form or "columnar" in form: setp("shape", "spray", "erect stems") if "round" in form: setp("shape", "mound", "rounded") if has(parts, "fruit") and not g("berries"): setp("berries", (190, 40, 50), "bears berries") if has(parts, "flowers") and not g("berries"): m = parts["flowers"] if "big" in m: setp("berries", (250, 245, 245), "showy flowers") setp("berry_r", .05, "showy flowers")
def _flower_rules(parts, form, g, setp, mul, D): m = parts.get("flowers", set()) allf = m | form if "ray" in allf: setp("bloom", "ray", "daisy-like flowers") elif "tubular" in allf: setp("bloom", "trumpet", "tubular / trumpet flowers") elif "bell" in allf: setp("bloom", "bell", "bell-shaped flowers") elif "star" in allf: setp("bloom", "star", "star-shaped flowers") elif "round" in m: setp("bloom", "ball", "globular flower heads") if "spike" in allf or has(parts, "fspike") or has(parts, "flowers", "elongate") or "long" in m and "thin" not in m and g("bloom") == "ray": setp("bloom", "spike", "flower spikes") if "big" in m or "showy" in m: mul("size", 1.3, "large flowers", hi=1.8) elif "small" in m: mul("size", .75, "small flowers") if "drooping" in allf: setp("face", .2, "nodding flowers") if has(parts, "stem", "long") or "tall" in form or "erect" in form: pass if _num(m, 0) > 1 and "petals" not in m: setp("stems", min(5, _num(m, 1)), "several flowers")
def _cactus_rules(parts, form, g, setp, mul, D): if "round" in form or "globular" in form: setp("form", "ball", "globular") elif "columnar" in form or "cylindrical" in form: setp("form", "column", "columnar") if has(parts, "flowers") and not g("flower"): setp("flower", (235, 80, 130), "flowers")
def _mushroom_rules(parts, form, g, setp, mul, D): if "conical" in form or "bell" in form: setp("cap", "cone" if "conical" in form else "bell", "cap shape") elif "flat" in form: setp("cap", "flat", "flat cap") elif "tubular" in form: setp("cap", "funnel", "funnel cap") if has(parts, "stem", "long") or has(parts, "stem", "thin"): mul("stem_h", 1.4, "long stalk")
def _building_rules(parts, form, g, setp, mul, D): if has(parts, "tower"): setp("towers", g("towers") or ("corners" if _num(parts["tower"], 1) > 1 else "end"), "towers") if "pointed" in parts["tower"] or "conical" in parts["tower"]: setp("tower_roof", "spire", "spire") if has(parts, "dome") or "domed" in form: setp("roof", "dome", "dome") if has(parts, "columns"): setp("columns", max(4, _num(parts["columns"], 6)), "columns") if has(parts, "chimney"): setp("chimney", 1, "chimney") if parts.get("roof"): m = parts["roof"] if "flat" in m: setp("roof", "flat", "flat roof") elif "pointed" in m or "conical" in m: setp("roof", "pyramid", "pointed roof") if any(x.startswith("mat=thatch") for x in m): setp("roof", "thatch", "thatched roof") if has(parts, "sails"): setp("sails", 1.0, "sails") if absent(parts, "windows"): setp("win_cols", 0, "windowless") if "tall" in form or "long" in form and "boxy" not in form: mul("storeys", 2.0, "tall") if "round" in form or "cylindrical" in form: setp("shape", "round", "round")
def _vessel_rules(parts, form, g, setp, mul, D): if has(parts, "handle"): n = _num(parts["handle"], 2 if "n=2" in parts["handle"] else 1) setp("handles", max(n, g("handles") or 0), "handle(s)") if "long" in parts["handle"]: setp("handle", "long", "long handle") elif absent(parts, "handle"): setp("handles", 0, "no handle") if has(parts, "spout"): setp("spout", g("spout") or ("tea" if "long" in parts["spout"] or "curved" in parts["spout"] else "lip"), "spout") if has(parts, "lid"): setp("lid", g("lid") or ("cork" if "stopper" in parts["lid"] else "dome"), "lid / cover") setp("knob", 1, "lid knob") elif absent(parts, "lid"): setp("lid", None, "open") if has(parts, "legs"): setp("legs", max(3, _num(parts["legs"], 3)), "legs / feet") if "tall" in form or "slender" in form or "cylindrical" in form or "elongate" in form or has(parts, "neck", "long"): mul("sx", .78, "tall / slender") if "flat" in form or "squat" in form or "broad" in form or "round" in form and "tall" not in form: mul("sx", 1.25, "wide / round")
def _vehicle_rules(parts, form, g, setp, mul, D): if has(parts, "tracks"): setp("tracks", 1, "tracks") if has(parts, "tower") or has(parts, "dome") and "turret" in D: setp("turret", 1, "turret") if has(parts, "barrel"): setp("gun", max(.5, g("gun") or 0), "gun") if has(parts, "chimney"): setp("boiler", 1, "smokestack") if "boxy" in form: setp("roof", max(.95, g("roof") or 0), "boxy") if "long" in form or "elongate" in form: mul("length", 1.25, "long") if has(parts, "wheels", "big"): mul("wheel_r", 1.3, "large wheels") if has(parts, "wheels"): n = _num(parts["wheels"], 0) if n == 2 and "axle_x" in D: pass
def _boat_rules(parts, form, g, setp, mul, D): if has(parts, "sails") or has(parts, "masts"): n = _num(parts.get("masts", set()) | parts.get("sails", set()), 1) setp("masts", max(g("masts") or 0, min(n, 4)), "sails / masts") if not g("sail"): setp("sail", "square" if "boxy" in parts.get("sails", ()) else "tri", "sails") if has(parts, "oars"): setp("oars", 1, "oars") setp("open", 1, "rowed boat") if has(parts, "chimney"): setp("funnels", max(1, _num(parts["chimney"], 1)), "funnel") if "flat" in form or "flat_bottom" in form: setp("flat", 1, "flat-bottomed") if "long" in form or "elongate" in form: mul("length", 1.2, "long") if "thin" in form: mul("beam", .8, "narrow") if has(parts, "cabin"): setp("wheelhouse", g("wheelhouse") or (.3, .3), "cabin") if has(parts, "deck"): n = _num(parts["deck"], 1) if n > 1: setp("decks", tuple([.3] * min(n - 1, 3)), "decks")
def _aircraft_rules(parts, form, g, setp, mul, D): if has(parts, "propeller"): setp("prop", 1, "propeller") if has(parts, "engine"): setp("engines", min(4, _num(parts["engine"], g("engines") or 2)), "engines") if has(parts, "wings") and _num(parts["wings"], 1) == 2: setp("biplane", 1, "two pairs of wings")
def _furniture_rules(parts, form, g, setp, mul, D): if has(parts, "cushion") or "fluffy" in form: setp("upholstered", 1, "upholstered / padded") if has(parts, "armrests") or has(parts, "arms"): setp("arms", 1, "arms") elif absent(parts, "armrests"): setp("arms", 0, "armless") if absent(parts, "backrest"): setp("back_h", 0.0, "backless") elif has(parts, "backrest", "long") or has(parts, "backrest", "tall"): mul("back_h", 1.6, "high back") if has(parts, "drawers"): setp("drawers", max(1, _num(parts["drawers"], 2)), "drawers") if has(parts, "shelves"): setp("shelves", max(2, _num(parts["shelves"], 3)), "shelves") if has(parts, "door"): setp("doors", max(1, _num(parts["door"], 2)), "doors") if "round" in form: setp("round_top", 1, "round") if has(parts, "legs"): n = _num(parts["legs"], 0) if n == 3: setp("legs", "three", "three legs") if False else None if "long" in parts["legs"] or "tall" in form: mul("seat_h", 1.4, "tall legs") elif "short" in parts["legs"] or "squat" in form: mul("seat_h", .6, "low") mul("top_h", .6, "low")
def _tool_rules(parts, form, g, setp, mul, D): if has(parts, "handle", "long"): mul("grip", 1.6, "long handle", hi=.8) elif has(parts, "handle", "short"): mul("grip", .6, "short handle") if parts.get("blade"): m = parts["blade"] if "curved" in m or "hooked" in m: setp("curve", max(.3, g("curve") or 0), "curved blade") if "long" in m: mul("tip", 1.4, "long blade") if "broad" in m or "big" in m: mul("bw", 1.5, "broad blade") if "thin" in m: mul("bw", .6, "narrow blade") if "curved" in form or "hooked" in form: setp("curve", max(.25, g("curve") or 0), "curved") if "pointed" in form or has(parts, "point", "pointed"): setp("point", max(.3, g("point") or 0), "pointed") if has(parts, "teeth"): setp("teeth", max(16, g("teeth") or 0), "teeth")
def _instrument_rules(parts, form, g, setp, mul, D): if has(parts, "strings"): n = _num(parts["strings"], 0) if n: setp("strings", n, "%d strings" % n) if has(parts, "neck", "long"): mul("body_len", .85, "long neck")
def _firearm_rules(parts, form, g, setp, mul, D): if has(parts, "barrel"): n = _num(parts["barrel"], 1) if n > 1: setp("bores", min(n, 3), "%d barrels" % n) if "long" in parts["barrel"]: mul("length", 1.3, "long barrel") elif "short" in parts["barrel"]: mul("length", .6, "short barrel")
def _device_rules(parts, form, g, setp, mul, D): if has(parts, "dial"): setp("dial", max(.25, g("dial") or 0), "dial") if has(parts, "knobs"): setp("knobs", max(2, _num(parts["knobs"], 3)), "knobs / buttons") if has(parts, "wheels"): setp("wheels", 1, "wheels") if has(parts, "legs"): setp("legs", 1, "legs") if "round" in form or "cylindrical" in form: setp("shape", "cyl", "round")
def _lathe_rules(parts, form, g, setp, mul, D): if has(parts, "handle"): setp("handle", 1, "handle") if has(parts, "spout"): setp("spout", 1, "spout") if has(parts, "lid"): setp("knob", 1, "lid")
PART_RULES = dict(quadruped=_quad_rules, primate=_prim_rules, bird=_bird_rules, fish=_fish_rules, lizard=_lizard_rules, snake=_snake_rules, arthropod=_arth_rules, turtle=_turtle_rules, frog=_frog_rules, worm=_worm_rules, dinosaur=_dino_rules, tree=_tree_rules, shrub=_shrub_rules, flower=_flower_rules, cactus=_cactus_rules, mushroom=_mushroom_rules, building=_building_rules, vessel=_vessel_rules, vehicle=_vehicle_rules, boat=_boat_rules, aircraft=_aircraft_rules, furniture=_furniture_rules, tool=_tool_rules, instrument=_instrument_rules, firearm=_firearm_rules, device=_device_rules, lathe=_lathe_rules)
# ------------------------------------------------------------------ referents ("similar to X", "smaller than X")_REF_CACHE = {}
def _ref_merged(word): """(family, merged params) for a referent word, from its taxa alone (no gloss: no recursion), or None.""" if word in _REF_CACHE: return _REF_CACHE[word] _REF_CACHE[word] = None try: from nltk.corpus import wordnet as wn from pydraw3d.families import TAXA, FAMILIES from . import open_vocab as ov lemma = wn.morphy(word.replace(" ", "_"), wn.NOUN) if not lemma: return None ch = ov._pinned(wn, lemma, TAXA) or ov._choose(wn, lemma, TAXA) if ch is None: return None s, names, hits = ch merged = {} for n in names: if n in TAXA: merged.update(TAXA[n]) if lemma in TAXA: merged.update(TAXA[lemma]) # rule: only a referent the families really know (a taxon on the word or just above it) lends its looks if not any(n in TAXA and not TAXA[n].get("root") for n in names[-2:]) and lemma not in TAXA: merged["_vague"] = True fam = merged.get("family") if fam not in FAMILIES: return None _REF_CACHE[word] = (fam, merged) except Exception: return None return _REF_CACHE[word]
def _ref_height(word): r = _ref_merged(word) if r and not r[1].get("_vague") and "height" in r[1]: return float(r[1]["height"]) try: from pydraw import CONCEPTS c = CONCEPTS.get(word) or CONCEPTS.get(word.rstrip("s")) if c and c.get("height"): return float(c["height"]) except Exception: pass return None
def ref_params(fam, F, word): """Parameters lent by "similar to X" / "X-shaped" / "X-like" referents drawn by the same family.""" for ref in F["like"]: ref = ref.strip() if ref == word or ref in STOPW: continue for cand in (ref, ref.split(" ")[0], ref.split(" ")[-1]): r = _ref_merged(cand) if r and r[0] == fam and not r[1].get("_vague"): p = {k: v for k, v in r[1].items() if k not in ("height", "setting", "row", "synset", "alias", "implied", "root", "natural_colors", "family", "animal", "flying", "on_top", "shadow", "_vague")} p["_ref"] = cand return p if r and r[0] == fam: break return None
# ------------------------------------------------------------------ entry point used by open_vocabSTATS = {"words": 0, "changed": 0}
def layer(word, s, names, TAXA, fam, base, defaults): """Gloss-derived overrides for `word` (synset s, hypernym path names) drawn by family `fam` on top of the ancestors' merged parameters `base`. Returns (overrides, notes, text).""" if not ENABLED[0]: return {}, [], [] try: texts = texts_for(s, names, TAXA, word) F = Feats() for src, t in texts: if t and src != "example": read(t, F, src if src in ("gloss", "anc", "name") else "parts") rp = ref_params(fam, F, word) out, notes = apply(fam, base, F, defaults, rp) except Exception as e: # the reader must never break resolution import sys print("pydraw.gloss: failed for %s: %r" % (word, e), file=sys.stderr) return {}, [], [] STATS["words"] += 1 STATS["changed"] += bool(out) return out, notes, texts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797"""Imagination rules (parser side): impossible pictures by composing what the system already knows.
Hooks in parse(): pre(toks) rewrites imaginative phrases into plain ones and remembers a PLAN; post(scene) attachesthe plan to the entities (entity["imagine"]) or swaps in DERIVED concepts that are registered on the fly (a modelbuilt from other models by pydraw3d/imagine.py, drawn by both renderers). Rules, not prompts:
material "X made of Y", "X carved from Y", "a Y X" (Y a stuff word: chocolate house, glass elephant, ice dragon) -> X keeps its shape, takes Y's material. Unlisted stuff words get a material from their WordNet kind (food / plant / mineral / metal / gem / fabric / animal) and their own model's colour and pattern. shape "X shaped like Y", "X in the shape of Y", "a Y-shaped X": shapeless stuff (cloud, hedge, cake, jelly) becomes Y made of that stuff; a solid thing becomes a MORPH: Y's body with X's function parts. chimeras named mythical creatures are recipes over family models (griffin = lion body + eagle head + wings); "X with (Y) wings / legs / horn / tail / fins / tentacles", "winged X", "two-headed X", "X with a Y for a head" graft parts. surreal tiny X on a small Y (X shrinks to Y's scale), lone giant small things (+ a person for scale), floating islands, "X with a garden on its back" / "trees growing on X", upside-down and melting things.Every decision is logged in the trace with the prefix "imagine:"."""import re
from .registry import CONCEPTS
# ---------------------------------------------------------------- vocabulary# stuff word -> skin (pydraw3d/imagine.py SKINS); adjective forms includedSTUFF = { "cheese": "cheese", "cheddar": "cheese", "chocolate": "chocolate", "cocoa": "chocolate", "fudge": "chocolate", "cake": "cake", "sponge": "cake", "frosting": "frosting", "icing": "frosting", "candy": "candy", "candies": "candy", "lollipop": "candy", "lollipops": "candy", "sweets": "candy", "gingerbread": "gingerbread", "bread": "bread", "toast": "bread", "dough": "bread", "pastry": "bread", "cookie": "cookie", "cookies": "cookie", "biscuit": "cookie", "jelly": "jelly", "jello": "jelly", "gummy": "jelly", "gelatin": "jelly", "honey": "honey", "sugar": "sugar", "marshmallow": "marshmallow", "marshmallows": "marshmallow", "ice cream": "ice cream", "glass": "glass", "glassy": "glass", "crystal": "crystal", "crystals": "crystal", "crystalline": "crystal", "diamond": "crystal", "diamonds": "crystal", "ruby": "crystal", "emerald": "crystal", "sapphire": "crystal", "amethyst": "crystal", "quartz": "crystal", "ice": "ice", "icy": "ice", "water": "water", "bubbles": "bubble", "bubble": "bubble", "gold": "gold", "silver": "silver", "metal": "metal", "metallic": "metal", "steel": "metal", "iron": "metal", "tin": "metal", "aluminum": "metal", "aluminium": "metal", "chrome": "chrome", "bronze": "bronze", "brass": "bronze", "copper": "copper", "rusty": "rust", "rust": "rust", "stone": "stone", "rock": "stone", "rocks": "stone", "granite": "stone", "concrete": "stone", "marble": "marble", "jade": "jade", "clay": "clay", "terracotta": "clay", "ceramic": "porcelain", "porcelain": "porcelain", "wood": "wood", "wooden": "wood", "timber": "wood", "bamboo": "bamboo", "wicker": "wicker", "straw": "straw", "hay": "straw", "paper": "paper", "origami": "paper", "papercraft": "paper", "cardboard": "cardboard", "plastic": "plastic", "lego": "lego", "legos": "lego", "voxel": "voxel", "voxels": "voxel", "pixelated": "voxel", "minecraft": "voxel", "blocky": "voxel", "balloon": "balloon", "balloons": "balloon", "inflatable": "balloon", "rubber": "rubber", "knitted": "knit", "knit": "knit", "crocheted": "knit", "crochet": "knit", "wool": "knit", "woolen": "knit", "woollen": "knit", "yarn": "knit", "felt": "felt", "plush": "plush", "stuffed": "plush", "leather": "leather", "denim": "denim", "fur": "fur", "cloud": "cloud", "clouds": "cloud", "cloudy": "cloud", "smoke": "smoke", "snow": "snow", "sand": "sand", "leaves": "leaves", "leafy": "leaves", "hedge": "leaves", "hedges": "leaves", "topiary": "leaves", "moss": "moss", "mossy": "moss", "grass": "moss", "flowers": "flowers", "flower": "flowers", "floral": "flowers", "petals": "flowers", "fire": "fire", "flames": "fire", "flame": "fire", "flaming": "fire", "fiery": "fire", "burning": "fire", "lava": "lava", "magma": "lava", "molten": "lava", "neon": "neon", "light": "light", "glowing": "light", "rainbow": "rainbow", "brick": "brick", "bricks": "brick", "bone": "bone", "bones": "bone", "coral": "coral",}GEM_COLOR = {"ruby": (200, 30, 60), "emerald": (40, 170, 90), "sapphire": (40, 80, 210), "amethyst": (150, 80, 200), "diamond": (225, 240, 250), "diamonds": (225, 240, 250), "quartz": (240, 230, 240)}# adjective-style use ("a Y X") is allowed for these only when X is an animal or a building (elementals)ELEMENTAL = {"ice", "icy", "water", "fire", "flames", "flame", "flaming", "fiery", "burning", "lava", "magma", "molten", "cloud", "clouds", "cloudy", "smoke", "snow", "sand", "light", "glowing", "rainbow", "bubble", "bubbles", "grass", "flower", "flowers", "leaves", "rock", "rocks", "bone", "bones", "honey", "sugar", "neon", "light"}# these stuff words are colours / ordinary attributes before a noun; only "made of" turns them into materialsNOT_ADJUNCT = {"gold", "silver", "golden", "tin", "iron", "toast", "sponge", "light", "fur", "rock", "cake", "flower", "petals", "hay", "straw", "honey", "bubble", "bubbles", "felt", "sugar", "crystal", "diamond", "diamonds", "water", "cookie", "cookies", "biscuit", "stuffed", "grass", "leaves", "bone", "bones"}# frequent compounds that are things of their own, not "a thing made of stuff"COMPOUNDS = set("""ice_cream ice_cube ice_skate ice_skates ice_rink ice_hockey ice_pop ice_bucket ice_pack ice_berg ice_age ice_teafire_truck fire_engine fire_hydrant fire_place fire_fighter fire_man fire_station fire_pit fire_works fire_alarmfire_extinguisher fire_escape fire_wood fire_ant fire_fly fire_ball fire_department fire_hosewater_bottle water_lily water_tower water_fountain water_park water_gun water_buffalo water_melon water_balloonpaper_towel paper_towels paper_plate paper_cup paper_bag paper_clip paper_weight paper_lanterncheese_grater cheese_board cheese_knife chocolate_chip chocolate_milk chocolate_bar candy_bar candy_store candy_shopcandy_cane candy_apple candy_floss bread_knife bread_basket bread_box cookie_jar cookie_cutter cookie_monstercake_stand cake_pan cake_tin glass_ceiling stone_age rock_band rock_star rock_climber snow_globe snow_leopardsnow_plow snow_man snow_mobile snow_owl snow_boots sand_dune sand_box sand_paper lava_lamp light_bulb light_houselight_saber light_switch light_post metal_detector wood_pecker wood_stove rubber_duck rubber_band rubber_bootsballoon_animal bubble_wrap bubble_tea neon_sign neon_lights brick_wall brick_road grass_hopper flower_potflower_vase flower_bed flower_shop flower_field leather_jacket leather_boots plastic_bag plastic_bottlecrystal_ball glass_slipper glass_bottle glass_jar honey_bee honey_pot honey_comb jelly_fish jelly_bean jelly_beansbone_marrow coral_reef cloud_nine smoke_detector smoke_stack wool_hat sugar_cane sugar_cube""".split())FOODISH = ("food.n.01", "food.n.02", "foodstuff.n.02", "beverage.n.01", "dish.n.02", "baked_goods.n.01", "edible_fruit.n.01")# shapeless stuff: "a cloud shaped like a sheep" is a sheep made of cloudAMORPHOUS = {"cloud": "cloud", "clouds": "cloud", "smoke": "smoke", "steam": "smoke", "fog": "smoke", "jelly": "jelly", "jello": "jelly", "gelatin": "jelly", "bush": "leaves", "hedge": "leaves", "shrub": "leaves", "topiary": "leaves", "cake": "cake", "cheese": "cheese", "chocolate": "chocolate", "cookie": "cookie", "bread": "bread", "ice": "ice", "snow": "snow", "sand": "sand", "balloon": "balloon", "fire": "fire", "flames": "fire", "water": "water", "candy": "candy", "ice cream": "ice cream", "lava": "lava", "pancake": "bread", "marshmallow": "marshmallow", "moss": "moss", "flowers": "flowers", "light": "light", "neon": "neon", "crystal": "crystal", "glass": "glass", "rock": "stone", "stone": "stone", "clay": "clay", "paper": "paper", "yarn": "knit", "wool": "knit", "lego": "lego", "legos": "lego", "bubble": "bubble", "bubbles": "bubble"}SHAPE_PHRASES = [("shaped", "like"), ("shaped", "as"), ("in", "the", "shape", "of"), ("in", "the", "form", "of"), ("in", "shape", "of"), ("that", "looks", "like"), ("that", "look", "like"), ("looking", "like"), ("resembling",), ("sculpted", "into"), ("carved", "into"), ("molded", "into"), ("moulded", "into"), ("built", "in", "the", "shape", "of"), ("made", "in", "the", "shape", "of")]GEOM_SHAPES = {"pentagon", "hexagon", "octagon", "circle", "square", "triangle", "heart", "star", "diamond", "rectangle", "oval", "crescent", "spiral", "cube", "sphere", "pyramid", "ring", "cone", "cylinder", "letter", "number", "round", "box", "ball", "egg", "u", "v", "s", "x", "l", "t"}MADE_VERBS = {"made", "built", "carved", "sculpted", "crafted", "formed", "constructed", "molded", "moulded", "woven", "knitted", "shaped", "cast", "assembled", "composed", "fashioned"}PART_WORDS = {"wings": "wings", "wing": "wings", "legs": "legs", "leg": "legs", "tail": "tail", "horn": "horn", "horns": "horns", "antlers": "antlers", "fins": "fins", "fin": "fins", "tentacles": "tentacles", "arms": "arms", "head": "head", "heads": "heads", "face": "head", "trunk": "trunk", "mane": "mane", "shell": "shell"}STOP_REL = {"on", "in", "at", "with", "next", "near", "under", "above", "below", "beside", "behind", "inside", "and", "while", "flying", "sitting", "standing", "floating", "zzeos", "by", "over", "under", "into", "holding", "that", "which", "who"}CREATURES = { # word -> (recipe, stand-in noun for the parser) "griffin": "griffin", "griffins": "griffin", "gryphon": "griffin", "griffon": "griffin", "hippogriff": "hippogriff", "centaur": "centaur", "centaurs": "centaur", "mermaid": "mermaid", "mermaids": "mermaid", "merman": "mermaid", "pegasus": "pegasus", "unicorn": "unicorn", "unicorns": "unicorn", "alicorn": "alicorn", "minotaur": "minotaur", "sphinx": "sphinx", "dragon": "dragon", "dragons": "dragon", "wyvern": "dragon", "fairy": "fairy", "fairies": "fairy", "angel": "angel", "angels": "angel", "faun": "faun", "satyr": "faun", "manticore": "manticore", "chimera": "chimera", "jackalope": "jackalope", "cerberus": "cerberus", "werewolf": "werewolf", "harpy": "harpy", "kraken": "kraken", "phoenix": "phoenix", "mercat": "mercat", "winged horse": "pegasus", "sea serpent": "seaserpent", "selkie": "mermaid", "naga": "naga",}CREATURE_FLYING = {"griffin", "hippogriff", "pegasus", "dragon", "fairy", "angel", "harpy", "phoenix", "alicorn"}TOP_STUFF = {"garden": "garden", "gardens": "garden", "forest": "forest", "trees": "forest", "tree": "tree", "flowers": "flowers", "flower": "flowers", "plants": "garden", "plant": "garden", "house": "house", "houses": "village", "castle": "castle", "village": "village", "town": "village", "city": "city", "skyscrapers": "city", "buildings": "city", "moss": "moss", "grass": "meadow", "meadow": "meadow", "mushrooms": "mushrooms", "mushroom": "mushrooms", "palm tree": "palm", "lighthouse": "lighthouse", "windmill": "windmill", "temple": "temple", "pagoda": "pagoda", "church": "church", "cottage": "house", "hut": "house", "island": "meadow", "volcano": "volcano", "waterfall": "garden", "bonsai": "tree", "jungle": "forest", "park": "garden", "farm": "village", "lake": "meadow", "pond": "meadow"}TOP_PLACES = ("back", "shell", "head", "roof", "top", "body", "hump", "nose", "belly", "tail")GIANT_WORDS = {"giant": 6.0, "gigantic": 7.0, "enormous": 6.0, "huge": 4.0, "colossal": 8.0, "massive": 4.0, "towering": 6.0, "titanic": 8.0, "monstrous": 5.0, "humongous": 7.0, "mammoth": 6.0, "oversized": 4.0, "kaiju": 9.0, "mega": 5.0, "supersized": 5.0}TINY_WORDS = {"tiny", "miniature", "mini", "little", "small", "teeny", "teensy", "itty", "minuscule", "microscopic", "pocket", "baby", "dollhouse", "toy"}
def _vocab(): from . import understanding as U return U
def _concept_kind(name, word=None): """animal / food / structure / plant / object for a concept (from its registry facts and WordNet).""" c = CONCEPTS.get(name) or {} if c.get("animal"): return "animal" ov = c.get("open_vocab") or {} fam = ov.get("family") if fam in ("building", "monument", "bridge", "barrier") or (c.get("height", 1) > 3.5 and not c.get("flying")): return "structure" if fam in ("baked", "dish", "sandwich", "sweet", "drink", "fooditem", "fruit", "bunch"): return "food" k = _wn_kind(word or name) if k == "food": return "food" if k == "plant": return "plant" return "object"
def _wn_kind(word): """WordNet kind of a word's main noun sense: food / plant / mineral / metal / gem / fabric / animal / None.""" try: from .open_vocab import _wn wn = _wn() ss = wn.synsets(word.replace(" ", "_"), "n")[:2] if wn else [] except Exception: ss = [] order = (("gem", ("gem.n.02", "crystal.n.01", "gem.n.01", "precious_stone.n.01")), ("metal", ("metallic_element.n.01", "metal.n.01", "alloy.n.01")), ("food", FOODISH), ("animal", ("animal.n.01",)), ("plant", ("plant.n.02", "plant_part.n.01", "plant_organ.n.01", "vegetation.n.01")), ("fabric", ("fabric.n.01", "yarn.n.01", "fiber.n.01")), ("mineral", ("mineral.n.01", "rock.n.01", "stone.n.02", "building_material.n.01", "material.n.01"))) sets = [{x.name() for path in s.hypernym_paths() for x in path} for s in ss] for kind, roots in order: # rule: a food sense wins over a plant sense (watermelon = the fruit, not the vine) if any(any(r in names for r in roots) for names in sets): return kind return None
def _noun_before(toks, i): """(start, length, hit) of the noun ending exactly at token i (exclusive), scanning back up to 3 tokens.""" U = _vocab() for ln in (3, 2, 1): s = i - ln if s < 0: continue h, l = U.match_noun(toks, s) if h and l == ln: return s, ln, h return None
def _noun_after(toks, j, skip_adj=True): """(start, length, hit, colour) of the first noun after j, skipping articles / colours / sizes.""" U = _vocab() col = None while j < len(toks) and (toks[j] in ("a", "an", "the", "some", "its", "their", "his", "her", "of", "pure", "solid", "entirely", "completely", "real") or (skip_adj and (toks[j] in U.COLORS or toks[j] in U.SIZES or toks[j] in U.COLOR_SHADES))): if toks[j] in U.COLORS: col = toks[j] j += 1 if j >= len(toks): return None h, l = U.match_noun(toks, j) if not h: return None return j, l, h, col
# ---------------------------------------------------------------- pre-pass on tokensdef pre(toks, trace): """Rewrite imaginative phrases into plain ones; returns (tokens, plan). plan = list of dicts with "head" (the X noun's tokens as they remain) and what to do with it.""" plan = [] try: toks = _pre(toks, plan, trace) except Exception as ex: # rule: imagination never breaks an ordinary parse trace.append("imagine: pre-pass skipped (%s)" % ex) return toks, [] return toks, plan
def _mark(plan, head_toks, pos, **kw): d = dict(head=" ".join(head_toks), pos=pos) d.update(kw) plan.append(d) return d
def _stuff_at(toks, j, made=True): """(skin, word, length) of a stuff phrase at j ("ice cream", "swiss cheese", "white chocolate", "lego bricks"). made=False (adjective use): two-word stuff phrases are left to the parser ("stained glass window" is a style).""" two = " ".join(toks[j:j + 2]) if made and two in ("white chocolate", "dark chocolate", "milk chocolate", "ice cream", "cotton candy", "swiss cheese", "stained glass", "sea glass", "lego bricks", "lego blocks", "candy canes", "gummy bears", "jelly beans", "playing cards", "fallen leaves", "autumn leaves", "pure gold", "solid gold"): sk = {"white chocolate": "white chocolate", "dark chocolate": "chocolate", "milk chocolate": "chocolate", "ice cream": "ice cream", "cotton candy": "candy", "swiss cheese": "cheese", "stained glass": "glass", "sea glass": "glass", "lego bricks": "lego", "lego blocks": "lego", "candy canes": "candy", "gummy bears": "jelly", "jelly beans": "candy", "playing cards": "paper", "fallen leaves": "leaves", "autumn leaves": "leaves", "pure gold": "gold", "solid gold": "gold"}[two] return sk, two, 2 if j < len(toks) and toks[j] in STUFF: return STUFF[toks[j]], toks[j], 1 return None
def _pre(toks, plan, trace): U = _vocab() n = len(toks) out = list(toks)
# --- (1a) "X made of Y" / "X carved from Y" / "X built out of Y" i = 0 while i < len(out) - 2: t = out[i] if t in MADE_VERBS and out[i + 1] in ("of", "from", "out", "with", "entirely", "completely", "purely", "only") and i > 0: j = i + 1 while j < len(out) and out[j] in ("of", "from", "out", "with", "entirely", "completely", "purely", "only"): j += 1 nb = _noun_before(out, i) or (_noun_before(out, i - 1) if out[i - 1] in ("is", "was", "all") else None) if nb and out[nb[0] + nb[1] - 1] in PART_WORDS or (nb and out[nb[0] + nb[1] - 1] in U.OBJECT_PARTS): nb = None # rule: "a mane made of rope" describes a part; the parser's part rules handle it if t == "shaped" or not nb: i += 1 continue k = j col = None while k < len(out) and (out[k] in ("a", "an", "the", "some", "pure", "solid", "real", "many", "lots", "tiny", "small") or out[k] in U.COLORS): if out[k] in U.COLORS: col = out[k] k += 1 st = _stuff_at(out, k) skin, word, ln = (st if st else (None, None, 0)) kind = None if not st: h = _noun_after(out, k, skip_adj=False) if not h: i += 1 continue k, ln, hit, _ = h # rule: "made of flower petals": the last noun of a compound is the stuff while k + ln < len(out): h2 = _noun_after(out, k + ln, skip_adj=False) if h2 and h2[0] == k + ln: k, ln, hit = h2[0], h2[1], h2[2] else: break word = " ".join(out[k:k + ln]) kind = _wn_kind(word) or _wn_kind(hit[0]) or _concept_kind(hit[0], word) skin = "derived" s0, l0, xh = nb d = _mark(plan, out[s0:s0 + l0], s0, op="skin", skin=skin, skin_word=word, skin_kind=kind, skin_color=U.COLORS.get(col) if col else (GEM_COLOR.get(word))) trace.append("imagine: '%s made of %s' -> %s skin%s" % (" ".join(out[s0:s0 + l0]), word, skin, " (%s, from WordNet)" % kind if kind else "")) out = out[:i] + out[k + ln:] continue i += 1
# --- (2) shapes: "X shaped like Y", "a Y-shaped X" i = 0 while i < len(out): ph = next((p for p in sorted(SHAPE_PHRASES, key=len, reverse=True) if tuple(out[i:i + len(p)]) == p), None) if ph: nb = _noun_before(out, i) na = _noun_after(out, i + len(ph)) if nb and na and out[na[0]] not in GEOM_SHAPES: s0, l0, xh = nb ys, yl, yh, ycol = na xw = " ".join(out[s0:s0 + l0]) xkind = _concept_kind(xh[0], xw) if ph[0] in ("that", "looking") and xkind == "animal": i += 1 continue # rule: "a cat that looks like a lion" stays the parser's business (a look, not a morph) stuff = AMORPHOUS.get(xw) or AMORPHOUS.get(out[s0 + l0 - 1]) yw = out[ys:ys + yl] if stuff: # rule: shapeless stuff takes Y's form and keeps its own stuff out = out[:s0] + yw + out[ys + yl:] _mark(plan, yw, s0, op="skin", skin=stuff, skin_word=xw, fly=stuff in ("cloud", "smoke")) trace.append("imagine: %s shaped like %s -> a %s made of %s" % (xw, " ".join(yw), " ".join(yw), stuff)) else: out = out[:s0 + l0] + out[ys + yl:] _mark(plan, out[s0:s0 + l0], s0, op="morph", shape=yh[0], shape_word=" ".join(yw)) trace.append("imagine: %s shaped like %s -> morph" % (xw, " ".join(yw))) i = s0 + 1 continue if out[i] == "shaped" and i > 0 and i + 1 < len(out): nb = _noun_before(out, i) na = _noun_after(out, i + 1) if nb and na and out[i - 1] not in GEOM_SHAPES and na[0] == i + 1 + sum(1 for t in out[i + 1:na[0]] if t in U.COLORS or t in U.SIZES): s0, l0, yh = nb xs, xl, xh, _ = na yw = out[s0:s0 + l0] xw = " ".join(out[xs:xs + xl]) stuff = AMORPHOUS.get(xw) if stuff: out = out[:s0] + out[i + 1:xs] + yw + out[xs + xl:] _mark(plan, yw, s0, op="skin", skin=stuff, skin_word=xw, fly=stuff in ("cloud", "smoke")) trace.append("imagine: %s-shaped %s -> a %s made of %s" % (" ".join(yw), xw, " ".join(yw), stuff)) else: out = out[:s0] + out[i + 1:] _mark(plan, xw.split(), s0, op="morph", shape=yh[0], shape_word=" ".join(yw)) trace.append("imagine: %s-shaped %s -> morph" % (" ".join(yw), xw)) i = s0 + 1 continue i += 1
# --- (1b) "a Y X": stuff adjunct before a noun i = 0 while i < len(out) - 1: st = _stuff_at(out, i, made=False) if st and out[i] not in NOT_ADJUNCT and not (i > 0 and out[i - 1] in ("stained", "sea", "cotton", "milk", "dark", "white")) and not (i + 1 < len(out) and " ".join(out[i:i + 2]) in ("ice cream", "stained glass", "cotton candy")) and not (i > 0 and out[i - 1] in ("of", "with", "made", "and")): skin, word, ln = st na = _noun_after(out, i + ln) if na and na[0] == i + ln: xs, xl, xh, _ = na xw = " ".join(out[xs:xs + xl]) comp = "_".join([word.replace(" ", "_"), out[xs]]) h_all, l_all = U.match_noun(out, i) xkind = _concept_kind(xh[0], xw) ok = comp not in COMPOUNDS and not (h_all and l_all > ln) if ok and word in ELEMENTAL and xkind not in ("animal", "structure"): ok = False # rule: "ice X" / "fire X" as adjectives only for elemental creatures and buildings if ok and skin in ("cheese", "chocolate", "cake", "candy", "bread", "cookie", "jelly", "ice cream", "frosting", "gingerbread", "honey", "sugar", "marshmallow", "white chocolate") and xkind == "food": ok = False # rule: a cheese pizza / chocolate cake is just food if ok and xh[0] in ("person",) and skin not in ("knit", "plush", "felt", "lego", "voxel", "paper", "stone", "marble", "gold", "bronze", "glass", "ice", "wood", "clay", "chocolate", "cloud"): ok = False if ok: _mark(plan, out[xs:xs + xl], i, op="skin", skin=skin, skin_word=word, skin_color=GEM_COLOR.get(word), adjunct=True) trace.append("imagine: '%s %s' -> %s skin" % (word, xw, skin)) out = out[:i] + out[i + ln:] continue i += 1
# --- (3) chimeras by name; "winged X"; "N-headed X"; "X with (Y) PART"; "X with a Y for a head" i = 0 while i < len(out): t = out[i] two = " ".join(out[i:i + 2]) cw = two if two in CREATURES else (t if t in CREATURES else None) if cw and not (cw in ("dragon", "dragons") and i + 1 < len(out) and out[i + 1] in ("fly", "flies", "fruit")): ln = len(cw.split()) rec = CREATURES[cw] plural = cw.endswith("s") and not cw.endswith("ss") and rec + "s" == cw or cw in ("fairies", "mermaids", "centaurs", "griffins", "angels", "unicorns", "dragons") stand = "dragons" if plural else "dragon" out = out[:i] + [stand] + out[i + ln:] _mark(plan, [stand], i, op="creature", recipe=rec, word=cw) trace.append("imagine: creature '%s' -> recipe %s" % (cw, rec)) i += 1 continue if t in ("winged", "flying") and i + 1 < len(out) and t == "winged": na = _noun_after(out, i + 1) if na: out = out[:i] + out[i + 1:] _mark(plan, out[na[0] - 1:na[0] - 1 + na[1]], i, op="graft", grafts=[("wings", None, 2)]) trace.append("imagine: winged %s -> graft wings" % " ".join(out[na[0] - 1:na[0] - 1 + na[1]])) continue if t in ("headed",) and i > 0 and i + 1 < len(out): num = U.NUMBERS.get(out[i - 1]) if out[i - 1] in U.NUMBERS else None na = _noun_after(out, i + 1) if num and num > 1 and na: out = out[:i - 1] + out[i + 1:] _mark(plan, out[na[0] - 2:na[0] - 2 + na[1]], i - 1, op="graft", grafts=[("heads", None, min(num, 9))]) trace.append("imagine: %d-headed -> extra heads" % num) continue nb = _noun_before(out, i) if nb and na: # "a lion-headed eagle", "a fish-headed man": head swap s0, l0, yh = nb yw = " ".join(out[s0:s0 + l0]) out = out[:s0] + out[i + 1:] _mark(plan, out[s0 + (na[0] - i - 1):s0 + (na[0] - i - 1) + na[1]], s0, op="graft", grafts=[("head", yh[0], 1)]) trace.append("imagine: %s-headed -> head of %s" % (yw, yh[0])) continue if t == "with" and i > 0: nb = _noun_before(out, i) if nb: g, end = _graft_clause(out, i + 1, nb) if g: s0, l0, xh = nb _mark(plan, out[s0:s0 + l0], s0, op="graft", grafts=g) trace.append("imagine: %s with %s -> graft" % (" ".join(out[s0:s0 + l0]), ", ".join("%s%s" % (p, " of " + y if y else "") for p, y, c in g))) out = out[:i] + out[end:] continue i += 1
# --- (4) things on an animal's back: "X with a garden on its back", "trees growing on (the back of) a X", # "a city on the back of a turtle" i = 0 while i < len(out): if out[i] == "with" and i > 0: nb = _noun_before(out, i) j = i + 1 while j < len(out) and out[j] in ("a", "an", "the", "some", "tiny", "little", "small", "lush", "whole", "entire", "beautiful", "little"): j += 1 tw = " ".join(out[j:j + 2]) if " ".join(out[j:j + 2]) in TOP_STUFF else (out[j] if j < len(out) and out[j] in TOP_STUFF else None) if nb and tw: k = j + len(tw.split()) if k + 2 < len(out) + 1 and k < len(out) and out[k] in ("on", "growing", "atop", "upon") : m = k while m < len(out) and out[m] in ("on", "growing", "atop", "upon", "its", "their", "his", "her", "the", "top", "of", "a"): m += 1 if m < len(out) and out[m] in TOP_PLACES: s0, l0, xh = nb _mark(plan, out[s0:s0 + l0], s0, op="top", top=TOP_STUFF[tw], top_word=tw) trace.append("imagine: %s with a %s on its %s -> grown on top" % (" ".join(out[s0:s0 + l0]), tw, out[m])) out = out[:i] + out[m + 1:] continue tw = " ".join(out[i:i + 2]) if " ".join(out[i:i + 2]) in TOP_STUFF else (out[i] if out[i] in TOP_STUFF else None) if tw: k = i + len(tw.split()) m = k while m < len(out) and out[m] in ("growing", "built", "sitting", "standing", "resting", "on", "upon", "atop", "the", "of", "top", "back", "shell", "a", "an", "giant", "huge"): m += 1 if m > k and "on" in out[k:m] + ["x"] and any(w in out[k:m] for w in ("on", "upon", "atop")) and \ (any(w in out[k:m] for w in ("back", "shell", "growing")) ): na = _noun_after(out, m - 0) if na and na[0] == m and _concept_kind(na[2][0], " ".join(out[na[0]:na[0] + na[1]])) == "animal": s = i while s > 0 and out[s - 1] in ("a", "an", "the", "some", "tiny", "little", "small", "lush", "whole"): s -= 1 xw = out[na[0]:na[0] + na[1]] out = out[:s] + out[m - 1:m - 1] + ["a"] + xw + out[na[0] + na[1]:] _mark(plan, xw, s, op="top", top=TOP_STUFF[tw], top_word=tw) trace.append("imagine: %s on the back of %s -> grown on top" % (tw, " ".join(xw))) i = s + 1 continue i += 1
# --- (5) upside down / melting / floating islands i = 0 while i < len(out): if out[i:i + 2] == ["upside", "down"]: na = _noun_after(out, i + 2) nb = _noun_before(out, i) tgt = (na[0], na[1]) if na and na[0] <= i + 3 else ((nb[0], nb[1]) if nb else None) if tgt: head = out[tgt[0]:tgt[0] + tgt[1]] out = out[:i] + out[i + 2:] _mark(plan, head, i, op="flip") trace.append("imagine: upside down %s" % " ".join(head)) continue if out[i] in ("melting", "melted", "melty", "dripping"): na = _noun_after(out, i + 1) nb = _noun_before(out, i) tgt = (na[0], na[1]) if na and na[0] <= i + 3 else ((nb[0], nb[1]) if nb else None) if tgt: head = out[tgt[0]:tgt[0] + tgt[1]] out = out[:i] + out[i + 1:] _mark(plan, head, i, op="melt") trace.append("imagine: melting %s" % " ".join(head)) continue if out[i] in ("floating", "flying", "sky", "levitating", "hovering") and i + 1 < len(out) and out[i + 1] in ("island", "islands", "rock", "rocks", "castle", "house", "city", "mountain", "mountains", "garden", "temple", "village"): w = out[i + 1] if w in ("island", "islands"): out = out[:i] + out[i + 1:] _mark(plan, [w], i, op="island") trace.append("imagine: floating island") continue if out[i] != "flying" or w not in ("rock", "rocks"): out = out[:i] + out[i + 1:] _mark(plan, [w], i, op="floating") trace.append("imagine: floating %s -> on a floating island chunk" % w) continue i += 1 return out
def _graft_clause(out, j, nb): """Parse a "with ..." clause into grafts [(part, donor concept or None, count)]; returns (grafts, end).""" U = _vocab() s0, l0, xh = nb xw = " ".join(out[s0:s0 + l0]) grafts = [] k = j while True: m = k cnt = None while m < len(out) and (out[m] in ("a", "an", "the", "big", "large", "huge", "giant", "small", "tiny", "little", "long", "short", "beautiful", "colorful", "colourful", "shiny", "sparkly", "golden", "feathered", "feathery", "two", "four", "six", "eight", "many", "three") or out[m] in U.COLORS): if out[m] in U.NUMBERS and out[m] not in ("a", "an"): cnt = U.NUMBERS[out[m]] m += 1 donor = None # "the wings of a butterfly" if m < len(out) and out[m] in PART_WORDS and m + 1 < len(out) and out[m + 1] == "of": na = _noun_after(out, m + 2) if na: donor = na[2][0] part = PART_WORDS[out[m]] grafts.append((part, donor, cnt)) k = na[0] + na[1] else: break else: na = None h, l = (U.match_noun(out, m) if m < len(out) else (None, 0)) if h and m + l < len(out) and out[m + l] in PART_WORDS and h[0] not in ("person",): donor, part = h[0], PART_WORDS[out[m + l]] k = m + l + 1 elif m < len(out) and out[m] in PART_WORDS: part = PART_WORDS[out[m]] k = m + 1 else: break # "with a fish for a head" handled below; here plain parts grafts.append((part, donor, cnt)) if k < len(out) and out[k] == "and" and k + 1 < len(out): k2 = k + 1 mm = k2 while mm < len(out) and (out[mm] in ("a", "an", "the", "long", "big", "small", "two", "four") or out[mm] in U.COLORS): mm += 1 h, l = (U.match_noun(out, mm) if mm < len(out) else (None, 0)) if (mm < len(out) and out[mm] in PART_WORDS) or (h and mm + l < len(out) and out[mm + l] in PART_WORDS): k = k2 continue break # "X with a Y for a head / face" if not grafts: na = _noun_after(out, j) if na and na[0] + na[1] + 2 < len(out) + 1 and out[na[0] + na[1]:na[0] + na[1] + 1] == ["for"]: m = na[0] + na[1] + 1 while m < len(out) and out[m] in ("a", "an", "its", "his", "her", "the"): m += 1 if m < len(out) and out[m] in ("head", "face"): return [("head", na[2][0], 1)], m + 1 return None, j # keep only grafts that change something: a named donor, or a part the subject does not have keep = [] xk = _concept_kind(xh[0], xw) for part, donor, cnt in grafts: if donor and donor != xh[0]: keep.append((part, donor, cnt)) elif not donor and not _has_part(xh[0], xw, part): keep.append((part, None, cnt)) if not keep or len(keep) != len(grafts): return None, j return keep, k
NATIVE = { # part -> concept words / families that already have it "wings": {"bird", "bat", "dragon", "butterfly", "bee", "insect", "airplane", "aircraft", "angel", "fairy", "moth", "dragonfly", "fly", "wasp", "ladybug", "owl", "eagle", "duck", "parrot", "chicken", "pegasus", "griffin"}, "legs": {"quadruped", "primate", "bird", "lizard", "dinosaur", "frog", "turtle", "arthropod", "person", "furniture", "dog", "cat", "horse", "chair", "table", "bed", "spider", "ant", "elephant", "cow", "sheep", "giraffe", "bear", "zebra"}, "horn": {"rhino", "rhinoceros", "unicorn", "goat", "narwhal"}, "horns": {"bull", "cow", "goat", "ram", "dragon", "devil", "buffalo"}, "antlers": {"deer", "moose", "elk", "reindeer", "stag"}, "tentacles": {"octopus", "squid", "jellyfish", "mollusc", "radial"}, "fins": {"fish", "shark", "whale", "dolphin", "pinniped"}, "arms": {"person", "primate", "robot", "octopus"}, "trunk": {"elephant", "tree", "mammoth"}, "tail": set(), "mane": {"horse", "lion", "zebra", "unicorn"}, "shell": {"turtle", "snail", "tortoise"}, "head": set(), "heads": set(),}
def _has_part(concept, word, part): nat = NATIVE.get(part) if nat is None: return True if part in ("tail", "head"): return True # rule: without a donor, "with a tail / head" is an ordinary attribute c = CONCEPTS.get(concept) or {} fam = (c.get("open_vocab") or {}).get("family") try: from pydraw3d.models import MODELS fam = fam or getattr(MODELS.get(concept, (None,))[0], "family", None) except Exception: pass return concept in nat or word in nat or (fam in nat) or (word.rstrip("s") in nat)
# ---------------------------------------------------------------- post-pass on the scenedef post(scene, plan, trace): if not plan: _surreal_scale(scene, trace) return try: _post(scene, plan, trace) except Exception as ex: import traceback trace.append("imagine: post-pass failed (%s)" % ex) if __import__("os").environ.get("PYDRAW_IMAGINE_DEBUG"): traceback.print_exc() try: _surreal_scale(scene, trace) except Exception as ex: trace.append("imagine: scale rules failed (%s)" % ex)
def _find(scene, head, used): hl = head.split() for k, e in enumerate(scene["entities"]): if k in used: continue w = (e.get("word") or "").split() if w and (w[-len(hl):] == hl or w[-1] == hl[-1] or e["concept"] == head or w[-1].rstrip("s") == hl[-1].rstrip("s")): used.add(k) return k return None
def _post(scene, plan, trace): from . import derived as D used_by = {} ents = scene["entities"] for p in sorted(plan, key=lambda d: d["pos"]): used = used_by.setdefault(p["op"], set()) k = _find(scene, p["head"], set(used)) if k is None and p["op"] == "skin" and p.get("adjunct"): # rule: "a wooden toy horse": the stuff word belongs to the next drawn thing even if the noun right after # it was folded into a compound k = next((j for j, e in enumerate(ents) if j not in used and not (e.get("imagine") or {}).get("skin")), None) if k is None: trace.append("imagine: no entity for '%s' (%s)" % (p["head"], p["op"])) continue e = ents[k] im = e.setdefault("imagine", {}) op = p["op"] if op == "skin": if e["concept"] in ("person",) and p["skin"] in ("cloud",): pass im.update(skin=p["skin"], skin_word=p.get("skin_word"), skin_kind=p.get("skin_kind")) if p.get("skin_color"): im["skin_color"] = tuple(p["skin_color"]) if p.get("fly"): e["pose"] = "flying" if not scene.get("place"): scene["place"] = "sky" if "sky" in _settings() else None # pixel renderer: the closest of its own materials e["material"] = _pixel_material(p["skin"], e, p.get("skin_color")) elif op == "morph": name = D.morph(e["concept"], p["shape"], trace) if name: e["concept"] = name elif op == "creature": name = D.creature(p["recipe"], trace) if name: e["concept"] = name e["word"] = p["word"] if p["recipe"] in CREATURE_FLYING and e.get("pose") is None and p["recipe"] not in ("dragon",) and False: e["pose"] = "flying" elif op == "graft": name = D.graft(e["concept"], p["grafts"], trace) if name: e["concept"] = name e.pop("attrs", None) if not (e.get("attrs") or {}).get("outfit") else None elif op == "top": name = D.on_top(e["concept"], p["top"], trace) if name: e["concept"] = name elif op in ("flip", "melt"): name = D.transform(e["concept"], op, trace) if name: e["concept"] = name if op == "flip" and CONCEPTS[name].get("height", 1) > 2 and not CONCEPTS[name].get("animal"): pass elif op == "island": name = D.island(trace) if name: e["concept"] = name e["pose"] = "flying" elif op == "floating": name = D.on_island(e["concept"], trace) if name: e["concept"] = name e["pose"] = "flying" used.add(k) # things standing on a floating island float with it for a, r, b in scene["relations"]: if r == "on" and ents[b]["concept"].startswith("floating island"): ents[b]["pose"] = "flying"
def _settings(): from .understanding import SETTINGS return SETTINGS
def _pixel_material(skin, e, color): from .materials import MATERIAL_WORDS direct = {"wood": "wood", "glass": "glass", "metal": "metal", "chrome": "metal", "silver": "metal", "gold": "gold", "bronze": "bronze", "copper": "bronze", "stone": "stone", "marble": "marble", "brick": "brick", "ice": "ice", "paper": "paper", "cardboard": "paper", "plastic": "plastic", "lego": "plastic", "rust": "rust", "clay": "clay", "porcelain": "clay", "chocolate": "chocolate", "neon": "neon", "rainbow": "rainbow", "leather": "leather", "jade": "jade", "knit": "fur", "felt": "fur", "plush": "fur", "fur": "fur", "jelly": "glass", "crystal": "glass", "water": "glass", "bubble": "glass", "cloud": "cloudstuff", "smoke": "cloudstuff", "fire": "fire", "lava": "fire", "sand": "sand", "leaves": "leafy", "moss": "leafy", "flowers": "rainbow", "candy": "plastic", "balloon": "plastic", "rubber": "plastic"} if skin in direct and (direct[skin] in MATERIAL_WORDS.values() or direct[skin] in ("cloudstuff", "fire", "sand", "leafy", "water")): return direct[skin] tints = {"cheese": (246, 196, 72), "cake": (238, 205, 150), "frosting": (248, 190, 210), "ice cream": (250, 200, 215), "gingerbread": (175, 105, 55), "bread": (200, 130, 62), "cookie": (205, 150, 85), "honey": (235, 160, 30), "sugar": (250, 250, 250), "marshmallow": (252, 240, 245), "snow": (245, 248, 252), "bone": (232, 222, 196), "coral": (245, 120, 110), "bamboo": (200, 190, 110), "wicker": (200, 160, 100), "straw": (220, 190, 110), "white chocolate": (240, 228, 205), "voxel": (110, 170, 80), "denim": (60, 90, 150), "light": (255, 235, 160)} c = color or tints.get(skin) if c: return "tint|%d,%d,%d" % tuple(int(v) for v in c) return e.get("material")
# ---------------------------------------------------------------- scale rules (work on any parse)def _surreal_scale(scene, trace): """rule: relative scale is the point of "a tiny X on a Y" and "a giant X": a tiny thing on a smaller support shrinks to the support's scale; a giant small thing becomes building-sized (with a person for scale if alone).""" ents = scene["entities"] text = " " + scene.get("text", "").lower().replace("-", " ") + " " for a, r, b in scene["relations"]: if r not in ("on", "in_a", "inside", "in") or a >= len(ents) or b >= len(ents): continue ea, eb = ents[a], ents[b] ha = CONCEPTS[ea["concept"]]["height"] * ea.get("size", 1) hb = CONCEPTS[eb["concept"]]["height"] * eb.get("size", 1) tiny = ea.get("size", 1) < 1 or any((" %s %s" % (w, (ea.get("word") or "").split()[-1] if ea.get("word") else "")) in text for w in TINY_WORDS) if tiny and ha > .8 * hb and CONCEPTS[eb["concept"]]["height"] < 3: new = .55 * hb / CONCEPTS[ea["concept"]]["height"] ea["size"] = new from .understanding import _attrs _attrs(ea)["fixed_scale"] = True _attrs(eb)["fixed_scale"] = True ea["pose"] = None if ea.get("pose") == "flying" else ea.get("pose") trace.append("imagine: tiny %s on a %s -> scaled to %.2fm" % (ea["concept"], eb["concept"], new * CONCEPTS[ea["concept"]]["height"])) for k, e in enumerate(ents): w = (e.get("word") or "").split() if not w: continue gw = next((g for g in GIANT_WORDS if (" %s %s " % (g, w[0])) in text or (" %s %s" % (g, " ".join(w))) in text), None) if not gw: continue h = CONCEPTS[e["concept"]]["height"] if h > 3.0: continue # rule: a giant house is just a big house others = [o for j, o in enumerate(ents) if j != k] from .understanding import _attrs if others: hmax = max(CONCEPTS[o["concept"]]["height"] * o.get("size", 1) for o in others) if hmax >= 8: continue # rule: next to a tower / lighthouse the layout's own size compression already reads as giant target = max(GIANT_WORDS[gw] * .6, 2.5 * hmax if hmax < 8 else 1.2 * hmax) for o in others: _attrs(o)["fixed_scale"] = True else: target = GIANT_WORDS[gw] if "person" in CONCEPTS and not scene.get("place") in ("table", "studio", "room", "kitchen", "bedroom", "bathroom", "office"): ents.append({"concept": "person", "word": "person", "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, "facing": None, "color_explicit": False, "attrs": {"fixed_scale": True}}) scene["relations"].append((len(ents) - 1, "next_to", k)) trace.append("imagine: giant %s alone -> a person next to it for scale" % e["concept"]) if scene.get("place") in ("room", "kitchen", "bedroom", "bathroom", "office") or " room " in text: target = 2.2 # rule (Magritte): a giant thing in a room fills the room e["size"] = target / h _attrs(e)["fixed_scale"] = True if CONCEPTS[e["concept"]].get("setting") == "table" and not scene.get("place"): scene["place"] = "field" # rule: a giant teacup / apple stands outdoors, not on a table trace.append("imagine: %s %s -> %.1fm tall" % (gw, e["concept"], target))100 unmodified lines101102103104105106107125 unmodified lines23323423523623723823960 unmodified lines300301302303304305100 unmodified linessupported = {s for s, rel, o in scene["relations"] if rel in ("on", "under", "above", "below")}supported |= {o for s, rel, o in scene["relations"] if rel in ("wearing", "holding", "uses")}loose = [i for i, e in enumerate(scene["entities"]) if CONCEPTS[e["concept"]]["setting"] == "table" and i not in supportedand e["concept"] not in ("clock", "window", "mirror") and not e.get("wall")]existing = [i for i, e in enumerate(scene["entities"]) if e["concept"] == "dining table"]if loose and existing:# rule: if the prompt already has a table, loose tabletop things go on it instead of a new one125 unmodified linespinned = {s for s, rel, o in rels if rel in ("on", "next_to", "under", "in_front_of", "behind")}pinned |= {o for s, rel, o in rels if rel == "above" and not CONCEPTS[scene["entities"][o]["concept"]]["flying"]} # rule: the thing below stays grounded (unless it lives in the sky, like the moon)for it in insts:if it.info["flying"] and it.ent not in pinned and it.pose not in ("perched", "sitting", "standing"):it.pose = "flying"for it in insts:if it.pose in ("running", "sleeping", "lying", "jumping", "walking"):60 unmodified linescontinue # rule: riders and their mounts keep real proportionsif it.implicit:continue # rule: an added table keeps furniture scalekeep = .6 if it.rel in ("on", "under") or (it.bound is None and any(o.bound is it and o.rel in ("on", "under") for o in insts)) else .42new = href * ratio ** keepif abs(math.log(ratio)) > .4:100 unmodified lines101102103104105106107108125 unmodified lines23423523623723823924060 unmodified lines301302303304305306307308100 unmodified linessupported = {s for s, rel, o in scene["relations"] if rel in ("on", "under", "above", "below")}supported |= {o for s, rel, o in scene["relations"] if rel in ("wearing", "holding", "uses")}loose = [i for i, e in enumerate(scene["entities"]) if CONCEPTS[e["concept"]]["setting"] == "table" and i not in supportedand e["concept"] not in ("clock", "window", "mirror") and not e.get("wall")and not (e.get("attrs") or {}).get("fixed_scale")] # (a giant apple in a room stands on the floor)existing = [i for i, e in enumerate(scene["entities"]) if e["concept"] == "dining table"]if loose and existing:# rule: if the prompt already has a table, loose tabletop things go on it instead of a new one125 unmodified linespinned = {s for s, rel, o in rels if rel in ("on", "next_to", "under", "in_front_of", "behind")}pinned |= {o for s, rel, o in rels if rel == "above" and not CONCEPTS[scene["entities"][o]["concept"]]["flying"]} # rule: the thing below stays grounded (unless it lives in the sky, like the moon)for it in insts:if it.info["flying"] and it.ent not in pinned and it.pose not in ("perched", "sitting", "standing", "sleeping", "one_leg", "swimming", "grazing", "walking", "lying"):it.pose = "flying"for it in insts:if it.pose in ("running", "sleeping", "lying", "jumping", "walking"):60 unmodified linescontinue # rule: riders and their mounts keep real proportionsif it.implicit:continue # rule: an added table keeps furniture scaleif (getattr(it, "attrs", None) or {}).get("fixed_scale"):continue # rule: surreal scale (a tiny dragon on a teacup, a giant snail) is the point; keep itkeep = .6 if it.rel in ("on", "under") or (it.bound is None and any(o.bound is it and o.rel in ("on", "under") for o in insts)) else .42new = href * ratio ** keepif abs(math.log(ratio)) > .4:
190 unmodified lines1911921931941951962 unmodified lines19920020120220320427 unmodified lines232233234235236237238190 unmodified linesfam = merged.get("family")if fam not in FAMILIES:return Nonename = lemmaif name not in CONCEPTS:_register(name, fam, merged, s, names, CONCEPTS, aspect_of, build)2 unmodified linesreturn resdef _register(name, fam, merged, s, names, CONCEPTS, aspect_of, build):from pydraw3d.models import MODELSheight = float(merged.get("height", 1.0))27 unmodified lineson_top=float(merged.get("on_top", 1.0)), default_color=tuple(col) if col else None,natural_colors=merged.get("natural_colors") or {}, flying=flying,shadow=bool(merged.get("shadow", True)), plurals={name: _plural(name)},open_vocab=dict(family=fam, synset=s.name(), path=[n for n in names if n in _taxa()],specific=name in _taxa() or any(n in _taxa() and not _taxa()[n].get("root") for n in names[-3:])))MODELS[name] = (model_fn, aspect)190 unmodified lines1911921931941951961972 unmodified lines20020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023127 unmodified lines259260261262263264265190 unmodified linesfam = merged.get("family")if fam not in FAMILIES:return Nonemerged = _with_gloss(lemma, s, names, TAXA, fam, merged, FAMILIES)name = lemmaif name not in CONCEPTS:_register(name, fam, merged, s, names, CONCEPTS, aspect_of, build)2 unmodified linesreturn resdef _with_gloss(lemma, s, names, TAXA, fam, merged, FAMILIES):"""rule: between the ancestors' taxa and the word's own hand-written taxon sits what the dictionary itself saysabout the word (pydraw.gloss: gloss, lemma name, meronyms -> colours, pattern, parts, proportions, material,setting). Hand entries (the word's own synset or word taxon) still win, key by key."""from . import glossif not gloss.ENABLED[0]:return mergedown = (s.name(), lemma)base = {}for n in names:if n in TAXA and n not in own:base.update(TAXA[n])base["family"] = famout, notes, _ = gloss.layer(lemma, s, names, TAXA, fam, base, FAMILIES[fam][2])if not out:return mergedres = dict(base)res.update(out)for n in own:if n in TAXA:res.update(TAXA[n])res["family"] = famres["_gloss"] = notesreturn resdef _register(name, fam, merged, s, names, CONCEPTS, aspect_of, build):from pydraw3d.models import MODELSheight = float(merged.get("height", 1.0))27 unmodified lineson_top=float(merged.get("on_top", 1.0)), default_color=tuple(col) if col else None,natural_colors=merged.get("natural_colors") or {}, flying=flying,shadow=bool(merged.get("shadow", True)), plurals={name: _plural(name)},open_vocab=dict(family=fam, synset=s.name(), path=[n for n in names if n in _taxa()], gloss=merged.get("_gloss", []),specific=name in _taxa() or any(n in _taxa() and not _taxa()[n].get("root") for n in names[-3:])))MODELS[name] = (model_fn, aspect)
249 unmodified lines25025125225325425511 unmodified lines267268269270271272221 unmodified lines49449549649749849950050150215 unmodified lines518519520521522523925 unmodified lines144914501451145214531454145514561457249 unmodified lines"volcanic": ("place", "volcanic"), "lava": ("place", "volcanic"),"rain": ("weather", "rain"), "rainy": ("weather", "rain"), "raining": ("weather", "rain"), "foggy": ("weather", "fog"), "fog": ("weather", "fog"),}SETTINGS = {k: v for k, v in SETTINGS.items() if v}SETTINGS.pop("golden", None)11 unmodified lines"silhouette": "silhouette", "silhouetted": "silhouette", "shadow puppet": "silhouette", "futuristic": "neon", "scifi": "neon", "dystopian": "neon", "abstract": "abstract", "geometric": "abstract", "cubism": "pop", "cubist": "pop", "minimalist": "abstract","painting": "oil", "drawing": "sketch", "doodle": "sketch", "crayon": "pastel", "chalk": "pastel"}POSES = {"flying": "flying", "sitting": "sitting", "running": "running", "sleeping": "sleeping", "perched": "perched","standing": "standing", "lying": "lying", "jumping": "jumping", "walking": "walking", "floating": "flying", "hovering": "flying", "levitating": "flying", "soaring": "flying","parked": "standing", "sailing": "floating", "airborne": "flying", "resting": "lying", "laying": "lying", "napping": "sleeping",221 unmodified linestext = text.lower().replace("-", " ").replace("'s", "")toks = re.findall(r"[a-z]+|\d+", text)toks = [TYPOS.get(t, t) for t in toks]trace.append("understand: tokens=%s" % " ".join(toks))scene = {"text": raw, "entities": [], "relations": [], "time": "day", "place": None, "season": None,"weather": None, "unknown": [], "style": None, "room": None}FEATURES = {"rainbow": "rainbow", "rainbows": "rainbow", "river": "river", "stream": "river", "creek": "river","path": "path", "trail": "path", "pathway": "path", "dirt road": "path", "clouds": "clouds", "cloud": "clouds","cloudy": "clouds", "aurora": "aurora", "northern lights": "aurora", "shooting star": "meteor",15 unmodified linesif f in ("aurora", "fireworks", "meteor"):scene["time"] = "night"toks = [t for t in toks if t not in w.split()]joined = " ".join(toks)# rule: multi-word style / setting phrases are read before the word loopfor phrase, key, val in (("black and white", "style", "bw"), ("oil painting", "style", "oil"),925 unmodified linescontinuekeep.append((a, r, b))scene["relations"] = keep# rule: layout binds each thing to its FIRST relation, so what it stands / sits on comes before what it holds or faces# ("a frog shouting into a microphone while standing on a stump" = on the stump, holding the microphone)scene["relations"].sort(key=lambda r: 0 if r[1] in ("on", "in_a", "riding", "under") else 1)if scene["unknown"]:trace.append("understand: not drawn, unknown words: %s" % ", ".join(scene["unknown"]))return scene249 unmodified lines25025125225325425525625725825926026126226326426526626711 unmodified lines279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427221 unmodified lines64965065165265365465565665765865966015 unmodified lines676677678679680681682925 unmodified lines160816091610161116121613161416151616161716181619249 unmodified lines"volcanic": ("place", "volcanic"), "lava": ("place", "volcanic"),"rain": ("weather", "rain"), "rainy": ("weather", "rain"), "raining": ("weather", "rain"), "foggy": ("weather", "fog"), "fog": ("weather", "fog"),}# wave 11 (worlds): setting nouns that used to be dropped; the coarse place here, the 3D world (pydraw3d/world.py)# reads the word itself for the fine biome (cliff, cornfield, lagoon, village, harbour...)for _k, _v in {"cliff": "mountains", "cliffs": "mountains", "clifftop": "mountains", "ledge": "mountains","precipice": "mountains", "summit": "mountains", "mountaintop": "mountains", "gorge": "mountains","fjord": "mountains", "cornfield": "farm", "cornfields": "farm", "wheatfield": "farm", "farmland": "farm","pasture": "field", "grassland": "field", "village": "field", "hamlet": "field", "woodland": "forest","grove": "forest", "lagoon": "beach", "atoll": "beach", "harbour": "water", "dock": "water", "docks": "water","pier": "water", "quay": "water", "wharf": "water", "stream": "water", "creek": "water", "brook": "water","riverbank": "water", "mesa": "desert", "badlands": "desert", "icefield": "arctic", "seafloor": "underwater","aurora": None, "underwater": "underwater"}.items():if _k not in SETTINGS:SETTINGS[_k] = ("place", _v) if _v else ("time", "night")SETTINGS = {k: v for k, v in SETTINGS.items() if v}SETTINGS.pop("golden", None)11 unmodified lines"silhouette": "silhouette", "silhouetted": "silhouette", "shadow puppet": "silhouette", "futuristic": "neon", "scifi": "neon", "dystopian": "neon", "abstract": "abstract", "geometric": "abstract", "cubism": "pop", "cubist": "pop", "minimalist": "abstract","painting": "oil", "drawing": "sketch", "doodle": "sketch", "crayon": "pastel", "chalk": "pastel"}# Art styles / media / artists -> a painting algorithm in pydraw3d/paint.py (scene["art"]) plus the nearest style the# pixel renderer knows (scene["style"]). "m" = the word is also an object or material ("a clay pot", "a crayon"),# so it names a style only as a medium: followed by drawing/art/style..., or after in/of/with/on ("made of clay").ART_STYLES = [# ukiyo-e woodblock("ukiyo e", "ukiyoe", "comic", ""), ("ukiyoe", "ukiyoe", "comic", ""), ("ukiyo", "ukiyoe", "comic", ""),("japanese woodblock", "ukiyoe", "comic", ""), ("woodblock", "ukiyoe", "comic", ""), ("woodcut", "ukiyoe", "comic", ""),("linocut", "ukiyoe", "comic", ""), ("hokusai", "ukiyoe", "comic", ""), ("hiroshige", "ukiyoe", "comic", ""),("utamaro", "ukiyoe", "comic", ""), ("great wave", "ukiyoe", "comic", ""), ("japanese print", "ukiyoe", "comic", ""),# stained glass("stained glass window", "stainedglass", "comic", ""), ("stained glass", "stainedglass", "comic", ""),("church window", "stainedglass", "comic", ""), ("leaded glass", "stainedglass", "comic", ""),("tiffany", "stainedglass", "comic", ""), ("leadlight", "stainedglass", "comic", ""),# mosaic("roman mosaic", "mosaic", "comic", ""), ("byzantine mosaic", "mosaic", "comic", ""), ("mosaic", "mosaic", "comic", ""),("mosaics", "mosaic", "comic", ""), ("tessellated", "mosaic", "comic", ""), ("byzantine", "mosaic", "comic", ""),("tile art", "mosaic", "comic", ""), ("gaudi", "mosaic", "comic", ""),# pointillism("pointillism", "pointillism", "oil", ""), ("pointillist", "pointillism", "oil", ""), ("pointillistic", "pointillism", "oil", ""),("seurat", "pointillism", "oil", ""), ("signac", "pointillism", "oil", ""), ("stippled", "pointillism", "oil", ""),("stipple", "pointillism", "oil", ""), ("stippling", "pointillism", "oil", ""), ("dot painting", "pointillism", "oil", ""),# low poly("low poly", "lowpoly", "comic", ""), ("lowpoly", "lowpoly", "comic", ""), ("polygonal", "lowpoly", "comic", ""),("faceted", "lowpoly", "comic", ""), ("triangulated", "lowpoly", "comic", ""), ("low polygon", "lowpoly", "comic", ""),# cut paper("layered paper", "papercut", "comic", ""), ("paper cut", "papercut", "comic", ""), ("papercut", "papercut", "comic", ""),("paper cutout", "papercut", "comic", ""), ("cut paper", "papercut", "comic", ""), ("papercraft", "papercut", "comic", ""),("paper craft", "papercut", "comic", ""), ("paper art", "papercut", "comic", ""), ("kirigami", "papercut", "comic", ""),("paper collage", "papercut", "comic", ""), ("collage", "papercut", "comic", ""), ("matisse", "papercut", "comic", ""),("paper diorama", "papercut", "comic", ""), ("made of paper", "papercut", "comic", ""),# claymation("claymation", "clay", "smooth", ""), ("plasticine", "clay", "smooth", ""), ("play doh", "clay", "smooth", ""),("playdough", "clay", "smooth", ""), ("stop motion", "clay", "smooth", ""), ("aardman", "clay", "smooth", ""),("wallace and gromit", "clay", "smooth", ""), ("clay", "clay", "smooth", "m"),# charcoal / graphite("charcoal", "charcoal", "sketch", "m"), ("conte crayon", "charcoal", "sketch", ""), ("graphite", "sketch", "sketch", "m"),# ink wash("sumi e", "inkwash", "sketch", ""), ("sumie", "inkwash", "sketch", ""), ("sumi", "inkwash", "sketch", ""),("ink wash", "inkwash", "sketch", ""), ("ink painting", "inkwash", "sketch", ""), ("chinese painting", "inkwash", "sketch", ""),("chinese ink", "inkwash", "sketch", ""), ("japanese ink", "inkwash", "sketch", ""), ("brush painting", "inkwash", "sketch", ""),("shan shui", "inkwash", "sketch", ""), ("guohua", "inkwash", "sketch", ""), ("calligraphic", "inkwash", "sketch", ""),# crayon / child's drawing("drawn by a child", "crayon", "pastel", ""), ("child drawing", "crayon", "pastel", ""), ("children drawing", "crayon", "pastel", ""),("kid drawing", "crayon", "pastel", ""), ("kids drawing", "crayon", "pastel", ""), ("childlike", "crayon", "pastel", ""),("childish", "crayon", "pastel", ""), ("kindergarten", "crayon", "pastel", ""), ("oil pastel", "crayon", "pastel", ""),("wax crayon", "crayon", "pastel", ""), ("crayons", "crayon", "pastel", "m"), ("crayon", "crayon", "pastel", "m"),("naive art", "crayon", "pastel", ""), ("fridge drawing", "crayon", "pastel", ""),# blueprint("blueprint", "blueprint", "sketch", ""), ("blueprints", "blueprint", "sketch", ""), ("technical drawing", "blueprint", "sketch", ""),("engineering drawing", "blueprint", "sketch", ""), ("schematic", "blueprint", "sketch", ""), ("cyanotype", "blueprint", "sketch", ""),("patent drawing", "blueprint", "sketch", ""), ("architectural drawing", "blueprint", "sketch", ""),# neon("neon sign", "neon", "neon", ""), ("neon lights", "neon", "neon", ""), ("neon line", "neon", "neon", ""),("glowing lines", "neon", "neon", ""), ("light painting", "neon", "neon", ""), ("tron", "neon", "neon", ""),# cross-stitch / embroidery("cross stitch", "crossstitch", "pixel", ""), ("crossstitch", "crossstitch", "pixel", ""), ("cross stitched", "crossstitch", "pixel", ""),("embroidery", "crossstitch", "pixel", ""), ("embroidered", "crossstitch", "pixel", ""), ("needlepoint", "crossstitch", "pixel", ""),("needlework", "crossstitch", "pixel", ""), ("tapestry", "crossstitch", "pixel", ""), ("stitched", "crossstitch", "pixel", ""),# van Gogh("vincent van gogh", "vangogh", "oil", ""), ("van gogh", "vangogh", "oil", ""), ("gogh", "vangogh", "oil", ""),("starry night", "vangogh", "oil", ""), ("swirling brushstrokes", "vangogh", "oil", ""), ("swirly", "vangogh", "oil", ""),("post impressionist", "vangogh", "oil", ""), ("post impressionism", "vangogh", "oil", ""), ("munch", "vangogh", "oil", ""),("expressionist", "vangogh", "oil", ""), ("expressionism", "vangogh", "oil", ""),# impressionism("impressionist", "impressionist", "oil", ""), ("impressionism", "impressionist", "oil", ""), ("monet", "impressionist", "oil", ""),("renoir", "impressionist", "oil", ""), ("pissarro", "impressionist", "oil", ""), ("sisley", "impressionist", "oil", ""),("degas", "impressionist", "oil", ""), ("morisot", "impressionist", "oil", ""), ("cassatt", "impressionist", "oil", ""),("en plein air", "impressionist", "oil", ""), ("plein air", "impressionist", "oil", ""), ("sorolla", "impressionist", "oil", ""),# oil (old masters)("old master", "oil", "oil", ""), ("old masters", "oil", "oil", ""), ("rembrandt", "oil", "oil", ""), ("vermeer", "oil", "oil", ""),("caravaggio", "oil", "oil", ""), ("velazquez", "oil", "oil", ""), ("baroque", "oil", "oil", ""), ("impasto", "oil", "oil", ""),("palette knife", "oil", "oil", ""), ("acrylic", "oil", "oil", ""), ("acrylics", "oil", "oil", ""), ("canvas painting", "oil", "oil", ""),("classical painting", "oil", "oil", ""), ("renaissance", "oil", "oil", ""), ("bob ross", "oil", "oil", ""), ("sargent", "oil", "oil", ""),# watercolour("aquarelle", "watercolor", "watercolor", ""), ("gouache", "watercolor", "watercolor", ""), ("wet on wet", "watercolor", "watercolor", ""),("turner", "watercolor", "watercolor", ""), ("ink and wash", "watercolor", "watercolor", ""),# art nouveau("art nouveau", "nouveau", "pop", ""), ("nouveau", "nouveau", "pop", ""), ("alphonse mucha", "nouveau", "pop", ""),("mucha", "nouveau", "pop", ""), ("jugendstil", "nouveau", "pop", ""), ("klimt", "nouveau", "pop", ""),("belle epoque", "nouveau", "pop", ""), ("art deco", "nouveau", "pop", ""), ("vintage poster", "nouveau", "pop", ""),("travel poster", "nouveau", "pop", ""), ("toulouse lautrec", "nouveau", "pop", ""), ("lautrec", "nouveau", "pop", ""),# risograph / halftone("risograph", "riso", "pop", ""), ("riso", "riso", "pop", ""), ("screen print", "riso", "pop", ""), ("screenprint", "riso", "pop", ""),("silkscreen", "riso", "pop", ""), ("halftone", "riso", "pop", ""), ("zine", "riso", "pop", ""), ("letterpress", "riso", "pop", ""),# pop art("roy lichtenstein", "pop", "pop", ""), ("ben day", "pop", "pop", ""), ("andy warhol", "pop", "pop", ""),# chalkboard("chalkboard", "chalkboard", "pastel", "m"), ("blackboard", "chalkboard", "pastel", "m"), ("sidewalk chalk", "chalkboard", "pastel", ""),("chalk", "chalkboard", "pastel", "m"),]ART_MEDIUM_NEXT = {"drawing", "drawings", "sketch", "sketches", "art", "artwork", "style", "styled", "painting", "paintings","print", "prints", "illustration", "portrait", "picture", "poster", "version", "rendering", "work","piece", "technique", "effect", "look", "aesthetic", "animation", "animated", "figure", "figurine","sculpture", "model", "image", "design", "pattern", "window", "panel", "mural", "tiles", "tile","sign", "signs", "lights", "doodle", "doodles", "scribble", "of", "inspired", "drawn", "character"}ART_GLUE_L = {"in", "the", "style", "of", "by", "like", "inspired", "a", "an", "as", "made", "out", "drawn", "painted","rendered", "done", "with", "using", "on", "styled", "type", "kind"}ART_GLUE_R = ART_MEDIUM_NEXT - {"portrait"}_ART_SORTED = sorted(ART_STYLES, key=lambda e: -len(e[0].split()))def art_prepass(toks, scene, trace):"""Rule: art media / art movements / artist names pick a painting algorithm (scene["art"]) and are removed from thetoken stream with their glue words ("in the style of hokusai", "a stained glass window of", "made of clay","a crayon drawing of"), so they never become objects."""out = list(toks)i = 0while i < len(out):hit = Nonefor ph, art, coarse, cond in _ART_SORTED:p = ph.split()if out[i:i + len(p)] != p:continuej = i + len(p)if cond == "m":prev = [t for t in out[max(0, i - 3):i] if t not in ("a", "an", "the")]nxt = out[j] if j < len(out) else None# a material / object word is a medium only next to drawing/art/... or after in/of/with/onif not (nxt in ART_MEDIUM_NEXT or (prev and prev[-1] in ("in", "of", "with", "using", "on"))):continuehit = (len(p), art, coarse, ph)breakif not hit:i += 1continuen, art, coarse, ph = hita, b = i, i + nwhile b < len(out) and out[b] in ART_GLUE_R:b += 1while a > 0 and out[a - 1] in ART_GLUE_L:a -= 1if not scene.get("art"):scene["art"] = artif not scene.get("style"):scene["style"] = coarsetrace.append("understand: art style '%s' -> %s (pixel renderer: %s)" % (ph, art, coarse))if ph == "starry night":scene["time"] = "night" # rule: "starry night" names the painting and the time of dayout = out[:a] + out[b:]i = areturn outPOSES = {"flying": "flying", "sitting": "sitting", "running": "running", "sleeping": "sleeping", "perched": "perched","standing": "standing", "lying": "lying", "jumping": "jumping", "walking": "walking", "floating": "flying", "hovering": "flying", "levitating": "flying", "soaring": "flying","parked": "standing", "sailing": "floating", "airborne": "flying", "resting": "lying", "laying": "lying", "napping": "sleeping",221 unmodified linestext = text.lower().replace("-", " ").replace("'s", "")toks = re.findall(r"[a-z]+|\d+", text)toks = [TYPOS.get(t, t) for t in toks]# rule: imaginative phrases (made of / shaped like / chimeras / surreal scale) are rewritten first (pydraw/imagine.py)from . import imagine as _imaginetoks, _iplan = _imagine.pre(toks, trace)trace.append("understand: tokens=%s" % " ".join(toks))scene = {"text": raw, "entities": [], "relations": [], "time": "day", "place": None, "season": None,"weather": None, "unknown": [], "style": None, "room": None, "art": None}FEATURES = {"rainbow": "rainbow", "rainbows": "rainbow", "river": "river", "stream": "river", "creek": "river","path": "path", "trail": "path", "pathway": "path", "dirt road": "path", "clouds": "clouds", "cloud": "clouds","cloudy": "clouds", "aurora": "aurora", "northern lights": "aurora", "shooting star": "meteor",15 unmodified linesif f in ("aurora", "fireworks", "meteor"):scene["time"] = "night"toks = [t for t in toks if t not in w.split()]toks = art_prepass(toks, scene, trace)joined = " ".join(toks)# rule: multi-word style / setting phrases are read before the word loopfor phrase, key, val in (("black and white", "style", "bw"), ("oil painting", "style", "oil"),925 unmodified linescontinuekeep.append((a, r, b))scene["relations"] = keepfrom .actions import apply as _actions # wave 11: verbs -> poses, actions, holding in mouth / beak, facing_actions(scene, trace)# rule: layout binds each thing to its FIRST relation, so what it stands / sits on comes before what it holds or faces# ("a frog shouting into a microphone while standing on a stump" = on the stump, holding the microphone)scene["relations"].sort(key=lambda r: 0 if r[1] in ("on", "in_a", "riding", "under") else 1)if scene["unknown"]:trace.append("understand: not drawn, unknown words: %s" % ", ".join(scene["unknown"]))_imagine.post(scene, _iplan, trace)return scene
33 unmodified lines34353637383933 unmodified lines- `k` > 0 blends this part smoothly into the union of the previous parts (smooth-min radius, in local units).- `spec` 0-1 specular strength, `rough` 0-1 (0.05 = glossy paint/glass, 0.9 = matte fur/leaves).- `emit` 0-1: the part glows with its own colour, ignoring light (screens, lamps, fire, neon).- `tex`: None (subtle noise), "fur", "leaves", "bark", "wood", "speckle", "tiles", "pores", "stone", "plaster".- `inst` (may be None) has `.word` (exact noun used, e.g. "puppy"), `.pose`, `.facing`, `.count`, `.k` (copy index).33 unmodified lines343536373839404142434433 unmodified lines- `k` > 0 blends this part smoothly into the union of the previous parts (smooth-min radius, in local units).- `spec` 0-1 specular strength, `rough` 0-1 (0.05 = glossy paint/glass, 0.9 = matte fur/leaves).- `emit` 0-1: the part glows with its own colour, ignoring light (screens, lamps, fire, neon).- light flags (optional keywords, read by `pydraw3d/light.py`): `glass=1` (refracts, IOR `ior=1.5`, tinted by `color`,`frost` 0-1 for milky ice), `metal=1` (mirrors the scene in its own colour; `rough` blurs it), `sss` 0-1(subsurface glow: skin, fruit, wax, jade). Mirror-glossy shells of vessels/gems/bottles, chrome-grey trims, gold-colouredglossy parts, skin and fruit get these automatically; material words in the prompt (glass, ice, metal, gold, jade)re-skin a model. Parts with `emit` >= .55 become point lights at night (bulbs, flames, screens).- `tex`: None (subtle noise), "fur", "leaves", "bark", "wood", "speckle", "tiles", "pores", "stone", "plaster".- `inst` (may be None) has `.word` (exact noun used, e.g. "puppy"), `.pose`, `.facing`, `.count`, `.k` (copy index).
15 unmodified lines161718192021222324252627285 unmodified lines3435363738391 unmodified line4142434445461 unmodified line48495051525354552 unmodified lines585960616263648 unmodified lines7374757677787980818283846 unmodified lines9192939495969798991001011021031 unmodified line1051061071081091103 unmodified lines11411511611711811912012112212312410 unmodified lines13513613713813914010 unmodified lines15115215315415515615715815916016116216364 unmodified lines2282292302312322332342352362372382392402412421 unmodified line2442452462472482492504 unmodified lines25525625725825926026126226326426526661 unmodified lines3283293303313323333343353364 unmodified lines34134234334434534634734834935023 unmodified lines3743753763773783793808 unmodified lines38939039139239339410 unmodified lines4054064074084094104114124134144154164175 unmodified lines4234244254264274284294304314324334 unmodified lines4384394404414424434444454464474484494501 unmodified line45245345445545645745845946046146246346446546646746846947047147216 unmodified lines4894904914924934944954964974984994 unmodified lines5045055065075085095103 unmodified lines51451551651751851952013 unmodified lines53453553653753853954054179 unmodified lines6216226236246256266276286296306316326334 unmodified lines6386396406416426436446456466476486496506513 unmodified lines6556566576586596606616 unmodified lines6686696706716726736746754 unmodified lines6806816826836846856866876886896906916926936946956966976981 unmodified line7007017027037047057067077087097107117127137147157167177187197207217227232 unmodified lines7267277287297307317327337346 unmodified lines7417427437447457461 unmodified line74874975075175275375475575675775875976076176276316 unmodified lines78078178278378478578678778815 unmodified linesfrom pydraw.layout import layoutfrom pydraw.variation import varyfrom . import sdf as Sfrom .models import MODELS, fallback, load_all as _load_models_load_models()from .families import load_all as _load_families_load_families()__all__ = ["plot3d"]SKIES = { # zenith, horizon, sun colour, sun intensity, ambient"day": ((70, 130, 215), (190, 215, 235), (255, 244, 225), 3.0, .9),"sunset": ((70, 80, 150), (250, 170, 110), (255, 170, 100), 2.4, .7),5 unmodified lines"street": ((95, 95, 100), (80, 80, 86)), "savanna": ((200, 170, 90), (170, 140, 70))}def lin(c):return (np.asarray(c, float) / 255.0) ** 2.21 unmodified lineclass Obj:def __init__(self, parts, base, scale, yaw, name, aspect=1.0):self.parts, self.base, self.scale, self.yaw, self.name = parts, np.asarray(base, float), scale, yaw, nameself.center = self.base + np.array([0, .5 * scale, 0])# rule: the bounding sphere encloses the model's box (width = aspect, height 1, depth <= aspect) with slackself.radius = scale * (.15 + .5 * math.sqrt(1 + 2 * max(1.0, aspect) ** 2))1 unmodified linedef local(self, P):return S.rot_y((P - self.base) / self.scale, -self.yaw)def dist(self, P):q = self.local(P)d = Nonefor pt in self.parts:e = pt.fn(q)2 unmodified linesdef part_index(self, P):q = self.local(P)ds = np.stack([pt.fn(q) for pt in self.parts], -1)return ds.argmin(-1), q8 unmodified linesz0 = np.zeros(len(x), np.int64)return (7 + 16 * S._hash(cell, z0 + 3, z0 + sd)) * m, celldef dist(self, P, want_id=False, margin=.05):d = P[:, 1].copy() if self.ground else np.full(len(P), 1e9)if self.backdrop_z is not None:# rule: indoor/studio scenes have a real back wall; a smooth cove joins it to the floor (seamless paper)d = S.smin(d, self.backdrop_z - P[:, 2], self.cove)ids = np.full(len(P), -1)if self.street is not None:# rule: a street has a row of buildings behind the far pavement (stepped heights, flat facades)hh, _ = self.facade_h(P[:, 0])6 unmodified linesd = np.where(better, df, d)ids[better] = -3for k, o in enumerate(self.objs):db = S.length(P - o.center) - o.radiusnear = db < margin * o.scale# rule: outside the bound the true distance is at least db; add the bound radius minus the object's real# extent so penumbras (which read d) are not darkened by the bounding spheredk = db.copy()if near.any():dk[near] = o.dist(P[near])better = dk < dd = np.where(better, dk, d)ids[better] = k1 unmodified linedef march(scene, O, D, tmax, steps=160):n = len(D)t = np.full(n, 1e-3)hit = np.zeros(n, bool)3 unmodified linesif not len(idx):breakP = (O[idx] if O.ndim == 2 else O) + D[idx] * t[idx, None] # O: one origin, or one per ray (orthographic)d = scene.dist(P)h = d < 4e-4 * t[idx] + 1e-5hit[idx[h]] = Truet[idx] += np.where(h, 0, d * .85)alive[idx[h | (t[idx] > tmax)]] = False# rule: polish the hit points onto the surface (uneven stopping distances show up as contour bands in AO/shadows)hi = np.nonzero(hit)[0]for _ in range(4):10 unmodified linesdef soft_shadow(scene, P, L, tmax, scl, k=6.0, steps=48):# rule: shadow rays step in units of the object scale (not scene depth) so surfaces don't shadow themselvesres = np.ones(len(P))t = np.full(len(P), .08 * scl)10 unmodified linesocc, w = 0.0, 1.0for i in range(1, 6):h = scale * .03 * iocc = occ + w * np.maximum(h - scene.dist(P + N * h, margin=1.5), 0)w *= .7return np.clip(1 - 3.0 * occ / scale / .03 / 5, 0, 1)def texture(kind, q, base, seed=0):"""rule: every surface gets a little material variation (fur, bark, leaves...) so nothing looks like flat plastic"""if kind is None:return base * (0.96 + .08 * S.noise3(q * 12, seed)[:, None])if kind == "fur":64 unmodified linessun_side = .85 + .3 * np.clip(np.sign(L[0]) * np.sin(az) * 4, -1, 1) * .5layers = []if place in ("mountains", "snow"):layers.append((.10 + .14 * _ridge(az, 2.5, seed), lin((112, 126, 150)), .55, True))layers.append((.04 + .05 * _ridge(az, 5, seed + 1), lin((80, 110, 90)) if place == "mountains" else lin((200, 210, 225)), .3, False))elif place in ("field", "park", "farm", "forest", "savanna"):layers.append((.05 + .06 * _ridge(az, 2, seed), lin((120, 140, 165)), .6, False))layers.append((.025 + .03 * _ridge(az, 4, seed + 1), lin((95, 135, 80)) if place != "savanna" else lin((170, 150, 90)), .35, False))if place != "savanna":# tree line: bumpy dark band right on the horizonbump = np.abs(np.sin(az * 90 + 3 * _ridge(az, 30, seed + 2))) ** .6layers.append((.006 + .016 * bump * _ridge(az, 8, seed + 3), lin((45, 80, 50)), .2, False))elif place in ("desert", "beach"):layers.append((.03 + .04 * _ridge(az, 2, seed), lin((205, 165, 120)) if place == "desert" else lin((120, 150, 170)), .5, False))elif place == "street":1 unmodified linez0 = np.zeros(len(az), np.int64)cell = np.floor(az * 40).astype(np.int64)h = .06 + .12 * S._hash(cell, z0, z0 + seed)layers.append((h, lin((150, 160, 180)), .55, False))cell2 = np.floor(az * 14).astype(np.int64)h2 = .04 + .1 * S._hash(cell2, z0 + 1, z0 + seed)pal = np.array([lin((170, 90, 70)), lin((215, 195, 160)), lin((120, 140, 170)), lin((200, 160, 120)), lin((160, 160, 150))])4 unmodified lineslit = S._hash(np.floor(az * 126).astype(np.int64), np.floor(up * 160).astype(np.int64), z0 + seed) > (.4 if tod == "night" else .85)bcol = np.where(win[:, None], np.where(lit[:, None], lin((255, 220, 150)) * (3 if tod == "night" else 1.2), bcol * .45), bcol)layers.append((h2, bcol, .18, False))for h, c, haze, snowcap in layers: # far to near: nearer bands paint over farther onesinside = (up < h) & (up > -.02)if not inside.any():continuev = np.clip((h - up) / np.maximum(h, 1e-3), 0, 1) # 0 at the crest, 1 at the basecc = (c if c.ndim == 2 else c[None, :]) * (1.05 - .25 * v[:, None]) * sun_side[:, None] * lightkif snowcap:cap = (v < .25) & (h > .14)cc[cap] = lin((235, 240, 248)) * sun_side[cap, None] * lightk61 unmodified linesreturn np.clip((x * (a * x + b)) / (x * (c * x + d) + e), 0, 1)def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trace=False):import osKX = dict(kv.split("=") for kv in os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv) # dev A/B knobsres = res or int(KX.get("res", 512))ss = ss or int(KX.get("ss", 1))# defaults chosen by judge A/B on bench/r3_ab.py (see NOTES.md): light haze, +25% saturation, +12% contrast,4 unmodified linest0 = time.time()trace = []rng = random.Random(seed)scene = parse(text, trace)# rule (3d): real golden-hour light and autumn ground tint every surface (an orange zebra), so the 3D renderer# varies time of day and season only when asked (knob vt=1 re-enables)vary(scene, trace, random.Random(seed * 7919 + 13), variation, off=() if KX.get("vt", "1") == "1" else {"t", "s"})R = resents = scene["entities"]if KX.get("famfill", "1") == "1":23 unmodified linesscene["relations"] = []scene["place"] = "table"trace.append("3d: things on a table -> tabletop close-up")insts, y0 = layout(scene, R, R, rng, trace)place, tod = scene["place"], scene["time"] if scene["time"] in SKIES else "day"f = float(R)cam = 1.08 unmodified linesZ = f * cam / (it.y - y0)scales.append((it.h * Z / f) / max(.01, it.world_h))upm = float(np.median(scales)) if scales else cam / 1.6 # world units per metrefor it in order:if it.bound is not None and it.rel == "on" and id(it.bound) in placed:Z = placed[id(it.bound)]10 unmodified linese = scene["entities"][it.ent] if isinstance(getattr(it, "ent", None), int) and it.ent < len(scene["entities"]) else {}cname = e.get("color")col = COLORS.get(cname) if cname in COLORS else CONCEPTS[it.concept].get("default_color")fn, aspect = MODELS.get(it.concept, (None, CONCEPTS[it.concept]["aspect"]))parts = fn(col, it) if fn else fallback(col, CONCEPTS[it.concept]["aspect"])box_a = CONCEPTS[it.concept]["aspect"]if fn and aspect > box_a * 1.08 and KX.get("fitw", "1") == "1":# rule: a model wider than its layout box (a family model borrowed for a concept, a long low animal)# shrinks to the box width, so it is not cropped or pushed into its neighboursHw *= box_a * 1.08 / aspectif fn is not None and getattr(fn, "family", None) and it.bound is None and KX.get("famdepth", "1") == "1":# rule: the layout gives a family model's FRONT line; its body is deep, so its centre goes back by half# its depth (else big things - tents, igloos, buildings - spill out of the bottom of the frame)5 unmodified lines# rule: only side-view things (animals, vehicles) flip for "facing left"; front-facing models (screens, books) never show their backyaw = (math.pi if side and getattr(it, "facing", None) == "left" else 0.0) + (-.55 if getattr(it, "facing", None) == "left" else .55) * (1 if side else 0)yaw += rng.uniform(-.15, .15)objs.append(Obj(parts, (X, max(0.0, Yb) if (it.bound is None or it.rel != "on") else Yb, Z), Hw, yaw, it.concept, aspect))objs[-1].col = colobjs[-1].target = COLORS[cname] if (cname in COLORS and e.get("color_explicit", True)) else Noneobjs[-1].cname = cnametrace.append("3d: %s at x=%.2f y=%.2f z=%.2f h=%.2f" % (it.concept, X, Yb, Z, Hw))indoor = place in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office") and KX.get("wall", "1") == "1"wall_z = Noneif indoor:4 unmodified lineszc_ = float(np.median([o.base[2] for o in objs])) if objs else 4 * camstreet = (zc_ + 9.0 * upm, upm, seed)sc = Scene3D(objs, backdrop_z=wall_z, cove=(.35 * wall_z if place == "studio" else .0), street=street)# ---- camera rays: principal point on the layout's horizon (built per pass below) ----O = np.array([0, cam, 0.0])zfar = max([o.base[2] for o in objs] + [cam * 8]) * 6zen, hor, sunc, sun_i, amb = SKIES[tod]zen, hor, sunc = lin(zen), lin(hor), lin(sunc)if KX.get("warm", "0") == "1" and tod == "day":# rule: warm key / cool fill: a slightly golden sun against a bluer sky ambient reads as late-morning lightsunc = lin((255, 232, 200)); zen = zen * np.array([.9, .95, 1.1])1 unmodified line# rule: snow stays white at golden hour (only a hint of warmth), otherwise it reads as desert sandsunc = sunc * .35 + lin((255, 240, 225)) * .65sx = -.55 if rng.random() < .5 else .55L = np.array([sx, .55 if tod == "day" else .18, -.45])L /= np.linalg.norm(L)studio = place in ("studio", "table") or place in ("room", "kitchen", "bedroom", "bathroom", "office")if studio:back = lin(rng.choice([(92, 158, 168), (226, 146, 124), (222, 186, 96), (150, 182, 150), (168, 160, 212), (128, 172, 218)]))if place == "table":back = lin(rng.choice([(226, 214, 196), (200, 214, 222), (230, 205, 190)]))hor = backzen = back * .7L = np.array([sx, .7, -.5]); L /= np.linalg.norm(L)sunc = lin((255, 246, 235))sun_i, amb = 2.4, 1.1def bg(D, xsf, ysf, land=True):# ---- background ----up = np.clip(D[:, 1], -1, 1)sky = hor + (zen - hor) * np.clip(up * 2.2, 0, 1)[:, None] ** .8if not studio:16 unmodified linessky = back * (1.05 - .9 * r2)[:, None]return skydef shade(D, xsf, ysf):t, hit = march(sc, O, D, zfar)P = O + D * t[:, None]sky = bg(D, xsf, ysf)col = sky.copy()idmap = np.full(len(D), -2)cmap = np.zeros(len(D), bool)4 unmodified linesif len(hi):Ph = P[hi]d, ids = sc.dist(Ph, want_id=True)N = normals(sc, Ph, 1e-3 * np.maximum(t[hi], .1)[:, None] * .5)alb = np.zeros((len(hi), 3))spec = np.zeros(len(hi))rough = np.ones(len(hi)) * .83 unmodified linesif g.any():q = Ph[g]wallm = (N[g][:, 2] < -.5) if wall_z is not None else np.zeros(len(q), bool)if studio and place == "table":wood = lin((150, 102, 64))grain = S.noise3(q * np.array([3, 1, 60]) / max(upm, 1e-3) * 2, seed)a_ = wood * (0.8 + .35 * grain)[:, None]13 unmodified linesframe = win & ((np.abs(np.abs(q[:, 0] - .9 * upm * np.sign(-L[0])) - .55 * upm) < .05 * upm) |(np.abs(q[:, 1] - .9 * upm) < .05 * upm) | (np.abs(q[:, 1] - 2.0 * upm) < .05 * upm) |(np.abs(q[:, 0] - .9 * upm * np.sign(-L[0])) < .025 * upm) | (np.abs(q[:, 1] - 1.45 * upm) < .025 * upm))a_[win] = lin((200, 225, 245)) * 3.0 # bright sky through the window (emissive-ish)a_[frame] = lin((245, 245, 240))alb[g] = a_spec[g], rough[g] = np.where(wallm, .05, .35), np.where(wallm, .9, .35)elif studio:79 unmodified linesgg = alb[g]gg[dot] = pal[pick[dot]]alb[g] = ggem = np.zeros(len(hi)) if fac_em is None else fac_emcpart = np.zeros(len(hi), bool)for k, o in enumerate(objs):sel = ids == kif not sel.any():continuepi, q = o.part_index(Ph[sel])a = np.zeros((sel.sum(), 3))sp = np.zeros(sel.sum())ro = np.zeros(sel.sum())4 unmodified linesif getattr(pt, "pat", None):a[m] = pattern(pt.pat, q[m], a[m], seed + k)sp[m], ro[m] = pt.spec, pt.roughif getattr(pt, "emit", 0):em[np.nonzero(sel)[0][m]] = pt.emitif o.target is not None and o.col is not None and np.allclose(pt.color, o.col):cpart[np.nonzero(sel)[0][m]] = Truealb[sel], spec[sel], rough[sel] = a, sp, roscl = np.maximum(np.array([o.scale for o in objs]).mean() if objs else cam, .05)sha = soft_shadow(sc, Ph + N * 2e-3 * scl, L, zfar * .5, scl)ao = ambient_occ(sc, Ph, N, scl)dif = np.clip(N @ L, 0, 1)skyl = np.clip(.5 + .5 * N[:, 1], 0, 1)bounce = np.clip(.5 - .5 * N[:, 1], 0, 1)3 unmodified linesspc = spec * np.clip(N @ L, 0, 1) ** 0 * np.clip((N * H).sum(-1), 0, 1) ** shin * (shin + 8) / 60 * shafres = spec * (1 - np.clip(-(N * D[hi]).sum(-1), 0, 1)) ** 5light = (sunc * sun_i * (dif * sha)[:, None] + (zen * .6 + hor * .4) * amb * (skyl * ao)[:, None]+ lin((120, 110, 90)) * .25 * (bounce * ao)[:, None])c = alb * light + sunc[None, :] * spc[:, None] + hor[None, :] * fres[:, None] * .4 * ao[:, None]if water_mask is not None and water_mask.any():# rule: water reflects the sky (and the landscape) along the mirrored ray, stronger at grazing angles,6 unmodified linesDv = D[hi][wi]Rv = Dv - 2 * (Dv * wn).sum(-1)[:, None] * wnRv[:, 1] = np.abs(Rv[:, 1])refl = bg(Rv.astype(np.float32), xsf[hi][wi], ysf[hi][wi])fr = .25 + .7 * (1 - np.clip(-(Dv * wn).sum(-1), 0, 1)) ** 4c[wi] = c[wi] * (1 - fr[:, None]) + refl * fr[:, None] * sha[wi][:, None] ** .3shiny = (spec > .7) & (rough < .2) & ((ids >= 0) | (ids == -3))if shiny.any() and KX.get("envrefl", "1") == "1":4 unmodified linesRv = Dv - 2 * (Dv * Ns).sum(-1)[:, None] * Nsrefl = bg(Rv.astype(np.float32), xsf[hi][si], ysf[hi][si], land=False)fr = .15 + .55 * (1 - np.clip(-(Dv * Ns).sum(-1), 0, 1)) ** 3c[si] = c[si] * (1 - fr[:, None] * .6) + refl * (fr * ao[si])[:, None]if em.any():# rule: emissive parts (screens, lamps, fire) glow with their own colour regardless of lightingc = c * (1 - np.clip(em, 0, 1))[:, None] + alb * (em * 2.2)[:, None]if KX.get("rim", "0") != "0":# rule: a soft rim light on object silhouettes separates them from the background (cinematic three-point look)obj = ids >= 0vdn = np.clip(-(N * D[hi]).sum(-1), 0, 1)rim = (1 - vdn) ** 3 * float(KX.get("rim")) * objc = c + (sunc * .6 + hor * .4)[None, :] * (rim * ao)[:, None]# rule: aerial perspective, far things fade into the horizon colourfog = 1 - np.exp(-t[hi] / (zfar * (.5 if studio else .25)) * fogk * (.45 if place == "street" else 1))c = c * (1 - fog[:, None]) + hor[None, :] * fog[:, None]col[hi] = cidmap[hi] = idscmap[hi] = cpart1 unmodified linedbg = os.environ.get("PYDRAW3D_DBG")if dbg:col[hi] = {"sha": sha, "ao": ao, "dif": dif}[dbg][:, None] * np.ones(3)return col, idmap, tmap, cmapdef rays(xp, yp):Dd = np.stack([(xp - R / 2) / f, (y0 - yp) / f, np.ones_like(xp)], -1)Dd = Dd / S.length(Dd)[:, None]return Dd.astype(np.float32) if KX.get("f32", "1") == "1" else Ddif KX.get("aa", "adaptive") == "adaptive" and ss == 1:# rule: anti-alias adaptively: shade one ray per pixel, find edges (object id changes or strong contrast),# then re-shade only those pixels with a 4-ray rotated grid (most of the 2x2 supersampling gain, ~1/3 the cost)n = Rys, xs = np.mgrid[0:n, 0:n].astype(float)xsf, ysf = xs.reshape(-1) + .5, ys.reshape(-1) + .5col, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf)idg = idm.reshape(n, n)lum = (col * np.array([.3, .59, .11])).sum(-1).reshape(n, n) ** (1 / 2.2)thr = float(KX.get("aathr", .06))edge = np.zeros((n, n), bool)eh = (idg[:, :-1] != idg[:, 1:]) | (np.abs(lum[:, :-1] - lum[:, 1:]) > thr)ev = (idg[:-1, :] != idg[1:, :]) | (np.abs(lum[:-1, :] - lum[1:, :]) > thr)2 unmodified linesei = np.nonzero(edge.reshape(-1))[0]if len(ei):acc = np.zeros((len(ei), 3))for ox, oy in ((-.375, -.125), (.125, -.375), (.375, .125), (-.125, .375)):cx, cy = xsf[ei] + ox, ysf[ei] + oyc_, _, _, _ = shade(rays(cx, cy), cx, cy)acc += c_col[ei] = acc / 4trace.append("3d: adaptive AA re-shaded %d edge pixels (%.0f%%)" % (len(ei), 100 * len(ei) / (n * n)))6 unmodified linesss_eff = ss# ---- tone map, grade, output ----out = aces(col * float(KX.get("expo", 1.1))) ** (1 / 2.2)sat, con = float(KX.get("sat", 1.0)), float(KX.get("con", 1.0))if sat != 1.0 or con != 1.0:1 unmodified linelum = (out * np.array([.299, .587, .114])).sum(-1, keepdims=True)out = lum + (out - lum) * satout = .5 + (out - .5) * conif KX.get("colorfix", "1") == "1":out = color_fix(np.clip(out, 0, 1), idm, cmp_, objs, trace)painted = Noneif scene.get("style") and KX.get("paint", "1") == "1":from .paint import STYLES as _PSif scene["style"] in _PS:# rule: a style word re-paints the render with a painting algorithm (oil strokes, watercolour washes,# pencil hatching, comic cel + ink) using the render's object ids and depthout = _PS[scene["style"]](np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), tm.reshape(n, n), seed)painted = scene["style"]trace.append("3d: painted as %s" % painted)img = (np.clip(out, 0, 1).reshape(n, n, 3) * 255 + .5).astype(np.uint8)im = Image.fromarray(img)16 unmodified linesif ss_eff > 1:im = im.resize((R, R), Image.LANCZOS)im = im.resize((size, size), Image.BICUBIC)if float(KX.get("soft", 0)) > 0 and not painted:from PIL import ImageFilterim = im.filter(ImageFilter.GaussianBlur(float(KX.get("soft")))) # rule: a touch of lens softnesstrace.append("3d: rendered %dx%d (ss=%d) in %.1fs" % (R, R, ss, time.time() - t0))im.info["trace"] = traceim.info["scene"] = scene15 unmodified lines161718192021222324252627282930313233343536373839405 unmodified lines4647484950515253541 unmodified line565758596061621 unmodified line64656667686970717273747576777879808182838485868788899091922 unmodified lines95969798991001011021031048 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371386 unmodified lines1451461471481491501511521531541551561571581591 unmodified line1611621631641651661673 unmodified lines17117217317417517617717817918018110 unmodified lines19219319419519619719819920020120210 unmodified lines21321421521621721821922022122222322422522622722822923023123223323464 unmodified lines2993003013023033043053063073083093103113123131 unmodified line3153163173183193203214 unmodified lines32632732832933033133233333433533633733833934034134261 unmodified lines4044054064074084094104114124134144154164174184194204214 unmodified lines42642742842943043143243343443543643743843944044144244344444523 unmodified lines4694704714724734744754764774784794804814824834848 unmodified lines49349449549649749849910 unmodified lines5105115125135145155165175185195205215225235245255265275285295305315325335 unmodified lines5395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755764 unmodified lines5815825835845855865875885895905915925935945955965975985996001 unmodified line60260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866916 unmodified lines6866876886896906916926936946956966976986997007017027037047054 unmodified lines7107117127137147157167177187197207217223 unmodified lines72672772872973073173273373473573673773873913 unmodified lines75375475575675775875976076176279 unmodified lines8428438448458468478488498508518528538548558568578588598608618624 unmodified lines8678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119123 unmodified lines9169179189199209219229239249259266 unmodified lines9339349359369379389399409419429439449459464 unmodified lines95195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061 unmodified line1008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810492 unmodified lines105210531054105510561057105810591060106110621063106410656 unmodified lines107210731074107510761077107810791080108110821 unmodified line10841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111916 unmodified lines113611371138113911401141114211431144114515 unmodified linesfrom pydraw.layout import layoutfrom pydraw.variation import varyfrom . import sdf as Sfrom . import natural as _NATfrom .models import MODELS, fallback, load_all as _load_modelsfrom . import accel as _accelfrom . import light as _light_load_models()from .families import load_all as _load_families_load_families()__all__ = ["plot3d"]import os as _osACCEL = "accel=0" not in _os.environ.get("PYDRAW3D_EXP", "") # dev switch: accel=0 = original brute-force SDF evaluationSHADOW_MARGIN = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("shm", .4))HIT_EPS = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("hit", 4e-4))STEP_K = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("stepk", .85))LIGHT = "light=0" not in _os.environ.get("PYDRAW3D_EXP", "") # dev switch: light=0 = wave-10 materials (no glass/metal/sss)AO_MARGIN = 1.5 if not ACCEL else .3 # rule (speed): AO probes reach .15 x scale; parts farther than that cannot occludeBACKDROPS = [(92, 158, 168), (226, 146, 124), (222, 186, 96), (150, 182, 150), (168, 160, 212), (128, 172, 218)]TABLE_WALLS = [(226, 214, 196), (200, 214, 222), (230, 205, 190)]SKIES = { # zenith, horizon, sun colour, sun intensity, ambient"day": ((70, 130, 215), (190, 215, 235), (255, 244, 225), 3.0, .9),"sunset": ((70, 80, 150), (250, 170, 110), (255, 170, 100), 2.4, .7),5 unmodified lines"street": ((95, 95, 100), (80, 80, 86)), "savanna": ((200, 170, 90), (170, 140, 70))}_STEPS = {} # preview knobs (pydraw3d/search.py): fewer march / shadow stepsdef lin(c):return (np.asarray(c, float) / 255.0) ** 2.21 unmodified lineclass Obj:def __init__(self, parts, base, scale, yaw, name, aspect=1.0):self.parts, self.base, self.scale, self.yaw, self.name = parts, np.asarray(base, float), scale, yaw, nameself.ent, self.k, self.inst = None, 0, None # set for prompted subjects; dressing keeps Noneself.center = self.base + np.array([0, .5 * scale, 0])# rule: the bounding sphere encloses the model's box (width = aspect, height 1, depth <= aspect) with slackself.radius = scale * (.15 + .5 * math.sqrt(1 + 2 * max(1.0, aspect) ** 2))1 unmodified linedef local(self, P):return S.rot_y((P - self.base) / self.scale, -self.yaw)def dist(self, P, margin=None):q = self.local(P)if margin is not None and ACCEL:# rule (speed): tight object/part boxes (pydraw3d/accel.py); exact SDF only within `margin` of a boxif not hasattr(self, "pbox"):_accel.compute_bounds(self)res = Noneif self.box is not None:bd = _accel.box_dist(q, *self.box)ex = bd < marginif not ex.all():res = bd.astype(np.float64)if not ex.any():return res * self.scaleq = q[ex]vals = _accel.part_values(self, q, margin)d = Nonefor pt, e in zip(self.parts, vals):d = e if d is None else S.smin(d, e, pt.k)if res is None:return d * self.scaleres[ex] = dreturn res * self.scaled = Nonefor pt in self.parts:e = pt.fn(q)2 unmodified linesdef part_index(self, P):q = self.local(P)if ACCEL and hasattr(self, "pbox"):ds = np.stack(_accel.part_values(self, q, .05), -1)else:ds = np.stack([pt.fn(q) for pt in self.parts], -1)return ds.argmin(-1), q8 unmodified linesz0 = np.zeros(len(x), np.int64)return (7 + 16 * S._hash(cell, z0 + 3, z0 + sd)) * m, cellworld = None # pydraw3d.world.World: the terrain replaces the ground plane (shadow / AO / normal rays)def dist(self, P, want_id=False, margin=.05, D=None):if self.world is not None and self.ground:d = self.world.sdf(P)elif D is not None and ACCEL and (self.backdrop_z is None or self.cove <= 0):# rule (speed): a camera ray steps to the floor / back wall by its distance ALONG THE RAY to the plane,# not the perpendicular distance (rays grazing the ground towards the horizon used to crawl 160 steps)d = np.where(D[:, 1] < -1e-6, P[:, 1] / np.maximum(-D[:, 1], 1e-6), 1e9) if self.ground else np.full(len(P), 1e9)if self.backdrop_z is not None:d = np.minimum(d, np.where(D[:, 2] > 1e-6, (self.backdrop_z - P[:, 2]) / np.maximum(D[:, 2], 1e-6), 1e9))else:d = P[:, 1].copy() if self.ground else np.full(len(P), 1e9)if D is None and self.backdrop_z is not None:# rule: indoor/studio scenes have a real back wall; a smooth cove joins it to the floor (seamless paper)d = S.smin(d, self.backdrop_z - P[:, 2], self.cove)elif self.backdrop_z is not None and not (ACCEL and self.cove <= 0):d = S.smin(d, self.backdrop_z - P[:, 2], self.cove)ids = np.full(len(P), -1)skip = getattr(self, "skip", ())if self.street is not None:# rule: a street has a row of buildings behind the far pavement (stepped heights, flat facades)hh, _ = self.facade_h(P[:, 0])6 unmodified linesd = np.where(better, df, d)ids[better] = -3for k, o in enumerate(self.objs):if k in skip:continue # (see-through pass behind glass objects)db = S.length(P - o.center) - o.radiusnear = db < margin * o.scale# rule: outside the bound the true distance is at least db; add the bound radius minus the object's real# extent so penumbras (which read d) are not darkened by the bounding spheredk = db.copy()if near.any():dk[near] = o.dist(P[near], margin)better = dk < dd = np.where(better, dk, d)ids[better] = k1 unmodified linedef march(scene, O, D, tmax, steps=160):steps = _STEPS.get("march", steps)n = len(D)t = np.full(n, 1e-3)hit = np.zeros(n, bool)3 unmodified linesif not len(idx):breakP = (O[idx] if O.ndim == 2 else O) + D[idx] * t[idx, None] # O: one origin, or one per ray (orthographic)d = scene.dist(P, D=D[idx] if D.ndim == 2 else D)h = d < HIT_EPS * t[idx] + 1e-5hit[idx[h]] = Truet[idx] += np.where(h, 0, d * STEP_K)alive[idx[h | (t[idx] > (tmax[idx] if np.ndim(tmax) else tmax))]] = False# rule: polish the hit points onto the surface (uneven stopping distances show up as contour bands in AO/shadows)hi = np.nonzero(hit)[0]for _ in range(4):10 unmodified linesdef soft_shadow(scene, P, L, tmax, scl, k=6.0, steps=48):steps = _STEPS.get("shadow", steps)if ACCEL:if LIGHT and getattr(scene, "glassy", None):return _light.glass_shadow(scene, P, L, tmax, scl, k, steps, SHADOW_MARGIN, _accel.soft_shadow)return _accel.soft_shadow(scene, P, L, tmax, scl, k, steps, margin=SHADOW_MARGIN)# rule: shadow rays step in units of the object scale (not scene depth) so surfaces don't shadow themselvesres = np.ones(len(P))t = np.full(len(P), .08 * scl)10 unmodified linesocc, w = 0.0, 1.0for i in range(1, 6):h = scale * .03 * iocc = occ + w * np.maximum(h - scene.dist(P + N * h, margin=AO_MARGIN), 0)w *= .7return np.clip(1 - 3.0 * occ / scale / .03 / 5, 0, 1)def texture(kind, q, base, seed=0):"""rule: every surface gets a little material variation (fur, bark, leaves...) so nothing looks like flat plastic"""if callable(kind): # imagination skins (pydraw3d/imagine.py) bring their own texture functionsreturn kind(q, base, seed)if _NAT.ON:# rule (natural): photographic renders use solid textures synthesised to hand-written natural statisticsreturn _NAT.surface(kind, q, base, seed, _texture_legacy)return _texture_legacy(kind, q, base, seed)def _texture_legacy(kind, q, base, seed=0):if kind is None:return base * (0.96 + .08 * S.noise3(q * 12, seed)[:, None])if kind == "fur":64 unmodified linessun_side = .85 + .3 * np.clip(np.sign(L[0]) * np.sin(az) * 4, -1, 1) * .5layers = []if place in ("mountains", "snow"):layers.append((.10 + .14 * _ridge(az, 2.5, seed), lin((112, 126, 150)), .55, True, "rock"))layers.append((.04 + .05 * _ridge(az, 5, seed + 1), lin((80, 110, 90)) if place == "mountains" else lin((200, 210, 225)), .3, False, "hills" if place == "mountains" else None))elif place in ("field", "park", "farm", "forest", "savanna"):layers.append((.05 + .06 * _ridge(az, 2, seed), lin((120, 140, 165)), .6, False))layers.append((.025 + .03 * _ridge(az, 4, seed + 1), lin((95, 135, 80)) if place != "savanna" else lin((170, 150, 90)), .35, False, "hills"))if place != "savanna":# tree line: bumpy dark band right on the horizonbump = np.abs(np.sin(az * 90 + 3 * _ridge(az, 30, seed + 2))) ** .6layers.append((.006 + .016 * bump * _ridge(az, 8, seed + 3), lin((45, 80, 50)), .2, False, "trees"))elif place in ("desert", "beach"):layers.append((.03 + .04 * _ridge(az, 2, seed), lin((205, 165, 120)) if place == "desert" else lin((120, 150, 170)), .5, False))elif place == "street":1 unmodified linez0 = np.zeros(len(az), np.int64)cell = np.floor(az * 40).astype(np.int64)h = .06 + .12 * S._hash(cell, z0, z0 + seed)layers.append((h, lin((150, 160, 180)), .55, False, "city"))cell2 = np.floor(az * 14).astype(np.int64)h2 = .04 + .1 * S._hash(cell2, z0 + 1, z0 + seed)pal = np.array([lin((170, 90, 70)), lin((215, 195, 160)), lin((120, 140, 170)), lin((200, 160, 120)), lin((160, 160, 150))])4 unmodified lineslit = S._hash(np.floor(az * 126).astype(np.int64), np.floor(up * 160).astype(np.int64), z0 + seed) > (.4 if tod == "night" else .85)bcol = np.where(win[:, None], np.where(lit[:, None], lin((255, 220, 150)) * (3 if tod == "night" else 1.2), bcol * .45), bcol)layers.append((h2, bcol, .18, False))for lay in layers: # far to near: nearer bands paint over farther onesh, c, haze, snowcap = lay[:4]inside = (up < h) & (up > -.02)if not inside.any():continuev = np.clip((h - up) / np.maximum(h, 1e-3), 0, 1) # 0 at the crest, 1 at the basecc = (c if c.ndim == 2 else c[None, :]) * (1.05 - .25 * v[:, None]) * sun_side[:, None] * lightkif _NAT.ON and len(lay) > 4 and lay[4]:# rule (natural): far bands are dead-leaves crowns / 1/f rock, not flat silhouettesii = np.nonzero(inside)[0]cc[ii] = cc[ii] * _NAT.band(lay[4], az[ii], up[ii], seed)if snowcap:cap = (v < .25) & (h > .14)cc[cap] = lin((235, 240, 248)) * sun_side[cap, None] * lightk61 unmodified linesreturn np.clip((x * (a * x + b)) / (x * (c * x + d) + e), 0, 1)def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trace=False, search=False, program=None, exp=None):"""search=True (or a time budget in seconds): generate-and-test over the scene program with a hand-writtencritic on cheap previews, then render the best candidate (pydraw3d/search.py). program: a scene program fromthat search (open choices: variation seed, layout seed, per-instance nudges, sun, backdrop, colours)."""import osif search:from .search import search_plot3dreturn search_plot3d(text, seed=seed, size=size, res=res, variation=variation, ss=ss, return_trace=return_trace,budget=8.0 if search is True else float(search))program = program or {}KX = dict(kv.split("=") for kv in os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv) # dev A/B knobsKX.update(exp or {})res = res or int(KX.get("res", 512))ss = ss or int(KX.get("ss", 1))# defaults chosen by judge A/B on bench/r3_ab.py (see NOTES.md): light haze, +25% saturation, +12% contrast,4 unmodified linest0 = time.time()trace = []rng = random.Random(seed)if "_parsed" in program: # search: parse once (~0.7 s), reuse per candidateimport copyscene = copy.deepcopy(program["_parsed"][0])trace += list(program["_parsed"][1])else:scene = parse(text, trace)scene["prompt_relations"] = list(scene["relations"]) # what the prompt asked for (layout appends implicit ones)# rule (3d): real golden-hour light and autumn ground tint every surface (an orange zebra), so the 3D renderer# varies time of day and season only when asked (knob vt=1 re-enables)vary(scene, trace, random.Random(program.get("vseed", seed * 7919 + 13)), variation, off=() if KX.get("vt", "1") == "1" else {"t", "s"})for ei, cn in program.get("colors", {}).items(): # search: colour of a thing the prompt leaves uncolourede_ = scene["entities"][ei] if ei < len(scene["entities"]) else Noneif e_ is not None and not (e_.get("color") and e_.get("color_explicit", True)) and not e_.get("material"):e_["color"], e_["color_explicit"] = cn, FalseR = resents = scene["entities"]if KX.get("famfill", "1") == "1":23 unmodified linesscene["relations"] = []scene["place"] = "table"trace.append("3d: things on a table -> tabletop close-up")if "lseed" in program:rng = random.Random(program["lseed"])insts, y0 = layout(scene, R, R, rng, trace)if program.get("inst"):from .search import apply_nudgesapply_nudges(insts, y0, R, program["inst"], trace)from . import interactinteract.prepare(insts, scene, trace) # wave 11: poses implied by interactions (riding, fleeing)_NAT.ON = _NAT.wanted(scene, KX) and not KX.get("preview") # search previews skip the camera simulation_NAT.RES = Rplace, tod = scene["place"], scene["time"] if scene["time"] in SKIES else "day"f = float(R)cam = 1.08 unmodified linesZ = f * cam / (it.y - y0)scales.append((it.h * Z / f) / max(.01, it.world_h))upm = float(np.median(scales)) if scales else cam / 1.6 # world units per metretops = {}for it in order:if it.bound is not None and it.rel == "on" and id(it.bound) in placed:Z = placed[id(it.bound)]10 unmodified linese = scene["entities"][it.ent] if isinstance(getattr(it, "ent", None), int) and it.ent < len(scene["entities"]) else {}cname = e.get("color")col = COLORS.get(cname) if cname in COLORS else CONCEPTS[it.concept].get("default_color")fn, aspect = interact.model_for(it, e, MODELS.get(it.concept), trace) or (None, CONCEPTS[it.concept]["aspect"])parts = fn(col, it) if fn else fallback(col, CONCEPTS[it.concept]["aspect"])if e.get("imagine") or e.get("material"):# rule: imagination (materials / skins on any model): see pydraw3d/imagine.pyfrom .imagine import apply_entityparts = apply_entity(parts, e, col, aspect, trace)if LIGHT and tod == "night":_light.night_dress(parts, it.concept, fn)mat3 = _light.apply_materials(parts, fn, it.concept, e, cname, it, col) if LIGHT else Noneif mat3:trace.append("3d: %s rendered as %s" % (it.concept, mat3))asp_r = max(aspect, getattr(parts, "aspect", None) or 0, getattr(parts, "height", 1.0) or 1.0) # a posed model's real extentbox_a = CONCEPTS[it.concept]["aspect"]aw = max(aspect, getattr(parts, "aspect", None) or 0) if getattr(parts, "fit_width", False) else aspectif fn and aw > box_a * 1.08 and KX.get("fitw", "1") == "1":# rule: a model wider than its layout box (a family model borrowed for a concept, a long low animal)# shrinks to the box width, so it is not cropped or pushed into its neighboursHw *= box_a * 1.08 / awif fn is not None and getattr(fn, "family", None) and it.bound is None and KX.get("famdepth", "1") == "1":# rule: the layout gives a family model's FRONT line; its body is deep, so its centre goes back by half# its depth (else big things - tents, igloos, buildings - spill out of the bottom of the frame)5 unmodified lines# rule: only side-view things (animals, vehicles) flip for "facing left"; front-facing models (screens, books) never show their backyaw = (math.pi if side and getattr(it, "facing", None) == "left" else 0.0) + (-.55 if getattr(it, "facing", None) == "left" else .55) * (1 if side else 0)yaw += rng.uniform(-.15, .15)if it.bound is not None and it.rel == "on" and id(it.bound) in tops and (getattr(it, "attrs", None) or {}).get("fixed_scale"):# rule (surreal scale): a tiny thing on a support stands exactly on the support's drawn topbX, bY, bZ, bH, bparts = tops[id(it.bound)]from .imagine import union, top_atty = top_at(union(bparts), 0.0, 0.0, 2.0)ty = CONCEPTS[it.bound.concept].get("on_top", 1.0) if ty is None else tyX, Yb, Z = bX, bY + bH * ty - .01 * bH, bZtops[id(it)] = (X, max(0.0, Yb), Z, Hw, parts)objs.append(Obj(parts, (X, max(0.0, Yb) if (it.bound is None or it.rel != "on") else Yb, Z), Hw, yaw, it.concept, asp_r))objs[-1].col = colobjs[-1].target = COLORS[cname] if (cname in COLORS and e.get("color_explicit", True)) else Noneobjs[-1].cname = cnameobjs[-1].ent, objs[-1].k, objs[-1].inst = getattr(it, "ent", None), getattr(it, "k", 0), itobjs[-1].yaw += program.get("yaw", {}).get((objs[-1].ent, objs[-1].k), 0.0)if mat3 in ("metal", "gold", "bronze"):objs[-1].target = None # rule: a metal's colour lives in its reflections; the colour check would flatten theminteract.place(it, objs[-1], trace) # wave 11: held things in hand / mouth / beak, riders on the saddletrace.append("3d: %s at x=%.2f y=%.2f z=%.2f h=%.2f" % (it.concept, X, Yb, Z, Hw))camd = Noneimport re as _re_framing = bool(_re.search(r"close[- ]?up|portrait|macro|wide shot|establishing|aerial|from above|top view|bird'?s[- ]eye|from below|low angle|high angle|isometric|eye level", text.lower()))_single = len(scene["entities"]) == 1 and scene["entities"][0].get("count", 1) == 1# rule: the director takes over only where it measurably helped by eye (framing words, a single subject); plain# multi-object scenes keep the layout's camera (the director could only shrink spread-out groups)_outdoor = place not in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office", "street", "space", "sky")# rule (merge): the procedural world needs the layout camera (its terrain caster assumes it), so a single outdoor# subject keeps the world unless the prompt asks for a framing_cam_on = KX.get("cam", "auto") == "1" or (KX.get("cam", "auto") == "auto" and (_framing or (_single and not (_outdoor and KX.get("world", "1") == "1"))))if _cam_on and objs:# rule: a director of photography picks the shot, composes by search and places the key light (pydraw3d/camera.py)from . import camera as _cameracamd = _camera.direct(text, scene, objs, place, tod, upm, R, seed, trace)indoor = place in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office") and KX.get("wall", "1") == "1"wall_z = Noneif indoor:4 unmodified lineszc_ = float(np.median([o.base[2] for o in objs])) if objs else 4 * camstreet = (zc_ + 9.0 * upm, upm, seed)sc = Scene3D(objs, backdrop_z=wall_z, cove=(.35 * wall_z if place == "studio" else .0), street=street)sc.glassy = {k for k, o in enumerate(objs) if any(getattr(pt, "glass", 0) for pt in o.parts)} if LIGHT else set()# ---- camera rays: principal point on the layout's horizon (built per pass below) ----O = np.array([0, cam, 0.0])zfar = max([o.base[2] for o in objs] + [cam * 8]) * 6zfog = zfarif camd is not None:O = camd.Ozfar = max([float(np.linalg.norm(o.base - O)) for o in objs] + [cam * 8]) * 6zen, hor, sunc, sun_i, amb = SKIES[tod]zen, hor, sunc = lin(zen), lin(hor), lin(sunc)if LIGHT and tod == "night":sun_i, amb = .35, .2 # rule: moonlight is dimmer, so lamps, fires and windows carry the pictureif KX.get("warm", "0") == "1" and tod == "day":# rule: warm key / cool fill: a slightly golden sun against a bluer sky ambient reads as late-morning lightsunc = lin((255, 232, 200)); zen = zen * np.array([.9, .95, 1.1])1 unmodified line# rule: snow stays white at golden hour (only a hint of warmth), otherwise it reads as desert sandsunc = sunc * .35 + lin((255, 240, 225)) * .65sx = -.55 if rng.random() < .5 else .55sx = program.get("sun_x", sx)L = np.array([sx, program.get("sun_y", .55) if tod == "day" else .18, -.45])L /= np.linalg.norm(L)studio = place in ("studio", "table") or place in ("room", "kitchen", "bedroom", "bathroom", "office")if studio:back = rng.choice(BACKDROPS)if place == "table":back = rng.choice(TABLE_WALLS)back = lin(program.get("backdrop", back))hor = backzen = back * .7L = np.array([sx, .7, -.5]); L /= np.linalg.norm(L)sunc = lin((255, 246, 235))sun_i, amb = 2.4, 1.1if tod == "night" and LIGHT:# rule: a room at night is dark: dim walls, faint cool moonlight; its lamps, candles and screens light itback = back * .16hor, zen = back, back * .7sunc, sun_i, amb = lin((150, 170, 225)), .35, .45rimk = float(KX.get("rim", "0"))if camd is not None:L, rimk = _camera.key_light(camd, tod, studio, trace)world = interior = Noneif wall_z is not None and place not in ("studio", "table") and KX.get("interior", "1") == "1":# rule (interior): rooms are furnished: furniture along the back wall, rug, paintings, curtains, a window viewfrom .interior import make_interiorinterior = make_interior(scene, objs, wall_z, upm, cam, seed, L, trace, Obj, MODELS)objs.extend(interior.objs)if not studio and camd is None and KX.get("world", "1") == "1":# rule (world): outdoor scenes get a procedurally generated world around the subjects (pydraw3d/world.py)from .world import make_worldworld = make_world(scene, text, objs, upm, cam, seed, tod, L, trace, KX)if world is not None:world.build()zen, hor, sunc, sun_i, amb = world.light(zen, hor, sunc, sun_i, amb)objs.extend(world.hero_objects(Obj, objs))sc.world = worldsc_obj = Scene3D(objs, ground=False)tobj = max([float(S.length(o.center[None, :] - O[None, :])[0]) + o.radius for o in objs] or [cam]) * 1.2lights = _light.find_lights(objs) if LIGHT and tod in ("night", "sunset") and KX.get("plights", "1") == "1" else []if LIGHT and studio and tod == "night" and not lights and KX.get("plights", "1") == "1":# rule: a room at night with no lamp in the prompt still has one, off-screen up and to the side (warm practical)zc_ = float(np.median([o.base[2] for o in objs])) if objs else 3 * camsc_ = float(np.median([o.scale for o in objs])) if objs else camlights = [(np.array([-L[0] / abs(L[0]) * 1.2 * sc_, 2.2 * sc_, zc_ - 1.0 * sc_]), lin((255, 200, 140)) / lin((255, 200, 140)).max(),2.2 * sc_ ** 2, -99, .3 * sc_)]lgain = float(KX.get("lgain", .7)) * (1.0 if tod == "night" else .35)if lights:trace.append("3d: %d emissive point light(s) from %s" % (len(lights), ", ".join(sorted({objs[l[3]].name if l[3] >= 0 else "off-screen lamp" for l in lights}))))# rule (colour bleeding): the light bouncing up from the ground has the ground's colour (green under animals# on grass, warm wood under things on a table, white on snow) and scales with the sunbounce_c = lin((120, 110, 90)) * .25if LIGHT and KX.get("bleed", "1") == "1":gcol = lin((150, 102, 64)) if place == "table" else lin((160, 118, 80)) if (studio and place != "studio") else \(back if studio else lin(GROUNDS.get(place, GROUNDS["field"])[0]) if place not in ("water", "lake", "sea", "river") else lin((60, 90, 110)))bounce_c = bounce_c * .4 + gcol * sunc * sun_i * .07floor_ref = lin((150, 102, 64)) if place == "table" else (lin((160, 118, 80)) if (studio and place != "studio") else (back if studio else hor))def bg(D, xsf, ysf, land=True):# ---- background ----if world is not None:return world.sky(D)up = np.clip(D[:, 1], -1, 1)sky = hor + (zen - hor) * np.clip(up * 2.2, 0, 1)[:, None] ** .8if not studio:16 unmodified linessky = back * (1.05 - .9 * r2)[:, None]return skydef shade(D, xsf, ysf, lcache=None, pix=None, O_=None, depth=0):Oc = O if O_ is None else O_ # secondary rays (refraction / reflection) start on a surfaceif world is not None and O_ is None:# rule (world): terrain hits come from the column heightfield caster, objects from the SDF marchtw, hw = world.cast(D)t_o, h_o = march(sc_obj, O, D, np.minimum(np.where(hw, tw * 1.001, tobj), tobj))useo = h_o & (~hw | (t_o < tw))t, hit = np.where(useo, t_o, tw), useo | hwelse:t, hit = march(sc, Oc, D, zfar)P = Oc + D * t[:, None]O0 = Ocsky = bg(D, xsf, ysf) if not (depth and studio and LIGHT) else _light.studio_env(D, back, L, floor_ref)col = sky.copy()idmap = np.full(len(D), -2)cmap = np.zeros(len(D), bool)4 unmodified linesif len(hi):Ph = P[hi]d, ids = sc.dist(Ph, want_id=True)if world is not None:N = np.zeros((len(hi), 3))ob_ = ids >= 0if ob_.any():N[ob_] = normals(sc, Ph[ob_], 1e-3 * np.maximum(t[hi][ob_], .1)[:, None] * .5)else:N = normals(sc, Ph, 1e-3 * np.maximum(t[hi], .1)[:, None] * .5)alb = np.zeros((len(hi), 3))spec = np.zeros(len(hi))rough = np.ones(len(hi)) * .83 unmodified linesif g.any():q = Ph[g]wallm = (N[g][:, 2] < -.5) if wall_z is not None else np.zeros(len(q), bool)if world is not None:Nw, a_, sp_, ro_, wmk, w_sh, w_ao, w_em = world.surface(q, D[hi][g], t[hi][g])N[g], alb[g], spec[g], rough[g] = Nw, a_, sp_, ro_water_mask = np.zeros(len(hi), bool)water_mask[np.nonzero(g)[0][wmk]] = Truefac_em = np.zeros(len(hi))fac_em[g] = w_emelif studio and place == "table":wood = lin((150, 102, 64))grain = S.noise3(q * np.array([3, 1, 60]) / max(upm, 1e-3) * 2, seed)a_ = wood * (0.8 + .35 * grain)[:, None]13 unmodified linesframe = win & ((np.abs(np.abs(q[:, 0] - .9 * upm * np.sign(-L[0])) - .55 * upm) < .05 * upm) |(np.abs(q[:, 1] - .9 * upm) < .05 * upm) | (np.abs(q[:, 1] - 2.0 * upm) < .05 * upm) |(np.abs(q[:, 0] - .9 * upm * np.sign(-L[0])) < .025 * upm) | (np.abs(q[:, 1] - 1.45 * upm) < .025 * upm))a_[win] = lin((200, 225, 245)) * (3.0 if tod != "night" else .12) # bright sky through the window (emissive-ish)a_[frame] = lin((245, 245, 240))if interior is not None:a_ = interior.surfaces(q, wallm, a_, win, frame)alb[g] = a_spec[g], rough[g] = np.where(wallm, .05, .35), np.where(wallm, .9, .35)elif studio:79 unmodified linesgg = alb[g]gg[dot] = pal[pick[dot]]alb[g] = ggif _NAT.ON and g.any():# rule (natural): ground / walls / facades get dead-leaves and synthesised-statistics detailalb[g] = _NAT.ground(place, Ph[g], alb[g], D[hi][g], t[hi][g], f, upm, cam, wallm, ids[g], studio, seed)em = np.zeros(len(hi)) if fac_em is None else fac_emmetal = np.zeros(len(hi)) # imagination skins: metals tint their reflections with their own colourglass = np.zeros(len(hi)) # imagination skins: glass / ice / jelly let the scene behind show throughcpart = np.zeros(len(hi), bool)fl = _light.Flags(len(hi)) if LIGHT else Nonefor k, o in enumerate(objs):sel = ids == kif not sel.any():continuepi, q = o.part_index(Ph[sel])if _NAT.ON:_NAT.FP = float(np.median(t[hi][sel])) / (f * o.scale) # model units per pixel (texture AA)a = np.zeros((sel.sum(), 3))sp = np.zeros(sel.sum())ro = np.zeros(sel.sum())4 unmodified linesif getattr(pt, "pat", None):a[m] = pattern(pt.pat, q[m], a[m], seed + k)sp[m], ro[m] = pt.spec, pt.roughif fl is not None:fl.collect(pt, np.nonzero(sel)[0][m])if getattr(pt, "emit", 0):em[np.nonzero(sel)[0][m]] = pt.emitif getattr(pt, "metal", 0):metal[np.nonzero(sel)[0][m]] = pt.metalif getattr(pt, "glass", 0):glass[np.nonzero(sel)[0][m]] = pt.glassif o.target is not None and o.col is not None and np.allclose(pt.color, o.col):cpart[np.nonzero(sel)[0][m]] = Truealb[sel], spec[sel], rough[sel] = a, sp, roif LIGHT:# rule (merge): with the light module on, glass and metal parts are traced by pydraw3d/light.py;# the imagination engine's simpler see-through / tinted-mirror passes stand downmetal[:] = 0glass[:] = 0subj_ = [o for o in objs if not getattr(o, "dressing", False)]scl = np.maximum(np.array([o.scale for o in subj_]).mean() if subj_ else cam, .05)if world is not None:# rule (world): soft shadows / AO are traced only near the subjects; the far world uses its baked mapssha, ao = np.ones(len(hi)), np.ones(len(hi))nr = (ids >= 0) | (t[hi] < world.zb * 2.5)if nr.any():sha[nr] = soft_shadow(sc, Ph[nr] + N[nr] * 2e-3 * scl, L, zfar * .5, scl)ao[nr] = ambient_occ(sc, Ph[nr], N[nr], scl)if g.any():sha[g] *= w_shao[g] *= w_aosha = sha * world.light_mod(Ph)elif lcache is not None and pix is None:sha, ao, good = lcache.lookup(xsf[hi], ysf[hi], ids)need = np.nonzero(~good)[0]if len(need):sha[need] = soft_shadow(sc, Ph[need] + N[need] * 2e-3 * scl, L, zfar * .5, scl)ao[need] = ambient_occ(sc, Ph[need], N[need], scl)else:sha = soft_shadow(sc, Ph + N * 2e-3 * scl, L, zfar * .5, scl)ao = ambient_occ(sc, Ph, N, scl)if lcache is not None:lcache.store(pix[hi], ids, sha, ao)dif = np.clip(N @ L, 0, 1)skyl = np.clip(.5 + .5 * N[:, 1], 0, 1)bounce = np.clip(.5 - .5 * N[:, 1], 0, 1)3 unmodified linesspc = spec * np.clip(N @ L, 0, 1) ** 0 * np.clip((N * H).sum(-1), 0, 1) ** shin * (shin + 8) / 60 * shafres = spec * (1 - np.clip(-(N * D[hi]).sum(-1), 0, 1)) ** 5light = (sunc * sun_i * (dif * sha)[:, None] + (zen * .6 + hor * .4) * amb * (skyl * ao)[:, None]+ bounce_c * (bounce * ao)[:, None])if lights:light = light + _light.point_lights(sc, lights, Ph, N, ids, scl, lgain)if fl is not None and fl.any:light = _light.sss_light(light, fl, N, L, sha, dif, alb, sunc, sun_i, (zen * .6 + hor * .4) * amb)c = alb * light + sunc[None, :] * spc[:, None] + hor[None, :] * fres[:, None] * .4 * ao[:, None]if water_mask is not None and water_mask.any():# rule: water reflects the sky (and the landscape) along the mirrored ray, stronger at grazing angles,6 unmodified linesDv = D[hi][wi]Rv = Dv - 2 * (Dv * wn).sum(-1)[:, None] * wnRv[:, 1] = np.abs(Rv[:, 1])if world is not None:c[wi] = world.water_color(Ph[wi], light[wi])refl = world.reflect(Ph[wi], Rv, lambda R_: bg(R_, None, None))else:refl = bg(Rv.astype(np.float32), xsf[hi][wi], ysf[hi][wi])fr = .25 + .7 * (1 - np.clip(-(Dv * wn).sum(-1), 0, 1)) ** 4if world is not None:fr = fr * world.refl_kc[wi] = c[wi] * (1 - fr[:, None]) + refl * fr[:, None] * sha[wi][:, None] ** .3shiny = (spec > .7) & (rough < .2) & ((ids >= 0) | (ids == -3))if shiny.any() and KX.get("envrefl", "1") == "1":4 unmodified linesRv = Dv - 2 * (Dv * Ns).sum(-1)[:, None] * Nsrefl = bg(Rv.astype(np.float32), xsf[hi][si], ysf[hi][si], land=False)fr = .15 + .55 * (1 - np.clip(-(Dv * Ns).sum(-1), 0, 1)) ** 3mt = metal[si][:, None]if mt.any():# rule (metal): a metal has almost no diffuse colour; it mirrors its surroundings (dark ground below,# bright sky above) at every angle, tinted by its own colourfr = fr * (1 - mt[:, 0]) + .9 * mt[:, 0]down = np.clip(-Rv[:, 1] * 3, 0, 1)[:, None]rm = refl * (1 - .8 * down) * alb[si] * 2.6refl = refl * (1 - mt) + rm * mtc[si] = c[si] * (1 - .75 * mt)c[si] = c[si] * (1 - fr[:, None] * .6) + refl * (fr * ao[si])[:, None]if fl is not None and fl.any and ((fl.glass > 0).any() or (fl.metal > 0).any()):c = _light.secondary(c, fl, ids, Ph, N, D[hi], alb, rough, sha, ao, objs,lambda D2, O2, xs2, ys2, dep: shade(D2, xs2, ys2, O_=O2, depth=dep)[0],(lambda D2, xs2, ys2: bg(D2, xs2, ys2, land=False)) if not studio else(lambda D2, xs2, ys2: _light.studio_env(D2, back, L, floor_ref)), xsf[hi], ysf[hi], depth, sunc, sun_i, L,(zen * .5 + hor * .5) if not studio else back)if em.any():# rule: emissive parts (screens, lamps, fire) glow with their own colour regardless of lightingc = c * (1 - np.clip(em, 0, 1))[:, None] + alb * (em * 2.2)[:, None]if rimk:# rule: a soft rim light on object silhouettes separates them from the background (cinematic three-point look)obj = ids >= 0vdn = np.clip(-(N * D[hi]).sum(-1), 0, 1)rim = (1 - vdn) ** 3 * rimk * objc = c + (sunc * .6 + hor * .4)[None, :] * (rim * ao)[:, None]if glass.any() and O_ is None and KX.get("glass", "1") == "1":# rule (glass): the ray goes on through the object, bent a little toward the inside (refraction), and the# scene behind is shaded with the glass objects skipped; the glass tints it and keeps its own# reflections at grazing angles (Fresnel)gi = np.nonzero(glass > 0)[0]Dg, Ng = D[hi][gi], N[gi]D2 = Dg - .35 * NgD2 = (D2 / S.length(D2)[:, None]).astype(D.dtype)sc.skip = {k for k, o in enumerate(objs) if any(getattr(pt, "glass", 0) for pt in o.parts)}try:behind, _, _, _ = shade(D2, xsf[hi][gi], ysf[hi][gi], O_=(Ph[gi] + D2 * 1e-3).astype(D.dtype))finally:sc.skip = ()tint = alb[gi] / np.maximum(alb[gi].max(-1, keepdims=True), 1e-3)fres = .08 + .8 * (1 - np.clip(-(Dg * Ng).sum(-1), 0, 1)) ** 3g_ = glass[gi][:, None]see = behind * (.35 + .65 * tint) * (1 - fres[:, None])c[gi] = c[gi] * (1 - g_) + (see + c[gi] * (fres[:, None] * .7 + .05)) * g_# rule: aerial perspective, far things fade into the horizon colourif world is not None:c = world.fog(c, t[hi], D[hi], Ph)else:tfog = t[hi] if camd is None else np.maximum(t[hi] - camd.fog_offset, 0)fog = 1 - np.exp(-tfog / (zfog * (.5 if studio else .25)) * fogk * (.45 if place == "street" else 1))c = c * (1 - fog[:, None]) + hor[None, :] * fog[:, None]col[hi] = cidmap[hi] = idscmap[hi] = cpart1 unmodified linedbg = os.environ.get("PYDRAW3D_DBG")if dbg:col[hi] = {"sha": sha, "ao": ao, "dif": dif}[dbg][:, None] * np.ones(3)if world is not None and world.uw:col = col + (sunc * .55 + zen * .3)[None, :] * world.godrays(D, tmap)[:, None] * 1.6return col, idmap, tmap, cmapdef rays(xp, yp):if camd is not None:Dd = camd.rays(xp, yp, R)return Dd.astype(np.float32) if KX.get("f32", "1") == "1" else DdDd = np.stack([(xp - R / 2) / f, (y0 - yp) / f, np.ones_like(xp)], -1)Dd = Dd / S.length(Dd)[:, None]return Dd.astype(np.float32) if KX.get("f32", "1") == "1" else Ddif KX.get("preview"):# search preview: the full-resolution camera sampled on a coarse n x n grid, one ray per pixel, no AAn = int(KX["preview"])ys, xs = np.mgrid[0:n, 0:n].astype(float)xsf, ysf = (xs.reshape(-1) + .5) * R / n, (ys.reshape(-1) + .5) * R / n_STEPS.update(march=int(KX.get("msteps", 90)), shadow=int(KX.get("shsteps", 12)))try:col, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf)finally:_STEPS.clear()ss_eff = 1elif KX.get("aa", "adaptive") == "adaptive" and ss == 1:# rule: anti-alias adaptively: shade one ray per pixel, find edges (object id changes or strong contrast),# then re-shade only those pixels with a 4-ray rotated grid (most of the 2x2 supersampling gain, ~1/3 the cost)n = Rys, xs = np.mgrid[0:n, 0:n].astype(float)xsf, ysf = xs.reshape(-1) + .5, ys.reshape(-1) + .5lc = _accel.LightCache(n) if (ACCEL and KX.get("lcache", "1") == "1") else Nonecol, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf, lc, np.arange(n * n))idg = idm.reshape(n, n)lum = (col * np.array([.3, .59, .11])).sum(-1).reshape(n, n) ** (1 / 2.2)# rule (natural): synthesised texture is band-limited (mip / fade), so it must not trigger edge re-shadingthr = float(KX.get("aathr", .11 if _NAT.ON else .06))edge = np.zeros((n, n), bool)eh = (idg[:, :-1] != idg[:, 1:]) | (np.abs(lum[:, :-1] - lum[:, 1:]) > thr)ev = (idg[:-1, :] != idg[1:, :]) | (np.abs(lum[:-1, :] - lum[1:, :]) > thr)2 unmodified linesei = np.nonzero(edge.reshape(-1))[0]if len(ei):acc = np.zeros((len(ei), 3))pat = ((-.375, -.125), (.125, -.375), (.375, .125), (-.125, .375))if KX.get("aan", "3") == "3":# rule (speed): the centre sample is already shaded; three more on a triangle make the 4-sample averagepat = ((-.36, -.2), (.36, -.2), (0, .4))acc += col[ei]for ox, oy in pat:cx, cy = xsf[ei] + ox, ysf[ei] + oyc_, _, _, _ = shade(rays(cx, cy), cx, cy, lc)acc += c_col[ei] = acc / 4trace.append("3d: adaptive AA re-shaded %d edge pixels (%.0f%%)" % (len(ei), 100 * len(ei) / (n * n)))6 unmodified linesss_eff = ss# ---- tone map, grade, output ----if LIGHT and KX.get("lens", "1") == "1":col = _light.lens(col, n, tod, float(KX.get("bloom", 1.0)), float(KX.get("vig", 0.0 if _NAT.ON else 1.0)), float(KX.get("grain", 0)), seed)if _NAT.ON and KX.get("ncam", "1") == "1":# rule (natural): a physically modelled camera (lens, Bayer sensor noise, demosaic, colour matrix) before the tone curvecol, idm, tm, cmp_ = _NAT.camera_linear(col, idm, tm, cmp_, n, tod, place, seed, trace, KX)out = aces(col * float(KX.get("expo", 1.1))) ** (1 / 2.2)sat, con = float(KX.get("sat", 1.0)), float(KX.get("con", 1.0))if sat != 1.0 or con != 1.0:1 unmodified linelum = (out * np.array([.299, .587, .114])).sum(-1, keepdims=True)out = lum + (out - lum) * satout = .5 + (out - .5) * conraw = np.clip(out, 0, 1)if KX.get("colorfix", "1") == "1":out = color_fix(np.clip(out, 0, 1), idm, cmp_, objs, trace)if camd is not None and KX.get("finish", "1") == "1":out = _camera.finish(np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), tm.reshape(n, n), camd, place, tod, hor, seed, trace).reshape(-1, 3)if world is not None:out = world.post(np.clip(out, 0, 1).reshape(n, n, 3), tm.reshape(n, n), idm.reshape(n, n), None).reshape(-1, 3)if _NAT.ON and KX.get("ncam", "1") == "1" and KX.get("sharp", "1.5") != "0":# rule (natural): in-camera sharpening sized by the measured gap to the 1/f^2 spectrumout, dfc = _NAT.spectral_sharpen(out, n, kx=KX)trace.append("3d: spectrum deficit %.2f log10 (mid/high band) -> spectral sharpening" % dfc)if _NAT.ON and KX.get("ncam", "1") == "1" and KX.get("jpeg", "1") == "1":out = _NAT.jpeg(out, n, int(KX.get("jq", 88)))painted = Noneif KX.get("preview"):# rule (search): previews hand back the buffers the critic reads (colour before/after the colour check,# object ids, depth) plus what it needs to re-march single objectsim = Image.fromarray((np.clip(out, 0, 1).reshape(n, n, 3) * 255 + .5).astype(np.uint8))im.info.update(trace=trace, scene=scene, buffers=dict(rgb=np.clip(out, 0, 1).reshape(n, n, 3), raw=raw.reshape(n, n, 3), ids=idm.reshape(n, n), depth=tm.reshape(n, n),objs=objs, insts=insts, R=R, n=n, f=f, y0=y0, O=O, zfar=zfar, place=place, tod=tod, studio=studio))return (im, trace) if return_trace else impst = scene.get("art") or scene.get("style")if pst and KX.get("paint", "1") == "1":from .paint import STYLES as _PSif pst in _PS:# rule: a style word re-paints the render with a painting algorithm (oil strokes, watercolour washes,# ukiyo-e, stained glass, mosaic, ...; pydraw3d/paint.py) using the render's object ids and depthout = _PS[pst](np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), tm.reshape(n, n), seed)painted = psttrace.append("3d: painted as %s" % painted)img = (np.clip(out, 0, 1).reshape(n, n, 3) * 255 + .5).astype(np.uint8)im = Image.fromarray(img)16 unmodified linesif ss_eff > 1:im = im.resize((R, R), Image.LANCZOS)im = im.resize((size, size), Image.BICUBIC)if float(KX.get("soft", 0)) > 0 and not painted and not (_NAT.ON and KX.get("ncam", "1") == "1"): # the camera MTF replaces itfrom PIL import ImageFilterim = im.filter(ImageFilter.GaussianBlur(float(KX.get("soft")))) # rule: a touch of lens softness_NAT.ON = Falsetrace.append("3d: rendered %dx%d (ss=%d) in %.1fs" % (R, R, ss, time.time() - t0))im.info["trace"] = traceim.info["scene"] = scene
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Speed-ups for the SDF ray marcher: tight per-object and per-part bounding boxes found by sampling each model once.
rule (speed): a model is a union of parts; most points a ray visits are far from most parts (a ray passing a horse'shead never needs the tail). Each part gets an axis-aligned box in the model's local frame that provably encloses itssurface: sample the part's SDF on a grid over the object's bounding sphere; any surface point lies within half acell diagonal of a grid point whose SDF value is <= that half diagonal (SDFs never over-estimate), so the box ofthose grid points grown by the half diagonal holds the whole surface. Outside the box, the distance to the box is alower bound of the distance to the part, so marching stays safe; inside (or within a margin) the part is evaluatedexactly. The whole object gets the union box, which is far tighter than its bounding sphere.Pure numpy; no change to what is rendered beyond rounding (exact evaluation wherever a surface can be)."""import numpy as np
GRID = 28
def box_dist(q, lo, hi): """distance from points q (N,3) to the axis-aligned box [lo, hi] (0 inside)""" c = (lo + hi) * .5 h = (hi - lo) * .5 d = np.abs(q - c) - h d = np.maximum(d, 0) return np.sqrt(np.einsum("ij,ij->i", d, d))
def compute_bounds(obj): """Sets obj.pbox (list of (lo, hi) per part, or None = unbounded), obj.box (lo, hi) or None, obj.kmax.""" rl = obj.radius / obj.scale cen = np.array([0, .5, 0], np.float32) ax = np.linspace(-rl, rl, GRID).astype(np.float32) g = np.stack(np.meshgrid(ax, ax, ax, indexing="ij"), -1).reshape(-1, 3) + cen h = float(ax[1] - ax[0]) hd = h * .5 * 3 ** .5 border = np.zeros((GRID,) * 3, bool) border[[0, -1], :, :] = border[:, [0, -1], :] = border[:, :, [0, -1]] = True border = border.reshape(-1) boxes = [] for pt in obj.parts: try: d = np.asarray(pt.fn(g), float).reshape(-1) except Exception: boxes.append(None) continue if d.shape[0] != len(g) or not np.isfinite(d).all(): boxes.append(None) continue m = d <= hd * 1.05 if (m & border).any(): boxes.append(None) # the part reaches the sampled domain's edge: leave it unbounded continue if not m.any(): # nothing within reach of the grid: a tiny or empty part -> fall back to exact evaluation boxes.append(None) continue lo = g[m].min(0) - hd - .01 hi = g[m].max(0) + hd + .01 boxes.append((lo.astype(np.float32), hi.astype(np.float32))) obj.pbox = boxes obj.kmax = max([float(pt.k) for pt in obj.parts] + [0.0]) if all(b is not None for b in boxes) and boxes: lo = np.min([b[0] for b in boxes], 0) - obj.kmax * .3 hi = np.max([b[1] for b in boxes], 0) + obj.kmax * .3 obj.box = (lo, hi) else: obj.box = None
def part_values(obj, q, margin): """per-part SDF values at local points q; parts whose box is farther than the margin get the box distance (a lower bound) instead of an exact evaluation""" thr = max(margin, 2 * obj.kmax + .02) out = [] for pt, b in zip(obj.parts, obj.pbox): if b is None: out.append(pt.fn(q)) continue bd = box_dist(q, b[0], b[1]) sub = bd < thr if sub.all(): out.append(pt.fn(q)) elif not sub.any(): out.append(bd) else: e = bd.astype(np.float64) e[sub] = pt.fn(q[sub]) out.append(e) return out
def soft_shadow(scene, P, L, tmax, scl, k=6.0, steps=48, margin=1.5, grow=1.3): """Soft shadows (iq's penumbra estimate), with two speed rules: rule (speed): a shadow ray only marches while it can still meet an object: its end is the farthest exit from the (grown) bounding spheres it crosses; rays that cross none are fully lit at once (ground and back walls never shadow the sun side; street facades keep the full march). rule (speed): rays leave the loop as soon as they are fully dark or past their end (compaction).""" n = len(P) res = np.ones(n) t = np.full(n, .08 * scl) if scene.street is not None or not scene.objs: tend = np.full(n, tmax) if scene.street is not None else np.zeros(n) else: tend = np.zeros(n) for o in scene.objs: oc = P - o.center b = oc @ L c = np.einsum("ij,ij->i", oc, oc) - (o.radius * grow) ** 2 disc = b * b - c ok = disc > 0 te = np.where(ok, -b + np.sqrt(np.maximum(disc, 0)), 0) tend = np.maximum(tend, te) tend = np.minimum(tend, tmax) active = tend > t for _ in range(steps): idx = np.nonzero(active)[0] if not len(idx): break ti = t[idx] d = scene.dist(P[idx] + L * ti[:, None], margin=margin) 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 < tend[idx]) & (r > .003) return np.clip(res, 0, 1) ** 1.5
class LightCache: """rule (speed): anti-aliasing sub-samples reuse the shadow and AO of the primary pass: bilinear interpolation between the four nearest pixel centres that show the SAME surface (object id); a sub-sample with no such neighbour is shaded exactly. Shadows and AO are smooth across a pixel, the edges AA cares about are silhouettes."""
def __init__(self, n): self.n = n self.sha = np.full(n * n, np.nan, np.float32) self.ao = np.full(n * n, np.nan, np.float32) self.ids = np.full(n * n, -9, np.int64)
def store(self, pix, ids, sha, ao): self.sha[pix], self.ao[pix], self.ids[pix] = sha, ao, ids
def lookup(self, x, y, ids): n = self.n fx, fy = x - .5, y - .5 x0, y0 = np.floor(fx).astype(np.int64), np.floor(fy).astype(np.int64) tx, ty = fx - x0, fy - y0 ws = np.zeros(len(x)); s = np.zeros(len(x)); a = np.zeros(len(x)) for dx, dy, w in ((0, 0, (1 - tx) * (1 - ty)), (1, 0, tx * (1 - ty)), (0, 1, (1 - tx) * ty), (1, 1, tx * ty)): xi, yi = np.clip(x0 + dx, 0, n - 1), np.clip(y0 + dy, 0, n - 1) k = yi * n + xi ok = (self.ids[k] == ids) & np.isfinite(self.sha[k]) w = np.where(ok, w, 0) ws += w s += w * np.nan_to_num(self.sha[k]) a += w * np.nan_to_num(self.ao[k]) good = ws > .2 return np.where(good, s / np.maximum(ws, 1e-9), 0), np.where(good, a / np.maximum(ws, 1e-9), 0), good123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559"""pydraw3d.camera: a pure-code director of photography.
The layout (pydraw/layout.py) decides WHAT is in the scene and where things stand relative to each other; plot3dback-projects that into a 3D world. This module then decides HOW to photograph that world, the way a photographeror illustrator would, with hand-written rules only (no learning):
1. shot choice: from the prompt's framing words (close-up, macro, portrait, wide/establishing shot, aerial, from below, isometric, eye level) and from what is in the scene (heroic large animals -> low angle; tabletop and small things -> slightly high; single small subject -> close; buildings and landscapes -> wide establishing shot with a shifted lens so verticals stay straight; pets -> down at their eye level).2. composition: a hand-written aesthetic energy over the projected scene (rule of thirds / golden section for the subject's centre of interest, subject size, headroom, lead room in the facing direction, no cut-off subjects, no tangents with the frame edges or between subjects, overlap that reveals depth without hiding counted things, horizon off-centre and not through a head, balance of visual weight), minimised by random search + local refinement over (azimuth, elevation, distance, field of view, pan, tilt, lens shift). Hard constraints keep the prompt readable: left/right order of things is kept, nothing counted is hidden or cut off.3. light: a three-quarter key light from the open side of the frame by day/indoors, a low back/side sun (rim) at sunset, a back rim at night.4. depth cues: soft out-of-focus foreground framing (grass blades / leaves) along an edge away from the subjects, distance haze relative to the subject distance, a gentle lens vignette.
Entry point: direct(...) -> Camera (used by pydraw3d.plot3d; knob cam=0 turns the director off)."""import math, random, reimport numpy as np
from pydraw.registry import CONCEPTS
THIRDS = (1 / 3, 2 / 3)GOLDEN = (.382, .618)
# ---- framing words (read from the raw prompt so the parser is untouched) ----WORDS = [ (r"\b(isometric|axonometric)\b", "iso"), (r"\b(aerial|bird'?s?[ -]eye|birds eye|top[- ]down|top view|overhead|from above|drone (shot|view)|satellite)\b", "aerial"), (r"\b(from below|low[- ]angle|worm'?s?[- ]eye|looking up at|towering)\b", "low"), (r"\b(high[- ]angle|looking down (at|on))\b", "high"), (r"\b(macro)\b", "macro"), (r"\b(extreme close[- ]?up|close[- ]?up|closeup|headshot|portrait of|portrait|detail shot)\b", "close"), (r"\b(wide[- ]angle|wide shot|establishing shot|panorama|panoramic|landscape shot|long shot|vista|in the distance)\b", "wide"), (r"\b(full[- ]body|full shot|medium shot)\b", "medium"), (r"\b(eye[- ]level)\b", "eye"),]
# ---- shot presets: (elevation deg range, fov deg range, subject height fraction target, azimuth deg range) ----SHOTS = { "medium": ((6, 16), (38, 50), .60, 22), "pet": ((0, 8), (34, 46), .50, 22), # down at the animal's eye level "table": ((18, 32), (32, 44), .60, 22), # tabletop: slightly high, gentle tele "small": ((14, 26), (28, 38), .58, 20), # one small object: close, slightly high "close": ((2, 12), (24, 34), .68, 16), "portrait": ((-2, 6), (22, 30), .66, 14), "macro": ((8, 22), (22, 30), .72, 18), "hero": ((-16, -5), (44, 60), .62, 24), # low angle, wide-ish lens, subject towers "wide": ((3, 10), (50, 64), .50, 18), # establishing shot "aerial": ((42, 62), (40, 52), .46, 20), "iso": ((33, 37), (8, 10), .55, 0),}
class Camera: def __init__(self, O, yaw, pitch, fov, shift=0.0): self.O = np.asarray(O, float) self.yaw, self.pitch, self.fov, self.shift = yaw, pitch, fov, shift cy, sy, cp, sp = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch) self.fwd = np.array([sy * cp, sp, cy * cp]) self.right = np.array([cy, 0.0, -sy]) self.up = np.cross(self.fwd, self.right) self.F = .5 / math.tan(fov / 2) # focal length in image widths
def project(self, P): d = P - self.O x, y, z = d @ self.right, d @ self.up, d @ self.fwd zz = np.maximum(z, 1e-6) u = .5 + x / zz * self.F v = .5 - y / zz * self.F - self.shift return u, v, z
def horizon_v(self): """screen v of the true horizon (direction of the view azimuth, level)""" h = np.array([math.sin(self.yaw), 0, math.cos(self.yaw)]) y, z = h @ self.up, h @ self.fwd return .5 - y / max(z, 1e-6) * self.F - self.shift
def rays(self, xp, yp, R): """unit ray directions for pixel centres (xp, yp) of an R x R image""" f = R * self.F a = (xp - R / 2) / f b = (R / 2 - yp) / f - self.shift * R / f D = self.fwd[None, :] + a[:, None] * self.right[None, :] + b[:, None] * self.up[None, :] return D / np.linalg.norm(D, axis=1)[:, None]
def frame_words(text): t = " " + text.lower().replace("-", " ") + " " found = [] for rx, tag in WORDS: if re.search(rx, t.replace(" ", " ")) or re.search(rx, text.lower()): found.append(tag) return found
# ---- occupancy point clouds (sample each SDF model on a grid; keep a thin shell) ----def cloud(o, n=16, keep=800, seed=0): """surface sample of a model: a coarse grid over its bounding sphere finds cells near the surface, each such cell is re-sampled 4x4x4 and only points on a thin shell around the surface are kept""" r = o.radius * 1.3 # models may poke a little out of their nominal bounding sphere g = np.linspace(-1, 1, n) * r X, Y, Z = np.meshgrid(g, g, g, indexing="ij") P = np.stack([X.ravel(), Y.ravel(), Z.ravel()], -1) + o.center cell = 2 * r / (n - 1) d = o.dist(P) C = P[np.abs(d) < .9 * cell] if len(C) > 6000: C = C[np.random.RandomState(seed).choice(len(C), 6000, replace=False)] off = (np.stack(np.meshgrid(*[np.linspace(-.375, .375, 4)] * 3, indexing="ij"), -1).reshape(-1, 3)) * cell Q = (C[:, None, :] + off[None]).reshape(-1, 3) sub = cell / 4 dq = o.dist(Q) m = (dq < .6 * sub) & (dq > -1.5 * sub) if m.sum() < 8: m = dq < 2 * sub P = Q[m] if len(P) > keep: P = P[np.random.RandomState(seed).choice(len(P), keep, replace=False)] if not len(P): P = o.center[None, :] return P
class Subject: """one rendered object with what the director needs to know about it""" def __init__(self, o, k, seed): it = getattr(o, "inst", None) self.o, self.k = o, k self.ent = getattr(it, "ent", k) self.implicit = bool(getattr(it, "implicit", False)) self.flying = getattr(it, "pose", None) == "flying" self.info = CONCEPTS.get(o.name, {}) self.P = cloud(o, seed=seed + k) y = self.P[:, 1] y0, y1 = y.min(), y.max() self.top = y1 living = self.info.get("animal") or o.name == "person" if living: # rule: the centre of interest of a creature is its head (upper part, front end) fw = np.array([math.cos(o.yaw), 0, -math.sin(o.yaw)]) hi = self.P[y > y0 + .65 * (y1 - y0)] if len(hi) > 3: proj = hi @ fw hi = hi[proj > np.percentile(proj, 50)] if (self.info.get("aspect", 1) > 1.05) else hi self.interest = hi.mean(0) if len(hi) else self.P.mean(0) else: self.interest = self.P.mean(0) self.living = living self.fw = np.array([math.cos(o.yaw), 0, -math.sin(o.yaw)]) # side-view models (animals, vehicles drawn in profile) face along local +x; frontal ones face the camera self.side_view = float(self.info.get("aspect", 1)) > 1.05 and bool(self.info.get("animal"))
def choose_shot(text, scene, subs, place, trace): words = frame_words(text) main = [s for s in subs if not s.implicit] or subs prim = [s for s in main if s.ent == main[0].ent] info = prim[0].info hm = float(info.get("height", 1.0)) # real-world metres n_ent = len({s.ent for s in main}) n_all = len(main) person = prim[0].o.name == "person" shot, why = None, "" for w in words: if w in ("iso", "aerial", "low", "macro", "close", "wide", "medium"): shot, why = {"low": "hero", "close": "portrait" if person else "close"}.get(w, w), "prompt says '%s'" % w break if shot is None and "high" in words: shot, why = "table" if place == "table" else "aerial", "prompt says high angle" if shot is None and scene.get("camera") == "high": shot, why = "aerial", "parser: seen from above" if shot is None and scene.get("camera") == "low": shot, why = "hero", "parser: from below" if shot is None and scene.get("framing") == "close": shot, why = ("portrait" if person else "close"), "parser: close-up framing" if shot is None: big = max(float(s.info.get("height", 1)) for s in main) if place == "table": shot, why = "table", "tabletop -> slightly high" elif big >= 5 and not any(s.info.get("animal") for s in main if float(s.info.get("height", 1)) >= 5): shot, why = "wide", "building / landscape-scale subject -> establishing shot" elif place in ("mountains", "farm") and n_ent >= 2: shot, why = "wide", "landscape with several things -> establishing shot" elif info.get("animal") and hm >= 2.4 and n_ent <= 2: shot, why = "hero", "large animal -> heroic low angle" elif n_all == 1 and hm <= .45 and not info.get("animal"): shot, why = "small", "single small object -> close and slightly high" elif n_all == 1 and hm <= .15: shot, why = "macro", "tiny creature -> macro" elif info.get("animal") and hm <= 1.0 and n_all == 1: shot, why = "pet", "small animal -> camera down at its eye level" elif person and n_all == 1 and scene.get("framing") != "far": shot, why = "medium", "single person -> medium shot" else: shot, why = "medium", "default medium shot" if "eye" in words and shot in ("medium", "table", "small"): shot, why = "pet" if info.get("animal") else "medium", "prompt says eye level" trace.append("camera: shot = %s (%s)" % (shot, why)) return shot, words
def direct(text, scene, objs, place, tod, upm, R, seed, trace, base=None): if not objs: return None rng = np.random.RandomState(seed * 31 + 7) subs = [Subject(o, k, seed) for k, o in enumerate(objs)] shot, words = choose_shot(text, scene, subs, place, trace) el_r, fov_r, size_t, az_max = SHOTS[shot] main = [s for s in subs if not s.implicit] or subs prim = [s for s in main if s.ent == main[0].ent] counted = main # everything the prompt named must stay readable p0 = prim[0] tall = (p0.P[:, 1].max() - p0.P[:, 1].min()) > 1.4 * (p0.P[:, 0].max() - p0.P[:, 0].min()) person_close = (shot == "portrait" and p0.o.name == "person") or (shot in ("close", "macro") and len(main) == 1 and tall) if person_close: # rule: a portrait frames head and shoulders; a close-up of a tall thing (a sunflower, a giraffe) frames its # top, where the interest is; the rest may leave the frame at the bottom y0_, y1_ = p0.P[:, 1].min(), p0.P[:, 1].max() p0.crop = y1_ - (.42 if p0.o.name == "person" else .38) * (y1_ - y0_) size_t = .78 allP = np.concatenate([s.P for s in main]) lo, hi_ = allP.min(0), allP.max(0) T = (lo + hi_) / 2 if person_close: T = np.array([T[0], prim[0].crop + .5 * (prim[0].top - prim[0].crop), T[2]]) ext = float(max(hi_[1] - lo[1], (hi_[0] - lo[0]) * .8, 1e-3)) if person_close: ext = float(prim[0].top - prim[0].crop) * 1.3 ground = min(0.0, float(lo[1])) # base camera ordering (the layout's view): keep left/right relations O0 = np.array([0.0, 1.0, 0.0]) cx0 = [float(np.median((s.P[:, 0] - O0[0]) / np.maximum(s.P[:, 2] - O0[2], 1e-3))) for s in main] cy0 = [float(np.median(s.P[:, 1])) for s in main] pairs = [(i, j) for i in range(len(main)) for j in range(len(main)) if main[i].ent != main[j].ent and cx0[i] < cx0[j] - .04] vpairs = [(i, j) for i in range(len(main)) for j in range(len(main)) if main[i].ent != main[j].ent and cy0[i] > cy0[j] + .3 * ext and (main[i].flying or main[i].o.base[1] > main[j].top * .9)] G = 40 living_prim = prim[0].living tabletop = place == "table" outdoor = place not in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office", "space", "underwater") multi = len(main) > 1 # rule: tall architecture keeps verticals straight (lens shift instead of tilt), except in a deliberate low angle arch = shot == "wide" and not any(s.living for s in prim)
def make(p): az, el, dist, fov, pan, tilt, sh = p O = T + dist * np.array([math.sin(az) * math.cos(el), math.sin(el), -math.cos(az) * math.cos(el)]) d = T - O yaw0 = math.atan2(d[0], d[2]) pitch0 = math.asin(max(-1, min(1, d[1] / np.linalg.norm(d)))) return Camera(O, yaw0 + pan, pitch0 + tilt, fov, sh)
def energy(p, detail=False): cam = make(p) E = {} if cam.O[1] < max(.05 * upm, ground + .02 * ext): return 1e9 if not detail else (1e9, {"under_ground": 1}) us, vs, zs = [], [], [] for s in subs: u, v, z = cam.project(s.P) us.append(u); vs.append(v); zs.append(z) # --- cut-off subjects (hard) + tangents with the frame edges --- cut = 0.0 tang = 0.0 for k, s in enumerate(subs): u, v, z = us[k], vs[k], zs[k] m = np.ones(len(u), bool) if getattr(s, "crop", None) is not None: m = s.P[:, 1] >= s.crop if not m.any(): continue out = ((u < .015) | (u > .985) | (v < .015) | (v > .985) | (z < .02 * ext))[m].mean() w = 2.0 if s.implicit else 80.0 cut += w * out + (w * 3 if out > .2 else 0) + (5.0 if out > .001 and not s.implicit else 0) if s.implicit: continue bb = (u[m].min(), u[m].max(), v[m].min(), v[m].max()) for e_ in (bb[0], 1 - bb[1], bb[2], (1 - bb[3]) if getattr(s, "crop", None) is None else 1): if -.01 < e_ < .07: # rule: a subject almost touching the frame edge is a tangent; give it breathing room tang += ((.07 - max(e_, 0)) / .07) ** 2 E["cut"] = cut E["tangent"] = 1.0 * tang # --- occlusion via a coarse z-buffer: counted things stay visible --- allu = np.concatenate(us); allv = np.concatenate(vs); allz = np.concatenate(zs) own = np.concatenate([np.full(len(u), k) for k, u in enumerate(us)]) ins = (allu >= 0) & (allu < 1) & (allv >= 0) & (allv < 1) & (allz > 0) cell = np.where(ins, (np.clip(allv, 0, .999) * G).astype(int) * G + (np.clip(allu, 0, .999) * G).astype(int), G * G) zmin = np.full(G * G + 1, np.inf) np.minimum.at(zmin, cell, np.where(ins, allz, np.inf)) # owner of the frontmost point per cell front = np.full(G * G + 1, -1) isf = ins & (allz <= zmin[cell]) front[cell[isf]] = own[isf] occl = ins & (front[cell] != own) & (front[cell] >= 0) & (zmin[cell] < allz * .995) occ_e, overlap_bonus = 0.0, 0.0 for k, s in enumerate(subs): m = own == k if not m.any() or s.implicit: continue f = occl[m].mean() if f > .25: occ_e += 25 * (f - .25) + 3 elif .03 < f <= .18: # rule: a little overlap between different things reveals depth (only if the occluder is another entity) fo = front[cell[m & occl]] if len(fo) and all(subs[j].ent != s.ent for j in set(fo.tolist())): overlap_bonus += .25 E["occlusion"] = occ_e E["overlap"] = -overlap_bonus # --- order constraints: left/right and above/below stay as the prompt said --- mu = [float(np.median(us[subs.index(s)])) for s in main] mv = [float(np.median(vs[subs.index(s)])) for s in main] E["order"] = sum(30 + 200 * (mu[i] - mu[j]) for i, j in pairs if mu[i] > mu[j] - .03) + \ sum(30 + 200 * (mv[i] - mv[j]) for i, j in vpairs if mv[i] > mv[j] - .03) # --- subject size --- mu_ = np.concatenate([us[subs.index(s)] for s in main]) mv_ = np.concatenate([vs[subs.index(s)] for s in main]) if person_close: pk = subs.index(prim[0]) mm = prim[0].P[:, 1] >= prim[0].crop hfrac = vs[pk][mm].max() - vs[pk][mm].min() wfrac = us[pk][mm].max() - us[pk][mm].min() else: hfrac = mv_.max() - mv_.min() wfrac = mu_.max() - mu_.min() size = max(hfrac, wfrac * .8) E["size"] = 9 * math.log(max(size, 1e-3) / size_t) ** 2 + (20 * (wfrac - .92) if wfrac > .92 else 0) # --- centre of interest on a third / golden point --- pk = subs.index(prim[0]) iu, iv, _ = cam.project(np.mean([s.interest for s in prim], 0)[None, :]) iu, iv = float(iu[0]), float(iv[0]) gu = float(np.mean(mu_)) if multi and len({s.ent for s in main}) > 1: # rule: a group of different things is balanced as a whole: its visual centre near the middle, but the # main subject still on a vertical third/golden line when that works xs = min([abs(iu - a) for a in THIRDS + GOLDEN] + [abs(iu - .5) + .06]) else: xs = min([abs(iu - a) for a in THIRDS + GOLDEN] + [abs(iu - .5) + (.05 if not living_prim else .09)]) if living_prim and (shot in ("portrait", "close", "hero") or (prim[0].o.name == "person" and not multi)): ys = min(abs(iv - a) for a in (1 / 3, .382, .30)) # eyes on the upper third line elif tabletop or shot in ("small", "close", "macro", "aerial", "iso"): ys = min(abs(np.mean(mv_) - a) for a in (.5, .55, .6)) else: ys = min(abs(np.mean(mv_) - a) for a in (.5, .56, .618)) if living_prim: ys = .7 * ys + .3 * min(abs(iv - a) for a in (1 / 3, .382, .45)) E["thirds"] = 8 * xs ** 2 + 12 * ys ** 2 # rule: no wasteland of empty foreground under grounded subjects (the group's feet sit in the lower part) vbot = float(np.percentile(mv_, 98)) if shot not in ("aerial", "iso", "hero") and not person_close and not all(s.flying for s in main): E["foreground"] = 30 * max(0.0, .72 - vbot) ** 2 # --- headroom (space above the top of the subjects) --- top = mv_.min() if not person_close else vs[pk][prim[0].P[:, 1] >= prim[0].crop].min() hr_t = {"portrait": .08, "close": .1, "macro": .1, "hero": .07, "wide": .2, "aerial": .12}.get(shot, .13) # too little headroom is cramped; too much only matters when the subject should fill the frame (a short wide # group under a big sky is fine) loose = shot in ("portrait", "close", "macro", "hero") or (not multi and hfrac > .35) E["headroom"] = 10 * (top - hr_t) ** 2 if top < hr_t else (3 * (top - hr_t) ** 2 if loose else 0.0) # --- lead room: more space in front of a creature than behind it --- E["lead"] = 0.0 if prim[0].side_view and len(prim) == 1: a, _, _ = cam.project(prim[0].o.center[None, :]) b, _, _ = cam.project((prim[0].o.center + prim[0].fw * prim[0].o.scale * .5)[None, :]) du = float(b[0] - a[0]) if abs(du) > .02: ahead = (1 - iu) if du > 0 else iu E["lead"] = 15 * max(0, .52 - ahead) ** 2 # --- horizon: off the middle, ideally on a third, and never through a head --- E["horizon"] = 0.0 hv = cam.horizon_v() if outdoor and -0.05 < hv < 1.05 and shot not in ("aerial", "iso"): E["horizon"] = (.8 if shot in ("pet", "hero", "portrait", "close", "medium") else 2.0) * min(abs(hv - 1 / 3), abs(hv - 2 / 3)) ** 2 + (1.2 * (.07 - abs(hv - .5)) if abs(hv - .5) < .07 else 0) if living_prim and abs(hv - iv) < .04: E["horizon"] += .5 # rule: the horizon must not cut through the subject's head if tod == "sunset" and hv < .5: E["horizon"] += .4 * (.5 - hv) # rule: a sunset sky deserves room: low horizon # --- balance of visual weight around the centre (for groups) --- if multi: w = np.array([len(u) for u in us], float) cxw = sum(float(np.mean(np.clip(us[k], 0, 1))) * w[k] for k in range(len(us))) / max(w.sum(), 1) E["balance"] = 3 * (cxw - .5) ** 2 # rule: things should not kiss each other in the picture (tangents between subjects) kiss = 0.0 bbs = [(np.percentile(us[subs.index(s)], 2), np.percentile(us[subs.index(s)], 98)) for s in main] for i in range(len(bbs)): for j in range(i + 1, len(bbs)): gap = max(bbs[j][0] - bbs[i][1], bbs[i][0] - bbs[j][1]) if -.006 < gap < .012: kiss += .15 E["kiss"] = kiss # --- priors: stay near the chosen shot, keep verticals straight in architecture --- az, el, dist, fov, pan, tilt, sh = p E["prior"] = .3 * (az / max(math.radians(az_max), 1e-3)) ** 2 + 2 * abs(sh) ** 2 # rule (variation): when the rules don't prefer a side, each seed has its own preferred third E["side"] = .015 if (iu - .5) * pref < 0 else 0.0 if arch: E["keystone"] = 40 * cam.pitch ** 2 tot = sum(E.values()) return (tot, E) if detail else tot
lo_el, hi_el = map(math.radians, el_r) lo_f, hi_f = map(math.radians, fov_r) azm = math.radians(az_max)
def dist_for(fov, k=1.0): # distance at which the subject extent fills size_t of the frame height return ext / (2 * math.tan(fov / 2) * size_t) * k + .5 * ext
best = [] side = 1 if rng.rand() < .5 else -1 pref = 1 if rng.rand() < .5 else -1 N = 500 for i in range(N): fov = rng.uniform(lo_f, hi_f) p = [side * abs(rng.normal(0, azm * .6)) * (1 if i % 2 else -1) if azm > 0 else (math.radians(45) * side if shot == "iso" else 0), rng.uniform(lo_el, hi_el), dist_for(fov, math.exp(rng.normal(0, .25))), fov, rng.normal(0, fov * .12), rng.normal(0, fov * .1), rng.normal(0, .06) if arch else 0.0] if shot == "iso": p[0] = math.radians(rng.choice([-30, 30])) best.append((energy(p), p)) best.sort(key=lambda t: t[0]) top = best[:6] steps = np.array([.06, .04, .08, .04, .03, .03, .03]) res = [] for e0, p0 in top: p, e = list(p0), e0 sc = 1.0 for it_ in range(70): q = list(p) j = rng.randint(7) if shot == "iso" and j == 0: continue if j == 2: q[2] *= math.exp(rng.normal(0, steps[2] * sc * 2)) else: q[j] += rng.normal(0, steps[j] * sc) q[1] = min(max(q[1], lo_el - math.radians(4)), hi_el + math.radians(4)) q[3] = min(max(q[3], lo_f * .9), hi_f * 1.1) q[0] = min(max(q[0], -azm - .05), azm + .05) if shot != "iso" else q[0] if not arch: q[6] = 0.0 eq = energy(q) if eq < e: p, e = q, eq elif it_ % 20 == 19: sc *= .6 res.append((e, p)) res.sort(key=lambda t: t[0]) e, p = res[0] tot, E = energy(p, detail=True) cam = make(p) cam.shot = shot cam.energy = E cam.subs = subs cam.main_ent = prim[0] trace.append("camera: az=%.0f el=%.0f dist=%.2f fov=%.0f pan=%.1f tilt=%.1f shift=%.2f E=%.2f (%s)" % ( math.degrees(p[0]), math.degrees(p[1]), p[2], math.degrees(p[3]), math.degrees(p[4]), math.degrees(p[5]), p[6], tot, ", ".join("%s %.2f" % (k, v) for k, v in E.items() if abs(v) > .005))) # where the subjects sit on screen (for light side, framing elements, vignette) u, v, _ = cam.project(np.concatenate([s.P for s in main])) cam.subj_u, cam.subj_v = float(np.mean(u)), float(np.mean(v)) iu, _, _ = cam.project(prim[0].interest[None, :]) cam.facing = 0 if prim[0].side_view: a, _, _ = cam.project(prim[0].o.center[None, :]) b, _, _ = cam.project((prim[0].o.center + prim[0].fw * prim[0].o.scale * .5)[None, :]) cam.facing = int(np.sign(b[0] - a[0])) if abs(b[0] - a[0]) > .02 else 0 cam.pts_uv = (u, v) cam.dist = p[2] # haze is measured from where the layout's camera stood: pulling the camera back (telephoto, establishing shot) # must not fog the subject itself; only what lies beyond it gets atmospheric perspective d_layout = float(np.median([np.linalg.norm(s.o.center - np.array([0, 1.0, 0])) for s in main])) d_now = float(np.median([np.linalg.norm(s.o.center - cam.O) for s in main])) cam.fog_offset = max(0.0, d_now - d_layout) cam.T = T return cam
def key_light(cam, tod, studio, trace): """rule: light for modelling. Day / indoors: a three-quarter key from the open side of the frame (in front of the subject, ~30-45 degrees to the side, ~35 degrees up; a profile animal is lit on the flank it shows), so the form reads and shadows fall across the ground beside and behind. Sunset: the sun low behind-and-to-the-side for a glowing rim. Night: a back rim (moon).""" # a profile subject turned toward the camera shows the flank on the side it faces away from: light that flank # (key on the opposite side to the facing); otherwise the key comes from the open side of the frame side = -cam.facing if cam.facing else (1 if cam.subj_u < .5 else -1) if tod == "sunset" and not studio: L = cam.fwd * .55 + cam.right * side * .7 + np.array([0, .22, 0]) rim, kind = 1.1, "sunset back/side light" elif tod == "night" and not studio: L = cam.fwd * .5 + cam.right * side * .6 + np.array([0, .5, 0]) rim, kind = .8, "night back rim" else: L = -cam.fwd * .8 + cam.right * side * .5 + np.array([0, .62 if not studio else .75, 0]) rim, kind = .5, "three-quarter key from the %s" % ("right" if side > 0 else "left") L = L / np.linalg.norm(L) if L[1] < .12: L[1] = .12 L = L / np.linalg.norm(L) trace.append("camera: light = %s" % kind) return L, rim
def finish(img, idm, tm, cam, place, tod, hor_rgb, seed, trace): """depth cues painted after rendering: out-of-focus foreground framing + lens vignette. img: float HxWx3 in 0..1""" n = img.shape[0] rng = np.random.RandomState(seed * 13 + 5) ys, xs = np.mgrid[0:n, 0:n].astype(float) / n out = img.copy() occupied = idm >= 0 u_, v_ = cam.pts_uv sidex = 1.0 if cam.subj_u < .5 else 0.0 # far side from the subjects corner_free = not (((np.abs(u_ - sidex) < .3) & (v_ > .55)).any()) if place in ("field", "park", "farm", "savanna", "forest", "mountains", "garden") and cam.shot in ("pet", "medium", "hero", "wide") \ and tod != "night" and corner_free and rng.rand() < .6: # rule: foreground framing: a few soft, out-of-focus grass blades rise from the bottom edge at the side away from # the subjects (never over a subject), darker and cooler than the lit ground: they say "we are looking past # something near" and push the subject back mask = np.zeros((n, n)) nb = rng.randint(7, 12) for b in range(nb): x0 = sidex + (rng.uniform(.0, .3) * (-1 if sidex > .5 else 1)) hgt = rng.uniform(.12, .32) * (1 - abs(x0 - sidex) * 1.6) lean = rng.uniform(-.25, .25) + (.2 if sidex < .5 else -.2) * 0 wid = rng.uniform(.008, .016) t = np.clip((1 - ys) / max(hgt, 1e-3), 0, 1) # 0 at the bottom edge .. 1 at the tip cxl = x0 + lean * t ** 2 * hgt half = wid * (1 - t) ** .7 blade = (np.abs(xs - cxl) < half) & ((1 - ys) < hgt) mask = np.maximum(mask, blade.astype(float)) if mask.any(): from scipy.ndimage import gaussian_filter soft = gaussian_filter(mask, n / 512 * 3.2) # keep subjects clear: drop the framing if it would cover them if (soft * occupied).sum() > .02 * soft.sum() + 1: trace.append("camera: foreground framing skipped (would cover a subject)") else: gcol = np.array([.16, .30, .10]) if place not in ("savanna",) else np.array([.42, .34, .14]) if tod == "sunset": gcol = gcol * .7 + np.array([.18, .08, .02]) tex = gcol[None, None, :] * (0.8 + .4 * gaussian_filter(rng.rand(n, n), 2)[..., None]) a = np.clip(soft * 1.0, 0, .8)[..., None] out = out * (1 - a) + tex * a trace.append("camera: foreground framing (out-of-focus grass, %s edge)" % ("right" if sidex > .5 else "left")) # rule: a gentle lens vignette pulls the eye to the centre of interest cu, cv = .5 * .6 + cam.subj_u * .4, .5 * .6 + cam.subj_v * .4 r2 = (xs - cu) ** 2 + (ys - cv) ** 2 vig = 1 - .22 * np.clip((r2 - .12) / .4, 0, 1) ** 1.3 out = out * vig[..., None] return np.clip(out, 0, 1)11 unmodified lines121314151617138 unmodified lines15615715815916016183 unmodified lines2452462472482492502514 unmodified lines25625725825926026126226311 unmodified lines27527627727827928092 unmodified lines37337437537637737837938038138238338431 unmodified lines4164174184194204214224234244256 unmodified lines43243343443543643737 unmodified lines4754764774784794804811 unmodified line48348448548648748848920 unmodified lines51051151251351451551651751811 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom ..models_animals import rcone, chain, mirror_z, eyesEYE = (22, 18, 18)138 unmodified linessh = np.array([(lo[0] + hi[0]) / 2, y0, (lo[2] + hi[2]) / 2])for pt in parts:pt.fn = (lambda f: (lambda p: f(p * h + sh) / h))(pt.fn)return parts, (hi[0] - lo[0]) / h83 unmodified lines)def _bird_raw(P, col, flying):col = tuple(col or (120, 110, 100))belly = tuple(P.color2) if P.color2 else lighter(col, .45)headc = tuple(P.head_col) if P.head_col else col4 unmodified linesrx, ry, rz = P.bodyfly = flying and P.can_flytilt = 0.08 if fly else P.tiltleg = 0.0 if fly else P.legfeet = "none" if fly else P.feet# body centre: the legs leave the belly at ~ -0.75 ry (in the tilted frame)by = leg + ry * .82 * (1 + .25 * np.sin(abs(tilt)))B = np.array([0.0, by, 0.0])11 unmodified linesH = loc(rx * .25, ry * .95) + np.array([0, hr * .55 + L * .5, 0])else:H = N0 + np.array([hr * .45 + L * .25, L + hr * .35, 0])if P.neck_s > 0 and L > .15:# rule: an S-neck goes back over the body first, then forward to the headM1 = N0 + np.array([-L * .18 * P.neck_s, L * .45, 0])92 unmodified lines# beakeye_n = np.array([.42, .2, .88])bdir = np.array([np.cos(-.05), np.sin(-.05), 0])if P.face == "front":bdir = np.array([.6, -.35, -.72])bdir /= np.linalg.norm(bdir)b0 = H + bdir * hr * .72bl, bw = P.beak, P.beak_wtipdir = np.array([np.cos(-P.droop - .05), np.sin(-P.droop - .05), 0]) if P.face != "front" else bdirif P.beak_shape == "flat":def beak(p):c = b0 + bdir * bl * .45 + np.array([0, -hr * .12, 0])31 unmodified lineslx = B[0] + rx * .1knee = leg > .3def legs(p):q = mirror_z(p)top = np.array([lx, by - ry * .55, rz * .32])foot = np.array([lx + (.0 if not knee else .02), .02, rz * .32])if knee:mid = np.array([lx - leg * .12, leg * .55, rz * .32])d = chain(q, [top, mid, foot], [P.leg_r * 1.6, P.leg_r, P.leg_r])6 unmodified linesif feet == "webbed":d = np.minimum(d, flat_fin(q, [(0, 0), (tl_ * 1.1, -tl_ * .5), (tl_ * 1.15, tl_ * .5)], .006,c=foot - np.array([0, .012, 0]), plane="xz"))return dparts.append(Part(legs, legc, spec=.35, rough=.4))# crest / comb37 unmodified linesside /= np.linalg.norm(side)for s in (-1, 1):ec = H + fdir * hr * .72 + side * s * hr * .38 + np.array([0, hr * .12, 0])parts += eyes(ec, hr * .26 * P.eye, fdir, both=False, pupil=.6, iris=EYE, sclera=(250, 200, 60))else:if P.mask_col:mc = H + np.array([hr * .2, hr * .15, hr * .55])1 unmodified lineS.ellipsoid(mirror_z(p), mc, V(hr * .75, hr * .22, hr * .7))),tuple(P.mask_col), spec=.3, rough=.5))ec = H + eye_n / np.linalg.norm(eye_n) * hr * .72parts += eyes(tuple(ec), hr * .3 * P.eye, eye_n)return parts20 unmodified lines@family("bird", aspect=lambda Pm: _bird_aspect(Pm), **BIRD_DEFAULTS)def f_bird(P, col, inst=None, _aspect_only=False):fly = is_flying(P, inst)parts = _bird_raw(P, col, fly)parts, asp = fit(parts, key=("bird", hashable(dict(P)), fly))return asp if _aspect_only else parts_bird_aspect = make_aspect("bird")11 unmodified lines12131415161718138 unmodified lines15715815916016116216383 unmodified lines2472482492502512522534 unmodified lines25825926026126226326426526626726826911 unmodified lines28128228328428528628728828929029129229329429529692 unmodified lines38939039139239339439539639739839940040140240340440540640740840941041131 unmodified lines4434444454464474484494504514524534544556 unmodified lines46246346446546646746846947047147247337 unmodified lines5115125135145155165175185195201 unmodified line52252352452552652752852953053120 unmodified lines55255355455555655755855956056156256356456556656756856957057157257357457557657757811 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom ..models_animals import rcone, chain, mirror_z, eyesfrom ..pose import pose_of, eyelids, ModelEYE = (22, 18, 18)138 unmodified linessh = np.array([(lo[0] + hi[0]) / 2, y0, (lo[2] + hi[2]) / 2])for pt in parts:pt.fn = (lambda f: (lambda p: f(p * h + sh) / h))(pt.fn)fit.last = (h, sh) # raw -> model frame: (raw - sh) / h (families map their anchors with it)return parts, (hi[0] - lo[0]) / h83 unmodified lines)def _bird_raw(P, col, flying, pose=None, anchors=None):col = tuple(col or (120, 110, 100))belly = tuple(P.color2) if P.color2 else lighter(col, .45)headc = tuple(P.head_col) if P.head_col else col4 unmodified linesrx, ry, rz = P.bodyfly = flying and P.can_flytilt = 0.08 if fly else P.tiltif pose == "graze" and not fly:tilt = min(tilt, .1) - .3 # rule: a bird pecking / drinking tips its body forwardif pose == "swim":tilt = min(tilt, .12)leg = 0.0 if (fly or pose == "swim") else P.legfeet = "none" if (fly or pose == "swim") else P.feet# body centre: the legs leave the belly at ~ -0.75 ry (in the tilted frame)by = leg + ry * .82 * (1 + .25 * np.sin(abs(tilt)))B = np.array([0.0, by, 0.0])11 unmodified linesH = loc(rx * .25, ry * .95) + np.array([0, hr * .55 + L * .5, 0])else:H = N0 + np.array([hr * .45 + L * .25, L + hr * .35, 0])if pose == "sleep" and not fly:# rule: a sleeping bird pulls its head down into its shoulders (no neck shows)if tilt > .7:H = H - np.array([0, L * .6 + hr * .1, 0]) # upright birds (owl, penguin) just sink the head a littleelse:H = N0 + (H - N0) * .25 + np.array([hr * .1, -hr * .1, 0])L = 0.0elif pose == "graze" and not fly:# rule: pecking / drinking: the head goes down in front of the body until the beak touches the groundH = np.array([B[0] + rx * 1.0 + hr * .4 + L * .3, hr * .85 + P.beak * .55, 0.0])if P.neck_s > 0 and L > .15:# rule: an S-neck goes back over the body first, then forward to the headM1 = N0 + np.array([-L * .18 * P.neck_s, L * .45, 0])92 unmodified lines# beakeye_n = np.array([.42, .2, .88])bdir = np.array([np.cos(-.05), np.sin(-.05), 0])if pose == "graze" and not fly:bdir = np.array([.45, -1.0, 0]) / np.linalg.norm([.45, -1.0])elif pose == "sleep" and not fly and tilt <= .7:bdir = np.array([.85, -.5, 0]) / np.linalg.norm([.85, -.5])if P.face == "front":bdir = np.array([.6, -.35, -.72])bdir /= np.linalg.norm(bdir)b0 = H + bdir * hr * .72bl, bw = P.beak, P.beak_wtipdir = np.array([np.cos(-P.droop - .05), np.sin(-P.droop - .05), 0]) if P.face != "front" else bdirif pose in ("graze", "sleep") and not fly:tipdir = bdirif anchors is not None:anchors["beak"] = b0 + bdir * P.beak * .6anchors["mouth"] = anchors["beak"]anchors["saddle"] = loc(0, ry * .95)anchors["seat"] = np.array([B[0], .0 if leg > 0 else by - ry * .9, 0])if P.beak_shape == "flat":def beak(p):c = b0 + bdir * bl * .45 + np.array([0, -hr * .12, 0])31 unmodified lineslx = B[0] + rx * .1knee = leg > .3one = pose == "one_leg"zl_ = 0.0 if one else rz * .32def legs(p):q = p if one else mirror_z(p)top = np.array([lx, by - ry * .55, zl_])foot = np.array([lx + (.0 if not knee else .02), .02, zl_])if knee:mid = np.array([lx - leg * .12, leg * .55, rz * .32])d = chain(q, [top, mid, foot], [P.leg_r * 1.6, P.leg_r, P.leg_r])6 unmodified linesif feet == "webbed":d = np.minimum(d, flat_fin(q, [(0, 0), (tl_ * 1.1, -tl_ * .5), (tl_ * 1.15, tl_ * .5)], .006,c=foot - np.array([0, .012, 0]), plane="xz"))if one:# rule: standing on one leg = the other leg folded up under the belly (knee back, foot tucked)t2 = np.array([lx, by - ry * .55, -rz * .3])k2 = t2 + np.array([-leg * .3, -leg * .22, -rz * .1])f2 = k2 + np.array([leg * .28, leg * .06, 0])d = np.minimum(d, chain(p, [t2, k2, f2], [P.leg_r * 1.5, P.leg_r, P.leg_r * .9]))return dparts.append(Part(legs, legc, spec=.35, rough=.4))# crest / comb37 unmodified linesside /= np.linalg.norm(side)for s in (-1, 1):ec = H + fdir * hr * .72 + side * s * hr * .38 + np.array([0, hr * .12, 0])if pose == "sleep" and not fly:parts += eyelids(ec, hr * .26 * P.eye, fdir, lighter(headc, .45), both=False)else:parts += eyes(ec, hr * .26 * P.eye, fdir, both=False, pupil=.6, iris=EYE, sclera=(250, 200, 60))else:if P.mask_col:mc = H + np.array([hr * .2, hr * .15, hr * .55])1 unmodified lineS.ellipsoid(mirror_z(p), mc, V(hr * .75, hr * .22, hr * .7))),tuple(P.mask_col), spec=.3, rough=.5))ec = H + eye_n / np.linalg.norm(eye_n) * hr * .72if pose == "sleep" and not fly:parts += eyelids(ec, hr * .3 * P.eye, eye_n, headc, mirror=mirror_z)else:parts += eyes(tuple(ec), hr * .3 * P.eye, eye_n)return parts20 unmodified lines@family("bird", aspect=lambda Pm: _bird_aspect(Pm), **BIRD_DEFAULTS)def f_bird(P, col, inst=None, _aspect_only=False):fly = is_flying(P, inst)pose = _bird_pose(inst)if pose == "fly" and P.can_fly:fly, pose = True, Noneanchors = {}parts = _bird_raw(P, col, fly, pose, anchors)floor = Noneif pose == "swim":# rule: a swimming bird floats: the water line is a little below the middle of its bodyrx, ry, rz = P.bodyfloor = ry * .82 * (1 + .25 * np.sin(abs(min(P.tilt, .12)))) - ry * .3parts, asp = fit(parts, key=("bird", hashable(dict(P)), fly, pose), floor=floor)if _aspect_only:return asph, sh = fit.lastreturn Model.of(parts, aspect=asp, height=1.0, anchors={k: tuple((np.asarray(v) - sh) / h) for k, v in anchors.items()})def _bird_pose(inst):p = pose_of(inst)return {"sit": "perch", "lie": "sleep", "graze": "graze", "eat": "graze", "crawl": None, "run": None, "walk": None,"rear": None, "upright": None, "howl": None, "hang": None, "ride": "perch", "balance": None}.get(p, p)_bird_aspect = make_aspect("bird")
4 unmodified lines5678910268 unmodified lines279280281282283284285173 unmodified lines4594604614624634644654664 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom .animals_other import (rcone, chain, mirror_z, eyes, lighter, rotz, rotx, flat_fin, fit, hashable, make_aspect, EYE, like)# =====================================================================================================268 unmodified lines# rule: a ray seen edge-on is a line; bank it toward the viewer (-z) so its kite shape readsfor pt in parts:pt.fn = (lambda f: (lambda p: f(rotx(p, (0, 0, 0), .9))))(pt.fn)parts, asp = fit(parts, key=("fish", hashable(dict(P))))return asp if _aspect_only else parts173 unmodified lines@family("pinniped", aspect=lambda Pm: _pin_aspect(Pm), **PIN_DEFAULTS)def f_pinniped(P, col, inst=None, _aspect_only=False):parts, asp = fit(_pin_raw(P, col), key=("pinniped", hashable(dict(P))))return asp if _aspect_only else parts_pin_aspect = make_aspect("pinniped")4 unmodified lines56789101112268 unmodified lines281282283284285286287288173 unmodified lines4624634644654664674684694704714724734744754764774784794804814824 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom .animals_other import (rcone, chain, mirror_z, eyes, lighter, rotz, rotx, flat_fin, fit, hashable, make_aspect, EYE, like)from . import P as _PBfrom ..pose import pose_of, pitch_parts, Model# =====================================================================================================268 unmodified lines# rule: a ray seen edge-on is a line; bank it toward the viewer (-z) so its kite shape readsfor pt in parts:pt.fn = (lambda f: (lambda p: f(rotx(p, (0, 0, 0), .9))))(pt.fn)deg = {"jump": 35, "graze": -25, "rear": 50, "upright": 50}.get(pose_of(inst), 0)parts, asp = fit(pitch_parts(parts, deg), key=("fish", hashable(dict(P)), deg))return asp if _aspect_only else parts173 unmodified lines@family("pinniped", aspect=lambda Pm: _pin_aspect(Pm), **PIN_DEFAULTS)def f_pinniped(P, col, inst=None, _aspect_only=False):pz = pose_of(inst)# rule: a balancing / begging / upright seal sits up tall; a lying / sleeping / swimming one lies flatr = {"balance": 1.0, "upright": 1.0, "sit": .9, "howl": 1.0, "lie": .1, "sleep": 0.0, "swim": .2, "crawl": .15}.get(pz)if r is not None:P = _PB(dict(P, raise_=r))raw = _pin_raw(P, col)hr = P.headH = np.array([.42 + .02 * (1 - P.raise_), .5 + .34 * P.raise_, 0])sn = H + np.array([hr * 1.3 * P.snout, -hr * .15, 0])parts, asp = fit(raw, key=("pinniped", hashable(dict(P))))if _aspect_only:return asph, sh = fit.lastan = {"nose": sn + np.array([-.01, .03, 0]), "mouth": sn - np.array([.02, .03, 0]), "saddle": np.array([-.05, .3 * P.fat, 0])}return Model.of(parts, aspect=asp, anchors={k: tuple((v - sh) / h) for k, v in an.items()})_pin_aspect = make_aspect("pinniped")
9 unmodified lines10111213141590 unmodified lines106107108109110111112113135 unmodified lines24925025125225325425569 unmodified lines32532632732832933067 unmodified lines3983994004014024034049 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom .animals_other import (rcone, chain, mirror_z, eyes, lighter, rotz, rotx, flat_fin, fit, hashable, make_aspect, like, mix)def _tongue(tip, d=(1, 0, 0), L=.08, r=.008):90 unmodified lines@family("snake", aspect=lambda Pm: _snake_aspect(Pm), **SNAKE_DEFAULTS)def f_snake(P, col, inst=None, _aspect_only=False):parts, asp = fit(_snake_raw(P, col), key=("snake", hashable(dict(P))))return asp if _aspect_only else parts_snake_aspect = make_aspect("snake")135 unmodified lines@family("lizard", aspect=lambda Pm: _lizard_aspect(Pm), **LIZ_DEFAULTS)def f_lizard(P, col, inst=None, _aspect_only=False):parts, asp = fit(_lizard_raw(P, col), key=("lizard", hashable(dict(P))))return asp if _aspect_only else parts69 unmodified lines@family("turtle", aspect=lambda Pm: _turtle_aspect(Pm), **TURTLE_DEFAULTS)def f_turtle(P, col, inst=None, _aspect_only=False):parts, asp = fit(_turtle_raw(P, col), key=("turtle", hashable(dict(P))))return asp if _aspect_only else parts67 unmodified lines@family("frog", aspect=lambda Pm: _frog_aspect(Pm), **FROG_DEFAULTS)def f_frog(P, col, inst=None, _aspect_only=False):parts, asp = fit(_frog_raw(P, col), key=("frog", hashable(dict(P))))return asp if _aspect_only else parts9 unmodified lines101112131415161790 unmodified lines108109110111112113114115116117118119120121122123124125126127128129135 unmodified lines26526626726826927027127227327469 unmodified lines34434534634734834935035135235367 unmodified lines4214224234244254264274289 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom .animals_other import (rcone, chain, mirror_z, eyes, lighter, rotz, rotx, flat_fin, fit, hashable, make_aspect, like, mix)from . import P as _PBfrom ..pose import pose_of, pitch_partsdef _tongue(tip, d=(1, 0, 0), L=.08, r=.008):90 unmodified lines@family("snake", aspect=lambda Pm: _snake_aspect(Pm), **SNAKE_DEFAULTS)def f_snake(P, col, inst=None, _aspect_only=False):pz = pose_of(inst)# rule: a snake's poses are its body plans: crawling / swimming = slithering S, coiled / sleeping = coil,# rearing up / striking / "standing" = raised front (cobra)sp = {"crawl": "slither", "swim": "slither", "walk": "slither", "run": "slither", "coil": "coil", "sleep": "coil","lie": "coil", "upright": "raised", "rear": "raised", "howl": "raised", "balance": "raised", "jump": "raised"}.get(pz)if sp and sp != P.pose:P = _PB(dict(P, pose=sp))parts, asp = fit(_snake_raw(P, col), key=("snake", hashable(dict(P))))if _aspect_only:return aspfrom ..pose import Modelif not sp:return partsm = Model.of(parts, aspect=asp)m.fit_width = True # a slithering snake is much wider than a coiled one: fit the layout box by widthreturn m_snake_aspect = make_aspect("snake")135 unmodified lines@family("lizard", aspect=lambda Pm: _lizard_aspect(Pm), **LIZ_DEFAULTS)def f_lizard(P, col, inst=None, _aspect_only=False):pz = pose_of(inst)deg = {"jump": 22, "upright": 55, "rear": 40, "howl": 25, "graze": -12}.get(pz, 0)parts = pitch_parts(_lizard_raw(P, col), deg)parts, asp = fit(parts, key=("lizard", hashable(dict(P)), deg))return asp if _aspect_only else parts69 unmodified lines@family("turtle", aspect=lambda Pm: _turtle_aspect(Pm), **TURTLE_DEFAULTS)def f_turtle(P, col, inst=None, _aspect_only=False):pz = pose_of(inst)if pz == "swim" and not P.flippers:P = _PB(dict(P, flippers=1)) # rule: a swimming turtle paddles with flippersfloor = Noneparts, asp = fit(_turtle_raw(P, col), key=("turtle", hashable(dict(P))))return asp if _aspect_only else parts67 unmodified lines@family("frog", aspect=lambda Pm: _frog_aspect(Pm), **FROG_DEFAULTS)def f_frog(P, col, inst=None, _aspect_only=False):deg = {"jump": 32, "swim": -8}.get(pose_of(inst), 0)parts, asp = fit(pitch_parts(_frog_raw(P, col), deg), key=("frog", hashable(dict(P)), deg))return asp if _aspect_only else parts
16 unmodified lines17181920212266 unmodified lines89909192939411 unmodified lines10610710810911011157 unmodified lines1691701711721731741751761771781791801811821831841857 unmodified lines1931941951961971983 unmodified lines20220320420520620720820921021121221323 unmodified lines23723823924024124224338 unmodified lines28228328428528628728828929029129229334 unmodified lines32832933033133233395 unmodified lines4294304314324334344353 unmodified lines43944044144244344417 unmodified lines46246346446546646746846947016 unmodified lines48748848949049149253 unmodified lines54654754854955055155255355455555655755855956056182 unmodified lines6446456466476486496501 unmodified line65265365465565665716 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom ..models_animals import rcone, chain, mirror_z, eyes, xformEYE = (22, 18, 18)PINK = (232, 160, 160)66 unmodified linesreturn pts# ============================================================ quadrupedQDEF = dict(body_len=.32, girth=.17, width=.95, rump=.95, leg_len=.28, leg_r=.05, thigh=1.0, slope=0.0,11 unmodified linesdef _quad(P, col, inst):col = tuple(col) if col else (150, 112, 78)bb = _BB()L, g, w = P.body_len, P.girth, P.widthll, lr = P.leg_len, P.leg_r57 unmodified linesd = S.smin(d, S.sphere(p, H, h), nr * .6)return ddef body(p):d = S.smin(torso_w(p), legs(p), lr * 1.2)d = S.smin(d, neck_head(p), g * .35)for c, r in hump_c:d = S.smin(d, S.sphere(p, c, r), g * .4)if P.fluffy > 0:d = d * .8 + P.fluffy * .03 * (S.noise3(p * 16) - .5)return ddef snout(p):d = rcone(p, sb, st, r1, r2)if P.trunk > 0:t = P.trunktp = [st, st + np.array([.14 * t, -.32 * t, 0]), st + np.array([.24 * t, -.62 * t, 0]),7 unmodified linescoat_pat = tuple(P.pat) if P.pat else Noneparts = [Part(body, col, spec=P.spec, rough=P.rough, tex=P.tex, pat=coat_pat),Part(snout, _ccol(P.muzzle, col), k=h * .25, spec=P.spec, rough=P.rough, tex=P.tex)]# ---- belly / bib / sock / back stripe / mask paintsif P.belly:3 unmodified linesbc = nb + nd * P.neck_len * .4reg = lambda p: np.maximum(S.ellipsoid(p, V(bc[0] + g * .35, bc[1] - g * .35, 0), V(g * .55, g * .9 + P.neck_len * .4, g * .8)),by - g * .55 - p[:, 1])parts.append(Part(_shell(body, reg), _ccol(P.bib, col), spec=P.spec, rough=P.rough, tex=P.tex))if P.sock:parts.append(Part(_shell(legs, lambda p: p[:, 1] - ll * P.sock_h, .004), _ccol(P.sock, col), spec=P.spec, rough=P.rough, tex=P.tex))if P.back_stripe:reg = lambda p: np.maximum(np.abs(p[:, 2]) - g * .28, by + g * .3 - p[:, 1])parts.append(Part(_shell(body, reg), _ccol(P.back_stripe, col), spec=P.spec, rough=P.rough, tex=P.tex))if P.mask:# face mask / blaze over the front of the headreg = lambda p: S.ellipsoid(p, V(H[0] + h * .55, H[1] + h * .1, 0), V(h * .55, h * .5, h * .35))23 unmodified linesparts.append(Part(_shell(neck_head, lambda p: S.ellipsoid(mirror_z(p), V(*(ec - np.array([h * .04, h * .06, 0]))),V(er * 1.7, er * 2.0, er * 1.9))),_ccol(P.eye_patch, col), spec=P.spec, rough=P.rough, tex=P.tex))parts += eyes(tuple(ec), er, tuple(en), iris=EYE, white=bool(P.eye_white), pupil=.66)# ---- earseb = H + h * np.array([-.22, .7, .52])38 unmodified lines# ---- tailtcol = _ccol(P.tail_col, col)t0 = R + np.array([-gr * .82, gr * .45, 0])td = _dir(180 - P.tail_ang)tl, tr = P.tail, P.tail_rtail = tuft = Nonetpat = coat_pat if P.pat_tail else Noneif P.tail_kind in ("thin", "tufted", "bushy") and tl > 0:t_pts = _poly(t0, td, tl, P.tail_curl)if P.tail_kind == "bushy":t_rs = [tl * .1, tl * .2, tl * .2, tl * .1]tail = lambda p: chain(p, t_pts, t_rs) * .934 unmodified linesparts.append(Part(tuft, _ccol(P.tip_col or P.mane_col, col), k=.01, spec=P.spec, rough=P.rough, tex=P.tex))# ---- mane / beardmcol = _ccol(P.mane_col, col)if P.mane == "neck":top = np.array([-nd[1], nd[0], 0.0])95 unmodified linesbb.pts(k_pts, h * .07)# ---- hooves / toenailsif hoofed:parts.append(Part(lambda p: np.minimum(S.cylinder(mirror_z(p), V(fx + .012, .028, zl), lr * 1.08, .03, .01),S.cylinder(mirror_z(p), V(hx, .028, zl), lr * 1.0, .03, .01)),_ccol(P.hoof_col, col), spec=.5, rough=.3))3 unmodified lines(225, 218, 200), spec=.4, rough=.35))# ---- spikes (hedgehog / porcupine) and armour (armadillo)if P.spikes > 0:sc = V(R[0] * .4 + C[0] * .1, by + g * .2, 0)sr = V(L * 1.02, g * 1.08, g * w * 1.15)17 unmodified linesreturn np.maximum((e + band) * .7, by - g * .55 - p[:, 1])parts.append(Part(armor, _ccol(P.armor_col, col), spec=.45, rough=.35))# head shieldparts.append(Part(lambda p: np.maximum(S.sphere(p, H + V(0, h * .1, 0), h * 1.04), H[1] + h * .1 - p[:, 1]),_ccol(P.armor_col, col), spec=.45, rough=.35))return _finish(parts, bb)@family("quadruped", aspect=lambda P: _quad(P, None, None)[1], **QDEF)16 unmodified linesbb = _BB()g, h, T = P.girth, P.head, P.torsopose = P.poseif pose == "sit":hip = np.array([0.0, g * .9, 0])sh = hip + np.array([.03, T, 0])53 unmodified lineselse:elbow = sha + np.array([.05, -P.arm_len * .5, .0])hand = elbow + np.array([P.arm_len * .35, P.arm_len * .05, -.04]) if P.arm_len < .3 else sha + np.array([.03, -P.arm_len, .02])arm_pts = [sha, elbow, hand]bb.pts(arm_pts, P.arm_r)def limbs(p):q = mirror_z(p)d = chain(q, legs_pts, lr)if pose != "hop":d = S.smin(d, S.ellipsoid(q, V(*fp), V(P.foot * .9, P.leg_r * .9, P.leg_r * 1.3)), .03)d = np.minimum(d, chain(q, arm_pts, [P.arm_r * 1.2, P.arm_r, P.arm_r * .95]))d = np.minimum(d, S.sphere(q, V(*hand), P.arm_r * 1.25))return ddef body(p):82 unmodified linesfr = math.pi * 2 * 5 / max(P.tail, .05)parts.append(Part(_shell(tail, lambda p: (np.sin(S.length(p - t0) * fr) - .1) * .02, .004), _ccol(P.tail_rings, col),spec=P.spec, rough=P.rough, tex=P.tex))return _finish(parts, bb)@family("primate", aspect=lambda P: _prim(P, None, None)[1], **PDEF)1 unmodified linereturn _prim(P, col, inst)[0]# ============================================================ bat@family("bat", aspect=1.7, wing_col="dark", ear_size=1.0, face=None, belly=None)def f_bat(P, col, inst=None):16 unmodified lines171819202122232466 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127211 unmodified lines28428528628728828929029129257 unmodified lines3503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873887 unmodified lines3963973983994004014024034044054064074084093 unmodified lines41341441541641741841942042142242342442542623 unmodified lines45045145245345445545645745845938 unmodified lines49849950050150250350450550650750850951051151251351451551651751834 unmodified lines55355455555655755855995 unmodified lines6556566576586596606616626636643 unmodified lines66866967067167267367417 unmodified lines69269369469569669769869970070170270370470570670770870971071171271371471571616 unmodified lines73373473573673773873974074174274374474574674774874975053 unmodified lines80480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384482 unmodified lines9279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649651 unmodified line96796896997097197297397497597616 unmodified linesfrom ..models import Part, V, darkerfrom .. import sdf as Sfrom ..models_animals import rcone, chain, mirror_z, eyes, xformfrom ..pose import pose_of, action_of, Rigid, rot_axis, about, posed, ik2, finish_posed, eyelids, Modelfrom pydraw.registry import CONCEPTS as CONCEPTS_EYE = (22, 18, 18)PINK = (232, 160, 160)66 unmodified linesreturn pts# ============================================================ quadruped posesdef rotz_pt(p, c, ang):"""points rotated by -ang about the z axis through c (evaluate a shape there to see it rotated by +ang)"""q = p - np.asarray(c, float)cs, sn = math.cos(ang), math.sin(ang)out = q.copy()out[:, 0] = cs * q[:, 0] + sn * q[:, 1]out[:, 1] = -sn * q[:, 0] + cs * q[:, 1]return out + np.asarray(c, float)# rule: quadruped poses as joint targets, shared by every four-legged species. feet: per leg (fl, fr = front# near / far, hl, hr = hind) the foot target relative to the leg's posed root, in units of that leg's length# (dx forward, dy down; dy = 0 means "on the ground"), optional knee bend (+1 joint forward, -1 back).# lift: body raised (+) / lowered (-) in leg lengths; pitch: chest up (deg); neck / head: pitch deltas (deg, + up);# yaw: head turned toward the camera (deg); mouth: jaw opening (deg); tail: tail angle in the world (deg above level).QPOSES = {"walk": dict(feet=dict(fl=(.3, 0), fr=(-.2, 0), hl=(-.22, 0), hr=(.25, 0)), neck=-6),"carry": dict(feet=dict(fl=(.28, 0), fr=(-.18, 0), hl=(-.2, 0), hr=(.22, 0)), neck=-10, head=-6, mouth=16, yaw=12),"run": dict(lift=.32, pitch=-3, feet=dict(fl=(.78, -.6), fr=(.48, -.8), hl=(-.85, -.55), hr=(-.62, -.75)), neck=-14, tail=12, mouth=10),"jump": dict(lift=.6, pitch=14, feet=dict(fl=(.33, -.42, 1), fr=(.24, -.5, 1), hl=(-.88, -.45), hr=(-.78, -.55)), neck=-2, tail=18),"crawl": dict(lift=-.32, feet=dict(fl=(.35, 0), fr=(-.05, 0), hl=(-.18, 0), hr=(.15, 0)), neck=-14, head=4),"sit": dict(mode="sit", yaw=22, tail=-4),"howl": dict(mode="sit", neck=40, head=28, mouth=30, tail=-4),"balance": dict(mode="sit", neck=34, head=40, yaw=8, tail=-4),"lie": dict(mode="lie", yaw=26, tail=-6),"sleep": dict(mode="lie", sleep=1, yaw=18, head=-6, closed=1),"rear": dict(mode="rear", pitch=46, neck=-26, feet=dict(fl=(.3, -.42, 1), fr=(.38, -.34, 1), hl=(.12, 0), hr=(.04, 0)), tail=-30),"upright": dict(mode="rear", pitch=70, neck=-58, yaw=14, feet=dict(fl=(.3, -.62, -1), fr=(.38, -.55, -1), hl=(.1, 0), hr=(.0, 0)), tail=-40),"graze": dict(mode="graze", feet=dict(fl=(.16, 0), fr=(-.06, 0), hl=(-.05, 0), hr=(.08, 0))),"swim": dict(mode="swim", feet=dict(fl=(.55, -.6), fr=(.2, -.82), hl=(-.6, -.62), hr=(-.3, -.8)), neck=16, head=-10, tail=0),}_QALIAS = {"perch": "sit", "ride": "sit", "kneel": "lie", "dance": "upright", "coil": "sleep", "hang": None, "fly": None,"one_leg": None, "stand": None, "eat": "graze"}def _qpose_name(inst):p = pose_of(inst)p = _QALIAS.get(p, p)if p is not None and p not in QPOSES:p = Noneif getattr(inst, "holding", None) and p in (None, "walk"):p = "carry" # rule: an animal holding something carries it in its mouth, head a little downreturn pdef _quad_pose(pose, P, G):sp = QPOSES[pose]R, C, g, gr, by, foot_y, ll = G["R"], G["C"], G["g"], G["gr"], G["by"], G["foot_y"], G["ll"]nb, H, st = G["nb"], G["H"], G["st"]lr = G["lr"]# rest-frame legs: root, rest joint, rest foot, bone lengths, radii, default bendlegs0 = {}for side, z in (("l", -G["zl"]), ("r", G["zl"])):af = np.array([G["fx"], C[1] - g * .35, z])Lf = af[1] - foot_ylegs0["f" + side] = (af, Lf * .5, Lf * .5, [lr * 1.35, lr * 1.1, lr], 1)ah = np.array([G["hx"], R[1] - g * .1, z])hk = np.array([G["hx"] - lr * .9, ll * .42 + foot_y * .5, z])ft = np.array([G["hx"], foot_y, z])legs0["h" + side] = (ah, float(np.linalg.norm(ah - hk)), float(np.linalg.norm(hk - ft)),[g * .55 * P.thigh * P.rump, lr * .95, lr * .92], -1)feet = dict(fl=(0, 0), fr=(0, 0), hl=(0, 0), hr=(0, 0))feet.update(sp.get("feet", {}))pitch = sp.get("pitch", 0.0)mode = sp.get("mode")hip0 = np.array([G["hx"], R[1] - g * .1, 0.0])floor = Nonezmul = {}def body_T(th, dy=0.0, piv=hip0):return Rigid(t=(0, dy, 0)) @ about(piv, rot_axis("z", th))if mode == "sit":# rule: sitting = chest raised about the hips until the straight front legs reach the ground, rump on the groundbest = Nonefor th in range(8, 72, 2):T = body_T(th)T = Rigid(t=(0, gr * .92 - T.pt(R)[1], 0)) @ Taf = T.pt(legs0["fl"][0])err = abs(af[1] - foot_y - .96 * (legs0["fl"][1] + legs0["fl"][2]))if best is None or err < best[0]:best = (err, th, T)_, pitch, Tb = bestfeet.update(fl=(.06, 0), fr=(.02, 0), hl=(.5, 0, 1), hr=(.42, 0, 1))zmul = {"hl": 1.15, "hr": 1.15}elif mode in ("lie",):# rule: lying (sphinx) = torso down on the ground, front legs stretched forward, hind legs folded beside itTb = Rigid(t=(0, g * 1.0 - by + .004, 0))feet.update(fl=(.85, 0, -1), fr=(.72, 0, -1), hl=(.42, 0, 1), hr=(.48, 0, 1))zmul = {"hl": 1.3, "hr": 1.3}elif mode == "rear":Tb = body_T(pitch)elif mode == "swim":Tb = Rigid()floor = by + g * .45else:Tb = body_T(pitch, sp.get("lift", 0.0) * ll)def head_T(Tb_, neck, yaw, head):Tn = Tb_ @ about(nb, rot_axis("y", yaw)) @ about(nb, rot_axis("z", neck))return Tn, Tn @ about(H, rot_axis("z", head))neck, yaw, head = sp.get("neck", 0.0), sp.get("yaw", 0.0), sp.get("head", 0.0)if mode == "sit":neck -= pitch * .85 # rule: a sitting animal keeps its head level although its chest is raisedif sp.get("sleep"):# rule: a sleeping animal lays its head down on its front paws (neck lowered until the head rests on them)for nk in range(0, -100, -3):Tn, Th = head_T(Tb, nk, yaw, head)if Th.pt(H)[1] <= G["h"] * 1.05 + foot_y:breakneck = nkif mode == "graze":# rule: grazing / drinking = the neck lowered until the mouth reaches the ground; a long-necked animal that# still can't reach spreads its front legs and tips its chest downfor th, fx_ in ((0, None), (-8, (.42, .2)), (-14, (.55, .3))):Tb = body_T(th, 0, hip0)if fx_:feet.update(fl=(fx_[0], 0), fr=(fx_[1], 0))ok = Falsefor nk in range(0, -126, -3):Tn, Th = head_T(Tb, nk, yaw, -10)if Th.pt(st)[1] <= foot_y + G["r2"] * 1.3:ok = Truebreakif ok:breakneck, head, pitch = nk, -10, thTn, Th = head_T(Tb, neck, yaw, head)legs = {}for k, (a0, l1, l2, rs, bend) in legs0.items():a = Tb.pt(a0)a[2] *= zmul.get(k, 1.0)spec = feet[k]Lt = l1 + l2tgt = np.array([a[0] + spec[0] * Lt, foot_y if spec[1] == 0 else a[1] + spec[1] * Lt, a[2]])if mode == "swim":tgt[1] = a[1] + spec[1] * Ltj, ft = ik2(a, tgt, l1, l2, spec[2] if len(spec) > 2 else bend)legs[k] = ([a, j, ft], rs)return dict(Tb=Tb, Tn=Tn, Th=Th, legs=legs, mouth=sp.get("mouth", 0) if (P.feet != "hooves" or pose in ("howl",)) else 0,closed=bool(sp.get("closed")), sleep=bool(sp.get("sleep")), tail=sp.get("tail"), pitch=pitch, floor=floor, mode=mode)def _quad_legs(QZ, P, lr, g):chains = list(QZ["legs"].values())paws = P.feet == "paws"def legs(p):d = Nonefor pts, rs in chains:e = chain(p, pts, rs)if paws:e = S.smin(e, S.ellipsoid(p, V(*(pts[2] + np.array([lr * .45, -lr * .05, 0]))), V(lr * 1.5, lr * .75, lr * 1.15)), lr * .5)d = e if d is None else np.minimum(d, e)return dreturn legsdef _quad_feet(QZ, P, lr, hoofed, col):chains = list(QZ["legs"].values())if hoofed:segs = []for pts, rs in chains:u = pts[2] - pts[1]u = u / max(np.linalg.norm(u), 1e-6)segs.append((pts[2] - u * .012, pts[2] + u * .04))return [Part(lambda p: np.minimum.reduce([rcone(p, a, b, lr * 1.06, lr * 1.0) for a, b in segs]),_ccol(P.hoof_col, col), spec=.5, rough=.3)]if P.feet == "pads":cs = [pts[2] + np.array([lr * .9, -lr * .4, dz]) for pts, rs in chains for dz in (-lr * .45, lr * .45)]return [Part(lambda p: np.minimum.reduce([S.sphere(p, V(*c), lr * .28) for c in cs]), (225, 218, 200), spec=.4, rough=.35)]return []# ============================================================ quadrupedQDEF = dict(body_len=.32, girth=.17, width=.95, rump=.95, leg_len=.28, leg_r=.05, thigh=1.0, slope=0.0,11 unmodified linesdef _quad(P, col, inst):col = tuple(col) if col else (150, 112, 78)pose = _qpose_name(inst)if P.trunk > 0 and pose == "graze":pose = None # rule: an elephant eats / drinks with its trunk, standingbb = _BB()L, g, w = P.body_len, P.girth, P.widthll, lr = P.leg_len, P.leg_r57 unmodified linesd = S.smin(d, S.sphere(p, H, h), nr * .6)return d# ---- pose: rigid transforms for the torso group (b), the neck (n) and the head group (h); posed legs in worldQZ = _quad_pose(pose, P, dict(R=R, C=C, g=g, gr=gr, zl=zl, ll=ll, lr=lr, by=by, fx=fx, hx=hx, foot_y=foot_y,nb=nb, nd=nd, H=H, h=h, st=st, sd=sd, r2=r2, w=w, half=half)) if pose else Noneif QZ is not None:tb_, tn_, th_ = QZ["Tb"], QZ["Tn"], QZ["Th"]legs = _quad_legs(QZ, P, lr, g)def body(p):if QZ is None:d = S.smin(torso_w(p), legs(p), lr * 1.2)d = S.smin(d, neck_head(p), g * .35)hp = pelse:hp = tb_.inv_pts(p)d = S.smin(torso_w(hp), legs(p), lr * 1.2)nk = rcone(tn_.inv_pts(p), nb - nd * g * .3, ne, nr * 1.25, nr)d = S.smin(d, S.smin(nk, S.sphere(th_.inv_pts(p), H, h), nr * .6), g * .35)for c, r in hump_c:d = S.smin(d, S.sphere(hp, c, r), g * .4)if P.fluffy > 0:d = d * .8 + P.fluffy * .03 * (S.noise3(p * 16) - .5)return dmouth = QZ["mouth"] if QZ else 0def snout(p):if mouth:# rule: an open mouth = the snout split into an upper jaw and a lower jaw hinged at the snout based = rcone(p, sb, st + np.array([0, r2 * .12, 0]), r1 * .92, r2 * .85)q = rotz_pt(p, sb, -math.radians(mouth))d = np.minimum(d, rcone(q, sb - np.array([0, r1 * .35, 0]), st - np.array([r2 * .3, r2 * .55, 0]), r1 * .6, r2 * .4))else:d = rcone(p, sb, st, r1, r2)if P.trunk > 0:t = P.trunktp = [st, st + np.array([.14 * t, -.32 * t, 0]), st + np.array([.24 * t, -.62 * t, 0]),7 unmodified linescoat_pat = tuple(P.pat) if P.pat else Noneparts = [Part(body, col, spec=P.spec, rough=P.rough, tex=P.tex, pat=coat_pat),Part(snout, _ccol(P.muzzle, col), k=h * .25, spec=P.spec, rough=P.rough, tex=P.tex)]marks = [(0, "w"), (1, "h")]if mouth:mc_ = (sb + st) * .5 - np.array([r2 * .2, r1 * .45, 0])parts.append(Part(lambda p: S.ellipsoid(p, V(*mc_), V((P.snout + h * .25) * .45, r1 * .42, r1 * .55)), (120, 40, 45), spec=.4, rough=.4))def torso_neck(p):return S.smin(torso_w(p), rcone(p, nb - nd * g * .3, ne, nr * 1.25, nr), g * .35)marks.append((len(parts), "b"))# ---- belly / bib / sock / back stripe / mask paintsif P.belly:3 unmodified linesbc = nb + nd * P.neck_len * .4reg = lambda p: np.maximum(S.ellipsoid(p, V(bc[0] + g * .35, bc[1] - g * .35, 0), V(g * .55, g * .9 + P.neck_len * .4, g * .8)),by - g * .55 - p[:, 1])parts.append(Part(_shell(body if QZ is None else torso_neck, reg), _ccol(P.bib, col), spec=P.spec, rough=P.rough, tex=P.tex))if P.back_stripe:reg = lambda p: np.maximum(np.abs(p[:, 2]) - g * .28, by + g * .3 - p[:, 1])parts.append(Part(_shell(body if QZ is None else torso_neck, reg), _ccol(P.back_stripe, col), spec=P.spec, rough=P.rough, tex=P.tex))marks.append((len(parts), "w"))if P.sock:parts.append(Part(_shell(legs, lambda p: p[:, 1] - ll * P.sock_h, .004), _ccol(P.sock, col), spec=P.spec, rough=P.rough, tex=P.tex))marks.append((len(parts), "h"))if P.mask:# face mask / blaze over the front of the headreg = lambda p: S.ellipsoid(p, V(H[0] + h * .55, H[1] + h * .1, 0), V(h * .55, h * .5, h * .35))23 unmodified linesparts.append(Part(_shell(neck_head, lambda p: S.ellipsoid(mirror_z(p), V(*(ec - np.array([h * .04, h * .06, 0]))),V(er * 1.7, er * 2.0, er * 1.9))),_ccol(P.eye_patch, col), spec=P.spec, rough=P.rough, tex=P.tex))if QZ is not None and QZ["closed"]:parts += eyelids(ec, er, en, darker(_ccol(P.mask, col) if P.mask else col, .92), mirror=mirror_z)else:parts += eyes(tuple(ec), er, tuple(en), iris=EYE, white=bool(P.eye_white), pupil=.66)# ---- earseb = H + h * np.array([-.22, .7, .52])38 unmodified lines# ---- tailtcol = _ccol(P.tail_col, col)t0 = R + np.array([-gr * .82, gr * .45, 0])tang = P.tail_ang if QZ is None or QZ["tail"] is None else QZ["tail"] + QZ["pitch"]td = _dir(180 - tang)tl, tr = P.tail, P.tail_rtail = tuft = Nonetpat = coat_pat if P.pat_tail else Nonewrap_tail = QZ is not None and QZ["sleep"] and P.tail_kind in ("thin", "tufted", "bushy") and tl > .12marks.append((len(parts), "w" if wrap_tail else "b"))if P.tail_kind in ("thin", "tufted", "bushy") and tl > 0:t_pts = _poly(t0, td, tl, P.tail_curl)if wrap_tail:# rule: a sleeping animal wraps its tail forward around its body on the near sidet0w = QZ["Tb"].pt(t0)zt = -(g * w * .95 + tr)t_pts = [t0w, np.array([t0w[0] - tl * .15, max(tr, t0w[1] * .4), zt * .7]),np.array([t0w[0] + tl * .2, tr * 1.2, zt * 1.15]), np.array([t0w[0] + tl * .65, tr * 1.1, zt * 1.2])]if P.tail_kind == "bushy":t_rs = [tl * .1, tl * .2, tl * .2, tl * .1]tail = lambda p: chain(p, t_pts, t_rs) * .934 unmodified linesparts.append(Part(tuft, _ccol(P.tip_col or P.mane_col, col), k=.01, spec=P.spec, rough=P.rough, tex=P.tex))# ---- mane / beardmarks.append((len(parts), "h"))mcol = _ccol(P.mane_col, col)if P.mane == "neck":top = np.array([-nd[1], nd[0], 0.0])95 unmodified linesbb.pts(k_pts, h * .07)# ---- hooves / toenailsmarks.append((len(parts), "w"))if QZ is not None:parts += _quad_feet(QZ, P, lr, hoofed, col)elif hoofed:parts.append(Part(lambda p: np.minimum(S.cylinder(mirror_z(p), V(fx + .012, .028, zl), lr * 1.08, .03, .01),S.cylinder(mirror_z(p), V(hx, .028, zl), lr * 1.0, .03, .01)),_ccol(P.hoof_col, col), spec=.5, rough=.3))3 unmodified lines(225, 218, 200), spec=.4, rough=.35))# ---- spikes (hedgehog / porcupine) and armour (armadillo)marks.append((len(parts), "b"))if P.spikes > 0:sc = V(R[0] * .4 + C[0] * .1, by + g * .2, 0)sr = V(L * 1.02, g * 1.08, g * w * 1.15)17 unmodified linesreturn np.maximum((e + band) * .7, by - g * .55 - p[:, 1])parts.append(Part(armor, _ccol(P.armor_col, col), spec=.45, rough=.35))# head shieldmarks.append((len(parts), "h"))parts.append(Part(lambda p: np.maximum(S.sphere(p, H + V(0, h * .1, 0), h * 1.04), H[1] + h * .1 - p[:, 1]),_ccol(P.armor_col, col), spec=.45, rough=.35))if QZ is None:return _finish(parts, bb)# posed: move every part with its group, then scale like the standing animal (bb = the standing bounds)T = {"b": QZ["Tb"], "h": QZ["Th"], "w": None}for i, pt in enumerate(parts):grp = [g_ for k_, g_ in marks if k_ <= i][-1]pt.fn = posed(pt.fn, T[grp])anchors = {"mouth": QZ["Th"].pt(st + sd * r2 * .2 - np.array([0, r2 * (.55 if mouth else .35), 0])),"nose": QZ["Th"].pt(st + np.array([-r2 * .2, r2 * 1.0, 0])),"saddle": QZ["Tb"].pt(R * .4 + C * .6 + np.array([0, g * 1.0, 0])),"head": QZ["Th"].pt(H + np.array([0, h, 0])), "pivot": QZ["Tb"].pt(np.array([0, by, 0]))}# the seat: the lowest point of the posed rump / belly (where a sitting / riding animal touches what it is on)if QZ["mode"] in ("sit", "lie"):anchors["seat"] = QZ["Tb"].pt(R + np.array([g * .2, 0, 0])) - np.array([0, gr * .95, 0])out = finish_posed(parts, bb.y1, anchors, floor=QZ.get("floor"))return out, out.aspect@family("quadruped", aspect=lambda P: _quad(P, None, None)[1], **QDEF)16 unmodified linesbb = _BB()g, h, T = P.girth, P.head, P.torsopose = P.posewant = pose_of(inst)hang = want == "hang"if want in ("sit", "ride", "lie", "sleep", "perch", "kneel", "balance") and pose != "hop":pose = "sit"elif want in ("stand", "upright", "hang", "walk", "run", "dance") and pose != "hop":pose = "stand"act = action_of(inst) or ""holding = getattr(inst, "holding", None)# rule: what the near hand does: food goes to the mouth, a wave / cheer goes up, anything else is held in fronthand_do = "mouth" if (act in ("eat", "drink") or (holding and act in ("", "carry", "hold") and(CONCEPTS_.get(holding, {}).get("setting") == "table"))) else \"up" if act in ("wave", "cheer") else "hold" if holding else Noneif pose == "sit":hip = np.array([0.0, g * .9, 0])sh = hip + np.array([.03, T, 0])53 unmodified lineselse:elbow = sha + np.array([.05, -P.arm_len * .5, .0])hand = elbow + np.array([P.arm_len * .35, P.arm_len * .05, -.04]) if P.arm_len < .3 else sha + np.array([.03, -P.arm_len, .02])if hang:# rule: hanging upside down = the standing body flipped, so the arms (raised here) dangle below the headelbow = sha + np.array([.03, P.arm_len * .5, .02])hand = sha + np.array([.06, P.arm_len * .95, .04])arm_pts = [sha, elbow, hand]bb.pts(arm_pts, P.arm_r)near = Noneif hand_do:shn = sha * np.array([1, 1, -1])if hand_do == "mouth":tgt = H + fd * h * 1.05 - up * h * .35 + side * h * .15elif hand_do == "up":tgt = shn + np.array([-P.arm_len * .45, P.arm_len * .8, -.06])else:tgt = shn + np.array([P.arm_len * .55, -P.arm_len * .3, -.1])L_ = np.linalg.norm(tgt - shn)mid = (shn + tgt) * .5 + np.array([0, -max(P.arm_len * .5 - L_ * .5, 0) - .01, -.04])if hand_do == "up":mid = (shn + tgt) * .5 + np.array([.0, 0, -.1])near = [shn, mid, tgt]bb.pts(near, P.arm_r)def limbs(p):q = mirror_z(p)d = chain(q, legs_pts, lr)if pose != "hop":d = S.smin(d, S.ellipsoid(q, V(*fp), V(P.foot * .9, P.leg_r * .9, P.leg_r * 1.3)), .03)if near is None:d = np.minimum(d, chain(q, arm_pts, [P.arm_r * 1.2, P.arm_r, P.arm_r * .95]))d = np.minimum(d, S.sphere(q, V(*hand), P.arm_r * 1.25))else:d = np.minimum(d, chain(p, arm_pts, [P.arm_r * 1.2, P.arm_r, P.arm_r * .95]))d = np.minimum(d, S.sphere(p, V(*hand), P.arm_r * 1.25))d = np.minimum(d, chain(p, near, [P.arm_r * 1.2, P.arm_r, P.arm_r * .95]))d = np.minimum(d, S.sphere(p, V(*near[2]), P.arm_r * 1.25))return ddef body(p):82 unmodified linesfr = math.pi * 2 * 5 / max(P.tail, .05)parts.append(Part(_shell(tail, lambda p: (np.sin(S.length(p - t0) * fr) - .1) * .02, .004), _ccol(P.tail_rings, col),spec=P.spec, rough=P.rough, tex=P.tex))hand_pt = near[2] if near is not None else hand * np.array([1, 1, -1])anchors = {"hand": hand_pt, "held": hand_pt, "seat": np.array([hip[0], max(hip[1] - g * .95, 0), 0]),"saddle": H + up * h, "head": H + up * h, "mouth": H + fd * h}if hang:return _hang(parts, bb, H[1] + h, legs_pts, P, anchors)hgt = max(bb.y1, 1e-3)sc = 1.0 / hgtcx = (bb.x0 + bb.x1) * .5parts, asp = _finish(parts, bb)return Model.of(parts, aspect=asp, height=1.0, anchors={k: tuple((np.asarray(v) - np.array([cx, 0, 0])) * sc) for k, v in anchors.items()}), aspdef _hang(parts, bb, ht, legs_pts, P, anchors):"""a body hanging upside down by its feet from a branch: the body flipped about its middle and lifted, plus thebranch it hangs from and the trunk that holds the branch up (the support is part of the picture)"""lift = ht * .75T = Rigid(t=(0, lift, 0)) @ about((0, ht * .5, 0), rot_axis("z", 180))for pt in parts:pt.fn = posed(pt.fn, T)feet = [T.pt(q) for q in legs_pts[-1:]]fy = max(f[1] for f in feet) + P.leg_r * 1.2fx = feet[0][0]br = max(.025, ht * .05)tx = fx - ht * .9wood = (112, 80, 52)parts.append(Part(lambda p: np.minimum(rcone(p, (tx, 0, .05), (tx, fy + ht * .25, .05), br * 2.2, br * 1.6),rcone(p, (tx, fy - br * .5, .05), (fx + ht * .35, fy, 0.0), br * 1.4, br * .8)),wood, k=br, spec=.1, rough=.85, tex="bark"))parts.append(Part(lambda p: S.sphere(p, V(tx - ht * .1, fy + ht * .45, .05), ht * .42) * .9 + .02 * (S.noise3(p * 12) - .5),(70, 140, 60), k=.02, spec=.05, rough=.9, tex="leaves"))anchors = {k: T.pt(v) for k, v in anchors.items()}return finish_posed(parts, ht, anchors, floor=0.0, max_h=1.7), None@family("primate", aspect=lambda P: _prim(P, None, None)[1], **PDEF)1 unmodified linereturn _prim(P, col, inst)[0]def _primate_action(inst):return action_of(inst)# ============================================================ bat@family("bat", aspect=1.7, wing_col="dark", ear_size=1.0, face=None, belly=None)def f_bat(P, col, inst=None):
12345678910111213"""Word-sense pins for common animal words whose FIRST WordNet sense is not the animal (wave 11: these words arefrequent subjects of action prompts). "tiger" is first a fierce person, "chicken" first the meat, "peacock" first abutterfly, "chameleon" first an inconstant person: each word is taught as its animal sense (all taxa on thatsense's path are merged, so the existing taxonomy entries do the shaping). Loaded last (z_) so the path is known."""from .animals_other import like
like("tiger", "tiger.n.02")like("chicken", "chicken.n.02", crest=.08, crest_kind="comb", color=(245, 240, 230), color2=(240, 235, 225), beak_col=(235, 175, 50))like("hen", "chicken.n.02", crest=.07, crest_kind="comb", color=(170, 100, 55), color2=(190, 120, 70))like("rooster", "chicken.n.02", crest=.11, crest_kind="comb", color=(180, 70, 40), tail_kind="streamers", tail=.4, tail_up=.4)like("peacock", "peacock.n.02")like("chameleon", "chameleon.n.03")like("seahorse", "seahorse.n.02")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793"""Imagination engine (3D side): impossible pictures from signed-distance fields. Pure code, no learned weights.
Every rule here works on a model's list of SDF parts, so it applies to ANY concept (hand-made model or generatorfamily) rather than to named prompts: - skins: "X made of Y" / "a Y X" -> X's geometry, Y's material (colour, gloss, texture, surface detail: cheese holes, chocolate drips, knit stitches, wood grain, marble veins, ice cracks, cloud puffs, lego voxels...) - morph: "X shaped like Y" -> Y's body with X's function parts (spout, door, windows) moved onto Y's surface - chimeras: griffin, centaur, mermaid, "a cat with butterfly wings", "a fish with legs": parts cut out of one family model (by region, using the eyes to find the head) and grafted onto another - surreal: things on an animal's back, floating islands, upside-down and melting thingsThe parser side (pydraw/imagine.py) decides WHAT to do; this module only transforms parts."""import mathimport numpy as np
from . import sdf as Sfrom .models import Part, V, MODELS
# ------------------------------------------------------------------ part utilitiesdef clone(pt, fn=None, color=None, **kw): q = Part(fn or pt.fn, pt.color if color is None else color, k=pt.k, spec=pt.spec, rough=pt.rough, tex=pt.tex, emit=getattr(pt, "emit", 0.0), pat=getattr(pt, "pat", None)) q.metal = getattr(pt, "metal", 0.0) q.glass = getattr(pt, "glass", 0.0) for k, v in kw.items(): setattr(q, k, v) return q
def union(parts): def f(p): d = None for pt in parts: e = pt.fn(p) d = e if d is None else S.smin(d, e, pt.k) return d return f
def moved(parts, offset=(0, 0, 0), scale=1.0, yaw=0.0, flip=False, sxyz=None): """Parts translated / uniformly scaled / turned about y (and optionally flipped upside down about y=.5*scale). sxyz: a mild non-uniform scale (the SDF is divided by the largest factor -> an under-estimate, safe to march).""" o = np.asarray(offset, np.float32) s = np.asarray(sxyz if sxyz is not None else (scale, scale, scale), np.float32) smin_ = float(s.min()) out = [] for pt in parts: def fn(p, _f=pt.fn): q = (p - o) if yaw: q = S.rot_y(q, -yaw) q = q / s if flip: q = q.copy() q[:, 1] = 1.0 - q[:, 1] return _f(q.astype(np.float32)) * smin_ tex = pt.tex if callable(tex): def tex(q, base, seed, _t=pt.tex): q2 = q - o if yaw: q2 = S.rot_y(q2, -yaw) q2 = q2 / s if flip: q2 = q2.copy() q2[:, 1] = 1.0 - q2[:, 1] return _t(q2, base, seed) out.append(clone(pt, fn=fn, k=pt.k * smin_, tex=tex)) return out
def clipped(parts, region, keep="out", soft=0.0): """Cut parts with a region SDF: keep="out" removes what is inside the region, keep="in" keeps only that.""" out = [] for pt in parts: if keep == "out": fn = lambda p, _f=pt.fn: np.maximum(_f(p), -region(p)) else: fn = lambda p, _f=pt.fn: np.maximum(_f(p), region(p)) out.append(clone(pt, fn=fn)) return out
def lum(c): c = np.asarray(c, float) return float(.3 * c[0] + .59 * c[1] + .11 * c[2])
_STATS = {}
def analyze(parts, aspect=1.0, n=30, bounds=None): """Sample a grid around the model: per part volume (share of inside points it owns), centroid and bbox of the points within half a cell of the part (so thin parts and small eyes are seen), the union's bbox, eye positions (tiny dark glossy parts) and the biggest part ("body"). Cached per parts list.""" key = (id(parts), bounds) if key in _STATS and _STATS[key][0] is parts: return _STATS[key][1] if bounds is None: w = max(aspect, .6) * .5 + .35 bounds = ((-w, w), (-.25, 1.45), (-w * .9, w * .9)) (x0, x1), (y0, y1), (z0, z1) = bounds xs = np.linspace(x0, x1, n) ys = np.linspace(y0, y1, n) zs = np.linspace(z0, z1, max(12, n * 3 // 4)) cell = np.array([xs[1] - xs[0], ys[1] - ys[0], zs[1] - zs[0]]) eps = .5 * float(np.linalg.norm(cell)) X, Y, Z = np.meshgrid(xs, ys, zs, indexing="ij") P = np.stack([X.ravel(), Y.ravel(), Z.ravel()], -1).astype(np.float32) ds = np.stack([np.asarray(pt.fn(P), float) for pt in parts], -1) du = union(parts)(P) inside = du < 0 own = ds.argmin(-1) res = {"parts": [], "inside": int(inside.sum()), "eps": eps} tot = max(1, inside.sum()) for j, pt in enumerate(parts): m = inside & (own == j) m2 = ds[:, j] < eps if m2.sum() == 0: res["parts"].append(dict(vol=0.0, c=np.zeros(3), lo=np.zeros(3), hi=np.zeros(3), n=0)) continue # rule: inside points give the extent (SDFs may under-estimate, so "near" can reach far); thin parts with # no inside sample fall back to the near-surface points m3 = ds[:, j] < 0 q = P[m3] if m3.sum() >= 3 else P[m2] pad = cell * .5 if m3.sum() >= 3 else -cell * .25 res["parts"].append(dict(vol=m.sum() / tot, c=q.mean(0), lo=q.min(0) - pad, hi=q.max(0) + pad, n=int(m2.sum()))) live = [s_ for s_ in res["parts"] if s_["n"]] if live: res["lo"] = np.min([s_["lo"] for s_ in live], 0) res["hi"] = np.max([s_["hi"] for s_ in live], 0) res["c"] = P[inside].mean(0) if inside.any() else np.mean([s_["c"] for s_ in live], 0) else: res["lo"], res["hi"], res["c"] = np.array([-.5, 0, -.3]), np.array([.5, 1, .3]), np.array([0, .5, 0]) eyes = [] for j, pt in enumerate(parts): st = res["parts"][j] if st["n"] == 0 or st["vol"] > .02: continue ext = st["hi"] - st["lo"] if max(ext[0], ext[1]) > .2: continue if lum(pt.color) < 70 and pt.spec >= .45: eyes.append(st) if eyes: # rule: the eyes are the highest cluster of small dark glossy parts (not a belt buckle) ytop = max(e["c"][1] for e in eyes) eyes = [e for e in eyes if e["c"][1] > ytop - .08] res["eyes"] = np.array([e["c"] for e in eyes]) if eyes else None res["eye_span"] = max([max(e["hi"][0] - e["lo"][0], e["hi"][2] - e["lo"][2]) for e in eyes]) if eyes else 0.0 order = np.argsort([-s["vol"] for s in res["parts"]]) res["body"] = int(order[0]) _STATS[key] = (parts, res) return res
def probe(fn, origin, direction, tmax=3.0): """Sphere-trace one ray; returns the hit point or None.""" o = np.asarray(origin, np.float32)[None, :] d = np.asarray(direction, np.float32) d = d / np.linalg.norm(d) t = 0.0 for _ in range(200): p = o + d[None, :] * t e = float(fn(p.astype(np.float32))[0]) if e < 1e-3: return p[0] t += max(e * .8, 1e-3) if t > tmax: return None return None
def top_at(fn, x, z, ytop=2.5): h = probe(fn, (x, ytop, z), (0, -1, 0), ytop + .5) return None if h is None else float(h[1])
def head_center(st): """Head position from the eyes (mean of the eye parts, moved to the midline and a bit back).""" e = st["eyes"] if e is None or not len(e): return None c = e.mean(0).copy() c[2] = 0.0 return c
# ------------------------------------------------------------------ material textures (callable tex)def _smooth(a, b, x): t = np.clip((x - a) / (b - a), 0, 1) return t * t * (3 - 2 * t)
def _lin(c): return (np.asarray(c, float) / 255.0) ** 2.2
def _thin_glow(fn, amount): """rule (translucency hint): thin parts of glass / ice / jelly glow brighter, as light passes through them. Thickness is read from the part's own SDF a short way inside the surface.""" def g(q, a): e = 2e-3 k = np.array([[1, -1, -1], [-1, -1, 1], [-1, 1, -1], [1, 1, 1]], np.float32) n = sum(kk[None, :] * fn((q + kk * e).astype(np.float32))[:, None] for kk in k) n = n / np.maximum(S.length(n)[:, None], 1e-9) inner = fn((q - n * .07).astype(np.float32)) thin = np.clip(1 + inner / .07, 0, 1) # 1 = thin (inner point already outside), 0 = thick return a * (1 + amount * thin[:, None]) return g
def thin_glow_tex(fn, amount): g = _thin_glow(fn, amount) return lambda q, base, seed: g(q, base[None, :] * np.ones((len(q), 1)))
def tex_knit(c2=None, scale=1.0): K = 26.0 * scale
def t(q, base, seed): u = (q[:, 0] + .65 * q[:, 2]) * K v = q[:, 1] * K * 1.35 fu = (u % 1.0) - .5 fv = (v % 1.0) - .5 # rule: a knit stitch is a V of two leaning loops; brightness peaks along each loop's ridge a = np.abs(fu) ridge = 1 - np.clip(np.abs((fv + .1) - (a * 1.3 - .35)) * 3.2, 0, 1) gap = _smooth(.38, .5, a) sh = (.5 + .6 * ridge) * (1 - .45 * gap) col = base[None, :] * sh[:, None] if c2 is not None: row = np.floor(v / 5).astype(np.int64) % 2 == 1 col[row] = _lin(c2)[None, :] * sh[row][:, None] return col return t
def tex_wood(light=(205, 150, 95), dark=(125, 78, 42)): def t(q, base, seed): n = S.fbm(q * np.array([1.5, 6, 1.5], np.float32), 3, seed) r = (q[:, 0] * 1.0 + q[:, 2] * .6) * 22 + n * 5 g = .5 + .5 * np.sin(r) g = g ** 3 fine = S.noise3(q * np.array([60, 4, 60], np.float32), seed + 3) c = _lin(light)[None, :] * (1 - g[:, None]) + _lin(dark)[None, :] * g[:, None] return c * (.88 + .2 * fine[:, None]) return t
def tex_marble(vein=(110, 110, 125)): def t(q, base, seed): w = (q[:, 0] + .7 * q[:, 1] + .3 * q[:, 2]) * 7 + 5 * S.fbm(q * 3, 4, seed) v = np.abs(np.sin(w)) m = 1 - _smooth(.0, .12, v) c = base[None, :] * (.95 + .08 * S.noise3(q * 20, seed)[:, None]) return c * (1 - m[:, None] * .8) + _lin(vein)[None, :] * m[:, None] * .8 return t
def tex_ice(): def t(q, base, seed): f1, f2, _ = S.worley(q * 7, seed) crack = 1 - _smooth(.0, .05, f2 - f1) frost = _smooth(.55, .8, S.fbm(q * 5, 3, seed + 2)) c = base[None, :] * (.9 + .2 * S.noise3(q * 9, seed)[:, None]) w = np.clip(crack * .8 + frost * .5, 0, 1)[:, None] return c * (1 - w) + np.array([.95, .98, 1.0]) * w * 1.2 return t
def tex_cheese(): def t(q, base, seed): n = S.noise3(q * 30, seed) return base[None, :] * (.92 + .14 * n[:, None]) return t
def tex_coat(top_color, base_color, drip_fn, sprinkles=False): """A coating (frosting / chocolate / icing) over the top with drips; colour only (the geometry swells in geo).""" def t(q, base, seed): m = drip_fn(q) c = _lin(base_color)[None, :] * (.92 + .12 * S.noise3(q * 25, seed)[:, None]) top = _lin(top_color)[None, :] * np.ones((len(q), 1)) out = c * (1 - m[:, None]) + top * m[:, None] if sprinkles: f1, f2, cid = S.worley(q * 40, seed + 5) sp = (f1 < .22) & (m > .5) pal = np.array([_lin(x) for x in ((240, 70, 90), (250, 220, 60), (80, 170, 240), (120, 210, 110), (250, 250, 250))]) out[sp] = pal[(cid[sp] * 5).astype(int) % 5] return out return t
def tex_bread(): def t(q, base, seed): n = S.fbm(q * 14, 3, seed) pores = S.noise3(q * 70, seed + 1) > .78 top = np.clip((q[:, 1] - .3) * 1.4, 0, 1) c = base[None, :] * (1.05 - .4 * top[:, None]) * (.85 + .3 * n[:, None]) c[pores] *= .7 return c return t
def tex_chips(chip=(70, 40, 22)): def t(q, base, seed): f1, _, cid = S.worley(q * 9, seed) m = (f1 < .2) & (cid > .4) c = base[None, :] * (.85 + .25 * S.fbm(q * 12, 3, seed)[:, None]) c[m] = _lin(chip) return c return t
def tex_spiral(c2=(250, 250, 250), turns=7): def t(q, base, seed): a = np.arctan2(q[:, 2], q[:, 0]) / (2 * math.pi) s = np.sin((q[:, 1] * turns + a * 2) * 2 * math.pi) m = (s > .25).astype(float) return base[None, :] * (1 - m[:, None]) + _lin(c2)[None, :] * m[:, None] return t
def tex_lava(): def t(q, base, seed): f1, f2, _ = S.worley(q * 6 + .4 * S.noise3(q * 8, seed)[:, None], seed) crack = 1 - _smooth(.0, .09, f2 - f1) crust = np.array([.03, .025, .025]) * (.7 + .6 * S.noise3(q * 20, seed)[:, None]) hot = np.array([1.6, .45, .05]) * (.8 + .4 * S.noise3(q * 5, seed + 1)[:, None]) return crust * (1 - crack[:, None]) + hot * crack[:, None] return t
def tex_fire(): def t(q, base, seed): n = S.fbm(q * np.array([5, 2.5, 5], np.float32) - np.array([0, 1, 0], np.float32), 3, seed) h = np.clip(q[:, 1] * 1.15 - .1 + .5 * (n - .5), 0, 1) c0, c1, c2 = np.array([1.0, .6, .08]), np.array([.9, .18, .02]), np.array([.45, .03, .02]) a = np.clip(h * 2, 0, 1)[:, None] b = np.clip(h * 2 - 1, 0, 1)[:, None] return (c0 * (1 - a) + c1 * a) * (1 - b) + c2 * b return t
def tex_rainbow(): pal = [(230, 60, 60), (245, 150, 50), (245, 220, 60), (90, 190, 90), (70, 140, 230), (140, 90, 210)]
def t(q, base, seed): k = np.clip((q[:, 1] * 6).astype(int), 0, 5) return np.array([_lin(c) for c in pal])[k] return t
def tex_bricks(): def t(q, base, seed): row = np.floor(q[:, 1] * 18) u = (q[:, 0] + q[:, 2]) * 9 + (row % 2) * .5 mortar = ((q[:, 1] * 18) % 1 < .14) | ((u % 1) < .07) c = base[None, :] * (.8 + .35 * S._hash(np.floor(u).astype(np.int64), row.astype(np.int64), np.zeros(len(q), np.int64) + 3, seed)[:, None]) c[mortar] = _lin((215, 210, 195)) return c return t
def tex_flowers(base_green=(70, 130, 55)): pal = [(250, 250, 245), (245, 210, 60), (235, 110, 150), (190, 120, 230), (240, 120, 70)]
def t(q, base, seed): f1, _, cid = S.worley(q * 16, seed) m = f1 < .3 c = _lin(base_green)[None, :] * (.6 + .7 * S.fbm(q * 18, 3, seed)[:, None]) c[m] = np.array([_lin(x) for x in pal])[(cid[m] * 5).astype(int) % 5] return c return t
def tex_leaves(): def t(q, base, seed): n = S.fbm(q * 18, 3, seed) return base[None, :] * (.55 + .8 * n[:, None]) * np.array([1, 1.05, .9]) return t
def tex_noise(amount=.15, freq=12): def t(q, base, seed): return base[None, :] * (1 - amount / 2 + amount * S.noise3(q * freq, seed)[:, None]) return t
def tex_weave(): def t(q, base, seed): u = (q[:, 0] + .6 * q[:, 2]) * 30 v = q[:, 1] * 30 over = ((np.floor(u) + np.floor(v)) % 2 == 0) f = np.where(over, np.abs((u % 1) - .5), np.abs((v % 1) - .5)) return base[None, :] * (1.1 - .6 * f[:, None] ** 1.5) return t
def tex_facets(base_col): """rule (papercraft / low poly): each lattice cell of a coarse grid is one flat-looking facet of slightly different brightness.""" def t(q, base, seed): c = np.floor(q * 7).astype(np.int64) h = S._hash(c[:, 0], c[:, 1], c[:, 2], seed) return base[None, :] * (.82 + .3 * h[:, None]) return t
# ------------------------------------------------------------------ geometric surface detail (fn wrappers)def geo_holes(fn, cell=.13, rmax=.045, density=.55, seed=3): """Swiss-cheese holes: one jittered sphere per lattice cell (kept inside its cell -> exact under-estimate).""" def f(p): d = fn(p) c = np.floor(p / cell) ci = c.astype(np.int64) j = np.stack([S._hash(ci[:, 0], ci[:, 1], ci[:, 2], seed + k) for k in range(4)], -1) cen = (c + .5 + (j[:, :3] - .5) * .25) * cell r = rmax * (.45 + .55 * j[:, 3]) * (j[:, 3] > (1 - density)) h = r - S.length(p - cen) return np.maximum(d, h) return f
def geo_bumps(fn, amp=.02, freq=12.0, seed=0): return lambda p: fn(p) * .8 - amp * (S.fbm(p * freq, 3, seed) - .35)
def geo_puffs(fn, amp=.07, seed=0): """Cloud / topiary puffs: big rounded lumps from cellular noise, plus a little fine fluff.""" def f(p): d = fn(p) f1, _, _ = S.worley(p * 7, seed) return d * .75 - amp * (1 - np.clip(f1 * 1.6, 0, 1)) - .012 * S.noise3(p * 28, seed) return f
def geo_swell(fn, mask, amp=.014): return lambda p: fn(p) - amp * mask(p)
def drip_mask(ytop, depth=.2, n=14, seed=1): """Coating mask: 1 above a wavy line under the top, with rounded drips running down.""" def m(q): a = np.arctan2(q[:, 2], q[:, 0]) / (2 * math.pi) * n + 2 * (q[:, 0] + q[:, 2]) ia = np.floor(a) fa = a - ia L = depth * (.4 + 1.2 * S._hash(ia.astype(np.int64), np.zeros(len(q), np.int64), np.zeros(len(q), np.int64), seed)) w = .3 prof = L * np.sqrt(np.clip(1 - ((fa - .5) / w) ** 2, 0, 1)) line = ytop - depth * .45 - prof + .015 * np.sin(a * 6.3) return _smooth(-.01, .01, q[:, 1] - line) return m
def geo_voxel(fn, s=.075, studs=True): """rule (lego / minecraft / pixelated): the shape becomes a stack of cubes on a lattice; cells whose centre is inside the original shape are filled. Under-estimate: an empty cell is at least its own face distance away.""" def f(p): c = (np.floor(p / s) + .5) * s fill = fn(c.astype(np.float32)) < 0 q = np.abs(p - c) box = S.rbox(p - c, np.zeros(3), (s * .49, s * .49, s * .49), s * .08) if studs: up = (np.floor(p / s) + .5) * s + np.array([0, s, 0], np.float32) top_free = fn(up.astype(np.float32)) >= 0 st = S.cylinder(p - c, np.array([0, s * .55, 0], np.float32), s * .22, s * .08, s * .02) box = np.where(top_free, np.minimum(box, st), box) bnd = s * .5 - q.max(-1) empty = np.maximum(np.maximum(bnd, .03 * s), fn(p) - .9 * s) return np.where(fill, box, empty) return f
def geo_lowpoly(fn, s=.09): """rule (origami / papercraft / low poly): the SDF is sampled on a coarse lattice and interpolated linearly, which flattens curved surfaces into facets with creases.""" def f(p): g = p / s i = np.floor(g) t = g - i acc = 0 for dx in (0, 1): for dy in (0, 1): for dz in (0, 1): w = (t[:, 0] if dx else 1 - t[:, 0]) * (t[:, 1] if dy else 1 - t[:, 1]) * (t[:, 2] if dz else 1 - t[:, 2]) acc = acc + w * fn(((i + np.array([dx, dy, dz])) * s).astype(np.float32)) return acc * .8 return f
def geo_melt(fn, amount=.35, floor=0.0): """rule (Dali): melting = the upper part sags down and spreads, pooling on the ground. Domain warp: a point at height y samples the shape higher up (stretching it down), more toward the edges.""" def f(p): q = p.copy() r = np.sqrt(q[:, 0] ** 2 + q[:, 2] ** 2) sag = amount * np.clip(1 - q[:, 1], 0, 1) ** 1.5 q[:, 1] = q[:, 1] + sag * (.6 + .6 * S.noise3(p * np.array([5, 1, 5], np.float32), 4)) q[:, 0] = q[:, 0] / (1 + .6 * sag) q[:, 2] = q[:, 2] / (1 + .6 * sag) return fn(q.astype(np.float32)) * .55 return f
# ------------------------------------------------------------------ skins# A skin is (colour, spec, rough, emit, tex-maker, geo-maker, keep_eyes, extra). Colours are sRGB.def _skin(color, spec=.2, rough=.5, emit=0.0, tex=None, geo=None, eyes="same", tint=True, glow=0.0, details=None, metal=0.0, glass=0.0): return dict(color=color, spec=spec, rough=rough, emit=emit, tex=tex, geo=geo, eyes=eyes, tint=tint, glow=glow, details=details, metal=metal, glass=glass)
SKINS = { "cheese": _skin((246, 196, 72), spec=.25, rough=.45, tex=lambda c, st: tex_cheese(), geo=lambda fn, st, k: geo_holes(fn, seed=3 + k)), "chocolate": _skin((98, 56, 30), spec=.55, rough=.25, tex="coat:(62,34,20)", geo="coat"), "white chocolate": _skin((240, 228, 205), spec=.5, rough=.3, tex="coat:(120,70,38)", geo="coat"), "cake": _skin((238, 205, 150), spec=.15, rough=.7, tex="coat:(248,170,200):sprinkles", geo="coat"), "frosting": _skin((248, 190, 210), spec=.3, rough=.5, tex="coat:(250,250,250)", geo="coat"), "ice cream": _skin((250, 200, 215), spec=.3, rough=.6, tex="coat:(250,245,235)", geo="coat"), "candy": _skin((240, 90, 130), spec=.85, rough=.08, tex=lambda c, st: tex_spiral((250, 250, 250))), "gingerbread": _skin((175, 105, 55), spec=.15, rough=.8, tex=lambda c, st: tex_noise(.2, 25), details=(252, 250, 245)), "bread": _skin((200, 130, 62), spec=.12, rough=.8, tex=lambda c, st: tex_bread()), "cookie": _skin((205, 150, 85), spec=.1, rough=.85, tex=lambda c, st: tex_chips()), "jelly": _skin((170, 25, 50), spec=.9, rough=.05, emit=.1, glow=.8, glass=.7), "honey": _skin((180, 105, 15), spec=.9, rough=.08, emit=.1, glow=.6, glass=.5), "sugar": _skin((250, 250, 250), spec=.3, rough=.6, tex=lambda c, st: tex_noise(.12, 60)), "marshmallow": _skin((252, 240, 245), spec=.1, rough=.9, geo=lambda fn, st, k: geo_bumps(fn, .012, 6, k)), "glass": _skin((70, 105, 120), spec=1.0, rough=.03, emit=.0, glow=.6, tint=False, glass=.9), "crystal": _skin((185, 150, 235), spec=1.0, rough=.04, emit=.1, glow=.8, glass=.5, tex=lambda c, st: tex_facets(c), geo=lambda fn, st, k: geo_lowpoly(fn, .1)), "ice": _skin((120, 160, 185), spec=.9, rough=.1, emit=.05, glow=.6, glass=.55, tex=lambda c, st: tex_ice()), "water": _skin((45, 95, 150), spec=1.0, rough=.04, emit=.05, glow=.6, glass=.8, geo=lambda fn, st, k: geo_bumps(fn, .006, 9, k)), "bubble": _skin((120, 135, 150), spec=1.0, rough=.03, emit=.05, glow=.6, glass=.9, tex=lambda c, st: tex_rainbow()), "gold": _skin((230, 170, 60), spec=.95, rough=.12, tint=False, metal=1.0), "silver": _skin((215, 218, 226), spec=.95, rough=.1, tint=False, metal=1.0), "metal": _skin((185, 190, 200), spec=.9, rough=.16, tint=False, metal=.8), "bronze": _skin((175, 105, 50), spec=.85, rough=.18, tint=False, metal=.9), "copper": _skin((205, 110, 65), spec=.9, rough=.15, tint=False, metal=.9), "chrome": _skin((235, 238, 242), spec=1.0, rough=.04, tint=False, metal=1.0), "rust": _skin((150, 75, 40), spec=.15, rough=.9, tex=lambda c, st: tex_noise(.4, 18)), "stone": _skin((165, 162, 152), spec=.08, rough=.92, tex=lambda c, st: tex_noise(.3, 9), tint=False, geo=lambda fn, st, k: geo_bumps(fn, .006, 14, k)), "marble": _skin((225, 222, 215), spec=.5, rough=.2, tex=lambda c, st: tex_marble((80, 80, 95)), tint=False), "jade": _skin((90, 170, 120), spec=.7, rough=.15, emit=.12, glow=.7, tex=lambda c, st: tex_marble((40, 110, 70)), tint=False), "clay": _skin((195, 105, 65), spec=.08, rough=.92, tex=lambda c, st: tex_noise(.12, 20), tint=False), "porcelain": _skin((246, 246, 248), spec=.8, rough=.1, tint=False, details=(40, 75, 165)), "wood": _skin((185, 130, 80), spec=.25, rough=.55, tex=lambda c, st: tex_wood(), tint=False), "bamboo": _skin((200, 190, 110), spec=.3, rough=.5, tex=lambda c, st: tex_wood((215, 205, 125), (150, 140, 70)), tint=False), "wicker": _skin((200, 160, 100), spec=.1, rough=.85, tex=lambda c, st: tex_weave(), tint=False), "straw": _skin((220, 190, 110), spec=.08, rough=.9, tex=lambda c, st: tex_weave(), tint=False), "paper": _skin((246, 243, 236), spec=.05, rough=.95, tex=lambda c, st: tex_facets(c), geo=lambda fn, st, k: geo_lowpoly(fn, .1)), "cardboard": _skin((190, 150, 100), spec=.05, rough=.95, tex=lambda c, st: tex_facets(c), geo=lambda fn, st, k: geo_lowpoly(fn, .1)), "plastic": _skin((230, 60, 50), spec=.7, rough=.15), "lego": _skin((225, 45, 40), spec=.6, rough=.2, geo=lambda fn, st, k: geo_voxel(fn, .085, True)), "voxel": _skin((110, 170, 80), spec=.1, rough=.8, geo=lambda fn, st, k: geo_voxel(fn, .085, False), tex=lambda c, st: tex_facets(c)), "balloon": _skin((235, 60, 80), spec=.95, rough=.08, geo=lambda fn, st, k: (lambda p: fn(p) - .03)), "rubber": _skin((240, 200, 40), spec=.7, rough=.25), "knit": _skin((205, 60, 70), spec=.05, rough=.95, eyes="button", geo=lambda fn, st, k: (lambda p: fn(p) - .008), tex="knit"), "felt": _skin((210, 90, 90), spec=.03, rough=1.0, eyes="button", tex=lambda c, st: tex_noise(.25, 60)), "plush": _skin((205, 160, 120), spec=.05, rough=.95, eyes="button", tex=lambda c, st: tex_noise(.3, 45), geo=lambda fn, st, k: (lambda p: fn(p) - .012)), "fur": _skin((180, 130, 90), spec=.05, rough=.95, eyes="keep", tex=lambda c, st: tex_noise(.35, 50)), "leather": _skin((120, 70, 40), spec=.45, rough=.35, tex=lambda c, st: tex_noise(.15, 40)), "denim": _skin((60, 90, 150), spec=.05, rough=.9, tex=lambda c, st: tex_weave()), "cloud": _skin((250, 251, 254), spec=.0, rough=1.0, emit=.32, eyes="keep", geo=lambda fn, st, k: geo_puffs(fn, .075, k), tint=False), "smoke": _skin((150, 150, 158), spec=.0, rough=1.0, emit=.15, geo=lambda fn, st, k: geo_puffs(fn, .06, k)), "snow": _skin((245, 248, 252), spec=.1, rough=.8, emit=.1, tex=lambda c, st: tex_noise(.08, 40), tint=False, geo=lambda fn, st, k: geo_bumps(fn, .008, 10, k)), "sand": _skin((222, 196, 140), spec=.03, rough=1.0, tex=lambda c, st: tex_noise(.25, 80), tint=False, geo=lambda fn, st, k: geo_bumps(fn, .005, 20, k)), "leaves": _skin((70, 135, 55), spec=.08, rough=.9, eyes="keep", tex=lambda c, st: tex_leaves(), geo=lambda fn, st, k: geo_puffs(fn, .03, k)), "moss": _skin((95, 140, 50), spec=.05, rough=.95, tex=lambda c, st: tex_leaves(), geo=lambda fn, st, k: geo_bumps(fn, .012, 25, k)), "flowers": _skin((70, 130, 55), spec=.08, rough=.85, eyes="keep", tex=lambda c, st: tex_flowers(), geo=lambda fn, st, k: geo_puffs(fn, .03, k), tint=False), "fire": _skin((255, 150, 40), spec=.0, rough=1.0, emit=.6, tex=lambda c, st: tex_fire(), tint=False, geo=lambda fn, st, k: geo_bumps(fn, .03, 7, k)), "lava": _skin((40, 30, 30), spec=.3, rough=.6, emit=.7, tex=lambda c, st: tex_lava(), tint=False, geo=lambda fn, st, k: geo_bumps(fn, .008, 10, k)), "neon": _skin((255, 60, 200), spec=.3, rough=.3, emit=.8), "light": _skin((255, 235, 160), spec=.2, rough=.4, emit=.85), "rainbow": _skin((250, 250, 250), spec=.4, rough=.3, tex=lambda c, st: tex_rainbow(), tint=False), "brick": _skin((175, 75, 55), spec=.05, rough=.9, tex=lambda c, st: tex_bricks(), tint=False), "bone": _skin((232, 222, 196), spec=.2, rough=.6, tex=lambda c, st: tex_noise(.12, 20), tint=False), "coral": _skin((245, 120, 110), spec=.1, rough=.8, geo=lambda fn, st, k: geo_holes(fn, .08, .025, .7, k), tint=False), "food": _skin((200, 140, 80), spec=.3, rough=.5, tex=lambda c, st: tex_noise(.18, 20)),}# rule: food-family stuff paints with its own pattern when it has one (watermelon stripes, strawberry seeds) -> "food"# skins built from a model's dominant part are made in derive()
def _resolve_tex(sk, c, st, ytop): t = sk["tex"] if t is None: return None if callable(t): return t(c, st) if t == "knit": return tex_knit(None) if isinstance(t, str) and t.startswith("coat:"): bits = t.split(":") top = tuple(int(v) for v in bits[1].strip("()").split(",")) return tex_coat(top, c, drip_mask(ytop), sprinkles="sprinkles" in bits) return None
def apply_skin(parts, skin, color=None, aspect=1.0, seed=0, trace=None): """Re-skin a model: every part takes the skin's material; X's own colours survive only as brightness (so a chocolate house still shows its door and windows); eyes stay readable where the skin says so.""" sk = SKINS[skin] if isinstance(skin, str) else skin st = analyze(parts, aspect) base = np.asarray(color if color is not None else sk["color"], float) body_l = max(30.0, lum(parts[st["body"]].color)) ytop = float(st["hi"][1]) eye_ids = set() if st["eyes"] is not None: for j, s_ in enumerate(st["parts"]): if s_["n"] and s_["vol"] < .02 and (s_["hi"] - s_["lo"]).max() < .18 and any(np.linalg.norm(s_["c"] - e) < .06 for e in st["eyes"]): eye_ids.add(j) tex = _resolve_tex(sk, tuple(base), st, ytop) out = [] for j, pt in enumerate(parts): if j in eye_ids and sk["eyes"] in ("keep", "button"): if sk["eyes"] == "button": out.append(clone(pt, color=(25, 22, 22) if lum(pt.color) < 128 else (245, 240, 230), spec=.6, rough=.2, tex=None, pat=None)) else: out.append(pt) continue small = st["parts"][j]["vol"] < .04 and j != st["body"] if sk.get("details") is not None and small: c = np.asarray(sk["details"], float) elif sk["tint"]: # rule: keep the original's light/dark structure as a gentle modulation of the new colour k = np.clip((lum(pt.color) / body_l) ** .35, .6, 1.25) c = np.clip(base * k, 0, 255) else: k = np.clip((lum(pt.color) / body_l) ** .25, .75, 1.12) c = np.clip(base * k, 0, 255) fn = pt.fn g = sk["geo"] if g == "coat": fn = geo_swell(fn, drip_mask(ytop), .012) elif callable(g): fn = g(fn, st, j) t = tex if sk["glow"]: gl = _thin_glow(pt.fn, sk["glow"]) t0 = t
def t(q, b, s_, _t0=t0, _gl=gl): a = _t0(q, b, s_) if _t0 is not None else b[None, :] * np.ones((len(q), 1)) return _gl(q, a) np_ = Part(fn, tuple(c), k=pt.k, spec=sk["spec"], rough=sk["rough"], tex=t, emit=sk["emit"], pat=sk.get("pat")) np_.metal = sk.get("metal", 0.0) np_.glass = sk.get("glass", 0.0) out.append(np_) if trace is not None: trace.append("imagine: re-skinned %d parts with %s" % (len(parts), skin if isinstance(skin, str) else "derived skin")) return out
# ------------------------------------------------------------------ deriving a skin from any noundef model_of(word, color=None): """(parts, aspect) for a concept name or any noun the open vocabulary can resolve, else None.""" from pydraw.registry import CONCEPTS name = word if name not in MODELS: try: from pydraw.understanding import match_noun h, ln = match_noun(word.split(), 0) if h and ln == len(word.split()): name = h[0] except Exception: pass if name not in MODELS: try: from pydraw.open_vocab import resolve, family_model r = resolve(word, CONCEPTS) if r: name = r[0] if name not in MODELS and name in CONCEPTS: fm = family_model(name) if fm: MODELS[name] = fm except Exception: return None if name not in MODELS and name in EXTRA_MODELS: fn, aspect = EXTRA_MODELS[name] return fn(color, None), aspect if name not in MODELS: return None fn, aspect = MODELS[name] col = color if color is not None else (CONCEPTS[name].get("default_color") if name in CONCEPTS else None) try: return fn(col, None), aspect except Exception: return None
def _shoe(col, inst=None): """A sneaker / boot for imagination use only (morph targets: "a house shaped like a shoe"); toe toward +x.""" up = col or (60, 110, 200) from .models_animals import chain
def upper(p): d = S.smin(S.ellipsoid(p, V(.35, .2, 0), V(.42, .2, .27)), S.rbox(p, V(-.35, .38, 0), (.3, .36, .26), .12), .2) d = np.maximum(d, p[:, 1] - .78) hole = S.ellipsoid(p, V(-.38, .8, 0), V(.22, .14, .17)) return np.maximum(d, -hole) * .9
def sole(p): return S.rbox(p, V(0, .06, 0), (.82, .065, .29), .05)
def laces(p): return np.minimum.reduce([S.capsule(p, (x, .41 - (x + .1) * .45, -.17), (x, .41 - (x + .1) * .45, .17), .022) for x in (-.1, .05, .2)]) return [Part(upper, up, spec=.25, rough=.5), Part(sole, (245, 245, 240), k=.02, spec=.3, rough=.4), Part(laces, (250, 250, 250), spec=.3, rough=.5)]
EXTRA_MODELS = {"shoe": (_shoe, 1.7), "boot": (_shoe, 1.7), "sneaker": (_shoe, 1.7)}
def derive(word, kind, color=None): """A skin for a stuff word nobody listed, from its WordNet kind (food / plant / mineral / metal / fabric / animal) and its own model's dominant colour and pattern (a car made of watermelon is green with dark stripes).""" m = model_of(word) col, pat, tex = (200, 160, 110), None, None if m: parts, asp = m st = analyze(parts, asp) b = parts[st["body"]] col, pat, tex = tuple(b.color), getattr(b, "pat", None), b.tex if color is not None: col = color base = dict(SKINS.get({"food": "food", "plant": "leaves", "mineral": "stone", "metal": "metal", "gem": "crystal", "fabric": "knit", "animal": "fur"}.get(kind, "food"), SKINS["food"])) base = dict(base) base["color"] = col base["tint"] = True if kind in ("mineral", "metal", "gem"): base["tint"] = False if pat and kind in ("food", "animal", "plant"): base["pat"] = pat if kind == "food" and tex: base["tex"] = None return base
def skin_parts(parts, skin_name, color, aspect, seed=0, trace=None, word=None, kind=None): if skin_name in SKINS: out = apply_skin(parts, skin_name, color, aspect, seed, trace) else: sk = derive(word or skin_name, kind or "food", color) out = apply_skin(parts, sk, None, aspect, seed, trace) if sk.get("pat"): st = analyze(parts, aspect) for j, pt in enumerate(out): if st["parts"][j]["vol"] > .04: pt.pat = sk["pat"] return out
# ------------------------------------------------------------------ entry point from the renderer# parser material names (pydraw/materials.py) -> skinsOLD_MATERIALS = {"wood": "wood", "glass": "glass", "metal": "metal", "gold": "gold", "bronze": "bronze", "stone": "stone", "marble": "marble", "brick": "brick", "ice": "ice", "paper": "paper", "plastic": "plastic", "rust": "rust", "clay": "clay", "chocolate": "chocolate", "neon": "neon", "rainbow": "rainbow", "leather": "leather", "jade": "jade", "cloudstuff": "cloud", "water": "water", "fire": "fire", "sand": "sand", "leafy": "leaves", "fur": "plush"}
def apply_entity(parts, e, col, aspect, trace=None): """Called by plot3d for every placed model whose entity carries a material or an imagination plan.""" from pydraw.registry import CONCEPTS im = e.get("imagine") or {} skin = im.get("skin") if not skin: m = e.get("material") if not m or not isinstance(m, str) or m.startswith(("pattern|", "tint|")): return parts skin = OLD_MATERIALS.get(m) if skin == "plush" and CONCEPTS.get(e["concept"], {}).get("animal"): return parts # rule: "a fluffy dog" is a dog with fur, not a plush toy if not skin: return parts from pydraw.understanding import COLORS c = COLORS.get(e.get("color")) if (e.get("color") and e.get("color_explicit", True)) else None c = im.get("skin_color") or c return skin_parts(parts, skin, c, aspect, trace=trace, word=im.get("skin_word"), kind=im.get("skin_kind"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336"""Mythical creatures as recipes over existing models (pure composition of SDF parts, no new hand-made animals):each recipe names a base body, the donors it borrows from, and the kit operations (head swap, cut, graft wings /horn / tail). See pydraw3d/imagine_kit.py."""import mathimport numpy as np
from . import sdf as Sfrom .models import Part, MODELSfrom .imagine import clipped, moved, analyze, model_of, union, apply_skin, clone, lumfrom .imagine_kit import (head_swap, head_of, facing, wings, horn, curved_horns, antlers, fish_tail, graft_onto, plane_region, back_point, place_piece, sphere_region, _mirror_z)from .models_animals import chain
class _Inst: def __init__(self, word="", k=0): self.word, self.k, self.pose, self.facing, self.count, self.attrs = word, k, None, None, 1, {}
def person(col=None, word="woman", k=1): fn, a = MODELS["person"] return fn(col, _Inst(word, k)), a
def _m(word, col=None): m = model_of(word, col) if not m: raise ValueError("no model for " + word) return m
def upper_body(col=None, word="woman", k=1, cut=.47): """A person from the hips up (the hip point (0, cut, 0) is returned as the attachment).""" pp, a = person(col, word, k) return clipped(pp, plane_region((0, cut, 0), (0, -1, 0)), keep="out"), np.array([0, cut, 0.0])
def horse_like(col, horse_col=None): return _m("horse", col or horse_col)
def recolor(parts, idx, col): out = list(parts) out[idx] = clone(out[idx], color=col) return out
def eagle_head(c, r, f=1, col=(250, 250, 245), beak=(245, 190, 40)): """A feathered raptor head at c (radius r) looking along +x (f=1) / -x: round crown, hooked yellow beak, eyes under a brow.""" from .models_animals import rcone c = np.asarray(c, float) fx = np.array([f, 0, 0.0]) b0 = c + fx * r * .75 + np.array([0, -.05 * r, 0]) b1 = c + fx * r * 1.55 + np.array([0, -.25 * r, 0]) b2 = c + fx * r * 1.45 + np.array([0, -.6 * r, 0]) ec = c + fx * r * .45 + np.array([0, .2 * r, .62 * r])
def head(p): d = S.ellipsoid(p, c.astype(np.float32), np.array([r * 1.05, r * .92, r * .85], np.float32)) d = S.smin(d, S.ellipsoid(p, (c - fx * r * .55 - np.array([0, r * .5, 0])).astype(np.float32), np.array([r * .9, r * .9, r * .8], np.float32)), r * .3) return d * .9 - .006 * S.noise3(p * 40, 2) return [Part(head, col, spec=.15, rough=.8, tex="fur"), Part(lambda p: np.minimum(rcone(p, b0, b1, r * .32, r * .12), rcone(p, b1, b2, r * .12, r * .03)), beak, k=r * .1, spec=.6, rough=.25), Part(lambda p: S.sphere(_mirror_z(p), ec.astype(np.float32), r * .16), (25, 20, 15), spec=1.0, rough=.05), Part(lambda p: S.capsule(_mirror_z(p), ec + np.array([-f * r * .2, r * .2, .02 * r]), ec + np.array([f * r * .25, r * .14, .02 * r]), r * .07), col, k=.0, spec=.15, rough=.8)]
def _raptor_front(body_parts, ba, scale=1.0): st = analyze(body_parts, ba) hc, hr = head_of(st) f = facing(st) or 1 keep = [pt for j, pt in enumerate(body_parts) if j == st["body"] or st["parts"][j]["n"] == 0 or np.linalg.norm(np.asarray(st["parts"][j]["c"]) - hc) > hr * 1.6 or st["parts"][j]["vol"] > .35] body = clipped(keep, sphere_region(hc, hr * 1.0), keep="out") return body + eagle_head(hc + np.array([0, .02, 0]), hr * scale, f), st
# ---------------------------------------------------------------- recipesdef r_griffin(c, inst=None): # rule: griffin = lion body + eagle head + eagle wings lion, la = _m("lion", c or (205, 160, 90)) out, st = _raptor_front(lion, la, 1.0) root = back_point(union(lion), st, .15) - np.array([0, .03, 0]) return out + wings(root, .75, "feather", (120, 82, 50), (70, 50, 35), tilt=1.05, sweep=.55, z0=.08)
def r_hippogriff(c, inst=None): horse, ha = _m("horse", c or (150, 110, 75)) out, st = _raptor_front(horse, ha, .95) root = back_point(union(horse), st, .2) - np.array([0, .03, 0]) return out + wings(root, .75, "feather", (120, 82, 50), (70, 50, 35), z0=.08)
def _unicorn(c, horn_on=True, wing_on=False): hp, ha = _m("horse", c or (246, 244, 248)) st = analyze(hp, ha) # rule: a unicorn's mane and tail are pastel; the horn is a golden spiral on the forehead out = recolor(hp, 1, (215, 150, 235)) out = recolor(out, 2, (170, 150, 240)) hc, hr = head_of(st) f = facing(st) or 1 if horn_on: base = hc + np.array([f * .05, hr * .55, 0]) out += horn(base, (.75 * f, 1, 0), .3, .03) if wing_on: root = back_point(union(hp), st, .35) - np.array([0, .03, 0]) out += wings(root, .7, "feather", (250, 250, 252), (225, 230, 245), z0=.08) return out
def r_unicorn(c, inst=None): return _unicorn(c)
def r_alicorn(c, inst=None): return _unicorn(c, True, True)
def r_pegasus(c, inst=None): return _unicorn(c, False, True)
def r_centaur(c, inst=None): hp, ha = _m("horse", (150, 95, 55)) st = analyze(hp, ha) f = facing(st) or 1 hc, hr = head_of(st) # rule: a centaur = a horse whose head and neck are replaced by a human torso rising from the withers wx = float(st["c"][0]) + .5 * (hc[0] - float(st["c"][0])) wy = .72 body = clipped(hp, plane_region((wx, wy - .1, 0), (f * 1.0, 1.0, 0)), keep="out") body = [pt for j, pt in enumerate(body) if j != 1] # no mane up, hip = upper_body(c or (205, 160, 120), "man", 0, cut=.5) up = recolor(up, 3, (238, 196, 160)) if len(up) > 3 else up return body + place_piece(up, hip, (wx + .02 * f, wy - .14, 0), 1.05, -1.0 * f)
def r_mermaid(c, inst=None): up, hip = upper_body((150, 90, 190), "woman", 1, cut=.47) tail_c = c or (40, 165, 150) tail = fish_tail(hip + np.array([0, .03, 0]), [(.02, -.3, -.02), (.12, -.44, -.04), (.35, -.46, -.02), (.55, -.36, 0), (.66, -.25, 0)], 1.0, .105, tail_c, tuple(np.clip(np.asarray(tail_c) * 1.25, 0, 255))) return up + tail
def r_minotaur(c, inst=None): pp, pa = person(c or (120, 80, 50), "man", 2) bull, ba = _m("bull", (110, 70, 45)) out = head_swap(pp, analyze(pp, pa), bull, analyze(bull, ba), scale_k=1.6, keep_r=1.4) st = analyze(pp, pa) hc, hr = head_of(st) return out + curved_horns(hc + np.array([0, hr * .9, .0]), .17, .022)
def r_sphinx(c, inst=None): lion, la = _m("lion") pp, pa = person((200, 170, 110), "man", 1) out = head_swap(lion, analyze(lion, la), pp, analyze(pp, pa), scale_k=1.15, keep_r=1.6) # rule: the sphinx is a monument: one sandstone material over the whole body, and the striped nemes headdress # (a cap over the head with two lappets down the sides of the face) is what makes it read as the sphinx from .imagine import SKINS sk = dict(SKINS["sand"], eyes="keep") out = apply_skin(out, sk, c or (215, 180, 120), la) st = analyze(lion, la) hc, hr = head_of(st) f = facing(st) or 1 r = hr * 1.05 cap_c = hc + np.array([-f * r * .15, r * .15, 0])
def nemes(p): cap = S.ellipsoid(p, cap_c.astype(np.float32), np.array([r * 1.2, r * 1.15, r * 1.25], np.float32)) cap = np.maximum(cap, -(f * (p[:, 0] - (hc[0] + f * r * .35)))) # open at the face q = _mirror_z(p) lap = S.rbox(q, np.array([hc[0] - f * r * .1, hc[1] - r * .9, r * .95], np.float32), np.array([r * .35, r * 1.0, r * .12], np.float32), r * .06) back = S.rbox(p, np.array([hc[0] - f * r * .7, hc[1] - r * .5, 0], np.float32), np.array([r * .4, r * .8, r * .8], np.float32), r * .2) return np.minimum(np.minimum(cap, lap), back) return out + [Part(nemes, (225, 185, 70), k=.0, spec=.5, rough=.35, pat=("bands", (40, 70, 150), 2.4))]
def r_dragon(c, inst=None): # rule: a western dragon = an upright dinosaur body + bat-like membrane wings + horns dn, da = _m("dinosaur", c or (70, 150, 62)) st = analyze(dn, da) out = graft_onto(dn, da, [("horns", None, None)]) root = back_point(union(dn), st, .1) - np.array([0, .04, 0]) col = tuple(int(v) for v in dn[st["body"]].color) hgt = float(st["hi"][1] - st["lo"][1]) return out + wings(root, .95 * hgt, "membrane", tuple(np.clip(np.asarray(col) * .6, 0, 255)), tuple(np.clip(np.asarray(col) * 1.25 + 25, 0, 255)), tilt=1.1, sweep=.6, z0=.05, facing_=facing(st) or 1)
def r_fairy(c, inst=None): pp, pa = person(c or (235, 140, 190), "girl", 1) return pp + wings(np.array([0, .7, .07]), .42, "fairy", (205, 235, 250), tilt=.6, sweep=.35, z0=.02, facing_=0)
def r_angel(c, inst=None): pp, pa = person(c or (248, 248, 250), "woman", 1) halo = Part(lambda p: S.torus(p, np.array([0, 1.03, 0], np.float32), .06, .009), (255, 215, 90), spec=.6, rough=.2, emit=.7) return pp + [halo] + wings(np.array([0, .72, .07]), .6, "feather", (250, 250, 252), (220, 225, 240), tilt=.8, sweep=.3, z0=.02, facing_=0)
def r_faun(c, inst=None): pp, pa = person(c or (90, 140, 80), "man", 2) st = analyze(pp, pa) fur = (120, 85, 55) out = [clone(pt, color=fur, tex="fur") if (st["parts"][j]["c"][1] < .5 and st["parts"][j]["n"]) else pt for j, pt in enumerate(pp)] hc, hr = head_of(st) return out + curved_horns(hc + np.array([0, hr * .6, 0]), .13, .02, (215, 200, 165), f=0)
def r_manticore(c, inst=None): lion, la = _m("lion", c or (190, 110, 70)) pp, pa = person(None, "man", 3) st = analyze(lion, la) out = head_swap(lion, st, pp, analyze(pp, pa), scale_k=1.2, keep_r=1.6) f = facing(st) or 1 s = np.array([float(st["c"][0]) - f * .55, .6, 0]) pts = [s, s + np.array([-.15 * f, .25, 0]), s + np.array([0, .5, 0]), s + np.array([.2 * f, .55, 0])] tail = Part(lambda p: chain(p, pts, [.04, .035, .028, .02]), (60, 40, 35), k=.03, spec=.5, rough=.3) from .models_animals import rcone tip = pts[-1] + np.array([.1 * f, -.1, 0]) sting = Part(lambda p: rcone(p, pts[-1], tip, .035, .004), (30, 25, 25), spec=.6, rough=.2) return out + [tail, sting]
def r_jackalope(c, inst=None): rb, ra = _m("rabbit", c) return graft_onto(rb, ra, [("antlers", None, None)])
def r_cerberus(c, inst=None): dg, da = _m("dog", c or (45, 40, 40)) return graft_onto(dg, da, [("heads", None, 3)])
def r_hydra(c, inst=None): lz, la = _m("komodo dragon", c or (60, 120, 90)) return graft_onto(lz, la, [("heads", None, 5)])
def r_werewolf(c, inst=None): pp, pa = person((90, 80, 75), "man", 2) wolf, wa = _m("wolf", c) fur = apply_skin(pp, "fur", tuple(int(v) for v in wolf[analyze(wolf, wa)["body"]].color), pa) return head_swap(fur, analyze(pp, pa), wolf, analyze(wolf, wa), scale_k=1.3, keep_r=1.2)
def r_harpy(c, inst=None): eg, ea = _m("eagle", c) pp, pa = person(None, "woman", 1) return head_swap(eg, analyze(eg, ea), pp, analyze(pp, pa), scale_k=1.25, keep_r=1.7)
def r_phoenix(c, inst=None): # rule: phoenix = a raptor with spread wings and a long trailing tail, all made of fire eg, ea = _m("eagle") st = analyze(eg, ea) f = facing(st) or 1 root = back_point(union(eg), st, .1) out = eg + wings(root, .8, "feather", (240, 120, 40), z0=.1, tilt=.9, sweep=.6, facing_=f) s0 = np.array([float(st["c"][0]) - f * .3, .35, 0]) pts = [s0, s0 + np.array([-f * .3, -.05, 0]), s0 + np.array([-f * .6, .05, .05]), s0 + np.array([-f * .85, -.05, -.05])] out.append(Part(lambda p: chain(p, pts, [.06, .07, .06, .02]), (240, 120, 40), k=.04, spec=.1, rough=.8)) return apply_skin(out, "fire", None, ea)
def r_kraken(c, inst=None): return _m("octopus", c or (150, 50, 60))[0]
def r_mercat(c, inst=None): cat, ca = _m("cat", c) st = analyze(cat, ca) top = clipped(cat, plane_region((0, .32, 0), (0, -1, 0)), keep="out") return top + fish_tail(np.array([float(st["c"][0]) - .05, .36, 0]), [(-.05, -.25, 0), (-.3, -.33, 0), (-.55, -.2, 0)], 1.0, .12, (40, 165, 150), (70, 200, 180))
def r_seaserpent(c, inst=None): return _m("snake", c or (40, 120, 110))[0]
def r_naga(c, inst=None): up, hip = upper_body((200, 170, 60), "woman", 1, cut=.47) tc = c or (60, 140, 70) pts = [hip, hip + np.array([.0, -.3, 0]), hip + np.array([.2, -.45, .05]), hip + np.array([.45, -.43, -.05]), hip + np.array([.4, -.42, -.3]), hip + np.array([.1, -.44, -.3])] tail = Part(lambda p: chain(p, pts, [.1, .09, .075, .06, .045, .02]), tc, k=.03, spec=.5, rough=.3, pat=("scales", (0, 0, 0), 1.6)) return up + [tail]
def r_chimera(c, inst=None): lion, la = _m("lion", c) out = graft_onto(lion, la, [("horns", None, None)]) st = analyze(lion, la) f = facing(st) or 1 s = np.array([float(st["c"][0]) - f * .55, .55, 0]) pts = [s, s + np.array([-.15 * f, .1, 0]), s + np.array([-.25 * f, .3, 0]), s + np.array([-.15 * f, .42, 0])] snake = Part(lambda p: chain(p, pts, [.05, .045, .04, .045]), (70, 120, 60), k=.03, spec=.5, rough=.3, pat=("scales", (0, 0, 0), 1.6)) return out + [snake]
def _r(build, base, **facts): facts.setdefault("animal", True) return dict(build=build, base=base, facts=facts)
RECIPES = { "griffin": _r(r_griffin, "lion", height=2.0, setting="mountains", default_color=None), "hippogriff": _r(r_hippogriff, "horse", height=2.2), "unicorn": _r(r_unicorn, "horse", height=1.9, default_color=(246, 244, 248)), "alicorn": _r(r_alicorn, "horse", height=2.2, default_color=(246, 244, 248)), "pegasus": _r(r_pegasus, "horse", height=2.2, default_color=(246, 244, 248)), "centaur": _r(r_centaur, "horse", height=2.4, default_color=None), "mermaid": _r(r_mermaid, "person", height=1.5, setting="beach", default_color=None), "minotaur": _r(r_minotaur, "person", height=2.4, default_color=None), "sphinx": _r(r_sphinx, "lion", height=6.0, setting="desert", animal=False, default_color=None), "dragon": _r(r_dragon, "dragon", height=3.0, default_color=(70, 150, 62)), "fairy": _r(r_fairy, "person", height=.6, default_color=None), "angel": _r(r_angel, "person", height=1.9, default_color=None), "faun": _r(r_faun, "person", height=1.7, setting="forest", default_color=None), "manticore": _r(r_manticore, "lion", height=1.6, default_color=None), "chimera": _r(r_chimera, "lion", height=1.6, default_color=None), "jackalope": _r(r_jackalope, "rabbit", height=.5, default_color=None), "cerberus": _r(r_cerberus, "dog", height=1.4, default_color=None), "werewolf": _r(r_werewolf, "person", height=2.0, default_color=None), "harpy": _r(r_harpy, "bird", height=1.4, default_color=None), "phoenix": _r(r_phoenix, "bird", height=1.2, flying=True, default_color=None), "kraken": _r(r_kraken, "octopus", height=6.0, setting="water", default_color=None), "mercat": _r(r_mercat, "cat", height=.5, setting="beach", default_color=None), "seaserpent": _r(r_seaserpent, "snake", height=2.0, setting="water", default_color=None), "naga": _r(r_naga, "person", height=1.8, default_color=None),}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737"""Imagination kit (3D): morphs, creature parts (wings, horns, legs, tails), grafts, head swaps, things grown on top,floating islands, upside-down / melting transforms. Works on any model's SDF parts; see pydraw3d/imagine.py."""import mathimport numpy as np
from . import sdf as Sfrom .models import Part, MODELSfrom .imagine import (clone, union, moved, clipped, lum, analyze, probe, top_at, model_of, _lin, _thin_glow, thin_glow_tex, geo_melt, apply_skin)from .models_animals import chain, rcone
# ------------------------------------------------------------------ normalisationdef bbox(parts, R=2.2, n=60): st = analyze(parts, 1.0, n=n, bounds=((-R, R), (-1.2, 2.6), (-R, R))) return st["lo"], st["hi"]
def normalize(parts): """Transform (for moved()) that puts the composite's base on y=0, height 1, centred on x=z=0; and its aspect.""" lo, hi = bbox(parts) h = max(float(hi[1] - lo[1]), 1e-3) k = 1.0 / h off = -np.array([(lo[0] + hi[0]) / 2, lo[1], (lo[2] + hi[2]) / 2]) * k xf = dict(offset=tuple(float(v) for v in off), scale=k) return moved(parts, **xf), float((hi[0] - lo[0]) * k), xf
def facing(st): """+1 / -1: a side-view model looks along +x / -x; 0: it faces the camera (-z).""" e = st["eyes"] if e is None: return 1 dx = float(e[:, 0].mean() - st["c"][0]) return 0 if abs(dx) < .12 else (1 if dx > 0 else -1)
def head_of(st): """(centre, radius) of the head, from the eyes; None when the model has no eyes.""" e = st["eyes"] if e is None: return None f = facing(st) c = e.mean(0).copy() h = float(st["hi"][1] - st["lo"][1]) c[2] = 0.0 if f == 0: r = .11 * h c[1] -= .01 * h else: r = .15 * h c[0] -= f * .07 * h c[1] -= .02 * h return c, r
def surface_toward(fn, center, target, R=3.0): d = np.asarray(target, float) - np.asarray(center, float) nd = np.linalg.norm(d) if nd < 1e-6: d, nd = np.array([0, 1.0, 0]), 1.0 d = d / nd return probe(fn, np.asarray(center) + d * R, -d, 2 * R)
def _mirror_z(p): q = p.copy() q[:, 2] = np.abs(q[:, 2]) return q
def place_piece(parts, src_c, dst_c, scale=1.0, yaw=0.0): """Move parts so that src_c lands on dst_c, scaled about src_c and turned about the vertical through it.""" src_c = np.asarray(src_c, float) p0 = moved(parts, offset=tuple(-src_c), scale=1.0) p1 = moved(p0, scale=scale, yaw=yaw) return moved(p1, offset=tuple(np.asarray(dst_c, float)))
def sphere_region(c, r): c = np.asarray(c, np.float32) return lambda p: S.sphere(p, c, r)
def plane_region(point, normal): """Half-space: negative (inside) on the side the normal points to.""" n = np.asarray(normal, float) n = n / np.linalg.norm(n) pnt = np.asarray(point, float) return lambda p: -((p - pnt) @ n).astype(np.float32)
def back_point(fn, st, frac=.25): """A point on the top of the back, `frac` of the way from the centre toward the head.""" f = facing(st) cx = float(st["c"][0]) hc = head_of(st) hx = float(hc[0][0]) if hc and f else cx + .4 * (f or 0) x = cx + frac * (hx - cx) y = top_at(fn, x, 0.0) return np.array([x, y if y is not None else float(st["hi"][1]) * .8, 0.0])
# ------------------------------------------------------------------ morph: X's function on Y's bodydef morph_parts(x, y, col): mx = model_of(x, col) my = model_of(y) if not mx or not my: raise ValueError("no model for %s or %s" % (x, y)) px, ax = mx py, ay = my sx, sy = analyze(px, ax), analyze(py, ay) bx = sx["body"] body_x = px[bx] blo, bhi = np.array(sx["lo"]), np.array(sx["hi"]) # rule: Y is scaled uniformly to X's overall height (not wider than 1.4x X) and stands where X stood hy = float(sy["hi"][1] - sy["lo"][1]) k = float(bhi[1] - blo[1]) / max(hy, 1e-3) wy = float(sy["hi"][0] - sy["lo"][0]) k = min(k, 1.4 * float(bhi[0] - blo[0]) / max(wy, 1e-3)) cy = np.array([(sy["lo"][0] + sy["hi"][0]) / 2, sy["lo"][1], 0]) tgt = np.array([(blo[0] + bhi[0]) / 2, max(0.0, blo[1]), 0]) yparts = moved(py, offset=tuple(tgt - cy * k), scale=k) # rule: the new body takes X's finish (a pumpkin teapot is glossy like porcelain) xcol = np.asarray(body_x.color, float) glossy = body_x.spec > .4 out = [clone(pt, spec=max(pt.spec, body_x.spec) if glossy else pt.spec, rough=min(pt.rough, body_x.rough) if glossy else pt.rough) for pt in yparts] ybody = out[sy["body"]].fn cX = np.asarray(sx["parts"][bx]["c"], float) lo2, hi2 = bbox(out) cY = (lo2 + hi2) / 2 newc = np.asarray(out[sy["body"]].color, float) for j, pt in enumerate(px): if j == bx: continue stp = sx["parts"][j] if stp["n"] == 0 or stp["vol"] > .15: continue # rule: big structural parts (a house's roof) give way to Y's form; small function parts stay a = np.asarray(stp["c"], float) # rule: a function part keeps its place RELATIVE to the outline (a door low on the front, wheels at the # bottom corners, a chimney on top): the point where it touches X maps to the same relative position in # Y's box, then onto Y's surface along X's surface normal there n = _grad(body_x.fn, a) sX = probe(body_x.fn, a + n * 2.5, -n, 5.0) if sX is None: sX = surface_toward(body_x.fn, cX, a) if sX is None: continue u = (sX - sx["lo"]) / np.maximum(sx["hi"] - sx["lo"], 1e-3) tgt_ = lo2 + u * (hi2 - lo2) sY = probe(ybody, tgt_ + n * 2.5, -n, 5.0) if sY is None: sY = surface_toward(ybody, cY, tgt_) if sY is None: continue off = sY - sX # rule: then the part settles onto Y's surface (no floating chimneys, no buried doors) pts = _inside_pts(pt.fn, stp) if len(pts): for _ in range(3): gap = float(np.min(ybody((pts + off).astype(np.float32)))) if abs(gap) < .006: break off = off - n * (gap - .004) c = pt.color if np.abs(np.asarray(pt.color, float) - xcol).sum() < 30: c = tuple(newc) # rule: parts in the body's own material take the new body's colour (spout, lid) out += [clone(q, color=c) for q in moved([pt], offset=tuple(off))] return out
def _grad(fn, a, e=2e-3): a = np.asarray(a, np.float32) k = np.eye(3, dtype=np.float32) * e g = np.array([float(fn((a + k[i])[None])[0] - fn((a - k[i])[None])[0]) for i in range(3)]) n = np.linalg.norm(g) return g / n if n > 1e-9 else np.array([0, 0, -1.0])
def _inside_pts(fn, stp, n=8): lo, hi = np.asarray(stp["lo"]), np.asarray(stp["hi"]) g = np.stack(np.meshgrid(*[np.linspace(lo[i], hi[i], n) for i in range(3)], indexing="ij"), -1).reshape(-1, 3).astype(np.float32) return g[fn(g) < .004]
# ------------------------------------------------------------------ creature parts kitdef _orient(p, root, tilt, sweep): """Wing coordinates: u along the span (rising by `tilt` and sweeping back by `sweep`), v along the chord, w through the membrane.""" q = p - np.asarray(root, np.float32) span = np.array([-math.sin(sweep) * math.cos(tilt), math.sin(tilt), math.cos(sweep) * math.cos(tilt)]) chord = np.array([math.cos(sweep), 0, math.sin(sweep)]) chord = chord - span * (chord @ span) chord /= np.linalg.norm(chord) nrm = np.cross(span, chord) return q @ span, q @ chord, q @ nrm
FEATHER = [(0, .12), (.3, .2), (.62, .2), (.9, .1), (1.0, -.02), (.93, -.14), (.85, -.08), (.8, -.24), (.7, -.16), (.64, -.33), (.52, -.24), (.46, -.38), (.34, -.28), (.27, -.38), (.16, -.27), (.08, -.3), (0, -.14)]MEMBRANE = [(0, .1), (.45, .3), (1.0, .22), (.72, .02), (.95, -.25), (.6, -.12), (.62, -.48), (.33, -.22), (.18, -.45), (0, -.14)]BUTTER_F = [(0, .05), (.25, .3), (.7, .55), (1.0, .55), (1.0, .25), (.6, .02), (0, -.02)]BUTTER_H = [(0, -.02), (.45, -.05), (.75, -.25), (.7, -.55), (.4, -.6), (.1, -.3)]
def wings(root, span, kind="feather", color=(245, 245, 245), color2=None, tilt=1.0, sweep=.5, z0=.06, facing_=1): """Two wings (mirrored in z) rooted at `root` on the back. kind: feather (birds, angels, pegasus), membrane (bats, dragons), butterfly (insects), fairy (glassy insect wings). facing_: the way the body looks (+1 = +x).""" root = np.asarray(root, np.float32) if facing_ == 0: # rule: a body facing the camera wears its wings on its back (+z), spread left and right side = wings(root, span, kind, color, color2, tilt, sweep, z0, 1) return place_piece(side, root, root, 1.0, math.pi / 2) th = .012 * span sw = sweep * (1 if facing_ >= 0 else -1) sgn = 1 if facing_ >= 0 else -1
def flat(verts, sc=1.0): vv = [(u * span * sc, v * span * sc * sgn) for u, v in verts]
def f(p): q = _mirror_z(p) u, v, w = _orient(q, root + np.array([0, 0, z0], np.float32), tilt, sw) d2 = S.polygon2d(u, v, vv) ww = np.stack([d2, np.abs(w) - th], -1) return (np.minimum(np.maximum(ww[:, 0], ww[:, 1]), 0) + S.length(np.maximum(ww, 0)) - th * .5) * .9 return f parts = [] if kind == "feather": c2 = color2 or tuple(np.clip(np.asarray(color, float) * .8, 0, 255)) parts.append(Part(flat(FEATHER), color, spec=.15, rough=.75, tex=_feather_tex(color, c2, span, root))) tipdir = np.array([-math.sin(sw) * math.cos(tilt), math.sin(tilt), math.cos(sw) * math.cos(tilt)]) r_end = root + np.array([0, 0, z0]) + tipdir * span * .3 parts.append(Part(lambda p: S.capsule(_mirror_z(p), root + np.array([0, 0, z0 * .5], np.float32), r_end, .04 * span), color, k=.03 * span, spec=.15, rough=.75)) elif kind == "membrane": f = flat(MEMBRANE) mc = color2 or tuple(np.clip(np.asarray(color, float) * 1.2 + 10, 0, 255)) parts.append(Part(f, mc, spec=.2, rough=.6, tex=thin_glow_tex(f, .5))) vv = [(u * span, v * span * sgn) for u, v in MEMBRANE]
def bones(p): q = _mirror_z(p) u, v, w = _orient(q, root + np.array([0, 0, z0], np.float32), tilt, sw) a = np.stack([u, v], -1) d = None for tip in (vv[2], vv[4], vv[6], vv[8], vv[1]): b = np.array(tip) h = np.clip((a @ b) / (b @ b), 0, 1) e = np.sqrt(((a - h[:, None] * b) ** 2).sum(-1) + w * w) - .02 * span * (1.3 - h) d = e if d is None else np.minimum(d, e) return d parts.append(Part(bones, color, k=.01, spec=.25, rough=.5)) elif kind == "butterfly": c2 = color2 or (30, 25, 25) tex = _butterfly_tex(color, c2, span, root) parts.append(Part(flat(BUTTER_F), color, spec=.3, rough=.4, tex=tex)) parts.append(Part(flat(BUTTER_H, .95), color, spec=.3, rough=.4, tex=tex)) elif kind == "fairy": g = color or (200, 230, 250) f1, f2 = flat(BUTTER_F), flat(BUTTER_H, .9) parts.append(Part(f1, g, spec=1.0, rough=.05, emit=.4, tex=thin_glow_tex(f1, 1.0))) parts.append(Part(f2, g, spec=1.0, rough=.05, emit=.4, tex=thin_glow_tex(f2, 1.0))) return parts
def _feather_tex(c1, c2, span, root): root = np.asarray(root, float)
def t(q, base, seed): # rule: feathers = rows of quills; the outer half (primaries) is a shade darker r = S.length((q - root).astype(np.float32)) stripe = .5 + .5 * np.sin(np.arctan2(q[:, 1] - root[1], np.abs(q[:, 2]) - root[2]) * 60) outer = np.clip((r / span - .55) * 5, 0, 1) c = _lin(c1)[None, :] * (1 - outer[:, None]) + _lin(c2)[None, :] * outer[:, None] return c * (.85 + .2 * stripe[:, None]) return t
def _butterfly_tex(c1, c2, span, root): root = np.asarray(root, float)
def t(q, base, seed): # rule: butterfly wings: a bright field, dark veins, a dark border with a row of pale spots r = S.length((q - root).astype(np.float32)) / span f1, f2, cid = S.worley((q * 7 / max(span, .1)).astype(np.float32), seed) c = _lin(c1)[None, :] * np.ones((len(q), 1)) * (.9 + .2 * S.noise3(q * 20, seed)[:, None]) vein = (f2 - f1) < .05 c[vein] = _lin(c2) border = r > .78 c[border] = _lin(c2) spots = border & (S.worley((q * 28 / max(span, .1)).astype(np.float32), seed + 3)[0] < .3) c[spots] = _lin((250, 250, 245)) return c return t
def horn(base, direction, length, r0, color=(240, 205, 110), spiral=True): base = np.asarray(base, np.float32) d = np.asarray(direction, float) d = d / np.linalg.norm(d) tip = base + d * length tex = None if spiral: def tex(q, b, seed): a = (q - base) @ d s = np.sin(a / length * 2 * math.pi * 5 + np.arctan2(q[:, 2] - base[2], q[:, 0] - base[0])) return _lin(color)[None, :] * (.8 + .25 * s[:, None]) return [Part(lambda p: rcone(p, base, tip, r0, r0 * .08), color, k=.01, spec=.6, rough=.25, tex=tex)]
def curved_horns(base, length, r0, color=(235, 225, 200), f=1): """A pair of bull horns: out sideways, then up and a little forward (mirrored in z).""" b = np.asarray(base, float) pts = [b + np.array([0, 0, .03]), b + np.array([.0, length * .1, length * .55]), b + np.array([.05 * f, length * .45, length * .85]), b + np.array([.1 * f, length * .85, length * .8])] rs = [r0, r0 * .75, r0 * .45, r0 * .12] return [Part(lambda p: chain(_mirror_z(p), pts, rs), color, k=.01, spec=.45, rough=.3)]
def antlers(base, size, color=(140, 105, 70), f=1): b = np.asarray(base, float) beam = [b, b + size * np.array([-.2 * f, .5, .25]), b + size * np.array([-.15 * f, 1.0, .45]), b + size * np.array([.1 * f, 1.35, .55])] tines = [(beam[1], beam[1] + size * np.array([.35 * f, .35, .02])), (beam[2], beam[2] + size * np.array([.3 * f, .4, -.05])), (beam[2], beam[2] + size * np.array([-.3 * f, .45, .05]))]
def fn(p): q = _mirror_z(p) d = chain(q, beam, [size * .07, size * .06, size * .05, size * .035]) for a, t in tines: d = np.minimum(d, rcone(q, a, t, size * .045, size * .02)) return d return [Part(fn, color, k=.01, spec=.2, rough=.6, tex="bark")]
def legs(attach_y, xs, z, length, kind="human", color=(238, 196, 160), shoe=(45, 40, 38)): """Legs from attach_y down to y=0. kind: human (bare legs + shoes), bird (thin scaly, three toes), animal (furry, hoofed), insect (thin bent).""" parts = [] xs = list(xs) if kind == "human": def f(p): q = _mirror_z(p) return np.minimum.reduce([chain(q, [(x, attach_y, z), (x + .01, attach_y * .5, z), (x, .06, z)], [length * .13, length * .1, length * .075]) for x in xs])
def s(p): q = _mirror_z(p) return np.minimum.reduce([S.ellipsoid(q, np.array([x + length * .06, length * .05, z], np.float32), np.array([length * .13, length * .06, length * .08], np.float32)) for x in xs]) parts += [Part(f, color, k=.02, spec=.25, rough=.5), Part(s, shoe, spec=.5, rough=.3)] elif kind == "bird": def f(p): q = _mirror_z(p) d = None for x in xs: e = chain(q, [(x, attach_y, z), (x - length * .12, attach_y * .5, z), (x, length * .04, z)], [length * .06, length * .035, length * .03]) for ang in (-.6, 0, .6): e = np.minimum(e, S.capsule(q, (x, .02, z), (x + math.cos(ang) * length * .22, .015, z + math.sin(ang) * length * .22), length * .022)) d = e if d is None else np.minimum(d, e) return d parts.append(Part(f, color, k=.01, spec=.35, rough=.4)) elif kind == "insect": def f(p): q = _mirror_z(p) return np.minimum.reduce([chain(q, [(x, attach_y, z * .5), (x + .02, attach_y + length * .25, z + length * .35), (x + .04, 0.01, z + length * .6)], [length * .03, length * .025, length * .015]) for x in xs]) parts.append(Part(f, color, spec=.4, rough=.3)) else: # animal def f(p): q = _mirror_z(p) return np.minimum.reduce([chain(q, [(x, attach_y + length * .15, z), (x + .01, attach_y * .5, z), (x, .05, z)], [length * .14, length * .1, length * .09]) for x in xs]) parts.append(Part(f, color, k=.02, spec=.12, rough=.8, tex="fur")) parts.append(Part(lambda p: np.minimum.reduce([S.cylinder(_mirror_z(p), np.array([x, .03, z], np.float32), length * .1, .03, .01) for x in xs]), (45, 38, 35), spec=.5, rough=.3)) return parts
def fish_tail(start, rel_pts, length, r0, color=(40, 160, 150), fluke=(70, 200, 180)): """A tapering scaly tail from `start` through points (relative, in units of length), ending in a two-lobed fluke.""" pts = [np.asarray(start, float)] + [np.asarray(start, float) + np.asarray(dv, float) * length for dv in rel_pts] rs = [r0 * (1 - .75 * i / (len(pts) - 1)) for i in range(len(pts))] end, pre = pts[-1], pts[-2] dd = (end - pre) / max(np.linalg.norm(end - pre), 1e-6) side = np.cross(dd, np.array([0, 0, 1.0])) side /= max(np.linalg.norm(side), 1e-6)
def fl(p): q = p - end a = q @ dd b = q @ side c = q[:, 2] out = None for sg in (-1, 1): loc = np.stack([a - r0 * .3, b - sg * r0 * .9 - a * 0, c], -1).astype(np.float32) rot = .6 * sg ca, sa = math.cos(rot), math.sin(rot) loc2 = np.stack([ca * loc[:, 0] - sa * loc[:, 1], sa * loc[:, 0] + ca * loc[:, 1], loc[:, 2]], -1) e = S.ellipsoid(loc2, np.zeros(3, np.float32), np.array([r0 * 1.3, r0 * .5, r0 * .12], np.float32)) out = e if out is None else np.minimum(out, e) return out return [Part(lambda p: chain(p, pts, rs), color, k=.03, spec=.6, rough=.25, pat=("scales", (0, 0, 0), 1.6)), Part(fl, fluke, k=.03, spec=.5, rough=.3)]
def head_swap(px, stx, donor_parts, std, scale_k=1.0, yaw=None, keep_r=1.45): """Remove X's head (a sphere around its eyes) and put the donor's head there, turned to look where X looked.""" hx, hd = head_of(stx), head_of(std) if hx is None: return px whole = hd is None if whole: # rule (Magritte): a donor without eyes (an apple, a lamp, a fish bowl) becomes the whole head lo, hi = std["lo"], std["hi"] cd, rd = (lo + hi) / 2, .5 * float(max(hi[1] - lo[1], .5 * (hi[0] - lo[0]))) keep_r = 9.0 else: cd, rd = hd cx, rx = hx # rule: small parts that belonged to the old head (eyes, ears, mane ruff, horns) go with it keep = [pt for j, pt in enumerate(px) if j == stx["body"] or stx["parts"][j]["n"] == 0 or np.linalg.norm(np.asarray(stx["parts"][j]["c"]) - cx) > rx * 1.6 or stx["parts"][j]["vol"] > .35] body = clipped(keep, sphere_region(cx, rx * 1.05), keep="out") fx = facing(stx) fd = facing(std) if not whole else fx ang = {1: 0.0, -1: math.pi, 0: -math.pi / 2} yw = (ang[fx] - ang[fd]) if yaw is None else yaw head = clipped(donor_parts, sphere_region(cd, rd * keep_r), keep="in") k = scale_k * rx / max(rd, 1e-3) * 1.1 return body + place_piece(head, cd, cx, k, -yw)
# ------------------------------------------------------------------ grafts ("X with Y wings / legs / horn ...")def _family(word): from pydraw.registry import CONCEPTS fam = (CONCEPTS.get(word, {}).get("open_vocab") or {}).get("family") return fam or getattr(MODELS.get(word, (None,))[0], "family", None)
def _wing_kind(donor): if not donor: return "feather" fam = _family(donor) if donor in ("fairy", "dragonfly", "bee", "fly", "wasp", "mosquito"): return "fairy" if donor in ("butterfly", "moth") or fam == "arthropod": return "butterfly" if donor in ("bat", "dragon") or fam in ("bat", "dinosaur", "lizard"): return "membrane" return "feather"
def graft_parts(x, grafts, col): mx = model_of(x, col) if not mx: raise ValueError("no model for " + x) px, ax = mx return graft_onto(px, ax, grafts)
def graft_onto(px, ax, grafts): st = analyze(px, ax) fn = union(px) out = list(px) hgt = float(st["hi"][1] - st["lo"][1]) width = float(st["hi"][0] - st["lo"][0]) f = facing(st) lift = 0.0 for part, donor, cnt in grafts: dm = model_of(donor) if donor else None dcol = None if dm: dst = analyze(dm[0], dm[1]) dcol = tuple(int(v) for v in dm[0][dst["body"]].color) if part == "wings": kind = _wing_kind(donor) sweep_ = .5 root = back_point(fn, st, .3) + np.array([0, lift - .03 * hgt, 0]) if width < 1.1 * hgt and f != 0: # rule: an upright / sitting animal wears its wings on its upper back, behind the head (probe the # body horizontally from behind at shoulder height) hit = probe(fn, (float(st["c"][0]) - f * 2.5, .62 * hgt + float(st["lo"][1]), 0), (f, 0, 0), 5.0) if hit is not None: root = np.asarray(hit) + np.array([f * .04 * hgt, lift, 0]) sweep_ = .95 span = .6 * max(hgt, .45 * width) colw = dcol if dcol else (248, 248, 250) c2 = None if kind == "butterfly": c2 = (30, 25, 25) colw = dcol if (dcol and lum(dcol) > 60) else (240, 140, 40) if kind == "membrane" and not dcol: colw = (90, 70, 60) out += wings(root, span, kind, colw, c2, sweep=sweep_, z0=max(.03, float(st["hi"][2]) * .3), facing_=f or 1) elif part == "legs": kind, lc = "human", (238, 196, 160) if donor: fam = _family(donor) from pydraw.registry import CONCEPTS if donor in ("chicken", "duck", "bird", "rooster", "ostrich", "flamingo", "hen", "goose") or fam == "bird": kind, lc = "bird", (240, 165, 50) elif fam == "arthropod" or donor in ("spider", "ant", "insect"): kind, lc = "insect", dcol or (40, 35, 35) elif CONCEPTS.get(donor, {}).get("animal") and donor != "person": kind, lc = "animal", dcol L = .55 * hgt lift_l = L * .85 cx = float(st["c"][0]) xs = [cx - .18 * width, cx + .18 * width] if kind == "insect": xs = [cx - .25 * width, cx, cx + .25 * width] if kind == "animal": xs = [cx - .3 * width, cx + .3 * width] zz = max(.05, float(st["hi"][2]) * .45) ay = float(st["lo"][1]) + .12 * hgt out = moved(out, offset=(0, lift_l, 0)) lift += lift_l out += legs(ay + lift, xs, zz, ay + lift, kind, lc) elif part in ("horn", "horns", "antlers"): hd = head_of(st) hc, hr = hd if hd else (np.array([float(st["hi"][0]) * .8, float(st["hi"][1]) * .9, 0]), .12 * hgt) top = top_at(fn, float(hc[0]), 0.0) ty = min(top, float(hc[1] + hr)) if top is not None else float(hc[1] + hr * .8) b = np.array([hc[0] + .03 * hgt * (f or 0), ty - .015 * hgt + lift, 0]) if part == "horn": out += horn(b, (.5 * (f or 0), 1, 0 if f else -.3), .32 * hgt, .035 * hgt) elif part == "horns": out += curved_horns(b - np.array([0, .02 * hgt, 0]), .22 * hgt, .03 * hgt, f=f or 1) else: out += antlers(b + np.array([0, 0, .03]), .25 * hgt, f=f or 1) elif part == "tail": fs = f or 1 rear = np.array([float(st["c"][0]) - fs * width, float(st["c"][1]), 0]) s = surface_toward(fn, st["c"], rear) s = (rear * .5 if s is None else s) + np.array([0, lift, 0]) if donor and (_family(donor) == "fish" or donor in ("fish", "mermaid", "shark", "goldfish")): tc = dcol or (240, 150, 40) out += fish_tail(s, [(-fs * .5, -.15, 0), (-fs * .9, -.1, 0), (-fs * 1.2, .1, 0)], .35 * hgt, .08 * hgt, tc, tc) else: tc = dcol or tuple(px[st["body"]].color) pts = [s, s + np.array([-fs * .2, .1, 0]) * hgt, s + np.array([-fs * .35, .3, 0]) * hgt] out.append(Part(lambda p, _p=pts: chain(p, _p, [.04 * hgt, .03 * hgt, .02 * hgt]), tc, k=.02, spec=.1, rough=.8, tex="fur")) elif part == "fins": top = back_point(fn, st, 0.0) + np.array([0, lift, 0]) fs = f or 1 vv = [(-.15 * hgt * fs, -.03), (.12 * hgt * fs, -.03), (-.15 * hgt * fs, .28 * hgt)] out.append(Part(lambda p, _t=top, _v=vv: S.extrude2d(p, _v, .015 * hgt, c=tuple(_t)), dcol or (110, 125, 150), k=.02, spec=.4, rough=.3)) elif part == "tentacles": L = .5 * hgt lt = L * .6 out = moved(out, offset=(0, lt, 0)) lift += lt tc = dcol or (200, 90, 120) ends = [] for k in range(6): a = k / 6 * 2 * math.pi + .3 r = .22 * width c0 = np.array([float(st["c"][0]) + .5 * r * math.cos(a), float(st["lo"][1]) + lift + .05, .5 * r * math.sin(a)]) ends.append([c0, c0 + np.array([r * math.cos(a), -lt * .7, r * math.sin(a)]), c0 + np.array([1.6 * r * math.cos(a), -lift + .02, 1.6 * r * math.sin(a)])]) out.append(Part(lambda p, _e=ends: np.minimum.reduce([chain(p, e, [.05 * hgt, .035 * hgt, .015 * hgt]) for e in _e]), tc, k=.03, spec=.5, rough=.3)) elif part == "head" and dm: out = head_swap(out, analyze(out, ax), dm[0], analyze(dm[0], dm[1])) elif part == "heads": hd = head_of(st) if hd: hc, hr = hd hc = hc + np.array([0, lift, 0]) head = clipped(out, sphere_region(hc, hr * 1.35), keep="in") n_ = int(cnt or 2) for k in range(n_ - 1): side = (k // 2 + 1) * (1 if k % 2 == 0 else -1) out += place_piece(head, hc, hc + np.array([-.08 * (f or 0) * abs(side) * hgt, .05 * abs(side) * hgt, side * hr * 2.3]), .95, -side * .5) elif part == "trunk": hd = head_of(st) if hd: hc, hr = hd d = np.array([f, 0, 0]) if f else np.array([0, 0, -1.0]) a = hc + d * hr * .8 + np.array([0, lift, 0]) pts = [a, a + d * hr * .8 - np.array([0, hr * .6, 0]), a + d * hr * 1.0 - np.array([0, hr * 1.7, 0])] out.append(Part(lambda p, _p=pts: chain(p, _p, [hr * .35, hr * .25, hr * .17]), tuple(px[st["body"]].color), k=.03, spec=.15, rough=.7)) elif part == "arms": c = st["c"] + np.array([0, lift, 0]) pts = [np.array([c[0], c[1] + .1 * hgt, .1 * hgt]), np.array([c[0] + .1 * hgt, c[1], .3 * hgt]), np.array([c[0] + .15 * hgt, c[1] - .2 * hgt, .35 * hgt])] out.append(Part(lambda p, _p=pts: chain(_mirror_z(p), _p, [.04 * hgt, .035 * hgt, .03 * hgt]), (238, 196, 160), k=.02, spec=.25, rough=.5)) elif part == "mane": pass return out
# ------------------------------------------------------------------ things grown on topdef _cluster(items): """items: [(word, x, z, scale, colour)] -> parts, each model standing at (x, 0, z) with the given height.""" out = [] for w, x, z, s, c in items: m = model_of(w, c) if not m: continue out += moved(m[0], offset=(x, 0, z), scale=s) return out
def top_model(kind): """A small composition to put on a back / roof: garden, forest, village, city, meadow, mushrooms, or any noun.""" if kind == "garden": return _cluster([("tree", 0, .05, .75, None), ("bush", -.45, -.1, .35, None), ("bush", .42, -.05, .3, None), ("tulip", -.2, -.3, .2, (230, 60, 80)), ("daisy", .2, -.3, .18, None), ("sunflower", .55, .15, .35, None), ("tulip", -.6, .2, .2, (240, 200, 60))]) if kind == "forest": return _cluster([("pine", -.35, .1, .7, None), ("tree", .05, .2, .85, None), ("pine", .4, 0, .6, None), ("tree", -.1, -.25, .5, None), ("pine", .25, -.3, .45, None)]) if kind == "village": return _cluster([("house", -.3, .1, .45, None), ("house", .3, .05, .38, None), ("tree", 0, .35, .55, None), ("church", .05, -.2, .5, None)]) if kind == "city": return _cluster([("skyscraper", -.25, .1, .9, None), ("skyscraper", .1, .2, 1.0, None), ("building", .35, -.05, .5, None), ("building", -.45, -.1, .45, None), ("skyscraper", .15, -.2, .7, None)]) if kind == "meadow": return _cluster([("bush", -.3, 0, .25, None), ("daisy", .1, -.1, .15, None), ("tulip", .3, .1, .16, None), ("tree", .1, .2, .5, None)]) if kind == "mushrooms": return _cluster([("mushroom", -.2, 0, .4, None), ("mushroom", .15, .1, .55, None), ("mushroom", .3, -.15, .3, None)]) if kind == "flowers": return _cluster([("tulip", -.3, 0, .3, (230, 60, 80)), ("daisy", 0, .1, .28, None), ("tulip", .3, -.05, .3, (240, 200, 60)), ("rose", .1, -.2, .3, None), ("sunflower", -.1, .25, .45, None)]) if kind == "moss": return [] m = model_of(kind) return m[0] if m else []
def put_on_top(px, ax, top, frac=.62): """Top composition scaled to `frac` of the base's width and set into its upper surface.""" st = analyze(px, ax) fn = union(px) if top == "moss": return apply_skin(px, "moss", None, ax) tp = top_model(top) if not tp: return px tlo, thi = bbox(tp) w = float(st["hi"][0] - st["lo"][0]) f = facing(st) cx = float(st["c"][0]) - .08 * w * (f or 0) y = top_at(fn, cx, 0.0) or float(st["hi"][1]) k = frac * w / max(float(thi[0] - tlo[0]), 1e-3) k = min(k, .9 * float(st["hi"][1] - st["lo"][1]) / max(float(thi[1] - tlo[1]), 1e-3)) sink = .04 * float(st["hi"][1] - st["lo"][1]) tpc = np.array([(tlo[0] + thi[0]) / 2, tlo[1], (tlo[2] + thi[2]) / 2]) # rule: a patch of soil / turf where the top things grow, hugging the back soil = [] if top in ("garden", "forest", "meadow", "flowers", "mushrooms", "village", "city"): rr = .32 * w soil = [Part(lambda p, _c=np.array([cx, y, 0], np.float32), _r=rr: np.maximum(S.ellipsoid(p, _c, np.array([_r, _r * .25, _r * .8], np.float32)), fn(p) - .025), (85, 140, 55) if top != "city" else (150, 150, 150), k=.0, spec=.05, rough=.95, tex="leaves" if top != "city" else "stone")] return px + soil + place_piece(tp, tpc, (cx, y - sink, 0), k)
def top_parts(x, top, col): mx = model_of(x, col) if not mx: raise ValueError("no model for " + x) return put_on_top(mx[0], mx[1], top)
# ------------------------------------------------------------------ transformsdef transform_parts(x, op, col): mx = model_of(x, col) if not mx: raise ValueError("no model for " + x) px, ax = mx if op == "flip": return moved(px, flip=True) if op == "melt": st = analyze(px, ax) out = [] for pt in px: out.append(clone(pt, fn=geo_melt(pt.fn, .35))) # rule: a melting thing drips: a puddle of its body colour on the ground c = px[st["body"]].color out.append(Part(lambda p: S.ellipsoid(p, np.array([0, 0, 0], np.float32), np.array([.55, .045, .4], np.float32)), c, k=.08, spec=.5, rough=.2)) return out return px
# ------------------------------------------------------------------ floating islandsdef island_parts(col=None, tree=True): """A floating island: a flat grassy top, a rocky underside narrowing to a point, dangling roots, a waterfall hint and (alone) a tree. Model frame: tip at y=0, top surface at y~.62.""" grass = col or (95, 150, 60) top_y, R = .62, .75
def rock(p): q = p - np.array([0, top_y, 0], np.float32) r = np.sqrt(q[:, 0] ** 2 + (q[:, 2] / .8) ** 2) # inverted cone with lumpy sides cone = np.maximum(r - R * np.clip(1 + q[:, 1] / top_y, 0, 1.2) ** .8, q[:, 1] - .0) cone = np.maximum(cone, -q[:, 1] - top_y) return cone * .65 - .05 * (S.fbm(p * 5, 3, 7) - .5)
def turf(p): q = p - np.array([0, top_y + .02, 0], np.float32) return S.ellipsoid(q, np.zeros(3, np.float32), np.array([R * 1.03, .06, R * .83], np.float32)) * .9 - .01 * S.noise3(p * 20, 3)
def roots(p): d = None for k in range(5): a = k * 1.3 + .4 x0, z0 = math.cos(a) * R * .45, math.sin(a) * R * .35 e = chain(p, [(x0, top_y * .5, z0), (x0 * 1.1, top_y * .2, z0), (x0 * 1.2, -.05 - .05 * k % 2, z0 * 1.1)], [.02, .012, .006]) d = e if d is None else np.minimum(d, e) return d parts = [Part(rock, (120, 95, 75), spec=.08, rough=.9, tex="stone"), Part(turf, grass, k=.02, spec=.05, rough=.95, tex="leaves"), Part(roots, (100, 75, 50), k=.01, spec=.05, rough=.9, tex="bark")] # rule: a thin waterfall pours off one edge (a glowing pale ribbon) parts.append(Part(lambda p: S.rbox(p, np.array([R * .92, top_y - .25, -.15], np.float32), np.array([.015, .27, .06], np.float32), .01), (200, 230, 250), spec=.8, rough=.1, emit=.35)) if tree: t = model_of("tree") if t: parts += moved(t[0], offset=(-.15, top_y + .03, .1), scale=.55) b = model_of("bush") if b: parts += moved(b[0], offset=(.3, top_y + .03, -.15), scale=.18) return parts
def on_island_parts(x, col): """X standing on a floating island chunk (a floating house / castle / temple).""" mx = model_of(x, col) if not mx: raise ValueError("no model for " + x) px, ax = mx isl = island_parts(None, tree=False) k = 1.0 / max(1.0, ax / 1.3) return isl + moved(px, offset=(0, .62 + .02, 0), scale=k * .9)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213"""Interactions in the 3D renderer: which model a posed instance uses, and where held things / riders go.
Hooks called from plot3d (small on purpose): prepare(insts, scene, trace) after layout: poses implied by interactions (riders sit astride, the chased runs away from the chaser, the carried thing marks its carrier) model_for(it, e, entry, trace) a hand-made animal model has one fixed pose; a posed instance (or one carrying something in its mouth) borrows its generator family, whose skeleton poses place(it, obj, trace) after an object is built: a held thing goes to the holder's hand / mouth / beak / nose anchor, a rider's seat goes on the mount's saddle anchor (both turn with it)Anchors are reported by posed family models (pydraw3d.pose.Model) in their model frame; pure geometry."""import mathimport numpy as npfrom . import sdf as Sfrom .pose import pose_of
_OBJ = {} # id(inst) -> Obj, per render (reset in prepare)SEAT_FURNITURE = {"couch", "chair", "bench", "bed", "sofa", "toilet", "dining table", "table", "desk", "bathtub", "car", "truck", "bus", "train", "boat", "airplane", "bicycle", "motorcycle"}SEATS = {"bicycle": (-.12, .84), "motorcycle": (-.1, .6), "scooter": (-.2, .55), "tricycle": (-.1, .6), "unicycle": (0, .9), "skateboard": (0, .12), "surfboard": (0, .1), "snowboard": (0, .08), "horse": (-.05, .72), "donkey": (-.05, .72), "elephant": (-.05, 1.0), "camel": (-.05, 1.0), "cow": (-.05, .72), "zebra": (-.05, .72)}
def prepare(insts, scene, trace): _OBJ.clear() ents = scene["entities"] by_ent = {} for it in insts: by_ent.setdefault(it.ent, []).append(it) for it in insts: e = ents[it.ent] if isinstance(it.ent, int) and it.ent < len(ents) else {} it.entity = e if getattr(it, "riding", False): it.pose3d = "ride" # rule: an animal "holding" a thing too big for the layout's paw rule (a stick, a key in a beak) still carries it first = {k: v[0] for k, v in by_ent.items()} from pydraw.registry import CONCEPTS for s_, r_, o_ in scene["relations"]: if s_ not in first or o_ not in first: continue if r_ == "riding": first[o_].ridden = True a_ = ((first[s_].attrs or {}) if getattr(first[s_], "attrs", None) else {}).get("action") # rule: playing / reading / carrying something a person can lift = holding it (a guitar, a cello, a sign) if r_ in ("uses", "toward") and first[s_].concept == "person" and a_ in ("play", "read", "carry", "hold", "drink", "eat"): r_ = "holding" if r_ != "holding": continue h_, o = first[s_], first[o_] if getattr(o, "held_by", None) is not None: continue if h_.concept == "person" and (CONCEPTS.get(o.concept, {}).get("height", 9) > 1.3 or o.concept in ("umbrella", "kite", "balloon")): continue o.held_by, o.bound, o.rel = s_, h_, "on" h_.holding = o.concept trace.append("3d: %s carries %s" % (h_.concept, o.concept)) for it in insts: a = (getattr(it, "attrs", None) or {}) # rule: the one being chased runs away from the chaser (same heading, both running) fl = a.get("flee_from") if fl is not None and fl in by_ent and by_ent[fl] and hasattr(it, "x") and hasattr(by_ent[fl][0], "x"): ch = by_ent[fl][0] it.facing = "right" if it.x > ch.x else "left" ch.facing = it.facing trace.append("3d: %s flees from %s (both face %s)" % (it.concept, ch.concept, it.facing)) if scene.get("arrange") == "facing": for it in insts: it.turn_to = True # rule: a group moving together (two dogs racing, ducks swimming, a herd running) shares one heading if scene.get("arrange") != "facing": for k, grp in by_ent.items(): if len(grp) > 1 and pose_of(grp[0]) in ("run", "walk", "swim", "fly", "crawl", "jump"): for o in grp[1:]: o.facing = grp[0].facing
def model_for(it, e, entry, trace): """(fn, aspect) for an instance: the hand-made model, or its generator family when the instance is posed.""" from pydraw.registry import CONCEPTS info = CONCEPTS.get(it.concept, {}) if entry is None or getattr(entry[0], "family", None) or not info.get("animal"): return entry p = pose_of(it) carry = (bool(getattr(it, "holding", None)) and it.concept != "person") or getattr(it, "ridden", False) if p in (None, "stand", "fly", "perch") and not carry: return entry if it.concept in ("person", "teddy bear"): return entry from pydraw.open_vocab import family_model fm = family_model(it.concept) if fm and fm[0].family in ("quadruped", "primate", "bird", "fish", "pinniped", "lizard", "frog", "turtle", "snake"): trace.append("3d: %s is %s -> posable %s family model" % (it.concept, p or "carrying", fm[0].family)) return fm return entry
def world_pt(obj, a): """model-frame point -> world (inverse of Obj.local)""" q = np.asarray(a, float)[None, :] * obj.scale return S.rot_y(q, obj.yaw)[0] + obj.base
def top_point(parts, x=0.0): """rule: with no saddle anchor, a rider sits on the highest surface point above the model's middle""" ys = np.linspace(2.0, 0.0, 201) p = np.stack([np.full_like(ys, x), ys, np.zeros_like(ys)], -1) d = np.minimum.reduce([pt.fn(p) for pt in parts]) hit = np.nonzero(d < .01)[0] return (x, float(ys[hit[0]]), 0.0) if len(hit) else None
def _anchor(obj, *names): an = getattr(obj.parts, "anchors", None) or {} for n in names: if n in an: return n, an[n] return None, None
def place(it, obj, trace): _OBJ[id(it)] = obj b = getattr(it, "bound", None) if b is None or id(b) not in _OBJ: return host = _OBJ[id(b)] held = getattr(it, "held_by", None) is not None if held: act = ((getattr(b, "attrs", None) or {}).get("action") or "") names = ("nose", "mouth") if act in ("balance", "balancing") else ("held", "hand", "beak", "mouth", "paw") if it.concept in ("umbrella", "kite", "balloon"): names = ("hand_top", "held", "hand") n, a = _anchor(host, *names) if a is None: return w = world_pt(host, a) obj.yaw = host.yaw from pydraw.registry import CONCEPTS if n in ("mouth", "beak") and CONCEPTS.get(it.concept, {}).get("aspect", 1) < .6: # rule: a long thin thing (stick, key, bone, pen) is carried crosswise in the mouth / beak from .pose import posed, about, rot_axis T = about((0, .5, 0), rot_axis("z", 90)) for pt in obj.parts: pt.fn = posed(pt.fn, T) obj.yaw = host.yaw + math.pi / 2 if n in ("mouth", "beak", "nose") and obj.radius > host.radius * .45: k = host.radius * .45 / obj.radius # rule: a long thing carried in a beak is shorter than the bird obj.scale *= k obj.radius *= k if n in ("held", "hand") and b.concept != "person" and obj.scale > host.scale * .32: k = host.scale * .32 / obj.scale # rule: an animal's paw holds something about a third of its size obj.scale *= k obj.radius *= k if n in ("mouth", "beak", "nose") and obj.scale > host.scale * .55: # rule: what a mouth / beak carries is at most about half the carrier's height k = host.scale * .55 / obj.scale obj.scale *= k obj.radius *= k if n == "nose": obj.base = w - np.array([0, obj.scale * .06, 0]) # rule: a balanced ball sits ON the nose tip elif n in ("hand", "hands", "paw") and it.concept not in ("umbrella", "kite", "balloon"): hk = getattr(host.parts, "grip", {}) or {} g = hk.get(it.concept, .42) obj.base = w - np.array([0, obj.scale * g, 0]) # rule: a hand holds a thing a little below its middle elif n == "hand_top": obj.base = w - np.array([0, obj.scale * .05, 0]) else: obj.base = w - np.array([0, obj.scale * .5, 0]) # mouth / beak: centred between the jaws obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s placed at %s's %s" % (it.concept, b.concept, n)) return from pydraw.registry import CONCEPTS if getattr(it, "rel", None) == "on" and CONCEPTS.get(it.concept, {}).get("animal") and not getattr(it, "riding", False) \ and b.concept not in SEAT_FURNITURE and (CONCEPTS.get(b.concept, {}).get("open_vocab") or {}).get("family") != "furniture": # rule: an animal on a natural support (a branch, a rock, a log) rests its seat / feet on the support's surface lx = S.rot_y((obj.base - host.base)[None, :] / host.scale, -host.yaw)[0] a = top_point(host.parts, x=float(lx[0])) if a is not None: _, seat = _anchor(obj, "seat") w = world_pt(host, (lx[0], a[1], lx[2])) dy = (w[1] - (seat[1] * obj.scale if seat is not None else 0.0)) - obj.base[1] obj.base = obj.base + np.array([0, dy, 0]) obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s rests on the surface of %s" % (it.concept, b.concept)) return if getattr(it, "riding", False) or getattr(it, "pose3d", None) == "ride": n, a = _anchor(host, "saddle") if a is None: # rule: hand-made vehicles have their seat at a known place in their box (x as a fraction of width) seat = SEATS.get(b.concept) if seat is not None: from pydraw.registry import CONCEPTS asp = CONCEPTS.get(b.concept, {}).get("aspect", 1.0) a = (seat[0] * asp, seat[1], 0.0) else: a = top_point(host.parts) if a is None: return w = world_pt(host, a) _, seat = _anchor(obj, "seat") person = it.concept == "person" or getattr(obj.parts, "front", None) == "-z" if not person and obj.scale > host.scale * .8: k = host.scale * .8 / obj.scale # rule: an animal rider is smaller than its mount obj.scale *= k obj.radius *= k _, seat = _anchor(obj, "seat") obj.yaw = host.yaw - (math.pi / 2 if person else 0.0) if seat is not None: obj.base = w - S.rot_y(np.asarray(seat, float)[None, :] * obj.scale, obj.yaw)[0] else: obj.base = w.copy() obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s rides on %s's back" % (it.concept, b.concept))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""pydraw3d.interior: furnished rooms (pure code). A room used to be a bare floor + one painted wall + a whitewindow. Now: furniture models stand along the back wall (never in front of / behind a subject, never a promptedconcept), a patterned rug lies under the subjects, framed paintings hang on the wall, the window has curtains anda view (sky, clouds, hills, a tree line), and some walls get wallpaper."""import mathimport numpy as np
from .world import vnoise, fbm2, hash2, smooth, lin
# per room kind: furniture (concept, real height m, distance of its centre from the wall m), in order of preferenceROOM_FURNITURE = { "room": [("bookshelf", 1.8, .2), ("floor lamp", 1.6, .3), ("potted plant", .95, .35)], "bedroom": [("floor lamp", 1.5, .3), ("potted plant", .9, .35), ("bookshelf", 1.6, .2)], "office": [("bookshelf", 1.9, .2), ("potted plant", 1.0, .35)], "library": [("bookshelf", 2.0, .2), ("bookshelf", 2.0, .2), ("floor lamp", 1.6, .3)], "classroom": [("bookshelf", 1.6, .2), ("potted plant", .9, .35)], "kitchen": [("potted plant", .7, .35)], "bathroom": [("potted plant", .8, .35)], "restaurant": [("potted plant", 1.2, .35), ("floor lamp", 1.6, .3)], "cafe": [("potted plant", 1.1, .35), ("bookshelf", 1.7, .2)],}SKIP_WORDS = {"bookshelf": {"bookshelf", "bookcase", "shelf", "book", "books"}, "floor lamp": {"lamp", "floor lamp", "light", "lantern", "candle"}, "potted plant": {"potted plant", "plant", "flower", "flowers", "vase", "tree", "cactus", "houseplant"}}
class Interior: def __init__(self, scene, objs, wall_z, upm, cam, seed, L, trace, Obj, MODELS): self.m, self.cam, self.seed = upm, cam, seed self.wall_z = wall_z self.win_x = .9 * upm * (1 if -L[0] > 0 else -1) rng = np.random.RandomState(seed + 31) self.rng = rng names = {e["concept"] for e in scene.get("entities", [])} words = set() for n in names: words |= {n, n.split()[-1]} subj = [o for o in objs] # subjects' horizontal screen ranges (u = x/z) self.usub = [] for o in subj: a_ = math.sqrt(max(((o.radius / o.scale - .15) / .5) ** 2 - 1, 0) / 2) hw = .55 * o.scale * max(a_, .6) zc = max(o.base[2], .3) self.usub.append(((o.base[0] - hw) / zc, (o.base[0] + hw) / zc)) floor = [o for o in subj if abs(o.base[1]) < .1 * o.scale + 1e-6] or subj if floor: xs = [o.base[0] for o in floor] zs = [o.base[2] for o in floor] ext = max([abs(o.base[0] - np.mean(xs)) + .5 * o.scale for o in floor] + [.6 * upm]) rx = min(ext * 1.1 + .15 * upm, 1.5 * upm) self.rug = (float(np.mean(xs)), float(np.mean(zs)) + .1 * upm, rx, min(ext * .6 + .3 * upm, .9 * upm)) else: self.rug = None self.rug_style = rng.randint(3) self.wallpaper = rng.rand() < .4 kind = scene.get("place") if scene.get("place") in ROOM_FURNITURE else "room" self.objs = [] placed = [] for name, h, dwall in ROOM_FURNITURE[kind]: if words & SKIP_WORDS.get(name, {name}): continue mdl = MODELS.get(name) if mdl is None: try: from pydraw.open_vocab import family_model mdl = family_model(name) except Exception: mdl = None if mdl is None: continue fn, asp = mdl z = wall_z - dwall * upm sc = h * upm half = .5 * sc * asp / z ok = None for tries in range(16): side = 1 if (tries + len(placed)) % 2 == 0 else -1 uc = side * rng.uniform(.18, .5) lo, hi = uc - half, uc + half if any(not (hi < a - .03 or lo > b + .03) for a, b in self.usub + placed): continue if name == "bookshelf" and abs(uc * z - self.win_x) < .55 * upm + .5 * sc * asp: continue # rule: never in front of the window ok = uc break if ok is None: continue try: parts = fn(None, None) except Exception: continue ob = Obj(parts, (ok * z, 0.0, z), sc, 0.0, "_room_" + name, asp) ob.col, ob.target, ob.cname, ob.dressing = None, None, None, True self.objs.append(ob) placed.append((ok - half, ok + half)) # paintings: 1-2 frames on the back wall, away from the window, above furniture height self.pictures = [] for k in range(2): for _ in range(10): px = rng.uniform(-1.6, 1.6) * upm pw, ph = rng.uniform(.45, .75) * upm, rng.uniform(.35, .55) * upm if abs(px - self.win_x) < .55 * upm + pw * .5 + .15 * upm: continue if any(abs(px - q[0]) < (pw + q[2]) * .5 + .15 * upm for q in self.pictures): continue self.pictures.append((px, rng.uniform(1.35, 1.65) * upm, pw, ph, rng.randint(3), rng.rand())) break trace.append("interior: %s furniture %s, %d paintings, rug=%s" % (kind, [o.name[6:] for o in self.objs], len(self.pictures), self.rug is not None))
def surfaces(self, q, wallm, a_, win, frame): """room surfaces: rug on the floor under the subjects, wallpaper, paintings, curtains, window view""" m = self.m floorm = ~wallm if self.rug is not None: cx, cz, rx, rz = self.rug lx, lz = (q[:, 0] - cx) / rx, (q[:, 2] - cz) / rz if self.rug_style == 2: r = np.sqrt(lx ** 2 + lz ** 2) inside = floorm & (r < 1) else: r = np.maximum(np.abs(lx), np.abs(lz)) inside = floorm & (r < 1) if inside.any(): li, lj, rr = lx[inside], lz[inside], r[inside] wool = (.85 + .25 * vnoise(q[inside, 0] / m * 60, q[inside, 2] / m * 60, self.seed))[:, None] if self.rug_style == 0: # Persian: red field, navy border with cream lines, central medallion c = np.tile(lin((150, 32, 36)), (len(li), 1)) c[rr > .8] = lin((30, 40, 90)) c[(np.abs(rr - .78) < .015) | (np.abs(rr - .93) < .012)] = lin((230, 215, 175)) md = np.abs(li) + np.abs(lj) c[md < .42] = lin((30, 40, 90)) c[md < .26] = lin((230, 215, 175)) c[md < .12] = lin((150, 32, 36)) orn = (rr < .75) & (md > .5) & (np.sin(li * 18) * np.sin(lj * 18) > .55) c[orn] = lin((210, 150, 60)) elif self.rug_style == 1: # modern stripes pal = np.array([lin(x) for x in ((230, 225, 210), (70, 90, 110), (200, 140, 90), (120, 150, 140))]) c = pal[(np.floor((li + 1) * 4.5).astype(int)) % 4] c[rr > .94] = lin((230, 225, 210)) else: # round braided jute c = lin((180, 150, 100)) * (.8 + .25 * (np.sin(rr * 60) > 0))[:, None] a_[inside] = c * wool wm = wallm & ~win & ~frame if self.wallpaper and wm.any(): # rule: some rooms have wallpaper: soft vertical stripes with a faint damask xx = q[wm, 0] / m st = (np.sin(xx * 2 * math.pi / .18) > .3) * .06 dm = .04 * (np.sin(xx * 25) * np.sin(q[wm, 1] / m * 25) > .4) a_[wm] = a_[wm] * (1 - st - dm)[:, None] + lin((240, 235, 220)) * (st + dm)[:, None] # paintings for px, py, pw, ph, style, hh in self.pictures: lx, ly = (q[:, 0] - px) / (pw * .5), (q[:, 1] - py) / (ph * .5) inside = wallm & (np.abs(lx) < 1) & (np.abs(ly) < 1) if not inside.any(): continue li, lj = lx[inside], ly[inside] fr = (np.abs(li) > .9) | (np.abs(lj) > .87) if style == 0: # small landscape: sky gradient, sun, two hill layers c = lin((150, 190, 225)) * (1 - (lj[:, None] + 1) * 0) * (.8 + .3 * ((lj + 1) / 2))[:, None] hill1 = lj < -.1 + .25 * np.sin(li * 2.5 + hh * 6) hill2 = lj < -.45 + .15 * np.sin(li * 4 + hh * 3) c[hill1] = lin((90, 130, 80)) c[hill2] = lin((60, 100, 55)) sun = ((li - .45) ** 2 + (lj - .45) ** 2) < .02 c[sun] = lin((250, 230, 160)) elif style == 1: # colour-field abstract: two soft blocks pal = [lin(x) for x in ((200, 80, 60), (240, 190, 90), (60, 90, 140), (230, 220, 200), (40, 110, 100))] i1 = int(hh * 5) % 5 c = np.where((lj > .05)[:, None], pal[i1], pal[(i1 + 2) % 5]) * (.9 + .15 * vnoise(li * 6, lj * 6, self.seed))[:, None] else: # botanical print: pale paper + a dark leafy silhouette c = np.tile(lin((235, 228, 210)), (len(li), 1)) leaf = (np.abs(li) < .06 + .5 * np.clip(1 - np.abs(lj + .1), 0, 1) * (np.abs(np.sin(lj * 9)) ** 2)) & (lj > -.8) & (lj < .8) c[leaf] = lin((60, 95, 60)) c[fr] = lin((60, 40, 28)) if hh < .6 else lin((190, 150, 70)) a_[inside] = c # window: a view instead of a white rectangle, plus curtains on both sides if win.any(): wx = (q[win, 0] - self.win_x) / (.55 * m) wy = (q[win, 1] / m - .9) / 1.1 # 0 bottom .. 1 top of the window sky = lin((120, 170, 225)) * (1 - wy[:, None]) * 0 + (lin((175, 205, 235)) * (1 - wy[:, None]) + lin((95, 150, 220)) * wy[:, None]) cl = smooth(.5, .7, fbm2(wx * 2 + 3, wy * 3, 4, self.seed + 5)) * smooth(.3, .7, wy) sky = sky * (1 - cl[:, None]) + lin((245, 245, 245)) * cl[:, None] hill = wy < .28 + .08 * np.sin(wx * 3 + self.seed) + .04 * fbm2(wx * 4, wx * 0, 3, self.seed) sky[hill] = lin((110, 150, 95)) * (.85 + .2 * vnoise(wx[hill] * 9, wy[hill] * 9, self.seed))[:, None] trees = wy < .18 + .07 * np.abs(np.sin(wx * 13 + 2 * fbm2(wx * 5, wx * 0, 2, self.seed))) sky[trees] = lin((60, 100, 60)) a_[win] = sky * 2.2 cur = wallm & (q[:, 1] > .75 * m) & (q[:, 1] < 2.2 * m) & (np.abs(np.abs(q[:, 0] - self.win_x) - .7 * m) < .17 * m) if cur.any(): fold = .75 + .3 * np.sin((q[cur, 0] - self.win_x) / m * 60) ccol = [lin((150, 60, 60)), lin((60, 90, 130)), lin((200, 180, 130))][self.seed % 3] a_[cur] = ccol * fold[:, None] rod = wallm & (np.abs(q[:, 1] - 2.22 * m) < .02 * m) & (np.abs(q[:, 0] - self.win_x) < .9 * m) a_[rod] = lin((70, 55, 40)) return a_
def make_interior(scene, objs, wall_z, upm, cam, seed, L, trace, Obj, MODELS): return Interior(scene, objs, wall_z, upm, cam, seed, L, trace, Obj, MODELS)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396"""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 mathimport numpy as npfrom . 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""" 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)14 unmodified lines15161718192021222324252614 unmodified linesclass Part:def __init__(self, fn, color, k=0.0, spec=.2, rough=.5, tex=None, emit=0.0, pat=None):self.fn, self.color, self.k, self.spec, self.rough, self.tex = fn, np.asarray(color, float), k, spec, rough, texself.emit = emit # 0..1: glows with its own colour (screens, lamps)# pat: coat / surface pattern (kind, second colour, scale): kind in stripes, spots, rosettes, patches,# bands, checker, scales. See pydraw3d.pattern.self.pat = patdef V(*a):14 unmodified lines151617181920212223242526272814 unmodified linesclass Part:def __init__(self, fn, color, k=0.0, spec=.2, rough=.5, tex=None, emit=0.0, pat=None, **light):self.fn, self.color, self.k, self.spec, self.rough, self.tex = fn, np.asarray(color, float), k, spec, rough, texself.emit = emit # 0..1: glows with its own colour (screens, lamps)# pat: coat / surface pattern (kind, second colour, scale): kind in stripes, spots, rosettes, patches,# bands, checker, scales. See pydraw3d.pattern.self.pat = pat# light: optional material flags read by pydraw3d/light.py (glass, ior, frost, metal, sss)self.__dict__.update(light)def V(*a):
10 unmodified lines1112131415161718191 unmodified line212223242526272829303132333489 unmodified lines12412512612712812913013110 unmodified lines# ---------------- helpers ----------------def rcone(p, a, b, r1, r2):"""tapered capsule from a (radius r1) to b (radius r2), exact SDF (iq's round cone)"""a, b = np.asarray(a, float), np.asarray(b, float)ba = b - al2 = ba @ barr = r1 - r2a2 = l2 - rr * rril2 = 1.0 / l21 unmodified liney = pa @ baz = y - l2w = pa * l2 - y[:, None] * bax2 = (w * w).sum(-1)y2 = y * y * l2z2 = z * z * l2k = np.sign(rr) * rr * rr * x2d_end = np.sqrt(x2 + z2) * il2 - r2d_start = np.sqrt(x2 + y2) * il2 - r1d_mid = (np.sqrt(np.maximum(x2 * a2 * il2, 0)) + y * rr) * il2 - r1return np.where(np.sign(z) * a2 * z2 > k, d_end, np.where(np.sign(y) * a2 * y2 < k, d_start, d_mid))def chain(p, pts, rs):89 unmodified lines# ---------------- person ----------------@model("person", "man", "woman", "boy", "girl", "child", "people", aspect=.42)def m_person(col, inst=None):shirt = col or (60, 130, 210)word = getattr(inst, "word", "") or ""skin_tones = [(238, 196, 160), (205, 150, 110), (150, 100, 70), (245, 210, 180)]10 unmodified lines11121314151617181920211 unmodified line2324252627282930313233343589 unmodified lines12512612712812913013110 unmodified lines# ---------------- helpers ----------------def rcone(p, a, b, r1, r2):"""tapered capsule from a (radius r1) to b (radius r2), exact SDF (iq's round cone)"""# rule (speed): stay in the points' float32, one einsum for the squared length (2x faster, same values)dt = p.dtype if p.dtype in (np.float32, np.float64) else np.float64a, b = np.asarray(a, dt), np.asarray(b, dt)ba = b - al2 = float(ba @ ba)rr = r1 - r2a2 = l2 - rr * rril2 = 1.0 / l21 unmodified liney = pa @ baz = y - l2w = pa * l2 - y[:, None] * bax2 = np.einsum("ij,ij->i", w, w)y2 = y * y * l2z2 = z * z * l2k = np.sign(rr) * rr * rr * x2d = (np.sqrt(np.maximum(x2 * (a2 * il2), 0)) + y * rr) * il2 - r1d = np.where(np.sign(y) * a2 * y2 < k, np.sqrt(x2 + y2) * il2 - r1, d)return np.where(np.sign(z) * a2 * z2 > k, np.sqrt(x2 + z2) * il2 - r2, d)def chain(p, pts, rs):89 unmodified lines# ---------------- person ----------------def m_person_v1(col, inst=None): # superseded by models_person.py (wave 11, posable person)shirt = col or (60, 130, 210)word = getattr(inst, "word", "") or ""skin_tones = [(238, 196, 160), (205, 150, 110), (150, 100, 70), (245, 210, 180)]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Fire: campfire / bonfire as SDF models. The flames are emissive, so at night they become a point light(pydraw3d/light.py find_lights) that lights the logs, stones, ground and anything nearby."""import numpy as npfrom pydraw3d.models import model, Part, Vfrom pydraw3d import sdf as S
def _flame(p, base, r, h, seed, wob=.5): """a flame tongue: a teardrop (ellipsoid narrowing to a tip) bent and flickered by noise""" q = p - base y = np.clip(q[:, 1] / h, 0, 1) bend = wob * r * (S.noise3(np.stack([q[:, 1] * 6 + seed, np.full(len(q), seed * 1.7), np.zeros(len(q))], -1) * 1.0) - .5) * y * 2 x = q[:, 0] - bend rad = r * np.sqrt(np.clip(np.sin(np.pi * np.clip(y * .85 + .15, 0, 1)), 0, 1)) * (1 - y) ** .5 d2 = np.sqrt(x * x + q[:, 2] ** 2) - rad return np.maximum(d2, np.maximum(-q[:, 1], q[:, 1] - h)) * .6
@model("campfire", "bonfire", "fire", "camp fire", aspect=1.25)def m_campfire(col, inst=None): flame_c = col or (255, 140, 30) seed = 3.0
def logs(p): d = None for a in (0.3, 1.35, 2.4): c, s = np.cos(a), np.sin(a) e = S.capsule(p, (-.42 * c, .07, -.42 * s), (.42 * c, .07, .42 * s), .065) d = e if d is None else np.minimum(d, e) # two leaning logs (a teepee) d = np.minimum(d, S.capsule(p, (-.3, .05, .05), (.02, .42, 0), .05)) d = np.minimum(d, S.capsule(p, (.3, .05, -.05), (-.02, .42, 0), .05)) return d
def stones(p): d = None for i in range(9): a = i / 9 * 2 * np.pi e = S.ellipsoid(p, V(.58 * np.cos(a), .05, .58 * np.sin(a) * .8), V(.1, .07, .08)) d = e if d is None else np.minimum(d, e) return d
def outer(p): d = _flame(p, V(0, .06, 0), .2, .8, seed) d = np.minimum(d, _flame(p, V(.15, .06, .03), .11, .5, seed + 2)) d = np.minimum(d, _flame(p, V(-.16, .06, -.02), .1, .58, seed + 5)) d = np.minimum(d, _flame(p, V(.05, .06, .1), .09, .66, seed + 7)) return d
def mid(p): d = _flame(p, V(.01, .06, -.07), .15, .55, seed + 1, .35) return np.minimum(d, _flame(p, V(-.1, .06, -.08), .08, .38, seed + 4, .4))
def core(p): return _flame(p, V(0, .06, -.15), .085, .3, seed + 3, .2)
# rule: a flame is layered: deep orange-red outside, orange-yellow inside, a pale core near the wood; the layers # step toward the camera so all three show (their emission ignores shading) return [Part(stones, (120, 116, 110), spec=.1, rough=.8, tex="stone"), Part(logs, (80, 52, 34), spec=.05, rough=.9, tex="bark"), Part(outer, (230, 70, 15), emit=1.0, spec=0, rough=1), Part(mid, flame_c, emit=1.0, spec=0, rough=1), Part(core, (255, 230, 150), emit=1.0, spec=0, rough=1)]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555"""The 3D person (wave 11): a posable skeleton dressed from the parser's attributes.
Skeleton: pelvis, a torso that can lean, a head that can pitch / turn, two arms and two legs solved with 3D 2-boneIK toward hand / foot TARGETS given per pose (so one pose table serves every person: man, girl, old woman...).Poses: stand, walk, run, jump, sit (on a seat or on the ground), ride (astride), lie / sleep, kneel, dance; handactions: wave, hold (one hand), hands (two hands: reading, carrying), mouth (drinking, eating), play (guitar /drums / flute style by the instrument), point, cheer.Dress: outfit items (top / outer / full / bottom) with their colours, hair colour + length (short, long, curly,bald), beard, skin tone, child / old proportions, facial expressions (happy, laughing, sad, angry, surprised,crying, shouting, scared) and closed eyes when asleep.Model frame: standing height 1, faces -z (the camera), base y=0 (the seat when sitting on something).Anchors (pydraw3d.pose.Model): hand, hands, hand_top, seat, head. Pure numpy SDFs, no learned anything."""import mathimport numpy as npfrom .models import model, Part, V, darkerfrom . import sdf as Sfrom .models_animals import rcone, chainfrom .pose import Rigid, rot_axis, about, posed, pose_of, Modelfrom pydraw.registry import CONCEPTS
SKIN = [(236, 192, 156), (198, 140, 100), (141, 92, 62), (246, 212, 184), (172, 116, 80)]HAIRC = [(68, 44, 28), (32, 26, 22), (24, 20, 18), (172, 104, 50), (205, 170, 110)]SHIRTS = [(60, 130, 210), (205, 70, 60), (70, 150, 90), (235, 190, 60), (150, 90, 170), (240, 240, 235)]PANTS = [(48, 62, 102), (55, 55, 62), (120, 100, 75), (40, 40, 44)]HAIR_NAMED = {"blonde": (226, 190, 110), "brown": (105, 66, 38), "red": (186, 78, 38), "gray": (170, 168, 165), "white": (236, 234, 230), "black": (28, 24, 22)}CHILD = {"child", "kid", "boy", "girl", "children", "kids", "boys", "girls", "schoolboy", "schoolgirl", "toddler", "baby", "infant"}FEMALE = {"woman", "girl", "lady", "mother", "bride", "princess", "women", "girls", "queen", "grandmother", "grandma", "nun", "ballerina", "mom", "sister", "daughter", "wife", "actress", "waitress", "witch", "fairy", "mermaid"}MALE = {"man", "boy", "men", "boys", "king", "father", "grandfather", "grandpa", "dad", "brother", "son", "husband", "gentleman", "groom", "prince", "monk", "wizard", "santa", "cowboy", "pirate"}
# ---------------------------------------------------------------- pose table# Targets in the torso frame (x: the person's left side is +x on screen... the person faces -z, so screen-right = +x;# s = +1 for the left-of-screen-right arm). Hand target (x*s, y, z) and an elbow pole; foot target and knee pole.# lean: torso pitch forward (deg); dy: pelvis shift (standing units); yaw: whole-body turn toward the heading.ARM = { "down": ((.17, .47, -.03), (1, -.2, .6)), "swing_f": ((.15, .56, -.17), (1, -.6, .8)), "swing_b": ((.16, .52, .13), (1, -.3, .6)), "run_f": ((.13, .68, -.19), (.4, -1, .6)), "run_b": ((.16, .6, .17), (.4, -1, -.2)), "up": ((.27, 1.04, -.03), (1, -.8, .3)), "wave": ((.3, 1.0, -.06), (1, -1, .4)), "hold": ((.15, .58, -.22), (1, -1, .6)), "hands": ((.07, .64, -.24), (1, -1, .2)), "mouth": ((.04, .85, -.13), (1, -.9, .2)), "reins": ((.08, .6, -.22), (1, -1, .4)), "point": ((.36, .8, -.3), (1, -.3, .5)), "lap": ((.1, .5, -.18), (1, -.6, .6)), "guitar_neck": ((.26, .72, -.16), (1, -1, .3)), "guitar_body": ((-.02, .56, -.18), (1, -.8, .5)), "drum": ((.12, .52, -.27), (1, -.6, .4)), "flute": ((.0, .86, -.16), (1, -.8, .2)), "fiddle_neck": ((.3, .8, -.26), (1, -1, .2)), "bow": ((-.02, .74, -.2), (1, -.6, .4)), "hips": ((.19, .55, .02), (1, .3, .3)),}LEG = { "stand": ((.07, .045, -.01), (0, .2, -1)), "step_f": ((.065, .05, -.14), (0, .2, -1)), "step_b": ((.065, .06, .13), (0, .2, -1)), "run_f": ((.06, .2, -.21), (0, .3, -1)), "run_b": ((.065, .2, .27), (0, -.2, -1)), "tuck": ((.08, .22, .02), (0, .2, -1)), "seat": ((.09, .045 + .03, -.27), (0, 1, -.6)), # thigh forward, shin hanging (relative: see dy) "ground": ((.11, .5, -.4), (0, 1, -.3)), "ride": ((.25, .19, -.06), (1, .3, -1)), "kneel_b": ((.07, .06, .2), (0, -1, -.3)), "kneel_f": ((.08, .045, -.2), (0, .5, -1)),}# name -> (right arm, left arm, right leg, left leg, lean, dy, yaw, head pitch)POSES = { "stand": ("down", "down", "stand", "stand", 0, 0, 0, 0), "walk": ("swing_f", "swing_b", "step_b", "step_f", 3, -.012, 55, 0), "run": ("run_b", "run_f", "run_f", "run_b", 14, .02, 60, -5), "jump": ("up", "up", "tuck", "tuck", 0, .06, 0, -8), "dance": ("up", "hips", "stand", "step_f", -4, 0, 20, -5), "sit": ("lap", "lap", "seat", "seat", 0, -.45, 0, 0), "sit_ground": ("lap", "lap", "ground", "ground", 4, -.45, 0, 0), "ride": ("reins", "reins", "ride", "ride", 4, -.45, 0, 0), "cycle": ("reins", "reins", "seat", "seat", 18, -.45, 0, 0), "kneel": ("down", "down", "kneel_b", "kneel_f", 0, -.2, 0, 0), "lie": ("down", "down", "stand", "stand", 0, 0, 0, 0),}CANON_PERSON = {"stand": "stand", "walk": "walk", "run": "run", "jump": "jump", "dance": "dance", "sit": "sit", "ride": "ride", "kneel": "kneel", "lie": "lie", "sleep": "lie", "crawl": "kneel", "upright": "stand", "swim": "lie", "graze": "stand", "howl": "stand", "rear": "stand", "hang": "stand", "balance": "stand", "one_leg": "stand", "fly": "stand", "perch": "sit", "coil": "lie"}HAND_ACTIONS = {"wave": ("wave", None), "read": ("hands", "hands"), "carry": ("hold", None), "hold": ("hold", None), "drink": ("mouth", None), "eat": ("mouth", None), "point": ("point", None), "cheer": ("up", "up"), "sing": ("mouth", None), "balance": ("up", None)}TWO_HANDED = {"newspaper", "book", "box", "laptop", "pizza", "cake", "baby", "basket", "tray", "map", "magazine", "present", "gift", "sign", "painting", "picture frame", "bowl", "letter", "envelope", "notebook", "kite"}
def ik3(a, f, l1, l2, pole): a, f, pole = np.asarray(a, float), np.asarray(f, float), np.asarray(pole, float) d = f - a L = float(np.linalg.norm(d)) if L > (l1 + l2) * .995: f = a + d * ((l1 + l2) * .995 / L) d, L = f - a, (l1 + l2) * .995 L = max(L, abs(l1 - l2) + 1e-4) u = d / L x = (l1 * l1 - l2 * l2 + L * L) / (2 * L) h = math.sqrt(max(l1 * l1 - x * x, 0.0)) pp = pole - (pole @ u) * u n = np.linalg.norm(pp) pp = pp / n if n > 1e-6 else np.array([0, 0, -1.0]) return a + u * x + pp * h, f
def _color(name, default): if not name: return default try: from pydraw.understanding import COLORS return tuple(COLORS[name]) if name in COLORS else default except Exception: return default
def _outfit(e, inst, col, k): """(top, sleeves 'short'/'long', bottom, bottom kind, full kind or None) from attrs['outfit'] + entity colour""" at = (e.get("attrs") if e else None) or getattr(inst, "attrs", None) or {} try: from pydraw.understanding import GARMENT_DEFAULT_COLOR except Exception: GARMENT_DEFAULT_COLOR = {} top, sleeves, bottom, bkind, full = None, "short", None, "pants", None outer = None for it in at.get("outfit") or []: c = _color(it.get("color") or GARMENT_DEFAULT_COLOR.get(it["kind"]), None) if it["slot"] == "top": top = c or top or SHIRTS[(k + 1) % len(SHIRTS)] sleeves = "long" if it["kind"] == "sweater" else sleeves elif it["slot"] == "outer": outer = c or (90, 80, 70) elif it["slot"] == "bottom": bottom = c or (48, 62, 102) bkind = it["kind"] elif it["slot"] == "full": full = it["kind"] c = c or col or SHIRTS[k % len(SHIRTS)] top = c if full in ("dress", "robe", "tutu", "costume", "apron"): bottom, bkind = c, ("robe" if full == "robe" else "skirt" if full in ("dress", "tutu", "apron") else "pants") if full == "dress" and "long" not in (it.get("adj") or []): bkind = "dress" else: bottom, bkind = (c if full not in ("suit",) else darker(c, .9)), "pants" sleeves = "long" if full in ("suit", "robe", "uniform", "spacesuit", "armor", "costume", "labcoat") else sleeves if outer is not None: top, sleeves = outer, "long" if top is None: top = tuple(col) if col else SHIRTS[k % len(SHIRTS)] if bottom is None: bottom = PANTS[k % len(PANTS)] if sum(top) < 200 and sum(bottom) < 220: bottom = (120, 110, 95) return top, sleeves, bottom, bkind, full
@model("person", "man", "woman", "boy", "girl", "child", "people", aspect=.42)def m_person(col, inst=None): e = getattr(inst, "entity", None) or {} word = (getattr(inst, "word", "") or e.get("word") or "").lower() words = set(word.split()) k = getattr(inst, "k", 0) or 0 attrs = (e.get("attrs") if e else None) or getattr(inst, "attrs", None) or {} child = bool(words & CHILD) old = bool(words & {"old", "elderly", "grandfather", "grandmother", "grandpa", "grandma", "aged"}) female = bool(words & FEMALE) or (not (words & MALE) and k % 2 == 1) # ---- colours sk = {"dark": 2, "brown": 1, "light": 3, "pale": 3, "black": 2, "white": 3, "tan": 4}.get(attrs.get("skin"), None) skin = SKIN[sk if sk is not None else k % len(SKIN)] hair = HAIR_NAMED.get(e.get("hair")) if e.get("hair") else None hair = hair or _color(e.get("hair"), None) or ((206, 204, 200) if old else HAIRC[k % len(HAIRC)]) hlen = attrs.get("hair_len") or ("long" if female else "short") bald = "bald" in words or (old and not female and k % 2 == 0 and not e.get("hair")) top, sleeves, bottom, bkind, full = _outfit(e, inst, col, k) shoes = (40, 34, 32) if full not in ("dress",) else darker(top, .6)
# ---- pose p = pose_of(inst) on_seat = getattr(inst, "bound", None) is not None and getattr(inst, "rel", None) == "on" and not getattr(inst, "riding", False) name = CANON_PERSON.get(p, "stand") if p else "stand" if name == "sit" and not on_seat: name = "sit_ground" if getattr(inst, "riding", False) or p == "ride": b = getattr(getattr(inst, "bound", None), "concept", "") name = "ride" if b not in ("skateboard", "surfboard", "snowboard", "skis", "scooter") else "stand" if b in ("bicycle", "motorcycle", "bike", "tricycle", "unicycle") or \ (CONCEPTS.get(b, {}).get("open_vocab") or {}).get("family") in ("cycle",): name = "cycle" # rule: on a bike the legs go down to the pedals, hands forward on the handlebar sleep = p in ("sleep",) ra, la, rl, ll_, lean, dy, yaw, hpitch = POSES[name] act = attrs.get("action") holding = getattr(inst, "holding", None) hc = CONCEPTS.get(holding, {}) if holding else {} fam = (hc.get("open_vocab") or {}).get("family") if holding: if holding in TWO_HANDED or fam in ("book", "sheet", "box", "framed") or act == "read": ra, la = "hands", "hands" if act == "read": hpitch = -14 elif act in ("drink", "eat", "sing") or fam in ("drink",) or holding in ("cup", "wine glass", "microphone", "ice cream", "donut", "apple", "banana", "sandwich", "hot dog"): ra = "mouth" if act in ("drink", "eat", "sing") or holding in ("microphone",) else "hold" elif fam == "instrument" or holding in ("guitar", "violin", "drum", "flute", "trumpet", "saxophone", "piano"): kind = holding if holding in ("drum", "drums", "piano"): ra, la = "drum", "drum" elif holding in ("violin", "viola", "fiddle"): ra, la = "bow", "fiddle_neck" # rule: a violin rests on the left shoulder, the right arm bows elif holding in ("flute", "trumpet", "saxophone", "clarinet"): ra, la = "flute", "flute" else: ra, la = "guitar_body", "guitar_neck" elif holding in ("umbrella", "kite", "balloon", "flag", "torch", "sword", "cane", "broom", "fishing rod"): ra = "hold" if holding not in ("umbrella", "torch", "flag") else "up" else: ra = "hold" if act in HAND_ACTIONS and not holding: ra = HAND_ACTIONS[act][0] if HAND_ACTIONS[act][1]: la = HAND_ACTIONS[act][1] if name in ("ride", "cycle") and not holding and act not in HAND_ACTIONS: ra, la = "reins", "reins" if name == "lie": ra, la = "down", "down"
# ---- proportions (standing adult; children get a big head and a shorter body) hr = .066 if not female else .063 HC = np.array([0, .895, 0]) vs = 1.0 if child: hr = .102 vs = (1 - hr * 2.25) / (1 - .066 * 2.25) HC = np.array([0, 1 - hr * 1.25, 0]) sw = (.118 if not female else .105) * (.9 if child else 1) hw = .072 if not female else .08 sv = lambda y: y * vs pel = np.array([0, sv(.52), 0]) hipy = sv(.495) shy = sv(.772) neck0 = np.array([0, sv(.8), 0]) la1, la2 = sv(.162), sv(.155) ll1, ll2 = sv(.235), sv(.232) if old: lean += 6 # torso transform: lean about the pelvis (forward = -z: rotate +y toward -z = negative x-rotation) Tt = about(pel, rot_axis("x", -lean)) Th = Tt @ about(neck0, rot_axis("x", hpitch)) sh = {s: Tt.pt((s * sw, shy, 0)) for s in (-1, 1)} arms = {} for s, nm in ((-1, ra), (1, la)): tgt, pole = ARM[nm] t = Tt.pt((tgt[0] * s * (sw / .118), sv(tgt[1]) if tgt[1] < 1.0 else tgt[1] * vs, tgt[2])) el, hd = ik3(sh[s], t, la1, la2, Tt.vec((pole[0] * s, pole[1], pole[2]))) arms[s] = (sh[s], el, hd) legs = {} for s, nm in ((-1, rl), (1, ll_)): tgt, pole = LEG[nm] hip = np.array([s * hw, hipy, 0]) ty = hipy + (tgt[1] - .5) if nm in ("ground", "ride") else sv(tgt[1]) t = np.array([tgt[0] * s, ty, tgt[2]]) if nm == "seat": t = np.array([tgt[0] * s, hipy - ll1 * .08, -ll1 * .98]) kn, an = ik3(hip, t, ll1, ll2, np.array([pole[0] * s, pole[1], pole[2]])) if nm == "seat": # rule: on a seat the shins hang straight down from the knees kn = t an = kn + np.array([0, -ll2, .02]) legs[s] = (hip, kn, an)
# ---- body SDFs (built in the body frame; the torso / head pieces in their own frames, then posed) tw = sw * .86
def torso_l(p): # torso frame d = rcone(p, pel + np.array([0, .03, 0]), np.array([0, sv(.715), 0]), hw * 1.05, tw * .95) d = S.smin(d, S.ellipsoid(p, V(0, sv(.735), 0), V(sw + .012, sv(.055), .066 if not female else .07)), .045) if female and not child: d = S.smin(d, S.ellipsoid(p, V(0, sv(.68), -.03), V(tw * .8, .045, .055)), .03) return d torso = posed(torso_l, Tt)
def neck_l(p): return S.capsule(p, neck0 - np.array([0, .02, 0]), HC - np.array([0, hr * .6, 0]), .028 if not child else .032)
def hips_fn(p): return S.rbox(p, V(0, hipy + .005, 0), (hw + .02, .055, .066), .05)
def seg(p, a, b, r1, r2): return rcone(p, a, b, r1, r2)
def arm_upper(p): d = None for s in (-1, 1): a, el, hd = arms[s] e_ = seg(p, a, el, .036, .03) d = e_ if d is None else np.minimum(d, e_) return d
def arm_fore(p): d = None for s in (-1, 1): a, el, hd = arms[s] e_ = seg(p, el, hd, .029, .023) d = e_ if d is None else np.minimum(d, e_) return d
def hands(p): d = None for s in (-1, 1): a, el, hd = arms[s] u = hd - el u /= np.linalg.norm(u) c = hd + u * .022 e_ = S.ellipsoid(p, V(*c), V(.026, .03, .022)) th = S.capsule(p, c, c + np.array([-s * .02, .012, -.012]), .009) e_ = np.minimum(e_, th) d = e_ if d is None else np.minimum(d, e_) return d
def thighs(p): return np.minimum(seg(p, legs[-1][0], legs[-1][1], .058, .046), seg(p, legs[1][0], legs[1][1], .058, .046))
def shins(p): return np.minimum(seg(p, legs[-1][1], legs[-1][2], .045, .036), seg(p, legs[1][1], legs[1][2], .045, .036))
def shoes_fn(p): d = None for s in (-1, 1): kn, an = legs[s][1], legs[s][2] u = an - kn u /= np.linalg.norm(u) fwd = np.array([0, 0, -1.0]) - u * (u[2] * -1) fwd = fwd / max(np.linalg.norm(fwd), 1e-6) c = an + fwd * .03 - u * .0 e_ = S.ellipsoid(p, V(*c), V(.04, .034, .062) if abs(u[1]) > .7 else V(.04, .06, .04)) d = e_ if d is None else np.minimum(d, e_) return d
# garment rules: short sleeves = sleeve to mid upper arm; shorts / skirts / dresses show the shins parts = [] top_fn = [torso] if sleeves == "long": top_fn += [arm_upper, arm_fore] else: top_fn += [_sleeve(arms, .6)] skin_fns = [posed(neck_l, Tt), hands] if sleeves != "long": skin_fns += [arm_upper, arm_fore] bshow_shin = bkind in ("shorts", "skirt", "dress", "tutu") if bkind in ("skirt", "dress", "tutu", "robe"): knee_y = min(legs[-1][1][1], legs[1][1][1]) flare = .09 if bkind != "tutu" else .16 lo = (knee_y + .02) if bkind != "robe" else .06
def skirt(p, lo=lo): q = p - np.array([0, hipy, 0]) spread = max(np.linalg.norm(legs[-1][1][[0, 2]] - legs[1][1][[0, 2]]), .1) top_r, bot_r = hw + .03, max(hw + flare, spread * .55 + .05) h = max(hipy + .06 - lo, .05) t = np.clip((hipy + .06 - p[:, 1]) / h, 0, 1) r = top_r + (bot_r - top_r) * t zc = np.minimum(legs[-1][1][2], legs[1][1][2]) * t * .6 rad = np.sqrt(p[:, 0] ** 2 + ((p[:, 2] - zc) * 1.15) ** 2) d = np.maximum(rad - r, np.maximum(p[:, 1] - (hipy + .06), lo - p[:, 1])) return d * .85 bottom_fns = [hips_fn, skirt] if bkind == "robe": bottom_fns += [thighs, shins] else: skin_fns += [shins, thighs] elif bkind == "shorts": bottom_fns = [hips_fn, lambda p: np.minimum(seg(p, legs[-1][0], legs[-1][0] + (legs[-1][1] - legs[-1][0]) * .6, .062, .055), seg(p, legs[1][0], legs[1][0] + (legs[1][1] - legs[1][0]) * .6, .062, .055))] skin_fns += [shins, thighs] else: bottom_fns = [hips_fn, thighs, shins] U = lambda fs: (lambda p: np.minimum.reduce([f(p) for f in fs])) if full == "dress" or bkind in ("dress",): parts.append(Part(U(top_fn + bottom_fns[:1]), top, k=.02, spec=.2, rough=.6)) parts.append(Part(U(bottom_fns[1:]), top, k=.02, spec=.2, rough=.6)) else: parts.append(Part(U(top_fn), top, k=.02, spec=.2, rough=.6)) parts.append(Part(U(bottom_fns), bottom, k=.02, spec=.15, rough=.7)) if full == "suit": # rule: a suit shows a white shirt V and a tie def vee(p): q = Tt.inv_pts(p) d = S.ellipsoid(q, V(0, sv(.71), -.07), V(.035, .065, .03)) return np.maximum(torso(p) - .004, d) parts.append(Part(vee, (240, 240, 236), spec=.2, rough=.5)) parts.append(Part(lambda p: S.capsule(Tt.inv_pts(p), (0, sv(.755), -.072), (0, sv(.64), -.075), .011), (150, 30, 40), spec=.3, rough=.5)) parts.append(Part(U(skin_fns), skin, k=.015, spec=.25, rough=.45)) parts.append(Part(shoes_fn, shoes, k=.01, spec=.5, rough=.35)) # belt line between top and trousers (not on dresses) if bkind in ("pants", "jeans", "shorts") and full in (None, "outfit", "uniform", "overalls"): parts.append(Part(lambda p: S.rbox(Tt.inv_pts(p), V(0, hipy + .052, 0), (hw + .021, .011, .067), .01), (58, 44, 34), spec=.5, rough=.3))
# ---- head (head frame: centre HC, faces -z), posed by Th head_parts = _head(hr, HC, skin, hair, hlen, bald, e.get("beard"), e.get("expression"), sleep, female, child, old, k) for pt in head_parts: pt.fn = posed(pt.fn, Th) parts += head_parts
# ---- held instruments: drumsticks in the hands if ra == "drum": sticks = [(arms[s][2], arms[s][2] + Tt.vec((0, .02, -.12))) for s in (-1, 1)] parts.append(Part(lambda p: np.minimum(S.capsule(p, *sticks[0], .007), S.capsule(p, *sticks[1], .007)), (210, 180, 130), spec=.4, rough=.4))
# ---- whole-body placement: heading turn, lying down anchors = {"hand": arms[-1][2] + (arms[-1][2] - arms[-1][1]) / np.linalg.norm(arms[-1][2] - arms[-1][1]) * .02, "hands": (arms[-1][2] + arms[1][2]) * .5 + np.array([0, 0, -.03]), "head": Th.pt(HC + np.array([0, hr, 0]))} anchors["hand_top"] = anchors["hand"] if ra in ("guitar_body",): anchors["hand"] = anchors["hands"] = Tt.pt((.06, sv(.6), -.13)) if ra == "drum": anchors["hand"] = anchors["hands"] = Tt.pt((0, sv(.36), -.3)) if ra == "bow": anchors["hand"] = anchors["held"] = Tt.pt((.1, sv(.7), -.12)) if ra == "flute": anchors["hand"] = anchors["hands"] = (arms[-1][2] + arms[1][2]) * .5 two = ra == la and ra in ("hands", "drum", "flute") anchors["held"] = anchors["hands"] if two else anchors["hand"] if ra in ("guitar_body", "drum", "flute"): anchors["held"] = anchors["hand"] anchors["seat"] = np.array([0, hipy - .055, 0]) Troot = Rigid(t=(0, dy, 0)) fac = getattr(inst, "facing", None) if getattr(inst, "turn_to", None) and not yaw: yaw = 38 # rule: people facing each other (talking, sharing, meeting) turn toward one another if yaw and fac in ("left", "right") and name != "ride": Troot = about((0, 0, 0), rot_axis("y", yaw if fac == "left" else -yaw)) @ Troot if name == "lie": # rule: lying = the standing body laid on its side along x (head to one end), resting on y=0 Troot = Rigid(t=(0, -.29, 0)) @ about((0, .5, 0), rot_axis("z", 90 if k % 2 == 0 else -90)) for pt in parts: pt.fn = posed(pt.fn, Troot) anchors = {a: Troot.pt(v) for a, v in anchors.items()} out = Model.of(parts, aspect=.42 if name != "lie" else 1.05, height=1.0 if name != "lie" else .36, anchors=anchors) out.front = "-z" out.grip = {"guitar": .5, "violin": .5, "drum": .0, "umbrella": .05, "cup": .4, "microphone": .55} return out
def _sleeve(arms, frac): def fn(p): d = None for s in (-1, 1): a, el, hd = arms[s] e_ = rcone(p, a, a + (el - a) * frac, .041, .037) d = e_ if d is None else np.minimum(d, e_) return d return fn
def _head(hr, HC, skin, hair, hlen, bald, beard, expr, sleep, female, child, old, k): """head, hair, face; head frame (centre HC, looking along -z)""" c = HC parts = []
def skull(p): d = S.sphere(p, V(*c), hr) d = S.smin(d, S.ellipsoid(p, V(*(c + np.array([0, -hr * .36, -hr * .1]))), V(hr * .74, hr * .64, hr * .8)), hr * .3) # jaw q = p.copy() q[:, 0] = np.abs(q[:, 0]) d = S.smin(d, S.ellipsoid(q, V(*(c + np.array([hr * 1.0, -hr * .05, hr * .05]))), V(hr * .16, hr * .28, hr * .2)), hr * .1) # ears d = S.smin(d, S.ellipsoid(p, V(*(c + np.array([0, -hr * .12, -hr * .98]))), V(hr * .14, hr * .2, hr * .16)), hr * .1) # nose return d parts.append(Part(skull, skin, spec=.3, rough=.4)) # hair: a cap cut by a fringe line; long hair falls behind the shoulders; curly hair is bumpy and big if not bald: def hair_fn(p): q = p - c big = 1.3 if hlen == "curly" else 1.0 cap = S.ellipsoid(p, V(*(c + np.array([0, hr * .16, hr * .1]))), V(hr * 1.1 * big, hr * 1.07 * big, hr * 1.1 * big)) fr = hr * (.62 - 3.0 * np.maximum(np.abs(q[:, 0]) / hr - .35, 0) * .3) * (1.0 if hlen != "curly" else 1.05) cut = -(q[:, 1] - np.where(q[:, 2] < -hr * .15, fr, -hr * .25)) d = np.maximum(cap, cut) if hlen == "long": back = S.rbox(p, V(*(c + np.array([0, -hr * 1.15, hr * .35]))), (hr * 1.08, hr * 1.25, hr * .65), hr * .5) back = np.maximum(back, -(q[:, 2] + hr * .05)) d = S.smin(d, back, hr * .2) if hlen == "curly": d = d * .8 + hr * .12 * (S.noise3(p / hr * 2.2) - .5) return d parts.append(Part(hair_fn, hair, k=hr * .08, spec=.35, rough=.4, tex="fur")) if beard: bc = (206, 204, 200) if old else hair L = 1.5 if beard == "long" else .8
def beard_fn(p): d = S.ellipsoid(p, V(*(c + np.array([0, -hr * (.55 + .2 * L), -hr * .55]))), V(hr * .78, hr * .45 * L + hr * .2, hr * .55)) d = np.maximum(d, -(S.ellipsoid(p, V(*(c + np.array([0, -hr * .35, -hr * .9]))), V(hr * .3, hr * .12, hr * .4)))) return np.maximum(d, (p[:, 1] - (c[1] - hr * .2))) parts.append(Part(beard_fn, bc, k=hr * .1, spec=.15, rough=.8, tex="fur")) parts.append(Part(lambda p: S.capsule(p, c + np.array([-hr * .35, -hr * .3, -hr * .95]), c + np.array([hr * .35, -hr * .3, -hr * .95]), hr * .1), bc, spec=.15, rough=.8)) # eyes / brows / mouth by expression ex = expr or ("happy" if k % 3 != 2 else None) ey = c + np.array([0, hr * .12, -hr * .93]) er = hr * (.13 if not child else .16) dx = hr * .36 if sleep: parts.append(Part(lambda p: np.minimum(S.capsule(p, ey + np.array([-dx - er, -er * .2, 0]), ey + np.array([-dx + er, -er * .2, 0]), er * .28), S.capsule(p, ey + np.array([dx - er, -er * .2, 0]), ey + np.array([dx + er, -er * .2, 0]), er * .28)), (50, 35, 30), spec=.2, rough=.5)) else: big = 1.3 if ex in ("surprised", "scared") else 1.0 parts.append(Part(lambda p: np.minimum(S.ellipsoid(p, V(*(ey + np.array([-dx, 0, 0]))), V(er * .8 * big, er * big, er * .6)), S.ellipsoid(p, V(*(ey + np.array([dx, 0, 0]))), V(er * .8 * big, er * big, er * .6))), (28, 22, 20), spec=1.0, rough=.06)) hl = ey + np.array([er * .3, er * .35, -er * .55]) parts.append(Part(lambda p: np.minimum(S.sphere(p, V(*(hl - np.array([dx, 0, 0]))), er * .28), S.sphere(p, V(*(hl + np.array([dx, 0, 0]))), er * .28)), (255, 255, 255), spec=1.0, rough=.05)) # brows: angle by expression (angry: inner ends down; sad / scared: inner ends up) tilt = {"angry": -.5, "sad": .5, "scared": .45, "crying": .5, "surprised": 0, "shouting": -.35}.get(ex, 0) by_ = ey[1] + er * (2.0 if ex in ("surprised", "scared") else 1.6) bcol = darker(hair, .8) if not bald else darker(skin, .7) bw_ = er * 1.25 br = [] for s in (-1, 1): inner = np.array([s * (dx - bw_ * .9), by_ + tilt * er * .9, ey[2] - er * .1]) outer = np.array([s * (dx + bw_ * .9), by_ - tilt * er * .3, ey[2] + er * .35]) br.append((inner, outer)) parts.append(Part(lambda p: np.minimum(S.capsule(p, *br[0], er * .22), S.capsule(p, *br[1], er * .22)), bcol, spec=.2, rough=.6)) # mouth my = c[1] - hr * .47 mz = c[2] - hr * .9 if ex in ("laughing", "surprised", "shouting", "scared", "crying"): w_, h_ = {"laughing": (.32, .2), "surprised": (.16, .2), "shouting": (.26, .26), "scared": (.22, .12), "crying": (.26, .14)}[ex] parts.append(Part(lambda p: S.ellipsoid(p, V(0, my, mz), V(hr * w_, hr * h_, hr * .12)), (120, 40, 45), spec=.4, rough=.4)) else: cur = {"happy": 1.0, "sad": -1.0, "angry": -.6}.get(ex, .25) R_ = hr * .34
def mouth(p): x, y = p[:, 0], p[:, 1] - (my + cur * R_ * .62) ring = np.abs(np.sqrt(x * x + y * y) - R_ * (.85 if cur > 0 else .75)) - hr * .045 side = (y * np.sign(cur) if cur != 0 else 0) + R_ * .25 if abs(cur) > .3 else np.abs(p[:, 1] - my) - hr * .03 arc = np.maximum(ring, side) if abs(cur) > .3 else np.maximum(np.abs(x) - hr * .22, np.abs(p[:, 1] - my) - hr * .035) return np.maximum(arc, np.abs(p[:, 2] - mz) - hr * .14) parts.append(Part(mouth, (150, 60, 60), spec=.3, rough=.4)) if ex == "crying": parts.append(Part(lambda p: np.minimum(S.capsule(p, ey + np.array([-dx, -er, -er * .3]), ey + np.array([-dx - er * .2, -hr * .55, -er * .1]), er * .2), S.capsule(p, ey + np.array([dx, -er, -er * .3]), ey + np.array([dx + er * .2, -hr * .55, -er * .1]), er * .2)), (140, 200, 250), spec=1, rough=.05)) if (female or child) and ex in ("happy", "laughing", None): parts.append(Part(lambda p: np.maximum(skull(p) - .0015, np.minimum(S.sphere(p, V(*(c + np.array([-hr * .55, -hr * .25, -hr * .75]))), hr * .2), S.sphere(p, V(*(c + np.array([hr * .55, -hr * .25, -hr * .75]))), hr * .2))), (236, 150, 140), spec=.2, rough=.5)) return parts12345678910111213141516171819202122232425262728293031323334353637"""Sky things for the 3D renderer (wave 11: "a wolf howling at the moon" used to drop to the pixel renderer becausethe moon had no 3D model): a full moon (a glowing ball with soft crater patches), a crescent moon (a ball minus anoffset ball), a star (a puffy five-pointed star). Emissive so they read at night. Pure SDFs."""import mathimport numpy as npfrom .models import model, Part, Vfrom . import sdf as S
@model("full moon", "moon", aspect=1.0)def m_moon(col, inst=None): col = col or (246, 238, 205) c = V(0, .5, 0)
def craters(p): f1, f2, _ = S.worley(p * 4.0, 7) return np.maximum(S.sphere(p, c, .502), (f1 - .28) * .3) return [Part(lambda p: S.sphere(p, c, .5), col, spec=.05, rough=.9, emit=.85), Part(craters, tuple(v * .86 for v in col), spec=.05, rough=.9, emit=.75)]
@model("crescent moon", aspect=.8)def m_crescent(col, inst=None): col = col or (250, 236, 170) return [Part(lambda p: np.maximum(S.sphere(p, V(0, .5, 0), .5), -S.sphere(p, V(.24, .58, -.05), .44)), col, spec=.1, rough=.8, emit=.85)]
@model("star", aspect=1.0)def m_star(col, inst=None): col = col or (255, 222, 90) pts = [] for i in range(10): a = math.pi / 2 + i * math.pi / 5 r = .5 if i % 2 == 0 else .22 pts.append((r * math.cos(a), .5 + r * math.sin(a))) return [Part(lambda p: S.extrude2d(p, pts, .05) - .04, col, spec=.4, rough=.3, emit=.5)]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731"""Realism from the statistics of natural images (pure numpy/scipy, no learned weights, no image files).
Real photographs share measurable regularities that clean CG renders lack. This module imposes them in code:
1. Scale invariance: natural images have a ~1/f^2 power spectrum. Surface detail is synthesised with a per-material spectral slope (power ~ f^-slope on the surface) instead of smooth 3-octave value noise. `spectrum()` measures the radially averaged spectrum of a render so the slope can be checked against the 1/f^2 reference.2. Dead leaves (Lee, Mumford & Huang 2001): natural clutter is a stack of occluding objects with a power-law size distribution (p(r) ~ r^-3, which is what makes the result scale invariant). Used for grass blades on the ground, foliage in tree crowns, gravel / aggregate, and the distant tree line.3. Texture synthesis to hand-written statistics (Portilla-Simoncelli style, simplified): per material we write down the spectral slope, orientation anisotropy, octave band limits, cross-scale magnitude coupling and the marginal histogram's skew / kurtosis, then alternate projections (impose subband energies, impose the marginal).4. A physically modelled camera as the last stage: lens distortion + lateral chromatic aberration, lens MTF, natural vignetting, sensor spectral cross-talk, Bayer RGGB mosaic with photon (shot) noise + read noise + ADC quantisation at an ISO picked from the scene light, Malvar-He-Cutler demosaic, white-balance gains and the inverse colour matrix (which colours the noise like a real sensor), raw highlight clipping, partial grey-world auto white balance, and after the tone curve a JPEG-like 4:2:0 + 8x8 DCT quantisation.
Hooks in pydraw3d/__init__.py are guarded by `ON` (set per render: photographic prompts only, never painted styles).All synthesised tiles are periodic, built lazily once per process and cached."""import math, zlibimport numpy as np
ON = False # set by plot3d for each renderFP = 0.004 # current object's footprint: local model units per pixel (set per object by plot3d)RES = 512
_CACHE = {}
# ---------------------------------------------------------------------------------------------------------------# measurement# ---------------------------------------------------------------------------------------------------------------def spectrum(img): """Radially averaged power spectrum of an image's luminance (H, W[, 3], uint8 or float 0..1), Hann-windowed. Returns (f in cycles/pixel, power, fitted slope of log P vs log f over 2/N .. 0.25 c/px).""" a = np.asarray(img, float) if a.max() > 1.5: a = a / 255.0 if a.ndim == 3: a = a[..., :3] @ np.array([.299, .587, .114]) n = min(a.shape) a = a[:n, :n] a = a - a.mean() w = np.hanning(n) a = a * w[:, None] * w[None, :] P = np.abs(np.fft.fftshift(np.fft.fft2(a))) ** 2 yy, xx = np.indices(P.shape) - n // 2 r = np.hypot(xx, yy).astype(int) tot = np.bincount(r.ravel(), P.ravel()) cnt = np.bincount(r.ravel()) k = np.arange(1, n // 2) p = tot[1:n // 2] / np.maximum(cnt[1:n // 2], 1) f = k / n sel = (f >= 2.0 / n) & (f <= .25) slope = np.polyfit(np.log(f[sel]), np.log(p[sel]), 1)[0] return f, p, slope
def band_slopes(img): """Slopes in three bands (low 2/N-.03, mid .03-.12, high .12-.35 c/px): a CG render is typically right at low frequencies (silhouettes) but falls off too fast at high frequencies (smooth surfaces).""" f, p, s = spectrum(img) out = [] for lo, hi in ((2.0 / (2 * len(f)), .03), (.03, .12), (.12, .35)): sel = (f >= lo) & (f <= hi) out.append(float(np.polyfit(np.log(f[sel]), np.log(p[sel]), 1)[0])) return s, out
# ---------------------------------------------------------------------------------------------------------------# synthesis to hand-specified statistics# ---------------------------------------------------------------------------------------------------------------def _freq(N, dim): k = np.fft.fftfreq(N) * N return np.meshgrid(*([k] * dim), indexing="ij")
def _cornish_fisher(z, skew, kurt): """map standard normal samples to a distribution with the given skew and excess kurtosis (Cornish-Fisher)""" return (z + skew / 6 * (z * z - 1) + kurt / 24 * (z ** 3 - 3 * z) - skew * skew / 36 * (2 * z ** 3 - 5 * z))
def _match_hist(x, skew, kurt, rng): """impose the marginal histogram exactly (rank matching to sorted target samples), mean 0, std 1""" t = np.sort(_cornish_fisher(rng.standard_normal(x.size), skew, kurt)) t = (t - t.mean()) / (t.std() + 1e-9) out = np.empty(x.size) out[np.argsort(x.ravel(), kind="stable")] = t return out.reshape(x.shape)
def synth(N=64, dim=3, slope=2.0, aniso=(1, 1, 1), band=(1.0, 16.0), skew=0.0, kurt=0.0, couple=0.0, seed=0, iters=2): """Periodic random field (N^dim) with hand-written statistics, Portilla-Simoncelli style (simplified): - power spectrum ~ k^-(slope + dim - 2) so any 2D slice / the 2D tile itself has power ~ f^-slope (slope 2 = natural images), stretched by `aniso` (features `aniso[i]` times longer along axis i), band-limited to `band` cycles per tile (soft octave edges); - cross-scale magnitude coupling: fine octaves are modulated by the local magnitude of the coarser octaves (edges and clumps co-occur across scales, which Gaussian noise lacks); - marginal skew / excess kurtosis imposed by histogram matching; - alternating projections: re-impose octave x orientation subband energies, then the marginal again.""" rng = np.random.default_rng(seed) K = _freq(N, dim) ka = np.sqrt(sum((k * a) ** 2 for k, a in zip(K, aniso[:dim]))) kr = np.sqrt(sum(k * k for k in K)) lo, hi = band win = np.clip(np.log2(np.maximum(ka, 1e-6) / (lo * .7)) / .5, 0, 1) * np.clip(np.log2(hi * 1.4 / np.maximum(ka, 1e-6)) / .5, 0, 1) A = np.where(ka > 0, np.maximum(ka, .5) ** (-(slope + dim - 2) / 2), 0) * win x = np.real(np.fft.ifftn(np.fft.fftn(rng.standard_normal((N,) * dim)) * A)) x /= x.std() + 1e-9 # octave x orientation subbands (orientation = which axis dominates the frequency vector) octv = np.floor(np.log2(np.maximum(kr, .5))).astype(int) orient = np.argmax(np.stack([np.abs(k) for k in K]), 0) lab = (octv + 2) * dim + orient lab[kr == 0] = 0
def energies(X): return np.bincount(lab.ravel(), (np.abs(X) ** 2).ravel(), minlength=lab.max() + 1)
Et = energies(np.fft.fftn(x)) if couple > 0: # coarse = lower half of the band (in octaves), fine = upper half; |coarse| envelope drives fine magnitude mid = math.sqrt(lo * hi) X = np.fft.fftn(x) coarse = np.real(np.fft.ifftn(X * (ka < mid))) fine = np.real(np.fft.ifftn(X * (ka >= mid))) env = np.abs(coarse) env = np.real(np.fft.ifftn(np.fft.fftn(env) * np.exp(-(kr / (mid * .7)) ** 2))) env = np.clip(env / (env.mean() + 1e-9), 0, 3) x = coarse + fine * env ** couple x /= x.std() + 1e-9 for it in range(iters): x = _match_hist(x, skew, kurt, rng) if it == iters - 1: break X = np.fft.fftn(x) E = energies(X) g = np.sqrt(Et / np.maximum(E, 1e-12)) g[Et == 0] = 1.0 x = np.real(np.fft.ifftn(X * g[lab])) x /= x.std() + 1e-9 return x.astype(np.float32)
def dead_leaves(N=256, dim=2, rmin=1.5, rmax=40.0, shape="disk", aspect=1.0, cover=4.0, seed=0, maxn=60000): """Dead-leaves model on a periodic N^dim grid: leaves (disks / balls / upright blades) with radii drawn from p(r) ~ r^-3 on [rmin, rmax] fall one after another; each pixel shows the first leaf that covers it in front-to-back order. Returns (leaf index per pixel, relative position inside the leaf in [-1,1] along the last axis, normalised radial distance from the leaf centre, number of leaves).""" rng = np.random.default_rng(seed) # radii from the r^-3 law by inverse CDF: F(r) = (rmin^-2 - r^-2) / (rmin^-2 - rmax^-2) vol = N ** dim # enough leaves to cover the plane ~`cover` times u = rng.random(maxn) r = 1.0 / np.sqrt(rmin ** -2 - u * (rmin ** -2 - rmax ** -2)) area = (math.pi if dim == 2 else 4 / 3 * math.pi) * r ** dim * (aspect if dim == 2 else 1.0) n = int(np.searchsorted(np.cumsum(area), cover * vol)) + 1 n = min(n, maxn) r = r[:n] cen = rng.random((n, dim)) * N zbuf = np.full((N,) * dim, n, np.int32) # bin radii so leaves of one bin share a stencil (vectorised minimum.at per bin) rb = np.clip(np.round(r * 2) / 2, rmin, rmax) info = [] for rv in np.unique(rb): idx = np.nonzero(rb == rv)[0] if dim == 2: ry, rx = rv * (aspect if shape == "blade" else 1.0), rv R = int(math.ceil(max(rx, ry))) oy, ox = np.mgrid[-R:R + 1, -R:R + 1] inside = (ox / rx) ** 2 + (oy / ry) ** 2 <= 1.0 if shape == "blade": # upright blade: tapers to a point at the top (narrower with height) tpos = (oy + ry) / (2 * ry) # 0 at the top (y down) ... 1 at the base inside = (np.abs(ox) <= rx * np.clip(tpos, 0, 1) ** .6) & (np.abs(oy) <= ry) offs = np.stack([oy[inside], ox[inside]], -1) else: R = int(math.ceil(rv)) o = np.mgrid[-R:R + 1, -R:R + 1, -R:R + 1].reshape(3, -1).T offs = o[(o ** 2).sum(-1) <= rv * rv] if len(offs) == 0: offs = np.zeros((1, dim), int) ci = np.floor(cen[idx]).astype(np.int64) pos = (ci[:, None, :] + offs[None, :, :]) % N flat = np.ravel_multi_index(tuple(pos[..., d] for d in range(dim)), (N,) * dim) np.minimum.at(zbuf.reshape(-1), flat.ravel(), np.repeat(idx.astype(np.int32), len(offs))) info.append((idx, offs, flat)) # second pass: position of each pixel inside its (visible) leaf rel = np.zeros(vol, np.float32) rad = np.zeros(vol, np.float32) zf = zbuf.reshape(-1) for idx, offs, flat in info: mine = zf[flat] == idx[:, None] rr = r[idx][:, None] ry = rr * (aspect if (shape == "blade" and dim == 2) else 1.0) oy = np.broadcast_to(offs[None, :, 0], flat.shape) rel[flat[mine]] = (oy / ry)[mine] rad[flat[mine]] = (np.sqrt((offs ** 2).sum(-1))[None, :] / rr)[mine] zbuf = np.where(zbuf >= n, 0, zbuf) return zbuf, rel.reshape(zbuf.shape), rad.reshape(zbuf.shape), n
# ---------------------------------------------------------------------------------------------------------------# material table: the hand-written statistics# ---------------------------------------------------------------------------------------------------------------# solid (3D) textures for model surfaces. slope = power-spectrum slope on the surface (2 = natural image),# aniso = feature elongation along local (x, y, z), amp = std of log-albedo, skew / kurt = marginal shape,# couple = cross-scale magnitude coupling, period = tile period in model units (object height = 1),# chroma = log-albedo shift per channel for the second (decorrelated) channel.SOLID = { None: dict(slope=2.0, aniso=(1, 1, 1), amp=.035, skew=0, kurt=0, couple=0, period=1.5, chroma=(.03, 0, -.03)), "fur": dict(slope=1.4, aniso=(1, 5, 1), amp=.11, skew=-.6, kurt=.5, couple=.4, period=.9, chroma=(.04, .01, -.05)), "bark": dict(slope=1.8, aniso=(1, 7, 1), amp=.32, skew=-1.0, kurt=1.0, couple=.8, period=.9, chroma=(.04, 0, -.05)), "stone": dict(slope=2.1, aniso=(1, 1, 1), amp=.22, skew=-.4, kurt=1.5, couple=.6, period=1.2, chroma=(.04, .01, -.04)), "plaster": dict(slope=2.4, aniso=(1, 1, 1), amp=.07, skew=-.3, kurt=.5, couple=.3, period=2.0, chroma=(.02, 0, -.02)), "pores": dict(slope=1.3, aniso=(1, 1, 1), amp=.07, skew=-.8, kurt=1.0, couple=.2, period=.8, chroma=(.03, 0, -.03)), "wood": dict(slope=1.8, aniso=(10, 1, 1), amp=.14, skew=-.5, kurt=.3, couple=.5, period=1.0, chroma=(.04, 0, -.05)), "speckle": dict(slope=2.0, aniso=(1, 2, 1), amp=.08, skew=0, kurt=0, couple=.3, period=1.0, chroma=(.05, -.02, -.03)), "tiles": dict(slope=2.0, aniso=(1, 1, 1), amp=.12, skew=-.5, kurt=.5, couple=.4, period=1.0, chroma=(.04, 0, -.04)), "lumpy": dict(slope=1.9, aniso=(1, 1, 1), amp=.12, skew=-.4, kurt=.5, couple=.5, period=1.0, chroma=(.04, 0, -.04)), "grain": dict(slope=1.4, aniso=(1, 1, 1), amp=.12, skew=.5, kurt=1.0, couple=.3, period=.8, chroma=(.04, 0, -.04)),}# kinds that REPLACE the legacy smooth noise (their legacy look is only fbm); others keep the legacy pattern# (wood rings, roof-tile rows, speckles...) and get the natural statistics on topREPLACE = {None, "fur", "bark", "stone", "plaster", "pores", "lumpy"}
def _solid(kind): key = ("solid", kind) if key not in _CACHE: m = SOLID.get(kind, SOLID[None]) v = synth(64, 3, m["slope"], m["aniso"], (1.0, 24.0), m["skew"], m["kurt"], m["couple"], seed=zlib.crc32(str(kind).encode()) % 997) c = synth(32, 3, 2.4, (1, 1, 1), (1.0, 8.0), 0, 0, 0, seed=zlib.crc32(str(kind).encode()) % 997 + 1) _CACHE[key] = (v, c) return _CACHE[key]
def _foliage(): """3D dead leaves (balls, r^-3 radii) for tree crowns: each leaf cluster its own brightness / hue, darker at its rim (self-shadowing inside the crown)""" if "foliage" not in _CACHE: N = 64 z, rel, rad, n = dead_leaves(N, 3, rmin=1.2, rmax=6.0, cover=3.0, seed=5, maxn=120000) rng = np.random.default_rng(6) lv = rng.standard_normal(n + 1).astype(np.float32) hv = rng.standard_normal(n + 1).astype(np.float32) val = lv[z] * .9 - .3 * rad ** 2 - .25 * rel # rel: -1 top .. 1 bottom of the ball -> lit from above _CACHE["foliage"] = (val - val.mean(), hv[z]) return _CACHE["foliage"]
def _tri(V, u): """periodic trilinear lookup, u in voxel units (M, 3)""" N = V.shape[0] f = np.floor(u) t = (u - f).astype(np.float32) i = f.astype(np.int64) % N j = (i + 1) % N out = 0 for dx in (0, 1): ix = j[:, 0] if dx else i[:, 0] wx = t[:, 0] if dx else 1 - t[:, 0] for dy in (0, 1): iy = j[:, 1] if dy else i[:, 1] wy = t[:, 1] if dy else 1 - t[:, 1] for dz in (0, 1): iz = j[:, 2] if dz else i[:, 2] wz = t[:, 2] if dz else 1 - t[:, 2] out = out + V[ix, iy, iz] * (wx * wy * wz) return out
_ROT = None
def _rot(): global _ROT if _ROT is None: # a fixed irrational rotation so the fine octave lookup doesn't align with the coarse one a, b = .61, 1.13 Ry = np.array([[math.cos(a), 0, math.sin(a)], [0, 1, 0], [-math.sin(a), 0, math.cos(a)]]) Rx = np.array([[1, 0, 0], [0, math.cos(b), -math.sin(b)], [0, math.sin(b), math.cos(b)]]) _ROT = (Ry @ Rx).astype(np.float32) return _ROT
def solid_field(kind, q, seed=0): """zero-mean unit-ish field on model-local points q: two lookups of the 64^3 tile (band 1..24 cycles) 5.3x apart in scale and irrationally rotated give ~7 octaves (1/period .. 127/period cycles per unit) without a visible repeat lattice; the fine lookup fades out where it would alias (finer than the pixel footprint)""" m = SOLID.get(kind, SOLID[None]) V, C = _solid(kind) off = (np.array([.37, .71, .13]) * (seed % 17 + 1) * 64).astype(np.float32) u = q.astype(np.float32) * (64.0 / m["period"]) + off a = _tri(V, u) # scale invariance: for slope 2 the 16x finer copy has the same amplitude; other slopes tilt it w2 = 5.3 ** (-(m["slope"] - 2) / 2) * .85 # rule: fade the fine lookup when its top frequency passes the pixel Nyquist rate (anti-aliasing) fine_cyc = 127.0 / m["period"] # cycles per model unit at the top of the fine lookup nyq = .5 / max(FP, 1e-6) w2 *= float(np.clip(nyq / fine_cyc * 2, 0, 1)) ** .5 b = _tri(V, (u @ _rot()) * 5.3 + off * 3) x = (a + w2 * b) / math.sqrt(1 + w2 * w2) c = _tri(C, u * .5 + off * 2) return x, c
def surface(kind, q, base, seed, legacy): """texture() hook: albedo = base * exp(amp * field) with a correlated hue shift; lognormal reflectance variation (reflectances multiply, so their log is what is Gaussian-like / heavy-tailed in real materials).""" if kind == "leaves": val, hv = _foliage() off = (seed % 13) * 7.3 u = q * (64 / .3) + off # ~4.7 mm voxels on a 1-unit model; trilinear = antialiased leaf edges v = _tri(val, u) h = _tri(hv, u) # leaves: strong per-cluster brightness spread, slight yellow/blue-green hue spread per cluster lg = .38 * v[:, None] + .06 * h[:, None] * np.array([.6, .2, -.9]) x, _ = solid_field("leaves", q, seed) lg = lg + .08 * x[:, None] return base * np.exp(lg - .05) * np.array([1, 1.04, .9]) m = SOLID.get(kind, SOLID[None]) b = base if kind in REPLACE else legacy(kind, q, base, seed) x, c = solid_field(kind, q, seed) lg = m["amp"] * x[:, None] + c[:, None] * np.asarray(m["chroma"], np.float32)[None, :] return b * np.exp(lg - .5 * m["amp"] ** 2)
# ---------------------------------------------------------------------------------------------------------------# ground plane: 2D tiles with mip levels# ---------------------------------------------------------------------------------------------------------------def _mips(T, levels=6): from scipy.ndimage import gaussian_filter out = [T.astype(np.float32)] for k in range(1, levels): s = 2.0 ** (k - 1) if T.ndim == 3: out.append(gaussian_filter(T, (s, s, 0), mode="wrap").astype(np.float32)) else: out.append(gaussian_filter(T, s, mode="wrap").astype(np.float32)) return out
def _bil(T, u): N = T.shape[0] f = np.floor(u) t = (u - f).astype(np.float32) i = f.astype(np.int64) % N j = (i + 1) % N if T.ndim == 3: t = t[:, :, None] return (T[i[:, 0], i[:, 1]] * (1 - t[:, 0]) * (1 - t[:, 1]) + T[j[:, 0], i[:, 1]] * t[:, 0] * (1 - t[:, 1]) + T[i[:, 0], j[:, 1]] * (1 - t[:, 0]) * t[:, 1] + T[j[:, 0], j[:, 1]] * t[:, 0] * t[:, 1]) return (T[i[:, 0], i[:, 1]] * (1 - t[:, 0]) * (1 - t[:, 1]) + T[j[:, 0], i[:, 1]] * t[:, 0] * (1 - t[:, 1]) + T[i[:, 0], j[:, 1]] * (1 - t[:, 0]) * t[:, 1] + T[j[:, 0], j[:, 1]] * t[:, 0] * t[:, 1])
def _mip_lookup(M, u, foot): """u in tile pixels (rows, cols); foot = pixel footprint in tile pixels -> blend two blur levels""" lv = np.clip(np.log2(np.maximum(foot, 1e-3)) + 1, 0, len(M) - 1.001) l0 = np.floor(lv).astype(int) fr = (lv - l0).astype(np.float32) out = None for L in np.unique(l0): s = l0 == L a = _bil(M[L], u[s]) b = _bil(M[L + 1], u[s]) w = fr[s] if a.ndim == 1 else fr[s][:, None] v = a * (1 - w) + b * w if out is None: out = np.zeros((len(u),) + v.shape[1:], np.float32) out[s] = v return out
def _grass_tile(dry=False): """dead-leaves grass: upright tapered blades (r^-3 sizes), each its own brightness and hue, dark at the base (shadowed by the blades in front), bright at the tip; log-albedo + hue as two channels""" key = ("grass", dry) if key not in _CACHE: N = 256 z, rel, rad, n = dead_leaves(N, 2, rmin=1.0, rmax=7.0, shape="blade", aspect=6.0, cover=5.0, seed=11 + dry, maxn=120000) rng = np.random.default_rng(12 + dry) lv = rng.standard_normal(n + 1).astype(np.float32) hv = rng.standard_normal(n + 1).astype(np.float32) lg = .30 * lv[z] + .35 * (-rel) # rel = -1 at the tip, +1 at the base lg = lg - lg.mean() T = np.stack([lg, hv[z] * .5], -1) _CACHE[key] = _mips(T) return _CACHE[key]
def _ps_tile(name, **kw): key = ("ps2", name) if key not in _CACHE: _CACHE[key] = _mips(synth(256, 2, seed=zlib.crc32(name.encode()) % 991, **kw)) return _CACHE[key]
def _gravel_tile(): """aggregate: dead-leaves stones (r^-3, small), each pebble its own tone, shaded like a dome lit from above, dark gaps of binder between them""" if "gravel" not in _CACHE: N = 256 z, rel, rad, n = dead_leaves(N, 2, rmin=1.0, rmax=6.0, cover=1.6, seed=21, maxn=80000) rng = np.random.default_rng(22) lv = rng.standard_normal(n + 1).astype(np.float32) lg = .35 * lv[z] - .3 * rad ** 3 - .15 * rel lg[z == 0] = -.6 _CACHE["gravel"] = _mips(lg - lg.mean()) return _CACHE["gravel"]
def ground(place, q, alb, D, t, f, upm, cam, wallm, ids, studio, seed): """ground-plane hook (shade()): per place, the ground albedo gets natural-statistics detail. q = world points, D = view rays, t = ray distance, f = focal length in pixels, upm = world units per metre.""" upm = max(upm, 1e-3) foot_w = t / f / upm # metres per pixel on a surface facing the camera out = alb.copy() floor = ~wallm & (ids != -3) so = (seed % 7) * 37.0 if place in ("field", "park", "farm", "mountains", "savanna", "forest") and floor.any(): # rule: grass = dead leaves of upright blades in a log-depth ground coordinate: (x, cam*ln z) keeps blades # vertical with the right perspective size, and makes the pixel footprint isotropic (= depth / f) # No single ground coordinate keeps blades both vertical and at their perspective size, so depth is cut into # octave bands; in band k the across coordinate is X * Zk / Z (screen-vertical blades, size right within # +-41%) and neighbouring bands cross-fade (variance-preserving blend of two independent dead-leaves fields). qq = q[floor] Z = np.maximum(qq[:, 2], 1e-3) s = cam * np.log(Z) px = 1.0 / .004 # tile pixels per metre (4 mm per tile pixel) fo = foot_w[floor] * px lz = np.log2(Z / upm) + 8.0 k0 = np.floor(lz) w = (lz - k0).astype(np.float32) M = _grass_tile(place == "savanna") T = 0 for kk, wk in ((k0, 1 - w), (k0 + 1, w)): Zk = upm * 2.0 ** (kk - 8.0) u = np.stack([-s / upm * px + so + kk * 71.3, qq[:, 0] * Zk / Z / upm * px + so + kk * 37.9], -1) T = T + _mip_lookup(M, u, fo) * wk[:, None] T = T / np.sqrt((1 - w) ** 2 + w ** 2)[:, None] lg = T[:, 0:1] * np.array([1.0, 1.0, 1.0]) + T[:, 1:2] * np.array([.10, .02, -.12]) # far away the blades merge: the (blurred) mean stays, the contrast goes (no shimmering) out[floor] = alb[floor] * np.exp(lg * 1.2 - .08) elif place in ("beach", "desert") and floor.any(): # rule: sand = wind ripples (strongly anisotropic, steep spectrum) + grain (white-ish, sparkly marginal) qq = q[floor] px = 1.0 / .01 u = np.stack([qq[:, 2] / upm * px + so, qq[:, 0] / upm * px + so], -1) fo = foot_w[floor] * px * np.clip(t[floor] / np.maximum(cam, 1e-3), 1, 30) ** .5 rip = _mip_lookup(_ps_tile("ripples", slope=2.6, aniso=(1, 6), band=(2, 40), skew=-.6, kurt=.0, couple=.5), u, fo) grn = _mip_lookup(_ps_tile("sandgrain", slope=1.2, aniso=(1, 1), band=(16, 128), skew=.9, kurt=2.0), u * 2, fo * 2) lg = .16 * rip + .10 * grn out[floor] = alb[floor] * np.exp(lg[:, None]) elif place == "snow" and floor.any(): qq = q[floor] px = 1.0 / .02 u = np.stack([qq[:, 2] / upm * px + so, qq[:, 0] / upm * px + so], -1) fo = foot_w[floor] * px * 3 a = _mip_lookup(_ps_tile("snow", slope=2.8, aniso=(1, 1.5), band=(1, 64), skew=-.3, kurt=.5, couple=.3), u, fo) out[floor] = alb[floor] * np.exp(.045 * a[:, None]) elif place == "street" and floor.any(): # rule: asphalt = dead-leaves aggregate (stones in binder) + 1/f stains; pavement slabs get 1/f mottling qq = q[floor] px = 1.0 / .006 u = np.stack([qq[:, 2] / upm * px + so, qq[:, 0] / upm * px + so], -1) fo = foot_w[floor] * px * np.clip(t[floor] / np.maximum(cam, 1e-3), 1, 30) ** .5 gv = _mip_lookup(_gravel_tile(), u, fo) st = _mip_lookup(_ps_tile("stains", slope=2.3, aniso=(1, 1), band=(1, 32), skew=-.8, kurt=1.0, couple=.6), u / 16, fo / 16) lum = alb[floor].mean(-1) dark = lum < .12 # asphalt (pavement and kerbs are brighter) lg = np.where(dark, .30 * gv + .14 * st, .06 * gv + .10 * st) out[floor] = alb[floor] * np.exp(lg[:, None]) elif studio and floor.any(): # tabletop / floorboards: fine wood fibre along x + 1/f stains qq = q[floor] px = 1.0 / .003 u = np.stack([qq[:, 2] / upm * px + so, qq[:, 0] / upm * px + so], -1) fo = foot_w[floor] * px * np.clip(t[floor] / np.maximum(cam, 1e-3), 1, 30) ** .5 fib = _mip_lookup(_ps_tile("fibre", slope=1.7, aniso=(1, 14), band=(2, 96), skew=-.6, kurt=.5, couple=.6), u, fo) st = _mip_lookup(_ps_tile("stains", slope=2.3, aniso=(1, 1), band=(1, 32), skew=-.8, kurt=1.0, couple=.6), u / 20, fo / 20) out[floor] = alb[floor] * np.exp((.18 * fib + .08 * st)[:, None]) if wallm.any(): # walls: faint plaster at 1/f^2.4 (painted walls are almost flat, but never perfectly) qw = q[wallm] px = 1.0 / .01 u = np.stack([qw[:, 1] / upm * px + so, qw[:, 0] / upm * px + so], -1) a = _mip_lookup(_ps_tile("plaster", slope=2.4, aniso=(1, 1), band=(1, 64), skew=-.3, kurt=.5, couple=.3), u, foot_w[wallm] * px) out[wallm] = alb[wallm] * np.exp(.08 * a[:, None]) fac = ids == -3 if fac.any(): # facades: vertical grime streaks (dark-skewed) at 1/f^2 qf = q[fac] px = 1.0 / .03 u = np.stack([qf[:, 1] / upm * px + so, qf[:, 0] / upm * px + so], -1) a = _mip_lookup(_ps_tile("grime", slope=2.0, aniso=(5, 1), band=(1, 64), skew=-1.2, kurt=1.5, couple=.6), u, foot_w[fac] * px) out[fac] = alb[fac] * np.exp(.10 * a[:, None]) return out
def _treeline_tile(): """distant forest: dead leaves of round crowns (r^-3), each crown lit on top and dark below""" if "treeline" not in _CACHE: z, rel, rad, n = dead_leaves(256, 2, rmin=1.0, rmax=10.0, cover=3.0, seed=31, maxn=80000) rng = np.random.default_rng(32) lv = rng.standard_normal(n + 1).astype(np.float32) hv = rng.standard_normal(n + 1).astype(np.float32) lg = .35 * lv[z] - .30 * rel - .2 * rad ** 2 # rel = -1 at a crown's top (lit) .. +1 at its bottom T = np.stack([lg - lg.mean(), hv[z]], -1) _CACHE["treeline"] = _mips(T) return _CACHE["treeline"]
def band(kind, az, up, seed): """landscape-band hook: multiplicative colour factor (M, 3) for far bands (screen-ish coordinates)""" u = np.stack([-up * RES * 1.1 + (seed % 5) * 31, az * RES * 1.1], -1) fo = np.ones(len(az), np.float32) if kind == "trees": T = _mip_lookup(_treeline_tile(), u, fo) return np.exp(T[:, 0:1] * .9 + T[:, 1:2] * np.array([.06, .02, -.08])) if kind == "hills": T = _mip_lookup(_treeline_tile(), u * .5, fo * .5) a = _mip_lookup(_ps_tile("hills", slope=2.0, aniso=(1, 3), band=(1, 64), skew=-.5, kurt=.5, couple=.5), u * .5, fo) return np.exp(T[:, 0:1] * .35 + .10 * a[:, None]) if kind == "rock": a = _mip_lookup(_ps_tile("gullies", slope=2.0, aniso=(4, 1), band=(1, 64), skew=-.8, kurt=1.0, couple=.6), u * .7, fo) return np.exp(.14 * a[:, None]) if kind == "city": a = _mip_lookup(_ps_tile("grime", slope=2.0, aniso=(5, 1), band=(1, 64), skew=-1.2, kurt=1.5, couple=.6), u, fo) return np.exp(.08 * a[:, None]) return 1.0
# ---------------------------------------------------------------------------------------------------------------# camera# ---------------------------------------------------------------------------------------------------------------# sensor spectral cross-talk (rows: sensor R, G, B responses to scene linear sRGB); the camera's colour matrix is its# inverse, which re-saturates colour but also amplifies (and colours) the noise, like a real raw pipelineM_SENSOR = np.array([[.78, .19, .03], [.10, .78, .12], [.03, .22, .75]])WB_RAW = np.array([.52, 1.0, .70]) # raw channel sensitivities under daylight (green has two photosites and most QE)
_MALVAR = None
def _malvar(): global _MALVAR if _MALVAR is None: G_at_RB = np.array([[0, 0, -1, 0, 0], [0, 0, 2, 0, 0], [-1, 2, 4, 2, -1], [0, 0, 2, 0, 0], [0, 0, -1, 0, 0]]) / 8.0 RB_at_G_row = np.array([[0, 0, .5, 0, 0], [0, -1, 0, -1, 0], [-1, 4, 5, 4, -1], [0, -1, 0, -1, 0], [0, 0, .5, 0, 0]]) / 8.0 RB_at_G_col = RB_at_G_row.T RB_at_BR = np.array([[0, 0, -1.5, 0, 0], [0, 2, 0, 2, 0], [-1.5, 0, 6, 0, -1.5], [0, 2, 0, 2, 0], [0, 0, -1.5, 0, 0]]) / 8.0 _MALVAR = (G_at_RB, RB_at_G_row, RB_at_G_col, RB_at_BR) return _MALVAR
def demosaic(m): """Malvar-He-Cutler (2004) gradient-corrected bilinear demosaic of an RGGB mosaic (H, W) -> (H, W, 3)""" from scipy.ndimage import convolve H, W = m.shape G_at_RB, RB_row, RB_col, RB_BR = _malvar() yy, xx = np.indices((H, W)) r = (yy % 2 == 0) & (xx % 2 == 0) b = (yy % 2 == 1) & (xx % 2 == 1) g_rrow = (yy % 2 == 0) & (xx % 2 == 1) # green in a red row g_brow = (yy % 2 == 1) & (xx % 2 == 0) # green in a blue row c_g = convolve(m, G_at_RB, mode="mirror") c_row = convolve(m, RB_row, mode="mirror") c_col = convolve(m, RB_col, mode="mirror") c_br = convolve(m, RB_BR, mode="mirror") R = np.where(r, m, np.where(g_rrow, c_row, np.where(g_brow, c_col, c_br))) G = np.where(r | b, c_g, m) B = np.where(b, m, np.where(g_brow, c_row, np.where(g_rrow, c_col, c_br))) return np.stack([R, G, B], -1)
def camera_linear(col, idm, tm, cmp_, n, tod, place, seed, trace, kx=None): """Physical camera on the linear render (n*n, 3): lens geometry + MTF + vignetting, then the sensor (mosaic, shot + read noise, ADC), demosaic, colour matrix, auto white balance. Object-id / depth / colour-part maps are warped with the same lens so later stages (colour check, painting) stay aligned.""" from scipy.ndimage import map_coordinates, gaussian_filter kx = kx or {} rng = np.random.default_rng(seed * 9973 + 17) img = col.reshape(n, n, 3).astype(np.float64) c = (n - 1) / 2.0 yy, xx = np.indices((n, n)).astype(np.float64) dx, dy = (xx - c) / c, (yy - c) / c r2 = (dx * dx + dy * dy) / 2.0 # 1 at the corners # rule: slight barrel distortion (k1 = 2.5%, corners pinned) + lateral chromatic aberration (R/B scale +-0.07%) k1 = float(kx.get("dist", .025)) sc = (1 + k1 * r2) / (1 + k1) out = np.empty_like(img) for ch, ca in ((0, 1.0007), (1, 1.0), (2, .9993)): sy, sx = c + (yy - c) * sc * ca, c + (xx - c) * sc * ca out[..., ch] = map_coordinates(img[..., ch], [sy, sx], order=1, mode="nearest") sy, sx = np.clip(np.round(c + (yy - c) * sc), 0, n - 1).astype(int), np.clip(np.round(c + (xx - c) * sc), 0, n - 1).astype(int) idm = idm.reshape(n, n)[sy, sx].reshape(-1) tm = tm.reshape(n, n)[sy, sx].reshape(-1) cmp_ = cmp_.reshape(n, n)[sy, sx].reshape(-1) # rule: lens MTF ~ a sharp core plus a faint wide skirt (aberrations / veiling glare): not a plain blur core = gaussian_filter(out, (.35, .35, 0)) skirt = gaussian_filter(out, (3.0, 3.0, 0)) out = core * .97 + skirt * .03 # rule: natural vignetting, half of cos^4 of the field angle (pinhole f = n pixels), as a real lens partly corrects it cos2 = 1.0 / (1.0 + (dx * dx + dy * dy) * (c / n) ** 2) out *= (1 - .5 * (1 - cos2 ** 2))[..., None] # ---- sensor ---- iso = {"night": 1600, "sunset": 400}.get(tod, 100) if place in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office") and tod != "night": iso = 400 # indoor light: the camera raises the gain iso = float(kx.get("iso", iso)) # one output pixel stands for a ~10x10 block of photosites of a real sensor (a 512 px image is a downsampled # photo), so its full well and read noise are those of the block: 300k e- and ~12 e- at ISO 100 # The sensor is simulated at 2x the output resolution (4 photosites per output pixel, then binned 2x2), with # its optical low-pass filter (birefringent plate, ~1 photosite): at 1x the demosaic leaves zipper / false-colour # artefacts on every sharp CG edge, which a downsampled real photo never shows. from scipy.ndimage import zoom, convolve1d fullwell, read_e, headroom = 300000.0 / 4, 12.0 / 2, 4.0 # per photosite; electrons at raw value `headroom` epu = fullwell / headroom * 100.0 / iso # electrons per linear unit out = zoom(out, (2, 2, 1), order=1, mode="nearest") k = np.array([.25, .5, .25]) out = convolve1d(convolve1d(out, k, 0, mode="nearest"), k, 1, mode="nearest") raw = (out @ M_SENSOR.T) * WB_RAW yy2, xx2 = np.indices(raw.shape[:2]) chan = np.where((yy2 % 2 == 0) & (xx2 % 2 == 0), 0, np.where((yy2 % 2 == 1) & (xx2 % 2 == 1), 2, 1)) m = np.take_along_axis(raw, chan[..., None], -1)[..., 0] e = np.clip(m, 0, None) * epu e = e + np.sqrt(e) * rng.standard_normal(e.shape) + read_e * rng.standard_normal(e.shape) # shot + read noise lsb = fullwell / 4096.0 * 100.0 / iso # 12-bit ADC m = np.clip(np.round(e / lsb) * lsb / epu, 0, headroom) # raw clip rgb = demosaic(m) / WB_RAW rgb = rgb.reshape(n, 2, n, 2, 3).mean((1, 3)) # bin 2x2 photosites -> output pixel rgb = rgb @ np.linalg.inv(M_SENSOR).T # rule: highlights that clipped in any raw channel go to white, not to a hue shift (camera highlight recovery) clipped = (rgb.max(-1, keepdims=True) - headroom * .8) / (headroom * .2) w = np.clip(clipped, 0, 1) rgb = rgb * (1 - w) + rgb.max(-1, keepdims=True) * w # rule: partial grey-world auto white balance (cameras pull the average colour toward neutral); only by day, # golden hour and night keep their cast if tod == "day": mean = np.clip(rgb, 0, 2).reshape(-1, 3).mean(0) g = np.clip((mean.mean() / np.maximum(mean, 1e-6)) ** float(kx.get("awb", .15)), .97, 1.03) rgb = rgb * g trace.append("3d: natural camera ISO %d, barrel %.1f%%, Bayer + Malvar demosaic" % (iso, 100 * k1)) return rgb.reshape(-1, 3).astype(np.float32), idm, tm, cmp_
def spectral_sharpen(out, n, gmax=1.5, kx=None): """In-camera sharpening sized by the measured spectral deficit: the luminance spectrum of the image is compared with the 1/f^2 line extrapolated from its own low frequencies (2/N .. .02 c/px); between .02 and .4 c/px each radial frequency gets amplitude gain sqrt(reference / actual), capped at `gmax`, tapered at both ends. Returns (image, mean log10 deficit before).""" kx = kx or {} gmax = float(kx.get("sharp", gmax)) x = np.clip(out, 0, 1).reshape(n, n, 3) Y = x @ np.array([.299, .587, .114]) f, p, _ = spectrum(Y) lo = (f >= 2.0 / n) & (f <= .02) # anchor a slope -2 line at the low band (least squares in log-log with fixed slope) b = np.mean(np.log(p[lo]) + 2 * np.log(f[lo])) ref = np.exp(b - 2 * np.log(f)) g = np.sqrt(np.maximum(ref / np.maximum(p, 1e-12), 1.0)) from scipy.ndimage import uniform_filter1d g = np.exp(uniform_filter1d(np.log(g), 9, mode="nearest")) taper = np.clip((f - .015) / .02, 0, 1) * np.clip((.45 - f) / .1, 0, 1) g = 1 + (np.minimum(g, gmax) - 1) * taper deficit = float(np.mean(np.log10(np.maximum(ref / p, 1e-9))[(f > .03) & (f < .3)])) # apply the radial gain with reflect padding (no wrap-around seams) pad = n // 4 Yp = np.pad(Y, pad, mode="reflect") M = Yp.shape[0] fy = np.fft.fftfreq(M)[:, None] fx = np.fft.fftfreq(M)[None, :] fr = np.sqrt(fx * fx + fy * fy) G = np.interp(fr, f, g, left=1.0, right=1.0) Y2 = np.real(np.fft.ifft2(np.fft.fft2(Yp) * G))[pad:pad + n, pad:pad + n] d = (Y2 - Y)[..., None] # rule: sharpening overshoot is soft-limited (camera JPEG engines clamp halos) d = .05 * np.tanh(d / .05) return np.clip(x + d, 0, 1).reshape(-1, 3), deficit
def jpeg(out, n, quality=88): """JPEG-like quantisation of the display image (n*n, 3, 0..1): YCbCr, 4:2:0 chroma, 8x8 DCT with the standard tables scaled to `quality`. Leaves the faint block/ringing signature real photos carry.""" from scipy.fft import dctn, idctn QL = np.array([[16, 11, 10, 16, 24, 40, 51, 61], [12, 12, 14, 19, 26, 58, 60, 55], [14, 13, 16, 24, 40, 57, 69, 56], [14, 17, 22, 29, 51, 87, 80, 62], [18, 22, 37, 56, 68, 109, 103, 77], [24, 35, 55, 64, 81, 104, 113, 92], [49, 64, 78, 87, 103, 121, 120, 101], [72, 92, 95, 98, 112, 100, 103, 99]], float) QC = np.full((8, 8), 99.0) QC[:4, :4] = [[17, 18, 24, 47], [18, 21, 26, 66], [24, 26, 56, 99], [47, 66, 99, 99]] s = (5000 / quality if quality < 50 else 200 - 2 * quality) / 100.0 QL, QC = np.clip(np.floor(QL * s + .5), 1, 255), np.clip(np.floor(QC * s + .5), 1, 255) x = np.clip(out, 0, 1).reshape(n, n, 3) * 255 Y = x @ np.array([.299, .587, .114]) Cb = 128 + x @ np.array([-.168736, -.331264, .5]) Cr = 128 + x @ np.array([.5, -.418688, -.081312])
def q(ch, Q): h, w = ch.shape H8, W8 = (h + 7) // 8 * 8, (w + 7) // 8 * 8 p = np.pad(ch - 128, ((0, H8 - h), (0, W8 - w)), mode="edge") b = p.reshape(H8 // 8, 8, W8 // 8, 8).transpose(0, 2, 1, 3) d = dctn(b, axes=(2, 3), norm="ortho") d = np.round(d / Q) * Q r = idctn(d, axes=(2, 3), norm="ortho").transpose(0, 2, 1, 3).reshape(H8, W8) return r[:h, :w] + 128
def sub(ch): # 4:2:0 h, w = ch.shape return ch[:h // 2 * 2, :w // 2 * 2].reshape(h // 2, 2, w // 2, 2).mean((1, 3))
def up(ch, h, w): from scipy.ndimage import zoom return zoom(ch, (h / ch.shape[0], w / ch.shape[1]), order=1)[:h, :w]
Y2 = q(Y, QL) Cb2 = up(q(sub(Cb), QC), n, n) Cr2 = up(q(sub(Cr), QC), n, n) R = Y2 + 1.402 * (Cr2 - 128) G = Y2 - .344136 * (Cb2 - 128) - .714136 * (Cr2 - 128) B = Y2 + 1.772 * (Cb2 - 128) return (np.clip(np.stack([R, G, B], -1), 0, 255) / 255.0).reshape(-1, 3)
PHOTO_STYLES = (None, "", "smooth", "photo", "realistic")
def wanted(scene, kx): """photographic prompts only: unstyled 3D renders (and 'realistic' / 'photo'); never painted or pixel styles""" return kx.get("nat", "1") == "1" and scene.get("style") in PHOTO_STYLES12345678910111213141516171819206 unmodified lines2728293031323334357 unmodified lines434445464748495051525354555657585960611 unmodified line6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719815 unmodified lines21421521621721821922022122222322416 unmodified lines241242243244245246247248"""Painting algorithms over the 3D render's buffers (colour, object ids, depth). Pure numpy/scipy, no learnedanything. The 3D renderer gives a clean "reference photo"; these re-paint it the way an artist would:oil : Hertzmann (1998) "Painterly rendering with curved brush strokes of multiple sizes": coarse-to-fine layers,long curved strokes that follow the image's isophotes, placed only where the canvas still differs fromthe reference, bristle texture and canvas weave.watercolor : after Curtis et al. (1997) / Bousseau et al. (2006) in image space: hand-tremor wobble, colourabstraction per region, pigment pooling at edges (edge darkening), granulation, transparent glaze overpaper texture, soft bleeds.sketch : ink contours from id / depth / colour discontinuities + tone hatching (cross-hatching in the darks) on paper.comic : cel shading (3 tones) + bold ink outlines + halftone dots in shadows."""import mathimport numpy as npfrom scipy import ndimage as ndidef _blur(a, s):if s <= 0:return a6 unmodified linesreturn a[..., 0] * .3 + a[..., 1] * .59 + a[..., 2] * .11def _noise(shape, scale, seed):rng = np.random.default_rng(seed)n = rng.random((max(2, shape[0] // scale + 3), max(2, shape[1] // scale + 3)))z = ndi.zoom(n, (shape[0] / (n.shape[0] - 2), shape[1] / (n.shape[1] - 2)), order=3)return z[:shape[0], :shape[1]]7 unmodified linesreturn totdef _edges(ids, depth, img, dthr=.08, cthr=.12):"""Contour mask: object id changes, depth jumps (relative), strong colour edges."""H, W = ids.shapee = np.zeros((H, W), bool)dep = np.where(np.isfinite(depth), depth, 1e4)for ax in (0, 1):a = np.diff(ids, axis=ax) != 0d0 = np.take(dep, range(dep.shape[ax] - 1), axis=ax)d1 = np.take(dep, range(1, dep.shape[ax]), axis=ax)b = np.abs(d0 - d1) / np.minimum(d0, d1) > dthrL = _lum(img)c = np.abs(np.diff(L, axis=ax)) > cthrm = a | b | cif ax == 0:e[:-1] |= melse:1 unmodified linereturn e# ---------------------------------------------------------------- oil (Hertzmann)def _stroke_raster(canvas, pts, r, col, rng, H, W, tex):pts = np.asarray(pts, float)x0, y0 = int(max(0, pts[:, 0].min() - r - 1)), int(max(0, pts[:, 1].min() - r - 1))x1, y1 = int(min(W, pts[:, 0].max() + r + 2)), int(min(H, pts[:, 1].max() + r + 2))if x1 <= x0 or y1 <= y0:returnyy, xx = np.mgrid[y0:y1, x0:x1].astype(float)d = np.full(xx.shape, 1e9)along = np.zeros(xx.shape)acc = 0.0if len(pts) == 1:d = np.hypot(xx - pts[0, 0], yy - pts[0, 1])for i in range(len(pts) - 1):a, b = pts[i], pts[i + 1]ab = b - aL2 = max(ab @ ab, 1e-9)h = np.clip(((xx - a[0]) * ab[0] + (yy - a[1]) * ab[1]) / L2, 0, 1)di = np.hypot(xx - a[0] - h * ab[0], yy - a[1] - h * ab[1])better = di < dd = np.where(better, di, d)along = np.where(better, acc + h * math.sqrt(L2), along)acc += math.sqrt(L2)# rule: soft round brush with a slightly ragged edge and bristle streaks along the strokeacross = d / ralpha = np.clip((1.0 - across) * 3.0, 0, 1) * .92bristle = 1 + tex * (np.sin(across * 9 + rng.random() * 6) * .5 + (rng.random() - .5) * .3)c = np.asarray(col)[None, None, :] * bristle[..., None]sub = canvas[y0:y1, x0:x1]sub += (c - sub) * alpha[..., None]def oil(img, ids, depth, seed=0, scale=1.0):H, W = img.shape[:2]rng = np.random.default_rng(seed)k = H / 512.0 * scaleradii = [max(1.5, r * k) for r in (10, 5, 2.5)]canvas = np.zeros_like(img) + _blur(img, 12 * k).mean((0, 1))[None, None, :]T = .045for li, R in enumerate(radii):ref = _blur(img, .7 * R)Lr = _lum(ref)gy, gx = np.gradient(_blur(Lr, R * .5))diff = np.sqrt(((canvas - ref) ** 2).sum(-1))grid = max(1, int(R))strokes = []for y in range(0, H, grid):for x in range(0, W, grid):cell = diff[y:y + grid, x:x + grid]if li == 0 or cell.mean() > T:iy, ix = np.unravel_index(np.argmax(cell), cell.shape)strokes.append((x + ix, y + iy))rng.shuffle(strokes)maxlen = 10 if li < 2 else 6for (x, y) in strokes:col = ref[y, x].copy()pts = [(x + .5, y + .5)]px, py = x + .5, y + .5ldx, ldy = 0.0, 0.0for n in range(maxlen):ix, iy = int(min(W - 1, max(0, px))), int(min(H - 1, max(0, py)))if n > 2 and np.abs(ref[iy, ix] - col).sum() > np.abs(canvas[iy, ix] - col).sum():breakg = math.hypot(gx[iy, ix], gy[iy, ix])if g < 1e-4:breakdx, dy = -gy[iy, ix] / g, gx[iy, ix] / g # along the isophoteif dx * ldx + dy * ldy < 0:dx, dy = -dx, -dydx, dy = .6 * dx + .4 * ldx if n else dx, .6 * dy + .4 * ldy if n else dynrm = math.hypot(dx, dy) or 1dx, dy = dx / nrm, dy / nrmpx, py = px + R * dx, py + R * dyif not (0 <= px < W and 0 <= py < H):breakpts.append((px, py))ldx, ldy = dx, dyjitter = 1 + (rng.random(3) - .5) * .06_stroke_raster(canvas, pts, R, np.clip(col * jitter, 0, 1), rng, H, W, .07)# rule: canvas weave shows through thin paintyy, xx = np.mgrid[0:H, 0:W]weave = (np.sin(xx * 1.7) * np.sin(yy * 1.7)) * .018 + (_noise((H, W), 3, seed + 5) - .5) * .03out = canvas * (1 + weave[..., None])# rule: impasto light: emboss the paint height (luminance of the strokes) toward the upper-lefthgt = _blur(_lum(canvas), .8)ey, ex = np.gradient(hgt)out = out * (1 + (-ex - ey)[..., None] * 1.2)return np.clip(out, 0, 1)# ---------------------------------------------------------------- watercolordef watercolor(img, ids, depth, seed=0):H, W = img.shape[:2]k = H / 512.0# hand-tremor: displace the image by low-frequency noisedx = (_noise((H, W), int(40 * k) or 1, seed) - .5) * 5 * kdy = (_noise((H, W), int(40 * k) or 1, seed + 1) - .5) * 5 * kyy, xx = np.mgrid[0:H, 0:W].astype(float)coords = [np.clip(yy + dy, 0, H - 1), np.clip(xx + dx, 0, W - 1)]im = np.stack([ndi.map_coordinates(img[..., c], coords, order=1) for c in range(3)], -1)idw = ndi.map_coordinates(ids.astype(float), coords, order=0).astype(int)# colour abstraction: flatten within regions (edge-aware blur: blur, but not across ids)flat = np.zeros_like(im)for v in np.unique(idw):m = (idw == v).astype(float)num = _blur(im * m[..., None], 5 * k)den = _blur(m, 5 * k)[..., None]flat = np.where(m[..., None] > 0, num / np.maximum(den, 1e-4), flat)# keep some tonal shading from the renderbase = flat * .65 + _blur(im, 2 * k) * .35# pigment density: thinner (lighter) paint, darker where pigment pools at region borderse = np.zeros((H, W), bool)e[:-1] |= idw[:-1] != idw[1:]e[:, :-1] |= idw[:, :-1] != idw[:, 1:]edist = ndi.distance_transform_edt(~e)pool = np.exp(-edist / (2.5 * k)) * .55gran = (_fbm((H, W), int(6 * k) or 1, seed + 3) - .5) * .5 + (_noise((H, W), 1, seed + 9) - .5) * .25flow = (_fbm((H, W), int(60 * k) or 1, seed + 4) - .5) * .6 # uneven washesdensity = np.clip(.75 + pool + gran * .5 + flow, .2, 1.6)# Kubelka-Munk-lite: transmittance model, paper white shows through thin paintabsorb = np.clip(1 - base, 0, 1)paper = .96 + (_fbm((H, W), int(8 * k) or 1, seed + 7) - .5) * .06out = paper[..., None] * np.exp(-absorb * 1.6 * density[..., None]) / np.exp(-0.0)# rule: sky/background washes are paler (the subject carries the strongest pigment)bg = (idw < 0)[..., None]out = np.where(bg, 1 - (1 - out) * .7, out)return np.clip(out * np.array([1.0, .995, .975]), 0, 1)# ---------------------------------------------------------------- sketchdef sketch(img, ids, depth, seed=0):H, W = img.shape[:2]k = H / 512.015 unmodified linestone *= np.where(obj, 1.0, .45) # rule: the background is only lightly hatchedpaper = .97 + (_fbm((H, W), int(6 * k) or 1, seed + 2) - .5) * .05g = np.clip(paper - np.clip(ink * 1.4, 0, .9) - tone * .5, 0, 1)out = np.stack([g * .99, g * .97, g * .93], -1)return out# ---------------------------------------------------------------- comic / celdef comic(img, ids, depth, seed=0):H, W = img.shape[:2]k = H / 512.016 unmodified linesout = np.where((dots & shade)[..., None], out * .7, out)e = _edges(ids, depth, img, cthr=.2)e = ndi.binary_dilation(e, iterations=max(1, int(round(1.2 * k))))out = np.where(e[..., None], .06, out)return outSTYLES = {"oil": oil, "watercolor": watercolor, "sketch": sketch, "comic": comic}1234567891011121314151617181920212223242526272829303132336 unmodified lines40414243444546474849507 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192931 unmodified line959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256315 unmodified lines57958058158258358458558658758816 unmodified lines6056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402"""Art styles over the 3D render's buffers (colour, object ids, ray depth). Pure numpy/scipy, no learned anything.The 3D renderer gives a clean "reference photo" plus G-buffers; each style re-paints it the way an artist (or aprinting / craft process) would. Every style is a function f(img, ids, depth, seed) -> img, all arrays HxW(x3),img in [0,1]; ids: >=0 objects, -1 ground, -2 sky, -3 street facades; depth: ray distance (inf = sky).Sources (classic non-photorealistic rendering, re-implemented from the papers' ideas, vectorised):oil / impressionist / pointillism : Hertzmann 1998 (coarse-to-fine layers, refine where the canvas is still wrong),Litwinowicz 1997 (strokes along the isophotes, clipped at edges), Haeberli 1990 (paint by numbers, dabs);strokes are splatted with a jittered-grid / nearest-stroke-wins rasteriser instead of a Python loop.vangogh : line integral convolution (Cabral & Leedom 1993) of noise along isophotes + curl-noise vortices inthe sky (Hays & Essa 2004 style stroke orientation field).watercolor : Curtis et al. 1997 / Bousseau et al. 2006 in image space: transparent pigment layers(transmittance), edge darkening, blooms, granulation, paper white left unpainted, deckled margin.stainedglass: Voronoi pieces (weighted seed density) split at object / colour boundaries, lead came, backlight glow.mosaic : Hausner 2001 / Elber & Wolberg 2003 idea: tile seeds on offset curves of the edges -> Voronoi tilesthat follow contours (opus vermiculatum), grout lines, bevel.lowpoly : Delaunay triangulation of edge + random points, flat facets.ukiyoe : flat traditional pigments, sumi key-block contours, bokashi gradient sky, woodgrain + washi paper.inkwash : sumi-e: few ink tones, wet edges, dry-brush contours, rice paper, red seal.crossstitch : Aida grid, palette (k-means floss colours), two-strand X stitches.riso : spot-colour separation (Beer-Lambert ink densities), rotated halftone screens, misregistration.others : papercut (depth layers + drop shadows), clay (soft re-lit plasticine), charcoal, crayon, blueprint,neon, nouveau (Mucha-style poster), chalkboard, pop (Lichtenstein), sketch, comic, bw, sepia, pastel."""import mathimport numpy as npfrom scipy import ndimage as ndi# ================================================================ helpersdef _blur(a, s):if s <= 0:return a6 unmodified linesreturn a[..., 0] * .3 + a[..., 1] * .59 + a[..., 2] * .11def _noise(shape, scale, seed, sy=None):"""Smooth value noise with feature size `scale` px (sy: different vertical scale = stretched fibres)."""sy = sy or scalerng = np.random.default_rng(seed)n = rng.random((max(2, int(shape[0] // sy) + 3), max(2, int(shape[1] // scale) + 3)))z = ndi.zoom(n, (shape[0] / (n.shape[0] - 2), shape[1] / (n.shape[1] - 2)), order=3)return z[:shape[0], :shape[1]]7 unmodified linesreturn totdef _sat(c, s):m = c.mean(-1, keepdims=True)return np.clip(m + (c - m) * s, 0, 1)def _grid(H, W):return np.mgrid[0:H, 0:W].astype(np.float32)def _smooth(x, a, b):t = np.clip((x - a) / (b - a), 0, 1)return t * t * (3 - 2 * t)def _edges(ids, depth, img, dthr=.08, cthr=.12):"""Contour mask: object id changes, depth jumps (relative), strong colour edges."""H, W = ids.shapee = np.zeros((H, W), bool)dep = np.where(np.isfinite(depth), depth, 1e4)L = _lum(img) if cthr < 9 else Nonefor ax in (0, 1):a = np.diff(ids, axis=ax) != 0d0 = np.take(dep, range(dep.shape[ax] - 1), axis=ax)d1 = np.take(dep, range(1, dep.shape[ax]), axis=ax)m = a | (np.abs(d0 - d1) / np.minimum(d0, d1) > dthr)if L is not None:# rule: colour edges count on objects / facades only; ground texture (meadow flowers, pebbles) would# turn into dotted noiseg = np.take(ids, range(ids.shape[ax] - 1), axis=ax) == -1m |= (np.abs(np.diff(L, axis=ax)) > cthr) & ~gif ax == 0:e[:-1] |= melse:1 unmodified linereturn edef _id_edges(ids):e = np.zeros(ids.shape, bool)e[:-1] |= ids[:-1] != ids[1:]e[:, :-1] |= ids[:, :-1] != ids[:, 1:]return edef _line(e, width, soft=.8):"""Anti-aliased line coverage of width `width` px around the mask e (distance transform)."""d = ndi.distance_transform_edt(~e)return np.clip((width / 2 + soft / 2 - d) / soft, 0, 1)def _region_flat(img, ids, s):"""Edge-aware abstraction: blur within each id region only (normalised convolution)."""out = np.zeros_like(img)for v in np.unique(ids):m = (ids == v)mf = m.astype(np.float32)num = _blur(img * mf[..., None], s)den = _blur(mf, s)[..., None]out[m] = (num / np.maximum(den, 1e-4))[m]return outdef _kmeans(img, k, seed, it=8, mask=None, n=6000):px = img.reshape(-1, 3)if mask is not None:px = px[mask.reshape(-1)]rng = np.random.default_rng(seed)sm = px[rng.integers(0, len(px), min(n, len(px)))]c = sm[rng.choice(len(sm), k, replace=False)]for _ in range(it):lab = ((sm[:, None, :] - c[None]) ** 2).sum(-1).argmin(1)for j in range(k):if (lab == j).any():c[j] = sm[lab == j].mean(0)return cdef _nearest(img, pal, w=(1.0, 1.2, .8)):w = np.asarray(w, np.float32)d = (((img[..., None, :] - pal[None, None]) ** 2) * w).sum(-1)return d.argmin(-1)def _bbox_main(ids):"""Bounding box (y0, y1, x0, x1) of all objects, or None."""m = ids >= 0if not m.any():return Noneys, xs = np.nonzero(m)return ys.min(), ys.max(), xs.min(), xs.max()def _orient(img, s=4.0, fallback=0.0):"""Stroke direction field: the tangent of the isophotes from the smoothed structure tensor; flat areas take thefallback angle. Returns (angle, strength 0..1)."""L = _blur(_lum(img), 1.0)gy, gx = np.gradient(L)jxx, jxy, jyy = _blur(gx * gx, s), _blur(gx * gy, s), _blur(gy * gy, s)th = .5 * np.arctan2(2 * jxy, jxx - jyy) + np.pi / 2 # tangent = gradient + 90 degmag = np.sqrt(jxx + jyy)st = _smooth(mag, .004, .03)# blend with the fallback in doubled-angle space (orientations are mod pi)fb = np.broadcast_to(np.asarray(fallback, np.float32), th.shape)c2 = st * np.cos(2 * th) + (1 - st) * np.cos(2 * fb)s2 = st * np.sin(2 * th) + (1 - st) * np.sin(2 * fb)return .5 * np.arctan2(s2, c2), stdef _normals(depth, ids, s=2.0):"""Approximate image-space normals (x right, y down, z toward camera) from the ray-depth buffer, smoothed withineach object."""H, W = depth.shapez = np.where(np.isfinite(depth), depth, np.nan)zf = np.where(np.isfinite(z), z, np.nanmax(z) if np.isfinite(z).any() else 1.0)zs = np.zeros_like(zf)for v in np.unique(ids):m = (ids == v).astype(np.float32)zs = np.where(m > 0, _blur(zf * m, s) / np.maximum(_blur(m, s), 1e-4), zs)gy, gx = np.gradient(zs)f = float(W)sx, sy = gx * f / np.maximum(zs, 1e-3), gy * f / np.maximum(zs, 1e-3)sx, sy = np.clip(sx, -6, 6), np.clip(sy, -6, 6)sky = ~np.isfinite(depth)sx[sky] = 0sy[sky] = 0n = np.stack([-sx, -sy, np.ones_like(sx)], -1)return n / np.linalg.norm(n, axis=-1, keepdims=True)def _paper(H, W, seed, k, tone=(.965, .95, .915), amt=.05):fib = (_noise((H, W), max(1, int(2 * k)), seed + 71, sy=max(1, int(14 * k))) - .5) * .5 + \(_noise((H, W), max(1, int(14 * k)), seed + 72, sy=max(1, int(2 * k))) - .5) * .5grain = _fbm((H, W), max(1, int(5 * k)), seed + 73) - .5p = 1 + (fib * .6 + grain) * amtreturn np.asarray(tone, np.float32)[None, None] * p[..., None]def _warp(arrs, H, W, amp, scale, seed, orders=None):"""Hand tremor: displace images by low-frequency noise."""dx = (_noise((H, W), max(1, int(scale)), seed) - .5) * 2 * ampdy = (_noise((H, W), max(1, int(scale)), seed + 1) - .5) * 2 * ampyy, xx = _grid(H, W)coords = [np.clip(yy + dy, 0, H - 1), np.clip(xx + dx, 0, W - 1)]out = []for a, o in zip(arrs, orders or [1] * len(arrs)):if a.ndim == 3:out.append(np.stack([ndi.map_coordinates(a[..., c], coords, order=o) for c in range(a.shape[2])], -1))else:out.append(ndi.map_coordinates(a.astype(np.float64), coords, order=o).astype(a.dtype))return outdef _lic(tex, ang, steps, seed=0, h=1.0, vec=None):"""Line integral convolution: average `tex` along the streamlines of the orientation field (nearest-neighbourlookups, direction kept consistent between steps)."""H, W = tex.shape[:2]if vec is None:vx, vy = np.cos(ang), np.sin(ang)else:vx, vy = vecyy, xx = _grid(H, W)acc = tex.astype(np.float32).copy()n = 1for sgn in (1.0, -1.0):px, py = xx.copy(), yy.copy()lx, ly = vx[yy.astype(int), xx.astype(int)] * sgn, vy[yy.astype(int), xx.astype(int)] * sgnfor _ in range(steps):ix = np.clip(px, 0, W - 1).astype(np.int32)iy = np.clip(py, 0, H - 1).astype(np.int32)dx, dy = vx[iy, ix], vy[iy, ix]flip = (dx * lx + dy * ly) < 0dx, dy = np.where(flip, -dx, dx), np.where(flip, -dy, dy)px, py = px + dx * h, py + dy * hlx, ly = dx, dyacc += tex[np.clip(py, 0, H - 1).astype(np.int32), np.clip(px, 0, W - 1).astype(np.int32)]n += 1return acc / ndef _splat(canvas, ref, ids, cell, length, width, ang, seed, mask=None, cols=None, clip_ids=True, tex=.12,alpha=.95, height=None, lenjit=.35):"""Vectorised stroke rasteriser. One stroke per jittered grid cell (centre, direction from `ang`, colour from`ref` or `cols`), capsule shaped (length x width px); every pixel takes the topmost (random priority) stroke thatcovers it, searching the neighbouring cells. clip_ids: a stroke stops at object boundaries (Litwinowicz).Returns the new canvas (and the impasto height map if `height` is given)."""H, W = ref.shape[:2]rng = np.random.default_rng(seed)gh, gw = int(math.ceil(H / cell)) + 1, int(math.ceil(W / cell)) + 1cy = (np.arange(gh)[:, None] + rng.random((gh, gw))) * cellcx = (np.arange(gw)[None, :] + rng.random((gh, gw))) * celliy, ix = np.clip(cy.astype(int), 0, H - 1), np.clip(cx.astype(int), 0, W - 1)th = (ang[iy, ix] if np.ndim(ang) else np.full((gh, gw), ang)) + rng.normal(0, .12, (gh, gw))col = ref[iy, ix] if cols is None else cols(iy, ix, rng)act = np.ones((gh, gw), bool) if mask is None else mask[iy, ix]pri = np.where(act, rng.random((gh, gw)), -1.0).ravel()Ls = (length * (1 + (rng.random((gh, gw)) - .5) * 2 * lenjit)).ravel() / 2Ws = (width * (.85 + rng.random((gh, gw)) * .3)).ravel() / 2cxf, cyf = cx.ravel(), cy.ravel()cs, sn = np.cos(th).ravel(), np.sin(th).ravel()sid = ids[iy, ix].ravel()ph = rng.random(gh * gw) * 6.28nb = int(math.ceil((length * (1 + lenjit) / 2 + width * .6) / cell))# only pixels some active stroke can reach are rasterised (fine layers touch a small part of the canvas)reach = ndi.binary_dilation(act, iterations=nb) if nb > 0 else actyy, xx = _grid(H, W)ci, cj = (yy // cell).astype(np.int32), (xx // cell).astype(np.int32)sel = reach[np.minimum(ci, gh - 1), np.minimum(cj, gw - 1)]pidx = np.nonzero(sel.ravel())[0]xs, ys = xx.ravel()[pidx], yy.ravel()[pidx]ci, cj = ci.ravel()[pidx], cj.ravel()[pidx]idp = ids.ravel()[pidx]n = len(pidx)best = np.full(n, -.5, np.float32)bk = np.zeros(n, np.int64)bd = np.ones(n, np.float32)bv = np.zeros(n, np.float32)for dy in range(-nb, nb + 1):a = np.clip(ci + dy, 0, gh - 1)for dx in range(-nb, nb + 1):kk = a * gw + np.clip(cj + dx, 0, gw - 1)p = pri[kk]cand = np.nonzero(p > best)[0]if not len(cand):continuekc = kk[cand]px, py = xs[cand] - cxf[kc], ys[cand] - cyf[kc]u = px * cs[kc] + py * sn[kc]v = -px * sn[kc] + py * cs[kc]du = np.maximum(np.abs(u) - Ls[kc], 0)d = np.sqrt(du * du + v * v) / Ws[kc]ok = d < 1if clip_ids:ok &= sid[kc] == idp[cand]ci_ = cand[ok]best[ci_] = p[ci_]bk[ci_] = kc[ok]bd[ci_] = d[ok]bv[ci_] = (v / Ws[kc])[ok]cov = best >= 0colf = col.reshape(-1, 3)# rule: bristle streaks run along the stroke (a function of the across-stroke coordinate)bri = 1 + tex * (np.sin(bv * 7.0 + ph[bk]) * .6 + np.sin(bv * 17.0 + ph[bk] * 2) * .4)c = colf[bk] * bri[:, None]a = np.clip((1 - bd) * Ws[bk] / 1.0, 0, 1) * alpha * covout = canvas.reshape(-1, 3).copy()out[pidx] += (c - out[pidx]) * a[:, None]out = out.reshape(canvas.shape)if height is not None:h = ((1 - bd ** 2) * (.85 + .15 * np.sin(bv * 5.0 + ph[bk])) * cov) * width / 10.0hf = height.reshape(-1).copy()hf[pidx] = np.where(a > .5, h, hf[pidx])return out, hf.reshape(height.shape)return outdef _seal(out, H, W, k, seed, corner="br"):"""A red artist's seal (hanko) with carved white strokes."""s = int(34 * k)m = int(16 * k)y0 = H - m - s if corner[0] == "b" else mx0 = W - m - s if corner[1] == "r" else mrng = np.random.default_rng(seed + 99)blk = np.ones((s, s), np.float32)yy, xx = np.mgrid[0:s, 0:s] / sfor _ in range(5): # carved strokes: short horizontal / vertical barsif rng.random() < .5:y, xa, xb = rng.uniform(.2, .8), rng.uniform(.15, .45), rng.uniform(.55, .85)blk[(np.abs(yy - y) < .05) & (xx > xa) & (xx < xb)] = 0else:x, ya, yb = rng.uniform(.2, .8), rng.uniform(.15, .45), rng.uniform(.55, .85)blk[(np.abs(xx - x) < .05) & (yy > ya) & (yy < yb)] = 0blk[(yy < .08) | (yy > .92) | (xx < .08) | (xx > .92)] = 1blk *= (np.random.default_rng(seed).random((s, s)) > .12)red = np.array([.78, .14, .12], np.float32)sub = out[y0:y0 + s, x0:x0 + s]out[y0:y0 + s, x0:x0 + s] = sub * (1 - blk[..., None] * .9) + red * blk[..., None] * .9return out# ================================================================ oildef oil(img, ids, depth, seed=0):"""Rich oil: warm toned ground, three coarse-to-fine layers of long curved strokes along the isophotes (laterlayers only where the canvas still differs from the reference), saturated colour with warm lights and coolshadows, impasto relief lit from the upper left, canvas weave."""H, W = img.shape[:2]k = H / 512.0L = _lum(img)# colour: richer chroma, warm lights, cool (ultramarine) shadowsref = _sat(img, 1.3)ref = ref + (np.array([.06, .03, -.04]) * _smooth(L, .5, .9)[..., None]) + \(np.array([-.04, -.02, .05]) * (1 - _smooth(L, .15, .5))[..., None])ref = np.clip(ref, 0, 1)ang, st = _orient(img, 5 * k, fallback=0.0)ang = ang + (_noise((H, W), int(60 * k) or 1, seed + 3) - .5) * .5 * (1 - st)ground = np.array([.55, .36, .22], np.float32)canvas = _blur(ref, 10 * k) * .6 + ground * .4hgt = np.zeros((H, W), np.float32)for li, (cell, ln, wd) in enumerate(((13, 36, 15), (7, 20, 8), (3.6, 10, 4.2))):cell, ln, wd = cell * k, ln * k, wd * kr = _blur(ref, .5 * wd)# rule (Hertzmann): a finer layer only where the canvas (seen at this brush size) still misses the referenceerr = np.sqrt(((_blur(canvas, .8 * wd) - r) ** 2).sum(-1))mask = None if li == 0 else _blur(err, cell * .5) > (.06 if li == 1 else .08)def cols(iy, ix, rng, r=r):c = r[iy, ix]return np.clip(c * (1 + (rng.random(c.shape[:2] + (1,)) - .5) * .2) + (rng.random(c.shape) - .5) * .08, 0, 1)canvas, hgt = _splat(canvas, r, ids, cell, ln, wd, ang, seed + li * 11, mask=mask, cols=cols,clip_ids=li > 0, tex=.10, height=hgt)# rule: impasto light: emboss the paint relief toward the upper-left light, small specular glints on ridgeshb = _blur(hgt, 1.4 * k)ey, ex = np.gradient(hb)sh = (-ex - ey) * .55out = canvas * (1 + np.clip(sh, -.12, .12)[..., None]) + np.clip(sh - .06, 0, .1)[..., None] * .5yy, xx = _grid(H, W)weave = (np.sin(xx * 1.9 / k) * np.sin(yy * 1.9 / k)) * .02 + (_noise((H, W), 2, seed + 5) - .5) * .03out = out * (1 + weave[..., None] * (1 - _smooth(hgt, 0, .5))[..., None])return np.clip(out, 0, 1)# ================================================================ impressionist (Monet)def impressionist(img, ids, depth, seed=0):"""Monet / Renoir: short broken dabs of vivid unmixed colour, lights warmed toward yellow, shadows colouredviolet-blue (never black), soft edges (strokes cross object boundaries), a light ground showing between dabs."""H, W = img.shape[:2]k = H / 512.0L = _lum(img)ref = _sat(img, 1.35)lights = _smooth(L, .45, .9)[..., None]shadows = (1 - _smooth(L, .1, .5))[..., None]ref = ref * (1 - .25 * lights) + np.array([1, .93, .7]) * .25 * lights * np.maximum(ref.max(-1, keepdims=True), .6)ref = ref * (1 - .45 * shadows) + np.array([.38, .32, .62]) * .45 * shadows * (.5 + L[..., None])ref = np.clip(ref * 1.06, 0, 1)ang, st = _orient(img, 4 * k, fallback=0.15)ang = ang + (_noise((H, W), int(30 * k) or 1, seed + 2) - .5) * .9canvas = np.ones_like(img) * np.array([.92, .88, .78]) * .5 + _blur(ref, 6 * k) * .5def cols(iy, ix, rng, r=ref):c = r[iy, ix]# rule: broken colour: each dab shifts hue a little (swap a bit of energy between channels)jit = (rng.random(c.shape) - .5) * .3return np.clip(c + jit - jit.mean(-1, keepdims=True) * .5, 0, 1)for li, (cell, ln, wd) in enumerate(((10, 18, 10), (6, 12, 6.5), (3.6, 7, 4))):cell, ln, wd = cell * k, ln * k, wd * kr = _blur(ref, .4 * wd)mask = None if li < 2 else _blur(np.sqrt(((canvas - r) ** 2).sum(-1)), cell) > .06canvas = _splat(canvas, r, ids, cell, ln, wd, ang, seed + li * 7, mask=mask, cols=lambda a, b, g, r=r: cols(a, b, g, r),clip_ids=False, tex=.12, alpha=1.0)yy, xx = _grid(H, W)weave = (np.sin(xx * 1.9 / k) * np.sin(yy * 1.9 / k)) * .015return np.clip(canvas * (1 + weave[..., None]), 0, 1)# ================================================================ pointillism (Seurat)POINT_PAL = np.array([[.95, .93, .85], [.98, .85, .2], [.95, .55, .12], [.85, .18, .15], [.88, .4, .6],[.5, .25, .6], [.15, .25, .7], [.25, .55, .85], [.15, .55, .35], [.55, .75, .25],[.35, .22, .15], [.7, .85, .95]], np.float32)def pointillism(img, ids, depth, seed=0):"""Seurat / Signac: round dots of a few pure pigments; each dot picks a pigment at random weighted by how closeit is to the local colour, so neighbouring dots mix optically; light canvas between the dots."""H, W = img.shape[:2]k = H / 512.0ref = _sat(img, 1.25)pal = POINT_PALcanvas = np.ones_like(img) * np.array([.95, .93, .86]) * .7 + _blur(ref, 6 * k) * .3def cols(iy, ix, rng, r=None):c = r[iy, ix]d = ((c[..., None, :] - pal) ** 2).sum(-1)p = np.exp(-d / .012)p /= p.sum(-1, keepdims=True)cum = p.cumsum(-1)pick = (rng.random(c.shape[:2] + (1,)) < cum).argmax(-1)out = pal[pick]# rule: half the dots keep the true local colour, so shapes still read at a distancekeep = rng.random(c.shape[:2]) < .45return np.where(keep[..., None], np.clip(c * 1.05, 0, 1), out * (.85 + .3 * c.mean(-1, keepdims=True)))for li, (cell, wd) in enumerate(((6.5, 7.0), (5.0, 5.6))):r = _blur(ref, 1.2 * k)canvas = _splat(canvas, r, ids, cell * k, 0.0, wd * k, 0.0, seed + li * 5,cols=lambda a, b, g, r=r: cols(a, b, g, r), clip_ids=False, tex=.05, alpha=1.0, lenjit=0)return np.clip(canvas, 0, 1)# ================================================================ van Goghdef vangogh(img, ids, depth, seed=0):"""Van Gogh: thick parallel strokes that flow along the forms (line integral convolution of stroke noise alongthe isophotes), the sky churned by curl-noise vortices, a saturated palette pulled toward cobalt / ultramarine /chrome yellow / viridian, dark blue contour strokes."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)sky = ids == -2ang, st = _orient(img, 6 * k, fallback=0.0)vx, vy = np.cos(ang), np.sin(ang)# curl noise swirls (stream function psi -> velocity (dpsi/dy, -dpsi/dx)) + a few vortices in the skypsi = _fbm((H, W), int(110 * k) or 1, seed + 4, oct=3) * 60 * kyy, xx = _grid(H, W)for _ in range(3):cyv, cxv = rng.uniform(.05, .45) * H, rng.uniform(.1, .9) * Wrr = rng.uniform(.08, .16) * Wpsi = psi + rr * np.exp(-((yy - cyv) ** 2 + (xx - cxv) ** 2) / (2 * rr * rr)) * rng.choice([-1, 1]) * 1.6gy, gx = np.gradient(psi)cvx, cvy = gy, -gxn = np.hypot(cvx, cvy) + 1e-6cvx, cvy = cvx / n, cvy / nw = np.where(sky, .9, .35 * (1 - st))[...]w = _blur(w.astype(np.float32), 3 * k)# align curl to the orientation sign before blendingsgn = np.sign(cvx * vx + cvy * vy + 1e-6)fx, fy = vx * sgn * (1 - w) + cvx * w, vy * sgn * (1 - w) + cvy * wn = np.hypot(fx, fy) + 1e-6fx, fy = fx / n, fy / n# palette pullpal = np.array([[.07, .14, .42], [.15, .3, .7], [.4, .6, .9], [.85, .9, .95], [.98, .85, .2], [.95, .62, .12],[.75, .3, .1], [.1, .4, .3], [.35, .6, .25], [.65, .75, .3], [.55, .35, .2], [.9, .9, .7]], np.float32)ref = _sat(_region_flat(img, ids, 2 * k) * .6 + img * .4, 1.45)q = pal[_nearest(ref, pal)]base = ref * .55 + q * .45# stroke texture: sparse noise smeared along the fieldnoise = (rng.random((H, W)) < .12).astype(np.float32) + rng.random((H, W)) * .3noise = _blur(noise, .6 * k)strokes = _lic(noise, None, int(9 * k) + 3, vec=(fx, fy), h=1.0)strokes = (strokes - strokes.mean()) / (strokes.std() + 1e-6)colsmear = np.stack([_lic(base[..., c], None, int(5 * k) + 2, vec=(fx, fy)) for c in range(3)], -1)# rule: each stroke alternates between a lighter and a darker version of the local colour (paint ridges)out = colsmear * (1 + strokes[..., None] * .16)lighter = np.clip(colsmear * 1.25 + .08, 0, 1)out = np.where((strokes > 1.1)[..., None], lighter, out)# contours in dark ultramarinee = _edges(ids, depth, img, cthr=.25)line = _line(e, 2.6 * k)line = line * (_noise((H, W), int(12 * k) or 1, seed + 8) > .3)out = out * (1 - line[..., None] * .75) + np.array([.08, .12, .35]) * line[..., None] * .75# impasto reliefey, ex = np.gradient(_blur(strokes, .8 * k))out = out * (1 + np.clip(-(ex + ey) * .25, -.15, .15)[..., None])return np.clip(out, 0, 1)# ================================================================ watercolordef watercolor(img, ids, depth, seed=0):"""Transparent watercolour: bright clean washes (colour as transmittance raised to the pigment concentration, sothin paint = paper white), darker pigment pooled at the wet edges, blooms (cauliflower backruns), granulation inthe paper tooth, highlights left unpainted, a graded sky wash, faint pencil underdrawing and a deckledunpainted margin."""H, W = img.shape[:2]k = H / 512.0im, idw = _warp([img, ids], H, W, 2.2 * k, 45 * k, seed, orders=[1, 0])L = _lum(im)flat = _region_flat(im, idw, 4 * k)base = _sat(flat * .7 + _blur(im, 1.5 * k) * .3, 1.55)# rule: pigment colour = the hue at full strength; the wash's lightness comes from concentration, not greypig = np.clip(base / np.maximum(base.max(-1, keepdims=True), .25) * np.clip(base.max(-1, keepdims=True) * 1.1, .35, 1), .02, 1)sky = idw == -2obj = idw >= 0conc = np.clip(.55 + (1 - L) * .9, .3, 1.6)# shadow glaze: a second transparent layer where the render is darker than its regionrel = L / np.maximum(_lum(flat), 1e-3)conc = conc + np.clip(.9 - rel, 0, .6) * 1.2# wet edges: pigment pools inside every wash bordere = _id_edges(idw)edist = ndi.distance_transform_edt(~e)conc = conc + np.exp(-edist / (1.8 * k)) * .55# blooms: backruns push pigment outwards leaving a pale centre and a dark frilly rimbl = _fbm((H, W), int(34 * k) or 1, seed + 11)thr = np.percentile(bl, 80)fr = (_noise((H, W), max(1, int(3 * k)), seed + 12) - .5) * .03rim = np.exp(-np.abs(bl - thr + fr) / .006) * (~sky)conc = conc * np.where(bl > thr, .55, 1.0) + rim * .5# granulation and uneven flowgran = _fbm((H, W), max(1, int(3 * k)), seed + 3) - .5flow = _fbm((H, W), int(70 * k) or 1, seed + 4) - .5conc = conc * (1 + gran * .45 + flow * .5)# highlights left as paperconc = conc * np.where(obj, 1 - _smooth(L, .78, .95) * .9, 1.0)# sky: a graded wash from the top, clouds left whiteyy, xx = _grid(H, W)skyrows = np.where(sky.any(1))[0]hz = skyrows.max() if len(skyrows) else H * .4grad = np.clip(1 - yy / max(hz, 1), 0, 1) ** .8cloud = _smooth(L - _blur(L, 30 * k), .02, .12) * _smooth(L, .75, .95)conc = np.where(sky, (.25 + .95 * grad) * (1 - cloud * .9) * (1 + flow * .8), conc)# background (ground, walls) paler than the subjectconc = np.where((idw < 0) & ~sky, conc * .75, conc)# deckled unpainted margindm = np.minimum(np.minimum(yy, H - 1 - yy), np.minimum(xx, W - 1 - xx)) / (22 * k)conc = conc * _smooth(dm + (_fbm((H, W), int(30 * k) or 1, seed + 5) - .5) * 1.1, .3, .9)conc = np.clip(_blur(conc, .7 * k), 0, 2.2)paper = _paper(H, W, seed, k, tone=(.985, .975, .95), amt=.05)out = paper * np.power(pig, conc[..., None] * .95)# faint pencil underdrawingpe = _line(_edges(idw, depth, im, cthr=9), 1.0 * k) * (_noise((H, W), int(8 * k) or 1, seed + 6) > .35)out = out * (1 - pe[..., None] * .22)return np.clip(out, 0, 1)# ================================================================ sketch (pencil)def sketch(img, ids, depth, seed=0):H, W = img.shape[:2]k = H / 512.015 unmodified linestone *= np.where(obj, 1.0, .45) # rule: the background is only lightly hatchedpaper = .97 + (_fbm((H, W), int(6 * k) or 1, seed + 2) - .5) * .05g = np.clip(paper - np.clip(ink * 1.4, 0, .9) - tone * .5, 0, 1)return np.stack([g * .99, g * .97, g * .93], -1)# ================================================================ comic / celdef comic(img, ids, depth, seed=0):H, W = img.shape[:2]k = H / 512.016 unmodified linesout = np.where((dots & shade)[..., None], out * .7, out)e = _edges(ids, depth, img, cthr=.2)e = ndi.binary_dilation(e, iterations=max(1, int(round(1.2 * k))))return np.where(e[..., None], .06, out)# ================================================================ ukiyo-eUKIYO_PAL = np.array([[.15, .23, .42], [.24, .38, .58], [.55, .69, .76], [.80, .27, .17], [.86, .62, .30],[.17, .15, .14], [.45, .54, .36], [.66, .71, .48], [.85, .60, .55], [.55, .36, .24],[.56, .55, .51], [.93, .89, .78], [.33, .40, .27], [.75, .45, .30]], np.float32)def ukiyoe(img, ids, depth, seed=0):"""Japanese woodblock print (Hokusai / Hiroshige): every region flattened to two tones of a traditional pigmentset (Prussian blue, indigo, vermilion, ochre, sage), a black key-block line, a bokashi (graded) sky from deepPrussian blue to the paper colour, a pink band at the horizon at dusk, woodgrain in the flat colour areas,slight misregistration and washi paper."""H, W = img.shape[:2]k = H / 512.0sky = ids == -2flat = _region_flat(img, ids, 3 * k)L = _lum(img)rel = L / np.maximum(_lum(flat), 1e-3)tone = np.where(rel < .78, .74, np.where(rel > 1.2, 1.12, 1.0))col = _sat(flat, 1.1) * tone[..., None]q = UKIYO_PAL[_nearest(col, UKIYO_PAL)]q = q * .8 + col * .2# bokashi skyyy, xx = _grid(H, W)rows = np.where(sky.any(1))[0]hz = rows.max() + 1 if len(rows) else H * .4t = np.clip(yy / max(hz, 1), 0, 1)skym = img[sky].mean(0) if sky.any() else np.array([.5, .6, .8])warm = skym[0] > skym[2] * 1.05top = np.array([.13, .22, .43])paperc = np.array([.93, .88, .76])band = np.array([.88, .55, .45]) if warm else np.array([.75, .82, .82])g = np.clip(t / .55, 0, 1)skyc = top * (1 - g[..., None]) + paperc * g[..., None]skyc = skyc * (1 - (_smooth(t, .7, .98) * .6)[..., None]) + band * (_smooth(t, .7, .98) * .6)[..., None]# stylised cloud bands: thin horizontal paper-coloured streaks where the render has cloudscl = _smooth(_blur(L, 4 * k) - _blur(L, 25 * k), .015, .06)skyc = skyc * (1 - cl[..., None] * .7) + paperc * cl[..., None] * .7q = np.where(sky[..., None], skyc, q)# water / ground: horizontal pattern lines like carved wave/grass marksgnd = ids == -1marks = (np.abs(((yy + (_noise((H, W), int(30 * k) or 1, seed + 9) - .5) * 14 * k) / (9 * k)) % 1 - .5) < .08) & gndmarks &= _noise((H, W), int(40 * k) or 1, seed + 10, sy=int(6 * k) or 1) > .55q = np.where(marks[..., None], q * .8, q)# woodgrain in flat areasgrain = _noise((H, W), int(40 * k) or 1, seed + 3, sy=max(1, int(2 * k))) - .5q = q * (1 + grain[..., None] * .07)# misregistration: colour block shifted 1px against the key blocksh = max(1, int(round(1.2 * k)))q = np.roll(q, (sh, -sh), axis=(0, 1))# key block lines (sumi)e = _edges(ids, depth, img, dthr=.06, cthr=.22)wv = 1.6 * k + (_noise((H, W), int(20 * k) or 1, seed + 7)) * 1.4 * kd = ndi.distance_transform_edt(~e)line = np.clip((wv - d) / .8, 0, 1)paper = _paper(H, W, seed, k, tone=(.95, .91, .8), amt=.06)out = q * paper / .93out = out * (1 - line[..., None]) + np.array([.12, .1, .1]) * line[..., None]# rule: ink is absorbed by the paper: soften slightly, add fibre speckleout = _blur(out, .45 * k)return np.clip(out, 0, 1)# ================================================================ stained glassdef stainedglass(img, ids, depth, seed=0):"""Stained glass: Voronoi glass pieces (smaller on the subject), split again at object and colour boundaries,each piece one saturated glass colour that glows brighter at its centre (backlit), mottled 'cathedral glass'texture, dark lead came between pieces with a soft halo of light."""from scipy.spatial import cKDTreeH, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)obj = ids >= 0pts = []for sp, m in ((40 * k, ~obj), (18 * k, obj)):gy, gx = np.mgrid[0:H:sp, 0:W:sp]py = gy.ravel() + rng.random(gy.size) * sppx = gx.ravel() + rng.random(gx.size) * spok = (py < H) & (px < W)py, px = py[ok], px[ok]keep = m[py.astype(int), px.astype(int)]pts.append(np.c_[px[keep], py[keep]])pts = np.concatenate(pts)yy, xx = _grid(H, W)P = np.c_[xx.ravel(), yy.ravel()]_, lab = cKDTree(pts).query(P, k=1)lab = lab.reshape(H, W)sm = _blur(img, 2.5 * k)cen = _kmeans(sm, 7, seed)q = _nearest(sm, cen)q = ndi.median_filter(q, size=max(3, int(5 * k) | 1))key = (lab.astype(np.int64) * 64 + (np.clip(ids, -3, 50) + 3)) * 8 + q_, inv = np.unique(key, return_inverse=True)inv = inv.reshape(H, W)n = inv.max() + 1cnt = np.bincount(inv.ravel(), minlength=n)col = np.stack([np.bincount(inv.ravel(), img[..., c].ravel(), minlength=n) for c in range(3)], -1) / np.maximum(cnt, 1)[:, None]# glass colour: saturated, value liftedmx = col.max(-1, keepdims=True)col = _sat(col[None], 1.9)[0]col = col / np.maximum(col.max(-1, keepdims=True), 1e-3) * np.clip(mx * 1.1 + .1, .35, .95)# rule: near-white / grey pieces become pale tinted cathedral glass (amber, sea green, pale blue), never dull greychroma = col.max(-1) - col.min(-1)tints = np.array([[.98, .88, .6], [.75, .9, .8], [.75, .85, .98], [.95, .8, .75]], np.float32)tc = tints[rng.integers(0, 4, n)] * np.clip(mx * 1.05, .4, .95)pale = (chroma < .12)[:, None]col = np.where(pale, tc * .7 + col * .3, col)col = col * (1 + (rng.random((n, 1)) - .5) * .18)c = col[inv]e = _id_edges(inv)d = ndi.distance_transform_edt(~e)lw = 1.7 * kglow = _smooth(d, lw, lw + 9 * k)mott = _fbm((H, W), max(1, int(7 * k)), seed + 2) - .5streak = _noise((H, W), max(1, int(3 * k)), seed + 3, sy=max(1, int(25 * k))) - .5c = c * (.72 + .4 * glow[..., None]) * (1 + (mott * .35 + streak * .15)[..., None])lead = np.clip((lw - d) / .9 + .5, 0, 1)halo = _blur(np.clip(c - .55, 0, 1), 5 * k) * .5out = c + halohl = np.clip(1 - np.abs(d - lw * .4) / (.6 * k), 0, 1) * .12out = out * (1 - lead[..., None]) + (np.array([.07, .07, .08]) + hl[..., None]) * lead[..., None]return np.clip(out, 0, 1)# ================================================================ mosaicdef mosaic(img, ids, depth, seed=0):"""Mosaic: tile seeds laid on offset curves of the image's edges (rows of tesserae follow the contours, as inRoman / Byzantine opus vermiculatum), Voronoi tiles, colours from a limited stone/glass palette, light grout,bevelled tile faces with a little gloss."""from scipy.spatial import cKDTreeH, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)s = 11.0 * ke = _edges(ids, depth, _blur(img, 1.5 * k), cthr=.07)d = ndi.distance_transform_edt(~e)band = np.abs((d % s) - s / 2) < .75ys, xs = np.nonzero(band)cell = s * .82key = (ys / cell).astype(np.int64) * 100000 + (xs / cell).astype(np.int64)order = rng.permutation(len(key))_, first = np.unique(key[order], return_index=True)sel = order[first]pts = np.c_[xs[sel], ys[sel]].astype(np.float32) + rng.random((len(sel), 2)) * .5yy, xx = _grid(H, W)dd, lab = cKDTree(pts).query(np.c_[xx.ravel(), yy.ravel()], k=2)d1, d2 = dd[:, 0].reshape(H, W), dd[:, 1].reshape(H, W)lab = lab[:, 0].reshape(H, W)ref = _sat(_blur(img, 1.0 * k), 1.45)pal = _kmeans(ref, 18, seed)tc = ref[np.clip(pts[:, 1].astype(int), 0, H - 1), np.clip(pts[:, 0].astype(int), 0, W - 1)]tc = pal[_nearest(tc[None], pal)[0]] * .35 + tc * .65tc = tc * (1 + (rng.random((len(tc), 1)) - .5) * .14)c = tc[lab]gap = (d2 - d1)grout_w = 1.0 * kinside = _smooth(gap, grout_w * .6, grout_w * 1.2) * (1 - _smooth(d1, s * .62, s * .8))bevel = _smooth(gap, grout_w, grout_w + 2.5 * k)c = c * (.82 + .18 * bevel[..., None]) * (1 + (_noise((H, W), max(1, int(2 * k)), seed + 4) - .5)[..., None] * .08)gloss = np.clip(1 - np.abs(gap - grout_w - 1.2 * k) / (1.0 * k), 0, 1) * (np.gradient(d1)[0] < 0) * .15c = c + gloss[..., None]grout = np.array([.62, .6, .56]) * (1 + (_noise((H, W), max(1, int(2 * k)), seed + 5) - .5)[..., None] * .1)out = grout * (1 - inside[..., None]) + c * inside[..., None]return np.clip(out, 0, 1)# ================================================================ low polydef lowpoly(img, ids, depth, seed=0):"""Low-poly: Delaunay triangulation of points sampled on the edges (so facets follow silhouettes) plus scatteredpoints (denser on the subject), each triangle filled with its mean colour; facet brightness from the surfacenormal so the planes read."""from scipy.spatial import DelaunayH, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)e = _edges(ids, depth, _blur(img, 1.5 * k), cthr=.08)ey, ex = np.nonzero(e)ne = min(len(ey), int(420 * (1 + (ids >= 0).mean() * 2)))sel = rng.choice(len(ey), ne, replace=False) if len(ey) else []pts = [np.c_[ex[sel], ey[sel]]] if len(ey) else []obj = ids >= 0u = rng.random((2500, 2)) * [W, H]oi = obj[u[:, 1].astype(int), u[:, 0].astype(int)]keep = np.where(oi, rng.random(len(u)) < .35, rng.random(len(u)) < .06)pts.append(u[keep])b = np.linspace(0, 1, 9)pts.append(np.r_[np.c_[b * (W - 1), b * 0], np.c_[b * (W - 1), b * 0 + H - 1], np.c_[b * 0, b * (H - 1)], np.c_[b * 0 + W - 1, b * (H - 1)]])pts = np.concatenate(pts).astype(np.float64)tri = Delaunay(pts)yy, xx = _grid(H, W)s = tri.find_simplex(np.c_[xx.ravel() + .5, yy.ravel() + .5]).reshape(H, W)s = np.where(s < 0, 0, s)n = len(tri.simplices)cnt = np.bincount(s.ravel(), minlength=n)col = np.stack([np.bincount(s.ravel(), img[..., c].ravel(), minlength=n) for c in range(3)], -1) / np.maximum(cnt, 1)[:, None]nm = _normals(depth, ids, 3 * k)lit = np.clip((nm * np.array([-.45, -.6, .66])).sum(-1), 0, 1)lt = np.bincount(s.ravel(), lit.ravel(), minlength=n) / np.maximum(cnt, 1)col = _sat(col[None], 1.15)[0] * (.9 + .2 * lt[:, None])out = col[s]return np.clip(out, 0, 1)# ================================================================ papercutdef papercut(img, ids, depth, seed=0):"""Layered cut paper: the scene split into stacked sheets (sky bands, ground bands by depth, each object, and alighter sheet for its lit part), each a flat paper colour with fibre texture and slightly wobbly hand-cut edges;every sheet casts a soft drop shadow on the sheets behind it."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)im, idw, dep = _warp([img, ids, np.where(np.isfinite(depth), depth, 1e6)], H, W, 1.5 * k, 22 * k, seed, orders=[1, 0, 0])lay = np.zeros((H, W), np.float32)yy, xx = _grid(H, W)sky = idw == -2# sky: 3 horizontal bands with wavy cut edgesrows = np.where(sky.any(1))[0]hz = rows.max() + 1 if len(rows) else 1wav = (_noise((H, W), int(60 * k) or 1, seed + 2) - .5) * 30 * kskyb = np.clip(((yy + wav) / max(hz, 1) * 3).astype(int), 0, 2)lay = np.where(sky, skyb.astype(np.float32), lay)# ground: bands by depth (log), wavy hillsgnd = (idw < 0) & (idw != -3)gnd &= ~skylay = np.where(idw == -3, 8.0 + (_lum(im) > np.median(_lum(im)[idw == -3]) * 1.1 if (idw == -3).any() else 0), lay)if gnd.any():ld = np.log(np.maximum(dep, 1e-3))lo, hi = np.percentile(ld[gnd], 2), np.percentile(ld[gnd], 98)gb = np.clip(((hi - ld + wav / (40 * k) * (hi - lo) * .3) / max(hi - lo, 1e-3) * 4).astype(int), 0, 3)lay = np.where(gnd, 4 + gb.astype(np.float32), lay)# objects: farther first; the lit half of each object is its own sheet on topobjs = [v for v in np.unique(idw) if v >= 0]objs.sort(key=lambda v: -np.median(dep[idw == v]))L = _lum(im)for r, v in enumerate(objs):m = idw == vmed = np.median(L[m])lay = np.where(m, 10 + 2 * r + (L > med * 1.12) * 1.0, lay)lay = ndi.median_filter(lay, size=max(3, int(3 * k) | 1))levels = np.unique(lay)out = np.zeros_like(img)for lv in levels:m = lay == lvc = np.median(im[m], 0)c = _sat(c[None, None], 1.25)[0, 0]c = c * .85 + np.array([.95, .93, .88]) * .15out[m] = c * (1 + (rng.random() - .5) * .06)# drop shadows: every nearer sheet shades the ones behind, offset down-rightsh = np.zeros((H, W), np.float32)off = max(1, int(round(4 * k)))for lv in levels[:-1]:above = (lay > lv).astype(np.float32)s = _blur(np.roll(above, (off, off // 2 + 1), axis=(0, 1)), 3.0 * k)sh = np.where(lay == lv, np.maximum(sh, s * (1 - above)), sh)out = out * (1 - sh[..., None] * .45)# cut edge highlight (paper thickness catching the light on the upper-left edge of each sheet)hi_e = (lay > np.roll(lay, (1, 1), axis=(0, 1))).astype(np.float32)out = out + _blur(hi_e, .6 * k)[..., None] * .12fib = _paper(H, W, seed, k, tone=(1, 1, 1), amt=.07)return np.clip(out * fib, 0, 1)# ================================================================ clay / plasticinedef clay(img, ids, depth, seed=0):"""Claymation: colours simplified to a few saturated plasticine colours, rounded puffy shading from smootheddepth normals (wrap diffuse + soft sheen), fingerprint ripples and small dents, creases where pieces meet, and ashallow-focus miniature-set background."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)obj = ids >= 0sm = _region_flat(img, ids, 2.5 * k)pal = _kmeans(sm, 10, seed, mask=obj if obj.sum() > 200 else None)q = _nearest(sm, pal)q = ndi.median_filter(q, size=max(3, int(7 * k) | 1))alb = _sat(pal[q], 1.55)# rule: plasticine is never dark: lift the albedo's valuealb = alb / np.maximum(alb.max(-1, keepdims=True), 1e-3) * np.clip(alb.max(-1, keepdims=True) * 1.15 + .12, 0, .95)nm = _normals(depth, ids, 6 * k)# fingerprints and dents as bumps on the normalyy, xx = _grid(H, W)bump = (_fbm((H, W), max(1, int(9 * k)), seed + 5) - .5) * 1.2ys, xs = np.nonzero(obj) if obj.any() else (np.array([0]), np.array([0]))for _ in range(14):j = rng.integers(len(ys))r = np.hypot(yy - ys[j], xx - xs[j])bump = bump + np.sin(r / (1.6 * k)) * np.exp(-r / (9 * k)) * .5by, bx = np.gradient(_blur(bump, .8 * k))nb = nm + np.stack([-bx, -by, np.zeros_like(bx)], -1) * .5 * obj[..., None]nb = nb / np.linalg.norm(nb, axis=-1, keepdims=True)l = np.array([-.5, -.6, .62])l = l / np.linalg.norm(l)ndl = (nb * l).sum(-1)wrap = np.clip((ndl + .45) / 1.45, 0, 1)hv = l + np.array([0, 0, 1.0])hv = hv / np.linalg.norm(hv)spec = np.clip((nb * hv).sum(-1), 0, 1) ** 18 * .22# keep the render's cast shadows / AO (ratio of the render to its flattened colour)L = _lum(img)occ = np.clip(_blur(L, 1.5 * k) / np.maximum(_lum(sm), 1e-3), .45, 1.1)shade = (.35 + .75 * wrap) * (occ * .6 + .4)c = alb * shade[..., None] + spec[..., None]# creases where pieces of clay meete = _id_edges(ids)cr = np.exp(-ndi.distance_transform_edt(~e) / (1.3 * k))c = c * (1 - cr[..., None] * .35)# background: soft focus miniature setbg = _blur(_sat(img, 1.15), 3.5 * k)out = np.where(obj[..., None], c, bg)edge = _blur(obj.astype(np.float32), 1.0 * k)[..., None]out = np.where(obj[..., None], out, out * (1 - edge * .3))return np.clip(out, 0, 1)# ================================================================ charcoaldef charcoal(img, ids, depth, seed=0):"""Charcoal on toned paper: smudged tone laid with directional strokes, deposit only on the paper's tooth (grainy),heavy broken contours, white chalk on the highlights, a smudged blank background."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)L = _blur(_lum(img), 1.0 * k)obj = ids >= 0tone = np.clip(1 - L * 1.1, 0, 1) ** 1.15tone = np.where(obj, tone, tone * .45 * (_noise((H, W), int(50 * k) or 1, seed + 2) * .8 + .4))sky = ids == -2tone = np.where(sky, tone * .25, tone)ang, _ = _orient(img, 5 * k, fallback=.7)streak = _lic((rng.random((H, W)) < .2).astype(np.float32), ang, int(8 * k) + 2)streak = (streak - streak.mean()) / (streak.std() + 1e-6)tone = np.clip(tone * (1 + streak * .22), 0, 1)tooth = _fbm((H, W), max(1, int(2.5 * k)), seed + 3) + (rng.random((H, W)) - .5) * .25tooth = (tooth - tooth.min()) / (np.ptp(tooth) + 1e-6)dep_ = np.clip((tone * 1.35 - tooth * .65) / .35, 0, 1)dep_ = _blur(dep_, .5 * k) * .9 + _blur(tone, 3 * k) * .25e = _edges(ids, depth, img, cthr=.14)wv = 1.3 * k + _noise((H, W), int(10 * k) or 1, seed + 4) * 2.2 * kline = np.clip((wv - ndi.distance_transform_edt(~e)) / (.8 * k), 0, 1)line *= np.clip((rng.random((H, W)) * .6 + .6 - tooth * .3), 0, 1)dark = np.clip(dep_ * .85 + line * .9, 0, 1)paper = _paper(H, W, seed, k, tone=(.86, .83, .77), amt=.05)out = paper * (1 - dark[..., None] * .92)chalk = (_smooth(_lum(img), .82, .97) * obj * (tooth > .45))out = out + chalk[..., None] * .2return np.clip(out, 0, 1)# ================================================================ ink wash (sumi-e)def inkwash(img, ids, depth, seed=0):"""Sumi-e ink wash: the subject in three ink tones laid as wet washes (darker wet edges, soft bleeding), adry-brush contour of varying width, the background mostly empty rice paper with a pale distant wash, and a redseal in the corner."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)im, idw = _warp([img, ids], H, W, 1.5 * k, 30 * k, seed, orders=[1, 0])obj = idw >= 0sky = idw == -2L = _lum(_region_flat(im, idw, 2 * k)) * .5 + _lum(_blur(im, 1.5 * k)) * .5c = 1 - Llv = np.where(c > .62, .85, np.where(c > .4, .5, np.where(c > .22, .25, .06)))lv = np.where(obj, lv, np.where(sky, 0.0, lv * .45))# distant ground: only a few soft horizontal washes fading downwardgnd = (idw == -1)yy, xx = _grid(H, W)# rule: the ground is mostly empty paper; only the shadows under the subject and a few horizontal strokesfade = _smooth(_noise((H, W), int(120 * k) or 1, seed + 6, sy=int(10 * k) or 1), .62, .8) * .5near = _blur(obj.astype(np.float32), 18 * k) * 2.5lv = np.where(gnd | (idw == -3), np.where(c > .45, lv * np.clip(near, 0, 1), lv * fade), lv)# wet edges in each tone regionlab = (lv * 10).astype(int) * 100 + np.clip(idw, -3, 90) + 3e = _id_edges(lab)wet = np.exp(-ndi.distance_transform_edt(~e) / (1.5 * k))lvb = _blur(lv, 1.6 * k) * (1 + (_fbm((H, W), max(1, int(6 * k)), seed + 2) - .5) * .5)ink = np.clip(lvb + wet * lv * .35, 0, 1)# dry brush contours on the subjectoe = _edges(idw, depth, im, cthr=.2) & (ndi.binary_dilation(obj, iterations=2))w = (1.0 + 2.5 * _noise((H, W), int(25 * k) or 1, seed + 3)) * kline = np.clip((w - ndi.distance_transform_edt(~oe)) / (.7 * k), 0, 1)ang, _ = _orient(im, 3 * k)dry = _lic((rng.random((H, W)) < .55).astype(np.float32), ang, int(5 * k) + 2)line = line * _smooth(dry, .35, .6)ink = np.clip(np.maximum(ink, line * .95), 0, 1)paper = _paper(H, W, seed, k, tone=(.95, .93, .87), amt=.06)out = paper * (1 - ink[..., None] * np.array([.88, .88, .86]))return np.clip(_seal(out, H, W, k, seed), 0, 1)# ================================================================ crayon / child's drawingCRAYON_PAL = np.array([[.9, .15, .15], [1, .5, .1], [1, .85, .1], [.3, .7, .2], [.1, .45, .2], [.2, .45, .9],[.45, .7, 1], [.5, .25, .7], [1, .5, .7], [.55, .3, .15], [.1, .1, .1], [.55, .55, .55],[.98, .95, .9], [.85, .65, .45]], np.float32)def crayon(img, ids, depth, seed=0):"""A child's crayon drawing: wobbly thick outlines, bright crayon-box colours scribbled back and forth in onedirection per shape (gaps of white paper), the sky a blue strip at the top with a sun in the corner, greenscribble ground, waxy texture caught on the paper grain."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)im, idw = _warp([img, ids], H, W, 6 * k, 55 * k, seed, orders=[1, 0])flat = _region_flat(im, idw, 4 * k)q = CRAYON_PAL[_nearest(_sat(flat, 1.6), CRAYON_PAL)]yy, xx = _grid(H, W)sky = idw == -2gnd = idw == -1obj = idw >= 0# scribble direction per regionang = np.zeros((H, W), np.float32)for v in np.unique(idw):ang[idw == v] = rng.uniform(0, np.pi)ang = np.where(sky, .05, ang)sp = 5.5 * kph = (xx * np.cos(ang + np.pi / 2) + yy * np.sin(ang + np.pi / 2)) / sp + (_noise((H, W), int(20 * k) or 1, seed + 2) - .5) * 2 \+ (_noise((H, W), int(6 * k) or 1, seed + 8) - .5) * 1.2scrib = np.abs(np.sin(ph * np.pi))grain = _fbm((H, W), max(1, int(2 * k)), seed + 3)cov = np.clip((scrib - .25) * 2.0 - (grain - .5) * 1.6, 0, 1)# sky: only a strip at the toprows = np.where(sky.any(1))[0]hz = rows.max() if len(rows) else H * .3skycov = 1 - _smooth(yy / max(hz, 1) + (_noise((H, W), int(40 * k) or 1, seed + 4) - .5) * .25, .25, .4)q = np.where(sky[..., None], np.array([.2, .45, .9]), q)cov = np.where(sky, cov * skycov, cov)q = np.where(gnd[..., None] & (_lum(flat) > .25)[..., None] & (flat[..., 1] > flat[..., 2])[..., None], np.array([.3, .7, .2]), q)cov = np.where(gnd, cov * .85, cov)paper = _paper(H, W, seed, k, tone=(.99, .985, .97), amt=.03)out = paper * (1 - cov[..., None]) + q * cov[..., None]# sun in the top corner if there is sky up thereif sky[:int(H * .3), int(W * .65):].mean() > .6 and _lum(img[sky]).mean() > .45:cx, cy, r = W * .84, H * .14, 32 * krr = np.hypot(xx - cx, yy - cy)a = np.arctan2(yy - cy, xx - cx)sun = (rr < r) * np.clip((np.abs(np.sin(ph * np.pi)) - .1) * 3, 0, 1)rays = (rr > r * 1.25) & (rr < r * 1.9) & (np.abs(((a / (2 * np.pi) * 12) % 1) - .5) < .07)ring = np.abs(rr - r) < 2 * kout = np.where((sun > .3)[..., None], np.array([1, .85, .1]), out)out = np.where((rays | ring)[..., None], np.array([1, .6, .05]), out)# thick wobbly outlines in a darker crayone = _edges(idw, depth, im, cthr=.3)w = 2.2 * k + _noise((H, W), int(15 * k) or 1, seed + 5) * 1.6 * kline = np.clip((w - ndi.distance_transform_edt(~e)) / (.8 * k), 0, 1) * np.clip(1.4 - grain * .9, 0, 1)lc = np.where(obj[..., None], q * .45, np.array([.15, .15, .15]))out = out * (1 - line[..., None]) + lc * line[..., None]return np.clip(out, 0, 1)# ================================================================ blueprintdef blueprint(img, ids, depth, seed=0):"""Blueprint: white technical line work (silhouettes, depth breaks and creases from the normal buffer, detailedges finer) on Prussian-blue paper with a drafting grid, centre lines, dimension lines with arrowheads aroundthe subject, a double border and a title block."""H, W = img.shape[:2]k = H / 512.0yy, xx = _grid(H, W)bg = np.array([.09, .27, .55]) * (1 + (_fbm((H, W), int(40 * k) or 1, seed) - .5)[..., None] * .12)g1 = (np.minimum(yy % (16 * k), xx % (16 * k)) < .8 * k).astype(np.float32) * .1g2 = (np.minimum(yy % (80 * k), xx % (80 * k)) < 1.0 * k).astype(np.float32) * .12ink = np.maximum(g1, g2)nm = _normals(depth, ids, 1.5 * k)ny, nx = np.gradient(nm[..., 0])[0], np.gradient(nm[..., 1])[1]crease = (np.hypot(ny, nx) > .18) & (ids >= 0)e = _edges(ids, depth, img, dthr=.05, cthr=9) | (_id_edges(ids) & (ids != -2))main = _line(e, 1.7 * k)det = _line(crease | (_edges(ids, depth, _blur(img, 1), dthr=9, cthr=.12) & (ids >= 0)), 1.0 * k) * .6ink = np.maximum(ink, np.maximum(main, det))# faint hatch fill on the objectshat = (np.abs(((xx + yy) / (7 * k)) % 1 - .5) < .07) & (ids >= 0)ink = np.maximum(ink, hat * .18)bb = _bbox_main(ids)if bb is not None:y0, y1, x0, x1 = [float(v) for v in bb]m = 10 * klw = .7 * kdef hline(y, a, b, w=lw):return ((np.abs(yy - y) < w) & (xx >= a) & (xx <= b)).astype(np.float32)def vline(x, a, b, w=lw):return ((np.abs(xx - x) < w) & (yy >= a) & (yy <= b)).astype(np.float32)dy = min(y1 + 2.5 * m, H - 6 * m)dx = min(x1 + 2.5 * m, W - 6 * m)dims = hline(dy, x0, x1) + vline(x0, y1 + m * .5, dy + m * .6) + vline(x1, y1 + m * .5, dy + m * .6)dims += vline(dx, y0, y1) + hline(y0, x1 + m * .5, dx + m * .6) + hline(y1, x1 + m * .5, dx + m * .6)# arrowheads (small triangles)for (ax, ay, sx, sy) in ((x0, dy, 1, 0), (x1, dy, -1, 0), (dx, y0, 0, 1), (dx, y1, 0, -1)):u = (xx - ax) * sx + (yy - ay) * syv = np.abs((xx - ax) * sy - (yy - ay) * sx)dims += ((u >= 0) & (u < 3 * m / 4) & (v < u * .3 + .3)).astype(np.float32)# dash-dot centre linecxl = (x0 + x1) / 2dash = ((yy % (14 * k)) < 8 * k) | (np.abs((yy % (14 * k)) - 11 * k) < 1 * k)dims += vline(cxl, y0 - m, y1 + m, .5 * k) * dashink = np.maximum(ink, np.clip(dims, 0, 1) * .85)# border + title blockb1 = 8 * kfr = ((np.minimum(np.minimum(yy, H - 1 - yy), np.minimum(xx, W - 1 - xx)) - b1) ** 2 < (1 * k) ** 2)tb = (xx > W * .66) & (yy > H * .86) & (xx < W - b1) & (yy < H - b1)tbl = tb & ((np.abs(xx - W * .66) < 1 * k) | (np.abs(yy - H * .86) < 1 * k) | (np.abs(yy - H * .92) < .6 * k) | (np.abs(xx - W * .82) < .6 * k))ticks = tb & (np.abs(((xx - W * .67) / (5 * k)) % 1 - .5) < .2) & (np.abs(yy - H * .89) < 1.2 * k) & (xx < W * .8)ink = np.maximum(ink, (fr | tbl).astype(np.float32) * .9)ink = np.maximum(ink, ticks * .6)ink = _blur(ink, .35 * k) * (1 - (_noise((H, W), max(1, int(2 * k)), seed + 3) - .5) * .25)out = bg * (1 - ink[..., None]) + np.array([.92, .95, 1.0]) * ink[..., None]return np.clip(out, 0, 1)# ================================================================ neon line artdef neon(img, ids, depth, seed=0):"""Neon sign line art: the scene almost black, every contour a glowing gas tube in its object's colour pushed tofull saturation (white-hot core, coloured bloom at three radii), the horizon a cyan tube."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)obj = ids >= 0hues = np.array([[1, .2, .6], [.1, .9, 1], [1, .85, .2], [.6, .3, 1], [.3, 1, .4], [1, .45, .1]], np.float32)col = np.zeros_like(img)for j, v in enumerate(np.unique(ids)):m = ids == vc = np.median(img[m], 0)mx, mn = c.max(), c.min()if v < 0:c = np.array([.1, .9, 1.0]) if v == -1 else np.array([.6, .3, 1.0])elif mx - mn < .12:c = hues[(j + seed) % len(hues)]else:c = (c - mn) / (mx - mn + 1e-6)c = np.clip(c * .9 + .1, 0, 1)col[m] = ce = _edges(ids, depth, img, cthr=9)det = _edges(ids, depth, _blur(img, 1.0), dthr=9, cthr=.16) & objcore = _line(e, 2.2 * k)core2 = _line(det, 1.4 * k) * .7tube = np.maximum(core, core2)# dilate colour so a line on the boundary takes the object's colourbig = ndi.grey_dilation(np.where(obj, ids, -9), size=max(3, int(5 * k) | 1))colx = col.copy()upd = (big >= 0) & ~objif upd.any():uid = np.unique(big[upd])for v in uid:mm = upd & (big == v)colx[mm] = col[ids == v][0] if (ids == v).any() else col[mm]lc = colx * tube[..., None]glow = _blur(lc, 2.5 * k) * 1.6 + _blur(lc, 7 * k) * 1.6 + _blur(lc, 18 * k) * 1.2base = _blur(_lum(img), 2 * k)[..., None] * np.array([.05, .05, .1])wall = (1 + (_fbm((H, W), int(6 * k) or 1, seed) - .5) * .4)[..., None]out = base * wall + glow + lc * .6 + (tube ** 2)[..., None] * .55# flicker: a few tube segments slightly dimmerout = out * (1 - (_noise((H, W), int(40 * k) or 1, seed + 1) > .78)[..., None] * .25)return np.clip(out, 0, 1)# ================================================================ cross-stitch / embroiderydef crossstitch(img, ids, depth, seed=0):"""Cross-stitch: the picture reduced to a grid of stitches in a small set of floss colours (k-means), each cell anX of two thread strands (the top strand over the bottom one, round thread shading, twisted fibres), on Aida clothwith its holes; near-white cells are left as bare fabric."""H, W = img.shape[:2]k = H / 512.0cs = max(4, int(round(8 * k)))gh, gw = H // cs, W // cssm = img[:gh * cs, :gw * cs].reshape(gh, cs, gw, cs, 3).mean((1, 3))pal = _kmeans(_sat(sm, 1.2), 14, seed, n=4000)q = _nearest(_sat(sm, 1.2), pal)fl = pal[q]fabric = np.array([.93, .91, .85])bare = (np.abs(fl - fabric).sum(-1) < .14)yy, xx = _grid(H, W)gi, gj = np.minimum((yy // cs).astype(int), gh - 1), np.minimum((xx // cs).astype(int), gw - 1)u, v = (xx % cs) / cs, (yy % cs) / csc = fl[gi, gj]b = bare[gi, gj]w = .2d1 = np.abs(u - v) / math.sqrt(2) # top strand "\"d2 = np.abs(u + v - 1) / math.sqrt(2) # bottom strand "/"in1, in2 = d1 < w, d2 < wprof1 = np.sqrt(np.clip(1 - (d1 / w) ** 2, 0, 1))prof2 = np.sqrt(np.clip(1 - (d2 / w) ** 2, 0, 1))tw1 = 1 + .12 * np.sin(((u + v) * 9 + d1 * 30) * np.pi)tw2 = 1 + .12 * np.sin(((u - v) * 9 + d2 * 30) * np.pi)s2 = c * (.55 + .5 * prof2[..., None]) * tw2[..., None]s1 = c * (.6 + .55 * prof1[..., None]) * tw1[..., None]# fabric with weave and holes at the cell cornersweave = 1 + (np.sin(xx * np.pi / (cs / 4)) * np.sin(yy * np.pi / (cs / 4))) * .03hole = np.hypot(np.minimum(u, 1 - u), np.minimum(v, 1 - v)) < .09fab = fabric * weave[..., None] * np.where(hole, .72, 1.0)[..., None]out = fabst = ~bshadow = (d1 < w * 1.5) & ~in1 & in2out = np.where((in2 & st)[..., None], s2 * np.where(shadow, .8, 1.0)[..., None], out)out = np.where((in1 & st)[..., None], s1, out)return np.clip(out, 0, 1)# ================================================================ art nouveau posterNOUVEAU_PAL = np.array([[.93, .87, .72], [.85, .72, .50], [.78, .60, .32], [.62, .66, .50], [.42, .50, .38],[.80, .55, .48], [.62, .33, .26], [.36, .42, .50], [.55, .62, .66], [.30, .24, .20],[.95, .80, .60], [.70, .48, .55]], np.float32)def nouveau(img, ids, depth, seed=0):"""Art nouveau poster (Mucha): flat muted colours, a thick flowing brown contour, the background replaced by acream panel with a large gold halo ring and radiating lines behind the subject, an ornamental frame with anarched top and whiplash vine curves in the corners."""H, W = img.shape[:2]k = H / 512.0yy, xx = _grid(H, W)obj = ids >= 0sky = ids == -2flat = _region_flat(img, ids, 3 * k)rel = _lum(img) / np.maximum(_lum(flat), 1e-3)tone = np.where(rel < .8, .82, 1.0)q = NOUVEAU_PAL[_nearest(flat * tone[..., None], NOUVEAU_PAL)] * .75 + flat * tone[..., None] * .25bb = _bbox_main(ids)if bb is not None:y0, y1, x0, x1 = bbcx, cy = (x0 + x1) / 2, y0 + (y1 - y0) * .4R = max(y1 - y0, x1 - x0) * .62 + 20 * kelse:cx, cy, R = W / 2, H * .4, W * .3rr = np.hypot(xx - cx, yy - cy)an = np.arctan2(yy - cy, xx - cx)bgc = np.where((rr < R)[..., None], np.array([.86, .78, .58]), np.array([.93, .88, .74]))rays = (rr > R) & (np.abs(((an / (2 * np.pi) * 36) % 1) - .5) < .08)bgc = np.where(rays[..., None], np.array([.88, .8, .62]), bgc)ring = (np.abs(rr - R) < 5 * k) | (np.abs(rr - R * .9) < 1.5 * k)bgc = np.where(ring[..., None], np.array([.76, .58, .27]), bgc)dots = (np.abs(rr - R * .95) < 2.2 * k) & (np.abs(((an / (2 * np.pi) * 48) % 1) - .5) < .18)bgc = np.where(dots[..., None], np.array([.42, .5, .38]), bgc)q = np.where(sky[..., None], bgc, q)# contours: smooth thick browne = _edges(ids, depth, img, cthr=.22)d = ndi.distance_transform_edt(~e)w = np.where(_blur(obj.astype(np.float32), 2) > .02, 2.4 * k, 1.4 * k)line = np.clip((w - d) / .8, 0, 1)out = q * (1 - line[..., None]) + np.array([.28, .19, .13]) * line[..., None]# ornamental frame: outer border, inner gold line, arched top panelbd = 14 * kdist_b = np.minimum(np.minimum(yy, H - 1 - yy), np.minimum(xx, W - 1 - xx))arch_r = W / 2 - bd * 1.6arch_cy = bd * 1.6 + arch_r * .55in_arch = np.where(yy < arch_cy, np.hypot((xx - W / 2), (yy - arch_cy) * 1.8) < arch_r, True)frame = (dist_b < bd) | ~in_arch# whiplash vines in the corners outside the archvine = np.zeros((H, W), bool)for sx in (1, -1):ox = W / 2 - sx * W / 2t = np.linspace(0, 1, 400)px = ox + sx * (bd + t * W * .32 + np.sin(t * 9) * 10 * k)py = bd + t * arch_cy * .9 + np.cos(t * 7) * 12 * kfrom scipy.spatial import cKDTreetr = cKDTree(np.c_[px, py])dd, _ = tr.query(np.c_[xx.ravel(), yy.ravel()], k=1, distance_upper_bound=4 * k)vine |= (dd.reshape(H, W) < 1.6 * k)fc = np.array([.42, .5, .38]) * (1 + (_noise((H, W), int(8 * k) or 1, seed) - .5)[..., None] * .1)out = np.where(frame[..., None], fc, out)out = np.where((frame & vine)[..., None], np.array([.78, .62, .32]), out)fl = (np.abs(dist_b - bd) < 1.4 * k) | (~in_arch & (dist_b >= bd) & ndi.binary_dilation(in_arch, iterations=max(1, int(2 * k))))out = np.where(fl[..., None], np.array([.78, .6, .3]), out)out = np.where((dist_b < 2 * k)[..., None], np.array([.28, .19, .13]), out)return np.clip(out * _paper(H, W, seed, k, tone=(1, 1, 1), amt=.05), 0, 1)# ================================================================ risographRISO_INKS = np.array([[1.0, .36, .62], [.0, .47, .75], [1.0, .86, .1]], np.float32)def riso(img, ids, depth, seed=0):"""Risograph print: the image separated into three fluorescent spot inks (Beer-Lambert densities), each printed asa rotated halftone screen, slightly misregistered, with ink grain and overprinting (multiply) on off-white paper."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)A = -np.log(np.clip(RISO_INKS, .03, 1)).T # channels x inkst = -np.log(np.clip(_blur(img, .8 * k), .04, 1)).reshape(-1, 3)dens = np.clip(np.linalg.lstsq(A, t.T, rcond=None)[0].T * 1.35, 0, 1.6).reshape(H, W, 3)yy, xx = _grid(H, W)cs = 5.2 * kpaper = _paper(H, W, seed, k, tone=(.97, .955, .93), amt=.04)out = paper.copy()for i, deg in enumerate((15, 75, 45)):dx, dy = rng.integers(-2, 3, 2) * kd = np.roll(dens[..., i], (int(dy), int(dx)), axis=(0, 1))a = np.deg2rad(deg)u = (xx * np.cos(a) + yy * np.sin(a)) / csv = (-xx * np.sin(a) + yy * np.cos(a)) / csr = np.hypot(u - np.round(u), v - np.round(v))rad = np.sqrt(np.clip(d / 1.0, 0, 1)) * .68cov = np.clip((rad - r) * cs / 1.0 + .5, 0, 1)cov = cov * (_fbm((H, W), max(1, int(3 * k)), seed + 10 + i) > .28)ink = RISO_INKS[i]out = out * (1 - cov[..., None] * (1 - ink))return np.clip(out, 0, 1)# ================================================================ pop art (Lichtenstein)POP_PAL = np.array([[.9, .12, .12], [1, .85, .1], [.12, .35, .8], [.98, .97, .92], [.08, .08, .08],[.98, .78, .68], [.15, .65, .3]], np.float32)def pop(img, ids, depth, seed=0):"""Pop art (Lichtenstein): flat primaries, Ben-Day dots for the lighter tones and the sky, heavy black outlines."""H, W = img.shape[:2]k = H / 512.0flat = _region_flat(img, ids, 3 * k)q = POP_PAL[_nearest(_sat(flat, 1.6), POP_PAL, w=(1, 1, 1))]yy, xx = _grid(H, W)sp = 7 * ku, v = (xx + yy) / sp, (xx - yy) / spr = np.hypot(u - np.round(u), v - np.round(v))L = _lum(img)rel = L / np.maximum(_lum(flat), 1e-3)sky = ids == -2light = (rel > 1.12) | skydotc = np.where(sky[..., None], POP_PAL[2], q)dots = r < .3out = np.where(light[..., None], np.where(dots[..., None], dotc, POP_PAL[3]), q)shade = (rel < .78) & (ids >= 0)out = np.where((shade & (r < .25))[..., None], out * .35, out)e = _edges(ids, depth, img, cthr=.2)line = _line(e, 3.0 * k)return np.clip(out * (1 - line[..., None]) + .05 * line[..., None], 0, 1)# ================================================================ chalkboarddef chalkboard(img, ids, depth, seed=0):"""Chalk on a blackboard: dark green slate with eraser smudges, pastel chalk fills laid in hatching that breaks onthe board's grain, bright chalk contours, a wooden frame."""H, W = img.shape[:2]k = H / 512.0rng = np.random.default_rng(seed)im, idw = _warp([img, ids], H, W, 2 * k, 40 * k, seed, orders=[1, 0])yy, xx = _grid(H, W)board = np.array([.13, .2, .17]) * (1 + (_fbm((H, W), int(40 * k) or 1, seed) - .5)[..., None] * .25)smudge = _smooth(_fbm((H, W), int(90 * k) or 1, seed + 1), .5, .9) * .07board = board + smudge[..., None]flat = _region_flat(im, idw, 3 * k)chalk = _sat(flat / np.maximum(flat.max(-1, keepdims=True), .3), 1.3) * .6 + .4 # pastel chalk coloursky = idw == -2L = _lum(im)ang = np.zeros((H, W), np.float32)for v in np.unique(idw):ang[idw == v] = rng.uniform(.3, 1.2)ph = (xx * np.cos(ang + np.pi / 2) + yy * np.sin(ang + np.pi / 2)) / (4 * k)hatch = np.clip((np.abs(np.sin(ph * np.pi)) - .35) * 2, 0, 1)grain = _fbm((H, W), max(1, int(1.5 * k)), seed + 3) + (rng.random((H, W)) - .5) * .3# rule: chalk goes on the subject; the ground gets a few sparse strokes, the sky stays boarddens = np.clip(L * .8 + .45, 0, 1) * np.where(idw >= 0, 1.0, .14)dens = np.where(sky, dens * .4, dens)cov = np.clip(hatch * dens * 1.8 - (grain - .5) * .9, 0, 1) * .9out = board * (1 - cov[..., None]) + chalk * cov[..., None]e = _edges(idw, depth, im, cthr=.18)line = _line(e, 2.0 * k) * np.clip(1.2 - (grain - .3) * 1.2, 0, 1)out = out * (1 - line[..., None] * .9) + np.array([.95, .95, .92]) * line[..., None] * .9# wooden framefw = 12 * kdist_b = np.minimum(np.minimum(yy, H - 1 - yy), np.minimum(xx, W - 1 - xx))wood = np.array([.55, .36, .2]) * (1 + (_noise((H, W), int(30 * k) or 1, seed + 5, sy=int(2 * k) or 1) - .5)[..., None] * .3)out = np.where((dist_b < fw)[..., None], wood * (.8 + .2 * _smooth(dist_b, 0, fw))[..., None], out)return np.clip(out, 0, 1)# ================================================================ tone styles (photographic finishes)def bw(img, ids, depth, seed=0):H, W = img.shape[:2]L = _lum(img)L = _smooth(L, .02, .98) * .9 + L * .1g = (np.random.default_rng(seed).random((H, W)) - .5) * .05v = 1 - .25 * (np.hypot(*(np.mgrid[0:H, 0:W] / np.array([H, W])[:, None, None] - .5)) ** 2) * 2return np.clip(((L + g) * v)[..., None] * np.ones(3), 0, 1)def sepia(img, ids, depth, seed=0):H, W = img.shape[:2]L = _lum(img) * .9 + .05v = 1 - .35 * (np.hypot(*(np.mgrid[0:H, 0:W] / np.array([H, W])[:, None, None] - .5)) ** 2) * 2c = np.stack([L * 1.07 + .03, L * .9 + .02, L * .68], -1) * v[..., None]return np.clip(c * (1 + (_noise((H, W), 2, seed) - .5)[..., None] * .06), 0, 1)def pastel(img, ids, depth, seed=0):k = img.shape[0] / 512.0c = _sat(_blur(img, .8 * k), .7)return np.clip(c * .62 + .38 * np.array([1, .97, .96]), 0, 1)STYLES = {"oil": oil, "impressionist": impressionist, "pointillism": pointillism, "vangogh": vangogh,"watercolor": watercolor, "sketch": sketch, "comic": comic, "ukiyoe": ukiyoe, "stainedglass": stainedglass,"mosaic": mosaic, "lowpoly": lowpoly, "papercut": papercut, "clay": clay, "charcoal": charcoal,"inkwash": inkwash, "crayon": crayon, "blueprint": blueprint, "neon": neon, "crossstitch": crossstitch,"nouveau": nouveau, "riso": riso, "pop": pop, "chalkboard": chalkboard, "bw": bw, "sepia": sepia,"pastel": pastel}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Poses: one small vocabulary of body poses shared by every creature family (quadruped, primate, bird, fish,reptile, person), plus the rigid-transform helpers the families use to pose their skeletons.
A pose is a NAME (stand, walk, run, sit, lie, sleep, jump, rear, upright, howl, graze, swim, fly, perch, hang,one_leg, crawl, ride ...) chosen from the instance (inst.pose from the parser, inst.attrs["action"], interactionsset by the layout / 3D placement). Each family turns the name into joint angles for its own skeleton (spine pitch,neck / head pitch and yaw, per-leg foot targets solved with 2-bone IK, tail, wings, mouth, eyelids), so a pose worksfor every species of the family, never per word.
Posed models are scaled like the same animal standing (a lying dog is low, a rearing horse is tall), and theyreport ANCHORS in the model frame (mouth, nose, beak, hand, saddle, seat ...) so the 3D renderer can put a heldthing in a mouth or hand and a rider on a back. Pure numpy; no learned anything."""import mathimport numpy as np
# ---------------------------------------------------------------- vocabulary# rule: every pose word the parser or layout may set maps to one canonical poseCANON = { None: None, "standing": "stand", "stand": "stand", "parked": None, "posing": "stand", "walking": "walk", "walk": "walk", "strolling": "walk", "trotting": "walk", "wandering": "walk", "marching": "walk", "running": "run", "run": "run", "racing": "run", "galloping": "run", "sprinting": "run", "chasing": "run", "fleeing": "run", "charging": "run", "dashing": "run", "jogging": "run", "sitting": "sit", "sit": "sit", "seated": "sit", "crouching": "sit", "begging": "sit", "lying": "lie", "lie": "lie", "resting": "lie", "lounging": "lie", "laying": "lie", "sunbathing": "lie", "basking": "lie", "sleeping": "sleep", "sleep": "sleep", "napping": "sleep", "asleep": "sleep", "curled": "sleep", "dozing": "sleep", "jumping": "jump", "jump": "jump", "leaping": "jump", "hopping": "jump", "bouncing": "jump", "pouncing": "jump", "rearing": "rear", "rear": "rear", "upright": "upright", "hind": "upright", "howling": "howl", "howl": "howl", "roaring": "howl", "baying": "howl", "crowing": "howl", "singing_up": "howl", "grazing": "graze", "graze": "graze", "eating": "graze", "drinking": "graze", "sniffing": "graze", "foraging": "graze", "swimming": "swim", "swim": "swim", "floating": "swim", "paddling": "swim", "diving": "swim", "flying": "fly", "fly": "fly", "soaring": "fly", "hovering": "fly", "gliding": "fly", "airborne": "fly", "levitating": "fly", "perched": "perch", "perch": "perch", "perching": "perch", "hanging": "hang", "hang": "hang", "dangling": "hang", "swinging": "hang", "one_leg": "one_leg", "crawling": "crawl", "crawl": "crawl", "creeping": "crawl", "slithering": "crawl", "stalking": "crawl", "sneaking": "crawl", "riding": "ride", "ride": "ride", "coiled": "coil", "coil": "coil", "balancing": "balance", "balance": "balance", "kneeling": "kneel", "kneel": "kneel", "dancing": "dance", "dance": "dance",}
def canon(name): if name is None: return None return CANON.get(name, name if name in set(CANON.values()) else None)
def pose_of(inst, default=None): """canonical pose of a layout instance (or None). Order: an explicit pose3d set by interactions, then the parser's pose, then the action verb.""" if inst is None: return default for k in ("pose3d", "pose"): v = canon(getattr(inst, k, None)) if v: return v a = (getattr(inst, "attrs", None) or {}).get("action") v = canon(a) if a else None return v or default
def action_of(inst): return (getattr(inst, "attrs", None) or {}).get("action") if inst is not None else None
# ---------------------------------------------------------------- rigid transformsclass Rigid: """world = R @ local + t (R a 3x3 rotation). Compose with @; .inv_pts maps world points back to local, so a part built in its rest frame is posed by evaluating it at inv_pts(p) (rigid motions keep SDFs exact).""" __slots__ = ("R", "t")
def __init__(self, R=None, t=None): self.R = np.eye(3) if R is None else np.asarray(R, float) self.t = np.zeros(3) if t is None else np.asarray(t, float)
def __matmul__(self, o): return Rigid(self.R @ o.R, self.R @ o.t + self.t)
def pt(self, x): return self.R @ np.asarray(x, float) + self.t
def vec(self, v): return self.R @ np.asarray(v, float)
def inv_pts(self, p): return (p - self.t) @ self.R # = R^T (p - t) for row vectors
def is_id(self): return np.allclose(self.R, np.eye(3)) and np.allclose(self.t, 0)
def rot_axis(axis, deg): a = math.radians(deg) c, s = math.cos(a), math.sin(a) if axis == "z": # + = counter-clockwise in x-y: a +x-facing body pitches its front UP return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1.0]]) if axis == "y": # + = turns +x toward -z (toward the camera, which looks along +z from -z) return np.array([[c, 0, s], [0, 1.0, 0], [-s, 0, c]]) return np.array([[1.0, 0, 0], [0, c, -s], [0, s, c]]) # x: + rolls +y toward +z
def about(pivot, R, t=(0, 0, 0)): """rotation R about `pivot`, then a translation t""" pivot = np.asarray(pivot, float) return Rigid(R, pivot - R @ pivot + np.asarray(t, float))
def posed(fn, T): """an SDF built in its rest frame, moved by rigid transform T (identity -> the same function)""" if T is None or T.is_id(): return fn return lambda p: fn(T.inv_pts(p))
def ik2(a, f, l1, l2, bend): """2-bone IK in the x-y plane (z interpolated): joint position between root a and end f with bone lengths l1, l2. bend: +1 = the joint sticks out toward +x (forward), -1 toward -x. An unreachable end is pulled in.""" a, f = np.asarray(a, float), np.asarray(f, float) d = f - a L = float(np.hypot(d[0], d[1])) if L > (l1 + l2) * .999: f = a + d * ((l1 + l2) * .999 / max(L, 1e-6)) d = f - a L = (l1 + l2) * .999 L = max(L, abs(l1 - l2) + 1e-4) x = (l1 * l1 - l2 * l2 + L * L) / (2 * L) h = math.sqrt(max(l1 * l1 - x * x, 0.0)) u = d[:2] / max(L, 1e-6) perp = np.array([-u[1], u[0]]) if perp[0] * bend < 0 or (abs(perp[0]) < 1e-6 and bend < 0): perp = -perp j = a[:2] + u * x + perp * h return np.array([j[0], j[1], (a[2] + f[2]) * .5]), f
# ---------------------------------------------------------------- posed model containerclass Model(list): """a list of Parts that also carries the posed model's facts: aspect (width / standing height), height (posed height in standing units; 1.0 standing, < 1 lying, > 1 rearing), anchors {name: (x, y, z)} in the model frame (base y=0, standing height 1, centred), facing (+x for side-view animals).""" aspect = None height = 1.0 anchors = None fit_width = False # True: the 3D placement shrinks the model to the layout box width (its pose made it wider)
@classmethod def of(cls, parts, aspect=None, height=1.0, anchors=None): m = cls(parts) m.aspect, m.height, m.anchors = aspect, height, dict(anchors or {}) return m
def measure(parts, lo=(-4., -4., -4.), hi=(4., 4., 4.)): """bounding box of the union of parts (coarse grid then a fine one)""" def dist(q): d = None for pt in parts: e = pt.fn(q) d = e if d is None else np.minimum(d, e) return d lo, hi = np.array(lo, float), np.array(hi, float) for n in (26, 44): ax = [np.linspace(lo[i], hi[i], n) for i in range(3)] g = np.stack(np.meshgrid(*ax, indexing="ij"), -1).reshape(-1, 3) step = (hi - lo) / (n - 1) inside = dist(g) < step.max() * .5 if not inside.any(): return np.array([-.5, 0, -.3]), np.array([.5, 1, .3]) pts = g[inside] lo, hi = pts.min(0) - step, pts.max(0) + step return lo + step * .5, hi - step * .5
def finish_posed(parts, href, anchors=None, floor=None, box=None, max_h=1.35, center_x=None): """normalise a posed raw model: uniform scale 1/href (the STANDING height, so poses keep the animal's size), lowest point (or `floor`, e.g. a water line) on y=0, centred in x and z. A pose taller than max_h x standing is shrunk to max_h. Returns a Model with aspect / height / anchors in the contract frame.""" lo, hi = box if box is not None else measure(parts) y0 = lo[1] if floor is None else floor h = max(hi[1] - y0, 1e-3) s = 1.0 / max(href, 1e-3) if h * s > max_h: s = max_h / h cx = (lo[0] + hi[0]) * .5 if center_x is None else center_x sh = np.array([cx, y0, (lo[2] + hi[2]) * .5]) for pt in parts: pt.fn = (lambda f: (lambda p: f(p / s + sh) * s))(pt.fn) anc = {k: tuple((np.asarray(v, float) - sh) * s) for k, v in (anchors or {}).items()} return Model.of(parts, aspect=(hi[0] - lo[0]) * s, height=h * s, anchors=anc)
def eyelids(c, r, n, col, both=True, mirror=None): """closed eyes: a lid of skin / fur colour over the eye ball plus a dark lash line across it (sleeping).""" from .models import Part from . import sdf as S c, n = np.asarray(c, float), np.asarray(n, float) n = n / np.linalg.norm(n) side = np.cross(np.array([0, 1.0, 0]), n) if np.linalg.norm(side) < 1e-6: side = np.array([1.0, 0, 0]) side /= np.linalg.norm(side) M = mirror if (both and mirror is not None) else (lambda p: p) lc = c + n * r * .55 - np.array([0, r * .12, 0]) a, b = lc - side * r * .75, lc + side * r * .75 lid = Part(lambda p: S.sphere(M(p), c, r * 1.03), col, spec=.2, rough=.6) lash = Part(lambda p: S.capsule(M(p), a, b, r * .16), (30, 24, 22), spec=.3, rough=.5) return [lid, lash]
def pitch_parts(parts, deg): """whole-body pitch (deg, + = nose up) of a raw model about its origin, before the family's fit() measures it (rigid-bodied families: a jumping fish / frog arcs nose-up, a grazing fish noses down)""" if not deg: return parts T = Rigid(rot_axis("z", deg)) for pt in parts: pt.fn = posed(pt.fn, T) return parts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392"""retro64: real 64 x 64 pixel art in the look of small pixel-art sprite models (in the spirit of Retro Diffusion'sRD Flow 64 samples), drawn purely in code.
Look we aim at (studied from that model card's published samples, no model involved):- a real 64 x 64 grid, every pixel one entry of a small palette (~16-40 colours), binary transparency;- a single subject: a transparent sprite, centred, filling most of the height with a clear margin; shown on a dark navy backdrop;- dark, hue-shifted outlines (a darker version of the local colour, not pure black), lighter lines between parts;- flat cel shading: 3-4 bands per material, light from the upper left, shadows shift toward blue / purple and get more saturated, highlights shift toward yellow, a bright rim on lit edges;- scenes (a place, a time of day): a full 64 x 64 frame with banded gradients and the same palette discipline.
Pipeline: the normal 3D layout (pydraw3d.plot3d, preview mode) gives the placed models; sprites are re-marched with anorthographic camera on a 3x supersampled 64 x 64 grid, with an object/part id per sample so small parts (eyes) wintheir pixel and outlines follow real part boundaries. Pure numpy; no image files, no learned weights."""import colorsysimport mathimport numpy as npfrom PIL import Image
BACKDROP = (23, 20, 32) # the dark navy the sprites are shown onN = 64
# ----------------------------------------------------------------------------------------------- colour helpersdef _hsv(c): return np.array(colorsys.rgb_to_hsv(*np.clip(c, 0, 1)))
def _rgb(h, s, v): return np.array(colorsys.hsv_to_rgb(h % 1.0, min(max(s, 0), 1), min(max(v, 0), 1)))
def _toward(h, target, amt): d = ((target - h + .5) % 1.0) - .5 return h + d * amt
def ramp_color(base, band): """rule (pixel art): one material colour -> a shading ramp. band -2 (deep shadow) .. +2 (highlight): shadows darken, gain saturation and shift hue toward blue-violet; highlights brighten, lose saturation and shift toward warm yellow. Grey/white materials get a cool shadow tint so they still read as lit.""" h, s, v = _hsv(base) if band < 0: k = -band if s < .12: # rule: neutral colours borrow a cool violet tint in shadow h, s = .70, s + .10 * k h = _toward(h, .70, .06 * k) s = s + .10 * k v = v * (1 - .20 * k) - .02 * k elif band > 0: k = band h = _toward(h, .14, .035 * k) s = s * (1 - .16 * k) v = v + (1 - v) * .35 * k + .05 * k return _rgb(h, s, v)
def outline_color(base): """rule: outline = a very dark, saturated, hue-shifted version of the local colour (dark brown for orange fur, deep navy for blue, near-black violet for black), never flat black""" h, s, v = _hsv(base) if s < .12: h, s = .72, .35 h = _toward(h, .72, .10) return _rgb(h, min(1, s + .25), min(.20, v * .28 + .06))
# ------------------------------------------------------------------------------------------------ 3D layoutdef _layout(text, seed, variation): """Run the normal 3D layout once, cheaply, and return its buffers (placed objects, scene).""" from . import plot3d im = plot3d(text, seed=seed, size=64, res=256, variation=variation, exp={"preview": "8", "msteps": "24", "shsteps": "2", "ncam": "0", "paint": "0", "fallback": "skip"}) return im.info.get("buffers"), im.info.get("scene") or {}, im.info.get("trace") or []
def _view_basis(tilt_deg=12.0): t = math.radians(tilt_deg) D = np.array([0.0, -math.sin(t), math.cos(t)]) up = np.array([0.0, math.cos(t), math.sin(t)]) right = np.array([1.0, 0.0, 0.0]) return D, up, right
def _march_ortho(sc, u, v, D, up, right, c0, back=40.0): from . import march O = c0[None, :] + u[:, None] * right[None, :] + v[:, None] * up[None, :] - D[None, :] * back Dm = np.tile(D, (len(O), 1)) t, hit = march(sc, O, Dm, 2 * back, steps=200) return O, Dm, t, hit
def render_sprite64(objs, ss=3, margin=5, light=(-.55, .70, -.45)): """Orthographic 64 x 64 sprite of the placed objects. Returns (ids (N,N) int: -1 empty, index into a part table), rgb (N,N,3) linear-ish 0-1 shaded and banded, part table).""" from . import Scene3D, normals, texture, pattern, lin sc = Scene3D(objs, ground=False) D, up, right = _view_basis() # framing pass: coarse grid around the bounding spheres -> the exact silhouette box cen = np.mean([o.center for o in objs], 0) ext = max(np.max(np.abs(o.center - cen)) + o.radius for o in objs) g = 72 gu, gv = np.meshgrid(np.linspace(-ext, ext, g), np.linspace(ext, -ext, g)) _, _, _, hit = _march_ortho(sc, gu.ravel(), gv.ravel(), D, up, right, cen) if not hit.any(): return None hu, hv = gu.ravel()[hit], gv.ravel()[hit] cell = 2 * ext / (g - 1) u0, u1, v0, v1 = hu.min() - cell, hu.max() + cell, hv.min() - cell, hv.max() + cell # rule (framing): the subject fills most of the frame with a clear margin on every side (whole subject visible) avail = N - 2 * margin px = max(u1 - u0, v1 - v0) / avail uc, vc = (u0 + u1) / 2, (v0 + v1) / 2 n = N * ss s = (np.arange(n) + .5) / ss - N / 2 U, V = np.meshgrid(uc + s * px, vc - s * px) # rule: sit the subject a little low (its feet on a ground line near the bottom margin) V = V + (N / 2 - margin - (v1 - v0) / px / 2) * px * .35 O, Dm, t, hit = _march_ortho(sc, U.ravel(), V.ravel(), D, up, right, cen) M = n * n pid = np.full(M, -1) alb = np.zeros((M, 3)) nrm = np.zeros((M, 3)) em = np.zeros(M) table = [] # (obj index, part index, base colour, part) hi = np.nonzero(hit)[0] if len(hi): P = O[hi] + Dm[hi] * t[hi, None] nrm[hi] = normals(sc, P, 1e-3 * max(o.scale for o in objs)) _, oid = sc.dist(P, want_id=True) for k, ob in enumerate(objs): mk = oid == k if not mk.any(): continue pi, q = ob.part_index(P[mk]) idx = hi[mk] for j, pt in enumerate(ob.parts): m = pi == j if not m.any(): continue tid = len(table) table.append((k, j, np.asarray(pt.color, float) / 255.0, pt)) pid[idx[m]] = tid a = texture(pt.tex, q[m], lin(pt.color), j) pat = getattr(pt, "pat", None) if pat: a = pattern(pat, q[m], a) alb[idx[m]] = np.clip(a, 0, 1) ** (1 / 2.2) em[idx[m]] = getattr(pt, "emit", 0.0) # ---- per output pixel: the winning part among its ss x ss samples pid_b = pid.reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) area = np.bincount(pid[pid >= 0], minlength=max(1, len(table))).astype(float) cover = (pid_b >= 0).sum(-1) out_id = np.full((N, N), -1) best = np.zeros((N, N)) for tid in np.unique(pid[pid >= 0]): c = (pid_b == tid).sum(-1).astype(float) # rule: a small part (an eye, a nose, a button) wins its pixel from fewer samples than a big one, so tiny # features survive the 64 px grid instead of averaging away score = c / (area[tid] ** .35 + 1e-6) * (c >= max(1, ss * ss // 4)) better = score > best out_id[better], best[better] = tid, score[better] out_id[cover < (ss * ss + 1) // 2] = -1 # rule: binary transparency, a pixel is in when most samples hit # rule: a pixel the coverage rule kept but no part won takes its most frequent part lost = (out_id < 0) & (cover >= (ss * ss + 1) // 2) if lost.any(): for y, x in zip(*np.nonzero(lost)): v = pid_b[y, x][pid_b[y, x] >= 0] out_id[y, x] = np.bincount(v).argmax() # mean albedo / normal of the winning part's samples alb_b = alb.reshape(N, ss, N, ss, 3).transpose(0, 2, 1, 3, 4).reshape(N, N, ss * ss, 3) nrm_b = nrm.reshape(N, ss, N, ss, 3).transpose(0, 2, 1, 3, 4).reshape(N, N, ss * ss, 3) w = (pid_b == out_id[..., None]).astype(float)[..., None] A = (alb_b * w).sum(2) / np.maximum(w.sum(2), 1e-6) Nn = (nrm_b * w).sum(2) Nn /= np.maximum(np.linalg.norm(Nn, axis=-1, keepdims=True), 1e-6) # depth per pixel (for interior lines: a part in front of another) tt = np.where(hit, t, np.inf).reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) Z = np.where(w[..., 0] > 0, tt, np.inf).min(-1) em_b = em.reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) E = (em_b * w[..., 0]).sum(-1) / np.maximum(w[..., 0].sum(-1), 1e-6) L = np.asarray(light, float) L /= np.linalg.norm(L) return dict(ids=out_id, alb=A, nrm=Nn, depth=Z, emit=E, table=table, L=L, px=px)
# ------------------------------------------------------------------------------------------------ stylisedef _bands(nrm, L, ids): """rule (cel shading): lambert -> 4 bands (-2 deep shadow, -1 shadow, 0 lit, +1 light) plus +2 rim highlights on the lit edge of each shape""" d = (nrm @ L) b = np.where(d > .55, 1, np.where(d > .12, 0, np.where(d > -.30, -1, -2))) # bright rim: a pixel whose up-left neighbour is empty or another part, facing the light sh = np.full_like(ids, -9) sh[1:, 1:] = ids[:-1, :-1] up = np.full_like(ids, -9) up[1:, :] = ids[:-1, :] rim = (ids >= 0) & ((sh != ids) | (up != ids)) & (d > .25) b = np.where(rim, np.maximum(b, 1) + (d > .5), b) return np.clip(b, -2, 2)
def _quantize(rgb, mask, colors): """rule: an exact small palette (median cut, no dithering): every pixel points at one palette entry""" pts = (np.clip(rgb[mask], 0, 1) * 255 + .5).astype(np.uint8) if len(pts) == 0: return rgb k = len(np.unique(pts.reshape(-1, 3), axis=0)) if k <= colors: out = rgb.copy() out[mask] = pts / 255.0 return out im = Image.fromarray(pts.reshape(1, -1, 3)) q = im.quantize(colors=colors, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE).convert("RGB") out = rgb.copy() out[mask] = np.asarray(q).reshape(-1, 3) / 255.0 return out
def _cleanup(rgb, mask, keep): """rule (pixel art): remove orphan pixels - a lone pixel whose colour no 4-neighbour shares, inside a region where 5+ of its 8 neighbours agree, takes that majority colour (texture noise, not features)""" key = (np.clip(rgb, 0, 1) * 255).astype(int) key = key[..., 0] * 65536 + key[..., 1] * 256 + key[..., 2] out = rgb.copy() H, W = mask.shape for y in range(1, H - 1): for x in range(1, W - 1): if not mask[y, x] or keep[y, x]: continue c = key[y, x] n4 = [key[y - 1, x], key[y + 1, x], key[y, x - 1], key[y, x + 1]] if c in n4: continue nb = key[y - 1:y + 2, x - 1:x + 2].ravel() nb = np.delete(nb, 4) vals, cnt = np.unique(nb, return_counts=True) if cnt.max() >= 5: v = vals[cnt.argmax()] yy, xx = np.nonzero(key[y - 1:y + 2, x - 1:x + 2] == v) out[y, x] = rgb[y - 1 + yy[0], x - 1 + xx[0]] return out
def stylise_sprite(r, colors=32): ids, A, Nn, Z, E, table, L = r["ids"], r["alb"], r["nrm"], r["depth"], r["emit"], r["table"], r["L"] mask = ids >= 0 band = _bands(Nn, L, ids) rgb = np.zeros((N, N, 3)) for y, x in zip(*np.nonzero(mask)): rgb[y, x] = ramp_color(A[y, x], int(band[y, x])) if E[y, x] > .3: # rule: glowing parts (flames, lamps) stay bright and unshaded rgb[y, x] = ramp_color(A[y, x], 1) # rule: small parts (eyes, noses, buttons) are features - keep them out of the orphan cleanup area = np.bincount(ids[mask], minlength=len(table)) feat = mask & (area[np.maximum(ids, 0)] <= 6) # rule: interior lines where one part sits in front of another (depth jump), drawn on the farther pixel in a # darker shade of its own colour - lighter than the silhouette outline (selective outline) line = np.zeros_like(mask) for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): nid = np.roll(ids, (dy, dx), (0, 1)) nz = np.roll(Z, (dy, dx), (0, 1)) jump = mask & (nid >= 0) & (nid != ids) & (np.nan_to_num(Z - nz, nan=0.0, posinf=0.0, neginf=0.0) > 1.6 * r["px"]) & ~feat line |= jump for y, x in zip(*np.nonzero(line)): rgb[y, x] = ramp_color(A[y, x], -2) * .8 rgb = _quantize(rgb, mask, colors - 6) rgb = _cleanup(rgb, mask, feat | line) # rule: silhouette outline one pixel outside the shape, coloured from the neighbouring part (dark brown around # orange fur, deep blue around blue cloth); corners are filled only where two sides touch (clean diagonals) out_rgb = rgb.copy() alpha = mask.copy() for y in range(N): for x in range(N): if mask[y, x]: continue nbs = [(y + dy, x + dx) for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)) if 0 <= y + dy < N and 0 <= x + dx < N and mask[y + dy, x + dx]] if nbs: cs = np.mean([A[p] for p in nbs], 0) out_rgb[y, x] = outline_color(cs) alpha[y, x] = True return out_rgb, alpha
# ------------------------------------------------------------------------------------------------ scenesdef stylise_scene(buf, colors=40): """Full-frame scene: the 3D preview buffers at 3x -> 64 x 64 (mode of object id per pixel, mean colour of the winning id), banded value, saturated / hue-shifted shadows, small palette, outlines around prompted subjects.""" rgb, ids = buf["rgb"], buf["ids"] n = rgb.shape[0] ss = n // N rb = rgb[:N * ss, :N * ss].reshape(N, ss, N, ss, 3).transpose(0, 2, 1, 3, 4).reshape(N, N, ss * ss, 3) ib = ids[:N * ss, :N * ss].reshape(N, ss, N, ss).transpose(0, 2, 1, 3).reshape(N, N, ss * ss) win = np.zeros((N, N), int) for y in range(N): for x in range(N): v, c = np.unique(ib[y, x], return_counts=True) win[y, x] = v[c.argmax()] w = (ib == win[..., None]).astype(float)[..., None] col = (rb * w).sum(2) / np.maximum(w.sum(2), 1e-6) # rule: pixel-art colour - more saturation and contrast than a photo, shadows pushed toward violet out = np.zeros_like(col) for y in range(N): for x in range(N): h, s, v = _hsv(col[y, x]) if v < .45: h = _toward(h, .70, .25 * (.45 - v) / .45) s = min(1, s * 1.15 + .06) s = min(1, s * 1.18) v = min(1, .5 + (v - .5) * 1.12) out[y, x] = _rgb(h, s, v) mask = np.ones((N, N), bool) out = _quantize(out, mask, colors) subj = np.zeros((N, N), bool) objs = buf["objs"] for k, o in enumerate(objs): if getattr(o, "ent", None) is not None: subj |= win == k out = _cleanup(out, mask, np.zeros_like(mask)) # rule: prompted subjects get a dark hue-shifted outline on their own edge pixels (scenery stays soft) edge = subj & ((np.roll(win, 1, 0) != win) | (np.roll(win, -1, 0) != win) | (np.roll(win, 1, 1) != win) | (np.roll(win, -1, 1) != win)) edge[0, :] = edge[-1, :] = False edge[:, 0] = edge[:, -1] = False for y, x in zip(*np.nonzero(edge)): out[y, x] = outline_color(col[y, x]) return out
# ------------------------------------------------------------------------------------------------ entry pointSCENE_WORDS = ("scene", "landscape", "background", "view of", "at night", "at sunset", "at sunrise", "at dawn", "at dusk", "underwater", "on a beach")
def is_sprite(text, scene): """rule: one subject (or a subject on a support) with no place / time / backdrop words -> transparent sprite; anything with a setting -> a full 64 x 64 scene""" t = " " + text.lower() + " " if scene.get("place") or any(w in t for w in SCENE_WORDS): return False return len(scene.get("entities", [])) <= 3
def retro64(text, seed=0, size=512, variation=1.0, mode="auto", colors=32, return_trace=False, backdrop=BACKDROP): """text -> (preview PIL image at `size` (nearest-neighbour upscale of the 64 x 64 art on the backdrop), and .info['pixels'] = the 64 x 64 RGBA art itself)""" buf, scene, trace = _layout(text, seed, variation) trace = list(trace) if buf is None and mode != "sprite": # rule: something has no 3D model -> pixelise the pixel renderer's own picture as a scene from pydraw import plot img = plot(text, seed=seed, size=192, variation=variation) a = np.array([p for row in img.pixels for p in row], float).reshape(img.height, img.width, 3) / 255.0 a = np.asarray(Image.fromarray((a * 255).astype(np.uint8)).resize((N * 3, N * 3), Image.NEAREST), float) / 255 buf = dict(rgb=a, ids=np.zeros((N * 3, N * 3), int), objs=[]) mode = "scene" trace.append("retro64: no 3D model for every object -> pixel renderer picture, pixelised") if mode == "auto": from pydraw.understanding import parse sprite = is_sprite(text, parse(text, [])) # rule: decide on what the prompt says, not the layout's default place else: sprite = mode == "sprite" if sprite: from .models import MODELS # rule: a sprite shows the prompted things that have a 3D model; a worn item without one (a chef costume) # is dropped rather than drawn as a placeholder box objs = [o for o in buf["objs"] if getattr(o, "ent", None) is not None and o.name in MODELS] or \ [o for o in buf["objs"] if getattr(o, "ent", None) is not None] or list(buf["objs"]) r = render_sprite64(objs) if r is None: sprite = False else: rgb, alpha = stylise_sprite(r, colors) trace.append("retro64: transparent 64x64 sprite of %d object(s), %d colours" % (len(objs), len(np.unique((rgb[alpha] * 255).astype(int), axis=0)))) if not sprite: from . import plot3d im = plot3d(text, seed=seed, size=192, res=512, variation=variation, exp={"preview": str(N * 3), "msteps": "140", "shsteps": "24", "ncam": "0", "paint": "0"}) b2 = im.info.get("buffers") or buf rgb = stylise_scene(b2, colors) alpha = np.ones((N, N), bool) trace.append("retro64: full-frame 64x64 scene") art = np.zeros((N, N, 4), np.uint8) art[..., :3] = (np.clip(rgb, 0, 1) * 255 + .5).astype(np.uint8) art[..., 3] = alpha * 255 bg = np.array(backdrop, float) comp = np.where(alpha[..., None], art[..., :3], bg).astype(np.uint8) im = Image.fromarray(comp).resize((size, size), Image.NEAREST) im.info["pixels"] = Image.fromarray(art, "RGBA") im.info["scene"] = scene return (im, trace) if return_trace else im123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708"""Generation as search: generate-and-test over the scene program with a hand-written critic.
from pydraw3d import plot3d plot3d("a cat behind a fence", search=True) # ~6 s of previews, then the full render plot3d("five apples", search=4.0) # budget in seconds
One-shot rule placement makes one guess. Here the open choices of the scene program (variation seed -> variants,unnamed colours, setting variant, framing jitter; layout seed -> instance positions, sizes, yaws; per-instance nudges;sun direction; backdrop colour; colours of things the prompt leaves uncoloured) are searched: cheap previews(96 px, one ray per pixel, few march / shadow steps) return colour + object-id + depth buffers, a critic written by hand(no learning) scores them, and a small Metropolis loop (cf. Talton et al. 2011, "Metropolis procedural modeling")with random restarts and critic-targeted proposals keeps the best candidate, which is then rendered in full.
The critic is a list of terms; add your own with @term(name, weight). Each term gets a Ctx (buffers + per-objectvisibility measured by re-marching every object alone) and yields Finding(severity 0..1, message, hard). A hardfinding means the picture fails the prompt (an entity missing, wrong count, broken relation, wrong colour);soft findings are taste (figure-ground contrast, tangents, size, balance)."""import math, random, time, copyimport numpy as np
PREVIEW = 72 # preview grid (pixels per side)MIN_FRAC = .0025 # an instance must cover at least this fraction of the frame to count as visible
# --------------------------------------------------------------------------------------------------------------# critic registryTERMS = []
class Finding: __slots__ = ("term", "sev", "msg", "hard", "ent", "insts", "rel")
def __init__(self, term, sev, msg, hard=False, ent=None, insts=(), rel=None): self.term, self.sev, self.msg, self.hard, self.ent, self.insts = term, float(np.clip(sev, 0, 1)), msg, hard, ent, tuple(insts) self.rel = rel # (subject entity, relation, object entity) for relation findings: lets proposals repair it
def __repr__(self): return "%s%s %.2f %s" % ("!" if self.hard else "", self.term, self.sev, self.msg)
def term(name, weight=1.0): """Register a critic term: fn(ctx) -> iterable of Finding. Others (camera/composition) can add terms the same way.""" def deco(fn): TERMS.append((name, weight, fn)) return fn return deco
# --------------------------------------------------------------------------------------------------------------# named colours from pixels (HSV rules, robust to shading)def _hsv(c): mx, mn = c.max(-1), c.min(-1) d = mx - mn + 1e-9 r, g, b = c[..., 0], c[..., 1], c[..., 2] h = np.where(mx == r, ((g - b) / d) % 6, np.where(mx == g, (b - r) / d + 2, (r - g) / d + 4)) / 6 return h, np.where(mx > 0, (mx - mn) / (mx + 1e-9), 0), mx
CLASSES = ["black", "white", "gray", "red", "orange", "brown", "yellow", "green", "cyan", "blue", "purple", "pink"]ALIAS = {"violet": "purple", "grey": "gray", "golden": "yellow", "gold": "yellow", "silver": "gray", "tan": "brown", "cream": "white", "teal": "cyan", "turquoise": "cyan", "beige": "white", "navy": "blue", "maroon": "red", "magenta": "pink", "lime": "green", "crimson": "red", "scarlet": "red"}NEAR = {("orange", "brown"), ("brown", "orange"), ("red", "pink"), ("pink", "red"), ("purple", "pink"), ("pink", "purple"), ("cyan", "blue"), ("blue", "cyan"), ("cyan", "green"), ("yellow", "orange"), ("orange", "yellow"), ("gray", "white"), ("white", "gray"), ("gray", "black"), ("black", "gray"), ("red", "orange"), ("brown", "red"), ("blue", "purple")}
def classify(rgb): """rgb in 0..1, (...,3) -> index into CLASSES""" h, s, v = _hsv(np.asarray(rgb, float)) out = np.full(h.shape, 2) out = np.where(v > .72, 1, out) # unsaturated + bright = white out = np.where(v < .2, 0, out) chrom = (s > .22) & (v >= .2) hb = np.select([(h < .035) | (h >= .94), h < .11, h < .18, h < .45, h < .53, h < .72, h < .84, h < .94], [3, 4, 6, 7, 8, 9, 10, 11], 3) hb = np.where((hb == 4) & (v < .55), 5, hb) # dark orange = brown hb = np.where((hb == 3) & (s < .5) & (v > .7), 11, hb) # light red = pink return np.where(chrom, hb, out)
def colour_class(name): name = ALIAS.get(name, name) return CLASSES.index(name) if name in CLASSES else None
# --------------------------------------------------------------------------------------------------------------# context: buffers + per-object solo visibilityclass Ctx: def __init__(self, info, scene, text): b = info self.b, self.scene, self.text = b, scene, text self.n, self.R = b["n"], b["R"] self.ids, self.depth, self.rgb, self.raw = b["ids"], b["depth"], b["rgb"], b["raw"] self.objs = b["objs"] self.ents = scene["entities"] self.prompted = [i for i, e in enumerate(self.ents) if not e.get("implicit")] self.rels = [tuple(r) for r in scene.get("prompt_relations", [])] self.solo = [solo_mask(b, k) for k in range(len(self.objs))] self.vis = [(self.ids == k) for k in range(len(self.objs))] self.area = self.n * self.n self.by_ent = {} for k, o in enumerate(self.objs): self.by_ent.setdefault(o.ent, []).append(k) self._sub_masks = {}
def ent_mask(self, ei): m = np.zeros((self.n, self.n), bool) for k in self.by_ent.get(ei, []): m |= self.vis[k] return m
def inst_ok(self, k, occl_ok=.55): v = self.vis[k].sum() s_in, s_all = self.solo[k][1], self.solo[k][2] return v >= MIN_FRAC * self.area and v >= (1 - occl_ok) * max(s_in, 1) and s_in >= .5 * max(s_all, 1)
def worn_or_held(self, ei): return any(getattr(self.objs[k].inst, "worn_by", None) is not None or getattr(self.objs[k].inst, "held_by", None) is not None for k in self.by_ent.get(ei, []))
def solo_mask(b, k): """March object k alone (plus the ground plane, which legitimately hides what is below it) over its projected bounding circle, extended past the frame. Returns (mask on the preview grid, in-frame px, total px incl. outside).""" from . import Scene3D, march n, R, f, y0, O = b["n"], b["R"], b["f"], b["y0"], b["O"] o = b["objs"][k] C = o.center - O if C[2] <= 1e-3: return np.zeros((n, n), bool), 0, 0 sc = n / R cx, cy = (R / 2 + f * C[0] / C[2]) * sc, (y0 - f * C[1] / C[2]) * sc rp = f * o.radius / max(C[2] - o.radius, .05 * C[2]) * sc x0, x1 = int(max(-n, math.floor(cx - rp))), int(min(2 * n, math.ceil(cx + rp))) y0p, y1p = int(max(-n, math.floor(cy - rp))), int(min(2 * n, math.ceil(cy + rp))) if x1 <= x0 or y1p <= y0p: return np.zeros((n, n), bool), 0, 0 ys, xs = np.mgrid[y0p:y1p, x0:x1] inside = (xs >= 0) & (xs < n) & (ys >= 0) & (ys < n) known = np.zeros(ys.shape, bool) known[inside] = b["ids"][ys[inside], xs[inside]] == k # visible pixels are hits already # outside the frame only the amount matters (for "cut by the edge"): sample every other pixel, weight 4 sub = ~inside & ((xs % 2) == 0) & ((ys % 2) == 0) todo = (inside & ~known) | sub xsf, ysf = (xs[todo] + .5) / sc, (ys[todo] + .5) / sc hm = known.copy() if len(xsf): D = np.stack([(xsf - R / 2) / f, (y0 - ysf) / f, np.ones_like(xsf)], -1) D = (D / np.linalg.norm(D, axis=1, keepdims=True)).astype(np.float32) s3 = Scene3D([o], ground=b["place"] not in ("sky", "space", "underwater")) t, hit = march(s3, O, D, b["zfar"], steps=60) if hit.any(): hi = np.nonzero(hit)[0] _, idd = s3.dist(O + D[hi] * t[hi, None], want_id=True) hit[hi] = idd == 0 hm[todo] = hit m = np.zeros((n, n), bool) m[ys[inside & hm], xs[inside & hm]] = True return m, int(m.sum()), int(m.sum() + 4 * (hm & sub).sum())
def _bbox(m): ys, xs = np.nonzero(m) return (xs.min(), ys.min(), xs.max(), ys.max()) if len(xs) else None
def _components(m): from scipy import ndimage lab, k = ndimage.label(m) if k == 0: return 0 sizes = ndimage.sum(m, lab, range(1, k + 1)) return int((sizes >= MIN_FRAC * m.size * .6).sum())
# --------------------------------------------------------------------------------------------------------------# critic terms@term("presence", 3.0)def t_presence(c): """every prompted entity is visible: enough pixels, not mostly occluded, not cut off by the frame edge""" for ei in c.prompted: ks = c.by_ent.get(ei, []) if not ks: continue name = c.ents[ei]["concept"] small = c.worn_or_held(ei) # worn / held things are small by nature: only need to be visible at all behind = any(s == ei and r == "behind" for s, r, o in c.rels) for k in ks: v = int(c.vis[k].sum()) m, s_in, s_all = c.solo[k] minpx = MIN_FRAC * c.area * (.3 if small else 1) if v < minpx: yield Finding("presence", 1, "%s#%d invisible (%d px)" % (name, c.objs[k].k, v), hard=True, ent=ei, insts=[k]) continue occl = 1 - v / max(s_in, 1) lim = .75 if behind else .55 if occl > lim and not small: yield Finding("presence", .5 + .5 * (occl - lim) / (1 - lim), "%s#%d %.0f%% occluded" % (name, c.objs[k].k, 100 * occl), hard=occl > lim + .15, ent=ei, insts=[k]) elif occl > .3 and not small: yield Finding("presence", .3 * (occl - .3) / (lim - .3), "%s#%d %.0f%% occluded" % (name, c.objs[k].k, 100 * occl), ent=ei, insts=[k]) cut = 1 - s_in / max(s_all, 1) if cut > .12: yield Finding("presence", min(1, cut / .5), "%s#%d %.0f%% outside the frame" % (name, c.objs[k].k, 100 * cut), hard=cut > .45, ent=ei, insts=[k]) seen = v / max(s_all, 1) if cut > .05 and seen < .4 and not small: # hidden AND cropped: what is left (a head poking in at the edge) no longer reads as the thing yield Finding("presence", .5 + (.4 - seen), "%s#%d only %.0f%% shows (occluded + cropped)" % (name, c.objs[k].k, 100 * seen), hard=seen < .25, ent=ei, insts=[k])
@term("count", 3.0)def t_count(c): """counts hold as distinct visible instances (each instance readable, and the group not merged into fewer blobs)""" for ei in c.prompted: e = c.ents[ei] want = e.get("count", 1) ks = c.by_ent.get(ei, []) if want < 2 or not ks or e.get("stack"): continue ok = [k for k in ks if c.inst_ok(k, occl_ok=.6)] if len(ok) < want: yield Finding("count", 1, "%s: %d of %d instances readable" % (e["concept"], len(ok), want), hard=True, ent=ei, insts=[k for k in ks if k not in ok]) # merged silhouettes: the entity's visible union splits into fewer blobs than instances m = c.ent_mask(ei) blobs = _components(m) if blobs < want and len(ok) >= want: # a viewer still counts overlapping copies if a visible edge separates them (a shading / colour step # where one instance meets the other); copies of one flat colour melt into a single shape lum = _lum(c.rgb) cut = np.zeros_like(m) for ax in (0, 1): a_ = np.take(c.ids, range(c.n - 1), ax); b_ = np.take(c.ids, range(1, c.n), ax) la = np.take(lum, range(c.n - 1), ax); lb = np.take(lum, range(1, c.n), ax) e_ = (a_ != b_) & np.isin(a_, ks) & np.isin(b_, ks) & (np.abs(la - lb) > .06) if ax == 0: cut[:-1] |= e_; cut[1:] |= e_ else: cut[:, :-1] |= e_; cut[:, 1:] |= e_ seen = _components(m & ~cut) hard = seen < want and seen <= want - 1 and (want - seen) / want >= .5 yield Finding("count", (.35 if not hard else .8) * (want - min(seen, want - 1)) / want, "%s: %d instances merge into %d blobs (%d with visible edges)" % (e["concept"], want, blobs, seen), hard=hard, ent=ei, insts=ks)
def _stats(c, ei): m = c.ent_mask(ei) if m.sum() < 3: return None ys, xs = np.nonzero(m) d = c.depth[m] return dict(cx=xs.mean(), cy=ys.mean(), top=np.percentile(ys, 5), bot=np.percentile(ys, 95), x0=np.percentile(xs, 5), x1=np.percentile(xs, 95), depth=float(np.median(d[np.isfinite(d)])) if np.isfinite(d).any() else np.inf, m=m)
@term("relation", 3.0)def t_relation(c): """left/right/above/below/on/under/behind/in front of/next to hold in image space""" n = c.n for s, rel, o in c.rels: if s >= len(c.ents) or o >= len(c.ents): continue A, B = _stats(c, s), _stats(c, o) if A is None or B is None: continue # presence already flags it na, nb = c.ents[s]["concept"], c.ents[o]["concept"] bad, sev = False, 0.0 if rel in ("left_of", "right_of"): dx = (B["cx"] - A["cx"]) if rel == "left_of" else (A["cx"] - B["cx"]) bad = dx < .03 * n sev = 1.0 if dx < 0 else .5 g = (.03 * n - dx) / n elif rel in ("above", "below"): dy = (B["cy"] - A["cy"]) if rel == "above" else (A["cy"] - B["cy"]) hi_, lo_ = (A, B) if rel == "above" else (B, A) # the upper thing's bottom clears the lower thing's top (a little overlap allowed) bad = dy < .03 * n or hi_["bot"] > lo_["top"] + .2 * (lo_["bot"] - lo_["top"]) sev = 1.0 if dy < 0 or hi_["cy"] > lo_["top"] else .6 g = (hi_["bot"] - lo_["top"]) / n elif rel == "on": # the subject rests on the object: its bottom inside the object's upper part, horizontally overlapping ov = min(A["x1"], B["x1"]) - max(A["x0"], B["x0"]) bad = A["bot"] > B["bot"] + .02 * n or A["cy"] > B["cy"] + .05 * n or ov < 0 sev = .8 g = max(0, A["bot"] - B["bot"]) / n + max(0, -ov) / n elif rel == "under": # beneath it: lower in the picture, inside its horizontal span, at about the same depth ov = (min(A["x1"], B["x1"]) - max(A["x0"], B["x0"])) / max(1.0, A["x1"] - A["x0"]) dr = abs(math.log(max(A["depth"], 1e-6) / max(B["depth"], 1e-6))) if np.isfinite(A["depth"] + B["depth"]) else 0 bad = A["cy"] < B["cy"] or ov < .5 or dr > .25 sev = .8 g = max(0, .5 - ov) + max(0, dr - .25) + max(0, B["cy"] - A["cy"]) / n elif rel in ("behind", "in_front_of"): dd = (A["depth"] - B["depth"]) if rel == "behind" else (B["depth"] - A["depth"]) bad = not dd > 0 sev = 1.0 g = max(0, -dd) / max(1e-6, B["depth"]) ov = (min(A["x1"], B["x1"]) - max(A["x0"], B["x0"])) / max(1.0, min(A["x1"] - A["x0"], B["x1"] - B["x0"])) if not bad and ov < .3: # "behind" / "in front of" reads only when the two overlap in the picture (else it is just "beside") bad, sev, g = True, .5, .3 - ov if not bad: # the occlusion should go the right way too: the nearer thing may hide the farther, never the reverse near_k, far_k = (c.by_ent[o], c.by_ent[s]) if rel == "behind" else (c.by_ent[s], c.by_ent[o]) wrong = sum(int((c.solo[k][0] & np.isin(c.ids, far_k)).sum()) for k in near_k) if wrong > MIN_FRAC * c.area: bad, sev, g = True, .6, wrong / c.area * 20 elif rel == "next_to": gap = max(A["x0"], B["x0"]) - min(A["x1"], B["x1"]) bad = gap > .3 * n sev = .5 g = gap / n - .3 else: continue if bad: # graded: how far from holding (gives the search a slope to climb even while the relation still fails) yield Finding("relation", .6 * sev + .4 * min(1.0, max(0.0, g) * 2), "%s %s %s fails in image space" % (na, rel, nb), hard=sev >= .8, ent=s, rel=(s, rel, o), insts=c.by_ent.get(s, []) + c.by_ent.get(o, []))
@term("colour", 2.0)def t_colour(c): """a named colour dominates its object's pixels (before the colour check repaints it); no other object carries the same named colour strongly (the binding would be ambiguous)""" cls_raw = classify(c.raw) cls_fin = classify(c.rgb) named = {} for ei in c.prompted: e = c.ents[ei] if not (e.get("color") and e.get("color_explicit", True)): continue tc = colour_class(e["color"]) if tc is None: continue named[ei] = tc m = c.ent_mask(ei) if m.sum() < 4: continue def dom(cl): v = cl[m] near = np.array([(CLASSES[x], CLASSES[tc]) in NEAR for x in range(len(CLASSES))]) return ((v == tc).mean() + .5 * near[v].mean()) d_raw, d_fin = dom(cls_raw), dom(cls_fin) if d_raw < .45: yield Finding("colour", (.45 - d_raw) / .45, "%s reads %.0f%% %s before the colour check" % (e["concept"], 100 * d_raw, e["color"]), hard=d_fin < .3, ent=ei, insts=c.by_ent.get(ei, [])) for ei, tc in named.items(): for ej in c.by_ent: if ej == ei or ej in named and named[ej] == tc or ej is None: continue m = c.ent_mask(ej) if m.sum() < MIN_FRAC * c.area: continue share = (cls_fin[m] == tc).mean() if share > .5: yield Finding("colour", .6 * share, "%s is also %s (binding ambiguous)" % (c.ents[ej]["concept"], CLASSES[tc]), ent=ej, insts=c.by_ent.get(ej, []))
def _lum(rgb): return rgb @ np.array([.299, .587, .114])
@term("figure_ground", 1.0)def t_contrast(c): """the subject separates from what surrounds it: luminance or colour difference to a ring of background""" from scipy import ndimage objm = c.ids >= 0 for ei in c.prompted[:3]: m = c.ent_mask(ei) if m.sum() < MIN_FRAC * c.area: continue ring = ndimage.binary_dilation(m, iterations=3) & ~ndimage.binary_dilation(m, iterations=1) & ~objm if ring.sum() < 6: continue a, g = c.rgb[m], c.rgb[ring] dl = abs(float(np.median(_lum(a)) - np.median(_lum(g)))) dc = float(np.linalg.norm(np.median(a, 0) - np.median(g, 0))) sep = max(dl * 1.6, dc) if sep < .16: w = 1.0 if ei == c.prompted[0] else .6 yield Finding("figure_ground", w * (.16 - sep) / .16, "%s blends into its surroundings (sep %.2f)" % (c.ents[ei]["concept"], sep), ent=ei, insts=c.by_ent.get(ei, []))
@term("overlap", 1.0)def t_overlap(c): """no awkward overlaps or tangents: unrelated objects slightly clipping each other, silhouettes that just kiss, objects grazing the frame edge""" from scipy import ndimage related = {(s, o) for s, r, o in c.rels} | {(o, s) for s, r, o in c.rels} for k, o in enumerate(c.objs): if o.ent is None: continue bnd = getattr(o.inst, "bound", None) m, s_in, s_all = c.solo[k] v = c.vis[k].sum() if s_in < MIN_FRAC * c.area: continue hidden = m & (c.ids >= 0) & (c.ids != k) for j in np.unique(c.ids[hidden]): oj = c.objs[j] if (o.ent, oj.ent) in related or bnd is oj.inst or getattr(oj.inst, "bound", None) is o.inst: continue fr = (hidden & (c.ids == j)).sum() / max(s_in, 1) if .03 < fr < .25: yield Finding("overlap", .5 * min(1, fr / .1), "%s#%d clipped %.0f%% by %s" % (o.name, o.k, 100 * fr, oj.name), ent=o.ent, insts=[k, int(j)]) # tangent: silhouettes touch along a short edge with (almost) no overlap rim = ndimage.binary_dilation(c.vis[k]) & ~c.vis[k] for j in np.unique(c.ids[rim]): if j < 0 or j == k: continue oj = c.objs[j] if (o.ent, oj.ent) in related or bnd is oj.inst or getattr(oj.inst, "bound", None) is o.inst or oj.ent == o.ent and False: continue touch = (rim & (c.ids == j)).sum() ov = (m & (c.ids == j)).sum() + (c.solo[j][0] & (c.ids == k)).sum() if touch >= 2 and ov <= 2 and k < j: yield Finding("overlap", .25, "%s#%d and %s#%d are tangent" % (o.name, o.k, oj.name, oj.k), ent=o.ent, insts=[k, int(j)]) # frame-edge tangent: an object that only grazes the frame edge bb = _bbox(c.vis[k]) if bb is not None and 0 < s_all - s_in <= .04 * s_all: yield Finding("overlap", .2, "%s#%d grazes the frame edge" % (o.name, o.k), ent=o.ent, insts=[k])
@term("prominence", 1.5)def t_prominence(c): """the first-named thing is the subject: it should not be a speck""" if not c.prompted: return ei = c.prompted[0] if c.worn_or_held(ei): return fr = c.ent_mask(ei).mean() want = .025 / (1 + .3 * (c.ents[ei].get("count", 1) - 1)) * c.ents[ei].get("count", 1) ** .5 if 0 < fr < want: yield Finding("prominence", (want - fr) / want, "%s is a speck (%.1f%% of frame)" % (c.ents[ei]["concept"], 100 * fr), hard=fr < .3 * want, ent=ei, insts=c.by_ent.get(ei, []))
@term("aesthetic", .6)def t_aesthetic(c): """cheap taste: the prompted things fill a sensible share of the frame; visual mass is balanced""" m = np.zeros((c.n, c.n), bool) for ei in c.prompted: m |= c.ent_mask(ei) fr = m.mean() if fr < .06: yield Finding("aesthetic", (.06 - fr) / .06, "subjects small (%.0f%% of frame)" % (100 * fr)) elif fr > .55: yield Finding("aesthetic", min(1, (fr - .55) / .3), "subjects crowd the frame (%.0f%%)" % (100 * fr)) if m.sum() > 10: ys, xs = np.nonzero(m) cx = xs.mean() / c.n if abs(cx - .5) > .17: yield Finding("aesthetic", min(1, (abs(cx - .5) - .17) / .2), "visual mass off-centre (x=%.2f)" % cx)
def critic(ctx, terms=None): """-> (score: lower is better, findings). Hard findings add a large constant so any faithful candidate beats any unfaithful one.""" fs = [] wts = {} for name, w, fn in TERMS: if terms and name not in terms: continue wts[name] = w fs.extend(fn(ctx)) score = sum(wts.get(f.term, 1.0) * f.sev + (4.0 if f.hard else 0.0) for f in fs) return score, fs
# --------------------------------------------------------------------------------------------------------------# scene program edits applied inside plot3d (hook after layout)def _subtree(insts, root): out, frontier = [root], [root] while frontier: nxt = [it for it in insts if getattr(it, "bound", None) is not None and any(it.bound is f for f in frontier) and it not in out] out += nxt frontier = nxt ents = {it.ent for it in out} # held / worn things follow their holder (single-instance holders only) for it in insts: for a in ("held_by", "worn_by"): hb = getattr(it, a, None) if hb is not None and hb in ents and sum(1 for x in insts if x.ent == hb) == 1 and it not in out: out.append(it) return out
def apply_nudges(insts, y0, R, nudges, trace): """nudges: {(ent, k): {"dx": fraction of width, "dd": depth factor -1..1 (+ = farther), "ds": size factor}}. A nudge moves the instance with everything resting on it (and what it holds / wears).""" for it in insts: nd = nudges.get((it.ent, it.k)) if not nd or not hasattr(it, "x"): continue group = _subtree(insts, it) flying = getattr(it, "pose", None) == "flying" dx = nd.get("dx", 0) * getattr(it, "w", it.h) s = 1 + nd.get("dd", 0) if getattr(it, "rel", None) != "on" and not flying else 1.0 dy = nd.get("dy", 0) * R if flying else 0.0 # flyers move up / down in the frame ds = nd.get("ds", 1.0) # size: the group scales about the instance's base point x0, yb = it.x, it.y for g in group: g.x = x0 + (g.x - x0) * ds / s + dx g.y = yb + (g.y - yb) * ds - dy g.h *= ds if hasattr(g, "w"): g.w *= ds if s != 1: g.y = y0 + (g.y - y0) / s g.h /= s if hasattr(g, "w"): g.w /= s trace.append("search: nudge %s#%d dx=%.2f dy=%.2f dd=%.2f ds=%.2f (+%d attached)" % (it.concept, it.k, nd.get("dx", 0), nd.get("dy", 0), nd.get("dd", 0), ds, len(group) - 1))
# --------------------------------------------------------------------------------------------------------------# searchfrom pydraw.variation import VARY_COLOR # noqa: E402
class Searcher: def __init__(self, text, seed=0, variation=1.0, res=512, preview=PREVIEW): from pydraw.understanding import parse tr = [] self.text, self.seed, self.variation, self.res, self.preview = text, seed, variation, res, preview self.parsed = (parse(text, tr), tr) self.evals = [] self.timing = []
def evaluate(self, prog): from . import plot3d t0 = time.time() p = dict(prog) p["_parsed"] = self.parsed im = plot3d(self.text, seed=self.seed, variation=self.variation, res=self.res, program=p, exp={"preview": str(self.preview), "soft": "0"}) b = im.info.get("buffers") if b is None: # the pixel renderer took over (a concept without a 3D model): nothing to search return None ctx = Ctx(b, im.info["scene"], self.text) score, fs = critic(ctx) self.timing.append(time.time() - t0) r = dict(prog=prog, score=score, findings=fs, hard=sum(f.hard for f in fs), img=im, ctx=ctx) self.evals.append(r) return r
# ---- proposals ---- def random_program(self, rng): return {"vseed": rng.randrange(1 << 30), "lseed": rng.randrange(1 << 30), "sun_x": rng.choice([-.55, .55])}
def propose(self, cur, rng): p = copy.deepcopy(cur["prog"]) ctx = cur["ctx"] fs = [f for f in cur["findings"] if f.insts] r = rng.random() rf = [f for f in fs if f.rel] if rf and r < .3: # data-driven proposal: repair a failing relation directly (move one side to where the relation holds) if self._repair(p, ctx, rng.choice(rf), rng): return p if fs and r < .6: # critic-targeted: move one of the instances a finding blames (sideways, in depth, or smaller) f = rng.choice(fs) k = rng.choice(f.insts) o = ctx.objs[k] key = (o.ent, o.k) nd = dict(p.setdefault("inst", {}).get(key, {})) # which move depends on what the finding says: a speck grows or comes closer, an occluded / merged / # misplaced thing moves sideways (flyers also up / down) or in depth moves = {"prominence": [("ds", 3), ("dd", 2), ("dx", 1)], "aesthetic": [("ds", 2), ("dd", 1), ("dx", 2)], "relation": [("dx", 3), ("dy", 2), ("dd", 2), ("ds", 1)]}.get(f.term, [("dx", 4), ("dd", 2), ("dy", 1), ("ds", 1)]) flying = getattr(o.inst, "pose", None) == "flying" moves = [(m, w) for m, w in moves if (m != "dy" or flying) and (m != "dd" or not flying)] mv = rng.choices([m for m, _ in moves], [w for _, w in moves])[0] if mv == "dy": nd["dy"] = float(np.clip(nd.get("dy", 0) + rng.uniform(-.12, .12), -.3, .3)) elif mv == "dx": nd["dx"] = float(np.clip(nd.get("dx", 0) + rng.choice([-1, 1]) * rng.uniform(.2, .7), -1.5, 1.5)) elif mv == "dd": closer = f.term in ("prominence",) nd["dd"] = float(np.clip(nd.get("dd", 0) + rng.uniform(-.3, .05 if closer else .25), -.6, .8)) else: up = f.term in ("prominence", "presence") nd["ds"] = float(np.clip(nd.get("ds", 1) * rng.uniform(.95 if up else .75, 1.35 if up else 1.1), .55, 1.6)) p["inst"][key] = nd if f.term == "colour" and rng.random() < .5: self._recolour(p, ctx, rng) if f.term == "figure_ground" and ctx.b["studio"] and rng.random() < .5: self._backdrop(p, rng) elif r < .7: p["lseed"] = rng.randrange(1 << 30) # new layout draw (positions, size jitter, yaws) elif r < .78: p["vseed"] = rng.randrange(1 << 30) # new variation draw (variants, setting, framing, mood) elif r < .86: p["sun_x"] = -p.get("sun_x", .55) p["sun_y"] = rng.uniform(.4, .75) elif r < .93 and ctx.b["studio"]: self._backdrop(p, rng) elif not self._recolour(p, ctx, rng): ks = list(range(len(ctx.objs))) if ks: o = ctx.objs[rng.choice(ks)] p.setdefault("yaw", {})[(o.ent, o.k)] = rng.uniform(-.5, .5) return p
def _repair(self, p, ctx, f, rng): s_, rel, o_ = f.rel ks, ko = ctx.by_ent.get(s_, []), ctx.by_ent.get(o_, []) if not ks or not ko: return False A, B = ctx.objs[rng.choice(ks)], ctx.objs[ko[0]] grpA = _subtree(ctx.b["insts"], A.inst) mover, other, sign = (A, B, 1) if B.inst not in grpA else (B, A, -1) # move the side that doesn't carry the other target = {"under": 1.0, "next_to": 1.0, "behind": 1.15, "in_front_of": .87, "on": 1.0}.get(rel) nd = dict(p.setdefault("inst", {}).get((mover.ent, mover.k), {})) if rel in ("left_of", "right_of"): sgn = (-1 if rel == "left_of" else 1) * sign want_x = other.inst.x + sgn * (other.inst.w + mover.inst.w) * .55 nd["dx"] = float(np.clip(nd.get("dx", 0) + (want_x - mover.inst.x) / max(mover.inst.w, 1), -3, 3)) elif rel in ("above", "below") and getattr(mover.inst, "pose", None) == "flying": nd["dy"] = float(np.clip(nd.get("dy", 0) + sign * (1 if rel == "above" else -1) * rng.uniform(.04, .12), -.4, .4)) elif target is None or getattr(mover.inst, "rel", None) == "on" or getattr(mover.inst, "pose", None) == "flying": return False else: if sign < 0: target = 1 / target # depth: scale the mover's layout depth so its Z becomes target x the other's Z; x: line up (with an # offset for behind / in front so the far one still shows) ratio = other.base[2] * target / max(mover.base[2], 1e-6) nd["dd"] = float(np.clip((1 + nd.get("dd", 0)) * ratio * rng.uniform(.95, 1.05) - 1, -.8, 2.0)) off = rng.uniform(-.45, .45) * other.inst.w if rel in ("behind", "in_front_of") else 0.0 if rel in ("under", "behind", "in_front_of", "on"): nd["dx"] = float(np.clip(nd.get("dx", 0) + (other.inst.x + off - mover.inst.x) / max(mover.inst.w, 1), -3, 3)) p["inst"][(mover.ent, mover.k)] = nd return True
def _backdrop(self, p, rng): from . import BACKDROPS, TABLE_WALLS p["backdrop"] = rng.choice(TABLE_WALLS if self.parsed[0].get("place") == "table" else BACKDROPS)
def _recolour(self, p, ctx, rng): free = [ei for ei, e in enumerate(ctx.ents) if e["concept"] in VARY_COLOR and not (e.get("color") and e.get("color_explicit", True)) and ei in ctx.prompted] if not free: return False ei = rng.choice(free) p.setdefault("colors", {})[ei] = rng.choice(VARY_COLOR[ctx.ents[ei]["concept"]]) return True
def run(self, budget=6.0, restarts=.25, temp=1.0, rng=None, log=None, evals=None): """budget: wall-clock seconds; evals: or a fixed number of previews (reproducible on a busy machine)""" rng = rng or random.Random(self.seed * 1009 + 7) t0 = time.time() base = self.evaluate({}) if base is None: return None, None best = cur = base n = 0 while (n < evals) if evals else (time.time() - t0 < budget): if best["score"] < .05: break frac = n / evals if evals else (time.time() - t0) / budget if frac < restarts: cand = self.evaluate(self.random_program(rng)) else: cand = self.evaluate(dict(self.propose(cur, rng))) n += 1 T = temp * max(.05, 1 - frac) if cand["score"] <= cur["score"] or rng.random() < math.exp(-(cand["score"] - cur["score"]) / T): cur = cand if cand["score"] < best["score"]: best = cand if frac >= restarts: cur = cand if frac >= restarts and cur is not best and rng.random() < .15: cur = best # occasional return to the best (keeps the chain from wandering off) if log: log("%5.2fs eval %d score %.2f (best %.2f)" % (time.time() - t0, n, cand["score"], best["score"])) # release image refs except base/best self.evals = [base, best] return base, best
def search_plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trace=False, budget=6.0, evals=None): from . import plot3d t0 = time.time() S = Searcher(text, seed=seed, variation=variation, res=res or 512) base, best = S.run(budget=budget, evals=evals) if best is None: return plot3d(text, seed=seed, size=size, res=res, variation=variation, ss=ss, return_trace=return_trace) prog = dict(best["prog"]) prog["_parsed"] = S.parsed im = plot3d(text, seed=seed, size=size, res=res, variation=variation, ss=ss, program=prog) tr = im.info["trace"] tr.append("search: %d previews in %.1fs (%.2fs each); critic %.2f -> %.2f, hard %d -> %d; program %s" % ( len(S.timing), sum(S.timing), np.mean(S.timing), base["score"], best["score"], base["hard"], best["hard"], {k: v for k, v in best["prog"].items()})) for f in best["findings"]: tr.append("search: remaining %r" % f) im.info["search"] = dict(base_score=base["score"], best_score=best["score"], base_findings=base["findings"], best_findings=best["findings"], program=best["prog"], previews=len(S.timing), secs=time.time() - t0) return (im, tr) if return_trace else im12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586"""pydraw3d.world: living, procedurally generated worlds around the prompt's subjects. Pure code (numpy maths + rules).
Instead of one object on a bare plane under a gradient sky, an outdoor scene gets a WORLD: eroded terrain (hills,mountains, cliffs, valleys, canyons, dunes), water (lakes, rivers, sea, lagoons, harbours), vegetation and buildingsas distant impostors (forests, orchards, cornfields, villages), a lit cloud sky (sunsets, stars, moon, aurora),weather (rain, snow, fog) and a real underwater world (caustics, god rays, sand ripples, kelp, coral, bubbles).
How it renders (fast on CPU):- the camera sits at the origin looking along +z, so x/z is constant along every primary ray. The world is stored on a WARPED grid: column u = x/z (one column per pixel column), row v = log z (rows get longer with distance, like pixels do). A primary ray walks one column, so its first terrain hit is a binary search in the column's running maximum of terrain elevation angle (the "voxel space" trick, exact per column). Mirrored camera = water reflections.- the terrain is: an eroded macro heightmap (Inigo Quilez's derivative-damped fbm + a stream-power incision pass with D8 flow accumulation + thermal slumping) sampled into the column grid, plus biome shaping (the subjects' flat stage, cliff drops, lake basins, river channels, dunes, strata) plus impostor bumps (tree crowns, corn rows, houses with gable roofs, rocks, coral, kelp).- shadows and ambient occlusion of the world are baked on the grid; the subjects are still SDF ray-marched by the main renderer and cast soft shadows on the near ground.- rule: dressing never duplicates a prompted concept (no trees if the prompt has a tree, no houses if it has a house...) and stays secondary: it starts behind the subjects, is small with distance and fades into haze."""import mathimport numpy as np
# ------------------------------------------------------------------------------------------------ noise_T = np.random.RandomState(20261125).rand(256, 256)
def vnoise(x, z, seed=0, deriv=False): """2D value noise in [0, 1] (smoothstep-interpolated lattice table), optionally with its analytic gradient.""" x = x + (seed * 37.17) % 256 z = z + (seed * 91.31) % 256 xf, zf = np.floor(x), np.floor(z) fx, fz = x - xf, z - zf xi = xf.astype(np.int64) & 255 zi = zf.astype(np.int64) & 255 x1, z1 = (xi + 1) & 255, (zi + 1) & 255 a, b, c, d = _T[zi, xi], _T[zi, x1], _T[z1, xi], _T[z1, x1] ux, uz = fx * fx * (3 - 2 * fx), fz * fz * (3 - 2 * fz) k = a - b - c + d n = a + (b - a) * ux + (c - a) * uz + k * ux * uz if not deriv: return n dux, duz = 6 * fx * (1 - fx), 6 * fz * (1 - fz) return n, dux * ((b - a) + k * uz), duz * ((c - a) + k * ux)
def fbm2(x, z, octaves=4, seed=0, gain=.5, lac=2.03): a, tot, s = .5, 0.0, 1.0 for o in range(octaves): tot = tot + a * vnoise(x * s, z * s, seed + o) a *= gain s *= lac return tot
def eroded_fbm(x, z, octaves=7, seed=0): """Inigo Quilez's terrain: fbm whose octaves are damped where the accumulated slope is large, which carves ridges and smooth valleys that look eroded (returns roughly 0..1).""" a, b = 0.0, .5 dx = np.zeros_like(x) dz = np.zeros_like(x) px, pz = x, z for o in range(octaves): n, gx, gz = vnoise(px, pz, seed + o, deriv=True) dx = dx + gx dz = dz + gz a = a + b * n / (1 + dx * dx + dz * dz) b *= .5 # rotate + scale the domain each octave (decorrelates the lattice) px, pz = 1.6 * px - 1.2 * pz, 1.2 * px + 1.6 * pz return a
def ridged(x, z, octaves=5, seed=0): a, tot, s, w = .5, 0.0, 1.0, 1.0 for o in range(octaves): n = 1 - np.abs(2 * vnoise(x * s, z * s, seed + o) - 1) n = n * n * w w = np.clip(n * 1.5, 0, 1) tot = tot + a * n a *= .5 s *= 2.1 return tot
def hash2(ix, iz, seed=0): n = (ix * 374761393 + iz * 668265263 + seed * 144665 + 1013904223) & 0xFFFFFFFF n = (n ^ (n >> 13)) * 1274126177 & 0xFFFFFFFF return ((n ^ (n >> 16)) & 0xFFFF) / 65535.0
def smooth(e0, e1, x): t = np.clip((x - e0) / (e1 - e0), 0, 1) return t * t * (3 - 2 * t)
def lin(c): return (np.asarray(c, float) / 255.0) ** 2.2
def blur2(a, r): """separable box blur x3 (~gaussian) on a 2D grid, radius r cells, edge-clamped""" r = int(max(1, r)) out = a for _ in range(3): for ax in (0, 1): pw = [(0, 0), (0, 0)] pw[ax] = (r + 1, r) p = np.pad(out, pw, mode="edge") c = np.cumsum(p, axis=ax) if ax == 0: out = (c[2 * r + 1:] - c[:-2 * r - 1]) / (2 * r + 1) else: out = (c[:, 2 * r + 1:] - c[:, :-2 * r - 1]) / (2 * r + 1) return out
# ------------------------------------------------------------------------------------------------ erosion_MACRO_CACHE = {}
def macro_terrain(seed, n=160, extent=3200.0, style="alpine"): """Uniform heightmap in metres (n x n cells over extent x extent, centred on x=0, z from 0 to extent). eroded fbm, then a few rounds of stream-power incision (D8 flow accumulation: rivers cut valleys where much water collects) and thermal slumping (slopes steeper than the talus angle slide). Returns (H, flow).""" key = (seed, n, extent, style) if key in _MACRO_CACHE: return _MACRO_CACHE[key] cs = extent / n xs = (np.arange(n) - n / 2 + .5) * cs zs = (np.arange(n) + .5) * cs X, Z = np.meshgrid(xs, zs) sc = 1 / 1500.0 if style == "mesa": h = eroded_fbm(X * sc, Z * sc, 5, seed) h = np.floor(h * 7) / 7 + .4 * (h * 7 % 1) ** 6 / 7 # rule: canyons/mesas = terraced rock strata else: h = eroded_fbm(X * sc, Z * sc, 5, seed) * .7 + .3 * ridged(X * sc * .6, Z * sc * .6, 4, seed + 11) h = (h - h.min()) / (np.ptp(h) + 1e-9) h = h * 1000.0 flow = np.ones_like(h) # rule: stream-power erosion: dh = -K * A^0.5 * S (A = upstream area, S = downhill slope), a few passes nb = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] dist = np.array([math.hypot(a, b) * cs for a, b in nb]) idx = np.arange(n * n).reshape(n, n) for it in range(5): hp = np.pad(h, 1, mode="edge") ip = np.pad(idx, 1, mode="edge") drops = np.stack([(h - hp[1 + a:n + 1 + a, 1 + b:n + 1 + b]) / dist[k] for k, (a, b) in enumerate(nb)], 0) best = drops.argmax(0) slope = np.maximum(drops.max(0), 0) rec = np.stack([ip[1 + a:n + 1 + a, 1 + b:n + 1 + b] for a, b in nb], 0) rec = np.take_along_axis(rec, best[None], 0)[0].ravel() rec = np.where(slope.ravel() > 0, rec, np.arange(n * n)) order = np.argsort(-h.ravel(), kind="stable").tolist() area = [1.0] * (n * n) recl = rec.tolist() for i in order: r = recl[i] if r != i: area[r] += area[i] A = np.asarray(area).reshape(n, n) flow = A h = h - .5 * np.sqrt(A) * slope * cs * .01 # thermal: talus ~ 38 degrees for _ in range(3): hp = np.pad(h, 1, mode="edge") lap = (hp[:-2, 1:-1] + hp[2:, 1:-1] + hp[1:-1, :-2] + hp[1:-1, 2:]) / 4 - h steep = np.abs(lap) > .8 * cs h = h + np.where(steep, .25 * lap, .05 * lap) h = (h - h.min()) / (np.ptp(h) + 1e-9) _MACRO_CACHE[key] = (h, flow) return h, flow
def sample_uniform(G, x, z, extent, n): """bilinear lookup of a macro grid (metres)""" cs = extent / n fx = np.clip(x / cs + n / 2 - .5, 0, n - 1.001) fz = np.clip(z / cs - .5, 0, n - 1.001) ix, iz = fx.astype(np.int64), fz.astype(np.int64) tx, tz = fx - ix, fz - iz return (G[iz, ix] * (1 - tx) * (1 - tz) + G[iz, ix + 1] * tx * (1 - tz) + G[iz + 1, ix] * (1 - tx) * tz + G[iz + 1, ix + 1] * tx * tz)
def worley2(x, z, seed=0): """2D cellular noise: (F1, F2, cell hash) with unit-sized cells""" xi, zi = np.floor(x).astype(np.int64), np.floor(z).astype(np.int64) b1 = np.full(x.shape, 9.0) b2 = np.full(x.shape, 9.0) cid = np.zeros(x.shape) for dx in (-1, 0, 1): for dz in (-1, 0, 1): cx, cz = xi + dx, zi + dz px = cx + hash2(cx, cz, seed) pz = cz + hash2(cx, cz, seed + 7) d = np.hypot(x - px, z - pz) closer = d < b1 b2 = np.where(closer, b1, np.minimum(b2, d)) cid = np.where(closer, hash2(cx, cz, seed + 29), cid) b1 = np.minimum(b1, d) return b1, b2, cid
# ------------------------------------------------------------------------------------------------ biomes# Each biome is a few numbers + switches (metres). The fine biome comes from the prompt's own words when it names# one (cliff, cornfield, lagoon, village...), else from the parser's coarse place.BIOMES = { "meadow": dict(ground="grass", relief=5, far=150, far0=450, trees=("broad", .10, 45, 14), flowers=1, fields=1, hero=("oak", "maple")), "park": dict(ground="lawn", relief=3, far=80, far0=600, trees=("broad", .30, 25, 12), flowers=1, pond=1, hero=("oak", "maple", "birch")), "farm": dict(ground="grass", relief=4, far=110, far0=500, trees=("broad", .06, 60, 16), fields=1, barns=1, hero=("oak",)), "cornfield": dict(ground="dirt", relief=2, far=100, far0=600, trees=("broad", .05, 120, 16), corn=1, fields=1), "village": dict(ground="grass", relief=5, far=160, far0=500, trees=("broad", .12, 40, 13), houses=1, fields=1, hero=("oak",)), "forest": dict(ground="forest", relief=4, far=200, far0=450, trees=("mixed", .92, 9, 5.5), haze=1200, hero=("oak",)), "jungle": dict(ground="jungle", relief=3, far=260, far0=400, trees=("jungle", 1.0, 7, 6.0), haze=600, humid=1, hero=("palm", "palm", "palm")), "mountains": dict(ground="alpine", relief=10, far=360, far0=250, trees=("conifer", .3, 40, 7), snowline=230), "valley": dict(ground="alpine", relief=6, far=380, far0=300, trees=("conifer", .3, 40, 7), snowline=260, valley=1, water="river_z"), "cliff": dict(ground="rocky", relief=3, far=420, far0=600, trees=("conifer", .5, 30, 7), snowline=220, cliff=140, mist=1), "ledge": dict(ground="rock", relief=2, far=420, far0=600, trees=("conifer", .5, 30, 7), snowline=220, cliff=200, wall=1, mist=1), "canyon": dict(ground="redsand", relief=2, far=260, far0=180, style="mesa", trees=None, canyon=1, rocks=.06), "desert": dict(ground="sand", relief=0, far=130, far0=900, style="mesa", trees=None, dunes=26), "savanna": dict(ground="savanna", relief=3, far=160, far0=900, trees=("acacia", .05, 50, 24), haze=1600, hero=("acacia", "acacia")), "snow": dict(ground="snow", relief=6, far=380, far0=450, trees=("snowpine", .22, 40, 8), snowline=-1e9), "glacier": dict(ground="ice", relief=4, far=560, far0=300, trees=None, snowline=-1e9, crevasses=1), "arctic": dict(ground="snow", relief=1, far=220, far0=900, trees=None, snowline=-1e9, water="sea_ice"), "beach": dict(ground="sand", relief=0, far=170, far0=600, trees=None, water="sea", headlands=1), "lagoon": dict(ground="sand", relief=0, far=100, far0=900, trees=None, water="lagoon"), "lake": dict(ground="grass", relief=3, far=300, far0=500, trees=("mixed", .55, 25, 7), water="lake", hero=("birch",)), "river": dict(ground="grass", relief=3, far=160, far0=600, trees=("broad", .4, 20, 9), water="river", hero=("willow",)), "harbour": dict(ground="stone", relief=0, far=160, far0=800, trees=None, water="harbour"), "swamp": dict(ground="swamp", relief=1, far=60, far0=800, trees=None, water="swamp", haze=380, humid=1, mist=1), "volcanic": dict(ground="basalt", relief=6, far=300, far0=400, trees=None, volcano=1, haze=900, rocks=.08), "underwater": dict(ground="seabed", relief=1.5, far=0, far0=60, trees=None, underwater=1, rocks=.12),}
PLACE2BIOME = {"field": "meadow", "park": "park", "farm": "farm", "mountains": "mountains", "forest": "forest", "jungle": "jungle", "savanna": "savanna", "desert": "desert", "snow": "snow", "arctic": "arctic", "beach": "beach", "water": "lake", "underwater": "underwater", "swamp": "swamp", "volcanic": "volcanic"}
# the prompt's own setting words pick a finer world (checked in this order: more specific first)WORLD_WORDS = [ ("underwater", ("underwater", "under water", "under the sea", "under the ocean", "seabed", "sea floor", "seafloor", "ocean floor", "coral reef", "reef", "aquarium", "bottom of the ocean", "bottom of the sea")), ("ledge", ("ledge",)), ("cliff", ("cliff", "cliffs", "clifftop", "cliff top", "precipice", "summit", "mountaintop", "mountain top", "peak")), ("canyon", ("canyon", "gorge", "mesa", "badlands")), ("glacier", ("glacier", "ice field", "icefield", "ice cap")), ("lagoon", ("lagoon", "atoll", "tropical island", "tropical beach", "island")), ("harbour", ("harbour", "harbor", "port", "dock", "docks", "pier", "quay", "wharf", "marina")), ("cornfield", ("cornfield", "corn field", "maize field", "wheat field", "wheatfield", "farmland")), ("village", ("village", "hamlet")), ("valley", ("valley", "dale", "fjord")), ("river", ("river", "stream", "creek", "brook", "riverbank", "river bank")), ("lake", ("lake", "pond", "lakeside", "lakeshore", "loch")), ("forest", ("forest", "woods", "woodland", "grove")), ("meadow", ("meadow", "pasture", "prairie", "grassland", "hillside")),]
def pick_biome(scene, text): import re low = " " + re.sub(r"[^a-z ]", " ", text.lower()) + " " place = scene.get("place") for b, words in WORLD_WORDS: for w in words: if " %s " % w in low: if b == "underwater" and w in ("reef", "aquarium", "island") and place not in ("underwater", "beach", "water", None): continue return b return PLACE2BIOME.get(place)
# ------------------------------------------------------------------------------------------------ conflictsDRESS_SYNSETS = { "trees": ("tree.n.01", "shrub.n.01", "palm.n.03"), "houses": ("building.n.01", "house.n.01", "housing.n.01", "barn.n.01", "church.n.02", "tower.n.01"), "rocks": ("rock.n.01", "stone.n.02", "boulder.n.01"), "corn": ("corn.n.01", "corn.n.02", "corn.n.03", "cereal.n.01", "wheat.n.01", "wheat.n.02"), "flowers": ("flower.n.01", "flower.n.02"), "coral": ("coral.n.01", "coral.n.04", "anthozoan.n.01"), "kelp": ("seaweed.n.01", "alga.n.01", "kelp.n.01"),}DRESS_WORDS = {"trees": {"tree", "palm", "pine", "oak", "bush", "shrub", "forest", "birch", "willow", "acacia"}, "houses": {"house", "building", "barn", "church", "castle", "cottage", "skyscraper", "hut", "cabin", "lighthouse", "windmill", "tower", "temple", "farmhouse", "village"}, "rocks": {"rock", "stone", "boulder"}, "corn": {"corn", "wheat"}, "flowers": {"flower", "rose", "tulip", "sunflower", "daisy"}, "coral": {"coral"}, "kelp": {"seaweed", "kelp"}}
def conflicts(scene): """rule: a world never adds another instance of something the prompt asked for (counts must stay right): the prompt's concepts are checked against each kind of dressing by name and by WordNet is-a links.""" names = [e["concept"] for e in scene.get("entities", [])] out = set() for kind, words in DRESS_WORDS.items(): if any(n in words or n.split()[-1] in words for n in names): out.add(kind) try: from nltk.corpus import wordnet as wn for n in names: for s in wn.synsets(n.replace(" ", "_"), "n")[:2]: anc = {a.name() for p in s.hypernym_paths() for a in p} for kind, syn in DRESS_SYNSETS.items(): if anc & set(syn): out.add(kind) except Exception: pass return out
# ------------------------------------------------------------------------------------------------ materialsGRASS, ROCK, SNOW, SAND, CONIF, BROAD, WALL, PALM, CORN, CROP, HEDGE, CORAL, KELP, LAVA, ICE, PATH, QUAY, DEAD, ACACIA, PIER = range(20)GROUND_PAL = { "grass": ((88, 148, 58), (64, 116, 42)), "lawn": ((92, 162, 62), (74, 140, 50)), "forest": ((72, 88, 46), (96, 78, 52)), "jungle": ((52, 100, 40), (40, 80, 32)), "alpine": ((100, 142, 64), (80, 116, 54)), "rocky": ((118, 128, 78), (120, 114, 104)), "rock": ((132, 126, 118), (104, 99, 94)), "redsand": ((206, 128, 78), (186, 104, 62)), "sand": ((218, 188, 138), (200, 168, 120)), "savanna": ((206, 176, 96), (176, 146, 76)), "snow": ((240, 244, 250), (226, 233, 246)), "ice": ((210, 232, 244), (184, 214, 236)), "stone": ((168, 162, 154), (142, 138, 132)), "swamp": ((78, 88, 46), (64, 60, 40)), "basalt": ((48, 45, 47), (66, 61, 58)), "seabed": ((214, 198, 158), (184, 168, 132)), "dirt": ((136, 110, 74), (112, 90, 62)),}SPEC = np.zeros(20); ROUGH = np.full(20, .9)SPEC[SNOW], ROUGH[SNOW] = .25, .45SPEC[ICE], ROUGH[ICE] = .6, .15SPEC[WALL], ROUGH[WALL] = .08, .8SPEC[LAVA] = 0
class World: NU, NV = 608, 720 U0 = .62
def __init__(self, biome, scene, text, objs, upm, cam, seed, tod, L, trace, KX): # rule (counts): a prompted moon is the only moon; the night sky does not add its own self.moon_prompted = any('moon' in str(e.get('concept', '')) for e in scene.get('entities', [])) self.biome, self.b = biome, dict(BIOMES[biome]) self.text = text.lower() self.m, self.cam, self.seed, self.tod = max(upm, 1e-3), cam, seed, tod self.L = np.asarray(L, float) self.trace = trace self.KX = KX self.skip = conflicts(scene) self.season = scene.get("season") w = scene.get("weather") t = self.text self.snowing = any(k in t for k in ("snowing", "snowfall", "blizzard", "snowstorm", "falling snow", "snowflakes")) self.rain = w == "rain" or any(k in t for k in ("rain", "storm")) self.fog_w = w == "fog" or any(k in t for k in ("fog", "mist", "haze")) self.overcast = self.rain or "overcast" in t or "cloudy" in t or self.snowing self.aurora = "aurora" in t or "northern lights" in t or "southern lights" in t self.uw = bool(self.b.get("underwater")) if self.uw: self.rain = self.snowing = self.overcast = self.aurora = False if self.season == "autumn" and biome in ("meadow", "park"): pass # ---- the stage: where the subjects stand (metres behind the camera plane) m = self.m grounded = [o for o in objs if o.base[1] < .1 * o.scale + 1e-6 and not getattr(o, "dressing", False)] flo = [o for o in grounded if getattr(o, "floats", False)] land = [o for o in grounded if not getattr(o, "floats", False)] allg = grounded or objs self.zb = max([o.base[2] + .5 * o.radius for o in allg] or [3 * cam]) self.zbm = self.zb / m self.xext = max([abs(o.base[0]) + .5 * o.radius for o in allg] or [cam]) / m if flo and land: zw = .5 * (max(o.base[2] + .3 * o.radius for o in land) + min(o.base[2] - .3 * o.radius for o in flo)) elif flo: zw = 0.0 else: zw = self.zb + 1.2 * m self.zwm = zw / m self.floaters = bool(flo) self.float_back = max([o.base[2] + .6 * o.radius for o in flo] or [0]) / m self.lift = getattr(self, "lift", 0.0) self.wl = 0.0 if self.b.get("water") or self.b.get("pond") else -1e9 # water level (m) if self.b.get("water") == "harbour" and not flo: self.wl = -1.6 # rule: a harbour without boats in it: we stand on the quay, the water is lower if self.uw: self.wl = -1e9 self.objs = objs self.usub = [] for o in grounded: a_ = math.sqrt(max(((o.radius / o.scale - .15) / .5) ** 2 - 1, 0) / 2) hw_ = .55 * o.scale * max(a_, .6) zc = max(o.base[2], .3) self.usub.append(((o.base[0] - hw_) / zc, (o.base[0] + hw_) / zc))
# ------------------------------------------------------------------ grid helpers def _grid(self): m = self.m self.u = np.linspace(-self.U0, self.U0, self.NU) self.du = self.u[1] - self.u[0] self.z0 = .5 * self.cam self.zmax = 3600.0 * m self.v = np.linspace(math.log(self.z0), math.log(self.zmax), self.NV) self.dv = self.v[1] - self.v[0] Z = np.exp(self.v)[:, None] * np.ones((1, self.NU)) X = self.u[None, :] * Z return X, Z
def _coords(self, x, z): """world (units) -> fractional grid indices (iv, iu)""" zc = np.maximum(z, self.z0) fu = np.clip((x / zc - self.u[0]) / self.du, 0, self.NU - 1.001) fv = np.clip((np.log(zc) - self.v[0]) / self.dv, 0, self.NV - 1.001) return fv, fu
def lookup(self, G, x, z, nearest=False): fv, fu = self._coords(x, z) iv, iu = fv.astype(np.int64), fu.astype(np.int64) if nearest: return G[np.minimum((fv + .5).astype(np.int64), self.NV - 1), np.minimum((fu + .5).astype(np.int64), self.NU - 1)] tv, tu = fv - iv, fu - iu if G.ndim == 3: tv, tu = tv[:, None], tu[:, None] return (G[iv, iu] * (1 - tu) * (1 - tv) + G[iv, iu + 1] * tu * (1 - tv) + G[iv + 1, iu] * (1 - tu) * tv + G[iv + 1, iu + 1] * tu * tv)
# ------------------------------------------------------------------ terrain def _scatter(self, xm, zm, Hb, sel, cell, dens, seed, kind, hrange, rrange, densfn=None): """impostor instances on a jittered grid (3x3 neighbour cells): returns (bump top height in m, instance hash) for the selected points. kind decides the crown profile.""" # rule (anti-aliasing): an instance must span >= ~2.5 grid rows in depth (rows lengthen with distance), or # it becomes a one-row pillar; farther instances are dropped (dense covers continue as a canopy LOD) zlim = rrange[0] / (1.25 * self.dv) inner = zm[sel] < zlim x, z = xm[sel][inner], zm[sel][inner] ix, iz = np.floor(x / cell).astype(np.int64), np.floor(z / cell).astype(np.int64) best = np.full(len(x), -1e9) hid = np.zeros(len(x)) m = self.m for dx in (-1, 0, 1): for dz in (-1, 0, 1): cx, cz = ix + dx, iz + dz h0 = hash2(cx, cz, seed) px = (cx + .5 + .7 * (hash2(cx, cz, seed + 1) - .5)) * cell pz = (cz + .5 + .7 * (hash2(cx, cz, seed + 2) - .5)) * cell dd = dens if densfn is None else dens * densfn(px, pz) if getattr(self, "usub", None): # rule: near dressing never stands right behind a subject (keeps silhouettes clear) uu = px / np.maximum(pz, 1.0) for a_, b_ in self.usub: dd = np.where((pz < self.zbm + 70) & (uu > a_ - .06) & (uu < b_ + .06), 0.0, dd) s = hash2(cx, cz, seed + 3) r = rrange[0] + (rrange[1] - rrange[0]) * s d = np.hypot(x - px, z - pz) / r ok = (h0 < dd) & (d < 1) if not ok.any(): continue hh = hrange[0] + (hrange[1] - hrange[0]) * hash2(cx, cz, seed + 4) base = self.lookup(Hb, px * m, pz * m) / m ok &= base > self.wl + .25 dk = d if kind == "conifer": b = hh * np.clip(1 - dk, 0, None) ** 1.1 * (1 + .07 * np.sin(dk * 18)) elif kind == "broad": # lumpy crown: irregular outline + cauliflower top dk = d * (.8 + .4 * vnoise(x / 1.7, z / 1.7, seed + 5)) ok &= dk < 1 b = hh * (.3 + .7 * np.sqrt(np.clip(1 - dk * dk, 0, 1)) ** .7) * (.82 + .3 * vnoise(x / 1.3, z / 1.3, seed)) elif kind == "palm": ang = np.arctan2(z - pz, x - px) star = .35 + .65 * np.abs(np.cos(ang * 3.5)) b = np.where(dk < .08, hh, np.where(dk < star, hh * (1 - .25 * dk), -1e9)) elif kind == "acacia": b = np.where(dk < .1, hh * .7, hh * (.75 + .25 * np.sqrt(np.clip(1 - dk * dk, 0, 1)))) elif kind == "dead": b = np.where(dk < .12, hh, np.where(dk < .5, hh * .4 * (1 - dk), -1e9)) elif kind == "rock": b = hh * np.sqrt(np.clip(1 - dk * dk, 0, 1)) * (.75 + .5 * vnoise(x * 1.3, z * 1.3, seed)) elif kind == "coral": b = hh * np.sqrt(np.clip(1 - dk * dk, 0, 1)) * (.6 + .8 * vnoise(x * 3, z * 3, seed)) elif kind == "kelp": b = np.where(dk < .4, hh * (.8 + .2 * vnoise(x * 2, z * 2, seed)), -1e9) else: b = hh * (1 - dk) top = base + b better = ok & (top > best) best = np.where(better, top, best) hid = np.where(better, s * .999 + 1e-4, hid) B_ = np.full(len(inner), -1e9) I_ = np.zeros(len(inner)) B_[inner], I_[inner] = best, hid return B_, I_
def build(self): t0 = __import__("time").time() B, sd, m = self.b, self.seed, self.m X, Z = self._grid() xm, zm = X / m, Z / m zs = zm - self.zbm H = np.zeros_like(xm) mat = np.zeros(xm.shape, np.int16) aux = np.zeros_like(xm) top = np.zeros_like(xm) ext, NM = 4800.0, 256 style = B.get("style", "alpine") mh, flow = macro_terrain(sd, NM, ext, style) mh_s = sample_uniform(mh, xm, zm, ext, NM) fl_s = sample_uniform(np.log1p(flow), xm, zm, ext, NM) self.flow = fl_s if B.get("far"): # rule: distant mountains / hills rise only far behind the subjects (the foreground stays a stage) H += B["far"] * mh_s ** 1.4 * smooth(B["far0"], B["far0"] * 4, zs) if B.get("relief"): H += B["relief"] * (fbm2(xm / 80, zm / 80, 4, sd + 3) - .42) * 2 * smooth(12, 80, zs) if B.get("dunes"): # rule: dunes are asymmetric ridges (gentle windward side, steep slip face) that grow with distance d1 = ridged((xm * .85 + zm * .35) / 130, (zm - .3 * xm) / 75, 3, sd + 8) H += B["dunes"] * d1 ** 1.6 * smooth(3, 60, zs) if B.get("canyon"): # rule: a canyon floor between stepped red rock walls (horizontal strata) that close in with distance xr = 25 * np.sin(zm / 230 + sd) side = smooth(35, 150, np.abs(xm - xr) - .08 * np.maximum(zs, 0)) H += 190 * side * (.55 + .6 * mh_s) * smooth(-5, 30, zs) if style == "mesa" and (B.get("canyon") or B.get("dunes")): Hq = np.floor(H / 16) * 16 + 16 * ((H / 16) % 1) ** 5 H = np.where(H > 6, Hq, H) if B.get("valley"): xr = 18 * np.sin(zm / 190 + 1 + sd) H += 340 * (.45 + .75 * mh_s) * smooth(60, 520, np.abs(xm - xr)) * smooth(0, 120, zs) if B.get("volcano"): xv, zv = (-1) ** sd * 380.0, 2400.0 r = np.hypot(xm - xv, zm - zv) cone = 820 * np.clip(1 - r / 2300, 0, 1) ** 1.25 - 160 * smooth(300, 120, r) H = np.maximum(H, cone) self.volc = (xv, zv) H = np.where(zs < 0, 0.0, H) # the stage itself is flat if B.get("cliff"): # rule: on a cliff / ledge the ground ends just behind the subjects and drops into a valley far below edge = .8 + 2.4 * fbm2(xm / 7, xm * 0 + 3.3, 3, sd + 5) drop = smooth(edge, edge + .5, zs) valley = -B["cliff"] + 10 * (fbm2(xm / 90, zm / 90, 4, sd + 6) - .45) * 2 + H * 1.35 H = H * (1 - drop) + valley * drop + .15 * fbm2(xm * 2, zm * 2, 2, sd) * (1 - drop) mat = np.where((drop > .02) & (drop < .98), ROCK, mat) self.mist_y = -B["cliff"] * .8 if B.get("wall"): # rule: a ledge clings to a rock face: a wall of rock rises on one side, close to the subjects sg = 1 if sd % 2 == 0 else -1 wx = self.xext + 1.2 + .8 * fbm2(zm / 3, zm * 0, 2, sd + 9) wall = (70 + 25 * fbm2(xm / 15, zm / 15, 3, sd + 10)) * smooth(wx, wx + 1.0, sg * xm) * smooth(80, 30, zs) H = np.maximum(H, wall) water = B.get("water") wl = self.wl if water or B.get("pond"): H = np.maximum(H, 0.0) if wl == 0 else H if water == "lake": near = self.zwm + (.6 * (fbm2(xm / 9, xm * 0, 3, sd + 11) - .45) if not self.floaters else -1e3) far = max(self.zwm, self.float_back) + 240 + 220 * fbm2(xm / 300, xm * 0 + 7, 3, sd + 12) lake = smooth(near, near + .5, zm) * (1 - smooth(far, far + 50, zm)) H = H * (1 - lake) + (-2.5) * lake H = np.where((lake < .5) & (zm > near + 1), H + 2.0 * smooth(far, far + 60, zm), H) elif water == "river": zc = self.zwm + 5 + 2 * np.sin(xm / 23 + sd) + 6 * (fbm2(xm / 70, xm * 0, 3, sd + 13) - .45) w = 5.0 + 1.5 * fbm2(xm / 30, xm * 0 + 2, 2, sd) if self.floaters: zc = np.full_like(xm, .5 * self.float_back + 1) w = zc + 3 d = np.abs(zm - zc) riv = 1 - smooth(w * .75, w, d) H = H * (1 - riv) - 1.6 * riv * (1 - (d / w) ** 2) H = np.where(zm > zc + w, H + .6 * smooth(zc + w, zc + w + 6, zm), H) elif water == "river_z": xr = 18 * np.sin(zm / 190 + 1 + sd) + 8 w = 4 + .012 * np.maximum(zs, 0) riv = (1 - smooth(w * .7, w, np.abs(xm - xr))) * smooth(4, 12, zs) H = H * (1 - riv) - 1.5 * riv elif water in ("sea", "lagoon", "sea_ice"): shore = self.zwm + .5 * np.sin(xm / 9 + sd) + .6 * (fbm2(xm / 25, xm * 0, 3, sd + 14) - .45) + (30 if water == "sea_ice" else 0) if self.floaters: shore = np.full_like(xm, -1e3) sea = smooth(shore - .2, shore + .4, zm) if water == "sea": depth = -(.15 + .05 * np.maximum(zm - shore, 0)) - .3 * fbm2(xm / 15, zm / 15, 2, sd) depth = np.maximum(depth, -40) elif water == "lagoon": f = fbm2(xm / 70, zm / 70, 4, sd + 15) depth = -(.25 + 2.2 * f) + 2.6 * smooth(.62, .7, f) * smooth(40, 120, zm - shore) reef = smooth(650, 700, zm) depth = depth * (1 - reef) - 25 * reef + 1.0 * smooth(15, 0, np.abs(zm - 660)) * (fbm2(xm / 8, xm * 0, 2, sd) > .5) else: f = fbm2(xm / 25, zm / 25, 3, sd + 16) depth = np.where(f > .52, .35, -1.5) H = H * (1 - sea) + depth * sea if B.get("headlands"): # rule: a coast has rocky headlands at the sides, so the sea is framed u = np.abs(xm / np.maximum(zm, 1)) H = np.maximum(H, 160 * mh_s ** 1.2 * smooth(.2, .45, u) * smooth(80, 300, zs)) elif water == "harbour": zq = max(self.zwm, self.float_back) + 38 + 4 * fbm2(xm / 40, xm * 0, 2, sd) Hw = -4.0 if self.wl < 0: # we stand on the near quay: water starts just behind the subjects near = self.zwm + 1.0 harb = smooth(near, near + .2, zm) * (1 - smooth(zq, zq + .2, zm)) else: harb = 1 - smooth(zq, zq + .2, zm) H = np.where(harb > .5, Hw, np.where(zm >= zq, 1.5 if self.wl == 0 else 0.0, H)) mat = np.where((harb <= .5), QUAY, mat) # pier: a wooden deck from the far quay toward us at one side sg = 1 if sd % 2 == 0 else -1 xp = sg * (self.xext + 7) pier = (np.abs(xm - xp) < 1.6) & (zm > zq - 22) & (zm < zq) & (harb > .5) H = np.where(pier, (1.5 if self.wl == 0 else 0.0) - .2, H) mat = np.where(pier, PIER, mat) self.quay = zq elif water == "swamp": f = fbm2(xm / 14, zm / 14, 3, sd + 17) pool = smooth(.5, .54, f) * smooth(1, 4, zs) if self.floaters: pool = np.maximum(pool, smooth(self.float_back + 4, self.float_back + 2, zm)) H = H * (1 - pool) - .4 * pool + .08 * smooth(0, 6, zs) H = np.where(zs < 0, np.where(pool > .5, -.4, 0.0), H) if B.get("pond"): sg = 1 if sd % 2 == 0 else -1 r = np.hypot((xm - sg * (self.xext + 14)) / 1.6, zm - self.zbm - 28) + 3 * fbm2(xm / 6, zm / 6, 2, sd) pond = 1 - smooth(9, 10, r) H = H * (1 - pond) - 1.0 * pond if self.uw: # rule: the seabed: sand dunes and ripples under the subjects, sloping away into the blue H = -self.lift / m + 1.2 * (fbm2(xm / 9, zm / 9, 3, sd + 18) - .45) * smooth(2, 12, zs) \ - .12 * np.maximum(zs - 25, 0) + 6 * mh_s * smooth(30, 120, zs) if water in ("lake", "river", "river_z", "sea", "lagoon", "sea_ice", "harbour", "swamp") or B.get("pond"): self.wetH = H.copy() Hb = H.copy() self.Hb_units = Hb * m # ---- impostor dressing (secondary, never a prompted concept, starts behind the subjects) skip = self.skip tr = B.get("trees") lod = 700.0 if tr and "trees" not in skip: kind, dens, start, cell = tr cover = lambda px, pz: smooth(.32, .5, vnoise(px / 160, pz / 160, sd + 21)) if dens < .6 else 1.0 if self.biome == "lagoon": cover = lambda px, pz: 1.0 hmax = 600 if self.b.get("snowline") is None or self.b["snowline"] < -1e8 else self.b["snowline"] - 20 sel = (zs > start) & (zm < lod) & (np.abs(xm) < zm * .7 + 20) if self.b.get("cliff"): sel &= zs > 5 kinds = {"mixed": [("conifer", (13, 24), (2.0, 3.2)), ("broad", (8, 13), (4.5, 6.5))], "conifer": [("conifer", (12, 22), (1.8, 3.0))], "snowpine": [("conifer", (10, 18), (1.8, 2.8))], "broad": [("broad", (7, 11), (4.5, 6.5))], "jungle": [], "palm": [("palm", (7, 12), (2.2, 3.2))], "acacia": [("acacia", (5, 8), (4, 6))], "dead": [("dead", (5, 9), (1.5, 2.5))]}[kind] for j, (kk, hr, rr) in enumerate(kinds): cl = cell * (1.0 if len(kinds) == 1 else 1.3) # rule: round-crowned impostors only far away (near, a heightfield crown reads as a green wall); # near trees are conifers (cones read fine) or real SDF hero trees nearlim = {"broad": 70.0 if self.biome != "jungle" else 45.0, "acacia": 250.0, "palm": 60.0}.get(kk, 0.0) sel_k = sel & (zs > nearlim) if nearlim else sel if not sel_k.any(): continue sel_ = sel sel = sel_k best, hid = self._scatter(xm, zm, Hb, sel, cl, dens / (1 if len(kinds) == 1 else 1.4), sd + 31 + 7 * j, kk, hr, rr, cover) up = best > H[sel] ii = np.nonzero(sel) Hs = H[sel] Hs[up] = best[up] H[sel] = Hs ms = mat[sel] ms[up] = {"conifer": CONIF, "broad": BROAD, "palm": PALM, "acacia": ACACIA, "dead": DEAD}[kk] mat[sel] = ms ax = aux[sel] ax[up] = hid[up] aux[sel] = ax tp = top[sel] tp[up] = best[up] - Hb[sel][up] top[sel] = tp sel = sel_ lod = min(700.0, max(r_[0] for _, _, r_ in kinds) / (1.25 * self.dv)) if kinds else start if dens >= .3: # rule (LOD): far forests are a continuous lumpy canopy (single trees would be sub-pixel noise) far = (zm >= lod) & (np.abs(xm) < zm * .7) if self.biome == "lagoon": far &= Hb > .3 cov = smooth(.3, .45, fbm2(xm / 260, zm / 260, 3, sd + 22)) if dens < .8 else np.ones_like(xm) ok = far & (Hb > self.wl + .3) & (cov > .05) if self.b.get("snowline") is not None and self.b["snowline"] > -1e8: ok &= Hb < self.b["snowline"] - 30 lump = fbm2(xm / 9, zm / 9, 2, sd + 23) if self.biome != "jungle" else fbm2(xm / 16, zm / 16, 3, sd + 23) can = (16 if self.biome != "jungle" else 24) * cov * (.75 + .5 * lump) * smooth(lod, lod + 60, zm) H = np.where(ok, Hb + can, H) mat = np.where(ok & (can > 1), CONIF if kind in ("conifer", "snowpine", "mixed") else BROAD, mat) aux = np.where(ok & (can > 1), fbm2(xm / 7, zm / 7, 1, sd), aux) self.canopy = ok & (can > 1) if B.get("rocks") and "rocks" not in skip: sel = (zs > 6) & (zm < 500) best, hid = self._scatter(xm, zm, Hb, sel, 9.0, B["rocks"], sd + 41, "rock", (.5, 2.2), (1.0, 2.6)) up = best > H[sel] Hs = H[sel]; Hs[up] = best[up]; H[sel] = Hs ms = mat[sel]; ms[up] = ROCK; mat[sel] = ms if self.uw: if "coral" not in skip: sel = ((zs > 2.5) | (np.abs(xm) > self.xext + 1.5)) & (zm < 120) best, hid = self._scatter(xm, zm, Hb, sel, 2.2, .55, sd + 51, "coral", (.3, 1.3), (.5, 1.1)) up = best > H[sel] Hs = H[sel]; Hs[up] = best[up]; H[sel] = Hs ms = mat[sel]; ms[up] = CORAL; mat[sel] = ms ax = aux[sel]; ax[up] = hid[up]; aux[sel] = ax if "kelp" not in skip: sel = ((zs > 4) | (np.abs(xm) > self.xext + 2)) & (zm < 150) best, hid = self._scatter(xm, zm, Hb, sel, 2.6, .22, sd + 53, "kelp", (2.0, 6.5), (.25, .4)) up = best > H[sel] Hs = H[sel]; Hs[up] = best[up]; H[sel] = Hs ms = mat[sel]; ms[up] = KELP; mat[sel] = ms ax = aux[sel]; ax[up] = hid[up]; aux[sel] = ax if B.get("corn") and "corn" not in skip: # rule: a cornfield = rows of tall stalks running away from the camera (strong perspective lines), # starting behind the subjects and at the frame sides; a stubble clearing where the subjects stand region = ((zs > 4) | ((np.abs(xm) > self.xext + .9) & (zs > -8))) & (zm < 420) fx = (xm / .76) % 1.0 - .5 fz = (zm / .34) % 1.0 - .5 plant = np.clip(1 - (np.abs(fz) / .5) ** 2, 0, 1) ** .25 * (.8 + .2 * vnoise(xm * 3, np.floor(zm / .34) * 7.3, sd + 62)) stalk = np.clip(1 - (np.abs(fx) / .4) ** 2, 0, 1) ** .35 * np.where(zm < 150, plant, 1.0) ch = (2.1 + .35 * vnoise(xm * 3, zm / 1.3, sd + 61)) * stalk * (1 - .25 * smooth(150, 420, zm)) \ + .35 * smooth(150, 420, zm) H = np.where(region, Hb + ch, H) mat = np.where(region & (ch > .2), CORN, mat) self.corn_end = 420 if B.get("fields") and "corn" not in skip: # rule: farmland is a patchwork of fields (wheat, pasture, ploughed earth, rapeseed) with hedgerows fsel = (zs > (30 if not B.get("corn") else 0)) & (mat == GRASS) & (Hb > self.wl + .2) & (zm > (420 if B.get("corn") else 0)) if self.b.get("snowline") is None: f1, f2, cid = worley2(xm[fsel] / 85, zm[fsel] / 55, sd + 71) mat_f = np.full(len(f1), CROP, np.int16) hedge = (f2 - f1) < .05 Hs = H[fsel] Hs = np.where(hedge, Hs + 2.4 * (.8 + .4 * vnoise(xm[fsel] / 2, zm[fsel] / 2, sd)), Hs + np.where(cid < .3, .8, 0)) mat_f[hedge] = HEDGE H[fsel] = Hs mat[fsel] = mat_f aux[fsel] = cid if (B.get("houses") or B.get("barns")) and "houses" not in skip: self._houses(xm, zm, zs, Hb, H, mat, aux, top) if water == "harbour" and "houses" not in skip: self._harbour_row(xm, zm, H, mat, aux, top) # ---- surface + maps self.H = H * m self.mat, self.aux, self.top = mat, aux, top * m self.Hm = H self.water = (H < self.wl) if self.wl > -1e8 else np.zeros(H.shape, bool) self.Hs = np.where(self.water, self.wl * m, self.H) self._maps(X, Z) self.trace.append("world: %s (%s%s) built in %.2fs" % (self.biome, self.tod, ", " + ",".join(sorted(self.skip)) + " skipped" if self.skip else "", __import__("time").time() - t0))
def _houses(self, xm, zm, zs, Hb, H, mat, aux, top): """village grammar: a road winds from the foreground to a village centre; houses (box + gable roof, one or two storeys) cluster around the centre and along the road, turned to face it; a church tower in the middle.""" sd = self.seed sg = 1 if sd % 2 == 0 else -1 vx, vz = sg * 60.0, self.zbm + 170.0 if self.b.get("barns"): vx, vz = -sg * 90.0, self.zbm + 220.0 self.village = (vx, vz) roadx = lambda z: vx * smooth(self.zbm + 20, vz, z) + 6 * np.sin(z / 40.0) sel = (zs > 25) & (zm < 900) x, z = xm[sel], zm[sel] cell = 20.0 if not self.b.get("barns") else 60.0 ix, iz = np.floor(x / cell).astype(np.int64), np.floor(z / cell).astype(np.int64) best = np.full(len(x), -1e9) hid = np.zeros(len(x)) tp = np.zeros(len(x)) for dx in (-1, 0, 1): for dz in (-1, 0, 1): cx, cz = ix + dx, iz + dz px = (cx + .5 + .4 * (hash2(cx, cz, sd + 81) - .5)) * cell pz = (cz + .5 + .4 * (hash2(cx, cz, sd + 82) - .5)) * cell rd = np.abs(px - roadx(pz)) dens = np.exp(-((px - vx) ** 2 + (pz - vz) ** 2) / (2 * 110.0 ** 2)) * .95 + .5 * smooth(30, 8, rd) * smooth(self.zbm + 40, self.zbm + 80, pz) if self.b.get("barns"): dens = .25 * np.ones_like(px) ok = (hash2(cx, cz, sd + 83) < dens) & (rd > 7) ang = np.where(hash2(cx, cz, sd + 84) < .5, 0.0, math.pi / 2) + .15 * (hash2(cx, cz, sd + 85) - .5) a = 4.0 + 3.0 * hash2(cx, cz, sd + 86) bb = 2.8 + 1.4 * hash2(cx, cz, sd + 87) hw = np.where(hash2(cx, cz, sd + 88) < .5, 3.4, 6.2) if self.b.get("barns"): a, bb, hw = a * 1.8, bb * 1.8, hw * 1.2 lx = (x - px) * np.cos(ang) + (z - pz) * np.sin(ang) lz = -(x - px) * np.sin(ang) + (z - pz) * np.cos(ang) inside = ok & (np.abs(lx) < a) & (np.abs(lz) < bb) base = self.lookup(self.Hb_units, px * self.m, pz * self.m) / self.m inside &= base > self.wl + .3 roof = .75 * bb * (1 - np.abs(lz) / bb) b = base + hw + roof better = inside & (b > best) best = np.where(better, b, best) hid = np.where(better, hash2(cx, cz, sd + 89) * .999 + 1e-4, hid) tp = np.where(better, base + hw, tp) # church: a tower with a spire at the centre (unless a building is prompted - already excluded by caller) if not self.b.get("barns"): dch = np.maximum(np.abs(x - vx), np.abs(z - vz)) base_c = float(self.lookup(self.Hb_units, np.array([vx * self.m]), np.array([vz * self.m]))[0] / self.m) tower = np.where(dch < 3.2, base_c + 20 + np.where(dch < 3.2, 11 * (1 - dch / 3.2), 0), -1e9) better = tower > best best = np.where(better, tower, best) hid = np.where(better, .5, hid) tp = np.where(better, base_c + 20, tp) up = best > H[sel] Hs = H[sel]; Hs[up] = best[up]; H[sel] = Hs ms = mat[sel]; ms[up] = WALL; mat[sel] = ms ax = aux[sel]; ax[up] = hid[up]; aux[sel] = ax t_ = top[sel]; t_[up] = tp[up]; top[sel] = t_ # the road itself (dirt / gravel) road = (np.abs(xm - roadx(zm)) < 2.6) & (zs > 3) & (mat != WALL) & (Hb > self.wl + .1) mat[road] = PATH H[road] = Hb[road]
def _harbour_row(self, xm, zm, H, mat, aux, top): """a harbour front: a continuous row of tall narrow coloured houses with gables facing the water""" zq = self.quay q0 = 1.5 if self.wl == 0 else 0.0 sel = (zm > zq + 5) & (zm < zq + 17) w = 6.5 cx = np.floor(xm[sel] / w) lx = xm[sel] / w - cx - .5 hw = 9 + 6 * hash2(cx.astype(np.int64), cx.astype(np.int64) * 0 + 1, self.seed + 91) roof = 4.5 * (1 - 2 * np.abs(lx)) b = q0 + hw + roof Hs = H[sel] Hs = np.maximum(Hs, b) H[sel] = Hs mat[sel] = WALL aux[sel] = hash2(cx.astype(np.int64), cx.astype(np.int64) * 0 + 2, self.seed + 92) * .999 + 1e-4 top[sel] = q0 + hw
# ------------------------------------------------------------------ baked maps def _maps(self, X, Z): H = self.Hs NV, NU = H.shape # normals from the warped grid: x = u e^v, z = e^v dHu = np.gradient(H, axis=1) / self.du dHv = np.gradient(H, axis=0) / self.dv zz = Z uu = X / Z # tangents: Pu = (z, dHu, 0), Pv = (u z, dHv, z) ; normal = Pv x Pu (pointing up) Pu = np.stack([zz, dHu, np.zeros_like(zz)], -1) Pv = np.stack([uu * zz, dHv, zz], -1) N = np.cross(Pv, Pu) N /= np.linalg.norm(N, axis=-1, keepdims=True) + 1e-12 N[N[..., 1] < 0] *= -1 self.N = N # ambient occlusion from height minus local average (anisotropic: rows are longer than columns) rr = max(1, int(round(self.du / self.dv * 6))) bl1 = blur2(H, 3) bl2 = blur2(H, 14) cw = zz * self.du ao = 1 - .9 * np.clip((bl1 - H) / (cw * 6), 0, 1) - .5 * np.clip((bl2 - H) / (cw * 30), 0, 1) self.AO = np.clip(ao, .25, 1) # sun shadows: march the heightfield toward the sun from every (half-res) cell L = self.L lh = math.hypot(L[0], L[2]) + 1e-9 lx, lz, tanv = L[0] / lh, L[2] / lh, L[1] / lh Hh = H[::2, ::2] Xh, Zh = X[::2, ::2], Z[::2, ::2] res = np.ones_like(Hh) dd = .05 * self.m while dd < 1500 * self.m: hx, hz = Xh + lx * dd, Zh + lz * dd hs = self.lookup(H, hx, hz) hs = np.where(hz < self.z0 * 2, 0.0 if not self.uw else hs, hs) res = np.minimum(res, np.clip(1 + 6 * (Hh + tanv * dd - hs) / dd, 0, 1)) dd *= 1.4 from scipy.ndimage import zoom sh = zoom(res, (NV / res.shape[0], NU / res.shape[1]), order=1)[:NV, :NU] self.SH = np.clip(sh, 0, 1) self.ALB = self._albedo(X / self.m, Z / self.m) # primary-ray tables: elevation slope of each grid point seen from the camera, running max per column A = np.clip((self.Hs - self.cam) / Z, -8, 8) self.A = A M = np.maximum.accumulate(A, axis=0) self.Mflat = (M.T + np.arange(NU)[:, None] * 32.0).ravel()
def _albedo(self, xm, zm): B, sd = self.b, self.seed mat, aux, Hm, N = self.mat, self.aux, self.Hm, self.N c1, c2 = GROUND_PAL.get(B["ground"], GROUND_PAL["grass"]) if self.season == "autumn" and B["ground"] in ("grass", "lawn", "alpine"): c1, c2 = (150, 145, 66), (122, 104, 50) f = fbm2(xm / 25, zm / 25, 4, sd + 100)[..., None] alb = lin(c1) * (1 - f) + lin(c2) * f if B["ground"] in ("grass", "alpine", "savanna", "lawn"): dry = smooth(.55, .7, fbm2(xm / 120, zm / 120, 3, sd + 101))[..., None] alb = alb * (1 - .45 * dry) + lin((158, 150, 82)) * .45 * dry # rule: valleys where water gathers are lusher lush = smooth(3.5, 6, self.flow)[..., None] alb = alb * (1 - .3 * lush) + lin((60, 110, 45)) * .3 * lush ny = N[..., 1] # rule: steep ground is bare rock; above the snow line (and on flat-enough slopes) lies snow rock = smooth(.82, .68, ny) if B["ground"] not in ("snow", "ice") else smooth(.6, .45, ny) if self.uw: rock = smooth(.6, .45, ny) rockc = lin((128, 122, 114)) if B["ground"] != "redsand" else lin((178, 96, 60)) if B["ground"] == "basalt": rockc = lin((40, 38, 40)) rr = rockc * (.75 + .5 * fbm2(xm / 6, zm / 6, 3, sd + 102))[..., None] if B.get("canyon") or B.get("style") == "mesa": # rule: sedimentary strata: horizontal colour bands in the rock band = np.sin(Hm * 1.3 + 2 * fbm2(xm / 40, zm / 40, 2, sd)) * .5 + .5 rr = rr * (.8 + .35 * band[..., None]) * np.array([1, .95 - .1 * 0, .9]) isg = (mat == GRASS) alb = np.where((isg | (mat == ROCK))[..., None], alb * (1 - rock[..., None]) + rr * rock[..., None], alb) alb[mat == ROCK] = rr[mat == ROCK] sl = B.get("snowline") if sl is not None: snow = smooth(sl - 30, sl + 30, Hm + 60 * (fbm2(xm / 80, zm / 80, 3, sd + 103) - .5)) * smooth(.45, .7, ny) if sl < -1e8: snow = smooth(.35, .55, ny) * np.ones_like(Hm) snowc = lin((242, 246, 252)) if B["ground"] != "ice" else lin((214, 234, 246)) alb = alb * (1 - snow[..., None]) + snowc * snow[..., None] self.snowmap = snow else: self.snowmap = np.zeros_like(Hm) if B.get("crevasses"): f1, f2, _ = worley2(xm / 30, zm / 12, sd + 104) crev = smooth(.06, .02, f2 - f1) * smooth(5, 15, zm - self.zbm) alb = alb * (1 - crev[..., None]) + lin((40, 110, 170)) * crev[..., None] # vegetation impostors: per-instance hue variation, darker toward the bottom of each crown h = aux[..., None] tree_pal = {CONIF: ((38, 72, 42), (28, 58, 36)), BROAD: ((70, 118, 46), (98, 132, 52)), PALM: ((70, 130, 50), (90, 140, 55)), ACACIA: ((96, 116, 52), (120, 128, 60)), DEAD: ((92, 80, 66), (70, 62, 52)), HEDGE: ((52, 92, 40), (62, 104, 44))} if self.season == "autumn": tree_pal[BROAD] = ((200, 110, 40), (215, 170, 60)) tree_pal[HEDGE] = ((150, 110, 50), (120, 95, 45)) if self.biome == "jungle": tree_pal[BROAD] = ((44, 104, 42), (70, 126, 44)) for code, (a, b) in tree_pal.items(): mk = mat == code if mk.any(): cc = lin(a) * (1 - h[mk]) + lin(b) * h[mk] leaf = (.7 + .6 * vnoise(xm[mk] * 1.7, zm[mk] * 1.7, sd + 105))[:, None] alb[mk] = cc * leaf if getattr(self, "canopy", None) is not None: # canopy LOD: crown-sized light/dark clumps so a far forest is not a smooth green hill ck = self.canopy alb[ck] *= (.45 + .9 * fbm2(xm[ck] / 4, zm[ck] / 4, 3, sd + 109))[:, None] if self.season == "autumn": mk = mat == BROAD red = aux[mk] > .7 tmp = alb[mk] tmp[red] = lin((170, 60, 35)) * (.7 + .6 * vnoise(xm[mk][red] * 1.7, zm[mk][red] * 1.7, sd))[:, None] alb[mk] = tmp if sl is not None and sl < -1e8: # rule: in snow, tree crowns carry snow on their upward-facing parts for code in (CONIF, BROAD, DEAD): mk = (mat == code) s = smooth(.55, .8, ny[mk]) * (vnoise(xm[mk] * 2, zm[mk] * 2, sd) > .35) alb[mk] = alb[mk] * (1 - s[:, None]) + lin((235, 240, 248)) * s[:, None] mk = mat == CORN if mk.any(): ht = (Hm[mk] - self.Hb_units.reshape(Hm.shape)[mk] / self.m) tip = smooth(1.9, 2.3, ht)[:, None] cc = lin((96, 132, 52)) * (.7 + .6 * vnoise(xm[mk] * 4, zm[mk] * 2, sd + 106))[:, None] if self.season == "autumn": cc = lin((190, 165, 90)) * (.75 + .5 * vnoise(xm[mk] * 4, zm[mk] * 2, sd + 106))[:, None] alb[mk] = cc * (1 - tip) + lin((215, 190, 110)) * tip mk = mat == CROP if mk.any(): pal = np.array([lin(c) for c in ((214, 182, 92), (110, 152, 62), (124, 96, 66), (230, 210, 70), (150, 170, 80), (96, 140, 58))]) k = (aux[mk] * 6).astype(int) % 6 cc = pal[k] plough = k == 2 stripe = (np.sin(xm[mk] * 2.0 + zm[mk] * .3) > 0) cc[plough & stripe] *= .75 alb[mk] = cc * (.85 + .3 * vnoise(xm[mk] / 6, zm[mk] / 6, sd + 107))[:, None] mk = mat == WALL if mk.any(): alb[mk] = lin((220, 210, 190)) # actual wall / roof colours are decided per hit (needs the 3D position) mk = mat == PATH alb[mk] = lin((165, 145, 112)) * (.85 + .3 * vnoise(xm[mk] * 2, zm[mk] * 2, sd))[:, None] mk = mat == QUAY alb[mk] = lin((150, 146, 140)) * (.85 + .3 * vnoise(xm[mk] * 3, zm[mk] * 3, sd))[:, None] mk = mat == PIER alb[mk] = lin((120, 90, 62)) * (.8 + .4 * (np.sin(zm[mk] * 12) > -.8))[:, None] mk = mat == CORAL if mk.any(): pal = np.array([lin(c) for c in ((236, 110, 90), (250, 170, 60), (180, 90, 200), (240, 200, 210), (90, 200, 190), (230, 80, 120))]) alb[mk] = pal[(aux[mk] * 6).astype(int) % 6] * (.7 + .6 * vnoise(xm[mk] * 8, zm[mk] * 8, sd))[:, None] mk = mat == KELP if mk.any(): alb[mk] = lin((96, 118, 36)) * (.6 + .6 * aux[mk])[:, None] if B.get("volcano") or B["ground"] == "basalt": # rule: volcanic ground: black basalt with glowing lava cracks f1, f2, _ = worley2(xm / 7, zm / 7, sd + 108) crack = smooth(.05, .015, f2 - f1) * smooth(4, 10, zm - self.zbm) * (fbm2(xm / 60, zm / 60, 2, sd) > .45) self.lava = crack else: self.lava = None return alb
# ------------------------------------------------------------------ rendering hooks def cast(self, D): """first terrain hit along primary rays from the camera (0, cam, 0); exact per grid column""" Dz = np.maximum(D[:, 2], 1e-4) u = D[:, 0] / Dz s = D[:, 1] / Dz iu = np.clip(np.round((u - self.u[0]) / self.du).astype(np.int64), 0, self.NU - 1) k = np.searchsorted(self.Mflat, s + iu * 32.0) - iu * self.NV hit = (k < self.NV) & (D[:, 2] > 1e-4) k = np.clip(k, 1, self.NV - 1) A1, A2 = self.A[k - 1, iu], self.A[k, iu] fr = np.clip((s - A1) / np.maximum(A2 - A1, 1e-9), 0, 1) z = np.exp(self.v[k - 1] + fr * self.dv) return z / Dz, hit
def sdf(self, P): """ground term for shadow / AO / normal rays near the subjects (a bound, not exact)""" h = self.lookup(self.Hs, P[:, 0], P[:, 2]) h = np.where(P[:, 2] < self.z0, self.lookup(self.Hs, P[:, 0] * 0, P[:, 2] * 0 + self.z0), h) return (P[:, 1] - h) * .6
def height_at(self, x, z): return self.lookup(self.Hb_units, np.asarray(x, float), np.asarray(z, float))
def surface(self, P, D, t): """materials at terrain hits: (normal, albedo, spec, rough, water mask, baked shadow, baked ao, emission)""" m, sd = self.m, self.seed # rule: a hit on a near-vertical heightfield wall lies between two grid rows; look the material up half a # row further along the ray (inside the wall), not in the ground cell in front of it P = P.copy() Pin = P + D * (.5 * self.dv * np.maximum(P[:, 2], self.z0))[:, None] x, z = Pin[:, 0], Pin[:, 2] N = self.lookup(self.N, P[:, 0], P[:, 2]) N /= np.linalg.norm(N, axis=-1, keepdims=True) + 1e-9 alb = self.lookup(self.ALB, x, z) sh = self.lookup(self.SH, x, z) ao = self.lookup(self.AO, x, z) mat = self.lookup(self.mat, x, z, nearest=True) aux = self.lookup(self.aux, x, z, nearest=True) xm, zm, ym = x / m, z / m, P[:, 1] / m dist = t / m near = dist < 40 em = np.zeros(len(P)) spec, rough = SPEC[mat].copy(), ROUGH[mat].copy() g = self.b["ground"] if near.any(): # rule: near ground shows fine texture (grass blades, sand grain, pebbles); it fades out with distance k = np.clip(1 - dist[near] / 40, 0, 1)[:, None] xn, zn = xm[near], zm[near] if g in ("grass", "lawn", "alpine", "savanna", "forest", "jungle", "swamp", "rocky"): bl = vnoise(xn * 38, zn * 9, sd + 120) * .6 + vnoise(xn * 9, zn * 38, sd + 121) * .4 tex = .72 + .5 * bl elif g in ("sand", "redsand", "seabed", "dirt"): tex = .9 + .2 * vnoise(xn * 30, zn * 30, sd + 122) else: tex = .88 + .25 * vnoise(xn * 12, zn * 12, sd + 123) gm = (mat[near] == GRASS) a = alb[near] a[gm] = a[gm] * (1 - k[gm]) + a[gm] * tex[gm, None] * k[gm] alb[near] = a if self.b.get("flowers") and "flowers" not in self.skip and self.tod != "night": cs = .09 ci = np.floor(np.stack([xn, zn], -1) / cs).astype(np.int64) hh = hash2(ci[:, 0], ci[:, 1], sd + 124) fr = np.stack([xn, zn], -1) / cs - ci - .5 dot = gm & (hh > .94) & ((fr ** 2).sum(-1) < .1) & (k[:, 0] > .2) pal = np.array([lin((250, 250, 245)), lin((245, 215, 70)), lin((235, 120, 150)), lin((180, 140, 230))]) pick = (hash2(ci[:, 0], ci[:, 1], sd + 125) * 4).astype(int) % 4 a = alb[near] a[dot] = pal[pick[dot]] alb[near] = a if g in ("sand", "seabed", "redsand") or self.b.get("dunes"): # rule: wind / wave ripples in sand: a sine ridge pattern bent by noise, as a normal perturbation ph = xn * 5.5 + zn * 2.2 + 3 * vnoise(xn / 2, zn / 2, sd + 126) amp = .22 * k[:, 0] Nn = N[near] Nn[:, 0] += amp * np.cos(ph) * .9 Nn[:, 2] += amp * np.cos(ph) * .35 N[near] = Nn / np.linalg.norm(Nn, axis=-1, keepdims=True) # houses: walls with windows and a door band, roofs with tile rows rk = ((mat == GRASS) | (mat == ROCK)) & (N[:, 1] < .6) & (dist < 400) if rk.any(): # rule: steep rock faces: cracked, layered stone (3D texture on the face), lichen-dark streaks lat = np.where(np.abs(N[rk][:, 0]) > np.abs(N[rk][:, 2]), zm[rk], xm[rk]) yy = ym[rk] rc = lin((118, 110, 100)) if self.b["ground"] not in ("redsand",) else lin((170, 95, 60)) if self.b["ground"] == "basalt": rc = lin((52, 50, 52)) f = fbm2(lat / 2.5, yy / 1.2, 4, sd + 131) crack = smooth(.04, 0, np.abs(vnoise(lat / 1.4, yy / 3, sd + 132) - .5)) strata = .5 + .5 * np.sin(yy * 2.2 + 2 * f) a = rc * (.35 + .9 * f + .15 * strata)[:, None] * (1 - .6 * crack)[:, None] streak = smooth(.55, .75, vnoise(lat * 1.5, yy / 8, sd + 133)) alb[rk] = a * (1 - .35 * streak)[:, None] cm = mat == CORN if cm.any(): # corn plants: green leaves with dark gaps, drier leaves low down, pale yellow tassels on top lat = np.where(np.abs(N[cm][:, 0]) > np.abs(N[cm][:, 2]), zm[cm], xm[cm]) hy = ym[cm] - self.lookup(self.Hb_units, x[cm], z[cm]) / m lf = vnoise(lat * 11 + hy * 3, hy * 6, sd + 128) * .6 + vnoise(lat * 27, hy * 2.5, sd + 129) * .4 base = lin((88, 128, 46)) if self.season != "autumn" else lin((190, 165, 90)) a = base * (.45 + .9 * lf)[:, None] a = np.where((lf < .33)[:, None], a * .35, a) dry = smooth(.9, .2, hy)[:, None] * .5 a = a * (1 - dry) + lin((150, 130, 80)) * dry * (.6 + .5 * lf)[:, None] tip = smooth(1.95, 2.15, hy)[:, None] a = a * (1 - tip) + lin((222, 200, 120)) * tip alb[cm] = a km = mat == KELP if km.any(): # kelp: long blades, banded, translucent-looking (brighter toward the light) hy = ym[km] - self.lookup(self.Hb_units, x[km], z[km]) / m band = .65 + .5 * vnoise(xm[km] * 6, hy * 2.5, sd + 134) alb[km] = alb[km] * band[:, None] * (.7 + .15 * hy)[:, None] em[km] = .08 wm = mat == WALL if wm.any(): hsh = aux[wm] topy = self.lookup(self.top, x[wm], z[wm], nearest=True) / m roof = (ym[wm] > topy - .05) & (N[wm][:, 1] > .25) wpal = np.array([lin(c) for c in ((236, 226, 206), (226, 200, 150), (210, 170, 130), (240, 240, 235), (190, 120, 90), (160, 180, 200), (225, 190, 110))]) rpal = np.array([lin(c) for c in ((168, 72, 52), (120, 60, 48), (90, 90, 100), (150, 90, 60))]) wc = wpal[(hsh * 7).astype(int) % 7] if self.b.get("barns"): wc = np.where((hsh < .6)[:, None], lin((160, 50, 40)), wc) rc = rpal[(hsh * 13).astype(int) % 4] * (.85 + .2 * (np.sin(ym[wm] * 25) > 0))[:, None] lat = np.where(np.abs(N[wm][:, 0]) > np.abs(N[wm][:, 2]), zm[wm], xm[wm]) wx = (lat / 2.4) % 1.0 wy = ((ym[wm] - (topy - 6.2)) / 2.9) % 1.0 win = (~roof) & (wx > .3) & (wx < .7) & (wy > .35) & (wy < .8) & (N[wm][:, 1] < .5) col = np.where(roof[:, None], rc, wc) lit = (hash2(np.floor(lat / 2.4).astype(np.int64), np.floor(ym[wm] / 2.9).astype(np.int64), sd + 127) > .45) col[win] = lin((50, 60, 72)) if self.tod != "night" else np.where(lit[win, None], lin((255, 200, 120)), lin((30, 30, 40))) a = alb[wm] alb[wm] = col if self.tod == "night": e = em[wm] e[win & lit] = .9 em[wm] = e s_, r_ = spec[wm], rough[wm] s_[win], r_[win] = .7, .15 spec[wm], rough[wm] = s_, r_ # rule: impostor trees: below the crown is the dark shaded trunk zone (so crowns read as crowns, not hedges) tm_ = np.isin(mat, (BROAD, ACACIA, CONIF, DEAD, PALM)) if tm_.any(): th = np.maximum(self.lookup(self.top, x[tm_], z[tm_], nearest=True), 1e-6) rel = (P[tm_, 1] - self.lookup(self.Hb_units, x[tm_], z[tm_])) / th cut = np.select([mat[tm_] == BROAD, mat[tm_] == ACACIA, mat[tm_] == PALM, mat[tm_] == DEAD], [.26, .7, .8, 1.1], .06) under = rel < cut a = alb[tm_] trunk = lin((52, 40, 30)) * (.6 + .5 * (np.sin(xm[tm_] * 9) > .3))[:, None] a[under] = a[under] * .25 * 0 + trunk[under] * (.35 + .65 * np.clip(rel[under] / np.maximum(cut[under], 1e-6), 0, 1))[:, None] ** 2 alb[tm_] = a # crowns are darker toward their lower edge (self-shadowing) a = alb[tm_] a[~under] *= (.55 + .45 * np.clip((rel[~under] - cut[~under]) / .4, 0, 1))[:, None] alb[tm_] = a water = self.water_mask(P) if self.lava is not None: lv = self.lookup(self.lava, x, z) em = np.maximum(em, lv * 1.6) alb = alb * (1 - lv[:, None]) + lin((255, 110, 30)) * lv[:, None] if self.rain: # rule: rain makes the ground darker and glossy alb *= .75 spec = np.maximum(spec, .35) rough = np.minimum(rough, .3) return N, alb, spec, rough, water, sh, ao, em
@property def refl_k(self): return {"lagoon": .45, "swamp": .25, "harbour": .6}.get(self.b.get("water"), .85)
def water_mask(self, P): if self.wl < -1e8: return np.zeros(len(P), bool) return (self.lookup(self.H, P[:, 0], P[:, 2]) < self.wl * self.m) & (np.abs(P[:, 1] - self.wl * self.m) < .02 * self.m + 1e-3)
def water_color(self, P, base_light): """rule: water colour = the bottom seen through the water (red absorbed first, so shallow sand turns turquoise and depth turns blue-green) + scattered light; foam where it is very shallow""" m = self.m depth = np.maximum(self.wl - self.lookup(self.H, P[:, 0], P[:, 2]) / m, 0) clar = {"lagoon": .55, "sea": .5, "swamp": .15}.get(self.b.get("water"), .35) sig = np.array([.45, .11, .07]) / clar bot = self.lookup(self.ALB, P[:, 0], P[:, 2]) * .45 tr = np.exp(-depth[:, None] * sig * 2) scat = np.array([.02, .09, .11]) if self.b.get("water") != "swamp" else np.array([.04, .05, .025]) c = bot * tr + scat * (1 - tr) foam = (depth < .12) & (vnoise(P[:, 0] / m * 3, P[:, 2] / m * 3, self.seed + 130) > .45) c[foam] = lin((235, 240, 240)) if self.b.get("water") == "swamp": # rule: swamp water is covered in patches of duckweed / algae xm, zm = P[:, 0] / m, P[:, 2] / m pt = smooth(.42, .55, fbm2(xm * 1.2, zm * 1.2, 3, self.seed + 135)) * (.7 + .3 * vnoise(xm * 9, zm * 9, self.seed)) c = c * (1 - pt[:, None]) + lin((80, 112, 40)) * pt[:, None] * 1.4 return c * base_light
def reflect(self, P, R, sky_fn): """mirror rays from water. A reflected camera ray stays (almost) in its grid column, so it is scanned row by row from the water point: blocks of rows whose max height is below the ray are skipped; inside a candidate block every row is tested (exact per row, no stride aliasing).""" n = len(P) out = sky_fn(R) if not hasattr(self, "_bmax"): BS = 16 nb = (self.NV + BS - 1) // BS pad = np.full((nb * BS, self.NU), -1e9) pad[:self.NV] = self.Hs self._bmax = pad.reshape(nb, BS, self.NU).max(1) self._BS, self._nb = BS, nb BS, nb = self._BS, self._nb zc = np.maximum(P[:, 2], self.z0) iu = np.clip(np.round((P[:, 0] / zc - self.u[0]) / self.du).astype(np.int64), 0, self.NU - 1) kw = np.clip(((np.log(zc) - self.v[0]) / self.dv).astype(np.int64) + 1, 0, self.NV - 1) sl = R[:, 1] / np.maximum(R[:, 2], 1e-4) y0 = P[:, 1] zrow = np.exp(self.v) hitk = np.full(n, -1) alive = (R[:, 2] > 1e-4) for b in range(kw.min() // BS, nb): k0 = b * BS cand = alive & (b >= kw // BS) if not cand.any(): continue zk0 = zrow[min(k0, self.NV - 1)] ci = np.nonzero(cand)[0] yr = y0[ci] + sl[ci] * (np.maximum(zk0, zc[ci]) - zc[ci]) ci = ci[self._bmax[b, iu[ci]] >= yr] if not len(ci): continue for j in range(BS): k = k0 + j if k >= self.NV: break ok = (k >= kw[ci]) & (hitk[ci] < 0) if not ok.any(): continue cj = ci[ok] hrow = self.Hs[k, iu[cj]] h = hrow >= y0[cj] + sl[cj] * (zrow[k] - zc[cj]) hitk[cj[h]] = k alive &= hitk < 0 if not alive.any(): break hi = hitk >= 0 if hi.any(): k, u_ = hitk[hi], iu[hi] zz = zrow[k] Q = np.stack([self.u[u_] * zz, self.Hs[k, u_], zz], -1) a = self.ALB[k, u_] Nq = self.N[k, u_] dif = np.clip(Nq @ self.L, 0, 1) * self.SH[k, u_] c = a * (self.sunc * self.sun_i * dif[:, None] + (self.zen * .6 + self.hor * .4) * self.amb * self.AO[k, u_][:, None]) tt = np.linalg.norm(Q - P[hi], axis=-1) + np.linalg.norm(P[hi] - np.array([0, self.cam, 0]), axis=-1) out[hi] = self.fog(c, tt, R[hi], Q) return out
# ------------------------------------------------------------------ light, sky, fog def light(self, zen, hor, sunc, sun_i, amb): """the world may change the light: overcast / rain / snow dim the sun and grey the sky, underwater is blue""" if self.uw: zen, hor = lin((40, 150, 190)), lin((12, 70, 105)) sunc = lin((200, 240, 255)) sun_i, amb = 2.2, .9 elif self.overcast: g = .8 if self.tod == "day" else .35 zen, hor = lin((128, 134, 146)) * g, lin((178, 182, 190)) * g sunc = lin((235, 238, 245)) sun_i, amb = sun_i * .3, amb * 1.35 if self.fog_w and not self.uw: g = 1 if self.tod == "day" else .3 if self.tod == "night" else .7 hor = lin((196, 200, 206)) * g zen = zen * .35 + hor * .65 sun_i, amb = sun_i * .55, amb * 1.2 self.overcast = True if self.aurora and self.tod == "night": amb *= 1.4 zen = zen * .6 + lin((20, 60, 50)) * .4 if self.b.get("volcano"): hor = hor * .7 + lin((200, 120, 90)) * .3 self.zen, self.hor, self.sunc, self.sun_i, self.amb = zen, hor, sunc, sun_i, amb return zen, hor, sunc, sun_i, amb
def sky(self, D): zen, hor, sunc, L = self.zen, self.hor, self.sunc, self.L sd, m = self.seed, self.m up = np.clip(D[:, 1], -1, 1) if self.uw: # rule: under water the "sky" is the water column: bright toward the surface, deep blue below k = np.clip(up * 1.6 + .25, 0, 1)[:, None] col = hor * (1 - k) + zen * k col = col * (1 + 1.5 * np.clip(up - .55, 0, 1)[:, None] ** 1.5 * 4) return col * np.clip(1 + up * .6, .35, 2)[:, None] sky = hor + (zen - hor) * np.clip(up * 2.2, 0, 1)[:, None] ** .8 sd_ = np.clip(D @ L, 0, 1) if self.tod == "sunset": # rule: at sunset the band near the horizon glows warm, most strongly on the sun's side Lh = np.array([L[0], 0, L[2]]) / (math.hypot(L[0], L[2]) + 1e-9) side = np.clip(D @ Lh, -1, 1) * .5 + .5 band = np.exp(-np.maximum(up, 0) / .12)[:, None] sky = sky + lin((255, 140, 80)) * .55 * band * (.35 + .65 * side[:, None]) - lin((60, 30, 0)) * .1 * (1 - band) if not self.overcast: sky = sky + sunc * (sd_ ** 400 * 6 + sd_ ** 8 * .25)[:, None] * (0 if self.tod == "night" else 1) if self.tod == "night": # stars: hashed cells on the direction sphere, a faint milky-way band, a moon with maria, a halo az = np.arctan2(D[:, 0], D[:, 2]) el = np.arcsin(np.clip(up, -1, 1)) ci, cj = np.floor(az * 260).astype(np.int64), np.floor(el * 260).astype(np.int64) hs = hash2(ci, cj, sd + 140) fx, fy = az * 260 - ci - .5, el * 260 - cj - .5 star = (hs > .985) * np.exp(-(fx * fx + fy * fy) * 14) * (hash2(ci, cj, sd + 141) * 1.5 + .2) nrm = np.array([.35, .75, .56]) mw = np.exp(-(D @ nrm) ** 2 / .02) * fbm2(az * 6, el * 6, 4, sd + 142) sky = sky + (star[:, None] * .9 + mw[:, None] * .06 * lin((200, 200, 230))) * np.clip(up * 5, 0, 1)[:, None] * (0 if self.overcast else 1) Mv = np.array([-.28 * (1 if L[0] > 0 else -1), .32, 1.0]) Mv /= np.linalg.norm(Mv) md = D @ Mv ang = np.arccos(np.clip(md, -1, 1)) disc = smooth(.036, .032, ang) mt = .8 + .25 * fbm2(D[:, 0] * 90, D[:, 1] * 90, 3, sd + 143) if not self.overcast and not self.moon_prompted: sky = sky + lin((250, 245, 225)) * (disc * mt * 1.8)[:, None] + lin((140, 150, 190)) * (np.exp(-ang / .12) * .12)[:, None] if self.aurora: # rule: aurora = folded curtains just above the horizon: green at the lower edge, fading to violet # upward, with fine vertical rays base = .06 + .1 * fbm2(az * 1.3, az * 0 + 5, 3, sd + 144) h = el - base curtain = np.where(h > -.01, np.exp(-np.maximum(h, 0) / .14), 0) * smooth(-.01, .005, h) rays = (.35 + .65 * vnoise(az * 160, az * 0 + 1, sd + 145)) ** 2 fold = .5 + .5 * np.sin(az * 5 + 4 * fbm2(az, az * 0, 2, sd + 146)) col = lin((60, 255, 140)) * (1 - smooth(.02, .25, h))[:, None] + lin((170, 70, 230)) * smooth(.02, .25, h)[:, None] sky = sky + col * (curtain * rays * (.4 + .9 * fold) * 1.1)[:, None] # clouds: a layer at ~1.8 km; density from fbm, self-shadowing toward the sun (darker bases, bright edges) ku = up > .004 if ku.any(): Dk = D[ku] tt = 1800.0 / Dk[:, 1] cx, cz = Dk[:, 0] * tt / 2600, Dk[:, 2] * tt / 2600 cov = .44 if not self.overcast else .18 if self.tod == "night" and not self.overcast: cov = .6 den = fbm2(cx, cz, 5, sd + 150) a = smooth(cov, cov + .22, den) den2 = fbm2(cx + L[0] * .06, cz + L[2] * .06, 4, sd + 150) shade = 1 - .6 * smooth(cov, cov + .35, den2) if self.tod == "sunset": lit = lin((255, 170, 120)) * 1.3 dark = lin((110, 80, 120)) elif self.tod == "night": lit, dark = lin((90, 100, 130)) * .5, lin((20, 24, 40)) elif self.overcast: lit, dark = hor * 1.15, hor * .55 else: lit, dark = lin((255, 252, 245)) * 1.15, lin((150, 160, 180)) cc = dark * (1 - shade[:, None]) + lit * shade[:, None] fade = smooth(.004, .09, Dk[:, 1]) * (1 - .4 * np.exp(-tt / 9000)) al = (a * fade * (.95 if not self.overcast else 1.0))[:, None] cir = smooth(.55, .8, fbm2(cx * .4, cz * 3.5, 4, sd + 151)) * smooth(.05, .3, Dk[:, 1]) * (.35 if self.tod != "night" else .1) * (not self.overcast) s_ = sky[ku] * (1 - al) + cc * al s_ = s_ + (lit * .5 - s_ * .3) * cir[:, None] sky[ku] = s_ if self.b.get("volcano"): # a smoke plume rising from the crater, drifting sideways xv, zv = self.volc Pv = np.array([xv, 760.0, zv]) dirv = Pv / np.linalg.norm(Pv) az0 = math.atan2(dirv[0], dirv[2]) az = np.arctan2(D[:, 0], D[:, 2]) el0 = math.asin(dirv[1]) el = np.arcsin(np.clip(up, -1, 1)) hh = el - el0 wdt = .015 + .5 * np.maximum(hh, 0) off = az - az0 - .6 * np.maximum(hh, 0) ** 1.3 plume = smooth(1, .3, np.abs(off) / wdt) * smooth(-.002, .01, hh) * (.55 + .45 * fbm2(az * 30, el * 30, 4, sd + 152)) sky = sky * (1 - .85 * plume[:, None]) + lin((95, 88, 86)) * .85 * plume[:, None] return sky
def fog(self, c, t, D, P): """aerial perspective: exponential haze thinning with altitude, tinted toward the sun; humid worlds and foggy weather are thicker; valleys below a cliff hold a layer of mist; under water light is absorbed (red first) and scattered blue-green""" m = self.m tm = t / m if self.uw: sig = np.array([.11, .045, .032]) * 1.4 tr = np.exp(-tm[:, None] * sig) depthk = np.clip(1 + D[:, 1] * .8, .3, 1.6)[:, None] wc = self.hor * depthk * 1.1 return c * tr + wc * (1 - tr) vis = self.b.get("haze", 2600) if self.fog_w: vis = 90 elif self.rain or self.snowing: vis = 700 k = np.clip(D[:, 1] * tm / 400, -30, 30) avg = np.where(np.abs(k) > 1e-4, (1 - np.exp(-k)) / np.where(np.abs(k) > 1e-4, k, 1), 1) od = tm / vis * np.clip(avg, 0, 5) if self.b.get("mist") or self.b.get("humid") or self.fog_w: # low mist: dense near the ground level of the far land (valley floor) and thin above my = getattr(self, "mist_y", 0.0) yy = P[:, 1] / m patchy = .5 + .7 * fbm2(P[:, 0] / m / 60, P[:, 2] / m / 60, 3, self.seed + 136) od = od + smooth(my + 40, my, yy) * smooth(20, 200, tm) * (.9 if self.b.get("cliff") else .18) * patchy f = 1 - np.exp(-od) sd_ = np.clip(D @ self.L, 0, 1) hz = self.hor[None, :] * (1 + .0 * sd_[:, None]) + self.sunc[None, :] * (sd_ ** 6 * (.6 if self.tod == "sunset" else .25))[:, None] * (0 if self.overcast else 1) if self.tod == "night": hz = self.hor[None, :] * np.ones((len(t), 1)) return c * (1 - f[:, None]) + hz * f[:, None]
def light_mod(self, P): """direct-light modulation at surface points: underwater caustics (focused ripple light)""" if not self.uw: return 1.0 m = self.m x, z = P[:, 0] / m, P[:, 2] / m wx = x + .6 * vnoise(x * .7, z * .7, self.seed + 160) wz = z + .6 * vnoise(x * .7 + 9, z * .7, self.seed + 161) r1 = 1 - np.abs(2 * vnoise(wx * 1.6, wz * 1.6, self.seed + 162) - 1) r2 = 1 - np.abs(2 * vnoise(wx * 2.3 + 3, wz * 2.3, self.seed + 163) - 1) ca = r1 ** 8 + r2 ** 8 return .45 + 1.8 * ca
def godrays(self, D, t): """under water: light shafts from the surface (volumetric: sample the shaft pattern along each ray)""" m = self.m n = len(D) acc = np.zeros(n) tmax = np.minimum(np.where(np.isfinite(t), t, 1e9), 30 * m) Ls = np.array([self.L[0] * .3, 1.0, self.L[2] * .3]) Ls /= np.linalg.norm(Ls) for i in range(8): tt = tmax * (i + .5) / 8 P = np.array([0, self.cam, 0]) + D * tt[:, None] ys = 12 * m k = (ys - P[:, 1]) / Ls[1] sx, sz = (P[:, 0] + Ls[0] * k) / m, (P[:, 2] + Ls[2] * k) / m pat = vnoise(sx * .55, sz * .55, self.seed + 170) pat = smooth(.55, .85, pat) * (.5 + .5 * vnoise(sx * 2, sz * 2, self.seed + 171)) acc += pat * np.exp(-tt / m * .08) * smooth(-14 * m, 6 * m, P[:, 1]) return acc / 8 * (tmax / (30 * m))
def post(self, img, depth, ids, D): """screen-space weather and water particles on the final (linear-ish, 0..1) image (n, n, 3)""" from PIL import Image, ImageDraw, ImageFilter n = img.shape[0] rng = np.random.RandomState(self.seed + 7) if self.uw: # bubbles: a few rising columns of small spheres with a bright rim ov = Image.new("RGBA", (n, n), (0, 0, 0, 0)) dr = ImageDraw.Draw(ov) for col in range(rng.randint(2, 5)): x0 = rng.uniform(.05, .95) * n y = n * rng.uniform(.6, 1.0) r0 = n * .004 while y > 0: r = r0 * rng.uniform(.6, 1.6) * (1 + (n - y) / n) x = x0 + np.sin(y / n * 20 + col) * n * .01 dr.ellipse([x - r, y - r, x + r, y + r], outline=(220, 245, 255, 150), width=max(1, int(r / 3))) dr.ellipse([x - r * .5, y - r * .6, x - r * .1, y - r * .2], fill=(255, 255, 255, 170)) y -= r * rng.uniform(3, 8) a = np.asarray(ov).astype(float) / 255 img = img * (1 - a[..., 3:]) + a[..., :3] * a[..., 3:] yy, xx = np.mgrid[0:n, 0:n] / n - .5 img = img * (1 - .35 * (xx ** 2 + yy ** 2))[..., None] if self.rain: # rain: thin bright slanted streaks (longer near), plus a cool desaturating veil 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)), 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) + .85 * a if self.snowing: 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
# ------------------------------------------------------------------ hero dressing objects def hero_objects(self, Obj, objs): """a few real SDF trees (generator family models) at the sides, 22-70 m away, never covering a subject. rule (speed): only round-crowned trees / palms / acacias (their overhangs need real geometry); conifers stay impostor cones (a hero conifer's needle SDF costs more than the whole rest of the picture)""" names = self.b.get("hero") if not names or "trees" in self.skip or self.KX.get("hero", "1") != "1": return [] from pydraw.open_vocab import family_model rng = np.random.RandomState(self.seed + 11) m = self.m subs = [] for o in objs: zc = max(o.base[2], .3) a_ = math.sqrt(max(((o.radius / o.scale - .15) / .5) ** 2 - 1, 0) / 2) # aspect back from the bound radius hw_ = .55 * o.scale * max(a_, .6) subs.append(((o.base[0] - hw_) / zc, (o.base[0] + hw_) / zc)) out = [] sides = [-1, 1] if rng.rand() < .5 else [1, -1] for i, nm in enumerate(names[:3]): fm = family_model(nm) if fm is None: continue fn, asp = fm for _ in range(12): zm_ = self.zbm + rng.uniform(22, 70) * (1.6 if self.biome == "savanna" else 1.0) hh = rng.uniform(.75, 1.15) * {"acacia": 8, "coconut palm": 11, "palm": 12, "willow": 10, "birch": 13, "spruce": 16}.get(nm, 12) # rule: hero trees frame the picture near its edges, whole (crown inside the frame), never covering a subject if (hh - self.cam / m) / zm_ > .4 and not ("palm" in nm and self.b.get("water")): zm_ = (hh - self.cam / m) / .4 uc = sides[i % 2] * rng.uniform(.28, .46) half = .5 * hh * asp / zm_ core = .35 * half if any(not (uc + core < a - .03 or uc - core > b + .03) for a, b in subs): continue if any(abs(uc - u2) < half + h2 for u2, h2 in [(q[0], q[1]) for q in out]): continue x, z = uc * zm_ * m, zm_ * m yb = float(self.height_at(np.array([x]), np.array([z]))[0]) if self.wl > -1e8 and float(self.lookup(self.H, np.array([x]), np.array([z]))[0]) < self.wl * m - 1e-6: continue parts = fn(None, None) ob = Obj(parts, (x, yb, z), hh * m, rng.uniform(0, 6.28), "_world_" + nm, asp) ob.col, ob.target, ob.cname, ob.dressing = None, None, None, True out.append((uc, half, ob)) break self.trace.append("world: hero trees %s" % [o.name for _, _, o in out]) return [o for _, _, o in out]
# ------------------------------------------------------------------------------------------------ entry pointNO_WORLD = ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office", "street", "space", "moon", "sky", "restaurant", "cafe", "library", "classroom", "supermarket", "garage", "cave", "throne room", "stadium", "station", "airport", "court", "rooftop", "alley")AMPHIBIOUS = {"frog", "toad", "turtle", "tortoise", "crocodile", "alligator", "hippo", "hippopotamus", "otter", "beaver", "platypus", "crab", "newt", "salamander", "capybara", "seal", "walrus", "sea lion", "penguin"}NOT_SWIMMERS = {"duck", "swan", "goose", "pelican", "penguin", "seagull", "gull", "flamingo", "heron"}
def make_world(scene, text, objs, upm, cam, seed, tod, L, trace, KX): """build the world for this scene, or None (indoor / street / space / sky keep their own settings)""" if KX.get("world", "1") != "1": return None from pydraw.registry import CONCEPTS place = scene.get("place") if place in NO_WORLD: return None biome = pick_biome(scene, text) ents = scene.get("entities", []) if biome in ("lake", "beach") and ents and all(CONCEPTS[e["concept"]]["setting"] == "underwater" or e["concept"].endswith("fish") for e in ents): biome = "underwater" # rule: fish alone in 'water' are seen under the surface if biome is None or biome not in BIOMES: return None if biome == "harbour": # rule: 'harbour' / 'pier' resolve to the marina concept; the harbour world already is the marina drop = [o for o in objs if o.name == "marina"] if drop and len(drop) < len(objs): for o in drop: objs.remove(o) trace.append("world: harbour world replaces the marina object") for o in objs: c = CONCEPTS.get(o.name, {}) # rule: amphibious animals (frogs, turtles, crocodiles...) stand on the bank; boats, birds on water and # sea animals are in the water o.floats = c.get("setting") in ("water", "underwater") and o.base[1] < .1 * o.scale + 1e-6 and o.name not in AMPHIBIOUS lift = 0.0 if biome == "underwater": # rule: swimmers hover above the seabed (the seabed is lowered under them); things that live on the bottom # (crabs, starfish, shells, divers' gear...) are set down onto it sw = [o for o in objs if CONCEPTS.get(o.name, {}).get("animal") and CONCEPTS[o.name]["setting"] in ("water", "underwater") and o.name not in NOT_SWIMMERS and o.name not in ("crab", "starfish", "lobster", "sea urchin")] if sw: lift = .45 * float(np.median([o.scale for o in sw])) for o in objs: if o not in sw and o.base[1] < .1 * o.scale: o.base = o.base - np.array([0, lift, 0]) o.center = o.center - np.array([0, lift, 0]) o.floats = False w = World.__new__(World) w.lift = lift World.__init__(w, biome, scene, text, objs, upm, cam, seed, tod, L, trace, KX) return wapp.py+17-10
pydraw/actions.pyAdded+287
pydraw/derived.pyAdded+125
pydraw/gloss.pyAdded+1616
pydraw/imagine.pyAdded+797
pydraw/layout.py+5-2
pydraw/open_vocab.py+28-1
pydraw/understanding.py+163-1
pydraw3d/MODELS.md+5
pydraw3d/__init__.py+411-54
pydraw3d/accel.pyAdded+155
pydraw3d/camera.pyAdded+559
pydraw3d/families/animals_other.py+71-11
pydraw3d/families/animals_other_aquatic.py+19-3
pydraw3d/families/animals_other_reptiles.py+27-3
pydraw3d/families/mammals.py+334-15
pydraw3d/families/z_sense_pins.pyAdded+13
pydraw3d/imagine.pyAdded+793
pydraw3d/imagine_creatures.pyAdded+336
pydraw3d/imagine_kit.pyAdded+737
pydraw3d/interact.pyAdded+213
pydraw3d/interior.pyAdded+206
pydraw3d/light.pyAdded+396
pydraw3d/models.py+3-1
pydraw3d/models_animals.py+9-9
pydraw3d/models_fire.pyAdded+63
pydraw3d/models_person.pyAdded+555
pydraw3d/models_sky.pyAdded+37
pydraw3d/natural.pyAdded+731
pydraw3d/paint.py+1298-144
pydraw3d/pose.pyAdded+223
pydraw3d/retro64.pyAdded+392
pydraw3d/search.pyAdded+708
pydraw3d/world.pyAdded+1586