diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..77e47b2ff446f4d24d444a51db1aae99d11e76bf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +pydraw/__pycache__/atmos.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw/__pycache__/characters.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw/__pycache__/scenes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw/__pycache__/stilllife.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw/__pycache__/world.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw/concepts/__pycache__/objects4.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw/concepts/__pycache__/people.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw3d/families/__pycache__/food.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +pydraw3d/families/__pycache__/objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/app.py b/app.py index 7dcfb524b975c25639f002616cf42cc40d45d884..c65e2933f3ad03967d6ee3354bfee62d3f4c769c 100644 --- a/app.py +++ b/app.py @@ -3,8 +3,9 @@ import os import time import nltk -# anime portraits use the 2D-first portrait path (wave 18); other styles keep the default path for now -os.environ.setdefault("PYDRAW_EXP", "fig2d=1,fig2d_pixel=0,fig2d_ink=0,fig2d_paint=0") +# wave 20 people and animals: 2D-first portraits in every style (fig2d), faces (expressions, age, costume), paint and +# ink portrait styles, full-body poses, contacts, and the new animal and bird drawers +os.environ.setdefault("PYDRAW_EXP", "fig2d=1,fx_face=1,st_paint=1,st_ink=1,body2d=1,cx=1,c2d=1") try: from nltk.corpus import wordnet @@ -203,6 +204,7 @@ footer { display:none !important; } .pd-about b { color:var(--pd-ink); } /* footer line (PyBot) */ +#pd-hint { font:13px/1.5 var(--pd-mono); color:var(--pd-muted); margin:-4px 0 4px; } #pd-foot { margin:14px 0 0; font:13px/1.5 var(--pd-mono); color:var(--pd-muted); overflow-wrap:anywhere; } #pd-foot a { color:inherit; text-underline-offset:2px; } @@ -264,15 +266,16 @@ with gr.Blocks(title="PyDraw") as demo: gr.Markdown("Describe a picture", elem_classes="pd-kicker") prompt = gr.Textbox(value=EXAMPLES[0], lines=2, max_lines=6, show_label=False, container=False, placeholder="a fox in a cape next to a waving flag", elem_id="pd-prompt") + gr.Markdown("Name a style in the prompt (watercolor, oil painting, ink and wash, linocut, pencil, anime). With no style word you get pixel art.", + elem_id="pd-hint") + style = gr.State("pixel") + search = gr.State(False) with gr.Column(elem_classes="pd-card"): - style = gr.Radio(RENDERERS, value="pixel", label="Renderer", elem_id="pd-renderer") with gr.Row(): seed = gr.Number(label="Seed", value=0, precision=0, min_width=120) size = gr.Dropdown([512, 768], value=512, label="Size", min_width=120) variation = gr.Slider(0, 1, value=1, step=0.25, label="Variation", info="Varies only what the prompt leaves open (breed, colour of unnamed things, time, setting, framing). 0 = canonical image.") - search = gr.Checkbox(False, label="Search (3D only, several times slower)", - info="Renders cheap previews of different scene layouts, scores them with hand-written rules and keeps the best.") with gr.Row(elem_id="pd-actions"): btn = gr.Button("Draw", variant="primary", elem_id="pd-draw") btn4 = gr.Button("4 variations", elem_id="pd-draw4") diff --git a/pydraw/__init__.py b/pydraw/__init__.py index e3c829e2fe860dd0ca50ec54001c6df795aa01f1..1dbfb7126bba7cd37ced477a4804edbaebf83a41 100644 --- a/pydraw/__init__.py +++ b/pydraw/__init__.py @@ -39,6 +39,7 @@ def plot(text, seed=0, size=512, style="pixel", res=None, variation=1.0): from .figure import try_portrait as _fig_portrait _fig = _fig_portrait(text, scene, seed, size, style, trace) if _fig is not None: + _claim(_fig, scene, "figure", seed, size) return _fig # wave 15 (gbuf): a medium renderer registered for the style word paints from the G-buffer (pydraw/gbuf.py; # knob media=0 / media_=0 keeps the old styles.py filter) @@ -49,6 +50,25 @@ def plot(text, seed=0, size=512, style="pixel", res=None, variation=1.0): return _render(text, scene, rng, pstyle, trace, seed, size, style, res) +def _claim(img, scene, renderer, seed, size, cv=None, ids=None, inst=None, y0=None, sun=None): + """wave 19 (plan): the claim record (subject, objects, depth layers, emitters, light key) on the Image; Image.save + writes it as .claim.json when PYDRAW_CLAIM=1 (pydraw/picplan.py)""" + from . import picplan as _pp + if not _pp.claim_level(): + return img + try: + if cv is not None: + ids, inst, y0, sun = cv.ids, getattr(cv, "id_inst", None), getattr(cv, "y0", None), getattr(cv, "sun", None) + rec = _pp.claim(scene, renderer, ids=ids, inst=inst, y0=y0, sun=sun, size=size, seed=seed, + key=getattr(cv, "pp_key", None) if cv is not None else None) + if ids is not None: + rec["_ids"] = ids + img.claim = rec + except Exception as ex: # a report must never take the picture down + img.trace.append("picplan: claim failed (%s)" % str(ex)[:80]) + return img + + def prepare(text, seed, variation, trace): """parse + vary + mood + style rules + the director's pre-pass: the scene every renderer draws (plot, gbuffer)""" rng = random.Random(seed) @@ -61,9 +81,13 @@ def prepare(text, seed, variation, trace): # 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()) % 100003 + _parsed = (scene.get("time"), scene.get("weather")) vary(scene, trace, random.Random(_vseed), float(_ev.get("vary", variation)), light=True) + from . import picplan as _pp # wave 19 (plan, pp_key): the variation layer may not invent a time of day + _pp.hold_time(scene, trace, _parsed) from . import mood as _mood _mood.apply(scene, text, trace) # wave 12: visual rhetoric (mood words -> time, weather, camera, framing, grade) + _pp.expose_key(scene) # wave 19 (plan, pp_key): scene["_light_key"] for the thumbnail search (pydraw/thumbs.py) pstyle = scene.get("style") if pstyle == "abstract": import re as _re @@ -112,11 +136,15 @@ def _render(text, scene, rng, pstyle, trace, seed, size, style, res): pixels = pixelart.upscale(px, max(1, size // _R)) else: pixels = styles.upscale_bilinear(px, size) if _R != size else px - return Image(pixels, scene, trace) + return _claim(Image(pixels, scene, trace), scene, "still", seed, size) if renderer == "pixel": # rule: draw at half the output size (512 -> 256): more detail scored better on every benchmark than 128 R = res or int(EXP.get("res", size // 2 if size >= 256 else size)) insts, y0 = layout(scene, R, R, rng, trace) + from . import picplan as _pp, canvas as _cvmod # wave 19 (plan): layer tags for the plan / claim + _cap = _pp.any_on() and not _cvmod.CAPTURE[0] + if _cap: + _cvmod.CAPTURE[0] = True if scene.get("abstract_comp"): # rule: abstract shapes float and overlap across the whole frame at varied sizes for it in insts: @@ -125,7 +153,12 @@ def _render(text, scene, rng, pstyle, trace, seed, size, style, res): it.x = R * rng.uniform(.2, .8) it.y = R * rng.uniform(.4, .95) it.pose, it.bound, it.rel = "flying", None, None - cv, outline_ids = compose(scene, insts, y0, R, R, rng, trace, ss=1) + try: + cv, outline_ids = compose(scene, insts, y0, R, R, rng, trace, ss=1) + finally: + if _cap: + _cvmod.CAPTURE[0] = False + _pp.run_canvas(cv, scene, trace) # wave 19 (plan): the picture's value plan before the palette snap pixelart.finish(cv, outline_ids if EXP.get("outline", "1") == "1" else set(), trace, dither=float(EXP.get("dither", 12.0))) if getattr(cv, "glyphs", None): # wave 16 (glyphs): face / hand symbols written on the finished grid from .rig.glyphs import restamp as _gly_restamp @@ -136,11 +169,22 @@ def _render(text, scene, rng, pstyle, trace, seed, size, style, res): styles.apply(pstyle, cv.px, seed, trace) # rule: tone styles run after the palette snap so it can't undo them frames.apply_px(scene, cv.px, trace) # language shift 2: "a postcard of X" pixels = pixelart.upscale(cv.px, max(1, size // R)) + renderer = "pixel" 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) + from . import picplan as _pp, canvas as _cvmod + _cap = _pp.any_on() and not _cvmod.CAPTURE[0] + if _cap: + _cvmod.CAPTURE[0] = True + try: + cv, _ = compose(scene, insts, y0, R, R, rng, trace, ss=2) + finally: + if _cap: + _cvmod.CAPTURE[0] = False + _pp.run_canvas(cv, scene, trace) # wave 19 (plan): the value plan before the style filter 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.px - return Image(pixels, scene, trace) + renderer = "smooth" + return _claim(Image(pixels, scene, trace), scene, renderer, seed, size, cv=cv) diff --git a/pydraw/__pycache__/__init__.cpython-310.pyc b/pydraw/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be794fc4b6ff2c1f42cadcf050947b5a7d0a6b55 Binary files /dev/null and b/pydraw/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/__pycache__/actions.cpython-310.pyc b/pydraw/__pycache__/actions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..612b3f06c678b779e85c6d9b5e8af9c5c05eb68d Binary files /dev/null and b/pydraw/__pycache__/actions.cpython-310.pyc differ diff --git a/pydraw/__pycache__/atmos.cpython-310.pyc b/pydraw/__pycache__/atmos.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12aa65d963a4138c90aee0e473651b90e9ccc01c --- /dev/null +++ b/pydraw/__pycache__/atmos.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8facd91510a0cb26266cdc7aceba1e054c9599c158605e678438c5bad37a9453 +size 100391 diff --git a/pydraw/__pycache__/attach.cpython-310.pyc b/pydraw/__pycache__/attach.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ca8447a2aab844baa3a87b517dd7dd29a074b1e Binary files /dev/null and b/pydraw/__pycache__/attach.cpython-310.pyc differ diff --git a/pydraw/__pycache__/canvas.cpython-310.pyc b/pydraw/__pycache__/canvas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dce738b2f7f960f81da51ee7a96be311f64a56d2 Binary files /dev/null and b/pydraw/__pycache__/canvas.cpython-310.pyc differ diff --git a/pydraw/__pycache__/character2d.cpython-310.pyc b/pydraw/__pycache__/character2d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..982649933a6a583d7af8fb28c18119fdb317ac5c Binary files /dev/null and b/pydraw/__pycache__/character2d.cpython-310.pyc differ diff --git a/pydraw/__pycache__/characters.cpython-310.pyc b/pydraw/__pycache__/characters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a23a3fd789bb6028404f610c9e008b44fd989afe --- /dev/null +++ b/pydraw/__pycache__/characters.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:250414d8a0889b8e8102d8af775ae818681a6e73610ca411ccf7652dbb0c9710 +size 104397 diff --git a/pydraw/__pycache__/colorcheck.cpython-310.pyc b/pydraw/__pycache__/colorcheck.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..561dfddc8f905b62e641b26847b46e266988f9e8 Binary files /dev/null and b/pydraw/__pycache__/colorcheck.cpython-310.pyc differ diff --git a/pydraw/__pycache__/compose.cpython-310.pyc b/pydraw/__pycache__/compose.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a09ea63b76ba704988495c4a3bb5c0315577a914 Binary files /dev/null and b/pydraw/__pycache__/compose.cpython-310.pyc differ diff --git a/pydraw/__pycache__/contact.cpython-310.pyc b/pydraw/__pycache__/contact.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2fee90b392fac5d40220bed6d241bf4aa2164a7 Binary files /dev/null and b/pydraw/__pycache__/contact.cpython-310.pyc differ diff --git a/pydraw/__pycache__/craft.cpython-310.pyc b/pydraw/__pycache__/craft.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a62c1fda6cc7ae536ad2380c403498e58e8d7892 Binary files /dev/null and b/pydraw/__pycache__/craft.cpython-310.pyc differ diff --git a/pydraw/__pycache__/director.cpython-310.pyc b/pydraw/__pycache__/director.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2229bcb9ab9c1d9093af41e706248ab250e80a30 Binary files /dev/null and b/pydraw/__pycache__/director.cpython-310.pyc differ diff --git a/pydraw/__pycache__/formlight.cpython-310.pyc b/pydraw/__pycache__/formlight.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..059e5cf98b6fa042cd2bdac8374d5c45f47a4d56 Binary files /dev/null and b/pydraw/__pycache__/formlight.cpython-310.pyc differ diff --git a/pydraw/__pycache__/frames.cpython-310.pyc b/pydraw/__pycache__/frames.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ee602bbeb140071192423147b941187f0a1b18a Binary files /dev/null and b/pydraw/__pycache__/frames.cpython-310.pyc differ diff --git a/pydraw/__pycache__/gbuf.cpython-310.pyc b/pydraw/__pycache__/gbuf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a81c3be1ca3a073584be48a933c29aff35a8c17 Binary files /dev/null and b/pydraw/__pycache__/gbuf.cpython-310.pyc differ diff --git a/pydraw/__pycache__/gloss.cpython-310.pyc b/pydraw/__pycache__/gloss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91953e6b043d9193288f25363cb23364b8fcb6e2 Binary files /dev/null and b/pydraw/__pycache__/gloss.cpython-310.pyc differ diff --git a/pydraw/__pycache__/imagine.cpython-310.pyc b/pydraw/__pycache__/imagine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4731d27ecf58c44dd86f24a429601b25237378dd Binary files /dev/null and b/pydraw/__pycache__/imagine.cpython-310.pyc differ diff --git a/pydraw/__pycache__/kit.cpython-310.pyc b/pydraw/__pycache__/kit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb3084019e7498745936ac799bdb567e9fa9d2f2 Binary files /dev/null and b/pydraw/__pycache__/kit.cpython-310.pyc differ diff --git a/pydraw/__pycache__/language.cpython-310.pyc b/pydraw/__pycache__/language.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..829b3106cea4fa2c3cfbac84c7705da826b97998 Binary files /dev/null and b/pydraw/__pycache__/language.cpython-310.pyc differ diff --git a/pydraw/__pycache__/layout.cpython-310.pyc b/pydraw/__pycache__/layout.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d47574cd9e873c0dda9f31950839c56a6463ad98 Binary files /dev/null and b/pydraw/__pycache__/layout.cpython-310.pyc differ diff --git a/pydraw/__pycache__/lexicon.cpython-310.pyc b/pydraw/__pycache__/lexicon.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..962f8a35851a3cebb15de0eb2e868daaa2d2397f Binary files /dev/null and b/pydraw/__pycache__/lexicon.cpython-310.pyc differ diff --git a/pydraw/__pycache__/materials.cpython-310.pyc b/pydraw/__pycache__/materials.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d97024a07f179342bde396f022393688c50e617b Binary files /dev/null and b/pydraw/__pycache__/materials.cpython-310.pyc differ diff --git a/pydraw/__pycache__/matpx.cpython-310.pyc b/pydraw/__pycache__/matpx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a8d46cee6369a10733f3f658388ea3a9f3c036e Binary files /dev/null and b/pydraw/__pycache__/matpx.cpython-310.pyc differ diff --git a/pydraw/__pycache__/media_ink.cpython-310.pyc b/pydraw/__pycache__/media_ink.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..579fce04f8116b58ea446213bfaab62da915ecce Binary files /dev/null and b/pydraw/__pycache__/media_ink.cpython-310.pyc differ diff --git a/pydraw/__pycache__/media_paint.cpython-310.pyc b/pydraw/__pycache__/media_paint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e296ff4f8dbeec0c262948914fecd6908248178 Binary files /dev/null and b/pydraw/__pycache__/media_paint.cpython-310.pyc differ diff --git a/pydraw/__pycache__/mood.cpython-310.pyc b/pydraw/__pycache__/mood.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d9039be4e5984ea3238db7bfa539985f7c3ac65 Binary files /dev/null and b/pydraw/__pycache__/mood.cpython-310.pyc differ diff --git a/pydraw/__pycache__/nature.cpython-310.pyc b/pydraw/__pycache__/nature.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f500a51644d28178f8e918a1d2c2e77856030d0f Binary files /dev/null and b/pydraw/__pycache__/nature.cpython-310.pyc differ diff --git a/pydraw/__pycache__/open_vocab.cpython-310.pyc b/pydraw/__pycache__/open_vocab.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94176254090feef86ee9b90715062acf19ae48df Binary files /dev/null and b/pydraw/__pycache__/open_vocab.cpython-310.pyc differ diff --git a/pydraw/__pycache__/perch.cpython-310.pyc b/pydraw/__pycache__/perch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ee72424b0420f65eb3f17b0bc4693ef2822404c Binary files /dev/null and b/pydraw/__pycache__/perch.cpython-310.pyc differ diff --git a/pydraw/__pycache__/physics.cpython-310.pyc b/pydraw/__pycache__/physics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22744716b881b487d4255d3b640e9088cda04200 Binary files /dev/null and b/pydraw/__pycache__/physics.cpython-310.pyc differ diff --git a/pydraw/__pycache__/physics2.cpython-310.pyc b/pydraw/__pycache__/physics2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec48e2b9c1fd6057163cbfabdfd5336d7ffe9ba5 Binary files /dev/null and b/pydraw/__pycache__/physics2.cpython-310.pyc differ diff --git a/pydraw/__pycache__/picplan.cpython-310.pyc b/pydraw/__pycache__/picplan.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bfadceed8e78ebc3e77cf4b03b1d58f936613c8 Binary files /dev/null and b/pydraw/__pycache__/picplan.cpython-310.pyc differ diff --git a/pydraw/__pycache__/pixelart.cpython-310.pyc b/pydraw/__pycache__/pixelart.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22cc0686641aeae73e99a8df69e78ed894576a03 Binary files /dev/null and b/pydraw/__pycache__/pixelart.cpython-310.pyc differ diff --git a/pydraw/__pycache__/pixelcraft.cpython-310.pyc b/pydraw/__pycache__/pixelcraft.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c50759faf2b027e0c6334ff431865d2b1b7e9c7 Binary files /dev/null and b/pydraw/__pycache__/pixelcraft.cpython-310.pyc differ diff --git a/pydraw/__pycache__/pixeltex.cpython-310.pyc b/pydraw/__pycache__/pixeltex.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a91d390bae0f9899d97003b9d45d295541a39e36 Binary files /dev/null and b/pydraw/__pycache__/pixeltex.cpython-310.pyc differ diff --git a/pydraw/__pycache__/plan.cpython-310.pyc b/pydraw/__pycache__/plan.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf79db3db680547d14dace793d2544108333ff8f Binary files /dev/null and b/pydraw/__pycache__/plan.cpython-310.pyc differ diff --git a/pydraw/__pycache__/planes.cpython-310.pyc b/pydraw/__pycache__/planes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc655e573cd8e5c1c6d1a8c0b42181a7cfcea474 Binary files /dev/null and b/pydraw/__pycache__/planes.cpython-310.pyc differ diff --git a/pydraw/__pycache__/ramps.cpython-310.pyc b/pydraw/__pycache__/ramps.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7711771f6ba65312e1e70cba7857bb566c978dba Binary files /dev/null and b/pydraw/__pycache__/ramps.cpython-310.pyc differ diff --git a/pydraw/__pycache__/registry.cpython-310.pyc b/pydraw/__pycache__/registry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44d22070538f4df35c2ef6605036688f57a4f246 Binary files /dev/null and b/pydraw/__pycache__/registry.cpython-310.pyc differ diff --git a/pydraw/__pycache__/retro.cpython-310.pyc b/pydraw/__pycache__/retro.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8bcd63ec22872212e1c0fd703978378850333ae Binary files /dev/null and b/pydraw/__pycache__/retro.cpython-310.pyc differ diff --git a/pydraw/__pycache__/scenes.cpython-310.pyc b/pydraw/__pycache__/scenes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c30f8dfa135ddf293e4ff2f3a3870b337ff6b104 --- /dev/null +++ b/pydraw/__pycache__/scenes.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14b7c8d8e1f69e26344ea4ec314754142df58de5a3257f2b81565b15afb919ae +size 144434 diff --git a/pydraw/__pycache__/shading.cpython-310.pyc b/pydraw/__pycache__/shading.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0178f357ba8347ff899da762d11bd17dc9f5bb70 Binary files /dev/null and b/pydraw/__pycache__/shading.cpython-310.pyc differ diff --git a/pydraw/__pycache__/skies.cpython-310.pyc b/pydraw/__pycache__/skies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dd5823c896fbe1c63afc18b5ebd0c40e199fc35 Binary files /dev/null and b/pydraw/__pycache__/skies.cpython-310.pyc differ diff --git a/pydraw/__pycache__/stage.cpython-310.pyc b/pydraw/__pycache__/stage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a06ca9bb566f92a3c72bc1fe12837d827093388b Binary files /dev/null and b/pydraw/__pycache__/stage.cpython-310.pyc differ diff --git a/pydraw/__pycache__/stilllife.cpython-310.pyc b/pydraw/__pycache__/stilllife.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de086bac9852659041ffb5edb303ec36eb20487c --- /dev/null +++ b/pydraw/__pycache__/stilllife.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7af37ca6fc6d10abe1858255f46da6fc0bd9648de6a107bfa7018c1759429a0 +size 107241 diff --git a/pydraw/__pycache__/styles.cpython-310.pyc b/pydraw/__pycache__/styles.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85fc6685a398abeea09077e47af893cd538d6c06 Binary files /dev/null and b/pydraw/__pycache__/styles.cpython-310.pyc differ diff --git a/pydraw/__pycache__/surface.cpython-310.pyc b/pydraw/__pycache__/surface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc2fa37e0546b948f3a7f07a8203ff4ff94774a3 Binary files /dev/null and b/pydraw/__pycache__/surface.cpython-310.pyc differ diff --git a/pydraw/__pycache__/tether.cpython-310.pyc b/pydraw/__pycache__/tether.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a59f5796c82628a8b2bd2c8e90cd36662854f588 Binary files /dev/null and b/pydraw/__pycache__/tether.cpython-310.pyc differ diff --git a/pydraw/__pycache__/thumbs.cpython-310.pyc b/pydraw/__pycache__/thumbs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de535f7b582862687409053bb2244d242c3b4eb3 Binary files /dev/null and b/pydraw/__pycache__/thumbs.cpython-310.pyc differ diff --git a/pydraw/__pycache__/toyscale.cpython-310.pyc b/pydraw/__pycache__/toyscale.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..531f6a4c4b45414768cfd1cf5d35e5442ca6da26 Binary files /dev/null and b/pydraw/__pycache__/toyscale.cpython-310.pyc differ diff --git a/pydraw/__pycache__/understanding.cpython-310.pyc b/pydraw/__pycache__/understanding.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..028e18aae146a245411da017c2629c9af24aefcb Binary files /dev/null and b/pydraw/__pycache__/understanding.cpython-310.pyc differ diff --git a/pydraw/__pycache__/variation.cpython-310.pyc b/pydraw/__pycache__/variation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70b4699a4104b1ef09fa8bbff60f1d65e3d86b38 Binary files /dev/null and b/pydraw/__pycache__/variation.cpython-310.pyc differ diff --git a/pydraw/__pycache__/world.cpython-310.pyc b/pydraw/__pycache__/world.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76425c6315c8495109f4266357a06c1cf70267c6 --- /dev/null +++ b/pydraw/__pycache__/world.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b740a3f030cecfb71c25edc057be12c071cee600ab5b42735df0576511d35a21 +size 103109 diff --git a/pydraw/anatomy/__pycache__/__init__.cpython-310.pyc b/pydraw/anatomy/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..705c5ccba4617c2a79a4806e65d91959ad05b6c7 Binary files /dev/null and b/pydraw/anatomy/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/anatomy/__pycache__/core.cpython-310.pyc b/pydraw/anatomy/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3ac9a52cfeac65d871822c97c9447abf31a4fb6 Binary files /dev/null and b/pydraw/anatomy/__pycache__/core.cpython-310.pyc differ diff --git a/pydraw/anatomy/__pycache__/head.cpython-310.pyc b/pydraw/anatomy/__pycache__/head.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3a058103036eff927412dbfd5ae32d6e57f7057 Binary files /dev/null and b/pydraw/anatomy/__pycache__/head.cpython-310.pyc differ diff --git a/pydraw/atmos.py b/pydraw/atmos.py index c5b0c78d6618e595b10b415839ba02b2207bd284..e3d5c62b1b10b7c2d5eb51f180c455d655c3541e 100644 --- a/pydraw/atmos.py +++ b/pydraw/atmos.py @@ -644,6 +644,7 @@ def candle_room(A, I, cv, ctx, scene, trace): box(cx - .9 * u, fy - 3.4 * u, cx + .9 * u, fy - .2 * u, (255, 160, 50)) box(cx - .45 * u, fy - 2.4 * u, cx + .45 * u, fy - .5 * u, (255, 246, 200)) yy, xx = np.mgrid[0:H, 0:W].astype(float) + cv.pp_candle = (cx, fy) # wave 19 (plan, pp_practical): the candle is the room's light source R = H * .62 d = np.hypot((xx - cx) / R, (yy - fy) / (R * .9)) L = np.select([d < .3, d < .6, d < .9], [1.05, .95, .86], .78) # gentle steps: the rings read as big circles @@ -972,7 +973,14 @@ def night_room(A, I, cv, ctx, scene, trace): lit = any(c in FIRES for c in idc.values()) or scene.get("_candle") bg = I == 0 win = getattr(ctx, "room_window", None) - if not lit: + from .picplan import on as _pp_on + if not lit and _pp_on("pp_practical"): + # wave 19 (plan, pp_practical): night is low value AND low chroma, not a blue multiply (value_light_colour rule 7, + # copy_room S8-S9): half the chroma, value to about .62, a faint cool cast (b* about -4) only + l = A[bg] @ np.array([.3, .59, .11]) + X = l[:, None] + (A[bg] - l[:, None]) * .5 + A[bg] = X * .62 + np.array([0, 2, 9.]) + elif not lit: A[bg] = A[bg] * np.array([.74, .8, 1.0]) + np.array([4, 8, 26.]) if win is not None: wx, wy, ww, wh = win @@ -2154,10 +2162,13 @@ def pre(cv, ctx, scene, rng, trace): cv.px = A.tolist() if st["hits"]: from .mood import glow_paint + from . import craft as _craft # w19 things (th_windows, default OFF): 40-70% of windows lit, 3 warmths + st["hits"] = _craft.night_windows(cv, st["hits"], trace) glow_paint(cv, st["hits"]) A = np.asarray(cv.px, float) window_pool(A, I, cv, st["hits"]) cv.px = A.tolist() + _craft.night_windows_tone(cv) trace.append("atmos: %d lit window pixels at night" % len(st["hits"])) return st diff --git a/pydraw/canvas.py b/pydraw/canvas.py index d74e227ea4da29b1169403b7587edee7c33405ff..acd3569c9898f34fd6681ce4015b927b55d16d25 100644 --- a/pydraw/canvas.py +++ b/pydraw/canvas.py @@ -260,6 +260,9 @@ class Image: def save(self, path): with open(path, "wb") as f: f.write(self.to_png()) + if os.environ.get("PYDRAW_CLAIM", "0") not in ("", "0"): # wave 19 (plan): .claim.json (pydraw/picplan.py) + from .picplan import write_claim + write_claim(self, path) return path def _repr_png_(self): # shows inline in Jupyter diff --git a/pydraw/compose.py b/pydraw/compose.py index d509aedad9b6c84a8e3ad7136c9d4a71dbd9af5b..d7cf36e0bb893f2c49672a327fd4442810e4fb55 100644 --- a/pydraw/compose.py +++ b/pydraw/compose.py @@ -210,6 +210,8 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): if getattr(it, "perch", False): from .perch import draw as draw_perch draw_perch(cv, ctx, it) # rule: a perch is a limb under the animal (pydraw/perch.py) + elif (getattr(it, "attrs", None) or {}).get("char") and _c2d_char(cv, ctx, it): + pass # wave 20 (quad, knob c2d): "a fox sitting" is a sitting animal, not the chibi sit character elif (getattr(it, "attrs", None) or {}).get("char"): from .character2d import draw as draw_char # wave 12: animals drawn as characters (face, clothes, anthro) draw_char(cv, ctx, it) @@ -219,7 +221,8 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): else: from .stilllife import sprite as _still_sprite # wave 14 (stilllife): "a basket of apples in the grass" if not _still_sprite(cv, ctx, it, scene, trace): - CONCEPTS[it.concept]["draw"](cv, ctx, it) + from .contact import draw_held as _cx_draw # wave 20 (contact, cx_hold): a held prop rotates about its grip + _cx_draw(CONCEPTS[it.concept]["draw"], cv, ctx, it) if (getattr(it, "attrs", None) or {}).get("wear") and getattr(it, "head", None): from .character2d import wear_person # wave 12: hats / glasses / neckwear a person wears wear_person(cv, ctx, it) @@ -262,6 +265,14 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): host._held_n = nheld + 1 r.x = hand[0] if nheld == 0 else hand[0] - (hand[0] - host.x) * 1.6 r.y = hand[1] + (r.h * .06 if r.concept == "umbrella" else r.h * .45) + if nheld == 0 and host.concept == "person": + from .contact import on as _cx_on, place_held as _cx_place + if _cx_on("cx_hold"): # wave 20 (contact, phys-020): the grip point in the fist, not beside it + _cx_place(host, r, hand, trace) + if getattr(host, "c2d", None) is not None and getattr(r, "riding", False): + from .contact import on as _cx_on2, seat_on_mount as _cx_seat + if _cx_on2("cx_seat"): # wave 20 (contact): the rider sits on the mount's DRAWN back (quad landmarks) + _cx_seat(host, r, trace) 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 None and not getattr(r, "attach_kind", None) and EXP.get("snapsup", "1") != "0"): @@ -289,6 +300,8 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): 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) + from .contact import draw_lines as _cx_lines # wave 20 (contact): lead rope, wagon handle, tug rope, fishing line + _cx_lines(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.place cv.light, cv.sun, cv.y0 = ctx.L, ctx.sun, y0 # wave 13 (form): the one key light, read by pydraw/formlight.py @@ -376,3 +389,11 @@ def finish(cv, ctx, scene, rng, insts, trace): k = 1 - (.25 if cv.ss > 1 else .08) * d * d # rule: pixel art gets a faint vignette (strong ones band) p = row[x] p[0] *= k; p[1] *= k; p[2] *= k + + +def _c2d_char(cv, ctx, it): + """wave 20 (quad): False unless c2d=1 and the char is a plain 'sit' (no chibi / clothes) the prompt says sits""" + if EXP.get("c2d", "0") == "0": + return False + from .concepts.zz_creature import _c2d + return _c2d(cv, ctx, it) diff --git a/pydraw/concepts/__pycache__/__init__.cpython-310.pyc b/pydraw/concepts/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76d15af304e6dc5eefd7e50ce3b587cff0ad796e Binary files /dev/null and b/pydraw/concepts/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/animals.cpython-310.pyc b/pydraw/concepts/__pycache__/animals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8c99fa8d8d411f616ec0f16ad83e19b575999ce Binary files /dev/null and b/pydraw/concepts/__pycache__/animals.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/animals2.cpython-310.pyc b/pydraw/concepts/__pycache__/animals2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..222d65372c4f23537c159d6fa7e1c91e4d7efb66 Binary files /dev/null and b/pydraw/concepts/__pycache__/animals2.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/animals3.cpython-310.pyc b/pydraw/concepts/__pycache__/animals3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e88d74a3b562cbbc226d336777109de00618aba Binary files /dev/null and b/pydraw/concepts/__pycache__/animals3.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/core.cpython-310.pyc b/pydraw/concepts/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cd725e138f3d632b2808b27ef08f4e841e14ce1 Binary files /dev/null and b/pydraw/concepts/__pycache__/core.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/food.cpython-310.pyc b/pydraw/concepts/__pycache__/food.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dde3ea8543fa446ba97ab4175fb6b70da6fb5882 Binary files /dev/null and b/pydraw/concepts/__pycache__/food.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/food2.cpython-310.pyc b/pydraw/concepts/__pycache__/food2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37d985ca89416e6d0b1de81818696b6b03e8efa1 Binary files /dev/null and b/pydraw/concepts/__pycache__/food2.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/indoor.cpython-310.pyc b/pydraw/concepts/__pycache__/indoor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1af12aea21149866fb46b9dc918bb904df8482c3 Binary files /dev/null and b/pydraw/concepts/__pycache__/indoor.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/misc3.cpython-310.pyc b/pydraw/concepts/__pycache__/misc3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e07fc12fd92aa7edf00b7badd93dc3c1d53acc9d Binary files /dev/null and b/pydraw/concepts/__pycache__/misc3.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/misc5.cpython-310.pyc b/pydraw/concepts/__pycache__/misc5.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..116e742e7ea0f1bc59dc1049e8fb032414704f77 Binary files /dev/null and b/pydraw/concepts/__pycache__/misc5.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/misc7.cpython-310.pyc b/pydraw/concepts/__pycache__/misc7.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c0a88ef026f7fc2058f0b379891dc1b0ab96a44 Binary files /dev/null and b/pydraw/concepts/__pycache__/misc7.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/misc8.cpython-310.pyc b/pydraw/concepts/__pycache__/misc8.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28be53423be01475c2bb49e67007bd2b8c5705f0 Binary files /dev/null and b/pydraw/concepts/__pycache__/misc8.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/objects2.cpython-310.pyc b/pydraw/concepts/__pycache__/objects2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ec25a451500ce326260f9738c57b038c50882c6 Binary files /dev/null and b/pydraw/concepts/__pycache__/objects2.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/objects4.cpython-310.pyc b/pydraw/concepts/__pycache__/objects4.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b45abe8294ab07beb19431e3f0a897c8306b91e4 --- /dev/null +++ b/pydraw/concepts/__pycache__/objects4.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:343bf7b58190e2a62389efc438d909264507a8a66c1e099bc1097729fdc3e644 +size 120632 diff --git a/pydraw/concepts/__pycache__/people.cpython-310.pyc b/pydraw/concepts/__pycache__/people.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d21674fe00629c5f94d8de43575f5974b96d53b --- /dev/null +++ b/pydraw/concepts/__pycache__/people.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d1d5ecfaaddfda1b44e3927882f189779df131dd0ba4f66ae7ce5945c4b1be1 +size 133371 diff --git a/pydraw/concepts/__pycache__/pottery.cpython-310.pyc b/pydraw/concepts/__pycache__/pottery.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79747006caec65e8b38a2c6121cf3ccb23f89163 Binary files /dev/null and b/pydraw/concepts/__pycache__/pottery.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/scifi.cpython-310.pyc b/pydraw/concepts/__pycache__/scifi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..864eb09143e26e89fd8782331fa072698f8a225b Binary files /dev/null and b/pydraw/concepts/__pycache__/scifi.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/shapes.cpython-310.pyc b/pydraw/concepts/__pycache__/shapes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c15930a59c55ac627149e16d608cf8ec32a6fe7e Binary files /dev/null and b/pydraw/concepts/__pycache__/shapes.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/structures.cpython-310.pyc b/pydraw/concepts/__pycache__/structures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cbdb85393a0d0fda2c43ae81e219abab8523a71 Binary files /dev/null and b/pydraw/concepts/__pycache__/structures.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/vehicles.cpython-310.pyc b/pydraw/concepts/__pycache__/vehicles.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92a6c2e52240c2b4525341c27c3cd51fbd916556 Binary files /dev/null and b/pydraw/concepts/__pycache__/vehicles.cpython-310.pyc differ diff --git a/pydraw/concepts/__pycache__/zz_creature.cpython-310.pyc b/pydraw/concepts/__pycache__/zz_creature.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f03354bde0b6f228214225a0b99e17d85abcd106 Binary files /dev/null and b/pydraw/concepts/__pycache__/zz_creature.cpython-310.pyc differ diff --git a/pydraw/concepts/core.py b/pydraw/concepts/core.py index 3db9120f1c905da85176a4ffcafdc705e6b1a411..b0af326c84f503a2b625c9b91fec49d327508e37 100644 --- a/pydraw/concepts/core.py +++ b/pydraw/concepts/core.py @@ -716,6 +716,14 @@ def draw_tree(cv, ctx, inst): return (40, 36, 36) return b return scale(b, .88 + .2 * fbm(u * 40, v * 6, seed + 6)) + # wave 19 (nature, nt_clump): an oak / apple crown as 3-7 clumps with sky holes and three values (nature.py) + from .. import nature as _nat + if kind in ("oak", "apple") and not gnarled_canopy and _nat.on("nt_clump"): + pal = [hazed(ctx, inst, c, .9) for c in (AUTUMN[0], AUTUMN[1], AUTUMN[0], AUTUMN[2])] if autumn else None + fruit = _at.get("fruit") + fc = (tuple(fruit) if fruit else (215, 35, 35)) if (kind == "apple" or fruit) else None + if _nat.clump_crown(cv, ctx, inst, F, rng, leaf, trunk, barkpat, autumn=autumn, snow=snow, palette=pal, fruit=fc): + return # --- trunk + branches if gnarled_canopy: pass # trunk and limbs already drawn by _crooked_tree @@ -833,6 +841,11 @@ def draw_pine(cv, ctx, inst): lite, shade = L.flat(green, .95), L.flat(green, .38) tiers = 4 snow = ctx.place == "snow" or (ctx.season == "winter") + from .. import nature as _nat # wave 19 (nature, nt_pine): uneven drooping tiers with a spire (nature.py) + if not xmas and _nat.on("nt_pine"): + from ..atmos import snowy as _snowy + _nat.pine(cv, ctx, inst, green, trunk, snow=snow or bool(getattr(ctx, "scene", None) and _snowy(ctx.scene))) + return tier_geo = [] for k in range(tiers): bot = y - h * (.14 + .62 * k / tiers) diff --git a/pydraw/concepts/objects2.py b/pydraw/concepts/objects2.py index 17a82bc664fac7c4313dae3cd2ead865de5e956e..37f6b76698e6d638035482fd5342466092e9fcf0 100644 --- a/pydraw/concepts/objects2.py +++ b/pydraw/concepts/objects2.py @@ -1166,7 +1166,8 @@ def draw_sword(cv, ctx, inst): cv.poly([(x - bw, gy), (x + bw, gy), (x + bw, y - h * .1), (x, y), (x - bw, y - h * .1)], lambda px, py: L.shade(blade, -.8 if px < x else .8, 0, .6)) cv.capsule(x, gy + h * .02, x, y - h * .14, max(.3, U(cv) * .35), scale(blade, .7)) - cv.ellipse(x, y, bw * 2.2, h * .02, (95, 80, 60), alpha=.6) + if getattr(inst, "grip", None) is None: # wave 20 (contact): a sword held in the fist has no earth mark at its point + cv.ellipse(x, y, bw * 2.2, h * .02, (95, 80, 60), alpha=.6) # crossguard, grip wrapping, pommel lit_capsule(cv, L, x - w * .46, gy - h * .01, x + w * .46, gy - h * .01, lw(cv, h * .025), c) lit_capsule(cv, L, x, gy - h * .03, x, y - h * .92, lw(cv, w * .09), grip) diff --git a/pydraw/concepts/people.py b/pydraw/concepts/people.py index 2864cbda560212b55cb2677fb476e3ccefbd59bf..7bbf9d8bb953137f068d896fa86eb49abba7ecd8 100644 --- a/pydraw/concepts/people.py +++ b/pydraw/concepts/people.py @@ -1533,6 +1533,11 @@ def draw_person(cv, ctx, inst): # 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 top shirt = [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]))] + if getattr(ctx, "L", None) is not None and "body2d=" in __import__("os").environ.get("PYDRAW_EXP", ""): + # (wave 20 body, knob body2d, default OFF): the full figure drawn 2D-first by pydraw/figure/body.py + from ..figure import body as _b2d + if _b2d.draw_scene_person(cv, ctx, inst, dict(locals())): + return if _night_on("prig") is not None and getattr(ctx, "L", None) is not None: # (wave 15 people, prig: PYDRAW_EXP prig=1) the 3D rig builds the body from this point (canon, verb pose, IK, # masses, Loomis head); it returns False for what it does not build yet and this drawer carries on diff --git a/pydraw/concepts/structures.py b/pydraw/concepts/structures.py index 9a8fe1c162dffd711bffa0148d2e31c879e6611a..5fd2b3ee523717965907749c2320c621ef9a1da6 100644 --- a/pydraw/concepts/structures.py +++ b/pydraw/concepts/structures.py @@ -134,7 +134,7 @@ def draw_lighthouse(cv, ctx, inst): L, h, w, x, y = ctx.L, inst.h, inst.w, inst.x, inst.y stripe = hazed(ctx, inst, color_of(inst)) white = hazed(ctx, inst, (242, 240, 234) if not inst.color == "white" else (60, 60, 70)) - lit = night(ctx) or ctx.time == "sunset" + lit = night(ctx) or ctx.time == "sunset" or bool((getattr(inst, "attrs", None) or {}).get("lit")) # wave 19: storm lamp # base platform / rocks rect(cv, x - w * .42, y - h * .06, x + w * .42, y, cyl(L, x, w * .42, hazed(ctx, inst, (120, 115, 110)))) yb, yt = y - h * .06, y - h * .7 diff --git a/pydraw/concepts/zz_creature.py b/pydraw/concepts/zz_creature.py index 261bd405ce0575796a386a45af0b9913110dbdfd..151677abf6bf6e01c98df0a6869c869d3f64fd96 100644 --- a/pydraw/concepts/zz_creature.py +++ b/pydraw/concepts/zz_creature.py @@ -57,8 +57,29 @@ def _only(name): return None +def _c2d(cv, ctx, inst): + """wave 20 (quad / bird lanes, knob c2d, default OFF): the 2D-first drawers in pydraw/creature2d/ go first""" + if not _on("c2d", "0") or getattr(inst, "holding", None) or _skip(inst) \ + or (getattr(inst, "attrs", None) or {}).get("char") and not _c2d_sit(ctx, inst): + return False + from .. import creature2d + return creature2d.draw(cv, ctx, inst) + + +def _c2d_sit(ctx, inst): + """'a fox sitting' parses as the chibi sit character (attrs char=sit, no clothes): the 2D drawer sits it instead""" + at = getattr(inst, "attrs", None) or {} + if at.get("char") != "sit" or at.get("chibi") or at.get("wear") or at.get("clothes"): + return False + sc = getattr(ctx, "scene", None) or {} + t = " %s " % (sc.get("text", "") if isinstance(sc, dict) else "").lower() + return " sit" in t or " seated" in t + + def _wrap(old, concept): def draw(cv, ctx, inst): + if _c2d(cv, ctx, inst): + return if _on("crig") and (_species_on(concept) or _only(concept)) and not getattr(inst, "holding", None) \ and not _skip(inst) \ and not (getattr(inst, "attrs", None) or {}).get("char"): @@ -82,6 +103,8 @@ def _wrap(old, concept): def rig_draw(cv, ctx, inst): """an open-vocabulary creature (pydraw/open_vocab.py): the rig draws it when its species table knows the word""" + if _c2d(cv, ctx, inst): + return True if not _on("crig") or getattr(inst, "holding", None) or (getattr(inst, "attrs", None) or {}).get("char") \ or _skip(inst): return False @@ -105,3 +128,27 @@ def rig_draw(cv, ctx, inst): for _c in COVER + BIRDS + FISH: if _c in CONCEPTS and not hasattr(CONCEPTS[_c]["draw"], "__wrapped__"): CONCEPTS[_c]["draw"] = _wrap(CONCEPTS[_c]["draw"], _c) + + +def _wrap2d(old, concept): + """wave 20: concepts the rig never covered (sheep, goat, pig, zebra, ...) - only the 2D drawer, then the old one""" + def draw(cv, ctx, inst): + if _c2d(cv, ctx, inst): + return + return old(cv, ctx, inst) + draw.__wrapped__ = old + return draw + + +try: + from ..creature2d.canon import CONCEPTS as _C2D +except Exception: + _C2D = () +try: # the bird lane's extra concepts (stork, flamingo, penguin): the list lives in its own file + from ..creature2d.bird import WRAP as _C2B + _C2D = tuple(_C2D) + tuple(_C2B) +except Exception: + pass +for _c in _C2D: + if _c in CONCEPTS and not hasattr(CONCEPTS[_c]["draw"], "__wrapped__"): + CONCEPTS[_c]["draw"] = _wrap2d(CONCEPTS[_c]["draw"], _c) diff --git a/pydraw/contact.py b/pydraw/contact.py new file mode 100644 index 0000000000000000000000000000000000000000..42668a5f8165d0fd83c97bd6e55bc7e6b451a246 --- /dev/null +++ b/pydraw/contact.py @@ -0,0 +1,856 @@ +"""Wave 20 (contact lane): people and animals touching things so it reads as physically real. + +Rules from docs/research21/phys.md (rule ids in comments), persp-033 and comp-007/014/090. Every interaction verb is +compiled to CONTACTS before anything is drawn: a hand target (inst.reach, honoured by every person drawer), a grip on +a held prop (the prop's grip point is placed in the fist and the prop rotates about it), a seat, a line (rope / leash / +wagon handle / fishing line) from a fist to an anchor on the other thing. Layout writes the targets; drawers read them. + +Knobs (PYDRAW_EXP): cx=1 turns every behaviour below on (each sub-knob can still be set to 0 on its own): + cx_hold held props at true size against the hand that holds them (phys-023), grip point in the fist and the prop + rotated about it (phys-019/020): swords and tools held, never planted + cx_pull pull / drag / push a wheeled or heavy thing: it stays on its ground, a hand on its handle (phys-003, 008) + cx_lead leading an animal: the leader at its head, a taut lead rope fist -> halter (phys-028) + cx_feed feeding an animal: feeder at its head, the food in the reaching hand at true size, the animal turned to + the hand (phys-029, phys-006) + cx_lap "a cat on her lap": the holder sits (a chair is added indoors, a bench outdoors), the animal lies on the + thighs, the near hand on its back (phys-030) + cx_tug tug of war: two figures face each other, one rope through the four fists (phys-009) + cx_ratio people and animals keep their true size ratio (persp-033: stage by depth, never scale-cheat) + cx_drink drinking / eating at a table: the drinker sits at the table on a stool, the cup at the lips (phys-024) + cx_seat a sitter faces the way the seat faces (phys-015): the drawn seat is turned to match the sitter (chairs are + drawn with the backrest toward `facing`, benches open toward it) + cx_paint painting at an easel: a brush in the near fist, its tip on the canvas face (phys-002 paint contacts) + cx_group a family / group doing one thing is ONE shape: same depth, overlapping, hands joined, never staggered apart + by the director (comp-007, comp-090, comp-014) +The support tree (move the host, move what it carries; phys-001) is in layout.py (knob cx_follow, default ON). +""" +import math +import os +import re + +from .registry import CONCEPTS + +_SUBS = ("cx_hold", "cx_pull", "cx_lead", "cx_feed", "cx_lap", "cx_tug", "cx_ratio", "cx_drink", "cx_group", "cx_seat", "cx_paint") + + +def _exp(): + return dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + + +def on(name): + e = _exp() + return e.get(name, e.get("cx", "0")) != "0" + + +def any_on(): + return any(on(k) for k in _SUBS) + + +CHILD_WORDS = {"child", "kid", "boy", "girl", "children", "kids", "boys", "girls", "schoolboy", "schoolgirl", "toddler", + "son", "daughter", "grandson", "granddaughter"} + + +def stature(it): + """drawn standing height of a person (people.py draws children at ~.64 of their box)""" + if it.concept != "person": + return it.h + w = (getattr(it, "word", "") or "").split()[-1:] if getattr(it, "word", "") else [] + kid = (w and w[0] in CHILD_WORDS) or (getattr(it, "attrs", None) or {}).get("age") == "child" \ + or getattr(it, "age_hint", None) == "child" + return it.h * (.64 if kid else 1.0) + + +def real_stature(it): + """the holder's real height in metres (children by the drawn ratio)""" + return 1.75 * stature(it) / max(it.h, 1e-6) if it.concept == "person" else CONCEPTS.get(it.concept, {}).get("height", 1.0) + + +def _side(it): + return -1 if getattr(it, "facing", None) == "left" else 1 + + +# ---- held props: grip point (fraction of the box height from the BOTTOM of the drawn prop), rest angle (degrees, +# positive tips the drawn top toward the holder's facing), real length (m) when the concept's height is not the length +# of the thing in the hand. phys-019 (grip by shape), phys-020 (staffs 0.4-0.6, tools near the end, hilts), phys-023. +GRIP = { + # sword concept is drawn point-down with the hilt on top: grip at the hilt, the point swung 20-30 deg forward + # ("sword at rest: point down 10-40 deg in front of the feet") + "sword": (.81, -24, .95), + "pitchfork": (.56, 8, 1.5), "rake": (.56, 8, 1.6), "shovel": (.6, 8, 1.1), "broom": (.6, 8, 1.4), + "spear": (.5, 6, 1.9), "staff": (.5, 6, 1.7), "hoe": (.56, 8, 1.5), "trident": (.5, 6, 1.6), "oar": (.6, 10, 1.8), + "rod": (.08, 50, 1.5), "fishing rod": (.08, 50, 1.5), "fishing pole": (.08, 50, 1.5), + "paintbrush": (.35, 62, .24), "brush": (.35, 62, .24), "pencil": (.35, 50, .17), "pen": (.35, 50, .15), + "torch": (.3, 10, .6), "wand": (.2, 35, .35), "magic wand": (.2, 35, .35), + "axe": (.15, 18, .75), "hammer": (.15, 18, .33), + "flower": (.35, 12, .4), "rose": (.35, 12, .4), "tulip": (.35, 12, .4), "sunflower": (.3, 8, .9), + "lantern": (.97, 0, .35), "bucket": (.97, 0, .3), "pail": (.97, 0, .3), "basket": (.95, 0, .35), + "cup": (.5, 0, .1), "mug": (.5, 0, .1), "coffee": (.5, 0, .11), "teacup": (.5, 0, .08), "glass": (.5, 0, .14), + "apple": (.5, 0, .085), "orange": (.5, 0, .08), "carrot": (.5, 0, .18), "pear": (.5, 0, .1), + "banana": (.5, 0, .2), "ball": (.5, 0, .22), "tennis ball": (.5, 0, .065), "book": (.5, 0, .24), + "phone": (.5, 0, .14), "letter": (.5, 0, .2), "envelope": (.5, 0, .12), +} +LONG = {"sword", "pitchfork", "rake", "shovel", "broom", "spear", "staff", "hoe", "trident", "oar", "rod", + "fishing rod", "fishing pole", "torch", "axe"} +SKIP_HOLD = {"kite", "balloon", "umbrella", "flag"} + + +def size_held(it, hold, H, trace): + """cx_hold: a thing in a person's hand at its true size against the hand (phys-023); below ~40 layout px of + stature (80 px at 512) the prop is enlarged 1.3x so the holder-object relation still reads (phys-054)""" + if it.concept in SKIP_HOLD or hold.concept != "person": + return False + g = GRIP.get(it.concept) + real = g[2] if g else CONCEPTS[it.concept]["height"] + if real > 1.4 * 1.75 and it.concept not in LONG: + return False + st = stature(hold) + k = 1.3 if st < H * .16 else 1.0 + h0 = it.h + it.h = max(H * .018, st * real / real_stature(hold) * k) + it.w = it.h * it.info["aspect"] + trace.append("contact: %s held at true size (%.0f -> %.0f px, %.3f of stature)" % (it.concept, h0, it.h, it.h / max(st, 1e-6))) + return True + + +def place_held(host, r, hand, trace): + """cx_hold (compose, before the held thing is drawn): its grip point goes in the fist; long props get a rest angle + and rotate about the grip (drawn through a rotating canvas)""" + if r.concept in SKIP_HOLD: + return False + g = GRIP.get(r.concept) + gy, ang = (g[0], g[1]) if g else (.5, 0) + f = _side(host) + r.facing = host.facing + r.x = hand[0] + r.y = hand[1] + gy * r.h + r.grip = (hand[0], hand[1]) + r.grip_rot = (hand[0], hand[1], math.radians(ang) * f) if ang else None + trace.append("contact: %s gripped in the %s's hand at %.0f,%.0f (angle %d)" % (r.concept, host.concept, hand[0], hand[1], ang * f)) + return True + + +def seat_on_mount(host, r, trace): + """cx_seat (compose, before a rider is drawn): when the mount's 2D drawer reported its landmarks (quad lane: + inst.c2d["pts"] withers / croup in canvas px), the rider's seat goes on the DRAWN back just behind the withers, at + the lowest point of the back (phys-013: saddle 0.2-0.35 of the body length behind the withers; phys-014)""" + c2d = getattr(host, "c2d", None) or {} + pts = c2d.get("pts") or {} + wi, cr = pts.get("withers"), pts.get("croup") + if not (wi and cr) or r.concept != "person" or not getattr(r, "riding", False): + return False + t = .3 + sx = wi[0] + (cr[0] - wi[0]) * t + sy = max(wi[1], cr[1]) + abs(cr[1] - wi[1]) * .1 # the saddle sits in the dip of the back + dx, dy = sx - r.x, sy - r.y + r.x, r.y = sx, sy + trace.append("contact: rider seated on the drawn back of the %s (moved %.0f,%.0f px)" % (host.concept, dx, dy)) + _err(trace, "rider seat", (sx, sy), (sx, sy), r, host.concept, "seat") + return True + + +def tip_of(r): + """the far end of a gripped long prop (screen px), after its rotation""" + gx, gy = r.grip + top = (r.x, r.y - r.h) + rot = getattr(r, "grip_rot", None) + if not rot: + return top + return _rot(top, (rot[0], rot[1]), rot[2]) + + +def _rot(p, c, a): + dx, dy = p[0] - c[0], p[1] - c[1] + co, si = math.cos(a), math.sin(a) + return c[0] + dx * co - dy * si, c[1] + dx * si + dy * co + + +class RotCanvas: + """a canvas seen through a rotation about a pivot: a concept drawn upright on it lands rotated on the real + canvas (colour callables and inside tests get the un-rotated coordinates back)""" + + def __init__(self, cv, cx, cy, a): + object.__setattr__(self, "_cv", cv) + object.__setattr__(self, "_c", (cx, cy)) + object.__setattr__(self, "_a", a) + + def __getattr__(self, k): + return getattr(self._cv, k) + + def __setattr__(self, k, v): + setattr(self._cv, k, v) + + def _f(self, x, y): + return _rot((x, y), self._c, self._a) + + def _i(self, x, y): + return _rot((x, y), self._c, -self._a) + + def _col(self, color): + if callable(color): + return lambda x, y: color(*self._i(x, y)) + return color + + def ellipse(self, cx, cy, rx, ry, color, rot=0.0, alpha=1.0): + x, y = self._f(cx, cy) + return self._cv.ellipse(x, y, rx, ry, self._col(color), rot=rot + self._a, alpha=alpha) + + def poly(self, pts, color, alpha=1.0): + return self._cv.poly([self._f(*p) for p in pts], self._col(color), alpha=alpha) + + def capsule(self, ax, ay, bx, by, r, color, alpha=1.0): + a, b = self._f(ax, ay), self._f(bx, by) + return self._cv.capsule(a[0], a[1], b[0], b[1], r, self._col(color), alpha=alpha) + + def fill(self, inside, bbox, color, alpha=1.0): + cs = [self._f(bbox[0], bbox[1]), self._f(bbox[2], bbox[1]), self._f(bbox[0], bbox[3]), self._f(bbox[2], bbox[3])] + bb = (min(c[0] for c in cs), min(c[1] for c in cs), max(c[0] for c in cs), max(c[1] for c in cs)) + return self._cv.fill(lambda x, y: inside(*self._i(x, y)), bb, self._col(color), alpha=alpha) + + def rows(self, y0, y1, color_fn): # full-width fills make no sense rotated: draw unrotated + return self._cv.rows(y0, y1, color_fn) + + +def draw_held(draw, cv, ctx, it): + """compose: draw a concept; a gripped prop with a rest angle is drawn rotated about its grip. Drawers made of canvas + primitives go through RotCanvas (exact); drawers that paste rasters (open-vocabulary 3D sprites write cv.px + directly) are drawn twice offscreen, on black and on white, which gives colour and coverage, and the result is + resampled rotated onto the canvas.""" + rot = getattr(it, "grip_rot", None) + if not rot or not on("cx_hold"): + return draw(cv, ctx, it) + if getattr(draw, "__module__", "") != "pydraw.open_vocab": + return draw(RotCanvas(cv, rot[0], rot[1], rot[2]), ctx, it) + import numpy as np + from .canvas import Canvas + shots = [] + for bg in ((0, 0, 0), (255, 255, 255)): + off = Canvas(cv.w, cv.h, bg=bg, ss=cv.ss) + for k, v in cv.__dict__.items(): + if k not in ("px", "ids", "part", "layer", "w", "h", "ss"): + setattr(off, k, v) + off.part = None + off.layer = None + off.clip_y = None + draw(off, ctx, it) + shots.append(np.asarray(off.px, float)) + blk, wht = shots + alpha = np.clip(1 - (wht - blk).mean(-1) / 255.0, 0, 1) + col = blk / np.maximum(alpha[..., None], 1e-3) + ys, xs = np.nonzero(alpha > .02) + if not len(ys): + return + # the rotated footprint on the real canvas, inverse-mapped to the source (nearest sample) + pts = [_rot((x, y), (rot[0], rot[1]), rot[2]) for x, y in ((xs.min(), ys.min()), (xs.max() + 1, ys.min()), + (xs.min(), ys.max() + 1), (xs.max() + 1, ys.max() + 1))] + x0, x1 = max(0, int(min(q[0] for q in pts)) - 1), min(cv.w, int(max(q[0] for q in pts)) + 2) + y0, y1 = max(0, int(min(q[1] for q in pts)) - 1), min(cv.h, int(max(q[1] for q in pts)) + 2) + co, si = math.cos(-rot[2]), math.sin(-rot[2]) + cid = cv.cur_id + for Y in range(y0, y1): + row, idr = cv.px[Y], cv.ids[Y] + for X in range(x0, x1): + dx, dy = X + .5 - rot[0], Y + .5 - rot[1] + sx, sy = int(rot[0] + dx * co - dy * si), int(rot[1] + dx * si + dy * co) + if not (0 <= sx < cv.w and 0 <= sy < cv.h): + continue + a = alpha[sy, sx] + if a <= .02: + continue + c, p = col[sy, sx], row[X] + p[0] += (min(255.0, c[0]) - p[0]) * a + p[1] += (min(255.0, c[1]) - p[1]) * a + p[2] += (min(255.0, c[2]) - p[2]) * a + if cid is not None and a >= .5: + idr[X] = cid + + +def canvas_for(cv, it): + rot = getattr(it, "grip_rot", None) + if not rot or not on("cx_hold"): + return cv + return RotCanvas(cv, rot[0], rot[1], rot[2]) + + +# ---- verbs -> contacts (pre-pass on the parsed scene, before layout normalises relations) +PULL_RX = r"\b(pull|pulls|pulling|pulled|drag|drags|dragging|tow|tows|towing|haul|hauls|hauling)\b" +PUSH_RX = r"\b(push|pushes|pushing|pushed|wheel|wheels|wheeling)\b" +LEAD_RX = r"\b(lead|leads|leading|led)\b" +FEED_RX = r"\b(feed|feeds|feeding|fed|offering|offers)\b" +LAP_RX = r"\b(?:on|in|across)\s+(?:her|his|their|my|your|its|the)\s+lap\b" +TUG_RX = r"\btug[\s-]*of[\s-]*war\b" +DRINK_RX = r"\b(drink|drinks|drinking|sip|sips|sipping|eat|eats|eating|having (?:tea|coffee|breakfast|lunch|dinner))\b" +TABLES = {"dining table", "table", "desk", "kitchen table", "coffee table", "cafe table", "picnic table"} +GROUP_RX = r"\b(family|together|walking|strolling|holding hands|hand in hand)\b" +WHEELED = {"wagon", "cart", "wheelbarrow", "shopping cart", "golf cart", "sled", "sledge", "stroller", "pram", "trolley", + "carriage", "cannon", "plow", "plough", "rickshaw", "barrow", "handcart", "baby carriage", "lawn mower", + "lawnmower", "suitcase", "log", "boat", "rowboat", "canoe", "kayak"} +LEADABLE_MIN_H = .8 # a led animal is at least knee-high to the leader (horse, cow, donkey, goat, sheep, camel, llama) +FOODS = {"apple", "carrot", "bread", "hay", "seed", "seeds", "grain", "corn", "banana", "fish", "bone", "treat", "sugar", + "cookie", "lettuce", "cabbage", "pear", "orange", "berries", "nut", "nuts", "peanut", "biscuit", "bottle"} + + +def _ent_word_pos(text, e): + w = (e.get("word") or e["concept"]).lower() + for cand in (w, w.split()[-1], e["concept"]): + m = re.search(r"\b%ss?\b" % re.escape(cand), text) + if m: + return m.start() + return None + + +def _new_entity(concept): + return {"concept": concept, "word": concept, "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, + "facing": None, "color_explicit": False, "attrs": {}} + + +def _mark(e, **kw): + a = e.get("attrs") + if a is None: + a = e["attrs"] = {} + a.setdefault("cx", {}).update(kw) + + +def pre(scene, trace): + if not any_on(): + return + # tug of war (phys-009): one rope through four fists (first: it removes the rope entity, which shifts indices) + text0 = " " + " ".join((scene.get("text") or "").lower().replace("-", " - ").split()) + " " + if re.search(TUG_RX, text0) and on("cx_tug"): + ents = scene["entities"] + rope = next((i for i, e in enumerate(ents) if e["concept"] in ("rope", "string", "cord")), None) + if rope is not None: + from .actions import _remove + _remove(scene, rope) + ps = [i for i, e in enumerate(ents) if e["concept"] == "person"] + n = sum(ents[i].get("count", 1) for i in ps) + if n >= 2: + for i in ps: + _mark(ents[i], kind="tug") + ents[i]["pose"] = None + scene["cx_tug"] = {"people": ps} + trace.append("contact: tug of war: %d figures on one rope" % n) + ents = scene["entities"] + text = " " + " ".join((scene.get("text") or "").lower().replace("-", " - ").split()) + " " + pos = [_ent_word_pos(text, e) for e in ents] + people = [i for i, e in enumerate(ents) if e["concept"] == "person"] + animals = [i for i, e in enumerate(ents) if CONCEPTS.get(e["concept"], {}).get("animal") and e["concept"] != "person"] + rels = scene["relations"] + + def drop(a, b): + scene["relations"] = [(s, r, o) for s, r, o in scene["relations"] if {s, o} != {a, b}] + + def after(i, m): + return pos[i] is not None and pos[i] > m.start() + + def before(i, m): + return pos[i] is not None and pos[i] < m.start() + + # a fishing rod named in the prompt is in the angler's hands (phys-020), not stuck in the ground beside the rock + if on("cx_hold") and re.search(r"\bfish(?:ing|es)?\b", text) and people: + rod = next((i for i, e in enumerate(ents) if e["concept"] in ("rod", "fishing rod", "fishing pole")), None) + if rod is not None: + p = people[0] + scene["relations"] = [(s_, r_, o_) for s_, r_, o_ in scene["relations"] if rod not in (s_, o_)] + scene["relations"].append((p, "holding", rod)) + if (ents[p].get("attrs") or {}).get("prop") in ("rod", "fishing rod"): + ents[p]["attrs"].pop("prop", None) + trace.append("contact: the fishing rod is in the %s's hands" % ents[p]["concept"]) + # drinking / eating at a table (phys-024): seated at it, the cup at the lips + m = re.search(DRINK_RX, text) + if m and on("cx_drink"): + p = next((i for i in people if before(i, m)), None) + t_ = next((i for i, e in enumerate(ents) if e["concept"] in TABLES), None) + if p is not None and t_ is not None: + if not any({s_, o_} == {p, t_} for s_, r_, o_ in scene["relations"]): + scene["relations"].append((p, "next_to", t_)) + _mark(ents[p], kind="drink", with_=t_) + trace.append("contact: the %s sits at the %s to drink" % (ents[p]["concept"], ents[t_]["concept"])) + # pull / push a wheeled or heavy thing (phys-003): never lifted to the chest + for rx, kind in ((PULL_RX, "pull"), (PUSH_RX, "push")): + m = re.search(rx, text) + if not m or not (on("cx_pull")): + continue + p = next((i for i in people if before(i, m)), None) + o = next((i for i in range(len(ents)) if after(i, m) and i not in people and ( + ents[i]["concept"] in WHEELED or (not CONCEPTS.get(ents[i]["concept"], {}).get("animal") + and CONCEPTS.get(ents[i]["concept"], {}).get("height", 0) >= .5))), None) + if p is None or o is None: + continue + drop(p, o) + scene["relations"].append((p, "next_to", o)) + _mark(ents[p], kind=kind, with_=o) + _mark(ents[o], role=kind + "ed", by=p) + trace.append("contact: %s %ss the %s (stays on its ground, hand on the handle)" % (ents[p]["concept"], kind, ents[o]["concept"])) + # leading an animal (phys-028) + m = re.search(LEAD_RX, text) + if m and on("cx_lead"): + p = next((i for i in people if before(i, m)), None) + a = next((i for i in animals if after(i, m) and CONCEPTS[ents[i]["concept"]]["height"] >= LEADABLE_MIN_H), None) + if p is not None and a is not None: + drop(p, a) + scene["relations"].append((p, "next_to", a)) + _mark(ents[p], kind="lead", with_=a) + trace.append("contact: %s leads the %s on a rope (taut, fist to halter)" % (ents[p]["concept"], ents[a]["concept"])) + # feeding an animal (phys-029) + m = re.search(FEED_RX, text) + if m and on("cx_feed"): + p = next((i for i in people if before(i, m)), None) + a = next((i for i in animals if after(i, m)), None) + food = next((i for i in range(len(ents)) if after(i, m) and i not in people and i not in animals and + (ents[i]["concept"] in FOODS or CONCEPTS.get(ents[i]["concept"], {}).get("setting") == "table")), None) + if p is not None and a is not None: + drop(p, a) + scene["relations"].append((p, "next_to", a)) + if food is not None: + drop(food, a) + drop(food, p) + scene["relations"].append((p, "holding", food)) + _mark(ents[p], kind="feed", with_=a, food=food) + trace.append("contact: %s feeds the %s%s from the hand" % (ents[p]["concept"], ents[a]["concept"], + (" " + ents[food]["concept"]) if food is not None else "")) + # an animal on a lap (phys-030): the holder sits + m = re.search(LAP_RX, text) + if m and on("cx_lap"): + a = max((i for i in animals if before(i, m)), key=lambda i: pos[i], default=None) + p = next((i for i in people if i != a), None) + if a is not None and p is not None and CONCEPTS[ents[a]["concept"]]["height"] < .7: + drop(a, p) + seat = None + for s_, r_, o_ in scene["relations"]: + if s_ == p and r_ == "on" and ents[o_]["concept"] in SEAT_CONCEPTS: + seat = o_ + if seat is None: + from .layout import ROOMS + indoor = scene.get("place") in ROOMS or re.search(r"\b(room|home|house|indoors|inside|kitchen|bedroom|sofa|couch|fireplace)\b", text) + sc = "armchair" if indoor and "armchair" in CONCEPTS else "bench" + ents.append(_new_entity(sc)) + seat = len(ents) - 1 + scene["relations"].append((p, "on", seat)) + pos.append(None) + ents[p]["pose"] = "sitting" + scene["relations"].append((a, "on", p)) + ents[a]["pose"] = "lying" + _mark(ents[a], role="lap", by=p) + _mark(ents[p], kind="lap", with_=a, seat=seat) + trace.append("contact: the %s lies on the %s's lap; the %s sits on a %s" % (ents[a]["concept"], ents[p]["concept"], + ents[p]["concept"], ents[seat]["concept"])) + + +SEAT_CONCEPTS = {"chair", "armchair", "bench", "couch", "sofa", "rocking chair", "stool", "throne"} + + +def _cx(it): + return (getattr(it, "attrs", None) or {}).get("cx") or {} + + +# ---- placement (layout, after the characters stage, before the facing defaults / director) +def _head_pt(a, f): + """an animal's muzzle (halter ring) and head-top estimate from its box when its drawer has not reported anchors""" + from .layout import HEAD_ANCHOR + hxf, htf = HEAD_ANCHOR.get(a.concept, (.38, .9)) + anc = getattr(a, "anchors", None) or {} + if "muzzle" in anc: + return anc["muzzle"] + return a.x + f * a.w * (hxf + .08), a.y - a.h * (htf - .16) + + +def post(insts, scene, W, H, y0, trace): + if not any_on(): + return + from .layout import record_seats + by_ent = {} + for it in insts: + if hasattr(it, "x"): + by_ent.setdefault(it.ent, []).append(it) + moved = [] + for it in list(insts): + c = _cx(it) + k = c.get("kind") + if not k or not hasattr(it, "x") or getattr(it, "k", 0) != 0: + continue + o = by_ent.get(c.get("with_"), [None])[0] + if k in ("pull", "push") and o is not None: + _pull(it, o, k, W, H, trace) + elif k == "lead" and o is not None: + _lead(it, o, W, H, trace) + elif k == "feed" and o is not None: + _feed(it, o, by_ent.get(c.get("food"), [None])[0], W, H, trace) + elif k == "lap" and o is not None: + _lap(it, o, W, H, trace) + moved.append(o) + elif k == "drink" and o is not None: + _drink(it, o, insts, W, H, trace) + tug = scene.get("cx_tug") + if tug: + _tug([o for i in tug["people"] for o in by_ent.get(i, [])], W, H, trace) + if on("cx_group"): + _group(scene, by_ent, W, H, trace) + if moved: + record_seats(moved) + for it in insts: # remember the targets relative to their owners: later framing moves (director, thumbs) carry them + if not hasattr(it, "x") or not hasattr(it, "h"): + continue + if getattr(it, "reach", None) and (_cx(it).get("kind") or getattr(it, "cx_reach", False)): + it._cx_reach0 = {k: _rel(v, it) for k, v in it.reach.items()} + it._cx_f0 = it.facing + L = getattr(it, "cx_line", None) + if L: + L["_rel"] = {"hand": _rel(L["hand"], it)} + if "end" in L: + L["_rel"]["end"] = _rel(L["end"], L["to"]) + if "pts" in L: + L["_rel"]["pts"] = [_rel(q, it) for q in L["pts"]] + + +def _rel(pt, o): + return ((pt[0] - o.x) / max(o.h, 1e-6), (pt[1] - o.y) / max(o.h, 1e-6), o.facing) + + +def _abs(r, o): + mir = -1 if (r[2] in ("left", "right") and o.facing in ("left", "right") and r[2] != o.facing) else 1 + return (o.x + mir * r[0] * o.h, o.y + r[1] * o.h) + + +def finalize(insts, trace): + """end of layout: hand targets and line ends follow their owners through the framing moves""" + if not any_on(): + return + n = 0 + for it in insts: + r0 = getattr(it, "_cx_reach0", None) + if r0: + new = {k: _abs(v, it) for k, v in r0.items()} + if any(abs(new[k][0] - it.reach.get(k, new[k])[0]) + abs(new[k][1] - it.reach.get(k, new[k])[1]) > 1 for k in new): + n += 1 + it.reach = new + L = getattr(it, "cx_line", None) + if L and "_rel" in L: + L["hand"] = _abs(L["_rel"]["hand"], it) + if "end" in L["_rel"]: + L["end"] = _abs(L["_rel"]["end"], L["to"]) + if "pts" in L["_rel"]: + L["pts"] = [_abs(q, it) for q in L["_rel"]["pts"]] + if n: + trace.append("contact: %d hand target(s) carried with their figure through the framing" % n) + if on("cx_seat"): + for p in insts: + b = getattr(p, "bound", None) + if p.concept != "person" or p.rel != "on" or b is None or p.facing not in ("left", "right"): + continue + want = None + if b.concept in ("chair", "rocking chair", "stool"): + want = "left" if p.facing == "right" else "right" # draw_chair skews its backrest toward `facing` + elif b.concept in ("bench", "park bench", "armchair", "couch", "sofa", "throne"): + want = p.facing + if want and b.facing != want: + b.facing = want + trace.append("contact: the %s is turned to face the way its sitter faces (phys-015)" % b.concept) + + +def _clampx(objs, W): + lo = min(o.x - o.w / 2 for o in objs) + hi = max(o.x + o.w / 2 for o in objs) + sh = 0 + if hi - lo < W * .96: + if lo < W * .02: + sh = W * .02 - lo + elif hi > W * .98: + sh = W * .98 - hi + for o in objs: + o.x += sh + + +def _pull(p, o, kind, W, H, trace): + """phys-003 / 008: the wagon stays on the ground behind the puller (in front of a pusher), the near hand on the + handle; the handle is drawn fist -> the wagon's front""" + st = stature(p) + o.bound = None if o.bound is p else o.bound + o.y, o.d = p.y - .5, p.d * 1.002 # same ground line, a hair behind + o.pose = None + f = _side(p) if p.facing else (1 if p.x <= W / 2 else -1) + p.facing = "right" if f > 0 else "left" + o.facing = p.facing + if kind == "pull": + # the puller walks ahead; the wagon trails behind at a handle's length (0.35-0.5 stature) + o.x = p.x - f * (st * .42 + o.w * .5) + hand = (p.x - f * st * .2, p.y - st * .46) + p.reach = {"front": hand} + p.pose = p.pose if p.pose not in (None, "standing") else "walking" + else: + # the pusher leans in behind it, both palms on its near end at hip height (phys-008) + o.x = p.x + f * (st * .24 + o.w * .5) + hand = (o.x - f * o.w * .46, p.y - st * .5) + p.reach = {"front": hand, "back": (hand[0] - f * st * .02, hand[1] + st * .02)} + p.cx_line = {"kind": "handle" if kind == "pull" else None, "to": o, "hand": hand, + "end": (o.x + f * o.w * .5, o.y - o.h * .35)} + _clampx([p, o], W) + trace.append("contact: %s %ss the %s on the ground (handle %s)" % (p.concept, kind, o.concept, "behind" if kind == "pull" else "ahead")) + + +def _lead(p, a, W, H, trace): + """phys-028: the leader walks at the animal's head, a little ahead, facing the same way; the rope runs taut from + the near fist back to the halter ring under the jaw""" + st = stature(p) + f = _side(a) if a.facing else (1 if a.x <= W / 2 else -1) + a.facing = p.facing = "right" if f > 0 else "left" + p.d = min(p.d, a.d) * .995 + a.d = max(a.d, p.d * 1.005) + p.y = max(p.y, a.y) + .5 + mz = _head_pt(a, f) + p.x = mz[0] + f * st * .16 + hand = (p.x - f * st * .13, min(p.y - st * .45, mz[1] + st * .04)) + p.reach = {"front": hand} + p.pose = p.pose if p.pose not in (None, "standing") else "walking" + a.pose = a.pose if a.pose not in (None, "standing") else "walking" + p.cx_line = {"kind": "lead", "to": a, "hand": hand, "end": mz} + _clampx([p, a], W) + trace.append("contact: %s walks at the %s's head, lead rope taut" % (p.concept, a.concept)) + + +def _feed(p, a, food, W, H, trace): + """phys-029 / 006: the feeder stands at the animal's head facing it; the reaching hand holds the food just under + the muzzle; the animal turns to the hand with its head lowered (inst.head_drop for the animal drawer)""" + st = stature(p) + side = 1 if p.x <= a.x else -1 # the person stands on this side of the animal + a.facing = "left" if side > 0 else "right" + p.facing = "right" if side > 0 else "left" + fa = -side + a.d = max(a.d, p.d) + p.d = a.d * .995 + p.y = a.y + .5 + mz = _head_pt(a, fa) + hand = (mz[0] + side * max(st * .03, a.w * .04), min(max(mz[1] + a.h * .1, p.y - st * .62), p.y - st * .36)) + p.x = hand[0] - side * st * .34 + p.reach = {"front": hand} + a.head_drop = 35 # phys-029: the animal lowers its head 20-60 deg to the food + a.look_at = hand + p.look_at = mz + if food is not None: + food.cx_feed_hand = True + _clampx([p, a], W) + trace.append("contact: %s holds the food under the %s's muzzle" % (p.concept, a.concept)) + + +def _lap(p, a, W, H, trace): + """phys-030: the animal lies along the thighs, its belly on them, facing the knees; the near hand on its back""" + st = stature(p) + f = _side(p) + a.facing = p.facing + real = CONCEPTS[a.concept]["height"] + k = max(H * .07, st * min(.34, real / real_stature(p))) / max(a.h, 1e-6) + a.h *= k + a.w *= k + # seated: the person drawer puts the hip at the seat line (inst.y) and the thighs forward along it + a.x = p.x + f * st * .1 + a.y = p.y + a.h * .3 # lying animals are drawn sunk by .3 of their box (compose): the belly lands on the thighs + a.d = p.d * .999 + p.reach = {"front": (a.x + f * a.w * .05, a.y - a.h * .62)} + trace.append("contact: the %s lies on the %s's lap, a hand on its back" % (a.concept, p.concept)) + + +def _tug(ps, W, H, trace): + """phys-009: two figures face each other across the rope, both lean back; the rope is one straight line through + the four fists at 0.45-0.55 stature""" + if len(ps) < 2: + return + ps = sorted(ps, key=lambda o: o.x)[:2] + a, b = ps + hm = max(a.h, b.h) # one rope, one ground line: the two pullers stand at one depth (same size class) + for o in (a, b): + o.w *= hm / o.h + o.h = hm + st = (stature(a) + stature(b)) / 2 + g = max(a.y, b.y) + d = min(a.d, b.d) + cx = min(max((a.x + b.x) / 2, W * .35), W * .65) + sep = st * .95 + a.x, b.x = cx - sep / 2, cx + sep / 2 + a.y = b.y = g + a.d, b.d = d, d * .998 + a.facing, b.facing = "right", "left" + for o, sd in ((a, 1), (b, -1)): + so = stature(o) + ry = g - so * .5 + o.reach = {"front": (o.x + sd * so * .26, ry), "back": (o.x + sd * so * .12, ry + so * .01)} + o.pose = None + o.tug_lean = -sd * 18 # phys-009: lean back 15-35 deg from the rope's centre (for drawers that tilt the trunk) + o.stagger = True # staged here: one ground line, the director does not zig-zag the pair in depth + ry = g - st * .5 + a.cx_line = {"kind": "tug", "pts": ((a.x - st * .2, ry + st * .02), (b.x + st * .2, ry + st * .02)), + "hand": (a.x + stature(a) * .26, ry)} + trace.append("contact: tug of war, rope at %.0f px through the fists" % ry) + + +def _drink(p, T, insts, W, H, trace): + """phys-024: the drinker sits on a stool at the table's end, turned to it; the cup in the near hand at the lips""" + st = stature(p) + side = -1 if p.x <= T.x else 1 # which end of the table the drinker sits at + p.pose = "sitting" + p.stool = True + p.facing = "right" if side < 0 else "left" + f = -side + p.x = T.x + side * (T.w * .5 + st * .1) + p.y = T.y + .5 + p.d = T.d * .995 + # seated on a stool the hip is at .27 stature, the mouth about .69 stature above the floor (people.py proportions) + mouth = (p.x + f * st * .05, p.y - st * .68) + cup = next((o for o in insts if getattr(o, "held_by", None) == p.ent and hasattr(o, "x")), None) + if cup is not None: + p.reach = {"front": (mouth[0] + f * st * .03, mouth[1] + st * .03)} + trace.append("contact: %s raises the %s to the lips at the %s" % (p.concept, cup.concept, T.concept)) + else: + p.reach = {"front": (T.x + side * T.w * .32, T.y - T.h * .98)} + trace.append("contact: %s sits at the %s, hands on the top" % (p.concept, T.concept)) + _clampx([p, T], W) + + +def _group(scene, by_ent, W, H, trace): + """comp-007 / 090 / 014: copies of a person doing one thing together (a family walking, friends together) are one + shape: one ground line and depth, side by side overlapping, adjacent hands joined when they walk together, and + framed as one unit (the director treats the group as one connected thing: no front / back zig-zag of a child)""" + text = " " + (scene.get("text") or "").lower() + " " + if not re.search(GROUP_RX, text): + return + for k, grp in by_ent.items(): + grp = [o for o in grp if hasattr(o, "x") and o.concept == "person" and getattr(o, "bound", None) is None] + if len(grp) < 2 or len(grp) > 6 or any((getattr(o, "attrs", None) or {}).get("inter") or _cx(o).get("kind") for o in grp): + continue + grp.sort(key=lambda o: o.x) + ga = max(o.y for o in grp) + d = min(o.d for o in grp) + for o in grp: + o.y, o.d = ga, d + walk = bool(re.search(r"\b(walk|walking|walks|stroll|strolling|hand in hand|holding hands)\b", text)) + fam = "family" in text + if walk or fam: + fc = grp[0].facing or ("right" if grp[0].x < W / 2 else "left") + for o in grp: + o.facing = fc + f = 1 if fc == "right" else -1 + # neighbours close enough to join hands: centre gap 0.3-0.4 of the taller one's stature + for a, b in zip(grp, grp[1:]): + gap = max(stature(a), stature(b)) * .34 + if b.x - a.x > gap: + b.x = a.x + gap + cx = (grp[0].x + grp[-1].x) / 2 + sh = min(max(cx, W * .3), W * .7) - cx + for o in grp: + o.x += sh + for a, b in zip(grp, grp[1:]): + hy = ga - min(stature(a), stature(b)) * .44 + mx = (a.x + b.x) / 2 + ka = "front" if f > 0 else "back" # a's hand toward b (b is to the right of a) + kb = "back" if f > 0 else "front" + a.reach = dict(getattr(a, "reach", None) or {}, **{ka: (mx, hy)}) + b.reach = dict(getattr(b, "reach", None) or {}, **{kb: (mx, hy)}) + trace.append("contact: %d %s walk together hand in hand, one depth" % (len(grp), grp[0].concept)) + for o in grp[1:]: + o.stagger = True # staged here: the director leaves the group as one shape (no front / back zig-zag) + grp[0].stagger = True + trace.append("contact: %d %s framed as one group (comp-007)" % (len(grp), grp[0].concept)) + + +# ---- size ratios (persp-033) +def keep_ratio(it, ref): + """cx_ratio: a person and an animal (or two different animals) keep their true height ratio""" + if not on("cx_ratio"): + return False + pa = it.concept == "person" or it.info.get("animal") + pr = ref.concept == "person" or ref.info.get("animal") + if not (pa and pr) or (getattr(it, "attrs", None) or {}).get("char") or (getattr(ref, "attrs", None) or {}).get("char"): + return False + return True + + +# ---- drawing (compose, after every object is drawn) +ROPE = (196, 160, 104) +ROPE_DARK = (108, 82, 50) + + +def _line(cv, pts, w, col, dark): + for (x0, y0), (x1, y1) in zip(pts, pts[1:]): + 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) + + +def _sagged(a, b, sag, n=12): + return [(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t + sag * 4 * t * (1 - t)) for t in [i / n for i in range(n + 1)]] + + +def draw_lines(cv, ctx, insts, trace): + if not any_on(): + return + for it in insts: + it._cx_res = (cv.w, cv.h) + for p in insts: + L = getattr(p, "cx_line", None) + if not L or not hasattr(p, "x"): + continue + st = stature(p) + hand = getattr(p, "hand", None) or L.get("hand") + cv.cur_id = getattr(p, "_oid", None) + if L["kind"] == "lead": + end = L["end"] + span = math.hypot(end[0] - hand[0], end[1] - hand[1]) + _line(cv, _sagged(hand, end, span * .02), max(.6, st * .007), ROPE, ROPE_DARK) + _err(trace, "lead rope fist", hand, L["hand"], p, L["to"].concept, "rope") + elif L["kind"] == "handle": + end = L["end"] + _line(cv, [hand, end], max(.6, st * .008), (70, 60, 56), (30, 26, 24)) + cv.capsule(hand[0] - st * .015, hand[1], hand[0] + st * .015, hand[1], max(.6, st * .01), (40, 34, 30)) + _err(trace, "handle fist", hand, L["hand"], p, L["to"].concept, "hand") + elif L["kind"] == "tug": + a, b = L["pts"] + _line(cv, [a, b], max(.7, st * .009), ROPE, ROPE_DARK) + _err(trace, "tug rope fist", hand, L["hand"], p, "rope", "hand") + cv.cur_id = None + if on("cx_paint"): + for p in insts: + if p.concept != "person" or not hasattr(p, "x") or (getattr(p, "attrs", None) or {}).get("action") != "work_at": + continue + ez = min((o for o in insts if o.concept == "easel" and hasattr(o, "x")), key=lambda o: abs(o.x - p.x), default=None) + hand = getattr(p, "hand", None) + if ez is None or not hand: + continue + st = stature(p) + # the canvas face: the upper middle of the easel; the brush points from the fist to it, 0.1-0.14 stature long + cxy = (ez.x, ez.y - ez.h * .68) + dx, dy = cxy[0] - hand[0], cxy[1] - hand[1] + dl = math.hypot(dx, dy) or 1.0 + ln = min(st * .13, dl) + ux, uy = dx / dl, dy / dl + tail = (hand[0] - ux * st * .03, hand[1] - uy * st * .03) + tip = (hand[0] + ux * ln, hand[1] + uy * ln) + cv.cur_id = getattr(p, "_oid", None) + w = max(.45, st * .006) + cv.capsule(tail[0], tail[1], tip[0], tip[1], w + .3, (60, 36, 22)) + cv.capsule(tail[0], tail[1], tip[0] - ux * ln * .2, tip[1] - uy * ln * .2, w, (178, 120, 62)) + cv.capsule(tip[0] - ux * ln * .22, tip[1] - uy * ln * .22, tip[0] - ux * ln * .12, tip[1] - uy * ln * .12, w * 1.1, (190, 190, 196)) + cv.capsule(tip[0] - ux * ln * .1, tip[1] - uy * ln * .1, tip[0], tip[1], w * 1.2, (200, 60, 50)) + cv.cur_id = None + _err(trace, "brush tip on the canvas", tip, (tip[0] + ux * max(0.0, dl - ln), tip[1] + uy * max(0.0, dl - ln)), p, "easel", "brush") + trace.append("contact: a brush from the %s's fist to the easel's canvas" % p.concept) + for r in insts: + if getattr(r, "grip", None) is not None and r.concept in ("rod", "fishing rod", "fishing pole") and hasattr(r, "x"): + # the fishing line falls from the rod tip to the water / ground ahead, a slight curve + tip = tip_of(r) + hb = r.bound + ground = (getattr(hb, "y", r.y) if hb is not None else r.y) + r.h * .05 + end = (tip[0] + (tip[0] - r.grip[0]) * .25, max(tip[1] + r.h * .5, ground)) + cv.cur_id = getattr(r, "_oid", None) + _line(cv, _sagged(tip, end, -r.h * .04), max(.45, r.h * .004), (240, 240, 232), (120, 120, 126)) + cv.cur_id = None + if getattr(r, "grip", None) is not None: + hb = r.bound + h_ = getattr(hb, "hand", None) + if h_: + _err(trace, "%s grip" % r.concept, h_, r.grip, hb, r.concept, "hand") + + +def _err(trace, what, a, b, inst=None, target=None, part="hand"): + e = math.hypot(a[0] - b[0], a[1] - b[1]) + trace.append("contact: %s err=%.1fpx" % (what, e)) + if inst is not None: # for critic13's claim adapter: what touches what, where, and how far off the target it landed + inst.__dict__.setdefault("contact_claim", []).append({"part": part, "target": target, "xy": (round(a[0], 1), round(a[1], 1)), + "err_px": round(e, 1), "res": list(getattr(inst, "_cx_res", (0, 0)))}) diff --git a/pydraw/craft.py b/pydraw/craft.py index e6acfff92addce7b72b0393490a2b881796352e4..077cfddd783df03e6356e9e4294ab19d9ce86800 100644 --- a/pydraw/craft.py +++ b/pydraw/craft.py @@ -25,7 +25,7 @@ _EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") LUM = np.array([.3, .59, .11]) -OFF_BY_DEFAULT = {"vplan", "edges", "vplan_simp", "dapple"} # round 1: speck simplification read flatter, not calmer; the ground-mass value step helped +OFF_BY_DEFAULT = {"vplan", "edges", "vplan_simp", "dapple", "th_windows"} # round 1: speck simplification read flatter, not calmer; the ground-mass value step helped # a boat on water / a fox in a forest but snapped desert sand onto a tan skin tone and erased the meadow texture # (sheets out/wave14_craft/pair_a1_*); kept as a hook (value_plan, shade_ramp) for smooth / 3D buffers. # edges: most pictures are ONE subject group (secondary things are drawn as setting), so it changed ~nothing (e1). @@ -1012,3 +1012,87 @@ def hue_family(cv, A, I, trace): if n: trace.append("craft: lit bands kept in their colour family on %d creatures" % n) return out + + +# ------------------------------------------------------------------------------------------------ night windows +# wave 19 (things lane, knob th_windows, default OFF; rule R16 / things.md BU3): at night a building lights SOME of its +# windows, 40-70% (Kautzky, Slynyrd pixelblog 14 cityscapes: "not every window lit"), in 2-3 different warmths from +# amber to pale lamp yellow and deep fire orange; the others are dark glass. atmos finds every glass pixel and lights it +# one amber (w16_7: three identical yellow blocks); these two hooks run round atmos' glow_paint. +WIN_TONES = (np.array((255, 196, 100.)), np.array((255, 228, 160.)), np.array((246, 168, 92.))) +WIN_DARK = np.array((34, 40, 56.)) + + +def _blobs(pts): + """8-connected components of a pixel list -> list of lists""" + S = set(pts) + out = [] + while S: + st = [S.pop()] + comp = [] + while st: + x, y = st.pop() + comp.append((x, y)) + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + q = (x + dx, y + dy) + if q in S: + S.remove(q) + st.append(q) + out.append(comp) + return out + + +def night_windows(cv, hits, trace): + """before glow_paint: per building, keep 40-70% of its window blobs lit (each with a tone), paint the rest dark glass; + returns the lit hits. A building with 1-2 windows keeps them all (one lit window is the story).""" + if not on("th_windows") or not hits: + return hits + import random + by = {} + for x, y in hits: + by.setdefault(cv.ids[y][x], []).append((x, y)) + keep, tones, ndark, nlit = [], [], 0, 0 + for bid, pts in sorted(by.items()): + bl = [b for b in _blobs(pts) if len(b) >= 2] + tiny = [p for b in _blobs(pts) if len(b) < 2 for p in b] + keep += tiny + if len(bl) < 3: + keep += [p for b in bl for p in b] + tones += [(b, 0) for b in bl] + continue + rr = random.Random(bid * 7919 + len(pts)) + n = len(bl) + k = max(2, min(n - 1, int(round(n * rr.uniform(.4, .7))))) + order = list(range(n)) + rr.shuffle(order) + lit = set(order[:k]) + for j, b in enumerate(bl): + if j in lit: + keep += b + tones.append((b, (len(tones) + rr.randrange(3)) % 3)) + nlit += 1 + else: + ndark += 1 + top, bot = min(y for _, y in b), max(y for _, y in b) + hr = max(1, int(round((bot - top + 1) * .25))) + for x, y in b: + # dark glass with the night sky reflected in its top quarter, so the window still reads as a window + c = WIN_DARK + (np.array((50., 58, 76)) if y < top + hr else 0) + cv.px[y][x] = [float(c[0]), float(c[1]), float(c[2])] + cv._th_win_tones = tones + if ndark: + trace.append("craft: night windows %d lit / %d dark (th_windows, 40-70%% lit, 3 warmths)" % (nlit, ndark)) + return keep + + +def night_windows_tone(cv): + """after glow_paint: tint each lit window blob to its own warmth (glow_paint makes them all one amber)""" + if not on("th_windows"): + return + for b, t in getattr(cv, "_th_win_tones", ()): + if t == 0: + continue + c = WIN_TONES[t] + for x, y in b: + cv.px[y][x] = [float(c[0]), float(c[1]), float(c[2])] diff --git a/pydraw/creature2d/__init__.py b/pydraw/creature2d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a9981dfdb683c1da7951831f9f5e7ca47b66defa --- /dev/null +++ b/pydraw/creature2d/__init__.py @@ -0,0 +1,34 @@ +"""creature2d: animals drawn 2D-first, the way animal illustrators build them (wave 20; knob c2d, default OFF). + + draw(cv, ctx, inst) -> bool True = drawn here; False = the old drawer (rig / sprite) takes over +Lanes: quad.py (four-legged animals, quad lane: canon.py, kit.py, this file), bird.py (bird lane). +Knobs (PYDRAW_EXP): c2d=1 turns the package on; c2d_quad=0 / c2d_bird=0 per lane; c2d_=0 per species +(c2d_fox=0, c2d_polar_bear=0). +After a draw, inst.c2d holds the landmarks in canvas px for critics (bench/critic13): species, pose, facing, wh_px +(withers height px), ground, pts {nose, eye, poll, withers, croup, tailroot, chest, buttock, brisket, belly}, legs +{fn, ff, hn, hf: [root, elbow / stifle, carpus / hock, fetlock, toe]}.""" +import os +from .kit import knob, on + + +def enabled(): + return knob("c2d", "0") != "0" + + +def draw(cv, ctx, inst): + if not enabled(): + return False + try: + try: + from . import bird as _bird # the bird lane's module (may not exist yet) + except ImportError: + _bird = None + if _bird is not None and on("c2d_bird") and hasattr(_bird, "covers") and _bird.covers(inst): + return bool(_bird.draw(cv, ctx, inst)) + if on("c2d_quad"): + from . import quad + return bool(quad.draw(cv, ctx, inst)) + except Exception: + if os.environ.get("PYDRAW_RIG_DEBUG"): + raise + return False diff --git a/pydraw/creature2d/__pycache__/__init__.cpython-310.pyc b/pydraw/creature2d/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f574dfcc5d6a6079a14b42c8a879ac631b3e14b5 Binary files /dev/null and b/pydraw/creature2d/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/creature2d/__pycache__/bird.cpython-310.pyc b/pydraw/creature2d/__pycache__/bird.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0e3f1c56415dc5ce6faebeb82c6b5bb38790724 Binary files /dev/null and b/pydraw/creature2d/__pycache__/bird.cpython-310.pyc differ diff --git a/pydraw/creature2d/__pycache__/canon.cpython-310.pyc b/pydraw/creature2d/__pycache__/canon.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6b2e64d93ef5b284665696106046401dd5be5c6 Binary files /dev/null and b/pydraw/creature2d/__pycache__/canon.cpython-310.pyc differ diff --git a/pydraw/creature2d/__pycache__/kit.cpython-310.pyc b/pydraw/creature2d/__pycache__/kit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abebb9c837b1f1464721dfd970d03ea07a3d706e Binary files /dev/null and b/pydraw/creature2d/__pycache__/kit.cpython-310.pyc differ diff --git a/pydraw/creature2d/__pycache__/quad.cpython-310.pyc b/pydraw/creature2d/__pycache__/quad.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6113dd61a20225ffaf8efc2a25a7c911a9fafa40 Binary files /dev/null and b/pydraw/creature2d/__pycache__/quad.cpython-310.pyc differ diff --git a/pydraw/creature2d/bird.py b/pydraw/creature2d/bird.py new file mode 100644 index 0000000000000000000000000000000000000000..f34bd2dcabe4610bd2cf08c14bf625e3814474f2 --- /dev/null +++ b/pydraw/creature2d/bird.py @@ -0,0 +1,2153 @@ +"""Birds drawn 2D-first, the way bird illustrators build them (wave 20, bird lane). Pure code, CPU only. + +Knob PYDRAW_EXP c2d=1 (the creature2d package, default OFF; c2d_bird=0 turns this lane off): every bird the vocabulary draws (owl, duck, goose, swan, pigeon, heron / +egret / stork, crow, songbirds, gull, chicken / rooster / chick, parrot, eagle / hawk perched, flamingo) goes through +draw() below instead of the tube rig (pydraw/rig/bird.py) or the old sprites. c2d_bird_ground (on with the lane): +a bird stands or perches unless the prompt says it flies (animal-086, pydraw/layout.py hook). + +The artist's order (John Muir Laws' method, research 21 animal-064, 065, 021, 067, 069; Seton's feather tracts, +animal-068; Sibley's parts of a bird, animal-095), each step one function: + 1. canon row ROWS[name]: proportions as RANGES in body-egg lengths (the seed picks inside them) + 2. posture pose_for(): the verb and the place pick perch / stand / walk / peck / swim / wade / fly / land / + sleep (animal-086); posture line at the species' rest angle (animal-064) + 3. layout build_*(): named 2D landmarks (crown, eye, gape, bill tip, wrist, primary tip, tail tip, leg exit, + feet) and closed outlines per mass, in unit coords (body egg length 1, y up, facing +x, origin = + the feet's contact point / the water line / the flight centre). 3D is used only for an open wing. + 4. value plan Plan: one light, a lit and a shadow value per local colour from the scene's light (ctx.L) + 5. masses painted back to front (far leg, far wing, tail, body, near leg, folded wing, neck, head, bill, near + wing), then DESIGNED shadow shapes: a crescent on the side away from the light per mass, the wing's + cast shadow on the flank, the head's on the breast (not lighting computed on tubes) + 6. features eye (dark, one catch-light upper front), eye ring, gape line, nostril, wing bars, markings, toes and + talons, sized by the bird's pixel size (size ladder animal-078..080) + 7. marks last feather-group edges (covert scallops, tertial and primary edges) only when the bird is big enough +Writes cv.px / ids / part / nbuf (designed pseudo-normals) / zbuf / fdir like the rig, so the pixel finish and every +G-buffer medium read it. Landmarks of the last drawn birds: LAST[cv.cur_id] (critic13).""" +import math +import os +import numpy as np +from PIL import Image, ImageDraw + +KNOB = "c2d_bird" +LAST = {} + +# --------------------------------------------------------------------------------------------------------- knobs +def _exp(): + return dict(kv.split("=", 1) for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + + +def on(name=KNOB, default="1"): + """the package knob c2d (default OFF) gates everything (creature2d/__init__.py); c2d_bird=0 turns the bird lane + off; each c2d_bird_* sub-knob is on with the lane unless set to 0 (or given another default)""" + ev = _exp() + if ev.get("c2d", "0") == "0" or ev.get(KNOB, "1") == "0": + return False + return ev.get(name, default) != "0" + + +# --------------------------------------------------------------------------------------------------------- canon +# Units: the body egg's length (breast to vent, no tail) = 1. Every proportion is a RANGE (lo, hi); the seed picks +# inside it. Sources: research 21 animal.md (rule ids in comments), Sibley parts-of-a-bird, Laws' head size check. +# keys: dep body depth / length; head head diameter; neck neck length; bill (length / head diameter, base depth / +# head diameter, shape); tail (length, angle to the body axis deg, + = up); leg visible tarsus; tib visible bare +# tibia (waders); toe type; wing folded wing length; proj primary projection past the body; span flying span; +# post posture deg above horizontal (perch, stand, swim); eye radius / head diameter; hang neck carriage. +R0 = dict(dep=(.58, .64), head=(.40, .46), neck=(0, 0), bill=(.42, .38, "cone"), tail=(.45, .58), tail_ang=(-6, 4), + tail_shape="wedge", leg=(.26, .32), tib=0, toe="perch", wing=(.95, 1.05), proj=(.15, .25), span=(2.0, 2.3), + post=dict(perch=(40, 58), stand=(28, 38), swim=(5, 8)), eye=(.11, .13), hang=60, fly="flap", + wingshape="round", fam="passerine") +ROWS = { + # songbirds (animal-063: head .40-.50 body, cone / thin bill .3-.5 head, wingtip 1/3-1/2 down the tail) + "songbird": dict(col=dict(back=(122, 98, 74), belly=(226, 214, 190), wing=(104, 82, 62), prim=(70, 56, 46), + tail=(86, 68, 54), bill=(60, 52, 46), leg=(120, 92, 76))), + "robin": dict(bill=(.5, .26, "thin"), leg=(.32, .38), tail=(.55, .65), post=dict(perch=(38, 50), stand=(30, 40), swim=(5, 8)), + col=dict(back=(112, 100, 88), head=(70, 64, 60), belly=(236, 230, 218), breast=(222, 106, 46), + wing=(96, 86, 76), prim=(66, 60, 56), tail=(62, 58, 56), bill=(226, 178, 60), + leg=(110, 90, 80), eyering=(240, 236, 224))), + "sparrow": dict(bill=(.4, .46, "cone"), col=dict(back=(150, 106, 66), head=(130, 112, 100), cap=(122, 82, 50), + belly=(214, 206, 188), wing=(140, 96, 58), prim=(84, 60, 42), + tail=(110, 80, 56), bill=(70, 62, 56), leg=(170, 130, 110), + bar=(240, 232, 212), streak=(70, 48, 32), cheek=(214, 206, 188))), + "finch": dict(parent="sparrow", col=dict(back=(150, 120, 80), head=(200, 70, 60), belly=(232, 210, 190), + breast=(206, 80, 70), streak=(130, 96, 70))), + "goldfinch": dict(parent="sparrow", col=dict(back=(238, 200, 40), head=(238, 200, 40), cap=(24, 22, 24), + belly=(246, 220, 80), wing=(30, 28, 30), prim=(20, 20, 22), + tail=(26, 24, 26), bill=(232, 170, 130), bar=(246, 242, 232), + streak=None)), + "bluebird": dict(col=dict(back=(64, 110, 206), head=(64, 110, 206), belly=(236, 230, 222), breast=(214, 124, 70), + wing=(58, 100, 196), prim=(40, 70, 150), tail=(50, 86, 180), bill=(36, 34, 36))), + "blue jay": dict(dep=(.56, .6), tail=(.95, 1.1), crest=.55, bill=(.5, .4, "thin"), + col=dict(back=(88, 136, 206), head=(98, 146, 214), belly=(232, 234, 238), wing=(66, 120, 206), + prim=(44, 86, 170), tail=(70, 120, 200), bill=(30, 30, 34), leg=(40, 40, 46), + bar=(246, 246, 246), necklace=(26, 26, 30), face=(236, 238, 242))), + "cardinal": dict(crest=.6, bill=(.45, .52, "cone"), col=dict(back=(196, 36, 40), head=(214, 40, 44), + belly=(214, 52, 52), wing=(170, 32, 36), + prim=(140, 28, 32), tail=(160, 30, 34), + bill=(238, 120, 60), mask=(28, 22, 24), leg=(150, 110, 100))), + "canary": dict(col=dict(back=(240, 206, 60), belly=(250, 228, 110), wing=(226, 190, 54), prim=(190, 160, 50), + tail=(210, 176, 52), bill=(232, 190, 150), leg=(220, 170, 150))), + "swallow": dict(dep=(.5, .55), tail=(1.1, 1.3), tail_shape="fork", wing=(1.35, 1.5), proj=(.6, .8), + leg=(.12, .16), span=(2.5, 2.8), wingshape="point", + col=dict(back=(36, 56, 112), belly=(240, 228, 214), throat=(190, 82, 52), wing=(30, 44, 92), + prim=(24, 32, 70), tail=(30, 44, 92), bill=(26, 24, 24), leg=(40, 36, 36))), + "wren": dict(parent="sparrow", tail=(.4, .5), tail_ang=(40, 60), streak=None), + "kingfisher": dict(head=(.5, .56), bill=(1.1, .4, "dagger"), tail=(.35, .45), leg=(.1, .13), + col=dict(back=(30, 150, 190), head=(30, 120, 170), belly=(226, 120, 50), wing=(28, 110, 160), + prim=(20, 80, 120), tail=(30, 130, 180), bill=(30, 28, 30), leg=(220, 100, 70), + cheek=(226, 120, 50), throat=(240, 236, 224))), + "hummingbird": dict(dep=(.5, .55), head=(.42, .46), bill=(1.3, .18, "thin"), tail=(.5, .6), leg=(.05, .07), + wing=(1.1, 1.2), span=(2.2, 2.4), wingshape="point", + col=dict(back=(60, 150, 90), belly=(220, 226, 216), throat=(200, 30, 70), wing=(50, 60, 64), + prim=(40, 46, 50), tail=(50, 90, 70), bill=(30, 30, 30), leg=(40, 40, 40))), + "woodpecker": dict(bill=(.8, .4, "dagger"), post=dict(perch=(70, 80), stand=(60, 70), swim=(5, 8)), + col=dict(back=(30, 30, 32), head=(240, 238, 232), cap=(200, 30, 36), belly=(236, 232, 222), + wing=(34, 34, 36), prim=(26, 26, 28), tail=(30, 30, 32), bill=(50, 50, 54), + bar=(242, 242, 238), leg=(90, 90, 96))), + "magpie": dict(tail=(1.3, 1.5), bill=(.55, .42, "thin"), + col=dict(back=(24, 26, 32), head=(22, 24, 30), belly=(244, 244, 242), wing=(30, 40, 80), + prim=(24, 30, 50), tail=(30, 50, 80), bill=(26, 26, 28), leg=(30, 30, 32), + scap=(244, 244, 242))), + # crows (stout bill, all black with a blue sheen) + "crow": dict(dep=(.52, .58), head=(.36, .4), bill=(.78, .4, "crow"), tail=(.65, .75), leg=(.32, .38), + post=dict(perch=(30, 42), stand=(22, 30), swim=(5, 8)), eye=(.08, .09), + col=dict(back=(34, 34, 42), belly=(40, 40, 48), wing=(32, 32, 44), prim=(26, 26, 34), + tail=(30, 30, 38), bill=(28, 28, 32), leg=(32, 32, 36), sheen=(90, 100, 150))), + # pigeon (animal-061: head .25-.3 body length, two dark wing bars, dark tail band, green-purple neck, + # short red legs .08-.12 of standing height, body 15-30 deg up, tail .35 of total length) + "pigeon": dict(dep=(.58, .64), head=(.28, .31), neck=(.08, .1), bill=(.42, .2, "pigeon"), tail=(.55, .62), + leg=(.13, .16), post=dict(perch=(20, 30), stand=(15, 28), swim=(5, 8)), eye=(.1, .11), + wing=(.95, 1.0), proj=(.05, .1), span=(2.3, 2.5), wingshape="point", hang=55, + col=dict(back=(150, 152, 166), head=(122, 124, 142), belly=(156, 154, 170), wing=(160, 162, 176), + prim=(86, 88, 100), tail=(132, 134, 150), tailband=(50, 50, 60), bill=(56, 52, 56), + cere=(232, 228, 226), leg=(214, 96, 96), bar=(48, 48, 58), neck=(96, 140, 128), + neck2=(140, 96, 150), iris=(230, 120, 40))), + "dove": dict(parent="pigeon", col=dict(back=(196, 180, 164), head=(200, 186, 172), belly=(216, 202, 190), + wing=(190, 172, 152), prim=(120, 108, 98), tail=(170, 156, 142), + tailband=None, neck=None, neck2=None, bar=None, iris=(40, 30, 30))), + "parrot": dict(head=(.52, .56), bill=(.55, .7, "parrot"), tail=(1.1, 1.3), tail_ang=(-8, 0), + post=dict(perch=(62, 72), stand=(55, 65), swim=(5, 8)), toe="zygo", leg=(.14, .18), + col=dict(back=(52, 166, 70), head=(70, 184, 80), belly=(84, 190, 90), wing=(48, 150, 64), + prim=(40, 90, 196), tail=(48, 140, 70), bill=(226, 220, 206), leg=(120, 110, 110), + face=(240, 240, 236))), + "macaw": dict(parent="parrot", tail=(1.6, 1.9), col=dict(back=(206, 40, 40), head=(214, 46, 44), + belly=(210, 44, 44), wing=(236, 196, 50), + prim=(40, 90, 200), tail=(200, 50, 46), + bill=(230, 226, 214), face=(246, 244, 240))), + "cockatoo": dict(parent="parrot", crest=.8, col=dict(back=(242, 242, 236), head=(244, 244, 240), + belly=(242, 242, 236), wing=(236, 236, 230), + prim=(230, 226, 200), tail=(236, 234, 226), bill=(44, 44, 48), + crestc=(246, 222, 80), face=None)), + "toucan": dict(parent="parrot", bill=(1.5, .7, "toucan"), head=(.42, .46), + col=dict(back=(26, 24, 28), head=(26, 24, 28), belly=(24, 22, 26), throat=(246, 230, 150), + wing=(26, 24, 28), prim=(20, 20, 22), tail=(22, 22, 26), bill=(246, 160, 40), + leg=(60, 90, 150), face=None)), + # gull (long angled wings, black primaries with white spots, yellow bill with a red spot, pink legs) + "gull": dict(dep=(.48, .52), head=(.32, .35), neck=(.08, .1), bill=(.68, .28, "gull"), tail=(.35, .4), + leg=(.3, .34), toe="web", wing=(1.35, 1.45), proj=(.45, .6), span=(3.2, 3.5), wingshape="gull", + post=dict(perch=(15, 22), stand=(10, 18), swim=(2, 5)), eye=(.08, .09), hang=60, + col=dict(back=(180, 188, 200), head=(246, 246, 244), belly=(246, 246, 244), wing=(176, 184, 198), + prim=(30, 30, 34), tail=(246, 246, 244), bill=(240, 204, 70), billspot=(214, 50, 40), + leg=(232, 170, 140), mirror=(246, 246, 244), iris=(236, 226, 160))), + # owls (animal-059: head .9-1.0 of body width, facial disc, eyes forward .2-.25 head width each, hooked beak low + # between the eyes, tufts on horned owls, upright 75-90 deg, short tail, feathered feet; 3/4 head reads better) + "owl": dict(fam="owl", dep=(.74, .8), head=(.9, .98), bill=(.18, .22, "hook"), tail=(.28, .34), leg=(.08, .1), + toe="zygo", wing=(.85, .95), proj=(.05, .1), span=(2.4, 2.7), wingshape="owl", tufts=1, + post=dict(perch=(78, 88), stand=(72, 82), swim=(5, 8)), eye=(.105, .12), + col=dict(back=(128, 94, 64), head=(140, 104, 70), belly=(214, 192, 156), wing=(118, 86, 58), + prim=(96, 70, 48), tail=(110, 80, 56), disc=(206, 176, 136), rim=(70, 50, 36), + bill=(60, 54, 52), leg=(206, 186, 156), iris=(250, 196, 40), streak=(84, 58, 38), + bar=(220, 200, 164), brow=(232, 220, 196))), + "barn owl": dict(parent="owl", tufts=0, disc="heart", eye=(.085, .095), + col=dict(back=(204, 160, 98), head=(208, 168, 106), belly=(246, 240, 226), wing=(198, 154, 92), + prim=(186, 150, 104), tail=(206, 170, 116), disc=(250, 246, 238), rim=(170, 120, 70), + bill=(224, 206, 186), leg=(240, 232, 216), iris=(22, 18, 20), streak=(120, 100, 90), + bar=(150, 140, 136), brow=None)), + "snowy owl": dict(parent="owl", tufts=0, col=dict(back=(236, 234, 228), head=(244, 243, 238), + belly=(246, 245, 240), wing=(232, 230, 224), prim=(222, 220, 214), + tail=(236, 234, 228), disc=(250, 250, 246), rim=(200, 198, 192), + bill=(40, 36, 40), leg=(246, 245, 240), iris=(250, 206, 40), + streak=(70, 66, 66), bar=(80, 76, 74), brow=None)), + "owlet": dict(parent="owl", head=(1.0, 1.08), tufts=0, eye=(.12, .13)), + # eagle / hawk perched (soaring raptors keep the old iconic silhouette unless c2d_bird_soar=1) + "eagle": dict(fam="raptor", dep=(.55, .6), head=(.34, .38), neck=(.08, .1), bill=(.6, .5, "hook"), tail=(.6, .7), + leg=(.24, .28), toe="raptor", wing=(1.05, 1.15), proj=(.1, .2), span=(3.0, 3.3), wingshape="finger", + post=dict(perch=(55, 65), stand=(45, 55), swim=(5, 8)), eye=(.08, .09), fly="soar", + col=dict(back=(88, 60, 40), head=(244, 242, 236), belly=(80, 54, 36), wing=(84, 58, 38), + prim=(46, 34, 28), tail=(244, 242, 236), bill=(240, 196, 60), leg=(240, 196, 60), + iris=(236, 206, 70), trousers=(84, 58, 38))), + "hawk": dict(parent="eagle", col=dict(back=(120, 84, 56), head=(124, 90, 62), belly=(236, 224, 204), + wing=(116, 80, 54), prim=(70, 50, 38), tail=(190, 96, 52), bill=(54, 52, 56), + cere=(236, 200, 60), streak=(110, 76, 50), trousers=(226, 210, 186))), + # waterfowl (animal-060: boat hull, flat back, short upturned tail point, round head on a short upright neck, + # flat bill .45-.6 head; mallard drake green head, white collar, chestnut breast, blue speculum; + # animal-097: walking tilted 10-25 deg, legs set far back; swan S-neck, bill down 30-60 deg) + "duck": dict(fam="duck", dep=(.48, .54), head=(.28, .31), neck=(.16, .2), bill=(.55, .3, "spatula"), + tail=(.2, .26), tail_ang=(18, 28), tail_shape="point", leg=(.14, .17), toe="web", wing=(.8, .85), + proj=(.02, .06), span=(2.3, 2.5), wingshape="point", post=dict(perch=(12, 18), stand=(12, 22), + swim=(2, 5)), eye=(.08, .09), + hang=80, legback=.12, + col=dict(back=(130, 116, 100), head=(36, 104, 64), belly=(200, 196, 190), breast=(122, 72, 52), + wing=(150, 140, 130), prim=(110, 102, 96), tail=(60, 56, 56), bill=(232, 200, 60), + leg=(240, 140, 50), collar=(246, 246, 240), spec=(64, 70, 196), sheen=(60, 160, 90), + flank=(196, 192, 186))), + "female duck": dict(parent="duck", col=dict(back=(140, 106, 70), head=(150, 120, 86), belly=(176, 140, 100), + breast=None, wing=(150, 116, 80), prim=(100, 80, 60), + tail=(130, 100, 70), bill=(200, 130, 60), collar=None, sheen=None, + flank=(170, 132, 92), streak=(90, 66, 44), eyestripe=(70, 52, 40))), + "white duck": dict(parent="duck", col=dict(back=(244, 242, 236), head=(246, 244, 240), belly=(244, 242, 236), + breast=None, wing=(236, 234, 228), prim=(222, 220, 214), + tail=(240, 238, 232), bill=(240, 170, 50), collar=None, spec=None, + sheen=None, flank=(240, 238, 232))), + "duckling": dict(fam="duck", dep=(.62, .7), head=(.55, .62), neck=(.05, .08), bill=(.36, .3, "spatula"), + tail=(.08, .1), tail_ang=(20, 30), tail_shape="point", leg=(.18, .22), toe="web", + wing=(.35, .4), proj=(0, 0), span=(1.4, 1.6), post=dict(perch=(15, 20), stand=(15, 22), + swim=(4, 8)), eye=(.09, .1), hang=85, + col=dict(back=(246, 210, 80), head=(248, 216, 90), belly=(252, 232, 140), wing=(240, 200, 70), + prim=(236, 196, 70), tail=(240, 204, 76), bill=(236, 136, 40), leg=(236, 146, 50))), + "goose": dict(fam="duck", dep=(.5, .56), head=(.26, .29), neck=(.5, .6), bill=(.6, .38, "goose"), tail=(.22, .28), + tail_ang=(10, 20), tail_shape="point", leg=(.24, .28), toe="web", wing=(.9, 1.0), proj=(.05, .1), + span=(2.6, 2.8), wingshape="point", post=dict(perch=(12, 18), stand=(10, 18), swim=(2, 5)), + eye=(.08, .09), hang=86, legback=.06, + col=dict(back=(130, 112, 92), head=(34, 30, 32), belly=(214, 206, 192), breast=(196, 186, 170), + wing=(122, 104, 86), prim=(70, 62, 56), tail=(40, 36, 36), bill=(36, 32, 32), + leg=(40, 36, 36), cheek=(246, 244, 238), neck=(34, 30, 32), vent=(244, 242, 236), + scallop=(176, 160, 140))), + "white goose": dict(parent="goose", col=dict(back=(244, 242, 236), head=(246, 244, 240), belly=(244, 242, 236), + breast=None, wing=(234, 232, 226), prim=(216, 214, 208), + tail=(240, 238, 232), bill=(240, 150, 50), leg=(240, 150, 60), + cheek=None, neck=None, vent=None, scallop=None)), + "swan": dict(fam="duck", dep=(.46, .52), head=(.2, .23), neck=(.85, .95), bill=(.7, .4, "swan"), tail=(.16, .2), + tail_ang=(14, 22), tail_shape="point", leg=(.2, .24), toe="web", wing=(.95, 1.05), proj=(0, .04), + span=(2.6, 2.8), wingshape="point", post=dict(perch=(8, 12), stand=(8, 14), swim=(0, 3)), + eye=(.08, .09), hang=88, legback=.06, arch=1, + col=dict(back=(246, 245, 240), head=(246, 245, 240), belly=(246, 245, 240), wing=(240, 239, 234), + prim=(232, 231, 226), tail=(244, 243, 238), bill=(236, 116, 46), knob=(28, 26, 26), + leg=(40, 36, 36), lore=(28, 26, 26))), + "black swan": dict(parent="swan", col=dict(back=(40, 38, 42), head=(42, 40, 44), belly=(40, 38, 42), + wing=(46, 44, 48), prim=(236, 236, 232), tail=(40, 38, 42), + bill=(206, 40, 46), knob=(240, 236, 232), lore=None)), + # waders (animal-062: legs .45-.5 of standing height, body 30-45 deg, S-neck at rest, dagger bill 1.1-1.3 skull, + # black crown stripe and plumes; IN FLIGHT the neck is pulled back into an S, legs trail past the tail) + "heron": dict(fam="wader", dep=(.4, .44), head=(.22, .25), neck=(1.05, 1.2), bill=(1.25, .36, "dagger"), + tail=(.22, .28), tail_ang=(-12, -4), tail_shape="wedge", leg=(.75, .85), tib=(.32, .38), toe="long", + wing=(1.0, 1.1), proj=(.0, .05), span=(3.2, 3.5), wingshape="broad", fly="heron", + post=dict(perch=(30, 40), stand=(30, 42), swim=(5, 8)), eye=(.08, .09), hang=70, + col=dict(back=(140, 150, 168), head=(236, 236, 232), belly=(214, 216, 220), wing=(132, 142, 160), + prim=(60, 64, 78), tail=(124, 132, 150), bill=(232, 196, 70), leg=(170, 150, 90), + neck=(196, 196, 204), crown=(30, 30, 36), streak=(40, 40, 48), plume=(36, 36, 40), + iris=(240, 214, 60), shoulder=(40, 40, 46))), + "egret": dict(parent="heron", col=dict(back=(246, 246, 242), head=(248, 248, 244), belly=(246, 246, 242), + wing=(240, 240, 236), prim=(234, 234, 230), tail=(242, 242, 238), + bill=(236, 200, 50), leg=(30, 30, 34), neck=(248, 248, 244), crown=None, + streak=None, plume=None, shoulder=None, iris=(236, 214, 70))), + "stork": dict(parent="heron", neck=(.55, .65), bill=(1.3, .5, "dagger"), fly="stork", + col=dict(back=(244, 244, 240), head=(246, 246, 242), belly=(244, 244, 240), wing=(244, 244, 240), + prim=(30, 30, 34), tail=(244, 244, 240), bill=(216, 60, 44), leg=(216, 80, 60), + neck=(246, 246, 242), crown=None, streak=None, plume=None, shoulder=None, + iris=(40, 30, 30))), + "flamingo": dict(parent="heron", dep=(.5, .56), neck=(1.4, 1.55), bill=(.9, .55, "flamingo"), leg=(1.15, 1.25), + tib=(.6, .7), fly="stork", + col=dict(back=(244, 140, 160), head=(246, 150, 170), belly=(246, 160, 176), wing=(240, 120, 146), + prim=(30, 26, 30), tail=(236, 130, 150), bill=(30, 26, 28), billbase=(240, 220, 220), + leg=(236, 120, 140), neck=(246, 150, 170), crown=None, streak=None, plume=None, + shoulder=None, iris=(240, 210, 80))), + # chickens (animal-093: comb, wattles, upright tail fan) + "chicken": dict(fam="fowl", dep=(.66, .72), head=(.3, .33), neck=(.2, .26), bill=(.38, .42, "fowl"), + tail=(.38, .46), tail_ang=(48, 62), tail_shape="fan", leg=(.32, .38), toe="ground", wing=(.6, .7), + proj=(0, 0), span=(1.8, 2.0), post=dict(perch=(20, 28), stand=(14, 24), swim=(5, 8)), + eye=(.09, .1), hang=78, comb=1, + col=dict(back=(176, 96, 46), head=(184, 104, 52), belly=(160, 86, 42), wing=(150, 80, 40), + prim=(110, 64, 36), tail=(140, 76, 38), bill=(236, 196, 90), leg=(236, 196, 80), + comb=(214, 40, 40), hackle=(210, 140, 70))), + "white chicken": dict(parent="chicken", col=dict(back=(246, 244, 236), head=(246, 244, 238), + belly=(244, 242, 234), wing=(238, 236, 228), prim=(226, 224, 216), + tail=(240, 238, 230), hackle=None)), + "rooster": dict(parent="chicken", tail=(.8, .95), tail_shape="sickle", comb=2, dep=(.62, .68), + col=dict(back=(150, 50, 30), head=(200, 120, 50), belly=(40, 36, 34), wing=(130, 50, 34), + prim=(90, 56, 36), tail=(26, 40, 36), hackle=(226, 150, 60), sheen=(40, 110, 90))), + "chick": dict(fam="fowl", dep=(.78, .86), head=(.62, .7), neck=(0, .02), bill=(.28, .36, "cone"), tail=(.06, .08), + tail_ang=(10, 20), tail_shape="point", leg=(.2, .24), toe="ground", wing=(.3, .36), proj=(0, 0), + span=(1.2, 1.4), post=dict(perch=(20, 30), stand=(16, 26), swim=(5, 8)), eye=(.1, .11), hang=80, + col=dict(back=(250, 218, 96), head=(252, 224, 110), belly=(252, 234, 150), wing=(244, 206, 80), + prim=(240, 200, 76), tail=(246, 210, 86), bill=(236, 150, 50), leg=(236, 160, 60))), + "penguin": dict(fam="penguin", dep=(.42, .46), head=(.3, .34), neck=(.04, .06), bill=(.6, .26, "dagger"), + tail=(.1, .14), tail_ang=(-10, 0), leg=(.04, .05), toe="web", wing=(.6, .7), proj=(0, 0), + post=dict(perch=(82, 88), stand=(82, 88), swim=(4, 8)), eye=(.07, .08), + col=dict(back=(30, 32, 40), head=(28, 30, 38), belly=(244, 244, 240), wing=(30, 32, 40), + prim=(30, 32, 40), tail=(30, 32, 40), bill=(36, 34, 38), leg=(60, 56, 60), + throat=(246, 200, 80))), +} +# words -> rows (the longest phrase wins; whole words; a plural s / es allowed) +SYN = {"bird": "songbird", "songbird": "songbird", "robin": "robin", "sparrow": "sparrow", "finch": "finch", + "house finch": "finch", "goldfinch": "goldfinch", "wren": "wren", "bluebird": "bluebird", "blue jay": "blue jay", + "jay": "blue jay", "bluejay": "blue jay", "cardinal": "cardinal", "canary": "canary", "swallow": "swallow", + "swift": "swallow", "martin": "swallow", "kingfisher": "kingfisher", "hummingbird": "hummingbird", + "woodpecker": "woodpecker", "magpie": "magpie", "crow": "crow", "raven": "crow", "blackbird": "crow", + "rook": "crow", "jackdaw": "crow", "starling": "crow", "pigeon": "pigeon", "dove": "dove", + "turtle dove": "dove", "parrot": "parrot", "parakeet": "parrot", "budgie": "parrot", "macaw": "macaw", + "cockatoo": "cockatoo", "toucan": "toucan", "gull": "gull", "seagull": "gull", "sea gull": "gull", + "tern": "gull", "owl": "owl", "great horned owl": "owl", "horned owl": "owl", "hoot owl": "owl", + "scops owl": "owl", "eagle owl": "owl", "barn owl": "barn owl", "snowy owl": "snowy owl", "owlet": "owlet", + "eagle": "eagle", "bald eagle": "eagle", "golden eagle": "hawk", "hawk": "hawk", "falcon": "hawk", + "kestrel": "hawk", "buzzard": "hawk", "red tailed hawk": "hawk", "duck": "duck", "mallard": "duck", + "drake": "duck", "ducky": "duck", "duck bird": "duck", "hen duck": "female duck", "female duck": "female duck", + "white duck": "white duck", "pekin duck": "white duck", "duckling": "duckling", "baby duck": "duckling", + "goose": "goose", "geese": "goose", "canada goose": "goose", "gander": "goose", "gosling": "duckling", + "white goose": "white goose", "domestic goose": "white goose", "swan": "swan", "mute swan": "swan", + "cygnet": "duckling", "black swan": "black swan", "heron": "heron", "grey heron": "heron", + "gray heron": "heron", "great blue heron": "heron", "egret": "egret", "great egret": "egret", "stork": "stork", + "crane bird": "heron", "flamingo": "flamingo", "pink flamingo": "flamingo", "chicken": "chicken", + "hen": "chicken", "poultry": "chicken", "rooster": "rooster", "cockerel": "rooster", "cock": "rooster", + "chick": "chick", "baby chick": "chick", "penguin": "penguin", "emperor penguin": "penguin", + "king penguin": "penguin"} +WRAP = ("stork", "flamingo", "penguin") # registered concepts the rig never wrapped (quad's _wrap2d loop) +CONCEPT_ROW = {"bird": "songbird", "owl": "owl", "eagle": "eagle", "duck": "duck", "goose": "goose", "swan": "swan", + "chicken": "chicken", "stork": "heron", "flamingo": "flamingo", "penguin": "penguin"} +WATERFOWL = ("duck", "female duck", "white duck", "duckling", "goose", "white goose", "swan", "black swan") +WADERS = ("heron", "egret", "stork", "flamingo") +GROUND = WATERFOWL + ("pigeon", "dove", "gull", "chicken", "white chicken", "rooster", "chick", "penguin", "crow") +PART = dict(body=203, head=204, leg=205, feather=213, primary=214, secondary=215, covert=216, beak=217, face=218, + tail=213, wing=216, neck=203, comb=219, eye=220) + + +def lookup(concept, word): + w = " %s " % " ".join((word or "").lower().replace("-", " ").split()) + for k in sorted(SYN, key=len, reverse=True): + if (" %s " % k) in w or (" %ss " % k) in w or (" %ses " % k) in w: + return SYN[k] + return CONCEPT_ROW.get(concept) + + +def get(name): + kw = dict(ROWS.get(name, {})) + par = kw.pop("parent", None) + out = dict(R0) if not par else get(par) + col = dict(out.get("col", {})) + for k, v in (kw.pop("col", {}) or {}).items(): + if v is None: + col.pop(k, None) + else: + col[k] = v + out.update(kw) + out["col"] = col + out["name"] = name + return out + + +def pick(row, rng): + """the seed picks every range of the canon row once (canon = ranges, never one typed picture)""" + P = {} + for k, v in row.items(): + if isinstance(v, tuple) and len(v) == 2 and all(isinstance(x, (int, float)) for x in v): + P[k] = rng.uniform(v[0], v[1]) + else: + P[k] = v + return P + + +# ---------------------------------------------------------------------------------------------------- geometry +def V(x, y): + return np.array([x, y], float) + + +def unit(v): + v = np.asarray(v, float) + return v / (np.linalg.norm(v) + 1e-12) + + +def perp(u): + return V(-u[1], u[0]) + + +def rot(v, deg): + a = math.radians(deg) + c, s = math.cos(a), math.sin(a) + return np.array([c * v[0] - s * v[1], s * v[0] + c * v[1]]) + + +def dirv(deg): + return V(math.cos(math.radians(deg)), math.sin(math.radians(deg))) + + +def crv(pts, closed=True, n=8): + """Catmull-Rom through the decided contour points""" + P = np.asarray(pts, float) + if len(P) < 3: + return P + Q = np.vstack([P[-1:], P, P[:2]]) if closed else np.vstack([P[:1], P, P[-1:]]) + out = [] + t = np.linspace(0, 1, n, endpoint=False)[:, None] + for i in range(1, len(Q) - 2): + p0, p1, p2, p3 = Q[i - 1], Q[i], Q[i + 1], Q[i + 2] + out.append(.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + + (-p0 + 3 * p1 - 3 * p2 + p3) * t ** 3)) + if not closed: + out.append(P[-1:]) + return np.vstack(out) + + +def ell(c, rx, ry, ang=0.0, n=36): + t = np.linspace(0, 2 * math.pi, n, endpoint=False) + E = np.stack([rx * np.cos(t), ry * np.sin(t)], 1) + if ang: + a = math.radians(ang) + R = np.array([[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]]) + E = E @ R.T + return E + np.asarray(c, float) + + +def egg(C, u, L, dep, full=.14, n=44): + """the body egg: fuller at the breast end (+u), tapering to the vent (animal-064 posture line first)""" + t = np.linspace(0, 2 * math.pi, n, endpoint=False) + p = .5 * L * np.cos(t) + q = .5 * L * dep * np.sin(t) * (1 + full * np.cos(t)) + return np.asarray(C, float) + p[:, None] * u + q[:, None] * perp(u) + + +def hull(P): + """convex hull (monotone chain): head + body hull = Laws' carved straight angles at nape and throat (no snowman)""" + P = sorted(map(tuple, np.round(np.asarray(P, float), 6))) + if len(P) < 3: + return np.asarray(P) + + def cross(o, a, b): + return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) + lo, up = [], [] + for p in P: + while len(lo) >= 2 and cross(lo[-2], lo[-1], p) <= 0: + lo.pop() + lo.append(p) + for p in reversed(P): + while len(up) >= 2 and cross(up[-2], up[-1], p) <= 0: + up.pop() + up.append(p) + return np.array(lo[:-1] + up[:-1]) + + +def ribbon(spine, widths, n=6): + """closed outline round a spine (root -> tip) with a width per spine point (smoothed)""" + S = crv(spine, closed=False, n=n) + w = np.interp(np.linspace(0, 1, len(S)), np.linspace(0, 1, len(widths)), widths) + d = np.gradient(S, axis=0) + N = np.stack([-d[:, 1], d[:, 0]], 1) + N /= np.linalg.norm(N, axis=1, keepdims=True) + 1e-12 + return np.vstack([S + N * (w / 2)[:, None], (S - N * (w / 2)[:, None])[::-1]]) + + +def outline_at(P, C, deg): + """the outline point of P seen from C in world direction deg""" + d = np.asarray(P) - np.asarray(C) + a = np.degrees(np.arctan2(d[:, 1], d[:, 0])) + i = int(np.argmin(np.abs((a - deg + 180) % 360 - 180))) + return np.asarray(P)[i] + + +# ----------------------------------------------------------------------------------------------------- the bird +class Bird: + """the decided drawing: masses (name -> list of (outline, colour key, part, z)), strokes, features, landmarks, + all in unit coords (y up, facing +x)""" + + def __init__(self, name, row, pose, P): + self.name, self.row, self.pose, self.P = name, row, pose, P + self.masses = [] # dict(name, pts, col, part, z, fd (deg), shade (bool), clip (mass name or None)) + self.strokes = [] # dict(pts, w, col, z, part) + self.dots = [] # dict(c, r, col, z, kind) + self.lm = {} + self.water = None # y of the water line (swim / wade) + self.ground = 0.0 + + def mass(self, name, pts, col, part="body", z=0.0, fd=180.0, shade=True, clip=None, line=True): + self.masses.append(dict(name=name, pts=np.asarray(pts, float), col=col, part=part, z=z, fd=fd, shade=shade, + clip=clip, line=line)) + + def stroke(self, pts, w, col, z=0.0, part="leg", fd=-90.0, cap=True): + self.strokes.append(dict(pts=np.asarray(pts, float), w=w, col=col, z=z, part=part, fd=fd)) + + def dot(self, c, r, col, z=9.0, kind="dot", ry=None, ang=0.0, part="eye"): + self.dots.append(dict(c=np.asarray(c, float), r=r, ry=ry if ry is not None else r, col=col, z=z, kind=kind, + ang=ang, part=part)) + + +def _bill_shape(shape, bl, bd, open_=0.0): + """the bill in its own frame (x along the eye-bill line from the gape, y up), as (upper, lower) outlines. + animal-095: bill length and shape (cone, dagger, hook, spatula) is the first ID mark after the silhouette""" + h = bd / 2 + if shape == "cone": + up = [(0, h), (bl * .5, h * .55), (bl, 0), (0, 0)] + lo = [(0, 0), (bl * .96, -.02 * bd), (bl * .5, -h * .45), (0, -h * .9)] + elif shape == "thin": + up = [(0, h * .8), (bl * .5, h * .45), (bl, 0), (0, 0)] + lo = [(0, 0), (bl * .97, -.02 * bd), (bl * .5, -h * .4), (0, -h * .75)] + elif shape in ("dagger",): + up = [(0, h), (bl * .45, h * .55), (bl, 0), (0, 0)] + lo = [(0, 0), (bl, -.01), (bl * .45, -h * .5), (0, -h * .85)] + elif shape == "crow": + up = [(0, h), (bl * .45, h * .8), (bl * .85, h * .3), (bl, -h * .15), (0, 0)] + lo = [(0, 0), (bl * .9, -h * .1), (bl * .5, -h * .5), (0, -h * .85)] + elif shape == "pigeon": + up = [(0, h), (bl * .35, h * .9), (bl * .55, h * .45), (bl, -h * .1), (0, 0)] + lo = [(0, 0), (bl * .95, -h * .15), (bl * .5, -h * .45), (0, -h * .7)] + elif shape == "hook": + up = [(0, h), (bl * .5, h * .9), (bl * .9, h * .35), (bl, -h * .5), (bl * .82, -h * .9), (bl * .7, -h * .1), + (0, -h * .1)] + lo = [(0, -h * .1), (bl * .66, -h * .2), (bl * .45, -h * .6), (0, -h * .8)] + elif shape == "parrot": + up = [(0, h), (bl * .55, h * 1.0), (bl * .95, h * .4), (bl, -h * .5), (bl * .82, -h * 1.15), (bl * .7, -h * .5), + (bl * .35, -h * .1), (0, -h * .1)] + lo = [(0, -h * .1), (bl * .45, -h * .2), (bl * .5, -h * .7), (bl * .25, -h * 1.0), (0, -h * .85)] + elif shape == "toucan": + up = [(0, h), (bl * .5, h * 1.05), (bl * .9, h * .55), (bl, h * .05), (bl * .6, -h * .05), (0, -h * .05)] + lo = [(0, -h * .05), (bl * .6, -h * .1), (bl * .98, h * .02), (bl * .75, -h * .45), (bl * .3, -h * .75), + (0, -h * .9)] + elif shape in ("spatula", "goose", "swan"): + # a flat broad bill with a slight dip in the culmen, a rounded tip and a dark nail (duck: .45-.6 head) + up = [(0, h * .9), (bl * .25, h * .55), (bl * .7, h * .42), (bl * .98, h * .2), (bl, -h * .05), (0, -h * .05)] + lo = [(0, -h * .05), (bl * .97, -h * .1), (bl * .75, -h * .4), (bl * .3, -h * .5), (0, -h * .7)] + if shape == "swan": + up = [(0, h * 1.1), (bl * .3, h * .75), (bl * .7, h * .45), (bl * .98, h * .2), (bl, -h * .1), + (0, -h * .1)] + elif shape == "gull": + up = [(0, h), (bl * .6, h * .55), (bl * .88, h * .45), (bl, h * .05), (bl * .96, -h * .25), (0, -h * .05)] + lo = [(0, -h * .05), (bl * .92, -h * .3), (bl * .72, -h * .75), (bl * .4, -h * .5), (0, -h * .75)] + elif shape == "fowl": + up = [(0, h), (bl * .5, h * .7), (bl * .95, h * .05), (bl, -h * .3), (0, -h * .05)] + lo = [(0, -h * .05), (bl * .85, -h * .25), (bl * .4, -h * .55), (0, -h * .8)] + elif shape == "flamingo": + up = [(0, h), (bl * .45, h * .85), (bl * .6, h * .2), (bl * .85, -h * .9), (bl, -h * 1.6), (bl * .9, -h * 1.7), + (bl * .55, -h * .3), (0, -h * .05)] + lo = [(0, -h * .05), (bl * .5, -h * .45), (bl * .82, -h * 1.55), (bl * .6, -h * 1.0), (bl * .4, -h * .8), + (0, -h * .8)] + else: + return _bill_shape("cone", bl, bd) + up, lo = np.array(up, float), np.array(lo, float) + if open_: + lo = lo @ np.array([[math.cos(math.radians(-open_)), -math.sin(math.radians(-open_))], + [math.sin(math.radians(-open_)), math.cos(math.radians(-open_))]]).T + return up, lo + + +def _frame(o, ang): + """local (x, y) in a frame at o rotated by ang deg -> world""" + R = np.array([[math.cos(math.radians(ang)), -math.sin(math.radians(ang))], + [math.sin(math.radians(ang)), math.cos(math.radians(ang))]]) + o = np.asarray(o, float) + return lambda pts: np.asarray(pts, float) @ R.T + o + + +# ------------------------------------------------------------------------------------------------ head features +def add_head(B, H, hr, gaze, zbase=5.0, open_=0.0, closed=False, lod=3): + """head circle at H (radius hr), eye-bill line at `gaze` deg (animal-021: set the eye-bill line first, the eye + on top of it just behind the gape), bill by family, eye, crest / comb / cap / markings by species""" + P, col = B.P, B.row["col"] + name = B.name + u = dirv(gaze) + n = perp(u) + head = ell(H, hr * 1.04, hr, gaze) + hc = col.get("head", col["back"]) + B.mass("head", head, hc, "head", zbase, fd=gaze + 180) + # bill (from the gape, slightly below the eye line), its length and depth by the canon row + bl_, bd_, shape = P["bill"] + bl, bd = bl_ * hr * 2, bd_ * hr * 2 + gape = H + u * hr * .86 - n * hr * (.14 if shape not in ("hook", "parrot") else .3) + if shape in ("hook",): + gape = H + u * hr * .78 - n * hr * .28 + up, lo = _bill_shape(shape, bl, bd, open_) + F = _frame(gape, gaze) + bc = col.get("bill", (60, 50, 46)) + B.mass("bill_lo", F(lo), _mix(bc, (0, 0, 0), .12), "beak", zbase + .3, fd=gaze, shade=False) + B.mass("bill", F(up), bc, "beak", zbase + .4, fd=gaze, shade=True) + tip = F([(bl, 0)])[0] + B.lm.update(gape=gape, bill_tip=tip, head_c=H, head_r=hr, gaze=gaze) + if lod >= 2 and shape not in ("hook", "parrot", "flamingo"): + B.stroke(F([(0, -.02 * bd), (bl * .6, -.03 * bd)]), max(.012 * hr * 2, .002), _mix(bc, (0, 0, 0), .55), zbase + .5, + part="beak") + if shape == "spatula" and lod >= 2: + B.mass("nail", F(ell((bl * .93, .02 * bd), bl * .07, bd * .22)), _mix(bc, (0, 0, 0), .5), "beak", zbase + .45, + shade=False, line=False) + if shape == "swan": + knob = col.get("knob") + if knob: + B.mass("knob", F(ell((bl * .07, bd * .5), bl * .1, bd * .3)), knob, "beak", zbase + .45, shade=False, + line=False) + if col.get("lore"): + B.mass("lore", F([(0, bd * .45), (0, -bd * .25), (-hr * .5, hr * .12), (-hr * .45, hr * .3)]), col["lore"], + "face", zbase + .35, shade=False, line=False) + if shape == "gull" and col.get("billspot") and lod >= 2: + B.mass("billspot", F(ell((bl * .72, -bd * .35), bl * .08, bd * .2)), col["billspot"], "beak", zbase + .45, + shade=False, line=False) + if shape == "flamingo" and col.get("billbase"): + B.mass("billbase", F([(0, bd * .5), (bl * .45, bd * .42), (bl * .5, -bd * .4), (0, -bd * .4)]), col["billbase"], + "beak", zbase + .45, shade=False, line=False) + if shape == "pigeon" and col.get("cere") and lod >= 2: + B.mass("cere", F(ell((bl * .2, bd * .45), bl * .2, bd * .28)), col["cere"], "beak", zbase + .45, shade=False, + line=False) + # eye: on top of the eye-bill line, just behind the gape (songbird); further back and higher on waterfowl + back = {"duck": .42, "wader": .3, "owl": .3, "fowl": .32, "raptor": .32}.get(B.row["fam"], .36) + E = gape - u * hr * (back + .28) + n * hr * (.24 if B.row["fam"] != "duck" else .3) + er = P["eye"] * hr * 2 + B.lm["eye"] = E + # face markings before the eye + if col.get("cap"): + B.mass("cap", F(ell((-hr * .9, hr * .5), hr * .75, hr * .5)), col["cap"], "head", zbase + .1, shade=False, + clip="head", line=False) + if col.get("crown"): # heron: black crown stripe from above the eye to the nape, then plumes + B.mass("crown", F([(-hr * .1, hr * .55), (-hr * .6, hr * 1.1), (-hr * 1.6, hr * .7), (-hr * 1.4, hr * .3), + (-hr * .2, hr * .3)]), col["crown"], "head", zbase + .1, shade=False, clip="head", + line=False) + if col.get("plume") and lod >= 2: + B.stroke(F([(-hr * .8, hr * .5), (-hr * 1.9, hr * .25), (-hr * 2.9, -hr * .1)]), hr * .09, col["plume"], + zbase - .1, part="feather") + if col.get("mask"): + B.mass("mask", F([(hr * .95, hr * .25), (-hr * .05, hr * .25), (-hr * .3, -hr * .1), (hr * .2, -hr * .75), + (hr * .9, -hr * .45)]), col["mask"], "face", zbase + .1, shade=False, clip="head", line=False) + if col.get("face"): + B.mass("face", F(ell((hr * .25, hr * .02), hr * .55, hr * .42)), col["face"], "face", zbase + .1, shade=False, + clip="head", line=False) + if col.get("cheek"): + if B.row["fam"] == "duck": # canada goose chinstrap: white from the cheek round the throat + B.mass("cheek", F([(-hr * .2, hr * .1), (hr * .3, -hr * .05), (hr * .2, -hr * .95), (-hr * .6, -hr * .9), + (-hr * .55, -hr * .2)]), col["cheek"], "face", zbase + .1, shade=False, clip="head", + line=False) + else: + B.mass("cheek", F(ell((-hr * .3, -hr * .25), hr * .45, hr * .32)), col["cheek"], "face", zbase + .1, + shade=False, clip="head", line=False) + if col.get("eyestripe") and lod >= 2: + B.stroke(F([(hr * .55, hr * .2), (-hr * .9, hr * .1)]), hr * .14, col["eyestripe"], zbase + .15, part="face") + if col.get("throat") and B.row["fam"] != "penguin": + B.mass("throatH", F(ell((hr * .2, -hr * .75), hr * .6, hr * .45)), col["throat"], "face", zbase + .1, + shade=False, clip="head", line=False) + if col.get("sheen") and B.row["fam"] == "duck" and lod >= 2: + B.mass("sheenH", F(ell((-hr * .1, hr * .35), hr * .55, hr * .3, 10)), _mix(hc, col["sheen"], .55), "head", + zbase + .1, shade=False, clip="head", line=False) + if P.get("crest"): + c = P["crest"] * hr * 2 + cc = col.get("crestc", hc) + B.mass("crest", F([(-hr * .1, hr * .8), (-hr * .5, hr * .8 + c * .9), (-hr * .95, hr * .6 + c * .55), + (-hr * .9, hr * .3)]), cc, "head", zbase - .05, fd=gaze + 120) + if P.get("comb"): + cm = col.get("comb", (210, 40, 40)) + k = 1.0 if P["comb"] == 1 else 1.5 + pts = [(hr * .55, hr * .55)] + for i in range(5): + a = -hr * .2 * k + (-i * hr * .28) + pts += [(a + hr * .55 + hr * .1, hr * (.95 + .35 * k)), (a + hr * .44, hr * .78)] + pts += [(-hr * .75, hr * .55)] + B.mass("comb", F(pts), cm, "comb", zbase - .05, fd=90, shade=True) + # wattles under the bill + B.mass("wattle", F(ell((-hr * .05, -hr * (.42 + .15 * k)), hr * .17, hr * (.26 + .12 * k))), cm, "comb", + zbase + .2, fd=-90) + # the eye: dark, one catch-light upper front (animal-095); eye ring as a species mark + if col.get("eyering") and lod >= 3: + B.dot(E, er * 1.45, col["eyering"], zbase + .6, kind="ring") + if closed: + B.stroke([E - u * er * 1.1, E + n * er * .25, E + u * er * 1.1], max(er * .5, .004), (30, 24, 24), + zbase + .7, part="eye") + else: + B.dot(E, er, col.get("iris", (22, 18, 18)), zbase + .7, kind="eye") + return head + + +# ----------------------------------------------------------------------------------------------- perched / ground +def build_ground(B, rng, lod): + """perch / stand / walk / peck / sleep / swim / wade: the side view built from the posture line (animal-064)""" + P, col, pose, fam = B.P, B.row["col"], B.pose, B.row["fam"] + posts = B.row["post"] + key = "swim" if pose == "swim" else "perch" if pose in ("perch", "sleep") else "stand" + a = rng.uniform(*posts[key]) + if pose == "walk": + a = a * .8 + 4 + if pose == "peck": + a = rng.uniform(-14, -4) if fam != "fowl" else rng.uniform(-6, 4) + if pose == "wade" and fam == "wader": + a = rng.uniform(28, 38) + if pose == "sleep": + a = a * .7 + fluff = pose == "sleep" + dep = P["dep"] * (1.18 if fluff else 1.0) # animal-070: fluffed body height/length .55-.65 + u = dirv(a) + n = perp(u) + L = 1.0 + # body egg at the origin first, then lifted so the leg exit stands on the ground + body0 = egg(V(0, 0), u, L, dep, full=.16 if fam != "duck" else .05) + leg = P["leg"] * (.55 if pose in ("perch", "sleep", "peck") and fam not in ("wader",) else 1.0) + if fluff and fam not in ("wader",): + leg *= .3 # animal-070: fluffed, the belly feathers hide the legs + tib = P.get("tib", 0) or 0 + if pose == "swim": + leg, tib = 0.0, 0.0 + # leg exit: below the centre of mass, a little behind it (legs set far back on waterfowl, animal-097) + lx = -P.get("legback", .02) * L + bot = body0[np.abs(body0[:, 0] - lx) < .09] + bottom = bot[:, 1].min() if len(bot) else body0[:, 1].min() + if pose == "swim": + # animal-0xx swimming: the water line at .3-.4 of body height + ys = body0[:, 1] + C = V(0, -(ys.min() + (ys.max() - ys.min()) * .35)) + B.water = 0.0 + else: + C = V(0, leg + tib - bottom * .97) + body = body0 + C + B.lm.update(posture_deg=a, body_c=C, body_len=L) + # --- tail (from inside the body, animal-066): the wedge / fan / point leaves the rump + rump = C - u * L * .42 + n * L * dep * .08 + ta = a + 180 - P["tail_ang"] if fam != "fowl" else 180 - P["tail_ang"] * (1 if pose != "peck" else .5) + if pose == "swim": + ta = 180 - max(P["tail_ang"], 12) + if fam == "duck": + ta = 180 - P["tail_ang"] if pose != "peck" else a + 180 - P["tail_ang"] + td = dirv(ta) + tl = P["tail"] * L + tw = dep * L * .42 + shape = B.row.get("tail_shape", "wedge") + tn = perp(td) + if shape == "fork": + tail = [rump + tn * tw * .5, rump + td * tl * 1.05 + tn * tw * .45, rump + td * tl * .62, + rump + td * tl * 1.05 - tn * tw * .2, rump - tn * tw * .5] + elif shape == "point": + tail = [rump + tn * tw * .6, rump + td * tl * .8 + tn * tw * .2, rump + td * tl, rump + td * tl * .7 - tn * tw * .25, + rump - tn * tw * .6] + elif shape == "fan": + # hen: a short upright fan that grows out of the back line (no paddle on a stalk) + rump = rump + u * .12 + n * dep * .1 + tail = [rump + tn * tw * .9, rump + td * tl * .7 + tn * tw * .55, rump + td * tl * 1.02 + tn * tw * .05, + rump + td * tl * .75 - tn * tw * .3, rump - tn * tw * 1.0] + elif shape == "sickle": + tail = [rump + tn * tw * .4, rump + td * tl * .7 + tn * tw * 1.2, rump + td * tl * 1.1 + tn * tw * .4, + rump + td * tl * 1.0 - tn * tw * .6, rump + td * tl * .55 - tn * tw * .7, rump - tn * tw * .6] + else: + tail = [rump + tn * tw * .5, rump + td * tl * .98 + tn * tw * .38, rump + td * tl * 1.02 - tn * tw * .05, + rump + td * tl * .98 - tn * tw * .4, rump - tn * tw * .5] + tcol = col.get("tail", col["back"]) + B.mass("tail", crv(tail, n=5), tcol, "tail", 1.0, fd=ta) + B.lm["tail_tip"] = rump + td * tl + if col.get("tailband") and lod >= 2: + B.mass("tailband", [rump + td * tl * .78 + tn * tw * .6, rump + td * tl * 1.1 + tn * tw * .6, + rump + td * tl * 1.1 - tn * tw * .6, rump + td * tl * .78 - tn * tw * .6], col["tailband"], + "tail", 1.05, clip="tail", shade=False, line=False) + if shape == "sickle" and lod >= 2: + for i in range(3): + s0 = rump + tn * tw * (.2 - .25 * i) + B.stroke(crv([s0, s0 + td * tl * .5 + tn * tw * (1.3 - .3 * i), s0 + td * tl * (1.05 - .1 * i) + - tn * tw * (.2 + .3 * i)], closed=False, n=6), tw * .22, _mix(tcol, col.get("sheen", tcol), .4), + 1.1, part="feather", fd=ta) + # --- body (undertail angle carved by the hull of the rear body and the tail base, animal-065) + bcol = col["back"] + # --- head + neck: the clock trick (animal-021): the head sits on top and forward of the breast + hr = P["head"] * L * .5 + neck = P["neck"] * L + gaze = rng.uniform(-8, 4) + if pose == "peck": + gaze = rng.uniform(-80, -60) + if pose == "crow": + gaze = 35 + open_ = 28 if pose == "crow" else 0.0 + sleep = pose == "sleep" + front = C + u * L * .5 + if pose == "peck": + # the head goes down to the ground ahead of the feet, bill touching the ground + bl_ = P["bill"][0] * hr * 2 + Hh = V(front[0] + hr * .15 + neck * .45, hr * .45 + bl_ * .85) + nb = C + u * L * .3 + n * dep * L * .25 + spine = [nb, (nb + Hh) * .5 + V(.05 * neck, .04), Hh] + if neck > .02: + B.mass("neck", ribbon(spine, [dep * L * .55, hr * 1.5]), col.get("neck", bcol), "neck", 4.0, fd=-90) + elif neck <= .12 or fam in ("fowl", "raptor") and neck < .3: + phi = B.row.get("hang", 60) + rng.uniform(-6, 6) + if fam in ("owl",): + phi = 90 + top = outline_at(body, C, phi) + Hh = top + dirv(phi) * hr * (.15 + neck * 4.0) + V(0, neck * .55) + if sleep: + Hh = top + dirv(phi) * hr * -.25 + if neck > .02: + # a short neck: the hull of the shoulder arc of the body and the head (straight carved nape and throat + # lines, animal-065); the hackles / neck patch colour it + d = body - C + ang = np.degrees(np.arctan2(d[:, 1], d[:, 0])) + arc = body[np.abs((ang - phi + 180) % 360 - 180) < 38] + npts = hull(np.vstack([arc, ell(Hh, hr * .92, hr * .9)])) + B.mass("neck", npts, col.get("hackle", col.get("neck", bcol)) if fam == "fowl" else col.get("neck", bcol), + "neck", 4.0, fd=-90) + else: + # a long neck is an S (goose, swan, heron): up from the breast, forward under the head (animal-062, 097) + nb = outline_at(body, C, a + 38) - u * .04 + if fam == "wader": + if pose in ("perch", "stand", "sleep") or sleep: + # at rest the heron's neck folds into an S kink, the head sunk on the shoulders + Hh = nb + V(.06, neck * .32 + hr * .4) + m1 = nb + V(.18, neck * .08) + m2 = nb + V(-.02, neck * .22) + spine = [nb, m1, m2, Hh] + else: + # wading / hunting: the neck stretched up and forward in an open S, ready to strike + Hh = nb + V(neck * .38, neck * .72) + m1 = nb + V(neck * .16, neck * .22) + m2 = nb + V(neck * .1, neck * .5) + spine = [nb, m1, m2, Hh] + if B.name == "flamingo": + Hh = nb + V(neck * .22, neck * .78) + spine = [nb, nb + V(neck * .25, neck * .2), nb + V(-neck * .05, neck * .5), Hh] + gaze = rng.uniform(-14, -4) if B.name != "flamingo" else -30 + elif B.name in ("swan", "black swan"): + # swan: a smooth S, the bill pointing down 30-60 deg (animal-097) + Hh = nb + V(neck * .2, neck * .86) + spine = [nb, nb + V(neck * .16, neck * .2), nb + V(neck * .14, neck * .42), nb + V(.0, neck * .62), + nb + V(.04, neck * .78), Hh] + gaze = rng.uniform(-50, -34) + else: + Hh = nb + V(neck * .2, neck * .9) + spine = [nb, nb + V(neck * .14, neck * .35), nb + V(neck * .06, neck * .7), Hh] + gaze = rng.uniform(-10, 2) + w0 = dep * L * (.46 if fam == "wader" else .5) + ws = [w0, hr * 1.25, hr * 1.1, hr * 1.25] if len(spine) == 4 else [w0, w0 * .62, hr * 1.2, hr * 1.1, + hr * 1.15, hr * 1.3] + B.mass("neck", ribbon(spine, ws, n=10), col.get("neck", bcol), "neck", 4.0, fd=-90) + if fam == "wader" and col.get("streak") and lod >= 2: + # heron: a dark streak line down the front of the neck + fr = crv(spine, closed=False, n=6) + d = np.gradient(fr, axis=0) + Nn = np.stack([d[:, 1], -d[:, 0]], 1) + Nn /= np.linalg.norm(Nn, axis=1, keepdims=True) + 1e-9 + seg = fr[len(fr) // 4: -2] + Nn[len(fr) // 4: -2] * hr * .35 + B.stroke(seg, hr * .16, col["streak"], 4.2, part="neck", fd=-90) + # the silhouette: hull of the body egg and the head (carved angles), the rear hull with the tail base + headpts = ell(Hh, hr * 1.04, hr) + if neck <= .12 or pose == "peck": + sil = hull(np.vstack([body, headpts])) + else: + sil = body + rear = hull(np.vstack([body[np.dot(body - C, u) < -.1], np.array(tail[:1] + tail[-1:])])) + B.mass("body", sil, bcol, "body", 2.0, fd=a + 180) + B.mass("rear", rear, bcol, "body", 1.9, fd=a + 180) + B.lm.update(body=body, rump=rump) + # underparts: belly / breast colours on the lower half of the body (Seton's tracts: throat, breast, belly) + lowc = col.get("belly") + if lowc: + under = [C + u * .62 - n * .02 * dep, C + u * .2 - n * dep * .12, C - u * .25 - n * dep * .06, + C - u * .6 + n * dep * .05, C - u * .6 - n * dep * 1.2, C + u * .62 - n * dep * 1.2] + if fam == "duck": + under = [C + u * .7 + V(0, -dep * .1), C + V(.1, -dep * .12), C + V(-.62, -dep * .05), C + V(-.62, -dep), + C + V(.7, -dep)] + B.mass("belly", under, lowc, "body", 2.1, clip="body", shade=False, line=False) + if col.get("breast"): + br = [C + u * .62 + n * dep * .5, C + u * .05 + n * dep * .2, C - u * .05 - n * dep * .2, + C + u * .1 - n * dep * .9, C + u * .7 - n * dep * .9] + if fam == "duck": + br = [C + V(.75, dep * .4), C + V(.18, dep * .3), C + V(.1, -dep * .6), C + V(.75, -dep * .6)] + B.mass("breast", br, col["breast"], "body", 2.15, clip="body", shade=False, line=False) + if col.get("flank") and pose != "swim": + pass + if col.get("vent"): + B.mass("vent", [rump + V(.05, .1), rump + V(.3, -.2), rump + V(-.1, -.3), rump + V(-.2, 0)], col["vent"], "body", + 2.12, clip="rear", shade=False, line=False) + if col.get("throat") and fam == "passerine": + B.mass("throat", ell(C + u * .48 + n * dep * .12, .14, .12), col["throat"], "body", 2.16, clip="body", + shade=False, line=False) + if col.get("necklace") and lod >= 2: + B.stroke(crv([Hh + V(-hr * .7, -hr * .2), Hh + V(hr * .1, -hr * 1.05), Hh + V(hr * .8, -hr * .55)], + closed=False), hr * .14, col["necklace"], 2.3, part="body") + if col.get("streak") and lod >= 3 and fam in ("passerine", "raptor"): + for i in range(11): + p = C + u * rng.uniform(-.25, .45) - n * dep * rng.uniform(.05, .38) + B.stroke([p, p - u * .07 - n * .01], .022, col["streak"], 2.2, part="body", fd=a + 180) + if fam == "duck" and col.get("collar") and lod >= 2 and neck > .1: + nb_ = outline_at(body, C, a + 38) if neck > .12 else Hh + cpt = (nb_ + Hh) * .5 + V(0, -.02) + B.mass("collar", [cpt + V(-hr * 2, hr * .1), cpt + V(hr * 2, -hr * .02), cpt + V(hr * 2, -hr * .26), + cpt + V(-hr * 2, -hr * .14)], col["collar"], "neck", 4.3, clip="neck", shade=False, + line=False) + if col.get("neck") and B.name in ("pigeon",) and lod >= 2: + B.mass("neckshine", ell(Hh + V(-hr * .2, -hr * 1.35), hr * .95, hr * .8), col["neck"], "neck", 4.5, + clip="body", shade=False, line=False) + if col.get("neck2"): + B.mass("neckshine2", ell(Hh + V(hr * .1, -hr * 1.6), hr * .7, hr * .5), col["neck2"], "neck", 4.55, + clip="body", shade=False, line=False) + if col.get("scallop") and lod >= 3: + for i in range(4): + y = C + V(-.15 - .1 * i, dep * (.12 - .08 * i)) + B.stroke(crv([y + V(-.12, 0), y + V(0, -.04), y + V(.12, 0)], closed=False), .015, col["scallop"], 2.25, + part="body") + # --- legs (animal-069: the visible 'knee' is the ankle; the leg exit by the clock trick, below the body centre) + exit_ = V(lx + C[0] * 0, C[1] + bottom * .97) + legc = col.get("leg", (120, 100, 80)) + lw = max(.035 * (P["dep"] / .6), .022) * (1.6 if fam == "raptor" else 1.0) + if fam == "wader": + lw = .03 + if fam == "duck": + lw = .05 + if fam == "fowl": + lw = .06 if B.name != "chick" else .05 + feet = [] + if pose != "swim": + sp = .1 if pose != "walk" else .22 + stances = [(-1, -sp * .5), (1, sp * .5)] + if pose == "wade" and fam == "wader" and rng.random() < .35 or pose == "one_leg": + stances = [(1, 0.0)] + for far, dx in stances: + fz = .5 if far < 0 else 3.0 + fx = exit_[0] + dx + (.04 if pose == "perch" else 0) + lc = legc if far > 0 else _mix(legc, (0, 0, 0), .25) + top = exit_ + V(dx * .3, .06) + if fam == "wader" or tib: + knee = V(fx - .02 + dx * .2, tib + leg * .02) + if pose == "walk" and far < 0: + knee = V(fx + .12, tib + leg * .25) + B.stroke([top, V(top[0] + .02, tib + leg * .6), knee, V(fx - .1, 0.0)], lw, lc, fz, part="leg") + feet.append((V(fx - .1, 0.0), far, lc, True)) + continue + B.stroke([top, V(top[0] + .01, leg + tib * .55), V(fx, leg), V(fx, 0.0)], lw, lc, fz, part="leg") + elif pose == "perch": + # perched: a short slanting tarsus from the heel under the belly feathers forward to the toes + B.stroke([top + V(-.04, 0), V(fx - .02, leg * .4), V(fx, 0.0)], lw, lc, fz, part="leg") + else: + heel = V(fx - .04, leg * .55) + B.stroke([top, heel, V(fx, 0.0)], lw, lc, fz, part="leg") + feet.append((V(fx, 0.0), far, lc, False)) + if fam == "raptor" and col.get("trousers"): + B.mass("trouser%d" % far, ell(top + V(0, -.06), .12, .14), col["trousers"], "body", fz + .1, fd=-90) + if fam == "owl": + B.mass("fleg%d" % far, ell(V(fx, .05), .09, .08), col.get("leg", col["belly"]), "leg", 2.5 + fz * .1, + fd=-90) + B.lm["feet"] = [f[0] for f in feet] + toe = B.row.get("toe", "perch") + for F_, far, lc, lifted in feet: + zt = 2.6 if pose == "perch" and far > 0 else (.55 if far < 0 else 3.05) + tl_ = {"web": .2, "long": .3, "ground": .2, "raptor": .14, "zygo": .1}.get(toe, .13) + tw_ = lw * .7 + if toe == "web" and pose != "perch": + B.mass("web%d" % far, [F_ + V(-.02, .01), F_ + V(tl_ * .9, .03), F_ + V(tl_, -.005), F_ + V(tl_ * .55, -.01), + F_ + V(-.04, -.005)], lc, "leg", zt, fd=0, shade=False) + continue + if pose == "perch": + # toes wrap the branch: 3 forward over the top and down its front, 1 back (animal-069) + for dx in ((.0, .04) if lod >= 2 else (.02,)): + B.stroke([F_ + V(-.02, .01), F_ + V(tl_ * .6 + dx, .0), F_ + V(tl_ * .75 + dx, -tl_ * .5)], tw_, lc, zt, + part="leg") + B.stroke([F_ + V(0, .01), F_ + V(-tl_ * .55, -.01), F_ + V(-tl_ * .6, -tl_ * .4)], tw_, lc, zt, part="leg") + else: + for ang in ((-4, 8) if lod >= 2 else (2,)): + d = dirv(ang) + B.stroke([F_ + V(-.01, .01), F_ + d * tl_], tw_, lc, zt, part="leg") + B.stroke([F_ + V(.01, .01), F_ + V(-tl_ * .5, .0)], tw_, lc, zt, part="leg") + # --- folded wing: feather GROUPS (animal-067: wrist at the shoulder, leading edge, secondaries edge, tertials, + # primary projection past the tertials toward the tail) + if fam != "penguin": + wl = P["wing"] * L + wrist = C + u * L * .26 + n * dep * L * .3 + if fam == "duck": + wrist = C + u * .22 + n * dep * .22 + proj = P["proj"] * L + back_edge = C + n * dep * L * .46 - u * .05 + tipw = C - u * (L * .44 + proj) + n * dep * L * (.05 if fam != "duck" else .3) + if fam == "duck": + tipw = C - u * (L * .38 + proj) + n * dep * .28 + sec = C - u * L * .18 - n * dep * L * .12 + low = C + u * L * .08 - n * dep * L * .1 + wing = [wrist, back_edge, (back_edge + tipw) * .5 + n * .02, tipw, (tipw + sec) * .5 - n * .01, sec, low] + if fam == "duck": + wing = [wrist, C + n * dep * .44 - u * .05, tipw + u * .2 + n * .04, tipw, C - u * .3 + n * dep * .06, + C + u * .05 + n * dep * .04] + wcol = col.get("wing", _mix(bcol, (0, 0, 0), .1)) + wpts = crv(wing, n=6) + B.mass("wing", wpts, wcol, "covert", 3.0, fd=a + 180) + B.lm.update(wrist=wrist, wing_tip=tipw) + pc = col.get("prim", _mix(wcol, (0, 0, 0), .3)) + # primaries: the rear third, darker + pr = [C - u * L * .12 + n * dep * .44, tipw + u * .02, C - u * L * .22 - n * dep * .1, + C - u * L * .1 - n * dep * .02] + B.mass("prim", crv(pr + [pr[0] + V(0, 0)], n=4), pc, "primary", 3.1, clip="wing", shade=False, line=False) + if col.get("spec") and lod >= 2: + B.mass("spec", [C - u * .08 - n * dep * .02, C - u * .38 + n * dep * .14, C - u * .4 + n * dep * .02, + C - u * .1 - n * dep * .14], col["spec"], "secondary", 3.2, clip="wing", shade=False, + line=False) + if col.get("scap") and lod >= 2: + B.mass("scap", ell(C + u * .1 + n * dep * .15, .28, .1, a), col["scap"], "covert", 3.15, clip="wing", + shade=False, line=False) + if col.get("mirror") and lod >= 3: + B.dot(tipw + u * .08 + n * .01, .025, col["mirror"], 3.3, kind="flat", part="primary") + if col.get("bar") and lod >= 2 and fam not in ("owl",): + # wing bars: rows of covert tips (pigeon: two dark bars; sparrow / jay: pale) + for i, t in enumerate((.42, .58)[:2 if B.name in ("pigeon", "sparrow", "goldfinch", "blue jay", "woodpecker") + else 1]): + p0 = wrist * (1 - t) + sec * t + q0 = back_edge * (1 - t) + tipw * t * .6 + C * .0 + mid = (p0 * .55 + q0 * .45) + B.stroke([mid + n * dep * .12 + u * .05, mid - n * dep * .08 - u * .01], .03, col["bar"], 3.25, + part="covert", fd=a + 180) + if lod >= 3: + # covert scallops and tertial / primary edges: feather GROUPS, not single feathers (animal-067, 068) + edge = _mix(wcol, (255, 250, 240), .16) + for i in range(3): + t = .25 + .14 * i + p = wrist * (1 - t) + sec * t + B.stroke(crv([p + n * dep * .2, p + n * dep * .02 - u * .05, p - n * dep * .12 - u * .02], + closed=False, n=4), .012, edge, 3.35, part="covert") + for i in range(3): + q = tipw + u * (.18 + .1 * i) + n * dep * (.03 + .02 * i) + B.stroke([q, q - u * .2 - n * .015 * i], .01, _mix(pc, (255, 250, 240), .14), 3.36, part="primary") + else: + flip = [C + u * .3 + n * dep * .2, C - u * .25 + n * dep * .25, C - u * .4 - n * dep * .2, + C + u * .1 - n * dep * .05] + B.mass("wing", crv(flip, n=5), col["wing"], "covert", 3.0, fd=a + 180) + B.mass("bellyP", [C + u * .7 - n * dep * .05, C - u * .6 - n * dep * .05, C - u * .6 - n, C + u * .7 - n], + col["belly"], "body", 2.1, clip="body", shade=False, line=False) + if col.get("throat"): + B.mass("throatP", ell(C + u * .42 - n * dep * .2, .1, .08, a), col["throat"], "body", 2.2, clip="body", + shade=False, line=False) + # --- head on top + add_head(B, Hh, hr, gaze, zbase=5.0, open_=open_, closed=sleep, lod=lod) + return B + + +# ----------------------------------------------------------------------------------------------------- the owl +def build_owl(B, rng, lod, f=1): + """animal-059: big round head .9-1.0 of body width, facial disc, forward eyes .2-.25 head width, hooked beak + low between them, tufts on horned owls, upright 75-90 deg, short tail just below the perch, feathered feet. + The head is THREE-QUARTER with the eye line tilted (animal-059: reads less like an emoji; Koson copy r20).""" + P, col = B.P, B.row["col"] + a = rng.uniform(*B.row["post"]["perch"]) + sleep = B.pose == "sleep" + u = dirv(a) + n = perp(u) + dep = P["dep"] + L = 1.0 + C = V(0, L * .48) + body = egg(C, u, L, dep, full=-.08) # an owl's egg is fuller below (the belly), pear-shaped + hw = P["head"] * dep * L # head width = .9-1.0 of the body width + hr = hw * .5 + H = C + u * L * .5 + V(0, hr * .25) + tilt = rng.uniform(8, 22) * rng.choice((-1, 1)) # head tilt: eye line not level + turn = rng.uniform(.45, .62) # how far the face turns toward the viewer (3/4) + B.lm.update(posture_deg=a, body_c=C, body_len=L, head_c=H, head_r=hr, tilt=tilt) + # tail (short, just below the perch) + tb = C - u * L * .4 + tail = [tb + V(-.08, .05), tb + V(-.14, -.28), tb + V(-.02, -.32), tb + V(.08, -.02)] + B.mass("tail", crv(tail, n=4), col["tail"], "tail", 1.0, fd=-100) + # body + head hull (no neck: the head sits in the shoulders) + headpts = ell(H, hr * 1.06, hr * .94, tilt * .3) + sil = hull(np.vstack([body, headpts])) + B.mass("body", sil, col["back"], "body", 2.0, fd=-90) + # breast: the pale front half of the body (the bird turns toward +x), with streaks / bars + br = [C + V(dep * .5 * .95, .45), C + V(-dep * .12, .38), C + V(-dep * .2, -.1), C + V(-dep * .05, -.6), + C + V(dep * .7, -.6)] + B.mass("belly", br, col["belly"], "body", 2.1, clip="body", shade=False, line=False) + if lod >= 2 and col.get("streak"): + rows = 5 if lod >= 3 else 3 + for i in range(rows): + y = C[1] + .32 - i * (.62 / rows) + for j in range(3 if lod >= 3 else 2): + x = C[0] - dep * .05 + j * dep * .2 + (i % 2) * dep * .08 + if B.name == "owl": # horned owl: fine bars across the breast + B.stroke([V(x - .05, y), V(x + .05, y - .01)], .02, col["streak"], 2.2, part="body", fd=0) + else: # barn / snowy: sparse spots + B.dot(V(x, y), .016, col["streak"], 2.2, kind="flat", part="body") + # folded wing: the near wing covers the back half of the body (the side away from the turn) + wing = [C + V(-dep * .06, .42), C + V(-dep * .52, .2), C + V(-dep * .55, -.28), C + V(-dep * .25, -.6), + C + V(-.02, -.5), C + V(dep * .02, .05)] + B.mass("wing", crv(wing, n=6), col["wing"], "covert", 3.0, fd=-100) + if lod >= 2: + for i in range(4 if lod >= 3 else 2): + y = C[1] + .25 - i * .19 + B.stroke(crv([V(C[0] - dep * .48, y), V(C[0] - dep * .25, y - .04), V(C[0] - dep * .02, y + .01)], + closed=False, n=4), .022, col.get("bar", _mix(col["wing"], (255, 255, 255), .3)), 3.2, + part="covert") + # feathered feet on the perch, toes over the front, dark talons + for dx, zf in ((-.07, 1.8), (.09, 3.0)): + F_ = V(C[0] + dx, 0.0) + B.mass("foot%d" % int(zf), ell(F_ + V(0, .04), .075, .06), col.get("leg", col["belly"]), "leg", zf, fd=-90) + if lod >= 2: + for k in ((-.03, .03) if lod >= 3 else (0,)): + B.stroke([F_ + V(k + .03, .0), F_ + V(k + .06, -.035), F_ + V(k + .045, -.06)], .018, (36, 30, 28), zf + .1, + part="leg") + B.lm["feet"] = [V(C[0] - .07, 0), V(C[0] + .09, 0)] + # head + three-quarter face + hc = col.get("head", col["back"]) + B.mass("head", headpts, hc, "head", 5.0, fd=90) + ex = H + V(hr * turn * .55, -hr * .05) + dc = ex + drx, dry = hr * (.62 + .2 * (1 - turn)), hr * .66 + Fh = _frame(dc, tilt) + disc = col.get("disc", col["belly"]) + if B.row.get("disc") == "heart": + dpts = Fh([(0, dry * .55), (drx * .7, dry * .95), (drx * 1.02, dry * .3), (drx * .7, -dry * .7), (0, -dry * 1.1), + (-drx * .7, -dry * .7), (-drx * .95, dry * .3), (-drx * .6, dry * .95)]) + dpts = crv(dpts, n=5) + else: + dpts = ell(dc, drx, dry, tilt) + B.mass("disc", dpts, disc, "face", 5.2, fd=90, shade=False) + if lod >= 2: + B.stroke(np.vstack([dpts, dpts[:1]]), hr * (.07 if lod >= 3 else .05), col.get("rim", _mix(hc, (0, 0, 0), .4)), + 5.25, part="face") + # eyes: near eye bigger and further from the disc rim; far eye foreshortened toward the far rim + er = P["eye"] * hw * 2 * .5 + e_near = Fh([(drx * .38, dry * .12)])[0] + e_far = Fh([(-drx * .42, dry * .1)])[0] + if col.get("brow") and lod >= 3: + for e_, s_ in ((e_near, 1), (e_far, .8)): + B.stroke(Fh([(0, -dry * .05)]).tolist() + [e_ + rot(V(er * .1, er * 1.25), tilt)], er * .4 * s_, col["brow"], + 5.3, part="face") + for e_, s_ in ((e_far, .8), (e_near, 1.0)): + if sleep: + B.stroke([e_ - rot(V(er * s_, 0), tilt), e_ + rot(V(0, -er * .25), tilt), e_ + rot(V(er * s_, 0), tilt)], + er * .35, (40, 30, 26), 5.6, part="eye") + continue + B.dot(e_, er * s_ * 1.32, _mix(col.get("rim", (60, 40, 30)), (0, 0, 0), .4), 5.4, kind="flat", ry=er * 1.32, + ang=tilt, part="eye") + B.dot(e_, er * s_, col.get("iris", (240, 200, 40)), 5.5, kind="eye", ry=er, ang=tilt) + bill = Fh([(-drx * .02, -dry * .05), (drx * .14, -dry * .12), (drx * .06, -dry * .52), (-drx * .02, -dry * .6), + (-drx * .1, -dry * .12)]) + B.mass("bill", bill, col["bill"], "beak", 5.6, fd=-90, shade=False) + B.lm.update(eye=e_near, eye_far=e_far, bill_tip=bill[3], gape=bill[0]) + if B.row.get("tufts"): + for sx, s_ in ((.55, 1.0), (-.35, .8)): + base = H + rot(V(hr * sx, hr * .72), tilt) + tp = base + rot(V(hr * .12 * np.sign(sx), hr * .62 * s_), tilt) + B.mass("tuft", [base + rot(V(-hr * .2, 0), tilt), tp, base + rot(V(hr * .22, -hr * .05), tilt)], hc, "head", + 4.95, fd=90) + return B + + +# ----------------------------------------------------------------------------------------------------- flight +FLAP = ("up", "down", "mid", "glide", "up2") + + +def build_fly(B, rng, lod, k=0, land=False): + """flight: body, head and tail built as the side view in the body plane, the wings as arms in 3D (shoulder, wrist, + hand; primaries from the hand; animal-071 flight silhouettes by family; animal-096 owl broad rounded wings + 2.3-2.8x body length), all seen through one camera: a beating wing (up / down stroke) from the side, the wing + raised or lowered in the picture plane; a glide from below and to the side so the span shows. The flap phase + comes from the instance number (a flock is never in one phase, animal-080).""" + P, col, fam = B.P, B.row["col"], B.row["fam"] + L = 1.0 + dep = P["dep"] * .9 + style = B.row.get("fly", "flap") + phase = FLAP[k % len(FLAP)] if style not in ("soar",) else "glide" + if fam in ("owl", "raptor") or B.name in ("gull",): + phase = ("glide", "up", "down")[k % 3] # broad / long wings read best spread (animal-096, 071) + if land: + phase = "land" + if style == "heron" or fam == "wader": + phase = ("glide", "up", "down")[k % 3] + tilt = rng.uniform(-4, 6) if not land else rng.uniform(26, 36) + below = phase in ("glide", "mid") or style == "soar" + if below: + yaw, pitch = math.radians(rng.uniform(18, 34)), math.radians(rng.uniform(50, 62)) + else: + yaw, pitch = math.radians(rng.uniform(12, 22)), math.radians(rng.uniform(4, 10)) + cy_, sy_, cp_, sp_ = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch) + + def pj(p3): + x, y, z = p3 + x1, z1 = x * cy_ + z * sy_, -x * sy_ + z * cy_ + return V(x1, y * cp_ + z1 * sp_), -y * sp_ + z1 * cp_ + + wview = np.array([pj((1, 0, 0))[1], pj((0, 1, 0))[1], pj((0, 0, 1))[1]]) # toward the camera + u = dirv(tilt) + n = perp(u) + C = V(0, 0) + body = egg(C, u, L, dep, full=.12) + # tail (fanned when soaring or landing) + rump = C - u * L * .42 + ta = tilt + 180 - (0 if not land else -35) + td = dirv(ta) + tl = P["tail"] * L * (1.0 if fam not in ("duck",) else 1.2) + fanw = dep * .5 * (1.7 if land or style == "soar" or below else 1.0) + tn = perp(td) + if B.row.get("tail_shape") == "fork": + tail = [rump + tn * fanw * .5, rump + td * tl * 1.05 + tn * fanw * .6, rump + td * tl * .6, + rump + td * tl * 1.05 - tn * fanw * .3, rump - tn * fanw * .5] + else: + tail = [rump + tn * fanw * .45, rump + td * tl + tn * fanw * .55, rump + td * tl * 1.06, + rump + td * tl - tn * fanw * .45, rump - tn * fanw * .45] + B.mass("tail", crv(tail, n=4), col.get("tail", col["back"]), "tail", 1.0, fd=ta) + B.lm["tail_tip"] = rump + td * tl + # head + neck by family (animal-071 / 062: heron neck tucked in an S and legs trailing; stork / crane / swan / + # goose / duck neck straight out) + hr = P["head"] * L * .5 + neck = P["neck"] * L + if style == "heron": + Hh = C + u * (L * .5 + hr * .3) + n * dep * .4 + spine = [C + u * .35 + n * dep * .1, C + u * .64 - n * dep * .38, Hh] + B.mass("neck", ribbon(spine, [dep * .55, hr * 1.7, hr * 1.4]), col.get("neck", col["back"]), "neck", 4.0) + gaze = tilt - 4 + elif neck > .12: + Hh = C + u * (L * .5 + neck * .85 + hr * .3) + spine = [C + u * L * .35, C + u * (L * .5 + neck * .4), Hh] + B.mass("neck", ribbon(spine, [dep * .55, hr * 1.3, hr * 1.2]), col.get("neck", col["back"]), "neck", 4.0) + gaze = tilt + rng.uniform(-6, 2) + else: + Hh = C + u * (L * .5 + hr * (.45 if fam != "owl" else .1)) + n * dep * (.12 if fam != "owl" else .18) + gaze = tilt + rng.uniform(-6, 0) + sil = hull(np.vstack([body, ell(Hh, hr, hr)])) if neck <= .12 and style != "heron" else body + B.mass("body", sil, col["back"], "body", 2.0, fd=tilt + 180) + if col.get("belly"): + B.mass("belly", [C + u * .7 - n * dep * .05, C - u * .6 - n * dep * .05, C - u * .6 - n, C + u * .7 - n], + col["belly"], "body", 2.1, clip="body", shade=False, line=False) + if col.get("breast"): + B.mass("breast", [C + u * .7 + n * dep * .5, C + u * .2 + n * dep * .5, C + u * .2 - n, C + u * .7 - n], + col["breast"], "body", 2.15, clip="body", shade=False, line=False) + if fam == "wader": + lc = col.get("leg", (150, 130, 90)) + a0 = rump - n * dep * .1 + ll = (P["leg"] + P.get("tib", 0)) * .95 + B.stroke([a0, a0 - u * ll - n * .02], .035, lc, 1.2, part="leg") + B.stroke([a0 - n * .03, a0 - u * ll * .95 - n * .06], .03, _mix(lc, (0, 0, 0), .2), .9, part="leg") + elif land: + lc = col.get("leg", (150, 130, 90)) + for dx in (-.04, .04): + a0 = C - n * dep * .35 + u * dx + ft = a0 + V(.18, -.3) + B.stroke([a0, ft], .04, lc, 3.2, part="leg") + for ang in (-50, -20, 10): + B.stroke([ft, ft + dirv(ang) * .1], .025, lc, 3.25, part="leg") + if fam == "owl": + _owl_head_fly(B, Hh, hr, lod) + else: + add_head(B, Hh, hr, gaze, zbase=5.0, lod=lod) + # everything so far lies in the body plane: through the camera (from below the body shows its width, so its + # depth is kept at ~.8 instead of shrinking with the pitch) + kb = (.85 / max(cp_, .3)) if below else 1.0 + + def T2(q): + q = np.asarray(q, float) + if q.ndim == 1: + return pj((q[0], q[1] * kb, 0))[0] + return np.array([pj((a_, b_ * kb, 0))[0] for a_, b_ in q]) + for m in B.masses: + m["pts"] = T2(m["pts"]) + for st in B.strokes: + st["pts"] = T2(st["pts"]) + for d in B.dots: + d["c"] = T2(d["c"]) + for k_, v in list(B.lm.items()): + if isinstance(v, np.ndarray) and v.shape == (2,): + B.lm[k_] = T2(v) + # wings: arm + hand in 3D (animal-067 / 071), the trailing edge from the chord profile of the family + span = P["span"] * L * .5 + shape = B.row.get("wingshape", "round") + chord = {"point": .5, "gull": .42, "finger": .6, "owl": .52, "broad": .56, "round": .52}.get(shape, .52) * L + el1, el2, fold, sweep = {"up": (66, 52, .0, -6), "up2": (44, 58, .45, -16), "down": (-42, -54, .0, 8), + "mid": (14, 4, .0, 2), "glide": (6, 0, .0, 0), "land": (66, 50, .08, 8)}[phase] + if style == "soar": + el1, el2 = 8, 3 + if style == "heron" or fam == "wader": + el1, el2, fold, sweep = {"up": (34, 18, .1, 4), "down": (-24, -40, .05, 8), "glide": (-4, -12, 0, 4)}[phase] + if shape == "gull" and phase in ("glide", "mid"): + el1, el2, fold, sweep = 20, -16, .05, -12 # the gull's M: arm up, the hand angled down at the wrist + sh0 = C + u * L * .12 + n * dep * .22 + under = col.get("under", _mix(col.get("belly", col["back"]), col.get("wing", col["back"]), .35)) + if B.name in ("gull",): + under = (236, 238, 240) + back3 = np.array([-1.0, 0, 0]) + order = [] + for side in (1, -1): + sh = np.array([sh0[0], sh0[1] * kb, side * dep * .22]) + e1, e2 = math.radians(el1), math.radians(el2) + arm = span * .46 * (1 - .35 * fold) + hand = span * .58 * (1 - .55 * fold) + sw = math.radians(sweep) + d1 = np.array([math.sin(sw) * .3 + .08, math.sin(e1), side * math.cos(e1)]) + d1 /= np.linalg.norm(d1) + wr = sh + d1 * arm + d2 = np.array([-.32 - .9 * fold, math.sin(e2), side * math.cos(e2) * (1 - .5 * fold)]) + d2 /= np.linalg.norm(d2) + tip = wr + d2 * hand + fwd = np.array([chord * .1, 0, 0]) # the leading edge bows forward at the wrist (the patagium) + lead = [sh, sh + d1 * arm * .5 + fwd * .6, wr + fwd, wr + d2 * hand * .4 + fwd * .5, wr + d2 * hand * .75, tip] + if shape in ("point", "gull"): + cs = [.95, .92, .8, .55, .3, 0.0] + elif shape in ("owl", "round", "broad"): + cs = [.95, .92, .85, .72, .55, .25] + else: # finger + cs = [.95, .95, .92, .85, .75, .5] + cs = [c_ * chord * (1 - .3 * fold) for c_ in cs] + trail = [lead[i] + back3 * cs[i] for i in range(len(lead))] + if shape == "finger": + # fingered primaries: slots at the hand's tip (5-7 on eagles, animal-071; owls rounded, 3-4 shallow) + nf, deep = (5, .26) if shape == "finger" else (4, .1) + fing = [] + for j in range(nf): + t = j / (nf - 1) + base_ = tip * (1 - t * .5) + (wr + d2 * hand * .5) * (t * .5) + q = base_ + back3 * (cs[-1] * t * .9) + fing.append(q + d2 * hand * deep * (1 - .4 * t)) + fing.append(q + back3 * chord * .06 - d2 * hand * .02) + trail = trail[:3] + fing[::-1] + outline = lead + fing + trail[:3][::-1] + else: + tr = trail[::-1] + if lod >= 2: + # the trailing edge is a row of feather tips (primaries, then secondaries): a scalloped edge, the + # notches deeper on the hand where the primaries part (animal-067 / 071 groups, not a paddle) + sc_ = [] + for i in range(len(tr) - 1): + a_, b_ = tr[i], tr[i + 1] + for t_ in (.33, .66): + q = a_ * (1 - t_) + b_ * t_ + li = lead[len(lead) - 1 - i] * (1 - t_) + lead[max(0, len(lead) - 2 - i)] * t_ + sc_.append(q + (li - q) * (.12 if i < 2 else .06) * (1 if t_ < .5 else 0)) + sc_.append(b_) + tr = [tr[0]] + sc_ + outline = lead + tr + P2 = np.array([pj(p)[0] for p in outline]) + zc = float(np.mean([pj(p)[1] for p in outline])) + top = -side * np.cross(d1 + d2, back3) + see_top = float(np.dot(top, wview)) > 0 + wc = col.get("wing", col["back"]) + wcol = wc if see_top or fam == "owl" else under + order.append((zc, side, P2, wcol, see_top, sh, wr, tip, d2, hand, lead, trail, cs)) + order.sort(key=lambda o: o[0]) + for rank, (zc, side, P2, wcol, see_top, sh, wr, tip, d2, hand, lead, trail, cs) in enumerate(order): + nearw = rank == 1 + z = 6.5 if (nearw and zc > -.05) else 0.3 + nm = "wingN" if nearw else "wingF" + wc_ = wcol if nearw else _mix(wcol, (0, 0, 0), .12) + B.mass(nm, P2 if shape in ("finger",) else crv(P2, n=3), wc_, "covert", z, fd=tilt + 180) + pc = col.get("prim", _mix(col.get("wing", col["back"]), (0, 0, 0), .3)) + if see_top or B.name in ("gull", "stork", "flamingo", "heron") or fam in ("wader",): + hp = [pj(p)[0] for p in (wr, wr + d2 * hand * .4, wr + d2 * hand * .75, tip)] + \ + [pj(p)[0] for p in (wr + d2 * hand * .75 + back3 * cs[4], wr + d2 * hand * .4 + back3 * cs[3], + wr + back3 * cs[2])] + if shape in ("finger",): + hp = [pj(p)[0] for p in (wr, tip)] + [pj(p)[0] for p in trail[3:]] + [pj(wr + back3 * cs[2])[0]] + B.mass(nm + "_p", hp, pc if nearw else _mix(pc, (0, 0, 0), .12), "primary", z + .05, clip=nm, + shade=False, line=False) + if lod >= 2 and fam not in ("owl",) and see_top: + cov = [pj(p)[0] for p in (sh, wr, wr + back3 * cs[2] * .4, sh + back3 * cs[0] * .45)] + B.mass(nm + "_c", cov, _mix(wc_, (255, 250, 240), .1), "covert", z + .04, clip=nm, shade=False, + line=False) + if fam == "owl" and lod >= 2: + for i in range(4): + t = .2 + .2 * i + a_ = pj(sh * (1 - t) + tip * t)[0] + b_ = pj(sh * (1 - t) + tip * t + back3 * chord * .55)[0] + B.stroke([a_, b_], .03, col.get("streak", (90, 60, 40)), z + .06, part="covert") + if col.get("spec") and lod >= 2 and see_top: + B.mass(nm + "_s", [pj(p)[0] for p in (sh + back3 * cs[0] * .6, wr + back3 * cs[2] * .6, + wr + back3 * cs[2] * .95, sh + back3 * cs[0] * .95)], + col["spec"], "secondary", z + .06, clip=nm, shade=False, line=False) + if nearw: + B.lm.update(wing_tip=pj(tip)[0], wrist=pj(wr)[0]) + else: + B.lm.update(wing_tip_far=pj(tip)[0], wrist_far=pj(wr)[0]) + B.lm.update(posture_deg=tilt, body_c=T2(C), body_len=L, phase=phase, view="below" if below else "side") + return B + + +def _owl_head_fly(B, H, hr, lod): + col = B.row["col"] + B.mass("head", ell(H, hr * 1.05, hr), col.get("head", col["back"]), "head", 5.0, fd=90) + dc = H + V(hr * .35, -hr * .05) + B.mass("disc", ell(dc, hr * .62, hr * .7), col.get("disc", col["belly"]), "face", 5.2, shade=False) + er = B.P["eye"] * hr * 2 * .9 + for dx, s_ in ((-.3, .8), (.3, 1.0)): + e = dc + V(dx * hr, hr * .08) + B.dot(e, er * s_, col.get("iris", (240, 200, 40)), 5.5, kind="eye") + B.mass("bill", [dc + V(-hr * .06, -hr * .05), dc + V(hr * .08, -hr * .05), dc + V(0, -hr * .4)], col["bill"], "beak", + 5.6, shade=False) + B.lm.update(eye=dc + V(.3 * hr, hr * .08), head_c=H, head_r=hr) + + +# --------------------------------------------------------------------------------------------- the value plan +def _mix(a, b, t): + return tuple(float(a[i]) * (1 - t) + float(b[i]) * t for i in range(3)) + + +class Plan: + """value plan before drawing (WAVE20 step 4): the light direction from the scene, a lit and a shadow value per + local colour through the scene's light (so night / sunset grade the bird like everything else)""" + + def __init__(self, ctx, style): + L = getattr(ctx, "L", None) + self.L = L + d = getattr(L, "d", (-.5, -.6, .6)) if L is not None else (-.5, -.6, .6) + ld = V(d[0], d[1]) + if np.linalg.norm(ld) < .15: + ld = V(-.5, -.6) + self.ld = unit(ld) # screen direction toward the light (y down) + z = abs(d[2]) if len(d) > 2 else .6 + self.nl = unit(np.array([d[0] * .55, d[1] * .55, .8 + z * .2])) + self.ns = unit(np.array([-d[0] * .8, -d[1] * .8, .35])) + self.style = style + self.cache = {} + + def ratios(self, c): + k = tuple(int(v) for v in c) + if k in self.cache: + return self.cache[k] + if self.L is None: + r = (np.ones(3), np.full(3, .62)) + else: + b = np.maximum(np.array(c, float), 1.0) + lit = np.array(self.L.shade(tuple(b), *self.nl), float) / b + sh = np.array(self.L.shade(tuple(b), *self.ns), float) / b + # designed values: keep the shadow a clear step (.55-.72 of the lit value), never black + lit = np.clip(lit, .55, 1.35) + sh = np.clip(np.minimum(sh, lit * .74), lit * .5, None) + r = (lit, sh) + self.cache[k] = r + return r + + +# -------------------------------------------------------------------------------------------------- the raster +class Plate: + """the bird's own local raster (bbox + margin): colour, coverage, owner mass, part, feather direction""" + + def __init__(self, x0, y0, w, h, aa): + self.x0, self.y0, self.w, self.h, self.aa = x0, y0, w, h, aa + self.ss = 4 if aa else 1 + self.col = np.zeros((h, w, 3), np.float32) + self.a = np.zeros((h, w), np.float32) + self.own = np.full((h, w), -1, np.int32) + self.part = np.zeros((h, w), np.int32) + self.fd = np.zeros((h, w, 2), np.float32) + + def cover(self, pts): + s = self.ss + if len(pts) < 3: + return np.zeros((self.h, self.w), np.float32) + im = Image.new("L", (self.w * s, self.h * s), 0) + Q = (np.asarray(pts, float) - [self.x0, self.y0]) * s - .5 * (s > 1) - (.5 if s == 1 else 0) + ImageDraw.Draw(im).polygon([tuple(map(float, q)) for q in Q], fill=255) + A = np.asarray(im, np.float32) / 255.0 + if s > 1: + A = A.reshape(self.h, s, self.w, s).mean((1, 3)) + return A + + def cover_line(self, pts, w): + s = self.ss + im = Image.new("L", (self.w * s, self.h * s), 0) + Q = (np.asarray(pts, float) - [self.x0, self.y0]) * s - (.5 if s == 1 else .5) + W_ = max(1, int(round(w * s))) + dr = ImageDraw.Draw(im) + dr.line([tuple(map(float, q)) for q in Q], fill=255, width=W_, joint="curve") + r = W_ / 2.0 + if W_ >= 3: + for q in (Q[0], Q[-1]): + dr.ellipse([q[0] - r + .5, q[1] - r + .5, q[0] + r - .5, q[1] + r - .5], fill=255) + A = np.asarray(im, np.float32) / 255.0 + if s > 1: + A = A.reshape(self.h, s, self.w, s).mean((1, 3)) + if w < 1.0 and s == 1: + A = A * 0 + A # pixel mode keeps a full 1 px line + return A + + def put(self, cov, c, own, part, fd): + if not self.aa: + cov = (cov >= .5).astype(np.float32) + m = cov > 0 + if not m.any(): + return + c = np.asarray(c, np.float32) + self.col[m] = self.col[m] * (1 - cov[m, None]) + c * cov[m, None] + self.a[m] = self.a[m] + cov[m] * (1 - self.a[m]) + k = cov >= .5 + self.own[k] = own + self.part[k] = part + self.fd[k] = fd + + +def _shift(m, dx, dy): + """mask moved by (dx, dy) px (fractional, bilinear)""" + from scipy import ndimage + return ndimage.shift(m, (dy, dx), order=1, mode="constant", cval=0.0) + + +def _blur(m, r): + from scipy import ndimage + return ndimage.gaussian_filter(m, r) if r > .3 else m + + +# ------------------------------------------------------------------------------------------------------- pose +FLY_WORDS = ("flying", "fly ", "flies", "in flight", "soaring", "soars", "gliding", "glides", "in the sky", + "overhead", "migrating", "circling", "swooping", "hovering", "taking off", "takes off", "flapping", + "wings spread", "spread wings", "spreading its wings", "in mid air", "mid-air", "midair", "flock of birds", + "across the sky", "through the sky", "against the sky", "flying over", "flew") +REST_WORDS = {"perched": "perch", "perching": "perch", "sitting": "perch", "standing": "stand", "walking": "walk", + "running": "walk", "swimming": "swim", "floating": "swim", "sleeping": "sleep", "asleep": "sleep", + "pecking": "peck", "eating": "peck", "feeding": "peck", "grazing": "peck", "drinking": "peck", + "foraging": "peck", "wading": "wade", "fishing": "wade", "hunting": "wade", "crowing": "crow", + "howling": "crow", "calling": "crow", "singing": "crow", "one_leg": "one_leg", "resting": "sleep", + "landing": "land", "lands": "land"} +PERCH_THINGS = ("branch", "bough", "limb", "twig", "stick", "perch", "fence", "post", "fence post", "wire", "pole", + "railing", "rail", "gate", "stump", "log", "tree", "birdhouse", "feeder", "bird feeder", "chair", + "mailbox", "lamp post", "lamppost", "signpost", "statue", "rock", "boulder", "roof", "rooftop", + "chimney", "windowsill", "sill", "bench", "shoulder", "hand", "arm", "pumpkin", "barrel", "crate", + "cage", "nest") + + +def text_says_fly(text): + t = " %s " % " ".join((text or "").lower().replace(",", " ").split()) + return any(w in t for w in FLY_WORDS) or " fly " in t + + +RAPTOR_SKY = ("eagle", "hawk") + + +def grounded(scene, it): + """animal-086 (layout hook, knob c2d_bird_ground): a bird is drawn flying only when the prompt says so; otherwise + it stands or perches (pose 'standing'; pose_for picks perch / stand / swim / wade at draw time). Raptors keep the + sky (an eagle with no verb soars), and a flock of birds over a place flies.""" + if not on("c2d_bird_ground"): + return False + g = it.get if isinstance(it, dict) else (lambda k_, d=None: getattr(it, k_, d)) + try: + name = lookup(g("concept"), g("word", "") or "") + except Exception: + return False + if name is None or name in RAPTOR_SKY: + return False + text = str((scene or {}).get("text", "")) + if text_says_fly(text) or g("pose") == "flying": + return False + words = " " + " ".join(text.lower().split()) + " " + if any(w in words for w in (" over the ", " over a ", " above the ", " above a ", " flock")): + return False + return True + + +def pose_for(ctx, inst, name): + sc = getattr(ctx, "scene", None) or {} + text = str(sc.get("text", "")).lower() + p = getattr(inst, "pose", None) + fam = get(name)["fam"] + bound = getattr(inst, "bound", None) + rel = getattr(inst, "rel", None) + if fam == "wader" and p in (None, "walking", "standing", "hunting", "fishing") and \ + any(w in text for w in (" wading", " wades", " fishing", " in the river", " in a river", " in the water", + " in the shallows", " in a pond", " in the pond", " in the marsh", " in a marsh", + " in a lake", " in the lake", " standing in")): + return "wade" + if p in REST_WORDS: + q = REST_WORDS[p] + if q == "perch" and bound is None and name in GROUND: + q = "stand" + if q == "swim" and name not in WATERFOWL + ("gull", "penguin"): + q = "stand" + if q == "wade" and fam != "wader": + q = "stand" + if q == "crow" and fam != "fowl": + q = "stand" + return q + if " landing" in text or " lands " in text: + return "land" + if p == "flying" and (bound is None or rel == "above"): + return "fly" + if any(w in text for w in (" wading", " wades", " fishing")) and fam == "wader": + return "wade" + setting = (getattr(inst, "info", None) or {}).get("setting") + place = sc.get("place") + watery = setting == "water" or place in ("water", "lake", "pond", "river", "sea", "beach", "ocean", "marsh") + words = " ".join((text or "").split()) + if name in WATERFOWL and (" swim" in words or " on the lake" in words or " on a lake" in words or " pond" in words + or " on the water" in words or " river" in words) and _on_water(ctx, inst): + return "swim" + if fam == "wader" and (watery or any(w in words for w in (" river", " marsh", " pond", " lake", " water", + " shore", " swamp", " creek", " stream"))): + return "wade" + if bound is not None and rel == "on": + bc = (getattr(bound, "concept", "") or "") + " " + (getattr(bound, "word", "") or "") + if any(k in bc for k in PERCH_THINGS) or getattr(bound, "perch", False): + if name in ("chicken", "white chicken", "rooster", "pigeon", "dove", "gull", "crow") and \ + not any(k in bc for k in ("branch", "twig", "wire", "bough", "limb")): + return "stand" if fam != "fowl" or "fence" not in bc else "perch" + return "perch" + if fam == "owl" or name in ("parrot", "macaw", "cockatoo", "toucan"): + return "perch" + if name in WATERFOWL and _on_water(ctx, inst): + return "swim" + return "stand" + + +def _on_water(ctx, inst): + try: + from ..concepts.animals2 import on_water + return bool(on_water(ctx, inst)) + except Exception: + return False + + +# ------------------------------------------------------------------------------------------------------- draw +def _style(ctx, cv): + sc = getattr(ctx, "scene", None) or {} + pixel = cv.ss == 1 and not sc.get("_gbuf") + st = (sc.get("art") or sc.get("style") or "") or "" + text = str(sc.get("text", "")).lower() + anime = any(w in text for w in ("anime", "manga", "cartoon", "comic", "cel shaded", "chibi")) or st in ("comic", + "anime") + return ("pixel" if pixel else "anime" if anime else "paint"), st + + +def recolour(row, c): + """a colour word in the prompt ('a red bird', 'a blue owl') recolours the plumage masses; the identity marks (bill, + legs, eyes, comb, owl disc rim) stay""" + col = dict(row["col"]) + lum = .3 * c[0] + .59 * c[1] + .11 * c[2] + for k_ in ("back", "head", "neck", "crest"): + if k_ in col or k_ in ("back",): + col[k_] = c + col["wing"] = _mix(c, (0, 0, 0), .1) + col["tail"] = _mix(c, (0, 0, 0), .18) + col["prim"] = _mix(c, (0, 0, 0), .32) + col["belly"] = _mix(c, (248, 242, 230), .45 if lum < 170 else .2) + if "disc" in col: + col["disc"] = _mix(c, (248, 242, 230), .55) + for k_ in ("breast", "sheen", "spec", "cap", "streak", "neck2", "tailband", "scap", "mask", "cheek", "throat", + "necklace", "hackle", "trousers", "flank", "crown", "plume", "shoulder", "scallop", "vent", "bar"): + col.pop(k_, None) + if row["fam"] == "owl": + col["streak"] = _mix(c, (0, 0, 0), .45) + row = dict(row) + row["col"] = col + return row + + +def build(name, pose, rng, lod, k=0, f=1, recol=None): + row = get(name) + if recol is not None: + row = recolour(row, recol) + P = pick(row, rng) + B = Bird(name, row, pose, P) + if pose in ("fly", "land"): + if row["fam"] == "penguin": + B.pose = "stand" + return build_ground(B, rng, lod) + return build_fly(B, rng, lod, k, land=pose == "land") + if row["fam"] == "owl" and pose in ("perch", "stand", "sleep", "walk", "peck", "wade", "swim", "crow", "one_leg"): + B.pose = "perch" if pose != "sleep" else "sleep" + return build_owl(B, rng, lod, f) + return build_ground(B, rng, lod) + + +def lod_for(hpx): + """size ladder (animal-078..080): 0 = silhouette (< 14 px), 1 = major masses (14-40), 2 = groups (40-110), + 3 = groups + marks (>= 110)""" + return 0 if hpx < 14 else 1 if hpx < 40 else 2 if hpx < 110 else 3 + + +def _bbox(B): + pts = [m["pts"] for m in B.masses] + [s["pts"] for s in B.strokes] + [d["c"][None] for d in B.dots] + A = np.vstack(pts) + return A[:, 0].min(), A[:, 1].min(), A[:, 0].max(), A[:, 1].max() + + +def covers(inst): + """a bird this module draws (the creature2d dispatcher asks first)""" + info = getattr(inst, "info", None) or {} + if not info.get("animal", True): + return False + c = getattr(inst, "concept", None) + if c not in CONCEPT_ROW and (info.get("open_vocab") or {}).get("family") not in ("bird", None) and \ + not _is_ov_bird(c): + return False + return lookup(c, getattr(inst, "word", "") or "") is not None + + +def _is_ov_bird(c): + try: + from ..registry import CONCEPTS + return (CONCEPTS.get(c, {}).get("open_vocab") or {}).get("family") == "bird" + except Exception: + return False + + +def draw(cv, ctx, inst): + """draw the bird of `inst` on cv; False = not a bird this module draws (the caller falls back)""" + name = lookup(getattr(inst, "concept", None), getattr(inst, "word", "") or "") + if name is None: + return False + sc = getattr(ctx, "scene", None) or {} + text = str(sc.get("text", "")).lower() + if name == "duck" and any(w in text for w in ("female duck", "hen duck", "female mallard")): + name = "female duck" + if name in ("chicken",) and getattr(inst, "color", None) in ("white",): + name = "white chicken" + if name == "goose" and getattr(inst, "color", None) in ("white",): + name = "white goose" + if name == "duck" and getattr(inst, "color", None) in ("white",): + name = "white duck" + pose = pose_for(ctx, inst, name) + recol = None + if getattr(inst, "color", None) and getattr(inst, "color_explicit", False) and \ + not (name.startswith("white") and inst.color == "white"): + try: + from ..kit import color_of + c = tuple(float(v) for v in color_of(inst)) + if np.ptp(c) > 1 or np.mean(c) != 150: + recol = c + except Exception: + recol = None + if pose == "fly" and get(name).get("fly") == "soar" and not on("c2d_bird_soar", "0"): + return False # a soaring raptor keeps the old iconic spread-eagle silhouette + style, st = _style(ctx, cv) + k = getattr(inst, "k", 0) or 0 + seed = (hash((name, k, int(getattr(inst, "x", 0)), int(getattr(inst, "y", 0)))) & 0xffff) + rng = np.random.default_rng(seed) + f = -1 if getattr(inst, "facing", "right") == "left" else 1 + hbox = max(float(getattr(inst, "h", 20)), 2.0) + lod = lod_for(hbox) + B = build(name, pose, rng, lod, k, f, recol) + if style == "anime" and B.row["fam"] != "owl": + for d in B.dots: + if d["kind"] == "eye": + d["r"] *= 1.35 + d["ry"] *= 1.35 + x0, y0, x1, y1 = _bbox(B) + bw_u, bh_u = max(x1 - x0, 1e-3), max(y1 - y0, 1e-3) + wbox = float(getattr(inst, "w", None) or hbox * (inst.info.get("aspect", 1.3) if hasattr(inst, "info") else 1.3)) + if B.pose in ("fly", "land"): + # a flier's box was laid out for its folded silhouette: the open bird spans ~1.2x the box's larger side + s = min(max(wbox, hbox) * 1.2 / bw_u, max(wbox, hbox) * 1.1 / bh_u) + else: + s = min(hbox / bh_u, wbox * 1.25 / bw_u) + if B.pose == "swim": + s = min(hbox * 1.1 / (y1 - 0), wbox * 1.2 / bw_u) + if name in ("duckling", "chick") and B.pose != "fly": + s *= .8 + lod2 = lod_for(bh_u * s) + if lod2 != lod: + rng = np.random.default_rng(seed) + B = build(name, pose, rng, lod2, k, f, recol) + lod = lod2 + x0, y0, x1, y1 = _bbox(B) + cx = (x0 + x1) * .5 + if B.pose in ("fly", "land"): + oy = inst.y - hbox * .5 + (y0 + y1) * .5 * s + else: + oy = inst.y + ox = inst.x - f * cx * s + + def S(p): + p = np.asarray(p, float) + return np.stack([ox + f * s * p[..., 0], oy - s * p[..., 1]], -1) + + if B.pose in ("perch", "sleep") and getattr(inst, "bound", None) is None and lod >= 1 and \ + (B.row["fam"] == "owl" or name in ("parrot", "macaw", "cockatoo", "toucan")) and on("c2d_bird_limb") and \ + (sc.get("place") or "") not in ("room", "studio", "table", "kitchen", "bedroom", "office", "bathroom"): + _limb(cv, ctx, inst, S, s, f) + _render(cv, ctx, inst, B, S, s, f, style, lod) + def _px(v): + if isinstance(v, np.ndarray) and v.shape == (2,): + return [round(float(q), 2) for q in S(v)] + if isinstance(v, list) and v and isinstance(v[0], np.ndarray): + return [_px(q) for q in v] + if isinstance(v, (float, int, str)) or v is None: + return v + return None + rec = dict(name=name, pose=B.pose, lod=lod, scale=s, facing=f) + for k_, v in B.lm.items(): + if k_ in ("head_r", "body_len"): + rec[k_ + "_px"] = float(v) * s + elif k_ != "body": + q = _px(v) + if q is not None: + rec[k_] = q + if len(LAST) > 256: + LAST.clear() + LAST[getattr(cv, "cur_id", None) or id(inst)] = rec + try: + rec = LAST[getattr(cv, "cur_id", None) or id(inst)] + inst.c2d = dict(kind="bird", species=name, pose=B.pose, facing=f, canvas_w=cv.w, lod=lod, + ground=float(inst.y) if B.pose not in ("fly", "land") else None, + perch_y=float(inst.y) if B.pose == "perch" else None, + water_y=float(oy) if B.water is not None else None, + pts={k_: v for k_, v in rec.items() if isinstance(v, list) and len(v) == 2 + and not isinstance(v[0], list)}, + feet=rec.get("feet"), head_r_px=float(B.lm.get("head_r", 0) * s), scale=s) + except Exception: + pass + try: + inst.form_kind = "keep" # our shading is designed; formlight keeps it (contact + key tint only) + except Exception: + pass + return True + + +def _render(cv, ctx, inst, B, S, s, f, style, lod): + pixel = style == "pixel" + plan = Plan(ctx, style) + # screen-space geometry, z-sorted + items = [] + for i, m in enumerate(B.masses): + items.append(("m", m["z"], i, m)) + for i, st in enumerate(B.strokes): + items.append(("s", st["z"], i, st)) + for i, d in enumerate(B.dots): + items.append(("d", d["z"], i, d)) + items.sort(key=lambda t: (t[1], t[0] != "m", t[2])) + allp = np.vstack([S(m["pts"]) for m in B.masses] + [S(st["pts"]) for st in B.strokes]) + pad = 4 + int(s * .05) + X0 = int(math.floor(allp[:, 0].min())) - pad + Y0 = int(math.floor(allp[:, 1].min())) - pad + X1 = int(math.ceil(allp[:, 0].max())) + pad + Y1 = int(math.ceil(allp[:, 1].max())) + pad + if B.water is not None: + Y1 = max(Y1, int(S(V(0, 0))[1]) + int(s * .5) + 4) + W_, H_ = max(1, X1 - X0), max(1, Y1 - Y0) + if W_ * H_ > 4_000_000: + return + pl = Plate(X0, Y0, W_, H_, not pixel) + full = {} + names = [m["name"] for m in B.masses] + from ..rig.bird import PART_IDS as RP + for kind, z, i, it in items: + if kind == "m": + Q = S(it["pts"]) + if f < 0: + Q = Q[::-1] + cov = pl.cover(Q) + full[it["name"]] = np.maximum(full.get(it["name"], 0), cov) + if it["clip"] and it["clip"] in full: + cov = cov * full[it["clip"]] + if it["clip"] == "body" and "rear" in full: + cov = np.maximum(cov, pl.cover(Q) * full["rear"]) if it["name"] in ("belly",) else cov + fd = dirv(it["fd"]) + pid = RP.get(it["part"], PART.get(it["part"], 203)) + pl.put(cov, it["col"], i, pid, (fd[0] * f, -fd[1])) + elif kind == "s": + Q = S(it["pts"]) + w = max(it["w"] * s, .6 if not pixel else 1.0) + cov = pl.cover_line(Q, w) + fd = dirv(it["fd"]) + pl.put(cov, it["col"], -2 - i, RP.get(it["part"], PART.get(it["part"], 205)), (fd[0] * f, -fd[1])) + else: + c = S(it["c"]) + r = it["r"] * s + ry = it["ry"] * s + if it["kind"] == "eye": + r, ry = max(r, .5), max(ry, .5) + if pixel: + r, ry = max(r, .6), max(ry, .6) + if r < .35 and it["kind"] != "eye": + continue + E = ell(c, max(r, .5), max(ry, .5), -it["ang"] * f) + cov = pl.cover(E) + if it["kind"] == "ring": + inner = pl.cover(ell(c, r * .62, ry * .62)) + cov = np.clip(cov - inner, 0, 1) + pl.put(cov, it["col"], -1000 - i, RP.get(it["part"], PART.get(it["part"], 220)), (0, 0)) + if it["kind"] == "eye": + # pupil for coloured irises (owl, gull), then the catch-light upper front + if np.mean(it["col"]) > 90 and r > 1.4: + pc = pl.cover(ell(c, r * .52, ry * .55)) + pl.put(pc, (18, 14, 14), -1000 - i, RP.get("eye", 220), (0, 0)) + if r >= 1.3: + hp = c + np.array([f * r * .3, -ry * .35]) + hc = pl.cover(ell(hp, max(r * .3, .5), max(ry * .3, .5))) + pl.put(hc, (250, 248, 240), -1000 - i, RP.get("eye", 220), (0, 0)) + # ---------------- designed shadow shapes (step 5): per mass, a crescent on the side away from the light + ld = plan.ld + ldx, ldy = ld[0], ld[1] + out = pl.col.copy() + shadow = np.zeros((H_, W_), np.float32) + for i, m in enumerate(B.masses): + if not m["shade"] or m["name"] not in full: + continue + M = full[m["name"]] + if M.sum() < 2: + continue + ys, xs = np.nonzero(M > .5) + if not len(ys): + continue + from scipy import ndimage + # the shadow's depth follows the mass's THICKNESS (largest inscribed disc), so an S-neck or a long tail gets + # a band along its shadow side, not slabs across it + size = max(2.0, float(ndimage.distance_transform_edt(M > .5).max()) * 2) + kk = size * (.3 if m["name"] not in ("bill", "comb") else .22) + if m["name"].startswith("wing") and B.pose in ("fly", "land"): + kk = size * .1 # an open wing is a thin plane: a narrow value step at its trailing side only + Mx = M + if m["name"] in ("neck", "head", "tail") and "body" in full: + Mx = np.maximum(M, full["body"]) # a mass that grows out of the body: no shadow band along its cut root + Msh = _shift(Mx, ldx * kk, ldy * kk) + S_ = np.clip(M - Msh, 0, 1) + if not pixel: + S_ = _blur(S_, max(.6, size * .03)) * M + mine = pl.own == i + shadow = np.where(mine, np.maximum(shadow, S_), shadow) + # cast shadows: the folded wing on the flank below it, the head on the breast (designed, short) + for caster, recv, k_ in (("wing", ("body", "rear", "belly", "breast"), .1), ("head", ("body", "belly", "breast"), .12), + ("wingN", ("body", "belly", "breast", "tail"), .08)): + if caster not in full: + continue + M = full[caster] + ys, xs = np.nonzero(M > .5) + if not len(ys): + continue + size = max(2.0, min(xs.max() - xs.min(), ys.max() - ys.min()) + 1) + cs = np.clip(_shift(M, -ldx * size * k_, -ldy * size * k_) - M, 0, 1) + if not pixel: + cs = _blur(cs, max(.6, size * .03)) + recv_mask = np.isin(pl.own, [j for j, m in enumerate(B.masses) if m["name"] in recv]) + shadow = np.where(recv_mask, np.maximum(shadow, cs * .85), shadow) + if pixel: + shadow = (shadow >= .5).astype(np.float32) + # apply the plan's lit / shadow values per pixel's own colour + covered = pl.a > 0 + ys, xs = np.nonzero(covered) + if not len(ys): + return + cols = out[ys, xs] + keys = np.round(cols / 8).astype(np.int32) + uk, inv = np.unique(keys, axis=0, return_inverse=True) + inv = inv.reshape(-1) + lit_r = np.zeros((len(uk), 3), np.float32) + sh_r = np.zeros((len(uk), 3), np.float32) + for j, kk_ in enumerate(uk): + lr, sr = plan.ratios(kk_ * 8) + lit_r[j], sh_r[j] = lr, sr + sv = shadow[ys, xs][:, None] + newc = cols * (lit_r[inv] * (1 - sv) + sh_r[inv] * sv) + eye_px = (pl.own[ys, xs] <= -1000)[:, None] + eyek = 1.25 if getattr(ctx, "time", "day") == "night" else 1.0 # night: an owl's eyes are the brightest marks + newc = np.where(eye_px, cols * np.clip(lit_r[inv], .8, 1.1) * eyek, newc) # an eye keeps its colour + # value-edge line between masses in AA styles (an illustrator's overlap line, light, on the shadow side only) + if not pixel and lod >= 1: + own = pl.own + edge = np.zeros_like(covered) + edge[:-1] |= (own[:-1] != own[1:]) & (own[:-1] >= 0) & (own[1:] >= 0) + edge[:, :-1] |= (own[:, :-1] != own[:, 1:]) & (own[:, :-1] >= 0) & (own[:, 1:] >= 0) + line_ok = np.zeros(len(B.masses) + 1, bool) + for j, m in enumerate(B.masses): + line_ok[j] = m["line"] + oj = np.where(own >= 0, own, len(B.masses)) + edge &= line_ok[oj] + ev = edge[ys, xs][:, None] + newc = np.where(ev, newc * (.78 if style != "anime" else .55), newc) + if style == "anime" and lod >= 1: + # anime / cartoon: a clean dark outline round the whole silhouette + sil = (pl.a > .5).astype(np.float32) + from scipy import ndimage + ring = sil - ndimage.binary_erosion(sil > 0, iterations=1).astype(np.float32) + rv = ring[ys, xs][:, None] > 0 + newc = np.where(rv, newc * .35, newc) + hz = float(getattr(inst, "haze", 0) or 0) + if hz > 0: + hc = np.array(getattr(ctx, "haze_color", (200, 220, 240)), np.float32) + newc = newc * (1 - hz) + hc * hz + out[ys, xs] = np.clip(newc, 0, 255) + # pseudo-normals for the G-buffer (designed domes per mass, light-agnostic) + owner_mask = pl.own + nb = np.zeros((H_, W_, 3), np.float32) + nb[..., 2] = 1.0 + for i, m in enumerate(B.masses): + if m["name"] not in full: + continue + mine = owner_mask == i + if not mine.any(): + continue + hgt = _blur(full[m["name"]], max(1.0, math.sqrt(mine.sum()) * .25)) + gy, gx = np.gradient(hgt) + nx, ny = -gx * 6, -gy * 6 + nz = np.ones_like(nx) + nn = np.sqrt(nx * nx + ny * ny + nz * nz) + nb[mine] = np.stack([nx / nn, ny / nn, nz / nn], -1)[mine] + # ---------------- ground contact: a small soft shadow under standing feet (not perched / swimming / flying) + if B.pose in ("stand", "walk", "peck", "crow", "one_leg") and lod >= 1: + g = S(V(0, 0)) + fx = [S(p)[0] for p in B.lm.get("feet", [])] or [g[0]] + cxs = (min(fx) + max(fx)) * .5 + rx = max(2.0, (max(fx) - min(fx)) * .5 + s * .22) + _ground_shadow(cv, ctx, cxs, g[1], rx, max(1.0, rx * .22), pixel) + if B.water is not None: + _water(cv, ctx, B, S, s, pixel, out, pl) + # ---------------- blit to the canvas + wl = S(V(0, B.water))[1] if B.water is not None else None + if B.pose == "wade": + wl = _wade_line(cv, ctx, B, S) + _blit(cv, pl, out, nb, wl, pixel) + if B.pose == "wade" and wl is not None: + _wade(cv, ctx, B, S, s, pixel, wl) + + +def _limb(cv, ctx, inst, S, s, f): + """an owl (or parrot) with nothing to perch on is given a limb under its feet, reaching in from the nearer frame + edge (perch.py's rule: never a bird standing on the lawn or floating; animal-0xx perched toes wrap the branch)""" + from ..shading import lit_capsule + g = S(V(0, 0)) + r = max(1.5, s * .045) + side = -1 if g[0] <= cv.w / 2 else 1 + x0 = -4 if side < 0 else cv.w + 4 + x1 = g[0] - side * s * .45 + y = g[1] + r * .7 + old = cv.cur_id + cv.cur_id = None + try: + c = (104, 80, 58) + n = 6 + for k in range(n): + a, bb = k / n, (k + 1) / n + xa, xb = x0 + (x1 - x0) * a, x0 + (x1 - x0) * bb + ya, yb = y + r * .6 * a * a, y + r * .6 * bb * bb + lit_capsule(cv, ctx.L, xa, ya, xb, yb, r * (1 - .4 * a), c) + fx = x0 + (x1 - x0) * .55 + lit_capsule(cv, ctx.L, fx, y + r * .2, fx - side * r * 3.5, y - r * 3.2, r * .45, c) + finally: + cv.cur_id = old + + +def _ground_shadow(cv, ctx, cx, cy, rx, ry, pixel): + old = cv.cur_id + cv.cur_id = None + try: + cv.ellipse(cx, cy + ry * .2, rx, ry, (20, 22, 26), 0.0, .22 if not pixel else .3) + finally: + cv.cur_id = old + + +def _water(cv, ctx, B, S, s, pixel, out, pl): + """swimming (animal-0xx): the water line cuts the body at .3-.4 of its height; a ripple ring at the water line, a + short V-wake from the breast and a broken dark reflection under the bird""" + wl = S(V(0, 0)) + x0 = S(V(-.7, 0))[0] + x1 = S(V(.9, 0))[0] + cx, cy = (x0 + x1) * .5, wl[1] + rx = abs(x1 - x0) * .62 + old = cv.cur_id + cv.cur_id = None + try: + if 0 <= int(cy) < cv.h and 0 <= int(cx) < cv.w: + w0 = cv.px[min(cv.h - 1, int(cy) + 2)][int(cx)] + else: + w0 = (90, 120, 150) + dark = tuple(max(0, v * .6) for v in w0) + light = tuple(min(255, v * 1.25 + 25) for v in w0) + # reflection: the bird's own colour, darker, in broken horizontal strokes below the line + ys, xs = np.nonzero(pl.a > .5) + if len(ys): + body_col = np.median(out[ys, xs], 0) + rc = tuple(float(v) * .55 + w0[i] * .45 for i, v in enumerate(body_col)) + hgt = (S(V(0, B.lm.get("body_c", V(0, .3))[1] * 2))[1] - cy) + nrow = max(1, int(abs(hgt) * .6 / max(1.0, s * .03))) + for r in range(nrow): + y = cy + 1 + r * abs(hgt) * .6 / nrow + frac = 1 - r / max(nrow, 1) + ww = rx * .75 * frac + cv.capsule(cx - ww + (r % 2) * s * .04, y, cx + ww * .8, y, max(.5, s * .012), rc, .55 * frac) + cv.ellipse(cx, cy + .5, rx, max(1.0, rx * .1), dark, 0.0, .45) + cv.capsule(cx - rx * .9, cy - .2, cx + rx * .9, cy - .2, max(.5, s * .008), light, .7) + if "swim" in str((getattr(ctx, "scene", None) or {}).get("text", "")) or B.pose == "swim": + bx = S(V(.75, 0)) + for sd in (-1, 1): + cv.capsule(bx[0], cy + .5, bx[0] - B_f(S) * rx * 1.1, cy + .5 + sd * rx * .12, max(.5, s * .01), light, + .45) + finally: + cv.cur_id = old + + +def B_f(S): + a = S(V(0, 0)) + b = S(V(1, 0)) + return 1 if b[0] > a[0] else -1 + + +def _wade_line(cv, ctx, B, S): + """the water line in canvas y when the bird stands in water (the ground at its feet reads as water, or the scene + is a water place); None = stand on the ground""" + feet = B.lm.get("feet") or [] + if not feet: + return None + sc = getattr(ctx, "scene", None) or {} + place = str(sc.get("place") or "") + watery = place in ("water", "lake", "pond", "river", "sea", "beach", "ocean", "marsh", "swamp") + p = S(feet[0]) + y, x = int(min(cv.h - 1, max(0, p[1] + 1))), int(min(cv.w - 1, max(0, p[0]))) + c = cv.px[y][x] + if c[2] > c[0] + 8 and c[2] >= c[1] - 12: + watery = True + if not watery: + return None + leg = B.P["leg"] + B.lm["water_y"] = float(leg * .45) + return float(S(V(0, leg * .45))[1]) + + +def _wade(cv, ctx, B, S, s, pixel, wl): + """animal-043 wading: the water line cuts the tarsus at .3-.6 of its length; a ripple ring round each leg and a + broken reflection of the legs and body below it""" + feet = B.lm.get("feet") or [] + old = cv.cur_id + cv.cur_id = None + try: + for F_ in feet: + p = S(F_) + x = int(min(cv.w - 1, max(0, p[0]))) + y = int(min(cv.h - 1, max(0, wl + 2))) + w0 = cv.px[y][x] + light = tuple(min(255, v * 1.2 + 30) for v in w0) + dark = tuple(v * .7 for v in w0) + rx = max(2.0, s * .1) + cv.ellipse(p[0], wl, rx * 1.5, max(.8, rx * .3), dark, 0.0, .45) + cv.ellipse(p[0], wl - .4, rx, max(.7, rx * .22), light, 0.0, .55) + # the leg's reflection: a broken dark stroke below the line + lc = B.row["col"].get("leg", (120, 100, 80)) + rc = tuple(lc[i] * .45 + w0[i] * .55 for i in range(3)) + seg = max(1.5, s * .06) + yy = wl + 2 + k = 0 + while yy < wl + s * B.P["leg"] * .5 and k < 6: + cv.capsule(p[0] + (k % 2) * .6, yy, p[0] + (k % 2) * .6, yy + seg, max(.5, s * .012), rc, .6) + yy += seg * 1.7 + k += 1 + finally: + cv.cur_id = old + + +def _blit(cv, pl, out, nb, clip_wl, pixel): + from ..rig.bird import PART_IDS as _RP # noqa: F401 (the part table is shared with the rig) + a = pl.a + if clip_wl is not None: + yy = np.arange(pl.h)[:, None] + pl.y0 + a = np.where(yy > clip_wl, 0, a) + if cv.clip_y is not None: + yy = np.arange(pl.h)[:, None] + pl.y0 + a = np.where(yy > cv.clip_y, 0, a) + if pixel: + a = (a >= .5).astype(np.float32) + ys, xs = np.nonzero(a > .02) + if not len(ys): + return + Y = ys + pl.y0 + X = xs + pl.x0 + ok = (Y >= 0) & (Y < cv.h) & (X >= 0) & (X < cv.w) + ys, xs, Y, X = ys[ok], xs[ok], Y[ok], X[ok] + cid = cv.cur_id + if cid is not None and getattr(cv, "part", None) is None: + cv.part = [[0] * cv.w for _ in range(cv.h)] + nbuf = getattr(cv, "nbuf", None) + if nbuf is None: + nbuf = np.zeros((cv.h, cv.w, 3), np.float32) + cv.nbuf = nbuf + zb = getattr(cv, "zbuf", None) + if zb is None: + zb = np.zeros((cv.h, cv.w), np.float32) + cv.zbuf = zb + fd = getattr(cv, "fdir", None) + if fd is None: + fd = np.zeros((cv.h, cv.w, 2), np.float32) + cv.fdir = fd + from scipy import ndimage + depth = ndimage.distance_transform_edt(pl.a > .5).astype(np.float32) + lay = getattr(cv, "layer", None) + av = a[ys, xs].tolist() + cl = out[ys, xs].tolist() + pt = pl.part[ys, xs].tolist() + for y, x, al, c, p in zip(Y.tolist(), X.tolist(), av, cl, pt): + px = cv.px[y][x] + px[0] += (c[0] - px[0]) * al + px[1] += (c[1] - px[1]) * al + px[2] += (c[2] - px[2]) * al + if al >= .5 and cid is not None: + cv.ids[y][x] = cid + cv.part[y][x] = int(p) + if lay is not None: + lay[y, x] = 0 + k = a[ys, xs] >= .5 + nbuf[Y[k], X[k]] = nb[ys[k], xs[k]] + zb[Y[k], X[k]] = depth[ys[k], xs[k]] + 1.0 + fd[Y[k], X[k]] = pl.fd[ys[k], xs[k]] + + +# --------------------------------------------------------------------------------------------- owl branch stub +def draw_limb(cv, ctx, inst, s_unit=None): + """an owl with nothing to perch on gets a limb under its feet from the nearer frame edge (perch.py's rule)""" + pass diff --git a/pydraw/creature2d/canon.py b/pydraw/creature2d/canon.py new file mode 100644 index 0000000000000000000000000000000000000000..8639113e487e595014890c1bdb6d16f09a4e2d6e --- /dev/null +++ b/pydraw/creature2d/canon.py @@ -0,0 +1,304 @@ +"""Species canon for the 2D quadruped drawer (wave 20, quad lane). + +Every length is in WITHERS HEIGHTS (W = ground to the top of the shoulder blades = 1) unless it says heads. Each value +is a RANGE (lo, hi); resolve() picks one value per instance from the seed, so two foxes are not clones and no number is +typed from one picture. Sources are research 21 rules (docs/research21/rules/animal.jsonl) and research 20 +(docs/research20/animals.md, copy_animals.md): + + head head length (poll -> nose) / W animal-006 (horse, cow, sheep, deer, wolf, cat 0.40; big dog 0.33; + bear 0.50), copy_animals A4 + body point of shoulder -> point of buttock / W animal-007 (square 0.95-1.05 .. fox 1.4-1.6) + clear ground -> belly at the girth / W animal-009; depth (withers -> brisket) = 1 - clear (animal-008) + croup croup height / W animal-093 + neck withers point -> poll in HEADS, as built animal-010 gives the neck proper (horse 1.0-1.05 heads); measured + from the WITHERS point it is longer (copy_animals A3: Stubbs' + walking horse 0.76 W = 1.9 heads, dog 0.32 W, cat 0.38 W) + nang neck angle above level, standing (deg) animal-019 (poll height per species) + hang head axis below level, standing (deg) animal-019 / 020 + hock hock height / W animal-011 + carpus front wrist height / W animal-011 + fore forearm half-width / W; cannon = lower leg half-width / W copy_animals leg widths (forearm 15-20, cannon + 7-9 per 100 px W -> half widths .075-.1 / .035-.045) + tail (kind, length / body length, carriage deg below level) animal-012, key shapes 051-057 + ears (kind, length / head, angle back deg) + legs ungul | digi | planti animal-023 + marks identity marks (key shapes, animal-051..058, 098): drawn by quad.py + coat colours (base, belly, points, ...); fur sleek | medium | shaggy | wool (animal-072) +""" +import random +import zlib + +R = {} + + +def sp(name, parent=None, **kw): + row = dict(R[parent]) if parent else {} + if parent: + row["coat"] = dict(R[parent]["coat"]) + row["marks"] = list(R[parent].get("marks", ())) + coat = kw.pop("coat", None) + if coat: + row["coat"].update(coat) if "coat" in row else row.__setitem__("coat", dict(coat)) + row.update(kw) + row["name"] = name + R[name] = row + return row + + +# ---- ungulates +sp("horse", legs="ungul", head=(.38, .42), body=(1.02, 1.15), clear=(.55, .59), croup=(.98, 1.01), neck=(1.5, 1.75), + nang=(32, 40), hang=(40, 50), hock=(.37, .41), carpus=(.27, .3), fore=(.08, .09), cannon=(.034, .038), tuck=(.0, .03), + tail=("hair", (.55, .65), 75), ears=("horse", .3, -5), fur="sleek", + head_shape=dict(skull=.23, muzzle=.15, jaw=.25, jaw_at=.34, stop=.0, muz_drop=.02), + marks=["mane", "points", "hoof"], + coat=dict(base=(122, 74, 44), belly=None, points=(40, 30, 28), mane=(36, 26, 22), hoof=(44, 38, 34), + nose=(70, 54, 50))) +sp("pony", "horse", head=(.42, .46), body=(1.0, 1.1), clear=(.52, .56), neck=(1.3, 1.5), fore=(.09, .1), + cannon=(.04, .045)) +sp("foal", "horse", head=(.45, .52), body=(.85, .92), clear=(.63, .68), neck=(1.3, 1.4), fore=(.06, .07), + cannon=(.03, .033), hock=(.4, .44), tail=("hair", (.3, .35), 60), marks=["mane", "hoof"]) +sp("zebra", "horse", head=(.42, .45), body=(1.0, 1.08), ears=("horse", .38, -5), tail=("tuft", (.5, .55), 80), + marks=["mane_short", "stripes", "hoof"], coat=dict(base=(238, 236, 228), stripes=(26, 24, 26), mane=(30, 28, 30), + points=None, nose=(30, 28, 30))) +sp("donkey", "horse", head=(.46, .5), body=(1.0, 1.08), clear=(.52, .56), neck=(1.25, 1.4), nang=(30, 40), hang=(45, 55), + ears=("long", .62, 10), tail=("tuft", (.5, .58), 80), fore=(.075, .085), + marks=["mane_short", "muzzle_pale", "belly_pale", "hoof", "eye_ring"], + coat=dict(base=(128, 120, 114), belly=(214, 208, 198), points=None, mane=(64, 58, 56), muzzle=(222, 216, 206), + nose=(60, 52, 50))) +sp("cow", legs="ungul", head=(.42, .45), body=(1.2, 1.35), clear=(.38, .42), croup=(.99, 1.02), neck=(1.0, 1.15), + nang=(8, 18), hang=(42, 50), hock=(.3, .34), carpus=(.24, .27), fore=(.085, .095), cannon=(.042, .048), + tuck=(-.035, -.01), tail=("tuft", (.55, .62), 88), ears=("cow", .32, -85), fur="sleek", + head_shape=dict(skull=.23, muzzle=.2, jaw=.2, jaw_at=.38, stop=.0, muz_drop=.04), + marks=["horns", "udder", "hips", "patches", "muzzle_pink", "hoof", "dewlap"], + coat=dict(base=(244, 242, 236), patches=(34, 30, 32), muzzle=(228, 170, 168), hoof=(56, 48, 44), + udder=(232, 168, 166), horn=(226, 216, 190), nose=(214, 150, 150))) +sp("calf", "cow", head=(.5, .55), body=(.95, 1.05), clear=(.5, .56), fore=(.07, .08), cannon=(.036, .04), + marks=["patches", "muzzle_pink", "hoof"]) +sp("bull", "cow", clear=(.36, .4), neck=(.9, 1.0), fore=(.1, .11), cannon=(.05, .055), + marks=["horns", "hips", "muzzle_pink", "hoof", "dewlap", "hump_neck"], + coat=dict(base=(64, 44, 34), patches=None, muzzle=(80, 62, 56), nose=(60, 46, 44), horn=(220, 210, 180))) +sp("bison", "bull", head=(.46, .5), clear=(.4, .44), croup=(.82, .88), nang=(-5, 5), hang=(55, 65), + marks=["horns_short", "hump", "beard", "hoof", "shag_front"], fur="shaggy", + coat=dict(base=(84, 60, 42), front=(52, 38, 28), muzzle=(40, 30, 26), horn=(40, 34, 30))) +sp("sheep", legs="ungul", head=(.38, .42), body=(1.0, 1.1), clear=(.45, .5), croup=(.99, 1.02), neck=(.95, 1.1), + nang=(25, 35), hang=(45, 58), hock=(.29, .32), carpus=(.23, .26), fore=(.04, .045), cannon=(.028, .032), + tuck=(-.02, 0), tail=("stub", (.12, .16), 70), ears=("side", .3, -80), fur="wool", + head_shape=dict(skull=.24, muzzle=.15, jaw=.16, jaw_at=.4, stop=.0, muz_drop=.03), + marks=["wool", "dark_face", "hoof"], + coat=dict(base=(236, 230, 214), face=(52, 46, 46), legs=(60, 54, 52), hoof=(36, 32, 32), nose=(40, 34, 34))) +sp("lamb", "sheep", head=(.46, .52), body=(.9, .98), clear=(.52, .56), coat=dict(face=(230, 222, 206), + legs=(220, 210, 196))) +sp("goat", legs="ungul", head=(.4, .44), body=(1.0, 1.08), clear=(.48, .52), croup=(1.0, 1.03), neck=(1.1, 1.25), + nang=(40, 50), hang=(40, 50), hock=(.3, .33), carpus=(.24, .27), fore=(.05, .055), cannon=(.03, .034), + tuck=(0, .02), tail=("up", (.14, .18), -60), ears=("side", .4, -60), fur="medium", + head_shape=dict(skull=.22, muzzle=.13, jaw=.15, jaw_at=.4, stop=.0, muz_drop=.02), + marks=["horns_back", "beard", "hoof"], + coat=dict(base=(232, 226, 214), horn=(150, 136, 116), hoof=(52, 46, 42), nose=(120, 100, 96))) +sp("pig", legs="ungul", head=(.36, .4), body=(1.3, 1.45), clear=(.27, .32), croup=(1.0, 1.03), neck=(.5, .6), + nang=(0, 10), hock=(.2, .23), carpus=(.16, .19), fore=(.085, .095), cannon=(.06, .066), + tuck=(-.04, -.01), tail=("curl", (.12, .16), 0), ears=("flop_fwd", .38, 0), fur="sleek", hang=(14, 22), + head_shape=dict(skull=.36, muzzle=.22, jaw=.32, jaw_at=.42, stop=.02, muz_drop=.0), + marks=["snout", "hoof"], + coat=dict(base=(238, 178, 170), belly=(240, 190, 182), hoof=(150, 110, 100), nose=(236, 140, 146), + ear=(214, 140, 140))) +sp("deer", legs="ungul", head=(.4, .44), body=(1.05, 1.15), clear=(.5, .55), croup=(1.0, 1.04), neck=(1.0, 1.15), + nang=(45, 55), hang=(32, 42), hock=(.4, .45), carpus=(.27, .3), fore=(.055, .062), cannon=(.025, .028), + tuck=(.02, .05), tail=("flag", (.12, .15), -20), ears=("deer", .48, 30), fur="sleek", + head_shape=dict(skull=.22, muzzle=.11, jaw=.15, jaw_at=.38, stop=.0, muz_drop=.03), + marks=["antlers", "rump", "belly_pale", "hoof", "nose_dark", "throat_pale"], + coat=dict(base=(150, 100, 60), belly=(228, 214, 190), rump=(240, 234, 222), hoof=(40, 34, 30), + nose=(30, 26, 24), antler=(196, 172, 136))) +sp("doe", "deer", marks=["rump", "belly_pale", "hoof", "nose_dark", "throat_pale"]) +sp("fawn", "doe", head=(.46, .52), body=(.9, .98), clear=(.58, .62), marks=["rump", "belly_pale", "hoof", "nose_dark", + "fawn_spots"]) +sp("reindeer", "deer", clear=(.45, .5), fore=(.065, .072), cannon=(.032, .036), neck=(.95, 1.05), + marks=["antlers_big", "mane_throat", "hoof", "belly_pale"], + coat=dict(base=(120, 100, 84), belly=(214, 206, 190), mane=(222, 214, 198))) +sp("moose", "deer", head=(.48, .52), body=(.95, 1.05), clear=(.55, .6), croup=(.9, .94), neck=(.75, .85), nang=(25, 35), + hang=(40, 50), fore=(.07, .08), cannon=(.034, .038), ears=("deer", .38, 20), tail=("stub", (.06, .08), 60), + head_shape=dict(skull=.2, muzzle=.2, jaw=.18, jaw_at=.4, stop=.0, muz_drop=.08), + marks=["palmate", "hump", "bell", "hoof"], + coat=dict(base=(64, 48, 38), belly=None, legs=(150, 130, 110), antler=(176, 156, 126))) + +# ---- digitigrade +sp("dog", legs="digi", head=(.36, .4), body=(1.0, 1.1), clear=(.5, .54), croup=(.97, 1.0), neck=(1.0, 1.15), + nang=(38, 48), hang=(20, 32), hock=(.25, .29), carpus=(.15, .18), fore=(.07, .078), cannon=(.04, .045), + tuck=(.06, .1), tail=("sabre", (.5, .6), 20), ears=("drop", .38, 10), fur="medium", + head_shape=dict(skull=.27, muzzle=.15, jaw=.16, jaw_at=.45, stop=.08, muz_drop=.04), + marks=["paw", "collar"], + coat=dict(base=(170, 112, 62), belly=(226, 196, 150), nose=(30, 24, 24))) +sp("puppy", "dog", head=(.48, .55), body=(.85, .95), clear=(.46, .5), fore=(.085, .095), cannon=(.055, .06), + tail=("sabre", (.35, .4), 0), head_shape=dict(skull=.32, muzzle=.13, jaw=.16, jaw_at=.45, stop=.1, muz_drop=.04)) +sp("retriever", "dog", fur="shaggy", tail=("plume", (.55, .62), 25), coat=dict(base=(212, 160, 84), + belly=(232, 200, 140))) +sp("labrador", "dog", coat=dict(base=(220, 186, 120), belly=(232, 204, 150)), tail=("otter", (.5, .55), 25)) +sp("husky", "dog", ears=("prick", .34, 8), tail=("curl_up", (.5, .55), -40), fur="shaggy", + marks=["paw", "mask_pale", "saddle"], + coat=dict(base=(236, 236, 232), saddle=(92, 96, 108), belly=(244, 244, 240), mask=(246, 246, 242), + eye=(110, 175, 235))) +sp("german shepherd", "dog", ears=("prick", .38, 12), tail=("brush", (.55, .6), 35), croup=(.92, .95), + marks=["paw", "saddle"], coat=dict(base=(176, 118, 60), saddle=(36, 30, 28), belly=(200, 150, 90))) +sp("dalmatian", "dog", fur="sleek", marks=["paw", "spots", "collar"], coat=dict(base=(242, 240, 234), spots=(28, 26, 28), + belly=None)) +sp("beagle", "dog", clear=(.46, .5), ears=("drop", .48, 0), tail=("sabre", (.45, .5), -40), + marks=["paw", "saddle", "tail_tip"], coat=dict(base=(196, 128, 60), saddle=(40, 32, 30), belly=(246, 244, 238), + tip=(246, 244, 238))) +sp("dachshund", "dog", head=(.55, .62), body=(1.9, 2.1), clear=(.2, .25), hock=(.18, .2), carpus=(.1, .12), + fore=(.1, .11), cannon=(.07, .075), ears=("drop", .5, 0), tail=("sabre", (.35, .4), 10), + coat=dict(base=(146, 70, 34), belly=(170, 92, 50))) +sp("corgi", "dog", head=(.5, .55), body=(1.55, 1.7), clear=(.28, .32), hock=(.18, .2), carpus=(.1, .12), + fore=(.1, .11), cannon=(.07, .075), ears=("prick", .42, 10), tail=("stub", (.06, .08), 0), + marks=["paw", "mask_pale"], coat=dict(base=(214, 122, 52), belly=(250, 248, 240), mask=(250, 248, 240))) +sp("greyhound", "dog", body=(1.0, 1.08), clear=(.5, .55), tuck=(.2, .25), fore=(.055, .06), cannon=(.03, .033), + tail=("whip", (.65, .75), 60), fur="sleek", head_shape=dict(skull=.22, muzzle=.11, jaw=.13, jaw_at=.45, stop=.03, + muz_drop=.03), + ears=("rose", .3, 40), coat=dict(base=(150, 150, 152), belly=(190, 190, 190))) +sp("poodle", "dog", fur="wool", ears=("drop", .45, 0), tail=("pom", (.3, .35), -50), coat=dict(base=(240, 236, 228), + belly=None)) +sp("terrier", "dog", head=(.4, .44), clear=(.46, .5), ears=("fold", .3, 0), tail=("up", (.25, .3), -70), + fur="shaggy", marks=["paw", "saddle", "beard"], coat=dict(base=(206, 172, 118), saddle=(60, 52, 48))) +sp("wolf", "dog", head=(.39, .42), body=(1.1, 1.2), clear=(.52, .56), nang=(25, 35), hang=(22, 32), + ears=("prick", .3, 8), tail=("brush", (.45, .5), 60), fur="shaggy", tuck=(.05, .08), + head_shape=dict(skull=.25, muzzle=.14, jaw=.15, jaw_at=.45, stop=.05, muz_drop=.04), + marks=["paw", "saddle", "mask_pale", "ruff"], + coat=dict(base=(128, 120, 108), saddle=(70, 66, 62), belly=(212, 204, 190), mask=(214, 208, 196), + eye=(200, 170, 80))) +sp("fox", legs="digi", head=(.4, .44), body=(1.35, 1.5), clear=(.5, .54), croup=(.97, 1.0), neck=(.7, .8), + nang=(20, 30), hang=(25, 35), hock=(.25, .29), carpus=(.15, .18), fore=(.052, .058), cannon=(.028, .032), + tuck=(.03, .06), tail=("brush", (.6, .7), 30), ears=("prick", .42, 6), fur="medium", + head_shape=dict(skull=.26, muzzle=.11, jaw=.17, jaw_at=.42, stop=.05, muz_drop=.04), + marks=["paw", "stockings", "bib", "tail_tip", "ear_backs"], + coat=dict(base=(210, 102, 40), belly=(246, 240, 228), mask=(246, 240, 228), points=(40, 30, 28), + tip=(248, 246, 240), ear_back=(40, 30, 28), nose=(30, 24, 24), eye=(200, 140, 40))) +sp("cat", legs="digi", head=(.42, .47), # Muybridge cat 0.47 (research 20 table) + body=(1.3, 1.42), clear=(.45, .5), croup=(1.02, 1.06), neck=(.7, .85), + nang=(22, 32), hang=(15, 25), hock=(.25, .28), carpus=(.15, .17), fore=(.055, .06), cannon=(.032, .036), + tuck=(.07, .1), tail=("cat", (.68, .75), 40), ears=("cat", .38, 4), fur="medium", + head_shape=dict(skull=.36, muzzle=.13, jaw=.2, jaw_at=.5, stop=.1, muz_drop=.03), + marks=["paw", "stripes_tabby", "whiskers"], + coat=dict(base=(140, 132, 126), belly=(222, 214, 202), stripes=(74, 68, 66), nose=(222, 148, 148), + eye=(170, 196, 70))) +sp("kitten", "cat", head=(.5, .56), body=(1.05, 1.15), clear=(.47, .52), fore=(.065, .072), cannon=(.042, .046), + tail=("cat", (.55, .6), 30)) +sp("lion", "cat", head=(.36, .4), body=(1.28, 1.38), clear=(.47, .52), croup=(.96, 1.0), nang=(18, 28), hang=(10, 20), + fore=(.085, .095), cannon=(.055, .06), ears=("round", .2, 0), tail=("tuftc", (.62, .7), 70), + head_shape=dict(skull=.34, muzzle=.21, jaw=.22, jaw_at=.5, stop=.08, muz_drop=.04), + marks=["paw", "lion_mane", "tail_tuft", "muzzle_pale"], + coat=dict(base=(198, 150, 86), belly=(228, 204, 158), mane=(130, 82, 40), muzzle=(236, 222, 196), + tuft=(70, 46, 30), nose=(150, 90, 80), eye=(200, 150, 50))) +sp("lioness", "lion", marks=["paw", "tail_tuft", "muzzle_pale"]) +sp("tiger", "lion", body=(1.4, 1.52), tail=("cat", (.6, .68), 50), + marks=["paw", "stripes_tiger", "muzzle_pale", "belly_pale"], + coat=dict(base=(222, 120, 40), belly=(246, 238, 222), stripes=(30, 24, 22), muzzle=(246, 240, 228), + nose=(200, 120, 110), eye=(220, 180, 60))) +sp("leopard", "lion", body=(1.35, 1.45), fore=(.075, .085), cannon=(.048, .052), tail=("cat", (.7, .78), 30), + marks=["paw", "rosettes", "belly_pale"], coat=dict(base=(214, 168, 96), belly=(240, 228, 200), spots=(40, 32, 26))) +sp("cheetah", "leopard", clear=(.55, .6), tuck=(.15, .2), fore=(.06, .066), cannon=(.034, .038), + marks=["paw", "spots", "belly_pale", "tear_line"], coat=dict(base=(222, 180, 110))) +sp("panther", "leopard", marks=["paw"], coat=dict(base=(34, 32, 36), belly=None, spots=None, eye=(210, 190, 70))) +sp("hyena", "dog", croup=(.82, .87), head=(.44, .48), ears=("round", .3, 0), tail=("tuft", (.3, .35), 70), + marks=["paw", "spots"], coat=dict(base=(170, 146, 108), spots=(60, 48, 40), belly=None)) +sp("rabbit", legs="digi", head=(.48, .54), body=(1.05, 1.15), clear=(.3, .36), croup=(1.25, 1.35), neck=(.3, .4), + nang=(55, 70), hang=(10, 20), hock=(.06, .08), carpus=(.1, .12), fore=(.05, .055), cannon=(.035, .04), + tuck=(-.05, 0), tail=("pom", (.12, .14), -30), ears=("rabbit", 1.05, 25), fur="medium", + head_shape=dict(skull=.33, muzzle=.16, jaw=.2, jaw_at=.45, stop=.05, muz_drop=.03), + marks=["paw", "tail_white", "belly_pale"], + coat=dict(base=(150, 120, 92), belly=(232, 222, 206), tail=(246, 244, 240), nose=(214, 150, 150), + eye=(60, 40, 30))) +sp("raccoon", "dog", head=(.42, .46), body=(1.2, 1.3), clear=(.38, .42), croup=(1.05, 1.1), ears=("round", .3, 0), + tail=("brush", (.45, .5), 30), legs="planti", marks=["paw", "mask_bandit", "tail_rings"], fur="shaggy", + coat=dict(base=(128, 124, 118), belly=(176, 170, 160), mask=(30, 28, 30), muzzle=(230, 226, 218))) + +# ---- plantigrade +sp("bear", legs="planti", head=(.48, .52), body=(1.0, 1.1), clear=(.38, .42), croup=(.92, .96), neck=(.9, 1.0), + nang=(-8, 2), hang=(18, 28), hock=(.09, .12), carpus=(.12, .14), fore=(.13, .145), cannon=(.1, .11), + tuck=(-.03, 0), tail=("none", (.0, .0), 40), ears=("round", .2, 0), fur="shaggy", + head_shape=dict(skull=.3, muzzle=.16, jaw=.22, jaw_at=.42, stop=.05, muz_drop=.03), + marks=["hump", "claws", "muzzle_pale"], + coat=dict(base=(96, 64, 42), muzzle=(150, 118, 86), nose=(26, 22, 22), claw=(214, 204, 186), eye=(40, 28, 20))) +sp("polar bear", "bear", head=(.42, .46), neck=(1.2, 1.3), nang=(10, 18), marks=["claws"], + head_shape=dict(skull=.24, muzzle=.13, jaw=.15, jaw_at=.45, stop=.0, muz_drop=.02), + coat=dict(base=(240, 236, 222), muzzle=(236, 230, 214), claw=(90, 80, 70))) +sp("panda", "bear", head=(.5, .55), marks=["panda"], coat=dict(base=(244, 242, 236), patch=(28, 26, 30), + muzzle=(244, 242, 236))) + +sp("elephant", legs="pillar", head=(.4, .44), body=(1.0, 1.1), clear=(.45, .5), croup=(.88, .92), neck=(.35, .45), + nang=(5, 15), hang=(62, 70), hock=(.25, .28), carpus=(.22, .25), fore=(.11, .12), cannon=(.095, .105), + tuck=(-.04, 0), tail=("tuft", (.35, .4), 85), ears=("elephant", .75, 0), fur="sleek", + head_shape=dict(skull=.34, muzzle=.16, jaw=.18, jaw_at=.5, stop=.0, muz_drop=.0), + marks=["trunk", "tusks", "toenails"], # animal-098: 2.5 heads high, angular, trunk + coat=dict(base=(138, 132, 128), tusk=(236, 228, 206), nose=(120, 112, 108), hoof=(170, 162, 150))) +sp("calf elephant", "elephant", head=(.5, .55), body=(.9, 1.0), marks=["trunk", "toenails"]) + +# ---- words -> rows (concept names, breeds, young) +SYN = {"horse": "horse", "stallion": "horse", "mare": "horse", "pony": "pony", "foal": "foal", "colt": "foal", + "zebra": "zebra", "donkey": "donkey", "mule": "donkey", "burro": "donkey", + "cow": "cow", "cattle": "cow", "calf": "calf", "bull": "bull", "ox": "bull", "oxen": "bull", "bison": "bison", + "buffalo": "bison", "yak": "bison", + "sheep": "sheep", "ram": "sheep", "ewe": "sheep", "lamb": "lamb", "goat": "goat", "kid": "goat", + "pig": "pig", "piglet": "pig", "hog": "pig", "boar": "pig", "swine": "pig", + "deer": "deer", "stag": "deer", "buck": "deer", "doe": "doe", "hind": "doe", "fawn": "fawn", "elk": "deer", + "reindeer": "reindeer", "caribou": "reindeer", "moose": "moose", + "dog": "dog", "puppy": "puppy", "pup": "puppy", "retriever": "retriever", "golden": "retriever", + "labrador": "labrador", "lab": "labrador", "husky": "husky", "malamute": "husky", "shepherd": "german shepherd", + "dalmatian": "dalmatian", "beagle": "beagle", "dachshund": "dachshund", "corgi": "corgi", + "greyhound": "greyhound", "whippet": "greyhound", "poodle": "poodle", "terrier": "terrier", + "wolf": "wolf", "coyote": "wolf", "fox": "fox", "hyena": "hyena", "raccoon": "raccoon", + "cat": "cat", "kitten": "kitten", "kitty": "kitten", "lion": "lion", "lioness": "lioness", "tiger": "tiger", + "leopard": "leopard", "jaguar": "leopard", "cheetah": "cheetah", "panther": "panther", "cougar": "lioness", + "puma": "lioness", + "bear": "bear", "grizzly": "bear", "polar bear": "polar bear", "panda": "panda", + "rabbit": "rabbit", "bunny": "rabbit", "hare": "rabbit", "elephant": "elephant"} + +# concepts (registry names) whose drawer this package can replace +CONCEPTS = ("horse", "zebra", "donkey", "cow", "sheep", "goat", "pig", "deer", "moose", "bison", "dog", "wolf", "fox", + "cat", "lion", "tiger", "leopard", "hyena", "rabbit", "bear", "polar bear", "raccoon", "panda", "unicorn", "elephant") + + +def lookup(concept, word): + """species row name for a parsed instance (word first: breeds live in the word), or None""" + w = (word or "").lower() + toks = w.replace("-", " ").split() + for n in (2, 1): + for i in range(len(toks) - n + 1): + k = " ".join(toks[i:i + n]) + if k in SYN: + return SYN[k] + if k.endswith("s") and k[:-1] in SYN: + return SYN[k[:-1]] + c = (concept or "").lower() + if c == "unicorn": + return "horse" + return SYN.get(c) + + +def resolve(name, seed=0, cute=False): + """one instance of the species: every range resolved from the seed. cute=True walks the cute ladder + (animal-081: bigger head, shorter body and legs) for cartoon / chibi / children's book styles only (animal-099)""" + row = R[name] + rng = random.Random(zlib.crc32(name.encode()) * 7919 + int(seed)) + out = {} + for k, v in row.items(): + if isinstance(v, tuple) and len(v) == 2 and all(isinstance(x, (int, float)) for x in v): + out[k] = v[0] + (v[1] - v[0]) * rng.random() + else: + out[k] = v + out["coat"] = dict(row["coat"]) + out["marks"] = list(row.get("marks", ())) + out["head_shape"] = dict(row.get("head_shape") or dict(skull=.25, muzzle=.14, jaw=.16, jaw_at=.42, stop=.04, + muz_drop=.03)) + t = row["tail"] + out["tail"] = (t[0], t[1][0] + (t[1][1] - t[1][0]) * rng.random() if isinstance(t[1], tuple) else t[1], t[2]) + if cute: + # bigger, ROUNDER head (not a longer one): a bigger cranium, a shorter muzzle (animal-081) + out["head"] *= 1.25 + out["body"] *= .85 + out["clear"] = out["clear"] * .9 + out["fore"] *= 1.2 + out["cannon"] *= 1.25 + hs = out["head_shape"] + hs["skull"] = min(.42, hs["skull"] * 1.35) + hs["muzzle"] *= .75 + hs["jaw"] *= 1.1 + out["rng"] = rng + return out diff --git a/pydraw/creature2d/kit.py b/pydraw/creature2d/kit.py new file mode 100644 index 0000000000000000000000000000000000000000..241566c6b56e09b00a1a539114544a53ef2487ad --- /dev/null +++ b/pydraw/creature2d/kit.py @@ -0,0 +1,280 @@ +"""Shared 2D kit for the creature2d drawers (wave 20; quad lane owns it, the bird lane may use it read-only). + +Everything is drawn in a local box (x0, y0, w, h) of the canvas, at canvas pixels: + + R = Raster(x0, y0, w, h, ss=3) supersampled coverage masks: R.ellipse / circle / capsule / poly / tube + m = R.get() -> float32 HxW coverage 0..1 (anti-aliased) + shadow_band(m, l, k), lit_band(...) DESIGNED value shapes (research 20 copy_animals A5): the shadow family is the + part of a shape not covered by itself shifted k px toward the light + Light2D(ctx) the scene light as three value families (lit / local / shadow) of a colour, + from ctx.L, so the key colour and the time of day come from the scene + composite(cv, inst, rgb, alpha, ...) writes the finished figure into cv.px and the G-buffer side channels the rig + writes (cv.ids, cv.part, cv.nbuf, cv.zbuf, cv.fdir), so pixel, smooth and every + gbuf medium see the same animal + style_of(ctx, cv) "pixel" | "paint" | "ink" | "cartoon" | "plain" + tier(px) size tier of a figure from its size in canvas px (animal-076..080) +Rules only, numpy + PIL. No image files.""" +import math +import os +import numpy as np +from PIL import Image, ImageDraw, ImageFilter + + +def knob(name, default="1"): + ev = dict(kv.split("=", 1) for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return ev.get(name, default) + + +def on(name, default="1"): + return knob(name, default) != "0" + + +# ------------------------------------------------------------------------------------------------ masks +class Raster: + """coverage masks in a canvas-px box, drawn at ss x supersampling""" + + def __init__(self, x0, y0, w, h, ss=3): + self.x0, self.y0, self.w, self.h, self.ss = x0, y0, int(w), int(h), ss + self.im = Image.new("L", (self.w * ss, self.h * ss), 0) + self.d = ImageDraw.Draw(self.im) + + def _p(self, p): + return ((float(p[0]) - self.x0) * self.ss, (float(p[1]) - self.y0) * self.ss) + + def poly(self, pts, v=255): + if len(pts) >= 3: + self.d.polygon([self._p(p) for p in pts], fill=v) + + def circle(self, c, r, v=255): + x, y = self._p(c) + r = max(float(r), .35) * self.ss + self.d.ellipse([x - r, y - r, x + r, y + r], fill=v) + + def ellipse(self, c, rx, ry, ang=0.0, v=255): + t = np.linspace(0, 2 * np.pi, 48, endpoint=False) + a = math.radians(ang) + x, y = rx * np.cos(t), ry * np.sin(t) + self.poly(list(zip(c[0] + x * math.cos(a) - y * math.sin(a), c[1] + x * math.sin(a) + y * math.cos(a))), v) + + def capsule(self, p0, p1, r0, r1, v=255): + p0, p1 = np.asarray(p0, float), np.asarray(p1, float) + d = p1 - p0 + L = float(np.linalg.norm(d)) + if L > 1e-6: + n = np.array([-d[1], d[0]]) / L + self.poly([p0 + n * r0, p1 + n * r1, p1 - n * r1, p0 - n * r0], v) + self.circle(p0, r0, v) + self.circle(p1, r1, v) + + def tube(self, pts, radii, v=255): + """a tapered tube through points (radius per point)""" + for i in range(len(pts) - 1): + self.capsule(pts[i], pts[i + 1], radii[i], radii[i + 1], v) + + def get(self): + if self.ss == 1: + return np.asarray(self.im, np.float32) / 255 + m = self.im.resize((self.w, self.h), Image.BOX) + return np.asarray(m, np.float32) / 255 + + +def spline(pts, n=8, closed=False): + """Catmull-Rom through pts (list of xy) -> denser list""" + P = [np.asarray(p, float) for p in pts] + if len(P) < 3: + return [tuple(p) for p in P] + if closed: + P = [P[-1]] + P + [P[0], P[1]] + else: + P = [P[0] * 2 - P[1]] + P + [P[-1] * 2 - P[-2]] + out = [] + for i in range(1, len(P) - 2): + p0, p1, p2, p3 = P[i - 1], P[i], P[i + 1], P[i + 2] + for t in np.linspace(0, 1, n, endpoint=False): + t2, t3 = t * t, t * t * t + out.append(tuple(.5 * (2 * p1 + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))) + if not closed: + out.append(tuple(P[-2])) + return out + + +# ------------------------------------------------------------------------------------------------ mask ops +def shift(m, dx, dy): + """mask moved by (dx, dy) px (bilinear, zero fill)""" + h, w = m.shape + ix, fx = int(math.floor(dx)), dx - math.floor(dx) + iy, fy = int(math.floor(dy)), dy - math.floor(dy) + + def sh(a, sx, sy): + o = np.zeros_like(a) + ys0, ys1 = max(0, sy), min(h, h + sy) + xs0, xs1 = max(0, sx), min(w, w + sx) + if ys1 > ys0 and xs1 > xs0: + o[ys0:ys1, xs0:xs1] = a[ys0 - sy:ys1 - sy, xs0 - sx:xs1 - sx] + return o + return (sh(m, ix, iy) * (1 - fx) * (1 - fy) + sh(m, ix + 1, iy) * fx * (1 - fy) + + sh(m, ix, iy + 1) * (1 - fx) * fy + sh(m, ix + 1, iy + 1) * fx * fy) + + +def shadow_band(m, l, k): + """designed form shadow: the part of the shape NOT covered by itself shifted k px toward the light (l = unit 2D + vector pointing toward the light, screen coords)""" + return np.clip(m - shift(m, l[0] * k, l[1] * k), 0, 1) * m + + +def lit_band(m, l, k): + """the lit top planes: the part not covered by itself shifted AWAY from the light""" + return np.clip(m - shift(m, -l[0] * k, -l[1] * k), 0, 1) * m + + +def blur(m, s): + if s <= 0: + return m + from scipy import ndimage + return ndimage.gaussian_filter(m, s) + + +def dilate(m, r): + from scipy import ndimage + if r <= 0: + return m + return ndimage.grey_dilation(m, size=(2 * r + 1, 2 * r + 1)) + + +def edge_in(m, r=1): + """inner edge band of a 0..1 mask (r px)""" + from scipy import ndimage + b = m > .5 + return (b & ~ndimage.binary_erosion(b, iterations=r)).astype(np.float32) + + +def hashn(x, y, seed=0): + """cheap per-pixel hash noise 0..1""" + return ((np.sin(x * 12.9898 + y * 78.233 + seed * 37.719) * 43758.5453) % 1.0).astype(np.float32) + + +def vnoise(x, y, scale, seed=0): + """smooth value noise on a grid of `scale` px (0..1)""" + gx, gy = x / scale, y / scale + x0, y0 = np.floor(gx), np.floor(gy) + fx, fy = gx - x0, gy - y0 + fx, fy = fx * fx * (3 - 2 * fx), fy * fy * (3 - 2 * fy) + a, b = hashn(x0, y0, seed), hashn(x0 + 1, y0, seed) + c, d = hashn(x0, y0 + 1, seed), hashn(x0 + 1, y0 + 1, seed) + return a * (1 - fx) * (1 - fy) + b * fx * (1 - fy) + c * (1 - fx) * fy + d * fx * fy + + +# ------------------------------------------------------------------------------------------------ light / value +class Light2D: + """the scene light as value families. ctx.L.shade(base, n) gives the colour of a plane with normal n; we ask it + for three designed planes (lit / local / shadow) instead of lighting every pixel from a computed normal.""" + + def __init__(self, ctx): + L = getattr(ctx, "L", None) + self.L = L + d = getattr(L, "d", (-.5, -.65, .55)) if L is not None else (-.5, -.65, .55) + lx, ly = float(d[0]), float(d[1]) + n = math.hypot(lx, ly) or 1.0 + self.l2 = (lx / n, ly / n) if n > .15 else (0.0, -1.0) # toward the light, screen coords (y down) + self.d3 = np.array(d, float) / (np.linalg.norm(d) or 1) + # three plane normals: facing the light, facing the viewer, turned away + dl = self.d3 + self.n_lit = dl * .75 + np.array([0, 0, 1.0]) * .25 + self.n_lit /= np.linalg.norm(self.n_lit) + self.n_loc = np.array([dl[0] * .35, dl[1] * .35, 1.0]) + self.n_loc /= np.linalg.norm(self.n_loc) + self.n_sh = np.array([-dl[0] * .7, -dl[1] * .2 + .25, .45]) + self.n_sh /= np.linalg.norm(self.n_sh) + + def _shade(self, base, n): + """vectorised ctx.L.shade for an HxWx3 base with one normal""" + L = self.L + if L is None: + k = max(0.0, float(n @ self.d3)) + return base * (.5 + .6 * k) + d = max(0.0, float(n[0] * L.d[0] + n[1] * L.d[1] + n[2] * L.d[2])) + sky = (-n[1] if n[1] < 0 else 0) * L.sky_amount + key = np.array(L.key, float) + out = base * (L.ambient + L.strength * d * key) + np.array(L.sky, float) * sky + return np.clip(out, 0, 255) + + def families(self, base): + """(lit, local, shadow) colour fields of an HxWx3 albedo""" + return self._shade(base, self.n_lit), self._shade(base, self.n_loc), self._shade(base, self.n_sh) + + +# ------------------------------------------------------------------------------------------------ style + size +def style_of(ctx, cv): + """the drawing manner the scene asks for (the medium renderers re-paint afterwards; this only picks the + construction: canon vs cute ladder, crisp vs soft value edges, mark density)""" + sc = getattr(ctx, "scene", None) or {} + st = (sc.get("style") or "") if isinstance(sc, dict) else "" + art = (sc.get("art") or "") if isinstance(sc, dict) else "" + text = (sc.get("text") or sc.get("prompt") or "") if isinstance(sc, dict) else "" + low = " %s " % str(text).lower() + if any(w in low for w in (" cartoon", " chibi", " kawaii", " cute ", " children's book", " childrens book", + " storybook", " mascot", " anime", " manga", " cel shaded", " comic")): + return "cartoon" + if cv.ss == 1 or st == "pixel": + return "pixel" + if st in ("sketch", "bw") or art in ("sketch",): + return "ink" + if st in ("oil", "watercolor", "pastel") or art: + return "paint" + return "plain" + + +def tier(px): + """size tier of a figure from its withers height in canvas px: 0 tiny <20, 1 small 20-40, 2 mid 40-100, + 3 big 100-300, 4 huge 300+ (canvas px; the output is 1-2x that). animal-077..080""" + return 0 if px < 20 else 1 if px < 40 else 2 if px < 100 else 3 if px < 300 else 4 + + +# ------------------------------------------------------------------------------------------------ composite +def composite(cv, inst, rgb, alpha, x0, y0, part=None, z=None, nrm=None, fdir=None, crisp=False, part_ids=None): + """write an HxW figure (rgb 0..255, alpha 0..1) whose top-left is canvas (x0, y0) into cv; side channels as the + rig writes them. part: HxW int part codes (mapped through part_ids to cv.part ints).""" + h, w = alpha.shape + X0, Y0 = int(x0), int(y0) + cid = cv.cur_id + if cid is not None and getattr(cv, "part", None) is None and part is not None: + cv.part = [[0] * cv.w for _ in range(cv.h)] + nb = getattr(cv, "nbuf", None) + if nb is None and nrm is not None: + nb = np.zeros((cv.h, cv.w, 3), np.float32) + cv.nbuf = nb + zb = getattr(cv, "zbuf", None) + if zb is None and z is not None: + zb = np.zeros((cv.h, cv.w), np.float32) + cv.zbuf = zb + fd = getattr(cv, "fdir", None) + if fd is None and fdir is not None: + fd = np.zeros((cv.h, cv.w, 2), np.float32) + cv.fdir = fd + clip = getattr(cv, "clip_y", None) + ys, xs = np.nonzero(alpha > (.5 if crisp else .004)) + for yy, xx in zip(ys.tolist(), xs.tolist()): + Y, X = Y0 + yy, X0 + xx + if Y < 0 or Y >= cv.h or X < 0 or X >= cv.w: + continue + if clip is not None and Y > clip: + continue + a = 1.0 if crisp else float(alpha[yy, xx]) + c = rgb[yy, xx] + p = cv.px[Y][X] + p[0] += (float(c[0]) - p[0]) * a + p[1] += (float(c[1]) - p[1]) * a + p[2] += (float(c[2]) - p[2]) * a + if a >= .5: + if cid is not None: + cv.ids[Y][X] = cid + if part is not None: + k = int(part[yy, xx]) + cv.part[Y][X] = int(part_ids.get(k, k)) if part_ids else k + if nrm is not None: + nb[Y, X] = nrm[yy, xx] + if z is not None: + zb[Y, X] = float(z[yy, xx]) + if fdir is not None: + fd[Y, X] = fdir[yy, xx] diff --git a/pydraw/creature2d/quad.py b/pydraw/creature2d/quad.py new file mode 100644 index 0000000000000000000000000000000000000000..8786dbdfc41be9c6d3677dcbc0e73ab719993e9e --- /dev/null +++ b/pydraw/creature2d/quad.py @@ -0,0 +1,1803 @@ +"""Four-legged animals drawn 2D-first, in the animal artist's order (wave 20, quad lane; knob c2d / c2d_quad). + +Method (research 20 copy_animals.md: hand-placed 2D copies built this way matched Stubbs, Steinlen and Potter at +silhouette IoU 0.76-0.93, against 0.12-0.32 for the tube rig): + 1 CANON canon.py: species ranges in withers heights / heads (animal-006..012), one value per instance + 2 POSE a pose silhouette per VERB (stand with the walk-phase stagger, walk with one fore lifted and folded, + trot, run, graze with the muzzle AHEAD of the hooves, sit, howl, lie sphinx / sternal, side, curl, rear, + upright, leap): trunk pitch + leg plans + neck / head angles (animal-019, 020, 029-040) + 3 LAYOUT named 2D landmarks: withers, croup, chest, buttock, brisket, the leg chains root -> elbow / stifle -> + carpus / hock -> fetlock -> toe built joint to joint so the zig-zag survives into the drawing (animal-024), + planted legs solved by 2-bone IK with the bend side fixed (elbow back, stifle forward) + 4 VALUE the scene light as three families (lit / local / shadow) from ctx.L; designed shadow shapes per mass + (shape minus itself shifted toward the light), the far pair one value step darker (animal-029, 074) + 5 MASSES in overlap order: far legs, tail, body (chest oval + hip oval + barrel), neck, mane, head, near legs + 6 FEATURES eyes, nostrils, hooves, paws, horns, antlers sized by the pixel size (animal-076..080) + 7 MARKS identity marks (key shapes animal-051..058, 098), fur as masses (wool, manes, ruffs), strands last +Every distance below is in WITHERS HEIGHTS (W) in a local frame: u forward (the facing), v up, ground v = 0.""" +import math +import numpy as np +from . import kit as K +from . import canon + +_PXL = [False] # pixel style lit by formlight (knob c2d_pxlight) +_CRISP = [False] # pixel style: colour boundaries inside the coat are hard steps, never quantised ramps + + +def _q(t): + return (t > .5).astype(np.float32) if _CRISP[0] else t + + +PART = {"body": 200, "head": 201, "muzzle": 202, "nose": 203, "ear": 204, "leg": 205, "hoof": 206, "tail": 207, + "mane": 208, "horn": 209, "eye": 210, "belly": 211} + + +def V(u, v): + return np.array([u, v], float) + + +def dirv(a): + """unit vector of a segment at angle a (deg) from straight DOWN, + = forward""" + r = math.radians(a) + return np.array([math.sin(r), -math.cos(r)]) + + +def ang_of(d): + return math.degrees(math.atan2(d[0], -d[1])) + + +def rot(p, c, deg): + """rotate p about c, counter-clockwise in (u, v) (v up): + lifts the front""" + a = math.radians(deg) + q = np.asarray(p, float) - c + return c + np.array([q[0] * math.cos(a) - q[1] * math.sin(a), q[0] * math.sin(a) + q[1] * math.cos(a)]) + + +def ik2(root, tgt, L0, L1, side): + """2-bone IK: the middle joint on the forward (side=+1) or backward (side=-1) side of the root->target line. + returns (mid, end, shortfall)""" + d = tgt - root + D = float(np.linalg.norm(d)) + 1e-9 + u = d / D + if D >= L0 + L1 - 1e-6: + return root + u * L0, root + u * (L0 + L1), D - (L0 + L1) + D = max(D, abs(L0 - L1) + 1e-4) + a = (L0 * L0 - L1 * L1 + D * D) / (2 * D) + h = math.sqrt(max(L0 * L0 - a * a, 0.0)) + nrm = np.array([-u[1], u[0]]) + if nrm[0] * side < 0: + nrm = -nrm + return root + u * a + nrm * h, tgt, 0.0 + + +# ================================================================================================ poses +def pose_of(inst, C, text=""): + """the pose name from the parsed verb (animal-020, 030-040)""" + p = getattr(inst, "pose", None) + at = getattr(inst, "attrs", None) or {} + g = (at.get("gait") or "") + " " + " ".join(at.get("verbs") or []) + " " + (at.get("action") or "") + legs = C["legs"] + low = " %s " % text.lower() + if p == "flying": + p = None # a quadruped never flies: the layout's 'flying' on a sill / shelf animal is a lost verb (research 20) + if p in (None, "standing") and at.get("char") == "sit" and (" sit" in low or " seated" in low): + p = "sitting" + if p in ("running", "chasing"): + if "trot" in g: + return "trot" + return "run" + if p == "walking": + return "trot" if "trot" in g else "walk" + if p == "jumping": + return "leap" + if p == "sitting": + if C["name"] == "rabbit": + return "crouch" + return "sit" if legs != "ungul" else "lie" + if p in ("lying", "resting"): + if at.get("lie") == "side": + return "side" + return "lie" + if p == "sleeping": + return "lie_sleep" if legs in ("ungul", "planti") else "curl" + if p == "grazing": + return "graze" + if p == "rearing": + return "rear" if legs == "ungul" else "upright" + if p == "upright": + return "upright" if legs != "ungul" else "rear" + if p == "howling": + return "howl" if legs != "ungul" else "stand" + if C["name"] == "rabbit" and p in (None, "standing"): + return "crouch" + return "stand" + + +# per pose: trunk pitch (deg, + = front up), and per leg either ("plant", du, (a2, a3) or None) = toe on the ground +# du W ahead of its rest place, lower segment angles from down (None = rest), or ("fk", (a0, a1, a2, a3)) = the leg +# hangs free at those angles. Muybridge walk frame: one fore lifted and folded (carpus 80-105 deg), hinds split +# (copy_animals A1b, animal-024, 029); stand = the walk-phase stagger, never four parallel posts (animal-029, L5) +LEGPLAN = { + "stand": dict(pitch=0, fn=("plant", .05, None), ff=("plant", -.06, None), hn=("plant", .07, None), + hf=("plant", -.1, None)), + "stand_b": dict(pitch=0, fn=("plant", -.05, None), ff=("plant", .07, None), hn=("plant", -.1, None), + hf=("plant", .06, None)), + "walk": dict(pitch=0, fn=("fk", (-28, 28, -62, -35)), ff=("plant", -.08, None), hn=("plant", .14, None), + hf=("plant", -.2, (-22, -10))), + "trot": dict(pitch=2, fn=("fk", (-15, 45, -60, -30)), ff=("plant", -.1, None), hn=("plant", .12, None), + hf=("fk", (25, -70, -25, 5)), lift=.02), + "graze": dict(pitch=-2, fn=("plant", .2, None), ff=("plant", -.04, None), hn=("plant", .06, None), + hf=("plant", -.14, None)), + "gallop": dict(pitch=5, fn=("fk", (40, 62, 66, 72)), ff=("fk", (5, 62, -75, -55)), hn=("fk", (72, -20, 40, 72)), + hf=("plant", -.3, (-38, -28)), lift=0), + "rotary": dict(pitch=3, fn=("fk", (30, 55, 48, 30)), ff=("fk", (15, 38, 30, 10)), hn=("fk", (-25, -62, -72, -95)), + hf=("fk", (-10, -45, -55, -80)), lift=.08), + "leap": dict(pitch=12, fn=("fk", (-10, 40, -100, -70)), ff=("fk", (-20, 30, -110, -80)), + hn=("fk", (-40, -75, -85, -90)), hf=("fk", (-30, -65, -78, -86)), lift=.35), +} + + +# ================================================================================================ the plan +class Plan: + pass + + +def _rest_legs(C, T): + """rest leg chains (standing frame) from the canon: joint heights from animal-011 / research 20 A7""" + d = T["d"] + typ = C["legs"] + fet = {"ungul": .12, "digi": .055, "planti": .035, "pillar": .06}[typ] + tdx = {"ungul": .055, "digi": .075, "planti": .11, "pillar": .03}[typ] + uc, ub, cr = T["uc"], T["ub"], T["cr"] + el = V(uc - .25, 1 - d + .03) + car = V(el[0] + .015, C["carpus"]) + fore = [V(uc - .12, 1 - .55 * d), el, car, V(car[0] - .005, fet), V(car[0] - .005 + tdx, 0)] + st = V(ub + .33 + .05 * d, 1 - d + .02) + if typ == "planti": + hk = V(ub + .14, C["hock"]) + hind = [V(ub + .27, cr - .45 * d), st, hk, V(hk[0] + .12, .035), V(hk[0] + .2, 0)] + else: + hk = V(ub + .06, C["hock"]) + hind = [V(ub + .27, cr - .45 * d), st, hk, V(hk[0] + .025, fet), V(hk[0] + .025 + tdx, 0)] + if typ == "pillar": + # elephant: legs are columns, the joints stacked (animal-098) + fore = [V(uc - .14, 1 - .5 * d), V(uc - .17, 1 - d + .02), V(uc - .17, C["carpus"]), V(uc - .17, .06), + V(uc - .15, 0)] + hind = [V(ub + .2, cr - .45 * d), V(ub + .25, 1 - d + .02), V(ub + .19, C["hock"]), V(ub + .19, .06), + V(ub + .21, 0)] + if C["name"] == "rabbit": + hk = V(ub + .02, .06) + hind = [V(ub + .3, cr - .45 * d), V(ub + .5, .35), hk, V(hk[0] + .22, .03), V(hk[0] + .32, 0)] + return {"f": fore, "h": hind} + + +def _trunk(C): + d = 1 - C["clear"] + B = C["body"] + cr = C["croup"] + tk = C["tuck"] + uc = .42 * d + .05 # point of shoulder ahead of the withers (horse ~0.23 W) + ub = uc - B + T = dict(d=d, B=B, cr=cr, uc=uc, ub=ub) + T["withers"] = V(0, 1) + T["chest"] = V(uc, 1 - .48 * d) + T["brisket"] = V(uc - .22, 1 - d) + T["belly"] = V(ub + .55 * B, 1 - d - max(0, -tk)) + T["flank"] = V(ub + .3, 1 - d + max(tk, 0) + .12 * d) + T["buttock"] = V(ub, cr - .38 * d) + T["croup"] = V(ub + .2, cr) + T["tailroot"] = V(ub + .05, cr - .08 * d / .45 * .45 - .02) + T["loin"] = V(ub + .42 * min(B, 1.4), (1 + cr) * .5 + .005) + T["back"] = V(-.3 * min(B, 1.3), 1 - .035) + T["chest_o"] = (V(uc - .25, 1 - .52 * d), .27, .52 * d) + tkp = max(tk, 0) + T["hip_o"] = (V(ub + .25, cr - (.5 - tkp * .6) * d), .26, (.5 - tkp * 1.1) * d) # a tucked loin: a higher, + # shallower haunch (greyhound, dog, cat) than the barrel + T["neck_front"] = V(uc - .02, 1 - .42 * d) + return T + + +def _xf(p, piv, pitch, off): + """trunk frame -> pose. pitch = deg, or (rear deg, front deg, hinge point): a spine that bends at the loin + (sitting: the pelvis steep, the thorax flatter; one long S from ear to haunch, copy_animals A9)""" + if not isinstance(pitch, tuple): + return rot(p, piv, pitch) + off + ph, pf, Hn = pitch + p = np.asarray(p, float) + rear = rot(p, piv, ph) + off + front = rot(p - Hn, np.zeros(2), pf) + rot(Hn, piv, ph) + off + t = float(np.clip((p[0] - (Hn[0] - .14)) / .28, 0, 1)) + t = t * t * (3 - 2 * t) + return rear * (1 - t) + front * t + + +def _pf(pitch): + return pitch[1] if isinstance(pitch, tuple) else pitch + + +def _ph(pitch): + return pitch[0] if isinstance(pitch, tuple) else pitch + + +def build_plan(C, pose): + """landmarks of the animal in its pose (local W units)""" + P = Plan() + P.C, P.pose = C, pose + if pose in ("lie", "lie_sleep") and 1 - C["clear"] > .55: + # a heavy body lying on its sternum spreads: a lower, longer mass (pig, cow, bear) + C = dict(C) + C["clear"] = 1 - (1 - C["clear"]) * .82 + C["body"] = C["body"] * 1.06 + if pose in ("sit", "howl") and C["body"] > 1.1: + # a sitting cat / fox curls its spine: the trunk reads shorter than standing (copy_animals A9) + C = dict(C) + C["body"] = 1.1 + (C["body"] - 1.1) * .4 + T = _trunk(C) + P.T = T + rest = _rest_legs(C, T) + Hd = C["head"] + P.Hd = Hd + d = T["d"] + lp = LEGPLAN.get(pose) + gait = pose + if pose == "run": + gait = "gallop" if C["legs"] == "ungul" else "rotary" + lp = LEGPLAN[gait] + if pose == "stand" and C["rng"].random() < .5: + lp = LEGPLAN["stand_b"] + if pose == "graze": + # the advanced foreleg only as far as the neck can reach past it (short-necked sheep, pigs: barely) + reach = C["neck"] * C["head"] + C["head"] * .5 + k_ = float(np.clip((reach - .45) / .3, 0, 1)) + lp = dict(lp) + lp["fn"] = ("plant", -.04 + .24 * k_, None) + lp["ff"] = ("plant", -.04 - .08 * (1 - k_), None) + P.gait = gait + piv = rest["h"][0].copy() + pitch, off = 0.0, V(0, 0) + legs = {} + lift = 0.0 + if lp is not None: + pitch = lp["pitch"] + lift = lp.get("lift", 0) or 0 + off = V(0, 0) + for it in range(6): + short = 0.0 + legs = {} + for k in ("fn", "ff", "hn", "hf"): + legs[k] = _leg(C, rest[k[0]], k, lp[k], piv, pitch, off, lift) + short = max(short, legs[k]["short"]) + if short <= 1e-4: + break + off = off - V(0, short + .002) + if lift: + off = off + V(0, lift) + for k in legs: + legs[k] = _leg(C, rest[k[0]], k, lp[k], piv, pitch, off, lift) + if gait in ("rotary", "leap"): + # the flying frame: the lowest foot just clear of the ground (rotary: extended flight) + lo = min(min(p[1] for p in L["j"]) for L in legs.values()) + off = off + V(0, (lift * .5 if gait == "rotary" else lift) - lo) + for k in legs: + legs[k] = _leg(C, rest[k[0]], k, lp[k], piv, pitch, off, lift) + else: + pitch, off, legs = _rest_pose(C, rest, T, pose, piv) + for k, L in legs.items(): + # a free (fk) leg never goes through the ground: fold it at the carpus / hock until its foot clears + if L.get("planted") or pose in ("lie", "side", "lie_sleep", "sit", "howl", "crouch", "curl"): + continue + for it in range(12): + if min(p[1] for p in L["j"]) >= .03: + break + j = L["j"] + sgn = -1 if L["fore"] else 1 + for i in (2, 3): + j[i + 1] = j[i] + dirv(ang_of(j[i + 1] - j[i]) + sgn * 12) * L["L"][i] + if i == 2: + j[4] = j[3] + dirv(ang_of(j[4] - j[3]) + sgn * 12) * L["L"][3] + P.pitch_full = pitch + P.pitch_r, P.pitch_f = _ph(pitch), _pf(pitch) + P.pitch, P.off, P.piv = _pf(pitch), off, piv + X = lambda p: _xf(p, piv, pitch, off) + P.X = X + for k in ("withers", "chest", "brisket", "belly", "flank", "buttock", "croup", "tailroot", "loin", "back", + "neck_front"): + setattr(P, k, X(T[k])) + P.chest_o = (X(T["chest_o"][0]), T["chest_o"][1], T["chest_o"][2]) + P.pitch_full = pitch + P.hip_o = (X(T["hip_o"][0]), T["hip_o"][1], T["hip_o"][2]) + if pose in ("sit", "howl", "crouch"): + # copy_animals A11: in a sitting pose the haunch is the biggest mass (1.5-1.8x the chest) + P.hip_o = (X(T["hip_o"][0] + V(.04, -.04)), T["hip_o"][1] * 1.35, T["hip_o"][2] * 1.3) + P.legs = legs + _neck_head(P, C, T, pose) + _tail(P, C, T, pose) + return P + + +def _leg(C, rest, key, spec, piv, pitch, off, lift): + """one leg chain in the pose. spec = ("plant", du, lower angles or None) | ("fk", (a0, a1, a2, a3))""" + fore = key[0] == "f" + far = key[1] == "f" + R = [np.asarray(p, float) for p in rest] + Ls = [float(np.linalg.norm(R[i + 1] - R[i])) for i in range(4)] + ra = [ang_of(R[i + 1] - R[i]) for i in range(4)] + root = _xf(R[0], piv, pitch, off) + if far: + root = root + V(.035 if fore else .03, .0) # the far pair hangs from the far side of the spine (animal-003) + out = dict(near=not far, fore=fore, L=Ls, short=0.0, planted=False) + if spec[0] == "fk": + a = spec[1] + j = [root] + for i in range(4): + j.append(j[-1] + dirv(a[i]) * Ls[i]) + out["j"] = j + return out + du = spec[1] + a2, a3 = (spec[2] if spec[2] else (ra[2], ra[3])) + gy = .018 if far else 0.0 # far feet sit a little higher on the ground plane (animal-004) + toe = V(root[0] + (R[4][0] - R[0][0]) + du, gy) + kpt = toe - dirv(a3) * Ls[3] - dirv(a2) * Ls[2] + mid, end, short = ik2(root, kpt, Ls[0], Ls[1], -1 if fore else 1) + shift = end - kpt + out["j"] = [root, mid, end, end + dirv(a2) * Ls[2], end + dirv(a2) * Ls[2] + dirv(a3) * Ls[3]] + out["short"] = short + out["planted"] = short <= 1e-3 + return out + + +def _rest_pose(C, rest, T, pose, piv): + """sit / howl / lie / side / curl / rear / upright / crouch: trunk pitch from the pose, legs folded by FK, the + whole figure set down on the ground (animal-036..039)""" + d = T["d"] + legs = {} + typ = C["legs"] + if pose in ("sit", "howl"): + # animal-036: the pelvis pitched 45-60 deg; the thorax is flatter (the spine curves), so the trunk pitch is + # the steepest one at which the straight forelegs still reach the ground from the shoulder + Lf = sum(float(np.linalg.norm(rest["f"][i + 1] - rest["f"][i])) for i in range(4)) * .97 + hip_r = T["hip_o"][2] * 1.3 + Hn = V(T["ub"] + .45 * min(T["B"], 1.3), 1.0) + ph = 58 if typ != "planti" else 62 + pitch = (ph, 10, Hn) + for pt in range(ph - 4, -6, -2): + q = (ph, pt, Hn) + sh = _xf(rest["f"][0], piv, q, V(0, 0))[1] - _xf(T["hip_o"][0], piv, q, V(0, 0))[1] + hip_r * .9 + if sh <= Lf: + pitch = q + break + hind = (82, -62, 88, 90) if typ != "planti" else (70, 20, 85, 90) + hindf = (78, -58, 86, 90) if typ != "planti" else (65, 25, 85, 90) + pl = dict(hn=("fk", hind), hf=("fk", hindf)) + elif pose in ("lie", "lie_sleep"): + pitch = 2 + if typ == "ungul": + pl = dict(fn=("fk", (-20, 75, -95, -90)), ff=("fk", (-15, 85, -92, -90)), hn=("fk", (80, -78, 90, 90)), + hf=("fk", (85, -70, 92, 92))) + else: + pl = dict(fn=("fk", (-25, 86, 90, 90)), ff=("fk", (-20, 88, 90, 90)), hn=("fk", (80, -75, 90, 90)), + hf=("fk", (84, -70, 90, 90))) + elif pose == "side": + pitch = 0 + pl = dict(fn=("fk", (40, 78, 85, 88)), ff=("fk", (30, 70, 80, 86)), hn=("fk", (60, -60, -80, -86)), + hf=("fk", (50, -55, -75, -82))) + elif pose == "crouch": # rabbit loaf (research 16: a rabbit rests as a loaf) + pitch = 8 + pl = dict(fn=("fk", (-10, 5, 30, 85)), ff=("fk", (-5, 10, 35, 85)), hn=("fk", (75, -70, 88, 90)), + hf=("fk", (78, -66, 88, 90))) + elif pose in ("rear", "upright"): + pitch = 50 if pose == "rear" else 72 + pl = dict(fn=("fk", (-10, 40, -95, -60)) if typ == "ungul" else ("fk", (10, 40, 30, 70)), + ff=("fk", (-20, 30, -105, -70)) if typ == "ungul" else ("fk", (0, 30, 20, 60)), + hn=("plant", .15, None), hf=("plant", -.05, None)) + else: # curl handled in its own builder; a safe fallback + pitch = 0 + pl = dict(fn=("fk", (-25, 86, 90, 90)), ff=("fk", (-20, 88, 90, 90)), hn=("fk", (80, -75, 90, 90)), + hf=("fk", (84, -70, 90, 90))) + off = V(0, 0) + for k in ("hn", "hf"): + if pl[k][0] == "plant": + continue + legs[k] = _leg(C, rest["h"], k, pl[k], piv, pitch, off, 0) + if pose in ("rear", "upright"): + for it in range(6): + sh = 0 + for k in ("hn", "hf"): + legs[k] = _leg(C, rest["h"], k, pl[k], piv, pitch, off, 0) + sh = max(sh, legs[k]["short"]) + if sh <= 1e-4: + break + off = off - V(0, sh + .002) + for k in ("fn", "ff"): + legs[k] = _leg(C, rest["f"], k, pl[k], piv, pitch, off, 0) + return pitch, off, legs + # set the figure down: the lowest point of the hind legs and the haunch / belly on the ground + lo = min(min(p[1] for p in L["j"]) for L in legs.values()) + hip = _xf(T["hip_o"][0], piv, pitch, off) + hip_lo = hip[1] - T["hip_o"][2] * .9 + bel = _xf(T["belly"], piv, pitch, off)[1] + if pose in ("sit", "howl"): + lo = min(lo, hip_lo) + elif pose in ("lie", "lie_sleep", "side", "crouch"): + lo = min(lo, bel - (.02 if pose != "crouch" else -.02)) + off = off + V(0, -lo) + for k in ("hn", "hf"): + legs[k] = _leg(C, rest["h"], k, pl[k], piv, pitch, off, 0) + if pose in ("sit", "howl"): + # forelegs: straight vertical columns from the shoulder to the ground, the chest held high (animal-100) + for k in ("fn", "ff"): + R0 = _xf(rest["f"][0], piv, pitch, off) + (V(.035, 0) if k == "ff" else V(0, 0)) + Ls = [float(np.linalg.norm(rest["f"][i + 1] - rest["f"][i])) for i in range(4)] + du = (.03 if k == "fn" else -.02) + legs[k] = _leg(C, rest["f"], k, ("plant", du + .04, (2, 70 if typ == "digi" else 80)), piv, pitch, off, 0) + if legs[k]["short"] > 1e-3: + # too short to reach: let the leg stand straight down from the root and lift the chest + pass + else: + for k in ("fn", "ff"): + legs[k] = _leg(C, rest["f"], k, pl[k], piv, pitch, off, 0) + return pitch, off, legs + + +def _neck_head(P, C, T, pose): + Hd = P.Hd + hs = C["head_shape"] + nang, hang = C["nang"], C["hang"] + if pose == "walk": + nang, hang = nang - 6, min(max(hang, 30), 42) # animal-020: walking head 35-45 deg down (as measured) + elif pose in ("trot",): + nang, hang = nang - 2, max(25, hang - 8) + elif pose == "run": + nang, hang = min(nang, 25) - 5, 28 # galloping: neck stretched forward, head 20-35 down + elif pose in ("sit",): + nang, hang = nang + 18, hang + 5 + elif pose == "howl": + nang, hang = 75, -45 # nose to the sky + elif pose in ("lie",): + nang, hang = max(nang, 25) + 5, hang + elif pose in ("lie_sleep",): + nang, hang = -10, 70 + elif pose in ("rear",): + nang, hang = 70, 30 + elif pose == "upright": + nang, hang = 95, 20 + elif pose == "leap": + nang, hang = nang + 5, hang - 5 + elif pose == "crouch": + nang, hang = 62, 22 + elif pose == "upright_rabbit": + nang, hang = 80, 10 + Ln = C["neck"] * Hd + W0 = P.withers + V(-.03, 0) + world_n = nang + P.pitch * (.6 if pose not in ("sit", "howl", "rear", "upright") else 0) + if pose == "graze": + # animal-035: neck 45-60 deg below level, head 60-75 deg, the muzzle ON the ground 0.5-1 head AHEAD of the + # fore hooves; the withers stay the highest point. Solve the neck angle for ground contact. + toe_u = max(P.legs["fn"]["j"][-1][0], P.legs["ff"]["j"][-1][0]) + best = None + for stretch in (1.0, 1.12, 1.25, 1.4): + for hg in (70, 66, 62, 74): + for a in np.linspace(-25, -78, 54): + poll = W0 + np.array([math.cos(math.radians(a)), math.sin(math.radians(a))]) * Ln * stretch + low = _head_low(poll, hg, Hd, hs) + if -.015 <= low[1] <= .015: + reach = (low[0] - toe_u) / Hd + sc_ = -abs(reach - .75) - abs(hg - 68) * .01 - (stretch - 1) * 1.2 - (3 if reach < .3 else 0) + if best is None or sc_ > best[0]: + best = (sc_, a, stretch, hg) + if best is not None and best[0] > -.3: + break + if best is None: + best = (0, -70, 1.4, 70) + world_n, Ln, hang = best[1], Ln * best[2], best[3] + poll = W0 + np.array([math.cos(math.radians(world_n)), math.sin(math.radians(world_n))]) * Ln + P.poll, P.hang, P.nang = poll, hang, world_n + h = math.radians(hang) + e = np.array([math.cos(h), -math.sin(h)]) + n = np.array([math.sin(h), math.cos(h)]) + P.e, P.n = e, n + rs, rm, rj = hs["skull"] * Hd, hs["muzzle"] * Hd, hs["jaw"] * Hd + P.skull = (poll + e * rs * .95 - n * rs * .92, rs) + P.muzzle = (poll + e * (Hd - rm) - n * (hs["stop"] * Hd + rm + hs["muz_drop"] * Hd), rm) + P.jaw = (poll + e * hs["jaw_at"] * Hd - n * (2 * rs + .015 * Hd - rj), rj) + P.nose = poll + e * Hd - n * (hs["stop"] * Hd + rm * .9) + ea = {"horse": .34, "donkey": .34, "zebra": .34, "cow": .36, "pig": .4}.get(C["name"], .38) + if C["legs"] == "digi" and C["name"] not in ("rabbit",): + ea = .42 if C["name"] in ("cat", "kitten", "lion", "lioness", "tiger", "leopard", "cheetah", "panther") else .4 + P.eye = poll + e * ea * Hd - n * rs * .72 + P.throat = poll + e * .3 * Hd - n * (2 * rs + .01 * Hd) + P.ear_base = poll + e * .08 * Hd - n * .02 * Hd + + +def _head_low(poll, hang, Hd, hs): + h = math.radians(hang) + e = np.array([math.cos(h), -math.sin(h)]) + n = np.array([math.sin(h), math.cos(h)]) + rm = hs["muzzle"] * Hd + M = poll + e * (Hd - rm) - n * (hs["stop"] * Hd + rm + hs["muz_drop"] * Hd) + return M - np.array([0, rm]) + + +def _tail(P, C, T, pose): + kind, frac, carry = C["tail"] + if kind == "none": # a bear's tail is hidden in the fur (animal-057) + P.tail_pts, P.tail_w, P.tail_kind = [], [], kind + return + Lt = frac * T["B"] + TR = P.tailroot + pts, wid = [TR], [] + # (start angle below level pointing back, curvature deg over the length, width profile in W) + prof = {"hair": (15, 75, [.035, .06, .075, .07, .045]), "tuft": (carry, 6, [.02, .018, .016, .016, .015]), + "tuftc": (35, 55, [.03, .026, .022, .02, .018]), + "brush": (carry, 12, [.045, .1, .13, .12, .06]), "sabre": (-15, -35, [.035, .035, .03, .022, .012]), + "plume": (5, -30, [.04, .06, .065, .055, .03]), "otter": (25, 10, [.06, .05, .04, .03, .018]), + "cat": (carry + 25, -95, [.035, .032, .03, .028, .024]), "flag": (-35, 0, [.04, .045, .04, .03, .02]), + "stub": (carry, 0, [.05, .045, .035, .025, .02]), "pom": (0, 0, [.07, .07, .07, .07, .07]), + "curl": (-30, -320, [.022, .02, .018, .016, .014]), "up": (-65, 0, [.03, .03, .025, .02, .012]), + "curl_up": (-75, -230, [.06, .07, .07, .06, .04]), "whip": (carry, -60, [.025, .02, .016, .012, .008])} + a0, curv, w = prof.get(kind, (carry, 0, [.03, .03, .025, .02, .015])) + if pose == "run" and kind not in ("pom", "stub", "curl", "curl_up"): + a0, curv = 5, 5 if kind != "cat" else -20 # streams back + elif pose in ("sit", "howl") and kind in ("cat", "brush", "sabre", "whip", "otter", "plume", "tuft"): + a0, curv = 70, 120 if kind == "cat" else 70 # lies on the ground round the feet + elif pose in ("lie", "side", "lie_sleep") and kind not in ("pom", "stub", "curl", "curl_up", "flag", "up"): + a0, curv = (35, -30) if kind in ("brush", "cat", "whip", "sabre") else (65, 50) + a0 = a0 - P.pitch_r * .7 + n = 8 + a = a0 + step = Lt / n + for i in range(n): + a += curv / n + r = math.radians(a) + pts.append(pts[-1] + np.array([-math.cos(r), -math.sin(r)]) * step) + if pose in ("sit", "howl", "lie", "side", "lie_sleep"): + # a tail that would go into the ground lies along it + pts = [np.array([p[0], max(p[1], .02)]) for p in pts] + xs = np.linspace(0, 1, len(w)) + P.tail_pts = pts + P.tail_w = [float(np.interp(i / n, xs, w)) for i in range(n + 1)] + P.tail_kind = kind + + +# ================================================================================================ curled sleep +def build_curl(C): + """cat / fox / dog asleep: curled into a bean, seen from a little above: the body an oval 1.6-1.9x as long as + high, the head tucked at the front end resting on the paws and flank, the tail wrapped along the front to the nose + (animal-038)""" + P = Plan() + P.C, P.pose, P.gait = C, "curl", "curl" + T = _trunk(C) + P.T = T + d = T["d"] + Hd = C["head"] + P.Hd = Hd + rx = (T["B"] + .35) * .42 + ry = rx * .56 + c = V(0, ry * .98) + P.ring = (c, rx, ry) + P.legs = {} + P.withers = c + V(rx * .2, ry * .9) + P.croup = c + V(-rx * .75, ry * .5) + P.buttock = c + V(-rx, 0) + P.pitch, P.off, P.piv = 0, V(0, 0), V(0, 0) + P.pitch_r = P.pitch_f = 0 + P.pitch_full = 0 + hs = C["head_shape"] + rs = hs["skull"] * Hd + # the head lies on the front of the curl, chin down on the paws, face toward the viewer's side + P.poll = c + V(rx * .32, ry * .28 + rs) + P.hang, P.nang = 55, 0 + h = math.radians(P.hang) + P.e = np.array([math.cos(h), -math.sin(h)]) + P.n = np.array([math.sin(h), math.cos(h)]) + e, n = P.e, P.n + rm, rj = hs["muzzle"] * Hd, hs["jaw"] * Hd + P.skull = (P.poll + e * rs * .95 - n * rs * .92, rs) + P.muzzle = (P.poll + e * (Hd - rm) - n * (hs["stop"] * Hd + rm + hs["muz_drop"] * Hd), rm) + P.jaw = (P.poll + e * hs["jaw_at"] * Hd - n * (2 * rs + .015 * Hd - rj), rj) + P.nose = P.poll + e * Hd - n * (hs["stop"] * Hd + rm * .9) + P.eye = P.poll + e * .4 * Hd - n * rs * .72 + P.throat = P.poll + e * .3 * Hd - n * 2 * rs + P.ear_base = P.poll + e * .08 * Hd - n * .02 * Hd + # paws peeking out under the chin + P.paws = [P.muzzle[0] + V(-.02, -rm * 1.2), P.muzzle[0] + V(-.12, -rm * 1.3)] + kind, frac, carry = C["tail"] + pts = [] + for i in range(9): + t = math.radians(-175 + i * (150 / 8)) + pts.append(c + V(rx * 1.0 * math.cos(t), ry * .95 * math.sin(t))) + pts = pts + [P.muzzle[0] + V(-.05, -rm * 1.6)] + P.tail_pts = pts + prof = {"brush": [.05, .09, .11, .11, .08], "cat": [.035, .033, .03, .03, .028]}.get(kind, [.04, .045, .045, .04, + .03]) + P.tail_w = [float(np.interp(i / (len(pts) - 1), np.linspace(0, 1, 5), prof)) for i in range(len(pts))] + P.tail_kind = kind + P.tailroot = pts[0] + P.X = lambda p: p + return P + + +def build_loaf(C, pose="crouch"): + """a rabbit / hare at rest: the loaf - a compact egg, the haunch round at the back over the long flat hind foot, + short straight forelegs, the head up on a short neck, the long ears up (research 16 / animal-098: a rabbit rests + as a loaf). pose "upright" = alert, sitting up on the haunches""" + P = Plan() + P.C, P.pose, P.gait = C, "crouch", "crouch" + T = _trunk(C) + up = pose == "upright" + a = 35 if up else 0 + c0 = V(-.2, .1) + + def Q(u, v): + return rot(V(u, v), c0, a) + T.update(dict(d=.7, B=1.0, cr=.9, uc=.42, ub=-.78)) + P.T = T + P.Hd = C["head"] + P.chest_o = (Q(.12, .52), .34, .42) + P.hip_o = (V(-.35, .44), .43, .45) + for k, (u, v) in dict(withers=(.15, .9), back=(-.1, .97), loin=(-.35, .95), croup=(-.58, .82), + tailroot=(-.76, .5), buttock=(-.78, .32), flank=(-.4, .06), belly=(-.05, .05), + brisket=(.2, .14), chest=(.42, .45), neck_front=(.38, .62)).items(): + setattr(P, k, Q(u, v) if k in ("withers", "back", "chest", "neck_front", "brisket") else V(u, v)) + P.pitch = P.pitch_r = P.pitch_f = 0 + P.pitch_full = 0 + P.off, P.piv = V(0, 0), V(0, 0) + P.X = lambda p: p + legs = {} + fr = Q(.3, .45) + for k, du in (("fn", 0.0), ("ff", .05)): + j = [fr + V(du, 0), V(fr[0] + du + .02, .24), V(fr[0] + du + .03, .1), V(fr[0] + du + .04, .04), + V(fr[0] + du + .12, 0)] + legs[k] = dict(j=j, near=k == "fn", fore=True, L=[.2, .14, .06, .08], short=0.0, planted=True) + for k, du in (("hn", 0.0), ("hf", .04)): + j = [V(-.35 + du, .4), V(-.12 + du, .24), V(-.6 + du, .05), V(-.22 + du, .025), V(-.05 + du, 0)] + legs[k] = dict(j=j, near=k == "hn", fore=False, L=[.3, .5, .38, .17], short=0.0, planted=True) + P.legs = legs + _neck_head(P, C, T, "crouch" if not up else "upright_rabbit") + P.tail_pts = [P.tailroot] + P.tail_w = [C["tail"][1] * .9] + P.tail_kind = "pom" + return P + + +# ================================================================================================ coat +def coat_of(C, inst): + """the coat with the prompt colour (a named colour owns the coat: markings that would fight it go)""" + coat = dict(C["coat"]) + col = getattr(inst, "color", None) + if not col and getattr(inst, "hair", None): + col = {"red": "orange", "blonde": "golden", "brown": "brown", "black": "black", "white": "white", + "gray": "gray", "orange": "orange"}.get(inst.hair) + inst.color = col + if col: + from ..kit import color_of + c = tuple(float(v) for v in color_of(inst)) + lc = .3 * c[0] + .59 * c[1] + .11 * c[2] + if not getattr(inst, "color_explicit", True): + coat["base"] = c + return coat + coat["base"] = c + for k in ("patches", "spots", "saddle", "stripes_off"): + if k in coat and k != "stripes": + coat[k] = None + if coat.get("stripes") is not None and C["name"] not in ("tiger", "zebra"): + coat["stripes"] = None if lc < 70 else tuple(v * .62 for v in c) + if coat.get("belly"): + coat["belly"] = tuple(c[i] * .55 + coat["belly"][i] * .45 for i in range(3)) if lc > 60 else \ + tuple(c[i] * .8 + coat["belly"][i] * .2 for i in range(3)) + if lc < 60 and coat.get("mane"): + coat["mane"] = (20, 18, 20) + if lc > 200 and coat.get("points"): + coat["points"] = None + if lc > 185 and coat.get("mane"): + # a white / grey horse: mane and tail a little darker than the coat, never black + coat["mane"] = tuple(c[i] * .78 + (150, 150, 156)[i] * .22 for i in range(3)) + coat["hoof"] = (90, 84, 80) + if lc < 70 and coat.get("points"): + coat["points"] = None + return coat + + +# ================================================================================================ drawing +def draw(cv, ctx, inst): + """draw the animal into the canvas. False = not ours (the old drawer takes over)""" + name = canon.lookup(inst.concept, getattr(inst, "word", "")) + if name is None or name not in canon.R: + return False + if not K.on("c2d_" + name.replace(" ", "_")): + return False + style = K.style_of(ctx, cv) + sc = getattr(ctx, "scene", None) or {} + if name == "calf" and isinstance(sc, dict): + # "an elephant with her calf": the young of the animal it goes with, not a cow calf + others = [e.get("concept") for e in sc.get("entities", []) if isinstance(e, dict)] + if "elephant" in others: + name = "calf elephant" + text = sc.get("text", "") if isinstance(sc, dict) else "" + seed = (getattr(inst, "k", 0) or 0) * 131 + int(((sc.get("_director") or {}).get("seed", 0)) if isinstance(sc, dict) else 0) + C = canon.resolve(name, seed, cute=(style == "cartoon")) + pose = pose_of(inst, C, text) + # scale from the STANDING animal (a lying animal keeps its body size); detail tier from it + Ps = build_loaf(C) if name == "rabbit" else build_plan(C, "stand") + top = max(Ps.poll[1] + C["head_shape"]["skull"] * C["head"] * .2, 1.0) + .05 + u0s, u1s = _uext(Ps) + s = inst.h / max(top, 1e-3) + bw = getattr(inst, "w", None) or inst.h * inst.info.get("aspect", 1.3) + s = min(s, bw * .98 / max(u1s - u0s, 1e-3)) + if s < 6: + return False + tr = K.tier(s) + if tr <= 1 and style != "cartoon": + # animal-079: small animals carry a bigger head (+0.05-0.1 W), bigger ears and tail + C["head"] *= 1.12 if tr == 1 else 1.22 + C["tail"] = (C["tail"][0], C["tail"][1] * 1.1, C["tail"][2]) + elif s < 64 and style != "cartoon" and C["legs"] == "digi": + # research 20 A6: under ~64 px withers the head is pushed up a little (+0.03-0.05 W) so the face reads + C["head"] *= 1.08 + if s < 100: + # animal-078: at 80-200 px the ears and tail are exaggerated 1.1-1.2x (they carry the species read) + k_, ln_, an_ = C["ears"] + C["ears"] = (k_, ln_ * 1.15, an_) + if name == "rabbit" and pose in ("crouch", "stand", "sit", "lie", "upright", "curl", "lie_sleep"): + P = build_loaf(C, "upright" if pose == "upright" else "crouch") + pose = P.pose + else: + P = build_curl(C) if pose == "curl" else build_plan(C, pose) + import os as _os + if _os.environ.get("C2D_DEBUG"): + print("c2d", name, pose, getattr(inst, "pose", None), (getattr(inst, "attrs", None) or {}), "box", inst.x, inst.y, inst.w, inst.h, "cv", cv.w, cv.h, "s", s, "ext", _uext(Ps)) + f = -1 if getattr(inst, "facing", "right") == "left" else 1 + ground = float(inst.y) + clip = getattr(cv, "clip_y", None) + if clip is not None and pose in ("lie", "lie_sleep", "side", "curl", "sit", "howl", "crouch"): + ground = float(clip) + u0, u1 = _uext(P) + if (u1 - u0) * s > bw * 1.15: + # a stretched pose (gallop, side lying) still fits its box (and so the frame) + s = bw * 1.15 / (u1 - u0) + cx = (u0 + u1) * .5 + ox = float(inst.x) - f * cx * s + + def S(p): + return (ox + f * p[0] * s, ground - p[1] * s) + coat = coat_of(C, inst) + render(cv, ctx, inst, C, P, S, s, f, style, coat, tr, ground) + # landmarks for critic13 (canvas px) + try: + lm = {"kind": "quad", "species": name, "pose": pose, "facing": int(f), "wh_px": float(s), "ground": float(ground), + "res": [int(cv.w), int(cv.h)], + "pts": {k: list(map(float, S(getattr(P, k)))) for k in ("nose", "eye", "poll", "withers", "croup", + "tailroot") if hasattr(P, k)}, + "legs": {k: [list(map(float, S(q))) for q in L["j"]] for k, L in P.legs.items()}} + for k in ("chest", "buttock", "brisket", "belly"): + if hasattr(P, k): + lm["pts"][k] = list(map(float, S(getattr(P, k)))) + inst.c2d = lm + except Exception: + pass + inst.form_skip = not (style == "pixel" and K.on("c2d_pxlight", "0")) + return True + + +def _uext(P): + us = [P.poll[0], P.nose[0], P.croup[0]] + [p[0] for p in P.tail_pts] + for L in P.legs.values(): + us += [p[0] for p in L["j"]] + if hasattr(P, "buttock"): + us.append(P.buttock[0]) + if hasattr(P, "ring"): + c, rx, ry = P.ring + us += [c[0] - rx, c[0] + rx] + return min(us) - .05, max(us) + .05 + + +def _shade_fields(L2, A, groups, kpx, style, far=False, under=None): + """designed value families for one layer: A albedo HxWx3; groups = mask whose shape makes the bands (the whole + form, not the occluded piece); kpx = band width px. Returns rgb, normal""" + l = L2.l2 + m = groups + sh = K.shadow_band(m, l, kpx) + sh = np.maximum(sh, K.shadow_band(m, (0.0, -1.0), kpx * .55) * .85) # the under planes face the ground + lt = K.lit_band(m, l, kpx * .45) + if under is not None: + sh = np.maximum(sh, under) + under = None + if style != "pixel": + sh = K.blur(sh, max(.5, kpx * .12)) + lt = K.blur(lt, max(.5, kpx * .12)) + else: + sh = (sh > .45).astype(np.float32) + lt = (lt > .5).astype(np.float32) + if under is not None: + sh = np.maximum(sh, under) + if far: + sh = np.clip(sh * .6 + .45, 0, 1) + lit, loc, shd = L2.families(A) + if style == "pixel" and _PXL[0]: + # pixel art: the one-light pass (formlight cel bands, contact) lights the drawn albedo from the designed + # normals below, so the colour stays the local colour (far parts one value step down) + lit, loc, shd = A * 1.0, A * 1.0, A * .78 + # line media hatch the darks themselves: keep the shadow family a step lighter and the coat a step higher + # in value so a mid-value coat does not fill in solid black (the line renderers threshold value) + lit, loc, shd = lit * .8 + 51, loc * .8 + 51, (loc * .55 + shd * .45) * .8 + 51 + t_l = (lt * (1 - sh))[..., None] + t_s = sh[..., None] + rgb = loc * (1 - t_s - t_l) + lit * t_l + shd * t_s + if far: + rgb = rgb * .86 + nrm = (L2.n_loc[None, None, :] * (1 - t_s - t_l) + L2.n_lit * t_l + L2.n_sh * t_s) + return rgb, nrm + + +def render(cv, ctx, inst, C, P, S, s, f, style, coat, tr, ground): + _CRISP[0] = style == "pixel" + _PXL[0] = style == "pixel" and K.on("c2d_pxlight", "0") + # ---- the box (canvas px) holding every landmark, padded + pts = [S(p) for p in (P.poll, P.nose, P.withers, P.croup)] + [S(p) for p in P.tail_pts] + for L in P.legs.values(): + pts += [S(q) for q in L["j"]] + if hasattr(P, "ring"): + c, rx, ry = P.ring + pts += [S(c + V(dx, dy)) for dx in (-rx, rx) for dy in (-ry, ry)] + xs = [p[0] for p in pts] + ys = [p[1] for p in pts] + pad = int(s * .9) + 4 + x0, y0 = int(math.floor(min(xs))) - pad, int(math.floor(min(ys))) - pad + x1, y1 = int(math.ceil(max(xs))) + pad, int(math.ceil(max(ys))) + int(s * .2) + 4 + x0, y0 = max(x0, -cv.w), max(y0, -cv.h) + x1, y1 = min(x1, 2 * cv.w), min(y1, 2 * cv.h) + w, h = x1 - x0, y1 - y0 + if w <= 2 or h <= 2: + return + ss = 1 if style == "pixel" and s > 40 else 3 if s < 60 else 2 + if style == "pixel": + ss = 2 + L2 = K.Light2D(ctx) + Hd = P.Hd + d = P.T["d"] + gy, gx = np.mgrid[y0:y1, x0:x1].astype(np.float32) + # local coordinates of every pixel (W units), for marks that move with the animal + U = (gx - (S(V(0, 0))[0])) * f / s + Vv = (ground - gy) / s + + def R_(): + return K.Raster(x0, y0, w, h, ss) + + def SP(p): + return S(p) + acc = np.zeros((h, w, 3), np.float32) + alpha = np.zeros((h, w), np.float32) + part = np.zeros((h, w), np.int16) + zb = np.zeros((h, w), np.float32) + nb = np.zeros((h, w, 3), np.float32) + fd = np.zeros((h, w, 2), np.float32) + base = np.array(coat["base"], np.float32) + haze = float(getattr(inst, "haze", 0) or 0) + hzc = np.array(getattr(ctx, "haze_color", (200, 220, 240)), np.float32) + + body_rgb = [None, None, None] + + def put(m, rgb, nrm, pid, z, fdir=None, line=None, noline=None): + nonlocal acc, alpha + if line is not None: + # an overlap line where this near form lies over a far one (the illustrator's overlap line), not where + # it grows out of its own body mass + ol = K.edge_in(m, 1) * (alpha > .5) * line + if noline is not None: + ol = ol * (noline < .5) + a = m[..., None] + acc = acc * (1 - a) + rgb * a + if line is not None: + acc = acc * (1 - ol[..., None] * .45) + top = m >= .5 + part[top] = pid + zb[top] = z + nb[top] = nrm[top] if nrm.ndim == 3 else nrm + if fdir is not None: + fd[top] = fdir + alpha = alpha + m * (1 - alpha) + + def leg_mask(L, fore): + """the leg as an illustrator draws it: a FRONT edge and a BACK edge offset from the joint chain by per-joint + widths (elbow point and forearm, flat knee, thin cannon with the tendon behind, fetlock knob; the hind leg's + gaskin wedge from the stifle and the hamstring line down to the point of the hock) - the zig-zag of the + chain shows in both edges (animal-024, copy_animals A1)""" + r = R_() + whole = not L["near"] or P.pose in ("lie", "side", "lie_sleep", "sit", "howl", "crouch") + poly, foot_poly, paw = _leg_outline(C, L, fore, whole, P, tr) + r.poly([SP(q) for q in poly]) + if paw is not None: + c_, rx_, ry_, an_ = paw + r.ellipse(SP(c_), max(.8, rx_ * s), max(.7, ry_ * s), -f * an_) + foot = None + if foot_poly is not None: + r.poly([SP(q) for q in foot_poly]) + rf = R_() + rf.poly([SP(q) for q in foot_poly]) + foot = rf.get() + m = r.get() + mn = .9 if style == "pixel" else .7 + if C["cannon"] * s < mn: + # animal-079: a leg is never thinner than ~2 px: thicken a too-thin drawing with its own chain + r2 = R_() + j = [SP(q) for q in L["j"]] + for i in range(0 if whole else 1, 4): + r2.capsule(j[i], j[i + 1], mn, mn) + m = np.maximum(m, r2.get()) + return m, foot + + def paint_leg(k, far): + L = P.legs[k] + fore = k[0] == "f" + m, foot = leg_mask(L, fore) + A = np.broadcast_to(base, (h, w, 3)).copy() + lc = coat.get("legs") + if lc is not None: + A[:] = lc + j = [SP(q) for q in L["j"]] + # points / stockings: the lower leg from just above the carpus / hock (animal-075) + ptc = coat.get("points") + if ptc is not None and ("points" in C["marks"] or "stockings" in C["marks"]): + yb = j[2][1] - (2.5 if "points" in C["marks"] else 6) * s / 60 + if "stockings" in C["marks"]: + yb = j[1][1] + (j[2][1] - j[1][1]) * .35 + t = _q(np.clip((gy - yb) / max(1.0, s * .04), 0, 1)) + A = A * (1 - t[..., None]) + np.array(ptc, np.float32) * t[..., None] + if foot is not None: + hc = np.array(coat.get("hoof", (50, 44, 40)), np.float32) + A = A * (1 - foot[..., None]) + hc * foot[..., None] + if "toenails" in C["marks"] and tr >= 2 and L["j"][-1][1] < .05: + tp = SP(L["j"][-1]) + for dx in (-.06, 0, .06): + q = (tp[0] + f * (dx + .07) * s, tp[1] - .025 * s) + tn = np.clip(1 - np.hypot((gx - q[0]) / max(.8, .025 * s), (gy - q[1]) / max(.6, .018 * s)), 0, 1) * 3 + tn = np.clip(tn, 0, 1) + A = A * (1 - tn[..., None]) + np.array(coat.get("hoof", (170, 160, 150)), np.float32) * tn[..., None] + if "claws" in C["marks"] and tr >= 2 and L["j"][-1][1] < .05 and fore: + tp = SP(L["j"][-1]) + for dx in (-.04, 0, .04): + q = (tp[0] + f * (dx + .1) * s, tp[1] - .01 * s) + cl = np.clip(1 - np.hypot((gx - q[0]) / max(.6, .012 * s), (gy - q[1]) / max(.6, .03 * s)), 0, 1) * 3 + cl = np.clip(cl, 0, 1) + A = A * (1 - cl[..., None]) + np.array(coat.get("claw", (210, 200, 180)), np.float32) * cl[..., None] + if "panda" in C["marks"]: + A[:] = coat.get("patch", (30, 28, 30)) + kpx = max(1.0, _leg_radii(C, fore, s, tr, style)[2] * 1.3) + # under the body the top of the leg sits in the body's cast shadow + bel = SP(P.belly)[1] if hasattr(P, "belly") else 0 + under = np.clip(1 - (gy - bel) / max(2.0, s * .14), 0, 1) * .75 if P.pose not in ("lie", "side", "sit") else None + rgb, nrm = _shade_fields(L2, A, m, kpx, style, far=far, under=under) + if not far and body_rgb[0] is not None: + # where the near leg comes out of the body it takes the body's value field (no 'trousers' seam) + bel = SP(P.belly)[1] if hasattr(P, "belly") else 0 + wb = (np.clip((bel - gy) / max(2.0, s * .1), 0, 1) * (body_rgb[2] > .5))[..., None] + rgb = rgb * (1 - wb) + body_rgb[0] * wb + nrm = nrm * (1 - wb) + body_rgb[1] * wb + z = 2.0 if far else 30.0 + put(m, rgb, nrm, PART["leg"], z, fdir=np.array([0, 1.0]), line=None if far else 1.0, + noline=body_rgb[2] if (not far and body_rgb[2] is not None) else None) + + # ---- contact shadows: every planted foot + a soft body shadow (animal-085), on the ground, not the animal + _contact(cv, ctx, P, S, s, f, style, ground) + # ---- far legs + for k in ("hf", "ff"): + if k in P.legs: + paint_leg(k, True) + # far ear / horn / antler behind the head + hm_far = _ears(C, P, SP, s, R_, far=True) + # ---- tail + def paint_tail(line=None): + tm = _tail_mask(P, SP, s, R_, C) + if tm is not None: + A = np.broadcast_to(base, (h, w, 3)).copy() + if coat.get("mane") is not None and C["tail"][0] in ("hair",): + A[:] = coat["mane"] + if "tail_tip" in C["marks"] and coat.get("tip") is not None: + tip = _tail_tip_mask(P, SP, s, R_, .7) + A = A * (1 - tip[..., None]) + np.array(coat["tip"], np.float32) * tip[..., None] + if C["tail"][0] in ("tuft", "tuftc"): + tc = np.array(coat.get("tuft", coat.get("mane") or tuple(v * .45 for v in coat["base"])), np.float32) + tip = _tail_tip_mask(P, SP, s, R_, .78) + A = A * (1 - tip[..., None]) + tc * tip[..., None] + if C["tail"][0] == "flag" or "tail_white" in C["marks"]: + A[:] = coat.get("tail", coat.get("rump", (240, 236, 228))) + if coat.get("stripes") is not None and C["name"] in ("tiger", "cat", "kitten", "zebra"): + bands = (np.sin((gx + gy) / max(1.5, s * .05)) > .45).astype(np.float32) * tm + A = A * (1 - bands[..., None]) + np.array(coat["stripes"], np.float32) * bands[..., None] + rgb, nrm = _shade_fields(L2, A, tm, max(1.0, s * .03), style) + put(tm, rgb, nrm, PART["tail"], 10.0, fdir=np.array([-f * 1.0, 0]), line=line) + + if P.pose != "curl": + paint_tail() + # ---- body: trunk + neck as ONE form (chest oval, hip oval, barrel; neck crest arc + throat) + bm, nm = _body_masks(P, C, SP, s, f, R_) + body = np.maximum(bm, nm) + A = _body_albedo(C, P, coat, gx, gy, U, Vv, s, f, SP, R_, body, tr, style) + kb = max(1.2, d * s * (.42 if style == "pixel" else .32)) # pixel art: a bolder 3-tone split + rgb, nrm = _shade_fields(L2, A, body, kb, style) + if C["fur"] == "wool": + wm = _wool_mask(P, C, SP, s, f, R_, tr) + body = np.maximum(body, wm) + Aw = np.broadcast_to(np.array(coat["base"], np.float32), (h, w, 3)).copy() + if tr >= 2: + curl = K.vnoise(gx, gy, max(1.5, s * .04), 3) + Aw = Aw * (.9 + .16 * curl[..., None]) + rgb2, nrm2 = _shade_fields(L2, Aw, wm, max(1.2, d * s * .3), style) + rgb = rgb * (1 - wm[..., None]) + rgb2 * wm[..., None] + nrm = nrm * (1 - wm[..., None]) + nrm2 * wm[..., None] + if "udder" in C["marks"] and P.pose in ("stand", "walk", "graze", "trot"): + um = _udder(P, SP, s, R_) + uc = np.array(coat.get("udder", (230, 170, 168)), np.float32) + urgb, unrm = _shade_fields(L2, np.broadcast_to(uc, (h, w, 3)).copy(), um, max(1, s * .03), style) + put(um, urgb, unrm, PART["belly"], 12.0) + body_rgb[0], body_rgb[1], body_rgb[2] = rgb, nrm, body + put(body, rgb, nrm, PART["body"], 15.0, fdir=np.array([-f * 1.0, 0])) + if P.pose == "curl": + # the curl reads by its overlaps: the haunch over the flank, the tail round the front, the head on top + c_, rx_, ry_ = P.ring + r = R_() + r.ellipse(SP(c_ + V(-rx_ * .38, ry_ * .05)), rx_ * .55 * s, ry_ * .85 * s) + hmk = r.get() + rgb2, nrm2 = _shade_fields(L2, A, hmk, kb * .8, style) + put(hmk, rgb2, nrm2, PART["body"], 16.0, line=.7) + paint_tail(line=.8) + # ---- mane (horse crest, lion mane), over the neck under the head + mm = _mane_mask(P, C, SP, s, f, R_, tr) + if mm is not None: + mc = np.array(coat.get("mane") or tuple(v * .5 for v in coat["base"]), np.float32) + A = np.broadcast_to(mc, (h, w, 3)).copy() + if "lion_mane" in C["marks"]: + # the mane lighter (coat colour) round the face, darker toward its edge and down the chest + sc_ = SP(P.skull[0]) + dd = np.hypot(gx - sc_[0], gy - sc_[1]) / max(1.0, P.skull[1] * s * 2.2) + t_ = np.clip(1.2 - dd, 0, 1)[..., None] * .7 + A = A * (1 - t_) + np.array(coat["base"], np.float32) * t_ + if tr >= 3: + st = K.vnoise(gx * .5, gy * 2.0, max(1.5, s * .025), 5) + A = A * (.85 + .3 * st[..., None]) + rgb, nrm = _shade_fields(L2, A, mm, max(1.0, s * .06), style) + put(mm, rgb, nrm, PART["mane"], 18.0, fdir=np.array([0, 1.0])) + # ---- head (skull + muzzle + jaw hull) and the near ear + if hm_far is not None: + # the far ear shows beside the near one (two ears always show unless the head is in pure profile, + # animal-018), a value step darker + eb = coat.get("ear_back") if "ear_backs" in C["marks"] else (coat.get("face") or coat["base"]) + if "panda" in C["marks"]: + eb = coat["patch"] + A = np.broadcast_to(np.array(eb, np.float32), (h, w, 3)).copy() + rgb, nrm = _shade_fields(L2, A, hm_far, max(1.0, s * .03), style, far=True) + put(hm_far, rgb, nrm, PART["ear"], 19.0) + hm = _head_mask(P, SP, s, R_, C) + A = _head_albedo(C, P, coat, gx, gy, SP, s, f, R_, hm) + rgb, nrm = _shade_fields(L2, A, hm, max(1.0, P.skull[1] * s * .5), style) + put(hm, rgb, nrm, PART["head"], 20.0, fdir=np.array([-f * 1.0, 0]), line=.6) + _ears(C, P, SP, s, R_, far=False, put=put, L2=L2, coat=coat, style=style, shape=(h, w), gx=gx, gy=gy) + _horns(C, P, SP, s, f, R_, put, L2, coat, style, (h, w), tr) + if "collar" in C["marks"] and P.pose not in ("curl",) and s >= 14: + # a pet dog's collar: a band round the neck behind the jaw (the old drawers' strongest 'dog' cue) + r = R_() + a = P.poll * .62 + P.withers * .38 + V(0, .02) + b = P.throat * .62 + P.neck_front * .38 - V(0, .02) + r.capsule(SP(a), SP(b), max(.7, .028 * s), max(.7, .028 * s)) + cm = r.get() * np.clip(body_rgb[2] if body_rgb[2] is not None else 1, 0, 1) + cc = np.array(coat.get("collar", (200, 40, 40)), np.float32) + crgb, cnrm = _shade_fields(L2, np.broadcast_to(cc, (h, w, 3)).copy(), cm, max(.8, s * .02), style) + put(cm, crgb, cnrm, 219, 21.0) + # ---- near legs over the body + for k in ("hn", "fn"): + if k in P.legs: + paint_leg(k, False) + # ---- features: eye, nostril, mouth (sized for the pixel size) + acc = _features(acc, alpha, C, P, SP, s, f, style, coat, tr, x0, y0, gx, gy) + # ---- fur strands, last (animal-072/076): only where the pixels can carry them + if tr >= 3 and style in ("paint", "plain") and C["fur"] in ("medium", "shaggy"): + acc = _strands(acc, alpha, part, gx, gy, s, f, C) + if haze > 0: + acc = acc * (1 - haze) + hzc * haze + K.composite(cv, inst, acc, alpha, x0, y0, part=part, z=zb, nrm=nb, fdir=fd, crisp=(style == "pixel")) + + +# per-joint (front, back) half-widths of the leg in W, before the species scale: root, elbow / stifle, mid upper, +# carpus / hock, mid cannon, fetlock, pastern (research 20 copy_animals leg widths: forearm 15-20, cannon 7-9 per +# 100 px W; joints 1.2-1.4x the cannon; Cuyer: the elbow point and the point of the hock stand out behind) +LEGW = { + ("ungul", "f"): [(.1, .1), (.075, .1), (.055, .045), (.04, .038), (.026, .03), (.03, .042), (.026, .03)], + ("ungul", "h"): [(.12, .16), (.05, .2), (.05, .09), (.04, .07), (.026, .034), (.03, .042), (.026, .03)], + ("digi", "f"): [(.09, .09), (.07, .085), (.05, .04), (.036, .032), (.03, .028), (.03, .03), (.028, .028)], + ("digi", "h"): [(.11, .14), (.05, .17), (.05, .08), (.035, .05), (.028, .03), (.028, .03), (.026, .026)], + ("planti", "f"): [(.13, .13), (.11, .12), (.1, .09), (.09, .08), (.085, .08), (.08, .08), (.08, .08)], + ("planti", "h"): [(.14, .16), (.1, .17), (.1, .12), (.09, .09), (.08, .08), (.07, .07), (.07, .07)], + ("pillar", "f"): [(.13, .13), (.12, .12), (.11, .1), (.1, .095), (.1, .095), (.105, .1), (.11, .105)], + ("pillar", "h"): [(.14, .15), (.12, .14), (.11, .11), (.1, .1), (.1, .095), (.105, .1), (.11, .105)], +} +_REF = {"ungul": (.085, .036), "digi": (.07, .042), "planti": (.135, .105), "pillar": (.115, .1)} + + +def _leg_outline(C, L, fore, whole, P, tr): + """(outline polygon, hoof polygon or None, paw ellipse or None) of one leg in local W units""" + typ = C["legs"] + j = [np.asarray(q, float) for q in L["j"]] + W_ = LEGW[(typ, "f" if fore else "h")] + fa0, cn0 = _REF[typ] + ku, kl = C["fore"] / fa0, C["cannon"] / cn0 + # the chain with two shaping points: mid upper (elbow -> carpus) and mid cannon (carpus -> fetlock) + pts = [j[0], j[1], j[1] * .5 + j[2] * .5, j[2], j[2] * .5 + j[3] * .5, j[3], j[3] * .45 + j[4] * .55] + ks = [ku, ku, (ku + kl) * .5, kl, kl, kl, kl] + n = len(pts) + fronts, backs = [], [] + for i in range(n): + a = pts[max(i - 1, 0)] + b = pts[min(i + 1, n - 1)] + d = b - a + dn = np.linalg.norm(d) + 1e-9 + nf = np.array([-d[1], d[0]]) / dn # down -> (+1, 0): the anatomical front + wf, wb = W_[i] + fronts.append(pts[i] + nf * wf * ks[i]) + backs.append(pts[i] - nf * wb * ks[i]) + if not fore and typ != "planti" and hasattr(P, "buttock") and P.pose not in ("sit", "howl", "lie", "side", + "lie_sleep", "crouch", "curl"): + # the gaskin wedge: the back edge runs from the hamstring under the point of buttock down to the hock + T = P.T + ham = P.X(V(T["ub"] + .05, T["cr"] - .38 * T["d"] - .16)) + backs[1] = ham + (V(.03, 0) if not L["near"] else 0) + backs[2] = backs[2] * .5 + (ham * .45 + backs[3] * .55) * .5 + i0 = 0 if whole else 1 + if not fore and P.pose in ("sit", "howl") and typ != "planti": + # sitting: thigh and shank are inside the haunch mass; only the hock, the long foot and the paw show on the + # ground in front of it (animal-036) + i0 = 3 + if not whole and i0 == 1: + # start just inside the body: the leg grows out from under the belly + fronts[1] = fronts[1] + (j[0] - j[1]) * .25 + backs[1] = backs[1] + (j[0] - j[1]) * .25 + poly = K.spline(fronts[i0:], 4) + K.spline(backs[i0:][::-1], 4) + foot, paw = None, None + t, fl = j[4], j[3] + ax = t - fl + an = np.linalg.norm(ax) + 1e-9 + if typ == "pillar": + # an elephant's foot: the pillar ends flat on the ground with toenails (drawn as marks) + return poly, None, None + if typ == "ungul": + # animal-089: the hoof wall at 50-55 deg to the ground, a darker band; flat on the ground when planted + up = -ax / an + nf = np.array([up[1], -up[0]]) + if nf[0] < 0 and L.get("planted"): + nf = -nf + hw = .036 * kl * (1.15 if C["name"] in ("cow", "bull", "bison", "pig") else 1.0) + hh = .055 * kl + top = t + up * hh + if L.get("planted") or t[1] < .02: + foot = [t + V(hw * 1.25, 0), t + V(-hw * .95, 0), top - nf * hw * .75, top + nf * hw * .55] + else: + foot = [t + nf * hw * 1.1, t - nf * hw * .9, top - nf * hw * .75, top + nf * hw * .55] + else: + # a paw: short and flat on the ground, toes forward (animal-025); bigger and clawed on a bear + ln = max(an * .7, .07 if typ == "digi" else .12) + c = fl * .35 + t * .65 + ang = math.degrees(math.atan2(ax[1], ax[0])) + if L.get("planted") or t[1] < .02: + c = V(t[0] - ln * .25, max(t[1], 0) + .03 * kl) + ang = 0 + paw = (c, ln * .62, .033 * kl * (1.25 if typ == "planti" else 1.0), ang) + return poly, foot, paw + + +def _leg_radii(C, fore, s, tr, style): + fa, cn = C["fore"], C["cannon"] + if fore: + r = [fa * 1.45, fa, cn * 1.25, cn * 1.05, cn * .95] + else: + r = [fa * 2.1, fa * 1.25, cn * 1.3, cn * 1.05, cn * .95] + if C["legs"] == "planti": + r = [fa * 1.35, fa, cn * 1.05, cn, cn] if fore else [fa * 1.8, fa * 1.15, cn * 1.05, cn, cn] + out = [v * s for v in r] + mn = .9 if style == "pixel" else .7 # animal-079: legs at least 2 px wide + return [max(mn, v) for v in out] + + +def _contact(cv, ctx, P, S, s, f, style, ground): + col = (30, 32, 40) + L = getattr(ctx, "L", None) + if L is not None: + col = (L.sky[0] * .2 + 10, L.sky[1] * .2 + 10, L.sky[2] * .24 + 14) + a0 = .35 if getattr(ctx, "time", "day") != "night" else .2 + old = cv.cur_id + cv.cur_id = None + try: + for k, L_ in P.legs.items(): + t = L_["j"][-1] + if t[1] < .04: + X, Y = S(t) + rw = max(1.2, P.C["cannon"] * s * 2.6) + cv.ellipse(X + f * rw * .2, ground + .5, rw, max(.8, rw * .3), col, alpha=a0) + if P.pose in ("lie", "side", "sit", "howl", "curl", "lie_sleep", "crouch"): + u0, u1 = _uext(P) + X0, _ = S(V(u0, 0)) + X1, _ = S(V(u1, 0)) + cv.ellipse((X0 + X1) * .5, ground + .5, abs(X1 - X0) * .45, max(1.0, s * .05), col, alpha=a0 * .8) + elif hasattr(P, "buttock") and min(L_["j"][-1][1] for L_ in P.legs.values()) < .05: + # the body's own shadow on the ground under the barrel (animal-085: 0.6-0.8 body length wide) + Xa, _ = S(P.buttock) + Xb, _ = S(P.chest) + cv.ellipse((Xa + Xb) * .5, ground + .5, abs(Xb - Xa) * .38, max(1.0, s * .045), col, alpha=a0 * .55) + finally: + cv.cur_id = old + + +def _body_masks(P, C, SP, s, f, R_): + if P.pose == "curl": + r = R_() + c, rx, ry = P.ring + r.ellipse(SP(c), rx * s, ry * s) + r.ellipse(SP(c + V(-rx * .35, ry * .1)), rx * .62 * s, ry * 1.02 * s) # the haunch, a little higher + nr = R_() + for q in P.paws: + nr.ellipse(SP(q), .07 * s, .035 * s) + return r.get(), nr.get() + T = P.T + r = R_() + (cc, crx, cry), (hc, hrx, hry) = P.chest_o, P.hip_o + rot_ = -f * P.pitch + r.ellipse(SP(cc), crx * s, cry * s, -f * P.pitch_f) + r.ellipse(SP(hc), hrx * s * (C.get("haunch", 1) or 1), hry * s, -f * P.pitch_r) + top = [P.withers, P.back, P.loin, P.croup, P.tailroot] + if "hump" in C["marks"]: + top = [P.X(V(.04, 1.0)), P.X(V(-.08, 1.06)), P.X(V(-.3, 1.0)), P.loin, P.croup, P.tailroot] + if "hips" in C["marks"]: + hook = P.X(P.T["croup"] + V(.12, .015)) + top = [P.withers, P.back, P.loin, hook, P.croup, P.tailroot] + under = [P.buttock, P.flank, P.belly, P.brisket, P.chest] + poly = K.spline([SP(p) for p in top], 6) + K.spline([SP(p) for p in under], 6) + r.poly(poly) + if C["fur"] == "shaggy" and s >= 40: + # a shaggy coat breaks the silhouette on the underside (animal-072): small tufts hanging from the belly line + ul = K.spline([SP(p) for p in under[1:4]], 10) + tl = max(1.2, s * .035) + rr = C["rng"] + for i in range(1, len(ul) - 1, 2): + a, b = np.asarray(ul[i - 1]), np.asarray(ul[i + 1]) + m_ = (a + b) * .5 + np.array([-f * tl * .5, tl * (.4 + .8 * rr.random())]) + r.poly([a, b, m_]) + if P.pose not in ("lie", "side", "lie_sleep", "sit", "howl", "crouch"): + for k, L in P.legs.items(): + if L["near"]: + rad = _leg_radii(C, k[0] == "f", s, 3, "plain") + r.capsule(SP(L["j"][0]), SP(L["j"][1]), rad[0], rad[1]) + bm = r.get() + # neck: crest arc from the withers to the poll, throat line from the throat to the chest front + nr = R_() + W0 = P.withers + (P.X(V(-.06, 1.0)) - P.X(V(0, 1.0))) + Pl = P.poll + v = Pl - W0 + Ln = np.linalg.norm(v) + 1e-6 + nrm = np.array([-v[1], v[0]]) / Ln + if nrm[1] < 0: + nrm = -nrm + arch = {"horse": .1, "donkey": .05, "zebra": .08}.get(C["name"], .04) + crest = [W0 + v * t + nrm * arch * Ln * math.sin(math.pi * t) for t in np.linspace(0, 1, 9)] + thr = P.throat + cf = P.neck_front + mid = (thr + cf) * .5 + vv = cf - thr + out_ = np.array([vv[1], -vv[0]]) / (np.linalg.norm(vv) + 1e-6) + if out_[0] < 0: + out_ = -out_ + sag = .06 if "dewlap" in C["marks"] else .0 + front = [thr, mid + out_ * .05 - np.array([0, sag]), cf] + inner = [P.X(V(P.T["uc"] - .25, 1 - P.T["d"] * .4)), P.X(V(-.1, .97))] + poly = [SP(p) for p in crest] + [SP(P.skull[0])] + [SP(p) for p in K.spline(front, 4)] + [SP(p) for p in inner] + nr.poly(poly) + # a neck thick enough to carry the head: a tube from the withers region to the head + nb0 = (W0 + cf) * .5 + nr.capsule(SP(nb0), SP(P.skull[0]), np.linalg.norm(W0 - cf) * .45 * s, P.skull[1] * s * .95) + return bm, nr.get() + + +def _body_albedo(C, P, coat, gx, gy, U, Vv, s, f, SP, R_, body, tr, style): + h, w = body.shape + base = np.array(coat["base"], np.float32) + A = np.broadcast_to(base, (h, w, 3)).copy() + d = P.T["d"] + # body frame coordinates (undo the trunk pitch and the offset) so marks wrap with the body + a = math.radians(-(P.pitch_r + P.pitch_f) * .5) + qu, qv = U - P.off[0] - P.piv[0], Vv - P.off[1] - P.piv[1] + bu = qu * math.cos(a) - qv * math.sin(a) + P.piv[0] + bv = qu * math.sin(a) + qv * math.cos(a) + P.piv[1] + if coat.get("belly") is not None and ("belly_pale" in C["marks"] or C["legs"] != "ungul") and P.pose != "curl": + # countershading: the belly and the inside of the chest lighter (animal-074) + t = _q(np.clip((1 - d * .62 - bv) / (d * .18), 0, 1)) + A = A * (1 - t[..., None]) + np.array(coat["belly"], np.float32) * t[..., None] + if coat.get("saddle") is not None and "saddle" in C["marks"]: + n = K.vnoise(gx, gy, max(2.0, s * .12), 11) * .12 + t = np.clip((bv - (1 - d * .42) + n) / (d * .08), 0, 1) * np.clip((P.T["uc"] - .02 - bu) / .12, 0, 1) \ + * np.clip((bu - P.T["ub"] - .02) / .1, 0, 1) + t = _q(t) + A = A * (1 - t[..., None]) + np.array(coat["saddle"], np.float32) * t[..., None] + if coat.get("patches") is not None and "patches" in C["marks"]: + # cow patches: big blobs that wrap the barrel (animal-073 markings follow the form) + n = K.vnoise(bu * 3.1, bv * 3.1, 1.0, 17 + int(C["rng"].random() * 50)) + n2 = K.vnoise(bu * 7, bv * 7, 1.0, 23) + t = ((n * .8 + n2 * .2) > .56).astype(np.float32) + A = A * (1 - t[..., None]) + np.array(coat["patches"], np.float32) * t[..., None] + if coat.get("spots") is not None and ("spots" in C["marks"] or "rosettes" in C["marks"]): + if "rosettes" in C["marks"]: + n = K.vnoise(bu / .07, bv / .07, 1.0, 31) + t = ((n > .72) & (n < .8)).astype(np.float32) + else: + # round spots on a jittered grid (dalmatian, cheetah): dots, not blobs + cs = .075 + gu, gv = np.floor(bu / cs), np.floor(bv / cs) + ju = K.hashn(gu, gv, 3) * .6 + .2 + jv = K.hashn(gu, gv, 4) * .6 + .2 + rr = (.18 + .16 * K.hashn(gu, gv, 5)) * cs + dd = np.hypot(bu - (gu + ju) * cs, bv - (gv + jv) * cs) + t = ((dd < rr) & (K.hashn(gu, gv, 6) > .25)).astype(np.float32) + A = A * (1 - t[..., None]) + np.array(coat["spots"], np.float32) * t[..., None] + if coat.get("stripes") is not None and ("stripes" in C["marks"] or "stripes_tiger" in C["marks"] + or "stripes_tabby" in C["marks"]): + # stripes: roughly vertical bands that bend with the body, bigger on the rear (animal-073, Hultgren) + warp = K.vnoise(bu * 4, bv * 4, 1.0, 41) * .5 + per = .11 if "stripes_tiger" in C["marks"] else .085 if "stripes" in C["marks"] else .075 + ph = (bu + warp * .25 + (bv - .5) * .15) / per + band = np.abs(((ph % 1.0) - .5)) * 2 + thick = .3 if "stripes_tiger" in C["marks"] else .45 if "stripes" in C["marks"] else .22 + if "stripes_tabby" in C["marks"]: + band = band + (K.vnoise(bu / .05, bv / .05, 1.0, 9) > .62) * 1.0 # broken mackerel stripes + top_only = (bv > 1 - d * .75) if "stripes_tiger" in C["marks"] else (bv > 0) + t = ((band < thick) & top_only).astype(np.float32) + A = A * (1 - t[..., None]) + np.array(coat["stripes"], np.float32) * t[..., None] + if "rump" in C["marks"] and coat.get("rump") is not None and P.pose != "curl": + rr = np.hypot((bu - (P.T["ub"] + .06)) / .1, (bv - (P.T["cr"] - .15)) / .14) + t = np.clip((1 - rr) * 3, 0, 1) + A = A * (1 - t[..., None]) + np.array(coat["rump"], np.float32) * t[..., None] + if ("bib" in C["marks"] or "throat_pale" in C["marks"]) and coat.get("mask", coat.get("belly")) is not None \ + and P.pose != "curl": + bc = np.array(coat.get("mask") or coat.get("belly"), np.float32) + # the bib: the throat and the front of the chest (fox, animal-055; deer throat patch) + r = R_() + a, b = P.throat - P.n * .02, P.chest + V(-.04, -.12) + if "throat_pale" in C["marks"]: + b = a * .6 + b * .4 + if "bib" in C["marks"]: + r.capsule(SP(a), SP(b), .1 * s, .13 * s) + else: + r.capsule(SP(a), SP(a * .6 + b * .4), .045 * s, .035 * s) + t = r.get() + A = A * (1 - t[..., None]) + bc * t[..., None] + if "panda" in C["marks"]: + t = ((bu > P.T["uc"] - .42) & (bu < P.T["uc"] - .12)).astype(np.float32) + A = A * (1 - t[..., None]) + np.array(coat["patch"], np.float32) * t[..., None] + if "fawn_spots" in C["marks"]: + n = K.vnoise(bu / .05, bv / .05, 1.0, 7) + t = ((n > .8) & (bv > 1 - d * .6)).astype(np.float32) + A = A * (1 - t[..., None]) + np.array((244, 238, 226), np.float32) * t[..., None] + if "shag_front" in C["marks"] and coat.get("front") is not None: + t = np.clip((bu - (P.T["uc"] - .55)) / .1, 0, 1) + A = A * (1 - t[..., None]) + np.array(coat["front"], np.float32) * t[..., None] + return A + + +def _wool_mask(P, C, SP, s, f, R_, tr): + """sheep / poodle wool: an oval mass 1.4-1.6x as long as deep with a scalloped edge (6-10 bumps at 128 px), + hanging to 0.45-0.5 W above the ground (animal-053)""" + r = R_() + T = P.T + d = T["d"] + c0 = P.X(V((T["uc"] + T["ub"]) * .5 - .02, 1 - d * .45)) + rx = (T["uc"] - T["ub"]) * .55 + .06 + ry = d * .62 + .02 + nb = 10 if tr >= 3 else 8 if tr >= 2 else 0 + r.ellipse(SP(c0), rx * s, ry * s, -f * P.pitch) + if nb: + for i in range(nb * 2): + t = 2 * math.pi * i / (nb * 2) + p = c0 + V(rx * math.cos(t), ry * math.sin(t)) + r.circle(SP(p), max(1.0, (ry * .28) * s)) + # the wool runs up the neck to behind the head + r.capsule(SP(c0 + V(rx * .55, ry * .3)), SP(P.skull[0] - P.e * P.skull[1] * .6), ry * s * .6, P.skull[1] * s * 1.1) + return r.get() + + +def _udder(P, SP, s, R_): + r = R_() + T = P.T + c = P.X(V(T["ub"] + .36, 1 - T["d"] - .05)) + r.ellipse(SP(c), .08 * s, .06 * s) + for dx in (-.04, .03): + r.capsule(SP(c + V(dx, -.03)), SP(c + V(dx, -.08)), max(.6, .012 * s), max(.5, .01 * s)) + return r.get() + + +def _mane_mask(P, C, SP, s, f, R_, tr): + if P.pose == "curl": + return None + W0 = P.withers + V(-.04, .0) + Pl = P.poll + if "lion_mane" in C["marks"]: + # the mane is a shaggy mass framing the face, down the neck to the chest and tapering back over the withers + # (animal-098): a ring of overlapping locks round the head + the neck mass + r = R_() + sk, rs = P.skull + c = sk - P.e * rs * .45 - P.n * rs * .15 + R0 = rs * 1.9 + rng = C["rng"] + nb = 18 + for i in range(nb): + t = 2 * math.pi * i / nb + rr = R0 * (.78 + .12 * rng.random()) + r.circle(SP(c + V(math.cos(t) * rr, math.sin(t) * rr)), R0 * s * (.36 + .1 * rng.random())) + r.circle(SP(c), R0 * s * .9) + r.capsule(SP(c), SP(P.neck_front + V(-.04, -.06)), R0 * s * .85, R0 * s * .5) + r.capsule(SP(c), SP(W0 + V(-.12, -.04)), R0 * s * .8, R0 * s * .25) + return r.get() + if not any(k in C["marks"] for k in ("mane", "mane_short", "mane_throat")): + return None + r = R_() + v = Pl - W0 + Ln = np.linalg.norm(v) + 1e-6 + nrm = np.array([-v[1], v[0]]) / Ln + if nrm[1] < 0: + nrm = -nrm + if "mane_throat" in C["marks"]: + th = P.throat + r.capsule(SP(th), SP(P.neck_front), .08 * s, .1 * s) + return r.get() + short = "mane_short" in C["marks"] + wd = (.05 if short else .075) + arch = .1 if C["name"] == "horse" else .05 + outer, inner = [], [] + n = 10 + for i in range(n + 1): + t = i / n + base = W0 + v * t + nrm * arch * Ln * math.sin(math.pi * t) + jag = (.35 if (i % 2 and tr >= 2 and not short) else 0) * wd + outer.append(base + nrm * (wd + jag) * (1 - .4 * t) - (np.array([0, wd * .4]) if not short else 0)) + inner.append(base - nrm * wd * .45) + if not short: + # the horse mane falls on the near side of the crest: hanging strands + for i in range(n + 1): + outer[i] = outer[i] - np.array([0, .0]) + r.poly([SP(p) for p in outer] + [SP(p) for p in inner[::-1]]) + if not short: + # forelock between the ears + fl = P.poll + P.e * .12 * P.Hd + r.capsule(SP(P.poll), SP(fl - P.n * .1 * P.Hd), .035 * s, .02 * s) + return r.get() + + +def _head_mask(P, SP, s, R_, C): + r = R_() + (sc, rs), (mc, rm), (jc, rj) = P.skull, P.muzzle, P.jaw + r.circle(SP(sc), rs * s) + r.capsule(SP(sc), SP(mc), rs * s * .92, rm * s) + r.capsule(SP(jc), SP(mc), rj * s, rm * s * .95) + r.circle(SP(jc), rj * s) + r.capsule(SP(sc), SP(jc), rs * s * .9, rj * s) + if "snout" in C["marks"]: + tip = P.nose + P.e * rm * .3 + r.capsule(SP(mc), SP(tip), rm * s, rm * s * 1.05) + if "trunk" in C["marks"]: + # the trunk hangs from the muzzle almost to the ground, tapering, the tip curling forward + M = P.muzzle[0] + rm = P.muzzle[1] + lo = max(.08, M[1] - P.Hd * 1.5) + pts = [M, M + V(.03, -(M[1] - lo) * .35), M + V(.05, -(M[1] - lo) * .7), V(M[0] + .08, lo + .02), + V(M[0] + .13, lo + .05)] + if P.pose in ("lie", "lie_sleep", "sit"): + pts = [M, M + V(.08, -.08), M + V(.18, -.12), M + V(.26, -.1)] + r.tube([SP(q) for q in pts], [rm * s * 1.05, rm * s * .8, rm * s * .62, rm * s * .48, rm * s * .4]) + if "beard" in C["marks"]: + b0 = P.jaw[0] + P.e * P.Hd * .35 - P.n * rj * .7 + r.poly([SP(b0), SP(b0 + P.e * .12 * P.Hd), SP(b0 - P.n * .28 * P.Hd + P.e * .02 * P.Hd)]) + return r.get() + + +def _head_albedo(C, P, coat, gx, gy, SP, s, f, R_, hm): + h, w = hm.shape + base = coat.get("face") or coat["base"] + A = np.broadcast_to(np.array(base, np.float32), (h, w, 3)).copy() + mz = coat.get("muzzle") + if mz is not None and any(k in C["marks"] for k in ("muzzle_pale", "muzzle_pink", "mask_pale", "panda")) \ + or (mz is not None and C["legs"] == "planti"): + r = R_() + mc, rm = P.muzzle + r.circle(SP(mc), rm * s * 1.1) + r.capsule(SP(mc), SP(P.nose), rm * s, rm * s * .8) + m = r.get() + A = A * (1 - m[..., None]) + np.array(mz, np.float32) * m[..., None] + if ("mask_pale" in C["marks"] or "bib" in C["marks"]) and coat.get("mask") is not None: + # cheeks and the lower jaw pale: the fox / wolf / husky mask + r = R_() + jc, rj = P.jaw + # the pale cheek: the lower half of the jowl running into the throat, the lower lip of the muzzle + r.capsule(SP(jc - P.n * rj * .35), SP(P.throat), rj * s * .8, rj * s * .8) + m = r.get() + A = A * (1 - m[..., None]) + np.array(coat["mask"], np.float32) * m[..., None] + if "stripes_tiger" in C["marks"] and coat.get("stripes") is not None: + sc, rs = P.skull + c = SP(sc) + band = (np.abs(np.sin((gx - c[0]) / max(1.0, rs * s * .35))) > .85) & (gy < c[1]) + A = A * (1 - band[..., None]) + np.array(coat["stripes"], np.float32) * band[..., None] + if "panda" in C["marks"]: + r = R_() + r.ellipse(SP(P.eye), P.Hd * .13 * s, P.Hd * .09 * s, -f * 30) + m = r.get() + A = A * (1 - m[..., None]) + np.array(coat["patch"], np.float32) * m[..., None] + if "mask_bandit" in C["marks"]: + r = R_() + r.capsule(SP(P.eye - P.e * .1 * P.Hd), SP(P.eye + P.e * .12 * P.Hd), P.Hd * .1 * s, P.Hd * .07 * s) + m = r.get() + A = A * (1 - m[..., None]) + np.array(coat["mask"], np.float32) * m[..., None] + if "snout" in C["marks"]: + r = R_() + tip = P.nose + P.e * P.muzzle[1] * .3 + ang_ = math.degrees(math.atan2(P.e[1], P.e[0])) + r.ellipse(SP(tip), P.muzzle[1] * s * .32, P.muzzle[1] * s * 1.05, -f * ang_) + m = r.get() + A = A * (1 - m[..., None]) + np.array(coat.get("nose", (220, 140, 140)), np.float32) * .78 * m[..., None] + for dn in (.35, -.35): + q = SP(tip + P.n * P.muzzle[1] * dn) + nm = np.clip((1 - np.hypot(gx - q[0], gy - q[1]) / max(.6, P.muzzle[1] * s * .2)) * 3, 0, 1) * m + A = A * (1 - nm[..., None] * .8) + np.array((110, 60, 60), np.float32) * nm[..., None] * .8 + return A + + +def _ear_polys(C, P, far): + kind, ln, back = C["ears"] + Hd = P.Hd + L = ln * Hd + n, e = P.n, P.e + b = P.ear_base + (e * .14 * Hd if far else 0) + if kind == "elephant": + if far: + return [("poly", [b + n * .08 * Hd, b - e * .25 * L + n * .1 * Hd, b - e * .2 * L - n * .3 * L])] + q = [b + e * .05 * L + n * .06 * Hd, b - e * .45 * L + n * .1 * Hd, b - e * .75 * L - n * .25 * L, + b - e * .7 * L - n * .75 * L, b - e * .4 * L - n * 1.05 * L, b - e * .05 * L - n * .85 * L, + b + e * .1 * L - n * .4 * L] + return [("poly", K.spline(q, 4, closed=True))] + if kind in ("horse", "prick", "cat", "deer", "long", "rabbit", "round"): + tilt = math.radians(back + ((22 if kind in ("rabbit", "long", "deer") else 8) if far else 0)) + dirn = n * math.cos(tilt) - e * math.sin(tilt) + wd = {"horse": .13, "prick": .17, "cat": .2, "deer": .2, "long": .15, "rabbit": .16, "round": .13}[kind] * Hd + side = e * math.cos(tilt) + n * math.sin(tilt) + tip = b + dirn * L + if kind == "round": + return [("circle", b + dirn * L * .4, L * .55)] + if kind in ("deer", "long", "rabbit"): + return [("poly", [b - side * wd * .5, b + dirn * L * .5 - side * wd * .62, tip, b + dirn * L * .55 + side * wd * .6, + b + side * wd * .5])] + return [("poly", [b - side * wd * .55, tip, b + side * wd * .55])] + if kind in ("side", "cow"): + # horizontal ears out to the side; in profile they point back-out from below the horn line + dirn = -e * .9 - n * .25 + dirn /= np.linalg.norm(dirn) + wd = .13 * Hd + sidev = np.array([-dirn[1], dirn[0]]) + bb = b - n * .08 * Hd + return [("poly", [bb - sidev * wd * .4, bb + dirn * L * .55 - sidev * wd * .65, bb + dirn * L, bb + dirn * L * .55 + sidev * wd * .6, + bb + sidev * wd * .4])] + if kind in ("drop", "fold", "rose"): + # a flap hanging beside the skull (dog) + bb = b - e * .02 * Hd + if kind == "rose": + return [("poly", [bb, bb - e * L * .8 + n * .05 * Hd, bb - e * L * .4 - n * .1 * Hd])] + if kind == "fold": + return [("poly", [bb, bb + n * L * .35 + e * L * .2, bb + e * L * .55 - n * .05 * Hd])] + dn = -n * .95 - e * .1 + wd = .2 * Hd + return [("poly", [bb - e * wd * .4, bb + e * wd * .5, bb + dn * L + e * wd * .35, bb + dn * L * 1.02 - e * wd * .2])] + if kind == "flop_fwd": + bb = b - e * .04 * Hd + return [("poly", [bb - e * .1 * Hd + n * .02 * Hd, bb + n * .22 * Hd + e * .12 * Hd, bb + e * .5 * Hd - n * .14 * Hd, + bb + e * .18 * Hd - n * .1 * Hd])] + return [] + + +def _ears(C, P, SP, s, R_, far, put=None, L2=None, coat=None, style=None, shape=None, gx=None, gy=None): + if P.pose == "curl" and far: + return None + polys = _ear_polys(C, P, far) + if not polys: + return None + r = R_() + for kind, *a in polys: + if kind == "poly": + r.poly([SP(p) for p in a[0]]) + else: + r.circle(SP(a[0]), a[1] * s) + m = r.get() + if put is None: + # far ear: stored, painted with the head layer below it (darker) + return m + h, w = shape + base = coat.get("face") or coat["base"] + if "ear_backs" in C["marks"] and coat.get("ear_back") is not None: + base = coat["ear_back"] + elif coat.get("ear") is not None: + base = coat["ear"] + if "panda" in C["marks"]: + base = coat["patch"] + A = np.broadcast_to(np.array(base, np.float32), (h, w, 3)).copy() + rgb, nrm = _shade_fields(L2, A, m, max(1.0, s * .03), style) + put(m, rgb, nrm, PART["ear"], 22.0) + return m + + +def _horns(C, P, SP, s, f, R_, put, L2, coat, style, shape, tr): + h, w = shape + mk = C["marks"] + Hd = P.Hd + e, n = P.e, P.n + top = P.poll + e * .05 * Hd + hc = np.array(coat.get("horn", (220, 210, 186)), np.float32) + r = R_() + any_ = False + if "horns" in mk and P.pose != "curl": + # cow horns: out-forward-up from the poll, short (animal-090) + L = .32 * Hd * (1.4 if C["name"] == "bull" else 1.0) + a = top + n * .02 * Hd + b = a + n * L * .55 + e * L * .5 + c = b + n * L * .45 - e * L * .05 + r.tube([SP(a), SP(b), SP(c)], [.055 * Hd * s, .04 * Hd * s, max(.5, .015 * Hd * s)]) + any_ = True + if "horns_short" in mk: + a = top + r.tube([SP(a), SP(a + n * .12 * Hd + e * .08 * Hd)], [.05 * Hd * s, .02 * Hd * s]) + any_ = True + if "horns_back" in mk: + a = top + e * .05 * Hd + pts = [a] + for i in range(1, 6): + t = i / 5 + pts.append(a + n * .35 * Hd * math.sin(t * 1.4) - e * .35 * Hd * (1 - math.cos(t * 1.6))) + r.tube([SP(p) for p in pts], [max(.5, (.06 - .045 * i / 5) * Hd * s) for i in range(6)]) + any_ = True + if ("antlers" in mk or "antlers_big" in mk or "palmate" in mk) and P.pose != "curl": + # stag antlers 0.8-1.4 head high, a main beam up and back with tines forward (animal-054, 090) + big = 1.25 if "antlers_big" in mk else 1.0 + H = (1.1 if "palmate" not in mk else .7) * Hd * big + a = top - e * .02 * Hd + beam = [a] + for i in range(1, 7): + t = i / 6 + beam.append(a + n * H * t - e * H * .32 * math.sin(t * 2.2) + e * H * .18 * t * t) + wd = [max(.6, (.045 - .03 * i / 6) * Hd * s) for i in range(7)] + if "palmate" in mk: + # moose: a broad palm spreading back and up from a short beam, tines along its upper rim + Hm = Hd * 1.0 + n, e = V(0, 1.0), V(float(np.sign(e[0]) or 1), 0) # the palm spreads back and out, not up the face + pal = [a + n * .12 * Hm, a + n * .25 * Hm - e * .3 * Hm, a + n * .3 * Hm - e * .85 * Hm] + for i in range(6): + t = i / 5 + base_ = a + n * (.42 + .2 * math.sin(t * math.pi)) * Hm - e * (.85 - 1.05 * t) * Hm + pal.append(base_) + pal.append(base_ + n * .14 * Hm - e * .03 * Hm) + pal.append(base_ - e * .07 * Hm) + pal += [a + n * .3 * Hm + e * .3 * Hm, a + n * .1 * Hm + e * .1 * Hm] + r.poly([SP(q) for q in pal]) + hc = np.array(coat.get("antler", (196, 172, 136)), np.float32) + m = r.get() + A = np.broadcast_to(hc, (h, w, 3)).copy() + rgb, nrm = _shade_fields(L2, A, m, max(.8, s * .02), style) + put(m, rgb, nrm, PART["horn"], 24.0, line=.6) + return + r.tube([SP(p) for p in beam], wd) + for i, frac in ((1, .55), (3, .45), (5, .35)): + q = beam[i] + tip = q + e * H * frac * .55 + n * H * frac * .45 + r.capsule(SP(q), SP(tip), wd[i] * .9, max(.5, wd[i] * .45)) + # the far antler a little forward + beam2 = [p + e * .1 * Hd for p in beam] + r.tube([SP(p) for p in beam2], [v * .85 for v in wd]) + any_ = True + hc = np.array(coat.get("antler", (196, 172, 136)), np.float32) + if "tusks" in mk and P.pose != "curl": + M = P.muzzle[0] + a = M - n * P.muzzle[1] * .2 - e * P.muzzle[1] * .6 + pts = [a, a + V(.06, -.1), a + V(.15, -.14), a + V(.22, -.1)] + r.tube([SP(p) for p in pts], [.035 * Hd * s * 1.2, .03 * Hd * s, .022 * Hd * s, max(.5, .01 * Hd * s)]) + hc = np.array(coat.get("tusk", (236, 228, 206)), np.float32) + any_ = True + if not any_: + return + m = r.get() + A = np.broadcast_to(hc, (h, w, 3)).copy() + rgb, nrm = _shade_fields(L2, A, m, max(.8, s * .015), style) + put(m, rgb, nrm, PART["horn"], 24.0) + + +def _tail_mask(P, SP, s, R_, C): + pts = P.tail_pts + if not pts: + return None + r = R_() + sp = [SP(p) for p in pts] + rad = [max(.6, wv * s) for wv in P.tail_w] + if C["tail"][0] == "pom": + r.circle(sp[0], rad[0]) + return r.get() + if C["tail"][0] in ("tuft", "tuftc"): + r.tube(sp, rad) + r.ellipse(sp[-1], max(1.0, .035 * s), max(1.2, .06 * s)) + return r.get() + r.tube(sp, rad) + return r.get() + + +def _tail_tip_mask(P, SP, s, R_, frac): + pts = P.tail_pts + n = len(pts) + i0 = int(n * frac) + r = R_() + r.tube([SP(p) for p in pts[i0:]], [max(.7, wv * s * 1.05) for wv in P.tail_w[i0:]]) + if P.tail_kind in ("tuft", "tuftc"): + r.ellipse(SP(pts[-1]), max(1.0, .04 * s), max(1.3, .065 * s)) + return r.get() + + +def _features(acc, alpha, C, P, SP, s, f, style, coat, tr, x0, y0, gx, gy): + """eye, nostril, mouth: clean symbols sized for the pixel size (animal-077..080, 095)""" + Hd = P.Hd + ex, ey = SP(P.eye) + er = {"cat": .085, "kitten": .1, "lion": .06, "tiger": .06, "leopard": .065, "bear": .045, "polar bear": .045, + "rabbit": .09, "deer": .075, "fawn": .085, "horse": .06, "cow": .065, "sheep": .055, "pig": .045, + "fox": .065, "wolf": .06}.get(C["name"], .065) * Hd * s + dark = np.array((22, 18, 18), np.float32) + closed = P.pose in ("curl", "lie_sleep") + if er < .7: + # tiny: one dark pixel on the head's mid line (animal-079) + X, Y = int(round(ex - x0)), int(round(ey - y0)) + if 0 <= Y < acc.shape[0] and 0 <= X < acc.shape[1] and not closed: + acc[Y, X] = acc[Y, X] * .3 + dark * .7 + return acc + if closed: + m = ((np.abs(gy - ey - er * .3) < max(.5, er * .25)) & (np.abs(gx - ex) < er * 1.1)).astype(np.float32) + acc = acc * (1 - m[..., None] * .8) + dark * m[..., None] * .8 + return acc + rr = np.hypot((gx - ex) / max(er, .6), (gy - ey) / max(er * .85, .6)) + iris = coat.get("eye") + m = np.clip((1 - rr) * er * 1.5, 0, 1) + if iris is not None and er >= 2.0: + acc = acc * (1 - m[..., None]) + np.array(iris, np.float32) * m[..., None] + pr = np.hypot((gx - ex) / max(er * (.35 if C["name"] in ("cat", "kitten", "panther") else .55), .6), + (gy - ey) / max(er * .8, .6)) + pm = np.clip((1 - pr) * er, 0, 1) + acc = acc * (1 - pm[..., None]) + dark * pm[..., None] + else: + acc = acc * (1 - m[..., None]) + dark * m[..., None] + if er >= 2.5: + # big eyes get the lid: a dark arc over the top, the brow shadow (animal-076: lid + highlight at 600 px+) + ring = np.abs(np.hypot((gx - ex) / (er * 1.25), (gy - ey + er * .15) / (er * 1.05)) - 1) < (.6 / er + .08) + lid = (ring & (gy < ey - er * .1)).astype(np.float32) + acc = acc * (1 - lid[..., None] * .55) + dark * lid[..., None] * .55 + if er >= 1.6 and style != "pixel" or er >= 2.5: + hx, hy = ex + f * er * .3, ey - er * .35 + hm = np.clip((1 - np.hypot(gx - hx, gy - hy) / max(.6, er * .3)) * 2, 0, 1) + acc = acc * (1 - hm[..., None] * .85) + np.array((250, 250, 245), np.float32) * hm[..., None] * .85 + # nostril and mouth line at mid sizes and up + if tr >= 2 and "snout" not in C["marks"]: + nx, ny = SP(P.nose - P.e * P.muzzle[1] * .35 + P.n * P.muzzle[1] * .25) + nr_ = max(.6, P.muzzle[1] * s * .28) + nm = np.clip((1 - np.hypot((gx - nx) / nr_, (gy - ny) / (nr_ * .7))) * 2, 0, 1) + nc = np.array(coat.get("nose", (40, 30, 30)), np.float32) + if C["legs"] != "ungul" or C["name"] in ("pig",): + nc = np.array(coat.get("nose", (30, 24, 24)), np.float32) + nm = np.clip((1 - np.hypot((gx - nx) / (nr_ * 1.3), (gy - ny) / (nr_ * 1.0))) * 2, 0, 1) + acc = acc * (1 - nm[..., None] * .8) + nc * nm[..., None] * .8 + if tr >= 3 and P.pose == "howl": + pass + return acc + + +def _strands(acc, alpha, part, gx, gy, s, f, C): + """short hair strokes along the fur direction (animal-072, 076: 2-6 px at the biggest sizes), darker in the + shadow, as value breaks - never before the shapes read""" + sc = max(1.5, s * .012) + nb = K.vnoise(gx * .35, gy * 2.2, sc, 77) # body, mane, tail: hair lies back along the body + nl = K.vnoise(gx * 2.2, gy * .35, sc, 78) # legs: hair runs down the leg (animal-073) + amp = .1 if C["fur"] == "shaggy" else .06 + body = np.isin(part, [PART["body"], PART["mane"], PART["tail"], PART["head"]]) & (alpha > .5) + legs = (part == PART["leg"]) & (alpha > .5) + k = 1 + (nb - .5) * 2 * amp * body + (nl - .5) * 2 * amp * .7 * legs + return acc * k[..., None] diff --git a/pydraw/figure/__init__.py b/pydraw/figure/__init__.py index 3fbc0d91dbadd2287ca1f201b795b72eb94a95ab..aa25bd8a64a784494ed349705235fb9617edd0c8 100644 --- a/pydraw/figure/__init__.py +++ b/pydraw/figure/__init__.py @@ -173,6 +173,10 @@ def render_figure(text, style="pixel", size=512, seed=0, framing=None, variant=N img = np.asarray(img) if img.dtype != np.uint8: img = (np.clip(img, 0, 1) * 255 + .5).astype(np.uint8) if img.max() <= 1.0 else np.clip(img, 0, 255).astype(np.uint8) + from .face import active as _fx_active + if _fx_active("fx_attr"): # wave 20 faces lane: hats, helmets, scarves, freckles (fx_face, default OFF) + from .attire import render as _attire + img = _attire(np.ascontiguousarray(img[..., :3]), fig, style, variant) if img.shape[0] != size: img = resize_to(img[..., :3], size, nearest=(style == "pixel")) return img[..., :3], fig diff --git a/pydraw/figure/__pycache__/__init__.cpython-310.pyc b/pydraw/figure/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed40f103624fb20d11a646afa78dcdf263fd458 Binary files /dev/null and b/pydraw/figure/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/attire.cpython-310.pyc b/pydraw/figure/__pycache__/attire.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1014151bd5167347a8c115d436b39ddf6bc80fb4 Binary files /dev/null and b/pydraw/figure/__pycache__/attire.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/body.cpython-310.pyc b/pydraw/figure/__pycache__/body.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed48209d08ab428db02006d20db7bc7cf5e1b7f3 Binary files /dev/null and b/pydraw/figure/__pycache__/body.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/body_canon.cpython-310.pyc b/pydraw/figure/__pycache__/body_canon.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8fd520df0386ec89482514832cbd631cf95a2d1 Binary files /dev/null and b/pydraw/figure/__pycache__/body_canon.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/body_draw.cpython-310.pyc b/pydraw/figure/__pycache__/body_draw.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7888d200c2f04affdf6b381c674118d29ef69276 Binary files /dev/null and b/pydraw/figure/__pycache__/body_draw.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/body_pose.cpython-310.pyc b/pydraw/figure/__pycache__/body_pose.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..518f1630f8b3d0b1526b0cd765d5e3f7937cbffd Binary files /dev/null and b/pydraw/figure/__pycache__/body_pose.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/canon.cpython-310.pyc b/pydraw/figure/__pycache__/canon.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81fb96c4279e5e4ef78305f4c011b8562dbae18b Binary files /dev/null and b/pydraw/figure/__pycache__/canon.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/design.cpython-310.pyc b/pydraw/figure/__pycache__/design.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9222ba4105bf0296b0f01f469b4203b90a7b6d41 Binary files /dev/null and b/pydraw/figure/__pycache__/design.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/face.cpython-310.pyc b/pydraw/figure/__pycache__/face.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acacc4b3d1e03a6459661a617a2d0e2af74e6a4a Binary files /dev/null and b/pydraw/figure/__pycache__/face.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/face_apply.cpython-310.pyc b/pydraw/figure/__pycache__/face_apply.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c22829067830f0b022e16efe6511b6a8047b8cc Binary files /dev/null and b/pydraw/figure/__pycache__/face_apply.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/flat.cpython-310.pyc b/pydraw/figure/__pycache__/flat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57715646ed3bb99557ea28b2b099cd92803fd581 Binary files /dev/null and b/pydraw/figure/__pycache__/flat.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/hairlayout.cpython-310.pyc b/pydraw/figure/__pycache__/hairlayout.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..861f8b29fc574dd99c037c781d4b300174a53ee2 Binary files /dev/null and b/pydraw/figure/__pycache__/hairlayout.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/kit.cpython-310.pyc b/pydraw/figure/__pycache__/kit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c31f3e277e483ed3486bc49be76cfa7cd2772ee6 Binary files /dev/null and b/pydraw/figure/__pycache__/kit.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/layout.cpython-310.pyc b/pydraw/figure/__pycache__/layout.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7329f06c8d739318a0d758e27c6aeaf776940d4c Binary files /dev/null and b/pydraw/figure/__pycache__/layout.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/paint2.cpython-310.pyc b/pydraw/figure/__pycache__/paint2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42f8572d43d3d3d674f4ed4d30cfafeb4a4b9c38 Binary files /dev/null and b/pydraw/figure/__pycache__/paint2.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/style_anime.cpython-310.pyc b/pydraw/figure/__pycache__/style_anime.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6ee60df54e113b895537470747050552f8711c8 Binary files /dev/null and b/pydraw/figure/__pycache__/style_anime.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/style_paint.cpython-310.pyc b/pydraw/figure/__pycache__/style_paint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e8cd9872f1107c9782762b779edbaa09521c75b Binary files /dev/null and b/pydraw/figure/__pycache__/style_paint.cpython-310.pyc differ diff --git a/pydraw/figure/__pycache__/value.cpython-310.pyc b/pydraw/figure/__pycache__/value.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7832052856f945ee41fa5786a3af028f86ae42a9 Binary files /dev/null and b/pydraw/figure/__pycache__/value.cpython-310.pyc differ diff --git a/pydraw/figure/attire.py b/pydraw/figure/attire.py new file mode 100644 index 0000000000000000000000000000000000000000..e373ece9a3b58ce8941e1a993b89b1319d17e1c3 --- /dev/null +++ b/pydraw/figure/attire.py @@ -0,0 +1,481 @@ +"""figure.attire: costume and attribute words that survive the portrait path (wave 20, faces lane; knob fx_attr under +fx_face): hats and helmets, scarves, freckles. Pure code. + +Built on the kit layout's 3D head frame (L.proj: canon head frame -> px), so every style gets the same object in the +same place, then drawn in that style's marks as the LAST layer at the work size (WAVE20 method 6-7): + hats human-393: the band encloses the cranium (front 0.30-0.38 H below the crown, tilting 10-20 deg down to the + back), the crown rises 0.1-0.3 H over the skull (caps, fedoras; more for top hats and pointed hats), brim + widths by kind (visor 0.4-0.5 H forward, fedora 0.2-0.3 H, sun hat 0.5-1 H); the brim casts a shadow band + over the eyes; hair above the band and outside the hat is cleared (the common failure: a hat perched on top + with the skull outline above the band). + helmet a knight's open-faced helmet: the dome over the cranium, cheek and neck guards to the jaw, a face opening + from the brows down and a nasal bar (Norman / bascinet family), steel with a designed highlight. + scarf a wrapped band round the neck base with folds and one hanging tail. + freckles small warm dots over the nose bridge and upper cheeks (never a texture over the whole face). +""" +import math +import re +import numpy as np +from . import face as F +from . import kit as K + +HAT_WORDS = [ + (r"\b(?:knight|armou?r(?:ed)?|helmet(?:ed)?|crusader|templar|paladin|centurion|viking)\b", "helmet"), + (r"\b(?:top hat)\b", "tophat"), (r"\b(?:witch)\b", "witch"), (r"\b(?:wizard|sorcerer|mage)\b", "wizard"), + (r"\b(?:cowboy|cowgirl|stetson)\b", "cowboy"), (r"\b(?:straw hat|sun ?hat|sombrero|wide[- ]brimmed hat)\b", "sunhat"), + (r"\b(?:beanie|woolly hat|wool hat|knit(?:ted)? (?:hat|cap)|toque|bobble hat)\b", "beanie"), + (r"\b(?:sailor hat|sailor cap|sailor)\b", "sailor"), (r"\b(?:captain|pilot|conductor|police(?:man|woman)?|officer)\b", "peaked"), + (r"\b(?:baseball cap|cap)\b", "cap"), (r"\b(?:fedora|trilby|detective)\b", "fedora"), + (r"\b(?:crown|king|queen|princess|prince|tiara)\b", "crown"), (r"\b(?:hat)\b", "fedora"), +] +HAT_COL = {"helmet": (0.62, 0.64, 0.68), "tophat": (0.12, 0.12, 0.14), "witch": (0.16, 0.13, 0.20), + "wizard": (0.22, 0.24, 0.52), "cowboy": (0.55, 0.38, 0.22), "sunhat": (0.86, 0.74, 0.46), + "beanie": (0.70, 0.22, 0.20), "sailor": (0.95, 0.95, 0.94), "peaked": (0.14, 0.17, 0.30), + "cap": (0.20, 0.32, 0.62), "fedora": (0.30, 0.26, 0.22), "crown": (0.90, 0.72, 0.22)} +COLW = {"red": (.72, .16, .14), "blue": (.20, .32, .66), "navy": (.12, .16, .34), "green": (.20, .45, .25), + "black": (.10, .10, .12), "white": (.94, .94, .92), "grey": (.50, .50, .52), "gray": (.50, .50, .52), + "brown": (.42, .28, .18), "yellow": (.92, .78, .22), "purple": (.40, .22, .52), "pink": (.90, .52, .62), + "orange": (.90, .48, .16), "gold": (.88, .70, .22), "golden": (.88, .70, .22), "silver": (.75, .76, .78), + "beige": (.82, .74, .60), "tan": (.70, .56, .38), "plaid": (.66, .20, .18), "striped": (.20, .28, .58)} + + +def parse(text): + t = " " + " ".join(re.findall(r"[a-z0-9'\-]+", (text or "").lower())) + " " + out = {} + if not re.search(r"\b(?:no hat|without a hat|hatless|bareheaded|bare-headed)\b", t): + for pat, kind in HAT_WORDS: + if re.search(pat, t): + out["hat"] = kind + break + if out.get("hat"): + m = re.search(r"\b(%s)\s+(?:[\w-]+\s+)?(?:hat|cap|beanie|helmet|fedora|crown|top hat|bonnet)\b" % "|".join(COLW), t) + out["hat_col"] = COLW[m.group(1)] if m else HAT_COL[out["hat"]] + if re.search(r"\b(?:scarf|scarves|muffler|bandana|neckerchief|kerchief)\b", t): + out["scarf"] = True + m = re.search(r"\b(%s)\s+(?:[\w-]+\s+)?(?:scarf|muffler|bandana|neckerchief)\b" % "|".join(COLW), t) + out["scarf_col"] = COLW[m.group(1)] if m else None + if out.get("hat") == "sailor" and out["scarf_col"] is None: + out["scarf_col"] = COLW["navy"] + if re.search(r"\b(?:freckles|freckled|freckle)\b", t): + out["freckles"] = True + return out + + +# ------------------------------------------------------------------------------------------------- geometry (px) +def _ring(L, y_front, drop, rx, rz, n=48, y_off=0.0): + """a band ring round the head (head frame), front height y_front, dropping `drop` toward the back""" + th = np.linspace(0, 2 * np.pi, n, endpoint=False) + c = L.cranium_c + x = c[0] + rx * np.sin(th) + z = c[2] + rz * np.cos(th) + y = y_front - drop * (1 - np.cos(th)) / 2 + y_off + return np.stack([x, y, z], 1).astype(np.float32), th + + +def _hull_px(P): + from .layout import _hull + h = _hull(np.asarray(P, float) * np.array([1, -1])) * np.array([1, -1]) + return h + + +def hat_shapes(L, kind, lift): + """the hat as px polygons in draw order: list of (name, poly, role) with role 'back' (behind the crown), 'crown', + 'front' (in front of the crown), plus the band polyline (front arc) for the brim shadow / hair clearing""" + r = L.cranium_r + c = L.cranium_c + top_y = c[1] + r[1] # skull top (head frame, the crown is ~0.5) + rxs, rzs = r[0] * 1.04 + lift * 0.55, r[2] * 1.02 + lift * 0.55 + band_front = 0.5 - {"beanie": 0.40, "helmet": 0.36, "crown": 0.22, "sailor": 0.24, "tophat": 0.31, + "witch": 0.32, "wizard": 0.30}.get(kind, 0.31) + drop = math.radians(15) * (2 * r[2]) # 10-20 deg tilt toward the back (human-393) + if kind == "crown": + drop *= 0.4 + ring, th = _ring(L, band_front, drop, rxs, rzs) + out = [] + crown_h = {"cap": 0.10, "peaked": 0.16, "sailor": 0.05, "fedora": 0.24, "cowboy": 0.26, "sunhat": 0.12, + "beanie": 0.06, "tophat": 0.55, "witch": 0.85, "wizard": 0.95, "crown": 0.0, "helmet": 0.06}[kind] + brim = {"cap": 0.0, "peaked": 0.0, "sailor": 0.0, "fedora": 0.26, "cowboy": 0.42, "sunhat": 0.62, "beanie": 0.0, + "tophat": 0.20, "witch": 0.42, "wizard": 0.12, "crown": 0.0, "helmet": 0.0}[kind] + P = L.proj + zf = lambda Q: L.projz(Q) + # the crown: the skull-hugging dome lifted + the crown height (cone for pointed hats, cylinder for top hats) + up = [] + for ph in np.linspace(0.05, np.pi / 2, 7): + for t in th[::2]: + x = c[0] + rxs * math.cos(ph) * math.sin(t) + z = c[2] + rzs * math.cos(ph) * math.cos(t) + y0 = band_front - drop * (1 - math.cos(t)) / 2 + y = y0 + (top_y + lift * (0.8 if kind != "beanie" else 0.35) - y0) * math.sin(ph) ** (0.8 if kind != "beanie" else 0.6) + up.append((x, y, z)) + up = np.array(up, np.float32) + if kind in ("tophat",): + cyl = ring.copy() * np.array([0.9, 1, 0.9], np.float32) + np.array([0, 0, 0], np.float32) + cyl[:, 0] = c[0] + (ring[:, 0] - c[0]) * 0.9 + topr = cyl.copy() + topr[:, 1] = top_y + crown_h + topr[:, 0] = c[0] + (ring[:, 0] - c[0]) * 0.95 + crown3 = np.vstack([cyl, topr]) + elif kind in ("witch", "wizard"): + tip = np.array([[c[0] + 0.06 * L.light_side * 0, top_y + crown_h, c[2] - 0.12]], np.float32) + crown3 = np.vstack([ring, up[up[:, 1] < top_y - 0.1], tip]) + else: + sq = up.copy() + sq[:, 1] = np.where(sq[:, 1] > band_front, sq[:, 1] + crown_h * np.clip((sq[:, 1] - band_front) / max(1e-3, top_y - band_front), 0, 1), sq[:, 1]) + crown3 = np.vstack([ring, sq]) + crown = _hull_px(P(crown3)) + # brims: a flat ring in the band plane (back half drawn first, front half last) + if brim > 0: + outer, _ = _ring(L, band_front, drop * 0.7, rxs + brim, rzs + brim, n=64) + if kind == "cowboy": # the sides turn up + outer[:, 1] += 0.10 * np.abs(np.sin(np.linspace(0, 2 * np.pi, 64, endpoint=False))) ** 2 + if kind == "sunhat": + outer[:, 1] -= 0.06 * (1 + np.cos(np.linspace(0, 2 * np.pi, 64, endpoint=False))) / 2 # front droops + # the brim tips forward 12 deg (front down) so its top plane shows as an ellipse, not an edge-on line + th64_ = np.linspace(0, 2 * np.pi, 64, endpoint=False) + outer[:, 1] -= math.tan(math.radians(9)) * (rzs + brim) * np.cos(th64_) * 0.8 + ring_in, _ = _ring(L, band_front, drop * 0.7, rxs, rzs, n=64) + ring_in[:, 1] -= math.tan(math.radians(9)) * rzs * np.cos(th64_) * 0.8 + po, pi = P(outer), P(ring_in) + disk = np.vstack([po, po[:1]]) + zo = zf(outer) + out.append(("brim_back", K.crv(po, closed=True, n=4), "back")) + front = zo > np.median(zo) + idx = np.where(front)[0] + if len(idx) > 3: + # the front half of the brim: the outer arc and the inner arc, a crescent in front of the crown + th64 = np.linspace(0, 2 * np.pi, 64, endpoint=False) + sel = np.cos(th64) > 0.0 + order = np.argsort(np.where(th64 > np.pi, th64 - 2 * np.pi, th64)) + order = [i for i in order if sel[i]] + fr = np.vstack([po[order], pi[order][::-1]]) + out.append(("brim_front", fr, "front")) + out.append(("crown", K.crv(crown, closed=True, n=4) if kind not in ("witch", "wizard") else crown, "crown")) + # visors (caps): a flat sector forward of the band, tilted down 10 deg + if kind in ("cap", "peaked"): + vs = [] + for t in np.linspace(-0.85, 0.85, 15): + x = c[0] + (rxs + 0.02) * math.sin(t) + z = c[2] + (rzs + 0.02) * math.cos(t) + vs.append((x, band_front - 0.01, z)) + for t in np.linspace(0.85, -0.85, 15): + x = c[0] + (rxs + 0.02) * math.sin(t) * 0.95 + z = c[2] + (rzs + 0.02 + (0.42 if kind == "cap" else 0.24)) * math.cos(t) ** 0.6 + vs.append((x, band_front - 0.06 - 0.05 * math.cos(t), z)) + out.append(("visor", P(np.array(vs, np.float32)), "front")) + if kind == "sailor": # the rolled, upturned brim: a band standing round the crown + lo, _ = _ring(L, band_front - 0.02, drop, rxs + 0.03, rzs + 0.03) + hi, _ = _ring(L, band_front + 0.09, drop, rxs + 0.06, rzs + 0.06) + zl = zf(lo) + th48 = np.linspace(0, 2 * np.pi, 48, endpoint=False) + order = [i for i in np.argsort(np.where(th48 > np.pi, th48 - 2 * np.pi, th48)) if math.cos(th48[i]) > -0.15] + out.append(("roll", np.vstack([P(lo)[order], P(hi)[order][::-1]]), "front")) + if kind == "crown": # points rising from the band + pts = [] + hi_y = band_front + 0.16 + for i, t in enumerate(np.linspace(-1.3, 1.3, 13)): + x = c[0] + rxs * math.sin(t) + z = c[2] + rzs * math.cos(t) + y = band_front - drop * (1 - math.cos(t)) / 2 + pts.append((x, y + (0.16 if i % 2 == 0 else 0.07), z)) + base = [(c[0] + rxs * math.sin(t), band_front - drop * (1 - math.cos(t)) / 2 - 0.03, c[2] + rzs * math.cos(t)) + for t in np.linspace(1.3, -1.3, 13)] + out = [("crownband", P(np.array(pts + base, np.float32)), "front")] + th0 = np.linspace(-1.2, 1.2, 20) + band = P(np.array([(c[0] + rxs * math.sin(t), band_front - drop * (1 - math.cos(t)) / 2, c[2] + rzs * math.cos(t)) + for t in th0], np.float32)) + return out, band + + +def helmet_shapes(L, lift): + """a knight's open-faced helmet (dome + cheek and neck guards + face opening + nasal bar) as px polygons""" + r, c = L.cranium_r, L.cranium_c + cn = L.canon + yf = lambda f: 0.5 - f + rx, rz = r[0] * 1.08 + lift * 0.5, r[2] * 1.05 + lift * 0.5 + pts = [] + for ph in np.linspace(-0.2, np.pi / 2, 9): + for t in np.linspace(0, 2 * np.pi, 36, endpoint=False): + pts.append((c[0] + rx * math.cos(ph) * math.sin(t), c[1] + (r[1] + lift * 0.7 + 0.04) * math.sin(ph), + c[2] + rz * math.cos(ph) * math.cos(t))) + jaw_y = yf(cn["mouth_y"] + 0.06) + for s in (-1, 1): # cheek guards and the back to the nape + for y in np.linspace(yf(cn["brow_y"]), jaw_y, 6): + for t in np.linspace(0.55, 2.6, 8): + pts.append((c[0] + s * rx * 1.02 * math.sin(t), y, c[2] + rz * math.cos(t) * 0.98)) + shell = _hull_px(L.proj(np.array(pts, np.float32))) + fz = 0.42 + hw = cn["face_w"] / 2 + opening = [(-hw * 0.62, yf(cn["brow_y"] - 0.07), fz), (-hw * 0.30, yf(cn["brow_y"] - 0.09), fz + 0.06), + (hw * 0.30, yf(cn["brow_y"] - 0.09), fz + 0.06), (hw * 0.62, yf(cn["brow_y"] - 0.07), fz), + (hw * 0.66, yf(cn["nose_y"]), fz - 0.06), (hw * 0.56, jaw_y - 0.06, fz - 0.10), + (hw * 0.45, -0.62, fz - 0.15), (-hw * 0.45, -0.62, fz - 0.15), + (-hw * 0.56, jaw_y - 0.06, fz - 0.10), (-hw * 0.66, yf(cn["nose_y"]), fz - 0.06)] + # the face opening from the layout's own 2D landmarks (a 3D ring at one depth slides off a turned face) + pt, Hh = L.pt, L.H + up = np.array([0, -1.0]) + bR, bL = np.asarray(L.brows["R"], float), np.asarray(L.brows["L"], float) + eo = {s: np.asarray(L.eyes[s]["outer"], float) for s in ("L", "R")} + ck = {s: np.asarray(pt["cheekbone_" + s], float) for s in ("L", "R")} + ja = {s: np.asarray(pt["jaw_angle_" + s], float) for s in ("L", "R")} + side = {s: (eo[s] * 0.45 + ck[s] * 0.55) for s in ("L", "R")} + chin = np.asarray(pt["chin"], float) + mcL, mcR = np.asarray(pt["mouth_L"], float), np.asarray(pt["mouth_R"], float) + op = np.array([bR[-1] + up * 0.07 * Hh, bR[0] + up * 0.09 * Hh, bL[0] + up * 0.09 * Hh, bL[-1] + up * 0.07 * Hh, + side["L"], (mcL * 0.5 + ja["L"] * 0.5), chin - up * 0.10 * Hh, (mcR * 0.5 + ja["R"] * 0.5), + side["R"]], np.float32) + nasal = L.proj(np.array([(-0.03, yf(cn["brow_y"] - 0.08), fz + 0.07), (0.03, yf(cn["brow_y"] - 0.08), fz + 0.07), + (0.022, yf(cn["nose_y"] - 0.02), 0.52), (-0.022, yf(cn["nose_y"] - 0.02), 0.52)], np.float32)) + brow_band = L.proj(np.array([(c[0] + rx * 1.01 * math.sin(t), yf(cn["brow_y"] - 0.10), c[2] + rz * 1.01 * math.cos(t)) + for t in np.linspace(-1.5, 1.5, 24)], np.float32)) + return shell, op, nasal, brow_band + + +# --------------------------------------------------------------------------------------------------- drawing +def _bg_estimate(img): + """per-row linear blend of the left and right border colours (flat or graded grounds)""" + a = img.astype(np.float32) + H, W = a.shape[:2] + l = a[:, 1:3].mean(1) + r = a[:, W - 3:W - 1].mean(1) + t = np.linspace(0, 1, W)[None, :, None] + return l[:, None, :] * (1 - t) + r[:, None, :] * t + + +def _shade(m, L, k=0.10): + """designed shadow: the part of the mask NOT covered by itself shifted toward the light""" + S = m.shape[0] + dx = int(round(-L.light_side * k * L.H)) + dy = int(round(0.04 * L.H)) + sh = np.zeros_like(m) + ys, xs = slice(max(0, dy), S), slice(max(0, dx), S + min(0, dx)) + yd, xd = slice(0, S - max(0, dy)), slice(max(0, -dx), S - max(0, dx)) + sh[ys, xs] = m[yd, xd] + return np.clip(m - sh, 0, 1) + + +def _medium(style, variant): + v = (variant or "").lower() + if style == "ink": + return "pencil" if v in ("pencil", "graphite", "sketch", "charcoal") else "pen" + return style + + +def render(img, fig, style, variant=None): + """draw the attributes over a finished portrait at the layout size (img HxWx3 uint8) -> uint8""" + if not F.active("fx_attr"): + return img + A = parse(fig.text) + if not A: + return img + L = fig.layout + S = int(L.size) + if img.shape[0] != S: + return img + a = img.astype(np.float32) / 255.0 + med = _medium(style, variant) + rng = np.random.default_rng(int(fig.seed) * 977 + 5) + ink = np.array([0.14, 0.12, 0.16]) if style != "pixel" else np.array([16, 16, 28]) / 255.0 + aa = style != "pixel" + lw = max(1.0, 0.009 * L.H) if style == "anime" else max(0.8, 0.006 * L.H) + if med == "pen" or med == "pencil": + lw = max(0.8, 0.005 * L.H) + lift = float(getattr(L, "hair_lift", 0.06) or 0.06) + if fig.person.hair_style in ("bald", "buzz"): + lift = 0.0 + paper = _bg_estimate(img) / 255.0 + + def put(m, colr, alpha=1.0): + mm = np.clip(m, 0, 1)[..., None] * alpha + a[:] = a * (1 - mm) + np.asarray(colr, np.float32)[None, None, :] * mm + + def body(m, base, shine=True, hatchdir=1): + """fill + designed shadow + highlight in the style's terms""" + if style == "pixel": + m = (m > 0.5).astype(np.float32) + if med in ("pen", "pencil"): + pm = np.clip(m, 0, 1)[..., None] + a[:] = a * (1 - pm) + paper * pm + sh = _shade(m, L) + v = 0.55 if med == "pen" else 0.45 + Y, X = np.mgrid[0:S, 0:S] + sp = max(2.5, 0.022 * L.H) + hat = ((X * 0.7 + Y * hatchdir * 0.7) % sp) < max(0.9, sp * 0.28) + put(sh * hat, ink, v) + if np.mean(base) < 0.35: # a dark material: a second, crossed layer + hat2 = ((X * 0.7 - Y * hatchdir * 0.7) % sp) < max(0.9, sp * 0.25) + put(m * hat2, ink, v * 0.8) + return + sh = _shade(m, L) + base = np.asarray(base, np.float32) + dark = base * np.array([0.62, 0.64, 0.72]) if np.mean(base) > 0.2 else base * 0.6 + 0.02 + if style == "paint": + m = K.blur(m, max(0.6, 0.006 * L.H)) + sh = K.blur(sh, max(1.0, 0.02 * L.H)) + put(m, base) + put(sh * (m > 0.02), dark, 0.95 if style != "paint" else 0.8) + if shine and style in ("anime", "paint", "pixel"): + lit = np.clip(m - np.roll(m, int(round(L.light_side * 0.05 * L.H)), axis=1), 0, 1) + lit = lit * np.clip(m, 0, 1) * (1 - sh) + put(lit * (np.roll(m, int(round(0.08 * L.H)), axis=0) > 0.5), np.clip(base * 1.25 + 0.12, 0, 1), + 0.8 if style != "paint" else 0.5) + + def outline(m, wmul=1.0): + if style == "paint": + return + if style == "pixel": + b = m > 0.5 + ring = b & ~(np.roll(b, 1, 0) & np.roll(b, -1, 0) & np.roll(b, 1, 1) & np.roll(b, -1, 1)) + put(ring.astype(np.float32), ink) + return + from scipy import ndimage + b = m > 0.5 + d_in = ndimage.distance_transform_edt(b) + line = np.clip(lw * wmul + 0.5 - d_in, 0, 1) * (m > 0.02) + put(line, ink, 0.95 if med != "pencil" else 0.7) + + def mask(P): + return K.shape_mask(np.asarray(P, np.float32), S, S, aa) + + # ---- hats + hk = A.get("hat") + if hk == "helmet": + shell, op, nasal, bb = helmet_shapes(L, lift) + ms = mask(K.crv(shell, closed=True, n=4)) + mo = mask(K.crv(op, closed=True, n=4)) + mh = np.clip(ms - mo, 0, 1) + # hair outside the shell above the brow line goes (the helmet hides it) + _clear_above(a, img, L, ms, float(np.max(op[:, 1])) - 0.35 * L.H, paper) + col = np.asarray(A.get("hat_col", HAT_COL["helmet"]), np.float32) + body(mh, col) + mn = mask(nasal) + body(mn, col * 1.05) + outline(mh) + outline(mn, 0.8) + if style != "pixel": + bl = K.stroke_mask(bb, max(1.0, 0.012 * L.H), S, S) + put(bl * mh, col * 0.55, 0.7 if med not in ("pen", "pencil") else 0.5) + for t in np.linspace(0.1, 0.9, 6): # rivets along the brow band + q = bb[int(t * (len(bb) - 1))] + r_ = max(0.8, 0.012 * L.H) + put(mask(K.ellipse(q, r_, r_, n=10)) * mh, col * 0.45 if med not in ("pen", "pencil") else ink, .9) + # the face opening casts a shadow band under the helmet's rim onto the brow + _brim_shadow(a, L, op[:4], style, 0.06) + elif hk: + shapes, band = hat_shapes(L, hk, lift) + col = np.asarray(A["hat_col"], np.float32) + hm = np.zeros((S, S), np.float32) + for name, P, role in shapes: + hm = np.maximum(hm, mask(P)) + _clear_above(a, img, L, hm, float(np.max(band[:, 1])), paper) + for name, P, role in shapes: + m = mask(P) + c_ = col + if name in ("roll",): + c_ = np.clip(col * 0.96, 0, 1) + if name == "brim_back": + c_ = col * 0.8 + body(m, c_, shine=(name in ("crown", "crownband")), hatchdir=1 if role != "front" else -1) + outline(m) + if name == "crown" and hk == "beanie": # the folded cuff and a few knit ribs + cuff = K.stroke_mask(band - np.array([0, 0.035 * L.H], np.float32), max(1.5, 0.08 * L.H), S, S) * m + if style == "pixel": + cuff = (cuff > 0.5).astype(np.float32) + put(cuff, col * 0.8 if med not in ("pen", "pencil") else ink, 0.9 if med not in ("pen", "pencil") else 0.3) + if style != "pixel": + for t in np.linspace(0.1, 0.9, 9): + q = band[int(t * (len(band) - 1))] + put(K.stroke_mask(np.array([q - [0, 0.07 * L.H], q], np.float32), max(0.8, 0.006 * L.H), S, S) * m, + col * 0.6 if med not in ("pen", "pencil") else ink, 0.6) + if name == "crown" and hk in ("fedora", "tophat", "cowboy", "sunhat", "peaked"): + bandc = (0.12, 0.10, 0.10) if np.mean(col) > 0.3 else (0.55, 0.12, 0.12) + bl = K.stroke_mask(band, max(1.5, 0.05 * L.H), S, S) * m + if style == "pixel": + bl = (bl > 0.5).astype(np.float32) + put(bl, bandc if med not in ("pen", "pencil") else ink, 0.9 if med not in ("pen", "pencil") else 0.55) + if hk in ("cap", "peaked", "fedora", "cowboy", "sunhat", "tophat", "witch"): + _brim_shadow(a, L, band, style, 0.10 if hk != "sunhat" else 0.2) + # ---- scarf + if A.get("scarf"): + col = A.get("scarf_col") + if col is None: + col = [COLW["red"], COLW["green"], COLW["blue"], COLW["yellow"], COLW["plaid"]][int(rng.integers(0, 5))] + for name, P in scarf_shapes(L, rng): + m = mask(P) + body(m, np.asarray(col, np.float32), shine=False, hatchdir=-1) + outline(m, 0.8) + # ---- freckles (pixel draws its own from the words) + if A.get("freckles") and style != "pixel": + _freckles(a, L, rng, style, med, put, mask) + return (np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8) + + +def _clear_above(a, img, L, hm, band_y, paper): + """hair above the band and outside the hat goes back to the ground (the hat holds the hair)""" + S = a.shape[0] + Y, X = np.mgrid[0:S, 0:S] + xs = np.nonzero(hm.max(0) > 0.5)[0] + if not len(xs): + return + x0, x1 = xs.min() - 0.18 * L.H, xs.max() + 0.18 * L.H + diff = np.abs(img.astype(np.float32) / 255.0 - paper).max(2) > 0.06 + reg = (Y < band_y) & (X > x0) & (X < x1) & (hm < 0.5) & diff + a[reg] = paper[reg] + + +def _brim_shadow(a, L, band, style, depth): + """the brim's cast shadow: a soft band just under the hat's front edge over the brow / eyes (human-393)""" + S = a.shape[0] + face = K.shape_mask(np.asarray(L.face, np.float32), S, S, True) + band = np.asarray(band, np.float32) + lo = band + np.array([0, depth * L.H], np.float32) + poly = np.vstack([band, lo[::-1]]) + m = K.shape_mask(poly, S, S, True) + if style != "pixel": + m = K.blur(m, max(1.0, 0.02 * L.H)) + else: + m = (m > 0.5).astype(np.float32) + k = (m * face)[..., None] * (0.22 if style != "ink" else 0.12) + a[:] = a * (1 - k) + a * 0.55 * k + + +def scarf_shapes(L, rng): + """a wrapped band round the neck base (two bulging folds) and one hanging tail on the side away from the face""" + pt = L.pt + H = L.H + nR, nL = np.asarray(pt["neck_base_R"], float), np.asarray(pt["neck_base_L"], float) + pit = np.asarray(pt["pit"], float) + w = np.linalg.norm(nL - nR) + up = np.array([0, -1.0]) + c = (nR + nL) / 2 + top = np.array([nR + (nR - c) * 0.25 + up * 0.10 * H, c + up * 0.02 * H, nL + (nL - c) * 0.25 + up * 0.10 * H]) + bot = np.array([nL + (nL - c) * 0.35 - up * 0.10 * H, pit - up * 0.12 * H, nR + (nR - c) * 0.35 - up * 0.10 * H]) + wrap = K.crv(np.vstack([top, bot]), closed=True, n=8) + fold = K.crv(np.array([nR + (nR - c) * 0.3 - up * 0.02 * H, c - up * 0.06 * H, nL + (nL - c) * 0.3 - up * 0.01 * H, + nL + (nL - c) * 0.32 - up * 0.08 * H, c - up * 0.13 * H, nR + (nR - c) * 0.32 - up * 0.08 * H]), + closed=True, n=6) + side = 1.0 if L.yaw <= 0 else -1.0 # the tail hangs on the far side of the turn... on the near chest side + root = c + np.array([side * w * 0.22, 0.05 * H]) + spine = np.array([root, root + np.array([side * 0.04 * H, 0.45 * H]), root + np.array([side * 0.02 * H, 0.95 * H])]) + tail = K.ribbon(spine, 0.30 * H, 0.26 * H, tip="flat")[0] + return [("tail", tail), ("wrap", wrap), ("fold", fold)] + + +def _freckles(a, L, rng, style, med, put, mask): + pt = L.pt + H = L.H + face = mask(L.face) + n = int(rng.integers(16, 26)) + nr = np.asarray(pt["nose_root"], float) + nb = np.asarray(pt["nose_base"], float) + ys = [] + skin = a[int(np.clip(nb[1] - 0.05 * H, 0, a.shape[0] - 1)), int(np.clip(nb[0], 0, a.shape[1] - 1))].copy() + col = skin * np.array([0.74, 0.62, 0.55]) if med not in ("pen", "pencil") else np.array([0.2, 0.18, 0.2]) + for i in range(n): + side = -1 if i % 2 else 1 + e = np.asarray(pt["eye_L" if side > 0 else "eye_R"], float) + u = rng.uniform(-0.15, 1.0) # from the bridge (u<0.2) out over the cheek + q = nr + (e - nr) * u * 1.1 + np.array([0, (0.10 + 0.10 * rng.random()) * H]) + if u < 0.2: + q = nr + (nb - nr) * rng.uniform(0.2, 0.7) + np.array([rng.normal(0, 0.03 * H), 0]) + r = max(0.6, H * rng.uniform(0.0045, 0.008)) + put(mask(K.ellipse(q, r, r * 0.9, n=8)) * face, col, 0.55 if med not in ("pen", "pencil") else 0.5) diff --git a/pydraw/figure/body.py b/pydraw/figure/body.py new file mode 100644 index 0000000000000000000000000000000000000000..06a66da21788d3e997b8ea6ece1cf015bdce203a --- /dev/null +++ b/pydraw/figure/body.py @@ -0,0 +1,458 @@ +"""pydraw.figure.body: full human figures drawn 2D-first (wave 20, body lane; knob body2d, default OFF). + +Public API (for the contact lane and critic13): + C = body.canon(style, age, sex, build, px, seed) body_canon.canon (head units, ranges by seed) + pose = body.pose_for(name, act, seed, **over) body_pose: names = POSES, acts = ACTS + B = body.pose_body(C, pose, x, y_feet, stature_px, facing, targets=None, seat=None) + -> body_pose.Body: B.J landmarks in canvas px (crown head chin neck_top neck chest waist pelvis back + sh_n/f el_n/f wr_n/f hand_n/f tip_n/f hip_n/f kn_n/f an_n/f heel_n/f toe_n/f), B.s px per head, + B.claim() (verb, act, J, H, heads_tall, support, knee / elbow flexion, lean, bend, com) + targets: {'hand_near': (x, y), 'hand_far': (x, y), 'foot_near'/'foot_far': (x, y)} solved by 2-bone IK + with the bend signs kept (elbows down / back, knees forward); seat: (x, y) of the seat surface + layer = body.draw(B, look, style, light=..., pixel=...) body_draw.render -> Layer (C, A, P) + body.figure_image(...) a standalone figure on a plain ground (sheets, tests) +Scene hook: concepts/people.draw_person calls draw_scene_person(cv, ctx, inst, locals()) when PYDRAW_EXP body2d=1; +it returns False (old drawer) for what it does not build. When it draws it sets inst.hand / inst.hand2 (palms), +inst.head (as the old drawers expect), inst.body2d (the Body) and inst.body2d_claim (the claim dict). +""" +import math +import os +import numpy as np + +from .body_canon import canon, age_years, srng +from .body_pose import pose_for, solve, screen_ik, verb_from_text, POSES, ACTS, Body +from . import body_draw + +LAST = [] # claims of the figures drawn in this process (bench/body_measure.py, critic13) + +__all__ = ["canon", "pose_for", "pose_body", "draw", "figure_image", "draw_scene_person", "POSES", "ACTS"] + + +def knob(name, default="0"): + for kv in os.environ.get("PYDRAW_EXP", "").split(","): + if "=" in kv: + k, v = kv.split("=", 1) + if k.strip() == name: + return v.strip() + return default + + +def pose_body(C, pose, x, y_feet, stature_px, facing=1, targets=None, seat=None, ground_y=None): + B = solve(C, pose) + B.facing = 1 if facing >= 0 else -1 + s = stature_px / C["N"] + J3 = B.J3 + if seat is not None and pose.meta.get("ground") == "seat": + # the ischia on the seat surface: the hip joints sit a quarter of the pelvis depth above it (phys-015) + hip_u = J3["pelvis"][1] + y0 = seat[1] + (hip_u - C["hip_d"] * .3) * s + B.project(0, y0, s) + dx = seat[0] - B.J["pelvis"][0] + B.project(dx, y0, s) + gy = ground_y if ground_y is not None else y_feet + if gy is not None: + for sd in ("n", "f"): + an = B.J["an_" + sd] + kn = B.J["kn_" + sd] + reach = C["shin"] * s + # a seat higher than the knee: the shin hangs plumb and the foot dangles (never a straight diagonal + # leg reaching for a far floor); a low seat: the foot is planted on the ground (phys-015) + tgt = (kn[0] + (an[0] - kn[0]) * .3, min(gy - C["ankle_h"] * s, kn[1] + reach * .98)) + if tgt[1] > kn[1] + reach * .3: + screen_ik(B, "f" + sd, tgt) + else: + B.project(0, y_feet, s) + # centre: standing figures on the support (pelvis over the feet) at x + if pose.meta.get("ground") in ("feet", "knee"): + ref = (B.J["an_n"][0] + B.J["an_f"][0]) / 2 if pose.meta.get("support") != "far" else B.J["an_f"][0] + ref = ref * .5 + B.J["pelvis"][0] * .5 + else: + ref = B.J["pelvis"][0] + B.project(x - ref, y_feet, s) + for key, limb in (("hand_near", "n"), ("hand_far", "f"), ("foot_near", "fn"), ("foot_far", "ff")): + t = (targets or {}).get(key) + if t is not None: + screen_ik(B, limb, t) + return B + + +def draw(B, look, style="paint", light=(-.6, -.65), sky=(150, 190, 240), key=(255, 248, 235), night=False, pixel=False): + return body_draw.render(B, look, style, light, sky, key, night, pixel) + + +DEFAULT_LOOK = dict(skin=(228, 184, 150), top=(70, 110, 170), bottom=(60, 58, 70), shoes=(60, 42, 34), hair=(70, 46, 32), + style="short", sleeves=True) + + +def look_for(seed, sex="m", age=30, **over): + """a plausible look for standalone sheets (the scene hook takes draw_person's own WHO decisions instead)""" + r = srng(seed, "look", sex, age) + skins = [(244, 210, 182), (228, 184, 150), (198, 150, 112), (160, 112, 80), (112, 76, 54)] + hairs = [(30, 24, 22), (70, 46, 32), (120, 80, 44), (200, 160, 100), (150, 60, 30)] + tops = [(70, 110, 170), (170, 60, 55), (90, 130, 80), (220, 190, 120), (120, 90, 140), (230, 228, 220), (60, 70, 90)] + bots = [(60, 58, 70), (70, 90, 130), (120, 100, 80), (40, 40, 46), (150, 130, 100)] + L = dict(skin=r.choice(skins), hair=r.choice(hairs), top=r.choice(tops), bottom=r.choice(bots), + shoes=r.choice([(60, 42, 34), (30, 28, 30), (120, 80, 50)]), sleeves=r.random() < .6, + style=("short" if sex == "m" else r.choice(["long", "pony", "bun", "long"]))) + if sex == "f" and r.random() < .45: + L["skirt"] = True + L["bottom"] = r.choice([(150, 60, 70), (60, 80, 140), (90, 110, 70), (60, 58, 70)]) + if age >= 60: + L["hair"] = r.choice([(200, 200, 205), (170, 170, 175), (235, 235, 235)]) + if sex == "m" and age >= 25 and r.random() < .3: + L["beard"] = True + L.update(over) + return L + + +def figure_image(name="stand", act=None, style="paint", size=512, stature=None, seed=0, sex="m", age=30, + build="normal", look=None, facing=1, bg=(206, 214, 200), ground=(150, 160, 120), book=False, chibi=False): + """a standalone figure on a plain two-tone ground (sheets / tests): HxWx3 uint8 and the Body""" + pixel = style == "pixel" + W = size // 2 if pixel else size + from .body_canon import stature_k + stature = (stature or size * .7 * stature_k(age)) / (2 if pixel else 1) + C = canon(style, age, sex, build, stature, seed, chibi=chibi, book=book) + pose = pose_for(name, act, seed) + gy = W * .88 + seat = None + if pose.meta.get("ground") == "seat": + seat = (W * .5, gy - (C["ankle_h"] + C["shin"] + .1) * stature / C["N"]) # seat at knee height (human-090) + B = pose_body(C, pose, W * .5, gy, stature, facing, seat=seat, ground_y=gy) + lk = look or look_for(seed, sex, age) + L = draw(B, lk, style, pixel=pixel) + img = np.zeros((W, W, 3), np.float32) + img[:] = bg + img[int(gy) - 2:] = ground + if seat is not None: + # a plain stool under the seat so the sitter reads + x0, x1 = int(seat[0] - stature * .12), int(seat[0] + stature * .12) + img[int(seat[1]):int(seat[1] + stature * .03), max(0, x0):x1] = (110, 80, 55) + for xx in (x0 + 2, x1 - 4): + img[int(seat[1]):int(gy), max(0, xx):max(0, xx) + max(2, int(stature * .015))] = (95, 68, 48) + # contact shadow (human-477 / scale.md G1) + ys, xs = np.mgrid[0:W, 0:W] + cx = B.J["pelvis"][0] + rx, ry = stature * .16, max(1.5, stature * .022) + sh = (((xs - cx) / rx) ** 2 + ((ys - gy) / ry) ** 2) < 1 + if pose.meta.get("support") != "air": + img[sh] = img[sh] * .7 + xa, ya = max(0, L.x0), max(0, L.y0) + xb, yb = min(W, L.x0 + L.w), min(W, L.y0 + L.h) + a = L.A[ya - L.y0:yb - L.y0, xa - L.x0:xb - L.x0][..., None] + c = L.C[ya - L.y0:yb - L.y0, xa - L.x0:xb - L.x0] + if pixel: + a = (a > .5).astype(np.float32) + img[ya:yb, xa:xb] = img[ya:yb, xa:xb] * (1 - a) + c * a + out = np.clip(img, 0, 255).astype(np.uint8) + if pixel: + out = np.repeat(np.repeat(out, 2, 0), 2, 1) + return out, B + + +# ------------------------------------------------------------------------------------------------ scene hook +UNSUPPORTED_POSES = {"climbing", "yoga", "kicking", "swimming", "hanging", "flying", "crawling"} +RIG_NAME = {"stand": "stand", "walk": "walk", "run": "run", "jump": "jump", "kneel": "kneel", "sleep": "sleep", + "lie": "lie", "sit": "sit", "sit_ground": "sit_ground", "cross_legged": "cross_legged"} +RIG_ACT = {"wave": "wave", "point": "point", "cheer": "cheer", "hold_up": "hold_up", "hands": "hands", "carry": "carry", + "carry_hip": "carry_hip", "carry_side": "carry_side", "hold": "hold", "knit": "knit", "rod": "rod", + "staff": "staff", "cane": "cane", "prop_up": "hold_up", "chop": "chop", "feed": "feed", "reach_up": "reach_up", + "leash": "leash", "reins": "reins", "handlebar": "handlebar", "hug": "hug", "pray": "pray", "drink": "drink", + "violin": "violin", "dance": "dance", "garden": "garden", "throw": "throw", "push": "push", "sad": "sad", + "akimbo": "akimbo", "scared": "scared", "surprised": "surprised", "hip": "hip", "pockets": "pockets", + "work_at": "work_at"} + + +def _style_of(cv, ctx): + if getattr(cv, "ss", 2) == 1: + return "pixel", False, False + sc = getattr(ctx, "scene", None) or {} + text = (sc.get("text") or "").lower() + from . import style_for + st, var = style_for(text, sc, None) + if st == "pixel": + st = "paint" + book = any(w in text for w in ("children's book", "childrens book", "storybook", "picture book", "cartoon", "comic")) + post = sc.get("style") in ("comic", "pop") # a later pass inks colour edges itself (styles.comic) + return st, book, post + + +def _verb(cv, ctx, inst, D): + """(pose name, act) or None when the body path does not build this person yet""" + if D.get("shoulder_ride") or D.get("in_chair") or D.get("chibi") or getattr(inst, "_rider", None) is not None: + return None + if D.get("role_name") == "ninja": + return None + pose = D.get("pose") + if pose in UNSUPPORTED_POSES: + return None + try: + from ..rig.person_px import _verb as _rv + v = _rv(D, inst) + except Exception: + v = None + sc = getattr(ctx, "scene", None) or {} + people = [e for e in sc.get("entities", []) if e.get("concept") == "person"] + single = len(people) == 1 # one person entity (a count of them shares the verb: "three women gleaning") + tname, tact = verb_from_text(sc.get("text") or "") if single else (None, None) + if v is None: + if pose in (None, "standing", "arms_up", "dancing", "walking", "running", "sitting", "kneeling", "lying", + "sleeping", "jumping"): + name = {"walking": "walk", "running": "run", "sitting": "sit", "kneeling": "kneel", "lying": "lie", + "sleeping": "sleep", "jumping": "jump"}.get(pose, "stand") + act = "cheer" if pose == "arms_up" else ("dance" if pose == "dancing" else None) + else: + return None + if D.get("hand_item") in ("guitar", "banjo", "jumprope", "lasso", "pillow", "bubbles", "paperplane"): + return None + else: + name, act, opts = v + name = RIG_NAME.get(name, "stand") + if act == "potter" or act == "shoulders": + return None + act = RIG_ACT.get(act, None) if act else None + if name == "sit" and opts.get("astride"): + name = "ride" + if tname in ("bend", "wind") and name in ("stand", "walk"): + name = tname + if tact and act is None and name not in ("lie", "sleep"): + act = tact + tx = " " + (sc.get("text") or "").lower() + " " + if any(w in tx for w in (" on his shoulder", " on her shoulder", " on his back", " on her back", " over his shoulder", + " over her shoulder", " on their shoulders")) and act in (None, "carry", "hold", "carry_side"): + act = "carry_back" # a sack on the shoulder: trunk forward 18-32 deg under the load (copy P1 town) + if tact == "lead" and act in (None, "staff", "hold", "cane"): + name, act = "walk", "lead" # leading an animal: walking, the lead hand forward (a tool rides in the far hand) + if name == "kneel" and act == "pray": + name = "kneel2" + if act == "work_at": + act = "paint" + return name, act + + +def draw_scene_person(cv, ctx, inst, D): + """the draw_person hook (knob body2d, default OFF). Returns True when it drew the person.""" + if knob("body2d", "0") == "0": + return False + if D.get("age") == "baby" and not D.get("toddler"): + return False + v = _verb(cv, ctx, inst, D) + if v is None: + return False + name, act = v + style, book, post = _style_of(cv, ctx) + pixel = style == "pixel" + age = age_years(D.get("age") or "adult") + if D.get("toddler"): + age = 2.5 + sex = "f" if D.get("fem") else "m" + try: + from ..rig.person_px import _build + build = _build(D, inst) + except Exception: + build = "normal" + x, y, h, f = D["x"], D["y"], D["h"], D["f"] + if getattr(inst, "lean", None): + return False # leaning on a post / tree: the old drawer rests the back on it (critic13 16:54) + if pixel and h >= 60 and name in ("stand", "walk") and act in (None, "cane", "staff", "hip", "pockets", "hold", "akimbo", + "sad", "carry_side") and knob("body2d_hero", "0") == "0": + # pixel figures of 120+ output px standing or walking: the old drawer's capped face and clean figure read better + # than this lane's (critic13 16:44 #12, 16:54 held-out); body2d keeps the verb poses there (bend, sit, kneel, dance...) + return False + if pixel and h > getattr(cv, "h", 1e9) * .85 and knob("body2d_hero", "0") == "0": + # a pixel hero crop (the figure taller than the frame): the old drawer's big anime face reads better than this + # lane's symbol face at that size (r1c 20 / r2t 05, looked); body2d_hero=1 draws it anyway + return False + astride = name == "ride" + seed = int(abs(x) * 131 + abs(y) * 17 + getattr(inst, "k", 0) * 7919) & 0xffff + C = canon(style, age, sex, build, h, seed, book=book) + pname = "sit" if astride else name + over = {} + if astride: + over = dict(hn=(44, 60), kn=(55, 80), an=(16, 24), hf=(44, 60), kf=(55, 80), af=(16, 24), lean=(-4, 6), yaw=(78, 88)) + if name in ("walk", "run", "bend", "wind", "kneel", "kneel2") or astride or D.get("handlebar"): + over.setdefault("yaw", (66, 86)) + if age >= 60 and pname in ("stand", "walk") and act not in ("reach_up", "cheer", "wave"): + # age reads from posture: head forward 0.1-0.25 H, knees 5-15 deg, upper back rounded (human-409, human-408) + over.setdefault("lean", (2, 6)) # the upper back rounds; the trunk does not tip over the legs + over.setdefault("bend", (10, 16)) + over.setdefault("hp", (6, 12)) + over.setdefault("kn", (8, 16)) # soft knees (human-409 knee flex 5-15) + tl = getattr(inst, "tug_lean", None) + if tl is not None and pname in ("stand", "walk"): + # contact lane: a pull / tug leans the trunk (+ toward the facing) and braces the legs (phys-008/009) + over["lean"] = (float(tl), float(tl)) + if tl < 0: + act = act or "pull" + pose = pose_for(pname, act, seed, **over) + seat = None + bound = D.get("bound") + ground_y = y + if pname == "sit": + if D.get("seated_on") or astride or D.get("stool"): + seat = (x - f * h * .02, y - h * .27 if D.get("stool") else y) + gb = getattr(bound, "y", None) + ground_y = gb if (gb is not None and gb > y) else (y + C["hip_h"] * .85 * h / C["N"]) + if astride: + ground_y = None + else: + # "sitting" with nothing under: sit on the ground + pose = pose_for("sit_ground", act, seed, **over) + targets = {} + rch = getattr(inst, "reach", None) or {} + if rch: + if rch.get("front") is not None: + targets["hand_near"] = rch["front"] + if rch.get("back") is not None: + targets["hand_far"] = rch["back"] + try: + from ..rig.person_px import _wheel, WORK_AT, WORK_PT + work = _wheel(ctx, inst, WORK_AT) if act == "paint" else None + except Exception: + work = None + if work is not None: + f = 1 if work.x >= x else -1 + inst.facing = "right" if f > 0 else "left" + if abs(work.x - x) - (work.w * .5 + h * .12) > 0 or abs(work.x - x) < work.w * .3: + x = inst.x = work.x - f * (work.w * .5 + h * .16) + up_, _ = WORK_PT.get(work.concept, (1.0, .0)) + targets["hand_near"] = (work.x - f * work.w * .3, min(work.y - work.h * up_, y - h * .5)) + B = pose_body(C, pose, x, y, h, f, targets=targets, seat=seat, ground_y=ground_y) + if os.environ.get("PYDRAW_BODY_DEBUG"): + print("body2d", name, act, "x,y,h", round(x), round(y), round(h), "seat", seat, "ground", ground_y, + "bound", getattr(bound, "concept", None), getattr(bound, "y", None), getattr(bound, "h", None), + "pelvis", [round(v) for v in B.J["pelvis"]], "an", [round(v) for v in B.J["an_n"]], "build", build, + "hand_item", D.get("hand_item"), "holding", D.get("holding"), "style", D.get("style"), "age", age, "N", round(C["N"], 2)) + look = _look(D) + if astride: + look["hide_far_leg"] = True # the mount hides the far leg (drawn before the rider) + L = getattr(ctx, "L", None) + light = (L.d[0], L.d[1]) if L is not None else (-.6, -.65) + sky = tuple(L.sky) if L is not None else (150, 190, 240) + key = tuple(k * 255 for k in L.key) if L is not None else (255, 248, 235) + night = getattr(ctx, "time", "day") == "night" + Ly = body_draw.render(B, look, style, light, sky, key, night, pixel, post_lines=post) + if astride: + # the mount hides the far leg below the hip: drawn earlier by the render, so cut it here + pass + from ..concepts.people import _ground_shadow, _draw_hat, _draw_hand_item, _pp, PARTS + pb = getattr(inst, "picnic_blanket", None) + if pb is not None: + # the picnic blanket under everyone (the old drawers' rule, kept): gingham in perspective + bx0, bx1, by_, bd = pb + top_, bot_ = by_ - bd * .5, by_ + bd * .5 + sk_ = (bx1 - bx0) * .08 + for i_ in range(8): + for j_ in range(3): + u0, u1, v0, v1 = i_ / 8, (i_ + 1) / 8, j_ / 3, (j_ + 1) / 3 + P_ = lambda u, v: (bx0 + sk_ * (1 - v) + (bx1 - bx0 - sk_ * (1 - v) * 2) * u, top_ + (bot_ - top_) * v) + cv.poly([P_(u0, v0), P_(u1, v0), P_(u1, v1), P_(u0, v1)], (205, 50, 55) if (i_ + j_) % 2 == 0 else (246, 240, 232)) + if pose.meta.get("ground") in ("feet", "knee") and pose.meta.get("support") != "air": + _ground_shadow(cv, B.J["pelvis"][0] + f * h * .01, y, h * .15, h * .022) + body_draw.PART_IDS.update(PARTS) + body_draw.stamp(cv, Ly, cv.cur_id, pixel=pixel) + # anchors for worn and held things (the old drawers' contract) + cr, ch = np.asarray(B.J["crown"]), np.asarray(B.J["chin"]) + hc = cr * .52 + ch * .48 + hl = float(np.hypot(*(cr - ch))) + inst.head = (float(hc[0]), float(hc[1]), hl * .43, hl * .5, f) + pn = B.J["hand_n"] + pf = B.J["hand_f"] + inst.hand = (float(pn[0]), float(pn[1])) + inst.hand2 = (float(pf[0]), float(pf[1])) + if act in ("hands", "carry", "knit", "pray", "chop", "rod", "reins"): + inst.hand = ((pn[0] + pf[0]) * .5, (pn[1] + pf[1]) * .5) + if act in ("hands", "knit") and not D.get("holding"): + try: + from ..rig.person_px import _grab + _grab(cv, ctx, inst, inst.hand[0], inst.hand[1], h) # the reader takes the book into the hands + except Exception: + pass + if h >= cv.h * .3: + inst.focal = True + hat = D.get("hat") + if hat and name not in ("lie", "sleep"): + _pp(cv, "hat") + _draw_hat(cv, D["L"], hat, inst.head[0], inst.head[1], inst.head[2], inst.head[3], f, D["shirt"], D["rng"]) + dog_ = getattr(inst, "leash_to", None) + if dog_ is not None: + side_ = 1 if dog_.x >= inst.hand[0] else -1 + cx_, cy_ = dog_.x + side_ * dog_.w * .3, dog_.y - dog_.h * .72 + hx, hy = inst.hand + pts_ = [(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)]] + _pp(cv, "prop") + 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)) + hand_item = D.get("hand_item") + if hand_item == "cane" and pname not in ("stand", "walk"): + hand_item = None # no walking cane planted by a kneeling / seated / lying figure + if hand_item and not D.get("holding") and hand_item not in ("cane",) or (hand_item == "cane" and act == "cane"): + _pp(cv, "prop") + cid = cv.cur_id + hx_, hy_ = inst.hand2 if act in ("lead", "leash") else inst.hand + _draw_hand_item(cv, D["L"], hand_item, hx_, hy_, h, f, y, D["shirt"]) + cv.cur_id = cid + if act == "paint" and not D.get("holding"): + # the brush: a short stick from the fist toward the canvas, a dark tip (critic13 16:44: the brush was gone) + _pp(cv, "prop") + wr_, hd_ = B.J["wr_n"], B.J["hand_n"] + ux, uy = hd_[0] - wr_[0], hd_[1] - wr_[1] + n_ = math.hypot(ux, uy) or 1.0 + ux, uy = ux / n_, uy / n_ + L_ = C["hand"] * B.s * 1.2 + bx, by = hd_[0] + ux * L_ * .2, hd_[1] + uy * L_ * .2 + cv.capsule(hd_[0] - ux * L_ * .3, hd_[1] - uy * L_ * .3, bx + ux * L_ * .5, by + uy * L_ * .5, max(.6, h * .006), (150, 100, 55)) + cv.capsule(bx + ux * L_ * .5, by + uy * L_ * .5, bx + ux * L_ * .7, by + uy * L_ * .7, max(.7, h * .008), (40, 34, 30)) + _pp(cv, None) + if knob("body2d_fl", "0") == "0": + inst.form_skip = True # the designed shadow shapes replace the silhouette relight (copy P7) + inst.body2d = B + inst.body2d_claim = dict(B.claim(), ground_y=round(float(y), 2), res=[cv.w, cv.h], style=style) + LAST.append(inst.body2d_claim) + if os.environ.get("PYDRAW_BODY_CLAIMS"): + import json + sc = getattr(ctx, "scene", None) or {} + with open(os.environ["PYDRAW_BODY_CLAIMS"], "a") as fh: + fh.write(json.dumps(dict(inst.body2d_claim, prompt=sc.get("text")), default=float) + "\n") + return True + + +def scale_(c, k): + return tuple(min(255.0, v * k) for v in c) + + +def _look(D): + R = D.get("R") or {} + style = D.get("style") or "short" + word = (D.get("word") or "") + " " + (D.get("role_name") or "") + toks = set(word.lower().replace("_", " ").split()) + male = D.get("g") == "m" or D.get("gender") == "m" or bool(toks & {"grandfather", "grandpa", "father", "man", "boy", + "king", "prince", "monk", "gentleman", "old man"}) + if male and not D.get("fem") and style in ("long", "pony", "bun"): + # sex and age cues survive (critic13 16:54: a grandfather drawn with long hair read as a woman) + style = "bald" if D.get("age") == "old" and (len(word) % 3 == 0) else "short" + if style == "cap": + style = "short" + dress = D.get("dress") + look = dict(skin=tuple(D["skin"]), top=tuple(D["shirt"]), bottom=tuple(D["pants"]), shoes=tuple(D["shoes"]), + hair=tuple(D["hair"]), style=style, sleeves=D.get("sleeves"), skirt=bool(D.get("skirt")) and not dress, + dress=tuple(D["shirt"]) if dress else None, coat=tuple(D["coat"]) if D.get("coat") else None, + shorts=R.get("shorts"), boots=R.get("boots"), mittens=R.get("mittens"), + eye=D.get("eye_c"), apron=(248, 246, 240) if R.get("apron") is True else (R.get("apron") or None)) + if dress in ("gown", "robe"): + look["long_skirt"] = True + if dress == "tutu": + look["tutu"] = True + if D.get("role_name") == "knight" or D.get("steel") or R.get("armour"): + # plate armour: a metal plan (hard dark core, bright lit band, human-029 / form steel) + tabard + great helm + mc = tuple(D.get("metal") or (150, 155, 166)) + look.update(top=mc, bottom=mc, shoes=scale_(mc, .8), armour=True, helm=True, sleeves=True, skirt=False, mittens=scale_(mc, .9), + dress=None, coat=None) + if D.get("tabard"): + look["tabard"] = tuple(D["tabard"]) + fk = R.get("face") + if fk in ("beard", "beard_long", "beard_short"): + look["beard"] = True + if fk == "beard_long": + look["beard_col"] = (238, 238, 240) + return look diff --git a/pydraw/figure/body_canon.py b/pydraw/figure/body_canon.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6222d9fb4d122e989a5a9e43294b9d41cc7202 --- /dev/null +++ b/pydraw/figure/body_canon.py @@ -0,0 +1,145 @@ +"""Full-figure canon for the 2D-first body (wave 20, body lane). Pure code, no data files. + +All lengths are in HEAD UNITS H (crown to chin) and every value is a RANGE sampled by the seed; nothing is typed from +one picture. Sources (rule ids from docs/research21/rules/human.jsonl, research 20 copy_people.md P-rules): + heads tall by style / age / role: human-398 (Stratz ages), human-425 (age table), human-472 (manga roles), + human-479 (comic 6.5 average, 8.75 hero), human-473 (deformed 3-5 H), human-436 (cartoon types), copy P4 (book adult + 5.5-6.5, book child 4.5-5, painterly adult 7-7.5), scale.md S3 (pixel 3.2-4.3 heads at 50-65 grid px) + widths by sex and build: human-419 (bideltoid / waist / hip by BMI band), human-424 (sex switch), human-225 + hand 0.75-0.85 H: human-338, human-074 (0.82-0.86); foot 1.10-1.14 H: human-359; thigh 1.9-2.0 H (WAVE20 brief) + crotch height fraction by age: human-425; child stature vs adult: human-399 +""" +import random +import zlib + + +def srng(*salt): + """a seeded rng that is stable across processes (no hash() randomisation)""" + return random.Random(zlib.crc32(repr(salt).encode())) + +# heads tall (adult) by style family: (lo, hi) +HEADS = { + "paint": (7.0, 7.6), # copy P4 painterly adult 1/7 - 1/7.5; human-424 7.26-7.37 + "ink": (7.0, 7.6), + "anime": (6.6, 7.4), # human-472 average adults 6-7 H, models 7-8 + "book": (5.6, 6.4), # copy P4 children's-book adult 5.5-6.5 + "pixel": (6.4, 7.0), # large pixel figures; small ones get the head ladder below + "chibi": (2.8, 3.4), # human-473 baby style 3 H +} +# age -> (heads tall realistic, stature vs adult man, crotch fraction) human-398 / human-399 / human-425 +AGES = [(1, 4.5, .40, .40), (3, 5.25, .54, .43), (5, 5.75, .62, .45), (8, 6.3, .73, .46), (10, 6.5, .79, .47), + (13, 7.0, .90, .48), (16, 7.25, .98, .48), (30, 7.4, 1.0, .48), (70, 7.1, .97, .475)] + +# front widths in H (bideltoid, waist, hip) by sex and build: human-419 (BMI 20-25 row), human-424 +WIDTH = {"m": (2.00, 1.22, 1.36), "f": (1.86, 1.10, 1.48)} +BUILD = { # multipliers (shoulder, waist, hip, limb girth) human-248/249: girth changes, bones stay + "normal": (1.0, 1.0, 1.0, 1.0), "slim": (.94, .88, .92, .86), "heavyset": (1.08, 1.38, 1.18, 1.22), + "chubby": (1.04, 1.32, 1.16, 1.2), "muscular": (1.14, 1.04, 1.0, 1.2), "stocky": (1.1, 1.22, 1.1, 1.15), +} + + +def _lerp_table(age): + if age <= AGES[0][0]: + return AGES[0][1:] + for a, b in zip(AGES, AGES[1:]): + if a[0] <= age <= b[0]: + t = (age - a[0]) / float(b[0] - a[0]) + return tuple(a[i] + (b[i] - a[i]) * t for i in (1, 2, 3)) + return AGES[-1][1:] + + +def age_years(age_word): + return {"baby": 1, "toddler": 2.5, "child": 7, "kid": 7, "teen": 15, "adult": 30, "old": 72}.get(age_word, 30) + + +def pixel_heads(px): + """small pixel figures carry the head (scale.md S3/S4, copy P4): heads tall by working-grid stature in px""" + if px <= 24: + return 2.9 + if px <= 40: + return 2.9 + (px - 24) / 16.0 * .7 # 3.6 at 40 + if px <= 70: + return 3.6 + (px - 40) / 30.0 * .8 # 4.4 at 70 + if px <= 130: + return 4.4 + (px - 70) / 60.0 * 1.4 # 5.8 at 130 + return None + + +def canon(style="paint", age=30, sex="m", build="normal", px=200, seed=0, chibi=False, book=False): + """the figure canon: a dict of head-unit lengths and widths plus heads tall N. `px` = standing stature in output + (working) pixels; it sets the small-figure head ladder (pixel style) and the detail row.""" + r = srng(seed, "canon", style, age, sex, build) + u = lambda lo, hi: lo + (hi - lo) * r.random() + fam = "chibi" if chibi else ("book" if book and style in ("anime", "paint", "ink") else style) + lo, hi = HEADS.get(fam, HEADS["paint"]) + N_ad = u(lo, hi) + N_real, stat_k, crotch = _lerp_table(age) + # children and old people scale the style's adult heads by the realistic ratio (human-398 ladder kept per style) + N = N_ad * (N_real / 7.4) if not chibi else N_ad + if style == "pixel" and not chibi: + ph = pixel_heads(px) + if ph is not None: + N = min(N, ph * (N_real / 7.4) ** .5) + elif px < 60 and not chibi: + N *= .9 + .1 * max(0.0, (px - 30) / 30.0) # scale.md S1: small heads enlarge a little in every medium + if sex == "f" and not chibi and age >= 13: + N -= u(.05, .15) # human-424 a woman 7.26 vs 7.37 heads + w_sh, w_wa, w_hi = WIDTH["f" if sex == "f" else "m"] + b = BUILD.get(build, BUILD["normal"]) + # narrower shoulders in children, in head units (the head is a bigger share): human-425 girth, copy P14 + kid = min(1.0, max(0.0, (age - 2) / 14.0)) + wk = .72 + .28 * kid + if chibi: + wk = .62 + C = dict(N=N, age=age, sex=sex, build=build, style=style, px=px, chibi=chibi) + C["head_w"] = u(.74, .80) if age >= 13 else u(.82, .9) # head width / height (rounder for children) + C["neck"] = (.05 if age >= 13 else .03) * (0 if chibi else 1) # chin ~0.33 H above the shoulder line (8 H canon) # neck length below the chin + if style == "pixel" and px < 48: + C["neck"] = 0.0 # scale.md C4: no neck below 48 px + C["neck_w"] = .5 * (.8 if sex == "f" else 1) * (.9 + .1 * b[3]) + # vertical landmarks, standing, from the sole (H units) + crotch_h = crotch * N + if chibi: + crotch_h = .26 * N + C["ankle_h"] = .045 * N * (1.0 if not chibi else 1.4) # ankle bone .27 foot (human-359) + C["hip_h"] = crotch_h + .03 * N # hip joints ~ the trochanters, half the stature (human-209) + leg = C["hip_h"] - C["ankle_h"] + C["thigh"] = leg * u(.50, .52) + C["shin"] = leg - C["thigh"] + C["crown_h"] = N + C["neckbase_h"] = N - 1.0 - C["neck"] + C["torso"] = C["neckbase_h"] - C["hip_h"] # neck base to hip-joint line + C["sh_drop"] = .15 if not chibi else .08 # shoulder joint below the neck base + # arm: fingertips reach mid-thigh adult (shoulder - fingertip span split .43 / .335 / .235, pydraw canon kept) + tip = C["hip_h"] - C["thigh"] * (.48 if not chibi else .1) + span = (C["neckbase_h"] - C["sh_drop"]) - tip + C["upper"], C["fore"], C["hand"] = span * .43, span * .335, span * .235 + if not chibi: + C["hand"] = min(max(C["hand"], .74), .86) # human-338 0.75-0.80 H, human-074 0.82-0.86 + C["foot"] = u(1.08, 1.14) * (.86 if sex == "f" else 1) * (1.0 if age >= 13 else .82 + .18 * kid) # human-359 + if chibi: + C["foot"] = .55 + # widths (front), H units + C["sh_w"] = w_sh * b[0] * wk + C["waist_w"] = w_wa * b[1] * wk + C["hip_w"] = w_hi * b[2] * wk + C["chest_d"] = (1.05 if sex == "m" else 1.0) * b[1] ** .5 * wk # side depths + C["belly_d"] = .9 * b[1] * wk + C["hip_d"] = .95 * b[2] * wk + g = b[3] * (.88 if sex == "f" else 1.0) * (.92 + .08 * kid) + if chibi: + g *= 1.15 + C["arm_w"] = (.50 * g, .44 * g, .40 * g, .24 * g) # shoulder, mid upper arm, elbow, wrist + C["leg_w"] = (.78 * g * (1.06 if sex == "f" else 1), .66 * g, .40 * g, .46 * g, .24 * g) # top, mid thigh, knee, calf, ankle + C["fat"] = max(0.0, b[1] - 1.0) + if sex == "f" and C["fat"] > 0: + # women carry weight on the hips, buttocks and thighs, not a belly ball (human-249 female zones) + C["hip_w"] *= 1.0 + C["fat"] * .35 + C["waist_w"] /= 1.0 + C["fat"] * .3 + C["leg_w"] = (C["leg_w"][0] * (1 + C["fat"] * .4), C["leg_w"][1] * (1 + C["fat"] * .3)) + tuple(C["leg_w"][2:]) + return C + + +def stature_k(age): + """stature of a person of this age relative to an adult (human-399)""" + return _lerp_table(age)[1] diff --git a/pydraw/figure/body_draw.py b/pydraw/figure/body_draw.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0b25ec033fb14836b3c04a095f5308af01a211 --- /dev/null +++ b/pydraw/figure/body_draw.py @@ -0,0 +1,1046 @@ +"""Masses, clothing, designed shadows, features and style marks for a posed full figure (wave 20, body lane). + +Draws a body_pose.Body into a local RGBA layer in the artist's order (WAVE20 method 4-7): + value plan (one light, shadow family) -> masses back to front (far arm, far leg, torso + garments, near leg, + skirt / coat, neck, head, near arm) -> designed shadow shape per part (the part minus itself shifted toward the + light: a band 0.2-0.4 of its width on the side away from the light, copy P7, human-029 value classes by size) + -> features sized for the pixels (hands human-351/354, feet human-371, faces by head px) -> style marks last + (ink / anime lines with a heavier silhouette, paint soft edges, pixel hard edges). +Pure numpy + PIL; no image files. +""" +import math +import numpy as np +from PIL import Image, ImageDraw, ImageFilter + +PART_IDS = dict(hair=1, top=2, bottom=3, shoes=4, metal=5, tabard=6, cape=7, coat=8, prop=9, hat=11, vest=12, + skin=14, arm=15, face=100, mark=101) + + +# ------------------------------------------------------------------------------------------------ geometry +def chaikin(P, n=1, closed=False): + P = np.asarray(P, float) + for _ in range(n): + if len(P) < 3: + return P + Q = [] + rng = range(len(P)) if closed else range(len(P) - 1) + if not closed: + Q.append(P[0]) + for i in rng: + a, b = P[i], P[(i + 1) % len(P)] + Q.append(a * .75 + b * .25) + Q.append(a * .25 + b * .75) + if not closed: + Q.append(P[-1]) + P = np.array(Q) + return P + + +def resample(P, n_per=6): + P = np.asarray(P, float) + out = [] + for i in range(len(P) - 1): + for t in np.linspace(0, 1, n_per, endpoint=False): + out.append(P[i] * (1 - t) + P[i + 1] * t) + out.append(P[-1]) + return np.array(out) + + +def ribbon(pts, widths, cap=True, smooth=1, n_per=8): + """a tapered limb / torso mass along a polyline: widths per input point (full width, px). Round caps.""" + P = np.asarray(pts, float) + W = np.asarray(widths, float) + t0 = np.r_[0, np.cumsum(np.hypot(*np.diff(P, axis=0).T))] + S = resample(P, n_per) + if smooth: + S = chaikin(S, smooth) + ts = np.r_[0, np.cumsum(np.hypot(*np.diff(S, axis=0).T))] + ts = ts / max(ts[-1], 1e-6) * t0[-1] + w = np.interp(ts, t0, W) / 2 + d = np.gradient(S, axis=0) + d /= np.maximum(np.hypot(d[:, 0], d[:, 1]), 1e-6)[:, None] + nrm = np.stack([-d[:, 1], d[:, 0]], 1) + L = S + nrm * w[:, None] + R = S - nrm * w[:, None] + out = [L] + if cap: + u, c, r = d[-1], S[-1], w[-1] + a0 = math.atan2(nrm[-1, 1], nrm[-1, 0]) + out.append(np.array([c + r * np.array([math.cos(a0 - t), math.sin(a0 - t)]) for t in np.linspace(0, math.pi, 7)[1:-1]])) + out.append(R[::-1]) + if cap: + c, r = S[0], w[0] + a0 = math.atan2(-nrm[0, 1], -nrm[0, 0]) + out.append(np.array([c + r * np.array([math.cos(a0 - t), math.sin(a0 - t)]) for t in np.linspace(0, math.pi, 7)[1:-1]])) + return np.vstack(out) + + +def ellipse(c, rx, ry, ang=0.0, n=36): + t = np.linspace(0, 2 * math.pi, n, endpoint=False) + ca, sa = math.cos(ang), math.sin(ang) + x, y = rx * np.cos(t), ry * np.sin(t) + return np.stack([c[0] + x * ca - y * sa, c[1] + x * sa + y * ca], 1) + + +def _v(a, b): + return np.asarray(b, float) - np.asarray(a, float) + + +def _unit(v): + v = np.asarray(v, float) + return v / max(float(np.hypot(*v)), 1e-6) + + +# ------------------------------------------------------------------------------------------------ raster +class Layer: + """local RGBA + part-id layer at 1x with masks rasterised at ss x""" + + def __init__(self, x0, y0, w, h, ss): + self.x0, self.y0, self.w, self.h, self.ss = x0, y0, w, h, ss + self.C = np.zeros((h, w, 3), np.float32) + self.A = np.zeros((h, w), np.float32) + self.P = np.zeros((h, w), np.int16) + self.U = np.zeros((h * ss, w * ss), np.float32) # hi-res union (for lines / silhouette) + + def mask_hi(self, poly): + ss = self.ss + im = Image.new("L", (self.w * ss, self.h * ss), 0) + for P in (poly if isinstance(poly, list) else [poly]): + pts = [((x - self.x0) * ss, (y - self.y0) * ss) for x, y in np.asarray(P, float)] + if len(pts) >= 3: + ImageDraw.Draw(im).polygon(pts, fill=255) + return np.asarray(im, np.float32) / 255 + + def down(self, m): + ss = self.ss + if ss == 1: + return m + h, w = self.h, self.w + return m.reshape(h, ss, w, ss).mean(axis=(1, 3)) + + +def _shift(m, dx, dy): + dx, dy = int(round(dx)), int(round(dy)) + o = np.zeros_like(m) + H, W = m.shape + if abs(dx) >= W or abs(dy) >= H: + return o + ys, yd = (slice(0, H - dy), slice(dy, H)) if dy >= 0 else (slice(-dy, H), slice(0, H + dy)) + xs, xd = (slice(0, W - dx), slice(dx, W)) if dx >= 0 else (slice(-dx, W), slice(0, W + dx)) + o[yd, xd] = m[ys, xs] + return o + + +def _erode(m, r): + r = int(round(r)) + if r <= 0: + return m + im = Image.fromarray((np.clip(m, 0, 1) * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(2 * r + 1)) + return np.asarray(im, np.float32) / 255 + + +def _dilate(m, r): + r = int(round(r)) + if r <= 0: + return m + im = Image.fromarray((np.clip(m, 0, 1) * 255).astype(np.uint8)).filter(ImageFilter.MaxFilter(2 * r + 1)) + return np.asarray(im, np.float32) / 255 + + +def _blur(m, r): + if r <= 0: + return m + im = Image.fromarray((np.clip(m, 0, 1) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(r)) + return np.asarray(im, np.float32) / 255 + + +def mix(a, b, t): + return tuple(a[i] + (b[i] - a[i]) * t for i in range(3)) + + +def scale(c, k): + return tuple(min(255.0, max(0.0, v * k)) for v in c) + + +def luma(c): + return .3 * c[0] + .59 * c[1] + .11 * c[2] + + +# ------------------------------------------------------------------------------------------------ value plan +class Shades: + """the designed shadow family for one picture light (copy P7; human-029 values by size; human-027 one light)""" + + def __init__(self, light=(-.6, -.65), sky=(150, 190, 240), key=(255, 248, 235), night=False, px=200, style="paint"): + lx, ly = light + n = math.hypot(lx, ly) or 1.0 + self.lx, self.ly = lx / n, ly / n + self.sky, self.key, self.night, self.px, self.style = sky, key, night, px, style + self.levels = 2 if px < 100 else (3 if px < 250 else 4) + + def shadow(self, c, mat="cloth"): + if mat == "metal": + return mix(scale(c, .42), scale(self.sky, .4), .15) # steel: a dark core, the sky in the shadow + k = .64 if mat != "skin" else .74 + if self.style == "anime": + k = .72 if mat != "skin" else .8 + if getattr(self, "soft", False): + k = max(k, 1 - 30.0 / max(luma(c), 40.0)) + s = scale(c, k) + return mix(s, scale(self.sky, .55), .10 if mat != "skin" else .06) # shadows take the sky's hue, never grey + + def light(self, c, mat="cloth"): + if mat == "metal": + return mix(c, (250, 250, 248), .55) # steel: a bright lit band + return mix(c, self.key, .14 if mat != "skin" else .10) + + def half(self, c, mat="cloth"): + return mix(c, self.shadow(c, mat), .5) + + +# ------------------------------------------------------------------------------------------------ the figure +def build_parts(B, look, sh_style="paint"): + """the figure's masses as (name, material key, polygon, part id, mat kind, z) back to front""" + C, J, s, f = B.C, B.J, B.s, B.facing + th = B.yaw * math.pi / 180 + st, ct = abs(math.sin(th)), abs(math.cos(th)) + proj = lambda W, D: math.sqrt((W * .5 * ct) ** 2 + (D * .5 * st) ** 2) * 2 + p = lambda k: np.asarray(J[k], float) + parts = [] + skin, top, bottom = look["skin"], look["top"], look["bottom"] + shoes, hair = look["shoes"], look["hair"] + dress, skirt, coat = look.get("dress"), look.get("skirt"), look.get("coat") + sleeves = look.get("sleeves", True) + shorts = look.get("shorts") + seated = B.pose.name in ("sit", "sit_ground", "cross_legged") + aw, lw = [v * s for v in C["arm_w"]], [v * s for v in C["leg_w"]] + + def arm(side): + sh, el, wr = p("sh_" + side), p("el_" + side), p("wr_" + side) + sleeve_c = coat or (top if not dress or sleeves else skin) + out = [] + # the deltoid cap sits on the torso contour (copy P9): the upper arm starts inside the shoulder mass + ua = ribbon([sh, el], [aw[0], aw[2]], smooth=0) + mid = sh + _v(sh, el) * .4 + ua2 = ribbon([sh, mid, el], [aw[0] * 1.02, aw[1], aw[2]], smooth=1) + if sleeves or coat: + fa = ribbon([el, wr], [aw[2] * 1.04, aw[3] * 1.25], smooth=0) + out.append(("fore_" + side, "sleeve", fa, "top" if not coat else "coat", "cloth", sleeve_c)) + out.append(("upper_" + side, "sleeve", ua2, "top" if not coat else "coat", "cloth", sleeve_c)) + cuff = wr + _v(el, wr) * -.06 + out.append(("wrist_" + side, "skin", ribbon([cuff, wr + _v(el, wr) * .08], [aw[3] * .95, aw[3] * .9], smooth=0), + "skin", "skin", skin)) + else: + fa = ribbon([el, wr], [aw[2] * .92, aw[3]], smooth=0) + out.append(("fore_" + side, "skin", fa, "skin", "skin", skin)) + tee = sh + _v(sh, el) * .5 + out.append(("upper_" + side, "skin", ribbon([sh, el], [aw[0] * .95, aw[2] * .92], smooth=0), "skin", "skin", skin)) + out.append(("sleeve_" + side, "top", ribbon([sh - _unit(_v(sh, el)) * aw[0] * .45, sh, mid, tee], [aw[0] * .9, aw[0] * 1.04, aw[1] * 1.08, aw[1] * 1.06], cap=False, smooth=0), + "top" if not dress else "top", "cloth", top if not dress else dress)) + hp_, thumb = hand_poly(B, side, look) + hc = look.get("mittens") or skin + if thumb is not None: + out.append(("thumb_" + side, "skin", thumb, "skin", "skin", hc)) + out.append(("hand_" + side, "skin", hp_, "skin", "skin", hc)) + return out + + def leg(side): + hip, kn, an = p("hip_" + side), p("kn_" + side), p("an_" + side) + heel, toe = p("heel_" + side), p("toe_" + side) + out = [] + thigh_mid = hip + _v(hip, kn) * .35 + calf = kn + _v(kn, an) * .3 + widths = [lw[0], lw[1], lw[2], lw[3], lw[4]] + pts = [hip, thigh_mid, kn, calf, an] + legpoly = [ribbon([hip, thigh_mid, kn], widths[:3], smooth=0), ribbon([kn, calf, an], widths[2:], smooth=0)] + legc = bottom + if dress or skirt or shorts: + legc = skin if not look.get("stockings") else look["stockings"] + if look.get("boots"): + boot_top = kn + _v(kn, an) * .25 + out.append(("leg_" + side, "bottom", legpoly, "bottom" if legc == bottom else "skin", + "cloth" if legc == bottom else "skin", legc)) + out.append(("boot_" + side, "shoes", ribbon([boot_top, an], [lw[3] * 1.1, lw[4] * 1.3], smooth=0), "shoes", "cloth", shoes)) + else: + out.append(("leg_" + side, "bottom", legpoly, "bottom" if legc == bottom else "skin", + "cloth" if legc == bottom else "skin", legc)) + if shorts and not (dress or skirt): + sp = [hip, thigh_mid, hip + _v(hip, kn) * .62] + out.append(("shorts_" + side, "bottom", ribbon(sp, [lw[0] * 1.08, lw[1] * 1.12, lw[1] * 1.1], smooth=0), + "bottom", "cloth", bottom)) + out.append(("foot_" + side, "shoes", foot_poly(B, side), "shoes", "cloth", shoes)) + return out + + # ---- torso: swept along the spine with a width profile, projected for the turn + pel, wai, che, nb = p("pelvis"), p("waist"), p("chest"), p("neck") + up = _unit(_v(pel, nb)) + crotch = pel - up * C["hip_d"] * .28 * s + shl = nb + _unit(_v(nb, che)) * C["sh_drop"] * s * .9 + tuck = not (dress or coat or look.get("tunic")) + belt = pel + _v(pel, wai) * .5 + spine = [crotch if not tuck else belt - up * .14 * s, pel if not tuck else belt - up * .07 * s, wai, che, shl, nb] + W = [proj(C["hip_w"] * (.82 if not tuck else .96), C["hip_d"] * (.85 if not tuck else .95)), + proj(C["hip_w"] * (1.0 if not tuck else .93), C["hip_d"] * (1.0 if not tuck else .93)), proj(C["waist_w"], C["belly_d"]), + proj(C["sh_w"] * .70, C["chest_d"]), proj(C["sh_w"] * .78, C["chest_d"] * .86), proj(C["neck_w"] * 1.5, C["neck_w"] * 1.3)] + W = [w * s for w in W] + # front / back bias (3/4 and profile): chest forward, rump back, belly by build (human-249) + fwd = np.array([f, 0.0]) * st + bias = [-.10, -.12, .02 + .55 * C.get("fat", 0), .10 + (.08 if C["sex"] == "f" and C["age"] >= 13 else 0), .04, .0] + spine_b = [pt + fwd * b * s for pt, b in zip(spine, bias)] + torso = chaikin(ribbon(spine_b, W, cap=False, smooth=1, n_per=6), 2, closed=True) + # shoulders: a rounded yoke between the two shoulder joints (the deltoid caps) + yoke = [ellipse(p("sh_" + k), aw[0] * .52, aw[0] * .5, 0) for k in ("n", "f")] + torso_c = coat or (dress if dress else top) + pel_poly = ribbon([crotch - up * C["hip_d"] * .05 * s, pel, pel + up * C["torso"] * .27 * s], + [W[0] * 1.02, W[1] * 1.03, (W[1] + W[2]) * .52], cap=False, smooth=0) + # crotch / pelvis garment joins the thighs (no background between the legs above the crotch, copy P9) + thighs = ribbon([p("hip_f"), crotch, p("hip_n")], [lw[0] * .9, lw[0] * .95, lw[0] * .9], cap=False, smooth=0) + # the neck rises from the shoulder line into the skull, behind the chin (human-124: it meets the jaw half way + # between chin and jaw angle in side view), never a tube up to the chin + hcen = p("chin") * .55 + p("crown") * .45 + hax = _unit(_v(p("chin"), p("crown"))) + behind = np.array([-f, 0.0]) * st * C["neck_w"] * s * .35 + neck = ribbon([nb - up * .1 * s, p("neck_top") + behind, hcen - hax * .05 * s + behind], + [C["neck_w"] * s * 1.05, C["neck_w"] * s * .92, C["neck_w"] * s * .9], smooth=0) + + far_arm_front = B.Z.get("hand_f", -1) > B.Z.get("chest", 0) + .3 * s and B.pose.act not in (None, "pockets", "hip", "akimbo") + order = [] + if not far_arm_front: + order += arm("f") + hair_back = hair_back_poly(B, look) + if hair_back is not None: + order.append(("hair_back", "hair", hair_back, "hair", "hair", hair)) + lf, ln = leg("f"), leg("n") + if look.get("hide_far_leg"): + lf = [q for q in lf if q[0].startswith("leg")][:0] or [("leg_f", "bottom", None, "bottom", "cloth", ln[0][5])] + order += [q for q in lf if not q[0].startswith("foot") and q[2] is not None] + legc = lf[0][5] + order.append(("thighs", "bottom", thighs, "bottom" if legc == bottom else "skin", "cloth" if legc == bottom else "skin", legc)) + if not dress and not coat and not skirt: + order.append(("pelvis", "bottom", pel_poly, "bottom", "cloth", bottom)) + order += [q for q in ln if not q[0].startswith("foot")] + order += [q for q in lf if q[0].startswith("foot")] + [q for q in ln if q[0].startswith("foot")] + if (dress or skirt) and not seated: + pass + if C.get("fat", 0) > .15 and C["sex"] == "m": + # heavy builds: a round belly mass over the waist (human-249 male belly / flank zones), forward in 3/4 + fat = C["fat"] + bc = wai + fwd * (C["belly_d"] * .1 + fat * .2) * s - up * .18 * s + torso = [torso, ellipse(bc, (C["waist_w"] * .5 * ct + C["belly_d"] * .5 * st + fat * .25) * s, + (.62 + fat * .4) * s, math.atan2(up[1], up[0]) + math.pi / 2)] + order.append(("torso", "top", torso, "top" if not coat else "coat", "cloth", torso_c)) + if dress or skirt: + sk = skirt_poly(B, look, W) + if sk is not None: + order.append(("skirt", "bottom", sk, "bottom", "cloth", dress or skirt_color(look))) + if coat: + order += coat_parts(B, look, W, torso) + if look.get("apron"): + order.append(("apron", "top", apron_poly(B, W), "top", "cloth", look["apron"])) + if look.get("tabard"): + tb = apron_poly(B, W) + tb[0] = tb[0] + (p("neck") - tb[0]) * .35 + tb[1] = tb[1] + (p("neck") - tb[1]) * .35 + order.append(("tabard", "tabard", tb, "tabard", "cloth", look["tabard"])) + order.append(("neck", "skin", neck, "skin", "skin", skin)) + order.append(("head", "skin", head_poly(B, look), "face", "skin", skin)) + if far_arm_front: + order += arm("f") + order += arm("n") + return order + + +def skirt_color(look): + return look.get("bottom") + + +def skirt_poly(B, look, W): + """A-line skirt / dress from the waist, touching at the hips, hem by length (human-388: A-line 8-15 deg)""" + C, J, s = B.C, B.J, B.s + p = lambda k: np.asarray(J[k], float) + wai, pel = p("waist"), p("pelvis") + up = _unit(_v(pel, p("neck"))) + side = np.array([up[1] * -1, up[0]]) + gown = bool(look.get("long_skirt")) + seated = B.pose.name in ("sit", "sit_ground", "cross_legged", "kneel", "kneel2") + kn_n, kn_f, an_n, an_f = p("kn_n"), p("kn_f"), p("an_n"), p("an_f") + if seated: + # the cloth lies over the thighs to the knees, then hangs from the knees (gown) or ends there + hip_w = W[1] * .55 + a = pel + up * C["torso"] * .2 * s + hem_t = .95 if not gown else 1.0 + pts = [a - side * hip_w * 1.0, a + side * hip_w * 1.0] + kmax = max([kn_n, kn_f], key=lambda k: (k - pel) @ np.array([B.facing, 0])) + tip = kmax + np.array([B.facing * C["leg_w"][2] * s * .55, 0]) + lowk = max(kn_n[1], kn_f[1]) + if gown: + ank = max(an_n[1], an_f[1]) + poly = [pts[0], pts[1], tip + np.array([0, -C["leg_w"][2] * s * .5]), tip + np.array([B.facing * C["leg_w"][2] * s * .4, ank - tip[1]]), + np.array([min(an_n[0], an_f[0], pel[0]) - C["leg_w"][2] * s * .3 * B.facing, ank]), + pel - up * C["hip_d"] * .3 * s] + else: + poly = [pts[0], pts[1], tip + np.array([0, -C["leg_w"][2] * s * .55]), tip + np.array([0, C["leg_w"][2] * s * .6]), + pel - up * C["hip_d"] * .45 * s + side * 0] + return chaikin(np.array(poly), 2, closed=True) + top_c = wai + up * C["torso"] * .05 * s + hw = W[2] * .5 * 1.02 + hip_c = pel + hiw = W[1] * .5 * 1.06 + if gown: + hem_y = max(an_n[1], an_f[1]) - C["ankle_h"] * s * .3 + elif look.get("tutu"): + hem_y = pel[1] + (kn_n[1] - pel[1]) * .45 + else: + hem_y = (kn_n[1] + kn_f[1]) / 2 + C["leg_w"][2] * s * .3 + flare = math.tan((12 if not gown else 16) * math.pi / 180) * (hem_y - hip_c[1]) + xs = [kn_n[0], kn_f[0]] if not gown else [an_n[0], an_f[0], kn_n[0], kn_f[0]] + lo_x = min(min(xs) - C["leg_w"][2] * s * .6, hip_c[0] - hiw - flare) + hi_x = max(max(xs) + C["leg_w"][2] * s * .6, hip_c[0] + hiw + flare) + poly = [top_c - side * hw, top_c + side * hw, hip_c + side * hiw, np.array([hi_x if side[0] > 0 else lo_x, hem_y]), + np.array([(lo_x + hi_x) / 2, hem_y + C["leg_w"][2] * s * .12]), + np.array([lo_x if side[0] > 0 else hi_x, hem_y]), hip_c - side * hiw] + return chaikin(np.array(poly), 1, closed=True) + + +def coat_parts(B, look, W, torso): + C, J, s = B.C, B.J, B.s + p = lambda k: np.asarray(J[k], float) + pel = p("pelvis") + up = _unit(_v(pel, p("neck"))) + side = np.array([-up[1], up[0]]) + hem = (p("kn_n") + p("kn_f")) / 2 + hem = pel + (hem - pel) * .55 + hw = W[1] * .55 + tails = [pel + up * C["torso"] * .3 * s - side * hw, pel + up * C["torso"] * .3 * s + side * hw, + hem + side * hw * 1.15, hem - side * hw * 1.15] + out = [("coat_tail", "coat", chaikin(np.array(tails), 1, closed=True), "coat", "cloth", look["coat"])] + # open front: a strip of the shirt on the facing side of the chest (3/4 view) + th = B.yaw * math.pi / 180 + fr = np.array([B.facing, 0.0]) * abs(math.sin(th)) * W[3] * .22 + nb = p("neck") + strip = ribbon([pel + up * C["torso"] * .35 * s + fr * .6, p("chest") + fr, nb - up * .25 * s + fr * .8], + [W[2] * .12, W[3] * .16, W[4] * .12], cap=False, smooth=0) + out.append(("coat_open", "top", strip, "top", "cloth", look["top"])) + return out + + +def apron_poly(B, W): + J, s, C = B.J, B.s, B.C + p = lambda k: np.asarray(J[k], float) + pel, che = p("pelvis"), p("chest") + up = _unit(_v(pel, p("neck"))) + side = np.array([-up[1], up[0]]) + fr = np.array([B.facing, 0.0]) * abs(math.sin(B.yaw * math.pi / 180)) * W[2] * .18 + hem = pel + (p("kn_n") - pel) * .75 + poly = [che + fr - side * W[3] * .22, che + fr + side * W[3] * .22, pel + fr + side * W[1] * .4, hem + fr + side * W[1] * .42, + hem + fr - side * W[1] * .42, pel + fr - side * W[1] * .4] + return np.array(poly) + + +def head_frame(B): + J = B.J + cr, ch = np.asarray(J["crown"], float), np.asarray(J["chin"], float) + ax = _unit(_v(ch, cr)) # chin -> crown + side = np.array([-ax[1], ax[0]]) # rotate: screen "right" of the head axis when upright is (1, 0) + if side[0] < 0: + side = -side + return cr, ch, ax, side + + +def head_poly(B, look): + """cranium + jaw: an egg on the head axis, wider and deeper in 3/4 and profile; the jaw follows the facing""" + C, s, f = B.C, B.s, B.facing + cr, ch, ax, side = head_frame(B) + hl = float(np.hypot(*(cr - ch))) + th = B.yaw * math.pi / 180 + st = abs(math.sin(th)) + hw = (C["head_w"] * (1 - st) + .92 * st) * hl * .5 # half width: front .75 H, profile ~.92 H (skull depth) + c = ch + ax * hl * .52 + pts = [] + for t in np.linspace(0, 2 * math.pi, 40, endpoint=False): + x, y = math.cos(t), math.sin(t) # y > 0 = toward the chin (down the axis) + r = 1.0 + if y > 0: + r *= 1 - .22 * y * y * (1 - .4 * st) # the jaw narrows toward the chin + px = x * hw * r + py = y * hl * .5 + if st > .2: + # 3/4: the face plane advances toward the facing; the back of the skull bulges behind (profile egg) + if x * f > 0 and y > -.3: + px += f * hw * .08 * st + if x * f < 0 and y < .35: + px -= f * hw * .06 * st + if x * f < 0 and y > .4: + px *= 1 - .3 * st # the neck takes the back of the jaw + pts.append(c + side * px - ax * py) + return np.array(pts) + + +def hair_back_poly(B, look): + st_ = look.get("style", "short") + if st_ not in ("long", "pony"): + return None + cr, ch, ax, side = head_frame(B) + hl = float(np.hypot(*(cr - ch))) + f = B.facing + st = abs(math.sin(B.yaw * math.pi / 180)) + back = -f * st + c = ch + ax * hl * .55 + if st_ == "long": + top = c + ax * hl * .35 + low = ch - ax * hl * (.9 if B.C["age"] >= 10 else .6) + w = hl * .55 + poly = [top - side * w * .9, top + side * w * .9, c + side * w * 1.05 + np.array([back * w * .3, 0]), + low + side * w * .9 + np.array([back * w * .5, 0]), low - side * w * .9 + np.array([back * w * .5, 0]), + c - side * w * 1.05 + np.array([back * w * .3, 0])] + return chaikin(np.array(poly), 2, closed=True) + tail = c + np.array([back * hl * .55, 0]) - ax * hl * .55 + return ribbon([c + np.array([back * hl * .35, 0]), tail], [hl * .32, hl * .14]) + + +def hair_cap_poly(B, look): + """the hair mass on the skull: hairline above the brow, covering the back of the head in 3/4 (human-117)""" + st_ = look.get("style", "short") + if st_ == "bald": + return None + cr, ch, ax, side = head_frame(B) + hl = float(np.hypot(*(cr - ch))) + hp = head_poly(B, look) + c = ch + ax * hl * .52 + f = B.facing + stv = abs(math.sin(B.yaw * math.pi / 180)) + lift = hl * (.06 if st_ != "short" else .04) + keep = [] + for q in hp: + rel = q - c + along = rel @ ax # + toward the crown + across = rel @ side + # hairline: high on the face side, low at the back of the head (3/4), temples + # hairline: across the forehead at 0.143 H below the crown (canon), down the temples, round the back of the + # skull to the nape in 3/4 and profile (human-117) + frac = across * f / max(hl * .5, 1e-6) # +1 face edge, -1 back of the head + if frac > .15: + lim = hl * .3 + else: + lim = hl * .3 - (.15 - frac) / 1.15 * hl * (.25 + .55 * stv) + if st_ in ("long", "pony", "bun") and frac < .2: + lim -= hl * .1 + if along > lim: + keep.append(q + _unit(rel) * lift) + if len(keep) < 3: + return None + keep = np.array(keep) + # close along the hairline (a gentle curve, not a straight cut) + return keep + + +def hand_poly(B, side, look): + """hand glyph by on-screen hand length (human-351/354, copy P10): blob / mitten + thumb / palm + finger mass. + Returns (main polygon, thumb polygon or None); finger separations are added by hand_marks at >= 30 px.""" + C, J, s = B.C, B.J, B.s + wr, hd = np.asarray(J["wr_" + side], float), np.asarray(J["hand_" + side], float) + el = np.asarray(J["el_" + side], float) + u = _unit(_v(wr, hd)) if np.hypot(*_v(wr, hd)) > 1e-3 else _unit(_v(el, wr)) + n = np.array([-u[1], u[0]]) + hl = C["hand"] * s + bw = C["arm_w"][3] * s + act = B.pose.act + if hl < 3.5: + return ellipse(wr + u * hl * .4, max(.7, bw * .62), max(.7, bw * .62)), None + fist = act in ("hold", "carry", "carry_side", "lead", "leash", "reins", "rod", "staff", "cane", "chop", "push", "pull", + "handlebar", "drink", "hold_up", "work_at", "paint") + # the palm faces the body: fingers curl toward the figure's front (relaxed curl 20-35 deg, fist 70+) + fr = n if (n[0] * B.facing) > 0 else -n + W = hl * .44 # breadth .45 of the hand length (human-338) + palm = wr + u * hl * .5 + if fist: + k = palm + fr * W * .1 + pts = [wr - n * bw * .45, wr + n * bw * .45, palm + n * W * .55, k + u * hl * .1 + n * W * .45, + k + u * hl * .18, k + u * hl * .1 - n * W * .45, palm - n * W * .55] + return chaikin(np.array(pts), 2, closed=True), None + curl = .35 if act not in ("wave", "cheer", "point", "reach_up", "feed", "surprised", "scared") else .05 + tipdir = _unit(u + fr * curl) + tip = palm + tipdir * hl * .5 + pts = [wr - n * bw * .45, palm - n * W * .52, tip - n * W * .36, tip + tipdir * hl * .04, tip + n * W * .36, + palm + n * W * .52, wr + n * bw * .45] + poly = chaikin(np.array(pts), 2, closed=True) + thumb = None + if hl >= 8: + tb = wr + u * hl * .2 + fr * W * .38 + thumb = ribbon([tb, tb + _unit(u * .7 + fr * .5) * hl * .36], [W * .36, W * .24]) + return poly, thumb + + +def _stroke(Ly, pts, w, col, alpha=.85, part=None): + P = chaikin(np.asarray(pts, float), 2) + n = len(P) + ws = [w * (.4 + .6 * math.sin(math.pi * (i + .5) / n)) for i in range(n)] # tapered both ends (pressure) + clip = None if part is None else np.isin(Ly.P, [PART_IDS.get(q, -1) for q in part]).astype(np.float32) + _paint(Ly, ribbon(P, ws, cap=True, smooth=0, n_per=2), col, False, None, alpha, clip) + + +def fold_marks(Ly, B, look, sh, style): + """cloth folds from ANCHORS only (human-163, human-373): compression folds inside a bent elbow / knee (human-165), + a few radiating from the crotch toward the forward knee, blouse folds over the belt (human-386), pipe folds down a + skirt (human-169). Count and length grow with the figure (human-396: 1-3 folds at 15-29 px heads, 3-6 above).""" + C, J, s, f = B.C, B.J, B.s, B.facing + p = lambda k: np.asarray(J[k], float) + stature = s * C["N"] + w = max(1.0, stature / 230.0) + many = stature >= 420 + top = look.get("coat") or look.get("dress") or look["top"] + bot = look["bottom"] + # elbows (sleeves only) + if look.get("sleeves", True) or look.get("coat"): + for sd in "nf": + e = B.pose.P["e" + sd] + if e < 25: + continue + sh_, el, wr = p("sh_" + sd), p("el_" + sd), p("wr_" + sd) + inside = _unit(_unit(_v(el, sh_)) + _unit(_v(el, wr))) + col = sh.shadow(scale(top, .86 if sd == "f" else 1.0), "cloth") + for k in range(3 if many else 2): + a = el + inside * C["arm_w"][2] * s * (.15 + .12 * k) + _unit(_v(el, sh_)) * s * .12 * (k - .5) + b = a + _unit(_v(el, wr)) * s * .22 + inside * s * .04 + _stroke(Ly, [a, (a + b) / 2 + inside * s * .03, b], w, col, part=("top", "coat")) + trousers = not (look.get("skirt") or look.get("dress") or look.get("shorts")) + if trousers: + colb = sh.shadow(bot, "cloth") + for sd in "nf": + k_ = B.pose.P["k" + sd] + hip, kn, an = p("hip_" + sd), p("kn_" + sd), p("an_" + sd) + if k_ >= 15: + back = _unit(_unit(_v(kn, hip)) + _unit(_v(kn, an))) + for i in range(2 if not many else 3): + a = kn + back * C["leg_w"][2] * s * (.1 + .1 * i) + _unit(_v(kn, hip)) * s * .1 + b = kn + back * C["leg_w"][2] * s * (.05 + .1 * i) + _unit(_v(kn, an)) * s * .18 + _stroke(Ly, [a, kn + back * C["leg_w"][2] * s * .3, b], w, scale(colb, .95 if sd == "n" else .85), part=("bottom",)) + # break folds over the shoe (human-387: 1-2) + if many: + a = an + _unit(_v(an, kn)) * s * .25 - np.array([f * C["leg_w"][4] * s * .4, 0]) + _stroke(Ly, [a, a + np.array([f * C["leg_w"][4] * s * .8, s * .05])], w, colb, part=("bottom",)) + # crotch: radiating toward the forward knee + cr = p("pelvis") + _unit(_v(p("neck"), p("pelvis"))) * C["hip_d"] * .2 * s + fwd = "n" if (p("kn_n")[0] - p("kn_f")[0]) * f > 0 else "f" + for i in range(2 if not many else 3): + tgt = cr + (p("kn_" + fwd) - cr) * (.35 + .12 * i) + _stroke(Ly, [cr + np.array([0, s * .04 * i]), (cr + tgt) / 2 + np.array([f * s * .03, 0]), tgt], w * .9, colb, part=("bottom",)) + # shirt over the belt + if not (look.get("dress") or look.get("coat")): + pel, wai = p("pelvis"), p("waist") + belt = pel + _v(pel, wai) * .5 + side = np.array([1.0, 0.0]) + colt = sh.shadow(top, "cloth") + for i, o in enumerate((-.25, .05, .3)[:3 if many else 2]): + a = belt + side * o * C["waist_w"] * s - np.array([0, s * .02]) + _stroke(Ly, [a, a + np.array([o * s * .1, -s * .22])], w * .9, colt, part=("top",)) + else: + # skirt / dress: pipe folds from the hip line to the hem (3-5) + if look.get("skirt") or look.get("dress"): + pel = p("pelvis") + hem_y = max(p("kn_n")[1], p("kn_f")[1]) if not look.get("long_skirt") else max(p("an_n")[1], p("an_f")[1]) - s * .2 + if hem_y > pel[1] + s * .5: + colk = sh.shadow(look.get("dress") or bot, "cloth") + n = 3 if not many else 5 + for i in range(n): + o = (i - (n - 1) / 2) / max(1, n - 1) + a = pel + np.array([o * C["hip_w"] * s * .5, s * .35]) + b = np.array([pel[0] + o * C["hip_w"] * s * .85, hem_y - s * .05]) + _stroke(Ly, [a, (a + b) / 2, b], w, colk, .7, part=("bottom",)) + + +def hand_marks(Ly, B, side, col, pixel): + """finger separations: 3 short dark strokes on the finger mass once the hand is >= 30 px (human-351 20-39 row)""" + C, J, s = B.C, B.J, B.s + hl = C["hand"] * s + if hl < 30 or B.pose.act in ("hold", "carry", "carry_side", "lead", "leash", "reins", "rod", "staff", "cane", "chop", + "push", "pull", "handlebar", "drink", "hold_up", "work_at", "paint"): + return + wr, hd = np.asarray(J["wr_" + side], float), np.asarray(J["hand_" + side], float) + u = _unit(_v(wr, hd)) + n = np.array([-u[1], u[0]]) + fr = n if (n[0] * B.facing) > 0 else -n + curl = .35 if B.pose.act not in ("wave", "cheer", "point", "reach_up", "feed", "surprised", "scared") else .05 + tipdir = _unit(u + fr * curl) + palm = wr + u * hl * .5 + W = hl * .44 + for o in (-.22, 0.0, .22): + a = palm + n * W * o + tipdir * hl * .08 + b = palm + n * W * o * .9 + tipdir * hl * .42 + _paint(Ly, ribbon([a, b], [max(.8, hl * .025), max(.6, hl * .015)], cap=False), col, pixel, None) + + +def foot_poly(B, side): + """shoe = foot + upper (human-365); length 1.1 H (human-359); front views still show a short wedge (human-371)""" + C, J, s, f = B.C, B.J, B.s, B.facing + an, heel, toe = (np.asarray(J[k + side], float) for k in ("an_", "heel_", "toe_")) + fl = C["foot"] * s + d = toe - heel + L = float(np.hypot(*d)) + if L < fl * .5: + # foreshortened (front-ish view): the foot points out a little and down the screen (toward the viewer) + d = np.array([f * .55, .35]) * fl * .6 + d * .5 + toe = heel + d + L = float(np.hypot(*d)) + u = _unit(d) + nrm = np.array([-u[1], u[0]]) + if nrm[1] < 0: + nrm = -nrm # the sole side is down on screen + hgt = max(1.0, C["leg_w"][4] * s * 1.05) + sole_h = an + nrm * hgt * .55 + pts = [an - nrm * hgt * .45 - u * hgt * .2, an - u * hgt * .5 + nrm * hgt * .1, heel + nrm * hgt * .5, + toe + nrm * hgt * .45, toe + u * hgt * .1 - nrm * hgt * .05, an + u * L * .45 - nrm * hgt * .35] + return chaikin(np.array(pts), 1, closed=True) + + +# ------------------------------------------------------------------------------------------------ draw +GROUPS = (("legs", ("leg_f", "thighs", "pelvis", "leg_n")), ("arm_n", ("upper_n", "fore_n")), ("arm_f", ("upper_f", "fore_f"))) + + +def _group_of(name, parts_by_name): + """garments drawn as ONE mass when their members share a colour (trousers = both legs + the seat; a sleeve = + upper arm + forearm): one fill and one designed shadow over the union, so the garment reads as cloth, not tubes""" + for g, members in GROUPS: + if name in members: + cols = {tuple(parts_by_name[m][5]) for m in members if m in parts_by_name} + if len(cols) == 1: + return g, [m for m in members if m in parts_by_name] + return None, None + + +def render(B, look, style="paint", light=(-.6, -.65), sky=(150, 190, 240), key=(255, 248, 235), night=False, + pixel=False, line=None, post_lines=False, text="", seed=0): + """draw the posed figure into a Layer (canvas px); returns the Layer (C rgb 0..255, A alpha, P part ids)""" + head = None + hl = B.s + import os as _os + if hl >= 56 and not pixel and "body2d_head=1" in _os.environ.get("PYDRAW_EXP", ""): # R1: opt-in (skin match open) + from .body_head import portrait_head + head = portrait_head(B, look, style, text, seed, hl) + if head is not None and head[4] is not None and style != "ink": + look = dict(look, skin=tuple(float(v) for v in head[4])) + xs = [v[0] for v in B.J.values()] + ys = [v[1] for v in B.J.values()] + pad = B.s * 1.3 + 3 + x0, y0 = int(math.floor(min(xs) - pad)), int(math.floor(min(ys) - pad)) + x1, y1 = int(math.ceil(max(xs) + pad)), int(math.ceil(max(ys) + pad)) + stature = B.s * B.C["N"] + ss = 4 if stature < 120 else (3 if stature < 400 else 2) + Ly = Layer(x0, y0, x1 - x0, y1 - y0, ss) + sh = Shades(light, sky, key, night, stature, style) + if style == "anime": + sh.levels = 2 # cel: one shadow tone per material (A2), no halftone / lit band + sh.soft = post_lines # a comic pass inks colour edges: keep the cel step under its threshold + parts = build_parts(B, look, style) + if look.get("armour"): + parts = [(q[0], q[1], q[2], q[3], "metal" if q[4] == "cloth" and q[3] in ("top", "bottom", "shoes", "coat") else q[4], q[5]) + for q in parts] + if head is not None and style != "ink": + parts = [q for q in parts if q[0] not in ("hair_back", "head")] + byname = {p_[0]: p_ for p_ in parts} + line_col = line or (scale(look.get("hair", (40, 34, 30)), .35) if style == "anime" else (38, 32, 28)) + lw_hi = 0 + if style in ("ink", "anime") and not pixel and not post_lines: + lw_hi = max(1.0, stature / 300.0) * ss * (1.0 if style == "anime" else 1.15) + inner = stature >= 110 # inner lines only once the parts are big enough to hold them (line hierarchy) + done = set() + for name, _k, poly, pid, mat, col in parts: + if name in done or poly is None or (not isinstance(poly, list) and len(poly) < 3): + continue + g, members = _group_of(name, {k: v for k, v in byname.items() if v[2] is not None}) + if g: + masks = {} + for mname in members: + mm_ = Ly.mask_hi(byname[mname][2]) + masks[mname] = (mm_ > .5).astype(np.float32) if pixel else mm_ + done.add(mname) + m = np.zeros_like(Ly.U) + for mm_ in masks.values(): + m = np.maximum(m, mm_) + else: + masks = None + m = Ly.mask_hi(poly) + if pixel: + m = (m > .5).astype(np.float32) + done.add(name) + if not m.any(): + continue + ys_, xs_ = np.nonzero(m > .5) + if len(xs_) == 0: + continue + # designed shadow shape: the part minus itself shifted toward the light (a band away from the light). Its + # width is a share of the part's own width across the light (copy P7 0.2-0.4) + if g in ("legs", "arm_n", "arm_f"): + wpx = (B.C["leg_w"][1] if g == "legs" else B.C["arm_w"][1]) * B.s * ss + ext = wpx * 1.1 + else: + pr = xs_ * sh.lx + ys_ * sh.ly + ext = float(pr.max() - pr.min()) + share = .32 if mat != "skin" else .28 + if name in ("torso", "pelvis", "skirt", "coat_tail", "thighs"): + share = .34 + if name.startswith(("hand", "foot", "wrist", "thumb")): + share = .4 + dsh = max(ss * 1.0, share * ext) + # the shadow shape is designed on the part's simplified (rounded) silhouette: notches and concavities do not + # spawn extra wedges of shadow (big shapes first) + ms = m if (pixel or dsh < 3 * ss) else (_blur(m, dsh * .35) > .5).astype(np.float32) + shadow_m = np.clip(ms - _shift(ms, sh.lx * dsh, sh.ly * dsh), 0, 1) * m + far = (g == "arm_f") or (g is None and (name.endswith("_f") or name in ("hair_back",))) + base = scale(col, .86) if far else col # far limbs one step darker (P6 / 3/4 depth) + if night: + base = mix(base, scale(sky, .5), .25) + cols = [(m, base)] + if masks is not None and "leg_f" in masks and "leg_n" in masks: + # the far leg one step darker where the near leg does not cover it + cols.append((masks["leg_f"] * (1 - masks["leg_n"]), scale(base, .88))) + sc = sh.shadow(base, mat) + if style == "paint" and not pixel: + shadow_m = _blur(shadow_m, ss * max(.6, stature / 300.0)) * m + cols.append((shadow_m, sc)) + if sh.levels >= 3 and not pixel: + half = np.clip(ms - _shift(ms, sh.lx * dsh * 1.35, sh.ly * dsh * 1.35), 0, 1) * (1 - shadow_m) * m + if style == "paint": + half = _blur(half, ss) * m + cols.insert(1, (half * .55, sh.half(base, mat))) + if (sh.levels >= 3 and not pixel) or (pixel and stature >= 100): + lit = np.clip(ms - _shift(ms, -sh.lx * dsh * .3, -sh.ly * dsh * .3), 0, 1) * m + cols.append((lit * (.7 if not pixel else 1.0), sh.light(base, mat))) + if sh.levels >= 4 and not pixel: + # reflected light: a thin band inside the shadow along its far edge (lit by the ground) + refl = np.clip(shadow_m - _shift(m, -sh.lx * dsh * .1, -sh.ly * dsh * .1), 0, 1) * shadow_m + cols.append((refl * .35, mix(sc, base, .45))) + M1 = Ly.down(m) + for mm, cc in cols: + mm1 = Ly.down(mm) if mm is not m else M1 + if pixel: + mm1 = (mm1 > .5).astype(np.float32) * (M1 > .5) + a = mm1[..., None] + Ly.C = Ly.C * (1 - a) + np.asarray(cc, np.float32) * a + if masks is not None and "leg_n" in masks and stature >= 90 and not lw_hi: + # the near leg's inside contour against the far leg: a shadow line (overlap reads as depth, human-150) + e = np.clip(masks["leg_n"] - _erode(masks["leg_n"], max(1, ss * .8)), 0, 1) * (masks.get("leg_f", 0) * 1.0) + if "pelvis" in masks or "thighs" in masks: + e = e * (1 - _dilate(np.maximum(masks.get("pelvis", 0 * m), masks.get("thighs", 0 * m)), ss)) + if not isinstance(e, float): + e1 = Ly.down(e) + if pixel: + e1 = (e1 > .5).astype(np.float32) + Ly.C = Ly.C * (1 - e1[..., None] * .8) + np.asarray(scale(sc, .8), np.float32) * e1[..., None] * .8 + Ly.A = np.maximum(Ly.A, M1 if not pixel else (M1 > .5).astype(np.float32)) + Ly.P[M1 > .5] = PART_IDS.get(pid, 0) + if lw_hi and (inner or name in ("head",)): + # key line laid with each shape (later shapes hide earlier lines); inner lines thinner (line hierarchy) + e = np.clip(m - _erode(m, lw_hi * .55), 0, 1) + if masks is not None and "leg_n" in masks: + en = np.clip(masks["leg_n"] - _erode(masks["leg_n"], lw_hi * .5), 0, 1) + if "pelvis" in masks or "thighs" in masks: + en = en * (1 - _dilate(np.maximum(masks.get("pelvis", 0 * m), masks.get("thighs", 0 * m)), lw_hi)) + e = np.maximum(e, en) + e1 = Ly.down(e)[..., None] + Ly.C = Ly.C * (1 - e1) + np.asarray(line_col, np.float32) * e1 + Ly.U = np.maximum(Ly.U, m) + if lw_hi: + # silhouette line heavier than the inner lines (human line weight rules) + e = np.clip(Ly.U - _erode(Ly.U, lw_hi * 1.15), 0, 1) + e1 = Ly.down(e)[..., None] + Ly.C = Ly.C * (1 - e1) + np.asarray(line_col, np.float32) * e1 + for sd in ("f", "n"): + hand_marks(Ly, B, sd, sh.shadow(look.get("mittens") or look["skin"], "skin"), pixel) + if not pixel and stature >= 200: + fold_marks(Ly, B, look, sh, style) + if head is not None: + from .body_head import paste + paste(Ly, head, B.J["crown"], B.J["chin"]) + # the near arm stays in front of the head when it is raised across it + return Ly + hair_and_face(Ly, B, look, sh, style, pixel, line_col) + return Ly + + +def _paint(Ly, poly, col, pixel, pid=None, alpha=1.0, clip=None): + if poly is None or len(poly) < 3: + return None + m = Ly.mask_hi(poly) + m1 = Ly.down(m) + if pixel: + m1 = (m1 > .5).astype(np.float32) + if clip is not None: + m1 = m1 * clip + a = (m1 * alpha)[..., None] + Ly.C = Ly.C * (1 - a) + np.asarray(col, np.float32) * a + Ly.A = np.maximum(Ly.A, m1 * alpha) + if pid is not None: + Ly.P[m1 > .5] = PART_IDS.get(pid, 0) + return m + + +def hair_and_face(Ly, B, look, sh, style, pixel, line_col): + """hair cap, then face features as symbols sized for the head's pixels (copy P10, human-396 ladder)""" + cr, ch, ax, side = head_frame(B) + hl = float(np.hypot(*(cr - ch))) + f = B.facing + st = abs(math.sin(B.yaw * math.pi / 180)) + ct = abs(math.cos(B.yaw * math.pi / 180)) + hair = look.get("hair", (60, 40, 30)) + if look.get("helm"): + # a great helm: the head mass in steel, a dark visor slit at the eye line, a lit band on the light side + hp = head_poly(B, look) + hp = (hp - (ch + ax * hl * .5)) * 1.1 + (ch + ax * hl * .5) + mc = look.get("top", (150, 155, 166)) + m = _paint(Ly, hp, mc, pixel, "metal") + if m is not None: + dsh = max(Ly.ss, .32 * hl * Ly.ss) + shm = Ly.down(np.clip(m - _shift(m, sh.lx * dsh, sh.ly * dsh), 0, 1)) + if pixel: + shm = (shm > .5).astype(np.float32) + Ly.C = Ly.C * (1 - shm[..., None]) + np.asarray(sh.shadow(mc, "metal"), np.float32) * shm[..., None] + eye = (ch + ax * hl * .5) + side * B.facing * hl * .2 * abs(math.sin(B.yaw * math.pi / 180)) + hw_ = hl * .42 + _paint(Ly, ribbon([eye - side * hw_ * .8, eye + side * hw_ * .9], [max(1.0, hl * .07), max(1.0, hl * .07)], cap=False), + (24, 22, 28), pixel, "metal") + return + cap = hair_cap_poly(B, look) + if cap is not None: + m = _paint(Ly, cap, hair, pixel, "hair") + if m is not None and hl >= 10: + ys_, xs_ = np.nonzero(m > .5) + dsh = max(Ly.ss, .3 * hl * Ly.ss) + shm = np.clip(m - _shift(m, sh.lx * dsh, sh.ly * dsh), 0, 1) + a = Ly.down(shm) + if pixel: + a = (a > .5).astype(np.float32) + Ly.C = Ly.C * (1 - a[..., None]) + np.asarray(sh.shadow(hair, "hair"), np.float32) * a[..., None] + if cap is not None and hl >= 24 and not pixel: + # lock masses: a few tapered strokes from the parting toward the hairline in the hair's shadow tone, more + # with size (human-396 detail ladder; hair as masses, not strands) + n = 3 if hl < 48 else 5 + part_pt = cr - ax * hl * .04 + side * f * hl * .1 + hc = sh.shadow(hair, "hair") + for i in range(n): + t = (i + .5) / n + ang = math.pi * (.15 + .7 * t) + end = (ch + ax * hl * .52) + (side * math.cos(ang) * -f + ax * math.sin(ang) * .2) * hl * .5 + mid = (part_pt + end) / 2 + ax * hl * .06 + _stroke(Ly, [part_pt, mid, end], max(1.0, hl * .035), hc, .55, part=("hair",)) + if look.get("style") == "bun": + c = cr - ax * hl * .02 + np.array([-f * st * hl * .3, 0]) + _paint(Ly, ellipse(c, hl * .22, hl * .2), hair, pixel, "hair") + if look.get("beard") and hl >= 6: + # the beard wraps the jaw from ear to ear and stays below the mouth (faces lane note: never across it) + hp = head_poly(B, look) + c0 = ch + ax * hl * .5 + rel = hp - c0 + low = hp[(rel @ ax) < -hl * .12] + if len(low) >= 3: + chin_pt = ch - ax * hl * (.07 if not look.get("beard_col") else .25) + _paint(Ly, chaikin(np.vstack([low, chin_pt[None]]), 1, closed=True), look.get("beard_col") or hair, pixel, "hair") + if hl < 5: + return + # face centre line: advances toward the facing with the turn (3/4: about a third of the half width) + hw = (B.C["head_w"] * (1 - st) + .92 * st) * hl * .5 + cx = (ch + ax * hl * .5) + side * f * hw * .62 * st + kid = B.C["age"] < 13 + eye_y = .44 if kid else .5 # human-471: the eye line is lower in children + eye_c = cx - ax * hl * (eye_y - .5) + dark = (30, 24, 26) if not look.get("eye") else scale(look["eye"], .4) + sep = hw * .42 * (ct * .85 + .15) + eyes = [eye_c - side * f * sep, eye_c + side * f * sep] if B.yaw < 72 else [eye_c - side * f * sep * .3] + if st > .45 and len(eyes) == 2: + eyes[1] = eye_c + side * f * sep * .75 # the far eye foreshortens toward the profile edge + r = max(.55, hl * (.05 if not kid else .062) * (1.25 if pixel else 1.0)) # pixel eyes read a size up + if hl < 14: + for e in eyes[:1 if B.yaw > 60 else 2]: + _paint(Ly, ellipse(e, r * .9, r * 1.1), dark, pixel, "face") + return + # 14+ px heads: brows, eyes with a white at 30+, nose shadow, mouth stroke + for i, e in enumerate(eyes): + k = 1.0 if i == 0 else .8 + ang = math.atan2(side[1], side[0]) + if hl >= (12 if pixel else 56): # pixel: a white + dark pupil from 12 grid px, so eyes read on any skin (critic13 12) + # the eye opening (a softened white, never paper white), iris toward the gaze, upper lid line (human-054/122) + _paint(Ly, ellipse(e, r * 1.6 * k, r * .78, ang), mix(look["skin"], (246, 242, 236), .6), pixel, "face") + _paint(Ly, ellipse(e + side * f * r * .3, r * .62 * k, r * .74), dark, pixel, "face") + _paint(Ly, ribbon([e - side * r * 1.6 * k - ax * r * .05, e + ax * r * .55, e + side * r * 1.6 * k - ax * r * .1], + [r * .3, r * .38, r * .22]), scale(line_col, 1.0), pixel, "face") + else: + _paint(Ly, ellipse(e, r * .7 * k, r * .95, ang), dark, pixel, "face") + if hl >= 20: + # brow: low at the inner end, arching to its peak two thirds out (a neutral brow; expressions are the + # faces lane's), never slanting down at the outer end (read as sad at 400+ px, looked) + inn = side * (1.0 if float((eye_c - e) @ side) >= 0 else -1.0) + _paint(Ly, ribbon([e + ax * r * 2.0 + inn * r * 1.2 * k, e + ax * r * 2.45 - inn * r * .5 * k, + e + ax * r * 2.2 - inn * r * 1.45 * k], [r * .34, r * .3, r * .16]), + mix(look["skin"], scale(look.get("hair", dark), .7), .7), pixel, "face") + skin = look["skin"] + nose = cx - ax * hl * (.72 - .5) + side * f * hw * .08 * (1 + st) + _paint(Ly, ellipse(nose, hl * .05, hl * .07), sh.shadow(skin, "skin"), pixel, "face") + if B.yaw > 74: + # profile: the nose breaks the face contour (a small wedge in the skin colour beyond the face edge) + hp = head_poly(B, look) + c0 = ch + ax * hl * .5 + band = hp[np.abs((hp - c0) @ ax + hl * .15) < hl * .14] + if len(band): + edge = band[np.argmax((band @ side) * f)] + tip = edge + side * f * hl * (.06 if B.C["sex"] == "m" and B.C["age"] >= 13 else .04) * st - ax * hl * .1 + _paint(Ly, np.array([edge + ax * hl * .1, tip, edge - ax * hl * .12, edge - side * f * hl * .05]), skin, pixel, "face") + mouth = cx - ax * hl * (.82 - .5) + side * f * hw * .05 + mw = hw * .34 * (ct * .7 + .3) + _paint(Ly, ribbon([mouth - side * mw, mouth + side * mw], [max(.6, hl * .026), max(.6, hl * .02)]), + mix(sh.shadow(skin, "skin"), (150, 70, 66), .3), pixel, "face") + if st > .25 and hl >= 18: + ear = (ch + ax * hl * .52) - side * f * hw * (.25 + .2 * st) + _paint(Ly, ellipse(ear, hl * .07, hl * .12), sh.half(skin, "skin"), pixel, "face") + if hl >= 56 and not pixel: + # detail grows with size (WAVE20: 1024 must show more): lips as two masses (upper darker, lower lit), the + # nostril, the lid crease, a catch light, the cheek plane lit, the ear's inner shadow (human-117/122/058) + lipc = mix(skin, (170, 80, 76), .45) + _paint(Ly, ribbon([mouth - side * mw * .85 + ax * hl * .012, mouth + ax * hl * .03, mouth + side * mw * .85 + ax * hl * .012], + [hl * .02, hl * .034, hl * .02]), scale(lipc, .82), pixel, "face") + _paint(Ly, ribbon([mouth - side * mw * .6 - ax * hl * .03, mouth + side * mw * .6 - ax * hl * .03], + [hl * .028, hl * .024]), mix(lipc, skin, .35), pixel, "face") + _paint(Ly, ellipse(nose - ax * hl * .02 + side * f * hl * .02, hl * .018, hl * .012), sh.shadow(sh.shadow(skin, "skin"), "skin"), + pixel, "face") + for i, e in enumerate(eyes): + k = 1.0 if i == 0 else .8 + _paint(Ly, ribbon([e + ax * r * 1.25 - side * r * 1.4 * k, e + ax * r * 1.5, e + ax * r * 1.2 + side * r * 1.4 * k], + [r * .14, r * .18, r * .12]), sh.shadow(skin, "skin"), pixel, "face") + _paint(Ly, ellipse(e + side * f * r * .1 + ax * r * .25, r * .16, r * .16), (250, 248, 244), pixel, "face") + cheek = cx - ax * hl * .12 - side * f * hw * .3 * (1 if st > .2 else 0) + _paint(Ly, ellipse(cheek, hl * .12, hl * .08), mix(skin, (235, 150, 140), .18), pixel, "face", .5) + if st > .25: + _paint(Ly, ellipse(ear + side * f * hl * .01, hl * .035, hl * .07), sh.shadow(skin, "skin"), pixel, "face") + + +def stamp(cv, Ly, cid, part_base=None, pixel=False): + """write the layer into a pydraw Canvas (list-of-lists px, ids, parts) over the covered pixels""" + H, W = cv.h, cv.w + xa, ya = max(0, Ly.x0), max(0, Ly.y0) + xb, yb = min(W, Ly.x0 + Ly.w), min(H, Ly.y0 + Ly.h) + if xa >= xb or ya >= yb: + return + A = Ly.A[ya - Ly.y0:yb - Ly.y0, xa - Ly.x0:xb - Ly.x0] + C = Ly.C[ya - Ly.y0:yb - Ly.y0, xa - Ly.x0:xb - Ly.x0] + P = Ly.P[ya - Ly.y0:yb - Ly.y0, xa - Ly.x0:xb - Ly.x0] + if getattr(cv, "part", None) is None and cid is not None: + cv.set_part(1) + cv.set_part(None) + parts = getattr(cv, "part", None) + ys, xs = np.nonzero(A > (.5 if pixel else .004)) + a_ = A[ys, xs].tolist() + c_ = C[ys, xs].tolist() + p_ = P[ys, xs].tolist() + px, ids = cv.px, cv.ids + lay = getattr(cv, "layer", None) + for y, x, a, c, pp in zip((ys + ya).tolist(), (xs + xa).tolist(), a_, c_, p_): + if pixel: + a = 1.0 + q = px[y][x] + q[0] += (c[0] - q[0]) * a + q[1] += (c[1] - q[1]) * a + q[2] += (c[2] - q[2]) * a + if a >= .5 and cid is not None: + ids[y][x] = cid + if parts is not None: + parts[y][x] = pp + if lay is not None: + lay[y, x] = 0 diff --git a/pydraw/figure/body_head.py b/pydraw/figure/body_head.py new file mode 100644 index 0000000000000000000000000000000000000000..251aa3745ec6782065bd4e098995042c12517a2f --- /dev/null +++ b/pydraw/figure/body_head.py @@ -0,0 +1,125 @@ +"""Big full figures borrow the portrait path's head (wave 20 body lane, knob body2d_head, default on under body2d). + +At a head of >= 56 px (figures >= ~400 px tall) a symbol face is too thin: the figure takes the FACES lane's +2D-first head (figure.build_figure closeup + the style module) for the same person, cut out by its own masks +(face, ears, hair, beard; never the portrait's neck or torso) and laid on the body's crown -> chin axis. The body's +skin then takes the portrait's skin colour so neck and hands match. Returns None for anything it cannot do (pixel, +profile turns beyond the portrait path's range, no style module).""" +import math +import numpy as np +from PIL import Image + + +def _head_text(look, age, sex, text): + hs = {"short": "short", "long": "long", "pony": "ponytail", "bun": "bun", "bald": "bald"}.get(look.get("style"), "short") + who = ("old " if age >= 60 else "") + ({True: "girl" if age < 13 else "woman", False: "boy" if age < 13 else "man"}[sex == "f"]) + return "portrait of a %s with %s hair%s" % (who, hs, " and a beard" if look.get("beard") else "") + + +def portrait_head(B, look, style, text="", seed=0, hl_px=60): + """(rgb HxWx3 float 0..255, alpha HxW, crown xy, chin xy) of the portrait path's head drawn so crown->chin is + about hl_px, or None""" + if style not in ("anime",): + return None # paint / ink portraits do not cut out cleanly yet (looked: hard block, paper halo) + yaw_b = B.yaw + if yaw_b > 66 and style not in ("pixel", "anime"): + return None # pixel / anime heads may turn toward the viewer on a walking body (look-at) + try: + from . import build_figure, style_module, fig_masks + from .layout import Pose + except Exception: + return None + mod = style_module(style) + if mod is None: + return None + age, sex = B.C["age"], B.C["sex"] + t = _head_text(look, age, sex, text) + hyaw = B.facing * min(34.0, yaw_b * .75) + pose = Pose(yaw=hyaw, pitch=-B.pose.P.get("hp", 0) * .4, roll=0.0) + try: + size = 384 + fig = build_figure(t, style, size, seed, framing="closeup", pose=pose) + L = fig.layout + cr, ch = L.proj(np.array([(0, .5, 0), (0, -.5, 0)], np.float32)) + hl0 = float(np.hypot(*(np.asarray(cr) - np.asarray(ch)))) + if hl0 < 8: + return None + size2 = int(max(160, min(1024, size * hl_px * 1.0 / hl0))) + if hasattr(mod, "work_size"): + pass + fig = build_figure(t, style, size2, seed, framing="closeup", pose=pose) + img = np.asarray(mod.render(fig, size2, seed, [])) + if img.dtype != np.uint8: + img = (np.clip(img, 0, 1) * 255) if img.max() <= 1.0 else np.clip(img, 0, 255) + img = np.asarray(img, np.float32)[..., :3] + if img.shape[0] != size2: + img = np.asarray(Image.fromarray(img.astype(np.uint8)).resize((size2, size2), Image.LANCZOS), np.float32) + M = fig_masks(fig) + L = fig.layout + cr, ch = L.proj(np.array([(0, .5, 0), (0, -.5, 0)], np.float32)) + hh = float(ch[1] - cr[1]) + ys = np.arange(M["face"].shape[0])[:, None] + z = 0 * M["face"] + facey = np.maximum.reduce([M["face"], M.get("ear_L", z), M.get("ear_R", z), M.get("beard", z)]) * (ys < ch[1] + hh * .04) + # the hair falls to the shoulders at most; the portrait's neck and collar never come along + a = np.maximum(facey, M["hair"] * (ys < ch[1] + hh * .35)) + # the portrait's own background never comes along: alpha falls off where the pixel is close to the colour of + # the frame's border (hair gaps in paint, paper between ink strokes) + border = np.concatenate([img[:4].reshape(-1, 3), img[:, :4].reshape(-1, 3), img[:, -4:].reshape(-1, 3)]) + bgc = np.median(border, 0) + d = np.abs(img - bgc).sum(-1) + keep = np.clip((d - 18.0) / 40.0, 0, 1) + if style == "ink": + a = a * keep # ink: the strokes only, laid over the body's own head mass + else: + a = a * np.maximum(keep, facey) + # skin from the cheek (a small disc below the face centre), so the body's neck and hands match the face + c = (np.asarray(cr) + np.asarray(ch)) / 2 + np.array([0, hh * .16]) + yy, xx = np.mgrid[0:img.shape[0], 0:img.shape[1]] + disc = ((xx - c[0]) ** 2 + (yy - c[1]) ** 2 < (hh * .07) ** 2) & (M["face"] > .9) + skin = img[disc] + sk = tuple(np.median(skin, 0)) if len(skin) > 8 else None + return img, a.astype(np.float32), np.asarray(cr, float), np.asarray(ch, float), sk + except Exception: + return None + + +def paste(Ly, head, crown, chin): + """lay the portrait head on the layer: similarity transform crown/chin (portrait) -> crown/chin (body)""" + img, a, pcr, pch = head[:4] + v_src = pch - pcr + v_dst = np.asarray(chin, float) - np.asarray(crown, float) + ls, ld = np.hypot(*v_src), np.hypot(*v_dst) + if ls < 1e-3 or ld < 1e-3: + return + k = ld / ls + ang = math.atan2(v_dst[1], v_dst[0]) - math.atan2(v_src[1], v_src[0]) + ca, sa = math.cos(ang), math.sin(ang) + # inverse map: dst (layer px) -> src + ox, oy = Ly.x0, Ly.y0 + H, W = Ly.h, Ly.w + yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) + dx = xx + ox - crown[0] + dy = yy + oy - crown[1] + sx = (ca * dx + sa * dy) / k + pcr[0] + sy = (-sa * dx + ca * dy) / k + pcr[1] + hs, ws = a.shape + ok = (sx >= 0) & (sy >= 0) & (sx < ws - 1) & (sy < hs - 1) + if not ok.any(): + return + ys_, xs_ = np.nonzero(ok) + x0 = sx[ok]; y0 = sy[ok] + xi, yi = x0.astype(int), y0.astype(int) + fx, fy = x0 - xi, y0 - yi + + def samp(arr): + return (arr[yi, xi] * ((1 - fx) * (1 - fy))[..., None] if arr.ndim == 3 else arr[yi, xi] * (1 - fx) * (1 - fy)) + \ + (arr[yi, xi + 1] * (fx * (1 - fy))[..., None] if arr.ndim == 3 else arr[yi, xi + 1] * fx * (1 - fy)) + \ + (arr[yi + 1, xi] * ((1 - fx) * fy)[..., None] if arr.ndim == 3 else arr[yi + 1, xi] * (1 - fx) * fy) + \ + (arr[yi + 1, xi + 1] * (fx * fy)[..., None] if arr.ndim == 3 else arr[yi + 1, xi + 1] * fx * fy) + al = samp(a) + col = samp(img) + cur = Ly.C[ys_, xs_] + Ly.C[ys_, xs_] = cur * (1 - al[:, None]) + col * al[:, None] + Ly.A[ys_, xs_] = np.maximum(Ly.A[ys_, xs_], al) + Ly.P[ys_[al > .5], xs_[al > .5]] = 100 diff --git a/pydraw/figure/body_pose.py b/pydraw/figure/body_pose.py new file mode 100644 index 0000000000000000000000000000000000000000..70c8c179e0acd4f95cdc086bcf6d4763ca62c898 --- /dev/null +++ b/pydraw/figure/body_pose.py @@ -0,0 +1,473 @@ +"""Verb -> pose library and the 2D-first pose solver for full figures (wave 20, body lane). Pure code. + +A pose is a set of joint-angle RANGES chosen from the VERB (sampled by the seed), not a typed figure. Angles are +world-frame sagittal angles, the way an illustrator states a gesture ("the arm hangs plumb", "the thigh is level"): + lean torso tilt from vertical, + forward (copy P1: standing 0-5, bending 60-120, wind 10-30) + bend extra chest tilt over the pelvis (spine bend, copy P1 30-80 for bending) + pel / chs pelvis and shoulder roll (+ = the near side up); contrapposto = opposite signs (human-189, human-457) + hp / hr head pitch (+ = looks down) and roll + h* k* a* f* thigh angle from plumb (+ forward), knee flexion (>= 0: knees only bend one way), hip abduction, ankle + s* e* b* w* upper-arm angle from plumb (+ forward, 180 = straight up), elbow flexion (>= 0), arm abduction, wrist + suffix n = near limb (toward the viewer), f = far limb. Near and far always differ (copy P6). +3D is only a helper: the figure turns by `yaw` (0 = front, 90 = profile) and is projected orthographically. +Balance: the centre of mass (head 1, chest 3, pelvis 2, limbs) is pushed over the support feet by moving the +pelvis back or forward (copy P12, human-012), and planted feet are solved onto the ground by 2-bone IK. +""" +import math +from .body_canon import srng + +D2R = math.pi / 180.0 + + +def _R(lo, hi=None): + return (lo, lo if hi is None else hi) + + +# --------------------------------------------------------------------------------------------- pose library +# Every value is a (lo, hi) range in degrees. Missing keys take the NEUTRAL range. `support` names the weight carriers +# (human-012), `ground` how the figure sits on the ground, `plant` the feet solved onto the ground. +NEUTRAL = dict(yaw=(30, 55), lean=(0, 3), bend=(0, 3), pel=(0, 0), chs=(0, 0), hp=(-2, 6), hr=(-4, 4), ht=(0, 0), + hn=(2, 6), kn=(2, 6), an=(3, 6), fn=(0, 0), hf=(-2, 2), kf=(0, 4), af=(3, 6), ff=(0, 0), + sn=(2, 10), en=(10, 22), bn=(5, 10), wn=(0, 10), sf=(-4, 6), ef=(12, 28), bf=(5, 10), wf=(0, 10)) + +POSES = { + # contrapposto: weight on the far leg, pelvis tilts up on that side, shoulders the other way, free knee bent + # (human-031, human-189, human-457: no part plumb, one knee bent, pelvis shift 0.1-0.25 H, feet differ 10-30 deg) + "stand": dict(yaw=(28, 58), lean=(-1, 3), bend=(1, 5), pel=(-9, -4), chs=(3, 7), hp=(-3, 7), hr=(-7, 7), + hn=(4, 12), kn=(12, 26), an=(5, 11), fn=(6, 16), hf=(-3, 2), kf=(0, 4), af=(1, 4), + sn=(-6, 8), en=(8, 26), bn=(6, 12), sf=(-2, 10), ef=(8, 24), bf=(5, 10), + support="far", ground="feet", plant=("f", "n")), + # walk, contact phase (front leg straight heel down, back leg toe-off), arms counter-swing (human-039) + "walk": dict(yaw=(62, 86), lean=(3, 8), bend=(0, 4), pel=(-3, 3), chs=(-3, 3), hp=(-2, 8), + hn=(16, 25), kn=(2, 8), fn=(-10, -4), hf=(-24, -16), kf=(14, 30), ff=(18, 34), + sn=(-24, -12), en=(12, 28), sf=(14, 28), ef=(18, 40), bn=(4, 8), bf=(4, 8), + support="both", ground="feet", plant=("n", "f"), swap=True), + # run: lean 12-22, knee drive, arms bent near 90 (scale.md P1 stride) + "run": dict(yaw=(70, 88), lean=(12, 22), bend=(2, 8), hp=(-6, 4), + hn=(42, 62), kn=(62, 96), fn=(-5, 15), hf=(-38, -24), kf=(24, 52), ff=(20, 45), + sn=(-44, -26), en=(70, 95), sf=(24, 42), ef=(56, 76), bn=(4, 10), bf=(4, 10), + support="air", ground="feet", plant=(), swap=True, lift=(.03, .06)), + # chair / bench: thighs near level, shins near plumb, >= 2 asymmetries (human-045, phys-015 trunk back 5-20) + "sit": dict(yaw=(24, 60), lean=(-12, 2), bend=(2, 8), pel=(-3, 3), chs=(-4, 4), hp=(0, 12), hr=(-6, 6), + hn=(78, 92), kn=(78, 96), an=(4, 10), fn=(-5, 5), hf=(70, 86), kf=(92, 118), af=(2, 6), ff=(-5, 10), + sn=(14, 32), en=(48, 80), bn=(4, 10), sf=(4, 22), ef=(40, 70), bf=(6, 12), + support="seat", ground="seat", plant=("n", "f")), + "sit_ground": dict(yaw=(40, 72), lean=(-14, 4), bend=(4, 12), hp=(0, 12), + hn=(58, 76), kn=(80, 115), an=(6, 12), fn=(-10, 5), hf=(72, 86), kf=(25, 55), af=(4, 8), + sn=(-40, -26), en=(0, 10), bn=(8, 14), sf=(30, 50), ef=(40, 70), bf=(4, 8), + support="pelvis", ground="pelvis", plant=()), + "cross_legged": dict(yaw=(10, 35), lean=(-2, 6), bend=(2, 8), hp=(2, 12), + hn=(68, 80), kn=(130, 148), an=(24, 34), hf=(68, 80), kf=(132, 150), af=(24, 34), + sn=(10, 22), en=(30, 50), bn=(14, 22), sf=(10, 22), ef=(30, 50), bf=(14, 22), + support="pelvis", ground="pelvis", plant=()), + # one knee down: support thigh near plumb, shin along the ground; the other foot flat, knee up (human-012) + "kneel": dict(yaw=(55, 82), lean=(2, 12), bend=(2, 8), hp=(6, 18), + hn=(70, 88), kn=(78, 96), fn=(-4, 4), hf=(-4, 6), kf=(86, 96), ff=(70, 90), + sn=(22, 38), en=(4, 24), sf=(-6, 6), ef=(6, 22), + support="knee", ground="knee", plant=()), + "kneel2": dict(yaw=(55, 80), lean=(-4, 8), bend=(0, 6), hp=(14, 30), + hn=(-4, 6), kn=(86, 96), fn=(70, 90), hf=(-4, 6), kf=(86, 96), ff=(70, 90), + sn=(36, 56), en=(96, 120), sf=(36, 56), ef=(96, 120), bn=(0, 4), bf=(0, 4), + support="knees", ground="knee", plant=()), + # bend over / glean / pick up: torso tilt 60-120, spine bend 30-80, head 1-2 H ahead, hips back (copy P1, P12) + "bend": dict(yaw=(66, 88), lean=(62, 96), bend=(12, 34), hp=(-30, -6), hr=(-6, 6), + hn=(4, 14), kn=(12, 32), hf=(-6, 6), kf=(6, 22), ff=(0, 8), + sn=(-4, 10), en=(4, 20), sf=(18, 42), ef=(30, 64), bn=(2, 6), bf=(4, 8), + support="both", ground="feet", plant=("n", "f"), balance=True), + # wind: walk bent into the wind, head down (copy P1 ejiri) + "wind": dict(yaw=(66, 86), lean=(12, 26), bend=(4, 12), hp=(14, 28), + hn=(14, 22), kn=(6, 14), hf=(-22, -14), kf=(14, 34), ff=(18, 34), + sn=(30, 56), en=(70, 110), sf=(-10, 6), ef=(20, 40), + support="both", ground="feet", plant=("n", "f"), swap=True), + "lie": dict(yaw=(60, 80), lean=(0, 4), bend=(0, 4), hp=(-6, 4), + hn=(34, 60), kn=(60, 95), hf=(0, 8), kf=(2, 12), + sn=(150, 175), en=(40, 80), bn=(20, 40), sf=(-10, 10), ef=(10, 30), + support="lie", ground="lie", plant=()), + "sleep": dict(yaw=(55, 75), lean=(0, 6), bend=(2, 8), hp=(-4, 6), hr=(10, 20), + hn=(20, 40), kn=(30, 60), hf=(4, 12), kf=(6, 16), + sn=(160, 178), en=(110, 140), bn=(20, 30), sf=(10, 30), ef=(20, 50), + support="lie", ground="lie", plant=()), + "jump": dict(yaw=(40, 70), lean=(-6, 4), bend=(0, 6), hp=(-18, -6), + hn=(40, 70), kn=(70, 110), hf=(30, 55), kf=(80, 120), ff=(30, 50), fn=(20, 40), + sn=(140, 170), en=(10, 30), bn=(20, 40), sf=(130, 165), ef=(10, 30), bf=(20, 40), + support="air", ground="feet", plant=(), lift=(.14, .22)), +} + +# arm actions laid over a body pose: (near arm, far arm) ranges; None keeps the body pose's arm +ACTS = { + "wave": dict(yaw=(18, 45), sn=(118, 148), en=(36, 70), bn=(28, 52), wn=(-10, 10), hp=(-8, 2)), + "point": dict(yaw=(62, 84), sn=(76, 94), en=(0, 8), bn=(4, 10), hp=(-6, 0)), + "cheer": dict(yaw=(10, 35), sn=(150, 172), en=(4, 22), bn=(22, 40), sf=(148, 172), ef=(4, 22), bf=(22, 40), hp=(-18, -8)), + "reach_up": dict(sn=(152, 174), en=(0, 14), bn=(6, 14), hp=(-34, -18), lean=(-6, -1), fn=(30, 45)), + "hold": dict(sn=(22, 44), en=(56, 86)), + "hold_up": dict(sn=(110, 140), en=(20, 50), bn=(8, 16)), + "hands": dict(sn=(16, 30), en=(66, 86), sf=(16, 30), ef=(66, 86), hp=(18, 34), bn=(0, 4), bf=(0, 4)), # reading + "carry": dict(sn=(16, 30), en=(44, 66), sf=(16, 30), ef=(44, 66), lean=(-8, -3), bn=(4, 8), bf=(4, 8)), + "carry_side": dict(sn=(-3, 3), en=(0, 6), bn=(10, 16), chs=(-8, -4), lean=(0, 3)), + "carry_back": dict(sn=(150, 172), en=(120, 150), sf=(140, 166), ef=(120, 150), lean=(18, 32), hp=(4, 14)), + "carry_hip": dict(sn=(-10, 6), en=(80, 100), bn=(16, 26), pel=(-12, -7), sf=(-4, 10), ef=(10, 25), bf=(12, 20)), + "paint": dict(sn=(62, 92), en=(18, 48), sf=(8, 24), ef=(70, 95), lean=(2, 8), hp=(0, 8)), + "rod": dict(sn=(36, 56), en=(36, 64), sf=(26, 44), ef=(54, 80)), + "staff": dict(sn=(6, 16), en=(20, 40), bn=(18, 26), sf=(-4, 8), ef=(10, 24)), + "cane": dict(sn=(10, 22), en=(20, 40), lean=(6, 14), hp=(8, 18)), + "lead": dict(sn=(24, 44), en=(8, 30), bn=(6, 12)), + "leash": dict(sn=(24, 44), en=(8, 30), bn=(6, 12)), + "reins": dict(sn=(28, 46), en=(46, 76), sf=(28, 46), ef=(46, 76)), + "push": dict(sn=(70, 90), en=(6, 22), sf=(68, 88), ef=(6, 22), lean=(26, 42)), + "pull": dict(sn=(52, 70), en=(0, 14), sf=(50, 68), ef=(0, 14), lean=(-30, -18)), + "pray": dict(sn=(36, 56), en=(100, 124), sf=(36, 56), ef=(100, 124), bn=(0, 3), bf=(0, 3), hp=(14, 30)), + "akimbo": dict(sn=(-30, -16), en=(90, 115), bn=(30, 45), sf=(-30, -16), ef=(90, 115), bf=(30, 45)), + "pockets": dict(sn=(-12, -4), en=(20, 34), bn=(10, 16), sf=(-12, -4), ef=(20, 34), bf=(10, 16)), + "hip": dict(sn=(-24, -12), en=(84, 104), bn=(28, 40)), + "sad": dict(hp=(22, 36), lean=(4, 10), bend=(6, 14), sn=(-2, 4), en=(4, 12), sf=(-2, 4), ef=(4, 12)), + "scared": dict(lean=(-10, -4), hp=(-6, 4), sn=(56, 80), en=(90, 120), sf=(60, 84), ef=(90, 120)), + "surprised": dict(sn=(60, 80), en=(100, 130), bn=(20, 30), sf=(60, 80), ef=(100, 130), bf=(20, 30), hp=(-8, 0)), + "drink": dict(sn=(40, 60), en=(120, 140), bn=(8, 16), hp=(-14, -4)), + "feed": dict(sn=(40, 62), en=(10, 30), lean=(6, 16), hp=(6, 16)), + "chop": dict(sn=(150, 175), en=(30, 60), sf=(150, 175), ef=(30, 60), lean=(-8, -2), hp=(0, 8)), + "throw": dict(sn=(140, 170), en=(40, 70), bn=(10, 20), sf=(50, 70), ef=(10, 30), lean=(-8, 0)), + "knit": dict(sn=(16, 30), en=(96, 120), sf=(16, 30), ef=(96, 120), hp=(18, 30)), + "garden": dict(sn=(40, 64), en=(10, 30), sf=(30, 50), ef=(20, 40), lean=(30, 50), hp=(10, 24)), + "dance": dict(sn=(130, 160), en=(20, 50), bn=(30, 50), sf=(50, 80), ef=(20, 50), bf=(30, 60), lean=(-8, 6), + chs=(6, 12), pel=(-12, -6), hn=(30, 52), kn=(40, 80), fn=(30, 50)), + "hug": dict(sn=(60, 80), en=(60, 90), sf=(60, 80), ef=(60, 90)), + "handlebar": dict(sn=(50, 66), en=(14, 30), sf=(50, 66), ef=(14, 30), lean=(18, 30)), + "work_at": dict(sn=(46, 66), en=(30, 60), sf=(30, 50), ef=(50, 80), lean=(4, 10)), + "violin": dict(sn=(60, 80), en=(100, 130), bn=(20, 30), sf=(30, 50), ef=(60, 90), hp=(6, 14), hr=(8, 14)), +} + +VERB_WORDS = [ # prompt words -> (body pose, act); longest first in use + ("gleaning", "bend", None), ("picking up", "bend", None), ("bending over", "bend", None), ("bending down", "bend", None), + ("bending", "bend", None), ("stooping", "bend", None), ("gathering", "bend", None), ("weeding", "bend", None), + ("harvesting", "bend", None), ("digging", "bend", "staff"), ("tying", "bend", None), ("planting", "bend", None), + ("against the wind", "wind", None), ("in the wind", "wind", None), ("windy", "wind", None), + ("leading", "walk", "lead"), ("walking", "walk", None), ("strolling", "walk", None), ("hiking", "walk", None), + ("running", "run", None), ("jogging", "run", None), ("sprinting", "run", None), ("jumping", "jump", None), + ("reading", None, "hands"), ("painting", None, "paint"), ("fishing", None, "rod"), ("waving", None, "wave"), + ("pointing", None, "point"), ("cheering", None, "cheer"), ("dancing", None, "dance"), ("carrying", None, "carry"), + ("pushing", None, "push"), ("pulling", None, "pull"), ("praying", "kneel2", "pray"), ("kneeling", "kneel", None), + ("riding", "sit", "reins"), ("sitting", "sit", None), ("seated", "sit", None), ("lying", "lie", None), + ("sleeping", "sleep", None), ("reaching", None, "reach_up"), ("holding", None, "hold"), ("drinking", None, "drink"), + ("feeding", None, "feed"), ("chopping", None, "chop"), ("throwing", None, "throw"), ("knitting", None, "knit"), +] + + +def verb_from_text(text): + """(body pose, act) for the first verb phrase in a prompt (None, None if none)""" + import re + t = " " + (text or "").lower() + " " + # style phrases are not verbs: "oil painting of a woman sitting" paints nothing (only "painting at / a ..." does) + t = re.sub(r"\b(oil|watercolou?r|gouache|acrylic|digital|ink|impressionist|realistic|tempera|fresco)\s+painting", " ", t) + t = re.sub(r"\b(a|an|the)\s+painting\s+of\b|\bpainting\s+of\b|,\s*painting\b|\bpainting\s*$", " ", t) + best = None + for w, p, a in sorted(VERB_WORDS, key=lambda x: -len(x[0])): + i = t.find(" " + w) + if i >= 0 and (best is None or i < best[0]): + best = (i, p, a) + return (best[1], best[2]) if best else (None, None) + + +class Pose: + """sampled joint angles for one figure (degrees) + its support / grounding meta""" + + def __init__(self, name, act, P, meta, seed): + self.name, self.act, self.P, self.meta, self.seed = name, act, P, meta, seed + + def __repr__(self): + return "Pose(%s%s)" % (self.name, "+" + self.act if self.act else "") + + +def pose_for(name="stand", act=None, seed=0, **over): + """sample a pose: the body verb `name` (POSES) with an arm action `act` (ACTS) laid over it. Keyword overrides + are fixed values or (lo, hi) ranges for any angle (e.g. yaw=70).""" + r = srng(seed, "pose", name, act) + spec = dict(NEUTRAL) + base = POSES.get(name, POSES["stand"]) + spec.update({k: v for k, v in base.items() if isinstance(v, tuple) and len(v) == 2 and not isinstance(v[0], str)}) + meta = {k: v for k, v in base.items() if k in ("support", "ground", "plant", "swap", "lift", "balance", "side")} + meta.setdefault("support", "both") + meta.setdefault("ground", "feet") + meta.setdefault("plant", ("n", "f")) + if act in ACTS: + a = ACTS[act] + for k, v in a.items(): + if name in ("sit", "sit_ground", "cross_legged", "kneel", "kneel2", "lie", "sleep") and k in ( + "lean",) and act not in ("garden", "handlebar", "reins"): + continue # seated readers keep the seat's trunk + if k[0] in "hkfa" and k not in ("hp", "hr") and name not in ("stand",): + continue # leg angles of an act only replace the idle stance + spec[k] = v + if act == "dance" and name == "stand": + meta["support"], meta["plant"] = "far", ("f",) + for k, v in over.items(): + spec[k] = v if isinstance(v, tuple) else (v, v) + P = {k: lo + (hi - lo) * r.random() for k, (lo, hi) in spec.items()} + if meta.get("swap") and r.random() < .5: + # which leg leads in the stride is the seed's choice; the arms counter-swing with it + for a_, b_ in (("hn", "hf"), ("kn", "kf"), ("fn", "ff")): + P[a_], P[b_] = P[b_], P[a_] + if act is None: + for a_, b_ in (("sn", "sf"), ("en", "ef")): + P[a_], P[b_] = P[b_], P[a_] + if meta.get("lift"): + meta["lift_v"] = meta["lift"][0] + (meta["lift"][1] - meta["lift"][0]) * r.random() + # knees and elbows bend one way only (WAVE20 brief, human-153) + for k in ("kn", "kf", "en", "ef"): + P[k] = max(0.0, P[k]) + return Pose(name, act, P, meta, seed) + + +# --------------------------------------------------------------------------------------------- solver +def _d(a, b=0.0): + """unit 3D vector (fwd, up, lat) for a sagittal angle a from plumb-down (+ forward) and lateral abduction b""" + a, b = a * D2R, b * D2R + return (math.sin(a) * math.cos(b), -math.cos(a) * math.cos(b), math.sin(b)) + + +def _up(a, roll=0.0): + """unit vector for a torso direction: angle a from plumb-UP, + forward""" + a = a * D2R + return (math.sin(a), math.cos(a), 0.0) + + +def _add(p, v, s=1.0): + return (p[0] + v[0] * s, p[1] + v[1] * s, p[2] + v[2] * s) + + +def _mid(a, b, t=.5): + return tuple(a[i] + (b[i] - a[i]) * t for i in range(3)) + + +class Body: + """a posed figure: J3 (H units, fwd/up/lat, ground at u=0), J (canvas px), Z (depth toward the viewer, px), + plus C (canon), pose, facing, yaw, scale s (px per H), H (head px), support, com""" + + def __init__(self, C, pose, J3, facing, yaw): + self.C, self.pose, self.J3, self.facing, self.yaw = C, pose, J3, facing, yaw + self.J, self.Z, self.s = {}, {}, 1.0 + self.support, self.com = pose.meta.get("support"), None + + def project(self, x0, y0, s): + th = self.yaw * D2R + st, ct = math.sin(th), math.cos(th) + f = self.facing + self.s = s + self.J, self.Z = {}, {} + for k, (a, u, l) in self.J3.items(): + self.J[k] = (x0 + f * s * (a * st - l * ct), y0 - s * u) + self.Z[k] = s * (a * ct + l * st) + self.H = s + return self + + def landmarks(self): + return {k: (round(v[0], 2), round(v[1], 2)) for k, v in self.J.items()} + + def claim(self): + """the record critic13 / contact read (inst.body2d_claim)""" + P = self.pose.P + return dict(verb=self.pose.name, act=self.pose.act, J=self.landmarks(), H=round(self.s, 2), + heads_tall=round(self.C["N"], 2), support=self.support, facing=self.facing, yaw=round(self.yaw, 1), + knee=[round(P["kn"], 1), round(P["kf"], 1)], elbow=[round(P["en"], 1), round(P["ef"], 1)], + lean=round(P["lean"], 1), bend=round(P["bend"], 1), + com=None if self.com is None else [round(self.com[0], 2), round(self.com[1], 2)]) + + +def build3d(C, pose): + """forward kinematics in H units from the hip centre; returns J3 (not grounded)""" + P = pose.P + J = {} + pel = (0.0, C["hip_h"], 0.0) + J["pelvis"] = pel + hw = C["hip_w"] * .30 # hip joints sit inside the pelvis mass (copy P9) + pr = P["pel"] * D2R + J["hip_n"] = (0.0, pel[1] + math.sin(pr) * hw, hw * math.cos(pr)) + J["hip_f"] = (0.0, pel[1] - math.sin(pr) * hw, -hw * math.cos(pr)) + lean, bend = P["lean"], P["bend"] + lp = lean * .55 # the pelvis takes about half the trunk tilt; the chest takes the rest + bend + tl = C["torso"] + J["waist"] = _add(pel, _up(lp), tl * .38) + J["chest"] = _add(J["waist"], _up(lean + bend * .6), tl * .30) + J["neck"] = _add(J["chest"], _up(lean + bend), tl * .32) + # back point (spine curve, for the swept torso): pushed behind the chord in a bend (copy P11) + cd = (lean + bend) * D2R + J["back"] = _add(J["chest"], (-math.cos(cd), math.sin(cd), 0.0), C["chest_d"] * .45) + cr = P["chs"] * D2R + shw = C["sh_w"] * .40 + nb = J["neck"] + dn = _up(lean + bend) + shc = _add(nb, dn, -C["sh_drop"]) + J["sh_n"] = (shc[0], shc[1] + math.sin(cr) * shw, shw * math.cos(cr)) + J["sh_f"] = (shc[0], shc[1] - math.sin(cr) * shw, -shw * math.cos(cr)) + # neck and head: the head continues the spine (P11) then pitches by hp; roll is drawn by the head + na = lean + bend + 15 # the neck tilts forward of the chest (human-174, 15-25 deg) + J["neck_top"] = _add(nb, _up(na), max(C["neck"], .08)) + ha = lean + bend + P["hp"] * 1.0 + ha = lean + bend + P["hp"] - (lean + bend) * .35 if lean + bend > 40 else ha # a bent figure lifts its head a bit + hu = _up(ha) + J["chin"] = _add(J["neck_top"], (math.cos(ha * D2R) * .18, -math.sin(ha * D2R) * .18 * 0, 0.0), 1.0) + J["chin"] = _add(J["neck_top"], hu, .05) + J["chin"] = (J["chin"][0] + .16 * math.cos(ha * D2R), J["chin"][1] - .16 * math.sin(ha * D2R), 0.0) + J["head"] = _add(J["chin"], hu, .5) + J["head"] = (J["head"][0] - .06 * math.cos(ha * D2R), J["head"][1] + .06 * math.sin(ha * D2R), 0.0) + J["crown"] = _add(J["chin"], hu, 1.0) + J["crown"] = (J["crown"][0] - .1 * math.cos(ha * D2R), J["crown"][1] + .1 * math.sin(ha * D2R), 0.0) + # legs + for s in ("n", "f"): + hip = J["hip_" + s] + h, k, a = P["h" + s], P["k" + s], P["a" + s] + lat = 1 if s == "n" else -1 + th = _d(h, a * lat) + kn = _add(hip, th, C["thigh"]) + sh = _d(h - k, a * lat * .5) + an = _add(kn, sh, C["shin"]) + fa = (h - k) + 90 - P["f" + s] # the foot points forward, toes down by f* + fd = _d(fa, a * lat * .6) + J["kn_" + s], J["an_" + s] = kn, an + J["heel_" + s] = _add(an, fd, -C["foot"] * .18) + J["toe_" + s] = _add(an, fd, C["foot"] * .80) + # arms + for s in ("n", "f"): + sh = J["sh_" + s] + lat = 1 if s == "n" else -1 + a, e, b = P["s" + s], P["e" + s], P["b" + s] + ud = _d(a, b * lat) + el = _add(sh, ud, C["upper"]) + fd = _d(a + e, b * lat * .6) + wr = _add(el, fd, C["fore"]) + hd = _d(a + e + P["w" + s] * .5, b * lat * .4) + J["el_" + s], J["wr_" + s] = el, wr + J["hand_" + s] = _add(wr, hd, C["hand"] * .5) + J["tip_" + s] = _add(wr, hd, C["hand"]) + return J + + +def _shift(J, df=0.0, du=0.0, dl=0.0, keys=None): + for k in (keys or list(J)): + a, u, l = J[k] + J[k] = (a + df, u + du, l + dl) + + +def _com(J): + W = dict(head=1.0, chest=3.0, waist=1.5, pelvis=2.0, kn_n=.8, kn_f=.8, an_n=.3, an_f=.3, el_n=.3, el_f=.3, + hand_n=.2, hand_f=.2) + sw = sum(W.values()) + return (sum(J[k][0] * w for k, w in W.items()) / sw, sum(J[k][1] * w for k, w in W.items()) / sw) + + +def _ik2(root, target, l1, l2, bend_sign): + """2-bone IK in a (fwd, up) plane; bend_sign +1 puts the joint forward (knee), -1 back (elbow)""" + dx, dy = target[0] - root[0], target[1] - root[1] + d = math.hypot(dx, dy) + d = min(max(d, abs(l1 - l2) + 1e-4), l1 + l2 - 1e-4) + a = math.atan2(dy, dx) + c = (l1 * l1 + d * d - l2 * l2) / (2 * l1 * d) + c = max(-1.0, min(1.0, c)) + b = math.acos(c) + j1 = (root[0] + l1 * math.cos(a + b), root[1] + l1 * math.sin(a + b)) + j2 = (root[0] + l1 * math.cos(a - b), root[1] + l1 * math.sin(a - b)) + return j1 if (j1[0] - j2[0]) * bend_sign > 0 else j2 + + +def solve(C, pose): + """pose + canon -> Body (3D-lite joints in H units, grounded and balanced; not yet projected)""" + P, M = pose.P, pose.meta + J = build3d(C, pose) + g = M.get("ground", "feet") + if g == "feet": + lows = [J[k][1] for k in ("an_n", "an_f", "toe_n", "toe_f", "heel_n", "heel_f")] + _shift(J, du=C["ankle_h"] * .35 - min(lows)) + # plant the feet that carry weight: ankle on the ground (2-bone IK in the sagittal plane, knee forward) + plant = M.get("plant", ()) + if pose.name in ("walk", "wind"): + # contact phase: only the leading heel is planted; the trailing leg pushes off on its toes with the knee + # bent (planting both straightened the back knee: R1 measured walk knee 0.8 deg) + plant = ("n",) if P["hn"] >= P["hf"] else ("f",) + for s in plant: + an = J["an_" + s] + tgt_u = C["ankle_h"] * (1.0 if P["f" + s] < 12 else 1.0 + P["f" + s] / 40.0) + if abs(an[1] - tgt_u) > .02: + hip = J["hip_" + s] + kn2 = _ik2((hip[0], hip[1]), (an[0], tgt_u), C["thigh"], C["shin"], +1) + dk = (kn2[0] - J["kn_" + s][0], kn2[1] - J["kn_" + s][1]) + J["kn_" + s] = (kn2[0], kn2[1], J["kn_" + s][2]) + d = (0.0, tgt_u - an[1]) + for k in ("an_", "heel_", "toe_"): + p = J[k + s] + J[k + s] = (p[0] + d[0], p[1] + d[1], p[2]) + if M.get("balance") or pose.name in ("stand", "bend") or pose.act in ("carry", "carry_back", "reach_up", "push", "pull"): + # centre of mass over the support feet: move everything above the ankles fore/aft (pelvis back as the + # counterweight in a bend, copy P12; human-012 margin) + sup = [J["an_n"][0], J["an_f"][0], J["toe_n"][0], J["toe_f"][0]] + if M.get("support") == "far": + sup = [J["an_f"][0], J["toe_f"][0]] + lo, hi = min(sup), max(sup) + if pose.act == "push": + lo, hi = lo, hi + 2.0 # leans on the thing pushed + elif pose.act == "pull": + lo, hi = lo - 2.0, hi + for _ in range(6): + cx = _com(J)[0] + tgt = min(max(cx, lo + .08), hi - .08) if hi - lo > .2 else (lo + hi) / 2 + err = tgt - cx + if abs(err) < .02: + break + upper = [k for k in J if not k.startswith(("an_", "toe_", "heel_", "kn_"))] + _shift(J, df=err, keys=upper) + for s in ("n", "f"): + hip, an = J["hip_" + s], J["an_" + s] + kn2 = _ik2((hip[0], hip[1]), (an[0], an[1]), C["thigh"], C["shin"], +1) + J["kn_" + s] = (kn2[0], kn2[1], J["kn_" + s][2]) + if M.get("lift_v"): + _shift(J, du=M["lift_v"] * C["N"]) + elif g == "seat": + _shift(J, du=-(J["pelvis"][1] - C["hip_h"])) # pelvis stays at its own height; caller moves to the seat + elif g == "pelvis": + _shift(J, du=C["hip_d"] * .32 - J["pelvis"][1]) + elif g == "knee": + lows = [J[k][1] for k in ("kn_n", "kn_f", "toe_n", "toe_f", "an_n", "an_f")] + _shift(J, du=C["leg_w"][2] * .4 - min(lows)) + elif g == "lie": + # lying: the standing-built figure turned 90 deg onto its back (face up) or side (sleep), on the ground + piv = J["pelvis"] + rot = 90.0 # face up: the head goes back, the front turns to the sky + cr, sr = math.cos(rot * D2R), math.sin(rot * D2R) + for k, (a, u, l) in list(J.items()): + da, du = a - piv[0], u - piv[1] + J[k] = (piv[0] + da * cr - du * sr, piv[1] + da * sr + du * cr, l) + # the back of the trunk and the head rest on the ground (not the lowest hand or heel) + lows = min(J["pelvis"][1] - C["hip_d"] * .5, J["chest"][1] - C["chest_d"] * .5, J["head"][1] - .42) + _shift(J, du=-lows) + for k in list(J): # nothing sinks under the ground + a, u, l = J[k] + if u < .04: + J[k] = (a, .04, l) + B = Body(C, pose, J, 1, P["yaw"]) + B.com = _com(J) + return B + + +def screen_ik(B, limb, target): + """move a hand ('n'/'f') or foot ('fn'/'ff') to a canvas-px target by 2-bone IK in screen space after + projection: elbows bend down / back, knees forward (bend signs kept). Updates B.J in place.""" + if limb in ("n", "f"): + r, m, e, l1, l2 = "sh_" + limb, "el_" + limb, "wr_" + limb, B.C["upper"], B.C["fore"] + sign = -B.facing + else: + s = limb[1] + r, m, e, l1, l2 = "hip_" + s, "kn_" + s, "an_" + s, B.C["thigh"], B.C["shin"] + sign = B.facing + S = B.s + root = B.J[r] + # screen y grows down: flip to a y-up frame for _ik2 + j = _ik2((root[0], -root[1]), (target[0], -target[1]), l1 * S, l2 * S, sign) + jm = (j[0], -j[1]) + d = math.hypot(target[0] - jm[0], target[1] - jm[1]) or 1.0 + end = (jm[0] + (target[0] - jm[0]) * min(1.0, l2 * S / d), jm[1] + (target[1] - jm[1]) * min(1.0, l2 * S / d)) + old_e = B.J[e] + B.J[m], B.J[e] = jm, end + dx, dy = end[0] - old_e[0], end[1] - old_e[1] + for k in (("hand_", "tip_") if limb in ("n", "f") else ("heel_", "toe_")): + kk = k + (limb if limb in ("n", "f") else limb[1]) + if kk in B.J: + B.J[kk] = (B.J[kk][0] + dx, B.J[kk][1] + dy) + return B diff --git a/pydraw/figure/design.py b/pydraw/figure/design.py new file mode 100644 index 0000000000000000000000000000000000000000..cde2bb54abe6397ffac0a6c94e6c5b9b655ae253 --- /dev/null +++ b/pydraw/figure/design.py @@ -0,0 +1,761 @@ +"""figure.design: the SHAPE STAGE every tonal portrait style shares (wave 20, styles lane). Pure code, CPU only. + +The illustrator's order (WAVE20 method steps 4-6): value plan and palette, masses in overlap order, DESIGNED shadow +shapes (never N.L per pixel), features as clean value symbols. Media finishers (paint2.py: oil, watercolor, gouache; +ink2.py: pen, pencil, charcoal) only add marks to what this module decides. + + D = design(fig, seed) # fig = pydraw.figure.Figure (kit layout + hair layout + value plan) + D.rgb HxWx3 float32 0..1 the clean flat design (a gouache-like poster: 2 families x 2 values per material) + D.fam HxW 1 = light family, 0 = shadow family (form-003), per pixel, soft at designed soft edges + D.val HxW 0..1 value inside the family (core shadow 0 .. reflected .35 | halftone .7 .. centre light 1) + D.reg HxW int region id (REG names) in z order + D.m dict of coverage masks (face, neck, torso, hair, hair_front, ears, beard, chest_skin, figure, ...) + D.feat HxWx4 RGBA of the feature symbols (eyes, brows, nostrils, mouth) so finishers can keep them crisp + D.lines list of (pts Nx2, weight 0..1, kind) feature / contour lines for the line media (F1-F3, I1) + D.shadow_polys the designed shadow shapes (2D polygons) for hatching (H1, H2) + D.flow HxW angle (rad) of the stroke direction: hair flow (R1), cross-contour on skin, folds on cloth + D.soft HxW 0..1 how lost the local edge should be (P-R5, form-040, human-043) + +Rules (docs/research18/copy_rules.md C1-C9, P-R1..P-R10, A2, F1-F3; docs/research21/rules form.jsonl, human.jsonl): + form-002 one key light, side from the layout (L.light_side); form-003 two families, no overlap; form-006 core shadow + strip just past the terminator; form-007 reflected light lifts the far shadow edge, never to the halftone; form-008 / + human-065 terminator sharp on angular forms (nose, brow, jaw corner) and soft on round ones (cheek); human-104 at most + 3 values per part; human-028 cast shadows darkest; P-R1 face one band below the lightest light; P-R2 lit-plane shape + + shadow shape split by a designed boundary (side of the nose, under the cheekbone, around the mouth, under the chin); + P-R3 features as value masses; P-R4 hair as 2-3 value masses with a dark pocket by the shadow cheek; P-R7 chin cast + shadow along the jaw; P-R9 skin shadows olive / brown never pink; A2 (b) rim under the hair, (c) bang cast shifted + down and away, (d) neck shaded except a lit wedge; human-003 state the blacks, leave the whites; human-033 the face + carries the strongest light; Loomis colour zones of the face (forehead gold, middle third ruddy, jaw cooler: human + "colour zones", my est. amplitudes). +Every number below is a RANGE (seeded) in head units H (crown-chin, L.H px) unless it says px. +""" +import math +import numpy as np +from scipy import ndimage as ndi + +from . import kit as K + +F32 = np.float32 +REG = {"bg": 0, "hair_back": 1, "torso": 2, "chest": 3, "neck": 4, "ear": 5, "face": 6, "beard": 7, "hair": 8} + + +# --------------------------------------------------------------------------------------------- colour helpers (Lab) +def _lin(c): + c = np.asarray(c, F32) + return np.where(c <= .04045, c / 12.92, ((c + .055) / 1.055) ** 2.4) + + +def _gam(c): + c = np.clip(c, 0, 1) + return np.where(c <= .0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - .055) + + +_M = np.array([[.4124, .3576, .1805], [.2126, .7152, .0722], [.0193, .1192, .9505]], F32) +_WP = np.array([.95047, 1.0, 1.08883], F32) + + +def to_lab(rgb): + xyz = _lin(rgb) @ _M.T / _WP + f = np.where(xyz > .008856, np.cbrt(xyz), 7.787 * xyz + 16 / 116) + return np.stack([116 * f[..., 1] - 16, 500 * (f[..., 0] - f[..., 1]), 200 * (f[..., 1] - f[..., 2])], -1) + + +def from_lab(lab): + lab = np.asarray(lab, F32) + fy = (lab[..., 0] + 16) / 116 + fx = fy + lab[..., 1] / 500 + fz = fy - lab[..., 2] / 200 + f = np.stack([fx, fy, fz], -1) + xyz = np.where(f ** 3 > .008856, f ** 3, (f - 16 / 116) / 7.787) * _WP + return _gam(xyz @ np.linalg.inv(_M).T).astype(F32) + + +def tone(rgb, L=None, dL=0.0, kC=1.0, dh=0.0, da=0.0, db=0.0): + """a colour moved in Lab: target lightness L (or +dL), chroma x kC, hue turned dh degrees, a/b nudged""" + lab = to_lab(np.asarray(rgb, F32)).astype(np.float64) + if L is not None: + lab[..., 0] = L + lab[..., 0] += dL + a, b = lab[..., 1] * kC, lab[..., 2] * kC + if dh: + r = math.radians(dh) + a, b = a * math.cos(r) - b * math.sin(r), a * math.sin(r) + b * math.cos(r) + lab[..., 1], lab[..., 2] = a + da, b + db + return from_lab(lab) + + +def Lof(rgb): + return float(to_lab(np.asarray(rgb, F32))[..., 0]) + + +def mix(a, b, t): + return (np.asarray(a, F32) * (1 - t) + np.asarray(b, F32) * t).astype(F32) + + +# --------------------------------------------------------------------------------------------- geometry helpers +def lerp(a, b, t): + return np.asarray(a, F32) * (1 - t) + np.asarray(b, F32) * t + + +def smooth_poly(P, n=6, sharp=()): + return K.crv(np.asarray(P, F32), closed=True, n=n, sharp=sharp) + + +def soft(m, r): + """gaussian softening of a coverage mask, radius r px (sigma r/2)""" + if r <= 0.3: + return m + return ndi.gaussian_filter(m.astype(F32), r / 2.0, mode="nearest") + + +class Design: + pass + + +# --------------------------------------------------------------------------------------------- the design +def design(fig, seed=0, medium="paint"): + L, HL, V = fig.layout, fig.hair, fig.plan + S = int(L.size) + H = float(L.H) + pt = L.pt + rng = np.random.default_rng(seed * 7919 + 101) + u = lambda a, b: float(rng.uniform(a, b)) + from . import fig_masks + M = fig_masks(fig) + D = Design() + D.S, D.H, D.L, D.fig, D.medium = S, H, L, fig, medium + + shadow_key = L.shadow_side # 'L' or 'R' (subject's side) + light_key = "R" if shadow_key == "L" else "L" + sx = 1.0 if (pt["eye_L"][0] > pt["eye_R"][0]) == (shadow_key == "L") else -1.0 # image x sign of the shadow side + D.sx = sx + yy, xx = np.mgrid[0:S, 0:S].astype(F32) + up = np.array([0, -1], F32) + + # ---------------------------------------------------------------- 1 masses in overlap order (exclusive coverage) + face = M["face"] + neck = M["neck"] * (1 - face) + torso = M["torso"] + for s in L.arms: + torso = np.maximum(torso, M["arm_" + s]) + chest = M["chest_skin"] + ears = np.zeros_like(face) + ear_over = np.zeros_like(face) + for s, e in L.ears.items(): + if e["visible"]: + if e.get("over_face"): + ear_over = np.maximum(ear_over, M["ear_" + s]) + else: + ears = np.maximum(ears, M["ear_" + s]) + hair_back, hair_front = M["hair_back"], M["hair_front"] + # simplify the hair silhouette into big masses (P-R4, C5: masses first, the tips are marks added later): a + # gaussian-threshold drops slivers thinner than ~0.05 H (stray locks across the cheek) and fills notches + def massify(m, r): + if m.max() <= 0: + return m + g = ndi.gaussian_filter(m.astype(F32), r) + return np.clip((g - .5) * 2.5 + .5, 0, 1).astype(F32) + hair_back = massify(hair_back, .022 * H) + hair_front = massify(hair_front, .018 * H) + M["hair_back"], M["hair_front"] = hair_back, hair_front + M["hair"] = np.maximum(hair_back, hair_front) + beard = M["beard"] + if L.beard is not None and L.beard.get("mouth_hole") is not None and L.beard.get("kind") != "mustache": + beard = beard * (1 - K.shape_mask(K.crv(np.asarray(L.beard["mouth_hole"]), n=6), S, S) * .0) + D.m = dict(face=face, neck=neck, torso=torso, chest=chest, ears=np.maximum(ears, ear_over), hair_back=hair_back, + hair_front=hair_front, beard=beard, hair=np.maximum(hair_back, hair_front)) + # z order: bg < hair_back < torso < chest < neck < ears(behind) < face < ear(over) < beard < hair_front + layers = [("hair_back", hair_back), ("torso", torso), ("chest", chest * torso), ("neck", neck), ("ear", ears), + ("face", face), ("ear", ear_over), ("beard", beard), ("hair", hair_front)] + reg = np.zeros((S, S), np.int16) + vis = {} + rem = np.ones((S, S), F32) + for name, m in layers[::-1]: # visible coverage, top layer first + c = np.clip(m, 0, 1) * rem + vis[name] = vis.get(name, 0) + c + rem = rem - c + for name, m in layers: + reg[m > .5] = REG[name] + D.reg, D.vis = reg, vis + fig_m = np.clip(1 - rem, 0, 1) + D.m["figure"] = fig_m + + # ---------------------------------------------------------------- 2 palette (value plan first, C1, P-R1, P-R9) + mat = {k: np.clip(np.asarray(v, F32), 0, 1) for k, v in V.materials.items()} + skin = mat["skin"] + hair_c = mat.get("hair", np.array([.3, .2, .15], F32)) + if L.beard is not None and L.beard.get("color"): + from .value import hair_rgb + beard_c = hair_rgb(L.beard["color"], seed)[0] + else: + beard_c = hair_c + def neutral(c): + # grey / white hair: the per-seed jitter must not tint it green or pink (keep it near-neutral, a touch warm) + lab = to_lab(np.asarray(c, F32)) + if float(np.hypot(lab[1], lab[2])) < 16 and lab[0] > 45: + return tone(c, kC=.15, db=2.0) + return c + hair_c, beard_c = neutral(hair_c), neutral(beard_c) + cloth = mat.get("cloth", np.array([.5, .5, .5], F32)) + bg = mat.get("bg", np.array([.6, .55, .5], F32)) + eyes_c = mat.get("eyes", np.array([.35, .22, .12], F32)) + lips = mat.get("lips", tone(skin, dL=-12, kC=1.3, dh=-12)) + Ls = Lof(skin) + # skin families: light = the base lifted a little (the face is one band below the lightest light, P-R1), + # shadow = darker, warmer and a little less chroma, toward olive / brown (P-R9), halftone cooler and greyer + # (Gurney: halftones lose chroma), reflected light warm. Shadow drop 18-30 L* (one value band, human-104). + drop = u(19, 27) * (0.75 + 0.35 * Ls / 80.0) + P = {} + P["skin_l"] = tone(skin, dL=u(2, 6), kC=1.0) + P["skin_hl"] = tone(skin, dL=u(10, 14), kC=.75, dh=8) + P["skin_ht"] = tone(skin, dL=-drop * .32, kC=.82, dh=-4) + P["skin_s"] = tone(skin, dL=-drop, kC=.92, dh=10) + P["skin_core"] = tone(skin, dL=-drop * 1.22, kC=.95, dh=6) + P["skin_refl"] = tone(skin, dL=-drop * .72, kC=1.12, dh=-2) + P["skin_cast"] = tone(skin, dL=-drop * 1.12, kC=1.05, dh=-6) + P["lip_u"] = tone(lips, dL=-drop * .55, kC=.95) + P["lip_l"] = tone(lips, dL=-2, kC=1.0) + hL = Lof(hair_c) + hdrop = max(10.0, min(30.0, hL * .42)) + P["hair_l"] = tone(hair_c, dL=hdrop * .15) + P["hair_m"] = tone(hair_c, dL=-hdrop * .35) + P["hair_s"] = tone(hair_c, dL=-hdrop * 1.0, kC=.9) + P["hair_hl"] = tone(hair_c, dL=min(22, (96 - hL) * .45 + 6), kC=.6, dh=6) + P["hair_dark"] = tone(hair_c, L=max(5.0, min(hL * .35, 22.0)), kC=.7) + bL = Lof(beard_c) + P["beard_l"], P["beard_s"] = tone(beard_c, dL=2), tone(beard_c, dL=-max(10, bL * .4), kC=.9) + cL = Lof(cloth) + cdrop = max(12.0, min(30.0, cL * .38)) + P["cloth_l"] = tone(cloth, dL=2) + P["cloth_s"] = tone(cloth, dL=-cdrop, kC=.85, dh=-6) + P["cloth_core"] = tone(cloth, dL=-cdrop * 1.25, kC=.8) + # background: counterchange (human-088, form-040): lighter behind the shadow side, darker behind the lit side + bgL = Lof(bg) + face_L = Lof(P["skin_l"]) + P["bg_a"] = tone(bg, dL=u(4, 10)) # behind the shadow side + P["bg_b"] = tone(bg, dL=-u(10, 18), kC=.9) # behind the lit side + # P-R1: the face is one band BELOW the lightest light. Cap the lit skin, then make sure the clothes (when light) + # or the ground behind the shadow side carry a lighter light than the face + fl = Lof(P["skin_l"]) + if fl > 82: + k = 82 - fl + for key in ("skin_l", "skin_hl", "skin_ht", "skin_refl"): + P[key] = tone(P[key], dL=k) + fl = 82.0 + need = fl + u(6, 10) + if Lof(P["cloth_l"]) > 55: + if Lof(P["cloth_l"]) < need: + P["cloth_l"] = tone(P["cloth_l"], L=min(96.0, need)) + elif Lof(P["bg_a"]) < need: + P["bg_a"] = tone(P["bg_a"], L=min(95.0, need)) + P["eye"] = eyes_c + P["ink"] = np.array([.16, .11, .09], F32) if face_L > 40 else np.array([.07, .05, .05], F32) + D.P = P + + # ---------------------------------------------------------------- 3 the face: designed shadow shape (P-R2, A2) + g = lambda k: np.asarray(pt[k], F32) + S_, O_ = shadow_key, light_key + mid_top = g("hairline") + up * .14 * H + # short lighting on a turned head puts the BROAD (near) side in shadow: move the terminator out onto the side + # plane there so the skin shadow stays ~0.3-0.45 of the face (A2 skin shadow fraction 0.3-0.4) + wide = 1.0 if (abs(L.yaw) > 12 and S_ == L.near) else 0.0 + k_fore = u(.42, .62) + .18 * wide + k_brow = u(.15, .55) + .35 * wide + rembrandt = rng.random() < .45 and abs(L.yaw) < 35 + term = [] + term.append(lerp(mid_top, g("temple_" + S_), k_fore) + up * .2 * H) + term.append(lerp(mid_top, g("temple_" + S_), k_fore)) + term.append(lerp(g("brow_in_" + S_), g("brow_mid_" + S_), k_brow) + up * .03 * H) + term.append(lerp(g("nose_root"), g("brow_in_" + S_), .25)) + for q in np.asarray(L.nose["side"], F32): + term.append(q) + wing = g("nose_wing_" + S_) + term.append(wing + np.array([sx * .005 * H, .01 * H], F32)) + k_cheek = u(.30, .50) + .3 * wide + q1 = lerp(wing, g("zygion_" + S_), k_cheek) + np.array([0, .045 * H], F32) + term.append(q1) + k_jaw = u(.15, .38) + .35 * wide + term.append(lerp(g("mouth_" + S_), g("jaw_angle_" + S_), k_jaw) + np.array([0, .03 * H], F32)) + term.append(lerp(g("chin_" + S_), g("chin"), u(.15, .45))) + term.append(g("chin") + np.array([sx * .02 * H, .25 * H], F32)) + far = np.array([sx * 1.5 * H, 0], F32) + tp = np.array(term) + poly = np.vstack([tp, tp[-1:] + far, tp[:1] + far]) + shade = K.shape_mask(smooth_poly(poly, n=5, sharp=[len(tp) - 1, len(tp), len(tp) + 1, 0]), S, S) + # the lit triangle of Rembrandt light on the shadow cheek (under the eye, beside the nose) + if rembrandt: + e_s = g("eye_" + S_) + tri = np.array([lerp(e_s, g("nose_root"), .25) + np.array([0, .06 * H], F32), + lerp(e_s, g("zygion_" + S_), .45) + np.array([0, .07 * H], F32), + wing + np.array([sx * .03 * H, -.005 * H], F32)]) + tri = smooth_poly(tri, n=4, sharp=[0, 1, 2]) + shade = shade * (1 - K.shape_mask(tri, S, S) * u(.75, .95)) + # edge design: crisp along the nose and brow (angular, human-065), soft over the cheek and forehead (round) + hard_zone = np.zeros((S, S), F32) + nose_line = np.vstack([term[3]] + [q for q in np.asarray(L.nose["side"], F32)] + [term[-6]]) + dn, _, _ = K._seg_dist(xx.ravel(), yy.ravel(), nose_line[:-1], nose_line[1:]) + hard_zone = np.exp(-(dn.reshape(S, S) / (.06 * H)) ** 2) + sh_soft = soft(shade, .055 * H) + sh_hard = soft(shade, .012 * H) + shade = sh_hard * hard_zone + sh_soft * (1 - hard_zone) + + # small shapes: cast shadows are darkest (human-028) + cast = np.zeros((S, S), F32) + # nose cast: from the tip down and away from the light (A2e) + tip, base = g("nose_tip"), g("nose_base") + ncast = np.array([wing + np.array([-sx * .01 * H, -.01 * H], F32), base + np.array([0, .005 * H], F32), + base + np.array([sx * .07 * H, .06 * H], F32) * np.array([u(.7, 1.1), u(.6, 1.0)], F32), + wing + np.array([sx * .04 * H, .025 * H], F32)]) + cast = np.maximum(cast, soft(K.shape_mask(smooth_poly(ncast, n=4), S, S), .012 * H)) + # under-plane of the nose (faces down: halftone-dark) + under = K.ellipse(base + np.array([sx * .006 * H, .004 * H], F32), np.ptp([pt["nose_wing_L"][0], pt["nose_wing_R"][0]]) * .48, + .022 * H) + cast = np.maximum(cast, soft(K.shape_mask(under, S, S), .01 * H) * .65) + # under the lower lip, the upper lip plane faces down (P-R3) + lb = g("lip_bot") + ul = K.ellipse(lb + np.array([sx * .01 * H, .028 * H], F32), L.mouth["w"] * .36, .026 * H) + cast = np.maximum(cast, soft(K.shape_mask(ul, S, S), .025 * H) * .75) + # eye sockets: a soft value mass from the brow to under the eye (P-R3: the eye is one soft dark mass) + sockets = np.zeros((S, S), F32) + for s_, e in L.eyes.items(): + c = np.asarray(e["c"], F32) + k = 1.0 if s_ == S_ else u(.45, .65) + el = K.ellipse(c + np.array([0, -.012 * H], F32), e["w"] * .78, .07 * H, rot=0) + sockets = np.maximum(sockets, soft(K.shape_mask(el, S, S), .06 * H) * k) + # under the chin onto the neck: the jaw line shifted down, along the jaw (P-R7) + jaw_pts = np.vstack([np.asarray(L.jaw["R"], F32)[::-1], np.asarray(L.jaw["L"], F32)[1:]]) + jaw_pts = jaw_pts[np.argsort(jaw_pts[:, 0])] + drop_c = u(.10, .17) * H + neck_cast_poly = np.vstack([jaw_pts + np.array([sx * .03 * H, -.05 * H], F32), + (jaw_pts + np.array([sx * .05 * H, drop_c], F32))[::-1]]) + neck_cast = soft(K.shape_mask(smooth_poly(neck_cast_poly, n=4), S, S), .03 * H) * vis["neck"].clip(0, 1) + # neck: shaded except a lit wedge on the light side (A2d) + nt = {s: g("neck_top_" + s) for s in ("L", "R")} + nb = {s: g("neck_base_" + s) for s in ("L", "R")} + wedge = np.array([lerp(nt[O_], nt[S_], .05), lerp(nt[O_], nt[S_], u(.42, .55)), lerp(nb[O_], nb[S_], u(.45, .6)), + lerp(nb[O_], nb[S_], -.05)]) + neck_lit = soft(K.shape_mask(wedge, S, S), .03 * H) + # hair cast on the forehead: the front hair shifted down and away from the light (A2b/c) + hf_shift = ndi.shift(hair_front, (.035 * H, sx * .025 * H), order=1, mode="constant") + hair_cast = soft(np.clip(hf_shift - hair_front, 0, 1), .02 * H) * face + # ear: shadow tone when on the shadow side, else halftone + D.face_shade = shade + + # family + value maps on the skin + fam = np.ones((S, S), F32) + val = np.ones((S, S), F32) + skin_area = np.clip(vis["face"] + vis["neck"] + vis["chest"] * 1 + vis["ear"], 0, 1) + # light family: centre light 1, halftone near the terminator and on the turning lit contour (form-005) + dist_term = ndi.distance_transform_edt(shade < .5).astype(F32) + ht = np.exp(-dist_term / (.09 * H)) * .30 + # the lit side plane of the face turns away: halftone along the lit contour (human-104 side planes read as sides) + fm = face > .5 + d_edge = ndi.distance_transform_edt(fm).astype(F32) + lit_side = np.clip((xx - g("nose_tip")[0]) * -sx / (.4 * H), 0, 1) + ht = np.maximum(ht, np.exp(-d_edge / (.05 * H)) * .22 * lit_side) + # forehead top and the chest below the neckline turn up / away: a little halftone + ht = np.maximum(ht, np.clip((g("pit")[1] + .05 * H - yy) * 0, 0, 0)) + v_light = 1 - ht + # shadow family: core 0 near the terminator, reflected light up to .35 toward the far contour (form-006/007) + dist_in = ndi.distance_transform_edt(shade > .5).astype(F32) + v_shadow = np.clip(.12 + .23 * np.clip((dist_in - .04 * H) / (.18 * H), 0, 1), 0, .35) + v_shadow = np.where(dist_in < .035 * H, .02 + dist_in / (.035 * H) * .1, v_shadow) + refl = np.exp(-d_edge / (.03 * H)) * (1 - lit_side) * u(.05, .12) + v_shadow = np.clip(v_shadow + refl, 0, .4) + sh_face = np.clip(shade, 0, 1) + fam_face = 1 - sh_face + # sockets / casts push toward the shadow family as value masses + val_face = fam_face * v_light + (1 - fam_face) * v_shadow + val_face = val_face * (1 - .42 * sockets) - .5 * cast * fam_face - .25 * cast * (1 - fam_face) - .55 * hair_cast + val_face = np.clip(val_face, 0, 1) + # neck: shadow, minus the lit wedge; chin cast darkest + fam_neck = neck_lit * (1 - neck_cast) + val_neck = np.clip(fam_neck * .82 + (1 - fam_neck) * .22 - .2 * neck_cast, 0, 1) + # chest skin: lit, with the head's cast shadow at the top on the shadow side + chest_cast = soft(ndi.shift((vis["neck"] + vis["face"] > .5).astype(F32), (.18 * H, sx * .06 * H), order=0), .05 * H) + fam_chest = 1 - chest_cast * .9 + val_chest = np.clip(.9 * fam_chest + .2 * (1 - fam_chest), 0, 1) + # ears + fam_ear = np.ones((S, S), F32) + for s_, e in L.ears.items(): + if e["visible"] and s_ == S_: + fam_ear = fam_ear * (1 - M["ear_" + s_]) + val_ear = fam_ear * .8 + (1 - fam_ear) * .25 + + # ---------------------------------------------------------------- 4 colour the skin from families x values + def skin_col(v, fam_): + lit = np.where((v > .9)[..., None], mix(P["skin_l"], P["skin_l"], 0), 0) + a = mix(P["skin_ht"], P["skin_l"], np.clip((v - .7) / .3, 0, 1)[..., None]) + b = mix(P["skin_core"], P["skin_refl"], np.clip(v / .38, 0, 1)[..., None]) + b = mix(b, P["skin_s"], .35) + return mix(b, a, fam_[..., None]) + + rgb = np.zeros((S, S, 3), F32) + # background + bx = np.clip(.5 + (xx - g("nose_tip")[0]) * sx / (.9 * S), 0, 1)[..., None] + by = np.clip(yy / S, 0, 1)[..., None] + bgc = mix(P["bg_b"], P["bg_a"], bx) + bgc = mix(bgc, tone(bg, dL=-u(6, 14)), (by ** 2) * .6) + rgb[:] = bgc + + def over(col, cov): + nonlocal rgb + cov = np.clip(cov, 0, 1)[..., None] + rgb = rgb * (1 - cov) + col * cov + + # hair (back mass): mostly in shadow (behind the head), a lit edge on the light side + hair_val, hair_fam = hair_values(D, L, HL, M, sx, xx, yy, rng) + hcol = hair_colour(P, hair_val, hair_fam) + over(hcol, hair_back) + # torso (cloth): designed light / shadow (human-104, cloth light from the same key) + tc = torso_values(D, L, sx, xx, yy, rng, vis) + D.cloth_val = tc + ccol = mix(mix(P["cloth_core"], P["cloth_s"], np.clip(tc / .35, 0, 1)[..., None]), P["cloth_l"], + np.clip((tc - .45) / .33, 0, 1)[..., None]) + over(ccol, torso) + over(skin_col(val_chest, fam_chest), chest * torso) + over(skin_col(val_neck, fam_neck), neck) + over(skin_col(val_ear, fam_ear), ears) + # colour zones of the face (my est.): forehead warmer / golden, the middle third ruddy, the jaw cooler (men) + face_rgb = skin_col(val_face, fam_face) + zt = np.clip((yy - g("brow_mid_L")[1]) / (.15 * H), -1, 1) + zb = np.clip((yy - g("nose_base")[1]) / (.12 * H), 0, 1) + ruddy = np.exp(-((yy - (g("nose_base")[1] - .06 * H)) / (.12 * H)) ** 2) + zone = np.zeros((S, S, 3), F32) + zone += (np.clip(-zt, 0, 1)[..., None] * np.array([.02, .012, -.02], F32)) + zone += ruddy[..., None] * np.array([.035, -.008, -.006], F32) * u(.7, 1.2) + sexm = float(getattr(L.person, "sex", .5)) + zone += zb[..., None] * np.array([-.018, .0, .012], F32) * (.4 + .9 * sexm) + face_rgb = np.clip(face_rgb + zone, 0, 1) + over(face_rgb, face) + over(skin_col(val_ear, fam_ear), ear_over) + # beard + if beard.max() > 0: + bv = np.clip(.75 - .55 * soft((xx - g("nose_tip")[0]) * sx > 0, .1 * H) - .3 * np.clip((yy - g("chin")[1]) / (.15 * H), 0, 1), 0, 1) + over(mix(P["beard_s"], P["beard_l"], bv[..., None]), beard) + D.beard_v = bv.astype(F32) + over(hcol, hair_front) + D.hair_val, D.hair_fam = hair_val, hair_fam + + # family / value maps over the whole figure (for finishers) + fam_all = np.ones((S, S), F32) + val_all = np.full((S, S), .6, F32) + beard_v = D.__dict__.get("beard_v", np.full((S, S), .6, F32)) + for v_, f_, m_ in ((hair_val, hair_fam, hair_back), (tc, (tc > .5).astype(F32), torso), + (val_chest, fam_chest, chest * torso), (val_neck, fam_neck, neck), + (val_ear, fam_ear, ears), (val_face, fam_face, face), (val_ear, fam_ear, ear_over), + (beard_v, (beard_v > .5).astype(F32), beard), (hair_val, hair_fam, hair_front)): + c = np.clip(m_, 0, 1) + fam_all = fam_all * (1 - c) + f_ * c + val_all = val_all * (1 - c) + v_ * c + D.fam, D.val = fam_all, val_all + D.shadow_polys = {"face": poly} + D.term = tp[1:-1] + D.cast = cast + D.neck_cast, D.hair_cast, D.sockets = neck_cast, hair_cast, sockets + D.base = rgb.copy() + + # ---------------------------------------------------------------- 5 features as value symbols (P-R3, F1-F3) + feat = np.zeros((S, S, 4), F32) + lines = [] + features(D, L, P, feat, lines, sx, S_, O_, rng, xx, yy) + a = feat[..., 3:4] + rgb = rgb * (1 - a) + feat[..., :3] * a + # front hair is drawn over the brows only where it covers them (brows over bangs only in anime, A5) + over(hcol, hair_front * (feat[..., 3] > 0)) + D.feat = feat + D.lines = lines + D.rgb = np.clip(rgb, 0, 1) + + # ---------------------------------------------------------------- 6 stroke direction and edge softness + D.flow = flow_map(D, L, HL, M, xx, yy) + D.soft = soft_map(D, sx, xx, yy) + return D + + +# --------------------------------------------------------------------------------------------- hair values (P-R4) +def hair_values(D, L, HL, M, sx, xx, yy, rng): + """2-3 value masses: the lit mass in mid value, the turning side dark, a dark pocket beside the shadow cheek, a + highlight band following the skull (A6/H2-7, from HL.crests), seams (HL.troughs) as lock separations; quantised so + the hair reads as designed masses (P-R4, human-104), then lightly softened""" + S = D.S + H = D.H + pt = L.pt + hair = np.maximum(M["hair_back"], M["hair_front"]) + cx = float(L.pt["head_c"][0]) + # side: across the head from lit to shadow + # the terminator on the hair is an arc round the skull (a sphere lit from the side), not a vertical cut + cyh = float(L.pt["head_c"][1]) - .15 * H + arc = np.sqrt(np.clip(1 - ((yy - cyh) / (.75 * H)) ** 2, 0, 1)) * .22 * H + side = np.clip(.5 + (xx - cx - sx * arc + sx * .05 * H) * sx / (.45 * H), 0, 1) + v = .72 - .45 * side ** 1.4 + # back hair is behind the head: one step darker + v = v - .22 * M["hair_back"] * (1 - M["hair_front"]) + # low hair (below the jaw) turns under: darker + v = v - .15 * np.clip((yy - pt["chin"][1]) / (.6 * H), 0, 1) + # troughs and crests from the hair layout (R1 value field) + step = 4 + if HL.troughs or HL.crests: + vf = K.value_field(S, S, step, base=0.0, troughs=HL.troughs, crests=[]) + vf = ndi.zoom(vf, (S / vf.shape[0], S / vf.shape[1]), order=1)[:S, :S] + v = v - .35 * vf + hl = np.zeros((S, S), F32) + if HL.highlight is not None and len(HL.highlight) > 1: + d = K.dist_to_curve(HL.highlight, S, S, step) + d = ndi.zoom(d, (S / d.shape[0], S / d.shape[1]), order=1)[:S, :S] + hl = np.exp(-(d / (.035 * H)) ** 2) * (1 - side) ** .7 + # dark pocket by the shadow-side cheek (P-R4): hair within ~0.12 H of the face contour on the shadow side + fd = ndi.distance_transform_edt(M["face"] < .5).astype(F32) + pocket = np.exp(-fd / (.07 * H)) * np.clip((xx - cx) * sx / (.2 * H), 0, 1) * (yy > pt["eye_L"][1] - .1 * H) + v = v - .3 * pocket + # quantise to 3 masses (dark / mid / light), softened a little: designed masses, not a gradient + q = np.where(v < .28, .12, np.where(v < .55, .45, .78)).astype(F32) + q = soft(q, .02 * H) * .75 + v.clip(0, 1) * .25 + q = np.clip(q + .55 * hl * (q > .3), 0, 1.2) + fam = (q > .5).astype(F32) + return q.astype(F32), fam + + +def hair_colour(P, v, fam): + v = v[..., None] + c = mix(P["hair_dark"], P["hair_s"], np.clip(v / .3, 0, 1)) + c = mix(c, P["hair_m"], np.clip((v - .3) / .3, 0, 1)) + c = mix(c, P["hair_l"], np.clip((v - .6) / .3, 0, 1)) + c = mix(c, P["hair_hl"], np.clip((v - .95) / .2, 0, 1)) + return c + + +def torso_values(D, L, sx, xx, yy, rng, vis): + """cloth: the shadow side of the chest and the arm turning away, the head's cast shadow under the neck, darker + toward the frame bottom (the light falls off down the figure, human-033)""" + S, H, pt = D.S, D.H, L.pt + pit = np.asarray(pt["pit"], F32) + shw = abs(float(pt["shoulder_L"][0] - pt["shoulder_R"][0])) / 2 + 1e-3 + xr = (xx - pit[0]) * sx / shw + k = float(rng.uniform(.28, .5)) + # the form shadow of the chest is an arc round the rib-cage barrel (human-099 planes of the trunk), not a + # vertical cut: the terminator bends away from the light lower down + yr = (yy - pit[1]) / H + shade = soft((xr > k - .1 * yr + .45 * yr ** 2).astype(F32), .14 * H) + v = .85 - .62 * shade + # side planes on the lit side turn away too (a softer halftone) + v = v - .18 * np.clip((-xr - .75) / .3, 0, 1) + # head / neck cast on the chest + cast = soft(ndi.shift((vis["neck"] + vis["face"] > .5).astype(F32), (.2 * H, sx * .1 * H), order=0), .06 * H) + v = v - .35 * cast + v = v - .15 * np.clip((yy - pit[1]) / (1.3 * H), 0, 1) + return np.clip(v, 0, 1).astype(F32) + + +# --------------------------------------------------------------------------------------------- features +def _fill(feat, P_, col, a=1.0, n=6, sharp=()): + S = feat.shape[0] + m = K.shape_mask(K.crv(np.asarray(P_, F32), closed=True, n=n, sharp=sharp), S, S) * a + _paint(feat, m, col) + return m + + +def _paint(feat, m, col, a=1.0): + m = np.clip(m * a, 0, 1)[..., None] + feat[..., :3] = feat[..., :3] * (1 - m) + np.asarray(col, F32) * m + feat[..., 3:4] = feat[..., 3:4] * (1 - m) + m + + +def _stroke(feat, pts, w, col, kind="swell", a=1.0, clip=None): + S = feat.shape[0] + m = K.stroke_mask(np.asarray(pts, F32), w, S, S, kind=kind) + if clip is not None: + m = m * clip + _paint(feat, m, col, a) + return m + + +def features(D, L, P, feat, lines, sx, S_, O_, rng, xx, yy): + S, H = D.S, D.H + pt = L.pt + base = D.base + ink = P["ink"] + # ---- eyes (F1: the eye is the upper lid; P-R3 the lower white dimmed to the skin halftone) + wmax = max(e["w"] for e in L.eyes.values()) + for s_, e in L.eyes.items(): + U, Dn = np.asarray(e["upper"], F32), np.asarray(e["lower"], F32) + w, h = float(e["w"]), float(e["h"]) + if w < 2: + continue + shadow_eye = s_ == S_ + c = np.asarray(e["c"], F32) + out = np.vstack([U, Dn[::-1][1:-1]]) + eye_m = K.shape_mask(K.crv(out, n=6, sharp=[0, len(U) - 1]), S, S) + loc = base[int(np.clip(c[1], 0, S - 1)), int(np.clip(c[0], 0, S - 1))] + white = mix(loc, np.array([.93, .91, .88], F32), .45 if not shadow_eye else .25) + _paint(feat, eye_m, white) + # iris: ~0.42 of the eye width, cut by the upper lid (F1: iris partly under the lid) + r = .215 * wmax * float(rng.uniform(.95, 1.05)) + rx = r * min(1.0, w / wmax * 1.05) + ic = c + np.array([0, .12 * h], F32) + iris = K.shape_mask(K.ellipse(ic, rx, r), S, S) * eye_m + ecol = P["eye"] if not shadow_eye else tone(P["eye"], dL=-8) + _paint(feat, iris, tone(ecol, dL=-6)) + inner = K.shape_mask(K.ellipse(ic + np.array([0, .15 * r], F32), rx * .72, r * .7), S, S) * eye_m + _paint(feat, inner, tone(ecol, dL=4, kC=1.1), .6) + pup = K.shape_mask(K.ellipse(ic, rx * .42, r * .42), S, S) * eye_m + _paint(feat, pup, np.array([.05, .04, .04], F32)) + # the upper lid casts a band onto the eyeball (A4 grey lid band; paint: one soft dark mass) + band = np.clip(K.shape_mask(np.vstack([U, (U + np.array([0, .45 * h], F32))[::-1]]), S, S) * eye_m, 0, 1) + _paint(feat, soft(band, .15 * h) * eye_m, tone(loc, dL=-28, kC=.6), .55) + # catchlight: one small dot on the iris toward the light, upper side + cl = ic + np.array([-sx * .35 * rx, -.4 * r], F32) + _paint(feat, soft(K.shape_mask(K.ellipse(cl, max(.7, .16 * r), max(.7, .16 * r)), S, S), .5), np.array([.97, .96, .93], F32), + .9 if not shadow_eye else .55) + # upper lid line: heavy, arched, thickest at the outer corner, runs into the lashes (F1) + outer_first = np.linalg.norm(U[0] - np.asarray(e["outer"], F32)) < 1e-3 + lw = max(1.2, .14 * h + .012 * H) + prof = np.linspace(.45, 1.0, len(U)) if not outer_first else np.linspace(1.0, .45, len(U)) + Uc = K.crv(U, closed=False, n=6) + _stroke(feat, Uc, lw, mix(ink, P["hair_dark"], .3), kind="swell", a=.95) + lines.append((Uc, 1.0, "lid")) + # lid crease: a thin halftone arc above (the lid mass) + crease = K.crv(U + np.array([0, -.42 * h], F32) + (U - c) * np.array([.12, 0], F32), closed=False, n=6) + crease = crease[int(len(crease) * .15):int(len(crease) * .92)] + _stroke(feat, crease, max(.8, .05 * h + .004 * H), tone(loc, dL=-22, kC=.8), kind="swell", a=.55) + lines.append((crease, .35, "crease")) + # lower lid: only the outer half, light (O1) + Dc = K.crv(Dn, closed=False, n=6) + oi = np.argmin(np.linalg.norm(Dc - np.asarray(e["outer"], F32), axis=1)) + half = Dc[len(Dc) // 2:] if oi > len(Dc) // 2 else Dc[:len(Dc) // 2 + 1] + _stroke(feat, half, max(.7, .05 * h + .003 * H), tone(loc, dL=-16, kC=.8), kind="swell", a=.5) + lines.append((half, .3, "lower")) + # tear duct: a warm dot at the inner corner + ic_ = np.asarray(e["inner"], F32) + _paint(feat, soft(K.shape_mask(K.ellipse(ic_ + (c - ic_) * .08, .06 * w, .07 * w), S, S), .5) * (1 - eye_m * 0), + tone(P["lip_l"], dL=6, kC=.6), .45) + # ---- brows: tapered masses in hair colour mixed with skin, heavier inner-middle (Loomis brows) + bc = mix(P["hair_s"] if Lof(P["hair_m"]) < 60 else tone(P["hair_m"], dL=-25), D.P["skin_s"], .3) + for s_, b in L.brows.items(): + bpts = np.asarray(b, F32) + bcrv = K.crv(bpts, closed=False, n=8) + w = (.024 + .012 * float(getattr(L.person, "sex", .5))) * H + _stroke(feat, bcrv, w, bc, kind="flick" if np.linalg.norm(bpts[0] - pt["nose_root"]) < np.linalg.norm(bpts[-1] - pt["nose_root"]) else "rflick", + a=.8 if s_ == O_ else .9) + lines.append((bcrv, .5, "brow")) + # ---- nose: nostrils (dark, F3), a light stroke on the lit side of the tip, the wing on the lit side as halftone + base_n = np.asarray(pt["nose_base"], F32) + for s_ in ("L", "R"): + wg = np.asarray(pt["nose_wing_" + s_], F32) + nc = lerp(base_n, wg, .52) + np.array([0, -.008 * H], F32) + rr = (.016 if s_ == S_ else .013) * H * (.6 if (s_ == L.far and abs(L.yaw) > 12) else 1.0) + nm = K.shape_mask(K.ellipse(nc, rr, rr * .55, rot=math.atan2(float(wg[1] - base_n[1]), float(wg[0] - base_n[0]))), S, S) + _paint(feat, soft(nm, .006 * H), tone(D.P["skin_core"], dL=-14, kC=.9), .9) + lines.append((K.ellipse(nc, rr, rr * .55)[:12], .6, "nostril")) + tipp = np.asarray(pt["nose_tip"], F32) + if abs(L.yaw) > 12: # 3/4: the nose's far contour against the far cheek (a found edge) + fs = 1.0 if pt["eye_" + L.far][0] > pt["eye_" + L.near][0] else -1.0 + root = np.asarray(pt["nose_root"], F32) + wf = np.asarray(pt["nose_wing_" + L.far], F32) + prof = np.array([lerp(root, tipp, .35) + np.array([fs * .004 * H, 0], F32), lerp(root, tipp, .8), + tipp + np.array([fs * .01 * H, .008 * H], F32), lerp(tipp, wf, .5) + np.array([0, .01 * H], F32)]) + pc = K.crv(prof, closed=False, n=6) + col = D.P["skin_core"] if L.far == S_ else D.P["skin_s"] + _stroke(feat, pc, max(1.0, .011 * H), col, kind="swell", a=.7) + lines.append((pc, .55, "nose")) + _paint(feat, soft(K.shape_mask(K.ellipse(tipp + np.array([-sx * .02 * H, -.012 * H], F32), .014 * H, .01 * H), S, S), .01 * H), + D.P["skin_hl"], .75) + lw_ = np.asarray(pt["nose_wing_" + O_], F32) + wing_arc = np.array([lw_ + np.array([0, -.035 * H], F32), lw_ + np.array([-sx * .012 * H, -.01 * H], F32), + lw_ + np.array([-sx * .004 * H, .012 * H], F32), lerp(lw_, base_n, .45) + np.array([0, .016 * H], F32)]) + wa = K.crv(wing_arc, closed=False, n=6) + _stroke(feat, wa, .012 * H, D.P["skin_ht"], kind="swell", a=.55) + lines.append((wa, .3, "wing")) + # ---- mouth: dark upper lip (faces down), slit darkest at the corners, lit lower lip with one light (F2, P-R3) + mo = L.mouth + if mo.get("open") is not None: # faces lane expression hook (optional) + _fill(feat, mo["open"], np.array([.18, .07, .07], F32)) + if mo.get("teeth") is not None: + _fill(feat, mo["teeth"], np.array([.92, .9, .85], F32), .95) + up_ = np.asarray(mo["upper"], F32) + lo_ = np.asarray(mo["lower"], F32) + _fill(feat, up_, P["lip_u"], .92, n=5, sharp=[0, 2]) + _fill(feat, lo_, P["lip_l"], .85, n=5, sharp=[0, 2]) + lb = np.asarray(pt["lip_bot"], F32) + _paint(feat, soft(K.shape_mask(K.ellipse(lb + np.array([-sx * .012 * H, -.018 * H], F32), mo["w"] * .14, .008 * H), S, S), .008 * H), + tone(P["lip_l"], dL=12, kC=.6), .55) + ml = K.crv(np.asarray(mo["line"], F32), closed=False, n=8) + _stroke(feat, ml, max(1.0, .011 * H), tone(P["lip_u"], dL=-26, kC=.8), kind="ends", a=.9) + lines.append((ml, .8, "mouth")) + for cpt in (mo["line"][0], mo["line"][-1]): + _paint(feat, soft(K.shape_mask(K.ellipse(np.asarray(cpt, F32), .012 * H, .009 * H), S, S), .006 * H), + tone(D.P["skin_core"], dL=-8), .6) + # ---- ears: the inner C in shadow tone + for s_, e in L.ears.items(): + if not e["visible"]: + continue + ol = np.asarray(e["outline"], F32) + c = np.asarray(e["c"], F32) + inner = c + (ol - c) * .55 + inner = inner[: int(len(inner) * .7)] + ic = K.crv(inner, closed=False, n=6) + _stroke(feat, ic, .018 * H, D.P["skin_s"] if s_ != S_ else D.P["skin_core"], kind="swell", a=.75) + lines.append((ic, .5, "ear")) + # ---- glasses + gl = getattr(L, "glasses", None) + if gl: + fc = np.array([.12, .1, .1], F32) + for s_, ln in gl["lens"].items(): + lc = K.crv(np.asarray(ln, F32), closed=True, n=4) + lens_m = K.shape_mask(lc, S, S) + _paint(feat, lens_m, np.array([.85, .9, .95], F32), .1) + _stroke(feat, np.vstack([lc, lc[:1]]), max(1.2, .012 * H), fc, kind=None, a=.95) + lines.append((np.vstack([lc, lc[:1]]), .9, "glasses")) + _stroke(feat, np.asarray(gl["bridge"], F32), max(1.2, .011 * H), fc, kind=None, a=.95) + for s_, a in gl["arms"].items(): + _stroke(feat, np.asarray(a, F32), max(1.2, .011 * H), fc, kind=None, a=.9) + + +# --------------------------------------------------------------------------------------------- flow + edges +def flow_map(D, L, HL, M, xx, yy): + """stroke direction per pixel: hair from the hair layout's guides (R1), skin cross-contour (perpendicular to the + direction to the face centre: cheek lines parallel to the jaw, H1), neck rings, cloth along the body diagonally""" + S, H = D.S, D.H + c = np.asarray(L.pt["head_c"], F32) + ang_skin = np.arctan2(yy - c[1], xx - c[0]) + np.pi / 2 + pit = np.asarray(L.pt["pit"], F32) + # cloth: cross-contour arcs round the chest cylinder (centre above the pit), a little wobble + ang_cloth = np.arctan2(yy - (pit[1] - 1.4 * H), xx - pit[0]) + np.pi / 2 + .15 * np.sin(xx / (.3 * H) + yy / (.5 * H)) + ang = np.where(D.reg >= REG["neck"], ang_skin, ang_cloth) + ang = np.where(D.reg == REG["neck"], np.arctan2(yy - (pit[1] + .5 * H), xx - pit[0]) + np.pi / 2, ang) + hair = np.maximum(M["hair_back"], M["hair_front"]) + if HL.guides: + step = 4 + th = K.flow_field(HL.guides, S, S, step) + th = ndi.zoom(np.cos(2 * th), (S / th.shape[0], S / th.shape[1]), order=1)[:S, :S], \ + ndi.zoom(np.sin(2 * th), (S / th.shape[0], S / th.shape[1]), order=1)[:S, :S] + th = .5 * np.arctan2(th[1], th[0]) + ang = np.where(hair > .5, th, ang) + if L.beard is not None: + ang = np.where(M["beard"] > .5, np.pi / 2 + .3 * np.sign(xx - c[0]), ang) + bgang = np.radians(60) + .4 * np.sin(yy / (.4 * H)) + .3 * np.cos(xx / (.5 * H)) + ang = np.where(D.m["figure"] > .5, ang, bgang) + return ang.astype(F32) + + +def soft_map(D, sx, xx, yy): + """how lost each region boundary should be (P-R5: 3-4 hard edges; shadow-side and hair-to-ground edges soft; + a light garment may lose its edge into a light ground; form-040 lost where values match)""" + S, H = D.S, D.H + reg = D.reg.astype(F32) + gx = np.abs(np.diff(reg, axis=1, append=reg[:, -1:])) + np.abs(np.diff(reg, axis=0, append=reg[-1:, :])) + edge = soft((gx > 0).astype(F32), 2.0) + shadow_side = np.clip(.5 + (xx - float(D.L.pt["nose_tip"][0])) * sx / (.5 * H), 0, 1) + low = np.clip((yy - float(D.L.pt["pit"][1])) / (.8 * H), 0, 1) + hairedge = soft(np.clip(D.m["hair"], 0, 1), 3.0) + hairedge = np.clip(hairedge * (1 - hairedge) * 4, 0, 1) + s = np.clip(edge * (.25 + .6 * shadow_side) + .5 * low * edge + .6 * hairedge * (.4 + .6 * shadow_side), 0, 1) + # the feature zone stays found + s = s * (1 - D.feat[..., 3] * .8) + return s.astype(F32) + + +def flat(fig, seed=0): + """the design itself as the picture (a clean poster: masses, designed shadows, features)""" + D = design(fig, seed) + return (np.clip(D.rgb, 0, 1) * 255 + .5).astype(np.uint8), D diff --git a/pydraw/figure/face.py b/pydraw/figure/face.py new file mode 100644 index 0000000000000000000000000000000000000000..321bddbde3e64fc0ee8c6a222e20bc599ea8e85b --- /dev/null +++ b/pydraw/figure/face.py @@ -0,0 +1,710 @@ +"""figure.face: what a face DOES (wave 20, faces lane): expression x intensity, age marks, gaze, from prompt words. + +Pure code (numbers from the research 21 rule tables, no images). Everything here is GEOMETRY IN EYE-WIDTH UNITS (ew) +so each style can call it in its own head frame: anime, ink, paint and pixel each keep their own face model and draw +the result with their own marks (style marks last). + + from pydraw.figure import face + spec = face.spec_from_text("portrait of a laughing old man", age=74, sex=1, seed=0) + spec.emotion, spec.level, spec.p # 'joy', 4, the parameter dict below + face.brow_offsets(spec.p) # inner / mid / outer dy and the inner squeeze (ew, +y down) + face.lid_offsets(spec.p) # upper-lid and lower-lid moves (ew), closure 0..1 + face.mouth_geom(spec.p, hw0=0.75) # slit or open shape, teeth, tongue, lips (ew, mouth-centred) + face.creases(spec, lm, ew_px) # wrinkle / fold polylines in PIXELS from a landmark dict + +Parameter dict (the ew-unit expression table, human-319..324; dy positive = DOWN): + brow_in, brow_out inner / outer brow end dy; squeeze inward dx of each inner brow end + upper_lid upper lid margin relative to the IRIS TOP (positive covers the iris; neutral +0.05; + negative = white above the iris) + lower_lid rise of the lower lid (positive up); opening None or the eye opening in ew (squeezed eyes) + mouth_w x neutral mouth width; open lip gap (ew); corner mouth-corner dy (negative = up) + teeth 'none' | 'upper' | 'lower' | 'both'; shape closed mouth: 'line' | 'press'; + open mouth: 'wedge' (joy) | 'oval' (surprise) | 'stretch' (fear) | 'square' (shout, bawl) | + 'snarl' (disgust) + marks crease kinds with strength 0..1 (nasolabial, crow, lowerlid, forehead, forehead_c, glabella, + nose_root, nose_side, chin, tears, flush, bag, marionette) + head_pitch deg added to the head pitch (sad looks down, contempt lifts the chin) +Sources: Faigin ladders human-305..312, FACS / EMFACS human-315/316/318, area blends human-325, Hamm laugh triangle +human-270, smile creases human-057/058, wrinkle policy human-061, aging human-327/329/330/289, children +human-288/331, gaze human-084. +""" +import math +import re +import numpy as np + +# --------------------------------------------------------------------------------------------- the expression table +_N = dict(brow_in=0.0, brow_out=0.0, squeeze=0.0, upper_lid=0.05, lower_lid=0.0, opening=None, mouth_w=1.0, open=0.0, + corner=0.0, teeth="none", shape="line", marks={}, head_pitch=0.0, arch=1.0, corner_side=None, snarl=0.0, + press=0.0, chin_up=0.0) + + +def _e(**kw): + d = dict(_N) + d["marks"] = dict(kw.pop("marks", {})) + d.update(kw) + return d + + +# levels per emotion, mildest first. Numbers: human-319..324 (directions sourced, magnitudes the rule's own estimates) +LADDER = { + "neutral": [_e()], + "joy": [ + _e(lower_lid=0.03, mouth_w=1.08, corner=-0.08, marks={"corner": .5}), # 12B + _e(brow_out=0.03, upper_lid=0.08, lower_lid=0.10, mouth_w=1.2, corner=-0.15, + marks={"nasolabial": .55, "bag": .35, "crow": .5}), # 6+12C + _e(brow_out=0.05, upper_lid=0.10, lower_lid=0.15, mouth_w=1.35, open=0.25, corner=-0.22, teeth="upper", + shape="wedge", marks={"nasolabial": .8, "bag": .5, "crow": .7}), # 6+12D+25 + _e(brow_in=-0.05, brow_out=0.03, upper_lid=0.20, lower_lid=0.20, opening=0.15, mouth_w=1.4, open=0.6, + corner=-0.25, teeth="upper", shape="wedge", tongue=True, + marks={"nasolabial": 1.0, "bag": .7, "crow": 1.0}), # laugh + ], + "sad": [ + _e(brow_in=-0.12, brow_out=0.02, squeeze=0.03, upper_lid=0.15, corner=0.06, arch=.6, head_pitch=-6), # 1B+15B + _e(brow_in=-0.22, brow_out=0.05, squeeze=0.08, upper_lid=0.20, lower_lid=0.05, mouth_w=0.95, corner=0.12, + arch=.4, chin_up=.6, head_pitch=-8, marks={"forehead_c": .6, "chin": .6}), # distraught + _e(brow_in=-0.28, brow_out=0.06, squeeze=0.12, upper_lid=0.25, lower_lid=0.15, opening=0.10, mouth_w=1.25, + open=0.3, corner=0.10, teeth="lower", shape="square", arch=.3, head_pitch=-6, + marks={"forehead_c": .8, "tears": 1.0, "flush": .7, "nasolabial": .7, "bag": .5}), # crying + _e(brow_in=-0.30, brow_out=0.08, squeeze=0.12, upper_lid=0.30, lower_lid=0.20, opening=0.0, mouth_w=1.35, + open=0.8, corner=0.10, teeth="both", shape="square", arch=.3, tongue=True, + marks={"forehead_c": 1.0, "tears": 1.0, "flush": 1.0, "nasolabial": .9, "bag": .7}), # bawling + ], + "anger": [ + _e(brow_in=0.15, brow_out=0.03, squeeze=0.12, upper_lid=0.0, lower_lid=0.05, arch=.5, + marks={"glabella": .6}), # annoyed + _e(brow_in=0.22, brow_out=0.05, squeeze=0.15, upper_lid=-0.03, lower_lid=0.10, mouth_w=0.92, corner=0.03, + shape="press", press=.6, arch=.4, marks={"glabella": .8}), # mad + _e(brow_in=0.28, brow_out=0.05, squeeze=0.18, upper_lid=-0.08, lower_lid=0.12, mouth_w=0.92, corner=0.05, + shape="press", press=.7, arch=.3, marks={"glabella": 1.0}), # angrier + _e(brow_in=0.30, brow_out=0.05, squeeze=0.20, upper_lid=-0.10, lower_lid=0.12, mouth_w=0.95, corner=0.10, + shape="press", press=.6, chin_up=1.0, arch=.3, marks={"glabella": 1.0, "chin": .8}), # + chin + _e(brow_in=0.33, brow_out=0.05, squeeze=0.20, upper_lid=-0.12, lower_lid=0.12, mouth_w=1.2, open=0.7, + corner=0.05, teeth="upper", shape="square", snarl=0.06, arch=.3, head_pitch=-3, + marks={"glabella": 1.0, "nose_root": .8, "nasolabial": .7}), # shouting + _e(brow_in=0.35, brow_out=0.08, squeeze=0.22, upper_lid=-0.15, lower_lid=0.12, mouth_w=1.35, open=0.7, + corner=-0.05, teeth="both", shape="square", snarl=0.15, arch=.3, head_pitch=-3, + marks={"glabella": 1.0, "nose_root": 1.0, "nose_side": .8, "nasolabial": .9}), # enraged + ], + "surprise": [ + _e(brow_in=-0.15, brow_out=-0.15, arch=1.4, marks={"forehead": .5}), # questioning + _e(brow_in=-0.30, brow_out=-0.30, upper_lid=-0.06, lower_lid=-0.02, mouth_w=0.65, open=0.5, shape="oval", + arch=1.6, marks={"forehead": .8}), # surprised + _e(brow_in=-0.40, brow_out=-0.40, upper_lid=-0.12, lower_lid=-0.04, mouth_w=0.7, open=0.9, shape="oval", + arch=1.7, marks={"forehead": 1.0}), # astonished + ], + "fear": [ + _e(brow_in=-0.15, brow_out=-0.03, squeeze=0.08, upper_lid=0.0, lower_lid=0.03, mouth_w=1.08, open=0.05, + corner=0.02, shape="stretch", arch=.35, marks={"forehead_c": .5}), # worried + _e(brow_in=-0.28, brow_out=-0.15, squeeze=0.12, upper_lid=-0.10, lower_lid=0.06, mouth_w=1.25, open=0.25, + corner=0.03, shape="stretch", arch=.3, marks={"forehead_c": .8}), # afraid + _e(brow_in=-0.38, brow_out=-0.20, squeeze=0.15, upper_lid=-0.18, lower_lid=0.05, mouth_w=1.4, open=0.55, + corner=0.08, teeth="lower", shape="stretch", arch=.3, marks={"forehead_c": 1.0}), # terrified + ], + "disgust": [ + _e(brow_in=0.08, brow_out=0.02, squeeze=0.05, upper_lid=0.10, lower_lid=0.08, mouth_w=0.98, corner=0.03, + snarl=0.05, marks={"nose_side": .6}), # dislike + _e(brow_in=0.15, brow_out=0.05, squeeze=0.08, upper_lid=0.15, lower_lid=0.15, mouth_w=0.95, open=0.12, + corner=0.08, teeth="upper", shape="snarl", snarl=0.12, chin_up=.6, + marks={"nose_side": 1.0, "nasolabial": .8, "lowerlid": .7, "chin": .5}), # disgust + _e(brow_in=0.20, brow_out=0.05, squeeze=0.10, upper_lid=0.25, lower_lid=0.20, mouth_w=1.1, open=0.35, + corner=0.10, teeth="upper", shape="snarl", snarl=0.15, + marks={"nose_side": 1.0, "nasolabial": 1.0, "lowerlid": 1.0}), # repulsion + ], + "contempt": [ + _e(upper_lid=0.10, corner_side=(-0.06, 0.0), head_pitch=4, marks={"dimple": .8}), # R12A+R14A + ], +} +LEVELS = {k: len(v) for k, v in LADDER.items()} + +# words -> (emotion, default level 1-based). Longest phrase first. Faigin ladders: the word picks the rung. +WORDS = [ + ("hysterical laughter", "joy", 4), ("laughing hysterically", "joy", 4), ("laughing", "joy", 4), ("laughs", "joy", 4), + ("laugh", "joy", 4), ("laughter", "joy", 4), ("giggling", "joy", 4), ("cackling", "joy", 4), + ("big smile", "joy", 3), ("broad smile", "joy", 3), ("beaming", "joy", 3), ("grinning", "joy", 3), ("grin", "joy", 3), + ("joyful", "joy", 3), ("delighted", "joy", 3), ("overjoyed", "joy", 4), ("ecstatic", "joy", 4), ("toothy", "joy", 3), + ("slight smile", "joy", 1), ("faint smile", "joy", 1), ("gentle smile", "joy", 1), ("soft smile", "joy", 1), + ("subtle smile", "joy", 1), ("smirk", "contempt", 1), ("smirking", "contempt", 1), + ("smiling", "joy", 2), ("smile", "joy", 2), ("smiles", "joy", 2), ("happy", "joy", 2), ("cheerful", "joy", 2), + ("glad", "joy", 2), ("pleased", "joy", 1), ("content", "joy", 1), ("friendly", "joy", 1), ("kind", "joy", 1), + ("sobbing", "sad", 4), ("bawling", "sad", 4), ("wailing", "sad", 4), ("weeping", "sad", 3), ("crying", "sad", 3), + ("cries", "sad", 3), ("in tears", "sad", 3), ("tearful", "sad", 3), ("tears", "sad", 3), ("grieving", "sad", 3), + ("heartbroken", "sad", 2), ("sorrowful", "sad", 2), ("mournful", "sad", 2), ("depressed", "sad", 2), + ("distraught", "sad", 2), ("sad", "sad", 1), ("unhappy", "sad", 1), ("melancholy", "sad", 1), ("gloomy", "sad", 1), + ("downcast", "sad", 1), ("pensive", "sad", 1), ("lonely", "sad", 1), ("sulking", "sad", 1), ("pouting", "sad", 1), + ("enraged", "anger", 6), ("raging", "anger", 6), ("in a rage", "anger", 6), ("livid", "anger", 6), + ("furious", "anger", 5), ("shouting", "anger", 5), ("yelling", "anger", 5), ("screaming in anger", "anger", 6), + ("roaring", "anger", 5), ("snarling", "anger", 6), ("angry", "anger", 3), ("mad", "anger", 2), ("cross", "anger", 2), + ("scowling", "anger", 2), ("glaring", "anger", 3), ("frowning", "anger", 1), ("grumpy", "anger", 1), + ("annoyed", "anger", 1), ("irritated", "anger", 1), ("stern", "anger", 1), ("fierce", "anger", 2), + ("astonished", "surprise", 3), ("astounded", "surprise", 3), ("amazed", "surprise", 3), ("shocked", "surprise", 3), + ("stunned", "surprise", 3), ("in awe", "surprise", 2), ("awestruck", "surprise", 3), ("surprised", "surprise", 2), + ("startled", "surprise", 2), ("curious", "surprise", 1), ("questioning", "surprise", 1), ("puzzled", "surprise", 1), + ("terrified", "fear", 3), ("horrified", "fear", 3), ("petrified", "fear", 3), ("panicked", "fear", 3), + ("screaming", "fear", 3), ("frightened", "fear", 2), ("scared", "fear", 2), ("afraid", "fear", 2), + ("fearful", "fear", 2), ("alarmed", "fear", 2), ("worried", "fear", 1), ("anxious", "fear", 1), + ("nervous", "fear", 1), ("uneasy", "fear", 1), ("timid", "fear", 1), + ("repulsed", "disgust", 3), ("revolted", "disgust", 3), ("grossed out", "disgust", 3), ("nauseated", "disgust", 3), + ("disgusted", "disgust", 2), ("disgust", "disgust", 2), ("sneering", "disgust", 2), ("distaste", "disgust", 1), + ("contemptuous", "contempt", 1), ("disdainful", "contempt", 1), ("scornful", "contempt", 1), + ("haughty", "contempt", 1), ("arrogant", "contempt", 1), + ("serious", "neutral", 1), ("calm", "neutral", 1), ("neutral", "neutral", 1), ("expressionless", "neutral", 1), + ("stoic", "neutral", 1), ("blank", "neutral", 1), +] +# human-325 compound expressions: (brow + upper lid from A, mouth + lower lid from B), rung of each +BLENDS = [ + ("bittersweet", ("sad", 2), ("joy", 2)), ("sad smile", ("sad", 2), ("joy", 2)), + ("smiling through tears", ("sad", 3), ("joy", 2)), ("happily surprised", ("surprise", 2), ("joy", 3)), + ("pleasantly surprised", ("surprise", 1), ("joy", 3)), ("sulky", ("anger", 2), ("sad", 1)), + ("smug", ("contempt", 1), ("joy", 1)), ("awed", ("surprise", 2), ("surprise", 2)), + ("angrily surprised", ("anger", 2), ("surprise", 2)), ("fearfully surprised", ("surprise", 2), ("fear", 2)), +] +UP = ("very", "extremely", "really", "so", "deeply", "wildly", "utterly", "absolutely", "incredibly", "intensely", + "hysterically", "totally", "super", "terribly", "visibly") +DOWN = ("slightly", "a little", "a bit", "faintly", "mildly", "somewhat", "barely", "gently", "softly", "a touch", + "subtly", "quietly", "a hint of", "hint of") + + +def knob(name, default="0"): + from . import knob as _k + return _k(name, default) + + +def active(name="fx_face"): + """the faces lane switch: fx_face=1 turns the lane on; each part also has its own sub-knob (default on under it)""" + if knob("fx_face", "0") == "0": + return False + return name == "fx_face" or knob(name, "1") != "0" + + +def _norm(text): + return " " + " ".join(re.findall(r"[a-z0-9'\-]+", (text or "").lower())) + " " + + +class Spec: + """one face's expression + age + gaze. p = the merged parameter dict (see the module docstring)""" + + def __init__(self, emotion="neutral", level=1, p=None, age=30.0, sex=0.5, gaze=(0.0, 0.0), blend=None, words=""): + self.emotion, self.level, self.blend = emotion, int(level), blend + self.p = p if p is not None else dict(_N) + self.age, self.sex, self.gaze, self.words = float(age), float(sex), gaze, words + self.age_p = age_params(self.age) + + @property + def neutral(self): + return self.emotion == "neutral" and self.blend is None + + def intensity(self): + """0..1 position on the emotion's ladder (0 = neutral)""" + if self.neutral: + return 0.0 + n = LEVELS.get(self.emotion, 1) + return self.level / float(n) + + def __repr__(self): + return "Spec(%s%s L%d/%d, age %g)" % (self.emotion, "+" + self.blend if self.blend else "", self.level, + LEVELS.get(self.emotion, 1), self.age) + + +def params(emotion, level): + lad = LADDER.get(emotion, LADDER["neutral"]) + lv = int(np.clip(level, 1, len(lad))) + d = dict(lad[lv - 1]) + d["marks"] = dict(d["marks"]) + return d + + +def blend(a, b): + """human-325: brow + upper lid from A, mouth + lower lid (+ cheek marks) from B; each capped at ~0.7 of its own""" + pa, pb = params(*a), params(*b) + out = dict(pb) + for k in ("brow_in", "brow_out", "squeeze", "upper_lid", "arch", "head_pitch"): + out[k] = pa[k] * (0.85 if k != "arch" else 1.0) if k != "upper_lid" else 0.05 + (pa[k] - 0.05) * 0.85 + m = {} + for k, v in pa["marks"].items(): + if k in ("forehead", "forehead_c", "glabella", "tears", "flush"): + m[k] = v * .8 + for k, v in pb["marks"].items(): + if k not in ("forehead", "forehead_c", "glabella"): + m[k] = max(m.get(k, 0), v * .85) + out["marks"] = m + return out + + +def parse_emotion(text): + """(emotion, level, blend name or None) from prompt words""" + t = _norm(text) + for name, a, b in BLENDS: + if (" " + name + " ") in t: + return a[0], a[1], (name, a, b) + best = None + for w, emo, lv in sorted(WORDS, key=lambda x: -len(x[0])): + i = t.find(" " + w + " ") + if i >= 0: + # a negation in front ("not smiling", "no smile") keeps the face neutral + if re.search(r"\b(not|no|never|without)\s+(?:\w+\s+)?$", t[:i + 1]): + continue + best = (emo, lv, i) + break + if best is None: + return "neutral", 1, None + emo, lv, i = best + pre = t[max(0, i - 24):i + 1] + if any((" " + u + " ") in pre for u in UP): + lv += 1 + if any((" " + d + " ") in pre for d in DOWN): + lv -= 1 + if emo == "neutral": + return "neutral", 1, None + return emo, int(np.clip(lv, 1, LEVELS[emo])), None + + +def parse_age(text): + """an explicit age in years ('80 year old', '80-year-old', 'aged 80', 'in her 70s') or None""" + t = _norm(text) + m = re.search(r"\b(\d{1,3})[ -]?(?:year|yr)s?[ -]old\b", t) or re.search(r"\baged (\d{1,3})\b", t) + if m: + return float(np.clip(int(m.group(1)), 0, 105)) + m = re.search(r"\bin (?:his|her|their) (?:early |late |mid )?(\d)0s\b", t) + if m: + return float(int(m.group(1)) * 10 + 5) + m = re.search(r"\b(?:twenties|thirties|forties|fifties|sixties|seventies|eighties|nineties)\b", t) + if m: + return float({"twenties": 25, "thirties": 35, "forties": 45, "fifties": 55, "sixties": 65, "seventies": 75, + "eighties": 85, "nineties": 93}[m.group(0)]) + if re.search(r"\b(?:very old|ancient|wizened|centenarian)\b", t): + return 86.0 + return None + + +def parse_gaze(text, framing="portrait"): + """(gx, gy) iris offset in iris radii (+x = the viewer's right, +y = down). Portraits look at the viewer by + default (direct appeal, human-084); words move the gaze.""" + t = _norm(text) + gx = gy = 0.0 + if re.search(r"\blooking (?:up|upward|skyward)|\bgazing up|\beyes (?:raised|up)\b|\blooks up\b", t): + gy = -0.45 + if re.search(r"\blooking down|\bgazing down|\beyes (?:lowered|down|downcast)\b|\blooks down\b|\bdowncast\b", t): + gy = 0.4 + m = re.search(r"\b(?:looking|glancing|gazing|eyes)\s+(?:to(?:wards?)?\s+)?(?:the\s+)?(left|right|sideways|away|aside)\b", t) + if m: + gx = {"left": -0.5, "right": 0.5}.get(m.group(1), 0.5) + return (gx, gy) + + +def spec_from_text(text, age=30.0, sex=0.5, seed=0, framing="portrait"): + emo, lv, bl = parse_emotion(text) + if bl is not None: + name, a, b = bl + p = blend(a, b) + sp = Spec(a[0], a[1], p, age, sex, parse_gaze(text, framing), blend=name, words=text) + return sp + p = params(emo, lv) + if emo == "sad" and lv <= 2 and re.search(r"\b(?:tear|tears|teary|tearful)\b", _norm(text)): + p["marks"]["tears"] = 0.8 + # EMFACS variants (human-318): the seed drops one optional cue so two angry people differ + rv = np.random.default_rng(int(seed) * 31 + LEVELS.get(emo, 1) * 7 + lv) + if emo == "anger" and lv >= 2 and rv.random() < .3: + p["lower_lid"] *= 0.5 + if emo == "fear" and lv >= 2 and rv.random() < .3: + p["mouth_w"] = 1.0 + (p["mouth_w"] - 1.0) * .6 + sp = Spec(emo, lv, p, age, sex, parse_gaze(text, framing), words=text) + if sp.age < 13: # children: no forehead / glabella lines, big clear irises + for k in ("forehead", "glabella", "forehead_c", "nasolabial", "crow", "bag", "nose_side", "lowerlid"): + if k in p["marks"]: + p["marks"][k] *= 0.0 if k in ("forehead", "glabella", "forehead_c", "crow", "lowerlid") else 0.35 + return sp + + +# --------------------------------------------------------------------------------------------------- age (wrinkles) +def _ramp(a, a0, a1): + return float(np.clip((a - a0) / max(1e-6, a1 - a0), 0, 1)) + + +def age_params(age): + """human-327/329/330/289: cumulative age deltas. Strengths 0..1 per wrinkle set (at most 1 line per set and side + below 60, human-327 / Loomis human-061), morph factors for features.""" + a = float(age) + m = { + "crow": 0.6 * _ramp(a, 32, 50) + 0.4 * _ramp(a, 55, 80), + "lowerlid": 0.5 * _ramp(a, 32, 50) + 0.5 * _ramp(a, 55, 80), + "nasolabial": 0.55 * _ramp(a, 36, 50) + 0.45 * _ramp(a, 52, 72), + "forehead": 0.5 * _ramp(a, 42, 58) + 0.5 * _ramp(a, 60, 82), + "glabella": 0.6 * _ramp(a, 45, 65), + "marionette": 0.7 * _ramp(a, 48, 68) + 0.3 * _ramp(a, 70, 85), + "bag": 0.8 * _ramp(a, 62, 82), + "cheek_hollow": _ramp(a, 64, 84), + "neck": _ramp(a, 52, 80), + "lip_lines": _ramp(a, 70, 88), + "spots": _ramp(a, 68, 88), + } + return dict( + marks=m, + lines_per_set=1 if a < 60 else (2 if a < 78 else 3), + lip_scale=1.0 - 0.35 * _ramp(a, 25, 65), # vermilion thins (human-329) + philtrum=1.0 + 0.4 * _ramp(a, 25, 65), + ear_scale=1.0 + 0.10 * _ramp(a, 50, 65) + 0.08 * _ramp(a, 65, 82), # human-330: x1.10 at 60, x1.18 at 80 + nose_scale=1.0 + 0.07 * _ramp(a, 45, 62) + 0.03 * _ramp(a, 62, 82), + hood=0.05 * _ramp(a, 50, 65) + 0.05 * _ramp(a, 65, 82), # upper-lid hooding (ew) + jowl=0.10 * _ramp(a, 55, 72) + 0.05 * _ramp(a, 72, 85), # jaw-line bulge (H fraction of jaw w) + eye_open=1.0 - 0.15 * _ramp(a, 62, 82), + grey=float(np.clip((a - 35) / 45.0, 0, 1)), # human-329 grey fraction + brow_out_droop=0.03 * _ramp(a, 50, 80), # only the outer tail (human-329) + old=_ramp(a, 55, 75), + child=float(np.clip((13.0 - a) / 11.0, 0, 1)), + ) + + +def marks_for(spec, ew_px=20.0, style="real"): + """the crease strengths to draw: the expression's marks + the age set (max), dropped by size first (human-305: + wrinkles go first, then the outer brow; mouth corners, upper-lid arc and inner brow stay to the last pixel)""" + m = dict(spec.age_p["marks"]) + for k, v in spec.p.get("marks", {}).items(): + m[k] = max(m.get(k, 0.0), v) + # expression folds deepen with age; a young face shows only the moving folds, lighter + young = 1.0 - 0.45 * _ramp(30 - spec.age, 0, 15) + for k in ("nasolabial", "crow", "bag", "forehead", "forehead_c", "glabella", "lowerlid", "nose_side"): + if k in m and k in spec.p.get("marks", {}): + m[k] = max(spec.age_p["marks"].get(k, 0.0), spec.p["marks"][k] * young) + # human-061: forehead lines only with raised brows, unless old + if spec.p["brow_in"] > -0.08 and spec.p["brow_out"] > -0.08: + m["forehead"] = min(m.get("forehead", 0.0), spec.age_p["marks"]["forehead"] * 0.8) + if ew_px < 7: + m = {k: v for k, v in m.items() if k in ("tears", "flush")} + elif ew_px < 12: + m = {k: v for k, v in m.items() if k in ("tears", "flush", "nasolabial", "corner", "dimple") and v > .45} + return {k: float(v) for k, v in m.items() if v > 0.08} + + +# ----------------------------------------------------------------------------------------- geometry in ew units +def brow_offsets(p, age_p=None): + """dy (ew, +down) for the inner / mid / outer brow points and the inner squeeze (ew toward the midline). + The arch scales the mid point's height above the inner-outer chord (surprise curves high, fear straightens: + human-311/310/315).""" + din, dout = float(p["brow_in"]), float(p["brow_out"]) + if age_p: + dout += age_p.get("brow_out_droop", 0.0) + return dict(din=din, dout=dout, dmid=0.5 * (din + dout) + 0.25 * min(din, dout) * (din < 0) * (dout < 0), + squeeze=float(p["squeeze"]), arch=float(p.get("arch", 1.0))) + + +def apply_brow(pts, ew, p, inner_dir, up=(0.0, -1.0), age_p=None): + """move a brow polyline (inner -> outer, pixels) by the spec. inner_dir = unit vector toward the face midline, + up = the face's up vector. Points in between follow the inner/outer weights; the arch is rescaled about the + inner-outer chord.""" + P = np.asarray(pts, np.float64).copy() + o = brow_offsets(p, age_p) + n = len(P) + up = np.asarray(up, np.float64) + ind = np.asarray(inner_dir, np.float64) + a, b = P[0].copy(), P[-1].copy() + ch = b - a + L = np.linalg.norm(ch) + 1e-9 + nrm = np.array([-ch[1], ch[0]]) / L + if np.dot(nrm, up) < 0: + nrm = -nrm + t = np.linspace(0, 1, n) + for i in range(n): + q = P[i] + # height above the chord, rescaled (arch) + s = float(np.dot(q - a, ch) / L ** 2) + base = a + ch * s + h = float(np.dot(q - base, nrm)) + P[i] = base + nrm * h * o["arch"] + dy = (1 - t) * o["din"] + t * o["dout"] + if n >= 3: + dy += np.sin(np.pi * t) * (o["dmid"] - 0.5 * (o["din"] + o["dout"])) + P += (-up[None, :]) * (dy[:, None] * ew) + P += ind[None, :] * ((1 - t) ** 2)[:, None] * (o["squeeze"] * ew) + # surprise curves the whole brow up: lift the middle a little more than the ends + if o["arch"] > 1.05: + P += up[None, :] * (np.sin(np.pi * t) * (o["arch"] - 1.0) * 0.08 * ew)[:, None] + return P + + +def lid_offsets(p, age_p=None): + """upper-lid move at its apex (ew, +down: covers more iris), lower-lid move (ew, +down), closure 0..1 (1 = shut), + and the squint kind: 'smile' (laugh: lower lid pushed up into an arch, human-319 joy4) or 'squeeze' (crying)""" + up = float(p["upper_lid"]) - 0.05 + lo = -float(p["lower_lid"]) + if age_p: + up += age_p.get("hood", 0.0) * 0.6 + closure, kind = 0.0, None + if p.get("opening") is not None: + closure = float(np.clip(1.0 - p["opening"] / 0.33, 0, 1)) + kind = "smile" if p["corner"] < -0.1 else "squeeze" + return dict(up=up, lo=lo, closure=closure, kind=kind) + + +def mouth_geom(p, hw0=0.75, lip_up=0.10, lip_lo=0.14, age_p=None, n=17): + """the mouth in mouth-frame ew units: x right, y DOWN, origin = the neutral slit centre. + Returns dict(kind 'closed'|'open', hw, corners [(x,y) left, right], slit (n,2) for closed mouths, + top/bot (n,2) the opening edges L->R, open_poly, teeth_up, teeth_lo, tongue (polys or None), lip_up / lip_lo + (vermilion polygons), chin_dy (how far the chin drops, ew), press 0..1, dimple (x,y) or None).""" + hw = hw0 * float(p["mouth_w"]) + if age_p: + lip_up *= age_p.get("lip_scale", 1.0) + lip_lo *= 0.5 + 0.5 * age_p.get("lip_scale", 1.0) + cs = p.get("corner_side") + cL = cR = float(p["corner"]) + if cs is not None: + cL, cR = float(cs[0]), float(cs[1]) + op = float(p["open"]) + shape = p.get("shape", "line") + u = np.linspace(-1, 1, n) + x = u * hw + cy = np.where(u < 0, cL, cR) * np.abs(u) ** 1.6 # corner lift follows a soft curve + press = float(p.get("press", 0.0)) + out = dict(hw=hw, corners=[(-hw, cL), (hw, cR)], press=press, chin_dy=0.0, dimple=None, teeth_up=None, + teeth_lo=None, tongue=None, open_poly=None, slit=None, top=None, bot=None) + if cs is not None: # contempt: one dimple at the raised corner + k = 0 if cL < cR else 1 + out["dimple"] = (out["corners"][k][0] * 1.08, out["corners"][k][1] - 0.01) + if op < 0.04: + # closed: slit; a smile is a U (centre stays, corners up), sadness an inverted U (human-308 / 309) + dip = 0.025 * (1 - press) # the tubercle dip + slit = np.stack([x, cy + dip * np.cos(u * np.pi / 2) ** 2 + float(p.get("snarl", 0)) * -0.3 * np.cos(u * np.pi / 2) ** 4], 1) + out.update(kind="closed", slit=slit) + lu = lip_up * (1 - 0.6 * press) + ll = lip_lo * (1 - 0.6 * press) * (1 + 0.3 * float(p.get("chin_up", 0))) + top_lip = np.stack([x, slit[:, 1] - lu * np.sin(np.pi * (u + 1) / 2) ** 0.7 * (1 - 0.25 * np.cos(u * np.pi * 2.5) ** 2 * (np.abs(u) < .4))], 1) + bot_lip = np.stack([x * 0.92, slit[:, 1] + ll * np.sin(np.pi * (u + 1) / 2) ** 0.8], 1) + out["lip_up"] = np.vstack([slit, top_lip[::-1]]) + out["lip_lo"] = np.vstack([slit, bot_lip[::-1]]) + return out + # ---- open shapes: top and bottom edges of the lip gap + env = np.clip(1 - u ** 2, 0, 1) + if shape == "wedge": # joy: a straight upper edge, a deeper narrower curved lower edge, angular corners + cc = np.where(u < 0, cL, cR) + top = cc + op * 0.06 * env # nearly straight between the raised corners + bot = cc + op * env ** 0.85 + out["chin_dy"] = op * 0.3 # Hamm: a laugh barely moves the chin (human-270) + elif shape == "oval": # surprise: a relaxed oval, taller than wide, no corners; the jaw drops + ang = np.linspace(np.pi, 0, n) + ex, ey = np.cos(ang), np.sin(ang) + x = ex * hw + c = op * 0.42 + top = c - ey * op * 0.5 + bot = c + ey * op * 0.5 + out["chin_dy"] = op * 0.75 + elif shape == "stretch": # fear: pulled sideways, wider than tall, the upper lip thinned flat + top = cy - op * 0.15 * env ** 0.3 + bot = cy + op * 0.85 * env ** 0.45 + out["chin_dy"] = op * 0.45 + elif shape == "snarl": # disgust: upper lip centre raised square (AU10), lower lip down and out + sn = float(p.get("snarl", 0.1)) + top = cy - (op * 0.3 + sn) * np.clip(1.25 - np.abs(u) * 1.25, 0, 1) ** 0.4 + bot = cy + op * 0.7 * env ** 0.6 + out["chin_dy"] = op * 0.3 + else: # square (shout, crying): wider than tall, flattened top and bottom, rounded corners + sn = float(p.get("snarl", 0.0)) + top = cy - (op * 0.42 + sn * 0.6) * env ** 0.25 - sn * 0.5 * env ** 3 + bot = cy + op * 0.58 * env ** 0.3 + if p["corner"] > 0.05: # crying: corners pulled down, upper edge an arch + top = top - op * 0.15 * env + out["chin_dy"] = op * 0.6 + T = np.stack([x, top], 1) + B = np.stack([x, bot], 1) + out.update(kind="open", top=T, bot=B, open_poly=np.vstack([T, B[::-1][1:-1]])) + gap = bot - top + # teeth (human-058): upper teeth more than lower; they stop 0.1-0.2 mouth width short of each corner + inner = np.abs(u) < (0.78 if shape != "oval" else 0.6) + if p.get("teeth") in ("upper", "both") and inner.sum() > 2: + th = np.minimum(gap * (0.42 if p.get("teeth") == "upper" else 0.32), 0.16) + ti = np.where(inner)[0] + up_edge = T[ti] + lo_edge = np.stack([T[ti, 0], T[ti, 1] + th[ti] * np.clip(1 - u[ti] ** 2 * 0.4, 0, 1)], 1) + out["teeth_up"] = np.vstack([up_edge, lo_edge[::-1]]) + if p.get("teeth") in ("lower", "both") and inner.sum() > 2: + th = np.minimum(gap * 0.28, 0.12) + ti = np.where(inner)[0] + lo_edge = B[ti] + up_edge = np.stack([B[ti, 0], B[ti, 1] - th[ti] * np.clip(1 - u[ti] ** 2 * 0.5, 0, 1)], 1) + out["teeth_lo"] = np.vstack([up_edge, lo_edge[::-1]]) + if p.get("tongue") and op >= 0.3: + a = np.linspace(0, 2 * np.pi, 20, endpoint=False) + bc = float(B[n // 2, 1]) + out["tongue"] = np.stack([np.cos(a) * hw * 0.42, bc - gap.max() * 0.22 + np.sin(a) * gap.max() * 0.24], 1) + # lips around the gap: thinned by stretch (human-310 fear: upper lip almost gone) + k_up = {"stretch": 0.35, "wedge": 0.55, "square": 0.5, "oval": 0.6, "snarl": 0.6}.get(shape, 0.6) + lu = lip_up * k_up + ll = lip_lo * {"stretch": 0.6, "wedge": 0.75, "square": 0.7, "oval": 0.8, "snarl": 1.1}.get(shape, 0.8) + env2 = np.clip(1 - (T[:, 0] / max(hw, 1e-6)) ** 2, 0, 1) ** 0.5 + out["lip_up"] = np.vstack([T, (T + np.stack([np.zeros(n), -lu * env2], 1))[::-1]]) + out["lip_lo"] = np.vstack([B, (B + np.stack([np.zeros(n), ll * env2], 1))[::-1]]) + return out + + +def transform(pts, c, ex, ey): + """mouth / eye frame (ew units) -> pixels: c = the frame origin in px, ex = the px vector of +1 ew along x, + ey = the px vector of +1 ew down""" + if pts is None: + return None + P = np.asarray(pts, np.float64) + return np.asarray(c, np.float64)[None, :] + P[:, :1] * np.asarray(ex)[None, :] + P[:, 1:2] * np.asarray(ey)[None, :] + + +def mouth_px(p, c, ex, ey, hw0=0.75, lip_up=0.10, lip_lo=0.14, age_p=None, n=17): + """mouth_geom mapped to pixels (every polygon / polyline key transformed; scalars kept in ew)""" + g = mouth_geom(p, hw0, lip_up, lip_lo, age_p, n) + out = dict(g) + for k in ("slit", "top", "bot", "open_poly", "teeth_up", "teeth_lo", "tongue", "lip_up", "lip_lo"): + out[k] = transform(g.get(k), c, ex, ey) + out["corners"] = transform(np.array(g["corners"]), c, ex, ey) + out["dimple"] = None if g["dimple"] is None else transform(np.array([g["dimple"]]), c, ex, ey)[0] + out["ew"] = float(np.linalg.norm(ex)) + return out + + +# --------------------------------------------------------------------------------------------- creases (pixels) +def _bez(P, n=12): + P = np.asarray(P, np.float64) + t = np.linspace(0, 1, n)[:, None] + if len(P) == 3: + return (1 - t) ** 2 * P[0] + 2 * (1 - t) * t * P[1] + t ** 2 * P[2] + return (1 - t) ** 3 * P[0] + 3 * (1 - t) ** 2 * t * P[1] + 3 * (1 - t) * t ** 2 * P[2] + t ** 3 * P[3] + + +def creases(spec, lm, ew, strengths=None): + """wrinkle and fold marks as pixel polylines: list of dict(kind, pts, s (0..1 strength), w (width in ew), + side ('L'/'R'/None)). lm: landmarks in px: eye_L, eye_R (centres), eye_out_L/R, eye_in_L/R (corners), + brow_in_L/R, brow_out_L/R, nose_wing_L/R, nose_root, mouth_L, mouth_R (corners), mouth_c, chin, top (forehead + top: hairline or brow + 1.6 ew), vis_L / vis_R (0..1 how much of that side shows). L/R = the SUBJECT's sides. + Faint by design: human-061 wrinkles are delicate shadow lines, at most 1 per set and side below 60.""" + S = strengths if strengths is not None else marks_for(spec, ew) + nl = spec.age_p["lines_per_set"] + g = lambda k: np.asarray(lm[k], np.float64) + eL, eR = g("eye_L"), g("eye_R") + xv = eL - eR + xv = xv / (np.linalg.norm(xv) + 1e-9) # unit toward the subject's LEFT + yv = np.array([-xv[1], xv[0]]) # down + if yv[1] < 0: + yv = -yv + out = [] + + def add(kind, pts, s, w=0.05, side=None): + if s > 0.05: + out.append(dict(kind=kind, pts=np.asarray(pts, np.float64), s=float(min(1.0, s)), w=w, side=side)) + + for sd, sx in (("L", 1.0), ("R", -1.0)): + vis = float(lm.get("vis_" + sd, 1.0)) + if vis < 0.25: + continue + o = xv * sx # outward on this side + mc = g("mouth_" + sd) + wing = g("nose_wing_" + sd) + if S.get("nasolabial"): + s = S["nasolabial"] + a = wing + o * 0.12 * ew - yv * 0.05 * ew + b = mc + o * (0.14 + 0.06 * s) * ew - yv * 0.05 * ew + c = mc + o * (0.10 + 0.04 * s) * ew + yv * (0.25 + 0.15 * s) * ew + add("nasolabial", _bez([a, a + (b - a) * 0.5 + o * 0.12 * ew, b, c], 14)[: int(10 + 4 * s)], s * vis, 0.06, sd) + if S.get("marionette"): + s = S["marionette"] + add("marionette", _bez([mc + o * 0.06 * ew + yv * 0.06 * ew, mc + o * 0.08 * ew + yv * 0.3 * ew, + mc + o * 0.02 * ew + yv * 0.55 * ew]), s * vis * .8, 0.05, sd) + eo = g("eye_out_" + sd) + if S.get("crow"): + s = S["crow"] + k = 1 + int(s > 0.55) + int(s > 0.85 and nl > 1) + for i in range(k): + ang = (-0.35 + 0.35 * i) if k > 1 else 0.0 + d = o * math.cos(ang) + yv * math.sin(ang) + st = eo + o * 0.12 * ew + add("crow", [st, st + d * (0.28 + 0.08 * s) * ew + yv * 0.03 * ew], s * vis * .85, 0.04, sd) + ec = g("eye_" + sd) + if S.get("lowerlid") or S.get("bag"): + s = max(S.get("lowerlid", 0), S.get("bag", 0)) + dd = 0.30 + 0.15 * S.get("bag", 0) + p0 = ec - o * 0.15 * ew + yv * dd * ew + p2 = eo + o * 0.02 * ew + yv * (dd - 0.12) * ew + add("lowerlid", _bez([p0, (p0 + p2) / 2 + yv * 0.10 * ew, p2]), s * vis * .8, 0.045, sd) + if S.get("flush"): + add("flush", [ec + yv * 0.7 * ew + o * 0.1 * ew], S["flush"] * vis, 0.55, sd) + if S.get("tears"): + ei = g("eye_in_" + sd) + st = ei + o * 0.15 * ew + yv * 0.18 * ew + add("tear", _bez([st, st + yv * 0.6 * ew + o * 0.08 * ew, st + yv * 1.25 * ew + o * 0.02 * ew]), + S["tears"] * vis, 0.09, sd) + if S.get("cheek_hollow") and S["cheek_hollow"] > .3: + z = g("eye_" + sd) + yv * 1.25 * ew + o * 0.45 * ew + add("cheek", _bez([z - yv * 0.25 * ew, z + o * 0.05 * ew, z + yv * 0.35 * ew - o * 0.08 * ew]), + S["cheek_hollow"] * vis * .6, 0.05, sd) + if S.get("nose_side"): + nr = g("nose_root") + st = nr + o * 0.12 * ew + yv * 0.2 * ew + for i in range(2): + q = st + yv * 0.12 * i * ew + add("nose_side", [q, q + o * 0.14 * ew + yv * 0.06 * ew], S["nose_side"] * vis * .8, 0.035, sd) + bi = (g("brow_in_L") + g("brow_in_R")) / 2 + top = g("top") if "top" in lm else bi - yv * 1.6 * ew + if S.get("forehead"): + s = S["forehead"] + k = max(1, min(3, int(round(1 + 2 * s)))) if nl > 1 or s > .7 else 1 + int(s > .6) + bo_L, bo_R = g("brow_out_L"), g("brow_out_R") + span = float(np.dot(bi - top, yv)) + for i in range(k): + f = 0.28 + 0.2 * i + if f * 1.0 > 0.85: + break + yoff = -yv * span * f + a, b = bo_R + yoff - xv * 0.0, bo_L + yoff + m = (a + b) / 2 - yv * 0.08 * ew + add("forehead", _bez([a + (b - a) * 0.1, m, b - (b - a) * 0.1]), s * (1 - 0.2 * i), 0.04) + if S.get("forehead_c"): + s = S["forehead_c"] + for i in range(1 + int(s > .6)): + c = bi - yv * (0.42 + 0.22 * i) * ew + add("forehead_c", _bez([c - xv * 0.45 * ew + yv * 0.08 * ew, c - yv * 0.06 * ew, + c + xv * 0.45 * ew + yv * 0.08 * ew]), s, 0.04) + if S.get("glabella"): + s = S["glabella"] + for sx in ((-1, 1) if s > .5 else (1,)): + c = bi + xv * sx * 0.09 * ew + add("glabella", [c - yv * 0.05 * ew, c - yv * 0.35 * ew + xv * sx * 0.03 * ew], s, 0.045) + if S.get("nose_root"): + nr = g("nose_root") + add("nose_root", _bez([nr - xv * 0.22 * ew, nr - yv * 0.04 * ew, nr + xv * 0.22 * ew]), S["nose_root"], 0.04) + if S.get("chin"): + ch, mcc = g("chin"), g("mouth_c") + z = mcc + (ch - mcc) * 0.55 + add("chin", _bez([z - xv * 0.28 * ew, z + yv * 0.06 * ew, z + xv * 0.28 * ew]), S["chin"] * .8, 0.04) + if S.get("lip_lines"): + mcc = g("mouth_c") + for k in (-0.25, 0.0, 0.22): + q = mcc + xv * k * ew - yv * 0.12 * ew + add("lip_line", [q, q - yv * 0.12 * ew], S["lip_lines"] * .7, 0.03) + if S.get("dimple") and spec.p.get("corner_side") is not None: + cs = spec.p["corner_side"] + sd = "R" if cs[0] < cs[1] else "L" + sx = 1.0 if sd == "L" else -1.0 + mc = g("mouth_" + sd) + add("dimple", _bez([mc + xv * sx * 0.06 * ew - yv * 0.06 * ew, mc + xv * sx * 0.12 * ew, + mc + xv * sx * 0.06 * ew + yv * 0.07 * ew]), S["dimple"], 0.05, sd) + if S.get("corner"): + for sd, sx in (("L", 1.0), ("R", -1.0)): + if float(lm.get("vis_" + sd, 1.0)) < 0.3: + continue + mc = g("mouth_" + sd) + add("corner", _bez([mc + xv * sx * 0.03 * ew - yv * 0.07 * ew, mc + xv * sx * 0.10 * ew - yv * 0.01 * ew, + mc + xv * sx * 0.07 * ew + yv * 0.05 * ew]), S["corner"] * .8, 0.04, sd) + return out + + +def frame_from_eyes(eye_L, eye_R): + """(xv, yv): the unit vector toward the subject's LEFT eye and the face's down vector""" + xv = np.asarray(eye_L, np.float64) - np.asarray(eye_R, np.float64) + xv = xv / (np.linalg.norm(xv) + 1e-9) + yv = np.array([-xv[1], xv[0]]) + if yv[1] < 0: + yv = -yv + return xv, yv + + +def spec_for(fig): + """the Spec for a Figure (cached on the person)""" + P = fig.person + sp = getattr(P, "face_spec", None) + if sp is None: + sp = spec_from_text(fig.text or "", P.age, P.sex, fig.seed, fig.framing) + P.face_spec = sp + return sp diff --git a/pydraw/figure/face_apply.py b/pydraw/figure/face_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb44a72ff31563a3613e70961d180345509dcc8 --- /dev/null +++ b/pydraw/figure/face_apply.py @@ -0,0 +1,150 @@ +"""figure.face_apply: put a face.Spec onto the kit Layout (wave 20, faces lane; knobs fx_face > fx_expr / fx_age). + +Moves the kit's own feature geometry so every style that reads the layout (ink reads L.eyes / L.brows / L.mouth, +paint reads L.brows and the eye boxes) gets the expression without new code, and adds what is new: + L.fx the face.Spec (None when the lane is off) + L.fx_ew eye width in px (the expression table's unit) + L.fx_frame (xv, yv) unit vectors: toward the subject's left eye, and the face's down + L.mouth['fx'] face.mouth_px(...) result: kind 'closed'|'open', slit / top / bot / open_poly / teeth_up / + teeth_lo / tongue / lip_up / lip_lo (px polygons), corners, chin_dy (ew) + L.eyes[s] + 'lid' dict(up, lo, closure, kind) in ew; upper / lower / outline moved; 'h' unchanged so a + style's iris keeps its size and white shows above it when the lid lifts (anger 3+, fear, surprise) + L.creases face.creases(...) list of dict(kind, pts px, s 0..1, w ew, side) +The chin drops with an open jaw (surprise, shouting; NOT for a laugh: Hamm's triangle, human-270). +""" +import math +import numpy as np +from . import face as F + + +def _lm(L, ew, xv, yv): + pt = L.pt + lm = {} + for s in ("L", "R"): + e = L.eyes[s] + U = np.asarray(e["upper"], np.float64) + D = np.asarray(e["lower"], np.float64) + lm["eye_" + s] = np.asarray(e["c"], np.float64) + lm["eye_in_" + s] = U[0] + lm["eye_out_" + s] = U[-1] + b = np.asarray(L.brows[s], np.float64) + lm["brow_in_" + s], lm["brow_out_" + s] = b[0], b[-1] + lm["nose_wing_" + s] = np.asarray(pt["nose_wing_" + s], np.float64) + lm["vis_" + s] = float(np.clip((e.get("fs", 1.0) - 0.35) / 0.45, 0, 1)) + mo = L.mouth.get("fx") + if mo is not None: + cL, cR = mo["corners"][1], mo["corners"][0] # corners are image-ordered (x right = subject's left) + else: + cL, cR = np.asarray(pt["mouth_L"]), np.asarray(pt["mouth_R"]) + lm["mouth_L"], lm["mouth_R"] = np.asarray(cL, np.float64), np.asarray(cR, np.float64) + lm["mouth_c"] = np.asarray(pt["mouth_c"], np.float64) + lm["nose_root"] = np.asarray(pt["nose_root"], np.float64) + lm["chin"] = np.asarray(pt["chin"], np.float64) + lm["top"] = np.asarray(pt["hairline"], np.float64) + return lm + + +def apply(L, person, spec, cn, Hpx): + L.fx = spec + L.creases = [] + ew = float(cn["eye_w"]) * float(Hpx) + xv, yv = F.frame_from_eyes(L.pt["eye_L"], L.pt["eye_R"]) + L.fx_ew, L.fx_frame = ew, (xv, yv) + p = spec.p + do_expr = F.active("fx_expr") and not spec.neutral + ap = spec.age_p if F.active("fx_age") else None + # ---- brows (human-315: inner end, outer end, squeeze, arch) + if do_expr or ap: + for s in ("L", "R"): + b = np.asarray(L.brows[s], np.float64) + ind = xv * (-1.0 if s == "L" else 1.0) # toward the midline + fs = float(L.eyes[s].get("fs", 1.0)) + L.brows[s] = F.apply_brow(b, ew * max(0.45, fs), p if do_expr else F._N, ind, up=-yv, age_p=ap).astype(np.float32) + # ---- lids + for s in ("L", "R"): + e = L.eyes[s] + lid = F.lid_offsets(p if do_expr else F._N, ap) + e["lid"] = lid + if not (do_expr or ap): + continue + U = np.asarray(e["upper"], np.float64) + D = np.asarray(e["lower"], np.float64) + n = len(U) + t = np.linspace(0, 1, n) + prof = np.sin(np.pi * t) ** 0.8 + U = U + yv[None, :] * (lid["up"] * ew * prof)[:, None] + D = D + yv[None, :] * (lid["lo"] * ew * np.sin(np.pi * t) ** 0.9)[:, None] + if ap is not None and ap.get("eye_open", 1.0) < 1.0: # human-330: eye opening -15% at 80 + mid = (U + D) / 2 + U = mid + (U - mid) * ap["eye_open"] + D = mid + (D - mid) * ap["eye_open"] + if lid["closure"] > 0: + o_t = float(p["opening"] or 0.0) * ew + h = ((D - U) @ yv) + if lid["kind"] == "smile": # laugh: the lower lid rides up into an arch under the lid (^ ^) + newU = U + yv[None, :] * ((h - o_t) * 0.35 * prof)[:, None] + newD = newU + yv[None, :] * (o_t * prof)[:, None] - yv[None, :] * (0.10 * ew * prof)[:, None] + else: # crying: squeezed shut from both lids, the upper lid lowered more + newU = U + yv[None, :] * ((h - o_t) * 0.6 * prof)[:, None] + newD = newU + yv[None, :] * (o_t * prof)[:, None] + U, D = newU, newD + e["upper"], e["lower"] = U.astype(np.float32), D.astype(np.float32) + e["outline"] = np.vstack([U, D[::-1][1:-1]]).astype(np.float32) + e["inner"], e["outer"] = e["upper"][0], e["upper"][-1] + # ---- mouth + mL, mR = np.asarray(L.pt["mouth_L"], np.float64), np.asarray(L.pt["mouth_R"], np.float64) + hw0 = max(0.35, float(cn["mouth_w"]) / 2 / float(cn["eye_w"])) + exv = (mL - mR) / 2.0 / hw0 + eyv = yv * ew + c = np.asarray(L.pt["mouth_c"], np.float64) + lip_up = 0.035 / float(cn["eye_w"]) * 0.9 + g = F.mouth_px(p if do_expr else F._N, c, exv, eyv, hw0=hw0, lip_up=lip_up, lip_lo=lip_up * 1.3, age_p=ap) + if do_expr or ap: + M = L.mouth + M["fx"] = g + # aliases the styles lane's design.py reads (board 15:54): the lip gap and the upper-teeth band, px polygons + M["open"] = None if g["open_poly"] is None else g["open_poly"].astype(np.float32) + M["teeth"] = None if g["teeth_up"] is None else g["teeth_up"].astype(np.float32) + if g["kind"] == "closed": + M["line"] = g["slit"].astype(np.float32) + else: + M["line"] = g["top"].astype(np.float32) + M["upper"] = g["lip_up"].astype(np.float32) + M["lower"] = g["lip_lo"].astype(np.float32) + M["top"] = g["lip_up"][int(np.argmin(g["lip_up"] @ yv))].astype(np.float32) + M["bot"] = g["lip_lo"][int(np.argmax(g["lip_lo"] @ yv))].astype(np.float32) + M["w"] = float(np.linalg.norm(g["corners"][1] - g["corners"][0])) + M["smile"] = float(np.clip(-p["corner"] / 0.2, 0, 1)) if do_expr else 0.0 + # the jaw drops with the open mouth: everything below the mouth line slides down, ramped to the chin + cd = float(g.get("chin_dy", 0.0)) * ew + if cd > 0.5: + _drop_chin(L, c, yv, cd) + if do_expr or ap: + L.creases = F.creases(spec, _lm(L, ew, xv, yv), ew, F.marks_for(spec if do_expr else _age_only(spec), ew)) + return L + + +def _age_only(spec): + s = F.Spec("neutral", 1, dict(F._N), spec.age, spec.sex) + return s + + +def _drop_chin(L, mc, yv, d): + """slide points below the mouth line down by up to d px (0 at the mouth, d at the chin)""" + chin = np.asarray(L.pt["chin"], np.float64) + span = max(1.0, float((chin - mc) @ yv)) + + def mv(P): + P = np.asarray(P, np.float64) + h = (P - mc[None, :]) @ yv + k = np.clip(h / span, 0, 1.0) ** 0.9 + k = np.where(h > span, 1.0, k) + return (P + yv[None, :] * (d * k)[:, None]).astype(np.float32) + L.face = mv(L.face) + for k in ("chin", "chin_front", "chin_L", "chin_R"): + if k in L.pt: + L.pt[k] = mv(L.pt[k][None])[0] + L.jaw = {s: mv(v) for s, v in L.jaw.items()} + L.midline = mv(L.midline) + if getattr(L, "beard", None) is not None: + L.beard["outline"] = mv(L.beard["outline"]) diff --git a/pydraw/figure/face_draw.py b/pydraw/figure/face_draw.py new file mode 100644 index 0000000000000000000000000000000000000000..9390fd042127fa141ca4cfd8b261d2ae2f821f87 --- /dev/null +++ b/pydraw/figure/face_draw.py @@ -0,0 +1,622 @@ +"""figure.face_draw: the faces lane's expression / age marks drawn in each style's own primitives (wave 20). + +Each style keeps its face model; the hooks (one guarded call per style, knob fx_face) hand this module the style's +canvas and frame, and the marks are drawn LAST over that style's features (WAVE20 method step 6-7): + ink_extras(ip) InkPortrait after its mouth(): open mouth (a designed black), teeth as paper, creases, tears + (anime / pixel / paint adapters below) +Geometry comes from figure.face (ew units) and figure.face_apply (the kit layout). +""" +import math +import numpy as np +from . import face as F + + +def _ramp(a, b): + return np.linspace(a, b, 2) + + +# ------------------------------------------------------------------------------------------------------------- ink +def ink_extras(ip): + """ip = style_ink.InkPortrait (after eye/brows/nose/mouth). The opening of an open mouth is a spotted black (pen) + or a dense tone (pencil / charcoal); upper teeth are paper with a soft lower edge (human-058: no lines between + teeth, they stop short of the corners); the lower lip gets one shadow stroke; creases are thin, light strokes + (human-061: delicate shadow lines, never the darkest marks).""" + from .style_ink import poly_mask, spline + L = ip.L + sp = getattr(L, "fx", None) + if sp is None: + return + pen, sc = ip.pen, ip.s + ew = float(getattr(L, "fx_ew", 20.0)) + g = L.mouth.get("fx") + if g is not None and g["kind"] == "open": + op = np.asarray(g["open_poly"], float) + pen.fill(op, 0.93 if ip.medium == "pen" else 0.8) + m_open = poly_mask(op, ip.W, ip.H) + pen.erase(m_open & ~ip.face_m, keep=0.0) # the far corner tucks behind the far cheek (human-335) + for key, keep in (("tongue", 0.55), ("teeth_up", 0.0), ("teeth_lo", 0.0)): + P = g.get(key) + if P is None: + continue + m = poly_mask(np.asarray(P, float), ip.W, ip.H) & m_open + pen.erase(m, keep=keep) + if key.startswith("teeth"): + Q = np.asarray(P, float) + half = len(Q) // 2 + edge = Q[half:] if key == "teeth_up" else Q[:half] + pen.stroke(spline(edge, step=1.0), 0.6, "swell", 0.35) + top, bot = np.asarray(g["top"], float), np.asarray(g["bot"], float) + pen.stroke(spline(top, step=1.0), 1.6 * ip.acc, "ends", 0.95) + pen.stroke(spline(bot, step=1.0)[2:-2], 1.0, "swell", 0.7) + lo = np.asarray(g["lip_lo"], float) + n = len(lo) // 2 + pen.stroke(spline(lo[n:][::-1], step=1.0)[3:-3] + np.array([0, 1.0 * sc]), 0.8, "swell", 0.5) + for c in L.creases: + _ink_crease(ip, c, ew) + + +def _ink_crease(ip, c, ew): + from .style_ink import spline + pen, sc = ip.pen, ip.s + P = np.asarray(c["pts"], float) + s = c["s"] + if c["kind"] == "flush": + return + if c["kind"] == "tear": + if len(P) < 2: + return + Q = spline(P, step=1.0) + pen.stroke(Q, 0.7, "swell", 0.45 + 0.3 * s) + e = Q[-1] + r = 0.09 * ew + a = np.linspace(0, 2 * np.pi, 14) + drop = np.stack([e[0] + r * np.cos(a) * 0.8, e[1] + r * 0.4 + r * np.sin(a)], 1) + drop[:3, 1] -= r * 0.6 + pen.stroke(drop, 0.8, "even", 0.6 + 0.3 * s) + return + if len(P) < 2: + return + Q = spline(P, step=1.0) + w = (0.55 + 0.55 * s) if c["kind"] in ("nasolabial", "glabella", "nose_root", "dimple", "corner") else (0.45 + 0.4 * s) + pen.stroke(Q, w, "swell", 0.35 + 0.45 * s) + + +# ----------------------------------------------------------------------------------------------------------- pixel +def pixel_features(G, L, light, pal_keys=None): + """style_pixel hook: the module's own draw_features runs first (nose, ears, freckles, sizes), then the eye, brow + and mouth zones go back to the pre-feature skin / beard and are redrawn from the expression spec as glyphs sized + for the pixel grid (human-305: inner brow, upper-lid arc and mouth corners survive to the last pixel).""" + from . import style_pixel as X + sp = getattr(L.get("kit"), "fx", None) + before = G.a.copy() + info = X.draw_features(G, L, light, pal_keys) + if sp is None: + return info + p = sp.p if (F.active("fx_expr") and not sp.neutral) else dict(F._N) + ap = sp.age_p if F.active("fx_age") else None + row, eyes = info["row"], info["eyes"] + if row in ("A", "B"): + return info + n = G.n + K, W_, S0, S1, S2 = X.K, X.W, X.S0, X.S1, X.S2 + SK = X.SKIN_KEYS + P, F_ = L["P"], L["feat"] + masc = L["masc"] + # ---- restore the zones + for x0, y0, g, s, e in eyes: + gw, gh = len(g[0]), len(g) + ya, yb = max(0, y0 - 5), min(n, y0 + gh + 2) + xa, xb = max(0, x0 - 1), min(n, x0 + gw + 1) + zone = before[ya:yb, xa:xb] + cur = G.a[ya:yb, xa:xb] + keep = np.isin(zone, (X.H0, X.H1, X.H2, K)) & np.isin(cur, (X.H0, X.H1, X.H2, K)) & ~np.isin(zone, SK) + cur[~keep] = zone[~keep] + mo = F_["mouth"] + wf = info["wf"] + mw = {"C": 3}.get(row, max(4, int(round(0.30 * wf * mo["fore"])))) + if masc < 0.5 and row in ("E", "F"): + mw = max(4, mw - 1) + mx0 = int(round(mo["x"] - mw / 2)) + my = int(round(mo["y"])) + ya, yb, xa, xb = max(0, my - 2), min(n, my + 3), max(0, mx0 - 2), min(n, mx0 + mw + 2) + G.a[ya:yb, xa:xb] = before[ya:yb, xa:xb] + base_w = max(2.0, float(np.mean([len(g[0]) for _, _, g, _, _ in eyes]))) + lid = F.lid_offsets(p, ap) + brow_key = X.K if X._lum(P["hair_rgb"]) < 0.45 else X.H0 + if P.get("hair_name") in ("white", "gray"): + brow_key = X.H0 + if masc < 0.5 and brow_key == X.K: + brow_key = X.H1 + child = L["child"] + # ---- brows: inner / outer ends moved in whole pixels (sign kept even when the move is under 1 px: the read + # is the slant, human-307 the knot, human-309 the inner end up) + bo = F.brow_offsets(p, ap) + + def q(v, scale): + d = v * scale + if abs(d) < 0.35: + return 0 + return int(np.sign(d) * max(1, round(abs(d)))) + for x0, y0, g, s, e in eyes: + gw = len(g[0]) + by = y0 - (2 if row in ("C", "D") else 3) - (1 if (masc < 0.5 or child > 0.5) and row != "C" else 0) + bl = max(2, int(round(gw * 1.05))) + bx = x0 + (gw - bl) // 2 + inner_left = s > 0 # this eye is on the image right: its inner end is on the left + din, dout = q(bo["din"], gw * 1.3), q(bo["dout"], gw * 1.3) + sq = 1 if bo["squeeze"] >= 0.11 and row in ("E", "F") else 0 + thick = 2 if (row in ("E", "F") and masc >= 0.5) or row == "F" else 1 + pts = [] + for i in range(bl): + t = i / max(1, bl - 1) + tt = t if inner_left else 1 - t # 0 at the inner end + dy = din * (1 - tt) + dout * tt + arch = (1 if 0.3 < tt < 0.8 else 0) * (1 if bo["arch"] > 1.2 else 0) + neutral_tail = 1 if (tt >= 0.85 and abs(din) + abs(dout) == 0 and row != "C") else 0 + x = bx + i + (sq if inner_left else -sq) * (1 - tt > 0.7) + pts.append((x, by + int(round(dy)) - arch + neutral_tail, tt)) + for x, y, tt in pts: + G.px([(x, y)], brow_key, only=SK) + if thick == 2 and tt < 0.75: + G.px([(x, y + 1)], brow_key if tt < 0.5 else S0, only=SK) + # ---- eyes + for x0, y0, g, s, e in eyes: + gw, gh = len(g[0]), len(g) + if lid["closure"] > 0.4: + yb = y0 + gh // 2 + if lid["kind"] == "smile": # ^ ^ : an arch, the lid line bent up + for c in range(gw): + t = abs((c + 0.5) / gw - 0.5) * 2 + G.px([(x0 + c, yb - (1 if t < 0.6 else 0))], K, only=SK + (K,)) + G.px([(x0 + (gw - 1 if s < 0 else 0), yb + 1)], S0, only=SK) + else: # squeezed: a level lid line, the ends pulled down + for c in range(gw): + t = abs((c + 0.5) / gw - 0.5) * 2 + G.px([(x0 + c, yb + (1 if t > 0.75 else 0))], K, only=SK + (K,)) + G.line([(x0, yb - 2), (x0 + gw - 1, yb - 2)], S1, only=(S2,)) + continue + gg = [list(r) for r in g] + lid_row = 1 if (gw >= 10 and any(k == X.S0 for k in gg[0] if k is not None) and gg[0][0] is None) else 0 + up = q(lid["up"], gw * 1.1) + lo = q(lid["lo"], gw * 1.0) + if up < 0: # the lid lifts: sclera above the iris (white shows) + for _ in range(min(2, -up)): + ins = [(W_ if k is not None and k != X.S0 else k) for k in gg[lid_row + 1]] + gg.insert(lid_row + 1, ins) + y0 -= min(2, -up) + elif up > 0: # the lid drops over the iris top + for r in range(lid_row + 1, min(len(gg) - 1, lid_row + 1 + up)): + gg[r] = [(K if k is not None else None) for k in gg[r]] + if lo < 0 and len(gg) > 2: # the lower lid rises: the bottom rows go + for _ in range(min(-lo, len(gg) - 2)): + gg.pop() + last = gg[-1] + gg.append([(S1 if (k is not None and ((c >= gw // 2) == (s > 0) or True)) else None) + for c, k in enumerate(last)]) + gg[-1] = [None if k is None else S1 for k in gg[-1]] + elif lo > 0: # surprise: the lower lid relaxed, a white row under the iris + last = gg[-1] + gg.append([(W_ if k is not None else None) for k in last]) + if sp.p.get("upper_lid", 0) < -0.1 and lo >= 0 and up < 0: # fear / terror: small pupils, white all round + pass + G.stamp(x0, y0, gg, only=SK + (K,)) + # ---- mouth from the expression geometry + ey = np.array([0.0, base_w]) + hw0 = max(0.3, mw / 2.0 / base_w) + # the mouth stays inside the face plate (a turned head: the far corner must not cross the contour) + hull_row = X.poly_mask(L["hull"], n)[min(n - 1, max(0, my))] + xs_ = np.nonzero(hull_row)[0] + k = 1.0 + if len(xs_): + room = min(mo["x"] - xs_.min() - 1.5, xs_.max() - mo["x"] - 0.5) + want = hw0 * base_w * float(p["mouth_w"]) + if want > room > 1: + k = room / want + ex = np.array([base_w * k, 0.0]) + if sp.emotion == "sad" and row != "F": + p = dict(p, teeth="none") # a 2-3 row crying mouth with a tooth row reads as a grin + g = F.mouth_px(p, (mo["x"], my + 0.5), ex, ey, hw0=hw0, age_p=ap) + allow = SK + (X.H0, X.H1, X.H2) + if L.get("beard") and getattr(L["kit"].beard, "get", None) and L["kit"].beard.get("kind") != "mustache": + # the lips show through the beard (beard over the jaw, not the mouth): a skin-shadow hole round the mouth + hm = X.ellipse_mask(mo["x"], my + 0.6 + p["open"] * base_w * 0.4, mw / 2.0 + 0.4, 1.2 + p["open"] * base_w * 0.6, n) + hm &= X.poly_mask(L["hull"], n) & G.mask(K, X.H0, X.H1, X.H2) + G.fill(hm, S1) + allow = allow + (K,) + if g["kind"] == "open": + opm = X.poly_mask(g["open_poly"], n) + if opm.sum() < 2: # keep at least a 2-row hole for a clearly open mouth + cx, cy_ = int(round(mo["x"])), int(round(float(np.mean(g["open_poly"][:, 1])))) + opm[cy_:cy_ + 2, max(0, cx - mw // 2):cx + (mw + 1) // 2] = True + G.fill(opm, K, only=allow) + for key, k in (("teeth_up", W_), ("teeth_lo", W_), ("tongue", S0)): + if g.get(key) is not None: + tm = X.poly_mask(g[key], n) & opm + if key.startswith("teeth") and not tm.any() and row in ("E", "F"): + ys, xs = np.nonzero(opm) + if len(ys): + yy_ = ys.min() if key == "teeth_up" else ys.max() + sel = (ys == yy_) + xs_ = xs[sel] + xs_ = xs_[(xs_ > xs_.min()) & (xs_ < xs_.max())] if len(xs_) > 2 else xs_[:0] + for xq in xs_: + tm[yy_, xq] = True + G.fill(tm, k) + ys, xs = np.nonzero(opm) + if len(ys) and row in ("D", "E", "F"): # the lower lip: a lit shadow cap under the opening + yl = ys.max() + 1 + xl = xs[ys == ys.max()] + G.line([(xl.min(), yl), (xl.max(), yl)], S1, only=(S2,)) + else: + sl = g["slit"] + pts = [(x, y - 0.5) for x, y in sl] + G.line(pts, K, only=allow) + for (cx_, cy_) in (sl[0], sl[-1]): # shadow caps outside the corners + G.px([(int(round(cx_ + (-1 if cx_ < mo["x"] else 1))), int(round(cy_ - 0.5)))], S0, only=(S2, S1)) + if row in ("D", "E", "F"): + lo_y = int(round(float(sl[:, 1].max()))) + 1 + (1 if g["press"] < .3 else 0) + G.line([(mx0 + 1, lo_y), (mx0 + mw - 2, lo_y)], S1, only=(S2,)) + # ---- creases and tears (rows E, F only, never K: research17 faces 15) + if row in ("E", "F") and getattr(L.get("kit"), "creases", None): + KL = L["kit"] + for c in _pixel_creases(sp, L, eyes, base_w, p): + P_ = c["pts"] + if c["kind"] == "tear": + G.line(P_, W_, only=SK) + elif c["kind"] in ("flush",): + continue + elif c["s"] > 0.35: + G.line(P_, S1 if c["s"] < 0.8 else S0, only=(S2, S1)) + return info + + +def _pixel_creases(sp, L, eyes, ew, p): + """face.creases on the pixel grid's own landmarks""" + F_ = L["feat"] + lm = {} + for x0, y0, g, s, e in eyes: + sd = "L" if s > 0 else "R" + gw, gh = len(g[0]), len(g) + lm["eye_" + sd] = np.array([x0 + gw / 2, y0 + gh / 2]) + o = s + lm["eye_out_" + sd] = np.array([x0 + (gw - 1 if o > 0 else 0), y0 + 1]) + lm["eye_in_" + sd] = np.array([x0 + (0 if o > 0 else gw - 1), y0 + gh - 1]) + lm["brow_in_" + sd] = lm["eye_in_" + sd] - [0, 3] + lm["brow_out_" + sd] = lm["eye_out_" + sd] - [0, 3] + lm["vis_" + sd] = float(np.clip((e["fore"] - 0.35) / 0.45, 0, 1)) + nz = F_["nose"] + lm["nose_wing_" + sd] = np.array([nz["x"] + s * max(1.5, ew * 0.4), nz["y"]]) + mo = F_["mouth"] + mw = ew * 1.4 + lm["mouth_L"] = np.array([mo["x"] + mw / 2, mo["y"]]) + lm["mouth_R"] = np.array([mo["x"] - mw / 2, mo["y"]]) + lm["mouth_c"] = np.array([mo["x"], mo["y"]]) + lm["nose_root"] = np.array(F_["nose"]["top"]) + lm["chin"] = np.array(F_["chin"]) + lm["top"] = np.array([mo["x"], L["top"] + 0.18 * L["H"]]) + S = F.marks_for(sp, ew * 1.6) if p is sp.p else F.marks_for(F.Spec("neutral", 1, dict(F._N), sp.age, sp.sex), ew * 1.6) + return F.creases(sp, lm, ew, S) + + +# ----------------------------------------------------------------------------------------------------------- anime +def anime_eye(cv, ctr, ew, eh, side, gaze, p, c, W, inkc, iris_col, skin_sh, smile, lightdir, deferred): + """style_anime._eye with the expression's lids (same unit box: x toward the OUTER corner in ew, y down in half + heights). Lid moves come from face.lid_offsets in ew and are converted to half heights; a lifted lid shrinks the + iris (manga shock / fear: white all round), closed eyes become designed glyphs: laugh = an ink arch (^), + crying = a squeezed arc bowed down.""" + from .style_anime import crv, taper, mix, _eye + sp = p["fx"] + pp = sp.p + lid = F.lid_offsets(pp, sp.age_p) + hh = eh / 2 + k = ew / max(hh, 1e-6) + up = float(np.clip(lid["up"] * k * 0.9, -0.45, 0.6)) + lo = float(np.clip(lid["lo"] * k * 0.9, -0.55, 0.25)) + fem, age = p["sex"] == "f", p["age"] + tilt = np.radians(-6 if fem else -3) * (1 if age != "elderly" else -.5) + ca, sa = np.cos(tilt), np.sin(tilt) + + def T(pts): + pts = np.asarray(pts, float) + x = pts[:, 0] * ew + y = pts[:, 1] * hh + X = x * ca - y * sa + Y = x * sa + y * ca + return np.stack([ctr[0] + side * X, ctr[1] + Y], 1) + lw = W * (3.6 if fem else 3.0) + if lid["closure"] > 0.4: + if lid["kind"] == "smile": + P = crv(T([(-.52, .35), (-.25, -.25), (.1, -.42), (.38, -.2), (.55, .3)]), False, 8) + else: + P = crv(T([(-.52, -.1), (-.2, .3), (.15, .38), (.4, .25), (.55, -.05)]), False, 8) + cv.line(P, np.interp(np.linspace(0, 1, len(P)), [0, .5, 1], [lw * .35, lw * .8, lw * .45]), inkc) + if lid["kind"] != "smile": # crying: the squeeze folds above and below the shut lid (AU6 + AU7) + deferred.append(("ink", crv(T([(-.35, -.55), (0, -.75), (.35, -.6)]), False, 5), W * .55)) + return + # a modified copy of the style's eye: lids moved, iris scaled when the lid lifts + upper = [(-.5, .15), (-.38, -.55), (-.08, -.98), (.22, -.95), (.44, -.55), (.53, -.05)] + prof = lambda x: max(0.0, 1 - (2 * x) ** 2) ** .6 + upper = [(x, y + up * prof(x)) for x, y in upper] + lr = 1.0 + lo + lower = [(.53, -.05), (.45, .45 * lr), (.2, .86 * lr), (-.12, .88 * lr), (-.38, .62 * lr)] + sclera = (252, 252, 250) + covS = cv.fill(crv(T(upper + lower), True, 6), sclera) + Pu = crv(T(upper), False, 8) + cv.line(Pu + np.array([0, hh * .16]), hh * .42, mix(sclera, (150, 150, 165), .6), covS) + gx = gaze * side * .12 + float(sp.gaze[0]) * side * .18 + gy = float(sp.gaze[1]) * .25 + shrink = float(np.clip(1 + up * 1.2, 0.55, 1.0)) if up < -0.05 else 1.0 + irx = (.36 if age != "elderly" else .30) * shrink + iry = (1.08 if age != "elderly" else .95) * shrink + ang = np.linspace(0, 2 * np.pi, 36, endpoint=False) + icx, icy = .02 + gx, .08 + gy + (0.0 if shrink == 1 else 0.1 * up) + dark = mix(inkc, iris_col, .22) + covI = cv.fill(T(np.stack([icx + irx * np.cos(ang), icy + iry * np.sin(ang)], 1)), dark, covS) + cres1 = T(np.stack([icx + irx * .92 * np.cos(ang), icy + .38 * shrink + iry * .62 * np.sin(ang)], 1)) + cv.fill(cres1, iris_col, covI * (1 - cv.cover(T(np.stack([icx + irx * 1.2 * np.cos(ang), icy - .15 + iry * .62 * np.sin(ang)], 1))))) + cv.fill(T(np.stack([icx + irx * .45 * np.cos(ang), icy - .1 * shrink + iry * .5 * np.sin(ang)], 1)), mix(inkc, (0, 0, 0), .3), covI) + hl_side = lightdir * side + hsz = (.12 if age != "elderly" else .08) * (0.8 + 0.2 * shrink) + cv.fill(T(np.stack([icx + hl_side * irx * .35 + hsz * np.cos(ang), icy - .42 * shrink + hsz * 1.9 * np.sin(ang)], 1)), (255, 255, 255), covS) + baby = c.get("baby", 0.0) + lw = W * (4.0 if fem else 3.0) * (.85 if age == "elderly" else 1) * (1 - .55 * baby) + wprof = np.array([.3, .6, .85, 1.0, 1.0, .85]) * lw + lash = [(-.53, .22), (-.38, -.58), (-.08, -1.02), (.22, -.99), (.46, -.58), (.58, -.08)] + lash = [(x, y + up * prof(x)) for x, y in lash] + Pl = crv(T(lash), False, 8) + cv.line(Pl, np.interp(np.linspace(0, 1, len(Pl)), np.linspace(0, 1, 6), wprof), inkc) + Po = crv(T([(.56, -.06), (.55, .25 * lr), (.46, .52 * lr)]), False, 4) + cv.line(Po, np.linspace(lw * .45, lw * .15, len(Po)), inkc) + lo_ = crv(T([(-.22 + gx * .8, .86 * lr + .05), (.05 + gx * .8, .95 * lr + .05), (.32 + gx * .8, .80 * lr + .05)]), False, 5) + cv.line(lo_, taper(len(lo_), W * (1.35 if fem else 1.15) * (1 - .4 * baby), ends=.35), inkc) + if age in ("adult", "elderly") or (fem and age == "teen"): + deferred.append(("ink", crv(T([(-.12, -1.12 + up), (.15, -1.24 + up), (.40, -1.0 + up)]), False, 5), W * .55)) + if age == "elderly": + deferred.append(("ink", crv(T([(-.3, 1.25), (.05, 1.4), (.35, 1.2)]), False, 5), W * .55)) + if lo < -0.15: # cheek pushed up under the eye (AU6): a short arc + deferred.append(("ink", crv(T([(-.2, 1.2 + lo), (.1, 1.32 + lo), (.38, 1.15 + lo)]), False, 5), W * .5)) + + +def anime_mouth(cv, mc, mw, H, W, Wi, inkc, mouthc, skin, skin_sh, covF, p): + """the expression mouth in anime marks: an open mouth is a dark warm cel shape with tongue and teeth shapes and + an ink top edge (A7 extended); a closed one is the lip-brown line bent by the corners. Returns the mouth px + geometry (for the marks pass).""" + from .style_anime import crv, taper, mix + sp = p["fx"] + pp = dict(sp.p) + # anime mouths are tiny when shut and big when open: the open size is measured in mouth widths + big = 1.0 + 0.9 * min(1.0, pp["open"] / 0.6) # manga: a shout / scream mouth is as wide as an eye + ex = np.array([mw * big, 0.0]) + ey = np.array([0.0, mw * (1.5 * big if pp["open"] > 0.04 else 0.7)]) + # a turned head: slide the mouth toward the face centre until its far corner sits inside the face plate + hw = 0.5 * big * mw * float(pp["mouth_w"]) + yy = int(np.clip(round(mc[1]), 0, covF.shape[0] - 1)) + xs = np.nonzero(covF[yy] > .5)[0] + mc = np.asarray(mc, float).copy() + if len(xs): + m = 0.012 * H + lo_, hi_ = xs.min() + m + hw, xs.max() - m - hw + if lo_ <= hi_: + mc[0] = float(np.clip(mc[0], lo_, hi_)) + else: + mc[0] = (xs.min() + xs.max()) / 2 + ex = ex * max(0.5, (xs.max() - xs.min() - 2 * m) / (2 * hw)) + g = F.mouth_px(pp, mc, ex, ey, hw0=0.5, age_p=None) + if g["kind"] == "open": + Pm = crv(g["open_poly"], True, 3) + cov = cv.fill(Pm, (110, 36, 40), covF) + if g.get("tongue") is not None: + cv.fill(crv(g["tongue"], True, 3), (228, 120, 118), cov) + for key in ("teeth_up", "teeth_lo"): + if g.get(key) is not None: + cv.fill(crv(g[key], True, 2), (252, 250, 246), cov) + cv.line(Pm, W * .9, inkc, closed=True) + top = crv(g["top"], False, 4) + cv.line(top, np.interp(np.linspace(0, 1, len(top)), [0, .5, 1], [W * .9, W * 1.5, W * .9]), inkc) + bot = np.asarray(g["bot"], float) + sh = crv(bot[3:-3] + np.array([0, .018 * H]), False, 4) + if len(sh) > 2: + cv.line(sh, taper(len(sh), Wi * 1.2), skin_sh, covF) + else: + sl = crv(g["slit"], False, 4) + w = np.interp(np.linspace(0, 1, len(sl)), [0, .2, .5, .8, 1], np.array([.45, 1.0, 1.1, 1.0, .45]) * W * 1.35) + cv.line(sl, w, mouthc) + if g["press"] > 0.3: # pressed lips: a short shadow tick above and below + cv.line(crv(g["slit"][4:-4] + np.array([0, .018 * H]), False, 3), Wi * .8, skin_sh, covF) + cv.fill(crv(np.array([mc + np.array([-mw * .2, .03 * H]), mc + np.array([mw * .25, .03 * H]), + mc + np.array([0, .042 * H])]), True, 4), skin_sh, covF) + if g["dimple"] is not None: + d = g["dimple"] + cv.line(crv(np.array([d + [0, -.01 * H], d + [.006 * H, 0], d + [0, .01 * H]]), False, 3), Wi * .8, inkc) + return g + + +def anime_marks(cv, p, eyes_px, nose_tip, mc, mw, H, W, ew_px, inkc, skin, skin_sh, covF, sgn): + """creases, tears and flush for anime: few interior-weight lines (anime keeps the face clean: only the folds + that carry the read: glabella knot, laugh / cry cheek folds, worry lines, nose-side snarl), tears as pale blue + cel streams with an ink edge, flush as hatch ticks""" + from .style_anime import crv, taper, mix + sp = p["fx"] + if sp is None: + return + S = F.marks_for(sp, ew_px) + keep = {"glabella", "forehead_c", "nose_side", "nose_root", "tears", "flush", "nasolabial", "chin", "forehead"} + if p["age"] == "elderly": + keep |= {"crow", "lowerlid", "marionette"} + S = {k: v for k, v in S.items() if k in keep} + if not S: + return + eyes = {("L" if s > 0 else "R"): (ctr, ws) for s, ctr, ws in eyes_px} + lm = {} + for sd, (ctr, ws) in eyes.items(): + s = 1 if sd == "L" else -1 + e = ew_px * ws + lm["eye_" + sd] = np.asarray(ctr, float) + lm["eye_out_" + sd] = ctr + np.array([s * e * .55, -.0]) + lm["eye_in_" + sd] = ctr + np.array([-s * e * .5, .2 * e]) + lm["brow_in_" + sd] = ctr + np.array([-s * e * .45, -.9 * e]) + lm["brow_out_" + sd] = ctr + np.array([s * e * .55, -.85 * e]) + lm["nose_wing_" + sd] = nose_tip + np.array([s * .03 * H, 0]) + lm["vis_" + sd] = float(np.clip((ws - .5) / .4, 0, 1)) + lm["mouth_L"], lm["mouth_R"] = mc + np.array([mw * .55, 0]), mc - np.array([mw * .55, 0]) + lm["mouth_c"], lm["nose_root"] = np.asarray(mc, float), nose_tip - np.array([0, .12 * H]) + lm["chin"] = mc + np.array([0, .09 * H]) + lm["top"] = (lm["brow_in_L"] + lm["brow_in_R"]) / 2 - np.array([0, .22 * H]) + for cz in F.creases(sp, lm, ew_px * .55, S): + P = np.asarray(cz["pts"], float) + if cz["kind"] == "tear": + sd = cz["side"] + ctr, ws = eyes.get(sd, (None, 1)) + if ctr is None: + continue + s_ = 1 if sd == "L" else -1 + e = ew_px * ws + st = np.asarray(ctr, float) + np.array([s_ * e * .12, e * .42]) + P = np.array([st, st + np.array([s_ * e * .04, .09 * H]), st + np.array([s_ * e * .02, .2 * H])]) + Q = crv(P, False, 4) + w = np.linspace(.02, .045, len(Q)) * H + cov = cv.line(Q, w, (176, 214, 240), covF) + cv.line(Q + np.array([sgn * .006 * H, 0]), taper(len(Q), W * .55), mix(inkc, (90, 140, 190), .5), covF) + e = Q[-1] + np.array([0, .025 * H]) + a = np.linspace(0, 2 * np.pi, 16) + drop = np.stack([e[0] + .016 * H * np.cos(a), e[1] + .02 * H * np.sin(a) - .012 * H * (np.sin(a) < 0)], 1) + cv.fill(drop, (196, 226, 246)) + cv.line(drop, W * .6, mix(inkc, (90, 140, 190), .5), closed=True) + elif cz["kind"] == "flush": + b = P[0] + for k in (-1, 0, 1): + x0 = b[0] + k * .022 * H + cv.line(np.array([(x0, b[1] + .012 * H), (x0 + .012 * H, b[1] - .012 * H)]), taper(2, W * .8), + mix((200, 90, 90), skin, .2), covF) + Y, X = np.mgrid[0:cv.img.shape[0], 0:cv.img.shape[1]].astype(np.float32) + .5 + g = np.exp(-(((X - b[0]) / (.075 * H)) ** 2 + ((Y - b[1]) / (.03 * H)) ** 2) * 1.6) + cv.paint(g * covF, (240, 140, 140), .3 * cz["s"]) + else: + if cz["s"] < 0.4: + continue + Q = crv(P, False, 4) + cv.line(Q, taper(len(Q), W * (.5 + .3 * cz["s"]), ends=.35), mix(inkc, skin_sh, .35), covF) + + +# ----------------------------------------------------------------------------------------------------------- paint +def paint_features(cv, Lo, p, C, s, sc, m_face, rng, orig): + """style_paint hook: the style's own _features paints nose, sockets and neutral masses first (orig), then the + eyes and mouth are repainted as value masses from the kit geometry the expression moved (face_apply), and the + folds go in as soft value strokes (human-061: delicate shadow lines, <= 15 L* below the skin, never black).""" + from .style_paint import put, ell_mask, poly_mask, stroke, lch, mixc, shift + KL = Lo.get("kit") + sp = getattr(KL, "fx", None) + orig(cv, Lo, p, C, s, sc, m_face, rng) + if sp is None: + return + expr = F.active("fx_expr") and not sp.neutral + ew = float(KL.fx_ew) + xv, yv = KL.fx_frame + skin_mid = C.get("skin_half", C["skin_sh"]) + if expr: + for sname in ("L", "R"): + e = KL.eyes[sname] + if float(e.get("fs", 1)) < .12: + continue + U, D = np.asarray(e["upper"], float), np.asarray(e["lower"], float) + c = np.asarray(e["c"], float) + lid = e.get("lid", {}) + # paint the neutral eye back to skin-in-shadow (the socket tone), then the new opening on top + box = np.vstack([U, D]) + put(cv, ell_mask(cv, c[0], c[1], ew * .62, ew * .42, 2 * sc) * m_face, mixc(C["socket"], skin_mid, .5), .9) + if lid.get("closure", 0) > .4: + Q = U if lid.get("kind") == "smile" else (U + D) / 2 + stroke(cv, Q, C["eye"], 2.6 * sc, .9, soft=.6 * sc, taper=(.15, .8)) + if lid.get("kind") == "smile": + stroke(cv, D + yv * ew * .18, C["skin_sh"], 2.2 * sc, .45, soft=1.2 * sc) + continue + m_eye = poly_mask(cv, np.vstack([U, D[::-1][1:-1]]), .7 * sc) + put(cv, m_eye, C["sclera"], .9) + hh = float(e["h"]) / 2 + shrink = 0.75 if lid.get("up", 0) < -0.1 else 1.0 + ir = min(float(e["w"]) * .24, hh * 1.25) * shrink + g = np.asarray(sp.gaze) * ir * .8 + put(cv, ell_mask(cv, c[0] + g[0], c[1] + hh * .05 + g[1], ir, ir, .8 * sc) * m_eye, C["eye"]) + stroke(cv, U, C["eye"], 2.4 * sc, .9, soft=.6 * sc, taper=(.15, .85)) + stroke(cv, D[len(D) // 2:], C["socket"], 1.4 * sc, .4, soft=.9 * sc) + put(cv, ell_mask(cv, c[0] + g[0] + s * ir * .35, c[1] - hh * .2, max(1., ir * .2), max(1., ir * .2), .4 * sc), + lch(.86, .01, 90), .8) + g = KL.mouth.get("fx") + if g is not None: + c = np.asarray(KL.pt["mouth_c"], float) + put(cv, ell_mask(cv, c[0], c[1], ew * .95 * g["hw"] / .75, ew * .32, 3 * sc) * m_face, skin_mid, .85) + mf = np.clip(m_face, 0, 1) # the far mouth corner tucks behind the far cheek (human-335) + put(cv, poly_mask(cv, g["lip_up"], 1.0 * sc) * mf, C["lip_up"], .9) + put(cv, poly_mask(cv, g["lip_lo"], 1.6 * sc) * mf, C["lip_lo"], .7) + if g["kind"] == "open": + m_o = poly_mask(cv, g["open_poly"], .8 * sc) * mf + put(cv, m_o, mixc(C["eye"], lch(.22, .08, 25), .5), .95) + if g.get("tongue") is not None: + put(cv, poly_mask(cv, g["tongue"], 1.2 * sc) * m_o, mixc(C["lip_lo"], C["skin_warm"], .4), .8) + for key in ("teeth_up", "teeth_lo"): + if g.get(key) is not None: + put(cv, poly_mask(cv, g[key], .7 * sc) * m_o, mixc(C["sclera"], lch(.84, .015, 85), .5), .95) + stroke(cv, g["top"], C["eye"], 1.8 * sc, .6, soft=.6 * sc, taper=(.2, .8)) + else: + stroke(cv, g["slit"], mixc(C["skin_deep"], C["eye"], .5), 2.6 * sc, .9, soft=.7 * sc, taper=(.2, .8)) + for cz in getattr(KL, "creases", []): + P = np.asarray(cz["pts"], float) + if cz["kind"] == "flush": + put(cv, ell_mask(cv, P[0][0], P[0][1], ew * .7, ew * .4, 6 * sc) * m_face, C["skin_warm"], .35 * cz["s"]) + elif cz["kind"] == "tear": + stroke(cv, P, C["skin_hi"], 2.4 * sc, .55, soft=.8 * sc) + stroke(cv, P + np.array([1.2 * sc, 0]), C["skin_sh"], 1.2 * sc, .35, soft=.8 * sc) + else: + stroke(cv, P, C["skin_sh"], (1.6 + 1.4 * cz["s"]) * sc, .25 + .35 * cz["s"], soft=1.1 * sc, taper=(.2, .8)) + if cz["kind"] in ("nasolabial", "lowerlid", "forehead", "cheek"): # the lit lip of a fold + stroke(cv, P - yv * 1.6 * sc, C["skin_hi"], 1.4 * sc, .18 * cz["s"], soft=1.2 * sc, taper=(.2, .8)) + + +def anime_beard(cv, lay, p, c, H, W, Wi, hair, hair_sh, inkc, lightdir, covF, mc, mw, sgn): + """the beard over the JAW, never across the mouth (WAVE20 faces): the top edge runs from the sideburn down the + cheek line to beside the mouth corners, a moustache rides above the upper lip, and the lips stay open as a + hole (Loomis beard mass; research20 'beard over mouth' bug). Stubble = the same shape as a light tone.""" + from .style_anime import crv, taper, mix + kind = p["beard"] + ny, my = c["nose_y"], c["mouth_y"] + mc = np.asarray(mc, float) + if kind == "mustache": + top = np.array([lay.P(-.13, my - .006), lay.P(-.07, ny + .045), lay.P(0, ny + .038), lay.P(.07, ny + .045), + lay.P(.13, my - .006)]) + bot = np.array([lay.P(.10, my - .004), lay.P(0, my - .016), lay.P(-.10, my - .004)]) + P = crv(np.vstack([top, bot]), True, 5) + cov = cv.fill(P, hair, covF) + cv.paint(cov * (1 - cv.cover(P + np.array([lightdir * .02 * H, -.012 * H]))), hair_sh) + cv.line(P, Wi, inkc, closed=True) + return + drop = .06 if kind == "full" else .02 + vs = np.linspace(.56, 1.0, 12) + Lc = lay.px(lay.contour_x(vs, -1) - .012, vs) + Rc = lay.px(lay.contour_x(vs, 1) + .012, vs) + chin = lay.px(np.array([(lay.contour_x(np.array([1.0]), -1) + lay.contour_x(np.array([1.0]), 1))[0] / 2]), + np.array([1.0 + drop])) + sbL = lay.px(lay.contour_x(np.array([.58]), -1) + .05, np.array([.58]))[0] + sbR = lay.px(lay.contour_x(np.array([.58]), 1) - .05, np.array([.58]))[0] + ck = .035 * H + inner = np.array([sbR, lay.P(.24, ny + .06), mc + np.array([mw * .8 + ck * .3, -.025 * H]), + lay.P(.07, ny + .04), lay.P(0, ny + .034), lay.P(-.07, ny + .04), + mc + np.array([-mw * .8 - ck * .3, -.025 * H]), lay.P(-.24, ny + .06), sbL]) + P = crv(np.vstack([Rc, chin, Lc[::-1], inner[::-1]]), True, 4) + cov = cv.cover(P) + a = np.linspace(0, 2 * np.pi, 24, endpoint=False) + sp = p.get("fx") + op = float(sp.p["open"]) if (sp is not None and not sp.neutral) else 0.0 + hole = np.stack([mc[0] + mw * (.55 + .4 * op) * np.cos(a), mc[1] + (.012 + .03 * op) * H + (.024 + .05 * op) * H * np.sin(a)], 1) + hm = cv.cover(hole) + cov = cov * (1 - hm) + if kind == "short": + cv.paint(cov * covF, hair_sh, .4) + return + cv.paint(cov, hair) + sh = cv.cover(P + np.array([lightdir * .05 * H, -.02 * H])) + cv.paint(cov * (1 - sh), hair_sh) + cv.line(P, W, inkc, closed=True, clip=None) + cv.line(hole, Wi * .8, inkc, closed=True, clip=cv.cover(P)) + for t in np.linspace(.15, .45, 4): + i = int(t * (len(P) - 1)) + cv.line(np.array([P[i], P[i] + (np.mean(P, 0) - P[i]) * .1]), taper(2, Wi * .8), inkc, cov) diff --git a/pydraw/figure/ink2.py b/pydraw/figure/ink2.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2c3d92d3fa22feae4bc4d288d8c2beb75a73bb --- /dev/null +++ b/pydraw/figure/ink2.py @@ -0,0 +1,429 @@ +"""figure.ink2: pen and ink, pencil and charcoal portraits on the shared shape stage (wave 20, styles lane). + +knob st_ink (PYDRAW_EXP st_ink=1; default OFF): style_ink.render sends pen / pencil / charcoal portraits here instead +of the wave-18 ink drawer. Pure code, CPU only. + +The design (design.py) decides the value plan, the designed shadow shapes and the feature symbols first; the line media +translate that decision into marks: + darkness map = the design's values per material (skin normalised to its own light so ~60% of the face is paper, O2; + things keep their local value, human-078), the casts darkest (human-028) + HATCHING follows the form (H1, form-071, human-035): layer 1 = iso-lines of the distance to the region's own contour + (cheek lines parallel to the jaw, rings round the neck, arcs round the chest), layer 2 crosses it at 50-70 deg + only in the shadow family, layer 3 only in the darkest 5% (H2); never ruled (H3): every line wobbles, its spacing + jitters ~15%, its ends stagger, and it lifts off (thins) toward the light (I3). Analytic per-pixel lines, so the + marks stay anti-aliased at any size and more lines appear at 1024 (size-dependent detail). + LINE HIERARCHY (I1, I2, human-001): three weights only (accents and hair darks, form contours, hatching); the shadow + side contour firm, the lit side contour broken or omitted; the neck bottom fades (O1); features from the + design's lines: the upper lid heaviest (F1), the mouth slit darkest at the corners (F2), nostrils, no bridge (F3). + DESIGNED BLACKS (human-003, R2): the hair's dark masses solid with ragged edges from flow streamlines (R1), the lit + hair left as paper with sparse streamlines, the silhouette broken by tips (R3); no isolated accents (O3). + pencil: graphite grey, a smudged tone under the hatching in the shadow family, grain from the paper tooth, softer + contours. charcoal: toned paper, big smudged darks, broad strokes along the flow, white chalk on the lights + (human-078: four tones: paper, light chalk, mid smudge, dark). +""" +import math +import numpy as np +from scipy import ndimage as ndi + +from . import design as DS +from . import kit as K +from .paint2 import vnoise, fbm + +F32 = np.float32 +R = DS.REG + + +def knob(name, default="0"): + from . import knob as _k + return _k(name, default) + + +def active(): + return knob("st_ink", "0") not in ("0", "", "off") + + +# --------------------------------------------------------------------------------------------- darkness plan +def darkness(D): + """0 paper .. 1 solid black, from the design (values per family) and each material's local value""" + S, H = D.S, D.H + lab = DS.to_lab(D.base)[..., 0] + P = D.P + dk = np.zeros((S, S), F32) + reg = D.reg + # skin by FAMILY (O2: ~60% of the face is paper): light family .05 .. halftone ~.2, shadow family .5 .. core .8, + # casts darkest (human-028); dark skin keeps its local value as one light layer (human-078) + Ll = DS.Lof(P["skin_l"]) + local = np.clip((72 - Ll) / 110.0, 0, .3) + v = D.val + sk = np.where(D.fam > .5, .03 + (1 - v) * .45, .42 + np.clip(.35 - v, 0, .35) * .7) + sk = sk + local + .3 * D.cast + .22 * D.neck_cast + .3 * D.hair_cast + .12 * D.sockets * (D.fam > .5) + skin = np.isin(reg, [R["face"], R["neck"], R["chest"], R["ear"]]) + dk = np.where(skin, sk, dk) + # hair: its own value masses on top of its local value (dark hair holds the darkest darks, C1) + hl = DS.Lof(P["hair_m"]) + hv = D.hair_val + hair_dk = np.clip((1 - hl / 100) * .75 + (.55 - hv) * .6, 0, 1) + hair = np.isin(reg, [R["hair"], R["hair_back"]]) + dk = np.where(hair, hair_dk, dk) + bl = DS.Lof(P["beard_l"]) + dk = np.where(reg == R["beard"], np.clip((1 - bl / 100) * .6 + (.3 if True else 0) * (D.fam < .5), 0, 1), dk) + cl = DS.Lof(P["cloth_l"]) + cloth_dk = np.clip((1 - cl / 100) * .5 + (.8 - D.cloth_val) * .6, 0, 1) + dk = np.where(reg == R["torso"], cloth_dk, dk) + # the features' own tones (lips, iris, brows) where the design laid them, weighted down (the lines carry them) + fl = DS.to_lab(D.feat[..., :3])[..., 0] + fdk = np.clip((Ll - fl) / max(25.0, Ll - 12), 0, 1) * D.feat[..., 3] + dk = np.maximum(dk, fdk * .9) + return np.clip(dk, 0, 1).astype(F32) + + +# --------------------------------------------------------------------------------------------- analytic hatching +def hatch(coord, sp, w, dk, thr, rng, wob=.6, breaks=.3, lift=.18, S=None, along=None, seglen=None): + """parallel lines = iso-lines of `coord` (px), spacing sp (+-15% per line, H3), width w px; a line is inked where + the darkness dk > thr + a per-line offset (staggered ends), thinning toward the threshold (lifts off toward the + light, I3); wob = wobble amplitude px along the line (never ruled); breaks = chance of a gap per line segment""" + if along is None: + along = coord * 0 + n = np.floor(coord / sp) + nid = (n.astype(np.int64) % 997 + 997) % 997 + rnd = rng.random(1000).astype(F32) + rnd2 = rng.random(1000).astype(F32) + off = (rnd[nid] - .5) * .3 * sp + ph = rnd2[nid] * 40 + wobble = wob * (np.sin(along / (23.0 + 30 * rnd[nid]) + ph) * .7 + np.sin(along / (9.0 + 5 * rnd2[nid]) + ph * 1.7) * .3) + u = coord - n * sp - sp / 2 + off + wobble + d = np.abs(u) + t = thr + (rnd2[nid] - .5) * .12 + # segment breaks along each line (staggered ends, H3) + sl = seglen or (sp * 9 + 25) + pos = (along + ph * 7) / sl + seg = np.floor(pos) + if seglen: # short strokes: each tapers at both ends (I3) + fr = pos - seg + w = w * np.clip(np.sin(np.pi * fr) * 1.6, .15, 1) + sid = ((seg.astype(np.int64) * 131 + nid * 7) % 997 + 997) % 997 + gap = rnd[sid] < breaks * .3 + strength = np.clip((dk - t) / lift, 0, 1) + ww = w * (.35 + .65 * strength) + cov = np.clip(ww / 2 + .5 - d, 0, 1) * (strength > 0) * (~gap) + return cov.astype(F32) + + +def region_coords(D, sx): + """per-pixel iso-coordinates for form-following hatching (H1): the face shadow in lines parallel to the + terminator (the plane the shadow lies on), bowed round the cheek; rings that sag round the neck cylinder; arcs + round the chest barrel; 'along' runs along each line (for the wobble and the staggered breaks)""" + S, H = D.S, D.H + reg = D.reg + yy, xx = np.mgrid[0:S, 0:S].astype(F32) + tp = np.asarray(D.term, F32) + v = tp[-1] - tp[0] + a = math.atan2(float(v[1]), float(v[0])) # terminator direction (top -> chin) + c = np.asarray(D.L.pt["head_c"], F32) + nrm = np.array([-math.sin(a), math.cos(a)], F32) + dirv = np.array([math.cos(a), math.sin(a)], F32) + t = (xx - c[0]) * dirv[0] + (yy - c[1]) * dirv[1] + co_face = (xx - c[0]) * nrm[0] + (yy - c[1]) * nrm[1] + .35 * (t / H) ** 2 * H * D.sx + along_face = t + pit = np.asarray(D.L.pt["pit"], F32) + rn = np.hypot(xx - pit[0], yy - (pit[1] - 1.6 * H)) + rt = np.hypot(xx - pit[0], yy - (pit[1] - 1.2 * H)) + ang_n = np.arctan2(yy - (pit[1] - 1.6 * H), xx - pit[0]) * rn + ang_t = np.arctan2(yy - (pit[1] - 1.2 * H), xx - pit[0]) * rt + co = co_face.copy() + along = along_face.copy() + for r, cc, al in ((R["neck"], rn, ang_n), (R["torso"], rt, ang_t), (R["chest"], rt, ang_t)): + m = reg == r + co = np.where(m, cc, co) + along = np.where(m, al, along) + bgc = xx * .7 + yy * .7 + co = np.where(reg == R["bg"], bgc, co) + along = np.where(reg == R["bg"], xx * .7 - yy * .7, along) + return co.astype(F32), along.astype(F32) + + +# --------------------------------------------------------------------------------------------- lines +def contour_lines(D, sx, medium): + """the figure's contours with weight by light (I1): firm on the shadow side, thin / broken on the lit side; + the neck bottom fades (O1); the far-cheek and the jaw firm; seams between hair and face from the hair""" + S, H = D.S, D.H + reg = D.reg + yy, xx = np.mgrid[0:S, 0:S].astype(F32) + out = np.zeros((S, S), F32) + c = np.asarray(D.L.pt["head_c"], F32) + shadow_side = np.clip(.5 + (xx - c[0]) * sx / (.3 * H), 0, 1) + pit = np.asarray(D.L.pt["pit"], F32) + + def edge_of(a, b_any): + """pixels of region a bordering any region in b_any""" + ma = a + mb = ndi.binary_dilation(b_any, iterations=1) + return ma & mb + + def ink_edge(e, w, fade=None): + if not e.any(): + return + d = ndi.distance_transform_edt(~e).astype(F32) + cov = np.clip(w / 2 + .5 - d, 0, 1) + if fade is not None: + cov = cov * fade + np.maximum(out, cov, out=out) + + wbase = max(1.0, .0075 * H) + face = reg == R["face"] + other = ~face & (reg != R["beard"]) + e = edge_of(face, other & ~np.isin(reg, [R["hair"]])) + noise = vnoise(S, S, .06 * H, np.random.default_rng(5)) + lit_keep = (noise > .45).astype(F32) * .55 # the lit contour broken, half weight (I1) + ink_edge(e, wbase * 1.3, np.clip(shadow_side + (1 - shadow_side) * lit_keep, 0, 1)) + # ears, neck sides, chest, torso + for r, k in ((R["ear"], .9), (R["neck"], 1.0), (R["torso"], .9)): + m = reg == r + e = edge_of(m, reg < r) if r != R["torso"] else edge_of(m, reg == R["bg"]) + fade = np.clip(1 - (yy - pit[1]) / (.9 * H), .15, 1) if r in (R["neck"], R["torso"]) else 1.0 + ink_edge(e, wbase * k, np.clip(shadow_side + (1 - shadow_side) * lit_keep * 1.2, 0, 1) * fade) + # the neckline + e = edge_of(reg == R["chest"], reg == R["torso"]) + ink_edge(e, wbase * .8, .8) + return out + + +def feature_lines(D, medium, scale=1.0): + S, H = D.S, D.H + out = np.zeros((S, S), F32) + w0 = max(1.0, .0075 * H) * scale + for pts, wt, kind in D.lines: + w = {"lid": 2.2, "crease": .8, "lower": .7, "brow": 0, "nostril": 1.1, "wing": .8, "mouth": 1.6, "ear": 1.0, + "glasses": 1.2, "nose": .9}.get(kind, 1.0) * w0 + if w <= 0: + continue + prof = {"lid": "swell", "mouth": "ends", "crease": "swell", "lower": "swell", "wing": "swell", "ear": "swell", + "nose": "swell", "nostril": None, "glasses": None}.get(kind, "swell") + m = K.stroke_mask(np.asarray(pts, F32), w, S, S, kind=prof) + np.maximum(out, m * min(1.0, .45 + wt * .6), out=out) + return out + + +def brows(D, rng, scale=1.0): + """brows as short strokes in the hair direction, denser at the inner-middle, lighter at the tail""" + S, H = D.S, D.H + out = np.zeros((S, S), F32) + for s_, b in D.L.brows.items(): + c = K.resample(K.crv(np.asarray(b, F32), closed=False, n=8), max(1.0, .006 * H)) + if len(c) < 3: + continue + nose = np.asarray(D.L.pt["nose_root"], F32) + if np.linalg.norm(c[0] - nose) > np.linalg.norm(c[-1] - nose): + c = c[::-1] + tan = np.gradient(c, axis=0) + tan /= np.linalg.norm(tan, axis=1, keepdims=True) + 1e-6 + nrm = np.stack([-tan[:, 1], tan[:, 0]], 1) + if nrm[len(nrm) // 2, 1] > 0: + nrm = -nrm + for i in range(0, len(c), 1): + t = i / max(1, len(c) - 1) + hgt = .03 * H * (1.0 - .6 * t) + p0 = c[i] - nrm[i] * hgt * .45 + rng.normal(0, .002 * H, 2) + p1 = p0 + (tan[i] * (.9 + .5 * t) + nrm[i] * (.9 - .7 * t)) * hgt * .9 + m = K.stroke_mask(np.array([p0, (p0 + p1) / 2 + nrm[i] * .002 * H, p1]), max(.8, .004 * H) * scale, S, S, + kind="flick") + np.maximum(out, m * (.85 - .35 * t), out=out) + return out + + +def iris_marks(D): + """the iris a dark disc under the lid with a paper catchlight, the pupil solid (F1)""" + S = D.S + out = np.zeros((S, S), F32) + lab = DS.to_lab(D.feat[..., :3])[..., 0] + a = D.feat[..., 3] + eyes = np.zeros((S, S), F32) + for s_, e in D.L.eyes.items(): + eyes = np.maximum(eyes, K.shape_mask(K.crv(np.asarray(e["outline"], F32), n=6), S, S)) + dk = np.clip((70 - lab) / 60, 0, 1) * a * eyes + return np.clip(dk * 1.1, 0, 1) + + +# --------------------------------------------------------------------------------------------- hair streamlines +def hair_marks(D, dk, rng, medium, scale=1.0): + """designed blacks (R2): solid where the hair is darkest, ragged by streamlines; lit hair sparse streamlines; tips + break the silhouette (R3)""" + S, H = D.S, D.H + hair = np.isin(D.reg, [R["hair"], R["hair_back"]]) + out = np.zeros((S, S), F32) + if not hair.any(): + return out + hd = np.where(hair, dk, 0) + solid_thr = .86 if medium == "pen" else .88 + solid = DS.soft((hd > solid_thr).astype(F32), .01 * H) + out = np.maximum(out, np.clip((solid - .5) * 2.2 + .35, 0, 1) * hair * (hd > solid_thr - .1)) + step = 4 + th = D.flow[::step, ::step] + val = ndi.zoom(hd, 1 / step, order=1)[:th.shape[0], :th.shape[1]] + ins = ndi.binary_dilation(hair, iterations=int(.01 * H)) + lines = K.streamlines(th, val, ins.astype(F32), step, rng, min_space=max(2.2, .014 * H / scale), + length=(.15 * H, .5 * H), seed_step=max(3, int(.012 * H)), vmin=.08, h=max(1.5, .004 * H)) + for P, V in lines: + if len(P) < 4: + continue + w = (.35 + 3.6 * np.clip(V, 0, 1) ** 1.6) * max(.55, .003 * H) * scale + m = K.stroke_mask(P, w, S, S, kind="swell") + np.maximum(out, m * float(np.clip(.4 + V.mean(), 0, 1)), out=out) + return out + + +# --------------------------------------------------------------------------------------------- media +def pen(fig, seed=0, medium="pen"): + D = DS.design(fig, seed, medium) + S, H = D.S, D.H + rng = np.random.default_rng(seed * 53 + 3) + sx = D.sx + dk = darkness(D) + co, along = region_coords(D, sx) + # size-dependent detail: spacing in px grows slower than the head (more lines at 1024) + sp = max(3.0, .025 * H) * (1.0 if medium == "pen" else .85) + w = max(.6, .0028 * H) if medium == "pen" else max(.8, .0045 * H) + ink = np.zeros((S, S), F32) + fig_m = D.m["figure"] > .5 + skin = np.isin(D.reg, [R["face"], R["neck"], R["chest"], R["ear"], R["torso"], R["beard"]]) + l1 = hatch(co, sp, w, dk, .3, rng, wob=.4 + .003 * H, lift=.2, along=along, seglen=.16 * H, breaks=.5) * skin + co2 = (np.mgrid[0:S, 0:S][1] * math.cos(1.1) + np.mgrid[0:S, 0:S][0] * math.sin(1.1) * sx).astype(F32) + l2 = hatch(co2, sp * 1.05, w * .9, dk, .62, rng, wob=.4, lift=.2, along=co, seglen=.12 * H, breaks=.5) * skin * (D.fam < .5) + co3 = (np.mgrid[0:S, 0:S][1] * math.cos(2.3) + np.mgrid[0:S, 0:S][0] * math.sin(2.3) * sx).astype(F32) + l3 = hatch(co3, sp * 1.1, w * .85, dk, .82, rng, wob=.4, lift=.15, along=co) * skin + for l in (l1, l2, l3): + np.maximum(ink, l, out=ink) + # the background: a loose hatched patch behind the LIT side of the head (counterchange defines the lit contour + # we left out, I1 / human-043) + yy, xx = np.mgrid[0:S, 0:S].astype(F32) + c = np.asarray(D.L.pt["head_c"], F32) + blob = np.exp(-(((xx - c[0] + sx * .62 * H) / (.32 * H)) ** 2 + ((yy - c[1] + .05 * H) / (.55 * H)) ** 2)) + blob = blob * (1 - DS.soft(D.m["figure"], .01 * H)) + (fbm(S, S, .15 * H, rng, 3) - .5) * .5 + bgd = np.clip(blob * .75, 0, 1) * (D.reg == R["bg"]) + co_bg = (xx * math.cos(.9) + yy * math.sin(.9)).astype(F32) + np.maximum(ink, hatch(co_bg, sp * 1.15, w, bgd, .3, rng, wob=.5, lift=.3, breaks=.5) * (D.reg == R["bg"]), out=ink) + # hair: designed blacks + streamlines + np.maximum(ink, hair_marks(D, dk, rng, medium), out=ink) + # contours and features last (in z order the features sit on top) + np.maximum(ink, contour_lines(D, sx, medium) * .95, out=ink) + np.maximum(ink, feature_lines(D, medium), out=ink) + np.maximum(ink, brows(D, rng), out=ink) + np.maximum(ink, iris_marks(D), out=ink) + # catchlights stay paper + cl = (D.feat[..., 3] > .5) & (DS.to_lab(D.feat[..., :3])[..., 0] > 90) + ink = np.where(cl, 0, ink) + paper = np.array([.97, .955, .925], F32) + inkc = np.array([.08, .07, .07], F32) + img = paper * (1 - ink[..., None]) + inkc * ink[..., None] + img = img * (1 + (vnoise(S, S, 1.6, rng)[..., None] - .5) * .03) + return (np.clip(img, 0, 1) * 255 + .5).astype(np.uint8), D + + +def pencil(fig, seed=0): + D = DS.design(fig, seed, "pencil") + S, H = D.S, D.H + rng = np.random.default_rng(seed * 59 + 5) + sx = D.sx + dk = darkness(D) + co, along = region_coords(D, sx) + tooth = np.clip(.55 + (fbm(S, S, 1.3, rng, 2) - .5) * 1.4, 0, 1) # paper tooth: graphite catches the peaks + sp = max(2.2, .012 * H) + w = max(.8, .0045 * H) + g = np.zeros((S, S), F32) + skin = np.isin(D.reg, [R["face"], R["neck"], R["chest"], R["ear"], R["torso"], R["beard"]]) + # a smudged tone under the hatching in the shadow family (graphite rubbed with a stump) + tonev = DS.soft(np.clip(dk - .15, 0, 1), .02 * H) * D.m["figure"] * .55 + g = g + tonev * (.6 + .4 * tooth) + co2 = (np.mgrid[0:S, 0:S][1] * math.cos(1.05) + np.mgrid[0:S, 0:S][0] * math.sin(1.05) * sx).astype(F32) + for cc, thr, a in ((co, .2, .45), (co2, .45, .45), (co, .7, .4)): + l = hatch(cc + (thr * 37 % sp), sp, w, dk, thr, rng, wob=.6 + .002 * H, lift=.25, breaks=.9, along=along, seglen=.09 * H) * skin + g = g + l * a * (.55 + .45 * tooth) + # hair strokes (graphite, not solid black) + hm = hair_marks(D, dk, rng, "pencil", scale=.9) + g = g + hm * .55 * (.6 + .4 * tooth) + lines = np.maximum(contour_lines(D, sx, "pencil") * .55, feature_lines(D, "pencil", .9) * .8) + lines = np.maximum(lines, brows(D, rng, .9) * .7) + lines = np.maximum(lines, iris_marks(D) * .9) + g = g + lines * (.75 + .25 * tooth) + cl = (D.feat[..., 3] > .5) & (DS.to_lab(D.feat[..., :3])[..., 0] > 90) + g = np.where(cl, 0, g) + dens = 1 - np.exp(-g * 1.6) + paper = np.array([.96, .955, .94], F32) + lead = np.array([.20, .20, .22], F32) + img = paper * (1 - dens[..., None]) + lead * dens[..., None] + # graphite sheen: the darkest areas a touch lighter and cooler than ink + img = img * (1 + (vnoise(S, S, 1.4, rng)[..., None] - .5) * .03) + return (np.clip(img, 0, 1) * 255 + .5).astype(np.uint8), D + + +def charcoal(fig, seed=0): + D = DS.design(fig, seed, "charcoal") + S, H = D.S, D.H + rng = np.random.default_rng(seed * 61 + 9) + sx = D.sx + dk = darkness(D) + tooth = np.clip(.5 + (fbm(S, S, 1.5, rng, 2) - .5) * 1.8, 0, 1) + streak = np.clip(.5 + (vnoise(S, S, 1.0, rng) - .5) * 1.5, 0, 1) + yy, xx = np.mgrid[0:S, 0:S].astype(F32) + c = np.asarray(D.L.pt["head_c"], F32) + # human-078 four tones: paper, chalk light, a mid smudge, the dark. The darks are DESIGNED masses (quantised), + # then smudged a little: big shapes, not a rendered gradient + q = np.where(dk < .28, dk * .4, np.where(dk < .55, .3, np.where(dk < .78, .58, .88))).astype(F32) + q = DS.soft((q * .55 + dk * .45) * D.m["figure"], .02 * H) + # the ground: a smudged dark behind the lit side (counterchange), rubbed out toward the edges + blob = np.exp(-(((xx - c[0] + sx * .55 * H) / (.5 * H)) ** 2 + ((yy - c[1] + .05 * H) / (.85 * H)) ** 2)) + bgd = np.clip(blob * .7 + (fbm(S, S, .18 * H, rng, 3) - .5) * .4, 0, 1) * (1 - DS.soft(D.m["figure"], .02 * H)) + bgd = DS.soft(bgd, .04 * H) * .55 + g = np.maximum(q, bgd) + # broad strokes of the stick on its side along the flow, in the mid and dark masses (the marks, last) + from .paint2 import Brush + cv = np.zeros((S, S, 3), F32) + ref = np.repeat(np.clip(q + .1, 0, 1)[..., None], 3, -1) + B = Brush(cv, ref, D, rng) + B.layer((q > .3) & (D.m["figure"] > .5), .014 * H, .16 * H, .7, jit=0, density=.55, lost=.5, bristle=.8, + dark_quiet=False, keep_fam=False) + st = B.cv[..., 0] + g = g * .55 + np.maximum(g, st) * .45 + # tooth: charcoal sits on the paper's peaks; dense darks fill the valleys too + g = g * (.5 + .5 * tooth) + (g ** 2.2) * .5 * (1 - tooth) + g = g * (.85 + .15 * streak) + # lines: soft, a little broad, grainy (the stick's edge) + ln = np.maximum(contour_lines(D, sx, "charcoal") * .5, feature_lines(D, "charcoal", 1.2)) + ln = np.maximum(ln, brows(D, rng, 1.3)) + ln = np.maximum(ln, iris_marks(D)) + ln = DS.soft(ln, 2.0) * 1.1 + g = np.maximum(g, np.clip(ln, 0, 1) * (.6 + .4 * tooth)) + g = np.clip(g, 0, 1) + paper = np.array([.83, .80, .74], F32) + char = np.array([.08, .075, .07], F32) + img = paper * (1 - g[..., None]) + char * g[..., None] + # white chalk lifts the lights: the centre light of the skin, the hair highlight, catchlights + skin = np.isin(D.reg, [R["face"], R["neck"], R["chest"], R["ear"]]) + chalk = ((D.fam > .5) & skin).astype(F32) * np.clip((D.val - .78) / .2, 0, 1) + chalk = DS.soft(chalk, .015 * H) + chalk = np.maximum(chalk, np.clip((D.hair_val - .85) * 3, 0, 1) * np.isin(D.reg, [R["hair"]]) * .8) + cl = (D.feat[..., 3] > .5) & (DS.to_lab(D.feat[..., :3])[..., 0] > 90) + chalk = np.maximum(chalk, cl.astype(F32)) + chalk = chalk * (.35 + .65 * tooth) * .9 + img = img * (1 - chalk[..., None]) + np.array([.97, .96, .93], F32) * chalk[..., None] + return (np.clip(img, 0, 1) * 255 + .5).astype(np.uint8), D + + +MEDIA = {"pen": pen, "pencil": pencil, "charcoal": charcoal} + + +def medium_for(fig): + t = ((getattr(fig, "variant", "") or "") + " " + (getattr(fig, "text", "") or "")).lower() + if "charcoal" in t: + return "charcoal" + if "pencil" in t or "graphite" in t: + return "pencil" + return "pen" + + +def render(fig, size, seed, trace=None): + m = medium_for(fig) + img, D = MEDIA[m](fig, seed) + if trace is not None: + trace.append("ink2: %s on the design stage (designed blacks, form hatching, line hierarchy)" % m) + return img diff --git a/pydraw/figure/layout.py b/pydraw/figure/layout.py index e25b2243edbb8293f445e4022eb3472874b67eae..8c9e0b39690f410fb464958f5cc5b8eb5c78a9fe 100644 --- a/pydraw/figure/layout.py +++ b/pydraw/figure/layout.py @@ -206,9 +206,31 @@ class Person: fringe = "full" glasses = has("glasses", "spectacles", "eyeglasses", "bespectacled") expr = "smile" if has("smile", "smiling", "happy", "cheerful", "grin", "grinning") else "neutral" - return cls(age=age, sex=sex, build=build, skin=skin, hair_style=hs, hair_color=hc, eye_color=ec, - cloth_color=cc, beard=beard, glasses=glasses, seed=seed, expression=expr, wavy=wavy, - beard_color=beard_color, fringe=fringe) + fxs = None + from . import face as _face + if _face.active("fx_face"): + # wave 20 faces lane (knob fx_face, default OFF): an explicit age ("80 year old", "in her 70s") beats the + # age word (fx_age); the expression spec (emotion x intensity, human-305..325) rides on the person + if _face.active("fx_age"): + ea = _face.parse_age(text) + if ea is not None: + age = ea + if age < 2.5 and hs not in ("bald",): + hs = "short" + if age >= 60 and hc is None and r.random() < .85: + # human-329: grey fraction ~ clamp((age-35)/45): unnamed hair goes grey / white with age + hc = "white" if age >= 78 or r.random() < .35 else "grey" + if _face.active("fx_expr"): + fxs = _face.spec_from_text(text, age, sex, seed) + expr = "smile" if fxs.emotion == "joy" else ("neutral" if fxs.neutral else fxs.emotion) + else: + fxs = _face.Spec(age=age, sex=sex) + P = cls(age=age, sex=sex, build=build, skin=skin, hair_style=hs, hair_color=hc, eye_color=ec, + cloth_color=cc, beard=beard, glasses=glasses, seed=seed, expression=expr, wavy=wavy, + beard_color=beard_color, fringe=fringe) + P.face_spec = fxs + P.freckles = has("freckles", "freckled", "freckle") + return P _SKIN_PHRASE = {"very dark": 0.95, "very light": 0.04, "very pale": 0.0, "dark brown": 0.8, "deep brown": 0.85, @@ -413,16 +435,30 @@ def build(person, pose=None, style="real", size=512, framing="portrait", seed=No back = np.cos(TH.reshape(-1)) < 0.35 cap = cap[(cap[:, 1] > yf(min(0.98, 0.52)) - 0.0) | (back & (cap[:, 1] > -0.22))] jaw = [] + _fxs = getattr(person, "face_spec", None) + from . import face as _face + _jowl = float(_fxs.age_p["jowl"]) if (_fxs is not None and _face.active("fx_age")) else 0.0 + _far = ("L" if pose.yaw > 0 else "R") if abs(pose.yaw) > 8 else None + _tq = math.sin(math.radians(min(60.0, abs(pose.yaw)))) if (_far and _fxs is not None and _face.active("fx_jaw")) else 0.0 for s in ("L", "R"): z0, za, zc = P3["zygion_" + s], P3["jaw_angle_" + s], P3["chin_" + s] + if s == _far and _tq > 0: + # fx_jaw (wave 20): in a turned head the far jaw angle hides behind the cheek-to-chin line (X9: far + # contour straight, chin pointed; human-335); left where it is it pokes out as a bulge under the cheek + za = (za[0] * (1 - 0.45 * _tq), za[1] + 0.03 * _tq, za[2] - 0.05 * _tq) + _bk = (1 - 0.8 * _tq) if s == _far else 1.0 for t in np.linspace(0, 1, 7): # cheek: zygion -> jaw angle, a slight outward bulge (young / fat) p = (1 - t) * np.array(z0) + t * np.array(za) - p[0] *= 1.0 + (0.05 + 0.08 * fat) * math.sin(math.pi * t) + p[0] *= 1.0 + (0.05 + 0.08 * fat) * math.sin(math.pi * t) * _bk jaw.append(p) for t in np.linspace(0, 1, 9): # jaw line: angle -> chin corner, convex p = (1 - t) * np.array(za) + t * np.array(zc) - p[0] *= 1.0 + (0.06 + 0.10 * fat) * math.sin(math.pi * t) + p[0] *= 1.0 + (0.06 + 0.10 * fat) * math.sin(math.pi * t) * _bk p[1] -= (0.02 + 0.02 * fat) * math.sin(math.pi * t) + if _jowl > 0: # fx_age (human-330/289): the jowl sags below the jaw line mid-way + k = math.sin(math.pi * min(1.0, t * 1.6)) ** 2 + p[0] *= 1.0 + _jowl * 0.6 * k + p[1] -= _jowl * 0.35 * k jaw.append(p) jaw += [np.array(P3["chin"]), np.array(P3["chin_front"])] jaw = np.array(jaw, F32) @@ -431,7 +467,9 @@ def build(person, pose=None, style="real", size=512, framing="portrait", seed=No cap[:, 1] = np.clip(cap[:, 1], -0.5, 0.5) # ---- rotation + projection ------------------------------------------------------------------------------- - R = _rot(pose.yaw, pose.pitch, pose.roll) + fxs = getattr(person, "face_spec", None) + hp = float(fxs.p.get("head_pitch", 0.0)) if fxs is not None else 0.0 + R = _rot(pose.yaw, pose.pitch + hp, pose.roll) Rt = _rot(pose.torso_yaw, 0.0, pose.roll * 0.3) piv = np.array([0.0, -0.30, -0.05], F32) @@ -570,6 +608,9 @@ def build(person, pose=None, style="real", size=512, framing="portrait", seed=No top, bot = np.array(P3["ear_top_" + s]), np.array(P3["ear_bot_" + s]) c3 = (top + bot) / 2 + np.array([sx * 0.02, 0, -0.01]) ry = (top[1] - bot[1]) / 2 * 1.05 + if _jowl > 0 or (_fxs is not None and _face.active("fx_age")): + ry *= float(_fxs.age_p["ear_scale"]) # human-330: ears x1.10 at 60, x1.18 at 80 (pendant lobe) + c3 = c3 - np.array([0, ry * (float(_fxs.age_p["ear_scale"]) - 1.0) * 0.8, 0]) rz = ry * 0.52 t = np.linspace(0, 2 * np.pi, 20, endpoint=False) o3 = np.stack([np.full_like(t, c3[0]) + sx * 0.012 * (1 - np.cos(t)) * 0.5, @@ -715,6 +756,10 @@ def build(person, pose=None, style="real", size=512, framing="portrait", seed=No np.array(P3["ear_top_" + s]) + np.array([0, -0.03, 0.02])])) for s, sx in (("L", 1.0), ("R", -1.0))} Lo.glasses = dict(lens=lens, bridge=br, arms=arms, round=bool(rnd)) + Lo.fx = None + if fxs is not None: + from .face_apply import apply as _fx_apply + _fx_apply(Lo, person, fxs, cn, Hpx) return Lo diff --git a/pydraw/figure/paint2.py b/pydraw/figure/paint2.py new file mode 100644 index 0000000000000000000000000000000000000000..7dfaaac81f0360c72fe18232f8d7d8a5ecbe41d2 --- /dev/null +++ b/pydraw/figure/paint2.py @@ -0,0 +1,414 @@ +"""figure.paint2: painted portraits on the shared shape stage (wave 20, styles lane). Pure code, CPU only. + +knob st_paint (PYDRAW_EXP st_paint=1 turns it on; default OFF): style_paint.render sends oil / watercolor / gouache / +painted / acrylic / pastel portraits here instead of the wave-18 painter. + +Order (WAVE20 method): design.design(fig) decides masses, designed shadow shapes and feature symbols FIRST; each +medium below only adds marks to that decision, never invents new values (marks last). + oil underpainting = the design with lost shadow-side edges (P-R5), then three brush passes coarse -> fine that + sample the design and follow the form (P-R10, human-035): the shadow family thin, quiet, few large strokes + with little colour change; the lights get the visible broken colour and the impasto (form-070); features + restated crisp on top (the eyes and mouth keep their found edges, C6), canvas grain last. + watercolor white paper; wash 1 = local colour in the light family over the whole figure (paper reserved for the + lightest lights, the highlight is the paper), wash 2 = ONE shadow glaze per material, hard-edged on angular + planes and bled wet-in-wet on round ones, pooled (darker) at its edge; wash 3 = darks (hair pocket, eyes, + nostrils, mouth); granulation in the shadows; a loose background wash around the head; the torso fades to + paper at the bottom (an unfinished vignette, the watercolour convention). + gouache the design as flat opaque shapes (4-5 values per material, human-104), matte and a little chalky, the + edges dry-brushed (broken, not blurred), broad flat brush marks in the ground and the clothes. +Shared rules: human-003 lint list (state the blacks, no pecky marks, no consistent grey), P-R1 (face < 5% of the +picture's top-3% values: the lightest light is reserved, here the highlight dots and the paper), P-R9 (skin shadows +olive / brown), form-070. +""" +import math +import numpy as np +from scipy import ndimage as ndi + +from . import design as DS +from . import kit as K + +F32 = np.float32 + + +def knob(name, default="0"): + from . import knob as _k + return _k(name, default) + + +def active(): + return knob("st_paint", "0") not in ("0", "", "off") + + +# --------------------------------------------------------------------------------------------- noise +def vnoise(H, W, cell, rng): + gh, gw = int(H / cell) + 3, int(W / cell) + 3 + g = rng.random((gh, gw)).astype(F32) + return ndi.map_coordinates(g, np.mgrid[0:H, 0:W].astype(F32) / cell, order=3, mode="nearest").astype(F32) + + +def fbm(H, W, cell, rng, oct=4): + out = np.zeros((H, W), F32) + a, tot = 1.0, 0.0 + for o in range(oct): + out += a * vnoise(H, W, max(1.0, cell / 2 ** o), rng) + tot += a + a *= .5 + return out / tot + + +# --------------------------------------------------------------------------------------------- brush strokes +class Brush: + """a stroke painter: each stroke follows the flow field from its centre (a short curve), its colour is sampled + from the reference at the centre (+ jitter in Lab), bristle streaks across its width, tapered ends, clipped to the + region it starts in unless the edge there is designed lost (D.soft).""" + + def __init__(self, cv, ref, D, rng): + self.cv, self.ref, self.D, self.rng = cv, ref, D, rng + self.S = cv.shape[0] + self.height = np.zeros(cv.shape[:2], F32) + self.bristle = rng.random(256).astype(F32) + + def path(self, x, y, length, step): + fl = self.D.flow + S = self.S + pts = [(x, y)] + for sgn in (1, -1): + px, py = x, y + prev = None + seq = [] + for _ in range(max(1, int(length / 2 / step))): + a = fl[int(np.clip(py, 0, S - 1)), int(np.clip(px, 0, S - 1))] + d = np.array([math.cos(a), math.sin(a)]) * sgn + if prev is not None and d @ prev < 0: + d = -d + px, py = px + d[0] * step, py + d[1] * step + prev = d + seq.append((px, py)) + pts = (seq[::-1] + pts) if sgn < 0 else (pts + seq) + return np.asarray(pts, F32) + + def stroke(self, P, w, col, alpha, clip_reg=None, lost=0.0, impasto=0.0, bristle=.35, fam0=None): + S = self.S + r = w / 2 + x0, y0 = int(max(0, P[:, 0].min() - r - 2)), int(max(0, P[:, 1].min() - r - 2)) + x1, y1 = int(min(S, P[:, 0].max() + r + 3)), int(min(S, P[:, 1].max() + r + 3)) + if x1 <= x0 or y1 <= y0: + return + yy, xx = np.mgrid[y0:y1, x0:x1].astype(F32) + .5 + if len(P) > 13: # at most 12 segments for the distance (vectorised over segments) + P = P[np.unique(np.linspace(0, len(P) - 1, 13).round().astype(int))] + A, Bp = P[:-1], P[1:] + ba = Bp - A + L2 = (ba ** 2).sum(1) + 1e-9 + seg = np.sqrt(L2) + cum0 = np.concatenate([[0.0], np.cumsum(seg)[:-1]]) + tot = float(seg.sum()) + 1e-6 + px = xx[None] - A[:, 0, None, None] + py = yy[None] - A[:, 1, None, None] + h = np.clip((px * ba[:, 0, None, None] + py * ba[:, 1, None, None]) / L2[:, None, None], 0, 1) + dx = px - h * ba[:, 0, None, None] + dy = py - h * ba[:, 1, None, None] + d = np.hypot(dx, dy) + k = np.argmin(d, 0) + ii = np.arange(d.shape[1])[:, None], np.arange(d.shape[2])[None, :] + best = d[k, ii[0], ii[1]] + tpar = (cum0[k] + h[k, ii[0], ii[1]] * seg[k]) / tot + cross = (dx[k, ii[0], ii[1]] * -ba[k, 1] + dy[k, ii[0], ii[1]] * ba[k, 0]) / seg[k] + taper = np.clip(np.minimum(tpar, 1 - tpar) / .18, 0, 1) ** .7 + rr = r * (.55 + .45 * taper) + cov = np.clip(rr + .5 - best, 0, 1) + if bristle: + idx = ((cross / max(r, 1) * 22 + self.rng.integers(0, 200)) % 255).astype(int) + br = self.bristle[idx] + cov = cov * (1 - bristle + bristle * (.4 + .6 * br) * (.6 + .4 * (1 - tpar))) + if clip_reg is not None: + reg = self.D.reg[y0:y1, x0:x1] + ok = (reg == clip_reg).astype(F32) + if fam0 is not None: # stay inside the designed family (shapes first, marks last) + ok = ok * (np.abs(self.D.fam[y0:y1, x0:x1] - fam0) < .5) + if lost > 0: + ok = np.maximum(ok, np.clip(self.D.soft[y0:y1, x0:x1] * 2 * lost, 0, 1)) + cov = cov * ok + a = (cov * alpha)[..., None] + self.cv[y0:y1, x0:x1] = self.cv[y0:y1, x0:x1] * (1 - a) + np.asarray(col, F32) * a + if impasto: + self.height[y0:y1, x0:x1] = np.maximum(self.height[y0:y1, x0:x1] * (1 - cov * .5), cov * impasto) + + def layer(self, where, radius, length, alpha, jit, density=1.0, err=None, lost=.5, impasto=0.0, bristle=.35, + dark_quiet=True, regs=None, keep_fam=True): + """one pass: centres on a jittered grid of ~radius spacing inside `where`, shuffled (painters do not paint in + raster order); optional error gate (Hertzmann): only where the canvas still differs from the reference""" + S = self.S + sp = max(1.5, radius * 1.1 / max(.3, density)) + ys, xs = np.mgrid[0:S:sp, 0:S:sp] + xs = (xs + self.rng.uniform(0, sp, xs.shape)).ravel() + ys = (ys + self.rng.uniform(0, sp, ys.shape)).ravel() + keep = where[np.clip(ys.astype(int), 0, S - 1), np.clip(xs.astype(int), 0, S - 1)] > .5 + if regs is not None: + keep &= np.isin(self.D.reg[np.clip(ys.astype(int), 0, S - 1), np.clip(xs.astype(int), 0, S - 1)], regs) + xs, ys = xs[keep], ys[keep] + if err is not None: + e = np.abs(self.cv - self.ref).sum(-1) + e = ndi.uniform_filter(e, max(1, int(radius))) + ok = e[np.clip(ys.astype(int), 0, S - 1), np.clip(xs.astype(int), 0, S - 1)] > err + xs, ys = xs[ok], ys[ok] + o = self.rng.permutation(len(xs)) + fam = self.D.fam + for i in o: + x, y = float(xs[i]), float(ys[i]) + iy, ix = int(min(S - 1, y)), int(min(S - 1, x)) + f = fam[iy, ix] + Ls = length * self.rng.uniform(.6, 1.3) + wv = radius * 2 * self.rng.uniform(.75, 1.2) + if dark_quiet and f < .5: # form-070: shadows thin and quiet: bigger, smoother, less broken + wv *= 1.25 + Ls *= 1.2 + P = self.path(x, y, Ls, max(1.0, radius * .6)) + c = self.ref[iy, ix] + j = jit * (1.0 if f >= .5 or not dark_quiet else .35) + if j: + c = DS.tone(c, dL=self.rng.normal(0, 2.2 * j), kC=1 + self.rng.normal(0, .08 * j), + dh=self.rng.normal(0, 6 * j)) + al = alpha * (1.0 if f >= .5 else .8) + self.stroke(P, wv, c, al, clip_reg=int(self.D.reg[iy, ix]), lost=lost, + impasto=impasto * (f >= .5), bristle=bristle, fam0=(float(f) if keep_fam else None)) + + +def lost_edges(img, D, r): + """P-R5: blur where the design says the edge is lost (shadow side, hair into ground, the low torso)""" + b = np.stack([ndi.gaussian_filter(img[..., c], r / 2) for c in range(3)], -1) + s = D.soft[..., None] + return img * (1 - s) + b * s + + +def canvas_tex(S, rng, cell=3.0): + yy, xx = np.mgrid[0:S, 0:S].astype(F32) + weave = (np.sin(xx * math.pi / cell) * np.sin(yy * math.pi / cell)) * .5 + n = vnoise(S, S, 2.0, rng) - .5 + return (weave * .6 + n * .4).astype(F32) + + +def emboss(height, light=(-.6, -.8)): + gy, gx = np.gradient(ndi.gaussian_filter(height, .8)) + return (gx * light[0] + gy * light[1]).astype(F32) + + +# --------------------------------------------------------------------------------------------- oil +R = DS.REG +SKIN_REGS = [R["face"], R["neck"], R["chest"], R["ear"]] +HAIR_REGS = [R["hair"], R["hair_back"]] + + +def restate_features(cv, D, a=.9, blur=.6): + """the design's feature symbols on top of the marks (C6: the eyes and the mouth keep their found edges)""" + fa0 = ndi.gaussian_filter(D.feat[..., 3], blur) if blur else D.feat[..., 3] + fc = np.stack([(ndi.gaussian_filter(D.feat[..., c] * D.feat[..., 3], blur) if blur else D.feat[..., c] * D.feat[..., 3]) + for c in range(3)], -1) / np.maximum(fa0, 1e-3)[..., None] + fa = (fa0 * a)[..., None] + return cv * (1 - fa) + np.clip(fc, 0, 1) * fa + + +def _unify_shadows(ref, D, k=.18): + sh = ((1 - D.fam) * D.m["figure"])[..., None] + if (D.fam < .5).any(): + mean = np.mean(ref[(D.fam < .5) & (D.m["figure"] > .5)], 0) if ((D.fam < .5) & (D.m["figure"] > .5)).any() else ref.mean((0, 1)) + ref = ref * (1 - k * sh) + DS.tone(mean, dL=-2) * k * sh + return ref + + +def oil(fig, seed=0): + D = DS.design(fig, seed, "oil") + S, H = D.S, D.H + rng = np.random.default_rng(seed * 31 + 7) + # the reference the brush samples: the design WITHOUT the feature symbols (they are restated last), shadows + # unified into one thin warm family (form-070), shadow-side edges lost (P-R5) + ref = _unify_shadows(D.base.copy(), D, .15) + ref = lost_edges(ref, D, .025 * H) + # imprimatura: a warm toned ground showing through between the first strokes + ground = DS.tone(D.P["bg_b"], dL=-4, kC=1.2, dh=-10) + cv = np.ones((S, S, 3), F32) * ground * .2 + lost_edges(ref, D, .05 * H) * .8 + B = Brush(cv, ref, D, rng) + every = np.ones((S, S), F32) + # pass 1: the ground and the clothes in big strokes (coarse, quiet) + B.layer(every, .045 * H, .26 * H, .8, jit=.7, density=1.0, lost=.6, bristle=.45, + regs=[R["bg"], R["torso"]]) + # pass 2: hair masses and the skin planes in medium strokes following the form + B.layer(every, .02 * H, .15 * H, .8, jit=.6, density=1.0, lost=.35, impasto=.5, bristle=.45, regs=HAIR_REGS + [R["beard"]]) + B.layer(every, .016 * H, .08 * H, .75, jit=.55, density=1.0, lost=.25, impasto=.6, bristle=.35, regs=SKIN_REGS) + # pass 3: small strokes where the canvas still differs from the design, in the lights (broken colour, impasto) + B.layer(D.fam > .5, .009 * H, .05 * H, .6, jit=.45, density=1.0, err=.07, lost=.15, impasto=1.0, bristle=.3, + regs=SKIN_REGS) + B.layer(D.fam > .5, .007 * H, .12 * H, .65, jit=.9, density=.8, lost=.2, impasto=.8, bristle=.6, regs=HAIR_REGS) + cv = restate_features(B.cv, D, .9, .7) + rel = emboss(B.height) * .05 + tex = canvas_tex(S, rng, cell=max(1.5, S / 340)) * .03 + cv = cv + rel[..., None] + tex[..., None] + yy, xx = np.mgrid[0:S, 0:S].astype(F32) / S + c = np.asarray(fig.layout.pt["head_c"], F32) / S + vg = np.clip(((xx - c[0]) ** 2 + (yy - c[1]) ** 2) ** .5 / .75, 0, 1) ** 2 * .2 + cv = cv * (1 - vg[..., None]) + return (np.clip(cv, 0, 1) * 255 + .5).astype(np.uint8), D + + +# --------------------------------------------------------------------------------------------- watercolor +def _ragged(m, rng, S, H, amp=.25, cell=.05, r=.004): + """a wash edge: the softened mask thresholded with noise, then anti-aliased (paper takes paint unevenly)""" + n = fbm(S, S, cell * H, rng, 3) - .5 + sm = DS.soft(m, max(1.0, r * H)) + out = np.clip((sm + n * amp - .5) * 5 + .5, 0, 1) + return DS.soft(out, 1.0).astype(F32) + + +def _pool(w, r): + """the pigment ring at the drying edge: 0..1, highest just inside the boundary (used to darken, never > 1)""" + inner = ndi.gaussian_filter(w, r) + return np.clip((w - inner) * 3, 0, 1) * w + + +def watercolor(fig, seed=0): + D = DS.design(fig, seed, "watercolor") + S, H = D.S, D.H + rng = np.random.default_rng(seed * 37 + 11) + yy, xx = np.mgrid[0:S, 0:S].astype(F32) + paper = np.array([.985, .978, .955], F32) + gr = fbm(S, S, 2.2, rng, 2) - .5 # granulation: pigment settles in the paper's valleys + T = np.ones((S, S, 3), F32) + + def glaze(tcol, dens, gran=0.0, pool=None, pool_k=.3): + """a transparent wash (transmittance tcol) at density dens 0..1; the drying edge pools darker""" + nonlocal T + tc = np.clip(np.asarray(tcol, F32), .02, 1) + if tc.ndim == 1: + tc = tc[None, None] + d = np.clip(dens, 0, 1) + if gran: + d = np.clip(d * (1 + gran * gr * .7), 0, 1) + f = 1 - d[..., None] * (1 - tc) + if pool is not None: + f = f * (1 - pool_k * pool[..., None] * (1 - tc)) + T = T * np.clip(f, 0, 1) + + def lighten(rgb, k): + """watercolour lights are thin washes: lift the design toward the paper (lab L up, chroma kept)""" + return DS.tone(rgb, dL=k) + + base = D.base + fig_m = D.m["figure"] + hc = np.asarray(fig.layout.pt["head_c"], F32) + pit = np.asarray(fig.layout.pt["pit"], F32) + low = fbm(S, S, .35 * H, rng, 2) - .5 # low-frequency noise: wash boundaries wander, no holes + # the vignette: the painting stops down the chest with a ragged, pooled edge (unfinished, the convention) + fade = np.clip((pit[1] + .3 * H + low * .6 * H - yy) / (.05 * H), 0, 1) + fade = fade * np.clip((1.25 * H + low * .4 * H - np.abs(xx - hc[0])) / (.06 * H), 0, 1) + fade = DS.soft(fade, 1.5) + # background: one loose wash behind the head on the shadow side, gradated out to the paper + blob = np.exp(-(((xx - hc[0] - D.sx * .35 * H) / (.85 * H)) ** 2 + ((yy - hc[1] + .1 * H) / (1.0 * H)) ** 2)) + bgw = np.clip((blob + low * .45 - .32) * 3, 0, 1) * (1 - DS.soft(fig_m, .015 * H)) + bgw = DS.soft(bgw, .01 * H) + bgt = np.clip(DS.tone(D.P["bg_a"], dL=6, kC=1.6, dh=float(rng.uniform(-40, 40))) / paper, 0, 1) + glaze(bgt, bgw * (.35 + .25 * blob), gran=.6, pool=_pool(bgw, .01 * H), pool_k=.6) + # wash 1: the light-family local colour of each mass in ONE flat thin wash (the highlights stay paper) + light_col = base.copy() + for name in ("face", "neck", "chest", "ear"): + m = (D.reg == R[name]) & (D.fam < .5) + light_col[m] = D.P["skin_l"] + light_col[np.isin(D.reg, HAIR_REGS) & (D.fam < .5)] = D.P["hair_m"] + light_col[(D.reg == R["torso"]) & (D.fam < .5)] = D.P["cloth_l"] + light_col[D.reg == R["beard"]] = D.P["beard_l"] + light_col = lighten(light_col, 11) + w1 = DS.soft(fig_m, 1.0) * fade + # a thin white gap between neighbouring washes on the lit side (laid wet-beside-dry, the paper shows) + rb = D.reg.astype(F32) + edge = (np.abs(np.diff(rb, axis=1, append=rb[:, -1:])) + np.abs(np.diff(rb, axis=0, append=rb[-1:, :]))) > 0 + lit_gap = DS.soft(edge.astype(F32), .8) * D.fam * (rng.random() < 2) * .7 + hl = np.clip((D.val - .95) / .05, 0, 1) * (D.fam > .5) * np.isin(D.reg, SKIN_REGS) + hl = np.maximum(hl, np.clip((D.hair_val - 1.0) * 3, 0, 1) * np.isin(D.reg, HAIR_REGS)) + w1 = w1 * (1 - lit_gap) * (1 - .8 * DS.soft(hl, .006 * H)) + glaze(np.clip(light_col / paper, 0, 1), w1, gran=.15, pool=_pool(w1, .008 * H), pool_k=.35) + # wash 2: ONE shadow glaze over the shadow family: the ratio that turns wash 1 into the designed shadow, + # a hard pooled edge on angular planes, bled (wet-in-wet) where the design loses the edge (D.soft) + shadow = (1 - D.fam) * fig_m * fade + cur = T * paper + tgt = lighten(base, 6) + ts = np.clip(tgt / np.maximum(cur, .04), 0, 1) + sh = DS.soft(shadow, 1.0) + bled = DS.soft(shadow, .03 * H) + sh = sh * (1 - D.soft) + np.maximum(sh * .7, bled) * D.soft + glaze(ts, sh, gran=.5, pool=_pool(sh, .006 * H), pool_k=.5) + # halftones: a thin glaze where the light family is still lighter than the design (the turn of the form) + cur = T * paper + tgt = lighten(base, 7) + ht = np.clip(Lab_diff(cur, tgt) * 6, 0, 1) * fig_m * fade * (D.fam > .5) + glaze(np.clip(tgt / np.maximum(cur, .04), 0, 1), DS.soft(ht, .012 * H) * .85) + # wash 3: darks last, small: the hair darks (dry-brush strokes along the locks), casts, features + cur = T * paper + dark = (np.isin(D.reg, HAIR_REGS) & (D.hair_val < .3)).astype(F32) * fade + dark = np.maximum(dark, D.cast * .8 * (D.reg == R["face"])) + glaze(np.clip(base / np.maximum(cur, .04), 0, 1), DS.soft(dark, 1.0) * .8, gran=.4, pool=_pool(dark, .005 * H), + pool_k=.4) + cv = T * paper + B = Brush(cv, lighten(base, -6), D, rng) + B.layer(fade > .5, .0045 * H, .14 * H, .35, jit=.4, density=.4, lost=.0, bristle=.8, + regs=HAIR_REGS + [R["beard"]], keep_fam=False) + cv = B.cv + fa = D.feat[..., 3:4] * .85 + fc = lighten(D.feat[..., :3], 4) + cv = cv * (1 - fa) + np.minimum(fc, cv) * fa + # cold-press paper tooth over everything + cv = cv * (1 + (vnoise(S, S, 1.3, rng)[..., None] - .5) * .05) + return (np.clip(cv, 0, 1) * 255 + .5).astype(np.uint8), D + + +def Lab_diff(a, b): + """lightness excess of a over b in 0..1 (L* / 100): where the wash is still lighter than the design""" + return np.clip((DS.to_lab(a)[..., 0] - DS.to_lab(b)[..., 0]) / 100.0, 0, 1) + + +# --------------------------------------------------------------------------------------------- gouache +def gouache(fig, seed=0): + D = DS.design(fig, seed, "gouache") + S, H = D.S, D.H + rng = np.random.default_rng(seed * 41 + 13) + ref = D.base.copy() + # gouache dries lighter and chalkier: a little white in the lights, matte + ref = ref * (1 - .06 * D.fam[..., None]) + .06 * D.fam[..., None] * np.array([.96, .95, .92], F32) + # flat opaque shapes: the halftone steps posterised (human-104: at most 3 values per part) + lab = DS.to_lab(ref) + q = 7.0 + lab[..., 0] = np.round(lab[..., 0] / q) * q * .7 + lab[..., 0] * .3 + ref = DS.from_lab(lab) + # dry-brush edges: broken by a noise threshold instead of a blur where the design loses the edge + n = fbm(S, S, 1.4, rng, 2) - .5 + b = np.stack([ndi.gaussian_filter(ref[..., c], 1.5) for c in range(3)], -1) + e = np.clip(D.soft * 1.5, 0, 1)[..., None] + pick = (n[..., None] > 0).astype(F32) + ref = ref * (1 - e) + (b * pick + ref * (1 - pick)) * e + B = Brush(ref.copy(), ref, D, rng) + every = np.ones((S, S), F32) + # broad flat brush marks in the ground; clothes and hair in a few flat strokes of their own colours + B.layer(every, .04 * H, .22 * H, .85, jit=.6, density=.8, lost=.0, bristle=.25, regs=[R["bg"]]) + B.layer(every, .025 * H, .16 * H, .8, jit=.3, density=.6, lost=.0, bristle=.2, regs=[R["torso"]]) + B.layer(every, .012 * H, .12 * H, .75, jit=.5, density=.7, lost=.0, bristle=.35, regs=HAIR_REGS) + cv = restate_features(B.cv, D, .95, 0) + cv = cv * (1 + (vnoise(S, S, 1.5, rng)[..., None] - .5) * .04) + return (np.clip(cv, 0, 1) * 255 + .5).astype(np.uint8), D + + +MEDIA = {"oil": oil, "watercolor": watercolor, "gouache": gouache} + + +def medium_for(fig): + t = ((getattr(fig, "variant", "") or "") + " " + (getattr(fig, "text", "") or "")).lower() + if "watercol" in t: + return "watercolor" + if "gouache" in t or "tempera" in t or "poster" in t: + return "gouache" + return "oil" + + +def render(fig, size, seed, trace=None): + m = medium_for(fig) + img, D = MEDIA[m](fig, seed) + if trace is not None: + trace.append("paint2: %s on the design stage (masses, designed shadows, features, marks last)" % m) + return img diff --git a/pydraw/figure/style_anime.py b/pydraw/figure/style_anime.py index 611eab395f49d712543d53e4f9213a09d7cbb505..1abc3b1c3b3edf84a57d5b70e59d32c99af18e38 100644 --- a/pydraw/figure/style_anime.py +++ b/pydraw/figure/style_anime.py @@ -1017,7 +1017,11 @@ def draw(lay, hl, p): mc = lay.P(0, my, flat=.4) mw = c["mouth_w"] * H * (1 if abs(yaw) < .2 else .8) mc = mc + np.array([sgn * .02 * H * abs(np.sin(yaw)) * 1.5, 0]) - if smile > 0: + _fx = p.get("fx") if (p.get("fx") is not None and not p["fx"].neutral) else None + if _fx is not None: # wave 20 faces lane hook + from .face_draw import anime_mouth + anime_mouth(cv, mc, mw, H, W, Wi, inkc, mouthc, skin, skin_sh, covF, p) + elif smile > 0: if age == "child" or (fem and age == "teen"): # small open smile: a D shape, dark mouth + tongue disc (A7) top = np.array([mc + np.array([-mw * .55, -.005 * H]), mc + np.array([0, -.002 * H]), mc + np.array([mw * .55, -.005 * H])]) @@ -1034,7 +1038,7 @@ def draw(lay, hl, p): else: Pm = crv(np.array([mc + np.array([-mw * .45, -.002 * H]), mc + np.array([0, .003 * H]), mc + np.array([mw * .45, -.003 * H])]), False, 6) ink(Pm, np.array([.45, 1.0, .45]) * W * 1.4, col=mouthc) - if not (smile > 0 and (age == "child" or (fem and age == "teen"))): + if _fx is None and not (smile > 0 and (age == "child" or (fem and age == "teen"))): cv.fill(crv(np.array([mc + np.array([-mw * .2, .03 * H]), mc + np.array([mw * .25, .03 * H]), mc + np.array([0, .042 * H])]), True, 4), skin_sh, covF) # lower-lip shadow tick (designed) if age == "elderly": # age lines (interior weight) @@ -1043,7 +1047,16 @@ def draw(lay, hl, p): deferred.append(("ink", crv(np.array([(x0 + s * .02 * H, ny * H + lay.cy0 + .0 * H), (x0 + s * .025 * H, mc[1] - .02 * H), (x0 + s * .01 * H, mc[1] + .015 * H)]), False, 5), Wi * .8)) - if p.get("beard"): + if p.get("beard") and p.get("fx") is not None: # wave 20 faces lane: beard over the jaw + from .face_draw import anime_beard, anime_mouth + anime_beard(cv, lay, p, c, H, W, Wi, hair, hair_sh, inkc, lightdir, covF, mc, mw, sgn) + if _fx is not None: + anime_mouth(cv, mc, mw, H, W, Wi, inkc, mouthc, skin, skin_sh, covF, p) + else: + Pm = crv(np.array([mc + np.array([-mw * .45, -.002 * H]), mc + np.array([0, .003 * H]), + mc + np.array([mw * .45, -.003 * H])]), False, 6) + ink(Pm, np.array([.45, 1.0, .45]) * W * 1.4, col=mouthc) + elif p.get("beard"): _beard(cv, lay, p, c, H, W, Wi, hair, hair_sh, inkc, lightdir, covF, mc, mw, smile, sgn) if p.get("glasses"): # simple frames (thin ink, A5 interior) lens = [] @@ -1103,11 +1116,17 @@ def draw(lay, hl, p): pts = np.array([(inner, by + .006 * H), (ctr[0] + s * bw_ * .05, by - arch), (outer, by + arch * .3)]) wb = (np.array([.9, 1.2, .5]) * W) if fem else (np.array([2.2, 2.0, 1.0]) * W * (1.15 if age == "elderly" else 1)) bcol = mix(hair_deep, inkc, .55) if not light_hair else mix(hair_sh, inkc, .3) + if _fx is not None: # wave 20 faces lane: the brow moves + from .face import apply_brow + pts = apply_brow(pts, ew * H * max(.6, wscale), _fx.p, (-s, 0.0), up=(0.0, -1.0), age_p=_fx.age_p) Pb = crv(pts, False, 6) cv.line(Pb, np.interp(np.linspace(0, 1, len(Pb)), [0, .5, 1], wb), bcol) for kind, P, w in deferred: if kind == "ink": ink(P, w) + if _fx is not None: # wave 20 faces lane: creases, tears + from .face_draw import anime_marks + anime_marks(cv, p, eyes_px, nose_tip, mc, mw, H, W, ew * H, inkc, skin, skin_sh, covF, sgn) # what was drawn where (the critic verifies claimed features against the picture; the kit layout's own points # come from a different face model, so the anime renderer reports its own) p["_claim"] = dict(eyes={s_: tuple(map(float, c_)) for s_, c_, _ in eyes_px}, nose=tuple(map(float, nose_tip)), @@ -1192,6 +1211,9 @@ def _eye(cv, ctr, ew, eh, side, gaze, p, c, W, inkc, iris_col, skin_sh, smile, l under the upper lid, nearly ink-dark with colour only in a 2-tone bottom crescent; highlight in the upper quarter on the light side + an outer sliver; grey lid-shadow band; upper lash wedge 3-4x the outline weight (lighter for men); short lower stroke under the iris; params: gaze, roll (with the head), openness (smile), age.""" + if p.get("fx") is not None and not p["fx"].neutral: # wave 20 faces lane hook (fx_face, default OFF) + from .face_draw import anime_eye + return anime_eye(cv, ctr, ew, eh, side, gaze, p, c, W, inkc, iris_col, skin_sh, smile, lightdir, deferred) fem, age = p["sex"] == "f", p["age"] tilt = np.radians(-6 if fem else -3) * (1 if age != "elderly" else -.5) # tsurime/tareme +-12 max (F33) hh = eh / 2 @@ -1759,6 +1781,7 @@ def params_from_figure(fig): light=int(np.sign(L.light_side) or 1), fringe="spiky" if re.search(r"\bspiky\b", fig.text.lower()) else getattr(HL, "fringe", None), part_side=(HL.parting or {}).get("side") if getattr(HL, "parting", None) else None) + p["fx"] = getattr(L, "fx", None) # wave 20 faces lane spec (None unless fx_face=1) crown = np.asarray(L.pt["crown"], float) p["place"] = (float(L.H), float(crown[1]), float(crown[0])) return p diff --git a/pydraw/figure/style_ink.py b/pydraw/figure/style_ink.py index e0c816cf5c7b021f73b01cc676ee27a49540316b..8382d5d214b45abb2e3611890fbcc82d2be0a4fc 100644 --- a/pydraw/figure/style_ink.py +++ b/pydraw/figure/style_ink.py @@ -1379,6 +1379,9 @@ class InkPortrait: self.brows() self.nose() self.mouth() + if getattr(self.L, "fx", None) is not None: # wave 20 faces lane hook (fx_face, default OFF) + from .face_draw import ink_extras + ink_extras(self) # 2 form hatching on the shadow side self.face_hatching() # neck / shoulders / ears @@ -1906,6 +1909,9 @@ def work_size(size, framing): def render(fig, size, seed, trace): """kit contract: fig.layout (L), fig.hair (HL), fig.variant ('pencil', 'charcoal', 'pen and ink', ...)""" + from . import ink2 + if ink2.active(): # wave 20 styles lane: design stage + pen / pencil / charcoal finishers (st_ink) + return ink2.render(fig, size, seed, trace) var = (getattr(fig, "variant", "") or "") + " " + (getattr(fig, "text", "") or "") medium = medium_from_text(var) if knob("inkstand", "0"): diff --git a/pydraw/figure/style_paint.py b/pydraw/figure/style_paint.py index 0dd304ceb5ef25b891cae5f5900091a2a0c1f3b5..7374acb79de658b3a3fc55c9674dfb8f3cb0e1ec 100644 --- a/pydraw/figure/style_paint.py +++ b/pydraw/figure/style_paint.py @@ -909,7 +909,11 @@ def draw(p, W=512, H=640, seed=None, layout=None, hair=None, medium=None, trace= if on("pp_chincast"): _chin_cast(cv, Lo, C, s, sc, m_face, m_neck) if on("pp_features"): - _features(cv, Lo, p, C, s, sc, m_face, rng) + if getattr(Lo.get("kit"), "fx", None) is not None: # wave 20 faces lane hook (fx_face, default OFF) + from .face_draw import paint_features + paint_features(cv, Lo, p, C, s, sc, m_face, rng, _features) + else: + _features(cv, Lo, p, C, s, sc, m_face, rng) _hair(cv, Lo, Hl, p, C, s, sc, m_face, rng) for e in Lo["ears"] if ears_over else []: me = _ear(cv, e, C, s, sc) @@ -1708,6 +1712,9 @@ def hair_from_kit(fig, p, Lo, rng): def render(fig, size, seed, trace): """kit contract: the painted portrait of fig (layout + hair layout from the kit lane) -> size x size uint8""" + from . import paint2 + if paint2.active(): # wave 20 styles lane: design stage + oil / watercolor / gouache finishers (st_paint) + return paint2.render(fig, size, seed, trace) p = params_from_fig(fig, seed) rng = np.random.default_rng(seed * 104729 + 3) Lo = layout_from_kit(fig, p, size, rng) diff --git a/pydraw/figure/style_pixel.py b/pydraw/figure/style_pixel.py index 095b48c606970712d69d1adb4e148c29f40aea22..ae5eba0110866adbcdbb8c52e08ae61e7aca01cb 100644 --- a/pydraw/figure/style_pixel.py +++ b/pydraw/figure/style_pixel.py @@ -1011,7 +1011,11 @@ def portrait(person, n=48, return_info=False, fig=None): # ---- 6 features (X8) if L.get("beard") and knob("px_beard"): _beard(G, L, light, HM) - info = draw_features(G, L, light, None) + if getattr(L.get("kit"), "fx", None) is not None: # wave 20 faces lane hook (fx_face, default OFF) + from .face_draw import pixel_features + info = pixel_features(G, L, light, None) + else: + info = draw_features(G, L, light, None) if L.get("glasses") and knob("px_glasses"): _glasses(G, L, light) # ---- 7 material lines: hair over skin (X6), ramp step (X5), shirt meets neck / hair diff --git a/pydraw/figure/value.py b/pydraw/figure/value.py index 6e9591174c002f344a3d55172b7259c0539197a0..4d7c090b9f39006e2d2f442dc1d4498d8f331c9f 100644 --- a/pydraw/figure/value.py +++ b/pydraw/figure/value.py @@ -95,7 +95,12 @@ def hair_rgb(name, seed=0, age=30.0, skin=0.3): if age >= 62: name = "grey" if r.random() < .6 else "white" c = np.array(HAIR.get(name, HAIR["brown"]), F32) - return np.clip(c * (1 + r.normal(0, 0.04, 3)), 0, 1).astype(F32), name + jit = r.normal(0, 0.04, 3) + if name in ("grey", "gray", "white", "silver", "platinum"): + from . import face as _face + if _face.active("fx_age"): # wave 20: neutral hair keeps one jitter for all channels (white went mint green) + jit = np.full(3, jit[0] * 0.5) + return np.clip(c * (1 + jit), 0, 1).astype(F32), name def eye_rgb(name, seed=0): diff --git a/pydraw/gbuf.py b/pydraw/gbuf.py index 5336f10b8713ce6ea1a52f0cf79a553522f7c937..1ea13dd28996a143dc102ccc1d3bc26592b160c2 100644 --- a/pydraw/gbuf.py +++ b/pydraw/gbuf.py @@ -1036,11 +1036,21 @@ def render_medium(name, text, scene, rng, trace, seed, size): gs = int(min(MAX_SIZE, max(64, round(size * scale)))) G = _build(text, scene, rng, trace, seed, gs) trace.append("gbuf: medium '%s' paints from the G-buffer (%d px)" % (name, gs)) + from . import picplan as _pp # wave 19 (plan): the picture's value plan before the medium (knobs pp_*, default off) + _pp.run_gbuf(G, trace) plan_hook(G, name, trace) out = np.asarray(fn(G, seed, trace), np.float64) if out.shape[0] != size: out = _resize(out, size) - return Image(np.clip(out, 0, 255), scene, trace) + img = Image(np.clip(out, 0, 255), scene, trace) + if _pp.claim_level(): + try: + inst = {k: o.get("inst") for k, o in (getattr(G, "objects", None) or {}).items()} + img.claim = _pp.claim(scene, "medium:" + name, ids=G.obj, inst=inst, y0=G.horizon, size=size, seed=seed) + img.claim["_ids"] = G.obj + except Exception as ex: + trace.append("picplan: claim failed (%s)" % str(ex)[:80]) + return img def plan_hook(G, name, trace): diff --git a/pydraw/inkmedia/__pycache__/__init__.cpython-310.pyc b/pydraw/inkmedia/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2df5dd244de3c85bfc15dbfa6dfba20dc624814 Binary files /dev/null and b/pydraw/inkmedia/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/inkmedia/__pycache__/adapt.cpython-310.pyc b/pydraw/inkmedia/__pycache__/adapt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c7729e190a8ba683c894490f6069f8861dbc075 Binary files /dev/null and b/pydraw/inkmedia/__pycache__/adapt.cpython-310.pyc differ diff --git a/pydraw/inkmedia/__pycache__/common.cpython-310.pyc b/pydraw/inkmedia/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f245cc0047bd2ad146a21c3190dc9b4fa7bb0dd9 Binary files /dev/null and b/pydraw/inkmedia/__pycache__/common.cpython-310.pyc differ diff --git a/pydraw/inkmedia/__pycache__/hatch.cpython-310.pyc b/pydraw/inkmedia/__pycache__/hatch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7888983b6d6b22bd93ea1ab51dd29cfed3ee32af Binary files /dev/null and b/pydraw/inkmedia/__pycache__/hatch.cpython-310.pyc differ diff --git a/pydraw/inkmedia/__pycache__/ink.cpython-310.pyc b/pydraw/inkmedia/__pycache__/ink.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25b442a420eb50e695e70c34b9d1bde61c7b5288 Binary files /dev/null and b/pydraw/inkmedia/__pycache__/ink.cpython-310.pyc differ diff --git a/pydraw/inkmedia/__pycache__/lines.cpython-310.pyc b/pydraw/inkmedia/__pycache__/lines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e003b67b06fd8d5fdd5ed2ed60423d66fee32c5 Binary files /dev/null and b/pydraw/inkmedia/__pycache__/lines.cpython-310.pyc differ diff --git a/pydraw/inkmedia/ink.py b/pydraw/inkmedia/ink.py index 5a62949e45db744046d2795c39f9d6868cb8729c..76572917cb34e634dec7734bd155e0f6f951a354 100644 --- a/pydraw/inkmedia/ink.py +++ b/pydraw/inkmedia/ink.py @@ -76,7 +76,7 @@ def render_ink(gb, seed=0, knobs=None): from ..gbuf import on16 if on16("ink_veil"): D, Dt = veil_darkness(gb, D), veil_darkness(gb, Dt, spot=True) - lines, _ = field_lines(gb, seed, weight=float(k.get("ink_w", 1.0))) + lines, _ = field_lines(gb, seed, weight=float(k.get("ink_w", 1.0)), hier=_md("md_pen")) hat = hatch(gb, D, seed, spacing=float(k.get("ink_sp", 4.2))) spot = spot_blacks(gb, Dt) * float(k.get("ink_spot", 1.0)) if k.get("ink_ground", "1") != "0": @@ -265,6 +265,8 @@ def render_comic(gb, seed=0, knobs=None): spot = spot_blacks(gb, Dt, thr=.86) # inker's spotting: the darkest local colours go solid black in their shadow spot = np.maximum(spot, ((Dt > .72) & shm).astype(np.float32)) + if _md("md_comic"): + spot = comic_spots(gb, Dt, shm, spot, k) lines, _ = field_lines(gb, seed, weight=float(k.get("ink_w", 1.45)), lost=.5, wobble=.4, pressure=.2) D = darkness(gb, seed=seed) feather = hatch(gb, D, seed, layers=(.7, .88, .95), max_layers=1, width=.7) * (gb["obj"] > 0) @@ -472,8 +474,10 @@ def render_linocut(gb, seed=0, knobs=None): water = _mat_mask(gb, ("water", "ice")) flatg = bg & (yy >= hz) & ~water phi = np.where(flatg, np.log(gy) * (S * .07 / sp), phi) - # the focal object: carve more white into its lit side so a face / a door survives the black mass rank = _rank(gb) + if _md("md_lino"): + D = lino_notan(gb, D_raw, D, rank, k) + # the focal object: carve more white into its lit side so a face / a door survives the black mass D = np.where(obj > 0, D * (1 - .5 * gb["focal"] * smoothstep(.35, .85, rank)), D) tri = np.abs((phi % 1.0) - .5) * 2 # 0 on a gouge centre .. 1 between gouges rough = noise(S, S, seed + 93, 3 * sc, 2) * .25 @@ -495,6 +499,8 @@ def render_linocut(gb, seed=0, knobs=None): # wave 16 plan lane (illustration.md rule 12): the open backdrop carved as tapered lens gouges on a flow field from .gouge import lenses lk, M = lenses(gb, np.clip(D, 0, 1), seed, sp=7.0 * float(k.get("lino_sp", 1.0)), D_raw=np.clip(D_raw, 0, 1)) + if _md("md_lino"): + M = M & (D < .9) # (md_lino) a black mass stays solid: no lens speckle inside it ink = np.where(M, lk, ink) if grassm.any(): ink = np.where(M & (tufts > .5), 0.0, ink) @@ -503,14 +509,24 @@ def render_linocut(gb, seed=0, knobs=None): if things.any(): dd = ndimage.distance_transform_edt(~things) halo = (dd > 1.5 * sc) & (dd < 5.5 * sc) & ~things - ink = np.where(halo & (D < .95), 0.0, ink) + ink = np.where(halo & (D < (.99 if _md("md_lino") else .95)), 0.0, ink) # the outline: cut as a heavy black line lines, _ = field_lines(gb, seed, weight=float(k.get("ink_w", 1.6)), lost=.4, wobble=1.6, pressure=.45) ink = np.maximum(ink, (lines > .5).astype(np.float32)) # carved edges are not anti-aliased pen lines: roughen the boundary, uneven ink on the paper - ink = ndimage.gaussian_filter(ink, .7 * sc) + noise(S, S, seed + 94, 1.5 * sc, 1) * .35 - ink = smoothstep(.42, .58, ink) - ink *= 1 - .22 * (tooth > .78) + if _md("md_lino"): + # (md_lino, media.md L3) texture is a gouge mark, never pixel noise: the per-pixel roughness only works on the + # cut edges; inside a black mass the ink is a low-frequency mottle (8-20 px blobs, 10-15% density loss) + hard = ink > .5 + edge = ~(ndimage.binary_erosion(hard, iterations=2) | ndimage.binary_erosion(~hard, iterations=2)) + nz = np.where(edge, noise(S, S, seed + 94, 1.5 * sc, 1) * .35, 0) + ink = smoothstep(.42, .58, ndimage.gaussian_filter(ink, .7 * sc) + nz) + mott = smoothstep(.55, .9, noise(S, S, seed + 96, 14 * sc, 2)) + ink *= 1 - .13 * mott * ndimage.gaussian_filter(tooth, 1.5 * sc) + else: + ink = ndimage.gaussian_filter(ink, .7 * sc) + noise(S, S, seed + 94, 1.5 * sc, 1) * .35 + ink = smoothstep(.42, .58, ink) + ink *= 1 - .22 * (tooth > .78) out = pap if k.get("lino_color", "1") != "0": # second block: one flat colour (the scene's strongest hue) under the black, where objects carry it @@ -532,6 +548,128 @@ def render_linocut(gb, seed=0, knobs=None): return _lay(out, ink, (22, 20, 24)) +def _md(name): + import os + E = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return E.get(name, "0") != "0" + + +def comic_spots(gb, Dt, shm, spot, k=None): + """(wave 19 media, knob md_comic; R18 comic, media.md K1, research17 rule 22) spot the blacks by the picture's own + value RANK, not by a fixed near-black: a bright sunrise lake measured 2.6% black, a comic page reads at 15-35%. + things the darkest part of each thing's shadow side goes solid: shadow-side pixels with Dt above the thing's own + md_cq quantile (.5) - the inker fills the half of the shadow that is farthest from the light + ground cast shadows on the ground go solid (the shadow map's core, gb shadow > .5) + top-up if the picture is still under md_cmin (.15) black, the darkest shadow-side / backdrop regions by rank join + until it is (regions whole: a spotted black is a shape decision, never per pixel)""" + k = k or {} + S = gb["obj"].shape[0] + obj = gb["obj"] + out = spot.copy() + q = float(k.get("md_cq", .5)) + for oid in np.unique(obj): + if oid == 0: + continue + m = (obj == oid) & shm + if m.sum() < 30: + continue + thr = np.quantile(Dt[m], q) + out = np.maximum(out, (m & (Dt >= thr)).astype(np.float32)) + sh = gb.get("shadow") + if sh is not None: + cast = ndimage.gaussian_filter((np.asarray(sh) > .5).astype(np.float32), 1.0 * S / 512) > .5 + out = np.maximum(out, (cast & (obj == 0) & ~gb["sky"]).astype(np.float32)) + cmin = float(k.get("md_cmin", .15)) + if (out > .5).mean() < cmin: + inv, n, col, isobj, cnt = regions(gb, min_frac=.0006) + dm = np.bincount(inv.ravel(), weights=Dt.ravel(), minlength=n) / np.maximum(cnt, 1) + skyr = np.bincount(inv.ravel(), weights=gb["sky"].ravel().astype(np.float64), minlength=n) / np.maximum(cnt, 1) + acc = float((out > .5).sum()) + for j in np.argsort(-dm): + if acc >= cmin * S * S or dm[j] < .35: + break + if skyr[j] > .3 or cnt[j] > .06 * S * S: + continue # the sky stays colour; a field (> 6% of the frame) black is not a spot + m = inv == j + acc += float((m & (out <= .5)).sum()) + out = np.maximum(out, m.astype(np.float32)) + return ndimage.gaussian_filter(out, .5 * S / 512) + + +def lino_notan(gb, D_raw, D, rank, k=None): + """(wave 19 media, knob md_lino; R18 linocut, media.md L1-L4, copy_graphic P1-P3) a relief print is DESIGNED in + black masses first and carved into: every shape is decided black or white before any gouge (the notan). Shapes + (regions) are taken darkest-first until the black share reaches md_linob (.45; relief prints read about half black, + media.md L1 target .35-.60 with one connected mass >= 15%). A black shape stays solid on its shadow side and gets + white gouges only on its lit side (L2: cut white into black, follow the form); a white shape is paper with a few + black lines left standing. Night skies go black (star nicks are cut by the bright-sky rule below).""" + k = k or {} + S = gb["obj"].shape[0] + inv, n, col, isobj, cnt = regions(gb, min_frac=.0006) + # a region is a thing when MOST of it is a thing (regions() flags any touch: rain streaks made the storm sky "a thing") + isobj = np.bincount(inv.ravel(), weights=(gb["obj"] > 0).ravel().astype(np.float64), minlength=n) / np.maximum(cnt, 1) > .5 + dsum = np.bincount(inv.ravel(), weights=np.clip(D_raw, 0, 1).ravel(), minlength=n) + dm = dsum / np.maximum(cnt, 1) + night = (gb.get("scene") or {}).get("time") in ("night", "dusk") + sky = gb["sky0"] | gb["sky"] + skyr = np.bincount(inv.ravel(), weights=sky.ravel().astype(np.float64), minlength=n) / np.maximum(cnt, 1) > .5 + if night: + dm = np.where(skyr, dm + 1.0, dm) # a night sky is the first black + # counterchange first (copy_graphic P2, R4): the ground right round a LIGHT thing is the first black, so a white + # sheep stands on a black hill rather than a white hill under a black sky + obj = gb["obj"] + tone = gb["tone"] + lightobj = np.zeros(obj.shape, bool) + for oid in np.unique(obj): + if oid and (obj == oid).sum() > .004 * S * S and float(tone[obj == oid].mean()) > .55: + lightobj |= obj == oid + if lightobj.any(): + ring = ndimage.binary_dilation(lightobj, iterations=max(2, int(8 * S / 512))) & (obj == 0) + touch = np.bincount(inv[ring].ravel(), minlength=n) / np.maximum(cnt, 1) + dm = np.where((touch > 0) & ~isobj & (np.bincount(inv[ring].ravel(), minlength=n) > .1 * ring.sum()), dm + .5, dm) + target = float(k.get("md_linob", .45)) * S * S + order = np.argsort(-dm) + black = np.zeros(n, bool) + acc = 0.0 + for j in order: # the backdrop's shapes first: they make the big mass + if isobj[j]: + continue + if acc >= target: + break + if acc + cnt[j] > .62 * S * S and acc > .3 * S * S: + continue # never more than ~60% black + black[j] = True + acc += cnt[j] + # the things: counterchange (copy_graphic P2) - a thing is black only when it is dark AND the ground around it is + # white; on a black ground it stays white and is carved with black lines (a white sheep on a black hill) + Bg = black[inv] + r = max(2, int(6 * S / 512)) + for j in np.nonzero(isobj)[0]: + m = inv == j + if not m.any(): + continue + ring = ndimage.binary_dilation(m, iterations=r) & ~m & (gb["obj"] == 0) + gbk = float(Bg[ring].mean()) if ring.any() else 0.0 + black[j] = dm[j] > .55 and gbk < .5 + B = black[inv] + # a black shape: solid in shadow, white gouges on the lit side (rank = light along the form, per object) + # backdrop: "lit" is relative to the shape's own mean tone (a pale sea chosen black must stay a black mass, cut + # only where it is lighter than itself - the glints, the sky's glow) + tmean = (np.bincount(inv.ravel(), weights=gb["tone"].ravel(), minlength=n) / np.maximum(cnt, 1))[inv] + lit = np.where(gb["obj"] > 0, rank > .62, gb["tone"] > tmean + .08) + Db = np.where(lit, .72, .97) + # (L2/L3) a big black backdrop mass is carved, not dead: broken level gouges in low-frequency patches (water + # gets more: the reflections), never per-pixel speckle + big = (cnt > .08 * S * S) & ~isobj + patch = noise(S, S, int(k.get("seed", 0)) + 97, 40 * S / 512, 2) + from .hatch import _mat_mask + wat = _mat_mask(gb, ("water", "ice")) + cut = big[inv] & (gb["obj"] == 0) & (patch > np.where(wat, -.05, .1)) + Db = np.where(cut & ~lit, np.where(wat, .45, .55), Db) + Dw = np.clip(D * .45, 0, .5) + return np.where(B, Db, Dw).astype(np.float32) + + # ------------------------------------------------------------------------------------------------ sumi-e def render_sumie(gb, seed=0, knobs=None): """East Asian ink painting (sumi-e / shan shui): one black ink diluted into a few densities ('five inks'), diff --git a/pydraw/inkmedia/lines.py b/pydraw/inkmedia/lines.py index 8c2675b9fd9cc9c2827faeedec0488f05c44bc2a..8fe3e7167f5471c4bf8e1fe083947316ce6832a8 100644 --- a/pydraw/inkmedia/lines.py +++ b/pydraw/inkmedia/lines.py @@ -81,7 +81,114 @@ def edge_maps(gb): inner = np.maximum(inner, np.where(bline, .55, 0).astype(np.float32)) sil[:, -1] = sil[-1, :] = 0 inner[:, -1] = inner[-1, :] = 0 - return sil, np.maximum(inner, detail), crease + inner = np.maximum(inner, detail) + if _md("md_contour"): + inner = tonal_off(gb, inner, K) + return sil, inner, crease + + +def _md(name): + import os + E = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return E.get(name, "0") != "0" + + +def _md_v(name, d): + import os + E = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + try: + return float(E.get(name, d)) + except ValueError: + return d + + +def tonal_off(gb, inner, K): + """(wave 19 media, knob md_contour; R17, media.md X1) contours are for form edges only. An inker draws silhouettes, + occlusions and creases, never a line round an edge that exists only in the albedo or the light: snow on rock, a + highlight, a cast shadow, a reflection in water (1905 Elements of Pen-and-Ink Rendering: "the pen is used simply to + express masses of light and shade"). Silhouettes (object-id edges) are never touched; this only clears the interior / + backdrop line map of: + caps a SMALL backdrop region (< 3% of the frame) lighter than the same-layer, same-material region around it + (a snowcap on a mountain is its own gbuf region): its border with that parent goes; its border with the + sky (a silhouette) stays + water colour edges inside water / ice (reflections, glitter, ripples): only the shoreline (a material or + layer change) keeps its line + shadows a line that runs along the cast-shadow map's edge with no material / layer change under it + highlights inside an object, the border of a small bright patch (the object's top 8% of tone, < 12% of it)""" + from ..gbuf import MAT + obj, mat, layer, tone = gb["obj"], gb["mat"], gb["layer"], gb["tone"] + S = obj.shape[0] + bg = obj == 0 + keep = np.ones(obj.shape, bool) + r2 = max(1, int(round(2 * S / 512))) + # material / layer change within 1 px: the backdrop's real plane seams + ml = mat.astype(np.int64) * 64 + layer + mchg = np.zeros(obj.shape, bool) + for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): + mchg |= np.roll(ml, (dy, dx), (0, 1)) != ml + mchg = ndimage.binary_dilation(mchg, iterations=r2 + 2) # a seam line may sit 2-3 px off the material edge + sky = ndimage.binary_dilation(gb["sky0"] | gb["sky"], iterations=r2 + 1) + # caps + Kb = np.where(bg, K, -1) + u, inv, cnt = np.unique(Kb, return_inverse=True, return_counts=True) + inv = inv.reshape(obj.shape) + tsum = np.bincount(inv.ravel(), weights=tone.ravel(), minlength=len(u)) + tmean = tsum / np.maximum(cnt, 1) + small = (cnt < .03 * S * S) & (u >= 0) + capm = np.zeros(obj.shape, bool) + boxes = ndimage.find_objects(inv + 1) + pad = r2 + 2 + for j in np.nonzero(small & (cnt > 6))[0]: + if j >= len(boxes) or boxes[j] is None: + continue + ys, xs = boxes[j] + sl = (slice(max(0, ys.start - pad), ys.stop + pad), slice(max(0, xs.start - pad), xs.stop + pad)) + m = inv[sl] == j + ring0 = ndimage.binary_dilation(m, iterations=r2 + 1) & ~m & ~sky[sl] + ring = ring0 & bg[sl] & (ml[sl] == np.bincount(ml[sl][m].ravel()).argmax()) + if ring.sum() < 4 or ring.sum() < .75 * ring0.sum(): + continue # enclosed by its parent (sky aside): a cap; a shore strip between water and grass is a plane + if tmean[j] - float(tone[sl][ring].mean()) > .06: + capm[sl] |= ndimage.binary_dilation(m, iterations=r2) & ~ndimage.binary_erosion(m, iterations=r2) + keep &= ~(capm & ~sky) + # water: reflections are tone + wat = bg & np.isin(mat, [MAT["water"], MAT["ice"]]) + # a seam between two BIG backdrop regions inside the water material is a shore (gbuf paints a beach strip as water) + bigr = (cnt >= .01 * S * S)[inv] & bg + kbig = np.zeros(obj.shape, bool) + for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): + kbig |= (np.roll(inv, (dy, dx), (0, 1)) != inv) & bigr & np.roll(bigr, (dy, dx), (0, 1)) + kbig = ndimage.binary_dilation(kbig, iterations=r2 + 5) + keep &= ~(wat & ~mchg & ~kbig) + # cast-shadow edges + sh = gb.get("shadow") + if sh is not None and np.ptp(sh) > 0: + gy, gx = np.gradient(ndimage.gaussian_filter(sh.astype(np.float32), .7)) + she = np.hypot(gx, gy) > .12 + oid_chg = np.zeros(obj.shape, bool) + for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): + oid_chg |= np.roll(obj, (dy, dx), (0, 1)) != obj + keep &= ~(ndimage.binary_dilation(she, iterations=r2) & ~mchg & ~ndimage.binary_dilation(oid_chg, iterations=r2)) + # highlights inside objects + hl = np.zeros(obj.shape, bool) + oboxes = ndimage.find_objects(obj) + for oid in np.unique(obj): + if oid == 0 or oid - 1 >= len(oboxes) or oboxes[oid - 1] is None: + continue + ys, xs = oboxes[oid - 1] + sl = (slice(max(0, ys.start - pad), ys.stop + pad), slice(max(0, xs.start - pad), xs.stop + pad)) + m = obj[sl] == oid + n = int(m.sum()) + if n < 60: + continue + tl = tone[sl] + t = tl[m] + thr = np.quantile(t, .92) + b = m & (tl >= thr) & (tl > np.median(t) + .12) + if 0 < b.sum() < .12 * n: + hl[sl] |= ndimage.binary_dilation(b, iterations=r2) & ~ndimage.binary_erosion(b, iterations=1) & m + keep &= ~hl + return np.where(keep, inner, 0).astype(np.float32) def _chains(mask): @@ -260,7 +367,8 @@ def ink_lines(gb, seed=0, weight=1.0, lost=1.0, wobble=1.0, classes=(1, 1, 1), m return cov, wmap -def field_lines(gb, seed=0, weight=1.0, lost=1.0, wobble=1.0, classes=(1, 1, 1), light_side=True, pressure=.3): +def field_lines(gb, seed=0, weight=1.0, lost=1.0, wobble=1.0, classes=(1, 1, 1), light_side=True, pressure=.3, + hier=False): """the same weighted lines rendered as a distance field (robust, no chain fragments): every edge pixel carries a radius smoothed ALONG the edge (pressure changes slowly within a stroke); a pixel is inked when it lies within the radius of its nearest edge pixel. Lost edges fade to nothing and so taper by themselves.""" @@ -279,6 +387,12 @@ def field_lines(gb, seed=0, weight=1.0, lost=1.0, wobble=1.0, classes=(1, 1, 1), lostf = 1 - lost * smoothstep(.8, .97, gb["tone"]) * (1 - focal) * .8 press = 1 + pressure * 2 * noise(S, S, seed + 17, 28 * sc, 2) wmap = Wt * sizef * sidef * (.78 + .45 * focal) * depthf * lostf * press + if hier: + # (wave 19 media, md_pen; R18 pen, media.md P2, copy_graphic P6-P7) a weight hierarchy: silhouettes of things + # 2-4x the interior / backdrop lines (Booth p90 3.0 px vs our lake_pen 1.0), heaviest on the shadow side; the + # interior and backdrop lines thin to hatch weight + thing = (sil > 0) & (obj > 0) + wmap = np.where(thing, wmap * float(_md_v("md_penk", 2.2)) * (.7 + .6 * shade), wmap * .8) E = Wt > 0 if not E.any(): return np.zeros((S, S), np.float32), wmap diff --git a/pydraw/inkmedia/woodblock.py b/pydraw/inkmedia/woodblock.py new file mode 100644 index 0000000000000000000000000000000000000000..99e492a342b09225c75295ebfc5f5568e46a9009 --- /dev/null +++ b/pydraw/inkmedia/woodblock.py @@ -0,0 +1,49 @@ +"""Woodblock print (ukiyo-e / moku hanga) from the G-buffer (wave 19 media lane, knob md_wood; R18, copy_graphic P4-P6). + +Measured on the Hiroshige night-snow copy (copy_graphic.md): a shared limited palette of at most 4 colours with >= 1% area +(near-neutral steps of one hue plus key black and paper), flat steps for every shape (a shadow side is its own flat shape +one step darker), ONE designed gradient band (bokashi) at the top of the sky, and a key line of ONE thin weight (about +0.18% of the width) on the big contours only. Turning the designed blacks off moved notan .67 -> .42; one heavy outline +weight was the next loss. + shapes the flat-vector shape pass (flat2: simplified regions, hue families, one shadow shape per object) + palette md_woodn (6) colours in all: the shapes are merged with the ramps budget (hue-safe), so 4 main colours plus + the key line and the paper survive + bokashi the sky's top md_wbk (.22) of the frame darkens smoothly toward the top in the sky's own darkest hue + key line silhouettes only, one weight, no taper (a cut line, not a brush), near-black of the palette's darkest hue + paper a uniform print grain (std ~1.5 levels) multiplied in, no per-region noise +""" +import numpy as np +from scipy import ndimage + +from .common import paper +from .lines import field_lines + + +def render_woodblock(gb, seed=0, knobs=None): + from .flat2 import render_flat2 + from .. import ramps + k = dict(knobs or {}) + k.setdefault("flat2_k", "4") + S = gb["obj"].shape[0] + out = np.asarray(render_flat2(gb, seed, k), np.float32) + out = np.asarray(ramps.cap(out, int(float(k.get("md_woodn", 6))), []), np.float32) + # bokashi: one designed gradient band at the top of the sky + sky = gb["sky0"] | gb["sky"] + if sky.mean() > .05: + yy = np.arange(S, dtype=np.float32)[:, None] * np.ones((1, S), np.float32) + band = float(k.get("md_wbk", .22)) * S + t = np.clip(1 - yy / band, 0, 1) ** 1.3 + sc = out[sky] + dark = np.percentile(sc, 10, axis=0) * .55 + a = (t * sky)[..., None] + out = out * (1 - a) + dark[None, None, :] * a + # key line: silhouettes, one thin weight, no taper or lost edges + lines, _ = field_lines(gb, seed, weight=float(k.get("md_wkw", .9)), lost=0, wobble=.3, pressure=0, + classes=(1, .6, 0), light_side=False) + key = np.percentile(out.reshape(-1, 3), 1, axis=0) * .6 + a = np.clip(lines, 0, 1)[..., None] + out = out * (1 - a) + key[None, None, :] * a + pap, tooth = paper(S, S, seed, tone=(242, 236, 222), tooth=.8) + grain = ndimage.gaussian_filter(tooth, .8) - .5 + out = out * (1 + .012 * grain[..., None]) * (pap.mean(-1, keepdims=True) / 240.0) + return np.clip(out, 0, 255) diff --git a/pydraw/language.py b/pydraw/language.py index 64c25da0f8df21da50cf887f386b12e193a7516e..3e86cc062df2f1e431b92d7b23f47cceb930bdfd 100644 --- a/pydraw/language.py +++ b/pydraw/language.py @@ -120,6 +120,23 @@ def on(rule=None): return rule is None or rule not in os.environ.get("PYDRAW_LANG_OFF", "").split(",") +# wave 19 (content lane, R14 "the prompt is a contract"): knobs read from PYDRAW_EXP like every other lane. +# Plain parse bug fixes are ON by default (ct_3d, ct_color, ct_door, ct_boat, ct_words); behaviour changes that add or +# change drawn content are behind ct_contract, default OFF. PYDRAW_EXP name=0 / name=1 overrides each. +CT_DEFAULTS = {"ct_3d": "1", "ct_color": "1", "ct_door": "1", "ct_boat": "1", "ct_words": "1", "ct_contract": "0", + "ct_3droute": "0", "ct_restpose": "1"} + + +def ct(name): + ev = dict(kv.split("=", 1) for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + v = ev.get(name) + if v is None and name != "ct_contract" and name.startswith("ct_") and name not in CT_DEFAULTS: + v = ev.get("ct_contract", "0") # sub-rules of the contract (ct_bed, ct_barn...) follow ct_contract + if v is None: + v = CT_DEFAULTS.get(name, "0") + return v != "0" + + # ---------------------------------------------------------------- pre-pass (tokens) def pre(toks, trace): if not on(): @@ -1587,3 +1604,151 @@ def _neg_parts(scene, toks, pos, trace): if part not in ab: ab.append(part) trace.append("language: '%s %s' -> %s without %s" % (t, toks[j], ents[k]["concept"], part)) + + +# ---------------------------------------------------------------- wave 19: the prompt is a contract (content lane, R14) +SAIL_WORDS = {"sail", "sails", "sailing", "sailboat", "sailboats", "yacht", "yachts", "regatta", "mast"} +ROW_CONTEXT = {"fisherman", "fishermen", "fishing", "rowing", "row", "rows", "rowed", "oar", "oars", "paddling", "paddle", + "angler", "punt", "ferryman"} +# place -> the key object a painter would never leave out (things 2: bedroom without a bed w16_33, farm without a barn +# w16_54). Only added when the prompt names the place word itself and nothing of that kind is already in the scene. +PLACE_KEY = {"bedroom": ("bed", {"bed", "bunk bed", "crib", "cot", "hammock", "sofa bed", "futon"}), + "farm": ("red barn", {"barn", "red barn", "farmhouse", "house", "cottage", "cabin", "shed", "windmill", "silo", "stable"})} +PLACE_KEY_WORDS = {"bedroom": {"bedroom", "bedrooms"}, "farm": {"farm", "farms", "farmyard", "barnyard"}} +# "lit by a lamp" / "lit windows": the thing glows; "a lighthouse in a storm": the lamp is lit (things 2: w16_52 unlit) +LIGHT_EMITTERS = {"lighthouse", "lamp", "lantern", "street lamp", "candle", "fireplace", "campfire", "bonfire"} + + +def _colors_known(): + from .understanding import COLORS + return COLORS + + +def contract(scene, trace): + """wave 19 content lane: plain parse fixes (default on) and contract rules (ct_contract, default off) that keep every + named object, pose and setting in the picture. Runs at the end of parse(), before imagine.post.""" + toks = _toks(scene.get("text", "")) + tset = set(toks) + ents = scene.get("entities", []) + from .actions import _locate + pos = _locate(toks, ents) if ents else [] + # ---- plain fixes (default on) + if ct("ct_boat"): + # copy_scene G13: "a fisherman in a small boat" is a rowing boat (low, long, no sail); a generic boat drew a sailboat + # in 12/12 renders. Size words and the boat's crew decide; any sail word keeps the sailboat. + for k, e in enumerate(ents): + if e["concept"] != "boat" or (e.get("word") or "boat").split()[-1] not in ("boat", "boats") or tset & SAIL_WORDS: + continue + near = toks[max(0, (pos[k] or 0) - 3):(pos[k] or 0)] + if e.get("size", 1.0) < 1.0 or set(near) & {"small", "little", "tiny", "wooden", "old"} or tset & ROW_CONTEXT: + e["word"] = "rowboat" if e.get("count", 1) == 1 else "rowboats" + trace.append("content: small / crewed boat -> rowing boat (no sail)") + if ct("ct_color"): + # a green valley / meadow / hill is green: the variation layer may not turn it into autumn or winter (vary pins the + # season when the trace says "season=") + sc = scene.get("setting_colors") or {} + if any(sc.get(w) in ("green", "lime", "forestgreen") for w in ("valley", "meadow", "meadows", "hills", "hill", "field", + "fields", "grass", "mountains", "forest", "park")) \ + and not scene.get("season"): + trace.append("content: green ground named -> season= kept (no varied autumn / winter)") + if ct("ct_door"): + # copy_room A12: "a living room with grey walls and a white door": the room's own walls are its walls (a colour of the + # setting), not a free-standing garden wall carrying the door as a feature (the door became a beige brick slab) + rels = scene.get("relations", []) + INDOOR = {"room", "bedroom", "kitchen", "office", "bathroom", "library", "cafe", "classroom", "studio", "restaurant"} + for k in range(len(ents) - 1, -1, -1): + e = ents[k] + if e["concept"] != "wall" or scene.get("place") not in INDOOR or any(k in (a, b) for a, _, b in rels): + continue + if e.get("color"): + scene.setdefault("setting_colors", {})["walls"] = e["color"] + door = ((e.get("attrs") or {}).get("parts") or {}).get("door") + del ents[k] + scene["relations"] = rels = [(a - (a > k), r, b - (b > k)) for a, r, b in rels] + if door: + col = door if isinstance(door, str) and door in _colors_known() else None + ents.append({"concept": "door", "word": "door", "count": 1, "color": col, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "color_explicit": bool(col)}) + trace.append("content: the room's walls are the setting (%s)%s" % (e.get("color") or "-", ", the door is an object" if door else "")) + pos = _locate(toks, ents) if ents else [] + if ct("ct_words"): + # things 11:08: "a lamp on the bedside table" drew a dining table laid with plates ("bedside" unknown): a bedside / side / + # end table is a small cabinet beside the bed (the wardrobe concept, cabinet-sized) + for k, e in enumerate(ents): + if e["concept"] == "dining table" and pos and pos[k] is not None and pos[k] > 0 \ + and toks[pos[k] - 1] in ("bedside", "side", "end", "night"): + e.update(concept="wardrobe", word="nightstand", size=min(e.get("size", 1.0), .42)) + if "bedside" in (scene.get("unknown") or []): + scene["unknown"].remove("bedside") + trace.append("content: '%s table' -> a nightstand (small cabinet), not a dining table" % toks[pos[k] - 1]) + # copy_room G4 / A03: words the parser left unknown that carry meaning: recorded on the scene for the renderers + unk = scene.get("unknown") or [] + known = [] + if "empty" in unk: + scene["empty"] = True # = no dressing beyond what is named + known.append("empty") + if "through" in unk: + k_ = toks.index("through") + nxt = [t for t in toks[k_ + 1:k_ + 4] if t not in ("a", "an", "the")] + if nxt: + scene["light_through"] = nxt[0] # "moonlight through a window": the light enters by the window (the pool) + known.append("through") + if "calm" in unk or "still" in unk: + scene["calm"] = True # calm / still water: a mirror, no waves + known += [w for w in ("calm", "still") if w in unk] + if "after" in unk and re.search(r"\bafter (the |a )?(rain|storm|shower|rainstorm)\b", " ".join(toks)): + scene["after_rain"] = True # the rain has stopped: wet ground, clearing sky, no falling rain + known.append("after") + if "lit" in unk: + known.append("lit") + if "dim" in unk: + scene["dim"] = True # a dim room: low key (plan lane's light key) + known.append("dim") + if known: + scene["unknown"] = [u for u in unk if u not in known] + trace.append("content: known words %s" % ", ".join(known)) + if not ct("ct_contract"): + return scene + # ---- contract rules (ct_contract, default off) + if ct("ct_lit"): + jt = " ".join(toks) + for k, e in enumerate(ents): + c, w = e["concept"], (e.get("word") or e["concept"]) + lit = False + if c == "lighthouse" and (scene.get("weather") in ("rain", "fog") or tset & {"storm", "stormy", "night", "dusk"}): + lit = True # a lighthouse in a storm has its lamp on (w16_52 unlit) + if c in LIGHT_EMITTERS and re.search(r"\blit by (a |an |the )?([a-z]+ )?%s\b" % re.escape(w.split()[-1]), jt): + lit = True # "lit by a bedside lamp": the lamp is the light + if lit: + e.setdefault("attrs", {})["lit"] = True + trace.append("content: %s is lit (the prompt's light)" % c) + if ct("ct_key"): + for place, (key, kinds) in PLACE_KEY.items(): + if not (tset & PLACE_KEY_WORDS[place]) or any(e["concept"] in kinds for e in ents): + continue + from .registry import CONCEPTS as _C + if key not in _C: + continue + ents.append({"concept": key, "word": key.split()[-1], "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, + "facing": None, "color_explicit": False, "implied": "contract"}) + trace.append("content: '%s' implies a %s (key object of the place)" % (place, key)) + if ct("ct_places"): + # copy_land L15: "mountains ... pine forest": the last place word won and the mountains vanished (13/15 renders) + if tset & {"mountains", "mountain", "peaks", "alps"} and scene.get("place") in ("forest", "field", "water") \ + and not (len(tset & {"mountain"}) and not tset & {"mountains", "peaks", "alps"} and "lake" not in tset + and scene.get("place") != "forest"): + was = scene["place"] + scene["place"] = "mountains" + if was == "forest" and not any(e["concept"] in ("tree", "pine", "oak tree", "palm tree", "birch") for e in ents): + ents.append({"concept": "pine", "word": "pine trees", "count": 4, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "color_explicit": False, "implied": "contract"}) + trace.append("content: mountains named with a %s -> place mountains, the %s kept as trees / water" % (was, was)) + if ct("ct_rainbow") and "rainbow" in (scene.get("features") or []): + # nature S4: the sun is behind the viewer for a rainbow; "after the rain" = the rain has stopped + scene["sun_out_of_frame"] = True + if scene.get("after_rain") and scene.get("weather") == "rain": + scene["weather"] = None + trace.append("content: rainbow -> sun behind the viewer (out of frame)%s" % (", rain stopped" if scene.get("after_rain") else "")) + if scene.get("time") == "day": + trace.append("content: rainbow -> setting time=day (pinned: a rainbow needs the sun, no invented sunset)") + return scene diff --git a/pydraw/layout.py b/pydraw/layout.py index b13a7da2b28ec21f90ad27798f124e8051abf4f2..355a6227059b9dd9de5f24ffa8a089485af72049 100644 --- a/pydraw/layout.py +++ b/pydraw/layout.py @@ -2,6 +2,7 @@ import re import math, os, random from .registry import CONCEPTS +from .contact import on as _cx_on, size_held as _cx_size, keep_ratio as _cx_keep from .scenes import HORIZON RANK = {"front": 0, "mid": 1, "back": 2} @@ -22,6 +23,20 @@ class Inst: _E0 = dict(kv.split("=") for kv in __import__("os").environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) +# rule: head anchors per concept: (x toward the face as fraction of width, head-top height as fraction of box) +HEAD_ANCHOR = {"frog": (.15, .8), "bear": (.38, .62), "pig": (.4, .72), "sheep": (.4, .82), "cow": (.42, .85), "horse": (.42, .98), "elephant": (.38, .9), "lion": (.38, .85), "tiger": (.4, .75), "fox": (.36, .8), "wolf": (.38, .82), "rabbit": (.2, 1.0), "duck": (.3, .95), "chicken": (.3, .95), "turtle": (.42, .55), "penguin": (.05, 1.0), "owl": (0, 1.0), "monkey": (.15, 1.0), "teddy bear": (0, 1.0), "giraffe": (.4, 1.0), "zebra": (.42, .95), "deer": (.4, .9), "camel": (.42, .9), "kangaroo": (.2, 1.0), "panda": (0, 1.0), "koala": (0, 1.0), "squirrel": (.2, 1.0), "snowman": (0, 1.0), "robot": (0, 1.0), "alien": (0, 1.0), "dinosaur": (.38, 1.0), "unicorn": (.42, .98), "gorilla": (.35, .85), "cat": (.36, .98), "dog": (.38, .98)} + +def _c2bird_grounded(scene, it): + """wave 20 bird lane (animal-086): pydraw/creature2d/bird.grounded; False unless PYDRAW_EXP c2d=1""" + if _E0.get("c2d", "0") == "0": + return False + try: + from .creature2d.bird import grounded + return grounded(scene, it) + except Exception: + return False + + def choose_place(scene, trace): if scene["place"]: return scene["place"] @@ -36,7 +51,8 @@ def choose_place(scene, trace): 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) + _E0.get("restfly", "1") != "0" and any(e.get("pose") in _rest for e in ents)) \ + and not any(_c2bird_grounded(scene, e) for e in ents): # wave 20 bird (animal-086): a bird on the ground # (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") @@ -91,6 +107,7 @@ ROOMS = tuple(sorted(set(_INDOOR) - {"table", "studio"})) def layout(scene, W, H, rng, trace): focal = float(H) + scene.setdefault("_place_named", bool(scene.get("place"))) # wave 19 (thumbs): did the prompt name the setting? 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"] @@ -110,7 +127,8 @@ def layout(scene, W, H, rng, trace): from .surface import mark as _surface_mark # night (scene): "a cracked rock" -> entity surface state from .stage import pre as _stage_pre # night (scene): "a knight facing a dragon" -> turned toward from .toyscale import pre as _toy_pre # wave 16 form: toy blocks beside a toddler stay toy-sized - for _f in (_attach_rel, _surface_mark, _stage_pre, _toy_pre): + from .contact import pre as _contact_pre # wave 20 (contact): verbs -> contacts (knobs cx_*, default OFF) + for _f in (_attach_rel, _surface_mark, _stage_pre, _toy_pre, _contact_pre): try: _f(scene, trace) except Exception as _ex: # a staging rule must never take the picture down @@ -180,6 +198,11 @@ def layout(scene, W, H, rng, trace): y0 = H * .78 if not insts: trace.append("layout: no drawable entities -> empty setting") + try: # wave 19 (compose, cmp_horizon): the horizon of an empty landscape leaves the middle + from .thumbs import empty_horizon as _eh + y0 = _eh(scene, H, y0, trace) + except Exception as _ex: + trace.append("layout: thumbs skipped (%s)" % str(_ex)[:80]) return [], y0 first = {} for it in insts: @@ -287,6 +310,10 @@ def layout(scene, W, H, rng, trace): pinned |= {o for s, rel, o in rels if rel == "above" and not CONCEPTS[scene["entities"][o]["concept"]]["flying"]} # rule: the thing below stays grounded (unless it lives in the sky, like the moon) for it in insts: if it.info["flying"] and it.ent not in pinned and it.pose not in ("perched", "sitting", "standing", "sleeping", "one_leg", "swimming", "grazing", "walking", "lying"): + if it.pose is None and _c2bird_grounded(scene, it): + it.pose = "standing" # wave 20 (bird, animal-086, knob c2d_bird_ground): a bird flies only when told + trace.append("layout: %s stands (the prompt does not say it flies)" % it.concept) + continue it.pose = "flying" for it in insts: if it.pose in ("running", "sleeping", "lying", "jumping", "walking"): @@ -354,6 +381,8 @@ def layout(scene, W, H, rng, trace): ratio = it.world_h * _wf / href if getattr(it, "riding", False) or any(getattr(o, "riding", False) and o.bound is it for o in insts): continue # rule: riders and their mounts keep real proportions + if _cx_keep(it, ref): + continue # wave 20 (contact, cx_ratio; persp-033): people and animals keep their true size ratio if it.implicit: continue # rule: an added table keeps furniture scale if (getattr(it, "attrs", None) or {}).get("fixed_scale"): @@ -730,6 +759,7 @@ def layout(scene, W, H, rng, trace): trace.append("layout: %s sits on %s at y=%.0f" % (it.concept, it.bound.concept, it.y)) elif it.rel in ("behind", "in_front_of") and it.bound is not None and hasattr(it.bound, "x"): b = it.bound + _x0 = it.x # wave 20 (contact, cx_follow; phys-001): the rider / held thing moves with its host below sib = [o for o in ground if o.bound is b and o.rel == it.rel] if (it.attrs or {}).get("toy"): # (wave 16 form, toyscale) toy blocks: a row on the floor beside the child's knees j = sib.index(it) @@ -740,6 +770,12 @@ def layout(scene, W, H, rng, trace): it.x = b.x - span / 2 + (j + .5) * span / len(sib) else: it.x = b.x + (b.w * .3 + it.w * .25) * (1 if it.k % 2 == 0 else -1) + if _E.get("cx_follow", "1") != "0" and abs(it.x - _x0) > 1e-6: + n_ = move_subtree(it, insts, it.x - _x0, 0.0) + if n_: + trace.append("layout: %s moved %s its host; %d carried thing(s) moved with it" % (it.concept, it.rel.replace("_", " "), n_)) + if _E.get("cx_follow", "1") != "0": + record_seats(insts) for s, rel, o in order: A = [it for it in insts if it.ent == s and hasattr(it, "x")] B = [it for it in insts if it.ent == o and hasattr(it, "x")] @@ -862,6 +898,8 @@ def layout(scene, W, H, rng, trace): else: it.h = max(H * .07, min(hold.h * .45, hold.h * it.info["height"] / max(.3, hold.info["height"]) * 1.5)) it.w = it.h * it.info["aspect"] + if _cx_on("cx_hold"): + _cx_size(it, hold, H, trace) # wave 20 (contact, phys-023): true size against the hand it.x = hold.x + side * (hold.w * .5 + it.w * .3) it.y = hold.y - hold.h * .38 + it.h * .5 it.bound, it.rel, it.d = hold, "on", hold.d @@ -881,14 +919,7 @@ def layout(scene, W, H, rng, trace): person = w8.concept == "person" it.h = max(H * .04, w8.h * (sp if person else sa)) it.w = it.h * it.info["aspect"] - # rule: head anchors per concept: (x toward the face as fraction of width, head-top height as fraction of box) - HEAD = {"frog": (.15, .8), "bear": (.38, .62), "pig": (.4, .72), "sheep": (.4, .82), "cow": (.42, .85), - "horse": (.42, .98), "elephant": (.38, .9), "lion": (.38, .85), "tiger": (.4, .75), "fox": (.36, .8), - "wolf": (.38, .82), "rabbit": (.2, 1.0), "duck": (.3, .95), "chicken": (.3, .95), "turtle": (.42, .55), - "penguin": (.05, 1.0), "owl": (0, 1.0), "monkey": (.15, 1.0), "teddy bear": (0, 1.0), "giraffe": (.4, 1.0), - "zebra": (.42, .95), "deer": (.4, .9), "camel": (.42, .9), "kangaroo": (.2, 1.0), "panda": (0, 1.0), - "koala": (0, 1.0), "squirrel": (.2, 1.0), "snowman": (0, 1.0), "robot": (0, 1.0), "alien": (0, 1.0), - "dinosaur": (.38, 1.0), "unicorn": (.42, .98), "gorilla": (.35, .85), "cat": (.36, .98), "dog": (.38, .98)} + HEAD = HEAD_ANCHOR # rule: head anchors per concept (module level, shared with pydraw/contact.py) CHILD = {"child", "kid", "boy", "girl", "children", "kids", "boys", "girls", "schoolboy", "schoolgirl", "toddler"} hxf, htf = HEAD.get(w8.concept, (.36, .98)) if person: @@ -950,7 +981,11 @@ def layout(scene, W, H, rng, trace): # rule: something resting on a flying thing travels with it (drawn just above it) for it in insts: if not hasattr(it, "x") and it.bound is not None and hasattr(it.bound, "x") and it.bound.pose == "flying": - it.pose, it.rel = "flying", "above" + # wave 19 (content, ct_restpose): a sleeping / sitting / lying animal on a wall-hung thing (a windowsill) keeps its + # rest pose; "flying" only means it is placed with its host, not on the ground (w16_4, w16_26 stood up) + _rest = getattr(it, "pose", None) in ("sleeping", "sitting", "lying", "perched") and getattr(it.bound, "wall_hung", False) \ + and os.environ.get("PYDRAW_EXP", "").find("ct_restpose=0") < 0 + it.pose, it.rel = (it.pose if _rest else "flying"), "above" if it.h > it.bound.h * .75: # rule: a thing sitting on a hung/flying thing is scaled to fit it k = it.bound.h * .75 / it.h it.h *= k @@ -988,6 +1023,11 @@ def layout(scene, W, H, rng, trace): trace.append("layout: close-up framing (subject h=%.0f)" % it.h) from .characters import frame as _char_frame # wave 12: a lone character is the subject (big enough for its face) _char_frame(scene, insts, W, H, trace) + try: # wave 20 (contact): interaction contacts - hand targets, seats, lines (knobs cx_*, default OFF) + from .contact import post as _contact_post + _contact_post(insts, scene, W, H, y0, trace) + except Exception as _ex: + trace.append("layout: contact skipped (%s)" % str(_ex)[:80]) for it in ground: it.haze = max(0, min(.5, (it.d / (d_s * 6)) ** 1.2 * .5)) if place not in tuple(_INDOOR) + ("space", "underwater") else 0 for it in insts: # rule: absolute sides ("a dog on the left") @@ -1069,11 +1109,79 @@ def layout(scene, W, H, rng, trace): y0 = _direct(insts, scene, W, H, y0, trace) except Exception as _ex: trace.append("layout: director skipped (%s)" % str(_ex)[:80]) + try: # wave 19 (compose): thumbnail search over camera moves, horizon / placement / tangent rules (pydraw/thumbs.py) + from . import thumbs as _thumbs + y0 = _thumbs.search(insts, scene, W, H, y0, trace) + trace.append(_thumbs.geom_line(insts, scene, W, H, y0)) + except Exception as _ex: + trace.append("layout: thumbs skipped (%s)" % str(_ex)[:80]) + if _E.get("cx_follow", "1") != "0": + reseat(insts, trace) + from .contact import finalize as _cx_final # wave 20 (contact): hand targets follow the framing moves (knobs cx_*) + _cx_final(insts, trace) for it in insts: trace.append("layout: %r" % it) return insts, y0 +# ---- wave 20 (contact): the support tree (phys-001, persp-020). A thing seated on / riding / resting on a host is a +# child in a tree; any later move of the host carries the whole subtree, and the end of layout re-seats a child whose +# host was moved without it (the knight left floating beside the horse that "in front of a castle" moved 280 px). +CARRIED = ("on", "above") + + +def children(host, insts): + return [o for o in insts if getattr(o, "bound", None) is host and o.rel in CARRIED and o is not host] + + +def move_subtree(host, insts, dx, dy, seen=None): + """move every thing carried by host (recursively) by dx, dy; returns how many moved""" + seen = seen if seen is not None else {id(host)} + n = 0 + for o in children(host, insts): + if id(o) in seen or not hasattr(o, "x"): + continue + seen.add(id(o)) + o.x += dx + o.y += dy + n += 1 + move_subtree(o, insts, dx, dy, seen) + return n + + +def record_seats(insts): + """remember where each carried thing sits on its host, in host-height units (after the seating pass), and where the + thing itself was then (so a later deliberate placement of the child - a perch limb, an attach rule - is respected)""" + for o in insts: + b = getattr(o, "bound", None) + if b is None or o.rel != "on" or not hasattr(o, "x") or not hasattr(b, "x") or getattr(o, "attach_kind", None) \ + or getattr(o, "held_by", None) is not None or getattr(o, "worn_by", None) is not None or b.pose == "flying": + continue + hh = max(1e-6, b.h) + o._seat_at = (b, (o.x - b.x) / hh, (o.y - b.y) / hh, o.h / hh, b.facing, (o.x, o.y, o.h)) + + +def reseat(insts, trace, tol=1.5): + """end of layout: a carried thing left behind by its host (moved or clamped differently) goes back on its seat. + Only the position follows the host; the thing keeps its own size (a perched owl is never scaled with its branch). + A host re-laid to fit the thing (perch limb, attach rule) is left as that rule made it.""" + for o in insts: + sa = getattr(o, "_seat_at", None) + if sa is None or getattr(o, "bound", None) is not sa[0] or o.rel != "on": + continue + b, fx, fy, fh, bf, (ox0, oy0, oh0) = sa + if getattr(b, "perch", False) or getattr(o, "perch", False) or getattr(o, "attach_kind", None) \ + or getattr(b, "attach_kind", None): + continue # the host was re-laid to fit the thing (a perch limb drawn under the owl, an attach rule): keep it + mirror = -1 if (bf in ("left", "right") and b.facing in ("left", "right") and bf != b.facing) else 1 + wx, wy = b.x + mirror * fx * b.h, b.y + fy * b.h + if abs(o.x - wx) <= tol and abs(o.y - wy) <= tol: + continue + dx, dy = wx - o.x, wy - o.y + o.x, o.y = wx, wy + move_subtree(o, insts, dx, dy) + trace.append("layout: %s re-seated on its host %s (moved %.0f,%.0f px, own size kept)" % (o.concept, b.concept, dx, dy)) + + def project(it, focal, cam, y0): it.h = focal * it.world_h / it.d it.w = it.h * it.info["aspect"] diff --git a/pydraw/media_ink.py b/pydraw/media_ink.py index 4e8f2aa978baf5395397de2e71535b5d7be8b553..da3fc426cbe5606fc5f1c4b807de1c977ad8bfb8 100644 --- a/pydraw/media_ink.py +++ b/pydraw/media_ink.py @@ -2,22 +2,32 @@ pydraw/inkmedia/ (lines.py contours, hatch.py form hatching + ground marks, ink.py the media). Knobs (PYDRAW_EXP): media_=0 turns one medium off (back to the old styles.py filter); ink_w (line weight), ink_sp (hatch spacing), ink_spot, ink_ground, wash, flat_line=1 (coloured outlines on flat), flat_k, lino_sp, lino_color=0 (black only).""" +import numpy as np from . import gbuf from .inkmedia import adapt, ink as _ink +def _md(name): + return gbuf._EXP.get(name, "0") != "0" + + def _wrap(fn, name): def paint(G, seed, trace): gb = adapt.from_gbuf(G) - if name == "flat" and gbuf.on16("flat2"): # wave 16 plan lane: illustration.md rule 13 + if name == "flat" and (gbuf.on16("flat2") or _md("md_flat")): # wave 16 plan lane: illustration.md rule 13 from .inkmedia.flat2 import render_flat2 trace.append("ink: flat painted as shapes + 5 hue families + Multiply shadow (rule 13)") - return render_flat2(gb, seed, gbuf._EXP) + out = render_flat2(gb, seed, gbuf._EXP) + if _md("md_flat"): + # (wave 19 media, md_flat; media.md F1) quantise LAST: soft region edges and the Multiply shadow blend + # left n95 39-140; flat vector is 3-5 key colours plus tints (n95 <= 16) + from . import ramps + out = ramps.cap(np.asarray(out, np.float32), int(float(gbuf._EXP.get("md_flatn", 16))), trace) + return out out = fn(gb, seed, gbuf._EXP) trace.append("ink: %s painted from the G-buffer" % name) if name in ("ink", "comicink", "manga", "lineart") and gbuf.on16("ink_wx"): # wave 16 (critic8 16:30: comic / manga drop the storm): the scene's rain / snow survives as ink marks - import numpy as np from .paint.common import weather out = weather(np.asarray(out, np.float32), G, mono=(22, 20, 24)) return out @@ -43,6 +53,19 @@ MEDIA = { # art "inkwash" (sumi e, ink painting, chinese ink, brush painting, shan shui, guohua) resolves to this by name "inkwash": (_ink.render_sumie, ("sumi e", "sumie", "ink painting", "chinese ink painting", "brush and ink", "shan shui")), } -OFF_BY_DEFAULT = {"flat"} # critic7 19:45: flat reads below the old smooth render's floor - on with media_flat=1 +def _woodblock(gb, seed, knobs): + from .inkmedia.woodblock import render_woodblock + return render_woodblock(gb, seed, knobs) + + +# wave 19 media (md_wood; R18): "woodblock" parsed to the ukiyoe pixel filter (a dithered pixel picture); it gets its own +# renderer. "woodcut" stays linocut (a black-and-white relief print). +MEDIA["woodblock"] = (_woodblock, ("woodblock", "woodblock print", "japanese woodblock", "japanese woodblock print", + "ukiyo e", "ukiyoe", "ukiyo", "japanese print", "hiroshige", "hokusai", "moku hanga")) +OFF_BY_DEFAULT = {"flat", "woodblock"} # critic7 19:45: flat reads below the old smooth render's floor - on with media_flat=1 +if _md("md_flat"): + OFF_BY_DEFAULT.discard("flat") # (wave 19 media, md_flat; R18 routing) "flat vector" reaches the flat renderer +if _md("md_wood"): + OFF_BY_DEFAULT.discard("woodblock") for _name, (_fn, _ph) in MEDIA.items(): gbuf.register(_name, phrases=_ph, default=_name not in OFF_BY_DEFAULT)(_wrap(_fn, _name)) diff --git a/pydraw/nature.py b/pydraw/nature.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb10a48b7fc7c322fd4506207a4642c9816458f --- /dev/null +++ b/pydraw/nature.py @@ -0,0 +1,754 @@ +"""Nature lane (wave 19, rule R15 of docs/research19/SYNTHESIS.md): landscape subjects drawn the way landscape +painters simplify them. Every behaviour has its own knob, default OFF until the lead turns it on: +PYDRAW_EXP nt_ridge=1 turns one on, nature=0 turns the whole lane off. + +nt_ridge mountains are designed ranges, not a comb of equal teeth (nature.md M1, V4; copy_land L1, L5, L8, L13; + compute R6): 2-3 ranges in stepped depth (far within ~10 L* of the sky, each nearer range darker and more + contrasted), ONE dominant peak 1.3-2x the next on a third, irregular gaps (CV >= .35), asymmetric slopes, + an fBm ridge, a lit and a shadow face split on a wandering spine, gully / rib planes running down the + slope, snow above one world altitude with a jagged line and fingers down the gullies (blue in shadow), and + mist at the base of every range. A low dark forested foothill band reserves the near dark. +nt_cloud a fair-weather sky in perspective: one base altitude, size and h/w by height above the horizon, 1 big + + 2-3 medium + 3-5 small far clouds (nature.md S2, copy_land L9, compute R5) - skies.paint_clouds. +nt_clump oak / apple crowns as 4-6 clumps on limbs with sky holes and three values (nature.md T1-T2, compute R6) + - concepts/core.draw_tree. +nt_water reflections: light things mirror darker, dark things lighter (nature.md W1-W2) - world.reflect. +nt_pine conifers as 5-8 uneven drooping tiers with a spire, a dark shelf under each tier, snow on every tier (T3, N1) + - concepts/core.draw_pine. +nt_surf a storm coast: dark rock blocks under the subject, surf and spray as the light group (W6, V3) - + skies.plan. +nt_treeline far-shore trees as 1-3 scalloped group masses with gaps, lit caps and a dark base (T4) - world.shore_trees. + +Sources for every range of numbers are cited at the constant that uses them. +""" +import math +import os + +import numpy as np + +_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + +DEFAULTS = {"nt_ridge": "0", "nt_cloud": "0", "nt_clump": "0", "nt_water": "0", "nt_pine": "0", "nt_treeline": "0", "nt_surf": "0"} # the lead flips a knob to "1" here once numbers and a look say better + + +def on(name): + if _EXP.get("nature", "1") == "0": + return False + return _EXP.get(name, DEFAULTS.get(name, "0")) not in ("0", "") + + +# ------------------------------------------------------------------ small helpers +def _mix(a, b, t): + a, b = np.asarray(a, float), np.asarray(b, float) + return a + (b - a) * np.clip(t, 0, 1) + + +def _noise1(x, seed): + """smooth 1D value noise (x float array), 0..1""" + i = np.floor(x).astype(np.int64) + f = x - i + f = f * f * (3 - 2 * f) + + def h(a): + n = (a * 374761393 + seed * 668265263) & 0xFFFFFFFF + n = ((n ^ (n >> 13)) * 1274126177) & 0xFFFFFFFF + return (n & 0xFFFF) / 65535.0 + return h(i) + (h(i + 1) - h(i)) * f + + +def _fbm1(x, seed, oct=5, H=.7): + """1D fBm with Hurst exponent H (nature.md M1: midpoint displacement / fBm, H 0.6-0.8, 4-6 octaves)""" + t, amp, tot = 0.0, 1.0, 0.0 + for o in range(oct): + t = t + (_noise1(x * 2 ** o, seed + 31 * o) - .5) * amp + tot += amp + amp *= 2 ** -H + return t / tot # about -0.5..0.5 + + +def _gaps(rng, n, cv_min=.35): + """n irregular positive gaps (normalised to sum 1) whose coefficient of variation is at least cv_min + (nature.md rule 4 / M1: gap CV >= 0.35; copy_land L8: references 0.45 and 0.58)""" + best = None + for _ in range(40): + g = np.array([rng.lognormvariate(0, .55) for _ in range(n)]) + cv = g.std() / g.mean() + if best is None or cv > best[0]: + best = (cv, g) + if cv >= cv_min: + break + g = best[1] + return g / g.sum() + + +def _paint(cv, mask, C, y_off=0): + """write colours C (h, w, 3) where mask (h, w) is set, into rows y_off.. of the canvas backdrop (ids stay 0)""" + ys, xs = np.nonzero(mask) + if not len(ys): + return + vals = C[ys, xs].tolist() + lay = cv.layer + cl = cv.cur_layer + px = cv.px + for y, x, c in zip((ys + y_off).tolist(), xs.tolist(), vals): + p = px[y][x] + p[0], p[1], p[2] = c + if lay is not None: + lay[y, x] = cl + + +def _rgb_L(c): + """CIELAB L* of an sRGB triple (for keeping value steps honest)""" + c = np.asarray(c, float) / 255.0 + c = np.where(c > .04045, ((c + .055) / 1.055) ** 2.4, c / 12.92) + Y = .2126 * c[..., 0] + .7152 * c[..., 1] + .0722 * c[..., 2] + return np.where(Y > .008856, 116 * np.cbrt(Y) - 16, 903.3 * Y) + + +# ------------------------------------------------------------------ nt_ridge: designed mountain ranges +def _peaks(rng, W, n, x_dom, h_dom, ratio): + """peak list [(x, height)] for one range: the dominant one at x_dom, the others placed with irregular gaps on + both sides, each at most h_dom / ratio (nature.md M1: dominant 1.3-2x the next; copy_land L8: 1.15-1.5x)""" + out = [(x_dom, h_dom)] + span_l, span_r = x_dom + W * .15, W * 1.15 - x_dom + nl = max(1, int(round((n - 1) * span_l / (span_l + span_r)))) + nr = max(1, n - 1 - nl) + for side, m, span in ((-1, nl, span_l), (1, nr, span_r)): + g = _gaps(rng, m + 1) + x = x_dom + for k in range(m): + x += side * span * g[k] * rng.uniform(.8, 1.0) + # the first neighbour is the runner-up at exactly h_dom / ratio; the rest lower and varied + out.append((x, h_dom / ratio * (1.0 if (k == 0 and side < 0) else rng.uniform(.55, .95)))) + return out + + +def _range_masks(W, top, rng, peaks, slope_lo, slope_hi, rough, seed): + """silhouette per cone (front-most wins): returns owner (H, W) int (-1 = none), cones list with geometry""" + ys = np.arange(top.shape[0], dtype=float)[:, None] + .5 + xs = np.arange(W, dtype=float)[None, :] + .5 + owner = np.full((top.shape[0], W), -1, int) + cones = [] + # the tallest peak is furthest back; smaller spurs stand in front of its base and overlap it (nature.md M1: + # ranges overlap; copy_land L8: at least one overlap, the middle peak sits behind the big one) + order = sorted(range(len(peaks)), key=lambda i: -peaks[i][1]) + for rank, i in enumerate(order): + px_, h = peaks[i] + py = top.base - h + # asymmetric slopes (nature.md M1: one side 25-40 deg, the other 40-60 deg; painters steepen them: dy/dx .55-1.4) + sl, sr = rng.uniform(*slope_lo), rng.uniform(*slope_hi) + if rng.random() < .5: + sl, sr = sr, sl + sil = py + np.where(xs < px_, (px_ - xs) * sl, (xs - px_) * sr) + # rule: the ridge is fBm over the designed envelope (amplitude scales with the peak, M1) + sil = sil + _fbm1(xs[0] / (W * .09), seed + i * 13)[None, :] * rough * h * 2 + m = ys >= sil + owner[m] = i # later (smaller, nearer) cones overwrite + skew = rng.uniform(-.3, .3) + (.18 if sl > sr else -.18) # the spine runs down toward the gentler side + cones.append(dict(i=i, x=px_, y=py, h=h, sl=sl, sr=sr, skew=skew, rank=rank)) + return owner, {c["i"]: c for c in cones} + + +class _Top: + def __init__(self, base, n): + self.base, self.shape = base, (n,) + + +def ranges(cv, ctx, scene, rng, trace, snowy=False, lake=False): + """nt_ridge: paint the mountain ranges between the sky and the ground (replaces scenes.mountains' comb loop). + Returns True when it drew (the caller then skips its old loop).""" + from .scenes import sky_colors, sky_at, _dawn + W, H, y0 = cv.w, cv.h, int(ctx.y0) + if y0 < H * .25: + return False + sx, sy = ctx.sun + t = scene["time"] + night, sunset = t == "night", t == "sunset" + dawn = sunset and _dawn(scene) + sun_right = sx >= W / 2 + top_c, hor_c = sky_colors(scene) + hz = np.asarray(ctx.haze_color if getattr(ctx, "haze_color", None) is not None else hor_c, float) + G = ctx.L.ground + import zlib + seed = (rng.randint(0, 99999) + zlib.crc32((scene.get("text") or "").encode())) % 99991 + base = y0 + 2 + rows = base + 1 + # --- the design: where the dominant peak stands and how tall (on a third, never the centre: nature.md M1 + # .25-.4 / .6-.75 W; C1 steelyard). Height: .26-.38 H above the base, clear of the frame top by >= 8% H (C2). + left = rng.random() < .5 + if sunset and 0 <= sx < W and sy > y0 - H * .4: + left = sx > W / 2 # a low sun in frame keeps its gap: the dominant peak stands on the other third (V3, C1) + x_dom = W * (rng.uniform(.26, .4) if left else rng.uniform(.6, .74)) + h_dom = min(H * rng.uniform(.26, .38), base - H * .08) + # --- palette by light family. day: rock, lit and shadow faces (Carlson slant planes: lit face +1 step, shadow + # -1 step; nature.md V1); sunset/dawn: backlit ranges become silhouettes stepping toward the glow (V3); + # night: dark violet silhouettes, the moon side barely lit (V3 night table: ground 12-28 L*) + if night: + rock_l, rock_s = np.array([40, 40, 66.]), np.array([24, 22, 42.]) + snow_l, snow_s = np.array([200, 212, 250.]), np.array([118, 128, 180.]) # after the night ground tint: L* 35-55 (V3) + fol = np.array([14, 20, 26.]) + elif sunset and not dawn: + rock_l, rock_s = np.array([150, 96, 120.]), np.array([96, 62, 104.]) + snow_l, snow_s = np.array([255, 206, 178.]), np.array([170, 140, 184.]) + fol = np.array([40, 32, 54.]) + elif dawn: + rock_l, rock_s = np.array([132, 108, 136.]), np.array([84, 76, 120.]) + snow_l, snow_s = np.array([255, 232, 222.]), np.array([142, 138, 190.]) # shadowed snow stays a mid value + fol = np.array([52, 58, 80.]) + else: + rock_l, rock_s = np.array([132, 124, 140.]), np.array([84, 82, 112.]) + snow_l = np.array([250, 251, 255.]) + snow_s = _mix(top_c, (226, 234, 248), .45) # snow in shadow is the colour of the sky (nature.md M1, N1) + fol = np.array([44, 78, 56.]) + fol_snow = None + # a colour the prompt gave the mountains ("green mountains"; content lane's scene["setting_colors"]) is their + # local colour; the plan keeps owning the value: lit / shadow faces keep their light-family brightness + named = (scene.get("setting_colors") or {}).get("mountains") or (scene.get("setting_colors") or {}).get("mountain") + if named: + from .understanding import COLORS + nc = COLORS.get(named) if isinstance(named, str) else named + if nc is not None: + nc = np.asarray(nc, float) + for nm in ("rock_l", "rock_s"): + c = locals()[nm] + c2 = nc * (_rgb_L(c) / max(1.0, float(_rgb_L(nc)))) + if nm == "rock_l": + rock_l = _mix(c, c2, .75) + else: + rock_s = _mix(c, c2, .75) + if snowy: + # trees in snow stay dark masses with white on their upper edges (nature.md N1; Hiroshige snow prints) + fol = np.array([30, 52, 50.]) if not night else np.array([12, 18, 28.]) + fol_snow = np.array([236, 242, 252.]) if not night else np.array([120, 132, 176.]) + # --- three planes (nature.md V4: each plane back moves 30-40% of the remaining way to the sky colour; + # copy_land L1: far = sky +-12 L*, near 25-40 L* darker): haze share, peak count, roughness, snow, contrast + planes = [dict(a=.62, n=rng.randint(5, 7), hmul=rng.uniform(.55, .72), rough=.05, ratio=rng.uniform(1.0, 1.25), + xd=rng.uniform(.1, .9) * W, ribs=0), + dict(a=.2, n=rng.randint(3, 5), hmul=1.0, rough=.07, ratio=rng.uniform(1.4, 1.9), xd=x_dom, ribs=3)] + drawn = 0 + snow_alt = None + for k, P in enumerate(planes): + hd = h_dom * P["hmul"] + peaks = _peaks(rng, W, P["n"], P["xd"], hd, P["ratio"]) + owner, cones = _range_masks(W, _Top(base, rows), rng, peaks, (.55, .85), (.9, 1.4), P["rough"], seed + 101 * k) + if snow_alt is None or k == 1: + # rule: snow lies above ONE world altitude (not a cap per peak): big peaks carry big fields, small ones + # none; on the dominant it covers the top 22-35% (nature.md M1: top 15-35%); snowy scenes go lower + snow_alt = h_dom * (1 - (rng.uniform(.4, .55) if snowy else rng.uniform(.22, .35))) + ys = np.arange(rows, dtype=float)[:, None] + .5 + xs = np.arange(W, dtype=float)[None, :] + .5 + face_lit = np.zeros((rows, W), bool) + gully = np.zeros((rows, W), bool) + rib = np.zeros((rows, W), bool) + front = np.zeros((rows, W), float) + for i, c in cones.items(): + m = owner == i + if not m.any(): + continue + # the spine wanders down from the summit (nature.md M1: split each mountain along the ridge spine) + dy = np.clip(ys - c["y"], 0, None) + spine = c["x"] + dy * c["skew"] + _fbm1(ys[:, 0] / (H * .05), seed + i * 7 + k)[:, None] * c["h"] * .12 * (dy / c["h"]).clip(0, 1) + lit = (xs >= spine) if sun_right else (xs < spine) + face_lit |= m & lit + front[m] = c["rank"] / max(1, len(cones) - 1) + if P["ribs"] and c["h"] > hd * .45: + # rule: gullies and ribs run down the slope from the flank (copy_land L13: 2-4 stripes that follow + # the slope, one shadow notch; nature.md M1: at least one spur divides a face) + for j in range(rng.randint(2, 4)): + side = rng.choice((-1, 1)) + s = c["sl"] if side < 0 else c["sr"] + f = rng.uniform(.12, .55) + gx = c["x"] + side * f * c["h"] / s * rng.uniform(.5, .95) + gy = c["y"] + f * c["h"] * rng.uniform(.55, .9) + ln = c["h"] * rng.uniform(.3, .6) + dxdy = side * rng.uniform(-.25, .35) + w0 = W * rng.uniform(.012, .026) + tt = ((ys - gy) / ln) + cx_ = gx + (ys - gy) * dxdy + wd = w0 * (1 - tt) * (tt > 0) * (tt < 1) + band = (np.abs(xs - cx_) < wd) & m + (gully if j % 2 == 0 else rib)[...] |= band + rng_m = owner >= 0 + if not rng_m.any(): + continue + a = P["a"] * (.65 if night else 1.0) # night: the horizon glow is darker than moonlit snow + # values: lit / shadow faces, gullies one step into shadow on the lit face, ribs one step lighter on the shadow + # face (copy_land L13 pixel: a 1-px middle step between lit and base) + Cl, Cs = rock_l.copy(), rock_s.copy() + if not night and not sunset: + Cl = _mix(Cl, (255, 240, 210), .12) # warm light, cool shadow (value_light_colour 3) + Cs = _mix(Cs, top_c, .18) + mid_l = _mix(Cl, Cs, .45) + mid_s = _mix(Cs, Cl, .3) + C = np.where(face_lit[..., None], Cl, Cs).astype(float) + C = np.where((face_lit & gully)[..., None], mid_l, C) + C = np.where((~face_lit & rib)[..., None], mid_s, C) + # snow: above the altitude with a jagged line (fBm, 4-8% of the mountain height) and fingers down the gullies + sline = base - snow_alt + _fbm1(xs[0] / (W * .05), seed + 9 + k)[None, :] * h_dom * .14 + snow = rng_m & (ys < sline) + snow |= rng_m & gully & (ys < sline + h_dom * .22) & ~face_lit + snow |= rng_m & rib & (ys < sline + h_dom * .12) & face_lit + if k == 0: + snow = rng_m & (ys < sline + h_dom * .05) # far: one flat snow tone per face, no fingers (V4: 2 tones) + S = np.where(face_lit[..., None], snow_l, snow_s) + C = np.where(snow[..., None], S, C) + # nearer spurs a touch darker than the big peak behind them (separation by value, not outline: L10) + C = C * (1 - .05 * front[..., None] * (k == 1)) + # aerial perspective toward the sky colour at each row + the far plane's lower contrast (V4) + skyrow = np.array([sky_at(scene, min(y, y0), y0) for y in range(rows)], float)[:, None, :] + C = C + (skyrow * .5 + hz * .5 - C) * a + # mist at the range base: the bottom 15-25% of each range height fades toward the haze (nature.md M1, V5) + mist_h = hd * rng.uniform(.18, .26) + km = np.clip((ys - (base - mist_h)) / mist_h, 0, 1)[..., None] * (.55 if k == 0 else .45) + C = C + (hz - C) * km + Cg = np.array(G((1.0, 1.0, 1.0)), float) # the ground tint of the light (multiplicative) + C = np.clip(C * Cg, 0, 255) + _paint(cv, rng_m, C) + drawn += int(rng_m.sum()) + # near foothills: a low dark band of forest (pine tips with irregular heights) that reserves the near dark + # (copy_land L2: p5 <= 15 L*, the darkest darks in the near layer; the ansimuz pixel reference forest is L* 11) + if not lake: + fh = H * rng.uniform(.035, .06) + xs1 = np.arange(W, dtype=float) + .5 + env = base - fh * (.55 + .45 * (_fbm1(xs1 / (W * .25), seed + 77) + .5)) + tips = np.zeros(W) + x = -rng.uniform(0, 4) + while x < W + 4: # pine tips: heights vary (CV >= .2, nature.md T3), spacing irregular + th = fh * rng.uniform(.25, .7) + wd = max(1.5, th * rng.uniform(.35, .5)) + d = np.abs(xs1 - x) + tips = np.maximum(tips, np.clip(th * (1 - d / wd), 0, None)) + x += wd * rng.uniform(.9, 1.8) + top = env - tips + ys = np.arange(rows, dtype=float)[:, None] + .5 + m = ys >= top[None, :] + lit = np.zeros_like(m) + if not snowy: + # a lit edge of the tips toward the light, one step (pixel guidance: lit cap, nature.md 2.10) + sh = 1 if sun_right else -1 + top2 = np.roll(top, sh) + lit = m & (ys < top2[None, :] + max(1.0, H / 128)) + if snowy: + lit = m & (ys < top[None, :] + max(1.0, H / 160)) # snow on every tip (N1: every upward surface) + Cf = np.zeros((rows, W, 3)) + _mix(fol, hz, .12) + Cf = np.where(lit[..., None], _mix(fol * 1.35, hz, .1) if fol_snow is None else fol_snow, Cf) + _paint(cv, m, np.clip(Cf, 0, 255)) + trace.append("nature: designed ranges (dominant peak at %.2f W, %d planes, snow above one altitude%s)" + % (x_dom / W, len(planes), "" if lake else ", dark foothill forest")) + return True + + +# ------------------------------------------------------------------ nt_cloud: a fair-weather sky in perspective +def fair_clouds(rng, W, H, y0, sx, sy, place, spheres_fn, haze_fn, trace): + """nt_cloud: cumulus are a ceiling seen in perspective. All bases sit at ONE altitude, so a cloud's screen size + is proportional to its base's height above the horizon e (0 horizon .. 1 top): width = (.06 + .36 e) W + (copy_land L9: 22-33% W high in the sky, 5-12% W near the horizon), height / width = .25 + .5 e (compute R5), + and the count is 1 big + 2-3 medium + 3-5 small far ones (nature.md S2: never 2-4 equal stamps; size CV >= .5). + Returns [(spheres, base_y, haze)] for skies.paint_clouds.""" + out, placed = [], [] + bands = [(.62, .86, 1)] + [(.32, .55, rng.randint(2, 3))] + [(.08, .26, rng.randint(3, 5))] + if place == "sky": + bands[1] = (.3, .6, rng.randint(3, 4)) + for lo, hi, n in bands: + for _ in range(n): + for _try in range(12): + e = rng.uniform(lo, hi) + by = y0 * (1 - e) + wid = W * (.06 + .36 * e) * rng.uniform(.8, 1.2) + cx = rng.uniform(-.05, 1.05) * W + # clouds keep off the sun / moon disc, and do not sit squarely on each other (they may overlap a little) + if abs(cx - sx) < wid * .6 + H * .08 and abs(by - wid * .2 - sy) < H * .14: + continue + if any(abs(cx - a) < (wid + b) * .42 and abs(by - c) < H * .05 + (wid + b) * .06 for a, c, b in placed): + continue + placed.append((cx, by, wid)) + tall = (.25 + .5 * e) / .44 * rng.uniform(.85, 1.15) + out.append((spheres_fn(cx, by, wid, tall), by, haze_fn(by))) + break + trace.append("nature: fair sky in perspective (%d clouds, one base altitude, size by height above the horizon)" % len(out)) + return out + + +# ------------------------------------------------------------------ nt_clump: a broadleaf crown as clumps with sky holes +def _clump_r(phi, r, seed): + """clump outline radius at angle phi: a run of small bumps (nature.md T1: bump radius .08-.15 of the clump, + amplitude 8-15%)""" + return r * (1 + .3 * _fbm1(phi * 2.2 + seed * .37, seed, 3, .6) + .07 * np.cos(phi * 9 + seed)) + + +def clump_crown(cv, ctx, inst, F, rng, leaf, trunk, barkpat, autumn=False, snow=False, palette=None, fruit=None): + """nt_clump: an oak / generic broadleaf as a painter designs it (nature.md T1-T2; compute R6; Carlson "sky holes"; + Oga clumps with a lit cap and a dark undercut): + - trunk tapering from a root flare (base 1.3-1.6x the width at 1/3), splitting at .35-.5 of the height into 2-3 + limbs at +-20-45 deg; the crown starts at .3-.42 so 25-45% of the trunk shows; + - 4-6 clumps (3-7 in the rule) with radii big-medium-small (1 : .7 : .45) on the limb tips, ragged outlines; + - 2-5 sky holes (each 1-6% of the crown) in the upper half near the edge, where the limbs show through; + - three values per clump (lit cap toward the light, mid body, dark cool undercut), a dark core where clumps + overlap, lower clumps ~6 L* darker per tier, leaf-cluster breakup of the band edges.""" + L = ctx.L + s = inst.h + hw = min(inst.w / inst.h / 2 * .98, .55) + vb = rng.uniform(.22, .3) # crown bottom (trunk visible 25-45%, T1) + a, b = hw, (1 - vb) / 2 # crown half-axes in tree-height units + vc = vb + b + # --- skeleton: split height and limb tips (T1) + vs = rng.uniform(.35, .5) + nl = rng.choice((2, 3, 3)) + angs = sorted(rng.uniform(20, 45) * (1 if i % 2 else -1) + (0 if nl == 2 else (i - 1) * 4) for i in range(nl)) + if nl == 3: + angs[1] = rng.uniform(-8, 8) + tips = [] + for ag in angs: + t = math.radians(ag) + d = rng.uniform(.42, .7) + tips.append((math.sin(t) * a * d * 1.5, vc + math.cos(t) * b * d * .8 - b * .1)) + # --- clumps: limb tips + a top clump + 1-2 small edge clumps; radii big-medium-small (1 : .7 : .45), sized so + # the union fills most of the crown ellipse (convexity .70-.88, T1) + R0 = .56 * math.sqrt(a * b) + cl = [(tu, tv) for tu, tv in tips] + [(rng.uniform(-.15, .15) * a, vc + b * rng.uniform(.3, .45))] + for _ in range(rng.randint(1, 2)): + side = rng.choice((-1, 1)) + cl.append((side * a * rng.uniform(.35, .5), vc - b * rng.uniform(.15, .4))) # low shoulder clumps fill the crown base + sizes = [1.0, .82, .72, .6, .5, .45, .42][:len(cl)] + rng.shuffle(sizes) + clumps = [] + for (cu, cv_), k in zip(cl, sizes): + r = R0 * k * rng.uniform(.9, 1.1) + # keep every clump inside the crown box + cu = max(-a + r * .8, min(a - r * .8, cu)) + cv_ = max(vb + r * .7, min(1 - r * .9, cv_)) + clumps.append((cu, cv_, r, rng.randint(0, 999))) + tw = rng.uniform(.05, .068) # trunk half-width at 1/3 + F.taper([(0, 0), (rng.uniform(-.01, .01), vs * .5), (0, vs)], tw * 1.0, tw * .8, trunk, barkpat) + F.ell(0, .012, tw * rng.uniform(1.4, 1.6), .028, trunk, pattern=barkpat) # root flare (T1: 1.3-1.6x) + for (tu, tv, _r, _s) in clumps: # every clump hangs on a limb that ends inside it (no floating clumps) + F.taper([(0, vs), ((tu * .5), (vs + tv) / 2 + .02), (tu, tv)], tw * .62, tw * .3, trunk, barkpat) + clumps.sort(key=lambda c: -c[1]) # upper clumps first: lower, nearer ones overlap them + # --- raster in screen space over the crown box + X0, Y0 = F.P(-a - R0 * .4, 1.02) + X1, Y1 = F.P(a + R0 * .4, vb - R0 * .3) + x0, y0_, x1, y1 = int(math.floor(min(X0, X1))), int(math.floor(min(Y0, Y1))), int(math.ceil(max(X0, X1))), int(math.ceil(max(Y0, Y1))) + x0, y0_ = max(0, x0), max(0, y0_) + x1, y1 = min(cv.w - 1, x1), min(cv.h - 1, y1) + if x1 <= x0 or y1 <= y0_: + return False + gx, gy = np.meshgrid(np.arange(x0, x1 + 1) + .5, np.arange(y0_, y1 + 1) + .5) + U = (gx - F.x) * F.f / s + V = (F.y - gy) / s + owner = np.full(U.shape, -1, int) + cover = np.zeros(U.shape, int) + lu = np.zeros(U.shape); lv = np.zeros(U.shape) + for i, (cu, cv_, r, sd) in enumerate(clumps): + du, dv = U - cu, V - cv_ + phi = np.arctan2(dv, du) + rr = _clump_r(phi, r, sd) + m = np.hypot(du, dv) < rr + cover += m + owner[m] = i + lu[m], lv[m] = du[m] / r, dv[m] / r + inside = owner >= 0 + if not inside.any(): + return False + crown = inside.copy() + # --- sky holes: 2-5 small ellipses fully inside the crown, upper half, near the edge (T1: 1-6% of the crown each) + area = inside.sum() + nh = rng.randint(2, 4) + holes = 0 + for _ in range(40): + if holes >= nh: + break + th = rng.uniform(.15, .85) * math.pi + rad = rng.uniform(.6, .85) + hu, hv = math.cos(th) * a * rad, vc + math.sin(th) * b * rad + hr = math.sqrt(area * rng.uniform(.006, .016) / math.pi) / s # tree units + hm = np.hypot((U - hu) / (hr * rng.uniform(.8, 1.4)), (V - hv) / hr) < 1 + hm |= np.hypot((U - hu - hr * rng.uniform(-.9, .9)), (V - hv - hr * rng.uniform(-.7, .2))) < hr * .7 # irregular + ring = np.hypot(U - hu, V - hv) < hr * 2.2 + if hm.sum() < 2 or not (inside[ring].mean() > .97): + continue + inside &= ~hm + holes += 1 + hole = crown & ~inside + # --- three values per clump (T2) + sun_r = 1.0 if L.d[0] > 0 else -1.0 + lx, ly = .55 * sun_r, .83 + n = _fbm1(gx[0] * .9 + gy[:, :1] * 1.7, inst.k * 13 + 5, 3, .5) # leaf-cluster breakup of the band edges + sdot = lu * lx * F.f + lv * ly + n * .9 + tier = np.zeros(U.shape) + order = {i: k for k, i in enumerate(sorted(range(len(clumps)), key=lambda i: -clumps[i][1]))} + for i in range(len(clumps)): + tier[owner == i] = order[i] / max(1, len(clumps) - 1) + band = np.where(sdot > .38, 0, np.where((lv < -.35 + n * .5) | ((cover >= 2) & (sdot < .05)), 2, 1)) + pal = palette or [leaf] + base = np.zeros(U.shape + (3,)) + np.asarray(leaf, float) + if len(pal) > 1: + for i in range(len(clumps)): + base[owner == i] = pal[i % len(pal)] + C = np.zeros(U.shape + (3,)) + for bi, (face, toward) in enumerate(((.98, (255, 236, 160)), (.6, None), (.26, (40, 58, 110)))): + m = band == bi + if not m.any(): + continue + cols = {} + for key in map(tuple, np.unique(base[m].round(), axis=0)): + c = np.asarray(L.flat(key, face), float) + if toward is not None: + c = _mix(c, toward, .16 if bi == 0 else .22) + cols[key] = c + bb = base[m].round() + out = np.zeros((m.sum(), 3)) + for key, c in cols.items(): + out[(bb == key).all(-1)] = c + C[m] = out + C = C * (1 - .14 * tier[..., None]) # lower clumps ~6 L* darker per tier (T2) + if snow: + capm = inside & (lv > .55 - n * .3) & (band == 0) | inside & (lv > .78) + C[capm] = (242, 246, 252) + # a sky hole is the backdrop (and the limbs behind) one step darker, never pure sky (T1: -3 to -8 L*); painting it + # as part of the tree keeps the pixel outline from ringing it like an eye + ys_, xs_ = np.nonzero(hole) + for yy, xx in zip(ys_.tolist(), xs_.tolist()): + C[yy, xx] = np.asarray(cv.px[yy + y0_][xx + x0], float) * .84 + if fruit is not None: + # fruit hangs inside the clumps, mostly on the lower half (apple tree) + cand = np.argwhere(inside & (lv < .3) & (lv > -.8)) + for _ in range(min(9, len(cand) // 6)): + yy, xx = cand[rng.randrange(len(cand))] + for dy in (0, 1): + for dx in (0, 1): + if 0 <= yy + dy < C.shape[0] and 0 <= xx + dx < C.shape[1] and inside[yy + dy, xx + dx]: + C[yy + dy, xx + dx] = fruit if (dx + dy) else _mix(fruit, (255, 255, 255), .3) + C = np.clip(C, 0, 255) + inside = crown + + def ins(x, y): + xi, yi = int(x) - x0, int(y) - y0_ + return 0 <= yi < inside.shape[0] and 0 <= xi < inside.shape[1] and bool(inside[yi, xi]) + + def col(x, y): + return tuple(C[min(C.shape[0] - 1, int(y) - y0_), min(C.shape[1] - 1, int(x) - x0)]) + cv.fill(ins, (x0, y0_, x1 + 1, y1 + 1), col) + inst._nt_crown = dict(clumps=len(clumps), holes=holes) + return True + + +# ------------------------------------------------------------------ nt_pine: a conifer as stacked, uneven, drooping tiers +def pine(cv, ctx, inst, green, trunk, snow=False): + """nt_pine (nature.md T3; Bob Ross fan-brush pine; Slynyrd / BJG pixel pines): a bare spire tip (.05-.12 of the + height), then 5-8 tiers whose width grows downward with jitter (w_i = W (i/n)^.8 U(.85, 1.15)), each tier a drooping + saw (tips 10-25 deg below horizontal) with left and right half-widths 5-20% different, the trunk showing in some + gaps; three values: the lit side toward the light, the shade side, and a dark shelf under each tier's overhang. + Snow lies on the upper edge of every tier (N1).""" + L, h, x, y, rng = ctx.L, inst.h, inst.x, inst.y, inst.rng + sun_r = L.d[0] > 0 + lite, shade, deep = L.flat(green, .95), L.flat(green, .42), L.flat(green, .2) + lite = tuple(_mix(lite, (255, 236, 170), .1)) + deep = tuple(_mix(deep, (30, 40, 90), .2)) + from .shading import lit_capsule + lit_capsule(cv, L, x, y, x, y - h * .3, h * .04, trunk) + n = rng.randint(5, 8) + spire = h * rng.uniform(.05, .12) + top_y = y - h + bot_y = y - h * rng.uniform(.12, .2) + span = bot_y - (top_y + spire) + Wmax = h * rng.uniform(.26, .34) + tiers = [] + for i in range(1, n + 1): + yb = top_y + spire + span * i / n + rng.uniform(-.15, .15) * span / n + w = Wmax * (i / n) ** .8 * rng.uniform(.85, 1.15) + asym = rng.uniform(.05, .2) * rng.choice((-1, 1)) + tiers.append((yb, w * (1 - asym), w * (1 + asym))) + # spire + cv.poly([(x, top_y), (x + h * .012, top_y + spire * 1.2), (x - h * .012, top_y + spire * 1.2)], shade) + prev_yb = top_y + spire * .6 + for k, (yb, wl, wr) in enumerate(tiers): + ytop = prev_yb - (yb - prev_yb) * rng.uniform(.25, .6) # each tier starts up inside the one above (overlap) + droop = math.tan(math.radians(rng.uniform(10, 25))) + teeth = 2 + int((wl + wr) / (h * .09)) + pts_l, pts_r = [], [] + for side, wd, pts in ((-1, wl, pts_l), (1, wr, pts_r)): + for j in range(teeth + 1): + f = j / teeth + tip = (j % 2 == 0) + pts.append((x + side * wd * f, yb + (wd * f * droop * .5 if tip else -h * .02 * f) + (h * .01 if tip else 0))) + left = [(x, ytop)] + pts_l[::-1][:-1] + [(x, yb)] + right = [(x, ytop)] + pts_r[::-1][:-1] + [(x, yb)] + cv.poly(left, shade if sun_r else lite) + cv.poly(right, lite if sun_r else shade) + # the dark shelf: the next tier's top part sits in this tier's shadow (drawn as this tier's lower band) + band = max(1.0, (yb - ytop) * .22) + cv.poly([(x - wl * .85, yb - band * .2), (x + wr * .85, yb - band * .2), (x + wr * .6, yb + band), (x - wl * .6, yb + band)], + deep, alpha=.55) + if snow: + # snow on the upper face of each tier: a white wedge from the tip along both slopes, thicker near the trunk + sw = (yb - ytop) * .28 + cv.poly([(x, ytop - .5), (x + wr * .55, ytop + (yb - ytop) * .55), (x + wr * .45, ytop + (yb - ytop) * .55 + sw * .4), + (x, ytop + sw), (x - wl * .45, ytop + (yb - ytop) * .55 + sw * .4), (x - wl * .55, ytop + (yb - ytop) * .55)], + (240, 244, 252), alpha=.95) + prev_yb = yb + return True + + +# ------------------------------------------------------------------ nt_treeline: far trees as group masses +def treeline_groups(cv, ctx, scene, rng, keep, colors, night=False): + """nt_treeline (nature.md T4; Carlson "a group of trees is one mass", Payne group mass): the far shore's trees merge + into 1-3 group masses with a scalloped top (bump widths varied, CV >= .3) and a straight soft bottom on the + waterline, with one or two gaps across the line; each bump has a lit cap toward the sun, the mass a darker base + band (self-shadow), the whole line pulled toward the haze (V4). Returns the number of groups.""" + W, H, y0 = cv.w, cv.h, int(ctx.y0) + u = H / 128.0 + sun_right = ctx.sun[0] >= W / 2 + hz = np.asarray(ctx.haze_color, float) + ng = rng.choice((1, 2, 2, 3)) + g = _gaps(rng, ng + 1, .3) + gap_w = W * rng.uniform(.06, .16) + segs, x = [], -W * .05 + total = W * 1.1 - gap_w * (ng - 1) + for k in range(ng): + w = total * (g[k] + g[-1] / ng) + segs.append((x, x + w)) + x += w + gap_w * rng.uniform(.6, 1.4) + xs = np.arange(W) + .5 + top = np.full(W, np.inf) + lit = np.zeros(W, bool) + bumps = 0 + for a, b in segs: + hmax = rng.uniform(6, 11) * u + x = a + while x < b: + r = rng.uniform(2.2, 5.5) * u + hb = hmax * rng.uniform(.55, 1.0) * (.6 + .4 * math.sin(math.pi * min(1, max(0, (x - a) / max(1, b - a))))) + d = (xs - x) / r + prof = np.where(np.abs(d) < 1, y0 - hb + r * (1 - np.sqrt(np.clip(1 - d * d, 0, 1))), np.inf) + top = np.minimum(top, prof) + x += r * rng.uniform(.9, 1.5) + bumps += 1 + base_c = np.asarray(colors[0], float) + if night: + base_c = base_c * .45 + base_c = _mix(base_c, hz, .3) + lit_c = _mix(base_c * 1.25, (250, 240, 190), .15) + dark_c = _mix(base_c * .72, (40, 50, 90), .1) + G = ctx.L.ground + sh = 1 if sun_right else -1 + for xi in range(W): + t = top[xi] + if not np.isfinite(t): + continue + y_top = int(max(0, math.floor(t))) + # the lit cap: the bump's upper edge on the sun side (the profile rises toward the sun) + nb = top[min(W - 1, max(0, xi + sh))] + sunward = np.isfinite(nb) and nb <= t + for y in range(y_top, y0 + 1): + if y >= H or cv.ids[y][xi]: + continue + k = (y - t) / max(1.0, y0 - t) + if y - t < 1.6 * u and sunward: + c = lit_c + elif k > .72: + c = dark_c + else: + c = base_c + p = cv.px[y][xi] + p[0], p[1], p[2] = G(tuple(c)) + keep.add((y, xi)) + return ng, bumps + + +# ------------------------------------------------------------------ nt_surf: a storm coast is dark rock + white surf +SEA_PLACES = {"beach", "sea", "ocean", "coast", "harbor", "harbour", "water", "lake"} + + +def storm_coast(cv, ctx, scene, insts, trace): + """nt_surf (nature.md W6, V3 storm table, N2; copy diagnosis w16_52): in a storm on the coast the brightest values + are surf and spray, never the sand. The standing subject (lighthouse, tower, house) gets a mass of dark rock under + it - 3-5 blocks, each a flattened 5-8 sided polygon (w/h 1.3-2.5) with a lit top plane, a mid front and a dark + shadow plane (R1 rock planes) - and surf bursting against the rock: white spray clusters 5-15% H tall on the + windward side plus broken foam lines at the rock foot. Drawn after the storm sea and the weather (skies.plan), in + front of the subject's foot (the subject stands ON the rock; those pixels become backdrop). Runs only when the + prompt names a storm (or rough sea) on the coast / sea.""" + from .atmos import stormy, toks + tk = toks(scene) + if not (stormy(scene) or tk & {"waves", "rough", "crashing", "surf", "gale"}): + return False + if scene.get("place") not in SEA_PLACES and not tk & {"coast", "sea", "ocean", "shore", "cliff", "cliffs"}: + return False + subj = [it for it in insts if getattr(it, "ent", None) == 0 and hasattr(it, "x") and getattr(it, "pose", None) != "flying"] + if not subj: + return False + it = subj[0] + W, H = cv.w, cv.h + import random as _r + import zlib + rng = _r.Random(zlib.crc32((scene.get("text") or "").encode()) + 17) + night = scene.get("time") == "night" + sun_r = ctx.L.d[0] > 0 + sd = 1 if sun_r else -1 + G = ctx.L.ground + top_c = np.array((92, 90, 98.)) if not night else np.array((44, 46, 60.)) + face = top_c * .62 + shade = top_c * .34 + span = max(it.w * rng.uniform(2.0, 2.8), W * .26) + cx = it.x + rng.uniform(-.12, .12) * span + yb = it.y + H * rng.uniform(.03, .06) # the rocks' foot in the water, below the subject's base + prev = cv.cur_id + # the coast itself: storm sea from the horizon to the frame bottom (no bright sand under a storm, V3); the subject + # stands on its own rock (Brehat / Hiroshige coast pictures); rain re-laid over the sea (N2: thin slanted + # streaks, 2-4% cover, a step above the water) + A = np.asarray(cv.px, float) + I = np.asarray(cv.ids, np.int64) + y0 = int(ctx.y0) + if H - y0 > 3: + from .atmos import storm_sea + storm_sea(A, I, cv, ctx, scene, [], (y0 + 1, H), rng) + k = int(W * (H - y0) * .02 / max(1, H * .05)) + for _ in range(k): + x, y = rng.uniform(0, W), rng.uniform(y0, H) + ln = H * rng.uniform(.03, .07) + for j in range(int(ln)): + xx, yy = int(x + j * .18), int(y + j) + if 0 <= xx < W and 0 <= yy < H and I[yy, xx] == 0: + A[yy, xx] = A[yy, xx] * .55 + np.array((190, 198, 210.)) * .45 + cv.px = A.tolist() + cv.cur_id = 0 + blocks = [] + nb = rng.randint(3, 5) + for k in range(nb): + bw = span * (rng.uniform(.4, .6) if k == 0 else rng.uniform(.18, .34)) # 1 big + smaller ones leaning on it + bh = bw / rng.uniform(1.3, 2.5) + bx = cx + (0 if k == 0 else rng.uniform(-.5, .5) * span) + by = yb + (0 if k == 0 else rng.uniform(-.2, .6) * bh * .4) + blocks.append((bx, by, bw, bh)) + blocks.sort(key=lambda b: b[1]) + for bx, by, bw, bh in blocks: + n = rng.randint(5, 8) + pts = [] + for j in range(n): + a = math.pi + math.pi * j / (n - 1) + pts.append((bx + math.cos(a) * bw * .5 * rng.uniform(.85, 1.05), by + math.sin(a) * bh * rng.uniform(.8, 1.0))) + pts += [(bx + bw * .5, by + 1), (bx - bw * .5, by + 1)] + cv.poly(pts, G(tuple(face))) + # shadow plane on the side away from the light, the lit top plane as a flat cap + cv.poly([(bx, by - bh * .9), (bx - sd * bw * .5, by - bh * .2), (bx - sd * bw * .5, by + 1), (bx - sd * bw * .05, by + 1)], G(tuple(shade))) + cv.poly([(bx - bw * .32, by - bh * .78), (bx + bw * .05 * sd, by - bh * 1.0), (bx + bw * .36, by - bh * .7), + (bx + bw * .02, by - bh * .62)], G(tuple(top_c))) + cv.capsule(bx - bw * .5, by, bx + bw * .5, by, max(.6, H / 200), G(tuple(shade * .6))) # darkest at the contact + # surf: spray bursting up the windward side and a broken foam line at the foot (the light group of a storm) + foam = np.array((236, 240, 242.)) if not night else np.array((170, 182, 200.)) + foam2 = foam * .84 + side = -sd if rng.random() < .7 else sd + ftop = H * rng.uniform(.06, .13) + for k in range(rng.randint(9, 15)): + t = rng.random() + x = cx + side * span * rng.uniform(.15, .65) + y = yb - ftop * t ** .7 + r = H * rng.uniform(.012, .028) * (1.2 - .6 * t) + cv.ellipse(x, y, r * rng.uniform(1.0, 1.6), r, tuple(foam if rng.random() < .65 else foam2)) + x = cx - span * .7 + while x < cx + span * .7: + ln = W * rng.uniform(.02, .06) + cv.capsule(x, yb + H * .006, x + ln, yb + H * .006 + rng.uniform(-1, 1), max(.6, H / 160), tuple(foam)) + x += ln + W * rng.uniform(.01, .04) + cv.cur_id = prev + trace.append("nature: storm coast - %d dark rock blocks under the subject, surf and spray as the light group" % nb) + return True diff --git a/pydraw/paint/__pycache__/__init__.cpython-310.pyc b/pydraw/paint/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05f58ced088ae9fe41432b1c98a1d5176fdb24a7 Binary files /dev/null and b/pydraw/paint/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/paint/__pycache__/common.cpython-310.pyc b/pydraw/paint/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08f2cd52213a0315d3dc4ed2132a6470fe7c2a55 Binary files /dev/null and b/pydraw/paint/__pycache__/common.cpython-310.pyc differ diff --git a/pydraw/paint/__pycache__/paper.cpython-310.pyc b/pydraw/paint/__pycache__/paper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5a2eeb8d94d98d3263e7b5fa22cd0c447489b38 Binary files /dev/null and b/pydraw/paint/__pycache__/paper.cpython-310.pyc differ diff --git a/pydraw/paint/__pycache__/pigment.cpython-310.pyc b/pydraw/paint/__pycache__/pigment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e94dd8e99190413c5a317e18a24726254df99d4 Binary files /dev/null and b/pydraw/paint/__pycache__/pigment.cpython-310.pyc differ diff --git a/pydraw/paint/__pycache__/water.cpython-310.pyc b/pydraw/paint/__pycache__/water.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c7f2f9e08701ae6c776e22b6384ce06fc0ecfc2 Binary files /dev/null and b/pydraw/paint/__pycache__/water.cpython-310.pyc differ diff --git a/pydraw/paint/__pycache__/watercolor.cpython-310.pyc b/pydraw/paint/__pycache__/watercolor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0f63e26d2372d95b4cfd589fa3d3f207397575b Binary files /dev/null and b/pydraw/paint/__pycache__/watercolor.cpython-310.pyc differ diff --git a/pydraw/paint/strokes.py b/pydraw/paint/strokes.py index 07413d28352aadc743f80e95b3045dfbbca71cf2..fb7161133c49db4a0e0eb5753ba60e5a6569046c 100644 --- a/pydraw/paint/strokes.py +++ b/pydraw/paint/strokes.py @@ -174,6 +174,17 @@ def render(G, seed=0, trace=None, preset="oil", opts=None): # gouache: a thin flat lay-in of every shape first, so no paper sliver survives between hand-cut shapes canvas = canvas * .25 + region_blur(C, cmap, 4 * sc) * .75 pal = _palette(C, rng) if clean else None + mk = _EXP.get("md_marks", "0") != "0" + if mk: + # (wave 19 media, md_marks; R19, copy_room S10, copy_land L14) marks last and scaled to the picture's OWN local + # value variation: a stroke's value / hue jitter may not exceed the local value std of the planned picture + # (sigma 4 px at 512) - a flat wall gets quiet strokes, broken foliage keeps its broken colour. Oil-amplitude marks + # on a soft picture cost .826 -> .833 in the Hammershoi copy; no marks cost .841 -> .804 in the Fantin-Latour. + L0 = lum(C) + mu = ndimage.gaussian_filter(L0, 4 * sc) + LS = np.sqrt(np.maximum(ndimage.gaussian_filter(L0 * L0, 4 * sc) - mu * mu, 0)).astype(np.float32) + lsd = float(np.median(LS)) + trace.append("paint: marks scaled to the picture's local value variation (median std %.3f, md_marks)" % lsd) painted = np.zeros((H, W), np.float32) # how much paint lies on each pixel (thin passages show the ground) height = np.zeros((H, W), np.float32) nstrokes = 0 @@ -229,7 +240,11 @@ def render(G, seed=0, trace=None, preset="oil", opts=None): # broken colour: per-stroke value + hue jitter; KM pickup of the wet paint under the stroke's start # (hue jitter scales with the local chroma: a grey wall stays grey, a red barn breaks into reds) chrm = np.clip((col.max(-1) - col.min(-1)) * 2.5, .25, 1)[:, None] - col = col * (1 + rng.normal(0, p["jitter_v"], (n, 1))) + rng.normal(0, p["jitter_h"], (n, 3)) * chrm + if mk: + f = np.clip((LS[sy, sx] * float(_EXP.get("md_markk", 1.5)) + .005) / max(p["jitter_v"], 1e-3), .15, 1.0)[:, None] + col = col * (1 + rng.normal(0, p["jitter_v"], (n, 1)) * f) + rng.normal(0, p["jitter_h"], (n, 3)) * chrm * f + else: + col = col * (1 + rng.normal(0, p["jitter_v"], (n, 1))) + rng.normal(0, p["jitter_h"], (n, 3)) * chrm col = np.clip(col, 0, 1) if p["pickup"] > 0 and li_ > 0: # wet-into-wet: the brush picks up the paint under it, only where that paint is near its own colour @@ -297,7 +312,10 @@ def render(G, seed=0, trace=None, preset="oil", opts=None): canvas = canvas + glint[..., None] * .5 # thin passages show the weave / paper tooth thin = np.clip(1 - painted / 1.5, 0, 1) - canvas = canvas * (1 + (tex[..., None] - .5) * (.08 + .14 * thin[..., None])) + ta = (.08 + .14 * thin[..., None]) + if mk: + ta = ta * np.clip(LS / .05, .35, 1.0)[..., None] # the ground's tooth shows as much as the picture's own texture + canvas = canvas * (1 + (tex[..., None] - .5) * ta) trace.append("paint: %s strokes (%d strokes, brushes %s px)" % (preset, nstrokes, "/".join("%.0f" % r for r in radii))) return np.clip(canvas * 255, 0, 255) diff --git a/pydraw/paint/watercolor.py b/pydraw/paint/watercolor.py index ce478f7eb2470ef88b3b28bb7b35e3b2c1f092f5..98a9f216e1565b7749093152334aa5f8da410552 100644 --- a/pydraw/paint/watercolor.py +++ b/pydraw/paint/watercolor.py @@ -94,8 +94,33 @@ def render(G, seed=0, trace=None, opts=None): lightv = G["lightmap"] if "lightmap" in G else np.nan_to_num(G.get("light", np.full((H, W), np.nan)), nan=.6) # -- 2. reserved whites: very light pixels, the lit tops of things in focus white = (m < .07) | ((lightv > .88) & (m < .22) & (focal > .5) & (obj > 0)) + if _EXP.get("md_wc", "0") != "0": + # (wave 19 media, md_wc; R18 watercolour, media.md W1, X4) the paper is the lightest value and is decided + # first: the lightest md_wcres (.15) of the picture by the value plan stays paper (Homer's Market Scene measures + # .17; target 10-25%), with hard dry edges. Small flecks merge away (a reserve is a shape, not speckle). + # A reserve is a whole shape: a wash region (or object part) is kept white when most of it is that light; the + # reserve only stops the FIRST wash - the shadow glazes still cross it (folds on a white cloth, snow shadows). + q = float(np.quantile(m, float(_EXP.get("md_wcres", .15)))) + px = (m <= q) & (m < .45) + key = reg.astype(np.int64) * 4096 + obj.astype(np.int64) + u, inv = np.unique(key, return_inverse=True) + inv = inv.reshape(key.shape) + frac = np.bincount(inv.ravel(), weights=px.ravel().astype(np.float64)) / np.maximum(np.bincount(inv.ravel()), 1) + res = (frac > .6)[inv] + if "mat" in G: + # a backdrop is reserved only where its material IS the light (sky, cloud, snow, water, a flame / light); + # a light patch of a studio wall is a wash (a reserved crescent behind a head reads as a hole) + from ..gbuf import MAT as _M2 + okm = np.isin(G["mat"], [_M2[n] for n in ("sky", "cloud", "snow", "water", "ice", "light", "flame")]) + res &= (obj > 0) | okm + res = ndimage.binary_opening(res, iterations=int(2 * sc) + 1) + else: + res = np.zeros(m.shape, bool) white = ndimage.binary_opening(white, iterations=1) keepw = 1 - ndimage.gaussian_filter(white.astype(np.float32), .8 * sc) + keep0 = keepw * (1 - ndimage.gaussian_filter(res.astype(np.float32), .8 * sc)) + if res.any(): + trace.append("paint: watercolour reserves %.0f%% paper by value (md_wc)" % (100 * (res | white).mean())) # -- 3. first wash = the local colour. A painter lays each shape's body colour flat (its middle tone), lighter # where the light hits; the shadow shapes come later as glazes. Objects: two flat values; background: one # graded wash (skies and fields are graded, not banded). @@ -191,7 +216,7 @@ def render(G, seed=0, trace=None, opts=None): # wash layer Mb = (w0 > .004).astype(np.float32) s0, E0 = wetedge(Mb, 2.5 * sc, .7 * sc) - x0 = w0 * s0 * keepw * sepf * flow * (1 + 1.2 * E0 + .9 * Ereg) * gran(0, hue) * vig + x0 = w0 * s0 * keep0 * sepf * flow * (1 + 1.2 * E0 + .9 * Ereg) * gran(0, hue) * vig if knob("wc_dry", 1) > 0: # dry brush on the ground: a wash dragged quickly over rough paper skips the tooth's peaks (sparkle of white) grd = (obj == 0) & ~sky & (yy > hor) @@ -234,6 +259,15 @@ def render(G, seed=0, trace=None, opts=None): # glints: paper left white on the light path (Rainey: "leave paper white for glints") g = (lake[2]["glint"] * vig)[..., None] R = R * (1 - g) + P.to_r(PAPER) * g + if _EXP.get("md_wc", "0") != "0": + # (md_wc, media.md W4 / Holmes) the honey pass: the darkest 2.5% of the value plan, near the eye, gets a last + # thick wet-on-dry glaze with a hard edge - the contact shadows and the darkest accents, painted last + dq = float(np.quantile(m[vig > .5], .975)) if (vig > .5).any() else 9.0 + hon = ((m >= dq) & (focal > .25)).astype(np.float32) + hon = ndimage.binary_opening(hon > 0, iterations=1).astype(np.float32) + if hon.sum() > 10: + sH, EH = wetedge(hon, .6 * sc, .5 * sc) + R = _glaze(R, hue * .85 + cool * .15, .55 * sH * (1 + 1.5 * EH) * vig) # -- paper tooth under raking light, pigment-dark valleys already from granulation R = R * PP.relief(paper_h, strength=1.3 * sc)[..., None] out = P.to_rgb(R) diff --git a/pydraw/physics.py b/pydraw/physics.py index 2176577aeadccd8b9931751a96e26781e8d10e6e..1d9c24fb8e1cbccc5a1ef2defaa02ea745d9e1b0 100644 --- a/pydraw/physics.py +++ b/pydraw/physics.py @@ -179,6 +179,8 @@ def h_pile(scene, toks, text, trace): # rule: " of [number] [adjectives] " within four words before the item mode, n = None, None for k in range(max(0, j - 5), j): + if mode and toks[k] in ("and", ",", "with", "next", "beside", "near"): + mode, n = None, None # (w19 things, bug fix) "a stack of books and a candle": the pile word stops at "and" if toks[k] in PILE_WORDS and (k + 1 < len(toks) and toks[k + 1] == "of" or toks[k] == "stacked"): mode = PILE_WORDS[toks[k]] if mode and toks[k] in NUM: diff --git a/pydraw/picplan.py b/pydraw/picplan.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7793bf5ccd105854aebd4ab4e61c43a10ccff --- /dev/null +++ b/pydraw/picplan.py @@ -0,0 +1,839 @@ +"""Plan the picture before drawing it (wave 19, plan lane; docs/research19/SYNTHESIS.md rules A1-A6, C12-C13). + +pydraw draws objects first and lights them afterwards; artists plan the whole picture's values first. This module holds +the picture-level plan and executes it on the finished id + colour buffers, before the palette snap (pixel), the style +filter (smooth) or the medium (G-buffer media). Every step works in CIELAB L* (0 black .. 100 white) and keeps each +pixel's hue: the plan owns value, the vocabulary owns local colour. + + key (R1) one light key record per picture from the prompt's own time and weather words (key_record). With the + knob on, the variation layer may no longer invent a sunset, dawn or night the prompt did not ask for + (prepare() calls hold_time). Families and numbers: value_light_colour.md table 3.2. + values (R2) per region (sky, ground rows far/mid/near, backdrop features above the horizon, scenery objects by depth) + the squinted median L* is moved into the key's plane band (Carlson: sky > flat ground > slants > uprights); + far things toward the sky value (aerial perspective, copy_land L1/L4, nature 1/3). + notan (R3) squinted to two values (Otsu): gap >= 25 L* by day, 20 at night; extremes reserved (p5 <= 15, + p95 >= 80 by day); a 42-58% split is tipped toward the key's dominant family (composition 2/4, copy_graphic P1/P3). + break (R4) the subject sits on a value break: the ground round it is pushed against it (light subject -> darker + surround, dark subject -> lighter) until >= 60/255 luma along most of the outline (copy_room S2, copy_scene G3). + winner (R5) no squint-contrast spot outside the subject reaches 0.7 of the subject's; emitters yield unless they + are the subject (composition 1, compute R1). + chroma (R6) C* > 45 is an accent: big masses capped at the key's chroma ceiling, the share outside the subject and + the lights kept <= 12%; night is low value AND low chroma (value_light_colour 6, copy_room S8-S9). + practical (R12/R13) a room at night lit by a lamp / fire / candle: the room first goes to the dark band, then 4 flat + rings at r0, r0 sqrt2, 2 r0, 2 sqrt2 r0 add the light back (inverse square: 1, 1/2, 1/4, 1/8) in the light's + colour (value_light_colour L5/L6, copy_room S6/S7). atmos.night_room's blue multiply becomes low value + low + chroma under this knob. + claim PYDRAW_CLAIM=1: Image.save(path) writes .claim.json (schema v1 on the board, out/night/BOARD.md + 10:41 UTC 2026-12-02); PYDRAW_CLAIM=2 adds .ids.png (8-bit id map at the output size). + +Knobs (PYDRAW_EXP, all default OFF): pp_key, pp_values, pp_notan, pp_break, pp_winner, pp_chroma, pp_practical; pp=1 turns +every one on (an explicit pp_=0 still wins). Numbers are ranges from several sources, cited at each table. +""" +import json +import math +import os +import re + +import numpy as np + +KNOBS = ("pp_key", "pp_values", "pp_notan", "pp_break", "pp_winner", "pp_chroma", "pp_practical") + + +def _exp(): + return dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + + +def on(name): + E = _exp() + if name in E: + return E[name] != "0" + return E.get("pp", "0") != "0" + + +def any_on(): + return any(on(k) for k in KNOBS) + + +def claim_level(): + try: + return int(os.environ.get("PYDRAW_CLAIM", "0") or 0) + except ValueError: + return 0 + + +# ------------------------------------------------------------------------------------------------ colour (numpy) +_M = np.array([[.4124564, .3575761, .1804375], [.2126729, .7151522, .0721750], [.0193339, .1191920, .9503041]]) +_MI = np.linalg.inv(_M) +_WP = np.array([.95047, 1.0, 1.08883]) + + +def rgb2lab(rgb): + c = np.clip(np.asarray(rgb, np.float64) / 255.0, 0, 1) + c = np.where(c <= .04045, c / 12.92, ((c + .055) / 1.055) ** 2.4) + xyz = (c @ _M.T) / _WP + f = np.where(xyz > .008856, np.cbrt(xyz), 7.787 * xyz + 16 / 116.) + L = 116 * f[..., 1] - 16 + return np.stack([L, 500 * (f[..., 0] - f[..., 1]), 200 * (f[..., 1] - f[..., 2])], -1) + + +def lab2rgb(lab): + L, a, b = lab[..., 0], lab[..., 1], lab[..., 2] + fy = (L + 16) / 116. + f = np.stack([fy + a / 500., fy, fy - b / 200.], -1) + xyz = np.where(f > .206893, f ** 3, (f - 16 / 116.) / 7.787) * _WP + c = xyz @ _MI.T + c = np.clip(c, 0, 1) + c = np.where(c <= .0031308, 12.92 * c, 1.055 * np.power(c, 1 / 2.4) - .055) + return np.clip(c * 255.0, 0, 255) + + +def _blur(x, s): + from scipy import ndimage + return ndimage.gaussian_filter(x, s, mode="nearest") + + +def _otsu(x, nb=64): + x = x[np.isfinite(x)].ravel() + if x.size < 4 or x.max() - x.min() < 1e-6: + return float(np.median(x)) if x.size else 50.0 + h, e = np.histogram(x, nb) + c = (e[:-1] + e[1:]) / 2 + w0 = np.cumsum(h) + w1 = w0[-1] - w0 + m0 = np.cumsum(h * c) / np.maximum(w0, 1) + m1 = ((h * c).sum() - np.cumsum(h * c)) / np.maximum(w1, 1) + v = w0 * w1 * (m0 - m1) ** 2 + return float(c[int(np.argmax(v))]) + + +# ------------------------------------------------------------------------------------------------ R1 light key +# value_light_colour.md table 3.2 (Carlson's plane order, Gurney's key notes, Speed's compression); copy_land L1-L4 and +# copy_scene G4-G9 measured the same orders on the Bierstadt, ansimuz, Liljefors and Corot copies. L* bands are the +# light-family value of each plane at mid depth; "key" is the target median, "rng" the minimum p2..p98 span, +# "cmax" the chroma ceiling of big masses, "dark" whether the dark family should dominate the notan (V2 unequal measure). +FAMILIES = { + "clear_day": dict(key=(55, 70), rng=75, sky=(65, 85), ground=(55, 70), slant=(45, 60), upright=(25, 45), cmax=40, dark=False, + light=(255, 246, 230), shadow=(120, 140, 190)), + "overcast": dict(key=(50, 65), rng=55, sky=(75, 90), ground=(45, 60), slant=(38, 50), upright=(25, 40), cmax=45, dark=False, + light=(228, 232, 238), shadow=(130, 138, 150)), + "golden": dict(key=(45, 60), rng=70, sky=(60, 85), ground=(35, 55), slant=(45, 65), upright=(30, 60), cmax=50, dark=False, + light=(255, 200, 130), shadow=(110, 100, 170)), + "sunset": dict(key=(30, 50), rng=80, sky=(45, 90), ground=(22, 42), slant=(15, 30), upright=(8, 25), cmax=55, dark=True, + light=(255, 170, 100), shadow=(70, 50, 90)), + "dawn": dict(key=(45, 62), rng=65, sky=(60, 88), ground=(35, 55), slant=(35, 55), upright=(25, 45), cmax=35, dark=False, + light=(255, 214, 190), shadow=(120, 125, 175)), + "dusk": dict(key=(25, 40), rng=60, sky=(30, 65), ground=(10, 25), slant=(10, 25), upright=(8, 20), cmax=25, dark=True, + light=(255, 200, 140), shadow=(60, 60, 110)), + "night_moon": dict(key=(20, 35), rng=50, sky=(15, 40), ground=(10, 25), slant=(10, 22), upright=(6, 18), cmax=20, dark=True, + light=(200, 210, 220), shadow=(40, 50, 75)), + "fog": dict(key=(65, 80), rng=30, sky=(70, 85), ground=(55, 75), slant=(50, 70), upright=(20, 40), cmax=12, dark=False, + light=(225, 225, 220), shadow=(150, 152, 158)), + "storm": dict(key=(25, 45), rng=55, sky=(20, 45), ground=(15, 40), slant=(15, 35), upright=(10, 30), cmax=15, dark=True, + light=(190, 196, 206), shadow=(70, 80, 100)), + "snow_day": dict(key=(70, 85), rng=75, sky=(65, 85), ground=(85, 96), slant=(75, 90), upright=(15, 35), cmax=35, dark=False, + light=(255, 250, 240), shadow=(140, 160, 210)), + "snow_night": dict(key=(25, 45), rng=65, sky=(10, 35), ground=(40, 65), slant=(35, 55), upright=(5, 20), cmax=25, dark=True, + light=(200, 210, 230), shadow=(60, 75, 120)), + "rain_day": dict(key=(40, 55), rng=55, sky=(60, 75), ground=(35, 55), slant=(30, 45), upright=(20, 40), cmax=25, dark=False, + light=(200, 204, 210), shadow=(100, 110, 130)), + "city_night_rain": dict(key=(15, 35), rng=75, sky=(15, 30), ground=(8, 25), slant=(8, 22), upright=(8, 20), cmax=30, dark=True, + light=(255, 200, 130), shadow=(40, 40, 70)), + "interior_practical": dict(key=(15, 35), rng=80, sky=(10, 30), ground=(8, 50), slant=(8, 50), upright=(8, 50), cmax=40, dark=True, + light=(255, 186, 110), shadow=(60, 44, 36)), + "interior_night": dict(key=(15, 30), rng=50, sky=(10, 30), ground=(8, 25), slant=(8, 25), upright=(8, 25), cmax=18, dark=True, + light=(190, 200, 220), shadow=(40, 42, 56)), + "interior_window": dict(key=(45, 60), rng=70, sky=(85, 98), ground=(30, 50), slant=(30, 50), upright=(30, 50), cmax=35, dark=False, + light=(240, 242, 246), shadow=(150, 130, 110)), + "interior_day": dict(key=(45, 62), rng=65, sky=(70, 90), ground=(35, 55), slant=(35, 55), upright=(30, 50), cmax=35, dark=False, + light=(250, 240, 225), shadow=(140, 125, 115)), +} +PRACTICALS = {"lamp": ("lamp", .11), "lantern": ("lamp", .10), "oil lamp": ("lamp", .10), "street lamp": ("lamp", .12), + "streetlight": ("lamp", .12), "lamppost": ("lamp", .12), "candle": ("candle", .08), "torch": ("fire", .10), + "campfire": ("fire", .15), "fire": ("fire", .15), "bonfire": ("fire", .15), "fireplace": ("fire", .15), + "fire pit": ("fire", .15), "jack-o-lantern": ("candle", .08), "lightbulb": ("lamp", .10), + "light bulb": ("lamp", .10)} +# r0 as a fraction of the picture width: value_light_colour L5 (1.5-3x a candle's height, 3-5x a lamp's, 4-8x a fire's) +# and copy_room S6 (the Hammershoi pool, r0 .08-.15 W), merged. +SKY_EMITTERS = {"sun": "sun", "moon": "moon", "full moon": "moon", "crescent moon": "moon", "half moon": "moon", + "harvest moon": "moon", "blood moon": "moon"} +SCREENS = {"tv", "television", "monitor", "computer", "laptop", "screen"} +_TIME_WORDS = {"night", "nighttime", "midnight", "moonlit", "moonlight", "starry", "stars", "sunset", "sunrise", "dusk", + "dawn", "twilight", "evening", "nightfall", "gloaming", "daybreak", "morning", "noon", "afternoon", + "golden", "dark", "moon"} +_WEATHER_WORDS = {"fog", "foggy", "mist", "misty", "rain", "rainy", "raining", "storm", "stormy", "thunderstorm", "snow", + "snowy", "snowing", "overcast", "cloudy", "blizzard", "haze", "hazy", "drizzle", "wet"} + + +def _words(text): + return set(re.findall(r"[a-z]+", (text or "").lower())) + + +def hold_time(scene, trace, parsed): + """pp_key (R1, no unasked sunset or night): undo the variation layer's time-of-day / dawn pick when the prompt named + none (value_light_colour rule 1: w16_0/2/11 got a sunset sky over noon-lit land). parsed = (time, weather) after + parse(). Mood words are prompt words, so mood.apply may still set them afterwards.""" + if not on("pp_key"): + return + v = scene.get("vary") or {} + t0, w0 = parsed + if v.get("time") and scene.get("time") != t0: + trace.append("picplan: key - the prompt named no time; varied %s undone -> %s" % (scene["time"], t0)) + scene["time"] = t0 + v["time"] = None + scene.pop("_dawn", None) + if scene.get("weather") != w0 and not (_words(scene.get("text")) & _WEATHER_WORDS): + scene["weather"] = w0 + + +def expose_key(scene): + """pp_key: the key record on the scene before the layout (compose lane's thumbs.py reads sky_v / ground_v / + thing_v, 0..1 values = the middle of each plane band)""" + if not on("pp_key"): + return + try: + k = key_record(scene) + except Exception: + return + d = {kk: k[kk] for kk in ("family", "source", "key", "sky", "ground", "slant", "upright", "cmax", "dark", "light", "shadow")} + d.update(sky_v=sum(k["sky"]) / 200.0, ground_v=sum(k["ground"]) / 200.0, thing_v=sum(k["upright"]) / 200.0) + scene["_light_key"] = d + + +def key_record(scene): + """R1: the light key record of this picture (a dict; FAMILIES row + family name + where it came from)""" + from .scenes import INDOOR + tw = _words(scene.get("text")) + t = scene.get("time") or "day" + w = scene.get("weather") + place = scene.get("place") + if place is None and scene.get("entities"): + try: # the still-life painter runs before the layout names the place: ask the layout's own rule + from .layout import choose_place + place = choose_place(scene, []) + except Exception: + place = None + indoor = place in INDOOR + concepts = {e.get("concept") for e in scene.get("entities", ())} + prac = sorted(c for c in concepts if c in PRACTICALS) + snowy = bool(tw & {"snow", "snowy", "snowing", "snowfall", "winter", "wintry", "blizzard", "snowcovered"}) or place == "snow" + if indoor: + if t == "night" or scene.get("_candle"): + fam = "interior_practical" if (prac or scene.get("_candle")) else "interior_night" + elif tw & {"window", "windowsill", "sunlit", "sunlight"} or "window" in concepts: + fam = "interior_window" + else: + fam = "interior_day" + elif t == "night": + fam = "snow_night" if snowy else ("city_night_rain" if w == "rain" else "night_moon") + elif t == "sunset": + from .scenes import _dawn + if _dawn(scene): + fam = "dawn" + elif tw & {"dusk", "twilight", "evening", "nightfall", "gloaming"}: + fam = "dusk" + elif tw & {"golden"}: + fam = "golden" + else: + fam = "sunset" + elif w == "fog": + fam = "fog" + elif w == "storm" or tw & {"storm", "stormy", "thunderstorm"}: + fam = "storm" + elif w == "rain": + fam = "rain_day" + elif snowy: + fam = "snow_day" + elif tw & {"cloudy", "overcast", "grey", "gray"}: + fam = "overcast" + else: + fam = "clear_day" + src = "prompt" if tw & (_TIME_WORDS | _WEATHER_WORDS) else ("mood" if (scene.get("mood") or {}).get("words") else "default") + rec = dict(FAMILIES[fam]) + if snowy and fam in ("dawn", "golden", "sunset", "dusk"): + # lit snow is the lightest ground there is and takes the light's colour (value_light_colour L11) + rec["ground"], rec["slant"] = (70, 92), (60, 85) + elif fam == "sunset" and place in ("desert", "beach"): + # sand under a low sun mirrors the sky's glow (table 3.2: "except a sky-mirroring band (water, wet sand)") + rec["ground"] = (30, 50) + rec.update(family=fam, source=src, indoor=indoor, practicals=prac, time=t, weather=w) + return rec + + +# ------------------------------------------------------------------------------------------------ the frame's facts +class Frame: + """what the plan needs from any renderer: colours, ids, layer tags, horizon, instances, scene""" + + def __init__(self, rgb, ids, layer, y0, inst, scene, sun=None): + self.rgb = np.asarray(rgb, np.float64) + self.ids = np.asarray(ids, np.int64) + H, W = self.ids.shape + self.H, self.W = H, W + self.layer = np.asarray(layer, np.int64) if layer is not None else None + self.y0 = float(y0) if y0 is not None else None + self.inst = inst or {} + self.scene = scene + self.sun = sun + self.concept = {k: getattr(v, "concept", "?") for k, v in self.inst.items()} + self._subject = None + + def subject(self): + """(subject id set, main instance): craft._subject_ids, minus big supports (a tree it sleeps under)""" + if self._subject is None: + ids, main = set(), None + try: + from .craft import _subject_ids + from .gbuf import _bound_to + + class _C: + pass + c = _C() + c.id_inst = self.inst + S, main = _subject_ids(c) + ids = {o for o in S if self.inst.get(o) is main or _bound_to(self.inst.get(o), main)} + except Exception: + pass + present = set(int(v) for v in np.unique(self.ids) if v) + self._subject = (ids & present, main) + return self._subject + + def emitters(self): + out = [] + for k, c in self.concept.items(): + if c in PRACTICALS: + out.append((PRACTICALS[c][0], k, PRACTICALS[c][1])) + elif c in SKY_EMITTERS: + out.append((SKY_EMITTERS[c], k, 0)) + elif c in SCREENS: + out.append(("screen", k, .08)) + return out + + def sky(self): + if self.layer is not None: + m = (self.ids == 0) & (self.layer == 1) + if m.sum() > 10: + return m + if self.y0 is None: + return np.zeros(self.ids.shape, bool) + rows = np.arange(self.H)[:, None] < self.y0 + return (self.ids == 0) & rows + + +def _bbox(m): + ys, xs = np.nonzero(m) + if not len(ys): + return None + return int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1 + + +def _depth_of(it, H, y0): + """0 near .. 1 far, from where the thing stands (gbuf._ground_depth: eps / (row - horizon))""" + if it is None or y0 is None: + return .5 + from .director import _root + r = _root(it) + gy = getattr(r, "ground_y", None) or getattr(r, "y", None) + if getattr(it, "pose", None) == "flying" and getattr(it, "bound", None) is None: + return .5 + if gy is None or gy <= y0: + return 1.0 + eps = max(1.0, H * .02) + return float(np.clip(eps / max(gy - y0, eps), 0, 1)) ** .5 + + +def _layer_name(d): + return "far" if d > .55 else ("mid" if d > .3 else "near") + + +# ------------------------------------------------------------------------------------------------ the plan passes +def apply(F, trace): + """run every knob that is on over Frame F; returns the new rgb (float64 HxWx3)""" + if not any_on(): + return F.rgb + key = key_record(F.scene) + F.key = key + lab = rgb2lab(F.rgb) + done = [] + if on("pp_practical"): + if practical(F, lab, key): + done.append("practical") + if on("pp_values") and not key["indoor"]: + n = values(F, lab, key) + if n: + done.append("values(%d regions)" % n) + if on("pp_notan"): + r = notan(F, lab, key) + if r: + done.append("notan(%s)" % r) + if on("pp_break"): + r = value_break(F, lab, key) + if r: + done.append("break(%s)" % r) + if on("pp_winner"): + r = winner(F, lab, key) + if r: + done.append("winner(%s)" % r) + if on("pp_chroma"): + r = chroma(F, lab, key) + if r: + done.append("chroma(%s)" % r) + if done: + trace.append("picplan: key %s (%s); %s" % (key["family"], key["source"], ", ".join(done))) + else: + trace.append("picplan: key %s (%s); nothing to change" % (key["family"], key["source"])) + lab[..., 0] = np.clip(lab[..., 0], 0, 100) + out = lab2rgb(lab) + # only pixels the plan actually moved are re-encoded (round trips through Lab would shift the rest by a hair) + moved = np.abs(lab - F._lab0).max(-1) > .25 if hasattr(F, "_lab0") else np.ones(F.ids.shape, bool) + res = F.rgb.copy() + res[moved] = out[moved] + return res + + +def _move(lab, m, target, strength=.8, squeeze=1.0): + if m.sum() < 8: + return False + L = lab[..., 0] + med = float(np.median(L[m])) + lo, hi = target + tgt = min(max(med, lo), hi) + if abs(tgt - med) < 1.5 and squeeze >= .999: + return False + new = med + (L[m] - med) * squeeze + (tgt - med) * strength + L[m] = new + return True + + +def values(F, lab, key): + """R2: plane and depth bands. Sky, then the ground in three depth rows, backdrop features above the horizon (far: + within ~10 L* of the sky, copy_land L1), then scenery objects by depth (uprights, pulled toward the sky value with + distance). The subject and emitters are left to break / winner. Returns how many regions moved.""" + if F.y0 is None: + return 0 + H, W = F.H, F.W + I = F.ids + n = 0 + sky = F.sky() + if sky.sum() > 20: + # the sun / moon disc and its glow (the lightest light, V7) keep their value when the sky band moves + core = sky & (lab[..., 0] > 88) + n += _move(lab, sky & ~core, key["sky"], .75) + sky_L = float(np.median(lab[..., 0][sky])) if sky.sum() > 20 else float(np.mean(key["sky"])) + rows = np.arange(H)[:, None] * np.ones((1, W)) + y0 = F.y0 + bg = I == 0 + if F.layer is not None: + bg_ground = bg & ~sky & (F.layer != 7) & (rows > y0) + bg_feat = bg & ~sky & (F.layer != 7) & (rows <= y0 + 1) + else: + bg_ground = bg & ~sky & (rows > y0) + bg_feat = bg & ~sky & (rows <= y0 + 1) + span = max(1.0, H - y0) + g_lo, g_hi = key["ground"] + # depth rows of the ground: far row toward the sky value (veil law, value_light_colour rule 8) + for a, b, k in ((0, .2, .55), (.2, .55, .25), (.55, 1.01, 0.0)): + m = bg_ground & (rows >= y0 + a * span) & (rows < y0 + b * span) + lo, hi = g_lo + (sky_L - g_lo) * k * .6, g_hi + (sky_L - g_hi) * k * .6 + n += _move(lab, m, (min(lo, hi), max(lo, hi)), .7) + # backdrop features above the horizon (mountains, tree lines, far hills): near the sky value, darker than it + # (far layer within ~10-20 L* of the sky: copy_land L1/L4; nature 3) + if bg_feat.sum() > 20 and key["family"] not in ("sunset", "dusk"): + n += _move(lab, bg_feat, (sky_L - 22, sky_L - 6), .6) + S, _main = F.subject() + em = {k for _, k, _ in F.emitters()} + for k, it in F.inst.items(): + if k in S or k in em: + continue + m = I == k + if m.sum() < 12: + continue + d = _depth_of(it, H, y0) + lo, hi = key["upright"] + # aerial perspective: an upright at depth d is veiled toward the sky value (Koschmieder: L = L0 e^-bd + Lair (1-e^-bd)) + v = 1 - math.exp(-1.6 * d) + lo, hi = lo + (sky_L - 8 - lo) * v, hi + (sky_L - 4 - hi) * v + if (getattr(it, "info", None) or {}).get("animal") or getattr(it, "concept", "") == "person": + lo, hi = lo - 5, hi + 15 # figures keep their local colour more than scenery does + n += _move(lab, m, (min(lo, hi), max(lo, hi)), .55, squeeze=1 - .25 * v) + F._sky_L = sky_L + return n + + +def notan(F, lab, key): + """R3: the squinted two-value read. Widen the gap between the families round the Otsu split, reserve the extremes, + tip a 50/50 split toward the key's dominant family. Monotone per pixel, so shapes never swap families.""" + L = lab[..., 0] + s = max(1.0, F.W / 80.0) # squint (critic.py uses sigma 2 at 256 px) + Ls = _blur(L, s) + t = _otsu(Ls) + dark = Ls < t + share = float(dark.mean()) + if share < .02 or share > .98: + return None + ml, md = float(Ls[~dark].mean()), float(Ls[dark].mean()) + gap = ml - md + night = key["dark"] + need = 20.0 if night else 25.0 + if key["family"] == "fog": + need = 12.0 + did = [] + if gap < need: + k = min(1.8, need / max(gap, 4.0)) + # stretch round t; detail inside each family keeps its own spread (the offset, not the detail, is scaled) + off = np.where(L >= t, 1.0, -1.0) * (k - 1) * gap / 2 + w = np.clip(np.abs(L - t) / 6.0, 0, 1) # pixels right at the split move less: no new hard contour + L += off * w + did.append("gap %.0f->%.0f" % (gap, gap * k)) + # unequal measure: 42-58% dark -> tip the near-split band toward the dominant family (Dow via composition 4) + if .42 <= share <= .58: + band = np.abs(Ls - t) < 7 + L[band] += (-4.0 if night else 4.0) + did.append("tip %.2f" % share) + # reserve the extremes (copy_land L3, composition 2): darkest p5 <= 15, lightest p95 >= 80 by day + # only the top / bottom 15% move (the accents), so a low-key design keeps its dark field and a high-key one its light + p5, p15, p85, p95 = np.percentile(L, (5, 15, 85, 95)) + if p5 > 15 and key["family"] != "fog" and p15 > p5 + 1: + lo = L < p15 + tgt5 = max(12.0, p5 - 12.0) # at most 12 L* deeper: a bigger stretch blackened shadow shapes (desert, snowy valley) + L[lo] = p15 - (p15 - L[lo]) * (p15 - tgt5) / max(1.0, p15 - p5) + did.append("p5 %.0f" % p5) + if not night and p95 < 80 and p95 > p85 + 1: + hi = L > p85 + L[hi] = p85 + (L[hi] - p85) * (82.0 - p85) / max(1.0, p95 - p85) + did.append("p95 %.0f" % p95) + np.clip(L, 0, 100, out=L) + return ", ".join(did) if did else None + + +def _ring(m, r): + from scipy import ndimage + return ndimage.binary_dilation(m, iterations=max(1, int(r))) & ~m + + +def value_break(F, lab, key): + """R4: the subject's outline sits on a value break. Measure the squinted luma just inside vs just outside the + outline; if fewer than 65% of the outline points differ by >= 60/255, the surround is pushed against the subject + with a soft falloff (a light subject gets a darker ground round it, a dark one a lighter ground).""" + from scipy import ndimage + S, _ = F.subject() + if not S: + return None + Sm = np.isin(F.ids, list(S)) + if Sm.sum() < 20: + return None + em = np.isin(F.ids, [k for _, k, _ in F.emitters() if k not in S]) + r = max(2, int(F.W * .015)) + L = lab[..., 0] + Ls = _blur(L, max(1.0, F.W / 160.0)) + inner = Sm & ~ndimage.binary_erosion(Sm, iterations=r) + outer = _ring(Sm, r) & ~em + if inner.sum() < 8 or outer.sum() < 8: + return None + # pair each outer pixel with the subject's mean value nearby (box mean of the inner ring) + k = 2 * r + 3 + num = ndimage.uniform_filter(np.where(inner, Ls, 0.), k) + den = ndimage.uniform_filter(inner.astype(float), k) + Lin = np.where(den > 1e-3, num / np.maximum(den, 1e-3), np.nan) + dif = Ls - Lin # outside minus inside, L* units + ok = outer & np.isfinite(dif) + # 60/255 luma ~ 24 L* in the mid tones (copy_room S2, copy_scene G3: difference >= 60 of 255 on 60-70% of the outline) + need = 24.0 + frac = float((np.abs(dif[ok]) >= need).mean()) if ok.any() else 1.0 + if frac >= .65: + return "ok %.2f" % frac + s_mean = float(np.median(L[Sm])) + o_mean = float(np.median(Ls[outer])) + # direction: away from the subject's own value; at night / sunset a light subject on dark keeps a dark ground + sign = -1.0 if s_mean >= o_mean else 1.0 + if abs(s_mean - o_mean) < 4: + sign = -1.0 if s_mean > 45 else 1.0 + delta = np.clip(need - np.abs(dif[ok]), 0, None) + amt = float(min(20.0, np.percentile(delta, 60))) + if amt < 2: + return "ok %.2f" % frac + # region-level shift (pixel art bands a smooth halo into rings): every region the outline touches - each object, + # and the backdrop split into sky / features above the horizon / ground below - moves as one flat value step, + # weighted by its share of the outline ring. The ground takes about two thirds, the subject a third (its hue kept). + reg = np.where(F.ids > 0, F.ids, 0).astype(np.int64) + sky = F.sky() + rows = np.arange(F.H)[:, None] * np.ones((1, F.W)) + y0 = F.y0 if F.y0 is not None else F.H + bgm = F.ids == 0 + reg[bgm & sky] = -1 + reg[bgm & ~sky & (rows <= y0)] = -2 + reg[bgm & ~sky & (rows > y0)] = -3 + named_em = _named_ids(F) & {k for _, k, _ in F.emitters()} + tot = float(outer.sum()) + for r_ in np.unique(reg[outer]): + if r_ in S or r_ in named_em or (r_ > 0 and r_ in {k for _, k, _ in F.emitters()}): + continue + share = float((reg[outer] == r_).sum()) / tot + if share < .05: + continue + w = min(1.0, share * 2.0) * (.4 if r_ == -1 else 1.0) + L[reg == r_] += sign * amt * w + # the subject itself is not moved: darkening a white horse dirtied it and dimmed the fire inside a fireplace (512 sheet) + np.clip(L, 0, 100, out=L) + return "%.2f %s%.0f" % (frac, "+" if sign > 0 else "-", amt) + + +def _named_ids(F): + """ids of things the prompt named (entities), and of emitters whose word is in the prompt (an owl 'under the moon')""" + tw = _words(F.scene.get("text")) + out = set() + for k, it in F.inst.items(): + c = getattr(it, "concept", "") + if getattr(it, "ent", None) is not None or set(c.split()) & tw: + out.add(k) + return out + + +def winner(F, lab, key): + """R5: one winner. Squint contrast (|L - local mean|) outside the subject is capped at 0.7 of the subject's own. + Each competing shape (a connected over-cap spot, only its pixels on the competing side of the local mean) is moved + toward the colour of its own surround, so it keeps its shape and hue family and loses contrast; emitters that are + not the subject yield too (the sun, lit windows, glitter), unless the prompt names them.""" + from scipy import ndimage + S, _ = F.subject() + if not S: + return None + Sm = np.isin(F.ids, list(S)) + if Sm.sum() < 20: + return None + L = lab[..., 0] + s1, s2 = max(1.0, F.W / 40.0), max(2.0, F.W / 10.0) + Ls = _blur(L, s1) + Lb = _blur(L, s2) + C = np.abs(Ls - Lb) + near = ndimage.binary_dilation(Sm, iterations=max(2, int(F.W * .03))) + cs = float(np.percentile(C[near], 95)) + if cs < 4: + return None + cap = .7 * cs + prot = near | np.isin(F.ids, list(_named_ids(F))) + prot |= F.sky() & (L > 80) # the sun / moon disc: a grey sun reads as a moon; it keeps its value (V7 lightest light) + over = (~prot) & (C > cap) + if over.mean() < .002: + return "ok" + lbl, n = ndimage.label(ndimage.binary_dilation(over, iterations=1)) + moved = 0 + for i in range(1, n + 1): + comp = (lbl == i) & ~prot + if comp.sum() < 4: + continue + sgn = 1.0 if Ls[comp].mean() >= Lb[comp].mean() else -1.0 + shape = comp & ((L - Lb) * sgn > 0) + ring = ndimage.binary_dilation(comp, iterations=max(2, int(F.W * .02))) & ~comp & ~prot + if shape.sum() < 2 or ring.sum() < 4: + continue + f = float(np.clip(cap / max(C[comp].max(), 1e-3), .55, 1.0)) # dimmed, never erased + ref = np.median(lab[ring], 0) + lab[shape] = ref + (lab[shape] - ref) * f + moved += int(shape.sum()) + return "%d px in %d spots toward their surround (cap %.0f)" % (moved, n, cap) + + +def chroma(F, lab, key): + """R6: saturation is an accent. Big masses outside the subject and the lights are capped at the key's ceiling; + the sky at min(ceiling, 35) by day; the share of C* > 45 outside the subject is pulled under 12%.""" + a, b = lab[..., 1], lab[..., 2] + C = np.hypot(a, b) + S, _ = F.subject() + keep = np.isin(F.ids, list(S) + [k for _, k, _ in F.emitters()]) + cmax = float(key["cmax"]) + # big masses (backdrop, scenery the prompt did not name) get the key's ceiling; things the prompt named keep their + # local colour up to C* 55 (objects keep their hue: SYNTHESIS A2), the subject and the lights are free + named = [k for k, it in F.inst.items() if getattr(it, "ent", None) is not None] + ceil = np.where(np.isin(F.ids, named), max(cmax, 55.0), cmax) + sky = F.sky() + ceil[sky] = min(cmax, 35.0 if not key["dark"] else cmax) + if F.scene.get("flower_field") or not S: # the prompt's subject is the field itself (a field of sunflowers) + ceil[(F.ids == 0) & ~sky] = max(cmax, 60.0) + if key["family"] in ("sunset", "dusk", "dawn", "golden"): + keep = keep | sky # a low-sun sky is the light source: its colour is the light's (R6 "on the subject or the light") + k = np.where(keep, 1.0, np.where(C > ceil, (ceil + (C - ceil) * .45) / np.maximum(C, 1e-3), 1.0)) + share0 = float((C > 45).mean()) + big = ~keep & (ceil <= cmax) # only the big masses the key caps (not named things, not a named field) + out_share = float(((C * k) > 45)[big].sum()) / C.size + if out_share > .12: + k2 = np.where(big & (C * k > 45), 44.0 / np.maximum(C * k, 1e-3), 1.0) + k = k * k2 + if np.all(k > .999): + return None + lab[..., 1] = a * k + lab[..., 2] = b * k + share1 = float((np.hypot(lab[..., 1], lab[..., 2]) > 45).mean()) + return "C45 %.2f->%.2f" % (share0, share1) + + +def practical(F, lab, key): + """R12/R13: practical lights light the room. Indoors at night with a lamp / fire / candle: everything but the + light goes to the dark band (warm dark, not blue: value_light_colour L6), then 4 flat rings at r0 * sqrt2^k add the + lit colour back with intensities 1, 1/2, 1/4, 1/8 (L5), tinted by the light's colour (local x light, R13).""" + if key["family"] != "interior_practical": + return False + em = [(kind, k, r0) for kind, k, r0 in F.emitters() if kind in ("lamp", "fire", "candle")] + H, W = F.H, F.W + yy, xx = np.mgrid[0:H, 0:W].astype(float) + srcs = [] + for kind, k, r0 in em: + bb = _bbox(F.ids == k) + if bb is None: + continue + x0, y0_, x1, y1 = bb + h = y1 - y0_ + cy = y0_ + h * (.35 if kind == "lamp" else .5) + # r0 from the source's size (L5: 1.5-3x a candle's height, 3-5x a lamp shade's, 4-8x a fire's; the shade is about + # a third of a lamp's drawn height) clamped to copy_room S6's .08-.3 W + rr = {"candle": 2.2, "lamp": 1.3, "fire": 1.8}.get(kind, 1.3) * h + srcs.append(((x0 + x1) / 2, cy, float(np.clip(rr, r0 * W, .3 * W)), kind, k)) + if not srcs: + cand = getattr(F, "candle_xy", None) # atmos.candle_room drew its own candle (no id) + if cand is None: + return False + srcs.append((cand[0], cand[1], .12 * W, "candle", None)) + L = lab[..., 0] + emm = np.isin(F.ids, [s[4] for s in srcs if s[4] is not None]) + core = emm + I = np.zeros((H, W)) + for cx, cy, r0, kind, k in srcs: + d = np.hypot(xx - cx, (yy - cy) * 1.15) + # inverse square with the source's own size as the softening radius: 1 inside r0, 1/2 at r0 sqrt2, 1/4 at 2 r0 + # (L5); the palette snap / medium quantises it into flat rings + I = np.maximum(I, np.minimum(1.0, (r0 / np.maximum(d, 1e-3)) ** 2)) + # dark band first (interior lamp at night: walls by falloff 8-50, key 15-35: table 3.2) + dark_L = 8.0 + .15 * L + lit_L = L + newL = dark_L + (lit_L - dark_L) * I + lc = rgb2lab(np.array(key["light"], float)[None, None, :])[0, 0] + tint = .35 * I # local x light: lit surfaces take the light's hue + na = lab[..., 1] * (.55 + .45 * I) + lc[1] * tint + nb = lab[..., 2] * (.55 + .45 * I) + lc[2] * tint + # warm dark in the shadow family (umber, not blue) + nb = np.where(I < .1, np.maximum(nb, 2.0), nb) + L[~core] = newL[~core] + lab[..., 1] = np.where(core, lab[..., 1], na) + lab[..., 2] = np.where(core, lab[..., 2], nb) + return True + + +# ------------------------------------------------------------------------------------------------ entry points +def run_canvas(cv, scene, trace): + """pixel / smooth path: plan cv.px in place (cv.ids, cv.layer, cv.id_inst, cv.y0 from compose)""" + if not any_on(): + return + try: + F = Frame(cv.px, cv.ids, getattr(cv, "layer", None), getattr(cv, "y0", None), getattr(cv, "id_inst", None), + scene, getattr(cv, "sun", None)) + F.candle_xy = getattr(cv, "pp_candle", None) + F._lab0 = rgb2lab(F.rgb) + out = apply(F, trace) + cv.px = out.tolist() + cv.pp_key = F.key + except Exception as ex: # a planning pass must never take the picture down + trace.append("picplan: failed (%s)" % str(ex)[:100]) + + +def run_gbuf(G, trace): + """G-buffer media: plan G.rgb before the medium paints (and before plan.py's wave-16 hook)""" + if not any_on(): + return G + try: + inst = {k: o.get("inst") for k, o in (G.objects or {}).items()} + F = Frame(G.rgb, G.obj, G.layer, G.horizon, inst, G.scene) + F._lab0 = rgb2lab(F.rgb) + out = apply(F, trace) + G.rgb = np.clip(out, 0, 255).astype(np.float32) + G.value = (G.rgb @ np.array([.3, .59, .11], np.float32)) / 255.0 + except Exception as ex: + trace.append("picplan: failed (%s)" % str(ex)[:100]) + return G + + +# ------------------------------------------------------------------------------------------------ claim file +def claim(scene, renderer, ids=None, inst=None, y0=None, sun=None, size=None, seed=None, text=None, key=None): + """the claim record (schema v1, board 10:41 UTC 2026-12-02). ids/inst may be None (still life, figures).""" + rec = {"v": 1, "prompt": text if text is not None else scene.get("text"), "seed": seed, "size": size, + "renderer": renderer, "place": scene.get("place"), "time": scene.get("time"), "weather": scene.get("weather")} + k = key or key_record(scene) + rec["light_key"] = {"family": k["family"], "source": k["source"], "key": list(k["key"]), "range": k["rng"], + "light_rgb": list(k["light"]), "shadow_rgb": list(k["shadow"]), "chroma_max": k["cmax"], + "planes": {p: list(k[p]) for p in ("sky", "ground", "slant", "upright")}, "sun": None} + rec["grid"], rec["horizon"], rec["subject"], rec["objects"], rec["emitters"] = None, None, None, [], [] + if ids is None: + return rec + I = np.asarray(ids, np.int64) + H, W = I.shape + rec["grid"] = [H, W] + rec["horizon"] = round(float(y0) / H, 4) if y0 is not None else None + if sun is not None and scene.get("time") in ("day", "sunset") and scene.get("place") not in _indoor(): + rec["light_key"]["sun"] = [round(float(sun[0]) / W, 4), round(float(sun[1]) / H, 4)] + F = Frame(np.zeros((H, W, 3)), I, None, y0, inst or {}, scene, sun) + S, main = F.subject() + em = {k: kind for kind, k, _ in F.emitters()} + n = I.size + + def nb(bb): + return [round(bb[0] / W, 4), round(bb[1] / H, 4), round(bb[2] / W, 4), round(bb[3] / H, 4)] + seen = {} + for k in sorted(int(v) for v in np.unique(I) if v): + it = (inst or {}).get(k) + m = I == k + bb = _bbox(m) + c = getattr(it, "concept", "?") + d = _depth_of(it, H, y0) + role = "subject" if k in S else ("emitter" if k in em else ( + "prop" if it is not None and getattr(it, "ent", None) is not None else "scenery")) + seen[c] = seen.get(c, -1) + 1 + rec["objects"].append({"id": k, "concept": c, "word": getattr(it, "word", c) if it is not None else c, + "role": role, "layer": _layer_name(d), "depth": round(d, 3), "bbox": nb(bb), + "share": round(float(m.sum()) / n, 5), "pose": getattr(it, "pose", None), + "count_index": seen[c]}) + if k in em: + rec["emitters"].append({"kind": em[k], "id": k, "xy": [round((bb[0] + bb[2]) / 2 / W, 4), + round((bb[1] + bb[3]) / 2 / H, 4)]}) + # wave 20 (critic13 15:22): figure landmarks of 2D-first people / animals / birds (body2d_claim, c2d), json-safe + figs, seen_i = [], set() + for it in (inst or {}).values(): + if it is None or id(it) in seen_i: + continue + seen_i.add(id(it)) + for d in (getattr(it, "c2d", None), getattr(it, "body2d_claim", None)): + if isinstance(d, dict): + try: + figs.append(json.loads(json.dumps(d, default=lambda o: o.tolist() if hasattr(o, "tolist") else str(o)))) + except Exception: + pass + if figs: + rec["figures"] = figs + if S: + Sm = np.isin(I, list(S)) + bb = _bbox(Sm) + if bb is not None: + rec["subject"] = {"ids": sorted(int(s) for s in S), "bbox": nb(bb), "share": round(float(Sm.sum()) / n, 5), + "concept": getattr(main, "concept", None)} + return rec + + +def _indoor(): + from .scenes import INDOOR + return INDOOR + + +def write_claim(img, path): + """called by Image.save when PYDRAW_CLAIM >= 1""" + rec = getattr(img, "claim", None) + if rec is None: + rec = {"v": 1, "prompt": (img.scene or {}).get("text"), "renderer": "unknown", "objects": [], "emitters": []} + rec = dict(rec) + ids = rec.pop("_ids", None) + with open(str(path) + ".claim.json", "w") as f: + json.dump(rec, f, indent=1) + if claim_level() >= 2 and ids is not None: + I = np.asarray(ids, np.int64) + H = img.height + rep = max(1, H // I.shape[0]) + I = np.repeat(np.repeat(I, rep, 0), rep, 1)[:H, :img.width] + from .canvas import png_bytes + G = np.clip(I, 0, 255).astype(int) + with open(str(path) + ".ids.png", "wb") as f: + f.write(png_bytes([[(int(v), int(v), int(v)) for v in row] for row in G], G.shape[1], G.shape[0])) diff --git a/pydraw/ramps.py b/pydraw/ramps.py index cc6716929314f8dc5d00e5a72051ed7ee246c68d..07133f51aa83a54109c35c4cc75ea2cd81b98484 100644 --- a/pydraw/ramps.py +++ b/pydraw/ramps.py @@ -25,18 +25,21 @@ Knob (PYDRAW_EXP): mramp=0 restores the old chart snap + split median cut. mr_st difference in degrees for a cross-family merge, 22). Pure numpy; no learned anything. """ +import math import os import numpy as np _EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) -OFF_BY_DEFAULT = {"gdither", "mr_coatall", "mr_still", "mr_stillsmooth"} # round 1: checker bands between neighbouring backdrop steps - too subtle to read at 192 px +OFF_BY_DEFAULT = {"gdither", "mr_coatall", "mr_still", "mr_stillsmooth", "md_pxramp", "md_pxvsep", "md_pxwall"} # round 1: checker bands between neighbouring backdrop steps - too subtle to read at 192 px def on(name="mramp"): if _EXP.get("craft", "1") == "0": return False + if name == "mr_still" and _EXP.get("md_pxramp", "0") != "0": + return True # wave 19 media (md_pxramp): the still-life painter's pixel hook runs snap_plain's md_pxramp branch return _EXP.get(name, "0" if name in OFF_BY_DEFAULT else "1") != "0" @@ -283,8 +286,9 @@ def _shape(c, light="day", skin=False): # ------------------------------------------------------------------ the snap -def snap(A, I, cv, trace, colors=48): - """A: (H,W,3) float pre-snap picture, I: object ids. -> A snapped to material ramps (one limited palette).""" +def snap(A, I, cv, trace, colors=48, subj=None, vsep=True): + """A: (H,W,3) float pre-snap picture, I: object ids. -> A snapped to material ramps (one limited palette). + subj: the subject ids when cv cannot say (the still-life painter's buffers); vsep=False skips the vkeep ring move.""" H, W, _ = A.shape X = np.clip(A.reshape(-1, 3), 0, 255) sm = getattr(cv, "sky_mask", None) @@ -301,11 +305,12 @@ def snap(A, I, cv, trace, colors=48): Pi = np.asarray(P, np.int64).reshape(-1) if P is not None else np.zeros(len(Ii), np.int64) Pi = np.where(Pi >= 100, 100, Pi) # drawn marks of a figure (eyes, buttons): one small group per object # unique colours with counts per (group) -> work on colour histograms (fast, deterministic) - try: - from .craft import _subject_ids - subj, _ = _subject_ids(cv) - except Exception: - subj = set() + if subj is None: + try: + from .craft import _subject_ids + subj, _ = _subject_ids(cv) + except Exception: + subj = set() gkey = Ii * 1000 + Pi gk, ginv, gcnt = np.unique(gkey, return_inverse=True, return_counts=True) ginv = ginv.ravel() @@ -377,7 +382,7 @@ def snap(A, I, cv, trace, colors=48): if light in ("night", "dull") and on("mr_nightsky"): S = _night_ground(S, pix_step, Ii, cv, H, W, trace, sky_fams) S0 = S.copy() - if on("vkeep") and subj and not (light == "night" and on("vk_night")): # (r3) the night keeps its own plan: lights vs dark + if vsep and on("vkeep") and subj and not (light == "night" and on("vk_night")): # (r3) the night keeps its own plan: lights vs dark S = _vsep(S, pix_step, Z[:, 0], Ii, subj, cv, H, W, trace) rep = _budget(S, colors) S2 = S[rep] @@ -591,6 +596,8 @@ def snap_plain(A, I, trace, light_dx=0): """material ramps for a plain (H,W,3) picture + (H,W) ids (0 = backdrop): the still-life painter's pixel finish.""" A = np.asarray(A, float).copy() I = np.asarray(I, np.int64) + if on("md_pxramp"): + return _still_px(A, I, trace) if on("mr_stillsmooth"): # the painter's backdrop carries soft low-frequency noise (a plaster wall); quantized as is, it breaks into # camouflage blotches. A pixel artist paints a backdrop as a few clean bands along its light falloff: the @@ -607,6 +614,98 @@ def snap_plain(A, I, trace, light_dx=0): return out +def _bilateral_bg(A, bg, r=3, sd=2.5, sr=.035): + """edge-keeping smoothing of the backdrop only: a plaster wall's soft noise goes (it would quantize into camouflage + blotches), a table's plank lines and the wall / table edge stay (they are steps far above the noise). OKLab L range.""" + H, W, _ = A.shape + L = to_lab(np.clip(A.reshape(-1, 3), 0, 255))[:, 0].reshape(H, W) + P = np.pad(A, ((r, r), (r, r), (0, 0)), mode="edge") + PL = np.pad(L, r, mode="edge") + PB = np.pad(bg.astype(float), r, mode="constant") + num = np.zeros_like(A) + den = np.zeros((H, W)) + for dy in range(-r, r + 1): + for dx in range(-r, r + 1): + w = math.exp(-(dx * dx + dy * dy) / (2 * sd * sd)) * PB[r + dy:r + dy + H, r + dx:r + dx + W] * \ + np.exp(-((PL[r + dy:r + dy + H, r + dx:r + dx + W] - L) / sr) ** 2) + num += w[..., None] * P[r + dy:r + dy + H, r + dx:r + dx + W] + den += w + out = A.copy() + m = bg & (den > 1e-6) + out[m] = num[m] / den[m][:, None] + return out + + +def _wall_smooth(A, bg, trace): + """(knob md_pxwall) a pixel artist paints the back wall as a few clean bands along its light falloff, not as the + painted plaster's blotches. The wall = the backdrop reached from the top edge through small steps (it stops at the + table edge, a window frame, a beam's hard edge); inside it the colour is replaced by a broad mask-normalised blur + (sigma md_pxwsg x width, .1: keeps a candle's glow, about .45 W, and the left-right falloff, removes 20-50 px + blotches at 192 px native).""" + from scipy import ndimage + H, W, _ = A.shape + Z = to_lab(np.clip(A.reshape(-1, 3), 0, 255)).reshape(H, W, 3) + wall = _flood_top(Z, bg, knob("md_pxwtol", .03)) + if wall.sum() < H * W * .08: + return A + sg = knob("md_pxwsg", .1) * W + wm = wall.astype(float) + den = ndimage.gaussian_filter(wm, sg) + out = A.copy() + for c in range(3): + sm = ndimage.gaussian_filter(A[..., c] * wm, sg) / np.maximum(den, 1e-6) + out[..., c] = np.where(wall, sm, A[..., c]) + trace.append("media: back wall painted as its light falloff (%.0f%% of the picture)" % (100 * wall.mean())) + return out + + +def _orphans(out, I, passes=2): + """PX2 (clusters, not noise): a pixel whose 4 neighbours all differ from it and all belong to its own object takes the + most common neighbour colour. Never across an id edge (silhouettes and outlines stay).""" + H, W, _ = out.shape + k = (out[..., 0].astype(np.int64) << 16) | (out[..., 1].astype(np.int64) << 8) | out[..., 2].astype(np.int64) + for _ in range(passes): + Pk = np.pad(k, 1, mode="edge") + Pi = np.pad(I, 1, mode="edge") + nb = np.stack([Pk[:-2, 1:-1], Pk[2:, 1:-1], Pk[1:-1, :-2], Pk[1:-1, 2:]]) + ni = np.stack([Pi[:-2, 1:-1], Pi[2:, 1:-1], Pi[1:-1, :-2], Pi[1:-1, 2:]]) + orph = np.all(nb != k, 0) & np.all(ni == I, 0) + if not orph.any(): + break + ys, xs = np.nonzero(orph) + for y, x in zip(ys, xs): + v, c = np.unique(nb[:, y, x], return_counts=True) + k[y, x] = v[np.argmax(c)] + return np.stack([(k >> 16) & 255, (k >> 8) & 255, k & 255], -1).astype(float) + + +def _still_px(A, I, trace): + """(wave 19 media, knob md_pxramp; R18 / media PX1, PX2, PX6) the still-life painter's pixel picture on per-material + ramps with ONE limited palette. Before: 319-1931 colours, 8-25% one-pixel clusters, 16-31% between-run (smooth + gradients) on the 9 still / kitchen prompts. The old mr_still hook snapped only the objects (the backdrop kept its + painted gradient and noise) and its whole-picture variant broke the wall's noise into camouflage blotches. + backdrop edge-keeping smoothing first (_bilateral_bg), then its own ramps (mr_kbg families) like any material + objects are the subject group: a subject step never merges into a backdrop step unless practically the same + colour (keeps the peach highlight of an orange from turning wall-beige under budget pressure) + budget md_pxn colours (32; Derek Yu "32 colors is a popular choice ... 16 is also common", Lospec DB32 / + Endesga 32 / PICO-8 16; media.md PX1 target n95 <= 32, total <= 48) + orphans 1 px islands inside one object take their neighbours' colour (PX2: target <= 1.5% one-pixel clusters) + Not global k-means: research19 sheet_px_fix.png shows k=16 global merges green apples into pears.""" + bg = I == 0 + if on("md_pxbil"): + A = _bilateral_bg(A, bg, r=int(knob("md_pxbr", 3)), sd=knob("md_pxbsd", 2.5), sr=knob("md_pxbsr", .035)) + if on("md_pxwall"): + A = _wall_smooth(A, bg, trace) + subj = set(int(v) for v in np.unique(I) if v > 0) + out = snap(A, I, _Plain(), trace, int(knob("md_pxn", 32)), subj=subj, vsep=on("md_pxvsep")) + if on("md_pxorph"): + out = _orphans(out, I) + out = cap(out, int(knob("md_pxcap", 40)), trace) # hard ceiling (media.md PX1: total <= 48 at 128-192 px native) + trace.append("media: still-life pixel finish on material ramps (md_pxramp), %d colours" % + len(np.unique(out.reshape(-1, 3), axis=0))) + return out + + def _vsep(S, pix_step, L, Ii, subj, cv, H, W, trace): """(knob vkeep; mr_vgap = the wanted OKLab value gap, .12) the value plan, done where it survives: on the ramps. When the subject's middle value sits within `mr_vgap` of the ground right around it, the ground RAMPS that fill that diff --git a/pydraw/rig/__pycache__/__init__.cpython-310.pyc b/pydraw/rig/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9b73d9d3ff49721c65327f6cbc429e13639052c Binary files /dev/null and b/pydraw/rig/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/bird.cpython-310.pyc b/pydraw/rig/__pycache__/bird.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f59fe6b32d96362e96e2e962d5674baff3e9b8f9 Binary files /dev/null and b/pydraw/rig/__pycache__/bird.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/body.cpython-310.pyc b/pydraw/rig/__pycache__/body.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca62f029f78b49f43299a0581f27db64e0df1cc9 Binary files /dev/null and b/pydraw/rig/__pycache__/body.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/core.cpython-310.pyc b/pydraw/rig/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..806e069c1d497136c8f270377a212f6dcadd0f2c Binary files /dev/null and b/pydraw/rig/__pycache__/core.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/creature.cpython-310.pyc b/pydraw/rig/__pycache__/creature.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc0b14c301800c36ef4df636ad2b684065b662aa Binary files /dev/null and b/pydraw/rig/__pycache__/creature.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/face.cpython-310.pyc b/pydraw/rig/__pycache__/face.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a38cc77fac46f05e17a63c96cf78d0812289b74f Binary files /dev/null and b/pydraw/rig/__pycache__/face.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/glyphs.cpython-310.pyc b/pydraw/rig/__pycache__/glyphs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a194d7bc3b8b9d6621a298163df0bc781cc4878 Binary files /dev/null and b/pydraw/rig/__pycache__/glyphs.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/human.cpython-310.pyc b/pydraw/rig/__pycache__/human.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69b18b1f6a0ab0ff07758317e1c68cf2badac186 Binary files /dev/null and b/pydraw/rig/__pycache__/human.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/person_px.cpython-310.pyc b/pydraw/rig/__pycache__/person_px.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d7b1b1846330c019a395f7ff5ef674ef666f5f0 Binary files /dev/null and b/pydraw/rig/__pycache__/person_px.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/sdfraster.cpython-310.pyc b/pydraw/rig/__pycache__/sdfraster.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2f6452d3c7d1ee55455ad122d52a6a80854e787 Binary files /dev/null and b/pydraw/rig/__pycache__/sdfraster.cpython-310.pyc differ diff --git a/pydraw/rig/__pycache__/species.cpython-310.pyc b/pydraw/rig/__pycache__/species.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1141253b7b7d61831ee9896cde7b330de8ec0e51 Binary files /dev/null and b/pydraw/rig/__pycache__/species.cpython-310.pyc differ diff --git a/pydraw/scenes.py b/pydraw/scenes.py index 032180d3d138b77661c424d9ea90b1a13e6c45fd..58e77a5d030f2630c744be028b3dff8d49636e77 100644 --- a/pydraw/scenes.py +++ b/pydraw/scenes.py @@ -292,7 +292,7 @@ def _draw_sky(cv, ctx, scene, rng, trace): 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: + elif not overcast and not scene.get("sun_out_of_frame"): # wave 19 (content, ct_contract): rainbow -> sun behind the viewer 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 halo from .atmos import on as _aon @@ -427,7 +427,9 @@ 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.L sd = 1 if ctx.sun[0] < W / 2 else -1 # shadow side (+1 = right faces are in shade) - for layer, (amp, hz) in enumerate(((.38, .55), (.26, .32))): + from . import nature as _nat # wave 19 (nature, nt_ridge): designed ranges instead of the comb below + _nt = _nat.on("nt_ridge") and _nat.ranges(cv, ctx, scene, rng, trace, snowy=_aon_m("snowground") and __import__("pydraw.atmos", fromlist=["snowy"]).snowy(scene), lake=bool(scene.get("lake"))) + for layer, (amp, hz) in enumerate(() if _nt else ((.38, .55), (.26, .32))): peaks = [] x = -W * .1 while x < W * 1.1: diff --git a/pydraw/skies.py b/pydraw/skies.py index 86a1bd92c61451b50ad9cd682116ea0841c39a1c..2eb01cb8577ea9f766f0b16f693bb62681988151 100644 --- a/pydraw/skies.py +++ b/pydraw/skies.py @@ -310,7 +310,11 @@ def paint_clouds(cv, ctx, scene, rng, trace, overcast): def haze_of(by): return .55 * max(0.0, min(1.0, by / max(1, y0))) ** 2.2 - if kind == "fair" or kind == "night": + from . import nature as _nat + if kind == "fair" and _nat.on("nt_cloud"): + clouds += _nat.fair_clouds(rng, W, H, y0, sx, sy, p, cumulus_spheres, haze_of, trace) + light = ((sx - W / 2) / W * 1.6, -.75, .55) + elif kind == "fair" or kind == "night": n = rng.randint(2, 4) if kind == "fair" else rng.randint(1, 2) if p == "sky": n += 2 @@ -504,6 +508,17 @@ def plan(cv, scene, insts, trace): """the weather value plans, after the mood grade (compose.finish hook)""" fog_plan(cv, scene, insts, trace) storm_plan(cv, scene, insts, trace) + from . import nature as _nat # wave 19 (nature, nt_surf): a storm coast = dark rock under the subject + white surf + if _nat.on("nt_surf"): + _nat.storm_coast(cv, getattr(cv, "_ctx", None) or _ctx_of(cv), scene, insts, trace) + + +class _ctx_of: + """the bits of the compose context storm_coast reads, rebuilt from the canvas (skies.plan gets no ctx)""" + def __init__(self, cv): + self.L = cv.light + self.sun = cv.sun + self.y0 = cv.y0 # ------------------------------------------------------------------ explicit light words beat defaults diff --git a/pydraw/stilllife.py b/pydraw/stilllife.py index b57ccfa398fa4d10fdbb146006cfaeb922e48424..5d9fbdca3bbc2a7c0eb9c1ddeec7d64c5e869dee 100644 --- a/pydraw/stilllife.py +++ b/pydraw/stilllife.py @@ -40,6 +40,16 @@ def on(name="still"): return _EXP.get(name, "1") != "0" +# wave 19 (things lane, rule R16): new behaviour is default OFF until the lead turns it on; PYDRAW_EXP th_=1 = on +TH_OFF_BY_DEFAULT = {"th_ground", "th_table", "th_group", "th_board"} + + +def on_th(name): + if _EXP.get("still", "1") == "0": + return False + return _EXP.get(name, "0" if name in TH_OFF_BY_DEFAULT else "1") != "0" + + # ------------------------------------------------------------------------------------------------ vocabulary FRUIT = {"olive", "roll", "apple", "pear", "orange", "lemon", "lime", "peach", "plum", "cherry", "grapes", "strawberry", "egg", "onion", "tomato", "banana", "mango", "kiwi", "walnut", "garlic", "potato", "radish", "apricot", "fig", "pomegranate", @@ -122,6 +132,8 @@ def _ent_kind(e): return "vase" if c in ("dining table", "table", "desk", "kitchen table", "coffee table", "counter", "shelf"): return "table" + if on_th("th_board") and re.search(r"\b(?:cutting|chopping|bread|cheese|wooden) ?board\b", c + " " + (e.get("word") or "")): + return "table" # (w19 things, th_board) "on a cutting board": the board is the support the things lie on if c in ("tablecloth", "napkin"): return "cloth" if c in ("window", "windowsill"): @@ -180,6 +192,8 @@ def plan(scene, text): for k, e in zip(kinds, ents): if k == "table": P["table_mat"] = e.get("material") or e.get("color") + if "board" in (e.get("concept") or "") + (e.get("word") or ""): + P["board"] = True if k == "cloth": P["cloth"] = {"kind": e["concept"], "color": e.get("color")} if P["cloth"] is None and re.search(r"\b(?:cloth|drapery|drape|linen|tablecloth|napkin)\b", t): @@ -1395,6 +1409,29 @@ P_TEXT = [""] # ------------------------------------------------------------------------------------------------ the scene +_NUMW = r"\b(?:one|two|three|four|five|six|seven|eight|nine|ten|a pair of|a couple of|\d+)\s+(?:\w+\s+)?" + + +def _odd_group(P, trace): + """(w19 things th_group, R16 / things.md SL1-SL3) odd count and a star: loose fruit in an even number (2, 4) that the + prompt did not number becomes odd (+1); a lone container of fruit gets two of its fruit rolled out in front (bowl + + 2 = 3 units, the w16_36 fix: "add 1-2 fruits on the table in front overlapping the bowl")""" + t = P["text"] + obs = P["objects"] + for o in obs: + if o["kind"] in FRUIT and not o.get("contents") and o["count"] in (2, 4): + w = o.get("word") or o["kind"] + if not re.search(_NUMW + re.escape(w[:4]), t): + o["count"] += 1 + trace.append("still: %d loose %s -> %d (odd count)" % (o["count"] - 1, o["kind"], o["count"])) + if len(obs) == 1 and obs[0].get("contents") and obs[0]["contents"]["kind"] in FRUIT and \ + obs[0]["kind"] in ("bowl", "basket", "plate"): + ck = obs[0]["contents"] + obs.append({"kind": ck["kind"], "count": 2, "color": ck.get("color"), "contents": None, "material": None, + "word": ck["kind"]}) + trace.append("still: two %s rolled out in front of the %s (3 units, odd)" % (ck["kind"], obs[0]["kind"])) + + def arrange(objs, rng, light_side): """triangle: main container centre-back, the tallest back and off-centre away from the light, small things in front overlapping, one loose fruit rolled forward""" @@ -1412,11 +1449,21 @@ def arrange(objs, rng, light_side): # small things: front, alternating sides, overlapping the main thing's front side = light_side fr = sorted(rest, key=lambda o: -o.r) + uneq = on_th("th_group") and len(fr) >= 2 + if uneq: + # rule (w19 things th_group, SL3 + R10): no mirror pairs - the flanking things sit at unequal distances (ratio + # 1.3-2.0) and depths, and half the time two of them gather on the same side (w16_38: a symmetric row) + same = rng.random() < .5 + reach = [rng.uniform(.1, .3), rng.uniform(.95, 1.25)] + rng.shuffle(reach) for i, o in enumerate(fr): for tries in range(40): if o.kind in ("book",) and o.prio >= 3: x = main.X - side * (main.r + o.r) * .9 z = main.Z - o.r * .3 + elif uneq and i < 2: + x = main.X + side * (main.r * reach[i] + o.r * (.6 + .9 * (same and i == 1)) + tries * .4) + z = main.Z + main.r * (.35 + .75 * (reach[i] < .5)) + o.r * .3 + tries * .15 # the near-centre one comes forward, overlapping else: x = main.X + side * (main.r * rng.uniform(.3, 1.0) + o.r * .6 + tries * .4) z = main.Z + main.r * rng.uniform(.55, 1.0) + o.r * .3 + tries * .15 @@ -1426,7 +1473,8 @@ def arrange(objs, rng, light_side): side = -side o.X, o.Z = x, z placed.append(o) - side = -side + if not (uneq and same and i == 0): + side = -side for o in objs: o.yaw = rng.uniform(-.5, .5) if o.kind in ("pitcher", "teapot") and o.X > 0: @@ -1435,11 +1483,17 @@ def arrange(objs, rng, light_side): pass -def _bg_colours(P, rng, candle): +def _bg_colours(P, rng, candle, subjL=None): """wall + table colours: a light warm wall under window light, or a dark backdrop (chiaroscuro); candle = dark""" dark = candle or P.get("time") == "night" or rng.random() < .45 if P.get("window") and not candle and P.get("time") != "night": dark = dark and rng.random() < .4 # a window in the wall: mostly a light room + if subjL is not None and not candle and P.get("time") != "night" and not P.get("window"): + # rule (w19 things th_ground, R16 + copy_room S2/G1): the ground opposes the subject. The backdrop is no longer a + # coin flip: a pale or mid subject (lemons, white roses, oranges, porcelain; albedo luma >= 95) gets the dark + # ground (Chardin, Fantin-Latour: 2-3 value steps below the lit objects; S2 >= 40 L apart), a dark subject (red + # roses, a wine bottle, plums) the light one. Flipping only the wall cost .841 -> .310 in copy_room's ablation. + dark = subjL >= 95 if re.search(r"\b(?:counter|worktop|countertop|kitchen)\b", P["text"]) and not candle: dark = False if dark: @@ -1453,6 +1507,8 @@ def _bg_colours(P, rng, candle): top = _ccol(tm) else: top = np.array(rng.choice([(140, 92, 55), (120, 78, 48), (160, 115, 70), (100, 70, 50)]), float) + if P.get("board"): + top = np.array(rng.choice([(196, 146, 92), (182, 130, 80), (210, 165, 112)]), float) # a pale end-grain board if P.get("sill"): top = np.array((228, 224, 214), float) if re.search(r"\b(?:counter|worktop|countertop)\b", P["text"]): @@ -1498,6 +1554,8 @@ def _paint(P, R, seed, renderer, trace): light_side = -1 if rng.random() < .6 else 1 # the window: left more often (the classic) if P.get("window"): light_side = light_side + if on_th("th_group"): + _odd_group(P, trace) objs = build_objects(P, rng, nz) if not objs: return None @@ -1505,26 +1563,73 @@ def _paint(P, R, seed, renderer, trace): for o in objs: o.light_side = light_side phi = math.radians(rng.uniform(19, 25)) - sphi, cphi = math.sin(phi), math.cos(phi) - # --- frame the group: bounds in camera space - xs_ = [o.X - o.r for o in objs] + [o.X + o.r for o in objs] - ytop = max(o.h * cphi - (o.Z - o.r) * sphi for o in objs) - ybot = min(-(o.Z + o.r) * sphi for o in objs) - gw = max(xs_) - min(xs_) - gh = ytop - ybot - s = min(W * .74 / max(gw, 1), H * .66 / max(gh, 1)) - cx = W / 2 - s * (max(xs_) + min(xs_)) / 2 drape = bool(P.get("cloth")) - # rule: with a cloth the table edge comes up so the drape shows (its folds are half the picture's interest) - cy = H * (.72 if drape else .80) + s * ybot # the front of the group - zf = max(o.Z + o.r for o in objs) + 2.5 + 4.0 * rng.random() * (not drape) # front edge of the table - lim = .8 if drape else .93 - if cy + s * zf * sphi > H * lim: - zf = (H * lim - cy) / (s * sphi) - zf = max(zf, max(o.Z + o.r * .6 for o in objs)) - yb_target = H * rng.uniform(.4, .5) - zb = (yb_target - cy) / (s * sphi) # wall - zb = min(zb, min(o.Z - o.r for o in objs) - 1.5) + thg, tht = on_th("th_group"), on_th("th_table") + if thg or tht: # (w19 things) the knob path draws its own choices once, so the eye can be lowered and re-framed + fill_, off_, cyf_ = rng.uniform(.72, .80), rng.uniform(.07, .11), rng.uniform(.84, .88) + zfr_, ybf_ = rng.random(), rng.uniform(.62, .72) + for _try in range(5): + sphi, cphi = math.sin(phi), math.cos(phi) + # --- frame the group: bounds in camera space + xs_ = [o.X - o.r for o in objs] + [o.X + o.r for o in objs] + ytop = max(o.h * cphi - (o.Z - o.r) * sphi for o in objs) + ybot = min(-(o.Z + o.r) * sphi for o in objs) + gw = max(xs_) - min(xs_) + gh = ytop - ybot + s = min(W * .74 / max(gw, 1), H * .66 / max(gh, 1)) + cx = W / 2 - s * (max(xs_) + min(xs_)) / 2 + # rule: with a cloth the table edge comes up so the drape shows (its folds are half the picture's interest) + cy = H * (.72 if drape else .80) + s * ybot # the front of the group + if thg: + # rule (w19 things, R9/S3): the group fills the frame - 0.75-0.95 of the width (copy_room S3: Fantin-Latour .89, + # Copy A .31), a tall bouquet may reach 0.05-0.1 H from the top rather than shrink the group; the star sits off + # the centre line (Interlochen: never the focal point in the centre; things.md SL4 0.28-0.45 / 0.55-0.72 W) + s = min(W * fill_ / max(gw, 1), H * (.70 if drape else .72) / max(gh, 1)) # heaps, grapes and spouts overhang the footprint + main = max(objs, key=lambda o: (o.prio, o.r)) + x0g, x1g = min(xs_), max(xs_) + cx = W / 2 - s * (x1g + x0g) / 2 + sx = (cx + s * main.X) / W + if abs(sx - .5) < .07: # the star on the centre line: slide the group (room left at either frame edge >= .06 W) + want = .5 - light_side * off_ # away from the window: the light side keeps the open space + dx = (want - sx) * W + lo, hi = W * .06 - (cx + s * x0g), W * .94 - (cx + s * x1g) # spouts and handles reach past the footprint + cx += min(max(dx, lo), hi) + if thg or tht: # S3: the group's contact line sits at 0.85-0.93 H + cy = H * (.74 if drape else cyf_) + s * ybot + if not (thg or tht): + zf = max(o.Z + o.r for o in objs) + 2.5 + 4.0 * rng.random() * (not drape) # front edge of the table + else: + zf = max(o.Z + o.r for o in objs) + 2.5 + 4.0 * zfr_ * (not drape) + lim = .8 if drape else .93 + if cy + s * zf * sphi > H * lim: + zf = (H * lim - cy) / (s * sphi) + zf = max(zf, max(o.Z + o.r * .6 for o in objs)) + if not (thg or tht): + yb_target = H * rng.uniform(.4, .5) + else: + yb_target = H * (ybf_ if tht else ybf_ - .22) # th_group alone keeps master's .40-.50 + zb = (yb_target - cy) / (s * sphi) # wall + zb = min(zb, min(o.Z - o.r for o in objs) - 1.5) + if not tht: + break + # rule (w19 things th_table, R8/S4): the table's back edge sits low, 0.62-0.72 H from the top (Fantin-Latour .70, + # Kalf and Renoir .62-.75; copy_room S4), never at mid height (R8 bans 0.42-0.58). A deep group pushes the wall + # back and the edge up: then the eye comes down (a lower camera, flatter table and ellipses; eye ~0.4 H in S4) + # and the group is framed again, down to 12 deg (lower opens no bowl: SL13) + # rule (R10, tangents): the back edge never runs through an object's top (the vase neck on the edge, copy_room + # A01): an edge within 3% H of a top is a reason to lower the eye again too + ye = cy + s * zb * sphi + tang = any(abs(ye - (cy - s * (o.h * cphi - o.Z * sphi))) < H * .03 for o in objs) + if (ye >= H * .60 and not tang) or drape or setting in ("sill", "shelf") or phi < math.radians(15): + break + phi *= .8 + if tht: + for _ in range(2): # a tangent left over: the edge moves up by 6% H (the wall can only go back), not into .42-.58 + ye = cy + s * zb * sphi + tops = [cy - s * (o.h * cphi - o.Z * sphi) for o in objs] + if not any(abs(ye - t) < H * .03 for t in tops) or ye - H * .06 < H * .58: + break + zb -= H * .06 / (s * sphi) if setting in ("sill", "shelf"): # a ledge: the wall (and the window) stand right behind the things zb = min(o.Z - o.r for o in objs) - 1.2 zf = min(zf, max(o.Z + o.r for o in objs) + 1.5) @@ -1541,10 +1646,37 @@ def _paint(P, R, seed, renderer, trace): o.draw(G, xs, oid, o) oid += 100 cloth = P.get("cloth") - wall, top, dark = _bg_colours(P, rng, candle) + subjL = None + if on_th("th_ground"): + Cs = G.arrays()[2] + if len(Cs): + subjL = float(np.percentile(Cs @ np.array([.2126, .7152, .0722]), 75)) # the lit star part, not the stems + wall, top, dark = _bg_colours(P, rng, candle, subjL) if cloth: _cloth(G, cloth, objs, zf, zb, s, cx, W, xs, rng, nz, light_side) Pw, Nw, Cw, Mw, Iw = G.arrays() + if thg and len(Pw): + # rule (w19 things th_group, R9: never touch the frame): the footprint radii miss what overhangs them (a bunch of + # grapes lying on its side, spouts, handles, a high heap); fit the real projected samples inside 0.04-0.96 W and + # below 0.04 H - slide first, shrink about the contact line only if sliding is not enough (s only gets smaller, + # so the splat density stays) + _o = np.isin(Iw // 100, [o.oid // 100 for o in objs]) & (Iw >= 10) # the things, not the cloth + _P = Pw[_o] if _o.any() else Pw + _x = cx + s * _P[:, 0] + _y = cy - s * (_P[:, 1] * cphi - _P[:, 2] * sphi) + x0_, x1_, y0_ = float(_x.min()), float(_x.max()), float(_y.min()) + k_ = min(1.0, (W * .92) / max(x1_ - x0_, 1), (cy - H * .04) / max(cy - y0_, 1)) + if k_ < 1.0: + xm_ = (x0_ + x1_) / 2 + cx = xm_ + (cx - xm_) * k_ + s *= k_ + x0_, x1_ = xm_ + (x0_ - xm_) * k_, xm_ + (x1_ - xm_) * k_ + if x0_ < W * .04: + cx += W * .04 - x0_ + elif x1_ > W * .96: + cx -= x1_ - W * .96 + if k_ < 1.0 or x0_ < W * .04 or x1_ > W * .96: + trace.append("still: group fitted inside the frame (scale x%.2f)" % k_) # --- light Ld = _nrm([light_side * .78, .62, .5]) if setting == "sill": @@ -1595,11 +1727,15 @@ def _paint(P, R, seed, renderer, trace): board = np.floor((zf - Zt) / 9.0) seam = ((zf - Zt) % 9.0) < .35 tk = .9 + .14 * gr + .05 * ((board * 7) % 3) / 2 + if P.get("board"): + seam = np.zeros_like(seam) # one board, no planks if P.get("sill") or (P.get("table_mat") or "") in ("marble", "stone") or setting == "counter": tk = .97 + .03 * gr seam = np.zeros_like(seam) GC[on_table] = (top * (tk * np.where(seam, .78, 1.0))[..., None])[on_table] plaster = .94 + .1 * nz(xc * .15, Yw * .15) + .04 * nz(xc * .9, Yw * .9) + if not smooth and _EXP.get("md_pxramp", "0") != "0": # wave 19 media (md_pxramp): pixel walls are bands, not blotches + plaster = plaster.mean() + float(_EXP.get("md_pxplaster", .25)) * (plaster - plaster.mean()) GC[on_wall] = (wall * plaster[..., None])[on_wall] Ytop = (cy / s) / cphi + zb * sphi / cphi # the wall height seen at the top of the frame ysb = min(38.0, Ytop * .5) diff --git a/pydraw/thumbs.py b/pydraw/thumbs.py new file mode 100644 index 0000000000000000000000000000000000000000..523c22fad13c7271780491af9cf33a3599d0928b --- /dev/null +++ b/pydraw/thumbs.py @@ -0,0 +1,794 @@ +"""Thumbnail search (wave 19, compose lane): plan the frame before drawing it. + +Rules R7-R11 of docs/research19/SYNTHESIS.md (composition.md A5/A6/E1/E2/H1/H2/T1/T2/G1/J1, copy_scene.md G1-G3/G7, +copy_room.md S3/S4, copy_land.md L7/L8, compute.md R4/R5). Runs at the end of layout(), after the wave-13 director. + +R7 cmp_thumbs generate 20-60 framings of the laid-out boxes (camera height x dolly x tilt x side), rasterise each as a + 64 px flat value mask, score with the rules below + director.score's box terms (about 1-2 ms each), + keep the winner. Every move is a camera move, so perspective stays consistent: + camera height c: each grounded group's distance below the horizon x c, sizes kept (y - y0 = f cam / d) + dolly s: everything scales about (cx, horizon), as director._xf (nearer / farther) + tilt dy: everything and the horizon move together (the frame slides over the world) + pan dx: the subject group (or everything) slides sideways +R8 cmp_horizon horizon / floor line never in 0.42-0.58 H; sky-led prompts put it at 0.62-0.75 (the sky gets two thirds), + ground-led at 0.25-0.40 (composition H1; copy_scene G2: 0.39 and 0.69 measured in the two references). +R9 cmp_place a scene with an animal / person in a named outdoor setting: subject group 0.20-0.32 H tall (composition + E1 0.18-0.35, copy_scene G1 0.13-0.25), width at most ~0.45 W, centroid at 0.33-0.45 W or its mirror + (copy_scene G3 0.38-0.41 measured; composition A6 thirds 0.28-0.40), lead room in front (E2 >= 1.5x), + the horizon above the subject's top by about 0.3 of its height (G2: -0.29 / -0.30 measured), a secondary + group on the other side as counterweight (G3 / Poore steelyard, A5). Landmarks (lighthouse, barn, cabin, + castle): 0.45-0.70 H (SYNTHESIS R9 50-80%; copy_graphic P10), off-centre. +R10 cmp_tangent the horizon keeps >= 2.5% H from any object's top or bottom; boxes of different groups overlap or keep + >= 3% W; nothing ends within 3% W of a frame side unless cut by >= 8% (composition T1, T2, H2). + cmp_repeat count > 1 copies get a size chain (CV >= 0.15) stepped back in depth and clustered spacing (CV >= 0.2) + instead of +-6% jitter on one ground line (composition G1, copy_land L8, compute R5). +R11 cmp_contact NOT IMPLEMENTED in round 1: the knob name is reserved. Contact shadows are drawn by formlight (plan lane) + and the pixel finish; the open gap is boats (a light hull stripe on water, copy_scene G7/G11). + +Knobs (PYDRAW_EXP), all default OFF: cmp_thumbs=1 turns on the search AND every rule knob not set to 0; +cmp_horizon=1 / cmp_place=1 / cmp_tangent=1 alone apply that rule as one deterministic candidate (no search). +cmp_room=1 (separate, never implied by cmp_thumbs) lets the search move a room's floor line too. +Pure arithmetic on boxes and a 64 px numpy raster; no renders, no models. +""" +import math +import os + +import numpy as np + +KNOBS = ("cmp_thumbs", "cmp_horizon", "cmp_place", "cmp_tangent", "cmp_repeat", "cmp_contact") + +# prompt words that make the sky the subject (composition H1: sunset, sunrise, storm, rainbow, moon, clouds) +SKY_WORDS = {"sunset", "sunrise", "dawn", "dusk", "storm", "stormy", "rainbow", "moon", "moonlit", "clouds", "cloudy", + "sky", "stars", "starry", "aurora", "twilight", "thunderstorm", "lightning"} +LANDMARK_WORDS = ("lighthouse", "barn", "cabin", "castle", "house", "cottage", "windmill", "tower", "church", "temple", + "hut", "farmhouse", "mill", "chapel", "palace") +OUTDOOR = {"field", "park", "farm", "mountains", "forest", "snow", "desert", "savanna", "beach", "water", "street", + "jungle", "swamp", "arctic", "volcanic", "meadow", "garden"} +SKY_BODIES = {"sun", "moon", "full moon", "crescent moon", "star", "stars", "cloud", "rainbow", "planet"} + +# numeric ranges (each from the cited reports; first values to calibrate) +DEAD = (.42, .58) # composition H1 / SYNTHESIS R8 +SKY_BAND = (.62, .75) # composition H1 (sky is the subject) +GROUND_BAND = (.25, .40) # composition H1 .25-.38, copy_scene G2 .39 (snow ref) +ROOM_BAND = (.60, .70) # floor line: composition H1 / A-35 ".68", copy_room S4 table edge .62-.75 +SCENE_H = (.20, .32) # composition E1 .18-.35, copy_scene G1 .13-.25 (bbox height / H); upper part of + # the union because a 192 px pixel grid needs ~45 px to read a figure (looked, round 1) +SCENE_PREF = .27 +PERSON_H = (.30, .44) # a person (or a person doing a named action: walking a dog, flying a kite) never +PERSON_PREF = .36 # below ~0.25 H visible: below that the action does not read at 384 px (lead, round 1) +SCENE_W = .45 # copy_scene G1 width <= 0.4 W (+ a little for side views) +LANDMARK_H = (.45, .70) # SYNTHESIS R9 hero building 50-80%; copy_graphic lighthouse .55-.6 +SLOT = (.33, .45) # copy_scene G3 .33-.45 (refs .38-.41), composition A6 thirds .28-.40 +EYE_ABOVE = (1.15, 1.30, 1.45) # (feet - horizon) / subject height: horizon 0.15-0.45 subject heights above its top + # (copy_scene G2 measured 0.29 / 0.30; 1.15 for standing people, Loomis heads rule) +EYE_LOW = (.12, .22) # sky-led scene: a low camera puts the horizon on the legs, the figure against the sky + # (composition H1/H3 "a low camera puts it at 0.65-0.80 on the legs") +C_MAX = 2.2 +TAN_Y = .025 # composition H2 / T2: 2.5% H +TAN_X = .03 # composition T1 / T2: 3% W + + +def _ev(): + return dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + + +def on(name, ev=None): + ev = _ev() if ev is None else ev + v = ev.get(name) + if v is not None: + return v == "1" + return name != "cmp_thumbs" and ev.get("cmp_thumbs", "0") == "1" + + +def any_on(ev=None): + ev = _ev() if ev is None else ev + return any(on(k, ev) for k in KNOBS) + + +# --------------------------------------------------------------------------------------------------------------- +# geometry +def _box(it): + return (it.x - it.w / 2, it.y - it.h, it.x + it.w / 2, it.y) + + +def _alive(it): + return bool(it.info.get("animal")) or it.concept == "person" + + +def _skybody(it): + return it.concept in SKY_BODIES or (it.info.get("row") == "sky" and getattr(it, "bound", None) is None + and it.pose == "flying" and not _alive(it)) + + +def _landmark(it): + return any(w in it.concept for w in LANDMARK_WORDS) and float(it.info.get("height", 1) or 1) >= 3.0 + + +def _treey(it): + return any(w in it.concept for w in ("tree", "pine", "palm", "oak", "willow", "birch", "maple", "bush")) + + +CHILD_WORDS = {"child", "kid", "boy", "girl", "children", "kids", "boys", "girls", "toddler", "schoolgirl", "schoolboy"} + + +def _vis(group, boxes): + """drawn height / box height of a group: a child is drawn at ~0.64 of its person box (director._frame_under)""" + tall = max(group, key=lambda it: boxes[id(it)][3]) + return .64 if tall.concept == "person" and getattr(tall, "word", "") in CHILD_WORDS else 1.0 + + +def _size_range(rd): + if rd["kind"] == "scene": + return PERSON_H if rd["person"] else SCENE_H + return LANDMARK_H if rd["kind"] == "landmark" else None + + +PERSON_FLOOR = .30 # a person's own visible height never below this (lead round 1: the action must read at 384 px) + + +def _person_h(group, boxes): + ps = [it for it in group if it.concept == "person"] + if not ps: + return 0.0 + it = max(ps, key=lambda o: boxes[id(o)][3]) + return boxes[id(it)][3] * (.64 if getattr(it, "word", "") in CHILD_WORDS else 1.0) + + +class Frame: + """one candidate: per-item (x, y, h, w) after the camera move + the horizon""" + __slots__ = ("boxes", "y0", "desc") + + def __init__(self, boxes, y0, desc): + self.boxes, self.y0, self.desc = boxes, y0, desc + + +def _state(placed): + return {id(it): (it.x, it.y, it.w, it.h) for it in placed} + + +def _apply(placed, st, y0): + """write a candidate's boxes back (with the side geometry: ground_y / cords / limbs) through director._xf""" + from .director import _xf + for it in placed: + x, y, w, h = st[id(it)] + s = h / max(it.h, 1e-6) if it.h else 1.0 + # _xf scales about (ax, ay) then translates: choose the anchor so the box lands exactly on (x, y, h) + if abs(s - 1) < 1e-9: + _xf(it, 1.0, 0, 0, dx=x - it.x, dy=y - it.y) + else: + ax = (x - s * it.x) / (1 - s) + ay = (y - s * it.y) / (1 - s) + _xf(it, s, ax, ay) + it.x, it.y, it.w, it.h = x, y, w, h # (exact, no float drift) + if hasattr(it, "view"): + it.view = None + return y0 + + +# --------------------------------------------------------------------------------------------------------------- +# the scene's reading: what is the subject group, what kind of shot, which horizon band +def read_scene(insts, scene, W, H, y0): + from .director import _root, _groups + placed = [it for it in insts if hasattr(it, "x") and hasattr(it, "h") and it.h > 0] + main = [it for it in placed if not it.implicit] + if not main: + return None + subj = main[0] + groups = _groups(placed) + sroot = _root(subj) + sgroup = next((g for g in groups if any(it is subj for it in g)), [subj]) + # the body of the group: what stands (a kite or balloon held up in the sky does not count for size / placement) + body = [it for it in sgroup if it is sroot or not (it.pose == "flying" or it.info.get("row") == "sky")] or sgroup + if any(_alive(it) for it in body): + # a backdrop bound to the creature ("in front of a castle", "under a big tree") is setting, not body + body = [it for it in body if _alive(it) or not (it.info.get("row") == "back" and float(it.info.get("height", 1) or 1) > 3) + or getattr(it, "held_by", None) is not None or getattr(it, "worn_by", None) is not None] or body + place = scene.get("place") + words = set(str(scene.get("text", "")).lower().replace(",", " ").split()) + sky_led = bool(words & SKY_WORDS) or scene.get("time") in ("sunset", "sunrise", "dawn", "dusk") and bool( + words & {"sunset", "sunrise", "dawn", "dusk"}) + from .scenes import INDOOR + indoor = place in INDOOR + alive = any(_alive(it) for it in sgroup) + if indoor: + kind = "room" # (the floor line moves whatever the subject hangs or sits on) + elif sroot.pose == "flying" or getattr(sroot, "wall_hung", False): + kind = "none" + elif place in OUTDOOR and alive: + kind = "scene" + elif place in OUTDOOR and _landmark(sroot): + kind = "landmark" + elif place in OUTDOOR: + kind = "land" + else: + kind = "none" + # a named setting: the prompt's own place word, or a named feature (river, path, lake, hill...) + setting_things = any(it.info.get("row") == "back" and not any(it is o for o in body) for it in placed) + return dict(named=bool(scene.get("_place_named", True)) or bool(scene.get("features")) or setting_things, + person=any(it.concept == "person" for it in body), + placed=placed, subj=subj, sroot=sroot, sgroup=body, fullgroup=sgroup, groups=groups, place=place, sky_led=sky_led, + kind=kind, alive=alive, features=list(scene.get("features") or ())) + + +def _gbox(boxes, items): + bs = [boxes[id(it)] for it in items] + x0 = min(b[0] - b[2] / 2 for b in bs) + x1 = max(b[0] + b[2] / 2 for b in bs) + y_0 = min(b[1] - b[3] for b in bs) + y1 = max(b[1] for b in bs) + return x0, y_0, x1, y1 + + +# --------------------------------------------------------------------------------------------------------------- +# candidate generation: camera moves on the whole picture +def _grounded_roots(rd): + from .director import _root + out = [] + for g in rd["groups"]: + r = _root(g[0]) + if r.pose == "flying" or getattr(r, "wall_hung", False) or _skybody(r): + continue + out.append((r, g)) + return out + + +def make(rd, st0, y0, W, H, c=1.0, s=1.0, yh=None, xt=None, pan_all=True): + """one framing. c: camera height factor; s: dolly scale about (cx, y0); yh: horizon target (frac of H) by tilt; + xt: subject-group centroid target (frac of W) by pan""" + b = dict(st0) + roots = _grounded_roots(rd) + # camera height: each grounded group's distance below the horizon x c (sizes unchanged) + if abs(c - 1) > 1e-6: + # every thing that stands on the ground plane moves by its OWN depth (a castle behind the knight stays far); + # riders, held, worn and on-top things follow the thing they stand on + ids = {id(it) for r, g in roots for it in g} + + def anchor(it): + seen = set() + while id(it) not in seen: + seen.add(id(it)) + up = None + if getattr(it, "held_by", None) is not None or getattr(it, "worn_by", None) is not None \ + or it.rel in ("on", "riding") or getattr(it, "_carrier", None) is not None: + up = getattr(it, "bound", None) or getattr(it, "_carrier", None) + if up is None or not hasattr(up, "x"): + return it + it = up + return it + dys = {} + for it in rd["placed"]: + if id(it) not in ids: + continue + a = anchor(it) + if id(a) not in dys: + dys[id(a)] = (st0[id(a)][1] - y0) * (c - 1) if id(a) in st0 else 0.0 + x, y, w, h = b[id(it)] + b[id(it)] = (x, y + dys[id(a)], w, h) + # dolly: scale about (cx, horizon); sky bodies keep their size and place in the sky + if abs(s - 1) > 1e-6: + gx0, _, gx1, _ = _gbox(b, rd["sgroup"]) + cx = (gx0 + gx1) / 2 + for it in rd["placed"]: + if _skybody(it): + continue + x, y, w, h = b[id(it)] + b[id(it)] = (cx + (x - cx) * s, y0 + (y - y0) * s, w * s, h * s) + ny0 = y0 + if yh is not None: + dy = yh * H - y0 + ny0 = y0 + dy + for it in rd["placed"]: + x, y, w, h = b[id(it)] + if _skybody(it): + # a sun / moon stays in the sky: keeps its frame position unless the horizon would cover it + y = min(y, ny0 - H * .04) + b[id(it)] = (x, y, w, h) + continue + b[id(it)] = (x, y + dy, w, h) + if xt is not None: + gx0, _, gx1, _ = _gbox(b, rd["sgroup"]) + dx = xt * W - (gx0 + gx1) / 2 + ids = {id(it) for it in rd["fullgroup"]} + for it in rd["placed"]: + if pan_all and _skybody(it): + continue + if pan_all or id(it) in ids: + x, y, w, h = b[id(it)] + b[id(it)] = (x + dx, y, w, h) + return Frame(b, ny0, dict(c=c, s=s, yh=yh, xt=xt, pan_all=pan_all)) + + +def candidates(rd, st0, y0, W, H, ev, trace=None): + """the R7 grid (or one deterministic candidate per enabled rule when the search is off)""" + kind = rd["kind"] + search = on("cmp_thumbs", ev) + place_on, hor_on = on("cmp_place", ev), on("cmp_horizon", ev) + sroot, sgroup = rd["sroot"], rd["sgroup"] + gx0, gy0, gx1, gy1 = _gbox(st0, sgroup) + gh = max(1.0, gy1 - gy0) * _vis(sgroup, st0) + feet = st0[id(sroot)][1] + r0 = (feet - y0) / gh # how far below the horizon the subject's feet are, in subject heights + + # camera heights + cs = [1.0] + if place_on and kind == "scene" and r0 > .05: + standing_person = any(it.concept == "person" and it.pose in (None, "standing", "walking") for it in sgroup) + eyes = EYE_ABOVE[:2] if standing_person else EYE_ABOVE[1:] + if r0 < eyes[0] - .05 or not search: + cs = [e / r0 for e in (eyes if search else eyes[:1])] + if search and r0 >= eyes[0] - .05: + cs = [1.0] + [e / r0 for e in eyes if abs(e - r0) > .08] + if search and rd["sky_led"]: + cs += [e / r0 for e in EYE_LOW] + if search and 1.0 not in cs: + cs.append(1.0) + # never a crane shot: past ~2x the camera height the ground becomes an empty field (looked, round 1: knight) + cs = sorted({round(min(C_MAX, max(.12, c_)), 3) for c_ in cs}) + # dolly (subject size) + rng_h = _size_range(rd) + ss = [1.0] + if place_on and kind == "land": + # things without a creature (boats, trees): the camera may step back so a tilt does not cut them (T1) + k = min(W * .88 / max(1.0, gx1 - gx0), 1.0) + ss = sorted({1.0, round(k, 3), .85, .7}) if search else ([round(k, 3)] if (gx0 < 0 or gx1 > W) else [1.0]) + if place_on and rng_h: + tgt = (rng_h[0] + rng_h[1]) / 2 + hs = [tgt] if not search else [rng_h[0] + .2 * (rng_h[1] - rng_h[0]), tgt, rng_h[1] - .15 * (rng_h[1] - rng_h[0])] + if kind == "landmark": # a wide landmark (castle, barn) is sized by width too: at most ~0.7 W + asp = (gx1 - gx0) / gh + hs = [min(h_, .6 * W / H / max(asp, 1e-6)) for h_ in hs] + if kind == "scene": # a side view as wide as the frame: also size by width (copy_scene G1 width <= .4 W) + asp = (gx1 - gx0) / gh + sw = SCENE_W if not rd["person"] else .62 + hs = [max(rng_h[0], min(h_, sw * W / H / max(asp, 1e-6))) if asp * h_ * H > sw * W * 1.15 else h_ for h_ in hs] + if kind == "scene" and rd["person"]: + # size by the person's own drawn height too (a man on a bench: the bench must not set the scale) + ph = _person_h(sgroup, st0) + hs_p = [p_ * gh / max(1.0, ph) for p_ in ((PERSON_FLOOR + .02, PERSON_PREF) if search else (PERSON_PREF,))] + hs = sorted(set(hs) | set(hs_p)) + ss = sorted({round(max(.25, min(2.5, h_ * H / gh)), 3) for h_ in hs}) + if not rd["named"]: + # no named setting (a generic ground): the camera never steps back, it may only move in + ss = sorted({max(1.0, v) for v in ss}) + # horizon (tilt) + if kind == "room": + band = ROOM_BAND + elif rd["sky_led"]: + band = SKY_BAND + else: + band = GROUND_BAND + yhs = [None] + cur = y0 / H + if hor_on and kind != "none": + pts = [band[0] + .3 * (band[1] - band[0]), (band[0] + band[1]) / 2, band[1] - .2 * (band[1] - band[0])] + if not search: + # one rule: keep a good horizon, else the nearest point of the prompt's band + yhs = [None] if not (DEAD[0] <= cur <= DEAD[1]) else [min(pts, key=lambda p: abs(p - cur))] + else: + yhs = [None] + pts + if kind in ("scene", "landmark", "land"): # the other band too: the score may prefer it + ob = GROUND_BAND if band is SKY_BAND else SKY_BAND + yhs.append((ob[0] + ob[1]) / 2) + if kind == "room": + # a room: no camera-height change; the camera may step back (x.85 / x.72) so a lower floor line does not cut + # the furniture at the bottom of the frame + cs, ss = [1.0], ([1.0, .85, .72] if search else [1.0]) + # pan (side): the facing side gets the room (lead room) + xts = [None] + if place_on and kind in ("scene", "landmark"): + face = getattr(sroot, "facing", None) or getattr(rd["subj"], "facing", None) + mid = (SLOT[0] + SLOT[1]) / 2 + left, right = mid, 1 - mid + pref = [left, right] if face != "left" else [right, left] + xts = pref if search else pref[:1] + pans = [True, False] if (search and len(rd["groups"]) > 1) else [True] + out = [] + for c in cs: + for s in ss: + for yh in yhs: + for xt in xts: + for pa in pans: + if xt is None and not pa: + continue + out.append(make(rd, st0, y0, W, H, c, s, yh, xt, pa)) + return out + + +# --------------------------------------------------------------------------------------------------------------- +# the 64 px value thumbnail +def _plan_values(scene): + """flat values (0 dark .. 1 light) for sky, ground and things until the plan lane's light key lands + (value_light_colour 1 / Carlson: sky lightest, flat ground next, uprights darkest; night low key)""" + key = scene.get("_light_key") if isinstance(scene.get("_light_key"), dict) else None + if key and all(k in key for k in ("sky_v", "ground_v")): + return float(key["sky_v"]), float(key["ground_v"]), float(key.get("thing_v", .3)) + t = scene.get("time") or "day" + place = scene.get("place") + sky = {"night": .15, "sunset": .62, "sunrise": .66, "dawn": .66, "dusk": .45}.get(t, .82) + ground = {"night": .1, "sunset": .35, "sunrise": .4, "dawn": .42, "dusk": .25}.get(t, .5) + if place in ("snow", "arctic"): + ground = min(.92, ground + .4) + elif place in ("beach", "desert"): + ground = min(.85, ground + .2) + elif place == "water": + ground = sky * .85 + thing = .3 if t not in ("night", "dusk") else .06 + return sky, ground, thing + + +def _thing_value(it, base): + from .understanding import COLORS + c = COLORS.get(it.color) if isinstance(getattr(it, "color", None), str) else None + if c is None: + return base + L = (.2126 * c[0] + .7152 * c[1] + .0722 * c[2]) / 255.0 + return .5 * base + .5 * L + + +def raster(fr, rd, scene, W, H, n=64): + sky, ground, thing = _plan_values(scene) + img = np.empty((n, n), np.float32) + hy = int(round(fr.y0 / H * n)) + img[:max(0, min(n, hy))] = sky + img[max(0, min(n, hy)):] = ground + sub = np.zeros((n, n), bool) + sids = {id(it) for it in rd["sgroup"]} + # far things first (painter's order by depth, then by feet row) + order = sorted(rd["placed"], key=lambda it: (-(getattr(it, "d", 0) or 0), fr.boxes[id(it)][1])) + for it in order: + x, y, w, h = fr.boxes[id(it)] + x0, x1 = int(max(0, (x - w / 2) / W * n)), int(min(n, math.ceil((x + w / 2) / W * n))) + y_0, y1 = int(max(0, (y - h) / H * n)), int(min(n, math.ceil(y / H * n))) + if x1 <= x0 or y1 <= y_0: + continue + # an ellipse-ish silhouette proxy (boxes overstate area at the corners) + yy, xx = np.mgrid[y_0:y1, x0:x1] + cxp, cyp = x / W * n, (y - h / 2) / H * n + rx, ry = max(.5, w / W * n / 2), max(.5, h / H * n / 2) + m = ((xx + .5 - cxp) / rx) ** 2 + ((yy + .5 - cyp) / ry) ** 2 <= 1.15 + v = .9 if _skybody(it) else _thing_value(it, thing) + img[y_0:y1, x0:x1][m] = v + if id(it) in sids: + sub[y_0:y1, x0:x1] |= m + return img, sub + + +def thumb_terms(img, sub): + """pixel terms on the thumbnail: notan dark share (composition B3), subject ring contrast (B2 / copy_scene G7), + steelyard balance (A5)""" + t = {} + thr = .5 * (float(img.min()) + float(img.max())) + dark = float((img < thr).mean()) + if .45 <= dark <= .55: + t["notan50"] = .3 * (1 - abs(dark - .5) / .05) + if sub.any(): + from scipy import ndimage as ndi + ring = ndi.binary_dilation(sub, iterations=2) & ~sub + if ring.any(): + d = abs(float(np.median(img[sub])) - float(np.median(img[ring]))) + if d < .2: + t["ring"] = (.2 - d) * 2.0 + n = img.shape[0] + w = np.abs(img - img.mean()) + xs = (np.arange(n) + .5) / n + bx = float((w.sum(0) * xs).sum() / max(1e-6, w.sum())) - .5 + if abs(bx) > .08: + t["balance"] = (abs(bx) - .08) * 2.0 + return t + + +# --------------------------------------------------------------------------------------------------------------- +# rule terms on the boxes +def rule_terms(fr, rd, W, H, ev): + t = {} + kind = rd["kind"] + boxes = fr.boxes + yh = fr.y0 / H + sgroup, sroot = rd["sgroup"], rd["sroot"] + gx0, gy0, gx1, gy1 = _gbox(boxes, sgroup) + gh = gy1 - gy0 + if on("cmp_horizon", ev) and kind != "none": + if DEAD[0] < yh < DEAD[1]: + t["horizon_mid"] = 1.0 + (1 - abs(yh - .5) / .08) + band = ROOM_BAND if kind == "room" else SKY_BAND if rd["sky_led"] else GROUND_BAND + dist = max(0.0, band[0] - yh, yh - band[1]) + if kind == "scene": + # a creature in a sunset may take either band (silhouette on the sky, or seen from above on the ground); + # the prompt's own lead is only a preference + ob = GROUND_BAND if band is SKY_BAND else SKY_BAND + dist = min(dist, max(0.0, ob[0] - yh, yh - ob[1]) + .05) + if dist: + t["horizon_band"] = dist * 1.5 + if on("cmp_place", ev) and kind in ("scene", "landmark"): + rng_h = _size_range(rd) + hf = gh * _vis(sgroup, boxes) / H + if not (rng_h[0] <= hf <= rng_h[1]): + t["size"] = min(abs(hf - rng_h[0]), abs(hf - rng_h[1])) * 4.0 + sw = SCENE_W if not rd["person"] else .62 # (a person with a dog / cow: the pair may be wider) + if kind == "scene" and (gx1 - gx0) / W > sw: + t["width"] = ((gx1 - gx0) / W - sw) * 2.0 + if kind == "scene" and rd["person"]: + ph = _person_h(sgroup, boxes) / H + if ph < PERSON_FLOOR: + t["person_small"] = (PERSON_FLOOR - ph) * 8.0 + if kind == "scene": + t["size_pref"] = abs(hf - (PERSON_PREF if rd["person"] else SCENE_PREF)) * 1.0 + if gy0 < H * .06: + t["headroom"] = (.06 - gy0 / H) * 6 # a roof or a head kissing the top edge (composition E3 / T1) + if kind == "landmark" and (gx1 - gx0) / W > .75: + t["width"] = ((gx1 - gx0) / W - .75) * 2.0 + cx = (gx0 + gx1) / 2 / W + d = min(abs(cx - (SLOT[0] + SLOT[1]) / 2), abs(cx - (1 - (SLOT[0] + SLOT[1]) / 2))) + if not (SLOT[0] <= cx <= SLOT[1] or 1 - SLOT[1] <= cx <= 1 - SLOT[0]): + t["slot"] = d * 2.0 + face = sroot.facing if sroot.facing in ("left", "right") else (rd["subj"].facing if rd["subj"].facing in ("left", "right") else None) + if face and rd["alive"]: + front = (W - gx1) if face == "right" else gx0 + back = gx0 if face == "right" else (W - gx1) + if front < 1.5 * back: + t["leadroom"] = (1.5 * back - front) / W * 1.5 + if kind == "scene": + # G2: the horizon above the subject's top (0.3 of its height), never inside its middle 80% + top = gy0 + if gy0 + .1 * gh < fr.y0 < gy1 - .22 * gh: + t["eye_through"] = .6 + elif fr.y0 > top and not rd["sky_led"]: + t["eye_through"] = .2 + elif fr.y0 < top and rd["sky_led"]: + t["sky_sil"] = .08 # the sky is what the prompt is about: the figure stands against it (H1 / H3) + if "path" in (rd.get("features") or ()) and rd["alive"]: + # the path (scenes.py: centre .55 - .1 sin(2.5 t), half width .005 + .16 t) runs under the walker + tt = max(0.0, min(1.0, (gy1 - fr.y0) / max(1.0, H - fr.y0))) + pcx, half = .55 - .1 * math.sin(2.5 * tt), .005 + .16 * tt + gcx = (gx0 + gx1) / 2 / W + off = max(0.0, abs(gcx - pcx) - half) + if off: + t["off_path"] = off * 3 + if gy1 > H * .95: + t["feet_low"] = (gy1 / H - .95) * 6 + # counterweight: another grounded group on the other side of the centre (G3 / A5) + others = [(r, g) for r, g in _grounded_roots(rd) if not any(it is rd["subj"] for it in g)] + if others: + side = 1 if (gx0 + gx1) / 2 < W / 2 else -1 + ok = False + for r, g in others: + ox0, _, ox1, _ = _gbox(boxes, g) + ocx = (ox0 + ox1) / 2 + if (ocx - W / 2) * side > W * .08: + ok = True + if not ok: + t["counterweight"] = .15 + if on("cmp_tangent", ev) or on("cmp_place", ev): + # crops and frame tangents (T1): every grounded thing either keeps 3% W of air or is cut by >= 8% + for it in rd["placed"]: + if _skybody(it): + continue + x, y, w, h = boxes[id(it)] + k = 3.0 if any(it is o for o in sgroup) else 1.0 + for e_in, size in (((x - w / 2), w), (W - (x + w / 2), w)): + if e_in < 0: + cut = -e_in / max(1.0, size) + t["crop"] = t.get("crop", 0) + k * (cut if k > 1 else (.3 * cut if cut >= .08 else .08 - cut + .05)) + elif e_in < TAN_X * W and on("cmp_tangent", ev): + t["frame_tan"] = t.get("frame_tan", 0) + .15 * k + if y - h < 0: + t["crop"] = t.get("crop", 0) + k * 2 * (-(y - h)) / H + lim = 1.03 if rd["kind"] == "room" else 1.0 # (furniture may run off the bottom a little in a room) + if y > H * lim: + t["crop"] = t.get("crop", 0) + (y / H - lim) * 4 * max(k, 2.0 if rd["kind"] == "room" else k) + if on("cmp_tangent", ev): + # H2: the horizon off every object's top and bottom by >= 2.5% H + for it in rd["placed"]: + if _skybody(it): + continue + x, y, w, h = boxes[id(it)] + for e in (y - h, y): + if abs(e - fr.y0) < TAN_Y * H: + t["hz_tan"] = t.get("hz_tan", 0) + .25 + # T2: groups either overlap by >= 3% W or keep a gap of >= 3% W + from .director import _root + roots = _grounded_roots(rd) + for i, (ra, ga) in enumerate(roots): + ax0, ay0, ax1, ay1 = _gbox(boxes, ga) + for rb, gb in roots[i + 1:]: + bx0, by0, bx1, by1 = _gbox(boxes, gb) + if min(ay1, by1) < max(ay0, by0): + continue # no vertical overlap: they can't kiss sideways + gap = max(bx0 - ax1, ax0 - bx1) # > 0 gap, < 0 overlap + if -TAN_X * W < gap < TAN_X * W: + t["kiss"] = t.get("kiss", 0) + .2 + return t + + +def score(fr, rd, scene, W, H, ev, base_score=None): + terms = rule_terms(fr, rd, W, H, ev) + if on("cmp_thumbs", ev): + img, sub = raster(fr, rd, scene, W, H) + terms.update(thumb_terms(img, sub)) + # small preference for the layout's own decision (stay close to it) + d = fr.desc + move = abs(math.log(d["s"])) * .15 + abs(math.log(d["c"])) * .03 + (.03 if d["yh"] is not None else 0) + terms["move"] = move + if base_score is not None: + terms["director"] = .5 * base_score(fr) + return sum(terms.values()), terms + + +# --------------------------------------------------------------------------------------------------------------- +def empty_horizon(scene, H, y0, trace): + """(cmp_horizon) a picture with nothing placed (a lake, hills, a desert): the horizon alone carries the composition; + move it out of the dead middle to the prompt's band (composition H1)""" + if not on("cmp_horizon") or scene.get("camera") in ("high", "low"): + return y0 + from .scenes import INDOOR + place = scene.get("place") + if place in INDOOR or place in ("sky", "space", "underwater", None): + return y0 + cur = y0 / H + if not (DEAD[0] <= cur <= DEAD[1]): + return y0 + words = set(str(scene.get("text", "")).lower().replace(",", " ").split()) + band = SKY_BAND if words & SKY_WORDS else GROUND_BAND + ny = band[1] - .2 * (band[1] - band[0]) if band is GROUND_BAND else band[0] + .3 * (band[1] - band[0]) + trace.append("thumbs: empty landscape - horizon %.2f -> %.2f (%s-led)" % (cur, ny, "sky" if band is SKY_BAND else "ground")) + return ny * H + + +def search(insts, scene, W, H, y0, trace): + """R7-R10 on the laid-out instances; returns the (maybe moved) horizon""" + ev = _ev() + if not any_on(ev): + return y0 + if on("cmp_repeat", ev): + try: + repeat(insts, scene, W, H, y0, trace) + except Exception as ex: # a composition rule must never take the picture down + trace.append("thumbs: repeat skipped (%s)" % str(ex)[:80]) + if not any(on(k, ev) for k in ("cmp_thumbs", "cmp_horizon", "cmp_place", "cmp_tangent")): + return y0 + if scene.get("framing") == "close" or scene.get("camera") in ("high", "low") or scene.get("style") == "abstract" \ + or scene.get("abstract_comp") or scene.get("shot") in ("close", "still"): + trace.append("thumbs: skipped (framing / camera asked)") + return y0 + if any(getattr(it, "side", None) for it in insts) or scene.get("arrange") == "stack": + trace.append("thumbs: skipped (the prompt placed things itself)") + return y0 + rd = read_scene(insts, scene, W, H, y0) + if rd is None or rd["kind"] == "none": + return y0 + if rd["kind"] == "room" and ev.get("cmp_room", "0") != "1": + # rooms (floor line .60-.70 + a camera step back) stay behind their own knob: round 1 looked mixed (a lower floor + # line leaves a big empty wall; things lane owns interiors) + return y0 + st0 = _state(rd["placed"]) + cands = candidates(rd, st0, y0, W, H, ev, trace) + if not cands: + return y0 + from .director import score as dscore + + def base(fr): + # the director's box terms on this framing (crop, headroom, thirds, lead room, tangents, overlap, balance) + _apply(rd["placed"], fr.boxes, fr.y0) + s, _ = dscore(rd["placed"], rd["subj"], W, H, fr.y0, scene.get("shot") or "medium") + return s + keep = Frame(st0, y0, dict(c=1.0, s=1.0, yh=None, xt=None, pan_all=True)) + cands = [keep] + [c for c in cands if c.desc != keep.desc] + scored = [] + for fr in cands: + s, terms = score(fr, rd, scene, W, H, ev, base) + scored.append((s, fr, terms)) + _apply(rd["placed"], st0, y0) + scored.sort(key=lambda t: t[0]) + s, fr, terms = scored[0] + s_keep = next(t for t in scored if t[1] is keep) + _apply(rd["placed"], fr.boxes, fr.y0) + for it in rd["placed"]: + if hasattr(it, "view"): + it.view = (W, H, fr.y0) + d = fr.desc + trace.append("thumbs: %s, %d candidates, best %.2f (layout's own %.2f): c=%.2f s=%.2f horizon %s x %s | %s" % ( + rd["kind"], len(cands), s, s_keep[0], d["c"], d["s"], "%.2f" % d["yh"] if d["yh"] is not None else "kept", + "%.2f" % d["xt"] if d["xt"] is not None else "kept", + " ".join("%s=%.2f" % kv for kv in sorted(terms.items()) if kv[1]))) + if os.environ.get("PYDRAW_THUMBS_LOG"): + for s_, fr_, t_ in scored[:8]: + trace.append("thumbs: %.2f %s %s" % (s_, fr_.desc, " ".join("%s=%.2f" % kv for kv in sorted(t_.items()) if kv[1]))) + scene["_cmp"] = dict(kind=rd["kind"], y0=fr.y0 / H, cands=len(cands), score=s, keep=s_keep[0], desc=d) + return fr.y0 + + +# --------------------------------------------------------------------------------------------------------------- +# R10 repetition with variation +CHAIN = (1.0, .66, .86, .74, .6, .8, .7, .56) # ratio chain: CV ~0.17-0.2 for 2-8 copies (composition G1 "1, .8, .65") + + +def _indoor(): + from .scenes import INDOOR + return INDOOR + + +def repeat(insts, scene, W, H, y0, trace): + """copies of one thing standing on one line (two sailboats, three houses, ducks) get unequal sizes, stepped back + in depth (scaled about the horizon, like director._xf: smaller = farther = higher), and clustered spacing + (gaps alternate tight / wide: spacing CV >= 0.2) instead of one size on one ground line""" + from .director import _root, _xf + import random + seed = (scene.get("_director") or {}).get("seed", 0) if isinstance(scene.get("_director"), dict) else 0 + rng = random.Random(seed * 31 + 7) + by_ent = {} + for it in insts: + if not hasattr(it, "x") or it.implicit or it.pose == "flying" or _skybody(it): + continue + if _root(it) is not it or getattr(it, "stacked", False) or getattr(it, "side", None): + continue + if scene.get("place") in _indoor(): + continue # (furniture is made in standard sizes: bookshelves and chairs in a room do not vary) + by_ent.setdefault(it.ent, []).append(it) + for ent, its in by_ent.items(): + if len(its) < 2 or len(its) > 8: + continue + e = (scene.get("entities") or [{}] * (ent + 1))[ent] if ent < len(scene.get("entities") or []) else {} + if e.get("family") or e.get("stack"): + continue + ys = [it.y for it in its] + if max(ys) - min(ys) > H * .12: + continue # already staged in depth + its = sorted(its, key=lambda it: it.x) + n = len(its) + cx0 = sum(it.x for it in its) / n + span0 = (its[-1].x + its[-1].w / 2) - (its[0].x - its[0].w / 2) + chain = list(CHAIN[:n]) + rest = chain[1:] + rng.shuffle(rest) + # the biggest goes on an off-centre slot (not the middle of a row: a centred big copy makes a symmetric pyramid) + slot = rng.choice([0, n - 1]) if n > 2 else rng.choice([0, 1]) + fac = rest[:slot] + [chain[0]] + rest[slot:] + hmax = max(it.h for it in its) + for it, f0 in zip(its, fac): + f = hmax * f0 / max(1e-6, it.h) # the chain sets the final heights (copies may come pre-staggered) + for o in insts: + if hasattr(o, "x") and _root(o) is it: + _xf(o, f, it.x, y0) + # clustered spacing: gaps alternate tight (a little overlap) and wide + gaps = [] + for i in range(n - 1): + mw = min(its[i].w, its[i + 1].w) + gaps.append((-.12 if i % 2 == (slot % 2) else rng.uniform(.5, 1.0)) * mw) + tot = sum(it.w for it in its) + sum(gaps) + x = cx0 - tot / 2 + newx = [] + for i, it in enumerate(its): + newx.append(x + it.w / 2) + x += it.w + (gaps[i] if i < n - 1 else 0) + # keep inside the frame + lo = min(nx - it.w / 2 for nx, it in zip(newx, its)) + hi = max(nx + it.w / 2 for nx, it in zip(newx, its)) + sh = max(W * .04 - lo, 0) - max(hi - W * .96, 0) + for it, nx in zip(its, newx): + dx = nx + sh - it.x + for o in insts: + if hasattr(o, "x") and _root(o) is it: + o.x += dx + for k in ("cord",): + pass + sizes = [it.h for it in its] + mu = sum(sizes) / n + cv = (sum((v - mu) ** 2 for v in sizes) / n) ** .5 / mu + trace.append("thumbs: %d %s varied (size CV %.2f, clustered spacing; was one size on one line, span %.0f)" % ( + n, its[0].concept, cv, span0)) + + +# --------------------------------------------------------------------------------------------------------------- +def geom_line(insts, scene, W, H, y0): + """a trace line for the measuring scripts (no behaviour): horizon and subject-group box as fractions""" + try: + rd = read_scene(insts, scene, W, H, y0) + if rd is None: + return "geom: y0=%.3f none" % (y0 / H) + b = _state(rd["placed"]) + x0, y_0, x1, y1 = _gbox(b, rd["sgroup"]) + xs = ";".join("%s:%.3f,%.3f,%.3f,%.3f" % (it.concept.replace(" ", "_"), (it.x - it.w / 2) / W, (it.y - it.h) / H, + (it.x + it.w / 2) / W, it.y / H) for it in rd["placed"]) + return "geom: y0=%.3f kind=%s subj=%.3f,%.3f,%.3f,%.3f items=%s" % (y0 / H, rd["kind"], x0 / W, y_0 / H, x1 / W, y1 / H, xs) + except Exception as ex: + return "geom: failed %s" % str(ex)[:60] diff --git a/pydraw/typography/__pycache__/__init__.cpython-310.pyc b/pydraw/typography/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4fd7526defe430224657afac4b8584fc87f1e6d Binary files /dev/null and b/pydraw/typography/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw/typography/__pycache__/understand.cpython-310.pyc b/pydraw/typography/__pycache__/understand.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf3b37ba854b5688e836e0f2f4a660a8fed11428 Binary files /dev/null and b/pydraw/typography/__pycache__/understand.cpython-310.pyc differ diff --git a/pydraw/understanding.py b/pydraw/understanding.py index 64002441747e257745ec5b1f12c853b1f7af1703..275223ef0aa85760948243ee7fea22d70e25966f 100644 --- a/pydraw/understanding.py +++ b/pydraw/understanding.py @@ -168,6 +168,8 @@ PART_ADJ = {"big", "large", "small", "little", "tiny", "long", "short", "pointy" OBJECT_PARTS = {"tire", "tires", "tyres", "rims", "rim", "hubcaps", "blades", "blade", "spokes", "sails", "sail", "handle", "handles", "lid", "strings", "keys", "buttons", "shutters", "chimney", "doors", "door", "windows", "roof", "frame", "stem", "petals", "trim", "stripe", "base"} +DOOR_OWNERS = {"wardrobe", "cabinet", "cupboard", "closet", "fridge", "refrigerator", "oven", "microwave", "dollhouse", "stove", + "dishwasher", "washing machine", "bookcase", "dresser", "locker", "safe", "cage"} # indoor things with their own doors SKIN_WORDS = {"dark": "dark", "black": "dark", "brown": "brown", "deep": "dark", "tan": "brown", "tanned": "brown", "olive": "brown", "fair": "light", "light": "light", "pale": "light", "white": "light", "rosy": "light"} # rule: "in the shape of X" / "shaped like X": shapeless stuff takes X's form; a solid object keeps its kind and gets X's look @@ -281,7 +283,8 @@ STYLES = {"watercolor": "watercolor", "watercolour": "watercolor", "sketch": "sk "gogh": "oil", "monet": "oil", "renoir": "oil", "rembrandt": "oil", "vermeer": "oil", "cezanne": "oil", "turner": "watercolor", "hokusai": "comic", "picasso": "pop", "dali": "oil", "klimt": "pop", "silhouette": "silhouette", "silhouetted": "silhouette", "shadow puppet": "silhouette", "futuristic": "neon", "scifi": "neon", "dystopian": "neon", "abstract": "abstract", "geometric": "abstract", "cubism": "pop", "cubist": "pop", "minimalist": "abstract", - "painting": "oil", "drawing": "sketch", "doodle": "sketch", "crayon": "pastel", "chalk": "pastel"} + "painting": "oil", "drawing": "sketch", "doodle": "sketch", "crayon": "pastel", "chalk": "pastel", + "threed": "smooth"} # wave 19: "3d render" -> the smooth-shading path until a 3D medium registers the phrase # Art styles / media / artists -> a painting algorithm in pydraw3d/paint.py (scene["art"]) plus the nearest style the # pixel renderer knows (scene["style"]). "m" = the word is also an object or material ("a clay pot", "a crayon"), @@ -681,6 +684,14 @@ def parse(text, trace): # 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", "") + if _language.ct("ct_3d"): + # wave 19 (content, bug fix, default on): "3d render" / "3-d" / "3 d model" is one style word, not the count 3 and + # a stray "d" ("a 3d render of a cat" drew three cats; research19 media R1/T1) + # routing "3d" to the smooth path is a behaviour change (ct_3droute, default off: the smooth path drops the mountain + # lake, scenes.py draws it in pixel only); by default the word is just no longer misread + text = re.sub(r"\b3\s?d\b", " threed " if _language.ct("ct_3droute") else " ", text) + if _language.ct("ct_words"): + text = re.sub(r"\bnight ?stands?\b", "bedside table", text) # wave 19: one word for the bedside table (see language.contract) 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) @@ -874,6 +885,12 @@ def parse(text, trace): part = "eyepatch" if patch else (BODY_PARTS.get(toks[j]) if j < n else None) ctx_ok = (pending_rel == "next_to" and pending_phrase[:1] == ("with",)) or attr_end in (i, i - 1) or last_noun_end == i \ or (i > 0 and toks[i - 1] in ("with", "has", "have", "its", "his", "her", "their", "and", "of")) or toks[i] in ("its", "his", "her", "their") + if part == "door" and _language.ct("ct_door"): + _down = _owner(scene, toks, i, j + 1, pre_ok=False) or scene["entities"][-1] + if CONCEPTS.get(_down["concept"], {}).get("setting") == "room" and _down["concept"] not in DOOR_OWNERS: + # wave 19 (content, bug fix, default on; copy_room G4): "a window and a door" - a window, lamp or bed has no + # door of its own, so the door is an object on the wall (it was dropped as a feature of the window) + part = None if part and ctx_ok and not (j + 1 < n and toks[j + 1] == "of") and (not match_noun(toks, j, fallback=False)[0] or ( toks[j] in OBJECT_PARTS and not _is_wearer(scene["entities"][-1]) and (pc or len(toks[i:j]) > 0 or ctx_ok))): # (an object's own part word wins over a same-named concept: "a fan with brown blades" are not swords) @@ -1533,6 +1550,13 @@ def parse(text, trace): continue if t in SETTINGS: k, v = SETTINGS[t] + if mods.get("color") and i > 0 and toks[i - 1] in COLORS and _language.ct("ct_color"): + # wave 19 (content, bug fix, default on; copy_land L15): "green mountains and white clouds" / "blue sky, sun and + # clouds": a colour right before a setting noun is that setting's colour (scene["setting_colors"]), never the + # next object's (it painted green clouds and blue clouds) + scene.setdefault("setting_colors", {})[t] = mods.pop("color") + mods.pop("color2", None) + trace.append("understand: colour '%s' binds to the setting '%s'" % (scene["setting_colors"][t], t)) # rule: a generic place word ("landscape", "scenery", "room") never overrides a specific one if k == "place" and scene.get("place") and t in ("landscape", "scenery", "room", "outdoors", "outside", "inside", "indoors", "hills"): i += 1 @@ -1663,6 +1687,10 @@ def parse(text, trace): # ("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 parts + try: + _language.contract(scene, trace) # wave 19 (content): the prompt is a contract (ct_* knobs) + except Exception as ex_: + trace.append("content: contract pass skipped (%s)" % ex_) if scene["unknown"]: trace.append("understand: not drawn, unknown words: %s" % ", ".join(scene["unknown"])) _imagine.post(scene, _iplan, trace) diff --git a/pydraw/world.py b/pydraw/world.py index 14a3aaa0595dd87a7fd11ceab225cdf1d941d84f..eea718a6837875daebd15efd833cc0ac1ede9c0a 100644 --- a/pydraw/world.py +++ b/pydraw/world.py @@ -2094,6 +2094,8 @@ def reflect(cv, ctx, scene, rng, y_top, y_bot, water=None, calm=None): if rough: return src = [[tuple(p) for p in cv.px[y]] for y in range(0, yt)] + from .nature import on as _nt_on + nt_water = _nt_on("nt_water") top_sky = sky_colors(scene)[0] offs = 0 band_left = 0 @@ -2117,7 +2119,13 @@ def reflect(cv, ctx, scene, rng, y_top, y_bot, water=None, calm=None): m = src[ym][xs] else: m = top_sky - m = (m[0] * .86, m[1] * .88, m[2] * .94) + if nt_water: + # rule (nature nt_water, nature.md W1-W2; Gurney): a reflection is darker than a light thing (-5..-15 + # L*) and lighter than a dark thing (+5..+10 L*); far water mirrors more (grazing), near less + yl = .3 * m[0] + .59 * m[1] + .11 * m[2] + m = (m[0] * .88, m[1] * .9, m[2] * .95) if yl > 90 else _mix(m, own, .18) + else: + m = (m[0] * .86, m[1] * .88, m[2] * .94) c = _mix(m, own, a) p = row[x] p[0], p[1], p[2] = c @@ -2144,6 +2152,12 @@ def shore_trees(cv, ctx, scene, rng, trace): keep = cv.tex_keep = set() sun_right = ctx.sun[0] >= W / 2 autumn = scene.get("season") == "autumn" + from . import nature as _nat + if _nat.on("nt_treeline"): # wave 19 (nature): far trees as 1-3 scalloped group masses, not a row of round bushes + cols = [(64, 116, 58)] if not autumn else [(206, 120, 50)] + ng, nb = _nat.treeline_groups(cv, ctx, scene, rng, keep, cols, night=scene.get("time") == "night") + trace.append("nature: far-shore trees as %d group masses (%d bumps)" % (ng, nb)) + return x = -rng.uniform(0, 6) * u k = 0 while x < W + 6 * u: diff --git a/pydraw3d/__pycache__/__init__.cpython-310.pyc b/pydraw3d/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9113f4505fc7532fd01deef349405ead50474ac7 Binary files /dev/null and b/pydraw3d/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/accel.cpython-310.pyc b/pydraw3d/__pycache__/accel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..672ea9582d10fcd5c905ecc416ef19e8c0ac4c3c Binary files /dev/null and b/pydraw3d/__pycache__/accel.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/light.cpython-310.pyc b/pydraw3d/__pycache__/light.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..565e0638de3c67a56b8d26bc975c6a7ba0762416 Binary files /dev/null and b/pydraw3d/__pycache__/light.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models.cpython-310.pyc b/pydraw3d/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d03822187cc7b37fd88cd69761f602c75042c863 Binary files /dev/null and b/pydraw3d/__pycache__/models.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_animals.cpython-310.pyc b/pydraw3d/__pycache__/models_animals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb1111597fcad20033f1f5e7e9e4e013d74f110a Binary files /dev/null and b/pydraw3d/__pycache__/models_animals.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_fire.cpython-310.pyc b/pydraw3d/__pycache__/models_fire.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e374c300aa041357023b1563a2901a50e973f7ef Binary files /dev/null and b/pydraw3d/__pycache__/models_fire.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_indoor.cpython-310.pyc b/pydraw3d/__pycache__/models_indoor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27f13b5cb6a03fb17bd7d1e117826ce6c97ebe5d Binary files /dev/null and b/pydraw3d/__pycache__/models_indoor.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_kitchen.cpython-310.pyc b/pydraw3d/__pycache__/models_kitchen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f42b6abf8627a763d5a9a0c086f2a891f6a6933 Binary files /dev/null and b/pydraw3d/__pycache__/models_kitchen.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_landmarks.cpython-310.pyc b/pydraw3d/__pycache__/models_landmarks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f68f798ce71fb9a48ed5cee154201d63d9802a Binary files /dev/null and b/pydraw3d/__pycache__/models_landmarks.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_person.cpython-310.pyc b/pydraw3d/__pycache__/models_person.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bc58a5b600c18bee2eb6f4f34c6bcf807f3dfa7 Binary files /dev/null and b/pydraw3d/__pycache__/models_person.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_sky.cpython-310.pyc b/pydraw3d/__pycache__/models_sky.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3010edf8c67e5e72c61b392da40c558831eec47b Binary files /dev/null and b/pydraw3d/__pycache__/models_sky.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/models_vehicles.cpython-310.pyc b/pydraw3d/__pycache__/models_vehicles.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c3d119879c343a78aeb9f5c67d0c0ad7fd95643 Binary files /dev/null and b/pydraw3d/__pycache__/models_vehicles.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/natural.cpython-310.pyc b/pydraw3d/__pycache__/natural.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b78b7d9393b2c8139c8b07f809e93621c7ab91e Binary files /dev/null and b/pydraw3d/__pycache__/natural.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/pose.cpython-310.pyc b/pydraw3d/__pycache__/pose.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f7e4ab6814bb42633b800b1cf4cb945fedfd42f Binary files /dev/null and b/pydraw3d/__pycache__/pose.cpython-310.pyc differ diff --git a/pydraw3d/__pycache__/sdf.cpython-310.pyc b/pydraw3d/__pycache__/sdf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae1027378988e95ea008ae174f729e614aa8a555 Binary files /dev/null and b/pydraw3d/__pycache__/sdf.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/__init__.cpython-310.pyc b/pydraw3d/families/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62f9fe7457ae7071a17b9fe4d6b98cbdeb4da0b8 Binary files /dev/null and b/pydraw3d/families/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/animals_other.cpython-310.pyc b/pydraw3d/families/__pycache__/animals_other.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd36137f9a9cc8f35e91a3fcbc0e530e1f098a70 Binary files /dev/null and b/pydraw3d/families/__pycache__/animals_other.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/animals_other_aquatic.cpython-310.pyc b/pydraw3d/families/__pycache__/animals_other_aquatic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f445b6c1191e6543ac98e93a0026a0d40042a083 Binary files /dev/null and b/pydraw3d/families/__pycache__/animals_other_aquatic.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/animals_other_inverts.cpython-310.pyc b/pydraw3d/families/__pycache__/animals_other_inverts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c27012c68601b804ea05e300fab3bb0b16934a8 Binary files /dev/null and b/pydraw3d/families/__pycache__/animals_other_inverts.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/animals_other_reptiles.cpython-310.pyc b/pydraw3d/families/__pycache__/animals_other_reptiles.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc42d90d9bc0e5c91f538d65fd017fee0f3c0fa1 Binary files /dev/null and b/pydraw3d/families/__pycache__/animals_other_reptiles.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/devices.cpython-310.pyc b/pydraw3d/families/__pycache__/devices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3281987078d25f2cc2f58e46c2bb16766918676c Binary files /dev/null and b/pydraw3d/families/__pycache__/devices.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/food.cpython-310.pyc b/pydraw3d/families/__pycache__/food.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2250bad61a77dd904477b2c3f3f1c82c767ae34e --- /dev/null +++ b/pydraw3d/families/__pycache__/food.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b051f12ec287c3ed64ba07c44623775e2d80d6d0fd8bc2c16e5be4c165372e9 +size 109648 diff --git a/pydraw3d/families/__pycache__/furniture.cpython-310.pyc b/pydraw3d/families/__pycache__/furniture.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6b247cbee09d857a62ed9356a128b8cf595adee Binary files /dev/null and b/pydraw3d/families/__pycache__/furniture.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/generic.cpython-310.pyc b/pydraw3d/families/__pycache__/generic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3e7b2dbdbc7e2ec28ef76770c23a6a3967c07a Binary files /dev/null and b/pydraw3d/families/__pycache__/generic.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/instruments.cpython-310.pyc b/pydraw3d/families/__pycache__/instruments.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3fd1c468db5255382844a6b7c576c44bb347e5b Binary files /dev/null and b/pydraw3d/families/__pycache__/instruments.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/mammals.cpython-310.pyc b/pydraw3d/families/__pycache__/mammals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61ca381d1f080a011684259014302702114b81a7 Binary files /dev/null and b/pydraw3d/families/__pycache__/mammals.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/nature.cpython-310.pyc b/pydraw3d/families/__pycache__/nature.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a4514aec1e69bf05fa40cd3b102789094a3c414 Binary files /dev/null and b/pydraw3d/families/__pycache__/nature.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/objects.cpython-310.pyc b/pydraw3d/families/__pycache__/objects.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2518b973ceb1880be03413049ee49ca08e052a82 --- /dev/null +++ b/pydraw3d/families/__pycache__/objects.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:269d0ee48628911e08d0ba4596c091a1aa75ff6cd31c9d2d8f4fbe53748cb51b +size 103111 diff --git a/pydraw3d/families/__pycache__/plants.cpython-310.pyc b/pydraw3d/families/__pycache__/plants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cbd567bcef88ea9524b1ee9255cf6b621352ad9 Binary files /dev/null and b/pydraw3d/families/__pycache__/plants.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/plants_produce.cpython-310.pyc b/pydraw3d/families/__pycache__/plants_produce.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3018bff218ed1daa0b59f7fdcc4ac399eaf5c387 Binary files /dev/null and b/pydraw3d/families/__pycache__/plants_produce.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/playthings.cpython-310.pyc b/pydraw3d/families/__pycache__/playthings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca5ed1fb0fa4106b376224f4128e6d53f7ddecf2 Binary files /dev/null and b/pydraw3d/families/__pycache__/playthings.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/strands.cpython-310.pyc b/pydraw3d/families/__pycache__/strands.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21dbec11d80aaa78d53ea9de653eeed0b89cfeed Binary files /dev/null and b/pydraw3d/families/__pycache__/strands.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/structures.cpython-310.pyc b/pydraw3d/families/__pycache__/structures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34145fa955a59f22beafff2ad9f468a70098937f Binary files /dev/null and b/pydraw3d/families/__pycache__/structures.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/tools.cpython-310.pyc b/pydraw3d/families/__pycache__/tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a3d69c9762c643518aa7e6866fe4a3e05449130 Binary files /dev/null and b/pydraw3d/families/__pycache__/tools.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/vehicles.cpython-310.pyc b/pydraw3d/families/__pycache__/vehicles.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..117452a5a189175c0b72bd0ebeefc70cbf54e81c Binary files /dev/null and b/pydraw3d/families/__pycache__/vehicles.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/vessels.cpython-310.pyc b/pydraw3d/families/__pycache__/vessels.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e13ff365f412b47f502440ecf503046b9afe1170 Binary files /dev/null and b/pydraw3d/families/__pycache__/vessels.cpython-310.pyc differ diff --git a/pydraw3d/families/__pycache__/z_sense_pins.cpython-310.pyc b/pydraw3d/families/__pycache__/z_sense_pins.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c43b0a0c03cf3de660cab400a58f875158d53d3 Binary files /dev/null and b/pydraw3d/families/__pycache__/z_sense_pins.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/__init__.cpython-310.pyc b/pydraw3d/sim/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26a5e7059c19dca0c0e2db73a481c3ce51bf17e1 Binary files /dev/null and b/pydraw3d/sim/__pycache__/__init__.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/build.cpython-310.pyc b/pydraw3d/sim/__pycache__/build.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3eb086534104caa61b0489d26005e69acfcafad Binary files /dev/null and b/pydraw3d/sim/__pycache__/build.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/cloth.cpython-310.pyc b/pydraw3d/sim/__pycache__/cloth.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9be93a2e07ba65632e398bb509d35f261658c9f6 Binary files /dev/null and b/pydraw3d/sim/__pycache__/cloth.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/composites.cpython-310.pyc b/pydraw3d/sim/__pycache__/composites.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7867a37ae6bfb4bb9bf93f396ab5d04dcbda09b6 Binary files /dev/null and b/pydraw3d/sim/__pycache__/composites.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/composites2.cpython-310.pyc b/pydraw3d/sim/__pycache__/composites2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad6342c7f971b97c0296bbf8c7e3a6181b4fcf6d Binary files /dev/null and b/pydraw3d/sim/__pycache__/composites2.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/composites3.cpython-310.pyc b/pydraw3d/sim/__pycache__/composites3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a87c0d4e799a32741e6e9908fe14d5fa9e999c0 Binary files /dev/null and b/pydraw3d/sim/__pycache__/composites3.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/fields.cpython-310.pyc b/pydraw3d/sim/__pycache__/fields.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f85aa3aaef98e9a28474e9d7982dc9d7823f16b Binary files /dev/null and b/pydraw3d/sim/__pycache__/fields.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/growth.cpython-310.pyc b/pydraw3d/sim/__pycache__/growth.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d450109f17a7f055855e8b58e2b05957216aaad0 Binary files /dev/null and b/pydraw3d/sim/__pycache__/growth.cpython-310.pyc differ diff --git a/pydraw3d/sim/__pycache__/rigid.cpython-310.pyc b/pydraw3d/sim/__pycache__/rigid.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e996075e16e814093ded2a66d4ac35107778ab64 Binary files /dev/null and b/pydraw3d/sim/__pycache__/rigid.cpython-310.pyc differ