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 clay, cyanotype, cross-stitch and retro-panel styles; one example per style
cloveric36ffa9b62a98
diff --git a/README.md b/README.mdindex db0fe32..fa1e40e 100644--- a/README.md+++ b/README.md@@ -1,17 +1,19 @@# Claude Drawing · Claude 绘图-**Claude paints with code — no image model.** Nine styles, from ink wash to pixel art.-**不用生图模型,Claude 用代码一笔一笔作画。** 九种画风,从水墨到像素。+**Claude paints with code — no image model.** Thirteen styles, from ink wash and impasto oil to clay, cyanotype and cross-stitch.+**不用生图模型,Claude 用代码一笔一笔作画。** 十三种画风,从水墨、油画到黏土、蓝晒和十字绣。[English](#english) · [中文](#中文)-| Ink wash · 水墨 | Watercolour · 水彩 | Paper collage · 剪纸拼贴 |-|---|---|---|-|  |  |  |-| **Coloured pencil · 韩国彩铅** | **Anime · 日本动漫** | **Editorial · 编辑风手绘** |-|  |  |  |-| **Impasto oil · 油画厚涂** | **Ukiyo-e · 浮世绘木版画** | **Pixel art · 像素风** |-|  |  |  |+<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>++| Watercolour · 水彩 | Paper collage · 剪纸拼贴 | Coloured pencil · 韩国彩铅 | Anime · 日本动漫 |+|---|---|---|---|+|  |  |  |  |+| **Editorial · 编辑风手绘** | **Impasto oil · 油画厚涂** | **Ukiyo-e · 浮世绘木版画** | **Pixel art · 像素风** |+|  |  |  |  |+| **Stop-motion clay · 黏土定格** | **Cyanotype · 蓝晒** | **Cross-stitch · 十字绣** | **Retro panel · 复古仪器面板** |+|  |  |  |  |### Gallery · 画廊@@ -27,8 +29,12 @@| <img src="examples/editorial_ideas.jpg" width="100%"> | <img src="examples/oil_wheatfield.jpg" width="100%"> || **富士曙** · *Fuji at Dawn*<br><sub>Ukiyo-e · 浮世绘</sub> | **雨夜咖啡店** · *Rainy Night Cafe*<br><sub>Pixel art · 像素风</sub> || <img src="examples/ukiyoe_fuji.jpg" width="100%"> | <img src="examples/pixel_rainy_cafe.png" width="100%"> |+| **灯塔岛** · *Lighthouse Island*<br><sub>Stop-motion clay · 黏土定格</sub> | **蓝晒植物** · *Sun-Print Botanicals*<br><sub>Cyanotype · 蓝晒</sub> |+| <img src="examples/clay_lighthouse.jpg" width="100%"> | <img src="examples/cyanotype_botanicals.jpg" width="100%"> |+| **家** · *Home Sampler*<br><sub>Cross-stitch · 十字绣</sub> | **Aurora 64 收音机** · *Aurora 64 Radio*<br><sub>Vintage instrument panel · 复古仪器面板</sub> |+| <img src="examples/stitch_sampler.jpg" width="100%"> | <img src="examples/panel_radio.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. 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.+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. 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.---@@ -36,7 +42,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 nine styles:+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with thirteen styles:| Style | Module | What makes it read as the real medium ||---|---|---|@@ -49,6 +55,10 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra| **Impasto oil** | `lib/oilpaint.py` · `OilPainting` | thousands of strokes following a *flow field*; each pixel knows its place inside its stroke → flat-topped paint ridges, bristle grooves, heavier paint where the brush lands; lit relief || **Ukiyo-e woodblock** | `lib/ukiyoe.py` · `Ukiyoe` | one block per colour on washi, with wood grain and registration drift; *bokashi* graded wipes; black key-block outlines; seigaiha waves; cloud bands; title cartouche and seal || **Pixel art** | `lib/pixelart.py` · `PixelArt` | a 320×180 canvas painted pixel by pixel; limited palette; ordered (Bayer) dithering for gradients, glows and reflections; 3×5 bitmap font; crisp ×6 upscale |+| **Stop-motion clay** | `lib/clay.py` · `Clay` | a *height map* of pressed pieces (pads, balls, rolled snakes, puffy letters, finger-smeared slabs, tool grooves, pokes) with lumps and fingerprints; lit like a photo of a set: wrap-diffuse key + cool fill, waxy sheen, shadows marched through the height field, ambient occlusion |+| **Cyanotype (sun print)** | `lib/cyanotype.py` · `Cyanotype` | emulsion brushed on in strokes with dry-brush ends; objects *block UV* (transmissions multiply): translucent leaves with whiter veins, fluff lifted off the paper with a soft penumbra, light scattering under edges; a Prussian-blue density curve; white handwriting printed in, pencil notes on the margin |+| **Cross-stitch embroidery** | `lib/stitch.py` · `Stitch` | Aida cloth with a hole at every block corner; one X per cell, lit as round twisted thread with a shadow, in hand-made variants; half stitches; back-stitch snapped hole to hole; padded glossy satin stitch; French knots; ASCII charts and a 5×7 sampler alphabet; a sewn-on woven label |+| **Vintage instrument panel** | `lib/panel.py` · `Panel` | teak veneer, brushed aluminium, moulded plastic, grille cloth with lurex floats, perforated metal; bevels, wells and drop shadows from one key light; machined knobs, piano keys, toggle switch, jewel lamp, magic-eye tube, meter; silkscreened scales and a backlit dial behind glass |Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:@@ -70,7 +80,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`.+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.### Quick start@@ -113,6 +123,10 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages- **Oil**: lay big strokes first, then smaller ones, then detail only where it matters. Keep the relief modest (flat-topped ridges, soft speculars), or strokes turn into plastic tubes.- **Ukiyo-e**: flat colour blocks plus bokashi only on skies and seas. Clouds are opaque bands. The key block outlines everything, and a cartouche and seal sit in the empty sky.- **Pixel art**: paint at the true low resolution and dither instead of blending. Keep glows small (a big dither glow turns into a square). Upscale with nearest-neighbour only.+- **Clay**: think in heights (px) and let pieces drape over what is below. Finger smears must be wide, soft and few, or the sky turns into crumpled foil. Never wrap non-tileable noise: it leaves straight seams.+- **Cyanotype**: think in UV transmission, not paint. Thin leaves ~0.85 opacity with fully blocking veins; lift fluff off the paper for a soft penumbra. A fern pinna is one lobed blade, not a row of separate leaflets. Dry-brush stroke ends are crisp broken streaks, not a blur.+- **Cross-stitch**: everything lives on the hole grid. Never lay half stitches over cross stitches (switch floss colour instead). A short diagonal back-stitch is one stitch from hole to hole, or it snaps into L-shaped steps.+- **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.### Roadmap@@ -124,7 +138,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,加上一个小巧的绘图库,内置十三种画风:| 画风 | 模块 | 为什么看起来像真的 ||---|---|---|@@ -137,6 +151,10 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages| **油画厚涂** | `lib/oilpaint.py` · `OilPainting` | 几万道笔触顺着**流向图**排列;每个像素都知道自己在笔触里的位置,算出平顶鼓边的颜料、笔毛沟、落笔处更厚的颜料,再打光出凸起 || **浮世绘木版画** | `lib/ukiyoe.py` · `Ukiyoe` | 每种颜色一块版,印在和纸上,带木纹和套印偏移;天空和海面用**晕色(bokashi)**;墨色主版勾线;青海波纹;横向云带;标题签和朱印 || **像素风** | `lib/pixelart.py` · `PixelArt` | 在 320×180 的小画布上逐像素作画;有限调色板;渐变、光晕、倒影都用 Bayer 抖动;3×5 像素字体;无插值放大 6 倍 |+| **黏土定格** | `lib/clay.py` · `Clay` | 用**高度图**一块块捏:压平的泥片、小球、搓条、鼓起的黏土字、手指抹开的泥面、刻线和戳洞,表面带小疙瘩和指纹;再像拍定格动画一样打光:暖色主光+冷色补光、蜡质光泽、沿光线步进算出的投影、缝隙里的环境光遮蔽 |+| **蓝晒** | `lib/cyanotype.py` · `Cyanotype` | 药水一笔笔刷上去,笔尾是干刷的断续刷丝;放上去的东西**挡紫外线**(透过率相乘):薄叶透一点光、叶脉更白,蒲公英绒毛离纸有距离、边缘柔和,边缘下还有散射;按普鲁士蓝的显影曲线上色;白色手写字一起晒出来,纸边再加铅笔字 |+| **十字绣** | `lib/stitch.py` · `Stitch` | Aida 布,每个布块四角有孔;每格一个 X,线按扭绞的圆线打光并投下小影子,还有几种手工误差;半针;回针沿孔走、一针从孔到孔;鼓起有光泽的缎面绣;法式结;字符图样和 5×7 刺绣字母;缝上去的织标 |+| **复古仪器面板** | `lib/panel.py` · `Panel` | 柚木贴皮、拉丝铝、注塑塑料、带金丝的喇叭布、冲孔网;同一盏主光照出倒角、凹槽和投影;车削旋钮、琴键、拨杆开关、宝石指示灯、绿色魔眼管、指针表;丝印刻度、玻璃后面的背光刻度窗 |对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;@@ -157,7 +175,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=字体路径` 指定。+题字和纸条需要中文字体。macOS 的楷体/宋体、Linux 的 Noto CJK、Windows 的楷体/宋体都会自动找到,也可以用 `INKPAINT_FONT=字体路径` 指定。黏土、蓝晒、十字绣、复古面板还会找常见的西文字体(无衬线、圆体、花体、手写体,见 `core.latin_font`),可用 `INKPAINT_FONT_<风格>` 指定,比如 `INKPAINT_FONT_HAND`。仓库里不附带任何字体文件。### 快速上手@@ -174,6 +192,10 @@ python3 examples/editorial_ideas.py out.png # 编辑风python3 examples/oil_wheatfield.py out.png # 油画厚涂:麦田星空python3 examples/ukiyoe_fuji.py out.png # 浮世绘:富士曙python3 examples/pixel_rainy_cafe.py out.png # 像素风:雨夜咖啡店+python3 examples/clay_lighthouse.py out.png # 黏土定格:灯塔岛+python3 examples/cyanotype_botanicals.py out.png # 蓝晒:蓝晒植物+python3 examples/stitch_sampler.py out.png # 十字绣:家+python3 examples/panel_radio.py out.png # 复古仪器面板:Aurora 64 收音机```### 作画要点(Claude 交图前逐条自查)@@ -187,6 +209,10 @@ python3 examples/pixel_rainy_cafe.py out.png # 像素风- **油画**:先大笔铺底,再中笔,细节笔只用在要紧处;颜料凸起要克制(平顶、弱高光),否则笔触像塑料管。- **浮世绘**:平涂色块,晕色只用在天空和海面;云带不透明;墨线勾住一切;标题签和印章放在天空留白处。- **像素风**:在真正的低分辨率上画,用抖动代替渐变;光晕要小(大面积抖动会变成方块);放大只能用无插值。+- **黏土**:按高度(像素)思考,部件顺着下面的东西铺;手指抹痕要宽、要柔、要少,否则天空像揉皱的锡纸;不可平铺的噪声不能循环平移,会留下笔直的接缝。+- **蓝晒**:想的是挡紫外线,不是上颜料:薄叶不透明度约 0.85、叶脉完全挡光;绒毛要离纸,边缘才柔;蕨类羽片是一整片带圆齿的叶子,不是一排分开的小叶;干刷的笔尾是利落的断续刷丝,不是一片模糊。+- **十字绣**:一切都在布孔的格子上;半针不要叠在十字绣上(亮部换浅色线);短的斜向回针一针从孔到孔,否则会被吸附成 L 形台阶。+- **复古面板**:所有部件同一盏主光:左上边亮、向右下投影;喇叭布的金丝要长浮,短了像冲孔板;丝印字别压在花纹上,也别挤到刻度末端。### 计划diff --git a/SKILL.md b/SKILL.mdindex 4e30d2d..857606d 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,6 +1,6 @@---name: claude绘图-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置九种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风,或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。+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 without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。---# Claude 绘图@@ -23,8 +23,12 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型| 油画厚涂 | `lib/oilpaint.py` · `OilPainting` | `examples/oil_wheatfield.py` 麦田星空(旋转的星空、麦田、柏树、乌鸦) | 约 2 秒 || 浮世绘木版画 | `lib/ukiyoe.py` · `Ukiyoe` | `examples/ukiyoe_fuji.py` 富士曙(晕色天空、富士、云带、青海波、帆船、崖松) | 约 7 秒 || 像素风 | `lib/pixelart.py` · `PixelArt` | `examples/pixel_rainy_cafe.py` 雨夜咖啡店(霓虹、路灯、雨、倒影、猫) | 约 0.1 秒 |+| 黏土定格 | `lib/clay.py` · `Clay` | `examples/clay_lighthouse.py` 灯塔岛(手指抹开的天空、条纹灯塔、喷水的鲸鱼、搓条浪花、小帆船) | 约 6 秒 |+| 蓝晒 | `lib/cyanotype.py` · `Cyanotype` | `examples/cyanotype_botanicals.py` 蓝晒植物(蕨叶、银杏、蒲公英、飘散的种子、白色手写标注) | 约 6 秒 |+| 十字绣 | `lib/stitch.py` · `Stitch` | `examples/stitch_sampler.py` 家(H♥ME 字母、缎面绣爱心、小屋、苹果树、松树、花边、缝上的布标) | 约 20 秒 |+| 复古仪器面板 | `lib/panel.py` · `Panel` | `examples/panel_radio.py` Aurora 64 收音机(柚木机壳、喇叭布、背光刻度窗、琴键、魔眼管、拨杆、旋钮) | 约 7 秒 |-各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找。+各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。**用户没有指定画风时怎么选**:- 禅意、古典、山水 → 水墨;@@ -35,9 +39,13 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型- 观点、概念、商业文章配图 → 编辑风手绘;- 浓烈、有笔触质感、名画感 → 油画厚涂;- 日式古典、海浪、富士、东方装饰感 → 浮世绘;-- 复古游戏、夜景霓虹、小尺寸动画 → 像素风。+- 复古游戏、夜景霓虹、小尺寸动画 → 像素风;+- 童趣立体、讲故事、手作感、定格动画 → 黏土定格;+- 植物、标本、自然科学、复古工艺感的蓝色海报 → 蓝晒;+- 家、温馨、手作礼物、贺卡、名字和字母 → 十字绣;+- 设备、仪表、音响收音机、复古科技与产品感 → 复古仪器面板。-每种画风一幅范例作为质量基准;水墨另加一幅「月印万川」(留白托月、水面倒影)。+每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。## 一、流程(每幅画都照做)@@ -132,6 +140,33 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 其他:`text('CAFE', x, y, 颜色, size)` 3×5 像素字、`rain()` 雨丝- 交付用 PNG(无损),像素才清晰+**黏土定格 `Clay`**:+- 同时维护高度图(像素为单位)和颜色图,最后用影棚光一次性打光。部件默认「铺」在下面的东西上(`base=None`),先远后近、后铺的在上+- `backdrop(颜色)` 底板;`gradient(top, bottom, y0, y1)` 生成颜色场,可传给 `pad`/`smear`+- 部件:`pad(mask, 颜色, height, round)` 压平的一片(round 小是硬边薄片,大是鼓鼓的枕头形)、`ball(x, y, r)` 小球、`snake(pts, r, taper=(起, 止))` 搓条(线条、浪花、嘴、茎)、`text(s, x, y, size)` 鼓起的黏土字+- 工具痕:`groove(pts, width, depth)` 刻线、`poke(x, y, r, depth)` 戳洞;`smear(mask, 颜色场)` 手指抹开的一大片(会把相邻颜色拖混,留下柔和的指痕脊)+- `marble=('#颜色', 0.25)` 两色没揉匀的纹路;表面自动带小疙瘩和指纹+- 遮罩:`circle()`、`ellipse()`、`poly()`、`blob()`、`rrect()`++**蓝晒 `Cyanotype`**:+- 思路是「挡紫外线」而不是「上颜料」:放上去的东西按不透明度挡光,透过率相乘;最后显影成普鲁士蓝+- `coat(x0, y0, x1, y1)` 刷涂药水:一笔笔横刷,笔尾是干刷的断续刷丝,边上会甩几滴药水+- `place(mask, opacity, lift, texture)`:opacity 薄叶约 0.85、叶脉 1.0、绒毛约 0.3;lift 是离纸的高度(0 压平清晰,1–3 柔和半影);texture 是叶肉的不均匀+- 批量画遮罩:`shapes([轮廓...])` 一次画很多片叶子,`lines([折线...], width, taper)` 一次画很多茎、叶脉、绒毛;`Cyanotype.leaf_pts(x, y, 角度, 长, 宽, tip, blunt)` 叶片轮廓+- 文字:`label()` 白色手写字(写在透明片上一起晒)、`pencil()` 晒完后写在纸边的铅笔字++**十字绣 `Stitch`**:+- 一切都在布孔的格子上(`cell` 像素一格)。`cells(mask)` 把像素遮罩变成格子,`at(gx, gy)` 取格子中心+- 针法:`cross(格子, 颜色)` 十字绣、`half(格子, 颜色)` 半针(天空、云、烟)、`back(pts, 颜色, step)` 回针(路径吸附到孔上,一针约 step 格)、`running(pts)` 平针虚线、`satin(mask, 颜色, angle)` 缎面绣(鼓起、有光泽)、`satin_text(s, x, y, size)`、`knot(x, y, 颜色)` 法式结+- 图样:`chart(['..#..', '.###.'], gx, gy, {'#': 颜色})` 按字符图绣;`letters('HOME', gx, gy, 颜色, scale)` 5×7 字母+- `label(x0, y0, x1, y1, 'EST. 2026')` 缝上去的织标++**复古仪器面板 `Panel`**:+- 所有部件都由同一盏左上方的主光照亮:朝光的边亮、背光的边暗、凸起的部件向右下投影+- 材质:`surface(mask, 材质, 颜色, height)`,材质可选 wood(柚木)、brushed(拉丝铝)、plastic、painted、fabric(喇叭布,`lurex=` 金丝);`recess(mask, 材质, 颜色, depth)` 下凹的窗口;`background()`、`paint()`、`glow()`、`drop_shadow()`+- 控件:`knob(x, y, r, angle)` 车削旋钮、`button()` 琴键(`pressed=True` 按下)、`toggle()` 拨杆开关、`lamp()` 宝石指示灯、`magic_eye()` 绿色魔眼调谐管、`meter()` 指针表、`screw()` 螺丝、`grille()` 冲孔网、`badge()` 镀铬草书铭牌+- 印刷:`text(s, x, y, size, spacing=)` 丝印字、`scale_arc()` 圆弧刻度、`scale_linear()` 直尺刻度、`glass(mask)` 玻璃反光+**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。## 三、毛病清单(都真实出现过)@@ -214,9 +249,51 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask| 背景底部露出一条黑带 | 天空渐变和楼群都要铺到地面线,不留缝 || 光晕变成一大块方形点阵 | 光晕半径要小(约 20 像素)、强度约 0.4–0.5;霓虹光晕压扁一些 |+**黏土定格**++| 问题 | 改法 |+|---|---|+| 手指抹开的天空像揉皱的锡纸 | 指痕要宽(40–70 像素)、数量适中(200–350 笔)、脊线柔和低矮(`smear` 的 height 约 4);先铺几种颜色再抹,拖色才看得出来 |+| 天空里出现笔直的矩形色块边 | 不可平铺的噪声不能取模循环平移,要在噪声图内部取窗口(已修) |+| 预先铺的色块边缘太硬,抹完还是一块一块 | 色块之间用 smoothstep 柔和过渡,再用手指抹 |+| 浪花像一排排一模一样的墙纸花纹 | 每朵浪的长短、高低、间距都随机;只排两三行,近大远小 |+| 鲸鱼像一条面包,尾鳍像两根分开的香肠 | 头要圆、身体向后收窄入水;尾鳍用一整片带中间缺口的翼形轮廓 |+| 前景水面在藏在下面的尾柄处鼓起一个包 | 部件默认顺着下面的高度铺;被遮住的部分别伸进水面太深,或在水线处用泡沫盖住 |++**蓝晒**++| 问题 | 改法 |+|---|---|+| 蕨叶像一串箭头或锯齿(鱼骨状) | 每片羽片做成一整片带圆齿边的叶片,加淡色小叶脉;不要一颗颗分开的小叶 |+| 小叶改成椭圆后又像含羞草 | 同上,蕨类的羽片是连在一起的 |+| 蒲公英绒毛几乎看不见 | 细丝不透明度约 0.3、lift 约 1;抬得太高会被半影模糊掉 |+| 刷涂边缘像毛刺、撕纸或动态模糊 | 按一笔笔横刷建模:每根刷毛在自己的位置干净利落地停住,干刷的断续用横向拉长的噪声(已修) |+| 茎穿过白色题字 | 题字放在留白处,茎的走向给题字让路 |+| 飘散的种子被涂布边缘裁掉,只剩一根线 | 小物件要完整落在涂布区域以内 |++**十字绣**++| 问题 | 改法 |+|---|---|+| 斜向的短线(太阳光芒)被吸附成一串 L 形台阶 | 短斜线就绣一针,从孔到孔(`step` 设大) |+| 半针叠在十字绣上,像贴了一层纹理 | 真实绣法不会这样叠:亮部直接换浅一号的线绣十字 |+| 烟囱被屋顶整个盖住、烟线穿过标题 | 先算好屋顶轮廓再定烟囱高度;烟用半针小烟团,往留白处飘 |+| 布面格子太黑,像方格纸 | 布孔暗度约 0.34,布块起伏约 0.065 |+| 花朵和松树重叠 | 摆放前按格子算好每样东西占的列 |++**复古仪器面板**++| 问题 | 改法 |+|---|---|+| 喇叭布上的金丝像一排点点,看着像冲孔板 | 金丝纬线要长浮(压过三根经线再钻下一根),闪光沿线缓慢变化 |+| 刻度单位和最后一个数字挤在一起 | 单位放到刻度末端外侧,或者直接写完整数值(530…1600 kHz) |+| 浅色字印在浅色喇叭布上看不见 | 丝印颜色要和底材拉开明度 |+| 一大片喇叭布太平、太假 | 布是半透明的:把后面喇叭的圆形暗影淡淡透出来 |+## 四、做成动画- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。+- 动图规格(多数现有动图和新增四幅一致):720×405;每个阶段停 900 毫秒,再用 5 帧(每帧 90 毫秒)叠化到下一阶段,最后一帧停 2600 毫秒,无限循环。新增四幅的所有帧共用一张 256 色调色板,文件小、不闪烁。- 更细的逐笔动画:把一组笔画单独画到透明层上导出,再用 Motion Canvas 遮罩按顺序显现。这个还没做成现成接口。## 五、文件@@ -232,6 +309,11 @@ lib/editorial.py 编辑风手绘lib/oilpaint.py 油画厚涂lib/ukiyoe.py 浮世绘木版画lib/pixelart.py 像素风+lib/clay.py 黏土定格+lib/cyanotype.py 蓝晒+lib/stitch.py 十字绣+lib/panel.py 复古仪器面板examples/*.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> 指定;字体文件不要放进仓库```diff --git a/examples/clay_lighthouse.jpg b/examples/clay_lighthouse.jpgnew file mode 100644index 0000000..c30ef7fBinary files /dev/null and b/examples/clay_lighthouse.jpg differdiff --git a/examples/clay_lighthouse.py b/examples/clay_lighthouse.pynew file mode 100644index 0000000..066ea91--- /dev/null+++ b/examples/clay_lighthouse.py@@ -0,0 +1,194 @@+"""Example (stop-motion clay): Lighthouse Island / 灯塔岛 — a plasticine relief: finger-smeared sky,+pillowy clouds, a striped lighthouse and cottage on a little island, a smiling whale spouting water,+a sailboat, rolled-coil waves. Everything is a height map lit like a photo of a set. No image model.+python3 clay_lighthouse.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 clay import Clay, hexc+from core import spline, fbm1d, noise2d, smoothstep++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'clay_lighthouse.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++c = Clay(1920, 1080, seed=11)+rng = c.rng+W, H = c.W, c.H+HORIZON = 600+NAVY, RED, CREAM, FOAM = '#2f3b63', '#d8453a', '#fbfaf5', '#eef8fb'++# ---- sky: bands of blue, pale blue and warm cream, then smeared together with fingertips+c.backdrop('#cfe6ee')+sky_col = c.gradient('#5fa8d8', '#f6e3bd', 0, HORIZON)+bands = noise2d(H, W, 260, 3, 3)[..., None]+hi = smoothstep(0.56, 0.72, bands) * 0.4 # soft patches of pale blue ...+sky_col = sky_col * (1 - hi) + hexc('#a6d4ee') * hi+low = smoothstep(0.44, 0.3, bands) * smoothstep(HORIZON - 260, HORIZON - 120, c.YY)[..., None] * 0.35+sky_col = sky_col * (1 - low) + hexc('#f7cfb8') * low # ... and peach near the horizon, for the fingers to drag around+sky = c.rrect(-40, -40, W + 40, HORIZON + 30, 10)+c.smear(sky, sky_col, strokes=340, angle=0.08, spread=0.3, height=4)+SX, SY = 1640, 180+for a in np.linspace(0, 2 * np.pi, 12, endpoint=False):+ c.snake([(SX + np.cos(a) * 106, SY + np.sin(a) * 106), (SX + np.cos(a) * 150, SY + np.sin(a) * 150)], 9, '#f7b33b', taper=(1.0, 0.6))+c.pad(c.circle(SX, SY, 86), '#fbc94a', height=22, round=18)+c.groove(spline([(SX - 40, SY + 18), (SX, SY + 44), (SX + 40, SY + 18)]), 7, 4) # sleepy sun smile+for sx in (-1, 1):+ c.groove(spline([(SX + sx * 36 - 16, SY - 14), (SX + sx * 36, SY - 24), (SX + sx * 36 + 16, SY - 14)]), 6, 3)+ c.pad(c.circle(SX + sx * 56, SY + 18, 13), '#f59a72', height=2, round=4)+++def cloud(cx, cy, w, h, n):+ m = np.zeros((H, W), np.float32)+ for i in range(n):+ x = cx - w / 2 + w * (i + 0.5) / n+ r = h * (0.5 + 0.45 * np.sin(np.pi * (i + 0.5) / n)) * rng.uniform(0.85, 1.1)+ m = np.maximum(m, c.circle(x, cy + h * 0.3 - r * 0.7, r))+ m = np.maximum(m, c.rrect(cx - w / 2, cy - h * 0.1, cx + w / 2, cy + h * 0.32, h * 0.2))+ c.pad(m, CREAM, height=26, round=16)+++cloud(930, 150, 320, 116, 4)+cloud(1290, 330, 220, 82, 3)+cloud(150, 330, 190, 74, 3)+for (bx, by, s) in [(620, 300, 1.0), (690, 266, 0.8), (560, 250, 0.7)]:+ c.snake([(bx - 30 * s, by + 4 * s), (bx - 15 * s, by - 12 * s), (bx, by)], 4.2 * s, CREAM, taper=(0.6, 1))+ c.snake([(bx, by), (bx + 15 * s, by - 12 * s), (bx + 30 * s, by + 4 * s)], 4.2 * s, CREAM, taper=(1, 0.6))+c.stage('sky')++# ---- sea: a deep slab, lighter towards the horizon, tool-grooved ripples+sea = c.rrect(-40, HORIZON - 6, W + 40, H + 40, 8)+c.pad(sea, c.gradient('#7cc3d6', '#2c6f98', HORIZON, H), height=12, round=4)+for k in range(12):+ y = HORIZON + 26 + k ** 1.5 * 9+ for _ in range(3 + k // 3):+ x = rng.uniform(40, W - 200); L = rng.uniform(80, 200) * (0.6 + k / 16)+ c.groove([(x, y + rng.normal(0, 4)), (x + L / 2, y - 3), (x + L, y + rng.normal(0, 4))], 3 + k * 0.3, 1.6)+c.stage('sea')++# ---- island: sandy base, grassy hill, rocks, lighthouse, cottage, tree+IX = 470+c.pad(c.blob(IX, HORIZON + 58, 330, 62, rough=0.05), '#e8cf99', height=20, round=10)+c.pad(c.blob(IX - 20, HORIZON + 22, 270, 70, rough=0.06), '#7db65a', height=24, round=18, marble=('#9ccd6c', 0.25))+for (x, y, r) in [(210, HORIZON + 70, 30), (250, HORIZON + 84, 20), (736, HORIZON + 76, 26), (700, HORIZON + 90, 16)]:+ c.pad(c.blob(x, y, r, r * 0.75, rough=0.12), '#9aa1a8', height=r * 0.7, round=r * 0.5)++LX, LB, LT = 400, HORIZON + 10, 250 # lighthouse: centre x, base y, top y+++def lh_x(y, side): # tapered tower edge+ t = (LB - y) / (LB - LT)+ return LX + side * (62 - 22 * t)+++tower = c.poly([(lh_x(LB, -1), LB), (lh_x(LB, 1), LB), (lh_x(LT, 1), LT), (lh_x(LT, -1), LT)])+c.pad(tower, '#f5efe4', height=40, round=16)+for (y0, y1) in [(LB - 70, LB - 20), (LB - 180, LB - 130), (LB - 290, LB - 240)]:+ band = c.poly([(lh_x(y1, -1) - 3, y1), (lh_x(y1, 1) + 3, y1), (lh_x(y0, 1) + 3, y0), (lh_x(y0, -1) - 3, y0)])+ c.pad(band, RED, height=4, round=3)+c.pad(c.rrect(LX - 20, LB - 64, LX + 20, LB + 2, 18), NAVY, height=5, round=4) # door+c.pad(c.circle(LX, LB - 205, 13), NAVY, height=4, round=3) # little window+c.pad(c.rrect(LX - 66, LT - 16, LX + 66, LT + 6, 8), NAVY, height=12, round=4) # gallery+c.pad(c.rrect(LX - 38, LT - 84, LX + 38, LT - 14, 6), '#ffd45e', height=14, round=6) # lamp room+for dx in (-13, 13):+ c.snake([(LX + dx, LT - 82), (LX + dx, LT - 16)], 3, NAVY, smooth=False)+c.snake([(LX - 64, LT - 38), (LX + 64, LT - 38)], 3.2, NAVY, smooth=False) # rail+for dx in (-58, -30, 30, 58):+ c.snake([(LX + dx, LT - 38), (LX + dx, LT - 14)], 2.6, NAVY, smooth=False)+c.pad(c.poly([(LX - 54, LT - 80), (LX + 54, LT - 80), (LX, LT - 142)]), RED, height=20, round=10)+c.ball(LX, LT - 146, 10, NAVY)+for side in (-1, 1): # the lamp's shine, pressed as little rays+ for a in (-0.32, 0.0, 0.32):+ x0, y0 = LX + side * 60, LT - 50 + a * 50+ c.snake([(x0, y0), (x0 + side * 46, y0 + a * 80)], 4.5, '#ffe28a', taper=(1, 0.45))++HX = 590 # cottage+c.pad(c.rrect(HX - 62, HORIZON - 50, HX + 62, HORIZON + 34, 6), '#f3e7d2', height=26, round=8)+c.pad(c.poly([(HX - 78, HORIZON - 44), (HX + 78, HORIZON - 44), (HX, HORIZON - 116)]), '#3f6fb0', height=18, round=8)+c.pad(c.rrect(HX + 12, HORIZON - 14, HX + 42, HORIZON + 34, 12), '#8a5a3c', height=4, round=3)+c.pad(c.rrect(HX - 44, HORIZON - 22, HX - 12, HORIZON + 6, 4), '#ffd45e', height=4, round=3)+c.snake([(HX - 28, HORIZON - 22), (HX - 28, HORIZON + 6)], 2.4, '#8a5a3c', smooth=False)+c.snake([(HX - 44, HORIZON - 8), (HX - 12, HORIZON - 8)], 2.4, '#8a5a3c', smooth=False)+c.snake([(220, HORIZON + 30), (226, HORIZON - 40)], 9, '#8a5a3c', taper=(1.1, 0.8)) # tree+tree = np.maximum.reduce([c.circle(226, HORIZON - 96, 58), c.circle(190, HORIZON - 66, 40), c.circle(262, HORIZON - 64, 44)])+c.pad(tree, '#4f9a4e', height=30, round=22, marble=('#6db55e', 0.2))+for (x, y) in [(200, HORIZON - 110), (248, HORIZON - 84), (214, HORIZON - 58)]:+ c.ball(x, y, 7, '#e2503f')+c.stage('island')++# ---- whale: big round head, body tapering right into the water, pale grooved throat, eye, smile, spout+WX, WY = 1150, 700+WATER = 772 # the front water line+body = c.poly(spline([(WX - 300, WY + 40), (WX - 296, WY - 60), (WX - 230, WY - 150), (WX - 110, WY - 190), (WX + 40, WY - 176),+ (WX + 180, WY - 120), (WX + 300, WY - 50), (WX + 380, WY + 10), (WX + 360, WY + 60), (WX - 300, WY + 60)], 16))+c.pad(body, '#4a7fc1', height=62, round=50)+throat = c.poly(spline([(WX - 300, WY + 2), (WX - 200, WY + 12), (WX - 60, WY + 22), (WX + 90, WY + 50), (WX + 90, WY + 90), (WX - 300, WY + 90)], 12))+c.pad(throat * (body > 0.5), '#d7e8f2', height=5, round=6)+for k in range(3):+ y0 = WY + 30 + k * 15+ c.groove([(WX - 262, y0 - 4), (WX - 120, y0 + 4), (WX + 50, y0 + 22)], 3.5, 2.2)+c.ball(WX - 170, WY - 76, 19, CREAM)+c.ball(WX - 167, WY - 73, 11, '#232838')+c.ball(WX - 172, WY - 79, 4, '#ffffff')+c.groove(spline([(WX - 290, WY - 20), (WX - 230, WY - 4), (WX - 150, WY - 16)]), 6, 5)+c.pad(c.ellipse(WX - 214, WY - 38, 20, 12), '#f29aa3', height=3, round=4)+c.pad(c.poly(spline([(WX - 30, WY + 6), (WX + 20, WY + 54), (WX + 96, WY + 76), (WX + 60, WY + 20)], 8)), '#3d6daa', height=16, round=10)+for dx in (-60, -20, 20, 60): # pale spots on the back+ c.pad(c.circle(WX + dx, WY - 150 + abs(dx) * 0.35, 8), '#6d9ad0', height=2, round=3)+SPX, SPY = WX - 120, WY - 190 # spout: three curling plumes and droplets+for side, reach in [(-1, 1.0), (0, 0.0), (1, 1.0)]:+ pts = [(SPX, SPY), (SPX + side * 16, SPY - 80), (SPX + side * 70 * reach, SPY - 140 - (1 - reach) * 40), (SPX + side * 118 * reach, SPY - 118 - (1 - reach) * 50)]+ c.snake(pts, 13, '#e3f2fa', taper=(1.2, 0.6))+for (x, y, r) in [(SPX - 132, SPY - 92, 9), (SPX + 136, SPY - 94, 8), (SPX - 70, SPY - 176, 7), (SPX + 64, SPY - 182, 7), (SPX, SPY - 214, 9), (SPX - 158, SPY - 56, 6), (SPX + 160, SPY - 60, 6)]:+ c.ball(x, y, r, '#e3f2fa')+FX, FY = 1660, 690 # tail fluke rising further out+c.snake([(FX - 56, WATER - 6), (FX - 20, FY + 40), (FX, FY - 6)], 26, '#4a7fc1', taper=(1.3, 0.6))+fluke = c.poly(spline([(FX, FY + 18), (FX - 56, FY - 4), (FX - 112, FY - 40), (FX - 156, FY - 80), (FX - 96, FY - 58), (FX - 36, FY - 40),+ (FX, FY - 26), (FX + 36, FY - 40), (FX + 96, FY - 60), (FX + 152, FY - 86), (FX + 110, FY - 42), (FX + 56, FY - 6), (FX, FY + 18)], 6))+c.pad(fluke, '#4a7fc1', height=28, round=14)+c.stage('whale')++# ---- water in front: a wavy slab over the whale's lower half, irregular curling wave coils, foam, a sailboat+wob = fbm1d(90, 12, 3, 5)+xs = np.linspace(-40, W + 40, 90)+front_top = [(x, WATER + 12 * np.sin(x / 64) + 10 * wob[i]) for i, x in enumerate(xs)]+front = c.poly(front_top + [(W + 40, H + 40), (-40, H + 40)])+c.pad(front, c.gradient('#4f9cc0', '#2a6690', WATER, H), height=14, round=6)+++def wave(x, y, L, r, col):+ """one rolled coil: a long low crest that curls over at the front"""+ curl = [(x, y + 6), (x + L * 0.3, y - L * 0.08), (x + L * 0.62, y - L * 0.14), (x + L * 0.84, y - L * 0.07),+ (x + L * 0.84, y + L * 0.02), (x + L * 0.74, y + L * 0.03), (x + L * 0.72, y - L * 0.03)]+ c.snake(curl, r, col, taper=(0.35, 1.0))+++for (x, y) in [(xs[i], front_top[i][1]) for i in range(2, 88, 7)]: # small crests along the top edge+ wave(x - 30, y + 6, rng.uniform(90, 130), 5.5, '#8fd0e0')+rows = [(WATER + 110, 170, 7.5), (WATER + 200, 210, 9), (WATER + 290, 250, 10.5)]+for (y, L0, r) in rows:+ x = -rng.uniform(40, 160)+ while x < W + 40:+ L = L0 * rng.uniform(0.75, 1.3)+ yy = y + rng.normal(0, 10)+ wave(x, yy, L, r * rng.uniform(0.85, 1.1), '#8fd0e0' if rng.random() < 0.75 else '#a9dde8')+ if rng.random() < 0.7:+ c.ball(x + L * 0.78, yy - L * 0.02, r * 0.7, FOAM)+ x += L * rng.uniform(1.1, 1.8)+for k in range(34): # foam at the whale's and the tail's waterline+ x = rng.uniform(WX - 300, WX + 380) if k < 24 else rng.uniform(FX - 110, FX + 20)+ c.ball(x, WATER + 6 + 12 * np.sin(x / 64) + rng.normal(0, 4), rng.uniform(4, 8), FOAM)+BX, BY = 640, 900 # sailboat in the foreground+c.pad(c.poly(spline([(BX - 120, BY - 34), (BX + 130, BY - 34), (BX + 86, BY + 22), (BX - 86, BY + 22)], 4)), '#e2503f', height=22, round=10)+c.snake([(BX - 108, BY - 14), (BX + 118, BY - 14)], 3.4, CREAM, smooth=False)+c.snake([(BX - 6, BY - 34), (BX - 6, BY - 250)], 5.5, '#8a5a3c', smooth=False)+c.pad(c.poly([(BX + 6, BY - 240), (BX + 6, BY - 50), (BX + 132, BY - 50)]), CREAM, height=12, round=8)+c.pad(c.poly([(BX - 18, BY - 210), (BX - 18, BY - 56), (BX - 104, BY - 56)]), '#f2d27a', height=10, round=7)+c.pad(c.poly([(BX - 4, BY - 252), (BX - 4, BY - 226), (BX + 36, BY - 239)]), '#3f6fb0', height=6, round=3)+for dx in (-64, 0, 64):+ c.poke(BX + dx, BY + 2, 6, 3)+wave(BX - 190, BY + 30, 150, 8, '#a9dde8')+wave(BX + 110, BY + 36, 130, 7, '#a9dde8')++c.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/cyanotype_botanicals.jpg b/examples/cyanotype_botanicals.jpgnew file mode 100644index 0000000..a4d1553Binary files /dev/null and b/examples/cyanotype_botanicals.jpg differdiff --git a/examples/cyanotype_botanicals.py b/examples/cyanotype_botanicals.pynew file mode 100644index 0000000..3c9cbe3--- /dev/null+++ b/examples/cyanotype_botanicals.py@@ -0,0 +1,156 @@+"""Example (cyanotype): Sun Print Botanicals / 蓝晒植物 — a photogram in the spirit of Anna Atkins:+a fern frond, a sprig of ginkgo leaves and a dandelion clock laid on brushed Prussian-blue emulsion.+Thin leaves let a little light through (pale body, whiter veins), dandelion fluff stands off the paper+(soft penumbra), white handwriting printed in, a pencil note on the margin. No image model.+python3 cyanotype_botanicals.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 cyanotype import Cyanotype+from core import spline, fbm1d++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'cyanotype_botanicals.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++cy = Cyanotype(1920, 1080, seed=1842)+rng = cy.rng+W, H = cy.W, cy.H+cy.coat(96, 64, 1826, 1000)+cy.stage('coated')+++def along(P, s):+ """point and unit tangent at arc-length fraction s of polyline P"""+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); cum = np.concatenate([[0], np.cumsum(seg)])+ d = s * cum[-1]; i = min(len(seg) - 1, int(np.searchsorted(cum, d) - 1)); i = max(i, 0)+ t = (d - cum[i]) / (seg[i] + 1e-6)+ p = P[i] + (P[i + 1] - P[i]) * t+ u = (P[i + 1] - P[i]) / (seg[i] + 1e-6)+ return p, u+++# ---- fern frond: rachis, alternating pinnae, each pinna a midrib with blunt pinnules+def fern(base, ctrl, tip, lmax, n_pairs, seed):+ """a pinnate frond: alternating pinnae, each one continuous blade with a scalloped (lobed) margin"""+ r = np.random.default_rng(seed)+ rachis = spline([base, ctrl, tip], 30)+ blades, ribs = [], []+ for k in range(n_pairs * 2):+ s = 0.07 + 0.9 * (k / (n_pairs * 2)) ** 0.92+ side = 1 if k % 2 == 0 else -1+ p, u = along(rachis, s)+ nrm = np.array([-u[1], u[0]]) * side+ L = lmax * np.sin(np.pi * (0.14 + 0.86 * s)) ** 0.7 * (1.1 - s * 0.35) * r.uniform(0.94, 1.04)+ out_dir = nrm * 0.9 + u * 0.42; out_dir /= np.linalg.norm(out_dir)+ bend = u * L * 0.16+ rib = spline([p, p + out_dir * L * 0.5 + bend * 0.3, p + out_dir * L + bend], 12)+ n = 60+ t = np.linspace(0, 1, n)+ seg = np.linalg.norm(np.diff(rib, axis=0), axis=1); cum = np.concatenate([[0], np.cumsum(seg)])+ pts = np.stack([np.interp(t * cum[-1], cum, rib[:, 0]), np.interp(t * cum[-1], cum, rib[:, 1])], 1)+ tg = np.gradient(pts, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6+ nm = np.stack([-tg[:, 1], tg[:, 0]], 1)+ lobes = max(3, L / 15)+ wmax = min(30, 7 + L * 0.13)+ half = wmax * (0.62 + 0.38 * np.sin(np.pi * np.clip(t * 1.15, 0, 1)) ** 0.5) * np.sqrt(np.clip(1 - t, 0, 1) + 0.02)+ scallop = 0.7 + 0.3 * np.abs(np.sin(np.pi * lobes * t)) ** 0.6+ left = pts + nm * (half * scallop)[:, None]+ right = pts - nm * (half * np.roll(scallop, 1))[:, None]+ blades.append(np.vstack([left, right[::-1]]))+ ribs.append(rib)+ for j in range(int(lobes)): # a faint vein into every lobe+ tj = (j + 0.5) / lobes+ i = min(n - 1, int(tj * (n - 1)))+ for sd in (1, -1):+ ribs.append([tuple(pts[i]), tuple(pts[i] + (nm[i] * sd * 0.85 + tg[i] * 0.5) * half[i] * 0.8)])+ return rachis, blades, ribs+++rachis, leaflets, ribs = fern((300, 1060), (440, 560), (800, 140), 215, 19, 3)+cy.place(cy.shapes(leaflets), opacity=0.88, texture=0.16)+cy.place(cy.lines(ribs, 1.6), opacity=0.5)+cy.line(rachis, 6.5, opacity=1.0, taper=True)+r2, l2, rb2 = fern((60, 960), (150, 700), (290, 470), 95, 12, 8) # a young frond behind it+cy.place(cy.shapes(l2), opacity=0.86, texture=0.18, lift=1.0)+cy.place(cy.lines(rb2, 1.3), opacity=0.45, lift=1.0)+cy.line(r2, 4, opacity=1.0, taper=True)+cy.stage('fern')+++# ---- ginkgo sprig: fan-shaped bilobed leaves with fine radiating veins on long petioles+def ginkgo(px, py, ang, R, span=2.3, notch=0.22, seed=0):+ r = np.random.default_rng(seed)+ th = np.linspace(-span / 2, span / 2, 90)+ wav = 1 + 0.035 * fbm1d(90, 8, 3, seed)+ rad = R * (1 - notch * np.exp(-(th / 0.07) ** 2)) * (0.9 + 0.1 * np.cos(th * 1.3)) * wav+ edge = [(px + np.cos(ang + t) * rr, py + np.sin(ang + t) * rr) for t, rr in zip(th, rad)]+ blade = [(px, py)] + [(px + np.cos(ang + th[0]) * R * 0.25, py + np.sin(ang + th[0]) * R * 0.25)] + edge + \+ [(px + np.cos(ang + th[-1]) * R * 0.25, py + np.sin(ang + th[-1]) * R * 0.25)]+ veins = []+ for t in np.linspace(-span / 2 + 0.06, span / 2 - 0.06, 34):+ rr = R * (1 - notch * np.exp(-(t / 0.07) ** 2)) * (0.9 + 0.1 * np.cos(t * 1.3)) * 0.97+ mid = 0.35 * t+ veins.append(spline([(px, py), (px + np.cos(ang + mid) * rr * 0.3, py + np.sin(ang + mid) * rr * 0.3), (px + np.cos(ang + t) * rr, py + np.sin(ang + t) * rr)], 6))+ return blade, veins+++GX, GY = 1120, 1060+blades, veins, stems = [], [], []+for (ang, plen, R, bend) in [(-2.05, 300, 128, 40), (-1.55, 360, 142, -20), (-1.02, 270, 120, -46), (-2.55, 170, 96, 30)]:+ tipx, tipy = GX + np.cos(ang) * plen, GY + np.sin(ang) * plen+ mid = ((GX + tipx) / 2 + bend, (GY + tipy) / 2)+ stems.append(spline([(GX, GY), mid, (tipx, tipy)], 12))+ b, v = ginkgo(tipx, tipy, ang, R, seed=int(R))+ blades.append(b); veins += v+cy.place(cy.shapes(blades), opacity=0.82, texture=0.12)+cy.place(cy.lines(veins, 1.3), opacity=0.55)+cy.place(cy.lines(stems, 4.2, taper=True), opacity=1.0)+cy.stage('ginkgo')++# ---- dandelion clock: seeds on a sphere, each a beak with an umbrella of filaments; fluff is lifted -> soft+DX, DY, DR = 1590, 330, 172+beaks, fluff = [], []+for i in range(340):+ v = rng.normal(size=3); v /= np.linalg.norm(v)+ proj = np.array([v[0], v[1]]); pl = np.linalg.norm(proj) + 1e-6+ u = proj / pl+ b0 = np.array([DX, DY]) + u * 10 * pl+ b1 = np.array([DX, DY]) + u * DR * 0.6 * pl+ beaks.append([tuple(b0), tuple(b1)])+ for f in range(14):+ a = np.arctan2(u[1], u[0]) + (f / 13 - 0.5) * 2.0+ L = DR * 0.42 * rng.uniform(0.8, 1.05) * (0.55 + 0.45 * pl)+ fluff.append([tuple(b1), tuple(b1 + np.array([np.cos(a), np.sin(a)]) * L)])+cy.place(cy.lines(fluff, 1.2), opacity=0.3, lift=1.1)+cy.place(cy.lines(beaks, 1.3), opacity=0.6, lift=0.8)+cy.place(cy.circle(DX, DY, 9), opacity=0.95, lift=1.0)+stem = spline([(DX, DY + 8), (DX - 20, DY + 240), (DX - 120, DY + 490), (DX - 250, H + 20)], 16)+cy.line(stem, 7, opacity=1.0, lift=1.0)+++def seed(x, y, ang, s=1.0):+ """one loose seed drifting away: achene, long beak, pappus umbrella"""+ u = np.array([np.cos(ang), np.sin(ang)])+ a0 = np.array([x, y]); a1 = a0 + u * 20 * s; b1 = a1 + u * 64 * s+ cy.place(cy.shapes([Cyanotype.leaf_pts(a0[0], a0[1], ang, 22 * s, 5 * s, tip=0.5, n=10)]), opacity=0.95)+ cy.line([tuple(a1), tuple(b1)], 1.4, opacity=0.75, lift=0.5)+ fl = []+ for f in range(18):+ a = ang + (f / 17 - 0.5) * 2.3+ fl.append([tuple(b1), tuple(b1 + np.array([np.cos(a), np.sin(a)]) * 46 * s)])+ cy.place(cy.lines(fl, 1.2), opacity=0.6, lift=0.8)+++for (x, y, a, s) in [(1300, 230, -2.25, 1.0), (1180, 140, -2.55, 0.9), (1110, 330, -2.05, 0.8), (980, 210, -2.8, 0.85), (1270, 400, -2.35, 0.72)]:+ seed(x, y, a, s)+cy.stage('dandelion')++# ---- white handwriting printed in, and a pencil note on the margin+cy.label('Fern, Ginkgo', 1792, 866, 52, anchor='rs', rot=2)+cy.label('& Dandelion', 1792, 924, 52, anchor='rs', rot=2)+cy.label('sun print · 14 min', 1790, 972, 32, anchor='rs', rot=2, opacity=0.85)+cy.pencil('No. 7 — June, bright sun', 104, 1046, 30, anchor='ls', rot=0.6)++cy.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/drawing_clay_lighthouse.gif b/examples/drawing_clay_lighthouse.gifnew file mode 100644index 0000000..188760eBinary files /dev/null and b/examples/drawing_clay_lighthouse.gif differdiff --git a/examples/drawing_cyanotype_botanicals.gif b/examples/drawing_cyanotype_botanicals.gifnew file mode 100644index 0000000..c55d434Binary files /dev/null and b/examples/drawing_cyanotype_botanicals.gif differdiff --git a/examples/drawing_panel_radio.gif b/examples/drawing_panel_radio.gifnew file mode 100644index 0000000..6b86bf8Binary files /dev/null and b/examples/drawing_panel_radio.gif differdiff --git a/examples/drawing_stitch_sampler.gif b/examples/drawing_stitch_sampler.gifnew file mode 100644index 0000000..27f8b99Binary files /dev/null and b/examples/drawing_stitch_sampler.gif differdiff --git a/examples/panel_radio.jpg b/examples/panel_radio.jpgnew file mode 100644index 0000000..dcbcbd5Binary files /dev/null and b/examples/panel_radio.jpg differdiff --git a/examples/panel_radio.py b/examples/panel_radio.pynew file mode 100644index 0000000..2acdf85--- /dev/null+++ b/examples/panel_radio.py@@ -0,0 +1,92 @@+"""Example (vintage industrial panel): Aurora 64 / 六十年代收音机 — the front of a 1960s tabletop radio:+teak cabinet, woven grille cloth with lurex threads and a chrome script badge, a backlit FM/AM dial behind+glass with a red needle, piano-key band buttons, a green magic-eye tuning tube, a toggle switch, a jewel+lamp, three machined knobs with printed scales, slotted screws. No image model.+python3 panel_radio.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 panel import Panel+from core import blur++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'panel_radio.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++p = Panel(1920, 1080, seed=64)+W, H = p.W, p.H+INK, RED, CREAM = '#2b2a27', '#c8452e', '#f3e5c2'++# ---- wall, sideboard, teak cabinet+p.background('#a9bcb0', 'painted')+p.img *= (0.9 + 0.16 * np.exp(-(((p.XX - 960) / 900) ** 2 + ((p.YY - 380) / 600) ** 2)))[..., None] # soft room light+top = p.rrect(-20, 968, W + 20, H + 40, 0)+p.surface(top, 'wood', '#c79d6c', height=0, dark='#8d6440', light='#e0bd8c', ring_scale=0.05)+p.paint(p.rrect(-20, 966, W + 20, 972, 0), '#f0d9b4', 0.5)+for fx in (230, 1690):+ p.surface(p.rrect(fx - 50, 930, fx + 50, 982, 6), 'painted', '#2a211b', height=4, shadow=0.5)+cab = p.rrect(80, 92, 1840, 956, 46)+p.drop_shadow(cab, dist=26, soft=26, strength=0.5)+p.surface(cab, 'wood', '#8a5230', height=16, soft=14)+p.recess(p.rrect(128, 140, 1792, 908, 24), 'painted', '#221c17', depth=10)+p.stage('cabinet')++# ---- speaker: brass trim, recessed grille cloth, chrome script badge+p.surface(p.rrect(150, 162, 908, 886, 18), 'brushed', '#c9a55c', height=6, soft=3, shadow=0.4)+cloth = p.rrect(164, 176, 894, 872, 12)+p.recess(cloth, 'fabric', '#d6c6a3', depth=6, pitch=4.0, lurex='#c89e45', lurex_every=6)+cone = blur(p.circle(529, 470, 250), 40) - 0.55 * blur(p.circle(529, 470, 70), 20) # the speaker behind the thin cloth+p.img *= (1 - 0.1 * cone * cloth)[..., None]+p.badge('Aurora', 700, 790, 96, 'script', '#e2dfd6')+p.text('SIXTY-FOUR', 704, 846, 19, '#5a4630', 'sans_bold', spacing=7)+p.stage('grille')++# ---- control panel: brushed aluminium plate, backlit dial behind glass+p.surface(p.rrect(930, 162, 1770, 886, 18), 'brushed', '#cfcfca', height=6, soft=3, shadow=0.4, band=0.35)+DX0, DY0, DX1, DY1 = 972, 202, 1728, 474+p.recess(p.rrect(DX0, DY0, DX1, DY1, 12), 'painted', '#1d1a17', depth=8)+face = p.rrect(DX0 + 14, DY0 + 14, DX1 - 14, DY1 - 14, 6)+p.surface(face, 'painted', CREAM, height=0)+p.img *= (1 + 0.12 * face * np.exp(-(((p.XX - 1350) / 420) ** 2 + ((p.YY - 330) / 160) ** 2)) - 0.1 * face * (p.YY < DY0 + 60) * (1 - (p.YY - DY0 - 14) / 46))[..., None]+X0, X1 = 1060, 1650+p.text('FM', 1018, 282, 26, RED, 'sans_bold')+p.scale_linear(X0, X1, 300, 41, major=4, length=20, colour=INK, labels=[str(v) for v in range(88, 110, 2)], size=19, label_gap=12)+p.text('MHz', 1686, 282, 17, INK, 'sans_bold')+p.paint(p.line_mask([(X0, 301), (X1, 301)], 1.6), INK)+p.text('AM', 1018, 372, 26, RED, 'sans_bold')+p.scale_linear(X0, X1, 356, 36, major=5, length=16, colour=INK, labels=['530', '600', '700', '800', '1000', '1200', '1400', '1600'], size=17, up=False, label_gap=12)+p.paint(p.line_mask([(X0, 355), (X1, 355)], 1.6), INK)+p.text('kHz', 1690, 386, 17, INK, 'sans_bold')+for i, city in enumerate(['LONDON', 'PARIS', 'ROMA', 'WIEN', 'OSLO', 'PRAHA', 'LISBOA']):+ p.text(city, X0 + 30 + i * (X1 - X0 - 60) / 6, 426, 15, '#7a6f5e', 'sans_bold', spacing=2.5)+NX = 1402+p.glow(NX, 330, 26, '#ff6a3d', 0.25)+p.paint(p.line_mask([(NX, DY0 + 22), (NX, DY1 - 22)], 3.2), RED)+p.glass(p.rrect(DX0 + 8, DY0 + 8, DX1 - 8, DY1 - 8, 8), streak=0.1)+p.stage('dial')++# ---- piano keys, magic eye, toggle switch, jewel lamp+labels = ['OFF', 'PH', 'AM', 'FM', 'SW']+for i, lab in enumerate(labels):+ x0 = 978 + i * 86+ p.button(x0, 516, x0 + 78, 612, '#efe9dc', pressed=(lab == 'FM'), label=lab, size=19)+p.magic_eye(1500, 560, 30, tuned=0.82)+p.text('TUNING', 1500, 628, 15, INK, 'sans_bold', spacing=3)+p.toggle(1612, 572, up=True, length=54)+p.text('STEREO', 1612, 500, 15, INK, 'sans_bold', spacing=3)+p.text('MONO', 1612, 628, 15, INK, 'sans_bold', spacing=3)+p.lamp(1706, 560, 13, '#ffae3b', on=True)+p.text('ON', 1706, 628, 15, INK, 'sans_bold', spacing=3)+p.stage('controls')++# ---- three knobs with printed scales, legends, screws+for (kx, lab, ang, labs) in [(1072, 'VOLUME', 38, ['0', '5', '10']), (1350, 'TONE', -30, ['BASS', 'TREBLE']), (1628, 'TUNING', 64, None)]:+ ky = 752+ p.scale_arc(kx, ky, 86, 98, -135, 135, 21 if labs != ['BASS', 'TREBLE'] else 11, 5, INK, labels=labs, label_r=118, size=16, width=1.8)+ p.knob(kx, ky, 58, angle=ang, face='#d6d6d1', skirt='#24221e', indicator=RED, skirt_w=13)+ p.text(lab, kx, 862, 17, INK, 'sans_bold', spacing=5)+for (sx, sy) in [(952, 184), (1748, 184), (952, 864), (1748, 864)]:+ p.screw(sx, sy, 8)++p.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/stitch_sampler.jpg b/examples/stitch_sampler.jpgnew file mode 100644index 0000000..3e209b7Binary files /dev/null and b/examples/stitch_sampler.jpg differdiff --git a/examples/stitch_sampler.py b/examples/stitch_sampler.pynew file mode 100644index 0000000..6b25873--- /dev/null+++ b/examples/stitch_sampler.py@@ -0,0 +1,141 @@+"""Example (cross-stitch embroidery): Home Sampler / 十字绣样本 — a classic sampler on Aida cloth: a stitched+border of diamonds, "H♥ME" in the cross-stitch alphabet with a satin-stitch heart for the O, a cottage with+back-stitched window panes and a satin door, an apple tree with French-knot apples, a pine, a satin sun,+half-stitch clouds, a row of flowers, and a woven label sewn on with running stitch. No image model.+python3 stitch_sampler.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 stitch import Stitch+from core import spline++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'stitch_sampler.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++s = Stitch(1920, 1080, cell=12, seed=7, cloth='#f0e8d6')+rng = s.rng+C = s.cell+GW, GH = s.gw, s.gh # 160 x 90 cells+NAVY, RED, CORAL, MUSTARD = '#2e3f66', '#c0423a', '#e0654a', '#e3a53a'+GREEN, DKGREEN, LTGREEN, BROWN = '#5f8f4e', '#3f6b45', '#9cbf6b', '#7a4e33'+SKY, PINK, WALL, ROOF, GREY = '#9cc0dc', '#e58f9f', '#f1d08a', '#b5523b', '#a4a8ae'+++def box(gx0, gy0, gx1, gy1):+ g = np.zeros((GH, GW), bool); g[gy0:gy1, gx0:gx1] = True; return g+++# ---- border: two framing lines and a band of alternating diamonds, flowers at the corners+frame = box(4, 4, GW - 4, GH - 4) & ~box(5, 5, GW - 5, GH - 5)+inner = box(12, 12, GW - 12, GH - 12) & ~box(13, 13, GW - 13, GH - 13)+s.cross(frame, DKGREEN)+s.cross(inner, DKGREEN)+diamond = ['..#..', '.###.', '#####', '.###.', '..#..']+k = 0+for gx in range(15, GW - 18, 8):+ for gy in (6, GH - 11):+ s.chart(diamond, gx, gy, {'#': RED if k % 2 == 0 else MUSTARD})+ k += 1+k = 0+for gy in range(15, GH - 18, 8):+ for gx in (6, GW - 11):+ s.chart(diamond, gx, gy, {'#': RED if k % 2 == 0 else MUSTARD})+ k += 1+corner = ['.#.#.', '#####', '#####', '.###.', '..#..'] # little hearts at the corners+for (gx, gy) in [(6, 6), (GW - 11, 6), (6, GH - 11), (GW - 11, GH - 11)]:+ s.chart(corner, gx, gy, {'#': CORAL})+s.stage('border')++# ---- "H♥ME": cross-stitch alphabet, with a padded satin heart in place of the O+TW = Stitch.letters_width('HOME', scale=2)+TX = (GW - TW) // 2+s.letters('H', TX, 16, NAVY, scale=2)+s.letters('ME', TX + 24, 16, NAVY, scale=2)+hx, hy = (TX + 12 + 5) * C, (16 + 7) * C+t = np.linspace(0, 2 * np.pi, 200)+heart = np.stack([hx + 16 * np.sin(t) ** 3 * 4.6, hy - (13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)) * 4.6 - 4], 1)+s.satin(s.poly(heart), RED, angle=0.85)+s.stage('title')++# ---- sky: satin sun with back-stitched rays, half-stitch clouds, back-stitched birds+SX, SY = 30 * C, 25 * C+s.satin(s.circle(SX, SY, 52), MUSTARD, angle=0.3)+for a in np.linspace(0, 2 * np.pi, 10, endpoint=False):+ s.back([(SX + np.cos(a) * 70, SY + np.sin(a) * 70), (SX + np.cos(a) * 112, SY + np.sin(a) * 112)], MUSTARD, step=6, smooth=False) # one long stitch per ray+for (cx, cy, w) in [(130, 23, 15), (46, 34, 8)]:+ cloud = np.maximum.reduce([s.circle((cx + dx) * C, (cy + dy) * C, r * C) for dx, dy, r in+ [(-w * 0.45, 1, w * 0.3), (0, -0.5, w * 0.38), (w * 0.42, 1, w * 0.28)]])+ cloud = np.maximum(cloud, s.rect((cx - w * 0.72) * C, cy * C, (cx + w * 0.7) * C, (cy + w * 0.22) * C))+ s.half(s.cells(cloud), SKY)+for (bx, by, sc) in [(134, 34, 1.0), (141, 31, 0.8)]:+ s.back([(bx * C - 26 * sc, by * C - 6 * sc), (bx * C - 12 * sc, by * C - 14 * sc), (bx * C, by * C)], NAVY, smooth=False)+ s.back([(bx * C, by * C), (bx * C + 12 * sc, by * C - 14 * sc), (bx * C + 26 * sc, by * C - 6 * sc)], NAVY, smooth=False)+s.stage('sky')++# ---- cottage: walls, stepped roof, chimney with half-stitch puffs of smoke, back-stitched windows, satin door+HX0, HX1, HY0, HY1 = 64, 97, 52, 72 # wall cells+s.cross(box(HX0, HY0, HX1, HY1), WALL)+roof = np.zeros((GH, GW), bool)+for r in range(14):+ roof[HY0 - 1 - r, HX0 - 4 + r:HX1 + 4 - r] = True+s.cross(roof, ROOF)+s.cross(box(92, 37, 96, 48) & ~roof, '#9a4a38')+s.cross(box(91, 36, 97, 37), '#7e3a2c')+for (px_, py_, pr) in [(98.5, 34, 1.2), (102.5, 31.8, 1.6), (107.5, 29.6, 2.0)]: # puffs of smoke drifting away+ s.half(s.cells(s.circle(px_ * C, py_ * C, pr * C), 0.35), '#d6d9de')+for (wx0, wy0) in [(67, 56), (86, 56)]:+ s.cross(box(wx0, wy0, wx0 + 8, wy0 + 7), SKY)+ x0, y0, x1, y1 = wx0 * C, wy0 * C, (wx0 + 8) * C, (wy0 + 7) * C+ s.back([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)], NAVY, smooth=False)+ s.back([((x0 + x1) / 2, y0), ((x0 + x1) / 2, y1)], NAVY, smooth=False)+ s.back([(x0, (y0 + y1) / 2 + 6), (x1, (y0 + y1) / 2 + 6)], NAVY, smooth=False)+ s.cross(box(wx0 - 1, wy0 + 7, wx0 + 9, wy0 + 8), BROWN) # window boxes+ for q in range(4):+ s.knot((wx0 + 0.8 + q * 2.2) * C, (wy0 + 7) * C - 2, [PINK, CORAL][q % 2])+door = s.rect(77 * C + 2, 61 * C, 84 * C - 2, HY1 * C) * (1 - (1 - s.circle(80.5 * C, 64.5 * C, 3.5 * C)) * (s.YY < 64.5 * C))+s.satin(door, RED, angle=1.45)+s.knot(82.6 * C, 67 * C, MUSTARD, r=4)+s.back([(HX0 * C, HY0 * C), (HX1 * C, HY0 * C), (HX1 * C, HY1 * C), (HX0 * C, HY1 * C), (HX0 * C, HY0 * C)], BROWN, smooth=False)+s.stage('cottage')++# ---- apple tree (left), pine (right), ground, path, flowers+TX0, TY0 = 38, 49+s.cross(box(TX0 - 1, TY0 + 6, TX0 + 2, 72), BROWN)+crown = s.cells(s.circle((TX0 + 0.5) * C, TY0 * C, 11.5 * C))+light = s.cells(s.circle((TX0 - 2.5) * C, (TY0 - 3) * C, 6 * C)) & crown # the lit side in a lighter floss+s.cross(crown & ~light, GREEN)+s.cross(light, LTGREEN)+for (dx, dy) in [(-6, -4), (4, -6), (-2, 3), (6, 2), (-7, 4), (1, -1), (7, -2)]:+ s.knot((TX0 + 0.5 + dx) * C, (TY0 + dy) * C, RED, r=C * 0.5)+PX = 122+pine = np.zeros((GH, GW), bool)+for tier, (top, h, w) in enumerate([(40, 11, 9), (47, 11, 12), (54, 12, 15)]):+ for r in range(h):+ half_w = int(1 + (w - 1) * r / (h - 1))+ pine[top + r, PX - half_w:PX + half_w + 1] = True+s.cross(box(PX - 1, 66, PX + 2, 72), BROWN)+left = pine & (np.arange(GW)[None, :] < PX)+s.cross(pine & ~left, DKGREEN)+s.cross(left, GREEN)+ground = box(13, 72, GW - 13, 75)+path = np.zeros((GH, GW), bool)+for r in range(72, 77):+ w = 3 + (r - 72)+ path[r, 80 - w:81 + w] = True+s.cross(ground & ~path, GREEN)+s.cross(path, '#d9b98a')+s.half(box(13, 75, GW - 13, 77) & ~path, LTGREEN)+flowers = [(19, PINK), (26, MUSTARD), (49, CORAL), (56, PINK), (102, MUSTARD), (142, PINK), (147, CORAL)]+for (fx, col) in flowers:+ s.back([(fx * C + C / 2, 72 * C), (fx * C + C / 2 - 4, 68 * C), (fx * C + C / 2, 65 * C)], DKGREEN, step=1)+ s.chart(['.#.', '#o#', '.#.'], fx - 1, 62, {'#': col})+ s.knot(fx * C + C / 2, 63.5 * C, MUSTARD if col != MUSTARD else CORAL, r=C * 0.45)+ s.chart(['l.', '.l'], fx - 2, 67, {'l': LTGREEN})+s.stage('garden')++# ---- a woven label sewn on over the corner of the border+s.label(1540, 944, 1856, 1040, 'EST. 2026', size=34)++s.save(out, stages_dir=stages)+print('saved', out)diff --git a/lib/clay.py b/lib/clay.pynew file mode 100644index 0000000..ca42399--- /dev/null+++ b/lib/clay.py@@ -0,0 +1,308 @@+"""clay — stop-motion plasticine relief, photographed under a soft studio light (numpy + Pillow only).++Model: the picture is a board of plasticine seen from the front. Two maps are built piece by piece:+ height h(x, y) in pixels -- every piece is pressed on top of whatever is already there+ (by default it drapes over the surface below, like real clay pressed on clay)+ albedo c(x, y) the clay colour, slightly uneven, with streaks where two colours were kneaded+Pieces are what hands make: flattened pads (any outline, round or pillowy edges), balls, rolled+snakes along a path, puffy letters, finger-smeared slabs, tool grooves and poked holes. Every surface+carries small lumps and the odd fingerprint whorl.+The render lights the height field like a photo of a set: wrap-diffuse warm key + cool fill, a soft+waxy sheen, cast shadows marched through the height field, ambient occlusion in the creases (clay+shadows stay saturated, not grey), then a little lens vignette and film grain.++ from clay import Clay+ c = Clay(1920, 1080, seed=1)+ c.backdrop('#bfe0ea')+ c.pad(c.circle(960, 540, 200), '#f4c542', height=18) # a pressed disc+ c.ball(900, 500, 16, '#2f3b63') # an eye+ c.snake([(860, 600), (960, 640), (1060, 600)], 8, '#2f3b63') # a rolled smile+ c.groove([(700, 700), (1200, 700)], 4, 3) # a tool line+ c.text('HELLO', 960, 200, 120, '#ee7453') # puffy letters+ c.save('out.png')+"""+import numpy as np+from PIL import Image, ImageDraw+from core import (blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, blob_pts, load_font, text_mask,+ height_normals, height_shadow, ambient_occlusion)+++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)+++class Clay:+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.5, -0.62, 0.6), backdrop='#d9dccb'):+ 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.light = np.asarray(light, np.float32) / np.linalg.norm(light)+ self.h = np.zeros((H, W), np.float32)+ self.alb = np.ones((H, W, 3), np.float32) * _c(backdrop)+ self.gloss = np.full((H, W), 1.0, np.float32)+ s = int(self.rng.integers(1 << 30))+ self.fine = noise2d(H, W, 2.4, 2, s) - 0.5 # pores and tiny crumbs+ self.lump = noise2d(H, W, 60, 3, s + 1) - 0.5 # hand-pressed unevenness+ self.tint = noise2d(H, W, 45, 3, s + 2) - 0.5 # colour not perfectly kneaded+ self.prints = self._fingerprints(int(W * H / 40000))+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ texture fields+ def _fingerprints(self, n):+ """sparse fingerprint whorls: concentric elliptical ridges in small fading patches"""+ f = np.zeros((self.H, self.W), np.float32)+ for _ in range(n):+ cx, cy = self.rng.uniform(0, self.W), self.rng.uniform(0, self.H)+ R = self.rng.uniform(22, 42); per = self.rng.uniform(4.2, 5.6)+ a = self.rng.uniform(0, np.pi); sq = self.rng.uniform(0.55, 0.8)+ x0, x1 = int(max(0, cx - R * 2)), int(min(self.W, cx + R * 2))+ y0, y1 = int(max(0, cy - R * 2)), int(min(self.H, cy + R * 2))+ if x1 <= x0 or y1 <= y0: continue+ X, Y = self.XX[y0:y1, x0:x1] - cx, self.YY[y0:y1, x0:x1] - cy+ u, v = X * np.cos(a) + Y * np.sin(a), (-X * np.sin(a) + Y * np.cos(a)) / sq+ r = np.hypot(u, v)+ ridge = np.sin(2 * np.pi * r / per + 0.35 * np.sin(3 * np.arctan2(v, u)))+ f[y0:y1, x0:x1] += ridge * np.exp(-(r / R) ** 2 * 1.6) * self.rng.uniform(0.5, 1.0)+ return f++ def _box(self, mask, margin=0):+ ys, xs = np.nonzero(mask > 0.002)+ if len(xs) == 0: return None+ return (slice(max(0, ys.min() - margin), min(self.H, ys.max() + margin + 1)),+ slice(max(0, xs.min() - margin), min(self.W, xs.max() + margin + 1)))++ def _roll(self, a, sl):+ """a random window of a precomputed field, the same size as box `sl` (no two pieces share a pattern).+ The window stays inside the field: wrapping non-tileable noise would leave straight seams."""+ h, w = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start+ oy = int(self.rng.integers(0, self.H - h + 1)); ox = int(self.rng.integers(0, self.W - w + 1))+ return a[oy:oy + h, ox:ox + w]++ # ------------------------------------------------------------ masks+ def circle(self, cx, cy, r):+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)++ def ellipse(self, cx, cy, rx, ry, rot=0.0):+ X, Y = self.XX - cx, self.YY - cy+ c, s = np.cos(rot), np.sin(rot)+ d = np.hypot((X * c + Y * s) / rx, (-X * s + Y * c) / ry)+ return np.clip((1 - d) * min(rx, ry) + 0.5, 0, 1)++ def poly(self, pts):+ return polygon_mask(self.H, self.W, pts, ss=2)++ def blob(self, cx, cy, rx, ry, rough=0.06, rot=0.0):+ return self.poly(blob_pts(cx, cy, rx, ry, rough=rough, n=120, seed=self._seed(), rot=rot))++ def rrect(self, x0, y0, x1, y1, r):+ im = Image.new('L', (self.W * 2, self.H * 2), 0)+ ImageDraw.Draw(im).rounded_rectangle((x0 * 2, y0 * 2, x1 * 2, y1 * 2), r * 2, fill=255)+ return np.asarray(im.resize((self.W, self.H), Image.BILINEAR), np.float32) / 255++ def gradient(self, top, bottom, y0=0, y1=None):+ """a vertical colour field (H, W, 3) to feed smear() or pad(colour=...)"""+ y1 = self.H if y1 is None else y1+ t = np.clip((self.YY - y0) / max(1, y1 - y0), 0, 1)[..., None]+ return _c(top) * (1 - t) + _c(bottom) * t++ # ------------------------------------------------------------ pressing a piece+ def _press(self, sl, hp, cover, colour, texture=1.0, gloss=1.0, marble=None):+ """composite one piece inside box `sl`: hp = its absolute height, cover = where it exists (0..1)"""+ cur = self.h[sl]+ tex = (self._roll(self.fine, sl) * 0.5 + self._roll(self.lump, sl) * 1.6 + self._roll(self.prints, sl) * 0.24) * texture+ hp = hp + tex * np.clip(cover * 3, 0, 1)+ k = np.clip((hp - cur) / 1.0 + 0.5, 0, 1) * cover+ if np.ndim(colour) == 3:+ col = colour[sl]+ else:+ col = np.broadcast_to(_c(colour), cur.shape + (3,))+ col = col * (1 + 0.07 * self._roll(self.tint, sl))[..., None]+ if marble is not None: # half-kneaded second colour in streaks+ mc, amt = marble+ ang = self.rng.uniform(0, np.pi)+ u = (-self.XX[sl] * np.sin(ang) + self.YY[sl] * np.cos(ang)) + 40 * self._roll(self.lump, sl)+ span = int(u.max() - u.min()) + 4+ st = np.interp(u - u.min(), np.arange(span), fbm1d(span, 26, 3, self._seed()))+ m = smoothstep(0.5 - amt, 0.62 - amt * 0.6, st * 0.5 + 0.5)[..., None]+ col = col * (1 - m) + _c(mc) * m+ self.alb[sl] = self.alb[sl] * (1 - k[..., None]) + col * k[..., None]+ self.h[sl] = cur * (1 - k) + np.maximum(cur, hp) * k+ self.gloss[sl] = self.gloss[sl] * (1 - k) + gloss * k+ return k++ def _base(self, sl, base):+ return blur(self.h[sl], 3) if base is None else np.float32(base)++ def pad(self, mask, colour, height=14, round=5, base=None, texture=1.0, gloss=1.0, marble=None):+ """a piece pressed flat to any outline. round: edge radius in px (small = crisp slab, large = pillow/dome).+ colour may be a hex / RGB or an (H, W, 3) field (e.g. from gradient()). base=None drapes it over what is below."""+ sl = self._box(mask, int(round * 3 + 4))+ if sl is None: return None+ b = blur(mask[sl], max(0.8, round))+ p = np.clip((b - 0.5) * 2.1, 0, 1)+ prof = np.sqrt(1 - (1 - p) ** 2) # a quarter-circle fillet into a flat top+ hp = self._base(sl, base) + prof * height+ cover = smoothstep(0.42, 0.56, b)+ return self._press(sl, hp, cover, colour, texture, gloss, marble)++ def ball(self, cx, cy, r, colour, squash=0.85, base=None, texture=0.6, gloss=1.0):+ """a rolled ball (eyes, berries, rivets, pebbles)"""+ m = 3+ sl = (slice(max(0, int(cy - r - m)), min(self.H, int(cy + r + m + 1))), slice(max(0, int(cx - r - m)), min(self.W, int(cx + r + m + 1))))+ if sl[0].stop <= sl[0].start or sl[1].stop <= sl[1].start: return+ d2 = (self.XX[sl] - cx) ** 2 + (self.YY[sl] - cy) ** 2+ prof = np.sqrt(np.clip(r * r - d2, 0, None)) * squash+ cover = np.clip(r - np.sqrt(d2) + 0.5, 0, 1)+ self._press(sl, self._base(sl, base) + prof, cover, colour, texture, gloss)++ def snake(self, pts, r, colour, taper=(1.0, 1.0), squash=0.8, base=None, smooth=True, texture=0.6, gloss=1.0):+ """a rolled coil of clay along a path (lines, rims, stems, waves, smiles); taper = radius factor at (start, end)"""+ P = spline(pts, 10) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)+ rmax = r * max(taper)+ x0, x1 = int(max(0, P[:, 0].min() - rmax - 3)), int(min(self.W, P[:, 0].max() + rmax + 4))+ y0, y1 = int(max(0, P[:, 1].min() - rmax - 3)), int(min(self.H, P[:, 1].max() + rmax + 4))+ if x1 <= x0 or y1 <= y0: return+ sl = (slice(y0, y1), slice(x0, x1))+ X, Y = self.XX[sl], self.YY[sl]+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); cum = np.concatenate([[0], np.cumsum(seg)]); L = cum[-1] + 1e-6+ best = np.full(X.shape, 1e9, np.float32); tpar = np.zeros(X.shape, np.float32)+ for i in range(len(P) - 1):+ a, b = P[i], P[i + 1]; d = b - a; l2 = float(d @ d) + 1e-9+ t = np.clip(((X - a[0]) * d[0] + (Y - a[1]) * d[1]) / l2, 0, 1)+ dist = np.hypot(X - a[0] - t * d[0], Y - a[1] - t * d[1])+ sel = dist < best+ best = np.where(sel, dist, best); tpar = np.where(sel, (cum[i] + t * seg[i]) / L, tpar)+ rr = r * (taper[0] + (taper[1] - taper[0]) * tpar)+ prof = np.sqrt(np.clip(rr * rr - best * best, 0, None)) * squash+ cover = np.clip(rr - best + 0.5, 0, 1)+ self._press(sl, self._base(sl, base) + prof, cover, colour, texture, gloss)++ def text(self, s, x, y, size, colour, height=None, font='rounded', anchor='mm', spacing=0.0, round=None, base=None):+ """puffy clay letters (any font style from core.load_font: rounded, sans_bold, cjk_sans, ...)"""+ m = text_mask(self.H, self.W, s, load_font(font, size), (x, y), anchor, spacing)+ return self.pad(m, colour, height if height is not None else size * 0.12, round if round is not None else size * 0.05, base, texture=0.5)++ def smear(self, mask, colour, strokes=220, length=(90, 190), width=(40, 70), angle=0.0, spread=0.5, height=6, drag=0.85):+ """a slab spread with fingertips: short curved finger strokes drag colour along and leave soft ridges.+ colour: a hex / RGB or an (H, W, 3) field -- the strokes smudge neighbouring colours into each other."""+ base_col = colour if np.ndim(colour) == 3 else np.broadcast_to(_c(colour), (self.H, self.W, 3))+ k = self.pad(mask, base_col, height, 3)+ if k is None: return+ field = self.alb.copy()+ ys, xs = np.nonzero(mask > 0.5)+ if len(xs) == 0: return+ for _ in range(strokes):+ i = int(self.rng.integers(len(xs))); sx, sy = float(xs[i]), float(ys[i])+ a = angle + self.rng.normal(0, spread); L = self.rng.uniform(*length); w = self.rng.uniform(*width)+ bend = self.rng.normal(0, 0.35)+ ex, ey = sx + np.cos(a) * L, sy + np.sin(a) * L+ mx, my = (sx + ex) / 2 - np.sin(a) * bend * L * 0.3, (sy + ey) / 2 + np.cos(a) * bend * L * 0.3+ P = spline([(sx, sy), (mx, my), (ex, ey)], 8)+ x0, x1 = int(max(0, P[:, 0].min() - w)), int(min(self.W, P[:, 0].max() + w + 1))+ y0, y1 = int(max(0, P[:, 1].min() - w)), int(min(self.H, P[:, 1].max() + w + 1))+ if x1 - x0 < 3 or y1 - y0 < 3: continue+ sl = (slice(y0, y1), slice(x0, x1))+ X, Y = self.XX[sl], self.YY[sl]+ best = np.full(X.shape, 1e9, np.float32); tp = np.zeros(X.shape, np.float32)+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); cum = np.concatenate([[0], np.cumsum(seg)])+ for j in range(len(P) - 1):+ a0, b0 = P[j], P[j + 1]; d = b0 - a0; l2 = float(d @ d) + 1e-9+ t = np.clip(((X - a0[0]) * d[0] + (Y - a0[1]) * d[1]) / l2, 0, 1)+ dist = np.hypot(X - a0[0] - t * d[0], Y - a0[1] - t * d[1])+ sel = dist < best; best = np.where(sel, dist, best); tp = np.where(sel, (cum[j] + t * seg[j]) / (cum[-1] + 1e-6), tp)+ u = best / (w / 2) # 0 centre .. 1 edge of the fingertip+ tp = np.clip(tp, 0, 1)+ env = smoothstep(1.9, 1.1, u) * smoothstep(0.0, 0.15, tp) * mask[sl]+ if env.max() <= 0: continue+ src = field[min(self.H - 1, int(sy)), min(self.W - 1, int(sx))] # colour picked up where the finger lands+ a_col = smoothstep(1.05, 0.45, u) * mask[sl] * drag * (1 - tp) ** 1.2+ self.alb[sl] = self.alb[sl] * (1 - a_col[..., None]) + src * a_col[..., None]+ # a shallow scoop under the fingertip, soft ridges of pushed clay along both sides and at the end+ prof = -0.7 * (1 - smoothstep(0.0, 1.1, u)) + 0.8 * np.exp(-((u - 1.05) / 0.38) ** 2)+ prof = prof * (1 - 0.4 * tp) + 0.9 * np.exp(-((tp - 0.97) / 0.07) ** 2) * (1 - smoothstep(0.3, 1.1, u))+ self.h[sl] = self.h[sl] + prof * env * height * 0.32++ def groove(self, pts, width, depth, smooth=True):+ """a line pressed in with a modelling tool (a trough with slightly raised lips)"""+ P = spline(pts, 10) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)+ w = width+ x0, x1 = int(max(0, P[:, 0].min() - w * 2 - 2)), int(min(self.W, P[:, 0].max() + w * 2 + 3))+ y0, y1 = int(max(0, P[:, 1].min() - w * 2 - 2)), int(min(self.H, P[:, 1].max() + w * 2 + 3))+ if x1 <= x0 or y1 <= y0: return+ sl = (slice(y0, y1), slice(x0, x1))+ X, Y = self.XX[sl], self.YY[sl]+ best = np.full(X.shape, 1e9, np.float32)+ for i in range(len(P) - 1):+ a, b = P[i], P[i + 1]; d = b - a; l2 = float(d @ d) + 1e-9+ t = np.clip(((X - a[0]) * d[0] + (Y - a[1]) * d[1]) / l2, 0, 1)+ best = np.minimum(best, np.hypot(X - a[0] - t * d[0], Y - a[1] - t * d[1]))+ u = best / (w / 2)+ trough = np.sqrt(np.clip(1 - u * u, 0, 1))+ lip = np.exp(-((u - 1.25) / 0.3) ** 2) * 0.25+ self.h[sl] -= depth * (trough - lip)++ def poke(self, cx, cy, r, depth):+ """a hole pushed in with a tool tip (portholes, nostrils, texture dots)"""+ m = int(r * 1.8 + 2)+ sl = (slice(max(0, int(cy - m)), min(self.H, int(cy + m + 1))), slice(max(0, int(cx - m)), min(self.W, int(cx + m + 1))))+ d = np.hypot(self.XX[sl] - cx, self.YY[sl] - cy) / r+ self.h[sl] -= depth * (np.sqrt(np.clip(1 - d * d, 0, 1)) - 0.22 * np.exp(-((d - 1.2) / 0.25) ** 2))++ def backdrop(self, colour, texture=1.0, lumps=3.0):+ """the board itself: a flat slab of one colour (or an (H, W, 3) field) with gentle hand-made unevenness"""+ self.alb = (np.broadcast_to(_c(colour), (self.H, self.W, 3)) if np.ndim(colour) < 3 else colour.copy()).astype(np.float32)+ self.alb = self.alb * (1 + 0.05 * self.tint)[..., None]+ self.h = (self.lump * lumps + self.fine * 0.35 + self.prints * 0.2) * texture++ # ------------------------------------------------------------ light and output+ def render(self, key=('#fff4e2', 1.0), fill=('#c9dcff', 0.28), ambient=0.34, sheen=0.16, shadow=0.62, ao=0.55,+ reach=180, grain=0.018, vignette=0.16):+ h = self.h+ n = height_normals(h)+ L = self.light+ wrap = 0.3+ diff = np.clip((n @ L + wrap) / (1 + wrap), 0, 1)+ Lf = np.array([-L[0], -L[1] * 0.3, 0.7], np.float32); Lf /= np.linalg.norm(Lf)+ fil = np.clip(n @ Lf, 0, 1)+ sh = blur(height_shadow(h, tuple(L), reach=reach, step=2.0, soft=2.5), 2.2)+ occ = ambient_occlusion(h)+ kc, ki = _c(key[0]), key[1]; fc, fi = _c(fill[0]), fill[1]+ direct = (diff * (1 - shadow * sh))[..., None] * kc * ki+ amb = (ambient * (1 - ao * occ))[..., None] * np.array([0.93, 0.97, 1.05], np.float32)+ light = direct + amb + (fil * fi * (1 - 0.5 * occ))[..., None] * fc+ alb = self.alb+ deep = np.clip(1 - light.mean(-1, keepdims=True), 0, 1) * 0.35 # clay shadows stay saturated (a little subsurface)+ sat = np.clip(alb + (alb - alb.mean(-1, keepdims=True)) * deep, 0, 1)+ img = sat * light+ Hv = L + np.array([0, 0, 1], np.float32); Hv /= np.linalg.norm(Hv)+ spec = np.clip(n @ Hv, 0, 1) ** 24 * sheen * self.gloss * (1 - 0.8 * sh)+ img = img + spec[..., None] * kc+ r = np.hypot((self.XX - self.W / 2) / self.W, (self.YY - self.H / 2) / self.H)+ img = img * (1 - vignette * r ** 2 * 2.2)[..., None]+ if grain:+ img = img + (np.random.default_rng(7).normal(0, grain, (self.H, self.W, 1))).astype(np.float32)+ return np.clip(img, 0, 1)++ def composite(self):+ return Image.fromarray((self.render() * 255).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None):+ img = self.composite(); 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/core.py b/lib/core.pyindex 33ddf94..c54841a 100644--- a/lib/core.py+++ b/lib/core.py@@ -148,3 +148,118 @@ def bristle_stroke(buf, pts, width, ink, dry=0.35, taper=(0.25, 0.35), jitter=0.k = np.exp(-((kx - (cx - ix)) ** 2 + (ky - (cy - iy)) ** 2) / (2 * (br * press[i]) ** 2 + 1e-3))sl = buf[iy - rad:iy + rad + 1, ix - rad:ix + rad + 1]np.copyto(sl, 1 - (1 - sl) * (1 - k * ink * load[i] * 0.55))+++# ---------------------------------------------------------------- helpers shared by clay / cyanotype / stitch / panel+def shift(a, dx, dy):+ """zero-padded shift, no wrap-around: out[y, x] = a[y - dy, x - dx]"""+ dx, dy = int(round(dx)), int(round(dy))+ H, W = a.shape[:2]+ out = np.zeros_like(a)+ if abs(dx) >= W or abs(dy) >= H: return out+ out[max(dy, 0):H + min(dy, 0), max(dx, 0):W + min(dx, 0)] = a[max(-dy, 0):H + min(-dy, 0), max(-dx, 0):W + min(-dx, 0)]+ return out+++_FONT_CANDIDATES = { # (glob pattern, face index); first hit wins -- macOS, Linux, Windows+ 'sans': [('/System/Library/Fonts/HelveticaNeue.ttc', 0), ('/System/Library/Fonts/Helvetica.ttc', 0),+ ('/usr/share/fonts/**/DejaVuSans.ttf', 0), ('/usr/share/fonts/**/LiberationSans-Regular.ttf', 0), ('C:/Windows/Fonts/arial.ttf', 0)],+ 'sans_bold': [('/System/Library/Fonts/HelveticaNeue.ttc', 1), ('/System/Library/Fonts/Supplemental/Arial Bold.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSans-Bold.ttf', 0), ('/usr/share/fonts/**/LiberationSans-Bold.ttf', 0), ('C:/Windows/Fonts/arialbd.ttf', 0)],+ 'rounded': [('/System/Library/Fonts/Supplemental/Arial Rounded Bold.ttf', 0), ('/usr/share/fonts/**/Nunito*Black*.ttf', 0),+ ('/usr/share/fonts/**/DejaVuSans-Bold.ttf', 0), ('C:/Windows/Fonts/ARLRDBD.TTF', 0), ('C:/Windows/Fonts/arialbd.ttf', 0)],+ 'geometric': [('/System/Library/Fonts/Supplemental/Futura.ttc', 0), ('/System/Library/Fonts/Avenir Next.ttc', 5),+ ('/usr/share/fonts/**/URWGothic-Book.*', 0), ('/usr/share/fonts/**/DejaVuSans.ttf', 0), ('C:/Windows/Fonts/GOTHIC.TTF', 0), ('C:/Windows/Fonts/arial.ttf', 0)],+ 'condensed': [('/System/Library/Fonts/Supplemental/DIN Condensed Bold.ttf', 0), ('/System/Library/Fonts/HelveticaNeue.ttc', 4),+ ('/usr/share/fonts/**/DejaVuSansCondensed-Bold.ttf', 0), ('C:/Windows/Fonts/ARIALNB.TTF', 0), ('C:/Windows/Fonts/arialbd.ttf', 0)],+ 'serif': [('/System/Library/Fonts/Supplemental/Georgia.ttf', 0), ('/System/Library/Fonts/Times.ttc', 0),+ ('/usr/share/fonts/**/DejaVuSerif.ttf', 0), ('C:/Windows/Fonts/georgia.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)],+ 'hand': [('/System/Library/Fonts/Supplemental/Bradley Hand Bold.ttf', 0), ('/System/Library/Fonts/Noteworthy.ttc', 0),+ ('/usr/share/fonts/**/*Kalam*Regular*.ttf', 0), ('/usr/share/fonts/**/*Caveat*.ttf', 0), ('C:/Windows/Fonts/segoepr.ttf', 0), ('C:/Windows/Fonts/comic.ttf', 0)],+ 'script': [('/System/Library/Fonts/Supplemental/SnellRoundhand.ttc', 1), ('/System/Library/Fonts/Supplemental/Apple Chancery.ttf', 0),+ ('/usr/share/fonts/**/z003*.[ot]tf', 0), ('C:/Windows/Fonts/segoesc.ttf', 0), ('C:/Windows/Fonts/Gabriola.ttf', 0)],+ 'cjk_sans': [('/System/Library/Fonts/STHeiti Medium.ttc', 0), ('/System/Library/Fonts/Hiragino Sans GB.ttc', 2),+ ('/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)],+}+++def latin_font(style='sans'):+ """(path, face_index) of a system font for `style`, or None.+ styles: sans, sans_bold, rounded, geometric, condensed, serif, typewriter, hand, script, cjk_sans, cjk.+ Override any style with $INKPAINT_FONT_<STYLE>, e.g. INKPAINT_FONT_HAND=/path/to/font.ttf"""+ env = os.environ.get('INKPAINT_FONT_' + style.upper())+ if env and os.path.exists(env): return env, 0+ if style == 'cjk':+ p = cjk_font()+ return (p, 0) if p else None+ for pat, idx in _FONT_CANDIDATES.get(style, []):+ fs = glob.glob(pat, recursive=True)+ if fs: return fs[0], idx+ return None+++def load_font(style, size):+ """PIL font for `style` at `size` px; falls back to the sans font, then the CJK font, then Pillow's default"""+ from PIL import ImageFont+ for st in (style, 'sans', 'cjk'):+ hit = latin_font(st)+ if hit:+ try:+ return ImageFont.truetype(hit[0], int(size), index=hit[1])+ except OSError:+ pass+ return ImageFont.load_default(size)+++def text_mask(h, w, s, font, xy, anchor='la', spacing=0.0, rot=0.0):+ """text -> anti-aliased float mask (h, w) in 0..1.+ font: a PIL font (see load_font); anchor as in Pillow ('la', 'mm', 'rs', ...);+ spacing: extra px between letters (letter-spaced legends); rot: degrees counter-clockwise about xy"""+ from PIL import ImageDraw+ im = Image.new('L', (w, h), 0)+ d = ImageDraw.Draw(im)+ x, y = float(xy[0]), float(xy[1])+ if not spacing:+ d.text((x, y), s, font=font, fill=255, anchor=anchor)+ else:+ adv = [font.getlength(ch) + spacing for ch in s]+ total = sum(adv) - spacing+ x0 = x - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ for ch, a in zip(s, adv):+ d.text((x0, y), ch, font=font, fill=255, anchor='l' + anchor[1])+ x0 += a+ if rot:+ im = im.rotate(rot, resample=Image.BICUBIC, center=(x, y))+ return np.asarray(im, np.float32) / 255+++def height_normals(hmap):+ """unit surface normals (H, W, 3) of a height field measured in pixels"""+ gy, gx = np.gradient(hmap.astype(np.float32))+ n = np.stack([-gx, -gy, np.ones_like(gx)], -1)+ return n / np.linalg.norm(n, axis=-1, keepdims=True)+++def height_shadow(hmap, light=(-0.45, -0.62, 0.64), reach=160, step=2.0, soft=3.0):+ """cast shadow of a height field onto itself: 0 lit .. 1 in shadow.+ March from every pixel toward the light; if the terrain rises above the light ray, the pixel is shadowed."""+ lx, ly, lz = light+ l = float(np.hypot(lx, ly)) + 1e-6+ dx, dy, slope = lx / l, ly / l, lz / l # slope: how fast the ray climbs per px+ occ = np.full(hmap.shape, -1e9, np.float32)+ t = step+ while t <= reach:+ s = shift(hmap, -dx * t, -dy * t) - t * slope+ np.maximum(occ, s, out=occ)+ t += step+ return smoothstep(0.0, soft, occ - hmap)+++def ambient_occlusion(hmap, radii=(4, 12, 32), depth=(6.0, 14.0, 30.0)):+ """crevices and the feet of raised shapes get less sky light: 0 open .. 1 occluded"""+ ao = np.zeros(hmap.shape, np.float32)+ for r, k in zip(radii, depth):+ ao += np.clip((blur(hmap, r) - hmap) / k, 0, 1)+ return np.clip(ao / len(radii), 0, 1)diff --git a/lib/cyanotype.py b/lib/cyanotype.pynew file mode 100644index 0000000..915a1d9--- /dev/null+++ b/lib/cyanotype.py@@ -0,0 +1,217 @@+"""cyanotype — sun print / photogram in Prussian blue (numpy + Pillow only).++Model (how a real cyanotype is made):+ 1. rag paper is brushed with iron-salt emulsion -> the coated area has ragged, streaky brushed edges+ and uneven thickness (it only turns blue where it was coated);+ 2. objects are laid on it under glass and the sheet is put in the sun. Each object *blocks* part of the UV:+ transmission multiplies, T = product(1 - opacity_i * mask_i). Thin leaves let a little light through+ (a pale blue body with whiter veins); things that don't lie flat (fluff, curled stems) are lifted off the+ paper and cast a soft penumbra instead of a sharp edge; light also scatters a little under every edge;+ 3. exposure E = coat x T x (uneven sunlight) is developed in water: Prussian-blue density D = 1 - exp(-k E),+ mapped through paper-white -> pale cyan -> deep Prussian blue; the paper tooth shows through the blue.+White handwriting can be printed in (written on a transparency, `label`), and pencil notes added on the+paper margin afterwards (`pencil`).++ from cyanotype import Cyanotype+ cy = Cyanotype(1920, 1080, seed=1)+ cy.coat(90, 70, 1830, 1010) # brushed emulsion area+ cy.place(cy.shapes([leaf1, leaf2]), opacity=0.9) # leaves pressed flat+ cy.place(cy.lines([vein1, vein2], 2), opacity=1.0) # veins block fully -> whiter+ cy.place(cy.lines(fluff, 1.2), opacity=0.35, lift=3) # fluff lifted off the paper -> soft+ cy.label('Ginkgo biloba', 1500, 960, 44)+ cy.save('out.png')+"""+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, blob_pts, load_font, text_mask+++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)+++class Cyanotype:+ RAMP = [(0.0, '#f3f0e6'), (0.18, '#c9d9e6'), (0.42, '#7ea5cc'), (0.68, '#2e64a1'), (0.86, '#174a86'), (1.0, '#0f3466')]++ def __init__(self, W=1920, H=1080, seed=0, paper='#f4f1e7', ramp=None, strength=3.0):+ 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.paper_col = _c(paper)+ self.ramp = ramp or self.RAMP+ self.k = strength+ self.trans = np.ones((H, W), np.float32) # how much UV reaches the paper+ self.coat_m = None+ s = int(self.rng.integers(1 << 30))+ self.tooth = noise2d(H, W, 1.8, 2, s) * 0.6 + noise2d(H, W, 6, 2, s + 1) * 0.4+ self.sun = 0.9 + 0.14 * noise2d(H, W, 380, 3, s + 2) # uneven sunlight / glass / coating thickness+ self.labels = []+ self.notes = []+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ the brushed emulsion+ def coat(self, x0, y0, x1, y1, ragged=1.0, strokes=None, splatter=14):+ """brush the emulsion onto a rectangle with overlapping horizontal brush strokes (~140 px wide):+ every stroke starts and stops at its own place, its ends thin into dry-brush bristle streaks,+ the top and bottom edges are the gently wavy sides of the first and last strokes"""+ H, W = self.H, self.W+ X, Y = self.XX, self.YY+ n = strokes or max(3, int(round((y1 - y0) / 130)))+ pitch = (y1 - y0) / n+ cov = np.zeros((H, W), np.float32)+ for k in range(n):+ s = self._seed()+ top = y0 + k * pitch - (0 if k == 0 else pitch * 0.18)+ bot = y0 + (k + 1) * pitch + (0 if k == n - 1 else pitch * 0.18)+ wav_t = fbm1d(W, 160, 3, s) * 10 * ragged + fbm1d(W, 6, 2, s + 1) * 1.2 * ragged+ wav_b = fbm1d(W, 160, 3, s + 2) * 10 * ragged + fbm1d(W, 6, 2, s + 3) * 1.2 * ragged+ band = smoothstep(-1.5, 1.5, Y - (top + wav_t)[None, :]) * smoothstep(-1.5, 1.5, (bot + wav_b)[None, :] - Y)+ xs = x0 + self.rng.normal(0, 22) * ragged; xe = x1 + self.rng.normal(0, 22) * ragged+ hair = np.interp(Y[:, 0], np.arange(H), fbm1d(H, 2.5, 3, s + 4)) # per-hair variation, ~1 px+ clump = np.interp(Y[:, 0], np.arange(H), fbm1d(H, 16, 3, s + 5)) # hairs clump in groups+ reach = (0.35 * hair + 0.65 * clump)[:, None] * 0.5 + 0.5 # 0..1: how far each hair drags on+ dry = 80 * ragged+ end_s = xs - dry * reach; end_e = xe + dry * reach+ sharp = smoothstep(-1.2, 1.2, X - end_s) * smoothstep(-1.2, 1.2, end_e - X) # every hair stops crisply+ inner = smoothstep(0, dry * 1.2, np.minimum(X - end_s, end_e - X)) # 0 at the ragged end .. 1 inside+ streaks = np.asarray(Image.fromarray(self.rng.random((H // 2, W // 14)).astype(np.float32)).resize((W, H), Image.BILINEAR))+ keep = smoothstep(0.42, 0.5, streaks * 0.8 + inner * 0.55 + 0.1) # dry brush breaks up near the ends+ thick = 0.94 + 0.06 * (np.interp(Y[:, 0], np.arange(H), fbm1d(H, 9, 3, s + 6))[:, None])+ cov = np.maximum(cov, band * sharp * keep * (0.82 + 0.18 * inner) * thick)+ for _ in range(splatter): # a few drops flicked off the brush+ side = int(self.rng.integers(4))+ if side < 2:+ x = self.rng.uniform(x0, x1); y = (y0 - self.rng.uniform(8, 40)) if side == 0 else (y1 + self.rng.uniform(8, 40))+ else:+ y = self.rng.uniform(y0, y1); x = (x0 - self.rng.uniform(70, 130)) if side == 2 else (x1 + self.rng.uniform(70, 130))+ r = self.rng.uniform(1.2, 4.5)+ cov = np.maximum(cov, np.clip(r - np.hypot(X - x, (Y - y) * self.rng.uniform(0.8, 1.3)) + 0.5, 0, 1) * 0.9)+ self.coat_m = np.clip(cov, 0, 1).astype(np.float32)++ # ------------------------------------------------------------ masks+ def shapes(self, polys, ss=2):+ """many closed outlines -> one mask, drawn in a single pass (fast for hundreds of leaflets)"""+ im = Image.new('L', (self.W * ss, self.H * ss), 0); d = ImageDraw.Draw(im)+ for pts in polys:+ d.polygon([(float(x) * ss, float(y) * ss) for x, y in pts], fill=255)+ if ss > 1: im = im.resize((self.W, self.H), Image.BILINEAR)+ return np.asarray(im, np.float32) / 255++ def lines(self, polylines, width, ss=2, taper=False):+ """many open polylines (stems, veins, filaments) -> one mask; taper=True thins each line toward its end"""+ im = Image.new('L', (self.W * ss, self.H * ss), 0); d = ImageDraw.Draw(im)+ for pts in polylines:+ P = [(float(x) * ss, float(y) * ss) for x, y in pts]+ if not taper or len(P) < 3:+ d.line(P, fill=255, width=max(1, int(round(width * ss))), joint='curve')+ else:+ n = len(P) - 1+ for i in range(n):+ w = width * (1 - 0.75 * i / n)+ d.line([P[i], P[i + 1]], fill=255, width=max(1, int(round(w * ss))))+ r = w * ss / 2+ d.ellipse((P[i + 1][0] - r, P[i + 1][1] - r, P[i + 1][0] + r, P[i + 1][1] + r), fill=255)+ if ss > 1: im = im.resize((self.W, self.H), Image.BILINEAR)+ return np.asarray(im, np.float32) / 255++ def poly(self, pts):+ return polygon_mask(self.H, self.W, pts, ss=2)++ def circle(self, cx, cy, r):+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)++ @staticmethod+ def leaf_pts(x, y, angle, length, width, tip=0.55, n=28, serrate=0.0, blunt=0.0):+ """a simple leaf/leaflet outline from its base (x, y) pointing along `angle`.+ tip < 0.5 fattens toward the tip; blunt 0..1 rounds the tip off (oblong fern pinnules);+ serrate > 0 adds small teeth"""+ t = np.linspace(0, 1, n)+ pointed = np.sin(np.pi * t ** tip) * (1 - 0.15 * t)+ oval = np.sqrt(np.clip(1 - (2 * t - 1) ** 2, 0, 1))+ half = width / 2 * ((1 - blunt) * pointed + blunt * oval)+ if serrate:+ half = half * (1 + serrate * (np.arange(n) % 2) * np.sin(np.pi * t))+ c, s = np.cos(angle), np.sin(angle)+ up = [(x + c * length * ti - s * hi, y + s * length * ti + c * hi) for ti, hi in zip(t, half)]+ dn = [(x + c * length * ti + s * hi, y + s * length * ti - c * hi) for ti, hi in zip(t[::-1], half[::-1])]+ return np.array(up + dn, np.float32)++ # ------------------------------------------------------------ laying things on the paper+ def place(self, mask, opacity=1.0, lift=0.0, texture=0.0):+ """lay an object on the paper. opacity: how much UV it stops (thin leaf ~0.85, card 1.0, fluff ~0.3);+ lift: px it stands off the paper (0 pressed flat under glass -> sharp; 2-8 -> soft penumbra);+ texture: internal unevenness of a translucent object (leaf tissue)"""+ m = blur(mask, lift) if lift > 0 else mask+ m = blur(m, 0.6) # even pressed edges are not razor sharp+ op = opacity+ if texture:+ op = opacity * (1 - texture * noise2d(self.H, self.W, 14, 3, self._seed()))+ self.trans *= (1 - np.clip(m * op, 0, 1))++ def line(self, pts, width, opacity=1.0, lift=0.0, taper=False):+ self.place(self.lines([pts], width, taper=taper), opacity, lift)++ def label(self, s, x, y, size=44, font='hand', anchor='la', rot=0.0, opacity=0.96):+ """white handwriting printed with the plants (ink on a transparency laid on the paper)"""+ self.labels.append((s, x, y, size, font, anchor, rot, opacity))++ def pencil(self, s, x, y, size=30, font='hand', anchor='la', rot=0.0, colour='#6b6f78'):+ """graphite note written on the paper margin after the print was washed"""+ self.notes.append((s, x, y, size, font, anchor, rot, colour))++ # ------------------------------------------------------------ develop+ def _colour(self, D):+ xs = [p for p, _ in self.ramp]+ cols = np.stack([_c(c) for _, c in self.ramp])+ out = np.empty(D.shape + (3,), np.float32)+ for ch in range(3):+ out[..., ch] = np.interp(D, xs, cols[:, ch])+ return out++ def develop(self):+ trans = self.trans.copy()+ for (s, x, y, size, font, anchor, rot, op) in self.labels:+ m = text_mask(self.H, self.W, s, load_font(font, size), (x, y), anchor, rot=rot)+ trans *= 1 - blur(m, 0.7) * op+ blocked = 1 - trans+ halo = blur(blocked, 5) * 0.22 + blur(blocked, 16) * 0.08 # light scattering under the edges+ t_eff = np.clip(trans * (1 - halo), 0, 1)+ coat = self.coat_m if self.coat_m is not None else np.ones((self.H, self.W), np.float32)+ E = coat * t_eff * self.sun+ D = (1 - np.exp(-self.k * E)) / (1 - np.exp(-self.k))+ D = np.clip(D * (1 - 0.07 * (self.tooth - 0.5)) - 0.02 * (self.tooth > 0.8), 0, 1)+ img = self._colour(D)+ paper = self.paper_col * (0.975 + 0.04 * self.tooth)[..., None]+ img = img * (paper / _c(self.ramp[0][1])) # paper fibre shows through the whole sheet+ stain = coat * (1 - D) * 0.06 # washed-out emulsion leaves a faint blue cast in the whites+ img = img * (1 - stain[..., None]) + _c('#9fbfd8') * stain[..., None]+ return img++ def composite(self):+ img = self.develop()+ for (s, x, y, size, font, anchor, rot, colour) in self.notes:+ m = text_mask(self.H, self.W, s, load_font(font, size), (x, y), anchor, rot=rot)+ m = m * (0.6 + 0.4 * self.tooth) # graphite catches on the tooth+ img = img * (1 - m[..., None] * (1 - _c(colour)))+ 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(); 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/panel.py b/lib/panel.pynew file mode 100644index 0000000..37503d3--- /dev/null+++ b/lib/panel.py@@ -0,0 +1,383 @@+"""panel — vintage industrial-design fronts: radios, hi-fi, instruments (numpy + Pillow only).++Model: a product front is built like the real thing, part by part, and every part is lit by one key light+from the upper left:+ materials teak veneer (warped growth rings + pores + satin varnish), brushed aluminium (brushing streaks+ + a broad anisotropic highlight), moulded plastic, painted metal, woven grille cloth (with lurex+ threads), perforated metal;+ relief raised plates, bevelled edges and recessed wells are small height fields: edges facing the light+ catch a highlight, the far edges fall into shadow, raised parts cast soft drop shadows;+ controls machined knobs (lathe rings, radial sheen, knurled skirt, indicator), piano-key buttons, bat-handle+ toggle switches, jewel lamps with glow, a green "magic eye" tuning tube, a moving-coil meter,+ slotted screws;+ print silkscreened legends (letter-spaced sans), arc and linear scales, a backlit dial behind glass+ with a needle and a reflection streak, a chrome script badge.++ from panel import Panel+ p = Panel(1920, 1080, seed=1)+ p.background('#b9c7bd')+ body = p.rrect(100, 120, 1820, 950, 40)+ p.surface(body, 'wood', '#8a5230', height=10, shadow=0.5)+ p.knob(1200, 740, 70, angle=-40)+ p.scale_arc(1200, 740, 84, 100, -135, 135, 11, labels=['0', '5', '10'])+ p.text('VOLUME', 1200, 850, 22, spacing=6, anchor='mm')+ p.save('out.png')+"""+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, shift, load_font, text_mask, height_normals+++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)+++class Panel:+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.5, -0.62, 0.6)):+ 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) * 0.8+ self.fine = noise2d(H, W, 1.3, 2, int(self.rng.integers(1 << 30)))+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ def _box(self, mask, margin=0):+ ys, xs = np.nonzero(mask > 0.002)+ if len(xs) == 0: return None+ return (slice(max(0, ys.min() - margin), min(self.H, ys.max() + margin + 1)),+ slice(max(0, xs.min() - margin), min(self.W, xs.max() + margin + 1)))++ # ------------------------------------------------------------ masks+ def rrect(self, x0, y0, x1, y1, r):+ im = Image.new('L', (self.W * 2, self.H * 2), 0)+ ImageDraw.Draw(im).rounded_rectangle((x0 * 2, y0 * 2, x1 * 2, y1 * 2), r * 2, fill=255)+ return np.asarray(im.resize((self.W, self.H), Image.BILINEAR), np.float32) / 255++ 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 poly(self, pts):+ return polygon_mask(self.H, self.W, pts, ss=2)++ def line_mask(self, pts, width):+ im = Image.new('L', (self.W * 2, self.H * 2), 0)+ ImageDraw.Draw(im).line([(float(x) * 2, float(y) * 2) for x, y in pts], fill=255, width=max(1, int(round(width * 2))), joint='curve')+ return np.asarray(im.resize((self.W, self.H), Image.BILINEAR), np.float32) / 255++ # ------------------------------------------------------------ materials (generated inside a box)+ def material(self, kind, colour, sl, **kw):+ H, W = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start+ X, Y = self.XX[sl], self.YY[sl]+ col = _c(colour)+ base = np.ones((H, W, 3), np.float32) * col+ s = self._seed()+ if kind == 'plastic': # moulded: faint orange-peel, gentle gradient+ t = 1.0 + 0.012 * (noise2d(H, W, 2.0, 2, s) - 0.5) + 0.03 * (noise2d(H, W, 260, 2, s + 1) - 0.5)+ return base * t[..., None]+ if kind == 'painted':+ t = 1.0 + 0.02 * (noise2d(H, W, 1.5, 2, s) - 0.5) + 0.04 * (noise2d(H, W, 180, 3, s + 1) - 0.5)+ return base * t[..., None]+ if kind == 'brushed': # aluminium brushed along x (or radially)+ rows = np.interp(Y[:, 0], np.arange(self.H), fbm1d(self.H, 1.5, 3, s))[:, None]+ streak = 0.6 * rows + 0.4 * (np.asarray(Image.fromarray(self.rng.random((H, max(2, W // 40))).astype(np.float32)).resize((W, H), Image.BILINEAR)) - 0.5)+ band = kw.get('band', 0.5)+ u = (X - X.min()) / max(1, W)+ aniso = 0.9 + 0.14 * np.exp(-((u - band) / 0.28) ** 2) - 0.05 * u+ return base * (aniso + 0.045 * streak)[..., None]+ if kind == 'wood': # teak veneer: warped growth rings, rays, pores+ dark = _c(kw.get('dark', '#5c3118')); light = _c(kw.get('light', '#b07442'))+ warp = noise2d(H, W, 220, 3, s) * 60 + noise2d(H, W, 40, 2, s + 1) * 8+ v = (Y + warp) * kw.get('ring_scale', 0.12) + 3 * np.sin(X / 380 + noise2d(H, W, 500, 2, s + 2) * 3)+ rings = 0.5 + 0.5 * np.sin(v + 1.5 * np.sin(v * 0.37))+ rings = rings ** 1.8+ fig = noise2d(H, W, 90, 3, s + 3)+ t = np.clip(0.55 * rings + 0.35 * fig + 0.1 * self.fine[sl], 0, 1)+ c = col * (1 - t[..., None] * 0.55) + dark * (t[..., None] * 0.55)+ c = c * (1 - 0.25 * (1 - rings)[..., None]) + light * (0.25 * (1 - rings))[..., None]+ pores = np.asarray(Image.fromarray(self.rng.random((H, max(2, W // 9))).astype(np.float32)).resize((W, H), Image.BILINEAR))+ c *= (1 - 0.18 * smoothstep(0.82, 0.95, pores))[..., None]+ return c+ if kind == 'fabric': # woven grille cloth with metallic lurex threads+ p = kw.get('pitch', 4.0)+ wx = 0.5 + 0.5 * np.cos(2 * np.pi * X / p); wy = 0.5 + 0.5 * np.cos(2 * np.pi * Y / p)+ over = ((np.floor(X / p) + np.floor(Y / p)) % 2)+ weave = np.where(over > 0, wx * 0.6 + 0.4, wy * 0.6 + 0.4)+ slub = noise2d(H, W, 3, 2, s)+ c = base * (0.78 + 0.22 * weave + 0.06 * (slub - 0.5))[..., None]+ lur = kw.get('lurex')+ if lur: # a metallic weft floating over 3 warps, then under 1+ every = kw.get('lurex_every', 7)+ ty = (Y / p) % 1+ rowline = (np.floor(Y / p) % every == 0) & (np.floor(X / p) % 4 != 0)+ cyl = 0.7 + 0.45 * np.sin(np.pi * ty)+ shine = 0.9 + 0.18 * np.cos(2 * np.pi * X / 97 + 1.3) + 0.08 * (slub - 0.5)+ c = np.where(rowline[..., None], _c(lur) * (cyl * shine)[..., None], c)+ return c+ if kind == 'glass':+ return base+ raise ValueError(kind)++ # ------------------------------------------------------------ relief and compositing+ def _relief(self, mask, height, soft):+ """lighting multiplier for a mask raised (height > 0) or sunk (height < 0) with rounded edges"""+ h = blur(mask, soft) * height+ n = height_normals(h)+ return 1 + 1.6 * (n @ self.L - self.L[2])++ def drop_shadow(self, mask, dist=8, soft=8, strength=0.45, colour='#1c1712'):+ d = np.array([-self.L[0], -self.L[1]]); d /= np.linalg.norm(d)+ sh = blur(shift(mask, d[0] * dist, d[1] * dist), soft)+ self.img = self.img * (1 - (strength * sh * (1 - mask))[..., None] * (1 - _c(colour)))++ def surface(self, mask, kind='plastic', colour='#e7e3da', height=4, soft=None, shadow=0.0, shadow_dist=None, **kw):+ """lay a part of some material: raised (height > 0, bevelled toward the light) or sunk (height < 0)"""+ sl = self._box(mask, 4)+ if sl is None: return+ soft = soft if soft is not None else max(1.0, abs(height) * 0.7)+ if shadow:+ self.drop_shadow(mask, shadow_dist if shadow_dist is not None else abs(height) * 1.4 + 2, abs(height) * 1.2 + 3, shadow)+ m = mask[sl]+ fill = self.material(kind, colour, sl, **kw)+ rel = self._relief(m, height, soft) if height else 1.0+ fill = fill * np.clip(rel, 0.3, 1.8)[..., None] if height else fill+ self.img[sl] = self.img[sl] * (1 - m[..., None]) + np.clip(fill, 0, 1) * m[..., None]++ def recess(self, mask, kind='painted', colour='#2b2a27', depth=10, **kw):+ """a sunken well: the floor is shaded by the wall on the light side, the far rim catches light"""+ sl = self._box(mask, int(depth * 2 + 6))+ if sl is None: return+ m = mask[sl]+ fill = self.material(kind, colour, sl, **kw)+ d = np.array([-self.L[0], -self.L[1]]); d /= np.linalg.norm(d)+ inner = m * blur(shift(1 - m, d[0] * depth, d[1] * depth), depth * 0.8)+ fill = fill * (1 - 0.6 * inner)[..., None]+ rim = self._relief(m, -depth * 0.6, 2.0)+ self.img[sl] = self.img[sl] * (1 - m[..., None]) + np.clip(fill, 0, 1) * m[..., None]+ edge = np.clip(blur(m, 1.5) - m, 0, 1) + np.clip(m - blur(m, 1.5), 0, 1)+ self.img[sl] = self.img[sl] * np.clip(1 + (rim - 1) * np.clip(edge * 3, 0, 1), 0.5, 1.6)[..., None]++ def paint(self, mask, colour, alpha=1.0):+ """flat colour on top (print, inlay), no relief"""+ a = np.clip(mask * alpha, 0, 1)[..., None]+ self.img = self.img * (1 - a) + _c(colour) * a++ def glow(self, x, y, r, colour, strength=0.6):+ g = np.exp(-((self.XX - x) ** 2 + (self.YY - y) ** 2) / (2 * r * r)) * strength+ self.img = 1 - (1 - self.img) * (1 - g[..., None] * _c(colour))++ def text(self, s, x, y, size, colour='#2b2a27', font='sans_bold', anchor='mm', spacing=0.0, rot=0.0, alpha=0.95):+ """silkscreened legend"""+ m = text_mask(self.H, self.W, s, load_font(font, size), (x, y), anchor, spacing, rot)+ self.paint(m * (0.92 + 0.08 * self.fine), colour, alpha)++ def scale_arc(self, cx, cy, r0, r1, a0=-135, a1=135, n=11, major=5, colour='#2b2a27', labels=None, label_r=None,+ size=18, font='sans_bold', width=2.0):+ """printed arc scale; angles in degrees clockwise from 12 o'clock"""+ segs = []+ for i in range(n):+ a = np.deg2rad(a0 + (a1 - a0) * i / (n - 1))+ big = (i % major == 0) if major else True+ ri = r0 if big else r0 + (r1 - r0) * 0.45+ segs.append(((cx + np.sin(a) * ri, cy - np.cos(a) * ri), (cx + np.sin(a) * r1, cy - np.cos(a) * r1), width * (1.4 if big else 0.9)))+ m = np.zeros((self.H, self.W), np.float32)+ for p0, p1, w in segs:+ m = np.maximum(m, self.line_mask([p0, p1], w))+ self.paint(m, colour)+ if labels:+ lr = label_r or r1 + size * 1.1+ for i, lab in enumerate(labels):+ a = np.deg2rad(a0 + (a1 - a0) * i / max(1, len(labels) - 1))+ self.text(lab, cx + np.sin(a) * lr, cy - np.cos(a) * lr, size, colour, font)++ def scale_linear(self, x0, x1, y, n, major=5, length=18, colour='#2b2a27', labels=None, size=20, font='sans_bold', up=True, width=2.0, label_gap=14):+ m = np.zeros((self.H, self.W), np.float32)+ for i in range(n):+ x = x0 + (x1 - x0) * i / (n - 1)+ big = (i % major == 0) if major else True+ L = length if big else length * 0.55+ m = np.maximum(m, self.line_mask([(x, y), (x, y - L if up else y + L)], width * (1.3 if big else 0.9)))+ self.paint(m, colour)+ if labels:+ for i, lab in enumerate(labels):+ if lab is None: continue+ x = x0 + (x1 - x0) * i / max(1, len(labels) - 1)+ self.text(lab, x, y - length - label_gap if up else y + length + label_gap, size, colour, font)++ # ------------------------------------------------------------ controls+ def knob(self, cx, cy, r, angle=0.0, face='#d4d4cf', skirt='#26241f', indicator='#d8452b', knurl=48, skirt_w=None):+ """machined aluminium knob on a dark knurled skirt; angle in degrees clockwise from 12 o'clock"""+ sw = skirt_w if skirt_w is not None else r * 0.22+ R = r + sw+ self.drop_shadow(self.circle(cx, cy, R), dist=r * 0.22, soft=r * 0.2, strength=0.55)+ sk = self.circle(cx, cy, R)+ th = np.arctan2(self.YY - cy, self.XX - cx)+ rr = np.hypot(self.XX - cx, self.YY - cy)+ ridges = 0.5 + 0.5 * np.cos(th * knurl)+ side = 0.55 + 0.45 * np.clip(-(np.cos(th) * self.L[0] + np.sin(th) * self.L[1]), -1, 1)+ skc = _c(skirt)[None, None, :] * (0.7 + 0.6 * side * (0.6 + 0.4 * ridges))[..., None]+ self.img = self.img * (1 - sk[..., None]) + np.clip(skc, 0, 1) * sk[..., None]+ fm = self.circle(cx, cy, r)+ lathe = np.interp(rr, np.arange(0, R + 4, 0.5), fbm1d(int((R + 4) * 2), 2.5, 4, self._seed()))+ sheen = 0.5 + 0.5 * np.cos(2 * (th - np.arctan2(self.L[1], self.L[0])))+ c = _c(face)[None, None, :] * (0.78 + 0.06 * lathe + 0.2 * sheen + 0.02 * (self.fine - 0.5))[..., None]+ chamfer = self.ring(cx, cy, r - 2.5, 5)+ lit = np.clip(-((self.XX - cx) * self.L[0] + (self.YY - cy) * self.L[1]) / (r * 1.1) + 0.5, 0, 1)+ c = c * (1 - chamfer[..., None]) + (c * (0.55 + 0.9 * lit[..., None])) * chamfer[..., None]+ self.img = self.img * (1 - fm[..., None]) + np.clip(c, 0, 1) * fm[..., None]+ a = np.deg2rad(angle)+ p0 = (cx + np.sin(a) * r * 0.25, cy - np.cos(a) * r * 0.25); p1 = (cx + np.sin(a) * r * 0.86, cy - np.cos(a) * r * 0.86)+ ind = self.line_mask([p0, p1], max(3, r * 0.09))+ self.paint(ind * fm, indicator)+ self.paint(self.circle(cx, cy, r * 0.09) * 0.5, '#8a8984')++ def button(self, x0, y0, x1, y1, colour='#efe9dc', pressed=False, label=None, label_colour='#2b2a27', size=18):+ """piano-key push button; a pressed key sits lower and darker"""+ m = self.rrect(x0, y0, x1, y1, 5)+ h = 3 if pressed else 9+ self.surface(m, 'plastic', colour, height=h, soft=3, shadow=0.35 if not pressed else 0.15, shadow_dist=h * 0.8)+ if pressed:+ self.paint(m, '#000000', 0.08)+ top = self.rrect(x0 + 3, y0 + 3, x1 - 3, y0 + (y1 - y0) * 0.35, 3)+ self.paint(top, '#ffffff', 0.08 if pressed else 0.16)+ if label:+ self.text(label, (x0 + x1) / 2, y0 + (y1 - y0) * 0.64, size, label_colour, 'sans_bold', spacing=1.5)++ def toggle(self, x, y, up=True, length=64, colour='#dcdcd8'):+ """bat-handle toggle switch: a chrome hex nut and a tapered lever"""+ nut = self.poly([(x + np.cos(a) * 26, y + np.sin(a) * 26) for a in np.linspace(0, 2 * np.pi, 6, endpoint=False) + np.pi / 6])+ self.surface(nut, 'brushed', '#c9c9c4', height=6, soft=2, shadow=0.4)+ self.surface(self.circle(x, y, 13), 'brushed', '#b8b8b2', height=5, soft=2)+ d = -1 if up else 1+ tip = (x + 6, y + d * length)+ lever = self.poly([(x - 7, y), (x + 7, y), (tip[0] + 5, tip[1]), (tip[0] - 5, tip[1])])+ self.drop_shadow(lever, dist=10, soft=5, strength=0.45)+ u = np.clip((self.XX - (x - 7 + (tip[0] - x) * np.clip((self.YY - y) / (d * length), 0, 1))) / 14, 0, 1)+ cyl = 0.55 + 0.6 * np.exp(-((u - 0.3) / 0.18) ** 2) + 0.1 * u+ self.img = self.img * (1 - lever[..., None]) + np.clip(_c(colour) * cyl[..., None], 0, 1) * lever[..., None]+ ball = self.circle(tip[0], tip[1], 8.5)+ self.surface(ball, 'brushed', colour, height=7, soft=4)++ def lamp(self, x, y, r, colour='#ffb347', on=True, bezel='#c9c9c4'):+ """jewel pilot lamp in a chrome bezel, glowing when on"""+ self.surface(self.circle(x, y, r + r * 0.45), 'brushed', bezel, height=5, soft=2, shadow=0.35)+ lens = self.circle(x, y, r)+ rr = np.hypot(self.XX - x, self.YY - y) / r+ facets = 0.5 + 0.5 * np.cos(np.arctan2(self.YY - y, self.XX - x) * 8)+ col = _c(colour)+ if on:+ c = col[None, None, :] * (1.15 - 0.5 * rr[..., None] + 0.12 * facets[..., None]) + (1 - col) * np.clip(0.8 - rr, 0, 1)[..., None]+ else:+ c = col[None, None, :] * (0.45 - 0.2 * rr[..., None] + 0.08 * facets[..., None])+ self.img = self.img * (1 - lens[..., None]) + np.clip(c, 0, 1) * lens[..., None]+ self.paint(self.circle(x - r * 0.35, y - r * 0.38, r * 0.22), '#ffffff', 0.7)+ if on:+ self.glow(x, y, r * 2.4, colour, 0.45)++ def magic_eye(self, x, y, r, tuned=0.7):+ """green 'magic eye' tuning tube: glowing fluorescent petals around a dark cap, the shadow wedge+ closes as the station is tuned in"""+ self.surface(self.circle(x, y, r * 1.35), 'brushed', '#c9c9c4', height=5, soft=2, shadow=0.35)+ win = self.circle(x, y, r)+ self.paint(win, '#0b1a10')+ th = np.arctan2(self.XX - x, -(self.YY - y)) # 0 at 12 o'clock, clockwise+ rr = np.hypot(self.XX - x, self.YY - y) / r+ gap = np.deg2rad(8 + 70 * (1 - tuned))+ shadow_wedge = (np.abs(th) < gap)+ petals = (rr > 0.28) * (rr < 0.95) * (~shadow_wedge)+ fl = np.clip(1.1 - rr * 0.7, 0, 1) * (0.85 + 0.15 * np.cos(th * 24))+ self.paint(win * petals * fl, '#6cff8a', 0.95)+ self.glow(x, y, r * 1.2, '#57e07a', 0.25)+ self.paint(self.circle(x, y, r * 0.3), '#1c1f1c')+ self.paint(self.circle(x - r * 0.3, y - r * 0.4, r * 0.18) * win, '#ffffff', 0.25)++ def meter(self, x0, y0, x1, y1, value=0.6, face='#f2e6c9', label='VU'):+ """moving-coil meter behind glass: printed arc scale, red zone, black needle"""+ m = self.rrect(x0, y0, x1, y1, 8)+ self.recess(m, 'plastic', face, depth=8)+ cx, cy = (x0 + x1) / 2, y1 - (y1 - y0) * 0.12+ R = (y1 - y0) * 0.72+ self.scale_arc(cx, cy, R * 0.86, R * 0.96, -50, 50, 21, 5, '#2b2a27', width=1.6)+ red = self.ring(cx, cy, R * 0.99, 5) * (np.arctan2(self.XX - cx, -(self.YY - cy)) > np.deg2rad(22))+ self.paint(red * m, '#c8332a')+ self.text(label, cx, cy - R * 0.45, (y1 - y0) * 0.14, '#2b2a27', 'sans_bold')+ a = np.deg2rad(-50 + 100 * value)+ self.paint(self.line_mask([(cx, cy), (cx + np.sin(a) * R * 0.98, cy - np.cos(a) * R * 0.98)], 2.4) * m, '#161514')+ self.glass(m)++ def glass(self, mask, streak=0.12):+ """a sheet of glass over a window: diagonal reflection streaks and a faint top shadow"""+ d = (self.XX * 0.55 + self.YY) / 60+ refl = np.clip(np.sin(d * 0.8) - 0.55, 0, 1) * 2.2 + np.clip(np.sin(d * 0.8 + 1.4) - 0.9, 0, 1) * 4+ self.img = self.img + (mask * refl * streak)[..., None] * np.array([1, 1, 1], np.float32)+ self.img = np.clip(self.img, 0, 1)++ def screw(self, x, y, r=9, slot=None):+ self.surface(self.circle(x, y, r), 'brushed', '#bdbdb7', height=4, soft=r * 0.5, shadow=0.35, shadow_dist=3)+ a = slot if slot is not None else self.rng.uniform(0, np.pi)+ sl = self.line_mask([(x - np.cos(a) * r * 0.8, y - np.sin(a) * r * 0.8), (x + np.cos(a) * r * 0.8, y + np.sin(a) * r * 0.8)], max(1.6, r * 0.22))+ self.paint(sl * self.circle(x, y, r), '#4d4b46', 0.85)++ def grille(self, mask, pitch=22, r=6, colour='#34322e', stagger=True):+ """perforated metal: a grid of drilled holes (each with a dark hole and a light lower lip)"""+ sl = self._box(mask)+ if sl is None: return+ X, Y = self.XX[sl], self.YY[sl]+ row = np.round(Y / (pitch * (0.866 if stagger else 1)))+ yc = row * pitch * (0.866 if stagger else 1)+ off = (row % 2) * pitch / 2 if stagger else 0+ xc = np.round((X - off) / pitch) * pitch + off+ d = np.hypot(X - xc, Y - yc)+ hole = np.clip(r - d + 0.5, 0, 1) * mask[sl]+ lip = np.clip(r - np.hypot(X - xc + 1.2, Y - yc + 1.6) + 0.5, 0, 1)+ m = self.img[sl]+ m = m * (1 - hole[..., None] * (1 - _c(colour)) * 0.95)+ m = m + (np.clip(hole - lip, 0, 1) * 0.35)[..., None]+ self.img[sl] = np.clip(m, 0, 1)++ def badge(self, s, x, y, size, font='script', colour='#d9d6cc', anchor='mm'):+ """chrome script badge: raised polished letters with a bevel and a small shadow"""+ m = text_mask(self.H, self.W, s, load_font(font, size), (x, y), anchor)+ sl = self._box(m, 12)+ if sl is None: return+ self.drop_shadow(m, dist=4, soft=3, strength=0.5)+ mm = m[sl]+ rel = self._relief(mm, 5, 1.6)+ grad = 0.75 + 0.35 * np.cos((self.YY[sl] - y) / size * 5.5)+ c = _c(colour)[None, None, :] * (grad * np.clip(rel, 0.4, 1.9))[..., None]+ self.img[sl] = self.img[sl] * (1 - mm[..., None]) + np.clip(c, 0, 1) * mm[..., None]++ # ------------------------------------------------------------ output+ def background(self, colour, kind='painted', **kw):+ sl = (slice(0, self.H), slice(0, self.W))+ self.img = self.material(kind, colour, sl, **kw)++ def composite(self, vignette=0.14):+ r = np.hypot((self.XX - self.W / 2) / self.W, (self.YY - self.H / 2) / self.H)+ img = self.img * (1 - vignette * r ** 2 * 2.2)[..., 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(); 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/stitch.py b/lib/stitch.pynew file mode 100644index 0000000..10a6e0e--- /dev/null+++ b/lib/stitch.py@@ -0,0 +1,370 @@+"""stitch — hand embroidery on Aida cloth: cross-stitch, back-stitch, satin stitch, French knots (numpy + Pillow only).++Model:+ cloth : Aida is woven in square blocks with a hole at every block corner. Stitches can only go+ through the holes, so the picture lives on a grid of cells (`cell` px each).+ thread : stranded cotton is a round, slightly flattened cord of twisted plies. Every thread is lit as a+ cylinder (bright on the side facing the light, darker at its flanks), shows diagonal twist+ stripes along its length, and casts a small shadow onto the cloth.+ stitches:+ cross one X per cell: the bottom leg '/', then the top leg '\\' laid over it (a few hand-made+ variants, so no two neighbouring X's are identical);+ back outlines: short straight stitches from hole to hole (paths snap to the hole grid);+ satin letters and small solid shapes: parallel floats laid side by side across the shape, with a+ sheen band, raised padding and slightly uneven float ends;+ knot French knots: tiny wrapped beads (flower centres, eyes, apples).+ Plus `chart()` for classic ASCII charts, `letters()` for a 5x7 cross-stitch alphabet and `label()` for+ a woven label sewn on with running stitch.++ from stitch import Stitch+ s = Stitch(1920, 1080, cell=12, seed=1)+ s.cross(s.cells(s.circle(960, 540, 120)), '#c8423a') # a filled disc in cross-stitch+ s.back([(800, 700), (1120, 700)], '#2e3f66') # a back-stitched line+ s.satin(s.text_mask('love', 960, 300, 90, 'script'), '#e0654a', angle=0.9)+ s.letters('HOME', 60, 10, '#2e3f66', scale=2) # cross-stitch alphabet on the grid+ s.knot(900, 520, '#f2c14e')+ s.save('out.png')+"""+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, shift, load_font, text_mask++FONT5x7 = {+ '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': [' ### ', '# #', '# #', ' ####', ' #', ' # ', ' ## '],+ '.': [' '] * 5 + [' ## ', ' ## '], '-': [' '] * 3 + [' ### '] + [' '] * 3, ' ': [' '] * 7,+ '&': [' ## ', '# # ', '# # ', ' # ', '# # #', '# # ', ' ## #'],+}+++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)+++class Stitch:+ def __init__(self, W=1920, H=1080, cell=12, seed=0, cloth='#efe7d4', light=(-0.5, -0.62, 0.6)):+ self.W, self.H, self.cell = W, H, cell+ self.gw, self.gh = W // cell, H // cell+ 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 = self._aida(_c(cloth))+ self.stages = []+ self._sprites = [self._x_sprite() for _ in range(6)]++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ cloth+ def _aida(self, col):+ c = self.cell+ u, v = (self.XX % c) / c, (self.YY % c) / c+ block = (np.sin(np.pi * u) * np.sin(np.pi * v)) ** 0.35 # each woven block is slightly domed+ weave = 0.5 + 0.5 * np.cos(2 * np.pi * 3 * u) * np.cos(2 * np.pi * 3 * v) # 3 x 3 threads interlaced per block+ slub = noise2d(self.H, self.W, 1.6, 2, self._seed())+ img = np.ones((self.H, self.W, 3), np.float32) * col+ img *= (0.91 + 0.065 * block + 0.03 * weave + 0.03 * slub)[..., None]+ du, dv = np.minimum(u, 1 - u) * c, np.minimum(v, 1 - v) * c+ hole = np.exp(-(du ** 2 + dv ** 2) / (2 * (c * 0.085) ** 2)) # holes at the block corners+ img *= (1 - 0.34 * hole)[..., None]+ img *= (0.98 + 0.04 * noise2d(self.H, self.W, 300, 3, self._seed()))[..., None]+ return img++ # ------------------------------------------------------------ thread lighting+ def _shade(self, across, pdir, along, twist=1.0, pitch=None):+ """lighting of a round thread. across: -1..1 across the thread; pdir: (px, py) unit vector across it"""+ pitch = pitch or self.cell * 0.32+ nz = np.sqrt(np.clip(1 - across ** 2, 0, 1))+ nx, ny = pdir[0] * across, pdir[1] * across+ diff = np.clip(nx * self.L[0] + ny * self.L[1] + nz * self.L[2], 0, 1)+ stripes = np.sin(2 * np.pi * (along + across * pitch * 0.8) / pitch) # twisted plies+ spec = np.clip(nz, 0, 1) ** 10 * 0.18+ return 0.42 + 0.62 * diff + 0.07 * twist * stripes * nz, spec++ def _paint(self, a, shade, spec, colour, shadow=0.38, off=(1.2, 1.6)):+ col = _c(colour)+ sh = blur(shift(a, off[0], off[1]), 1.1)+ self.img *= (1 - shadow * sh * (1 - a))[..., None]+ lit = col[None, None, :] * np.clip(shade, 0, 2)[..., None]+ lit = lit + (1 - col) * np.clip(shade - 1, 0, 1)[..., None] * 0.35 + spec[..., None]+ self.img = self.img * (1 - a[..., None]) + np.clip(lit, 0, 1) * a[..., None]++ def _x_sprite(self):+ """one hand-made X (supersampled), returns coverage and (shade, spec) in a cell"""+ c, SS = self.cell, 4+ n = c * SS+ yy, xx = (np.mgrid[0:n, 0:n].astype(np.float32) + 0.5) / SS+ legs = []+ for (ax, ay, bx, by) in [(0, c, c, 0), (0, 0, c, c)]: # bottom '/', then top '\'+ j = self.rng.normal(0, c * 0.03, 4)+ ins = c * 0.07+ ax_, ay_ = ax + (ins if ax == 0 else -ins) + j[0], ay + (ins if ay == 0 else -ins) + j[1]+ bx_, by_ = bx + (ins if bx == 0 else -ins) + j[2], by + (ins if by == 0 else -ins) + j[3]+ d = np.array([bx_ - ax_, by_ - ay_], np.float32); Lg = float(np.linalg.norm(d)); u = d / Lg+ p = np.array([-u[1], u[0]])+ w = c * 0.4 * self.rng.uniform(0.93, 1.07)+ along = (xx - ax_) * u[0] + (yy - ay_) * u[1]+ perp = (xx - ax_) * p[0] + (yy - ay_) * p[1]+ taper = np.clip(np.minimum(along, Lg - along) / (w * 0.45) + 0.35, 0, 1) # legs narrow into the holes+ half = w / 2 * taper+ a = np.clip((half - np.abs(perp)) * SS / 1.5, 0, 1) * (along > -0.3) * (along < Lg + 0.3)+ across = np.clip(perp / (half + 1e-3), -1, 1)+ sh, sp = self._shade(across, p, along + self.rng.uniform(0, 5))+ legs.append((a, sh, sp, across))+ (a1, s1, p1, _), (a2, s2, p2, x2) = legs+ A = np.maximum(a1, a2)+ S = np.where(a2 > 0.5, s2, s1)+ edge = (a2 > 0.02) & (a2 < 0.7)+ S = np.where(edge, S * 0.8, S) # the top leg shades the one below+ P = np.where(a2 > 0.5, p2, p1)+ ds = lambda z: z.reshape(c, SS, c, SS).mean((1, 3))+ return ds(A), ds(S), ds(P)++ # ------------------------------------------------------------ grid helpers and masks+ def cells(self, mask, thresh=0.5):+ """pixel mask -> bool cell grid (gh, gw): a cell is stitched when enough of it is covered"""+ c = self.cell+ m = mask[:self.gh * c, :self.gw * c]+ return m.reshape(self.gh, c, self.gw, c).mean((1, 3)) > thresh++ def at(self, gx, gy):+ """pixel centre of cell (gx, gy)"""+ return (gx + 0.5) * self.cell, (gy + 0.5) * self.cell++ def circle(self, cx, cy, r):+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)++ def poly(self, pts):+ return polygon_mask(self.H, self.W, pts, ss=2)++ def rect(self, x0, y0, x1, y1):+ return ((self.XX >= x0) & (self.XX < x1) & (self.YY >= y0) & (self.YY < y1)).astype(np.float32)++ def text_mask(self, s, x, y, size, font='script', anchor='mm', spacing=0.0, rot=0.0):+ return text_mask(self.H, self.W, s, load_font(font, size), (x, y), anchor, spacing, rot)++ # ------------------------------------------------------------ stitches+ def cross(self, cells, colour, shade_var=0.05):+ """cross-stitch every True cell of a (gh, gw) bool grid (use cells(mask) to get one from a pixel mask)"""+ cells = np.asarray(cells, bool)+ if not cells.any(): return+ c = self.cell+ pick = self.rng.integers(0, len(self._sprites), cells.shape)+ a = np.zeros((self.gh * c, self.gw * c), np.float32); s = a.copy(); p = a.copy()+ for k, (A, S, P) in enumerate(self._sprites):+ sel = (cells & (pick == k)).astype(np.float32)+ if not sel.any(): continue+ a += np.kron(sel, A); s += np.kron(sel, S); p += np.kron(sel, P)+ var = np.kron(1 + self.rng.normal(0, shade_var, cells.shape).astype(np.float32), np.ones((c, c), np.float32))+ full = lambda z, fill=0.0: np.pad(z, ((0, self.H - z.shape[0]), (0, self.W - z.shape[1])), constant_values=fill)+ self._paint(full(a), full(s * var, 1.0), full(p), colour)++ def half(self, cells, colour, shade_var=0.05):+ """half stitches (only the '/' leg): lighter, used for sky, shading and soft backgrounds"""+ cells = np.asarray(cells, bool)+ if not cells.any(): return+ c, SS = self.cell, 4+ n = c * SS+ yy, xx = (np.mgrid[0:n, 0:n].astype(np.float32) + 0.5) / SS+ ins = c * 0.07+ ax, ay, bx, by = ins, c - ins, c - ins, ins+ d = np.array([bx - ax, by - ay]); Lg = float(np.linalg.norm(d)); u = d / Lg; pdir = np.array([-u[1], u[0]])+ w = c * 0.4+ along = (xx - ax) * u[0] + (yy - ay) * u[1]; perp = (xx - ax) * pdir[0] + (yy - ay) * pdir[1]+ half = w / 2 * np.clip(np.minimum(along, Lg - along) / (w * 0.45) + 0.35, 0, 1)+ A = np.clip((half - np.abs(perp)) * SS / 1.5, 0, 1) * (along > -0.3) * (along < Lg + 0.3)+ S, P = self._shade(np.clip(perp / (half + 1e-3), -1, 1), pdir, along)+ ds = lambda z: z.reshape(c, SS, c, SS).mean((1, 3))+ A, S, P = ds(A), ds(S), ds(P)+ sel = cells.astype(np.float32)+ var = np.kron(1 + self.rng.normal(0, shade_var, cells.shape).astype(np.float32), np.ones((c, c), np.float32))+ full = lambda z, fill=0.0: np.pad(z, ((0, self.H - z.shape[0]), (0, self.W - z.shape[1])), constant_values=fill)+ self._paint(full(np.kron(sel, A)), full(np.kron(sel, S) * var, 1.0), full(np.kron(sel, P)), colour)++ def _segments(self, segs, width, colour, shadow=0.38):+ """render straight thread segments [(p0, p1), ...] in one pass"""+ a = np.zeros((self.H, self.W), np.float32); S = np.ones((self.H, self.W), np.float32); P = np.zeros((self.H, self.W), np.float32)+ for (p0, p1) in segs:+ p0 = np.asarray(p0, np.float32); p1 = np.asarray(p1, np.float32)+ d = p1 - p0; Lg = float(np.linalg.norm(d))+ if Lg < 0.5: continue+ u = d / Lg; pd = np.array([-u[1], u[0]])+ m = width + 3+ x0, x1 = int(max(0, min(p0[0], p1[0]) - m)), int(min(self.W, max(p0[0], p1[0]) + m + 1))+ y0, y1 = int(max(0, min(p0[1], p1[1]) - m)), int(min(self.H, max(p0[1], p1[1]) + m + 1))+ if x1 <= x0 or y1 <= y0: continue+ X, Y = self.XX[y0:y1, x0:x1], self.YY[y0:y1, x0:x1]+ along = (X - p0[0]) * u[0] + (Y - p0[1]) * u[1]; perp = (X - p0[0]) * pd[0] + (Y - p0[1]) * pd[1]+ half = width / 2 * np.clip(np.minimum(along, Lg - along) / (width * 0.5) + 0.45, 0, 1)+ aa = np.clip((half - np.abs(perp)) / 0.8 + 0.5, 0, 1) * (along > -0.5) * (along < Lg + 0.5)+ sh, sp = self._shade(np.clip(perp / (half + 1e-3), -1, 1), pd, along + self.rng.uniform(0, 6), pitch=width * 0.9)+ sel = aa > a[y0:y1, x0:x1]+ S[y0:y1, x0:x1] = np.where(sel, sh, S[y0:y1, x0:x1]); P[y0:y1, x0:x1] = np.where(sel, sp, P[y0:y1, x0:x1])+ a[y0:y1, x0:x1] = np.maximum(a[y0:y1, x0:x1], aa)+ self._paint(a, S, P, colour, shadow)++ def back(self, pts, colour, width=None, snap=True, step=1.0, smooth=True):+ """back-stitch along a path: the path is snapped to the hole grid and sewn as short straight stitches+ (about `step` cells long), exactly as it would be on Aida"""+ c = self.cell+ width = width or c * 0.3+ P = spline(pts, 12) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); cum = np.concatenate([[0], np.cumsum(seg)])+ n = max(2, int(cum[-1] / (c * step)) + 1)+ t = np.linspace(0, cum[-1], n)+ Q = np.stack([np.interp(t, cum, P[:, 0]), np.interp(t, cum, P[:, 1])], 1)+ if snap:+ Q = np.round(Q / c) * c+ keep = [0] + [i for i in range(1, len(Q)) if np.any(Q[i] != Q[i - 1])]+ Q = Q[keep]+ segs = [(Q[i], Q[i + 1]) for i in range(len(Q) - 1)]+ self._segments(segs, width, colour)++ def running(self, pts, colour, width=None, dash=1.0, gap=1.0, smooth=True):+ """running stitch (dashed line): quilting lines, label borders, wind"""+ c = self.cell+ width = width or c * 0.28+ P = spline(pts, 12) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); cum = np.concatenate([[0], np.cumsum(seg)])+ segs, t = [], 0.0+ while t < cum[-1]:+ t1 = min(cum[-1], t + dash * c)+ segs.append(((np.interp(t, cum, P[:, 0]), np.interp(t, cum, P[:, 1])), (np.interp(t1, cum, P[:, 0]), np.interp(t1, cum, P[:, 1]))))+ t = t1 + gap * c+ self._segments(segs, width, colour, shadow=0.3)++ def satin(self, mask, colour, angle=0.8, period=None, pad=1.0):+ """satin stitch: parallel floats laid side by side across the shape (angle in radians), raised and glossy"""+ period = period or self.cell * 0.3+ m0 = np.clip(mask, 0, 1)+ if m0.max() <= 0: return+ ca, sa = np.cos(angle), np.sin(angle)+ q = -self.XX * sa + self.YY * ca # across the floats+ along = self.XX * ca + self.YY * sa+ idx = np.floor(q / period)+ f = q / period - idx+ jit = fbm1d(4096, 3, 2, self._seed())[(idx.astype(np.int64) % 4096)]+ m = smoothstep(0.4, 0.6, blur(m0, 0.7) + jit * 0.16) # every float ends a little differently+ across = (f - 0.5) * 2+ sh, sp = self._shade(across, (-sa, ca), along, twist=0.6, pitch=period * 3)+ dome = blur(m0, self.cell * 0.4) # padded satin: lit on the light side+ gy, gx = np.gradient(dome)+ tilt = np.clip(-(gx * self.L[0] + gy * self.L[1]) * 6, -0.25, 0.25) * pad+ sheen = 0.14 * np.exp(-((np.cos(angle - np.arctan2(self.L[1], self.L[0])) ** 2) * 2))+ self._paint(m, sh * (1 + tilt) + sheen, sp * 1.5, colour, shadow=0.45, off=(1.6, 2.2))++ def satin_text(self, s, x, y, size, colour, font='script', angle=0.9, anchor='mm', spacing=0.0, rot=0.0):+ self.satin(self.text_mask(s, x, y, size, font, anchor, spacing, rot), colour, angle)++ def knot(self, x, y, colour, r=None):+ """French knot: a small bead of wrapped thread"""+ r = r or self.cell * 0.42+ m = int(r + 4)+ x0, x1, y0, y1 = int(max(0, x - m)), int(min(self.W, x + m + 1)), int(max(0, y - m)), int(min(self.H, y + m + 1))+ X, Y = self.XX[y0:y1, x0:x1] - x, self.YY[y0:y1, x0:x1] - y+ d = np.hypot(X, Y) / r+ a = np.zeros((self.H, self.W), np.float32); S = np.ones_like(a); P = np.zeros_like(a)+ a[y0:y1, x0:x1] = np.clip((1 - d) * r / 0.8 + 0.5, 0, 1)+ nz = np.sqrt(np.clip(1 - d ** 2, 0, 1)); nx, ny = X / r, Y / r+ diff = np.clip(nx * self.L[0] + ny * self.L[1] + nz * self.L[2], 0, 1)+ wrap = np.sin(np.arctan2(Y, X) * 3 + d * 7) # thread wrapped round and round+ S[y0:y1, x0:x1] = 0.45 + 0.65 * diff + 0.1 * wrap * nz+ P[y0:y1, x0:x1] = nz ** 12 * 0.2+ self._paint(a, S, P, colour, shadow=0.45)++ # ------------------------------------------------------------ charts and lettering+ def chart(self, rows, gx, gy, palette, half_keys=()):+ """classic chart: rows of characters placed with the top-left at cell (gx, gy); palette maps char -> colour.+ Characters listed in half_keys are sewn as half stitches."""+ by_key = {}+ for r, row in enumerate(rows):+ for q, ch in enumerate(row):+ if ch in palette:+ by_key.setdefault(ch, []).append((gy + r, gx + q))+ for ch, lst in by_key.items():+ g = np.zeros((self.gh, self.gw), bool)+ for (r, q) in lst:+ if 0 <= r < self.gh and 0 <= q < self.gw: g[r, q] = True+ (self.half if ch in half_keys else self.cross)(g, palette[ch])++ def letters_grid(self, s, gx, gy, scale=1, spacing=1):+ g = np.zeros((self.gh, self.gw), bool)+ x = gx+ for ch in s.upper():+ glyph = FONT5x7.get(ch, FONT5x7[' '])+ for r, row in enumerate(glyph):+ for q, b in enumerate(row):+ if b == '#':+ for dy in range(scale):+ for dx in range(scale):+ yy, xx = gy + r * scale + dy, x + q * scale + dx+ if 0 <= yy < self.gh and 0 <= xx < self.gw: g[yy, xx] = True+ x += (5 + spacing) * scale+ return g++ def letters(self, s, gx, gy, colour, scale=1, spacing=1):+ """cross-stitched capitals from the 5x7 sampler alphabet, top-left at cell (gx, gy)"""+ self.cross(self.letters_grid(s, gx, gy, scale, spacing), colour)++ @staticmethod+ def letters_width(s, scale=1, spacing=1):+ return len(s) * (5 + spacing) * scale - spacing * scale++ def label(self, x0, y0, x1, y1, text, colour='#fbf7ee', ink='#3d3a33', thread='#c8423a', size=30, font='typewriter'):+ """a woven label sewn on with running stitch"""+ lab = np.zeros((self.H, self.W), np.float32)+ im = Image.new('L', (self.W * 2, self.H * 2), 0)+ ImageDraw.Draw(im).rounded_rectangle((x0 * 2, y0 * 2, x1 * 2, y1 * 2), 6, fill=255)+ lab = np.asarray(im.resize((self.W, self.H), Image.BILINEAR), np.float32) / 255+ sh = blur(shift(lab, 3, 4), 4)+ self.img *= (1 - 0.4 * sh * (1 - lab))[..., None]+ twill = 0.96 + 0.04 * (((self.XX + self.YY) // 2) % 2)+ fold = 1 - 0.1 * (1 - smoothstep(0, 7, np.minimum.reduce([self.XX - x0, x1 - self.XX, self.YY - y0, y1 - self.YY])))+ face = _c(colour)[None, None, :] * (twill * fold)[..., None]+ self.img = self.img * (1 - lab[..., None]) + face * lab[..., None]+ t = self.text_mask(text, (x0 + x1) / 2, (y0 + y1) / 2, size, font, 'mm', spacing=size * 0.12)+ t = t * (0.82 + 0.18 * (((self.XX + self.YY) // 2) % 2)) # woven, not printed+ self.img = self.img * (1 - t[..., None]) + _c(ink) * t[..., None]+ ins = 9+ self.running([(x0 + ins, y0 + ins), (x1 - ins, y0 + ins), (x1 - ins, y1 - ins), (x0 + ins, y1 - ins), (x0 + ins, y0 + ins)],+ thread, width=self.cell * 0.24, dash=0.8, gap=0.55, smooth=False)++ # ------------------------------------------------------------ output+ def composite(self, vignette=0.12):+ r = np.hypot((self.XX - self.W / 2) / self.W, (self.YY - self.H / 2) / self.H)+ img = self.img * (1 - vignette * r ** 2 * 2.2)[..., 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(); 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 img