Claude paints with code: a Claude Code skill for procedural illustration in 83 styles, from ink wash (水墨), watercolour and ukiyo-e to stained glass, Roman mosaic, Art Deco, shadow puppets, pastel UI, sketchbook doodles, spot illustrations, grainy picture books, dreamy hills, sunlit greenery. No image model: numpy + Pillow on a CPU, draw-on GIFs.
Python agent-skillsanimechinese-paintingclaudeclaude-codeclaude-skillscolored-pencilcreative-codingcross-stitcheditorial-illustrationgenerative-artink-wash-paintingoil-paintingpaper-collagepixel-artprocedural-generationrisographshanshuiukiyo-ewatercolor
Add ten styles (27 total): cartoon, isometric 2.5D, flat vector, line art, soft 3D, shape morph, newspaper collage, aurora glass, Bauhaus, synthwave
cloveric26f02868e518
diff --git a/README.md b/README.mdindex f2102a5..c77f36d 100644--- a/README.md+++ b/README.md@@ -1,12 +1,16 @@# Claude Drawing · Claude 绘图-**Claude paints with code — no image model.** Seventeen styles, from ink wash and impasto oil to clay, cyanotype, cross-stitch, sticker collage, a lab notebook, a chalkboard and a cyberpunk street.-**不用生图模型,Claude 用代码一笔一笔作画。** 十七种画风,从水墨、油画到黏土、蓝晒、十字绣、贴纸小票、实验笔记本、黑板板书和赛博朋克。+**Claude paints with code — no image model.** Twenty-seven styles, from ink wash and impasto oil to clay, cyanotype, cross-stitch, a chalkboard, a cyberpunk street, an isometric island, a ray-traced ball pit and a synthwave sunset.+**不用生图模型,Claude 用代码一笔一笔作画。** 二十七种画风,从水墨、油画到黏土、蓝晒、十字绣、黑板板书、赛博朋克、等轴小岛、光线追踪的小球海和 Synthwave 落日。[English](#english) · [中文](#中文)<p align="center"><img src="examples/drawing_bawansiqian.gif" width="100%"><br><sub><b>Ink wash · 水墨</b> — every style below is drawn stage by stage like this · 下面每种画风都是这样一步步画出来的</sub></p>+| Isometric 2.5D · 等轴 2.5D | Soft 3D · 柔光 3D |+|---|---|+|  |  |+| Watercolour · 水彩 | Paper collage · 剪纸拼贴 | Coloured pencil · 韩国彩铅 | Anime · 日本动漫 ||---|---|---|---||  |  |  |  |@@ -16,6 +20,10 @@|  |  |  |  || **Sticker collage × receipt · 贴纸拼贴 · 小票** | **Lab notebook × stickers · 实验笔记本 · 贴纸** | **Chalkboard · 黑板板书** | **Cyberpunk · 赛博朋克** ||  |  |  |  |+| **Hand-drawn cartoon · 卡通手绘** | **Flat vector · 扁平矢量** | **Continuous line art · 单线画** | **Shape morph · 形变动画** |+|  |  |  |  |+| **Newspaper collage · 报刊拼贴** | **Aurora glass · 弥散玻璃** | **Bauhaus geometric · 包豪斯几何** | **Retro synthwave · 复古 Synthwave** |+|  |  |  |  |### Gallery · 画廊@@ -39,8 +47,18 @@| <img src="examples/sticker_market.jpg" width="100%"> | <img src="examples/notebook_brewing.jpg" width="100%"> || **为什么天空是蓝的** · *Why Is the Sky Blue?*<br><sub>Chalkboard · 黑板板书</sub> | **霓虹不夜城** · *Neon District*<br><sub>Cyberpunk · 赛博朋克</sub> || <img src="examples/chalk_lesson.jpg" width="100%"> | <img src="examples/cyberpunk_neon_street.jpg" width="100%"> |--Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 30 s per 1920×1080 image.+| **早安吐司** · *Good Morning, Toast*<br><sub>Hand-drawn cartoon · 卡通手绘</sub> | **岛上的气象站** · *Island Weather Station*<br><sub>Isometric 2.5D · 等轴 2.5D</sub> |+| <img src="examples/cartoon_toaster.jpg" width="100%"> | <img src="examples/isometric_weather_island.jpg" width="100%"> |+| **周末书店** · *The Weekend Bookshop*<br><sub>Flat vector · 扁平矢量</sub> | **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> |+| <img src="examples/flatvector_bookshop.jpg" width="100%"> | <img src="examples/lineart_paper_plane.jpg" width="100%"> |+| **浮出** · *Rise*<br><sub>Soft 3D · 柔光 3D</sub> | **一滴水的旅程** · *A Drop's Round Trip*<br><sub>Shape morph · 形变动画</sub> |+| <img src="examples/soft3d_rise.jpg" width="100%"> | <img src="examples/morph_water_cycle.jpg" width="100%"> |+| **好奇心周刊 · 拆开看看** · *Curiosity Weekly · Take It Apart*<br><sub>Newspaper collage · 报刊拼贴</sub> | **晨间计划** · *Morning Plan*<br><sub>Aurora glassmorphism · 弥散玻璃</sub> |+| <img src="examples/newscollage_curiosity.jpg" width="100%"> | <img src="examples/aurora_morning.jpg" width="100%"> |+| **形与色** · *Form & Colour*<br><sub>Bauhaus geometric · 包豪斯几何</sub> | **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> |+| <img src="examples/bauhaus_form_colour.jpg" width="100%"> | <img src="examples/synthwave_coastline.jpg" width="100%"> |++Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street, a blue-pencil rough under boiling brush ink, an island ray-traced under one soft sun, faceless flat-vector figures, a single unbroken gold line, candy balls with softbox glints, one outline morphing through six shapes, halftone photos cut out with scissors, frosted glass blurring the real pixels behind it, screen-printed primaries out of register, a slit sun sinking behind a neon grid played off tape. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 45 s (the soft 3D ray tracer) per 1920×1080 image.---@@ -48,7 +66,7 @@ Every mark above is computed: paper fibres, ink washes and mist, dry-brush strok### What it is-A [Claude Code](https://claude.com/claude-code) skill and a small painting library with seventeen styles:+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with twenty-seven styles:| Style | Module | What makes it read as the real medium ||---|---|---|@@ -69,6 +87,16 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra| **Lab notebook × stickers** | `lib/notebook.py` · `Notebook` | a wire-o graph-paper notebook on a graphite desk (hard back cover, stepped page stack, divider tabs, dog-ear, wire loops lit as metal tubes); graphite that only catches the paper tooth, with pressure, taper and hand wobble; ruled lines, hatching, pencil charts and check boxes; multiply highlighter swipes with pooled starts, felt streaks and dry tails; red felt-pen loops that overshoot instead of closing; curling sticky notes, die-cut vinyl stickers, embossed label-maker tape, a coffee ring; a hexagonal pencil with a scalloped sharpened edge || **Chalkboard** | `lib/chalk.py` · `Chalkboard` | cloudy green slate paint; chalk that only catches the board's tooth, with pressure, grain and broken edges; side-of-the-stick shading; a felt eraser that really removes chalk, drags a smear along the wipe and leaves ghosts of the last lesson; dust settling thicker toward the tray; hand-set text where each character sits a little differently; hand-drawn ∝, waves, arrows and open loops; a mitred wooden frame with chalk sticks and an eraser on the ledge || **Cyberpunk** | `lib/cyberpunk.py` · `Cyberpunk` | a pinhole camera down a rain-soaked street canyon, rendered in HDR with a z-buffer: glass-tube neon with over-exposed cores, dead and flickering tubes; backlit light boxes; a translucent hologram ad with scan lines, tear slices and colour fringing; each object mirrored from its own ground line into the wet asphalt and puddles; depth fog lit by the city; steam lit by the signs; three layers of rain lit only near the neon; flying-car light trails; bloom, halation, grain and one glitch line |+| **Hand-drawn cartoon** | `lib/cartoon.py` · `Cartoon` | drawn the way an animator draws one frame: a blue col-erase pencil rough left under everything; brush-pen ink that lands thin, swells and lifts off to a point, closed shapes inked in one stroke whose ends overlap, heavier on the shadow side; flat colour painted a little off the lines (a sliver of paper here, a spill there); hard one- or two-tone cel shadows and white glints; crayon that only catches the paper tooth, screentone, ink hatching; faces, rubber-hose arms with mitten gloves, sparkles, speed lines, starbursts; chunky extruded lettering; lines that boil from frame to frame; a staged replay rough → ink → colour → shadow → effects → type |+| **Isometric 2.5D** | `lib/isometric.py` · `Isometric` | a true isometric orthographic camera and a small ray tracer: every part is an exact analytic solid (chamfered boxes, roofs, rocks and hulls as convex polyhedra; cylinders and cones on any axis; ellipsoids cut by planes) in a G-buffer, so hiding never depends on draw order; one soft sun gives the three-tone faces and percentage-closer soft shadows that widen with distance; occlusion comes from a top-down map that knows eaves and tree crowns float; pastel albedos under a lilac sky, chamfer highlights, shore foam, glassy water walls, a floating slab whose shadow lands on the backdrop; data cards printed on iso planes |+| **Flat vector** | `lib/flatvector.py` · `FlatVector` | crisp geometric shapes with no outlines (tapered capsules, filleted polygons, rounded rects, leaves); a seven-colour palette where every shade is a tone of it, never grey; volume from stacked flat blocks — a crescent cut as "the shape minus itself nudged toward the light", straight-cut planes, hard multiply cast shadows; translucent grainy light beams; faceless adult figures (7.5 heads, IK hands and feet, far limbs one tone darker); a whisper of print grain |+| **Continuous line art** | `lib/lineart.py` · `LineArt` | the whole picture is one path: shapes strung together in drawing order with tangent-continuous bridges, loop-the-loops laid along the path, invisible retraces to reach a window; rasterised once into a time map, so every draw-on stage is an exact prefix of the line; a hand-pressure width (touch-down and lift-off tapers, slow drift, heavier in sharp turns, a flick where the pen doubles back, a lighter hand for motion paths); a gilded wire with angle-dependent sheen and a faint, tight glow on night blue (or dark ink on cream); a hot pen tip while drawing; one glowing accent; letter-spaced Didot titles |+| **Soft 3D** | `lib/soft3d.py` · `Soft3D` | an actual little ray tracer: tens of thousands of balls found by walking a grid (DDA) with exact ray–sphere hits; puffy letters as signed distance fields (exact 2D distance transform of the glyph, extruded, rounded and inflated); a studio sky dome with ambient occlusion sampled in the scene's own distance field; a big softbox key with soft penumbra shadows, a rim light, softbox reflections and Fresnel edges; shade that turns deeper and more saturated instead of grey; displaced balls that settle into real hollows; aerial haze, layered depth of field, 1.5× supersampling |+| **Shape morph** | `lib/morph.py` · `Morph` | one closed outline per object: resampled to 256 points evenly along its arc length, given the same winding, start point aligned by FFT cross-correlation, then blended point by point while its centroid travels an eased motion path with squash & stretch; compound shapes (cloud, snowflake) are unions of primitives traced back to a single outline; colours switch through OKLab; the poster freezes the animation as a film strip: one flat colour panel per keyframe, onion-skin ghosts that change colour at the panel border, matched points dotted on the middle frame, a dashed motion path and a timeline of ease curves |+| **Newspaper collage** | `lib/newscollage.py` · `NewsCollage` | everything is paper that was printed, then torn or cut, then glued: kraft board with fibres; hand-torn newsprint of generated pseudo-text that shows a pale fibrous core along stretches of the tear; "old photos" that are real renders (height field, key light, chrome reflections, cast shadows) printed as a 45° halftone with ragged dots and dot gain, cut out with scissors in short straight snips; ransom-note letters each from a different magazine; masking tape that shows the paper edges beneath; uneven rubber stamps |+| **Aurora glassmorphism** | `lib/aurora.py` · `Aurora` | a mesh gradient of colour pools mixed in OKLab on a domain-warped grid, with aurora ribbons and fine grain; glossy iridescent orbs; frosted panes that blur the *actual* pixels beneath them (backdrop, orbs, the cards and text behind), boost saturation and add a milky veil that is thicker toward the light; a bevelled rim that bends the view outward with faint dispersion, a light-facing 1 px edge highlight, frost grain and a soft shadow tinted by what it falls on; crisp SDF controls: gradient toggles, sliders, conic progress rings, pill bars, sparklines, glass chips, a glossy sun behind a glass cloud; SF + PingFang lettering |+| **Bauhaus geometric** | `lib/bauhaus.py` · `Bauhaus` | a press sheet printed screen by screen, light to dark, on cream uncoated stock (cloudy pulp, fibres, flecks, tooth, a slight cockle); each screen has its own registration error, so colour meets black with a sliver of paper or a dark overlap and the register targets print as a stack of offset crosshairs; an ink film streaked along the squeegee pull and thinning toward the end of the stroke, with bare tooth pits and pinholes where it is thin and a mesh-ragged stencil edge; semi-opaque inks that darken where they overprint; circles, sectors, triangles and heavy bars on a strict module grid; Futura-style caps and heavy Hei, knocked out of solids; crop marks, a colour bar and a pencilled edition number |+| **Retro synthwave** | `lib/synthwave.py` · `Synthwave` | an 80s retro-future dusk through a pinhole camera: a gradient sun cut by slits that thicken toward the horizon; an analytic neon grid with honest line widths that fades to its average instead of moiré; wireframe mountains glowing magenta to cyan; a sea whose reflection is torn into bars stretched about the sun's column; palm silhouettes with sunset rims; chrome caps mirroring sky over ground with a sharp horizon, extrusion and glints; neon script; then played back off tape: chroma bleed, a tracking band, head-switching noise, on-screen display and scanlines |Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:@@ -90,7 +118,7 @@ git clone https://github.com/cloveric/claude-drawing-skill.git ~/.claude/skills/pip install -r ~/.claude/skills/claude-drawing/requirements.txt # numpy, Pillow```-Titles and notes need a CJK font. macOS Kaiti/Songti, Linux Noto CJK and Windows KaiTi/SimSun are found automatically; you can also set `INKPAINT_FONT=/path/to/font`. The clay, cyanotype, cross-stitch and panel styles also look for common Latin system fonts (a sans, a rounded bold, a script and a handwriting face, via `core.latin_font`); override any of them with `INKPAINT_FONT_<STYLE>`, e.g. `INKPAINT_FONT_HAND`. No font files are bundled.+Titles and notes need a CJK font. macOS Kaiti/Songti, Linux Noto CJK and Windows KaiTi/SimSun are found automatically; you can also set `INKPAINT_FONT=/path/to/font`. Many styles also look for common Latin system fonts (a sans, a rounded bold, a script and a handwriting face, via `core.latin_font`); override any of them with `INKPAINT_FONT_<STYLE>`, e.g. `INKPAINT_FONT_HAND`. No font files are bundled.### Quick start@@ -139,6 +167,16 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages- **Panel**: one key light for every part: lit upper-left edges, shadows to the lower right. Grille-cloth lurex needs long floats (short ones read as a perforated dot grid). Keep legends off busy textures and away from scale ends.- **Chalkboard**: even full-pressure chalk keeps ~15% pits and soft, broken edges, or it reads as vector lines. Draw ∝ by hand (a bold font's ∝ closes up into ∞). Shade large areas lightly with a pressure gradient. Ghosts of the last lesson stay faint and sit in empty space.- **Cyberpunk**: mirror each object from its own ground row, not one horizon line. Keep shop interiors dim (0.2–0.45) or the street turns into over-exposed walls. Light rain streaks only near the neon. Light trails cross the street instead of all flying into the vanishing point.+- **Hand-drawn cartoon**: draw back to front, since every fill knocks out what is behind it; put limbs down before the body so the shoulder hides. Lines are heavier on the shadow side, and colour sits a few pixels off the line. Keep texture where it belongs (toasted edges, not across a face). Boil only the ink between frames: pencil and colour stay on the sheet, which also keeps the GIF small.+- **Isometric**: light real solids with one sun instead of painting three face tones by hand. Wall occlusion must look out along the normal and skip the building's own height and eaves, or white walls turn grey; never interpolate column tops and bottoms across an edge. Keep floating cards, clouds and hairlines out of the height map. Lay wave dashes along world y − x (screen horizontal), and leave a wide sea on the two front edges so the island reads as an island.+- **Flat vector**: there are no outlines, so plan every value against what sits behind it (dark hair on a dark shelf vanishes). Save the accent colour for the one thing the picture is about. Cut hair at a hairline, or heads turn into hoods; in 3/4 view reach with the far arm so the arm doesn't sweep across the face. Keep grain around 1%.+- **Line art**: one path, drawn in order: string shapes with `chain()`, reach windows with an invisible retrace, let loops ride along the path, and put a loop where the path runs level, not on a climb. Draw motion paths with a lighter hand (~0.6) or they read as one more hill. Keep exactly one accent colour and plenty of empty space.+- **Soft 3D**: near a shape, light queries (AO, shadows, dropping a ball) need its exact distance, not its bounding box, or balls rest on thin air. Don't carve a trench around a subject: pile the displaced balls into the hollows at its feet. Fill shade with the material's own hue (grey mint looks dirty). Match the haze to the backdrop, and set the lens with the camera so every stage is soft.+- **Shape morph**: every object is one closed outline. Resample both shapes to the same point count, same winding, and align the start point before blending, or the in-betweens collapse into slivers. Keep keyframes around 0.6 of the panel width and show only three ghosts per transition, with the middle one filled. Dash the motion path so it doesn't mix with the dotted matched points. Shapes stay perfectly flat: paper tooth only where bare paper shows.+- **Newspaper collage**: print first, then tear or cut, then glue. The pale torn core shows only along stretches of a tear; scissor cuts are chains of short straight snips with a margin that wanders. Halftone subjects must be a step darker than their backdrop, and gear teeth or spring coils need about 4 screen cells of spacing or they turn to grey mush. Fake newspaper text is generated pseudo-words only.+- **Aurora glass**: blur what is really under the pane, then veil it lightly (tint ~0.24, saturate ~1.5), or it turns into milky plastic. Let orbs pass a third or more behind the glass and never touch an edge tangentially. Overlap cards only inside each other's padding. Give each gradient one meaning. For the GIF, weight saturated pixels in the palette sample and add one static Bayer pattern.+- **Bauhaus**: print light to dark, one ink per screen, and keep everything of one colour on its screen so misregistration moves it together. Keep bare-paper pits to ~2% and only in thin-film streaks, or solids turn to sandpaper and type to a worn rubber stamp. Use a light 3×3 edge blur (a big blur rounds the corners). Knock labels out of dark solids instead of printing black on blue, and keep margin text clear of the crop marks.+- **Synthwave**: keep the sun's base colour low and let the bloom lift it, or it burns to white and the slits fill in. Break the sea's reflection into bands stretched about the sun's column, and let light sources reflect more strongly than the sky. Measure grid lines in screen pixels and swap dense cells for their average. Keep tape damage mild: one tracking band, sub-pixel jitter.### Roadmap@@ -150,7 +188,7 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages### 这是什么-一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库,内置十七种画风:+一个 [Claude Code](https://claude.com/claude-code) skill,加上一个小巧的绘图库,内置二十七种画风:| 画风 | 模块 | 为什么看起来像真的 ||---|---|---|@@ -171,6 +209,16 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages| **实验笔记本 · 贴纸** | `lib/notebook.py` · `Notebook` | 石墨蓝灰桌面上的线圈方格本:硬封底、错开的页边、分隔标签、折角,线圈按金属管打光;石墨只挂在纸纹凸起上,有压力、收笔和手抖;靠尺直线、排线、铅笔折线图、勾选框;荧光笔正片叠底,起笔积墨、纤维条纹、尾部干涩;红笔圈故意不闭合;翘角便利贴、模切贴纸、标签机压印胶带、咖啡杯印;六棱铅笔 || **黑板板书** | `lib/chalk.py` · `Chalkboard` | 云状不匀的墨绿石板漆;粉笔只挂在板面「齿」的凸起上,有压力、颗粒和断口;粉笔横躺的侧锋铺色;板擦真的能擦掉粉笔,顺着擦的方向拖出残迹,留下上节课的残影;越往下越厚的粉笔灰;每个字微转、错位、轻重不一;手写 ∝、波浪线、箭头和不闭合的圈;斜接木框,粉笔槽里放着粉笔和板擦 || **赛博朋克** | `lib/cyberpunk.py` · `Cyberpunk` | 一台针孔相机看向雨夜街道深处,HDR 缓冲加深度遮挡:玻璃管霓虹中心过曝、边缘彩色光晕,还有坏管和闪烁管;背光灯箱;半透明全息广告,带扫描线、撕裂切片和色边;每样东西按自己的着地行翻出湿路面和水洼里的倒影;被城市灯光照亮的深度雾;被招牌照亮的井盖蒸汽;三层雨,只在霓虹附近看得见;飞车光轨;泛光、胶片红晕、颗粒和一道故障扫描线 |+| **卡通手绘** | `lib/cartoon.py` · `Cartoon` | 照动画师画一张原画的办法画:蓝铅笔稿留在底下;毛笔线落笔细、中段粗、收笔尖,闭合轮廓一笔画完、首尾交叠,背光一侧更粗;平涂颜色略微错开线(这边露一条纸白,那边压过线);一到两层硬边赛璐璐阴影和白色高光;只挂在纸纹凸起上的蜡笔、网点纸、墨线排线;表情、橡皮管手臂和带拇指的白手套、闪光星、速度线、爆炸框;带挤出阴影的粗描边大字;墨线每一帧都轻微抖动;能按 起稿 → 勾线 → 上色 → 阴影 → 特效 → 字 的顺序回放 |+| **等轴 2.5D** | `lib/isometric.py` · `Isometric` | 正等轴正交相机加一个小光线追踪器:每个部件都是精确的解析实体(倒角盒子、屋顶、礁石、船体用凸多面体;任意轴向的圆柱圆锥;可被平面切开的椭球),写进 G-buffer,遮挡与绘制顺序无关;一个柔和的太阳照出三个面三种明度,PCSS 软阴影随遮挡距离变宽;AO 来自记得屋檐和树冠是悬空的顶视高度图;粉彩反照率配淡紫天光、倒角高光、岸边浪花、透亮的水体侧壁,漂浮底座的影子落在背景上;数据卡的文字印在等轴平面上 |+| **扁平矢量** | `lib/flatvector.py` · `FlatVector` | 无描边的干净几何形(锥形胶囊、圆弧倒角多边形、圆角矩形、叶片);七色限定色板,所有明暗都是色板色的色调,不用灰黑;色块叠压出体积:「形状减去朝光源挪动的自己」切出月牙暗面、直线切面、硬边正片叠底投影;带颗粒的半透明光束;无五官的成年人(7.5 头身、手脚可指定落点、远侧手脚暗一档);极轻的印刷颗粒 |+| **单线画** | `lib/lineart.py` · `LineArt` | 整幅画是一条路径:各个形状按作画顺序串起来,断开处用切线连续的曲线接上,翻圈沿路径插入,够不到的窗户用看不见的原路折返;一次栅格化成「时间图」,每个动画阶段都是整条线精确的前一段;带手感的线宽(起笔轻、收笔尖、压力缓慢起伏、急转处变粗、原路折返处提笔收尖、航迹这类运动轨迹用轻手);深蓝底上是随角度变亮、只带一点柔光的金线(奶油底上是墨线);画的时候笔尖发光;唯一一处发光的点睛色;字距拉开的 Didot 标题 |+| **柔光 3D** | `lib/soft3d.py` · `Soft3D` | 真的是一台小光线追踪器:几万颗球靠逐格查找(DDA)加精确的光线–球求交;鼓鼓的字是有向距离场(字形精确距离变换→挤出、倒圆、吹胀);摄影棚天光穹顶,环境光遮蔽在场景自己的距离场里采样;大柔光箱主光投下边缘渐软的阴影,加轮廓光;光面上映出灯片,边缘有菲涅尔亮边;阴影和缝隙变深变饱和而不发灰;被挤开的球真的落进窝里堆起来;远处空气雾、分层景深、1.5 倍超采样 |+| **形变动画** | `lib/morph.py` · `Morph` | 每样东西都是一条闭合轮廓:按弧长等距重采样成 256 个点、统一绕向、用 FFT 互相关对齐起点,再逐点插值;质心沿缓动的运动路径走,快的时候沿运动方向挤压拉伸;云、雪花这类组合形状用圆、线、多边形拼好后描出外轮廓;颜色在 OKLab 里切换;海报把动画定格成一条胶片:每个关键帧一块纯色面板,洋葱皮残影跨面板时跟着换色,中间帧标出对应点,加虚线轨迹和缓动曲线时间轴 |+| **报刊拼贴** | `lib/newscollage.py` · `NewsCollage` | 所有东西都是「先印、再撕或剪、最后粘」的纸:带纤维的牛皮纸底;手撕的伪词报纸,撕口一段段露出毛糙的白色纸芯;「老照片」是真的布光渲染(高度图、主光、镀铬反射、投影),印成 45° 网点(毛边网点、网点扩大),再用剪刀一段段直线剪下;每个字来自不同杂志的勒索信拼贴字;透出底下纸边的美纹纸胶带;压力不匀的橡皮章 |+| **弥散玻璃** | `lib/aurora.py` · `Aurora` | 网格渐变:几团色光在 OKLab 里混色,坐标扭曲成流动的形状,加极光光带和细颗粒;虹彩光泽小球;磨砂玻璃模糊的是它下面**真实的像素**(背景、小球、后面的卡片和字),提高饱和度,蒙一层近光源更厚的白纱;边缘斜面向外折射并带一点色散,朝光的边有 1 px 高光,玻璃上有磨砂颗粒,投影颜色取自下面的背景;界面用距离场画,边缘干净:渐变开关、滑块、锥形渐变进度环、胶囊柱状图、折线图、玻璃小胶囊、躲在玻璃云后的光泽太阳;SF + 苹方字体 |+| **包豪斯几何** | `lib/bauhaus.py` · `Bauhaus` | 在奶油色未涂布纸(云状纸浆、纤维、纸屑、纸齿、微微不平)上按色版先浅后深逐版刮印;每块网版有自己的套准误差,色块和黑线相接处露出一丝纸白或压出一道深边,套准十字叠成几色错开的样子;墨膜顺刮板方向有条纹、行程末端变薄,薄处露出纸齿坑点和针孔,版边有网目锯齿;墨半透明,叠印变深;圆、扇形、三角、粗黑条都落在严格的模数网格上;Futura 式几何无衬线大写和粗黑体,可从色块里挖空;裁切线、色标条和铅笔版号 |+| **复古 Synthwave** | `lib/synthwave.py` · `Synthwave` | 针孔相机看 80 年代复古未来的黄昏:横条切口越往下越厚的渐变落日;逐像素解析的霓虹网格,线宽准确,远处换成平均值不出摩尔纹;从品红渐变到青色的线框山脉;倒影按横带拉伸、碎成一条条光带的海面;带落日轮廓光的棕榈剪影;上映天空、下映地面、中间一道锐利地平线的镀铬大字,带挤出和星闪;霓虹手写字;最后「过一遍录像带」:色度渗色、跟踪噪带、磁头噪声、屏显字和扫描线 |对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;@@ -191,7 +239,7 @@ git clone https://github.com/cloveric/claude-drawing-skill.git ~/.claude/skills/pip install -r ~/.claude/skills/claude-drawing/requirements.txt # numpy、Pillow```-题字和纸条需要中文字体。macOS 的楷体/宋体、Linux 的 Noto CJK、Windows 的楷体/宋体都会自动找到,也可以用 `INKPAINT_FONT=字体路径` 指定。黏土、蓝晒、十字绣、复古面板还会找常见的西文字体(无衬线、圆体、花体、手写体,见 `core.latin_font`),可用 `INKPAINT_FONT_<风格>` 指定,比如 `INKPAINT_FONT_HAND`。仓库里不附带任何字体文件。+题字和纸条需要中文字体。macOS 的楷体/宋体、Linux 的 Noto CJK、Windows 的楷体/宋体都会自动找到,也可以用 `INKPAINT_FONT=字体路径` 指定。不少画风还会找常见的西文字体(无衬线、圆体、花体、手写体,见 `core.latin_font`),可用 `INKPAINT_FONT_<风格>` 指定,比如 `INKPAINT_FONT_HAND`。仓库里不附带任何字体文件。### 快速上手@@ -217,6 +265,16 @@ python3 examples/sticker_market.py out.png # 贴纸拼python3 examples/notebook_brewing.py out.png # 实验笔记本 · 贴纸:咖啡萃取实验python3 examples/chalk_lesson.py out.png # 黑板板书:为什么天空是蓝的python3 examples/cyberpunk_neon_street.py out.png # 赛博朋克:霓虹不夜城+python3 examples/cartoon_toaster.py out.png # 卡通手绘:早安吐司+python3 examples/isometric_weather_island.py out.png # 等轴 2.5D:岛上的气象站+python3 examples/flatvector_bookshop.py out.png # 扁平矢量:周末书店+python3 examples/lineart_paper_plane.py out.png # 单线画:从这扇窗到那扇窗+python3 examples/soft3d_rise.py out.png # 柔光 3D:浮出+python3 examples/morph_water_cycle.py out.png # 形变动画:一滴水的旅程+python3 examples/newscollage_curiosity.py out.png # 报刊拼贴:好奇心周刊 · 拆开看看+python3 examples/aurora_morning.py out.png # 弥散玻璃:晨间计划+python3 examples/bauhaus_form_colour.py out.png # 包豪斯几何:形与色+python3 examples/synthwave_coastline.py out.png # 复古 Synthwave:海岸线 1987```### 作画要点(Claude 交图前逐条自查)@@ -236,6 +294,16 @@ python3 examples/cyberpunk_neon_street.py out.png # 赛博朋- **复古面板**:所有部件同一盏主光:左上边亮、向右下投影;喇叭布的金丝要长浮,短了像冲孔板;丝印字别压在花纹上,也别挤到刻度末端。- **黑板**:满压的粉笔也要留约 15% 的坑点和毛边,否则像矢量线;∝ 要手写一笔(粗体字形会糊成 ∞);大面积用轻压力加渐变铺色;上节课的残影要淡,放在空白处。- **赛博朋克**:倒影按每样东西自己的着地行翻转,不能按一条地平线整体翻;店内亮度压在 0.2–0.45,否则街面成了过曝的墙;雨丝只在霓虹附近被照亮;飞车光轨横穿街道,不要全都飞向灭点。+- **卡通手绘**:先远后近,因为每次平涂都会挖掉身后的东西;手臂先画、身体后画,把肩膀藏起来。背光一侧的线更粗,颜色错开线几像素。质感放在该在的地方(烤边,而不是脸上)。帧与帧之间只抖墨线,铅笔稿和颜色不动,动图也小。+- **等轴 2.5D**:三个面的明度靠一个太阳照出来,不要手涂;墙面 AO 要沿法线往外看,不能把楼自己和屋檐的高度算进去,否则白墙发灰;柱子的顶和底不能跨边插值;悬浮卡片、云和细线不进高度图;海浪短线沿世界 y − x(屏幕水平)画;岛的前两条边留宽海面,才看得出是岛。+- **扁平矢量**:没有描边,每块颜色都要按身后的背景定明度(深色头发贴深色书架就消失);点睛色只留给画面要讲的那一样东西;头发要沿发际线切开,否则像头巾;3/4 侧身够东西用远侧手臂,免得手臂扫过脸;颗粒压在 1% 左右。+- **单线画**:整幅画只有一条线,按作画顺序串:用 `chain()` 串形状,够不到的窗户原路进出,翻圈沿路径插入,放在路径平缓处,别放在爬升段;航迹这类运动轨迹用轻手(约 0.6 倍),否则会读成又一座山;点睛色只留一处,留白要多。+- **柔光 3D**:AO、阴影、落球这些查询在物体附近要用精确距离,不能用包围盒,否则球会停在半空;主体周围别挖一圈空槽,把挤开的球堆进脚边的窝里;阴影用材质自身的色调去补(发灰的薄荷色很脏);雾色和背景一致;景深跟相机一起先设好,每个阶段都是柔的。+- **形变动画**:每样东西只用一条闭合轮廓;插值前先重采样成同样点数、统一绕向、对齐起点,否则中间帧会塌成碎片;关键帧约占面板宽的六成,每段只画三个残影,中间那帧填色;轨迹用虚线,别和对应点的圆点混;形状保持纯平,纸纹只加在露出的纸面上。+- **报刊拼贴**:先印、再撕或剪、最后粘;手撕的白色纸芯只出现在一段段边上,剪刀边是一串短直线,白边宽窄随手变化;网点照片里的物件要比背景深一档,齿、发条圈这类细节间距至少约 4 个网点,否则糊成灰;报纸正文只用生成的伪词。+- **弥散玻璃**:玻璃要模糊它下面真实的东西,白纱要薄(约 0.24,饱和度约 1.5),否则像奶白塑料;小球要有三四成压在玻璃后面,别和卡片边相切;卡片只在对方的内边距里重叠;一种渐变只代表一件事;动图调色板给饱和像素加权,再叠同一张 Bayer 抖动。+- **包豪斯**:先浅后深,一种颜色一块版,同色的东西放在同一块版上,错位才会整体一起动;露纸坑点约 2%、只在墨膜薄的条纹里,否则色块像砂纸、字像旧橡皮章;版边只做 3×3 轻模糊(大模糊会把直角磨圆);深色块上的标注用挖空,不要黑字压蓝;页边小字让开裁切线。+- **复古 Synthwave**:太阳底色压低、靠泛光提亮,否则冲成白团、切口被填平;海面倒影按横带以太阳所在列为中心拉伸打碎,光源的倒影比天空更强;网格线按屏幕像素算宽度,格子太密就换成平均值;录像带损伤要轻:一条跟踪噪带、不到一像素的逐行抖动。### 计划diff --git a/SKILL.md b/SKILL.mdindex a661115..3d2e3ce 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,6 +1,6 @@---name: claude绘图-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置十七种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置二十七种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、扁平矢量(无描边几何色块、限定色板、无五官人物)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、扁平矢量、扁平插画、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city / cartoon / hand-drawn animation / isometric / 2.5D / flat vector / flat illustration / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。---# Claude 绘图@@ -31,6 +31,16 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型| 实验笔记本 · 贴纸 | `lib/notebook.py` · `Notebook` | `examples/notebook_brewing.py` 咖啡萃取实验(线圈方格笔记本、铅笔表格与折线图、排线标出最佳区间、荧光笔、没闭合的红笔圈、便利贴结论、模切贴纸、标签机日期、桌上的六棱铅笔) | 约 3 秒 || 黑板板书 | `lib/chalk.py` · `Chalkboard` | `examples/chalk_lesson.py` 为什么天空是蓝的(墨绿石板、半擦掉的上节课残影与板擦痕、越往下越厚的粉笔灰;白黄粉蓝粉笔写的标题、太阳→大气层→眼睛示意图、长短波浪线、手写 ∝ 与圈出的 1/λ⁴、光谱条与散射曲线、带缺口的「小结」框;木框和粉笔槽里的粉笔、板擦) | 约 5 秒 || 赛博朋克 | `lib/cyberpunk.py` · `Cyberpunk` | `examples/cyberpunk_neon_street.py` 霓虹不夜城 · Neon District(雨夜街道峡谷、真玻璃管霓虹竖招牌(坏管与闪烁管)、背光灯箱、过街天桥「不夜城」、全息海月水母广告、电线、飞车光轨、井盖蒸汽、透明伞背影、湿路面与水洼倒影、胶片颗粒与一道撕裂扫描线) | 约 10 秒 |+| 卡通手绘(逐帧手绘) | `lib/cartoon.py` · `Cartoon` | `examples/cartoon_toaster.py` 早安吐司(薄荷绿吐司机笑着弹出两片举手的吐司、「叮!」爆炸框、盘子上打瞌睡的化黄油、窗外日出、墙上 7 点的钟;左侧 ①按下拉杆 ②电热丝烧红 3 分钟 ③弹起来 的图解;蓝铅笔稿留底、毛笔线、错位平涂、赛璐璐阴影、蜡笔天空与烤边、网点橱柜、抖线) | 约 4 秒 |+| 等轴 2.5D | `lib/isometric.py` · `Isometric` | `examples/isometric_weather_island.py` 岛上的气象站(漂浮的分层底座、一格一格的倒角地砖与台地、带双道浪花的海;观测场里的百叶箱、雨量筒、带风杯和风向标的风杆;看守小屋与卫星天线、太阳能板、石板路、栈桥小船、风袋、浮标、开花灌木;探空气球和平底云;四张悬浮数据卡用细引线指向各自仪器,地面上一个指北针) | 约 5 秒 |+| 扁平矢量 | `lib/flatvector.py` · `FlatVector` | `examples/flatvector_bookshop.py` 周末书店(无描边几何色块、七色限定色板、色块叠压出体积、极轻颗粒;梯子上的店员把唯一一本珊瑚色诗集递给仰头伸手的银发顾客,虚线标出它从顶层空位落下的路线;拱窗日落、OPEN 挂牌、台灯光锥下读书的人、窗台橘猫、¥10 旧书箱) | 约 1 秒 |+| 单线画 | `lib/lineart.py` · `LineArt` | `examples/lineart_paper_plane.py` 从这扇窗到那扇窗(一根不断开的金线:圆树、小屋、从窗口穿墙飞出的纸飞机航迹与顶部翻圈、飞镖形纸飞机穿墙飞进对面小屋的窗;窗子亮起是全画唯一的点睛色;字距拉开的衬线标题) | 约 6 秒 |+| 柔光 3D | `lib/soft3d.py` · `Soft3D` | `examples/soft3d_rise.py` 浮出(糖果色小球海里顶出鼓鼓的软字 rise:被挤开的球堆在字脚、几颗骑在字肩上、几颗滚落,i 的点是一颗黄球;天光穹顶、柔光箱主光、粉色轮廓光、环境光遮蔽、软阴影、次表面色调、景深) | 约 46 秒 |+| 形变动画 | `lib/morph.py` · `Morph` | `examples/morph_water_cycle.py` 一滴水的旅程(一条 256 点轮廓线依次变成水滴→云→雪花→雪山→河→海浪,六块纯色背景随之切换;洋葱皮残影、挤压拉伸、虚线运动轨迹、中间帧标出对应点、缓动曲线时间轴) | 约 1 秒 |+| 报刊拼贴 | `lib/newscollage.py` · `NewsCollage` | `examples/newscollage_curiosity.py` 好奇心周刊 · 拆开看看(牛皮纸底、手撕旧报纸(程序生成的假文字栏)、被剪刀剪开并掀起上半的网点印刷闹钟照片、飞出的齿轮 / 发条 / 红色网点摆轮 / 螺丝各自剪下并配打字标签和引线、大红纸圆、勒索信拼贴字「拆开看看?」和 WHAT MAKES IT TICK、刊头、黑色邮戳、红色「附零件图」印章、美纹纸胶带) | 约 3 秒 |+| 弥散玻璃 | `lib/aurora.py` · `Aurora` | `examples/aurora_morning.py` 晨间计划(日出色弥散渐变与极光光带、光泽小球;磨砂玻璃卡片层叠:晨间计划时间线(3/5 完成,进行中那一行是玻璃叠玻璃)、专注倒计时圆环、光泽太阳躲在玻璃云后的天气卡、勿扰开关与白噪音滑块、近 7 天专注柱状图、9:00 站会提醒胶囊) | 约 2 秒 |+| 包豪斯几何 | `lib/bauhaus.py` · `Bauhaus` | `examples/bauhaus_form_colour.py` 形与色 · Form & Colour(奶油色纸上的丝网印刷讲座海报:黄三角、红方、蓝圆站在粗黑地线上,60° 弧、直角框、挖空的圆心和半径,下面大字角数 3 / 4 / 0;「形与色」大标题、挖空字的黑条论点「角越尖,色越亮」;构成网格、套准十字、裁切线、色标条、铅笔版号) | 约 2 秒 |+| 复古 Synthwave | `lib/synthwave.py` · `Synthwave` | `examples/synthwave_coastline.py` 海岸线 1987(横条切口的渐变落日沉入海面、倒影碎成一条条光带、线框小岛与线框山脉、霓虹网格地面、霓虹边线的海岸公路、灭点处亮灯的小城、带落日轮廓光的棕榈剪影、驶向城市的尾灯、镀铬大字 COASTLINE 与霓虹手写 Last Sunset、录像机 PLAY 与日期屏显、色度渗色、跟踪噪带和扫描线) | 约 4 秒 |各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。@@ -51,7 +61,17 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型- 清单、账单、价格、购物、市集、活动海报、轻松但成熟的讲解片封面 → 贴纸拼贴 · 小票;- 实验记录、数据对比、复盘笔记、讲解片里的「算账 / 结论」页 → 实验笔记本 · 贴纸;- 讲课、知识点、公式推导、原理示意图、讲解片里的「板书 / 课堂」页 → 黑板板书;-- 夜景、城市、雨、霓虹、电影感氛围、讲解片的「未来 / 科技 / 城市」封面 → 赛博朋克(要复古小尺寸或像素动画仍用像素风)。+- 夜景、城市、雨、霓虹、电影感氛围、讲解片的「未来 / 科技 / 城市」封面 → 赛博朋克(要复古小尺寸或像素动画仍用像素风);+- 可爱的拟人小物件、日常小事讲故事、带表情的角色、讲解片里轻松的「步骤 / 原理」图解、要逐帧抖线的动画 → 卡通手绘(要立体手作感用黏土定格,要纸片感用剪纸拼贴);+- 小世界、城市 / 园区 / 工厂 / 校园示意,系统或流程的「微缩模型」图解,围着场景放数据卡的信息图,讲解片的「全景 / 系统概览」页 → 等轴 2.5D(要霓虹夜景用赛博朋克;要复古小尺寸用像素风);+- 生活场景、人物小故事、产品 / App 讲解插图、MG 动画式讲解片分镜 → 扁平矢量(要立体手作感用黏土,要纸感用剪纸);+- 高级克制、极简、品牌感封面、要看「一笔画出来」的过程、讲一段路线或旅程 → 单线画(深蓝底金线或奶油底墨线,只一个点睛色);+- 产品感、软萌立体、糖果色、MG 片头大字、「3D 渲染」、讲解片封面的立体标题 → 柔光 3D(要手作、捏泥的质感仍用黏土定格);+- 过程、变化、循环、「从 A 变成 B」的小故事,讲解片的转场、片头和「演变」页 → 形变动画(要真的动起来,用 `Morph.at` 逐帧出图);+- 杂志封面、观点海报、达达 / 复古拼贴、「拆开看看 / 里面有什么」类讲解页、需要老照片质感又不能用真人照片 → 报刊拼贴(要童趣温暖的彩纸拼贴仍用剪纸拼贴);+- 产品界面、App / 小组件展示、效率工具与数据面板、明亮通透的科技感、讲解片的「功能 / 界面」页 → 弥散玻璃(要暗夜霓虹氛围仍用赛博朋克);+- 设计感海报、讲座 / 展览 / 活动海报、概念图解(形状、比例、对比、原则)、讲解片里的「定义 / 原理」页 → 包豪斯几何;+- 80 年代复古未来、怀旧、夏夜公路与海边、音乐和歌单封面、讲解片的「复古科技 / 回到过去」封面 → 复古 Synthwave(要雨夜城市用赛博朋克,要低分辨率游戏感用像素风)。每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。@@ -220,6 +240,133 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 氛围:`steam(X, Z, height, width, drift, density)` 井盖蒸汽;`mist()` 只躺在远处街面的薄雾;`figure(X, Z, umbrella='clear'|'dark'|None)` 打伞背影(两侧霓虹轮廓光,无脸);`rain(far, mid, near, slant, rings)` 三层雨和溅落圈;`glitch(y, h, shift, split)` 一道撕裂扫描线,只在成片里出现,用一次就够- 颜色常量 `MAGENTA CYAN AMBER RED WHITE`;`save('x.jpg')` 默认 quality 88、4:4:4 色度,霓虹边缘不糊+**卡通手绘 `Cartoon`**:+- 思路:照动画师画一张原画的顺序——蓝铅笔起稿 → 勾线 → 平涂 → 赛璐璐阴影 → 蜡笔/网点 → 特效 → 字。每一笔按种类落进一个「组」:`rough` 铅笔、`ink` 墨线、`flat` 平涂、`shade` 阴影/高光/腮红、`texture` 蜡笔/网点/排线、`fx` 特效、`type` 字。`stage(name, show=[组...], rough=强度)` 只显示这些组,画完的一张图可以按作画顺序回放;`with c.group(ink='ink_bg'):` 把某一类改投到别的组,`with c.group('fx'):` 全部改投+- 遮挡:东西不透明,`fill` 会挖掉身后已画的墨线和颜色(隐藏线自动去掉),所以先远后近;`fx`、`type` 是最后叠上去的覆盖层,它们的挖空只在显示时生效,阶段快照不会出现空洞+- 墨线:`line(pts, width, taper)` 毛笔线(落笔细、中段粗、收笔尖,有手抖和压力起伏);`outline(pts, width, weight, gaps)` 一笔画完的闭合轮廓,首尾两个尖头交叠,背光的右下侧按 weight 加粗,`gaps=n` 留几处小断口;`ink_fill()` 实心墨块、`dot()` 墨点。每条墨线会自动先起一遍蓝铅笔稿(`rough=False` 关掉),`sketch()` 只画铅笔辅助线+- 颜色:`fill(pts|mask, 颜色, slop)` 平涂,整体错开 slop 像素、边缘游走,返回 `Mask`,可作 clip;`shade(形状, 颜色, offset=(dx, dy), clip)` 硬边赛璐璐阴影(形状减去朝光源挪过的自己,得到背光侧的月牙),offset=None 时直接用给的形状;`glint(pts, width)` 白色高光笔;`shape(pts, 颜色, shade=(颜色, dx, dy), shade2=...)` 一次做完平涂、两层阴影和描边;`darker(颜色)` 取阴影色+- 质感:`crayon(形状, 颜色, pressure, angle)` 蜡笔(只挂在纸纹凸起上,顺着涂的方向有条纹,毛边;pressure 可以是整幅数组,做渐变);`tone(形状, 颜色, cell, angle, amount)` 网点纸;`hatch(形状, angle, spacing)` 墨线排线(接触阴影);`blush()` 腮红+- 角色:`face(cx, cy, size, mood, rot)`,mood 可选 happy(^ ^ 眼加张嘴吐舌)、wow(圆眼加 o 嘴)、sleepy、smile、wink,自带腮红;`arm(肩, 手, bend, hand, thumb)` 橡皮管手臂加带拇指的白手套(先画手臂再画身体)+- 特效(默认进 fx 覆盖层,`fx=False` 当普通物件画):`sparkle()` 四角闪光星、`speed_lines(p0, p1, angle)` 速度线、`steam()` 热气、`puff()` 扇贝边烟团、`burst()` 爆炸星形框、`crumbs(..., avoid=遮罩)` 飞溅碎屑、`pop_lines()` 强调短线+- 字(默认进 type 覆盖层):`letter(s, x, y, size, fill, depth, depth_colour)` 大标题字(中文圆体加漫画西文,每个字微转、上下跳,带挤出阴影、左上白边和粗墨描边);`note()` 手写注释;`arrow()` 手绘箭头;`badge(x, y, r, '1')` 编号圆标;`pencil_note()` 纸角的蓝铅笔编号;`text_width()` 量宽度+- 形状:`Cartoon.rrect_pts(x0, y0, x1, y1, r 或 (左上, 右上, 右下, 左下))`、`ellipse_pts(cx, cy, rx, ry, rot, a0, a1)`(给 a0/a1 就是一段弧)、`densify()` 保留尖角的折线、`place(局部点, cx, cy, scale, rot)` 摆放在局部坐标里画好的物件;`mask(pts)` 整幅遮罩,可以用 numpy 相乘相减+- 抖线:`Cartoon(..., boil=2.0)`,每次 `stage()` 用一张新的平滑位移场重描墨线(1–2 像素),颜色和铅笔稿不动;`save()` 用第 0 次描线+- 角度都是逆时针为正(同 PIL);颜色常量 `INK PAPER PENCIL WHITE RED YELLOW PINK ORANGE`++**等轴 2.5D `Isometric`**:+- 思路:一台正等轴正交相机加一个小光线追踪器。每个部件都是解析实体(平面围成的凸多面体、任意轴向的圆台、可被平面切开的椭球),逐像素求交写进 G-buffer(深度、法线、反照率、材质),画的先后不影响遮挡。同样的实体再从太阳方向画一张阴影图、从正上方画一张记录「柱子顶和底」的高度图,最后统一算光:天空环境光 × AO + 太阳 × N·L × 软阴影(PCSS,半影随遮挡距离变宽)+- 构造:`Isometric(W, H, seed, scale=每格像素, look=(x, y, z), at=(屏幕比例 x, y), sun=(x, y, z), ss=2, floor=-2.4, record=True)`。世界 x 朝屏幕左下、y 朝右下、z 朝上,一格 = 1。`iso(x, y, z)` 世界 → 屏幕;`unproject(sx, sy, z)` 屏幕 → 该高度平面上的世界点(按屏幕位置摆悬浮物)+- 地面:`backdrop(top, bottom, glow, centre)` 浅色渐变和底座下面看不见的地板(接住底座的影子);`slab(x0, y0, x1, y1, z0, z1, layers)` 漂浮的分层底座;`tiles(levels, heights, colours, soil, gap, paved=(4,))` 倒角地砖(0 海、1 沙、2 草、3 台地、4 铺装);`sea(shallow, deep, foam, waves)` 海面(岸边浪花、断续第二道浪线、深浅过渡、浪短线、透亮侧壁);`top_z(x, y)` 取砖面高度;`road()` 带中心虚线的路;`path(cells)` 石板+- 基本体:`box(x0, y0, z0, x1, y1, z1, colour, side, bevel)` 倒角盒子;`obox(centre, size, yaw, pitch, roll)`;`prism(pts, z0, z1)`;`convex([(normal, d)], lo, hi)`;`cylinder(x, y, z0, z1, r, r1=None)`(给 r1 是圆锥 / 圆台);`tube(p0, p1, r)`;`ellipsoid(centre, radii, yaw, pitch, roll, clip=[(normal, d)])`、`sphere()`、`dome()`。都接受 `paint(P, n, tag)`(按世界坐标上色:砖缝、土层、瓦行、百叶、电池片、卡面文字)、`mat='matte'|'water'|'glass'|'soft'|'gloss'|'card'`、`cast=`(投不投影)、`ao=`(进不进高度图:悬浮物和细线都关掉)+- 建筑:`building(x0, y0, x1, y1, z, h, wall, roof='gable'|'hip'|'shed'|'flat', roof_colour, axis, windows=(行, +x 墙几扇, +y 墙几扇), door=('+x', 位置), trim)`;`roof()`;`window(x, y, z, w, h, facing)`(白框、十字棂、斜向天光、窗台);`door()`;`sign(x, y, z, w, h, '字', facing)`+- 自然与道具:`tree(x, y, z, size, kind='round'|'pine'|'poplar'|'bush', flowers=)`、`rock()`、`cloud()` 平底云、`windmill(x, y, z, h, yaw, spin)`、`windsock()`、`dish()` 卫星天线、`solar_panel()`、`fence(pts, z, h, closed)`、`pier()`、`boat()`、`balloon()`+- 信息图:`card(x, y, z, w, h, facing='+x', title, tag, value, unit, note, series, icon='wind'|'temp'|'rain'|'balloon'|'sun', anchor=(x, y, z), accent)` 竖在空中的数据卡(文字印在等轴平面上,带细引线和锚点);`compass(x, y, z, r, north)` 平躺在地面上的指北针;`text()`、`rule()`、`dot()` 平面排版叠在最上层+- 光:太阳从左后上方来,顶面最亮,+x 面(左下)次之,+y 面(右下)只吃天光;`sun_c / sky_c / hor_c / gnd_c`、`soft`、`pen`(最小 / 最大半影)可调。不要霓虹发光、泛光和描边++**扁平矢量 `FlatVector`**:+- 思路:矢量软件的画板。每样东西都是边缘干净的几何形 `Mask`(覆盖率小块 + 偏移);`|` 并、`&` 交、`-` 减、`moved(dx, dy)` 平移,只算包围盒重叠处,上千个形状也在 1 秒内+- 形状:`circle` `ellipse` `rect` `rrect(x0, y0, x1, y1, r 或 (左上, 右上, 右下, 左下), rot)`;`capsule(p0, p1, r0, r1)` 锥形胶囊,`limb(点列, 半径列)`,`tube(控制点, r)` 平滑曲线管;`poly(pts, round=)` 圆弧倒角多边形;`arc` 环段、`pie` 扇形、`leaf(p0, p1, 宽, bend)` 叶片、`star`;`split(m, p0, p1)` 取直线左侧的部分;`text_mask`+- 上色:`fill(m, 颜色, alpha, grain)`;`tone(c, k)`:k<0 向墨色混、k>0 向奶油色混,所有明暗都是色板色的色调+- 体积(色块叠压):`shade(m, strength, depth)` 背光侧月牙(形状减去朝光源挪动的自己);`glint()` 受光侧亮月牙;`plane(m, p0, p1)` 直线切面;`cast(m, dx, dy, clip=)` 硬边投影(乘墨色,落在几种颜色上各自变深);`darken` / `lighten`+- 人物 `person(hip, 身高, facing, lean, head_tilt, arm=(上臂, 前臂), leg=(大腿, 小腿), sit, hand_to, hand_far_to, foot_to, foot_far_to, top, bottom, shoes, skin, hair, hair_style='short'|'bun'|'bob'|'long'|'pony', coat, skirt, apron, bag, draw_near_arm)`:7.5 头身、无五官,远侧手脚暗一档;角度从「竖直向下」量起、朝面向为正;返回关节字典(hand、hand_far、head、knee…);`draw_near_arm=False` 时先画道具,再调 `near_arm()` 让手压在道具上+- 物件:`books(x0, x1, 书脚y, 最高, 颜色, gap_at, gap_w, stack_at, back=背板遮罩)` 一排书脊;`book(cx, cy, w, h, rot, colour, open)`;`plant(kind='leafy'|'snake'|'round')`;`pendant(x, 顶, y, r, beam_to=)`;`cat(tail_down=)`;`cloud`;`sun(rays)`;`dashes(点列, arrow=)` 运动虚线;`sparkle`;`text(s, x, y, size, font_style='geo'|'geo_medium', cjk='cjk'|'cjk_light')`+- 颜色常量 `INK BLUE CORAL MUSTARD TEAL PEACH CREAM`;`light=(0.8, -0.6)` 是指向光源的屏幕方向;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**单线画 `LineArt`**:+- 思路:整幅画是一条路径。先把各个形状做成点列,再 `chain()` 按作画顺序串成一条线;线只栅格化一次成「时间图」(每个子像素记住笔第一次经过时走了多少像素),画到哪一步就是 `时间 <= s`+- 底:`backdrop('night'|'cream')`:深蓝丝绒底(中间亮、细颗粒)或奶油纸,同时设定默认线色(金 / 墨)和点睛色(琥珀 / 朱红)+- 形状(静态方法,返回点列):`smooth(控制点)` 样条、`poly(点, r, sharp=(下标,))` 圆角折线、`arc(cx, cy, rx, ry, a0, a1)`、`scallop(cx, cy, r, a0, a1, bumps, depth)` 树冠灌木的扇贝边、`place(点, 原点, angle, scale)` 局部坐标摆放、`curl(P, s, r, span, side, aspect)` 在路径第 s 像素处插一个翻圈、`retrace(点)` 原路去再原路回+- 路径:`chain([(名字, 点列), ...])` 返回 `(P, marks)`,断开处自动用切线连续的三次曲线接上;`trim(P, s0, s1)` 按长度裁剪;`locate(P, (x, y))` 最近点的长度;`at(P, s)` 取点和方向;`length(P)`+- 画线:`line(P, width, pressure=[(s0, s1, 倍数)], sheen, glow, hot)`:起笔轻、收笔长尖、压力缓慢起伏、急转处变粗、原路折返处提笔收尖;深色底上是随角度变亮、只带一点柔光的金线+- 动画:`draw_to(s 或 marks 名字)` 移动笔头,没画完时笔头带光点、刚画的一段更亮;`stage(name)`+- 点睛:`accent(遮罩, 颜色, glow, warm)`,遮罩用 `rect()`、`disc()`;深色底上会发光,并把附近的线染暖+- 文字:`text(s, x, y, size, colour, font='display', spacing)`(Didot 类衬线,中文自动换细宋体)、`text_width()`、`hairline()` 细装饰线+- 颜色常量 `GOLD GOLD_HI GOLD_LO AMBER VERMILION NIGHT CREAM INK`;`save('x.jpg')` 默认 quality 88、4:4:4++**柔光 3D `Soft3D`**:+- 真 3D:`Soft3D(W, H, seed, eye, target, fov)` 针孔相机,世界坐标 X 右、Y 上、Z 远离镜头;每个像素一条光线,numpy 在 CPU 上算+- 球海 `ball_field(x0, x1, z0, z1, r, gap, colours, weights, mat)`:方格上成千上万颗球,光线逐格查找(DDA),每格只测一颗球,十万颗也不慢;`tint_balls(x, z, radius, colours, chance)` 局部换色;`floor(颜色)` 球缝里看到的地板+- 主体(有向距离场,只在自己的包围盒里步进):`text(s, at, size, depth, colour, mat, yaw, spacing, bob, roll, turn, dot)` 鼓鼓的挤出字(字形→精确距离变换→挤出、整圈倒圆、再吹胀;`dot=颜色` 把 i/j 的点换成一颗球;返回 {'heroes', 'dots', 'centre'});`rbox()` 圆角盒、`capsule()` 胶囊、`cylinder()` 圆角圆柱、`torus()` 圆环+- `part(heap, reach, pile, pile_top)`:主体从球海里顶出来,被挤开的球落进最近的空窝、堆在脚边(pile 是被挤开球数的倍数,pile_top 是堆的最高高度,别让它挡住字的下半截),周围的球海微微隆起+- 散球:`ball(x, y, z, r, 颜色)` 指定位置;`drop(x, z, r, 颜色, roll)` 从上方落下碰到东西为止,再往低处滚进窝里(roll=0 停在落点,比如骑在字肩上)+- 灯光:`sky(top, horizon, strength, haze, haze_start)` 天光穹顶(背景渐变、地面反光、远处雾);`key(azimuth, elevation, strength, size)` 大柔光箱主光,size 越大影子越软;`rim()` 轮廓光;`softbox()` 只出现在反光里的灯片。方位角从镜头算:0 从相机身后,−90 左,+90 右,180 主体背后+- 材质 `mat=`:candy(清漆糖果,锐利灯片高光)、satin(缎面小球)、jelly、matte、pearl;缝隙和阴影变深变饱和而不发灰+- `lens(focus, aperture)` 景深(focus 可传 text() 的返回值或一个点,最好和相机一起先设);`film(bloom, vignette, grain)`+- `save(path, stages_dir, ss=1.5)` 成片超采样;`stage(name)` 是当前场景的真实预览渲染,还没调用 sky() 时是灰色白模++**形变动画 `Morph`**:+- 思路:每样东西都是**一条**闭合轮廓;两条轮廓重采样成同样点数(默认 `Morph.N = 256`)、统一绕向、对齐起点,再逐点插值,就是形变;背景色和形状颜色跟着切换+- 形状库 `shape(name, cx, cy, size, rot, flip, stretch)`:`SHAPES` 有 circle / square / triangle / star / heart / drop / cloud / snowflake / mountain / river / wave / sun / moon / leaf / bird / fish / pin / house;`union([('circle', x, y, r), ('line', 点列, 宽), ('poly', 点列), ('sub', 图元)], cx, cy, size)` 用图元拼出自己的形状,自动描出外轮廓+- 几何:`resample(P, n)` 按弧长等距重采样;`normalise(P)` 顺时针、从正上方起;`align(A, B)` 统一绕向并用 FFT 找最佳起点;`chain([...])` 整串依次对齐;`ease(t, 'inout'|'sine'|'quad'|'in'|'out'|'back'|'expo'|'linear')`;`tween(A, B, s, at=, stretch=, direction=, spin=, scale=)` 轮廓绕质心插值、质心单独走运动路径,stretch 是沿运动方向的挤压拉伸;`at(keys, T)` 整串关键帧在全局时间 T 的轮廓(逐帧做真动画用);`mix(c0, c1, t)` 在 OKLab 里混色(蓝到黄不发灰)+- 背景:`paper(颜色)`;`panel(x0, y0, x1, y1, 颜色, ink=)` 一块纯色面板,ink 是画在这块面板上的残影和线条默认用的颜色;`wipe(cx, cy, r, 颜色, ink, clip_box)` 定格的圆形转场+- 形状层:`fill(P, 颜色, alpha, clip=另一轮廓, half=((x0, y0), (x1, y1)))`,half 只填直线右侧,用来做两色折面;`outline(P, 颜色, width, dash=(实, 虚))`;`stroke(点列, 颜色, width)` 圆头线(高光、水纹、热气);`dot()`+- 定格动画:`ghost(P, fill, fill_alpha, line_alpha, width)` 洋葱皮残影,线色为 None 时取下面面板的 ink,跨面板自动换色;`points(P, every)` 标出对应点;`links(A, B, every)` 对应点连线;`path(点列)` 过质心的平滑路径,`along(路径, u)` 取点和方向;`trail(路径, dash=)` 运动轨迹;`chevron()` 方向箭头;`streaks()` 速度线+- 时间轴:`diamond(x, y, r, fill)` 关键帧菱形;`ease_curve(x0, y0, x1, y1, kind, ticks=帧时间)` 一段缓动曲线,带帧点和虚线投影+- 文字 `text(s, x, y, size, 颜色, font='sans'|'display'|'mono'|'mono_bold'|'cjk'|'cjk_bold', anchor='l'|'m'|'r', spacing, alpha)`:y 是基线,中西文自动换字体,返回宽度;`text_width()` 量宽度+- 坐标都是像素、y 向下;角度逆时针为正++**报刊拼贴 `NewsCollage`**:+- 思路:每样东西都是「先印好、再撕或剪、最后粘上去」的一张纸 `Sheet`;老照片不是贴图,而是 `Photo` 用高度图布光渲染出来,再印成网点+- 底板:`board()` 牛皮纸(云状纸浆、深浅短纤维、树皮碎屑)+- 纸片:`sheet(w, h, 颜色)` 返回 `Sheet`,可用 `text()`、`block(…, minus=文字遮罩)` 反白字、`ink()`、`rule()`;`tear('rtb', depth, rim)` 手撕(边线游走、露出白色纸芯、飞出纤维),其余边算剪刀剪;`cut_rect()` 歪一点的剪刀四边形;`cut(pts)`;`wrinkle()` 浆糊起皱;`age()` 泛黄和霉斑+- 报纸:`newsprint(w, h, columns, size, headline, picture, ad)` 返回一整版假报纸(伪词栏、刊头线、大标题、导语、小标题、栏线、框线广告、网点小照片、背面透印),接着 `tear()`+- 老照片:在 `Photo(w, h)` 上搭物件:`disc()`、`dome(…, rot, cut)`(钟铃、球)、`ring()`(表圈)、`rod()`、`poly()`(指针)、`gear(r, teeth, spokes, pinion)`、`spiral(r0, r1, turns, flare)`(发条、游丝)、`screw()`;`text()` / `lines()` 印在表面的字和刻度;`glare()` 玻璃反光。z 是底座高度,height 是自身厚度,albedo / metal / gloss 是材质+- 印成网点:`print_photo(photo, cell, angle, ink)` 显影并印成网点,返回 Sheet;`s.cutout(margin, centre)` 沿轮廓用剪刀剪下;`s.split(p0, p1)` 一剪两半+- 粘贴:`paste(sheet, cx, cy, rot, lift)` 返回 Frame,`f.pt(lx, ly)` 把局部坐标换成画面坐标;`disc(cx, cy, r, 颜色)` 剪刀剪的色纸圆+- 字:`ransom('拆开看看', x, y, size, faces=[…], styles=[…])` 勒索信拼贴字,返回 [(Frame, 字)];`clipping(字, size, face, paper, block, fg, extra)` 单个剪字,extra 可选 'text'(带邻字)或 'tint'(网点底);`label(文字, x, y, size, face, fg, bg, block)` 剪下的一条印刷字+- 其他:`tape(cx, cy, 长, rot)` 美纹纸胶带;`stamp(cx, cy, [(字, 字号)], shape='box'|'round', ring=环形字)` 橡皮章;`pen(pts, dash=(实, 虚), dot)` 墨线引线+- 字体:news / news_bold / news_italic / serif_bold / slab / clarendon / didone / poster / futura / grotesk / typewriter(_bold) / cjk_song / cjk_hei / cjk_round / cjk_kai;缺字自动换中文黑体+- 颜色常量 `INK BLACK RED MUSTARD KRAFT NEWS PAPER TAPE`;rot 逆时针为正++**弥散玻璃 `Aurora`**:+- 思路:一块明亮的「光屏」(弥散渐变)上面悬着几片真的磨砂玻璃。透过玻璃看到的是它下面**真实像素**的高斯模糊(背景、小球、后面的卡片和字都算),再蒙一层白纱,界面印在玻璃上。先画的在后面,后画的卡片会把前面画好的卡片连字一起模糊+- 背景:`backdrop(base, blobs=[(x, y, rx, ry, 颜色, 强度)], ribbons=[(点列, 宽, 颜色, 强度)], warp, grain)` 网格渐变:色团按权重在 OKLab 里混色,坐标扭曲成不规则形状,光带沿样条走,自带细颗粒;`sparkles(n)` 零星光点;`orb(cx, cy, r, (亮, 中, 暗))` 光泽小球:虹彩色阶、菲涅尔边缘映出背景色、高光、落在背景上的彩色投影+- 玻璃:`glass(x0, y0, x1, y1, radius, blur, tint, sat, shadow, elevation, bevel, rim, sheen)` 返回 `Card`(x0 y0 x1 y1 w h cx cy r)。blur 是磨砂程度(约 20–30);tint 是白纱(约 0.24,近光源一侧厚);sat 是透过来的颜色饱和度(约 1.5);bevel 是边缘斜面,向外折射,各色通道偏移不同,带很淡的色散;rim 是朝光边的高光描边;阴影只落在卡片外,颜色取自下面的背景。`pill()` 是小玻璃胶囊(按钮、提醒、高亮行,玻璃叠玻璃),`cloud(cx, cy, w)` 是玻璃云+- 形状(带符号距离场,1 px 解析抗锯齿):`rrect()`、`circle(ring=线宽)`、`line(点列, smooth)`,都可以传 `grad=色阶, angle=`;`divider()` 是蚀刻细线+- 控件:`toggle(x, y, on)`、`slider(x0, x1, y, value)`、`knob()`、`ring(cx, cy, r, width, frac)`(从 12 点顺时针,锥形渐变、圆头、光晕、末端白点)、`check(cx, cy, r, 'done'|'now'|'todo')`、`bars(x0, y0, x1, y1, values, labels=, highlight=)`、`spark(x0, y0, x1, y1, values, dots=)`(返回各点坐标)、`sun()`、`app_icon(x, y, size, grad, glyph)`+- 文字 `text(s, x, y, size, fill, weight='light'|'regular'|'medium'|'semibold'|'bold', anchor, alpha, spacing, grad)`:西文用 SF(按字号调光学尺寸),中文用苹方,自动分段;anchor 第二个字母 s 基线、m 居中、t 顶、b 底;`text_width()` 量宽度+- 颜色:`INK` 深靛文字;渐变色阶 `WARM`(杏→粉→紫)、`COOL`(天蓝→长春花→紫)、`MINT`;`ramp(t, stops)`、`mix()` 在 OKLab 里插值。一种渐变只代表一件事+- `save('x.jpg')` 默认 quality 88、4:4:4 色度++**包豪斯几何 `Bauhaus`**:+- 思路:画面是一张丝网印刷的印张,每种颜色一块网版,先浅后深逐版刮印;同一色版上的所有东西共享这块版的套准误差(平移加极小旋转),所以色块和黑线相接处会露出一丝纸白或压出一道深边+- 纸:`paper(colour, margin, module)` 奶油色未涂布纸(云状纸浆、短纤维、纸屑、纸齿、微微不平的受光),同时设定设计区和网格模数;`at(col, row)` 网格坐标转像素;`grid()` 用浅灰色版印构成网格+- 遮罩(全画布、抗锯齿,可以相加相减):`circle()`、`ring()`、`sector(cx, cy, r, a0, a1)` 半圆和四分之一圆、`arc()`、`rect(x0, y0, x1, y1, rot)`、`bar(x0, y0, x1, y1, width, cap='butt'|'square'|'round')` 粗黑条和细线、`poly()`、`triangle(x0, x1, base_y)`(默认正三角)+- 印刷:`pull(mask, ink, knock, edge, density, opacity)` 刮一版:墨膜顺刮板方向有条纹、行程末端变薄,薄处露出纸齿坑点,网版灰尘留针孔,版边有网目锯齿、边缘略积墨;墨半透明(黄最透、黑最不透),叠印变深。`knock` 是挖空遮罩,`edge=0` 让细线保持干净+- 文字:`text(s, x, y, size, ink, font, anchor, spacing, rot, weight)` 直接印;`text_mask()` 取遮罩用来挖空;font 用 geo(Futura Bold)、geo_book、geo_cond(窄体特粗)、cjk(粗黑体)、cjk_book,中西文逐字换字体;`text_width()` 量宽度+- 印刷标记:`marks(targets, crop, bar, inks, overprints)` 套准十字、四角裁切线、色标条。登记后每块色版第一次刮印时自动印上自己那一份,所以十字会叠成几色错开的样子+- 印完之后:`pencil(s, x, y, size)` 页边铅笔版号,石墨只挂在纸齿凸起上+- 颜色常量 `YELLOW RED BLUE BLACK`,纸色 `PAPER`,网格色 `TINT`;角度逆时针为正,0° 指 3 点钟;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**复古 Synthwave `Synthwave`**:+- 思路:+ - 一台水平针孔相机看向无限平地(X 右、Y 上、Z 向前,单位米),颜色缓冲从远到近画;+ - 会发光的东西同时写进发光缓冲,后画的不透明物会挡掉身后的光;+ - 最后四个半径泛光,过曝的通道溢向白色,成片再「过一遍录像带」+- 构造:`Synthwave(W, H, seed, horizon=610, vp_x=1060, focal=1100, eye=3.5, record=True)`;相机工具 `project(X, Y, Z)`、`ground_row(Z)`+- 天空:`sky(stops, ground)` 暮色渐变,地平线下先铺没点亮的地面;`stars(n, bright)` 越近地平线越稀,最亮的带四角星芒;`streaks([(y, x0, x1, 厚)])` 底边被照亮的细条云+- `sun(x, y, r, bands=8, band_top, gaps=(0.2, 0.7), level, gain)`:黄→橙→粉渐变落日,横条切口越往下越厚,切口是真缺口;在地平线处截断+- 远景:+ - `mountains(x0, x1, z0, z1, height, cell, taper, edge=(MAGENTA, CYAN))`:世界坐标里的抖动网格高度场,三角面暗色平涂,边线从山脚品红渐变到山脊青色;+ - `skyline(X0, X1, Z, heights, widths, tall=(X, 高), windows)`:远处小城剪影、窗光、航空红灯+- 地面:+ - `floor(colour, spacing, width, fog, scroll, x_range)`:霓虹网格,逐像素解析线宽,远处换成平均值防摩尔纹,带粉色地雾和太阳光带;+ - `sea(coast, bar, spread, sky, glitter, stretch)`:X < coast 一侧的海,倒影碎成一条条光带;+ - `road(x0, x1, dash)`:光滑路面加霓虹边线和中心虚线;+ - `neon_line(X, colour, width, dash)`:地上任意一条纵向霓虹线(海岸线)+- 物件:+ - `palm(X, Z, height, lean, fronds)`:棕榈剪影,环节树干、仰角不一的叶柄、下垂小叶、椰子、朝太阳一侧的轮廓光;+ - `car(X, Z)`:背影跑车,整条尾灯和路面上的红色倒影+- 字:+ - `chrome_text(s, x, y, size, depth, glints=(字序号...))`:镀铬大字,深色描边、阶梯挤出、发光浅边,上映天空、下映地面,中间一道锐利地平线,左上打光的倒角和四角星闪;+ - `glint(x, y, length)`:单独一个四角星闪;+ - `neon_script(s, x, y, size, colour, rot)`:霓虹手写体;+ - `caption(s, x, y, size, colour, rules)`:字距拉开的小字加两侧细线+- 录像带:+ - `osd(s, x, y, px, anchor)`:5×7 块字的录像机屏显(PLAY ▶、日期);+ - `vhs(bleed, shift_px, jitter, noise, scan, tracking, head)`:只作用于成片,包括 YIQ 色度模糊右移、重影振铃、逐行抖动、一条跟踪噪带、底部磁头噪声、掉磁白线、扫描线、黑位抬升;阶段快照保持干净+- 颜色常量 `MAGENTA CYAN VIOLET ORANGE YELLOW PINK RED WHITE`;字体用 `synth_font('chrome'|'script'|'caption', size)` 找系统字体(Avenir Next Heavy Italic / Brush Script / 冬青黑体),可用 `INKPAINT_FONT_CHROME` 等指定;`save('x.jpg')` 默认 quality 88、4:4:4 色度+**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。## 三、毛病清单(都真实出现过)@@ -395,11 +542,162 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask| 光轨沿街飞,全都汇向灭点,像激光或钢丝 | 让飞车横穿街道:从一侧墙后出现,拱形掠过,消失在另一侧墙后;加频闪点 || 全息水母的 1 像素线被雾和扫描线吃掉;C 形生殖腺像数字「93」,后排两个像一双眼睛(成了脸) | 线宽至少 2 像素;生殖腺放在伞内的水平面上,侧视压成一条柔和的粉带;副标用 Light 字重,撕裂切片别落在字上 |+**卡通手绘**++| 问题 | 改法 |+|---|---|+| 窗外的太阳画到了墙上 | 窗里的东西都乘玻璃遮罩;被挡住的轮廓只画露出来的那段弧(`ellipse_pts` 给 a0/a1) |+| 手臂从头顶直直伸出、末端一个圆球,像触角或棒棒糖 | 肩膀放在身体侧面中部,先画手臂再画身体;bend 的正负让手肘朝外弯;手套加拇指、袖口和两道指缝 |+| 两个角色挨得太近,一个的手套落到另一个脸上 | 只画外侧那只手臂,内侧的藏在身后 |+| 烤色蜡笔涂在面包中间,像脸上的脏污 | 烤色只涂面包芯内缘一圈(轮廓遮罩减去内缩的轮廓),脸所在的中间保持干净 |+| 纸纹太粗,色块上像砂纸 | 纸纹受光约 0.026,颜料盖住的地方纹理减半(已处理) |+| 闪光星像菱形 | 用指数约 3 的星形线,竖向拉长(已处理) |+| 白字写在米色纸上看不见;白云、手套、烟团都是白色小圆团,挤在一起分不清 | 浅色字只写在深色块上;白色圆团之间拉开距离,背景里不放白云 |+| 飞溅的碎屑落到脸上 | `crumbs(..., avoid=角色遮罩)` |+| 动图 2.3 MB:铅笔稿每阶段换强度又跟着抖,网点和蜡笔也跟着抖,每次叠化都整片重编码 | 只抖墨线,颜色和铅笔稿留在纸上不动;铅笔稿强度在勾线之后固定;阴影和质感合成一个阶段(1.9 MB) |+| 黄油的嘴压在底边线上;滴落太小,水洼像一根黄条 | 脸按物件正面的高度缩放、上移;滴落画成从前沿挂下来连到水洼的一道,最后画,压在轮廓线上 |++**等轴 2.5D**++| 问题 | 改法 |+|---|---|+| 白墙整面发灰,比同一面墙上方的山墙暗一截 | 高度图 AO 会把楼自己的高度算进墙面;侧面改为沿法线(及左右 40°)看地平线,只算挡在前面的东西(已处理) |+| 屋檐、树冠被当成实心柱子,墙顶一圈发黑 | 顶视图同时记录最高那根「柱子」的顶和底:相接的实体合并,悬空的单算,只挡它实际覆盖的那段仰角;檐下不算墙角折痕(已处理) |+| 平顶楼墙上出现一条锯齿状灰带 | 柱子的顶 / 底不能跨边插值:细檐口一插值就在墙边造出一块假悬空板;改最近邻采样(已处理) |+| 长投影的半影满是颗粒 | PCSS 每像素旋转采样之后,再做一遍按深度保边的可分离模糊(已处理) |+| 海面上的短浪线竖着立起来 | 等轴视角里世界 (1, 1) 是屏幕竖直方向;浪线沿世界 y − x 走才是屏幕水平(已处理) |+| 砖缝像棕色勾缝,沙滩缝像一根根圆木 | 草地砖侧面保持草色,只让台地露出土层;缝宽约 0.028 格 |+| 岛占满底座,沙滩一圈像棋盘,看不出是岛 | 屏幕左下、右下两条前边留 1.5–2 格海面;沙滩只放在部分岸边 |+| 卫星天线正对镜头,像棒棒糖或路牌 | 朝向和视线错开(yaw 约 125°、仰约 50°);反射面中间暗、边缘一圈亮(已处理) |+| 数据卡字太小,折线图压到单位上 | 卡片约 2.9 × 1.65 格,大数字约 0.7 格高;折线图从「数值 + 单位」之后开始(已处理) |+| 引线横穿房顶,画面乱 | 卡片围着各自仪器摆,用 `unproject()` 按屏幕位置定点,引线短、不跨主体 |+| 草地上散落的小花像彩色糖珠 | 花开在灌木上:`tree(kind='bush', flowers=…)` |++**扁平矢量**++| 问题 | 改法 |+|---|---|+| 头发像头巾,从前到后裹住脸一直到下巴 | 头发 = 大一圈的椭圆减去向前下方挪动的脸,再沿「后颈→太阳穴」的发际线切掉下半;波波头另加一块只在下颌后面的发帘 |+| 耳朵画在脸中间 | 耳朵放在发际线上(头心向后约 0.12u),画在头发之后 |+| 颗粒太重,大色块像砂纸 | 全画面颗粒约 1%,以细颗粒为主;只有光束、光斑用 `grain` 打散透明度 |+| 手脚按角度摆,手伸进标题、脚踩空 | 用 `hand_to` / `foot_to` 目标点(两段 IK):手落在栏杆和书上,脚落在梯级上 |+| 3/4 侧身用近侧手臂向前上方够东西,手臂横扫过脸 | 改用远侧手臂(从前肩出发,画在头后面),近侧手臂垂下挎包 |+| 没有描边,深色头发、深色裤子、黑猫贴在深色书架或楼影上就消失 | 按身后背景定明度:银发、橘猫、深裤配中蓝护墙板、浅色鞋;深色衣服的远侧手脚改为提亮一档 |+| 书脊的色带和书名短线交叉成「+」,像十字架 | 色带只放书头书脚,书名短线放中段 |+| 抽走那本书留下的空位被人挡住,故事看不出来 | 空位放在开阔处,邻书以底角为支点倒进空位,从空位拉一条珊瑚色虚线到手里的书 |+| 珊瑚色花盆、书架上的珊瑚色书跟主角抢眼 | 点睛色只留给画面要讲的那一样东西 |+| 动图把小面积的珊瑚色量化成褐色;透明占位色是黑色时,最暗的阴影像素变透明 | 中值切分前饱和像素 ×5,强制放入七个色板色;占位色改成纯品红 |++**单线画**++| 问题 | 改法 |+|---|---|+| 纸飞机画成小三角,像风筝或三角旗 | 用 3/4 俯视的飞镖形:近翼大、远翼透视缩小、中间一道折痕;笔从尾部缺口进、从机头出,四个角保持尖 |+| 航迹从谷底地面起飞又落回地面,看不出从哪飞到哪 | 线从 A 屋的窗里穿墙飞出,从机头穿墙飞进 B 屋的窗;两屋之间不画地面 |+| 翻圈放在爬升段,像挂在线上的气球或套索 | 翻圈放在轨迹顶部、路径接近水平处,`curl(..., aspect≈1.2)` 让圈更圆 |+| 航迹和房子一样粗、从地面附近起落,整条读成山丘或山脉轮廓 | 航迹段 `pressure=[(s0, s1, 0.62)]` 用轻手画细,从窗口直接上扬,不先下沉 |+| 轨迹末端急转直下,在飞机尾部勾出钩子,还和后翼边贴成细长条 | 把飞机尾部缺口的坐标作为轨迹最后一个控制点,入射角放缓到约 35° |+| 窗户、山肩这类要从里面够到的形状一笔连不过去;原路回来的短线头是钝圆头 | 用 `retrace()` 原路去再原路回(成图看不见);原路折返处自动提笔收尖(已处理) |+| 树冠贴着屋檐,两样东西粘成一团 | 物件之间留出间隙 |+| 动图里深蓝渐变出现一圈圈色带,唯一的琥珀色窗被量化成米黄 | 调色板拆开:空底色 110 色、画出来的东西 145 色(饱和像素 ×6);量化前加固定的 4×4 Bayer 抖动,每帧相同 |++**柔光 3D**++| 问题 | 改法 |+|---|---|+| 掉下去的球悬在字上方,字面上有莫名的暗斑 | AO、阴影、落球这类查询在包围盒外用了盒子距离,球停在了看不见的盒子上;字形距离网格覆盖的范围内一律用精确距离(已修) |+| 字脚一圈球发黑,字的下半侧有黑带 | 球海距离场只查 2×2 格、封顶半格,清空的格子旁边 AO 以为贴着球;改查 3×3 格、封顶一整格,AO 半径 0.3、强度 1.25、留 0.1 的底(已修) |+| 字从球海冒出来,脚下一圈空槽露出黑地板,像抠图 | 被挤开的球不删,按「落进最近的空窝、层层叠、要有三点支撑」堆到字脚:`part(pile=10, pile_top=0.3)` |+| 字埋得太深,s 只露出上半截像 c,整词读成 rice | s、e 用 bob 单独抬高,让它的下半弯露出来;part() 加 pile_top=0.3,只堆一层,堆起的球不能高过字母下半部 |+| 阴影里的薄荷球发青灰、发脏 | 淡紫天光乘薄荷色会发灰:阴影加按材质自身色调的次表面补光,天光调强、主光调弱 |+| 球排成直行一直通到远方,像条纹墙纸 | 整个场景转 30°,行列斜着走 |+| 清晰的字边有锯齿,高光一节一节 | 成片 1.5 倍超采样再 Lanczos 缩小;字形距离场模糊 2 像素,法线差分步长 2.5 个格(已处理) |+| 上三分之一一片惨白,远处和背景之间有一道硬地平线 | 雾色等于背景地平线色,雾距约 42;镜头稍抬,露出天空渐变 |+| 动图 3.4 MB,小黄球被量化成一块平色片 | 景深跟相机一起先设好(每个阶段都柔),曝光并进灯光强度,主光和轮廓光合成一个阶段;调色板样本里彩色像素 ×5 |++**形变动画**++| 问题 | 改法 |+|---|---|+| 起点、绕向没对齐,中间帧塌成一条条碎片 | 先 `normalise`(同样点数、顺时针、从正上方起),再 `align`(FFT 互相关找最佳起点);一串关键帧用 `chain` 依次对齐 |+| 每段 5 个残影、关键帧又太大,雪花和云的花边残影叠成一片噪点 | 关键帧约占面板宽的六成;每段只画 3 个残影,中间那帧填色约 0.42,两侧只留细线和约 0.14 的淡填色 |+| 运动轨迹画成圆点,和中间帧上的对应点混在一起,看着像轨迹绕了个圈 | 轨迹用虚线(`trail(dash=)`),圆点只用来标对应点,图例里分开写 |+| 速度线等长等距,像梯子,落在河边还被当成水流线 | 海报里不画速度线,靠挤压拉伸和残影间距表现速度 |+| 纸纹把奶白色的云也盖成了砂纸 | 形状保持纯平:纸纹只加在露出的纸面上(`tooth` 遮罩),面板和形状只有极轻的印刷颗粒 |+| 闭合样条在直角处过冲,海浪底角鼓出一个包;太阳的细光芒是断开的小棍 | 只对曲线部分做样条,底边用直线接;光芒用楔形加圆头,和圆盘连成一体再描外轮廓 |+| 后一段的残影线压在前一个关键帧上;标签重复画了两遍,颜色变深 | 画完残影后重画前一个关键帧(只重画形状内的细节);文字和形状外的点缀只画一次 |+| 「↺」在所用中文黑体里没有字形,显示成方框 | 循环箭头用 `outline` 画圆弧再加 `chevron`,方向取圆弧终点的切线 |++**报刊拼贴**++| 问题 | 改法 |+|---|---|+| 齿轮像一块灰饼:齿面和背景一样亮,窗口被投影压灰,齿比网点还细 | 齿面反照率约 0.56、metal 约 0.3,加车床纹的「领结」反光;抬起高度约 8,背景投影 0.35;齿距至少约 4 个网点(r=108 用 36 齿),剪边约 9 px |+| 发条画成一圈圈同心圆,像靶子 | 圈数 4–5,`flare` 约 1.6:里圈密、外圈松,才看得出是螺旋 |+| 打字机字体没有「→」,出现豆腐块 | 逐字检查字形,缺字自动换中文黑体(已处理) |+| 问号纸片压住主体表盘的数字 | 用上一个字的 Frame 算位置,整排标题缩小;主体整体右移给标题让位 |+| 红章盖在密密的报纸字上认不出 | 章盖在牛皮纸的空处 |+| 邮戳环形小字断成「CUR:OSTI」 | 环形字至少 18 px;橡皮漏印改成部分漏墨(0.3 + 0.7 × keep),细笔画不断(已处理) |+| 剪下的照片白边处处一样宽,像模切贴纸 | 白边宽度沿周长慢慢变宽变窄(`wander` 约 0.45),但永远不剪进物体(已处理) |+| 散落的零件看不出是从闹钟里飞出来的 | 先从缺口画几条虚线弧再贴零件,起点错开别汇成尖点;离缺口最近放一颗螺丝 |+| 带邻字的报纸剪字,邻字太大太黑,抢了主字 | 邻字字号约 0.075 倍、浓度 0.62,主字周围留一圈空 |+| 报纸透印太重,镜像标题像渲染错误 | 透印浓度约 0.045,模糊 1.4 px |+| 牛皮纸纤维太长太黑,像裂纹或头发 | 纤维 4–20 px,深色浓度 0.2 |+| 动图调色板被牛皮纸和报纸占满,芥末黄纸片变成土黄 | 调色板取样时高饱和像素算 5 倍(色差 24 → 2.7 / 255) |++**弥散玻璃**++| 问题 | 改法 |+|---|---|+| 前面的卡片压住后面卡片的字(「周三」「60%」被切掉一半) | 卡片只在对方的内边距里重叠(不超过内边距),文字离重叠区远一点 |+| 列表最后一行和底部按钮撞在一起 | 先按行距(约 84)算好列表总高,按钮从卡片底边往上放,不够就加高卡片 |+| 玻璃太「奶」,像磨砂塑料,后面的东西透不出来 | 白纱 tint 约 0.24(近光源一侧厚、另一侧薄),saturate 约 1.5;背景色团之间要有足够的色相差 |+| 小球刚好顶在卡片边上,像放在卡片上面 | 让小球三到四成真正压在玻璃后面,模糊的那一半才读得出「透过玻璃」;小球也别和卡片边相切 |+| 背景的色团和光带几乎全被卡片挡住 | 光带穿过卡片之间的空隙走,色团饱和度提一点 |+| 折线图的面积填充在末端成了一团紫雾 | 填充 alpha 约 0.16,两端各 22 px 渐隐(已处理) |+| 柱状图柱子太细,满高的空槽像幽灵柱,「一」看着像减号 | 柱宽取间距的一半,空槽 alpha 0.1;横轴用日期加「今天」 |+| 动图调色板被浅色背景占满,渐变控件量化成灰,小球出现等高线色带 | 调色板样本给饱和像素加权(×6 / ×3,暗色 ×4),每帧叠同一张 4×4 Bayer 抖动(约 ±2.4 级):逐帧不变,「和上一帧相同」的透明差分照样有效 |++**包豪斯几何**++| 问题 | 改法 |+|---|---|+| 颗粒太重(约一成面积露纸),色块像砂纸、字像磨旧的橡皮章 | 露纸坑点控制在约 2%,只出现在墨膜偏薄的刮板条纹里;黑墨最少(GRAIN 0.4) |+| 坑点成团,像均匀撒了一层雪 | 纸齿用像素级白噪声加少量团块;墨膜另加约 ±2.5% 的浓淡微纹理,不全靠露白点 |+| 方块直角被磨圆 | 版边只做 3×3 轻模糊再加噪声阈值,不用大半径模糊 |+| 页边小字、铅笔版号、色标条压在裁切线上 | 左起 x≈86、右止 x≈1834,色标条末端离裁切线至少 40 px |+| 叠印色标全显示成上层颜色 | 丝网墨基本不透明,叠印色标默认关(`overprints=False`) |+| 黑色标注印在蓝色上看不清 | 深色块上的标注从该色版挖空(`knock=`),露出纸色 |+| 「60 °」度数符号离得太远 | 度数符号自动收紧 0.1 em(`_KERN`) |+| 标题和右上角讲座信息撞在一起 | 先按 120 px 模数排好每栏宽度,信息行写短 |++**复古 Synthwave**++| 问题 | 改法 |+|---|---|+| 太阳被泛光冲成一团白,横条切口被光晕填平 | 太阳底色先压到约 0.72、发光 level 约 0.4,让泛光提回来;切口厚度从条距的 0.2 递增到 0.7 |+| 横穿太阳的细条云像多出来的切口 | 有切口的太阳前面不加 `streaks`,细条云只放在太阳外 |+| 海面倒影是一团糊的圆,像水下还有一个太阳 | 按世界深度把水面切成横带,每带横移、以太阳所在列为中心随机拉伸或压缩(越近越乱),再用短划调制;光源的倒影比天空强约 2.4 倍 |+| 远处网格变成一大片平的橘色雾带 | 雾距 150 m,雾色压暗、偏品红;网格线按屏幕像素距离算覆盖,格子小于几个像素就换成平均值,不出摩尔纹 |+| 录像带噪点像画布纹理,线条满屏抖动打折 | 噪点约 0.014、横向拉长;逐行抖动约 0.35 像素,只留一条跟踪噪带和底部磁头噪声 |+| 霓虹手写字白芯太粗,整句像白字;随机断管像渲染错误 | 白芯只取笔画最中间,core 约 0.5;断管默认不加 |+| 棕榈冠像冷杉,改了又像平顶伞 | 叶柄仰角从陡到平均匀分配,加两片下垂枯叶;小叶在 3D 里朝叶尖前扫、向两侧展开再下垂后投影,不要一律竖直挂下 |+| 城市摆在线框山前面,暗对暗,高楼像幽灵 | 城市放在灭点旁、背靠落日余晖,山脉从城市右边才开始 |+| 小岛挡住太阳正下方,吃掉最亮的一段倒影 | 小岛只和太阳左缘略微相交 |+| 阶段快照里地平线下是整块橘色,太阳下半截露在地上 | `sky()` 先铺一层没点亮的暗色地面;太阳在地平线处截断 |+## 四、做成动画- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。-- 动图规格(多数现有动图和新增四幅一致):720×405;每个阶段停 900 毫秒,再用 5 帧(每帧 90 毫秒)叠化到下一阶段,最后一帧停 2600 毫秒,无限循环。新增四幅的所有帧共用一张 256 色调色板,文件小、不闪烁。+- 动图规格(多数现有动图和后来新增的都一致):720×405;每个阶段停 900 毫秒,再用 5 帧(每帧 90 毫秒)叠化到下一阶段,最后一帧停 2600 毫秒,无限循环。后来新增的动图所有帧共用一张 256 色调色板,文件小、不闪烁。- 调色板别只取最后一帧:满屏单色(黑板的墨绿、赛博朋克的夜色)会吃掉色位,彩色部分被量化成灰。黑板按加权像素样本做中值切分(彩色像素 ×5、亮色 ×2);赛博朋克从全部关键帧的拼图取 255 色,留 1 个透明色标记「和上一帧相同」的像素,并去掉 Pillow 每帧重复写入的局部调色板(3.8 MB → 1.8 MB)。+- 调色板的另外几条经验(新增十种里反复出现):+ - 小面积的点睛色(扁平矢量的珊瑚色书、报刊拼贴的芥末黄纸片、单线画的琥珀色窗、柔光 3D 的黄球)会被量化成褐色、土黄或平色片:取调色板样本时饱和像素 ×5 左右,限定色板的画风可以把色板色强制放进调色板。+ - 大片渐变(弥散玻璃的背景、单线画的深蓝底、Synthwave 的天空)出现一圈圈色带:量化前叠一张固定的 4×4 Bayer 抖动,每帧同一张,「和上一帧相同」的透明差分照样有效。+ - 标记「和上一帧相同」的透明占位色不要用黑色:最暗的阴影像素会被当成透明(扁平矢量自检时 37 帧对不上),改用纯品红这类画面里没有的颜色。+ - 最后一个 `stage()` 和成品完全相同时,Pillow 会把相同的帧合并,按帧数自检会报 EOFError:`save()` 前不要紧挨着再调一次 `stage()`。+ - 卡通手绘的抖线动图只抖墨线,铅笔稿和颜色不动,否则每次叠化都整片重编码,体积翻倍。+- 形变动画可以直接出真动画:`Morph.at(keys, T)` 给出全局时间 T 的轮廓,逐帧渲染即可。- 更细的逐笔动画:把一组笔画单独画到透明层上导出,再用 Motion Canvas 遮罩按顺序显现。这个还没做成现成接口。## 五、文件@@ -423,7 +721,17 @@ lib/sticker.py 贴纸拼贴 · 小票lib/notebook.py 实验笔记本 · 贴纸lib/chalk.py 黑板板书lib/cyberpunk.py 赛博朋克+lib/cartoon.py 卡通手绘(逐帧手绘)+lib/isometric.py 等轴 2.5D+lib/flatvector.py 扁平矢量+lib/lineart.py 单线画+lib/soft3d.py 柔光 3D+lib/morph.py 形变动画+lib/newscollage.py 报刊拼贴+lib/aurora.py 弥散玻璃(弥散渐变 · 玻璃拟态)+lib/bauhaus.py 包豪斯几何(丝网印刷海报)+lib/synthwave.py 复古 Synthwaveexamples/*.py 范例脚本;*.jpg 成品;drawing_*.gif 逐步画出的动图中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT-西文字体(新四种用):core.latin_font(style) 按 sans / sans_bold / rounded / script / hand / typewriter 等找系统字体,可用 INKPAINT_FONT_<STYLE> 指定;字体文件不要放进仓库+西文字体(后来新增的画风用):core.latin_font(style) 按 sans / sans_bold / rounded / script / hand / typewriter 等找系统字体,可用 INKPAINT_FONT_<STYLE> 指定;字体文件不要放进仓库```diff --git a/examples/aurora_morning.jpg b/examples/aurora_morning.jpgnew file mode 100644index 0000000..f089324Binary files /dev/null and b/examples/aurora_morning.jpg differdiff --git a/examples/aurora_morning.py b/examples/aurora_morning.pynew file mode 100644index 0000000..dd4bfcd--- /dev/null+++ b/examples/aurora_morning.py@@ -0,0 +1,141 @@+"""Example (aurora glassmorphism): 晨间计划 · Morning Plan — one weekday morning at 08:26, told by a stack of+frosted-glass widgets over a sunrise-coloured aurora: the plan card (3 of 5 done, the deep-work block running now),+a focus ring counting down that block, today's weather (a glossy sun behind a glass cloud), the focus settings+(do-not-disturb on, rain noise at 40 %), the last seven days of focus time, and a reminder pill for the 9:00+stand-up. Warm gradients belong to the morning plan, cool ones to focus. No image model.+python3 aurora_morning.py [out.jpg] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from aurora import Aurora, INK, WARM, COOL, MINT, WHITE++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'aurora_morning.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++a = Aurora(1920, 1080, seed=5)++# ---- the aurora: a sunrise wash, warm at the top, cool below, one pale ribbon of light across it+a.backdrop(base='#f6f2fb',+ blobs=[(260, 150, 560, 380, '#ffb28c', 1.0), # apricot+ (980, 40, 640, 300, '#ffe29a', 0.9), # butter (the sun is up)+ (1700, 220, 520, 440, '#bba2ff', 1.0), # lilac+ (880, 640, 520, 400, '#ff9cc9', 0.8), # pink+ (200, 930, 600, 400, '#86cbff', 1.0), # sky+ (1640, 960, 620, 380, '#8feccd', 0.9), # mint+ (1330, 600, 420, 320, '#a7bfff', 0.7)], # periwinkle+ ribbons=[([(-120, 560), (420, 520), (1000, 600), (1500, 600), (2040, 470)], 70, '#fff8f0', 1.4),+ ([(-100, 1080), (600, 1020), (1300, 1010), (2040, 1000)], 60, '#c6b2ff', 1.0),+ ([(900, -40), (1320, 60), (1700, 40), (2040, -20)], 60, '#ffd0e4', 0.9)],+ grain=0.019)+a.sparkles(46)+a.stage('aurora')++a.orb(596, 150, 104, ('#fff0dc', '#ffa2b8', '#8e6bff'))+a.orb(1700, 628, 100, ('#e3f7ff', '#6cc0ff', '#6a55ff'))+a.orb(1175, 1000, 58, ('#f4fff9', '#8fe8c8', '#4f9dff'))+a.stage('orbs')++# ---- weather (behind the plan card)+w = a.glass(130, 110, 590, 500, radius=38)+a.text('今天 · 晴', w.x0 + 40, w.y0 + 62, 24, INK, 'medium', alpha=0.62)+a.text('21°', w.x0 + 34, w.y0 + 176, 104, INK, 'light', spacing=-3)+a.sun(w.x0 + 286, w.y0 + 100, 46)+a.cloud(w.x0 + 318, w.y0 + 146, 128)+a.text('微风 · 最高 26° 最低 15°', w.x0 + 40, w.y0 + 226, 21, INK, 'regular', alpha=0.6)+pts = a.spark(w.x0 + 58, w.y0 + 272, w.x0 + 330, w.y0 + 318, [21, 22, 24, 25, 26], WARM, 3, fill=0.16, dots=(0,))+for i, (x, y) in enumerate(pts):+ a.text('现在' if i == 0 else f'{8 + i}时', x, w.y0 + 364, 18, INK, 'semibold' if i == 0 else 'regular', 'ms',+ alpha=0.85 if i == 0 else 0.5)+a.stage('weather')++# ---- focus settings (behind the plan card)+c = a.glass(130, 560, 590, 970, radius=38)+a.text('专注设置', c.x0 + 40, c.y0 + 64, 28, INK, 'semibold')+a.text('FOCUS', c.x0 + 40, c.y0 + 96, 15, INK, 'semibold', alpha=0.4, spacing=3)+a.text('勿扰模式', c.x0 + 40, c.y0 + 160, 24, INK, 'medium')+a.text('只有闹钟会响', c.x0 + 40, c.y0 + 190, 18, INK, alpha=0.5)+a.toggle(c.x0 + 270, c.y0 + 142, on=True)+a.divider(c.x0 + 40, c.x0 + 350, c.y0 + 226)+a.text('自动回复', c.x0 + 40, c.y0 + 272, 24, INK, 'medium')+a.toggle(c.x0 + 270, c.y0 + 246, on=False)+a.text('白噪音 · 雨声', c.x0 + 40, c.y0 + 334, 22, INK, 'medium', alpha=0.85)+a.text('40%', c.x0 + 350, c.y0 + 334, 20, INK, 'medium', 'rs', alpha=0.55)+a.slider(c.x0 + 44, c.x0 + 346, c.y0 + 368, 0.4)+a.stage('settings')++# ---- the plan: the card this morning is about+p = a.glass(520, 200, 1190, 990, radius=44, blur=30, elevation=34, shadow=0.3)+X0, X1 = p.x0 + 56, p.x1 - 56+a.stage('plan_glass')+a.text('MORNING PLAN', X0, p.y0 + 66, 16, INK, 'semibold', alpha=0.45, spacing=3.5)+a.text('周三', X1, p.y0 + 66, 20, INK, 'medium', 'rs', alpha=0.5)+a.text('晨间计划', X0, p.y0 + 134, 56, INK, 'semibold')+a.text('7:00 – 9:30 · 已完成 3 / 5', X0, p.y0 + 176, 22, INK, alpha=0.6)+a.rrect(X0, p.y0 + 204, X1, p.y0 + 216, 6, WHITE, 0.5)+a.rrect(X0, p.y0 + 204, X0 + (X1 - X0) * 0.6, p.y0 + 216, 6, grad=WARM)+a.text('60%', X1, p.y0 + 176, 22, INK, 'semibold', 'rs', alpha=0.75)++rows = [('07:00', '起床,喝一杯温水', '', 'done'),+ ('07:15', '拉伸', '10 分钟', 'done'),+ ('07:30', '早餐 · 燕麦和水果', '', 'done'),+ ('08:00', '深度工作 · 写方案', '', 'now'),+ ('09:00', '团队站会', '15 分钟', 'todo')]+y = p.y0 + 286+cx = X0 + 20+for i, (t, title, note, st) in enumerate(rows):+ if i < len(rows) - 1: # the thread between the checks+ a.line([(cx, y + 26), (cx, y + 84 - 26)], 3, WHITE, 0.8 if st == 'done' else 0.5)+ if st == 'now':+ a.pill(X0 - 16, y - 38, X1 + 16, y + 38, blur=6, tint=0.5, shadow=0.14)+ a.check(cx, y, 20, 'now', COOL, frac=0.59)+ a.text(t, X0 + 58, y, 21, INK, 'semibold', 'lm', alpha=0.8)+ a.text(title, X0 + 146, y, 27, INK, 'semibold', 'lm')+ a.rrect(X1 - 128, y - 20, X1, y + 20, 20, grad=COOL, angle=0, shadow=0.15)+ a.text('进行中', X1 - 64, y, 19, WHITE, 'semibold', 'mm')+ else:+ a.check(cx, y, 20, st, WARM)+ al = 1.0 if st == 'done' else 0.9+ a.text(t, X0 + 58, y, 21, INK, 'medium', 'lm', alpha=0.5)+ a.text(title, X0 + 146, y, 27, INK, 'medium', 'lm', alpha=0.62 if st == 'done' else 0.92)+ if note: a.text(note, X1, y, 20, INK, 'regular', 'rm', alpha=0.45)+ y += 84+a.pill(X0, p.y1 - 96, X0 + 170, p.y1 - 50, tint=0.5)+a.text('+ 添加事项', X0 + 85, p.y1 - 73, 19, INK, 'medium', 'mm', alpha=0.8)+a.pill(X0 + 186, p.y1 - 96, X0 + 356, p.y1 - 50, tint=0.5)+a.text('明早照旧', X0 + 271, p.y1 - 73, 19, INK, 'medium', 'mm', alpha=0.8)+a.stage('plan')++# ---- focus ring: the deep-work block, 18:24 left of 45 minutes+f = a.glass(1150, 96, 1570, 576, radius=40, elevation=30, shadow=0.3)+a.text('专注中', f.x0 + 40, f.y0 + 62, 26, INK, 'semibold')+a.text('45 分钟', f.x1 - 40, f.y0 + 62, 20, INK, 'medium', 'rs', alpha=0.5)+a.ring(f.cx, f.y0 + 238, 118, 20, 26.6 / 45, COOL)+a.text('18:24', f.cx, f.y0 + 250, 58, INK, 'semibold', 'ms', spacing=-1)+a.text('深度工作 · 写方案', f.cx, f.y0 + 290, 19, INK, 'regular', 'ms', alpha=0.55)+a.pill(f.x0 + 40, f.y1 - 92, f.cx - 10, f.y1 - 40, tint=0.5)+a.text('暂停', (f.x0 + 40 + f.cx - 10) / 2, f.y1 - 66, 20, INK, 'medium', 'mm', alpha=0.8)+a.rrect(f.cx + 10, f.y1 - 92, f.x1 - 40, f.y1 - 40, 26, grad=COOL, angle=0, shadow=0.18)+a.text('休息 5 分钟', (f.cx + 10 + f.x1 - 40) / 2, f.y1 - 66, 20, WHITE, 'semibold', 'mm')+a.stage('focus')++# ---- the last seven days of focus time+k = a.glass(1230, 636, 1810, 976, radius=38, blur=20)+a.text('近 7 天专注', k.x0 + 40, k.y0 + 60, 24, INK, 'semibold')+a.text('15.2', k.x0 + 40, k.y0 + 132, 60, INK, 'semibold', spacing=-1)+wv = a.text_width('15.2', 60, 'semibold', -1)+a.text('小时', k.x0 + 48 + wv, k.y0 + 132, 22, INK, 'medium', alpha=0.55)+a.rrect(k.x0 + 40, k.y0 + 156, k.x0 + 150, k.y0 + 190, 17, grad=MINT, angle=0)+a.text('↑ 18%', k.x0 + 95, k.y0 + 173, 18, WHITE, 'semibold', 'mm')+a.bars(k.x0 + 244, k.y0 + 66, k.x1 - 30, k.y1 - 74, [2.8, 3.1, 1.2, 0.6, 3.6, 2.5, 1.4], 4.0,+ ['24', '25', '26', '27', '28', '29', '今天'], highlight=6, label_size=18)+a.text('较上周', k.x0 + 162, k.y0 + 173, 18, INK, 'regular', 'lm', alpha=0.5)+a.stage('week')++# ---- the reminder pill at the top+n = a.pill(660, 56, 1100, 146, blur=14, tint=0.4, shadow=0.22, elevation=18)+a.app_icon(n.x0 + 22, n.y0 + 17, 56, WARM, '9', 30)+a.text('9:00 团队站会', n.x0 + 94, n.y0 + 40, 22, INK, 'semibold', 'lm')+a.text('还有 34 分钟 · 会议室 B', n.x0 + 94, n.y0 + 66, 17, INK, 'regular', 'lm', alpha=0.55)+a.text('现在', n.x1 - 30, n.y0 + 40, 16, INK, 'regular', 'rm', alpha=0.45)++a.save(out, stages)diff --git a/examples/bauhaus_form_colour.jpg b/examples/bauhaus_form_colour.jpgnew file mode 100644index 0000000..3366fb8Binary files /dev/null and b/examples/bauhaus_form_colour.jpg differdiff --git a/examples/bauhaus_form_colour.py b/examples/bauhaus_form_colour.pynew file mode 100644index 0000000..19e7610--- /dev/null+++ b/examples/bauhaus_form_colour.py@@ -0,0 +1,90 @@+"""Example (Bauhaus geometric poster): 形与色 · Form & Colour — a screen-printed poster for a (fictional) foundation-+course lecture. It diagrams one small idea: the sharper a shape's corners, the brighter its colour. Three shapes+stand on a heavy black ground line, each in its colour: the triangle (three acute 60° corners) in yellow, the square+(four right angles) in red, the circle (no corners at all) in blue, with angle marks drawn over them and big+corner counts 3 / 4 / 0 underneath. Title 形与色, the thesis knocked out of a black bar, the lecture details, a+construction grid, register targets, crop marks, a colour bar and a pencilled edition number. Printed screen by+screen, light to dark: tint grid -> yellow -> red -> blue -> black. No image model.+python3 bauhaus_form_colour.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from bauhaus import Bauhaus, YELLOW, RED, BLUE, BLACK++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'bauhaus_form_colour.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++b = Bauhaus(1920, 1080, seed=19, misreg=2.6)+W, H = b.W, b.H++# ---- the sheet: cream stock, a 15 x 8 grid of 120 px modules inside a 60 px printer's margin+b.paper(margin=60, module=120)+GROUND = 840 # top of the black ground line (half a module under row 6)+b.marks(targets=[(960, 30), (960, 1050), (30, 540), (1890, 540)], bar=(1712, 1040))+b.stage('paper')++# ---- screen 0: pale tint, the construction grid+b.grid()+b.stage('grid')++# ---- screen 1: yellow -- the triangle, three acute corners+TX0, TX1 = 60, 600+b.pull(b.triangle(TX0, TX1, GROUND), YELLOW)+b.stage('yellow')++# ---- screen 2: red -- the square, four right angles+SX0, SX1 = 720, 1200+b.pull(b.rect(SX0, GROUND - (SX1 - SX0), SX1, GROUND), RED)+b.stage('red')++# ---- screen 3: blue -- the circle, no corners+CR = 240+CX, CY = 1560, GROUND - CR+# the circle's centre and radius are cut out of the blue stencil, so they print as bare paper+radius = np.maximum.reduce([b.circle(CX, CY, 12), b.bar(CX, CY, CX + CR - 18, CY, 7),+ b.text_mask('r', CX + CR / 2 - 6, CY - 20, 46, anchor='ms')])+b.pull(b.circle(CX, CY, CR), BLUE, knock=radius)+b.stage('blue')++# ---- screen 4: black -- ground line, thesis bar (type knocked out), angle marks+b.pull(b.rect(60, GROUND, 1860, GROUND + 26), BLACK)+knock = np.maximum(b.text_mask('角越尖,色越亮。', 752, 258, 58, font='cjk'),+ b.text_mask('SHARPER CORNERS · BRIGHTER COLOUR', 1830, 250, 20, anchor='rs', spacing=3.2))+b.pull(b.rect(720, 190, 1860, 282), BLACK, knock=knock)+# triangle: the 60° corner+b.pull(b.arc(TX0, GROUND, 96, 0, 60, 6), BLACK)+b.text('60°', TX0 + 118, GROUND - 40, 34)+# square: the right angle+b.pull(np.maximum(b.bar(SX0, GROUND - 80, SX0 + 80, GROUND - 80, 6, cap='square'),+ b.bar(SX0 + 80, GROUND - 80, SX0 + 80, GROUND, 6, cap='square')), BLACK)+b.text('90°', SX0 + 104, GROUND - 40, 34)+b.stage('bars')++# ---- black: the title+b.text('形与色', 52, 262, 210, font='cjk')+b.text('FORM & COLOUR', 720, 150, 56, spacing=2)+b.stage('title')++# ---- black: lecture details and the three captions under the ground line+b.text('基础课 · 第 3 讲', 1860, 104, 32, font='cjk', anchor='rs')+b.text('10 月 16 日 周五 19:00 · 北楼 204', 1860, 146, 23, font='cjk', anchor='rs')+for x, n, l1, l2, l3 in [(TX0, '3', '三个锐角 → 黄', '最尖,所以最亮', 'TRIANGLE · 60° · YELLOW'),+ (SX0, '4', '四个直角 → 红', '最稳,所以最重', 'SQUARE · 90° · RED'),+ (1320, '0', '没有角 → 蓝', '最静,所以最深', 'CIRCLE · NO CORNERS · BLUE')]:+ b.text(n, x - 4, 1012, 150)+ nx = x + b.text_width(n, 150) + 26+ b.text(l1, nx, 934, 34, font='cjk')+ b.text(l2, nx, 974, 24, font='cjk')+ b.text(l3, nx, 1008, 15, spacing=2.4)+# margin slugs+b.text('形与色 · FORM & COLOUR — 基础课讲座海报', 86, 38, 14, font='cjk_book', spacing=1.2)+b.text('SHEET 03 / 12 · SCREEN PRINT · Y R B K', 1834, 38, 13, anchor='rs', spacing=2.2)+b.text('丝网四色 · 先浅后深 · 黄 → 红 → 蓝 → 黑', 200, 1057, 14, font='cjk_book', spacing=1.2)++# ---- after printing: the edition number in pencil+b.pencil('7/40', 86, 1060, 28, pressure=0.85)++b.save(out, stages)+print(out, f'{time.time() - t0:.1f}s')diff --git a/examples/cartoon_toaster.jpg b/examples/cartoon_toaster.jpgnew file mode 100644index 0000000..adb97e3Binary files /dev/null and b/examples/cartoon_toaster.jpg differdiff --git a/examples/cartoon_toaster.py b/examples/cartoon_toaster.pynew file mode 100644index 0000000..ee9a3b2--- /dev/null+++ b/examples/cartoon_toaster.py@@ -0,0 +1,277 @@+"""Example (hand-drawn cartoon, frame by frame): 早安吐司 / Good Morning, Toast — how a toaster makes breakfast,+told as one drawing from a hand-drawn cartoon: a mint toaster with a happy face; two slices of toast shooting out+of its glowing slots, arms up, one delighted and one surprised; a "叮!" starburst; a pat of butter dozing on a plate+waiting for them; a morning window with the sun coming up over the hills. Numbered notes on the left follow the+toast up through the machine: ① press the lever, ② the coils glow red for three minutes, ③ ding, up it pops.+Brush-pen ink that boils, flat colour a little off the lines, one or two cel-shadow tones, crayon sky and toast,+screentone cabinet, blue-pencil rough left under everything. No image model.+python3 cartoon_toaster.py [out.png] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from cartoon import Cartoon, WHITE, RED, YELLOW+from core import spline++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'cartoon_toaster.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++W, H = 1920, 1080+c = Cartoon(W, H, seed=12, boil=2.0)+E, R, P = Cartoon.ellipse_pts, Cartoon.rrect_pts, Cartoon.place++MINT, MINT_L, MINT_D, MINT_DD = '#86cdbf', '#b4e4d9', '#5ba99d', '#3f877f'+CHROME, CHROME_D = '#e3e5e0', '#a9b2af'+CRUST, CRUST_D = '#b8692e', '#8d4b21'+CRUMB, CRUMB_D, TOASTED = '#f6ca76', '#e3a553', '#d68735'+BUTTER, BUTTER_L, BUTTER_D = '#ffdf7e', '#fff0b4', '#ecbb4b'+GLASS, SKY, SUN = '#d6ecf3', '#8cc6de', '#ffc93f'+HILL, HILL_D = '#a2d08a', '#7cb56a'+FRAME, FRAME_D = '#f8f0e1', '#dccdb4'+WOOD, WOOD_D, WOOD_DD = '#efd3a0', '#d9a96b', '#b67f47'+CAB, CAB_D = '#8fb4d2', '#6c93b5'+PLATE, PLATE_D, PLATE_B = '#fbf6ec', '#d9d3cb', '#9ccbdc'+SLOT, COIL = '#3a2620', '#ff7a33'+DX = 30 # the toaster group sits a little right of centre++# ---------------------------------------------------------------- back wall: tiles+for y in (712, 762):+ c.line([(0, y), (700, y + 1)], 2.4, taper=(0, 30), jitter=1.2)+ c.line([(1180, y), (W, y - 1)], 2.4, taper=(30, 0), jitter=1.2)+rt = np.random.default_rng(4)+for row, (ya, yb) in enumerate([(712, 762), (762, 812)]):+ for x in np.arange(40 + 60 * (row % 2), W, 120):+ if rt.random() < 0.3 or 560 < x < 1260: continue+ c.line([(x, ya + 3), (x + 1, yb - 3)], 2.2, taper=(4, 6), jitter=0.5)++# ---------------------------------------------------------------- the window: arch, sky, sun over the hills, clouds+WX, WY, WR = 1100, 330, 290 # arch centre and radius+def arch(inset):+ r = WR - inset+ top = [(WX + r * np.cos(t), WY + r * np.sin(t)) for t in np.linspace(np.pi, 2 * np.pi, 60)]+ return np.array(top + [(WX + r, 612 - inset)] + [(WX - r, 612 - inset)], np.float32)+outer, glass = arch(0), arch(26)+c.fill(outer, FRAME)+Fg = c.fill(glass, GLASS, slop=0, knock=True)+gm = c.mask(glass)+c.crayon(glass, SKY, pressure=np.clip((600 - c.YY) / 520, 0.12, 0.8) * 0.95, angle=20, clip=gm)+sun = E(1250, 574, 92, 92)+c.fill(c.mask(sun) * gm, SUN, slop=2)+c.crayon(E(1250, 574, 150, 150), '#ffe79a', pressure=0.42, angle=-30, clip=gm * (1 - c.mask(sun)))+c.line(E(1250, 574, 92, 92, a0=186, a1=354), 6, taper=(0, 0))+for a in np.linspace(38, 142, 6):+ t = np.deg2rad(a)+ c.line([(1250 + np.cos(t) * 112, 574 - np.sin(t) * 112), (1250 + np.cos(t) * 138, 574 - np.sin(t) * 138)], 5, (4, 6), smooth=False)+hx = np.linspace(WX - WR + 20, WX + WR - 20, 30)+hills = np.array([(x, 548 - 22 * np.sin((x - 820) / 95) - 10 * np.cos((x - 820) / 41)) for x in hx] + [(WX + WR, 640), (WX - WR, 640)], np.float32)+Fh = c.fill(c.mask(hills) * gm, HILL, slop=2)+c.shade(c.mask(hills) * gm, HILL_D, (0, -12), clip=Fh)+c.line(hills[:30], 5, taper=(0, 0))+for x0, x1, y0, y1 in [(WX - 13, WX + 13, WY - WR, 598), (WX - WR + 20, WX + WR - 20, 318, 342)]:+ bar = R(x0, y0, x1, y1, 3)+ c.shape(bar, FRAME, shade=(FRAME_D, 6, 6), width=4.5, slop=1.5)+c.outline(glass, 5)+c.outline(outer, 7.5)+sill = R(WX - WR - 34, 598, WX + WR + 34, 632, 8)+c.shape(sill, FRAME, shade=(FRAME_D, 0, 10), width=6)++# ---------------------------------------------------------------- a wall clock: seven o'clock+KX, KY = 1712, 468+c.shade(E(KX + 9, KY + 11, 82, 82), '#e0d3bb', None)+rim = E(KX, KY, 80, 80)+Fk = c.fill(rim, MINT)+c.shade(rim, MINT_D, (14, 14), clip=Fk)+dialk = E(KX, KY, 61, 61)+Fd = c.fill(dialk, PLATE, slop=2, knock=False)+c.shade(dialk, PLATE_D, (-8, -8), clip=Fd)+c.outline(rim, 7.5, 0.4)+c.outline(dialk, 4, 0.2)+for k in range(12):+ t = np.deg2rad(90 - k * 30)+ r0 = 44 if k % 3 == 0 else 49+ c.line([(KX + np.cos(t) * r0, KY - np.sin(t) * r0), (KX + np.cos(t) * 55, KY - np.sin(t) * 55)], 4.2 if k % 3 == 0 else 2.8, (2, 2), smooth=False)+for ang, L, w in [(90 - 7 * 30, 30, 7), (90, 44, 5)]:+ t = np.deg2rad(ang)+ c.line([(KX, KY), (KX + np.cos(t) * L, KY - np.sin(t) * L)], w, (2, 6), smooth=False)+c.dot(KX, KY, 5)+c.glint([(KX - 58, KY - 28), (KX - 44, KY - 52)], 6)++# ---------------------------------------------------------------- the counter and the cabinet below it+top = np.array([(-20, 812), (W + 20, 812), (W + 20, 948), (-20, 948)], np.float32)+Ft = c.fill(top, WOOD, slop=0)+c.line([(-10, 812), (W + 10, 812)], 5, taper=(0, 0))+rg = np.random.default_rng(7)+for y in (838, 866, 902, 930):+ xs = np.sort(rg.uniform(0, W, 6))+ for xa, xb in zip(xs[::2], xs[1::2]):+ c.line([(xa, y), ((xa + xb) / 2, y + rg.uniform(-3, 3)), (xb, y + rg.uniform(-2, 2))], 2.2, (20, 30), jitter=0.8)+edge = np.array([(-20, 948), (W + 20, 948), (W + 20, 984), (-20, 984)], np.float32)+c.shape(edge, WOOD_D, shade=(WOOD_DD, 0, 12), width=6, slop=1.5)+cab = np.array([(-20, 984), (W + 20, 984), (W + 20, H + 20), (-20, H + 20)], np.float32)+Fc = c.fill(cab, CAB, slop=0)+c.shade(np.array([(-20, 984), (W + 20, 984), (W + 20, 1010), (-20, 1010)], np.float32), CAB_D, None, clip=Fc)+c.tone(cab, '#46698c', cell=10, angle=45, amount=np.clip((1080 - c.YY) / 96, 0, 1) * 0.16 + 0.04)+for x in (330, 800, 1270, 1740):+ c.line([(x, 988), (x + 1, H + 10)], 4.5, taper=(0, 0))+ for sx in (-1, 1):+ k = E(x + sx * 34, 1032, 9, 9)+ c.shape(k, CHROME, shade=(CHROME_D, 3, 3), width=3.5, slop=1)++# contact shadows on the counter (hatched)+for cx, cy, rx, ry in [(900 + DX, 856, 300, 24), (1590, 912, 232, 26)]:+ sh = E(cx, cy, rx, ry)+ c.shade(sh, WOOD_D, None, clip=Ft)+ c.hatch(E(cx + 10, cy + 4, rx * 0.92, ry * 0.7), angle=-60, spacing=13, width=2.6)++# ---------------------------------------------------------------- the cord and its plug+cord = [(660 + DX, 820), (600, 846), (548, 880), (560, 912), (612, 904), (604, 874), (540, 868), (450, 896), (372, 906)]+c.line(cord, 7.5, taper=(2, 2), press=0.05)+plug = R(300, 889, 368, 925, 12)+c.shape(plug, CHROME, shade=(CHROME_D, 6, 6), width=5)+for y in (898, 916):+ c.line([(300, y), (270, y)], 5, (1, 1), smooth=False)++# ---------------------------------------------------------------- the toaster+for fx0 in (690 + DX, 1020 + DX):+ c.shape(R(fx0, 836, fx0 + 62, 866, 9), '#4d3c35', width=5, slop=1)+body = R(640 + DX, 512, 1130 + DX, 848, (105, 105, 36, 36))+Fb = c.fill(body, MINT)+fe = spline([(642 + DX, 600), (720 + DX, 584), (885 + DX, 577), (1050 + DX, 584), (1128 + DX, 600)], per=10)+topm = c.mask(body) * c.mask(np.vstack([fe, [(1150 + DX, 470), (620 + DX, 470)]]))+c.fill(topm, MINT_L, slop=2, knock=False)+c.shade(body, MINT_D, (40, 12), clip=Fb)+c.shade(body, MINT_DD, (13, 5), clip=Fb)+skirt = R(646 + DX, 804, 1124 + DX, 848, (4, 4, 34, 34))+Fs = c.fill(skirt, CHROME, slop=2, knock=False)+c.shade(skirt, CHROME_D, (20, 10), clip=Fs)+c.glint([(690 + DX, 816), (760 + DX, 815)], 6)+c.glint([(682 + DX, 596), (690 + DX, 560), (722 + DX, 530)], 11)+c.glint([(752 + DX, 528), (760 + DX, 526)], 9, taper=(3, 3))+c.glint([(760 + DX, 622), (755 + DX, 700)], 9)+c.outline(body, 9.5, 0.45)+c.line(fe, 5, taper=(6, 6))+c.line([(650 + DX, 804), (1120 + DX, 804)], 4.5, taper=(6, 6))+for sx0 in (700 + DX, 902 + DX):+ slot = R(sx0, 535, sx0 + 168, 561, 12)+ c.fill(slot, SLOT, slop=1, knock=False)+ c.glint([(sx0 + 14, 553), (sx0 + 154, 553)], 5, COIL, taper=(10, 10))+ c.glint([(sx0 + 30, 546), (sx0 + 138, 546)], 2.5, '#ffb070', taper=(10, 10))+ c.outline(slot, 4.5, 0.2)+# lever (up: the toast has just popped) and the timer dial+track = R(664 + DX, 614, 682 + DX, 744, 8)+c.fill(track, SLOT, slop=1, knock=False); c.outline(track, 3.5, 0)+knob = R(612 + DX, 604, 712 + DX, 640, 15)+c.shape(knob, RED, shade=('#b3342a', 8, 7), width=6.5, slop=2)+c.glint([(626 + DX, 614), (660 + DX, 612)], 5)+dial = E(700 + DX, 772, 26, 26)+c.shape(dial, CHROME, shade=(CHROME_D, 6, 6), width=5, slop=1.5)+for a in np.linspace(-20, 200, 6):+ t = np.deg2rad(a)+ c.line([(700 + DX + np.cos(t) * 33, 772 - np.sin(t) * 33), (700 + DX + np.cos(t) * 41, 772 - np.sin(t) * 41)], 3.2, (2, 2), smooth=False)+c.line([(700 + DX, 772), (700 + DX + 15, 772 - 15)], 4.5, (3, 3), smooth=False)+c.face(900 + DX, 690, 150, 'happy')++# ---------------------------------------------------------------- the toast, popping+SL = [(-0.40, 0.52), (0.0, 0.545), (0.40, 0.52), (0.43, 0.10), (0.41, -0.16), (0.50, -0.30), (0.49, -0.47), (0.33, -0.60),+ (0.0, -0.64), (-0.33, -0.60), (-0.49, -0.47), (-0.50, -0.30), (-0.41, -0.16), (-0.43, 0.10)]+CR = [(x * 0.8, y * 0.8 + 0.01) for x, y in SL]+++def toast(cx, cy, s, rot, mood, arms, seed):+ for sh, hd, bend, th in arms: # arms first: the slice sits in front of them+ c.arm(P([sh], cx, cy, s, rot)[0], hd, bend, width=6, hand=24, thumb=th)+ crust = P(SL, cx, cy, s, rot)+ Fc_ = c.fill(crust, CRUST)+ c.shade(crust, CRUST_D, (14, 8), clip=Fc_)+ crumb = P(CR, cx, cy, s, rot)+ Fi = c.fill(crumb, CRUMB, slop=2.5)+ inset = P([(x * 0.66, y * 0.64 + 0.03) for x, y in SL], cx, cy, s, rot)+ c.crayon(c.mask(crumb) * (1 - c.mask(inset)), TOASTED, pressure=0.5, angle=rot + 30, soft=5, clip=Fi) # toasted edges+ c.shade(crumb, CRUMB_D, (12, 10), clip=Fi)+ c.outline(crust, 8, 0.4)+ c.outline(crumb, 3.4, 0.2, gaps=2)+ rr = np.random.default_rng(seed)+ for _ in range(7):+ q = P([(rr.uniform(-0.27, 0.27), rr.uniform(0.22, 0.4) if rr.random() < 0.6 else rr.uniform(-0.45, -0.3))], cx, cy, s, rot)[0]+ c.dot(q[0], q[1], rr.uniform(1.6, 2.6))+ f = P([(0, 0.0)], cx, cy, s, rot)[0]+ c.face(f[0], f[1], 108, mood, rot=rot)+++toast(790 + DX, 300, 205, 12, 'happy', [((-0.45, 0.12), (636, 232), -0.38, -1)], 3) # each slice throws its outer arm up+toast(1010 + DX, 276, 205, -10, 'wow', [((0.45, 0.12), (1214, 210), 0.38, 1)], 8)+slices = c.mask(P(SL, 790 + DX, 300, 225, 12)) + c.mask(P(SL, 1010 + DX, 276, 225, -10))++# ---------------------------------------------------------------- plate, a dozing pat of butter, a knife+plate = E(1590, 885, 216, 50)+Fp = c.fill(plate, PLATE_B)+c.fill(E(1590, 883, 198, 44), PLATE, slop=1.5, knock=False)+c.shade(plate, PLATE_D, (0, 9), clip=Fp)+well = E(1590, 880, 150, 31)+c.shade(well, PLATE_D, (0, -7))+c.outline(plate, 7, 0.4)+c.outline(well, 3.4, 0.1, gaps=1)+puddle = E(1522, 895, 36, 7.5)+c.shape(puddle, BUTTER, shade=(BUTTER_D, 5, 3), width=3.6, slop=1)+bt = Cartoon.densify([(1500, 838), (1524, 806), (1664, 806), (1664, 852), (1642, 878), (1500, 878)], 6)+Fbt = c.fill(bt, BUTTER)+c.fill(np.array([(1500, 838), (1524, 806), (1664, 806), (1642, 838)], np.float32), BUTTER_L, slop=1.5, knock=False)+c.fill(np.array([(1642, 838), (1664, 806), (1664, 852), (1642, 878)], np.float32), BUTTER_D, slop=1.5, knock=False)+c.outline(bt, 7, 0.4, smooth=False)+c.line([(1502, 838), (1642, 838), (1662, 808)], 3.6, (6, 6), smooth=False)+c.line([(1642, 840), (1642, 874)], 3.6, (6, 6), smooth=False)+drip = [(1497, 842), (1512, 840), (1518, 856), (1520, 880), (1527, 893), (1520, 899), (1511, 893), (1509, 874), (1500, 862), (1494, 852)]+Fdr = c.fill(drip, BUTTER, slop=1) # melting over the front edge into the puddle+c.shade(drip, BUTTER_D, (5, 3), clip=Fdr)+c.outline(drip, 3.8, 0.3)+c.glint([(1502, 848), (1506, 858)], 3.5, taper=(2, 2))+c.face(1578, 851, 76, 'sleepy', width=5.0)+knife_rot = 17.5+blade = P(R(-72, -9, 72, 9, (9, 2, 2, 9)), 1714, 886, 1, knife_rot)+c.shape(blade, CHROME, shade=(CHROME_D, 0, 6), width=5, slop=1)+c.glint(P([(-55, -2), (40, -2)], 1714, 886, 1, knife_rot), 3.5)+handle = P(R(-50, -12, 50, 12, 12), 1835, 848, 1, knife_rot)+c.shape(handle, RED, shade=('#b3342a', 4, 6), width=5.5, slop=1.5)+for u in (-26, 22):+ q = P([(u, 0)], 1835, 848, 1, knife_rot)[0]+ c.dot(q[0], q[1], 3.2)++# ---------------------------------------------------------------- effects: whoosh, puffs, crumbs, the ding+c.speed_lines((716 + DX, 506), (852 + DX, 500), angle=98, n=4, length=(46, 84), width=4.2)+c.speed_lines((918 + DX, 500), (1058 + DX, 506), angle=83, n=4, length=(46, 84), width=4.2)+c.puff(724 + DX, 522, 34, bumps=5, squash=0.62, rot=10)+c.puff(1066 + DX, 518, 36, bumps=5, squash=0.62, rot=-20)+c.crumbs(900 + DX, 270, n=10, spread=(300, 190), size=(5, 9), avoid=slices)+c.pop_lines(1040 + DX, 116, 34, 62, [64, 90, 116], width=5)+bx, by = 1430, 236+c.burst(bx, by, 170, 122, RED, spikes=13, depth=0.3, rot=8, shade='#b3342a')+for x, y, r in [(760, 84, 18), (1110, 60, 12), (640, 470, 18), (1790, 640, 18), (1820, 604, 10), (1590, 470, 14)]:+ c.sparkle(x, y, r)++# ---------------------------------------------------------------- lettering and the numbered notes+c.sketch([(86, 204), (600, 202)], width=1.6)+c.sketch([(86, 100), (600, 99)], width=1.6)+c.letter('早安吐司', 92, 200, 116, YELLOW, depth=(6, 8), depth_colour=MINT_DD, spacing=4)+c.note('GOOD MORNING, TOAST!', 98, 262, 35, spacing=1)+c.note('z', 1684, 800, 26, rot=8)+c.note('Z', 1712, 770, 36, rot=12)+c.letter('叮!', bx - 6, by + 36, 104, YELLOW, depth=(5, 6), depth_colour='#8d2a22', anchor='m', rot=6)+steps = [(3, 404, '弹起来!', 'POP', [(420, 392), (560, 386), (726, 372)]),+ (2, 528, '电热丝烧红 3 分钟', 'HEAT · 3 MIN', [(556, 520), (640, 530), (694 + DX, 548)]),+ (1, 652, '按下拉杆', 'PRESS', [(392, 640), (500, 636), (598 + DX, 624)])]+for n, y, zh, en, arr in steps:+ c.badge(128, y - 12, 25, str(n), YELLOW)+ c.note(zh, 168, y, 36)+ c.note(en, 170, y + 36, 24, '#6b5a4c', spacing=2)+ c.arrow(arr, 4.2, head=18)+c.pencil_note('TOAST · A-07', 1846, 50, 26, anchor='r')++# ---------------------------------------------------------------- the drawing, replayed the way it was made+c.stage('paper', show=[])+c.stage('rough', show=['rough'], rough=0.9)+c.stage('ink', show=['rough', 'ink'], rough=0.55)+c.stage('flat', show=['rough', 'ink', 'flat'])+c.stage('shade', show=['rough', 'ink', 'flat', 'shade', 'texture'])+c.stage('fx', show=['rough', 'ink', 'flat', 'shade', 'texture', 'fx'])+c.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/drawing_aurora_morning.gif b/examples/drawing_aurora_morning.gifnew file mode 100644index 0000000..0062a75Binary files /dev/null and b/examples/drawing_aurora_morning.gif differdiff --git a/examples/drawing_bauhaus_form_colour.gif b/examples/drawing_bauhaus_form_colour.gifnew file mode 100644index 0000000..0208f3eBinary files /dev/null and b/examples/drawing_bauhaus_form_colour.gif differdiff --git a/examples/drawing_cartoon_toaster.gif b/examples/drawing_cartoon_toaster.gifnew file mode 100644index 0000000..2add723Binary files /dev/null and b/examples/drawing_cartoon_toaster.gif differdiff --git a/examples/drawing_flatvector_bookshop.gif b/examples/drawing_flatvector_bookshop.gifnew file mode 100644index 0000000..02b360fBinary files /dev/null and b/examples/drawing_flatvector_bookshop.gif differdiff --git a/examples/drawing_isometric_weather_island.gif b/examples/drawing_isometric_weather_island.gifnew file mode 100644index 0000000..79ee8d3Binary files /dev/null and b/examples/drawing_isometric_weather_island.gif differdiff --git a/examples/drawing_lineart_paper_plane.gif b/examples/drawing_lineart_paper_plane.gifnew file mode 100644index 0000000..85a953cBinary files /dev/null and b/examples/drawing_lineart_paper_plane.gif differdiff --git a/examples/drawing_morph_water_cycle.gif b/examples/drawing_morph_water_cycle.gifnew file mode 100644index 0000000..0128daaBinary files /dev/null and b/examples/drawing_morph_water_cycle.gif differdiff --git a/examples/drawing_newscollage_curiosity.gif b/examples/drawing_newscollage_curiosity.gifnew file mode 100644index 0000000..0dce41fBinary files /dev/null and b/examples/drawing_newscollage_curiosity.gif differdiff --git a/examples/drawing_soft3d_rise.gif b/examples/drawing_soft3d_rise.gifnew file mode 100644index 0000000..bc747adBinary files /dev/null and b/examples/drawing_soft3d_rise.gif differdiff --git a/examples/drawing_synthwave_coastline.gif b/examples/drawing_synthwave_coastline.gifnew file mode 100644index 0000000..b880437Binary files /dev/null and b/examples/drawing_synthwave_coastline.gif differdiff --git a/examples/flatvector_bookshop.jpg b/examples/flatvector_bookshop.jpgnew file mode 100644index 0000000..4649f5cBinary files /dev/null and b/examples/flatvector_bookshop.jpg differdiff --git a/examples/flatvector_bookshop.py b/examples/flatvector_bookshop.pynew file mode 100644index 0000000..b53feef--- /dev/null+++ b/examples/flatvector_bookshop.py@@ -0,0 +1,240 @@+"""Example (flat vector): 周末书店 / The Weekend Bookshop — a Saturday at dusk in a small bookshop, drawn as a+modern flat illustration: no outlines, seven flat colours, volume from overlapping colour blocks, a whisper of+grain. The one small story: the only coral book has just come down from the top poetry shelf. A bookseller on+the rolling ladder hangs on to the rail with one hand and lowers it with the other; a silver-haired customer in a+mustard coat reaches up for it; a dashed coral trail marks its drop from the gap it left (the neighbour has+already tipped over into the space). Beside the arched window -- an OPEN sign on strings, the sun setting behind+the street -- a reader sits in a lounge chair under a pendant lamp's beam, a mug steaming on the side table; the+shop cat watches the street from the sill; a crate of second-hand books waits on the floor.+No image model.+python3 flatvector_bookshop.py [out.jpg] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from flatvector import FlatVector, Mask, INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'flatvector_bookshop.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++W, H = 1920, 1080+fv = FlatVector(W, H, seed=5, light=(0.8, -0.6))+T = fv.tone+FLOOR_Y = 905+WOOD = T(MUSTARD, -0.12)++# ---------------------------------------------------------------- wall and floor+fv.backdrop(BLUE)+floor = fv.rect(0, FLOOR_Y, W, H)+fv.fill(floor, T(MUSTARD, -0.3))+for y in (938, 984, 1046): # plank joints, wider apart toward us+ fv.fill(fv.rect(0, y, W, y + 5), T(MUSTARD, -0.38))+fv.fill(fv.rect(0, 738, W, FLOOR_Y), T(BLUE, -0.08)) # wainscot below the sill line+fv.fill(fv.rect(0, 732, W, 744), T(BLUE, 0.12)) # dado rail+fv.fill(fv.rect(0, FLOOR_Y - 22, W, FLOOR_Y), T(BLUE, -0.3)) # skirting board+fv.stage('wall')++# ---------------------------------------------------------------- the arched window, sunset outside+WX0, WX1, WY0, WY1 = 1150, 1560, 170, 716+wr = (WX1 - WX0) / 2+opening = fv.rrect(WX0, WY0, WX1, WY1, (wr, wr, 0, 0))+glass = fv.rrect(WX0 + 24, WY0 + 24, WX1 - 24, WY1, (wr - 24, wr - 24, 0, 0))+fv.fill(opening, CREAM)+sky = [(WY0, T(PEACH, 0.45)), (330, T(PEACH, 0.2)), (440, PEACH), (540, T(CORAL, 0.3))]+for y, c in sky:+ fv.fill(glass & fv.rect(WX0, y, WX1, WY1), c)+fv.fill(glass & fv.circle(1405, 560, 74), MUSTARD) # the low sun+fv.fill(glass & fv.circle(1405, 560, 74) & fv.rect(0, 560, W, H), T(MUSTARD, 0.25))+far = [(1150, 560), (1215, 505), (1262, 585), (1330, 540), (1470, 598), (1512, 520)]+for x, y in far: # far blocks, brick-red+ fv.fill(glass & fv.rect(x, y, x + 64, WY1), T(CORAL, -0.28))+near = [(1150, 610, 110), (1262, 640, 70), (1335, 596, 96), (1432, 650, 70), (1500, 612, 80)]+for x, y, w in near: # near blocks with lit windows+ b = glass & fv.rect(x, y, x + w, WY1)+ fv.fill(b, T(BLUE, -0.42))+ for wy in range(y + 16, WY1 - 10, 30):+ for wx in range(x + 12, x + w - 12, 24):+ if (wx * 7 + wy * 3) % 5 < 2:+ fv.fill(glass & fv.rect(wx, wy, wx + 10, wy + 14), MUSTARD)+fv.fill(glass & fv.rect(WX0, 686, WX1, WY1), T(BLUE, -0.55)) # the street wall opposite+mull = fv.rect(1350, WY0, 1360, WY1) | fv.rect(WX0, 440, WX1, 450)+fv.fill(mull & opening, CREAM)+fv.fill(fv.rect(WX0 + 24, WY0, WX0 + 36, WY1) & glass, T(CREAM, -0.14)) # reveal: inner side of the frame+# a little OPEN sign hanging inside the glass on two strings+SX, SY = 1264, 322+for dx in (-44, 44):+ fv.fill(fv.capsule((SX, 250), (SX + dx, SY - 20), 1.6), T(INK, 0.2))+fv.fill(fv.circle(SX, 250, 5), T(INK, 0.2))+sign = fv.rrect(SX - 64, SY - 22, SX + 64, SY + 44, 10)+fv.fill(sign, TEAL); fv.shade(sign, 0.0, 6, colour=T(TEAL, -0.2))+fv.text('OPEN', SX, SY + 8, 25, CREAM, anchor='ms', spacing=4)+fv.text('10:00 — 22:00', SX, SY + 31, 14, T(TEAL, 0.6), anchor='ms', spacing=1, font_style='geo_medium')+sill = fv.rrect(WX0 - 28, WY1 - 6, WX1 + 28, WY1 + 22, 6)+fv.cast(sill, 0, 14, 0.28)+fv.fill(sill, CREAM)+fv.fill(fv.rect(WX0 - 28, WY1 + 14, WX1 + 28, WY1 + 22) & sill, T(CREAM, -0.14))+# the low sun lays a patch of light across the floor, falling toward us and to the left+patch = fv.poly([(1190, FLOOR_Y), (1520, FLOOR_Y), (1300, H), (820, H)])+fv.fill(patch, T(PEACH, 0.2), 0.2, grain=0.5)+fv.stage('window')++# ---------------------------------------------------------------- the bookcase+BX0, BX1, BY0 = 70, 1010, 66+case = fv.rect(BX0, BY0, BX1, FLOOR_Y)+fv.cast(case, 22, 0, 0.3, clip=fv.rect(0, 0, W, FLOOR_Y)) # hard shadow on the wall+fv.fill(case, CREAM)+fv.shade(case, 0.0, 14, colour=T(CREAM, -0.12))+fv.fill(fv.rect(BX0 - 16, BY0 - 14, BX1 + 16, BY0 + 12), T(CREAM, -0.06)) # top cap+fv.text('周末书店', 120, 142, 60, INK, cjk='cjk')+x_dot = 120 + fv.text_width('周末书店', 60, cjk='cjk') + 22+fv.fill(fv.circle(x_dot, 124, 6), CORAL)+fv.text('WEEKEND BOOKS', x_dot + 22, 136, 30, T(BLUE, -0.1), spacing=6)+rows = [(172, 316), (330, 474), (488, 632), (646, 790)] # (top, board) per row+bays = [(BX0 + 22, 372), (390, 690), (708, BX1 - 22)]+back = Mask(np.zeros((0, 0)))+for (y0, y1) in rows:+ for (a, b) in bays:+ back = back | fv.rect(a, y0, b, y1)+back = back | fv.rect(BX0 + 22, 804, BX1 - 22, 856)+fv.fill(back, T(BLUE, -0.3))+fv.darken(back & fv.rect(0, 0, W, 186) | back & fv.rect(0, 330, W, 344) | back & fv.rect(0, 488, W, 502)+ | back & fv.rect(0, 646, W, 660), 0.18) # under each board, a flat shadow+fv.fill(fv.rect(BX0 + 22, 856, BX1 - 22, 872), CREAM)+# the ladder rail runs along under the top cap+fv.fill(fv.capsule((BX0 + 10, 162), (BX1 - 10, 162), 7), INK)+for x in (BX0 + 30, 540, BX1 - 30):+ fv.fill(fv.rrect(x - 7, 150, x + 7, 176, 3), T(INK, 0.2))+fv.stage('bookcase')++# ---------------------------------------------------------------- books+cols = [INK, CREAM, TEAL, MUSTARD, PEACH, T(BLUE, 0.45), T(TEAL, -0.3)]+for ri, (y0, y1) in enumerate(rows):+ for bi, (a, b) in enumerate(bays):+ gap = (842, 40) if (ri, bi) == (0, 2) else (None, 0)+ stack = {(1, 0): 250, (2, 1): 560, (3, 2): 900, (0, 0): None}.get((ri, bi))+ fv.books(a + 4, b - 2, y1, (y1 - y0) * 0.9, cols, seed=100 + ri * 10 + bi, gap_at=gap[0], gap_w=gap[1],+ stack_at=stack, back=back)+fv.books(BX0 + 26, BX1 - 24, 856, 48, [T(INK, 0.1), T(TEAL, -0.2), T(BLUE, 0.3)], seed=77, w_range=(0.9, 1.6), title=False)+# category tabs hanging from the boards+for (x, y, s) in [(918, 316, '诗歌 POETRY'), (240, 474, '小说 FICTION'), (470, 632, '旅行 TRAVEL')]:+ w = fv.text_width(s, 17, spacing=1.5) + 30+ tab = fv.rrect(x - w / 2, y + 2, x + w / 2, y + 34, (0, 0, 8, 8))+ fv.fill(tab, MUSTARD)+ fv.text(s, x, y + 25, 17, INK, anchor='ms', spacing=1.5)+fv.stage('books')++# ---------------------------------------------------------------- furniture: ladder, plant, table, chair, lamp+# rolling ladder: hooks on the rail, stiles splay toward the wheels on the floor+LT, LB = 162, 932+stiles = [((598, LT), (578, LB)), ((724, LT), (744, LB))]+for (p0, p1) in stiles:+ fv.cast(fv.capsule(p0, p1, 9), -10, 0, 0.25, clip=back | case)+for yr in range(236, 900, 74):+ t = (yr - LT) / (LB - LT)+ xa, xb = 598 + (578 - 598) * t, 724 + (744 - 724) * t+ fv.fill(fv.rrect(xa, yr - 7, xb, yr + 7, 4), T(WOOD, -0.12))+for (p0, p1) in stiles:+ s = fv.capsule(p0, p1, 11)+ fv.fill(s, WOOD); fv.shade(s, 0.0, 7, colour=T(WOOD, -0.2))+fv.fill(fv.circle(598, LT, 13) | fv.circle(724, LT, 13), INK) # hooks over the rail+fv.darken(fv.ellipse(661, LB + 14, 120, 10), 0.3)+for x in (578, 744):+ fv.fill(fv.circle(x, LB, 15), INK); fv.fill(fv.circle(x, LB, 5), T(INK, 0.4))++fv.stage('ladder')++# tall plant between the bookcase and the window+fv.darken(fv.ellipse(1090, 928, 80, 9), 0.3)+fv.plant(1090, 928, 430, pot=CREAM, leaf=TEAL, kind='leafy', seed=8, n=9)++# rug, lounge chair (facing left), side table+rug = fv.rrect(1260, 912, 1880, 968, 28)+fv.fill(rug, T(TEAL, -0.42))+for x in range(1296, 1860, 44):+ fv.fill(fv.rect(x, 912, x + 14, 968) & rug, T(TEAL, -0.28))+CH = T(TEAL, 0.0)+for (p0, p1, k) in [((1560, 850), (1548, 928), -0.3), ((1790, 850), (1806, 928), -0.3)]:+ fv.fill(fv.capsule(p0, p1, 7, 5), T(WOOD, k)) # far legs+fv.darken(fv.ellipse(1680, 934, 150, 10), 0.3)+backrest = fv.rrect(1742, 590, 1836, 850, (46, 46, 30, 30), rot=-10)+fv.cast(backrest, -26, 0, 0.22, clip=fv.rect(0, 0, W, FLOOR_Y - 22))+fv.fill(backrest, CH); fv.shade(backrest, 0.0, 26, colour=T(CH, -0.2))+fv.fill(fv.rrect(1760, 610, 1800, 720, 20, rot=-10), T(CH, 0.14)) # the button tuft band+seat = fv.rrect(1530, 792, 1800, 850, 24)+fv.fill(seat, CH); fv.shade(seat, 0.0, 18, colour=T(CH, -0.2))+fv.fill(fv.rect(1540, 846, 1806, 862), WOOD)+for (p0, p1) in [((1580, 860), (1568, 930)), ((1772, 860), (1788, 930))]:+ fv.fill(fv.capsule(p0, p1, 8, 6), WOOD)+# side table with two books and a mug of tea+TT = 816+fv.darken(fv.ellipse(1390, 932, 70, 8), 0.3)+fv.fill(fv.capsule((1390, TT), (1390, 924), 7), T(INK, 0.15))+fv.fill(fv.rrect(1344, 918, 1436, 930, 6), T(INK, 0.15))+top = fv.rrect(1316, TT, 1464, TT + 16, 8)+fv.fill(top, WOOD); fv.shade(top, 0.0, 6, colour=T(WOOD, -0.2))+yb = TT+for (x, w, h, c) in [(1334, 116, 18, INK), (1344, 100, 16, T(BLUE, 0.45))]:+ bk = fv.rrect(x, yb - h, x + w, yb, 3)+ fv.fill(bk, c); fv.fill(fv.rect(x + w - 10, yb - h, x + w, yb) & bk, T(c, -0.2))+ fv.fill(fv.rect(x, yb - h * 0.6, x + w - 12, yb - h * 0.4), T(c, 0.5))+ yb -= h+MX = 1398+mug = fv.rrect(MX, yb - 44, MX + 40, yb, (4, 4, 10, 10))+fv.fill(fv.arc(MX + 40, yb - 23, 8, 15, -90, 90), CREAM)+fv.fill(mug, CREAM); fv.shade(mug, 0.0, 10, colour=T(CREAM, -0.14))+fv.fill(fv.rect(MX, yb - 33, MX + 40, yb - 25), CORAL)+MUG_TOP = yb - 44+# pendant lamp over the chair (its beam comes later)+LX, LY = 1655, 346+fv.pendant(LX, 0, LY, 56, shade=INK, bulb=CREAM)+# a crate of second-hand books on the floor, bottom left+fv.darken(fv.ellipse(290, 1010, 200, 12), 0.3)+fv.books(150, 430, 948, 118, [CREAM, T(BLUE, 0.45), TEAL, MUSTARD, PEACH, INK], seed=31, w_range=(0.16, 0.3), title=False)+crate = fv.rrect(128, 930, 452, 1010, 6)+fv.fill(crate, WOOD); fv.shade(crate, 0.0, 16, colour=T(WOOD, -0.2))+for y in (955, 983):+ fv.fill(fv.rect(128, y, 452, y + 4), T(WOOD, -0.28))+fv.fill(fv.rrect(250, 944, 330, 996, 6), CREAM) # a card pinned on the front+fv.text('¥10', 290, 980, 26, INK, anchor='ms')+fv.stage('furniture')++# ---------------------------------------------------------------- people+# the customer in front of the bookcase, reaching up for the book, head tipped back to look at it+fv.darken(fv.ellipse(912, 962, 78, 9), 0.32)+BOOK = (786, 372)+B = fv.person((908, 748), 400, facing=-1, lean=-5, head_tilt=-20, hand_far_to=(826, 458), arm=(-6, 4),+ leg=(-3, 0), leg_far=(5, 0), top=MUSTARD, bottom=INK, coat=True, hair=T(CREAM, -0.2), hair_style='bob',+ bag=CREAM)+# the bookseller on the ladder: near foot on a rung, far foot one rung up, far hand on the rail, the near hand+# lowering the book+RUNG = lambda y: (y - 7)+A = fv.person((652, 404), 372, facing=1, lean=8, head_tilt=12, hand_to=(BOOK[0] - 14, BOOK[1] + 6),+ hand_far_to=(742, 166), foot_to=(648, RUNG(606) - 15), foot_far_to=(682, RUNG(532) - 15),+ top=CREAM, bottom=T(INK, 0.1), apron=TEAL, hair=T(MUSTARD, -0.62), hair_style='bun', draw_near_arm=False)+fv.book(*BOOK, 66, 88, rot=-16, colour=CORAL)+fv.near_arm()+fv.stage('handoff')+# the reader in the lounge chair, a book open in both hands, head bowed over it+C = fv.person((1692, 790), 372, facing=-1, sit=True, lean=-6, head_tilt=18, hand_to=(1612, 716), hand_far_to=(1598, 728),+ foot_to=(1560, 884), foot_far_to=(1600, 892), top=CREAM, bottom=INK, shoes=CREAM, hair=T(CORAL, -0.6),+ hair_style='bob', draw_near_arm=False)+fv.book(1600, 712, 104, 66, rot=-22, colour=MUSTARD, open=True)+fv.near_arm()+# the shop cat on the sill, watching the street+fv.cat(1296, WY1 - 6, 78, T(MUSTARD, -0.12), facing=1, tail_down=WY1 + 80)+fv.stage('reader')++# ---------------------------------------------------------------- light and the story marks+fv.fill(fv.poly([(LX - 40, LY), (LX + 40, LY), (1800, 912), (1500, 912)]), T(CREAM, 0.3), 0.12, grain=0.4)+fv.fill(fv.circle(LX, LY + 3, 17), T(CREAM, 0.5))+# a dashed trail from the empty slot on the top shelf down to the book in the bookseller's hand+fv.dashes([(862, 262), (850, 318), (818, 338)], width=6, dash=14, gap=11, colour=CORAL)+for (x, y, r, c) in [(884, 236, 15, MUSTARD), (744, 326, 10, CREAM), (824, 300, 8, CREAM)]:+ fv.sparkle(x, y, r, c)+# steam off the mug+for dx, h in ((-7, 48), (7, 36)):+ y0 = MUG_TOP - 8+ fv.fill(fv.tube([(MX + 20 + dx, y0), (MX + 26 + dx, y0 - h * 0.35), (MX + 16 + dx, y0 - h * 0.7), (MX + 21 + dx, y0 - h)],+ [3.2, 3, 2.2, 1.2]), CREAM, 0.75)+img = fv.save(out, stages_dir=stages) # the final frame is the 'light' stage+print('saved', out)diff --git a/examples/isometric_weather_island.jpg b/examples/isometric_weather_island.jpgnew file mode 100644index 0000000..10e58e7Binary files /dev/null and b/examples/isometric_weather_island.jpg differdiff --git a/examples/isometric_weather_island.py b/examples/isometric_weather_island.pynew file mode 100644index 0000000..5abc18c--- /dev/null+++ b/examples/isometric_weather_island.py@@ -0,0 +1,200 @@+"""Example (isometric 2.5D): 岛上的气象站 · Island Weather Station — a pastel isometric diorama of a small island that+turns its weather into four numbers: a fenced observation plot on a raised terrace (a louvred thermometer screen,+a rain gauge, a wind mast with cup anemometer and vane), the keeper's house with a satellite dish and solar panels,+a jetty with a boat, trees, rocks and a shore of foam; a weather balloon rising with its radiosonde and two+flat-bottomed clouds. Floating data cards (wind, temperature, rain, upper air) drop slim leaders to the+instrument each number comes from. Everything is traced solids lit by one soft sun. No image model.+python3 isometric_weather_island.py [out.jpg] [--stages DIR]+"""+import os, sys, time+import numpy as np+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from isometric import Isometric, INK, CORAL++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'isometric_weather_island.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++iso = Isometric(1920, 1080, seed=11, scale=80, look=(5, 5, 0), at=(0.515, 0.55), record=stages is not None)++WHITE, LAV, LAVD = '#fbfaf8', '#e7e1f3', '#b9addc'++# ---- 1. the floating slab+iso.backdrop('#e4def3', '#f5eeee', '#fbf8ff')+iso.slab(0, 0, 10, 10, z0=-0.95)+iso.stage('slab')++# ---- 2. land and sea: 0 sea, 1 sand, 2 grass, 3 the raised terrace of the observation plot, 4 a paved path+levels = np.array([+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],+ [0, 0, 1, 1, 1, 1, 1, 0, 0, 0],+ [0, 1, 2, 3, 3, 3, 2, 1, 0, 0],+ [0, 1, 2, 3, 3, 3, 2, 2, 1, 0],+ [0, 1, 2, 3, 3, 3, 2, 2, 1, 0],+ [0, 2, 2, 4, 2, 2, 2, 2, 1, 0],+ [0, 2, 2, 4, 2, 2, 2, 1, 0, 0],+ [0, 1, 1, 4, 2, 2, 1, 1, 0, 0],+ [0, 0, 0, 1, 1, 1, 0, 0, 0, 0],+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])+iso.tiles(levels)+iso.sea(shallow='#c3eae6', deep='#abc9f1', waves=1.0)+iso.stage('land')++G, T = 0.32, 0.60 # grass and terrace tile tops++# ---- 3. jetty, steps from the path up to the terrace, rocks on the shore+iso.pier(7.2, 1.72, 9.85, 2.2, z=0.27)+for k in range(3): # three steps from the grass up to the terrace+ x0 = 5.02 + 0.13 * (2 - k)+ iso.box(x0, 3.22, 0.0, x0 + 0.13, 3.78, 0.3 + (T - 0.3) * (k + 1) / 3.3, LAV, bevel=0.012)+for (x, y, r) in [(1.3, 1.55, 0.12), (1.15, 1.9, 0.08), (8.3, 3.25, 0.13), (7.35, 7.35, 0.11), (2.25, 7.7, 0.1),+ (8.6, 5.9, 0.1)]:+ z = iso.top_z(x, y)+ iso.rock(x, y, z - (0.05 if z < 0.2 else 0), r)+for (x, y, col) in [(9.0, 6.3, CORAL), (6.4, 9.1, '#f7df97')]: # two channel buoys+ iso.cylinder(x, y, 0.04, 0.24, 0.13, col, r1=0.11)+ iso.cylinder(x, y, 0.24, 0.3, 0.11, WHITE, r1=0.1)+ iso.cylinder(x, y, 0.3, 0.62, 0.035, WHITE)+ iso.cylinder(x, y, 0.62, 0.74, 0.07, col, r1=0.0)+iso.stage('shore')++# ---- 4. the keeper's house, dish and solar panels+iso.building(5.25, 1.25, 6.65, 2.75, z=G, h=0.72, wall=WHITE, roof='gable', axis='y', roof_colour='#f3a597',+ windows=(1, 2, 1), door=('+x', 2.0), trim='#e9e2f3')+iso.dish(4.5, 2.0, G, r=0.22, yaw=125, tilt=40, h=0.42)+iso.windsock(7.55, 1.1, 0.22, h=0.85, yaw=135) # streams north-west: a south-east wind+for k in range(2):+ iso.solar_panel(6.05, 4.35 + k * 1.05, G, w=0.92, d=0.62, tilt=26, yaw=0)+iso.stage('station')++# ---- 5. the observation plot: fence, thermometer screen, rain gauge, wind mast+++def stevenson(x, y, z):+ """a louvred thermometer screen on four legs, white, with a double roof"""+ for dx in (-0.14, 0.14):+ for dy in (-0.11, 0.11):+ iso.box(x + dx - 0.014, y + dy - 0.014, z, x + dx + 0.014, y + dy + 0.014, z + 0.52, WHITE, bevel=0.005)+ zb = z + 0.5+ c = np.array([1.0, 1.0, 1.0], np.float32) * np.array([0.985, 0.978, 0.972], np.float32)++ def louvre(P, n, t):+ v = np.mod((P[:, 2] - zb) / 0.042, 1.0)+ side = np.abs(n[:, 2]) < 0.5+ k = np.where(side & (v < 0.34), 0.82, np.where(side & (v < 0.42), 0.93, 1.0))+ return c * k[:, None]+ iso.box(x - 0.2, y - 0.17, zb, x + 0.2, y + 0.17, zb + 0.36, WHITE, bevel=0.01, paint=louvre)+ iso.box(x - 0.23, y - 0.2, zb + 0.38, x + 0.23, y + 0.2, zb + 0.405, WHITE, bevel=0.008)+ iso.box(x - 0.25, y - 0.22, zb + 0.43, x + 0.25, y + 0.22, zb + 0.455, WHITE, bevel=0.008)+ return np.array([x, y, zb + 0.46])+++def rain_gauge(x, y, z):+ """a copper-free white gauge: base ring, body, a darker funnel opening"""+ iso.cylinder(x, y, z, z + 0.03, 0.11, LAV)+ rim = np.array([0.30, 0.28, 0.40], np.float32)++ def top(P, n, t):+ r = np.hypot(P[:, 0] - x, P[:, 1] - y)+ c = np.where((n[:, 2] > 0.9) & (r < 0.062), 0.55, 1.0)[:, None]+ return np.array([0.975, 0.97, 0.965], np.float32) * c + rim * (1 - c) * 0.0+ iso.cylinder(x, y, z + 0.03, z + 0.33, 0.08, WHITE, paint=top)+ iso.cylinder(x, y, z + 0.33, z + 0.36, 0.088, WHITE, r1=0.09)+ return np.array([x, y, z + 0.37])+++def wind_mast(x, y, z, h=2.7):+ """a slim white mast with coral bands, three guy wires, a cross-arm carrying a cup anemometer and a vane"""+ top = z + h+ band = np.array([0.95, 0.62, 0.57], np.float32); wh = np.array([0.985, 0.98, 0.975], np.float32)++ def bands(P, n, t):+ f = (P[:, 2] - z) / h+ on = ((f > 0.62) & (f < 0.68)) | ((f > 0.82) & (f < 0.88))+ return np.where(on[:, None], band, wh)+ iso.cylinder(x, y, z, top, 0.032, WHITE, r1=0.024, paint=bands)+ for a in (100, 220, 340):+ ax_, ay_ = x + 0.55 * np.cos(np.radians(a)), y + 0.55 * np.sin(np.radians(a))+ iso.tube((x, y, z + h * 0.6), (ax_, ay_, z + 0.01), 0.005, '#cfc8e4', ao=False)+ iso.box(ax_ - 0.03, ay_ - 0.03, z, ax_ + 0.03, ay_ + 0.03, z + 0.04, LAVD, bevel=0.01)+ arm0, arm1 = np.array([x, y - 0.38, top - 0.02]), np.array([x, y + 0.38, top - 0.02])+ iso.tube(arm0, arm1, 0.016, WHITE)+ # cup anemometer on the +y end+ ax_, ay_ = arm1[0], arm1[1]+ iso.cylinder(ax_, ay_, top - 0.02, top + 0.2, 0.014, WHITE)+ iso.cylinder(ax_, ay_, top + 0.17, top + 0.23, 0.035, WHITE)+ for k in range(3):+ a = np.radians(20 + 120 * k)+ e = np.array([ax_ + 0.24 * np.cos(a), ay_ + 0.24 * np.sin(a), top + 0.2])+ iso.tube((ax_, ay_, top + 0.2), e, 0.008, WHITE)+ tng = np.degrees(a) + 90 # cups open sideways, all the same way round+ iso.ellipsoid(e, (0.062, 0.062, 0.062), CORAL, yaw=tng, clip=[((np.cos(np.radians(tng)), np.sin(np.radians(tng)), 0),+ np.cos(np.radians(tng)) * e[0] + np.sin(np.radians(tng)) * e[1])])+ # wind vane on the -y end: shaft, pointer, tail fin+ vx, vy = arm0[0], arm0[1]+ iso.cylinder(vx, vy, top - 0.02, top + 0.16, 0.014, WHITE)+ yaw = -45.0 # points into the wind: south-east (north is +y)+ d = np.array([np.cos(np.radians(yaw)), np.sin(np.radians(yaw)), 0])+ c = np.array([vx, vy, top + 0.16])+ iso.tube(c - d * 0.27, c + d * 0.24, 0.011, WHITE)+ iso.tube(c + d * 0.24, c + d * 0.37, 0.038, CORAL, r1=0.0)+ iso.obox(c - d * 0.25, (0.2, 0.014, 0.16), yaw=yaw, colour=CORAL, bevel=0.005)+ iso.sphere(x, y, top + 0.035, 0.028, CORAL) # obstruction light+ return np.array([ax_, ay_, top + 0.24])+++iso.fence([(2.12, 3.12), (4.88, 3.12), (4.88, 5.88), (2.12, 5.88)], z=T, h=0.18, closed=True, spacing=0.23)+a_screen = stevenson(3.75, 3.95, T)+a_rain = rain_gauge(3.2, 5.25, T)+a_wind = wind_mast(2.55, 3.55, T, h=3.1)+iso.stage('instruments')++# ---- 6. trees, bushes, the boat+for (x, y, s_, k) in [(2.5, 6.55, 1.05, 'round'), (3.45, 7.35, 0.9, 'round'), (4.3, 7.5, 1.0, 'pine'),+ (5.45, 7.15, 1.05, 'round'), (6.45, 6.55, 0.95, 'pine'), (1.55, 2.55, 0.9, 'pine'),+ (1.6, 6.35, 0.85, 'round'), (4.45, 6.75, 0.85, 'poplar'), (5.4, 6.2, 0.8, 'poplar'),+ (7.3, 4.5, 0.85, 'round'), (3.5, 1.5, 0.9, 'round')]:+ iso.tree(x, y, iso.top_z(x, y), s_, k)+for (x, y, fl) in [(6.85, 3.25, '#f6b3c4'), (5.15, 1.05, None), (7.35, 5.65, '#f7df97'), (1.7, 4.4, None),+ (6.6, 6.35, '#f6b3c4'), (2.95, 6.2, '#fbfaf8'), (4.6, 2.8, '#c9b8f2'), (7.3, 3.8, None)]:+ iso.tree(x, y, iso.top_z(x, y), 1.1 if fl else 1.0, 'bush', flowers=fl)+iso.boat(8.9, 2.72, 0.14, length=0.95, width=0.38, yaw=0)+iso.stage('trees')++# ---- 7. the sky: a rising weather balloon and two clouds+bx, by, bz = iso.unproject(1440, 300, 4.4)+iso.balloon(bx, by, bz, r=0.4, colour='#fbe3ea', string=0.85)+a_ball = np.array([bx, by, bz - 0.4 - 0.85 - 0.06])+cx, cy, cz = iso.unproject(470, 470, 3.0)+iso.cloud(cx, cy, cz, 0.95)+cx, cy, cz = iso.unproject(1760, 760, 2.4)+iso.cloud(cx, cy, cz, 0.7)+iso.stage('sky')++# ---- 8. data cards, each with a leader to its instrument+cards = [+ dict(at=(700, 300), z=2.6, title='气温', tag='TEMP', value='21.4', unit='°C', note='百叶箱内,离地 1.5 m', icon='temp',+ series=[16.2, 16.8, 18.1, 19.6, 20.4, 21.0, 21.6, 21.4], anchor=a_screen, accent='#f08f86'),+ dict(at=(1265, 215), z=4.2, title='风速', tag='WIND', value='4.6', unit='m/s', note='东南风,3 级', icon='wind',+ series=[3.1, 3.8, 3.4, 4.4, 5.2, 4.1, 4.9, 4.6], anchor=a_wind, accent='#8f7ee6'),+ dict(at=(1700, 350), z=3.6, title='探空', tag='UPPER AIR', value='12.8', unit='km', note='每分钟升约 300 m', icon='balloon',+ series=[0, 1.6, 3.3, 5.0, 6.8, 8.6, 10.6, 12.8], anchor=a_ball, accent='#e98bb4'),+ dict(at=(1560, 640), z=1.8, title='降水', tag='RAIN', value='0.6', unit='mm', note='近 1 小时累计', icon='rain',+ series=[0, 0, 0.1, 0.1, 0.3, 0.4, 0.5, 0.6], anchor=a_rain, accent='#6fa8e8'),+]+for c in cards:+ x, y, z = iso.unproject(*c['at'], z=c['z'])+ iso.card(x, y, z, 2.9, 1.65, facing='+x', title=c['title'], tag=c['tag'], value=c['value'], unit=c['unit'],+ note=c['note'], icon=c['icon'], series=c['series'], anchor=c['anchor'], accent=c['accent'])++# ---- title and caption, set flat on top+iso.text('ISLAND WEATHER STATION', 112, 118, 20, '#8a80b8', font='sans_bold', spacing=4.5)+iso.text('岛上的气象站', 108, 196, 70, INK)+iso.rule(112, 226, 176, 226, '#9d86e8', 4)+iso.text('风杆测风,百叶箱测温,雨量筒接雨,', 112, 272, 25, '#5b5782')+iso.text('探空气球把高空的数据发回来。', 112, 308, 25, '#5b5782')+iso.text('每 10 分钟记一次,经卫星天线回传', 112, 352, 19, '#8f88b0')+kx, ky, kz = iso.unproject(292, 858, iso.floor)+iso.compass(kx, ky, kz, r=0.95, north=(0, 1)) # north is +y: the 10:40 sun stands in the south-east+iso.save(out, stages_dir=stages)+print('saved', out, f'{time.time() - t0:.1f}s')diff --git a/examples/lineart_paper_plane.jpg b/examples/lineart_paper_plane.jpgnew file mode 100644index 0000000..e8672d7Binary files /dev/null and b/examples/lineart_paper_plane.jpg differdiff --git a/examples/lineart_paper_plane.py b/examples/lineart_paper_plane.pynew file mode 100644index 0000000..fc1fa33--- /dev/null+++ b/examples/lineart_paper_plane.py@@ -0,0 +1,96 @@+"""Example (continuous line art): 从这扇窗到那扇窗 / From Window to Window — one unbroken gold line on a night-blue+card. It comes in along a hill, draws a round tree and a small house, and leaves through the house's window as+the flight path of a paper plane: a long climb, one loop-the-loop at the top, a glide down, then the plane+itself, which flies straight on through the wall into the window of a second house across the gap. That window+is the only colour in the picture: it lights up once the line has finished the second house and run out along+the far hill. The flight path is drawn with a lighter hand than the houses. Letter-spaced title underneath.+No image model.+python3 lineart_paper_plane.py [out.png] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from lineart import LineArt, AMBER, GOLD++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'lineart_paper_plane.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++la = LineArt(1920, 1080, seed=11)+la.backdrop('night')+S, P, back = LineArt.smooth, LineArt.poly, LineArt.retrace++# ---- left hill: fade in, a round tree, house A+ground_in = S([(160, 718), (190, 716), (218, 713), (236, 712)])+crown = LineArt.scallop(247, 606, 42, 104, 436, bumps=7, depth=0.13)+tree = np.vstack([S([(236, 712), (237, 686), tuple(crown[0])]), crown, S([tuple(crown[-1]), (257, 686), (260, 712)])])+lane = S([(260, 712), (284, 711), (310, 709), (330, 708)])+AX0, AX1, AY0, AY1, AAP = 330, 454, 616, 708, 540 # walls, eaves height, ground, apex+WA = (386, 428, 626, 668) # window A: x0, x1, y0, y1 (near the right wall)+YA = 647 # where the flight leaves through the wall+house_a = np.vstack([+ P([(AX0, AY1), (AX0, AY0), (AX0 - 14, AY0), ((AX0 + AX1) / 2, AAP), (AX1 + 14, AY0), (AX1, AY0), (AX1, AY1)], r=4, sharp=(3,)),+ back(S([(AX1, AY1), (478, 710), (506, 715), (528, 721)])), # hill shoulder, and back+ P([(AX1, AY1), (AX1, YA), (WA[1], YA)], r=0), # back up the wall, in to the window+ P([(WA[1], YA), (WA[1], WA[3]), (WA[0], WA[3]), (WA[0], WA[2]), (WA[1], WA[2]), (WA[1], YA)], r=2),+ P([(WA[1], YA), (AX1, YA)], r=0)]) # out through the wall+# ---- the paper plane, seen three-quarter from above (local frame: nose at 0,0 pointing +x): near wing N-T-K,+# far wing N-K-B (foreshortened), crease N-K. The pen enters at the rear notch K and leaves at the nose.+N, T, K, B = (0, 0), (-150, -62), (-116, 2), (-130, 42)+PLANE_AT, PLANE_ANG, PLANE_SIZE = (1390, 622), 16, 0.86+place = lambda pts: LineArt.place(pts, PLANE_AT, PLANE_ANG, PLANE_SIZE)+KW = tuple(place([K])[0])+plane = place(P([K, B, N, K, T, N], r=2 / PLANE_SIZE, sharp=(1, 2, 3, 4)))+# ---- the flight: out through the wall and straight up into a long climb, one loop-the-loop at the top, then the+# glide down into the plane's tail. The hand eases off along it (see `pressure` below), so the flight path is+# lighter than the things it connects and never reads as a hill.+flight = S([(AX1, YA), (486, 641), (524, 624), (580, 588), (648, 530), (724, 466), (804, 412), (884, 374),+ (962, 350), (1036, 344), (1104, 360), (1156, 404), (1196, 468), (1232, 532), (1262, 574), KW])+flight = LineArt.curl(flight, LineArt.locate(flight, (1000, 346)), 62, span=96, aspect=1.2)+# ---- house B: the line flies on from the nose, in through the left wall to the window, then builds the house+BX0, BX1, BY0, BY1, BAP = 1424, 1600, 610, 709, 520+WB = (1450, 1506, 616, 668)+YB = 640+slope = (BY0 - BAP) / (BX1 + 14 - (BX0 + BX1) / 2)+cy = lambda x: BAP + (x - (BX0 + BX1) / 2) * slope+NX, NY = plane[-1]+JB = (BX0, NY + (YB - NY) * (BX0 - NX) / (WB[0] - NX)) # where the arrival crosses the left wall+arrive = P([(NX, NY), (WB[0], YB)], r=0)+house_b = np.vstack([+ P([(WB[0], YB), (WB[0], WB[2]), (WB[1], WB[2]), (WB[1], WB[3]), (WB[0], WB[3]), (WB[0], YB)], r=2),+ P([(WB[0], YB), JB, (BX0, BY1)], r=0),+ back(S([(BX0, BY1), (1400, 711), (1374, 716), (1352, 721)])), # hill shoulder, and back+ P([(BX0, BY1), (BX0, BY0), (BX0 - 14, BY0), ((BX0 + BX1) / 2, BAP), (1546, cy(1546)), (1546, 512), (1570, 512),+ (1570, cy(1570)), (BX1 + 14, BY0), (BX1, BY0), (BX1, BY1)], r=4, sharp=(3,))])+bush = LineArt.scallop(1672, 708, 22, 180, 360, bumps=3, depth=0.2, squash=0.9)+ground_out = np.vstack([S([(BX1, BY1), (1628, 710), tuple(bush[0])]), bush,+ S([tuple(bush[-1]), (1712, 712), (1740, 715), (1772, 718), (1800, 721)])])++path, marks = la.chain([('ground', ground_in), ('tree', tree), ('lane', lane), ('house_a', house_a),+ ('flight', flight), ('plane', plane), ('arrive', arrive), ('house_b', house_b), ('end', ground_out)])+DY = -56 # lift the whole drawing above the title+path = path + np.float32([0, DY])+la.line(path, width=3.3, pressure=[(marks['house_a'], marks['flight'], 0.62), (marks['plane'], marks['arrive'], 0.7)])++window_b = 2 * ((WB[1] - WB[0]) + (WB[3] - WB[2])) # perimeter of the far window+steps = [('tree', marks['tree']), ('house_a', marks['house_a']), ('climb', marks['house_a'] + 400),+ ('loop', marks['house_a'] + 1000), ('glide', marks['flight']), ('plane', marks['plane']),+ ('window', marks['arrive'] + window_b), ('end', marks['end'])]+for name, s in steps:+ la.draw_to(s); la.stage(name)++# ---- the one accent: the far window lights up (four panes, glazing bars left dark)+wx0, wx1, wy0, wy1 = WB[0] + 5, WB[1] - 5, WB[2] + 5 + DY, WB[3] - 5 + DY+xm, ym = (wx0 + wx1) / 2, (wy0 + wy1) / 2+win = la.rect(wx0, wy0, wx1, wy1, r=1.5) * (1 - la.rect(xm - 1.6, wy0, xm + 1.6, wy1)) * (1 - la.rect(wx0, ym - 1.6, wx1, ym + 1.6))+la.accent(win, AMBER)+la.stage('light')++# ---- title+la.text('FROM WINDOW TO WINDOW', 960, 832, 38, GOLD, 'display', spacing=10)+cap = '一架纸飞机,一笔没有断开'+la.text(cap, 960, 886, 24, '#b9ab8a', 'display', spacing=7)+wc = la.text_width(cap, 24, 'display', spacing=7) / 2+la.hairline(960 - wc - 86, 878, 960 - wc - 26, 878, colour='#8d7f63')+la.hairline(960 + wc + 26, 878, 960 + wc + 86, 878, colour='#8d7f63')+la.save(out, stages)+print('saved', out)diff --git a/examples/morph_water_cycle.jpg b/examples/morph_water_cycle.jpgnew file mode 100644index 0000000..7b66cadBinary files /dev/null and b/examples/morph_water_cycle.jpg differdiff --git a/examples/morph_water_cycle.py b/examples/morph_water_cycle.pynew file mode 100644index 0000000..372de9b--- /dev/null+++ b/examples/morph_water_cycle.py@@ -0,0 +1,153 @@+"""Example (shape morph): 一滴水的旅程 / A Drop's Round Trip — the water cycle told by one outline.+A single 256-point outline turns into six things in a row -- a drop, a cloud, a snowflake, a snowy peak, a river,+a breaking wave -- and the background colour switches with it. The poster freezes the animation like a film+strip: six flat colour panels, the solid keyframe in each, onion-skin ghosts of the in-between frames (bunched+near the keys, spread out in the middle because of the easing), squash & stretch in the fast middle, a dashed+motion path through the centroids, the resampled points dotted on every middle frame, and an animation timeline+underneath with keyframe diamonds and the ease curve of every transition. No image model.+python3 morph_water_cycle.py [out.png] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from morph import Morph, INK++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'morph_water_cycle.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++PAPER, CREAM, BLUE = '#efe9dd', '#f4efe4', '#2437d6'+m = Morph(1920, 1080, seed=6)+m.paper(PAPER)++Y0, Y1, PW = 300, 780, 320 # the film strip: six panels, 320 px each+EASE = 'sine'+U = [0.25, 0.5, 0.75] # frame times of the ghosts (even in time)+# name, label, english, (cx, cy, size), background, shape colour, ink on this background+KEYS = [('drop', '水滴', 'DROP', (160, 540, 180), '#f2b93b', BLUE, INK),+ ('cloud', '云', 'CLOUD', (480, 460, 214), BLUE, CREAM, CREAM),+ ('snowflake', '雪花', 'SNOWFLAKE', (800, 530, 190), '#171a3c', '#ffffff', CREAM),+ ('mountain', '雪山', 'SNOWPACK', (1120, 575, 214), '#ee5a3c', INK, INK),+ ('river', '河', 'RIVER', (1440, 575, 200), '#2e9a68', '#bfe0ff', CREAM),+ ('wave', '海', 'SEA', (1760, 585, 206), '#10707f', CREAM, CREAM)]+VERBS = [('凝结', 'CONDENSE'), ('降雪', 'SNOWFALL'), ('积存', 'SETTLE'), ('融化', 'MELT'), ('入海', 'FLOW')]++outlines = m.chain([m.shape(n, *p) for n, _, _, p, _, _, _ in KEYS])+cents = [m.centroid(P) for P in outlines]+route = m.path(cents, 60) # motion path through the centroids+segs = [route[60 * k:60 * (k + 1) + 1] for k in range(len(KEYS) - 1)]+++def keyframe(k):+ """the solid shape of keyframe k plus the details that live inside it"""+ name, _, _, (cx, cy, sz), bg, fg, ink = KEYS[k]+ P = outlines[k]+ m.fill(P, fg)+ if name == 'drop': # a highlight on the belly+ a = np.linspace(np.deg2rad(200), np.deg2rad(250), 12)+ m.stroke(np.stack([cx + 0.2 * sz * np.cos(a), cy + 0.15 * sz - 0.2 * sz * np.sin(a)], 1), CREAM, sz * 0.05, 0.9)+ if name == 'mountain': # a lighter right flank, snow cap with a zigzag hem+ top = P[np.argmin(P[:, 1])]+ m.fill(P, '#2b2f5a', half=((top[0], top[1]), (top[0] - 60, top[1] + 400)))+ cap = [(top[0], top[1] - 4), (top[0] + 0.14 * sz, top[1] + 0.22 * sz), (top[0] + 0.07 * sz, top[1] + 0.18 * sz),+ (top[0] + 0.01 * sz, top[1] + 0.25 * sz), (top[0] - 0.06 * sz, top[1] + 0.17 * sz),+ (top[0] - 0.12 * sz, top[1] + 0.21 * sz)]+ m.fill(np.array(cap), CREAM, clip=P)+ if name == 'river': # current lines on the water+ for (x0, y0, x1, y1) in [(-0.04, 0.24, 0.1, 0.3), (-0.02, 0.02, 0.07, -0.02), (0.0, -0.24, 0.04, -0.28)]:+ m.stroke([(cx + x0 * sz, cy + y0 * sz), (cx + x1 * sz, cy + y1 * sz)], '#7fb3e6', sz * 0.022, 1.0)+++def extras(k):+ """details around keyframe k that are drawn once"""+ name, _, _, (cx, cy, sz), bg, fg, ink = KEYS[k]+ if name == 'drop': # heat shimmer under the drop: it is evaporating+ for dx in (-34, 0, 34):+ y = np.linspace(0, 1, 30)+ m.stroke(np.stack([cx + dx + 6 * np.sin(y * 2 * np.pi * 1.2), cy + 112 + y * 52], 1), ink, 4.5, 0.5)+ if name == 'snowflake': # a few flakes still falling+ r = np.random.default_rng(3)+ for _ in range(9):+ x, y = r.uniform(k * PW + 30, (k + 1) * PW - 30), r.uniform(Y0 + 30, Y1 - 90)+ if np.hypot(x - cx, y - cy) > sz * 0.62: m.dot(x, y, r.uniform(3, 6), CREAM, 0.7)+ if name == 'wave': # spray off the lip+ for dx, dy, rr in [(-0.46, -0.3, 7), (-0.5, -0.18, 5), (-0.42, -0.42, 4.5)]:+ m.dot(cx + dx * sz, cy + dy * sz, rr, CREAM, 0.9)+++def label(k):+ name, cn, en, _, bg, fg, ink = KEYS[k]+ x = k * PW + 26+ m.text('BG ' + bg.upper(), (k + 1) * PW - 22, Y0 + 36, 12, ink, 'mono', anchor='r', spacing=1.5, alpha=0.7)+ w = m.text(f'{k + 1:02d}', x, Y1 - 26, 17, ink, 'mono_bold')+ m.text(f'/{len(KEYS):02d}', x + w, Y1 - 26, 17, ink, 'mono', alpha=0.55)+ m.text(cn, x + 72, Y1 - 24, 24, ink, 'cjk_bold')+ m.text(en, x + 72 + m.text_width(cn, 24, 'cjk_bold') + 10, Y1 - 26, 12, ink, 'mono', spacing=2.5, alpha=0.75)+++def transition(k):+ """onion skin from keyframe k to k+1: ghosts, the sampled points of the middle frame, a path chevron"""+ A, B = outlines[k], outlines[k + 1]+ fa, fb = KEYS[k][5], KEYS[k + 1][5]+ for u in U:+ s = float(m.ease(u, EASE))+ c, d = m.along(segs[k], s)+ G = m.tween(A, B, s, at=c, stretch=0.16 * np.sin(np.pi * s), direction=d)+ mid = u == 0.5+ m.ghost(G, fill=m.mix(fa, fb, s), fill_alpha=0.42 if mid else 0.14, line_alpha=0.75 if mid else 0.42,+ width=2.6 if mid else 2.0)+ if mid: m.points(G, every=8, r=2.8, alpha=0.95)+ c, d = m.along(segs[k], 0.34)+ m.chevron(c[0], c[1], d, 11, None, 2.6, 0.6)+++# ---- header+m.fill(np.array([(80, 88), (122, 88), (122, 94), (80, 94)]), BLUE)+m.text('形变动画 · SHAPE TWEEN', 136, 97, 17, INK, 'mono_bold', spacing=1.5)+m.text('一滴水的旅程', 74, 196, 84, INK, 'cjk_bold')+m.text('THE ROUND TRIP OF A WATER DROP', 80, 244, 17, INK, 'mono', spacing=4, alpha=0.7)+m.text('同一条轮廓线,256 个点,先后变成六样东西:', 1190, 132, 26, INK, 'cjk')+m.text('蒸发、凝结、降雪、积存、融化,再流回大海。', 1190, 172, 26, INK, 'cjk')+lx = 1192 # legend+m.diamond(lx + 8, 226, 8, fill=BLUE, line=INK, width=2)+lx += 40 + m.text('关键帧', lx + 24, 232, 16, INK, 'cjk')+m.outline(m.shape('circle', lx + 10, 226, 20), INK, 2, 0.8)+lx += 44 + m.text('残影', lx + 26, 232, 16, INK, 'cjk')+m.trail(np.array([(lx, 226), (lx + 36, 226)]), INK, 2.2, dash=(8, 6), alpha=0.8)+lx += 62 + m.text('轨迹', lx + 46, 232, 16, INK, 'cjk')+for i in range(4): m.dot(lx + i * 10, 226, 2.6, INK)+m.text('对应点', lx + 46, 232, 16, INK, 'cjk')+m.stage('title')++# ---- the strip, panel by panel+for k in range(len(KEYS)):+ m.panel(k * PW, Y0, (k + 1) * PW, Y1, KEYS[k][4], ink=KEYS[k][6])+ if k > 0:+ m.trail(segs[k - 1], None, 2.2, dash=(9, 9), alpha=0.5)+ transition(k - 1)+ keyframe(k - 1) # the previous key stays on top of its own ghosts+ keyframe(k)+ extras(k)+ label(k)+ m.stage(f'{k + 1:02d}_{KEYS[k][0]}')++# ---- timeline: keyframe diamonds and the ease curve of every transition+TY, TH = 988, 92+m.outline(np.array([(60, TY), (1860, TY)]), INK, 2.0, 0.8, closed=False)+for k in range(len(KEYS)):+ x = k * PW + PW / 2+ if k < len(KEYS) - 1:+ m.ease_curve(x + 26, TY, x + PW - 26, TY - TH, EASE, INK, 2.6, ticks=U, tick_colour=INK)+ cn, en = VERBS[k]+ w = m.text_width(cn, 20, 'cjk_bold') + 8 + m.text_width(en, 12, 'mono', 2)+ m.text(cn, x + PW / 2 - w / 2, 1036, 20, INK, 'cjk_bold')+ m.text(en, x + PW / 2 - w / 2 + m.text_width(cn, 20, 'cjk_bold') + 8, 1034, 12, INK, 'mono', spacing=2, alpha=0.7)+ m.diamond(x, TY, 12, fill=KEYS[k][4], line=INK, width=2.4)+ m.text(f'00:{k * 2:02d}', x, TY + 40, 14, INK, 'mono', anchor='m', alpha=0.7)+a = np.linspace(np.deg2rad(-150), np.deg2rad(150), 40) # loop back to 01+m.outline(np.stack([1832 + 16 * np.cos(a), TY - 44 - 16 * np.sin(a)], 1), INK, 2.6, closed=False)+m.chevron(1832 + 16 * np.cos(a[-1]), TY - 44 - 16 * np.sin(a[-1]), 240, 9, INK, 2.6, 1.0)+m.text('蒸发 · 回到 01', 1806, TY - 38, 16, INK, 'cjk_bold', anchor='r')+m.text('EASE IN-OUT · 3 ONION-SKIN FRAMES PER TRANSITION', 60, TY - TH - 22, 13, INK, 'mono', spacing=2, alpha=0.7)++m.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/newscollage_curiosity.jpg b/examples/newscollage_curiosity.jpgnew file mode 100644index 0000000..815595dBinary files /dev/null and b/examples/newscollage_curiosity.jpg differdiff --git a/examples/newscollage_curiosity.py b/examples/newscollage_curiosity.pynew file mode 100644index 0000000..8f5be7e--- /dev/null+++ b/examples/newscollage_curiosity.py@@ -0,0 +1,210 @@+"""Example (newspaper collage): 好奇心周刊 · 拆开看看 / Curiosity Weekly · Take It Apart -- the cover of a made-up+weekly, cut and pasted on kraft board. A halftone photograph of a twin-bell alarm clock has been cut in two with+scissors and the top half hinged open; out of the gap fly the parts that make it tick, each its own halftone+clipping with a typed label and an inked leader line: wheels (齿轮), the mainspring (发条), the balance wheel+(摆轮, printed in red) and screws (螺丝). Behind it a scissor-cut disc of red paper; on the left a torn page of old+newsprint (generated pseudo-text), the masthead, ransom-note letters 拆开看看? and WHAT MAKES IT TICK; masking+tape, a black postmark, a red 附零件图 (parts inside) stamp, and a typed strip that says how a clock works:+mainspring -> wheels -> balance -> hands. Every photograph is rendered from a height field, no image model.+python3 newscollage_curiosity.py [out.jpg] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from newscollage import NewsCollage, Photo, RED, INK, PAPER, MUSTARD++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'newscollage_curiosity.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++nc = NewsCollage(1920, 1080, seed=42)+CHROME = dict(albedo=0.95, metal=1.0, gloss=0.5)+++# ------------------------------------------------------------ things to photograph+def alarm_clock(R=205):+ k = R / 250+ P = Photo(640, 690, seed=5, backdrop=(0.96, 0.84), lift=34)+ cx, cy = 318, 360+ for s in (-1, 1): # legs and ball feet, behind the case+ a = np.deg2rad(90 + s * 38)+ p0 = (cx + np.cos(a) * (R - 60 * k), cy + np.sin(a) * (R - 60 * k)); p1 = (cx + np.cos(a) * (R + 58 * k), cy + np.sin(a) * (R + 58 * k))+ P.rod(p0, p1, 11 * k, **CHROME)+ P.dome(p1[0], p1[1] + 4 * k, 22 * k, 20 * k, height=18 * k, **CHROME)+ P.rod((cx, cy - R + 20 * k), (cx, cy - R - 64 * k), 7 * k, **CHROME) # hammer between the bells+ P.rod((cx - 22 * k, cy - R - 64 * k), (cx + 22 * k, cy - R - 64 * k), 9 * k, **CHROME)+ for s in (-1, 1): # bells on their posts, tilted outward+ a = np.deg2rad(-90 + s * 42)+ bx, by = cx + np.cos(a) * (R + 62 * k), cy + np.sin(a) * (R + 62 * k)+ P.rod((cx + np.cos(a) * (R - 30 * k), cy + np.sin(a) * (R - 30 * k)), (bx, by), 8 * k, **CHROME)+ P.dome(bx, by, 112 * k, 96 * k, height=70 * k, rot=-s * 42, cut=0.3, **CHROME)+ t = np.deg2rad(-s * 42); lx, ly = 112 * k * 0.95, 96 * k * 0.3+ ends = [(bx + u * np.cos(t) + ly * np.sin(t), by - u * np.sin(t) + ly * np.cos(t)) for u in (-lx * 0.97, lx * 0.97)]+ P.rod(ends[0], ends[1], 6 * k, z=6 * k, **CHROME)+ P.disc(cx, cy, R, height=20 * k, bevel=14 * k, albedo=0.55, metal=0.9, gloss=0.4) # case, dial, bezel+ P.disc(cx, cy, R - 34 * k, z=6 * k, height=6 * k, bevel=2, albedo=0.95, metal=0.0, gloss=0.25)+ P.ring(cx, cy, R - 40 * k, R - 4 * k, z=4 * k, height=26 * k, **CHROME)+ ticks = []+ for i in range(60):+ a = np.deg2rad(i * 6 - 90)+ r0 = R - (74 if i % 5 == 0 else 62) * k+ ticks.append([(cx + np.cos(a) * r0, cy + np.sin(a) * r0), (cx + np.cos(a) * (R - 50 * k), cy + np.sin(a) * (R - 50 * k))])+ P.lines(ticks[::5], 5 * k, 0.08)+ P.lines([p for i, p in enumerate(ticks) if i % 5], 2.4 * k, 0.12)+ for i in range(1, 13):+ a = np.deg2rad(i * 30 - 90)+ P.text(str(i), cx + np.cos(a) * (R - 108 * k), cy + np.sin(a) * (R - 108 * k), 46 * k, 'didone', 0.08, 'mm')++ def hand(angle, L, W, tail, z):+ a = np.deg2rad(angle - 90); ux, uy = np.cos(a), np.sin(a); nx, ny = -uy, ux+ pts = [(-tail, -W * 0.5), (L * 0.62, -W * 0.5), (L * 0.72, -W * 1.5), (L, 0), (L * 0.72, W * 1.5), (L * 0.62, W * 0.5), (-tail, W * 0.5)]+ P.poly([(cx + ux * u + nx * v, cy + uy * u + ny * v) for u, v in pts], z=z, height=4, bevel=1.5, albedo=0.12, metal=0.4, gloss=0.5)+ hand(-58, 118 * k, 9 * k, 20 * k, 12 * k) # ten past ten+ hand(52, 172 * k, 7 * k, 26 * k, 16 * k)+ a = np.deg2rad(150 - 90)+ P.rod((cx - np.cos(a) * 40 * k, cy - np.sin(a) * 40 * k), (cx + np.cos(a) * 190 * k, cy + np.sin(a) * 190 * k), 2.2 * k, z=20 * k, albedo=0.15, metal=0.3)+ P.dome(cx, cy, 15 * k, z=22 * k, height=8 * k, **CHROME)+ P.glare(cx, cy, 150 * k, 205 * k, 195, 255, 0.45) # the glass crystal+ P.glare(cx, cy, 60 * k, 90 * k, 20, 50, 0.2)+ return P, (cx, cy)+++def wheel(r, teeth, spokes=5, pinion=None, rot=0.0, seed=1):+ n = int(2 * r + 60)+ P = Photo(n, n, seed=seed, backdrop=(0.96, 0.86), lift=8)+ P.gear(r + 20, r + 20, r, teeth=teeth, spokes=spokes, pinion=pinion, rot=rot, albedo=0.56, metal=0.32,+ depth=r * 0.11, rim=r * 0.15)+ return P, (r + 20, r + 20)+++def balance_wheel(r=62, seed=7):+ n = int(2 * r + 70)+ P = Photo(n, n, seed=seed, backdrop=(0.96, 0.86), lift=8)+ c = r + 22+ P.ring(c, c, r - 11, r, height=6, albedo=0.42, metal=0.35, gloss=0.5)+ P.rod((c - r + 6, c), (c + r - 6, c), 4.5, albedo=0.45, metal=0.4)+ for i in range(10): # timing screws round the rim+ a = np.deg2rad(i * 36 + 18)+ P.dome(c + np.cos(a) * (r + 3), c + np.sin(a) * (r + 3), 5, height=5, albedo=0.8, metal=0.8, gloss=0.5)+ P.spiral(c, c, 7, r * 0.52, turns=7, width=1.8, z=8, height=1.5, albedo=0.35, metal=0.7)+ P.disc(c, c, 7, z=6, height=6, albedo=0.7, metal=0.9)+ return P, (c, c)+++def mainspring(r=80, seed=9):+ n = int(2 * r + 70)+ P = Photo(n, n, seed=seed, backdrop=(0.96, 0.86), lift=8)+ c = r + 22+ P.spiral(c, c, 12, r, turns=4.5, width=6.5, height=3, albedo=0.45, metal=0.5, rot=30, flare=1.6)+ P.disc(c, c, 10, height=5, albedo=0.6, metal=0.8, hole=3)+ return P, (c, c)+++def screw_photo(length=96, r=10, seed=11):+ P = Photo(int(length + 70), int(4 * r + 60), seed=seed, backdrop=(0.96, 0.86), lift=8)+ P.screw(22, 2 * r + 20, length, r, rot=0)+ return P, (22 + length / 2, 2 * r + 20)+++def clip_photo(P, c, cell, margin=9, ink=INK, shadow=0.35):+ s = nc.print_photo(P, cell=cell, ink=ink, shadow=shadow)+ return s.cutout(margin, centre=c)+++def place(sheet, local, canvas, rot):+ """paste so that the sheet's local point `local` lands on `canvas`"""+ u, v = local[0] - sheet.w / 2, local[1] - sheet.h / 2+ t = np.deg2rad(rot)+ cx = canvas[0] - (u * np.cos(t) + v * np.sin(t)); cy = canvas[1] - (-u * np.sin(t) + v * np.cos(t))+ return nc.paste(sheet, cx, cy, rot)+++# ------------------------------------------------------------ kraft board+nc.board()+nc.stage('board')++# ------------------------------------------------------------ old newspaper, torn by hand+s = nc.newsprint(660, 1080, columns=3, size=10.5)+s.tear('rtb', depth=11, rim=8)+s.wrinkle(0.7)+nc.paste(s, 250, 548, rot=-2.2)+s = nc.newsprint(560, 430, columns=3, size=10, headline=1, picture=False)+s.tear('lt', depth=10, rim=7)+nc.paste(s, 1700, 935, rot=3.5)+nc.stage('newsprint')++# ------------------------------------------------------------ red paper disc+nc.disc(1104, 500, 318, RED)+nc.stage('red_disc')++# ------------------------------------------------------------ the clock, cut in two; the top half hinged open+P, C = alarm_clock()+cs = clip_photo(P, C, 6.2, margin=14, shadow=0.55)+ang = np.deg2rad(18)+d = np.array([np.cos(ang), -np.sin(ang)])+top, bottom = cs.split(np.array(C) - d * 420, np.array(C) + d * 420, kinks=4, jag=3)+CX, CY = 1066, 548 # dial centre on the board+place(bottom, C, (CX, CY), 0)+pivot_l = np.array(C) - d * 222 # hinge: where the cut leaves the case+pivot = (CX + pivot_l[0] - C[0], CY + pivot_l[1] - C[1])+place(top, pivot_l, pivot, 11)+nc.stage('clock')++# ------------------------------------------------------------ the parts that make it tick, flying out of the gap+for p0, p1, bend in [((1282, 440), (1470, 330), -40), ((1276, 428), (1650, 190), -90), ((1288, 456), (1790, 350), -60),+ ((1270, 478), (1610, 560), 50)]: # flight paths out of the gap+ p0 = np.array(p0, float); p1 = np.array(p1, float); mid = (p0 + p1) / 2+ nrm = np.array([-(p1 - p0)[1], (p1 - p0)[0]]) / np.hypot(*(p1 - p0))+ nc.pen([p0, mid + nrm * bend, p1], 2.0, INK, 0.7, dash=(9, 9))+parts = {}+p, c = screw_photo(); parts['screw1'] = place(clip_photo(p, c, 5.2, 10), c, (1346, 420), 28)+p, c = wheel(108, 36, 5, pinion=24, rot=4, seed=21); parts['gear1'] = place(clip_photo(p, c, 5.8), c, (1478, 318), 12)+p, c = wheel(70, 26, 4, pinion=16, rot=9, seed=22); parts['gear2'] = place(clip_photo(p, c, 5.4), c, (1660, 170), -8)+p, c = wheel(46, 16, 4, pinion=11, seed=23); parts['gear3'] = place(clip_photo(p, c, 5.0), c, (1392, 156), 0)+p, c = balance_wheel(); parts['balance'] = place(clip_photo(p, c, 5.0, ink=RED), c, (1802, 350), 0)+p, c = mainspring(); parts['spring'] = place(clip_photo(p, c, 5.6), c, (1618, 560), 0)+p, c = screw_photo(80, 9, seed=12); parts['screw2'] = place(clip_photo(p, c, 5.0, 10), c, (1826, 598), -62)+nc.stage('parts')++# ------------------------------------------------------------ typed labels and inked leader lines+nc.label('齿轮 GEAR', 1520, 470, 25, 'typewriter', rot=2)+nc.pen([(1560, 452), (1540, 425), (1515, 395)], 2.2, dot=3.5)+nc.label('摆轮 BALANCE', 1700, 470, 25, 'typewriter', rot=-3)+nc.pen([(1800, 448), (1806, 430), (1806, 418)], 2.2, dot=3.5)+nc.label('发条 MAINSPRING', 1430, 680, 25, 'typewriter', rot=-1.5)+nc.pen([(1600, 662), (1608, 640), (1612, 622)], 2.2, dot=3.5)+nc.label('螺丝 SCREW', 1268, 300, 22, 'typewriter', rot=4)+nc.pen([(1318, 318), (1328, 360), (1338, 398)], 2.2, dot=3.5)+nc.stage('labels')++# ------------------------------------------------------------ masthead+m = nc.sheet(660, 214, PAPER)+tm = m.text_mask('CURIOSITY WEEKLY · No.42 · 2026 AUTUMN', 330, 190, 22, 'grotesk', 'ms', spacing=3)+m.block(0, 162, 660, 214, RED, minus=tm)+m.text('好奇心周刊', 330, 138, 122, 'cjk_song', INK, 'ms')+m.tear('b', depth=6, rim=5)+m.cut_rect(1, 2)+nc.paste(m, 372, 128, rot=-1.6, lift=0.8)+nc.stage('masthead')++# ------------------------------------------------------------ ransom-note title+CL = nc.CLIPPINGS+title = nc.ransom('拆开看看', 54, 806, 116, rot=1.5, faces=['cjk_song', 'cjk_hei', 'cjk_kai', 'cjk_round'],+ styles=[CL[2], (PAPER, None, INK, ''), CL[3], CL[1]], seed=4)+last = title[-1][0]+q = nc.clipping('?', 124, 'cjk_song', MUSTARD, None, INK)+nc.paste(q, *last.pt(last.w + q.w * 0.5 - 4, last.h * 0.5 + 40), rot=-9)+nc.ransom('WHAT MAKES IT TICK', 70, 972, 54, rot=0.5, seed=8)+nc.stage('title')++# ------------------------------------------------------------ how it works, stamps, tape+nc.label('发条上劲 → 齿轮传动 → 摆轮定速 → 指针走动', 1432, 846, 21, 'typewriter', rot=-1.2)+nc.stamp(1210, 960, [('附零件图', 40), ('PARTS INSIDE', 22)], rot=7, colour=RED, face='slab', pressure=200)+nc.stamp(690, 262, [('10·01', 34)], shape='round', r=88, ring='好奇心周刊 · CURIOSITY WEEKLY ·', colour=INK,+ face='typewriter_bold', ring_face='cjk_hei', ring_size=18, alpha=0.82, rot=-12)+nc.tape(56, 44, 150, rot=-40)+nc.tape(600, 34, 150, rot=24)+nc.tape(1462, 730, 150, rot=-32, width=42)+nc.tape(848, 744, 110, rot=58, width=38)++nc.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/soft3d_rise.jpg b/examples/soft3d_rise.jpgnew file mode 100644index 0000000..486fe9dBinary files /dev/null and b/examples/soft3d_rise.jpg differdiff --git a/examples/soft3d_rise.py b/examples/soft3d_rise.pynew file mode 100644index 0000000..f803621--- /dev/null+++ b/examples/soft3d_rise.py@@ -0,0 +1,63 @@+"""Example (soft 3D): 浮出 · Rise — the word "rise" pushes up through a sea of 84,000 mint candy balls (about+20,000 in view). The balls it shoved aside are heaped around its feet, a few rode up on its shoulders, others+rolled off onto the sea; the dot of the i is a butter-yellow ball. Studio sky dome, a big soft key light,+a pink rim light, ambient occlusion in every crevice, soft shadows, subsurface tint and a shallow depth of field.+No image model.+python3 soft3d_rise.py [out.jpg] [--stages DIR] [--scale 0.5]+"""+import os, sys, time+import numpy as np+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from soft3d import Soft3D++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'soft3d_rise.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+scale = float(sys.argv[sys.argv.index('--scale') + 1]) if '--scale' in sys.argv else 1.0+t0 = time.time()++# the set is laid out facing the camera, then turned YAW degrees so the rows of the sea run diagonally+YAW = 30.0+c, n = np.cos(np.radians(YAW)), np.sin(np.radians(YAW))+def turn(x, z, ox=0.1, oz=0.5):+ """a point of the layout -> the turned set (rotation about the word's centre)"""+ return ox + (x - ox) * c + (z - oz) * n, oz - (x - ox) * n + (z - oz) * c+ex, ez = turn(-0.9, -6.4); tx, tz = turn(0.15, 0.4)+s = Soft3D(int(1920 * scale), int(1080 * scale), seed=11, eye=(ex, 2.05, ez), target=(tx, 0.74, tz), fov=29,+ record=stages is not None)+s.lens(focus=(0.1, 0.8, 0.5), aperture=0.0085) # focus on where the word will stand (the turn's pivot)++# ---- the sea: mint balls on a floor, a few pale accents mixed in+MINT = ['#c3ecdc', '#b7e6d2', '#cdf1e3', '#bde9dc']+s.floor('#b9e3d2')+s.ball_field(-30, 30, -14, 52, r=0.1, gap=0.016, colours=MINT + ['#f7f3ea', '#ffd6e2'],+ weights=[30, 30, 20, 20, 1.2, 0.8])+s.stage('ball_sea')++# ---- the word rises through it; the balls it pushed aside heap up around its feet+word = s.text('rise', at=(0.1, 0.0, 0.5), size=2.3, depth=0.46, colour='#ff6d8c', mat='candy', yaw=-7 + YAW,+ spacing=0.03, bob=[0.02, 0.06, 0.24, 0.2], roll=[3, -2, 2.5, -4], turn=[4, 0, -3, 2],+ dot='#ffd45e')+moved = s.part(heap=0.05, reach=0.5, pile=10, pile_top=0.3) # a low heap: s and e stay legible+s.stage('letters')++# ---- balls that rode up on the letters, and balls that rolled off+for x, z in [(-1.05, 0.52), (0.62, 0.45), (1.38, 0.5)]:+ s.drop(*turn(x, z), 0.1, MINT[0], roll=0)+for x, z, col in [(-1.9, -0.35, '#c7b6f6'), (1.9, 0.1, '#ffd45e'), (-0.4, -0.6, MINT[1]), (0.9, -0.9, '#ffb3c8'),+ (2.6, -0.8, '#c7b6f6'), (-2.7, 0.9, '#ffd45e'), (-3.4, -1.4, '#ffb3c8'), (3.3, 1.8, '#a9d3ff'),+ (-1.2, 2.6, '#c7b6f6'), (0.2, -1.8, '#a9d3ff'), (4.2, -1.2, '#ffd45e')]:+ s.drop(*turn(x, z), 0.1, col, roll=30)+s.stage('loose_balls')++# ---- light it+s.sky(top='#b6a3ee', horizon='#e9cbe9', strength=1.22, haze=42, haze_start=9)+s.stage('sky_light')+s.key(azimuth=-62, elevation=44, colour='#fff4ea', strength=1.62, size=12)+s.rim(azimuth=150, elevation=22, colour='#ffd0e0', strength=1.8)+s.softbox(azimuth=30, elevation=35, width=26, height=10, strength=0.72)+s.stage('key_and_rim')+s.film(bloom=0.25, vignette=0.2, grain=0.006)+print('balls pushed aside:', moved, ' loose balls:', len(s.br))++s.save(out, stages_dir=stages)+print('saved', out, f'{time.time() - t0:.1f}s')diff --git a/examples/synthwave_coastline.jpg b/examples/synthwave_coastline.jpgnew file mode 100644index 0000000..c49ec04Binary files /dev/null and b/examples/synthwave_coastline.jpg differdiff --git a/examples/synthwave_coastline.py b/examples/synthwave_coastline.pynew file mode 100644index 0000000..23ea5b2--- /dev/null+++ b/examples/synthwave_coastline.py@@ -0,0 +1,63 @@+"""Example (synthwave): 海岸线 1987 · Coastline 1987 — a home video of the last sunset of summer 1987, played back+off a worn tape: a striped sun sinking into the sea behind a low wireframe island, its reflection broken into+glowing bars on the water; a coast road with neon edges running to a small lit city at the vanishing point; a+magenta grid across the land, wireframe mountains beyond; palm silhouettes rimmed by the sunset; one car's+tail lights heading for the city; chrome COASTLINE with a neon-script "Last Sunset"; VCR on-screen display+(PLAY, date and time), chroma bleed, a tracking band and scanlines. No image model.+python3 synthwave_coastline.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from synthwave import Synthwave, MAGENTA, CYAN, PINK++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'synthwave_coastline.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++s = Synthwave(1920, 1080, seed=1987, horizon=610, vp_x=1060, focal=1100, eye=3.5, record=stages is not None)++# ---- dusk sky and stars+s.sky()+s.stars(n=1700, bright=16)+s.stage('sky')++# ---- the striped sun sinking into the sea+s.sun(560, 585, 255, bands=8, band_top=0.36)+s.stage('sun')++# ---- far shore: a low wireframe island in front of the sun, mountains beyond the land, the city at the road's end+s.mountains(-2700, -1250, 1650, 2300, 60, cell=(70, 120), level=0.7)+s.mountains(230, 1500, 900, 1750, 210, cell=(52, 85), taper=(True, False))+s.skyline(5, 175, 780, heights=(14, 60), widths=(10, 24), tall=(112, 100), windows=0.22)+s.stage('far')++# ---- the neon grid, the sea, the coast road+s.floor(MAGENTA, spacing=(2.4, 2.4), width=0.07)+s.stage('grid')+s.sea(coast=-9.0)+s.neon_line(-9.0, CYAN, width=0.16, level=1.0)+s.road(-7.0, -2.0)+s.stage('sea')++# ---- palms along the beach and the roadside, one car heading for the city+for X, Z, h, lean in ((-8.3, 29, 11.5, -0.07), (-8.4, 47, 10.5, 0.09), (-8.2, 82, 10.0, -0.05)):+ s.palm(X, Z, h, lean)+for X, Z, h, lean in ((-0.9, 104, 11.0, -0.04), (-0.9, 73, 10.0, 0.06),+ (-0.9, 52, 11.5, -0.03), (-0.9, 36, 10.5, 0.05)):+ s.palm(X, Z, h, lean)+s.car(-3.4, 31)+s.stage('palms')++# ---- lettering+s.caption('海岸线 1987 · 夏天的最后一次日落', 1450, 96, 27, CYAN, rules=(70, 20))+s.chrome_text('COASTLINE', 1450, 215, 150)+s.neon_script('Last Sunset', 1575, 352, 112, PINK, rot=7)+s.stage('title')++# ---- played back off tape+s.osd('PLAY ▶', 84, 70, px=6)+s.osd('PM 7:42', 1836, 960, px=5, anchor='rb')+s.osd('AUG.31 1987', 1836, 1010, px=5, anchor='rb')+s.vhs()+s.save(out, stages_dir=stages)+print('saved', out, f'{time.time() - t0:.1f}s')diff --git a/lib/aurora.py b/lib/aurora.pynew file mode 100644index 0000000..2c32633--- /dev/null+++ b/lib/aurora.py@@ -0,0 +1,669 @@+"""aurora — 弥散渐变 · 玻璃拟态: frosted-glass UI cards floating over a soft aurora / mesh gradient+(numpy + Pillow only).++Model: a bright screen of light, then real panes of frosted glass held a little above it, then the interface+printed on the glass.+ backdrop a mesh gradient: a pale base plus a few large coloured light pools (anisotropic gaussians) and+ aurora ribbons (soft bands along a spline). Every pixel is the weighted average of the pools'+ colours, mixed in OKLab so pink into blue passes through lilac instead of grey mud, on a domain-warped+ grid so the pools wander like dye in water instead of sitting as circles. It is computed at 1/4 size+ (it has no detail to lose), upsampled, then given a fine monochrome grain (+ a little chroma), which+ also kills 8-bit banding. `sparkles()` scatters a few tiny motes of light.+ orbs glossy pastel spheres floating over the backdrop: wrap-diffuse shading through an iridescent colour+ ramp (lit -> mid -> shade), a Fresnel rim that picks up the backdrop's colour, a tight specular spot+ plus a broad sheen, and a soft coloured contact shadow cast down onto the backdrop. They are sharp+ where they are free and melt into colour where a pane of glass passes in front of them -- which is+ what proves the glass is real.+ glass a slab of frosted acrylic `elevation` px above what is under it. What you see through it is the+ *actual* pixels below (backdrop, orbs, other cards and their text) gaussian-blurred (the frost+ scatters light; sigma ~ blur), saturated a little (backdrop-filter: saturate), then veiled with milky+ white that is thicker toward the light (upper left) and thinner away from it. At the rim the slab is+ bevelled: over the last `bevel` px the view is bent outward (the rim acts as a lens and pulls in what+ lies just outside the pane), each colour channel by a slightly different amount (dispersion: faint+ colour fringes), and the rim gathers a little extra light. A 1 px edge highlight is brightest on the+ edges that face the light, a fainter one on the far edges (light leaving the slab), a hairline of+ darkness just outside separates pale glass from a pale background. The pane casts a large soft+ shadow tinted with the colour of what it falls on, plus a tight contact shadow -- only outside the+ pane, like CSS box-shadow. A static frost grain sits on the glass. Panes stack: a front card blurs the+ cards behind it, text and all.+ interface drawn with signed-distance shapes (1 px analytic anti-aliasing, so every pill, ring and knob is+ crisp): gradient toggles with a white knob and its drop shadow, sliders, a progress ring with a conic+ gradient, round caps, a soft coloured glow and an end knob, pill bars, sparklines with a fading area+ fill, round checkmarks, small glass chips and pills (glass on glass), squircle app icons, a glossy sun+ behind a glass cloud, etched dividers. Text: SF (Latin, variable weight and optical size) and PingFang+ (CJK) on macOS, split by script run; Noto / YaHei / core fonts elsewhere.+Colour stops (gradients) are mixed in OKLab. Angles for rings are degrees clockwise from 12 o'clock (UI+convention). Everything is drawn in screen pixels; `glass()` returns a Card (x0, y0, x1, y1, w, h, r) to measure+from.++ from aurora import Aurora, INK, WARM, COOL+ a = Aurora(1920, 1080, seed=3)+ a.backdrop(blobs=[(300, 200, 500, 380, '#ffc3a0'), (1600, 300, 520, 420, '#c9b5ff'),+ (400, 900, 560, 380, '#9fd8ff')],+ ribbons=[([(-100, 800), (900, 520), (2000, 200)], 120, '#ffffff', 0.8)])+ a.orb(1200, 300, 120, ('#ffe0c8', '#ff9cc0', '#8d6bff'))+ c = a.glass(600, 240, 1300, 860, radius=40) # a frosted card -> Card+ a.text('晨间计划', c.x0 + 48, c.y0 + 100, 52, weight='semibold')+ a.toggle(c.x1 - 128, c.y0 + 160, on=True)+ a.slider(c.x0 + 48, c.x1 - 48, c.y0 + 260, 0.4)+ a.ring(c.x0 + 200, c.y0 + 450, 110, 20, 0.6, COOL)+ a.save('out.jpg')+"""+import glob+import os+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, spline, noise2d, smoothstep, shift, load_font++INK = '#1d2250' # deep indigo: text and hairlines on the glass+WARM = ('#ffae6e', '#ff6f93', '#b06cff') # sunrise: apricot -> pink -> violet+COOL = ('#56d0ff', '#6f8dff', '#9b6bff') # calm: sky -> periwinkle -> violet+MINT = ('#5fe3b8', '#2fbf9b')+WHITE = '#ffffff'+LIGHT = (-0.42, -0.91) # screen direction toward the key light (upper left)+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++# ---------------------------------------------------------------- colour: sRGB <-> OKLab+_M1 = np.array([[0.4122214708, 0.5363325363, 0.0514459929], [0.2119034982, 0.6806995451, 0.1073969566],+ [0.0883024619, 0.2817188376, 0.6299787005]], np.float32)+_M2 = np.array([[0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099],+ [0.0259040371, 0.7827717662, -0.8086757660]], np.float32)+_M1i, _M2i = np.linalg.inv(_M1).astype(np.float32), np.linalg.inv(_M2).astype(np.float32)+++def _lin(c):+ c = np.asarray(c, np.float32)+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)+++def _srgb(c):+ c = np.clip(c, 0, 1)+ return np.where(c <= 0.0031308, 12.92 * c, 1.055 * np.power(c, 1 / 2.4) - 0.055)+++def to_lab(rgb):+ """sRGB (..., 3) in 0..1 -> OKLab"""+ return np.cbrt(_lin(rgb) @ _M1.T) @ _M2.T+++def from_lab(lab):+ """OKLab (..., 3) -> sRGB in 0..1"""+ return _srgb((np.asarray(lab, np.float32) @ _M2i.T) ** 3 @ _M1i.T).astype(np.float32)+++def ramp(t, stops):+ """colours along a gradient: t (any shape) in 0..1, stops = colours (hex or rgb) -> t.shape + (3,), OKLab mix"""+ L = np.stack([to_lab(_c(s)) for s in stops])+ t = np.clip(np.asarray(t, np.float32), 0, 1) * (len(stops) - 1)+ i = np.minimum(t.astype(int), len(stops) - 2)+ f = (t - i)[..., None]+ return from_lab(L[i] * (1 - f) + L[i + 1] * f)+++def mix(a, b, t):+ """one colour between a and b (OKLab), t in 0..1"""+ return ramp(np.float32(t), (a, b))+++# ---------------------------------------------------------------- signed distances (negative inside)+def sdf_rrect(u, v, hw, hh, r):+ qx, qy = np.abs(u) - (hw - r), np.abs(v) - (hh - r)+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r+++def sdf_segment(X, Y, a, b):+ ab = np.subtract(b, a, dtype=np.float32); l2 = float(ab @ ab) + 1e-9+ t = np.clip(((X - a[0]) * ab[0] + (Y - a[1]) * ab[1]) / l2, 0, 1)+ return np.hypot(X - (a[0] + t * ab[0]), Y - (a[1] + t * ab[1])), t+++def smin(a, b, k):+ """smooth union of two distance fields (k px of fillet)"""+ h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1)+ return b * (1 - h) + a * h - k * h * (1 - h)+++def _cov(d):+ return np.clip(0.5 - d, 0, 1)+++def _bilinear(img, x, y):+ H, W = img.shape+ x = np.clip(x, 0, W - 1.001); y = np.clip(y, 0, H - 1.001)+ x0 = x.astype(np.int32); y0 = y.astype(np.int32)+ fx, fy = x - x0, y - y0+ a, b = img[y0, x0], img[y0, x0 + 1]+ c, d = img[y0 + 1, x0], img[y0 + 1, x0 + 1]+ return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy+++# ---------------------------------------------------------------- fonts: SF / PingFang on macOS, fallbacks elsewhere+_WEIGHT = {'light': 300, 'regular': 400, 'medium': 510, 'semibold': 600, 'bold': 700}+_CJK_FACES = [ # (glob, {weight: face index})+ ('/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/PingFang.ttc',+ {'light': 15, 'regular': 3, 'medium': 7, 'semibold': 11, 'bold': 11}),+ ('/System/Library/Fonts/Hiragino Sans GB.ttc', {'light': 0, 'regular': 0, 'medium': 2, 'semibold': 2, 'bold': 2}),+ ('/usr/share/fonts/**/NotoSansCJK*-{W}.tt[cf]', None),+ ('C:/Windows/Fonts/msyh{W}.ttc', None),+]+_FONTS = {}+++def _find(pat):+ fs = glob.glob(pat, recursive=True)+ return fs[0] if fs else None+++def _cjk_font(weight, size):+ env = os.environ.get('INKPAINT_FONT_CJK_SANS')+ if env and os.path.exists(env): return ImageFont.truetype(env, size)+ for pat, faces in _CJK_FACES:+ if faces is None:+ if 'Noto' in pat:+ w = {'light': 'Light', 'regular': 'Regular', 'medium': 'Medium', 'semibold': 'Bold', 'bold': 'Bold'}[weight]+ else:+ w = {'light': 'l', 'regular': '', 'medium': '', 'semibold': 'bd', 'bold': 'bd'}[weight]+ p = _find(pat.replace('{W}', w)) or _find(pat.replace('{W}', 'Regular' if 'Noto' in pat else ''))+ if p:+ try: return ImageFont.truetype(p, size)+ except OSError: pass+ continue+ p = _find(pat)+ if p:+ try: return ImageFont.truetype(p, size, index=faces[weight])+ except OSError: pass+ return load_font('cjk_sans', size)+++def _latin_font(weight, size):+ env = os.environ.get('INKPAINT_FONT_SANS')+ if not (env and os.path.exists(env)) and os.path.exists('/System/Library/Fonts/SFNS.ttf'):+ try:+ f = ImageFont.truetype('/System/Library/Fonts/SFNS.ttf', size)+ f.set_variation_by_axes([100, float(np.clip(size * 0.62, 17, 96)), 400, _WEIGHT[weight]])+ return f+ except (OSError, ValueError):+ pass+ if os.path.exists('/System/Library/Fonts/HelveticaNeue.ttc') and not env:+ idx = {'light': 7, 'regular': 0, 'medium': 10, 'semibold': 10, 'bold': 1}[weight]+ return ImageFont.truetype('/System/Library/Fonts/HelveticaNeue.ttc', size, index=idx)+ return load_font('sans_bold' if weight in ('semibold', 'bold') else 'sans', size)+++def _font(kind, weight, size):+ key = (kind, weight, int(size))+ if key not in _FONTS:+ _FONTS[key] = (_cjk_font if kind == 'cjk' else _latin_font)(weight, int(size))+ return _FONTS[key]+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++class Card:+ """a pane of glass (or any rounded rectangle) in screen pixels"""++ def __init__(self, x0, y0, x1, y1, r):+ self.x0, self.y0, self.x1, self.y1, self.r = x0, y0, x1, y1, r+ self.w, self.h = x1 - x0, y1 - y0+ self.cx, self.cy = (x0 + x1) / 2, (y0 + y1) / 2+++class Aurora:+ def __init__(self, W=1920, H=1080, seed=0, light=LIGHT):+ self.W, self.H = W, H+ self.rng = np.random.default_rng(seed)+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)+ l = np.asarray(light, np.float32); self.L = l / np.linalg.norm(l)+ self.img = np.ones((H, W, 3), np.float32) * 0.96+ g = blur(self.rng.standard_normal((H, W)).astype(np.float32), 0.55)+ self.frost = (g / (g.std() + 1e-6)).astype(np.float32) # static frost grain for every pane+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ low-level+ def _box(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))+ if x1 <= x0 or y1 <= y0: return None+ return (slice(y0, y1), slice(x0, x1))++ def _blend(self, sl, a, col):+ a = np.clip(a, 0, 1)[..., None]+ col = col if isinstance(col, np.ndarray) and col.ndim == 3 else _c(col)+ self.img[sl] = self.img[sl] * (1 - a) + col * a++ def _mul(self, sl, a, col):+ self.img[sl] *= 1 - np.clip(a, 0, 1)[..., None] * (1 - (col if isinstance(col, np.ndarray) else _c(col)))++ def _paint(self, sl, d, fill, alpha=1.0, grad=None, angle=90.0, box=None):+ """fill the shape with signed distance d (over slice sl): a colour, or `grad` stops along `angle`+ (degrees, 90 = top -> bottom, 0 = left -> right) across `box` (x0, y0, x1, y1)"""+ cov = _cov(d) * alpha+ if grad is not None:+ X, Y = self.XX[sl], self.YY[sl]+ bx0, by0, bx1, by1 = box+ a = np.deg2rad(angle); ux, uy = np.cos(a), np.sin(a)+ pc = np.array([[bx0, by0], [bx1, by0], [bx0, by1], [bx1, by1]], np.float32) @ [ux, uy]+ t = ((X * ux + Y * uy) - pc.min()) / (pc.max() - pc.min() + 1e-6)+ self._blend(sl, cov, ramp(t, grad))+ else:+ self._blend(sl, cov, fill)+ return cov++ def _drop(self, sl, cov, dx=0.0, dy=3.0, soft=4.0, strength=0.25, colour='#2a2466'):+ """soft drop shadow of coverage `cov` (cropped to sl), cast down and away from the light"""+ sh = blur(shift(cov, dx, dy), soft) * strength+ self._mul(sl, sh * (1 - cov), colour)++ # ------------------------------------------------------------ backdrop+ def backdrop(self, base='#f7f3fb', blobs=(), ribbons=(), warp=120.0, warp_scale=560.0, base_weight=0.32,+ grain=0.022, seed=None):+ """the mesh gradient. blobs: [(x, y, rx, ry, colour[, strength])]; ribbons: [(pts, width, colour[, strength])].+ warp: how far (px) the pools wander; grain: film grain amplitude (0.015-0.03)"""+ s = self._seed() if seed is None else seed+ k = 4+ h, w = self.H // k + 1, self.W // k + 1+ Y, X = np.mgrid[0:h, 0:w].astype(np.float32) * k+ if warp:+ X = X + (noise2d(h, w, warp_scale / k, 3, s) - 0.5) * 2 * warp+ Y = Y + (noise2d(h, w, warp_scale / k, 3, s + 1) - 0.5) * 2 * warp+ num = np.zeros((h, w, 3), np.float32) + to_lab(_c(base)) * base_weight+ den = np.full((h, w), base_weight, np.float32)+ for b in blobs:+ x, y, rx, ry, col = b[:5]+ st = b[5] if len(b) > 5 else 1.0+ wt = st * np.exp(-0.5 * (((X - x) / rx) ** 2 + ((Y - y) / ry) ** 2) * 2.2)+ num += wt[..., None] * to_lab(_c(col)); den += wt+ for rb in ribbons:+ pts, width, col = rb[:3]+ st = rb[3] if len(rb) > 3 else 1.0+ P = spline(pts, 24)+ dist = np.full((h, w), 1e9, np.float32)+ for i in range(len(P) - 1):+ dist = np.minimum(dist, sdf_segment(X, Y, P[i], P[i + 1])[0])+ wt = st * np.exp(-0.5 * (dist / width) ** 2 * 2.0)+ num += wt[..., None] * to_lab(_c(col)); den += wt+ rgb = from_lab(num / den[..., None])+ up = np.stack([np.asarray(Image.fromarray(rgb[..., c]).resize((w * k, h * k), Image.BICUBIC))[:self.H, :self.W]+ for c in range(3)], -1)+ g = blur(self.rng.standard_normal((self.H, self.W)).astype(np.float32), 0.5)+ g /= g.std() + 1e-6+ ch = blur(self.rng.standard_normal((self.H, self.W, 1)).astype(np.float32)[..., 0], 0.8)+ ch = ch / (ch.std() + 1e-6)+ self.img = np.clip(up + grain * g[..., None] + grain * 0.35 * ch[..., None] * np.array([1, -0.4, -0.6], np.float32),+ 0, 1).astype(np.float32)++ def sparkles(self, n=40, box=None, size=(0.8, 2.4), alpha=(0.25, 0.7), seed=None):+ """tiny motes of light drifting in the aurora (soft white dots)"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ x0, y0, x1, y1 = box or (0, 0, self.W, self.H)+ for _ in range(n):+ x, y = r.uniform(x0, x1), r.uniform(y0, y1)+ rad = r.uniform(*size); a = r.uniform(*alpha)+ sl = self._box(x - rad * 4, y - rad * 4, x + rad * 4, y + rad * 4)+ if sl is None: continue+ d = np.hypot(self.XX[sl] - x, self.YY[sl] - y)+ self._blend(sl, a * np.exp(-0.5 * (d / rad) ** 2), WHITE)++ # ------------------------------------------------------------ orbs+ def orb(self, cx, cy, r, stops=('#ffe2cc', '#ff9ec4', '#8d6bff'), spec=0.85, shadow=0.3, rim=0.55):+ """a glossy pastel sphere floating over the backdrop: stops run lit -> mid -> shade"""+ # contact shadow on the backdrop, cast down and to the right (away from the light)+ ox, oy = -self.L[0] * r * 0.28, -self.L[1] * r * 0.34+ sl = self._box(cx - r * 1.8 + ox, cy - r * 1.6 + oy, cx + r * 1.8 + ox, cy + r * 2.0 + oy)+ X, Y = self.XX[sl], self.YY[sl]+ dsh = np.hypot((X - cx - ox) / 0.95, (Y - cy - oy) / 0.9) - r+ env = self.img[sl].mean((0, 1)) # what the rim reflects+ shade_col = np.clip(env * 0.45 + hexc('#3b2d8a') * 0.3, 0, 1)+ self._mul(sl, blur(_cov(dsh), r * 0.32) * shadow, shade_col)+ sl = self._box(cx - r - 2, cy - r - 2, cx + r + 2, cy + r + 2)+ X, Y = self.XX[sl], self.YY[sl]+ nx, ny = (X - cx) / r, (Y - cy) / r+ rr = nx * nx + ny * ny+ nz = np.sqrt(np.clip(1 - rr, 0, 1))+ Lv = np.array([self.L[0] * 0.62, self.L[1] * 0.62, 0.78], np.float32); Lv /= np.linalg.norm(Lv)+ ndl = nx * Lv[0] + ny * Lv[1] + nz * Lv[2]+ wrap = np.clip((ndl + 0.45) / 1.45, 0, 1)+ col = ramp(1 - wrap ** 0.9, stops)+ fres = (1 - nz) ** 2.6+ col = col + (np.clip(env * 1.05, 0, 1) - col) * (fres * rim)[..., None] # rim picks up the backdrop+ Hv = Lv + np.array([0, 0, 1], np.float32); Hv /= np.linalg.norm(Hv)+ ndh = np.clip(nx * Hv[0] + ny * Hv[1] + nz * Hv[2], 0, 1)+ sp = spec * (ndh ** 70 * 0.9 + ndh ** 9 * 0.16)+ col = col + (1 - col) * sp[..., None]+ d = (np.sqrt(rr) - 1) * r+ self._blend(sl, _cov(d), np.clip(col, 0, 1))++ # ------------------------------------------------------------ glass+ def _glass(self, sl, d, bbox, blur_px=26.0, tint=0.24, sat=1.5, shadow=0.26, elevation=26.0, bevel=14.0,+ rim=1.0, frost=0.012, sheen=0.5, tint_colour=WHITE, disperse=1.0, shade='#3a2f86'):+ X, Y = self.XX[sl], self.YY[sl]+ reg = self.img[sl]+ cov = _cov(d)+ B = np.stack([blur(reg[..., k], blur_px) for k in range(3)], -1) if blur_px > 0 else reg.copy()+ lum = (B @ np.array([0.2126, 0.7152, 0.0722], np.float32))[..., None]+ B = np.clip(lum + (B - lum) * sat, 0, 1)+ # the bevelled rim bends the view outward, a little more for blue than red+ gy, gx = np.gradient(d)+ gn = np.hypot(gx, gy) + 1e-6; nx, ny = gx / gn, gy / gn+ t = np.clip(1 + d / bevel, 0, 1) * (d < 1)+ m = bevel * 1.1 * t ** 2+ lx, ly = X - sl[1].start, Y - sl[0].start+ G = np.empty_like(B)+ for k, f in enumerate((1 - 0.3 * disperse, 1.0, 1 + 0.3 * disperse)):+ G[..., k] = _bilinear(B[..., k], lx + nx * m * f, ly + ny * m * f)+ # milky veil, thicker toward the light; a broad sheen; light gathered in the bevel; frost grain+ bx0, by0, bx1, by1 = bbox+ u = np.clip(((X - bx0) / max(bx1 - bx0, 1) + (Y - by0) / max(by1 - by0, 1)) / 2, 0, 1)+ a = np.clip(tint * (1.3 - 0.6 * u), 0, 1)[..., None]+ G = G * (1 - a) + _c(tint_colour) * a+ G = G + (1 - G) * (sheen * 0.16 * smoothstep(0.62, 0.0, u) + 0.12 * rim * t ** 3)[..., None]+ G = G + frost * self.frost[sl][..., None]+ facing = nx * self.L[0] + ny * self.L[1]+ line = np.exp(-(((d + 1.1) / 0.85) ** 2))+ ra = rim * line * (0.28 + 0.62 * np.clip(facing, 0, 1) + 0.3 * np.clip(-facing, 0, 1))+ G = G * (1 - ra[..., None]) + ra[..., None]+ # shadow outside the pane (large, tinted by what it falls on) + tight contact shadow + outer hairline+ if shadow > 0:+ ox, oy = -self.L[0] * elevation * 0.35, elevation * 0.55+ S = blur(shift(cov, ox, oy), elevation * 0.95) * shadow + blur(shift(cov, ox * 0.2, elevation * 0.12),+ max(1.0, elevation * 0.18)) * shadow * 0.35+ sc = np.clip(B * 0.5 + _c(shade) * 0.35, 0, 1)+ reg = reg * (1 - (S * (1 - cov))[..., None] * (1 - sc))+ hl = np.exp(-(((d - 0.9) / 0.7) ** 2)) * 0.075 * rim+ reg = reg * (1 - hl[..., None] * (1 - hexc(INK)))+ c3 = cov[..., None]+ self.img[sl] = np.clip(reg * (1 - c3) + G * c3, 0, 1)++ def glass(self, x0, y0, x1, y1, radius=36, blur=26.0, tint=0.24, sat=1.5, shadow=0.26, elevation=26.0,+ bevel=14.0, rim=1.0, frost=0.012, sheen=0.5, tint_colour=WHITE, disperse=1.0):+ """a frosted glass card; everything already on the canvas under it is blurred through it -> Card"""+ pad = int(max(3 * blur, 3.2 * elevation) + bevel + 8)+ sl = self._box(x0 - pad, y0 - pad, x1 + pad, y1 + pad)+ X, Y = self.XX[sl], self.YY[sl]+ d = sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, radius)+ self._glass(sl, d, (x0, y0, x1, y1), blur, tint, sat, shadow, elevation, min(bevel, radius), rim, frost,+ sheen, tint_colour, disperse)+ return Card(x0, y0, x1, y1, radius)++ def pill(self, x0, y0, x1, y1, blur=8.0, tint=0.42, shadow=0.1, elevation=8.0, rim=0.9, **kw):+ """a small glass pill / chip (glass on glass): a fully rounded glass() with a light touch"""+ return self.glass(x0, y0, x1, y1, radius=(y1 - y0) / 2, blur=blur, tint=tint, shadow=shadow,+ elevation=elevation, bevel=min(8, (y1 - y0) / 3), rim=rim, **kw)++ # ------------------------------------------------------------ shapes+ def rrect(self, x0, y0, x1, y1, r, fill=WHITE, alpha=1.0, grad=None, angle=0.0, shadow=0.0):+ sl = self._box(x0 - 20, y0 - 20, x1 + 20, y1 + 24)+ X, Y = self.XX[sl], self.YY[sl]+ d = sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, min(r, (x1 - x0) / 2, (y1 - y0) / 2))+ if shadow: self._drop(sl, _cov(d), 0, 3, 5, shadow)+ return self._paint(sl, d, fill, alpha, grad, angle, (x0, y0, x1, y1))++ def circle(self, cx, cy, r, fill=WHITE, alpha=1.0, grad=None, angle=90.0, shadow=0.0, ring=0.0):+ """a disc (or, with ring=w, a circular stroke w px wide)"""+ sl = self._box(cx - r - 16, cy - r - 16, cx + r + 16, cy + r + 20)+ X, Y = self.XX[sl], self.YY[sl]+ d = np.hypot(X - cx, Y - cy) - r+ if ring: d = np.abs(d + ring / 2) - ring / 2+ if shadow: self._drop(sl, _cov(d), 0, max(2, r * 0.12), max(2, r * 0.22), shadow)+ return self._paint(sl, d, fill, alpha, grad, angle, (cx - r, cy - r, cx + r, cy + r))++ def line(self, pts, width=3.0, fill=INK, alpha=1.0, grad=None, angle=0.0, smooth=False):+ """polyline with round caps and joins (spline-smoothed if smooth=True)"""+ P = np.asarray(pts, np.float32)+ if smooth and len(P) > 2: P = spline(P, 12)+ pad = width + 4+ sl = self._box(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)+ X, Y = self.XX[sl], self.YY[sl]+ dist = np.full(X.shape, 1e9, np.float32)+ for i in range(len(P) - 1):+ dist = np.minimum(dist, sdf_segment(X, Y, P[i], P[i + 1])[0])+ return self._paint(sl, dist - width / 2, fill, alpha, grad, angle,+ (P[:, 0].min(), P[:, 1].min(), P[:, 0].max(), P[:, 1].max()))++ def divider(self, x0, x1, y, alpha=1.0):+ """an etched hairline: a faint dark line with a light line under it"""+ self.rrect(x0, y - 0.6, x1, y + 0.6, 0.6, INK, 0.08 * alpha)+ self.rrect(x0, y + 0.8, x1, y + 2.0, 0.6, WHITE, 0.55 * alpha)++ # ------------------------------------------------------------ text+ def _runs(self, s):+ runs = []+ for ch in s:+ k = _is_cjk(ch)+ if runs and runs[-1][1] == k: runs[-1][0] += ch+ else: runs.append([ch, k])+ return runs++ def _glyphs(self, s, size, weight, spacing):+ """-> [(font, piece, x offset)], total advance"""+ out, x = [], 0.0+ for piece, k in self._runs(s):+ f = _font('cjk' if k else 'latin', weight, size)+ if spacing:+ for ch in piece:+ out.append((f, ch, x)); x += f.getlength(ch) + spacing+ else:+ out.append((f, piece, x)); x += f.getlength(piece)+ return out, (x - spacing if spacing else x)++ def text_width(self, s, size, weight='regular', spacing=0.0):+ return self._glyphs(s, size, weight, spacing)[1]++ def text(self, s, x, y, size, fill=INK, weight='regular', anchor='ls', alpha=1.0, spacing=0.0, grad=None,+ angle=0.0):+ """text in SF / PingFang (script runs split automatically). anchor: [l m r] + [s baseline, m middle,+ t cap top, b bottom]; spacing: extra px between letters; grad: gradient stops across the text -> advance"""+ size = int(round(size))+ gl, tw = self._glyphs(s, size, weight, spacing)+ x0 = x - tw * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ base = y + {'s': 0.0, 'm': 0.36 * size, 't': 0.74 * size, 'b': -0.24 * size}[anchor[1]]+ bx0, by0 = int(np.floor(x0)) - 4, int(np.floor(base - size * 1.2))+ bw, bh = int(tw) + 10, int(size * 1.6) + 6+ im = Image.new('L', (bw, bh), 0)+ dr = ImageDraw.Draw(im)+ for f, piece, off in gl:+ dr.text((x0 - bx0 + off, base - by0), piece, font=f, fill=255, anchor='ls')+ m = np.asarray(im, np.float32) / 255+ sl = self._box(bx0, by0, bx0 + bw, by0 + bh)+ if sl is None: return tw+ m = m[sl[0].start - by0:sl[0].stop - by0, sl[1].start - bx0:sl[1].stop - bx0]+ if grad is not None:+ X, Y = self.XX[sl], self.YY[sl]+ a = np.deg2rad(angle)+ t = ((X - x0) * np.cos(a) + (Y - (base - size * 0.74)) * np.sin(a)) / max(tw * abs(np.cos(a)) + size * 0.74 * abs(np.sin(a)), 1)+ self._blend(sl, m * alpha, ramp(t, grad))+ else:+ self._blend(sl, m * alpha, fill)+ return tw++ # ------------------------------------------------------------ controls+ def toggle(self, x, y, on=True, w=80, h=46, grad=COOL):+ """an iOS-style switch, top-left at (x, y): gradient track when on, recessed glass when off, white knob"""+ r = h / 2+ sl = self._box(x - 10, y - 10, x + w + 10, y + h + 14)+ X, Y = self.XX[sl], self.YY[sl]+ d = sdf_rrect(X - (x + w / 2), Y - (y + h / 2), w / 2, h / 2, r)+ if on:+ self._paint(sl, d, None, 1.0, grad, 0, (x, y, x + w, y + h))+ inner = np.clip(-d / 3, 0, 1) * np.exp(-np.clip(Y - y, 0, None) / 5) * _cov(d)+ self._mul(sl, inner * 0.18, INK) # the track is a groove: top edge in shade+ self._blend(sl, _cov(d) * np.exp(-((Y - (y + h - 3)) / 3) ** 2) * 0.25, WHITE)+ else:+ self._paint(sl, d, WHITE, 0.4)+ self._mul(sl, _cov(d) * 0.08, INK)+ inner = _cov(d) * np.exp(-np.clip(Y - y, 0, None) / 6) * np.clip(-d / 2, 0, 1)+ self._mul(sl, inner * 0.14, INK)+ self._blend(sl, np.exp(-(((d + 0.6) / 0.7) ** 2)) * 0.12, INK)+ kx = x + w - r if on else x + r+ self.knob(kx, y + h / 2, r - 4)++ def knob(self, cx, cy, r, shadow=0.3):+ """a white knob with a soft drop shadow and a faint top-lit gradient"""+ self.circle(cx, cy, r, grad=('#ffffff', '#f1f1f8'), angle=90, shadow=shadow)+ self.circle(cx, cy, r, INK, 0.06, ring=1.0)++ def slider(self, x0, x1, y, value, grad=COOL, h=8, knob=13, glow=0.25):+ """a slider track centred on y with a gradient fill up to `value` and a white knob"""+ xv = x0 + (x1 - x0) * float(np.clip(value, 0, 1))+ self.rrect(x0, y - h / 2, x1, y + h / 2, h / 2, WHITE, 0.5)+ self.rrect(x0, y - h / 2, x1, y + h / 2, h / 2, INK, 0.06)+ if glow:+ sl = self._box(x0 - 30, y - 30, xv + 30, y + 34)+ X, Y = self.XX[sl], self.YY[sl]+ d = sdf_rrect(X - (x0 + xv) / 2, Y - y, (xv - x0) / 2 + h / 2, h / 2, h / 2)+ g = blur(_cov(d), 7) * glow+ self._blend(sl, g, ramp(np.clip((X - x0) / max(xv - x0, 1), 0, 1), grad))+ self.rrect(x0, y - h / 2, xv + h / 2, y + h / 2, h / 2, grad=grad, angle=0)+ self.knob(xv, y, knob)++ def ring(self, cx, cy, r, width, frac, grad=COOL, track=0.55, glow=0.35, knob=True):+ """a progress ring: faint track, conic gradient arc from 12 o'clock clockwise with round caps, a soft+ coloured glow and a white knob at the end"""+ a1 = 360.0 * float(np.clip(frac, 0.002, 0.999))+ pad = width + 40+ sl = self._box(cx - r - pad, cy - r - pad, cx + r + pad, cy + r + pad)+ X, Y = self.XX[sl], self.YY[sl]+ dx, dy = X - cx, Y - cy+ rho = np.hypot(dx, dy)+ th = np.degrees(np.arctan2(dx, -dy)) % 360+ band = np.abs(rho - r) - width / 2+ if track:+ self._paint(sl, band, WHITE, track)+ self._mul(sl, _cov(band) * 0.035, INK)+ e = np.radians(a1)+ c0 = (cx, cy - r); c1 = (cx + r * np.sin(e), cy - r * np.cos(e))+ dcap = np.minimum(np.hypot(X - c0[0], Y - c0[1]), np.hypot(X - c1[0], Y - c1[1])) - width / 2+ d = np.where(th <= a1, band, 1e9)+ d = np.minimum(d, dcap)+ t = np.where(th <= a1, th / a1, np.where(360 - th < th - a1, 0.0, 1.0))+ col = ramp(t, grad)+ if glow:+ g = blur(_cov(d), width * 0.7) * glow+ self._blend(sl, g * (1 - _cov(d)), col)+ self._blend(sl, _cov(d), col)+ hi = _cov(d) * np.exp(-(((rho - (r - width * 0.18)) / (width * 0.22)) ** 2)) * 0.18 # a faint tube highlight+ self._blend(sl, hi, WHITE)+ if knob:+ self.knob(c1[0], c1[1], width * 0.34, shadow=0.25)++ def check(self, cx, cy, r, state='done', grad=WARM, frac=0.5):+ """a round checkmark: done (gradient disc + white tick), now (ring with a small progress arc), todo (ring)"""+ if state == 'done':+ self.circle(cx, cy, r, grad=grad, angle=45, shadow=0.18)+ self.line([(cx - r * 0.42, cy + r * 0.02), (cx - r * 0.1, cy + r * 0.34), (cx + r * 0.45, cy - r * 0.3)],+ r * 0.2, WHITE)+ elif state == 'now':+ self.circle(cx, cy, r, WHITE, 0.75, shadow=0.12)+ self.ring(cx, cy, r * 0.6, r * 0.26, frac, grad, track=0.0, glow=0.0, knob=False)+ else:+ self.circle(cx, cy, r, WHITE, 0.35)+ self.circle(cx, cy, r, INK, 0.28, ring=2.0)++ def bars(self, x0, y0, x1, y1, values, vmax=None, labels=(), highlight=None, grad=COOL, label_size=19,+ bar=0.5, slots=0.1, fade=()):+ """a pill bar chart in the box (labels sit below y1). highlight: index drawn with the gradient;+ slots: alpha of the empty full-height slot behind each bar; fade: indices left as empty slots"""+ n = len(values); vmax = vmax or max(values)+ step = (x1 - x0) / n; bw = step * bar+ for i, v in enumerate(values):+ cx = x0 + step * (i + 0.5)+ top = y1 - max(bw, (y1 - y0) * v / vmax)+ if slots: self.rrect(cx - bw / 2, y0, cx + bw / 2, y1, bw / 2, WHITE, slots) # the empty slot+ if i == highlight:+ self.rrect(cx - bw / 2, top, cx + bw / 2, y1, bw / 2, grad=grad, angle=-90, shadow=0.12)+ elif i in fade:+ pass+ else:+ self.rrect(cx - bw / 2, top, cx + bw / 2, y1, bw / 2, WHITE, 0.78, shadow=0.06)+ if i < len(labels):+ self.text(labels[i], cx, y1 + label_size * 1.6, label_size, INK, 'semibold' if i == highlight else 'regular',+ 'ms', alpha=0.85 if i == highlight else 0.5)++ def spark(self, x0, y0, x1, y1, values, grad=WARM, width=3.0, fill=0.32, dots=(), vmin=None, vmax=None):+ """a smooth sparkline across the box with a gradient line and an area fill fading downward -> points"""+ v = np.asarray(values, np.float32)+ lo = v.min() if vmin is None else vmin; hi = v.max() if vmax is None else vmax+ xs = np.linspace(x0, x1, len(v)); ys = y1 - (v - lo) / max(hi - lo, 1e-6) * (y1 - y0)+ P = spline(np.stack([xs, ys], 1), 16)+ if fill:+ sl = self._box(x0, y0 - 4, x1 + 1, y1 + 30)+ X, Y = self.XX[sl], self.YY[sl]+ top = np.interp(X[0], P[:, 0], P[:, 1])[None, :]+ a = np.clip(Y - top + 0.5, 0, 1) * np.clip(1 - (Y - top) / (y1 + 26 - top + 1e-3), 0, 1) ** 1.6 * fill+ a *= smoothstep(x0 - 1, x0 + 22, X) * smoothstep(x1 + 1, x1 - 22, X) # fade out at both ends+ self._blend(sl, a, ramp((X - x0) / max(x1 - x0, 1), grad))+ self.line(P, width, grad=grad, angle=0)+ pts = list(zip(xs, ys))+ for i in dots:+ self.circle(pts[i][0], pts[i][1], width * 2.2, WHITE, shadow=0.2)+ self.circle(pts[i][0], pts[i][1], width * 1.2, grad=grad)+ return pts++ # ------------------------------------------------------------ icons+ def sun(self, cx, cy, r, stops=('#fff3b8', '#ffc85a', '#ff8a3d'), glow=0.5):+ """a glossy sun: warm halo, shaded orb, specular spot"""+ sl = self._box(cx - r * 3, cy - r * 3, cx + r * 3, cy + r * 3)+ d = np.hypot(self.XX[sl] - cx, self.YY[sl] - cy)+ self._blend(sl, glow * np.exp(-0.5 * (d / (r * 1.25)) ** 2), hexc('#ffd27a'))+ self.orb(cx, cy, r, stops, spec=0.6, shadow=0.0, rim=0.2)++ def cloud(self, cx, cy, w, blur=7.0, tint=0.5, shadow=0.16):+ """a frosted glass cloud (the sun behind it shows through, blurred)"""+ pad = int(w * 0.6 + 3 * blur + 20)+ sl = self._box(cx - pad, cy - pad, cx + pad, cy + pad)+ X, Y = self.XX[sl], self.YY[sl]+ base = sdf_segment(X, Y, (cx - 0.3 * w, cy + 0.12 * w), (cx + 0.3 * w, cy + 0.12 * w))[0] - 0.17 * w+ c1 = np.hypot(X - (cx - 0.1 * w), Y - (cy - 0.04 * w)) - 0.24 * w+ c2 = np.hypot(X - (cx + 0.17 * w), Y - (cy + 0.03 * w)) - 0.17 * w+ d = smin(smin(base, c1, 0.06 * w), c2, 0.06 * w)+ self._glass(sl, d, (cx - 0.47 * w, cy - 0.28 * w, cx + 0.47 * w, cy + 0.29 * w), blur, tint, 1.2, shadow,+ w * 0.12, w * 0.07, 1.0, 0.01, 0.6, WHITE, 0.6)++ def app_icon(self, x, y, size, grad=WARM, glyph='', glyph_size=None, weight='semibold'):+ """a squircle app icon at (x, y) top-left: gradient, top gloss, drop shadow, white glyph"""+ sl = self._box(x - 12, y - 12, x + size + 12, y + size + 16)+ X, Y = self.XX[sl], self.YY[sl]+ u, v = (X - (x + size / 2)) / (size / 2), (Y - (y + size / 2)) / (size / 2)+ f = (np.abs(u) ** 5 + np.abs(v) ** 5) ** 0.2 # superellipse+ d = (f - 1) * size / 2 / np.maximum(1, 0.8 + 0.2 * f)+ self._drop(sl, _cov(d), 0, size * 0.06, size * 0.1, 0.25)+ self._paint(sl, d, None, 1.0, grad, 60, (x, y, x + size, y + size))+ gl = _cov(d) * smoothstep(0.2, -0.9, v) * 0.22+ self._blend(sl, gl, WHITE)+ self._blend(sl, np.exp(-(((d + 0.9) / 0.7) ** 2)) * 0.35, WHITE)+ if glyph:+ self.text(glyph, x + size / 2, y + size / 2, glyph_size or size * 0.5, WHITE, weight, 'mm')++ # ------------------------------------------------------------ output+ def composite(self):+ return Image.fromarray((np.clip(self.img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/bauhaus.py b/lib/bauhaus.pynew file mode 100644index 0000000..36dc343--- /dev/null+++ b/lib/bauhaus.py@@ -0,0 +1,530 @@+"""bauhaus — a geometric-constructivist poster in the Bauhaus manner, hand-pulled as a screen print on cream stock:+red, yellow and blue plus black, circles, triangles, squares and heavy bars on a strict grid, big geometric sans+lettering (numpy + Pillow only).++Model: the picture is a press sheet. Every colour is its own screen, pulled one after another, light to dark.+ stock uncoated cream paper: a cloudy, slightly warmer tone where the pulp is thicker, short fibres, a few dark+ flecks in the pulp, a per-pixel "tooth" (the tiny hills and pits of the surface) and a very low+ cockle -- the sheet is never perfectly flat, so the room light rolls across it.+ grid a pale warm-grey tint screen prints the construction grid (the module every shape and every line of+ type sits on), the way a designer's proof sheet shows it.+ screens one per ink. A screen is laid down once per colour, so everything printed in one ink shares that+ screen's registration error: a small shift (and a hair of rotation about the sheet centre) against+ the other colours. Where a colour meets black exactly, the error opens a sliver of bare paper on one+ side and a dark overlap on the other; the register targets and crop marks are on every screen, so+ they print as a little stack of coloured crosshairs, and each screen adds its own patch (and the+ overprint patches) to the colour bar.+ ink film the squeegee pulls the ink through the mesh in one direction. The film is a little thicker or thinner+ in long streaks along the pull, blotchy on a larger scale, and runs slightly thin toward the end of+ the stroke. Where the film is thin the deepest pits of the tooth stay bare (fine paper-coloured grain),+ dust on the stencil leaves pinholes, the stencil edge is ragged at the scale of the mesh and the ink+ squeezes a hair past it, and the edge of a solid carries slightly more ink than its middle.+ inks semi-opaque, like real screen inks: a pull partly covers what is under it and partly multiplies with+ it (yellow is the most transparent, black the least), so overprints turn into darker mixed colours.+ type a heavy geometric sans (Futura Bold via core.latin_font('geometric'), else the system bold sans) for+ Latin, a heavy system Hei (黑体) for Chinese; mixed strings switch font per character. Type is just a+ stencil on the black screen, so it has the same grain and edge as the shapes, and can be knocked out+ of a solid (`knock=`), leaving the paper to show through.+ pencil after printing, the edition number is written in the margin in soft graphite, which only catches the+ tops of the paper tooth.+Coordinates are pixels; `at(col, row)` converts grid cells (fractions allowed) into pixels. Angles are degrees+counter-clockwise from 3 o'clock (like a maths diagram); `rot` of rectangles and text is counter-clockwise too.++ from bauhaus import Bauhaus, YELLOW, RED, BLUE, BLACK+ b = Bauhaus(1920, 1080, seed=3)+ b.paper(margin=60, module=120)+ b.marks(targets=[(960, 30), (960, 1050)], bar=(1712, 1040)) # register targets, crop marks, colour bar+ b.grid() # tint screen: construction grid+ b.pull(b.triangle(60, 600, 840), YELLOW) # one pull of the yellow screen+ b.pull(b.rect(720, 360, 1200, 840), RED)+ b.pull(b.circle(1560, 600, 240), BLUE)+ b.pull(b.rect(60, 840, 1860, 866), BLACK) # a heavy black bar+ b.text('形与色', 60, 262, 210, font='cjk')+ b.pull(b.rect(720, 190, 1860, 282), BLACK, knock=b.text_mask('FORM', 752, 258, 60)) # type knocked out+ b.pencil('7/40', 86, 1060, 28)+ b.save('out.jpg')+"""+import os+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, noise2d, smoothstep, shift, latin_font++YELLOW, RED, BLUE, BLACK = '#f2bd1b', '#d63129', '#1f4e9c', '#1a1917'+PAPER, TINT = '#f0e7d4', '#d6cab4'+OPACITY = {YELLOW: 0.62, RED: 0.84, BLUE: 0.88, BLACK: 0.97, TINT: 0.35} # the rest multiplies with what's under+GRAIN = {YELLOW: 0.9, RED: 0.72, BLUE: 0.66, BLACK: 0.4, TINT: 0.3} # how much bare tooth shows in thin film+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++# ---------------------------------------------------------------- fonts (kept inside this module)+_STYLE, _FONTS, _HAS = {}, {}, {}+++def _face_of(hit, want, avoid=()):+ """in the collection `hit` = (path, index), the first face whose style name has every word of `want`"""+ if not hit: return None+ for i in range(32):+ try:+ f = ImageFont.truetype(hit[0], 20, index=i)+ except (OSError, ValueError):+ break+ sty = f.getname()[1] or ''+ if all(w in sty for w in want) and not any(a in sty for a in avoid):+ return hit[0], i+ return None+++def _find(style):+ """(path, index) for a style: geo (heavy geometric sans), geo_book, geo_cond, cjk (heavy Hei), cjk_book, hand"""+ if style in _STYLE: return _STYLE[style]+ env = os.environ.get('INKPAINT_FONT_' + style.upper())+ if env and os.path.exists(env):+ hit = (env, 0)+ elif style == 'geo':+ hit = _face_of(latin_font('geometric'), ('Bold',), ('Italic', 'Oblique', 'Condensed')) or latin_font('sans_bold')+ elif style == 'geo_book':+ hit = latin_font('geometric') or latin_font('sans')+ elif style == 'geo_cond':+ hit = (_face_of(latin_font('geometric'), ('Condensed', 'Bold'), ('Italic',)) or latin_font('condensed')+ or latin_font('sans_bold'))+ elif style == 'cjk':+ hg = '/System/Library/Fonts/Hiragino Sans GB.ttc' # 冬青黑体 W6 if present (macOS)+ hit = (_face_of((hg, 0), ('W6',)) if os.path.exists(hg) else None) or latin_font('cjk_sans') or latin_font('cjk')+ elif style == 'cjk_book':+ hit = latin_font('cjk_sans') or latin_font('cjk')+ elif style == 'hand':+ hit = latin_font('hand') or latin_font('sans')+ else:+ hit = latin_font(style)+ _STYLE[style] = hit+ return hit+++def _font(style, size):+ k = (style, int(round(size)))+ if k not in _FONTS:+ hit = _find(style)+ size = max(4, int(round(size)))+ _FONTS[k] = ImageFont.truetype(hit[0], size, index=hit[1]) if hit else ImageFont.load_default(size)+ return _FONTS[k]+++def _box3(a):+ """3 x 3 box average (a very light blur that keeps corners sharp)"""+ p = np.pad(a, 1, mode='edge')+ h, w = a.shape+ return sum(p[i:i + h, j:j + w] for i in range(3) for j in range(3)) / 9+++_KERN = {'°': -0.1} # em; the degree sign sits too far off+++def _is_cjk(ch):+ o = ord(ch)+ return 0x2E80 <= o <= 0x9FFF or 0xF900 <= o <= 0xFAFF or 0xFF00 <= o <= 0xFFEF or 0x3000 <= o <= 0x303F+++def _has(style, ch):+ """does the font for `style` draw a real glyph for ch (not the .notdef box)?"""+ k = (style, ch)+ if k not in _HAS:+ f = _font(style, 48)+ a, b = f.getmask(ch), f.getmask('')+ _HAS[k] = ch.isspace() or not (a.size == b.size and bytes(a) == bytes(b))+ return _HAS[k]+++def _pick(ch, style):+ """per-character font: Chinese in the Hei, Latin in the geometric sans; a missing glyph falls back to the other"""+ cjk_style = 'cjk_book' if style == 'cjk_book' else 'cjk'+ lat_style = 'geo' if style in ('cjk', 'cjk_book') else style+ if _is_cjk(ch):+ return cjk_style+ if _has(lat_style, ch): return lat_style+ return cjk_style if _has(cjk_style, ch) else lat_style+++class Bauhaus:+ def __init__(self, W=1920, H=1080, seed=0, misreg=2.6, pull=90.0):+ """misreg: typical registration error of a screen, px. pull: squeegee direction in degrees (90 = the stroke+ runs down the sheet, 0 = left to right)"""+ self.W, self.H = W, H+ self.rng = np.random.default_rng(seed)+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)+ self.misreg, self.pull_dir = misreg, pull+ self.paper_col = _c(PAPER)+ self.img = np.ones((H, W, 3), np.float32) * self.paper_col+ self.fibre = np.ones((H, W), np.float32)+ self.light = np.ones((H, W), np.float32)+ g = self.rng.random((H, W)).astype(np.float32) # pixel-sized pits ...+ c = noise2d(H, W, 6.0, 2, self._seed()) # ... a little clumped+ t = 0.8 * (g - 0.5) / 0.29 + 0.5 * (c - c.mean()) / (c.std() + 1e-6)+ self.tooth = np.clip(0.5 + t / 3.8, 0, 1).astype(np.float32) # 1 = the deepest pits of the surface+ self.screens = {}+ self._reg = None # register targets + crop marks+ self._patches = [] # colour-bar patches: (mask, inks)+ self._mark_inks = ()+ self.x0, self.y0, self.x1, self.y1, self.M = 0, 0, W, H, 120+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ the sheet+ def paper(self, colour=PAPER, margin=60, module=120, warm='#e6d6b6'):+ """uncoated cream stock. Sets the design area (the sheet minus `margin`) and the grid module."""+ H, W, r = self.H, self.W, self.rng+ self.paper_col = _c(colour)+ self.x0, self.y0, self.x1, self.y1, self.M = margin, margin, W - margin, H - margin, module+ cloud = noise2d(H, W, 360, 4, self._seed())+ t = smoothstep(0.35, 0.9, cloud)[..., None] * 0.22 # thicker pulp: a touch warmer, darker+ base = self.paper_col * (1 - t) + _c(warm) * t+ base = base * (1 + 0.012 * (noise2d(H, W, 60, 3, self._seed()) - 0.5))[..., None]+ self.img = base.astype(np.float32)+ # short fibres, some lighter and some darker than the sheet+ fim = Image.new('L', (W, H), 128)+ d = ImageDraw.Draw(fim)+ for _ in range(int(W * H / 700)):+ x, y = r.uniform(0, W), r.uniform(0, H)+ a, L = r.uniform(0, np.pi), r.uniform(5, 26)+ bend = r.normal(0, 0.25)+ pts = [(x + np.cos(a + bend * s) * L * s, y + np.sin(a + bend * s) * L * s) for s in np.linspace(-0.5, 0.5, 5)]+ d.line(pts, fill=int(128 + r.choice([-1, 1]) * r.uniform(10, 30)), width=1)+ fib = blur((np.asarray(fim, np.float32) - 128) / 128, 0.6)+ fine = blur(r.random((H, W)).astype(np.float32), 0.7)+ fine = (fine - fine.mean()) / (fine.std() + 1e-6)+ self.fibre = (1 + 0.05 * fib + 0.006 * fine).astype(np.float32)+ # flecks in the pulp (they sit under the ink)+ fl = Image.new('L', (W * 2, H * 2), 0)+ d = ImageDraw.Draw(fl)+ for _ in range(int(W * H / 9000)):+ x, y, rr = r.uniform(0, W * 2), r.uniform(0, H * 2), r.uniform(0.7, 2.6) * (3 if r.random() < 0.04 else 1)+ d.ellipse((x - rr, y - rr * r.uniform(0.5, 1), x + rr, y + rr * r.uniform(0.5, 1)), fill=int(r.uniform(70, 200)))+ fl = np.asarray(fl.resize((W, H), Image.BOX), np.float32) / 255+ self.img *= (1 - fl[..., None] * (1 - _c('#6a5a45')))+ # room light rolling over a sheet that is not quite flat+ cockle = noise2d(H, W, 520, 2, self._seed()) - 0.5+ grad = 1 + 0.03 * (0.5 - (self.XX / W * 0.65 + self.YY / H * 0.35))+ vig = 1 - 0.06 * (((self.XX - W * 0.5) / W) ** 2 + ((self.YY - H * 0.48) / H) ** 2) * 2+ self.light = (grad * vig + 0.022 * cockle).astype(np.float32)++ def at(self, c, r):+ """grid cell (col, row) -> pixel (x, y); fractions allowed"""+ return self.x0 + c * self.M, self.y0 + r * self.M++ # ------------------------------------------------------------ masks (full canvas, anti-aliased, 0..1)+ def circle(self, cx, cy, r):+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)++ def ring(self, cx, cy, r, width):+ return np.clip(width / 2 - np.abs(np.hypot(self.XX - cx, self.YY - cy) - r) + 0.5, 0, 1)++ def _wedge(self, cx, cy, a0, a1):+ """signed distance to the wedge between angles a0 -> a1 (ccw, degrees)"""+ dx, dy = self.XX - cx, self.YY - cy+ t0, t1 = np.deg2rad(a0), np.deg2rad(a1)+ h0 = -np.cos(t0) * dy - np.sin(t0) * dx # left of the a0 ray+ h1 = np.cos(t1) * dy + np.sin(t1) * dx # right of the a1 ray+ span = (a1 - a0) % 360+ return np.minimum(h0, h1) if span <= 180 else np.maximum(h0, h1)++ def sector(self, cx, cy, r, a0, a1):+ """a slice of a disc from angle a0 to a1 (ccw): (0, 180) is the upper half, (270, 360) the lower-right quarter"""+ return np.minimum(self.circle(cx, cy, r), np.clip(self._wedge(cx, cy, a0, a1) + 0.5, 0, 1))++ def arc(self, cx, cy, r, a0, a1, width):+ """a line arc of radius r from a0 to a1 (ccw), butt ends"""+ return np.minimum(self.ring(cx, cy, r, width), np.clip(self._wedge(cx, cy, a0, a1) + 0.5, 0, 1))++ def rect(self, x0, y0, x1, y1, rot=0.0):+ if not rot:+ return (np.clip(np.minimum(self.XX - x0, x1 - self.XX) + 0.5, 0, 1)+ * np.clip(np.minimum(self.YY - y0, y1 - self.YY) + 0.5, 0, 1))+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2+ t = np.deg2rad(rot)+ c, s = np.cos(t), np.sin(t)+ pts = [(cx + u * c + v * s, cy - u * s + v * c) for u, v in+ [(x0 - cx, y0 - cy), (x1 - cx, y0 - cy), (x1 - cx, y1 - cy), (x0 - cx, y1 - cy)]]+ return self.poly(pts)++ def bar(self, x0, y0, x1, y1, width, cap='butt'):+ """a straight bar (or a rule, when thin) from (x0, y0) to (x1, y1); cap 'butt' | 'square' | 'round'"""+ dx, dy = x1 - x0, y1 - y0+ L = float(np.hypot(dx, dy)) + 1e-6+ ux, uy = dx / L, dy / L+ u = (self.XX - x0) * ux + (self.YY - y0) * uy+ v = -(self.XX - x0) * uy + (self.YY - y0) * ux+ if cap == 'round':+ uc = np.clip(u, 0, L)+ return np.clip(width / 2 - np.hypot(u - uc, v) + 0.5, 0, 1)+ ext = width / 2 if cap == 'square' else 0+ return np.clip(np.minimum(width / 2 - np.abs(v), np.minimum(u + ext, L + ext - u)) + 0.5, 0, 1)++ def poly(self, pts):+ """filled polygon; convex ones are exact (half-plane distances), others are supersampled"""+ P = np.asarray(pts, np.float64)+ n = len(P)+ e = np.roll(P, -1, 0) - P+ cr = e[:, 0] * np.roll(e, -1, 0)[:, 1] - e[:, 1] * np.roll(e, -1, 0)[:, 0]+ if np.all(cr >= -1e-9) or np.all(cr <= 1e-9):+ sgn = 1.0 if cr.sum() > 0 else -1.0+ d = np.full((self.H, self.W), 1e9, np.float32)+ for i in range(n):+ ex, ey = e[i] / (np.hypot(*e[i]) + 1e-9)+ # inside is to the right of each edge for clockwise-on-screen order, flip for the other order+ np.minimum(d, sgn * ((self.XX - P[i, 0]) * ey - (self.YY - P[i, 1]) * ex) * -1, out=d)+ return np.clip(d + 0.5, 0, 1)+ ss = 4+ x0, y0 = int(np.floor(P[:, 0].min())) - 2, int(np.floor(P[:, 1].min())) - 2+ x1, y1 = int(np.ceil(P[:, 0].max())) + 2, int(np.ceil(P[:, 1].max())) + 2+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P], fill=255)+ a = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ return self._place(a, x0, y0)++ def triangle(self, x0, x1, base_y, apex=None, height=None):+ """a triangle standing on the line base_y between x0 and x1; equilateral unless apex / height is given"""+ if apex is None:+ h = height if height is not None else (x1 - x0) * np.sqrt(3) / 2+ apex = ((x0 + x1) / 2, base_y - h)+ return self.poly([(x0, base_y), apex, (x1, base_y)])++ def _place(self, a, x0, y0):+ out = np.zeros((self.H, self.W), np.float32)+ h, w = a.shape+ ys, xs = max(0, y0), max(0, x0)+ ye, xe = min(self.H, y0 + h), min(self.W, x0 + w)+ if ye > ys and xe > xs:+ out[ys:ye, xs:xe] = a[ys - y0:ye - y0, xs - x0:xe - x0]+ return out++ # ------------------------------------------------------------ type+ def text_mask(self, s, x, y, size, font='geo', anchor='ls', spacing=0.0, rot=0.0, weight=0.0, ss=2):+ """lettering -> full-canvas mask. anchor: l/m/r then s (baseline), m (middle of the capitals), t (cap top).+ font: geo (heavy geometric sans), geo_book, geo_cond, cjk (heavy Hei), cjk_book. spacing: extra px per letter.+ rot: degrees ccw about (x, y). weight: faux-bold px."""+ chars = [(ch, _pick(ch, font)) for ch in s]+ runs = [] # consecutive same-font chars keep kerning+ for ch, st in chars:+ if runs and runs[-1][1] == st and not spacing and ch not in _KERN:+ runs[-1][0] += ch+ else:+ runs.append([ch, st])+ advs = [_font(st, size).getlength(t) + spacing * len(t) + _KERN.get(t[0], 0) * size for t, st in runs]+ total = sum(advs) - (spacing if s else 0)+ if any(_is_cjk(ch) for ch in s):+ capH = -_font('cjk' if font != 'cjk_book' else 'cjk_book', size).getbbox('中', anchor='ls')[1] * 0.93+ else:+ capH = -_font(_pick('H', font), size).getbbox('H', anchor='ls')[1]+ desc = size * 0.28+ dyb = {'s': 0, 'm': capH / 2, 't': capH, 'a': capH, 'b': -desc, 'd': -desc}.get(anchor[1], 0)+ xs0 = x - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ base = y + dyb+ pad = int(size * 0.3 + weight + 6)+ bx0, by0 = int(np.floor(xs0)) - pad, int(np.floor(base - capH * 1.3)) - pad+ bx1, by1 = int(np.ceil(xs0 + total)) + pad, int(np.ceil(base + desc)) + pad+ im = Image.new('L', ((bx1 - bx0) * ss, (by1 - by0) * ss), 0)+ d = ImageDraw.Draw(im)+ cx = (xs0 - bx0) * ss+ for (t, st), adv in zip(runs, advs):+ f = _font(st, size * ss)+ cx += _KERN.get(t[0], 0) * size * ss+ if spacing:+ for ch in t:+ if not ch.isspace():+ d.text((cx, (base - by0) * ss), ch, font=f, fill=255, anchor='ls',+ stroke_width=int(round(weight * ss)), stroke_fill=255)+ cx += (f.getlength(ch) + spacing * ss)+ else:+ d.text((cx, (base - by0) * ss), t, font=f, fill=255, anchor='ls',+ stroke_width=int(round(weight * ss)), stroke_fill=255)+ cx += (adv - _KERN.get(t[0], 0) * size) * ss+ a = np.asarray(im.resize((bx1 - bx0, by1 - by0), Image.BOX), np.float32) / 255+ if rot:+ R = int(np.hypot(bx1 - bx0, by1 - by0)) + 4+ big = np.zeros((2 * R, 2 * R), np.float32)+ ox, oy = int(round(x)) - R, int(round(y)) - R+ big[by0 - oy:by1 - oy, bx0 - ox:bx1 - ox] = a+ bim = Image.fromarray((big * 255).astype(np.uint8)).rotate(rot, resample=Image.BICUBIC,+ center=(x - ox, y - oy))+ return self._place(np.asarray(bim, np.float32) / 255, ox, oy)+ return self._place(a, bx0, by0)++ def text_width(self, s, size, font='geo', spacing=0.0):+ return sum(_font(_pick(ch, font), size).getlength(ch) + spacing + _KERN.get(ch, 0) * size for ch in s) - (spacing if s else 0)++ def text(self, s, x, y, size, ink=BLACK, font='geo', anchor='ls', spacing=0.0, rot=0.0, weight=0.0):+ """print lettering through the screen of `ink` (default black)"""+ m = self.text_mask(s, x, y, size, font, anchor, spacing, rot, weight)+ self.pull(m, ink, edge=float(np.clip((size - 14) / 50, 0, 1)))+ return m++ # ------------------------------------------------------------ printer's marks+ def marks(self, targets=(), crop=True, bar=None, patch=22, gap=4, inks=(YELLOW, RED, BLUE, BLACK),+ overprints=False, r=10, hair=1.4):+ """register targets (ring + crosshair) at `targets`, crop marks at the corners of the design area and a colour+ bar whose top-left is `bar`. They are carried by every screen in `inks`: each pull of a new ink prints its+ copy (with that screen's registration error) and its patches."""+ m = np.zeros((self.H, self.W), np.float32)+ for (x, y) in targets:+ m = np.maximum(m, self.ring(x, y, r, hair))+ m = np.maximum(m, self.bar(x - r - 9, y, x + r + 9, y, hair))+ m = np.maximum(m, self.bar(x, y - r - 9, x, y + r + 9, hair))+ if crop:+ g, L = 10, 30+ for (cx, cy, sx, sy) in [(self.x0, self.y0, -1, -1), (self.x1, self.y0, 1, -1),+ (self.x0, self.y1, -1, 1), (self.x1, self.y1, 1, 1)]:+ m = np.maximum(m, self.bar(cx + sx * g, cy, cx + sx * (g + L), cy, hair))+ m = np.maximum(m, self.bar(cx, cy + sy * g, cx, cy + sy * (g + L), hair))+ self._reg = m+ self._patches = []+ if bar is not None:+ sets = [(k,) for k in inks]+ if overprints:+ col = [k for k in inks if k != BLACK]+ sets += [(a, b) for i, a in enumerate(col) for b in col[i + 1:]]+ x, y = bar+ for k, st in enumerate(sets):+ px = x + k * (patch + gap)+ self._patches.append((self.rect(px, y, px + patch, y + patch), set(st)))+ self._mark_inks = tuple(inks)+ for k in list(self.screens): # screens already used print theirs now+ self._print_marks(k)++ def _print_marks(self, ink):+ if ink not in self._mark_inks or self._reg is None: return+ m = self._reg.copy()+ for pm, st in self._patches:+ if ink in st: m = np.maximum(m, pm)+ self.pull(m, ink, edge=0.0)++ # ------------------------------------------------------------ screens and the pull+ def _screen(self, ink):+ if ink in self.screens: return self.screens[ink]+ H, W, r = self.H, self.W, self.rng+ a = r.uniform(0, 2 * np.pi)+ mag = self.misreg * r.uniform(0.55, 1.0) * (0.4 if ink == TINT else 1.0)+ t = np.deg2rad(self.pull_dir)+ # film thickness: long streaks along the pull, blotches, thinning toward the end of the stroke+ along = (self.XX * np.cos(t) + self.YY * np.sin(t))+ along = (along - along.min()) / (along.max() - along.min() + 1e-6)+ k = bool(abs(np.sin(t)) > 0.5) # streaks run along y for a vertical pull+ gh, gw = (H // 40 + 3, W // 2 + 3) if k else (H // 2 + 3, W // 40 + 3)+ st = np.asarray(Image.fromarray(r.random((gh, gw)).astype(np.float32)).resize((W, H), Image.BICUBIC))+ bh, bw = (3, W // 70 + 3) if k else (H // 70 + 3, 3)+ band = np.asarray(Image.fromarray(r.random((bh, bw)).astype(np.float32)).resize((W, H), Image.BICUBIC))+ blot = noise2d(H, W, 70, 3, self._seed())+ film = 1.0 - 0.04 * (st - 0.5) - 0.05 * (band - 0.5) - 0.06 * (blot - 0.5) - 0.04 * smoothstep(0.55, 1, along)+ # pinholes: dust on the stencil+ pim = Image.new('L', (W * 2, H * 2), 0)+ d = ImageDraw.Draw(pim)+ for _ in range(int(W * H / 16000)):+ x, y, rr = r.uniform(0, W * 2), r.uniform(0, H * 2), r.uniform(0.8, 2.4)+ d.ellipse((x - rr, y - rr, x + rr, y + rr), fill=int(r.uniform(120, 255)))+ pins = np.asarray(pim.resize((W, H), Image.BOX), np.float32) / 255+ fine = blur(r.random((H, W)).astype(np.float32), 1.0)+ fine = np.clip(0.5 + (fine - fine.mean()) / (fine.std() + 1e-6) * 0.18, 0, 1)+ scr = dict(t=(np.cos(a) * mag, np.sin(a) * mag), rot=r.normal(0, 0.00032), film=film.astype(np.float32),+ pins=pins, fine=fine.astype(np.float32),+ roll=(int(r.integers(0, H)), int(r.integers(0, W))))+ self.screens[ink] = scr+ self._print_marks(ink)+ return scr++ def _subshift(self, a, dx, dy):+ ix, iy = int(np.floor(dx)), int(np.floor(dy))+ fx, fy = dx - ix, dy - iy+ return ((1 - fx) * (1 - fy) * shift(a, ix, iy) + fx * (1 - fy) * shift(a, ix + 1, iy)+ + (1 - fx) * fy * shift(a, ix, iy + 1) + fx * fy * shift(a, ix + 1, iy + 1))++ def pull(self, mask, ink, knock=None, edge=1.0, density=1.0, opacity=None):+ """one pull of the squeegee: print `mask` in `ink` through that ink's screen.+ knock: a mask cut out of the stencil (knocked-out type). edge: 0 keeps hairlines clean, 1 = full+ ragged mesh edge. density scales the ink film; opacity overrides the ink's own covering power."""+ m = np.clip(mask if knock is None else mask - knock, 0, 1).astype(np.float32)+ rows, cols = np.flatnonzero(m.max(1) > 0.002), np.flatnonzero(m.max(0) > 0.002)+ if not len(rows): return+ scr = self._screen(ink)+ p = int(self.misreg * 2 + 10)+ y0, y1 = max(0, rows[0] - p), min(self.H, rows[-1] + p + 1)+ x0, x1 = max(0, cols[0] - p), min(self.W, cols[-1] + p + 1)+ sl = (slice(y0, y1), slice(x0, x1))+ # this screen's registration error, evaluated where the shape is+ cx, cy = (x0 + x1) / 2 - self.W / 2, (y0 + y1) / 2 - self.H / 2+ dx = scr['t'][0] - scr['rot'] * cy+ dy = scr['t'][1] + scr['rot'] * cx+ mm = self._subshift(m[sl], dx, dy)+ if edge > 0: # ragged stencil edge, ink spread+ fine = np.roll(scr['fine'], scr['roll'], (0, 1))[sl]+ mb = _box3(mm)+ e = mb + (fine - 0.5) * 0.3 * edge + 0.03+ m2 = smoothstep(0.5 - 0.2, 0.5 + 0.2, e) * np.clip(mb * 3, 0, 1)+ m2 = mm * (1 - edge) + m2 * edge+ else:+ m2 = mm+ film = scr['film'][sl] * density+ tooth = self.tooth[sl]+ g = GRAIN.get(ink, 0.8)+ bare = smoothstep(0.91, 1.0, tooth + (1.0 - film) * 2.6 - 0.02) * g # pits the thin film misses+ cover = np.clip(1 - bare - scr['pins'][sl] * 0.85, 0, 1)+ rim = np.clip(m2 - blur(m2, 2.5), 0, 1) if edge > 0 else 0+ micro = 1 - 0.05 * (tooth - 0.5) # the film follows the tooth+ dd = np.clip(m2 * np.clip(film, 0, 1) * cover * micro, 0, 1)[..., None]+ op = OPACITY.get(ink, 0.8) if opacity is None else opacity+ col = _c(ink)[None, None, :] * (1 - 0.07 * (rim[..., None] if edge > 0 else 0))+ cur = self.img[sl]+ T = cur * (1 - dd + dd * np.clip(col / self.paper_col, 0, 1.2)) # the transparent part multiplies+ O = cur * (1 - dd) + dd * col # the pigment part covers+ self.img[sl] = T * (1 - op) + O * op++ # ------------------------------------------------------------ construction grid+ def grid(self, colour=TINT, width=1.5, every=1, extend=0):+ """print the construction grid (every `every` modules) inside the design area through a pale tint screen"""+ M = self.M * every+ x0, y0, x1, y1 = self.x0 - extend, self.y0 - extend, self.x1 + extend, self.y1 + extend+ rx = np.mod(self.XX - self.x0 + M / 2, M) - M / 2+ ry = np.mod(self.YY - self.y0 + M / 2, M) - M / 2+ inside = (np.clip(np.minimum(self.XX - x0, x1 - self.XX) + 1, 0, 1)+ * np.clip(np.minimum(self.YY - y0, y1 - self.YY) + 1, 0, 1))+ m = np.maximum(np.clip(width / 2 - np.abs(rx) + 0.5, 0, 1), np.clip(width / 2 - np.abs(ry) + 0.5, 0, 1))+ self.pull(m * inside, colour, edge=0.0)++ # ------------------------------------------------------------ pencil, after printing+ def pencil(self, s, x, y, size, colour='#4a4b4f', pressure=0.7, font='hand', anchor='ls', rot=0.0):+ """soft graphite in the margin (the edition number): only the tops of the tooth take it"""+ m = self.text_mask(s, x, y, size, font, anchor, rot=rot)+ rows, cols = np.flatnonzero(m.max(1) > 0), np.flatnonzero(m.max(0) > 0)+ if not len(rows): return+ sl = (slice(rows[0], rows[-1] + 1), slice(cols[0], cols[-1] + 1))+ catch = smoothstep(0.62 - pressure * 0.25, 0.3 - pressure * 0.25, self.tooth[sl])+ a = np.clip(m[sl] * (0.35 + 0.65 * catch) * pressure, 0, 1)[..., None]+ self.img[sl] *= 1 - a * (1 - _c(colour))++ # ------------------------------------------------------------ output+ def composite(self):+ img = self.img * (self.fibre * self.light)[..., None]+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0) # 4:4:4 keeps red edges crisp+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/cartoon.py b/lib/cartoon.pynew file mode 100644index 0000000..1ae282d--- /dev/null+++ b/lib/cartoon.py@@ -0,0 +1,991 @@+"""cartoon — a drawing from a hand-drawn cartoon animation (逐帧手绘 / frame by frame): brush-pen ink that boils+from frame to frame, flat colour with one or two hard cel-shadow tones, cream paper, crayon and screentone accents,+and small everyday things with faces (numpy + Pillow only).++Model: one drawing of a hand-drawn animation, made the way an animator makes it, on one sheet of cream paper.+ paper warm cream drawing paper: a bumpy "tooth" (cold-press grain lit from the upper left, so every colour+ laid on the sheet still shows the grain), slow mottling and a few fibres. Crayon and pencil only catch+ the tops of the tooth; ink and flat colour cover it but keep its light and shade.+ rough the animator's blue col-erase pencil. Every ink line is first sketched loosely in blue: one or two+ passes that drift off the final line, overshoot the ends and run past the start of closed shapes. The+ rough stays on the sheet under the colour, faint, the way it does on real animation drawings.+ ink a brush pen: a line lands thin, swells, and lifts off to a point; pressure drifts along it and the+ hand wobbles slowly; closed shapes are one stroke whose two tapered ends overlap where the pen came+ back round, and they are heavier on the side away from the light (bottom right), so shapes read solid.+ Edges pick up a little of the paper tooth, so a line is never vector-clean.+ colour flat gouache / marker fills painted slightly off the lines: every fill is shifted a few pixels and its+ edge wanders, so here it spills over a line and there it leaves a sliver of paper -- hand-coloured,+ a little mis-registered. Big fills also drift slowly in density.+ cel shade one or two hard-edged shadow tones inside a shape: the shape minus itself nudged toward the light+ (a crescent on the far side), plus white glints (tapered strokes of opaque white paint).+ accents crayon (wax that only takes on the tooth tops, streaked along the scribble direction, with a ragged+ edge), screentone (a rotated halftone dot grid), ink hatching for contact shadows.+ things faces (happy ^ ^ eyes and an open grin with a tongue, surprised, sleepy, smiling, blush), rubber-hose+ arms with round white gloves, 4-point sparkles, speed lines, steam wisps, scalloped puffs, starbursts,+ crumbs, emphasis ticks; display lettering (chunky rounded letters, each a little tilted and bounced,+ with an extruded shadow, a white rim light and a thick ink outline), hand-lettered notes, arrows,+ numbered badges, and blue-pencil notes in the corner of the sheet.+ boil a hand-drawn animation is traced again for every frame, so its lines never sit still ("boiling+ line"). Every snapshot re-traces the ink through a fresh smooth displacement field of a pixel or two;+ the colour and the pencil stay where they are on the sheet, so line and colour slide against each+ other a little from frame to frame.+ occlusion things are opaque: a fill knocks out the ink and colour of whatever was drawn before it inside its+ outline (hidden lines removed), so draw back to front. Effects ('fx') and lettering ('type') are+ overlays drawn last; their knock-outs apply only when those groups are shown, so staged snapshots+ never show holes.+Groups: every mark lands in a named group chosen by its kind -- 'rough' (pencil), 'ink' (lines), 'flat' (fills),+'shade' (cel shadows, glints, blush), 'texture' (crayon, screentone, hatching), 'fx' (effects), 'type' (lettering,+notes, arrows). Methods take kind=...; `with c.group(ink='ink_bg'):` sends one kind to another group, `with+c.group('fx'):` sends everything. stage(name, show=[groups]) snapshots only those groups, so a finished drawing can+be replayed the way it was made: rough -> ink -> flat colour -> shadows -> texture -> effects -> lettering.+Lettering: chunky CJK rounded (Yuanti on macOS, Noto Sans CJK Bold on Linux, YaHei Bold on Windows) and a comic+Latin face (Chalkboard SE / Marker Felt / Comic Sans, else a rounded bold). Angles are degrees counter-clockwise.++ from cartoon import Cartoon, YELLOW, RED, WHITE+ c = Cartoon(1920, 1080, seed=3) # draw back to front: every fill hides what is behind it+ c.arm((1150, 640), (1300, 540), bend=0.35) # limbs first, so the body hides the shoulder+ body = Cartoon.rrect_pts(700, 500, 1200, 850, (90, 90, 30, 30))+ c.shape(body, '#83cbbd', shade=('#57a89d', 30, 10)) # fill + cel shadow + brush outline+ c.face(950, 680, 120, 'happy')+ c.sparkle(1350, 420, 30)+ c.burst(1500, 260, 150, 110, RED)+ c.letter('POP!', 1500, 290, 90, YELLOW, anchor='m')+ c.stage('ink', show=['rough', 'ink'])+ c.save('out.png')+"""+import glob+import numpy as np+from contextlib import contextmanager+from PIL import Image, ImageDraw, ImageFont+from core import blur, fbm1d, spline, noise2d, smoothstep, shift, polygon_mask, latin_font++PAPER, INK, PENCIL, WHITE = '#f0e7d5', '#231c18', '#6c9be0', '#fffbf1'+RED, YELLOW, PINK, ORANGE = '#e04a3a', '#f8cd48', '#f39486', '#f58a3c'+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++def darker(colour, k=0.78):+ """a cel-shadow tone of `colour`: darker and nudged a little toward violet, never grey"""+ c = _c(colour) * k+ return np.clip(c * np.array([0.98, 0.95, 1.04], np.float32) + np.array([0.01, 0, 0.02], np.float32), 0, 1)+++def _resample(P, step, closed=False):+ P = np.asarray(P, np.float32)+ if closed: P = np.vstack([P, P[:1]])+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ if s[-1] < 1e-3: return P[:1]+ n = max(2, int(s[-1] / step) + 1)+ ss = np.linspace(0, s[-1], n, endpoint=not closed)+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)+++def _closed_spline(pts, per=12):+ """periodic Catmull-Rom through control points (closed smooth curve)"""+ P = np.asarray(pts, np.float32)+ n = len(P)+ out = []+ for i in range(n):+ p0, p1, p2, p3 = P[(i - 1) % n], P[i], P[(i + 1) % n], P[(i + 2) % n]+ for t in np.linspace(0, 1, per, endpoint=False):+ t2, t3 = t * t, t * t * t+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))+ return np.array(out, np.float32)+++def _normals(P):+ T = np.gradient(P, axis=0)+ T /= np.linalg.norm(T, axis=1, keepdims=True) + 1e-6+ return T, np.stack([-T[:, 1], T[:, 0]], 1)+++def _dilate(m, r):+ """grow a mask by about r px (alternating plus / square steps ~ an octagon)"""+ out = m+ for i in range(int(round(r))):+ o = out.copy()+ nb = ((1, 0), (-1, 0), (0, 1), (0, -1)) + (((1, 1), (1, -1), (-1, 1), (-1, -1)) if i % 2 else ())+ for dx, dy in nb:+ np.maximum(o, shift(out, dx, dy), out=o)+ out = o+ return out+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++# ---------------------------------------------------------------- fonts (looked up on the system, never bundled)+_FONT_CANDIDATES = {+ 'cjk_round': [('/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/Yuanti.ttc', 2),+ ('/Library/Fonts/Yuanti.ttc', 2), ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0),+ ('/usr/share/fonts/**/NotoSansSC*Bold*.[ot]tf', 0), ('C:/Windows/Fonts/msyhbd.ttc', 0)],+ 'comic': [('/System/Library/Fonts/Supplemental/ChalkboardSE.ttc', 2), ('/System/Library/Fonts/MarkerFelt.ttc', 1),+ ('/System/Library/Fonts/Supplemental/Comic Sans MS Bold.ttf', 0), ('/usr/share/fonts/**/ComicNeue*Bold*.[ot]tf', 0),+ ('/usr/share/fonts/**/ComicRelief*.ttf', 0), ('C:/Windows/Fonts/comicbd.ttf', 0)],+}+_FALLBACK = {'comic': ('rounded', 'sans_bold'), 'cjk_round': ('cjk_sans', 'cjk')}+_PATHS, _FONTS, _HAS = {}, {}, {}+++def _font_path(style):+ if style in _PATHS: return _PATHS[style]+ hit = None+ for pat, idx in _FONT_CANDIDATES.get(style, []):+ for p in glob.glob(pat, recursive=True):+ try:+ ImageFont.truetype(p, 20, index=idx); hit = (p, idx); break+ except OSError:+ pass+ if hit: break+ if hit is None:+ for st in _FALLBACK.get(style, (style,)):+ h = latin_font(st)+ if h: hit = h; break+ _PATHS[style] = hit+ return hit+++def _font(style, size):+ key = (style, int(size))+ if key not in _FONTS:+ hit = _font_path(style)+ try:+ _FONTS[key] = ImageFont.truetype(hit[0], int(size), index=hit[1]) if hit else ImageFont.load_default(int(size))+ except OSError:+ _FONTS[key] = ImageFont.load_default(int(size))+ return _FONTS[key]+++def _has(style, ch):+ """does the font for `style` have a real glyph for ch (not the .notdef box)?"""+ key = (style, ch)+ if key not in _HAS:+ f = _font(style, 40)+ try:+ a, b = f.getmask(ch), f.getmask('\U000F0000')+ _HAS[key] = a.size != b.size or bytes(a) != bytes(b)+ except Exception:+ _HAS[key] = False+ return _HAS[key]+++def _pick(ch, style):+ if style is None: style = 'cjk_round' if _is_cjk(ch) else 'comic'+ if _has(style, ch): return style+ for alt in ('cjk_round', 'comic', 'cjk_sans'):+ if alt != style and _has(alt, ch): return alt+ return style+++class Mask:+ """a mask cropped to its bounding box: sl = (row slice, col slice), a = values"""++ def __init__(self, sl, a):+ self.sl, self.a = sl, a+++class Cartoon:+ ORDER = ('rough', 'ink', 'flat', 'shade', 'texture', 'fx', 'type')+ OVERLAY = ('fx', 'type')++ def __init__(self, W=1920, H=1080, seed=0, boil=1.8, slop=3.5, rough=True, light=(-0.55, -0.83)):+ self.W, self.H = W, H+ self.seed = seed+ self.rng = np.random.default_rng(seed)+ self.boil, self.slop, self.auto_rough = boil, slop, rough+ l = np.asarray(light, np.float32)+ self.light = l / np.linalg.norm(l)+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)+ r = np.random.default_rng(seed + 991)+ g = blur(r.random((H, W)).astype(np.float32), 0.7) # fine grain ...+ m = noise2d(H, W, 4.5, 3, seed + 3) # ... in cold-press bumps+ g = (g - g.mean()) / (g.std() + 1e-6)+ m = (m - m.mean()) / (m.std() + 1e-6)+ self.tooth = np.clip(0.5 + (0.45 * g + 0.75 * m) / 3.4, 0, 1).astype(np.float32)+ gy, gx = np.gradient(blur(0.35 * g + m, 1.0))+ s = -(gx * self.light[0] + gy * self.light[1])+ self._bump = np.clip(s / (s.std() + 1e-6), -3, 3).astype(np.float32)+ self._mott = (noise2d(H, W, 380, 3, seed + 5) - 0.5).astype(np.float32)+ self._var = noise2d(H, W, 90, 3, seed + 7) # slow density drift of fills+ self._wob = noise2d(H, W, 15, 2, seed + 11) # wandering fill edges+ self.paint, self.ink, self.pencil, self.cover = {}, {}, {}, {}+ self.created = []+ self._all, self._map = None, {}+ self.stages = []+ self.paper()++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ groups and buffers+ @contextmanager+ def group(self, name=None, **kinds):+ """with c.group('fx'): every mark goes to group 'fx'; with c.group(ink='ink_bg'): only ink lines move"""+ old = (self._all, dict(self._map))+ if name: self._all = name+ self._map.update(kinds)+ try:+ yield+ finally:+ self._all, self._map = old++ def _g(self, kind):+ return self._all or self._map.get(kind, kind)++ def _prio(self, g):+ return self.ORDER.index(g) if g in self.ORDER else self.ORDER.index('texture') + 0.5++ def _new(self, g):+ if g not in self.created: self.created.append(g)++ def _pbuf(self, g):+ if g not in self.paint:+ self._new(g)+ self.paint[g] = [np.zeros((self.H, self.W, 3), np.float32), np.zeros((self.H, self.W), np.float32)]+ return self.paint[g]++ def _ibuf(self, g):+ if g not in self.ink:+ self._new(g); self.ink[g] = np.zeros((self.H, self.W), np.float32)+ return self.ink[g]++ def _rbuf(self, g):+ if g not in self.pencil:+ self._new(g); self.pencil[g] = np.zeros((self.H, self.W), np.float32)+ return self.pencil[g]++ def _box(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))+ if x1 <= x0 or y1 <= y0: return None+ return (slice(y0, y1), slice(x0, x1))++ def _region(self, shape, pad=4):+ """points (n, 2), a full-size mask or a Mask -> (slices, cropped mask)"""+ if isinstance(shape, Mask):+ y0, x0 = shape.sl[0].start, shape.sl[1].start+ h, w = shape.a.shape+ sl = self._box(x0 - pad, y0 - pad, x0 + w + pad, y0 + h + pad)+ out = np.zeros((sl[0].stop - sl[0].start, sl[1].stop - sl[1].start), np.float32)+ oy, ox = y0 - sl[0].start, x0 - sl[1].start+ out[oy:oy + h, ox:ox + w] = shape.a+ return sl, out+ a = np.asarray(shape, np.float32)+ if a.ndim == 2 and a.shape == (self.H, self.W):+ rows = np.flatnonzero(a.max(1) > 1e-3); cols = np.flatnonzero(a.max(0) > 1e-3)+ if not len(rows): return None, None+ sl = self._box(cols[0] - pad, rows[0] - pad, cols[-1] + 1 + pad, rows[-1] + 1 + pad)+ return sl, a[sl].copy()+ sl = self._box(a[:, 0].min() - pad, a[:, 1].min() - pad, a[:, 0].max() + pad + 1, a[:, 1].max() + pad + 1)+ if sl is None: return None, None+ h, w = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start+ return sl, polygon_mask(h, w, a - np.array([sl[1].start, sl[0].start], np.float32), ss=2)++ def _crop(self, shape, sl):+ """any mask-like `shape` sampled on the slices sl"""+ if shape is None: return 1.0+ if isinstance(shape, Mask):+ full = np.zeros((self.H, self.W), np.float32); full[shape.sl] = shape.a+ return full[sl]+ a = np.asarray(shape, np.float32)+ if a.ndim == 2 and a.shape == (self.H, self.W): return a[sl]+ return self.mask(a)[sl]++ def mask(self, pts, ss=2):+ """filled polygon -> full-size float mask (combine masks with numpy, then pass them to any method)"""+ return polygon_mask(self.H, self.W, pts, ss)++ def _knock(self, g, sl, occ_paint, occ_ink):+ """an opaque thing: whatever was drawn before it inside its outline disappears. Overlay groups (fx, type)+ knock their own group now and everything else only when they are shown (see composite)."""+ if g in self.OVERLAY:+ cp, ci = self.cover.setdefault(g, [np.zeros((self.H, self.W), np.float32), np.zeros((self.H, self.W), np.float32)])+ cp[sl] = np.maximum(cp[sl], occ_paint); ci[sl] = np.maximum(ci[sl], occ_ink)+ targets = [g]+ else:+ targets = list(self.created)+ for t in targets:+ if t in self.paint:+ pc, pa = self.paint[t]+ pc[sl] *= (1 - occ_paint)[..., None]; pa[sl] *= 1 - occ_paint+ if t in self.ink:+ self.ink[t][sl] *= 1 - occ_ink++ def _put(self, g, sl, a, colour):+ """paint (premultiplied over); colour may be (3,) or (h, w, 3)"""+ pc, pa = self._pbuf(g)+ a = np.clip(a, 0, 1)+ col = colour if (isinstance(colour, np.ndarray) and colour.ndim == 3) else _c(colour)+ pc[sl] = pc[sl] * (1 - a[..., None]) + col * a[..., None]+ pa[sl] = pa[sl] * (1 - a) + a++ def _inkon(self, g, sl, a):+ """ink: edges pick up a little paper tooth, overlapping ink does not get darker"""+ e = 4 * a * (1 - a)+ a = np.clip(a + e * (self.tooth[sl] - 0.5) * 0.9, 0, 1)+ ia = self._ibuf(g)+ ia[sl] = 1 - (1 - ia[sl]) * (1 - a)++ # ------------------------------------------------------------ geometry helpers+ @staticmethod+ def place(pts, cx, cy, scale=1.0, rot=0.0):+ """local points (x right, y down) -> scaled, rotated counter-clockwise by rot degrees, moved to (cx, cy)"""+ P = np.asarray(pts, np.float32) * scale+ t = np.deg2rad(rot)+ c, s = np.cos(t), np.sin(t)+ return np.stack([cx + P[:, 0] * c + P[:, 1] * s, cy - P[:, 0] * s + P[:, 1] * c], 1)++ @staticmethod+ def ellipse_pts(cx, cy, rx, ry, rot=0.0, a0=0.0, a1=360.0, n=None):+ """ellipse (or an arc from a0 to a1 degrees, clockwise on screen from +x) as points"""+ full = abs(a1 - a0) >= 360+ n = n or max(24, int(abs(a1 - a0) / 360 * 2 * np.pi * max(rx, ry) / 5))+ t = np.deg2rad(np.linspace(a0, a1, n, endpoint=not full))+ return Cartoon.place(np.stack([np.cos(t) * rx, np.sin(t) * ry], 1), cx, cy, 1, rot)++ @staticmethod+ def rrect_pts(x0, y0, x1, y1, r=20, step=10):+ """rounded rectangle; r is one radius or (top-left, top-right, bottom-right, bottom-left)"""+ tl, tr, br, bl = (r,) * 4 if np.isscalar(r) else r+ out = []++ def edge(p, q):+ n = max(2, int(np.hypot(q[0] - p[0], q[1] - p[1]) / step))+ for t in np.linspace(0, 1, n, endpoint=False): out.append((p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t))++ def arc(cx, cy, rr, a0):+ if rr <= 0: out.append((cx, cy)); return+ for a in np.deg2rad(np.linspace(a0, a0 + 90, max(4, int(rr / 4)), endpoint=False)):+ out.append((cx + np.cos(a) * rr, cy + np.sin(a) * rr))++ edge((x0 + tl, y0), (x1 - tr, y0)); arc(x1 - tr, y0 + tr, tr, -90)+ edge((x1, y0 + tr), (x1, y1 - br)); arc(x1 - br, y1 - br, br, 0)+ edge((x1 - br, y1), (x0 + bl, y1)); arc(x0 + bl, y1 - bl, bl, 90)+ edge((x0, y1 - bl), (x0, y0 + tl)); arc(x0 + tl, y0 + tl, tl, 180)+ return np.array(out, np.float32)++ @staticmethod+ def densify(pts, step=8, closed=True):+ """straight-edged polygon -> many points along its edges (keeps the corners sharp)"""+ P = np.asarray(pts, np.float32)+ Q = np.vstack([P, P[:1]]) if closed else P+ out = []+ for a, b in zip(Q[:-1], Q[1:]):+ n = max(1, int(np.hypot(*(b - a)) / step))+ for t in np.arange(n) / n: out.append(a + (b - a) * t)+ if not closed: out.append(Q[-1])+ return np.array(out, np.float32)++ # ------------------------------------------------------------ paper+ def paper(self, colour=PAPER, grain=1.0, mottle=1.0, fibres=260):+ """cream drawing paper; the grain (lit tooth) shows through everything painted on it"""+ H, W = self.H, self.W+ base = _c(colour)+ col = base[None, None, :] * (1 + 0.055 * mottle * self._mott)[..., None]+ col = col + np.array([0.004, 0.0, -0.006], np.float32) * self._mott[..., None] * 4+ r = np.random.default_rng(self.seed + 17)+ im = Image.new('L', (W, H), 0)+ d = ImageDraw.Draw(im)+ for _ in range(fibres):+ x, y = r.uniform(0, W), r.uniform(0, H)+ a, L = r.uniform(0, np.pi), r.uniform(8, 34)+ bend = r.uniform(-0.5, 0.5)+ pts = [(x + np.cos(a + bend * t) * L * t, y + np.sin(a + bend * t) * L * t) for t in np.linspace(0, 1, 6)]+ d.line(pts, fill=int(r.uniform(90, 200)), width=1)+ fib = blur(np.asarray(im, np.float32) / 255, 0.45)+ self.paperc = (col * (1 - 0.07 * fib[..., None])).astype(np.float32)+ self.grain = (1 + grain * (0.026 * self._bump + 0.016 * (self.tooth - 0.5))).astype(np.float32)++ # ------------------------------------------------------------ the brush pen+ def _dense(self, pts, smooth=True, closed=False, step=1.4):+ """control points -> an evenly spaced centreline (Catmull-Rom through few points, as-is for many)"""+ P = np.asarray(pts, np.float32)+ if smooth and 3 <= len(P) < 60:+ P = _closed_spline(P, 10) if closed else spline(P, per=10)+ P = _resample(P, step, closed)+ return P if len(P) >= 2 else np.vstack([P, P + 0.5])++ def _profile(self, P, width, taper=(10, 22), jitter=1.0, press=0.14, step=1.4):+ """hand wobble (slow sideways drift) and the pressure / width profile along a dense centreline"""+ n = len(P)+ _, N = _normals(P)+ s = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))])+ L = s[-1]+ if jitter:+ P = P + N * (fbm1d(n, max(4, 150 / step), 3, self._seed()) * jitter * 1.6)[:, None]+ w = width * (1 + press * fbm1d(n, max(4, 80 / step), 3, self._seed()))+ if taper:+ w = w * (0.22 + 0.78 * smoothstep(0, max(taper[0], 1e-3), s)) * (0.1 + 0.9 * smoothstep(0, max(taper[1], 1e-3), L - s))+ return P.astype(np.float32), w.astype(np.float32)++ def _prep(self, pts, width, taper=(10, 22), smooth=True, jitter=1.0, press=0.14):+ return self._profile(self._dense(pts, smooth), width, taper, jitter, press)++ def _raster(self, P, w, ss=3):+ """variable-width centreline -> (slices, alpha): quads between offset points + round joins, drawn at ss x"""+ r = float(w.max()) / 2 + 3+ sl = self._box(P[:, 0].min() - r, P[:, 1].min() - r, P[:, 0].max() + r + 1, P[:, 1].max() + r + 1)+ if sl is None: return None, None+ x0, y0 = sl[1].start, sl[0].start+ bw, bh = sl[1].stop - x0, sl[0].stop - y0+ im = Image.new('L', (bw * ss, bh * ss), 0)+ d = ImageDraw.Draw(im)+ Q = (P - np.array([x0, y0], np.float32)) * ss+ R = np.maximum(w * ss / 2, 0.6)+ T, N = _normals(Q)+ A = (Q + N * R[:, None]).tolist(); B = (Q - N * R[:, None]).tolist()+ for i in range(len(Q) - 1):+ d.polygon(A[i] + A[i + 1] + B[i + 1] + B[i], fill=255)+ seg = np.diff(Q, axis=0)+ seg /= np.linalg.norm(seg, axis=1, keepdims=True) + 1e-6+ turn = np.concatenate([[1.0], np.sum(seg[1:] * seg[:-1], 1), [1.0]])+ idx = set(np.flatnonzero(turn < 0.96).tolist()) | set(range(0, len(Q), 3)) | {0, len(Q) - 1}+ Ql, Rl = Q.tolist(), R.tolist()+ for i in idx:+ (x, y), rr = Ql[i], Rl[i]+ d.ellipse([x - rr, y - rr, x + rr, y + rr], fill=255)+ return sl, np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255++ def _pencil_pass(self, P, closed=False, drift=3.2, width=1.7, alpha=0.6, passes=None, kind='rough'):+ """loose blue col-erase pencil along a line: drifts off it, overshoots the ends, runs past closed starts"""+ buf = self._rbuf(self._g(kind))+ r = self.rng+ for _ in range(passes or int(r.integers(1, 3))):+ Q = _resample(P, 2.5)+ if len(Q) < 2: continue+ T, N = _normals(Q)+ n = len(Q)+ off = fbm1d(n, max(4, 90), 3, self._seed()) * drift + r.normal(0, 1.0)+ Q = Q + N * off[:, None] + r.normal(0, 1.4, 2).astype(np.float32)+ if closed:+ k = max(2, int(n * r.uniform(0.04, 0.1)))+ Q = np.vstack([Q, Q[1:k] + r.normal(0, 1.5, 2).astype(np.float32)])+ else:+ e0, e1 = r.uniform(3, 15), r.uniform(3, 15)+ Q = np.vstack([Q[:1] - T[:1] * e0, Q, Q[-1:] + T[-1:] * e1])+ wv = np.full(len(Q), width, np.float32) * (0.8 + 0.4 * r.random())+ sl, a = self._raster(Q, wv, ss=2)+ if sl is None: continue+ a = a * alpha * smoothstep(0.2, 0.7, self.tooth[sl] + 0.22)+ buf[sl] = 1 - (1 - buf[sl]) * (1 - a)++ def sketch(self, pts, closed=False, width=1.7, alpha=0.6, smooth=True, passes=1):+ """construction lines in blue pencil only (guides, centre lines, ellipses): they never get inked"""+ P = np.asarray(pts, np.float32)+ if smooth and 3 <= len(P) < 60: P = _closed_spline(P, 10) if closed else spline(P, per=10)+ self._pencil_pass(P, closed, drift=2.0, width=width, alpha=alpha, passes=passes)++ def line(self, pts, width=6.0, taper=(10, 22), smooth=True, jitter=1.0, press=0.14, kind='ink', rough=True):+ """an open brush-pen line: lands thin, swells, lifts off to a point"""+ P, w = self._prep(pts, width, taper, smooth, jitter, press)+ if rough and self.auto_rough: self._pencil_pass(P)+ sl, a = self._raster(P, w)+ if sl is not None: self._inkon(self._g(kind), sl, a)+ return P++ def lines(self, paths, width=6.0, **kw):+ for p in paths: self.line(p, width, **kw)++ def outline(self, pts, width=7.0, weight=0.35, overlap=0.05, gaps=0, jitter=1.0, press=0.12, taper=(18, 26),+ smooth=None, start=None, kind='ink', rough=True):+ """a closed shape inked in one stroke: the two tapered ends overlap where the pen came back round;+ heavier on the side away from the light. gaps=n leaves n small breaks (open-ended hand inking)."""+ P = np.asarray(pts, np.float32)+ smooth = len(P) < 60 if smooth is None else smooth+ C = self._dense(P, smooth, closed=True)+ n = len(C)+ _, Nl = _normals(np.vstack([C[-1:], C, C[:1]]))+ Nl = Nl[1:-1]+ sign = 1.0 if np.mean(np.sum(Nl * (C - C.mean(0)), 1)) > 0 else -1.0+ out = Nl * sign+ i0 = int(self.rng.integers(n)) if start is None else int(start) % n+ idx = (i0 + np.arange(int(n * (1 + overlap)))) % n+ Pp, O = C[idx], out[idx]+ if rough and self.auto_rough: self._pencil_pass(C, closed=True)+ cuts = [(0, len(Pp))]+ if gaps:+ pos = np.sort(self.rng.uniform(0.15, 0.85, gaps)) * len(Pp)+ cuts, a = [], 0+ for p in pos:+ g = int(self.rng.uniform(5, 12) / 1.4)+ cuts.append((a, int(p))); a = int(p) + g+ cuts.append((a, len(Pp)))+ for a, b in cuts:+ if b - a < 4: continue+ Pr, w = self._profile(Pp[a:b], width, taper, jitter, press)+ w = w * (1 + weight * np.clip(O[a:b] @ (-self.light), -1, 1))+ sl, al = self._raster(Pr, w)+ if sl is not None: self._inkon(self._g(kind), sl, al)+ return C++ def ink_fill(self, shape, kind='ink'):+ """a solid ink area (slots, soles, a very dark pupil that needs no glint)"""+ sl, M = self._region(shape, 2)+ if sl is not None: self._inkon(self._g(kind), sl, M)++ def dot(self, x, y, r=3.0, kind='ink'):+ sl, a = self._raster(np.array([[x - 0.3, y], [x + 0.3, y]], np.float32), np.array([2 * r, 2 * r], np.float32))+ if sl is not None: self._inkon(self._g(kind), sl, a)++ # ------------------------------------------------------------ colour+ def fill(self, shape, colour, slop=None, wander=1.0, drift=0.05, knock=True, kind='flat'):+ """flat colour, painted a little off the lines (shifted by `slop` px, wandering edge); knocks out what is+ behind. Returns the painted area as a Mask (use it as clip= for shade)."""+ slop = self.slop if slop is None else slop+ sl, M = self._region(shape, int(slop + 8))+ if sl is None: return None+ F = M+ if slop:+ a = self.rng.uniform(0, 2 * np.pi)+ F = shift(M, np.cos(a) * slop, np.sin(a) * slop)+ if wander:+ F = smoothstep(0.3, 0.7, blur(F, 1.2) + (self._wob[sl] - 0.5) * 0.5 * wander)+ col = _c(colour)[None, None, :] * (1 + drift * (self._var[sl] - 0.5) * 2)[..., None]+ g = self._g(kind)+ if knock: self._knock(g, sl, np.maximum(M, F), M)+ self._put(g, sl, F, col)+ return Mask(sl, F)++ def shade(self, shape, colour, offset=(12, 12), clip=None, wander=0.6, kind='shade'):+ """a hard cel shadow: the shape minus itself nudged toward the light (offset px away from the light),+ or with offset=None the shape itself; clipped to `clip` (e.g. the Mask returned by fill)"""+ pad = int(max(abs(offset[0]), abs(offset[1])) + 6) if offset else 6+ sl, M = self._region(shape, pad)+ if sl is None: return None+ S = M * (1 - shift(M, -offset[0], -offset[1])) if offset else M+ S = S * self._crop(clip, sl)+ if wander:+ S = smoothstep(0.35, 0.65, blur(S, 0.8) + (self._wob[sl] - 0.5) * 0.3 * wander) * (S > 0.02)+ self._put(self._g(kind), sl, S, colour)+ return Mask(sl, S)++ def glint(self, pts, width=7.0, colour=WHITE, taper=(8, 14), smooth=True, kind='shade'):+ """a white highlight: a tapered stroke of opaque paint"""+ P, w = self._prep(pts, width, taper, smooth, 0.3, 0.1)+ sl, a = self._raster(P, w)+ if sl is not None: self._put(self._g(kind), sl, a, colour)++ def shape(self, pts, colour, shade=None, shade2=None, width=7.0, weight=0.35, slop=None, gaps=0, kind=('flat', 'ink')):+ """fill + up to two cel shadows (colour, dx, dy) + brush outline, in that order"""+ F = self.fill(pts, colour, slop, kind=kind[0])+ for sh in (shade, shade2):+ if sh: self.shade(pts, sh[0], (sh[1], sh[2]), clip=F)+ self.outline(pts, width, weight, gaps=gaps, kind=kind[1])+ return F++ def _streaks(self, sl, angle, spacing=2.6):+ xx, yy = self.XX[sl], self.YY[sl]+ a = np.deg2rad(angle)+ along = xx * np.cos(a) - yy * np.sin(a)+ k = (xx * np.sin(a) + yy * np.cos(a)) / spacing+ k0 = np.floor(k.min())+ n = int(k.max() - k0) + 3+ r1, r2 = self.rng.random(n), self.rng.random(n)+ j = k - k0+ s = np.interp(j, np.arange(n), r1)+ mod = 0.5 + 0.5 * np.sin(along / (18 + 30 * np.interp(j, np.arange(n), r2)) + np.interp(j, np.arange(n), r2) * 40)+ return (0.62 * s + 0.38 * mod).astype(np.float32)++ def crayon(self, shape, colour, pressure=0.6, angle=35, soft=5, edge=1.0, alpha=0.95, clip=None, kind='texture'):+ """wax crayon: only the tops of the tooth take colour, streaked along the scribble direction, ragged+ edge. pressure may be a full-size array (a gradient)."""+ sl, M = self._region(shape, int(soft * 3 + 6))+ if sl is None: return+ E = smoothstep(0.25, 0.75, blur(M, soft) + (self._wob[sl] - 0.5) * 0.7 * edge)+ tex = 0.55 * self.tooth[sl] + 0.45 * self._streaks(sl, angle)+ p = pressure[sl] if isinstance(pressure, np.ndarray) else pressure+ thr = 1 - np.asarray(p, np.float32)+ a = E * smoothstep(thr - 0.13, thr + 0.13, tex) * alpha * self._crop(clip, sl)+ self._put(self._g(kind), sl, a, colour)++ def blush(self, cx, cy, rx=16, ry=9, colour=PINK, rot=0.0, kind='shade'):+ self.crayon(self.ellipse_pts(cx, cy, rx, ry, rot), colour, pressure=0.72, angle=40 + rot, soft=2.5, edge=0.4, kind=kind)++ def tone(self, shape, colour=INK, cell=9.0, angle=45, amount=0.22, alpha=1.0, clip=None, kind='texture'):+ """screentone: a rotated grid of dots; amount (0..1 ink coverage) may be a full-size array"""+ sl, M = self._region(shape, 2)+ if sl is None: return+ xx, yy = self.XX[sl], self.YY[sl]+ a = np.deg2rad(angle)+ u = (xx * np.cos(a) - yy * np.sin(a)) / cell+ v = (xx * np.sin(a) + yy * np.cos(a)) / cell+ d = np.hypot(u - np.round(u), v - np.round(v)) * cell+ amt = amount[sl] if isinstance(amount, np.ndarray) else amount+ rad = cell * np.sqrt(np.clip(amt, 0, 1) / np.pi)+ dots = np.clip(rad - d + 0.5, 0, 1) * M * self._crop(clip, sl) * alpha+ self._put(self._g(kind), sl, dots, colour)++ def hatch(self, shape, angle=-55, spacing=11, width=2.8, jitter=0.5, trim=5, kind='texture'):+ """ink hatching clipped to a mask: parallel short strokes with uneven, tapered ends (contact shadows)"""+ sl, M = self._region(shape, 4)+ if sl is None: return+ y0, x0 = sl[0].start, sl[1].start+ h, w = M.shape+ a = np.deg2rad(angle)+ d = np.array([np.cos(a), -np.sin(a)], np.float32)+ p = np.array([-d[1], d[0]], np.float32)+ corners = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32)+ pr, dr = corners @ p, corners @ d+ ts = np.arange(dr.min(), dr.max(), 1.5, dtype=np.float32)+ for o in np.arange(pr.min() + spacing * 0.5, pr.max(), spacing):+ o = o + self.rng.uniform(-0.12, 0.12) * spacing+ pts = o * p + ts[:, None] * d+ ix, iy = np.round(pts[:, 0]).astype(int), np.round(pts[:, 1]).astype(int)+ ok = (ix >= 0) & (iy >= 0) & (ix < w) & (iy < h)+ inside = np.zeros(len(ts), bool)+ inside[ok] = M[iy[ok], ix[ok]] > 0.5+ edges = np.flatnonzero(np.diff(np.concatenate([[0], inside.astype(np.int8), [0]])))+ for s0, s1 in zip(edges[::2], edges[1::2]):+ s0 = s0 + int(self.rng.uniform(0, trim) / 1.5); s1 = s1 - int(self.rng.uniform(0, trim) / 1.5)+ if s1 - s0 < 4: continue+ seg = pts[s0:s1] + np.array([x0, y0], np.float32)+ self.line(seg, width, taper=(3, 6), smooth=False, jitter=jitter, kind=kind, rough=False)++ # ------------------------------------------------------------ faces and limbs+ def face(self, cx, cy, size=100, mood='happy', rot=0.0, blush=True, width=None, kind=('flat', 'ink')):+ """a face on anything. size ~ the face width in px. moods: happy (^ ^ and an open grin with a tongue),+ wow (round eyes, little o mouth), sleepy (closed eyes, small smile), smile (dot eyes, smile), wink"""+ u = size / 100.0+ lw = width or max(3.0, 5.4 * u)+ X = lambda pts: self.place(pts, cx, cy, u, rot)+ ex, ey = 34, -8++ def dot_eye(sx):+ e = X(self.ellipse_pts(sx * ex, ey, 7.5, 10.5))+ self.fill(e, INK, slop=0.6, wander=0.2, kind=kind[0])+ self.outline(e, lw * 0.5, 0, kind=kind[1], rough=False)+ gl = X(self.ellipse_pts(sx * ex - 2.2, ey - 4.2, 2.6, 3.2))+ self.fill(gl, WHITE, slop=0, wander=0, knock=False, kind='shade')++ if mood in ('happy', 'grin', 'wink'):+ for sx in (-1, 1):+ if mood == 'wink' and sx == 1:+ dot_eye(sx); continue+ self.line(X([(sx * ex - 12, ey + 6), (sx * ex, ey - 7), (sx * ex + 12, ey + 6)]), lw, (5, 6), kind=kind[1])+ top = [(-24, 14), (-10, 17), (10, 17), (24, 14)]+ bot = [(22, 18), (12, 38), (0, 43), (-12, 38), (-22, 18)]+ mouth = X(_closed_spline(top + bot, 8))+ F = self.fill(mouth, '#6b2723', slop=1.5, kind=kind[0])+ tongue = X(self.ellipse_pts(1, 40, 15, 10))+ self.fill(self.mask(tongue) * self._full(F), '#ef6b5d', slop=0, wander=0.3, knock=False, kind='shade')+ self.outline(mouth, lw * 0.9, 0.2, overlap=0.03, kind=kind[1])+ elif mood == 'wow':+ for sx in (-1, 1): dot_eye(sx)+ o = X(self.ellipse_pts(0, 27, 9, 11))+ self.fill(o, '#6b2723', slop=1, kind=kind[0])+ self.outline(o, lw * 0.85, 0.2, kind=kind[1])+ elif mood == 'sleepy':+ for sx in (-1, 1):+ self.line(X([(sx * ex - 12, ey - 2), (sx * ex, ey + 6), (sx * ex + 12, ey - 2)]), lw * 0.9, (5, 6), kind=kind[1])+ self.line(X([(sx * ex + sx * 12, ey - 1), (sx * ex + sx * 17, ey - 5)]), lw * 0.55, (2, 4), kind=kind[1])+ self.line(X([(-8, 22), (0, 27), (8, 22)]), lw * 0.8, (4, 5), kind=kind[1])+ else: # smile+ for sx in (-1, 1): dot_eye(sx)+ self.line(X([(-17, 17), (0, 29), (17, 17)]), lw, (5, 6), kind=kind[1])+ if blush:+ for sx in (-1, 1):+ p = X([(sx * (ex + 11), ey + 23)])[0]+ self.blush(p[0], p[1], 15 * u, 8.5 * u, rot=rot)++ def _full(self, m):+ full = np.zeros((self.H, self.W), np.float32)+ if m is not None: full[m.sl] = m.a+ return full++ def arm(self, p0, p1, bend=0.25, width=5.5, hand=22, glove=WHITE, thumb=1, kind=('flat', 'ink')):+ """a rubber-hose arm: one even ink line from the shoulder p0, and a round white mitten at p1 (thumb on+ side thumb=+1 / -1 of the arm direction, a cuff line, two finger creases)"""+ from core import curve+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ L = float(np.hypot(*(p1 - p0)))+ self.line(curve(p0, p1, bend * L, n=16), width, taper=(3, 3), press=0.05, kind=kind[1])+ d = (p1 - p0) / (L + 1e-6)+ ang = np.degrees(np.arctan2(-d[1], d[0]))+ hx, hy = p1 + d * hand * 0.35+ at = lambda pts: self.place(pts, hx, hy, hand, ang)+ th = at(self.ellipse_pts(0.05, -0.78 * thumb, 0.42, 0.34, 25 * thumb)) # thumb lobe, behind the palm+ self.fill(th, glove, slop=1, kind=kind[0])+ self.outline(th, width * 0.75, 0.2, kind=kind[1])+ palm = at(self.ellipse_pts(0.1, 0.05, 1.0, 0.86))+ F = self.fill(palm, glove, slop=1.5, kind=kind[0])+ self.shade(palm, '#dcd9e2', (-hand * 0.0 + 4, 5), clip=F)+ self.outline(palm, width * 0.8, 0.3, kind=kind[1])+ self.line(at([(-0.72, -0.62), (-0.95, 0.0), (-0.72, 0.62)]), width * 0.55, (3, 4), kind=kind[1])+ for v in (0.12, 0.42):+ self.line(at([(0.55, v * thumb), (0.98, v * thumb * 0.9)]), width * 0.45, (2, 4), smooth=False, kind=kind[1])++ # ------------------------------------------------------------ effects (overlay group 'fx' unless fx=False)+ def _k(self, fx, base):+ return 'fx' if fx else base++ def sparkle(self, x, y, r=24, colour=YELLOW, rot=8, width=None, fx=True):+ """a 4-point sparkle (astroid with concave sides), filled and outlined"""+ t = np.linspace(0, 2 * np.pi, 160, endpoint=False)+ c, s = np.cos(t), np.sin(t)+ e = 3.1+ pts = self.place(np.stack([np.sign(c) * np.abs(c) ** e * 0.9, np.sign(s) * np.abs(s) ** e * 1.2], 1), x, y, r, rot)+ self.fill(pts, colour, slop=r * 0.08, kind=self._k(fx, 'flat'))+ self.outline(pts, width or max(2.4, r * 0.11), 0.2, smooth=False, overlap=0.03, kind=self._k(fx, 'ink'))++ def speed_lines(self, p0, p1, angle=90, n=6, length=(60, 140), width=4.5, fx=True):+ """motion lines: n strokes starting along the segment p0-p1, heading `angle` (ccw, 90 = up)"""+ a = np.deg2rad(angle)+ d = np.array([np.cos(a), -np.sin(a)], np.float32)+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ for t in (np.arange(n) + self.rng.uniform(0.2, 0.8, n)) / n:+ q = p0 + (p1 - p0) * t + d * self.rng.uniform(0, 18)+ L = self.rng.uniform(*length)+ self.line([q, q + d * L * 0.5, q + d * L], width * self.rng.uniform(0.75, 1.15), (L * 0.3, L * 0.45),+ smooth=False, jitter=0.6, kind=self._k(fx, 'ink'))++ def steam(self, x, y, h=120, amp=14, width=4.5, turns=1.3, fx=True):+ """a steam wisp rising from (x, y): an S-curve that widens as it rises, tapered both ends"""+ t = np.linspace(0, 1, 24)+ ph = self.rng.uniform(0, 2 * np.pi)+ pts = np.stack([x + amp * (0.4 + t) * np.sin(2 * np.pi * turns * t + ph), y - h * t], 1)+ self.line(pts, width, (h * 0.25, h * 0.35), kind=self._k(fx, 'ink'))++ def puff(self, cx, cy, r, colour=WHITE, bumps=6, width=5.0, curl=True, shadow='#dcdbe3', rot=0.0, squash=0.85, fx=True):+ """a scalloped cloud / smoke puff with an inner curl line and a cel shadow"""+ th = np.linspace(0, 2 * np.pi, 260, endpoint=False)+ amp = self.rng.uniform(0.8, 1.2, bumps)+ k = (th + np.deg2rad(rot)) / (2 * np.pi) * bumps+ rr = r * (0.8 + 0.2 * np.abs(np.sin(np.pi * k)) ** 0.7 * amp[np.floor(k).astype(int) % bumps])+ pts = np.stack([cx + rr * np.cos(th), cy + rr * np.sin(th) * squash], 1)+ F = self.fill(pts, colour, slop=r * 0.04, kind=self._k(fx, 'flat'))+ if shadow: self.shade(pts, shadow, (r * 0.16, r * 0.2), clip=F, kind=self._k(fx, 'shade'))+ self.outline(pts, width, 0.3, smooth=False, kind=self._k(fx, 'ink'))+ if curl:+ a0 = self.rng.uniform(15, 45)+ arc = self.ellipse_pts(cx, cy, r * 0.55, r * 0.55 * squash, 0, a0, a0 + 70)+ self.line(arc, width * 0.7, (6, 10), kind=self._k(fx, 'ink'))+ return pts++ def burst(self, cx, cy, rx, ry, colour=RED, spikes=14, depth=0.3, rot=0.0, width=7.0, shade=None, fx=True):+ """a comic starburst with uneven spikes; returns its outline points"""+ n = 2 * spikes+ th = np.linspace(0, 2 * np.pi, n, endpoint=False) + np.deg2rad(rot) + self.rng.uniform(-0.08, 0.08, n)+ rr = np.where(np.arange(n) % 2 == 0, self.rng.uniform(0.9, 1.1, n), (1 - depth) * self.rng.uniform(0.94, 1.04, n))+ pts = self.densify(np.stack([cx + rx * rr * np.cos(th), cy + ry * rr * np.sin(th)], 1), 7)+ F = self.fill(pts, colour, kind=self._k(fx, 'flat'))+ if shade: self.shade(pts, shade, (rx * 0.06, ry * 0.08), clip=F, kind=self._k(fx, 'shade'))+ self.outline(pts, width, 0.3, smooth=False, overlap=0.03, kind=self._k(fx, 'ink'))+ return pts++ def crumbs(self, cx, cy, n=8, spread=(150, 80), size=(5, 10), colour='#c9803c', width=2.6, avoid=None, fx=True):+ """little flying bits: irregular chunks, each outlined; avoid = a full-size mask they must not land on"""+ placed, tries = 0, 0+ while placed < n and tries < n * 40:+ tries += 1+ a = self.rng.uniform(0, 2 * np.pi); rr = np.sqrt(self.rng.uniform(0.15, 1))+ x, y = cx + np.cos(a) * spread[0] * rr, cy + np.sin(a) * spread[1] * rr+ if avoid is not None and (not (0 <= x < self.W and 0 <= y < self.H) or avoid[int(y), int(x)] > 0.1): continue+ placed += 1+ s = self.rng.uniform(*size)+ k = int(self.rng.integers(4, 6))+ th = np.sort(self.rng.uniform(0, 2 * np.pi, k))+ pts = np.stack([x + np.cos(th) * s * self.rng.uniform(0.6, 1.2, k), y + np.sin(th) * s * self.rng.uniform(0.6, 1.2, k)], 1)+ pts = self.densify(pts, 3)+ self.fill(pts, colour, slop=1, kind=self._k(fx, 'flat'))+ self.outline(pts, width, 0, smooth=False, rough=False, kind=self._k(fx, 'ink'))++ def pop_lines(self, cx, cy, r0, r1, angles, width=5.0, fx=True):+ """emphasis ticks radiating from a point (surprise, a sudden sound)"""+ for a in angles:+ t = np.deg2rad(a)+ d = np.array([np.cos(t), -np.sin(t)])+ self.line([(cx + d[0] * r0, cy + d[1] * r0), (cx + d[0] * r1, cy + d[1] * r1)], width, (4, 8), smooth=False,+ jitter=0.3, kind=self._k(fx, 'ink'))++ # ------------------------------------------------------------ lettering (overlay group 'type')+ def _word(self, s, size, font=None, tilt=3.0, bounce=0.04, spacing=0.0, scale=0.04):+ """hand-set word mask: every glyph a little tilted, bounced and resized. -> (mask, pad, baseline, width)"""+ r = np.random.default_rng(self._seed())+ items = []+ for ch in s:+ sz = size * (1 + r.uniform(-scale, scale))+ f = _font(_pick(ch, font), sz)+ adv = (size * 0.3 if not ch.strip() else f.getlength(ch)) + spacing+ items.append((ch, f, sz, adv))+ total = sum(it[3] for it in items) - spacing+ pad = int(size * 0.55) + 12+ Wc, Hc = int(total + 2 * pad), int(size * 1.55 + 2 * pad)+ base = pad + size * 1.08+ canvas = np.zeros((Hc, Wc), np.float32)+ x = float(pad)+ for ch, f, sz, adv in items:+ if ch.strip():+ cw, chh = int(adv + sz * 1.2), int(sz * 2.2)+ im = Image.new('L', (cw, chh), 0)+ ox, oy = sz * 0.6, sz * 1.45+ ImageDraw.Draw(im).text((ox, oy), ch, font=f, fill=255, anchor='ls')+ im = im.rotate(r.uniform(-tilt, tilt), Image.BICUBIC, center=(ox + adv / 2, oy - sz * 0.36))+ a = np.asarray(im, np.float32) / 255+ px, py = int(round(x - ox)), int(round(base + r.uniform(-bounce, bounce) * size - oy))+ ya, xa = max(0, py), max(0, px)+ yb, xb = min(Hc, py + chh), min(Wc, px + cw)+ if yb > ya and xb > xa:+ np.maximum(canvas[ya:yb, xa:xb], a[ya - py:yb - py, xa - px:xb - px], out=canvas[ya:yb, xa:xb])+ x += adv+ return canvas, pad, base, total++ def _place_word(self, canvas, pad, base, total, x, y, anchor, rot):+ if rot:+ ax = pad + total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor]+ canvas = np.asarray(Image.fromarray(canvas).rotate(rot, Image.BICUBIC, center=(ax, base)), np.float32)+ x0 = int(round(x - pad - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor]))+ y0 = int(round(y - base))+ h, w = canvas.shape+ sl = self._box(x0, y0, x0 + w, y0 + h)+ if sl is None: return None, None+ return sl, canvas[sl[0].start - y0:sl[0].stop - y0, sl[1].start - x0:sl[1].stop - x0]++ def text_width(self, s, size, font=None, spacing=0.0):+ return sum((size * 0.3 if not ch.strip() else _font(_pick(ch, font), size).getlength(ch)) + spacing for ch in s) - spacing++ def letter(self, s, x, y, size, fill=YELLOW, depth=(5, 7), depth_colour=RED, outline=None, font=None, anchor='l',+ rot=0.0, tilt=4.0, bounce=0.05, spacing=0.0, highlight=True, kind='type'):+ """display lettering: chunky letters, each a little tilted and bounced, an extruded shadow in+ depth_colour, a white rim light on the upper-left edges and a thick ink outline round it all.+ (x, y) is the baseline point at `anchor` ('l', 'm', 'r')."""+ canvas, pad, base, total = self._word(s, size, font, tilt, bounce, spacing)+ sl, M = self._place_word(canvas, pad, base, total, x, y, anchor, rot)+ if sl is None: return+ ow = outline or max(3.0, size * 0.065)+ E = np.zeros_like(M)+ if depth:+ k = int(max(abs(depth[0]), abs(depth[1]))) + 1+ for i in range(1, k + 1): np.maximum(E, shift(M, depth[0] * i / k, depth[1] * i / k), out=E)+ U = np.maximum(M, E)+ ring = np.clip(_dilate(U, ow) - U, 0, 1)+ inner = np.clip(_dilate(M, max(2, ow * 0.45)) - M, 0, 1) * E+ occ = _dilate(U, ow)+ g = self._g(kind)+ self._knock(g, sl, occ, occ)+ if depth: self._put(g, sl, E, depth_colour)+ col = _c(fill)[None, None, :] * (1 + 0.05 * (self._var[sl] - 0.5) * 2)[..., None]+ self._put(g, sl, M, col)+ if highlight:+ hl = np.clip(M - shift(M, 2, 3), 0, 1) * smoothstep(0.35, 0.6, self._wob[sl])+ self._put(g, sl, hl * 0.95, WHITE)+ self._inkon(g, sl, np.maximum(ring, inner))++ def note(self, s, x, y, size, colour=INK, font=None, anchor='l', rot=0.0, tilt=3.0, bounce=0.04, spacing=0.0,+ bold=0, kind='type'):+ """hand-lettered text in ink (or paint, if colour is not INK); (x, y) = baseline point at anchor"""+ canvas, pad, base, total = self._word(s, size, font, tilt, bounce, spacing)+ if bold: canvas = _dilate(canvas, bold)+ sl, M = self._place_word(canvas, pad, base, total, x, y, anchor, rot)+ if sl is None: return total+ if isinstance(colour, str) and colour.lower() == INK:+ self._inkon(self._g(kind), sl, M)+ else:+ self._put(self._g(kind), sl, M, colour)+ return total++ def pencil_note(self, s, x, y, size=26, anchor='l', rot=0.0, colour=PENCIL, alpha=0.8):+ """blue-pencil writing on the sheet (drawing numbers, timing notes): grainy, shown with the rough"""+ canvas, pad, base, total = self._word(s, size, 'comic', 2.0, 0.03, 1.0)+ sl, M = self._place_word(canvas, pad, base, total, x, y, anchor, rot)+ if sl is None: return+ a = M * alpha * smoothstep(0.2, 0.62, self.tooth[sl] + 0.2)+ self._put(self._g('rough'), sl, a, colour)++ def arrow(self, pts, width=4.5, head=22, spread=30, smooth=True, kind='type'):+ """a hand-drawn arrow: a tapered line and two flicks meeting at the tip"""+ P = self.line(pts, width, taper=(8, 3), smooth=smooth, kind=kind)+ tip = P[-1]+ back = P[max(0, len(P) - 12)]+ a = np.arctan2(back[1] - tip[1], back[0] - tip[0])+ for sgn in (-1, 1):+ b = a + sgn * np.deg2rad(spread)+ self.line([(tip[0] + np.cos(b) * head, tip[1] + np.sin(b) * head), tuple(tip)], width, (4, 2), smooth=False,+ jitter=0.3, kind=kind)++ def badge(self, x, y, r, label, colour=YELLOW, size=None, width=4.5, kind='type'):+ """a numbered round badge: filled disc, outline, the label in ink"""+ e = self.ellipse_pts(x, y, r, r)+ self.fill(e, colour, slop=2, kind=kind)+ self.outline(e, width, 0.3, kind=kind)+ self.note(label, x, y + (size or r * 1.1) * 0.36, size or r * 1.1, anchor='m', tilt=0, bounce=0, kind=kind)++ # ------------------------------------------------------------ output+ def _field(self, k, amp):+ r = np.random.default_rng(self.seed * 7919 + k * 104729 + 1)++ def smooth(cell):+ gh, gw = self.H // cell + 3, self.W // cell + 3+ a = Image.fromarray(r.random((gh, gw)).astype(np.float32)).resize((gw * cell, gh * cell), Image.BICUBIC)+ return (np.asarray(a, np.float32)[:self.H, :self.W] - 0.5) * 2++ return [amp * (0.8 * smooth(44) + 0.45 * smooth(150)) for _ in range(2)] # (dx, dy)++ def _warp(self, arrs, fx, fy):+ x = np.clip(self.XX + fx, 0, self.W - 1.001); y = np.clip(self.YY + fy, 0, self.H - 1.001)+ x0, y0 = x.astype(np.int32), y.astype(np.int32)+ wx, wy = x - x0, y - y0+ out = []+ for a in arrs:+ X, Y = (wx[..., None], wy[..., None]) if a.ndim == 3 else (wx, wy)+ out.append((a[y0, x0] * (1 - X) + a[y0, x0 + 1] * X) * (1 - Y) + (a[y0 + 1, x0] * (1 - X) + a[y0 + 1, x0 + 1] * X) * Y)+ return out++ def composite(self, show=None, rough=None, boil=0):+ """show: groups to include (None = all); rough: pencil strength (default 0.3); boil: which retrace"""+ H, W = self.H, self.W+ vis = lambda g: show is None or g in show+ covers = [(self._prio(g), cv) for g, cv in self.cover.items() if vis(g)]++ def knocked(g, arr, which):+ for pg, cv in covers:+ if self._prio(g) < pg:+ k = 1 - cv[which]+ arr = arr * (k[..., None] if arr.ndim == 3 else k)+ return arr++ PC = np.zeros((H, W, 3), np.float32); PA = np.zeros((H, W), np.float32)+ for g in sorted(self.paint, key=lambda g: (self._prio(g), self.created.index(g))):+ if not vis(g): continue+ pc, pa = knocked(g, self.paint[g][0], 0), knocked(g, self.paint[g][1], 0)+ PC = PC * (1 - pa[..., None]) + pc; PA = PA * (1 - pa) + pa+ IA = np.zeros((H, W), np.float32)+ for g, ia in self.ink.items():+ if vis(g): IA = 1 - (1 - IA) * (1 - knocked(g, ia, 1))+ R = np.zeros((H, W), np.float32)+ for g, rb in self.pencil.items():+ if vis(g): R = 1 - (1 - R) * (1 - rb)+ R = R * (0.3 if rough is None else rough)+ if self.boil: # the ink is re-traced, colour and pencil stay+ fx, fy = self._field(boil, self.boil)+ IA, = self._warp([IA], fx, fy)+ out = self.paperc * (1 - R[..., None] * (1 - _c(PENCIL)))+ out = out * (1 - PA[..., None]) + PC+ out = out * (1 + (self.grain - 1) * (1 - 0.55 * PA))[..., None] # paint fills the tooth a little+ out = out * (1 - IA[..., None]) + _c(INK) * IA[..., None]+ return Image.fromarray((np.clip(out, 0, 1) * 255).astype(np.uint8))++ def stage(self, name, show=None, rough=None):+ """snapshot for the draw-on animation; each one is a fresh retrace (the lines boil)"""+ self.stages.append((name, self.composite(show, rough, boil=len(self.stages) + 1)))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality)+ else: img.save(path)+ if stages_dir:+ import os+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/flatvector.py b/lib/flatvector.pynew file mode 100644index 0000000..e8a3285--- /dev/null+++ b/lib/flatvector.py@@ -0,0 +1,943 @@+"""flatvector — modern flat vector illustration: geometric shapes, no outlines, a small saturated palette, volume+built from overlapping blocks of flat colour, a whisper of print grain, and faceless grown-up people+(numpy + Pillow only).++Model: an artboard in a vector app, not a canvas with paint on it.+ shapes every mark is a closed geometric shape with a crisp anti-aliased edge: circles, ellipses, rounded+ rectangles (per-corner radii), tapered capsules (limbs, stems, cords), polygons whose corners are+ filleted with true arcs, ring segments and pies, leaves (a vesica between two points). A shape is a+ `Mask`: a coverage patch plus its offset on the artboard, so union `|`, intersection `&`,+ difference `-` and `moved()` only touch the overlap of bounding boxes -- a picture of a thousand+ shapes stays fast.+ no lines there are no outlines. Two neighbouring shapes are told apart only by value and hue, so every+ object is planned against what sits behind it (a cream shelf on a blue wall, a mustard coat on a+ cream shelf). Thin things (cords, rails, steam, dashes) are themselves filled capsules.+ palette five to seven flat hues (here INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM). Every other colour+ is a *tone* of one of them: `tone(c, -k)` mixes toward the palette's ink, `tone(c, +k)` toward its+ cream. Shadows are never grey or black -- they are the ink mixed in, so they stay in the family.+ volume flat colour blocks stacked on top of each other, the way you would cut them in a vector app:+ `shade()` lays a darker block on the side away from the light, cut out as "the shape minus a+ copy of itself nudged toward the light" (a crisp crescent that follows the silhouette);+ `plane()` cuts an object with a straight line (the side face of a box, the dark half of a leaf);+ `glint()` is the same crescent in a lighter tone on the lit side; `cast()` drops a hard-edged+ flat shadow onto whatever is already underneath (it multiplies by an ink tint, so a shadow that+ falls across three colours darkens each in its own hue). No gradients, no blur.+ light a lamp's beam or a patch of low sun is one translucent flat shape (`fill(..., alpha)`), its alpha+ lightly broken by grain so it reads as light, not as a pane of glass.+ grain the finished artboard gets a very light monochrome print grain (about 1% in value, a little+ clumpy), just enough to stop large flat fields looking like a screen.+ people simplified, faceless, adult proportions (7.5 heads tall): a skeleton of hip, shoulders, elbows,+ wrists, knees and ankles driven by joint angles, or by hand / foot targets (two-bone IK: elbows+ drop, knees go forward); a 3/4 torso (shoulders wider than waist, rounded+ shoulder fillets), tapered limbs, mitten hands, flat shoes; a head that is one ellipse whose hair+ is "a slightly bigger ellipse minus the face ellipse nudged forward and down" (plus a bun, bob,+ long panel or pony). The far arm and far leg are one tone darker, so the body turns in space+ without a single line. Clothes: top, trousers or skirt, coat, apron, tote bag.+ objects a row of book spines (varied heights and widths, bands and a title dash in tones of the spine's+ own colour, a pile lying flat, the neighbour of a taken-out book tipped into the gap, the last book+ of a short row leaning on the side panel, each dropping a flat shadow on the shelf back), a single+ book (closed or open),+ potted plants (split two-tone leaves), a pendant lamp with a flat beam, a sitting cat, clouds,+ sun, dashed motion paths, four-point sparkles, and set lettering (geometric sans + CJK sans).+Angles: `rot` for shapes is degrees counter-clockwise; a person's joint angles are degrees measured from+"straight down", positive toward the way the person faces.++ from flatvector import FlatVector, INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM+ fv = FlatVector(1920, 1080, seed=3)+ fv.backdrop(BLUE)+ floor = fv.rect(0, 880, 1920, 1080); fv.fill(floor, fv.tone(MUSTARD, -0.3))+ sofa = fv.rrect(1200, 700, 1700, 900, (60, 60, 12, 12)); fv.cast(sofa, 30, 0, clip=floor); fv.fill(sofa, TEAL)+ fv.shade(sofa, 0.2, depth=40) # a darker block on the side away from the light+ p = fv.person((1450, 760), 400, facing=-1, sit=True, top=CORAL, hair_style='bun')+ fv.book(*p['hand'], 90, 60, rot=10, colour=MUSTARD, open=True)+ fv.pendant(1450, 0, 320, 70, beam_to=(1300, 1600, 760))+ fv.text('周末 WEEKEND', 120, 160, 64, CREAM)+ fv.save('out.jpg')+"""+import glob+import os+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, spline, noise2d, load_font++INK, BLUE, CORAL, MUSTARD, TEAL, PEACH, CREAM = '#1e1b45', '#3346d3', '#ff6150', '#ffb838', '#19b39a', '#f6b39b', '#fbf1df'+PALETTE = dict(ink=INK, blue=BLUE, coral=CORAL, mustard=MUSTARD, teal=TEAL, peach=PEACH, cream=CREAM)+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ if isinstance(c, str): return hexc(PALETTE.get(c, c))+ return np.asarray(c, np.float32)+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++# ---------------------------------------------------------------- fonts (local list; falls back to core.load_font)+_FONTS = {+ 'geo': [('/System/Library/Fonts/Supplemental/Futura.ttc', 2), ('/System/Library/Fonts/Avenir Next.ttc', 0),+ ('/usr/share/fonts/**/URWGothic-Demi.*', 0), ('/usr/share/fonts/**/Montserrat-Bold.ttf', 0),+ ('C:/Windows/Fonts/GOTHICB.TTF', 0), ('C:/Windows/Fonts/arialbd.ttf', 0)],+ 'geo_medium': [('/System/Library/Fonts/Supplemental/Futura.ttc', 0), ('/System/Library/Fonts/Avenir Next.ttc', 5),+ ('/usr/share/fonts/**/URWGothic-Book.*', 0), ('C:/Windows/Fonts/GOTHIC.TTF', 0), ('C:/Windows/Fonts/arial.ttf', 0)],+ 'cjk': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 2), ('/System/Library/Fonts/STHeiti Medium.ttc', 1),+ ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0), ('/usr/share/fonts/**/NotoSansCJK*.tt[cf]', 0),+ ('C:/Windows/Fonts/msyhbd.ttc', 0), ('C:/Windows/Fonts/msyh.ttc', 0)],+ 'cjk_light': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 0), ('/System/Library/Fonts/STHeiti Light.ttc', 1),+ ('/usr/share/fonts/**/NotoSansCJK*Regular*.tt[cf]', 0), ('C:/Windows/Fonts/msyh.ttc', 0)],+}+_FONT_CACHE = {}+++def font(style, size):+ """PIL font for 'geo' (geometric sans bold), 'geo_medium', 'cjk' (CJK sans bold), 'cjk_light';+ any other name goes to core.load_font (sans, sans_bold, rounded, ...). $INKPAINT_FONT_<STYLE> overrides."""+ key = (style, int(size))+ if key in _FONT_CACHE: return _FONT_CACHE[key]+ f = None+ env = os.environ.get('INKPAINT_FONT_' + style.upper())+ cands = ([(env, 0)] if env and os.path.exists(env) else []) + _FONTS.get(style, [])+ for pat, idx in cands:+ for p in glob.glob(pat, recursive=True):+ try:+ f = ImageFont.truetype(p, int(size), index=idx); break+ except OSError:+ pass+ if f: break+ if f is None:+ f = load_font({'geo': 'sans_bold', 'geo_medium': 'sans', 'cjk': 'cjk_sans', 'cjk_light': 'cjk_sans'}.get(style, style), size)+ _FONT_CACHE[key] = f+ return f+++# ---------------------------------------------------------------- Mask: a coverage patch with an offset+class Mask:+ """anti-aliased coverage `a` (0..1, float32) whose top-left pixel sits at artboard (x0, y0).+ a | b union, a & b intersection, a - b difference, a * k fade, a.moved(dx, dy) nudge (free)."""+ __slots__ = ('a', 'x0', 'y0')++ def __init__(self, a, x0=0, y0=0):+ self.a, self.x0, self.y0 = np.asarray(a, np.float32), int(x0), int(y0)++ @property+ def x1(self): return self.x0 + self.a.shape[1]++ @property+ def y1(self): return self.y0 + self.a.shape[0]++ @property+ def empty(self): return self.a.size == 0 or not self.a.any()++ def on(self, x0, y0, x1, y1):+ """this mask sampled on the box [x0, x1) x [y0, y1) (zero outside itself)"""+ out = np.zeros((max(0, y1 - y0), max(0, x1 - x0)), np.float32)+ ix0, iy0, ix1, iy1 = max(x0, self.x0), max(y0, self.y0), min(x1, self.x1), min(y1, self.y1)+ if ix1 > ix0 and iy1 > iy0:+ out[iy0 - y0:iy1 - y0, ix0 - x0:ix1 - x0] = self.a[iy0 - self.y0:iy1 - self.y0, ix0 - self.x0:ix1 - self.x0]+ return out++ def __or__(self, o):+ if o is None or o.a.size == 0: return self+ if self.a.size == 0: return o+ b = (min(self.x0, o.x0), min(self.y0, o.y0), max(self.x1, o.x1), max(self.y1, o.y1))+ return Mask(np.maximum(self.on(*b), o.on(*b)), b[0], b[1])++ def __and__(self, o):+ b = (max(self.x0, o.x0), max(self.y0, o.y0), min(self.x1, o.x1), min(self.y1, o.y1))+ if b[2] <= b[0] or b[3] <= b[1]: return Mask(np.zeros((0, 0)), 0, 0)+ return Mask(self.on(*b) * o.on(*b), b[0], b[1])++ def __sub__(self, o):+ if o is None or o.a.size == 0: return self+ return Mask(self.a * (1 - o.on(self.x0, self.y0, self.x1, self.y1)), self.x0, self.y0)++ def __mul__(self, k):+ return Mask(self.a * k, self.x0, self.y0)++ def moved(self, dx, dy):+ return Mask(self.a, self.x0 + int(round(dx)), self.y0 + int(round(dy)))++ def grown(self, r):+ """dilate (r > 0) or erode (r < 0) by about |r| px, keeping a crisp edge"""+ p = int(abs(r)) + 3+ a = np.pad(self.a, p)+ b = blur(a, abs(r) * 0.6 + 0.5)+ t = 0.5 - 0.42 * np.sign(r) * min(1.0, abs(r) / (abs(r) + 1.2))+ return Mask(np.clip((b - t) * 3.0 + 0.5, 0, 1) if r else a, self.x0 - p, self.y0 - p)++ @staticmethod+ def union(*ms):+ out = Mask(np.zeros((0, 0)))+ for m in ms: out = out | m+ return out+++def _fillet(pts, r, n=10):+ """polygon with every corner replaced by a true circular arc of radius r (scalar or per-vertex list)"""+ P = np.asarray(pts, np.float64)+ k = len(P)+ rs = np.broadcast_to(np.asarray(r, np.float64), (k,))+ out = []+ for i in range(k):+ p, a, b = P[i], P[i - 1], P[(i + 1) % k]+ if rs[i] <= 0.5:+ out.append(p); continue+ u, v = a - p, b - p+ lu, lv = np.linalg.norm(u), np.linalg.norm(v)+ if lu < 1e-6 or lv < 1e-6:+ out.append(p); continue+ u, v = u / lu, v / lv+ th = np.arccos(np.clip(u @ v, -1, 1))+ if th < 1e-3 or th > np.pi - 1e-3:+ out.append(p); continue+ t = min(rs[i] / np.tan(th / 2), 0.5 * lu, 0.5 * lv)+ rr = t * np.tan(th / 2)+ w = (u + v) / np.linalg.norm(u + v)+ c = p + w * rr / np.sin(th / 2)+ t1, t2 = p + u * t, p + v * t+ for s in np.linspace(0, 1, n):+ q = t1 * (1 - s) + t2 * s - c+ out.append(c + q / (np.linalg.norm(q) + 1e-9) * rr)+ return np.array(out)+++class FlatVector:+ def __init__(self, W=1920, H=1080, seed=0, light=(0.8, -0.6), ink=INK, cream=CREAM):+ self.W, self.H = W, H+ self.rng = np.random.default_rng(seed)+ self.img = np.ones((H, W, 3), np.float32)+ self.ink, self.cream = _c(ink), _c(cream)+ l = np.asarray(light, np.float32)+ self.light = l / (np.linalg.norm(l) + 1e-9) # unit vector pointing toward the light (screen)+ self._noise = None+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ colour+ def tone(self, c, k):+ """a tone of palette colour c: k < 0 mixes toward the ink (shade), k > 0 toward the cream (tint)"""+ c = _c(c)+ return c + (self.ink - c) * (-k) if k < 0 else c + (self.cream - c) * k++ @staticmethod+ def mix(a, b, t):+ return _c(a) * (1 - t) + _c(b) * t++ # ------------------------------------------------------------ shape masks+ def _grid(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0)) - 2), max(0, int(np.floor(y0)) - 2)+ x1, y1 = min(self.W, int(np.ceil(x1)) + 2), min(self.H, int(np.ceil(y1)) + 2)+ if x1 <= x0 or y1 <= y0: return None+ Y, X = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ return X + 0.5, Y + 0.5, x0, y0++ @staticmethod+ def _cov(d):+ return np.clip(0.5 - d, 0, 1).astype(np.float32)++ def _mk(self, g, d):+ if g is None: return Mask(np.zeros((0, 0)))+ return Mask(self._cov(d), g[2], g[3])++ def circle(self, cx, cy, r):+ g = self._grid(cx - r, cy - r, cx + r, cy + r)+ return self._mk(g, None if g is None else np.hypot(g[0] - cx, g[1] - cy) - r)++ def ellipse(self, cx, cy, rx, ry, rot=0.0):+ R = max(rx, ry)+ g = self._grid(cx - R, cy - R, cx + R, cy + R)+ if g is None: return self._mk(g, None)+ t = np.deg2rad(rot)+ dx, dy = g[0] - cx, g[1] - cy+ u, v = dx * np.cos(t) - dy * np.sin(t), dx * np.sin(t) + dy * np.cos(t)+ k0 = np.hypot(u / rx, v / ry)+ k1 = np.hypot(u / rx ** 2, v / ry ** 2) + 1e-9+ return self._mk(g, k0 * (k0 - 1) / k1)++ def rect(self, x0, y0, x1, y1):+ return self.rrect(x0, y0, x1, y1, 0)++ def rrect(self, x0, y0, x1, y1, r=0, rot=0.0):+ """rounded rectangle; r scalar or (top-left, top-right, bottom-right, bottom-left); rot about its centre"""+ cx, cy, hw, hh = (x0 + x1) / 2, (y0 + y1) / 2, abs(x1 - x0) / 2, abs(y1 - y0) / 2+ R = np.hypot(hw, hh) if rot else 0+ g = self._grid(cx - (R or hw), cy - (R or hh), cx + (R or hw), cy + (R or hh))+ if g is None: return self._mk(g, None)+ t = np.deg2rad(rot)+ dx, dy = g[0] - cx, g[1] - cy+ u, v = dx * np.cos(t) - dy * np.sin(t), dx * np.sin(t) + dy * np.cos(t)+ rs = np.broadcast_to(np.asarray(r, np.float32), (4,))+ rr = np.where(v < 0, np.where(u < 0, rs[0], rs[1]), np.where(u < 0, rs[3], rs[2]))+ rr = np.minimum(rr, min(hw, hh))+ qx, qy = np.abs(u) - hw + rr, np.abs(v) - hh + rr+ d = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - rr+ return self._mk(g, d)++ def capsule(self, p0, p1, r0, r1=None):+ """a bar with round ends from p0 (radius r0) to p1 (radius r1): limbs, stems, cords, dashes"""+ r1 = r0 if r1 is None else r1+ (ax, ay), (bx, by) = p0, p1+ R = max(r0, r1)+ g = self._grid(min(ax, bx) - R, min(ay, by) - R, max(ax, bx) + R, max(ay, by) + R)+ if g is None: return self._mk(g, None)+ dx, dy = bx - ax, by - ay+ L2 = dx * dx + dy * dy + 1e-9+ t = np.clip(((g[0] - ax) * dx + (g[1] - ay) * dy) / L2, 0, 1)+ d = np.hypot(g[0] - ax - t * dx, g[1] - ay - t * dy) - (r0 + (r1 - r0) * t)+ return self._mk(g, d)++ def limb(self, pts, radii):+ """a chain of tapered capsules through pts with a radius per point (arms, legs, tails)"""+ m = Mask(np.zeros((0, 0)))+ for i in range(len(pts) - 1):+ m = m | self.capsule(pts[i], pts[i + 1], radii[i], radii[i + 1])+ return m++ def tube(self, pts, r, per=10):+ """a smooth capsule along a Catmull-Rom curve (cords, tails, steam)"""+ P = spline(pts, per) if len(pts) > 2 else np.asarray(pts, np.float32)+ rr = np.broadcast_to(np.asarray(r, np.float32), (len(P),)) if np.ndim(r) == 0 else np.interp(+ np.linspace(0, 1, len(P)), np.linspace(0, 1, len(r)), r)+ return self.limb(P, rr)++ def poly(self, pts, round=0, ss=4):+ """filled polygon; `round` fillets every corner (scalar or one radius per vertex) with a true arc"""+ P = _fillet(pts, round) if np.any(np.asarray(round) > 0) else np.asarray(pts, np.float64)+ x0, y0 = P.min(0); x1, y1 = P.max(0)+ g = self._grid(x0, y0, x1, y1)+ if g is None: return Mask(np.zeros((0, 0)))+ gx, gy = g[2], g[3]+ w, h = g[0].shape[1], g[0].shape[0]+ im = Image.new('L', (w * ss, h * ss), 0)+ ImageDraw.Draw(im).polygon([((x - gx) * ss, (y - gy) * ss) for x, y in P], fill=255)+ a = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255+ return Mask(a, gx, gy)++ def arc(self, cx, cy, r0, r1, a0, a1):+ """ring segment between radii r0 < r1, from angle a0 to a1 (degrees, counter-clockwise from +x)"""+ g = self._grid(cx - r1, cy - r1, cx + r1, cy + r1)+ if g is None: return self._mk(g, None)+ dx, dy = g[0] - cx, -(g[1] - cy)+ rad = np.hypot(dx, dy)+ dr = np.maximum(r0 - rad, rad - r1)+ mid, half = np.deg2rad((a0 + a1) / 2), np.deg2rad(abs(a1 - a0) / 2)+ ang = np.abs((np.arctan2(dy, dx) - mid + np.pi) % (2 * np.pi) - np.pi)+ da = (ang - half) * np.maximum(rad, 1)+ return self._mk(g, np.maximum(dr, da))++ def pie(self, cx, cy, r, a0, a1):+ return self.arc(cx, cy, -1, r, a0, a1)++ def leaf(self, p0, p1, width, bend=0.0, n=28):+ """a leaf / petal: a pointed vesica from base p0 to tip p1, `bend` bows it sideways (px)"""+ p0, p1 = np.asarray(p0, np.float64), np.asarray(p1, np.float64)+ d = p1 - p0; L = np.linalg.norm(d) + 1e-9+ nrm = np.array([-d[1], d[0]]) / L+ t = np.linspace(0, 1, n)+ spine = p0 + d * t[:, None] + nrm * (4 * t * (1 - t) * bend)[:, None]+ w = width / 2 * np.sin(np.pi * t) ** 0.75 * (1 - 0.25 * t)+ left = spine + nrm * w[:, None]; right = spine - nrm * w[:, None]+ return self.poly(np.vstack([left, right[::-1]]))++ def star(self, cx, cy, r, points=4, inner=0.28, rot=0.0):+ """a sparkle / star polygon"""+ a = np.deg2rad(rot) + np.arange(points * 2) * np.pi / points - np.pi / 2+ rr = np.where(np.arange(points * 2) % 2 == 0, r, r * inner)+ return self.poly(np.stack([cx + rr * np.cos(a), cy + rr * np.sin(a)], 1), round=r * 0.04)++ def split(self, m, p0, p1):+ """the part of m on the left of the line p0 -> p1 as you walk along it on screen+ (a line drawn left -> right keeps what is above it; top -> bottom keeps what is to its right)"""+ if m.a.size == 0: return m+ Y, X = np.mgrid[m.y0:m.y1, m.x0:m.x1].astype(np.float32)+ dx, dy = p1[0] - p0[0], p1[1] - p0[1]+ L = np.hypot(dx, dy) + 1e-9+ d = -((X + 0.5 - p0[0]) * dy - (Y + 0.5 - p0[1]) * dx) / L+ return Mask(m.a * self._cov(d), m.x0, m.y0)++ def text_mask(self, s, x, y, size, font_style='geo', anchor='ls', spacing=0.0, cjk='cjk'):+ """set lettering as a mask. Latin runs use `font_style`, CJK runs `cjk`; anchor: l/m/r + s (baseline)/m"""+ runs = []+ for ch in s:+ st = cjk if _is_cjk(ch) else font_style+ if runs and runs[-1][0] == st: runs[-1][1] += ch+ else: runs.append([st, ch])+ adv = []+ for st, t in runs:+ f = font(st, size)+ adv.append(sum(f.getlength(ch) + spacing for ch in t))+ total = sum(adv) - spacing+ x0 = x - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ if anchor[1] == 'm':+ y = y + size * 0.36+ pad = int(size * 0.6) + 4+ bx0, by0 = int(x0) - pad, int(y - size * 1.3) - pad+ w, h = int(total) + 2 * pad, int(size * 1.9) + 2 * pad+ im = Image.new('L', (w, h), 0)+ d = ImageDraw.Draw(im)+ cx = x0 - bx0+ for (st, t), a in zip(runs, adv):+ f = font(st, size)+ if spacing:+ for ch in t:+ d.text((cx, y - by0), ch, font=f, fill=255, anchor='ls'); cx += f.getlength(ch) + spacing+ else:+ d.text((cx, y - by0), t, font=f, fill=255, anchor='ls'); cx += a+ return Mask(np.asarray(im, np.float32) / 255, bx0, by0)++ def text_width(self, s, size, font_style='geo', spacing=0.0, cjk='cjk'):+ return sum(font(cjk if _is_cjk(ch) else font_style, size).getlength(ch) + spacing for ch in s) - spacing++ # ------------------------------------------------------------ painting+ def _region(self, m):+ x0, y0, x1, y1 = max(0, m.x0), max(0, m.y0), min(self.W, m.x1), min(self.H, m.y1)+ if x1 <= x0 or y1 <= y0: return None, None+ return (slice(y0, y1), slice(x0, x1)), m.a[y0 - m.y0:y1 - m.y0, x0 - m.x0:x1 - m.x0]++ def _grain_field(self):+ if self._noise is None:+ r = np.random.default_rng(12345)+ fine = blur(r.random((self.H, self.W)).astype(np.float32), 0.55)+ fine = (fine - fine.mean()) / (fine.std() + 1e-6)+ clump = noise2d(self.H, self.W, 3.0, 2, 777)+ self._noise = (0.85 * fine + 0.25 * (clump - 0.5) / 0.15).astype(np.float32)+ return self._noise++ def fill(self, m, colour, alpha=1.0, grain=0.0):+ """lay a flat colour through mask m. alpha < 1 is a translucent sheet; grain breaks its alpha into a+ fine speckle (light beams, sun patches)"""+ sl, a = self._region(m)+ if sl is None: return m+ a = a * alpha+ if grain:+ a = np.clip(a * (1 + grain * self._grain_field()[sl] * 0.5), 0, 1)+ c = _c(colour)+ self.img[sl] += (c - self.img[sl]) * a[..., None]+ return m++ def darken(self, m, strength=0.25, tint=None):+ """multiply what is already there by an ink tint (flat shadow on any colour, stays in the palette)"""+ sl, a = self._region(m)+ if sl is None: return m+ t = self.ink if tint is None else _c(tint)+ k = 1 + (t - 1) * strength+ self.img[sl] *= 1 + (k - 1) * a[..., None]+ return m++ def lighten(self, m, strength=0.25, tint=None):+ """screen toward the cream (a lit plane on any colour)"""+ sl, a = self._region(m)+ if sl is None: return m+ t = self.cream if tint is None else _c(tint)+ self.img[sl] += (t - self.img[sl]) * (a * strength)[..., None]+ return m++ def shade(self, m, strength=0.22, depth=14, colour=None):+ """a crisp crescent on the side away from the light: m minus m nudged `depth` px toward the light"""+ cr = m - m.moved(self.light[0] * depth, self.light[1] * depth)+ return self.fill(cr, colour) if colour is not None else self.darken(cr, strength)++ def glint(self, m, strength=0.3, depth=8, colour=None):+ """the lit-side crescent in a lighter tone"""+ cr = m - m.moved(-self.light[0] * depth, -self.light[1] * depth)+ return self.fill(cr, colour) if colour is not None else self.lighten(cr, strength)++ def plane(self, m, p0, p1, strength=0.22, colour=None):+ """cut m with the line p0 -> p1 and shade the part on its left (see split): box side faces, the dark half+ of a leaf. Pass colour for a flat block instead of a multiply"""+ part = self.split(m, p0, p1)+ return self.fill(part, colour) if colour is not None else self.darken(part, strength)++ def cast(self, m, dx, dy, strength=0.22, clip=None):+ """a hard flat shadow of m, offset (dx, dy), onto whatever is already painted (clip limits the surface).+ Call it before painting the object itself."""+ s = m.moved(dx, dy)+ if clip is not None: s = s & clip+ return self.darken(s, strength)++ def backdrop(self, colour):+ self.img[:] = _c(colour)++ # ------------------------------------------------------------ lettering and graphic marks+ def text(self, s, x, y, size, colour=INK, font_style='geo', anchor='ls', spacing=0.0, cjk='cjk', alpha=1.0):+ m = self.text_mask(s, x, y, size, font_style, anchor, spacing, cjk)+ return self.fill(m, colour, alpha)++ def dashes(self, pts, width=6, dash=22, gap=16, colour=CREAM, per=16, arrow=None):+ """a dashed motion path along a smooth curve (round-capped dashes); arrow=size puts a head at the end"""+ P = spline(pts, per)+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ L = s[-1]+ m = Mask(np.zeros((0, 0)))+ t = 0.0+ stop = L - (arrow * 0.9 if arrow else 0)+ while t < stop:+ t1 = min(t + dash, stop)+ a = (np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1]))+ b = (np.interp(t1, s, P[:, 0]), np.interp(t1, s, P[:, 1]))+ m = m | self.capsule(a, b, width / 2)+ t += dash + gap+ if arrow:+ tip = P[-1]; back = np.array([np.interp(L - arrow, s, P[:, 0]), np.interp(L - arrow, s, P[:, 1])])+ d = (tip - back) / (np.linalg.norm(tip - back) + 1e-9); n = np.array([-d[1], d[0]])+ m = m | self.poly([tip + d * arrow * 0.2, back + n * arrow * 0.62, back - n * arrow * 0.62], round=arrow * 0.14)+ return self.fill(m, colour)++ def sparkle(self, cx, cy, r, colour=CREAM, rot=0.0):+ return self.fill(self.star(cx, cy, r, 4, 0.26, rot), colour)++ def sun(self, cx, cy, r, colour=MUSTARD, rays=0, ray_colour=None, ray_len=0.45, ray_w=0.07):+ """a flat disc; rays > 0 adds that many short round-capped rays"""+ m = self.fill(self.circle(cx, cy, r), colour)+ for i in range(rays):+ a = 2 * np.pi * i / rays+ p0 = (cx + np.cos(a) * r * 1.25, cy + np.sin(a) * r * 1.25)+ p1 = (cx + np.cos(a) * r * (1.25 + ray_len), cy + np.sin(a) * r * (1.25 + ray_len))+ self.fill(self.capsule(p0, p1, r * ray_w), ray_colour or colour)+ return m++ def cloud(self, cx, cy, w, colour=CREAM, seed=None):+ """flat cloud: a rounded base bar with three or four bumps on top"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ h = w * 0.26+ m = self.rrect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2, h / 2)+ k = int(r.integers(2, 4))+ xs = np.linspace(cx - w * 0.2, cx + w * 0.16, k) + r.uniform(-0.03, 0.03, k) * w+ for i, x in enumerate(xs):+ rr = w * (0.14 + 0.05 * r.random()) * (1.35 if i == k // 2 else 1)+ m = m | self.circle(x, cy + h / 2 - rr * 1.05, rr)+ m = m & self.rect(cx - w, cy - w, cx + w, cy + h / 2)+ return self.fill(m, colour)++ # ------------------------------------------------------------ objects+ def book(self, cx, cy, w, h, rot=0.0, colour=CORAL, open=False, pages=CREAM, band=None):+ """a single book seen from the front: closed (cover, page block showing on the fore-edge, spine band)+ or open (two pages fanning from the gutter over a slightly larger cover)"""+ t = np.deg2rad(rot)+ ca, sa = np.cos(t), np.sin(t)+ P = lambda lx, ly: (cx + lx * ca + ly * sa, cy - lx * sa + ly * ca)+ if not open:+ cover = self.rrect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2, (w * 0.06, w * 0.12, w * 0.12, w * 0.06), rot)+ bx, by = P(w * 0.08, 0) # page block peeks out on the fore-edge+ block = self.rrect(bx - w * 0.48, by - h * 0.45, bx + w * 0.48, by + h * 0.45, w * 0.06, rot)+ self.fill(block, pages)+ self.fill(cover, colour)+ hinge = self.split(cover, P(-w / 2 + w * 0.16, -h), P(-w / 2 + w * 0.16, h)) # the cover right of the hinge+ self.fill(cover - hinge, self.tone(colour, -0.18)) # the spine strip+ b = self.rrect(cx - w * 0.18, cy - h * 0.2, cx + w * 0.34, cy - h * 0.06, h * 0.07, rot)+ self.fill(b & cover, band or self.tone(colour, 0.55))+ return cover+ # open: two page quads over a cover+ cov = self.poly([P(-w / 2 - w * 0.03, -h / 2 + h * 0.02), P(0, -h / 2 + h * 0.1), P(w / 2 + w * 0.03, -h / 2 + h * 0.02),+ P(w / 2 + w * 0.03, h / 2 + h * 0.04), P(0, h / 2 + h * 0.12), P(-w / 2 - w * 0.03, h / 2 + h * 0.04)], round=w * 0.03)+ self.fill(cov, colour)+ left = self.poly([P(-w / 2, -h / 2), P(0, -h / 2 + h * 0.09), P(0, h / 2 + h * 0.06), P(-w / 2, h / 2 - h * 0.02)], round=w * 0.02)+ right = self.poly([P(0, -h / 2 + h * 0.09), P(w / 2, -h / 2), P(w / 2, h / 2 - h * 0.02), P(0, h / 2 + h * 0.06)], round=w * 0.02)+ self.fill(left, pages); self.fill(right, self.tone(pages, -0.08))+ for i in range(3): # three lines of text+ for side in (-1, 1):+ y = -h * 0.22 + i * h * 0.16+ self.fill(self.capsule(P(side * w * 0.08, y), P(side * w * 0.36, y - side * 0), h * 0.022), self.tone(pages, -0.2))+ return cov++ def books(self, x0, x1, y_base, h_max, colours, seed=None, w_range=(0.13, 0.3), gap_at=None, gap_w=0,+ stack_at=None, back=None, shadow=0.3, title=True):+ """a row of spines standing on a shelf from x0 to x1 with their feet at y_base (h_max = tallest book).+ colours: palette colours to draw from (neighbours never repeat). gap_at / gap_w: one book has been taken+ out there -- the book on the left of the gap has tipped over into it, pivoting on its bottom corner until+ its top rests on the next book. stack_at: x of a small pile lying flat. If the row does not fill the+ shelf, the last book leans against the side panel. Each spine: base colour, a darker block on the side+ away from the light, bands and a title dash in tones of its own colour, and a hard flat shadow on the+ shelf `back` mask. Returns a list of (mask, colour)"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ plan, x, prev = [], float(x0), None+ while True:+ if stack_at is not None and x <= stack_at < x + h_max * 0.3:+ plan.append(dict(kind='stack', x=x, w=h_max * 0.84)); x += h_max * 0.9; prev = None; continue+ if gap_at is not None and x <= gap_at < x + h_max * 0.3:+ if plan and plan[-1]['kind'] == 'stand': plan[-1]['lean'] = gap_at + gap_w - (plan[-1]['x'] + plan[-1]['w'])+ x = gap_at + gap_w; prev = None; continue+ bw = h_max * r.uniform(*w_range)+ if x + bw > x1: break+ opts = [c for c in colours if prev is None or not np.allclose(_c(c), _c(prev))]+ c = opts[r.integers(len(opts))]+ plan.append(dict(kind='stand', x=x, w=bw, h=h_max * r.uniform(0.68, 0.98), c=c, lean=0.0))+ prev = c+ x += bw + (h_max * 0.012 if r.random() < 0.3 else 0)+ if plan and plan[-1]['kind'] == 'stand' and x1 - x > h_max * 0.12:+ plan[-1]['lean'] = x1 - (plan[-1]['x'] + plan[-1]['w'])+ out = []+ for b in plan:+ if b['kind'] == 'stack':+ sw, yb = b['w'], y_base+ for i in range(int(r.integers(3, 5))):+ bh = h_max * r.uniform(0.1, 0.16); bw = sw * r.uniform(0.8, 1.0)+ c = colours[r.integers(len(colours))]+ xa = b['x'] + (sw - bw) / 2 + r.uniform(-0.04, 0.04) * sw+ bm = self.rrect(xa, yb - bh, xa + bw, yb, 2)+ if back is not None: self.cast(bm, -h_max * 0.06, 0, shadow, clip=back)+ self.fill(bm, c)+ self.fill(self.rect(xa, yb - bh * 0.62, xa + bw * 0.9, yb - bh * 0.38), self.tone(c, 0.5))+ self.fill(self.rect(xa + bw * 0.92, yb - bh, xa + bw, yb) & bm, self.tone(c, -0.2))+ out.append((bm, c)); yb -= bh+ continue+ x, bw, bh, c = b['x'], b['w'], b['h'], b['c']+ if b['lean'] > 1: # tipped over to the right+ th = np.arcsin(min(b['lean'] / bh, 0.55))+ t = -th+ px, py = x + bw, y_base # pivot: bottom-right corner+ ox = bw / 2 * np.cos(t) + bh / 2 * np.sin(t); oy = -bw / 2 * np.sin(t) + bh / 2 * np.cos(t)+ cx, cy = px - ox, py - oy+ m = self.rrect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, (bw * 0.12, bw * 0.12, 0, 0), np.rad2deg(t))+ if back is not None: self.cast(m, -bw * 0.45, 0, shadow, clip=back)+ self.fill(m, c)+ P = lambda lx, ly: (cx + lx * np.cos(t) + ly * np.sin(t), cy - lx * np.sin(t) + ly * np.cos(t))+ self.fill(self.split(m, P(-bw * 0.26, bh), P(-bw * 0.26, -bh)), self.tone(c, -0.2)) # left strip+ q0, q1 = P(-bw * 0.26, -bh * 0.2), P(bw * 0.5, -bh * 0.2)+ self.fill(self.capsule(q0, q1, bh * 0.03) & m, self.tone(c, 0.55))+ out.append((m, c)); continue+ m = self.rrect(x, y_base - bh, x + bw, y_base, (bw * 0.12, bw * 0.12, 0, 0))+ if back is not None: self.cast(m, -bw * 0.45, 0, shadow, clip=back)+ self.fill(m, c)+ self.fill(self.rect(x, y_base - bh, x + bw * 0.26, y_base) & m, self.tone(c, -0.2))+ bc = self.tone(c, 0.55) if r.random() < 0.6 else self.tone(c, -0.35) # bands sit near the head and foot+ style = r.integers(0, 4)+ if style in (1, 3):+ yy = r.uniform(0.8, 0.88)+ self.fill(self.rect(x + bw * 0.26, y_base - bh * yy - bh * 0.03, x + bw, y_base - bh * yy + bh * 0.03), bc)+ if style in (2, 3):+ yy = r.uniform(0.1, 0.16)+ self.fill(self.rect(x + bw * 0.26, y_base - bh * yy - bh * 0.03, x + bw, y_base - bh * yy + bh * 0.03), bc)+ if title and bw > h_max * 0.15 and r.random() < 0.75: # the title: one dash in the middle+ ty = y_base - bh * r.uniform(0.44, 0.54)+ self.fill(self.capsule((x + bw * 0.62, ty - bh * 0.13), (x + bw * 0.62, ty + bh * 0.13), bw * 0.09),+ self.tone(c, 0.6) if r.random() < 0.7 else self.tone(c, -0.4))+ out.append((m, c))+ return out++ def plant(self, x, y, h, pot=CORAL, leaf=TEAL, kind='leafy', seed=None, n=None):+ """a potted plant standing at (x, y) (pot bottom centre), total height h.+ kind: 'leafy' (split two-tone leaves on stems), 'snake' (upright blades with bands), 'round' (bushy)"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ pw, ph = h * 0.34, h * 0.26+ top = y - ph+ stems, leaves = Mask(np.zeros((0, 0))), []+ if kind == 'snake':+ for i in range(n or 6):+ bx = x + (i - (n or 6) / 2 + 0.5) * pw * 0.16+ tip = (bx + r.uniform(-0.2, 0.2) * h * 0.4, top - h * r.uniform(0.45, 0.72))+ leaves.append(((bx, top + 4), tip, pw * r.uniform(0.2, 0.28), r.uniform(-8, 8)))+ else:+ k = n or (7 if kind == 'leafy' else 11)+ for i in range(k):+ a = np.deg2rad(-90 + (i - (k - 1) / 2) * (150 / k) + r.uniform(-8, 8))+ L = h * r.uniform(0.38, 0.62) * (1 - 0.35 * abs(np.cos(a)))+ base = (x + r.uniform(-0.1, 0.1) * pw, top + 2)+ mid = (base[0] + np.cos(a) * L * 0.55, base[1] + np.sin(a) * L * 0.55)+ if kind == 'leafy':+ stems = stems | self.tube([base, (base[0] + np.cos(a) * L * 0.3, base[1] + np.sin(a) * L * 0.34), mid], max(2, h * 0.008))+ tip = (mid[0] + np.cos(a + 0.35 * np.sign(np.cos(a))) * L * 0.5, mid[1] + np.sin(a + 0.35 * np.sign(np.cos(a))) * L * 0.5)+ leaves.append((mid, tip, L * 0.42, np.sign(np.cos(a)) * L * 0.06))+ else:+ leaves.append((base, (base[0] + np.cos(a) * L, base[1] + np.sin(a) * L), L * 0.34, 0))+ self.fill(stems, self.tone(leaf, -0.35))+ order = sorted(range(len(leaves)), key=lambda i: -abs(leaves[i][1][0] - x))+ for i in order:+ p0, p1, wd, bend = leaves[i]+ m = self.leaf(p0, p1, wd, bend)+ self.fill(m, leaf)+ if kind == 'snake': self.plane(m, p0, p1, colour=self.tone(leaf, -0.2)) # left half of an upright blade+ elif p1[0] > p0[0]: self.plane(m, p1, p0, colour=self.tone(leaf, -0.2)) # lower half of the leaf+ else: self.plane(m, p0, p1, colour=self.tone(leaf, -0.2))+ if kind == 'snake':+ for j in range(3):+ tt = 0.25 + j * 0.2+ q = (p0[0] + (p1[0] - p0[0]) * tt, p0[1] + (p1[1] - p0[1]) * tt)+ self.fill(self.ellipse(q[0], q[1], wd * 0.34, wd * 0.08, -np.rad2deg(np.arctan2(-(p1[1] - p0[1]), p1[0] - p0[0])) + 90) & m,+ self.tone(leaf, 0.35))+ body = self.poly([(x - pw / 2, top + ph * 0.18), (x + pw / 2, top + ph * 0.18), (x + pw * 0.38, y), (x - pw * 0.38, y)],+ round=[0, 0, pw * 0.08, pw * 0.08])+ rim = self.rrect(x - pw / 2 - pw * 0.04, top, x + pw / 2 + pw * 0.04, top + ph * 0.24, ph * 0.05)+ self.fill(body, pot)+ self.shade(body, 0.2, pw * 0.3)+ self.fill(rim, self.tone(pot, 0.12))+ self.shade(rim, 0.2, pw * 0.2)+ return body | rim++ def pendant(self, x, y_top, y, r, shade=INK, bulb=CREAM, beam_to=None, beam_alpha=0.13, beam_colour=None, cord=3):+ """a pendant lamp hanging from y_top: a cord, a dome shade of radius r whose bottom edge is at y, a bulb,+ and optionally a flat translucent beam spreading down to (x_left, x_right, y_floor)"""+ if beam_to is not None:+ bl, br, by = beam_to+ beam = self.poly([(x - r * 0.72, y), (x + r * 0.72, y), (br, by), (bl, by)])+ self.fill(beam, beam_colour or self.tone(bulb, 0.2), beam_alpha, grain=0.35)+ self.fill(self.capsule((x, y_top), (x, y - r * 0.95), cord), self.tone(shade, 0.05))+ dome = self.pie(x, y, r, 0, 180)+ self.fill(self.circle(x, y + r * 0.05, r * 0.3), bulb)+ self.fill(dome, shade)+ self.plane(dome, (x + r * 0.08, y - r - 10), (x + r * 0.34, y + 10), colour=self.tone(shade, 0.12)) # lit right side+ self.fill(self.rrect(x - r * 0.12, y - r - r * 0.12, x + r * 0.12, y - r + r * 0.05, r * 0.04), self.tone(shade, 0.12))+ return dome++ def cat(self, x, y, size, colour=INK, facing=1, pose='sit', tail_down=None):+ """a flat cat seen from behind / side, sitting with its base centre at (x, y); size = body height.+ tail_down: a y to let the tail hang down to (over a sill edge)"""+ s = size+ f = facing+ body = self.ellipse(x, y - s * 0.38, s * 0.34, s * 0.42) | self.ellipse(x, y - s * 0.12, s * 0.42, s * 0.2)+ body = body & self.rect(x - s, y - s * 2, x + s, y)+ hx, hy = x + f * s * 0.08, y - s * 0.86+ head = self.ellipse(hx, hy, s * 0.26, s * 0.22)+ ears = self.poly([(hx - s * 0.24, hy - s * 0.02), (hx - s * 0.2, hy - s * 0.34), (hx - s * 0.04, hy - s * 0.16)], round=s * 0.03) | \+ self.poly([(hx + s * 0.24, hy - s * 0.02), (hx + s * 0.2, hy - s * 0.34), (hx + s * 0.04, hy - s * 0.16)], round=s * 0.03)+ if tail_down is not None:+ tail = self.tube([(x - f * s * 0.2, y - s * 0.08), (x - f * s * 0.42, y + s * 0.05), (x - f * s * 0.46, (y + tail_down) / 2),+ (x - f * s * 0.36, tail_down)], [s * 0.07, s * 0.07, s * 0.065, s * 0.06])+ else:+ tail = self.tube([(x - f * s * 0.3, y - s * 0.05), (x + f * s * 0.1, y + s * 0.02), (x + f * s * 0.5, y - s * 0.04),+ (x + f * s * 0.62, y - s * 0.18)], s * 0.065)+ allm = body | head | ears | tail+ self.fill(allm, colour)+ self.shade(body | head, 0.0, s * 0.12, colour=self.tone(colour, 0.12) if _c(colour).mean() < 0.3 else self.tone(colour, -0.2))+ return allm++ # ------------------------------------------------------------ people+ def person(self, hip, height, facing=1, lean=0.0, head_tilt=0.0, arm=(10, 20), arm_far=(-8, -2),+ leg=(2, 0), leg_far=(-4, 0), sit=False, top=MUSTARD, bottom=INK, shoes=None, skin=PEACH,+ hair=INK, hair_style='short', sleeve='long', coat=False, skirt=False, apron=None, bag=None,+ collar=None, build=1.0, far_tone=-0.2, draw_near_arm=True, hand_to=None, hand_far_to=None,+ foot_to=None, foot_far_to=None):+ """a faceless adult (about 7.5 heads tall) with the hip centre at `hip`, facing +1 right / -1 left.+ Joint angles are degrees from straight down, positive toward the facing side:+ arm=(upper, fore) of the near arm, arm_far the far arm, leg=(thigh, shin), leg_far the far leg.+ sit=True is a shortcut for thighs forward (90) and shins down.+ hand_to / hand_far_to / foot_to / foot_far_to: put that hand or ankle on a point instead (two-bone IK:+ elbows drop, knees go forward; a point out of reach gets the limb stretched straight toward it).+ Clothes: top (sweater / shirt colour), bottom (trousers), skirt=colour, coat=True (top becomes a long coat),+ apron=colour, bag=colour (a tote hanging from the near shoulder), collar=colour. hair_style: short, bun, bob, long, pony.+ Returns the joints: head, neck, shoulder, hand, hand_far, elbow, knee, knee_far, foot, foot_far, u."""+ f = 1 if facing >= 0 else -1+ u = height / 7.5+ H = np.array(hip, np.float64)+ lam = np.deg2rad(lean)+ up = np.array([f * np.sin(lam), -np.cos(lam)])+ fwd = np.array([f * np.cos(lam), np.sin(lam)])++ def dv(a):+ a = np.deg2rad(a)+ return np.array([f * np.sin(a), np.cos(a)])++ if sit:+ leg = leg if leg != (2, 0) else (88, 4)+ leg_far = leg_far if leg_far != (-4, 0) else (92, 0)+ shoes = shoes if shoes is not None else self.tone(bottom, -0.35)+ S = H + up * 2.78 * u+ N = H + up * 3.02 * u+ tilt = np.deg2rad(head_tilt)+ head_up = np.array([f * np.sin(lam + tilt), -np.cos(lam + tilt)])+ C = N + head_up * 0.62 * u + fwd * 0.1 * u+ sh_n, sh_f = S - fwd * 0.36 * u * build, S + fwd * 0.34 * u * build+ hp_n, hp_f = H - fwd * 0.26 * u, H + fwd * 0.22 * u+ joints = dict(u=u, hip=tuple(H), shoulder=tuple(S), neck=tuple(N), head=tuple(C))++ def ang(v):+ return float(np.rad2deg(np.arctan2(f * v[0], v[1])))++ def ik(root, target, L1, L2, knee):+ d = np.asarray(target, np.float64) - root+ dist = float(np.clip(np.linalg.norm(d), abs(L1 - L2) + 1e-3, L1 + L2 - 1e-3))+ base = np.arctan2(d[1], d[0])+ al = np.arccos(np.clip((L1 * L1 + dist * dist - L2 * L2) / (2 * L1 * dist), -1, 1))+ cands = [root + L1 * np.array([np.cos(base + s_ * al), np.sin(base + s_ * al)]) for s_ in (1, -1)]+ J = max(cands, key=lambda e: f * e[0]) if knee else max(cands, key=lambda e: e[1] - 0.3 * f * e[0])+ tip = root + d / (np.linalg.norm(d) + 1e-9) * dist+ return (ang(J - root), ang(tip - J))++ if hand_to is not None: arm = ik(S - fwd * 0.36 * u * build, hand_to, 1.42 * u, 1.42 * u, False)+ if hand_far_to is not None: arm_far = ik(S + fwd * 0.34 * u * build, hand_far_to, 1.42 * u, 1.42 * u, False)+ if foot_to is not None: leg = ik(H - fwd * 0.26 * u, foot_to, 1.92 * u, 1.86 * u, True)+ if foot_far_to is not None: leg_far = ik(H + fwd * 0.22 * u, foot_far_to, 1.92 * u, 1.86 * u, True)++ def arm_pts(sh, a):+ E = sh + dv(a[0]) * 1.42 * u+ Wr = E + dv(a[1]) * 1.22 * u+ Hd = Wr + dv(a[1]) * 0.2 * u+ return E, Wr, Hd++ def leg_pts(hp, a):+ K = hp + dv(a[0]) * 1.92 * u+ A = K + dv(a[1]) * 1.86 * u+ return K, A++ def tn(c, k): # a darker far limb; a dark colour+ return self.tone(c, k) if k >= 0 or _c(c).mean() > 0.3 else self.tone(c, -k * 0.6) # lifts instead++ def draw_arm(sh, a, tone_k):+ E, Wr, Hd = arm_pts(sh, a)+ sc = tn(top, tone_k)+ if sleeve == 'long':+ am = self.fill(self.limb([sh, E, Wr], [0.27 * u, 0.22 * u, 0.18 * u]), sc)+ self.shade(am, 0.16, 0.1 * u)+ self.fill(self.capsule(Hd - dv(a[1]) * 0.05 * u, Hd + dv(a[1]) * 0.05 * u, 0.16 * u), tn(skin, tone_k))+ self.fill(self.capsule(Wr - dv(a[1]) * 0.14 * u, Wr - dv(a[1]) * 0.02 * u, 0.2 * u), tn(top, tone_k - 0.1))+ else:+ self.fill(self.limb([E, Wr], [0.19 * u, 0.15 * u]), tn(skin, tone_k))+ self.fill(self.capsule(Hd - dv(a[1]) * 0.05 * u, Hd + dv(a[1]) * 0.05 * u, 0.16 * u), tn(skin, tone_k))+ self.fill(self.limb([sh, sh + dv(a[0]) * 0.8 * u], [0.3 * u, 0.25 * u]), sc)+ return E, Wr, Hd++ def draw_leg(hp, a, tone_k):+ K, A = leg_pts(hp, a)+ m = self.limb([hp, K, A], [0.38 * u, 0.27 * u, 0.2 * u])+ self.fill(m, tn(bottom, tone_k))+ toe = A + np.array([f * 0.78 * u, 0.1 * u])+ heel = A + np.array([-f * 0.18 * u, 0.1 * u])+ if a[1] < -25: # on tiptoe / foot on a rung behind+ toe = A + np.array([f * 0.7 * u, 0.26 * u])+ shoe = self.capsule(heel, toe, 0.2 * u, 0.17 * u) | self.rrect(min(heel[0], toe[0]), A[1] - 0.05 * u, max(heel[0], toe[0]),+ A[1] + 0.3 * u, (0.14 * u, 0.14 * u, 0.04 * u, 0.04 * u)) & \+ self.rect(min(heel[0], toe[0]) - u, A[1] - u, max(heel[0], toe[0]) + u, max(heel[1], toe[1]) + 0.3 * u)+ self.fill(self.limb([A - dv(a[1]) * 0.12 * u, A + np.array([0, 0.06 * u])], [0.21 * u, 0.21 * u]), tn(bottom, tone_k - 0.05))+ self.fill(shoe, tn(shoes, tone_k * 0.5))+ return K, A, m++ # long hair panel sits behind everything+ if hair_style == 'long':+ self.fill(self.rrect(C[0] - f * 0.55 * u - 0.1 * u, C[1] - 0.2 * u, C[0] + f * 0.2 * u + 0.1 * u, S[1] + 1.0 * u, 0.3 * u)+ if f > 0 else self.rrect(C[0] - 0.3 * u, C[1] - 0.2 * u, C[0] + 0.65 * u, S[1] + 1.0 * u, 0.3 * u), self.tone(hair, -0.1))+ E_f, W_f, H_f = draw_arm(sh_f, arm_far, far_tone)+ K_f, A_f, _ = draw_leg(hp_f, leg_far, far_tone)+ pelvis = self.ellipse(H[0], H[1] + 0.05 * u, 0.72 * u, 0.5 * u, -np.rad2deg(lam) * f)+ self.fill(pelvis, bottom)+ K_n, A_n, legm = draw_leg(hp_n, leg, 0.0)+ self.shade(legm, 0.16, 0.1 * u)+ if skirt:+ sk_len = 1.9 * u+ if sit:+ K = K_n+ sk = self.poly([H - fwd * 0.72 * u + up * 0.3 * u, H + fwd * 0.6 * u + up * 0.3 * u, K + np.array([f * 0.2 * u, -0.3 * u]),+ K + np.array([f * 0.25 * u, 0.4 * u]), H - fwd * 0.8 * u + np.array([0, 0.6 * u])], round=0.15 * u)+ else:+ sk = self.poly([H - fwd * 0.7 * u + up * 0.3 * u, H + fwd * 0.62 * u + up * 0.3 * u, H + fwd * 0.9 * u + np.array([0, sk_len]),+ H - fwd * 1.0 * u + np.array([0, sk_len])], round=[0.2 * u, 0.2 * u, 0.1 * u, 0.1 * u])+ self.fill(sk, skirt)+ self.shade(sk, 0.18, 0.3 * u)+ # torso+ def at(k, w_front, w_back):+ c = H + up * k * u+ return c + fwd * w_front * u * build, c - fwd * w_back * u * build+ s_f, s_b = at(2.82, 0.72, 0.78)+ c_f, c_b = at(2.1, 0.78, 0.7)+ w_f, w_b = at(1.1, 0.62, 0.66)+ hem = -0.12 if not coat else -2.1+ if coat and sit: hem = -0.5+ h_f, h_b = at(hem, 0.72 if not coat else 0.95, 0.76 if not coat else 1.0)+ torso = self.poly([s_b, s_f, c_f, w_f, h_f, h_b, w_b, c_b],+ round=[0.55 * u, 0.5 * u, 0.3 * u, 0.2 * u, 0.1 * u, 0.1 * u, 0.2 * u, 0.3 * u])+ self.fill(torso, top)+ self.shade(torso, 0.2, 0.34 * u)+ if coat: # front panel overlaps: a placket block+ pl = self.split(torso, tuple(H + fwd * 0.3 * u + up * 3 * u), tuple(H + fwd * 0.42 * u - up * 3 * u))+ self.fill(pl, self.tone(top, -0.1))+ self.fill(self.poly([N + fwd * 0.05 * u, N + fwd * 0.5 * u + up * -0.1 * u, H + fwd * 0.42 * u + up * 1.7 * u]), self.tone(top, -0.16))+ if apron is not None:+ ap = self.poly([H + fwd * 0.05 * u + up * 2.35 * u, H + fwd * 0.78 * u + up * 2.35 * u, H + fwd * 0.95 * u - up * 1.3 * u,+ H - fwd * 0.35 * u - up * 1.3 * u], round=[0.08 * u, 0.08 * u, 0.12 * u, 0.12 * u])+ self.fill(ap, apron)+ self.shade(ap, 0.16, 0.2 * u)+ self.fill(self.capsule(H + fwd * 0.2 * u + up * 2.35 * u, N + fwd * 0.12 * u, 0.06 * u), self.tone(apron, -0.1))+ self.fill(self.capsule(H - fwd * 0.4 * u + up * 1.1 * u, H + fwd * 0.4 * u + up * 1.1 * u, 0.07 * u), self.tone(apron, -0.12))+ self.fill(self.rrect(*(H + fwd * 0.18 * u + up * 0.1 * u + np.array([-0.26, -0.22]) * u),+ *(H + fwd * 0.18 * u + up * 0.1 * u + np.array([0.26, 0.22]) * u), 0.06 * u), self.tone(apron, -0.12))+ # neck and head+ neck = self.capsule(N - up * 0.1 * u, C, 0.17 * u)+ self.fill(neck, skin)+ self.darken(neck & self.circle(C[0] + f * 0.02 * u, C[1] + 0.3 * u, 0.4 * u), 0.22)+ if collar is not None:+ self.fill(self.poly([N - fwd * 0.3 * u, N + fwd * 0.35 * u, N + fwd * 0.05 * u + up * -0.35 * u], round=0.05 * u), collar)+ else:+ self.fill(self.ellipse(N[0], N[1], 0.34 * u, 0.13 * u, -np.rad2deg(lam) * f) & torso.grown(2), self.tone(top, -0.14))+ rot_h = -np.rad2deg(lam + tilt) * f+ hr = self.ellipse(C[0], C[1], 0.42 * u, 0.52 * u, rot_h)+ self.fill(hr, skin)+ # hair = a slightly bigger ellipse minus the face (the head nudged forward and down), then cut at the+ # hairline: from the nape at the back up to the temple in front, so the jaw and the ear show below it+ face = hr.moved(*(fwd * 0.2 * u + np.array([0, 0.2 * u])))+ cap = self.ellipse(C[0] - f * 0.03 * u, C[1] - 0.04 * u, 0.47 * u, 0.56 * u, rot_h) - face+ back_pt = C - fwd * 0.6 * u+ front_pt = C + fwd * 0.6 * u+ nape, temple = {'short': (0.2, -0.16), 'bun': (0.16, -0.12), 'pony': (0.16, -0.12)}.get(hair_style, (0.62, 0.1))+ bp = back_pt + np.array([0, nape * u]) + head_up * 0; fp = front_pt + np.array([0, temple * u])+ lo, hi = (bp, fp) if bp[0] < fp[0] else (fp, bp)+ cap = self.split(cap, tuple(lo), tuple(hi)) # keep what is above the hairline+ extra = Mask(np.zeros((0, 0)))+ if hair_style == 'bun':+ extra = self.circle(*(C - fwd * 0.3 * u + np.array([0, -0.5 * u])), 0.23 * u)+ elif hair_style == 'pony':+ extra = self.tube([C - fwd * 0.4 * u + np.array([0, -0.2 * u]), C - fwd * 0.7 * u + np.array([0, 0.25 * u]),+ C - fwd * 0.6 * u + np.array([0, 0.85 * u])], [0.2 * u, 0.16 * u, 0.08 * u])+ elif hair_style in ('bob', 'long'): # a curtain behind the jaw, down to the chin+ bx0, bx1 = sorted([C[0] - f * 0.5 * u, C[0] + f * 0.02 * u])+ extra = self.rrect(bx0, C[1] - 0.2 * u, bx1, C[1] + 0.62 * u, (0, 0, 0.18 * u, 0.18 * u) if f > 0 else (0, 0, 0.18 * u, 0.18 * u)) - face+ if not extra.empty and hair_style in ('bun', 'pony'):+ self.fill(extra, self.tone(hair, -0.08))+ self.fill(cap | (extra if hair_style in ('bob', 'long') else Mask(np.zeros((0, 0)))), hair)+ self.glint(cap, 0.14, 0.06 * u)+ if hair_style in ('short', 'bun', 'pony'):+ ear = self.ellipse(*(C - fwd * 0.12 * u + np.array([0, 0.08 * u])), 0.085 * u, 0.12 * u, rot_h)+ self.fill(ear, self.tone(skin, -0.1))+ if bag is not None: # a tote on the near shoulder+ bc = H - fwd * 0.62 * u + np.array([0, 0.62 * u])+ bw_, bh_ = 1.05 * u, 1.15 * u+ for dx in (-0.36, 0.3):+ self.fill(self.capsule(sh_n + np.array([0, 0.05 * u]), bc + np.array([dx * u, -bh_ / 2 + 0.05 * u]), 0.055 * u),+ self.tone(bag, -0.3))+ bm = self.rrect(bc[0] - bw_ / 2, bc[1] - bh_ / 2, bc[0] + bw_ / 2, bc[1] + bh_ / 2, (0.05 * u, 0.05 * u, 0.12 * u, 0.12 * u))+ self.fill(bm, bag); self.shade(bm, 0.0, 0.22 * u, colour=self.tone(bag, -0.14))+ self.fill(self.rect(bc[0] - bw_ / 2, bc[1] + 0.08 * u, bc[0] + bw_ / 2, bc[1] + 0.26 * u) & bm, self.tone(bag, -0.3)+ if _c(bag).mean() > 0.6 else self.tone(bag, 0.5))+ E_n, W_n, H_n = draw_arm(sh_n, arm, 0.0) if draw_near_arm else arm_pts(sh_n, arm)+ joints.update(hand=tuple(H_n), hand_far=tuple(H_f), elbow=tuple(E_n),+ knee=tuple(K_n), knee_far=tuple(K_f), foot=tuple(A_n), foot_far=tuple(A_f), shoulder_near=tuple(sh_n),+ shoulder_far=tuple(sh_f))+ self._last_person = dict(sh_n=sh_n, arm=arm, top=top, skin=skin, sleeve=sleeve, u=u, f=f, draw=draw_arm)+ return joints++ def near_arm(self):+ """draw the near arm of the last person() called with draw_near_arm=False (after a prop it should cover)"""+ p = self._last_person+ E, Wr, Hd = p['draw'](p['sh_n'], p['arm'], 0.0)+ return tuple(Hd)++ def hand(self, x, y, r, skin=PEACH):+ return self.fill(self.circle(x, y, r), skin)++ # ------------------------------------------------------------ output+ def composite(self, grain=0.012):+ img = self.img+ if grain:+ n = self._grain_field()+ img = img * (1 + grain * n[..., None])+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/isometric.py b/lib/isometric.pynew file mode 100644index 0000000..42acc02--- /dev/null+++ b/lib/isometric.py@@ -0,0 +1,1373 @@+"""isometric — a pastel isometric 2.5D diorama: a tiny world of blocks on a floating slab, seen through an+orthographic camera and lit by one low, soft sun and a lavender sky (numpy + Pillow only).++Model: a small ray tracer, not a painter's algorithm.+ camera a true isometric orthographic camera (azimuth 45 deg, elevation 35.26 deg). World x runs to the+ lower left of the screen, y to the lower right, z straight up; one world unit is one ground tile.+ Parallel lines stay parallel and nothing shrinks with distance -- the "model on a desk" look.+ solids every part is an exact analytic solid, traced per pixel:+ convex polyhedra given as planes (boxes with chamfered edges, gable and hip roofs, rotated+ panels, low-poly rocks, boat hulls, card panels),+ frustums along any axis (cylinders, cones, masts, trunks, tubes, arms),+ ellipsoids that may be cut by planes (tree crowns, cups, domes, a balloon, flat-bottomed clouds).+ The camera pass writes a G-buffer -- depth, normal, albedo, material -- so what hides what never+ depends on drawing order. Surfaces can carry a `paint(P, n, tag)` function evaluated at the exact+ world point: tile edges, soil layers, roof courses, louvres, solar cells, text on a card.+ sun the same solids are traced again from the sun into a shadow map and from straight above into a+ height map. Shading is albedo x (sky ambient x occlusion + sun x N.L x visibility).+ Axis-aligned faces therefore come out in three clean values: tops brightest, the sun side (+x,+ facing lower left) a step darker, the far side (+y, facing lower right) lit only by the sky. The+ three-tone look of isometric art falls out of the lighting, it is not painted on.+ shadows percentage-closer soft shadows: a blocker search measures how far the receiver is from what+ shades it, and the penumbra widens with that distance -- crisp where a wall meets the ground,+ blurred at the tip of a long shadow, very soft under a floating cloud or balloon. Filter taps are+ corrected for the receiver's slope, so wide filters do not self-shadow.+ occlusion from the top-down map, which keeps for every ground point the top *and the bottom* of the+ highest column above it (touching solids merge; an eave or a tree crown is a slab in the air).+ Upward faces: how far the blurred surroundings rise above the point, at three radii -- tile gaps+ go deep, the ground darkens round every footing. Side faces: the horizon seen out along the normal+ (and 40 deg either side), where a column only hides the band of sky it really covers -- a wall is+ never darkened by its own building or its own eaves, only by what stands in front of it, plus a+ small crease where it meets the ground. Column extents are sampled nearest, never interpolated.+ Floating things (clouds, cards, the balloon) and hairlines (guy wires) stay out of the map.+ colour pastel albedos, a lilac-blue sky ambient (shadows are cool lilac, never grey), a warm low sun.+ Chamfers on box edges catch a thin line of light. Materials: matte, water (shore foam, shallow to+ deep tint, glassy side walls), glass (sky sheen), soft (wrapped light for foliage and clouds),+ gloss (a small highlight), card (printed panels that stay legible). No glow, no bloom, no outline.+ backdrop a light vertical gradient with an invisible floor far below the slab: the slab's own shadow and a+ broad contact shade land on it, which is what makes the diorama float.+ finish rendered at `ss` x resolution and box-filtered down, so edges are clean; titles, a compass and+ captions are typeset on top in 2D. `stage()` shades a half-size preview (fast) for drawing animations.++ from isometric import Isometric+ iso = Isometric(1920, 1080, seed=3, scale=72, look=(5, 5, 0), at=(0.56, 0.52))+ iso.backdrop()+ iso.slab(0, 0, 10, 10) # the floating base with its soil layers+ iso.tiles(levels) # 10x10 ints: 0 sea, 1 sand, 2 grass (top 0.32), 3 terrace (0.60), 4 paving+ iso.sea() # water in the 0 cells, foam along the shore+ iso.building(3, 3, 5, 4.4, z=0.32, h=0.9, roof='gable', axis='y', windows=(1, 2, 2), door=('+x', 3.6))+ iso.tree(6.5, 2.5, iso.top_z(6.5, 2.5), size=1.0, kind='round')+ iso.windmill(2, 7, 0.32, h=2.6, yaw=30)+ x, y, z = iso.unproject(1500, 250, z=3.0) # place a floating card by its screen position+ iso.card(x, y, z, 2.9, 1.65, title='风速', tag='WIND', value='4.6', unit='m/s', anchor=(2.2, 7, 2.9))+ iso.text('Island Station', 120, 150, 64)+ iso.save('out.jpg')+Coordinates are world units (x, y on the ground, z up); `iso.iso(x, y, z)` gives the screen point.+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, smoothstep, load_font++MATTE, WATER, GLASS, CARD, SOFT, GLOSS = 1, 2, 3, 4, 5, 6+_MAT = {'matte': MATTE, 'water': WATER, 'glass': GLASS, 'card': CARD, 'soft': SOFT, 'gloss': GLOSS}+INK = '#34305a' # deep indigo for type+LILAC, MINT, PEACH, BUTTER, CORAL, SKY = '#c9b8f2', '#a9e0c2', '#f6cdb4', '#f7df97', '#f19a8e', '#a9cdf2'+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++def _unit(v):+ v = np.asarray(v, np.float64)+ return v / (np.linalg.norm(v) + 1e-12)+++def rot(yaw=0.0, pitch=0.0, roll=0.0):+ """rotation matrix local -> world (degrees): roll about x, then pitch about y, then yaw about z"""+ a, b, c = np.radians([yaw, pitch, roll])+ Rz = np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]])+ Ry = np.array([[np.cos(b), 0, np.sin(b)], [0, 1, 0], [-np.sin(b), 0, np.cos(b)]])+ Rx = np.array([[1, 0, 0], [0, np.cos(c), -np.sin(c)], [0, np.sin(c), np.cos(c)]])+ return Rz @ Ry @ Rx+++def _hash(ix, iy, seed=0):+ """integer lattice -> [0, 1) (vectorised)"""+ n = (np.asarray(ix, np.int64) * 374761393 + np.asarray(iy, np.int64) * 668265263 + seed * 144269477) & 0xffffffff+ n = ((n ^ (n >> 13)) * 1274126177) & 0xffffffff+ return ((n ^ (n >> 16)) & 0xffff).astype(np.float32) / 65536.0+++def _bilerp(M, i, j):+ """bilinear sample of a 2D map at float (row, col) index coordinates, clamped to the edge"""+ H, W = M.shape+ i = np.clip(i, 0, H - 1.001); j = np.clip(j, 0, W - 1.001)+ i0 = i.astype(np.int32); j0 = j.astype(np.int32)+ fi = (i - i0).astype(np.float32); fj = (j - j0).astype(np.float32)+ return ((M[i0, j0] * (1 - fj) + M[i0, j0 + 1] * fj) * (1 - fi)+ + (M[i0 + 1, j0] * (1 - fj) + M[i0 + 1, j0 + 1] * fj) * fi)+++def _tex(T, u, v):+ """bilinear sample of an (h, w, C) texture at u, v in 0..1 (u right, v down)"""+ h, w = T.shape[:2]+ x = np.clip(u * w - 0.5, 0, w - 1.001); y = np.clip(v * h - 0.5, 0, h - 1.001)+ x0 = x.astype(np.int32); y0 = y.astype(np.int32)+ fx = (x - x0)[:, None]; fy = (y - y0)[:, None]+ return ((T[y0, x0] * (1 - fx) + T[y0, x0 + 1] * fx) * (1 - fy)+ + (T[y0 + 1, x0] * (1 - fx) + T[y0 + 1, x0 + 1] * fx) * fy)+++# ------------------------------------------------------------------ cameras+class _Cam:+ """orthographic camera: pixel (i, j) looks along v from C + a*r - b*u, a = (j+.5-W/2)/S, b = (i+.5-H/2)/S"""++ def __init__(self, C, r, u, v, S, W, H):+ self.C = np.asarray(C, np.float64); self.r = _unit(r); self.u = _unit(u); self.v = _unit(v)+ self.S = float(S); self.W = int(W); self.H = int(H)++ def cols(self, j):+ return ((np.asarray(j, np.float64) + 0.5 - self.W / 2) / self.S).astype(np.float32)[None, :]++ def rows(self, i):+ return ((np.asarray(i, np.float64) + 0.5 - self.H / 2) / self.S).astype(np.float32)[:, None]++ def project(self, P):+ d = np.asarray(P, np.float64) - self.C+ return (d @ self.r * self.S + self.W / 2 - 0.5, -(d @ self.u) * self.S + self.H / 2 - 0.5, d @ self.v)++ def bbox(self, lo, hi, pad=2):+ lo, hi = np.asarray(lo, np.float64), np.asarray(hi, np.float64)+ cs = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])])+ j, i, _ = self.project(cs)+ return (max(0, int(np.floor(i.min())) - pad), min(self.H, int(np.ceil(i.max())) + pad + 1),+ max(0, int(np.floor(j.min())) - pad), min(self.W, int(np.ceil(j.max())) + pad + 1))++ def points(self, a, b, t):+ return (self.C[None] + a[:, None] * self.r[None] - b[:, None] * self.u[None]+ + np.asarray(t, np.float64)[:, None] * self.v[None])+++# ------------------------------------------------------------------ analytic solids+class _Convex:+ """intersection of half-spaces n.X <= d; tag = index of the face hit"""++ def __init__(self, N, d, lo, hi):+ N = np.asarray(N, np.float64)+ nn = np.linalg.norm(N, axis=1, keepdims=True)+ self.N = N / nn; self.d = np.asarray(d, np.float64) / nn[:, 0]+ self.lo = np.asarray(lo, np.float64); self.hi = np.asarray(hi, np.float64)++ def trace(self, cam, a, b):+ shape = (b.shape[0], a.shape[1])+ tn = np.full(shape, -np.inf, np.float32); tf = np.full(shape, np.inf, np.float32)+ tag = np.zeros(shape, np.int16)+ for k, (n, d) in enumerate(zip(self.N, self.d)):+ dn = float(n @ cam.v)+ num = np.float32(d - n @ cam.C) - a * np.float32(n @ cam.r) + b * np.float32(n @ cam.u)+ if dn < -1e-9:+ t = num / np.float32(dn)+ upd = t > tn+ np.copyto(tn, t, where=upd); np.copyto(tag, np.int16(k), where=upd)+ elif dn > 1e-9:+ np.minimum(tf, num / np.float32(dn), out=tf)+ else:+ tf[num < 0] = -np.inf+ hit = tn <= tf+ return np.where(hit, tn, np.inf).astype(np.float32), tag, np.where(hit, tf, -np.inf).astype(np.float32)++ def normal(self, P, tag):+ return self.N[tag]+++class _Frustum:+ """solid cone frustum (cylinder when r0 == r1) from base B along unit axis A, length h; tag 0 side, 1 base, 2 top"""++ def __init__(self, B, A, h, r0, r1):+ self.B = np.asarray(B, np.float64); self.A = _unit(A); self.h = float(h); self.r0 = float(r0); self.r1 = float(r1)+ self.k = (self.r1 - self.r0) / self.h+ E = self.B + self.A * self.h; R = max(self.r0, self.r1)+ self.lo = np.minimum(self.B, E) - R; self.hi = np.maximum(self.B, E) + R++ def trace(self, cam, a, b):+ A = self.A; w0 = cam.C - self.B+ va = float(cam.v @ A); wv = float(w0 @ cam.v)+ wa = np.float32(w0 @ A) + a * np.float32(cam.r @ A) - b * np.float32(cam.u @ A)+ ww = (np.float32(w0 @ w0) + a * a + b * b + 2 * a * np.float32(w0 @ cam.r) - 2 * b * np.float32(w0 @ cam.u))+ pq = np.float32(wv) - wa * np.float32(va); pp = ww - wa * wa; qq = np.float32(1 - va * va)+ al = self.r0 + self.k * wa; be = np.float32(self.k * va)+ Aq = qq - be * be+ if abs(Aq) < 1e-7: Aq = np.float32(1e-7)+ Bq = pq - al * be; Cq = pp - al * al+ disc = Bq * Bq - Aq * Cq+ sq = np.sqrt(np.maximum(disc, 0))+ best = np.full(disc.shape, np.inf, np.float32); tag = np.zeros(disc.shape, np.int16)+ far = np.full(disc.shape, -np.inf, np.float32)+ for sgn in (-1, 1):+ t = (-Bq + sgn * sq) / Aq+ s = wa + t * np.float32(va)+ ok = (disc >= 0) & (s >= 0) & (s <= self.h)+ np.copyto(far, np.maximum(far, t), where=ok)+ np.copyto(best, t, where=ok & (t < best))+ if abs(va) > 1e-9:+ for tg, s0, rr in ((1, 0.0, self.r0), (2, self.h, self.r1)):+ t = (np.float32(s0) - wa) / np.float32(va)+ rad2 = pp + 2 * t * pq + t * t * qq+ ok = rad2 <= rr * rr+ np.copyto(far, np.maximum(far, t), where=ok)+ ok &= t < best+ np.copyto(best, t, where=ok); np.copyto(tag, np.int16(tg), where=ok)+ return best, tag, far++ def normal(self, P, tag):+ w = P - self.B+ s = w @ self.A+ m = w - s[:, None] * self.A[None]+ m = m / (np.linalg.norm(m, axis=1, keepdims=True) + 1e-9)+ n = m - self.k * self.A[None]+ n = n / np.linalg.norm(n, axis=1, keepdims=True)+ n[tag == 1] = -self.A; n[tag == 2] = self.A+ return n+++class _Ellipsoid:+ """ellipsoid (centre c, semi-axes R along the columns of M) cut by optional half-spaces n.X <= d; tag 0 = curved"""++ def __init__(self, c, R, M=None, clip=()):+ self.c = np.asarray(c, np.float64); self.R = np.asarray(R, np.float64)+ self.M = np.eye(3) if M is None else np.asarray(M, np.float64) # local -> world+ self.clip = [(_unit(n), float(d) / np.linalg.norm(n)) for n, d in clip]+ ext = np.sqrt(((self.M * self.R[None]) ** 2).sum(1))+ self.lo = self.c - ext; self.hi = self.c + ext++ def trace(self, cam, a, b):+ Mt = self.M.T # world -> local+ o0 = Mt @ (cam.C - self.c) / self.R; orr = Mt @ cam.r / self.R; ou = Mt @ cam.u / self.R+ dv = Mt @ cam.v / self.R+ A = float(dv @ dv)+ Bq = np.float32(o0 @ dv) + a * np.float32(orr @ dv) - b * np.float32(ou @ dv)+ oo = 0+ for k in range(3):+ ok = np.float32(o0[k]) + a * np.float32(orr[k]) - b * np.float32(ou[k])+ oo = oo + ok * ok+ disc = Bq * Bq - A * (oo - 1)+ sq = np.sqrt(np.maximum(disc, 0))+ tn = np.where(disc >= 0, (-Bq - sq) / A, np.inf).astype(np.float32)+ tf = np.where(disc >= 0, (-Bq + sq) / A, -np.inf).astype(np.float32)+ tag = np.zeros(tn.shape, np.int16)+ for k, (n, d) in enumerate(self.clip):+ dn = float(n @ cam.v)+ num = np.float32(d - n @ cam.C) - a * np.float32(n @ cam.r) + b * np.float32(n @ cam.u)+ if dn < -1e-9:+ t = num / np.float32(dn); upd = t > tn+ np.copyto(tn, t, where=upd); np.copyto(tag, np.int16(k + 1), where=upd)+ elif dn > 1e-9:+ np.minimum(tf, num / np.float32(dn), out=tf)+ else:+ tf[num < 0] = -np.inf+ hit = tn <= tf+ return np.where(hit, tn, np.inf).astype(np.float32), tag, np.where(hit, tf, -np.inf).astype(np.float32)++ def normal(self, P, tag):+ p = (P - self.c) @ self.M / self.R+ n = (p / self.R) @ self.M.T+ n = n / (np.linalg.norm(n, axis=1, keepdims=True) + 1e-12)+ for k, (cn, _) in enumerate(self.clip):+ n[tag == k + 1] = cn+ return n+++def _box_planes(lo, hi, bevel=0.0):+ N, d = [], []+ for ax in range(3):+ e = np.zeros(3); e[ax] = 1+ N += [e, -e]; d += [hi[ax], -lo[ax]]+ if bevel > 0:+ for a1, a2 in ((0, 1), (0, 2), (1, 2)):+ for s1 in (1, -1):+ for s2 in (1, -1):+ n = np.zeros(3); n[a1] = s1; n[a2] = s2+ e1 = hi[a1] if s1 > 0 else lo[a1]; e2 = hi[a2] if s2 > 0 else lo[a2]+ N.append(n); d.append(s1 * e1 + s2 * e2 - bevel)+ return np.array(N, np.float64), np.array(d, np.float64)+++class _Prim:+ __slots__ = ('solid', 'colour', 'paint', 'mat', 'cast', 'ao')++ def __init__(self, solid, colour, paint, mat, cast, ao):+ self.solid = solid; self.colour = colour; self.paint = paint; self.mat = mat; self.cast = cast; self.ao = ao+++# ------------------------------------------------------------------ the diorama+class Isometric:+ def __init__(self, W=1920, H=1080, seed=0, scale=72.0, look=(5.0, 5.0, 0.0), at=(0.56, 0.52),+ bounds=(-3, -3, -1.6, 13, 13, 8), sun=(0.36, -0.72, 0.52), ss=2, floor=-2.4, record=True,+ elevation=35.264, azimuth=45.0):+ self.W, self.H, self.ss = int(W), int(H), int(ss)+ self.seed = seed; self.rng = np.random.default_rng(seed)+ self.record = record; self.stages = []; self.overlays = []+ self.floor = float(floor)+ Ws, Hs = self.W * self.ss, self.H * self.ss+ self.Ws, self.Hs = Ws, Hs+ el, az = np.radians(elevation), np.radians(azimuth)+ v = -np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)])+ r = np.array([-np.sin(az), np.cos(az), 0.0])+ u = np.array([-np.cos(az) * np.sin(el), -np.sin(az) * np.sin(el), np.cos(el)])+ S = scale * self.ss+ look = np.asarray(look, np.float64)+ C = look - ((at[0] * Ws - Ws / 2) / S) * r + ((at[1] * Hs - Hs / 2) / S) * u+ self.cam = _Cam(C, r, u, v, S, Ws, Hs)+ self.scale = float(scale)+ # sun and its shadow camera+ self.L = _unit(sun)+ lv = -self.L; lr = _unit(np.cross([0, 0, 1.0], lv)); lu = np.cross(lv, lr)+ b0, b1 = np.array(bounds[:3], np.float64), np.array(bounds[3:], np.float64)+ cs = np.array([[x, y, z] for x in (b0[0], b1[0]) for y in (b0[1], b1[1]) for z in (b0[2], b1[2])])+ cen = (b0 + b1) / 2+ er = np.abs((cs - cen) @ lr).max(); eu = np.abs((cs - cen) @ lu).max()+ Sl = min(150.0, 2600 / (2 * max(er, eu)))+ self.lcam = _Cam(cen, lr, lu, lv, Sl, int(2 * er * Sl) + 8, int(2 * eu * Sl) + 8)+ St = 90.0+ self.tcam = _Cam((cen[0], cen[1], b1[2] + 1), (1, 0, 0), (0, -1, 0), (0, 0, -1), St,+ int((b1[0] - b0[0]) * St) + 8, int((b1[1] - b0[1]) * St) + 8)+ # buffers+ self.dep = np.full((Hs, Ws), np.inf, np.float32)+ self.nrm = np.zeros((Hs, Ws, 3), np.float16)+ self.alb = np.zeros((Hs, Ws, 3), np.float16)+ self.mat = np.zeros((Hs, Ws), np.uint8)+ self.ldep = np.full((self.lcam.H, self.lcam.W), np.inf, np.float32)+ self.tdep = np.full((self.tcam.H, self.tcam.W), np.inf, np.float32)+ self.tbot = np.full((self.tcam.H, self.tcam.W), -np.inf, np.float32)+ # light: a warm low sun, a lilac-blue sky, a warm bounce from below+ self.sun_c = np.array([1.0, 0.955, 0.87], np.float32) * 0.52+ self.sky_c = np.array([0.735, 0.735, 0.875], np.float32)+ self.hor_c = np.array([0.705, 0.690, 0.790], np.float32)+ self.gnd_c = np.array([0.760, 0.700, 0.700], np.float32)+ self.soft = 0.085 # penumbra growth per unit of receiver-blocker distance (the sun's size)+ self.pen = (0.012, 0.55) # smallest / largest penumbra radius (world units)+ self.bg = ('#e6e1f4', '#f6efef', '#fbf8ff')+ self.glow_centre = tuple(look)+ self.sea_z = 0.14++ # ------------------------------------------------------------ helpers+ def iso(self, x, y, z=0.0):+ """world point -> output-image pixel (x, y)"""+ j, i, _ = self.cam.project(np.array([x, y, z], np.float64))+ return float((j + 0.5) / self.ss), float((i + 0.5) / self.ss)++ def unproject(self, sx, sy, z=0.0):+ """output-image pixel (sx, sy) -> the world point on the horizontal plane at height z that lands there"""+ cam = self.cam+ a = (sx * self.ss - self.Ws / 2) / cam.S; b = (sy * self.ss - self.Hs / 2) / cam.S+ Q = cam.C + a * cam.r - b * cam.u+ t = (z - Q[2]) / cam.v[2]+ P = Q + t * cam.v+ return float(P[0]), float(P[1]), float(z)++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ def add(self, solid, colour='#ffffff', paint=None, mat='matte', cast=True, ao=True):+ """rasterise any analytic solid into the camera G-buffer, the sun's shadow map and the height map"""+ pr = _Prim(solid, _c(colour), paint, _MAT[mat] if isinstance(mat, str) else mat, cast, ao)+ self._raster_g(pr)+ if cast: self._raster_d(self.lcam, self.ldep, solid)+ if ao: self._raster_d(self.tcam, self.tdep, solid, self.tbot)+ return pr++ def _raster_g(self, pr):+ cam = self.cam+ i0, i1, j0, j1 = cam.bbox(pr.solid.lo, pr.solid.hi)+ if i1 <= i0 or j1 <= j0: return+ a = cam.cols(np.arange(j0, j1))+ step = max(8, 600000 // max(1, j1 - j0))+ for r0 in range(i0, i1, step):+ r1 = min(i1, r0 + step)+ b = cam.rows(np.arange(r0, r1))+ t, tag, _ = pr.solid.trace(cam, a, b)+ sub = self.dep[r0:r1, j0:j1]+ m = t < sub+ if not m.any(): continue+ ii, jj = np.nonzero(m)+ tt = t[ii, jj]; tg = tag[ii, jj]+ P = cam.points(a[0, jj].astype(np.float64), b[ii, 0].astype(np.float64), tt)+ n = pr.solid.normal(P, tg)+ if pr.paint is not None:+ col = np.asarray(pr.paint(P, n, tg), np.float32)+ else:+ col = np.broadcast_to(pr.colour, (len(tt), 3))+ sub[ii, jj] = tt+ self.nrm[r0 + ii, j0 + jj] = n+ self.alb[r0 + ii, j0 + jj] = col+ self.mat[r0 + ii, j0 + jj] = pr.mat++ def _raster_d(self, cam, buf, solid, bot=None):+ """depth-only pass (shadow map, or the top-down map). For the top-down map `bot` keeps the bottom of the+ topmost column: solids that touch or overlap merge into one column, a solid floating above replaces it+ (so an eave or a tree crown is a slab in the air, not a pillar down to the ground)"""+ i0, i1, j0, j1 = cam.bbox(solid.lo, solid.hi)+ if i1 <= i0 or j1 <= j0: return+ a = cam.cols(np.arange(j0, j1))+ step = max(8, 600000 // max(1, j1 - j0))+ for r0 in range(i0, i1, step):+ r1 = min(i1, r0 + step)+ t, _, tout = solid.trace(cam, a, cam.rows(np.arange(r0, r1)))+ T = buf[r0:r1, j0:j1]+ if bot is None:+ np.minimum(T, t, out=T); continue+ B = bot[r0:r1, j0:j1]+ hit = np.isfinite(t)+ touch = hit & (t <= B + 0.004) & (tout >= T - 0.004)+ above = hit & ~touch & (t < T)+ np.copyto(B, np.maximum(B, tout), where=touch); np.copyto(T, np.minimum(T, t), where=touch)+ np.copyto(B, tout, where=above); np.copyto(T, t, where=above)++ # ------------------------------------------------------------ primitives+ def box(self, x0, y0, z0, x1, y1, z1, colour='#f4f1ee', side=None, bevel=0.022, paint=None, **kw):+ """axis-aligned block with chamfered edges; `side` colours the walls (default: same as the top)"""+ lo = np.array([min(x0, x1), min(y0, y1), min(z0, z1)]); hi = np.array([max(x0, x1), max(y0, y1), max(z0, z1)])+ bev = min(bevel, 0.45 * (hi - lo).min())+ N, d = _box_planes(lo, hi, bev)+ if paint is None and side is not None:+ ct, cs = _c(colour), _c(side)+ paint = lambda P, n, t: np.where(n[:, 2:3] > 0.5, ct, cs)+ return self.add(_Convex(N, d, lo, hi), colour, paint, **kw)++ def obox(self, centre, size, yaw=0.0, pitch=0.0, roll=0.0, colour='#f4f1ee', bevel=0.015, paint=None, **kw):+ """oriented block: `size` = full extents along its local axes, rotated by yaw / pitch / roll (degrees)"""+ R = rot(yaw, pitch, roll); c = np.asarray(centre, np.float64); h = np.asarray(size, np.float64) / 2+ N, d = _box_planes(-h, h, min(bevel, 0.45 * (2 * h).min()))+ Nw = N @ R.T+ dw = d + Nw @ c+ ext = np.abs(R) @ h+ return self.add(_Convex(Nw, dw, c - ext, c + ext), colour, paint, **kw)++ def convex(self, planes, lo, hi, colour='#f4f1ee', paint=None, **kw):+ """any convex solid given as [(normal, d), ...] meaning normal . X <= d, with its world bounding box"""+ N = [p[0] for p in planes]; d = [p[1] for p in planes]+ return self.add(_Convex(N, d, lo, hi), colour, paint, **kw)++ def prism(self, pts, z0, z1, colour='#f4f1ee', paint=None, **kw):+ """vertical extrusion of a convex footprint polygon (counter-clockwise or clockwise, any order of turn)"""+ P = np.asarray(pts, np.float64); c = P.mean(0)+ N, d = [[0, 0, 1], [0, 0, -1]], [z1, -z0]+ for k in range(len(P)):+ p, q = P[k], P[(k + 1) % len(P)]+ n = np.array([q[1] - p[1], -(q[0] - p[0]), 0.0])+ if n[:2] @ (c - p) > 0: n = -n+ N.append(n); d.append(n[:2] @ p)+ lo = np.r_[P.min(0), z0]; hi = np.r_[P.max(0), z1]+ return self.add(_Convex(N, d, lo, hi), colour, paint, **kw)++ def cylinder(self, x, y, z0, z1, r, colour='#f4f1ee', r1=None, paint=None, **kw):+ """upright cylinder, or a cone / frustum when r1 is given"""+ return self.add(_Frustum((x, y, z0), (0, 0, 1), z1 - z0, r, r if r1 is None else r1), colour, paint, **kw)++ def tube(self, p0, p1, r, colour='#f4f1ee', r1=None, paint=None, **kw):+ """cylinder (or cone) between two world points: arms, rails, wires, masts, pipes"""+ p0, p1 = np.asarray(p0, np.float64), np.asarray(p1, np.float64)+ L = float(np.linalg.norm(p1 - p0))+ return self.add(_Frustum(p0, p1 - p0, L, r, r if r1 is None else r1), colour, paint, **kw)++ def ellipsoid(self, centre, radii, colour='#f4f1ee', yaw=0.0, pitch=0.0, roll=0.0, clip=(), paint=None, **kw):+ """ellipsoid with semi-axes `radii`, rotated; `clip` = [(normal, d)] half-spaces cut it (flat bottoms, cups)"""+ return self.add(_Ellipsoid(centre, radii, rot(yaw, pitch, roll), clip), colour, paint, **kw)++ def sphere(self, x, y, z, r, colour='#f4f1ee', **kw):+ return self.ellipsoid((x, y, z), (r, r, r), colour, **kw)++ def dome(self, x, y, z, r, colour='#f4f1ee', h=None, **kw):+ """half ellipsoid sitting on z (radius r, height h)"""+ return self.ellipsoid((x, y, z), (r, r, r if h is None else h), colour, clip=[((0, 0, -1), -z)], **kw)++ # ------------------------------------------------------------ ground+ def backdrop(self, top='#e6e1f4', bottom='#f6efef', glow='#fbf8ff', centre=None):+ """the light vertical gradient the diorama floats in front of, with a soft pale glow behind world point+ `centre` (default: the look point). Its invisible floor lies at `floor`, far below the slab, and takes the+ slab's shadow."""+ self.bg = (top, bottom, glow)+ if centre is not None: self.glow_centre = tuple(centre)++ def slab(self, x0, y0, x1, y1, z0=-1.1, z1=0.0, top='#e4dcf2',+ layers=(('#f1dccb', 0.10), ('#dccff1', 0.30), ('#cdbfec', 0.28), ('#bfb0e6', 0.42)), bevel=0.05):+ """the floating base: a thick block whose walls show layered strata with gently wavy boundaries"""+ cols = [_c(c) for c, _ in layers]+ edges = np.cumsum([h for _, h in layers])+ ct = _c(top); seed = self._seed()+ ph = np.random.default_rng(seed).uniform(0, 6.28, (len(layers), 3))++ def paint(P, n, t):+ s = P[:, 0] + P[:, 1]+ depth = z1 - P[:, 2]+ k = np.zeros(len(P), np.int32)+ for li in range(len(layers) - 1):+ wav = 0.025 * np.sin(s * 1.7 + ph[li, 0]) + 0.012 * np.sin(s * 4.3 + ph[li, 1])+ k += (depth > edges[li] + wav * (li > 0)).astype(np.int32)+ out = np.stack(cols)[np.minimum(k, len(cols) - 1)]+ return np.where(n[:, 2:3] > 0.5, ct, out)+ self.box(x0, y0, z0, x1, y1, z1, top, bevel=bevel, paint=paint)++ def tiles(self, levels, x0=0.0, y0=0.0, heights=None, colours=None, soil=None, gap=0.028, bevel=0.03, paved=(4,)):+ """ground tiles on a grid: levels[i][j] is the level of cell (x0 + i, y0 + j); 0 = none (sea).+ Default levels: 1 sand, 2 grass, 3 raised grass (terrace), 4 paving. Each tile is its own chamfered block+ with a gap round it; the terrace shows a soil band under the turf; paved levels are cut into flagstones."""+ L = np.asarray(levels)+ heights = heights or {1: 0.22, 2: 0.32, 3: 0.60, 4: 0.30}+ colours = colours or {1: ['#f7e3c6', '#f4ddbd', '#f8e8cf'], 2: ['#a9e0c2', '#a1dbba', '#b1e5c9'],+ 3: ['#9dd8b8', '#a6dfc0', '#95d1b0'], 4: ['#e3ddef', '#ddd6ec', '#e8e3f3']}+ soil = soil or {1: '#f1d6b8', 2: '#e9cdb4', 3: '#e3c3a8', 4: '#d3cbe6'}+ rng = np.random.default_rng(self._seed())+ self.levels = L; self.grid0 = (x0, y0); self.heights = heights+ for i in range(L.shape[0]):+ for j in range(L.shape[1]):+ lv = int(L[i, j])+ if lv <= 0: continue+ h = heights[lv]; ct = _c(colours[lv][rng.integers(len(colours[lv]))]); cs = _c(soil[lv])+ turf = 0.07 if lv == 3 else h+ cside = ct * 0.96+ pave = lv in paved++ def paint(P, n, t, h=h, ct=ct, cs=cs, turf=turf, cside=cside, pave=pave):+ top = n[:, 2:3] > 0.5+ band = (P[:, 2:3] > h - turf)+ col = np.where(top, ct, np.where(band, cside, cs))+ if pave:+ fx = np.mod(P[:, 0] - x0, 0.5); fy = np.mod(P[:, 1] - y0 + 0.25 * (np.floor((P[:, 0] - x0) * 2) % 2), 0.5)+ jt = ((np.minimum(fx, 0.5 - fx) < 0.011) | (np.minimum(fy, 0.5 - fy) < 0.011)) & top[:, 0]+ col = np.where(jt[:, None], ct * 0.9, col)+ return col+ self.box(x0 + i + gap, y0 + j + gap, 0.0, x0 + i + 1 - gap, y0 + j + 1 - gap, h, ct, bevel=bevel, paint=paint)++ def top_z(self, x, y):+ """height of the tile under world point (x, y) (0.14 on the sea)"""+ i, j = int(np.floor(x - self.grid0[0])), int(np.floor(y - self.grid0[1]))+ if 0 <= i < self.levels.shape[0] and 0 <= j < self.levels.shape[1] and self.levels[i, j] > 0:+ return self.heights[int(self.levels[i, j])]+ return self.sea_z++ def sea(self, levels=None, x0=None, y0=None, z=0.14, shallow='#bfe8e6', deep='#a6c9f0', foam='#fbfdff',+ side='#c5dcf6', waves=0.6):+ """water in every level-0 cell: shore foam hugging the tiles, a second broken wave line, a tint from+ shallow to deep with distance from land, sparse wave dashes, and clear glassy walls at the slab edge"""+ L = self.levels if levels is None else np.asarray(levels)+ gx0, gy0 = (self.grid0 if x0 is None else (x0, y0))+ self.sea_z = z+ # distance to the nearest land cell, on a fine grid+ R = 40; nx, ny = L.shape+ xs = (np.arange(nx * R) + 0.5) / R; ys = (np.arange(ny * R) + 0.5) / R+ X, Y = np.meshgrid(xs, ys, indexing='ij')+ D = np.full(X.shape, 9.0, np.float32)+ for i, j in zip(*np.nonzero(L > 0)):+ dx = np.maximum(np.maximum(i - X, X - (i + 1)), 0); dy = np.maximum(np.maximum(j - Y, Y - (j + 1)), 0)+ np.minimum(D, np.hypot(dx, dy), out=D)+ cs, cd, cf, cw = _c(shallow), _c(deep), _c(foam), _c(side)+ seed = self._seed()++ def paint(P, n, t):+ lx, ly = P[:, 0] - gx0, P[:, 1] - gy0+ d = _bilerp(D, lx * R - 0.5, ly * R - 0.5)+ k = smoothstep(0.0, 1.6, d)[:, None]+ col = cs * (1 - k) + cd * k+ wob = 0.018 * np.sin(lx * 9.0 + ly * 3.1) + 0.012 * np.sin(ly * 11.0 - lx * 2.3)+ f1 = 1 - smoothstep(0.045, 0.075, d + wob)+ line = np.abs(d - 0.19 + wob * 1.4)+ brk = _hash(np.floor((lx - ly) * 3.1).astype(np.int64), np.floor((lx + ly) * 1.3).astype(np.int64), seed) > 0.28+ f2 = (1 - smoothstep(0.010, 0.020, line)) * brk * 0.85+ # sparse wave dashes out at sea: short strokes along the x - y diagonal+ cu, cv = (ly - lx) * 0.55, (lx + ly) * 2.2+ iu, iv = np.floor(cu).astype(np.int64), np.floor(cv).astype(np.int64)+ hsh = _hash(iu, iv, seed + 7)+ fu, fv = cu - iu, cv - iv+ dash = (hsh < 0.16 * waves) & (np.abs(fv - 0.5) < 0.075) & (np.abs(fu - 0.5 - 0.1 * (hsh - 0.1)) < 0.09 + 0.1 * hsh)+ f3 = dash * smoothstep(0.35, 0.8, d) * 0.8+ f = np.clip(np.maximum(np.maximum(f1, f2), f3), 0, 1)[:, None]+ top = n[:, 2:3] > 0.5+ wall = cw * (0.92 + 0.08 * np.clip((P[:, 2:3] + 0.0) / z, 0, 1))+ lip = (P[:, 2:3] > z - 0.02)+ wall = np.where(lip, cf * 0.97, wall)+ return np.where(top, col * (1 - f) + cf * f, wall)+ for i in range(nx): # runs of sea cells along y+ j = 0+ while j < ny:+ if L[i, j] > 0: j += 1; continue+ j1 = j+ while j1 < ny and L[i, j1] == 0: j1 += 1+ self.box(gx0 + i, gy0 + j, 0.0, gx0 + i + 1, gy0 + j1, z, shallow, bevel=0.0, paint=paint, mat='water')+ j = j1++ def road(self, x0, y0, x1, y1, z=0.0, h=0.05, colour='#d9d4e8', line='#fbfaff', dash=(0.22, 0.16), kerb=None):+ """a flat road slab with a dashed centre line along its long axis (and optional lighter kerbs)"""+ along_x = abs(x1 - x0) >= abs(y1 - y0)+ cc, cl = _c(colour), _c(line); ck = _c(kerb) if kerb else None+ mid = (y0 + y1) / 2 if along_x else (x0 + x1) / 2+ half = (abs(y1 - y0) if along_x else abs(x1 - x0)) / 2++ def paint(P, n, t):+ s = P[:, 0] if along_x else P[:, 1]; q = (P[:, 1] if along_x else P[:, 0]) - mid+ on = (np.abs(q) < 0.028) & (np.mod(s, dash[0] + dash[1]) < dash[0]) & (n[:, 2] > 0.5)+ out = np.where(on[:, None], cl, cc)+ if ck is not None:+ out = np.where((np.abs(q) > half - 0.07)[:, None] & (n[:, 2:3] > 0.5), ck, out)+ return out+ return self.box(x0, y0, z, x1, y1, z + h, colour, bevel=0.012, paint=paint)++ def path(self, cells, z=None, colour='#e6e0f1', joint='#cfc6e4', h=0.26, gap=0.035):+ """paved slabs on any list of cells (x, y), e.g. a walkway on a roof or a quay; each is cut into four+ flagstones by fine joints (for paving inside the ground grid use level 4 in `tiles`)"""+ cc, cj = _c(colour), _c(joint)+ for (x, y) in cells:+ zz = 0.0 if z is None else z++ def paint(P, n, t):+ fx = np.mod(P[:, 0], 0.5); fy = np.mod(P[:, 1], 0.5)+ jt = ((np.minimum(fx, 0.5 - fx) < 0.012) | (np.minimum(fy, 0.5 - fy) < 0.012)) & (n[:, 2] > 0.5)+ return np.where(jt[:, None], cj, cc)+ self.box(x + gap, y + gap, zz, x + 1 - gap, y + 1 - gap, zz + h, colour, bevel=0.03, paint=paint)++ # ------------------------------------------------------------ architecture+ def roof(self, x0, y0, x1, y1, z, h, kind='gable', axis='x', overhang=0.08, colour='#f2a494', gable='#f7f2ee',+ courses=0.11, thick=0.05):+ """gable (ridge along `axis`), hip (all four sides at one pitch) or shed (falling toward +x) roof on the+ rectangle, with eaves, tile courses and a light fascia along the lower edge; gable ends take the wall colour"""+ x0, x1 = x0 - overhang, x1 + overhang; y0, y1 = y0 - overhang, y1 + overhang+ z0 = z - thick+ cr, cg = _c(colour), _c(gable)+ N, d, slopes = [(0, 0, -1)], [-z0], []+ if kind == 'gable':+ if axis == 'x':+ k = h / ((y1 - y0) / 2)+ N += [(0, k, 1), (0, -k, 1), (1, 0, 0), (-1, 0, 0)]; d += [k * y1 + z, -k * y0 + z, x1, -x0]+ else:+ k = h / ((x1 - x0) / 2)+ N += [(k, 0, 1), (-k, 0, 1), (0, 1, 0), (0, -1, 0)]; d += [k * x1 + z, -k * x0 + z, y1, -y0]+ slopes = [1, 2]+ elif kind == 'hip':+ k = h / (min(x1 - x0, y1 - y0) / 2)+ N += [(k, 0, 1), (-k, 0, 1), (0, k, 1), (0, -k, 1)]; d += [k * x1 + z, -k * x0 + z, k * y1 + z, -k * y0 + z]+ slopes = [1, 2, 3, 4]+ else:+ k = h / (x1 - x0)+ N += [(k, 0, 1), (-1, 0, 0), (1, 0, 0), (0, 1, 0), (0, -1, 0)]; d += [k * x0 + z + h, -x0, x1, y1, -y0]+ slopes = [1]+ N = np.array(N, np.float64); d = np.array(d, np.float64)++ def paint(P, n, t):+ slope = np.isin(t, slopes)[:, None]+ zz = P[:, 2:3]+ crs = np.mod((zz - z0) / courses, 1.0)+ line = (crs < 0.13) & slope+ fas = (zz < z0 + thick * 0.95) & slope+ col = np.where(line, cr * 0.91, cr)+ col = np.where(fas, np.minimum(cr * 1.1 + 0.02, 1.0), col)+ return np.where(slope, col, np.where(np.abs(n[:, 2:3]) > 0.9, cr * 0.8, cg))+ lo = (x0, y0, z0); hi = (x1, y1, z + h + 0.01)+ return self.add(_Convex(N, d, lo, hi), colour, paint)++ def window(self, x, y, z, w=0.22, h=0.28, facing='+x', frame='#fbfaf8', glass='#a9c8ee', sill=True, mullion=True):+ """a window on a wall: (x, y) is the wall point under its centre, z its bottom. A white frame, glass with a+ diagonal sky sheen and a cross mullion, and a sill that throws a thin shadow"""+ ax = 0 if facing[1] == 'x' else 1; sg = 1 if facing[0] == '+' else -1+ o = np.array([x, y], np.float64)+ e = np.zeros(2); e[ax] = sg # out of the wall+ t = np.zeros(2); t[1 - ax] = 1 # along the wall+ cg, cf = _c(glass), _c(frame)++ def seg(u0, u1, out0, out1, z0, z1, col, paint=None, mat='matte', bev=0.006):+ p0 = o + t * u0 + e * out0; p1 = o + t * u1 + e * out1+ self.box(p0[0], p0[1], z0, p1[0], p1[1], z1, col, bevel=bev, paint=paint, mat=mat, ao=False)+ seg(-w / 2 - 0.025, w / 2 + 0.025, -0.01, 0.018, z - 0.025, z + h + 0.025, frame)++ def gpaint(P, n, tg):+ along = (P[:, :2] - o) @ t+ vz = (P[:, 2] - z) / h+ sheen = np.abs((along / w + 0.5) * 0.8 + vz - 0.95) < 0.09+ sheen |= np.abs((along / w + 0.5) * 0.8 + vz - 1.2) < 0.035+ col = cg * (0.92 + 0.14 * vz[:, None])+ col = np.where(sheen[:, None], np.minimum(col * 1.18 + 0.05, 1), col)+ if mullion:+ mm = (np.abs(along) < 0.011) | (np.abs(vz - 0.52) * h < 0.011)+ col = np.where(mm[:, None], cf, col)+ return col+ seg(-w / 2, w / 2, -0.01, 0.024, z, z + h, glass, paint=gpaint, mat='glass', bev=0.0)+ if sill:+ seg(-w / 2 - 0.04, w / 2 + 0.04, -0.01, 0.06, z - 0.045, z - 0.012, frame)++ def door(self, x, y, z, w=0.26, h=0.46, facing='+x', colour='#f6d98a', frame='#fbfaf8', canopy=True):+ """a door with a frame, a small window pane, a knob and a little canopy above it"""+ ax = 0 if facing[1] == 'x' else 1; sg = 1 if facing[0] == '+' else -1+ o = np.array([x, y], np.float64); e = np.zeros(2); e[ax] = sg; t = np.zeros(2); t[1 - ax] = 1++ def seg(u0, u1, out0, out1, z0, z1, col, **kw):+ p0 = o + t * u0 + e * out0; p1 = o + t * u1 + e * out1+ self.box(p0[0], p0[1], z0, p1[0], p1[1], z1, col, ao=False, **kw)+ seg(-w / 2 - 0.03, w / 2 + 0.03, -0.01, 0.016, z, z + h + 0.03, frame, bevel=0.006)+ cd = _c(colour)++ def dpaint(P, n, tg):+ along = (P[:, :2] - o) @ t; vz = (P[:, 2] - z) / h+ pane = (np.abs(along) < w * 0.26) & (vz > 0.62) & (vz < 0.86)+ panel = (np.abs(np.abs(along) - w * 0.3) < 0.006) & (vz < 0.5) & (vz > 0.12)+ col = np.where(pane[:, None], _c('#bcd5f2'), cd)+ return np.where(panel[:, None], cd * 0.9, col)+ seg(-w / 2, w / 2, -0.01, 0.022, z, z + h, colour, bevel=0.004, paint=dpaint)+ k = o + t * (w * 0.3) + e * 0.03+ self.sphere(k[0], k[1], z + h * 0.45, 0.014, '#f7f3ea', ao=False)+ if canopy:+ seg(-w / 2 - 0.08, w / 2 + 0.08, -0.01, 0.16, z + h + 0.06, z + h + 0.1, frame, bevel=0.01)++ def building(self, x0, y0, x1, y1, z=0.0, h=1.0, wall='#f7f3ef', roof='gable', roof_colour='#f2a494', axis='x',+ roof_h=None, windows=(1, 2, 2), window_h=0.26, door=None, trim=None):+ """a house or block: walls, a roof ('gable' / 'hip' / 'shed' / 'flat'), windows = (rows, n on the +x wall,+ n on the +y wall) -- the two walls the camera sees (+x faces lower left, +y lower right) --, an optional+ door = ('+x' or '+y', position along that wall) and an optional trim band at the foot of the walls"""+ cw = _c(wall); tr = _c(trim) if trim else None++ def wpaint(P, n, t):+ if tr is None: return np.broadcast_to(cw, (len(P), 3))+ band = (P[:, 2:3] < z + 0.07)+ return np.where(band & (np.abs(n[:, 2:3]) < 0.5), tr, cw)+ self.box(x0, y0, z, x1, y1, z + h, wall, bevel=0.02, paint=wpaint)+ if roof == 'flat':+ self.box(x0 - 0.03, y0 - 0.03, z + h, x1 + 0.03, y1 + 0.03, z + h + 0.07, roof_colour, bevel=0.015)+ else:+ rh = roof_h if roof_h is not None else 0.42 * ((y1 - y0) if axis == 'x' else (x1 - x0))+ self.roof(x0, y0, x1, y1, z + h, rh, kind=roof, axis=axis, colour=roof_colour, gable=wall)+ rows, nx, ny = windows+ for face, (a0, a1), fixed, n in (('+x', (y0, y1), x1, nx), ('+y', (x0, x1), y1, ny)):+ for rr in range(rows):+ zz = z + (rr + 0.5) * h / rows - window_h / 2 + 0.02+ for cc in range(n):+ s = a0 + (cc + 0.5) * (a1 - a0) / n+ if door and door[0] == face and abs(s - door[1]) < 0.3 and rr == 0: continue+ if face == '+x': self.window(fixed, s, zz, 0.2, window_h, '+x')+ else: self.window(s, fixed, zz, 0.2, window_h, '+y')+ if door:+ face, s = door+ if face == '+x': self.door(x1, s, z, facing='+x')+ else: self.door(s, y1, z, facing='+y')++ # ------------------------------------------------------------ nature+ def tree(self, x, y, z=0.0, size=1.0, kind='round', colour=None, trunk='#d7b49c', seed=None, flowers=None):+ """'round' (lumpy crown of three puffs), 'pine' (stacked cones), 'poplar' (tall column), 'bush';+ a bush can carry `flowers` (a colour or a list): small blossoms dotted over the top of its puffs"""+ rng = np.random.default_rng(self._seed() if seed is None else seed)+ s = size+ if kind == 'bush':+ col = colour or ['#9fdcb9', '#93d3ae', '#abe3c3'][rng.integers(3)]+ puffs = []+ for k in range(3):+ a = rng.uniform(0, 6.28) + k * 2.1; d = 0.06 * s+ r = s * rng.uniform(0.07, 0.1)+ c = (x + d * np.cos(a), y + d * np.sin(a), z + r * 0.55); puffs.append((c, r))+ self.ellipsoid(c, (r, r, r * 0.85), col, mat='soft', clip=[((0, 0, -1), -z)])+ if flowers:+ fl = [flowers] if isinstance(flowers, str) else list(flowers)+ for k in range(9):+ (cx, cy, cz), r = puffs[k % 3]+ th, ph = rng.uniform(0, 6.28), rng.uniform(0.15, 0.95)+ p = (cx + r * np.sin(ph) * np.cos(th), cy + r * np.sin(ph) * np.sin(th), cz + r * 0.85 * np.cos(ph))+ self.sphere(*p, 0.018 * s, fl[k % len(fl)], ao=False)+ return+ if kind == 'pine':+ col = colour or ['#86cfa3', '#7cc79b', '#8fd6ab'][rng.integers(3)]+ self.cylinder(x, y, z, z + 0.16 * s, 0.03 * s, trunk)+ zz = z + 0.1 * s+ for k, (r, hh) in enumerate(((0.2, 0.3), (0.16, 0.27), (0.11, 0.24))):+ self.cylinder(x, y, zz, zz + hh * s, r * s, col, r1=0.012 * s, mat='soft')+ zz += hh * s * 0.52+ return+ if kind == 'poplar':+ col = colour or ['#addfc4', '#a6dcc0'][rng.integers(2)]+ self.cylinder(x, y, z, z + 0.14 * s, 0.028 * s, trunk)+ self.ellipsoid((x, y, z + 0.5 * s), (0.13 * s, 0.13 * s, 0.4 * s), col, mat='soft')+ return+ col = colour or ['#a3dfbd', '#97d6b2', '#aee6c6', '#9bd8c0'][rng.integers(4)]+ th = 0.2 * s+ self.cylinder(x, y, z, z + th + 0.1 * s, 0.035 * s, trunk)+ R = 0.25 * s+ cz = z + th + R * 0.9+ self.ellipsoid((x, y, cz), (R, R, R * 0.95), col, mat='soft')+ for k in range(2):+ a = rng.uniform(0, 6.28)+ rr = R * rng.uniform(0.55, 0.7)+ self.ellipsoid((x + np.cos(a) * R * 0.55, y + np.sin(a) * R * 0.55, cz + R * rng.uniform(-0.15, 0.35)),+ (rr, rr, rr * 0.95), _c(col) * rng.uniform(0.97, 1.02), mat='soft')++ def rock(self, x, y, z=0.0, r=0.14, colour='#d8d0ea', seed=None):+ """a low-poly boulder: random facets around a squashed sphere, flat on the ground"""+ rng = np.random.default_rng(self._seed() if seed is None else seed)+ N, d = [(0, 0, -1)], [-z]+ c = np.array([x, y, z + r * 0.2])+ k = np.arange(13) + 0.5 # facets spread evenly over the upper half+ th = k * 2.39996 + rng.uniform(0, 6.28); ph = np.arccos(1 - k / 13 * 0.95)+ for t_, p_ in zip(th, ph):+ n = _unit(np.array([np.sin(p_) * np.cos(t_), np.sin(p_) * np.sin(t_), np.cos(p_)]) + rng.normal(0, 0.12, 3))+ N.append(n); d.append(n @ c + r * rng.uniform(0.8, 1.0) * np.sqrt(n[0] ** 2 + n[1] ** 2 + (0.62 * n[2]) ** 2))+ return self.convex(list(zip(N, d)), c - r * 1.3, c + r * 1.3, colour)++ def cloud(self, x, y, z, size=1.0, colour='#fbfaff', seed=None, cast=True):+ """a flat-bottomed cloud of overlapping puffs, softly lit; floats, so it casts a very soft shadow"""+ rng = np.random.default_rng(self._seed() if seed is None else seed)+ s = size+ puffs = [(0, 0, 0.42), (0.34, -0.3, 0.3), (-0.36, 0.32, 0.3), (0.12, 0.42, 0.26), (-0.1, -0.44, 0.24)]+ for dx, dy, r in puffs:+ r = r * s * rng.uniform(0.9, 1.1)+ self.ellipsoid((x + dx * s, y + dy * s, z + r * 0.15), (r, r, r * 0.9), colour, mat='soft',+ clip=[((0, 0, -1), -(z - 0.02 * s))], cast=cast, ao=False)++ # ------------------------------------------------------------ machines and props+ def windmill(self, x, y, z=0.0, h=2.4, yaw=35.0, spin=15.0, colour='#fbfaf8', accent='#f19a8e', blade=0.9):+ """a small wind turbine: tapered tower, nacelle, hub and three slim blades (accent-tipped)"""+ self.cylinder(x, y, z, z + h, 0.055, colour, r1=0.03)+ R = rot(yaw)+ f = R @ np.array([1.0, 0, 0]) # the way the rotor faces+ top = np.array([x, y, z + h])+ self.obox(top + f * 0.03 + np.array([0, 0, 0.02]), (0.26, 0.09, 0.09), yaw=yaw, colour=colour, bevel=0.02)+ hub = top + f * 0.19 + np.array([0, 0, 0.02])+ self.ellipsoid(hub, (0.07, 0.045, 0.045), colour, yaw=yaw)+ ca = _c(accent); cc = _c(colour)+ for k in range(3):+ ang = spin + 120 * k+ ctr = hub + (R @ np.array([0.0, np.cos(np.radians(ang)), np.sin(np.radians(ang))])) * (blade / 2 + 0.03)++ def bp(P, n, t, hub=hub):+ dd = np.linalg.norm(P - hub, axis=1)+ return np.where((dd > blade * 0.86)[:, None], ca, cc)+ self.ellipsoid(ctr, (0.012, blade / 2, 0.045), colour, yaw=yaw, roll=ang, paint=bp)++ def dish(self, x, y, z=0.0, r=0.2, yaw=35.0, tilt=50.0, h=0.45, colour='#fbfaf8', face='#eeeaf6', accent='#f19a8e'):+ """a satellite dish on a post: a shallow bowl (half an ellipsoid; its flat face is the reflector, shaded+ darker toward the rim), a feed arm and a small receiver at the focus. The dish looks along yaw / tilt"""+ el = np.radians(90 - tilt); az = np.radians(yaw)+ f = np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)]) # where it looks+ c = np.array([x, y, z + h])+ self.cylinder(x, y, z, z + h - 0.02, 0.022, colour)+ # local frame: third axis = f+ e3 = f; e1 = _unit(np.cross([0, 0, 1.0], e3)); e2 = np.cross(e3, e1)+ M = np.stack([e1, e2, e3], 1)+ cf = _c(face)++ def paint(P, n, t):+ q = np.linalg.norm((P - c) - ((P - c) @ e3)[:, None] * e3[None], axis=1) / r+ bowl = cf * (0.86 + 0.16 * q[:, None] ** 2) # a concave face: darker in the middle+ bowl = np.where((q > 0.9)[:, None], _c(colour), bowl) # the rolled rim+ return np.where((t == 1)[:, None], bowl, _c(colour))+ self.add(_Ellipsoid(c, (r, r, r * 0.35), M, clip=[(e3, e3 @ c)]), colour, paint)+ tip = c + f * r * 0.75+ self.tube(c + f * 0.005, tip, 0.008, colour, ao=False)+ self.sphere(*tip, 0.028, accent, ao=False)++ def windsock(self, x, y, z=0.0, h=0.9, yaw=30.0, droop=12.0, length=0.55, colour='#f19a8e', stripe='#fbfaf8',+ pole='#fbfaf8'):+ """an airfield windsock: a pole, a ring, and a tapered striped sock streaming downwind (yaw) and drooping"""+ self.cylinder(x, y, z, z + h + 0.06, 0.018, pole)+ top = np.array([x, y, z + h])+ d = np.array([np.cos(np.radians(yaw)) * np.cos(np.radians(droop)),+ np.sin(np.radians(yaw)) * np.cos(np.radians(droop)), -np.sin(np.radians(droop))])+ base = top + d * 0.03+ cs, cc = _c(stripe), _c(colour)++ def paint(P, n, t):+ k = ((P - base) @ d) / length+ return np.where((np.floor(k * 5) % 2 == 1)[:, None], cs, cc)+ self.add(_Frustum(base, d, length, 0.075, 0.035), colour, paint)+ self.tube(top - d * 0.02, top + d * 0.03, 0.08, pole, r1=0.08)++ def solar_panel(self, x, y, z=0.0, w=0.9, d=0.5, tilt=28.0, yaw=0.0, colour='#8fb0e6', frame='#f4f1f8', h=0.18):+ """a tilted solar panel on two legs: glass with a cell grid and a pale frame"""+ R = rot(yaw, -tilt)+ c = np.array([x, y, z + h + np.sin(np.radians(tilt)) * d / 2])+ cp, cf = _c(colour), _c(frame)++ def paint(P, n, t):+ q = (P - c) @ R # local coordinates+ top = (n @ (R @ np.array([0, 0, 1.0]))) > 0.9+ gu = np.mod(q[:, 1] / (w / 6), 1.0); gv = np.mod(q[:, 0] / (d / 3), 1.0)+ grid = (np.minimum(gu, 1 - gu) < 0.05) | (np.minimum(gv, 1 - gv) < 0.06)+ rim = (np.abs(q[:, 1]) > w / 2 - 0.025) | (np.abs(q[:, 0]) > d / 2 - 0.025)+ col = np.where(grid[:, None], cp * 1.14, cp)+ col = np.where(rim[:, None] | ~top[:, None], cf, col)+ return np.minimum(col, 1)+ self.obox(c, (d, w, 0.03), yaw=yaw, pitch=-tilt, colour=colour, paint=paint, mat='glass', bevel=0.008)+ for s in (-1, 1):+ p = np.array([x, y]) + (R @ np.array([0, s * w * 0.36, 0]))[:2]+ self.cylinder(p[0], p[1], z, c[2], 0.018, frame)++ def fence(self, pts, z=0.0, h=0.2, colour='#fbfaf8', spacing=0.2, closed=False):+ """a picket fence along a polyline of (x, y): posts with pointed tops and two rails"""+ P = [np.asarray(p, np.float64) for p in pts] + ([np.asarray(pts[0], np.float64)] if closed else [])+ zz = z if np.isscalar(z) else None+ for a, b in zip(P[:-1], P[1:]):+ L = np.linalg.norm(b - a); n = max(1, int(round(L / spacing)))+ z0 = zz if zz is not None else z(a[0], a[1])+ for k in range(n + 1):+ q = a + (b - a) * k / n+ self.box(q[0] - 0.018, q[1] - 0.018, z0, q[0] + 0.018, q[1] + 0.018, z0 + h, colour, bevel=0.008)+ for rz in (0.35, 0.75):+ self.tube((a[0], a[1], z0 + h * rz), (b[0], b[1], z0 + h * rz), 0.011, colour, ao=False)++ def pier(self, x0, y0, x1, y1, z=0.26, colour='#ecd7c4', post='#d9bca5', plank=0.12, bottom=0.0):+ """a jetty: planks across its length with small gaps, on round posts standing in the water"""+ along_x = abs(x1 - x0) >= abs(y1 - y0)+ L = abs(x1 - x0) if along_x else abs(y1 - y0)+ n = int(L / plank)+ rng = np.random.default_rng(self._seed())+ for k in range(n):+ s0 = k * L / n + 0.008; s1 = (k + 1) * L / n - 0.008+ col = _c(colour) * rng.uniform(0.97, 1.02)+ if along_x: self.box(min(x0, x1) + s0, y0, z - 0.04, min(x0, x1) + s1, y1, z, col, bevel=0.008)+ else: self.box(x0, min(y0, y1) + s0, z - 0.04, x1, min(y0, y1) + s1, z, col, bevel=0.008)+ m = max(2, int(L / 0.7) + 1)+ for k in range(m):+ s = 0.08 + k * (L - 0.16) / (m - 1)+ for side in (0, 1):+ if along_x: px, py = min(x0, x1) + s, (y0 + 0.06 if side == 0 else y1 - 0.06)+ else: px, py = (x0 + 0.06 if side == 0 else x1 - 0.06), min(y0, y1) + s+ self.cylinder(px, py, bottom, z - 0.04 + 0.05, 0.035, post)++ def boat(self, x, y, z=0.14, length=0.9, width=0.36, yaw=0.0, hull='#fbfaf8', stripe='#f19a8e', deck='#ecd7c4',+ cabin='#fbfaf8'):+ """a small boat afloat at water level z: a convex hull with a pointed bow and raked keel, a coloured band,+ a wooden deck and a little cabin with a coloured roof. The bow points along `yaw` (degrees from +x)"""+ R = rot(yaw); c = np.array([x, y, z], np.float64)+ l, w, hd, hb, bl = length / 2, width / 2, 0.11, 0.08, length * 0.32+ loc = [((0, 0, 1), hd), ((0, 0, -1), hb), ((0, 1, 0), w), ((0, -1, 0), w), ((-1, 0, 0), l),+ ((w, bl, 0), w * l), ((w, -bl, 0), w * l), ((0.9, 0, -1), 0.9 * l * 0.25 + hb), ((-0.7, 0, -1), 0.7 * l * 0.7 + hb)]+ N, d = [], []+ for n, dd in loc:+ n = np.asarray(n, np.float64); nn = np.linalg.norm(n)+ nw = R @ (n / nn); N.append(nw); d.append(dd / nn + nw @ c)+ cs, ch, cd = _c(stripe), _c(hull), _c(deck)++ def paint(P, n, t):+ zz = P[:, 2:3] - z+ top = n[:, 2:3] > 0.9+ band = (zz > hd * 0.35) & (zz < hd * 0.72)+ return np.where(top, cd, np.where(band, cs, ch))+ self.convex(list(zip(N, d)), c - l - 0.05, c + l + 0.05, hull, paint=paint)+ self.obox(c + R @ np.array([-l * 0.28, 0, hd + 0.08]), (length * 0.32, width * 0.6, 0.16), yaw=yaw,+ colour=cabin, bevel=0.02)+ self.obox(c + R @ np.array([-l * 0.28, 0, hd + 0.175]), (length * 0.38, width * 0.7, 0.03), yaw=yaw,+ colour=stripe, bevel=0.01)++ def balloon(self, x, y, z, r=0.42, colour='#fbe4ea', string=0.9, payload='#fbfaf8'):+ """a weather balloon: a glossy sphere with a neck, a string and a small instrument box hanging below"""+ self.sphere(x, y, z, r, colour, mat='gloss', ao=False)+ self.cylinder(x, y, z - r - 0.05, z - r * 0.8, 0.03, colour, r1=0.07, ao=False)+ self.tube((x, y, z - r - 0.05), (x, y, z - r - string), 0.006, '#9f98c0', ao=False)+ bz = z - r - string+ self.box(x - 0.06, y - 0.05, bz - 0.12, x + 0.06, y + 0.05, bz, payload, bevel=0.012, ao=False)++ # ------------------------------------------------------------ infographics+ def card(self, x, y, z, w=2.4, h=1.5, facing='+x', title='', tag='', value='', unit='', note='', series=None,+ accent='#9d86e8', icon=None, anchor=None, paper='#fdfcff', ink=INK, thick=0.05, stamp=''):+ """a floating data card: a thin panel standing upright (its face towards `facing`), printed with a label,+ a big value, a unit, a note and a small trend line; a slim leader drops from it to `anchor`.+ (x, y) is the centre of the card's bottom edge, z its bottom."""+ ax = 0 if facing[1] == 'x' else 1+ tex = self._card_texture(w, h, title, tag, value, unit, note, series, accent, icon, paper, ink, stamp)+ if ax == 0:+ lo, hi = (x - thick, y - w / 2, z), (x, y + w / 2, z + h)+ ev = np.array([0, 1.0, 0]); org = np.array([x, y - w / 2, z + h])+ else:+ lo, hi = (x - w / 2, y - thick, z), (x + w / 2, y, z + h)+ ev = np.array([-1.0, 0, 0]); org = np.array([x + w / 2, y, z + h])+ cp = _c(paper); cedge = _c(accent) * 0.35 + cp * 0.65++ def paint(P, n, t):+ front = n[:, ax] > 0.9+ u = ((P - org) @ ev) / w; v = (org[2] - P[:, 2]) / h+ rgba = _tex(tex, u, v)+ col = rgba[:, :3] * rgba[:, 3:4] + cp * (1 - rgba[:, 3:4])+ return np.where(front[:, None], col, cedge)+ self.box(*lo, *hi, paper, bevel=0.02, paint=paint, mat='card', ao=False, cast=True)+ if anchor is not None:+ a = np.asarray(anchor, np.float64)+ s = np.array([x - (thick / 2 if ax == 0 else 0), y - (thick / 2 if ax == 1 else 0), z])+ self.tube(s, a, 0.009, '#a49bd0', ao=False, cast=False)+ self.sphere(*a, 0.035, accent, ao=False, cast=False)+ self.sphere(*s, 0.02, '#a49bd0', ao=False, cast=False)++ def sign(self, x, y, z, w, h, text, facing='+x', colour='#fbfaf8', ink=INK, font='cjk_sans', thick=0.025):+ """a small plate on a wall or post with centred lettering; (x, y) = wall point under its centre, z = bottom"""+ ax = 0 if facing[1] == 'x' else 1; sg = 1 if facing[0] == '+' else -1+ ppu = 260; TW, TH = max(8, int(w * ppu)), max(8, int(h * ppu))+ im = Image.new('RGBA', (TW, TH), (0, 0, 0, 0)); d = ImageDraw.Draw(im)+ f = load_font(font, int(TH * 0.62))+ d.text((TW / 2, TH / 2), text, font=f, fill=tuple(int(c * 255) for c in _c(ink)) + (255,), anchor='mm')+ tex = np.asarray(im, np.float32) / 255+ cp = _c(colour)+ if ax == 0:+ lo, hi = (x, y - w / 2, z), (x + sg * thick, y + w / 2, z + h)+ org = np.array([x, y - w / 2 if sg > 0 else y + w / 2, z + h]); ev = np.array([0, float(sg), 0])+ else:+ lo, hi = (x - w / 2, y, z), (x + w / 2, y + sg * thick, z + h)+ org = np.array([x + w / 2 if sg > 0 else x - w / 2, y, z + h]); ev = np.array([-float(sg), 0, 0])++ def paint(P, n, t):+ front = n[:, ax] * sg > 0.9+ rgba = _tex(tex, ((P - org) @ ev) / w, (org[2] - P[:, 2]) / h)+ col = rgba[:, :3] * rgba[:, 3:4] + cp * (1 - rgba[:, 3:4])+ return np.where(front[:, None], col, cp)+ self.box(*lo, *hi, colour, bevel=0.006, paint=paint, ao=False)++ def _card_texture(self, w, h, title, tag, value, unit, note, series, accent, icon, paper, ink, stamp):+ ppu = 220+ TW, TH = int(w * ppu), int(h * ppu)+ im = Image.new('RGBA', (TW, TH), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ A = tuple(int(c * 255) for c in _c(accent)); K = tuple(int(c * 255) for c in _c(ink))+ soft = tuple(int(c * 255) for c in (_c(ink) * 0.5 + _c(paper) * 0.5))+ U = lambda v: int(v * ppu)+ m = U(0.16)+ d.rectangle([0, 0, U(0.06), TH], fill=A + (255,)) # accent spine+ x0 = m + U(0.04)+ f_cn = load_font('cjk_sans', U(0.25)); f_tag = load_font('sans_bold', U(0.12))+ f_val = load_font('geometric', U(0.7)); f_unit = load_font('sans', U(0.22))+ f_note = load_font('cjk_sans', U(0.17))+ cy = m + U(0.15)+ ix = x0+ if icon:+ self._icon(d, icon, x0 + U(0.12), cy, U(0.12), A)+ ix = x0 + U(0.33)+ d.text((ix, cy), title, font=f_cn, fill=K + (255,), anchor='lm')+ xx = ix + d.textlength(title, font=f_cn) + U(0.1)+ for ch in tag:+ d.text((xx, cy + U(0.01)), ch, font=f_tag, fill=soft + (255,), anchor='lm')+ xx += d.textlength(ch, font=f_tag) + U(0.025)+ if stamp:+ d.text((TW - m, cy + U(0.01)), stamp, font=f_tag, fill=soft + (255,), anchor='rm')+ by = m + U(1.0)+ d.text((x0 - U(0.02), by), value, font=f_val, fill=K + (255,), anchor='ls')+ vw = d.textlength(value, font=f_val)+ d.text((x0 + vw + U(0.05), by), unit, font=f_unit, fill=soft + (255,), anchor='ls')+ vend = x0 + vw + U(0.05) + d.textlength(unit, font=f_unit)+ if note:+ d.text((x0, TH - m + U(0.02)), note, font=f_note, fill=soft + (255,), anchor='ls')+ if series is not None and len(series) > 1:+ s = np.asarray(series, np.float64)+ cx0, cx1 = max(int(TW * 0.58), int(vend + U(0.2))), TW - m+ cy0, cy1 = m + U(0.5), by - U(0.02)+ lo_, hi_ = s.min(), s.max(); rng_ = max(hi_ - lo_, 1e-6)+ pts = [(cx0 + (cx1 - cx0) * k / (len(s) - 1), cy1 - (cy1 - cy0) * (v - lo_) / rng_) for k, v in enumerate(s)]+ A2 = tuple(int(c * 255) for c in (_c(accent) * 0.22 + _c(paper) * 0.78))+ d.polygon(pts + [(cx1, cy1), (cx0, cy1)], fill=A2 + (255,))+ d.line([(cx0, cy1), (cx1, cy1)], fill=soft + (255,), width=max(1, U(0.01)))+ d.line(pts, fill=A + (255,), width=U(0.03), joint='curve')+ px, py = pts[-1]; rr = U(0.05)+ d.ellipse([px - rr, py - rr, px + rr, py + rr], fill=A + (255,), outline=(255, 255, 255, 255), width=U(0.018))+ return np.asarray(im, np.float32) / 255++ @staticmethod+ def _icon(d, kind, cx, cy, r, col):+ c = col + (255,); lw = max(2, r // 5)+ if kind == 'wind':+ for dy, x0, x1 in ((-0.62, -1.0, 0.7), (0.0, -0.6, 1.1), (0.62, -1.0, 0.4)):+ y = cy + dy * r+ d.line([(cx + x0 * r, y), (cx + x1 * r, y)], fill=c, width=lw)+ for xe in (x0, x1):+ d.ellipse([cx + xe * r - lw / 2, y - lw / 2, cx + xe * r + lw / 2, y + lw / 2], fill=c)+ elif kind == 'temp':+ d.rounded_rectangle([cx - 0.28 * r, cy - 1.1 * r, cx + 0.28 * r, cy + 0.4 * r], radius=int(0.28 * r), outline=c, width=lw)+ d.ellipse([cx - 0.55 * r, cy + 0.1 * r, cx + 0.55 * r, cy + 1.2 * r], fill=c)+ elif kind == 'rain':+ d.polygon([(cx, cy - 1.15 * r), (cx - 0.72 * r, cy + 0.15 * r), (cx + 0.72 * r, cy + 0.15 * r)], fill=c)+ d.ellipse([cx - 0.75 * r, cy - 0.45 * r, cx + 0.75 * r, cy + 1.05 * r], fill=c)+ elif kind == 'balloon':+ d.ellipse([cx - 0.7 * r, cy - 1.15 * r, cx + 0.7 * r, cy + 0.35 * r], fill=c)+ d.line([(cx, cy + 0.35 * r), (cx, cy + 1.05 * r)], fill=c, width=max(1, lw // 2))+ d.rectangle([cx - 0.22 * r, cy + 0.95 * r, cx + 0.22 * r, cy + 1.25 * r], fill=c)+ elif kind == 'sun':+ d.ellipse([cx - 0.5 * r, cy - 0.5 * r, cx + 0.5 * r, cy + 0.5 * r], fill=c)+ for k in range(8):+ a = k * np.pi / 4+ d.line([(cx + np.cos(a) * 0.72 * r, cy + np.sin(a) * 0.72 * r), (cx + np.cos(a) * 1.05 * r, cy + np.sin(a) * 1.05 * r)], fill=c, width=lw)++ # ------------------------------------------------------------ 2D type on top+ def text(self, s, x, y, size, colour=INK, font='cjk_sans', anchor='ls', spacing=0.0, alpha=1.0):+ """type set flat on the finished image (titles, captions); x, y in output pixels"""+ self.overlays.append(('text', s, x, y, size, colour, font, anchor, spacing, alpha))++ def rule(self, x0, y0, x1, y1, colour=INK, width=2, alpha=1.0):+ self.overlays.append(('rule', x0, y0, x1, y1, colour, width, alpha))++ def dot(self, x, y, r, colour=INK, alpha=1.0):+ self.overlays.append(('dot', x, y, r, colour, alpha))++ def compass(self, x, y, z=0.0, r=0.6, north=(0.0, 1.0), colour='#8a80b8', label='N', size=20):+ """a map compass lying flat in the iso ground plane at (x, y, z): a ring with four ticks, a two-tone north+ needle and its letter (drawn on top, like the titles)"""+ nx, ny = _unit([north[0], north[1], 0])[:2]; ex, ey = ny, -nx+ P = lambda a, b: self.iso(x + a, y + b, z)+ self.overlays.append(('poly', [P(r * np.cos(t), r * np.sin(t)) for t in np.linspace(0, 2 * np.pi, 97)], colour, 2, 0.75, False))+ for k in range(4):+ c, s_ = np.cos(k * np.pi / 2), np.sin(k * np.pi / 2)+ dx, dy = nx * c - ex * s_, ny * c - ey * s_+ self.overlays.append(('poly', [P(dx * r * 0.84, dy * r * 0.84), P(dx * r, dy * r)], colour, 2, 0.75, False))+ tip, tail = P(nx * r * 0.78, ny * r * 0.78), P(-nx * r * 0.78, -ny * r * 0.78)+ left, right, mid = P(ex * r * 0.15, ey * r * 0.15), P(-ex * r * 0.15, -ey * r * 0.15), P(0, 0)+ self.overlays.append(('poly', [tip, left, mid, right], colour, 0, 0.95, True))+ self.overlays.append(('poly', [tail, left, mid, right], colour, 0, 0.3, True))+ lx, ly = P(nx * r * 1.3, ny * r * 1.3)+ self.text(label, lx, ly, size, colour, font='sans_bold', anchor='mm')++ def _draw_overlays(self, img):+ if not self.overlays: return img+ lay = Image.new('RGBA', img.size, (0, 0, 0, 0)); d = ImageDraw.Draw(lay)+ for o in self.overlays:+ if o[0] == 'text':+ _, s, x, y, size, colour, font, anchor, spacing, alpha = o+ f = load_font(font, size); c = tuple(int(v * 255) for v in _c(colour)) + (int(alpha * 255),)+ if not spacing:+ d.text((x, y), s, font=f, fill=c, anchor=anchor)+ else:+ adv = [f.getlength(ch) + spacing for ch in s]; tot = sum(adv) - spacing+ xx = x - tot * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ for ch, a in zip(s, adv):+ d.text((xx, y), ch, font=f, fill=c, anchor='l' + anchor[1]); xx += a+ elif o[0] == 'rule':+ _, x0, y0, x1, y1, colour, width, alpha = o+ d.line([(x0, y0), (x1, y1)], fill=tuple(int(v * 255) for v in _c(colour)) + (int(alpha * 255),), width=width)+ elif o[0] == 'poly':+ _, pts, colour, width, alpha, fill = o+ c = tuple(int(v * 255) for v in _c(colour)) + (int(alpha * 255),)+ if fill: d.polygon([tuple(p) for p in pts], fill=c)+ else: d.line([tuple(p) for p in pts], fill=c, width=width, joint='curve')+ elif o[0] == 'dot':+ _, x, y, r, colour, alpha = o+ d.ellipse([x - r, y - r, x + r, y + r], fill=tuple(int(v * 255) for v in _c(colour)) + (int(alpha * 255),))+ return Image.alpha_composite(img.convert('RGBA'), lay).convert('RGB')++ # ------------------------------------------------------------ lighting+ def _maps(self):+ tc = self.tcam+ Hm = np.where(np.isfinite(self.tdep), (tc.C[2] - self.tdep), self.floor).astype(np.float32)+ ao = []+ for r, k, w in ((0.05, 0.07, 0.40), (0.16, 0.22, 0.35), (0.5, 0.6, 0.25)):+ ao.append((blur(Hm, r * tc.S), r, k, w))+ occ_top = blur((Hm > self.floor + 0.3).astype(np.float32), 0.7 * tc.S)+ h0 = Hm+ hb = np.minimum(np.where(np.isfinite(self.tbot), (tc.C[2] - self.tbot), self.floor).astype(np.float32), h0)+ k = 4+ lo = np.isfinite(self.ldep).astype(np.float32)+ Hl, Wl = lo.shape+ small = np.asarray(Image.fromarray(lo, 'F').resize((max(2, Wl // k), max(2, Hl // k)), Image.BOX), np.float32)+ occ_l = blur(small, 0.55 * self.lcam.S / k)+ return {'ao': ao, 'occ_top': occ_top, 'occ_l': occ_l, 'occ_k': k, 'h0': h0, 'hb': hb}++ def _pcss(self, P, n, ndl, jit):+ lc = self.lcam; D = self.ldep; Hh, Ww = D.shape+ j, i, d = lc.project(P + n * 0.02)+ j = j.astype(np.float32); i = i.astype(np.float32); d = d.astype(np.float32)+ inv = 1.0 / np.maximum(ndl, 0.25)+ gx = ((n @ lc.r) * inv).astype(np.float32); gy = ((n @ lc.u) * inv).astype(np.float32)+ S = np.float32(lc.S); bias = np.float32(0.012)+ c, s = np.cos(jit).astype(np.float32), np.sin(jit).astype(np.float32)+ Rb = np.float32(self.pen[1])++ def taps(K, R):+ k = np.arange(K) + 0.5+ rr = np.sqrt(k / K); th = k * 2.39996323+ for px, py in zip(rr * np.cos(th), rr * np.sin(th)):+ ox = (px * c - py * s) * R; oy = (px * s + py * c) * R+ jj = np.clip(np.rint(j + ox * S), 0, Ww - 1).astype(np.int32)+ ii = np.clip(np.rint(i - oy * S), 0, Hh - 1).astype(np.int32)+ yield D[ii, jj], d + ox * gx + oy * gy+ sd = np.zeros_like(d); cnt = np.zeros_like(d)+ for z, ref in taps(14, Rb):+ blk = z < ref - bias+ sd += np.where(blk, ref - z, 0); cnt += blk+ has = cnt > 0+ dist = sd / np.maximum(cnt, 1)+ w = np.clip(dist * np.float32(self.soft) + np.float32(self.pen[0]), self.pen[0], self.pen[1]).astype(np.float32)+ vis = np.zeros_like(d)+ K = 28+ for z, ref in taps(K, w):+ vis += z >= ref - bias+ vis /= K+ return np.where(has, vis, 1.0).astype(np.float32)++ def _ao(self, P, n, maps):+ """ambient occlusion. Upward faces: how far the blurred surroundings rise above the point (three radii).+ Side and downward faces: the horizon seen along the normal (and 40 deg either side) on the raw height+ map -- a wall is not darkened by its own building, only by what stands in front of it -- plus a+ small crease where it meets the ground."""+ tc = self.tcam+ z = P[:, 2]++ def hmap(M, x, y):+ return _bilerp(M, (y - tc.C[1]) * tc.S + tc.H / 2 - 0.5, (x - tc.C[0]) * tc.S + tc.W / 2 - 0.5)++ def hnear(M, x, y): # column extents must not be interpolated across an edge+ i = np.clip(np.rint((y - tc.C[1]) * tc.S + tc.H / 2 - 0.5), 0, tc.H - 1).astype(np.int32)+ j = np.clip(np.rint((x - tc.C[0]) * tc.S + tc.W / 2 - 0.5), 0, tc.W - 1).astype(np.int32)+ return M[i, j]+ top = np.zeros(len(P), np.float32)+ for Hr, r, k, w in maps['ao']:+ top += w * np.clip((hmap(Hr, P[:, 0] + n[:, 0] * r * 0.5, P[:, 1] + n[:, 1] * r * 0.5) - z) / k, 0, 1)+ wt = smoothstep(0.35, 0.75, n[:, 2]).astype(np.float32)+ side = np.zeros(len(P), np.float32)+ need = wt < 0.999+ if need.any():+ Ps, ns = P[need], n[need]; zs = z[need]+ h = np.hypot(ns[:, 0], ns[:, 1]) + 1e-6+ dx, dy = ns[:, 0] / h, ns[:, 1] / h+ H0, HB = maps['h0'], maps['hb']+ occ = np.zeros(len(Ps), np.float32)+ for ang in (-0.7, 0.0, 0.7):+ ca, sa = np.cos(ang), np.sin(ang)+ ux, uy = dx * ca - dy * sa, dx * sa + dy * ca+ best = np.zeros(len(Ps), np.float32)+ for dd in (0.04, 0.09, 0.18, 0.35, 0.7):+ x, y = Ps[:, 0] + ux * dd, Ps[:, 1] + uy * dd+ t1 = np.maximum(hnear(H0, x, y) - zs, 0) / dd; t0 = np.maximum(hnear(HB, x, y) - zs, 0) / dd+ band = t1 / np.sqrt(1 + t1 * t1) - t0 / np.sqrt(1 + t0 * t0) # sky band this column hides+ np.maximum(best, band, out=best)+ occ += best * (0.4 if ang == 0.0 else 0.3)+ gx, gy = Ps[:, 0] + dx * 0.05, Ps[:, 1] + dy * 0.05+ g = hnear(H0, gx, gy)+ under = hnear(HB, gx, gy) > zs - 0.02 # a floating slab (eave) there: no crease+ crease = np.where(under, 0, np.clip(1 - np.abs(zs - g) / 0.14, 0, 1) ** 2 * 0.35)+ side[need] = np.clip(occ * 0.95 + crease, 0, 1)+ return np.clip(wt * top + (1 - wt) * side, 0, 1)++ def _colour(self, P, n, alb, mat, vis, ao):+ L = self.L.astype(np.float32)+ ndl = n @ L+ nz = n[:, 2:3]+ amb = np.where(nz >= 0, self.hor_c + (self.sky_c - self.hor_c) * nz, self.hor_c + (self.gnd_c - self.hor_c) * (-nz))+ soft = mat == SOFT+ nd = np.where(soft, (ndl + 0.35) / 1.35, ndl)+ direct = np.clip(nd, 0, 1) * vis+ aok = np.where(mat == WATER, 0.5, 1.0)[:, None] * ao[:, None]+ light = amb * (1 - 0.55 * aok) + self.sun_c * direct[:, None]+ light = light * (1 - 0.14 * aok)+ col = alb * light+ g = mat == GLASS+ if g.any():+ vdir = -self.cam.v.astype(np.float32)+ fr = 0.06 + 0.2 * (1 - np.clip(n[g] @ vdir, 0, 1)) ** 3+ col[g] = col[g] * (1 - fr[:, None]) + self.sky_c * 1.12 * fr[:, None]+ w = mat == WATER+ if w.any(): # water lets light through: its walls glow a little+ wall = (np.abs(n[w, 2]) < 0.5)[:, None]+ col[w] = np.where(wall, col[w] * 0.7 + alb[w] * 0.34, col[w])+ gl = (mat == GLOSS)+ if gl.any():+ Hv = _unit(self.L - self.cam.v).astype(np.float32)+ sp = np.clip(n[gl] @ Hv, 0, 1) ** 40 * vis[gl]+ col[gl] = col[gl] + (0.5 * sp)[:, None]+ c = mat == CARD+ if c.any():+ col[c] = alb[c] * (0.8 + 0.2 * light[c])+ return col++ def _vis_blur(self, V, D, radius):+ """depth-aware separable blur of the shadow term: removes the grain of wide penumbras, keeps edges"""+ fin = np.isfinite(D)+ Dz = np.where(fin, D, 1e6).astype(np.float32)+ for ax in (0, 1):+ num = np.zeros_like(V); den = np.zeros_like(V)+ for o in range(-radius, radius + 1):+ Vs = np.roll(V, o, axis=ax); Ds = np.roll(Dz, o, axis=ax)+ wgt = np.exp(-((Ds - Dz) / 0.04) ** 2) * np.float32(np.exp(-(o / (0.6 * radius + 0.5)) ** 2))+ num += wgt * Vs; den += wgt+ V = num / np.maximum(den, 1e-6)+ return V++ def shade(self, k=1):+ """light the current G-buffer; k = stride in supersampled pixels (1 = final quality)"""+ maps = self._maps()+ cam, lc, tc = self.cam, self.lcam, self.tcam+ rows = np.arange(k // 2, self.Hs, k); cols = np.arange(k // 2, self.Ws, k)+ if k == 1:+ DEP, NRM, ALB, MAT = self.dep, self.nrm, self.alb, self.mat+ else:+ ix = np.ix_(rows, cols)+ DEP, NRM, ALB, MAT = self.dep[ix], self.nrm[ix], self.alb[ix], self.mat[ix]+ Hk, Wk = DEP.shape+ acols = cam.cols(cols)+ VIS = np.ones((Hk, Wk), np.float32); AO = np.zeros((Hk, Wk), np.float32)+ step = max(1, 500000 // Wk)+ L = self.L.astype(np.float32)+ # ---- pass 1: sun visibility (soft shadows) and occlusion+ for s0 in range(0, Hk, step):+ sl = slice(s0, min(Hk, s0 + step))+ dep = DEP[sl]+ ii, jj = np.nonzero(np.isfinite(dep))+ if not len(ii): continue+ b = cam.rows(rows[sl])+ P = cam.points(acols[0, jj].astype(np.float64), b[ii, 0].astype(np.float64), dep[ii, jj]).astype(np.float32)+ n = NRM[sl][ii, jj].astype(np.float32); n /= np.linalg.norm(n, axis=1, keepdims=True) + 1e-6+ ndl = n @ L+ vis = np.zeros(len(P), np.float32)+ lit = ndl > -0.3+ if lit.any():+ gi = rows[sl][ii][lit].astype(np.float32); gj = cols[jj][lit].astype(np.float32)+ jit = (2 * np.pi * np.mod(52.9829189 * np.mod(0.06711056 * gj + 0.00583715 * gi, 1.0), 1.0)).astype(np.float32)+ vis[lit] = self._pcss(P[lit], n[lit], np.maximum(ndl[lit], 0.05), jit)+ VIS[sl][ii, jj] = vis+ AO[sl][ii, jj] = self._ao(P, n, maps)+ VIS = self._vis_blur(VIS, DEP, 3 if k == 1 else 1)+ # ---- pass 2: colour+ out = np.empty((Hk, Wk, 3), np.float32)+ top, bottom, glow = (_c(c) for c in self.bg)+ gx, gy = self.iso(*self.glow_centre)+ gx *= self.ss; gy *= self.ss+ for s0 in range(0, Hk, step):+ sl = slice(s0, min(Hk, s0 + step))+ rr = rows[sl]; dep = DEP[sl]; b = cam.rows(rr)+ blk = np.empty((len(rr), Wk, 3), np.float32)+ ty = (rr.astype(np.float32) / self.Hs)[:, None, None]+ bgc = top * (1 - ty) + bottom * ty+ X, Y = np.meshgrid(cols.astype(np.float32), rr.astype(np.float32))+ gd = ((X - gx) / (0.55 * self.Ws)) ** 2 + ((Y - gy) / (0.45 * self.Hs)) ** 2+ bgc = bgc + (glow - bgc) * (np.exp(-gd * 2.2) * 0.8)[..., None]+ miss = ~np.isfinite(dep)+ if miss.any():+ ii, jj = np.nonzero(miss)+ Q = cam.points(acols[0, jj].astype(np.float64), b[ii, 0].astype(np.float64), np.zeros(len(ii)))+ t = (self.floor - Q[:, 2]) / cam.v[2]+ Pf = Q + t[:, None] * cam.v[None]+ lj, li, _ = lc.project(Pf)+ kk = maps['occ_k']+ shl = _bilerp(maps['occ_l'], (li + 0.5) / kk - 0.5, (lj + 0.5) / kk - 0.5)+ tj = (Pf[:, 0] - tc.C[0]) * tc.S + tc.W / 2 - 0.5; ti = (Pf[:, 1] - tc.C[1]) * tc.S + tc.H / 2 - 0.5+ inside = (tj > 0) & (tj < tc.W - 1) & (ti > 0) & (ti < tc.H - 1)+ aof = np.where(inside, _bilerp(maps['occ_top'], ti, tj), 0)+ tint = np.array([0.78, 0.76, 0.93], np.float32)+ amt = np.clip(0.55 * shl + 0.45 * aof, 0, 1)[:, None] * 0.55+ blk[ii, jj] = bgc[ii, jj] * (1 - amt * (1 - tint))+ ii, jj = np.nonzero(~miss)+ if len(ii):+ P = cam.points(acols[0, jj].astype(np.float64), b[ii, 0].astype(np.float64), dep[ii, jj]).astype(np.float32)+ n = NRM[sl][ii, jj].astype(np.float32); n /= np.linalg.norm(n, axis=1, keepdims=True) + 1e-6+ blk[ii, jj] = self._colour(P, n, ALB[sl][ii, jj].astype(np.float32), MAT[sl][ii, jj],+ VIS[sl][ii, jj], AO[sl][ii, jj])+ out[sl] = blk+ out = np.where(out > 0.9, 0.9 + 0.1 * np.tanh((out - 0.9) / 0.1), out)+ return np.clip(out, 0, 1)++ # ------------------------------------------------------------ output+ def composite(self, preview=False):+ if preview:+ img = self.shade(k=2 * self.ss)+ im = Image.fromarray((img * 255 + 0.5).astype(np.uint8)).resize((self.W, self.H), Image.BILINEAR)+ else:+ img = self.shade(k=1)+ s = self.ss+ img = img[:self.H * s, :self.W * s].reshape(self.H, s, self.W, s, 3).mean((1, 3))+ im = Image.fromarray((img * 255 + 0.5).astype(np.uint8))+ return self._draw_overlays(im)++ def stage(self, name):+ if self.record: self.stages.append((name, self.composite(preview=True)))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/lineart.py b/lib/lineart.pynew file mode 100644index 0000000..68f7d16--- /dev/null+++ b/lib/lineart.py@@ -0,0 +1,511 @@+"""lineart — continuous single-line drawing (one-line art): one unbroken line draws the whole picture, with a+single accent colour and a lot of empty space (numpy + Pillow only).++Model: one pen that never leaves the paper.+ path the drawing is ONE path. Shapes are built as polylines (ruled corners get a small fillet: a hand+ moving at speed rounds every corner a little), Catmull-Rom splines (organic parts), scalloped+ outlines (canopies, bushes) and loop-the-loops laid along the path (`curl`), then+ `chain()` strings them together in drawing order. Where one shape ends away from where the next+ begins, the pen does not lift: a cubic bridge leaves along the old tangent and arrives along the new+ one. Where a shape has to be reached "from inside" (a window hung off a wall), the pen goes in and+ comes back over the same stretch -- a retrace is invisible in the final picture. The whole path is+ resampled to 1 px steps, so everything downstream works in arc length s (px).+ pressure width follows the hand, not a ruler: a light touch-down taper at the start and a longer lift-off at+ the end, a slow drift of pressure along the line (+-9 %), the pen slowing down -- and so laying+ more ink -- where the path turns sharply (corners and tight loops get up to ~25 % heavier), and a+ light flick wherever it doubles straight back (a retraced stub ends in a point, not a blunt cap).+ Whole stretches can be drawn with a lighter or heavier hand (`pressure=[(s0, s1, factor)]`): a+ motion path at ~0.6 reads as a trajectory, not as one more object.+ ink the line is rasterised once into a time map: every sub-pixel stores the arc length at which the pen+ first covered it (dabs stamped from the end backwards, so the earliest pass wins at crossings). Any+ prefix of the drawing -- "the pen has travelled s px" -- is then just `time <= s`, which is what+ makes draw-on stages cheap and exact. Supersampled 4x for clean anti-aliased edges.+ metal on a dark ground the line is a thin gilded wire: its colour runs from old gold to pale champagne with+ the angle between the line and a light from the upper left (anisotropic sheen) plus a slow drift along+ its length, and it gives off a faint, tight glow (three small blurs, never a neon bloom). On cream+ paper it is a dark ink line with no glow.+ pen tip while the drawing is unfinished, the last ~120 px of line are still "hot" (brighter, a stronger+ glow) and the head carries a small spark -- the tell-tale of a line being drawn.+ accent exactly one filled shape in one accent colour (a lit window, a sun, a seal), revealed at the end; on+ a dark ground it glows softly and warms the nearby line.+ type letter-spaced display serif (Didot / Bodoni / Baskerville, else any serif) and a light Song-style CJK+ face for a quiet caption; centred under the drawing.+Colours: GOLD / GOLD_HI / GOLD_LO for the wire, AMBER (warm light) and VERMILION (seal red) as accents,+NIGHT (deep navy) and CREAM grounds, INK for a dark line on cream. Angles are screen degrees (clockwise, y down).++ from lineart import LineArt, AMBER+ la = LineArt(1920, 1080, seed=1)+ la.backdrop('night')+ P, marks = la.chain([('ground', LineArt.smooth([(200, 700), (600, 705), (900, 700)])),+ ('box', LineArt.poly([(900, 700), (900, 560), (1100, 560), (1100, 700)], r=5)),+ ('tail', LineArt.smooth([(1100, 700), (1400, 706), (1700, 700)]))])+ la.line(P, width=3.2)+ la.draw_to(marks['box']); la.stage('box') # the pen has reached the end of the box+ la.draw_to(None); la.accent(la.rect(960, 600, 1040, 660), AMBER)+ la.text('ONE LINE', 960, 860, 44, font='display', spacing=14)+ la.save('out.jpg')+"""+import glob+import os+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, fbm1d, spline, noise2d, smoothstep, load_font, cjk_font, text_mask++GOLD, GOLD_HI, GOLD_LO = '#dcc28c', '#fbf0d2', '#8f7040'+AMBER, VERMILION = '#ffb257', '#d4553a'+NIGHT, CREAM, INK = '#172540', '#f1e9da', '#2a2b33'+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++def _cumlen(P):+ return np.concatenate([[0.0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))]).astype(np.float64)+++def _is_cjk(s):+ return any(ord(ch) >= 0x2e80 for ch in s)+++_DISPLAY = [('/System/Library/Fonts/Supplemental/Didot.ttc', 0), ('/System/Library/Fonts/Supplemental/Bodoni 72.ttc', 0),+ ('/System/Library/Fonts/Supplemental/Baskerville.ttc', 0), ('/usr/share/fonts/**/*Playfair*Regular*.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSerif.ttf', 0), ('C:/Windows/Fonts/bod_r.ttf', 0), ('C:/Windows/Fonts/georgia.ttf', 0)]+_CJK_SERIF = [('/System/Library/Fonts/Supplemental/Songti.ttc', 3), ('/usr/share/fonts/**/NotoSerifCJK*Light*.tt[cf]', 0),+ ('/usr/share/fonts/**/NotoSerifCJK*.tt[cf]', 0), ('C:/Windows/Fonts/simsun.ttc', 0)]+++def _find_font(cands, size):+ for pat, idx in cands:+ for f in glob.glob(pat, recursive=True):+ try:+ return ImageFont.truetype(f, int(size), index=idx)+ except OSError:+ continue+ return None+++class LineArt:+ def __init__(self, W=1920, H=1080, seed=0, ss=4):+ self.W, self.H, self.ss = W, H, ss+ self.rng = np.random.default_rng(seed)+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)+ self.bg = np.full((H, W, 3), 0.1, np.float32)+ self.dark = True+ self.ink, self.accent_colour = GOLD, AMBER+ self.strokes = [] # rasterised lines (time maps) with their pen heads+ self.acc_a = np.zeros((H, W), np.float32) # accent fill: alpha + colour+ self.acc_c = np.zeros((H, W, 3), np.float32)+ self.acc_glow = np.zeros((H, W, 3), np.float32) # additive light from the accent (dark grounds)+ self.acc_warm = np.zeros((H, W), np.float32) # how much the accent light tints the nearby line+ self.txt_a = np.zeros((H, W), np.float32)+ self.txt_c = np.zeros((H, W, 3), np.float32)+ self.marks = {}+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ ground+ def backdrop(self, kind='night', colour=None, edge=None, grain=None):+ """kind 'night': deep navy, lighter in the middle (like a dark velvet card under one soft light), fine+ grain; 'cream': warm paper with faint fibres and mottling. Sets the default ink / accent / glow."""+ H, W = self.H, self.W+ r = np.hypot((self.XX - W * 0.5) / (W * 0.62), (self.YY - H * 0.44) / (H * 0.72))+ t = smoothstep(0.0, 1.25, r)[..., None]+ mott = noise2d(H, W, 260, 3, self._seed()) - 0.5+ if kind == 'night':+ self.dark = True+ c0, c1 = _c(colour or NIGHT), _c(edge or '#060a13')+ img = c0 * (1 - t) + c1 * t+ img *= (1 + 0.05 * mott)[..., None]+ img += (smoothstep(0.55, 0.0, self.YY / H) * 0.012)[..., None] * _c('#8fa6d8') # faint top light+ g = grain if grain is not None else 0.007+ self.ink, self.accent_colour = GOLD, AMBER+ else:+ self.dark = False+ c0, c1 = _c(colour or CREAM), _c(edge or '#e2d6bf')+ img = c0 * (1 - t * 0.8) + c1 * (t * 0.8)+ img *= (1 + 0.035 * mott)[..., None]+ fib = np.asarray(Image.fromarray(self.rng.random((H // 3, W // 40)).astype(np.float32))+ .resize((W, H), Image.BILINEAR)) - 0.5+ img *= (1 + 0.012 * fib)[..., None]+ g = grain if grain is not None else 0.012+ self.ink, self.accent_colour = INK, VERMILION+ img *= (1 + g * self.rng.normal(0, 1, (H, W)).astype(np.float32))[..., None]+ self.bg = np.clip(img, 0, 1).astype(np.float32)++ # ------------------------------------------------------------ building the one path+ @staticmethod+ def resample(P, step=1.0):+ P = np.asarray(P, np.float64)+ s = _cumlen(P)+ if s[-1] < 1e-6: return P[:1].astype(np.float32)+ n = max(2, int(np.ceil(s[-1] / step)) + 1)+ ss = np.linspace(0, s[-1], n)+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)++ @staticmethod+ def length(P):+ return float(_cumlen(np.asarray(P, np.float64))[-1])++ @staticmethod+ def smooth(pts, per=24):+ """Catmull-Rom spline through control points (organic parts: hills, trails, canopies)"""+ return LineArt.resample(spline(pts, per), 1.0)++ @staticmethod+ def poly(pts, r=5.0, sharp=()):+ """polyline with filleted corners (radius r px, clipped to half of each side). Indices in `sharp` stay+ pointed (paper corners, a nose, a spire)."""+ P = np.asarray(pts, np.float64)+ out = [P[0]]+ for i in range(1, len(P) - 1):+ a, b, c = P[i - 1], P[i], P[i + 1]+ d1, d2 = b - a, c - b+ l1, l2 = np.hypot(*d1), np.hypot(*d2)+ rr = 0.0 if i in sharp else min(r, l1 * 0.5, l2 * 0.5)+ if rr < 0.5 or l1 < 1e-6 or l2 < 1e-6:+ out.append(b); continue+ p1, p2 = b - d1 / l1 * rr, b + d2 / l2 * rr+ t = np.linspace(0, 1, 9)[:, None]+ out.extend(list((1 - t) ** 2 * p1 + 2 * (1 - t) * t * b + t ** 2 * p2))+ out.append(P[-1])+ return LineArt.resample(np.array(out), 1.0)++ @staticmethod+ def arc(cx, cy, rx, ry=None, a0=0.0, a1=360.0, step=1.0):+ """elliptical arc from angle a0 to a1 (screen degrees: 0 = right, 90 = down); a1 < a0 runs anticlockwise"""+ ry = rx if ry is None else ry+ n = max(8, int(abs(np.deg2rad(a1 - a0)) * max(rx, ry) / step) + 1)+ a = np.deg2rad(np.linspace(a0, a1, n))+ return np.stack([cx + rx * np.cos(a), cy + ry * np.sin(a)], 1).astype(np.float32)++ @staticmethod+ def scallop(cx, cy, r, a0, a1, bumps=6, depth=0.12, squash=1.0):+ """a scalloped outline (tree canopy, bush, cloud) from angle a0 to a1: `bumps` round lobes meeting in+ small inward cusps, like a hand drawing a cloud in one go"""+ n = max(60, int(abs(np.deg2rad(a1 - a0)) * r * 1.2))+ u = np.linspace(0, 1, n)+ a = np.deg2rad(a0 + (a1 - a0) * u)+ rr = r * (1 - depth + depth * 1.6 * np.abs(np.sin(np.pi * bumps * u)) ** 0.7)+ return LineArt.resample(np.stack([cx + rr * np.cos(a), cy + rr * np.sin(a) * squash], 1), 1.0)++ @staticmethod+ def place(pts, origin, angle=0.0, scale=1.0):+ """move a shape drawn in local coordinates: rotate by `angle` (screen degrees, clockwise), scale, then+ put its (0, 0) at `origin`"""+ P = np.asarray(pts, np.float64) * scale+ a = np.deg2rad(angle)+ x = P[:, 0] * np.cos(a) - P[:, 1] * np.sin(a)+ y = P[:, 0] * np.sin(a) + P[:, 1] * np.cos(a)+ return np.stack([x + origin[0], y + origin[1]], 1).astype(np.float32)++ @staticmethod+ def curl(P, s, r, span=None, side=1, aspect=1.0):+ """insert a loop-the-loop into path P at arc length s: the pen runs on, swings round a near-circle of+ radius r on `side` (+1 = left of the direction of travel, i.e. 'up' when moving right, -1 = the other+ side) and crosses its own track before carrying on (a prolate cycloid laid along the path).+ aspect > 1 makes the loop rounder along the direction of travel (useful where the path is bending)."""+ P = LineArt.resample(P, 1.0).astype(np.float64)+ sc = _cumlen(P)+ span = 1.1 * r if span is None else span+ n = int(2 * np.pi * r * 1.6) + 8+ u = np.linspace(0, 1, n)+ sb = s + u * span+ bx, by = np.interp(sb, sc, P[:, 0]), np.interp(sb, sc, P[:, 1])+ tx = np.interp(sb + 1.5, sc, P[:, 0]) - np.interp(sb - 1.5, sc, P[:, 0])+ ty = np.interp(sb + 1.5, sc, P[:, 1]) - np.interp(sb - 1.5, sc, P[:, 1])+ tl = np.hypot(tx, ty) + 1e-9; tx, ty = tx / tl, ty / tl+ nx, ny = side * ty, -side * tx+ ph = 2 * np.pi * u+ ox, oy = r * aspect * np.sin(ph), r * (1 - np.cos(ph))+ loop = np.stack([bx + tx * ox + nx * oy, by + ty * ox + ny * oy], 1)+ return LineArt.resample(np.vstack([P[sc < s], loop, P[sc > s + span]]), 1.0)++ @staticmethod+ def retrace(pts):+ """go out along a stretch and come back over it (a hill shoulder, a window sill): the pen never lifts,+ and the doubled stretch is invisible in the finished picture"""+ Q = np.asarray(pts, np.float32)+ return np.vstack([Q, Q[::-1][1:]])++ @staticmethod+ def _bridge(p0, t0, p3, t3, k=0.42):+ d = float(np.hypot(*(p3 - p0)))+ c1, c2 = p0 + t0 * d * k, p3 - t3 * d * k+ t = np.linspace(0, 1, max(4, int(d * 1.5)))[:, None]+ return (1 - t) ** 3 * p0 + 3 * (1 - t) ** 2 * t * c1 + 3 * (1 - t) * t ** 2 * c2 + t ** 3 * p3++ def chain(self, parts, bridge=0.42):+ """string shapes into ONE continuous path, in drawing order. parts: [(name, pts), ...] (or bare pts).+ Gaps are closed with a tangent-continuous cubic bridge (the pen never lifts). Returns (P, marks):+ P resampled at 1 px, marks[name] = arc length (px) at the end of that part (use it for stages)."""+ def tan(A, end):+ B = A[-min(len(A), 6):] if end else A[:min(len(A), 6)]+ d = B[-1] - B[0]+ n = np.hypot(*d)+ return d / n if n > 1e-6 else np.zeros(2)+ out, ends = [], []+ for i, part in enumerate(parts):+ name, pts = part if isinstance(part, tuple) else (f'part{i}', part)+ Q = np.asarray(pts, np.float64)+ if out:+ p0 = out[-1][-1]+ if np.hypot(*(Q[0] - p0)) > 1.0:+ prev = np.vstack(out[-3:])+ out.append(self._bridge(p0, tan(prev, True), Q[0], tan(Q, False), bridge)[1:-1])+ out.append(Q)+ ends.append((name, sum(len(o) for o in out) - 1))+ P = np.vstack(out)+ s = _cumlen(P)+ marks = {name: float(s[idx]) for name, idx in ends}+ self.marks.update(marks)+ return self.resample(P, 1.0), marks++ @staticmethod+ def trim(P, s0=0.0, s1=None):+ """the stretch of path P between arc lengths s0 and s1 (px)"""+ P = np.asarray(P, np.float64)+ s = _cumlen(P)+ s1 = s[-1] if s1 is None else min(s1, s[-1])+ s0 = max(0.0, s0)+ if s1 <= s0: return P[:1].astype(np.float32)+ inner = (s > s0) & (s < s1)+ a = np.array([np.interp(s0, s, P[:, 0]), np.interp(s0, s, P[:, 1])])+ b = np.array([np.interp(s1, s, P[:, 0]), np.interp(s1, s, P[:, 1])])+ return np.vstack([a, P[inner], b]).astype(np.float32)++ @staticmethod+ def locate(P, xy):+ """arc length (px) of the point of P closest to xy -- for placing a curl or a stage by eye"""+ P = np.asarray(P, np.float64)+ i = int(np.argmin(np.hypot(P[:, 0] - xy[0], P[:, 1] - xy[1])))+ return float(_cumlen(P)[i])++ @staticmethod+ def at(P, s):+ """point and heading (screen degrees) at arc length s"""+ P = np.asarray(P, np.float64)+ sc = _cumlen(P)+ x, y = np.interp(s, sc, P[:, 0]), np.interp(s, sc, P[:, 1])+ x2, y2 = np.interp(s + 2, sc, P[:, 0]), np.interp(s + 2, sc, P[:, 1])+ x1, y1 = np.interp(s - 2, sc, P[:, 0]), np.interp(s - 2, sc, P[:, 1])+ return (float(x), float(y)), float(np.degrees(np.arctan2(y2 - y1, x2 - x1)))++ # ------------------------------------------------------------ pressure and ink+ def pressure(self, P, width=3.2, taper=(50, 150), drift=0.09, slow=0.25, flick=36, spans=None, ramp=60):+ """width (px) at every point of P: touch-down / lift-off tapers, slow pressure drift, more ink where the+ pen slows down in sharp turns, and a light flick wherever the pen doubles straight back on itself (the+ tip of a retraced stub comes out tapered, not blunt). spans = [(s0, s1, factor), ...]: the hand eases+ off (factor < 1) or bears down (> 1) between arc lengths s0 and s1, easing in and out over `ramp` px --+ e.g. a lighter line for a motion path than for the objects it connects."""+ P = np.asarray(P, np.float64)+ s = _cumlen(P); L = s[-1]; n = len(P)+ d = np.gradient(P, axis=0)+ th = np.unwrap(np.arctan2(d[:, 1], d[:, 0]))+ k = np.abs(np.gradient(th)) / np.maximum(np.gradient(s), 1e-3)+ win = 9+ k = np.convolve(np.pad(k, win, mode='edge'), np.ones(2 * win + 1) / (2 * win + 1), 'same')[win:-win]+ w = np.full(n, width, np.float64)+ for s0, s1, f in (spans or ()):+ w *= 1 + (f - 1) * smoothstep(s0 - ramp / 2, s0 + ramp / 2, s) * (1 - smoothstep(s1 - ramp / 2, s1 + ramp / 2, s))+ w *= 1 + slow * smoothstep(0.01, 0.16, k)+ w *= 1 + drift * fbm1d(n, 320, 3, self._seed())+ if flick:+ h = 8 # samples (P is resampled at 0.5 px)+ a, b = P[h:-h] - P[:-2 * h], P[2 * h:] - P[h:-h]+ cosang = (a * b).sum(1) / (np.hypot(*a.T) * np.hypot(*b.T) + 1e-9)+ idx = np.nonzero(cosang < -0.985)[0] + h+ if len(idx):+ groups = np.split(idx, np.nonzero(np.diff(idx) > 4)[0] + 1)+ for g in groups:+ sc = s[int(np.round(g.mean()))]+ w *= 0.22 + 0.78 * smoothstep(0, flick, np.abs(s - sc))+ w *= 0.3 + 0.7 * smoothstep(0, taper[0], s)+ w *= 0.1 + 0.9 * smoothstep(0, taper[1], L - s)+ return w.astype(np.float32), th++ def line(self, P, width=3.2, colour=None, taper=(50, 150), sheen=0.32, glow=1.0, light=225.0, hot=120.0,+ pressure=None):+ """ink the path P as one pressure-sensitive line (fully drawn until draw_to() says otherwise).+ colour: base ink (default: gold on night, INK on cream); sheen: strength of the angle-dependent metallic+ highlight (dark grounds); glow: multiplier on the soft light round the line; light: direction the light+ comes from (screen degrees); hot: length (px) of the still-bright fresh stretch behind the pen tip;+ pressure: [(s0, s1, factor), ...] spans where the hand is lighter or heavier (see pressure())."""+ P = self.resample(P, 0.5)+ s = _cumlen(P).astype(np.float32)+ w, th = self.pressure(P, width, taper, spans=pressure)+ ss = self.ss+ pad = float(w.max()) + 3+ x0, y0 = max(0, int(P[:, 0].min() - pad)), max(0, int(P[:, 1].min() - pad))+ x1, y1 = min(self.W, int(P[:, 0].max() + pad) + 1), min(self.H, int(P[:, 1].max() + pad) + 1)+ tm = Image.new('F', ((x1 - x0) * ss, (y1 - y0) * ss), 1e9)+ dr = ImageDraw.Draw(tm)+ X, Y, R = (P[:, 0] - x0) * ss, (P[:, 1] - y0) * ss, np.maximum(w * 0.5 * ss, 0.7)+ for i in range(len(P) - 1, -1, -1): # backwards: the earliest pass wins at crossings+ dr.ellipse((X[i] - R[i], Y[i] - R[i], X[i] + R[i], Y[i] + R[i]), fill=float(s[i]))+ # metallic sheen: a thin wire is brightest where it runs across the light, plus a slow drift+ lt = np.deg2rad(light)+ b = 0.55 + sheen * np.sin(th - lt) ** 2 * 1.4 - sheen * 0.7 + 0.1 * fbm1d(len(P), 900, 3, self._seed())+ self.strokes.append(dict(P=P, s=s, L=float(s[-1]), box=(x0, y0, x1, y1), tmap=np.asarray(tm, np.float32),+ bright=np.clip(b, 0, 1).astype(np.float32), colour=colour, glow=glow, hot=hot,+ head=float(s[-1])))+ return len(self.strokes) - 1++ def draw_to(self, s=None, stroke=-1):+ """move the pen head of a stroke to arc length s (px) or to a mark name; None = finished"""+ st = self.strokes[stroke]+ if isinstance(s, str): s = self.marks[s]+ st['head'] = st['L'] if s is None else float(np.clip(s, 0, st['L']))++ def _stroke_layer(self, st):+ """coverage, colour and glow weight of one stroke up to its pen head (cropped to its box)"""+ ss = self.ss+ x0, y0, x1, y1 = st['box']+ h, w = y1 - y0, x1 - x0+ head = st['head']+ m = st['tmap'] <= head+ cov = m.reshape(h, ss, w, ss).mean((1, 3))+ tsum = np.where(m, st['tmap'], 0).reshape(h, ss, w, ss).sum((1, 3))+ tt = tsum / np.maximum(cov * ss * ss, 1)+ bright = np.interp(tt, st['s'], st['bright']).astype(np.float32)+ live = head < st['L'] - 0.5+ hot = (np.exp(-np.clip(head - tt, 0, None) / st['hot']) * (cov > 0)).astype(np.float32) if live else None+ return (slice(y0, y1), slice(x0, x1)), cov.astype(np.float32), bright, hot++ # ------------------------------------------------------------ accent, marks, type+ def _ss_mask(self, box, draw, ss=4):+ """anti-aliased mask drawn by draw(ImageDraw, to_ss) at 4x inside box = (x0, y0, x1, y1), pasted on canvas"""+ x0, y0 = max(0, int(np.floor(box[0])) - 2), max(0, int(np.floor(box[1])) - 2)+ x1, y1 = min(self.W, int(np.ceil(box[2])) + 3), min(self.H, int(np.ceil(box[3])) + 3)+ out = np.zeros((self.H, self.W), np.float32)+ if x1 <= x0 or y1 <= y0: return out+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ draw(ImageDraw.Draw(im), lambda x, y: ((x - x0) * ss, (y - y0) * ss))+ out[y0:y1, x0:x1] = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ return out++ def rect(self, x0, y0, x1, y1, r=0.0):+ """anti-aliased (rounded) rectangle mask"""+ return self._ss_mask((x0, y0, x1, y1), lambda d, T: d.rounded_rectangle([*T(x0, y0), *T(x1, y1)],+ radius=r * 4, fill=255))++ def disc(self, cx, cy, r):+ """anti-aliased disc mask (a sun, a moon, a seal)"""+ return np.clip(r + 0.5 - np.hypot(self.XX - cx, self.YY - cy), 0, 1)++ def accent(self, mask, colour=None, glow=1.0, inner=0.25, warm=0.55):+ """the one point of colour: fill `mask` with the accent colour, lighter toward its middle (`inner`);+ on a dark ground it glows (`glow`) and warms the line around it (`warm`)"""+ col = _c(colour or self.accent_colour)+ m = np.clip(mask, 0, 1).astype(np.float32)+ ys, xs = np.nonzero(m > 0.01)+ if len(xs) == 0: return+ cx, cy = xs.mean(), ys.mean()+ rad = max(xs.max() - xs.min(), ys.max() - ys.min()) * 0.6 + 1+ lift = inner * np.exp(-((self.XX - cx) ** 2 + (self.YY - cy) ** 2) / (2 * rad * rad))+ fill = col[None, None, :] * (1 - inner * 0.6) + (1 - col[None, None, :]) * lift[..., None] * 0.5 + col * lift[..., None] * 0.6+ self.acc_c = self.acc_c * (1 - m[..., None]) + np.clip(fill, 0, 1) * m[..., None]+ self.acc_a = np.maximum(self.acc_a, m)+ if self.dark and glow > 0:+ g = blur(m, 6) * 0.45 + blur(m, 22) * 0.3 + blur(m, 70) * 0.16+ self.acc_glow += g[..., None] * col * glow+ self.acc_warm = np.maximum(self.acc_warm, np.clip(blur(m, 26) * 2.2, 0, 1) * warm)++ def _font(self, s, size, font):+ if font == 'display' and not _is_cjk(s):+ f = _find_font(_DISPLAY, size)+ if f: return f+ if _is_cjk(s):+ f = _find_font(_CJK_SERIF, size)+ if f: return f+ p = cjk_font()+ if p: return ImageFont.truetype(p, int(size))+ return load_font('serif' if font in ('display', 'serif') else font, size)++ def text(self, s, x, y, size, colour=None, font='display', anchor='ms', spacing=0.0, alpha=1.0):+ """quiet lettering: font 'display' (Didot-like serif, CJK falls back to a light Song face), 'serif',+ 'sans'; spacing = extra px between letters (letter-spaced caps)"""+ f = self._font(s, size, font)+ m = text_mask(self.H, self.W, s, f, (x, y), anchor, spacing) * alpha+ col = _c(colour or (GOLD if self.dark else INK))+ self.txt_c = self.txt_c * (1 - m[..., None]) + col * m[..., None]+ self.txt_a = np.maximum(self.txt_a, m)++ def text_width(self, s, size, font='display', spacing=0.0):+ f = self._font(s, size, font)+ return sum(f.getlength(ch) + spacing for ch in s) - spacing++ def hairline(self, x0, y0, x1, y1, width=1.2, colour=None, alpha=0.7):+ """a thin typographic rule (beside a caption), not part of the drawing's line"""+ box = (min(x0, x1) - width, min(y0, y1) - width, max(x0, x1) + width, max(y0, y1) + width)+ m = self._ss_mask(box, lambda d, T: d.line([T(x0, y0), T(x1, y1)], fill=255, width=max(1, int(width * 4)))) * alpha+ col = _c(colour or (GOLD if self.dark else INK))+ self.txt_c = self.txt_c * (1 - m[..., None]) + col * m[..., None]+ self.txt_a = np.maximum(self.txt_a, m)++ # ------------------------------------------------------------ output+ def composite(self, tip=True):+ img = self.bg.copy()+ if self.dark:+ img += self.acc_glow * (1 - img) # screen-ish light+ a = self.acc_a[..., None]+ img = img * (1 - a) + self.acc_c * a+ glow = np.zeros((self.H, self.W), np.float32)+ tips = []+ for st in self.strokes:+ if st['head'] <= 0: continue+ sl, cov, bright, hot = self._stroke_layer(st)+ if self.dark:+ lo, mid, hi = _c(GOLD_LO), _c(st['colour'] or self.ink), _c(GOLD_HI)+ b = bright[..., None]+ col = np.where(b < 0.5, lo + (mid - lo) * (b * 2), mid + (hi - mid) * (b * 2 - 1))+ if hot is not None:+ col = col + (_c(GOLD_HI) * 1.05 - col) * (hot[..., None] * 0.85)+ warm = self.acc_warm[sl][..., None]+ col = col * (1 - warm) + (col * 0.35 + _c(self.accent_colour) * 0.75) * warm+ g = cov * (0.55 + 0.45 * bright) * st['glow']+ if hot is not None: g = g * (1 + 2.2 * hot)+ glow[sl] = np.maximum(glow[sl], g)+ else:+ col = np.broadcast_to(_c(st['colour'] or self.ink), cov.shape + (3,))+ c = cov[..., None]+ img[sl] = img[sl] * (1 - c) + np.clip(col, 0, 1.2) * c+ if st['head'] < st['L'] - 0.5:+ tips.append(self.at(st['P'], st['head'])[0])+ if self.dark and glow.any():+ gl = blur(glow, 1.6) * 0.4 + blur(glow, 6) * 0.22 + blur(glow, 20) * 0.09+ img += gl[..., None] * _c(GOLD) * (1 - img)+ if tip and tips:+ for (tx, ty) in tips:+ d2 = (self.XX - tx) ** 2 + (self.YY - ty) ** 2+ if self.dark:+ spark = np.exp(-d2 / (2 * 2.6 ** 2)) * 1.0 + np.exp(-d2 / (2 * 9 ** 2)) * 0.5 + np.exp(-d2 / (2 * 30 ** 2)) * 0.16+ img += spark[..., None] * (_c('#fff6e0') * 1.1 - img).clip(0, None) * 0.95+ else:+ img *= 1 - (np.exp(-d2 / (2 * 2.0 ** 2)) * 0.6)[..., None] * (1 - _c(self.ink))+ t = self.txt_a[..., None]+ img = img * (1 - t) + self.txt_c * t+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None):+ img = self.composite(tip=False)+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=88, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/morph.py b/lib/morph.pynew file mode 100644index 0000000..a3394aa--- /dev/null+++ b/lib/morph.py@@ -0,0 +1,709 @@+"""morph — shape-morph motion graphics: one flat shape turns smoothly into the next while the background colour+switches with it, frozen into a poster (numpy + Pillow only).++Model: a motion designer's shape layer, not a drawing. Every object is ONE closed outline -- no strokes, no+gradients, no texture on the shape itself -- and the whole story is told by that outline changing.+ shapes a library of flat icon silhouettes in a unit box (y down, about -0.5..0.5): drop, cloud, snowflake,+ mountain, river, wave, sun, moon, leaf, heart, star, bird, fish, pin, house, circle, square, triangle.+ Simple ones are written as curves; compound ones (a cloud is a capsule plus three circles, a+ snowflake is six branched arms) are drawn as a union of primitives into a mask and the outer+ contour is traced back out (Moore neighbour tracing, then smoothed), so any union of circles, lines+ and polygons becomes a single morphable outline.+ resample an outline is re-sampled to N points spaced evenly along its arc length. Two shapes can only be+ blended point by point if they have the same number of points, run the same way round (winding),+ and start at corresponding places.+ align same winding first, then the cyclic start offset of the second outline that minimises the summed+ squared distance to the first (both centred and scaled to unit RMS radius), found for all offsets+ at once with an FFT cross-correlation. Without this the in-betweens twist and self-intersect.+ tween the outline relative to its own centroid is interpolated separately from the centroid itself, so+ the shape deforms in place while its centre travels a curved motion path. Time is eased (ease in+ and out: slow off the keyframe, fast in the middle, settling into the next), and a little squash+ and stretch along the direction of travel is added in the fast middle part.+ colour background and shape colours switch with the shape; blends go through OKLab so blue -> yellow+ does not pass through grey.+ poster the frozen animation reads left to right like a film strip: one flat colour panel per keyframe,+ the solid keyframe shape in the middle, onion-skin ghosts (thin outline + faint fill) at evenly+ spaced frame times between keyframes -- bunched up near the keys, spread out in the middle because+ of the easing --, the middle ghost filled more strongly and dotted with its resampled points, a+ dashed motion path through the centroids with chevrons, and an animation timeline under the strip:+ keyframe diamonds and the ease curve of every transition with its frame ticks. (`streaks` speed+ lines and `links` point-pair lines are there too, but read as clutter on a busy strip.)+ paper a very light print grain over everything; bare paper (not panels, not shapes) gets a fine tooth.+Ghost and line colours default to the per-pixel "ink" of the panel underneath, so a ghost that straddles two+panels switches colour at the border, exactly like the background does.+Lettering: geometric sans / mono (Avenir Next, Menlo on macOS) plus a CJK sans; never handwriting fonts.+Angles are degrees counter-clockwise (like PIL); coordinates are pixels, y down.++ import numpy as np+ from morph import Morph+ m = Morph(1920, 1080, seed=1)+ m.paper('#efe9dd')+ A = m.shape('drop', 500, 540, 220)+ B = m.align(A, m.shape('cloud', 1400, 480, 260))+ m.panel(0, 0, 960, 1080, '#f2c13e', ink='#16182b'); m.panel(960, 0, 1920, 1080, '#2437d6', ink='#f4efe4')+ for u in (0.2, 0.4, 0.6, 0.8):+ s = m.ease(u)+ m.ghost(m.tween(A, B, s, stretch=0.16 * np.sin(np.pi * s)), fill=m.mix('#2437d6', '#f4efe4', s))+ m.fill(A, '#2437d6'); m.fill(B, '#f4efe4')+ m.save('out.png')+"""+import glob+import os+from functools import lru_cache+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, noise2d, spline, load_font++PAPER, INK = '#efe9dd', '#16182b'+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++# ------------------------------------------------------------------ OKLab (colour switching without grey mud)+def _lin(c):+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)+++def _srgb(c):+ c = np.clip(c, 0, 1)+ return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055)+++def _oklab(c):+ r, g, b = _lin(np.asarray(c, np.float64))+ l = np.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)+ m = np.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)+ s = np.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)+ return np.array([0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,+ 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s])+++def _from_oklab(L):+ l = (L[0] + 0.3963377774 * L[1] + 0.2158037573 * L[2]) ** 3+ m = (L[0] - 0.1055613458 * L[1] - 0.0638541728 * L[2]) ** 3+ s = (L[0] - 0.0894841775 * L[1] - 1.2914855480 * L[2]) ** 3+ rgb = np.array([4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,+ -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s])+ return _srgb(rgb).astype(np.float32)+++# ------------------------------------------------------------------ fonts (geometric sans, mono, CJK)+_FONTS = {+ 'display': [('/System/Library/Fonts/Avenir Next.ttc', 0), ('/System/Library/Fonts/HelveticaNeue.ttc', 1),+ ('/usr/share/fonts/**/DejaVuSans-Bold.ttf', 0), ('C:/Windows/Fonts/arialbd.ttf', 0)],+ 'sans': [('/System/Library/Fonts/Avenir Next.ttc', 5), ('/System/Library/Fonts/HelveticaNeue.ttc', 10),+ ('/usr/share/fonts/**/DejaVuSans.ttf', 0), ('C:/Windows/Fonts/arial.ttf', 0)],+ 'mono': [('/System/Library/Fonts/Menlo.ttc', 0), ('/usr/share/fonts/**/DejaVuSansMono.ttf', 0),+ ('C:/Windows/Fonts/consola.ttf', 0)],+ 'mono_bold': [('/System/Library/Fonts/Menlo.ttc', 1), ('/usr/share/fonts/**/DejaVuSansMono-Bold.ttf', 0),+ ('C:/Windows/Fonts/consolab.ttf', 0)],+ 'cjk_bold': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 2), ('/System/Library/Fonts/STHeiti Medium.ttc', 1),+ ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0), ('C:/Windows/Fonts/msyhbd.ttc', 0)],+ 'cjk': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 0), ('/System/Library/Fonts/STHeiti Light.ttc', 1),+ ('/usr/share/fonts/**/NotoSansCJK*Regular*.tt[cf]', 0), ('C:/Windows/Fonts/msyh.ttc', 0)],+}+_CJK_FOR = {'display': 'cjk_bold', 'sans': 'cjk', 'mono': 'cjk', 'mono_bold': 'cjk_bold', 'cjk_bold': 'cjk_bold',+ 'cjk': 'cjk'}+++@lru_cache(maxsize=None)+def _font(style, size):+ env = os.environ.get('INKPAINT_FONT_' + style.upper())+ if env and os.path.exists(env): return ImageFont.truetype(env, int(size))+ for pat, idx in _FONTS.get(style, []):+ for f in glob.glob(pat, recursive=True):+ try:+ return ImageFont.truetype(f, int(size), index=idx)+ except OSError:+ pass+ return load_font('cjk_sans' if style.startswith('cjk') else 'sans', size)+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++def _runs(s, style):+ """split mixed CJK / Latin text into runs with the right font for each"""+ out = []+ for ch in s:+ st = _CJK_FOR[style] if _is_cjk(ch) else style+ if out and out[-1][1] == st: out[-1][0] += ch+ else: out.append([ch, st])+ return out+++# ------------------------------------------------------------------ outline geometry+def _area(P):+ x, y = P[:, 0], P[:, 1]+ return 0.5 * float(np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))+++def _smooth_closed(P, sigma):+ if sigma <= 0: return P+ r = int(3 * sigma) + 1+ k = np.exp(-np.arange(-r, r + 1) ** 2 / (2 * sigma * sigma)); k /= k.sum()+ Q = np.vstack([P[-r:], P, P[:r]])+ return np.stack([np.convolve(Q[:, 0], k, 'valid'), np.convolve(Q[:, 1], k, 'valid')], 1)+++def _trace(mask):+ """Moore-neighbour tracing of the outer boundary of a boolean mask -> (n, 2) pixel coords (x, y)"""+ h, w = mask.shape+ m = np.zeros((h + 2, w + 2), bool); m[1:-1, 1:-1] = mask+ ys, xs = np.nonzero(m)+ if len(ys) == 0: return np.zeros((0, 2), np.float64)+ i = int(np.argmin(ys * (w + 2) + xs)); cx, cy = int(xs[i]), int(ys[i])+ nbr = [(-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)] # W NW N NE E SE S SW (clockwise)+ b = 0+ out = [(cx, cy)]; first = None+ for _ in range(8 * m.size):+ for k in range(8):+ d = (b + k) % 8+ nx, ny = cx + nbr[d][0], cy + nbr[d][1]+ if m[ny, nx]: break+ else:+ break+ pd = (d - 1) % 8+ b = nbr.index((cx + nbr[pd][0] - nx, cy + nbr[pd][1] - ny))+ cx, cy = nx, ny+ if first is None: first = (cx, cy, b)+ elif (cx, cy, b) == first: break+ out.append((cx, cy))+ P = np.array(out[:-1] if len(out) > 1 else out, np.float64) - 1+ return P+++_RES = 900 # tracing resolution for a 1.4-unit box+++def _draw_prims(prims, res=_RES, span=1.4):+ """rasterise a list of primitives (unit coords) -> boolean mask. ('poly', pts) ('circle', x, y, r)+ ('line', pts, width) with round caps; any primitive can be ('sub', prim) to cut it out."""+ k = res / span+ T = lambda x, y: ((x + span / 2) * k, (y + span / 2) * k)+ im = Image.new('L', (res, res), 0); d = ImageDraw.Draw(im)+ for p in prims:+ fill = 255+ if p[0] == 'sub': fill = 0; p = p[1]+ if p[0] == 'poly':+ d.polygon([T(x, y) for x, y in p[1]], fill=fill)+ elif p[0] == 'circle':+ (x, y), r = T(p[1], p[2]), p[3] * k+ d.ellipse([x - r, y - r, x + r, y + r], fill=fill)+ elif p[0] == 'line':+ pts = [T(x, y) for x, y in p[1]]; w = p[2] * k+ d.line(pts, fill=fill, width=max(1, int(round(w))), joint='curve')+ for x, y in (pts[0], pts[-1]):+ d.ellipse([x - w / 2, y - w / 2, x + w / 2, y + w / 2], fill=fill)+ return np.asarray(im) > 127, k, span+++def _union(prims, smooth=1.6):+ m, k, span = _draw_prims(prims)+ P = _trace(m)+ P = _smooth_closed(P, smooth)+ return P / k - span / 2+++def _circle(n=180, r=0.5, cx=0.0, cy=0.0):+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)+ return np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)+++def _rot(P, deg, c=(0.0, 0.0)):+ t = np.deg2rad(deg); c = np.asarray(c)+ R = np.array([[np.cos(t), np.sin(t)], [-np.sin(t), np.cos(t)]]) # counter-clockwise on screen (y down)+ return (np.asarray(P) - c) @ R.T + c+++def _arm(ang, r0, r1):+ t = np.deg2rad(ang)+ return [(r0 * np.cos(t), -r0 * np.sin(t)), (r1 * np.cos(t), -r1 * np.sin(t))]+++@lru_cache(maxsize=None)+def _unit_shape(name):+ """unit outline (y down, roughly inside -0.5..0.5) for a named shape"""+ if name == 'circle':+ return _circle(240, 0.46)+ if name == 'square':+ return _union([('line', [(-0.28, -0.28), (0.28, -0.28), (0.28, 0.28), (-0.28, 0.28), (-0.28, -0.28)], 0.26),+ ('poly', [(-0.3, -0.3), (0.3, -0.3), (0.3, 0.3), (-0.3, 0.3)])])+ if name == 'triangle':+ return np.array([(0, -0.46), (0.5, 0.4), (-0.5, 0.4)])+ if name == 'star':+ t = np.deg2rad(90 + np.arange(10) * 36)+ r = np.where(np.arange(10) % 2 == 0, 0.52, 0.22)+ return np.stack([r * np.cos(t), -r * np.sin(t) + 0.04], 1)+ if name == 'heart':+ t = np.linspace(0, 2 * np.pi, 240, endpoint=False)+ x = 16 * np.sin(t) ** 3+ y = -(13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t))+ return np.stack([x, y + 1.5], 1) / 34+ if name == 'drop': # tip up, round belly: straight tangents into a circle+ cy, r, tip = 0.15, 0.34, -0.56+ b = np.arccos(r / (cy - tip)) # tangent points sit +-b either side of straight up+ th = np.linspace(np.pi / 2 + b, np.pi / 2 - b + 2 * np.pi, 200)+ arc = np.stack([r * np.cos(th), cy - r * np.sin(th)], 1)+ return np.vstack([[(0.0, tip)], arc])+ if name == 'cloud':+ return _union([('line', [(-0.33, 0.15), (0.33, 0.15)], 0.24),+ ('circle', -0.19, 0.04, 0.17), ('circle', 0.03, -0.08, 0.25), ('circle', 0.25, 0.04, 0.155)])+ if name == 'snowflake':+ prims = [('circle', 0, 0, 0.1)]+ for i in range(6):+ a = 90 + 60 * i+ prims.append(('line', _arm(a, 0, 0.47), 0.07))+ for dist, ln in ((0.2, 0.14), (0.33, 0.1)):+ t = np.deg2rad(a); bx, by = dist * np.cos(t), -dist * np.sin(t)+ for s in (-1, 1):+ u = np.deg2rad(a + s * 50)+ prims.append(('line', [(bx, by), (bx + ln * np.cos(u), by - ln * np.sin(u))], 0.06))+ return _union(prims, smooth=1.2)+ if name == 'mountain':+ return np.array([(-0.56, 0.32), (-0.27, -0.1), (-0.17, 0.0), (0.08, -0.42), (0.56, 0.32)])+ if name == 'river': # a winding river seen in perspective: thin far, wide near+ C = spline([(0.05, -0.47), (-0.07, -0.33), (0.09, -0.14), (-0.09, 0.12), (0.0, 0.45)], 30)+ n = len(C); tg = np.gradient(C, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True)+ nr = np.stack([-tg[:, 1], tg[:, 0]], 1)+ w = (0.03 + 0.4 * np.linspace(0, 1, n) ** 1.5)[:, None] / 2+ return np.vstack([C + nr * w, (C - nr * w)[::-1]])+ if name == 'wave': # a breaking wave: body on the right, crest curling over to the left+ K = [(-0.5, 0.16), (-0.34, 0.12), (-0.2, 0.04), (-0.11, -0.08), (-0.08, -0.19), (-0.12, -0.27),+ (-0.19, -0.29), (-0.24, -0.25), (-0.26, -0.18), (-0.3, -0.14), (-0.36, -0.19), (-0.37, -0.3),+ (-0.3, -0.4), (-0.16, -0.46), (0.0, -0.44), (0.16, -0.34), (0.28, -0.17), (0.4, 0.04), (0.5, 0.2),+ (0.55, 0.3)]+ return np.vstack([spline(K, 16), [(0.54, 0.36), (-0.5, 0.36)]])+ if name == 'sun': # a disc with eight rounded wedge rays+ prims = [('circle', 0, 0, 0.26)]+ for i in range(8):+ t = np.deg2rad(22.5 + 45 * i); u = np.array([np.cos(t), -np.sin(t)]); v = np.array([-u[1], u[0]])+ prims.append(('poly', [tuple(u * 0.22 + v * 0.07), tuple(u * 0.44 + v * 0.02), tuple(u * 0.44 - v * 0.02),+ tuple(u * 0.22 - v * 0.07)]))+ prims.append(('circle', *(u * 0.44), 0.025))+ return _union(prims, smooth=1.2)+ if name == 'moon':+ return _union([('circle', 0, 0, 0.42), ('sub', ('circle', 0.2, -0.12, 0.36))])+ if name == 'leaf':+ t = np.linspace(0, np.pi, 90)+ up = np.stack([-0.42 * np.cos(t), -0.26 * np.sin(t) ** 0.9], 1)+ body = np.vstack([up, up[::-1][1:-1] * [1, -1]])+ body = _rot(body, 35)+ return _union([('poly', body), ('line', [(-0.28, 0.2), (-0.44, 0.36)], 0.05)])+ if name == 'bird': # a gull gliding: two long arched wings, a small body+ K = [(-0.52, 0.04), (-0.34, -0.14), (-0.14, -0.12), (0.0, 0.02), (0.14, -0.12), (0.34, -0.14), (0.52, 0.04),+ (0.34, -0.06), (0.16, -0.02), (0.05, 0.1), (0.0, 0.14), (-0.05, 0.1), (-0.16, -0.02), (-0.34, -0.06)]+ P = spline(K + K[:3], 14)+ return P[14:14 * (len(K) + 1)]+ if name == 'fish':+ return _union([('poly', _circle(160, 1.0) * [0.34, 0.2] + [-0.08, 0]),+ ('poly', [(0.18, 0), (0.48, -0.2), (0.42, 0), (0.48, 0.2)])])+ if name == 'pin':+ c, r, tip = np.array([0, -0.12]), 0.31, np.array([0, 0.5])+ return _union([('circle', c[0], c[1], r),+ ('poly', [(-r * 0.86, -0.02), (r * 0.86, -0.02), tuple(tip)])], smooth=2.0)+ if name == 'house':+ return _union([('poly', [(-0.36, 0.42), (-0.36, -0.02), (0, -0.4), (0.36, -0.02), (0.36, 0.42)]),+ ('poly', [(0.14, -0.2), (0.14, -0.38), (0.25, -0.38), (0.25, -0.1)])], smooth=1.0)+ raise KeyError(name)+++SHAPES = ('circle', 'square', 'triangle', 'star', 'heart', 'drop', 'cloud', 'snowflake', 'mountain', 'river',+ 'wave', 'sun', 'moon', 'leaf', 'bird', 'fish', 'pin', 'house')+++class Morph:+ N = 256 # points per outline for every morphable shape++ def __init__(self, W=1920, H=1080, seed=0, ss=4):+ self.W, self.H, self.ss = W, H, ss+ self.rng = np.random.default_rng(seed)+ self.img = np.ones((H, W, 3), np.float32) * hexc(PAPER)+ self.ink = np.ones((H, W, 3), np.float32) * hexc(INK)+ self.tooth = np.ones((H, W), np.float32) # where bare paper shows (gets a little paper tooth)+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ================================================================ shapes and geometry (static)+ @staticmethod+ def resample(P, n=None):+ """closed outline -> n points evenly spaced along its arc length"""+ n = n or Morph.N+ P = np.asarray(P, np.float64)+ Q = np.vstack([P, P[:1]])+ seg = np.hypot(*np.diff(Q, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ t = np.linspace(0, s[-1], n, endpoint=False)+ return np.stack([np.interp(t, s, Q[:, 0]), np.interp(t, s, Q[:, 1])], 1)++ @staticmethod+ def shape(name, cx, cy, size, rot=0.0, n=None, flip=False, stretch=(1.0, 1.0)):+ """a library shape (see SHAPES) centred on (cx, cy), `size` px across the unit box, rotated `rot` degrees+ counter-clockwise, optionally mirrored and stretched (sx, sy); returned resampled to n points, clockwise+ on screen, starting at the top"""+ P = np.array(_unit_shape(name), np.float64)+ if flip: P[:, 0] *= -1+ P = P * np.asarray(stretch, np.float64)+ if rot: P = _rot(P, rot)+ return Morph.normalise(P * size + [cx, cy], n)++ @staticmethod+ def union(prims, cx, cy, size, n=None):+ """your own compound shape: primitives in unit coords (('circle', x, y, r), ('line', pts, width),+ ('poly', pts), ('sub', prim)) -> one traced, morphable outline"""+ return Morph.normalise(_union(prims) * size + [cx, cy], n)++ @staticmethod+ def normalise(P, n=None):+ """resample to n points, clockwise on screen (y down), first point = the topmost point above the centroid"""+ P = Morph.resample(P, n)+ if _area(P) < 0: P = P[::-1]+ c = P.mean(0)+ d = P - c+ ang = np.abs(np.arctan2(d[:, 0], -d[:, 1])) # angle from straight up+ return np.roll(P, -int(np.argmin(ang)), axis=0)++ @staticmethod+ def align(A, B):+ """B re-indexed so that B[i] corresponds to A[i]: same winding, best cyclic start (FFT cross-correlation+ of the centred, RMS-normalised outlines). Both must have the same number of points."""+ A, B = np.asarray(A, np.float64), np.asarray(B, np.float64)+ if len(A) != len(B): B = Morph.resample(B, len(A))+ if np.sign(_area(A)) != np.sign(_area(B)): B = B[::-1]+ a = A - A.mean(0); b = B - B.mean(0)+ a /= np.sqrt((a ** 2).sum(1).mean()) + 1e-9; b /= np.sqrt((b ** 2).sum(1).mean()) + 1e-9+ corr = sum(np.real(np.fft.ifft(np.conj(np.fft.fft(a[:, i])) * np.fft.fft(b[:, i]))) for i in (0, 1))+ return np.roll(B, -int(np.argmax(corr)), axis=0)++ @staticmethod+ def chain(shapes):+ """align every shape in a sequence to the one before it"""+ out = [np.asarray(shapes[0], np.float64)]+ for s in shapes[1:]: out.append(Morph.align(out[-1], s))+ return out++ @staticmethod+ def ease(t, kind='inout'):+ """timing curves: linear, in, out, inout (cubic), sine, quad, back (overshoot), expo"""+ t = np.clip(np.asarray(t, np.float64), 0, 1)+ if kind == 'linear': return t+ if kind == 'in': return t ** 3+ if kind == 'out': return 1 - (1 - t) ** 3+ if kind == 'inout': return np.where(t < 0.5, 4 * t ** 3, 1 - (-2 * t + 2) ** 3 / 2)+ if kind == 'quad': return np.where(t < 0.5, 2 * t * t, 1 - (-2 * t + 2) ** 2 / 2)+ if kind == 'sine': return -(np.cos(np.pi * t) - 1) / 2+ if kind == 'back':+ c1 = 1.70158 * 1.525+ return np.where(t < 0.5, (2 * t) ** 2 * ((c1 + 1) * 2 * t - c1) / 2,+ ((2 * t - 2) ** 2 * ((c1 + 1) * (t * 2 - 2) + c1) + 2) / 2)+ if kind == 'expo':+ return np.where(t < 0.5, 2 ** (20 * t - 10) / 2, (2 - 2 ** (-20 * t + 10)) / 2)+ raise KeyError(kind)++ @staticmethod+ def tween(A, B, s, at=None, stretch=0.0, direction=None, spin=0.0, scale=1.0):+ """in-between at eased progress s (0 = A, 1 = B; A and B aligned). The outline about its centroid is+ blended separately from the centroid, which moves to `at` if given (a point on your motion path).+ stretch: squash & stretch along `direction` (degrees, screen; default = the A->B direction);+ spin: extra rotation in degrees; scale: uniform scale."""+ A, B = np.asarray(A, np.float64), np.asarray(B, np.float64)+ cA, cB = A.mean(0), B.mean(0)+ rel = (1 - s) * (A - cA) + s * (B - cB)+ c = (1 - s) * cA + s * cB if at is None else np.asarray(at, np.float64)+ if direction is None:+ d = cB - cA; direction = np.degrees(np.arctan2(-d[1], d[0]))+ if stretch:+ t = np.deg2rad(direction); u = np.array([np.cos(t), -np.sin(t)]); v = np.array([-u[1], u[0]])+ a, b = rel @ u, rel @ v+ rel = np.outer(a * (1 + stretch), u) + np.outer(b / (1 + stretch), v)+ if spin: rel = _rot(rel, spin)+ return rel * scale + c++ @staticmethod+ def at(keys, T, kind='inout'):+ """for real animation: the outline at global time T (0 .. len(keys)-1) along an aligned chain of keys"""+ i = int(np.clip(np.floor(T), 0, len(keys) - 2))+ return Morph.tween(keys[i], keys[i + 1], float(Morph.ease(T - i, kind)))++ @staticmethod+ def mix(c0, c1, t):+ """colour blend through OKLab"""+ return _from_oklab((1 - t) * _oklab(_c(c0)) + t * _oklab(_c(c1)))++ @staticmethod+ def centroid(P):+ return np.asarray(P, np.float64).mean(0)++ # ================================================================ compositing+ def _box(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))+ if x1 <= x0 or y1 <= y0: return None+ return (slice(y0, y1), slice(x0, x1))++ def _over(self, sl, a, colour):+ a = np.clip(a, 0, 1)[..., None]+ col = self.ink[sl] if colour is None else (colour if isinstance(colour, np.ndarray) and colour.ndim == 3 else _c(colour))+ self.img[sl] = self.img[sl] * (1 - a) + col * a++ def _mask(self, polys, pad=4, width=None, closed=True, ss=None, round_caps=True):+ """supersampled polygon fill (width None) or polyline stroke -> (mask, slices)"""+ ss = ss or self.ss+ allp = np.concatenate([np.asarray(p, np.float64) for p in polys])+ pad = pad + (width or 0)+ sl = self._box(allp[:, 0].min() - pad, allp[:, 1].min() - pad, allp[:, 0].max() + pad, allp[:, 1].max() + pad)+ if sl is None: return None, None+ x0, y0 = sl[1].start, sl[0].start+ bw, bh = sl[1].stop - x0, sl[0].stop - y0+ im = Image.new('L', (bw * ss, bh * ss), 0); d = ImageDraw.Draw(im)+ for p in polys:+ Q = [((x - x0) * ss, (y - y0) * ss) for x, y in np.asarray(p, np.float64)]+ if width is None:+ d.polygon(Q, fill=255)+ else:+ w = width * ss+ if closed: Q = Q + Q[:2]+ d.line(Q, fill=255, width=max(1, int(round(w))), joint='curve')+ if round_caps and not closed:+ for x, y in (Q[0], Q[-1]):+ d.ellipse([x - w / 2, y - w / 2, x + w / 2, y + w / 2], fill=255)+ return np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255, sl++ def _clipmask(self, sl, clip, half):+ m = 1.0+ if clip is not None:+ cm, csl = self._mask([clip])+ full = np.zeros((self.H, self.W), np.float32)+ if csl is not None: full[csl] = cm+ m = m * full[sl]+ if half is not None:+ (x0, y0), (x1, y1) = half+ X, Y = np.meshgrid(np.arange(sl[1].start, sl[1].stop) + 0.5, np.arange(sl[0].start, sl[0].stop) + 0.5)+ dx, dy = x1 - x0, y1 - y0; L = np.hypot(dx, dy) + 1e-9+ side = ((X - x0) * dy - (Y - y0) * dx) / L # > 0: right of the directed line on screen+ m = m * np.clip(side + 0.5, 0, 1)+ return m++ # ================================================================ background+ def paper(self, colour=PAPER, ink=INK):+ """the whole sheet: flat pale paper (grain is added at composite time)"""+ self.img[:] = _c(colour); self.ink[:] = _c(ink); self.tooth[:] = 1++ def panel(self, x0, y0, x1, y1, colour, ink=INK):+ """a flat colour field (one keyframe's background); `ink` is the colour ghosts and lines take on it"""+ sl = self._box(x0, y0, x1, y1)+ if sl is None: return+ self.img[sl] = _c(colour); self.ink[sl] = _c(ink); self.tooth[sl] = 0++ def wipe(self, cx, cy, r, colour, ink=INK, clip_box=None):+ """a circular colour reveal frozen mid-way (background switching outward from a point)"""+ P = _circle(360, r, cx, cy)+ m, sl = self._mask([P])+ if sl is None: return+ if clip_box is not None:+ x0, y0, x1, y1 = clip_box+ X, Y = np.meshgrid(np.arange(sl[1].start, sl[1].stop), np.arange(sl[0].start, sl[0].stop))+ m = m * ((X >= x0) & (X < x1) & (Y >= y0) & (Y < y1))+ self._over(sl, m, colour)+ self.ink[sl] = self.ink[sl] * (1 - m[..., None]) + _c(ink) * m[..., None]+ self.tooth[sl] *= 1 - m++ # ================================================================ shape layer+ def fill(self, P, colour, alpha=1.0, clip=None, half=None):+ """a flat shape. clip: only inside another outline; half=((x0, y0), (x1, y1)): only right of that line+ (a two-tone fold / facet)"""+ m, sl = self._mask([P])+ if sl is None: return+ if clip is not None or half is not None: m = m * self._clipmask(sl, clip, half)+ self._over(sl, m * alpha, colour)+ self.tooth[sl] *= 1 - m * alpha+ return m, sl++ def outline(self, P, colour=None, width=3.0, alpha=1.0, closed=True, dash=None):+ """outline of a shape (or open path if closed=False). colour None = the panel ink underneath.+ dash=(on, off) in px"""+ P = np.asarray(P, np.float64)+ if dash is None:+ m, sl = self._mask([P], width=width, closed=closed, round_caps=not closed)+ else:+ m, sl = self._mask(self._dashes(P, dash, closed), width=width, closed=False)+ if sl is None: return+ self._over(sl, m * alpha, colour)++ def stroke(self, pts, colour=None, width=6.0, alpha=1.0, smooth=True):+ """a round-capped open line (sun rays, highlights, ripples, foam)"""+ P = np.asarray(pts, np.float64)+ if smooth and len(P) > 2: P = spline(P, 12)+ m, sl = self._mask([P], width=width, closed=False)+ if sl is not None: self._over(sl, m * alpha, colour)++ def dot(self, x, y, r, colour=None, alpha=1.0):+ m, sl = self._mask([_circle(max(24, int(r * 3)), r, x, y)])+ if sl is not None: self._over(sl, m * alpha, colour)++ @staticmethod+ def _dashes(P, dash, closed=True):+ on, off = dash+ Q = np.vstack([P, P[:1]]) if closed else P+ seg = np.hypot(*np.diff(Q, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ out = []; a = 0.0+ while a < s[-1]:+ b = min(a + on, s[-1])+ ts = np.linspace(a, b, max(2, int((b - a) / 2) + 2))+ out.append(np.stack([np.interp(ts, s, Q[:, 0]), np.interp(ts, s, Q[:, 1])], 1))+ a = b + off+ return out++ def ghost(self, P, fill=None, line=None, fill_alpha=0.16, line_alpha=0.62, width=2.4, dash=None):+ """an onion-skin frame: a faint fill plus a thin outline (line None = the panel ink underneath)"""+ if fill is not None: self.fill(P, fill, fill_alpha)+ self.outline(P, line, width, line_alpha, dash=dash)++ def points(self, P, every=4, r=2.6, colour=None, alpha=0.9):+ """dots on every `every`-th resampled point: shows that the outline is N matching points"""+ P = np.asarray(P)[::every]+ polys = [_circle(16, r, x, y) for x, y in P]+ m, sl = self._mask(polys)+ if sl is not None: self._over(sl, m * alpha, colour)++ def links(self, A, B, every=16, colour=None, width=1.2, alpha=0.35, dash=(5, 6)):+ """thin dashed lines from points of A to their partners on B (the correspondence the morph uses)"""+ segs = []+ for a, b in zip(np.asarray(A)[::every], np.asarray(B)[::every]):+ segs += self._dashes(np.array([a, b]), dash, closed=False)+ m, sl = self._mask(segs, width=width, closed=False)+ if sl is not None: self._over(sl, m * alpha, colour)++ # ================================================================ motion marks+ def path(self, pts, per=40):+ """a smooth motion path through control points (Catmull-Rom) -> dense polyline"""+ return spline(np.asarray(pts, np.float64), per).astype(np.float64)++ @staticmethod+ def along(P, u):+ """point and direction (degrees, screen) at fraction u of a polyline's length"""+ P = np.asarray(P, np.float64)+ seg = np.hypot(*np.diff(P, axis=0).T); s = np.concatenate([[0], np.cumsum(seg)])+ t = float(np.clip(u, 0, 1)) * s[-1]+ x, y = np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1])+ i = int(np.clip(np.searchsorted(s, t) - 1, 0, len(P) - 2))+ d = P[i + 1] - P[i]+ return np.array([x, y]), float(np.degrees(np.arctan2(-d[1], d[0])))++ def trail(self, P, colour=None, r=2.4, gap=15, alpha=0.7, dash=None):+ """the motion path: dots of radius r every `gap` px, or dashes if dash=(on, off) (then r = line width)"""+ P = np.asarray(P, np.float64)+ if dash is not None:+ m, sl = self._mask(self._dashes(P, dash, closed=False), width=r, closed=False)+ else:+ seg = np.hypot(*np.diff(P, axis=0).T); s = np.concatenate([[0], np.cumsum(seg)])+ ts = np.arange(gap / 2, s[-1], gap)+ pts = np.stack([np.interp(ts, s, P[:, 0]), np.interp(ts, s, P[:, 1])], 1)+ m, sl = self._mask([_circle(16, r, x, y) for x, y in pts])+ if sl is not None: self._over(sl, m * alpha, colour)++ def chevron(self, x, y, direction, size=12, colour=None, width=3.0, alpha=0.8):+ """a small arrowhead pointing along `direction` (degrees)"""+ t = np.deg2rad(direction); u = np.array([np.cos(t), -np.sin(t)]); v = np.array([-u[1], u[0]])+ c = np.array([x, y]) + u * size * 0.4+ pts = np.array([c - u * size + v * size * 0.75, c, c - u * size - v * size * 0.75])+ m, sl = self._mask([pts], width=width, closed=False)+ if sl is not None: self._over(sl, m * alpha, colour)++ def streaks(self, x, y, direction, n=3, length=60, spread=26, colour=None, width=5.0, alpha=0.8, seed=None):+ """speed lines trailing behind a moving shape: they start at (x, y) (the shape's trailing edge) and run+ back against `direction`; uneven lengths and offsets so they never look like a ladder"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ t = np.deg2rad(direction); u = np.array([np.cos(t), -np.sin(t)]); v = np.array([-u[1], u[0]])+ segs = []+ for k in range(n):+ off = (k - (n - 1) / 2) * spread + r.uniform(-0.2, 0.2) * spread+ p0 = np.array([x, y]) - u * r.uniform(0, 0.35) * length + v * off+ segs.append(np.array([p0, p0 - u * length * r.uniform(0.4, 1.0) * (1.0 if k != (n - 1) // 2 else 1.25)]))+ m, sl = self._mask(segs, width=width, closed=False)+ if sl is not None: self._over(sl, m * alpha, colour)++ # ================================================================ timeline+ def diamond(self, x, y, r=11, fill=None, line=INK, width=2.4):+ P = np.array([(x, y - r), (x + r, y), (x, y + r), (x - r, y)])+ if fill is not None: self.fill(P, fill)+ self.outline(P, line, width)++ def ease_curve(self, x0, y0, x1, y1, kind='inout', colour=INK, width=3.0, ticks=(), tick_colour=None,+ drop=True, alpha=1.0):+ """the value graph of one transition: eased progress from (x0, y0) (value 0) to (x1, y1) (value 1),+ with a dot on the curve at each frame time in `ticks` and a dashed drop line to the baseline"""+ t = np.linspace(0, 1, 120)+ P = np.stack([x0 + (x1 - x0) * t, y0 + (y1 - y0) * self.ease(t, kind)], 1)+ self.outline(P, colour, width, alpha, closed=False)+ for u in ticks:+ px, py = x0 + (x1 - x0) * u, y0 + (y1 - y0) * float(self.ease(u, kind))+ if drop: self.outline(np.array([(px, py), (px, y0)]), tick_colour or colour, 1.4, 0.45 * alpha,+ closed=False, dash=(4, 5))+ self.dot(px, py, width * 1.35, tick_colour or colour, alpha)++ # ================================================================ lettering+ def text_width(self, s, size, font='sans', spacing=0.0):+ return sum(_font(st, size).getlength(r) for r, st in _runs(s, font)) + spacing * max(0, len(s) - 1)++ def text(self, s, x, y, size, colour=INK, font='sans', anchor='l', spacing=0.0, alpha=1.0, baseline=True):+ """one line of text; x anchored left / middle / right ('l', 'm', 'r'), y is the baseline+ (baseline=False: y is the vertical middle of capitals). CJK runs switch to the CJK sans automatically."""+ runs = _runs(s, font)+ tw = self.text_width(s, size, font, spacing)+ x0 = x - tw * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor]+ if not baseline: y = y + size * 0.36+ pad = int(size * 1.6)+ sl = self._box(x0 - 4, y - pad, x0 + tw + 4, y + pad * 0.5)+ if sl is None: return tw+ bx, by = sl[1].start, sl[0].start+ im = Image.new('L', (sl[1].stop - bx, sl[0].stop - by), 0); d = ImageDraw.Draw(im)+ cx = x0 - bx+ for r, st in runs:+ f = _font(st, size)+ if spacing:+ for ch in r:+ d.text((cx, y - by), ch, font=f, fill=255, anchor='ls'); cx += f.getlength(ch) + spacing+ else:+ d.text((cx, y - by), r, font=f, fill=255, anchor='ls'); cx += f.getlength(r)+ self._over(sl, np.asarray(im, np.float32) / 255 * alpha, colour)+ return tw++ # ================================================================ output+ def composite(self, grain=0.006, paper_tooth=0.011):+ img = self.img.copy()+ if not hasattr(self, '_grain'):+ r = np.random.default_rng(12345)+ g = r.standard_normal((self.H, self.W)).astype(np.float32)+ fib = noise2d(self.H, self.W, 2.0, 2, 777) - 0.5+ self._grain = (g * 0.5 + blur(g, 1.0) * 1.8 + fib * 1.6).astype(np.float32)+ k = grain + paper_tooth * self.tooth[..., None] # bare paper shows a bit more tooth+ img = img + self._grain[..., None] * k+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/newscollage.py b/lib/newscollage.pynew file mode 100644index 0000000..a4fdbd2--- /dev/null+++ b/lib/newscollage.py@@ -0,0 +1,1312 @@+"""newscollage -- a Dada / magazine cut-and-paste collage on a kraft board (numpy + Pillow only).++Old newspaper torn by hand, halftone "photographs" of objects cut out with scissors, a big disc of red paper,+ransom-note letters snipped one by one out of different magazines, masking tape and rubber stamps.++Model: everything is a piece of paper that was printed first, then torn or cut, then glued down.+ board kraft paper: warm brown, cloudy (unevenly pulped), full of short dark and pale fibres and a few bark+ flecks, plus a per-pixel tooth field that stamp ink catches on.+ sheet one piece of paper in its own frame: paper colour, printed ink (multiplied, with a little ink spread+ and uneven density) and an outline. Printing happens before the paper is torn or cut, so the ink runs+ right up to a scissor cut.+ tear tearing splits the paper in its thickness. The outline wanders (slow bays plus fine jaggies), and along+ some stretches the printed top layer comes away further than the bottom, so a band of pale, unprinted+ paper core shows (the torn rim), with loose fibres sticking out past the edge. Sides that are not torn+ are scissor-cut: straight, with a slight kink wherever the blades were re-opened.+ cutout scissors follow a silhouette at a small distance: the outline is a chain of short straight cuts+ (Douglas-Peucker on the offset outline) that skips the narrow gaps a blade cannot get into, with an+ occasional overcut nick.+ newsprint greyish-yellow paper, columns of justified fake text (generated pseudo-words, never real news), a+ folio line, kicker, headline and deck, subheads, column rules, a boxed advertisement, a halftone picture+ with a caption; yellowing toward the edges, foxing, and the reverse page showing through, mirrored.+ photo an "old photograph" is actually rendered: a studio still life built as a height field with albedo /+ metal / gloss maps (discs, domes, rings, rods, gears, spirals, screws, printed marks), lit by one key+ light (Lambert + Blinn; chrome reflects a bright sky over a dark floor), with cast shadows on itself and+ on the backdrop and ambient occlusion in the crevices. It is then printed as an AM halftone: a 45-degree+ screen of round dots that grow, join into a chequerboard at 50 % and leave only white holes in the+ shadows; ragged dot edges from the paper fibres, dot gain, uneven ink.+ paste a sheet is rotated into place and glued: a tight contact shadow plus a softer lifted one, the cut edge+ catching the light on the upper-left and going dark on the lower-right; optional glue ripples (a wrinkle+ height field lit by the same light).+ letters ransom-note lettering: every character cut from a different magazine, with its own typeface, size,+ paper and ink (black on white, knocked out of red or black, black on newsprint with neighbouring text,+ on mustard, on a halftone tint), its own tilt and bounce, and a crooked scissor cut round it.+ tape masking tape: crepe paper, translucent (what is under it shows through, dimmed), fine crepe ridges+ across its width, serrated torn ends; wherever it bridges a paper edge the edge shows as a lit ridge.+ stamp a rubber stamp: ink pressed unevenly (a pressure gradient, voids where the rubber did not take), ink+ piling up at the glyph edges, soaked into whatever paper is underneath (multiply).+Order: board -> big sheets (newsprint) -> colour fields (red disc) -> photos -> letters and labels -> tape, stamps.+Rotations are degrees counter-clockwise, like PIL.++ from newscollage import NewsCollage, Photo, RED, INK+ nc = NewsCollage(1920, 1080, seed=1)+ nc.board()+ s = nc.newsprint(600, 900, columns=3); s.tear('rtb'); nc.paste(s, 320, 540, rot=-3)+ nc.disc(1100, 520, 330, RED)+ p = Photo(420, 420, seed=2); p.gear(210, 210, 170, teeth=40, spokes=5)+ s = nc.print_photo(p); s.cutout(14); nc.paste(s, 1100, 520, rot=8)+ nc.ransom('拆开看看', 90, 820, 150)+ nc.tape(400, 120, 180, rot=-8)+ nc.stamp(1700, 950, [('第 42 期', 40), ('No.42', 30)], rot=6)+ nc.save('out.jpg')+"""+import glob+import os+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import (blur, fbm1d, spline, noise2d, smoothstep, shift, load_font, height_normals, height_shadow,+ ambient_occlusion)++INK, BLACK, RED, MUSTARD = '#1f1c1a', '#1b1918', '#c8281d', '#d9a531'+KRAFT, NEWS, PAPER, TAPE = '#b28a5b', '#e6ddc5', '#f1ece0', '#e8d9ae'+NEWS_CORE, PAPER_CORE = '#f5f1e6', '#fbf8f1'+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++# ---------------------------------------------------------------- fonts: newspaper and magazine faces+_FACES = { # (glob, face index), first hit wins -- macOS, Linux, Windows; anything missing falls back to core fonts+ 'news': [('/System/Library/Fonts/Supplemental/Times New Roman.ttf', 0), ('/usr/share/fonts/**/LiberationSerif-Regular.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSerif.ttf', 0), ('C:/Windows/Fonts/times.ttf', 0)],+ 'news_bold': [('/System/Library/Fonts/Supplemental/Times New Roman Bold.ttf', 0), ('/usr/share/fonts/**/LiberationSerif-Bold.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0), ('C:/Windows/Fonts/timesbd.ttf', 0)],+ 'news_italic': [('/System/Library/Fonts/Supplemental/Times New Roman Italic.ttf', 0), ('/usr/share/fonts/**/LiberationSerif-Italic.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSerif-Italic.ttf', 0), ('C:/Windows/Fonts/timesi.ttf', 0)],+ 'serif_bold': [('/System/Library/Fonts/Supplemental/Georgia Bold.ttf', 0), ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0),+ ('C:/Windows/Fonts/georgiab.ttf', 0)],+ 'slab': [('/System/Library/Fonts/Supplemental/Rockwell.ttc', 2), ('/System/Library/Fonts/Supplemental/SuperClarendon.ttc', 7),+ ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0), ('C:/Windows/Fonts/ROCKB.TTF', 0)],+ 'clarendon': [('/System/Library/Fonts/Supplemental/SuperClarendon.ttc', 7), ('/System/Library/Fonts/Supplemental/Rockwell.ttc', 2),+ ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0)],+ 'didone': [('/System/Library/Fonts/Supplemental/Bodoni 72.ttc', 2), ('/System/Library/Fonts/Supplemental/Didot.ttc', 2),+ ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0), ('C:/Windows/Fonts/BOD_B.TTF', 0)],+ 'poster': [('/System/Library/Fonts/Supplemental/Impact.ttf', 0), ('/System/Library/Fonts/HelveticaNeue.ttc', 9),+ ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', 0), ('C:/Windows/Fonts/impact.ttf', 0)],+ 'futura': [('/System/Library/Fonts/Supplemental/Futura.ttc', 4), ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', 0),+ ('C:/Windows/Fonts/GOTHICB.TTF', 0)],+ 'grotesk': [('/System/Library/Fonts/HelveticaNeue.ttc', 4), ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', 0),+ ('C:/Windows/Fonts/arialbd.ttf', 0)],+ 'typewriter': [('/System/Library/Fonts/Supplemental/AmericanTypewriter.ttc', 0), ('/System/Library/Fonts/Supplemental/Courier New.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSansMono.ttf', 0), ('C:/Windows/Fonts/cour.ttf', 0)],+ 'typewriter_bold': [('/System/Library/Fonts/Supplemental/AmericanTypewriter.ttc', 2), ('/System/Library/Fonts/Supplemental/Courier New Bold.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSansMono-Bold.ttf', 0), ('C:/Windows/Fonts/courbd.ttf', 0)],+ 'cjk_song': [('/System/Library/Fonts/Supplemental/Songti.ttc', 0), ('/usr/share/fonts/**/NotoSerifCJK*Black*.tt[cf]', 0),+ ('/usr/share/fonts/**/NotoSerifCJK*Bold*.tt[cf]', 0), ('C:/Windows/Fonts/simsun.ttc', 0)],+ 'cjk_hei': [('/System/Library/Fonts/STHeiti Medium.ttc', 1), ('/System/Library/Fonts/Hiragino Sans GB.ttc', 2),+ ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0), ('C:/Windows/Fonts/msyhbd.ttc', 0)],+ 'cjk_round': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 2), ('/System/Library/Fonts/STHeiti Medium.ttc', 1),+ ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0), ('C:/Windows/Fonts/msyhbd.ttc', 0)],+}+_GENERIC = {'news': 'serif', 'news_bold': 'serif', 'news_italic': 'serif', 'serif_bold': 'serif', 'slab': 'serif',+ 'clarendon': 'serif', 'didone': 'serif', 'poster': 'condensed', 'futura': 'condensed', 'grotesk': 'sans_bold',+ 'typewriter_bold': 'typewriter', 'cjk_song': 'cjk', 'cjk_hei': 'cjk_sans', 'cjk_round': 'cjk_sans', 'cjk_kai': 'cjk'}+_FONT_CACHE, _PATH_CACHE = {}, {}+++def font(style, size):+ """PIL font for a collage style: news, news_bold, news_italic, serif_bold, slab, clarendon, didone, poster, futura,+ grotesk, typewriter(_bold), cjk_song, cjk_hei, cjk_round, cjk_kai, or any core.load_font style"""+ key = (style, int(size))+ if key in _FONT_CACHE: return _FONT_CACHE[key]+ if style not in _PATH_CACHE:+ _PATH_CACHE[style] = None+ env = os.environ.get('INKPAINT_FONT_' + style.upper())+ if env and os.path.exists(env):+ _PATH_CACHE[style] = (env, 0)+ for pat, idx in _FACES.get(style, []):+ if _PATH_CACHE[style]: break+ for p in glob.glob(pat, recursive=True):+ try:+ ImageFont.truetype(p, 12, index=idx)+ _PATH_CACHE[style] = (p, idx); break+ except OSError:+ pass+ hit = _PATH_CACHE[style]+ f = ImageFont.truetype(hit[0], int(size), index=hit[1]) if hit else load_font(_GENERIC.get(style, style), size)+ _FONT_CACHE[key] = f+ return f+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++_HAS = {}+++def _has(style, ch):+ """does the face for `style` really have a glyph for ch (not the .notdef box)?"""+ key = (style, ch)+ if key not in _HAS:+ f = font(style, 40)+ _HAS[key] = ch.isspace() or bytes(f.getmask(ch)) != bytes(f.getmask('\uffff'))+ return _HAS[key]+++def _runs(s, style):+ """split text into CJK / Latin runs, each with a face that has its glyphs (arrows etc. fall back to CJK)"""+ cjk = style if style.startswith('cjk') else ('cjk_song' if style in ('news', 'news_bold', 'serif_bold', 'didone', 'slab', 'clarendon') else 'cjk_hei')+ lat = style if not style.startswith('cjk') else {'cjk_song': 'serif_bold', 'cjk_kai': 'serif_bold'}.get(style, 'sans_bold')+ runs = []+ for ch in s:+ k = _is_cjk(ch) or not _has(lat, ch)+ if runs and runs[-1][1] == k: runs[-1][0] += ch+ else: runs.append([ch, k])+ return [(t, cjk if k else lat) for t, k in runs]+++def text_width(s, size, style='serif_bold', spacing=0.0):+ w = 0.0+ for t, st in _runs(s, style):+ f = font(st, size)+ w += sum(f.getlength(ch) + spacing for ch in t) if spacing else f.getlength(t)+ return w - (spacing if spacing else 0)+++def text_mask(h, w, s, x, y, size, style='serif_bold', anchor='ls', spacing=0.0, rot=0.0, weight=0.0, ss=2):+ """text -> float mask (h, w). Mixed CJK / Latin, letter spacing, faux-bold weight (px), rotation about (x, y).+ anchor: first letter l/m/r, second s (baseline) / m (middle of the capitals) / t (top of the capitals)"""+ runs = _runs(s, style)+ items = []+ for t, st in runs:+ f = font(st, size * ss)+ if spacing:+ for ch in t: items.append((ch, f, f.getlength(ch) + spacing * ss))+ else:+ items.append((t, f, f.getlength(t)))+ total = sum(a for _, _, a in items) - (spacing * ss if spacing else 0)+ f0 = items[0][1]+ ref = '中' if _is_cjk(s.strip()[:1] or 'H') else 'H'+ capH = -f0.getbbox(ref, anchor='ls')[1]+ dyb = {'s': 0, 'm': capH / 2, 't': capH}.get(anchor[1], 0)+ im = Image.new('L', (w * ss, h * ss), 0)+ d = ImageDraw.Draw(im)+ cx = x * ss - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ by = y * ss + dyb+ sw = int(round(weight * ss))+ for t, f, adv in items:+ d.text((cx, by), t, font=f, fill=255, anchor='ls', stroke_width=sw, stroke_fill=255)+ cx += adv+ if rot:+ im = im.rotate(rot, resample=Image.BICUBIC, center=(x * ss, y * ss))+ if ss > 1:+ im = im.resize((w, h), Image.BOX)+ return np.asarray(im, np.float32) / 255+++def poly_mask(h, w, pts, ss=3):+ im = Image.new('L', (w * ss, h * ss), 0)+ ImageDraw.Draw(im).polygon([(float(x) * ss, float(y) * ss) for x, y in pts], fill=255)+ if ss > 1: im = im.resize((w, h), Image.BOX)+ return np.asarray(im, np.float32) / 255+++def lines_mask(h, w, paths, width, ss=3):+ """polylines of a given width (px) -> float mask"""+ im = Image.new('L', (w * ss, h * ss), 0)+ d = ImageDraw.Draw(im)+ for P in paths:+ P = [(float(x) * ss, float(y) * ss) for x, y in P]+ d.line(P, fill=255, width=max(1, int(round(width * ss))), joint='curve')+ r = width * ss / 2+ for q in (P[0], P[-1]):+ d.ellipse([q[0] - r, q[1] - r, q[0] + r, q[1] + r], fill=255)+ if ss > 1: im = im.resize((w, h), Image.BOX)+ return np.asarray(im, np.float32) / 255+++def _dp(P, tol):+ """Douglas-Peucker simplification of an open polyline"""+ if len(P) < 3: return P+ a, b = P[0], P[-1]+ ab = b - a; L = np.hypot(*ab) + 1e-9+ d = np.abs(ab[0] * (P[:, 1] - a[1]) - ab[1] * (P[:, 0] - a[0])) / L+ i = int(np.argmax(d))+ if d[i] > tol:+ return np.vstack([_dp(P[:i + 1], tol)[:-1], _dp(P[i:], tol)])+ return np.vstack([a, b])+++def halftone(tone, cell=6.5, angle=45.0, rough=0.08, seed=0, gain=0.5):+ """AM halftone screen: tone (0 black .. 1 white) -> ink coverage 0..1.+ Round dots on a screen at `angle`, `cell` px apart; they grow with darkness, touch in a chequerboard at 50 %+ and leave white holes in the shadows. rough: ragged dot edges from paper fibres; gain: dot gain (ink spread, px)."""+ h, w = tone.shape+ Y, X = np.mgrid[0:h, 0:w].astype(np.float32)+ a = np.deg2rad(angle)+ u = (X * np.cos(a) + Y * np.sin(a)) / cell+ v = (-X * np.sin(a) + Y * np.cos(a)) / cell+ spot = 0.5 - 0.25 * (np.cos(2 * np.pi * u) + np.cos(2 * np.pi * v))+ grad = (np.pi / (2 * cell)) * np.sqrt(np.sin(2 * np.pi * u) ** 2 + np.sin(2 * np.pi * v) ** 2) + 0.035+ if rough:+ n = blur(np.random.default_rng(seed).random((h, w)).astype(np.float32), 0.7)+ spot = spot + rough * (n - 0.5) / (n.std() * 3.4 + 1e-6)+ c = np.clip(1 - tone, 0, 1)+ ink = np.clip((c - spot) / grad + 0.5, 0, 1) * smoothstep(0.0, 0.04, c)+ ink = np.maximum(ink, smoothstep(0.93, 1.0, c))+ if gain:+ ink = np.clip(blur(ink, gain) * 1.12, 0, 1)+ return ink+++class Frame:+ """a rotated rectangle on the board. pt(lx, ly) maps a point measured from the sheet's top-left corner (in its+ own rotated axes) to canvas coordinates; rot is the rotation to use for anything written on it."""++ def __init__(self, cx, cy, w, h, rot):+ self.cx, self.cy, self.w, self.h, self.rot = cx, cy, w, h, rot++ def pt(self, lx, ly):+ u, v = lx - self.w / 2, ly - self.h / 2+ t = np.deg2rad(self.rot)+ return (self.cx + u * np.cos(t) + v * np.sin(t), self.cy - u * np.sin(t) + v * np.cos(t))+++# ================================================================ a piece of paper+class Sheet:+ """one piece of paper in its own frame (w x h px): colour, printed ink, outline, torn rim.+ core: the colour of the paper's inside (shows along torn edges); kind is informational ('news', 'photo', ...)"""++ def __init__(self, w, h, colour=PAPER, seed=0, core=None, kind='paper'):+ self.w, self.h = int(round(w)), int(round(h))+ self.rng = np.random.default_rng(seed)+ self.YY, self.XX = np.mgrid[0:self.h, 0:self.w].astype(np.float32)+ col = _c(colour)+ self.colour = col+ self.core = _c(core) if core is not None else np.clip(col + (1 - col) * 0.55, 0, 1)+ self.kind = kind+ g = blur(self.rng.random((self.h, self.w)).astype(np.float32), 0.6)+ mt = noise2d(self.h, self.w, 70, 3, self._seed())+ self.tooth = np.clip(0.5 + (g - g.mean()) / (g.std() * 5 + 1e-6), 0, 1)+ self.rgb = np.ones((self.h, self.w, 3), np.float32) * col * (1 + 0.035 * (mt - 0.5) + 0.02 * (self.tooth - 0.5))[..., None]+ self.mask = np.ones((self.h, self.w), np.float32)+ self.obj = None+ self.centre = None++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ def copy(self):+ s = Sheet.__new__(Sheet)+ s.__dict__.update(self.__dict__)+ s.rgb, s.mask = self.rgb.copy(), self.mask.copy()+ s.rng = np.random.default_rng(self._seed())+ return s++ # ------------------------------------------------------------ printing+ def ink(self, m, colour=INK, alpha=0.94, spread=0.35, mottle=0.14):+ """print ink through mask m (0..1): a little spread, uneven density, multiplied onto the paper"""+ m = np.clip(m, 0, 1)+ if spread: m = np.maximum(m, np.clip(blur(m, spread) * 1.08, 0, 1))+ dens = alpha * (1 - mottle + mottle * self.tooth) * (0.96 + 0.04 * noise2d(self.h, self.w, 40, 2, self._seed()))+ self.rgb *= 1 - (m * dens)[..., None] * (1 - _c(colour))++ def paint(self, m, colour, alpha=1.0):+ """opaque colour (not multiplied): white-out, pasted-in paper colour"""+ a = np.clip(m, 0, 1)[..., None] * alpha+ self.rgb = self.rgb * (1 - a) + _c(colour) * (1 + 0.02 * (self.tooth - 0.5))[..., None] * a++ def rect(self, x0, y0, x1, y1):+ X, Y = self.XX, self.YY+ return np.clip(X - x0 + 0.5, 0, 1) * np.clip(x1 - X + 0.5, 0, 1) * np.clip(Y - y0 + 0.5, 0, 1) * np.clip(y1 - Y + 0.5, 0, 1)++ def text_mask(self, s, x, y, size, font='serif_bold', anchor='ls', spacing=0.0, rot=0.0, weight=0.0):+ return text_mask(self.h, self.w, s, x, y, size, font, anchor, spacing, rot, weight)++ def text(self, s, x, y, size, font='serif_bold', colour=INK, anchor='ls', spacing=0.0, rot=0.0, weight=0.0, alpha=0.95):+ m = self.text_mask(s, x, y, size, font, anchor, spacing, rot, weight)+ self.ink(m, colour, alpha)+ return m++ def block(self, x0, y0, x1, y1, colour=RED, minus=None, alpha=0.96):+ """a solid printed block; `minus` (a mask) is knocked out and stays paper-coloured (reversed type)"""+ m = self.rect(x0, y0, x1, y1)+ if minus is not None: m = m * (1 - np.clip(minus, 0, 1))+ self.ink(m, colour, alpha, spread=0.25, mottle=0.1)++ def rule(self, x0, y0, x1, y1, width=1.2, colour=INK, alpha=0.9):+ self.ink(lines_mask(self.h, self.w, [[(x0, y0), (x1, y1)]], width), colour, alpha, spread=0.2)++ # ------------------------------------------------------------ outline: tear, cut+ def tear(self, sides='rb', depth=9.0, rim=7.0, rough=1.0, fibres=True):+ """tear the listed sides ('t', 'r', 'b', 'l'); the others are scissor-cut. depth: how far the torn line+ wanders in from the edge; rim: max width of the pale torn core that shows where the top layer came away"""+ r = self.rng+ h, w = self.h, self.w+ X, Y = self.XX, self.YY+ paper = np.ones((h, w), np.float32); printed = np.ones((h, w), np.float32)+ fib_paths = []+ for side in 'trbl':+ L = w if side in 'tb' else h+ along = (X if side in 'tb' else Y).astype(np.int32).clip(0, L - 1)+ inward = {'t': Y, 'b': h - 1 - Y, 'l': X, 'r': w - 1 - X}[side]+ if side in sides:+ s0 = self._seed()+ big = fbm1d(L, 70, 4, s0)+ fine = fbm1d(L, 5, 3, s0 + 1)+ off = 1.5 + depth * (0.55 + 0.45 * big) + rough * 1.6 * fine+ bites = np.zeros(L, np.float32) # a few deeper bites where the tear turned+ for _ in range(max(1, L // 260)):+ c0 = r.uniform(0, L); bw = r.uniform(14, 40)+ bites += r.uniform(0.3, 0.9) * depth * np.exp(-((np.arange(L) - c0) / bw) ** 2)+ off = off + bites+ rw = rim * np.clip(0.35 + 1.1 * fbm1d(L, 45, 3, s0 + 2), 0, 1) + 0.6 * np.abs(fbm1d(L, 3, 2, s0 + 3))+ o, rr = off[along], rw[along]+ paper *= np.clip(inward - o + 0.5, 0, 1)+ printed *= np.clip((inward - o - rr) / 1.3 + 0.5, 0, 1)+ if fibres:+ for t in r.uniform(0, L, int(L / 9)):+ ti = int(t); ln = r.uniform(1.5, 6.5); ang = r.uniform(-1.0, 1.0)+ base = off[min(ti, L - 1)] + 0.8+ if side == 't': p0 = (t, base); dv = (np.sin(ang), -np.cos(ang))+ elif side == 'b': p0 = (t, h - 1 - base); dv = (np.sin(ang), np.cos(ang))+ elif side == 'l': p0 = (base, t); dv = (-np.cos(ang), np.sin(ang))+ else: p0 = (w - 1 - base, t); dv = (np.cos(ang), np.sin(ang))+ fib_paths.append([p0, (p0[0] + dv[0] * ln, p0[1] + dv[1] * ln)])+ else:+ nk = int(r.integers(1, 4))+ kx = np.concatenate([[0], np.sort(r.uniform(0.15, 0.85, nk)) * L, [L - 1]])+ ky = r.uniform(0.6, 2.4, len(kx))+ o = np.interp(np.arange(L), kx, ky).astype(np.float32)[along]+ paper *= np.clip(inward - o + 0.5, 0, 1)+ printed *= np.clip(inward - o + 0.5, 0, 1)+ rimA = np.clip(paper - printed, 0, 1)+ corecol = self.core * (0.965 + 0.06 * self.tooth)[..., None]+ self.rgb = self.rgb * (1 - rimA[..., None]) + corecol * rimA[..., None]+ self.mask = self.mask * paper+ if fib_paths:+ fm = lines_mask(h, w, fib_paths, 0.8) * 0.75 * (1 - paper)+ self.rgb = self.rgb * (1 - fm[..., None]) + corecol * fm[..., None]+ self.mask = np.maximum(self.mask, fm)+ return self++ def cut(self, pts, ss=3):+ """scissor-cut the sheet to a polygon (local coordinates)"""+ self.mask = self.mask * poly_mask(self.h, self.w, pts, ss)+ return self++ def cut_rect(self, inset=2.0, jitter=2.5, snip=0.0):+ """scissor-cut a slightly crooked quadrilateral (corners jittered); snip: chance to snip each corner off"""+ r = self.rng+ w, h = self.w, self.h+ cs = [(inset, inset), (w - 1 - inset, inset), (w - 1 - inset, h - 1 - inset), (inset, h - 1 - inset)]+ pts = []+ for i, (x, y) in enumerate(cs):+ jx, jy = r.uniform(0, jitter), r.uniform(0, jitter)+ x = x + (jx if i in (0, 3) else -jx); y = y + (jy if i in (0, 1) else -jy)+ if r.random() < snip:+ k = r.uniform(5, 12)+ dx = k if i in (0, 3) else -k; dy = k * r.uniform(0.6, 1.4) if i in (0, 1) else -k * r.uniform(0.6, 1.4)+ pts += [(x, y + dy), (x + dx, y)] if i in (0, 2) else [(x + dx, y), (x, y + dy)]+ else:+ pts.append((x, y))+ return self.cut(pts)++ def cutout(self, margin=12.0, centre=None, tol=1.6, nicks=2, obj=None, wander=0.45):+ """cut round the object silhouette (self.obj, or `obj`) at `margin` px, the way scissors do: a chain of short+ straight cuts that bridges narrow gaps, the margin wandering wider and tighter (never into the object),+ plus a nick or two where the blade overshot"""+ obj = self.obj if obj is None else obj+ h, w = self.h, self.w+ sig = max(1.0, margin / 2.1)+ dil = blur(obj, sig) > 0.03+ dil = blur(dil.astype(np.float32), 1.0)+ if centre is None:+ ys, xs = np.nonzero(obj > 0.5)+ centre = (xs.mean(), ys.mean())+ cx, cy = centre+ N = 900+ th = np.linspace(0, 2 * np.pi, N, endpoint=False)+ R = np.arange(0, np.hypot(w, h), 1.0)+ px = cx + np.cos(th)[:, None] * R[None, :]; py = cy + np.sin(th)[:, None] * R[None, :]+ ok = (px >= 0) & (py >= 0) & (px < w - 1) & (py < h - 1)+ val = np.zeros(px.shape, np.float32)+ val[ok] = dil[py[ok].astype(int), px[ok].astype(int)]+ inside = val > 0.5+ last = np.where(inside.any(1), R.size - 1 - np.argmax(inside[:, ::-1], 1), 0).astype(np.float32)+ rad = np.maximum.reduce([np.roll(last, k) for k in range(-3, 4)]) # keep thin bits+ rad = np.convolve(np.concatenate([rad[-4:], rad, rad[:4]]), np.ones(9) / 9, 'same')[4:-4]+ if wander: # the hand drifts closer and further+ ov = np.zeros(px.shape, np.float32)+ ov[ok] = obj[py[ok].astype(int), px[ok].astype(int)]+ oin = ov > 0.3+ orad = np.where(oin.any(1), R.size - 1 - np.argmax(oin[:, ::-1], 1), 0).astype(np.float32)+ orad = np.maximum.reduce([np.roll(orad, k) for k in range(-6, 7)])+ ph = self.rng.uniform(0, 2 * np.pi, 3)+ wob = sum(np.sin(th * f + p) / f ** 0.5 for f, p in zip((2, 3, 5), ph)) / 1.9+ rad = np.maximum(rad + margin * wander * wob, orad + 2.5)+ P = np.stack([cx + np.cos(th) * rad, cy + np.sin(th) * rad], 1)+ k = int(np.argmin(P[:, 1]))+ P = np.vstack([P[k:], P[:k + 1]])+ j = int(np.argmax(np.hypot(P[:, 0] - P[0, 0], P[:, 1] - P[0, 1]))) # closed: simplify two open halves+ Q = np.vstack([_dp(P[:j + 1], tol)[:-1], _dp(P[j:], tol)[:-1]])+ r = self.rng+ Q = Q + r.normal(0, 0.5, Q.shape)+ pts = [tuple(q) for q in Q]+ for _ in range(nicks):+ i = int(r.integers(0, len(pts)))+ a, b = np.array(pts[i]), np.array(pts[(i + 1) % len(pts)])+ if np.hypot(*(b - a)) < 30: continue+ t = r.uniform(0.3, 0.7); m = a + (b - a) * t+ dvec = (b - a) / np.hypot(*(b - a)); nrm = np.array([dvec[1], -dvec[0]])+ inw = np.array([cx, cy]) - m; nrm = nrm if nrm @ inw > 0 else -nrm+ dep = r.uniform(4, 8)+ pts[i + 1:i + 1] = [tuple(m - dvec * 1.2), tuple(m + nrm * dep), tuple(m + dvec * 0.6)]+ self.mask = self.mask * poly_mask(h, w, pts)+ self.outline = pts+ return self++ def split(self, p0, p1, kinks=3, jag=3.0):+ """cut the sheet in two with scissors along p0 -> p1 (a few short straight cuts); returns (left, right),+ left being the part to the left of the direction of the cut"""+ r = self.rng+ p0, p1 = np.array(p0, np.float32), np.array(p1, np.float32)+ d = p1 - p0; L = np.hypot(*d); d /= L; nrm = np.array([d[1], -d[0]]) # nrm points to the left (screen)+ ts = np.concatenate([[0], np.sort(r.uniform(0.1, 0.9, kinks)), [1]])+ pts = [p0 + d * t * L + nrm * (r.uniform(-jag, jag) if 0 < t < 1 else 0) for t in ts]+ far = 4 * (self.w + self.h)+ poly = [pts[0] - d * far] + pts + [pts[-1] + d * far, pts[-1] + d * far + nrm * far, pts[0] - d * far + nrm * far]+ mL = poly_mask(self.h, self.w, poly)+ a, b = self.copy(), self.copy()+ a.mask = self.mask * mL; b.mask = self.mask * (1 - mL)+ return a, b++ # ------------------------------------------------------------ ageing and glue+ def age(self, amount=1.0, foxing=6, yellow='#c9a85a'):+ """yellowing toward the edges, a few foxing spots"""+ X, Y = self.XX, self.YY+ e = np.minimum.reduce([X, Y, self.w - 1 - X, self.h - 1 - Y])+ n = noise2d(self.h, self.w, 90, 3, self._seed())+ yl = amount * (0.16 * np.exp(-e / 45) + 0.06 * n)+ self.rgb *= 1 - yl[..., None] * (1 - _c(yellow))+ r = self.rng+ for _ in range(int(foxing * amount)):+ cx, cy, rr = r.uniform(0, self.w), r.uniform(0, self.h), r.uniform(2, 9)+ d = np.hypot(X - cx, Y - cy)+ if d.min() > rr * 3: continue+ k = np.exp(-(d / rr) ** 2) * r.uniform(0.08, 0.2) * (0.7 + 0.6 * self.tooth)+ self.rgb *= 1 - k[..., None] * (1 - _c('#8b5a2b'))+ return self++ def wrinkle(self, amount=1.0, scale=70, light=(-0.5, -0.7, 0.5)):+ """glue ripples: the wet paste stretched the paper; shade a soft ridged height field with the room light"""+ n1 = noise2d(self.h, self.w, scale, 3, self._seed())+ n2 = noise2d(self.h, self.w, scale * 0.45, 2, self._seed())+ ridge = (1 - np.abs(2 * n1 - 1)) ** 4+ hm = (ridge * 3.0 + n2 * 2.0) * amount+ N = height_normals(blur(hm, 1.5))+ L = np.asarray(light, np.float32); L /= np.linalg.norm(L)+ sh = (N @ L) / L[2]+ self.rgb *= np.clip(1 + 0.5 * (sh - 1), 0.8, 1.15)[..., None]+ return self+++# ================================================================ a studio photograph, as a height field+class Photo:+ """a black-and-white studio still life, built as a height field with material maps and lit, before printing.+ Primitives stack front to back in call order; z is the height a part sits at, height its own thickness.+ albedo 0..1 (paint / brass / steel brightness), metal 0..1 (reflects the studio instead of scattering light),+ gloss 0..1 (a varnish highlight on non-metals). Everything drawn becomes part of the object silhouette `obj`."""++ def __init__(self, w, h, seed=0, backdrop=(0.95, 0.8), light=(-0.55, -0.62, 0.56), lift=34):+ self.w, self.h = int(w), int(h)+ self.rng = np.random.default_rng(seed)+ self.YY, self.XX = np.mgrid[0:self.h, 0:self.w].astype(np.float32)+ self.hmap = np.zeros((self.h, self.w), np.float32)+ self.alb = np.zeros((self.h, self.w), np.float32)+ self.metal = np.zeros((self.h, self.w), np.float32)+ self.gloss = np.zeros((self.h, self.w), np.float32)+ self.obj = np.zeros((self.h, self.w), np.float32)+ self.extra = np.zeros((self.h, self.w), np.float32)+ self.L = np.asarray(light, np.float32) / np.linalg.norm(light)+ g = np.clip(self.XX / self.w * 0.4 + self.YY / self.h * 0.6, 0, 1)+ self.backdrop = backdrop[0] + (backdrop[1] - backdrop[0]) * g+ self.lift = lift++ def _box(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.w, int(np.ceil(x1)) + 1), min(self.h, int(np.ceil(y1)) + 1)+ if x1 <= x0 or y1 <= y0: return None, None, None+ sl = (slice(y0, y1), slice(x0, x1))+ return sl, self.XX[sl], self.YY[sl]++ def _part(self, sl, m, hgt, albedo, metal, gloss):+ m = np.clip(m, 0, 1)+ self.hmap[sl] = self.hmap[sl] * (1 - m) + hgt * m+ self.alb[sl] = self.alb[sl] * (1 - m) + albedo * m+ self.metal[sl] = self.metal[sl] * (1 - m) + metal * m+ self.gloss[sl] = self.gloss[sl] * (1 - m) + gloss * m+ self.obj[sl] = np.maximum(self.obj[sl], m)++ @staticmethod+ def _bevel(e, bevel):+ t = np.clip(e / max(bevel, 1e-3), 0, 1)+ return np.sqrt(1 - (1 - t) ** 2)++ # ------------------------------------------------------------ primitives+ def disc(self, cx, cy, r, z=0.0, height=8.0, bevel=3.0, albedo=0.8, metal=0.0, gloss=0.3, hole=0.0, turned=0.0):+ """a flat round part with a rounded edge (dial, plate, washer if hole > 0); turned: lathe rings"""+ sl, X, Y = self._box(cx - r - 2, cy - r - 2, cx + r + 2, cy + r + 2)+ if sl is None: return None+ d = np.hypot(X - cx, Y - cy)+ e = r - d+ if hole: e = np.minimum(e, d - hole)+ m = np.clip(e + 0.5, 0, 1)+ alb = albedo * (1 + turned * 0.08 * np.sin(d * 1.7)) if turned else albedo+ self._part(sl, m, z + height * self._bevel(e, bevel), alb, metal, gloss)+ return sl, m++ def dome(self, cx, cy, rx, ry=None, z=0.0, height=None, rot=0.0, cut=None, albedo=0.8, metal=0.0, gloss=0.3):+ """an elliptical cap (bell, knob, ball); cut keeps only local v < cut * ry (a dome sliced by a chord)"""+ ry = rx if ry is None else ry+ R = max(rx, ry) + 2+ sl, X, Y = self._box(cx - R, cy - R, cx + R, cy + R)+ if sl is None: return None+ t = np.deg2rad(rot); dx, dy = X - cx, Y - cy+ u = dx * np.cos(t) - dy * np.sin(t); v = dx * np.sin(t) + dy * np.cos(t)+ q = (u / rx) ** 2 + (v / ry) ** 2+ m = np.clip((1 - np.sqrt(q)) * min(rx, ry) + 0.5, 0, 1)+ if cut is not None: m = m * np.clip(cut * ry - v + 0.5, 0, 1)+ hh = min(rx, ry) * 0.8 if height is None else height+ self._part(sl, m, z + hh * np.sqrt(np.clip(1 - q, 0, 1)), albedo, metal, gloss)+ return sl, m++ def ring(self, cx, cy, r0, r1, z=0.0, height=None, albedo=0.8, metal=1.0, gloss=0.3):+ """a torus-like ring (bezel, rim)"""+ sl, X, Y = self._box(cx - r1 - 2, cy - r1 - 2, cx + r1 + 2, cy + r1 + 2)+ if sl is None: return None+ d = np.hypot(X - cx, Y - cy)+ rm, hw = (r0 + r1) / 2, (r1 - r0) / 2+ q = (d - rm) / hw+ m = np.clip(hw - np.abs(d - rm) + 0.5, 0, 1)+ self._part(sl, m, z + (hw if height is None else height) * np.sqrt(np.clip(1 - q * q, 0, 1)), albedo, metal, gloss)+ return sl, m++ def rod(self, p0, p1, r, z=0.0, albedo=0.8, metal=1.0, gloss=0.3):+ """a round bar between two points (legs, posts, arbors)"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ sl, X, Y = self._box(min(p0[0], p1[0]) - r - 2, min(p0[1], p1[1]) - r - 2, max(p0[0], p1[0]) + r + 2, max(p0[1], p1[1]) + r + 2)+ if sl is None: return None+ ab = p1 - p0; l2 = float(ab @ ab) + 1e-6+ t = np.clip(((X - p0[0]) * ab[0] + (Y - p0[1]) * ab[1]) / l2, 0, 1)+ d = np.hypot(X - p0[0] - t * ab[0], Y - p0[1] - t * ab[1])+ m = np.clip(r - d + 0.5, 0, 1)+ self._part(sl, m, z + r * np.sqrt(np.clip(1 - (d / r) ** 2, 0, 1)), albedo, metal, gloss)+ return sl, m++ def poly(self, pts, z=0.0, height=5.0, bevel=2.5, albedo=0.15, metal=0.3, gloss=0.4):+ """a flat part cut to a polygon (clock hands, levers, key wings), edges rounded over `bevel` px"""+ P = np.asarray(pts, np.float32)+ pad = bevel * 3 + 3+ sl, X, Y = self._box(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)+ if sl is None: return None+ x0, y0 = sl[1].start, sl[0].start+ m = poly_mask(X.shape[0], X.shape[1], P - [x0, y0])+ prof = np.sqrt(np.clip((blur(m, bevel * 0.7) - 0.5) * 2, 0, 1))+ self._part(sl, m, z + height * prof, albedo, metal, gloss)+ return sl, m++ def gear(self, cx, cy, r, teeth=30, z=0.0, height=9.0, depth=None, spokes=5, hub=None, rim=None, rot=0.0,+ albedo=0.86, metal=0.35, gloss=0.5, pinion=None, bevel=2.5, turned=1.0):+ """a clock wheel: trapezoid teeth, a flat rim, `spokes` crossings with windows between them (the backdrop+ shows through), a raised hub, and optionally a steel pinion (leaves) and arbor in the middle"""+ depth = float(np.clip(r * 0.09, 3.5, 14)) if depth is None else depth+ sl, X, Y = self._box(cx - r - 3, cy - r - 3, cx + r + 3, cy + r + 3)+ if sl is None: return None+ dx, dy = X - cx, Y - cy+ d = np.hypot(dx, dy)+ th = np.arctan2(dy, dx) + np.deg2rad(rot)+ ph = (th * teeth / (2 * np.pi)) % 1.0+ tooth = smoothstep(0.06, 0.2, ph) * (1 - smoothstep(0.46, 0.6, ph))+ Rr = r - depth * (1 - tooth)+ m = np.clip(Rr - d + 0.5, 0, 1)+ hub = r * 0.2 if hub is None else hub+ rim = max(4.0, r * 0.11) if rim is None else rim+ if spokes:+ r_in, r_out = hub + 2, r - depth - rim+ sw = max(2.5, r * 0.055)+ ang = th * spokes / (2 * np.pi)+ dth = (ang - np.round(ang)) * 2 * np.pi / spokes+ perp = np.abs(d * np.sin(dth))+ win = np.clip(d - r_in + 0.5, 0, 1) * np.clip(r_out - d + 0.5, 0, 1) * np.clip(perp - sw + 0.5, 0, 1) * (np.cos(dth) > 0)+ m = m * (1 - win)+ prof = np.sqrt(np.clip((blur(m, bevel * 0.7) - 0.5) * 2, 0, 1))+ # circular graining from the lathe: fine rings, and the bow-tie sheen of turned metal across the light+ az = np.arctan2(-self.L[1], -self.L[0])+ bow = np.cos(2 * (np.arctan2(dy, dx) - az - np.pi / 2))+ alb = albedo * (1 + turned * (0.06 * np.sin(d * 1.3 + 0.8 * np.sin(th * 3)) + 0.28 * bow * smoothstep(hub, hub + 12, d)))+ hb = np.clip(hub - d + 0.5, 0, 1)+ hgt = z + height * prof + hb * height * 0.35+ self._part(sl, m, hgt, alb, metal, gloss)+ if pinion:+ self.gear(cx, cy, pinion, teeth=max(6, int(pinion / 3)), z=z + height, height=height * 1.2, depth=pinion * 0.3,+ spokes=0, hub=0, rot=rot * 1.7, albedo=albedo * 0.72, metal=0.85, gloss=0.5, turned=0)+ self.disc(cx, cy, pinion * 0.34, z=z + height * 2.2, height=4, bevel=2, albedo=0.42, metal=0.9, gloss=0.5)+ return sl, m++ def spiral(self, cx, cy, r0, r1, turns=6, width=5.0, z=0.0, height=None, rot=0.0, albedo=0.45, metal=0.8, gloss=0.5,+ flare=1.0):+ """a coiled flat spring (mainspring, hairspring): a spiral ribbon from r0 to r1. flare > 1 packs the inner+ coils tight and lets the outer ones open up (a mainspring let down), so it reads as a spiral, not rings"""+ sl, X, Y = self._box(cx - r1 - width, cy - r1 - width, cx + r1 + width, cy + r1 + width)+ if sl is None: return None+ dx, dy = X - cx, Y - cy+ d = np.hypot(dx, dy)+ f = ((np.arctan2(dy, dx) + np.deg2rad(rot)) / (2 * np.pi)) % 1.0+ dd = np.full(d.shape, 1e9, np.float32)+ for k in range(int(np.ceil(turns)) + 1):+ ph = (f + k) / turns+ rs = r0 + (r1 - r0) * np.clip(ph, 0, 1) ** flare+ dd = np.where((ph <= 1) & (np.abs(d - rs) < dd), np.abs(d - rs), dd)+ hw = width / 2+ m = np.clip(hw - dd + 0.5, 0, 1)+ self._part(sl, m, z + (hw if height is None else height) * np.sqrt(np.clip(1 - (dd / hw) ** 2, 0, 1)), albedo, metal, gloss)+ return sl, m++ def screw(self, x, y, length, r, rot=0.0, z=0.0, pitch=None, albedo=0.62, metal=0.85, gloss=0.4):+ """a screw seen from the side, head at (x, y), shank running along rot (degrees, counter-clockwise):+ a cheese head with its slot, slanted threads, a pointed tip"""+ pitch = r * 0.75 if pitch is None else pitch+ t = np.deg2rad(rot)+ R = length + r * 2+ sl, X, Y = self._box(x - R, y - R, x + R, y + R)+ if sl is None: return None+ dx, dy = X - x, Y - y+ u = dx * np.cos(t) - dy * np.sin(t)+ v = dx * np.sin(t) + dy * np.cos(t)+ hl, hr = r * 1.4, r * 1.9+ head = np.clip(u + 0.5, 0, 1) * np.clip(hl - u + 0.5, 0, 1) * np.clip(hr - np.abs(v) + 0.5, 0, 1)+ slot = np.clip(r * 0.6 - u + 0.5, 0, 1) * np.clip(r * 0.28 - np.abs(v) + 0.5, 0, 1)+ head = head * (1 - slot)+ ph = (u + 0.4 * v) / pitch+ thread = 1 - 2 * np.abs(ph - np.floor(ph) - 0.5)+ tip = np.clip((length - u) / (r * 1.6), 0, 1)+ re = r * (0.8 + 0.2 * thread) * tip+ shank = np.clip(u - hl + 0.5, 0, 1) * np.clip(length - u + 0.5, 0, 1) * np.clip(re - np.abs(v) + 0.5, 0, 1)+ hh = np.where(head > 0, hr * 0.55 * np.sqrt(np.clip(1 - (v / hr) ** 2, 0, 1)) + 2, re * np.sqrt(np.clip(1 - (v / np.maximum(re, 1e-3)) ** 2, 0, 1)))+ m = np.maximum(head, shank)+ self._part(sl, m, z + hh, albedo, metal, gloss)+ return sl, m++ # ------------------------------------------------------------ printed marks, reflections+ def mark(self, m, tone=0.08, sl=None):+ """paint / print on a surface (dial numerals, ticks): changes albedo only"""+ sl = sl or (slice(0, self.h), slice(0, self.w))+ m = np.clip(m, 0, 1)+ self.alb[sl] = self.alb[sl] * (1 - m) + tone * m+ self.gloss[sl] = self.gloss[sl] * (1 - m * 0.5)++ def text(self, s, x, y, size, font='didone', tone=0.08, anchor='mm', rot=0.0, spacing=0.0):+ self.mark(text_mask(self.h, self.w, s, x, y, size, font, anchor, spacing, rot), tone)++ def lines(self, paths, width, tone=0.08):+ self.mark(lines_mask(self.h, self.w, paths, width), tone)++ def glare(self, cx, cy, r0, r1, a0, a1, strength=0.35, soft=6.0):+ """a reflection on glass: a soft crescent between radii r0..r1 and angles a0..a1 (degrees, screen)"""+ d = np.hypot(self.XX - cx, self.YY - cy)+ a = (np.rad2deg(np.arctan2(self.YY - cy, self.XX - cx)) - a0) % 360+ span = (a1 - a0) % 360+ ang = smoothstep(0, span * 0.3, a) * smoothstep(0, span * 0.3, span - a) * (a <= span)+ rad = smoothstep(r0 - soft, r0 + soft, d) * (1 - smoothstep(r1 - soft, r1 + soft, d))+ self.extra += ang * rad * strength++ # ------------------------------------------------------------ light it+ def develop(self, contrast=1.15, brightness=0.0, grain=0.03, soft=0.7, shadow=0.55, reach=170):+ """render the tone image (0 black .. 1 white): key light, chrome environment, cast shadows, occlusion"""+ H = self.hmap+ N = height_normals(H)+ nx, ny, nz = N[..., 0], N[..., 1], N[..., 2]+ L = self.L+ dif = np.clip(N @ L, 0, 1) / L[2]+ Hv = L + np.array([0, 0, 1], np.float32); Hv /= np.linalg.norm(Hv)+ spec = np.clip(N @ Hv, 0, 1)+ rx, ry, rz = 2 * nz * nx, 2 * nz * ny, 2 * nz * nz - 1+ Ls = np.array([-0.62, -0.72, 0.32], np.float32); Ls /= np.linalg.norm(Ls)+ box = smoothstep(0.62, 0.9, rx * Ls[0] + ry * Ls[1] + rz * Ls[2])+ sky = smoothstep(0.35, -0.55, ry)+ env = 0.08 + 0.42 * sky + 0.75 * box - 0.05 * smoothstep(-0.2, 0.6, ry)+ zmap = H + self.obj * self.lift+ sh = height_shadow(zmap, tuple(L), reach, 1.5, 2.0)+ ao = ambient_occlusion(H, (3, 9, 22), (3.0, 8.0, 18.0))+ a, mt, gl = self.alb, self.metal, self.gloss+ diff = a * (0.2 + 0.8 * dif * (1 - 0.75 * sh))+ met = a * (env * (1 - 0.5 * sh) + 0.15 * dif) + 0.95 * spec ** 80 * (1 - sh)+ tone_o = diff * (1 - mt) + met * mt + gl * 0.45 * spec ** 30 * (1 - sh)+ tone_o *= 1 - 0.55 * ao+ shb = blur(sh, 5)+ bd = self.backdrop * (1 - shadow * shb)+ t = bd * (1 - self.obj) + tone_o * self.obj + self.extra+ t = np.clip((t - 0.5) * contrast + 0.5 + brightness, 0, 1)+ if soft: t = blur(t, soft)+ if grain: t = t + grain * (noise2d(self.h, self.w, 1.5, 2, int(self.rng.integers(1 << 30))) - 0.5)+ return np.clip(t, 0, 1)+++# ================================================================ pseudo-text for newsprint+_ON = ['b', 'c', 'd', 'f', 'g', 'h', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'br', 'cl', 'dr', 'fr', 'gr', 'pl',+ 'pr', 'st', 'tr', 'th', 'sh', 'ch', 'qu', '', '']+_NU = ['a', 'e', 'i', 'o', 'u', 'a', 'e', 'o', 'ea', 'ou', 'ai', 'ie', 'y']+_CO = ['', '', '', 'n', 'r', 's', 't', 'l', 'm', 'nd', 'rt', 'st', 'ck', 'ng', 'x']+++class _Gib:+ """meaningless but word-shaped text (syllable soup) -- looks like a newspaper column, says nothing"""++ def __init__(self, rng):+ self.r = rng+ self.cap = True++ def word(self, syl=None):+ r = self.r+ n = syl or int(r.choice([1, 1, 1, 1, 1, 2, 2, 2, 3]))+ w = ''.join(str(r.choice(_ON)) + str(r.choice(_NU)) + str(r.choice(_CO)) for _ in range(n))+ return w or 'a'++ def next(self):+ r = self.r+ if r.random() < 0.035:+ w = str(int(r.integers(2, 1990)))+ else:+ w = self.word()+ if self.cap: w = w[0].upper() + w[1:]+ self.cap = False+ p = r.random()+ if p < 0.075: w += '.'; self.cap = True+ elif p < 0.14: w += ','+ return w++ def title(self, n):+ return ' '.join(self.word(int(self.r.integers(1, 4))).capitalize() for _ in range(n))+++# ================================================================ the collage+class NewsCollage:+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.5, -0.7, 0.5)):+ self.W, self.H = W, H+ self.rng = np.random.default_rng(seed)+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)+ self.L = np.asarray(light, np.float32) / np.linalg.norm(light)+ self.img = np.ones((H, W, 3), np.float32) * _c(KRAFT)+ self.hmap = np.zeros((H, W), np.float32)+ self.tooth = np.full((H, W), 0.5, np.float32)+ self._grain = (noise2d(H, W, 1.2, 2, self._seed()) - 0.5).astype(np.float32)+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ def _box(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))+ if x1 <= x0 or y1 <= y0: return None+ return (slice(y0, y1), slice(x0, x1))++ # ------------------------------------------------------------ board+ def board(self, colour=KRAFT, fibres=1.0):+ """kraft paper: cloudy pulp, short dark and pale fibres, bark flecks, fine grain"""+ H, W = self.H, self.W+ r = self.rng+ mott = noise2d(H, W, 320, 3, self._seed()); cl = noise2d(H, W, 45, 3, self._seed())+ g = blur(r.random((H, W)).astype(np.float32), 0.7)+ g = (g - g.mean()) / (g.std() + 1e-6)+ self.tooth = np.clip(0.5 + g / 5, 0, 1).astype(np.float32)+ base = _c(colour)[None, None, :] * (1 + 0.07 * (mott - 0.5) + 0.05 * (cl - 0.5) + 0.018 * g)[..., None]+ ss = 2+ layers = []+ for n, lo, hi, wd in [(int(11000 * fibres), 4, 20, 1), (int(6000 * fibres), 4, 16, 1)]:+ im = Image.new('L', (W * ss, H * ss), 0); d = ImageDraw.Draw(im)+ for _ in range(n):+ x, y = r.uniform(0, W * ss), r.uniform(0, H * ss)+ ln = r.uniform(lo, hi) * ss; a = r.uniform(0, np.pi); bend = r.uniform(-0.25, 0.25)+ pts = [(x + np.cos(a + bend * k) * ln * k / 3, y + np.sin(a + bend * k) * ln * k / 3) for k in range(4)]+ d.line(pts, fill=int(r.uniform(90, 255)), width=wd)+ layers.append(np.asarray(im.resize((W, H), Image.BOX), np.float32) / 255)+ dark, light = layers+ img = base * (1 - (dark * 0.2)[..., None] * (1 - _c('#5a3d1e')))+ img = img * (1 - (light * 0.22)[..., None]) + (light * 0.22)[..., None] * _c('#dcc29a')+ im = Image.new('L', (W, H), 0); d = ImageDraw.Draw(im)+ for _ in range(int(700 * fibres)):+ x, y = r.uniform(0, W), r.uniform(0, H); s = r.uniform(0.5, 1.8)+ d.ellipse([x - s, y - s * r.uniform(0.5, 1), x + s, y + s * r.uniform(0.5, 1)], fill=int(r.uniform(80, 230)))+ fl = blur(np.asarray(im, np.float32) / 255, 0.5)+ img = img * (1 - (fl * 0.55)[..., None] * (1 - _c('#3b2612')))+ self.img = img.astype(np.float32)+ self.hmap[:] = 0++ # ------------------------------------------------------------ sheets+ def sheet(self, w, h, colour=PAPER, core=None, kind='paper'):+ return Sheet(w, h, colour, self._seed(), core, kind)++ def newsprint(self, w, h, columns=3, size=11, headline=2, head_font='news_bold', picture=True, ad=True,+ colour=NEWS, ink=INK, margin=16, gutter=12, lead=1.24, folio=True, showthrough=0.045, age=1.0):+ """an old newspaper page (w x h px) full of generated pseudo-text: folio, kicker, headline, deck, justified+ columns with rules, subheads, a boxed ad, a halftone picture with caption. Returns a Sheet (tear it next)."""+ r = np.random.default_rng(self._seed())+ gib = _Gib(r)+ s = Sheet(w, h, colour, self._seed(), NEWS_CORE, 'news')+ im = Image.new('L', (w, h), 0); d = ImageDraw.Draw(im)+ fb, fbo, fi = font('news', size), font('news_bold', size), font('news_italic', size)+ extra = np.zeros((h, w), np.float32)+ y = margin+ W0 = w - 2 * margin+ if folio:+ fs = font('news_bold', size * 0.85)+ y += size+ left = f'No. {int(r.integers(100, 999))} · {gib.title(2).upper()}'+ d.text((margin, y), left, font=fs, fill=255, anchor='ls')+ d.text((w - margin, y), f'{gib.title(1).upper()} {int(r.integers(1, 28))}', font=fs, fill=255, anchor='rs')+ y += size * 0.55+ d.line([(margin, y), (w - margin, y)], fill=255, width=1)+ y += size * 0.9+ if headline:+ ks = font('news_bold', size * 0.95)+ y += size+ d.text((margin, y), ' '.join(gib.word(2).upper() for _ in range(2)), font=ks, fill=255, anchor='ls')+ y += size * 0.5+ hs = size * r.uniform(2.7, 3.3)+ fh = font(head_font, hs)+ for _ in range(int(headline)):+ y += hs * 0.98+ words, tot = [], 0.0+ while True:+ wd = gib.word(int(r.integers(1, 4))).capitalize()+ wl = fh.getlength(wd + ' ')+ if tot + wl > W0 * r.uniform(0.86, 1.0) and words: break+ words.append(wd); tot += wl+ d.text((margin, y), ' '.join(words), font=fh, fill=255, anchor='ls')+ y += size * 1.6+ fdk = font('news_italic', size * 1.3)+ deck = ' '.join(gib.word() for _ in range(40))+ while fdk.getlength(deck) > W0 * 0.95: deck = deck.rsplit(' ', 1)[0]+ d.text((margin, y), deck.capitalize(), font=fdk, fill=255, anchor='ls')+ y += size * 0.8+ d.line([(margin, y), (w - margin, y)], fill=255, width=2)+ d.line([(margin, y + 3), (w - margin, y + 3)], fill=255, width=1)+ y += size * 0.9+ colw = (W0 - (columns - 1) * gutter) / columns+ lh = size * lead+ sp = fb.getlength(' ')+ pic_col = int(r.integers(columns)) if picture else -1+ ad_col = int((pic_col + 1 + r.integers(max(1, columns - 1))) % columns) if ad else -1+ for c in range(columns):+ x0 = margin + c * (colw + gutter)+ yy = y + size+ if c == pic_col:+ ph = colw * r.uniform(0.62, 0.8)+ if yy + ph < h - margin - lh * 3:+ self._news_picture(extra, int(x0), int(yy - size * 0.8), int(colw), int(ph), r)+ yy += ph + size * 0.6+ cap = ' '.join(gib.word() for _ in range(12))+ while fi.getlength(cap) > colw: cap = cap.rsplit(' ', 1)[0]+ d.text((x0, yy), cap.capitalize(), font=fi, fill=255, anchor='ls')+ yy += lh * 1.5+ ad_at = r.uniform(0.3, 0.6) * h if c == ad_col else 1e9+ first = True+ while yy + lh * 0.3 <= h - margin:+ if yy > ad_at and yy + lh * 9 < h - margin:+ ad_at = 1e9+ bh = lh * r.integers(6, 9)+ top = yy - size+ d.rectangle([x0, top, x0 + colw, top + bh], outline=255, width=2)+ d.rectangle([x0 + 4, top + 4, x0 + colw - 4, top + bh - 4], outline=255, width=1)+ fa = font('news_bold', size * 2.1)+ word = gib.word(2).upper()+ while fa.getlength(word) > colw - 20 and len(word) > 3: word = word[:-1]+ d.text((x0 + colw / 2, top + bh * 0.45), word, font=fa, fill=255, anchor='ms')+ for k in range(2):+ ln = ' '.join(gib.word() for _ in range(8))+ while fb.getlength(ln) > colw - 24: ln = ln.rsplit(' ', 1)[0]+ d.text((x0 + colw / 2, top + bh * 0.45 + lh * (1.3 + k)), ln, font=fb, fill=255, anchor='ms')+ yy += bh + lh * 0.4+ continue+ if not first and r.random() < 0.09:+ sub = gib.title(int(r.integers(2, 4))).upper()+ while fbo.getlength(sub) > colw: sub = sub.rsplit(' ', 1)[0]+ yy += lh * 0.35+ d.text((x0 + colw / 2, yy), sub, font=fbo, fill=255, anchor='ms')+ yy += lh * 1.15+ continue+ first = False+ n = int(r.integers(3, 13))+ for i in range(n):+ if yy > h - margin: break+ last = i == n - 1+ ind = size * 1.3 if i == 0 else 0+ avail = colw - ind+ if last: avail *= r.uniform(0.25, 0.85)+ words, tot = [], 0.0+ while True:+ wd = gib.next(); wl = fb.getlength(wd)+ if tot + wl + len(words) * sp > avail and words: break+ words.append((wd, wl)); tot += wl+ gap = sp if (last or len(words) < 2) else (colw - ind - tot) / (len(words) - 1)+ xx = x0 + ind+ for wd, wl in words:+ d.text((xx, yy), wd, font=fb, fill=255, anchor='ls'); xx += wl + gap+ yy += lh+ yy += lh * 0.15+ if c < columns - 1:+ xr = x0 + colw + gutter / 2+ d.line([(xr, y), (xr, h - margin)], fill=200, width=1)+ m = np.maximum(np.asarray(im, np.float32) / 255, extra)+ if showthrough:+ back = shift(blur(m[:, ::-1].copy(), 1.4), 3, 5)+ s.ink(back, '#6d6454', showthrough, spread=0, mottle=0.3)+ s.ink(m, ink, 0.9, spread=0.3, mottle=0.22)+ if age: s.age(age)+ return s++ def _news_picture(self, extra, x0, y0, pw, ph, r):+ """a small halftone news photograph: an abstract street or landscape, screened coarse"""+ Y, X = np.mgrid[0:ph, 0:pw].astype(np.float32)+ hz = ph * r.uniform(0.45, 0.65)+ t = 0.82 - 0.2 * Y / ph+ t = np.where(Y > hz, 0.5 - 0.15 * (Y - hz) / ph, t)+ for _ in range(int(r.integers(3, 7))):+ bx, bw = r.uniform(0, pw), r.uniform(pw * 0.08, pw * 0.25)+ bh = r.uniform(ph * 0.15, ph * 0.5)+ m = np.clip(bw / 2 - np.abs(X - bx) + 0.5, 0, 1) * np.clip(Y - (hz - bh) + 0.5, 0, 1) * (Y < hz + 4)+ t = t * (1 - m) + r.uniform(0.18, 0.4) * m+ for _ in range(int(r.integers(2, 5))):+ bx, by, rr = r.uniform(0, pw), hz + r.uniform(-5, 10), r.uniform(pw * 0.05, pw * 0.14)+ m = np.clip(rr - np.hypot(X - bx, (Y - by) * 1.3) + 0.5, 0, 1)+ t = t * (1 - m) + 0.15 * m+ t = np.clip(blur(t, 1.4) + 0.08 * (noise2d(ph, pw, 6, 2, int(r.integers(1 << 30))) - 0.5), 0, 1)+ ink = halftone(t, 3.4, 45, 0.1, int(r.integers(1 << 30)), 0.35)+ ink[:1, :] = 1; ink[-1:, :] = 1; ink[:, :1] = 1; ink[:, -1:] = 1+ H, W = extra.shape+ ys, xs = slice(max(0, y0), min(H, y0 + ph)), slice(max(0, x0), min(W, x0 + pw))+ extra[ys, xs] = np.maximum(extra[ys, xs], ink[ys.start - y0:ys.stop - y0, xs.start - x0:xs.stop - x0])++ def print_photo(self, photo, cell=6.5, angle=45.0, ink=INK, paper=PAPER, rough=0.08, gain=0.5, alpha=0.93, **develop):+ """develop a Photo and print it as a halftone on magazine paper; the Sheet remembers the object silhouette+ (so .cutout() can follow it)"""+ tone = photo.develop(**develop)+ s = Sheet(photo.w, photo.h, paper, self._seed(), PAPER_CORE, 'photo')+ s.ink(halftone(tone, cell, angle, rough, self._seed(), gain), ink, alpha, spread=0, mottle=0.12)+ s.obj = photo.obj.copy()+ return s++ # ------------------------------------------------------------ gluing things down+ def _composite(self, rgbp, a, ox, oy, lift=1.0, shadow=0.34, thickness=1.0, edge=True, tint='#2b1a0b'):+ """rgbp: premultiplied colour, a: coverage (both already rotated); top-left at canvas (ox, oy)"""+ h, w = a.shape+ L2 = -self.L[:2] / (np.linalg.norm(self.L[:2]) + 1e-6)+ dist, soft = 1.5 + 6.5 * lift, 1.0 + 6.0 * lift+ pad = int(dist + 3 * soft + 4)+ sl = self._box(ox - pad, oy - pad, ox + w + pad, oy + h + pad)+ if sl is None: return+ rh, rw = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start+ ax, ay = ox - sl[1].start, oy - sl[0].start+ A = np.zeros((rh, rw), np.float32); C = np.zeros((rh, rw, 3), np.float32)+ ys0, xs0 = max(0, -ay), max(0, -ax)+ ys1, xs1 = min(h, rh - ay), min(w, rw - ax)+ if ys1 <= ys0 or xs1 <= xs0: return+ A[ay + ys0:ay + ys1, ax + xs0:ax + xs1] = a[ys0:ys1, xs0:xs1]+ C[ay + ys0:ay + ys1, ax + xs0:ax + xs1] = rgbp[ys0:ys1, xs0:xs1]+ if shadow:+ con = blur(shift(A, L2[0] * 1.3, L2[1] * 1.3), 1.1)+ drop = blur(shift(A, L2[0] * dist, L2[1] * dist), soft)+ sh = np.clip(con * 0.3 + drop * shadow, 0, 0.9)+ self.img[sl] *= 1 - sh[..., None] * (1 - _c(tint))+ if edge:+ tl = np.clip(A - shift(A, 1, 1), 0, 1)+ br = np.clip(A - shift(A, -1, -1), 0, 1)+ C = C * (1 - 0.14 * br)[..., None] + (tl * 0.07)[..., None] * A[..., None]+ self.img[sl] = self.img[sl] * (1 - A[..., None]) + C+ self.hmap[sl] += A * thickness++ @staticmethod+ def _rotate(arrs, rot, pad=4):+ out = []+ for arr in arrs:+ arr = np.pad(arr, pad)+ if rot:+ arr = np.asarray(Image.fromarray(arr.astype(np.float32), 'F').rotate(rot, resample=Image.BICUBIC, expand=True), np.float32)+ out.append(arr)+ return out++ def paste(self, sheet, cx, cy, rot=0.0, lift=1.0, shadow=0.34, edge=True):+ """glue a Sheet with its centre at (cx, cy), rotated `rot` degrees; returns a Frame for writing on it"""+ m = np.clip(sheet.mask, 0, 1)+ chans = self._rotate([m] + [sheet.rgb[..., k] * m for k in range(3)], rot)+ a = np.clip(chans[0], 0, 1)+ rgbp = np.clip(np.stack(chans[1:], -1), 0, 1) * (a > 0)[..., None]+ rgbp = np.minimum(rgbp, a[..., None])+ h, w = a.shape+ self._composite(rgbp, a, int(round(cx - w / 2)), int(round(cy - h / 2)), lift, shadow, edge=edge)+ return Frame(cx, cy, sheet.w, sheet.h, rot)++ def disc(self, cx, cy, r, colour=RED, lift=0.9, shadow=0.34, facets=None):+ """a disc cut from dyed paper with scissors: many short straight cuts, never a perfect circle"""+ rr = self.rng+ s = Sheet(2 * r + 14, 2 * r + 14, colour, self._seed(), None, 'colour')+ n = facets or max(16, int(2 * np.pi * r / 30))+ th = np.sort((np.arange(n) + rr.uniform(-0.3, 0.3, n)) / n * 2 * np.pi)+ wob = fbm1d(n + 1, 8, 2, self._seed())[:n]+ rad = r * (1 + 0.006 * wob) + rr.normal(0, 0.9, n)+ c0 = r + 7+ s.cut(list(zip(c0 + np.cos(th) * rad, c0 + np.sin(th) * rad)))+ n1 = noise2d(s.h, s.w, 25, 3, self._seed())+ s.rgb *= (1 + 0.05 * (n1 - 0.5))[..., None]+ return self.paste(s, cx, cy, 0.0, lift, shadow)++ # ------------------------------------------------------------ letters and labels+ CLIPPINGS = [ # (paper, printed block colour or None, glyph colour or 'knock' for reversed type, extra)+ (PAPER, None, INK, ''), (PAPER, RED, 'knock', ''), (PAPER, BLACK, 'knock', ''), (NEWS, None, INK, 'text'),+ (PAPER, None, RED, ''), ('#e9c46a', None, INK, ''), (NEWS, None, INK, 'tint'), ('#ece3cf', None, RED, 'text'),+ ]+ CJK_FACES = ['cjk_song', 'cjk_hei', 'cjk_kai', 'cjk_round']+ LATIN_FACES = ['didone', 'slab', 'poster', 'serif_bold', 'futura', 'typewriter_bold', 'clarendon', 'grotesk']++ def clipping(self, ch, size, face, paper=PAPER, block=None, fg=INK, extra='', pad=None):+ """one ransom-note letter: a character cut out of a magazine page (returns a Sheet, not yet pasted)"""+ r = self.rng+ f = font(face, size)+ x0, y0, x1, y1 = f.getbbox(ch, anchor='ls')+ gw, gh = x1 - x0, y1 - y0+ px = size * (r.uniform(0.08, 0.2) if pad is None else pad)+ py = size * (r.uniform(0.07, 0.16) if pad is None else pad * 0.8)+ w, h = int(gw + 2 * px + 6), int(gh + 2 * py + 6)+ s = Sheet(w, h, paper, self._seed(), PAPER_CORE, 'clipping')+ bx, by = (w - gw) / 2 - x0, (h - gh) / 2 - y0+ m = text_mask(h, w, ch, bx, by, size, face, 'ls')+ if extra == 'text': # neighbouring text on the page+ gib = _Gib(r); fs = font('news', max(7, size * 0.075)); im = Image.new('L', (w, h), 0); d = ImageDraw.Draw(im)+ for yy in np.arange(size * 0.08, h + 4, max(8.5, size * 0.095)):+ d.text((2 - r.uniform(0, 20), yy), ' '.join(gib.next() for _ in range(12)), font=fs, fill=255, anchor='ls')+ bg = np.asarray(im, np.float32) / 255 * (1 - np.clip(blur(m, size * 0.06) * 4, 0, 1))+ s.ink(bg, INK, 0.62)+ if extra == 'tint': # a grey halftone tint behind the letter+ s.ink(halftone(np.full((h, w), 0.72, np.float32), 4.5, 45, 0.06, self._seed(), 0.3) * (1 - np.clip(blur(m, 1.5) * 2, 0, 1)), INK, 0.85)+ if block is not None:+ s.block(0, 0, w, h, block, minus=m if fg == 'knock' else None)+ if fg != 'knock':+ s.ink(m, fg, 0.96, spread=0.3)+ s.cut_rect(1.5, max(2.0, size * 0.035), snip=0.25)+ return s++ def ransom(self, text, x, y, size, rot=0.0, gap=0.05, bounce=0.07, tilt=7.0, scale=(0.86, 1.14), styles=None,+ faces=None, lift=0.7, seed=None):+ """ransom-note lettering: each character its own clipping (face, paper, ink), pasted along a baseline from+ (x, y) at angle rot. styles: list of CLIPPINGS tuples to cycle through; faces: list of font styles.+ Returns [(Frame, char)] so later tape or stamps can find the letters."""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ t = np.deg2rad(rot)+ ux, uy = np.cos(t), -np.sin(t)+ nx, ny = np.sin(t), np.cos(t)+ pos = 0.0+ out, last_style = [], None+ pool = list(styles or self.CLIPPINGS)+ for i, ch in enumerate(text):+ if ch == ' ':+ pos += size * 0.38; continue+ cjk = _is_cjk(ch)+ fl = faces[i % len(faces)] if faces else str(r.choice(self.CJK_FACES if cjk else self.LATIN_FACES))+ if styles:+ st = pool[i % len(pool)]+ else:+ st = pool[int(r.integers(len(pool)))]+ while st is last_style: st = pool[int(r.integers(len(pool)))]+ last_style = st+ sz = size * r.uniform(*scale) * (1.0 if cjk else 1.0)+ s = self.clipping(ch, sz, fl, *st)+ b = r.uniform(-bounce, bounce) * size+ cxl = pos + s.w / 2+ cx, cy = x + ux * cxl + nx * b, y + uy * cxl + ny * b - size * 0.35 * ny+ fr = self.paste(s, cx, cy, rot + r.uniform(-tilt, tilt), lift)+ out.append((fr, ch))+ pos += s.w * (1 + r.uniform(-0.04, 0.02)) + gap * size+ return out++ def label(self, text, x, y, size, face='typewriter', fg=INK, bg=PAPER, rot=0.0, pad=(0.55, 0.38), anchor='l',+ block=None, tear='', lift=0.6, spacing=0.0, weight=0.0):+ """a word or line of print on a scissor-cut strip (block: a printed colour field behind; fg 'knock' reverses+ the type out of the block); tear: sides to tear instead of cut. (x, y) is the strip's left end or centre."""+ tw = text_width(text, size, face, spacing)+ f = font(_runs(text, face)[0][1], size)+ ref = '中' if _is_cjk(text.strip()[0]) else 'H'+ capH = -f.getbbox(ref, anchor='ls')[1]+ w, h = tw + 2 * size * pad[0], capH + 2 * size * pad[1] + size * 0.15+ s = Sheet(w, h, bg, self._seed(), PAPER_CORE, 'label')+ m = s.text_mask(text, s.w / 2, s.h / 2 + capH / 2 - size * 0.02, size, face, 'ms', spacing, 0, weight)+ if block is not None:+ s.block(0, 0, s.w, s.h, block, minus=m if fg == 'knock' else None)+ if fg != 'knock':+ s.ink(m, fg, 0.95)+ if tear: s.tear(tear, depth=size * 0.12, rim=size * 0.1)+ if tear != 'tblr': s.cut_rect(1.0, 1.8)+ t = np.deg2rad(rot)+ cx = x + (s.w / 2 * np.cos(t) if anchor == 'l' else 0)+ cy = y - (s.w / 2 * np.sin(t) if anchor == 'l' else 0)+ return self.paste(s, cx, cy, rot, lift)++ # ------------------------------------------------------------ tape, stamps, pen+ def tape(self, cx, cy, length, rot=0.0, width=46, colour=TAPE, alpha=0.62):+ """masking tape: translucent crepe paper, fine crepe ridges across it, serrated torn ends; paper edges+ underneath show through as lit ridges"""+ r = self.rng+ w, h = int(length + 24), int(width + 12)+ Y, X = np.mgrid[0:h, 0:w].astype(np.float32)+ u, v = X - w / 2, Y - h / 2+ rows = np.arange(h)+ def end(sgn):+ zig = np.abs(((rows / r.uniform(3.2, 4.6)) % 2) - 1) * 2.2 + fbm1d(h, 4, 2, self._seed()) * 1.6+ return sgn * length / 2 + r.uniform(-0.2, 0.2) * (rows - h / 2) + zig * (-sgn)+ eL, eR = end(-1)[:, None], end(1)[:, None]+ m = np.clip(u - eL + 0.5, 0, 1) * np.clip(eR - u + 0.5, 0, 1) * np.clip(width / 2 - np.abs(v) + 0.5, 0, 1)+ crepe = fbm1d(w, 1.8, 2, self._seed())[None, :] + 0.5 * fbm1d(w, 9, 2, self._seed())[None, :]+ wr = noise2d(h, w, 40, 2, self._seed())+ edge = np.exp(-(width / 2 - np.abs(v)) / 1.6)+ shade = (1 + 0.04 * crepe + 0.04 * (wr - 0.5) - 0.07 * edge)+ a = m * alpha * (1 + 0.06 * crepe)+ chans = self._rotate([a] + [_c(colour)[k] * shade * a for k in range(3)], rot)+ A = np.clip(chans[0], 0, 1)+ C = np.clip(np.stack(chans[1:], -1), 0, 1)+ hh, ww = A.shape+ ox, oy = int(round(cx - ww / 2)), int(round(cy - hh / 2))+ sl = self._box(ox, oy, ox + ww, oy + hh)+ if sl is None: return+ ys, xs = slice(sl[0].start - oy, sl[0].stop - oy), slice(sl[1].start - ox, sl[1].stop - ox)+ A, C = A[ys, xs], C[ys, xs]+ hb = blur(self.hmap[sl], 1.3)+ gy, gx = np.gradient(hb)+ ridge = np.clip(-(gx * self.L[0] + gy * self.L[1]) * 1.6, -0.35, 0.35)+ L2 = -self.L[:2] / np.linalg.norm(self.L[:2])+ sh = blur(shift(A, L2[0] * 1.5, L2[1] * 1.5), 1.2) * 0.22+ self.img[sl] *= 1 - sh[..., None] * (1 - _c('#2b1a0b'))+ base = self.img[sl] * (1 - A[..., None] * 0.1)+ self.img[sl] = base * (1 - A[..., None]) + C + (A * ridge * 0.9)[..., None] * np.where(ridge[..., None] > 0, 1.0, 0.8)+ self.hmap[sl] += (A > 0.2) * 0.3++ def stamp(self, cx, cy, lines, rot=0.0, colour=RED, shape='box', face='slab', w=None, h=None, r=None, ring=None,+ ring_face='grotesk', ring_size=None, alpha=0.86, pressure=None):+ """a rubber stamp. lines: [(text, size), ...] stacked in the middle. shape 'box' (double border, w x h) or+ 'round' (radius r, `ring` text running round the rim). Ink is pressed unevenly and soaks into the paper."""+ rng = self.rng+ lines = [(t, 36) if isinstance(t, str) else t for t in lines]+ widths = [text_width(t, sz, face) for t, sz in lines]+ tot_h = sum(sz * 1.08 for _, sz in lines)+ if shape == 'box':+ w = w or max(widths) + 70+ h = h or tot_h + 50+ R = int(np.hypot(w, h) / 2 + 14)+ else:+ r = r or max(max(widths) / 2 + 44, 80)+ R = int(r + 14)+ S = 2 * R+ m = np.zeros((S, S), np.float32)+ im = Image.new('L', (S * 2, S * 2), 0); d = ImageDraw.Draw(im)+ c = R * 2+ if shape == 'box':+ d.rounded_rectangle([c - w, c - h, c + w, c + h], radius=10, outline=255, width=11)+ d.rounded_rectangle([c - w + 18, c - h + 18, c + w - 18, c + h - 18], radius=6, outline=255, width=4)+ else:+ d.ellipse([c - 2 * r, c - 2 * r, c + 2 * r, c + 2 * r], outline=255, width=10)+ ri = r * (0.66 if ring else 0.86)+ d.ellipse([c - 2 * ri, c - 2 * ri, c + 2 * ri, c + 2 * ri], outline=255, width=5)+ m = np.asarray(im.resize((S, S), Image.BOX), np.float32) / 255+ yy = R - tot_h / 2+ for t, sz in lines:+ yy += sz * 1.0+ m = np.maximum(m, text_mask(S, S, t, R, yy - sz * 0.08, sz, face, 'ms'))+ yy += sz * 0.08+ if shape == 'round' and ring:+ rs = ring_size or r * 0.2+ fr = font(ring_face, rs)+ rr = r * 0.83+ advs = [fr.getlength(ch) + rs * 0.12 for ch in ring]+ tot = sum(advs)+ span = min(tot / rr, 2 * np.pi * 0.96)+ a = -np.pi / 2 - span / 2+ for ch, adv in zip(ring, advs):+ aa = a + adv / 2 / rr * (span / (tot / rr))+ px, py = R + np.cos(aa) * rr, R + np.sin(aa) * rr+ m = np.maximum(m, text_mask(S, S, ch, px, py, rs, ring_face, 'mm', rot=-np.rad2deg(aa) - 90))+ a += adv / rr * (span / (tot / rr))+ # rubber: pressure gradient, voids, ink piling at the edges, a little bleed+ Y, X = np.mgrid[0:S, 0:S].astype(np.float32)+ pa = rng.uniform(0, 2 * np.pi) if pressure is None else np.deg2rad(pressure)+ grad = ((X - R) * np.cos(pa) + (Y - R) * np.sin(pa)) / R+ press = np.clip(0.8 + 0.28 * grad + 0.2 * (noise2d(S, S, 50, 3, self._seed()) - 0.5), 0.35, 1.1)+ n = noise2d(S, S, 3.5, 2, self._seed())+ keep = smoothstep(0.6 - 0.5 * press, 0.8 - 0.5 * press, n)+ edge = np.clip(m - blur(m, 1.6), 0, 1)+ ink = np.clip(blur(m, 0.6) * press * (0.3 + 0.7 * keep) * (1 + 0.6 * edge), 0, 1)+ ink = np.clip(ink * alpha, 0, 1)+ A = np.clip(self._rotate([ink], rot, pad=0)[0], 0, 1)+ hh, ww = A.shape+ ox, oy = int(round(cx - ww / 2)), int(round(cy - hh / 2))+ sl = self._box(ox, oy, ox + ww, oy + hh)+ if sl is None: return+ A = A[sl[0].start - oy:sl[0].stop - oy, sl[1].start - ox:sl[1].stop - ox]+ A = A * (0.8 + 0.4 * self.tooth[sl])+ self.img[sl] *= 1 - np.clip(A, 0, 1)[..., None] * (1 - _c(colour))++ def pen(self, pts, width=2.4, colour=INK, alpha=0.85, dash=None, smooth=True, jitter=0.5, dot=0.0):+ """an ink line drawn on the board (leader lines of the diagram): slight hand wobble, optional dashes+ (on, off) in px, optional dot of radius `dot` at the end"""+ P = np.asarray(pts, np.float32)+ if smooth and len(P) > 2: P = spline(P, 12)+ seg = np.hypot(*np.diff(P, axis=0).T); s = np.concatenate([[0], np.cumsum(seg)])+ n = max(2, int(s[-1] / 1.2))+ ss_ = np.linspace(0, s[-1], n)+ P = np.stack([np.interp(ss_, s, P[:, 0]), np.interp(ss_, s, P[:, 1])], 1)+ tg = np.gradient(P, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6+ P = P + np.stack([-tg[:, 1], tg[:, 0]], 1) * (fbm1d(n, 60, 3, self._seed()) * jitter)[:, None]+ paths = []+ if dash:+ on, off = dash; per = on + off+ k = (ss_ % per) < on+ cur = []+ for i in range(n):+ if k[i]: cur.append(P[i])+ elif cur:+ if len(cur) > 1: paths.append(cur)+ cur = []+ if len(cur) > 1: paths.append(cur)+ else:+ paths = [P]+ pad = width + dot + 4+ sl = self._box(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)+ if sl is None: return+ o = np.array([sl[1].start, sl[0].start], np.float32)+ bh, bw = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start+ m = lines_mask(bh, bw, [np.asarray(p) - o for p in paths], width)+ if dot:+ Y, X = np.mgrid[0:bh, 0:bw].astype(np.float32)+ e = P[-1] - o+ m = np.maximum(m, np.clip(dot - np.hypot(X - e[0], Y - e[1]) + 0.5, 0, 1))+ m = blur(m, 0.35)+ self.img[sl] *= 1 - (m * alpha * (0.85 + 0.3 * self.tooth[sl]))[..., None] * (1 - _c(colour))++ # ------------------------------------------------------------ output+ def composite(self, vignette=0.2, grain=0.03):+ r2 = ((self.XX - self.W * 0.42) / self.W) ** 2 + ((self.YY - self.H * 0.38) / self.H) ** 2+ light = 1.03 - vignette * r2 * 2.0+ img = self.img * light[..., None] + grain * self._grain[..., None]+ return Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=88, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/soft3d.py b/lib/soft3d.pynew file mode 100644index 0000000..03ddb03--- /dev/null+++ b/lib/soft3d.py@@ -0,0 +1,957 @@+"""soft3d — soft pastel 3D renders: a sea of small candy balls, puffy extruded letters and rounded solids, lit+like a product shot in a photo studio (numpy + Pillow only).++Model: a real (small) 3D renderer, not a 2D imitation. A pinhole camera looks into a scene measured in world units+(X right, Y up, Z away from the camera); every pixel is a ray.+ geometry analytic wherever possible, so edges stay clean and ten thousand objects stay cheap:+ ball field thousands of spheres on a square grid resting on a floor, each a little different in size,+ position and colour. A ray walks the grid cell by cell (a DDA) and tests only the one ball+ in each cell, so the whole sea costs about as much as a handful of balls.+ loose balls any size, anywhere (on top of the sea, riding on a letter, the dot of an i): exact+ ray-sphere tests through a depth buffer. drop() lets a ball fall until it touches+ something and roll down into the nearest hollow.+ heroes signed distance fields, ray-marched only inside their own bounding boxes: puffy letters+ (font glyph -> exact 2D distance transform -> extruded, edges rounded right through, then+ inflated like a balloon), rounded boxes, capsules, rounded cylinders, tori; each with its+ own position and rotation.+ part() heroes rising through the sea push it aside: balls they overlap are gone, the balls around+ them are heaped into a soft mound that hugs their feet.+ The whole scene can also be asked "how far is the nearest surface from here?" (a distance field built+ from the same grid, a hash of the loose balls and the heroes) -- that is what the light uses.+ light a photo studio, not a sun:+ sky a big gradient dome (backdrop colour above, a bounce of the floor colour below) lights every+ surface by its normal, dimmed by ambient occlusion sampled in the distance field (the dark+ crevices between balls, the foot of a letter). The occlusion is coloured: shaded pastel+ material turns deeper and more saturated instead of grey, the way light scatters inside it.+ key a large area light: wrap-around diffuse (light bleeds a saturated tint across the terminator:+ the subsurface look), soft shadows marched through the distance field whose penumbra widens+ with distance from the occluder, tinted the same way.+ rim a back light that outlines silhouettes.+ gloss every light is also a softbox seen in reflections: glossy candy mirrors a crisp rounded+ panel, satin balls a broad soft sheen; Fresnel makes grazing edges reflective, and the sky+ gradient and the floor colour show up in the lower half of every reflection.+ lens aerial haze toward the horizon, then a thin-lens depth of field: a circle of confusion from depth,+ gathered in layers so a sharp subject never smears into the blurred background behind it.+ film a gentle tone curve (pastel highlights roll off instead of clipping), bloom, vignette, fine grain.+Stages: stage() is a real re-render, at preview size, of what exists so far -- grey clay (no sky yet) -> materials+under the sky -> key and rim light -> film, the way a 3D scene is built up. Set lens() early (with the camera) and+every stage already has the depth of field: softer previews, and a drawing GIF that compresses much better.+Angles are degrees. Light azimuth is measured from the camera: 0 = from behind the camera, -90 = from the left,++90 = from the right, 180 = from behind the subject. Hero yaw > 0 turns its front toward the left, pitch > 0 leans+it back, roll > 0 leans it left (counter-clockwise on screen, like PIL).++ from soft3d import Soft3D+ s = Soft3D(1920, 1080, seed=1, eye=(0, 2.1, -6.2), target=(0, 0.6, 0.4), fov=29)+ s.floor('#b9e6d4')+ s.ball_field(-12, 12, -5, 40, r=0.1, colours=['#c4ecdc', '#b8e5d2'])+ word = s.text('hey', at=(0, -0.2, 0.4), size=2.2, colour='#ff6a88')+ s.part(heap=0.09)+ s.drop(0.3, 1.0, 0.1, '#ffd35c') # a loose ball falls and rolls into a hollow+ s.sky('#cfc6f4', '#fbe4dc')+ s.key(azimuth=-40, elevation=48)+ s.rim(azimuth=160)+ s.lens(focus=word)+ s.film()+ s.save('out.jpg')+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, smoothstep, load_font+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++def _lin(c):+ """sRGB-ish colour -> linear light (all lighting is done in linear light)"""+ return np.power(_c(c), 2.2).astype(np.float32)+++def _unit(v):+ v = np.asarray(v, np.float32)+ return v / (np.linalg.norm(v, axis=-1, keepdims=True) + 1e-12)+++def _rot(yaw=0.0, pitch=0.0, roll=0.0):+ """local -> world rotation (degrees): roll about Z, then pitch about X, then yaw about Y"""+ a, b, c = np.radians([yaw, pitch, roll])+ Ry = np.array([[np.cos(a), 0, np.sin(a)], [0, 1, 0], [-np.sin(a), 0, np.cos(a)]])+ Rx = np.array([[1, 0, 0], [0, np.cos(b), -np.sin(b)], [0, np.sin(b), np.cos(b)]])+ Rz = np.array([[np.cos(c), -np.sin(c), 0], [np.sin(c), np.cos(c), 0], [0, 0, 1]])+ return (Ry @ Rx @ Rz).astype(np.float32)+++def _edt(mask, R):+ """distance (px) from every pixel to the nearest True pixel of `mask`: exact up to R px, capped at R.+ Rows first (nearest set pixel on the same row, by running max / min of indices), then columns within +-R."""+ H, W = mask.shape+ idx = np.arange(W, dtype=np.float32)[None, :]+ left = np.maximum.accumulate(np.where(mask, idx, -1e6), axis=1)+ right = np.minimum.accumulate(np.where(mask, idx, 1e6)[:, ::-1], axis=1)[:, ::-1]+ g = np.minimum(np.minimum(idx - left, right - idx), R + 1).astype(np.float32)+ g2 = g * g+ D = g2.copy()+ for k in range(1, int(R) + 1):+ kk = np.float32(k * k)+ np.minimum(D[k:], g2[:-k] + kk, out=D[k:])+ np.minimum(D[:-k], g2[k:] + kk, out=D[:-k])+ return np.minimum(np.sqrt(D), R)+++def _bilinear(a, x, y):+ H, W = a.shape+ x = np.clip(x, 0, W - 1.001); y = np.clip(y, 0, H - 1.001)+ x0 = x.astype(np.int32); y0 = y.astype(np.int32)+ fx = x - x0; fy = y - y0+ f = a.ravel(); i = y0 * W + x0+ return (f[i] * (1 - fx) + f[i + 1] * fx) * (1 - fy) + (f[i + W] * (1 - fx) + f[i + W + 1] * fx) * fy+++def _blur_big(a, sigma):+ """gaussian-ish blur of a 2D float array; large radii are done on a downsampled copy"""+ if sigma < 0.3: return a+ k = 1+ while sigma / k > 7 and min(a.shape) / (k * 2) > 32: k *= 2+ if k == 1: return blur(a, sigma)+ H, W = a.shape+ small = np.asarray(Image.fromarray(a.astype(np.float32), 'F').resize((W // k, H // k), Image.BOX))+ small = blur(small, sigma / k)+ return np.asarray(Image.fromarray(small, 'F').resize((W, H), Image.BILINEAR))+++def _blur3(img, sigma):+ return np.stack([_blur_big(img[..., i], sigma) for i in range(img.shape[-1])], -1)+++# material presets: rough = reflection blur, spec = how much the surface mirrors, sss = how far light wraps and+# how saturated its shade gets, sheen = soft glow along silhouettes+MATERIALS = {+ 'satin': dict(rough=0.42, spec=0.55, sss=0.6, sheen=0.22),+ 'candy': dict(rough=0.07, spec=1.0, sss=0.8, sheen=0.10),+ 'jelly': dict(rough=0.14, spec=0.9, sss=1.0, sheen=0.25),+ 'matte': dict(rough=0.8, spec=0.18, sss=0.35, sheen=0.3),+ 'pearl': dict(rough=0.25, spec=0.8, sss=0.5, sheen=0.4),+}+++class Soft3D:+ def __init__(self, W=1920, H=1080, seed=0, eye=(0, 2.0, -6.0), target=(0, 0.5, 0), fov=30.0, floor=0.0,+ preview=0.5, record=True):+ """fov: vertical field of view in degrees. preview: scale of the stage() renders. record=False makes+ stage() a no-op (no preview renders)."""+ self.W, self.H = W, H+ self.rng = np.random.default_rng(seed)+ self.floor_y = float(floor)+ self.preview, self.record = preview, record+ self.camera(eye, target, fov)+ self.mats, self._matkey = [], {}+ self.floor_mat = self._mat('#d8d8d8', 'matte')+ self.field = None+ self.bc = np.zeros((0, 3), np.float32); self.br = np.zeros(0, np.float32); self.bm = np.zeros(0, np.int32)+ self.heroes = []+ self.env = None; self.lights = []; self.panels = []+ self.lens_cfg = None; self.film_cfg = None+ self.version = 0; self._cache = {}; self._hash = None+ self.stages = []++ # ------------------------------------------------------------------ camera+ def camera(self, eye, target, fov=30.0):+ self.eye = np.asarray(eye, np.float32); self.target = np.asarray(target, np.float32)+ self.fwd = _unit(self.target - self.eye)+ self.right = _unit(np.cross([0, 1, 0], self.fwd))+ self.up = np.cross(self.fwd, self.right).astype(np.float32)+ self.fov = float(fov)+ self._cache = {}++ def _focal(self, h):+ return (h / 2) / np.tan(np.radians(self.fov) / 2)++ def project(self, X, Y, Z, scale=1.0):+ """world point -> (x, y) pixel position and camera depth"""+ w, h = self.W * scale, self.H * scale; f = self._focal(h)+ rel = np.asarray([X, Y, Z], np.float32) - self.eye+ zc = float(rel @ self.fwd)+ return w / 2 + f * float(rel @ self.right) / zc, h / 2 - f * float(rel @ self.up) / zc, zc++ # ------------------------------------------------------------------ materials+ def _mat(self, colour, kind='satin', **kw):+ key = (tuple(np.round(_c(colour), 4)), kind, tuple(sorted(kw.items())))+ if key in self._matkey: return self._matkey[key]+ p = dict(MATERIALS[kind]); p.update(kw)+ alb = _lin(colour)+ tint = alb ** 0.9 / (alb ** 0.9).max() # the material's own saturated hue, peak 1+ tint = np.clip(tint * 1.0, 0.05, 1)+ self.mats.append(dict(alb=alb, tint=tint.astype(np.float32), **p))+ self._matkey[key] = len(self.mats) - 1+ self._mtab = None+ return len(self.mats) - 1++ def _mat_table(self):+ if getattr(self, '_mtab', None) is None:+ self._mtab = {k: np.array([m[k] for m in self.mats], np.float32)+ for k in ('alb', 'tint', 'rough', 'spec', 'sss', 'sheen')}+ return self._mtab++ def _touch(self):+ self.version += 1; self._hash = None++ # ------------------------------------------------------------------ geometry: floor and the ball field+ def floor(self, colour='#d0d0d0', mat='matte'):+ """the ground plane at y = floor (seen only in the gaps between balls and beyond the field)"""+ self.floor_mat = self._mat(colour, mat); self._touch()++ def ball_field(self, x0, x1, z0, z1, r=0.1, gap=0.015, colours=('#c4ecdc',), weights=None, mat='satin',+ size_var=0.05, jitter=0.5, lift_var=0.0):+ """a sea of balls on a square grid resting on the floor. gap: space between neighbours; size_var: relative+ radius spread; jitter: 0..1 of the free room each ball may wander in its cell; lift_var: random height."""+ s = 2 * r + gap+ NI, NJ = int((x1 - x0) / s), int((z1 - z0) / s)+ n = NI * NJ+ rng = self.rng+ rad = r * (1 + size_var * rng.uniform(-1, 1, n))+ rad = np.minimum(rad, s / 2 - 1e-3).astype(np.float32)+ room = s / 2 - rad+ ii, jj = np.meshgrid(np.arange(NI), np.arange(NJ), indexing='ij')+ cx = x0 + (ii.ravel() + 0.5) * s + rng.uniform(-1, 1, n) * room * jitter+ cz = z0 + (jj.ravel() + 0.5) * s + rng.uniform(-1, 1, n) * room * jitter+ cy = self.floor_y + rad + np.abs(rng.normal(0, 1, n)) * lift_var+ wts = np.ones(len(colours)) if weights is None else np.asarray(weights, float)+ pick = rng.choice(len(colours), n, p=wts / wts.sum())+ mids = np.array([self._mat(col, mat) for col in colours], np.int32)+ self.field = dict(s=np.float32(s), x0=np.float32(x0), z0=np.float32(z0), NI=NI, NJ=NJ, r0=r,+ C=np.stack([cx, cy, cz], 1).astype(np.float32), r=rad, m=mids[pick])+ self._field_bounds()+ self._touch()+ return self.field++ def _field_bounds(self):+ F = self.field; ok = F['r'] > 0+ F['ylo'] = np.float32(self.floor_y - 1e-3)+ F['yhi'] = np.float32((F['C'][ok, 1] + F['r'][ok]).max() + 1e-3)++ def tint_balls(self, x, z, radius, colours, chance=1.0, mat='satin'):+ """recolour field balls within `radius` of (x, z) (a few scattered accents, a coloured patch...)"""+ F = self.field+ d = np.hypot(F['C'][:, 0] - x, F['C'][:, 2] - z)+ sel = np.nonzero((d < radius) & (self.rng.random(len(d)) < chance))[0]+ mids = np.array([self._mat(c, mat) for c in colours], np.int32)+ F['m'][sel] = mids[self.rng.integers(0, len(mids), len(sel))]+ self._touch()++ def part(self, heap=0.05, reach=0.5, pile=1.0, pile_top=None, clear=1.02, seed=None):+ """the heroes push up through the sea. Balls they overlap are shoved aside and pile up around their feet:+ each settles into the nearest free hollow (between four balls of the sea, or on top of the pile), layer on+ layer, and is kept only where it would really rest (three contacts, the floor, or leaning on a hero).+ pile: how many balls pile up, as a multiple of the ones pushed aside; pile_top: the highest a piled ball's+ centre may sit above the floor (keep the heap low so it doesn't hide the bottoms of letters). The sea+ around them swells by `heap`, fading over `reach`, without ever touching a hero."""+ F = self.field; s = float(F['s']); NJ, NI = F['NJ'], F['NI']+ C, r = F['C'], F['r']+ rng = np.random.default_rng(seed) if seed is not None else self.rng+ alive = r > 0+ d = self._heroes_d(C)+ gone = np.nonzero(alive & (d < r * clear))[0]+ gone_m = F['m'][gone].copy()+ r[gone] = 0+ alive[gone] = False+ lift = (heap * np.exp(-(np.maximum(d - r, 0) / reach) ** 2)).astype(np.float32)+ lift[~alive] = 0+ for _ in range(6): # never push a ball into a hero+ P = C.copy(); P[:, 1] += lift+ bad = alive & (lift > 1e-4) & (self._heroes_d(P) < r * clear)+ if not bad.any(): break+ lift[bad] *= 0.5+ C[:, 1] += lift+ self._field_bounds()+ n = int(len(gone) * pile)+ if n:+ r0 = float(F['r0'])+ near = np.nonzero(alive & (d < 5 * s) | np.isin(np.arange(len(r)), gone))[0]+ ci, cj = near // NJ, near % NJ+ cand = np.concatenate([np.stack([ci + a, cj + b], 1) for a in (0, 1) for b in (0, 1)]).astype(np.float32)+ cand = np.unique(cand, axis=0)+ corners = np.stack([F['x0'] + cand[:, 0] * s, F['z0'] + cand[:, 1] * s], 1)+ centres = np.stack([F['x0'] + (ci + 0.5) * s, F['z0'] + (cj + 0.5) * s], 1)+ xz = np.concatenate([corners, centres])+ hd = self._heroes_d(np.stack([xz[:, 0], np.full(len(xz), 2.3 * r0), xz[:, 1]], 1).astype(np.float32))+ order = np.argsort(hd + rng.uniform(0, 0.6 * s, len(hd)) + (np.arange(len(xz)) >= len(corners)) * 0.5 * s)+ pc, pr = [], []+ for q in order:+ if len(pc) >= n: break+ x, z = xz[q]+ if hd[q] > 6 * s: continue+ rb = r0 * (1 + 0.04 * rng.uniform(-1, 1))+ i, j = int((x - F['x0']) // s), int((z - F['z0']) // s)+ cells = [(i + a) * NJ + (j + b) for a in (-1, 0, 1) for b in (-1, 0, 1)+ if 0 <= i + a < NI and 0 <= j + b < NJ]+ sc, sr = C[cells], r[cells]+ if pc:+ A = np.asarray(pc, np.float32); B = np.asarray(pr, np.float32)+ close = np.hypot(A[:, 0] - x, A[:, 2] - z) < 2.5 * r0+ sc = np.vstack([sc, A[close]]); sr = np.concatenate([sr, B[close]])+ rho = np.hypot(sc[:, 0] - x, sc[:, 2] - z)+ ok = (sr > 0) & (rho < rb + sr)+ ys = sc[ok, 1] + np.sqrt((rb + sr[ok]) ** 2 - rho[ok] ** 2)+ y = max(self.floor_y + rb, ys.max() if len(ys) else -1e9)+ if pile_top is not None and y > self.floor_y + pile_top: continue+ contacts = int((ys > y - 0.025).sum())+ dh = float(self._heroes_d(np.float32([[x, y, z]]))[0])+ if dh < rb * 1.01: continue+ if contacts >= 3 or y <= self.floor_y + rb + 1e-4 or (dh < rb + 0.02 and contacts >= 2):+ pc.append((x + rng.normal(0, 0.003), y + 1e-3, z + rng.normal(0, 0.003))); pr.append(rb)+ if pc:+ cols = gone_m[rng.integers(0, len(gone_m), len(pc))]+ self.bc = np.vstack([self.bc, np.asarray(pc, np.float32)])+ self.br = np.concatenate([self.br, np.asarray(pr, np.float32)])+ self.bm = np.concatenate([self.bm, cols.astype(np.int32)])+ self._touch()+ return len(gone)++ # ------------------------------------------------------------------ geometry: loose balls+ def ball(self, x, y, z, r, colour, mat='satin'):+ """a loose ball exactly where you say"""+ self.bc = np.vstack([self.bc, np.float32([[x, y, z]])])+ self.br = np.append(self.br, np.float32(r)); self.bm = np.append(self.bm, np.int32(self._mat(colour, mat)))+ self._touch()+ return len(self.br) - 1++ def drop(self, x, z, r, colour, mat='satin', roll=24, y=None):+ """drop a ball straight down at (x, z) until it touches the scene, then let it roll `roll` small steps+ downhill into a hollow (roll=0: it stays balanced where it landed). Returns its centre."""+ top = self._scene_top() + r + 0.5 if y is None else y+ p = np.float32([x, top, z])++ def settle(p):+ for _ in range(400):+ d = float(self._sdf(p[None])[0]) - r+ if d < 2e-4: break+ p[1] -= max(d, 2e-4)+ return p+ p = settle(p)+ for _ in range(roll):+ n = self._grad(p[None])[0]+ h = np.hypot(n[0], n[2])+ if h < 0.03: break+ p[0] += n[0] / h * r * 0.18 * min(1, h * 3); p[2] += n[2] / h * r * 0.18 * min(1, h * 3)+ p[1] += r * 0.3+ p = settle(p)+ self.ball(float(p[0]), float(p[1]) + 2e-4, float(p[2]), r, colour, mat)+ return p++ # ------------------------------------------------------------------ geometry: heroes (signed distance fields)+ def _hero(self, kind, R, t, lo, hi, mat, **kw):+ h = dict(kind=kind, R=np.asarray(R, np.float32), t=np.asarray(t, np.float32),+ lo=np.asarray(lo, np.float32), hi=np.asarray(hi, np.float32), mat=mat, near=1e9, **kw)+ self.heroes.append(h); self._touch()+ return len(self.heroes) - 1++ def rbox(self, centre, size, radius=0.05, colour='#ffb3c7', mat='candy', yaw=0, pitch=0, roll=0):+ """rounded box; size = full (w, h, d)"""+ b = np.asarray(size, np.float32) / 2+ return self._hero('rbox', _rot(yaw, pitch, roll), centre, -b, b, self._mat(colour, mat), b=b, rr=radius)++ def capsule(self, centre, length, radius, colour='#ffb3c7', mat='candy', yaw=0, pitch=0, roll=0):+ """a pill standing along its local Y axis"""+ hl = length / 2+ e = np.float32([radius, hl + radius, radius])+ return self._hero('capsule', _rot(yaw, pitch, roll), centre, -e, e, self._mat(colour, mat), hl=hl, rad=radius)++ def cylinder(self, centre, radius, height, round=0.04, colour='#ffb3c7', mat='candy', yaw=0, pitch=0, roll=0):+ """rounded cylinder (a puck, a pedestal) along local Y"""+ e = np.float32([radius, height / 2, radius])+ return self._hero('rcyl', _rot(yaw, pitch, roll), centre, -e, e, self._mat(colour, mat),+ ra=radius, hh=height / 2, rr=round)++ def torus(self, centre, R, r, colour='#ffb3c7', mat='candy', yaw=0, pitch=0, roll=0):+ """a ring lying in the local XZ plane (pitch=90 stands it up)"""+ e = np.float32([R + r, r, R + r])+ return self._hero('torus', _rot(yaw, pitch, roll), centre, -e, e, self._mat(colour, mat), Rt=R, rt=r)++ def _glyph(self, ch, px, style, reach, undot):+ font = load_font(style, px)+ x0, y0, x1, y1 = font.getbbox(ch, anchor='ls')+ m = int(reach) + 8+ ox, oy = m - x0, m - y0+ im = Image.new('L', (x1 - x0 + 2 * m, y1 - y0 + 2 * m), 0)+ ImageDraw.Draw(im).text((ox, oy), ch, font=font, fill=255, anchor='ls')+ a = np.asarray(im, np.float32) / 255+ dot = None+ if undot: # cut the tittle off an i / j: it becomes a ball+ rows = np.nonzero(a.max(1) > 0.5)[0]+ gaps = np.nonzero(np.diff(rows) > 1)[0]+ if len(gaps):+ cut = rows[gaps[0]] + 1+ top = a[:cut].copy(); a = a.copy(); a[:cut] = 0+ ys, xs = np.nonzero(top > 0.5)+ dot = ((xs.mean() - ox), (oy - ys.mean()), np.sqrt(len(xs) / np.pi))+ inside = a >= 0.5+ sd = np.where(inside, -(_edt(~inside, reach) - 0.5), _edt(inside, reach) - 0.5)+ sd = blur(sd.astype(np.float32), 2.0)+ ys, xs = np.nonzero(inside)+ ink = (xs.min() - ox, oy - ys.max(), xs.max() - ox, oy - ys.min()) # px, y up+ return sd, ox, oy, font.getlength(ch), ink, dot, float(-sd.min())++ def text(self, s, at=(0, 0, 0), size=2.0, depth=0.4, colour='#ff6f91', mat='candy', yaw=0.0, pitch=0.0,+ spacing=0.0, round=None, inflate=0.02, style='rounded', bob=None, roll=None, turn=None,+ dot=None, dot_mat='satin', px=360):+ """puffy extruded letters standing on their baseline. at = centre of the word's baseline; size = em height+ (world units); depth = thickness; round = edge radius (default: most of the stroke half-width, so the+ letters are fully rounded like balloons); inflate = how much fatter than the font they are blown up.+ Per-letter lists: bob (raise / sink), roll (lean, degrees), turn (extra yaw). dot = a colour turns the+ dots of i and j into balls of that colour. Returns {'heroes': [...], 'dots': [...], 'centre': xyz}."""+ n = len(s)+ bob = bob or [0] * n; roll = roll or [0] * n; turn = turn or [0] * n+ k = size / px # world units per glyph pixel+ reach = int(0.22 * px)+ glyphs = [self._glyph(ch, px, style, reach, dot is not None and ch in 'ij') for ch in s]+ adv = [g[3] * k + spacing for g in glyphs]+ width = sum(adv) - spacing+ Rw = _rot(yaw, pitch, 0)+ at = np.asarray(at, np.float32)+ out = dict(heroes=[], dots=[])+ pen = -width / 2+ for i, (ch, g) in enumerate(zip(s, glyphs)):+ sd, ox, oy, _, ink, dt, depth_px = g+ if ch.isspace(): pen += adv[i]; continue+ half_w = depth_px * k # half the stroke width, world units+ rr = min(0.92 * half_w + inflate, depth / 2 - 1e-3) if round is None else round+ hz = depth / 2+ Rl = _rot(turn[i], 0, roll[i])+ R = Rw @ Rl+ cg = np.float32([(ink[0] + ink[2]) / 2 * k, 0, 0]) # pivot: bottom centre of the ink+ pivot = np.float32([pen + cg[0], bob[i], 0])+ t = at + Rw @ pivot - R @ cg+ pad = inflate + 0.01+ lo = np.float32([ink[0] * k - pad, ink[1] * k - pad, -hz - 0.01])+ hi = np.float32([ink[2] * k + pad, ink[3] * k + pad, hz + 0.01])+ mid = self._mat(colour, mat)+ out['heroes'].append(self._hero('glyph', R, t, lo, hi, mid, sd=sd, ox=np.float32(ox), oy=np.float32(oy),+ k=np.float32(k), inv=np.float32(1 / k), rr=np.float32(rr),+ hz=np.float32(hz), inflate=np.float32(inflate)))+ self.heroes[-1]['near'] = (reach - 2) * k - pad+ if dt is not None:+ dxl, dyl, drp = dt+ rad = max(drp * k + inflate, half_w + inflate) * 1.08+ c = R @ np.float32([dxl * k, dyl * k + rad * 0.25, 0]) + t+ out['dots'].append(self.ball(float(c[0]), float(c[1]), float(c[2]), rad, dot, dot_mat))+ pen += adv[i]+ lo, hi = self.hero_bounds(out['heroes'])+ out['centre'] = (lo + hi) / 2+ return out++ def hero_bounds(self, ids):+ """world-space bounding box (lo, hi) of some heroes"""+ pts = []+ for i in ids:+ h = self.heroes[i]+ for cx in (0, 1):+ for cy in (0, 1):+ for cz in (0, 1):+ c = np.where([cx, cy, cz], h['hi'], h['lo'])+ pts.append(h['R'] @ c + h['t'])+ pts = np.array(pts)+ return pts.min(0), pts.max(0)++ def _local_d(self, h, p):+ k = h['kind']+ if k == 'glyph':+ u = p[:, 0] * h['inv'] + h['ox']; v = h['oy'] - p[:, 1] * h['inv']+ d2 = _bilinear(h['sd'], u, v) * h['k'] - h['inflate']+ rr = h['rr']+ qx = d2 + rr; qz = np.abs(p[:, 2]) - h['hz'] + rr+ return np.minimum(np.maximum(qx, qz), 0) + np.hypot(np.maximum(qx, 0), np.maximum(qz, 0)) - rr+ if k == 'rbox':+ q = np.abs(p) - h['b'] + h['rr']+ return np.linalg.norm(np.maximum(q, 0), axis=1) + np.minimum(q.max(1), 0) - h['rr']+ if k == 'capsule':+ y = np.clip(p[:, 1], -h['hl'], h['hl'])+ return np.sqrt(p[:, 0] ** 2 + (p[:, 1] - y) ** 2 + p[:, 2] ** 2) - h['rad']+ if k == 'rcyl':+ qx = np.hypot(p[:, 0], p[:, 2]) - h['ra'] + h['rr']; qy = np.abs(p[:, 1]) - h['hh'] + h['rr']+ return np.minimum(np.maximum(qx, qy), 0) + np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) - h['rr']+ if k == 'torus':+ q = np.hypot(p[:, 0], p[:, 2]) - h['Rt']+ return np.hypot(q, p[:, 1]) - h['rt']+ raise ValueError(k)++ def _hero_d(self, h, P):+ """exact distance within `near` of the hero's box (glyphs: inside their distance grid), the box distance+ (a lower bound) farther out -- light queries (AO, shadows, drop) need the exact value close by"""+ pl = (P - h['t']) @ h['R']+ c = (h['lo'] + h['hi']) / 2; e = (h['hi'] - h['lo']) / 2+ q = np.abs(pl - c) - e+ d = np.linalg.norm(np.maximum(q, 0), axis=1) + np.minimum(q.max(1), 0)+ sel = np.nonzero(d < h['near'])[0]+ if len(sel): d[sel] = self._local_d(h, pl[sel])+ return d++ def _heroes_d(self, P):+ d = np.full(len(P), 1e9, np.float32)+ for h in self.heroes:+ np.minimum(d, self._hero_d(h, P), out=d)+ return d++ # ------------------------------------------------------------------ the distance field of the whole scene+ def _field_d(self, P):+ """distance to the sea: the 3 x 3 cells around P. Every ball stays inside its own cell, so any ball not+ looked at is at least one cell width away -- the result is capped there (still a lower bound)"""+ F = self.field; s = F['s']; NJ = F['NJ']+ i0 = np.clip(np.floor((P[:, 0] - F['x0']) / s).astype(np.int32), 1, F['NI'] - 2)+ j0 = np.clip(np.floor((P[:, 2] - F['z0']) / s).astype(np.int32), 1, NJ - 2)+ base = i0 * NJ + j0+ d = np.full(len(P), s, np.float32)+ for off in (-NJ - 1, -NJ, -NJ + 1, -1, 0, 1, NJ - 1, NJ, NJ + 1):+ cell = base + off+ r = F['r'][cell]+ dd = np.linalg.norm(P - F['C'][cell], axis=1) - r+ np.minimum(d, np.where(r > 0, dd, s), out=d)+ return np.maximum(d, P[:, 1] - F['yhi'])++ def _build_hash(self):+ """loose balls -> a grid of lists: a query only looks at the balls registered in its own cell. A ball is+ registered in every cell within `margin` of its footprint, so anything not listed is at least `margin` away+ (the returned distance is capped there, still a lower bound)."""+ n = len(self.br)+ if n == 0: self._hash = False; return+ G = max(0.2, float(self.br.max()) * 2.2); mg = G * 0.5+ rmax = float(self.br.max())+ lo = self.bc[:, [0, 2]].min(0) - rmax - G; hi = self.bc[:, [0, 2]].max(0) + rmax + G+ ni, nj = int(np.ceil((hi[0] - lo[0]) / G)) + 1, int(np.ceil((hi[1] - lo[1]) / G)) + 1+ lists = {}+ for b in range(n):+ x, z, r = self.bc[b, 0], self.bc[b, 2], self.br[b]+ for a in range(int((x - r - mg - lo[0]) // G), int((x + r + mg - lo[0]) // G) + 1):+ for c in range(int((z - r - mg - lo[1]) // G), int((z + r + mg - lo[1]) // G) + 1):+ lists.setdefault(a * nj + c, []).append(b)+ K = max(len(l) for l in lists.values())+ tab = np.full((ni * nj, K), -1, np.int32)+ for i, l in lists.items(): tab[i, :len(l)] = l+ self._hash = dict(G=np.float32(G), mg=np.float32(mg), lo=lo.astype(np.float32), ni=ni, nj=nj, tab=tab)++ def _balls_d(self, P):+ if self._hash is None: self._build_hash()+ hs = self._hash+ if not hs: return np.full(len(P), 1e9, np.float32)+ G = hs['G']+ a = np.floor((P[:, 0] - hs['lo'][0]) / G).astype(np.int32); c = np.floor((P[:, 2] - hs['lo'][1]) / G).astype(np.int32)+ inside = (a >= 0) & (a < hs['ni']) & (c >= 0) & (c < hs['nj'])+ d = np.full(len(P), hs['mg'], np.float32)+ sel = np.nonzero(inside)[0]+ if not len(sel): return d+ ids = hs['tab'][a[sel] * hs['nj'] + c[sel]]+ sub = d[sel]+ for k in range(ids.shape[1]):+ ok = np.nonzero(ids[:, k] >= 0)[0]+ if not len(ok): break+ b = ids[ok, k]+ dd = np.linalg.norm(P[sel[ok]] - self.bc[b], axis=1) - self.br[b]+ sub[ok] = np.minimum(sub[ok], dd)+ d[sel] = sub+ return d++ def _sdf(self, P):+ d = P[:, 1] - self.floor_y+ if self.field is not None: np.minimum(d, self._field_d(P), out=d)+ if len(self.br): np.minimum(d, self._balls_d(P), out=d)+ if self.heroes: np.minimum(d, self._heroes_d(P), out=d)+ return d++ def _grad(self, P, e=1e-3):+ n = np.zeros_like(P)+ for k in ((1, -1, -1), (-1, -1, 1), (-1, 1, -1), (1, 1, 1)):+ kv = np.float32(k)+ n += kv * self._sdf(P + kv * e)[:, None]+ return _unit(n)++ def _scene_top(self):+ top = self.floor_y+ if self.field is not None: top = max(top, float(self.field['yhi']))+ if len(self.br): top = max(top, float((self.bc[:, 1] + self.br).max()))+ if self.heroes: top = max(top, float(self.hero_bounds(range(len(self.heroes)))[1][1]))+ return top++ # ------------------------------------------------------------------ primary rays+ def _rays(self, w, h):+ f = self._focal(h)+ ys, xs = np.mgrid[0:h, 0:w].astype(np.float32)+ D = (self.fwd[None, None] + ((xs + 0.5 - w / 2) / f)[..., None] * self.right+ - ((ys + 0.5 - h / 2) / f)[..., None] * self.up)+ return _unit(D.reshape(-1, 3)), f++ def _rect(self, pts, w, h, f, pad=3):+ rel = pts - self.eye+ zc = rel @ self.fwd+ if (zc < 0.05).any(): return 0, 0, w, h+ x = w / 2 + f * (rel @ self.right) / zc; y = h / 2 - f * (rel @ self.up) / zc+ x0, x1 = int(max(0, x.min() - pad)), int(min(w, x.max() + pad + 1))+ y0, y1 = int(max(0, y.min() - pad)), int(min(h, y.max() + pad + 1))+ return (x0, y0, x1, y1) if x1 > x0 and y1 > y0 else None++ def _hit_heroes(self, D, T, kind, oid, w, h, f):+ O = self.eye+ for hi_, hr in enumerate(self.heroes):+ corners = np.array([hr['R'] @ np.where([a, b, c], hr['hi'], hr['lo']) + hr['t']+ for a in (0, 1) for b in (0, 1) for c in (0, 1)], np.float32)+ rc = self._rect(corners, w, h, f)+ if rc is None: continue+ x0, y0, x1, y1 = rc+ ids = (np.arange(y0, y1)[:, None] * w + np.arange(x0, x1)[None, :]).ravel()+ Dl = D[ids] @ hr['R']; Ol = (O - hr['t']) @ hr['R']+ with np.errstate(divide='ignore', invalid='ignore'):+ inv = 1 / Dl+ ta = (hr['lo'] - Ol) * inv; tb = (hr['hi'] - Ol) * inv+ tin = np.fmax(np.nanmax(np.fmin(ta, tb), 1), 0); tout = np.nanmin(np.fmax(ta, tb), 1)+ ok = (tin < tout) & (tin < T[ids])+ ids, Dl, t, tout = ids[ok], Dl[ok], tin[ok], tout[ok]+ pixf = 0.4 / f+ for _ in range(160):+ if not len(ids): break+ d = self._local_d(hr, Ol + Dl * t[:, None])+ hit = d < pixf * t+ if hit.any():+ g = ids[hit]; better = t[hit] < T[g]+ g = g[better]; T[g] = t[hit][better]; kind[g] = 4; oid[g] = hi_+ t = t + d+ keep = ~hit & (t < tout) & (t < T[ids])+ ids, Dl, t, tout = ids[keep], Dl[keep], t[keep], tout[keep]++ def _hit_balls(self, D, T, kind, oid, w, h, f):+ O = self.eye+ for b in range(len(self.br)):+ c, r = self.bc[b], float(self.br[b])+ rel = c - O; zc = float(rel @ self.fwd)+ if zc < r + 0.05: continue+ sx = w / 2 + f * float(rel @ self.right) / zc; sy = h / 2 - f * float(rel @ self.up) / zc+ rp = f * r / np.sqrt(max(zc * zc - r * r, 1e-6)) * 1.15 + 3+ x0, x1 = int(max(0, sx - rp)), int(min(w, sx + rp + 1)); y0, y1 = int(max(0, sy - rp)), int(min(h, sy + rp + 1))+ if x1 <= x0 or y1 <= y0: continue+ ids = (np.arange(y0, y1)[:, None] * w + np.arange(x0, x1)[None, :]).ravel()+ oc = O - c+ bq = D[ids] @ oc; disc = bq * bq - (oc @ oc - r * r)+ th = -bq - np.sqrt(np.maximum(disc, 0))+ upd = (disc > 0) & (th > 0) & (th < T[ids])+ g = ids[upd]; T[g] = th[upd]; kind[g] = 3; oid[g] = b++ def _hit_field(self, D, T, kind, oid):+ F = self.field; O = self.eye+ s = F['s']; x0, z0, NI, NJ = F['x0'], F['z0'], F['NI'], F['NJ']+ with np.errstate(divide='ignore', invalid='ignore'):+ inv = 1 / D+ lo = np.float32([x0, F['ylo'], z0]); hi = np.float32([x0 + NI * s, F['yhi'], z0 + NJ * s])+ ta = (lo - O) * inv; tb = (hi - O) * inv+ tmin = np.fmax(np.nanmax(np.fmin(ta, tb), 1), 0); tmax = np.fmin(np.nanmin(np.fmax(ta, tb), 1), T)+ ids = np.nonzero(tmin < tmax)[0]+ d = D[ids]; t1 = tmax[ids]+ p = O + d * (tmin[ids] + 1e-5)[:, None]+ i = np.clip(np.floor((p[:, 0] - x0) / s), 0, NI - 1).astype(np.int32)+ j = np.clip(np.floor((p[:, 2] - z0) / s), 0, NJ - 1).astype(np.int32)+ sx = np.where(d[:, 0] > 0, 1, -1).astype(np.int32); sz = np.where(d[:, 2] > 0, 1, -1).astype(np.int32)+ with np.errstate(divide='ignore', invalid='ignore'):+ tdx = np.abs(s / d[:, 0]); tdz = np.abs(s / d[:, 2])+ tmx = np.where(d[:, 0] != 0, (x0 + (i + (sx > 0)) * s - O[0]) / d[:, 0], np.inf)+ tmz = np.where(d[:, 2] != 0, (z0 + (j + (sz > 0)) * s - O[2]) / d[:, 2], np.inf)+ C, Rr = F['C'], F['r']+ while len(ids):+ cell = i * NJ + j+ r = Rr[cell]; oc = O - C[cell]+ bq = (oc * d).sum(1); disc = bq * bq - ((oc * oc).sum(1) - r * r)+ hit = (r > 0) & (disc > 0)+ th = -bq - np.sqrt(np.where(hit, disc, 0))+ hit &= (th > 0) & (th < t1)+ if hit.any():+ g = ids[hit]; T[g] = th[hit]; kind[g] = 2; oid[g] = cell[hit]+ ax = tmx < tmz+ tn = np.where(ax, tmx, tmz)+ i = i + np.where(ax, sx, 0); j = j + np.where(ax, 0, sz)+ tmx = np.where(ax, tmx + tdx, tmx); tmz = np.where(ax, tmz, tmz + tdz)+ keep = ~hit & (tn < t1) & (i >= 0) & (i < NI) & (j >= 0) & (j < NJ)+ ids, d, t1, i, j, sx, sz, tdx, tdz, tmx, tmz = (a[keep] for a in (ids, d, t1, i, j, sx, sz, tdx, tdz, tmx, tmz))++ def _trace(self, scale):+ key = (scale, self.version)+ if key in self._cache: return self._cache[key]+ self._cache = {k: v for k, v in self._cache.items() if k[1] == self.version}+ w, h = int(round(self.W * scale)), int(round(self.H * scale))+ D, f = self._rays(w, h)+ n = len(D)+ T = np.full(n, np.inf, np.float32); kind = np.zeros(n, np.int8); oid = np.full(n, -1, np.int32)+ if self.heroes: self._hit_heroes(D, T, kind, oid, w, h, f)+ if len(self.br): self._hit_balls(D, T, kind, oid, w, h, f)+ if self.field is not None: self._hit_field(D, T, kind, oid)+ with np.errstate(divide='ignore'):+ tf = np.where(D[:, 1] < 0, (self.floor_y - self.eye[1]) / D[:, 1], np.inf)+ fl = tf < T+ T[fl] = tf[fl]; kind[fl] = 1+ hit = np.nonzero(kind > 0)[0]+ P = self.eye + D[hit] * T[hit, None]+ Nn = np.zeros_like(P); mat = np.zeros(len(hit), np.int32)+ kh = kind[hit]; oh = oid[hit]+ m = kh == 1+ Nn[m] = (0, 1, 0); mat[m] = self.floor_mat+ m = kh == 2+ if m.any():+ cell = oh[m]; Nn[m] = (P[m] - self.field['C'][cell]) / self.field['r'][cell][:, None]+ mat[m] = self.field['m'][cell]+ m = kh == 3+ if m.any():+ b = oh[m]; Nn[m] = (P[m] - self.bc[b]) / self.br[b][:, None]; mat[m] = self.bm[b]+ for hi_, hr in enumerate(self.heroes):+ m = np.nonzero((kh == 4) & (oh == hi_))[0]+ if not len(m): continue+ pl = (P[m] - hr['t']) @ hr['R']+ e = float(hr.get('k', 0.001)) * 2.5 if hr['kind'] == 'glyph' else 1e-3+ g = np.zeros_like(pl)+ for kv in ((1, -1, -1), (-1, -1, 1), (-1, 1, -1), (1, 1, 1)):+ kv = np.float32(kv); g += kv * self._local_d(hr, pl + kv * e)[:, None]+ Nn[m] = _unit(g) @ hr['R'].T+ mat[m] = hr['mat']+ Nn = _unit(Nn)+ Z = np.full(n, 1e6, np.float32); Z[hit] = T[hit] * (D[hit] @ self.fwd)+ tr = dict(w=w, h=h, f=f, D=D, T=T, Z=Z, kind=kind, hit=hit, P=P, N=Nn, mat=mat, shadows={})+ tr['ao'] = self._ao(P, Nn)+ self._cache[key] = tr+ return tr++ # ------------------------------------------------------------------ light transport helpers+ def _ao(self, P, N, radius=0.3):+ """ambient occlusion: how much of the distance field crowds in along the normal (1 open .. 0 buried)"""+ hs = radius * np.array([0.05, 0.13, 0.25, 0.42, 0.66, 1.0], np.float32)+ occ = np.zeros(len(P), np.float32); tot = 0.0; w = 1.0+ base = P + N * 2e-3+ for hgt in hs:+ d = self._sdf(base + N * hgt)+ occ += np.clip(hgt - d, 0, None) * w; tot += hgt * w; w *= 0.72+ return np.clip(1 - 1.25 * occ / tot, 0, 1)++ def _shadow(self, P, N, L, k):+ """soft shadow toward a light of direction L: march the distance field, keep the closest near-miss"""+ n = len(P); res = np.ones(n, np.float32)+ top = self._scene_top() + 1e-3+ ndl = N @ L+ ids = np.nonzero(ndl > -0.35)[0]+ res[ndl <= -0.35] = 0+ o = P[ids] + N[ids] * 3e-3+ t = np.full(len(ids), 4e-3, np.float32)+ for _ in range(64):+ if not len(ids): break+ p = o + L * t[:, None]+ hd = self._sdf(p)+ res[ids] = np.minimum(res[ids], k * hd / t)+ t = t + np.clip(hd, 0.006, 0.3)+ keep = (res[ids] > 0.002) & (p[:, 1] < top)+ ids, o, t = ids[keep], o[keep], t[keep]+ return smoothstep(0, 1, np.clip(res, 0, 1))++ # ------------------------------------------------------------------ lights, sky, lens, film+ def _dir(self, azimuth, elevation):+ fh = _unit([self.fwd[0], 0, self.fwd[2]]); rh = _unit(np.cross([0, 1, 0], fh))+ a, e = np.radians(azimuth), np.radians(elevation)+ return _unit(-fh * np.cos(a) * np.cos(e) + rh * np.sin(a) * np.cos(e) + np.float32([0, 1, 0]) * np.sin(e))++ def sky(self, top='#cfc6f4', horizon='#fbe4dc', ground=None, strength=1.0, haze=45.0, haze_start=6.0,+ haze_colour=None):+ """the studio dome: backdrop gradient (what the camera sees behind everything), ambient light from above+ and a floor bounce from below (ground defaults to the floor colour). haze: distance over which far things+ fade into haze_colour (default: the horizon colour), starting haze_start from the camera."""+ g = self.mats[self.floor_mat]['alb'] ** (1 / 2.2) if ground is None else _c(ground)+ self.env = dict(top=_lin(top), hor=_lin(horizon), ground=np.power(g, 2.2).astype(np.float32) * 0.8,+ k=strength, haze=haze, haze0=haze_start,+ hazec=_lin(horizon if haze_colour is None else haze_colour))++ def key(self, azimuth=-40, elevation=48, colour='#fff3e8', strength=2.4, size=11, shadow=True):+ """the main soft area light (size = angular radius in degrees: bigger = softer shadows, broader gloss)"""+ L = self._dir(azimuth, elevation)+ self.lights.append(dict(L=L, col=_lin(colour), k=strength, size=size, shadow=shadow))+ self._panel(L, size * 1.25, size, strength, len(self.lights) - 1)++ def rim(self, azimuth=160, elevation=26, colour='#ffd9e6', strength=1.3, size=14, shadow=False):+ """a back light: bright outlines along the far side of every silhouette"""+ L = self._dir(azimuth, elevation)+ self.lights.append(dict(L=L, col=_lin(colour), k=strength, size=size, shadow=shadow, rim=True))+ self._panel(L, size, size * 0.6, strength * 0.6, len(self.lights) - 1)++ def softbox(self, azimuth, elevation, width=20, height=12, strength=1.0):+ """a panel that only shows in reflections (adds a studio highlight without changing the lighting)"""+ self._panel(self._dir(azimuth, elevation), width / 2, height / 2, strength, None)++ def _panel(self, L, hw, hh, strength, light):+ a1 = _unit(np.cross([0, 1, 0], L)); a2 = _unit(np.cross(L, a1))+ hw, hh = np.radians(hw), np.radians(hh)+ self.panels.append(dict(c=L, a1=a1, a2=a2, hw=hw, hh=hh, rad=strength / (4 * hw * hh) * 1.6, light=light))++ def lens(self, focus=None, aperture=0.006, max_blur=0.018):+ """depth of field. focus: a world point, a hero list (text() result) or None (the heroes' centre);+ aperture: blur radius of infinity as a fraction of the image width"""+ if isinstance(focus, dict): focus = focus['centre']+ if focus is None:+ focus = np.mean(self.hero_bounds(range(len(self.heroes))), 0) if self.heroes else self.target+ zf = float((np.asarray(focus, np.float32) - self.eye) @ self.fwd)+ self.lens_cfg = dict(zf=zf, a=aperture, mx=max_blur)++ def film(self, bloom=0.22, vignette=0.22, grain=0.012, exposure=1.0):+ self.film_cfg = dict(bloom=bloom, vignette=vignette, grain=grain, exposure=exposure)++ # ------------------------------------------------------------------ shading+ def _backdrop(self, D):+ if self.env is None:+ t = smoothstep(-0.05, 0.5, D[:, 1])[:, None]+ return np.float32([0.62, 0.62, 0.64]) * (1 - t) + np.float32([0.5, 0.5, 0.53]) * t+ e = self.env+ t = smoothstep(-0.01, 0.3, D[:, 1])[:, None] ** 0.8+ return (e['hor'] * (1 - t) + e['top'] * t) * e['k'] * 1.12++ def _env(self, R, rough, shadows):+ e = self.env+ up = R[:, 1:2]+ sky = e['hor'] + (e['top'] - e['hor']) * np.clip(up, 0, 1) ** 0.6+ gnd = e['hor'] + (e['ground'] - e['hor']) * np.clip(-up * 3, 0, 1) ** 0.5+ col = np.where(up > 0, sky, gnd) * e['k']+ for p in self.panels:+ cz = R @ p['c']+ u = np.arctan2(R @ p['a1'], np.maximum(cz, 1e-4)); v = np.arctan2(R @ p['a2'], np.maximum(cz, 1e-4))+ sp = rough * 0.9 + 0.01+ hw, hh = p['hw'] + sp, p['hh'] + sp+ rr = np.minimum(hw, hh) * 0.45+ qx = np.abs(u) - hw + rr; qy = np.abs(v) - hh + rr+ dist = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - rr+ soft = 0.015 + sp * 0.7+ I = p['rad'] * (p['hw'] * p['hh']) / (hw * hh) * smoothstep(soft, -soft, dist) * (cz > 0)+ if p['light'] is not None and p['light'] in shadows:+ I = I * (0.15 + 0.85 * shadows[p['light']])+ col = col + I[:, None] * self.lights[p['light']]['col'] if p['light'] is not None else col + I[:, None]+ return col++ def _shade(self, tr):+ D, hit = tr['D'], tr['hit']+ out = np.zeros((len(D), 3), np.float32)+ miss = tr['kind'] == 0+ out[miss] = self._backdrop(D[miss])+ P, N, ao = tr['P'], tr['N'], tr['ao']+ V = -D[hit]+ ndv = np.clip((N * V).sum(1), 0, 1)+ if self.env is None: # clay render: grey clay under a white dome+ dome = 0.55 + 0.35 * np.clip(N[:, 1], 0, 1)+ out[hit] = (0.62 * dome * ao ** 1.2)[:, None]+ return out+ mt = self._mat_table(); m = tr['mat']+ alb, tint, rough, spec, sss, sheen = (mt[k][m] for k in ('alb', 'tint', 'rough', 'spec', 'sss', 'sheen'))+ e = self.env+ sat = (1 - tint) * sss[:, None] # 0 on the dominant channel: shade stays saturated+ ao_rgb = (0.1 + 0.9 * ao[:, None]) ** (1 + 1.6 * sat)+ up = N[:, 1:2]+ E = np.where(up > 0, e['hor'] + (e['top'] - e['hor']) * up, e['hor'] + (e['ground'] - e['hor']) * (-up))+ col = alb * E * ao_rgb * e['k']+ shadows = {}+ for li, L in enumerate(self.lights):+ if L['shadow']:+ sk = ('sh', li, tuple(np.round(L['L'], 4)), L['size'])+ if sk not in tr['shadows']:+ tr['shadows'][sk] = self._shadow(P, N, L['L'], 1 / np.tan(np.radians(L['size'])))+ sh = tr['shadows'][sk]+ else:+ sh = np.clip(0.35 + 0.65 * ao, 0, 1)+ shadows[li] = sh+ ndl = N @ L['L']+ lam = np.clip(ndl, 0, 1); wr = 0.5 * sss+ wrp = np.clip((ndl + wr) / (1 + wr), 0, 1)+ diff = lam[:, None] + (wrp - lam)[:, None] * tint+ # shade is filled a little by light scattered inside the soft material: saturated, never grey+ sh_rgb = sh[:, None] ** (1 + 1.2 * sat) + 0.4 * sss[:, None] * tint * (1 - sh)[:, None]+ k = L['k'] * (0.55 if L.get('rim') else 1.0)+ col += alb * diff * sh_rgb * L['col'] * k * (0.6 + 0.4 * ao)[:, None]+ if L.get('rim'): # the back light also grazes along silhouettes+ edge = (1 - ndv) ** 1.8 * np.clip(ndl + 0.4, 0, 1)+ col += (alb * 0.5 + 0.5 * tint * alb.max(1, keepdims=True)) * (edge * sh * L['k'] * 1.1)[:, None] * L['col']+ R = D[hit] - 2 * (D[hit] * N).sum(1, keepdims=True) * N+ f0 = 0.045+ F = f0 + (1 - f0) * (1 - ndv) ** 5+ spec_occ = np.clip(ao * 1.25, 0, 1) ** 1.5+ refl = self._env(R, rough, shadows)+ col += refl * (F * spec * spec_occ)[:, None]+ col += alb * tint * (sheen * (1 - ndv) ** 3 * ao)[:, None] * E * e['k']+ out[hit] = col+ if e['haze']:+ fog = 1 - np.exp(-np.maximum(tr['T'][hit] - e['haze0'], 0) / e['haze'])+ out[hit] = out[hit] * (1 - fog[:, None]) + (e['hazec'] * e['k'] * 1.12) * fog[:, None]+ return out++ def _dof(self, img, tr):+ h, w = tr['h'], tr['w']+ L = self.lens_cfg+ Z = tr['Z'].reshape(h, w)+ coc = np.minimum(L['a'] * w * np.abs(1 - L['zf'] / Z), L['mx'] * w)+ levels = np.array([0, 1.0, 2.2, 3.8, 6.0, 9.0, 13.0, 18.5, 26.0, 36.0]) * w / 1920+ levels = levels[levels <= coc.max() * 1.05 + 1e-3]+ if len(levels) < 2: return img+ out = np.zeros_like(img); wsum = np.zeros((h, w), np.float32)+ pos = np.interp(coc, levels, np.arange(len(levels)))+ for k, rad in enumerate(levels):+ wk = np.clip(1 - np.abs(pos - k), 0, 1)+ if wk.max() < 1e-4: continue+ if k == 0:+ layer = img+ else:+ src = smoothstep(0.35 * rad, 0.8 * rad, coc)+ num = _blur3(img * src[..., None], rad * 0.6)+ den = _blur_big(src, rad * 0.6)+ layer = np.where(den[..., None] > 1e-3, num / np.maximum(den, 1e-3)[..., None], img)+ out += layer * wk[..., None]; wsum += wk+ return out / np.maximum(wsum, 1e-6)[..., None]++ def _film(self, img, final):+ c = self.film_cfg+ exp = c['exposure'] if c else 1.0+ img = img * exp+ if c and c['bloom']:+ lum = img.mean(-1, keepdims=True)+ hi = img * np.clip(lum - 0.75, 0, None) / np.maximum(lum, 1e-3)+ w = img.shape[1]+ img = img + (_blur3(hi, w * 0.006) * 0.6 + _blur3(hi, w * 0.022) * 0.6) * c['bloom']+ a = 0.72 # tone curve: linear below `a`, soft shoulder above+ img = np.where(img < a, img, a + (1 - a) * (1 - np.exp(-(img - a) / (1 - a))))+ img = np.clip(img, 0, 1) ** (1 / 2.2)+ if c:+ h, w = img.shape[:2]+ ys, xs = np.mgrid[0:h, 0:w].astype(np.float32)+ r2 = ((xs - w / 2) / (w / 2)) ** 2 * 0.7 + ((ys - h / 2) / (h / 2)) ** 2 * 0.9+ img = img * (1 - c['vignette'] * 0.5 * r2)[..., None]+ if c['grain'] and final:+ g = np.random.default_rng(7).normal(0, 1, (h, w)).astype(np.float32)+ g = g * 0.8 + blur(g, 0.8) * 0.9+ img = img + (g * c['grain'])[..., None]+ return np.clip(img, 0, 1)++ def render(self, scale=1.0, final=True):+ tr = self._trace(scale)+ img = self._shade(tr).reshape(tr['h'], tr['w'], 3)+ if self.lens_cfg: img = self._dof(img, tr)+ img = self._film(img, final)+ return Image.fromarray((img * 255 + 0.5).astype(np.uint8))++ # ------------------------------------------------------------------ output+ def stage(self, name, ss=1.5):+ """snapshot of the scene so far: a real render at `preview` size (supersampled `ss` times)"""+ if not self.record: return+ w, h = int(round(self.W * self.preview)), int(round(self.H * self.preview))+ im = self.render(self.preview * ss, final=False)+ self.stages.append((name, im.resize((w, h), Image.LANCZOS) if im.size != (w, h) else im))++ def save(self, path, stages_dir=None, quality=88, ss=1.5):+ """final render, supersampled `ss` times per axis and downsampled (clean silhouettes)"""+ img = self.render(ss)+ if img.size != (self.W, self.H): img = img.resize((self.W, self.H), Image.LANCZOS)+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/synthwave.py b/lib/synthwave.pynew file mode 100644index 0000000..79c57c8--- /dev/null+++ b/lib/synthwave.py@@ -0,0 +1,914 @@+"""synthwave — an 80s retro-future poster played back off a worn VHS tape (numpy + Pillow only).++Model: one pinhole camera over an endless flat world at dusk, painted like an airbrushed record sleeve, then+recorded to tape and played back on a CRT.+ camera a level camera `eye` metres above the ground looking along +Z (X right, Y up, Z into the picture).+ A point lands at (vx + f*X/Z, horizon + f*(eye - Y)/Z): every line along Z runs to the vanishing+ point, sizes fall off as 1/Z. Ground pixels know their own world coordinates (Xg, Zg), so the grid,+ the sea and the road are evaluated per pixel and stay correct right down to the horizon.+ buffers a display-space colour buffer painted far to near (sky, sun, mountains, city, ground, objects,+ lettering), and an emission buffer: anything that gives off light (sun, neon lines, windows, tail+ lights, the rim of the chrome title) writes its colour there too, and opaque things painted later+ blank the emission behind them. At the end the emission is bloomed at four radii and added, and a+ shoulder curve lets over-driven channels spill into the others, so neon cores burn toward white+ while their halos keep the colour.+ sky a banded dusk gradient (ink-blue zenith, violet, magenta, coral at the horizon), stars thinning+ toward the bright horizon with a few four-point sparkles, optional thin streak clouds lit from below.+ sun a disc with a vertical yellow-orange-pink gradient cut by horizontal slits that get thicker toward the+ bottom (the retro "venetian blind" sun); the slits are real gaps, the sky and its halo show through.+ mountains a height field on a jittered world grid, split into triangles, painted back to front with flat+ dark faces and glowing edges whose colour runs from magenta at the foot to cyan on the ridges;+ distant rows dim, the foot sinks into the horizon haze.+ grid analytic neon lines on the ground plane: the distance to the nearest line is measured in *screen*+ pixels (world distance / gradient), so lines keep an honest anti-aliased width, sub-pixel lines keep+ their energy, and where the cells shrink below a few pixels the pattern is replaced by its average+ instead of shimmering into moire. Lines fade into a pink ground haze with depth; the glossy ground+ carries a soft streak of the sun.+ sea everything above the horizon mirrored about it, torn into horizontal bars: rows are shifted+ sideways in world-space bands and modulated by elongated dashes, so the sun's reflection breaks+ into the stacked glowing strokes of 80s airbrush art; Fresnel makes the far water the better mirror.+ road glossy asphalt with a blurred reflection, neon edge lines and dashed centre line (all per pixel).+ objects palm silhouettes (tapered, ring-notched trunk; fronds as drooping rachises with leaflets hanging on+ both sides, foreshortened by their azimuth; coconuts; a rim of sunset light on the sun side), a low+ city skyline with tiny lit windows and red aviation lights, a car seen from behind with a full-width+ tail-light bar reflected in the road.+ lettering chrome: heavy italic caps with a dark keyline, a stepped extrusion, a pale rim that glows, a face+ that mirrors a sky (deep blue to almost white) above a sharp horizon and a warm ground below it, a+ bevel lit from the upper left and four-point glints. Neon script: a coloured tube with a white-hot+ core. Letter-spaced captions with side rules. VCR on-screen display in a 5x7 block font.+ tape the last pass (only in the finished frame): luma softened with a faint ghost and ringing, chroma+ blurred and pulled to the right (YIQ), per-line jitter, one tracking band, head-switching noise at+ the bottom, streaky noise and a few dropouts; then the OSD, CRT scanlines, lifted blacks, vignette.++ from synthwave import Synthwave, MAGENTA, CYAN+ s = Synthwave(1920, 1080, seed=87, horizon=610, vp_x=1060, eye=3.5)+ s.sky(); s.stars(); s.sun(560, 640, 270)+ s.mountains(30, 1100, 900, 1700, 190)+ s.floor(); s.sea(coast=-9); s.road(-7, -2)+ s.palm(-8.5, 29, 11)+ s.chrome_text('COASTLINE', 1450, 230, 150)+ s.neon_script('Last Sunset', 1560, 370, 110)+ s.osd('PLAY \u25b6', 90, 70); s.vhs()+ s.save('out.jpg')+"""+import glob+import os+import numpy as np+from PIL import Image, ImageDraw, ImageFont, ImageFilter+from core import blur, smoothstep, load_font, text_mask, shift++MAGENTA, CYAN, VIOLET, ORANGE, YELLOW = '#ff2bd6', '#35e8ff', '#9b4dff', '#ff8a3d', '#ffe45c'+PINK, RED, WHITE = '#ff4f9a', '#ff2a3a', '#fff6fb'+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++def _stops(t, stops):+ """piecewise-linear colour ramp: t (any shape) -> (..., 3); stops = [(t0, colour), ...] ascending"""+ t = np.asarray(t, np.float32)+ ts = np.array([s[0] for s in stops], np.float32)+ cs = np.stack([_c(s[1]) for s in stops])+ return np.stack([np.interp(t, ts, cs[:, i]) for i in range(3)], -1).astype(np.float32)+++def _gblur(a, s):+ """gaussian blur of (H, W) or (H, W, C); large radii run at reduced resolution (same look, much faster)"""+ if s <= 0: return a.astype(np.float32).copy()+ if a.ndim == 3: return np.stack([_gblur(a[..., i], s) for i in range(a.shape[2])], -1)+ k = int(min(8, max(1, s // 4)))+ if k == 1: return blur(a, s)+ H, W = a.shape+ sm = np.asarray(Image.fromarray(a.astype(np.float32), 'F').resize((max(2, W // k), max(2, H // k)), Image.BOX))+ sm = blur(sm, s / k)+ return np.asarray(Image.fromarray(sm, 'F').resize((W, H), Image.BILINEAR))+++def _blur_axis(a, s, axis):+ """gaussian (three box passes) along one axis only"""+ if s < 0.3: return a.astype(np.float32).copy()+ out = a.astype(np.float32)+ w = int(np.sqrt(12 * s * s / 3 + 1)); w += (w % 2 == 0); r = w // 2+ for _ in range(3):+ pad = [(0, 0)] * out.ndim; pad[axis] = (r + 1, r)+ c = np.cumsum(np.pad(out, pad, mode='edge'), axis=axis, dtype=np.float64)+ n = c.shape[axis]+ out = ((np.take(c, np.arange(w, n), axis=axis) - np.take(c, np.arange(0, n - w), axis=axis)) / w).astype(np.float32)+ return out+++def _sample(img, x, y):+ """bilinear sample of (H, W) or (H, W, C) at float pixel coordinates (clamped to the edge)"""+ H, W = img.shape[:2]+ x = np.clip(x, 0, W - 1.001); y = np.clip(y, 0, H - 1.001)+ x0 = x.astype(np.int32); y0 = y.astype(np.int32)+ fx = (x - x0).astype(np.float32); fy = (y - y0).astype(np.float32)+ if img.ndim == 3: fx = fx[..., None]; fy = fy[..., None]+ return ((img[y0, x0] * (1 - fx) + img[y0, x0 + 1] * fx) * (1 - fy)+ + (img[y0 + 1, x0] * (1 - fx) + img[y0 + 1, x0 + 1] * fx) * fy)+++def _vnoise(x, y, seed=0):+ """smooth value noise at float coordinates (lattice spacing 1), in [0, 1]"""+ xi = np.floor(x); yi = np.floor(y)+ fx = x - xi; fy = y - yi+ fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy)+ xi = xi.astype(np.int64); yi = yi.astype(np.int64)++ def h(a, b):+ n = (a * 374761393 + b * 668265263 + seed * 144269477) & 0xffffffff+ n = ((n ^ (n >> 13)) * 1274126177) & 0xffffffff+ return ((n ^ (n >> 16)) & 0xffff).astype(np.float32) / 65535.0+ return ((h(xi, yi) * (1 - fx) + h(xi + 1, yi) * fx) * (1 - fy)+ + (h(xi, yi + 1) * (1 - fx) + h(xi + 1, yi + 1) * fx) * fy).astype(np.float32)+++def _fbm(x, y, octaves=4, seed=0):+ out = 0.0; amp = 1.0; tot = 0.0; fr = 1.0+ for o in range(octaves):+ out = out + amp * _vnoise(x * fr, y * fr, seed + o * 7919); tot += amp; amp *= 0.5; fr *= 2.0+ return (out / tot).astype(np.float32)+++def _dilate(m, r):+ """grow a 0..1 mask by about r px (max filter on an 8-bit copy)"""+ if r <= 0: return m+ im = Image.fromarray((np.clip(m, 0, 1) * 255).astype(np.uint8))+ n = int(r)+ while n > 0:+ k = min(n, 3); im = im.filter(ImageFilter.MaxFilter(2 * k + 1)); n -= k+ return np.asarray(im, np.float32) / 255+++# ---------------------------------------------------------------- lettering fonts (never committed to the repo)+_FONTS = { # (glob pattern, face index, already italic)+ 'chrome': [('/System/Library/Fonts/Avenir Next.ttc', 9, True), ('/System/Library/Fonts/Supplemental/Futura.ttc', 4, False),+ ('/System/Library/Fonts/Supplemental/Arial Black.ttf', 0, False), ('/usr/share/fonts/**/DejaVuSans-BoldOblique.ttf', 0, True),+ ('/usr/share/fonts/**/LiberationSans-BoldItalic.ttf', 0, True), ('C:/Windows/Fonts/ariblk.ttf', 0, False)],+ 'script': [('/System/Library/Fonts/Supplemental/Brush Script.ttf', 0, True), ('/System/Library/Fonts/Supplemental/SnellRoundhand.ttc', 2, True),+ ('/usr/share/fonts/**/z003*.[ot]tf', 0, True), ('C:/Windows/Fonts/BRUSHSCI.TTF', 0, True), ('C:/Windows/Fonts/segoesc.ttf', 0, True)],+ 'caption': [('/System/Library/Fonts/Hiragino Sans GB.ttc', 2, False), ('/System/Library/Fonts/STHeiti Medium.ttc', 0, False),+ ('/usr/share/fonts/**/NotoSansCJK*Bold*.tt[cf]', 0, False), ('/usr/share/fonts/**/NotoSansCJK*.tt[cf]', 0, False),+ ('C:/Windows/Fonts/msyhbd.ttc', 0, False)],+}+_FCACHE = {}+++def synth_font(kind, size):+ """(PIL font, is_italic) for 'chrome' (heavy italic caps), 'script' (brush script) or 'caption' (CJK sans).+ Override with $INKPAINT_FONT_CHROME / _SCRIPT / _CAPTION."""+ key = (kind, int(size))+ if key in _FCACHE: return _FCACHE[key]+ env = os.environ.get('INKPAINT_FONT_' + kind.upper())+ hit = None+ for pat, idx, it in ([(env, 0, kind == 'script')] if env else []) + _FONTS.get(kind, []):+ for p in glob.glob(pat, recursive=True):+ try:+ hit = (ImageFont.truetype(p, max(4, int(size)), index=idx), it); break+ except OSError:+ pass+ if hit: break+ if hit is None: hit = (load_font({'chrome': 'sans_bold', 'script': 'script'}.get(kind, 'cjk_sans'), size), False)+ _FCACHE[key] = hit+ return hit+++# ---------------------------------------------------------------- VCR on-screen display: 5x7 block glyphs+_OSD = {+ 'A': '.###.|#...#|#...#|#####|#...#|#...#|#...#', 'B': '####.|#...#|#...#|####.|#...#|#...#|####.',+ 'C': '.###.|#...#|#....|#....|#....|#...#|.###.', 'D': '####.|#...#|#...#|#...#|#...#|#...#|####.',+ 'E': '#####|#....|#....|####.|#....|#....|#####', 'F': '#####|#....|#....|####.|#....|#....|#....',+ 'G': '.###.|#...#|#....|#.###|#...#|#...#|.####', 'H': '#...#|#...#|#...#|#####|#...#|#...#|#...#',+ 'I': '.###.|..#..|..#..|..#..|..#..|..#..|.###.', 'J': '..###|...#.|...#.|...#.|...#.|#..#.|.##..',+ 'K': '#...#|#..#.|#.#..|##...|#.#..|#..#.|#...#', 'L': '#....|#....|#....|#....|#....|#....|#####',+ 'M': '#...#|##.##|#.#.#|#.#.#|#...#|#...#|#...#', 'N': '#...#|#...#|##..#|#.#.#|#..##|#...#|#...#',+ 'O': '.###.|#...#|#...#|#...#|#...#|#...#|.###.', 'P': '####.|#...#|#...#|####.|#....|#....|#....',+ 'Q': '.###.|#...#|#...#|#...#|#.#.#|#..#.|.##.#', 'R': '####.|#...#|#...#|####.|#.#..|#..#.|#...#',+ 'S': '.####|#....|#....|.###.|....#|....#|####.', 'T': '#####|..#..|..#..|..#..|..#..|..#..|..#..',+ 'U': '#...#|#...#|#...#|#...#|#...#|#...#|.###.', 'V': '#...#|#...#|#...#|#...#|#...#|.#.#.|..#..',+ 'W': '#...#|#...#|#...#|#.#.#|#.#.#|#.#.#|.#.#.', 'X': '#...#|#...#|.#.#.|..#..|.#.#.|#...#|#...#',+ 'Y': '#...#|#...#|.#.#.|..#..|..#..|..#..|..#..', 'Z': '#####|....#|...#.|..#..|.#...|#....|#####',+ '0': '.###.|#...#|#..##|#.#.#|##..#|#...#|.###.', '1': '..#..|.##..|..#..|..#..|..#..|..#..|.###.',+ '2': '.###.|#...#|....#|...#.|..#..|.#...|#####', '3': '#####|...#.|..#..|...#.|....#|#...#|.###.',+ '4': '...#.|..##.|.#.#.|#..#.|#####|...#.|...#.', '5': '#####|#....|####.|....#|....#|#...#|.###.',+ '6': '..##.|.#...|#....|####.|#...#|#...#|.###.', '7': '#####|....#|...#.|..#..|.#...|.#...|.#...',+ '8': '.###.|#...#|#...#|.###.|#...#|#...#|.###.', '9': '.###.|#...#|#...#|.####|....#|...#.|.##..',+ ':': '.....|..#..|..#..|.....|..#..|..#..|.....', '.': '.....|.....|.....|.....|.....|.##..|.##..',+ '-': '.....|.....|.....|#####|.....|.....|.....', '/': '....#|....#|...#.|..#..|.#...|#....|#....',+ "'": '..#..|..#..|.#...|.....|.....|.....|.....', ' ': '.....|.....|.....|.....|.....|.....|.....',+ '\u25b6': '#....|##...|###..|####.|###..|##...|#....', '\u25a0': '.....|#####|#####|#####|#####|#####|.....',+ '\u25c0': '....#|...##|..###|.####|..###|...##|....#', '\u2016': '##.##|##.##|##.##|##.##|##.##|##.##|##.##',+}+++class Synthwave:+ def __init__(self, W=1920, H=1080, seed=0, horizon=None, vp_x=None, focal=1100.0, eye=3.5, record=True):+ self.W, self.H = W, H+ self.rng = np.random.default_rng(seed)+ self.hy = H * 0.565 if horizon is None else float(horizon)+ self.vx = W * 0.55 if vp_x is None else float(vp_x)+ self.f, self.eye = float(focal), float(eye)+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)+ self.img = np.zeros((H, W, 3), np.float32)+ self.emi = np.zeros((H, W, 3), np.float32)+ dy = self.YY - self.hy+ self.below = np.clip(dy + 0.5, 0, 1) # ground coverage (horizon row anti-aliased)+ self.dyc = np.maximum(dy, 0.35)+ self.Zg = self.f * self.eye / self.dyc # world coordinates of every ground pixel+ self.Xg = (self.XX - self.vx) * self.Zg / self.f+ self.dXdx = self.Zg / self.f # metres per pixel, used for anti-aliasing+ self.dXdy = -self.Xg / self.dyc+ self.dZdy = -self.Zg / self.dyc+ self.sun_info = None+ self.horizon_col = hexc('#ff5a86')+ self.osd_items, self.vhs_opts = [], None+ self.record = record+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ camera+ def project(self, X, Y, Z):+ """world metres -> screen pixels"""+ Z = np.maximum(Z, 1e-3)+ return self.vx + self.f * np.asarray(X) / Z, self.hy + self.f * (self.eye - np.asarray(Y)) / Z++ def ground_row(self, Z):+ return self.hy + self.f * self.eye / np.maximum(Z, 1e-3)++ # ------------------------------------------------------------ compositing+ def _over(self, mask, colour, emit=0.0, at=(0, 0)):+ """paint `colour` (3,) or an array shaped like `mask` + (3,) over the picture with coverage `mask`,+ placed with its top-left corner at `at`; emission behind it is replaced by colour * emit"""+ m = np.asarray(mask, np.float32)+ x0, y0 = int(at[0]), int(at[1])+ h, w = m.shape+ X0, Y0, X1, Y1 = max(0, x0), max(0, y0), min(self.W, x0 + w), min(self.H, y0 + h)+ if X1 <= X0 or Y1 <= Y0: return+ lm = m[Y0 - y0:Y1 - y0, X0 - x0:X1 - x0]+ rows = np.nonzero(lm.max(1) > 1e-4)[0]; cols = np.nonzero(lm.max(0) > 1e-4)[0]+ if not len(rows): return+ ly0, ly1, lx0, lx1 = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1+ a = lm[ly0:ly1, lx0:lx1][..., None]+ sl = (slice(Y0 + ly0, Y0 + ly1), slice(X0 + lx0, X0 + lx1))+ col = np.asarray(colour, np.float32)+ if col.ndim == 3: col = col[Y0 - y0 + ly0:Y0 - y0 + ly1, X0 - x0 + lx0:X0 - x0 + lx1]+ e = np.asarray(emit, np.float32)+ if e.ndim >= 2: e = e[Y0 - y0 + ly0:Y0 - y0 + ly1, X0 - x0 + lx0:X0 - x0 + lx1]+ if e.ndim == 2: e = e[..., None]+ self.img[sl] = self.img[sl] * (1 - a) + col * a+ self.emi[sl] = self.emi[sl] * (1 - a) + col * e * a++ def _canvas(self, x0, y0, x1, y1, ss):+ """a supersampled local drawing surface; returns (image, draw, origin, to_local)"""+ x0, y0 = int(np.floor(x0)), int(np.floor(y0))+ w, h = max(1, int(np.ceil(x1)) - x0), max(1, int(np.ceil(y1)) - y0)+ im = Image.new('L', (w * ss, h * ss), 0)+ return im, ImageDraw.Draw(im), (x0, y0), (lambda px, py: ((px - x0) * ss, (py - y0) * ss))++ @staticmethod+ def _down(im, ss):+ w, h = im.size+ return np.asarray(im.resize((w // ss, h // ss), Image.BOX), np.float32) / 255++ # ------------------------------------------------------------ sky+ def sky(self, stops=None, ground=('#2a0834', '#08020f')):+ """dusk gradient from the zenith to the horizon; below it an unlit ground (horizon, bottom colours)+ until the floor, sea or road are laid over it"""+ stops = stops or [(0.0, '#03010f'), (0.3, '#0e0630'), (0.55, '#2a0b52'), (0.76, '#661470'),+ (0.91, '#c02a78'), (1.0, '#ff6a6a')]+ t = np.clip(self.YY / self.hy, 0, 1)+ self.img[:] = _stops(t, stops)+ self.horizon_col = _c(stops[-1][1])+ if ground:+ g = np.clip((self.YY - self.hy) / (self.H - self.hy), 0, 1) ** 0.5+ self._over(self.below, _stops(g, [(0, ground[0]), (1, ground[1])]))++ def stars(self, n=1600, bright=14, y_max=None, seed=None):+ """stars thinning toward the bright horizon; the `bright` brightest get four-point sparkles"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ ym = self.hy * 0.82 if y_max is None else y_max+ H, W = self.H, self.W+ ys = ym * (1 - np.sqrt(1 - r.random(n))); xs = r.uniform(0, W - 1, n)+ mag = np.clip(r.pareto(2.4, n) * 0.22 + 0.06, 0, 1.6)+ mag *= np.clip(1 - ys / (self.hy * 0.9), 0, 1) ** 0.8 # the sky outshines them lower down+ tint = np.stack([_c('#ffffff'), _c('#cfe4ff'), _c('#ffd6f4'), _c('#fff1c9')])[r.integers(0, 4, n)]+ lay = np.zeros((H, W, 3), np.float32)+ x0 = xs.astype(int); y0 = ys.astype(int); fx = xs - x0; fy = ys - y0+ for dx, dy, wgt in ((0, 0, (1 - fx) * (1 - fy)), (1, 0, fx * (1 - fy)), (0, 1, (1 - fx) * fy), (1, 1, fx * fy)):+ yy = np.clip(y0 + dy, 0, H - 1); xx = np.clip(x0 + dx, 0, W - 1)+ np.add.at(lay, (yy, xx), (mag * wgt)[:, None] * tint)+ lay = np.stack([blur(lay[..., i], 0.5) for i in range(3)], -1) * 2.2+ # sparkles on the brightest+ top = np.argsort(-mag)[:bright]+ for i in top:+ L = 6 + 16 * min(1.0, mag[i])+ sl = (slice(max(0, int(ys[i] - L)), min(H, int(ys[i] + L) + 1)), slice(max(0, int(xs[i] - L)), min(W, int(xs[i] + L) + 1)))+ dx = self.XX[sl] - xs[i]; dy = self.YY[sl] - ys[i]+ spike = (np.exp(-np.abs(dx) / (L * 0.28)) * np.exp(-(dy / 0.7) ** 2) + np.exp(-np.abs(dy) / (L * 0.28)) * np.exp(-(dx / 0.7) ** 2))+ spike += np.exp(-(dx * dx + dy * dy) / 3.0) * 1.5+ lay[sl] += (spike * mag[i] * 0.9)[..., None] * tint[i]+ self.img += lay; self.emi += lay * 0.5++ def streaks(self, bands, colour='#2a0a44', lit='#ff6a8a', seed=None):+ """thin horizontal streak clouds: bands = [(y, x0, x1, thickness_px), ...]; dark bodies lit from below"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ for (y, x0, x1, th) in bands:+ sd = int(r.integers(1 << 20))+ u = (self.XX - x0) / max(1, x1 - x0)+ prof = smoothstep(0, 0.25, u) * smoothstep(1, 0.7, u)+ wav = (_fbm(self.XX / 260.0, np.full_like(self.XX, sd % 997), 3, sd) - 0.5) * th * 1.6+ thick = th * (0.35 + 0.9 * _fbm(self.XX / 140.0, np.full_like(self.XX, 3.0), 3, sd + 1)) * prof+ d = (self.YY - (y + wav))+ m = np.clip(thick * 0.5 + 0.5 - np.abs(d), 0, 1) * (prof > 0.01)+ under = smoothstep(-thick * 0.1, thick * 0.5, d) # the underside catches the sunset+ col = _c(colour)[None, None] * (1 - under[..., None]) + _c(lit)[None, None] * under[..., None]+ self._over(m * 0.92, col, emit=under * 0.25)++ def sun(self, x, y, r, stops=None, bands=8, band_top=0.34, gaps=(0.2, 0.7), glow=1.0, level=0.4, gain=0.72):+ """the retro sun: a vertical gradient cut by horizontal slits that thicken toward the bottom.+ The slits are spread over the part above the horizon; glow is the halo painted into the sky first."""+ stops = stops or [(0.0, '#ffe95a'), (0.3, '#ffc03a'), (0.56, '#ff7a3a'), (0.8, '#ff3d7a'), (1.0, '#ff1f9f')]+ d = np.hypot(self.XX - x, self.YY - y)+ halo = np.exp(-(d / (r * 1.3)) ** 2) * 0.2 + np.exp(-(d / (r * 2.6)) ** 2) * 0.12 + np.exp(-(d / (r * 5)) ** 2) * 0.05+ hc = _stops(np.clip((self.YY - (y - r)) / (2 * r), 0, 1), [(0, '#ff9a4a'), (1, '#ff3d8a')])+ above = np.clip(self.hy - self.YY + 0.5, 0, 1)+ self.img += hc * (halo * above * glow)[..., None]+ top = y - r; bot = min(y + r, self.hy)+ v = np.clip((self.YY - top) / max(1.0, bot - top), 0, 1)+ col = _stops(v, stops)+ col = col * gain * (1 + 0.12 * np.exp(-(d / (r * 0.6)) ** 2))[..., None] # bloom brings it back up+ disc = np.clip(r - d + 0.5, 0, 1) * above # it sets: nothing below the horizon+ y0 = top + band_top * (bot - top); pitch = (bot - y0) / max(1, bands)+ cut = np.zeros_like(disc)+ for k in range(bands):+ g = pitch * (gaps[0] + (gaps[1] - gaps[0]) * k / max(1, bands - 1))+ yc = y0 + pitch * (k + 0.62)+ cut = np.maximum(cut, np.clip(g / 2 + 0.5 - np.abs(self.YY - yc), 0, 1))+ self._over(disc * (1 - cut), col, emit=level)+ self.sun_info = (float(x), float(y), float(r))++ # ------------------------------------------------------------ far things+ def mountains(self, x0, x1, z0, z1, height, cell=(55.0, 80.0), seed=None, fill='#150629', edge=(MAGENTA, CYAN),+ width=1.5, level=0.9, taper=(True, True), scale=320.0, haze=0.55, light=(-0.8, 0.35, 0.45), ss=3):+ """a wireframe range: a height field on a jittered world grid (x0..x1, z0..z1 metres), split into+ triangles and painted far to near: flat dark faces faintly lit by the sun, glowing edges magenta at the+ foot to cyan on the ridges. taper=(left, right): let the range fade to the ground at that end."""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ cx, cz = cell+ nx = max(2, int(round((x1 - x0) / cx))); nz = max(2, int(round((z1 - z0) / cz)))+ X, Z = np.meshgrid(np.linspace(x0, x1, nx + 1), np.linspace(z0, z1, nz + 1))+ X[:, 1:-1] += r.uniform(-0.32, 0.32, (nz + 1, nx - 1)) * cx+ Z[1:-1, :] += r.uniform(-0.3, 0.3, (nz - 1, nx + 1)) * cz+ u = (X - x0) / (x1 - x0); w = (Z - z0) / (z1 - z0)+ envx = (smoothstep(0, 0.14, u) if taper[0] else 1.0) * (smoothstep(1, 0.86, u) if taper[1] else 1.0)+ envz = np.sin(np.pi * np.clip(0.1 + 0.75 * w, 0, 1)) ** 0.8 * smoothstep(0.0, 0.3, w)+ sd = int(r.integers(1 << 20))+ n = _fbm(X / scale, Z / scale, 4, sd)+ ridge = 1 - np.abs(2 * n - 1)+ Hh = height * envx * envz * (0.2 + 0.8 * ridge ** 1.5) * r.uniform(0.85, 1.15, X.shape)+ Hh[0, :] = 0+ sx, sy = self.project(X, Hh, Z)+ bx0, bx1 = max(0, sx.min() - 4), min(self.W, sx.max() + 4)+ by0, by1 = max(0, sy.min() - 4), min(self.H, sy.max() + 4)+ if bx1 <= bx0 or by1 <= by0: return+ cw, ch = int(np.ceil(bx1 - bx0)), int(np.ceil(by1 - by0))+ ox, oy = int(np.floor(bx0)), int(np.floor(by0))+ col = Image.new('RGB', (cw * ss, ch * ss)); alp = Image.new('L', (cw * ss, ch * ss)); emi = Image.new('RGB', (cw * ss, ch * ss))+ dc, da, de = ImageDraw.Draw(col), ImageDraw.Draw(alp), ImageDraw.Draw(emi)+ P = lambda j, i: ((sx[j, i] - ox) * ss, (sy[j, i] - oy) * ss)+ L = np.array(light, np.float32); L /= np.linalg.norm(L)+ fc = _c(fill); sunc = _c('#ff6a7a'); e0, e1 = _c(edge[0]), _c(edge[1])+ lw = max(1, int(round(width * ss)))+ for j in reversed(range(nz)): # far rows first+ tris = []+ for i in range(nx):+ a, b, c, d = (j, i), (j, i + 1), (j + 1, i), (j + 1, i + 1)+ tris += [(a, b, d), (a, d, c)] if r.random() < 0.5 else [(a, b, c), (b, d, c)]+ fade = np.exp(-(Z[j, 0] - z0) / (2.2 * (z1 - z0)))+ for t in tris:+ p = np.array([(X[q], Hh[q], Z[q]) for q in t], np.float32)+ nrm = np.cross(p[1] - p[0], p[2] - p[0]); nrm /= np.linalg.norm(nrm) + 1e-6+ if nrm[1] < 0: nrm = -nrm+ lam = max(0.0, float(nrm @ L))+ cf = fc * (0.8 + 0.35 * lam) + sunc * 0.1 * lam+ poly = [P(*q) for q in t]+ dc.polygon(poly, fill=tuple(int(v) for v in np.clip(cf * 255, 0, 255))); da.polygon(poly, fill=255); de.polygon(poly, fill=(0, 0, 0))+ for t in tris:+ for q0, q1 in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0])):+ hgt = 0.5 * (Hh[q0] + Hh[q1]) / max(1e-6, height)+ ce = e0 + (e1 - e0) * np.clip(hgt * 1.5, 0, 1) ** 0.9+ cl = tuple(int(v) for v in np.clip(ce * 255 * (0.55 + 0.45 * fade), 0, 255))+ cm = tuple(int(v) for v in np.clip(ce * 127 * level * fade, 0, 255))+ dc.line([P(*q0), P(*q1)], fill=cl, width=lw); da.line([P(*q0), P(*q1)], fill=255, width=lw)+ de.line([P(*q0), P(*q1)], fill=cm, width=lw)+ dn = lambda im: np.asarray(im.resize((cw, ch), Image.BOX), np.float32) / 255+ A = dn(alp); C = dn(col); E = dn(emi) * 2+ hz = haze * np.exp(-np.maximum(0, self.hy - (self.YY[oy:oy + ch, ox:ox + cw])) / 26.0)[..., None]+ C = C * (1 - hz) + self.horizon_col * hz * A[..., None]+ C = C / np.maximum(A, 1e-4)[..., None]+ self._over(A, C, emit=0.0, at=(ox, oy))+ sl = (slice(oy, oy + A.shape[0]), slice(ox, ox + A.shape[1]))+ self.emi[sl] += E++ def skyline(self, X0, X1, Z, heights=(18, 80), widths=(12, 34), colour='#1c0934', windows=0.2, tall=None,+ seed=None, haze=0.55, ss=3):+ """a distant city: blocks, setbacks, antennas with red lights, tiny lit windows; its foot in the haze.+ tall = (X, height) forces one landmark tower."""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ s = self.f / Z+ gy = self.ground_row(Z)+ blocks = []+ X = X0+ while X < X1:+ wdt = r.uniform(*widths)+ mid = 1 - abs((X + wdt / 2 - (X0 + X1) / 2) / ((X1 - X0) / 2))+ h = r.uniform(heights[0], heights[0] + (heights[1] - heights[0]) * (0.35 + 0.65 * mid))+ blocks.append([X, wdt, h]); X += wdt * r.uniform(0.7, 1.05)+ if tall: blocks.append([tall[0] - 7, 14, tall[1]])+ top_px = max(b[2] for b in blocks) * s + 30+ x0p, x1p = self.vx + X0 * s - 10, self.vx + X1 * s + 10+ im, d, (ox, oy), T = self._canvas(x0p, gy - top_px, x1p, gy + 2, ss)+ win = Image.new('RGB', im.size); dw = ImageDraw.Draw(win)+ red = Image.new('L', im.size); dr = ImageDraw.Draw(red)+ wcols = [(255, 214, 140), (255, 190, 120), (140, 240, 255), (255, 140, 210)]+ for bx, bw, bh in sorted(blocks, key=lambda b: b[2]):+ L, R = self.vx + bx * s, self.vx + (bx + bw) * s+ topy = gy - bh * s+ d.rectangle([T(L, topy), T(R, gy + 1)], fill=255)+ kind = r.random()+ if kind < 0.3: # setback crown+ inset = bw * r.uniform(0.18, 0.3) * s; th = bh * r.uniform(0.12, 0.2) * s+ d.rectangle([T(L + inset, topy - th), T(R - inset, topy)], fill=255); topy -= th+ elif kind < 0.42: # spire+ cxp = (L + R) / 2; d.polygon([T(L + (R - L) * 0.3, topy), T(cxp, topy - bh * 0.25 * s), T(R - (R - L) * 0.3, topy)], fill=255)+ topy -= bh * 0.25 * s+ if bh > heights[1] * 0.55 and r.random() < 0.7: # antenna + aviation light+ ax = L + (R - L) * r.uniform(0.3, 0.7); ah = r.uniform(6, 14) * s+ d.line([T(ax, topy), T(ax, topy - ah)], fill=255, width=max(1, int(0.8 * s * ss)))+ dr.ellipse([T(ax - 1.2, topy - ah - 1.2), T(ax + 1.2, topy - ah + 1.2)], fill=255)+ # windows: rows every 3.6 m, columns every 3 m+ rows = int(bh / 3.6); cols = max(1, int(bw / 3.0))+ for i in range(rows):+ wy = gy - (i + 0.6) * 3.6 * s+ if wy < gy - bh * s + 2: continue+ for k in range(cols):+ if r.random() > windows: continue+ wx = L + (k + 0.3) * (R - L) / cols+ dw.rectangle([T(wx, wy), T(wx + 1.3 * s, wy + 1.4 * s)], fill=wcols[int(r.integers(0, 4)) if r.random() < 0.35 else 0])+ A = self._down(im, ss)+ Wn = np.asarray(win.resize(A.shape[::-1], Image.BOX), np.float32) / 255+ Rd = self._down(red, ss)+ yy = self.YY[oy:oy + A.shape[0], ox:ox + A.shape[1]]+ hz = (haze * np.exp(-np.maximum(0, gy - yy) / (0.35 * top_px)))[..., None]+ C = _c(colour) * (1 - hz) + self.horizon_col * 0.8 * hz+ self._over(A, C, at=(ox, oy))+ sl = (slice(oy, oy + A.shape[0]), slice(ox, ox + A.shape[1]))+ lights = Wn * 1.3 + Rd[..., None] * _c(RED) * 2.2+ self.img[sl] += lights * (1 - hz * 0.5); self.emi[sl] += lights * 0.9++ # ------------------------------------------------------------ ground+ def _lines(self, g, gdx, gdy, halfw, min_px=1.0):+ """coverage of neon lines at integer values of g (lines of half-width `halfw` in g units);+ gdx, gdy: derivatives of g per pixel. Sub-pixel lines keep their energy; dense lines fade to their mean."""+ grad = np.hypot(gdx, gdy) + 1e-9+ d = np.abs(g - np.round(g)) / grad # px to the nearest line+ hw = halfw / grad+ hwe = np.maximum(hw, min_px * 0.5)+ cov = np.clip(hwe + 0.5 - d, 0, 1) * (hw / hwe)+ k = smoothstep(2.0, 7.0, 1 / grad)+ return cov * k + np.clip(2 * halfw, 0, 1) * (1 - k)++ def _region(self, X0, X1):+ """anti-aliased coverage of the ground strip X0 < X < X1"""+ gx = np.hypot(self.dXdx, self.dXdy) + 1e-9+ a = np.ones_like(self.Xg)+ if X0 is not None: a = a * np.clip(0.5 + (self.Xg - X0) / gx, 0, 1)+ if X1 is not None: a = a * np.clip(0.5 + (X1 - self.Xg) / gx, 0, 1)+ return a * self.below++ def _mirror(self, stretch=0.9, xs=None):+ """the picture above the horizon mirrored into the rows below it (sampled at columns xs)"""+ ys = self.hy - (self.YY - self.hy) * stretch+ ys = np.clip(ys, 0, self.hy - 1)+ xs = self.XX if xs is None else xs+ return _sample(self.img, xs, ys), _sample(self.emi, xs, ys)++ def floor(self, colour=MAGENTA, spacing=(2.4, 2.4), width=0.07, base='#12031f', haze=None, fog=150.0,+ level=1.0, scroll=0.0, gloss=0.3, x_range=(None, None)):+ """the neon grid: lines along Z every spacing[0] m and across it every spacing[1] m, `width` m wide,+ on a dark glossy floor fading into a pink haze toward the horizon; a soft streak of the sun on it"""+ hz = _c(haze) if haze is not None else self.horizon_col * 0.55 + _c(MAGENTA) * 0.25+ sx, sz = spacing+ T = np.exp(-self.Zg / fog)[..., None]+ near = np.clip((self.YY - self.hy) / (self.H - self.hy), 0, 1)+ basec = _c(base) * (0.8 + 0.4 * near[..., None])+ col = basec * T + hz * 0.6 * (1 - T)+ Ll = self._lines(self.Xg / sx, self.dXdx / sx, self.dXdy / sx, width / (2 * sx))+ Lt = self._lines((self.Zg - scroll) / sz, 0.0, self.dZdy / sz, width / (2 * sz))+ Lg = 1 - (1 - Ll) * (1 - Lt)+ vis = T ** 0.55+ lc = _c(colour)+ col = col * (1 - Lg[..., None] * vis) + lc * 1.45 * (Lg[..., None] * vis)+ em = lc * (Lg[..., None] * vis) * level+ if self.sun_info and gloss:+ x, y, r = self.sun_info+ wdt = r * (0.55 + 0.6 * near)+ st = np.exp(-((self.XX - x) / wdt) ** 2) * np.exp(-near * 2.2) * gloss+ col = col + _c('#ff6a6a') * st[..., None]+ hl = np.exp(-((self.YY - self.hy) / 2.2) ** 2) + 0.4 * np.exp(-((self.YY - self.hy) / 9) ** 2)+ col = col + hz * 0.6 * hl[..., None]; em = em + hz * 0.5 * hl[..., None]+ a = self._region(*x_range)+ self._over(a, col, emit=0.0)+ self.emi += em * a[..., None]++ def neon_line(self, X, colour=CYAN, width=0.12, level=1.1, dash=None, fog=140.0):+ """a neon line lying on the ground along Z at X (coastline, road edge); dash=(on, period) metres"""+ g = self.Xg - X+ cov = self._lines(g / 1000.0, self.dXdx / 1000.0, self.dXdy / 1000.0, width / 2000.0) * (np.abs(g) < 500)+ if dash:+ on, per = dash+ ph = np.mod(self.Zg, per)+ dz = np.abs(self.dZdy) + 1e-6+ cov = cov * np.clip(np.minimum(ph, on - ph) / dz + 0.5, 0, 1) * (1 - smoothstep(0.5, 2.0, dz / per * 4)) \+ + cov * (on / per) * smoothstep(0.5, 2.0, dz / per * 4)+ cov = cov * self.below+ T = np.exp(-self.Zg / fog) ** 0.5+ c = _c(colour)+ self._over(cov * T, c * 1.45, emit=level)++ def sea(self, coast=-9.0, base='#0a0520', reflect=(0.45, 0.95), bar=(4.0, 0.9), ripple=1.0, stretch=1.0,+ spread=0.5, sky=0.75, glitter=1.8, lines=0.16, line_colour=CYAN, seed=None):+ """water on the side X < coast: the sky, sun and far shore mirrored about the horizon and torn into+ horizontal bars. The water is cut into world bands bar[1] m deep; every band shifts sideways and is+ stretched or squeezed about the sun's column by up to +-spread, so the sun's reflection becomes a stack+ of glowing strokes of different lengths instead of a second disc; dashes bar[0] m long break them up.+ Light sources (the emission buffer) reflect `glitter` times stronger than the sky (`sky`)."""+ sd = self._seed() if seed is None else seed+ near = np.clip((self.YY - self.hy) / (self.H - self.hy), 0, 1)+ band = self.Zg / bar[1]+ bpx = np.abs(self.dZdy) / bar[1] # bands per pixel+ res = 1 - smoothstep(0.25, 0.8, bpx) # 1 where bands are resolved+ bi = np.floor(band); fr = band - bi+ one = np.ones_like(band)+ cx = self.sun_info[0] if self.sun_info else self.vx+ sc = 1 + (_vnoise(bi * 0.83, one * 1.5, sd + 3) - 0.5) * 2 * spread * (0.5 + 1.2 * near) * res+ dx = (_vnoise(bi * 0.9, one * 0.5, sd) - 0.5) * (6 + 50 * near) * ripple * res+ dx += (_vnoise(band * 0.23, one * 3.5, sd + 1) - 0.5) * (3 + 20 * near) * ripple+ m = smoothstep(0.3, 0.5, _vnoise(self.Xg / bar[0] + bi * 1.7, bi * 0.37 + 0.5, sd + 2))+ gap = smoothstep(0.0, 0.25, fr) * smoothstep(1.0, 0.75, fr)+ m = (m * (0.15 + 0.85 * gap)) * res + 0.5 * (1 - res)+ mir, mem = self._mirror(stretch, cx + (self.XX - cx) * sc + dx)+ mir = _blur_axis(_blur_axis(mir, 1.2, 0), 2.0, 1); mem = _blur_axis(_blur_axis(mem, 2.0, 0), 3.0, 1)+ R = reflect[0] + (reflect[1] - reflect[0]) * (1 - near) ** 2.5+ k = (0.08 + 0.92 * m) * R+ col = _c(base) * (1 - 0.5 * R[..., None]) + (mir * sky + mem * glitter) * k[..., None]+ em = mem * (k * 1.2)[..., None]+ if lines:+ Lt = self._lines(self.Zg / 3.0, 0.0, self.dZdy / 3.0, 0.03)+ T = np.exp(-self.Zg / 60.0) ** 0.5+ col = col + _c(line_colour) * (Lt * T * lines)[..., None]+ em = em + _c(line_colour) * (Lt * T * lines * 0.6)[..., None]+ a = self._region(None, coast)+ self._over(a, col, emit=0.0)+ self.emi = self.emi + em * a[..., None]++ def road(self, x0, x1, surface='#0b0316', edge=CYAN, centre='#ffe6a0', dash=(3.0, 8.0), gloss=0.35, level=1.0):+ """a glossy two-lane road between x0 and x1 (metres): blurred reflection, neon edges, dashed centre"""+ near = np.clip((self.YY - self.hy) / (self.H - self.hy), 0, 1)+ mir, mem = self._mirror(0.8)+ mir = _blur_axis(_blur_axis(mir, 16, 0), 2.5, 1)+ R = gloss * (0.35 + 0.65 * (1 - near) ** 2)+ col = _c(surface) * (0.8 + 0.4 * near[..., None]) + mir * R[..., None]+ a = self._region(x0, x1)+ self._over(a, col)+ self.emi += _blur_axis(mem, 16, 0) * (R * 0.5 * a)[..., None]+ self.neon_line(x0, edge, 0.14, level); self.neon_line(x1, edge, 0.14, level)+ self.neon_line((x0 + x1) / 2, centre, 0.12, level * 0.7, dash=dash)++ # ------------------------------------------------------------ objects+ def palm(self, X, Z, height=11.0, lean=0.1, fronds=10, seed=None, colour='#0a0314', rim='#ff5a8a', rim_side=None,+ spread=1.0, ss=3):+ """a palm silhouette standing at ground point (X, Z): tapered ring-notched trunk leaning by `lean`+ (fraction of height, + is right), a crown of drooping fronds with hanging leaflets, coconuts, and a thin+ rim of sunset light on the side facing the sun"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ s = self.f / Z+ bx, by = self.project(X, 0, Z)+ crown = 4.6 * spread+ x0p = bx - (crown + abs(lean) * height + 1) * s; x1p = bx + (crown + abs(lean) * height + 1) * s+ y0p = by - (height + crown * 0.8) * s; y1p = by + 3+ im, d, (ox, oy), T = self._canvas(x0p, y0p, x1p, y1p, ss)+ # trunk centreline (metres, y up) -> pixels+ u = np.linspace(0, 1, 90)+ bend = r.uniform(-0.04, 0.04) * height+ cxm = lean * height * u ** 1.7 + bend * np.sin(np.pi * u)+ cym = height * u+ px = bx + cxm * s; py = by - cym * s+ tx = np.gradient(px); ty = np.gradient(py); tl = np.hypot(tx, ty) + 1e-6; nx, ny = -ty / tl, tx / tl+ ring = 1 - 0.14 * (np.mod(cym / 0.32, 1.0) < 0.3)+ half = (0.27 - 0.12 * u + 0.12 * np.exp(-u / 0.05)) * s * ring+ left = [T(px[i] + nx[i] * half[i], py[i] + ny[i] * half[i]) for i in range(len(u))]+ right = [T(px[i] - nx[i] * half[i], py[i] - ny[i] * half[i]) for i in range(len(u))][::-1]+ d.polygon(left + right, fill=255)+ topx, topy = px[-1], py[-1]++ def blade(p0, p1, w0, w1):+ p0 = np.array(p0); p1 = np.array(p1); dv = p1 - p0; L = np.hypot(*dv) + 1e-6; nv = np.array([-dv[1], dv[0]]) / L+ d.polygon([T(*(p0 + nv * w0)), T(*(p1 + nv * w1)), T(*(p1 - nv * w1)), T(*(p0 - nv * w0))], fill=255)+ # fronds spread evenly round the crown (azimuth phi: 0 = to the right, pi/2 = toward the camera)+ az = np.linspace(0, 2 * np.pi, fronds, endpoint=False) + r.uniform(0, 2 * np.pi) + r.normal(0, 0.18, fronds)+ elevs = np.linspace(1.05, 0.12, fronds - 2)[r.permutation(fronds - 2)] # a spread from steep to flat fronds+ for k, phi in enumerate(az):+ dead = k < 2 # two old fronds hang down the trunk+ L = r.uniform(3.8, 4.8) * spread * (0.75 if dead else 1)+ elev = r.uniform(-0.6, -0.3) if dead else elevs[k - 2] + r.normal(0, 0.08)+ droop = (r.uniform(0.9, 1.2) + 0.5 * elev) if not dead else r.uniform(0.6, 0.9)+ beta = r.uniform(0.7, 0.95) if not dead else 1.25 # how steeply the leaflets hang+ t = np.linspace(0, 1, 30)+ hor = L * t * np.cos(elev)+ ver = L * (np.sin(elev) * t - droop * 0.5 * t * t)+ fx = topx + hor * np.cos(phi) * s; fy = topy - ver * s # cos(phi): foreshortened toward camera+ for i in range(len(t) - 1):+ blade((fx[i], fy[i]), (fx[i + 1], fy[i + 1]), 0.075 * s * (1 - 0.75 * t[i]), 0.075 * s * (1 - 0.75 * t[i + 1]))+ # leaflets on both sides, built in 3D and projected: a sweep along the rachis toward the tip, a+ # sideways part (only seen when the frond points at us) and a droop+ dh = np.gradient(hor); dv = np.gradient(ver); dl = np.hypot(dh, dv) + 1e-6; dh /= dl; dv /= dl+ side = np.array([-np.sin(phi), 0.0, np.cos(phi)])+ for i in range(2, len(t) - 1):+ ll = (0.3 + 1.1 * np.sin(np.pi * min(1.0, t[i] * 1.02)) ** 0.7) * (1 - 0.2 * t[i]) * spread * (0.75 if dead else 1)+ tan = np.array([np.cos(phi) * dh[i], dv[i], np.sin(phi) * dh[i]])+ for sgn in (-1, 1):+ b = beta + r.normal(0, 0.06)+ v3 = tan * 0.62 + side * sgn * np.cos(b) + np.array([0.0, -np.sin(b), 0.0])+ v3 /= np.linalg.norm(v3)+ blade((fx[i], fy[i]), (fx[i] + v3[0] * ll * s, fy[i] - v3[1] * ll * s), 0.05 * s, 0.006 * s)+ for _ in range(4): # coconuts+ cx_ = topx + r.normal(0, 0.18) * s; cy_ = topy + r.uniform(0.1, 0.45) * s; rr = 0.19 * s+ d.ellipse([T(cx_ - rr, cy_ - rr), T(cx_ + rr, cy_ + rr)], fill=255)+ A = self._down(im, ss)+ self._over(A, _c(colour), at=(ox, oy))+ # rim light on the side facing the sun+ if rim:+ sgn = rim_side if rim_side is not None else (-1 if (self.sun_info and self.sun_info[0] < bx) else 1)+ k = max(1.2, 0.08 * s)+ rimm = np.clip(A - shift(A, -sgn * k, k * 0.6), 0, 1) * A+ self._over(rimm, _c(rim), emit=0.9, at=(ox, oy))++ def car(self, X, Z, body='#10041c', light=RED, level=2.2, ss=4):+ """a low 80s coupe seen from behind: body, cabin, full-width tail-light bar, and the lights' streak+ reflected in the glossy road below"""+ s = self.f / Z+ bx, by = self.project(X, 0, Z)+ im, d, (ox, oy), T = self._canvas(bx - 1.3 * s, by - 1.5 * s, bx + 1.3 * s, by + 0.2 * s, ss)+ lt = Image.new('L', im.size); dl = ImageDraw.Draw(lt)+ hl = Image.new('L', im.size); dh = ImageDraw.Draw(hl)+ P = lambda mx, my: T(bx + mx * s, by - my * s)+ d.polygon([P(-0.92, 0.18), P(-0.95, 0.62), P(-0.86, 0.78), P(0.86, 0.78), P(0.95, 0.62), P(0.92, 0.18)], fill=255)+ d.polygon([P(-0.66, 0.78), P(-0.48, 1.12), P(0.48, 1.12), P(0.66, 0.78)], fill=255) # cabin+ d.rectangle([P(-0.86, 0.2), P(-0.56, 0.0)], fill=255); d.rectangle([P(0.56, 0.2), P(0.86, 0.0)], fill=255) # tyres+ dh.polygon([P(-0.62, 0.8), P(-0.47, 1.1), P(0.47, 1.1), P(0.62, 0.8)], fill=110) # rear glass catches the sky+ dh.line([P(-0.86, 0.77), P(0.86, 0.77)], fill=200, width=max(1, int(0.05 * s * ss)))+ dl.rectangle([P(-0.9, 0.62), P(0.9, 0.5)], fill=255) # tail-light bar+ dh.rectangle([P(-0.18, 0.4), P(0.18, 0.28)], fill=90) # plate+ A = self._down(im, ss); Lm = self._down(lt, ss) * A; Hm = self._down(hl, ss) * A+ self._over(A, _c(body), at=(ox, oy))+ sl = (slice(oy, oy + A.shape[0]), slice(ox, ox + A.shape[1]))+ self.img[sl] += Hm[..., None] * _c('#b04aa0') * 0.5+ lc = _c(light)+ self.img[sl] = self.img[sl] * (1 - Lm[..., None]) + lc * 1.6 * Lm[..., None]+ self.emi[sl] += lc * level * Lm[..., None]+ # the tail lights smeared down the glossy road+ ly = by - 0.56 * s+ wdt = 0.9 * s+ st = np.exp(-((self.XX - bx) / wdt) ** 8) * smoothstep(by + 1, by + 4, self.YY) * np.exp(-(self.YY - by) / (4.5 * s))+ st *= (_vnoise(self.YY / 2.5, self.XX / 9.0, 5) * 0.7 + 0.3)+ self.img += lc * (st * 0.55)[..., None]; self.emi += lc * (st * 0.6)[..., None]++ # ------------------------------------------------------------ lettering+ def chrome_text(self, s, x, y, size, spacing=0.02, italic=0.22, depth=18, direction=(0.3, 1.0),+ sky=('#0e2a78', '#3f95ff', '#e9f8ff'), ground=('#3a0c30', '#ff4f96', '#ffd98a'), horizon=0.54,+ rim='#ffe6f6', keyline='#090318', side=('#ff3fae', '#2a0636'), glow=MAGENTA, level=0.4,+ glints=(0, 4, 8), bevel=1.0):+ """80s chrome caps centred on (x, y) (the middle of the cap height). The face mirrors a sky (deep blue+ to almost white) above a sharp horizon and a warm ground below it; a stepped extrusion `depth` px along+ `direction`, a dark keyline, a pale rim that glows, a bevel lit from the upper left, and four-point+ glints at the top-left corners of the letters listed in `glints`."""+ font, is_it = synth_font('chrome', size)+ sp = spacing * size+ adv = [font.getlength(ch) + sp for ch in s]+ tw = sum(adv) - sp+ cap = -font.getbbox('H', anchor='ls')[1]+ pad = int(depth * 1.6 + size * 0.5)+ w, h = int(tw + 2 * pad + size * 0.4), int(cap * 1.6 + 2 * pad)+ base_y = pad + cap * 1.25+ x_l = pad + size * 0.2+ im = Image.new('L', (w, h), 0); dd = ImageDraw.Draw(im)+ xs = [x_l]+ for a in adv[:-1]: xs.append(xs[-1] + a)+ for ch, xx in zip(s, xs): dd.text((xx, base_y), ch, font=font, fill=255, anchor='ls')+ sh = 0.0 if is_it else italic+ if sh:+ im = im.transform(im.size, Image.AFFINE, (1, sh, -sh * base_y, 0, 1, 0), resample=Image.BICUBIC)+ M = np.asarray(im, np.float32) / 255+ ox = int(round(x - (x_l + tw / 2))); oy = int(round(y - (base_y - cap / 2)))+ YL = np.arange(h, dtype=np.float32)[:, None] + np.zeros((1, w), np.float32)+ XL = np.arange(w, dtype=np.float32)[None, :] + np.zeros((h, 1), np.float32)+ # extrusion + keyline+ ddx, ddy = direction+ ext = M.copy()+ for k in range(1, depth + 1): ext = np.maximum(ext, shift(M, ddx * k, ddy * k))+ self._over(_dilate(ext, 3), _c(keyline), at=(ox, oy))+ s0, s1 = _c(side[0]), _c(side[1])+ for k in range(depth, 0, -1):+ lay = shift(M, ddx * k, ddy * k)+ t = k / depth+ vv = np.clip((YL - (base_y - cap)) / (cap + depth), 0, 1)[..., None]+ c = s0 * (1 - t) + s1 * t+ c = c * (1.1 - 0.5 * vv)+ self._over(lay, c, at=(ox, oy))+ # rim (glows)+ rimm = _dilate(M, 2)+ self._over(rimm, _c(rim), emit=0.0, at=(ox, oy))+ sl = (slice(max(0, oy), min(self.H, oy + h)), slice(max(0, ox), min(self.W, ox + w)))+ crop = (slice(sl[0].start - oy, sl[0].stop - oy), slice(sl[1].start - ox, sl[1].stop - ox))+ halo = np.clip(_dilate(M, 4) - M * 0.7, 0, 1)+ self.emi[sl] += (halo[crop] * level)[..., None] * _c(glow)+ # face: sky / horizon / ground reflection, then bevel light+ v = (YL - (base_y - cap)) / cap+ vs = np.clip(v / horizon, 0, 1); vg = np.clip((v - horizon) / (1 - horizon), 0, 1)+ skyc = _stops(vs, [(0, sky[0]), (0.6, sky[1]), (1, sky[2])])+ grc = _stops(vg, [(0, ground[0]), (0.45, ground[1]), (1, ground[2])])+ face = np.where((v < horizon)[..., None], skyc, grc)+ edge = np.exp(-(((v - horizon) * cap) / 1.8) ** 2)+ face = face * (1 - 0.6 * edge[..., None])+ above = np.exp(-(((horizon - v) * cap - 3.5) / 2.2) ** 2) * (v < horizon)+ face = face + (1.0 - face) * (0.7 * above)[..., None]+ hb = blur(M, max(1.5, size * 0.03))+ gy_, gx_ = np.gradient(hb)+ lit = np.clip(-(gx_ * -0.6 + gy_ * -0.8) * size * 0.09, -1, 1) * bevel+ face = face + (1.0 - face) * np.clip(lit, 0, 1)[..., None] * 0.85+ face = face * (1 - 0.45 * np.clip(-lit, 0, 1))[..., None]+ self._over(M, face, at=(ox, oy))+ # glints+ for gi in glints:+ if gi >= len(s): continue+ x_a, x_b = xs[gi], xs[gi] + (adv[gi] - sp) * 0.6+ cols = (XL >= x_a) & (XL <= x_b) & (M > 0.6)+ if not cols.any(): continue+ score = np.where(cols, YL + 0.35 * (XL - x_a), 1e9)+ j = np.unravel_index(np.argmin(score), score.shape)+ self.glint(ox + j[1] + 2, oy + j[0] + 2, size * 0.32)++ def glint(self, x, y, length, colour=WHITE, level=1.3):+ """a four-point star flare (long horizontal and vertical spikes, short diagonals)"""+ L = length+ sl = (slice(max(0, int(y - L)), min(self.H, int(y + L) + 1)), slice(max(0, int(x - L)), min(self.W, int(x + L) + 1)))+ dx = self.XX[sl] - x; dy = self.YY[sl] - y+ sp = np.exp(-np.abs(dx) / (L * 0.22)) * np.exp(-(dy / 1.1) ** 2) + np.exp(-np.abs(dy) / (L * 0.22)) * np.exp(-(dx / 1.1) ** 2)+ u = (dx + dy) / 1.414; v = (dx - dy) / 1.414+ sp += 0.35 * (np.exp(-np.abs(u) / (L * 0.08)) * np.exp(-(v / 0.9) ** 2) + np.exp(-np.abs(v) / (L * 0.08)) * np.exp(-(u / 0.9) ** 2))+ sp += 1.4 * np.exp(-(dx * dx + dy * dy) / (L * 0.05) ** 2)+ c = _c(colour)+ self.img[sl] += (sp * level)[..., None] * c; self.emi[sl] += (sp * level * 0.6)[..., None] * c++ def neon_script(self, s, x, y, size, colour=PINK, rot=8.0, anchor='mm', level=1.1, core=0.5, breaks=0, seed=None):+ """a neon tube in brush script: a coloured tube with a white-hot core; breaks=n paints n dark joints+ over the glass (as on real signs; off by default, it easily reads as a rendering fault)"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ font, _ = synth_font('script', size)+ M = text_mask(self.H, self.W, s, font, (x, y), anchor=anchor, rot=rot)+ ys, xs = np.nonzero(M > 0.5)+ for _ in range(breaks if len(xs) else 0):+ i = int(r.integers(0, len(xs)))+ gx, gy = xs[i], ys[i]+ cut = np.exp(-(((self.XX - gx) * np.cos(0.4) + (self.YY - gy) * np.sin(0.4)) / 1.4) ** 2) * (np.hypot(self.XX - gx, self.YY - gy) < size * 0.12)+ M = M * (1 - 0.85 * cut)+ cm = smoothstep(0.75, 0.98, blur(M, max(1.0, size * 0.014))) * M+ c = _c(colour)+ tube = c * 1.25 + (1 - c) * 0.1+ col = tube[None, None] * (1 - core * cm[..., None]) + _c(WHITE) * 1.3 * (core * cm[..., None])+ self._over(M, col, emit=level)++ def caption(self, s, x, y, size, colour=CYAN, spacing=0.35, anchor='mm', rules=(90, 22), level=0.45, font='caption'):+ """a letter-spaced line of small type with thin rules on both sides"""+ f, _ = synth_font(font, size) if font in _FONTS else (load_font(font, size), False)+ sp = spacing * size+ M = text_mask(self.H, self.W, s, f, (x, y), anchor=anchor, spacing=sp)+ c = _c(colour)+ if rules:+ tw = sum(f.getlength(ch) + sp for ch in s) - sp+ x0 = x - tw * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ L, g = rules+ yr = y + (size * 0.05 if anchor[1] == 'm' else 0)+ for a, b in ((x0 - g - L, x0 - g), (x0 + tw + g, x0 + tw + g + L)):+ M = np.maximum(M, np.clip(1.1 - np.abs(self.YY - yr), 0, 1) * np.clip(np.minimum(self.XX - a, b - self.XX) + 0.5, 0, 1)+ * smoothstep(0, L * 0.6, np.where(a < x0, self.XX - a, b - self.XX)))+ self._over(M, c * 1.2, emit=level)++ def osd(self, s, x, y, px=6, colour=WHITE, anchor='la'):+ """VCR on-screen display text in a 5x7 block font (drawn onto the finished frame, over the tape noise)"""+ self.osd_items.append((s, x, y, px, colour, anchor))++ def _osd_mask(self, s, x, y, px, anchor):+ w = len(s) * 6 * px - px; h = 7 * px+ x0 = x - w * {'l': 0, 'm': 0.5, 'r': 1}[anchor[0]]; y0 = y - h * {'a': 0, 'm': 0.5, 'b': 1}.get(anchor[1], 0)+ m = np.zeros((self.H, self.W), np.float32)+ for k, ch in enumerate(s.upper()):+ g = _OSD.get(ch, _OSD[' ']).split('|')+ for j, row in enumerate(g):+ for i, c in enumerate(row):+ if c != '#': continue+ xa = int(round(x0 + (k * 6 + i) * px)); ya = int(round(y0 + j * px))+ m[max(0, ya):max(0, ya + px), max(0, xa):max(0, xa + px)] = 1+ return m++ # ------------------------------------------------------------ tape and output+ def vhs(self, bleed=3.5, shift_px=3.0, ghost=0.06, jitter=0.35, noise=0.014, scan=0.1, pitch=3.0,+ tracking=(0.83, 12, 5.0), head=12, dropouts=14, seed=None):+ """play the finished frame back off tape: chroma bleed and shift, ghost and ringing, line jitter, one+ tracking band (y as a fraction of H, height px, shift px), head-switching noise, noise, dropouts, OSD,+ scanlines. Only the finished frame gets this; stage snapshots stay clean."""+ self.vhs_opts = dict(bleed=bleed, shift_px=shift_px, ghost=ghost, jitter=jitter, noise=noise, scan=scan, pitch=pitch,+ tracking=tracking, head=head, dropouts=dropouts, seed=self._seed() if seed is None else seed)++ def _tape(self, out):+ o = self.vhs_opts; H, W = self.H, self.W+ r = np.random.default_rng(o['seed'])+ Y = out @ np.array([0.299, 0.587, 0.114], np.float32)+ I = out @ np.array([0.596, -0.274, -0.322], np.float32)+ Q = out @ np.array([0.211, -0.523, 0.312], np.float32)+ Yb = _blur_axis(Y, 0.8, 1)+ Yb = Yb * (1 - o['ghost']) + shift(Yb, 9, 0) * o['ghost']+ Yb = Yb + 0.35 * (Yb - _blur_axis(Yb, 2.2, 1)) # playback sharpening rings at edges+ I = shift(_blur_axis(_blur_axis(I, o['bleed'], 1), 0.8, 0), o['shift_px'], 0)+ Q = shift(_blur_axis(_blur_axis(Q, o['bleed'] * 1.3, 1), 0.8, 0), o['shift_px'] * 1.4, 0)+ rows = np.arange(H, dtype=np.float32)+ off = (_vnoise(rows / 3.0, np.zeros(H), o['seed']) - 0.5) * 2 * o['jitter']+ ty, th, tsh = o['tracking']; ty = ty * H+ tb = np.exp(-((rows - ty) / th) ** 2)+ off += tb * tsh * (0.6 + 0.8 * _vnoise(rows / 1.5, np.ones(H), o['seed'] + 1))+ hb = rows >= H - o['head']+ off += hb * (8 + 14 * (_vnoise(rows / 2.0, np.full(H, 2.0), o['seed'] + 2)))+ xs = self.XX - off[:, None]+ Yb, I, Q = _sample(Yb, xs, self.YY), _sample(I, xs, self.YY), _sample(Q, xs, self.YY)+ n = _blur_axis(r.normal(0, 1, (H, W)).astype(np.float32), 2.5, 1); n /= n.std() + 1e-6+ Yb = Yb + n * o['noise'] * (0.5 + 0.8 * np.sqrt(np.clip(Yb, 0, 1)))+ spk = (r.random((H, W)) < 0.02).astype(np.float32)+ spk = _blur_axis(spk, 3.0, 1) * 4+ Yb = Yb + spk * (tb[:, None] * 0.35 + hb[:, None] * 0.5)+ Yb[hb] *= 0.8+ for _ in range(o['dropouts']): # oxide dropouts: short white streaks+ yy = int(r.integers(0, H)); xx = int(r.integers(0, W)); L = int(r.integers(12, 70))+ Yb[yy, xx:xx + L] += np.linspace(0.6, 0.0, len(Yb[yy, xx:xx + L])) * r.uniform(0.3, 0.8)+ out = np.stack([Yb + 0.956 * I + 0.621 * Q, Yb - 0.272 * I - 0.647 * Q, Yb - 1.106 * I + 1.703 * Q], -1)+ # OSD: drawn by the deck, crisp-ish, with a dark edge+ for (s, x, y, px, colour, anchor) in self.osd_items:+ m = self._osd_mask(s, x, y, px, anchor)+ sh = np.clip(shift(m, px * 0.5, px * 0.5) + _gblur(m, px * 0.5) * 0.6, 0, 1)+ m = blur(m, 0.6)+ out = out * (1 - 0.75 * sh[..., None])+ out = out * (1 - m[..., None]) + _c(colour) * 0.95 * m[..., None]+ # CRT scanlines, lifted blacks+ out = out * (1 - o['scan'] * (0.5 + 0.5 * np.cos(2 * np.pi * self.YY / o['pitch'])))[..., None]+ out = 0.03 + out * 0.96+ return out++ def _tone(self, x):+ over = np.clip(x - 1.0, 0, None).sum(-1, keepdims=True)+ x = x + over * 0.28 # over-driven channels spill: cores go white+ k = 0.8+ return np.clip(np.where(x < k, x, k + (1 - k) * (1 - np.exp(-(x - k) / (1 - k)))), 0, 1)++ def render(self, final=True):+ e = self.emi+ bloom = _gblur(e, 3) * 0.5 + _gblur(e, 10) * 0.42 + _gblur(e, 32) * 0.34 + _gblur(e, 100) * 0.28+ out = self._tone(self.img + bloom)+ rr = np.hypot((self.XX - self.W / 2) / (self.W / 2), (self.YY - self.H / 2) / (self.H / 2)) / np.sqrt(2)+ out = out * (1 - 0.3 * rr ** 2.4)[..., None]+ if final and self.vhs_opts: out = self._tape(out)+ return np.clip(out, 0, 1)++ def composite(self, final=True):+ return Image.fromarray((self.render(final) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ if self.record: self.stages.append((name, self.composite(final=False)))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite(final=True)+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return img