Spaces:
Running
Running
night wave 3 merge (master decb488): body emotions, shoulders, pouch, fetch, horseback, shelters, circus balls, tethers, 3D window views, pixel atmosphere
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- pydraw/__init__.py+13-3
- pydraw/actions.py+64-1
- pydraw/atmos.pyAdded
- pydraw/attach.pyAdded+1097
- pydraw/character2d.py+418-15
- pydraw/characters.py
- pydraw/compose.py+55-1
- pydraw/concepts/animals.py+93-2
- pydraw/concepts/animals2.py+200-28
- pydraw/concepts/animals3.py+27-6
- pydraw/concepts/core.py+171-8
- pydraw/concepts/misc3.py+37-1
- pydraw/concepts/objects2.py+11-1
- pydraw/concepts/objects4.py+73
- pydraw/concepts/people.py+450-19
- pydraw/concepts/shapes.py+42-1
- pydraw/concepts/structures.py+101
- pydraw/concepts/vehicles.py+28
- pydraw/condition_px.pyAdded+361
- pydraw/frames.pyAdded+85
- pydraw/imagine.py+6-4
- pydraw/language.pyAdded+1589
- pydraw/layout.py+143-15
- pydraw/lexicon.py+1-1
- pydraw/mood.py+266-4
- pydraw/open_vocab.py+4
- pydraw/perch.py+3-1
- pydraw/physics.py+61
- pydraw/physics2.py+37-4
- pydraw/pixelart.py+16
- pydraw/pixeltex.py+6
- pydraw/retro.pyAdded+72
- pydraw/scenes.py+525-42
- pydraw/stage.pyAdded+400
- pydraw/surface.pyAdded+99
- pydraw/tether.pyAdded+145
- pydraw/typography/draw2d.py+1-1
- pydraw/typography/draw3d.py+8-6
- pydraw/typography/understand.py+39
- pydraw/understanding.py+33
- pydraw/variation.py+17-1
- pydraw3d/__init__.py+335-16
- pydraw3d/attach.pyAdded+284
- pydraw3d/characters.py+39-2
- pydraw3d/compile/__init__.py+98-4
- pydraw3d/compile/emit.py+2
- pydraw3d/compile/runtime.c+166
- pydraw3d/condition3d.pyAdded+190
- pydraw3d/contents.pyAdded+127
- pydraw3d/families/mammals.py+19
11 unmodified lines121314151617181920218 unmodified lines3031323334353643 unmodified lines808182838485868788899011 unmodified linesfrom .layout import layoutfrom .compose import composefrom .canvas import Imagefrom . import pixelart, stylesfrom .variation import vary__all__ = ["plot", "Image", "CONCEPTS"]def plot(text, seed=0, size=512, style="pixel", res=None, variation=1.0):8 unmodified linesscene = parse(text, trace)import os as _os_ev = dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)vary(scene, trace, random.Random(seed * 7919 + 13), float(_ev.get("vary", variation)))from . import mood as _mood_mood.apply(scene, text, trace) # wave 12: visual rhetoric (mood words -> time, weather, camera, framing, grade)pstyle = scene.get("style")43 unmodified linesfrom .typography.draw2d import restamprestamp(cv, trace)styles.apply(pstyle, cv.px, seed, trace) # rule: tone styles run after the palette snap so it can't undo thempixels = pixelart.upscale(cv.px, max(1, size // R))else:R = res or max(128, size // 2)insts, y0 = layout(scene, R, R, rng, trace)cv, _ = compose(scene, insts, y0, R, R, rng, trace, ss=2)styles.apply(pstyle, cv.px, seed, trace, ids=cv.ids)pixels = styles.upscale_bilinear(cv.px, size) if R != size else cv.pxreturn Image(pixels, scene, trace)11 unmodified lines1213141516171819202122238 unmodified lines3233343536373839404142434443 unmodified lines88899091929394959697989910011 unmodified linesfrom .layout import layoutfrom .compose import composefrom .canvas import Imagefrom . import pixelart, styles, framesfrom .variation import varyfrom .physics import display_name # readable concept names for summaries (simulated composites have internal keys)__all__ = ["plot", "Image", "CONCEPTS", "display_name"]def plot(text, seed=0, size=512, style="pixel", res=None, variation=1.0):8 unmodified linesscene = parse(text, trace)import os as _os_ev = dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)_vseed = seed * 7919 + 13if _ev.get("varytext", "1") != "0" and _ev.get("atmos", "1") != "0" and _ev.get("craft", "1") != "0":# rule (night pixel2, varytext): the open choices (breed, time, light, setting, mood) are drawn from the seed AND# the prompt, so different prompts at the same seed don't all get the same noon meadow (critic3 round 17)import zlib as _zlib_vseed += _zlib.crc32(" ".join(text.lower().split()).encode()) % 100003vary(scene, trace, random.Random(_vseed), float(_ev.get("vary", variation)), light=True)from . import mood as _mood_mood.apply(scene, text, trace) # wave 12: visual rhetoric (mood words -> time, weather, camera, framing, grade)pstyle = scene.get("style")43 unmodified linesfrom .typography.draw2d import restamprestamp(cv, trace)styles.apply(pstyle, cv.px, seed, trace) # rule: tone styles run after the palette snap so it can't undo themframes.apply_px(scene, cv.px, trace) # language shift 2: "a postcard of X"pixels = pixelart.upscale(cv.px, max(1, size // R))else:R = res or max(128, size // 2)insts, y0 = layout(scene, R, R, rng, trace)cv, _ = compose(scene, insts, y0, R, R, rng, trace, ss=2)styles.apply(pstyle, cv.px, seed, trace, ids=cv.ids)frames.apply_px(scene, cv.px, trace)pixels = styles.upscale_bilinear(cv.px, size) if R != size else cv.pxreturn Image(pixels, scene, trace)
39 unmodified lines4041424344454612 unmodified lines596061626364176 unmodified lines24124224324424524631 unmodified lines27827928028128228339 unmodified lines_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")12 unmodified linesDET = {"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)176 unmodified lineselse:rels.append((a, r, b))scene["relations"] = rels# rule: "balancing X on its nose / head" = holding it therefor k in anim:at = ents[k].get("attrs") or {}31 unmodified linesscene["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 toofor i, t in enumerate(toks):if t in ("walking", "walks") and i + 2 < len(toks) and toks[i + 1] in DET:39 unmodified lines4041424344454612 unmodified lines5960616263646566676869176 unmodified lines24624724824925025125225325425525625725825926026126226326426526626726826927027127227327427531 unmodified lines30730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534639 unmodified lines_v("cheering cheers celebrating", None, "cheer")_v("pointing", None, "point")_v("singing sings", None, "sing")_v("sleeping sleeps snoozing snoozes dozing dozes napping naps", "sleeping")_v("sitting sits", "sitting")_v("lying", "lying")_v("walking walks strolling strolls marching marches wandering wanders hiking hikes", "walking")12 unmodified linesDET = {"a", "an", "the", "two", "three", "four", "some", "one", "his", "her", "its", "their", "little", "big", "small", "young", "old", "cute", "baby"}def _os_env():import osreturn os.environ.get("PYDRAW_EXP", "")def _toks(text):text = re.sub(r'"[^"]*"', " ", text).lower().replace("-", " ").replace("'s", "")return re.findall(r"[a-z]+|\d+", text)176 unmodified lineselse:rels.append((a, r, b))scene["relations"] = rels# rule (night, knob mouth2=0): "a dog by the door with a leash in its mouth" - the thing right before# "in its mouth" is held by the nearest creature before it, even when the parser tied it to something else# (the leash hung 'on' the door)if dict(kv.split("=") for kv in _os_env().split(",") if "=" in kv).get("mouth2", "1") != "0":for i in range(len(toks) - 2):if toks[i] != "in" or toks[i + 1] not in ("its", "his", "her", "their") or toks[i + 2] not in MOUTH_WORDS | HAND_WORDS:continueth = [k for k in range(len(ents)) if pos[k] is not None and pos[k] < i]if not th:continuet_ = max(th, key=lambda k: pos[k])if pos[t_] != i - 1:continueow = [k for k in anim if pos[k] is not None and pos[k] < pos[t_] and k != t_]if not ow:continueo_ = max(ow, key=lambda k: pos[k])had = any(a == o_ and r == "holding" and b == t_ for a, r, b in scene["relations"])scene["relations"] = [(a, r, b) for a, r, b in scene["relations"] if a != t_ and not (b == t_ and r != "holding")]if had:continuescene["relations"].append((o_, "holding", t_))ents[o_].setdefault("attrs", {}).setdefault("action", "carry")trace.append("actions: %s held in %s's %s" % (ents[t_]["concept"], ents[o_]["concept"], toks[i + 2]))# rule: "balancing X on its nose / head" = holding it therefor k in anim:at = ents[k].get("attrs") or {}31 unmodified linesscene["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 (night, knob flee=0): "a mouse running / fleeing / escaping from a cat" = a chase seen from the prey's side:# the prey runs away from the other creature, which runs after itimport os as _osif dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv).get("flee", "1") != "0":for i, t in enumerate(toks):if t in ("running", "runs", "racing", "dashing", "sprinting", "chasing") and i + 1 < len(toks) and toks[i + 1] == "after":# "a cheetah running after a gazelle" = the cheetah chases: the gazelle flees from itprv = [k for k in anim if pos[k] is not None and pos[k] < i]nxt = [k for k in anim if pos[k] is not None and pos[k] > i]if prv and nxt:a, b = max(prv, key=lambda k: pos[k]), min(nxt, key=lambda k: pos[k])if a != b and (ents[b].get("attrs") or {}).get("flee_from") is None:ents[a]["pose"] = "running"ents[a].setdefault("attrs", {}).setdefault("action", "chase")ents[b]["pose"] = "running"ents[b].setdefault("attrs", {})["flee_from"] = atrace.append("actions: %s runs after %s (chase)" % (ents[a]["concept"], ents[b]["concept"]))continueif t not in ("running", "runs", "fleeing", "flees", "escaping", "escapes", "racing", "dashing") or i + 1 >= len(toks) \or toks[i + 1] not in ("from", "away"):continueprv = [k for k in anim if pos[k] is not None and pos[k] < i]nxt = [k for k in anim if pos[k] is not None and pos[k] > i]if not prv or not nxt:continuea, b = max(prv, key=lambda k: pos[k]), min(nxt, key=lambda k: pos[k])if a == b or (ents[a].get("attrs") or {}).get("flee_from") is not None:continueents[a]["pose"] = "running"ents[a].setdefault("attrs", {})["flee_from"] = bif ents[b].get("pose") in (None, "standing"):ents[b]["pose"] = "running"ents[b].setdefault("attrs", {}).setdefault("action", "chase")trace.append("actions: %s runs from %s (chase)" % (ents[a]["concept"], ents[b]["concept"]))# rule: "walking a dog" = the dog walks toofor i, t in enumerate(toks):if t in ("walking", "walks") and i + 2 < len(toks) and toks[i + 1] in DET:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097"""Attachments (night round 1, scene lane): things that live ON other things, not beside them.
flags "a castle with a waving flag", "a lighthouse with a flag on top", "a sailboat with a red flag", "a sandcastle with a flag": the flag flies from the host's top (a tower, the keep, the roof peak) or is hoisted up a mast; "a flag on a pole" = the flag's own pole IS the pole (one tall flagpole). signs "a bakery with a sign that says BREAD": the sign board is mounted on the building's front, no posts. hanging "a lantern hanging from a branch / tree": a branch becomes a limb reaching in from the frame edge, the lantern hangs below it on a cord; on a tree it hangs under the canopy.
Two hooks: relations(scene, trace) runs before the layout builds instances (a "with" / "hanging from" phrase becomesan "on" binding, so the layout does not reserve a side-by-side slot), and layout_rule(...) runs at the end of thelayout and places the attached thing on its anchor. 3D reads inst.attach in pydraw3d/attach.py (anchors are found onthe host's SDF). Knob: PYDRAW_EXP attach=0 restores the old side-by-side placement.rule: everything keys on sentence shape + concept facts (size, animal, building family), never on prompt lists."""import osimport re
from .registry import CONCEPTS
_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)
_FULL = "fullof" not in os.environ.get("PYDRAW_LANG_OFF", "").split(",") # language shift 3: "a jar full of marbles"
def enabled(): return _EXP.get("attach", "1") != "0"
FLAG_WORDS = {"flag", "banner", "pennant", "flags", "banners", "pennants", "standard", "ensign", "jolly roger"}POLE_CONCEPTS = {"post", "pole", "flagpole", "mast"}POLE_WORDS = {"pole", "flagpole", "flag pole", "mast", "staff", "post"}HANG_VERBS = r"(hanging|hangs|hung|hang|dangling|dangles|suspended|swinging)"PERCH_HOSTS = {"branch", "bough", "limb", "twig", "tree branch"}TREE_HOSTS = {"tree", "oak", "pine", "willow", "birch", "maple", "palm tree", "cherry tree"}SIDE_WORDS = r"\b(next to|beside|near|alongside|by|behind|in front of|left of|right of)\b"
# flag anchors per host: (x as a fraction of the width from the centre (x facing), height fraction, mode, flag size# as a fraction of the host height). mode "top" = the pole stands on the anchor; "hoist" = the pole runs down the# mast and its top is at the anchorFLAG_ANCHOR = { "castle": (0.0, .71, "top", .42), "tower": (0.0, .93, "top", .3), "lighthouse": (0.0, .9, "top", .24), "house": (0.0, .97, "top", .4), "church": (-.15, .6, "top", .3), "windmill": (0.0, .86, "top", .3), "boat": (-.02, 1.0, "hoist", .36), "pirate ship": (0.0, 1.0, "hoist", .22), "tent": (0.0, .95, "top", .38), "igloo": (0.0, .95, "top", .45), "barn": (0.0, .98, "top", .4), "red barn": (0.0, .98, "top", .4), "skyscraper": (0.0, .98, "top", .12), "treehouse": (0.0, .98, "top", .3),}NOSAIL = ("rowboat", "row boat", "canoe", "kayak", "dinghy", "raft", "motorboat", "speedboat", "fishing boat", "rowing boat", "paddle boat")SEAT_VEHICLES = {"car": (-.1, .42, .8), "truck": (.28, .55, .5), "pickup truck": (.25, .5, .55), "bus": (.3, .47, .45), "tractor": (-.08, .55, .8), "go kart": (0.0, .5, .7), "train": (.35, .55, .35), "boat": (-.05, .25, .4), "rowboat": (0.0, .5, .6), "canoe": (0.0, .5, .6)} # (seat x toward the front, door line, rider h) as fractionsBACK_WEAR = {"backpack", "rucksack", "knapsack", "quiver", "cape", "guitar", "bag", "sack", "basket"}TOPPERS = {"weather vane", "weathervane", "antenna", "satellite dish", "star", "angel", "rooster", "cross", "spire", "lightning rod", "chimney", "bell", "crown", "cherry", "candle", "topper"}NESTS = {"bird nest", "nest", "birds nest", "bird's nest"}PEGS = {"coat rack", "hook", "peg", "nail", "hat stand", "coat hook", "hanger", "clothesline", "washing line"}OVER_HOSTS = {"dining table", "table", "desk", "bed", "counter", "kitchen table", "pool table", "bar", "crib", "piano", "stove"}SHELTERS = {"mushroom", "toadstool", "leaf", "umbrella", "lily pad", "giant leaf"}BALLS = {"ball", "beach ball", "soccer ball", "football", "basketball", "circus ball", "yarn ball"}CONTAINERS_GLASS = {"bottle", "jar", "snow globe", "snowglobe", "terrarium", "light bulb", "lightbulb", "glass jar", "fishbowl", "fish bowl", "glass", "vase", "globe", "lantern", "teacup", "cup", "mug"}MOUNTABLE = {"clock", "window", "door", "sign", "poster", "painting", "plaque", "mirror", "shield", "wreath", "birdhouse", "lamp", "lantern", "horseshoe", "mailbox", "picture", "frame", "banner"}WALLS = {"wall", "fence", "brick wall", "stone wall"}CLIMBERS = {"owl", "bird", "squirrel", "cat", "kitten", "monkey", "koala", "sloth", "parrot", "raccoon", "chameleon", "lemur", "chimpanzee", "orangutan", "leopard", "snake", "eagle", "crow", "robin", "toucan", "woodpecker", "bat"}# mounted things: (centre height as a fraction of the host, width as a fraction of the host width)FRONT_ANCHOR = {"door": (.68, .5), "tower": (.68, .62), "lighthouse": (.45, .5), "house": (.42, .25), "tree": (.2, .14), "pine": (.15, .14), "wall": (.55, .3), "fence": (.55, .3), "church": (.62, .14), "castle": (.45, .18), "barn": (.6, .2), "red barn": (.6, .2)}# where a sign board sits on a building front: board centre height fraction, board width fractionSIGN_ANCHOR = {"house": (.38, .42), "red barn": (.5, .4), "barn": (.5, .4), "church": (.35, .4)}
def is_flag(concept): c = CONCEPTS.get(concept, {}) return concept in ("flag", "banner", "pennant") or (c.get("sim") or {}).get("kind") == "flag" \ or (c.get("open_vocab") or {}).get("family") == "flag"
def is_building(concept): c = CONCEPTS.get(concept, {}) if c.get("animal") or concept == "person": return False fam = (c.get("open_vocab") or {}).get("family") if fam in ("building", "house", "tower", "castle", "temple", "barn", "shop"): return True return c.get("row") in ("back", "mid") and c.get("height", 0) >= 4 and c.get("aspect", 0) >= .6 \ and c.get("setting") in ("field", "street", "beach", "snow", "farm") and not c.get("flying")
def _word(e): return (e.get("word") or e["concept"]).lower()
def _pos(text, e): """index of the entity's word in the text (first occurrence of its last word), or -1 (the variation pass may have swapped the word for a variant, "tree" -> "birch": then the concept name is looked up)""" for w in (_word(e).split()[-1], e["concept"].split()[-1]): m = re.search(r"\b%ss?\b" % re.escape(w.rstrip("s")), text) if m: return m.start() return -1
def relations(scene, trace): """pre-layout: rewrite the bindings of attached things (see module doc)""" if not enabled(): return if any(e["concept"] == "roof" for e in scene["entities"]) and not any(is_building(e["concept"]) and e["concept"] != "roof" for e in scene["entities"]): # rule: "a cat stuck on a roof" - a roof is the top of a house, not a slab lying on the grass for e in scene["entities"]: if e["concept"] == "roof" and "house" in CONCEPTS: e["concept"], e["word"] = "house", "house" trace.append("attach: a roof alone -> the house it tops") _peek_window(scene, trace) try: _shop_front(scene, trace) except Exception as ex: # a staging rule must never take the render down trace.append("attach: shop front skipped (%s)" % str(ex)[:80]) ents, rels = scene["entities"], scene["relations"] text = (scene.get("text") or "").lower() side = re.search(SIDE_WORDS, text) new = [] drop = [] changed = False if any(e["concept"] == "treehouse" for e in ents): # rule: "a treehouse ... in a big oak tree": the treehouse is drawn with its own tree, a second one is a twin for i, e in enumerate(ents): if e["concept"] in TREE_HOSTS and e.get("count", 1) == 1 and any(i in (s_, o_) for s_, r_, o_ in rels): drop.append(i) trace.append("attach: the treehouse brings its own %s" % _word(e)) changed = True for s, rel, o in rels: if s >= len(ents) or o >= len(ents): new.append((s, rel, o)) continue if s in drop or o in drop: continue # "a turtle carrying a tiny house on its back", "an elephant with a monkey on its back" _mb = re.search(r"\bon (?:its|his|her|their|the) backs?\b", text) if rel in ("holding", "next_to") and _mb and 0 <= _pos(text, ents[o]) < _mb.start() and \ CONCEPTS.get(ents[s]["concept"], {}).get("animal") and ents[s]["concept"] != "person" and o > s: # (only when the thing is named BEFORE "on its back": "an otter floating on its back holding a starfish" is # the otter lying on its back) ents[o]["attach"] = "back" if not CONCEPTS.get(ents[o]["concept"], {}).get("animal") else None if ents[o]["attach"] is None: ents[o].pop("attach") else: # its world size = its share of the carrier (so the pair fits the frame as drawn) ents[o]["size"] = .62 * CONCEPTS[ents[s]["concept"]]["height"] * ents[s].get("size", 1.0) / max(.05, CONCEPTS[ents[o]["concept"]]["height"]) new.append((o, "on", s)) scene["unknown"] = [u for u in scene.get("unknown", []) if u != "back"] trace.append("attach: the %s rides on the %s's back" % (_word(ents[o]), _word(ents[s]))) changed = True continue es, eo = ents[s], ents[o] cs, co = es["concept"], eo["concept"] # flags: "<host> with a flag" (next_to from "with") or "a flag on <host>" if rel == "next_to" and is_flag(co) and not is_flag(cs) and not side and _host_ok(cs): eo["attach"] = "flag" _flag_size(eo, es) new.append((o, "on", s)) trace.append("attach: '%s with a %s' -> the %s flies from the %s" % (_word(es), _word(eo), _word(eo), _word(es))) changed = True continue if rel == "on" and is_flag(cs) and _host_ok(co): es["attach"] = "flag" if co in POLE_CONCEPTS or _word(eo) in POLE_WORDS: # rule: "a flag on a pole" = the flag's own pole IS the pole (one tall flagpole, not a flag on a stump) drop.append(o) es["attach"] = "flagpole" es["size"] = max(es.get("size", 1.0), 1.0) trace.append("attach: a %s on a %s -> one flagpole" % (_word(es), _word(eo))) changed = True continue else: _flag_size(es, eo) trace.append("attach: the %s flies from the %s" % (_word(es), _word(eo))) new.append((s, rel, o)) changed = True continue # signs on buildings: "<building> with a sign" if rel == "next_to" and co == "sign" and is_building(cs) and not side: eo["attach"] = "sign" new.append((o, "on", s)) trace.append("attach: the sign is mounted on the %s's front" % _word(es)) changed = True continue if rel == "on" and cs == "sign" and is_building(co): es["attach"] = "sign" new.append((s, rel, o)) trace.append("attach: the sign is mounted on the %s's front" % _word(eo)) changed = True continue # "a mailbox stuffed with letters", "a backpack overflowing with books": they poke out of its top / slot if rel == "on" and (re.search(r"\b(stuffed|crammed|overflowing|bursting|packed|jammed)\s+with\b", text) or ( _FULL and re.search(r"\b(full|brimming)\s+of\b|\bfilled\s+with\b", text))) and \ not CONCEPTS.get(cs, {}).get("animal") and CONCEPTS.get(cs, {}).get("height", 9) < CONCEPTS.get(co, {}).get("height", 0) * 1.2: es["attach"] = "stuffed" new.append((s, rel, o)) trace.append("attach: %s poke out of the %s" % (_word(es), _word(eo))) changed = True continue # "a lighthouse in a bottle", "a ship in a bottle", "a tiny house in a snow globe": a miniature inside if rel == "in_a" and (co in CONTAINERS_GLASS or _word(eo) in CONTAINERS_GLASS) and \ CONCEPTS.get(cs, {}).get("height", 0) > CONCEPTS.get(co, {}).get("height", 9) * .8: es["attach"] = "inside" es["size"] = .5 * CONCEPTS[co]["height"] * eo.get("size", 1.0) / max(.05, CONCEPTS[cs]["height"]) new.append((s, "on", o)) if CONCEPTS.get(co, {}).get("setting") == "table" and scene.get("place") in (None, "beach", "water", "field", "street", "snow"): scene["place"] = "table" # rule: the miniature's world is the shelf / table the container stands on trace.append("attach: a miniature %s inside the %s" % (_word(es), _word(eo))) changed = True continue # in a vehicle: "a dog driving a red convertible", "a bear driving a bus", "a cat in a car": seated in it if (rel in ("in_a", "riding") or rel == "on" and re.search(r"\b(driv\w*|steer\w*|behind the wheel)\b", text)) and co in SEAT_VEHICLES and (CONCEPTS.get(cs, {}).get("animal") or cs == "person") \ and es.get("count", 1) <= 2 and CONCEPTS.get(cs, {}).get("height", 9) < CONCEPTS[co]["height"]: es["attach"] = "seat" new.append((s, "on", o)) trace.append("attach: the %s sits in the %s" % (_word(es), _word(eo))) changed = True continue # "a bunny under a mushroom", "a frog sheltering under a leaf": the little shelter becomes a roof over the creature if rel in ("under", "below") and (co in SHELTERS or _word(eo).split()[-1] in SHELTERS) and \ not (CONCEPTS.get(cs, {}).get("animal") or cs == "person"): # "a bunny reading a book under a mushroom": the clause landed on the held book - shelter its holder instead hold = [h for h, r_, x in rels if r_ == "holding" and x == s and (CONCEPTS.get(ents[h]["concept"], {}).get("animal") or ents[h]["concept"] == "person")] if hold: s, es = hold[0], ents[hold[0]] cs = es["concept"] if rel in ("under", "below") and (co in SHELTERS or _word(eo).split()[-1] in SHELTERS) and \ (CONCEPTS.get(cs, {}).get("animal") or cs == "person"): eo["attach"] = "shelter" new.append((o, "on", s)) # (bound to the creature so the layout keeps them together) trace.append("attach: the %s is a roof over the %s" % (_word(eo), _word(es))) changed = True continue # "an elephant balancing on a ball": standing ON a big circus ball (not holding a small one) if rel in ("holding", "on", "toward", "next_to") and (co in BALLS or _word(eo).split()[-1] in BALLS) and \ CONCEPTS.get(cs, {}).get("animal") and re.search(r"\b(?:balanc\w*|stand\w*|roll\w*|on top)\s+(?:on|upon|atop)\s+(?:a|an|the)?\s*(?:\w+\s+)?ball", text): eo["attach"] = "ballsupport" eo["size"] = .55 * CONCEPTS[cs]["height"] * es.get("size", 1.0) / max(.05, CONCEPTS[co]["height"]) new.append((s, "on", o)) if es.get("attrs", {}).get("action") in ("carry", "balance", "hold"): es["attrs"].pop("action", None) trace.append("attach: the %s balances on a big %s" % (_word(es), _word(eo))) changed = True continue # "a birdhouse on a pole with a bird": the "with" phrase belongs to the subject on top, so the bird perches on it if rel == "next_to" and CONCEPTS.get(co, {}).get("animal") and CONCEPTS.get(co, {}).get("flying") \ and CONCEPTS.get(co, {}).get("height", 9) < 1 and any(r_ == "on" and o_ == s and s_ != o for s_, r_, o_ in rels) and not side: top_ = next(s_ for s_, r_, o_ in rels if r_ == "on" and o_ == s and s_ != o) if not CONCEPTS.get(ents[top_]["concept"], {}).get("animal"): new.append((o, "on", top_)) trace.append("attach: the %s perches on the %s" % (_word(eo), _word(ents[top_]))) changed = True continue # "a girl blowing out candles on a birthday cake": a person / animal is not ON a much smaller tabletop thing hc, oc_ = CONCEPTS.get(cs, {}), CONCEPTS.get(co, {}) if rel == "on" and (hc.get("animal") or cs == "person") and oc_.get("setting") == "table" and \ oc_.get("height", 9) < hc.get("height", 0) * .5 and not (es.get("attrs") or {}).get("fixed_scale") \ and not re.search(r"\b(tiny|miniature|little|small|mini)\s+\w*\s*" + re.escape(_word(es).split()[-1]), text): new.append((s, "next_to", o)) trace.append("attach: the %s is beside the %s, not standing on it" % (_word(es), _word(eo))) changed = True continue # "a bear cub climbing a pine tree", "a koala clinging to a tree": on the trunk, part way up if (co in TREE_HOSTS or _word(eo) in TREE_HOSTS) and (hc.get("animal") or cs == "person") and \ re.search(r"\b(climb\w*|cling\w*|clamber\w*|scal(?:ing|es)|shimm(?:y|ying|ies))\b", text): es["attach"] = "climb" new.append((s, "on", o)) trace.append("attach: the %s climbs the %s trunk" % (_word(es), _word(eo))) changed = True continue # "a koala hugging a eucalyptus branch": an animal holding on to a branch is on that limb if rel in ("toward", "next_to", "holding") and hc.get("animal") and (co in PERCH_HOSTS or _word(eo).split()[-1] in PERCH_HOSTS) \ and re.search(r"\b(hug\w*|cling\w*|hold\w*|grip\w*|clutch\w*|sitting|perch\w*|rest\w*|sleep\w*|nap\w*)\b", text): new.append((s, "on", o)) trace.append("attach: the %s is on the %s" % (_word(es), _word(eo))) changed = True continue # "a backpack on a boy's back": a wearable on a person's back is worn, not balanced on the head if rel == "on" and cs in BACK_WEAR and co == "person" and re.search(r"\bback\b", text): new.append((o, "wearing", s)) scene["unknown"] = [u for u in scene.get("unknown", []) if u != "back"] trace.append("attach: the %s is worn on the %s's back" % (_word(es), _word(eo))) changed = True continue # toppers: "a weather vane on top of a barn", "a star on top of a christmas tree", "an antenna on a roof" if rel == "on" and (cs in TOPPERS or _word(es) in TOPPERS) and not CONCEPTS.get(co, {}).get("animal") and co != "person": es["attach"] = "topper" new.append((s, rel, o)) trace.append("attach: the %s crowns the %s" % (_word(es), _word(eo))) changed = True continue # things stuck in a tree / a nest in a tree: up in the crown like animals in a tree if rel in ("in_a", "on") and (co in TREE_HOSTS or _word(eo) in TREE_HOSTS) and not CONCEPTS.get(cs, {}).get("animal") \ and (cs in NESTS or re.search(r"\b(stuck|caught|tangled|trapped|lodged)\b", text)) and CONCEPTS.get(cs, {}).get("height", 9) <= 2: es["attach"] = "intree" new.append((s, "on", o)) scene["unknown"] = [u for u in scene.get("unknown", []) if u not in ("stuck", "caught", "tangled", "trapped", "lodged")] trace.append("attach: the %s is up in the %s" % (_word(es), _word(eo))) changed = True continue # ladders: "a treehouse with a rope ladder", "a ladder against a house" -> up the host's front to its floor if rel == "next_to" and (co == "ladder" and _ladder_host(cs) or cs == "ladder" and _ladder_host(co)): li, hi_ = (o, s) if co == "ladder" else (s, o) ents[li]["attach"] = "ladder" new.append((li, "on", hi_)) trace.append("attach: the ladder goes up the %s" % _word(ents[hi_])) changed = True continue # other mounted things: "a clock on a tower", "a window in the tree's trunk", "a door on the wall" if rel == "next_to" and co in MOUNTABLE and cs == "door" and co not in ("door", "window") and not side: # "a red door with a wreath": the wreath hangs on the door eo["attach"] = "front" new.append((o, "on", s)) trace.append("attach: the %s hangs on the door" % _word(eo)) changed = True continue if rel == "on" and cs in MOUNTABLE and es.get("count", 1) <= 2 and (is_building(co) or co in TREE_HOSTS or co in WALLS or co in FRONT_ANCHOR) \ and not (cs == "window" and co in ("house",) and not es.get("peek")): es["attach"] = "front" new.append((s, rel, o)) trace.append("attach: the %s is mounted on the %s" % (_word(es), _word(eo))) changed = True continue # animals in a tree: "owls in a tree", "a cat up in a tree", "a bird on the tree" if rel in ("in_a", "on") and (co in TREE_HOSTS or _word(eo) in TREE_HOSTS) and _climber(cs) and not side: es["attach"] = "intree" new.append((s, "on", o)) trace.append("attach: the %s sits on a branch in the %s" % (_word(es), _word(eo))) changed = True continue new.append((s, rel, o)) related = {(a_, b_) for a_, r_, b_ in new} | {(b_, a_) for a_, r_, b_ in new} for i, e in enumerate(ents): for j, h in enumerate(ents): if i == j or (i, j) in related: continue ch = CONCEPTS.get(h["concept"], {}) # "a jaguar resting on a jungle branch" (the parser kept no relation): on the limb if (h["concept"] in PERCH_HOSTS or _word(h).split()[-1] in PERCH_HOSTS) and CONCEPTS.get(e["concept"], {}).get("animal") \ and re.search(r"\bon\s+(?:a|an|the|its|some)?\s*(?:\w+\s+)?(?:branch|bough|limb)\b", text): new.append((i, "on", j)) related |= {(i, j), (j, i)} trace.append("attach: the %s is on the %s" % (_word(e), _word(h))) changed = True # "a firefighter rescuing a kitten from a tree": the kitten is up in the tree elif (h["concept"] in TREE_HOSTS or _word(h) in TREE_HOSTS) and _climber(e["concept"]) and \ re.search(r"\b(?:from|out of|down from)\s+(?:a|an|the)?\s*(?:\w+\s+)?tree\b", text) and _pos(text, e) < _pos(text, h): new.append((i, "on", j)) e["attach"] = "intree" related |= {(i, j), (j, i)} trace.append("attach: the %s is up in the %s (rescued from it)" % (_word(e), _word(h))) changed = True # rule: "an otter floating on its back", "a duck floating": an animal floating is on the water if re.search(r"\bfloat\w*\b", text) and any(CONCEPTS.get(e["concept"], {}).get("animal") and CONCEPTS[e["concept"]].get("setting") in ("water", "beach", "underwater") for e in ents) \ and scene.get("place") in (None, "sky", "field", "beach"): scene["place"] = "water" for e in ents: c_ = CONCEPTS.get(e["concept"], {}) if c_.get("animal") and not c_.get("flying") and (e.get("pose") in ("floating", "flying") or (e.get("pose") is None and c_.get("setting") in ("water", "beach", "underwater"))): e["pose"] = "swimming" trace.append("attach: a sea animal floating -> on the water") from .layout import ROOMS as _ROOMS if scene.get("place") in _ROOMS and any(e["concept"] in TREE_HOSTS for e in ents) and not re.search( r"\b(room|kitchen|bedroom|bathroom|office|classroom|library|garage|cafe|restaurant|indoors?|inside|house|home|hall)\b", text): # rule: a tree in the picture with no room word is outdoors (the kitten made it a living room with a tree on the rug) scene["place"] = "field" scene["room"] = None trace.append("attach: a tree and no room named -> outdoors") # rule: "a nest ... with eggs": the eggs lie in the nest (whatever the "with" bound to) nests = [i for i, e in enumerate(ents) if e["concept"] in NESTS] if nests: for i, e in enumerate(ents): if e["concept"] in ("egg", "eggs") and i != nests[0]: new = [r for r in new if not (i in (r[0], r[2]) and r[1] in ("next_to", "on", "in_a"))] new.append((i, "on", nests[0])) e["attach"] = "stuffed" trace.append("attach: the eggs lie in the nest") changed = True # hanging: "X hanging from Y" (the parser leaves no relation for it) m = re.search(r"\b%s\s+(?:from|on|in|off|under|below|beneath|over|above)\s+(?:the|a|an|its|his|her|their|some)?\s*" % HANG_VERBS, text) if m: hi = [i for i, e in enumerate(ents) if _pos(text, e) >= 0 and _pos(text, e) < m.start()] ho = [i for i, e in enumerate(ents) if _pos(text, e) >= m.end() - 1] if hi and not ho and re.search(r"\b(branch|bough|limb)\b", text[m.end() - 1:]): # rule: "a monkey hanging from a tree branch" - the parser dropped the branch; the limb comes back from .open_vocab import resolve r_ = resolve("branch", CONCEPTS, []) cb = r_[0] if r_ and r_[0] in CONCEPTS else ("stick" if "stick" in CONCEPTS else None) if cb: ents.append({"concept": cb, "word": "branch", "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, "facing": None}) ho = [len(ents) - 1] if hi and ho: s, o = hi[-1], min(ho, key=lambda i: _pos(text, ents[i])) cs, co = ents[s]["concept"], ents[o]["concept"] small = CONCEPTS.get(cs, {}).get("height", 9) <= 2.0 and cs != "person" and \ (not CONCEPTS.get(cs, {}).get("animal") or co in PERCH_HOSTS or _word(ents[o]) in PERCH_HOSTS) if small and (co in PEGS or _word(ents[o]) in PEGS or (co in OVER_HOSTS and m.group(0).split()[1] in ("over", "above"))): # "a hat hanging on a coat rack", "a lamp hanging over a kitchen table" new = [r for r in new if not ({r[0], r[2]} == {s, o})] new.append((s, "on", o)) ents[s]["attach"] = "peg" if (co in PEGS or _word(ents[o]) in PEGS) else "over" if ents[s]["attach"] == "over" and scene.get("place") in (None, "field", "park", "street") and not re.search( r"\b(outside|outdoors?|garden|park|field|meadow|yard|patio|terrace|beach|forest|street|picnic)\b", text): # rule: a lamp / chandelier hanging over a table is indoors (the ceiling it hangs from) scene["place"] = "kitchen" if "kitchen" in text else "room" trace.append("attach: hanging over a table -> indoors") trace.append("attach: the %s hangs %s the %s" % (_word(ents[s]), "on" if ents[s]["attach"] == "peg" else "over", _word(ents[o]))) scene["unknown"] = [u for u in scene.get("unknown", []) if u != m.group(1)] changed = True elif small and (co in PERCH_HOSTS or _word(ents[o]) in PERCH_HOSTS or co in TREE_HOSTS or _word(ents[o]) in TREE_HOSTS): new = [r for r in new if not ({r[0], r[2]} == {s, o})] new.append((s, "on", o)) ents[s]["attach"] = "hang" ents[o]["attach_role"] = "limb" if (co in PERCH_HOSTS or _word(ents[o]) in PERCH_HOSTS) else "tree" trace.append("attach: the %s hangs from the %s" % (_word(ents[s]), _word(ents[o]))) if "hanging" in scene.get("unknown", []) or m.group(1) in scene.get("unknown", []): scene["unknown"] = [u for u in scene["unknown"] if u != m.group(1)] changed = True # tied: "a bunch of balloons tied to a mailbox" -> they float right above it on their strings m = re.search(r"\b(?:tied|tethered|attached|fastened|anchored)\s+to\s+(?:the|a|an|its|his|her)?\s*", text) if m: hi = [i for i, e in enumerate(ents) if 0 <= _pos(text, e) < m.start()] ho = [i for i, e in enumerate(ents) if _pos(text, e) >= m.end() - 1] if hi and ho: s_, o_ = hi[-1], min(ho, key=lambda i: _pos(text, ents[i])) if ents[s_]["concept"] in ("balloon", "kite") and not CONCEPTS.get(ents[o_]["concept"], {}).get("flying"): new = [r for r in new if {r[0], r[2]} != {s_, o_}] new.append((s_, "on", o_)) ents[s_]["attach"] = "tied" scene["unknown"] = [u for u in scene.get("unknown", []) if u not in ("tied", "tethered", "attached", "fastened", "anchored")] trace.append("attach: the %s float tied to the %s" % (_word(ents[s_]), _word(ents[o_]))) changed = True if changed: scene["relations"] = new # rule: a host with only its attachments (a castle with a flag, a bakery with a sign) is framed like a lone # subject: the attachment is part of it rest = [e for e in ents[1:] if e.get("worn_on") is None] if ents and ents[0].get("count", 1) == 1 and rest and all(e.get("attach") in ("flag", "sign") and e.get("count", 1) == 1 for e in rest) \ and all(o == 0 for s_, r_, o in new if r_ == "on"): scene["attach_solo"] = True if drop: from .physics import _drop for i in sorted(set(drop), reverse=True): for t in scene.get("texts") or []: if isinstance(t.get("entity"), int) and t["entity"] > i: t["entity"] -= 1 _drop(scene, i)
def _climber(concept): c = CONCEPTS.get(concept, {}) return bool(c.get("animal")) and c.get("height", 9) <= 1.6 and (c.get("flying") or concept in CLIMBERS)
def _ladder_host(concept): return concept in ("treehouse", "house", "barn", "red barn", "tree", "wall", "bunk bed") or is_building(concept)
def _flag_size(ef, eh): """the flag's world size = its share of the host (so the host + flag fit the frame as they will be drawn)""" hc, fc = CONCEPTS.get(eh["concept"], {}), CONCEPTS.get(ef["concept"], {}) frac = FLAG_ANCHOR.get(eh["concept"], (0, 1, "top", .3))[3] ef["size"] = max(.05, frac * hc.get("height", 2.0) * eh.get("size", 1.0) / max(.1, fc.get("height", 2.4)))
def _host_ok(concept): c = CONCEPTS.get(concept, {}) return not c.get("animal") and concept != "person" and not c.get("flying") and not is_flag(concept)
def _pole_dx(it): """x offset from the instance centre to its pole (drawn flags: pole on the side away from the cloth)""" if getattr(it, "pole_free", False): return 0.0 if (CONCEPTS.get(it.concept, {}).get("sim") or {}).get("kind") == "flag": return -it.w * .46 # simulated cloth: the pole is the model's left edge f = -1 if it.facing == "left" else 1 return -f * it.w * .42
def layout_rule(insts, scene, W, H, y0, trace): """post-layout: put attached things on their anchors""" if not enabled(): return ents = scene["entities"] for it in insts: it.view = (W, H, y0) # (3D rebuilds perch limbs from the 2D box: pydraw3d/attach.limb3d) place = scene.get("place") from .layout import ROOMS for it in insts: if it.concept == "door" and place in ROOMS and getattr(it, "bound", None) is None and hasattr(it, "x") \ and _EXP.get("walldoor", "1") != "0" and y0 > H * .2: # rule: a door in a room is IN the back wall (its sill on the floor line), not a slab standing on the rug asp = it.w / max(1e-6, it.h) it.h = y0 * .82 it.w = it.h * asp it.y = y0 + max(2.0, (H - y0) * .07) # (just in front of the wall line: 3D back-projects depth from it) it.d = max(getattr(o, "d", 0) for o in insts if hasattr(o, "d")) * 1.5 + 1 it.shadow_skip = True it.haze = 0.0 others = [o for o in insts if o is not it and hasattr(o, "x") and getattr(o, "bound", None) is None] if others: # the door is on the side away from the subject, or behind it for "at / by the door" sx = others[0].x it.x = sx + (W * .17 if sx < W / 2 else -W * .17) trace.append("attach: the door is set in the back wall") for it in insts: e = ents[it.ent] if isinstance(it.ent, int) and it.ent < len(ents) else {} kind = e.get("attach") b = getattr(it, "bound", None) if not kind or b is None or not hasattr(b, "x") or not hasattr(it, "x"): continue it.view = (W, H, y0) if kind == "flag": _flag(it, b, ents, W, H, trace) elif kind == "sign": _sign(it, b, W, H, trace) e["mounted"] = True # (read by the 3D sign model: no posts) elif kind == "hang": _hang(it, b, ents, W, H, y0, trace) elif kind == "tied": _tied(it, b, insts, W, H, trace) elif kind == "back": _back(it, b, W, H, trace) elif kind == "stuffed": _stuffed(it, b, insts, W, H, trace) elif kind == "inside": _inside(it, b, W, H, trace) elif kind == "seat": _seat(it, b, insts, W, H, trace) elif kind == "topper": _topper(it, b, W, H, trace) elif kind == "peg": _peg(it, b, W, H, trace) elif kind == "over": _over(it, b, W, H, y0, trace) elif kind == "climb": _climb(it, b, W, H, y0, trace) elif kind == "shelter": _shelter(it, b, W, H, trace) elif kind == "ladder": _ladder(it, b, W, H, trace) elif kind == "front": _front(it, b, W, H, trace) e["mounted"] = True elif kind == "intree": _intree(it, b, insts, W, H, y0, trace) if getattr(b, "d", None) is not None and getattr(it, "d", None) is not None and it.d <= b.d: # (3D places instances in depth order: an attached thing must come after its host, or it is placed with no # host to hang on and lands far away - the teddy in a jar did) it.d = b.d * 1.0001 + 1e-6
def _flag(it, b, ents, W, H, trace): be = ents[b.ent] if isinstance(b.ent, int) and b.ent < len(ents) else {} asp = it.w / max(1e-6, it.h) ax, ay, mode, frac = FLAG_ANCHOR.get(b.concept, (0.0, 1.0, "top", .3)) word = (getattr(b, "word", "") or "") if b.concept == "boat" and (word in NOSAIL or word.rstrip("s") in NOSAIL): ax, ay, mode, frac = (-.38, .26, "top", .45) # rule: a boat without a mast flies its flag from the stern if (b.info.get("open_vocab") or {}).get("family") == "building" and b.concept not in FLAG_ANCHOR: ay = .98 bf = -1 if b.facing == "left" else 1 axp = b.x + bf * ax * b.w ayp = b.y - ay * b.h it.h = max(b.h * frac, H * .1) if it.h > b.h * .9: it.h = b.h * .9 it.w = it.h * asp # rule: the cloth streams toward the open side of the frame (a boat's flag streams aft) if b.concept in ("boat", "pirate ship"): it.facing = "left" if bf > 0 else "right" else: it.facing = "right" if axp < W * .55 else "left" if (CONCEPTS.get(it.concept, {}).get("sim") or {}).get("kind") == "flag": it.facing = "right" # (the simulated cloth's pole is always its left edge) it.x = axp - _pole_dx(it) it.y = ayp if mode == "top" else ayp + it.h * .97 top = it.y - it.h if top < H * .02: # rule: keep the flag inside the frame (shrink it toward its anchor) k = (it.y - H * .02) / it.h if k > .3: it.h *= k it.w *= k it.x = axp - _pole_dx(it) it.d = b.d it.attach = (mode, (ax * bf, ay)) trace.append("attach: %s on the %s's %s at (%.0f, %.0f), h=%.0f" % (it.concept.split(":")[0], b.concept, "mast" if mode == "hoist" else "top", axp, ayp, it.h))
def _sign(it, b, W, H, trace): cy, wf = SIGN_ANCHOR.get(b.concept, (.62, .44)) asp = it.w / max(1e-6, it.h) board_asp = asp / .58 # the board is the top 58% of the sign's box (pydraw/typography/draw2d.py _sign) bw = b.w * wf bh = bw / board_asp if bh > b.h * .3: bh = b.h * .3 bw = bh * board_asp it.h = bh / .58 it.w = it.h * asp it.x = b.x it.y = (b.y - cy * b.h) + bh / 2 + .42 * it.h it.d = b.d it.mounted = True it.shadow_skip = True it.attach = ("front", (0.0, cy)) trace.append("attach: sign board on the %s front at y=%.0f, w=%.0f" % (b.concept, b.y - cy * b.h, bw))
def _hang(it, b, ents, W, H, y0, trace): be = ents[b.ent] if isinstance(b.ent, int) and b.ent < len(ents) else {} asp = it.w / max(1e-6, it.h) if be.get("attach_role") == "limb": # rule: a branch something hangs from is a limb reaching in from the frame edge, high in the picture side = -1 if it.rng.random() < .5 else 1 it.h = max(it.h, H * .24) it.w = it.h * asp it.x = W * (.5 - side * .06) b.perch = True b.perch_r = max(2.0, H * .03) b.perch_y = H * .2 b.perch_x0 = -4 if side < 0 else W + 4 b.perch_x1 = it.x - side * W * .22 b.shadow_skip = True b.x, b.y = (b.perch_x0 + b.perch_x1) / 2, b.perch_y + b.perch_r b.w, b.h = abs(b.perch_x1 - b.perch_x0), b.perch_r * 3 # the limb droops toward its tip: the cord starts on the limb's lower edge above the lantern t = (it.x - b.perch_x0) / (b.perch_x1 - b.perch_x0) cy = b.perch_y + b.perch_r * .8 * t * t + b.perch_r * .6 it.y = cy + H * .1 + it.h it.cord = (it.x, cy, it.x, it.y - it.h * .97) if it.info.get("animal"): # rule: an animal hangs by its own arms / tail right under the limb (no cord) it.y = cy + it.h * .95 it.cord = None it.attach = ("hang", (0.0, 0.0)) it.shadow_skip = True trace.append("attach: %s hangs on a cord from a limb reaching in from the %s edge" % (it.concept, "left" if side < 0 else "right")) return # a tree: under the canopy, off the trunk if b.h < H * .62: # rule: the tree something hangs from is the frame of the picture (a lantern in a tiny far tree is a speck): # it grows in place and comes forward to the front of the ground k = H * .66 / b.h b.h *= k b.w *= k b.y = max(b.y, min(H * .93, y0 + (H - y0) * .8)) b.x = W * .5 + (W * .08 if b.x >= W / 2 else -W * .08) b.haze = 0.0 side = 1 if b.x < W / 2 else -1 it.h = max(b.h * .14, H * .1) it.w = it.h * asp it.x = b.x + side * b.w * .3 cy = b.y - b.h * .5 it.y = cy + b.h * .1 + it.h it.cord = (it.x, cy, it.x, it.y - it.h * .97) it.d = b.d it.attach = ("hang", (side * .3, .5)) it.shadow_skip = True trace.append("attach: %s hangs on a cord under the %s's canopy" % (it.concept, b.concept))
def draw_cord(cv, ctx, it): """pixel: the cord / chain a hanging thing hangs from (drawn just before the thing itself)""" x0, y0_, x1, y1 = it.cord cv.capsule(x0, y0_, x1, y1, max(.5, it.h * .015), (60, 50, 45))
def _front(it, b, W, H, trace): """a mounted thing sits on the host's front face (a clock on a tower's face, a window in a trunk)""" cy, wf = FRONT_ANCHOR.get(b.concept, (.55, .3))
if it.concept == "window" and getattr(it, "peek", False): cy, wf = .6, .26 # an upper-floor window someone tall looks into if b.concept not in FRONT_ANCHOR and (CONCEPTS.get(b.concept, {}).get("open_vocab") or {}).get("family") in ("tree",): cy, wf = FRONT_ANCHOR["tree"] asp = it.w / max(1e-6, it.h) w = b.w * wf h = w / max(.2, asp) cap = .75 if b.concept in WALLS else .3 if h > b.h * cap: h = b.h * cap w = h * asp it.h, it.w = h, w it.x = b.x it.y = b.y - cy * b.h + h / 2 if it.concept == "door" and b.concept not in TREE_HOSTS: # rule: a door stands on the host's ground line, beside the middle (a sign above it stays readable) it.h = b.h * .36 it.w = it.h * min(.6, asp) it.y = b.y it.x = b.x + b.w * .22 cy = .18 it.d = b.d it.pose = None it.wall = it.wall_hung = False it.mounted = True it.shadow_skip = True it.attach = ("front", (0.0, cy, "obj")) trace.append("attach: %s mounted on the %s at y=%.0f, w=%.0f" % (it.concept, b.concept, it.y - h / 2, w))
def _intree(it, b, insts, W, H, y0, trace): """an animal in a tree sits on a branch inside the crown, in front of the leaves; several spread over branches""" sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "intree"] j = sib.index(it) if it in sib else 0 n = len(sib) if b.h < H * .6 and not getattr(b, "_grown", False): # rule: the tree is the stage: it comes forward and grows so its residents read b._grown = True b.y = max(b.y, min(H * .93, y0 + (H - y0) * .8)) k = min(H * .74 / b.h, (b.y - H * .03) / b.h) if k > 1: b.h *= k b.w *= k b.haze = 0.0 asp = it.w / max(1e-6, it.h) if n == 1 and (getattr(it, "attrs", None) or {}).get("hollow") and b.concept == "tree": # rule (language shift 3, knob hollow): "an owl in a tree hole" = it looks out of a dark hollow in the trunk, # under the crown (the hole swells the trunk a little), not on a branch beside it ry = b.h * .085 cx, cy = b.x, b.y - b.h * .27 it.h = ry * 1.55 it.w = it.h * asp if it.w > ry * 1.5: it.w = ry * 1.5 it.h = it.w / asp it.x, it.y, it.d = cx, cy + ry * .72, b.d it.pose = "sitting" if not it.info.get("flying") else "perched" it.facing = "right" if it.x < W / 2 else "left" it.hollow = (cx, cy, max(it.w * .62, ry * .8), ry) it.shadow_skip = True it.attach = ("intree", (0.0, .27)) trace.append("attach: %s looks out of a hollow in the %s's trunk" % (it.concept, b.concept)) return it.h = b.h * (.25 if n == 1 else .2 if n == 2 else .15) * (getattr(it, "world_h", 1) / max(1e-6, max(o.world_h for o in sib)) if n > 1 else 1) ** .5 it.w = it.h * asp slots = [(-.26, .5), (.26, .58), (-.05, .7), (.32, .44), (-.32, .66)] sx, sy = slots[j % len(slots)] it.x = b.x + sx * b.w it.y = b.y - sy * b.h it.d = b.d it.pose = "perched" if it.info.get("flying") else (it.pose or "sitting") it.facing = "right" if sx < 0 else "left" if n > 1 and j == 0: it.facing = "right" if sib[1].x > it.x else "left" # rule: the first one (the teacher, the parent) faces the others # the branch under its feet: from the trunk out past the feet r = max(1.5, b.h * .018) it.limb = (b.x, it.y + r * 2.2, it.x + (it.w * .45 if sx > 0 else -it.w * .45), it.y + r * .2, r) it.shadow_skip = True it.attach = ("intree", (sx, sy)) trace.append("attach: %s on a branch in the %s at (%.0f, %.0f)" % (it.concept, b.concept, it.x, it.y))
def draw_limb(cv, ctx, it): """pixel: the branch an animal in a tree sits on (drawn just before the animal)""" from .shading import lit_capsule x0, y0_, x1, y1, r = it.limb lit_capsule(cv, ctx.L, x0, y0_, x1, y1, r, (96, 70, 48))
def draw_hollow(cv, ctx, it): """pixel: the hollow an animal sits in (drawn just before it): a bark swelling, a dark oval, a pale lower lip""" cx, cy, rx, ry = it.hollow # (the bark colour is the tree's own choice - birch white, oak brown - so the rim is a neutral dark knot ring) cv.ellipse(cx, cy, rx * 1.22, ry * 1.18, (72, 52, 36)) cv.ellipse(cx, cy, rx, ry, (28, 20, 16)) cv.ellipse(cx, cy + ry * .78, rx * .82, ry * .2, (150, 112, 74))
LADDER_TOP = {"treehouse": .46, "tree": .5, "house": .5, "barn": .55, "red barn": .55, "wall": .95}
def _ladder(it, b, W, H, trace): """a ladder stands on the ground in front of its host and reaches the host's floor / eave""" top = LADDER_TOP.get(b.concept, .55) asp = it.w / max(1e-6, it.h) it.h = b.h * top it.w = min(it.h * asp, b.w * .25) side = 1 if b.x <= W / 2 else -1 it.x = b.x + side * b.w * (.12 if b.concept == "treehouse" else .22) it.y = b.y + 1 it.d = b.d it.shadow_skip = True it.attach = ("ladder", (0.0, top)) trace.append("attach: ladder up the %s to %.0f%% of its height" % (b.concept, top * 100))
def _tied(it, b, insts, W, H, trace): """balloons tied to a thing float above it in a bunch; their own strings end at the knot on the thing's top""" sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "tied"] j, n = (sib.index(it) if it in sib else 0), max(1, len(sib)) asp = it.w / max(1e-6, it.h) it.h = max(H * .16, min(b.h * .9, H * .3)) it.w = it.h * asp ky = b.y - b.h * .95 # the knot spread = it.w * .75 it.x = b.x + (j - (n - 1) / 2) * spread it.y = ky - abs(j - (n - 1) / 2) * it.h * .12 + it.h * .04 it.pose = "flying" it.d = b.d it.attach = ("tied", (0.0, .95)) if j == 0: trace.append("attach: %d %s float over the %s on strings" % (n, it.concept, b.concept))
SHOP_RX = r"\b(shop|store|shopfront|storefront|boutique)s?\b"FRONT_THINGS = {"sign", "door", "window", "awning", "bench", "lamp", "lantern", "clock", "flower", "potted plant", "cat", "dog", "bicycle"}
def _insert0(scene, e): """insert entity e at index 0, shifting every index that points into the entity list""" scene["entities"].insert(0, e) scene["relations"] = [(a + 1, r, b + 1) for a, r, b in scene["relations"]] for act in scene.get("actions") or []: for k in ("subject", "object"): if isinstance(act.get(k), int): act[k] += 1 for t in scene.get("texts") or []: if isinstance(t.get("entity"), int): t["entity"] += 1 for k_ in ("entity",): pass for e2 in scene["entities"][1:]: if isinstance(e2.get("worn_on"), int): e2["worn_on"] += 1 tx = (e2.get("attrs") or {}).get("text") if isinstance(tx, dict) and isinstance(tx.get("entity"), int) and tx is not None and tx not in (scene.get("texts") or []): tx["entity"] += 1
def _shop_front(scene, trace): """rule: "a shop with a sign", "a flower shop", "a shop sign over a dusty door" are shop FRONTS (outside, on a street): the word shop set an indoor supermarket with shelves; only an inside word (inside, aisle, shelves) keeps it""" text = (scene.get("text") or "").lower() if scene.get("place") != "supermarket" or not re.search(SHOP_RX, text) or \ re.search(r"\b(inside|interior|aisle|aisles|shelf|shelves|counter|supermarket|grocery|checkout|cashier|in a shop|in the shop|in a store|in the store)\b", text): return ents = scene["entities"] if any(e["concept"] not in FRONT_THINGS and not CONCEPTS.get(e["concept"], {}).get("animal") and e["concept"] != "person" and e.get("worn_on") is None for e in ents): return from .open_vocab import resolve m = re.search(SHOP_RX, text) host = None for w in (m.group(1), "shop", "store"): r = resolve(w, CONCEPTS, []) if r and r[0] in CONCEPTS and (CONCEPTS[r[0]].get("open_vocab") or {}).get("family") == "building": host = r[0] break if host is None: return goods = [g[0] for g in re.findall(r"\b([a-z]+)\s+" + SHOP_RX[2:], text)] _insert0(scene, {"concept": host, "word": m.group(1), "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, "facing": None, "implicit": False}) for i, e in enumerate(scene["entities"][1:], 1): if e["concept"] in ("sign", "door", "window", "awning", "clock", "lamp", "lantern") and \ not any(a == i and r == "on" for a, r, b in scene["relations"]): scene["relations"] = [(a, r, b) for a, r, b in scene["relations"] if i not in (a, b)] + [(i, "on", 0)] for g in goods: g1 = g.rstrip("s") if g1 in CONCEPTS and not CONCEPTS[g1].get("open_vocab") and CONCEPTS[g1].get("height", 9) < 2.5 and g1 not in ("coffee",): scene["entities"].append({"concept": g1, "word": g, "count": 3, "color": None, "shade": 1.0, "size": 1.0, "pose": None, "facing": None}) scene["relations"].append((len(scene["entities"]) - 1, "in_front_of", 0)) trace.append("attach: a %s shop shows its %ss out front" % (g, g1)) break scene["place"] = "street" scene["room"] = None trace.append("attach: '%s' -> a shop front on a street (not an indoor supermarket)" % m.group(0))
def _back(it, b, W, H, trace): """a thing carried on an animal's back sits on the top of its body, about as big as the carrier allows""" asp = it.w / max(1e-6, it.h) it.h = b.h * .56 it.w = it.h * asp if it.w > b.w * .7: it.w = b.w * .7 it.h = it.w / asp f = -1 if b.facing == "left" else 1 it.x = b.x - f * b.w * .06 it.y = b.y - b.h * min(.78, max(.5, b.info.get("on_top", .8))) + it.h * .08 # (sinks into the shell / fur a little) it.d = b.d it.shadow_skip = True it.attach = ("top", (-f * .06, .9)) trace.append("attach: %s on the %s's back" % (it.concept, b.concept))
def _stuffed(it, b, insts, W, H, trace): """things stuffed into a container poke out of its top (or a mailbox's slot), fanned, overlapping its rim""" sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "stuffed"] j, n = (sib.index(it) if it in sib else 0), max(1, len(sib)) asp = it.w / max(1e-6, it.h) it.h = max(H * .05, b.h * .22) it.w = it.h * asp if it.w > b.w * .45: it.w = b.w * .45 it.h = it.w / asp top = b.y - b.h * (.72 if b.concept == "mailbox" else b.info.get("on_top", .9)) it.x = b.x + (j - (n - 1) / 2) * min(it.w * .45, b.w * .6 / n) it.y = top + it.h * (.55 + .12 * ((j * 3) % 3) / 2) it.d = b.d it.shadow_skip = True it.attach = ("stuffed", (0.0, .8)) if j == 0: trace.append("attach: %d %s poke out of the %s" % (n, it.concept, b.concept))
def snap_top(cv, host, r): """pixel: move a carried / stuffed thing onto the host's drawn top surface under it (a drawing rarely fills its box)""" hid = getattr(host, "_oid", None) if hid is None: return xs = [int(r.x + dx * r.w * .25) for dx in (0, -1, 1)] # (the centre column first) tops = [] for x in xs: if not 0 <= x < cv.w: continue for y in range(max(0, int(host.y - host.h)), min(cv.h, int(host.y) + 1)): if cv.ids[y][x] == hid: tops.append(y) break if not tops: return t = sorted(tops)[len(tops) // 2] if len(tops) == 3 else tops[0] if len(tops) == 3 and tops[0] < t: # a thin host (a post, a mast): the centre column is the top it rests on t = tops[0] sink = {"back": .08, "stuffed": .45, "topper": .06}.get(getattr(r, "attach_kind", None), .04) if getattr(host, "attach_kind", None) == "ballsupport": sink = .14 # (a quadruped's drawn feet sit a little above its box bottom) r.y = t + r.h * sink
def _inside(it, b, W, H, trace): """a miniature stands on the container's floor, inside its outline (drawn after it, so it reads through the glass)""" if b.h < H * .42: # rule: the container holding the miniature is the picture: it grows in place (base kept) k = min(H * .5 / b.h, (b.y - H * .04) / b.h) if k > 1: b.h *= k b.w *= k asp = it.w / max(1e-6, it.h) it.h = b.h * .5 it.w = it.h * asp if it.w > b.w * .7: it.w = b.w * .7 it.h = it.w / asp it.x = b.x it.y = b.y - b.h * .07 it.d = b.d it.shadow_skip = True it.attach = ("inside", (0.0, .07)) trace.append("attach: %s inside the %s (h=%.0f)" % (it.concept, b.concept, it.h))
def _seat(it, b, insts, W, H, trace): """a rider in a vehicle: seated behind the door / under the window line, drawn clipped at that line""" sx, door, rh = SEAT_VEHICLES.get(b.concept, (.1, .5, .5)) if b.h < H * .3 and b.concept in ("boat", "rowboat", "canoe") and not getattr(b, "_grown", False): # rule: a boat with named passengers is framed large enough to show them (not a speck on the horizon) b._grown = True k = H * .36 / b.h b.h *= k b.w *= k b.y = max(b.y, H * .8) b.x = W * .5 b.haze = 0.0 sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "seat"] j = sib.index(it) if it in sib else 0 f = -1 if b.facing == "left" else 1 asp = it.w / max(1e-6, it.h) it.h = b.h * rh it.w = it.h * asp dl = b.y - b.h * door it.x = b.x + f * b.w * (sx - .22 * j) it.y = dl + it.h * .3 it.facing = b.facing it.d = b.d it.clip_below = dl it.shadow_skip = True it.attach = ("seat", (f * sx, door)) trace.append("attach: %s seated in the %s (clipped at the door line y=%.0f)" % (it.concept, b.concept, dl))
def _topper(it, b, W, H, trace): """a topper crowns its host: its base on the host's top (a vane on the roof ridge, a star on the tree's tip)""" asp = it.w / max(1e-6, it.h) frac = .18 if b.concept not in TREE_HOSTS else .12 if b.info.get("height", 9) < 1.0: frac = .45 # rule: on a small host (a crown on a cake) the topper is a good share of it, not a crumb it.h = min(max(H * .05, b.h * frac, it.h if b.info.get("height", 9) < 2 else 0), b.h * .6) # (a bell on a post keeps its own size) it.w = it.h * asp it.x = b.x it.y = b.y - b.h * (.97 if b.concept not in ("barn", "red barn", "house") else .99) + it.h * .1 it.d = b.d it.shadow_skip = True it.attach = ("top", (0.0, .98)) it.pole_free = True trace.append("attach: %s on top of the %s" % (it.concept, b.concept))
def _peg(it, b, W, H, trace): """hung on a peg / rack / hook: at the host's top, hanging down over its side""" asp = it.w / max(1e-6, it.h) it.h = min(it.h, b.h * .3) it.w = it.h * asp it.x = b.x + b.w * .2 it.y = b.y - b.h * .82 + it.h it.d = b.d it.shadow_skip = True it.attach = ("peg", (.2, .82)) trace.append("attach: %s hangs on the %s" % (it.concept, b.concept))
def _over(it, b, W, H, y0, trace): """a lamp hanging over a table: high over its middle on a cord from the top of the picture""" asp = it.w / max(1e-6, it.h) it.h = max(H * .1, min(it.h, b.h * .5)) it.w = it.h * asp it.x = b.x top = b.y - b.h it.y = max(it.h + H * .1, top - H * .14) it.d = b.d it.pose = "flying" it.cord = (it.x, 0, it.x, it.y - it.h * .95) it.view = (W, H, y0) it.shadow_skip = True it.attach = ("over", (0.0, 1.0)) trace.append("attach: %s hangs on a cord over the %s" % (it.concept, b.concept))
def _climb(it, b, W, H, y0, trace): """a climber clings to the trunk part way up, turned to the tree, the tree big enough to climb""" if b.h < H * .6 and not getattr(b, "_grown", False): b._grown = True b.y = max(b.y, min(H * .93, y0 + (H - y0) * .8)) k = min(H * .74 / b.h, (b.y - H * .03) / b.h) if k > 1: b.h *= k b.w *= k b.haze = 0.0 asp = it.w / max(1e-6, it.h) it.h = b.h * .2 it.w = it.h * asp side = -1 if b.x >= W / 2 else 1 it.x = b.x + side * (b.w * .06 + it.w * .3) it.y = b.y - b.h * .28 it.facing = "left" if side > 0 else "right" it.d = b.d it.shadow_skip = True it.attach = ("climb", (side * .1, .28)) trace.append("attach: %s climbs the %s trunk at y=%.0f" % (it.concept, b.concept, it.y))
def _peek_window(scene, trace): """rule: "a giraffe peeking into a second floor window": a tall creature looking IN at a window is outside a house (the parser made it a room); the window goes high on the house front, the creature stands beside it""" text = (scene.get("text") or "").lower() ents = scene["entities"] if not re.search(r"\b(peek\w*|peer\w*|look\w*|peep\w*|star\w*|gaz\w*)\s+(?:in|into|through|in at)\s+(?:a|an|the)?\s*(?:\w+\s+){0,3}windows?\b", text): return win = [i for i, e in enumerate(ents) if e["concept"] == "window"] tall = [i for i, e in enumerate(ents) if CONCEPTS.get(e["concept"], {}).get("animal") and CONCEPTS[e["concept"]].get("height", 0) >= 2.5] if not win or not tall or "house" not in CONCEPTS or any(is_building(e["concept"]) for e in ents): return ents.append({"concept": "house", "word": "house", "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, "facing": None}) h = len(ents) - 1 scene["relations"] = [r for r in scene["relations"] if win[0] not in (r[0], r[2])] + [(win[0], "on", h), (tall[0], "next_to", h)] ents[win[0]].pop("wall", None) ents[win[0]]["peek"] = True scene["place"] = "field" scene["room"] = None trace.append("attach: the %s looks in at a window of a house, from outside" % ents[tall[0]]["concept"])
def _shelter(it, b, W, H, trace): """a little shelter (mushroom, leaf) grows into a roof over the creature: its cap just above the creature's head, standing right behind it""" asp = it.w / max(1e-6, it.h) it.h = b.h * 1.55 it.w = max(it.h * asp, b.w * 1.3) it.x = b.x it.y = b.y - max(1.0, H * .006) it.d = b.d * 1.0001 + 1e-6 it.rel = "behind_host" it.shelter_of = b it.attach = ("shelter", (0.0, 0.0)) trace.append("attach: %s roof over the %s (h=%.0f)" % (it.concept, b.concept, it.h))23 unmodified lines242526272829108 unmodified lines13813914014114214369 unmodified lines21321421521621721821922022113 unmodified lines23523623723823924024152 unmodified lines2942952962972982993005 unmodified lines30630730830931031112 unmodified lines32432532632732832931 unmodified lines36136236336436536620 unmodified lines387388389390391392393215 unmodified lines6096106116126136146156166176186196206215 unmodified lines6276286296306316326 unmodified lines6396406416426436446453 unmodified lines64965065165265365465565665765865966066133 unmodified lines69569669769869970070170270370470570623 unmodified lines7307317327337347351 unmodified line7377387397407417428 unmodified lines75175275375475575675775875924 unmodified lines78478578678778878979079179279379479579679779879980080180280351 unmodified lines85585685785885986086186286386431 unmodified lines89689789889990090114 unmodified lines9169179189199209219229239249259269279289298 unmodified lines9389399409419429436 unmodified lines95095195295395495595695795895996096196296385 unmodified lines10491050105110521053105410551056105723 unmodified linesGOLD2 = (225, 180, 60)def _dk(c, k=.62):return (c[0] * k, c[1] * k, c[2] * k * 1.05 + 3)108 unmodified linesclosed_happy(ex_, ey_)else:open_eye(ex_, ey_)elif ex == "sleepy":for ex_, ey_ in eyes: # rule: sleepy = heavy half-closed lids (lid colour over the top half + lash line)open_eye(ex_, ey_)69 unmodified linescv.capsule(a[0], a[1], b[0], b[1], lw, INK)elif ex == "sleepy":cv.ellipse(mx, my + mw * .35, max(.7, mw * .3), max(.7, mw * .34), MOUTH)else:if kind == "frog":_arc(cv, mx, my - mw * .6, mw, mw * .7, math.pi * .2, math.pi * .8, lw, INK, 6)else: # the friendly "w" mouth of a cartoon animalfor s in (-1, 1):_arc(cv, mx + s * mw * .38, my, mw * .4, mw * .4, math.pi * .1, math.pi * .9, lw, INK, 4)13 unmodified lines# ---------------------------------------------------------------- headsdef _ear_angle(expr, base):return base + {"angry": 38, "scared": 48, "sad": 62, "crying": 55, "surprised": -8, "sleepy": 22}.get(expr, 0)def ears(cv, L, R, lk, expr, back=True):52 unmodified linesfur = lk["fur"]kind = lk["kind"]R.top = hy - ryif lk.get("mane"):for k in range(12): # rule: a lion's mane = a ring of lobes behind the heada = k * math.pi / 6lit_ellipse(cv, L, hx + math.cos(a) * rx * 1.08, hy + math.sin(a) * ry * 1.0, rx * .42, ry * .42, lk["mane"])5 unmodified linespx, py = -math.sin(a), math.cos(a)cv.poly([(hx + math.cos(a) * rx * .7 + px * rx * .3, hy + math.sin(a) * ry * .7 + py * ry * .3), (tx, ty),(hx + math.cos(a) * rx * .7 - px * rx * .3, hy + math.sin(a) * ry * .7 - py * ry * .3)], lk["spikes"])if kind == "mammal" or kind == "primate":ears(cv, L, R, lk, expr, back=True)if kind == "bird" and lk.get("comb"):12 unmodified linesfor k in range(8):a = math.pi * (1.1 + k * .11)lit_ellipse(cv, L, hx + math.cos(a) * rx * .7, hy + math.sin(a) * ry * .75, rx * .32, ry * .3, _lt(fur, .2))# markingsif lk.get("stripes") and kind == "mammal":sc = lk["stripes"]31 unmodified linesmz = lk.get("muzzle") or (_lt(fur, .5) if sn >= .05 else None)mw, mh = rx * (.48 + min(sn, .15) * 1.2), ry * (.34 + min(sn, .15) * 1.0)my_ = hy + ry * .42if lk.get("pig"):cv.ellipse(fx, my_ - ry * .02, rx * .36, ry * .26, _dk(lk["nose_col"], .92))cv.ellipse(fx, my_ - ry * .05, rx * .32, ry * .22, lk["nose_col"])20 unmodified linesfor k in (-1, 0, 1):cv.capsule(fx + s * mw * .65, my_ + k * mh * .18, fx + s * (mw * .65 + rx * .5), my_ + k * mh * .32 - mh * .1,.5, _dk(mz or fur, .5), alpha=.8)if lk.get("horns"):for s in (-1, 1):cv.poly([(hx + s * rx * .35, hy - ry * .8), (hx + s * rx * .65, hy - ry * .75), (hx + s * rx * .75, hy - ry * 1.35)],L.shade((235, 222, 190), s * .4, -.5, .8))215 unmodified lineslit_ellipse(cv, L, R.hx + s * R.rx * 1.0, R.hy + R.ry * .05, R.rx * .22, R.ry * .32, c)def back_items(cv, L, R, wear, U):"""things worn behind the body: cape, backpack (drawn before the body)"""f = R.fR.layer(SUB["back"])for wi in wear:if wi["item"] == "cape":c = tuple(wi["color"]) if wi.get("color") else (200, 35, 40)sx, sy = R.shoulderssw = R.sh_wbot = R.ground - U * .045 unmodified linesxa = sx - sw + 2 * sw * txb = sx - sw * 1.5 - f * U * .18 + (2.9 * sw) * tcv.capsule(xa, sy + U * .05, xb, bot - U * .01, max(.5, U * .006), _dk(c, .62))elif wi["item"] == "backpack":c = tuple(wi["color"]) if wi.get("color") else (200, 80, 50)bx_ = R.cx - f * R.sh_w * 1.056 unmodified linesdef front_items(cv, L, R, wear, U):"""backpack straps, neckwear, glasses, headphones, hats, in drawing order"""order = {"backpack": 0, "cape": 0.5, "scarf": 1, "tie": 1, "bowtie": 2, "glasses": 3, "headphones": 4, "hat": 5}for wi in sorted(wear, key=lambda w: order.get(w["item"], 9)):it = wi["item"]R.layer(SUB.get({"backpack": "back", "scarf": "neck", "tie": "neck", "bowtie": "neck", "cape": "neck"}.get(it, it), .45))3 unmodified linesfor s in (-1, 1):x = sx + s * R.sh_w * .55cv.capsule(x, sy, x - s * R.sh_w * .1, sy + R.chest_h * .7, max(.6, U * .012), _dk(c, .8))elif it in ("bowtie", "tie", "scarf"):neckwear(cv, L, R, it, wi.get("color"))elif it == "cape":# rule (combos): a cape reads from the front by its collar over the shoulders and the clasp at the throatc = tuple(wi["color"]) if wi.get("color") else (200, 35, 40)nx, ny, nw = R.neckfor s_ in (-1, 1):cv.poly([(nx + s_ * nw * .15, ny - nw * .05), (nx + s_ * nw * 1.15, ny - nw * .1), (nx + s_ * nw * 1.05, ny + nw * .35),(nx + s_ * nw * .2, ny + nw * .25)], L.shade(c, s_ * .4, -.2, .9))cv.ellipse(nx, ny + nw * .1, max(.8, nw * .16), max(.8, nw * .16), (235, 195, 70))33 unmodified linesR = Rig()R.cv, R.base = cv, cv.cur_idR.f = -1 if inst.facing == "left" else 1if mode == "biped":_biped(cv, L, inst, R, lk, expr, chibi, wear)else:_sit(cv, L, inst, R, lk, expr, chibi, wear)inst.head = (R.hx, R.hy, R.rx, R.ry, R.f)cv.cur_id = R.basedef _fit(inst, top_frac, half_w_frac):23 unmodified lineshy += U * .03 # rule: a sad / sleepy head hangs a littleR.hx, R.hy, R.ry = x + f * U * .02, hy, U * hrR.rx = R.ry * (1.08 if kind not in ("frog",) else 1.45)belly = lk.get("belly") or lk.get("bib") or (_lt(fur, .45) if kind == "mammal" else None)bcx, bcy = x, g - U * body_h * .5bw, bh = U * (.27 if kind != "frog" else .36), U * body_h * .551 unmodified lineR.sh_w = bw * .8R.chest_h = U * body_h * .5R.neck = (R.hx, R.hy + R.ry * .95, R.rx * .95)back_items(cv, L, R, wear, U)if kind in ("mammal", "primate", "reptile"):tail(cv, L, R, lk, expr, x - f * bw * .55, g - U * .06, U)8 unmodified lineslit_ellipse(cv, L, bcx, g - U * .42, U * .3, U * .42, fur) # egg bodyif lk.get("belly"):lit_ellipse(cv, L, bcx + f * U * .02, g - U * .3, U * .19, U * .26, lk["belly"])for s in (-1, 1):fc = (240, 160, 50)cv.ellipse(bcx + s * U * .1, g - U * .015, U * .07, U * .03, fc)R.hy = g - U * (.74 + (.03 if chibi else 0))R.ry = U * hr * .95R.rx = R.ry * 1.0524 unmodified linespattern=(lambda px, py, b: lk["spots"] if lk.get("spots") and (int(px / max(1, U * .06)) + int(py / max(1, U * .07))) % 3 == 0 else b))for s in (-1, 1): # hauncheslit_ellipse(cv, L, bcx + s * bw * .75, g - U * .1, U * .14, U * .11, fur)cv.ellipse(bcx + s * bw * 1.0, g - U * .02, U * .09, U * .035, _dk(fur, .85) if not lk.get("hooves") else lk["hooves"])lit_ellipse(cv, L, bcx, bcy, bw, bh, fur, pattern=_stripes(lk, bcx, bcy, bw) if lk.get("stripes") else None)if belly:lit_ellipse(cv, L, bcx + f * bw * .05, bcy + bh * .1, bw * .55, bh * .75, belly)if lk.get("spots"):for k, (dx, dy) in enumerate(((-.5, -.3), (.45, -.1), (-.2, .35), (.55, .4), (-.6, .25))):cv.ellipse(bcx + dx * bw, bcy + dy * bh, bw * .16, bh * .12, lk["spots"])for s in (-1, 1): # front legslx = bcx + s * bw * .38lc = fur if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"] # panda: black legslit_capsule(cv, L, lx, bcy - bh * .2, lx, g - U * .05, U * .055, lc)pc = lk["hooves"] if lk.get("hooves") else _lt(lc, .15)lit_ellipse(cv, L, lx + s * U * .005, g - U * .03, U * .07, U * .04, pc)_clothes_sit(cv, L, R, wear, U, bcx, bcy, bw, bh, kind)R.layer(0)head(cv, L, R, lk, expr, chibi)front_items(cv, L, R, wear, U)51 unmodified linesR.ry = U * hrR.rx = R.ry * (1.08 if kind != "frog" else 1.4)R.neck = (R.hx, sh_y + U * .01, sw * 1.05)gw = _garments(wear)act = at.get("action")holding = getattr(inst, "holding", None)pc = _lt(fur, .1) # paw colourleg_c = furif "overalls" in gw or "robe" in gw:leg_c = tuple(gw.get("overalls", gw.get("robe"))["color"] or (60, 95, 160))31 unmodified lineshands[f] = (x + f * (sw + U * .12), sh_y - U * .1)if act == "cheer":hands[-f] = (x - f * (sw + U * .12), sh_y - U * .1)sleeve = Nonefor k_ in ("jacket", "shirt", "robe", "dress"):if k_ in gw and not (k_ == "shirt" and (gw[k_].get("style") == "sweater" and False)):14 unmodified lineslit_capsule(cv, L, sx_, sy_, ex_, ey_, arm_r, c)lit_capsule(cv, L, ex_, ey_, hx_, hy_, arm_r * .92, c)R.layer(0)if kind != "bird":lit_ellipse(cv, L, hx_, hy_, arm_r * 1.25, arm_r * 1.2, pc if not front else _lt(fur, .12) if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"])arm(-f, False)# ---- legs and feetlr = U * .062 * (1.15 if chibi else 1)for s in (-1, 1):lx = x + s * tw * .45c = leg_c if s == f else _dk(leg_c, .85)if kind == "frog":lit_capsule(cv, L, lx, hip_y, lx + s * U * .03, g - U * .03, lr, c)cv.ellipse(lx + s * U * .06, g - U * .015, U * .09, U * .03, _dk(fur, .85))8 unmodified linesR.layer(0)fc = lk["hooves"] if lk.get("hooves") else _lt(fur, .1) if not (lk.get("eye_patch") and not lk.get("mask")) else lk["eye_patch"]lit_ellipse(cv, L, lx + f * U * .025, g - U * .03, U * .075, U * .04, fc)# ---- torsotcx, tcy = x, (sh_y + hip_y) / 2 + U * .01tc = fur6 unmodified lineslit_ellipse(cv, L, tcx + f * tw * .05, tcy + U * .02, tw * .62, U * torso * .45, belly)# garments over the torso_clothes_biped(cv, L, R, gw, U, tcx, tcy, tw, torso, hip_y, g, f)R.layer(0)# head and the near armhead(cv, L, R, lk, expr, chibi)front_items(cv, L, R, [w for w in wear if w["item"] not in ("hat",)], U)arm(f, True)if two:arm(-f, True)front_items(cv, L, R, [w for w in wear if w["item"] == "hat"], U)hx_, hy_ = hands[f]if two:hx_, hy_ = (hands[-1][0] + hands[1][0]) / 2, (hands[-1][1] + hands[1][1]) / 285 unmodified linesex_ = fx + e * rx * .34cv.ellipse(ex_, ey - ry * .06, rx * .2, ry * .12, scale(skin, .92))cv.capsule(ex_ - rx * .16, ey + ry * .02, ex_ + rx * .16, ey + ry * .02, max(.5, ry * .05), INK)elif expr == "winking":ex_ = fx + f * rx * .34cv.ellipse(ex_, ey, rx * .17, ry * .13, skin)_arc(cv, ex_, ey + ry * .1, rx * .14, ry * .12, math.pi * 1.15, math.pi * 1.85, max(.5, ry * .05), INK, 5)mx, my = fx + f * rx * .08, hy + ry * .64cv.ellipse(mx, my + ry * .02, rx * .22, ry * .1, MOUTH)23 unmodified lines24252627282930313233343536108 unmodified lines14514614714814915015115215315469 unmodified lines22422522622722822923023123223323423523623723813 unmodified lines25225325425525625725852 unmodified lines3113123133143153163173185 unmodified lines32432532632732832933033133233312 unmodified lines34634734834935035135235335435535635735835936036131 unmodified lines39339439539639739839940020 unmodified lines421422423424425426427428429430431432433434435436437438439440441442443444445446447215 unmodified lines6636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577585 unmodified lines7647657667677687697707716 unmodified lines7787797807817827837843 unmodified lines78878979079179279379479579679779879980080180280380480580680780880981081181233 unmodified lines84684784884985085185285385485585685785885986086186286386486586686786886987087187287387487523 unmodified lines8999009019029039049059069079089099101 unmodified line9129139149159169179189199209219228 unmodified lines93193293393493593693793893994094194294394494524 unmodified lines97097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100851 unmodified lines10601061106210631064106510661067106810691070107131 unmodified lines11031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117414 unmodified lines1189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712188 unmodified lines122712281229123012311232123312341235123612376 unmodified lines124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127785 unmodified lines1363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146023 unmodified linesGOLD2 = (225, 180, 60)def _on(name):"""night-wave knobs (PYDRAW_EXP name=0 turns a rule off), read at call time"""import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get(name, "1") != "0"def _dk(c, k=.62):return (c[0] * k, c[1] * k, c[2] * k * 1.05 + 3)108 unmodified linesclosed_happy(ex_, ey_)else:open_eye(ex_, ey_)elif ex == "asleep":for ex_, ey_ in eyes: # rule (night): asleep = eyes shut, a soft downward arc_arc(cv, ex_, ey_ - er * .35, er * 1.0, er * .75, math.pi * .12, math.pi * .88, max(w, er * .26), ink2)zzz2d(cv, hx + f * rx * 1.05, hy - ry * 1.05, ry * .22, _lum(fur) < 70)elif ex == "sleepy":for ex_, ey_ in eyes: # rule: sleepy = heavy half-closed lids (lid colour over the top half + lash line)open_eye(ex_, ey_)69 unmodified linescv.capsule(a[0], a[1], b[0], b[1], lw, INK)elif ex == "sleepy":cv.ellipse(mx, my + mw * .35, max(.7, mw * .3), max(.7, mw * .34), MOUTH)elif ex == "asleep":cv.ellipse(mx, my + mw * .3, max(.6, mw * .2), max(.6, mw * .14), MOUTH)else:if kind == "frog":_arc(cv, mx, my - mw * .6, mw, mw * .7, math.pi * .2, math.pi * .8, lw, INK, 6)elif mw < 3.6 and _on("smallmouth"):# rule (night): at small sizes the "w" closes into a dark blob that reads as bared teeth - draw one small# upturned smile instead_arc(cv, mx, my - mw * .15, mw * .55, mw * .42, math.pi * .15, math.pi * .85, max(.5, lw * .8), _dk(INK, 1.0), 5)else: # the friendly "w" mouth of a cartoon animalfor s in (-1, 1):_arc(cv, mx + s * mw * .38, my, mw * .4, mw * .4, math.pi * .1, math.pi * .9, lw, INK, 4)13 unmodified lines# ---------------------------------------------------------------- headsdef _ear_angle(expr, base):return base + {"angry": 38, "scared": 48, "sad": 62, "crying": 55, "surprised": -8, "sleepy": 22, "asleep": 30}.get(expr, 0)def ears(cv, L, R, lk, expr, back=True):52 unmodified linesfur = lk["fur"]kind = lk["kind"]R.top = hy - rycrest = bool(lk.get("mane") and lk.get("hooves") and _on("hoofmane"))if lk.get("mane") and not crest:for k in range(12): # rule: a lion's mane = a ring of lobes behind the heada = k * math.pi / 6lit_ellipse(cv, L, hx + math.cos(a) * rx * 1.08, hy + math.sin(a) * ry * 1.0, rx * .42, ry * .42, lk["mane"])5 unmodified linespx, py = -math.sin(a), math.cos(a)cv.poly([(hx + math.cos(a) * rx * .7 + px * rx * .3, hy + math.sin(a) * ry * .7 + py * ry * .3), (tx, ty),(hx + math.cos(a) * rx * .7 - px * rx * .3, hy + math.sin(a) * ry * .7 - py * ry * .3)], lk["spikes"])longface = bool(lk.get("hooves") and kind == "mammal" and _on("longface"))if longface and (lk.get("neck", 0) > .5 or lk.get("horn_kind") in ("antlers", "palmate", "ossicones")):# giraffe / deer ears stick out sideways under the ossicones / antlers (upright ears made a cat with antlers)lk = dict(lk, ears="side", ear_size=max(lk.get("ear_size", 1.0), 1.1))if kind == "mammal" or kind == "primate":ears(cv, L, R, lk, expr, back=True)if kind == "bird" and lk.get("comb"):12 unmodified linesfor k in range(8):a = math.pi * (1.1 + k * .11)lit_ellipse(cv, L, hx + math.cos(a) * rx * .7, hy + math.sin(a) * ry * .75, rx * .32, ry * .3, _lt(fur, .2))if longface and lk.get("spots") and lk.get("neck", 0) > .5:for dx, dy in ((-.45, -.25), (.42, -.3), (-.3, .1), (.35, .12)): # a few patches on the giraffe's facecv.ellipse(hx + dx * rx, hy + dy * ry, rx * .14, ry * .1, lk["spots"])if crest:# rule (night): a hoofed animal's mane (horse, giraffe, zebra) is a forelock on the brow and a crest on top,# not a lion's ring (a giraffe character read as a poodle / lion)mc = lk["mane"]for k, dx in enumerate((-.22, .0, .22)):lit_ellipse(cv, L, hx + dx * rx + R.f * rx * .05, hy - ry * (.86 + (.08 if k == 1 else 0)), rx * .2, ry * .26, mc)cv.poly([(hx - rx * .18, hy - ry * .78), (hx + rx * .18, hy - ry * .78), (hx + R.f * rx * .06, hy - ry * .35)], mc)# markingsif lk.get("stripes") and kind == "mammal":sc = lk["stripes"]31 unmodified linesmz = lk.get("muzzle") or (_lt(fur, .5) if sn >= .05 else None)mw, mh = rx * (.48 + min(sn, .15) * 1.2), ry * (.34 + min(sn, .15) * 1.0)my_ = hy + ry * .42if longface: # the long muzzle sits low and wide at the bottom of the long facemw, mh, my_ = rx * .78, ry * .4, hy + ry * .55if lk.get("pig"):cv.ellipse(fx, my_ - ry * .02, rx * .36, ry * .26, _dk(lk["nose_col"], .92))cv.ellipse(fx, my_ - ry * .05, rx * .32, ry * .22, lk["nose_col"])20 unmodified linesfor k in (-1, 0, 1):cv.capsule(fx + s * mw * .65, my_ + k * mh * .18, fx + s * (mw * .65 + rx * .5), my_ + k * mh * .32 - mh * .1,.5, _dk(mz or fur, .5), alpha=.8)hk = lk.get("horn_kind") if _on("longface") else Noneif lk.get("horns") and hk in ("antlers", "palmate"):ac = (196, 172, 130)for s in (-1, 1): # rule (night): antlers = a branching beam sweeping up and out, tines pointing upbx0, by0 = hx + s * rx * .32, hy - ry * .78bx1, by1 = hx + s * rx * 1.05, hy - ry * 1.75aw = max(.6, rx * .08)cv.capsule(bx0, by0, (bx0 + bx1) / 2 + s * rx * .1, (by0 + by1) / 2, aw, ac)cv.capsule((bx0 + bx1) / 2 + s * rx * .1, (by0 + by1) / 2, bx1, by1, aw * .9, ac)for t_ in (.35, .7):tx_, ty_ = bx0 + (bx1 - bx0) * t_ + s * rx * .1, by0 + (by1 - by0) * t_cv.capsule(tx_, ty_, tx_ - s * rx * .12, ty_ - ry * .35, aw * .8, ac)elif lk.get("horns") and hk == "ram":for s in (-1, 1): # rule (night): ram horns curl round beside the ears_arc(cv, hx + s * rx * .75, hy - ry * .35, rx * .38, ry * .36, (math.pi * 1.6 if s > 0 else math.pi * 1.4),(math.pi * 3.3 if s > 0 else -math.pi * .3), max(.8, rx * .14), (215, 200, 170), 9)elif lk.get("horns") and longface and (lk.get("neck", 0) > .5 or hk == "ossicones"):for s in (-1, 1): # rule (night): giraffe ossicones = two short furry stalks with dark knobbed tipscv.capsule(hx + s * rx * .28, hy - ry * .78, hx + s * rx * .36, hy - ry * 1.25, max(.6, rx * .1), _dk(fur, .9))cv.ellipse(hx + s * rx * .36, hy - ry * 1.28, max(.7, rx * .13), max(.7, rx * .12), (95, 60, 40))elif lk.get("horns"):for s in (-1, 1):cv.poly([(hx + s * rx * .35, hy - ry * .8), (hx + s * rx * .65, hy - ry * .75), (hx + s * rx * .75, hy - ry * 1.35)],L.shade((235, 222, 190), s * .4, -.5, .8))215 unmodified lineslit_ellipse(cv, L, R.hx + s * R.rx * 1.0, R.hy + R.ry * .05, R.rx * .22, R.ry * .32, c)def _cape_col(wi, R):if wi.get("color"):return tuple(wi["color"])from .characters import cape_defaultreturn cape_default(getattr(R, "fur", None))def _qcurve(a, m, b, n=8):"""quadratic curve through a, m (passed at t=.5), b"""cx, cy = 2 * m[0] - (a[0] + b[0]) / 2, 2 * m[1] - (a[1] + b[1]) / 2return [((1 - t) ** 2 * a[0] + 2 * (1 - t) * t * cx + t * t * b[0], (1 - t) ** 2 * a[1] + 2 * (1 - t) * t * cy + t * t * b[1])for t in [i / n for i in range(n + 1)]]def cape_back(cv, L, R, c, U):"""rule (night, cape2): a full cape seen from the front - it hangs from the shoulders BEHIND the body, reachespast the silhouette on both sides, and flows: the trailing side (away from the facing) lifts and billows out,the hem is scalloped, folds run from the shoulders to the hem crests, and where the hem lifts the darker liningshows. Stays saturated (lit from the key side like a cylinder) so it reads as cloth, not shadow."""f = R.fsx, sy = R.shoulderssw = R.sh_wbx, by, bw, bh = R.bodyW = max(sw * 1.05, bw)top = sy - U * .01bot = R.ground - U * .025H = bot - toplead_t, trail_t = (sx + f * sw * .95, top), (sx - f * sw * .95, top)lead_b = (sx + f * (W * 1.5 + U * .03), bot)trail_b = (sx - f * (W * 1.65 + U * .2), bot - H * .2)lead = _qcurve(lead_t, (sx + f * (W * 1.2 + U * .015), top + H * .5), lead_b)trail = _qcurve(trail_b, (sx - f * (W * 1.45 + U * .13), top + H * .5), trail_t)n = 18hem = []for i in range(1, n):t = i / nx_ = lead_b[0] + (trail_b[0] - lead_b[0]) * ty_ = lead_b[1] + (trail_b[1] - lead_b[1]) * t ** 1.6y_ -= abs(math.sin(t * math.pi * 3)) * U * .03 # scallops: the hem rises between the fold crestshem.append((x_, y_))pts = [trail_t] + lead[:] + hem + traillining = mix(_dk(c, .55), (40, 20, 60), .25)cv.poly(pts, lambda px, py: L.shade(c, max(-1, min(1, (px - sx) / (W * 2.6))), -.1, .92))# lining: the inside of the lifted trailing hem (a band along the hem's far third)lin = [(x_, y_) for (x_, y_) in hem if (x_ - sx) * -f > W * .55]if len(lin) >= 2:up = [(x_ + f * U * .015, y_ - U * .045 - (abs(x_ - sx) - W * .55) * .12) for (x_, y_) in lin]cv.poly(lin + [trail_b] + [(trail_b[0] + f * U * .03, trail_b[1] - U * .06)] + up[::-1], lining)# folds: from under the shoulders to the hem crests (where the scallops hang lowest)for k in (1, 2, 3):t = k / 3.0 - 1 / 6.0hx_ = lead_b[0] + (trail_b[0] - lead_b[0]) * thy_ = lead_b[1] + (trail_b[1] - lead_b[1]) * t ** 1.6x0_ = sx + f * sw * (.6 - 1.2 * t)cv.capsule(x0_, top + H * .18, hx_, hy_ - U * .02, max(.5, U * .007), _dk(c, .7), alpha=.85)R.cape_col = cdef cape_front(cv, L, R, wear, U):"""rule (night, cape2): the cape's front edges drape over the shoulders and fall down both sides of the chest,so a front-facing character shows cloth inside its silhouette too (drawn before the head)"""if not _on("cape2") or not getattr(R, "body", None):returnfor wi in wear:if wi["item"] != "cape":continuec = getattr(R, "cape_col", None) or _cape_col(wi, R)nx, ny, nw = R.necksx, sy = R.shoulderssw = R.sh_wbx, by, bw, bh = R.bodyR.layer(SUB["back"])for s in (-1, 1):pts = [(nx + s * nw * .28, ny - nw * .08), (sx + s * sw * 1.12, sy - U * .005), (bx + s * bw * 1.08, by + bh * .3),(bx + s * bw * .94, by + bh * .55), (bx + s * bw * .72, by + bh * .15), (nx + s * nw * .32, ny + nw * .35)]cv.poly(pts, L.shade(c, s * .3, -.2, .92))cv.capsule(nx + s * nw * .32, ny + nw * .3, bx + s * bw * .68, by + bh * .12, max(.5, U * .007), _dk(c, .72))R.layer(0)def back_items(cv, L, R, wear, U):"""things worn behind the body: cape, backpack (drawn before the body)"""f = R.fR.layer(SUB["back"])for wi in wear:if wi["item"] == "cape":c = _cape_col(wi, R)if _on("cape2") and getattr(R, "body", None):cape_back(cv, L, R, c, U)continuesx, sy = R.shoulderssw = R.sh_wbot = R.ground - U * .045 unmodified linesxa = sx - sw + 2 * sw * txb = sx - sw * 1.5 - f * U * .18 + (2.9 * sw) * tcv.capsule(xa, sy + U * .05, xb, bot - U * .01, max(.5, U * .006), _dk(c, .62))elif wi["item"] == "satchel":pass # drawn in front (front_items)elif wi["item"] == "backpack":c = tuple(wi["color"]) if wi.get("color") else (200, 80, 50)bx_ = R.cx - f * R.sh_w * 1.056 unmodified linesdef front_items(cv, L, R, wear, U):"""backpack straps, neckwear, glasses, headphones, hats, in drawing order"""order = {"backpack": 0, "cape": 0.5, "satchel": .7, "scarf": 1, "tie": 1, "bowtie": 2, "glasses": 3, "headphones": 4, "hat": 5}for wi in sorted(wear, key=lambda w: order.get(w["item"], 9)):it = wi["item"]R.layer(SUB.get({"backpack": "back", "scarf": "neck", "tie": "neck", "bowtie": "neck", "cape": "neck"}.get(it, it), .45))3 unmodified linesfor s in (-1, 1):x = sx + s * R.sh_w * .55cv.capsule(x, sy, x - s * R.sh_w * .1, sy + R.chest_h * .7, max(.6, U * .012), _dk(c, .8))elif it == "satchel" and getattr(R, "body", None):# rule (night): a satchel = a strap across the chest and a flap bag at the hip, an envelope peeking outc = tuple(wi["color"]) if wi.get("color") else (125, 82, 45)sx, sy = R.shouldersbx, by, bw, bh = R.bodyhx_, hy_ = bx + R.f * bw * .95, by + bh * .55cv.capsule(sx - R.f * R.sh_w * .85, sy, hx_, hy_ - bh * .2, max(.6, U * .012), _dk(c, .8))cv.poly([(hx_ - bw * .42, hy_ - bh * .32), (hx_ + bw * .42, hy_ - bh * .32), (hx_ + bw * .38, hy_ + bh * .3),(hx_ - bw * .38, hy_ + bh * .3)], L.shade(c, R.f * .3, 0, .9))cv.poly([(hx_ - bw * .3, hy_ - bh * .42), (hx_ + bw * .3, hy_ - bh * .42), (hx_ + bw * .26, hy_ - bh * .3), (hx_ - bw * .26, hy_ - bh * .3)],(246, 244, 236))cv.poly([(hx_ - bw * .42, hy_ - bh * .32), (hx_ + bw * .42, hy_ - bh * .32), (hx_ + bw * .4, hy_), (hx_ - bw * .4, hy_)], _dk(c, .85))elif it in ("bowtie", "tie", "scarf"):neckwear(cv, L, R, it, wi.get("color"))elif it == "cape":# rule (combos): a cape reads from the front by its collar over the shoulders and the clasp at the throatc = getattr(R, "cape_col", None) or _cape_col(wi, R)nx, ny, nw = R.neckfor s_ in ((-1, 1) if not (_on("cape2") and getattr(R, "body", None)) else ()):cv.poly([(nx + s_ * nw * .15, ny - nw * .05), (nx + s_ * nw * 1.15, ny - nw * .1), (nx + s_ * nw * 1.05, ny + nw * .35),(nx + s_ * nw * .2, ny + nw * .25)], L.shade(c, s_ * .4, -.2, .9))cv.ellipse(nx, ny + nw * .1, max(.8, nw * .16), max(.8, nw * .16), (235, 195, 70))33 unmodified linesR = Rig()R.cv, R.base = cv, cv.cur_idR.f = -1 if inst.facing == "left" else 1R.fur = lk["fur"]if mode == "biped":_biped(cv, L, inst, R, lk, expr, chibi, wear)else:_sit(cv, L, inst, R, lk, expr, chibi, wear)inst.head = (R.hx, R.hy, R.rx, R.ry, R.f)inst.rig = Rcv.cur_id = R.baserun_after(inst)def run_after(inst):"""rule (night): what a partner drawn earlier puts OVER this one (hugging arms, a paw on the far shoulder)"""for fn in inst.__dict__.pop("after_draw", []) or []:fn()def _note(cv, x, y, r, fur):"""a music note (dancing): head, stem, flag - dark, or light on a dark character"""c = (60, 40, 90) if _lum(fur) > 70 else (240, 230, 250)r = max(1.0, r)cv.ellipse(x, y, r * 1.1, r * .8, c, rot=-.4)cv.capsule(x + r * .9, y - r * .1, x + r * .9, y - r * 3.0, max(.5, r * .22), c)cv.capsule(x + r * .9, y - r * 3.0, x + r * 2.0, y - r * 2.2, max(.5, r * .22), c)def _fit(inst, top_frac, half_w_frac):23 unmodified lineshy += U * .03 # rule: a sad / sleepy head hangs a littleR.hx, R.hy, R.ry = x + f * U * .02, hy, U * hrR.rx = R.ry * (1.08 if kind not in ("frog",) else 1.45)if lk.get("hooves") and kind == "mammal" and _on("longface"):# rule (night): a hoofed animal's face is long (horse, giraffe, deer): taller than wide; a giraffe's head is# also bigger on its long neck (it read as a tiny poodle head)R.ry *= 1.3 if neck else 1.08R.rx = R.ry * .8R.hy -= R.ry * .1belly = lk.get("belly") or lk.get("bib") or (_lt(fur, .45) if kind == "mammal" else None)bcx, bcy = x, g - U * body_h * .5bw, bh = U * (.27 if kind != "frog" else .36), U * body_h * .551 unmodified lineR.sh_w = bw * .8R.chest_h = U * body_h * .5R.neck = (R.hx, R.hy + R.ry * .95, R.rx * .95)R.body = (bcx, bcy, bw, bh)if kind == "bird":R.shoulders, R.sh_w, R.body = (x, g - U * .62), U * .2, (bcx, g - U * .42, U * .3, U * .42)elif kind == "frog":R.shoulders, R.body = (x, g - U * .3), (bcx, g - U * .17, U * .3, U * .17)back_items(cv, L, R, wear, U)if kind in ("mammal", "primate", "reptile"):tail(cv, L, R, lk, expr, x - f * bw * .55, g - U * .06, U)8 unmodified lineslit_ellipse(cv, L, bcx, g - U * .42, U * .3, U * .42, fur) # egg bodyif lk.get("belly"):lit_ellipse(cv, L, bcx + f * U * .02, g - U * .3, U * .19, U * .26, lk["belly"])bc_ = _wear_col(wear, "boots", _boot_default(fur)) if _on("outfit2") else Nonefor s in (-1, 1):fc = (240, 160, 50)if bc_ is not None:R.layer(SUB["clothes"])boot(cv, L, bcx + s * U * .1, g, U, U * .05, bc_, s, .12)R.layer(0)else:cv.ellipse(bcx + s * U * .1, g - U * .015, U * .07, U * .03, fc)R.hy = g - U * (.74 + (.03 if chibi else 0))R.ry = U * hr * .95R.rx = R.ry * 1.0524 unmodified linespattern=(lambda px, py, b: lk["spots"] if lk.get("spots") and (int(px / max(1, U * .06)) + int(py / max(1, U * .07))) % 3 == 0 else b))for s in (-1, 1): # hauncheslit_ellipse(cv, L, bcx + s * bw * .75, g - U * .1, U * .14, U * .11, fur)if _on("outfit2") and any(w_["item"] == "boots" for w_ in wear):R.layer(SUB["clothes"]) # boots on the hind feet toobcol = _wear_col(wear, "boots", _boot_default(fur))lit_ellipse(cv, L, bcx + s * bw * 1.0, g - U * .03, U * .1, U * .045, _dk(bcol, .9))cv.capsule(bcx + s * bw * 1.0 - U * .08, g - U * .004, bcx + s * bw * 1.0 + U * .08, g - U * .004, max(.5, U * .01), _dk(bcol, .55))R.layer(0)else:cv.ellipse(bcx + s * bw * 1.0, g - U * .02, U * .09, U * .035, _dk(fur, .85) if not lk.get("hooves") else lk["hooves"])lit_ellipse(cv, L, bcx, bcy, bw, bh, fur, pattern=_stripes(lk, bcx, bcy, bw) if lk.get("stripes") else None)if belly:lit_ellipse(cv, L, bcx + f * bw * .05, bcy + bh * .1, bw * .55, bh * .75, belly)if lk.get("spots"):for k, (dx, dy) in enumerate(((-.5, -.3), (.45, -.1), (-.2, .35), (.55, .4), (-.6, .25))):cv.ellipse(bcx + dx * bw, bcy + dy * bh, bw * .16, bh * .12, lk["spots"])bc_ = _wear_col(wear, "boots", _boot_default(fur)) if _on("outfit2") else Nonemit = _wear_col(wear, "mittens", (200, 50, 55)) if _on("outfit2") else Nonefor s in (-1, 1): # front legslx = bcx + s * bw * .38lc = fur if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"] # panda: black legslit_capsule(cv, L, lx, bcy - bh * .2, lx, g - U * .05, U * .055, lc)pc = lk["hooves"] if lk.get("hooves") else _lt(lc, .15)if bc_ is not None:R.layer(SUB["clothes"])boot(cv, L, lx, g, U, U * .055, bc_, s, .14)R.layer(0)elif mit is not None:R.layer(SUB["clothes"])lit_ellipse(cv, L, lx + s * U * .005, g - U * .035, U * .08, U * .05, mit)R.layer(0)else:lit_ellipse(cv, L, lx + s * U * .005, g - U * .03, U * .07, U * .04, pc)_clothes_sit(cv, L, R, wear, U, bcx, bcy, bw, bh, kind)cape_front(cv, L, R, wear, U)R.layer(0)head(cv, L, R, lk, expr, chibi)front_items(cv, L, R, wear, U)51 unmodified linesR.ry = U * hrR.rx = R.ry * (1.08 if kind != "frog" else 1.4)R.neck = (R.hx, sh_y + U * .01, sw * 1.05)R.body = (x, (sh_y + hip_y) / 2 + U * .01, U * (.15 if kind != "frog" else .16) * (1.1 if chibi else 1.0), U * torso * .6)gw = _garments(wear)act = at.get("action")holding = getattr(inst, "holding", None)pc = _lt(fur, .1) # paw colourmit = _wear_col(wear, "mittens", (200, 50, 55)) if _on("outfit2") else Noneleg_c = furif "overalls" in gw or "robe" in gw:leg_c = tuple(gw.get("overalls", gw.get("robe"))["color"] or (60, 95, 160))31 unmodified lineshands[f] = (x + f * (sw + U * .12), sh_y - U * .1)if act == "cheer":hands[-f] = (x - f * (sw + U * .12), sh_y - U * .1)# ---- night: interactions (hug / dance / hand over), staged by characters.stageinter_on = _on("inter")hug = getattr(inst, "hug", None) if inter_on else Nonerole = getattr(inst, "hug_role", None)dance = getattr(inst, "dance", None) if inter_on else Nonerch = (getattr(inst, "reach", None) or {}).get("front") if inter_on else Nonedefer = Falsekick = Noneif hug is not None:side = 1 if hug.x > x else -1 if hug.x < x else fp_sh = g - (g - sh_y) * hug.h / max(1e-6, inst.h) # partner's shoulder line (same ground)if role in ("first", "second"):# rule: side-by-side hug = cheek to cheek (heads lean in), the arm toward the partner goes round its# shoulders: the one drawn first reaches BEHIND (only its paw shows on the far shoulder), the second overR.hx += side * U * .045R.hy += U * .015pr = getattr(hug, "rig", None)if role == "second" and pr is not None:hands[side] = (pr.cx + side * pr.sh_w * .95, pr.shoulders[1] + U * .03)else:tgt = (hug.x + side * hug.h * .1, p_sh + U * .04)hands[side] = (x + side * (sw + U * .1), sh_y + U * .07)pc_ = _lt(fur, .12) if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"]ar_ = U * .045 * (1.1 if chibi else 1)def _paw(tgt=tgt, pc_=pc_, ar_=ar_, base=R.base):old = cv.cur_idcv.cur_id = baselit_ellipse(cv, L, tgt[0], tgt[1], ar_ * 1.3, ar_ * 1.2, pc_)cv.cur_id = oldhug.__dict__.setdefault("after_draw", []).append(_paw)hands[-side] = (x - side * (sw + U * .02), sh_y + U * torso * .8)elif role == "back":# rule: a big one hugs a small one from behind: both arms come round the small one's chest, drawn# after it; the big head bows a little over the small one's headcy_ = hug.y - hug.h * .42for s_ in (-1, 1):hands[s_] = (hug.x + s_ * hug.h * .07, cy_)R.hy += U * .02defer = Trueelif role == "front":# the hugged one holds the arms around it (paws up at the chest)for s_ in (-1, 1):hands[s_] = (x + s_ * tw * .45, sh_y + U * torso * .38)elif dance is not None or (inter_on and act == "dance"):partner = dance[0] if dance is not None else Noneside = (1 if partner.x > x else -1) if partner is not None else fif partner is not None:# rule: dancing together = the inner paws held between them at shoulder height, the outer arm flung uphands[side] = ((x + partner.x) / 2, sh_y + U * .02)else:hands[side] = (x + side * (sw + U * .14), sh_y - U * .02)hands[-side] = (x - side * (sw + U * .1), sh_y - U * .2)kick = -side # the outer foot kicks outif getattr(inst, "hands_only", False):hands[side] = ((x + partner.x) / 2, sh_y + U * torso * .55) if partner is not None else hands[side]hands[-side] = (x - side * (sw + U * .05), sh_y + U * torso * .8)kick = Noneif getattr(inst, "high_five", False) and partner is not None and _on("highfive"):# night characters 2: a high five = the inner paws meet up above the headshands[side] = ((x + partner.x) / 2, sh_y - U * .42)if rch is not None and hug is None:hands[f] = rch # rule: handing something over = the near paw reaches out to the meeting pointletter = at.get("prop") == "letter" and _on("props")if letter and not holding:hands[f] = (x + f * (sw + U * .1), sh_y - U * .04)sleeve = Nonefor k_ in ("jacket", "shirt", "robe", "dress"):if k_ in gw and not (k_ == "shirt" and (gw[k_].get("style") == "sweater" and False)):14 unmodified lineslit_capsule(cv, L, sx_, sy_, ex_, ey_, arm_r, c)lit_capsule(cv, L, ex_, ey_, hx_, hy_, arm_r * .92, c)R.layer(0)if kind != "bird" and mit is not None:R.layer(SUB["clothes"])lit_ellipse(cv, L, hx_, hy_, arm_r * 1.4, arm_r * 1.3, mit if front else _dk(mit, .85))cv.capsule(hx_ - arm_r * 1.1, hy_ - arm_r * 1.0, hx_ + arm_r * 1.1, hy_ - arm_r * 1.0, max(.5, arm_r * .35), _lt(mit, .5))R.layer(0)elif kind != "bird":lit_ellipse(cv, L, hx_, hy_, arm_r * 1.25, arm_r * 1.2, pc if not front else _lt(fur, .12) if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"])if not defer:arm(-f, False)# ---- legs and feetlr = U * .062 * (1.15 if chibi else 1)for s in (-1, 1):lx = x + s * tw * .45c = leg_c if s == f else _dk(leg_c, .85)if kick == s and kind not in ("frog", "bird"):# rule (night): a dance kick - the outer leg swings out and up, the foot pointedfx_, fy_ = lx + s * U * .16, g - U * .13lc = c if not (lk.get("eye_patch") and not lk.get("mask")) or "overalls" in gw else lk["eye_patch"]R.layer(SUB["clothes"] if leg_c != fur else 0)lit_capsule(cv, L, lx, hip_y - U * .02, fx_, fy_, lr, lc)R.layer(0)fc = lk["hooves"] if lk.get("hooves") else _lt(fur, .1) if not (lk.get("eye_patch") and not lk.get("mask")) else lk["eye_patch"]lit_ellipse(cv, L, fx_ + s * U * .03, fy_ + U * .01, U * .075, U * .04, fc, rot=s * .5)continueif kind == "frog":lit_capsule(cv, L, lx, hip_y, lx + s * U * .03, g - U * .03, lr, c)cv.ellipse(lx + s * U * .06, g - U * .015, U * .09, U * .03, _dk(fur, .85))8 unmodified linesR.layer(0)fc = lk["hooves"] if lk.get("hooves") else _lt(fur, .1) if not (lk.get("eye_patch") and not lk.get("mask")) else lk["eye_patch"]lit_ellipse(cv, L, lx + f * U * .025, g - U * .03, U * .075, U * .04, fc)bc_ = _wear_col(wear, "boots", _boot_default(fur)) if _on("outfit2") else Noneif bc_ is not None:R.layer(SUB["clothes"])boot(cv, L, lx, g, U, lr, bc_ if s == f else _dk(bc_, .85), f, .15)R.layer(0)# ---- torsotcx, tcy = x, (sh_y + hip_y) / 2 + U * .01tc = fur6 unmodified lineslit_ellipse(cv, L, tcx + f * tw * .05, tcy + U * .02, tw * .62, U * torso * .45, belly)# garments over the torso_clothes_biped(cv, L, R, gw, U, tcx, tcy, tw, torso, hip_y, g, f)cape_front(cv, L, R, wear, U)R.layer(0)# head and the near armhead(cv, L, R, lk, expr, chibi)front_items(cv, L, R, [w for w in wear if w["item"] not in ("hat",)], U)if defer:def _arms():old = cv.cur_idcv.cur_id = R.basearm(-f, True)arm(f, True)cv.cur_id = oldhug.__dict__.setdefault("after_draw", []).append(_arms)else:arm(f, True)if two or (role == "front") or (dance is not None or (inter_on and act == "dance")):arm(-f, True)front_items(cv, L, R, [w for w in wear if w["item"] == "hat"], U)if letter and not holding:ex_, ey_ = hands[f]ew_ = U * .07cv.poly([(ex_ - ew_, ey_ - ew_ * 1.2), (ex_ + ew_, ey_ - ew_ * 1.2), (ex_ + ew_, ey_ - ew_ * .05), (ex_ - ew_, ey_ - ew_ * .05)], (246, 244, 236))cv.capsule(ex_ - ew_ * .9, ey_ - ew_ * 1.1, ex_, ey_ - ew_ * .55, max(.4, U * .005), (180, 175, 165))cv.capsule(ex_, ey_ - ew_ * .55, ex_ + ew_ * .9, ey_ - ew_ * 1.1, max(.4, U * .005), (180, 175, 165))cv.ellipse(ex_ + f * ew_ * .6, ey_ - ew_ * .9, max(.6, ew_ * .2), max(.6, ew_ * .2), (210, 50, 50))lit_ellipse(cv, L, ex_, ey_, U * .05, U * .045, _lt(fur, .12))if ((dance is not None and dance[1] > 0) or (inter_on and act == "dance" and dance is None)) and not getattr(inst, "hands_only", False):_note(cv, R.hx - (dance[1] if dance is not None else f) * R.rx * 1.9, R.hy - R.ry * 1.3, R.ry * .5, fur)hx_, hy_ = hands[f]if two:hx_, hy_ = (hands[-1][0] + hands[1][0]) / 2, (hands[-1][1] + hands[1][1]) / 285 unmodified linesex_ = fx + e * rx * .34cv.ellipse(ex_, ey - ry * .06, rx * .2, ry * .12, scale(skin, .92))cv.capsule(ex_ - rx * .16, ey + ry * .02, ex_ + rx * .16, ey + ry * .02, max(.5, ry * .05), INK)elif expr == "asleep" and _on("asleep"):for e in (-1, 1): # rule (night): asleep = lids fully shut (a soft arc) + z's rising from the headex_ = fx + e * rx * .34cv.ellipse(ex_, ey - ry * .02, rx * .2, ry * .13, scale(skin, .95))_arc(cv, ex_, ey - ry * .06, rx * .15, ry * .09, math.pi * .1, math.pi * .9, max(.5, ry * .05), INK, 5)zzz2d(cv, hx + f * rx * 1.2, hy - ry * 1.1, max(1.0, ry * .25))elif expr == "winking":ex_ = fx + f * rx * .34cv.ellipse(ex_, ey, rx * .17, ry * .13, skin)_arc(cv, ex_, ey + ry * .1, rx * .14, ry * .12, math.pi * 1.15, math.pi * 1.85, max(.5, ry * .05), INK, 5)mx, my = fx + f * rx * .08, hy + ry * .64cv.ellipse(mx, my + ry * .02, rx * .22, ry * .1, MOUTH)def person_expr(cv, hx, hy, rx, ry, f, skin, hair, expr):"""rule (night, pexpr): surprised / scared on a person's face read from the EYES first - the friendly defaultbrows and smile are painted out, the eyes become whites with small pupils, the brows jump up (surprised: higharcs; scared: tilted up in the middle) and the mouth opens (surprised: a big O; scared: a tight grimace withteeth), plus a sweat drop when scared. Same anchors as people._face (3/4 head facing f)."""fx = hx + f * rx * .2ey = hy + ry * .14big = ry >= 9.5dark = (38, 26, 24)browc = scale(hair, .62) if sum(hair) < 560 else (150, 145, 145)sk = scale(skin, .97)my, mx = hy + ry * (.64 if big else .6), fx + f * rx * (.08 if big else .05)# paint out the default brows and smilefor e, k in ((1, .34), (-1, .36)):ex = fx + f * e * rx * kcv.ellipse(ex, ey - ry * .3, rx * .2, ry * .1, sk)cv.ellipse(mx, my + ry * .02, rx * .3, ry * .1, sk)for e, k, sz in ((1, .34, 1.0), (-1, .36, .86)):ex = fx + f * e * rx * kew, eh = rx * .15 * sz * (1.15 if big else 1.25), ry * .15 * (1.2 if big else 1.3)cv.ellipse(ex, ey, ew, eh, (248, 246, 242))pr = max(.55, ew * (.36 if expr == "surprised" else .28))cv.ellipse(ex + f * ew * .1, ey + eh * .05, pr, pr * 1.1, dark)if big:_arc(cv, ex, ey, ew, eh, math.pi * 1.0, math.pi * 2.0, max(.5, ry * .03), dark, 6)bw = max(.5, ry * .05)if expr == "surprised":_arc(cv, ex, ey - eh * 1.6, ew * 1.15, eh * .7, math.pi * 1.1, math.pi * 1.9, bw, browc, 5)else: # worried: the inner end (toward the nose, -f*e side) is raisedinner, outer = ex - f * e * ew * 1.1, ex + f * e * ew * 1.15cv.capsule(inner, ey - eh * 2.3, outer, ey - eh * 1.5, bw, browc)if expr == "surprised":cv.ellipse(mx, my + ry * .06, rx * .13, ry * .16, dark)if big:cv.ellipse(mx, my + ry * .13, rx * .08, ry * .06, (200, 90, 100))else:mw = rx * .22cv.ellipse(mx, my + ry * .04, mw, ry * .075, dark)cv.capsule(mx - mw * .75, my + ry * .04, mx + mw * .75, my + ry * .04, max(.5, ry * .035), (245, 243, 238))if ry >= 6:sx, sy = hx - f * rx * .7, hy - ry * .35cv.poly([(sx, sy - ry * .2), (sx - ry * .08, sy), (sx + ry * .08, sy)], TEAR)cv.ellipse(sx, sy + ry * .02, ry * .09, ry * .09, TEAR)def _boot_default(fur):"""boots are brown, unless the wearer is brownish itself - then near-black, so they read as boots"""b = (120, 70, 40)if fur and sum((a - c) ** 2 for a, c in zip(fur, b)) ** .5 < 110:return (50, 45, 55)return bdef _wear_col(wear, item, default):for wi in wear:if wi["item"] == item:return tuple(wi["color"]) if wi.get("color") else defaultreturn Nonedef boot(cv, L, x, g, U, r, col, f, h=.13):"""rule (night, outfit2): a boot over a paw - shaft up the lower leg, a rounded toe forward, a darker sole and aturned-down cuff, so it reads as footwear even at 2-3 px wide"""top = g - U * hlit_capsule(cv, L, x, top, x, g - U * .035, r * 1.12, col)lit_ellipse(cv, L, x + f * r * .45, g - U * .03, r * 1.55, U * .042, col)cv.capsule(x - f * r * .8, g - U * .006, x + f * r * 1.7, g - U * .006, max(.5, U * .01), _dk(col, .55))cv.capsule(x - r * 1.2, top + U * .01, x + r * 1.2, top + U * .01, max(.6, U * .016), _lt(col, .25))def zzz2d(cv, x, y, r, light=False):"""rule (night): a z z Z trail rising up and out from a sleeping head (screen space; r = the small z's half size)"""c = (70, 60, 120) if not light else (225, 225, 245)r = max(1.0, r)for i, (dx, dy, k) in enumerate(((0, 0, 1.0), (r * 1.6, -r * 2.4, 1.4), (r * 3.6, -r * 5.2, 1.9))):rr = r * kcx, cy = x + dx, y + dyw = max(.5, rr * .3)cv.capsule(cx - rr, cy - rr, cx + rr, cy - rr, w, c)cv.capsule(cx + rr, cy - rr, cx - rr, cy + rr, w, c)cv.capsule(cx - rr, cy + rr, cx + rr, cy + rr, w, c)
87 unmodified lines8889909192939495969712 unmodified lines11011111211311411525 unmodified lines14114214314414514614714814915015115215315415515615711 unmodified lines16917017117217317410 unmodified lines1851861871881891906 unmodified lines1971981992002012022032049 unmodified lines21421521621721821987 unmodified linesp[i] = min(255, max(0, l2 + (p[i] - l2) * sat))def compose(scene, insts, y0, W, H, rng, trace, ss=2):ctx = Ctx()ctx.time, ctx.place, ctx.season, ctx.y0 = scene["time"], scene["place"], scene["season"], y0ctx.W, ctx.H = W, H# rule: the sun goes on the side the subject faces, so the subject's face is litfacing = insts[0].facing if insts else ("right" if rng.random() < .5 else "left")side = 1 if facing == "right" else -112 unmodified linesctx.haze_color = (200, 220, 240)cv = Canvas(W, H, ss=ss)cv.id_concept = {}cv.unit = H / 128.0bg = SCENES.get(scene["place"], SCENES["field"])if scene["place"] in ("beach", "water"):25 unmodified linesoid[0] += 1cv.cur_id = oid[0]cv.id_concept[oid[0]] = it.concept # wave 12 (mood): which object each id isoutline_ids.add(oid[0])if it.info.get("animal") or it.concept in ("person", "fruit", "apple", "pear", "orange", "banana"):ctx.organic_ids.add(oid[0]) # read by pixelcraft.form_shadow (organic forms only)sink = 0if it.info.get("animal") and it.concept not in ("person", "bird", "butterfly", "fish", "snake", "duck", "owl", "penguin") \and it.pose in ("lying", "sleeping", "sitting", "resting") and getattr(it, "worn_by", None) is None:# rule: a lying / sitting animal is drawn sunk into the ground with everything below the ground clipped,# so the legs fold out of sightsink = it.h * (.3 if it.pose != "sitting" else .2)cv.clip_y = it.yit.y += sinkif getattr(it, "perch", False):from .perch import draw as draw_perchdraw_perch(cv, ctx, it) # rule: a perch is a limb under the animal (pydraw/perch.py)11 unmodified linesif sink:it.y -= sinkcv.clip_y = Nonecv.cur_id = Noneif scene.get("style") == "silhouette":# rule: silhouette style = every object becomes one flat dark shape against the sky10 unmodified lines# (colours implied by the noun, like "school bus" -> yellow, are left to the concept's own drawing)enforce(cv, oid[0], it.color, trace, it.concept)ctx.colored_ids.add(oid[0])def draw_riders(host):for r in riders:6 unmodified lineshost._held_n = nheld + 1r.x = hand[0] if nheld == 0 else hand[0] - (hand[0] - host.x) * 1.6r.y = hand[1] + (r.h * .06 if r.concept == "umbrella" else r.h * .45)draw(r)draw_riders(r)if scene["place"] in INDOOR:# rule: things resting on a flying / hung thing are drawn after itfor it in sorted(flying, key=lambda i: (1 if i.bound is not None and i.bound in flying else 0, i.h)):9 unmodified linesfor it in flying:if it.bound is not None and scene["place"] not in INDOOR:draw(it)trace.append("compose: drew %d objects far-to-near" % len(insts))cv.light_dx, cv.time, cv.place = ctx.L.d[0], ctx.time, ctx.placecv.organic_ids = ctx.organic_ids # read by pixelart.finish (rim pixels, bloom)87 unmodified lines88899091929394959697989910010110210310412 unmodified lines11711811912012112212325 unmodified lines14915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219311 unmodified lines20520620720820921021121210 unmodified lines2232242252262272282292302312322332346 unmodified lines2412422432442452462472482492502512522532542552569 unmodified lines26626726826927027127227387 unmodified linesp[i] = min(255, max(0, l2 + (p[i] - l2) * sat))NATURAL_SUPPORTS = {"rock", "boulder", "log", "stump", "tree stump", "haystack", "hay bale", "pumpkin", "mushroom", "hill","sand dune", "iceberg", "cloud", "car", "bus", "truck", "pickup truck", "van", "taxi", "train", "tractor","cake", "roof", "house", "barn", "red barn", "shed", "piano", "ball", "soccer ball", "beach ball", "basketball", "suitcase", "barrel", "crate", "chest", "trunk", "drum", "turtle", "tortoise"} # night (scene): riders sit on the drawn top (pydraw/attach.snap_top)def compose(scene, insts, y0, W, H, rng, trace, ss=2):ctx = Ctx()ctx.time, ctx.place, ctx.season, ctx.y0 = scene["time"], scene["place"], scene["season"], y0ctx.W, ctx.H = W, Hfrom .tether import spread as _tether_gap # language shift 3: a tied thing steps back so its rope shows_tether_gap(insts, W, trace)# rule: the sun goes on the side the subject faces, so the subject's face is litfacing = insts[0].facing if insts else ("right" if rng.random() < .5 else "left")side = 1 if facing == "right" else -112 unmodified linesctx.haze_color = (200, 220, 240)cv = Canvas(W, H, ss=ss)cv.id_concept = {}cv.id_inst = {}cv.unit = H / 128.0bg = SCENES.get(scene["place"], SCENES["field"])if scene["place"] in ("beach", "water"):25 unmodified linesoid[0] += 1cv.cur_id = oid[0]cv.id_concept[oid[0]] = it.concept # wave 12 (mood): which object each id iscv.id_inst[oid[0]] = it # night pixel round 3: post passes (cast shadow, reflection, fog depth) read the instanceit._oid = oid[0]outline_ids.add(oid[0])if it.info.get("animal") or it.concept in ("person", "fruit", "apple", "pear", "orange", "banana"):ctx.organic_ids.add(oid[0]) # read by pixelcraft.form_shadow (organic forms only)_cond = (getattr(it, "attrs", None) or {}).get("cond")if _cond:from . import language as _lang_cond = _cond if _lang.on("condpx") else None_snap = Noneif _cond: # night wave (language): conditions need what was behind the object (torn holes, bent shapes)from .condition_px import snapshot as _cond_snap_snap = _cond_snap(cv)sink = 0if it.info.get("animal") and it.concept not in ("person", "bird", "butterfly", "fish", "snake", "duck", "owl", "penguin") \and it.pose in ("lying", "sleeping", "sitting", "resting") and getattr(it, "worn_by", None) is None \and getattr(it, "clip_below", None) is None \and not (it.pose == "sitting" and it.concept in ("dog", "cat") and EXP.get("sit2", "1") != "0"):# rule: a lying / sitting animal is drawn sunk into the ground with everything below the ground clipped,# so the legs fold out of sightsink = it.h * (.3 if it.pose != "sitting" else .2)if it.pose == "sleeping" and EXP.get("doze2", "1") != "0":# rule (night characters 2, doze2): long-legged sleepers sink until the belly rests on the ground# (a sleeping deer / lion stood knee-deep in the grass)sink = it.h * {"deer": .4, "horse": .42, "zebra": .42, "cow": .4, "lion": .4, "tiger": .4, "wolf": .38,"goat": .4, "sheep": .36, "giraffe": .3, "camel": .42, "llama": .42}.get(it.concept, .3)cv.clip_y = it.yit.y += sinkif getattr(it, "clip_below", None) is not None:cv.clip_y = it.clip_below # night (scene): a rider in a vehicle is hidden below the door lineif getattr(it, "cord", None):from .attach import draw_cord # night (scene): a hanging thing's cord, drawn under itdraw_cord(cv, ctx, it)if getattr(it, "hollow", None):from .attach import draw_hollow # language shift 3: an owl in a tree holedraw_hollow(cv, ctx, it)if getattr(it, "limb", None):from .attach import draw_limb # night (scene): the branch an animal in a tree sits ondraw_limb(cv, ctx, it)if getattr(it, "perch", False):from .perch import draw as draw_perchdraw_perch(cv, ctx, it) # rule: a perch is a limb under the animal (pydraw/perch.py)11 unmodified linesif sink:it.y -= sinkcv.clip_y = Noneif getattr(it, "clip_below", None) is not None:cv.clip_y = Nonecv.cur_id = Noneif scene.get("style") == "silhouette":# rule: silhouette style = every object becomes one flat dark shape against the sky10 unmodified lines# (colours implied by the noun, like "school bus" -> yellow, are left to the concept's own drawing)enforce(cv, oid[0], it.color, trace, it.concept)ctx.colored_ids.add(oid[0])if _snap is not None: # rule: rare adjectives (tattered, rusty, gleaming, gnarled...) drawn on the object's pixelsfrom .condition_px import apply as _cond_apply_cond_apply(cv, oid[0], _cond, _snap, it, trace, seed=getattr(it, "k", 0))if getattr(it, "surface", None) == "cracked":from .surface import draw_cracks # night (scene): a cracked surface statedraw_cracks(cv, ctx, it, oid[0])def draw_riders(host):for r in riders:6 unmodified lineshost._held_n = nheld + 1r.x = hand[0] if nheld == 0 else hand[0] - (hand[0] - host.x) * 1.6r.y = hand[1] + (r.h * .06 if r.concept == "umbrella" else r.h * .45)if getattr(r, "attach_kind", None) in ("back", "stuffed", "topper") or (host.concept in NATURAL_SUPPORTS and r.rel == "on" and getattr(r, "held_by", None) is Noneand not getattr(r, "attach_kind", None) and EXP.get("snapsup", "1") != "0"):from .attach import snap_top # night (scene): sits on the host's DRAWN top, not its box topsnap_top(cv, host, r)draw(r)draw_riders(r)fn = host.__dict__.pop("after_riders", None) # night characters 2: e.g. a puddle's splash over the splasherif fn:fn()if scene["place"] in INDOOR:# rule: things resting on a flying / hung thing are drawn after itfor it in sorted(flying, key=lambda i: (1 if i.bound is not None and i.bound in flying else 0, i.h)):9 unmodified linesfor it in flying:if it.bound is not None and scene["place"] not in INDOOR:draw(it)from .tether import draw_px as _tethers # language shift 3: "a boat tied to a dock with a rope" (rope line)_tethers(cv, ctx, insts, trace)trace.append("compose: drew %d objects far-to-near" % len(insts))cv.light_dx, cv.time, cv.place = ctx.L.d[0], ctx.time, ctx.placecv.organic_ids = ctx.organic_ids # read by pixelart.finish (rim pixels, bloom)
53 unmodified lines545556575859154 unmodified lines21421521621721821922022119 unmodified lines2412422432442452462472482492502512527 unmodified lines2602612622632642658 unmodified lines27427527627727827953 unmodified lines# rule: eyes and nostrils never shrink below one pixel or they vanish in pixel artX, Y = self.P(u, v)rr = max(r * self.s, .6 * self.px)self.cv.ellipse(X, Y, rr, rr, col)def leg(self, hip, knee, foot_u, r0, r1, col, hoof=None, hoof_h=.03, pattern=None):154 unmodified lines# ---------------------------------------------------------------- horse + zebradef draw_equine(cv, ctx, inst, zebra=False):F = Frame(cv, ctx, inst)c = coat_of(inst, None)if zebra:# rule: zebra prompt colour is the base coat, stripes stay dark (black zebra -> white stripes)19 unmodified linesif zebra:F.taper([(-.47, .70), (-.53, .60), (-.55, .48)], .018, .014, base, pat)F.taper([(-.55, .50), (-.56, .40), (-.55, .33)], .03, .02, mane) # rule: zebra tail ends in a dark tuftelse:F.taper([(-.46, .7), (-.54, .6), (-.57, .46), (-.57, .32), (-.53, .2)], .06, .04, mane,fur(F, .25, 7)) # rule: a long flowing horse tail, the signature from behind# far legs (darker)F.leg((.24, .48), (.28, .22), .27, .058 * k, .03 * k, far, HOOF, pattern=pat if zebra else None)F.leg((-.30, .5), (-.38, .23), -.33, .068 * k, .03 * k, far, HOOF, pattern=pat if zebra else None)# body: haunch + barrel + chestF.blob([("e", -.28, .57, .18 * k, .18 * k), ("e", 0, .545, .34, .17 * k), ("e", .25, .57, .16 * k, .18 * k),("c", .25, .6, .32, .74, .14 * k), ("c", .32, .74, .38, .85, .11 * k), ("c", .38, .85, .43, .92, .08)],7 unmodified linesF.cap(u - .045, v + .02, u - .065, v + .06, .018, mane if i % 2 == 0 else (236, 234, 228))else:F.taper([(.22, .76), (.29, .86), (.36, .94), (.41, .985)], .035, .03, mane, fur(F, .3, 9))F.cap(.45, .97, .48, .925, .02, mane) # forelock# head: wedge from poll to muzzleF.ell(.455, .9, .075, .065, base, pattern=pat)8 unmodified linesF.dot(.485, .905, .013, EYE)F.dot(.625, .78, .009, (20, 16, 16))# near legsF.leg((.27, .48), (.31, .22), .33, .062 * k, .032 * k, base if zebra else base, HOOF, pattern=pat if zebra else None)F.leg((-.26, .51), (-.35, .23), -.29, .072 * k, .032 * k, base, HOOF, pattern=pat if zebra else None)if not zebra:53 unmodified lines545556575859606162636465666768697071154 unmodified lines22622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329419 unmodified lines3143153163173183193203213223233243253263273283293303317 unmodified lines3393403413423433443453463473488 unmodified lines35735835936036136236336436536636736836937053 unmodified lines# rule: eyes and nostrils never shrink below one pixel or they vanish in pixel artX, Y = self.P(u, v)rr = max(r * self.s, .6 * self.px)if col == EYE and getattr(self.inst, "pose", None) == "sleeping" and _night_on("doze2"):# rule (night characters 2, doze2): a sleeping side-view animal (bear, fox, deer ...) lies sunk in the grass# with its eye shut - a little downward arc - and z's rising from the head (it lay there wide awake)er = max(r * 1.25, .7 * self.px / self.s)w = max(.006, er * .32)self.cap(u - er * 1.2, v + er * .2, u, v - er * .35, w, EYE, lit=False)self.cap(u, v - er * .35, u + er * 1.1, v + er * .1, w, EYE, lit=False)if not getattr(self.inst, "_zzz", False):self.inst._zzz = Truefrom .core import zzzzzz(self, u - .02, v + .1, night=self.ctx.time == "night")returnself.cv.ellipse(X, Y, rr, rr, col)def leg(self, hip, knee, foot_u, r0, r1, col, hoof=None, hoof_h=.03, pattern=None):154 unmodified lines# ---------------------------------------------------------------- horse + zebradef _night_on(name):import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get(name, "1") != "0"def gallop_leg(F, hip, knee, hoof, r0, r1, col, hoof_c=None, pattern=None):"""a leg with a free foot (running): hip -> knee -> hoof / paw anywhere, not planted on the ground"""F.cap(hip[0], hip[1], knee[0], knee[1], r0, col, pattern)F.cap(knee[0], knee[1], hoof[0], hoof[1], r1, col, pattern)if hoof_c:F.cap(hoof[0], hoof[1], hoof[0] + .006, hoof[1] - .012, r1 * 1.15, hoof_c)def motion_marks(F, back_u, vs, ground_lift=0.0):"""rule (night, run2): speed lines streak behind a runner (at heights vs) and dust puffs kick up on the ground"""sl = (236, 236, 230)for k, v in enumerate(vs):u0 = back_u - .03 * kF.cap(u0, v, u0 - .2 + .05 * (k % 2), v, max(.006, .55 * F.px / F.s), sl, lit=False, alpha=.75)for du, r in ((-.0, .045), (-.12, .035), (-.22, .025)):X, Y = F.P(back_u + .1 + du, 0)F.cv.ellipse(X, Y + ground_lift * F.s - r * F.s * .5, r * F.s * 1.3, r * F.s, (214, 200, 172), 0, .8)def start_run(F, inst):"""rule (night, run2): a running side-view animal is drawn mid-stride, airborne over its shadow; the frameshrinks a little so the longer stride fits its box. Returns True when the gallop applies."""if inst.pose not in ("running", "jumping") or not _night_on("run2"):return False # (jumping / leaping / hopping = the same suspended phase, a little higher)F.s *= .9F.x += F.f * .04 * F.sF.y -= (.07 if inst.pose == "running" else .2) * F.sreturn Truedef gallop(F, hip, r0, r1, col, front, near, hoof=None, pattern=None, paw=None):"""one leg of the gallop from its hip: near fore reaches forward, far fore folds under, near hind pushes underthe body, far hind stretches back"""hu, hv = hipif front and near:knee, foot = (hu + .14, hv * .8), (hu + .3, hv * .62)elif front:knee, foot = (hu + .12, hv * .66), (hu + .03, hv * .42)elif near:knee, foot = (hu - .06, hv * .55), (hu + .08, hv * .24)else:knee, foot = (hu - .16, hv * .72), (hu - .36, hv * .58)gallop_leg(F, hip, knee, foot, r0, r1, col, hoof, pattern)if paw is not None:F.ell(foot[0] + (.015 if front else -.015), foot[1], r1 * 1.6, r1 * .95, paw)return footdef draw_equine(cv, ctx, inst, zebra=False):F = Frame(cv, ctx, inst)run = inst.pose == "running" and _night_on("run2")if run:# rule (night, run2): a galloping horse = the suspended phase - fore legs reaching / folded, hind legs# stretched back, body lifted over its shadow, tail and mane streaming; the frame shrinks to fit the strideF.s *= .9F.x += F.f * .07 * F.sF.y -= .07 * F.sc = coat_of(inst, None)if zebra:# rule: zebra prompt colour is the base coat, stripes stay dark (black zebra -> white stripes)19 unmodified linesif zebra:F.taper([(-.47, .70), (-.53, .60), (-.55, .48)], .018, .014, base, pat)F.taper([(-.55, .50), (-.56, .40), (-.55, .33)], .03, .02, mane) # rule: zebra tail ends in a dark tuftelif run:F.taper([(-.46, .7), (-.57, .69), (-.67, .64), (-.76, .6), (-.84, .58)], .06, .04, mane, fur(F, .25, 7))else:F.taper([(-.46, .7), (-.54, .6), (-.57, .46), (-.57, .32), (-.53, .2)], .06, .04, mane,fur(F, .25, 7)) # rule: a long flowing horse tail, the signature from behind# far legs (darker)if run:gallop_leg(F, (.24, .48), (.34, .33), (.27, .22), .058 * k, .03 * k, far, HOOF, pat if zebra else None)gallop_leg(F, (-.30, .5), (-.46, .34), (-.66, .27), .068 * k, .03 * k, far, HOOF, pat if zebra else None)else:F.leg((.24, .48), (.28, .22), .27, .058 * k, .03 * k, far, HOOF, pattern=pat if zebra else None)F.leg((-.30, .5), (-.38, .23), -.33, .068 * k, .03 * k, far, HOOF, pattern=pat if zebra else None)# body: haunch + barrel + chestF.blob([("e", -.28, .57, .18 * k, .18 * k), ("e", 0, .545, .34, .17 * k), ("e", .25, .57, .16 * k, .18 * k),("c", .25, .6, .32, .74, .14 * k), ("c", .32, .74, .38, .85, .11 * k), ("c", .38, .85, .43, .92, .08)],7 unmodified linesF.cap(u - .045, v + .02, u - .065, v + .06, .018, mane if i % 2 == 0 else (236, 234, 228))else:F.taper([(.22, .76), (.29, .86), (.36, .94), (.41, .985)], .035, .03, mane, fur(F, .3, 9))if run: # the mane streams back off the crestfor t in (.2, .5, .8):u, v = .22 + .19 * t, .78 + .2 * tF.cap(u, v, u - .09, v + .025, .016, mane)F.cap(.45, .97, .48, .925, .02, mane) # forelock# head: wedge from poll to muzzleF.ell(.455, .9, .075, .065, base, pattern=pat)8 unmodified linesF.dot(.485, .905, .013, EYE)F.dot(.625, .78, .009, (20, 16, 16))# near legsif run:gallop_leg(F, (.27, .48), (.43, .4), (.58, .33), .062 * k, .032 * k, base, HOOF, pat if zebra else None)gallop_leg(F, (-.26, .51), (-.33, .3), (-.2, .14), .072 * k, .032 * k, base, HOOF, pat if zebra else None)if not zebra:F.cap(.48, .37, .58, .33, .033, leg_lo)F.cap(-.27, .25, -.2, .14, .033, leg_lo)motion_marks(F, -.62, (.72, .55, .4), .07)returnF.leg((.27, .48), (.31, .22), .33, .062 * k, .032 * k, base if zebra else base, HOOF, pattern=pat if zebra else None)F.leg((-.26, .51), (-.35, .23), -.29, .072 * k, .032 * k, base, HOOF, pattern=pat if zebra else None)if not zebra:
1 unmodified line2345678117 unmodified lines12612712812913013113253 unmodified lines1861871881891901911921931941951961971981992002012027 unmodified lines21021121221321421521621710 unmodified lines22822923023123223323423523623723823911 unmodified lines25125225325425525641 unmodified lines29829930030130230330430530630730830931031131231331431523 unmodified lines339340341342343344239 unmodified lines58458558658758858959059159259359459559659759859960060110 unmodified lines612613614615616617137 unmodified lines75575675775875976076176276376476515 unmodified lines781782783784785786382 unmodified lines11691170117111721173117411751176117711781 unmodified lineSame convention as animals.py: a local side-view Frame (u forward toward the head, v up from the ground, both inunits of inst.h) so each recipe works at any size and mirrors with inst.facing."""from ..kit import *from .animals import Frame, fur, EYE, HOOFWATER = (34, 88, 138)FOAM = (236, 246, 252)117 unmodified lineswater = on_water(ctx, inst)lift = -.12 if water else .16 # rule: on water the bottom of the body sits below the surface# legs on landif not water:for du, sh in ((-.06, .8), (.06, 1.0)):F.cap(du, .17, du + .02, .03, .018, scale(ORANGE_BILL, sh))F.ell(du + .07, .02, .07, .022, scale(ORANGE_BILL, sh))53 unmodified linesreturn bfar = scale(base, .7)k = 1.15 if wolf else 1.0# tail (rule: fox tail is huge, bushy and white-tipped; wolf tail hangs low and bushy)if wolf:F.taper([(-.46, .6), (-.56, .5), (-.6, .38), (-.6, .26)], .06, .1, base, pat0)F.ell(-.6, .24, .07, .075, scale(base, .55)) # rule: wolf tail hangs low, bushy, with a dark tipelse:F.taper([(-.42, .55), (-.56, .47), (-.7, .4), (-.82, .37)], .07, .12, base, pat0)F.ell(-.88, .37, .075, .075, WHITE)# far legsF.leg((.28, .4), (.3, .2), .32, .05 * k, .034 * k, far)F.leg((-.32, .42), (-.38, .22), -.34, .058 * k, .034 * k, far)if not wolf:F.cap(.31, .2, .32, .03, .032, scale(sock, .8))F.cap(-.38, .2, -.34, .03, .032, scale(sock, .8))# body + neck + head7 unmodified linesF.taper([(.5, .73), (.62, .69), (.72, .66)], .075, .04, base)F.cap(.52, .67, .68, .645, .03, mix(base, (238, 232, 220), .55))F.dot(.73, .665, .026, BLACK)F.dot(.55, .77, .02, (235, 200, 80))F.dot(.553, .77, .01, BLACK)else:# snout: long and pointed (rule: a narrow pointed snout separates fox/wolf from dog)F.taper([(.5, .72), (.6, .68), (.69, .65)], .065, .028, base)10 unmodified linesif not wolf:F.poly([(.42 + du, .82), (.46 + du, .82), (.435 + du, .93)], scale(BLACK, sh * 1.2), (0, .5, .8))# near legsF.leg((.3, .4), (.32, .2), .35, .052 * k, .036 * k, base)F.leg((-.28, .42), (-.33, .22), -.29, .06 * k, .036 * k, base)F.cap(.33, .2, .35, .03, .034, sock)F.cap(-.33, .2, -.29, .03, .034, sock)def draw_fox(cv, ctx, inst):draw_canine(cv, ctx, inst, wolf=False)11 unmodified linesinner = PINK if inst.color not in ("pink", "red") else (250, 215, 220)tail = WHITE if inst.color != "white" else (225, 222, 215)el = .1 if hare else 0 # rule: hares have longer ears and legs# far ear (laid slightly back)F.cap(.17, .58, .05, .92 + el, .045, scale(base, .75))# body: big round haunch + chest + head as one mass41 unmodified linespat = chain(fur(F, .12, 7), under, stripes) if not lion else chain(fur(F, .14, 7), under)lpat = legstripes if not lion else Nonefar = scale(base, .7)# tail: long, low, curling up at the endtpts = [(-.52, .6), (-.64, .5), (-.74, .4), (-.83, .38), (-.87, .45)]F.taper(tpts, .028, .022, base, stripes if not lion else None)if lion:F.ell(-.875, .47, .03, .045, (90, 52, 28)) # rule: lion tail ends in a dark tuftelse:F.ell(-.87, .46, .026, .03, dark)# far legsF.leg((.3, .48), (.31, .22), .33, .06, .042, far, pattern=lpat)F.leg((-.36, .5), (-.43, .24), -.37, .068, .042, far, pattern=lpat)F.ell(.36, .03, .065, .03, far)F.ell(-.34, .03, .065, .03, far)# body# rule: heavy shoulders and a slightly sagging belly line give the big-cat massF.blob([("e", -.34, .57, .17, .17), ("c", -.34, .58, .25, .6, .16), ("e", .27, .6, .16, .19),23 unmodified linesif not lion:F.ell(.6, .79, .03, .012, WHITE, rot=.2, lit=False)# near legsF.leg((.33, .48), (.34, .22), .37, .062, .044, base, pattern=lpat)F.leg((-.3, .5), (-.36, .24), -.31, .07, .044, base, pattern=lpat)F.ell(.4, .03, .068, .032, belly if not lion else base)239 unmodified linespat = fur(F, .2, 21)far = scale(base, .7)k = 1.25 if gorilla else 1.0# tail (rule: only monkeys have a long tail curling up behind; apes have none)if not ape:F.taper([(-.18, .18), (-.34, .12), (-.46, .2), (-.48, .38), (-.4, .5), (-.32, .44)], .035, .028, base, pat)# far arm, long, hand on the groundF.taper([(.0, .58), (.14, .36), (.2, .06)], .06 * k, .045 * k, far)# body: pear, leaning forward; folded legs with knees forwardF.blob([("e", -.04, .36, .2 * k, .26), ("e", .02, .56, .17 * k, .14), ("e", .1, .2, .17, .1)], base, pat)F.ell(.17, .06, .1, .045, face if not gorilla else scale(base, .8)) # footif gorilla:F.ell(.03, .42, .13, .14, scale(base, 1.25), pattern=pat) # chest# headhu, hv = .12, .74F.ell(hu - .02, hv, .15, .14, base, pattern=pat)if gorilla:F.ell(hu - .06, hv + .1, .1, .07, base, pattern=pat) # rule: gorilla crest + heavy brow10 unmodified linesF.dot(hu + .14, hv + .03, .014, EYE)F.cap(hu + .1, hv - .08, hu + .17, hv - .075, .006, scale(face, .5), lit=False)# near armF.taper([(.04, .56), (.2, .36), (.26, .06)], .065 * k, .05 * k, base, pat)F.ell(.28, .04, .05 * k, .035, face if not gorilla else scale(base, .7))137 unmodified linesif v > .5 and -.38 < u < .22 and noise(u * 20, v * 20, 9) > .62:return (245, 240, 230)return b# white tail flagF.ell(-.38, .54, .03, .045, (245, 240, 232))# far legs: long and thinF.leg((.22, .42), (.24, .2), .25, .04, .022, far, HOOF, .025)F.leg((-.3, .45), (-.36, .22), -.31, .048, .022, far, HOOF, .025)# body + neck + head (rule: the head sits low enough that big antlers fit above it)F.blob([("e", -.27, .5, .13, .12), ("c", -.27, .5, .2, .5, .11), ("e", .2, .52, .12, .13),("c", .22, .55, .34, .7, .06), ("e", .36, .72, .065, .055)], base, pat)15 unmodified lines((.275, .92), (.35 * A, .97)), ((.28, .9), (.2, .97))):F.cap(bu + du, bv, tu + du, tv, .01, c)# near legsF.leg((.24, .42), (.26, .2), .28, .042, .023, base, HOOF, .025)F.leg((-.26, .45), (-.31, .22), -.26, .05, .023, base, HOOF, .025)382 unmodified linesF.dot(.22, .87, .014, EYE)for du, sh in ((-.04, .8), (0, 1.0)):F.ell(.15 + du, .96, .025, .06, scale(base, sh), rot=.2)F.taper([(.13, .62), (.22, .55), (.26, .5)], .03, .02, scale(base, .9)) # small armF.ell(-.04, .24, .13, .17, base, rot=.4, pattern=pat) # near thighF.taper([(-.04, .14), (.02, .05)], .05, .04, base)F.ell(.08, .03, .2, .035, base)# ---------------------------------------------------------------- koala (sitting, front)1 unmodified line2345678117 unmodified lines12612712812913013113213313413513613713813914014114214314453 unmodified lines1981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282297 unmodified lines23723823924024124224324424524624710 unmodified lines25825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233311 unmodified lines34534634734834935035135235335435535635735835936036136236336436536636736841 unmodified lines41041141241341441541641741841942042142242342442542642742842943043143243343443523 unmodified lines459460461462463464465466467468469239 unmodified lines70971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374410 unmodified lines755756757758759760761762763764137 unmodified lines90290390490590690790890991091191291391491591691715 unmodified lines933934935936937938939940941942943382 unmodified lines13261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501 unmodified lineSame convention as animals.py: a local side-view Frame (u forward toward the head, v up from the ground, both inunits of inst.h) so each recipe works at any size and mirrors with inst.facing."""from ..kit import *from .animals import Frame, fur, EYE, HOOF, start_run, gallop, motion_marksWATER = (34, 88, 138)FOAM = (236, 246, 252)117 unmodified lineswater = on_water(ctx, inst)lift = -.12 if water else .16 # rule: on water the bottom of the body sits below the surface# legs on landwear = (getattr(inst, "attrs", None) or {}).get("wear") or []bootc = Noneif (getattr(inst, "attrs", None) or {}).get("profile_boots"):bootc = next((tuple(w["color"]) for w in wear if w["item"] == "boots" and w.get("color")), (235, 200, 40))if not water and bootc:# rule (night characters 2, duckboots): rain boots on a duck = two chunky wellies on its legs, toes forwardfor du, sh in ((-.07, .78), (.07, 1.0)):bc = scale(bootc, sh)F.cap(du, .19, du + .005, .07, .055, bc)F.cap(du - .01, .04, du + .07, .035, .035, bc)F.cap(du - .02, .012, du + .085, .012, .012, scale(bc, .55), lit=False)F.cap(du - .045, .2, du + .05, .2, .012, scale(bc, 1.12) if sum(bc) < 600 else scale(bc, .85), lit=False)elif not water:for du, sh in ((-.06, .8), (.06, 1.0)):F.cap(du, .17, du + .02, .03, .018, scale(ORANGE_BILL, sh))F.ell(du + .07, .02, .07, .022, scale(ORANGE_BILL, sh))53 unmodified linesreturn bfar = scale(base, .7)k = 1.15 if wolf else 1.0from .animals import _night_onif inst.pose == "howling" and _night_on("howl"):_canine_howl(F, inst, base, far, belly, pat, pat0, wolf)returnif inst.pose == "sleeping" and not wolf and _night_on("curl"):_canine_curl(F, inst, base, belly, pat0)returnrun = start_run(F, inst)# tail (rule: fox tail is huge, bushy and white-tipped; wolf tail hangs low and bushy)if run: # the brush streams straight out behindF.taper([(-.42, .55), (-.58, .56), (-.72, .58), (-.84, .6)], .06 if not wolf else .055, .1, base, pat0)F.ell(-.89, .6, .07, .07, WHITE if not wolf else scale(base, .55))elif wolf:F.taper([(-.46, .6), (-.56, .5), (-.6, .38), (-.6, .26)], .06, .1, base, pat0)F.ell(-.6, .24, .07, .075, scale(base, .55)) # rule: wolf tail hangs low, bushy, with a dark tipelse:F.taper([(-.42, .55), (-.56, .47), (-.7, .4), (-.82, .37)], .07, .12, base, pat0)F.ell(-.88, .37, .075, .075, WHITE)# far legsif run:gallop(F, (.28, .4), .05 * k, .034 * k, far, True, False, paw=scale(sock, .8))gallop(F, (-.32, .42), .058 * k, .034 * k, far, False, False, paw=scale(sock, .8))else:F.leg((.28, .4), (.3, .2), .32, .05 * k, .034 * k, far)F.leg((-.32, .42), (-.38, .22), -.34, .058 * k, .034 * k, far)if not wolf and not run:F.cap(.31, .2, .32, .03, .032, scale(sock, .8))F.cap(-.38, .2, -.34, .03, .032, scale(sock, .8))# body + neck + head7 unmodified linesF.taper([(.5, .73), (.62, .69), (.72, .66)], .075, .04, base)F.cap(.52, .67, .68, .645, .03, mix(base, (238, 232, 220), .55))F.dot(.73, .665, .026, BLACK)if inst.pose == "sleeping":F.dot(.55, .77, .018, EYE) # night characters 2 (doze2): a sleeping wolf's amber eye is shut (Frame.dot)else:F.dot(.55, .77, .02, (235, 200, 80))F.dot(.553, .77, .01, BLACK)else:# snout: long and pointed (rule: a narrow pointed snout separates fox/wolf from dog)F.taper([(.5, .72), (.6, .68), (.69, .65)], .065, .028, base)10 unmodified linesif not wolf:F.poly([(.42 + du, .82), (.46 + du, .82), (.435 + du, .93)], scale(BLACK, sh * 1.2), (0, .5, .8))# near legsif run:gallop(F, (.3, .4), .052 * k, .036 * k, base, True, True, paw=sock)gallop(F, (-.28, .42), .06 * k, .036 * k, base, False, True, paw=sock)motion_marks(F, -.95, (.62, .48, .34), .07)returnF.leg((.3, .4), (.32, .2), .35, .052 * k, .036 * k, base)F.leg((-.28, .42), (-.33, .22), -.29, .06 * k, .036 * k, base)F.cap(.33, .2, .35, .03, .034, sock)F.cap(-.33, .2, -.29, .03, .034, sock)def _canine_curl(F, inst, base, belly, pat0):"""(night characters 3, curl; critic4 "a fox curled up asleep"): a sleeping fox curls into a ball - a low roundbody, the head tucked down at the front, the huge brush wrapped round the front with its white tip over the nose.(The compose pass sinks a sleeper .3 of its box: v = .3 is the ground here.) Before: a standing fox sunk in snow."""g = .3F.ell(-.12, g + .14, .3, .17, scale(base, .9), pattern=pat0) # haunchF.blob([("e", .02, g + .1, .38, .14), ("e", -.14, g + .17, .2, .14)], base, pat0) # curled bodyfor du, sh in ((-.06, .7), (0, 1.0)): # ears up, dark tipsF.poly([(.22 + du, g + .25), (.32 + du, g + .27), (.25 + du, g + .4)], scale(base, sh), (0, .5, .8))F.poly([(.235 + du, g + .33), (.27 + du, g + .335), (.25 + du, g + .4)], (40, 28, 26), (0, .5, .8))F.ell(.3, g + .18, .13, .1, base, pattern=pat0) # head resting on the bodyF.ell(.36, g + .13, .085, .05, mix(base, belly, .7)) # pale cheekF.dot(.33, g + .2, .02, EYE) # (shut: sleeping)# the brush wraps round the front, over the snout, white tip at the noseF.taper([(-.38, g + .12), (-.3, g + .03), (-.05, g + .0), (.25, g + .02), (.42, g + .07)], .07, .1, base, pat0)F.ell(.47, g + .1, .085, .075, WHITE)def _canine_howl(F, inst, base, far, belly, pat, pat0, wolf):"""(night characters 3, howl; critic C26) the classic howl silhouette: sitting on the haunches, chest up on straightfront legs, neck stretched and the head thrown back with the long snout pointing up at the sky, mouth open, earslaid back, the bushy tail along the ground. Before: a standing wolf looking straight ahead."""F.x -= F.f * .08 * F.s # the sitting silhouette is narrower than the standing box: centre ittip = scale(base, .55) if wolf else WHITE# tail along the ground behind the haunchF.taper([(-.3, .14), (-.46, .08), (-.6, .06), (-.7, .07)], .055, .075, base, pat0)F.ell(-.74, .08, .065, .05, tip)# far front legF.cap(.14, .42, .17, .05, .04, far)F.ell(.2, .03, .05, .025, scale(far, .9))def hpat(px, py, b):# pale chest / throat only on the front of the upright body (the standing belly band would paint the haunch)u, v = F.uv(px, py)b = pat0(px, py, b)if u > .1 and .3 < v < .8:b = mix(b, belly, min(1, (u - .1) * 7) * (.55 if wolf else .9))return b# haunch + body rising to the chest, thick neck ruff up to the thrown-back headF.blob([("e", -.16, .24, .22, .22), ("c", -.12, .3, .12, .5, .16), ("e", .14, .5, .15, .18),("c", .14, .56, .26, .8, .13), ("e", .26, .82, .12, .11)], base, hpat)# hind foot flat on the ground in front of the haunchF.ell(-.02, .035, .13, .035, scale(base, .9))# near front leg, straightF.cap(.2, .42, .24, .05, .045, base)F.ell(.27, .03, .055, .028, base)# head thrown back: the long snout points up at the sky, the mouth open under itF.taper([(.3, .86), (.36, .95), (.41, 1.03)], .06, .028, base)F.taper([(.32, .82), (.38, .88), (.44, .95)], .03, .018, scale(base, .9)) # lower jaw, apartF.poly([(.33, .87), (.42, 1.0), (.43, .955)], (60, 30, 34)) # open mouth gapF.dot(.415, 1.035, .022, BLACK) # nose at the tipF.cap(.3, .8, .38, .87, .025, mix(base, (238, 232, 220), .55)) # pale throat / cheekF.dot(.27, .88, .018, EYE if not wolf else (235, 200, 80))if wolf:F.dot(.272, .88, .009, BLACK)# ears laid back along the skullfor du, sh in ((-.04, .8), (0, 1.0)):F.poly([(.17 + du, .86), (.24 + du, .9), (.1 + du, .97)], scale(base, sh), (0, .5, .8))def draw_fox(cv, ctx, inst):draw_canine(cv, ctx, inst, wolf=False)11 unmodified linesinner = PINK if inst.color not in ("pink", "red") else (250, 215, 220)tail = WHITE if inst.color != "white" else (225, 222, 215)el = .1 if hare else 0 # rule: hares have longer ears and legsif start_run(F, inst):# rule (night, run2): a running rabbit is mid-hop - body stretched long, hind feet kicked back, front paws# reaching, ears laid back, high over its shadowF.y -= .08 * F.sF.cap(.15, .56, -.08, .8 + el * .6, .045, scale(base, .75))F.cap(-.3, .24, -.62, .1, .07, scale(base, .9))F.ell(-.66, .08, .14, .04, scale(base, .9), rot=-.3)F.blob([("e", -.2, .32, .25, .2), ("e", .05, .36, .2, .18), ("c", .1, .42, .26, .52, .09),("e", .32, .55, .13, .11)], base, pat)F.cap(.18, .3, .4, .16, .04, base)F.ell(.43, .15, .05, .03, scale(base, 1.05))F.ell(-.45, .36, .07, .07, tail)F.cap(.22, .6, -.02, .86 + el * .6, .05, base)F.cap(.2, .64, .02, .83 + el * .6, .022, inner, lit=False)F.dot(.35, .58, .022, EYE)F.ell(.45, .52, .022, .018, inner)motion_marks(F, -.75, (.5, .36, .24), .15)return# far ear (laid slightly back)F.cap(.17, .58, .05, .92 + el, .045, scale(base, .75))# body: big round haunch + chest + head as one mass41 unmodified linespat = chain(fur(F, .12, 7), under, stripes) if not lion else chain(fur(F, .14, 7), under)lpat = legstripes if not lion else Nonefar = scale(base, .7)run = start_run(F, inst)# tail: long, low, curling up at the endtpts = [(-.52, .6), (-.64, .5), (-.74, .4), (-.83, .38), (-.87, .45)]if run:tpts = [(-.52, .6), (-.66, .6), (-.8, .62), (-.92, .66), (-.98, .72)]F.taper(tpts, .028, .022, base, stripes if not lion else None)tip = tpts[-1]if lion:F.ell(tip[0] - .005, tip[1] + .02, .03, .045, (90, 52, 28)) # rule: lion tail ends in a dark tuftelse:F.ell(tip[0], tip[1] + .01, .026, .03, dark)# far legsif run:gallop(F, (.3, .48), .06, .042, far, True, False, pattern=lpat, paw=far)gallop(F, (-.36, .5), .068, .042, far, False, False, pattern=lpat, paw=far)else:F.leg((.3, .48), (.31, .22), .33, .06, .042, far, pattern=lpat)F.leg((-.36, .5), (-.43, .24), -.37, .068, .042, far, pattern=lpat)F.ell(.36, .03, .065, .03, far)F.ell(-.34, .03, .065, .03, far)# body# rule: heavy shoulders and a slightly sagging belly line give the big-cat massF.blob([("e", -.34, .57, .17, .17), ("c", -.34, .58, .25, .6, .16), ("e", .27, .6, .16, .19),23 unmodified linesif not lion:F.ell(.6, .79, .03, .012, WHITE, rot=.2, lit=False)# near legsif run:gallop(F, (.33, .48), .062, .044, base, True, True, pattern=lpat, paw=belly if not lion else base)gallop(F, (-.3, .5), .07, .044, base, False, True, pattern=lpat, paw=belly if not lion else base)motion_marks(F, -1.0, (.7, .55, .4), .07)returnF.leg((.33, .48), (.34, .22), .37, .062, .044, base, pattern=lpat)F.leg((-.3, .5), (-.36, .24), -.31, .07, .044, base, pattern=lpat)F.ell(.4, .03, .068, .032, belly if not lion else base)239 unmodified linespat = fur(F, .2, 21)far = scale(base, .7)k = 1.25 if gorilla else 1.0import os as _oshang = (getattr(inst, "attach_kind", None) == "hang" or inst.pose == "hanging") and \dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv).get("hang2", "1") != "0"if hang:# rule (night, hang2): hanging from a limb = both long arms straight up gripping the top of the box (where the# limb is), the body dangling below, legs hanging, a monkey's tail curling down (it sat in mid-air)if not ape:F.taper([(-.06, .28), (-.14, .16), (-.12, .05), (-.04, .03), (.0, .08)], .03, .026, base, pat)F.taper([(-.08, .6), (-.11, .8), (-.1, .98)], .055 * k, .045 * k, far)F.ell(-.1, .985, .045 * k, .03, face if not gorilla else scale(base, .7))F.blob([("e", .0, .4, .15 * k, .22), ("e", .02, .58, .15 * k, .12)], base, pat)for du, c_ in ((-.05, far), (.06, base)):F.taper([(du, .24), (du + .01, .12), (du + .02, .04)], .055 * k, .045 * k, c_, pat)F.ell(du + .04, .03, .05, .03, face if not gorilla else scale(base, .8))if gorilla:F.ell(.02, .45, .11, .13, scale(base, 1.25), pattern=pat)hu, hv = .06, .74# tail (rule: only monkeys have a long tail curling up behind; apes have none)if not ape and not hang:F.taper([(-.18, .18), (-.34, .12), (-.46, .2), (-.48, .38), (-.4, .5), (-.32, .44)], .035, .028, base, pat)if not hang:# far arm, long, hand on the groundF.taper([(.0, .58), (.14, .36), (.2, .06)], .06 * k, .045 * k, far)# body: pear, leaning forward; folded legs with knees forwardF.blob([("e", -.04, .36, .2 * k, .26), ("e", .02, .56, .17 * k, .14), ("e", .1, .2, .17, .1)], base, pat)F.ell(.17, .06, .1, .045, face if not gorilla else scale(base, .8)) # footif gorilla:F.ell(.03, .42, .13, .14, scale(base, 1.25), pattern=pat) # chest# headhu, hv = .12, .74F.ell(hu - .02, hv, .15, .14, base, pattern=pat)if gorilla:F.ell(hu - .06, hv + .1, .1, .07, base, pattern=pat) # rule: gorilla crest + heavy brow10 unmodified linesF.dot(hu + .14, hv + .03, .014, EYE)F.cap(hu + .1, hv - .08, hu + .17, hv - .075, .006, scale(face, .5), lit=False)# near armif hang:F.taper([(.12, .6), (.16, .8), (.16, .98)], .06 * k, .05 * k, base, pat)F.ell(.16, .985, .05 * k, .032, face if not gorilla else scale(base, .7))returnF.taper([(.04, .56), (.2, .36), (.26, .06)], .065 * k, .05 * k, base, pat)F.ell(.28, .04, .05 * k, .035, face if not gorilla else scale(base, .7))137 unmodified linesif v > .5 and -.38 < u < .22 and noise(u * 20, v * 20, 9) > .62:return (245, 240, 230)return brun = start_run(F, inst)# white tail flagF.ell(-.38, .54 + (.04 if run else 0), .03, .045, (245, 240, 232))# far legs: long and thinif run:gallop(F, (.22, .42), .04, .022, far, True, False, HOOF)gallop(F, (-.3, .45), .048, .022, far, False, False, HOOF)else:F.leg((.22, .42), (.24, .2), .25, .04, .022, far, HOOF, .025)F.leg((-.3, .45), (-.36, .22), -.31, .048, .022, far, HOOF, .025)# body + neck + head (rule: the head sits low enough that big antlers fit above it)F.blob([("e", -.27, .5, .13, .12), ("c", -.27, .5, .2, .5, .11), ("e", .2, .52, .12, .13),("c", .22, .55, .34, .7, .06), ("e", .36, .72, .065, .055)], base, pat)15 unmodified lines((.275, .92), (.35 * A, .97)), ((.28, .9), (.2, .97))):F.cap(bu + du, bv, tu + du, tv, .01, c)# near legsif run:gallop(F, (.24, .42), .042, .023, base, True, True, HOOF)gallop(F, (-.26, .45), .05, .023, base, False, True, HOOF)motion_marks(F, -.5, (.6, .48, .36), .07)returnF.leg((.24, .42), (.26, .2), .28, .042, .023, base, HOOF, .025)F.leg((-.26, .45), (-.31, .22), -.26, .05, .023, base, HOOF, .025)382 unmodified linesF.dot(.22, .87, .014, EYE)for du, sh in ((-.04, .8), (0, 1.0)):F.ell(.15 + du, .96, .025, .06, scale(base, sh), rot=.2)joey = getattr(inst, "joey", False)if not joey:F.taper([(.13, .62), (.22, .55), (.26, .5)], .03, .02, scale(base, .9)) # small armF.ell(-.04, .24, .13, .17, base, rot=.4, pattern=pat) # near thighF.taper([(-.04, .14), (.02, .05)], .05, .04, base)F.ell(.08, .03, .2, .035, base)if joey:# (night characters 3, pouch): the joey's head, ears and paws poke out over the pouch rim on the belly; the# mother's small arm rests round itjb = mix(base, (250, 236, 210), .42)F.ell(.17, .46, .1, .045, scale(base, .5)) # pouch opening (dark)F.ell(.19, .66, .022, .06, scale(jb, .75), rot=.35) # far earF.blob([("e", .25, .555, .085, .075), ("e", .32, .54, .05, .04)], jb) # joey head + snout, out past the chestF.ell(.225, .67, .023, .062, jb, rot=.2) # near earF.dot(.365, .545, .014, (30, 22, 20))F.dot(.275, .575, .015, EYE)F.ell(.29, .475, .024, .018, jb) # paws on the rimF.ell(.15, .425, .14, .06, scale(belly, .92), pattern=pat) # pouch front, below the rimF.taper([(.13, .62), (.2, .56), (.22, .5)], .03, .02, scale(base, .9)) # mother's arm round it# ---------------------------------------------------------------- koala (sitting, front)
1 unmodified line2345678197 unmodified lines20620720820921021121221321421521621721821922014 unmodified lines235236237238239240565 unmodified lines8068078088098108111 unmodified lineSame convention as animals.py: a local side-view Frame (u forward toward the head, v up from the ground, both inunits of inst.h) so every recipe works at any size and mirrors with inst.facing."""from ..kit import *from .animals import Frame, fur, EYE, HOOF, IVORYfrom .animals2 import on_water, clip_above, ripple, body_belly, chain, WHITE, BLACK, CREAM, PINKTAN = (214, 186, 140)197 unmodified linesT = 1.35 if snow else 1.0 # rule: snow leopards carry a thick long tailhr0 = .095 if cheetah else (.13 if jaguar else .125)fit(F, -.94, .68 if cheetah else .73, .42 * L + .32 + hr0 * .9 + .03)# tail: long, low, curling up; dark tipF.taper([(-.5, .6), (-.64, .5), (-.74, .38), (-.84, .32), (-.9, .38)], .028 * T, .026 * T, base, spots)F.ell(-.9, .4, .026 * T, .03 * T, dark)if cheetah:F.ell(-.88, .34, .03, .02, (245, 240, 230)) # rule: cheetah tail ends in a white tip after dark ringslv = .42 * L# far legsF.leg((.3, lv), (.31, .22 * L), .33, .055, .038, far, pattern=farpat)F.leg((-.36, lv + .02), (-.43, .24 * L), -.37, .062, .038, far, pattern=farpat)# body: lean in the cheetah, heavy in the jaguark = 1.0 if cheetah else (1.3 if jaguar else 1.22) # rule: a deep chest keeps the cat from looking stick-likeby = lv + .114 unmodified lines# rule: black "tear lines" from the eye to the mouth mark a cheetahF.cap(.575 + hx, hy + .015, .6 + hx, hy - .08, .011, dark, lit=False)# near legsF.leg((.33, lv), (.34, .22 * L), .37, .058, .04, base, pattern=spots)F.leg((-.3, lv + .02), (-.36, .24 * L), -.31, .065, .04, base, pattern=spots)F.ell(.4, .03, .06, .03, belly)565 unmodified linesF.ell(.37, .26, .03, .03, base)F.ell(-.45, .2, .06, .04, scale(base, .8), rot=.8) # feet upF.ell(-.55, .14, .05, .035, scale(base, .8), rot=.6)_ripple(cv, ctx, inst, F.P(0, 0)[0], inst.y, inst.w * .44)returnfit(F, -.92, .58, .56)1 unmodified line2345678197 unmodified lines20620720820921021121221321421521621721821922022122222322422522622722822914 unmodified lines244245246247248249250251252253254565 unmodified lines8208218228238248258268278288298308318321 unmodified lineSame convention as animals.py: a local side-view Frame (u forward toward the head, v up from the ground, both inunits of inst.h) so every recipe works at any size and mirrors with inst.facing."""from ..kit import *from .animals import Frame, fur, EYE, HOOF, IVORY, start_run, gallop, motion_marksfrom .animals2 import on_water, clip_above, ripple, body_belly, chain, WHITE, BLACK, CREAM, PINKTAN = (214, 186, 140)197 unmodified linesT = 1.35 if snow else 1.0 # rule: snow leopards carry a thick long tailhr0 = .095 if cheetah else (.13 if jaguar else .125)fit(F, -.94, .68 if cheetah else .73, .42 * L + .32 + hr0 * .9 + .03)run = start_run(F, inst)# tail: long, low, curling up; dark tipif run: # streaming out straight behindF.taper([(-.5, .6), (-.64, .61), (-.78, .63), (-.9, .66), (-.98, .7)], .028 * T, .026 * T, base, spots)F.ell(-.98, .71, .026 * T, .03 * T, dark)else:F.taper([(-.5, .6), (-.64, .5), (-.74, .38), (-.84, .32), (-.9, .38)], .028 * T, .026 * T, base, spots)F.ell(-.9, .4, .026 * T, .03 * T, dark)if cheetah and not run:F.ell(-.88, .34, .03, .02, (245, 240, 230)) # rule: cheetah tail ends in a white tip after dark ringslv = .42 * L# far legsif run:gallop(F, (.3, lv), .055, .038, far, True, False, pattern=farpat, paw=far)gallop(F, (-.36, lv + .02), .062, .038, far, False, False, pattern=farpat, paw=far)else:F.leg((.3, lv), (.31, .22 * L), .33, .055, .038, far, pattern=farpat)F.leg((-.36, lv + .02), (-.43, .24 * L), -.37, .062, .038, far, pattern=farpat)# body: lean in the cheetah, heavy in the jaguark = 1.0 if cheetah else (1.3 if jaguar else 1.22) # rule: a deep chest keeps the cat from looking stick-likeby = lv + .114 unmodified lines# rule: black "tear lines" from the eye to the mouth mark a cheetahF.cap(.575 + hx, hy + .015, .6 + hx, hy - .08, .011, dark, lit=False)# near legsif run:gallop(F, (.33, lv), .058, .04, base, True, True, pattern=spots, paw=belly)gallop(F, (-.3, lv + .02), .065, .04, base, False, True, pattern=spots, paw=belly)motion_marks(F, -1.0, (.7, .55, .4), .07)returnF.leg((.33, lv), (.34, .22 * L), .37, .058, .04, base, pattern=spots)F.leg((-.3, lv + .02), (-.36, .24 * L), -.31, .065, .04, base, pattern=spots)F.ell(.4, .03, .06, .03, belly)565 unmodified linesF.ell(.37, .26, .03, .03, base)F.ell(-.45, .2, .06, .04, scale(base, .8), rot=.8) # feet upF.ell(-.55, .14, .05, .035, scale(base, .8), rot=.6)pt_ = getattr(inst, "paw_to", None)if pt_ is not None and hasattr(pt_, "x"):# (night characters 3, otterhands): the near paw reaches out to the partner's, meeting between the headspx_, py_ = F.P(.22, .22)mx_ = (inst.x + pt_.x) / 2cv.capsule(px_, py_, mx_, py_ - inst.h * .06, max(.7, inst.h * .045), scale(base, .9))cv.ellipse(mx_, py_ - inst.h * .06, max(.8, inst.h * .05), max(.8, inst.h * .045), scale(base, .75))_ripple(cv, ctx, inst, F.P(0, 0)[0], inst.y, inst.w * .44)returnfit(F, -.92, .58, .56)
103 unmodified lines10410510610710810912 unmodified lines12212312412512612712812913013113213313413513666 unmodified lines20320420520620720817 unmodified lines2262272282292302314 unmodified lines23623723823924024118 unmodified lines26026126226326426526610 unmodified lines27727827928028128220 unmodified lines30330430530630730830922 unmodified lines3323333343353363373384 unmodified lines343344345346347348135 unmodified lines48448548648748848923 unmodified lines51351451551651751851933 unmodified lines5535545555565575585 unmodified lines5645655665675685695705715725735745755763 unmodified lines580581582583584585103 unmodified lines]def quad(cv, ctx, inst, P):"""Side-view dog/cat: one soft body blob (haunch, barrel, chest, neck, head, snout) on two-segment legs."""cat = P.get("cat", False)12 unmodified lineshu = bl + (.12 if not cat else .1) + (.02 if P.get("puppy") else 0)hv = vb + bt + (.17 if not cat else .13) + (-.02 if P.get("puppy") else 0)tu, tv = -bl - bt * .75, vb + bt * .45 # tail rooteh = P.get("ear_h", .2 if cat else .1)# rule: auto-fit: the skeleton is measured and scaled so ears, tail and nose stay inside the boxtop = max(hv + hr + (eh if P["ears"] in ("up", "cat") else .02), tv + (.42 if cat else .3))front = hu + max(sn + snr, hr)back = -tu + (.22 if P["tail"] in ("wag", "plume", "thin") else .12 if cat else .08)half = inst.w / inst.h / 2 * .97fit = min(1.0, 1.0 / top, half * 2 / (front + back))F.s = inst.h * P["sc"] * fitF.x = inst.x - F.f * (front - back) / 2 * F.s # rule: centre the measured silhouette in the boxfz = .14 if marks != "poodle" else .3def furp(px, py, b):66 unmodified lines# --- tail (behind everything)tail = P["tail"]tcol = baseif tail == "wag":F.taper([(tu, tv), (tu - .08, tv + .1), (tu - .13, tv + .2), (tu - .14, tv + .27)], .035, .022, tcol, pattern)17 unmodified linesF.ell(tu + .02, tv + .02, .04, .035, base, pattern=pattern)elif tail == "stub_up":F.taper([(tu + .02, tv), (tu - .01, tv + .1), (tu - .02, tv + .15)], .035, .025, base, pattern)elif tail == "cat":# rule: a cat holds its tail high with a question-mark hook at the tipk = 1.0 if not P.get("puppy") else .754 unmodified lines# --- legs: (hip, knee, foot_u) far pair first (darker), near pair after the bodydef legs(du, col, near):r = lr * (1 if near else .95)# hind leg: thigh back-down to the hock, then down to the pawF.leg((-bl + .02 + du, vb - .02), (-bl - .05 + du, lg * .45), -bl - .01 + du, r * 1.35, r * .9, col,pattern=legpat if near else None)18 unmodified linesparts = [("e", -bl, vb + .02, bt * .98, bt * .95), ("c", -bl + .02, vb + bt * .2, bl * .2, vb + bt * .05, bt * .75),("e", bl * .3, vb - bt * .05, bl * .75, bt * .95), ("e", bl, vb, bt * 1.08 * ck, bt * 1.12 * ck),("c", bl + .02, vb + .05, hu - .02, hv - .04, nr), ("e", hu, hv, hr * 1.04, hr * .96)]if marks == "poodle":parts[0] = ("e", -bl, vb + .01, bt * 1.0, bt * .9)if sn > 0:parts.append(("c", hu + .02, hv - hr * .35, hu + sn, hv - hr * .4, snr))10 unmodified lines# --- earsears = P["ears"]if ears in ("up", "cat"):for k, sh in ((-1, .78), (1, 1.0)):o = hr * (.38 if k < 0 else 0) * -120 unmodified lines# --- faceeye = P.get("eye", (60, 36, 20))ex, ey = hu + hr * .4, hv + hr * .22if cat:er = .028 if P.get("puppy") else .022glow = ctx.time == "night"ec = (215, 255, 120) if glow else (eye if inst.color != "black" else (232, 200, 50))22 unmodified lines# --- collar (rule: pet dogs wear a red collar; red dogs get a blue one so it still reads)if P.get("collar") and not cat:cc = (205, 40, 50) if inst.color not in ("red", "pink", "orange") else (40, 90, 200)a = (bl + .02, vb + .05)bpt = (hu - .02, hv - .04)t = .42mx, my = a[0] + (bpt[0] - a[0]) * t, a[1] + (bpt[1] - a[1]) * t4 unmodified linesF.dot(mx + qx * .9 + .01, my + qy * .9 - .025, .016, (235, 195, 60))# --- near legslegs(0, base, True)def draw_dog(cv, ctx, inst):135 unmodified linestrunk = hazed(ctx, inst, {"birch": (236, 232, 222), "cherry": (88, 60, 56)}.get(kind, (104, 70, 44)), .9)seed = inst.k * 7 + 3snow = ctx.place == "snow"def leafpat(px, py, b):u, v = F.uv(px, py)23 unmodified linesreturn breturn scale(b, .88 + .2 * fbm(u * 40, v * 6, seed + 6))# --- trunk + branchesif kind == "birch":F.taper([(0, 0), (.005, .3), (-.01, .6), (0, .8)], .042, .026, trunk, barkpat)F.taper([(.0, .02), (.06, .3), (.1, .55)], .026, .016, trunk, barkpat) # rule: birches grow in clumpselif kind == "willow":33 unmodified lineslobes = crown(0, .68, .27, .2, 10, .36)else:lobes = crown(0, .64, .25, .25, 10, .38)lobes = [(p[0], j(p[1]) if p[0] == "e" else p[1], p[2], j(p[3]), j(p[4]), *p[5:]) if p[0] == "e" else pfor p in lobes]# rule: clamp the canopy inside the box width5 unmodified linesfor i in range(14):u = -.3 + .6 * i / 13F.cap(u, .6, u * 1.03, .25 + .08 * abs(math.sin(i * 2.1)), .006, strand, lit=False, alpha=.7)if kind == "apple":# rule: apple tree = round canopy dotted with red apples (a couple fallen on the grass)for i in range(9):a, r = rng.uniform(0, 2 * math.pi), math.sqrt(rng.random())F.dot(math.cos(a) * r * .25, .7 + math.sin(a) * r * .17, .022, (215, 35, 35))F.dot(.14, .015, .02, (200, 35, 35))F.dot(-.1, .012, .02, (200, 35, 35))if kind == "cherry" and not snow:for i in range(10): # falling petalsF.ell(rng.uniform(-.35, .35), rng.uniform(.02, .5), .012, .008, mix(leaf, WHITE, .3), lit=False)3 unmodified linesF.ell(p[1], p[2] + p[4] * .62, p[3] * .7, p[4] * .32, (242, 246, 252), lit=False, alpha=.92)def draw_pine(cv, ctx, inst):"""Conifer: stacked drooping tiers, light/shade split down the middle; christmas trees get a star and lights."""L, h, x, y, rng = ctx.L, inst.h, inst.x, inst.y, inst.rng103 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512612712812913013112 unmodified lines14414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218366 unmodified lines25025125225325425525625717 unmodified lines2752762772782792802812822832842852862872882892902912922934 unmodified lines29829930030130230330430530630730830931031131231331431531631731831932032118 unmodified lines34034134234334434534634734834935010 unmodified lines36136236336436536636736820 unmodified lines38939039139239339439539639739839940040140240340440540622 unmodified lines4294304314324334344354 unmodified lines440441442443444445446447448449450451452453454455456457458459135 unmodified lines59559659759859960060160260360460560660760860961061161261361423 unmodified lines63863964064164264364464564633 unmodified lines6806816826836846856866876886895 unmodified lines6956966976986997007017027037047057067077087093 unmodified lines713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748103 unmodified lines]def _night_on(name):"""night-wave knob (PYDRAW_EXP name=0 turns the rule off)"""import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get(name, "1") != "0"def zzz(F, u, v, night=False, k=1.0):"""rule (night, sleep2): sleep reads from a trail of z's rising from the head, small to big (a comic convention)"""c = (70, 60, 120) if not night else (225, 225, 245)for i, (du, dv, r) in enumerate(((0, 0, .035), (-.06, .08, .05), (-.14, .19, .068))):r *= ka, b = F.P(u + du * k - r, v + dv * k + r)c2, d2 = F.P(u + du * k + r, v + dv * k + r)e, g = F.P(u + du * k - r, v + dv * k - r)h2, i2 = F.P(u + du * k + r, v + dv * k - r)w = max(.5, r * F.s * .28)F.cv.capsule(a, b, c2, d2, w, c)F.cv.capsule(c2, d2, e, g, w, c)F.cv.capsule(e, g, h2, i2, w, c)def quad(cv, ctx, inst, P):"""Side-view dog/cat: one soft body blob (haunch, barrel, chest, neck, head, snout) on two-segment legs."""cat = P.get("cat", False)12 unmodified lineshu = bl + (.12 if not cat else .1) + (.02 if P.get("puppy") else 0)hv = vb + bt + (.17 if not cat else .13) + (-.02 if P.get("puppy") else 0)tu, tv = -bl - bt * .75, vb + bt * .45 # tail rootasleep = inst.pose == "sleeping" and _night_on("sleep2")if asleep:# rule (night, sleep2): a sleeping dog / cat rests its head low and forward on its paws (it used to lie with# its head up, eyes open - "awake")hu, hv = bl + hr * .9 + .05, vb + bt * .15sit = inst.pose == "sitting" and _night_on("sit2") and not asleepif sit:# rule (night characters 2, sit2): a sitting dog / cat in side view - haunch down on the ground, chest up on# straight front legs, head high, tail laid along the ground (it used to stand, or became a front-facing# sit character that lost the sleek profile: "a black cat sitting on a fence")Hu, Hv = -bl * .42, bt * 1.2Cu, Cv = bl * .38, lg + bt * .55hu, hv = Cu + hr * .55 + (.02 if not cat else 0), lg + bt * 2.0 + (.08 if cat else .1)tu, tv = Hu - bt * .9, bt * .6vb = bt * .7 # belly / stripe bands of the coat pattern follow the low hauncheh = P.get("ear_h", .2 if cat else .1)# rule: auto-fit: the skeleton is measured and scaled so ears, tail and nose stay inside the boxtop = max(hv + hr + (eh if P["ears"] in ("up", "cat") else .02), tv + (.42 if cat else .3))front = hu + max(sn + snr, hr)back = -tu + (.22 if P["tail"] in ("wag", "plume", "thin") else .12 if cat else .08)if sit:top = hv + hr + (eh if P["ears"] in ("up", "cat") else .02)back = -Hu + bt * 1.3 + (.12 if cat else .1)run = inst.pose in ("running", "jumping") and _night_on("run2")if run:# rule (night, run2): a running dog / cat is drawn in the flying gallop - front legs reaching forward, hind# legs stretched back, all four off the ground - so its box must hold the longer silhouettefront, back = front + .16, back + .2half = inst.w / inst.h / 2 * .97fit = min(1.0, 1.0 / top, half * 2 / (front + back))F.s = inst.h * P["sc"] * fitF.x = inst.x - F.f * (front - back) / 2 * F.s # rule: centre the measured silhouette in the boxif run:F.y -= lg * (.22 if inst.pose == "running" else .7) * F.s # airborne: the shadow stays on the ground belowfz = .14 if marks != "poodle" else .3def furp(px, py, b):66 unmodified lines# --- tail (behind everything)tail = P["tail"]if "tail" in ((getattr(inst, "attrs", None) or {}).get("absent") or ()):tail = None # night wave (language): "a cat with no tail" (attrs from pydraw/language.py)tcol = baseif tail == "wag":F.taper([(tu, tv), (tu - .08, tv + .1), (tu - .13, tv + .2), (tu - .14, tv + .27)], .035, .022, tcol, pattern)17 unmodified linesF.ell(tu + .02, tv + .02, .04, .035, base, pattern=pattern)elif tail == "stub_up":F.taper([(tu + .02, tv), (tu - .01, tv + .1), (tu - .02, tv + .15)], .035, .025, base, pattern)elif sit and tail != "curl":# sitting: the tail lies along the ground; a cat's curls forward round the pawsif cat:F.taper([(tu + .04, tv + .02), (tu - .06, tv - .04), (tu - .04, .025), (tu + .08, .018), (Cu + .02, .02)],.03, .026, base, pattern)elif tail in ("stub", "stub_up", "pom"):F.ell(tu + .02, tv, .04, .035, base, pattern=pattern)else:F.taper([(tu + .04, tv + .02), (tu - .08, tv - .02), (tu - .17, .03)], .034, .024, base, pattern)elif tail == "cat" and asleep:F.taper([(tu + .02, tv - .02), (tu - .12, tv - .07), (tu - .24, tv - .08), (tu - .31, tv - .03)], .032, .026, base, pattern)elif tail == "cat" and run:F.taper([(tu + .02, tv - .02), (tu - .1, tv + .04), (tu - .2, tv + .1), (tu - .29, tv + .17)], .032, .026, base, pattern)elif tail == "cat":# rule: a cat holds its tail high with a question-mark hook at the tipk = 1.0 if not P.get("puppy") else .754 unmodified lines# --- legs: (hip, knee, foot_u) far pair first (darker), near pair after the bodydef legs(du, col, near):r = lr * (1 if near else .95)if sit:fu = Cu + .03 + du * .6F.cap(Cu + du * .6, Cv - bt * .4, fu, .04, r * 1.1, col, legpat if near else None)pc = WHITE if (near and sock_h > 0) else colF.ell(fu + .022, .022, r * 1.3, .024, pc if near else scale(pc, .9))if near: # the hind paw peeks out in front of the haunchF.ell(Hu + bt * .9, .024, r * 1.4, .026, scale(base, .92))returnif run:ph = 0 if near else .05 # the far pair a beat behindhind = [(-bl + .02 + du, vb - .02), (-bl - .1 + du - ph, lg * .62), (-bl - .3 + du + ph, lg * .3)]fore = [(bl - .01 + du, vb - .03), (bl + .14 + du - ph, lg * .58), (bl + .3 + du - ph * 2, lg * .45)]for (h_, k_, f_), r0 in ((hind, r * 1.35), (fore, r * 1.15)):F.cap(h_[0], h_[1], k_[0], k_[1], r0, col, legpat if near else None)F.cap(k_[0], k_[1], f_[0], f_[1], r * .9, col, legpat if near else None)pc = WHITE if (near and sock_h > 0) else colF.ell(f_[0] + (.012 if f_ is fore[2] else -.012), f_[1], r * 1.25, r * 1.0, pc if near else scale(pc, .9))return# hind leg: thigh back-down to the hock, then down to the pawF.leg((-bl + .02 + du, vb - .02), (-bl - .05 + du, lg * .45), -bl - .01 + du, r * 1.35, r * .9, col,pattern=legpat if near else None)18 unmodified linesparts = [("e", -bl, vb + .02, bt * .98, bt * .95), ("c", -bl + .02, vb + bt * .2, bl * .2, vb + bt * .05, bt * .75),("e", bl * .3, vb - bt * .05, bl * .75, bt * .95), ("e", bl, vb, bt * 1.08 * ck, bt * 1.12 * ck),("c", bl + .02, vb + .05, hu - .02, hv - .04, nr), ("e", hu, hv, hr * 1.04, hr * .96)]if sit:parts = [("e", Hu, Hv, bt * 1.25, bt * 1.2), ("c", Hu + .02, Hv + .03, Cu, Cv, bt * .88),("e", Cu, Cv, bt * .95 * ck, bt * 1.12 * ck), ("c", Cu + .01, Cv + .04, hu - .02, hv - .04, nr),("e", hu, hv, hr * 1.04, hr * .96)]if marks == "poodle" and not sit:parts[0] = ("e", -bl, vb + .01, bt * 1.0, bt * .9)if sn > 0:parts.append(("c", hu + .02, hv - hr * .35, hu + sn, hv - hr * .4, snr))10 unmodified lines# --- earsears = P["ears"]if "ears" in ((getattr(inst, "attrs", None) or {}).get("absent") or ()):ears = None # night wave (language): "a dog with no ears"if ears in ("up", "cat"):for k, sh in ((-1, .78), (1, 1.0)):o = hr * (.38 if k < 0 else 0) * -120 unmodified lines# --- faceeye = P.get("eye", (60, 36, 20))ex, ey = hu + hr * .4, hv + hr * .22if asleep:# closed eye = a little downward arc, and a "z z Z" drifting up from the header = .03 if P.get("puppy") else .024F.cap(ex - er * 1.2, ey + er * .2, ex, ey - er * .35, max(.006, er * .3), EYE, lit=False)F.cap(ex, ey - er * .35, ex + er * 1.1, ey + er * .1, max(.006, er * .3), EYE, lit=False)if cat:F.dot(hu + hr * .98, hv - hr * .22, .014, PINK if inst.color != "pink" else (150, 60, 80))else:nx, ny = (hu + sn + snr * .55, hv - hr * .32) if sn > .05 else (hu + hr * 1.02 + snr * .2, hv - hr * .3)F.dot(nx, ny, max(snr * .55, .02), NOSE)zzz(F, hu - hr * .2, hv + hr * 1.3, night=ctx.time == "night")elif cat:er = .028 if P.get("puppy") else .022glow = ctx.time == "night"ec = (215, 255, 120) if glow else (eye if inst.color != "black" else (232, 200, 50))22 unmodified lines# --- collar (rule: pet dogs wear a red collar; red dogs get a blue one so it still reads)if P.get("collar") and not cat:cc = (205, 40, 50) if inst.color not in ("red", "pink", "orange") else (40, 90, 200)a = (bl + .02, vb + .05) if not sit else (Cu + .01, Cv + .04)bpt = (hu - .02, hv - .04)t = .42mx, my = a[0] + (bpt[0] - a[0]) * t, a[1] + (bpt[1] - a[1]) * t4 unmodified linesF.dot(mx + qx * .9 + .01, my + qy * .9 - .025, .016, (235, 195, 60))# --- near legslegs(0, base, True)if getattr(inst, "holding", None) and _night_on("mouth2"):# rule (night): a dog / cat holds things in its MOUTH - report the mouth as the "hand" so the held thing# (a leash, a bone, a stick) is drawn there instead of floating in front of the chestinst.hand = F.P(hu + hr * .7 + (sn * .7 if sn > .05 else hr * .2), hv - hr * .62)if run:# rule (night, run2): speed lines streak behind a runner and dust puffs where its feet left the groundsl = mix(ctx.sky_col if hasattr(ctx, "sky_col") else (240, 240, 235), WHITE, .5)for k, dv in enumerate((bt * .6, 0, -bt * .55)):u0 = -bl - bt - .06 - .03 * kF.cap(u0, vb + dv, u0 - .22 + .05 * (k % 2), vb + dv, max(.008, .55 * F.px / F.s), sl, lit=False, alpha=.75)dust = (214, 200, 172)for k, (du_, r_) in enumerate(((-.42, .05), (-.55, .04), (-.66, .028))):X, Y = F.P(-bl + du_, 0)cv.ellipse(X, Y + lg * .22 * F.s - r_ * F.s * .5, r_ * F.s * 1.3, r_ * F.s, dust, 0, .8)def draw_dog(cv, ctx, inst):135 unmodified linestrunk = hazed(ctx, inst, {"birch": (236, 232, 222), "cherry": (88, 60, 56)}.get(kind, (104, 70, 44)), .9)seed = inst.k * 7 + 3snow = ctx.place == "snow"_at = getattr(inst, "attrs", None) or {}# night wave (language): "a gnarled oak" = crooked thick trunk + lumpy broken canopy; "a tree without leaves" /# "a dead / withered tree" = bare branches (attrs from pydraw/language.py; PYDRAW_LANG_OFF=tree turns this off)from ..language import on as _lang_ongnarled = "twisted" in _at.get("cond", ()) and _lang_on("tree")bare = ("leaves" in _at.get("absent", ()) or "branches" not in _at.get("absent", ()) and ("withered" in _at.get("cond", ()) or "bare" in _at.get("cond", ()))) \and _lang_on("tree")if gnarled or bare:_crooked_tree(F, rng, inst, trunk, gnarled, bare, leaf, seed)if bare:returngnarled_canopy = Trueelse:gnarled_canopy = Falsedef leafpat(px, py, b):u, v = F.uv(px, py)23 unmodified linesreturn breturn scale(b, .88 + .2 * fbm(u * 40, v * 6, seed + 6))# --- trunk + branchesif gnarled_canopy:pass # trunk and limbs already drawn by _crooked_treeelif kind == "birch":F.taper([(0, 0), (.005, .3), (-.01, .6), (0, .8)], .042, .026, trunk, barkpat)F.taper([(.0, .02), (.06, .3), (.1, .55)], .026, .016, trunk, barkpat) # rule: birches grow in clumpselif kind == "willow":33 unmodified lineslobes = crown(0, .68, .27, .2, 10, .36)else:lobes = crown(0, .64, .25, .25, 10, .38)if gnarled_canopy:# rule: an old gnarled tree's crown is broken into separate clumps on the ends of its limbslobes = [("e", u_, v_, r_, r_ * .8) for u_, v_, r_ in ((-.2, .66, .13), (.17, .72, .14), (-.02, .84, .12),(.26, .58, .09), (-.3, .56, .08))]lobes = [(p[0], j(p[1]) if p[0] == "e" else p[1], p[2], j(p[3]), j(p[4]), *p[5:]) if p[0] == "e" else pfor p in lobes]# rule: clamp the canopy inside the box width5 unmodified linesfor i in range(14):u = -.3 + .6 * i / 13F.cap(u, .6, u * 1.03, .25 + .08 * abs(math.sin(i * 2.1)), .006, strand, lit=False, alpha=.7)fruit = _at.get("fruit") # night wave (language): "a plum / lemon / pear tree" carries that fruitif kind == "apple" or fruit:# rule: apple tree = round canopy dotted with red apples (a couple fallen on the grass)fc = tuple(fruit) if fruit else (215, 35, 35)for i in range(9):a, r = rng.uniform(0, 2 * math.pi), math.sqrt(rng.random())F.dot(math.cos(a) * r * .25, .7 + math.sin(a) * r * .17, .022, fc)F.dot(.14, .015, .02, scale(fc, .92))F.dot(-.1, .012, .02, scale(fc, .92))if kind == "cherry" and not snow:for i in range(10): # falling petalsF.ell(rng.uniform(-.35, .35), rng.uniform(.02, .5), .012, .008, mix(leaf, WHITE, .3), lit=False)3 unmodified linesF.ell(p[1], p[2] + p[4] * .62, p[3] * .7, p[4] * .32, (242, 246, 252), lit=False, alpha=.92)def _crooked_tree(F, rng, inst, trunk, gnarled, bare, leaf, seed):"""crooked trunk with knots and bent limbs (gnarled), or a full bare branch skeleton (no leaves)"""import math as _mw0 = .085 if gnarled else .06sway = (1 if inst.k % 2 else -1)pts = [(0, 0), (.04 * sway, .12), (-.035 * sway, .26), (.03 * sway, .4), (-.01 * sway, .52)] if gnarled else \[(0, 0), (.005, .2), (-.01, .4), (0, .5)]F.taper(pts, w0, w0 * .6, trunk)F.ell(0, .02, w0 * 1.5, .025, trunk) # flared rootsif gnarled:for v_ in (.18, .34): # knotsF.ell(.02 * sway, v_, .022, .028, scale(trunk, .65), lit=False)def limb(u, v, ang, ln, r, depth):# rule: each limb bends a little and forks in two, thinner each timepts_ = [(u, v)]for _ in range(3):ang += rng.uniform(-.35, .35) if gnarled else rng.uniform(-.15, .15)u, v = u + _m.cos(ang) * ln / 3, v + _m.sin(ang) * ln / 3pts_.append((u, v))F.taper(pts_, r, r * .7, trunk)if depth > 0:for d_ in (-1, 1):limb(u, v, ang + d_ * rng.uniform(.35, .7), ln * .68, r * .62, depth - 1)top = pts[-1]depth = 3 if bare else 1for ang, ln in ((1.15, .24), (1.95, .24), (1.55, .3)) if bare else ((.75, .22), (2.4, .2)):limb(top[0], top[1], ang, ln, w0 * .55, depth)def draw_pine(cv, ctx, inst):"""Conifer: stacked drooping tiers, light/shade split down the middle; christmas trees get a star and lights."""L, h, x, y, rng = ctx.L, inst.h, inst.x, inst.y, inst.rng
919 unmodified lines92092192292392492592625 unmodified lines952953954955956957919 unmodified linescv.poly([(x - w * .48, rim_y)] + arc_pts(x, rim_y, w * .48, h * .6, 0, math.pi, 12)[::-1] + [(x + w * .48, rim_y)],lambda px, py: L.shade(c, (px - x) / w, .4, .8))cv.ellipse(x, rim_y, w * .42, h * .2, scale(c, .45))for k in range(3):ex = x + (k - 1) * w * .17lit_ellipse(cv, L, ex, rim_y - h * .1, w * .1, h * .2, egg)cv.ellipse(ex + w * .02, rim_y - h * .18, w * .02, h * .03, (220, 240, 245), alpha=.7)25 unmodified linespts = arc_pts(*P(-.1, .62), w * .2, h * .3, math.pi, 2 * math.pi, 10)chain(cv, pts, lw(cv, h * .04), scale(c, .85), L)cv.poly(quad(bx0, y - h * .1, bx1, y - h * .06), L.shade(scale(c, .75), 0, 0, 1))# ================================================================ beach and camp919 unmodified lines92092192292392492592692792892993093193293393493593693793893994094125 unmodified lines967968969970971972973974975976977978979980981982983984985986987988989990991992993919 unmodified linescv.poly([(x - w * .48, rim_y)] + arc_pts(x, rim_y, w * .48, h * .6, 0, math.pi, 12)[::-1] + [(x + w * .48, rim_y)],lambda px, py: L.shade(c, (px - x) / w, .4, .8))cv.ellipse(x, rim_y, w * .42, h * .2, scale(c, .45))nch = getattr(inst, "chicks_in", 0)if nch:# (night characters 3, nestfeed): fluffy chicks, heads up, orange beaks wide open, a worm held over themfl = (236, 214, 120)sd = getattr(inst, "feed_side", 1)for k in range(nch):ex = x + (k - (nch - 1) / 2) * w * .2ey = rim_y - h * (.25 + .12 * ((k + 1) % 2))lit_ellipse(cv, L, ex, ey + h * .12, w * .11, h * .22, scale(fl, .92))lit_ellipse(cv, L, ex, ey - h * .1, w * .1, h * .17, fl)cv.poly([(ex - w * .045, ey - h * .2), (ex + w * .045, ey - h * .2), (ex + w * .025, ey - h * .46)], (240, 130, 40))cv.poly([(ex - w * .04, ey - h * .2), (ex + w * .03, ey - h * .2), (ex - w * .035, ey - h * .4)], (205, 55, 40))cv.ellipse(ex + w * .04, ey - h * .1, max(.6, w * .012), max(.6, h * .035), (20, 16, 16))wx = x + sd * w * .3cv.capsule(wx, rim_y - h * 1.0, wx - sd * w * .06, rim_y - h * .7, lw(cv, h * .03, .5), (210, 110, 120))for k in range(3 if not nch else 0):ex = x + (k - 1) * w * .17lit_ellipse(cv, L, ex, rim_y - h * .1, w * .1, h * .2, egg)cv.ellipse(ex + w * .02, rim_y - h * .18, w * .02, h * .03, (220, 240, 245), alpha=.7)25 unmodified linespts = arc_pts(*P(-.1, .62), w * .2, h * .3, math.pi, 2 * math.pi, 10)chain(cv, pts, lw(cv, h * .04), scale(c, .85), L)cv.poly(quad(bx0, y - h * .1, bx1, y - h * .06), L.shade(scale(c, .75), 0, 0, 1))if (getattr(inst, "attrs", None) or {}).get("pour"):# rule (night characters 2, watering): a can in use sprinkles - fans of drops arc out of the rose and fall# to the plant below itdrop = (150, 205, 240)fall = h * (2.6 if getattr(inst, "held_by", None) is not None else .8)# continuous thin streams (single drops were merged away as specks by the pixel clean-up)to = getattr(inst, "pour_to", None)for i in range(4):vx = (.22 + .12 * i) * wprev = Nonefor j in range(0, 9):t = j / 8X = rx + f * vx * tY = ry + fall * t * t + h * .04if to is not None: # aimed: a ballistic arc from the rose onto the plant (spread across its top)ex, ey = to[0] + (i - 1.5) * to[2] * .18, to[1]X = rx + (ex - rx) * tY = ry + (ey - ry) * t * t - h * .25 * t * (1 - t)if prev is not None:cv.capsule(prev[0], prev[1], X, Y, lw(cv, h * .03, .6), drop)prev = (X, Y)# ================================================================ beach and camp
1012 unmodified lines1013101410151016101710182 unmodified lines10211022102310241025102610271028102910301012 unmodified lines# ---------------------------------------------------------------- small propsdef draw_balloon(cv, ctx, inst):L, x, y, w, h = ctx.L, inst.x, inst.y, inst.w, inst.hc = color_of(inst)2 unmodified linescy = y - h + ry# string: wavy, leaning toward the canvas centre so a bunch reads as tied togetherend_x = x + (cv.w / 2 - x) * .25pts = []for i in range(9):t = i / 8pts.append((x + (end_x - x) * t + math.sin(t * 9) * w * .07, cy + ry + h * .04 + (y - cy - ry - h * .04) * t))chain(cv, pts, max(.35, U(cv) * .4), (90, 90, 95))# rule: egg-shaped body (narrower at the knot) + knot + strong glossy highlight = balloonlit_ellipse(cv, L, x, cy, rx, ry, c)1012 unmodified lines1013101410151016101710181019102010211022102310242 unmodified lines102710281029103010311032103310341035103610371038103910401012 unmodified lines# ---------------------------------------------------------------- small propsdef _night_on(name):import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get(name, "1") != "0"def draw_balloon(cv, ctx, inst):L, x, y, w, h = ctx.L, inst.x, inst.y, inst.w, inst.hc = color_of(inst)2 unmodified linescy = y - h + ry# string: wavy, leaning toward the canvas centre so a bunch reads as tied togetherend_x = x + (cv.w / 2 - x) * .25end_y = yhb = getattr(inst, "bound", None)if hb is not None and getattr(inst, "held_by", None) is not None and getattr(hb, "hand", None) and _night_on("inter"):end_x, end_y = hb.hand # rule (night): a held balloon's string ends in the holder's handpts = []for i in range(9):t = i / 8pts.append((x + (end_x - x) * t + math.sin(t * 9) * w * .07 * (1 - t * .7), cy + ry + h * .04 + (end_y - cy - ry - h * .04) * t))chain(cv, pts, max(.35, U(cv) * .4), (90, 90, 95))# rule: egg-shaped body (narrower at the knot) + knot + strong glossy highlight = balloonlit_ellipse(cv, L, x, cy, rx, ry, c)
558 unmodified lines55956056156256356412 unmodified lines577578579580581582558 unmodified linesdef P(u, v): # u -1..1 across, v 0 (near) .. 1 (far)half = w * .5 * (1 - .14 * v)return (x + u * half * .94, y - h * .08 - v * h * .84)border = (235, 215, 160) if sum(c) < 500 else (70, 50, 110)inner = darker(c, .8)cv.poly([P(-1, 0), P(1, 0), P(1, 1), P(-1, 1)], L.shade(border, 0, -1, .3))12 unmodified linescv.capsule(a[0], a[1], a[0] + s * w * .03, a[1], lw(cv, h * .015, .45), (245, 240, 225))@concept("pillow", height=.3, aspect=1.4, row="front", setting="room", on_top=.8,synonyms=["cushion", "throw pillow", "bed pillow", "sofa cushion"], default_color=(235, 230, 220))def draw_pillow(cv, ctx, inst):558 unmodified lines55956056156256356456556656756856957057157257357457557657712 unmodified lines590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655558 unmodified linesdef P(u, v): # u -1..1 across, v 0 (near) .. 1 (far)half = w * .5 * (1 - .14 * v)return (x + u * half * .94, y - h * .08 - v * h * .84)if (inst.word or "").startswith("picnic"):# rule (language shift 3): a picnic blanket = gingham spread flat on the grass: crossing bands of the colour# over white, darker where two bands cross (it drew a stack of folded towels in a living room)light = (248, 246, 240)mid = tuple(int((a + b) / 2) for a, b in zip(c, light))nu, nv = 8, 6for i in range(nu):for j in range(nv):u0, u1 = -1 + 2 * i / nu, -1 + 2 * (i + 1) / nuv0, v1 = j / nv, (j + 1) / nvcol = c if (i % 2 and j % 2) else mid if (i % 2 or j % 2) else lightcv.poly([P(u0, v0), P(u1, v0), P(u1, v1), P(u0, v1)], L.shade(col, 0, -1, .3))returnborder = (235, 215, 160) if sum(c) < 500 else (70, 50, 110)inner = darker(c, .8)cv.poly([P(-1, 0), P(1, 0), P(1, 1), P(-1, 1)], L.shade(border, 0, -1, .3))12 unmodified linescv.capsule(a[0], a[1], a[0] + s * w * .03, a[1], lw(cv, h * .015, .45), (245, 240, 225))# language shift 3: a picnic blanket is its own thing (outdoors, flat gingham; 3D: cushion family kind "spread")concept("picnic blanket", height=.3, aspect=3.0, row="front", setting="field", on_top=.3,synonyms=["picnic blankets", "picnic cloth", "picnic rug"], default_color=(196, 44, 48))(draw_rug)@concept("puddle", height=.2, aspect=4.2, row="front", setting="field", on_top=.05, shadow=False,synonyms=["mud puddle", "rain puddle", "muddy puddle", "mud hole"])def draw_puddle(cv, ctx, inst):"""rule (night characters 2, puddle): a puddle is a flat lens of water on the ground in perspective - a darkerwet lip, the sky colour inside (brown when muddy), a pale glint band and two thin ripple rings round whoever standsin it; a splashing one throws a crown of drops. It used to be the open-vocab white box."""x, y, w, h = inst.x, inst.y, inst.w, inst.hmuddy = "mud" in (inst.word or "") or bool((getattr(inst, "attrs", None) or {}).get("muddy"))night = ctx.time == "night"if inst.color:water = color_of(inst)elif muddy:water = (118, 88, 58)else:water = (60, 72, 110) if night else (150, 184, 214)lip = darker(water, .55) if not muddy else (78, 58, 40)cy, rx, ry = y - h * .42, w * .5, h * .4# lip, then water a little inside it, lobed so it is not a perfect ellipsecv.ellipse(x, cy + ry * .12, rx, ry * 1.05, lip)cv.ellipse(x - rx * .35, cy - ry * .1, rx * .55, ry * .7, lip)cv.ellipse(x, cy + ry * .08, rx * .93, ry * .86, water)cv.ellipse(x - rx * .33, cy - ry * .1, rx * .5, ry * .6, water)hi = lighter(water, .35) if not night else lighter(water, .2)cv.capsule(x - rx * .55, cy - ry * .35, x - rx * .1, cy - ry * .45, lw(cv, h * .04, .5), hi)cv.capsule(x + rx * .2, cy + ry * .1, x + rx * .55, cy + ry * .05, lw(cv, h * .03, .5), hi, .7)at = getattr(inst, "attrs", None) or {}if at.get("stood_in"):for k, a in ((.28, .8), (.42, .5)): # ripple rings round the one standing in it (placed at the middle)cv.ellipse(x, cy + ry * .1, rx * k, ry * k * 1.3, hi, 0, a * .55)cv.ellipse(x, cy + ry * .1, rx * k - lw(cv, h * .04, .5), ry * k * 1.3 - lw(cv, h * .03, .5), water, 0, a * .55)if at.get("splash"):def _splash():# a crown of drops thrown up and out round the feet, drawn after the splasher so it shows in frontimport randomrng = random.Random(7)drop = mix(water, (255, 255, 255), .6) if not muddy else (150, 112, 78)for i in range(14):t = (i / 13) * 2 - 1side = 1 if t >= 0 else -1dx = side * rx * (.45 + .45 * abs(t)) * rng.uniform(.85, 1.05)dy = -(1.15 - abs(t)) * h * 1.6 * rng.uniform(.6, 1.0)r = lw(cv, h * rng.uniform(.07, .11), .7)cv.ellipse(x + dx, cy + dy, r, r * 1.3, drop)if _night_on_pud():inst.after_riders = _splashelse:_splash()def _night_on_pud():import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get("puddle", "1") != "0"@concept("pillow", height=.3, aspect=1.4, row="front", setting="room", on_top=.8,synonyms=["cushion", "throw pillow", "bed pillow", "sofa cushion"], default_color=(235, 230, 220))def draw_pillow(cv, ctx, inst):
25 unmodified lines26272829303149 unmodified lines81828384858615 unmodified lines1021031041051061075 unmodified lines11311411511611711811912012112212312412512622 unmodified lines14915015115215315422 unmodified lines177178179180181182183173 unmodified lines357358359360361362334 unmodified lines69769869970070170270370470590 unmodified lines79679779879980080180280380480574 unmodified lines88088188288388488533 unmodified lines9199209219229239249259269279288 unmodified lines9379389399409419429439449459469479489499509511 unmodified line95395495595695795895996096117 unmodified lines97998098198298398498598698798898999099117 unmodified lines10091010101110121013101410155 unmodified lines1021102210231024102510266 unmodified lines10331034103510361037103815 unmodified lines105410551056105710581059106010611062106359 unmodified lines11231124112511261127112820 unmodified lines1149115011511152115311548 unmodified lines11631164116511661167116814 unmodified lines11831184118511861187118829 unmodified lines12181219122012211222122367 unmodified lines129112921293129412951296129712981299130036 unmodified lines13371338133913401341134213431344134548 unmodified lines13941395139613971398139914001401140236 unmodified lines143914401441144214431444328 unmodified lines1773177417751776177717781779221 unmodified lines2001200220032004200520062 unmodified lines200920102011201220132014201525 unmodified lines"light": [(255, 219, 186), (241, 194, 160)]}def _named(col):"""Colour name from the parser -> rgb (None stays None)."""if not col:49 unmodified linesvest=(120, 80, 45), boots=True, shoes=(110, 65, 35), belt=True, main="top", gender="f"),"ninja": dict(top=BLACK, bottom=BLACK, sleeves=True, hat="ninja", shoes=BLACK, belt="red", main="top",hand="ninja_sword", gender="m"),"clown": dict(top=(240, 200, 40), bottom=(40, 120, 210), sleeves=True, hat="clown", face="clown", dots=True,shoes=(220, 40, 40), big_shoes=True, neck="ruff", main="top"),"farmer": dict(top=(200, 55, 50), bottom=(60, 95, 160), sleeves=False, hat="straw", overalls=True, plaid=True,15 unmodified lines"dancer": dict(top=(245, 160, 195), bottom=(250, 205, 215), sleeves=False, dress="tutu", hair="bun",arms="up", shoes=(245, 160, 195), main="top", gender="f"),}WORD_ROLE = {"chef": "chef", "cook": "chef", "baker": "chef",5 unmodified lines"king": "king", "queen": "queen", "princess": "princess", "prince": "prince","knight": "knight","wizard": "wizard", "sorcerer": "wizard", "mage": "wizard", "witch": "witch","pirate": "pirate", "cowboy": "cowboy", "cowgirl": "cowgirl", "ninja": "ninja", "clown": "clown","farmer": "farmer", "scientist": "scientist", "chemist": "scientist","businessman": "business", "businesswoman": "business", "businessperson": "business","student": "student", "schoolboy": "student", "schoolgirl": "student","athlete": "athlete", "runner": "athlete", "jogger": "athlete", "sprinter": "athlete","dancer": "dancer", "ballerina": "dancer", "ballet dancer": "dancer","politician": "business", "senator": "business", "mayor": "business","superman": "superman", "spiderman": "spiderman", "spider man": "spiderman", "batman": "batman",}# word -> (age, gender)WORD_AGE = {22 unmodified lines"businessmen": "businessman", "businesswomen": "businesswoman", "gentlemen": "gentleman","babies": "baby", "grannies": "granny", "witches": "witch", "princesses": "princess"}# rule: bare "baby" is NOT registered: it is a size word ("baby elephant") and would steal those promptsROLE_SYNONYMS = sorted((set(WORD_ROLE) | set(WORD_AGE)) - {"baby"})22 unmodified linesdef _role_age(word):w = _singular(word)role = WORD_ROLE.get(w)age, gender = WORD_AGE.get(w, ("adult", None))return w, role, age, gender173 unmodified linescv.poly([(fx - h * .035, fy + h * .03), (fx + h * .035, fy + h * .03), (fx + h * .01, fy - h * .03),(fx - h * .01, fy - h * .03)], (110, 225, 110))cv.capsule(fx, fy - h * .03, fx, fy - h * .06, max(.6, h * .01), (200, 225, 230))elif kind == "briefcase":bx, by = hx, hy + h * .05cv.capsule(bx - h * .015, hy + h * .01, bx + h * .015, hy + h * .01, max(.5, h * .006), (60, 40, 30))334 unmodified linesif in_chair:f = -1 if bound.facing == "left" else 1 # rule: a person in a wheelchair sits in it, facing its wayif bound is not None and inst.rel == "on" and bc in ("horse", "bicycle", "motorcycle", "camel", "elephant", "snowmobile","donkey", "pony", "scooter"):f = -1 if bound.facing == "left" else 1 # rule: a rider faces where the mount/vehicle facesword, role_name, age, gender = _role_age(getattr(inst, "word", ""))inst.hand = (x + f * inst.w * .35, y - H * .45) # fallback; replaced by the drawn near hand belowR = ROLES.get(role_name, {})skin = rng.choice(SKINS)90 unmodified linesR = dict(R, top=gc or WHITE, bottom=gc or WHITE, sleeves=True, boots=True, shoes=(200, 200, 205), main="top")elif k in ("shirt", "sweater") and gc:R = dict(R, top=gc, main="top", sleeves=(k == "sweater") or R.get("sleeves"))first_col = next((g.get("kind") for g in outfit if g.get("color") and g.get("slot") != "bottom"), None)if first_col and R:# rule: the prompt colour (= the first coloured garment) goes on that garment, not on a later coat or vestR["main"] = "coat" if first_col in ("jacket", "coat", "labcoat") and R.get("coat") else "dress" if R.get("dress") and first_col in ("dress", "gown", "robe") else "top"if A.get("face") == "eyepatch":R = dict(R, face="eyepatch") # rule: "with an eye patch" = the pirate eyepatch74 unmodified linesif role_name == "princess" and rng.random() < .6 and skin[0] >= 170:hair = HAIRS[4]hand_item = R.get("hand")holding = getattr(inst, "holding", None) # optional hint from the layout: what the near hand holdsif holding:hand_item = None # rule: a held prompt object replaces the role's default prop33 unmodified linesstoop = h * .03 * f if age == "old" else 0pose = "sitting" if in_chair else inst.poseif R.get("arms") == "up" and pose in (None, "standing"):pose = "arms_up"seated_on = pose == "sitting" and bound is not None and inst.rel == "on"astride = seated_on and bc in ("horse", "camel", "elephant", "donkey", "pony", "bicycle", "motorcycle", "snowmobile", "scooter")handlebar = seated_on and bc in ("bicycle", "motorcycle", "snowmobile", "scooter")far = lambda c: scale(c, .76) # rule: limbs on the far side are darker, giving 3/4 depthif dress and pose == "sitting":8 unmodified linesdef skin_ids(on):cv.cur_id = skin_id if on else base_id# ---- skeleton (top-down): head top at y - h, so worn hats/sunglasses anchored by the layout still fitry = h * .082 * headkrx = h * .071 * headkneck_len = h * (.03 if age != "child" else .022)torso_len = h * (1 - legk) - 2 * ry - neck_lenif pose == "sitting":hip_y = y if seated_on else y - h * .06sh_y = hip_y - torso_lentorso_x = x - f * h * .04else:hip_y = y - h * legksh_y = hip_y - torso_len1 unmodified linelean = {"running": .07, "walking": .015}.get(pose, 0) * f * h + stoopif handlebar:lean += f * h * .07 # rule: a cyclist leans forward over the handlebarscx = torso_x + lean # shoulder centre (leans with gait / stoop)head_cx = scx + stoop * .8 + f * rx * .08head_cy = sh_y - neck_len - ry * .96# body widths: men broad-shouldered, women narrower waist and fuller hips, children stubbyif age == "child":sw, tw, hw = h * .125, h * .1, h * .117 unmodified linescb = (hip_y + h * .02) if pose == "sitting" else y - h * (.02 if dress else .12)cw0, cw1 = sw * 1.0, h * (.2 if dress else .16)cx0 = scx - f * h * .02cv.poly([(cx0 - cw0, sh_y + h * .01), (cx0 + cw0, sh_y + h * .01), (cx0 + cw1, cb), (cx0 - cw1, cb)],lambda px, py: L.shade(cape, (px - cx0) / (cw1 * 2), .1, .85))if role_name in ("king", "queen"):# rule: royal robe = red cape with a white fur (ermine) hem with black fleckscv.capsule(cx0 - cw1, cb - h * .015, cx0 + cw1, cb - h * .015, h * .022, (245, 245, 240))for k in range(-2, 3):cv.ellipse(cx0 + k * cw1 * .4, cb - h * .015, max(.5, h * .007), max(.5, h * .009), BLACK)bpc = Noneif R.get("backpack") is not None:bpc = R["backpack"] if R["backpack"] is not True else (pcol if pcol and main != "top" else (60, 110, 190))17 unmodified linessc = shoes if front else far(shoes)hip = (torso_x + s * hw * .42, hip_y + h * .01)if pose == "sitting":if astride:# rule: riding = astride: thigh angled down-forward along the flank, shin hanging, foot slightly backknee = (hip[0] + f * l1 * .6, hip[1] + l1 * .72)foot = (knee[0] - f * l2 * .12, knee[1] + l2 * .95)5 unmodified lines# rule: sitting on the ground = knees drawn up, feet flat in frontfoot = (hip[0] + f * h * .32 + s * h * .02, y - h * .02)knee = _knee(hip, foot, l1, l2, f)else:if pose == "running":# rule: running = near leg reaches forward with a bent knee, far leg kicks up behind6 unmodified lines# rule: walking = scissor legs; the near leg steps forward, the far leg pushes off behindfoot = (x + f * h * .1, y - h * .035) if front else (x - f * h * .085, y - h * .045)knee = _knee(hip, foot, l1, l2, f)else:foot = (x + s * h * .05 + (f * h * .012 if front else 0), y - h * .035)knee = _knee(hip, foot, l1, l2, f)15 unmodified linesbk = (knee[0] + (foot[0] - knee[0]) * .4, knee[1] + (foot[1] - knee[1]) * .4)_taper(cv, L, bk[0], bk[1], foot[0], foot[1], lr * 1.0, lr * .85, sc)_shoe(cv, L, foot[0], foot[1], foot_u, f, sc, bs)return knee, footif pose == "sitting":_ground_shadow(cv, x + f * h * .05, y if not seated_on else y + h * .02, h * .16, h * .025)else:_ground_shadow(cv, x, y, h * .15, h * .024)leg(-f, False)59 unmodified linesdef arm_angles(s, front):"""(upper, fore) bone angles; 0 = hanging straight down, positive = toward +x."""if handlebar:return f * .75, f * 1.35 # rule: on a bike the arms reach forward to the handlebarif astride:20 unmodified linesreturn f * .3, f * .45if front and hand_item == "briefcase":return f * .05, f * .05# rule: relaxed arms hang slightly away from the body, elbows soft, hands a little forwardif big:return s * .04 - f * .03, s * .0 + f * .16 # close up: arms rest nearer the body8 unmodified linescol_skin = BLACKa1, a2 = arm_angles(s, front)sho = (scx + s * (sw - ar * 1.05), sh_y + h * .012 + ar)elb = _seg(sho, ua, a1)wri = _seg(elb, fa, a2)wide = 1.3 if dress == "robe" else 1.014 unmodified lines_taper(cv, L, mid[0], mid[1], elb[0], elb[1], ar * .98, ar * .9, col_skin)_taper(cv, L, sho[0], sho[1], mid[0], mid[1], ar * 1.16, ar * 1.08, col_sleeve)hand_c = col_skin if role_name != "knight" else scale(metal, .8)hx2, hy2 = _seg(wri, ar * .75, a2)skin_ids(True)lit_ellipse(cv, L, hx2, hy2, ar * 1.0, ar * 1.12, hand_c, rot=a2 * -.3)29 unmodified linesif stripes == "pirate":# rule: pirate = bold horizontal red/white stripes on the shirtbase = shirt if int((py - sh_y) / max(1.2, h * .035)) % 2 == 0 else (200, 40, 45)elif stripes == "reflect" and abs((py - sh_y) - h * .2) < h * .018:base = (235, 235, 210) # rule: firefighter coat = reflective silver band round the middleelif stripes == "jersey" and abs((px - tcx(py)) - f * h * .0) < h * .012:67 unmodified linesif big: # collar edgefor s_ in (-1, 1):cv.capsule(tx0 + s_ * rx * .5, sh_y - h * .004, tx0 + f * h * .005, sh_y + h * .045, max(.5, h * .004), scale(shirt, .78))if R.get("buttons"):for k in range(3): # chef's double-breasted buttonsfor s in (-1, 1):cv.ellipse(tx0 + f * h * .01 + s * h * .025, sh_y + h * (.08 + k * .07), max(.5, h * .007), max(.5, h * .007), (150, 150, 150))belt = R.get("belt")if belt and pose != "sitting":bcol = (200, 40, 40) if belt == "red" else (50, 38, 30)36 unmodified linescv.ellipse(head_cx + f * rx * .05, head_cy + ry * .98, nr * 1.05, ry * .2, scale(skin, .78), alpha=.75)# arm in front after the neck so a raised prop arm overlaps the chestskin_ids(False)near_hand = arm(f, True)skin_ids(True)inst.hand = near_handif role_name == "knight":# rule: knight = closed steel great-helm (rounded box) with a dark visor slit and a coloured plume48 unmodified linesface = R.get("face")_face(cv, L, head_cx, head_cy, rx, ry, f, skin, hair, eye_c, age == "old", fem,smile=face not in ("beard", "beard_long"))if getattr(inst, "expression", None) and ry >= 4.6:_expression(cv, head_cx, head_cy, rx, ry, f, skin, inst.expression)if inst.expression in ("sleepy", "winking"):from ..character2d import expression_extra # wave 12expression_extra(cv, head_cx, head_cy, rx, ry, f, skin, inst.expression)inst.head = (head_cx, head_cy, rx, ry, f) # wave 12: anchor for worn hats / glasses / neckwear36 unmodified linescv.capsule(head_cx - f * rx * .8, head_cy - ry * .45, ex_ + f * rx * .2, head_cy + ry * .05, max(.5, ry * .07), BLACK)cv.ellipse(ex_, head_cy + ry * .14, max(.8, rx * .24), max(.8, ry * .2), BLACK)cv.ellipse(head_cx + f * rx * .2, head_cy + ry * .7, rx * .62, ry * .26, mix(skin, hair, .5), alpha=.7)elif face == "clown":cv.ellipse(head_cx + f * rx * .52, head_cy + ry * .38, max(.9, rx * .26), max(.9, ry * .24), (230, 30, 35))cv.capsule(head_cx - rx * .1 + f * rx * .1, head_cy + ry * .62, head_cx + f * rx * .5 + rx * .2, head_cy + ry * .62,328 unmodified linescv.poly([(px + bw, py - bw * .6), (px, py), (px + bw, py + bw * .6)], second if i % 4 else c)prev = (px, py)# string trailing down-and-sideways out of frame (rule: a line to the ground says "flying kite")if inst.pose == "flying":sx = 1 if x < cv.w / 2 else -1cv.capsule(C[0], C[1] + h * .05, C[0] + sx * h * 1.2, C[1] + h * 2.5, max(.4, h * .005), (245, 245, 245), alpha=.45)221 unmodified lines# ---------------------------------------------------------------- registryconcept("person", height=1.75, aspect=.38, row="front", setting="street", on_top=.55, default_color=None,synonyms=["man", "woman", "boy", "girl", "child", "kid", "guy", "lady", "pedestrian", "human", "adult","teenager", "student", "player", "tourist"] + ROLE_SYNONYMS,2 unmodified lines"fireman": "firemen", "firewoman": "firewomen", "businessman": "businessmen","businesswoman": "businesswomen", "gentleman": "gentlemen", "old man": "old men","old woman": "old women", "elderly man": "elderly men", "elderly woman": "elderly women","baby boy": "baby boys"})(draw_person)concept("umbrella", height=1.0, aspect=1.15, row="front", setting="beach", on_top=1.0, default_color=(215, 50, 60),synonyms=["parasol", "beach umbrella"])(draw_umbrella)concept("tie", height=.42, aspect=.38, row="front", setting="table", default_color=(170, 30, 45),25 unmodified lines26272829303132333435363738394041424344454647484950515253545556575859606162636449 unmodified lines11411511611711811912012112212315 unmodified lines1391401411421431441451465 unmodified lines15215315415515615715815916016116216316416522 unmodified lines18818919019119219319419519619719819922 unmodified lines222223224225226227228229230231232233234173 unmodified lines408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498334 unmodified lines83383483583683783883984084184284384484584690 unmodified lines93793893994094194294394494594694794894995095195295395495595695795895996096196296374 unmodified lines1038103910401041104210431044104533 unmodified lines107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011018 unmodified lines111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351 unmodified line113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116417 unmodified lines1182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121917 unmodified lines123712381239124012411242124312441245124612475 unmodified lines12531254125512561257125812591260126112621263126412656 unmodified lines127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129615 unmodified lines131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134859 unmodified lines1408140914101411141214131414141514161417141814191420142114221423142414251426142720 unmodified lines14481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014818 unmodified lines1490149114921493149414951496149714981499150014 unmodified lines1515151615171518151915201521152229 unmodified lines155215531554155515561557155815591560156167 unmodified lines162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166236 unmodified lines1699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173948 unmodified lines17881789179017911792179317941795179617971798179936 unmodified lines18361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858328 unmodified lines218721882189219021912192219321942195219621972198219922002201220222032204221 unmodified lines2426242724282429243024312432243324342435243624372 unmodified lines244024412442244324442445244625 unmodified lines"light": [(255, 219, 186), (241, 194, 160)]}# (night characters 3, body) words that throw the arms up in joy (plain "happy" / "smiling" keep the relaxed stance)JOY_WORDS = {"excited", "joyful", "delighted", "cheering", "celebrating", "ecstatic", "overjoyed", "thrilled", "elated","triumphant", "jubilant", "victorious", "cheers", "celebrates"}def _night_on(name):import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get(name, "1") != "0"def _reach(sho, tgt, l1, l2):"""(upper, fore) bone angles (0 = down, +pi/2 = +x) so a two-bone arm from sho ends at tgt (or points at it)"""dx, dy = tgt[0] - sho[0], tgt[1] - sho[1]d = math.hypot(dx, dy) or 1e-6base = math.atan2(dx, dy)if d >= l1 + l2 * .98:return base, basec1 = max(-1.0, min(1.0, (l1 * l1 + d * d - l2 * l2) / (2 * l1 * d)))t1 = math.acos(c1)sg = 1 if dx >= 0 else -1a1 = base - sg * t1 # the elbow drops (toward "down" = 0)ex, ey = sho[0] + math.sin(a1) * l1, sho[1] + math.cos(a1) * l1return a1, math.atan2(tgt[0] - ex, tgt[1] - ey)def _cape2():"""night knob: PYDRAW_EXP cape2=0 restores the old cape rules"""import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get("cape2", "1") != "0"def _named(col):"""Colour name from the parser -> rgb (None stays None)."""if not col:49 unmodified linesvest=(120, 80, 45), boots=True, shoes=(110, 65, 35), belt=True, main="top", gender="f"),"ninja": dict(top=BLACK, bottom=BLACK, sleeves=True, hat="ninja", shoes=BLACK, belt="red", main="top",hand="ninja_sword", gender="m"),# night characters 2 (critic C21): samurai = dark red lamellar armour laced in rows, dark wide hakama, a topknot,# a katana in the hand (it was a generic person in a coat)"samurai": dict(top=(150, 36, 42), bottom=(42, 42, 58), sleeves=True, stripes="lamellar", belt=True, hair="bun",hair_col=BLACK, shoes=(60, 45, 35), hand="ninja_sword", main="top", gender="m"),"clown": dict(top=(240, 200, 40), bottom=(40, 120, 210), sleeves=True, hat="clown", face="clown", dots=True,shoes=(220, 40, 40), big_shoes=True, neck="ruff", main="top"),"farmer": dict(top=(200, 55, 50), bottom=(60, 95, 160), sleeves=False, hat="straw", overalls=True, plaid=True,15 unmodified lines"dancer": dict(top=(245, 160, 195), bottom=(250, 205, 215), sleeves=False, dress="tutu", hair="bun",arms="up", shoes=(245, 160, 195), main="top", gender="f"),}# rule (night): a generic "superhero" wears the superman suit + flowing cape (it used to be a plain red outfit)ROLES["superhero"] = {k: v for k, v in ROLES["superman"].items() if k not in ("gender", "hair_col")}WORD_ROLE = {"chef": "chef", "cook": "chef", "baker": "chef",5 unmodified lines"king": "king", "queen": "queen", "princess": "princess", "prince": "prince","knight": "knight","wizard": "wizard", "sorcerer": "wizard", "mage": "wizard", "witch": "witch","pirate": "pirate", "cowboy": "cowboy", "cowgirl": "cowgirl", "ninja": "ninja", "samurai": "samurai", "ronin": "samurai", "clown": "clown","farmer": "farmer", "scientist": "scientist", "chemist": "scientist","businessman": "business", "businesswoman": "business", "businessperson": "business","student": "student", "schoolboy": "student", "schoolgirl": "student","athlete": "athlete", "runner": "athlete", "jogger": "athlete", "sprinter": "athlete","dancer": "dancer", "ballerina": "dancer", "ballet dancer": "dancer","politician": "business", "senator": "business", "mayor": "business","superman": "superman", "superhero": "superhero", "superheroine": "superhero", "spiderman": "spiderman", "spider man": "spiderman", "batman": "batman",}# word -> (age, gender)WORD_AGE = {22 unmodified lines"businessmen": "businessman", "businesswomen": "businesswoman", "gentlemen": "gentleman","babies": "baby", "grannies": "granny", "witches": "witch", "princesses": "princess"}# rule: bare "baby" is NOT registered: it is a size word ("baby elephant") and would steal those promptsif _night_on("props"):# night: mail carriers are people in a blue uniform (the word used to be unknown: "a postman" drew nothing);# characters._activity_props adds the satchel, cap and letterROLES["postman"] = dict(top=(70, 110, 180), bottom=(40, 50, 85), sleeves=True, main="top")WORD_ROLE.update({"postman": "postman", "mailman": "postman", "postwoman": "postman", "mailwoman": "postman","mail carrier": "postman"})ROLE_SYNONYMS = sorted((set(WORD_ROLE) | set(WORD_AGE)) - {"baby"})22 unmodified linesdef _role_age(word):w = _singular(word)role = WORD_ROLE.get(w)if role is None and w not in WORD_AGE and " " in w and _night_on("roleword"):# night characters 2 (roleword, critic C27): "sad clown", "brave knight", "tired chef" - an adjective left in# the word hid the role; the last word alone still names itrole = WORD_ROLE.get(w.split()[-1])if role == "superhero" and not _cape2():role = Noneage, gender = WORD_AGE.get(w, WORD_AGE.get(w.split()[-1], ("adult", None)) if w and _night_on("roleword") else ("adult", None))return w, role, age, gender173 unmodified linescv.poly([(fx - h * .035, fy + h * .03), (fx + h * .035, fy + h * .03), (fx + h * .01, fy - h * .03),(fx - h * .01, fy - h * .03)], (110, 225, 110))cv.capsule(fx, fy - h * .03, fx, fy - h * .06, max(.6, h * .01), (200, 225, 230))elif kind == "knitting":# rule (night): knitting = two needles crossing at the hands, a knitted swatch hanging below, a strand of# yarn running down to a ball on the groundyc = col if col and sum(col) < 600 and col != (240, 240, 235) else (200, 70, 90)yc = (205, 75, 95) if sum(yc) < 200 else yccv.poly([(hx - h * .03, hy + h * .005), (hx + h * .03, hy + h * .005), (hx + h * .026, hy + h * .06), (hx - h * .026, hy + h * .06)],L.shade(yc, 0, 0, .9))for k in range(3):cv.capsule(hx - h * .026, hy + h * (.018 + k * .016), hx + h * .026, hy + h * (.018 + k * .016), max(.4, h * .003), scale(yc, .75))for s_ in (-1, 1):cv.capsule(hx - s_ * h * .045, hy - h * .035, hx + s_ * h * .04, hy + h * .025, max(.45, h * .005), (205, 190, 150))bx_, by_ = hx + f * h * .1, y - h * .025cv.capsule(hx + f * h * .02, hy + h * .05, bx_, by_ - h * .02, max(.4, h * .003), yc)lit_ellipse(cv, L, bx_, by_, h * .028, h * .025, yc)cv.capsule(bx_ - h * .02, by_ - h * .008, bx_ + h * .02, by_ + h * .006, max(.4, h * .003), scale(yc, .7))elif kind == "bubbles":# rule (night): blowing bubbles = a wand ring held at the lips and a drift of see-through bubbleswx, wy = hx + f * h * .05, hy - h * .1cv.capsule(hx, hy, wx, wy, max(.5, h * .005), (230, 90, 160))cv.ellipse(wx, wy - h * .02, h * .022, h * .022, (230, 90, 160))import random as _rrr = _r.Random(int(hx * 3 + hy))for k_ in range(6):t_ = (k_ + 1) / 6bx_ = wx + f * (h * .1 + t_ * h * .6) + rr.uniform(-h * .04, h * .04)by_ = wy - h * .04 - t_ * h * .42 + rr.uniform(-h * .06, h * .06)br_ = h * (.035 + .04 * rr.random())# thin bright rings (a filled translucent disc posterised into grey lumps), tinted cyan / pink like soap filmrc_ = (120, 205, 245) if k_ % 2 == 0 else (235, 140, 210)_ring = [(bx_ + math.cos(a_) * br_, by_ + math.sin(a_) * br_) for a_ in [i_ * math.pi / 7 for i_ in range(15)]]for p0, p1 in zip(_ring, _ring[1:]):cv.capsule(p0[0], p0[1], p1[0], p1[1], max(.45, h * .004), rc_)cv.ellipse(bx_ - br_ * .4, by_ - br_ * .4, max(.6, br_ * .2), max(.6, br_ * .2), (255, 255, 255))elif kind == "lasso":# rule (night): a lasso = a rope loop twirled above the head, its line running down to the handlx_, ly_ = hx + f * h * .02, y - h * 1.08pts_ = [(lx_ + math.cos(a_) * h * .16, ly_ + math.sin(a_) * h * .05) for a_ in [i_ * math.pi / 8 for i_ in range(17)]]for p0, p1 in zip(pts_, pts_[1:]):cv.capsule(p0[0], p0[1], p1[0], p1[1], max(.5, h * .006), (200, 170, 110))cv.capsule(hx, hy, lx_ + f * h * .12, ly_ + h * .03, max(.5, h * .006), (200, 170, 110))elif kind == "pillow":# rule (night): a pillow swung overhead + a few feathers drifting around itpx_, py_ = hx + f * h * .03, hy - h * .06lit_ellipse(cv, L, px_, py_, h * .1, h * .065, (246, 244, 240), rot=f * .3)cv.capsule(px_ - h * .07, py_ - h * .03, px_ + h * .07, py_ + h * .03, max(.4, h * .004), (215, 210, 205))import random as _rrr = _r.Random(int(hx * 7 + hy))for k_ in range(5):fx_, fy_ = px_ + rr.uniform(-h * .25, h * .25), py_ + rr.uniform(-h * .2, h * .15)cv.capsule(fx_ - h * .012, fy_, fx_ + h * .012, fy_ - h * .008, max(.5, h * .006), (250, 250, 250))elif kind == "jumprope":# rule (night): jumping rope = a rope loop from the near hand, swung down under the lifted feet and back upax_, ay_ = hx, hybx_ = hx - f * h * .18pts_ = [(ax_ + (bx_ - ax_) * t_, ay_ + math.sin(t_ * math.pi) * (y - ay_ + h * .16)) for t_ in [k_ / 12 for k_ in range(13)]]for a_, b_ in zip(pts_, pts_[1:]):cv.capsule(a_[0], a_[1], b_[0], b_[1], max(.5, h * .006), (220, 60, 90))for e_ in (ax_, bx_):cv.capsule(e_, ay_ - h * .015, e_, ay_ + h * .03, max(.6, h * .012), (240, 200, 60))elif kind == "paperplane":# rule (night): a paper airplane = a small white folded dart held up, about to be throwntx_, ty_ = hx + f * h * .09, hy - h * .05cv.poly([(hx - f * h * .02, hy - h * .01), (tx_, ty_), (hx, hy - h * .05)], (248, 248, 244))cv.poly([(hx - f * h * .02, hy - h * .01), (tx_, ty_), (hx + f * h * .01, hy + h * .015)], (220, 222, 228))elif kind == "rod":# rule (night): fishing = a long thin rod angled up and out from the hand, the line dropping from its tiptx, ty = hx + f * h * .42, hy - h * .38cv.capsule(hx - f * h * .03, hy + h * .03, tx, ty, max(.5, h * .007), (110, 80, 55))cv.capsule(hx, hy, hx + f * h * .04, hy - h * .02, max(.6, h * .012), (60, 60, 64))lx_, ly_ = tx + f * h * .06, y - h * .02cv.capsule(tx, ty, lx_, ly_, max(.4, h * .003), (235, 235, 235))cv.ellipse(lx_, ly_ - h * .01, max(.6, h * .012), max(.6, h * .012), (220, 50, 50))elif kind == "ladle":# rule (night): stirring = a long wooden spoon / ladle reaching down from the hand into the pottx, ty = hx + f * h * .1, hy + h * .14cv.capsule(hx - f * h * .02, hy - h * .03, tx, ty, max(.6, h * .009), (150, 105, 60))cv.ellipse(tx, ty, h * .02, h * .012, (125, 85, 50))elif kind == "letter":# rule (night): a letter held up = a white envelope with the flap's V and a red stampex, ey = hx + f * h * .02, hy - h * .02cv.poly([(ex - h * .045, ey - h * .03), (ex + h * .045, ey - h * .03), (ex + h * .045, ey + h * .03), (ex - h * .045, ey + h * .03)],(246, 244, 236))cv.capsule(ex - h * .042, ey - h * .027, ex, ey + h * .002, max(.4, h * .004), (180, 175, 165))cv.capsule(ex, ey + h * .002, ex + h * .042, ey - h * .027, max(.4, h * .004), (180, 175, 165))cv.ellipse(ex + f * h * .03, ey - h * .015, h * .009, h * .009, (210, 50, 50))elif kind == "briefcase":bx, by = hx, hy + h * .05cv.capsule(bx - h * .015, hy + h * .01, bx + h * .015, hy + h * .01, max(.5, h * .006), (60, 40, 30))334 unmodified linesif in_chair:f = -1 if bound.facing == "left" else 1 # rule: a person in a wheelchair sits in it, facing its wayif bound is not None and inst.rel == "on" and bc in ("horse", "bicycle", "motorcycle", "camel", "elephant", "snowmobile","donkey", "pony", "scooter") + \(("unicorn", "zebra", "deer", "reindeer", "llama", "cow", "ostrich", "dragon", "bear", "lion", "tiger", "dog")if _night_on("astride") else ()):f = -1 if bound.facing == "left" else 1 # rule: a rider faces where the mount/vehicle facesword, role_name, age, gender = _role_age(getattr(inst, "word", ""))age = (getattr(inst, "attrs", None) or {}).get("age", age) # night wave (language): "an old fisherman"if getattr(inst, "age_hint", None):age = inst.age_hint # night characters 2 (group): the children of "a family of four"inst.hand = (x + f * inst.w * .35, y - H * .45) # fallback; replaced by the drawn near hand belowR = ROLES.get(role_name, {})skin = rng.choice(SKINS)90 unmodified linesR = dict(R, top=gc or WHITE, bottom=gc or WHITE, sleeves=True, boots=True, shoes=(200, 200, 205), main="top")elif k in ("shirt", "sweater") and gc:R = dict(R, top=gc, main="top", sleeves=(k == "sweater") or R.get("sleeves"))elif k == "apron" and _night_on("outfit2"):# rule (night): "a woman in an apron" wears it (the outfit kind had no rule and was dropped)R = dict(R, apron=gc or (248, 246, 240), apron_default=gc is None)elif k == "cape" and _cape2():# rule (night): "a man in a cape" / "a girl in a red cape" wears the cape (it used to be dropped)R = dict(R, cape=gc or R.get("cape") or (200, 35, 40))if gc:R["main"] = "cape"first_col = next((g.get("kind") for g in outfit if g.get("color") and g.get("slot") != "bottom"), None)if first_col and R:# rule: the prompt colour (= the first coloured garment) goes on that garment, not on a later coat or vestR["main"] = "cape" if first_col == "cape" and R.get("cape") and _cape2() else "coat" if first_col in ("jacket", "coat", "labcoat") and R.get("coat") else "dress" if R.get("dress") and first_col in ("dress", "gown", "robe") else "top"if _night_on("outfit2"):for wi in A.get("wear") or []:if wi.get("item") == "boots":# rule (night): worn boots = the boot rule (shoe colour up the shin), brown unless colouredR = dict(R, boots=True, shoes=tuple(wi["color"]) if wi.get("color") else (95, 62, 40))elif wi.get("item") == "backpack" and _night_on("pbackpack"):R = dict(R, backpack=tuple(wi["color"]) if wi.get("color") else True)elif wi.get("item") == "mittens":R = dict(R, mittens=tuple(wi["color"]) if wi.get("color") else (200, 50, 55))if A.get("face") == "eyepatch":R = dict(R, face="eyepatch") # rule: "with an eye patch" = the pirate eyepatch74 unmodified linesif role_name == "princess" and rng.random() < .6 and skin[0] >= 170:hair = HAIRS[4]hand_item = R.get("hand")if (getattr(inst, "attrs", None) or {}).get("prop") and _night_on("props"):hand_item = inst.attrs["prop"] # night: what the activity verb puts in the hand (knitting, ladle, letter)holding = getattr(inst, "holding", None) # optional hint from the layout: what the near hand holdsif holding:hand_item = None # rule: a held prompt object replaces the role's default prop33 unmodified linesstoop = h * .03 * f if age == "old" else 0pose = "sitting" if in_chair else inst.poseppose = _night_on("ppose")if ppose and pose == "jumping":y -= h * .12 # rule (night): a jumping person is off the ground (knees tucked below)if ppose and pose == "meditating":pose = "sitting" # cross-legged on the ground, hands on the knees (legs drawn as sitting)dancing_ = pose == "dancing" and _night_on("pdance") and not getattr(inst, "reach", None)if (R.get("arms") == "up" and pose in (None, "standing")) or dancing_:pose = "arms_up" # night: a dancing person raises both arms in an arch (it stood still)stool = bool(getattr(inst, "stool", False)) and pose == "sitting" and _night_on("table")shoulder_ride = bool(getattr(inst, "shoulder_ride", False)) and _night_on("shoulders")if shoulder_ride:pose = "sitting"seated_on = pose == "sitting" and ((bound is not None and inst.rel == "on") or stool or shoulder_ride)astride = seated_on and bc in ("horse", "camel", "elephant", "donkey", "pony", "bicycle", "motorcycle", "snowmobile", "scooter") + \(("unicorn", "zebra", "deer", "reindeer", "llama", "cow", "ostrich", "dragon", "bear", "lion", "tiger", "dog")if _night_on("astride") else ()) # night: any mount is ridden astride (a girl lay on a unicorn's back)astride = astride or shoulder_ride # night characters 3 (shoulders): a child straddles the carrier's shouldershandlebar = seated_on and bc in ("bicycle", "motorcycle", "snowmobile", "scooter")far = lambda c: scale(c, .76) # rule: limbs on the far side are darker, giving 3/4 depthif dress and pose == "sitting":8 unmodified linesdef skin_ids(on):cv.cur_id = skin_id if on else base_idif _night_on("paleskin") and min(shirt) > 215 and .3 * skin[0] + .59 * skin[1] + .11 * skin[2] > 200 \and not R and pcol is None:# rule (night): pale skin above a white top washes into one grey-white figure in the pixel palette (a seated# old lady read as a ghost) - such a person gets a coloured topshirt = [c_ for c_ in SHIRTS if min(c_) < 200][int(rng.random() * 997) % max(1, len([c_ for c_ in SHIRTS if min(c_) < 200]))]# ---- skeleton (top-down): head top at y - h, so worn hats/sunglasses anchored by the layout still fitry = h * .082 * headkrx = h * .071 * headkneck_len = h * (.03 if age != "child" else .022)torso_len = h * (1 - legk) - 2 * ry - neck_lenkneel = pose == "kneeling" and _night_on("kneel")if pose == "sitting":hip_y = (y - h * .27 if stool else y) if seated_on else y - h * .06sh_y = hip_y - torso_lentorso_x = x - f * h * .04elif kneel:# rule (night): kneeling on one knee - the hips drop to about a thigh's length above the groundhip_y = y - h * legk * .55sh_y = hip_y - torso_lentorso_x = xelse:hip_y = y - h * legksh_y = hip_y - torso_len1 unmodified linelean = {"running": .07, "walking": .015}.get(pose, 0) * f * h + stoopif handlebar:lean += f * h * .07 # rule: a cyclist leans forward over the handlebar# (night characters 3, body): emotions read from the whole body at a glance, not only from a few face pixelsbody_ = Noneif _night_on("body") and not big and not holding and not getattr(inst, "reach", None) and not astride and not handlebar \and pose in (None, "standing", "sitting") and not (getattr(inst, "attrs", None) or {}).get("inter"):ex_ = getattr(inst, "expression", None)ew_ = getattr(inst, "expr_word", None)if ex_ in ("sad", "sleepy") or ex_ == "crying":body_ = ex_ if ex_ != "sleepy" else "sad"elif ex_ in ("angry", "scared", "surprised") and not hand_item:body_ = ex_elif ex_ in ("happy", "laughing") and ew_ in JOY_WORDS and not hand_item and pose != "sitting":body_ = "joy"if body_ == "scared":lean -= f * h * .035 # recoils, leaning back from the dangerelif body_ in ("sad", "crying"):lean += f * h * .012 # shoulders slump forwardscx = torso_x + lean # shoulder centre (leans with gait / stoop)head_cx = scx + stoop * .8 + f * rx * .08head_cy = sh_y - neck_len - ry * .96if body_ in ("sad", "crying"):head_cx += f * rx * .3 # the head hangs forward and downhead_cy += ry * .28# body widths: men broad-shouldered, women narrower waist and fuller hips, children stubbyif age == "child":sw, tw, hw = h * .125, h * .1, h * .117 unmodified linescb = (hip_y + h * .02) if pose == "sitting" else y - h * (.02 if dress else .12)cw0, cw1 = sw * 1.0, h * (.2 if dress else .16)cx0 = scx - f * h * .02if _cape2() and pose != "sitting":# rule (night, cape2): the cape flows - the trailing side (away from the facing) lifts and flares out,# the hem is scalloped, folds run down from the shoulders and the lifted hem shows the darker liningimport math as _mtop_, H_ = sh_y + h * .01, cb - sh_ylb, tb = (cx0 + f * cw1 * 1.05, cb), (cx0 - f * (cw1 * 1.55 + h * .05), cb - H_ * .16)hem = []for i in range(1, 15):t = i / 15hem.append((lb[0] + (tb[0] - lb[0]) * t, lb[1] + (tb[1] - lb[1]) * t ** 1.6 - abs(_m.sin(t * _m.pi * 3)) * h * .012))tm = (cx0 - f * (cw1 * 1.3 + h * .03), top_ + H_ * .5)cpx, cpy = 2 * tm[0] - (tb[0] + cx0 - f * cw0) / 2, 2 * tm[1] - (tb[1] + top_) / 2trail = [((1 - t) ** 2 * tb[0] + 2 * (1 - t) * t * cpx + t * t * (cx0 - f * cw0), (1 - t) ** 2 * tb[1] + 2 * (1 - t) * t * cpy + t * t * top_)for t in [i / 8 for i in range(9)]]cv.poly([(cx0 + f * cw0, top_), lb] + hem + trail, lambda px, py: L.shade(cape, (px - cx0) / (cw1 * 2.4), .05, .9))far_ = [q for q in hem if (q[0] - cx0) * -f > cw1 * .5]if len(far_) >= 2:up = [(q[0], q[1] - h * .02) for q in far_]cv.poly(far_ + [tb] + up[::-1], _tone(cape, .55))for k in (1, 2, 3):t = k / 3.0 - 1 / 6.0cv.capsule(cx0 + f * cw0 * (.6 - 1.2 * t), top_ + H_ * .2, lb[0] + (tb[0] - lb[0]) * t,lb[1] + (tb[1] - lb[1]) * t ** 1.6 - h * .01, max(.5, h * .004), _tone(cape, .72))else:cv.poly([(cx0 - cw0, sh_y + h * .01), (cx0 + cw0, sh_y + h * .01), (cx0 + cw1, cb), (cx0 - cw1, cb)],lambda px, py: L.shade(cape, (px - cx0) / (cw1 * 2), .1, .85))if role_name in ("king", "queen"):# rule: royal robe = red cape with a white fur (ermine) hem with black fleckscv.capsule(cx0 - cw1, cb - h * .015, cx0 + cw1, cb - h * .015, h * .022, (245, 245, 240))for k in range(-2, 3):cv.ellipse(cx0 + k * cw1 * .4, cb - h * .015, max(.5, h * .007), max(.5, h * .009), BLACK)sat = next((w for w in (A.get("wear") or []) if w.get("item") == "satchel"), None) if _night_on("props") else Nonebpc = Noneif R.get("backpack") is not None:bpc = R["backpack"] if R["backpack"] is not True else (pcol if pcol and main != "top" else (60, 110, 190))17 unmodified linessc = shoes if front else far(shoes)hip = (torso_x + s * hw * .42, hip_y + h * .01)if pose == "sitting":if shoulder_ride:# (night characters 3): legs hang almost straight down over the carrier's shoulders and chestknee = (hip[0] + f * l1 * .18, hip[1] + l1 * .95)foot = (knee[0] + f * l2 * .1, knee[1] + l2 * .95)elif astride:# rule: riding = astride: thigh angled down-forward along the flank, shin hanging, foot slightly backknee = (hip[0] + f * l1 * .6, hip[1] + l1 * .72)foot = (knee[0] - f * l2 * .12, knee[1] + l2 * .95)5 unmodified lines# rule: sitting on the ground = knees drawn up, feet flat in frontfoot = (hip[0] + f * h * .32 + s * h * .02, y - h * .02)knee = _knee(hip, foot, l1, l2, f)elif kneel:if front: # the near knee is up: thigh forward, shin straight down to a flat footknee = (hip[0] + f * l1 * .92, hip[1] - h * .01)foot = (knee[0] + f * h * .01, y - h * .03)else: # the far knee is on the ground, the shin lies back along itknee = (hip[0] - f * h * .01, y - h * .035)foot = (knee[0] - f * l2 * .9, y - h * .03)else:if pose == "running":# rule: running = near leg reaches forward with a bent knee, far leg kicks up behind6 unmodified lines# rule: walking = scissor legs; the near leg steps forward, the far leg pushes off behindfoot = (x + f * h * .1, y - h * .035) if front else (x - f * h * .085, y - h * .045)knee = _knee(hip, foot, l1, l2, f)elif ppose and pose == "kicking" and front:# rule (night): kicking = the near leg swung forward, foot up at the ballfoot = (x + f * h * .24, y - h * .14)knee = _knee(hip, foot, l1, l2, f)elif ppose and pose == "yoga" and front:# rule (night): yoga tree pose = the near foot pressed to the other knee, knee pointing outknee = (hip[0] + f * h * .13, hip[1] + l1 * .55)foot = (hip[0] + f * h * .01, hip[1] + l1 * .95)elif ppose and pose == "climbing":# rule (night): climbing = one knee drawn up high, the other leg reaching down for a footholdfoot = (x + f * h * .07, y - h * .25) if front else (x - f * h * .02, y - h * .02)knee = _knee(hip, foot, l1, l2, f) if not front else (hip[0] + f * h * .13, hip[1] + l1 * .3)elif ppose and pose == "jumping":foot = (x + s * h * .04 - f * h * .06, y - h * .06)knee = (hip[0] + f * h * .1, hip[1] + l1 * .7)elif dancing_ and front:# rule (night): the dancing near leg points forward and up on its toefoot = (x + f * h * .15, y - h * .11)knee = _knee(hip, foot, l1, l2, f)else:foot = (x + s * h * .05 + (f * h * .012 if front else 0), y - h * .035)knee = _knee(hip, foot, l1, l2, f)15 unmodified linesbk = (knee[0] + (foot[0] - knee[0]) * .4, knee[1] + (foot[1] - knee[1]) * .4)_taper(cv, L, bk[0], bk[1], foot[0], foot[1], lr * 1.0, lr * .85, sc)_shoe(cv, L, foot[0], foot[1], foot_u, f, sc, bs)if front and shoulder_ride:# (night characters 3, shoulders): the rider is drawn behind the carrier (so his head is in front of her# body); her near leg is drawn again over his chest by the carrier (see below)inst._ride_leg = (hip, knee, foot, lr, col, skc, sc, foot_u, bool(shorts), bool(R.get("boots")))return knee, footpb = getattr(inst, "picnic_blanket", None)if pb is not None and _night_on("picnic"):# rule (night): a picnic = a red-and-white checked blanket on the grass under everyone (drawn first)bx0, bx1, by_, bd = pbtop_, bot_ = by_ - bd * .5, by_ + bd * .5sk_ = (bx1 - bx0) * .08nx_, ny_ = 8, 3for i_ in range(nx_):for j_ in range(ny_):u0, u1 = i_ / nx_, (i_ + 1) / nx_v0, v1 = j_ / ny_, (j_ + 1) / ny_def P_(u, v):return (bx0 + sk_ * (1 - v) + (bx1 - bx0 - sk_ * (1 - v) * 2) * u, top_ + (bot_ - top_) * v)c_ = (205, 50, 55) if (i_ + j_) % 2 == 0 else (246, 240, 232)cv.poly([P_(u0, v0), P_(u1, v0), P_(u1, v1), P_(u0, v1)], c_)if pose == "sitting" and shoulder_ride:passelif pose == "sitting":_ground_shadow(cv, x + f * h * .05, y if (not seated_on or stool) else y + h * .02, h * .16, h * .025)if stool:# rule (night): at a table with no chair named, a person sits on a plain wooden stoolwc = (150, 105, 65)for s_ in (-1, 1):cv.capsule(torso_x + s_ * h * .055, hip_y + h * .04, torso_x + s_ * h * .07, y - h * .005, max(.6, h * .011), scale(wc, .8))lit_ellipse(cv, L, torso_x, hip_y + h * .035, h * .085, h * .018, wc)else:_ground_shadow(cv, x, y, h * .15, h * .024)leg(-f, False)59 unmodified linesdef arm_angles(s, front):"""(upper, fore) bone angles; 0 = hanging straight down, positive = toward +x."""if body_ == "sad":return s * .02 + f * .04, f * .06 # arms hang limp, close to the bodyif body_ == "crying":return (f * .25, f * 2.75) if front else (f * .15, f * 2.65) # both hands up to the faceif body_ == "angry" and pose == "sitting":return s * .12, -s * 1.45 + f * .1 # seated: arms folded across the chestif body_ == "angry":return s * .75, -s * 1.35 # fists on the hips, elbows out (arms akimbo)if body_ == "scared":return (f * .95, f * 2.5) if front else (f * .75, f * 2.35) # hands up in front, palms outif body_ == "surprised":return s * .55, s * 2.85 # hands flung up beside the headif body_ == "joy":return s * 2.7, s * 2.95 # both arms thrown up in a Vif handlebar:return f * .75, f * 1.35 # rule: on a bike the arms reach forward to the handlebarif astride:20 unmodified linesreturn f * .3, f * .45if front and hand_item == "briefcase":return f * .05, f * .05if hand_item == "knitting":return (f * .25, f * 1.95) if front else (f * .15, f * 1.8) # both hands together in front of the chestif front and hand_item == "letter":return f * .55, f * 2.2if front and hand_item == "ladle":return f * .45, f * 1.25if front and hand_item == "rod":return f * .5, f * 1.6if hand_item == "jumprope":return (f * .35 + s * .5, s * .9) if True else Noneif front and hand_item == "paperplane":return -f * .3, f * 2.8 # cocked back over the shoulderif ppose and pose == "kicking":return (f * .5, f * .9) if not front else (-f * .45, -f * .2) # arms swing against the kickif ppose and pose in ("climbing",):return (s * .6 + f * 2.5, s * .2 + f * 2.8) if front else (f * 2.7, f * 3.0) # both hands up on the trunkif ppose and pose == "yoga":return s * 2.85, -s * 2.6 # palms together above the headif ppose and inst.pose == "meditating":return s * .35 + f * .15, s * 1.2 + f * .3 # hands resting on the kneesif not front and getattr(inst, "dance_up", False):return -f * 2.5, -f * 2.9 # a partner dance: the far arm flung upif front and hand_item == "pillow":return f * 2.6, f * 2.9 # swung up overheadif front and hand_item == "bubbles":return f * .35, f * 2.6 # the wand at the lipsif front and hand_item == "lasso":return f * 2.7, f * 3.0# rule: relaxed arms hang slightly away from the body, elbows soft, hands a little forwardif big:return s * .04 - f * .03, s * .0 + f * .16 # close up: arms rest nearer the body8 unmodified linescol_skin = BLACKa1, a2 = arm_angles(s, front)sho = (scx + s * (sw - ar * 1.05), sh_y + h * .012 + ar)rch = (getattr(inst, "reach", None) or {}).get("front" if front else "back")if rch is not None and _night_on("inter"):# rule (night): reaching for a point (handing something over, an arm round a friend): two-bone IK,# elbow dropping below the linea1, a2 = _reach(sho, rch, ua, fa + ar * .75)elb = _seg(sho, ua, a1)wri = _seg(elb, fa, a2)wide = 1.3 if dress == "robe" else 1.014 unmodified lines_taper(cv, L, mid[0], mid[1], elb[0], elb[1], ar * .98, ar * .9, col_skin)_taper(cv, L, sho[0], sho[1], mid[0], mid[1], ar * 1.16, ar * 1.08, col_sleeve)hand_c = col_skin if role_name != "knight" else scale(metal, .8)if R.get("mittens"):hand_c = R["mittens"] if front else far(R["mittens"])hx2, hy2 = _seg(wri, ar * .75, a2)skin_ids(True)lit_ellipse(cv, L, hx2, hy2, ar * 1.0, ar * 1.12, hand_c, rot=a2 * -.3)29 unmodified linesif stripes == "pirate":# rule: pirate = bold horizontal red/white stripes on the shirtbase = shirt if int((py - sh_y) / max(1.2, h * .035)) % 2 == 0 else (200, 40, 45)elif stripes == "lamellar" and int((py - sh_y) / max(1.5, h * .032)) % 2 == 1 and py - sh_y > h * .02:# rule (night characters 2): lamellar armour = rows of plates, every other row a shade darker, gold lacingu_ = (px - tcx(py)) / max(1.5, h * .045)base = (205, 165, 70) if abs(u_ - round(u_)) < .12 else scale(shirt, .72)elif stripes == "reflect" and abs((py - sh_y) - h * .2) < h * .018:base = (235, 235, 210) # rule: firefighter coat = reflective silver band round the middleelif stripes == "jersey" and abs((px - tcx(py)) - f * h * .0) < h * .012:67 unmodified linesif big: # collar edgefor s_ in (-1, 1):cv.capsule(tx0 + s_ * rx * .5, sh_y - h * .004, tx0 + f * h * .005, sh_y + h * .045, max(.5, h * .004), scale(shirt, .78))if R.get("apron") and pose != "sitting":# rule (night): an apron = a bib from mid chest to the knees over the clothes, neck strap, waist tie, a pocketac = R["apron"]if R.get("apron_default") and sum(shirt) > 600:ac = (205, 90, 75) # a white apron vanishes on a white top: default to a red one thereat_, ab_ = sh_y + h * .07, y - h * .25aw0, aw1 = tw * .75, hw * 1.15cv.poly([(tx0 - aw0, at_), (tx0 + aw0, at_), (torso_x + aw1, ab_), (torso_x - aw1, ab_)],lambda px, py: L.shade(ac, (px - tx0) / (aw1 * 2.4), 0, .95))for s_ in (-1, 1):cv.capsule(tx0 + s_ * aw0 * .8, at_, tx0 + s_ * rx * .45, sh_y - h * .004, max(.5, h * .006), scale(ac, .8))cv.capsule(torso_x - hw * 1.05, waist_y, torso_x + hw * 1.05, waist_y, max(.5, h * .008), scale(ac, .8))cv.poly([(torso_x - aw1 * .45, waist_y + h * .05), (torso_x + aw1 * .45, waist_y + h * .05),(torso_x + aw1 * .43, waist_y + h * .1), (torso_x - aw1 * .43, waist_y + h * .1)], scale(ac, .9))if R.get("buttons"):for k in range(3): # chef's double-breasted buttonsfor s in (-1, 1):cv.ellipse(tx0 + f * h * .01 + s * h * .025, sh_y + h * (.08 + k * .07), max(.5, h * .007), max(.5, h * .007), (150, 150, 150))if sat is not None:# rule (night): a mail satchel = a strap across the chest from the far shoulder and a flap bag at the near hipsc_ = tuple(sat["color"]) if sat.get("color") else (125, 82, 45)cv.capsule(tx0 - f * sw * .75, sh_y + h * .01, torso_x + f * hw * .95, hip_y - h * .02, max(.6, h * .011), scale(sc_, .8))bx_, by_ = torso_x + f * hw * 1.05, hip_y + h * .02lit_box(cv, L, bx_ - h * .05, by_ - h * .035, bx_ + h * .05, by_ + h * .04, h * .008, sc_, side=f)cv.poly([(bx_ - h * .05, by_ - h * .035), (bx_ + h * .05, by_ - h * .035), (bx_ + h * .05, by_ + h * .005), (bx_ - h * .05, by_ + h * .005)],scale(sc_, .85))cv.poly([(bx_ - h * .03, by_ - h * .045), (bx_ + h * .03, by_ - h * .045), (bx_ + h * .025, by_ - h * .025), (bx_ - h * .025, by_ - h * .025)],(246, 244, 236))belt = R.get("belt")if belt and pose != "sitting":bcol = (200, 40, 40) if belt == "red" else (50, 38, 30)36 unmodified linescv.ellipse(head_cx + f * rx * .05, head_cy + ry * .98, nr * 1.05, ry * .2, scale(skin, .78), alpha=.75)# arm in front after the neck so a raised prop arm overlaps the chestskin_ids(False)rl = getattr(getattr(inst, "_rider", None), "_ride_leg", None)if rl is not None and _night_on("shoulders"):# (night characters 3, shoulders): the shoulder rider's near leg hangs over the carrier's chesthip_, knee_, foot_, lr_, col_, skc_, sc_, fu_, sho_, bt_ = rlhip_ = (hip_[0] + (knee_[0] - hip_[0]) * .35, hip_[1] + (knee_[1] - hip_[1]) * .35) # (keeps his chin clear)if sho_:_taper(cv, L, knee_[0], knee_[1], foot_[0], foot_[1], lr_ * .8, lr_ * .62, skc_)_taper(cv, L, hip_[0], hip_[1], knee_[0], knee_[1], lr_ * 1.12, lr_ * .85, col_)else:_taper(cv, L, knee_[0], knee_[1], foot_[0], foot_[1], lr_ * .88, lr_ * .72, col_)_taper(cv, L, hip_[0], hip_[1], knee_[0], knee_[1], lr_ * 1.15, lr_ * .9, col_)_shoe(cv, L, foot_[0], foot_[1], fu_, f, sc_, 1.0)near_hand = arm(f, True)skin_ids(True)inst.hand = near_handdog_ = getattr(inst, "leash_to", None)if dog_ is not None and _night_on("leash"):# rule (night): the leash = a slack line from the walker's hand to the dog's collar (dog drawn first)side_ = 1 if dog_.x >= x else -1cx_, cy_ = dog_.x + side_ * dog_.w * .3, dog_.y - dog_.h * .72hx_, hy_ = near_handpts_ = [(hx_ + (cx_ - hx_) * t, hy_ + (cy_ - hy_) * t + math.sin(t * math.pi) * h * .05) for t in [k_ / 8 for k_ in range(9)]]for a_, b_ in zip(pts_, pts_[1:]):cv.capsule(a_[0], a_[1], b_[0], b_[1], max(.5, h * .006), (190, 40, 45))hp = getattr(inst, "hug_hand_on", None)if hp is not None and _night_on("inter"):# rule (night): an arm round a friend drawn in front of this person: the hand shows on its far shoulderhc_, hr_, base_ = (skin if role_name not in ("knight", "ninja") else scale(metal, .8)), ar * 1.15, cv.cur_iddef _hand(p=hp[1], hc_=hc_, hr_=hr_, base_=base_):old = cv.cur_idcv.cur_id = base_lit_ellipse(cv, L, p[0], p[1], hr_, hr_ * 1.1, hc_)cv.cur_id = oldhp[0].__dict__.setdefault("after_draw", []).append(_hand)if role_name == "knight":# rule: knight = closed steel great-helm (rounded box) with a dark visor slit and a coloured plume48 unmodified linesface = R.get("face")_face(cv, L, head_cx, head_cy, rx, ry, f, skin, hair, eye_c, age == "old", fem,smile=face not in ("beard", "beard_long"))if getattr(inst, "expression", None) in ("surprised", "scared") and ry >= 6 and _night_on("pexpr"):from ..character2d import person_expr # night: eyes-first surprised / scared facesperson_expr(cv, head_cx, head_cy, rx, ry, f, skin, hair, inst.expression)elif getattr(inst, "expression", None) and ry >= 4.6:_expression(cv, head_cx, head_cy, rx, ry, f, skin, inst.expression)if inst.expression in ("sleepy", "winking", "asleep"):from ..character2d import expression_extra # wave 12expression_extra(cv, head_cx, head_cy, rx, ry, f, skin, inst.expression)inst.head = (head_cx, head_cy, rx, ry, f) # wave 12: anchor for worn hats / glasses / neckwear36 unmodified linescv.capsule(head_cx - f * rx * .8, head_cy - ry * .45, ex_ + f * rx * .2, head_cy + ry * .05, max(.5, ry * .07), BLACK)cv.ellipse(ex_, head_cy + ry * .14, max(.8, rx * .24), max(.8, ry * .2), BLACK)cv.ellipse(head_cx + f * rx * .2, head_cy + ry * .7, rx * .62, ry * .26, mix(skin, hair, .5), alpha=.7)elif face == "clown" and getattr(inst, "expression", None) in ("sad", "crying") and _night_on("sadclown"):# (night characters 3, sadclown; critic C27): the sad clown's paint - a big downturned red mouth, a blue tear# painted under the eye, brows tilted up in the middle; readable when the head is only a few pixels widecx_ = head_cx + f * rx * .2my_ = head_cy + ry * .66rw_ = max(.6, ry * .1)cv.capsule(cx_ - rx * .42, my_ + ry * .16, cx_, my_ - ry * .02, rw_, (220, 40, 50))cv.capsule(cx_, my_ - ry * .02, cx_ + rx * .42, my_ + ry * .16, rw_, (220, 40, 50))tx_ = head_cx + f * rx * .56cv.ellipse(tx_, head_cy + ry * .5, max(.8, rx * .1), max(1.0, ry * .17), (60, 120, 230))cv.poly([(tx_ - max(.8, rx * .09), head_cy + ry * .46), (tx_ + max(.8, rx * .09), head_cy + ry * .46),(tx_, head_cy + ry * .26)], (60, 120, 230))for e in (1, -1):ex = cx_ + f * e * rx * .34cv.capsule(ex - f * e * rx * .16, head_cy - ry * .2, ex + f * e * rx * .12, head_cy - ry * .06,max(.5, ry * .05), (40, 30, 40))cv.ellipse(head_cx + f * rx * .52, head_cy + ry * .34, max(.9, rx * .22), max(.9, ry * .2), (230, 30, 35))elif face == "clown":cv.ellipse(head_cx + f * rx * .52, head_cy + ry * .38, max(.9, rx * .26), max(.9, ry * .24), (230, 30, 35))cv.capsule(head_cx - rx * .1 + f * rx * .1, head_cy + ry * .62, head_cx + f * rx * .5 + rx * .2, head_cy + ry * .62,328 unmodified linescv.poly([(px + bw, py - bw * .6), (px, py), (px + bw, py + bw * .6)], second if i % 4 else c)prev = (px, py)# string trailing down-and-sideways out of frame (rule: a line to the ground says "flying kite")hb = getattr(inst, "bound", None)if inst.pose == "flying" and hb is not None and getattr(hb, "hand", None) and _night_on("inter"):# rule (night): a held kite's string runs to the flyer's hand, sagging a little (it used to run past# the girl to the ground - critic C6)hx_, hy_ = hb.handpts = []for i in range(9):t = i / 8pts.append((C[0] + (hx_ - C[0]) * t, C[1] + h * .05 + (hy_ - C[1] - h * .05) * t + math.sin(t * math.pi) * h * .25))for a_, b_ in zip(pts, pts[1:]):cv.capsule(a_[0], a_[1], b_[0], b_[1], max(.4, h * .005), (245, 245, 245), alpha=.6)elif inst.pose == "flying":sx = 1 if x < cv.w / 2 else -1cv.capsule(C[0], C[1] + h * .05, C[0] + sx * h * 1.2, C[1] + h * 2.5, max(.4, h * .005), (245, 245, 245), alpha=.45)221 unmodified lines# ---------------------------------------------------------------- registrydef _draw_person_then(cv, ctx, inst):draw_person(cv, ctx, inst)from ..character2d import run_after # night: what a partner drawn earlier puts over this person (a hugging arm)run_after(inst)concept("person", height=1.75, aspect=.38, row="front", setting="street", on_top=.55, default_color=None,synonyms=["man", "woman", "boy", "girl", "child", "kid", "guy", "lady", "pedestrian", "human", "adult","teenager", "student", "player", "tourist"] + ROLE_SYNONYMS,2 unmodified lines"fireman": "firemen", "firewoman": "firewomen", "businessman": "businessmen","businesswoman": "businesswomen", "gentleman": "gentlemen", "old man": "old men","old woman": "old women", "elderly man": "elderly men", "elderly woman": "elderly women","baby boy": "baby boys"})(_draw_person_then)concept("umbrella", height=1.0, aspect=1.15, row="front", setting="beach", on_top=1.0, default_color=(215, 50, 60),synonyms=["parasol", "beach umbrella"])(draw_umbrella)concept("tie", height=.42, aspect=.38, row="front", setting="table", default_color=(170, 30, 45),
287 unmodified lines288289290291292293294287 unmodified linesreturn L.shade((200, 195, 185) if mortar else scale(base, k), 0, 0, 1)cv.poly([(x0, y), (x1, y), (x1, y0), (x0, y0)], face)cv.poly([(x0 - 1, y0), (x1 + 1, y0), (x1 + 1, y0 - h * .07), (x0 - 1, y0 - h * .07)], L.shade((190, 185, 175), 0, -1, .3))if "graffiti" in inst.word:# rule: graffiti = bold overlapping colour blobs and outlines, never lettersfor k in range(6):col = inst.rng.choice([(240, 70, 120), (60, 200, 230), (250, 210, 40), (120, 220, 90), (160, 90, 230)])287 unmodified lines288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335287 unmodified linesreturn L.shade((200, 195, 185) if mortar else scale(base, k), 0, 0, 1)cv.poly([(x0, y), (x1, y), (x1, y0), (x0, y0)], face)cv.poly([(x0 - 1, y0), (x1 + 1, y0), (x1 + 1, y0 - h * .07), (x0 - 1, y0 - h * .07)], L.shade((190, 185, 175), 0, -1, .3))from ..atmos import on as _aonif "graffiti" in inst.word and _aon("graffiti2"):# rule (night pixel2, graffiti2): graffiti = a row of fat bubble-letter shapes (rounded slabs of varied# width, dark outline, two-tone fill, white shine, paint drips) plus thin spray tags and a star / arrow# (critic P15: the old overlapping ovals read as hats); still abstract, so no misspelt wordsrng = inst.rngrows = 1 if h < 30 * u else 2for r_ in range(rows):col = rng.choice([(240, 70, 120), (60, 200, 230), (250, 210, 40), (120, 220, 90), (160, 90, 230), (250, 130, 40)])col2 = rng.choice([(250, 250, 250), (30, 30, 40), (250, 210, 40), (60, 200, 230)])lh = h * (.42 if rows == 1 else .3)cy = y0 + h * (.5 if rows == 1 else (.3 + .42 * r_))gx = x0 + w * rng.uniform(.05, .35)gend = gx + w * rng.uniform(.4, .6) # (critic2: edge-to-edge rows read as a pattern; leave bare brick)alt = rng.choice([(240, 70, 120), (60, 200, 230), (250, 210, 40), (120, 220, 90), (160, 90, 230), (250, 130, 40)])base_col = colwhile gx < min(gend, x1 - w * .08):col = alt if rng.random() < .3 else base_collw = lh * rng.uniform(.7, 1.15)tilt = rng.uniform(-.2, .2) * lhlh_ = lh * rng.uniform(.85, 1.15)pts = [(gx, cy - lh_ / 2 + tilt), (gx + lw, cy - lh_ / 2 - tilt), (gx + lw, cy + lh_ / 2 - tilt), (gx, cy + lh_ / 2 + tilt)]o = max(1.0, 1.3 * u)cv.poly([(px_ - o if i in (0, 3) else px_ + o, py_ - o if i < 2 else py_ + o) for i, (px_, py_) in enumerate(pts)], (22, 20, 28))cv.poly(pts, col)cv.poly([pts[0], pts[1], (pts[1][0], (pts[1][1] + pts[2][1]) / 2), (pts[0][0], (pts[0][1] + pts[3][1]) / 2)],tuple(min(255, int(c_ * 1.15 + 20)) for c_ in col))if rng.random() < .5: # a counter hole, like a bubble O / A / Phx, hy = gx + lw / 2, cy - lh * .05cv.ellipse(hx, hy, lw * .16, lh * .14, (22, 20, 28))cv.ellipse(gx + lw * .25, cy - lh * .3, max(.6, .6 * u), max(.6, .6 * u), (255, 255, 255)) # shineif rng.random() < .45: # dripdx_ = gx + rng.uniform(.2, .8) * lwcv.capsule(dx_, cy + lh / 2, dx_, cy + lh / 2 + rng.uniform(1.5, 4) * u, max(.4, .35 * u), col)gx += lw * rng.uniform(.6, .8)# a thin spray tag line through / under the letters in the second colourtx = x0 + w * rng.uniform(.1, .5)for k in range(14):ax = tx + k * w * .03cv.capsule(ax, cy + lh * .62 + math.sin(k * 1.3) * 2 * u, ax + w * .03, cy + lh * .62 + math.sin((k + 1) * 1.3) * 2 * u,max(.4, .4 * u), col2)elif "graffiti" in inst.word:# rule: graffiti = bold overlapping colour blobs and outlines, never lettersfor k in range(6):col = inst.rng.choice([(240, 70, 120), (60, 200, 230), (250, 210, 40), (120, 220, 90), (160, 90, 230)])
174 unmodified lines17517617717817918050 unmodified lines231232233234235236784 unmodified lines102110221023174 unmodified linessynonyms=["stone bridge", "arch bridge", "footbridge", "viaduct", "aqueduct"], default_color=(178, 160, 132))def draw_bridge(cv, ctx, inst):L, h, w, x, y = ctx.L, inst.h, inst.w, inst.x, inst.ystone = hazed(ctx, inst, color_of(inst))x0, x1 = x - w / 2, x + w / 2deck = y - h * .7650 unmodified linescv.ellipse(lx, y - h * 1.04, h * .16, h * .16, (255, 210, 120), alpha=.2)# ---------------------------------------------------------------- windmill@concept("windmill", height=15, aspect=.9, row="back", setting="field", on_top=.6,synonyms=["wind mill", "dutch windmill", "mill"], default_color=(150, 100, 65))784 unmodified lineslit_capsule(cv, L, x - f * s * .1, fy - s * .62, x - f * s * .14, fy - s * .3, s * .04, c) # lowered armfor k in (.15, .3, .45): # robe foldscv.capsule(x + s * (k - .3) * .3, fy - s * .55, x + s * (k - .3) * .45, fy, max(.4, s * .008), scale(c, .75), alpha=.6)174 unmodified lines17517617717817918018118218350 unmodified lines234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305784 unmodified lines10901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124174 unmodified linessynonyms=["stone bridge", "arch bridge", "footbridge", "viaduct", "aqueduct"], default_color=(178, 160, 132))def draw_bridge(cv, ctx, inst):L, h, w, x, y = ctx.L, inst.h, inst.w, inst.x, inst.ykind = (getattr(inst, "attrs", None) or {}).get("bridge_kind")if kind in ("rope", "plank"):return _strung_bridge(cv, ctx, inst, kind)stone = hazed(ctx, inst, color_of(inst))x0, x1 = x - w / 2, x + w / 2deck = y - h * .7650 unmodified linescv.ellipse(lx, y - h * 1.04, h * .16, h * .16, (255, 210, 120), alpha=.2)def _strung_bridge(cv, ctx, inst, kind):"""rule (language shift 2): a rope bridge = planks hung on a sagging curve between two post pairs on rocky banks,two hand ropes above with thin hangers down to the deck, the gap (chasm / water) showing between the planks.A wooden (plank) bridge = a low timber deck on posts with a simple rail, over a strip of water."""L, h, w, x, y, rng = ctx.L, inst.h, inst.w, inst.x, inst.y, inst.rngx0, x1 = x - w / 2, x + w / 2wood = hazed(ctx, inst, color_of(inst) if inst.color else (150, 108, 66))rope = hazed(ctx, inst, (196, 168, 118))dark = (40, 32, 28)t_ = lambda k: max(.6, h * k)if kind == "plank":deck = y - h * .32if ctx.place not in ("water", "snow", "desert"):wc = (95, 150, 200) if not night(ctx) else (40, 55, 85)cv.poly([(x0 + w * .04, y), (x1 - w * .04, y), (x1 - w * .08, y - h * .2), (x0 + w * .08, y - h * .2)], wc)for k in range(5): # posts into the water / groundpx = x0 + w * (.06 + .88 * k / 4)rect(cv, px - t_(.035), deck, px + t_(.035), y, L.flat(darker(wood, .75), .6))rect(cv, x0, deck - h * .07, x1, deck + h * .03, L.flat(wood, .8))n = max(8, int(w / max(2.0, h * .09)))for i in range(n + 1): # plank seamspx = x0 + w * i / ncv.capsule(px, deck - h * .07, px, deck + h * .03, .5, darker(wood, .7), alpha=.6)for i in range(7): # rail posts + top railpx = x0 + w * (.02 + .96 * i / 6)rect(cv, px - t_(.018), deck - h * .45, px + t_(.018), deck - h * .07, L.flat(wood, .75))rect(cv, x0, deck - h * .48, x1, deck - h * .42, L.flat(lighter(wood, .1), .85))returndeck_y = lambda u: y - h * .6 + h * .24 * math.sin(math.pi * u)rail_y = lambda u: y - h * .86 + h * .2 * math.sin(math.pi * u)# rocky banks rising to the anchors, the chasm between themrock = hazed(ctx, inst, (150, 120, 95) if ctx.place == "desert" else (120, 115, 110))for side in (-1, 1):ex = x0 if side < 0 else x1bw = w * .16pts = [(ex - side * w * .02, y), (ex + side * bw, y), (ex + side * bw * .85, y - h * .35), (ex + side * bw * .6, y - h * .6),(ex - side * w * .02, y - h * .64)]cv.poly(pts, lambda px, py: L.shade(darker(rock, .85) if noise(px * .3, py * .3, 5) > .6 else rock, 0, 0, 1))cv.ellipse(x, y - h * .02, w * .3, h * .025, (0, 0, 0), alpha=.18) # soft shadow of the deck far belowfor side in (-1, 1): # anchor postspx = x0 + w * .03 if side < 0 else x1 - w * .03rect(cv, px - t_(.03), y - h * 1.02, px + t_(.03), y - h * .6, L.flat(darker(wood, .8), .6))n = max(10, int(w / max(2.2, h * .075)))for i in range(n): # planks with gapsu0, u1 = (i + .12) / n, (i + .88) / nif rng.random() < .04:continuea, b = x0 + w * .03 + (w * .94) * u0, x0 + w * .03 + (w * .94) * u1# rule: seen a little from above, each plank is a short slab across the deck with a dark gap after itcv.poly([(a, deck_y(u0) - t_(.035)), (b, deck_y(u1) - t_(.035)), (b, deck_y(u1) + t_(.05)), (a, deck_y(u0) + t_(.05))],L.flat(wood if i % 3 else darker(wood, .88), .75))cv.poly([(a, deck_y(u0) + t_(.05)), (b, deck_y(u1) + t_(.05)), (b, deck_y(u1) + t_(.075)), (a, deck_y(u0) + t_(.075))],L.flat(darker(wood, .6), .5))m = 24for side_off in (0.0, h * .03): # two hand ropes (near + far), two deck ropesfor j in range(m):u0, u1 = j / m, (j + 1) / mxa, xb = x0 + w * .03 + w * .94 * u0, x0 + w * .03 + w * .94 * u1cv.capsule(xa, rail_y(u0) + side_off, xb, rail_y(u1) + side_off, t_(.012), rope)cv.capsule(xa, deck_y(u0) + side_off * .3, xb, deck_y(u1) + side_off * .3, t_(.01), darker(rope, .8))for j in range(1, 9): # hangersu = j / 9xa = x0 + w * .03 + w * .94 * ucv.capsule(xa, rail_y(u), xa, deck_y(u), t_(.006), darker(rope, .9), alpha=.85)# ---------------------------------------------------------------- windmill@concept("windmill", height=15, aspect=.9, row="back", setting="field", on_top=.6,synonyms=["wind mill", "dutch windmill", "mill"], default_color=(150, 100, 65))784 unmodified lineslit_capsule(cv, L, x - f * s * .1, fy - s * .62, x - f * s * .14, fy - s * .3, s * .04, c) # lowered armfor k in (.15, .3, .45): # robe foldscv.capsule(x + s * (k - .3) * .3, fy - s * .55, x + s * (k - .3) * .45, fy, max(.4, s * .008), scale(c, .75), alpha=.6)# ---------------------------------------------------------------- lattice tower (language shift 2)@concept("eiffel tower", height=30, aspect=.5, row="mid", setting="park", on_top=.98,synonyms=["the eiffel tower", "eiffel", "lattice tower", "radio tower", "pylon", "transmission tower"],default_color=(95, 75, 60))def draw_eiffel(cv, ctx, inst):"""rule: a lattice tower = two legs curving in to a needle (the profile is concave), a big arch between the legs,two platform bands, and cross-bracing drawn as an X lattice so it reads as open iron, not a solid spire"""L, h, w, x, y = ctx.L, inst.h, inst.w, inst.x, inst.yiron = hazed(ctx, inst, color_of(inst))hw = lambda t: w * .48 * (1 - t) ** 2.2 + w * .02 # half width at height fraction t (concave)lat = max(1.5, h * .022)t1, t2 = .2, .5for side in (-1, 1): # legs: outer edge + inner edge, filled with latticepts_o = [(x + side * hw(t), y - h * t) for t in [k / 24 for k in range(25)]]pts_i = [(x + side * max(0.0, hw(t) - w * (.17 if t < t1 else .1) * (1 - t) - w * .012), y - h * t) for t in [k / 24 for k in range(25)]]poly = pts_o + pts_i[::-1]cv.poly(poly, lambda px, py: darker(iron, .7) if (int((px + py) / lat) + int((px - py) / lat)) % 3 == 0else L.shade(iron, 0, 0, 1))# the arch between the legs under the first platformn = 14arch = [(x + hw(0) * .62 * math.cos(math.pi * k / n), y - h * t1 * .55 * math.sin(math.pi * k / n) - h * .02) for k in range(n + 1)]for a, b in zip(arch, arch[1:]):cv.capsule(a[0], a[1], b[0], b[1], max(.6, h * .008), darker(iron, .85))for t, k in ((t1, .045), (t2, .03)): # platformsrect(cv, x - hw(t) - w * .03, y - h * t - h * k * .5, x + hw(t) + w * .03, y - h * t + h * k * .5, L.flat(darker(iron, .8), .8))cv.capsule(x, y - h * .97, x, y - h, max(.5, w * .012), darker(iron, .7)) # needleif night(ctx): # rule: lit at night, warm lamps up the legsfor k in range(14):t = .05 + .85 * k / 13cv.ellipse(x + (hw(t) - w * .03) * (1 if k % 2 else -1), y - h * t, max(.6, h * .006), max(.6, h * .006), (255, 210, 120))
369 unmodified lines370371372373374375369 unmodified linescv.poly(rrect(b0, y - h, b1, chassis, h * .03), vgrad(L, paint, y - h, chassis, 1.0))# rule: a slightly lighter panel inset on the box keeps it from reading as a flat blobcv.poly(rrect(X(-w * .46), y - h * .92, X(w * .12), chassis - h * .08, h * .02), vgrad(L, lighter(paint, .12), y - h * .92, chassis))# chassis railcv.poly([(X(-w * .5), chassis), (X(w * .5), chassis), (X(w * .5), chassis + h * .07), (X(-w * .5), chassis + h * .07)], (45, 45, 48))# cab with sloped windshield369 unmodified lines370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403369 unmodified linescv.poly(rrect(b0, y - h, b1, chassis, h * .03), vgrad(L, paint, y - h, chassis, 1.0))# rule: a slightly lighter panel inset on the box keeps it from reading as a flat blobcv.poly(rrect(X(-w * .46), y - h * .92, X(w * .12), chassis - h * .08, h * .02), vgrad(L, lighter(paint, .12), y - h * .92, chassis))if (inst.word or "").startswith(("ice cream", "icecream")) and __import__("os").environ.get("PYDRAW_LANG_OFF", "").find("icecreamtruck") < 0:# rule (language shift 2, critic L39): an ice cream truck = pastel box with a scalloped awning over a serving# window, a candy stripe along the bottom and a giant cone on the roof (a plain white box truck said nothing)pastel = (165, 225, 205) if not inst.color or inst.color == "white" else paintcv.poly(rrect(X(-w * .46), y - h * .92, X(w * .12), chassis - h * .08, h * .02), vgrad(L, pastel, y - h * .92, chassis))wx0, wx1, wy0, wy1 = X(-w * .36), X(w * .02), y - h * .78, y - h * .48cv.poly(rrect(min(wx0, wx1), wy0, max(wx0, wx1), wy1, h * .015), (70, 60, 70))cv.poly(rrect(min(wx0, wx1), wy1 - h * .03, max(wx0, wx1), wy1 + h * .02, h * .01), (235, 235, 240)) # counterfor k in range(6): # tubs of colours on the countertx = min(wx0, wx1) + (k + .5) * abs(wx1 - wx0) / 6cv.ellipse(tx, wy1 - h * .045, abs(wx1 - wx0) / 16, h * .025, [(250, 240, 220), (120, 70, 40), (240, 150, 170), (150, 210, 160), (250, 220, 120), (180, 140, 220)][k])n = 7for k in range(n): # scalloped awninga0 = min(wx0, wx1) - w * .03 + k * (abs(wx1 - wx0) + w * .06) / na1 = a0 + (abs(wx1 - wx0) + w * .06) / ncol = (230, 70, 90) if k % 2 == 0 else (250, 250, 250)cv.poly([(a0, wy0 - h * .14), (a1, wy0 - h * .14), (a1, wy0), (a0, wy0)], col)cv.ellipse((a0 + a1) / 2, wy0, (a1 - a0) / 2, h * .045, col)for k in range(10): # candy stripe along the bottom of the boxsx0 = min(b0, b1) + k * abs(b1 - b0) / 10cv.poly([(sx0, chassis - h * .07), (sx0 + abs(b1 - b0) / 20, chassis - h * .07), (sx0 + abs(b1 - b0) / 10, chassis - h * .02),(sx0 + abs(b1 - b0) / 20, chassis - h * .02)], (230, 70, 90))cx_, top_ = X(-w * .17), y - hcv.poly([(cx_ - h * .16, top_ - h * .2), (cx_ + h * .16, top_ - h * .2), (cx_, top_ + h * .02)],lambda px, py: (215, 160, 90) if int((px + py) / max(1.5, h * .04)) % 2 else (190, 130, 70))for k, (dx, dy, c_) in enumerate(((-.08, -.27, (240, 130, 160)), (.08, -.27, (250, 240, 220)), (0, -.39, (120, 70, 45)))):cv.ellipse(cx_ + h * dx, top_ + h * dy, h * .12, h * .1, L.shade(c_, 0, -.4, .9))cv.ellipse(cx_, top_ - h * .5, h * .04, h * .04, (200, 30, 40))# chassis railcv.poly([(X(-w * .5), chassis), (X(w * .5), chassis), (X(w * .5), chassis + h * .07), (X(-w * .5), chassis + h * .07)], (45, 45, 48))# cab with sloped windshield
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361"""Conditions drawn on any object (pixel renderer): the parser's attrs["cond"] (pydraw/language.py) -> a pass over theobject's own pixels (its id mask) right after it is drawn, before the pixel-art finish. Rules, per condition class:
torn ragged silhouette: bites out of the edge and a few holes show what was behind (snapshot), dark hem rusty orange-brown corrosion blotches (low-frequency noise), darker pits weathered colour drains toward grey-beige, vertical streaks of grime, lighter top broken dark cracks (random walks from a few seeds) with a lit lip; dents as dark blotches mossy green moss on top faces and the bottom, a few leaf tufts past the silhouette moldy grey-green spots shiny more contrast + saturation, a hard specular streak on the lit side, a sparkle or two glowing lighter body and a soft halo of its own colour around it withered colour toward dry brown, desaturated dirty brown-grey grime, heavier near the ground burnt charred black from the edges in, a few embers frosty white-blue rime on top faces, cooler overall wet darker, richer, short highlight streaks twisted the shape bends: rows shift sideways along a wave that grows with height (base stays put) stout/thin the shape widens / narrows about its centre line scruffy a fuzzy outline: pixels stick out and bite in along the edgeEvery class works from the mask alone, so it applies to any concept (hand-drawn, open-vocabulary, derived).Knob: PYDRAW_LANG_OFF=condpx (or PYDRAW_LANG=0) turns the drawing off; the parse still records the conditions."""import math
import numpy as np
def snapshot(cv): return [[p[:] for p in row] for row in cv.px], [row[:] for row in cv.ids]
def _noise(h, w, scale, seed): """smooth value noise in [0, 1] at a pixel scale (cells of `scale` px)""" rs = np.random.RandomState(seed) gh, gw = int(h / scale) + 3, int(w / scale) + 3 g = rs.rand(gh, gw) ys = np.arange(h) / scale xs = np.arange(w) / scale y0, x0 = ys.astype(int), xs.astype(int) fy, fx = ys - y0, xs - x0 fy, fx = fy * fy * (3 - 2 * fy), fx * fx * (3 - 2 * fx) a = g[y0][:, x0] b = g[y0][:, x0 + 1] c = g[y0 + 1][:, x0] d = g[y0 + 1][:, x0 + 1] top = a + (b - a) * fx[None, :] bot = c + (d - c) * fx[None, :] return top + (bot - top) * fy[:, None]
def _fbm(h, w, scale, seed): return (.6 * _noise(h, w, scale, seed) + .3 * _noise(h, w, scale / 2.3, seed + 1) + .1 * _noise(h, w, scale / 5, seed + 2))
def _edge(m): e = np.zeros_like(m) e[1:-1, 1:-1] = m[1:-1, 1:-1] & ~(m[:-2, 1:-1] & m[2:, 1:-1] & m[1:-1, :-2] & m[1:-1, 2:]) return e
def _top(m): """mask pixels with empty space above (top faces)""" t = np.zeros_like(m) t[1:] = m[1:] & ~m[:-1] t[0] = m[0] return t
def _grow(m, r=1): o = m.copy() for _ in range(r): n = o.copy() n[1:] |= o[:-1] n[:-1] |= o[1:] n[:, 1:] |= o[:, :-1] n[:, :-1] |= o[:, 1:] o = n return o
def _mix(A, m, col, t): t = np.clip(t, 0, 1) if np.ndim(t): t = t[..., None] A[m] = A[m] * (1 - (t[m] if np.ndim(t) else t)) + np.asarray(col, float) * (t[m] if np.ndim(t) else t)
def _shade(A, m): """per-pixel shading of an object relative to its median: a recolour keeps windows, wheels and form shadows""" L = _lum(A) med = max(1.0, float(np.median(L[m]))) return np.clip(L / med, .35, 1.35)
def _lum(A): return A[..., 0] * .3 + A[..., 1] * .59 + A[..., 2] * .11
def apply(cv, oid, conds, snap, inst, trace, seed=0): if not conds: return A = np.asarray(cv.px, float) I = np.asarray(cv.ids, float) m = np.floor(I) == oid if m.sum() < 6: return S = np.asarray(snap[0], float) SI = np.asarray(snap[1], float) H, W = m.shape ys, xs = np.nonzero(m) y0, y1, x0, x1 = ys.min(), ys.max(), xs.min(), xs.max() bh, bw = y1 - y0 + 1, x1 - x0 + 1 sz = max(bh, bw) seed = (seed * 131 + oid * 17) % 100000 lx = getattr(cv, "light_dx", None) lit_left = True if lx is None else lx < 0 yy, xx = np.mgrid[0:H, 0:W] rel_h = np.clip((y1 - yy) / max(1, bh), 0, 1) # 0 at the base, 1 at the top done = [] for c in conds: if c in ("twisted", "stout", "thin"): # geometry: resample the object's pixels; uncovered pixels get what was behind (snapshot) obj, oids = A.copy(), I.copy() cx = (x0 + x1) / 2 src_y = yy if c == "twisted": amp = max(2.0, bw * .13) dx = amp * np.sin(rel_h * math.pi * 2.2 + (seed % 7)) * rel_h ** .7 dx = dx + amp * .7 * rel_h * (1 if seed % 2 else -1) # a lean src_x = np.rint(xx - dx).astype(int) elif bh >= bw * .8: # tall things (people, penguins, bottles, trees): wider / narrower, most at the middle (a belly, a waist) K = 1.34 if c == "stout" else .72 prof = .45 + .55 * np.sin(math.pi * np.clip(rel_h * 1.05, 0, 1)) k = 1 + (K - 1) * prof src_x = np.rint(cx + (xx - cx) / k).astype(int) else: # wide things (animals side on, cars): the body above the legs gets deeper / shallower, legs untouched K = 1.25 if c == "stout" else .78 ya = y1 - .38 * bh src_x = xx src_y = np.where(yy < ya, np.rint(ya - (ya - yy) / K), yy).astype(int) src_x = np.rint(cx + (xx - cx) / (1 + (K - 1) * .25)).astype(int) src_x = np.clip(src_x, 0, W - 1) src_y = np.clip(src_y, 0, H - 1) take = m[src_y, src_x] region = m | take A[region] = S[region] I[region] = SI[region] A[take] = obj[src_y[take], src_x[take]] I[take] = oids[src_y[take], src_x[take]] m = np.floor(I) == oid done.append(c) continue e = _edge(m) if c == "torn": from scipy.ndimage import distance_transform_edt thick = _grow(distance_transform_edt(m) >= 2.5, 2) & m # rule: thin parts (a pole, a string) stay whole n = _noise(H, W, max(1.5, sz / 12), seed) bite = e & (n > .58) & thick bite = _grow(bite, max(1, int(sz / 22))) & thick hn = _fbm(H, W, max(2, sz / 7), seed + 5) holes = thick & (hn > .8) & (rel_h < .95) & ~_grow(e, 2) cut = bite | holes if cut.sum() > .25 * m.sum(): cut = bite A[cut] = S[cut] I[cut] = SI[cut] hem = _grow(cut, 1) & m & ~cut A[hem] *= .62 elif c == "rusty": n = _fbm(H, W, max(2, sz / 6), seed) t = np.where(m, np.clip((n - .45) * 3.2, 0, .85), 0) _mix(A, m, (150, 72, 30), t) pit = m & (_noise(H, W, 1.2, seed + 3) > .9) A[pit] *= .55 elif c == "weathered": L = _lum(A)[..., None] A[m] = (A * .45 + L * .55 * np.array([1.02, 1.0, .94]))[m] streak = m & (_noise(H, W, 1, seed)[0][None, :].repeat(H, 0) > .7) & (_noise(H, W, max(2, sz / 5), seed + 1) > .45) A[streak] *= .8 A[m & _top(m)] = np.minimum(255, A[m & _top(m)] * 1.12) elif c == "broken": rs = np.random.RandomState(seed) crack = np.zeros_like(m) for _ in range(2 + sz // 60): py, px_ = ys[rs.randint(len(ys))], xs[rs.randint(len(xs))] ang = rs.uniform(0, 2 * math.pi) for step in range(int(sz * .45)): ang += rs.uniform(-.7, .7) py, px_ = py + math.sin(ang), px_ + math.cos(ang) iy, ix = int(round(py)), int(round(px_)) if not (0 <= iy < H and 0 <= ix < W) or not m[iy, ix]: break crack[iy, ix] = True lip = np.zeros_like(m) lip[:-1] = crack[1:] lip &= m & ~crack A[crack] = A[crack] * .3 A[lip] = np.minimum(255, A[lip] * 1.25 + 12) dn = m & (_noise(H, W, max(2, sz / 9), seed + 9) > .78) A[dn] *= .75 elif c == "mossy": n = _fbm(H, W, max(2, sz / 8), seed) bias = np.maximum(1 - rel_h * 2.2, 0) * .5 + _grow(_top(m), max(1, sz // 30)) * .45 t = np.where(m, np.clip((n + bias - .62) * 3, 0, .9), 0) moss = np.array([68, 112, 44]) * (.8 + .4 * _noise(H, W, 1.5, seed + 2))[..., None] A[m] = A[m] * (1 - t[m][:, None]) + moss[m] * t[m][:, None] # a few tufts past the top edge tufts = _grow(_top(m) & (_noise(H, W, 1.3, seed + 4) > .8), 1) & ~m & (yy < y1) A[tufts] = moss[tufts] * .9 I[tufts] = oid elif c == "moldy": spots = m & (_noise(H, W, max(1.2, sz / 20), seed) > .72) _mix(A, spots, (150, 160, 120), .75) A[m & ~spots] = A[m & ~spots] * .9 + 8 elif c == "shiny": mean = A[m].mean(0) A[m] = np.clip(mean + (A[m] - mean) * 1.25, 0, 255) L = _lum(A)[..., None] A[m] = np.clip(L[m] + (A[m] - L[m]) * 1.2, 0, 255) u = (xx - x0) / max(1, bw) u = u if lit_left else 1 - u spec = m & ~e & (np.abs(u - .22 - (1 - rel_h) * .1) < max(.05, 1.2 / bw)) & (rel_h > .35) & (rel_h < .9) A[spec] = A[spec] * .25 + 230 rs = np.random.RandomState(seed) for _ in range(1 + sz // 70): k_ = rs.randint(len(ys)) sy, sx = ys[k_], xs[k_] if rel_h[sy, sx] < .5: continue r = max(1, sz // 30) for d in range(-r, r + 1): for (py, px_) in ((sy + d, sx), (sy, sx + d)): if 0 <= py < H and 0 <= px_ < W: A[py, px_] = (255, 255, 245) elif c == "glowing": L_ = _lum(A)[m] col = np.minimum(255, A[m][L_ >= np.percentile(L_, 75)].mean(0) * 1.15 + 60) # its light colours, not the mean A[m] = np.minimum(255, A[m] * 1.1 + 30) from scipy.ndimage import distance_transform_edt d = distance_transform_edt(~m) R = max(3, sz * .16) # rule: a pixel-art glow = two flat stepped rings, not a smooth gradient the palette would dither away for r_, t_ in ((R, .35), (R * .5, .6)): ring = ~m & (d < r_) & (np.floor(I) != oid) A[ring] = A[ring] * (1 - t_) + col * t_ elif c == "withered": L = _lum(A)[..., None] dry = np.array([150, 112, 62]) * (L / 140) A[m] = (A * .35 + dry * .65)[m] elif c == "dirty": n = _fbm(H, W, max(2, sz / 7), seed) t = np.where(m, np.clip((n + (1 - rel_h) * .35 - .55) * 2.5, 0, .7), 0) _mix(A, m, (92, 76, 58), t) elif c == "burnt": from scipy.ndimage import distance_transform_edt d = distance_transform_edt(m) n = _fbm(H, W, max(2, sz / 8), seed) t = np.where(m, np.clip(1.1 - d / max(2, sz * .12) + (n - .5) * .9, 0, .92), 0) _mix(A, m, (26, 20, 18), t) emb = m & (t > .6) & (_noise(H, W, 1.1, seed + 3) > .9) A[emb] = (255, 120, 30) elif c == "frosty": A[m] = np.minimum(255, A[m] * .75 + np.array([50, 62, 78])) rime = _grow(_top(m), max(1, sz // 40)) & m A[rime] = (236, 244, 255) elif c == "wet": L = _lum(A)[..., None] A[m] = np.clip((L + (A - L) * 1.25) * .78, 0, 255)[m] hl = m & ~e & (_noise(H, W, 1, seed)[0][None, :].repeat(H, 0) > .88) & (_noise(H, W, 2, seed + 1) > .6) A[hl] = np.minimum(255, A[hl] * .4 + 170) elif c == "scruffy": n = _noise(H, W, 1, seed) out_ = _grow(m, 1) & ~m & (n > .6) & (yy < y1 - 1) near = np.clip(np.rint(np.stack([yy, xx], -1)), 0, None) A[out_] = A[m].mean(0) * .8 I[out_] = oid bite = e & (n < .25) A[bite] = S[bite] I[bite] = SI[bite] elif c.startswith("skin_"): # "made of X" stuff the pixel renderer only tinted: X's own marks on the tinted object (rule: chips on # cookie, icing lines on gingerbread, holes in cheese, frosting + drips on cake, stripes on candy, # rind + seeds on watermelon, crust on bread) k_ = c[5:] rs = np.random.RandomState(seed) r_ = max(1, int(round(sz / 40))) if k_ == "cookie": # rule: a cookie = warm golden-brown dough, a few big round chips (critic: small specks read as bugs) sh = _shade(A, m) A[m] = np.clip(np.array([214, 156, 84]) * np.clip(sh[m], .7, 1.2)[:, None], 0, 255) from scipy.ndimage import distance_transform_edt R = max(1.5, sz / 32) inner = np.argwhere(m & (distance_transform_edt(m) > R + 1)) rs_ = np.random.RandomState(seed) nchip = max(3, int(m.sum() / (R * R * 40))) for _ in range(min(nchip, len(inner))): cy, cx = inner[rs_.randint(len(inner))] disc = ((yy - cy) ** 2 + (xx - cx) ** 2 <= R * R) & m A[disc] = (72, 42, 24) hl = (yy == cy - int(R * .5)) & (np.abs(xx - cx + int(R * .4)) <= 0) & disc A[hl] = (120, 80, 50) elif k_ == "gingerbread": from scipy.ndimage import distance_transform_edt dt = distance_transform_edt(m) # rule: piped icing = a zigzag line just inside the top edge of the thick parts, plus a few dots top = _top(m) & (dt[np.clip(yy + 3, 0, H - 1), xx] >= 3) ys_, xs_ = np.nonzero(top) for y_, x_ in zip(ys_, xs_): yz = y_ + 2 + (x_ // 2) % 2 if yz < H and m[yz, x_]: A[yz, x_] = (250, 246, 240) pts = m & (dt >= 3) & (np.random.RandomState(seed).rand(H, W) < .01) A[pts] = (250, 246, 240) elif k_ == "cheese": holes = m & ~_grow(e, 1) & (_noise(H, W, max(1.5, sz / 9), seed) > .76) A[holes] = A[holes] * .78 lip = _grow(holes, 1) & m & ~holes lip[1:] &= holes[:-1] A[lip] = np.minimum(255, A[lip] * 1.12) elif k_ in ("cake", "frosting", "ice cream"): # rule: frosting = a cap over the top faces with a few short drips, keeping the form's shading cap = _grow(_top(m), max(2, int(sz / 12))) & m cols = np.nonzero(cap.any(0))[0] drip = np.zeros_like(m) for x_ in cols[::max(3, int(sz / 9))]: ys_ = np.nonzero(cap[:, x_])[0] y_ = ys_.max() drip[y_:y_ + 2 + (x_ * 7 % 5), x_] = True fr = (cap | drip) & m sh = _shade(A, m) col_ = np.array((250, 200, 220) if k_ != "cake" else (252, 246, 236)) A[fr] = np.clip(col_ * np.clip(sh[fr], .8, 1.15)[:, None], 0, 255) sprk = fr & (np.random.RandomState(seed + 5).rand(H, W) < .05) A[sprk] = [(230, 60, 90), (70, 150, 230), (250, 210, 60)][seed % 3] elif k_ == "candy": u = (xx + yy) / max(2.0, sz / 9) stripe = m & ((np.floor(u) % 2) == 0) sh = _shade(A, m) A[stripe] = np.clip(np.array([226, 40, 60]) * sh[stripe][:, None], 0, 255) A[m & ~stripe] = np.clip(np.array([250, 246, 246]) * sh[m & ~stripe][:, None], 0, 255) elif k_ == "watermelon": rind = _grow(e, r_) & m sh = _shade(A, m) A[m] = np.clip(np.array([232, 62, 74]) * sh[m][:, None], 0, 255) A[rind] = np.clip(np.array([46, 128, 52]) * sh[rind][:, None], 0, 255) A[_edge(rind) & m & ~e] = (190, 230, 150) seeds = m & ~rind & (_noise(H, W, max(1.5, sz / 12), seed) > .84) A[seeds] = (30, 24, 22) elif k_ == "bread": A[_grow(e, r_) & m] *= .72 else: continue else: continue done.append(c) cv.px = A.tolist() cv.ids = [[int(v) if v == int(v) else v for v in row] for row in I.tolist()] if done: trace.append("condition: %s drawn %s" % (getattr(inst, "concept", "?"), "+".join(done)))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Whole-picture frames named by the prompt (language shift 2): "a postcard of the eiffel tower" is the picture of thetower printed on a postcard - a cream card border, a perforated stamp in the corner and a wavy postmark over it.Pure numpy drawing on the finished image; both renderers (pixel: cv.px rows, 3D: the PIL image).Knob: PYDRAW_LANG_OFF=frame."""import osimport numpy as np
CARD = (246, 240, 226)INK = (55, 55, 85)
def _on(): return os.environ.get("PYDRAW_LANG", "1") != "0" and "frame" not in os.environ.get("PYDRAW_LANG_OFF", "").split(",")
def postcard(a, seed=0): """a: (H, W, 3) float array 0-255 -> the postcard version (same size)""" H, W = a.shape[:2] m = max(2, int(round(min(H, W) * .055))) ih, iw = H - 2 * m, W - 2 * m ys = (np.arange(ih) * H / ih).astype(int).clip(0, H - 1) xs = (np.arange(iw) * W / iw).astype(int).clip(0, W - 1) inner = a[ys][:, xs] out = np.empty_like(a) out[:] = CARD # rule: the card is paper - a faint fibre noise and a slightly darker rim rng = np.random.default_rng(seed) out += rng.normal(0, 2.2, (H, W, 1)) yy, xx = np.mgrid[0:H, 0:W] rim = np.minimum(np.minimum(yy, H - 1 - yy), np.minimum(xx, W - 1 - xx)) < max(1, m // 5) out[rim] *= .93 out[m:m + ih, m:m + iw] = inner # thin shadow line under the printed picture out[m + ih:m + ih + 1, m:m + iw] *= .85 out[m:m + ih, m + iw:m + iw + 1] *= .85 # stamp: top-right corner of the picture, perforated white edge, coloured inside with a little motif s = max(8, int(min(H, W) * .15)) sx1, sy0 = m + iw - max(2, m // 2), m + max(2, m // 2) sx0, sy1 = sx1 - s, sy0 + int(s * 1.2) out[sy0:sy1, sx0:sx1] = (250, 248, 242) per = max(2, s // 7) for k in range(sx0, sx1, per): # perforation notches out[sy0:sy0 + max(1, per // 2), k:k + max(1, per // 2)] = inner[0, 0] * .5 + 120 out[sy1 - max(1, per // 2):sy1, k:k + max(1, per // 2)] = inner[0, 0] * .5 + 120 b = max(2, s // 8) pal = [(190, 50, 60), (50, 100, 170), (60, 140, 90)][seed % 3] out[sy0 + b:sy1 - b, sx0 + b:sx1 - b] = pal cy, cx = (sy0 + sy1) / 2, (sx0 + sx1) / 2 r = (sx1 - sx0) / 2 - b sub = (yy[sy0:sy1, sx0:sx1] - cy) ** 2 / (r * .55) ** 2 + (xx[sy0:sy1, sx0:sx1] - cx) ** 2 / (r * .45) ** 2 < 1 blk = out[sy0:sy1, sx0:sx1] blk[sub] = (250, 236, 200) # motif: a pale oval (a sun / a portrait) # postmark: a ring left of the stamp + wavy cancellation lines across the stamp pr = s * .42 pcx, pcy = sx0 - pr * .5, sy0 + s * .55 d = np.sqrt((yy - pcy) ** 2 + (xx - pcx) ** 2) ring = (np.abs(d - pr) < max(.8, s * .035)) | (np.abs(d - pr * .72) < max(.6, s * .02)) wav = np.zeros_like(ring) for k in range(4): yk = pcy - pr * .5 + k * pr * .33 + np.sin((xx - pcx) / max(2.0, s * .12)) * s * .05 wav |= (np.abs(yy - yk) < max(.7, s * .025)) & (xx > pcx + pr * .9) & (xx < sx1 + s * .1) mark = ring | wav out[mark] = out[mark] * .35 + np.array(INK) * .65 return np.clip(out, 0, 255)
def apply_px(scene, px, trace): """pixel renderer: px = rows of [r, g, b] lists (drawing resolution)""" if scene.get("frame") != "postcard" or not _on(): return a = postcard(np.asarray(px, float), scene.get("seed", 0) or 0) for y in range(len(px)): row = px[y] for x in range(len(row)): row[x] = [int(v) for v in a[y, x]] trace.append("frame: printed on a postcard (border, stamp, postmark)")
def apply_pil(scene, im, trace): if scene.get("frame") != "postcard" or not _on(): return im from PIL import Image a = postcard(np.asarray(im.convert("RGB"), float), scene.get("seed", 0) or 0) trace.append("frame: printed on a postcard (border, stamp, postmark)") return Image.fromarray(a.astype(np.uint8))633 unmodified lines6346356366376386396406413 unmodified lines64564664764864965065125 unmodified lines67767867968068168271 unmodified lines754755756757758759760633 unmodified linesif k in used:continuew = (e.get("word") or "").split()if w and (w[-len(hl):] == hl or w[-1] == hl[-1] or e["concept"] == head orw[-1].rstrip("s") == hl[-1].rstrip("s")):used.add(k)return kreturn None3 unmodified linesfrom . import derived as Dused_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"):25 unmodified lineselif op == "creature":name = D.creature(p["recipe"], trace)if name:e["concept"] = namee["word"] = p["word"]if p["recipe"] in CREATURE_FLYING and e.get("pose") is None and p["recipe"] not in ("dragon",) and False:71 unmodified linesha = 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"] = newfrom .understanding import _attrs633 unmodified lines6346356366376386396406413 unmodified lines64564664764864965065165225 unmodified lines67867968068168268368471 unmodified lines756757758759760761762633 unmodified linesif k in used:continuew = (e.get("word") or "").split()if (w and (w[-len(hl):] == hl or w[-1] == hl[-1] or e["concept"] == head orw[-1].rstrip("s") == hl[-1].rstrip("s"))) or e.get("stand_in") == head:used.add(k)return kreturn None3 unmodified linesfrom . import derived as Dused_by = {}ents = scene["entities"]# night wave (language): creature ops first, so "a mermaid made of seaweed" finds the mermaid (its token was a stand-in)for p in sorted(plan, key=lambda d: (0 if d["op"] == "creature" else 1, 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"):25 unmodified lineselif op == "creature":name = D.creature(p["recipe"], trace)if name:e["stand_in"] = e.get("word") # night wave: later ops on this creature still find it by its stand-in tokene["concept"] = namee["word"] = p["word"]if p["recipe"] in CREATURE_FLYING and e.get("pose") is None and p["recipe"] not in ("dragon",) and False:71 unmodified linesha = 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 and eb["concept"] != "puddle": # a little girl IN a puddlenew = .55 * hb / CONCEPTS[ea["concept"]]["height"]ea["size"] = newfrom .understanding import _attrs
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589"""Language rules (night wave, lane "language"): long / odd prompts lose less meaning.
Hooks in parse(): pre(toks) rewrites token runs before the imagine pre-pass; post(scene, trace) runs after theaction / character post-passes and before imagine.post. Rules, not prompts:
quantity number phrases the parser read as unknown words: "a dozen" = 12, "half a dozen" = 6, "a trio of" = 3, eleven..twenty, "two or three" = 3, "countless / dozens of / hundreds of / numerous" = many (12 / 8). clause relative clauses are flattened so the old rules see the plain phrase: "a dog that is waiting" = "a dog waiting", "a car that has been abandoned" = "a car abandoned", "a boy whose kite is stuck in a tree" = "a boy with a kite stuck in a tree" (the kite is his; the tree holds the kite, not the boy). condition rare adjectives of state / wear / form ("gnarled", "tattered", "gleaming", "overgrown", "rusty", "chubby", "gaunt", "withered", "glowing") -> entity["attrs"]["cond"]: a list of condition classes that the renderers draw generically on any object (pydraw/condition_px.py). Hand lexicon + WordNet relatives (synonyms / similar-to of a hand word), so an unlisted adjective ("decrepit", "corroded") still lands. The adjective belongs to the noun after it ("a rusty tractor"), or before it when predicative ("the fence is weathered", "a tractor, rusty and half buried"). verb -ing words left unknown get a pose / action from WordNet's verb hierarchy (travel -> walking, rest -> lying, consume -> eat), after the hand verb table in actions.py. negation "a tree without leaves" / "a cat with no tail": a negated PART of the thing named before becomes attrs["absent"] (the leafless tree drops its canopy) instead of a lost noun.
Knobs: PYDRAW_LANG=0 turns the whole module off; PYDRAW_LANG_OFF=quantity,clause,condition,verb,negation turns offsingle rules. Every decision is logged with the prefix "language:"."""import osimport re
NUM_WORDS = {"eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "hundred": 100}MANY = {"countless": 12, "innumerable": 12, "numberless": 12, "myriad": 12, "myriads": 12, "dozens": 12, "hundreds": 12, "thousands": 12, "millions": 12, "scores": 12, "multitude": 12, "numerous": 8, "plenty": 8, "tons": 10, "loads": 10, "masses": 10, "heaps": 8}GROUP_N = {"trio": 3, "quartet": 4, "quintet": 5, "sextet": 6, "octet": 8, "score": 12, "brace": 2, "duo": 2, "twosome": 2, "threesome": 3, "foursome": 4, "half dozen": 6}SMALL = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
# colour names the parser dropped (28 of 35 common ones). Unambiguous words become colours anywhere; words that are also# things ("a rose", "a plum", "an olive") only right before another noun ("a rose dress"), as "<word>hue".COLOR_PLAIN = {"mauve": (176, 120, 160), "ochre": (204, 140, 40), "indigo": (75, 40, 130), "burgundy": (128, 20, 45), "khaki": (195, 176, 120), "aqua": (60, 210, 210), "azure": (40, 130, 230), "cerulean": (40, 125, 200), "chartreuse": (175, 225, 40), "fuchsia": (225, 50, 180), "vermilion": (225, 60, 35), "sienna": (160, 82, 45), "umber": (110, 70, 40), "taupe": (140, 125, 110), "periwinkle": (140, 150, 235), "skyblue": (125, 190, 235), "babyblue": (160, 205, 240), "forestgreen": (34, 110, 50), "hotpink": (240, 80, 160)}COLOR_NOUNY = {"rose": (225, 110, 140), "peach": (250, 185, 140), "plum": (110, 40, 90), "salmon": (245, 135, 115), "olive": (120, 125, 45), "amber": (235, 160, 30), "coral": (245, 120, 100), "mustard": (215, 170, 40), "lavender": (180, 160, 220), "lilac": (195, 160, 215), "mint": (150, 225, 180), "emerald": (30, 160, 90), "ivory": (245, 240, 225), "charcoal": (55, 55, 60), "ruby": (170, 20, 50), "sapphire": (25, 70, 170), "cherry": (190, 20, 45), "lemon": (245, 225, 70), "chocolate": (110, 65, 35), "honey": (225, 165, 50), "wine": (115, 20, 40), "sand": (215, 195, 150), "slate": (95, 110, 125), "steel": (130, 140, 150)}# rule: "a plum tree", "peach pie", "lemon juice": the fruit / plant, not its colourCOLOR_NOT_BEFORE = {"tree", "trees", "bush", "bushes", "blossom", "blossoms", "pie", "pies", "jam", "juice", "sauce", "cake", "cakes", "tea", "oil", "branch", "branches", "garden", "gardens", "field", "fields", "pit", "seed", "seeds", "petal", "petals", "orchard", "grove", "slice", "slices", "tart", "bud", "buds", "plant", "plants", "leaf", "leaves", "ice", "candy", "drop", "drops", "bar", "bars", "milk", "chip", "chips"}COLOR_PAIRS = {("sky", "blue"): "skyblue", ("baby", "blue"): "babyblue", ("forest", "green"): "forestgreen", ("hot", "pink"): "hotpink", ("navy", "blue"): "navy", ("lime", "green"): "lime", ("blood", "red"): "crimson", ("royal", "blue"): "sapphirehue", ("mint", "green"): "minthue", ("olive", "green"): "olivehue", ("lemon", "yellow"): "lemonhue", ("cherry", "red"): "cherryhue", ("rose", "pink"): "rosehue"}
def _compound(a, b): """'wine glass', 'chocolate cake', 'honey bee': a two-word noun the registry knows""" from .understanding import index return (a, b) in index() or (a + b,) in index()
def colors_add(COLORS): if on("colors"): for k, v in COLOR_PLAIN.items(): COLORS.setdefault(k, v) for k, v in COLOR_NOUNY.items(): COLORS.setdefault(k + "hue", v)
def _colors(toks, trace): from .understanding import COLORS out, i, n = [], 0, len(toks) while i < n: t = toks[i] if i + 1 < n and (t, toks[i + 1]) in COLOR_PAIRS and COLOR_PAIRS[(t, toks[i + 1])] in COLORS: out.append(COLOR_PAIRS[(t, toks[i + 1])]) trace.append("language: colour '%s %s' -> %s" % (t, toks[i + 1], out[-1])) i += 2 continue if t in COLOR_NOUNY and t not in COLOR_PLAIN and i + 1 < n and (toks[i + 1] in ("colored", "coloured", "tinted") or (_nounish(toks[i + 1]) and toks[i + 1] not in AUX and toks[i + 1] not in COLOR_NOT_BEFORE)) \ and not (out and out[-1] in ("of",)) and t + "hue" in COLORS and not _compound(t, toks[i + 1]): out.append(t + "hue") # "a rose dress", "an olive jacket"; "a rose in a vase" stays a rose trace.append("language: colour '%s' before a noun -> %s" % (t, out[-1])) i += 1 + (1 if toks[i + 1] in ("colored", "coloured", "tinted") else 0) continue if t in COLOR_PLAIN and i + 1 < n and toks[i + 1] in ("colored", "coloured", "tinted"): out.append(t) i += 2 continue out.append(t) i += 1 return out
def settings_add(SETTINGS): if on("setting"): for k, v in SETTINGS_ADD.items(): SETTINGS.setdefault(k, ("place", v)) for k in ("puddle", "puddles"): # rule: a puddle is wet ground after rain (pixel rain draws puddles), not a blob SETTINGS.setdefault(k, ("weather", "rain")) if on("summer"): # rule (shift 3): summer was an unknown word ("a snowman melting in the summer sun"); it is a season like # autumn / spring (renderers that know no summer look keep their default sunny day) for k in ("summer", "summertime", "midsummer", "summery"): SETTINGS.setdefault(k, ("season", "summer"))
def on(rule=None): if os.environ.get("PYDRAW_LANG", "1") == "0": return False return rule is None or rule not in os.environ.get("PYDRAW_LANG_OFF", "").split(",")
# ---------------------------------------------------------------- pre-pass (tokens)def pre(toks, trace): if not on(): return toks try: if on("colors"): toks = _colors(toks, trace) if on("quantity"): toks = _quantity(toks, trace) if on("clause"): toks = _clause(toks, trace) except Exception as ex: # rule: these rewrites never break an ordinary parse trace.append("language: pre-pass skipped (%s)" % ex) return toks
PHRASES = [ # (tokens, replacement): fixed phrases whose words mislead the word loop (("moth", "eaten"), ("tattered",)), (("sun", "is", "setting"), ("sunset",)), (("setting", "sun"), ("sunset",)), (("sun", "sets"), ("sunset",)), (("sun", "is", "rising"), ("sunrise",)), (("rising", "sun"), ("sunrise",)), (("getting", "dark"), ("dusk",)), (("growing", "dark"), ("dusk",)), (("night", "falls"), ("dusk",)), (("parking", "lot"), ("street",)), (("car", "park"), ("street",)), (("never", "stops"), ()), (("never", "stop"), ()), (("keeps", "on"), ()), (("with", "holes"), ()), (("full", "of", "holes"), ()), (("with", "rips"), ()), (("carved", "out", "of", "a", "tree", "trunk"), ("made", "of", "wood")), (("carved", "from", "a", "tree", "trunk"), ("made", "of", "wood")), (("made", "of", "driftwood"), ("made", "of", "wood")), (("made", "from", "driftwood"), ("made", "of", "wood")), (("carved", "out", "of", "a", "log"), ("made", "of", "wood")), (("made", "of", "logs"), ("made", "of", "wood")), (("city", "square"), ("city",)), (("town", "square"), ("town",)), (("village", "square"), ("village",)), (("market", "square"), ("market",)), (("mountain", "pass"), ("mountains",)), (("shooting", "stars"), ("meteors",)), (("falling", "stars"), ("meteors",)), (("ice", "skating"), ("skating",)), (("lights", "in", "the", "windows"), ("dusk",)), (("lights", "in", "its", "windows"), ("dusk",)), (("lights", "in", "every", "window"), ("dusk",)), (("lit", "windows"), ("dusk",)), (("glowing", "windows"), ("dusk",)), (("windows", "glowing"), ("dusk",)), (("lit", "up", "windows"), ("dusk",)), (("icy", "hill"), ("snowy", "hill")), (("frozen", "hill"), ("snowy", "hill")), (("icy", "slope"), ("snowy", "hill")), (("snowy", "slope"), ("snowy", "hill")), (("icy", "field"), ("snowy", "field")), (("at", "christmas"), ("in", "winter")), (("at", "christmastime"), ("in", "winter")), (("christmas", "eve"), ("winter", "night")), (("christmas", "village"), ("snowy", "village")), (("christmas", "market"), ("snowy", "market")), (("christmas", "morning"), ("winter", "morning")),]# rule (shift 2): "a ball of yarn" / "a coil of rope" name ONE thing whose model already has that form (strands family)PHRASES2 = []for _w in ("yarn", "wool", "twine", "string"): PHRASES2 += [(("balls", "of", _w), ("yarns",)), (("ball", "of", _w), ("yarn",)), (("skeins", "of", _w), ("yarns",)), (("skein", "of", _w), ("yarn",))]for _w in ("rope", "cord", "cable", "line"): PHRASES2 += [(("coil", "of", _w), (_w,)), (("coils", "of", _w), (_w + "s",)), (("length", "of", _w), (_w,))]PHRASES2 += [(("fishing", "net"), ("net",)), (("fishing", "nets"), ("nets",)), (("tree", "hole"), ("tree", "hollow"))]# rule (shift 2, critic L53-L57): figures of speech and compound places that misled the word loopPHRASES3 = [(("in", "the", "world"), ()), (("in", "the", "whole", "world"), ()), (("in", "all", "the", "world"), ()), (("on", "earth"), ()), (("on", "the", "planet"), ()), (("in", "the", "universe"), ()), (("kitchen", "island"), ("kitchen", "table")), (("mushroom", "forest"), ("forest", "with", "giant", "mushrooms")), (("mushroom", "forests"), ("forest", "with", "giant", "mushrooms")), (("blanket", "fort"), ("tent", "in", "a", "bedroom")), (("pillow", "fort"), ("tent", "in", "a", "bedroom")), (("afraid", "of", "the", "dark"), ("scared", "at", "night")), (("scared", "of", "the", "dark"), ("scared", "at", "night")), (("in", "the", "dark"), ("at", "night")), (("wooden", "floors"), ()), (("wood", "floors"), ()), (("hardwood", "floors"), ()), (("hardwood", "floor"), ()), (("wooden", "floor"), ("floor",)), (("tiled", "floor"), ("floor",)), (("tiled", "floors"), ()), (("marble", "floors"), ()), (("checkered", "floor"), ("floor",))]ROYAL = {"prince": "crown", "princess": "tiara", "king": "crown", "queen": "crown", "emperor": "crown", "empress": "crown"}SHAPE_GIVERS = {"pumpkin", "watermelon", "melon", "mushroom", "strawberry", "pear", "acorn", "egg", "pineapple", "teapot", "shoe", "boot", "seashell", "shell", "barrel", "bottle"}SHAPE_HEADS = {"carriage", "coach", "house", "cottage", "hut", "car", "boat", "bus", "castle", "lamp", "tower", "home"}# rule: plural "stars" after these words is the night sky ("under the stars", "a sky full of stars"), not objectsSTAR_SKY = {"the", "of", "with", "beneath", "twinkling", "bright", "shining", "glittering", "starlit"}# rule: what is waited / searched for is not in the picture ("a dog waiting for its owner")ABSENT_AFTER = {"waiting", "waits", "longing", "searching", "looking", "wishing", "hoping", "missing"}# small hand list: legendary little people WordNet files under "imaginary being" (drawn as small people)LITTLE_PEOPLE = {"gnome": .5, "gnomes": .5, "elf": .6, "elves": .6, "dwarf": .65, "dwarves": .65, "dwarfs": .65, "leprechaun": .5, "leprechauns": .5, "hobbit": .6, "hobbits": .6, "pixie": .4, "pixies": .4, "troll": 1.3, "trolls": 1.3, "ogre": 1.4, "ogres": 1.4}# settings the parser dropped (singular "hill", "market"...): added to understanding.SETTINGS when the module is onSETTINGS_ADD = {"hill": "field", "hilltop": "field", "hillock": "field", "knoll": "field", "plains": "field", "battlefield": "field", "market": "street", "marketplace": "street", "bazaar": "street", "plaza": "street", "boulevard": "street", "avenue": "street", "lane": "street", "harbor": "water", "port": "water", "seashore": "beach", "glade": "forest", "clearing": "forest", "thicket": "forest", "heath": "field", "moor": "field", "moors": "field", "steppe": "field", "lakefront": "water", "riverside": "water", "junkyard": "field", "scrapyard": "field", "dump": "field", "campsite": "forest", "campground": "forest"}
def _animal_tok(w): from .registry import CONCEPTS, SYNONYMS c = (SYNONYMS.get(w) or SYNONYMS.get(w[:-1] if w.endswith("s") else w) or (None,))[0] return bool(c and CONCEPTS.get(c, {}).get("animal"))
def _phrases(toks, trace): out, i, n = [], 0, len(toks) tail_ = [] while i < n: if tail_ and toks[i] == "zzeos": for w_ in tail_: out += ["by", "a", w_] tail_ = [] hit = next(((a, b) for a, b in (PHRASES + (PHRASES2 if on("strands2") else []) + (PHRASES3 if on("figure") else [])) if tuple(toks[i:i + len(a)]) == a), None) if hit and hit[1] == ("dusk",) and any(t in ("night", "midnight", "nighttime", "evening", "dusk", "sunset", "twilight", "dawn", "sunrise", "moon", "moonlit", "starry") for t in toks): hit = (hit[0], ()) # lit windows: the time the prompt names wins if hit and hit[1] == () and hit[0][-1] in ("holes", "rips") and tuple(toks[i + len(hit[0]):i + len(hit[0]) + 2]) in ( ("in", "the"), ("in", "its"), ("at", "the")) and i + len(hit[0]) + 2 < n: hit = (tuple(toks[i:i + len(hit[0]) + 3]), ()) # "... in the elbows" goes with the holes (condition pass: torn) if hit: out += list(hit[1]) trace.append("language: '%s' -> %s" % (" ".join(hit[0]), " ".join(hit[1]))) i += len(hit[0]) continue if toks[i] in ROYAL and out and on("royal") and _animal_tok(out[-1]): # rule (critic L49): "a frog prince" is a frog (with a crown), not a human prince trace.append("language: '%s %s' -> a %s with a %s" % (out[-1], toks[i], out[-1], ROYAL[toks[i]])) if not any(t in ("crown", "tiara", "crowned") for t in toks): out += ["with", "a", ROYAL[toks[i]]] i += 1 continue if toks[i] in ("building", "making", "sculpting", "carving") and out and out[-1] not in NOUN_GAP and i + 1 < n \ and toks[i + 1] in ("a", "an", "the", "his", "her", "their", "some") and on("building"): out += ["next", "to"] # rule: "a child building a sandcastle" = beside it, busy; never a building trace.append("language: '%s' is a verb here -> next to" % toks[i]) i += 1 continue if toks[i] in PART_OF and i + 2 < n and toks[i + 1] == "of" and toks[i + 2] in ("a", "an", "the", "this", "that", "its", "his", "her", "their", "some") \ and out and out[-1] in ("the", "a", "an") and on("partof"): # rule: "in the fork of a tree", "at the top of a hill", "on the edge of a cliff": the place is the tree / hill; # the word before "of" is a spot on it, not a second thing (the fork became a dinner fork) out.pop() trace.append("language: 'the %s of' -> a spot on the next thing" % toks[i]) i += 2 continue if toks[i] in ("flock", "herd") and not (i + 1 < n and toks[i + 1] == "of") and on("quantity"): # rule: a bare "flock" / "herd" ("a shepherd with his flock") names its usual animals if out and out[-1] in ("a", "an", "the", "his", "her", "their", "its"): out.pop() out += {"flock": ["5", "sheep"], "herd": ["4", "cows"]}[toks[i]] trace.append("language: bare '%s' -> %s" % (toks[i], " ".join(out[-2:]))) i += 1 continue if toks[i] == "before" and out and i + 1 < n and toks[i + 1] in ("a", "an", "the", "her", "his", "their") \ and out[-1] not in ("just", "long", "right", "shortly", "day", "night", "moments") and on("clause"): out += ["in", "front", "of"] # rule: "kneels before a queen" = in front of her i += 1 continue if on("verb") and out and i + 1 < n and toks[i + 1] in PREP_DET and _nounish(out[-1]) \ and toks[i] not in NOUN_GAP and not toks[i].isdigit() and not toks[i].endswith("ing") and not _mainly_verb(out[-1]) \ and (not _stable_noun(toks[i]) or _gerund(toks[i], out[-1]) in _hand_verbs() or (_animate_word(out[-1]) and verb_of(_gerund(toks[i], out[-1]) or "") is not None)): g = _gerund(toks[i], out[-1]) if g: out.append(g) trace.append("language: '%s' after a noun is a verb -> %s" % (toks[i], g)) i += 1 continue if out and _stable_noun(out[-1]) and not _animate_word(out[-1]) and not _stable_noun(toks[i]) \ and (toks[i],) and person_noun(toks[i]) and on("person"): # rule: "a lighthouse keeper", "a bus driver": the person, by the thing that names the job w_ = out.pop() out.append(toks[i]) tail_.append(w_) # "by a <thing>" goes at the end of the sentence, so the person's verbs stay the person's trace.append("language: '%s %s' -> %s by a %s" % (w_, toks[i], toks[i], w_)) i += 1 continue if toks[i] in ("passing", "carrying", "holding", "riding", "following", "chasing", "watching") and out \ and out[-1] in ("a", "an", "the") and on("clause"): trace.append("language: 'a %s X' is an adjective here" % toks[i]) # "a passing ship" is not passed i += 1 continue if toks[i] in ("family", "families") and out and out[-1] not in NOUN_GAP and _animate_word(out[-1]) \ and out[-1] not in ("royal", "human", "person", "people") and on("family"): w_ = out.pop() if out and out[-1] in ("a", "an", "the"): out.pop() out += ["family", "of", w_] # rule: "a mouse family" = a family of mice (sizes vary in layout) trace.append("language: '%s family' -> family of %s" % (w_, w_)) i += 1 continue if toks[i] in ("festival", "parade", "fair") and out and _nounish(out[-1]) and out[-1] not in NOUN_GAP and on("quantity"): w_ = out.pop() if out and out[-1] in ("a", "an", "the"): out.pop() out += ["8", w_] # rule: "a lantern festival" = many lanterns trace.append("language: '%s %s' -> many %s" % (w_, toks[i], w_)) i += 1 continue if toks[i] in SHAPE_HEADS and out and out[-1] in SHAPE_GIVERS and on("shapecompound"): # rule: "a pumpkin carriage", "a mushroom house", "a watermelon boat": the second thing in the first one's shape w_ = out.pop() out += [toks[i], "shaped", "like", "a", w_] trace.append("language: '%s %s' -> %s shaped like a %s" % (w_, toks[i], toks[i], w_)) i += 1 continue if toks[i] == "stars" and out and out[-1] in STAR_SKY and on("stars"): out.append("starry") trace.append("language: '%s stars' -> night sky (starry)" % out[-2]) i += 1 continue if toks[i] == "for" and out and out[-1] in ABSENT_AFTER and on("absent"): j = i + 1 while j < n and toks[j] in ("a", "an", "the", "its", "his", "her", "their", "my", "our", "your", "some"): j += 1 if j < n and toks[j] != "zzeos": trace.append("language: '%s for ... %s' -> %s is not in the picture" % (out[-1], toks[j], toks[j])) i = j + 1 continue # "a house on chicken legs" / "a tower standing on four spider legs" = legs grafted on (imagine reads "with Y legs") if toks[i] == "on" and i > 0 and out and out[-1] not in ("a", "an", "the"): j = i + 1 while j < n and (toks[j] in SMALL or toks[j].isdigit() or toks[j] in ("giant", "huge", "long", "thin", "tall", "big", "spindly", "skinny", "little", "tiny")): j += 1 if j + 1 < n and toks[j + 1] in ("legs", "feet", "stilts") and toks[j] not in ("its", "his", "her", "their", "hind", "two", "four", "all", "my"): while out and out[-1] in ("standing", "stands", "perched", "raised", "built", "set", "mounted", "resting", "balanced", "walking", "walks", "sitting", "sits", "is", "that"): out.pop() # rule: "standing on legs" -> the legs say it; the graft rule wants the noun right before "with" out += ["with"] + toks[i + 1:j + 2] trace.append("language: 'on %s' -> grafted legs" % " ".join(toks[i + 1:j + 2])) i = j + 2 continue out.append(toks[i]) i += 1 for w_ in tail_: out += ["by", "a", w_] return out
PART_OF = {"fork", "top", "edge", "side", "foot", "base", "corner", "middle", "center", "centre", "end", "tip", "bottom", "crown", "rim", "brink", "shore", "bank", "banks", "surface", "peak", "summit", "heart", "depths", "outskirts", "entrance", "doorway", "branches", "branch", "boughs", "bough", "limbs", "canopy"} # (shift 3: "stuck in the branches of a willow")PREP_DET = {"on", "in", "at", "over", "under", "above", "a", "an", "the", "into", "onto", "across", "around", "beside", "behind", "near", "along", "through", "from", "toward", "towards"}
def _not_verbs(scene, toks, pos, trace): """rule: "a fox that never sleeps" / "a dog not sitting": a negated verb's pose is taken back""" from .actions import VERBS for i, t in enumerate(toks): if i == 0 or toks[i - 1] not in ("never", "not", "doesnt", "dont", "isnt", "nt", "cannot", "no", "longer") or t not in VERBS: continue pose = VERBS[t][0] prv = [k for k, p in enumerate(pos) if p is not None and p < i and i - p <= 5] if pose and prv and scene["entities"][prv[-1]].get("pose") == pose: scene["entities"][prv[-1]]["pose"] = None trace.append("language: '%s %s' -> %s is not %s" % (toks[i - 1], t, scene["entities"][prv[-1]]["concept"], pose))
def _animate_word(w): from .understanding import index from .registry import CONCEPTS h = index().get((w,)) if h and (h[0] in ("person", "robot", "snowman", "alien", "astronaut", "teddy bear") or CONCEPTS.get(h[0], {}).get("animal")): return True if person_noun(w): return True try: # "mouse" indexes the computer mouse; WordNet's main sense is the animal from nltk.corpus import wordnet as wn lem = wn.morphy(w, "n") syn = wn.synsets(lem, "n")[:1] if lem else [] return bool(syn) and "animal.n.01" in {x.name() for x in syn[0].closure(lambda y: y.hypernyms())} except Exception: return False
def _hand_verbs(): from .actions import VERBS return VERBS
def _stable_noun(w): """a hand-made concept word (not one open vocabulary registered on the fly): 'candles', 'ducks', 'mother'""" from .understanding import index from .registry import CONCEPTS h = index().get((w,)) return bool(h) and not CONCEPTS.get(h[0], {}).get("open_vocab")
def _nounish(w): from .understanding import index, COLORS, SIZES, NUMBERS if w.isdigit() or w in NUMBERS or w in MANY or w in GAP_BREAK or w in PREP_DET or w in ("and", "or", "zzeos"): return False if (w,) in index(): return True if w in NOUN_GAP or w in COLORS or w in SIZES or w in AUX or w in REL_PRON or w.endswith("ing") or w.endswith("ly"): return False try: from nltk.corpus import wordnet as wn lem = wn.morphy(w, "n") return bool(lem) and len(wn.synsets(lem, "n")) >= len(wn.synsets(w, "a")) + len(wn.synsets(w, "v")) except Exception: return False
def _gerund(w, prev): """'perch' (after a plural) / 'guards' (after a singular) -> 'perching' / 'guarding' when WordNet knows the verb""" try: from nltk.corpus import wordnet as wn except Exception: return None if w.endswith("s") and not prev.endswith("s"): base = wn.morphy(w, "v") if not base or base == w: return None elif prev.endswith("s") and not w.endswith("s") and not prev.endswith("ss"): base = w if wn.synsets(w, "v") else None else: return None if not base or not wn.synsets(base, "v") or len(wn.synsets(base, "v")) * 4 < len(wn.synsets(base, "n")): return None if base.endswith("ie"): return base[:-2] + "ying" if base.endswith("e") and not base.endswith("ee"): return base[:-1] + "ing" if len(base) <= 4 and base[-1] in "bdgmnpt" and base[-2] in "aeiou" and base[-3] not in "aeiou": return base + base[-1] + "ing" return base + "ing"
def _quantity(toks, trace): toks = _phrases(toks, trace) out, i, n = [], 0, len(toks) while i < n: t = toks[i] nx = toks[i + 1] if i + 1 < n else "" # "half a dozen" / "half dozen" if t == "half" and nx in ("a", "dozen") and "dozen" in toks[i + 1:i + 3]: j = i + 1 + toks[i + 1:i + 3].index("dozen") + 1 out.append("6") trace.append("language: 'half a dozen' -> 6") i = j + (1 if j < n and toks[j] == "of" else 0) continue # "a dozen" / "one dozen" / "a dozen of" ("dozens of" is many, below) if t == "dozen": if out and out[-1] in ("a", "one"): out.pop() k = 12 if out and out[-1] in SMALL: # "two dozen" -> as many as we draw out.pop() k = 12 out.append(str(k)) trace.append("language: 'dozen' -> 12") i += 1 + (1 if nx == "of" else 0) continue # "a trio of" / "a quartet of" / "a score of" if t in GROUP_N and nx == "of": if out and out[-1] in ("a", "an", "the"): out.pop() out.append(str(GROUP_N[t])) trace.append("language: '%s of' -> %d" % (t, GROUP_N[t])) i += 2 continue # "countless stars", "dozens of lanterns", "a multitude of birds", "plenty of apples" if t in MANY and (t not in ("scores", "tons", "loads", "masses", "heaps", "plenty", "multitude", "dozens", "hundreds", "thousands", "millions", "myriads") or nx == "of"): if out and out[-1] in ("a", "an", "the"): out.pop() out.append(str(MANY[t])) trace.append("language: '%s' -> %d" % (t, MANY[t])) i += 1 + (1 if nx == "of" else 0) continue # eleven .. twenty / fifty before a noun if t in NUM_WORDS and t != "hundred": out.append(str(min(NUM_WORDS[t], 20))) trace.append("language: '%s' -> %s" % (t, out[-1])) i += 1 continue # "two or three", "one or two", "three to four": the larger if t in SMALL and nx in ("or", "to") and i + 2 < n and toks[i + 2] in SMALL: k = max(SMALL[t], SMALL[toks[i + 2]]) out.append(str(k)) trace.append("language: '%s %s %s' -> %d" % (t, nx, toks[i + 2], k)) i += 3 continue out.append(t) i += 1 return out
AUX = {"is", "are", "was", "were", "be", "being", "been", "has", "have", "had", "seems", "seem", "looks", "look"}REL_PRON = {"that", "who", "which"}
def _clause(toks, trace): out, i, n = [], 0, len(toks) while i < n: t = toks[i] # "X whose Y is Z" -> "X with a Y Z" if t == "whose" and i + 1 < n: j = i + 1 noun = [] while j < n and toks[j] not in AUX and toks[j] != "zzeos" and len(noun) < 3: noun.append(toks[j]) j += 1 if j < n and toks[j] in AUX and noun: out += ["with", "a"] + noun j += 1 while j < n and toks[j] in AUX: j += 1 trace.append("language: 'whose %s' -> with a %s" % (" ".join(noun), " ".join(noun))) i = j continue # "that is waiting" / "who are reading" / "which has been abandoned" / "that has lost": drop the pronoun + aux if t in REL_PRON and i > 0 and i + 1 < n and toks[i + 1] in AUX: j = i + 1 while j < n and toks[j] in AUX: j += 1 if j < n and toks[j] not in ("a", "an", "the", "like", "as") and toks[j] != "zzeos": # ("that looks like" = hybrid) trace.append("language: clause '%s %s' flattened" % (t, " ".join(toks[i + 1:j]))) i = j continue out.append(t) i += 1 return out
# ---------------------------------------------------------------- nouns WordNet knows as places / peopleROOMISH = {"nook", "alcove", "cranny", "parlor", "parlour", "study", "den", "pantry", "chamber", "chambers"}_PLACE_CACHE = {}
def place_of(w): """'room' / 'street' for nouns that name a space you are IN (hallway, attic, ballroom, courtyard, plaza), else None""" if w in _PLACE_CACHE: return _PLACE_CACHE[w] res = None if w in ROOMISH: res = "room" else: try: from nltk.corpus import wordnet as wn lem = wn.morphy(w, "n") syn = wn.synsets(lem, "n")[:1] if lem else [] for sy in syn: clos = {h.name() for h in sy.closure(lambda x: x.hypernyms())} if clos & {"room.n.01", "floor.n.02", "passageway.n.01"}: res = "room" elif clos & {"public_square.n.01"} or (sy.name() != "room.n.01" and "area.n.05" in clos): res = "street" except Exception: pass _PLACE_CACHE[w] = res return res
def places(toks, trace, SETTINGS, stable): """token pass inside parse (after the phrase pass): place nouns become setting words""" if not on("place"): return toks out = [] for i, t in enumerate(toks): if len(t) > 3 and t not in SETTINGS and not stable(t) and not stable(t.rstrip("s")): p = place_of(t) if p: rep = {"room": "indoors", "street": "town"}[p] trace.append("language: '%s' is a place -> setting %s" % (t, p)) out.append(rep) continue out.append(t) return out
_PERSON_CACHE = {}
def person_noun(w, acting=False): """('person', None, plural) for a noun whose main WordNet sense is a person (gardener, violinist, blacksmith), or a legendary little person (gnome, elf). acting: a human activity verb follows ("campers telling stories"), so a first-sense person wins even when another sense is a thing (camper van, hanger).""" if not on("person") or " " in w: return None if acting and _PERSON_CACHE.get(("act", w)) is not None: return _PERSON_CACHE[("act", w)] if acting: try: from nltk.corpus import wordnet as wn lem = wn.morphy(w, "n") syn = wn.synsets(lem, "n")[:1] if lem else [] if syn and "person.n.01" in {h.name() for h in syn[0].closure(lambda x: x.hypernyms())}: _PERSON_CACHE[("act", w)] = ("person", None, lem != w) return _PERSON_CACHE[("act", w)] except Exception: pass if w in _PERSON_CACHE: return _PERSON_CACHE[w] res = None if w in LITTLE_PEOPLE: res = ("person", None, w.endswith("s") or w in ("elves", "dwarves")) else: try: from nltk.corpus import wordnet as wn from .understanding import SIZES, COLORS, NUMBERS, STOP lem = wn.morphy(w, "n") if lem and w not in SIZES and w not in COLORS and w not in NUMBERS and w not in STOP and len(w) > 3: syn = wn.synsets(lem, "n") vl = wn.morphy(w, "v") other = len(wn.synsets(vl, "v") if vl else []) + len(wn.synsets(w, "a")) if syn and other <= len(syn) and "person.n.01" in {h.name() for h in syn[0].closure(lambda x: x.hypernyms())} \ and not any("artifact.n.01" in {h.name() for h in s2.closure(lambda x: x.hypernyms())} for s2 in syn[1:3]): res = ("person", None, lem != w) # ("hanger": a worker who hangs, but mostly a coat hanger) except Exception: pass _PERSON_CACHE[w] = res return res
# ---------------------------------------------------------------- conditions (adjectives of state / wear / form)COND = {}
def _c(words, cls): for w in words.split(): COND[w] = cls
_c("tattered frayed ragged torn ripped shredded threadbare tatty", "torn")_c("rusty rusted corroded oxidized oxidised", "rusty")_c("weathered faded worn aged dilapidated decrepit ramshackle crumbling derelict rundown shabby peeling neglected " "abandoned forgotten timeworn", "weathered")_c("broken shattered smashed damaged battered dented chipped busted wrecked bruised", "broken")_c("mossy overgrown lichen ivied vined", "mossy")_c("moldy mouldy rotten rotting decaying spoiled", "moldy")_c("shiny gleaming glossy polished glistening lustrous sparkling glittering shimmering burnished spotless pristine " "gleamy shining", "shiny")_c("glowing luminous radiant incandescent illuminated phosphorescent bioluminescent fluorescent glowy aglow", "glowing")_c("withered wilted wilting shriveled shrivelled drooping parched dried", "withered")_c("dusty dirty grimy muddy filthy sooty stained", "dirty")_c("burnt burned charred scorched singed", "burnt")_c("frosty frosted icy", "frosty")_c("wet soaked drenched soggy dripping", "wet")_c("gnarled gnarly twisted crooked lopsided warped knotted contorted wonky misshapen", "twisted")_c("chubby plump fat burly stout portly rotund stocky beefy pudgy podgy hefty bulky", "stout")_c("gaunt skinny lanky scrawny emaciated bony wiry spindly lean", "thin")_c("scruffy shaggy unkempt bedraggled disheveled dishevelled mangy matted", "scruffy")_c("leafless bare dead", "bare") # trees: the bare branch skeleton (pydraw/concepts/core.py draw_tree)COND["moth"] = "torn" # "moth eaten" ("-" is split by the tokenizer)# words that are conditions only right before a noun (never predicative "it is ..."): too common otherwiseATTRIB_ONLY = {"bare", "dead", "worn", "lean", "dried", "stained", "aged", "forgotten", "abandoned", "neglected", "wet"}# condition classes a renderer can show; anything else is recorded but drawn as nothingCLASSES = {"torn", "rusty", "weathered", "broken", "mossy", "moldy", "shiny", "glowing", "withered", "dirty", "burnt", "frosty", "wet", "twisted", "stout", "thin", "scruffy", "bare"}_WN_CACHE = {}
def cond_of(w): """condition class of an adjective: hand lexicon first, then its WordNet relatives (synonyms and similar-to of its two main adjective senses) that are in the hand lexicon.""" if w in COND: return COND[w], "hand" if w in _WN_CACHE: return _WN_CACHE[w] res = None, None try: from nltk.corpus import wordnet as wn syn = wn.synsets(w, "a")[:2] + wn.synsets(w, "s")[:2] # rule: only words that are mainly adjectives ("ancient", not "ram") and not mainly nouns if syn and len(wn.synsets(w, "n")) <= len(syn): votes = {} for s in syn: rel = [s] + s.similar_tos() for r in rel: for l in r.lemmas(): c = COND.get(l.name().lower()) if c and l.name().lower() != w: votes[c] = votes.get(c, 0) + (2 if r is s else 1) if votes: res = max(votes.items(), key=lambda kv: kv[1])[0], "wordnet" except Exception: pass _WN_CACHE[w] = res return res
# ---------------------------------------------------------------- post-pass (scene)def _toks(text): text = re.sub(r'"[^"]*"', " ", text).lower().replace("-", " ").replace("'s", "") text = re.sub(r"[.!?;]+(\s|$)", " zzeos ", text) return re.findall(r"[a-z]+|\d+", text)
def post(scene, trace): if on() and on("frame") and re.search(r"\bpostcards?\b", scene.get("text", "").lower()): scene["frame"] = "postcard" # rule (shift 2, critic L38): "a postcard of X" = X printed on a postcard trace.append("language: postcard -> the picture is printed on a postcard") if not on() or not scene.get("entities"): return scene try: toks = _toks(scene.get("text", "")) from .actions import _locate pos = _locate(toks, scene["entities"]) if on("condition"): _conditions(scene, toks, pos, trace) if on("verb"): _verbs(scene, toks, pos, trace) _not_verbs(scene, toks, pos, trace) if on("negation"): _neg_parts(scene, toks, pos, trace) if on("young"): _young(scene, toks, pos, trace) if on("old"): _old(scene, toks, pos, trace) if on("bridgekind"): _bridges(scene, toks, pos, trace) if on("sharing"): _sharing(scene, toks, pos, trace) if on("tether"): _tethers(scene, toks, pos, trace) if on("picnic"): _picnic(scene, toks, trace) if on("iceground"): _ice_ground(scene, toks, pos, trace) if on("hollow"): _hollow(scene, toks, trace) if on("ruralroad"): _rural_road(scene, toks, trace) if on("balance"): _balance(scene, toks, pos, trace)
if on("pier") and not scene.get("place") and any( e["concept"] == "marina" and (e.get("word") or "").split()[-1:] in (["pier"], ["piers"], ["dock"], ["docks"], ["jetty"], ["wharf"], ["boardwalk"]) for e in scene["entities"]): scene["place"] = "water" # rule: a pier stands in water (it drew a pier on a city road) trace.append("language: pier / dock -> place water") except Exception as ex: trace.append("language: post-pass skipped (%s)" % ex) return scene
OLD = {"old", "ancient", "aged", "elderly", "aging", "ageing", "venerable", "age"}
ROPE_BRIDGE = {"rope", "suspension", "hanging", "swinging", "swaying", "wobbly", "rickety", "vine", "jungle"}
def _bridges(scene, toks, pos, trace): """rule (shift 2): "a rope / suspension / rickety bridge" is strung planks between posts (was a stone arch bridge that looked like a ruin when frayed); "a wooden / plank / timber bridge" is a low timber deck with a rail""" for k, e in enumerate(scene["entities"]): if e["concept"] != "bridge" or pos[k] is None: continue before = toks[max(0, pos[k] - 3):pos[k]] kind = "rope" if ROPE_BRIDGE & set(before) else "plank" if ({"wooden", "wood", "plank", "timber", "log"} & set(before) or e.get("material") == "wood") else None if kind: e.setdefault("attrs", {}) if e["attrs"] is None: e["attrs"] = {} e["attrs"]["bridge_kind"] = kind e["info_override"] = dict(e.get("info_override") or {}, on_top=.4 if kind == "rope" else .36) # walk on the deck trace.append("language: %s bridge -> strung %s bridge" % (" ".join(before), kind))
SHARE_SEATS = {"bench", "couch", "bed", "sofa", "blanket", "picnic blanket", "rug", "log", "hammock", "swing", "chair", "armchair", "boat", "sled", "seat", "cushion", "pillow"}
TIE_VERBS = {"tied": "rope", "tethered": "rope", "moored": "rope", "roped": "rope", "lashed": "rope", "hitched": "rope", "leashed": "leash", "chained": "chain", "anchored": "rope", "fastened": "rope", "ties": "rope", "tie": "rope"}CONNECTORS = {"rope": "rope", "ropes": "rope", "cord": "rope", "line": "rope", "string": "string", "twine": "string", "hawser": "rope", "leash": "leash", "lead": "leash", "chain": "chain", "chains": "chain", "cable": "rope", "tether": "rope", "lasso": "rope"}
def _tethers(scene, toks, pos, trace): """rule (shift 3: "a boat tied to a dock with a rope" drew a rope coil floating in front of a hidden boat): A tied / moored / chained to B (with a rope / on a leash) = A stands next to B and a slack line runs from A (a boat's bow, an animal's collar) to B; the rope / leash / chain is that line, not a coil of its own. Balloons / kites tied to things stay with pydraw/attach.py (they float above it).""" vi = [k for k, t in enumerate(toks) if t in TIE_VERBS and k + 1 < len(toks) and toks[k + 1] in ("to", "onto", "up")] if not vi: return from .registry import CONCEPTS ents = scene["entities"] i = vi[0]
def conn(k): return CONNECTORS.get((ents[k].get("word") or "").split()[-1] if ents[k].get("word") else "") or \ CONNECTORS.get(ents[k]["concept"]) subs = [k for k, p in enumerate(pos) if p is not None and p < i and not conn(k) and ents[k].get("worn_on") is None] objs = [k for k, p in enumerate(pos) if p is not None and p > i and not conn(k) and ents[k].get("worn_on") is None] if not subs or not objs: return a, b = subs[-1], min(objs, key=lambda k: pos[k]) if ents[a]["concept"] in ("balloon", "kite"): return kind = TIE_VERBS[toks[i]] cs = [k for k in range(len(ents)) if conn(k)] for k in cs: kind = conn(k) from .physics import _drop for k in sorted(cs, reverse=True): _drop(scene, k) a -= a > k b -= b > k trace.append("language: the %s is the line that ties them, not a thing of its own" % kind) # a tethered thing faces what it is tied to (the line leaves from an animal's collar / a boat's bow); "toward" # also keeps a boat beside the pier (a plain next_to put the pier IN the boat: boats hold things) fly = CONCEPTS.get(ents[a]["concept"], {}).get("flying") and not CONCEPTS.get(ents[a]["concept"], {}).get("animal") rel = "next_to" if ents[a]["concept"] == "person" or fly else "toward" scene["relations"] = [r for r in scene["relations"] if {r[0], r[2]} != {a, b}] + [(a, rel, b)] at = ents[a].setdefault("attrs", None) or {} ents[a]["attrs"] = at at["tether"] = {"to": b, "kind": kind} scene["unknown"] = [u for u in scene.get("unknown", []) if u not in TIE_VERBS] trace.append("language: %s %s to the %s (a %s runs between them)" % (ents[a]["concept"], toks[i], ents[b]["concept"], kind))
CLOTHS = {"blanket", "blankets", "cloth", "tablecloth", "rug", "mat", "quilt", "towel", "sheet", "throw"}INDOORS = {"room", "kitchen", "bedroom", "house", "indoors", "inside", "living", "hall", "office", "classroom", "attic"}
RURAL = {"dirt", "gravel", "country", "farm", "muddy", "dusty", "sandy", "rural", "unpaved", "winding"}ROADS = {"road", "roads", "lane", "lanes", "track", "tracks", "path", "trail"}
def _rural_road(scene, toks, trace): """rule (shift 3: "a lonely mailbox at the end of a dirt road" stood in a city): a dirt / gravel / country road or lane is the countryside with a path running through it, not a city street""" hit = [k for k in range(len(toks) - 1) if toks[k] in RURAL and toks[k + 1] in ROADS] if not hit or scene.get("place") not in (None, "street"): return if any(t in ("city", "town", "downtown", "urban", "street", "streets", "sidewalk") for t in toks): return scene["place"] = "field" if "path" not in scene.setdefault("features", []): scene["features"].append("path") scene["unknown"] = [u for u in scene.get("unknown", []) if u not in RURAL] trace.append("language: '%s %s' -> countryside with a path" % (toks[hit[0]], toks[hit[0] + 1]))
BODY_TOPS = {"shell", "back", "head", "hump", "shoulders", "shoulder", "nose", "horn", "horns", "antlers", "belly", "tail", "arms", "arm"}
def _on_its_part(scene, toks, pos, trace): """rule (shift 3: "a tortoise carrying a tiny village on its shell" drew a seashell under the tortoise and the houses beside it): "... X on its shell / back / head" = X rides on the animal named before; the body part is not a thing of its own. Things bigger than the carrier shrink to a toy-like size on it (a village on a tortoise).""" from .registry import CONCEPTS from .physics import _drop ents = scene["entities"] for k, t in enumerate(toks[:-2]): if t not in ("on", "upon", "atop") or toks[k + 1] not in ("its", "his", "her", "their") or toks[k + 2] not in BODY_TOPS: continue part = [j for j, p in enumerate(pos) if p == k + 2] car = [j for j, p in enumerate(pos) if p is not None and p < k and (CONCEPTS.get(ents[j]["concept"], {}).get("animal") or ents[j]["concept"] in ("person", "robot", "scarecrow", "snowman", "statue", "teddy bear"))] if not car: return a = car[0] load = [j for j, p in enumerate(pos) if (p is None or pos[a] < p < k) and j != a and j not in part] if not load: return if part: _drop(scene, part[0]) pos = pos[:part[0]] + pos[part[0] + 1:] a -= a > part[0] load = [j - (j > part[0]) for j in load] ha = CONCEPTS[ents[a]["concept"]]["height"] * ents[a].get("size", 1.0) for j in load: scene["relations"] = [r for r in scene["relations"] if {r[0], r[2]} != {a, j}] + [(j, "on", a)] hj = CONCEPTS[ents[j]["concept"]]["height"] * ents[j].get("size", 1.0) if hj > ha * .5: ents[j]["size"] = ents[j].get("size", 1.0) * ha * .4 / hj at = ents[j].get("attrs") or {} at["fixed_scale"] = True ents[j]["attrs"] = at trace.append("language: the %s rides on the %s's %s" % (ents[j]["concept"], ents[a]["concept"], toks[k + 2])) return
def _balance(scene, toks, pos, trace): """rule (shift 3: "an elephant balancing on a beach ball" held the ball): balancing / standing / perched ON a thing = on top of it (balancing a thing on its nose stays held)""" for k, t in enumerate(toks[:-1]): if t not in ("balancing", "balances", "balanced", "teetering", "wobbling") or toks[k + 1] not in ("on", "upon", "atop"): continue subs = [j for j, p in enumerate(pos) if p is not None and p < k] objs = [j for j, p in enumerate(pos) if p is not None and p > k + 1] if not subs or not objs: return a, b = subs[-1], min(objs, key=lambda j: pos[j]) scene["relations"] = [r for r in scene["relations"] if {r[0], r[2]} != {a, b}] + [(a, "on", b)] scene["unknown"] = [u for u in scene.get("unknown", []) if u != t] trace.append("language: %s %s on the %s -> on top of it" % (scene["entities"][a]["concept"], t, scene["entities"][b]["concept"])) return
def _hollow(scene, toks, trace): """rule (shift 3: "an owl in a tree hole" sat on a branch beside the tree): a hollow / tree hole / knothole = the animal looks out of a hole in the trunk (pydraw/attach.py _intree draws it)""" text = " ".join(toks) if not re.search(r"\b(hollow|hollows|knothole|knot hole|tree hole|hole in (the|a|an|its) (tree|trunk|oak))\b", text): return from .registry import CONCEPTS ents = scene["entities"] trees = [k for k, e in enumerate(ents) if e["concept"] == "tree"] ani = [k for k, e in enumerate(ents) if CONCEPTS.get(e["concept"], {}).get("animal") and e.get("count", 1) == 1] if not trees or not ani: return a, t = ani[0], trees[0] ents[a].setdefault("attrs", {}) if ents[a]["attrs"] is None: ents[a]["attrs"] = {} ents[a]["attrs"]["hollow"] = True if not any({r[0], r[2]} == {a, t} for r in scene["relations"]): scene["relations"].append((a, "in_a", t)) scene["unknown"] = [u for u in scene.get("unknown", []) if u not in ("hollow", "hollows", "knothole", "peeking", "peeks", "peering")] trace.append("language: the %s looks out of a hollow in the tree" % ents[a]["concept"])
def _ice_ground(scene, toks, pos, trace): """rule (shift 3: "a penguin sliding on the ice" stood on a floating icicle): "on / across / over the ice" is the ground, not an object - an ice field (arctic) when no place is named, else the named place stays""" from .physics import _drop for k in range(len(scene["entities"]) - 1, -1, -1): e = scene["entities"][k] if e.get("word") != "ice" or pos[k] is None or pos[k] < 2: continue p0 = pos[k] prev = toks[p0 - 1] if toks[p0 - 1] not in ("the", "thin", "frozen", "slippery", "cracked", "sea", "pack") else toks[p0 - 2] if prev not in ("on", "across", "over", "onto", "upon", "along"): continue _drop(scene, k) pos = pos[:k] + pos[k + 1:] if not scene.get("place"): scene["place"] = "arctic" elif not scene.get("season"): scene["season"] = "winter" # (skating on the ice in the park: a winter park) trace.append("language: 'on the ice' is the ground -> %s" % scene["place"])
def _picnic(scene, toks, trace): """rule (shift 3: "a family having a picnic on a picnic blanket" drew folded towels and a table in a living room): a picnic is outdoors (a meadow unless a place is named) and its blanket / cloth is a gingham spread on the grass""" if not any(t in ("picnic", "picnics", "picnicking", "picnicked") for t in toks): return from .registry import CONCEPTS for e in scene["entities"]: w = (e.get("word") or "").split() if w and w[-1] in CLOTHS and "picnic blanket" in CONCEPTS and e.get("worn_on") is None: e["concept"], e["word"] = "picnic blanket", "picnic " + w[-1] if not e.get("color"): e["color"], e["color_explicit"] = (196, 44, 48), False trace.append("language: picnic %s -> a gingham spread on the ground" % w[-1]) if not scene.get("place") and not scene.get("room") and not any(t in INDOORS for t in toks): scene["place"] = "field" # (a meadow: the pixel park backdrop is a city skyline) trace.append("language: a picnic is outdoors -> meadow")
def _sharing(scene, toks, pos, trace): """rule (shift 2: "a cat and a dog sharing a bowl of milk" had the cat HOLD the bowl): sharing a thing = all the sharers gather round it (the thing between them); sharing a seat / bed / blanket = they are all on it""" if not any(t in ("sharing", "share", "shares", "shared") for t in toks): return from .registry import CONCEPTS i = next(k for k, t in enumerate(toks) if t in ("sharing", "share", "shares", "shared")) ents = scene["entities"] subs = [k for k, p in enumerate(pos) if p is not None and p < i and (CONCEPTS.get(ents[k]["concept"], {}).get("animal") or ents[k]["concept"] in ("person", "robot", "teddy bear"))] objs = [k for k, p in enumerate(pos) if p is not None and p > i] if not subs or not objs: return o = min(objs, key=lambda k: pos[k]) seat = ents[o]["concept"] in SHARE_SEATS or (ents[o].get("word") or "") in SHARE_SEATS rel = "on" if seat else "next_to" rels = [r for r in scene["relations"] if not (r[0] in subs and r[2] == o)] for k in subs: rels.append((k, rel, o)) scene["relations"][:] = rels trace.append("language: sharing -> %s %s the %s" % ("+".join(ents[k]["concept"] for k in subs), rel, ents[o]["concept"]))
def _old(scene, toks, pos, trace): """rule: "old" was a stop word. An old person is drawn old (grey hair, stoop, cane: people.py reads attrs age); an old tree is gnarled; an old made thing is weathered. Animals keep their look.""" from .registry import CONCEPTS ents = scene["entities"] for i, t in enumerate(toks): if t not in OLD: continue nxt = [k for k, p in enumerate(pos) if p is not None and i < p <= i + 3 and all(x not in GAP_BREAK for x in toks[i + 1:p])] if not nxt: continue e = ents[nxt[0]] at = e.get("attrs") if at is None: at = e["attrs"] = {} c = e["concept"] if c == "person": if not str(e.get("word", "")).startswith(("old", "elderly")): at["age"] = "old" trace.append("language: '%s' -> %s is old" % (t, e.get("word"))) elif CONCEPTS.get(c, {}).get("animal"): continue elif c in ("tree", "pine", "palm tree", "tree stump"): if "twisted" not in at.setdefault("cond", []): at["cond"].append("twisted") trace.append("language: '%s %s' -> gnarled" % (t, c)) elif t != "age" and not e.get("material") and not e.get("color"): if "weathered" not in at.setdefault("cond", []): at["cond"].append("weathered") trace.append("language: '%s %s' -> weathered" % (t, c))
# rule: adjectives stack ("a gnarled olive tree"): any word may sit between the adjective and its noun except theseGAP_BREAK = {"in", "on", "at", "by", "with", "of", "under", "over", "near", "next", "to", "from", "that", "which", "who", "is", "are", "was", "were", "while", "zzeos", "beside", "behind", "above", "below", "into", "for", "as", "like", "or", "but", "than", "its", "his", "her", "their"}NOUN_GAP = {"a", "an", "the", "and", "very", "slightly", "quite", "rather", "somewhat", "old", "little", "small", "big", "large", "tiny", "huge", "giant", "tall", "half", "badly", "partly", "covered", "deeply", "really", "so", "too"}
SKIN_MARKS = {"cookie", "gingerbread", "cheese", "cake", "frosting", "ice cream", "candy", "watermelon", "bread"}
def _strandy(word): """rope, cord, string, clothesline, thread, nets: WordNet says a line or a mesh""" try: from nltk.corpus import wordnet as wn lem = wn.morphy(word.replace(" ", "_"), "n") for s in (wn.synsets(lem, "n")[:3] if lem else []): if {"line.n.18", "net.n.02", "net.n.06"} & ({h.name() for h in s.closure(lambda x: x.hypernyms())} | {s.name()}): return True except Exception: pass return False
def drop_blob_strands(scene, trace): """rule (critic L26): a rope / net / clothesline that open vocabulary can only build as a generic 'blob' rendered as a fridge-sized box; a missing rope reads better than a box. Other blob nouns stay.""" if not on("strands"): return from .registry import CONCEPTS from .actions import _remove for k in range(len(scene.get("entities", [])) - 1, -1, -1): e = scene["entities"][k] ov = CONCEPTS.get(e["concept"], {}).get("open_vocab") or {} if ov.get("family") == "blob" and _strandy(e.get("word") or e["concept"]): trace.append("language: '%s' is a line / mesh with no drawable model -> not drawn (was a box)" % e.get("word")) _remove(scene, k)
FRUIT_RGB = {"plum": (110, 40, 110), "lemon": (245, 220, 60), "pear": (190, 200, 70), "peach": (250, 160, 110), "orange": (245, 140, 30), "apple": (215, 35, 35), "cherry": (200, 20, 40), "fig": (110, 60, 90), "apricot": (245, 160, 70), "lime": (130, 200, 60), "mango": (245, 180, 50), "pomegranate": (190, 30, 50), "olive": (90, 100, 50), "date": (130, 70, 30), "avocado": (80, 110, 40), "walnut": (150, 110, 70), "chestnut": (120, 70, 40), "coconut": (120, 80, 50), "persimmon": (240, 120, 40), "quince": (230, 210, 80)}
def fruit_trees(scene, trace): """rule (critic: "a plum tree" drew one plum on the grass): '<fruit> tree' is a tree carrying that fruit""" if not on("fruittree"): return from .registry import CONCEPTS for e in scene.get("entities", []): w = (e.get("word") or "").split() if len(w) >= 2 and w[-1] in ("tree", "trees") and w[-2] in FRUIT_RGB and e["concept"] != "tree" and "tree" in CONCEPTS \ and (CONCEPTS.get(e["concept"], {}).get("open_vocab") or e["concept"] == w[-2]): e["concept"] = "tree" at = e.get("attrs") if at is None: at = e["attrs"] = {} at["fruit"] = FRUIT_RGB[w[-2]] trace.append("language: '%s' -> a tree with %s fruit" % (" ".join(w), w[-2]))
def water_birds(scene, trace): """rule (critic: "three swans gliding under a stone bridge" stood in the sky): a water bird that glides / floats / drifts is swimming, on water""" if not on("waterbird"): return toks = _toks(scene.get("text", "")) if not any(t in ("gliding", "glides", "floating", "floats", "drifting", "drifts", "paddling", "bobbing") for t in toks): return if any(t in ("sky", "clouds", "air", "flying", "flies", "soaring") for t in toks): return for e in scene.get("entities", []): if e["concept"] in ("duck", "swan", "goose", "duckling", "stork") or (e.get("word") or "").split()[-1:] in ( ["swans"], ["swan"], ["geese"], ["goose"], ["ducks"], ["duck"], ["pelican"], ["pelicans"]): if e.get("pose") == "flying": e["pose"] = "swimming" if not scene.get("place") or scene.get("place") in ("field", "sky"): scene["place"] = "water" trace.append("language: gliding %s -> swimming on water" % e["concept"])
def village(scene, trace): """rule (critic: "a snowy village at night" = an empty plane): a village / hamlet with no building named is a few cottages (the city / town backgrounds already draw their buildings)""" if not on("village"): return toks = _toks(scene.get("text", "")) if not any(t in ("village", "hamlet", "villages") for t in toks) or "house" not in __import__( "pydraw.registry", fromlist=["CONCEPTS"]).CONCEPTS: return if any(e["concept"] in ("house", "castle", "church", "barn", "tower", "lighthouse", "windmill", "cabin") for e in scene["entities"]): return if scene.get("place") in ("room", "kitchen", "bedroom", "office", "bathroom", "library", "classroom", "cafe", "restaurant"): return scene["entities"].append({"concept": "house", "word": "cottages", "count": 3, "color": None, "shade": 1.0, "size": .85, "pose": None, "facing": None, "stack": False, "material": None, "color_explicit": False}) trace.append("language: a village with no building named -> 3 cottages")
def derived_tint(scene, trace): """rule: "made of X" with an X the pixel renderer has no material for (seaweed, sapphire, emerald...) takes X's colour from its WordNet gloss ("a precious stone of rich BLUE corundum"), or green for plants (was: untouched)""" if not on("derivedtint"): return for e in scene.get("entities", []): im = e.get("imagine") or {} w = im.get("skin_word") if im.get("skin") != "derived" or not w or e.get("material"): continue col = None try: from nltk.corpus import wordnet as wn from . import gloss lem = wn.morphy(w, "n") or w for s in wn.synsets(lem, "n")[:2]: F = gloss.read(s.definition()) if F.get("col"): col = F["col"][0][1] break if {"plant.n.02", "alga.n.01"} & {h.name() for h in s.closure(lambda x: x.hypernyms())}: col = (70, 130, 60) break except Exception: col = None if col: e["material"] = "tint|%d,%d,%d" % tuple(int(v) for v in col) trace.append("language: %s made of %s -> tint %s (WordNet gloss)" % (e["concept"], w, col))
def sea_things(scene, trace): """rule: a surfer's wave / a sandcastle / a lifeguard tower with no place named is at the beach (was a city street)""" if not on("seathings") or scene.get("place"): return if any(e["concept"] in ("wave", "lifeguard tower", "sandcastle") for e in scene["entities"]): scene["place"] = "beach" trace.append("language: wave / surfboard with no place -> beach")
NUMS2 = {"two", "2", "pair", "couple", "both", "twin", "twins", "double"}
def small_counts(scene, trace): """rule (shift 2: "a dozen balls of yarn" drew 12 balls as big as the kittens): several small things next to an animal / person keep a believable size against it (at least ~1/3 of its height) instead of being compressed up to its size, and stay on the floor beside it (no added table)""" if not on("smallcount"): return from .registry import CONCEPTS ents = scene.get("entities", []) if on("handful"): # rule (shift 3, knob handful): tiny things named in the plural with no number (marbles, beads, pebbles under # 5 cm) come by the handful, not as a pair toks = _toks(scene.get("text", "")) for e in ents: c = CONCEPTS.get(e["concept"]) or {} w = (e.get("word") or "").split()[-1:] if e.get("count") == 2 and w and w[0].endswith("s") and c.get("height", 1) * e.get("size", 1.0) < .05 \ and not c.get("animal") and not any(t in NUMS2 for t in toks): e["count"] = 5 trace.append("language: tiny %s with no number -> a handful (5)" % e["concept"]) live = [CONCEPTS[e["concept"]]["height"] * e.get("size", 1.0) for e in ents if e["concept"] in CONCEPTS and (CONCEPTS[e["concept"]].get("animal") or e["concept"] == "person")] if not live: return href = max(live) for e in ents: c = CONCEPTS.get(e["concept"]) if not c or c.get("animal") or e["concept"] == "person" or c.get("sim"): continue if (e.get("count") or 1) < 2 and not _small_one(scene, e): continue h = c["height"] * e.get("size", 1.0) if h > .3 or h * 1.6 > href or c["setting"] == "table" or e.get("worn_on") is not None: continue at = e.get("attrs") if at is None: at = e["attrs"] = {} if at.get("fixed_scale"): continue at["fixed_scale"] = at["small_count"] = True if h < .25 * href: e["size"] = e.get("size", 1.0) * min(.25 * href, 3 * h) / h trace.append("language: %d small %s keep their size beside the %.2f m subject" % (e["count"], e["concept"], href))
def _small_one(scene, e): """rule (shift 3, knob smallone: "a kitten with a ball of yarn" drew the ball as big as the kitten): ONE small plaything / tool beside an animal or person ("with", "playing with", "next to") keeps its real size too, unless it is held, worn or carried (then the hand sizes it) or it is the picture's own subject (named first)""" if not on("smallone"): return False ents = scene["entities"] i = ents.index(e) if i == 0 or e.get("worn_on") is not None or e.get("_held_by") is not None: return False from .registry import CONCEPTS for a, r, b in scene.get("relations", []): if i in (a, b) and r not in ("next_to", "near", "toward", "with"): return False return any(j != i and (CONCEPTS.get(x["concept"], {}).get("animal") or x["concept"] == "person") for j, x in enumerate(ents))
def strands_beside(scene, trace): """rule (shift 2): mending nets / coiling a rope = working beside the heap or coil, not holding it overhead""" if not on("strands2"): return from .registry import CONCEPTS rels = scene.get("relations", []) for k, (s_, r, o) in enumerate(rels): if r in ("toward", "holding") and o < len(scene["entities"]) and \ (CONCEPTS.get(scene["entities"][o]["concept"], {}).get("open_vocab") or {}).get("family") in ("coil", "net"): rels[k] = (s_, "next_to", o) trace.append("language: %s works beside the %s (not held)" % (scene["entities"][s_]["concept"], scene["entities"][o]["concept"])) elif on("marbles") and r in ("toward", "holding", "uses") and o < len(scene["entities"]) and \ (CONCEPTS.get(scene["entities"][o]["concept"], {}).get("open_vocab") or {}).get("family") == "marble" and \ scene["entities"][o].get("count", 1) > 1: # rule (shift 3): playing marbles = kneeling by them, the marbles on the ground (not a fistful held up) rels[k] = (s_, "next_to", o) sub = scene["entities"][s_] if sub["concept"] == "person" and sub.get("pose") in (None, "standing"): sub["pose"] = "kneeling" trace.append("language: %s plays with the %s on the ground" % (sub["concept"], scene["entities"][o]["concept"]))
def after_imagine(scene, trace): drop_blob_strands(scene, trace) strands_beside(scene, trace) small_counts(scene, trace) sea_things(scene, trace) derived_tint(scene, trace) village(scene, trace) if on() and on("onitspart"): # (after village: "a tiny village on its shell" is cottages by now) try: from .actions import _locate toks_ = _toks(scene.get("text", "")) _on_its_part(scene, toks_, _locate(toks_, scene["entities"]), trace) except Exception as ex: trace.append("language: on-its-part skipped (%s)" % ex) fruit_trees(scene, trace) water_birds(scene, trace) """rule: a word that re-skinned the thing as a material ("rusty", "mossy" -> imagine / material rules) gets no second condition pass""" for e in scene.get("entities", []): im = e.get("imagine") or {} sk = "watermelon" if im.get("skin_word") in ("watermelon", "watermelons") else im.get("skin") if sk in SKIN_MARKS and on("skinpx"): # rule: "made of cookies": the pixel renderer only tints the thing; condition_px adds the stuff's own marks at_ = e.get("attrs") if at_ is None: at_ = e["attrs"] = {} if "skin_" + sk not in at_.setdefault("cond", []): at_["cond"].append("skin_" + sk) trace.append("language: %s made of %s -> pixel marks" % (e["concept"], sk)) for e in scene.get("entities", []): at = e.get("attrs") or {} if not at.get("cond") or not (e.get("material") or e.get("imagine")): continue sk = (e.get("imagine") or {}).get("skin_word") from .materials import MATERIAL_WORDS for w in list(at.get("cond_words", [])): if w == sk or MATERIAL_WORDS.get(w) == e.get("material"): c = COND.get(w) or cond_of(w)[0] at["cond_words"].remove(w) if c in at["cond"] and not any((COND.get(x) or cond_of(x)[0]) == c for x in at["cond_words"]): at["cond"].remove(c) trace.append("language: '%s' is already %s's material; no condition pass" % (w, e["concept"]))
def _conditions(scene, toks, pos, trace): ents = scene["entities"] unknown = set(scene.get("unknown", [])) starts = [] for k, e in enumerate(ents): p = pos[k] ln = len((e.get("word") or e["concept"]).split()) starts.append(None if p is None else p - ln + 1) used = set() inside = set() # rule: a word inside a noun ("hair drier") is never an adjective for k, s in enumerate(starts): if s is not None: inside.update(range(s, pos[k] + 1)) for i, t in enumerate(toks): if len(t) < 3 or t.isdigit() or i in inside: continue if t in ("holes", "rips", "tears", "patches") and i > 0 and toks[i - 1] in ("with", "of"): # rule: "a sweater with holes", "a coat full of holes": the thing before is torn (people's tears are crying) prv = [kk for kk, p in enumerate(pos) if p is not None and p < i and i - p <= 4] if prv and not (t == "tears" and _animate_word((ents[prv[-1]].get("word") or "x").split()[-1])): at = ents[prv[-1]].get("attrs") if at is None: at = ents[prv[-1]]["attrs"] = {} if "torn" not in at.setdefault("cond", []): at["cond"].append("torn") trace.append("language: 'with %s' -> %s is torn" % (t, ents[prv[-1]]["concept"])) continue cls, how = cond_of(t) if not cls or (how == "wordnet" and t not in unknown): continue # rule: WordNet relatives only for words the parser dropped (hand words anywhere) if t == "moth" and not (i + 1 < len(toks) and toks[i + 1] == "eaten"): continue k = None # attributive: the next entity whose word starts within a few tokens, only adjectives / colours between from .understanding import COLORS, SIZES, MATERIAL_WORDS for kk, s in enumerate(starts): if s is not None and i < s <= i + 4 and all(x in NOUN_GAP or x in COLORS or x in SIZES or MATERIAL_WORDS.get(x) or x in ("wooden", "metal", "stone", "iron", "brick", "leather") or cond_of(x)[0] or x == "eaten" or (x not in GAP_BREAK and (not x.endswith("ing") or s - i <= 2) and s - i <= 3) for x in toks[i + 1:s]): k = kk break # predicative: "the fence is weathered", "a tractor, rusty and half buried", "its hull is battered" if k is None: prv = [kk for kk, p in enumerate(pos) if p is not None and p < i and i - p <= 4] gap = set(AUX) | REL_PRON | ({"so", "all", "now", "still"} if t in ATTRIB_ONLY else NOUN_GAP | {"so", "all", "now", "still"}) if prv and all(x in gap for x in toks[pos[prv[-1]] + 1:i]): k = prv[-1] if k is None and on("partcond"): # rule: "a ship with tattered sails", "a tower with a crooked roof": a condition on a part dresses its owner from .understanding import BODY_PARTS nxt = [x for x in toks[i + 1:i + 4] if x not in NOUN_GAP and not (x in COLORS)] if nxt and nxt[0] in BODY_PARTS and cls not in ("glowing", "shiny", "bare"): # (glowing windows != a glowing house) prv = [kk for kk, p in enumerate(pos) if p is not None and p < i and i - p <= 6] if prv: k = prv[-1] if k is None: continue at = ents[k].get("attrs") if at is None: at = ents[k]["attrs"] = {} lst = at.setdefault("cond", []) if cls not in lst: lst.append(cls) at.setdefault("cond_words", []).append(t) used.add(t) trace.append("language: '%s' -> %s is %s%s" % (t, ents[k]["concept"], cls, "" if how == "hand" else " (wordnet)")) if used and scene.get("unknown"): scene["unknown"] = [u for u in scene["unknown"] if u not in used and not (u == "eaten" and "moth" in used)]
# verbs: WordNet roots -> (pose, action); checked in order on the hypernym closure of the verb's first two sensesVERB_ROOTS = [("kneel.v.01", "kneeling", None), ("sleep.v.01", "sleeping", None), ("rest.v.02", "lying", None), ("lie.v.02", "lying", None), ("sit.v.01", "sitting", None), ("wait.v.01", "sitting", None), ("swim.v.01", "swimming", None), ("fly.v.01", "flying", None), ("float.v.01", "flying", None), ("drift.v.01", "flying", None), ("jump.v.01", "jumping", None), ("run.v.01", "running", None), ("walk.v.01", "walking", None), ("travel.v.01", "walking", None), ("eat.v.01", None, "eat"), ("consume.v.02", None, "eat"), ("drink.v.01", None, "drink"), ("make.v.03", None, "work"), ("repair.v.01", None, "work"), ("hit.v.03", None, "work"), ("sew.v.01", None, "work"), ("clean.v.01", None, "work")]
def verb_of(w): if ("v", w) in _WN_CACHE: return _WN_CACHE[("v", w)] res = None try: from nltk.corpus import wordnet as wn lem = wn.morphy(w, "v") if lem: syn = wn.synsets(lem, "v")[:2] for s in syn: clos = {s.name()} | {h.name() for h in s.closure(lambda x: x.hypernyms())} for root, pose, act in VERB_ROOTS: if root in clos: res = (pose, act, lem) break if res: break except Exception: pass _WN_CACHE[("v", w)] = res return res
def _is_verb(w): try: from nltk.corpus import wordnet as wn return bool(wn.morphy(w, "v")) except Exception: return False
def _mainly_verb(w): try: from nltk.corpus import wordnet as wn lem = wn.morphy(w, "v") return bool(lem) and len(wn.synsets(lem, "v")) > 2 * len(wn.synsets(w, "n")) and not wn.synsets(w, "a") except Exception: return False
def _transitive(scene, toks, pos, i, k, trace): """rule: "a raccoon raiding a trash can": a verb with a thing right after it links subject -> object (facing it)""" j = i + 1 while j < len(toks) and (toks[j] in NOUN_GAP or toks[j] in ("some", "his", "her", "its", "their", "single")) and j - i < 5: j += 1 obj = [kk for kk, p in enumerate(pos) if p is not None and kk != k and j <= p <= j + 2] if not obj: return o = obj[0] if any({a, b} == {k, o} for a, _, b in scene["relations"]): return lem = (verb_of(toks[i]) or (None, None, toks[i]))[2] if lem in ("cross", "climb", "traverse", "scale"): rel = "on" # rule: "geese crossing a bridge" are on it elif scene["entities"][k].get("count", 1) > 1: return # rule: several subjects facing one thing made layout clone the thing (critic: a second bridge) else: rel = "toward" scene["relations"].append((k, rel, o)) trace.append("language: '%s' links %s -> %s (toward)" % (toks[i], scene["entities"][k]["concept"], scene["entities"][o]["concept"]))
def _verbs(scene, toks, pos, trace): from .registry import CONCEPTS from .actions import VERBS, _animate ents = scene["entities"] anim = [k for k, e in enumerate(ents) if _animate(e, CONCEPTS)] if not anim: return used = set() for i, t in enumerate(toks): if t in VERBS and t.endswith("ing") and i + 1 < len(toks) and toks[i + 1] in ("a", "an", "the", "his", "her", "its", "their") \ and on("transitive"): # rule: "a snail racing a tortoise": a table verb with a thing after it links subject -> object too prv = [kk for kk in anim if pos[kk] is not None and pos[kk] < i and i - pos[kk] <= 3] if prv: _transitive(scene, toks, pos, i, prv[-1], trace) if t in ("pack", "herd", "flock", "family", "friends", "siblings", "litter") and i > 0 \ and toks[i - 1] in ("its", "his", "her", "their") and on("quantity"): # rule: "a wolf howling with its pack": more of the same kind prv = [kk for kk in anim if pos[kk] is not None and pos[kk] < i] if prv and ents[prv[-1]].get("count", 1) < 3: ents[prv[-1]]["count"] = 4 trace.append("language: 'with %s %s' -> %d %s" % (toks[i - 1], t, 4, ents[prv[-1]]["concept"])) used.add(t) if t not in VERBS and i > 0 and i + 1 < len(toks) and toks[i + 1] in PREP_DET and _nounish(toks[i - 1]) \ and (not _stable_noun(t) or _gerund(t, toks[i - 1]) in VERBS or (_animate_word(toks[i - 1]) and verb_of(_gerund(t, toks[i - 1]) or "") is not None)): g = _gerund(t, toks[i - 1]) # "birds fly over", "horses race across": the hand verb table by its -ing form prv = [kk for kk in anim if pos[kk] == i - 1] if g in VERBS and prv: e = ents[prv[0]] pose_, act_ = VERBS[g] if pose_ and e.get("pose") in (None, "standing") and not (pose_ == "flying" and e["concept"] == "person"): e["pose"] = pose_ if act_: (e.setdefault("attrs", None) or e.__setitem__("attrs", {}) or e["attrs"]).setdefault("action", act_) trace.append("language: '%s' (%s) -> %s pose=%s" % (t, g, e["concept"], e.get("pose"))) used.add(t) continue if g and prv: # a verb the table lacks ("a dragon guards a pile"): still links subject -> object vo = verb_of(g) e = ents[prv[0]] if vo and vo[0] and e.get("pose") in (None, "standing"): pz = "flying" if vo[0] == "walking" and CONCEPTS.get(e["concept"], {}).get("flying") else vo[0] if not (pz == "flying" and e["concept"] == "person"): e["pose"] = pz # "seagulls circle over" -> flying _transitive(scene, toks, pos, i, prv[0], trace) used.add(g) continue if t in VERBS or t not in scene.get("unknown", []) or len(t) < 3: continue v = verb_of(t) if not v: if t.endswith("ing") and _is_verb(t): # no pose for it, but it still links subject -> object prv = [kk for kk in anim if pos[kk] is not None and pos[kk] < i and i - pos[kk] <= 3] if prv: _transitive(scene, toks, pos, i, prv[-1], trace) continue # rule: "-ing" words are verbs; other unknown words when WordNet knows them mainly as verbs, or an -s form right # after a noun ("a knight in dented armor rests") if not t.endswith("ing") and not _mainly_verb(t) and not (t.endswith("s") and i > 0 and toks[i - 1] not in NOUN_GAP and not t.endswith("ss")): continue pose, act, lem = v prv = [k for k in anim if pos[k] is not None and pos[k] < i] nxt = [k for k in anim if pos[k] is not None and i < pos[k] <= i + 3] k = max(prv, key=lambda kk: pos[kk]) if prv else (nxt[0] if nxt else None) if k is None: continue e = ents[k] at = e.get("attrs") if at is None: at = e["attrs"] = {} if pose == "walking" and CONCEPTS.get(e["concept"], {}).get("flying"): pose = "flying" # rule: a bird that travels / circles / drifts flies if pose and e.get("pose") in (None, "standing") and not (pose == "flying" and not CONCEPTS.get(e["concept"], {}).get("flying") and e["concept"] == "person"): e["pose"] = pose if act and not at.get("action"): at["action"] = act at.setdefault("verbs", []).append(lem) used.add(t) _transitive(scene, toks, pos, i, k, trace) trace.append("language: verb '%s' (%s) -> %s pose=%s action=%s" % (t, lem, e["concept"], e.get("pose"), act)) if used: scene["unknown"] = [u for u in scene["unknown"] if u not in used]
YOUNG = {"duckling", "ducklings", "kitten", "kittens", "puppy", "puppies", "pup", "pups", "cub", "cubs", "chick", "chicks", "foal", "foals", "calf", "calves", "lamb", "lambs", "piglet", "piglets", "gosling", "goslings", "fawn", "fawns", "cygnet", "cygnets", "owlet", "owlets", "joey", "joeys", "bunny", "bunnies", "kit", "kits", "hatchling", "hatchlings"}PARENT = {"mother", "mom", "mum", "mama", "mommy", "father", "dad", "papa", "daddy", "parent", "parents"}
def _young(scene, toks, pos, trace): """rule: young animals are small; "their / its mother" after animals is a grown animal of the same kind""" from .registry import CONCEPTS ents = scene["entities"] for k, e in enumerate(ents): w = (e.get("word") or "").split()[-1:] if w and w[0] in YOUNG and CONCEPTS.get(e["concept"], {}).get("animal") and abs(e.get("size", 1) - 1) < .01: e["size"] = .6 trace.append("language: '%s' is young -> %s size .6" % (w[0], e["concept"])) for k, e in enumerate(ents): w = (e.get("word") or "").split()[-1:] if not w or w[0] not in PARENT or e["concept"] != "person" or pos[k] is None: continue if not (pos[k] > 0 and toks[pos[k] - 1] in ("their", "its", "her", "his")): continue prv = [j for j in range(k) if CONCEPTS.get(ents[j]["concept"], {}).get("animal") and ents[j]["concept"] != "person"] if not prv: continue j = prv[-1] e["concept"], e["count"], e["size"] = ents[j]["concept"], 1, 1.0 e["color"] = e.get("color") or ents[j].get("color") trace.append("language: '%s %s' after %s -> a grown %s" % (toks[pos[k] - 1], w[0], ents[j]["word"], e["concept"]))
# negated parts: "without leaves" / "with no tail" / "no leaves on it" -> the thing before has that part absentPART_NEG = {"leaves": "leaves", "leaf": "leaves", "foliage": "leaves", "tail": "tail", "branches": "branches", "branch": "branches", "windows": "windows", "window": "windows", "wheels": "wheels", "roof": "roof", "legs": "legs", "petals": "petals", "sails": "sails", "sail": "sails", "doors": "door", "door": "door", "head": "head", "wings": "wings", "fur": "fur", "feathers": "feathers", "ears": "ears", "eyes": "eyes", "hands": "hands", "arms": "arms", "lid": "lid", "handle": "handle", "chimney": "chimney", "needles": "leaves"}NEG_WORDS = ("no", "without", "lacking")
def _neg_parts(scene, toks, pos, trace): neg = scene.get("negated") or [] ents = scene["entities"] for i, t in enumerate(toks): if t not in NEG_WORDS: continue j = i + 1 while j < len(toks) and toks[j] in ("a", "an", "any", "its", "their", "single"): j += 1 if j >= len(toks) or toks[j] not in PART_NEG: continue part = PART_NEG[toks[j]] prv = [k for k, p in enumerate(pos) if p is not None and p < i and i - p <= 3] if not prv: continue k = prv[-1] at = ents[k].get("attrs") if at is None: at = ents[k]["attrs"] = {} ab = at.setdefault("absent", []) if part not in ab: ab.append(part) trace.append("language: '%s %s' -> %s without %s" % (t, toks[j], ents[k]["concept"], part))12345612 unmodified lines192021222324252627282930313233343550 unmodified lines868788899091924 unmodified lines97989910010110235 unmodified lines1381391401411421432 unmodified lines14614714814915015184 unmodified lines23623723823924024124288 unmodified lines33133233333433533617 unmodified lines35435535635735835936012 unmodified lines37337437537637737837960 unmodified lines4404414424434444453 unmodified lines449450451452453454455456457458459460197 unmodified lines65865966066166266366437 unmodified lines7027037047057067077084 unmodified lines7137147157167177187197207219 unmodified lines73173273373473573673740 unmodified lines77877978078178278378445 unmodified lines8308318328338348355 unmodified lines84184284384484584684784884985085156 unmodified lines908909910911912913914915"""Layout rules: scene graph -> placed instances (x, ground y, pixel height) via a pinhole camera."""import reimport math, randomfrom .registry import CONCEPTSfrom .scenes import HORIZON12 unmodified lines(" %s %s" % (self.rel, self.bound.concept)) if self.bound else "")def choose_place(scene, trace):if scene["place"]:return scene["place"]ents = scene["entities"]if not ents:return "field"settings = [CONCEPTS[e["concept"]]["setting"] for e in ents]if scene.get("framing") == "close" and ents[0]["concept"] == "person":trace.append("layout: portrait of a person -> studio backdrop")return "studio"if all(CONCEPTS[e["concept"]]["flying"] for e in ents):if any(CONCEPTS[e["concept"]]["setting"] == "space" for e in ents):return "space"trace.append("layout: everything flies -> sky setting")50 unmodified linesfocal = float(H)scene["place"] = choose_place(scene, trace)if scene["place"] in ("mountains", "field", "forest", "farm", "park", "savanna") and any(CONCEPTS[e["concept"]]["setting"] in ("water", "underwater") and CONCEPTS[e["concept"]]["animal"] for e in scene["entities"]):trace.append("layout: sea animal on land -> water (with %s behind)" % scene["place"])scene["place"] = "water" # rule: a whale near a mountain is in the water, not on grassfv = scene.get("vary", {}).get("field_variant")4 unmodified linesscene["place"] = "underwater" # rule: only sea creatures + "ocean/sea" = under the seatrace.append("layout: only sea creatures -> underwater")place = scene["place"]if place in ROOMS and "dining table" in CONCEPTS:# rule: in a room, tabletop things stand on a table (added if the prompt names no support)supported = {s for s, rel, o in scene["relations"] if rel in ("on", "under", "above", "below")}35 unmodified linesfor k in range(e["count"] if e.get("worn_on") is None else 0): # wave 12: a worn thing is drawn by its wearer# rule: repeated instances vary a little in size so a group doesn't look clonedjitter = rng.uniform(.92, 1.06) if e["count"] > 1 else 1.0insts.append(Inst(concept=e["concept"], ent=ei, k=k, info=info, color=e["color"], shade=e.get("shade", 1.0),pose=e["pose"], facing=e["facing"], world_h=info["height"] * e["size"] * jitter, word=e.get("word", ""),wall=e.get("wall", False), implicit=e.get("implicit", False),2 unmodified linesside=e.get("side"), depth=e.get("depth"), color_explicit=e.get("color_explicit", True),hair=e.get("hair"), beard=e.get("beard"), expression=e.get("expression"),rng=random.Random(rng.random()), bound=None, rel=None, haze=0.0, place=place, attrs=e.get("attrs") or {}))y0 = H * (HORIZON.get(place, .5) + scene.get("vary", {}).get("horizon_dy", 0))if scene.get("camera") == "high": # rule: seen from above = high horizon, more groundy0 = H * .2284 unmodified linescontinuerel = "on" if oc in CONTAIN else "next_to"if rel == "holding":if scene["entities"][s]["concept"] in ("person",) or (CONCEPTS[scene["entities"][s]["concept"]]["animal"] and CONCEPTS[oc]["height"] < .8) \or (scene["entities"][s].get("attrs") or {}).get("anthro"): # wave 12: anthro animals hold like peoplefor it in insts:if it.ent == o:88 unmodified linescontinue # 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 ** keep / _wfif abs(math.log(ratio)) > .4:17 unmodified lines_E = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)target_px = H * float(_E.get("subj", .52)) / (1 + .3 * (n_subj - 1))target_px *= scene.get("vary", {}).get("size_k", 1.0)if len(scene["entities"]) == 1 and n_subj == 1 and len(insts) == 1 and not scene.get("framing") \and _E.get("solo", "1") != "0":# rule (framing): a lone subject is the picture - it fills well over half the frame height (a pixel artist# frames the hero big, with a clear silhouette), still leaving room for the setting above12 unmodified linesdef stack_h(it):# rule: whatever sits on top of a thing counts toward its height when fitting the frameriders = [o for o in insts if o.bound is it and o.rel == "on"]return it.world_h + (max(stack_h(o) for o in riders) if riders else 0)def need(it):60 unmodified linesit.w *= mp / it.hit.h = mpcontinueif it.h < mp and it.rel != "on":it.d *= it.h / mpit.d = max(it.d, d_near(it) * .55)3 unmodified linesit.y = H * .985units = []for it in ground:if it.rel == "on":continueif it.bound is None or it.rel in ("behind", "in_front_of") or it.bound.pose == "flying" or it.bound.rel == "on":units.append([it])for it in ground:if it.bound is not None and it.rel in ("under", "next_to", "left_of", "right_of") and it.bound.pose != "flying":for u in units:if u[0] is it.bound:197 unmodified linesk = _mt * .94 / it.hit.h *= kit.w *= kif it.h > b.h * 1.2 and not getattr(it, "riding", False): # rule: a rider can't dwarf what it sits on (except real riders)s = b.h * 1.2 / it.hit.h *= sit.w *= s37 unmodified lines# flying things: in the sky band; subject flyers get bigfor it in flying:it.d = 0big = it is subj or it.ent == subj.entnfly = sum(1 for o in flying if o.ent == it.ent)base = H * (.3 if place == "sky" else .26) / (1 + .35 * (nfly - 1)) if big else H * .12it.h = base * min(1.6, (it.world_h / it.info["height"]) ** .5)4 unmodified linesif big:it.h = min(it.h, H * .6)it.w = it.h * it.info["aspect"]for i, it in enumerate(flying):big = it is subj or it.ent == subj.entif it.bound is not None and hasattr(it.bound, "x"):sib = [o for o in flying if o.bound is it.bound]j = sib.index(it)it.x = it.bound.x + (j - (len(sib) - 1) / 2) * it.w * 1.159 unmodified linesit.x = W * (.5 + .22 * (1 if it.rng.random() < .5 else -1)) if len(insts) > 1 else W / 2it.y = getattr(it, "wall_y", y0 * .2 + it.h)else:sib = [o for o in flying if o.bound is None]j = sib.index(it)tot = sum(o.w for o in sib)if tot > W * .9: # rule: flyers never overlap; shrink the flock to fit the width40 unmodified linesit.y = hold.y - hold.h * .58 # rule: the canopy clears the headelif hold.concept != "person":# rule: an animal holding / reading something holds it in front of its chest, about a third of its sizeit.h = max(H * .08, hold.h * .32)it.w = it.h * it.info["aspect"]it.x = hold.x + side * hold.w * .3it.y = hold.y - hold.h * .2545 unmodified linesit.y = w8.y - w8.h * anchor + it.h * .5it.bound, it.rel, it.d = w8, "on", w8.dit.facing = w8.facingtrace.append("layout: %s worn by %s on the %s" % (it.concept, w8.concept, kind))for it in ground:if getattr(it, "wrap", False) and it.bound is not None and hasattr(it.bound, "x"):5 unmodified lines# rule: a jumping thing is lifted off the ground by a third of its height; its shadow stays belowit.ground_y = it.yit.y -= it.h * .32# rule: final size floor: every named ground thing is at least 12% of the frame tall (grown in place)for it in ground:if hasattr(it, "h") and it.h < H * .12 and not getattr(it, "stacked", False) and getattr(it, "worn_by", None) is None \and getattr(it, "held_by", None) is None and not it.implicit:k = H * .12 / it.hit.h *= kit.w *= k# rule: something resting on a flying thing travels with it (drawn just above it)56 unmodified linesit.facing = "left" if it.rng.random() < .5 else "right"else:it.facing = "left" if it.x > W / 2 else "right"from .perch import layout_rule as _perch_perch(insts, W, H, trace)for it in insts:trace.append("layout: %r" % it)return insts, y012345612 unmodified lines19202122232425262728293031323334353637383940414250 unmodified lines939495969798991001014 unmodified lines10610710810911011111211311411511611711811912035 unmodified lines1561571581591601611621632 unmodified lines16616716816917017117217317417517617784 unmodified lines26226326426526626726888 unmodified lines35735835936036136236336417 unmodified lines38238338438538638738812 unmodified lines40140240340440540640760 unmodified lines4684694704714724734744753 unmodified lines479480481482483484485486487488489490491492493494495496497498499500501197 unmodified lines69970070170270370470570670770870971071171271371471571671771871972072172272337 unmodified lines7617627637647657667674 unmodified lines7727737747757767777787797807817827837847857867877887897907917927937949 unmodified lines80480580680780880981040 unmodified lines85185285385485585685745 unmodified lines9039049059069079089095 unmodified lines91591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594656 unmodified lines10031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043"""Layout rules: scene graph -> placed instances (x, ground y, pixel height) via a pinhole camera."""import reimport math, os, randomfrom .registry import CONCEPTSfrom .scenes import HORIZON12 unmodified lines(" %s %s" % (self.rel, self.bound.concept)) if self.bound else "")_E0 = dict(kv.split("=") for kv in __import__("os").environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)def choose_place(scene, trace):if scene["place"]:return scene["place"]ents = scene["entities"]if not ents:return "field"if _E0.get("wornplace", "1") != "0": # rule (night): a worn scarf / hat does not pick the setting (it is part of its wearer)ents = [e for e in ents if e.get("worn_on") is None] or entssettings = [CONCEPTS[e["concept"]]["setting"] for e in ents]if scene.get("framing") == "close" and ents[0]["concept"] == "person":trace.append("layout: portrait of a person -> studio backdrop")return "studio"_rest = ("sleeping", "sitting", "lying", "resting", "perched", "standing", "walking", "grazing", "curled")if all(CONCEPTS[e["concept"]]["flying"] for e in ents) and not (_E0.get("restfly", "1") != "0" and any(e.get("pose") in _rest for e in ents)): # (night: a sleeping dragon is on the ground)if any(CONCEPTS[e["concept"]]["setting"] == "space" for e in ents):return "space"trace.append("layout: everything flies -> sky setting")50 unmodified linesfocal = float(H)scene["place"] = choose_place(scene, trace)if scene["place"] in ("mountains", "field", "forest", "farm", "park", "savanna") and any(CONCEPTS[e["concept"]]["setting"] in ("water", "underwater") and CONCEPTS[e["concept"]]["animal"]and not (e.get("pose") in ("walking", "standing", "running", "sitting", "sleeping", "lying") and _E0.get("landwalk", "1") != "0")for e in scene["entities"]): # (night: "five ducks waddling in a row" walk on land)trace.append("layout: sea animal on land -> water (with %s behind)" % scene["place"])scene["place"] = "water" # rule: a whale near a mountain is in the water, not on grassfv = scene.get("vary", {}).get("field_variant")4 unmodified linesscene["place"] = "underwater" # rule: only sea creatures + "ocean/sea" = under the seatrace.append("layout: only sea creatures -> underwater")place = scene["place"]from .attach import relations as _attach_rel # night (scene): flags on towers, signs on fronts, hanging thingsfrom .surface import mark as _surface_mark # night (scene): "a cracked rock" -> entity surface statefrom .stage import pre as _stage_pre # night (scene): "a knight facing a dragon" -> turned towardfor _f in (_attach_rel, _surface_mark, _stage_pre):try:_f(scene, trace)except Exception as _ex: # a staging rule must never take the picture downtrace.append("layout: %s skipped (%s)" % (_f.__module__, str(_ex)[:80]))place = scene["place"] # (the night pre-passes may move the scene: shop front -> street, at sea -> water, room)if place in ROOMS and "dining table" in CONCEPTS:# rule: in a room, tabletop things stand on a table (added if the prompt names no support)supported = {s for s, rel, o in scene["relations"] if rel in ("on", "under", "above", "below")}35 unmodified linesfor k in range(e["count"] if e.get("worn_on") is None else 0): # wave 12: a worn thing is drawn by its wearer# rule: repeated instances vary a little in size so a group doesn't look clonedjitter = rng.uniform(.92, 1.06) if e["count"] > 1 else 1.0if e.get("family") and e["count"] > 1: # rule (night, pydraw/stage.py): a family = parents + smaller youngjitter = (1.0, .9, .6, .55, .5, .48)[min(k, 5)]insts.append(Inst(concept=e["concept"], ent=ei, k=k, info=info, color=e["color"], shade=e.get("shade", 1.0),pose=e["pose"], facing=e["facing"], world_h=info["height"] * e["size"] * jitter, word=e.get("word", ""),wall=e.get("wall", False), implicit=e.get("implicit", False),2 unmodified linesside=e.get("side"), depth=e.get("depth"), color_explicit=e.get("color_explicit", True),hair=e.get("hair"), beard=e.get("beard"), expression=e.get("expression"),rng=random.Random(rng.random()), bound=None, rel=None, haze=0.0, place=place, attrs=e.get("attrs") or {}))if e.get("surface"):insts[-1].surface = e["surface"]if e.get("attach"):insts[-1].attach_kind = e["attach"] # night (scene): pydraw/attach.pyif e.get("peek"):insts[-1].peek = Truey0 = H * (HORIZON.get(place, .5) + scene.get("vary", {}).get("horizon_dy", 0))if scene.get("camera") == "high": # rule: seen from above = high horizon, more groundy0 = H * .2284 unmodified linescontinuerel = "on" if oc in CONTAIN else "next_to"if rel == "holding":if scene["entities"][s]["concept"] in ("person",) or (CONCEPTS[scene["entities"][s]["concept"]]["animal"] and CONCEPTS[oc]["height"] * (scene["entities"][o].get("size", 1) if scene["entities"][o].get("mouth_size") else 1) < .8) \or (scene["entities"][s].get("attrs") or {}).get("anthro"): # wave 12: anthro animals hold like peoplefor it in insts:if it.ent == o:88 unmodified linescontinue # 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 itif getattr(it, "attach_kind", None) in ("flag", "sign", "hang", "front", "ladder", "back", "stuffed", "inside", "ballsupport", "shelter"):continue # rule (night): an attached thing is sized from its host (pydraw/attach.py)keep = .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 ** keep / _wfif abs(math.log(ratio)) > .4:17 unmodified lines_E = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)target_px = H * float(_E.get("subj", .52)) / (1 + .3 * (n_subj - 1))target_px *= scene.get("vary", {}).get("size_k", 1.0)if ((len(scene["entities"]) == 1 and len(insts) == 1) or scene.get("attach_solo")) and n_subj == 1 and not scene.get("framing") \and _E.get("solo", "1") != "0":# rule (framing): a lone subject is the picture - it fills well over half the frame height (a pixel artist# frames the hero big, with a clear silhouette), still leaving room for the setting above12 unmodified linesdef stack_h(it):# rule: whatever sits on top of a thing counts toward its height when fitting the frameriders = [o for o in insts if o.bound is it and o.rel == "on" and getattr(o, "attach_kind", None) not in ("sign", "hang", "front", "intree", "ladder", "stuffed", "inside")]return it.world_h + (max(stack_h(o) for o in riders) if riders else 0)def need(it):60 unmodified linesit.w *= mp / it.hit.h = mpcontinueif it.h < mp and (it.attrs or {}).get("small_count") and "smallcount" not in os.environ.get("PYDRAW_LANG_OFF", ""):continue # rule (language shift 2): counted small things beside an animal keep their size against itif it.h < mp and it.rel != "on":it.d *= it.h / mpit.d = max(it.d, d_near(it) * .55)3 unmodified linesit.y = H * .985units = []# rule (language shift 2): counted small things beside an animal / person (a dozen balls of yarn round two kittens)# take no room in the row; they are scattered round the others' feet afterwards at their own small sizescatter = [it for it in ground if (it.attrs or {}).get("small_count") and it.rel != "on"and "smallcount" not in os.environ.get("PYDRAW_LANG_OFF", "")]if not [it for it in ground if it not in scatter and it.rel != "on"]:scatter = []for it in ground:if it.rel == "on" or it in scatter:continueif it.bound is None or it.rel in ("behind", "in_front_of") or it.bound.pose == "flying" or it.bound.rel == "on":units.append([it])for it in ground:if it in scatter:continueif it.bound is not None and it.bound in scatter and it.rel in ("under", "next_to", "left_of", "right_of"):units.append([it])continueif it.bound is not None and it.rel in ("under", "next_to", "left_of", "right_of") and it.bound.pose != "flying":for u in units:if u[0] is it.bound:197 unmodified linesk = _mt * .94 / it.hit.h *= kit.w *= kif it.h > b.h * 1.2 and not getattr(it, "riding", False) and it.ent == subj.ent and float(b.info.get("aspect", 1) or 1) >= 2.2 \and b.bound is None and _E.get("flatsup", "1") != "0":# rule (night, scene): a subject lying on a wide flat support (a dragon on its hoard, a cat on a# rug) keeps its size; the support spreads out under it instead of shrinking the subject to a speckk = min(it.w * 1.25 / max(1e-6, b.w), W * .95 / max(1e-6, b.w))if k > 1:b.w *= kb.h *= kit.y = b.y - b.h * b.info["on_top"]trace.append("layout: %s spreads under the %s (x%.1f)" % (b.concept, it.concept, k))continueflat_ = _E.get("flatpad", "1") != "0" and float(b.info.get("aspect", 1) or 1) >= 2.5 and b.info.get("on_top", 1) <= .5# (night characters 2, flatpad): standing on a rug / in a puddle is not sitting on a box - no shrinkif flat_ and b.concept in ("lily pad", "puddle") and it.w > b.w * .7 and len(sibs) == 1:k = it.w * 1.4 / b.w # (flatpad) the pad / puddle grows round its stander, not the stander shrinksb.w *= kb.h *= kit.y = b.y - b.h * b.info["on_top"]if it.h > b.h * 1.2 and not getattr(it, "riding", False) and not flat_ and getattr(b, "attach_kind", None) != "ballsupport": # rule: a rider can't dwarf what it sits on (except real riders)s = b.h * 1.2 / it.hit.h *= sit.w *= s37 unmodified lines# flying things: in the sky band; subject flyers get bigfor it in flying:it.d = 0big = it is subj or it.ent == subj.ent or any(getattr(o, "bound", None) is it and o.rel in ("on", "riding") for o in insts) # (night: a flyer carrying a rider is a main subject)nfly = sum(1 for o in flying if o.ent == it.ent)base = H * (.3 if place == "sky" else .26) / (1 + .35 * (nfly - 1)) if big else H * .12it.h = base * min(1.6, (it.world_h / it.info["height"]) ** .5)4 unmodified linesif big:it.h = min(it.h, H * .6)it.w = it.h * it.info["aspect"]# (night, scene: a flyer bound to another flyer - "a girl flying on the back of a giant bird" - is placed after its# host; before, the host had no position yet and the free-flyer branch crashed looking the rider up)for i, it in enumerate(sorted(flying, key=lambda o: o.bound is not None and o.bound in flying)):big = it is subj or it.ent == subj.entif it.bound is not None and hasattr(it.bound, "x") and it.bound in flying and it.rel in ("on", "riding") \and it.bound.info.get("animal"):# rule: a rider on a flying creature sits on its back (not in clear air above it)b = it.boundif it.h > b.h * .7:k_ = b.h * .7 / it.hit.h *= k_it.w *= k_it.x = b.x - b.w * .05it.y = b.y - b.h * .55it.pose = "flying"it.riding = Trueelif it.bound is not None and hasattr(it.bound, "x"):sib = [o for o in flying if o.bound is it.bound]j = sib.index(it)it.x = it.bound.x + (j - (len(sib) - 1) / 2) * it.w * 1.159 unmodified linesit.x = W * (.5 + .22 * (1 if it.rng.random() < .5 else -1)) if len(insts) > 1 else W / 2it.y = getattr(it, "wall_y", y0 * .2 + it.h)else:sib = [o for o in flying if o.bound is None or o is it]j = sib.index(it)tot = sum(o.w for o in sib)if tot > W * .9: # rule: flyers never overlap; shrink the flock to fit the width40 unmodified linesit.y = hold.y - hold.h * .58 # rule: the canopy clears the headelif hold.concept != "person":# rule: an animal holding / reading something holds it in front of its chest, about a third of its sizeit.h = max(H * .08, hold.h * .32) if not scene["entities"][it.ent].get("mouth_size") else max(H * .04, hold.h * .2)it.w = it.h * it.info["aspect"]it.x = hold.x + side * hold.w * .3it.y = hold.y - hold.h * .2545 unmodified linesit.y = w8.y - w8.h * anchor + it.h * .5it.bound, it.rel, it.d = w8, "on", w8.dit.facing = w8.facingit._worn_at = (w8, it.x - w8.x, it.y - w8.y, w8.h, it.h) # (night characters 3, wornfix) re-anchored belowtrace.append("layout: %s worn by %s on the %s" % (it.concept, w8.concept, kind))for it in ground:if getattr(it, "wrap", False) and it.bound is not None and hasattr(it.bound, "x"):5 unmodified lines# rule: a jumping thing is lifted off the ground by a third of its height; its shadow stays belowit.ground_y = it.yit.y -= it.h * .32anchors = [it for it in ground if it not in scatter and hasattr(it, "x") and it.rel != "on"]if scatter and anchors:xs0 = min(a.x - a.w / 2 for a in anchors)xs1 = max(a.x + a.w / 2 for a in anchors)yc = max(a.y for a in anchors)xc, rx = (xs0 + xs1) / 2, min(W * .46, (xs1 - xs0) / 2 + W * .1)ry_f, ry_b = min(H * .97 - yc, H * .035), min(yc - y0 - H * .02, H * .08)n_ = len(scatter)for k, it in enumerate(scatter):# rule: most lie just behind / among the others, a third just in front (never a wall hiding the subject)a = math.pi * (k + .5) / n_ * 2 + it.rng.uniform(-.2, .2)front_ = k % 3 == 2yy = yc + (ry_f if front_ else -ry_b) * abs(math.sin(a)) * it.rng.uniform(.5, 1.0)yy = max(y0 + H * .02, min(H * .97, yy))it.d = focal * cam / max(.5, yy - y0)project(it, focal, cam, y0)it.x = max(it.w / 2, min(W - it.w / 2, xc + rx * math.cos(a) * it.rng.uniform(.75, 1.05)))trace.append("layout: %d small things scattered round the others" % n_)# rule: final size floor: every named ground thing is at least 12% of the frame tall (grown in place)for it in ground:if hasattr(it, "h") and it.h < H * .12 and not getattr(it, "stacked", False) and getattr(it, "worn_by", None) is None \and getattr(it, "held_by", None) is None and not it.implicit \and not ((it.attrs or {}).get("small_count") and it.h >= H * .045 and "smallcount" not in os.environ.get("PYDRAW_LANG_OFF", "")):# (language shift 3, knob smallfloor: counted small things grow to 4.5% only - marbles drew knee-high)fl = .045 if (it.attrs or {}).get("small_count") and "smallfloor" not in os.environ.get("PYDRAW_LANG_OFF", "") else .12k = H * fl / it.hit.h *= kit.w *= k# rule: something resting on a flying thing travels with it (drawn just above it)56 unmodified linesit.facing = "left" if it.rng.random() < .5 else "right"else:it.facing = "left" if it.x > W / 2 else "right"from .stage import post as _stage # night (scene): watcher in the foreground, opponents face, fed birds on the groundfrom .attach import layout_rule as _attachfor _f in (_stage, _attach):try:_f(insts, scene, W, H, y0, trace)except Exception as _ex: # a staging rule must never take the picture downtrace.append("layout: %s skipped (%s)" % (_f.__module__, str(_ex)[:80]))from .perch import layout_rule as _perch_perch(insts, W, H, trace)if _E.get("wornfix", "1") != "0":# (night characters 3, wornfix; critic C32): a wearer moved / rescaled after its worn things were anchored (a dog# put into the driver's seat of a car) takes them along - the sunglasses were left floating in the skyfor it in insts:wa = getattr(it, "_worn_at", None)if wa is None or it.bound is not wa[0]:continuew8, dx, dy, h0, ih0 = wak_ = w8.h / max(h0, 1e-6)if abs(w8.y - (it.y - dy * k_)) > .5 or abs(k_ - 1) > .01:it.x, it.y = w8.x + (dx if w8.facing == it.facing else -dx) * k_, w8.y + dy * k_oh_ = max(it.h, 1e-6)it.h = ih0 * k_it.w *= it.h / oh_it.facing = w8.facingtrace.append("layout: %s follows its wearer %s" % (it.concept, w8.concept))for it in insts:# (wornfix) a thing an animal holds in its mouth sits on the side it finally faces (the holding pass ran# before "bringing a stick to its owner" turned the dog to its owner: the stick was behind its tail)hb = it.bound if getattr(it, "held_by", None) is not None else Noneif hb is None or hb.concept == "person" or (getattr(hb, "attrs", None) or {}).get("anthro") or not hasattr(it, "x"):continueside = 1 if hb.facing != "left" else -1if (it.x - hb.x) * side < 0:it.x = hb.x + side * abs(it.x - hb.x)trace.append("layout: %s turned to the %s's front" % (it.concept, hb.concept))for it in insts:trace.append("layout: %r" % it)return insts, y0
46 unmodified lines4748495051525346 unmodified lines"bamboo": ("potted plant", "green"), "fan": ("clock", None), "diamond": ("star", "white"), "gem": ("star", "blue"),"jewel": ("star", "red"), "crystal": ("star", "white"), "suit": ("tie", "black"), "tuxedo": ("tie", "black"),"cards": ("book", "white"), "card": ("book", "white"), "brain": ("heart", "pink"), "cash": ("book", "green"),"money": ("book", "green"), "poster": ("book", None), "painting": None, "photo": None, "picture": None, "sun": None, "police car": ("police cruiser", None), "red panda": ("fox", "red"), "polar bear": ("bear", "white"),# vehicles"van": ("truck", "white"), "jeep": ("car", "green"), "suv": ("car", None), "limousine": ("car", "black"), "limo": ("car", "black"),"convertible": ("car", "red"), "sports car": ("car", "red"), "race car": ("car", "red"), "racecar": ("car", "red"),46 unmodified lines4748495051525346 unmodified lines"bamboo": ("potted plant", "green"), "fan": ("clock", None), "diamond": ("star", "white"), "gem": ("star", "blue"),"jewel": ("star", "red"), "crystal": ("star", "white"), "suit": ("tie", "black"), "tuxedo": ("tie", "black"),"cards": ("book", "white"), "card": ("book", "white"), "brain": ("heart", "pink"), "cash": ("book", "green"),"money": ("book", "green"), "poster": ("book", None), "painting": None, "photo": None, "picture": None, "sun": None, "police car": ("police cruiser", None), "red panda": ("fox", "red"), "polar bear": ("bear", "white"), "yeti": ("gorilla", "white"), "bigfoot": ("gorilla", "brown"), "sasquatch": ("gorilla", "brown"),# vehicles"van": ("truck", "white"), "jeep": ("car", "green"), "suv": ("car", None), "limousine": ("car", "black"), "limo": ("car", "black"),"convertible": ("car", "red"), "sports car": ("car", "red"), "race car": ("car", "red"), "racecar": ("car", "red"),
105 unmodified lines10610710810911011150 unmodified lines162163164165166167311 unmodified lines47948048148248348448548648748848949049149249349422 unmodified lines517518519520521522523524107 unmodified lines63263363463563663713 unmodified lines651652653654655656657658659660661662663664665666667668669670105 unmodified lines"dignified": dict(sym=.8, cam=("low", .4), con=.3, sat=-.1, warm=.15),"cinematic": dict(con=.45, sat=-.05, warm=.15, vig=.4, fog=.2, time={"sunset": .4}),"dystopian_mood": dict(warm=-.3, tint=(150, 170, 150), sat=-.45, con=.5, fog=.5, glow=-.5),}# head words -> profile (and strength). The literal word list a director would use for each profile.50 unmodified lines"dignified": "dignified humble","cinematic": "cinematic","dystopian_mood": "bleakest",}.items():for _w in _words.split():LEX[_w.replace("_", " ")] = (_prof, 1.0)311 unmodified linesreturn ex_time, ex_weather, ex_camdef apply(scene, text, trace, renderer="pixel"):"""decide the mood's scene-level choices (time, weather, camera, framing, supporting objects) before layout,and store the grade recipe in scene['mood'] for the renderers' finishing passes. Returns the recipe or None."""import osif os.environ.get("PYDRAW_MOOD", "1") == "0":return Nonem = compose_mood(text, renderer)if m is None:return Nonescene["mood"] = mtrace.append("mood: %s" % ", ".join("%s->%s%s" % (w, p, "" if how == "hand" else "(%s)" % how) for w, p, _, how in m["words"]))if scene.get("unknown"):mw = {w for w, _, _, _ in m["words"]}22 unmodified linesif not ex_weather and not indoor:scene["overcast"] = Truedid.append("overcast sky")elif m["weather"] and not ex_weather and not indoor and place not in ("space", "underwater", "sky") and not styled:scene["weather"] = m["weather"]did.append("weather=%s" % m["weather"])# rule: camera height - low angle for power, high angle for smallness; never against the prompt's own cameraif m["cam"] and not ex_cam:107 unmodified linesif scene.get("time") == "night":hz = tuple(c * .35 for c in hz)yh = y0 if y0 is not None else H * .5for y in range(H):row, idr = cv.px[y], cv.ids[y]fy = max(0.0, 1 - abs(y - yh) / (H * .45)) if fog else 0.0 # rule (pixel): mood fog thickens toward the horizon13 unmodified linesr, g, b = (.5 + (r - .5) * con), (.5 + (g - .5) * con), (.5 + (b - .5) * con)r, g, b = max(0, r) ** gam, max(0, g) ** gam, max(0, b) ** gamif fog:a = fog * fy * (.2 if obj else 1.0) # rule: subjects stand in front of the haze, the distance sinks into itr += (hz[0] / 255 - r) * ag += (hz[1] / 255 - g) * ab += (hz[2] / 255 - b) * ap[0], p[1], p[2] = min(255, r * 255), min(255, g * 255), min(255, b * 255)if m["vig"] > .05:# rule (pixel): a stepped vignette (3 flat rings) - smooth falloff would band into noise after the palette snapk = .32 * m["vig"]for y in range(H):row = cv.px[y]for x in range(W):d = ((x - W / 2) ** 2 + (y - H / 2) ** 2) / ((W / 2) ** 2 * 2)step = 0 if d < .38 else 1 if d < .6 else 2 if d < .8 else 3if step:f = 1 - k * step / 3p = row[x]p[0] *= f; p[1] *= f; p[2] *= f105 unmodified lines10610710810911011111211350 unmodified lines164165166167168169170311 unmodified lines48248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273322 unmodified lines756757758759760761762763764765107 unmodified lines87387487587687787887988088188288313 unmodified lines897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932105 unmodified lines"dignified": dict(sym=.8, cam=("low", .4), con=.3, sat=-.1, warm=.15),"cinematic": dict(con=.45, sat=-.05, warm=.15, vig=.4, fog=.2, time={"sunset": .4}),"dystopian_mood": dict(warm=-.3, tint=(150, 170, 150), sat=-.45, con=.5, fog=.5, glow=-.5),# rule (night pixel round 3): windy = crisp, a little brighter; it is drawn as gusts, never as rain"breezy": dict(con=.15, sat=.1, bright=.05),}# head words -> profile (and strength). The literal word list a director would use for each profile.50 unmodified lines"dignified": "dignified humble","cinematic": "cinematic","dystopian_mood": "bleakest","breezy": "windy breezy blustery gusty windswept",}.items():for _w in _words.split():LEX[_w.replace("_", " ")] = (_prof, 1.0)311 unmodified linesreturn ex_time, ex_weather, ex_camdef _night_hint(scene, text, trace):"""rule (night pixel round 3, knob moonnight=0): a moon or stars in the picture mean night, unless the promptnames its time ("an owl under a full moon" was drawn at noon with no moon)"""from .pixelcraft import onif not on("moonnight") or not on("atmos") or scene.get("time") == "night":returntoks = set(re.findall(r"[a-z]+", text.lower()))moon = any(e.get("concept") in ("full moon", "crescent moon", "moon") for e in scene.get("entities", ())) \or bool(toks & {"moonlight", "moonlit", "starlit", "starry", "moonrise"}) or "under the stars" in text.lower() \or (bool(toks & {"firefly", "fireflies"}) and on("fireflies")) # (night pixel2) fireflies glow at nightif not moon:returnfrom .understanding import SETTINGSif "time=" in " ".join(trace) or any(SETTINGS.get(t, (None,))[0] == "time" for t in toks - {"moon", "moonlight", "stars", "starry"}):returnscene["time"] = "night"trace.append("mood: a moon / stars in the prompt -> night")BARE_PLACE = {"autumn": "forest", "fall": "forest", "winter": "snow", "snow": "snow", "spring": "park", "summer": "beach","rain": "street", "rainy": "street", "night": "field", "fog": "forest", "mist": "field"}def _bare_season_hint(scene, text, trace):"""rule (night pixel2, bareseason): a prompt that is only a season / weather word ("autumn", "winter", "rain") withnothing to draw gets the setting that shows it best - autumn woods, a snowfield, a park in spring, a summer beach,a rainy street - instead of an empty generic meadow (critic3 round 17)"""from .pixelcraft import onif not on("bareseason") or not on("atmos") or scene.get("entities") or scene.get("place"):returntoks = [t for t in re.findall(r"[a-z]+", text.lower()) if t not in ("a", "an", "the", "in", "at", "of", "day", "time")]if len(toks) > 2:returnfor t in toks:if t in BARE_PLACE:scene["place"] = BARE_PLACE[t]if t in ("autumn", "fall") and not scene.get("season"):scene["season"] = "autumn"if t == "spring" and not scene.get("season"):scene["season"] = "spring"trace.append("mood: bare '%s' -> %s" % (t, scene["place"]))returndef _after_rain_hint(scene, text, trace):"""rule (night pixel2, afterrain): "after the rain / after the storm" is the clearing, not the rain - no fallingrain, a rainbow by day after a storm, and the ground wet with puddles holding the sky (atmos.after_rain)"""from .pixelcraft import onif not on("afterrain") or not on("atmos"):returnlow = text.lower()m = re.search(r"\bafter (the |a )?(rain|storm|rainstorm|thunderstorm|shower|downpour)\b", low)if not m:returnif scene.get("weather") == "rain":scene["weather"] = Nonescene["_after_rain"] = Trueif "storm" in m.group(2) and scene.get("time") in ("day", None, "sunset"):fs = scene.setdefault("features", [])if "rainbow" not in fs:fs.append("rainbow")trace.append("mood: after the rain -> clearing sky, wet ground, puddles")def _frozen_hint(scene, text, trace):"""rule (night pixel2, frozen): "a frozen lake / pond / river", "skating on a pond" = winter: the water is ice(atmos.ice_over) and the shore is snowy"""from .pixelcraft import onif not on("frozen") or not on("atmos"):returnlow = text.lower()if re.search(r"\b(frozen|icy|iced[- ]over|ice[- ]covered)\s+(lake|pond|river|sea|bay|harbou?r|canal|stream|waterfall)", low) \or re.search(r"\b(skating|skaters?|ice[- ]skat\w*)\b.*\b(lake|pond|river|canal)\b", low):scene["_frozen"] = Trueif not scene.get("season"):scene["season"] = "winter"trace.append("mood: frozen water -> ice, winter")BURN_PRE = {"burning", "flaming", "blazing", "smouldering", "smoldering"}def _burn_hint(scene, text, trace):"""rule (night pixel2, burning): "a burning castle" / "a house on fire" / "a barn in flames" = that thing burns(atmos.burning draws the flames on it); the separate campfire that "on fire" used to add is dropped"""from .pixelcraft import onif not on("burning") or not on("atmos"):returnw = re.findall(r"[a-z]+", text.lower())tg = set()stop = {"a", "an", "the", "is", "are", "and", "of", "with"}for i, t in enumerate(w):if t in BURN_PRE:for n in w[i + 1:i + 3]:if n in stop:breaktg |= {n, n[:-1] if n.endswith("s") else n}if (t in ("on", "in") and i + 1 < len(w) and w[i + 1] in ("fire", "flames", "flame")) or t == "ablaze":for n in w[max(0, i - 2):i]:if n not in stop:tg |= {n, n[:-1] if n.endswith("s") else n}if t in ("on", "in"):ents = scene.get("entities") or []keep = [e for e in ents if not ((e.get("word") or "") in ("fire", "flames", "flame") or(e.get("concept") in ("campfire", "fire") and (e.get("word") or "") in ("fire", "flames", "flame", "")))]if len(keep) < len(ents) and len(keep):scene["entities"][:] = keepif w and set(w) & {"erupting", "erupts", "eruption", "erupt", "erupted"}:scene["_erupt"] = True # (atmos.erupt draws the lava fountain + ash plume on the volcano)tg -= {"fire", "flames", "flame", "on", "in"}if tg:scene["_burning"] = tgtrace.append("mood: burning -> flames on %s" % ",".join(sorted(tg)))def _firefly_hint(scene, text, trace):"""rule (night pixel2, fireflies): fireflies are a swarm of tiny lights the pixel renderer draws over the scene(atmos.fireflies), not a big beetle object (they were drawn as two giant black beetles)"""from .pixelcraft import onif not on("fireflies") or not on("atmos"):returnents = scene.get("entities") or []keep = [e for e in ents if (e.get("word") or "").lower() not in ("firefly", "fireflies")]if len(keep) < len(ents) and keep is not None:scene["entities"][:] = keepscene["_fireflies"] = Truetrace.append("mood: fireflies -> a swarm of lights, not beetle objects")def _sunset_hint(scene, text, trace):"""rule (night pixel2, setsun): "the setting sun / the rising sun / a sunset glow" means a low sun: sunset timeunless the prompt names another time ("a couple against the setting sun" was drawn at noon)"""from .pixelcraft import onif not on("setsun") or not on("atmos") or scene.get("time") == "sunset":returnlow = text.lower()if not re.search(r"\b(setting|sinking|rising) sun\b", low):returntoks = set(re.findall(r"[a-z]+", low))from .understanding import SETTINGSif any(SETTINGS.get(t, (None,))[0] == "time" for t in toks - {"sun", "setting", "rising", "sinking"}):returnscene["time"] = "sunset"if "rising sun" in low:scene["_dawn"] = Truetrace.append("mood: a setting / rising sun -> low sun")CANDLE_WORDS = {"candlelight", "candlelit", "lamplight", "lamplit"}def _candle_hint(scene, text, trace):"""rule (night pixel2, candlelit): "by candlelight / candlelit / lamplight" is a dark interior lit by a warm flame:night unless the prompt names its time, a room when it names no place, and a candle on hand if no light sourceis named (critic P13: "a wizard reading a giant spellbook by candlelight" was a bright street at noon)"""from .pixelcraft import onif not on("candlelit") or not on("atmos"):returnlow = text.lower()toks = set(re.findall(r"[a-z]+", low))if not (toks & CANDLE_WORDS or "candle light" in low or "lamp light" in low):returnfrom .understanding import SETTINGSif not any(SETTINGS.get(t, (None,))[0] == "time" for t in toks - {"candlelight", "candlelit"}):scene["time"] = "night"if not scene.get("place"):scene["place"] = "room"if not any(e.get("concept") in ("candle", "lantern", "lamp", "torch", "campfire", "fireplace", "oil lamp")for e in scene.get("entities") or ()):scene["_candle"] = True # pixel: atmos.candle_room draws a small candle by the subject and its lighttrace.append("mood: candlelight -> lamp-lit interior at night")def _sky_show(scene, text):"""rule (night pixel round 3, skyshow=0 off): a prompt that names something to see in the sky (northern lights,stars, a rainbow, fireworks) never gets a mood's fog / rain / snow vote that would hide it"""from .pixelcraft import onif not on("skyshow") or not on("atmos"):return Falsetoks = set(re.findall(r"[a-z]+", text.lower()))return bool(set(scene.get("features") or ()) & {"aurora", "rainbow", "fireworks", "meteor"}) \or bool(toks & {"starry", "stars", "aurora", "milky", "constellation", "constellations", "starlit"})def _fog_hint(scene, text, trace, renderer):"""rule (night pixel round 3, knob mistfog=0): "misty / foggy" outdoors is fog weather in pixel art (the parserkept it only as a mood word, so the haze was a per-row band that posterised into stripes)"""from .pixelcraft import onif renderer != "pixel" or not on("mistfog") or not on("atmos") or scene.get("weather") or scene.get("place") in INDOOR | {"space", "underwater"}:returntoks = set(re.findall(r"[a-z]+", text.lower()))if toks & {"misty", "foggy", "fog", "mist", "fogbound", "hazy"}:scene["weather"] = "fog"if not toks & {"foggy", "fog", "fogbound"}:scene["weather_src"] = "mist" # rule: mist / haze is a lighter fog than "foggy" (atmos.fog2)trace.append("mood: misty / foggy -> fog weather")def _season_hint(scene, text, trace):"""rule (night pixel round 3, leafseason=0): fallen / autumn leaves, fall foliage, pumpkins in a field = autumn"""from .pixelcraft import onif not on("leafseason") or not on("atmos") or scene.get("season"):returnt = text.lower()if re.search(r"(fallen|autumn|fall|falling|dry|dead|red|orange|golden) leaves|fall foliage|autumn foliage|pumpkin patch", t):scene["season"] = "autumn"trace.append("mood: fallen leaves -> autumn")def apply(scene, text, trace, renderer="pixel"):"""decide the mood's scene-level choices (time, weather, camera, framing, supporting objects) before layout,and store the grade recipe in scene['mood'] for the renderers' finishing passes. Returns the recipe or None."""import os_night_hint(scene, text, trace)_sunset_hint(scene, text, trace)_candle_hint(scene, text, trace)_firefly_hint(scene, text, trace)_burn_hint(scene, text, trace)_frozen_hint(scene, text, trace)_after_rain_hint(scene, text, trace)_bare_season_hint(scene, text, trace)if re.search(r"\b(spray[- ]?paint\w*|tags|tagged|graffit\w*|street art|murals?)\b", text.lower()):from .pixelcraft import on as _on2for e in scene.get("entities") or ():if e.get("concept") == "wall" and "graffiti" not in (e.get("word") or "") and _on2("graffiti2"):e["word"] = "graffiti " + (e.get("word") or "wall") # (night pixel2) the wall carries the tagstrace.append("mood: spray paint / tags -> graffiti on the wall")_fog_hint(scene, text, trace, renderer)_season_hint(scene, text, trace)if renderer == "pixel" and (scene.get("vary") or {}).get("mood", "neutral") in ("warm", "neutral"):from .pixelcraft import on as _onfrom .atmos import snowy as _snowyif _on("atmos") and _on("snowcool") and _snowy(scene) and scene.get("time") == "day":scene.setdefault("vary", {})["mood"] = "cool" # rule: the warm day grade turns snow into sand; snow days grade cooltrace.append("mood: snowy day -> cool grade (not warm)")if os.environ.get("PYDRAW_MOOD", "1") == "0":return Nonem = compose_mood(text, renderer)if m is None:return Nonescene["mood"] = mif renderer == "pixel" and m.get("warm", 0) > 0:from .pixelcraft import on as _onfrom .atmos import snowy as _snowyif _on("atmos") and _on("snowcool") and _snowy(scene) and scene.get("time") == "day":m["warm"] = 0.0 # rule: a warm mood grade on a snow day turns the snow to sand: keep it neutraltrace.append("mood: %s" % ", ".join("%s->%s%s" % (w, p, "" if how == "hand" else "(%s)" % how) for w, p, _, how in m["words"]))if scene.get("unknown"):mw = {w for w, _, _, _ in m["words"]}22 unmodified linesif not ex_weather and not indoor:scene["overcast"] = Truedid.append("overcast sky")elif m["weather"] and not ex_weather and not indoor and place not in ("space", "underwater", "sky") and not styled \and not _sky_show(scene, text):scene["weather"] = m["weather"]scene["weather_src"] = "mood" # read by atmos.fog2: a mood's fog is a light haze, not a fog bankdid.append("weather=%s" % m["weather"])# rule: camera height - low angle for power, high angle for smallness; never against the prompt's own cameraif m["cam"] and not ex_cam:107 unmodified linesif scene.get("time") == "night":hz = tuple(c * .35 for c in hz)yh = y0 if y0 is not None else H * .5from .pixelcraft import on as _onfloor = scene.get("time") == "night" and br < 0 and _on("nightfloor") and _on("atmos")near = getattr(cv, "near_bg", None) # near scenery (framing pines) stays out of the haze like a subjectif near is not None:near = near.tolist()for y in range(H):row, idr = cv.px[y], cv.ids[y]fy = max(0.0, 1 - abs(y - yh) / (H * .45)) if fog else 0.0 # rule (pixel): mood fog thickens toward the horizon13 unmodified linesr, g, b = (.5 + (r - .5) * con), (.5 + (g - .5) * con), (.5 + (b - .5) * con)r, g, b = max(0, r) ** gam, max(0, g) ** gam, max(0, b) ** gamif fog:a = fog * fy * (.2 if obj or (near is not None and near[y][x]) else 1.0) # rule: subjects stand in front of the haze, the distance sinks into itr += (hz[0] / 255 - r) * ag += (hz[1] / 255 - g) * ab += (hz[2] / 255 - b) * aif floor and not obj and not (near is not None and near[y][x]):l3 = .3 * r + .59 * g + .11 * bif l3 < .14: # rule (night pixel round 3, nightfloor): a dark night keeps a navy floor in the skyf_ = .7 * (1 - l3 / .14) # and ground, so near silhouettes (framing pines) still read against itr += (.075 - r) * f_; g += (.085 - g) * f_; b += (.16 - b) * f_p[0], p[1], p[2] = min(255, r * 255), min(255, g * 255), min(255, b * 255)if m["vig"] > .05:# rule (pixel): a stepped vignette (3 flat rings) - smooth falloff would band into noise after the palette snapk = .32 * m["vig"]from .pixelcraft import on as _onif scene.get("time") == "night" and _on("nightvig"):k *= .45 # rule (night pixel round 3): night is already dark at the edges; a full vignette crushed the# frame to black with a hard stepped rectangle in the middle# rule (night pixel2, vigroom): in a room the rings fall on a flat painted wall and read as a big bright dome# over the window ("a cozy kitchen in the morning"): pixel rooms get no vignette (the light is in the room)from .scenes import INDOOR as _INif scene.get("place") in _IN and _on("vigroom"):k = 0.0e0, e1, e2 = .38, .6, .8cv.vig_params = (k, e0, e1, e2) # night pixel2: atmos.sky_ramp re-applies the same rings to its sky bandsfor y in range(H):row = cv.px[y]for x in range(W):d = ((x - W / 2) ** 2 + (y - H / 2) ** 2) / ((W / 2) ** 2 * 2)step = 0 if d < e0 else 1 if d < e1 else 2 if d < e2 else 3if step and k:f = 1 - k * step / 3p = row[x]p[0] *= f; p[1] *= f; p[2] *= f
137 unmodified lines13813914014114214312 unmodified lines156157158159160161137 unmodified lines_CACHE[key] = Noneif not re.fullmatch(r"[a-z][a-z \-]{2,}", word) or word in STOP or word.split(" ")[-1] in STOP:return Nonewn = _wn()if wn is None:return None12 unmodified linesreturn resreturn Nonelemma = lemma.replace("_", " ")plural = lemma != word# rule: only words that are mostly nouns open a new concept ("has" -> have, "running", "red", "light" do not)n_ = _counts(wn, lemma.replace(" ", "_"))["n"]137 unmodified lines13813914014114214314414512 unmodified lines158159160161162163164165137 unmodified lines_CACHE[key] = Noneif not re.fullmatch(r"[a-z][a-z \-]{2,}", word) or word in STOP or word.split(" ")[-1] in STOP:return Noneif word.endswith("s") and word[:-1] in STOP and __import__("os").environ.get("PYDRAW_LANG_OFF", "").find("stopplural") < 0:return None # rule (language shift 2): "wooden floors" / "walls" are framing words too, plural or notwn = _wn()if wn is None:return None12 unmodified linesreturn resreturn Nonelemma = lemma.replace("_", " ")if lemma == word and word.endswith("s") and (TAXA.get(word[:-1]) or {}).get("synset"):lemma = word[:-1] # rule (shift 3): "marbles" is also the game; a word whose singular is pinned is its pluralplural = lemma != word# rule: only words that are mostly nouns open a new concept ("has" -> have, "running", "red", "light" do not)n_ = _counts(wn, lemma.replace(" ", "_"))["n"]
12 unmodified lines1314151617181912 unmodified linesreturnfor it in insts:b = getattr(it, "bound", None)if it.rel != "on" or b is None or b.concept not in PERCHES or not it.info.get("animal") or not hasattr(it, "x"):continueside = -1 if it.x <= W / 2 else 1 # limb comes in from this edgeb.perch = True12 unmodified lines13141516171819202112 unmodified linesreturnfor it in insts:b = getattr(it, "bound", None)if it.rel != "on" or b is None or (b.concept not in PERCHES and (getattr(b, "word", "") or "").split()[-1:] != ["branch"]) \or not (it.info.get("animal") or it.info.get("height", 9) <= 1.5) or not hasattr(it, "x") \or getattr(it, "attach_kind", None): # (night: hanging animals are placed by pydraw/attach.py)continueside = -1 if it.x <= W / 2 else 1 # limb comes in from this edgeb.perch = True
101 unmodified lines102103104105106107108109110111112101 unmodified lineson_top=b.get("on_top", 1.0), default_color=default_color, natural_colors={},flying=False, shadow=True, plurals={}, sim=spec)CONCEPTS[name].update(over)MODELS[name] = (model_fn, aspect)trace.append("physics: %s -> simulated %s (%.2f m tall, aspect %.2f)" % (base, kind, P["height"], aspect))return name# ------------------------------------------------------------------ handlersdef h_pile(scene, toks, text, trace):for i, e in enumerate(scene["entities"]):101 unmodified lines102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173101 unmodified lineson_top=b.get("on_top", 1.0), default_color=default_color, natural_colors={},flying=False, shadow=True, plurals={}, sim=spec)CONCEPTS[name].update(over)CONCEPTS[name]["label"] = label(spec) # night (scene): readable name for summaries ("ivy-covered wall")MODELS[name] = (model_fn, aspect)trace.append("physics: %s -> simulated %s (%.2f m tall, aspect %.2f)" % (base, kind, P["height"], aspect))return namedef _pl(w, n=2):"""plural of a concept name (concept facts first: CONCEPTS[...]['plurals'] = irregular singular -> plural)"""if n == 1 or not w:return wpl = (CONCEPTS.get(w, {}).get("plurals") or {}).get(w)if pl:return plif w.endswith(("s", "sh", "ch", "x")):return w + "es"if w.endswith("y") and w[-2:-1] not in "aeiou":return w[:-1] + "ies"return w + "s"def label(spec):"""rule: a simulated composite's readable name, from its kind + the parameters that matter to a reader(the concept key "sim cover=0.95:host=wall:kind=ivy:..." stays the internal id)"""k = spec.get("kind")host = str(spec.get("host") or "").replace("_", " ")if k == "pile":item = spec.get("item", "thing")return "%s of %s" % ("stack" if spec.get("mode") == "stack" else "pile", _pl(item, spec.get("n", 2)))if k == "spill":return "%s spilling out of a %s" % (_pl(spec.get("item", "thing")), spec.get("container", "container"))if k == "drape":return "%s draped over a %s" % (spec.get("cloth", "cloth"), host or "thing")if k == "flag":return "flag waving in the wind"if k == "frost":return "frosted %s" % (host or "window")if k == "ivy":return "ivy-covered %s" % (host or "wall")if k == "web":return "spider web" + (" with a spider" if spec.get("spider") else "")if k == "melt":return "melting candle"if k == "rods":return "plate of spaghetti" + (" with sauce" if spec.get("sauce") else "")if k == "crumple":return "crumpled paper"if k == "reef":return "coral reef"if k == "pour":return "%s pouring" % (host or "liquid")if k == "splash":return "splash"if k == "fx":fx = spec.get("fx") or "smoke"if not host:return str(fx)return "steaming %s" % host if fx == "steam" else "%s with rising %s" % (host, fx)return str(k or "simulated thing")def display_name(concept):"""the name a person should read for a concept (simulated composites have an internal key)"""c = CONCEPTS.get(concept) or {}return c.get("label") or concept# ------------------------------------------------------------------ handlersdef h_pile(scene, toks, text, trace):for i, e in enumerate(scene["entities"]):
205 unmodified lines20620720820921021121267 unmodified lines28028128228328428528628728819 unmodified lines308309310311312313314315316317318319205 unmodified linesif not any(t in ("splash", "splashing", "splashes", "raindrop") for t in toks):returni, e = _find(scene, toks, concepts={"puddle", "pond"}, words={"puddle"})if e is None:returnname = composite("splash", dict(seed=0), e["concept"], trace, setting="street")if name:67 unmodified lines# ------------------------------------------------------------------ pixel-renderer effectsdef draw_puffs(cv, ctx, inst, res):"""smoke / steam particles above a pixel-art host: translucent soft discs, lit from above"""X, r, op, col = res["X"], res["r"], res["op"], res["col"]f = -1 if getattr(inst, "facing", None) == "left" else 1cid = cv.cur_idcv.cur_id = None19 unmodified linesox = rng.uniform(.3, .7) * W - 45 * sxP = [(c[1] * sx + ox, c[0] * sx) for c in cells]ms = set(main)for i, p in enumerate(parent):if p >= 0 and i in ms:cv.capsule(P[p][0], P[p][1], P[i][0], P[i][1], 2.2 * u, (170, 180, 255), alpha=.35)for i, p in enumerate(parent):if p >= 0:cv.capsule(P[p][0], P[p][1], P[i][0], P[i][1], (.7 if i in ms else .3) * u, (255, 255, 235) if i in ms else (215, 220, 255))def ground_fx(cv, ctx, scene, trace):205 unmodified lines20620720820921021121267 unmodified lines28028128228328428528628728828929029129229329429529629729829930019 unmodified lines320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352205 unmodified linesif not any(t in ("splash", "splashing", "splashes", "raindrop") for t in toks):returni, e = _find(scene, toks, concepts={"puddle", "pond"}, words={"puddle"})if e is None or (e.get("attrs") or {}).get("stood_in"): # night characters 2: someone splashing IN the puddlereturnname = composite("splash", dict(seed=0), e["concept"], trace, setting="street")if name:67 unmodified lines# ------------------------------------------------------------------ pixel-renderer effectsCHIMNEY_HOSTS = {"house", "cabin", "cottage", "log cabin", "farmhouse", "barn", "hut", "chalet", "lodge", "factory", "bakery","campfire", "bonfire", "fire", "fire pit", "fireplace", "candle", "torch"}def draw_puffs(cv, ctx, inst, res):"""smoke / steam particles above a pixel-art host: translucent soft discs, lit from above"""X, r, op, col = res["X"], res["r"], res["op"], res["col"]import re as _refrom pydraw.atmos import on as _aonhm = _re.search(r"host=([a-z ]+?)(:|$)", str(getattr(inst, "concept", "")))if getattr(cv, "ss", 2) == 1 and _aon("chimney") and hm and "smoke" in str(inst.concept) and hm.group(1) in CHIMNEY_HOSTS:# rule (night pixel2, chimney): smoke "from the chimney" rises from the host's chimney (atmos.chimney_smoke);# the free-standing puff cloud laid out beside the house read as a grey blob in the skycv.chimney_hosts = set(getattr(cv, "chimney_hosts", set())) | {hm.group(1)}returnf = -1 if getattr(inst, "facing", None) == "left" else 1cid = cv.cur_idcv.cur_id = None19 unmodified linesox = rng.uniform(.3, .7) * W - 45 * sxP = [(c[1] * sx + ox, c[0] * sx) for c in cells]ms = set(main)from pydraw.atmos import on as _aon# rule (night pixel round 3, bolt2): on a grey day-storm sky the wide glow read as a smoke worm: thin itday = scene.get("time") == "day" and getattr(cv, "ss", 2) == 1 and _aon("bolt2")for i, p in enumerate(parent):if p >= 0 and i in ms and not day:cv.capsule(P[p][0], P[p][1], P[i][0], P[i][1], 2.2 * u, (170, 180, 255), alpha=.35)br = day and _aon("bolt3")for i, p in enumerate(parent):if p >= 0 and not br: # (bolt3: by day the whole bolt is stamped after the finish, below)cv.capsule(P[p][0], P[p][1], P[i][0], P[i][1], (.7 if i in ms else .3) * u, ((235, 242, 255) if day else (255, 255, 235)) if i in ms else (215, 220, 255))if day:# the pixel palette had no near-white for a few bolt pixels on a grey storm sky (it came out yellow-green):# the main channel is stamped back after the pixel finish, like writing (typography.restamp)st = getattr(cv, "text_stamps", None)if st is None:st = cv.text_stamps = []# rule (night pixel2, bolt3): the thin side branches snapped to pale yellow too - stamp them a cooler, dimmer# blue-white so the bolt stays one electric colour (main channel brightest)for i, p in enumerate(parent):if p >= 0 and (i in ms or br):(ax, ay), (bx, by) = P[p], P[i]n = int(max(abs(bx - ax), abs(by - ay))) + 1for k in range(n + 1):x, y = int(ax + (bx - ax) * k / n), int(ay + (by - ay) * k / n)for xx in ((x, x + 1) if br and i in ms else (x,)): # the main channel 2 px wideif 0 <= xx < cv.w and 0 <= y < cv.h and not cv.ids[y][xx]:st.append((xx, y, (240, 246, 255) if i in ms else (196, 206, 238), 0))def ground_fx(cv, ctx, scene, trace):
147 unmodified lines1481491501511521531 unmodified line15515615715815916054 unmodified lines21521621721821922045 unmodified lines266267268269270271147 unmodified linesdef finish(cv, outline_ids, trace, dither=6.0):W, H = cv.w, cv.hif LOOK == "clean":import numpy as npif _EXP.get("craft", "1") != "0":1 unmodified linecv.px = _pc.form_shadow(np.asarray(cv.px, float), np.asarray(cv.ids), getattr(cv, "light_dx", 0), trace,only=getattr(cv, "organic_ids", None)).tolist()cv.px = [[list(p) for p in row] for row in _celband(cv.px, cv.ids, trace, organic=getattr(cv, "organic_ids", None))]dither = float(_EXP.get("cdither", 0.0)) # rule: no screen-door dither; gradients become clean bandscraft = LOOK == "clean" and _EXP.get("craft", "1") != "0"if craft:54 unmodified linesk = float(_EXP.get("rimpx", "1"))sx = 1 if getattr(cv, "light_dx", 0) >= 0 else -1key = (255, 240, 215) if getattr(cv, "time", "day") != "night" else (190, 205, 255)oset = set(out)hits = []for x, y in out:45 unmodified linesA2, naa = pc.hand_aa(A, I, O, trace)if naa:A = pc.snap_to(A2, (A2 != A).any(-1), pal)for y in range(H):for x in range(W):px[y][x][0], px[y][x][1], px[y][x][2] = A[y, x]147 unmodified lines1481491501511521531541551561 unmodified line15815916016116216316416516654 unmodified lines22122222322422522622722822945 unmodified lines275276277278279280281282283284285286287147 unmodified linesdef finish(cv, outline_ids, trace, dither=6.0):W, H = cv.w, cv.hif getattr(cv, "sky_mask", None) is not None:from .atmos import sky_ramp_presky_ramp_pre(cv) # night pixel2 (skyramp): the graded sky colours before the palette snapif LOOK == "clean":import numpy as npif _EXP.get("craft", "1") != "0":1 unmodified linecv.px = _pc.form_shadow(np.asarray(cv.px, float), np.asarray(cv.ids), getattr(cv, "light_dx", 0), trace,only=getattr(cv, "organic_ids", None)).tolist()cv.px = [[list(p) for p in row] for row in _celband(cv.px, cv.ids, trace, organic=getattr(cv, "organic_ids", None))]if getattr(cv, "moonlit_skip", None) is not None:from .atmos import moonlit_latemoonlit_late(cv, trace) # night pixel round 3: objects cooled to moonlight, band by banddither = float(_EXP.get("cdither", 0.0)) # rule: no screen-door dither; gradients become clean bandscraft = LOOK == "clean" and _EXP.get("craft", "1") != "0"if craft:54 unmodified linesk = float(_EXP.get("rimpx", "1"))sx = 1 if getattr(cv, "light_dx", 0) >= 0 else -1key = (255, 240, 215) if getattr(cv, "time", "day") != "night" else (190, 205, 255)if getattr(cv, "time", "day") == "sunset" and _EXP.get("goldrim", "1") != "0" and _EXP.get("atmos", "1") != "0":# rule (night pixel round 3): golden hour = a strong warm rim on the sun side of everythingkey, k = (255, 186, 112), k * 1.8oset = set(out)hits = []for x, y in out:45 unmodified linesA2, naa = pc.hand_aa(A, I, O, trace)if naa:A = pc.snap_to(A2, (A2 != A).any(-1), pal)if getattr(cv, "sky_y0", None) is not None and _EXP.get("skydither", "1") != "0" and _EXP.get("atmos", "1") != "0" and craft:from .atmos import sky_dither, sky_rampA = sky_ramp(A, cv, trace)A = sky_dither(A, np.asarray(ids, np.int64), cv.sky_y0, trace)if getattr(cv, "retro", None):from .retro import snap as _retro_snapA = _retro_snap(A, cv.retro, trace) # night pixel round 3: console palettes (game boy, pico-8, nes...)for y in range(H):for x in range(W):px[y][x][0], px[y][x][1], px[y][x][2] = A[y, x]
57 unmodified lines58596061626332 unmodified lines9697989910010157 unmodified linesdef grass(cv, ctx, scene, rng, trace, density=1.0):"""rule (tuft): drawn grass tufts in patches over a clean banded ground."""from .shading import fbmW, H, y0 = cv.w, cv.h, ctx.y0u = H / 128.032 unmodified linesdef flowers(cv, ctx, scene, rng, trace, pal, count, y_from=.3):"""rule (bloom): a flower is a little cluster - a plus of petals with a yellow eye near, two pixels far."""W, H, y0 = cv.w, cv.h, ctx.y0L = ctx.Ln = 057 unmodified lines58596061626364656632 unmodified lines9910010110210310410510610757 unmodified linesdef grass(cv, ctx, scene, rng, trace, density=1.0):"""rule (tuft): drawn grass tufts in patches over a clean banded ground."""from .atmos import snowy, on as _aonif _aon("snowground") and snowy(scene):return # rule (night pixel round 3): snow covers the grassfrom .shading import fbmW, H, y0 = cv.w, cv.h, ctx.y0u = H / 128.032 unmodified linesdef flowers(cv, ctx, scene, rng, trace, pal, count, y_from=.3):"""rule (bloom): a flower is a little cluster - a plus of petals with a yellow eye near, two pixels far."""from .atmos import snowy, on as _aonif _aon("snowground") and snowy(scene) and scene.get("place") not in ("snow",):returnW, H, y0 = cv.w, cv.h, ctx.y0L = ctx.Ln = 0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Retro console palettes for the pixel renderer (night pixel round 3, knob retro=0 off; atmos=0 / craft=0 too).
"game boy", "pico-8", "nes / 8-bit / nintendo", "c64 / commodore", "cga" in the prompt: the finished picture isre-snapped into that machine's fixed, published colour list (no model). Game Boy maps by brightness onto its 4greens; the others by nearest colour (red-mean weighted); CGA gets a 2x2 ordered dither so 4 colours still show agradient."""import reimport numpy as np
RETRO = { "gameboy": [(15, 56, 15), (48, 98, 48), (139, 172, 15), (155, 188, 15)], "pico8": [(0, 0, 0), (29, 43, 83), (126, 37, 83), (0, 135, 81), (171, 82, 54), (95, 87, 79), (194, 195, 199), (255, 241, 232), (255, 0, 77), (255, 163, 0), (255, 236, 39), (0, 228, 54), (41, 173, 255), (131, 118, 156), (255, 119, 168), (255, 204, 170)], "c64": [(0, 0, 0), (255, 255, 255), (136, 57, 50), (103, 182, 189), (139, 63, 150), (85, 160, 73), (64, 49, 141), (191, 206, 114), (139, 84, 41), (87, 66, 0), (184, 105, 98), (80, 80, 80), (120, 120, 120), (148, 224, 137), (120, 105, 196), (159, 159, 159)], "nes": [(0, 0, 0), (124, 124, 124), (188, 188, 188), (252, 252, 252), (0, 0, 252), (0, 88, 248), (60, 188, 252), (164, 228, 252), (104, 68, 252), (152, 120, 248), (216, 0, 204), (248, 120, 248), (168, 0, 32), (248, 56, 0), (248, 120, 88), (228, 92, 16), (252, 160, 68), (172, 124, 0), (248, 184, 0), (252, 224, 168), (0, 120, 0), (0, 184, 0), (88, 216, 84), (184, 248, 24), (0, 88, 0), (0, 168, 68), (0, 136, 136), (0, 232, 216), (80, 48, 0), (136, 20, 0)], "cga": [(0, 0, 0), (85, 255, 255), (255, 85, 255), (255, 255, 255)],}
def key(scene): from .atmos import on if not on("retro"): return None t = (scene.get("text") or "").lower() if re.search(r"game ?boy", t): return "gameboy" if re.search(r"pico[- ]?8", t): return "pico8" if re.search(r"\bc64\b|commodore", t): return "c64" if re.search(r"\bcga\b", t): return "cga" if re.search(r"\bnes\b|\b8[- ]?bit\b|nintendo", t): return "nes" return None
def snap(A, k, trace): pal = np.array(RETRO[k], float) H, W, _ = A.shape if k == "gameboy": l = A @ np.array([.3, .59, .11]) lo, hi = np.percentile(l, 3), np.percentile(l, 97) q = np.clip((l - lo) / max(1.0, hi - lo) * 4, 0, 3.999).astype(int) out = pal[q] else: X = A.reshape(-1, 3) # console palettes are saturated: boost saturation first, or every muted green / brown snaps to grey l = (X @ np.array([.3, .59, .11]))[:, None] X = np.clip(l + (X - l) * 1.7, 0, 255) if k == "cga": B = np.array([[0, 2], [3, 1]], float) / 4 - .375 X = X + np.tile(B, (H // 2 + 1, W // 2 + 1))[:H, :W].reshape(-1, 1) * 70 else: # a light 4x4 ordered dither: a gradient between two palette colours becomes a pattern instead of one # hard diagonal edge (critic: pico-8 forests turned into big green slashes) B4 = np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]], float) / 16 - .47 X = X + np.tile(B4, (H // 4 + 1, W // 4 + 1))[:H, :W].reshape(-1, 1) * 26 rm = (X[:, None, 0] + pal[None, :, 0]) / 2 d = pal[None] - X[:, None] dist = (2 + rm / 256) * d[..., 0] ** 2 + 4 * d[..., 1] ** 2 + (2 + (255 - rm) / 256) * d[..., 2] ** 2 out = pal[dist.argmin(1)].reshape(H, W, 3) trace.append("retro: %s palette (%d colours)" % (k, len(pal))) return out9 unmodified lines1011121314151617181920212223242526274 unmodified lines32333435363738394019 unmodified lines6061626364656643 unmodified lines1101111121131141151161176 unmodified lines12412512612712812913013113213313413513613713815 unmodified lines15415515615715815959 unmodified lines21922022122222322422522622722822923023123223323412 unmodified lines2472482492502512522532542558 unmodified lines2642652662672682692702713 unmodified lines2752762772782792802813 unmodified lines2852862872882892902912922932942952962972982993003013023033043051 unmodified line30730830931031131231331431531631731831941 unmodified lines36136236336436536657 unmodified lines424425426427428429430431432433434435436437132 unmodified lines57057157257357457557657757816 unmodified lines5955965975985996009 unmodified lines6106116126136146156166176186192 unmodified lines62262362462562662762862963063163263363425 unmodified lines66066166266366466519 unmodified lines685686687688689690691692300 unmodified lines993994995996997998102 unmodified lines110111021103110411051106110711081109111042 unmodified lines1153115411551156115711581159139 unmodified lines1299130013011302130313041305449 unmodified lines1755175617571758175917601761553 unmodified lines23152316231723182319232023215 unmodified lines232723282329233023312332233322 unmodified lines23562357235823592360236118 unmodified lines238023812382238323842385238623872388238923902391239223932394239523963 unmodified lines24002401240224039 unmodified linesINDOOR = {"studio", "table", "room", "kitchen", "bathroom", "bedroom", "office"}def sky_colors(scene):t, p, w = scene["time"], scene["place"], scene.get("weather")if p == "volcanic": # rule: volcanic skies are ash-laden: smoky orange by day, blood red at sunset, ember-lit at nightreturn {"day": ((120, 108, 108), (222, 164, 112)), "sunset": ((60, 30, 52), (232, 96, 52)), "night": ((14, 8, 18), (92, 34, 26))}[t]if t == "night":return (12, 16, 46), (46, 58, 108)if t == "sunset":return (58, 56, 130), (255, 178, 104)if p == "swamp": # rule: swamp air is humid: a hazy grey-green skyreturn (118, 140, 140), (198, 208, 188)if p == "arctic": # rule: polar sky is crisp and pale, bluer than overcast "snow"return (84, 146, 214), (216, 234, 246)if p == "snow" or w in ("rain", "fog"):return (140, 152, 172), (205, 212, 222)if p == "desert":4 unmodified linesdef sky_at(scene, y, y0):"""Sky colour at row y (shared by draw_sky, windows and cloud edge tests)."""top, hor = sky_colors(scene)if scene["time"] == "sunset":# rule: sunset sky = indigo -> rose -> amber, three stopsmid = (232, 120, 120)k = y / (y0 * .62)return mix(top, mid, k) if k < 1 else mix(mid, hor, (y - y0 * .62) / (y0 * .38))if scene["time"] == "night":19 unmodified linesdef cloud_palette(scene):"""rule: clouds are three flat tones (light rim, body, shadowed belly) tinted by the time of day."""t, w = scene["time"], scene.get("weather")if w == "rain" or (scene["place"] == "snow" and t == "day") or w == "fog":return (205, 208, 216), (178, 183, 196), (140, 146, 162)if t == "sunset":return (255, 222, 170), (246, 170, 150), (170, 110, 145)43 unmodified linessx, sy = ctx.sunu = H / 128.0night = scene["time"] == "night"overcast = scene["place"] == "snow" or scene.get("weather") in ("rain", "fog")if night:# rule: night stars = many faint 1px dots + a few bright 4-point twinklers, thinning toward the horizonfor _ in range(int(W * y0 / (160 * u * u))):x, y = rng.uniform(0, W), y0 * rng.random() ** 1.6 * .856 unmodified linescv.rows(y0 - H * .06, y0 + 2, lambda x, y: mix(sky_at(scene, y, y0), (90, 96, 150), .25 * (1 - (y0 - y) / (H * .06))))if not any(e["concept"] in ("full moon", "crescent moon", "planet") for e in scene.get("entities", [])):# rule: the sky's own moon is skipped when the prompt names a moon (no double moons)for r, a in ((.11, .06), (.08, .1)):cv.ellipse(sx, sy, H * r, H * r, (225, 232, 255), alpha=a)lit_ellipse(cv, ctx.L, sx, sy, H * .045, H * .045, (248, 246, 228))cv.ellipse(sx + H * .022, sy - H * .012, H * .04, H * .04, sky_at(scene, sy, y0))trace.append("scene: night sky -> stars + crescent moon")elif not overcast:sun_c = (255, 246, 205) if scene["time"] == "day" else (255, 214, 140)# rule: the sun's glow is several faint rings, not one hard halofor r, a in ((.2, .05), (.15, .07), (.11, .1), (.085, .14)):cv.ellipse(sx, sy, H * r, H * r, sun_c, alpha=a)cv.ellipse(sx, sy, H * .065, H * .065, sun_c)if scene["time"] == "sunset":15 unmodified linesn_cl = 4if scene.get("weather") in ("rain",):n_cl = 6placed = []for _ in range(n_cl):for _try in range(8):59 unmodified linesdraw_sky(cv, ctx, scene, rng, trace)W, H, y0 = cv.w, cv.h, ctx.y0autumn = scene.get("season") == "autumn"g = (150, 140, 70) if autumn else (95, 150, 80)# rule: three hill layers, bluer and paler with distance (atmospheric perspective)hills(cv, ctx, rng, mix(g, (70, 110, 150), .3), layers=((-.08, .05, .42),))treeline(cv, ctx, rng, (160, 110, 50) if autumn else (45, 95, 60), y0 - H * .045, H * .03, .3)hills(cv, ctx, rng, g, layers=((-.022, .022, .2), (-.006, .016, .06)))ground_plane(cv, ctx, (60, 112, 46) if not autumn else (120, 110, 50), (125, 180, 84) if not autumn else (175, 160, 80), grain=.25)trace.append("scene: field -> sky, layered hills, distant woods, grass")def mountains(cv, ctx, scene, rng, trace):draw_sky(cv, ctx, scene, rng, trace)W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.Lsd = 1 if ctx.sun[0] < W / 2 else -1 # shadow side (+1 = right faces are in shade)12 unmodified linespts.append(v)pts.append(peaks[-1])rock = L.ground(mix((105, 100, 125), ctx.haze_color, hz))cv.poly(pts + [(W * 1.1, y0 + 2), (-W * .1, y0 + 2)], rock)# rule: every peak has a lit face and a shaded face (one light source), which is what makes ranges read as 3Dshade = L.ground(mix((70, 68, 100), ctx.haze_color, hz))for i, (px_, py_) in enumerate(peaks):j = i if sd > 0 else i - 1if 0 <= j < len(valleys):8 unmodified linescv.poly(cap, snow_c)half = [(px_, py_), (px_ + sd * sh * .7, py_ + sh), (px_ + sd * sh * .3, py_ + sh * .78), (px_ + sd * sh * .05, py_ + sh * 1.0)]cv.poly(half, snow_s)hills(cv, ctx, rng, (90, 140, 80), layers=((-.01, .02, .25),))ground_plane(cv, ctx, (60, 110, 48), (120, 170, 84), grain=.25)trace.append("scene: mountains -> two shaded ranges with snowcaps")3 unmodified linessd = 1 if ctx.sun[0] > W / 2 else -1# rule: a dense wall of pines in two hazy layers; each pine has a lit half toward the sun, and they overlap so# the band reads as woods rather than a countable row of treesfor layer, hz in enumerate((.5, .25)):x = -5col = L.ground(mix((35, 85, 50), ctx.haze_color, hz))lit = L.ground(mix((70, 125, 70), ctx.haze_color, hz))3 unmodified linescv.poly([(x, y0 - h), (x + sd * h * .22, y0 + 2), (x + sd * h * .06, y0 + 2)], lit)x += h * rng.uniform(.16, .26)cv.rows(y0 - H * .02 * (layer + 1), y0 + 2, lambda x, y, col=col: col)ground_plane(cv, ctx, (50, 90, 40), (95, 140, 65), grain=.25)# rule: "in a forest" frames the scene with big dark pines at both edges (you're among the trees)W_, H_, y0_, L_ = cv.w, cv.h, ctx.y0, ctx.Lfor side in (0, 1):tx = W_ * (.03 if side == 0 else .97)th = H_ * .9base = y0_ + (H_ - y0_) * .55cv.capsule(tx, H_, tx, base - th * .2, W_ * .02, L_.ground((60, 45, 32)))for k in range(4):yb = base - th * (.15 + .2 * k)half = W_ * (.15 - .025 * k)cv.poly([(tx - half, yb), (tx, yb - th * .32), (tx + half, yb)], L_.ground(scale((30, 75, 42), 1 - .06 * k)))trace.append("scene: forest -> layered treeline, framing pines")def snow(cv, ctx, scene, rng, trace):draw_sky(cv, ctx, scene, rng, trace)W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.L1 unmodified linehills(cv, ctx, rng, (200, 212, 232), layers=((-.06, .04, .45),))treeline(cv, ctx, rng, (70, 90, 105), y0 - H * .045, H * .03, .35)hills(cv, ctx, rng, (236, 240, 248), layers=((-.02, .022, .15), (-.004, .015, .0)))shade = (186, 198, 228)def drift(x, y):t = (y - y0) / (H - y0)# rule: long soft drift bands (sin ridges stretched by perspective), lit on top, shaded belowr = math.sin((y - y0) / (H * (.035 + .07 * t)) + 2.2 * math.sin(x / W * 5 + 1))return L.ground(mix((250, 251, 255), shade, .2 + .6 * max(0, r) * (.4 + .6 * t) - .1 * t))cv.poly([(0, y0 + 1), (W, y0 - 1), (W, H), (0, H)], drift)trace.append("scene: snow -> pale hills, frosted treeline, drifts")41 unmodified lines# rule: things standing on the beach stand on sand, so the waterline goes above the highest footshore = max(y0 + (H - y0) * .05, min(y0 + (H - y0) * .2, min(feet) - (H - y0) * .12))ctx.shore = shoreu = H / 128top, hor = sky_colors(scene)deep = mix((30, 92, 160), top, .2)57 unmodified linesif _ptex_ripple:pixeltex.ripples(cv, ctx, scene, rng, trace, y0 + 1 + H * .025, H, glint(scene), int(50 * W / 256))ctx.waterline = True# rule: things that can't float stand on a near bank, so a dog by a boat isn't wadinglandlubbers = [it for it in insts if it.info.get("setting") not in ("water", "underwater") and it.pose != "flying" and it.rel != "on"]if landlubbers:bank = min(it.y for it in landlubbers) - (H - y0) * .1bank = max(y0 + (H - y0) * .25, bank)pts = [(x, bank + u * (1.5 * math.sin(x / W * 13 + 1) + .8 * math.sin(x / W * 31))) for x in range(0, W + 4, max(1, W // 64))]cv.poly(pts + [(W, H), (0, H)], lambda x, y: L.ground(mix((130, 170, 80), (70, 115, 50), (y - bank) / (H - bank) + fbm(x * .1 * 128 / H, y * .1 * 128 / H, 3) * .3)))cv.poly(pts + [(W, bank + 2 * u), (0, bank + 2 * u)], L.ground((200, 185, 140)), alpha=.8)trace.append("scene: water -> near bank for things that can't float")trace.append("scene: water -> far shore, ripples")132 unmodified lines# rule: walls are nearly flat with a faint paint texture (gradients band badly in pixel art), a touch brighter# near the window by day (or round a warm lamp pool at night) so the back plane has a light sourcedef wallc(x, y):glow = (.06 - .1 * abs(x - wcx) / W) if not night else (.14 - .25 * abs(x - lampx) / W)v = .94 + .04 * (y / y0) + max(-.03, glow) + .03 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5)if kind == "bedroom" and (x % stripe) < W * .02: # wallpaper stripesv *= .94return scale(wall, k * v)16 unmodified linescv.rows(0, y0 * .32, lambda x, y: scale(cab, .78 if (x % (W * .2)) < max(1, u) else .92 + .06 * (y / (y0 * .32))))cv.rows(y0 * .32 - max(1, u), y0 * .32, lambda x, y: scale(cab, .6))window(cv, ctx, scene, k, wx, wy, ww, wh, blinds=kind == "office")if kind in ("living", "bedroom"):# rule: soft curtains hang either side of the window (cosy, and part of the wall, not a free object)cur = scale(rng.choice([(190, 90, 80), (110, 140, 170), (200, 170, 110), (140, 160, 120)]), k)9 unmodified linesif kind in ("kitchen", "bathroom"):fc = (210, 210, 215) if kind == "bathroom" else (180, 150, 120)def fl(x, y):t = (y - y0) / (H - y0)a = int((x - W / 2) / (t + .05) / (W * .08))b = int((y - y0) / (H * .05))return scale(fc, k * (.84 + .14 * ((a + b) % 2)) * (.85 + .22 * t))else:floor = rng.choice([(165, 115, 75), (186, 142, 98), (146, 100, 68)])2 unmodified linesfrom .pixeltex import active as _pt_active, wood_tone_plank = _pt_active(cv, "plank")def fl(x, y):t = (y - y0) / (H - y0)uu = (x - W / 2) / (t + .08)pw = W * .12idx = math.floor(uu / pw)seam = (uu - idx * pw) < pw * .07 / (t + .3)if _plank:tone = .94 + .04 * ((idx * 7) % 3) / 2tone *= wood_tone(idx, (uu - idx * pw) / pw, (y - y0) / (H * .04 * (t + .3)), False) / .93else:25 unmodified linescv.poly(rugpts(0), mix(rc, (230, 215, 185), .45))cv.poly(rugpts(2.5 * u), rc)cv.poly(rugpts(4 * u), lambda x, y: scale(rc, .92 + .08 * ((int(x / (3 * u)) + int(y / (3 * u))) % 2)))if night:warm_night(cv, H, (wx, wy, wx + ww, wy + wh))ctx.L.ambient += .0519 unmodified linesreturn 1 + (.09 * (1 - abs(dx) * 2) ** .5 if abs(dx) < .5 else 0)# rule: the wall is flat paint lit a little from the window side, and darkens just above the table (contact shade)def wallc(x, y):v = .93 + .05 * (y / y0) + .05 - .1 * abs(x - lsx) / W + .03 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5)v -= .08 * max(0, 1 - (y0 - y) / (H * .05))return scale(wall, k * v)cv.rows(0, y0, wallc)300 unmodified linesfrom .shading import _hashdef _has(scene, *names):"""True when the prompt names one of these things itself (then the background must not add more of them)."""for e in scene.get("entities", []):102 unmodified lines_rect(cv, x - 4 * u, yb - .2 * u, x + 4 * u, yb + .8 * u, (255, 236, 186))def _aurora(cv, ctx, rng, strength=1.0):"""rule: aurora = curtains of vertical light from a wavy top edge, bright at the top and fading downward,green with a violet fringe; shimmer comes from per-column brightness."""W, H, y0 = cv.w, cv.h, ctx.y0for kk, (col, a0) in enumerate((((90, 240, 160), .55 * strength), ((150, 120, 240), .3 * strength))):base = y0 * (.18 + .14 * kk)ph = rng.uniform(0, 6)42 unmodified linesg += q if q > 0 else 0return gcv.rows(0, y0, lambda x, y: scale(wall, k * (.84 + (.2 if night else .1) * glow(x, y) + .05 * y / y0+ .03 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 17) - .5))))wy0 = y0 * .62panel = (96, 62, 42)pw = W * .125139 unmodified linesctx.haze_color = (210, 210, 195)wall = rng.choice([(236, 230, 206), (206, 222, 200), (214, 222, 232)])sun_r = ctx.sun[0] > W / 2cv.rows(0, y0, lambda x, y: scale(wall, k * (.95 + .04 * y / y0 + .02 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 31) - .5))))cv.rows(y0 * .7, y0, lambda x, y: scale(mix(wall, (120, 150, 150), .35), k))# rule: classroom = a big green chalkboard (wood frame, chalk tray, faint erased smudges, never any writing),# tall windows on the sun side, and a row of small desks along the back wall449 unmodified linesu = H / 128.0hz = ctx.haze_colorif scene["time"] == "night" and "aurora" not in scene.get("features", []):_aurora(cv, ctx, rng, .7) # rule: a polar night sky carries a faint aurorasd = 1 if ctx.sun[0] < W / 2 else -1 # +1: right faces in shade# rule: arctic = flat-topped tabular icebergs and a glacier wall with sheer blue-shaded faces, a dark open-water# lead with floes, then flat blue-white sea ice with pressure ridges and cracks (no trees, no falling snow:553 unmodified linesreturn ri <= d <= ro and y < y0cv.fill(inside, (cx - ro, y0 - ro, cx + ro, y0), c, .55)if "aurora" in fs:_aurora(cv, ctx, rng)if "meteor" in fs:x, y = W * .7, y0 * .15cv.capsule(x, y, x - W * .3, y + y0 * .2, .8 * u, (255, 250, 220), alpha=.7)5 unmodified linesfor a in range(14):ang = a * math.pi * 2 / 14cv.capsule(cx, cy, cx + math.cos(ang) * 8 * u, cy + math.sin(ang) * 8 * u, .45 * u, col, alpha=.85)if "lightning" in fs and "lightning" in (scene.get("sim_fx") or []):from .physics2 import draw_bolt # wave 12: dielectric-breakdown lightningdraw_bolt(cv, ctx, scene, rng, W, y0, u)elif "lightning" in fs:22 unmodified lines# rule: a river has a pale sandy bank edge on both sides and mirrors the sky coloursbank = [(x - u * (1 + 2 * (y - y0) / (H - y0)), y) for x, y in pts_l] + [(x + u * (1 + 2 * (y - y0) / (H - y0)), y) for x, y in pts_r[::-1]]cv.poly(bank, L.ground((196, 180, 136)))wf, wn = water_colors(scene)cv.poly(pts_l + pts_r[::-1], lambda x, y: L.ground(mix(mix(wf, (70, 130, 180), .3), wn, (y - y0) / (H - y0))))for _ in range(22):18 unmodified linesdef weather(cv, ctx, scene, rng, trace):W, H = cv.w, cv.hu = H / 128if scene["place"] == "snow" or scene.get("weather") == "snow":for _ in range(int(W * H / (500 * u * u))):r = rng.choice([.5, .6, .8, 1.0]) * ucv.ellipse(rng.uniform(0, W), rng.uniform(0, H), r, r, (255, 255, 255), alpha=rng.uniform(.5, .9))trace.append("scene: falling snow")if scene.get("weather") == "rain":for _ in range(int(W * H / (250 * u * u))):x, y = rng.uniform(0, W), rng.uniform(0, H)cv.capsule(x, y, x - 1.2 * u, y + 4 * u, .3 * u, (200, 210, 230), alpha=.45)trace.append("scene: rain streaks")if scene.get("weather") == "fog":y0 = ctx.y0for y in range(H):a = max(0, .55 - abs(y - y0) / H * 1.2)3 unmodified linesfor i in range(3):p[i] += (215 - p[i]) * atrace.append("scene: fog band at the horizon")9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431444 unmodified lines14915015115215315415515615719 unmodified lines17717817918018118218318418518643 unmodified lines2302312322332342352362372382392402412422432442452462472482496 unmodified lines25625725825926026126226326426526626726826927027127227327427527627727827928028128228328428515 unmodified lines30130230330430530630730830931031131231331459 unmodified lines37437537637737837938038138238338438538638738838939039139239339439539639712 unmodified lines4104114124134144154164174184194204214224238 unmodified lines4324334344354364374384394404414424434443 unmodified lines4484494504514524534544554564574583 unmodified lines4624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146151 unmodified line61761861962062162262362462562662762862963063163263341 unmodified lines67567667767867968068157 unmodified lines739740741742743744745746747748749750751752753754755756132 unmodified lines88989089189289389489589689789889990090116 unmodified lines9189199209219229239249259269279289299309319329339349359369379389399 unmodified lines9499509519529539549559569579589599609619629632 unmodified lines96696796896997097197297397497597697797897998098198298398498525 unmodified lines1011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103919 unmodified lines105910601061106210631064106510661067106810691070300 unmodified lines1371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407102 unmodified lines1510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155642 unmodified lines1599160016011602160316041605139 unmodified lines1745174617471748174917501751449 unmodified lines2201220222032204220522062207553 unmodified lines27612762276327642765276627675 unmodified lines2773277427752776277727782779278027812782278327842785278622 unmodified lines28092810281128122813281428152816281728182819282028212822282328242825282618 unmodified lines28452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428753 unmodified lines287928802881288228832884288528869 unmodified linesINDOOR = {"studio", "table", "room", "kitchen", "bathroom", "bedroom", "office"}def milky_way(cv, ctx, scene, rng):"""rule (night pixel round 3, milky): a starry sky gets the milky way - a diagonal band two flat tones lighterthan the sky, split by a dark dust lane, dense with tiny stars and a few coloured bright ones"""W, H, y0 = cv.w, cv.h, ctx.y0u = H / 128.0keep = getattr(cv, "tex_keep", None)if keep is None:keep = cv.tex_keep = set()s_ = 1 if rng.random() < .5 else -1x0, y0b, x1, y1b = (W * -.1, y0 * .95, W * 1.1, -y0 * .1) if s_ > 0 else (W * -.1, -y0 * .1, W * 1.1, y0 * .95)dx, dy = x1 - x0, y1b - y0bln = math.hypot(dx, dy)nx, ny = -dy / ln, dx / lnwid = H * .1for y in range(int(y0)):row = cv.px[y]for x in range(W):d = (x - x0) * nx + (y - y0b) * nywob = math.sin(((x - x0) * dx + (y - y0b) * dy) / ln / W * 9) * wid * .25dd = abs(d - wob)if dd < wid:k = .16 if dd < wid * .45 else .08if abs(d - wob - wid * .12) < wid * .09:k = .02 # the dust lanep = row[x]p[0] += (150 - p[0]) * k; p[1] += (160 - p[1]) * k; p[2] += (210 - p[2]) * kfor _ in range(int(W * H / (30 * u * u))):t = rng.random()off = rng.gauss(0, wid * .45)x = x0 + dx * t + nx * offy = y0b + dy * t + ny * offxi, yi = int(x), int(y)if 0 <= xi < W and 0 <= yi < y0 - 2:c = rng.choice(((235, 238, 255), (210, 220, 255), (255, 236, 210), (240, 240, 255)))a = rng.uniform(.4, .95)p = cv.px[yi][xi]p[0] += (c[0] - p[0]) * a; p[1] += (c[1] - p[1]) * a; p[2] += (c[2] - p[2]) * akeep.add((yi, xi))for _ in range(6): # a few coloured bright starsx, y = int(rng.uniform(0, W)), int(rng.uniform(0, y0 * .7))c = rng.choice(((255, 200, 160), (170, 200, 255), (255, 245, 200)))for ddx, ddy in ((0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)):xx, yy = x + ddx, y + ddyif 0 <= xx < W and 0 <= yy < H:a = 1.0 if (ddx, ddy) == (0, 0) else .45p = cv.px[yy][xx]p[0] += (c[0] - p[0]) * a; p[1] += (c[1] - p[1]) * a; p[2] += (c[2] - p[2]) * akeep.add((yy, xx))def _sunny(scene):"""rule (night pixel round 3, sunnysnow): "sunny / clear / bluebird" snow days get a blue sky, sun and nosnowfall (the snow setting was always overcast and snowing)"""v = scene.get("_sunny")if v is None:from .atmos import on, toksv = scene["_sunny"] = bool(on("sunnysnow") and scene.get("time") != "night"and (not scene.get("weather") or (scene.get("weather_src") == "mood" and on("namedsun")))and bool(toks(scene) & ({"sunny", "clear", "sunshine", "sunlit", "bluebird", "cloudless"}| ({"sun"} if on("namedsun") else set()))or (on("thaw") and _thaw(scene))))return vdef _thaw(scene):"""rule (night pixel2, thaw): a melting / thawing snow scene, or snow under a spring / summer sun, is a thaw:sunny, no snowfall, grass showing through the snow (critic P12 "a snowman melting in the spring sun")"""from .atmos import tokst = toks(scene)return bool(t & {"melting", "melts", "melt", "thaw", "thawing", "melted"}) or (scene.get("season") in ("spring", "summer") and bool(t & {"sun", "sunny", "sunshine", "warm"})) or (bool(t & {"warm", "hot"}) and bool(t & {"sun", "sunshine", "sunny"}))def _dawn(scene):"""rule (night pixel round 3, dawn): low sun in the morning (dawn / sunrise / daybreak / morning) is not a sunset -paler, cooler sky (periwinkle -> blush -> pale gold) and a low mist on the ground. Cached on the scene."""v = scene.get("_dawn")if v is None:from .atmos import on, toksv = scene["_dawn"] = bool(on("dawn") and scene.get("time") == "sunset"and toks(scene) & {"dawn", "sunrise", "daybreak", "morning", "sunup"}and not toks(scene) & {"sunset", "dusk", "evening", "twilight"})return vdef _storm(scene):from .atmos import stormyreturn stormy(scene)def _tk_(scene):from .atmos import toksreturn toks(scene)def _rain_dusk_on():from .atmos import onreturn on("rainsunset")def sky_colors(scene):t, p, w = scene["time"], scene["place"], scene.get("weather")from .atmos import on as _aon0, toks as _tk0if _aon0("blizzard") and t != "night" and _tk0(scene) & {"blizzard", "blizzards", "snowstorm", "whiteout"}:return (150, 160, 178), (214, 220, 230) # rule (night pixel2, blizzard): a snowstorm sky is a grey whiteoutfrom .atmos import on as _aonfrom .atmos import storm_named as _snif t == "day" and ((w == "rain" and _storm(scene)) or (_aon("galesky") and _sn(scene))):# rule (night pixel round 3): a storm sky is dark slate, not drizzle grey; (night pixel2, galesky) also when# the storm is named without rain ("a tugboat in rough seas during a gale" had a clear sky and a sun)return (56, 62, 80), (126, 132, 146)if w == "rain" and t == "sunset" and not _dawn(scene) and _aon("rainsunset"):# rule (night pixel2, rainsunset): rain at dusk is a dim grey-violet overcast, not a clear sunsetreturn (78, 76, 106), (176, 150, 150)if p == "volcanic": # rule: volcanic skies are ash-laden: smoky orange by day, blood red at sunset, ember-lit at nightreturn {"day": ((120, 108, 108), (222, 164, 112)), "sunset": ((60, 30, 52), (232, 96, 52)), "night": ((14, 8, 18), (92, 34, 26))}[t]if t == "night":return (12, 16, 46), (46, 58, 108)if t == "sunset":if _dawn(scene):return (92, 116, 182), (255, 222, 168) # rule (dawn): a cool periwinkle top over a pale gold horizonreturn (58, 56, 130), (255, 178, 104)if p == "swamp": # rule: swamp air is humid: a hazy grey-green skyreturn (118, 140, 140), (198, 208, 188)if p == "arctic": # rule: polar sky is crisp and pale, bluer than overcast "snow"return (84, 146, 214), (216, 234, 246)if p == "snow" and not w and _sunny(scene):return (84, 146, 214), (216, 234, 246) # rule: a sunny snow day has a crisp blue skyif p == "snow" or w in ("rain", "fog"):return (140, 152, 172), (205, 212, 222)if p == "desert":4 unmodified linesdef sky_at(scene, y, y0):"""Sky colour at row y (shared by draw_sky, windows and cloud edge tests)."""top, hor = sky_colors(scene)if scene["time"] == "sunset" and not (scene.get("weather") == "rain" and not _dawn(scene) and _rain_dusk_on()):# rule: sunset sky = indigo -> rose -> amber, three stopsmid = (232, 120, 120) if not _dawn(scene) else (238, 178, 186)k = y / (y0 * .62)return mix(top, mid, k) if k < 1 else mix(mid, hor, (y - y0 * .62) / (y0 * .38))if scene["time"] == "night":19 unmodified linesdef cloud_palette(scene):"""rule: clouds are three flat tones (light rim, body, shadowed belly) tinted by the time of day."""t, w = scene["time"], scene.get("weather")from .atmos import on as _aon, storm_named as _snif t == "day" and ((w == "rain" and _storm(scene)) or (_aon("galesky") and _sn(scene))):return (156, 160, 172), (112, 118, 134), (74, 80, 98)if w == "rain" or (scene["place"] == "snow" and t == "day" and not _sunny(scene)) or w == "fog":return (205, 208, 216), (178, 183, 196), (140, 146, 162)if t == "sunset":return (255, 222, 170), (246, 170, 150), (170, 110, 145)43 unmodified linessx, sy = ctx.sunu = H / 128.0night = scene["time"] == "night"overcast = (scene["place"] == "snow" and not _sunny(scene)) or scene.get("weather") in ("rain", "fog")if scene["time"] == "day":from .atmos import on as _aon, storm_named as _snovercast = overcast or (_aon("galesky") and _sn(scene))if overcast and scene.get("weather_src") == "mood" and _aon("namedsun") and "sun" in _tk_(scene):overcast = False # rule (night pixel2, namedsun): a named sun shows through a mood's light haze (critic2 P18)if _aon("blizzard") and _tk_(scene) & {"blizzard", "blizzards", "snowstorm", "whiteout"}:overcast = Trueif scene["place"] == "jungle" and _aon("junglesun") and getattr(cv, "ss", 2) == 1:overcast = True # rule (night pixel2, junglesun): the canopy hides the sun; a pale disc in a gap read as a moon (critic2 P17)if night:from .atmos import on as _aon, toks as _toksif cv.ss == 1 and _aon("milky") and _toks(scene) & {"starry", "stars", "milky", "galaxy", "constellations", "starlit"}:milky_way(cv, ctx, scene, rng)# rule: night stars = many faint 1px dots + a few bright 4-point twinklers, thinning toward the horizonfor _ in range(int(W * y0 / (160 * u * u))):x, y = rng.uniform(0, W), y0 * rng.random() ** 1.6 * .856 unmodified linescv.rows(y0 - H * .06, y0 + 2, lambda x, y: mix(sky_at(scene, y, y0), (90, 96, 150), .25 * (1 - (y0 - y) / (H * .06))))if not any(e["concept"] in ("full moon", "crescent moon", "planet") for e in scene.get("entities", [])):# rule: the sky's own moon is skipped when the prompt names a moon (no double moons)from .atmos import on as _aonif _aon("moon2"):# rule (night pixel round 3): the moon is the brightest thing in the sky - a flat pale crescent# with two faint maria, inside one tight glow ring (the old moon was night-shaded to a grey ring)R = H * .045cv.fill(lambda x, y: R * 1.05 < math.hypot(x - sx, y - sy) < R * 1.6, (sx - 2 * R, sy - 2 * R, sx + 2 * R, sy + 2 * R),(150, 165, 215), alpha=.16)cv.ellipse(sx, sy, R, R, (246, 240, 212))cv.ellipse(sx - R * .35, sy + R * .2, R * .26, R * .22, (226, 218, 194))cv.ellipse(sx - R * .05, sy - R * .4, R * .17, R * .14, (226, 218, 194))cv.ellipse(sx + R * .5, sy - R * .27, R * .9, R * .9, lambda x, y: sky_at(scene, y, y0))else:for r, a in ((.11, .06), (.08, .1)):cv.ellipse(sx, sy, H * r, H * r, (225, 232, 255), alpha=a)lit_ellipse(cv, ctx.L, sx, sy, H * .045, H * .045, (248, 246, 228))cv.ellipse(sx + H * .022, sy - H * .012, H * .04, H * .04, sky_at(scene, sy, y0))trace.append("scene: night sky -> stars + crescent moon")elif not overcast:sun_c = (255, 246, 205) if scene["time"] == "day" else (255, 214, 140)# rule: the sun's glow is several faint rings, not one hard halofrom .atmos import on as _aon# rule (night pixel round 3, sun2): in pixel art the glow is one tight ring - four faint rings snapped into# four big stepped discsfor r, a in (((.092, .2),) if cv.ss == 1 and _aon("sun2") else ((.2, .05), (.15, .07), (.11, .1), (.085, .14))):cv.ellipse(sx, sy, H * r, H * r, sun_c, alpha=a)cv.ellipse(sx, sy, H * .065, H * .065, sun_c)if scene["time"] == "sunset":15 unmodified linesn_cl = 4if scene.get("weather") in ("rain",):n_cl = 6if cv.ss == 1 and ("aurora" in (scene.get("features") or ()) or "starry" in (scene.get("text") or "")):from .atmos import on as _aonif _aon("aurora2"):n_cl = 0 # rule (night pixel round 3): a sky that is the show stays clear of cloudsif cv.ss == 1 and scene["place"] == "jungle":from .atmos import on as _aonif _aon("junglesun"):n_cl = 0 # rule (night pixel2, junglesun): no clouds above a canopy - a cloud cut by the leaves read as a moon (critic3)placed = []for _ in range(n_cl):for _try in range(8):59 unmodified linesdraw_sky(cv, ctx, scene, rng, trace)W, H, y0 = cv.w, cv.h, ctx.y0autumn = scene.get("season") == "autumn"from .atmos import on as _aon, snowy as _snowysn = _snowy(scene) and _aon("snowground")g = (150, 140, 70) if autumn else (95, 150, 80)if sn:g = (226, 232, 244) # rule: snowy hills, a frosted blue-grey treeline# rule: three hill layers, bluer and paler with distance (atmospheric perspective)hills(cv, ctx, rng, mix(g, (70, 110, 150), .3 if not sn else .12), layers=((-.08, .05, .42),))treeline(cv, ctx, rng, (160, 110, 50) if autumn else (45, 95, 60) if not sn else (84, 104, 118), y0 - H * .045, H * .03, .3)hills(cv, ctx, rng, g, layers=((-.022, .022, .2), (-.006, .016, .06)))if sn:snow_ground(cv, ctx) # rule (night pixel round 3): a snowy field is snow, not grasselse:ground_plane(cv, ctx, (60, 112, 46) if not autumn else (120, 110, 50), (125, 180, 84) if not autumn else (175, 160, 80), grain=.25)trace.append("scene: field -> sky, layered hills, distant woods, grass")def mountains(cv, ctx, scene, rng, trace):from .atmos import on as _aon_mdraw_sky(cv, ctx, scene, rng, trace)W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.Lsd = 1 if ctx.sun[0] < W / 2 else -1 # shadow side (+1 = right faces are in shade)12 unmodified linespts.append(v)pts.append(peaks[-1])rock = L.ground(mix((105, 100, 125), ctx.haze_color, hz))nk = 1.0if scene["time"] == "night" and _aon_m("nightpeaks"):# rule (night pixel round 3): night ranges are dark violet silhouettes, clearly darker than the horizon# glow (same-tone rock merged into the sky and left the snowcaps floating as triangles)rock, nk = ((26, 24, 44) if layer == 0 else (17, 15, 30)), .7cv.poly(pts + [(W * 1.1, y0 + 2), (-W * .1, y0 + 2)], rock)# rule: every peak has a lit face and a shaded face (one light source), which is what makes ranges read as 3Dshade = scale(rock, nk) if nk != 1.0 else L.ground(mix((70, 68, 100), ctx.haze_color, hz))for i, (px_, py_) in enumerate(peaks):j = i if sd > 0 else i - 1if 0 <= j < len(valleys):8 unmodified linescv.poly(cap, snow_c)half = [(px_, py_), (px_ + sd * sh * .7, py_ + sh), (px_ + sd * sh * .3, py_ + sh * .78), (px_ + sd * sh * .05, py_ + sh * 1.0)]cv.poly(half, snow_s)from .atmos import on as _aon, snowy as _snowyif _snowy(scene) and _aon("snowground"):hills(cv, ctx, rng, (225, 232, 245), layers=((-.01, .02, .25),))snow_ground(cv, ctx)else:hills(cv, ctx, rng, (90, 140, 80), layers=((-.01, .02, .25),))ground_plane(cv, ctx, (60, 110, 48), (120, 170, 84), grain=.25)trace.append("scene: mountains -> two shaded ranges with snowcaps")3 unmodified linessd = 1 if ctx.sun[0] > W / 2 else -1# rule: a dense wall of pines in two hazy layers; each pine has a lit half toward the sun, and they overlap so# the band reads as woods rather than a countable row of treesfrom .atmos import on as _aon0autumn = scene.get("season") == "autumn" and cv.ss == 1 and _aon0("autumn2")if autumn:autumn_woods(cv, ctx, rng)for layer, hz in enumerate(() if autumn else (.5, .25)):x = -5col = L.ground(mix((35, 85, 50), ctx.haze_color, hz))lit = L.ground(mix((70, 125, 70), ctx.haze_color, hz))3 unmodified linescv.poly([(x, y0 - h), (x + sd * h * .22, y0 + 2), (x + sd * h * .06, y0 + 2)], lit)x += h * rng.uniform(.16, .26)cv.rows(y0 - H * .02 * (layer + 1), y0 + 2, lambda x, y, col=col: col)from .atmos import on as _aon, snowy as _snowysn = _snowy(scene) and _aon("snowground")if sn:snow_ground(cv, ctx)elif autumn:ground_plane(cv, ctx, (96, 78, 40), (150, 120, 62), grain=.25)leaf_litter(cv, ctx, rng)else:ground_plane(cv, ctx, (50, 90, 40), (95, 140, 65), grain=.25)# rule: "in a forest" frames the scene with big dark pines at both edges (you're among the trees)W_, H_, y0_, L_ = cv.w, cv.h, ctx.y0, ctx.Lif cv.ss == 1 and _aon("pines2"):framing_pines(cv, ctx, scene, sn)else:for side in (0, 1):tx = W_ * (.03 if side == 0 else .97)th = H_ * .9base = y0_ + (H_ - y0_) * .55cv.capsule(tx, H_, tx, base - th * .2, W_ * .02, L_.ground((60, 45, 32)))for k in range(4):yb = base - th * (.15 + .2 * k)half = W_ * (.15 - .025 * k)cv.poly([(tx - half, yb), (tx, yb - th * .32), (tx + half, yb)], L_.ground(scale((30, 75, 42), 1 - .06 * k)))trace.append("scene: forest -> layered treeline, framing pines")def _snow_hi(cv):"""rule (night pixel round 3, snowcool): pixel snow is a cool blue-white - the warm daylight grade turned the oldpure white into cream sand"""if cv.ss == 1:from .atmos import onif on("snowcool"):return (230, 239, 255)return (250, 251, 255)def _snow_bend(cv):"""pixel snow drifts are long gentle swells (a strong bend made one big V-shaped lavender wedge)"""return 2.2 if _snow_hi(cv)[0] > 240 else .9def snow_ground(cv, ctx):"""snow drifts as the ground (shared by the snow setting and snowy forests / fields)"""W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.Lshade = (186, 198, 228) if _snow_hi(cv)[0] > 240 else (204, 214, 236)night_snow = _snow_hi(cv)[0] < 240 and ctx.time == "night"def drift(x, y):t = (y - y0) / (H - y0)r = math.sin((y - y0) / (H * (.035 + .07 * t)) + _snow_bend(cv) * math.sin(x / W * 5 + 1))k_ = .2 + .6 * max(0, r) * (.4 + .6 * t) - .1 * tif night_snow: # rule (snowcool): moonlit snow is pale blue-grey, quiet drifts (the night tint made violet)return mix((132, 146, 188), (104, 118, 166), .3 + .5 * k_)return L.ground(mix(_snow_hi(cv), shade, k_))cv.poly([(0, y0 + 1), (W, y0 - 1), (W, H), (0, H)], drift)AUTUMN = ((214, 104, 38), (232, 160, 44), (178, 52, 34), (196, 132, 52), (120, 110, 44))def autumn_woods(cv, ctx, rng):"""rule (night pixel round 3, autumn2): an autumn forest is a wall of round deciduous crowns in fall colours -a hazy far band, then a near row of overlapping crowns, each crown one flat colour with a lit cap toward the sunand a few dark trunks showing under them (pines stay green: only the framing pines)"""W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.Lu = H / 128.0sd = 1 if ctx.sun[0] > W / 2 else -1treeline(cv, ctx, rng, (190, 120, 60), y0 - H * .07, H * .06, .45)x = -4 * uwhile x < W + 4 * u:r = rng.uniform(5, 9) * ucy = y0 - r * rng.uniform(.6, 1.2)c = rng.choice(AUTUMN)cv.capsule(x, cy + r, x, y0 + 2, max(.6, .7 * u), L.ground((70, 50, 38)))cv.ellipse(x, cy, r, r * .85, L.ground(mix(c, ctx.haze_color, .18)))cv.ellipse(x + sd * r * .3, cy - r * .3, r * .55, r * .45, L.ground(mix(scale(c, 1.15), (255, 230, 160), .2)))x += r * rng.uniform(1.0, 1.5)cv.rows(y0 - H * .01, y0 + 2, lambda x, y: L.ground((92, 70, 40)))def leaf_litter(cv, ctx, rng):"""fallen leaves: 2-3 px flecks in fall colours on the ground, bigger toward the viewer (registered as drawnmarks so the cleanup keeps them)"""W, H, y0 = cv.w, cv.h, ctx.y0keep = getattr(cv, "tex_keep", None)if keep is None:keep = cv.tex_keep = set()for _ in range(int(W * (H - y0) / (40 * (H / 128.0) ** 2))):y = int(y0 + 2 + (H - y0 - 3) * rng.random() ** .8)x = int(rng.uniform(0, W))t = (y - y0) / (H - y0)c = ctx.L.ground(rng.choice(AUTUMN))pts = [(0, 0)] + ([(1, 0)] if t > .25 else []) + ([(1, -1)] if t > .6 and rng.random() < .6 else [])for dx, dy in pts:xx, yy = x + dx, y + dyif 0 <= xx < W and 0 <= yy < H and not cv.ids[yy][xx]:p = cv.px[yy][xx]p[0], p[1], p[2] = ckeep.add((yy, xx))def framing_pines(cv, ctx, scene, snowy=False):"""rule (night pixel round 3, pines2): the framing pines at the edges are drawn like pixel-art trees - stackedtiers with drooping saw-tooth branch tips, a lit edge toward the light, a dark trunk, snow on the tiers when thescene is snowy. Their pixels are recorded in ctx.near_bg (near scenery: fog stays off them, no cast shadows)."""W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.Lu = H / 128.0sd = 1 if ctx.sun[0] > W / 2 else -1cv.cur_id = -7for side in (0, 1):tx = W * (.02 if side == 0 else .98)base = y0 + (H - y0) * .62th = H * .95lit_side = (sd > 0) == (side == 0) # the inner edge faces the light when the light is across the framecv.poly([(tx - W * .018, H), (tx - W * .014, base - th * .3), (tx + W * .014, base - th * .3), (tx + W * .018, H)],L.ground((58, 42, 34)))n = 5for k in range(n):yb = base - th * (.1 + .16 * k)ytop = yb - th * .24half = W * (.17 - .026 * k)body = L.ground(scale((30, 72, 44), 1 - .05 * k)) if scene["time"] != "night" else (9, 12, 18)teeth = 4 + (n - k) // 2pts = [(tx, ytop)]for j in range(teeth, -teeth - 1, -1): # saw-tooth bottom edge, right to left; tips droop outwardf = j / teethpts.append((tx + half * f, yb - (u * 2.2 if j % 2 else 0) + abs(f) * u * 1.5))cv.poly(pts, body)# lit edge: a thin band along the upper slope on the side facing the lights_ = 1 if (side == 0) == (sd > 0) else -1edge = scale((62, 112, 70), 1 - .05 * k)if scene["time"] == "night":edge = (44, 60, 78) # moonlight catches the edge of the tiers, so the trees read against the darkcv.poly([(tx, ytop), (tx + s_ * half, yb + u), (tx + s_ * half * .82, yb + u), (tx + s_ * u * .5, ytop + u * 3)],L.ground(edge) if scene["time"] != "night" else edge)if snowy:cv.poly([(tx, ytop), (tx + half * .55, ytop + (yb - ytop) * .55), (tx + half * .2, ytop + (yb - ytop) * .45),(tx - half * .2, ytop + (yb - ytop) * .5), (tx - half * .55, ytop + (yb - ytop) * .55)], (236, 242, 252))cv.cur_id = Noneimport numpy as _npI = _np.asarray(cv.ids)ctx.near_bg = cv.near_bg = I == -7for row in cv.ids:for x, v in enumerate(row):if v == -7:row[x] = 0def snow(cv, ctx, scene, rng, trace):draw_sky(cv, ctx, scene, rng, trace)W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.L1 unmodified linehills(cv, ctx, rng, (200, 212, 232), layers=((-.06, .04, .45),))treeline(cv, ctx, rng, (70, 90, 105), y0 - H * .045, H * .03, .35)hills(cv, ctx, rng, (236, 240, 248), layers=((-.02, .022, .15), (-.004, .015, .0)))shade = (186, 198, 228) if _snow_hi(cv)[0] > 240 else (204, 214, 236)night_snow = _snow_hi(cv)[0] < 240 and ctx.time == "night"def drift(x, y):t = (y - y0) / (H - y0)# rule: long soft drift bands (sin ridges stretched by perspective), lit on top, shaded belowr = math.sin((y - y0) / (H * (.035 + .07 * t)) + _snow_bend(cv) * math.sin(x / W * 5 + 1))k_ = .2 + .6 * max(0, r) * (.4 + .6 * t) - .1 * tif night_snow: # rule (snowcool): moonlit snow is pale blue-grey, quiet drifts (the night tint made violet)return mix((132, 146, 188), (104, 118, 166), .3 + .5 * k_)return L.ground(mix(_snow_hi(cv), shade, k_))cv.poly([(0, y0 + 1), (W, y0 - 1), (W, H), (0, H)], drift)trace.append("scene: snow -> pale hills, frosted treeline, drifts")41 unmodified lines# rule: things standing on the beach stand on sand, so the waterline goes above the highest footshore = max(y0 + (H - y0) * .05, min(y0 + (H - y0) * .2, min(feet) - (H - y0) * .12))ctx.shore = shorectx.water_rows = (y0 + 2 * H / 128 + 1, shore - 3 * H / 128) # read by atmos (reflections, sun path)u = H / 128top, hor = sky_colors(scene)deep = mix((30, 92, 160), top, .2)57 unmodified linesif _ptex_ripple:pixeltex.ripples(cv, ctx, scene, rng, trace, y0 + 1 + H * .025, H, glint(scene), int(50 * W / 256))ctx.waterline = Truectx.water_rows = (y0 + 1, H) # read by atmos (reflections, moon path)# rule: things that can't float stand on a near bank, so a dog by a boat isn't wadinglandlubbers = [it for it in insts if it.info.get("setting") not in ("water", "underwater") and it.pose != "flying" and it.rel != "on"]if scene.get("_frozen") and getattr(cv, "ss", 2) == 1:landlubbers = [] # rule (night pixel2, frozen): skaters stand on the ice, not on a bankif landlubbers:bank = min(it.y for it in landlubbers) - (H - y0) * .1bank = max(y0 + (H - y0) * .25, bank)pts = [(x, bank + u * (1.5 * math.sin(x / W * 13 + 1) + .8 * math.sin(x / W * 31))) for x in range(0, W + 4, max(1, W // 64))]cv.poly(pts + [(W, H), (0, H)], lambda x, y: L.ground(mix((130, 170, 80), (70, 115, 50), (y - bank) / (H - bank) + fbm(x * .1 * 128 / H, y * .1 * 128 / H, 3) * .3)))cv.poly(pts + [(W, bank + 2 * u), (0, bank + 2 * u)], L.ground((200, 185, 140)), alpha=.8)ctx.water_rows = (y0 + 1, bank)trace.append("scene: water -> near bank for things that can't float")trace.append("scene: water -> far shore, ripples")132 unmodified lines# rule: walls are nearly flat with a faint paint texture (gradients band badly in pixel art), a touch brighter# near the window by day (or round a warm lamp pool at night) so the back plane has a light source_wflat = _wall_steps(cv)def wallc(x, y):glow = (.06 - .1 * abs(x - wcx) / W) if not night else (.14 - .25 * abs(x - lampx) / W)v = .94 + .04 * (y / y0) + max(-.03, glow) + .03 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5)if _wflat:v = _wflat(y, y0)if kind == "bedroom" and (x % stripe) < W * .02: # wallpaper stripesv *= .94return scale(wall, k * v)16 unmodified linescv.rows(0, y0 * .32, lambda x, y: scale(cab, .78 if (x % (W * .2)) < max(1, u) else .92 + .06 * (y / (y0 * .32))))cv.rows(y0 * .32 - max(1, u), y0 * .32, lambda x, y: scale(cab, .6))window(cv, ctx, scene, k, wx, wy, ww, wh, blinds=kind == "office")ctx.room_window = (wx, wy, ww, wh) # night pixel2: atmos.night_room lays the moonlight patch from itif scene.get("weather") in ("rain", "snow") and getattr(cv, "ss", 2) == 1:from .atmos import on as _aonif _aon("rainpane"):# rule (night pixel2, rainpane): the rain stays outside but shows on the glass - slanted streaks and# beads in the window (snow: flakes); "watching the rain" had a plain grey windowfor _ in range(int(ww * wh / (11 * u * u))):x, y = rng.uniform(wx + 1, wx + ww - 1), rng.uniform(wy + 1, wy + wh - 2 * u)b = cv.px[min(cv.h - 1, int(y))][min(cv.w - 1, int(x))]c = (min(255, b[0] + 30), min(255, b[1] + 32), min(255, b[2] + 38)) # a little lighter than the glassif scene["weather"] == "snow":cv.ellipse(x, y, .5 * u, .5 * u, scale((250, 252, 255), k))elif rng.random() < .7:cv.capsule(x, y, x - .4 * u, y + 3.2 * u, .35 * u, c, alpha=.85)else:cv.ellipse(x, y, .45 * u, .55 * u, c)if kind in ("living", "bedroom"):# rule: soft curtains hang either side of the window (cosy, and part of the wall, not a free object)cur = scale(rng.choice([(190, 90, 80), (110, 140, 170), (200, 170, 110), (140, 160, 120)]), k)9 unmodified linesif kind in ("kitchen", "bathroom"):fc = (210, 210, 215) if kind == "bathroom" else (180, 150, 120)_far = _floor_far(cv)def fl(x, y):t = (y - y0) / (H - y0)a = int((x - W / 2) / (t + .05) / (W * .08))b = int((y - y0) / (H * .05))if _far and W * .08 * (t + .05) < _far * .45:# far tiles too narrow to draw: their rows only, in a soft two-tone (critic2: a flat band looked unfinished)return scale(fc, k * (.86 + .1 * (b % 2)) * (.85 + .22 * t))return scale(fc, k * (.84 + .14 * ((a + b) % 2)) * (.85 + .22 * t))else:floor = rng.choice([(165, 115, 75), (186, 142, 98), (146, 100, 68)])2 unmodified linesfrom .pixeltex import active as _pt_active, wood_tone_plank = _pt_active(cv, "plank")_far = _floor_far(cv)def fl(x, y):t = (y - y0) / (H - y0)uu = (x - W / 2) / (t + .08)pw = W * .12idx = math.floor(uu / pw)seam = (uu - idx * pw) < pw * .07 / (t + .3)if _far and pw * (t + .08) < _far:# far floor: planks narrower than a few pixels lose their grain and keep every third seam (a plain band# looked unfinished; every seam was streak noise)tone = .95seam = seam and idx % 3 == 0elif _plank:tone = .94 + .04 * ((idx * 7) % 3) / 2tone *= wood_tone(idx, (uu - idx * pw) / pw, (y - y0) / (H * .04 * (t + .3)), False) / .93else:25 unmodified linescv.poly(rugpts(0), mix(rc, (230, 215, 185), .45))cv.poly(rugpts(2.5 * u), rc)cv.poly(rugpts(4 * u), lambda x, y: scale(rc, .92 + .08 * ((int(x / (3 * u)) + int(y / (3 * u))) % 2)))if not night and getattr(cv, "ss", 2) == 1 and not scene.get("weather"):from .atmos import on as _aon, toks as _tkif _aon("sunpatch") and _tk(scene) & {"sun", "sunny", "sunlight", "sunbeam", "sunbeams", "sunshine", "sunlit", "sunlight"}:# rule (night pixel2, sunpatch): "in the sun" indoors = the window's light lies on the floor as a crisp# bright parallelogram with the mullion cross in shadow (the cat sleeps in it); was a faint smudgeside = -1 if ctx.sun[0] < W / 2 else 1yt, yb = y0 + (H - y0) * .22, y0 + (H - y0) * .9sh_t, sh_b = -side * W * .05, -side * W * .28wl, wr = wx - ww * .1, wx + ww * 1.1k_ = 1.0for y in range(int(yt), min(H, int(yb))):v = (y - yt) / (yb - yt)grow = 1 + .9 * vxl = wcx + (wl - wcx) * grow + sh_t + (sh_b - sh_t) * vxr = wcx + (wr - wcx) * grow + sh_t + (sh_b - sh_t) * vrow = cv.px[y]for x in range(max(0, int(xl)), min(W, int(xr) + 1)):uu = (x - xl) / max(1.0, xr - xl)if abs(uu - .5) < .035 or abs(v - .5) < .03:continue # the window cross throws its shadowp_ = row[x]p_[0] = min(255, p_[0] * 1.22 + 14); p_[1] = min(255, p_[1] * 1.18 + 10); p_[2] = min(255, p_[2] * 1.08 + 2)trace.append("scene: a sun patch from the window on the floor")if night:warm_night(cv, H, (wx, wy, wx + ww, wy + wh))ctx.L.ambient += .0519 unmodified linesreturn 1 + (.09 * (1 - abs(dx) * 2) ** .5 if abs(dx) < .5 else 0)# rule: the wall is flat paint lit a little from the window side, and darkens just above the table (contact shade)_wflat = _wall_steps(cv)def wallc(x, y):v = .93 + .05 * (y / y0) + .05 - .1 * abs(x - lsx) / W + .03 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5)if _wflat:v = _wflat(y, y0) + .01v -= .08 * max(0, 1 - (y0 - y) / (H * .05))return scale(wall, k * v)cv.rows(0, y0, wallc)300 unmodified linesfrom .shading import _hashdef _wt(cv):"""rule (night pixel round 3, flatwall): pixel-art walls are flat paint - the faint fbm paint texture posterisedinto big grey cloud smudges on the back wall (critic P3)"""if getattr(cv, "ss", 2) == 1:from .atmos import onif on("flatwall"):return 0.0return 1.0def _wall_steps(cv):"""rule (night pixel2 round 1, wallsteps): in pixel art the wall's light falls in flat horizontal steps (a darkerceiling band, then plain paint). The smooth window glow (x) plus height gradient (y) had diagonal iso-lines thatthe palette snapped into big pastel pyramids and grey diagonal wedges on bedroom / living-room walls."""if getattr(cv, "ss", 2) == 1:from .atmos import onif on("flatwall") and on("wallsteps"):return lambda y, y0: .9 if y < y0 * .07 else .96return Nonedef _floor_far(cv):"""rule (night pixel2, floorfar): in pixel art, plank seams converging toward the back wall turned the far floorinto a band of streak noise; planks narrower than ~5 px on screen are drawn as plain floor"""if getattr(cv, "ss", 2) == 1:from .atmos import onif on("floorfar"):return 8.0 * cv.h / 192.0return 0.0def _has(scene, *names):"""True when the prompt names one of these things itself (then the background must not add more of them)."""for e in scene.get("entities", []):102 unmodified lines_rect(cv, x - 4 * u, yb - .2 * u, x + 4 * u, yb + .8 * u, (255, 236, 186))def _aurora2(cv, ctx, rng, strength=1.0, scene=None):"""rule (night pixel round 3, aurora2): an aurora is 2 curtains hanging from the sky: a bright green lower hem ona slow wave, vertical rays rising from it in 2-3 px groups of different height, fading in 3 flat steps fromgreen to teal to violet at the top. Painted only on sky pixels (hills, trees and clouds stay in front)."""W, H, y0 = cv.w, cv.h, ctx.y0u = H / 128.0steps = ((.28, (160, 255, 190), .92), (.62, (70, 225, 165), .62), (1.0, (160, 100, 240), .38))for kk in range(2):hem = y0 * (.5 + .16 * kk) if kk == 0 else y0 * .36ph, f1 = rng.uniform(0, 6), rng.uniform(3.5, 6)x0, x1 = (0, W) if kk == 0 else (int(W * rng.uniform(.0, .3)), int(W * rng.uniform(.6, 1.0)))k = strength * (1.0 if kk == 0 else .7)x = x0while x < x1:g = rng.choice((2, 2, 3))ln = y0 * rng.uniform(.18, .34) * (.6 + .4 * abs(math.sin(x / W * 7 + ph)))for xx in range(x, min(x1, x + g)):yb = hem + math.sin(xx / W * f1 + ph) * H * .06 + math.sin(xx / W * 15 + ph * 2) * H * .012# fade at the curtain's endse = min(1.0, (xx - x0) / (W * .12) + .2, (x1 - xx) / (W * .12) + .2)prev = ybfor frac, col, a in steps:yt = yb - ln * fracfor yy in range(max(0, int(yt)), min(int(y0), int(prev) + 1)):p = cv.px[yy][xx]ref = sky_at(scene, yy, y0)if abs(p[0] - ref[0]) + abs(p[1] - ref[1]) + abs(p[2] - ref[2]) > 60 and sum(p) < 600:continue # not sky (hill, tree, cloud): stays in frontaa = min(1.0, a * k * e)p[0] += (col[0] - p[0]) * aa; p[1] += (col[1] - p[1]) * aa; p[2] += (col[2] - p[2]) * aaprev = ytx += gdef _aurora(cv, ctx, rng, strength=1.0, scene=None):"""rule: aurora = curtains of vertical light from a wavy top edge, bright at the top and fading downward,green with a violet fringe; shimmer comes from per-column brightness."""W, H, y0 = cv.w, cv.h, ctx.y0from .atmos import on as _aonif cv.ss == 1 and scene is not None and _aon("aurora2"):return _aurora2(cv, ctx, rng, strength, scene)for kk, (col, a0) in enumerate((((90, 240, 160), .55 * strength), ((150, 120, 240), .3 * strength))):base = y0 * (.18 + .14 * kk)ph = rng.uniform(0, 6)42 unmodified linesg += q if q > 0 else 0return gcv.rows(0, y0, lambda x, y: scale(wall, k * (.84 + (.2 if night else .1) * glow(x, y) + .05 * y / y0+ .03 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 17) - .5))))wy0 = y0 * .62panel = (96, 62, 42)pw = W * .125139 unmodified linesctx.haze_color = (210, 210, 195)wall = rng.choice([(236, 230, 206), (206, 222, 200), (214, 222, 232)])sun_r = ctx.sun[0] > W / 2cv.rows(0, y0, lambda x, y: scale(wall, k * (.95 + .04 * y / y0 + .02 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 31) - .5))))cv.rows(y0 * .7, y0, lambda x, y: scale(mix(wall, (120, 150, 150), .35), k))# rule: classroom = a big green chalkboard (wood frame, chalk tray, faint erased smudges, never any writing),# tall windows on the sun side, and a row of small desks along the back wall449 unmodified linesu = H / 128.0hz = ctx.haze_colorif scene["time"] == "night" and "aurora" not in scene.get("features", []):_aurora(cv, ctx, rng, .7, scene) # rule: a polar night sky carries a faint aurorasd = 1 if ctx.sun[0] < W / 2 else -1 # +1: right faces in shade# rule: arctic = flat-topped tabular icebergs and a glacier wall with sheer blue-shaded faces, a dark open-water# lead with floes, then flat blue-white sea ice with pressure ridges and cracks (no trees, no falling snow:553 unmodified linesreturn ri <= d <= ro and y < y0cv.fill(inside, (cx - ro, y0 - ro, cx + ro, y0), c, .55)if "aurora" in fs:_aurora(cv, ctx, rng, scene=scene)if "meteor" in fs:x, y = W * .7, y0 * .15cv.capsule(x, y, x - W * .3, y + y0 * .2, .8 * u, (255, 250, 220), alpha=.7)5 unmodified linesfor a in range(14):ang = a * math.pi * 2 / 14cv.capsule(cx, cy, cx + math.cos(ang) * 8 * u, cy + math.sin(ang) * 8 * u, .45 * u, col, alpha=.85)from . import atmos as _atmif _atm.on("thunder") and _atm.toks(scene) & {"thunderstorm", "thunder", "thunderstorms"} and "lightning" not in fs \and scene["place"] not in INDOOR | {"space", "underwater"}:fs = list(fs) + ["lightning"] # rule (night pixel round 3): a thunderstorm shows its (simulated) lightningfrom .physics2 import draw_boltdraw_bolt(cv, ctx, scene, rng, W, y0, u)trace.append("scene: thunderstorm -> lightning bolt")elif "lightning" in fs and "lightning" in (scene.get("sim_fx") or []):from .physics2 import draw_bolt # wave 12: dielectric-breakdown lightningdraw_bolt(cv, ctx, scene, rng, W, y0, u)elif "lightning" in fs:22 unmodified lines# rule: a river has a pale sandy bank edge on both sides and mirrors the sky coloursbank = [(x - u * (1 + 2 * (y - y0) / (H - y0)), y) for x, y in pts_l] + [(x + u * (1 + 2 * (y - y0) / (H - y0)), y) for x, y in pts_r[::-1]]cv.poly(bank, L.ground((196, 180, 136)))wf, wn = water_colors(scene)if scene.get("_frozen") and getattr(cv, "ss", 2) == 1:# rule (night pixel2, frozen): a frozen river is ice - pale blue-white, a few pale skate streaks, no glintscv.poly(bank, L.ground((236, 240, 248)))cv.poly(pts_l + pts_r[::-1], lambda x, y: L.ground(mix((214, 230, 242), (168, 198, 222), (y - y0) / (H - y0))))for _ in range(10):t = rng.uniform(.2, 1)yy = y0 + (H - y0) * tcx = W * (.5 + .22 * math.sin(t * 3.2 + 1))cv.capsule(cx - W * .06 * t, yy, cx + W * .06 * t, yy + u * .5, .3 * u, (240, 248, 255), alpha=.8)fs = [f for f in fs if f != "river"]if "river" in fs and scene["place"] in ("field", "forest", "mountains", "savanna", "snow", "desert", "farm", "park", "jungle"):wf, wn = water_colors(scene)cv.poly(pts_l + pts_r[::-1], lambda x, y: L.ground(mix(mix(wf, (70, 130, 180), .3), wn, (y - y0) / (H - y0))))for _ in range(22):18 unmodified linesdef weather(cv, ctx, scene, rng, trace):W, H = cv.w, cv.hu = H / 128from . import atmos # night pixel round 3: light + atmosphere passes (pixel renderer only; knob atmos=0)st = atmos.pre(cv, ctx, scene, rng, trace)kinds = set()if st is not None:if scene.get("weather") == "rain" and atmos.on("rain2"):kinds.add("rain")if scene.get("weather") == "fog" and atmos.on("fog2"):kinds.add("fog")if atmos.toks(scene) & atmos.WINDY and scene.get("weather") is None and scene["place"] not in INDOOR and atmos.on("wind"):kinds.add("wind")if (scene["place"] == "snow" and not _sunny(scene)) or scene.get("weather") == "snow":for _ in range(int(W * H / (500 * u * u))):r = rng.choice([.5, .6, .8, 1.0]) * ucv.ellipse(rng.uniform(0, W), rng.uniform(0, H), r, r, (255, 255, 255), alpha=rng.uniform(.5, .9))trace.append("scene: falling snow")if scene["place"] in INDOOR and cv.ss == 1 and atmos.on("indoorrain"):kinds.discard("rain")if scene.get("weather") == "rain":trace.append("scene: rain stays outside (indoors)") # rule (night pixel round 3): no rain in the living roomif scene.get("weather") == "rain" and "rain" not in kinds and not (scene["place"] in INDOOR and cv.ss == 1 and atmos.on("indoorrain")):for _ in range(int(W * H / (250 * u * u))):x, y = rng.uniform(0, W), rng.uniform(0, H)cv.capsule(x, y, x - 1.2 * u, y + 4 * u, .3 * u, (200, 210, 230), alpha=.45)trace.append("scene: rain streaks")if scene.get("weather") == "fog" and "fog" not in kinds:y0 = ctx.y0for y in range(H):a = max(0, .55 - abs(y - y0) / H * 1.2)3 unmodified linesfor i in range(3):p[i] += (215 - p[i]) * atrace.append("scene: fog band at the horizon")if st is not None and atmos.on("blizzard") and atmos.toks(scene) & {"blizzard", "blizzards", "snowstorm", "whiteout"} \and scene["place"] not in INDOOR:kinds.add("blizzard")if kinds:atmos.post(cv, ctx, scene, rng, trace, st, kinds)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400"""Staging (night round 1, scene lane): a picture with two or three subjects tells a little story through where theystand, how big they are and who looks at whom.
watching "a cat watching a bird on a fence", "a dog looking at a butterfly", "a fox staring at a rabbit": the watcher is in the foreground on one third, big, turned toward what it watches; the watched thing (and what it sits on) is further back on the other third - an over-the-shoulder shot, not a row of specimens. facing "a knight facing a dragon", "a fox confronting a badger": both on the ground on opposite thirds, facing each other (a flying creature that is faced comes down to face its opponent). feeding "an old man feeding pigeons", "a girl feeding ducks": the fed animals stand on the ground around the feeder's feet, a few in front, all turned to the feeder (not flying overhead).pre(scene, trace) runs before the layout builds instances; post(...) after it. Knob: PYDRAW_EXP stage=0.rule: keyed on verbs + concept facts (animate, flying, size), never on prompt lists."""import osimport re
from .registry import CONCEPTS
_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)
WATCH = {"watching", "watches", "watch", "looking at", "looks at", "staring at", "stares at", "gazing at", "gazes at", "observing", "observes", "eyeing", "eyes", "admiring", "admires", "peeking at", "peeks at", "spying on", "stalking", "stalks", "glaring at", "peering at", "looking up at", "looking down at", "watching over"}FACE = {"facing", "faces", "confronting", "confronts", "challenging", "challenges", "fighting", "fights", "battling", "battles", "attacking", "attacks", "dueling", "duelling", "squaring off with", "standing up to"}FEED = {"feeding", "feeds", "feed"}
def enabled(): return _EXP.get("stage", "1") != "0"
def _animate(concept): c = CONCEPTS.get(concept, {}) return bool(c.get("animal")) or concept == "person" or (c.get("open_vocab") or {}).get("family") in ("creature", "animal")
def _word_pos(text, e): for w in ((e.get("word") or e["concept"]).split()[-1], e["concept"].split()[-1]): m = re.search(r"\b%s(?:e?s)?\b" % re.escape(w.rstrip("s")), text) if m: return m.start(), m.end() return None
def pre(scene, trace): """'X facing Y' between two animate things -> X turned toward Y (the parser keeps no relation for 'facing')""" if not enabled(): return ents = scene["entities"] text = (scene.get("text") or "").lower() if scene.get("place") == "beach" and ents and all(CONCEPTS.get(e["concept"], {}).get("setting") in ("water", "underwater") for e in ents) \ and not re.search(r"\b(beach|shore|sand|sandy|coast|seaside|dunes?|surf|waves? crashing)\b", text): # rule: a ship "at sea" / "on the ocean" is out on open water, not parked on the sand of a beach scene["place"] = "water" trace.append("stage: only boats / sea things and no shore word -> open water") for e in ents: # rule: "a family of snowmen / ducks" = two grown-ups and smaller young, not identical clones w = (e.get("word") or e["concept"]).split()[-1] if e.get("count", 1) > 1 and re.search(r"\bfamily of\s+(?:\w+\s+)?%s\b" % re.escape(w), text): e["family"] = True trace.append("stage: a family of %s -> mixed sizes" % w) if scene.get("place") == "table": # rule: "a cozy kitchen ... with bread on the counter" is the KITCHEN (a room with a table), not a tabletop close-up m = re.search(r"\b(kitchen|bedroom|bathroom|classroom|office|library|garage|cafe|restaurant|living room|dining room)\b", text) if m: rm = {"living room": "room", "dining room": "room"}.get(m.group(1), m.group(1)) from .layout import ROOMS if rm in ROOMS: scene["place"] = rm trace.append("stage: '%s' named -> the room, not a tabletop close-up" % m.group(1)) for e in ents: # rule: "a field of sunflowers / tulips / lavender" = rows of them receding to the horizon, not two big ones c = CONCEPTS.get(e["concept"], {}) w = (e.get("word") or e["concept"]).split()[-1] if not c.get("animal") and c.get("height", 9) <= 3.5 and c.get("setting") in ("field", "garden", "farm", "table") and \ re.search(r"\b(?:field|fields|meadow|sea|carpet|rows|row)\s+of\s+(?:\w+\s+){0,2}%s\b" % re.escape(w), text) and not e.get("count_explicit"): e["count"] = 21 e["field_of"] = True trace.append("stage: a field of %s -> rows receding to the horizon" % w) if len(ents) < 2: return related = {(s, o) for s, r, o in scene["relations"]} | {(o, s) for s, r, o in scene["relations"]} for i in range(len(ents) - 1): j = i + 1 if (i, j) in related or not (_animate(ents[i]["concept"]) and _animate(ents[j]["concept"])): continue a, b = _word_pos(text, ents[i]), _word_pos(text, ents[j]) if not a or not b or b[0] <= a[1]: continue between = text[a[1]:b[0]] verb = next((v for v in sorted(FACE, key=len, reverse=True) if re.search(r"\b%s\b" % v, between)), None) if verb: scene["relations"].append((i, "toward", j)) scene.setdefault("actions", []).append({"subject": i, "verb": verb, "object": j}) scene["arrange"] = scene.get("arrange") or "facing" trace.append("stage: '%s' -> %s faces %s" % (verb, ents[i]["concept"], ents[j]["concept"]))
def post(insts, scene, W, H, y0, trace): if not enabled(): return _sky_bodies(insts, W, H, y0, trace) _air = re.search(r"\b(?:through|among|above|across|in|over)\s+the\s+(?:clouds|sky|air)\b", (scene.get("text") or "").lower()) if scene.get("place") == "sky" or (_air and _EXP.get("airborne", "1") != "0"): for it in insts: # rule: in a sky scene ("a whale swimming through the clouds") an unsupported subject is airborne, not on a lawn if it.pose != "flying" and getattr(it, "bound", None) is None and hasattr(it, "x") and it.ent == 0: it.pose = "flying" it.y = H * .5 + it.h * .5 if scene.get("place") == "sky" else min(H * .5 + it.h * .5, y0 - H * .03) it.x = W * .5 trace.append("stage: %s floats in the sky scene" % it.concept) _fields(insts, scene, W, H, y0, trace) _depth(insts, scene, W, H, y0, trace) _peek_behind(insts, scene, W, H, y0, trace) acts = scene.get("actions") or [] by_ent = {} for it in insts: by_ent.setdefault(it.ent, []).append(it) for act in acts: s, o, verb = act.get("subject"), act.get("object"), (act.get("verb") or "").lower() if not isinstance(s, int) or not isinstance(o, int) or s not in by_ent or o not in by_ent: continue S_, O_ = by_ent[s], by_ent[o] if verb in WATCH and len(S_) == 1 and s == 0: _watch(S_[0], O_, insts, W, H, y0, trace) elif verb in FACE and len(S_) == 1 and len(O_) == 1: _face(S_[0], O_[0], insts, W, H, y0, trace) elif verb in FEED and len(S_) == 1 and O_ and CONCEPTS.get(O_[0].concept, {}).get("animal") and O_[0].info.get("height", 9) < S_[0].info.get("height", 0): _feed(S_[0], O_, insts, W, H, y0, trace)
def _group(it, insts): """the thing plus what it stands on and what stands on it (moved together)""" root = it while getattr(root, "bound", None) is not None and root.rel == "on" and hasattr(root.bound, "x"): root = root.bound out = [root] for _ in range(3): for o in insts: if o not in out and getattr(o, "bound", None) in out and o.rel == "on" and hasattr(o, "x"): out.append(o) return root, out
def _watch(w, targets, insts, W, H, y0, trace): if not hasattr(w, "x") or getattr(w, "bound", None) is not None and w.rel == "on": return if any(getattr(t, "held_by", None) is not None for t in targets): return t0 = targets[0] root, grp = _group(t0, insts) if w in grp: return side = -1 if w.x <= root.x else 1 # the watcher keeps its side of the picture # rule: the watcher is close to the camera: big, its feet near the bottom edge, on its third k = max(1.0, min(6.0, H * .42 / max(1e-6, w.h))) w.h *= k w.w *= k w.y = max(min(H * .975, y0 + (w.y - y0) * k) if w.y > y0 + 1 else H * .97, H * .93) w.d = getattr(w, "d", 1.0) / k if getattr(w, "d", 0) else getattr(w, "d", 0) w.x = W * (.5 + side * .27) w.haze = 0.0 # the watched group goes to the other third, behind gx = W * (.5 - side * .2) dx = gx - root.x if root.pose == "flying" or t0.pose == "flying": dx = W * (.5 - side * .22) - t0.x for t in targets: t.x += dx t.y = min(t.y, w.y - w.h * .7) if t.h < H * .09: t.w *= H * .09 / t.h t.h = H * .09 else: for m in grp: m.x += dx for t in targets: if t not in grp: t.x += dx if root.y > w.y - H * .04: # rule: the watched thing stands further back than the watcher s = max(.55, (w.y - H * .06 - y0) / max(1e-6, root.y - y0)) for m in grp: m.y = y0 + (m.y - y0) * s m.h *= s m.w *= s m.x = gx + (m.x - gx) * s if getattr(m, "d", 0): m.d /= s # the watcher must not cover the watched: slide it toward its edge if they overlap tl, tr = min(m.x - m.w / 2 for m in [t0]), max(m.x + m.w / 2 for m in [t0]) if side < 0 and w.x + w.w * .35 > tl: w.x = max(w.w * .3, tl - w.w * .35) if side > 0 and w.x - w.w * .35 < tr: w.x = min(W - w.w * .3, tr + w.w * .35) w.facing = "right" if side < 0 else "left" w.stage_fg = True trace.append("stage: %s watches from the foreground (%s third), %s further back" % (w.concept, "left" if side < 0 else "right", t0.concept))
def _face(a, b, insts, W, H, y0, trace): if not hasattr(a, "x") or not hasattr(b, "x"): return if b.pose == "flying" and not getattr(b, "bound", None): # rule: a creature being faced comes down to the ground line of its opponent, at its own size b.pose = None b.y = a.y hb = max(b.h, a.h * min(2.2, max(.4, b.world_h / max(1e-6, a.world_h)))) b.w *= hb / b.h b.h = hb b.d = getattr(a, "d", 0) left, right = (a, b) if a.x <= b.x else (b, a) gap = W * .04 span = left.w + right.w + gap if span > W * .94: # rule: two opponents both fit the frame, side by side (scaled about the ground line) k = W * .94 / span for m in (left, right): m.h *= k m.w *= k m.y = y0 + (m.y - y0) * (k ** .5) if m.y > y0 else m.y span = left.w + right.w + gap if span < W * 1.02: c = W / 2 left.x = c - span / 2 + left.w / 2 right.x = c + span / 2 - right.w / 2 left.facing, right.facing = "right", "left" trace.append("stage: %s and %s face each other" % (a.concept, b.concept))
def _feed(f, birds, insts, W, H, y0, trace): if not hasattr(f, "x"): return side = 1 if f.x <= W / 2 else -1 n = len(birds) for j, b in enumerate(birds): if getattr(b, "bound", None) is not None and b.rel == "on": continue b.pose = None hb = min(max(f.h * .26, H * .07), f.h * .34) b.w *= hb / max(1e-6, b.h) b.h = hb # rule: they gather on the ground in a loose fan in front of / beside the feeder, all turned to the feeder u = (j + .5) / n b.x = f.x + side * (f.w * .55 + u * f.w * 1.6) + (-1) ** j * f.w * .08 b.y = f.y + (H - f.y) * (.12 + .5 * ((j * 37) % 7) / 7) b.y = min(b.y, H * .985) b.d = getattr(f, "d", 0) b.facing = "left" if b.x > f.x else "right" b.haze = 0.0 f.facing = "right" if side > 0 else "left" trace.append("stage: %d %s gather on the ground at the %s's feet" % (n, birds[0].concept, f.concept))
SKY_BODIES = {"full moon", "crescent moon", "moon", "planet", "sun"}
def _sky_bodies(insts, W, H, y0, trace): """rule: a moon / planet in the sky goes high in the corner the subject looks toward (a wolf howls up at it), never behind the subject's head where it hides""" bodies = [it for it in insts if it.concept in SKY_BODIES and hasattr(it, "x") and not any(getattr(o, "bound", None) is it for o in insts)] subs = [it for it in insts if it not in bodies and hasattr(it, "x") and it.pose != "flying"] if len(bodies) != 1 or not subs: return m = bodies[0] s0 = subs[0] side = 1 if s0.facing == "right" else -1 if abs(s0.x - W / 2) > W * .15: # an off-centre subject: the moon takes the open side side = 1 if s0.x < W / 2 else -1 m.h = max(m.h, H * .13) m.w = m.h * m.info["aspect"] m.x = W * (.5 + side * .3) top = min(o.y - o.h for o in subs) m.y = max(m.h + H * .04, min(H * .3, top - H * .02) if top - H * .02 > m.h + H * .04 else m.h + H * .04) m.bound = None m.rel = None m.pose = "flying" m.stack_top = False trace.append("stage: %s high in the %s corner of the sky" % (m.concept, "right" if side > 0 else "left"))
def _fields(insts, scene, W, H, y0, trace): """rows of a 'field of X' in perspective: a full front row big at the bottom edge, rows shrinking toward the horizon""" ents = scene["entities"] for ei, e in enumerate(ents): if not e.get("field_of"): continue its = [it for it in insts if it.ent == ei and hasattr(it, "x")] if len(its) < 6: continue rows = [(.985, 4), (.86, 5), (.76, 5), (.68, 7)] top_h = H * .3 yb = H * .985 others = [it for it in insts if it.ent != ei and hasattr(it, "x") and it.pose != "flying" and (getattr(it, "bound", None) is None or getattr(it.bound, "ent", None) == ei)] if others: # rule: someone standing in the field is in front of it: the field starts a row back, the figure is big rows = [(.88, 5), (.78, 5), (.7, 6), (.64, 5)] for o in others[:1]: kk = max(1.0, H * .45 / max(1e-6, o.h)) o.h *= kk o.w *= kk o.y = H * .975 o.x = W * .5 o.d = .5 o.bound = o.rel = None o.haze = 0.0 k = 0 for r, (fy, n) in enumerate(rows): y = y0 + (H - y0) * (fy - (1 - (H * .985 - y0) / max(1.0, H - y0)) * 0) if False else y0 + (yb - y0) * ((fy - .6) / .385) ** 1.6 for j in range(n): if k >= len(its): break it = its[k] k += 1 sc = max(.08, (y - y0) / max(1.0, yb - y0)) asp = it.w / max(1e-6, it.h) it.h = max(3.0, top_h * sc) it.w = it.h * asp it.x = W * (j + .5 + (.5 if r % 2 else 0) * .9) / n + it.rng.uniform(-.04, .04) * W it.y = y + it.rng.uniform(-.01, .01) * H * sc it.d = 1.0 / max(1e-3, sc) it.bound, it.rel, it.pose = None, None, None it.haze = .35 * (1 - sc) for it in its[k:]: # extras: hidden in the far haze line it.h = it.w = 0.5 it.y = y0 + 1 trace.append("stage: field of %s in %d receding rows" % (e.get("word"), len(rows)))
def _depth(insts, scene, W, H, y0, trace): """rule (knob depth=0): two or three companions with nothing tying them ("a fox and a rabbit in a meadow", "a cow, a pig and a sheep") stand in a shallow diagonal / arc instead of a flat specimen row: the subject (first named) keeps the front, the next ones step back a little (smaller, higher on the ground, a touch of haze). No overlap is created: x stays, so prompts that ask for counts or sides read the same.""" if _EXP.get("depth", "1") == "0" or scene.get("arrange") or scene.get("place") in ("sky", "space", "underwater", "studio"): return if any(r in ("left_of", "right_of", "behind", "in_front_of", "above", "below", "under") for _, r, _o in scene["relations"]): return ground = [it for it in insts if hasattr(it, "x") and it.pose != "flying" and getattr(it, "bound", None) is None and not getattr(it, "attach_kind", None) and not getattr(it, "stage_fg", False) and not getattr(it, "implicit", False)] ents = {it.ent for it in ground} if not 2 <= len(ground) <= 3 or len(ents) != len(ground) or len(insts) != len(ground) + sum( 1 for it in insts if getattr(it, "bound", None) in ground): return if any(not (CONCEPTS.get(it.concept, {}).get("animal") or it.concept == "person") for it in ground): return if any(e.get("field_of") or e.get("family") for e in scene["entities"]): return if any(it.y <= y0 + 2 for it in ground): return order = sorted(ground, key=lambda it: it.ent) steps = [1.0, .84, .88] if len(order) == 3 else [1.0, .84] if len(order) == 3: # an arc: the middle one (by x) steps back, the outer two stay near mid = sorted(order, key=lambda it: it.x)[1] steps = [1.0 if it is not mid else .84 for it in order] for it, k in zip(order, steps): if k >= 1.0: continue movers = [it] + [o for o in insts if getattr(o, "bound", None) is it] for m in movers: m.y = y0 + (m.y - y0) * k m.h *= k m.w *= k if getattr(m, "d", 0): m.d /= k m.haze = min(.5, getattr(m, "haze", 0) + .06) trace.append("stage: %d companions staggered in depth (%s)" % (len(order), "arc" if len(order) == 3 else "diagonal"))
def _peek_behind(insts, scene, W, H, y0, trace): """rule: "a fox peeking out from behind a tree", "a clown peeking from behind a tree", "a child hiding behind a curtain": the peeker stands just behind the cover, at its edge, half of it hidden, turned out toward the open side""" text = (scene.get("text") or "").lower() m = re.search(r"\b(peek\w*|peer\w*|peep\w*|hid\w*|lurk\w*|spy\w*|watch\w*|look\w*)\s+(?:out\s+)?(?:from\s+)?behind\s+(?:a|an|the|some)?\s*", text) if not m: return ents = scene["entities"] before = [i for i, e in enumerate(ents) if _word_pos(text, e) and _word_pos(text, e)[0] < m.start()] after = [i for i, e in enumerate(ents) if _word_pos(text, e) and _word_pos(text, e)[0] >= m.end() - 1] if not before or not after: return S_ = [it for it in insts if it.ent == before[-1] and hasattr(it, "x")] C_ = [it for it in insts if it.ent == min(after, key=lambda i: _word_pos(text, ents[i])[0]) and hasattr(it, "x")] if len(S_) != 1 or not C_ or S_[0].pose == "flying" or C_[0].pose == "flying": return p, c = S_[0], C_[0] if not (CONCEPTS.get(p.concept, {}).get("animal") or p.concept == "person"): return side = 1 if c.x <= W / 2 else -1 # peek out toward the wider open side of the picture p.bound, p.rel = None, None p.x = c.x + side * (c.w * .5 - p.w * .1) # about half the peeker shows past the cover's edge p.y = c.y - max(1.0, H * .006) # a hair behind the cover's base line: drawn first if p.h > c.h * .95: k = c.h * .95 / p.h p.h *= k p.w *= k if getattr(c, "d", 0): p.d = c.d * 1.02 p.facing = "right" if side > 0 else "left" p.haze = getattr(c, "haze", 0) trace.append("stage: %s peeks out from behind the %s (%s edge)" % (p.concept, c.concept, "right" if side > 0 else "left"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Surface states (night round 1, scene lane): "a frog on a cracked rock", "a cracked old vase", "a wall with cracks".
The parser leaves state adjectives like "cracked" unknown; this pass (run at the start of the layout, so bothrenderers see it) marks the entity: entity["surface"] = "cracked". Pixel: a few branching crack lines drawn inside theobject's own pixels (dark line + a lit lip pixel), kept through the pixel finish. 3D: pydraw3d/attach.py crack_partswraps the model's textures with a Worley crack network (dark fissures, lighter edges) in model space.Knob: PYDRAW_EXP surface=0. rule: keyed on the word right before / after the noun, never on prompt lists."""import mathimport osimport randomimport re
_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)
CRACK_WORDS = {"cracked", "cracking", "crackled", "fissured", "crazed", "broken-up", "split"}WITH_CRACKS = r"\bwith\s+(?:a\s+|deep\s+|many\s+|big\s+|long\s+|fine\s+)*(?:cracks?|fissures?)\b"
def enabled(): return _EXP.get("surface", "1") != "0"
def mark(scene, trace): if not enabled(): return text = (scene.get("text") or "").lower() toks = re.findall(r"[a-z]+(?:-[a-z]+)?", text) for e in scene["entities"]: if e.get("surface"): continue w = (e.get("word") or e["concept"]).split()[-1].rstrip("s") cands = [e["concept"].split()[-1].rstrip("s"), w] idx = [i for i, t in enumerate(toks) if t.rstrip("s") in cands] if not idx: continue i = idx[0] before = toks[max(0, i - 3):i] hit = any(t in CRACK_WORDS for t in before) and not any(t in ("on", "in", "with", "and", "under", "by", "near") for t in before[[k for k, t in enumerate(before) if t in CRACK_WORDS][-1]:]) after = " ".join(toks[i:i + 6]) if hit or re.search(r"^\S+\s+" + WITH_CRACKS[2:], after): e["surface"] = "cracked" trace.append("surface: %s is cracked" % (e.get("word") or e["concept"])) scene["unknown"] = [u for u in scene.get("unknown", []) if u not in CRACK_WORDS]
def draw_cracks(cv, ctx, it, oid): """pixel: branching cracks inside the object's pixels""" W, H = cv.w, cv.h x0, x1 = int(max(0, it.x - it.w / 2)), int(min(W - 1, it.x + it.w / 2)) y0, y1 = int(max(0, it.y - it.h)), int(min(H - 1, it.y)) ids = cv.ids pts = [(x, y) for y in range(y0, y1 + 1) for x in range(x0, x1 + 1) if ids[y][x] == oid] if len(pts) < 30: return rng = random.Random(int(it.x * 7 + it.y * 13) + 5) lx = 1 if ctx.L.d[0] >= 0 else -1 # the object's typical colour -> crack ink (deep shade) and lip (lighter) cs = [cv.px[y][x] for x, y in pts[::max(1, len(pts) // 200)]] mc = [sorted(c[i] for c in cs)[len(cs) // 2] for i in range(3)] ink = (mc[0] * .32 + 6, mc[1] * .3 + 6, mc[2] * .34 + 12) lip = tuple(min(255, v * 1.22 + 18) for v in mc) keep = getattr(cv, "tex_keep", None) if keep is None: keep = cv.tex_keep = set() marks = set() size = max(it.w, it.h) n_main = 2 if size < 60 else 3
def put(x, y, c): x, y = int(round(x)), int(round(y)) if 0 <= x < W and 0 <= y < H and ids[y][x] == oid: p = cv.px[y][x] p[0], p[1], p[2] = c keep.add((y, x)) return True return False
def walk(x, y, ang, length, depth): step = 1.0 n = int(length) for k in range(n): ang += rng.uniform(-.55, .55) x += math.cos(ang) * step y += math.sin(ang) * step if not put(x, y, ink): return marks.add((int(round(x)), int(round(y)))) if depth < 2 and k > 2 and rng.random() < .09: walk(x, y, ang + rng.choice((-1, 1)) * rng.uniform(.6, 1.1), length * rng.uniform(.3, .5), depth + 1) tops = sorted(pts, key=lambda p: p[1])[: max(5, len(pts) // 6)] # cracks start near the top edge (where they open) for j in range(n_main): sx, sy = tops[rng.randrange(len(tops))] ang = math.pi / 2 + rng.uniform(-.7, .7) walk(sx, sy, ang, size * rng.uniform(.35, .6), 0) # rule: the lit lip - one pixel beside each crack on the side away from the light catches it for x, y in marks: xx = x - lx if (xx, y) not in marks and 0 <= xx < W and 0 <= y < H and ids[y][xx] == oid: put(xx, y, lip)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""Tethers (language shift 3): "a boat tied to a dock with a rope", "a goat tied to a fence post", "a dog on a leashtied to a lamppost". The parse (pydraw/language.py _tethers) drops the rope / leash / chain entity and marks the tiedthing with attrs["tether"] = {"to": entity index, "kind": rope | leash | chain | string}; here the line is drawn as aslack curve from the tied thing (an animal's collar, a boat's bow) to the post / dock it is tied to.Knob: PYDRAW_LANG_OFF=tether (the parse rule; nothing is marked, nothing drawn).rule: anchors come from concept facts (animal or not, the box of each placed thing), never from prompt lists."""from .registry import CONCEPTS
COLORS = {"rope": (205, 172, 118), "leash": (170, 40, 40), "chain": (96, 98, 106), "string": (225, 222, 210)}DECK = {"marina": .27} # anchor height (fraction of the box height, from the top) on structures with a deck
def pairs(insts): """[(tied inst, host inst, kind)] for every tether mark with both ends placed""" out = [] for it in insts: t = (getattr(it, "attrs", None) or {}).get("tether") if not t or getattr(it, "k", 0) != 0: continue host = next((o for o in insts if getattr(o, "ent", None) == t["to"] and getattr(o, "k", 0) == 0), None) if host is not None: out.append((it, host, t.get("kind", "rope"))) return out
def anchors(a, b): """screen-space ends of the line: (xa, ya, xb, yb). a = the tied thing, b = what it is tied to.""" side = 1 if b.x >= a.x else -1 if CONCEPTS.get(a.concept, {}).get("flying") and not CONCEPTS.get(a.concept, {}).get("animal"): xa, ya = a.x, a.y - a.h * .03 # a hot air balloon / airship: the line hangs from its basket / gondola elif CONCEPTS.get(a.concept, {}).get("animal"): # the collar: just behind the head, on the side the animal faces f = 1 if getattr(a, "facing", None) == "right" else -1 if getattr(a, "facing", None) == "left" else side xa, ya = a.x + f * a.w * .3, a.y - a.h * .7 else: # a boat's bow / a cart's front: the side facing the host, a little above half height # (a boat's box holds its mast: the bow cleat sits low, on the hull) low = CONCEPTS.get(a.concept, {}).get("setting") == "water" xa, ya = a.x + side * a.w * (.36 if low else .42), a.y - a.h * (.2 if low else .45) top, bot = b.y - b.h * .92, b.y - b.h * .12 if b.concept in DECK: yb = b.y - b.h * DECK[b.concept] else: yb = min(bot, max(top, ya - a.h * .1)) # the knot sits about as high as the tied end, inside the post's box half = b.w * (.08 if b.w < b.h * .4 else .42) xb = min(b.x + half, max(b.x - half, xa)) if abs(xb - xa) < 1e-3 and abs(yb - ya) < 1e-3: xb += side return xa, ya, xb, yb
def spread(insts, W, trace): """before drawing: a tied animal / boat standing right against its post / pier steps back a little, so the line between them shows (the side-by-side layout packs them touching)""" for a, b, kind in pairs(insts): if getattr(a, "rel", None) == "on" or getattr(b, "rel", None) == "on": continue side = 1 if a.x >= b.x else -1 gap = abs(a.x - b.x) - (a.w + b.w) / 2 want = max(a.w, a.h) * .35 if gap < want: nx = a.x + side * (want - gap) nx = min(W - a.w * .45, max(a.w * .45, nx)) if abs(nx - a.x) > .5: trace.append("tether: the %s steps back from the %s so the %s shows" % (a.concept, b.concept, kind)) a.x = nx
def draw_px(cv, ctx, insts, trace): for a, b, kind in pairs(insts): xa, ya, xb, yb = anchors(a, b) span = ((xb - xa) ** 2 + (yb - ya) ** 2) ** .5 sag = span * (.12 if kind != "chain" else .08) col = COLORS.get(kind, COLORS["rope"]) w = max(.7, min(a.h, b.h) * .02) pts = [] for i in range(13): t = i / 12 pts.append((xa + (xb - xa) * t, ya + (yb - ya) * t + sag * 4 * t * (1 - t))) cv.cur_id = getattr(a, "_oid", None) # the line belongs to the tied thing (background passes leave it alone) dark = tuple(int(c * .55) for c in col) for (x0, y0), (x1, y1) in zip(pts, pts[1:]): # a dark edge round a lighter core: reads on wood and grass cv.capsule(x0, y0, x1, y1, w + .45, dark) for (x0, y0), (x1, y1) in zip(pts, pts[1:]): cv.capsule(x0, y0, x1, y1, w * .6, col) # the knot / ring at the host end cv.capsule(xb - w * .8, yb, xb + w * .8, yb, w * 1.4, tuple(int(c * .7) for c in col)) cv.cur_id = None trace.append("tether: a %s from the %s to the %s" % (kind, a.concept, b.concept))
def _surface_pt(o, toward_x, frac): """3D: the first point on o's surface at height frac (of its scale), probing in from the side facing toward_x""" import numpy as np side = 1.0 if toward_x >= o.base[0] else -1.0 ts = np.linspace(o.radius, 0.0, 120) P = np.stack([o.base[0] + side * ts, np.full_like(ts, o.base[1] + frac * o.scale), np.full_like(ts, o.base[2])], -1) try: d = o.dist(P) except Exception: return None hit = np.nonzero(d < .01 * o.scale)[0] return P[hit[0]] if len(hit) else None
def build3d(objs, Obj, trace): """3D: the same tethers as slack lines between the placed objects (pydraw3d/interact.extras calls this)""" import numpy as np from pydraw3d.models import Part from pydraw3d.interact import _line, _anchor, world_pt by_ent = {} for o in objs: if getattr(o, "inst", None) is not None and getattr(o.inst, "k", 0) == 0: by_ent.setdefault(getattr(o.inst, "ent", None), o) out = [] for o in objs: it = getattr(o, "inst", None) t = (getattr(it, "attrs", None) or {}).get("tether") if it is not None else None if not t or getattr(it, "k", 0) != 0 or t["to"] not in by_ent: continue h = by_ent[t["to"]] p0 = None if CONCEPTS.get(o.name, {}).get("flying") and not CONCEPTS.get(o.name, {}).get("animal"): p0 = o.base + np.array([0, o.scale * .03, 0]) elif CONCEPTS.get(o.name, {}).get("animal"): _, an = _anchor(o, "collar", "head") if an is not None: p0 = world_pt(o, an) - np.array([0, o.scale * .2, 0]) else: asp = float(CONCEPTS.get(o.name, {}).get("aspect", 1.5)) p0 = world_pt(o, (asp * .3, .62, 0.0)) else: low = CONCEPTS.get(o.name, {}).get("setting") == "water" p0 = _surface_pt(o, h.base[0], .2 if low else .45) if p0 is None: continue frac = .73 if h.name == "marina" else min(.85, max(.15, (p0[1] - h.base[1]) / max(1e-6, h.scale))) p1 = _surface_pt(h, p0[0], frac) if p1 is None: continue kind = t.get("kind", "rope") out += _line(np.asarray(p0, float), np.asarray(p1, float), .12 if kind != "chain" else .08, max(.012, min(o.scale, h.scale) * .012), COLORS.get(kind, COLORS["rope"]), Part, Obj) trace.append("3d: a %s ties the %s to the %s" % (kind, o.name, h.name)) return out259 unmodified lines260261262263264265266259 unmodified linespw = max(1.2, w * .045)bt, bb = y - h, y - h * .42# rule: a standalone sign = a board on two posts; the board is the top 58% (writing surface + frame)for px_ in (x - w * .32, x + w * .32):cv.poly([(px_ - pw, bt + h * .1), (px_ + pw, bt + h * .1), (px_ + pw, y), (px_ - pw, y)], L.shade(post, -.3, 0, .9))fr = max(1.5, w * .045)cv.poly(rrect(x - w * .5, bt, x + w * .5, bb, w * .03), L.shade(scale(c, .62), 0, 0, 1))259 unmodified lines260261262263264265266259 unmodified linespw = max(1.2, w * .045)bt, bb = y - h, y - h * .42# rule: a standalone sign = a board on two posts; the board is the top 58% (writing surface + frame)for px_ in (x - w * .32, x + w * .32) if not getattr(it, "mounted", False) else (): # (night: a mounted sign has no posts)cv.poly([(px_ - pw, bt + h * .1), (px_ + pw, bt + h * .1), (px_ + pw, y), (px_ - pw, y)], L.shade(post, -.3, 0, .9))fr = max(1.5, w * .045)cv.poly(rrect(x - w * .5, bt, x + w * .5, bb, w * .03), L.shade(scale(c, .62), 0, 0, 1))
93 unmodified lines949596979899100101102103104105106107108160 unmodified lines26927027127227327493 unmodified linesfx = (s - self.gx[0]) / (self.gx[-1] - self.gx[0]) * (len(self.gx) - 1)fy = (t - self.gy[0]) / (self.gy[-1] - self.gy[0]) * (len(self.gy) - 1)out = (fx < 0) | (fy < 0) | (fx > len(self.gx) - 1) | (fy > len(self.gy) - 1)fx = np.clip(fx, 0, len(self.gx) - 1.001)fy = np.clip(fy, 0, len(self.gy) - 1.001)ix, iy = fx.astype(int), fy.astype(int)ax, ay = fx - ix, fy - iyif arr == "ang":v = A[np.round(fy).astype(int), np.round(fx).astype(int)]else:v = (A[iy, ix] * (1 - ax) * (1 - ay) + A[iy, ix + 1] * ax * (1 - ay) + A[iy + 1, ix] * (1 - ax) * ay+ A[iy + 1, ix + 1] * ax * ay)if arr in ("sd", "cd"):# rule: outside the sampled band the field is at least the band margin away (keeps the SDF conservative)dxo = np.maximum(np.maximum(self.gx[0] - s, s - self.gx[-1]), 0)160 unmodified linesparts = [board,Part(lambda p: S.rbox(p, V(-hw * .62, .45, .03), (.035, .45, .03), .01), post, tex="wood"),Part(lambda p: S.rbox(p, V(hw * .62, .45, .03), (.035, .45, .03), .01), post, tex="wood")]fr = PlaneFrame(-hw + .06, hw - .06, .45, .95, zf)grid = TextGrid(spec, fr)if spec.get("material") not in ("carved", "engraved"):93 unmodified lines949596979899100101102103104105106107108160 unmodified lines26927027127227327427527693 unmodified linesfx = (s - self.gx[0]) / (self.gx[-1] - self.gx[0]) * (len(self.gx) - 1)fy = (t - self.gy[0]) / (self.gy[-1] - self.gy[0]) * (len(self.gy) - 1)out = (fx < 0) | (fy < 0) | (fx > len(self.gx) - 1) | (fy > len(self.gy) - 1)if arr == "ang":fx = np.clip(fx, 0, len(self.gx) - 1.001)fy = np.clip(fy, 0, len(self.gy) - 1.001)v = A[np.round(fy).astype(int), np.round(fx).astype(int)]else:# (night render3d: the same clamped bilinear lookup as one traceable table read, so carriers of writing# compile to C with the rest of the scene; pydraw3d/sim/fields.lerp2)from pydraw3d.sim.fields import lerp2v = lerp2(A, fx, fy)if arr in ("sd", "cd"):# rule: outside the sampled band the field is at least the band margin away (keeps the SDF conservative)dxo = np.maximum(np.maximum(self.gx[0] - s, s - self.gx[-1]), 0)160 unmodified linesparts = [board,Part(lambda p: S.rbox(p, V(-hw * .62, .45, .03), (.035, .45, .03), .01), post, tex="wood"),Part(lambda p: S.rbox(p, V(hw * .62, .45, .03), (.035, .45, .03), .01), post, tex="wood")]if e.get("mounted"):parts = [board] # rule (night, pydraw/attach.py): a sign mounted on a building front has no postsfr = PlaneFrame(-hw + .06, hw - .06, .45, .95, zf)grid = TextGrid(spec, fr)if spec.get("material") not in ("carved", "engraved"):
80 unmodified lines81828384858642 unmodified lines12913013113213313450 unmodified lines18518618718818919023 unmodified lines21421521621721821922022122222322422580 unmodified linesr"lowercase|serif|sans|serif|gothic|retro|vintage|glowing|shiny|sparkly|bright|dark|light|" + "|".join(COLOR_WORDS) + r")"def _style_from(words, spec, colors=True):"""read writing-style words ("in red cursive letters", "handwritten", "in gold") into the spec"""w = " ".join(words).lower()42 unmodified linesbest = (ph[:-1], CARRIERS[ph[:-1]])breakif best:return bestif len(words) - i > 9:break50 unmodified linesi = m.start(1)def extract(text, trace=None):"""-> (text with writing removed, [spec]). spec: text, kind, noun, material, face, color, case, span"""specs = []23 unmodified linesrest = work[m.end():]toks = re.findall(r"[A-Za-z0-9'!?&$#%]+|[,.;:]", rest)words = []for t in toks:if t in ",.;:" or (t.lower() in STOP and words) or (t.lower() in ("a", "an", "the") and words):breakwords.append(t)if not words or (words[0].lower() in ("a", "an", "the") and len(words) == 1):continueif m.group(0).lower().strip().endswith(("the word", "with the word")):words = words[:1] # rule: "the word X" = one wordendpos = m.end() + len(" ".join(words))80 unmodified lines8182838485868788899091929342 unmodified lines13613713813914014114214314414514614714814950 unmodified lines20020120220320420520620720820921023 unmodified lines23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326480 unmodified linesr"lowercase|serif|sans|serif|gothic|retro|vintage|glowing|shiny|sparkly|bright|dark|light|" + "|".join(COLOR_WORDS) + r")"def _readact():"""night knob (PYDRAW_EXP readact=0 restores the old reading-as-writing rule)"""import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get("readact", "1") != "0"def _style_from(words, spec, colors=True):"""read writing-style words ("in red cursive letters", "handwritten", "in gold") into the spec"""w = " ".join(words).lower()42 unmodified linesbest = (ph[:-1], CARRIERS[ph[:-1]])breakif best:if best[1] == "generic" and _lang_on("carrier"):# night wave (language): "a sign above a door that says X" - a real carrier a little further back wins# over a generic surface right before the verbfor i2 in range(i - 1, max(-1, i - 7), -1):for n2 in (2, 1):ph2 = " ".join(words[max(0, i2 - n2 + 1):i2 + 1])if ph2 in CARRIERS and CARRIERS[ph2] != "generic":return (ph2, CARRIERS[ph2])return bestif len(words) - i > 9:break50 unmodified linesi = m.start(1)def _lang_on(rule):from ..language import onreturn on(rule)def extract(text, trace=None):"""-> (text with writing removed, [spec]). spec: text, kind, noun, material, face, color, case, span"""specs = []23 unmodified linesrest = work[m.end():]toks = re.findall(r"[A-Za-z0-9'!?&$#%]+|[,.;:]", rest)words = []caps = bool(toks) and toks[0].isupper() and len(toks[0]) > 1for t in toks:if caps and t.isupper() and words and _lang_on("capsrun"):words.append(t) # night wave: "DONT FORGET THE MILK" - an all-caps run is one piece of writingcontinueif t in ",.;:" or (t.lower() in STOP and words) or (t.lower() in ("a", "an", "the") and words):breakwords.append(t)if not words or (words[0].lower() in ("a", "an", "the") and len(words) == 1):continueif re.match(r"\s*(?:(?:that|which)\s+)?(?:reads|reading|read)\b", m.group(0), re.I) and words[0].lower() in STOP \and _lang_on("reading"):continue # night wave (language): "a girl reading in her bedroom" - a preposition after reading is not writingif re.match(r"\s*(?:(?:that|which)\s+)?(?:reads|reading|read)\b", m.group(0), re.I) and not words[0][:1].isupper() \and not words[0][:1].isdigit() and not _carrier_before(work, m.start()) and _lang_on("reading"):continue # night wave (language): "a fox reading a book", "a reading nook" = the activity, not writingtrig = m.group(0).lower().split()if trig and trig[-1] == "reading" and re.search(r"\b(?:a|an|the|my|his|her|their|our)\s+$", work[:m.start()], re.I) and _readact():continue # rule (night): "a reading lamp / reading glasses / a reading nook" - an adjective, not writingREADABLE = {"book", "books", "newspaper", "newspapers", "magazine", "map", "letter", "comic", "comics", "novel","poem", "story", "stories", "storybook", "scroll", "manga", "paper", "note"}if trig and trig[-1] in ("read", "reads", "reading") and words[0].lower() in ("a", "an", "the", "his", "her", "its","their", "my", "some", "this") \and (not _carrier_before(work, m.start()) or any(w.lower() in READABLE for w in words[1:3])) and _readact():continue # rule (night): "a girl reading a book" is the activity of reading, not writing that reads "a book"if m.group(0).lower().strip().endswith(("the word", "with the word")):words = words[:1] # rule: "the word X" = one wordendpos = m.end() + len(" ".join(words))
262 unmodified lines263264265266267268278 unmodified lines54754854955055155294 unmodified lines647648649650651652653654655656657658598 unmodified lines125712581259126012611262239 unmodified lines1502150315041505150615071508150988 unmodified lines15981599160016011602160314 unmodified lines161816191620162116221623162416251626262 unmodified linesif _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)STYLES = {"watercolor": "watercolor", "watercolour": "watercolor", "sketch": "sketch", "pencil": "sketch",278 unmodified lines# rule: unknown nouns borrow the nearest drawable concept from the fallback lexiconfrom .lexicon import lookupfrom .open_vocab import resolve# rule: a noun without a concept: a specific generator family (WordNet taxon near the word) first, then the# stand-in lexicon, then any family that knows an ancestor of the wordfor strict in (True, None, False):94 unmodified linestrace.append("understand: ignoring quoted text %s (pydraw draws no letters)" % ", ".join(quoted))text = re.sub(r'"[^"]*"|\u201c[^\u201d]*\u201d', " ", text)text = text.replace("\u2019", "'").replace("\u2018", "'") # rule: curly apostrophes are apostrophes# rule: a sentence end closes any open relation ("... on a race track. The sloth ..." must not put the track on the sloth)text = re.sub(r"[.!?;]+(\s|$)", " zzeos ", text)text = 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))598 unmodified lineshit = ("stork", None, toks[i] == "cranes")# rule: "tulip field" / "flower garden" / "pine forest": a noun right before a place word describes the placeif hit and i + ln < n and toks[i + ln] in SETTINGS and SETTINGS[toks[i + ln]][0] == "place" and not match_noun(toks, i + ln, fallback=False)[0] \and not (hit[0] in ("windmill", "wind turbine", "cow", "sheep", "horse", "chicken", "pig", "tent", "house", "boat") and toks[i + ln] in ("farm", "field", "camp", "village", "harbor", "marina")):if hit[0] in ("flower",):scene["flower_field"] = mods.get("color") or hit[1] or "mixed"239 unmodified linesif k == "place" and scene.get("place") and t in ("landscape", "scenery", "room", "outdoors", "outside", "inside", "indoors", "hills"):i += 1continuescene[k] = vtrace.append("understand: '%s' -> setting %s=%s" % (t, k, v))i += 1continueif t.isdigit():88 unmodified linesdel e[k]ents_ = scene["entities"]if len(ents_) == 1 and ents_[0]["concept"] == "person" and ents_[0]["count"] == 1 and ents_[0].get("expression") \and not scene.get("framing") and not scene.get("place") and not scene["relations"]:# rule: a lone person whose point is an emotion ("an angry man") is shown close up, or the face is a few pixelsscene["framing"] = "close"14 unmodified lines# 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)_tx_attach(scene, _texts, trace)from .physics import apply as _physics # wave 12: piles, spills, drapes, flags... as simulated composites_physics(scene, trace)262 unmodified lines263264265266267268269270271272278 unmodified lines55155255355455555655755855956056156256356456556694 unmodified lines661662663664665666667668669670671672673674675676677678679598 unmodified lines1278127912801281128212831284239 unmodified lines152415251526152715281529153015311532153315341535153615371538153988 unmodified lines162816291630163116321633163414 unmodified lines16491650165116521653165416551656165716581659262 unmodified linesif _k not in SETTINGS:SETTINGS[_k] = ("place", _v) if _v else ("time", "night")SETTINGS = {k: v for k, v in SETTINGS.items() if v}from .language import colors_add as _colors_add # night wave: rare colour names (mauve, ochre, "a rose dress")_colors_add(COLORS)from .language import settings_add as _settings_add # night wave: singular / missing setting nouns (hill, market...)_settings_add(SETTINGS)SETTINGS.pop("golden", None)STYLES = {"watercolor": "watercolor", "watercolour": "watercolor", "sketch": "sketch", "pencil": "sketch",278 unmodified lines# rule: unknown nouns borrow the nearest drawable concept from the fallback lexiconfrom .lexicon import lookupfrom .open_vocab import resolve# night wave (language): a noun whose main sense is a person (gardener, violinist) is a personfrom .language import person_nounif toks[i] not in SETTINGS and (toks[i],) not in idx and not (i > 0 and (toks[i - 1],) in idx and toks[i - 1] not in COLORSand (idx[(toks[i - 1],)][0] == "person"or CONCEPTS.get(idx[(toks[i - 1],)][0], {}).get("animal")or idx[(toks[i - 1],)][0] in ("robot", "snowman", "alien"))):ph = person_noun(toks[i], acting=i + 1 < len(toks) and toks[i + 1].endswith("ing")and toks[i + 1] not in ("building", "ceiling", "wedding", "clothing", "painting", "morning", "evening"))if ph:return ph, 1# rule: a noun without a concept: a specific generator family (WordNet taxon near the word) first, then the# stand-in lexicon, then any family that knows an ancestor of the wordfor strict in (True, None, False):94 unmodified linestrace.append("understand: ignoring quoted text %s (pydraw draws no letters)" % ", ".join(quoted))text = re.sub(r'"[^"]*"|\u201c[^\u201d]*\u201d', " ", text)text = text.replace("\u2019", "'").replace("\u2018", "'") # rule: curly apostrophes are apostrophesfrom . import language as _languageif _language.on("accents"): # night wave: "pi\u00f1ata", "caf\u00e9", "cr\u00e8me br\u00fbl\u00e9e": accented letters are plain lettersimport unicodedata as _udtext = "".join(c for c in _ud.normalize("NFKD", text) if not _ud.combining(c))# rule: a sentence end closes any open relation ("... on a race track. The sloth ..." must not put the track on the sloth)text = re.sub(r"[.!?;]+(\s|$)", " zzeos ", text)text = 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 language as _language # night wave: counts in words, relative clauses (pydraw/language.py)toks = _language.pre(toks, trace)toks = _language.places(toks, trace, SETTINGS, lambda w: (w,) in index() and not CONCEPTS.get(index()[(w,)][0], {}).get("open_vocab"))from . import imagine as _imaginetoks, _iplan = _imagine.pre(toks, trace)trace.append("understand: tokens=%s" % " ".join(toks))598 unmodified lineshit = ("stork", None, toks[i] == "cranes")# rule: "tulip field" / "flower garden" / "pine forest": a noun right before a place word describes the placeif hit and i + ln < n and toks[i + ln] in SETTINGS and SETTINGS[toks[i + ln]][0] == "place" and not match_noun(toks, i + ln, fallback=False)[0] \and not (toks[i + ln] in ("inside", "outside", "indoors", "outdoors") and _language.on("inside")) \and not (hit[0] in ("windmill", "wind turbine", "cow", "sheep", "horse", "chicken", "pig", "tent", "house", "boat") and toks[i + ln] in ("farm", "field", "camp", "village", "harbor", "marina")):if hit[0] in ("flower",):scene["flower_field"] = mods.get("color") or hit[1] or "mixed"239 unmodified linesif k == "place" and scene.get("place") and t in ("landscape", "scenery", "room", "outdoors", "outside", "inside", "indoors", "hills"):i += 1continueif k == "place" and scene.get("place") == "snow" and v in ("field", "mountains") and i > 0 and t not in ("mountains", "mountain") \and toks[i - 1] in ("snowy", "snow", "covered", "frozen", "wintry", "icy") and _language.on("snowy"):# night wave: "a snowy valley" / "a snow covered field": the snow is the look of that place; keep snowtrace.append("understand: '%s %s' -> stays snow" % (toks[i - 1], t))i += 1continuescene[k] = vtrace.append("understand: '%s' -> setting %s=%s" % (t, k, v))if mods.get("count") == 1 and any(x in ("a", "an") for x in toks[max(0, i - 3):i]) and _language.on("article"):mods.pop("count") # night wave: "a street with lanterns": the article was the street's, not the lanterns'i += 1continueif t.isdigit():88 unmodified linesdel e[k]ents_ = scene["entities"]if len(ents_) == 1 and ents_[0]["concept"] == "person" and ents_[0]["count"] == 1 and ents_[0].get("expression") \and not ents_[0].get("body_emotion") \and not scene.get("framing") and not scene.get("place") and not scene["relations"]:# rule: a lone person whose point is an emotion ("an angry man") is shown close up, or the face is a few pixelsscene["framing"] = "close"14 unmodified lines# 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)_language.post(scene, trace) # night wave: rare adjectives -> conditions, WordNet verbs, negated partsif scene["unknown"]:trace.append("understand: not drawn, unknown words: %s" % ", ".join(scene["unknown"]))_imagine.post(scene, _iplan, trace)_language.after_imagine(scene, trace)_tx_attach(scene, _texts, trace)from .physics import apply as _physics # wave 12: piles, spills, drapes, flags... as simulated composites_physics(scene, trace)
38 unmodified lines3940414243444525 unmodified lines71727374757638 unmodified linesOUTDOOR = {"field", "park", "farm", "mountains", "forest", "beach", "snow", "desert", "savanna", "water", "street", "sky", "jungle"}def vary(scene, trace, rng, strength=1.0, off=None):"""Decide the open choices up front (before layout) and record them in the scene.off: set of switches to disable (v variants, c colours, t time, s season, p place, f framing, m mood)."""if strength <= 0:25 unmodified lines# rule: time of day, only if the prompt names none (mostly day, sometimes golden hour)if "t" not in off and not named_colour and not explicit_time and scene.get("style") not in ("neon", "silhouette") and rng.random() < .25 * strength:v["time"] = "sunset"# rule: season, only outdoors and only if unnamedif "s" not in off and not explicit_season and rng.random() < .15 * strength:v["season"] = "autumn"38 unmodified lines3940414243444525 unmodified lines7172737475767778798081828384858687888990919238 unmodified linesOUTDOOR = {"field", "park", "farm", "mountains", "forest", "beach", "snow", "desert", "savanna", "water", "street", "sky", "jungle"}def vary(scene, trace, rng, strength=1.0, off=None, light=False):"""Decide the open choices up front (before layout) and record them in the scene.off: set of switches to disable (v variants, c colours, t time, s season, p place, f framing, m mood)."""if strength <= 0:25 unmodified lines# rule: time of day, only if the prompt names none (mostly day, sometimes golden hour)if "t" not in off and not named_colour and not explicit_time and scene.get("style") not in ("neon", "silhouette") and rng.random() < .25 * strength:v["time"] = "sunset"# rule (night pixel2, barelight; pixel only): a prompt that names no time, weather, place or colour gets its light# from a pleasant set - noon, golden hour, misty dawn, moonlit night - instead of noon three times in fourif light and "t" not in off and not named_colour and not explicit_time and not explicit_place and not scene.get("weather") \and not scene.get("style") and strength > 0:from .pixelcraft import on as _pc_onif _pc_on("atmos") and _pc_on("barelight"):r = rng.random()if r < .14:v["time"] = "night"elif r < .26:v["time"] = "sunset"scene["_dawn"] = Trueelif r < .4:v["time"] = "sunset"elif r < .52:v.pop("time", None)# rule: season, only outdoors and only if unnamedif "s" not in off and not explicit_season and rng.random() < .15 * strength:v["season"] = "autumn"
6 unmodified lines78910111230 unmodified lines4344454647484 unmodified lines5354555657585972 unmodified lines13213313413513613775 unmodified lines2132142152162172182192202212222232242252262276 unmodified lines234235236237238239240241242243244245246247203 unmodified lines45145245345445545645738 unmodified lines49649749849950050127 unmodified lines52953053153253353427 unmodified lines5625635645655665675684 unmodified lines57357457557657757833 unmodified lines6126136146156166176186199 unmodified lines6296306316326336346356366376386396406416426434 unmodified lines6486496506516526536546557 unmodified lines6636646656666676686696 unmodified lines67667767867968068168268368410 unmodified lines69569669769869970070170270370470570670770870971071171217 unmodified lines730731732733734735736145 unmodified lines882883884885886887888889890891892893186 unmodified lines108010811082108310841085108610871088108948 unmodified lines11381139114011411142114316 unmodified lines11601161116211631164116549 unmodified lines1215121612171218121912206 unmodified linesback-projected through the same pinhole camera into world space, then every concept is a 3D SDF model, lit by a sunand sky with soft shadows, ambient occlusion, specular highlights and aerial perspective."""import math, random, timeimport numpy as npfrom PIL import Image30 unmodified linesfrom . import compile as _cmpreturn _cmp.get(scene, _accel, ACCEL)BACKDROPS = [(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, ambient4 unmodified linesGROUNDS = {"field": ((95, 150, 60), (70, 120, 45)), "park": ((95, 150, 60), (70, 120, 45)), "farm": ((120, 150, 60), (90, 120, 45)),"mountains": ((100, 140, 70), (80, 110, 60)), "beach": ((225, 205, 160), (205, 185, 140)),"desert": ((225, 180, 120), (200, 150, 100)), "snow": ((240, 245, 252), (215, 225, 240)),"street": ((95, 95, 100), (80, 80, 86)), "savanna": ((200, 170, 90), (170, 140, 70))}_STEPS = {} # preview knobs (pydraw3d/search.py): fewer march / shadow steps72 unmodified linesck = _ck(self) if _COMPILE[0] else Noneif ck is not None:return ck.dist(P, want_id, margin, D)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):75 unmodified linesreturn n / np.maximum(S.length(n)[:, None], 1e-9)def 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)ck = _ck(scene) if _COMPILE[0] else Noneif ck is not None:return ck.soft_shadow(P, L, tmax, scl, k, steps, SHADOW_MARGIN)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)6 unmodified linesreturn np.clip(res, 0, 1) ** 1.5def ambient_occ(scene, P, N, scale):ck = _ck(scene) if _COMPILE[0] else Noneif ck is not None:return ck.ambient_occ(P, N, scale, AO_MARGIN)occ, 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)203 unmodified linesfor k_, v_ in (("fog", ".35"), ("sat", "1.25"), ("con", "1.12"), ("rim", ".5"), ("soft", ".7")):KX.setdefault(k_, v_)fogk = float(KX.get("fog", 1.0))_COMPILE[0] = KX.get("compile", "0") == "1"_GI[0] = int(KX.get("gi", 0)) if _COMPILE[0] else 0_GI[1] = float(KX.get("giao", 1.0))if _COMPILE[0]:38 unmodified linestrace.append("3d: %s has no hand-made 3D model -> generator family" % c_)missing = sorted({e["concept"] for e in ents if e["concept"] not in MODELS and e.get("worn_on") is None # (worn: drawn by the wearer)and (((e.get("attrs") or {}).get("text") or {}).get("kind") or "generic") == "generic"})if missing and KX.get("fallback", "pixel") == "pixel":# rule: if any object has no 3D model yet, the whole picture uses the pixel renderer (consistent style# beats a mix of 3D models and placeholder boxes)27 unmodified linescam = 1.0y0 = min(max(y0, 2.0), R - 2.0)# ---- back-project the 2D layout into world space (same pinhole as the layout) ----placed, objs = {}, []order = sorted(insts, key=lambda it: (it.bound is not None, getattr(it, "d", 0)))27 unmodified linesfn, aspect = carrier_model(e["attrs"]["text"], it, e, MODELS.get(it.concept), trace)else: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")) and not (e.get("attrs") or {}).get("text"): # (writing carriers handle their material)# rule: imagination (materials / skins on any model): see pydraw3d/imagine.pyfrom .imagine import apply_entity4 unmodified linesmat3 = _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 = it.info["aspect"] # (== CONCEPTS aspect unless a carrier of writing overrides it)aw = max(aspect, getattr(parts, "aspect", None) or 0) if getattr(parts, "fit_width", False) else aspect33 unmodified linesobjs[-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()))9 unmodified lines# 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:zs = [o.base[2] + o.scale * .6 for o in objs] or [cam * 3]wall_z = max(zs) * (1.35 if place in ("studio", "table") else 1.6) + .2 * camstreet = Noneif place == "street" and KX.get("facades", "1") == "1":zc_ = 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()4 unmodified linesif 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 picture7 unmodified linessx = 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":6 unmodified linessun_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)10 unmodified linesif 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}))))17 unmodified lines# rule: a few soft cumulus clouds high in the sky (fbm on the ray direction)cl = S.fbm(np.stack([D[:, 0] / np.maximum(up, .05) * 1.2, D[:, 2] / np.maximum(up, .05) * 1.2, np.zeros(len(D))], -1) * 1.5, 4, seed)cov = np.clip((cl - .52) * 4, 0, 1) * np.clip(up * 6, 0, 1)if tod != "night":cloud = hor * .4 + sunc * .9sky = sky * (1 - cov[:, None] * .85) + cloud * cov[:, None] * .85else:145 unmodified linesspec[g], rough[g] = sp_, ro_else:c1, c2 = GROUNDS.get(place, GROUNDS["field"])if scene.get("season") == "autumn" and place in ("field", "park"):c1, c2 = (150, 140, 60), (120, 100, 45)m = S.fbm(q * 2.0 / max(upm, 1e-3), 4, seed)[:, None]fine = S.noise3(q * 60 / max(upm, 1e-3), seed + 3)[:, None]alb[g] = lin(c1) * (1 - m) + lin(c2) * malb[g] *= (0.85 + .3 * fine)if place in ("field", "park", "farm", "mountains") and tod != "night" and KX.get("flowers", "1") == "1":# rule: a meadow has scattered small flowers (hashed cells; a few colours)cs = .06 * upm186 unmodified linesreturn 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 Dd48 unmodified linescol, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf)ss_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)16 unmodified linesout = _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 KX.get("simfx", "1") == "1":# wave 12: smoke / steam puffs and lightning from the simulators (pydraw3d/sim/post.py)from .sim.post import post3d as _simpost49 unmodified linesim = im.filter(ImageFilter.GaussianBlur(float(KX.get("soft")))) # rule: a touch of lens softnessif scene.get("mood"):im = _mood.post_image(im, scene) # wave 12: dutch angle_NAT.ON = Falseif _COMPILE[0]:trace.extend(_cmp.LOG)6 unmodified lines7891011121330 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485864 unmodified lines919293949596979872 unmodified lines17117217317417517617717817918018118218318418518618718818919019119219319419519619719875 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003016 unmodified lines308309310311312313314315316317318319320321322323324325326327328329330331332203 unmodified lines53653753853954054154254354454554654738 unmodified lines58658758858959059159259359459559627 unmodified lines62462562662762862963063127 unmodified lines6596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926934 unmodified lines69869970070170270370470570633 unmodified lines7407417427437447457467477487497507517527537547557567577587597607617627637647657667679 unmodified lines7777787797807817827837847857867877887897907917927937947957967977987998004 unmodified lines8058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378387 unmodified lines8468478488498508518526 unmodified lines85986086186286386486586686786886910 unmodified lines88088188288388488588688788888989089189289389489589689789889990090190217 unmodified lines920921922923924925926927928929930931932933934935936937938939940941145 unmodified lines1087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114186 unmodified lines1301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140148 unmodified lines1450145114521453145414551456145716 unmodified lines14741475147614771478147914801481148249 unmodified lines153215331534153515361537153815396 unmodified linesback-projected through the same pinhole camera into world space, then every concept is a 3D SDF model, lit by a sunand sky with soft shadows, ambient occlusion, specular highlights and aerial perspective."""import math, random, timeimport re as _re_modimport numpy as npfrom PIL import Image30 unmodified linesfrom . import compile as _cmpreturn _cmp.get(scene, _accel, ACCEL)def _extend(parts, extra):"""append to a model's part list keeping its attributes (anchors, aspect...)"""parts.extend(extra)return partsINDOOR2 = ("throne room", "library", "classroom", "cafe", "restaurant", "supermarket", "garage")_HYBRID = [True] # night wave: knob hybrid=0 = a scene with any untraceable object runs fully in numpy (as before)def _hy(scene):"""(compiled sub-scene of the traceable objects, the sub-scene, their indices, the other indices) or None.rule (speed): sim fields (ivy, webs, piles: k-d tree closures) cannot be traced to C, and one such object usedto send the WHOLE scene (terrain, trees, everything) back to numpy; now only that object stays in numpy."""if not (_COMPILE[0] and ACCEL and _HYBRID[0]):return Nonesig = (tuple(id(o) for o in scene.objs), id(scene.world))h = scene.__dict__.get("_hy")if h is not None and h[0] == sig:return h[1]from . import compile as _cmpres = Noneif _cmp.get(scene, _accel, ACCEL) is None:bad = [k for k, o in enumerate(scene.objs) if not _cmp.traceable(o)]good = [k for k in range(len(scene.objs)) if k not in bad]if bad:sub = Scene3D([scene.objs[k] for k in good], ground=scene.ground, backdrop_z=scene.backdrop_z,cove=scene.cove, street=scene.street)sub.world = scene.worldcs = _cmp.get(sub, _accel, ACCEL)if cs is not None:res = (cs, sub, np.array(good + [-1], np.int64), bad)_cmp.LOG.append("compile: hybrid, %d objects in numpy (%s)" % (len(bad), ", ".join(scene.objs[k].name for k in bad)))scene.__dict__["_hy"] = (sig, res)return resBACKDROPS = [(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, ambient4 unmodified linesGROUNDS = {"field": ((95, 150, 60), (70, 120, 45)), "park": ((95, 150, 60), (70, 120, 45)), "farm": ((120, 150, 60), (90, 120, 45)),"mountains": ((100, 140, 70), (80, 110, 60)), "beach": ((225, 205, 160), (205, 185, 140)),"desert": ((225, 180, 120), (200, 150, 100)), "snow": ((240, 245, 252), (215, 225, 240)),"street": ((95, 95, 100), (80, 80, 86)), "savanna": ((200, 170, 90), (170, 140, 70)),"moon": ((150, 150, 152), (112, 112, 116))}_STEPS = {} # preview knobs (pydraw3d/search.py): fewer march / shadow steps72 unmodified linesck = _ck(self) if _COMPILE[0] else Noneif ck is not None:return ck.dist(P, want_id, margin, D)hy = _hy(self) if _COMPILE[0] else Noneif hy is not None:# night wave (hybrid): compiled ground / world / traceable objects, numpy for the untraceable ones (sim# fields: k-d trees). Same per-object rule as the numpy loop below, so the values are the same.cs, sub, good, bad = hyskip = getattr(self, "skip", ())sub.skip = tuple(j for j, k in enumerate(good) if k in skip) if skip else ()d, ids = cs.dist(P, True, margin, D)ids = np.where(ids >= 0, good[np.maximum(ids, 0)], ids)for k in bad:if k in skip:continueo = self.objs[k]db = S.length(P - o.center) - o.radiusnear = db < margin * o.scaledk = db.copy()if near.any():dk[near] = o.dist(P[near], margin)better = dk < dd = np.where(better, dk, d)ids[better] = kreturn (d, ids) if want_id else dif 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):75 unmodified linesreturn n / np.maximum(S.length(n)[:, None], 1e-9)SH_FIT = [True] # night wave knob shfit=0def soft_shadow(scene, P, L, tmax, scl, k=6.0, steps=48):steps = _STEPS.get("shadow", steps)# night wave rule: with the compiled kernel, shadow rays evaluate objects exactly within 1.5 x their scale (the# pre-accel value); the .4 speed margin answered them with bounding-sphere bounds and drew false penumbra rings# on the table around small objectsSHM = max(SHADOW_MARGIN, 1.5) if (_COMPILE[0] and SH_FIT[0] and not _STEPS) else SHADOW_MARGINif ACCEL:if LIGHT and getattr(scene, "glassy", None):def _sf(sc_, P_, L_, tmax_, scl_, k_, steps_, margin):# night wave: the two shadow passes of a glass scene use the compiled kernel toock_ = _ck(sc_) if _COMPILE[0] else Noneif ck_ is not None:return ck_.soft_shadow(P_, L_, tmax_, scl_, k_, steps_, margin)return _accel.soft_shadow(sc_, P_, L_, tmax_, scl_, k_, steps_, margin=margin)return _light.glass_shadow(scene, P, L, tmax, scl, k, steps, SHM, _sf)ck = _ck(scene) if _COMPILE[0] else Noneif ck is not None:return ck.soft_shadow(P, L, tmax, scl, k, steps, SHM)return _accel.soft_shadow(scene, P, L, tmax, scl, k, steps, margin=SHM)# 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)6 unmodified linesreturn np.clip(res, 0, 1) ** 1.5AO_FIT = [True] # night wave knob aofit=0def ambient_occ(scene, P, N, scale):mg = AO_MARGINif AO_FIT[0] and ACCEL and scene.objs:# night wave rule: the AO probes reach .15 x the MEAN subject scale; an object much smaller than the mean (a# lemon beside oranges) answered them with its bounding-sphere bound, and each of the 5 probes drew a# concentric ring on the table around it. The exact-evaluation margin (relative to each object's scale)# now covers the probe reach for the smallest object.mg = max(AO_MARGIN, .2 * float(scale) / max(min(o.scale for o in scene.objs), 1e-6))mg = min(mg, 4.0)ck = _ck(scene) if _COMPILE[0] else Noneif ck is not None:return ck.ambient_occ(P, N, scale, mg)occ, 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=mg), 0)w *= .7return np.clip(1 - 3.0 * occ / scale / .03 / 5, 0, 1)203 unmodified linesfor k_, v_ in (("fog", ".35"), ("sat", "1.25"), ("con", "1.12"), ("rim", ".5"), ("soft", ".7")):KX.setdefault(k_, v_)fogk = float(KX.get("fog", 1.0))# night wave: the scene compiler is ON by default (byte-identical to numpy, 4-8x faster); compile=0 = pure numpy.# It needs gcc; without it every scene quietly falls back to numpy._COMPILE[0] = KX.get("compile", "1") == "1"_HYBRID[0] = KX.get("hybrid", "1") == "1"AO_FIT[0] = KX.get("aofit", "1") == "1"SH_FIT[0] = KX.get("shfit", "1") == "1"_GI[0] = int(KX.get("gi", 0)) if _COMPILE[0] else 0_GI[1] = float(KX.get("giao", 1.0))if _COMPILE[0]:38 unmodified linestrace.append("3d: %s has no hand-made 3D model -> generator family" % c_)missing = sorted({e["concept"] for e in ents if e["concept"] not in MODELS and e.get("worn_on") is None # (worn: drawn by the wearer)and (((e.get("attrs") or {}).get("text") or {}).get("kind") or "generic") == "generic"})if missing and KX.get("relief", "1") == "1":# night wave (parity): concepts with no 3D model become reliefs of their own pixel drawing (pydraw3d/relief.py)# instead of sending the whole picture to the pixel renderertrace.append("3d: no 3D model for %s -> relief of the pixel drawing" % ", ".join(missing))missing = []if missing and KX.get("fallback", "pixel") == "pixel":# rule: if any object has no 3D model yet, the whole picture uses the pixel renderer (consistent style# beats a mix of 3D models and placeholder boxes)27 unmodified linescam = 1.0y0 = min(max(y0, 2.0), R - 2.0)from . import models_indoor as _mi_mi.CUR_SCENE[0] = (scene.get("time") or "day", scene.get("weather")) if KX.get("winmodel", "1") == "1" else None# ---- back-project the 2D layout into world space (same pinhole as the layout) ----placed, objs = {}, []order = sorted(insts, key=lambda it: (it.bound is not None, getattr(it, "d", 0)))27 unmodified linesfn, aspect = carrier_model(e["attrs"]["text"], it, e, MODELS.get(it.concept), trace)else:fn, aspect = interact.model_for(it, e, MODELS.get(it.concept), trace) or (None, CONCEPTS[it.concept]["aspect"])parts = Noneif fn is None and it.concept not in MODELS and KX.get("relief", "1") == "1":from .relief import relief_partsrp = relief_parts(it, scene, col)if rp is not None:parts, aspect = rpfn = Noneif parts is None:parts = fn(col, it) if fn else fallback(col, CONCEPTS[it.concept]["aspect"])if scene.get("season") == "autumn" and not cname and KX.get("fallleaves", "1") == "1" and \("tree" in it.concept or it.concept in ("oak", "maple", "bush", "hedge", "shrub")) and "pine" not in it.concept:# night wave rule: in autumn a prompted (uncoloured) tree turns too, not only the world's trees_pal = [(214, 120, 40), (190, 60, 35), (225, 175, 50)]for _j, _pt in enumerate(parts):_c = np.asarray(_pt.color, float)if _c[1] > _c[0] * 1.1 and _c[1] > _c[2] * 1.1:_pt.color = np.asarray(_pal[(_j + seed) % 3], float) * (.85 + .3 * (_c[1] / 255.0))trace.append("3d: %s in autumn colours" % it.concept)if KX.get("contents", "1") == "1" and it.concept in __import__("pydraw3d.contents", fromlist=["x"]).CONTAINERS:# night wave: "a vase of flowers", "a basket of oranges", "a cup of coffee" - fill the containerfrom .contents import contents_partstry:extra = contents_parts(it.concept, e.get("word") or it.concept, text, parts, aspect,random.Random(seed * 31 + 7 + it.k), trace) # (own rng: the scene's draws stay put)except Exception as ex_:extra = []trace.append("3d: contents of %s skipped (%s)" % (it.concept, type(ex_).__name__))if extra:parts = parts + extra if not hasattr(parts, "__dict__") else _extend(parts, extra)if (e.get("imagine") or e.get("material")) and not (e.get("attrs") or {}).get("text"): # (writing carriers handle their material)# rule: imagination (materials / skins on any model): see pydraw3d/imagine.pyfrom .imagine import apply_entity4 unmodified linesmat3 = _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))if (e.get("attrs") or {}).get("cond") or (e.get("attrs") or {}).get("absent"): # night wave (language): tattered / rusty / gleaming / gnarled... on any modelfrom .condition3d import apply as _cond3dparts = _cond3d(parts, e, trace, seed=getattr(it, "k", 0))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 = it.info["aspect"] # (== CONCEPTS aspect unless a carrier of writing overrides it)aw = max(aspect, getattr(parts, "aspect", None) or 0) if getattr(parts, "fit_width", False) else aspect33 unmodified linesobjs[-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 them_nt = len(trace)interact.place(it, objs[-1], trace) # wave 11: held things in hand / mouth / beak, riders on the saddleif KX.get("rest", "1") == "1" and it.bound is not None and it.rel == "on" and len(trace) == _nt and not it.concept.startswith("sim ") \and getattr(it, "held_by", None) is None and getattr(it, "worn_by", None) is None and not getattr(it, "riding", False) \and it.concept != "person" and not (getattr(it, "attrs", None) or {}).get("fixed_scale") and getattr(it, "pose", None) != "flying":# night wave rule (rest=0 off; not for simulated composites, which place themselves): a thing ON another# thing rests on the host model's real top surface (the# layout's box top floats above a low family model: apples hovered over a wheelbarrow), at the host's depthhob = interact._OBJ.get(id(it.bound))if hob is not None and hob is not objs[-1]:o_ = objs[-1]lx = S.rot_y((o_.base - hob.base)[None, :] / hob.scale, -hob.yaw)[0]tp = interact.top_point(hob.parts, x=float(np.clip(lx[0], -.45 * hob.radius / hob.scale, .45 * hob.radius / hob.scale)))if tp is not None:w_ = interact.world_pt(hob, (lx[0], tp[1], 0.0))nb = np.array([o_.base[0], w_[1] - .04 * o_.scale, w_[2]])if abs(nb[1] - o_.base[1]) > .02 * hob.scale or abs(nb[2] - o_.base[2]) > .05 * hob.scale:o_.center = o_.center + (nb - o_.base)o_.base = nbtrace.append("3d: %s rests on the top of %s" % (it.concept, it.bound.concept))trace.append("3d: %s at x=%.2f y=%.2f z=%.2f h=%.2f" % (it.concept, X, Yb, Z, Hw))objs += interact.extras(objs, Obj, trace) # night characters 2: leashes joining two placed objectscamd = 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()))9 unmodified lines# 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)# night wave rule (indoor2=0 off): the named rooms the pixel renderer furnishes (throne room, library, classroom,# cafe, restaurant, supermarket, garage) are rooms in 3D too (they were an empty field with a sky)_rooms = ("room", "kitchen", "bedroom", "bathroom", "office") + (INDOOR2 if KX.get("indoor2", "1") == "1" else ())indoor = place in ("studio", "table") + _rooms and KX.get("wall", "1") == "1"wall_z = Noneif indoor:zs = [o.base[2] + o.scale * .6 for o in objs] or [cam * 3]wall_z = max(zs) * (1.35 if place in ("studio", "table") else 1.6) + .2 * cam# night wave: "a snowy street" - falling snow on streets (no world draws it) and a snowy pavement_snowwd = place == "street" and not scene.get("weather") and bool(_re_mod.search(r"\b(snowy|snowing|snowfall|blizzard|winter)\b", text.lower()))street = Noneif place == "street" and KX.get("facades", "1") == "1":zc_ = float(np.median([o.base[2] for o in objs])) if objs else 4 * cam# night wave rule (cityview=0 off): with nothing (or only small things) in the street, the facade row stands# further back so the picture shows a street receding to a skyline, not one grey wall filling the frame_small = all(o.scale < .6 * cam for o in objs)_cv = KX.get("cityview", "1") == "1"street = (zc_ + ((26.0 if _small else 16.0) if _cv else 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()4 unmodified linesif camd is not None:O = camd.Ozfar = max([float(np.linalg.norm(o.base - O)) for o in objs] + [cam * 8]) * 6if KX.get("wornfront", "1") == "1":# night wave rule: a worn thing the wearer's model does not draw itself (sunglasses on a snowman, a relief hat)# sits on the wearer's FRONT surface as seen from the camera, not at the wearer's centre (inside the head)for o in objs:wb = getattr(o.inst, "worn_by", None) if o.inst is not None else Nonehost = [h_ for h_ in objs if h_ is not o and h_.ent == wb] if wb is not None else []if not host:continuec_ = o.base + np.array([0, .5 * o.scale, 0])dvec = c_ - OL_ = float(np.linalg.norm(dvec))dvec = dvec / max(L_, 1e-9)ts = np.linspace(max(L_ - 2.5 * host[0].radius, 0), L_, 160)dd = host[0].dist(O + ts[:, None] * dvec[None, :])inside = np.nonzero(dd < 0)[0]if len(inside) and ts[inside[0]] < L_:shift = (L_ - ts[inside[0]]) + .06 * o.scaleo.base = o.base - dvec * shifto.center = o.center - dvec * shifttrace.append("3d: %s worn on the front of %s" % (o.name, host[0].name))zen, hor, sunc, sun_i, amb = SKIES[tod]moon3d = place == "moon" and KX.get("moon3d", "1") == "1"if moon3d:# night wave rule (moon3d=0 off): on the moon the sky is black at any hour (stars, the Earth hanging in it),# the sun is hard and white, almost no ambient light; the ground is grey regolith with craters (it was a# green meadow under a blue sky once a concept without a 3D model stopped sending the picture to pixel art)zen, hor, sunc, sun_i, amb = (4, 5, 12), (10, 10, 18), (255, 252, 245), 3.2, .22zen, 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 picture7 unmodified linessx = 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 _roomsif studio:back = rng.choice(BACKDROPS)if place == "table":6 unmodified linessun_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 it_cz = (scene.get("mood") or {}).get("glow", 0) > .5 and KX.get("cozylamp", "1") == "1"# (night wave: a COZY room at night is lamp-lit, not dark: brighter warm walls, more ambient)back = back * (.3 if _cz else .16) * (np.array([1.15, 1.0, .8]) if _cz else 1.0)hor, zen = back, back * .7sunc, sun_i, amb = lin((150, 170, 225)), .35, (.75 if _cz else .45)rimk = float(KX.get("rim", "0"))if camd is not None:L, rimk = _camera.key_light(camd, tod, studio, trace)10 unmodified linesif world is not None:world.build()zen, hor, sunc, sun_i, amb = world.light(zen, hor, sunc, sun_i, amb)if world.b.get("ground") == "snow" and tod == "sunset" and place not in ("snow", "mountains"):sunc = sunc * .35 + lin((255, 240, 225)) * .65 # (same rule as above: snow stays white at golden hour)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 []_cozy = (scene.get("mood") or {}).get("glow", 0) > .5 and KX.get("cozylamp", "1") == "1"if LIGHT and studio and tod == "night" and (not lights or _cozy) and KX.get("plights", "1") == "1":# (night wave, cozylamp=0 off: a COZY room at night always gets the warm practical, even when a small lamp# or fire is in the scene - "a cozy library" was nearly black)# 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(),(3.2 if _cozy else 2.2) * sc_ ** 2, -99, .3 * sc_)] + list(lights)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}))))17 unmodified lines# rule: a few soft cumulus clouds high in the sky (fbm on the ray direction)cl = S.fbm(np.stack([D[:, 0] / np.maximum(up, .05) * 1.2, D[:, 2] / np.maximum(up, .05) * 1.2, np.zeros(len(D))], -1) * 1.5, 4, seed)cov = np.clip((cl - .52) * 4, 0, 1) * np.clip(up * 6, 0, 1)if moon3d:stars = (S.noise3(D * 300, seed) > .982) * np.clip(up * 6 + .2, 0, 1)sky = sky + stars[:, None] * .7# the Earth: a blue-white disc with cloud swirls, high on the side away from the suned = np.array([-np.sign(L[0]) * .45, .42, 1.0])ed /= np.linalg.norm(ed)ca = D @ eder = np.sqrt(np.maximum(1 - ca * ca, 0))disc = (ca > 0) & (er < .07)if disc.any():cl_ = S.fbm(D[disc] * 40, 3, seed + 9) > .55land_ = S.fbm(D[disc] * 25, 3, seed + 11) > .58ec = np.where(cl_[:, None], lin((240, 245, 250)), np.where(land_[:, None], lin((90, 140, 80)), lin((40, 90, 190))))shade_ = np.clip(.25 + ((D[disc] - ed) @ L) * 12, .15, 1.2)[:, None]sky[disc] = ec * shade_ * 1.2elif tod != "night":cloud = hor * .4 + sunc * .9sky = sky * (1 - cov[:, None] * .85) + cloud * cov[:, None] * .85else:145 unmodified linesspec[g], rough[g] = sp_, ro_else:c1, c2 = GROUNDS.get(place, GROUNDS["field"])if _snowwd:c1, c2 = (225, 228, 235), (200, 205, 215)if scene.get("season") == "autumn" and place in ("field", "park"):c1, c2 = (150, 140, 60), (120, 100, 45)m = S.fbm(q * 2.0 / max(upm, 1e-3), 4, seed)[:, None]fine = S.noise3(q * 60 / max(upm, 1e-3), seed + 3)[:, None]alb[g] = lin(c1) * (1 - m) + lin(c2) * malb[g] *= (0.85 + .3 * fine)if moon3d:# regolith: craters = dark floors with a bright rim (hashed cells, several sizes)gg = alb[g]for cs_, k_ in ((.9, 0), (.35, 1), (.15, 2)):cs = cs_ * upmci = np.floor(q[:, [0, 2]] / cs).astype(np.int64)hsh = S._hash(ci[:, 0], ci[:, 1], np.zeros(len(ci), np.int64) + 21 + k_, seed)fr = q[:, [0, 2]] / cs - ci - .5rr = np.sqrt((fr ** 2).sum(-1))has = hsh > .6rad = .2 + .2 * S._hash(ci[:, 0], ci[:, 1], np.zeros(len(ci), np.int64) + 31 + k_, seed)gg = np.where((has & (rr < rad * .8))[:, None], gg * .72, gg)gg = np.where((has & (np.abs(rr - rad) < .06))[:, None], gg * 1.25, gg)alb[g] = ggif place in ("field", "park", "farm", "mountains") and tod != "night" and KX.get("flowers", "1") == "1":# rule: a meadow has scattered small flowers (hashed cells; a few colours)cs = .06 * upm186 unmodified linesreturn col, idmap, tmap, cmapzoom = Noneif camd is None and place == "table" and KX.get("tzoom", "1") == "1" and insts:# night wave rule (tzoom=0 off): a tabletop still life is framed like a photograph: the camera zooms in (a# window of the layout's view) until the group spans ~72% of the width, the group's base low in the frame# (a row of apples was a thin strip along the bottom of an empty wall)subj = [o for o in objs if o.inst is not None and not getattr(o, "dressing", False)]free = [o for o in subj if getattr(o.inst, "bound", None) is None]if len(free) >= 2 and len(free) == len(subj) and KX.get("tpack", "1") == "1":# rule (still life, tpack=0 off): the things stand close together (gap ~ a fifth of their width); three# stagger the middle one back, four or more form two rows (a cluster, not a parade across the table)free.sort(key=lambda o: o.base[0])for o in free:if not hasattr(o, "pbox"):_accel.compute_bounds(o)ws = [(.5 * float(o.box[1][0] - o.box[0][0]) * o.scale if getattr(o, "box", None) is not None else .5 * o.radius) for o in free]gap = .18 * float(np.mean(ws))xc = float(np.mean([o.base[0] for o in free]))# four or more: two staggered rows (the back row sits in the front row's gaps)rows = [list(range(len(free)))] if len(free) < 4 else [list(range(0, len(free), 2)), list(range(1, len(free), 2))]for r_, idx in enumerate(rows):tot = sum(2 * ws[j] for j in idx) + gap * (len(idx) - 1)x_ = xc - tot / 2 + (.5 * (2 * float(np.mean(ws)) + gap) if r_ == 1 else 0.0) * (1 if len(rows[0]) == len(idx) else 0)for k_, j in enumerate(idx):o, w_ = free[j], ws[j]nb = o.base.copy()nb[0] = x_ + w_if len(rows) == 2:nb[2] = nb[2] + (2.2 * float(np.mean(ws)) if r_ == 1 else 0.0)elif len(free) == 3 and k_ == 1:nb[2] = nb[2] + .6 * float(np.mean(ws))o.center = o.center + (nb - o.base)o.base = nbx_ += 2 * w_ + gaptrace.append("3d: still life - %d things packed into a cluster" % len(free))# the group's screen box in the layout camera (pinhole: x = R/2 + X f / Z, y = y0 - (Y - cam) f / Z)px = []for o in subj:for dx in (-1, 1):for yy in (o.base[1], o.base[1] + o.scale):Z_ = max(o.base[2] - .3 * o.radius, 1e-3)hw_ = .5 * float(o.box[1][0] - o.box[0][0]) * o.scale if getattr(o, "box", None) is not None else .6 * o.radiuspx.append((R / 2 + (o.base[0] + dx * hw_) * f / Z_, y0 - (yy - cam) * f / Z_))px = np.array(px) if px else np.zeros((1, 2))gx0, gx1 = px[:, 0].min(), px[:, 0].max()gy0, gy1 = px[:, 1].min(), px[:, 1].max()Wn = max((gx1 - gx0) / .76, (gy1 - gy0) / .55, R * .35)if Wn < R * .97:# (the window may reach below the layout frame: the camera just looks a little lower, more table in front)wx0 = (gx0 + gx1) / 2 - Wn / 2wy0 = gy1 - .8 * Wnzoom = (wx0, wy0, Wn / R)trace.append("3d: tabletop framing - zoom x%.2f on the group" % (R / Wn))trace.append("3d: tabletop group box x %.0f-%.0f y %.0f-%.0f" % (gx0, gx1, gy0, gy1))elif camd is None and place not in ("table", "sky", "space", "moon") and KX.get("gzoom", "1") == "1":# night wave rule (gzoom=0 off): small subjects in a big frame (two figures at the edge of a room, a girl and# a cake specks in a field): the camera zooms in (a window of the layout view, at most 1.6x) so the group# spans ~60% of the frame width, its base low in the frame; never when the group already fills itsubj = [o for o in objs if o.inst is not None and not getattr(o, "dressing", False)]px = []for o in subj:if not hasattr(o, "pbox"):_accel.compute_bounds(o)hw_ = .5 * float(o.box[1][0] - o.box[0][0]) * o.scale if getattr(o, "box", None) is not None else .6 * o.radiusZ_ = max(o.base[2] - .3 * o.radius, 1e-3)for dx in (-1, 1):for yy in (o.base[1], o.base[1] + o.scale):px.append((R / 2 + (o.base[0] + dx * hw_) * f / Z_, y0 - (yy - cam) * f / Z_))if px:px = np.array(px)gx0, gx1, gy0, gy1 = px[:, 0].min(), px[:, 0].max(), px[:, 1].min(), px[:, 1].max()Wn = max((gx1 - gx0) / .6, (gy1 - gy0) / .62, R / 1.6)# keep the horizon in the picture (>= 34% from the top: room for sky), else a zoom on a low group shows only groundif world is not None or not studio:Wn = max(Wn, (gy1 - y0) / .58)if Wn < R * .8:wx0 = (gx0 + gx1) / 2 - Wn / 2wy0 = max(gy1 - .84 * Wn, gy0 - .3 * Wn)if world is not None or not studio:wy0 = min(wy0, y0 - .34 * Wn)zoom = (wx0, wy0, Wn / R)trace.append("3d: group framing - zoom x%.2f on the subjects" % (R / Wn))elif gy1 > R * 1.02 and scene.get("framing") != "close" and KX.get("unclip", "1") == "1":# night wave rule (unclip=0 off): subjects whose base falls below the frame (people sitting on the# ground in front of the camera were cut at the waist) - the camera widens (<= 1.35x) until the base# is inside, keeping the top edge where it wasWn = min(R * 1.35, gy1 / .95)zoom = (R / 2 - Wn / 2, 0.0, Wn / R)trace.append("3d: group framing - widen x%.2f so the subjects' base is in the frame" % (Wn / R))def 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 Ddif zoom is not None:xp, yp = zoom[0] + xp * zoom[2], zoom[1] + yp * zoom[2]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 Dd48 unmodified linescol, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf)ss_eff = ssif LIGHT and KX.get("beam", "1") == "1" and not KX.get("preview"):col = _light.beams(col, rays(xsf, ysf), O, tm, objs, tod, trace)# ---- 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)16 unmodified linesout = _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)elif LIGHT and wall_z is None and (scene.get("weather") in ("rain", "storm", "snow") or _snowwd) and KX.get("wxpost", "1") == "1":out = _light.weather_post(np.clip(out, 0, 1).reshape(n, n, 3), scene.get("weather") or "snow", seed, tod == "night").reshape(-1, 3)trace.append("3d: %s particles (no world)" % scene.get("weather"))if KX.get("simfx", "1") == "1":# wave 12: smoke / steam puffs and lightning from the simulators (pydraw3d/sim/post.py)from .sim.post import post3d as _simpost49 unmodified linesim = im.filter(ImageFilter.GaussianBlur(float(KX.get("soft")))) # rule: a touch of lens softnessif scene.get("mood"):im = _mood.post_image(im, scene) # wave 12: dutch anglefrom pydraw.frames import apply_pil as _frame # language shift 2: "a postcard of X"im = _frame(scene, im, trace)_NAT.ON = Falseif _COMPILE[0]:trace.extend(_cmp.LOG)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284"""3D side of pydraw/attach.py: attached things find their anchor on the host's own SDF (night round 1, scene lane).
flag the pole base stands on the highest surface of the host near the layout's anchor (the keep, the lantern room's roof, the roof ridge); "hoist" = the pole's top at the mast top (the pole overlaps the mast) front a mounted sign board sits flat on the host's front face (first surface hit along +z in host space) hang a cord part from the thing's top up to the limb / canopy; a limb host is rebuilt as a horizontal bough and the pair is moved to a sensible depth (rays through the camera are kept, so the picture's 2D layout holds)Called from interact.place (inst.attach set by the 2D layout). Knob: PYDRAW_EXP attach=0 (no inst.attach is set)."""import mathimport numpy as np
from . import sdf as Sfrom .models import Part, V
CAM = 1.0 # plot3d's camera height (the layout's pinhole is back-projected with cam = 1.0)
def _union_d(parts, q): d = None for pt in parts: e = pt.fn(q) d = e if d is None else np.minimum(d, e) return d
def _local(obj, P): return S.rot_y((np.asarray(P, float) - obj.base)[None, :] / obj.scale, -obj.yaw)[0]
def _world(obj, a): q = np.asarray(a, float)[None, :] * obj.scale return S.rot_y(q, obj.yaw)[0] + obj.base
def top_near(parts, lx, aspect, thin=False): """highest surface point of `parts` (model space) in columns around x = lx; thin = look for a mast (fine grid)""" xs = lx + np.linspace(-.05, .05, 5) * max(1.0, aspect) if not thin else lx + np.linspace(-.04, .04, 9) * max(1.0, aspect) zs = np.linspace(-.7, .7, 15) * max(1.0, aspect) if not thin else np.linspace(-.12, .12, 13) ys = np.linspace(2.2, 0.0, 221) X, Z, Y = np.meshgrid(xs, zs, ys, indexing="ij") q = np.stack([X.ravel(), Y.ravel(), Z.ravel()], -1).astype(np.float32) d = _union_d(parts, q).reshape(X.shape) hit = d < .006 best = None for i in range(len(xs)): for j in range(len(zs)): k = np.nonzero(hit[i, j])[0] if not len(k): continue y = ys[k[0]] score = y - .3 * abs(xs[i] - lx) if best is None or score > best[0]: best = (score, (float(xs[i]), float(y), float(zs[j]))) return None if best is None else best[1]
def front_at(parts, lx, ly, aspect): """first surface hit along +z (toward the back) at model (lx, ly): the host's front face""" zs = np.linspace(-1.6 * max(1.0, aspect), 1.6 * max(1.0, aspect), 321) q = np.stack([np.full_like(zs, lx), np.full_like(zs, ly), zs], -1).astype(np.float32) d = _union_d(parts, q) k = np.nonzero(d < .006)[0] return float(zs[k[0]]) if len(k) else None
def pole_x(it): """the flag model's pole x in its own model space""" from pydraw.registry import CONCEPTS c = CONCEPTS.get(it.concept, {}) if (c.get("sim") or {}).get("kind") == "flag": return -float(c.get("aspect", .5)) / 2 + .02 if getattr(it, "pole_free", False) or getattr(it, "attach_kind", None) != "flag": return 0.0 return -.42
def place(it, obj, host, trace): mode, anchor = it.attach from pydraw.registry import CONCEPTS hasp = float(CONCEPTS.get(host.name, {}).get("aspect", 1.0)) if host.name in CONCEPTS else 1.0 if mode in ("top", "hoist"): lx = anchor[0] * hasp p = top_near(host.parts, lx, hasp, thin=(mode == "hoist")) if p is None: return w = _world(host, p) off = S.rot_y(np.array([[pole_x(it) * obj.scale, 0.0, 0.0]]), obj.yaw)[0] base = w - off if mode == "hoist": base[1] -= .97 * obj.scale # rule: the flag is hoisted to the masthead, its pole along the mast else: base[1] -= .01 * obj.scale obj.base = base obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s flies from the %s (%s at y=%.2f)" % (it.concept.split(":")[0], host.name, mode, w[1])) elif mode == "front" and len(anchor) > 2: # a mounted object (clock, window, door...): its centre on the host's front face, its back touching it ly = anchor[1] zf = front_at(host.parts, 0.0, ly, hasp) if zf is None: return obj.yaw = host.yaw oasp = float(CONCEPTS.get(it.concept, {}).get("aspect", 1.0)) zs = np.linspace(1.2 * max(1.0, oasp), -1.2 * max(1.0, oasp), 241) q = np.stack([np.zeros_like(zs), np.full_like(zs, .5), zs], -1).astype(np.float32) k_ = np.nonzero(_union_d(obj.parts, q) < .006)[0] zb = float(zs[k_[0]]) if len(k_) else .1 # the object's back face (model units) c = _world(host, (0.0, ly, zf - .01)) off = S.rot_y(np.array([[0.0, 0.0, zb * obj.scale]]), obj.yaw)[0] obj.base = c - off - np.array([0, .5 * obj.scale, 0]) obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s mounted on the %s's front (z=%.2f)" % (it.concept, host.name, zf)) elif mode == "inside": # rule: a miniature in a bottle / jar stands just behind the front glass (inside the SDF it would be hidden by # the container's own surface): moved along its camera ray to the container's front face zf = front_at(host.parts, 0.0, .3, hasp) if zf is None: return wf = _world(host, (0.0, .3, zf)) Zo = obj.base[2] Zc = max(Zo * .5, wf[2] - .02 * host.scale) s_ = Zc / max(1e-6, Zo) O = np.array([0.0, CAM, 0.0]) obj.base = O + (obj.base - O) * s_ obj.scale *= s_ obj.radius *= s_ obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s inside the %s, behind its front glass" % (it.concept, host.name)) elif mode == "climb": # rule: a climber is on the trunk's front, not inside it: moved along its ray to the trunk's front face zf = front_at(host.parts, 0.0, anchor[1], hasp) if zf is not None: wf = _world(host, (0.0, anchor[1], zf)) Zo = obj.base[2] Zc = max(Zo * .5, wf[2] - .12 * obj.scale) s_ = Zc / max(1e-6, Zo) O = np.array([0.0, CAM, 0.0]) obj.base = O + (obj.base - O) * s_ obj.scale *= s_ obj.radius *= s_ obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s climbs the front of the %s" % (it.concept, host.name)) elif mode == "intree" and getattr(it, "hollow", None) is not None: # rule (language shift 3): an animal in a tree hole sits IN the trunk's front face: half sunk into the bark, # a dark hollow ring round it (the hole), no branch Zo = obj.base[2] Zc = max(Zo * .45, host.base[2] - .075 * host.scale) s = Zc / max(1e-6, Zo) O = np.array([0.0, CAM, 0.0]) obj.base = O + (obj.base - O) * s obj.base[0] = host.base[0] obj.scale *= s obj.radius *= s obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) oasp = float(CONCEPTS.get(it.concept, {}).get("aspect", 1.0)) obj.parts = list(obj.parts) + [ Part(lambda p, ra=(.62 * max(1.0, oasp), .68, .55): S.ellipsoid(p, np.array([0.0, .5, .5], np.float32), np.array(ra, np.float32)), (26, 18, 14), rough=1.0, spec=0.0), Part(lambda p: S.torus(np.stack([p[:, 0], p[:, 2] - .02, p[:, 1] - .5], -1) * np.array([1, 1, 1.1], np.float32), np.array([0.0, 0.0, 0.0], np.float32), .66 * max(1.0, oasp), .09), (92, 66, 44), rough=.9, tex="wood")] for a_ in ("pbox", "box"): if hasattr(obj, a_): delattr(obj, a_) trace.append("3d: %s looks out of a hollow in the %s" % (it.concept, host.name)) elif mode == "intree": # rule: an animal in a tree sits in front of the leaves on a branch that runs back into the crown Zo = obj.base[2] Zc = max(Zo * .45, Zo - .5 * host.scale * hasp) s = Zc / max(1e-6, Zo) O = np.array([0.0, CAM, 0.0]) obj.base = O + (obj.base - O) * s obj.scale *= s obj.radius *= s obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) oasp = float(CONCEPTS.get(it.concept, {}).get("aspect", 1.0)) trunk = np.array([host.base[0], obj.base[1] - .02 * obj.scale, host.base[2]]) lt = _local(obj, trunk) sx = 1.0 if anchor[0] > 0 else -1.0 obj.parts = list(obj.parts) + [Part(lambda p, a=(sx * .45 * oasp, -.03, 0.0), c=tuple(float(v) for v in lt): S.capsule(p, a, c, .07), (96, 70, 48), rough=.9, tex="wood")] obj.radius = max(obj.radius, float(np.linalg.norm(trunk - obj.center)) + .1 * obj.scale) for a_ in ("pbox", "box"): if hasattr(obj, a_): delattr(obj, a_) trace.append("3d: %s on a branch in the %s" % (it.concept, host.name)) elif mode == "front": ly = anchor[1] zf = front_at(host.parts, 0.0, ly, hasp) if zf is None: return obj.yaw = host.yaw # the sign board (model y .41-.99, centre .7, back face at z = +.04) lies on the front face k = obj.scale / host.scale c = _world(host, (0.0, ly, zf - .045 * k)) obj.base = c - np.array([0, .7 * obj.scale, 0]) obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) trace.append("3d: %s mounted on the %s's front (z=%.2f)" % (it.concept, host.name, zf)) elif mode == "hang": W, H, y0 = it.view f = float(W) if getattr(it.bound, "perch", False): # rule: a limb + what hangs from it sit at a natural depth (as if over the near ground), in the air Zt = f * CAM / max(4.0, H * .9 - y0) Zo = obj.base[2] s = Zt / max(1e-6, Zo) O = np.array([0.0, CAM, 0.0]) obj.base = O + (obj.base - O) * s obj.scale *= s obj.radius *= s obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) limb3d(it.bound, host, Zt) Zc = Zt else: # rule: under a tree the hanging thing comes forward out of the crown (half the crown's depth) Zo = obj.base[2] Zc = max(Zo * .45, Zo - .55 * host.scale * hasp) s = Zc / Zo O = np.array([0.0, CAM, 0.0]) obj.base = O + (obj.base - O) * s obj.scale *= s obj.radius *= s obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) if not getattr(it, "cord", None): trace.append("3d: %s hangs from the %s" % (it.concept, host.name)) return cx, cy = it.cord[0], it.cord[1] top = np.array([(cx - W / 2) * Zc / f, CAM - (cy - y0) * Zc / f, Zc]) lt = _local(obj, top) r = max(.012, .02 / max(.2, obj.scale / max(1e-6, host.scale))) obj.parts = list(obj.parts) + [Part(lambda p, a=(0.0, .96, 0.0), c=tuple(float(v) for v in lt): S.capsule(p, a, c, min(r, .03)), (55, 48, 42), rough=.6, spec=.3)] # the bounding sphere must reach the cord's top obj.radius = max(obj.radius, float(np.linalg.norm(top - obj.center)) + .05 * obj.scale) for a_ in ("pbox", "box"): if hasattr(obj, a_): delattr(obj, a_) trace.append("3d: %s hangs on a cord from the %s" % (it.concept, host.name))
def crack_parts(obj, trace=None): """rule (surface state "cracked"): every part's texture gets a crack network - dark fissures along Worley cell borders (two scales: wide main cracks + a finer second set), with a lighter lip beside each crack""" from . import texture as _texture for pt in obj.parts: def tex(q, base, seed, _t=pt.tex): c = _texture(_t, q, base, seed) qq = q + .06 * S.noise3(q * 6, seed + 7)[:, None] f1, f2, _ = S.worley(qq * 4.5, seed + 11) g1, g2, _ = S.worley(qq * 11, seed + 12) # (a full Voronoi network reads as tiles or a turtle shell: cracks are broken runs of it) mask = np.clip((S.fbm(q * 2.2, 3, seed + 3) - .47) * 12, 0, 1) main = (1 - np.clip((f2 - f1) / .04, 0, 1)) * mask fine = (1 - np.clip((g2 - g1) / .025, 0, 1)) * np.clip((S.fbm(q * 3, 2, seed + 13) - .58) * 12, 0, 1) crack = np.maximum(main, .8 * fine) lip = np.clip((f2 - f1 - .045) / .03, 0, 1) * (1 - np.clip((f2 - f1 - .075) / .03, 0, 1)) * mask return c * (1 - .8 * crack[:, None]) + c * .25 * lip[:, None] pt.tex = tex if trace is not None: trace.append("3d: %s drawn cracked (Worley crack network on every part)" % obj.name)
def limb3d(b, host, Z=None): """rebuild a perch host (2D: a limb reaching in from the frame edge, pydraw/perch.py) as a 3D bough at depth Z""" W, H, y0 = getattr(b, "view", (None, None, None)) if W is None: return f = float(W) Z = Z or float(host.base[2]) host.base = np.array([(b.x - W / 2) * Z / f, CAM - (b.y - y0) * Z / f, Z]) host.scale = b.h * Z / f host.yaw = 0.0 host.center = host.base + np.array([0, .5 * host.scale, 0]) Lw = b.w / max(1e-6, b.h) # the limb's box in host model units (height 1) side = 1 if b.perch_x1 > b.perch_x0 else -1 # the free end col = (105, 80, 58) x0, x1 = -side * Lw / 2, side * Lw / 2 host.parts = [Part(lambda p, a=(x0, .55, 0), c=(x1, .38, 0): S.capsule(p, a, c, .34), col, rough=.9, tex="wood"), Part(lambda p, a=(x0 + (x1 - x0) * .7, .45, 0), c=(x0 + (x1 - x0) * .7 + side * 1.1, 1.4, 0): S.capsule(p, a, c, .16), col, rough=.9, tex="wood")] host.radius = host.scale * (.3 + .5 * math.sqrt(1 + 2 * Lw ** 2)) for a_ in ("pbox", "box"): if hasattr(host, a_): delattr(host, a_)85 unmodified lines868788899091485 unmodified lines57757857958058158224 unmodified lines6076086096106116126134 unmodified lines618619620621622623120 unmodified lines74474574674774874912 unmodified lines76276376476576676776885 unmodified lines# ---------------------------------------------------------------- heads with expressionsdef head3d(lk, c, r, expr, chibi, k=0):"""front-facing species head centred at c (radius r, looking -z) -> (parts, Head anchors)"""c = np.asarray(c, float)kind = lk["kind"]fur = tuple(lk["fur"])485 unmodified lines# ---------------------------------------------------------------- wearables on body anchorsdef body_wear(wear, B, f=1):"""neckwear / cape / backpack / apron with body anchors B: neck (front point), neck_r, chest_z (front surface zat mid chest), back_z, sh_y (shoulder y), sw (shoulder half width), hip_y, ground (y), torso (SDF or None)"""24 unmodified linesP.append(Part(lambda p: np.minimum(S.torus(p, nc, Rn, nr * .38) if True else 0,flat_rcone(tail[0], tail[1], nr * .35, nr * .4, .35)(p)), c, k=nr * .2, spec=.15, rough=.8, tex="fur"))elif it == "cape":c = col or (200, 35, 40)y1, y0 = B["sh_y"], B["ground"] + (B["sh_y"] - B["ground"]) * .06zb, sw = B["back_z"], B["sw"]4 unmodified linesd = np.maximum(np.abs(p[:, 2] - zc) - sw * .05, np.abs(p[:, 0]) - w)d = np.maximum(d, np.maximum(p[:, 1] - y1, y0 - p[:, 1]))return d * .8P.append(Part(cape, c, spec=.25, rough=.55))P.append(Part(lambda p: S.torus(p, np.array([N[0], B["sh_y"] + nr * .1, (N[2] + zb) * .5]), abs(zb - N[2]) * .5 + nr * .2, nr * .2), _dk(c, .8),spec=.25, rough=.55))120 unmodified linespc = tuple(lk["hooves"]) if lk.get("hooves") else _lt(legc, .12)paws = [lambda p, s=s: S.ellipsoid(p, np.array([s * .1, .035, -.2]), np.array([.065, .036, .075])) for s in (-1, 1)]paws += [lambda p, s=s: S.ellipsoid(p, np.array([s * .25, .03, -.07]), np.array([.07, .032, .1])) for s in (-1, 1)]P.append(Part(_U(paws), pc, spec=.15, rough=.7))P += tail3d(lk, np.array([-f * .12, .06, .22]), expr, 1.0, f)if lk.get("spikes"):12 unmodified linesif expr in ("sad", "crying", "sleepy"):hc = hc + np.array([0, -.03, -.01])B = dict(neck=hc + np.array([0, -hrr * .92, -hrr * .5]), neck_r=hrr * .5, chest_z=-.25, back_z=.25, sh_y=bh * .9, sw=.2, hip_y=.15,ground=0.0, torso=body)hp, H = head3d(lk, hc, hrr, expr, chibi)P += hp# clothes on a sitting body: a coat over the chest and back85 unmodified lines8687888990919293485 unmodified lines57958058158258358458558658758858959059159259359459559624 unmodified lines6216226236246256266276284 unmodified lines633634635636637638639640641642643644645646647648649650651652653120 unmodified lines77477577677777877978078178278378478578612 unmodified lines79980080180280380480585 unmodified lines# ---------------------------------------------------------------- heads with expressionsdef head3d(lk, c, r, expr, chibi, k=0):"""front-facing species head centred at c (radius r, looking -z) -> (parts, Head anchors)"""if expr == "asleep":expr = "sleepy" # night: a dozing character (pixel: shut eyes + z's) shuts its eyes in 3D tooc = np.asarray(c, float)kind = lk["kind"]fur = tuple(lk["fur"])485 unmodified lines# ---------------------------------------------------------------- wearables on body anchorsdef _on(name):import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get(name, "1") != "0"def _cape2():import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get("cape2", "1") != "0"def body_wear(wear, B, f=1):"""neckwear / cape / backpack / apron with body anchors B: neck (front point), neck_r, chest_z (front surface zat mid chest), back_z, sh_y (shoulder y), sw (shoulder half width), hip_y, ground (y), torso (SDF or None)"""24 unmodified linesP.append(Part(lambda p: np.minimum(S.torus(p, nc, Rn, nr * .38) if True else 0,flat_rcone(tail[0], tail[1], nr * .35, nr * .4, .35)(p)), c, k=nr * .2, spec=.15, rough=.8, tex="fur"))elif it == "cape":from pydraw.characters import cape_defaultc = col or cape_default(B.get("fur"))y1, y0 = B["sh_y"], B["ground"] + (B["sh_y"] - B["ground"]) * .06zb, sw = B["back_z"], B["sw"]4 unmodified linesd = np.maximum(np.abs(p[:, 2] - zc) - sw * .05, np.abs(p[:, 0]) - w)d = np.maximum(d, np.maximum(p[:, 1] - y1, y0 - p[:, 1]))return d * .8if _cape2():# rule (night, cape2): the cape flares well past the body (seen from the front it frames both sides),# billows back, ripples in vertical folds and its hem is scalloped and lifts at the far cornersH_ = max(y1 - y0, 1e-3)fw = max(sw, B.get("body_w", sw))def cape(p, y1=y1, y0=y0, zb=zb, sw=sw, H_=H_, fw=fw):t = np.clip((y1 - p[:, 1]) / H_, 0, 1)zc = zb + sw * .12 + t * t * fw * .9 + np.sin(p[:, 0] / max(fw, 1e-3) * 4.2) * fw * .09 * tw = sw * 1.0 + t * (fw * 1.6 - sw * .3)hem = y0 + H_ * (.04 * np.abs(np.sin(p[:, 0] / max(fw, 1e-3) * 2.4)) + .1 * (np.abs(p[:, 0]) / max(fw * 1.9, 1e-3)) ** 2)d = np.maximum(np.abs(p[:, 2] - zc) - sw * .05, np.abs(p[:, 0]) - w)d = np.maximum(d, np.maximum(p[:, 1] - y1, hem - p[:, 1]))return d * .55P.append(Part(cape, c, spec=.25, rough=.55))P.append(Part(lambda p: S.torus(p, np.array([N[0], B["sh_y"] + nr * .1, (N[2] + zb) * .5]), abs(zb - N[2]) * .5 + nr * .2, nr * .2), _dk(c, .8),spec=.25, rough=.55))120 unmodified linespc = tuple(lk["hooves"]) if lk.get("hooves") else _lt(legc, .12)paws = [lambda p, s=s: S.ellipsoid(p, np.array([s * .1, .035, -.2]), np.array([.065, .036, .075])) for s in (-1, 1)]paws += [lambda p, s=s: S.ellipsoid(p, np.array([s * .25, .03, -.07]), np.array([.07, .032, .1])) for s in (-1, 1)]bw_ = next((w for w in wear if w.get("item") == "boots"), None)if bw_ is not None and _cape2() and _on("outfit2"):# rule (night, outfit2): boots on a sitting character = paws in the boot colour + shafts up the front legsfrom pydraw.character2d import _boot_defaultpc = tuple(bw_["color"]) if bw_.get("color") else _boot_default(fur)shafts = [lambda p, s=s: S.capsule(p, np.array([s * .1, .14, -.165]), np.array([s * .1, .04, -.18]), .065) for s in (-1, 1)]P.append(Part(_U(shafts), pc, spec=.4, rough=.45))P.append(Part(_U(paws), pc, spec=.15, rough=.7))P += tail3d(lk, np.array([-f * .12, .06, .22]), expr, 1.0, f)if lk.get("spikes"):12 unmodified linesif expr in ("sad", "crying", "sleepy"):hc = hc + np.array([0, -.03, -.01])B = dict(neck=hc + np.array([0, -hrr * .92, -hrr * .5]), neck_r=hrr * .5, chest_z=-.25, back_z=.25, sh_y=bh * .9, sw=.2, hip_y=.15,ground=0.0, torso=body, body_w=.3, fur=fur)hp, H = head3d(lk, hc, hrr, expr, chibi)P += hp# clothes on a sitting body: a coat over the chest and back
123429 unmodified lines34353637383971 unmodified lines11111211311411511611732 unmodified lines15015115215315415538 unmodified lines1941951961971981991 unmodified line20120220320420520620759 unmodified lines26726826927027127229 unmodified lines30230330430530630730830931031131231331431531631731831932032132240 unmodified lines36336436536636736836937021 unmodified lines3923933943953963977 unmodified lines405406407408409410411"""Scene compiler (experimental, PYDRAW3D_EXP=compile=1; default off).A placed scene's SDF (every Part.fn of every Obj, the ground / back wall / street facades / world heightfield) becomesONE C kernel: each part closure is traced symbolically (tracer.py) into an expression DAG, emitted as a C function29 unmodified lines_LIBS = {} # source hash -> ctypes lib_PART_CACHE = {} # id(fn) -> (fn, body or None, err, node count, speculative)OS_, PS_ = 20, 9SP_N = 1771 unmodified linesbreakSTATS["trace_s"] += time.time() - t0_PART_CACHE[id(fn)] = (fn,) + res + (fp, False)if fp is not None and res[0] is not None:_FP_CACHE[fp] = res_disk_put(fp, res)return res32 unmodified lineslib.pd_soft_shadow.argtypes = [V, I, V, V, D, D, D, I, D, D, V]lib.pd_ambient_occ.argtypes = [V, I, V, V, D, D, V]lib.pd_part_index.argtypes = [V, I, I, V, V, V]lib.pd_gi.argtypes = [V, I, V, V, V, I, V, V, V, V, V, V, V, D, D, I, I, V, I, V]_LIBS[h] = libreturn lib, h, dt38 unmodified linesfid = bodies.setdefault(body, len(bodies))row.append(fid)per_obj.append(row)self.fallbacks = failsself.n_spec = specif fails:1 unmodified lineself.ok = Falsereturnfuncs = []for body, fid in bodies.items():funcs.append(body.replace("PARTFN", "part_%d" % fid, 1))disp = ["static double eval_part(int fid, double x, double y, double z) {", " switch (fid) {"]disp += [" case %d: return part_%d(x, y, z);" % (fid, fid) for fid in range(len(bodies))]59 unmodified linesself.S = Scene(_ptr(self.sp).value, _ptr(self.ot).value, _ptr(self.pt).value,_ptr(self.hs).value if self.hs is not None else None, _ptr(self.skip).value, len(objs))self.Sp = ctypes.byref(self.S)self.ok = Trueself.verify_err = self._verify(objs, per_obj)if self.verify_err is not None:29 unmodified linesfin = np.isfinite(ref)if (np.isfinite(got) != fin).any():return (o.name, j, "verify: finite/non-finite mismatch")err = np.abs(got[fin] - ref[fin]) / np.maximum(1.0, np.abs(ref[fin]))e = float(err.max()) if err.size else 0.0worst = max(worst, e)if e > TOL:return (o.name, j, "verify: max rel err %.2e" % e)if fp is not None and not light:if fp not in VERIFIED:VERIFIED.add(fp)_disk_put(fp, _FP_CACHE[fp], verified=True)STATS["verify_s"] += time.time() - t0self.verify_max = worstreturn None# ---------------------------------------------------------------- kernelsdef set_skip(self):sk = getattr(self.scene, "skip", ())self.skip[:] = 0for k in sk:40 unmodified linesfloat(margin), float(grow), _ptr(out))return outdef part_index(self, k, P):"""Obj.part_index's argmin (margin .05 bounds), object k; the local points stay numpy's (exact)"""P = _f64c(P).reshape(-1, 3)idx = np.empty(len(P), np.int64)Q = np.empty((len(P), 3))21 unmodified linesreturn outdef _sig(scene):w = scene.worldreturn (tuple(id(o) for o in scene.objs), id(w), scene.ground, scene.backdrop_z, scene.cove, scene.street)7 unmodified linesreturn ck[1]try:cs = CompiledScene(scene, accel_mod, accel_on)except RuntimeError as e:FALLBACKS.append(("<scene>", -1, str(e)[:300]))cs = Noneif cs is not None and not cs.ok:123429 unmodified lines3435363738394041424371 unmodified lines11511611711811912012132 unmodified lines15415515615715815916016138 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402411 unmodified line24324424524624724824925025125259 unmodified lines31231331431531631731829 unmodified lines34834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340 unmodified lines44444544644744844945045145245345445545645745845921 unmodified lines4814824834844854864874884894904917 unmodified lines499500501502503504505"""Scene compiler (default ON since the night wave; PYDRAW3D_EXP=compile=0 turns it off).A placed scene's SDF (every Part.fn of every Obj, the ground / back wall / street facades / world heightfield) becomesONE C kernel: each part closure is traced symbolically (tracer.py) into an expression DAG, emitted as a C function29 unmodified lines_LIBS = {} # source hash -> ctypes lib_PART_CACHE = {} # id(fn) -> (fn, body or None, err, node count, speculative)import re as _re_SIMRE = _re.compile(r"SIMKEY\d+")_SIMKIND = {"sphere": 0, "tube": 1, "tri": 2, "inst": 3, "mls": 4, "tab": 5}OS_, PS_ = 20, 9SP_N = 1771 unmodified linesbreakSTATS["trace_s"] += time.time() - t0_PART_CACHE[id(fn)] = (fn,) + res + (fp, False)if fp is not None and res[0] is not None and "SIMKEY" not in res[0]: # (sim keys are per process)_FP_CACHE[fp] = res_disk_put(fp, res)return res32 unmodified lineslib.pd_soft_shadow.argtypes = [V, I, V, V, D, D, D, I, D, D, V]lib.pd_ambient_occ.argtypes = [V, I, V, V, D, D, V]lib.pd_part_index.argtypes = [V, I, I, V, V, V]lib.pd_sim_set.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, V, V, D, D, D, V, V, V, V, V]lib.pd_shadow_dirs.argtypes = [V, I, V, V, V, D, D, I, D, V]lib.pd_gi.argtypes = [V, I, V, V, V, I, V, V, V, V, V, V, V, D, D, I, I, V, I, V]_LIBS[h] = libreturn lib, h, dt38 unmodified linesfid = bodies.setdefault(body, len(bodies))row.append(fid)per_obj.append(row)# night wave: simulation fields (pydraw3d/sim/fields.py) traced as sim(slot, x, y, z) nodes; copies placed by an# instance field need their own part functionsself.sims = []slots = {}todo = [b for b in bodies]while todo and not fails:b = todo.pop()for key in _SIMRE.findall(b):if key in slots:continuefrom ..sim import fields as _Ff = _F._SIMREG.get(key)if f is None:fails.append(("<sim>", -1, "unknown sim field %s" % key))breakg = _F.sim_grid(f)el = g["el"]if g["kind"] == "inst":fmap = []for ifn in g["fns"]:ib, ierr = trace_part(ifn)[:2]if ib is None:fails.append(("<sim copy>", -1, ierr))breakif ib not in bodies:bodies[ib] = len(bodies)todo.append(ib)fmap.append(bodies[ib])if fails:breakel = el.copy()el[:, 0] = np.asarray(fmap, float)[el[:, 0].astype(np.int64)]slots[key] = len(self.sims)self.sims.append(dict(g, el=_f64c(el), kind_id=_SIMKIND[g["kind"]]))if len(self.sims) > 512:fails.append(("<sim>", -1, "too many sim fields"))self.fallbacks = failsself.n_spec = specif fails:1 unmodified lineself.ok = Falsereturnfuncs = []# (parts reading only exact tables - lerp2 - keep the strict numeric check)self.simfid = {fid for body, fid in bodies.items() if any(self.sims[slots[k_]]["kind"] != "tab" for k_ in _SIMRE.findall(body))}for body, fid in bodies.items():body = _SIMRE.sub(lambda m: str(slots[m.group(0)]), body)funcs.append(body.replace("PARTFN", "part_%d" % fid, 1))disp = ["static double eval_part(int fid, double x, double y, double z) {", " switch (fid) {"]disp += [" case %d: return part_%d(x, y, z);" % (fid, fid) for fid in range(len(bodies))]59 unmodified linesself.S = Scene(_ptr(self.sp).value, _ptr(self.ot).value, _ptr(self.pt).value,_ptr(self.hs).value if self.hs is not None else None, _ptr(self.skip).value, len(objs))self.Sp = ctypes.byref(self.S)self._bind()self.ok = Trueself.verify_err = self._verify(objs, per_obj)if self.verify_err is not None:29 unmodified linesfin = np.isfinite(ref)if (np.isfinite(got) != fin).any():return (o.name, j, "verify: finite/non-finite mismatch")if per_obj[k][j] in self.simfid and not light:# extra test points around the elements of every sim field (in case the part is the field itself)rs = np.random.RandomState(1)ex = []for g in self.sims:if g["kind"] == "tab":continueii = rs.randint(0, len(g["ec"]), 400)ex.append(g["ec"][ii] + rs.normal(0, 1, (400, 3)) * g["er"][ii, None])q2 = np.ascontiguousarray(np.concatenate(ex), float) if ex else np.zeros((0, 3))with np.errstate(all="ignore"):r2 = np.asarray(pt.fn(q2), float).reshape(-1)g2 = np.empty(len(q2))self.lib.pd_eval_part(per_obj[k][j], len(q2), _ptr(q2), _ptr(g2))ref, got = np.concatenate([ref, r2]), np.concatenate([got, g2])fin = np.isfinite(ref)if per_obj[k][j] in self.simfid:# sim fields: C (grid cells) is exact below M; numpy (k nearest) is exact near the surface and a# looser lower bound elsewhere (checked offline: bench/simgrid_check.py). numpy is always a lower# bound, so where C is below M (exact) numpy must not exceed it; C must not exceed numpy far aboveMmin = min([g["M"] for g in self.sims if g["kind"] != "tab"] or [0.0])low = fin & (got < .5 * Mmin) & (ref > got + 1e-6 * np.maximum(1, np.abs(got)))if low.sum() > max(2, .01 * fin.sum()):return (o.name, j, "verify: sim field below a numpy bound at %d of %d points" % (low.sum(), fin.sum()))continueerr = np.abs(got[fin] - ref[fin]) / np.maximum(1.0, np.abs(ref[fin]))e = float(err.max()) if err.size else 0.0worst = max(worst, e)if e > TOL:return (o.name, j, "verify: max rel err %.2e" % e)if fp is not None and not light:if fp not in VERIFIED and fp in _FP_CACHE:VERIFIED.add(fp)_disk_put(fp, _FP_CACHE[fp], verified=True)STATS["verify_s"] += time.time() - t0self.verify_max = worstreturn Nonedef _bind(self):"""point the runtime's sim slots at this scene's fields (a cached lib can be shared by scenes of equal source)"""if getattr(self.lib, "_pd_owner", None) is self:returnfor k, g in enumerate(self.sims):self.lib.pd_sim_set(k, g["kind_id"], g["stride"], _ptr(g["el"]), _ptr(_f64c(g["box"])), g["h"], g["M"], g["pad"],_ptr(g["nc"]), _ptr(g["start"]), _ptr(g["items"]), _ptr(g["lb"]), _ptr(g["prm"]))self.lib._pd_owner = self# ---------------------------------------------------------------- kernelsdef set_skip(self):self._bind()sk = getattr(self.scene, "skip", ())self.skip[:] = 0for k in sk:40 unmodified linesfloat(margin), float(grow), _ptr(out))return outdef shadow_dirs(self, P, Ld, tmax, scl, k, steps, margin):self.set_skip()P, Ld, tm = _f64c(P), _f64c(Ld), _f64c(np.broadcast_to(tmax, (len(P),)))out = np.empty(len(P))self.lib.pd_shadow_dirs(self.Sp, len(P), _ptr(P), _ptr(Ld), _ptr(tm), float(scl), float(k), int(steps), float(margin), _ptr(out))return outdef part_index(self, k, P):"""Obj.part_index's argmin (margin .05 bounds), object k; the local points stay numpy's (exact)"""self._bind()P = _f64c(P).reshape(-1, 3)idx = np.empty(len(P), np.int64)Q = np.empty((len(P), 3))21 unmodified linesreturn outdef traceable(o):"""every part of object o traces to C"""return all(trace_part(pt.fn)[0] is not None for pt in o.parts)def _sig(scene):w = scene.worldreturn (tuple(id(o) for o in scene.objs), id(w), scene.ground, scene.backdrop_z, scene.cove, scene.street)7 unmodified linesreturn ck[1]try:cs = CompiledScene(scene, accel_mod, accel_on)except Exception as e: # (gcc failed or missing, cache dir unwritable: numpy fallback)FALLBACKS.append(("<scene>", -1, str(e)[:300]))cs = Noneif cs is not None and not cs.ok:
91 unmodified lines92939495969791 unmodified linese = ("pd_sign(%s)" if n.dt == "f" else "pd_isign(%s)") % a[0]elif op == "isfinite":e = "pd_isfinite(%s)" % a[0]elif op == "isnan":e = "(%s != %s)" % (a[0], a[0])else:91 unmodified lines929394959697989991 unmodified linese = ("pd_sign(%s)" if n.dt == "f" else "pd_isign(%s)") % a[0]elif op == "isfinite":e = "pd_isfinite(%s)" % a[0]elif op == "sim": # night wave: a simulation field (runtime.c pd_sim); the key becomes a slot number per scenee = "pd_sim(%s, %s, %s, %s)" % (n.val, a[0], a[1], a[2])elif op == "isnan":e = "(%s != %s)" % (a[0], a[0])else:
46 unmodified lines474849505152197 unmodified lines25025125225325425546 unmodified linesstatic double eval_part(int fid, double x, double y, double z);/* scene parameter vector sp[] */enum { SP_GROUND, SP_HAS_BACK, SP_BACK_Z, SP_COVE, SP_HAS_STREET, SP_ST_ZF, SP_ST_M, SP_ST_SEED, SP_ACCEL, SP_HAS_WORLD,SP_W_Z0, SP_W_U0, SP_W_DU, SP_W_NU, SP_W_V0, SP_W_DV, SP_W_NV, SP_N };197 unmodified lines}}void pd_ambient_occ(const Scene *S, int64_t n, const double *P, const double *N, double scale, double margin, double *out) {#pragma omp parallel for schedule(dynamic, 256) if(n > 1024)for (int64_t i = 0; i < n; i++) {46 unmodified lines4748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198197 unmodified lines39639739839940040140240340440540640740840941041141241341441541641741841942042146 unmodified linesstatic double eval_part(int fid, double x, double y, double z);/* ---- simulation fields (night wave): unions of many elements (spheres, tapered tubes, thin triangles, placed copies* of a traced part) over a uniform grid. Each cell lists every element whose bounding sphere comes within M of the* cell, so the min over the list is EXACT wherever it is < M; unlisted elements are >= M away and >= a bound blended* from the corner lower bounds lb (a lower bound, safe for marching). Outside the grid box (padded by pad >= M): box distance + pad. Data set from python by pd_sim_set. */enum { SK_SPHERE, SK_TUBE, SK_TRI, SK_INST, SK_MLS, SK_TAB };typedef struct {int kind, stride;const double *el;double lo[3], hi[3], h, M, pad, prm[4];int64_t nc[3];const int64_t *start, *items;const double *lb;} SimField;#define PD_NSIM 512static SimField SIMF[PD_NSIM];void pd_sim_set(int slot, int kind, int stride, const double *el, const double *box, double h, double M, double pad, const int64_t *nc,const int64_t *start, const int64_t *items, const double *lb, const double *prm) {SimField *f = &SIMF[slot];f->kind = kind; f->stride = stride; f->el = el;for (int j = 0; j < 3; j++) { f->lo[j] = box[j]; f->hi[j] = box[3 + j]; f->nc[j] = nc[j]; }for (int j = 0; j < 4; j++) f->prm[j] = prm[j];f->h = h; f->M = M; f->pad = pad; f->start = start; f->items = items; f->lb = lb;}static inline double sim_seg(double px, double py, double pz, const double *e, double *hh) {double pax = px - e[0], pay = py - e[1], paz = pz - e[2];double bax = e[3] - e[0], bay = e[4] - e[1], baz = e[5] - e[2];double bb = bax * bax + bay * bay + baz * baz;double h = (pax * bax + pay * bay + paz * baz) / (bb > 1e-12 ? bb : 1e-12);h = h < 0 ? 0 : (h > 1 ? 1 : h);double vx = pax - h * bax, vy = pay - h * bay, vz = paz - h * baz;*hh = h;return sqrt(vx * vx + vy * vy + vz * vz);}static inline double seg3(double px, double py, double pz, const double *a, const double *b) {double e[6] = {a[0], a[1], a[2], b[0], b[1], b[2]}, h;return sim_seg(px, py, pz, e, &h);}static double sim_tri(double px, double py, double pz, const double *e) {const double *a = e, *b = e + 3, *c = e + 6;double ab[3] = {b[0] - a[0], b[1] - a[1], b[2] - a[2]}, ac[3] = {c[0] - a[0], c[1] - a[1], c[2] - a[2]};double n[3] = {ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]};double nn = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) + 1e-12;n[0] /= nn; n[1] /= nn; n[2] /= nn;double dpl = (px - a[0]) * n[0] + (py - a[1]) * n[1] + (pz - a[2]) * n[2];double pr[3] = {px - dpl * n[0], py - dpl * n[1], pz - dpl * n[2]};const double *V[3] = {a, b, c};int inside = 1;for (int s = 0; s < 3; s++) {const double *u = V[s], *v = V[(s + 1) % 3];double vu[3] = {v[0] - u[0], v[1] - u[1], v[2] - u[2]}, pu[3] = {pr[0] - u[0], pr[1] - u[1], pr[2] - u[2]};double cr[3] = {vu[1] * pu[2] - vu[2] * pu[1], vu[2] * pu[0] - vu[0] * pu[2], vu[0] * pu[1] - vu[1] * pu[0]};if (cr[0] * n[0] + cr[1] * n[1] + cr[2] * n[2] < 0) { inside = 0; break; }}if (inside) return fabs(dpl);double e1 = seg3(px, py, pz, a, b), e2 = seg3(px, py, pz, b, c), e3 = seg3(px, py, pz, c, a);return pd_min(pd_min(e1, e2), e3);}static inline double sim_elem(const SimField *f, int64_t i, double px, double py, double pz) {const double *e = f->el + i * f->stride;switch (f->kind) {case SK_SPHERE: {double dx = px - e[0], dy = py - e[1], dz = pz - e[2];return sqrt(dx * dx + dy * dy + dz * dz) - e[3];}case SK_TUBE: {double h, sd = sim_seg(px, py, pz, e, &h);return sd - (e[6] * (1 - h) + e[7] * h);}case SK_TRI:return sim_tri(px, py, pz, e) - e[9];default: { /* fid, s, t[3], R[9] (local -> world); q = R^T (p - t) / s */double s = e[1], dx = px - e[2], dy = py - e[3], dz = pz - e[4];const double *R = e + 5;double qx = (dx * R[0] + dy * R[3] + dz * R[6]) / s;double qy = (dx * R[1] + dy * R[4] + dz * R[7]) / s;double qz = (dx * R[2] + dy * R[5] + dz * R[8]) / s;return eval_part((int)e[0], qx, qy, qz) * s;}}}static double pd_sim(int slot, double px, double py, double pz) {const SimField *f = &SIMF[slot];if (f->kind == SK_TAB) { /* fields.lerp2: bilinear T[v, u], u / v clamped to the table (pz unused) */int64_t nx = f->nc[0], ny = f->nc[1];double u = pd_clip(px, 0, nx - 1.001), v = pd_clip(py, 0, ny - 1.001);int64_t iu = (int64_t)u, iv = (int64_t)v;double fu = u - iu, fv = v - iv;const double *T = f->el;return T[iv * nx + iu] * (1 - fu) * (1 - fv) + T[iv * nx + iu + 1] * fu * (1 - fv) + T[(iv + 1) * nx + iu] * (1 - fu) * fv+ T[(iv + 1) * nx + iu + 1] * fu * fv;}double ox = pd_max(pd_max(f->lo[0] - px, px - f->hi[0]), 0), oy = pd_max(pd_max(f->lo[1] - py, py - f->hi[1]), 0),oz = pd_max(pd_max(f->lo[2] - pz, pz - f->hi[2]), 0);if (ox > 0 || oy > 0 || oz > 0) return sqrt(ox * ox + oy * oy + oz * oz) + f->pad;int64_t ix = (int64_t)((px - f->lo[0]) / f->h), iy = (int64_t)((py - f->lo[1]) / f->h), iz = (int64_t)((pz - f->lo[2]) / f->h);ix = ix < 0 ? 0 : (ix >= f->nc[0] ? f->nc[0] - 1 : ix);iy = iy < 0 ? 0 : (iy >= f->nc[1] ? f->nc[1] - 1 : iy);iz = iz < 0 ? 0 : (iz >= f->nc[2] ? f->nc[2] - 1 : iz);int64_t c = (ix * f->nc[1] + iy) * f->nc[2] + iz;/* bound for the unlisted elements: max(M, sum_i w_i (L(c_i) - |p - c_i|)) over the 8 cell corners (trilinear w) */double ux = (px - f->lo[0]) / f->h - ix, uy = (py - f->lo[1]) / f->h - iy, uz = (pz - f->lo[2]) / f->h - iz;int64_t n1 = f->nc[1] + 1, n2 = f->nc[2] + 1;double B = 0;for (int a = 0; a < 2; a++) for (int b = 0; b < 2; b++) for (int e = 0; e < 2; e++) {double w = (a ? ux : 1 - ux) * (b ? uy : 1 - uy) * (e ? uz : 1 - uz);double dx = (ux - a) * f->h, dy = (uy - b) * f->h, dz = (uz - e) * f->h;B += w * (f->lb[((ix + a) * n1 + iy + b) * n2 + iz + e] - sqrt(dx * dx + dy * dy + dz * dz));}if (f->kind == SK_MLS) {/* cloth (fields.sheet_mls): blend of the 4 nearest vertices' tangent planes; prm = (edge h, thickness) */double hh = f->prm[0], th = f->prm[1], kd[4]; int64_t ki[4]; int nk = 0;for (int64_t j = f->start[c]; j < f->start[c + 1]; j++) {const double *e = f->el + f->items[j] * 6;double dx = px - e[0], dy = py - e[1], dz = pz - e[2], dd = sqrt(dx * dx + dy * dy + dz * dz);int q = nk < 4 ? nk++ : 4;if (q == 4) { if (dd >= kd[3]) continue; q = 3; }while (q > 0 && kd[q - 1] > dd) { kd[q] = kd[q - 1]; ki[q] = ki[q - 1]; q--; }kd[q] = dd; ki[q] = f->items[j];}if (nk == 0) return pd_max(B + 2.5 * hh - th, 2.5 * hh - th);if (kd[0] > 2 * hh) return kd[0] - hh - th;double ws = 0, acc = 0, s0 = 0;for (int a = 0; a < nk; a++) {const double *e = f->el + ki[a] * 6;double w = 1.0 / ((kd[a] + .3 * hh) * (kd[a] + .3 * hh));double sa = (px - e[0]) * e[3] + (py - e[1]) * e[4] + (pz - e[2]) * e[5];if (a == 0) s0 = sa;ws += w; acc += w * sa;}double sd = fabs(acc / ws), lat = sqrt(pd_max(kd[0] * kd[0] - s0 * s0, 0));return (pd_max(sd, lat - .75 * hh) - th) * .8;}double d = pd_max(B, f->M);for (int64_t j = f->start[c]; j < f->start[c + 1]; j++) {double v = sim_elem(f, f->items[j], px, py, pz);if (v < d) d = v;}return d;}/* scene parameter vector sp[] */enum { SP_GROUND, SP_HAS_BACK, SP_BACK_Z, SP_COVE, SP_HAS_STREET, SP_ST_ZF, SP_ST_M, SP_ST_SEED, SP_ACCEL, SP_HAS_WORLD,SP_W_Z0, SP_W_U0, SP_W_DU, SP_W_NU, SP_W_V0, SP_W_DV, SP_W_NV, SP_N };197 unmodified lines}}/* night wave: light.py _shadow_dirs (soft shadow toward a point light, per-point direction and length) */void pd_shadow_dirs(const Scene *S, int64_t n, const double *P, const double *Ld, const double *tmax, double scl, double k,int64_t steps, double margin, double *out) {#pragma omp parallel for schedule(dynamic, 64) if(n > 512)for (int64_t i = 0; i < n; i++) {double px = P[3 * i], py = P[3 * i + 1], pz = P[3 * i + 2];const double *L = Ld + 3 * i;double res = 1, t = .03 * scl;int active = t < tmax[i];for (int64_t s = 0; s < steps && active; s++) {double d = scene_dist1(S, px + L[0] * t, py + L[1] * t, pz + L[2] * t, NULL, margin, NULL);double r = pd_min(res, pd_clip(k * d / t, 0, 1));res = r;t = t + pd_clip(d, .01 * scl, .3 * scl);active = (t < tmax[i]) && (r > .003);}out[i] = pow(res, 1.5);}}void pd_ambient_occ(const Scene *S, int64_t n, const double *P, const double *N, double scale, double margin, double *out) {#pragma omp parallel for schedule(dynamic, 256) if(n > 1024)for (int64_t i = 0; i < n; i++) {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""Conditions on any 3D model (parity with pydraw/condition_px.py): the parser's attrs["cond"] (pydraw/language.py)re-dress a model's parts after it is built. Model frame: base on y=0, about one unit tall, centred on x=0.
surface rusty / mossy / moldy / dirty / burnt / weathered / withered / frosty / wet / torn / broken: the part's texture is wrapped (the old texture first, then the condition mixed in by 3D noise), plus spec / rough light shiny -> high spec, low rough (and a touch of metal on grey things); glowing -> emissive shape twisted (domain warp: sideways wave growing with height + lean), stout / thin (wider / narrower in x and z); the SDF is scaled down by the warp's stretch so marching stays safeKnob: PYDRAW_LANG_OFF=cond3d (or PYDRAW_LANG=0)."""import numpy as np
from . import sdf as S
def _lin(c): return (np.asarray(c, float) / 255.0) ** 2.2
def _mixer(kind, seed): """texture post-function (q, albedo) -> albedo for a surface condition""" rust, moss, mold, dirt, char = _lin((150, 72, 30)), _lin((68, 112, 44)), _lin((150, 160, 120)), _lin((92, 76, 58)), _lin((26, 20, 18)) rime, dry = _lin((236, 244, 255)), _lin((150, 112, 62))
def f(q, a): if kind == "rusty": n = S.fbm(q * 7, 3, seed) t = np.clip((n - .45) * 3.2, 0, .85)[:, None] return a * (1 - t) + rust * t * (.7 + .5 * S.noise3(q * 40, seed + 1)[:, None]) if kind == "mossy": n = S.fbm(q * 6, 3, seed) + np.clip(.35 - q[:, 1], 0, .35) t = np.clip((n - .55) * 3, 0, .9)[:, None] return a * (1 - t) + moss * t * (.75 + .5 * S.noise3(q * 50, seed + 2)[:, None]) if kind == "moldy": t = (S.noise3(q * 22, seed) > .72)[:, None] * .75 return a * (1 - t) + mold * t if kind == "dirty": n = S.fbm(q * 6, 3, seed) + (1 - np.clip(q[:, 1], 0, 1)) * .35 t = np.clip((n - .6) * 2.5, 0, .7)[:, None] return a * (1 - t) + dirt * t if kind == "burnt": n = S.fbm(q * 5, 3, seed) t = np.clip(.7 + (n - .3) * 1.2, .55, .95)[:, None] # mostly charred, a few lighter scorched patches return a * (1 - t) + char * t if kind == "weathered": L = (a * np.array([.3, .59, .11])).sum(1, keepdims=True) g = (a * .4 + L * .6 * np.array([1.02, 1.0, .94])) * .72 + np.array([.06, .05, .035]) return g * (.7 + .45 * S.noise3(q * np.array([60, 5, 60]), seed)[:, None]) if kind == "withered": L = (a * np.array([.3, .59, .11])).sum(1, keepdims=True) return a * .35 + dry * (L / max(1e-3, float((dry * np.array([.3, .59, .11])).sum()))) * .65 if kind == "frosty": up = np.clip((S.noise3(q * 30, seed) - .3) * 2, 0, 1)[:, None] * .6 return a * .75 * (1 - up) + rime * (up + .25 * (1 - up)) if kind == "wet": L = (a * np.array([.3, .59, .11])).sum(1, keepdims=True) return np.clip((L + (a - L) * 1.25) * .7, 0, 1) if kind == "torn": t = (S.fbm(q * 9, 3, seed) > .6)[:, None] * .85 # dark rips (3D keeps the surface; the pixel pass cuts holes) return a * (1 - t) if kind == "broken": n = np.abs(S.noise3(q * 14, seed) - .5) t = (n < .03)[:, None] * .8 return a * (1 - t) return a return f
SURFACE = {"rusty": (.15, .9), "mossy": (.05, .95), "moldy": (.05, .9), "dirty": (.08, .9), "burnt": (.05, .95), "weathered": (.06, .9), "withered": (.05, .9), "frosty": (.4, .4), "wet": (.7, .12), "torn": (None, None), "broken": (None, None)}
def _wrap_tex(pt, kind, seed): old = pt.tex mix = _mixer(kind, seed)
def tex(q, base, s, _old=old): from . import texture return mix(q, texture(_old, q, base, s)) pt.tex = tex sp, ro = SURFACE[kind] if sp is not None: pt.spec, pt.rough = sp, ro
def _warp(pt, kind, seed): f0 = pt.fn if kind == "twisted": amp, lean = .09, .06 * (1 if seed % 2 else -1)
def fn(p, _f=f0): q = p.copy() y = np.clip(q[:, 1], 0, None) q[:, 0] = q[:, 0] - (amp * np.sin(y * 6.9 + seed % 7) * y ** .7 + lean * y) return _f(q.astype(np.float32)) * .7 else: k = 1.3 if kind == "stout" else .75
def fn(p, _f=f0): q = p.copy() q[:, 0] = q[:, 0] / k q[:, 2] = q[:, 2] / k return _f(q.astype(np.float32)) * min(k, 1.0) pt.fn = fn old = pt.tex if callable(old): if kind == "twisted": def tex(q, base, s, _t=old): q2 = q.copy() y = np.clip(q2[:, 1], 0, None) q2[:, 0] = q2[:, 0] - (amp * np.sin(y * 6.9 + seed % 7) * y ** .7 + lean * y) return _t(q2, base, s) else: def tex(q, base, s, _t=old): q2 = q.copy() q2[:, 0] /= k q2[:, 2] /= k return _t(q2, base, s) pt.tex = tex
def _branches(seed, bark_col): """a bare crown: limbs forking from the trunk top, thinner each fork (rule: same as the pixel draw_tree skeleton)""" from .models import Part rs = np.random.RandomState(seed) segs = []
def limb(a, d, ln, r, depth): b = a + d * ln segs.append((a, b, r)) if depth: for _ in range(2): n = d + rs.uniform(-.6, .6, 3) * np.array([1, .4, 1]) n[1] = abs(n[1]) + .25 limb(b, n / np.linalg.norm(n), ln * .7, r * .65, depth - 1) top = np.array([0, .46, 0.]) for ang in np.linspace(0, 2 * np.pi, 4, endpoint=False) + rs.uniform(0, 1): d = np.array([np.cos(ang) * .9, 1, np.sin(ang) * .9]) limb(top, d / np.linalg.norm(d), .24, .022, 3) segs = [(a.astype(np.float32), b.astype(np.float32), r) for a, b, r in segs]
def fn(p): d = None for a, b, r in segs: x = S.capsule(p, tuple(a), tuple(b), r) d = x if d is None else np.minimum(d, x) return d return Part(fn, bark_col, spec=.05, rough=.9, tex="bark")
def apply(parts, e, trace, seed=0): from pydraw.language import on at = e.get("attrs") or {} conds = list(at.get("cond") or []) if not on("cond3d") or not parts: return parts leafy = [j for j, pt in enumerate(parts) if pt.tex == "leaves"] if leafy and on("tree") and ("leaves" in at.get("absent", []) or "bare" in conds or "withered" in conds) \ and "branches" not in at.get("absent", []): # rule: a tree without leaves / a dead tree = its trunk + a bare branch skeleton in place of the crown bark = next((pt.color for pt in parts if pt.tex != "leaves"), (110, 75, 45)) parts = [pt for j, pt in enumerate(parts) if j not in leafy] + [_branches(seed + 3, bark)] conds = [c for c in conds if c not in ("bare", "withered")] trace.append("3d: %s without leaves -> bare branches" % e.get("concept")) if leafy and "twisted" in conds: for pt in parts: # rule: a gnarled tree also has a thicker, knotted trunk (every non-leaf part) if pt.tex != "leaves": f0 = pt.fn pt.fn = lambda p, _f=f0: _f(p) - .025 - .012 * S.noise3(p * 18) if not conds: return parts done = [] for c in conds: for j, pt in enumerate(parts): if c in SURFACE: _wrap_tex(pt, c, seed + j) elif c == "shiny": pt.spec, pt.rough = max(pt.spec, .85), min(pt.rough, .12) elif c == "glowing": pt.emit = max(getattr(pt, "emit", 0.0), .55) elif c in ("twisted", "stout", "thin"): _warp(pt, c, seed) else: break else: done.append(c) if done: trace.append("3d: conditions %s on %s" % ("+".join(done), e.get("concept"))) return parts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Containers with contents in 3D (night wave, knob PYDRAW3D_EXP=...,contents=0).
"a vase of flowers", "a basket of oranges", "a bowl of cherries", "a cup of coffee": the parser keeps the containerand drops "of Y", so the 3D container was drawn EMPTY. Here the prompt text is read once more for "<container> (full)of <thing>" right after the container word; the thing is drawn inside the container's own model frame (so it moves,turns and scales with it):- liquids (coffee, tea, milk, water, juice, soup, wine...): a liquid surface just below the rim, its colour;- flowers in a vase / jar / pot: a fanned bouquet of the flower model, stems in the neck;- anything else with a model: a small heap of copies resting on the container's inner floor (a ring + one on top), as one instanced field (compiles to C).Rules only; the thing's size comes from the concept heights (clamped to fit the opening)."""import mathimport re
import numpy as np
CONTAINERS = {"vase", "basket", "bowl", "bucket", "jar", "crate", "box", "cup", "mug", "glass", "pot", "tray", "pail", "barrel", "cart", "wheelbarrow", "plate", "dish", "pitcher", "jug", "teapot", "kettle", "sack", "bag"}LIQUIDS = {"coffee": (70, 42, 25), "tea": (150, 85, 35), "milk": (246, 244, 236), "water": (150, 195, 225), "juice": (245, 160, 40), "orange juice": (245, 160, 40), "soup": (200, 110, 50), "wine": (110, 20, 40), "lemonade": (245, 235, 150), "hot chocolate": (95, 55, 35), "cocoa": (95, 55, 35), "beer": (220, 160, 50), "cereal": (215, 175, 100), "porridge": (225, 205, 160), "oatmeal": (225, 205, 160), "honey": (230, 160, 40), "paint": (60, 110, 200), "ink": (25, 25, 45)}FLOWERS = {"flower", "flowers", "rose", "roses", "tulip", "tulips", "daisy", "daisies", "sunflower", "sunflowers", "lily", "lilies", "poppy", "poppies", "bouquet"}FLOWER_COLS = {"rose": (200, 30, 50), "tulip": (235, 80, 90), "daisy": (250, 250, 245), "sunflower": (250, 200, 30), "lily": (250, 240, 235), "poppy": (220, 40, 30)}STOP = r"(?:on|in|at|next|beside|by|with|near|under|and|,|$)"
def find(text, container_word): """-> the thing phrase after '<container> (full) of', or None""" low = " " + re.sub(r"[^a-z, ]", " ", text.lower()) + " " m = re.search(r"\b%ss? (?:full of|filled with|of) ((?:[a-z]+ ?){1,3}?) ?%s" % (re.escape(container_word), STOP), low) if not m: return None w = m.group(1).strip() w = re.sub(r"^(?:fresh|hot|cold|red|green|yellow|white|pink|ripe|wild|some|many|a few|lots of|delicious) ", "", w) return w or None
def _concept(word): from pydraw.registry import CONCEPTS for c in (word, word.rstrip("s"), re.sub(r"ies$", "y", word), re.sub(r"es$", "", word), word.split()[-1], word.split()[-1].rstrip("s")): if c in CONCEPTS: return c return None
def _col(word, default): from pydraw.understanding import COLORS for w in word.split(): if w in COLORS: return tuple(COLORS[w]) return default
def contents_parts(container, word, text, parts, aspect, rng, trace): """extra Parts (container model frame) for the container's contents, or []""" from .models import Part from . import sdf as S from .sim.build import model_parts, instanced, union from .imagine import top_at from pydraw.registry import CONCEPTS thing = find(text, word.split()[-1]) or (find(text, container) if container != word else None) if not thing: return [] hit = union(parts) # the container's opening height and inner floor at the middle (probe straight down from above) rim = top_at(hit, aspect * .3, 0.0, 2.0) floor = top_at(hit, 0.0, 0.0, 2.0) rim = 1.0 if rim is None else rim floor = .1 if floor is None or floor > rim else floor key = next((k for k in sorted(LIQUIDS, key=len, reverse=True) if k in thing), None) if key: lc = LIQUIDS[key] y = floor + (rim - floor) * .78 r = aspect * .5 * .92
def liquid(p, y=y, r=r): # a thin disc, cut away wherever the container itself is solid (its walls hold the liquid's edge) return np.maximum(S.cylinder(p, np.array([0, y - .02, 0], np.float32), r, .02), -hit(p) - .006) trace.append("3d: %s filled with %s" % (container, key)) return [Part(liquid, lc, spec=.9 if key not in ("cereal", "porridge", "oatmeal") else .2, rough=.08)] words = thing.split() if words[-1] in FLOWERS or (container in ("vase", "jar", "pitcher", "jug") and words[-1] in ("flower", "flowers")): kind = words[-1].rstrip("s").replace("daisie", "daisy").replace("lilie", "lily").replace("poppie", "poppy") fc = _col(thing, FLOWER_COLS.get(kind)) fp, fa = model_parts("flower", fc) if not fp: return [] n = 5 items = [] for i in range(n): a = (i - (n - 1) / 2) * .32 + rng.uniform(-.06, .06) tilt = abs(a) * .5 Rm = np.array([[math.cos(a), -math.sin(a), 0], [math.sin(a), math.cos(a), 0], [0, 0, 1]]) Rx = np.array([[1, 0, 0], [0, math.cos(tilt * (1 if i % 2 else -1)), -math.sin(tilt * (1 if i % 2 else -1))], [0, math.sin(tilt * (1 if i % 2 else -1)), math.cos(tilt * (1 if i % 2 else -1))]]) s = (1.0 if container == "vase" else .8) * rng.uniform(.85, 1.05) t = np.array([0, rim - .35 * s, 0.0]) items.append((fp, Rm @ Rx, t, s)) trace.append("3d: %d %s stand in the %s" % (n, kind, container)) return instanced(items) c = _concept(thing) if c is None or c in CONTAINERS: return [] ip, ia = model_parts(c, _col(thing, None)) if not ip: return [] h_c = CONCEPTS.get(container, {}).get("height", .3) s = float(np.clip(CONCEPTS[c]["height"] / max(h_c, 1e-3), .12, .42)) open_r = aspect * .5 * .8 items = [] ring = max(3, min(7, int(2 * math.pi * open_r / max(s * ia, .05) * .8))) for i in range(ring): a = 2 * math.pi * i / ring + rng.uniform(-.2, .2) rr = max(open_r - .55 * s * ia, 0) Ry = np.array([[math.cos(a * 3), 0, math.sin(a * 3)], [0, 1, 0], [-math.sin(a * 3), 0, math.cos(a * 3)]]) items.append((ip, Ry, np.array([rr * math.cos(a), floor + .05 * s, rr * math.sin(a)]), s)) items.append((ip, np.eye(3), np.array([0, floor + .55 * s, 0]), s)) # rule: the heap shows above the rim (a basket "of oranges" reads only if the oranges peek out) lift = max(0.0, (rim - .35 * s) - (floor + .55 * s)) items = [(p_, R_, t_ + np.array([0, lift, 0]), s_) for p_, R_, t_, s_ in items] trace.append("3d: %d %s heaped in the %s" % (len(items), c, container)) return instanced(items)926 unmodified lines9279289299309319326 unmodified lines939940941942943944926 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}6 unmodified linesreturn 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)"""926 unmodified lines9279289299309319329339349359369379389399409419429439449456 unmodified lines952953954955956957958959960961962963926 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))if pose == "hop" and getattr(inst, "joey", False) and _joey_on():# night characters 3 (pouch): a joey's head and ears poke out of the pouch on the bellyjc = hip + (sh - hip) * .5 + fd * g * .95 + up * g * .15jr = h * .58jcol = _light(col, .25) if isinstance(col, tuple) else colparts.append(Part(lambda p, c=jc, r=jr: S.smin(S.sphere(p, V(*c), r),S.sphere(p, V(*(c + fd * r * .9 - up * r * .15)), r * .55), r * .3),jcol, k=.02, spec=P.spec, rough=P.rough, tex=P.tex))for e_ in (-1, 1):ea = jc + up * jr * .7 + side * e_ * jr * .45eb = ea + up * jr * .9 - fd * jr * .2parts.append(Part(lambda p, a=ea, b=eb, r=jr * .22: rcone(p, a, b, r, r * .6), jcol, k=.01))bb.pts([jc], [jr * 1.4])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}6 unmodified linesreturn 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 _joey_on():import osev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)return ev.get("pouch", "1") != "0"def _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)"""
pydraw/__init__.py+13-3
pydraw/actions.py+64-1
pydraw/atmos.pyAdded
pydraw/attach.pyAdded+1097
pydraw/character2d.py+418-15
pydraw/characters.py
pydraw/compose.py+55-1
pydraw/concepts/animals.py+93-2
pydraw/concepts/animals2.py+200-28
pydraw/concepts/animals3.py+27-6
pydraw/concepts/core.py+171-8
pydraw/concepts/misc3.py+37-1
pydraw/concepts/objects2.py+11-1
pydraw/concepts/objects4.py+73
pydraw/concepts/people.py+450-19
pydraw/concepts/shapes.py+42-1
pydraw/concepts/structures.py+101
pydraw/concepts/vehicles.py+28
pydraw/condition_px.pyAdded+361
pydraw/frames.pyAdded+85
pydraw/imagine.py+6-4
pydraw/language.pyAdded+1589
pydraw/layout.py+143-15
pydraw/lexicon.py+1-1
pydraw/mood.py+266-4
pydraw/open_vocab.py+4
pydraw/perch.py+3-1
pydraw/physics.py+61
pydraw/physics2.py+37-4
pydraw/pixelart.py+16
pydraw/pixeltex.py+6
pydraw/retro.pyAdded+72
pydraw/scenes.py+525-42
pydraw/stage.pyAdded+400
pydraw/surface.pyAdded+99
pydraw/tether.pyAdded+145
pydraw/typography/draw2d.py+1-1
pydraw/typography/draw3d.py+8-6
pydraw/typography/understand.py+39
pydraw/understanding.py+33
pydraw/variation.py+17-1
pydraw3d/__init__.py+335-16
pydraw3d/attach.pyAdded+284
pydraw3d/characters.py+39-2
pydraw3d/compile/__init__.py+98-4
pydraw3d/compile/emit.py+2
pydraw3d/compile/runtime.c+166
pydraw3d/condition3d.pyAdded+190
pydraw3d/contents.pyAdded+127
pydraw3d/families/mammals.py+19