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 fifteen styles (58 total): blueprint, crayon, CRT terminal, thermal camera, Delft tiles, cave painting, 1-bit paint program, Greek black-figure, graphite sketch, X-ray, rubber-hose cartoon, linocut, VHS home video, flat vector (redone), storybook character animation
cloveric339a382781b9
diff --git a/README.md b/README.mdindex ad3e4ac..d74133b 100644--- a/README.md+++ b/README.md@@ -1,37 +1,51 @@# Claude Drawing · Claude 绘图-**Claude paints with code — no image model.** Forty-three styles, from ink wash and impasto oil to clay, cyanotype, stained glass, an Egyptian tomb painting, a Roman mosaic, a cyberpunk street, a ray-traced ball pit, low-poly 3D, an ASCII line printer and a synthwave sunset.-**不用生图模型,Claude 用代码一笔一笔作画。** 四十三种画风,从水墨、油画到黏土、蓝晒、彩色玻璃花窗、古埃及墓室壁画、罗马马赛克、赛博朋克、光线追踪的小球海、低多边形 3D、ASCII 字符画和 Synthwave 落日。+**Claude paints with code — no image model.** Fifty-eight styles, from ink wash and impasto oil to clay, cyanotype, stained glass, a Roman mosaic, Delft tiles, a cyberpunk street, a ray-traced ball pit, low-poly 3D, a thermal camera, an X-ray, a VHS tape and a synthwave sunset.+**不用生图模型,Claude 用代码一笔一笔作画。** 五十八种画风,从水墨、油画到黏土、蓝晒、彩色玻璃花窗、罗马马赛克、代尔夫特蓝瓷砖、赛博朋克、光线追踪的小球海、低多边形 3D、热成像、X 光片、VHS 录像带和 Synthwave 落日。[English](#english) · [中文](#中文)-<p align="center"><img src="examples/drawing_bawansiqian.gif" width="100%"><br><sub><b>Ink wash · 水墨</b> — every style below is drawn stage by stage like this · 下面每种画风都是这样一步步画出来的</sub></p>--| Watercolour · 水彩 | Paper collage · 剪纸拼贴 | Coloured pencil · 韩国彩铅 | Anime · 日本动漫 |-|---|---|---|---|-|  |  |  |  |-| **Editorial · 编辑风手绘** | **Impasto oil · 油画厚涂** | **Ukiyo-e · 浮世绘木版画** | **Pixel art · 像素风** |-|  |  |  |  |-| **Stop-motion clay · 黏土定格** | **Cyanotype · 蓝晒** | **Cross-stitch · 十字绣** | **Retro panel · 复古仪器面板** |-|  |  |  |  |-| **Sticker collage × receipt · 贴纸拼贴 · 小票** | **Lab notebook × stickers · 实验笔记本 · 贴纸** | **Chalkboard · 黑板板书** | **Cyberpunk · 赛博朋克** |-|  |  |  |  |-| **Hand-drawn cartoon · 卡通手绘** | **Continuous line art · 单线画** | **Soft 3D · 柔光 3D** | **Shape morph · 形变动画** |-|  |  |  |  |-| **Newspaper collage · 报刊拼贴** | **Aurora glass · 弥散玻璃** | **Bauhaus geometric · 包豪斯几何** | **Retro synthwave · 复古 Synthwave** |-|  |  |  |  |--| Isometric 2.5D · 等轴 2.5D | Perler beads · 拼豆 | Petroglyph · 岩画 | Egyptian tomb painting · 古埃及墓室壁画 |-|---|---|---|---|-|  |  |  |  |-| **Roman mosaic · 罗马马赛克** | **Stained glass · 彩色玻璃花窗** | **Illuminated manuscript · 泥金手抄本** | **Leonardo codex · 达·芬奇手稿** |-|  |  |  |  |-| **Silhouette · 剪影** | **Letterpress poster · 凸版印刷海报** | **Soviet constructivism · 苏联构成主义** | **Art Deco · 装饰艺术** |-|  |  |  |  |-| **Golden-age comic · 黄金时代漫画** | **Pop silkscreen · 波普丝网** | **ASCII art (line printer) · ASCII 字符画** | **Low poly · 低多边形** |-|  |  |  |  |-| **Stencil graffiti · 喷漆模板涂鸦** | **Embroidered patches · 刺绣徽章** | | |-|  |  | | |+<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 (the storybook one is a real character animation) · 下面每种画风都是这样一步步画出来的(绘本角色动画是一段真正的角色动画)</sub></p>++| Watercolour · 水彩 | Paper collage · 剪纸拼贴 | Coloured pencil · 韩国彩铅 |+|---|---|---|+|  |  |  |+| **Anime · 日本动漫** | **Editorial · 编辑风手绘** | **Impasto oil · 油画厚涂** |+|  |  |  |+| **Ukiyo-e · 浮世绘木版画** | **Pixel art · 像素风** | **Stop-motion clay · 黏土定格** |+|  |  |  |+| **Cyanotype · 蓝晒** | **Cross-stitch · 十字绣** | **Retro panel · 复古仪器面板** |+|  |  |  |+| **Sticker collage × receipt · 贴纸拼贴 · 小票** | **Lab notebook × stickers · 实验笔记本 · 贴纸** | **Chalkboard · 黑板板书** |+|  |  |  |+| **Cyberpunk · 赛博朋克** | **Hand-drawn cartoon · 卡通手绘** | **Continuous line art · 单线画** |+|  |  |  |+| **Soft 3D · 柔光 3D** | **Shape morph · 形变动画** | **Newspaper collage · 报刊拼贴** |+|  |  |  |+| **Aurora glass · 弥散玻璃** | **Bauhaus geometric · 包豪斯几何** | **Retro synthwave · 复古 Synthwave** |+|  |  |  |+| **Isometric 2.5D · 等轴 2.5D** | **Perler beads · 拼豆** | **Petroglyph · 岩画** |+|  |  |  |+| **Egyptian tomb painting · 古埃及墓室壁画** | **Roman mosaic · 罗马马赛克** | **Stained glass · 彩色玻璃花窗** |+|  |  |  |+| **Illuminated manuscript · 泥金手抄本** | **Leonardo codex · 达·芬奇手稿** | **Silhouette · 剪影** |+|  |  |  |+| **Letterpress poster · 凸版印刷海报** | **Soviet constructivism · 苏联构成主义** | **Art Deco · 装饰艺术** |+|  |  |  |+| **Golden-age comic · 黄金时代漫画** | **Pop silkscreen · 波普丝网** | **ASCII art (line printer) · ASCII 字符画** |+|  |  |  |+| **Low poly · 低多边形** | **Stencil graffiti · 喷漆模板涂鸦** | **Embroidered patches · 刺绣徽章** |+|  |  |  |+| **Blueprint · 蓝图工程图** | **Children's crayon · 儿童蜡笔画** | **Green-screen CRT · 绿屏终端** |+|  |  |  |+| **Thermal camera · 热成像** | **Delft tiles · 代尔夫特蓝瓷砖** | **Cave painting · 洞穴壁画** |+|  |  |  |+| **1-bit paint program · 1-bit 早期画图软件** | **Greek black-figure vase · 古希腊黑绘陶瓶** | **Graphite pencil · 铅笔素描** |+|  |  |  |+| **X-ray · X 光片** | **1930s rubber hose · 1930 年代黑白橡皮管动画** | **Linocut · 黑白麻胶版画** |+|  |  |  |+| **VHS home video · VHS 家庭录像** | **Flat vector · 扁平矢量** | **Storybook animation · 绘本角色动画** |+|  |  |  |### Gallery · 画廊@@ -39,50 +53,66 @@|---|---|| **八万四千法门** · *Many Paths, One Summit*<br><sub>Ink wash · 水墨</sub> | **月印万川** · *One Moon in Ten Thousand Rivers*<br><sub>Ink wash · 水墨</sub> || <img src="examples/bawansiqian.jpg" width="100%"> | <img src="examples/moon_river.jpg" width="100%"> |-| **秋日湖畔** · *Autumn Lake*<br><sub>Watercolour · 水彩</sub> | **热气球小镇** · *Balloon Day*<br><sub>Paper collage · 剪纸拼贴</sub> |-| <img src="examples/watercolor_autumn.jpg" width="100%"> | <img src="examples/papercut_balloons.jpg" width="100%"> |-| **午后甜点** · *Afternoon Dessert*<br><sub>Coloured pencil · 韩国彩铅</sub> | **夏空** · *Summer Sky*<br><sub>Anime · 日本动漫</sub> |-| <img src="examples/colorpencil_dessert.jpg" width="100%"> | <img src="examples/anime_summer.jpg" width="100%"> |-| **灵感生长** · *Growing Ideas*<br><sub>Editorial · 编辑风手绘</sub> | **麦田星空** · *Swirling Sky over the Wheat Field*<br><sub>Impasto oil · 油画厚涂</sub> |-| <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%"> |-| **周末市集** · *Weekend Market*<br><sub>Sticker collage × receipt · 贴纸拼贴 · 小票</sub> | **咖啡萃取实验** · *Coffee Brewing Experiment*<br><sub>Lab notebook × stickers · 实验笔记本 · 贴纸</sub> |-| <img src="examples/sticker_market.jpg" width="100%"> | <img src="examples/notebook_brewing.jpg" width="100%"> |-| **为什么天空是蓝的** · *Why Is the Sky Blue?*<br><sub>Chalkboard · 黑板板书</sub> | **霓虹不夜城** · *Neon District*<br><sub>Cyberpunk · 赛博朋克</sub> |-| <img src="examples/chalk_lesson.jpg" width="100%"> | <img src="examples/cyberpunk_neon_street.jpg" width="100%"> |-| **早安吐司** · *Good Morning, Toast*<br><sub>Hand-drawn cartoon · 卡通手绘</sub> | **岛上的气象站** · *Island Weather Station*<br><sub>Isometric 2.5D · 等轴 2.5D</sub> |-| <img src="examples/cartoon_toaster.jpg" width="100%"> | <img src="examples/isometric_weather_island.jpg" width="100%"> |-| **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> | **浮出** · *Rise*<br><sub>Soft 3D · 柔光 3D</sub> |-| <img src="examples/lineart_paper_plane.jpg" width="100%"> | <img src="examples/soft3d_rise.jpg" width="100%"> |-| **一滴水的旅程** · *A Drop's Round Trip*<br><sub>Shape morph · 形变动画</sub> | **好奇心周刊 · 拆开看看** · *Curiosity Weekly · Take It Apart*<br><sub>Newspaper collage · 报刊拼贴</sub> |-| <img src="examples/morph_water_cycle.jpg" width="100%"> | <img src="examples/newscollage_curiosity.jpg" width="100%"> |-| **晨间计划** · *Morning Plan*<br><sub>Aurora glassmorphism · 弥散玻璃</sub> | **形与色** · *Form & Colour*<br><sub>Bauhaus geometric · 包豪斯几何</sub> |-| <img src="examples/aurora_morning.jpg" width="100%"> | <img src="examples/bauhaus_form_colour.jpg" width="100%"> |-| **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> | **草莓杯垫** · *Strawberry Coaster*<br><sub>Perler beads · 拼豆</sub> |-| <img src="examples/synthwave_coastline.jpg" width="100%"> | <img src="examples/perler_strawberry_coaster.jpg" width="100%"> |-| **迁徙季** · *Migration Season*<br><sub>Petroglyph · 岩画</sub> | **尼罗河丰收** · *Harvest on the Nile*<br><sub>Egyptian tomb painting · 古埃及墓室壁画</sub> |-| <img src="examples/petroglyph_migration.jpg" width="100%"> | <img src="examples/tomb_harvest.jpg" width="100%"> |-| **港口渔获** · *The Day's Catch*<br><sub>Roman mosaic · 罗马马赛克</sub> | **四季之窗** · *Window of the Seasons*<br><sub>Stained glass · 彩色玻璃花窗</sub> |-| <img src="examples/mosaic_harbor.jpg" width="100%"> | <img src="examples/stainedglass_seasons.jpg" width="100%"> |-| **星辰之书** · *Liber Stellarum*<br><sub>Illuminated manuscript · 泥金手抄本</sub> | **扑翼机** · *The Ornithopter*<br><sub>Leonardo codex · 达·芬奇手稿</sub> |-| <img src="examples/illuminated_starchart.jpg" width="100%"> | <img src="examples/codex_ornithopter.jpg" width="100%"> |-| **剪影小像** · *Shades of the Wren Household*<br><sub>Silhouette · 剪影</sub> | **马戏团来了** · *The Circus Is Coming*<br><sub>Letterpress poster · 凸版印刷海报</sub> |-| <img src="examples/silhouette_family.jpg" width="100%"> | <img src="examples/letterpress_circus.jpg" width="100%"> |-| **无线电** · *Radio*<br><sub>Soviet constructivism · 苏联构成主义</sub> | **夜行快车** · *Night Express*<br><sub>Art Deco · 装饰艺术</sub> |-| <img src="examples/constructivism_radio.jpg" width="100%"> | <img src="examples/artdeco_express.jpg" width="100%"> |-| **火箭小队** · *Rocket Squad*<br><sub>Golden-age comic · 黄金时代漫画</sub> | **猫的六种心情** · *Six Moods of a Cat*<br><sub>Pop silkscreen · 波普丝网</sub> |-| <img src="examples/comic_rocket.jpg" width="100%"> | <img src="examples/popart_cat_moods.jpg" width="100%"> |-| **发射记录** · *Liftoff Trace*<br><sub>ASCII art (line printer) · ASCII 字符画(行式打印机)</sub> | **峡谷飞行** · *Canyon Run*<br><sub>Low poly · 低多边形</sub> |-| <img src="examples/lineprinter_launch.jpg" width="100%"> | <img src="examples/lowpoly_canyon.jpg" width="100%"> |-| **放风筝** · *Hold On*<br><sub>Stencil graffiti · 喷漆模板涂鸦</sub> | **三晚露营** · *Three Nights Out*<br><sub>Embroidered patches · 刺绣徽章</sub> |-| <img src="examples/stencil_kite.jpg" width="100%"> | <img src="examples/patch_camping.jpg" width="100%"> |--Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street, a blue-pencil rough under boiling brush ink, an island ray-traced under one soft sun, a single unbroken gold line, candy balls with softbox glints, one outline morphing through six shapes, halftone photos cut out with scissors, frosted glass blurring the real pixels behind it, screen-printed primaries out of register, a slit sun sinking behind a neon grid played off tape, hollow fuse beads on a pegboard melting together under an iron. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 45 s (the soft 3D ray tracer) per 1920×1080 image.+| **秋日湖畔** · *Autumn Lake*<br><sub>Watercolour · 水彩</sub> | **水彩底纹** · *Watercolour Washes*<br><sub>Watercolour · 水彩 — a background for explainer videos · 讲解视频的背景</sub> |+| <img src="examples/watercolor_autumn.jpg" width="100%"> | <img src="examples/watercolor_washes.jpg" width="100%"> |+| **热气球小镇** · *Balloon Day*<br><sub>Paper collage · 剪纸拼贴</sub> | **午后甜点** · *Afternoon Dessert*<br><sub>Coloured pencil · 韩国彩铅</sub> |+| <img src="examples/papercut_balloons.jpg" width="100%"> | <img src="examples/colorpencil_dessert.jpg" width="100%"> |+| **夏空** · *Summer Sky*<br><sub>Anime · 日本动漫</sub> | **灵感生长** · *Growing Ideas*<br><sub>Editorial · 编辑风手绘</sub> |+| <img src="examples/anime_summer.jpg" width="100%"> | <img src="examples/editorial_ideas.jpg" width="100%"> |+| **麦田星空** · *Swirling Sky over the Wheat Field*<br><sub>Impasto oil · 油画厚涂</sub> | **富士曙** · *Fuji at Dawn*<br><sub>Ukiyo-e · 浮世绘</sub> |+| <img src="examples/oil_wheatfield.jpg" width="100%"> | <img src="examples/ukiyoe_fuji.jpg" width="100%"> |+| **雨夜咖啡店** · *Rainy Night Cafe*<br><sub>Pixel art · 像素风</sub> | **灯塔岛** · *Lighthouse Island*<br><sub>Stop-motion clay · 黏土定格</sub> |+| <img src="examples/pixel_rainy_cafe.png" width="100%"> | <img src="examples/clay_lighthouse.jpg" width="100%"> |+| **蓝晒植物** · *Sun-Print Botanicals*<br><sub>Cyanotype · 蓝晒</sub> | **家** · *Home Sampler*<br><sub>Cross-stitch · 十字绣</sub> |+| <img src="examples/cyanotype_botanicals.jpg" width="100%"> | <img src="examples/stitch_sampler.jpg" width="100%"> |+| **Aurora 64 收音机** · *Aurora 64 Radio*<br><sub>Vintage instrument panel · 复古仪器面板</sub> | **周末市集** · *Weekend Market*<br><sub>Sticker collage × receipt · 贴纸拼贴 · 小票</sub> |+| <img src="examples/panel_radio.jpg" width="100%"> | <img src="examples/sticker_market.jpg" width="100%"> |+| **咖啡萃取实验** · *Coffee Brewing Experiment*<br><sub>Lab notebook × stickers · 实验笔记本 · 贴纸</sub> | **为什么天空是蓝的** · *Why Is the Sky Blue?*<br><sub>Chalkboard · 黑板板书</sub> |+| <img src="examples/notebook_brewing.jpg" width="100%"> | <img src="examples/chalk_lesson.jpg" width="100%"> |+| **霓虹不夜城** · *Neon District*<br><sub>Cyberpunk · 赛博朋克</sub> | **早安吐司** · *Good Morning, Toast*<br><sub>Hand-drawn cartoon · 卡通手绘</sub> |+| <img src="examples/cyberpunk_neon_street.jpg" width="100%"> | <img src="examples/cartoon_toaster.jpg" width="100%"> |+| **岛上的气象站** · *Island Weather Station*<br><sub>Isometric 2.5D · 等轴 2.5D</sub> | **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> |+| <img src="examples/isometric_weather_island.jpg" width="100%"> | <img src="examples/lineart_paper_plane.jpg" width="100%"> |+| **浮出** · *Rise*<br><sub>Soft 3D · 柔光 3D</sub> | **一滴水的旅程** · *A Drop's Round Trip*<br><sub>Shape morph · 形变动画</sub> |+| <img src="examples/soft3d_rise.jpg" width="100%"> | <img src="examples/morph_water_cycle.jpg" width="100%"> |+| **好奇心周刊 · 拆开看看** · *Curiosity Weekly · Take It Apart*<br><sub>Newspaper collage · 报刊拼贴</sub> | **晨间计划** · *Morning Plan*<br><sub>Aurora glassmorphism · 弥散玻璃</sub> |+| <img src="examples/newscollage_curiosity.jpg" width="100%"> | <img src="examples/aurora_morning.jpg" width="100%"> |+| **形与色** · *Form & Colour*<br><sub>Bauhaus geometric · 包豪斯几何</sub> | **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> |+| <img src="examples/bauhaus_form_colour.jpg" width="100%"> | <img src="examples/synthwave_coastline.jpg" width="100%"> |+| **草莓杯垫** · *Strawberry Coaster*<br><sub>Perler beads · 拼豆</sub> | **迁徙季** · *Migration Season*<br><sub>Petroglyph · 岩画</sub> |+| <img src="examples/perler_strawberry_coaster.jpg" width="100%"> | <img src="examples/petroglyph_migration.jpg" width="100%"> |+| **尼罗河丰收** · *Harvest on the Nile*<br><sub>Egyptian tomb painting · 古埃及墓室壁画</sub> | **港口渔获** · *The Day's Catch*<br><sub>Roman mosaic · 罗马马赛克</sub> |+| <img src="examples/tomb_harvest.jpg" width="100%"> | <img src="examples/mosaic_harbor.jpg" width="100%"> |+| **四季之窗** · *Window of the Seasons*<br><sub>Stained glass · 彩色玻璃花窗</sub> | **星辰之书** · *Liber Stellarum*<br><sub>Illuminated manuscript · 泥金手抄本</sub> |+| <img src="examples/stainedglass_seasons.jpg" width="100%"> | <img src="examples/illuminated_starchart.jpg" width="100%"> |+| **扑翼机** · *The Ornithopter*<br><sub>Leonardo codex · 达·芬奇手稿</sub> | **剪影小像** · *Shades of the Wren Household*<br><sub>Silhouette · 剪影</sub> |+| <img src="examples/codex_ornithopter.jpg" width="100%"> | <img src="examples/silhouette_family.jpg" width="100%"> |+| **马戏团来了** · *The Circus Is Coming*<br><sub>Letterpress poster · 凸版印刷海报</sub> | **无线电** · *Radio*<br><sub>Soviet constructivism · 苏联构成主义</sub> |+| <img src="examples/letterpress_circus.jpg" width="100%"> | <img src="examples/constructivism_radio.jpg" width="100%"> |+| **夜行快车** · *Night Express*<br><sub>Art Deco · 装饰艺术</sub> | **火箭小队** · *Rocket Squad*<br><sub>Golden-age comic · 黄金时代漫画</sub> |+| <img src="examples/artdeco_express.jpg" width="100%"> | <img src="examples/comic_rocket.jpg" width="100%"> |+| **猫的六种心情** · *Six Moods of a Cat*<br><sub>Pop silkscreen · 波普丝网</sub> | **发射记录** · *Liftoff Trace*<br><sub>ASCII art (line printer) · ASCII 字符画(行式打印机)</sub> |+| <img src="examples/popart_cat_moods.jpg" width="100%"> | <img src="examples/lineprinter_launch.jpg" width="100%"> |+| **峡谷飞行** · *Canyon Run*<br><sub>Low poly · 低多边形</sub> | **放风筝** · *Hold On*<br><sub>Stencil graffiti · 喷漆模板涂鸦</sub> |+| <img src="examples/lowpoly_canyon.jpg" width="100%"> | <img src="examples/stencil_kite.jpg" width="100%"> |+| **三晚露营** · *Three Nights Out*<br><sub>Embroidered patches · 刺绣徽章</sub> | **灯塔剖面** · *Halvard Rock Light*<br><sub>Blueprint · 蓝图工程图</sub> |+| <img src="examples/patch_camping.jpg" width="100%"> | <img src="examples/blueprint_lighthouse.jpg" width="100%"> |+| **我的周末** · *My Weekend*<br><sub>Children's crayon · 儿童蜡笔画</sub> | **今天带伞吗** · *Bring an Umbrella?*<br><sub>Green-screen CRT terminal · 绿屏终端(荧光字符画)</sub> |+| <img src="examples/crayon_picnic.jpg" width="100%"> | <img src="examples/crt_weather.jpg" width="100%"> |+| **厨房里的温度** · *Kitchen Heat Map*<br><sub>Thermal camera · 热成像</sub> | **一阵风** · *The Gust*<br><sub>Delft tiles · 代尔夫特蓝瓷砖</sub> |+| <img src="examples/thermal_kitchen.jpg" width="100%"> | <img src="examples/delft_canal.jpg" width="100%"> |+| **篝火旁的岩洞** · *The Hunt by the Fire*<br><sub>Cave painting · 洞穴壁画</sub> | **窗台花园** · *Windowsill Garden*<br><sub>1-bit paint program · 1-bit 早期画图软件</sub> |+| <img src="examples/cave_hunt.jpg" width="100%"> | <img src="examples/macpaint_garden.jpg" width="100%"> |+| **赛跑与赛车** · *Games on a Vase*<br><sub>Greek black-figure vase · 古希腊黑绘陶瓶</sub> | **老街角的自行车** · *The Bread Run*<br><sub>Graphite pencil · 铅笔素描</sub> |+| <img src="examples/blackfigure_games.jpg" width="100%"> | <img src="examples/graphite_bicycle.jpg" width="100%"> |+| **行李安检** · *Security Check*<br><sub>X-ray · X 光片</sub> | **早晨的闹钟** · *Seven O'Clock*<br><sub>1930s rubber hose · 1930 年代黑白橡皮管动画</sub> |+| <img src="examples/xray_luggage.jpg" width="100%"> | <img src="examples/rubberhose_morning.jpg" width="100%"> |+| **雪夜归途** · *Homeward, First Snow*<br><sub>Linocut · 黑白麻胶版画</sub> | **吹蜡烛** · *Blow Out the Candles*<br><sub>VHS home video · VHS 家庭录像</sub> |+| <img src="examples/linocut_snowy_village.jpg" width="100%"> | <img src="examples/vhs_birthday.jpg" width="100%"> |+| **山间夜营** · *Night Camp*<br><sub>Flat vector · 扁平矢量</sub> | **小橡果的秋天** · *An Acorn's Autumn*<br><sub>Storybook animation · 绘本角色动画</sub> |+| <img src="examples/flatvector_night_camp.jpg" width="100%"> | <img src="examples/storybook_acorn.jpg" width="100%"> |++Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street, a blue-pencil rough under boiling brush ink, an island ray-traced under one soft sun, a single unbroken gold line, candy balls with softbox glints, one outline morphing through six shapes, halftone photos cut out with scissors, frosted glass blurring the real pixels behind it, screen-printed primaries out of register, a slit sun sinking behind a neon grid played off tape, hollow fuse beads on a pegboard melting together under an iron, pits knocked through desert varnish, a red grid showing through flaking plaster, stones laid row by row along an outline, daylight through leaded glass, burnished gold that mirrors the room, left-handed hatching in iron-gall ink, black paper cut with scissors, wood type printed a hair out of register, red and black plates slipping apart, airbrush fades inside knife-cut friskets, Ben-Day dots on yellowed newsprint, one photo key pulled across hand-painted colour, characters struck through a fading ribbon, flat-shaded triangles dithered to 15 bits, spray drifting past cut card, satin stitches catching the light by their angle, ink lines printed white on Prussian blue, wax scribbles skipping the paper's pits, phosphor glowing behind curved glass, heat leaking out of a kitchen, cobalt fired into tin glaze tile by tile, ochre blown onto rock lit by a fire, 1-bit patterns in an old paint program, slip silhouettes incised to the clay, graphite that never quite reaches black, X-rays adding up through a suitcase, grey cels shot on scratched film, gouge marks in a rolled-up block, a birthday smeared onto tape, seven flat colours lifting off each other, an acorn squashing and stretching through a world drawn as it goes. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 45 s (the soft 3D ray tracer) per 1920×1080 image.---@@ -90,7 +120,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 forty-three styles:+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with fifty-eight styles:| Style | Module | What makes it read as the real medium ||---|---|---|@@ -137,6 +167,21 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra| **Low poly (1999 3D)** | `lib/lowpoly.py` · `LowPoly` | an actual little software rasterizer drawing into a 384×216 framebuffer: a pinhole camera, vertices snapped to whole pixels, back-face culling, every triangle of the scene in one painter's-sorted list (the console ordering table) with a depth bias for decals, near-plane clipping, an optional z-buffer; flat shading per face (hemisphere ambient + sun + a per-facet glint, so gold flashes facet by facet); tiny procedural textures sampled nearest-neighbour and interpolated affinely, so strata bend on big polygons near the camera; per-vertex fog that swallows the far clip plane; alpha-cut crossed-quad trees; the era's four blend modes for a propeller disc, blob shadows, sparkles and a lens flare; then 15-bit colour through the 4×4 ordered dither and a ×5 nearest-neighbour blow-up; a stamped bitmap HUD (italic ramp digits with outline and drop shadow, a stepped speed bar, a minimap) || **Stencil graffiti** | `lib/stencil.py` · `Stencil` | a board-marked concrete wall built as albedo plus height and lit by a low sun (sawn-plank bands and wood grain pressed into the cement, broken paste fins along the seams, cone-shaped form-tie holes with rusted rods or mortar plugs, bug holes, rust and rain streaks, a damp tide line with efflorescence, a hairline crack); stencils that are real cut card: every island the cuts isolate is found and held by the shortest bridge, letters get bridged counters, and the bridges show as hairlines of bare wall; a picture in tones is several cards sprayed light to dark, each a few pixels off; the can moves in overlapping sweeps whose gaussian cones add up to a paint film, crisp where the card lay flat, creeping under where it lifted, with a drifting overspray halo; coverage is droplets, so thin film is a scatter of dots, not a blur; paint misses the bottom of pits, lies on the relief with a satin sheen, and runs from heavy lower edges as drips with a neck and a bead; freehand skinny-cap lines that follow the hand's speed; a council roller buff in stepped vertical passes with an old tag ghosting through; snapshots with the card still taped up || **Embroidered patches** | `lib/patch.py` · `Patch` | stitched the way an embroidery machine does it: every shape is cut into parallel rows at its own angle and each row into stitches — short staggered tatami for backgrounds, one long float per row for satin (split above a max length) — so every edge is made of stitch ends; each stitch is a round glossy thread that dives into the cloth at both needle holes and carries an anisotropic (Kajiya–Kay) highlight, so one colour sewn at two angles catches the light differently; padded satin domes into a light-to-dark sheen along each float; merrowed edges are a rolled cord of slanted wraps, die-cut shapes get a hot-cut satin border, both supersampled and faded where stitches crowd into tight corners; a 3/1 right-hand twill denim (warp denser than weft, ~60° wales, ring-dyed slubby warp, worn high points) with a felled seam and double topstitching; one patch still being whip-stitched on, the needle and thread lying on the cloth |+| **Blueprint** | `lib/blueprint.py` · `Blueprint` | the drawing is inked first, on tracing linen, with a few fixed ruling-pen weights and single-stroke lettering-guide capitals (pencil guide lines left on the linen, hatching scraped back behind dimension figures), then contact-printed: ink blocks the arc lamp so the iron salts under every line wash out white while everything else turns Prussian blue; density follows a threshold S-curve, so heavy lines print clean white, hairlines print pale blue and the ground saturates; light creeps under line edges, sharp where the glass pressed the linen flat and softer where contact was poor, with a faint halo; the lamp is stronger mid-frame, the coating carries machine streaks, mottle and wash runs from the drying line, and colour is Beer–Lambert Prussian blue on paper with the fibres showing through; drafting conventions throughout (hatching by material, dimension and extension lines, level datums, cutting planes, detail bubbles, a north point, graphic scales, a zoned border, title and revision blocks); then the sheet's life: folded in six with creases cracking the blue to white, the outside panel faded and handled, an alkaline water stain gone rust-brown inside two tide lines, rusty pin holes, and a site engineer's red wax-pencil revision cloud |+| **Children's crayon** | `lib/crayon.py` · `Crayon` | rough paper whose tooth is equalised so pressure maps straight to coverage; wax only catches on the peaks, and dragging the stick stretches the bare pits into short streaks along each stroke; a worn, faceted tip lays a bundle of uneven sub-lines, so every stroke carries white streaks; later wax catches on earlier wax (build-up) and mixes semi-opaquely (blue over yellow turns green, black outlines survive the colour); a child's hand: outline first, then back-and-forth scribbles patch by patch at arm's reach, each patch at its own angle, V-turns that overshoot the outline but stop short of anything being coloured round; circle scribbles, strokes along rainbow bands, shapes whose ends miss their starts; letters re-drawn over a thinned glyph with a round crayon, each tilted, resized and coloured differently; burnished wax that closes up and shines; paper and wax lit as one height field; real crayons in printed paper sleeves, one snapped, and wax crumbs lying on the sheet |+| **Green-screen CRT terminal** | `lib/crt.py` · `CRTTerminal` | a character terminal, not a picture: 120×36 cells of character memory with dim / normal / bold, reverse video, underline and double-height lines, a 5×7 dot-matrix ROM with descenders plus a graphics set (box drawing, the five scan-line bars for plotting, block eighths). ASCII art comes from a hidden map of materials and tones: interiors pick from a ramp with error diffusion, silhouettes by the edge's direction and height in the cell, and on a screen dense means *bright*, so a storm cloud is sparse and dim with a lit rim. The beam paints ten scan lines per row: dots stretched by half a dot (before reverse video, so dark strokes survive), smeared by the video amplifier, with a spot that swells with current. P1 phosphor saturates to pale mint and leaves afterglow trails behind falling rain; an old status line is burnt in. The raster is barrel-curved and falls off at the edges, with bloom and halation in the glass, a room window reflected in it, and the bezel's shadow. The putty plastic bezel has a chamfer that catches the green spill, a mould seam, a power LED and two knurled thumbwheels |+| **Thermal camera** | `lib/thermal.py` · `Thermal` | never painted in colour: the scene is a temperature field in °C — a room layered warm over cool, every object at its own temperature with its own gradients (a pot hottest at the base, a cat's eye hotter than its nose and ears), polished metal reading the room it reflects through emissivity, rounded bodies cooling toward their outline. Heat then leaks out the way it does: soaking into the wall behind the stove, rising in plumes that widen, cool and break into eddies and wisps, cold air pouring off an open fridge and spreading over the floor in tongues, warm paw prints that fade and spread with age, glazed tiles mirroring the oven. That field is seen by a modelled uncooled camera: lens blur, box sampling onto a 480×270 sensor, temporal noise and column stripes, a centre-cool vignette, detail enhancement, a hand-set tone curve mixed with plateau histogram equalisation, a false-colour palette, and a bilinear upscale that keeps a trace of the pixel grid. The OSD (status bar, spot meters, area box, hottest/coldest markers, a line-profile inset, a non-linear scale bar) reads every number off the same sensor image |+| **Delft tiles** | `lib/delft.py` · `DelftTile` | a tin-glazed tile wall made in workshop order: blank tiles on a grid that is never quite straight, the design pounced through a pricked pattern as charcoal dots, outlines with a fine brush (a bead where it lands, a taper where it lifts, heavier on the downstroke, a slow hand wobble), washes that cannot be blended (brush bands, bristle streaks, a darker rim where the water dried last, overlaps that darken, never quite inside the outline, white kept by painting round it); one transparent pigment, so everything is painted front to back with reserves instead of layers; dull grey-black raw pigment that the kiln turns into cobalt by per-channel Beer–Lambert absorption, with a soft bleed into the glaze and a speckle of grains; every tile painted and fired on its own, so lines step at the joints and each tile has its own white and its own blue; quarter ornaments that only become whole where four single tiles meet; recessed lime-mortar joints; every tile a little cushioned and tilted, so a window reflects as bent, broken panes and the rounded edges catch the light; crazing, iron specks, chips showing the buff body, a crack that stops at the joint |+| **Cave painting (ochre)** | `lib/cave.py` · `CavePainting` | the opposite of the petroglyph: pigment laid *on* pale limestone and seen only by a fire. The wall is a height field (broad swells, ridged folds, faint solution scallops, pits that hold clay, calcite crust on the convex parts, wet flowstone drapery) under a cream-to-buff albedo; every pigment is a coverage field multiplied into it, so the rock's mottling shows through even a dense coat. How it was applied decides the look: charcoal searching lines on a wandering contour, a dry stick that catches only the rock's tooth, blown paint with a soft edge, halo and droplet speckle, denser at the rim and on the side of a bulge turned away from the fire, pale bellies left bare; hand stencils sprayed in several puffs aimed at the fingertips. Lit only by a campfire and a fat lamp on the floor: half-Lambert point lights with inverse-square falloff and shadows marched per pixel, so raking light makes every bulge the animals were painted on read as volume; flame tongues, sparks, bloom, a smoke plume, soot on the ceiling, calcite veils, flaked paint and a cave bear's claw marks |+| **1-bit paint program** | `lib/macpaint.py` · `MacPaint` | the whole screen of a 1984-style black-and-white paint program, not "pixel art": a 640×360 framebuffer with exactly two values, blown up ×3 with no smoothing; every tone is one of 38 eight-by-eight patterns anchored to the document origin (two fills of one pattern butt seamlessly and never bend with the shape), and gradients are bands of patterns; the tools behave like the originals — square-pen Bresenham lines with stair-step jaggies, shapes filled with a pattern and framed inside their outline at the current line width, a 4-connected paint bucket, a spray can that ORs random pixels in a disc, brush shapes, select-and-drag copies with Flip Horizontal, XOR; a hand-made bold bitmap system face (9-px capitals, 2-px stems), TrueType rendered with antialiasing off, bold / italic / underline / outline / shadow done as bitmap operations; the interface is redrawn for every snapshot: a menu bar with invented menus and rounded black screen corners, a 20-tool palette with the active tool inverted, a line-width box, a pattern palette with the current fill, a striped title bar with a close box, scroll bars with a 50 % track, a pull-down menu that shows each type style in its own style, a fat-bits zoom window, marching ants, cursors with white halos |+| **Greek black-figure vase** | `lib/blackfigure.py` · `BlackFigure` | the pot is thrown first — a profile r(y) with two round handles — and everything is painted on its unrolled surface, so the same painting wraps onto the curved pot and lies flat in the rollout without ever disagreeing. Work goes in the workshop's order: bands painted while the wheel spins (dead level, a small lap where the brush lifted), silhouettes in slip that is still a dull brown, details incised through it to the orange clay, matte added red and white laid on last; every figure part is z-ordered, so a nearer black horse hides the farther horse's lines and colour and cuts its own outline — four horses overlap and still read as four. Firing turns the slip into blue-black gloss that fires reddish where thin. Then 2,500 years: flaking white leaving a dull ghost, calcareous crust and root marks, chips showing the fabric, a toned plaster fill with glued cracks, a misfired patch. The photograph is lit like a museum shot (a tall softbox and a strip light reflected in the glaze, satin clay, the pale plinth in the lower glaze, a slight perspective bending every band into an arc), and each frieze is unrolled at its own circumference |+| **Graphite pencil** | `lib/graphite.py` · `Graphite` | graphite is a mass on the paper, not a colour: value is Dmax·(1 − e^−m), so layers build up but never reach black, darks stay a cool slate and hard pressure polishes them to a faint silvery sheen; the lead only deposits where it touches the tooth — light pressure grazes the peaks and leaves white specks, soft leads and hard pressure fill the valleys; grades 2H–8B differ in mass, reach and width; every stroke eases in, swells and flicks off; hatching is laid patch by patch with wandering seams and built up in layers (one direction, interleaved, then crossed at two more angles, each only where the tone asks for it); the side of the lead lays a grainy base tone, a blending stump smooths it inside the area it works, a kneaded eraser lifts soft lights and a hard eraser cuts crisp ones; construction lines to the vanishing point and looped wheel ellipses stay visible, and only the middle is finished — tone drops out stroke by stroke toward the edges, leaving bare line drawing, margin notes and a strip of pencil swatches |+| **X-ray** | `lib/xray.py` · `XRay` | nothing is drawn as a picture of an object: every object is built as material along the beam (a solid with rounded edges, a hollow shell, a round rod or tube, a spring whose far half dives along the beam, discs seen edge-on or face-on, zips, screws, cables, folded cloth), measured in canvas pixels, and adds μ × density × path length to two attenuation maps, one per beam energy — so overlaps simply add, and outlines glow for a physical reason (the beam runs along a case's side wall, a tube's walls, a lens barrel seen end-on). Beer–Lambert transmission then goes through a modelled line-scan detector (scatter haze at quarter resolution, focal-spot blur, per-row gain streaks and module seams, Poisson noise that grows where few photons get through) and two displays: an edge-enhanced, phosphor-glowing blue film where dense is bright, and the security pseudo-colour where the ratio of the two energies gives Zeff (organic orange, inorganic green, metal blue, opaque black) with the belt calibrated out. The OSD reads Zeff and volume off the picture, background-subtracted around each tagged object |+| **1930s rubber hose** | `lib/rubberhose.py` · `RubberHose` | made the way a studio made one frame, then printed and worn: a grey-gouache background painted once on board (washes with a dry-brush streak, airbrushed pools of light and contact shadows, a thin grey outline); actors roughed in pencil, inked on cels in an even, heavy black line and painted on the back in five flat greys with no shading; opaque cels stacked back to front, with clip masks for the overlays they pass behind (a hill, a window bar, a blanket). The vocabulary does the rest: constant-width hose limbs with no elbows, four-fingered white gloves with three stitch lines and a flared cuff, big shiny shoes, pie-cut pupils, open grins, props that come alive. Then the camera and the years: lens softness worse in the corners, halation, lifted blacks and held whites in a silvery-warm print tone, midtone-weighted grain clumps, uneven density, gate weave, a rounded projector gate, white and dark scratches that come and go, dust, lint and a hair in the gate |+| **Linocut** | `lib/linocut.py` · `Linocut` | made by subtraction, like the real thing: a rolled-up block prints solid black and every white in the picture is lino a gouge took away. Each block is a relief map; every cut is a tapered polygon with a crumbly edge — a V-gouge dips in to a point, widens and lifts out, a U-gouge bites with a round head and tears off at the tail — so tone is only ever the density and width of cuts (white lines in black) or of ridges left standing (black lines in white). Cleared areas keep a few low ridges of chatter that catch a little ink; a black thing on a black ground gets a carved white halo. Printing is simulated: a brayer film with stop-lines, the circular pressure of a hand baren, and the paper's tooth decide where ink lands, so big blacks go salty while edges stay solid; one spot-colour block is printed under the key, a few pixels out of register; the paper is pressed into the block, and the margin carries the pencil edition number, title, signature and a blind chop |+| **VHS home video** | `lib/vhs.py` · `VHSCamcorder` | not a retro filter over a picture but the three steps a home-video frame really went through, each one leaving its own marks. The room is painted as surface colour lit by its lamps (a dim warm ambient, a floor lamp that throws scallops up and down the wall, candle flames that light the cake and the child's hair from the front), with self-lit things in their own buffer and the child right in front of the lens on a defocus layer. A consumer CCD camcorder then sees it: hand-held roll, white balance left on 'outdoor' under tungsten bulbs (an orange room, a blue window), a soft highlight knee, bloom, vertical CCD smear through the flames only, a short lag tail, gain noise in the shadows — and its character generator mixes a chunky dot-matrix OSD into the signal, so REC, the counter and the date stamp go onto tape with the picture. Finally the tape: 480 lines, luma low-passed with the playback sharpness halo, chroma smeared ~6× wider, averaged over two lines and delayed to the right (reds bleed out of their outlines), streaky luma and chroma noise, line-by-line timebase jitter, flagging at the top, a tracking-error band, head-switching tear, dropouts and a lifted black level |+| **Flat vector** | `lib/flatvector.py` · `FlatVector` | an artboard of crisp anti-aliased geometric shapes (analytic circles, filleted polygons, tapered capsules, spline land profiles) combined with boolean ops, with no outlines anywhere; seven flat hues, every other colour a tone or mix of them; one light for the whole board, so every object splits into a lit face and a shade face (faceted ridge lines on the mountains, pines split down the middle, a cloud's belly cut from the cloud itself); the vector-paper depth cue: each lifted layer first drops a short, soft, night-blue shadow on what is already there, so every overlap shows a thin seam; glow as stacked flat translucent rings; a faint per-layer fibre and a fine, fixed print grain |+| **Storybook animation** | `lib/storybook.py` · `Storybook` | a real animation, not a draw-on: every piece of scenery is pre-painted once with a reveal map (the moment the pen or brush reaches each pixel), so ink lines draw along their length, washes spread with a darker wet front and props pop in with an overshoot — and the hills, flowers and banks are drawn exactly as the character passes (`follow`). The character is rendered every frame from implicit shapes in its own frame, squashed and stretched with a volume-preserving affine along its motion, rested exactly on the ground, lit by one fixed light so the highlight stays put while it rolls; poses come from eased, sprung and ballistic choreography plus impact lines, dust puffs, speed lines and ripples. The closing line writes itself in stroke order (skeleton walk), and the same scene renders a journey poster with the key poses multiply-exposed on a pencil motion arc |Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:@@ -233,6 +278,21 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages- **Low poly (1999 3D)**: build the frame the way the hardware did and let its limits show: a small framebuffer blown up with no smoothing, flat-shaded facets, blocky texels, fog that hides the far plane, 15-bit dither. Don't make the painter's sort fight hidden geometry: leave out faces nobody sees (the river bed under the water) and give decals a depth bias. Compose with the camera: put the hero on a third with aim(), bend the track so the targets step away diagonally, and keep some sky for the sun and its flare. Gold wants a thick tube, few facets, a low-shine glint and a warm base, or the blue sky light turns it olive; if the sun is in frame, light the scene from higher than the sun you see. Keep the flare to dots and solid hexagons, away from the subject.- **Stencil graffiti**: cut it like a real stencil: run `bridges()` (or check `islands()` is 0) on every card, or the middle of every O and every gap between an arm and the body silently falls out. Do tones as separate cards, light to dark, with `shade_side()` for the grey and black plates; make the black plate bold (a third of the figure), keep the grey clearly between white and black. Keep the card mostly flat: the crisp core is the point, and a lifted card everywhere turns every edge furry. Spend drips where they tell (the black plate, the lettering, under the reel), a couple at most on the light plate, never from bridges. Things that stick out of a figure (a scarf, a fringe) must not read as limbs: two tails from one knot, stripes, fringe strands that do not touch.- **Embroidered patches**: give every shape its own stitch angle and change it between neighbours — the angle, not the colour, is what separates two pieces of thread. Tatami for anything wider than ~60 px; satin for letters, peaks, flames and other narrow shapes, laid across the narrow dimension (flames sideways, not up). Keep the lit face of a mountain mid-tone so white satin snowcaps pop. Draw small details before whatever sits on top of them, and clip running stitches to the patch. Die-cut corners need a radius of at least twice the border width. Merrow for circles, ovals and rockers; a hot-cut satin border for any other outline.+- **Blueprint**: ink the tracing and let the print make the look — never paint white lines on blue. Stick to a few pen weights (heavy for cut outlines, medium for edges, thin for hatching and dimensions) and keep small lettering at a pen of at least 1 px, or poor-contact areas blur it away. Make every view obey drafting conventions and agree with the others: the same levels across elevation and section, cutting planes marked where they cut, hatching scraped back behind figures (clear=True). Give the sheet one small story told by a labelled detail (here: how the lamp, the prisms and the lens make one beam). Age it only after printing — folds, a faded outside panel, a stain, pin holes — and keep red pencil as the single accent; reserve palette slots for it in the GIF.+- **Children's crayon**: draw it the way a child does: outline the things first, then colour the big areas (sky, hills, grass) around everything already on the paper with `avoid=U(OBJ, c.drawn())`, and colour the things last on bare paper; crayon over crayon is semi-opaque, so a red tulip coloured on top of green grass turns brown. Big areas want a wide crayon (20–22 px), low density (0.55–0.65) and a reach of 240–300 px, so the patchwork of stroke directions and the white gaps show; small things get `reach=None`, a narrower crayon and higher density. Keep the hand naive (big heads, stick arms with rake fingers, a sun in the corner, everyone in a row) and let some colour overshoot. Leave a clear patch round the title and the signature, and stop background lines behind people with `line(avoid=...)`. Real crayons on the sheet are a strong material cue but keep them to a corner.+- **Green-screen CRT terminal**: think in light, not ink — dense characters are bright, so dark things (a storm cloud) get a sparse dim fill and a bold rim only where lit. Brighten with attributes (dim → normal → bold) rather than busier characters, and keep line-like characters (- = +) out of fills. Outline clouds with `'cloud'` (every slope a ( or ), flat tops and bases _ . - ') and put cloud bases on whole rows so they print as one `_`. Thin outlines don't survive a 5×7 font: fill small shapes such as a crescent moon with bold % # @. Stretch dots before reverse video and keep reverse bars dim. Downscale the GIF with BOX and a Bayer dither.+- **Thermal camera**: paint temperatures, not colours: decide what temperature every object has and how it varies (base vs. rim, face vs. back, top vs. bottom of a window), then let the heat leak out (`soak`, `plume`, `pool`, `prints`). Use a hand-set `curve=` so the room, the warm bodies and the stove each get their own band of the palette — automatic histogram equalisation turns a room-temperature scene garish and gives the cat the same colour as the wall. Only flames should reach the white end; break up big uniform warm areas (a damp towel on the oven door); low emissivity (a polished lid, steel handles) separates parts for free. Put the OSD over the boring parts of the picture and let `spot`, `box` and `profile` read the numbers off it — never type them in.+- **Delft tiles**: paint in workshop order and keep outlines and washes apart (every layer has a trek and a wash part), so the stages can replay pounce → outline → wash → kiln. Draw front to back and `occlude()` every silhouette: there is one transparent pigment and nothing can be painted over. Get the blue from absorption, not from a colour pick (pale washes are grey-blue, thick lines violet-navy). Let every tile shift its paint by a pixel or two and fire to its own strength — that is what makes a tableau read as tiles rather than a print on a grid. Keep the glaze smooth at small scales: orange-peel noise turns the window reflection into glitter; only the tile's cushion, tilt and a slow ripple should bend it. Screen the reflection over the glaze (never add pure white) and put it over painted sky or border, so the blue shows through and it breaks at the joints. Cracks stop at the joint.+- **Cave painting**: paint on the rock, don't cut it: pigment multiplies into a pale limestone albedo and the only light is a low fire, so relief does the modelling — put the bison on a real bulge and let raking light round it. Keep fine height grain tiny (grazing light turns it into sandpaper) and the big swells moderate (a low lamp drags them into dirty shadows; let only the fire cast shadows). Blow paint densely (≈0.95) with a light rim; a whole-hand blur makes stencils into red rings — spray several puffs aimed at the fingertips and let 1 − exp(−c) fade them. Black legs must stop at the body line or the thighs turn into two black blobs. Cracks must be thin zigzags, or they read as twigs and strings.+- **1-bit paint program**: tone is patterns only — choose a lighter or darker pattern per region, build skies with `bands()`, and make the window (the light) the brightest area in the picture. Put small subjects on the emptiest ground (a white butterfly in front of gingham vanishes) and separate dark shapes with white lines or XOR, never grey. Spray sparingly — one soft edge under a ledge, a shadow beside a black shape; on a patterned ground it reads as dirt. Draw one of a symmetric pair and `copy(..., flip=True, mask=...)` the other. Keep distant objects out from behind foreground plants. Let the snapshots show the work: change the tool, pattern and cursor at every stage, open a menu or a zoom window once, and end on a selection.+- **Greek black-figure vase**: paint on the unrolled surface and let the pot and the rollout share it; put the figures you want seen on the front half (x from 0 to C/2) and let the back carry the rest of the story — the rollout is where it gets told. Declare figures far to near and keep incision and added colour as separate passes: overlaps are told apart only by incised outlines, never by a second shade of black. Horses need their bellies well off the ground line and legs angled down to it, or the team looks like it is swimming; put a white horse farthest and raise its head. Narrow the softbox reflection to a vertical strip, or the glaze highlight reads as an extra white figure. Age gently: a little flaked white, crust low on the body, a mend toned close to the clay.+- **Graphite pencil**: work like a pencil artist — construction lines first (horizon, lines to the vanishing point, ellipses with their axes), then contours, then the side of the lead for a base tone, hatching layers for the middle values, the darks pressed in last; blend with the stump inside each area (`contain=True`) and pull the lights out with erasers (rims, tube highlights, the lit edge of a corner, glints on glass) rather than leaving holes. Paint dark objects (a painted frame, tyres, a saddle) as real values, not white cut-outs with outlines. Keep cast shadows hatched, crisp-edged and lighter than the object that casts them, or they read as a blurred double. Finish only the middle (`focus`): let strokes drop out toward the edges so the sheet ends in bare lines — fading the tone smoothly looks airbrushed.+- **X-ray**: build things the way they are made, not the way they look: a case is a thin shell 25 cm deep, a trolley rail is two nested aluminium tubes, a lens is rings seen end-on plus glass that is thickest in the middle, a heating element is a coil of coil — the X-ray look (glowing outlines, double edges, bright spring turns, white bolt ends) then comes out of the path lengths by itself. Give the story object the most attenuation per pixel (chunky bones, a steel pin) and keep big organic masses (clothes) faint but textured. Let several things overlap — it is additive, and overlap is what makes it read as X-ray — but keep the hero clear of the brightest metal. Tag what the OSD talks about and write `{tag.z}` / `{tag.ml}` instead of typing numbers.+- **Rubber hose**: keep the cels flat and the background soft — five flat cel greys with a heavy black line, sitting on a grey-gouache background with thin grey lines, is what reads as "1930s"; shading a character makes it modern. Ink only outside the fill, paint the pieces of a glove or shoe as one union so no line splits them, and draw back to front with clip masks for whatever an actor passes behind. Never put a flat ellipse over a head (it reads as a halo) or a crown of triangle rays on a sun — give the sun a scalloped corona with short, bold dashes. Age the print last: midtone-weighted grain, lifted blacks, gate weave and a rounded gate do more than piling on scratches.+- **Linocut**: start from a solid black block and only ever cut — tone is the spacing and width of gouge marks, never grey. Keep most of the sky black (a few hundred thin wind streaks in bands, nothing near the moon) or the big black-and-white contrast is lost. Give black things on black ground a carved white halo, and white things crossing white ground (smoke over a snowy hill) a thin black edge. Keep the spot colour to a few small, meaningful places (lit windows, a lamp, a spill of light) and let the key block's ridges run over it. Let the print do the ageing: salty blacks, solid edges, faint chatter, a light emboss — don't paint them in.+- **VHS home video**: light the room, don't tint it: give the scene real lamps (`light`, `floor_lamp`, a `light` on every flame `cake` returns) and keep the ambient low, so the camcorder has something to clip and the corners have something to be noisy in. Let only point sources go far over the top — anything big over ~2 turns the CCD smear into a pillar across the frame. One strong complementary colour against the tungsten orange (a blue window, a green sofa, a teal shirt) does more than any filter. Paint the near subject on `layer(defocus=)`, tilt the camera a degree or two, and put the OSD in through the camera (`rec`, `datestamp`, `zoom_bar`) so it smears with the tape; keep the tracking band at the bottom, off the subject. Make OSD text from the dot-matrix font only — 1-dot gaps fill in, so check 0/8, W, M after the tape.+- **Flat vector**: win with a few big shapes and empty space, not with detail: three or four land layers, one moon, a generous sky, and one small story told with one or two warm accents. Seven colours; every other shade is a tone of one of them. One light for the whole board, with the shade faces always on the far side. With no outlines, choose each object's colour against what sits behind it (an orange tent goes on the sand, not in front of the orange hills). Lift layers a few pixels for a soft seam of shadow, and keep texture around 1% so flat fields still read as flat. Put translucent shapes over a single background colour only. People, if any, are tiny silhouettes.+- **Storybook animation**: the story is the acting, so choreograph first — anticipation before every big move (squash and lean away), stretch along the velocity, squash on every landing with impact lines and dust, a spring settle afterwards — and let the world be drawn by the character (`follow=` with a lead of 150–350 px, `pre=` for what is left of the start). Give `soft` in pixels, not as a fraction of a 2000-px layer, or the paint front turns into fog. Keep the camera still: only what moves is re-encoded, so 151 frames stay near 0.6 MB. On the poster, pick poses that sit apart along the path, draw the end state itself instead of a ghost on top of it, and hide the props' final positions.### Roadmap@@ -244,7 +304,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,加上一个小巧的绘图库,内置五十八种画风:| 画风 | 模块 | 为什么看起来像真的 ||---|---|---|@@ -291,6 +351,21 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages| **低多边形(1999 年代 3D)** | `lib/lowpoly.py` · `LowPoly` | 一个真的软件光栅化器,画进 384×216 的帧缓冲:针孔相机,顶点吸附到整像素,背面剔除,整个场景的三角形排成一张按深度排序的表(主机的 ordering table)从远到近画,贴花带排序偏置,近平面裁剪,可选 z-buffer;每个面一个颜色的平面着色(半球环境光 + 太阳 + 逐面闪光,金环一面一面地闪);几十像素的程序贴图最近邻取样、仿射插值,靠近镜头的大三角形上岩层会弯;逐顶点雾吞掉远裁剪面;alpha 硬裁切的十字插片树;当年的四种半透明模式画螺旋桨盘、圆斑影子、星光和镜头光晕;最后 15 位色加 4×4 有序抖动,最近邻放大 5 倍;点阵 HUD(带描边和投影的渐变斜体数字、阶梯速度条、小地图) || **喷漆模板涂鸦** | `lib/stencil.py` · `Stencil` | 木纹模板清水混凝土墙是反照率加高度图、低太阳打光(木板压出的色带和木纹、板缝的断续水泥浆棱、锥形对拉螺栓孔里的锈铁头或灰浆堵头、气泡孔、锈水和雨痕、返潮水线和泛碱、发丝裂缝);模板是真的刻开的卡纸:刻断的孤岛自动找出来、补最短的桥,字腔自带桥,桥在漆上是露墙的细缝;多层就是多张卡纸先浅后深、每张贴歪几像素;喷罐来回扫,高斯喷锥叠成漆膜,卡纸贴平处边缘锐利、翘起处往里渗、外面一圈雾化;漆是雾滴,薄处是散点不是模糊;盖不进小孔、贴着墙面起伏、带缎面光泽,下边缘太厚就流成带细颈和圆珠的滴痕;徒手细喷嘴线条随手速变粗变重;竖向滚道的市政灰漆,底下的旧签名还透出来;快照里模板还贴在墙上 || **刺绣徽章** | `lib/patch.py` · `Patch` | 像绣花机一样绣:每块形状按自己的针向切成平行的行、每行再切成针——大面积用短针错位的填充绣(tatami),细长形用一行一根长线的缎面绣(太长自动拆成分段缎面),所以形状的边缘就是一排针脚;每针都是一根有光泽的圆线,两头扎进布里,高光是各向异性的(Kajiya–Kay),同一种颜色换个针向亮度就不同;缎面按衬垫拱起,一根线上从亮到暗;圆章、弧形条章包锁边(斜着一圈圈绕的圆绳),异形章包热切缎面边,两者都做了子采样,在急弯处针距过密时把线的起伏淡成平滑的扇形;3/1 右斜纹牛仔布(经密纬疏、斜纹约 60°、环染竹节纱、高处磨白),折边缝压双道明线;最后一枚徽章正在手缝,针和线还躺在布上 |+| **蓝图工程图** | `lib/blueprint.py` · `Blueprint` | 先在描图布上画墨线:几种固定粗细的鸭嘴笔、字模板式的单笔画大写字(描图布上留着铅笔导线,尺寸数字后面的剖面线刮掉),再接触晒图:墨挡住弧光灯,线底下的铁盐冲洗后是白的,其余地方生成普鲁士蓝;显影按有阈值的 S 曲线,粗线纯白、发丝线发浅蓝、底色饱和;光从线边爬进去,玻璃压紧处锐、接触不良处软,外面一圈淡光晕;灯在中间强、四周弱,药面有涂布条纹、斑驳和晾干时的流痕,颜色按普鲁士蓝在纸上的比尔–朗伯吸收算,纸纤维透出来;处处守制图规范(按材料分的剖面线、尺寸线与尺寸界线、标高、剖切符号、详图索引圈、指北针、比例尺、带分区编号的图框、标题栏和修改栏);再过图纸的一生:折成六折,折痕把蓝色裂成白线,朝外那格褪色发灰,碱性水渍变成锈褐色、留下两道潮线,图钉孔生锈,工地工程师的红蜡笔修改云线 |+| **儿童蜡笔画** | `lib/crayon.py` · `Crayon` | 糙纸纸纹均衡过,压力直接对应覆盖率;蜡只挂在纸纹凸起上,拖着走时露白的小坑被拉成顺着笔道的短条;用秃的笔头是带棱的平面,一笔是一束强弱不一的细线,笔道里有白色细纹;后涂的蜡更容易挂在先涂的蜡上(蜡层堆积),半透明叠色(黄上涂蓝变绿,黑线涂不掉);小孩的手:先勾线,再按胳膊够得着的一块块来回涂,每块各自的角度,转折处出界,绕着要留白的东西小心停住;绕圈涂、顺着彩虹带子涂、形状首尾对不上;字是细化后的中心线用圆头蜡笔重描,每个字歪的方向、大小、颜色都不同;使劲压过的蜡白点合上、发亮;纸和蜡一起当高度图打光;纸上躺着带印花包装纸的真蜡笔(一根断了)和蜡屑 |+| **绿屏终端 CRT(荧光字符画)** | `lib/crt.py` · `CRTTerminal` | 重做一台字符终端,而不是画一张图:120×36 格字符内存,每格有 dim / normal / bold、反白、下划线,行可以双倍高;5×7 点阵字库(小写带下伸部),加一套图形字符(框线、画曲线的五档扫描线横条、八分块)。字符画先画进隐藏的「材质 + 调子」图:里面的格子按阶梯选字并做误差扩散,剪影按边在格里的方向和高低选字;屏幕上「密 = 亮」,所以雷暴云稀而暗、只有受光的边亮。电子束每行扫 10 条扫描线:点拉伸半个点(在反白之前做,暗笔画不被吃掉),视频放大器拖尾,光斑随电流变粗。P1 荧光粉亮到发白,落雨留下上一帧的余辉,状态栏里烧着一行旧字。光栅桶形外鼓、边缘变暗,玻璃里有光晕、窗户倒影和机壳的阴影。米色塑料机壳的斜面映着绿光,还有合模线、电源灯和两个滚花拨轮 |+| **热成像** | `lib/thermal.py` · `Thermal` | 从头到尾不画颜色,画的是一张摄氏度的温度场:房间上暖下凉,每样东西有自己的温度和温度分布(锅底最烫,猫的眼睛比鼻子和耳朵热),抛光金属按发射率读出的是它反射的房间,圆形物体越到轮廓越凉;然后让热按真实的方式往外走:渗进灶后的墙,热气和蒸汽成羽流往上飘、越来越宽、越来越凉、碎成涡和丝,打开的冰箱往下淌冷气、在地上铺成冷舌,暖爪印越旧越淡越散,釉面地砖倒映烤箱;这张温度场再交给一台模拟的非制冷热像仪:镜头模糊、按 480×270 像元采样、时间噪声和竖条纹、中心偏凉、细节增强、手调色调曲线混平台直方图均衡、伪彩色板、双线性放大并留一点像素格;OSD(状态栏、点测温、区域框、最热 / 最冷标记、线剖面插图、非线性色标)上的每个数字都从同一张传感器图像上读出来 |+| **代尔夫特蓝瓷砖** | `lib/delft.py` · `DelftTile` | 照作坊工序做一面锡釉砖墙:白坯砖排在一张从来不完全横平竖直的网格上;刺孔纸样拍出炭粉点线;细笔勾线(落笔一颗墨珠、收笔变尖、往下的笔画更粗、手微微抖);晕染没法晕开(笔道、鬃毛丝、最后干的边缘积色、叠染变深、总和轮廓差一点,留白靠绕着画);只有一种透明颜料,所以从前往后画、靠留白而不是覆盖;生颜料是灰黑色,入窑后按每通道 Beer–Lambert 吸收变成钴蓝,洇进釉里、带细颗粒;每块砖单独画、单独烧,线条在砖缝处错开,每块砖的白和蓝都不一样;单块砖四角各画四分之一,四块拼起来才是一朵角饰;下凹的石灰浆砖缝;每块砖略鼓略斜,窗户倒影碎成弯曲的几片,圆倒角接住光;开片、铁斑、崩瓷露出浅褐坯体、裂纹到砖缝就停 |+| **洞穴壁画(赭石颜料)** | `lib/cave.py` · `CavePainting` | 和岩画正相反:颜料是涂在浅色石灰岩上的,只有火光照着。洞壁是高度图(大起伏、岩脊、淡淡的溶蚀扇贝纹、积了泥的小坑、凸处的钙华皮、湿亮的钟乳石帘),颜料是一层层覆盖场乘进 albedo,再浓也透出石头的斑驳。怎么上的色决定了样子:炭条沿游移轮廓找形,干炭条只挂在岩面的「牙口」上,吹喷的颜料有软边、晕和雾点,靠轮廓和鼓包背光的一侧更浓,肚子留出浅色;手印是对着指尖和手侧吹几口气喷出来的。只用地上的篝火和油灯照明:点光源半 Lambert + 平方反比衰减 + 逐像素步进的投影,掠射光让画在鼓包上的动物自己鼓起来;火舌、火星、泛光、烟柱、熏黑的顶壁、钙华薄膜、零星掉色和洞熊爪痕 |+| **1-bit 早期画图软件** | `lib/macpaint.py` · `MacPaint` | 画的是一台 1984 年式黑白画图软件的整屏,不是「像素风插画」:640×360 帧缓冲只有黑白两值,×3 无平滑放大;所有色调都来自 38 种 8×8 图案,图案贴着文档原点平铺(同一图案的两块天然对缝,不随形状弯),渐变是几条图案带;工具照当年的规矩:方笔头 Bresenham 线和台阶状锯齿,形状是图案填充加画在轮廓内侧的当前线宽边框,4 连通油漆桶,往圆盘里随机撒点(OR)的喷枪,笔刷形状,选取拖动复制和左右翻转,XOR;手工点阵的粗体系统字(大写 9 px、竖笔 2 px),TrueType 关掉抗锯齿,粗体 / 斜体 / 下划线 / 空心 / 阴影都是对字形遮罩的位运算;界面每个快照重画:自编菜单名的菜单栏和屏幕黑圆角、当前工具反白的 20 件工具栏、线宽框、带当前填充框的图案板、带关闭框的条纹标题栏、50% 灰轨滚动条、每项按自身样式书写的下拉菜单、放大镜窗、行军蚁、带白边的光标 |+| **古希腊黑绘陶瓶** | `lib/blackfigure.py` · `BlackFigure` | 先在轮上拉出瓶子(轮廓 r(y) 加两只圆把手),所有彩绘都画在它的展开面上,所以同一幅画既包在曲面瓶上、又能平铺成展开图,两边永远对得上;按作坊的工序画:转着轮画的饰带(绝对水平,收笔处有一点搭接),泥釉剪影(这时还是暗褐色),刻刀划透泥釉露出橙色细节,最后上哑光的加红加白;人物的每个部件按远近排序,近处的黑马盖住远处那匹的刻线和加彩、再刻出自己的轮廓——四匹马叠在一起仍然分得清;烧成后泥釉变成泛蓝的亮黑,薄处发红;然后过两千五百年:加白剥落留下哑光残影,钙质结壳和根痕,缺口露出胎土,调色补土的修补和胶合裂缝,一片没烧透的发红釉;照片按博物馆的打光(黑釉里一长条柔光箱和一条侧光的反射,粘土是缎面微光,下半身映着浅色展台,一点透视让每条饰带弯成弧),每一圈饰带按自己的周长展开 |+| **铅笔素描** | `lib/graphite.py` · `Graphite` | 石墨是纸上的一层「量」而不是颜色:深浅是 Dmax·(1 − e^−m),越叠越深但到不了黑,暗部是冷灰,重压处被压亮、带一点银灰反光;铅只在碰到纸纹的地方留下:轻压擦过纸纹的峰、留下白点,软铅和重压才填进谷;2H–8B 的石墨量、压进纸纹的深度和线宽各不相同;每一笔起笔、加力、收笔;排线一块一块地排,块与块的接缝略有漂移,一层层加(先一个方向、再插密、再从两个角度交叉,只在需要那么暗的地方下笔);侧锋铺出带颗粒的底色,纸擦笔只在它擦的那块里匀开,可塑橡皮按出柔和的亮,硬橡皮擦出清楚的白线;通往灭点的透视线和绕几圈的车轮椭圆留在画面上,只有中间画完——越往纸边调子一笔笔地少下去,只剩线稿、页边笔记和一排试笔色阶 |+| **X 光片** | `lib/xray.py` · `XRay` | 不画物体的样子:每样东西都是「沿射线方向的材料」(倒圆边的实心体、空心壳、圆棒和管子、远半圈潜下去的弹簧、侧看 / 正看的圆片、拉链、螺钉、电线、叠好的衣服),按画布像素量,把 μ × 密度 × 路径长度加进高低两种能量的衰减图——所以重叠就是相加,轮廓发亮也有物理原因(射线顺着箱子侧壁、管壁、正对着的镜筒穿过);比尔定律透射后经过一台模拟的线阵探测器(1/4 分辨率的散射雾、焦点模糊、逐行增益条纹和模块缝、光子少的地方噪声大),再进两种显示:越密越亮、带边缘增强和荧光辉光的蓝色胶片,以及按双能比值算 Zeff 的安检伪彩(有机橙、无机绿、金属蓝、穿不透黑,传送带当空气校准扣掉);OSD 上的 Zeff 和体积都是在物体外一圈扣掉背景后从画面上量的 |+| **1930 年代黑白橡皮管动画** | `lib/rubberhose.py` · `RubberHose` | 照动画厂做一格画面的方式做,再印成拷贝、放旧:背景在板上用灰色水粉画一次(平涂带干笔刷纹、喷枪光斑和接触阴影、细灰轮廓);角色先铅笔起稿,再用粗而均匀的黑墨描到赛璐璐上,背面涂五档平灰,不画明暗;赛璐璐不透明、从后往前叠,角色要从后面经过的山、窗档、被子存成遮罩。剩下的靠这套词汇:等粗无关节的橡皮管四肢、三道缝线加外翻袖口的四指白手套、发亮的大圆鞋、切掉一角的饼切瞳孔、张大的笑嘴、活过来的家什。最后是镜头和岁月:四角更软的柔焦、高光晕、抬起的黑位和压住的白位、银灰偏暖的拷贝色调、中间调最重的团粒颗粒、密度不匀、片门晃动、圆角片门,时有时无的白 / 黑划痕、灰尘、纤维和片门里的一根头发 |+| **黑白麻胶版画** | `lib/linocut.py` · `Linocut` | 和真的一样是减法:滚上墨的整块版印出来是一片黑,画里每一处白都是刻刀挖掉的。每块版是一张浮雕图,每一刀是两头收尖、边缘带碎口的多边形——V 口刀尖着下去、越刻越宽、提刀收尖,U 口刀圆头咬进去、尾巴崩断——所以明暗只能靠刀痕的疏密和粗细(黑里刻白线,或白里留黑线)。清掉的大片白里留着几道残刀印,吃一点墨;黑东西压在黑底上,就在外面刻一圈白边。印刷是算出来的:墨辊滚出的墨层和停辊横纹、木蘑菇一圈圈的压力、纸纹的高低决定哪里吃墨,大片实地发花、边缘始终是实的;一块套色版垫在黑版下面印,错开几像素;纸被压进版里,页边有铅笔版次、题名、签名和一枚钢印 |+| **VHS 家庭录像** | `lib/vhs.py` · `VHSCamcorder` | 不是在画面上盖一层复古滤镜,而是照一帧家庭录像真实经过的三步来做,每一步留下自己的痕迹:房间画成表面颜色,再由屋里的灯照亮(暗暗的暖色环境光,落地灯在墙上照出上下两片扇形光,烛焰从前面照亮蛋糕和孩子的头发),会发光的东西单独一层,镜头跟前的孩子画在离焦图层里;然后交给一台家用 CCD 摄像机:手持微倾,白平衡停在「室外」拍钨丝灯(屋里发橙、窗外发蓝),高光软膝、泛光,只有烛焰拉出竖向拖影,高光身后一小段拖尾,暗处增益噪声——摄像机的字符发生器把粗点阵 OSD 混进信号,REC、计数器和日期跟画面一起上带;最后是录像带:480 行,亮度低通再加回放锐化光晕,色度宽约 6 倍、隔行平均、往右延迟(红色渗出轮廓),条状亮度噪声和横向色度噪声、逐行时基抖动、顶部偏摆、跟踪噪带、磁头切换撕裂、掉磁白点、抬高的黑电平 |+| **扁平矢量** | `lib/flatvector.py` · `FlatVector` | 矢量软件的画板:边缘干净、抗锯齿的几何形(解析圆、圆角多边形、锥形胶囊、样条地块),可以并、交、减,全画没有一根描边;七种平涂色,其余颜色都是它们的深浅或相互调和;整幅只有一个光源,每样东西都分成亮面和暗面(山的折线山脊,松树从中间劈开,云的暗面是云减去挪动后的自己);「矢量纸片」的层次:每抬起一层,先往已有画面投一道短而柔的夜蓝色阴影,所以每处重叠都有一道细缝;光是一圈圈叠起来的平涂半透明光环;每层极淡的纤维纹,加固定的细颗粒 |+| **绘本角色动画** | `lib/storybook.py` · `Storybook` | 是真动画,不是阶段叠化:每样风景都预画一次,并记一张「揭示图」(笔或刷子在第几时刻碰到每个像素),所以墨线沿着笔路画出来、水彩带着一道略深的湿边晕开、小物件回弹着冒出来;山坡、小花、河岸正好在角色经过时画上(`follow`)。角色每帧用隐式曲面现画,沿运动方向做保体积的挤压拉伸,最低点正好贴地,光照固定在世界里(滚动时高光不跟着转);动作由缓动、弹簧和抛物线编排,配冲击线、白色尘团、速度线和水波。结尾一行字按笔顺一笔笔写出来(走骨架),同一个场景还能出一张旅程总图:关键姿态多次曝光在铅笔运动弧上 |对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;@@ -363,6 +438,21 @@ python3 examples/lineprinter_launch.py out.png # ASCII 字python3 examples/lowpoly_canyon.py out.png # 低多边形:峡谷飞行python3 examples/stencil_kite.py out.png # 喷漆模板涂鸦:放风筝python3 examples/patch_camping.py out.png # 刺绣徽章:三晚露营+python3 examples/blueprint_lighthouse.py out.png # 蓝图工程图:灯塔剖面+python3 examples/crayon_picnic.py out.png # 儿童蜡笔画:我的周末+python3 examples/crt_weather.py out.png # 绿屏终端 CRT:今天带伞吗+python3 examples/thermal_kitchen.py out.png # 热成像:厨房里的温度+python3 examples/delft_canal.py out.png # 代尔夫特蓝瓷砖:运河小镇 · 一阵风+python3 examples/cave_hunt.py out.png # 洞穴壁画:篝火旁的岩洞+python3 examples/macpaint_garden.py out.png # 1-bit 早期画图软件:窗台花园+python3 examples/blackfigure_games.py out.png # 古希腊黑绘陶瓶:赛跑与赛车+python3 examples/graphite_bicycle.py out.png # 铅笔素描:老街角的自行车+python3 examples/xray_luggage.py out.png # X 光片:行李安检+python3 examples/rubberhose_morning.py out.png # 1930 年代黑白橡皮管动画:早晨的闹钟+python3 examples/linocut_snowy_village.py out.png # 黑白麻胶版画:雪夜归途+python3 examples/vhs_birthday.py out.png # VHS 家庭录像:吹蜡烛+python3 examples/flatvector_night_camp.py out.png # 扁平矢量:山间夜营+python3 examples/storybook_acorn.py out.jpg --gif out.gif # 绘本角色动画:小橡果的秋天```### 作画要点(Claude 交图前逐条自查)@@ -408,6 +498,21 @@ python3 examples/patch_camping.py out.png # 刺绣徽- **低多边形**:照当年硬件的做法画,并且让它的局限露出来:小帧缓冲无平滑放大、平面着色的小面、块状纹素、用雾藏住远裁剪面、15 位色抖动;别让画家排序去和看不见的几何打架:没人看得见的面(水下的河床)干脆不生成,贴花加排序偏置;构图靠相机:用 aim() 把主角放到三分点,让赛道转弯、目标沿对角线排开,留出天空给太阳和光晕;金环要粗管、少面、低 shine 的闪光和偏暖的底色,否则蓝天光一照就发橄榄色;太阳在画里时,着色光比看得见的太阳抬高一些;光晕只用小圆点和实心六边形,别压在主体上。- **喷漆模板涂鸦**:照真模板来刻:每张卡纸都跑一遍 `bridges()`(或者确认 `islands()` 是 0),否则每个 O 的中间、手臂和身体之间的卡纸都会悄悄掉掉。分几个色调就分几张卡纸,先浅后深,灰版、黑版用 `shade_side()` 切;黑版要大胆(约占人物三分之一),灰色要明显介于黑白之间。卡纸以平贴为主:清晰的核心是这种画风的看点,到处翘起来,所有边都会长毛。滴痕用在有戏的地方(黑版、字、线轮下),白版最多一两道,桥上不起滴。从人物身上伸出去的东西(围巾、流苏)别让它像胳膊:一个结里分出两条尾巴、画横条纹、流苏散开别碰在一起。- **刺绣徽章**:每块形状给自己的针向,相邻的要换角度——分开两块线的是针向,不是颜色。宽过约 60 px 的用填充绣;字、山尖、火焰等细长形用缎面绣,针横跨窄的那一边(火焰横着走,不是竖着)。山的亮面用中间调,白色缎面雪顶才跳得出来。小细节要先于压在它上面的东西画,平针用 `clip=` 限在徽章里。异形章的圆角半径至少是边框宽度的两倍。圆、椭圆、弧形条章用锁边,其他轮廓用热切缎面边。+- **蓝图工程图**:只画墨线,让晒图出效果——不要直接在蓝底上画白线。笔只用几种固定粗细(剖切轮廓粗、可见边中、剖面线和尺寸细),小字的笔宽至少 1 像素,否则接触不良的区域会把它糊掉。每张图都守制图规范、互相对得上:立面和剖面用同一套标高,剖切符号画在真正剖开的位置,尺寸数字后面的剖面线刮掉(clear=True)。整张图讲一件小事,用一张带标注的详图讲清楚(这里是灯、棱镜和透镜怎样做出一束光)。老化只在晒好之后做——折痕、朝外那格褪色、水渍、图钉孔;红铅笔是唯一的点睛色,动图里给它单独留调色板位。+- **儿童蜡笔画**:照小孩的顺序画:先把东西勾出来,再涂大片(天空、山坡、草地),用 `avoid=U(OBJ, c.drawn())` 绕开纸上已有的一切,最后在白纸上给东西上色;蜡笔叠蜡笔是半透明的,红郁金香涂在绿草上会发褐。大片用宽笔(20–22 px)、低密度(0.55–0.65)、reach 240–300 px,笔道方向一块块不同、留出白缝;小东西 `reach=None`、笔窄一点、密度高一点。画法要天真(大头、火柴棍胳膊加耙子手指、角上的太阳、一家人站成一排),让一些颜色涂出界。标题和签名周围留一圈空白;背景的线用 `line(avoid=...)` 停在人后面。纸上放真蜡笔很能说明材料,但只放在一个角落。+- **绿屏终端 CRT**:按「光」想,不按「墨」想——字越密越亮,所以暗的东西(雷暴云)用稀疏的 dim 填充,只在受光的边上用 bold。提亮靠属性(dim → normal → bold),不靠更花的字;填充里不要用 - = + 这种像线的字。云用 `'cloud'` 轮廓(斜坡一律 ( ),平顶平底 _ . - '),云底放在整数行上,才能打成一根 `_`。细线在 5×7 字里留不住,月牙这类小形状用 bold 的 % # @ 填满。点拉伸要在反白之前做,反白条用 dim。动图缩小用 BOX 加 Bayer 抖动。+- **热成像**:画温度,不画颜色:先想清楚每样东西多少度、温度怎么分布(锅底和锅沿、脸和背、窗玻璃的上和下),再让热往外走(`soak`、`plume`、`pool`、`prints`)。用手调的 `curve=` 让房间、温暖的身体、灶台各占色板的一段——自动直方图均衡会把室温场景拉得花哨,还让猫和墙同一个颜色。只有火焰可以到白;大块一样暖的面要打断(烤箱门上搭一条湿抹布);低发射率(抛光锅盖、钢把手)能白送一层区分。OSD 放在画面里没戏的地方,数字一律用 `spot`、`box`、`profile` 从画面上读,不要手写。+- **代尔夫特蓝瓷砖**:按作坊工序画,线和晕染分开存(每层都有 trek 和 wash 两份),动图才能重演粉印 → 勾线 → 晕染 → 入窑。从前往后画,每画完一样东西就 `occlude()` 它的轮廓——只有一种透明颜料,后画的盖不住先画的。蓝色靠吸收算出来,不要直接挑色(淡染是灰蓝,浓线是紫藏青)。每块砖的画面错开一两像素、各烧各的浓淡,砖画才像一块块砖,而不是印在格子上的图。釉面小尺度要平:橘皮噪声会把窗户倒影变成闪粉,只让砖的鼓起、倾斜和缓慢的起伏去弯它。倒影按滤色叠上去、不要加成纯白,放在画了东西的天空或边框上,底下的蓝透得出来、在砖缝处断开。裂纹到砖缝就停。+- **洞穴壁画**:是涂在石头上,不是凿:颜料乘进浅色石灰岩的 albedo,唯一的光是地上的低矮火光,所以体积靠岩面起伏——把野牛画在真的鼓包上,让掠射光把它照圆。细颗粒高度要极小(掠射光会把它放大成砂纸),大起伏要适中(低矮油灯会把它拖成一团团脏影子,只让篝火投影)。吹喷要浓(约 0.95)、rim 要轻;手印别用整只手模糊一次(会变成红圈),要对着指尖和手侧吹几口气、用 1 − exp(−c) 自然淡出。黑腿要停在身体轮廓线下,否则大腿变成两团黑。裂缝要细而成之字形,否则像小树枝、像吊绳。+- **1-bit 早期画图软件**:色调只靠图案——每块区域挑浅一点或深一点的图案,天空用 `bands()` 分带,窗户(光源)要是全画最亮的地方。小东西放在最空的底上(白蝴蝶放在格子布前就没了),深色形体之间用白线或 XOR 分开,不用灰。喷枪少用:窗台下一道软边、黑色形体旁一片影子就够,在图案底上喷多了像脏。对称的一对只画一个,另一个 `copy(..., flip=True, mask=...)`。远景小物别躲在前景植物后面。快照里要看得出在操作:每一阶段换工具、图案和光标,中间开一次菜单或放大镜窗,最后停在一个选区上。+- **古希腊黑绘陶瓶**:画在展开面上,瓶子和展开图共用一张;想让人看见的人物放在正面半圈(x 从 0 到 C/2),背面留给故事的后半段,展开图负责把它讲完。人物从远到近声明,刻线和加彩各走一遍:叠在一起的部件只靠刻线分开,不要用第二种黑。马肚子要离地线足够高、腿斜着够到地线,不然整队马像在游泳;白马放在最远一匹并把头抬高。柔光箱的反射收成一条竖光,否则黑釉上的高光会被看成多出来的白色人物。做旧要轻:加白剥一点,结壳只在下半身,补土颜色贴近胎色。+- **铅笔素描**:照画素描的顺序来——先起形(视平线、通往灭点的透视线、带轴线的椭圆),再勾轮廓、侧锋铺底、排线铺中间调、最后压暗部;纸擦笔只在一块里匀(`contain=True`),亮部用橡皮提出来(轮圈、管子高光、墙角亮边、玻璃反光),不要靠留白挖洞。深色的东西(漆过的车架、车胎、车座)要画出真实的深浅,别成了带轮廓的白剪影。投影用排线、边要清楚、比投影的东西浅,否则像一个糊掉的重影。只画完中间(`focus`):往纸边让笔画整笔整笔地少下去,最后只剩线稿——调子平滑地渐隐会像喷枪。+- **X 光片**:按东西的造法建模,别按长相画:箱子是 25 cm 深的薄壳,拉杆是两层套着的铝管,镜头是正对射线的圆环加中间厚的玻璃,电热丝是螺旋上再绕螺旋——轮廓发光、双边线、弹簧亮点、螺栓白点这些 X 光的样子会从路径长度里自己长出来。讲故事的那样东西每个像素的衰减要最大(骨头做粗、里面穿钢销),大团的有机物(衣服)保持淡但有纹理。让几样东西互相重叠——X 光是相加的,重叠正是它像 X 光的地方——但主角别压在最亮的金属上。OSD 要说的东西加 tag,数字写 `{tag.z}` / `{tag.ml}`,不要手填。+- **橡皮管动画**:赛璐璐要平、背景要软——五档平灰加粗黑线的角色压在细灰线的灰色水粉背景上,这个反差就是「30 年代」,给角色加明暗就变现代了。墨线只在填色外侧,手套、鞋这类几块拼起来的东西用 union 一次画成,中间不出线;从后往前画,角色要从后面经过的东西用 clip 遮罩。头顶不要放扁椭圆(像光环),太阳不要一圈尖三角,用扇贝边光晕加粗短的放射短线。胶片老化放最后:中间调颗粒、抬起的黑位、片门晃动和圆角片门比堆划痕更管用。+- **黑白麻胶版画**:从一整块黑开始,只做减法——明暗靠刀痕的疏密和粗细,不用灰。天空大部分要留黑(几百道细风痕、只刻在几条云带里,月亮周围不刻),否则大块黑白对比就没了。黑东西压在黑底上要刻一圈白边,白东西穿过白底(雪坡前的炊烟)要留一圈黑边。套色只放在几处有意义的小地方(亮窗、灯、门前那摊光),让黑版的线从它上面穿过。发花、实边、残刀印、压印都让「印刷」这一步算出来,别手画。+- **VHS 家庭录像**:给房间打光,不要给画面调色:放真实的灯(`light`、`floor_lamp`,`cake` 返回的每个火苗各放一盏 `light`),环境光压低,摄像机才有东西可以过曝、暗角才有地方出噪点。只让点光源远远超出上限——大面积超过约 2 的地方会把 CCD 拖影拉成一根贯穿画面的光柱。在钨丝灯的满屏橙里放一块强补色(蓝色的窗、绿色的沙发、青绿的衣服),比任何滤镜都管用。离镜头太近的主体画在 `layer(defocus=)` 里,镜头歪一两度,OSD 通过摄像机加(`rec`、`datestamp`、`zoom_bar`),让它跟着录像带一起糊;跟踪噪带放在底边,别压主体。OSD 只用点阵字库,1 点宽的缝会被填死,过了录像带检查 0/8、W、M 读不读得出来。+- **扁平矢量**:靠几个大形状和留白取胜,不靠细节:三四层地形、一个月亮、大片天空,用一两处暖色讲一件小事。只用 7 色,其余都是它们的深浅。整幅一个光源,暗面永远在背光那边。没有描边,所以每样东西的颜色要对着它身后的颜色来定(橙色帐篷放在黄沙上,别放在橙色山丘前)。每层抬起几像素,留一道柔和的阴影缝;纹理控制在 1% 左右,平涂看上去还得是平的。半透明形状只放在单一底色上。要画人,只画很小的剪影。+- **绘本角色动画**:故事靠表演,先编排动作——每个大动作前都要有预备(压扁、往反方向后仰),沿速度方向拉伸,每次落地压扁并配冲击线和尘团,之后用弹簧回稳——再让世界跟着角色画出来(`follow=` 提前量 150–350 px,起点左边那段用 `pre=`)。柔边按像素给,别写成 2000 px 宽层的比例,否则湿边变成一团雾。镜头别动:只有动的地方重新编码,151 帧才能压在 0.6 MB 左右。总图里选沿路分得开的姿态,终点画最后一帧本身,别再叠残影,道具终点位置也藏掉。### 计划diff --git a/SKILL.md b/SKILL.mdindex 7813c6b..a99e741 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,6 +1,6 @@---name: claude绘图-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置四十三种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)、拼豆(钉板上的熔珠小管、熨烫熔合)、岩画(沙漠漆上凿出的凹坑图形、新旧凿痕、剥落)、古埃及墓室壁画(灰泥墙、红格起稿、分栏叙事、象形文字、剥落)、罗马马赛克(石子与玻璃沿轮廓一排排铺、灰缝、燕尾铭牌)、彩色玻璃花窗(哥特尖拱窗、通体着色玻璃、grisaille 彩绘与银染、铅条、透光)、泥金手抄本(羊皮纸、鹅毛笔哥特体、朱红标题、打磨金箔首字母)、达·芬奇手稿(铁胆墨水、左手排线、红粉笔、镜像手写、机械分解图)、剪影(黑纸剪出的侧影小像、薄金粉、椭圆金框)、凸版印刷海报(木活字、红黑双色错版、木刻插图)、苏联构成主义(红黑两版、斜条与楔形、西里尔大字、网点照片拼贴)、装饰艺术 Art Deco(1930 年代喷枪流线型海报、交替射线、阶梯高楼、金色 Deco 字)、黄金时代漫画(毛笔墨线、Ben-Day 网点、四色错版、新闻纸)、波普丝网(多格撞色平涂 + 错位的照相黑版)、ASCII 字符画(行式打印机、绿条连续纸、叠打)、低多边形(1999 年代 3D:平面着色、仿射贴图、逐顶点雾、15 位色抖动)、喷漆模板涂鸦(混凝土墙上多层卡纸模板喷绘、雾化与滴痕)、刺绣徽章(牛仔布上的机绣徽章:填充绣、缎面绣、锁边)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古、拼豆、拼拼豆、熔珠、熨豆、豆豆画、钉板、烫豆、岩画、岩刻、凿刻、石刻、沙漠漆、史前壁刻、大角羊、古埃及、埃及壁画、墓室壁画、法老时代、象形文字、尼罗河、底比斯、罗马马赛克、马赛克镶嵌、镶嵌画、石子拼画、地砖画、古罗马地板、彩色玻璃、彩绘玻璃、花窗、玻璃花窗、教堂花窗、哥特花窗、铅条玻璃、泥金手抄本、手抄本、彩饰手抄本、中世纪手稿、羊皮纸、哥特体、花体首字母、泥金、贴金、星盘、达芬奇、达·芬奇、达芬奇手稿、手稿风、文艺复兴手稿、发明手稿、镜像字、镜像书写、扑翼机、红粉笔、钢笔排线、机械草图、分解图、剪影、剪影肖像、侧影、侧面像、黑纸剪影、剪影小像、椭圆金框、乔治时代肖像、摄政时期肖像、凸版印刷、活版印刷、木活字、铅字海报、马戏团海报、复古海报、老海报、19 世纪海报、双色套印、错版、套色错位、木刻插图、构成主义、苏联海报、苏联构成主义、俄国先锋派、罗德琴科风、红黑海报、照片蒙太奇、照片拼贴海报、西里尔字、装饰艺术、装饰风、流线型、流线型海报、1930 年代海报、旅行海报、铁路海报、火车海报、喷枪画、喷笔画、阶梯高楼、射线背景、盖茨比风、黄金时代漫画、老漫画、复古漫画、美漫封面、漫画封面、Ben-Day 网点、本戴点、网点上色、四色印刷、四色错版、新闻纸、对白框、拟声字、1940 年代漫画、波普、波普艺术、波普丝网、沃霍尔风、丝网版画头像、撞色头像、多格重复头像、六宫格撞色头像、ASCII、字符画、字符艺术、文字画、行式打印机、绿条纸、连续打印纸、针孔打印纸、老电脑打印、叠打、低多边形、低面数、低模、多边形风、千禧年 3D、90 年代 3D、复古 3D 游戏、老游戏截图、PS1 风、N64 风、平面着色、线框、游戏 HUD、飞行游戏、穿环、喷漆、模板涂鸦、镂空模板、喷漆模板、模板喷绘、街头涂鸦、街头艺术、墙绘、滴漆、班克西风格、刺绣徽章、徽章、布章、臂章、刺绣贴、绣标、锁边、牛仔外套徽章、户外徽章、营地徽章、弧形条章),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun / perler beads / hama beads / artkal / fuse beads / melty beads / pegboard beads / petroglyph / rock art / rock carving / desert varnish / Egyptian tomb painting / ancient Egypt / hieroglyphs / Theban tomb / Roman mosaic / floor mosaic / tesserae / opus vermiculatum / Pompeii mosaic / stained glass / leaded glass / church window / Gothic window / grisaille / illuminated manuscript / medieval manuscript / book of hours / gold leaf / illuminated initial / blackletter / vellum / astrolabe / da Vinci notebook / Leonardo codex / Renaissance sketchbook / mirror writing / iron-gall ink / red chalk / sanguine / ornithopter / exploded view / inventor's sketch / silhouette / silhouette portrait / cut-paper profile / shade portrait / Georgian portrait / Regency portrait / oval gilt frame / letterpress / wood type / playbill / circus poster / Victorian poster / two-colour misregistration / woodcut poster / constructivism / constructivist poster / Soviet avant-garde / Russian avant-garde / Rodchenko style / photomontage poster / art deco / streamline moderne / 1930s travel poster / railway poster / airbrush poster / sunburst rays / Gatsby style / golden age comic / vintage comic book / comic cover / Ben-Day dots / four-color printing / newsprint / speech balloon / pulp cover / pop art / Warhol-style / pop silkscreen / silkscreen portrait / repeated pop portrait grid / ASCII art / text art / typewriter art / line printer / greenbar / fanfold paper / tractor feed / overstrike / printer plot / low poly / low-poly / retro 3D / 90s 3D game / PS1 style / N64 style / software rasterizer / flat shading / affine texture mapping / vertex fog / game HUD / stencil / stencil graffiti / spray paint stencil / street art / drips and overspray / Banksy-style stencil / embroidered patch / embroidery patch / iron-on patch / sew-on patch / merit badge / camp badge / merrow border / rocker patch / denim jacket patches without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。单独说「剪纸」指剪纸拼贴、「刺绣」指十字绣、「丝网印刷 / screen print」指包豪斯几何;「打马赛克」是打码,不是马赛克画风。+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置五十八种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)、拼豆(钉板上的熔珠小管、熨烫熔合)、岩画(沙漠漆上凿出的凹坑图形、新旧凿痕、剥落)、古埃及墓室壁画(灰泥墙、红格起稿、分栏叙事、象形文字、剥落)、罗马马赛克(石子与玻璃沿轮廓一排排铺、灰缝、燕尾铭牌)、彩色玻璃花窗(哥特尖拱窗、通体着色玻璃、grisaille 彩绘与银染、铅条、透光)、泥金手抄本(羊皮纸、鹅毛笔哥特体、朱红标题、打磨金箔首字母)、达·芬奇手稿(铁胆墨水、左手排线、红粉笔、镜像手写、机械分解图)、剪影(黑纸剪出的侧影小像、薄金粉、椭圆金框)、凸版印刷海报(木活字、红黑双色错版、木刻插图)、苏联构成主义(红黑两版、斜条与楔形、西里尔大字、网点照片拼贴)、装饰艺术 Art Deco(1930 年代喷枪流线型海报、交替射线、阶梯高楼、金色 Deco 字)、黄金时代漫画(毛笔墨线、Ben-Day 网点、四色错版、新闻纸)、波普丝网(多格撞色平涂 + 错位的照相黑版)、ASCII 字符画(行式打印机、绿条连续纸、叠打)、低多边形(1999 年代 3D:平面着色、仿射贴图、逐顶点雾、15 位色抖动)、喷漆模板涂鸦(混凝土墙上多层卡纸模板喷绘、雾化与滴痕)、刺绣徽章(牛仔布上的机绣徽章:填充绣、缎面绣、锁边)、蓝图工程图(描图墨线晒成蓝底白线)、儿童蜡笔画(小孩在糙纸上的蜡笔涂抹)、绿屏终端 CRT(荧光字符画、扫描线、余辉)、热成像(先画温度场再上伪彩色)、代尔夫特蓝瓷砖(锡釉砖上的钴蓝手绘)、洞穴壁画(火光下的赭石、吹喷手印)、1-bit 早期画图软件(黑白整屏、8×8 图案填充)、古希腊黑绘陶瓶(黑釉剪影、刻线、饰带展开图)、铅笔素描(石墨排线、擦笔、边缘只剩线稿)、X 光片(安检透视、轮廓发亮、伪彩)、1930 年代黑白橡皮管动画(白手套、饼切眼、老胶片)、黑白麻胶版画(刻刀减法、手拓发花、套色错版)、VHS 家庭录像(钨丝灯偏色、色度渗色、REC)、扁平矢量(分层几何色块、七色、层间投影)、绘本角色动画(小角色挤压拉伸的真动画)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古、拼豆、拼拼豆、熔珠、熨豆、豆豆画、钉板、烫豆、岩画、岩刻、凿刻、石刻、沙漠漆、史前壁刻、大角羊、古埃及、埃及壁画、墓室壁画、法老时代、象形文字、尼罗河、底比斯、罗马马赛克、马赛克镶嵌、镶嵌画、石子拼画、地砖画、古罗马地板、彩色玻璃、彩绘玻璃、花窗、玻璃花窗、教堂花窗、哥特花窗、铅条玻璃、泥金手抄本、手抄本、彩饰手抄本、中世纪手稿、羊皮纸、哥特体、花体首字母、泥金、贴金、星盘、达芬奇、达·芬奇、达芬奇手稿、手稿风、文艺复兴手稿、发明手稿、镜像字、镜像书写、扑翼机、红粉笔、钢笔排线、机械草图、分解图、剪影、剪影肖像、侧影、侧面像、黑纸剪影、剪影小像、椭圆金框、乔治时代肖像、摄政时期肖像、凸版印刷、活版印刷、木活字、铅字海报、马戏团海报、复古海报、老海报、19 世纪海报、双色套印、错版、套色错位、木刻插图、构成主义、苏联海报、苏联构成主义、俄国先锋派、罗德琴科风、红黑海报、照片蒙太奇、照片拼贴海报、西里尔字、装饰艺术、装饰风、流线型、流线型海报、1930 年代海报、旅行海报、铁路海报、火车海报、喷枪画、喷笔画、阶梯高楼、射线背景、盖茨比风、黄金时代漫画、老漫画、复古漫画、美漫封面、漫画封面、Ben-Day 网点、本戴点、网点上色、四色印刷、四色错版、新闻纸、对白框、拟声字、1940 年代漫画、波普、波普艺术、波普丝网、沃霍尔风、丝网版画头像、撞色头像、多格重复头像、六宫格撞色头像、ASCII、字符画、字符艺术、文字画、行式打印机、绿条纸、连续打印纸、针孔打印纸、老电脑打印、叠打、低多边形、低面数、低模、多边形风、千禧年 3D、90 年代 3D、复古 3D 游戏、老游戏截图、PS1 风、N64 风、平面着色、线框、游戏 HUD、飞行游戏、穿环、喷漆、模板涂鸦、镂空模板、喷漆模板、模板喷绘、街头涂鸦、街头艺术、墙绘、滴漆、班克西风格、刺绣徽章、徽章、布章、臂章、刺绣贴、绣标、锁边、牛仔外套徽章、户外徽章、营地徽章、弧形条章、蓝图、工程图、施工图、蜡笔画、儿童画、绿屏终端、CRT、显像管、热成像、热像仪、温度图、代尔夫特、荷兰蓝瓷砖、洞穴壁画、史前壁画、赭石、1-bit、黑白画图软件、MacPaint 风、黑绘、古希腊陶瓶、希腊瓶画、铅笔素描、素描、铅笔画、X 光、X 光片、安检图像、橡皮管动画、黑白卡通、老动画、麻胶版画、黑白版画、藏书票、VHS、家庭录像、录像带、扁平插画、扁平风、矢量插画、绘本动画、角色动画、挤压拉伸),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun / perler beads / hama beads / artkal / fuse beads / melty beads / pegboard beads / petroglyph / rock art / rock carving / desert varnish / Egyptian tomb painting / ancient Egypt / hieroglyphs / Theban tomb / Roman mosaic / floor mosaic / tesserae / opus vermiculatum / Pompeii mosaic / stained glass / leaded glass / church window / Gothic window / grisaille / illuminated manuscript / medieval manuscript / book of hours / gold leaf / illuminated initial / blackletter / vellum / astrolabe / da Vinci notebook / Leonardo codex / Renaissance sketchbook / mirror writing / iron-gall ink / red chalk / sanguine / ornithopter / exploded view / inventor's sketch / silhouette / silhouette portrait / cut-paper profile / shade portrait / Georgian portrait / Regency portrait / oval gilt frame / letterpress / wood type / playbill / circus poster / Victorian poster / two-colour misregistration / woodcut poster / constructivism / constructivist poster / Soviet avant-garde / Russian avant-garde / Rodchenko style / photomontage poster / art deco / streamline moderne / 1930s travel poster / railway poster / airbrush poster / sunburst rays / Gatsby style / golden age comic / vintage comic book / comic cover / Ben-Day dots / four-color printing / newsprint / speech balloon / pulp cover / pop art / Warhol-style / pop silkscreen / silkscreen portrait / repeated pop portrait grid / ASCII art / text art / typewriter art / line printer / greenbar / fanfold paper / tractor feed / overstrike / printer plot / low poly / low-poly / retro 3D / 90s 3D game / PS1 style / N64 style / software rasterizer / flat shading / affine texture mapping / vertex fog / game HUD / stencil / stencil graffiti / spray paint stencil / street art / drips and overspray / Banksy-style stencil / embroidered patch / embroidery patch / iron-on patch / sew-on patch / merit badge / camp badge / merrow border / rocker patch / denim jacket patches / blueprint / technical drawing / crayon / kid's drawing / CRT terminal / green screen / thermal camera / thermal imaging / Delft tiles / Delft blue / cave painting / ochre / Lascaux-style / 1-bit / MacPaint-style / black-figure / Greek vase / pencil drawing / graphite / X-ray / baggage scanner / rubber hose / 1930s cartoon / linocut / lino print / VHS / home video / flat vector / flat illustration / storybook animation / squash and stretch without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。单独说「剪纸」指剪纸拼贴、「刺绣」指十字绣、「丝网印刷 / screen print」指包豪斯几何;「打马赛克」是打码,不是马赛克画风;单说「蓝图」指蓝图工程图,「蓝晒 / 晒图」仍指蓝晒;「铅笔 / 素描」指铅笔素描,「彩铅」指韩国彩铅;「像素」仍指像素风,「1-bit / 黑白画图软件」指 1-bit 早期画图软件;「霓虹」仍指赛博朋克。---# Claude 绘图@@ -57,6 +57,21 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型| 低多边形(1999 年代 3D) | `lib/lowpoly.py` · `LowPoly` | `examples/lowpoly_canyon.py` 峡谷飞行 · Canyon Run(一帧虚构的 1999 年飞行游戏:小特技飞机在沙漠峡谷的右弯处压坡度,对准九个金环里的第五个,第六个挂在天然石拱下;阶梯状分层岩壁、起伏小面的河、十字插片杜松、雾里化开的方山;半透明螺旋桨盘、金环闪光、镜头光晕;384×216 帧缓冲、15 位色 4×4 有序抖动、无平滑放大 5 倍;HUD:金环计数 04/09、单圈时间、阶梯速度条、赛道小地图) | 约 0.2 秒 || 喷漆模板涂鸦 | `lib/stencil.py` · `Stencil` | `examples/stencil_kite.py` 放风筝 · Hold On(木纹模板清水混凝土墙:木纹、浆棱、对拉螺栓孔、锈水雨痕、返潮泛碱、发丝裂缝;三张卡纸模板白 → 灰 → 黑喷出的小孩:毛线帽、羽绒服、往前飘的条纹围巾,身子后仰攥着线轮;徒手喷的风筝线连到左上角的红色菱形风筝;同一张小模板转着角度喷的燕子和树叶;带桥的 HOLD ON 模板字;清晰核心、外溢雾化、飞沫、滴痕;滚筒灰漆盖掉的旧签名、被水枪冲淡的粉色签名) | 约 6 秒 || 刺绣徽章 | `lib/patch.py` · `Patch` | `examples/patch_camping.py` 三晚露营(牛仔夹克后背,过肩缝压着双道明线,一晚一枚徽章:第一晚是热切缎面边的拱形异形章——日落分层天空、远山、湖面倒影、亮灯的帐篷;第二晚是金色锁边圆章——雪峰、松林、营火与火星、弯月,缎面字 HIGH CAMP / NIGHT 2,上方弧形条章 THREE NIGHTS OUT;第三晚是正在手缝的指南针章,针和线还留在牛仔布上;一条刺子绣虚线把三枚徽章串成路线) | 约 6 秒 |+| 蓝图工程图 | `lib/blueprint.py` · `Blueprint` | `examples/blueprint_lighthouse.py` 灯塔剖面 · Halvard Rock Light(1911 年一套灯塔施工图,描图布上墨后晒成蓝图:南立面的花岗岩砌层和背光一侧的明暗线;A–A 剖面里越往上越薄的石墙、绕空心中柱盘上去的悬挑石阶、值守室的钟表机构;+6.50 平面和指北针;详图 1 讲灯焰、棱镜和透镜怎样送出一束平行光;总说明、比例尺、修改栏、中英文标题栏;折成六折、朝外那格褪色、碱性水渍、图钉孔,工地工程师用红蜡笔圈出楼梯批注) | 约 5 秒 |+| 儿童蜡笔画 | `lib/crayon.py` · `Crayon` | `examples/crayon_picnic.py` 我的周末(六岁小孩在糙纸上用蜡笔画的一家人野餐:戴墨镜的笑脸太阳、四种颜色写的歪扭标题「我的周末!」、风筝和彩虹,天空绕着东西涂、越往下越稀;冒卷烟的小房子和苹果树;爸爸、妈妈和我手拉手站在红格子野餐布后面,小狗扑向皮球;郁金香、蝴蝶和签名「朵朵 6岁」;纸上还躺着一根用秃的红蜡笔、一截断了的蓝蜡笔和蜡屑) | 约 8 秒 |+| 绿屏终端 CRT(荧光字符画) | `lib/crt.py` · `CRTTerminal` | `examples/crt_weather.py` 今天带伞吗 · Bring an Umbrella?(80 年代米色机壳的视频终端上敲了一条 forecast 命令,回来一屏绿色 P1 荧光字符画:一整天从左到右画成一条——清晨的太阳、积云、14:00–17:30 在小镇上下雨的雷暴云(闪电、带余辉的雨丝)、雨后碎云、夜里的月牙和灯塔光;下面同一条时间轴上的扫描线气温曲线、八分块雨量柱和反白的「umbrella? YES」;双倍高标题、方框线、烧着旧字的状态栏;扫描线、光晕、桶形畸变,机壳斜面映着绿光) | 约 7 秒 |+| 热成像 | `lib/thermal.py` · `Thermal` | `examples/thermal_kitchen.py` 厨房里的温度 · Kitchen Heat Map(晚饭时分厨房的热像仪画面:汤锅的蒸汽卷进抽油烟机,抛光锅盖因发射率低读数低一档;水壶喷出一道蒸汽;烤箱门封漏热,把手上的湿抹布比室温还凉;刚出炉的面包冒热气;冰箱门没关,冷气顺着抽屉淌到地砖上铺成冷舌;猫踩过冷坑又回到暖砖上,留下一串越早越淡的暖脚印;点测温、区域框、沿脚印的线剖面,读数全从画面上读出来;480×270 传感器、噪声与竖条纹、铁红色板) | 约 2 秒 |+| 代尔夫特蓝瓷砖 | `lib/delft.py` · `DelftTile` | `examples/delft_canal.py` 运河小镇 · 一阵风 De Windvlaag(一面锡釉砖墙:中间 11 × 7 块砖连成一幅砖画,四周是四角带角饰、圆框里画小图的单块砖。一阵西风吹过运河小镇:风车在转,平底帆船顺风驶来,烟、床单和衬衫都往右扬,郁金香一齐弯腰,一个人的帽子被吹到河面上,小狗腾空扑过去;藤蔓边框和卷轴题字 DE WINDVLAAG;每块砖单独画、单独烧,线条在砖缝处错开;开片、铁斑、崩瓷,云上一块窗户倒影在砖缝处断开错位) | 约 6 秒 |+| 洞穴壁画(赭石颜料) | `lib/cave.py` · `CavePainting` | `examples/cave_hunt.py` 篝火旁的岩洞(只靠篝火和石油灯照亮的石灰岩洞壁讲一次狩猎:野牛画在岩壁天然的鼓包上,背插两支矛,转身对着两个红色猎人;马、雄鹿和母鹿往反方向跑,上方一匹只起了炭稿的马;火堆上方四只吹喷手印,墙脚一排掌印红点;地上放着三堆研磨赭石和炭条的石板、一根吹颜料的骨管;钟乳石帘、钙华薄膜、零星掉色、熊爪抓痕、熏黑的顶壁) | 约 7 秒 |+| 1-bit 早期画图软件 | `lib/macpaint.py` · `MacPaint` | `examples/macpaint_garden.py` 窗台花园 · Windowsill Garden(一台 1984 年式黑白画图软件的整屏:菜单栏、工具栏、图案板、条纹标题栏窗口;画布上一扇窗,格子布窗帘画好左边再翻转复制出右边,窗外是图案分带的天空和山坡小屋;窗台上种子袋和三盆向日葵讲 40 天:发芽、长叶、开花,喷壶还对着第 2 天那盆滴水;黑猫盯着一只被选框行军蚁框住的白蝴蝶;Shadow 样式标题 watch it grow!;全画只有黑白两值,色调全靠 8×8 图案) | 约 0.4 秒 |+| 古希腊黑绘陶瓶 | `lib/blackfigure.py` · `BlackFigure` | `examples/blackfigure_games.py` 赛跑与赛车 · Games on a Vase(博物馆展台上一只阿提卡黑绘颈柄双耳瓶,旁边展板把两圈饰带展开成平面:上圈四马战车赛,正面是领先的两辆,转到瓶背才看得见折返柱、落后的第三辆、奖品三足鼎和裁判;下圈短跑,背面是终点柱和摆着奖品的桌子;棕榈叶莲花链、舌纹、回纹、放射纹、古希腊字母题字;赤陶橙底、黑釉剪影、刻线、加红加白,黑釉上一条柔光箱反光;加白剥落、钙质结壳、缺口和修补) | 约 7 秒 |+| 铅笔素描 | `lib/graphite.py` · `Graphite` | `examples/graphite_bicycle.py` 老街角的自行车 · The Bread Run(素描纸上的石墨写生:女式城市自行车靠在老街转角的灰泥墙上,前筐里一根法棍和一束纸包的郁金香;阴影里的侧墙挂着只画了面包的铁艺招牌,左边一扇深门洞,麻雀在啄面包屑;起形辅助线、轮廓、侧锋铺调、分层排线、纸擦笔、橡皮提亮一步步做完;只有中间画完,越往纸边越只剩线稿;页边铅笔笔记、2H–8B 试笔色阶和一枚石墨指纹) | 约 11 秒 |+| X 光片 | `lib/xray.py` · `XRay` | `examples/xray_luggage.py` 行李安检 · Security Check(双能 X 光安检机俯视图:传送带上的硬壳拉杆箱,箱壳轮廓发亮、铝拉杆是两层套管;箱里一把折叠伞、一个旅行吹风机(电机、双重螺旋电热丝)、一台仰面躺着的相机、钥匙和硬币、叠好的衣服、一瓶水,还有一副脊柱里穿着钢销的石膏恐龙骨架玩具;侧栏是同一只包的材料伪彩视图和 1 号物体放大,操作员结论:1 是玩具放行,2 超过 100 ml 要取出;Zeff 和毫升数都是从画面上量出来的) | 约 2 秒 |+| 1930 年代黑白橡皮管动画 | `lib/rubberhose.py` · `RubberHose` | `examples/rubberhose_morning.py` 早晨的闹钟(7 点整的小卧室:双铃闹钟蹦上床头柜摇铃,一只鞋踮着脚,挥着白手套指着床,「RRRING!」在头顶蹦跳;戴条纹睡帽的枕头还在打呼,举起手套「再睡五分钟」;窗外的太阳在两座山之间打哈欠伸懒腰,阳光落在地毯上,一双拖鞋已经跳起舞;灰色水粉背景、描线上色的赛璐璐、饼切眼、橡皮管四肢,拍成老胶片:柔焦、颗粒、片门晃动、圆角片门、划痕、灰尘和片门里的一根头发) | 约 3 秒 |+| 黑白麻胶版画(linocut) | `lib/linocut.py` · `Linocut` | `examples/linocut_snowy_village.py` 雪夜归途 · Homeward, First Snow(两块版的麻胶版画:V 口刀刻出的风雪流线、刻出来的满月和断续光环、两缕炊烟;雪坡的黑色等高线、山脚积雪的云杉林、五座积雪木屋;一个人提着灯笼、拖着一雪橇劈柴走回家,脚印和雪橇辙从画外进来,那家的门敞着、暖光洒在雪上,小狗跑出来迎他;灯黄套色版只印亮窗、门前的光和灯笼,略微错版;实地发花、残刀印、压印,页边铅笔版次 7/30、题名、签名和一枚钢印) | 约 9 秒 |+| VHS 家庭录像 | `lib/vhs.py` · `VHSCamcorder` | `examples/vhs_birthday.py` 吹蜡烛 · Blow Out the Candles(一家人生日录像里的一帧:70 年代客厅的圆环墙纸、胡桃木护墙板、兔耳天线电视、牛油果绿丝绒沙发、长毛地毯;彩带、HAPPY BIRTHDAY 三角小旗、戴派对帽的泰迪熊;茶几上的蛋糕四根蜡烛刚吹灭冒着烟、两根还亮着,过生日的孩子戴着尖帽从背后凑近、离镜头太近而虚焦;白平衡停在「室外」拍钨丝灯、烛焰过曝和 CCD 竖向拖影、点阵 OSD;录像带的色度渗色、跟踪噪带、磁头切换噪声、掉磁白点) | 约 6 秒 |+| 扁平矢量 | `lib/flatvector.py` · `FlatVector` | `examples/flatvector_night_camp.py` 山间夜营(七色限定色板,无描边的大块几何形一层层叠起来,层与层之间一道柔和投影,加极细颗粒;夜蓝天空里一轮带橙色光芒的月亮,紫色雪山分出亮面和折线暗面,品红、橙色两种山丘带,黄沙地;下午插在山顶的小旗下,一条虚线小路走之字形下山、穿过山丘,尽头是戴头灯走最后一段路的小小背包客;营地已经亮了:橙色 A 字帐篷门口透出光,篝火的光在沙地上铺成一圈圈平涂光环;几何松树、圆冠树、两朵平底云、一颗流星) | 约 1 秒 |+| 绘本角色动画 | `lib/storybook.py` · `Storybook` | `examples/storybook_acorn.py` 小橡果的秋天(真动画 + 旅程总图:米色纸上,枝头打盹的小橡果被晃醒、拉长掉下、落地压扁再弹起,追着一片红橡叶滚下山坡,山坡、小花、远山随它经过一笔笔画出来;跳上漂在小河上的橡叶,撞岸后空翻上岸,钻进土里发芽长成一棵还戴着橡果帽的小橡树;最后「hello, little oak」按笔顺写出来,彩纸屑飞起。总图把六个关键姿态多次曝光在铅笔运动弧上;加 `--gif out.gif` 出 15 fps 的真动画) | 约 1 秒(总图)/ 约 3 秒(151 帧动图) |各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。@@ -103,7 +118,22 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型- 计算机史、老机房、复古科技、数据和日志、「当年的电脑怎么画画」、程序员 / 极客向的配图、讲解片里的「输出结果 / 运行日志 / 打印报告」页 → ASCII 字符画(行式打印机)(要屏幕上的低分辨率游戏感用像素风,要手写板书用黑板板书);- 游戏感、复古 3D、「90 年代末 / 千禧年」怀旧、飞行 / 赛车 / 闯关、带 HUD 的「关卡 / 进度 / 任务」页、讲解片里的「早期 3D 图形是怎么画出来的」(线框 → 平面着色 → 贴图 → 雾)→ 低多边形(要 2D 小尺寸游戏感用像素风,要柔和现代的 3D 渲染用柔光 3D,要正交微缩模型用等轴 2.5D);- 街头、城市、态度与幽默、一句短口号配一个小人物的海报、公益与社区宣传、「一个人 + 一件小事」的极简故事、讲解片的「观点 / 金句」页 → 喷漆模板涂鸦(要霓虹夜景用赛博朋克;要设计感的丝网海报用包豪斯几何;要剪报拼贴用报刊拼贴);-- 徽章、勋章、打卡 / 成就 / 里程碑、旅行与户外、社团与活动标志、讲解片里的「收集 / 解锁 / 第 N 关」页 → 刺绣徽章(要手作布艺的十字格子感用十字绣;要贴纸质感用贴纸拼贴)。+- 徽章、勋章、打卡 / 成就 / 里程碑、旅行与户外、社团与活动标志、讲解片里的「收集 / 解锁 / 第 N 关」页 → 刺绣徽章(要手作布艺的十字格子感用十字绣;要贴纸质感用贴纸拼贴);+- 工程、建筑、机械和设备的结构与原理(剖面、零件、尺寸、「里面是怎么造的 / 怎么动起来的」),产品或建筑的技术说明页,讲解片里的「结构 / 设计图 / 原理图 / 施工图」页 → 蓝图工程图(要植物和自然物的蓝色剪影用蓝晒;要发明构思和手绘草图感用达·芬奇手稿;要讲课推导用黑板板书);+- 童趣、家庭与亲子、「我的一天 / 我的家 / 我的周末 / 长大想当什么」这类孩子口吻的小故事、节日与生日贺卡、儿童教育和绘本感、讲解片里「用孩子的眼光看」的页 → 儿童蜡笔画(要精致柔和的成人手绘用韩国彩铅;要彩纸拼贴的童趣用剪纸拼贴;要成熟的卡通角色用卡通手绘);+- 终端、命令行、黑客 / 程序员向、老电脑屏幕、「敲一条命令得到结果」、复古版的数据面板,讲解片里的「查询 / 运行结果 / 系统状态」页 → 绿屏终端 CRT(荧光字符画)(要打印在纸上的日志和报表用 ASCII 字符画(行式打印机);要低分辨率的游戏画面用像素风;要 80 年代霓虹用复古 Synthwave);+- 温度、冷热、保温与漏热、散热、能耗,「看不见的东西」的可视化(热量、气流、体温、余温留下的痕迹),夜视 / 侦测 / 检测报告感,讲解片里的「数据告诉你哪里热、哪里漏」页 → 热成像(要霓虹夜景氛围用赛博朋克;要手写的实验数据与图表用实验笔记本;要复古仪表盘用复古仪器面板);+- 荷兰、运河、风车、郁金香、帆船与航海,老派欧洲家居(厨房、壁炉、瓷砖墙),蓝白两色的典雅装饰,一组图标式的小图(单块砖可以一砖一个主题),讲解片里的「传统工艺 / 历史 / 一组图标」页 → 代尔夫特蓝瓷砖(要石子和玻璃拼的古代地面画用罗马马赛克;要普鲁士蓝的日光晒图用蓝晒);+- 史前、人类起源、「最早的艺术 / 人类最早怎么画画」、狩猎与动物群、火与夜晚、讲解片里的「艺术的起源 / 远古的一个夜晚」页 → 洞穴壁画(赭石颜料)(要在日晒岩面上凿出来的符号用岩画;要分栏叙事、有文字的古文明壁画用古埃及墓室壁画);+- 复古电脑、「第一代图形界面 / 早期个人电脑」怀旧、黑白像素插画、软件和工具的「界面 / 操作步骤」图解、讲解片里的「当年的电脑怎么画画」页 → 1-bit 早期画图软件(要彩色的低分辨率游戏感用像素风;要打印纸上的字符画用 ASCII 字符画);+- 古希腊、古代奥运与体育比赛、「古人怎么比赛 / 劳动 / 过日子」,绕一圈又回到起点的事(跑道、循环、四季、流程),博物馆展品感、「一件器物 + 它的展开图」式的图解,讲解片里的「历史 / 起源 / 古代」页 → 古希腊黑绘陶瓶(要分栏的多彩墙画用古埃及墓室壁画;要石子铺成的地面画用罗马马赛克;要红黑两色的印刷海报用凸版印刷海报);+- 写实而安静的日常一角(街角、老物件、静物、交通工具)、旅行写生、怀旧、「先画个草图 / 观察细节」的构思页、讲解片里的「观察 / 写生 / 手稿」页、要黑白高级感又不要漫画感 → 铅笔素描(要彩色可爱的小物用韩国彩铅;要发明与机械原理的手稿用达·芬奇手稿;要讲课推导用黑板板书);+- 「里面有什么」「看穿」「拆开看结构」、透视 / 内部构造 / 原理图解(电器、工具、机械里面长什么样),安检、体检、检测、质检、排查问题,讲解片里的「真相 / 揭秘 / 一眼看穿」页 → X 光片(要手绘的机械分解图用达·芬奇手稿;要「拆开看看」的剪报拼贴用报刊拼贴;要冷热分布用热成像);+- 复古动画、老电影 / 默片 / 黑白卡通的感觉、拟人的日常物件又唱又跳、起床 / 闹钟 / 上班这类节奏感强的小场面、讲解片里的「很久以前 / 第一代动画 / 老片头」页 → 1930 年代黑白橡皮管动画(要彩色、蓝铅笔稿的现代手绘卡通用卡通手绘;要网点和对白框的漫画书用黄金时代漫画);+- 冬天、夜晚、乡村与小镇、民间故事和童话、节日贺卡和藏书票、「回家 / 守夜 / 一盏灯」这类温暖的小故事、要手作感又要强烈黑白对比的封面、讲解片里的「过去的冬夜 / 手工年代」页 → 黑白麻胶版画(要红黑两色的木活字海报用凸版印刷海报;要日式多色套印和晕色用浮世绘;要喷漆模板的街头感用喷漆模板涂鸦);+- 家庭回忆、怀旧、「当年的那一天」(生日、过年、毕业、第一次……)、童年和老房子、found footage 式的悬念开场、讲解片里的「回到 80 年代 / 那时候的家 / 老录像里的证据」页 → VHS 家庭录像(要霓虹落日的 80 年代复古未来用复古 Synthwave;要老照片和剪报用报刊拼贴;要屏幕上的字符用 ASCII 字符画);+- 风景、户外、旅行与露营、MG 动画式的场景背景和转场、讲解片的「场景 / 旅程 / 夜晚」页、要干净现代又有层次的插画 → 扁平矢量(要撕纸边和蜡笔的手作感用剪纸拼贴;要正等轴的微缩模型用等轴 2.5D;要 80 年代霓虹用复古 Synthwave);+- 要「真的动起来」的小故事、一个可爱小角色的旅程或成长(从 A 到 B、出发—遇到—到达)、讲解片的片头片尾和转场、品牌吉祥物小动画、「一路走一路画出来」的过程感 → 绘本角色动画(`Storybook.gif()` 出真动画,`journey()` 出一张旅程总图;只要一条轮廓的变形用形变动画;要逐帧抖线的静态卡通插画用卡通手绘)。每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。@@ -675,6 +705,240 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 手缝:`whip(blank, 颜色, frm, to)` 卷边针,按轮廓长度的比例缝一段,返回最后一针的位置;`thread(pts, 颜色, lift)` 散落的缝线(有捻度,抬起越高影子越远);`needle(eye, tip)` 躺在布上的钢针(先画线:线会从针眼里露出来)- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度+**蓝图工程图 `Blueprint`**:+- 思路:先在描图布上用几种固定粗细的鸭嘴笔上墨(轮廓、剖面线、尺寸、单笔画字全是「墨」),再像真的晒图那样接触曝光:有墨的地方挡住弧光灯,药面不变蓝,冲洗后是白线;其余地方生成普鲁士蓝。曝光 = 透光 × 灯的照度,显影按 S 曲线(有阈值)——粗线纯白、发丝线发浅蓝、底色饱和;线的边缘有爬光(压得紧的地方锐、接触不良的地方软)和一圈淡淡的光晕;灯在中间强、四周弱,药面有涂布条纹、斑驳和晾干时自上而下的流痕;颜色按普鲁士蓝在纸上的比尔–朗伯吸收计算,纸纤维透出来。晒好之后再过它的「一生」:折叠、褪色、手摸、水渍、图钉,最后工地上的人拿红蜡笔批注+- 构造:`Blueprint(W, H, seed, ss=3, tracing=(x0, y0, x1, y1))`;`expose(time, contact)`:曝光时间(0.8 欠曝发浅、1.3 过曝)和压框接触不均的程度+- 笔:`line(pts, pen, closed)`,pen 为 `'heavy' 'thick' 'medium' 'thin' 'fine'` 或像素宽,线头有一点积墨;`dashed(pts, pen, dash)` 虚线;`centerline(pts)` 点划线;`circle`、`arc`、`box`;`fill(pts)` 涂实(薄金属剖面、箭头、比例尺黑格);`dot`;`erase(pts)` 用刀片刮掉墨;`pencil(pts)` 留在描图布上的铅笔线(晒出来是很淡的浅线);`Blueprint.arc_pts(...)` 取弧线点(角度逆时针、纸面 y 向上)+- 剖面线:`hatch(polys, angle, spacing, pen, holes, kind)`,kind 为 `'lines'` 石材 / 通用、`'cross'` 金属、`'glass'` 三短线玻璃、`'rock'` 岩石裂纹、`'stipple'` 混凝土点、`'solid'` 涂实;`ground(pts)` 自然地面线加短斜线组;`breakline(p0, p1)` 折断线+- 字:`text(s, x, y, size, anchor, pen, slant, spacing, rot, guide, clear)` 内置单笔画大写字体(字模板样式:A–Z、0–9、Ø ± ° × ℄ ✓ → 等),size 是大写字高,anchor 如 `'ls' 'mm' 'rs'`(s = 基线),slant 约 0.22 是斜体字,guide=True 留下铅笔导线,clear=True 先刮掉字后面的剖面线,`\n` 换行;`text_width(s, size)`;`cjk(s, x, y, size, anchor, condense)` 中文长仿宋(压窄,找 STFangsong / FangSong,找不到用中文字体,可用 `INKPAINT_FONT_FANGSONG` 指定)+- 制图符号:`dim(p0, p1, offset, text, size, arrows, scale, fmt, text_off, shift, clear)` 尺寸(尺寸界线、箭头、数字顺着尺寸线写,短尺寸自动把箭头放到外面;offset=0 时不画界线,可以自己画链式尺寸);`level(x, y, text, side, length, mark_at)` 标高符号;`leader(pts, text, end='arrow'|'dot'|None)` 引出线;`cut_mark(p0, p1, label, view)` 剖切符号;`bubble(x, y, r, top, bottom)` 详图索引圈;`view_title(x, y, title, sub, size, bubble)` 图名(粗细双下划线 + 比例);`north(x, y, r)` 指北针;`scale_bar(x, y, px_per_unit, units, label)` 比例尺;`border(x0, y0, x1, y1, zones)` 图框和分区编号;`table(x0, y0, widths, heights)` 标题栏 / 修改栏,返回每格坐标 `[行][列]`;`revision(x, y, mark)` 修改三角+- 图纸的一生(只作用在晒好的图上):`fold(xs, ys, wear)` 折成档案尺寸(折痕处药面裂白、两侧一明一暗、交叉处磨损);`fade(x0, y0, x1, y1, amount)` 朝外那一格褪色;`grime(...)` 手摸发灰;`stain(x, y, r)` 碱性水渍(蓝变锈褐、两道潮线);`tack(x, y)` 图钉孔与锈圈;`tear(x, y, direction, length)` 折痕碰到纸边处的小裂口+- 红蜡笔:`red(pts, width)`、`cloud(pts, bump)` 修改云线、`red_text(s, x, y, size, rot)` 手写批注;红色是全图唯一不属于晒图本身的颜色+- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**儿童蜡笔画 `Crayon`**:+- 思路:糙纸是一张纸纹高度图,均衡成 [0, 1] 的均匀分布,所以「1 − 阈值」就是蜡能挂上的纸面比例;蜡只挂在纸纹凸起上:`纸纹 + 0.35 × 已有的蜡 > 1 − 接触 × 压力` 才上蜡,轻涂露出一片白点,重涂压进凹处,后涂的颜色更容易挂在先涂的蜡上(蜡层堆积)。蜡笔沿笔道被拖着走,所以露白的小坑被拉成顺着笔道的短条。用秃的笔头是一个带棱的平面:一笔 = K(≈ 宽 / 3)条强弱不一的平行细线,笔道里有白色细纹。颜色是半透明的乘性混合:`新 = lerp(底, 颜色 × 底^0.6, 覆盖)`,黄上涂蓝变绿、黑线涂不掉、同色重复越涂越深。最后纸纹和蜡层一起当高度图,左上低角度光打光,厚蜡处有一点蜡光+- 构造:`Crayon(W, H, seed, paper='#f7f3e9')`;`paper(tone, grain, fibres, scan)` 糙纸(纸纹、纸浆纤维、不匀的扫描光);颜色常量 `c.C`(24 色蜡笔盒:red orange yellow yellowgreen green darkgreen sky blue navy violet purple pink magenta brown tan peach apricot black grey white …)+- 小孩的手画的形状(返回点列):`circle(cx, cy, rx, ry, rot, lumpy)`、`rect(x0, y0, x1, y1, skew)`(四个角各歪一点)、`poly(pts)`、`wobble(pts, amp)`;遮罩:`mask(pts)`、`stroke_mask(pts, width)`、`grow(mask, px)`、`drawn()`(纸上已经画了的地方)+- 涂色:+ - `scribble(mask, 颜色, angle, width, density, pressure, reach, mess, angle_jitter, avoid, halo, fade)`:来回涂。reach 是胳膊够得着的长度,大片按块涂、每块各自的角度(None = 一块);density 低时两道之间留三角形白缝;mess 是在轮廓处的过冲 / 没涂到;avoid + halo 绕着涂、留一圈白(绕开处转折小心,不进比 0.7 × 笔宽窄的缝);fade=(y 满, y 无) 越往下越稀(涂烦了的天空);+ - `loops(mask, 颜色, r, width, density)`:一圈圈的绕圈涂(树冠、太阳、皮球、斑点);+ - `follow(pts, 颜色, width, passes, crayon)`:顺着一条带子涂(彩虹的每一道、路);+ - `burnish(mask, strength)`:使劲压着涂:已有的蜡压进纸坑,白点合上,颜色变深发亮+- 线和点:`line(pts, 颜色, width, pressure, closed, avoid)` 一根蜡笔线,落笔重、收笔轻;closed=True 时尾巴越过起点、差几像素对不上;avoid 让线停在东西背后;`dab(x, y, r, 颜色)` 拧进纸里的实心点(眼睛、苹果、西瓜籽)+- 写字:`write(s, x, y, size, 颜色或颜色列表, width, tilt, jumble, spacing, anchor)`:细字体字形细化成中心线,再用圆头蜡笔描;每个字各自歪 ±tilt°、大小和基线乱跳 jumble、按列表轮换颜色。字体按 STHeiti Light / Hiragino Sans GB / Noto Sans CJK Light / 微软雅黑 Light 找,可用 `INKPAINT_FONT_CRAYON` 指定+- 纸上的东西:`crumbs(x0, y0, x1, y1, colours, n)` 蹭下来的蜡屑(凸起、带小影子);`stick(x, y, angle, 颜色, length=360, radius=22, tip='worn'|'new'|'broken', wrap, peel, label)` 一根真蜡笔(哑光蜡、印花包装纸、伪文字标签、断口、撕掉的纸),合成时画、带柔和投影+- 顺序:先勾线(东西的内部遮罩收进一个 OBJ),再涂大片并绕开 `U(OBJ, drawn())`,最后在白纸上给东西上色;字和签名写在涂天空 / 草地之前+- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度;底层 `deposit(cover, box, 颜色)` 把任意接触场按纸纹上蜡++**绿屏终端 CRT(荧光字符画) `CRTTerminal`**:+- 思路:重做一台字符终端,不在屏幕上「画图」:+ - 屏幕上的一切都是字符内存里的字:每格带亮度属性(dim / normal / bold)、反白、下划线,行可以是双倍宽或双倍高;+ - 字库 ROM 是 7×10 点阵格里的 5×7 字,小写字母带两行下伸部;另有一套图形字符:框线 ─│┌┐└┘├┤┬┴┼、画曲线用的五档扫描线横条 ⎺⎻─⎼⎽(`SCAN`)、八分块 ▁▂▃▄▅▆▇█(`EIGHTHS`)、░▒▓、° ·、▲▼◆、箭头;+ - 字符画先画进一张隐藏的「材质 + 调子」图(每格 7×10 个采样),`compose()` 逐格选字:里面的格子按材质的阶梯和调子选字,同组之内做误差扩散;剪影穿过的格子按边的方向和位置选 _ . - ' / \ ( ) |;笔画格子按笔画方向选字。屏幕上「密 = 亮」:暗的东西要稀、要 dim;+ - 电子束每行字扫 10 条扫描线:点拉伸半个点,视频放大器有拖尾,光斑随电流变粗(bold 时扫描线之间的缝被填满);+ - P1 荧光粉亮到饱和时发白;之后依次是余辉、烧屏、桶形畸变、边缘变暗、玻璃里的光晕,以及房间的倒影+- 构造:`CRTTerminal(W, H, seed, cols=120, rows=36, phosphor='green'|'amber'|'white', opening=(88, 60, 1832, 958), radius=62, raster=(0.955, 0.93), curve=0.065)`;opening 是机壳开口,raster 是未畸变的光栅占开口的比例,curve 是桶形强度;`cw`、`ch` 是一格的像素宽高+- 字符内存:`write(col, row, s, attr)`,attr 取 `'dim'`、`'normal'` 或 `'bold'`,可加 `'+rev'` 反白、`'+ul'` 下划线;`big(col, row, s)` 双倍高双倍宽,占 row 和 row+1 两行(这两行只能放大字,每个字占两列);`wide()` 双倍宽;`box(c0, r0, c1, r1, attr, title)`、`hline()`、`vline()`;`cursor(col, row, 'block'|'ul')`;`clear()`;`listing(path)` 存成纯文本+- 字符画(隐藏图):+ - `material(name, ramp, attrs, outline, group, edge, dither)`:ramp 从暗到亮,如 `' .:+*%#@'`;attrs 每档一个亮度,提亮优先靠它,不靠更花的字;outline 取 `'cloud'`(斜坡一律 ( ))、`'round'`、`'straight'` 或 `None`(只按调子,不描边);group 相同的材质之间不描边;edge 固定轮廓字的亮度+ - 形状:`circle(col, row, r)`(r 按列数,自动按格子比例变圆)、`ellipse()`、`poly()`、`shape()`(平滑闭合)、`rect()`;调子:`sphere_tone()`、`radial_tone()`、`ramp_tone()`+ - 作画:`fill(mask, 材质, tone)`、`erase(mask)`、`stroke(点列, 材质, width, glyph)`;`puffs([(col, row, r), ...], 材质, light, amb, base, flat, base_dark)` 一朵云,base 用整数行,平底打成一根 _+ - `compose(region)` 选字,`reveal(r0, r1)` 把选好的字一段段放进屏幕;`put(col, row, s, attr)`、`sprite(col, row, 行列表, attr, attrs, swap)` 手摆的小件(星、雨、房子、灯塔、开灯的窗),sprite 行内的空格不透明+- 图表:`plot(col, row, w, h, xs, ys, xlim, ylim, attr)` 每列一个扫描线横条、每行 5 档高度,返回 `at(x, y)` 把数据坐标换成格子坐标,方便标注;`bars(col, row, h, values, vmax, attr)` 八分块柱+- 显像管:`trail(col, row, s, level)` 余辉(前一帧约 0.32、再前一帧约 0.10);`burn(col, row, s, depth)` 烧屏,放在反白条的空白处最好认;`tear(row, dx, lines)` 行同步错位;`power(on)` 关机时只剩玻璃和倒影;`brightness` 光栅底亮+- 动图阶段:关机 → 开机光栅 → 敲命令 → 标题 → 字符画一段段出来 → 曲线 → 柱和轴 → 结论;`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度+- 常量 `LEVELS PHOSPHORS SCAN EIGHTHS PUTTY ROM_CHARS`++**热成像 `Thermal`**:+- 思路:热像仪看不见颜色和光,只看见每个表面有多热,所以不画 RGB,分三步:先画一张温度场(°C,传感器分辨率的 2 倍);再让它经过一台非制冷热像仪(镜头模糊、按像元采样、噪声和竖条纹、中心偏凉、细节增强、自动增益);最后用伪彩色板上色,叠清晰的 OSD。坐标都用画布像素,温度用摄氏度+- 构造:`Thermal(W, H, sensor=(640, 360), ss=2, seed, ambient=21)`;sensor 越小越有热像仪的糊,范例用 480×270+- 形状 → 遮罩:`poly(pts)`、`shape(pts)` 闭合样条、`rect(x0, y0, x1, y1, r)`、`ellipse(cx, cy, rx, ry, rot)`、`blob()`、`line(pts, width)`;用 `*`、`1 - m`、`np.clip(a + b, 0, 1)` 组合+- 温度场:`ramp(p0, t0, p1, t1, ease)` 线性渐变、`radial(cx, cy, rx, ry, t0, t1, power)`、`texture(scale, seed)` 噪声;`room(top, bottom, y_top, y_bottom)` 背景空气分层(上暖下凉)+- 物体:`surface(mask, temp, emissivity, reflected, grain, soft, fuzz, limb, limb_px)`:temp 可以是数或 ramp / radial 场;emissivity < 1 的抛光金属读数被拉向反射温度(默认室温);grain 材料不匀(°C);fuzz 毛边;limb 圆形物体在轮廓处变凉。`warm(mask, dT)` 加减热;`seam(pts, dT, width)` 门缝、砖缝、折线+- 热往外走:+ - `soak(mask, temp, reach, strength, onto)`:热晕渗进周围表面(先 soak 再画物体本身,onto 限定承受的表面)+ - `plume(path, temp, w0, w1, opacity, cool, eddy, wisp, puffs, seed, fade_out)`:沿路径的热气 / 蒸汽 / 冷气,越走越宽、越凉、越碎;temp 低于室温就是冷气(路径朝下);`rise(x, y, height, sway, lean)` 生成一条往上飘的路径+ - `pool(x, y, temp, reach, spread, tongues, squash, width)`:落到地上铺开的冷(暖)气舌,spread 是地面上的方向范围(0 = 向右,90 = 朝镜头)+ - `prints(steps, temp, size, squash, spread)`:余温脚印,steps = [(x, y, 朝向°, 比例, 年龄 0 新 .. 1 没了)],越旧越淡越散;`paw()` 单个爪印遮罩+ - `reflect(region, axis_y, strength, blur_px, fade)`:釉面地砖倒映上方更热的东西+- 相机:`camera(palette, span, agc, plateau, curve, netd, fpn, optics, dde, dde_clip, narcissus, pixel, saturate)`+ - palette:iron / rainbow / white_hot / black_hot / arctic;span=None 时按画面自动定上下限+ - agc:直方图均衡(平台限幅)占的比例;curve=[(°C, 0..1), ...] 是手调色调曲线,替代线性 span,要让房间、猫、灶台各占一段颜色时用它+ - netd、fpn:时间噪声和竖条纹(°C);optics:镜头模糊;dde:细节增强(只放大小温差);narcissus:中心偏凉;pixel:保留多少传感器像素格+- OSD(调用时记下,出图时按该阶段的传感器图像读数,数字和颜色永远对得上):+ - `statusbar(rec, date, clock, battery, emissivity, mode, height, reflected)`+ - `scalebar(x0, y0, x1, y1, ticks, height)`:宽 > 高是横向;刻度按增益曲线的非线性位置放,挤在一起的自动跳过;给 height 时底部加半透明条+ - `spot(x, y, label, name, side, r)`、`box(x0, y0, x1, y1, label, name)`、`hottest(region)`、`coldest(region)`、`profile(p0, p1, inset=(x, y, w, h), label, name)` 线剖面 + 插图、`results(x, y, width)` 读数表、`reticle()`、`text()`+- `level(v)` 某个温度落在色板的哪个位置;`stage(name)` 只存温度场和 OSD 条数,`save(path, stages_dir)` 统一用最终的增益出所有快照,颜色不会在阶段之间跳;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**代尔夫特蓝瓷砖 `DelftTile`**:+- 思路:照作坊工序画一面锡釉砖墙——白坯砖排在一张从来不完全横平竖直的网格上;用刺孔纸样拍炭粉留下点线(粉印);trek(勾线)用细长笔沿粉印勾轮廓;再用稀钴蓝大笔晕染(生釉吸水快,染色不能晕开,留下笔道、鬃毛丝、干边积色、叠染变深、和轮廓错位);没烧之前颜料是灰黑色、釉是哑光粉白;入窑后釉面变亮,颜料按每通道 Beer–Lambert 吸收变成钴蓝,洇进釉里、带细颗粒。只有一种透明颜料,所以从前往后画,用 `occlude()` 留出前面的东西。每块砖单独画、单独烧:砖缝处线条错开一两像素,每块砖的白和蓝都不同;单块砖四角各画四分之一角饰,四块拼在一起才是一朵。墙面是高度场:每块砖略鼓、略斜,倒角打光,窗户倒影碎成弯曲的几片+- 构造:`DelftTile(W, H, seed, tile=128, joint=3.6, origin=(0, -36), ss=3, glaze=(冷白, 暖白), mortar, light)`;tile 是砖距(约 13 cm 一块),origin 让砖画对齐网格;`tableau(i0, k0, i1, k1)` 指定连成一幅画的砖(i0 ≤ i < i1),返回外框像素;`rect(i, k)`、`centre(i, k)`、`visible()`、`in_tableau(i, k)`+- 图层:`layer(名字)`,每层分 trek(线)和 wash(晕染)两份;`stage(name, hide=(…))` 可以隐藏层名('single')、种类('wash')、具体某份('picture.wash')、粉印('pounce')或全部('*'),用来重演作坊工序+- 笔:+ - `trek(点列, width, dens, taper, wobble, smooth, pounce, bead)` 勾线:落笔有小墨珠、收笔变尖、往下走的笔画更粗、手有点抖,同时记下粉印点;`line(p0, p1, bend)`、`closed(点列)`、`dot(x, y, r)`;+ - `wash(形状, tone, angle, pool, ragged, slip, band, streak, grad, holes)` 晕染:形状可以是多边形、多边形列表或整幅遮罩;tone 约 0.1 淡到 0.5 深;angle 是笔道方向;`grad=((x0, y0), (x1, y1), f0, f1)` 沿一条线渐变;`holes=[多边形]` 留白;+ - `hatch(形状, angle, spacing, width, dens, wave)` 排线(阴面、帆、茅草、船身);+ - `letters(字, x, y, size, font='serif', spacing)` 手绘字+- 遮挡:`occlude(形状, grow)` 把画好的东西的轮廓留出来,之后的线和晕染自动避开;`clear_occlusion()`+- 图案(代尔夫特常见题材,坐标都是画布像素):`windmill(x, 地面y, 轮毂高, sails, squash, cloth)` 带回廊的罩式风车(squash < 1 让风叶转向左前方);`sailboat(船尾x, 水线y, 船长, facing, belly, cargo, skipper, pennant, leeboard)` 平底帆船(斜桁主帆、前帆、披水板、桅顶三角旗、货袋、舵手),返回船体轮廓;`house(x0, x1, 地面y, 墙高, gable='step'|'bell'|'neck'|'spout', gable_h, floors, chimney, smoke=(dx, dy), vane=-1, shade='right')` 运河屋(十字窗、门、吊货梁、砖缝短线、烟、风向鸡);`tree(x, 地面y, h, w, lean, clumps)`;`bushes(x0, x1, y, h, gap)` 地平线上的远树;`tulip(x, 地面y, h, lean)`;`cloud(cx, cy, w, h, lean)`;`birds([(x, y), …])`;`water(x0, x1, y0, y1, far, near, avoid)` 远密近疏的水纹;`reflection(x, 水面y, w, depth)`;`grass()`;`smoke()`;取点工具 `arc()`、`ellipse_pts()`+- 单块砖:`field(tiles=None, corners='spin'|'lelie'|'dot', medallion=True, motifs)` 给砖画以外的每块砖画四角的四分之一角饰、双圈圆框和小图('tulip' 'ship' 'mill' 'boat' 'fish' 'bird' 'house' 'pot',和左、上邻砖不重复);也可以单独用 `corner()`、`medallion(i, k)`、`vignette(i, k, kind)`+- 边框:`border(rect, band, inset, tone, leaf, reserve=[卷轴形状])` 砖画外一圈蓝边框:藤蔓、叶子、浆果留白,四角玫瑰花,reserve 给题字卷轴留白+- 工序:`fire()` 入窑(灰黑颜料变钴蓝、釉面变亮、颜料洇开带颗粒、粉印烧掉、每块砖钴蓝浓淡不同);`set_wall()` 石灰浆勾缝;`age(craze, chips, specks, nails, cracks=[点列])` 开片、铁斑和针孔、崩瓷、四角裁坯模板的钉孔、只在一块砖里的裂纹;`light(window=(x, y, w, h), strength=0.5, panes=(2, 3), soft=8)` 窗户在釉面上的倒影,x, y 是墙面完全平整时倒影所在的位置;倒影按滤色叠在釉面上,画面透得出来;放在画了东西的地方(云、边框)才看得出,纯白釉上几乎看不见+- `stage(name, hide)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度+- 常量 `COBALT_K`(烧成的钴蓝吸收系数)、`RAW_K`(生颜料)、`GLAZE_COOL GLAZE_WARM RAW_GLAZE MORTAR BED BODY`++**洞穴壁画 `CavePainting`**:+- 思路:颜料是涂上去的,不是凿出来的(和岩画相反):浅色石灰岩高度图 + 一层层颜料覆盖场(乘进 albedo,石头的斑驳透出来),最后只用地上的篝火和油灯照:每盏都是点光源,半 Lambert 明暗 + 平方反比衰减 + 逐像素沿光线步进的投影(掠射光让每个鼓包都显形)、湿钙华上的高光、凹处一点冷色环境光;再叠火焰发光、泛光、烟和色调曲线。光照缓存,只有高度图变了才重算+- 构造:`CavePainting(W, H, seed)`+- 洞壁:`wall(colour, relief, scallops, grain)` 石灰岩(大起伏、岩脊、溶蚀扇贝纹、颗粒、小坑、赭色和灰色斑、凸处钙华皮);`boss(x, y, rx, ry, height, rot)` 鼓包(把野牛的肚子、马的侧腹画在上面);`fold(pts, height, soft, side)` 岩面转折;`flowstone(x0, x1, top, length)` 钟乳石帘(橙色条纹、湿亮);`crack(pts, width, depth, branches)`;`floor(y, tilt)` 朝观者倾斜的泥地;`floor_h(x, y)` 地面高度+- 火与道具:`fire(x, y, size)` 篝火(石圈、灰、辐射状的柴、火舌、火星、烟柱 + 主光源);`lamp(x, y, size)` 红砂岩油灯(碗、柄、油面、灯芯小火 + 第二光源);`stone(pts, colour, height)` 石板 / 石子;`heap(x, y, r, pigment)` 研磨颜料堆;`stick(p0, p1, width, colour, hollow, tip)` 炭条 / 空心骨管(hollow=True,tip 是管口的颜料)+- 起稿(单位坐标,facing 1 朝右 / −1 朝左,size 是身长):`bison(x, y, size, facing, head_drop)`、`horse(…, gait='run'|'gallop'|'stand')`、`deer(…, kind='stag'|'hind', gait='leap'|'stand')`、`hunter(x, 脚底y, 身高, facing, pose='throw'|'run')`(`anchors['grip']`、`['spear_dir']` 挂矛)、`spear(p0, p1, width)`、`hand(x, y, size, rot, side, spread, fold=(3, 4))`(腕部为原点、手指朝上,fold 是弯下去的手指)、`shape(...)` 自定义;返回 `Figure`:部件 body / legs(只算身体轮廓以下)/ tail / horns / antlers / mane / ears,区域 head / hump / belly / back / front;`fig.sel('head', 'mane')` 取一部分,`fig.anchors['eye']` 等+- 上色(都接受 Figure 或 `fig.sel(...)`):+ - `sketch(fig, width, passes, strength)` 炭条找形线(每遍沿略微游移的轮廓);+ - `blow(t, 颜料, density, edge, halo, speckle, rim, gradient, relief, clip, exclude)` 吹喷:软边、晕、雾点、不匀;rim 靠轮廓更浓,gradient 背上更深,relief 在背向火光的岩面上更浓(借岩面起伏),clip 不出界,exclude 留出浅色肚子;+ - `daub(t, 颜料)` 毛皮垫拍涂;`paint(fig, 颜料, kind)` 把猎人、矛整形涂实;`line(pts, width, 颜料, kind='charcoal'|'finger'|'brush')`;+ - `outline(fig, 颜料, width, top, gaps, kind='charcoal'|'blow')` 收边:轮廓内侧一条带,背上和上沿粗、肚子细、有断笔;+ - `dots(pts, r, 颜料)` 掌印点;`stencil(hand, 颜料, spread, puffs)` 吹喷负手印;`handprint(hand, 颜料)` 正手印+- 颜料:`PIGMENTS` 的 red 赤铁矿红赭 / darkred / orange / yellow 针铁矿黄赭 / brown / black 炭黑 / manganese 锰黑 / white 高岭土,或 '#rrggbb'+- 岁月:`calcite(x, y, rx, ry, amount)` 钙华乳白薄膜(盖在画上);`flake(n, size, min_load)` 零星掉色;`claws(x, y, angle, n, length, spread)` 洞熊爪痕(新鲜浅色沟,划穿颜料);`soot(x, y, amount, drift, spread)` 篝火熏出的烟柱和顶壁+- 顺序:wall → boss / fold / flowstone / crack → floor → fire / lamp / 道具 → sketch → 红、黄(blow / daub)→ 黑(blow / outline / line)→ 猎人、手印、点 → calcite / flake / claws / soot+- `stage(name)` 立即合成快照,`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**1-bit 早期画图软件 `MacPaint`**:+- 思路:画的不是「像素风插画」,是一台 1984 年式黑白画图软件的整屏。640×360 帧缓冲只有黑白两值,×3 最近邻放大到 1920×1080。文档位图 `doc`(1 = 黑)里的一切都按当年工具的规矩画:8×8 图案贴着文档原点平铺(同一图案的两块天然对缝,图案不随形状弯);线是方笔头 Bresenham;形状 = 图案填充 + 画在轮廓内侧的边框;油漆桶是 4 连通泛填;文字关掉抗锯齿,样式是对字形遮罩做位运算。界面在渲染时才画,所以每个 `stage()` 都能换工具、图案、光标、菜单+- 构造:`MacPaint(seed, title='untitled', menus=(...), screen=(640, 360), scale=3, ink, paper, doc=None, scroll=(0, 0))`;文档坐标原点是窗口内容区左上角,默认 554×246+- 图案:`PATTERNS` 共 41 种(white / black / gray 50% / light 25% / lighter 12.5% / mist / faint / dark / darker,dots、polka、hlines、vlines、diag、rdiag、thick_diag、grid、xhatch、bricks、scales、weave、basket、diamonds、shingles、waves、zigzag、stars、sprigs、checker、gingham、hstripes、vstripes、wood、grass、pebbles、circles……),图案板显示其中 `PALETTE` 38 种;`paint(mask, 图案, mode='opaque'|'or'|'erase'|'invert')`;`bands(mask, [图案…], y0, y1)` 用几条图案带做「渐变」,接缝处交错打散+- 形状工具(都返回遮罩):`rect(x0, y0, x1, y1, fill, line, radius)`、`oval(cx, cy, rx, ry, fill, line)`、`shape(点, fill, line, smooth)` 自由形 / 多边形;`line(p0, p1, width)`、`pencil(点, mode)`、`brush(点, size, shape='round'|'square'|'slash'|'backslash'|'bar'|'vbar'|'dot', pat)`、`spray(点, radius, density, pat, clip)`、`bucket(x, y, 图案)`、`dotted(点, gap, size)`;遮罩:`mask_rect / mask_oval / mask_poly / mask_path`、`border(mask, w)` 内侧边框、`pen(mask, w)` 方笔加粗+- 编辑:`copy(rect, to, flip, mask)` 选取 + 拖动复制(flip 是左右翻转,mask 相当于套索选取,背景不跟着走)、`invert(rect 或 mask)` XOR、`erase(rect 或 mask)`+- 文字:`text(s, x, y, size, font='system'|core 字体风格, style=('bold', 'italic', 'underline', 'outline', 'shadow'), anchor='l'|'m'|'r', opaque)`;'system' 是自带的粗体点阵字(大写 9 px 高、2 px 竖笔,只有拉丁字母、数字和少量符号),其他字体走 `core.load_font` 并关掉抗锯齿;outline / shadow 是空心字+- 界面状态(下一次 `stage()` 生效):`use(tool, pattern, line)` 反白工具(`MacPaint.TOOLS` 里 20 个名字)、当前图案、线宽打勾;`cursor(kind, x, y)`(arrow / cross / ibeam / bucket / spray / brush / pencil,kind=None 隐藏);`select(rect=…)` 或 `select(lasso=mask)` 行军蚁;`menu(名字, items, checked, hilite, styled)` 下拉菜单,styled=True 时每项按自己的样式写,`menu(None)` 收起;`zoom(x, y, w, h, at, fat)` 放大镜窗,`zoom(None)` 关掉;`retitle(标题)` 存盘改名+- `render()` 返回 640×360 的 0/1 屏幕,`image()` 放大后的 PIL 图;`stage(name)`、`save(path, stages_dir)`(JPG 默认 quality 88,纯黑白时存灰度)+- 动图:帧是纯黑白,缩到 720 宽用 BOX、配固定灰阶调色板(不要用默认的 LANCZOS + 中值切分)++**古希腊黑绘陶瓶 `BlackFigure`**:+- 思路:先在轮上拉出一只陶瓶(轮廓 r(y) 加两只圆把手),所有彩绘都画在「展开面」上(绕瓶一周的弧长 × 高度),同一张展开面既包到曲面瓶上,也能平铺成展开图,两边永远一致。工序照古代作坊:轮上画饰带 → 泥釉画剪影 → 刻线 → 加红加白 → 三段烧成(泥釉这时才变成亮黑)→ 做旧 → 按博物馆照片打光+- 构造:`BlackFigure(W, H, seed)`;`museum(wall, plinth, spot, plinth_x)` 深色展墙、聚光、浅色展台;`pot = throw(cx, foot, height, rmax=None, shape='neck_amphora', eye=0.42)`:foot 是瓶底落在展台上的屏幕 y+- 瓶上的坐标:`y` 是从口沿往下的像素;饰带里的 `x` 是该圈半径处的弧长像素,0 在左把手,正面(看得见的半圈)是 0 .. C/2,背面 C/2 .. C;`pot.TW` 是展开面宽度(按最大半径),`pot.radius(y)`+- 轮制与纹样:`pot.paint_handles()`;`pot.band(y0, y1)` 转着画的黑带(水平、收笔处有一点搭接);`pot.palmettes(y0, y1, n)` 棕榈叶 + 莲花垂花链;`pot.tongues(y0, y1, n, red_every=2)` 肩部舌纹;`pot.meander(y0, y1, n)` 回纹;`pot.rays(y0, y1, n)` 瓶脚放射纹+- 人物:`z = pot.zone(y0, y1)`,`z.C` 是这一圈的周长;`z.quadriga(x, hw, white_horse, red_manes, bends)` 四马战车(x = 最近那匹马的肚带,hw = 马高);`z.runner(x, height, phase, beard, back_arm)`;`z.column(x, height, red)` 多立克柱(折返柱 / 终点柱);`z.judge(x, height, facing=-1, holds='wreath'|'rod')`;`z.tripod(x, height)` 奖品三足鼎;`z.prize_table(x, height)` 摆着小双耳瓶和花冠的桌子;`z.bird(x, y, size, facing, flap)`;`z.letters(text, x, y, size, vertical, retro)` 古阿提卡字母(细笔泥釉写,可反写)+- 自己画新人物:建一个 `blackfigure._Fig()`,用局部单位(脚在 (0, 0),朝 +x,y 向下)按由远到近调 `slip(poly)` / `cut(pts, w)` / `red(poly)` / `white(poly)` / `reserve(poly)` / `line(pts, w)`,再 `z.emit(fig, X, G, scale, facing)`;线宽是像素(刻刀和细笔的宽度不随人物缩放)+- 三遍上色:`pot.paint()` 刷泥釉剪影(只画新声明的);`pot.incise()` 刻线;`pot.add_colour()` 加红加白。后两遍按声明顺序重放:近处的黑剪影会盖掉远处的刻线和加彩,再刻出自己的轮廓——四匹马叠在一起也分得清+- `pot.fire()` 烧成;`pot.age(mend=(u, v, rx, ry), misfire=(u, v, r), chips=7, roots=14)`:u, v 是展开面像素(正面中心 u = TW/4)+- 展板:`panel(box, title, subtitle, english, greek)`;`rollout(pot, bands, x, y, scale, half=0|1, caption, ticks)` 把几圈饰带按各自周长展开成上下居中的几条(half 0 = 正面,1 = 背面);`legend(x, y, [(label, 'clay'|'black'|'incision'|'red'|'white')])`+- `stage(name)` / `save(path, stages_dir)`;每次 stage 都按陶瓶当时的状态重新打光渲染(几何只算一次)++**铅笔素描 `Graphite`**:+- 思路:石墨是一张「质量场」`m`,看到的深浅是 Dmax·(1 − e^−m),层层叠加但永远到不了黑;石墨是冷灰不是黑,重压处被压亮(`b`),在斜光下带一点银灰的反光。铅笔只在笔尖碰到纸的地方留下石墨:轻压只擦过纸纹的峰(灰里透着白点),重压和软铅才填进纸纹的谷。每一笔都有起笔、加力、收笔,越往纸边画得越少+- 构造:`Graphite(W, H, seed, ss=2)`;`paper(tone, tooth=1.6, felt, mottle)` 素描纸(纸纹高度场、斜光下的微浮雕、左上亮的光线落差)+- 铅笔硬度 `GRADES`:'4H' 'H' 'HB' '2B' '4B' '6B' '8B',决定每笔多少石墨、能压进纸纹多深、线多宽;越硬越淡越细、纸纹越白+- 遮罩和调子场:`poly(pts)`、`ellipse(cx, cy, rx, ry, rot)`、`ring(cx, cy, r0, r1)`、`band(pts, width)` 粗线(管子、杆)、`lines_mask(lines, width)` 一批细线、`rect()`;`linear(p0, p1)` 从 0 到 1 的渐变、`radial(cx, cy, r)`;`circle_pts(cx, cy, rx, ry, a0, a1, rot)` 椭圆弧上的点(度,屏幕顺时针)+- 完成区:`focus(cx, cy, rx, ry, soft, rough)`:参差的椭圆里画完,往外调子按 finish^0.6 变淡、排线和侧锋整笔整笔地丢,线条变淡,纸边只剩线稿;各方法 `finish=False` 时不受它影响+- 起形:`guide(p0, p1, grade='2H', overshoot)` 两头出头的长辅助线(视平线、透视线、铅垂线);`guide_ellipse(cx, cy, rx, ry, rot, loops=2)` 绕两三圈的松椭圆加轴线+- 线:`line(pts, grade, pressure, closed, searching, lost, weight, fade=0.35)`:压力沿线起伏;`lost` 让亮面的边断开;`weight` 是一张场(如背光面),高的地方线更重更粗;`searching` 先轻轻找几遍;`strokes(lines, grade, pressure, width, taper, clip, fade)` 一批自由笔画(辐条、链节、篮子的编条)+- 排线:`hatch(mask, tone, angle, grade, spacing, length, layers=(0, 0, 58, -38), pressure, zigzag, edge)`:tone 0 纸白 .. 1 最暗(数或场);layers 是每层的角度偏移,同一角度重复一次就插在前一层的两线之间,第 k 层只在 tone > k/层数 的地方下笔,越暗压得越重;一块一块地排(每块共用略有漂移的接缝),手腕弧让每笔同向微弯,起笔重收笔挑;`zigzag` 来回不抬笔的连笔排线。`contour_hatch(lines, mask, tone, grade, pressure)` 顺着形体走的笔画(绕车胎、沿管子、沿面包)+- 侧锋:`shade(mask, tone, angle, grade='4B', width=9, pressure, passes=3)` 钝软铅的侧面,宽而软的笔触三遍交叠,只挂在纸纹峰上——晕染前的底色+- 纸擦笔:`smudge(mask, amount, radius, direction, length, pickup, contain=True)` 把石墨推进纸纹谷、往旁边匀开(可顺一个方向拖),颗粒消失;contain 时只在遮罩里匀,不把旁边的空白抹进来+- 橡皮:`lift(mask, amount)` 可塑橡皮按出柔和的亮;`erase(pts, width, amount, soft)` 硬橡皮边擦出清楚的白线(轮圈、管子高光、转角亮边、玻璃反光),会留一点残影+- 页边:`write(s, x, y, size, grade, pressure, font='hand')` 铅笔手写;`value_scale(x, y, w, h, grades)` 试笔色阶(每格一种硬度、下面写标号);`fingerprint(x, y, r, rot, amount)` 石墨指纹;`smear(pts, width, amount)` 手侧蹭过的灰+- `stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度;颜色常量 `PAPER GRAPHITE SHEEN`++**X 光片 `XRay`**:+- 思路:不画物体的样子,只建「沿射线方向有多厚的什么材料」。每样东西往两张衰减图里累加 μ(材料, 能量) × 密度 × 沿射线的长度(双能:低能约 60 keV、高能约 120 keV),没有先后遮挡,重叠就相加;再按比尔定律 I = e^(−A) 让射线穿过去,经过探测器(散射雾、焦点模糊、线阵探测器逐行增益条纹和每 64 行的模块缝、光子噪声),最后进显示(胶片:越密越亮;或安检伪彩:按 Zeff 分有机橙 / 无机绿 / 金属蓝 / 穿不透黑)。轮廓发光不是画上去的:空心壳体在轮廓处被射线沿侧壁穿过,路径最长+- 构造:`XRay(W, H, px_cm=17, seed)`;所有长度都是画布像素,包括沿射线的深度,`px_cm` 定物理比例。材料表 `MATERIALS`:organic、water、rubber、pvc、pcb、magnesium、mica、glass、aluminium、bone、plaster、ferrite、zinc、steel、brass、copper、tin、lead+- 轮廓:`rrect(cx, cy, w, h, r, rot)`、`ellipse(cx, cy, rx, ry, rot)`、`poly(pts, cx, cy, rot, scale)`(局部坐标搬到画布)、`closed(ctrl)` 闭合样条、`path(ctrl)` 开放样条(点可带第三维深度 z)、`offset(P, d)` 侧移+- 物体:+ - `slab(outline, material, depth, edge, holes, density, tag, texture)`:实心,边缘按半径 edge 倒圆(默认 depth/2 像卵石,0 是锯切边);holes 打穿的孔;density 可以为负(钥匙上铣出的槽)+ - `shell(outline, material, depth, wall, edge)`:空心壳(箱子、吹风机外壳、相机机身),轮廓发亮、中间淡+ - `rod(P, material, r, wall, ribs, flat)`:沿路径的圆线 / 圆棒,r 可逐点渐变;wall 变管子(两边亮中间暗);P 带 z 时沿射线潜下去的段更亮;ribs=(幅度, 周期) 螺纹、双重螺旋、绞合线的起伏;flat 扁带(可以是弧长的函数)。`tube(P, m, r, wall)` 同上+ - `coil(p0, p1, R, turns, material, r_wire)` 弹簧 / 电热丝(侧看:转折点亮、前后两半成之字);`edgeon(p0, p1, thick, material)` 侧看的圆片(风扇、格栅、滤网);`disc(cx, cy, r, material, depth, hole, rim, dome)` 正看的圆片(硬币带凸边、垫圈、镜片 dome>0 中厚、镜筒圆环正对射线全是壁);`ball()` 滚珠+ - `zipper(P, material, tooth, pitch, depth, tape)`、`screw(p0, p1, r, head, pitch)`、`cable(P, r, cores, core_r)`+ - `fabric(outline, depth, layers, sheet, density, weave, scale, angle, creases)`:叠好的衣服,折边处布翻过去成软亮边;`weave('plain' | 'twill' | 'knit', scale, angle, amount)` 也可单独给 `slab(texture=)`+ - `belt(y0, y1, lacing=x)`:传送带(纵向帘线纹)、两侧钢导轨和螺栓、钢钩接头;它的衰减记作空气校准,伪彩视图里自动扣掉+- 探测器和显示:`scan(kv, ma, flux=(低能, 高能光子数), scatter, scatter_px, focal, streak, module)`;`film(a0, amax, mix, edge=(细, 粗), glow, vignette, stops)`;`detect()` → (A'_lo, A'_hi),`show_film(Lo, Hi)`、`show_material(Lo, Hi)`、`zeff(Lo, Hi)` 可单独用+- OSD:`status(left_lines, right_lines)` 顶栏;`footer(left, right)` 底栏((文字, 颜色),琥珀 / 绿 / 红自动加底色块);`flag(x0, y0, x1, y1, n, label, note, side)` 编号报警框;`panel(x0, y0, x1, y1, title)`;`inset(src, dst, 'material' | 'film', title)` 任意区域的插图;`legend(x, y, w)`;`scale(x0, y0, x1, y1, [(标签, 材料, 厚度px)], title)` 衰减标尺(刻度按同一条显示曲线算);`text()`、`line(pts, dash=)`+- 读数:给物体加 `tag='名字'`,OSD 文字里写 `{名字.z:.1f}`(Zeff)、`{名字.ml:.0f}`(按水折算的体积)、`{名字.cm2}`;出图时从该阶段的探测器图像上量(物体外一圈扣背景),数字和画面永远对得上;`x.readings` 留着最后一次的读数+- `stage(name)` 存 float16 的两张衰减图和 OSD 条数;`save(path, stages_dir)` 每个阶段用同一张噪声出图,阶段之间只有新加的东西在变;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**1930 年代黑白橡皮管动画 `RubberHose`**:+- 思路:照 1930 年代动画厂做一格画面的方式:背景师在板上用灰色水粉画一次背景(平涂 + 干笔刷纹、喷枪光斑和接触阴影,背景线细而灰);动画师铅笔起稿(两遍、略错开,带结构圆、十字线和动势线);描线员用黑墨描到赛璐璐上(粗而均匀,压力略有起伏);上色员在背面涂几档平灰(白、浅、中、深、黑,赛璐璐上不画明暗);叠在背景上用黑白胶片拍下、印成拷贝、放映很多遍。赛璐璐不透明、从后往前画,后画的挡住先画的;角色要从「后面」经过的背景部分(窗外近山、窗横档、窗帘、被子)存成 clip 遮罩+- 构造:`RubberHose(W, H, seed, ss=2, ink_w=5.5)`(内部 2 倍超采样);灰阶常量 `WHITE LIGHT PALE MID DARK BLACK INK`+- 背景(画在板上):`wash(pts, value, value2, axis, tex, line, dark)` 平涂 / 渐变水粉 + 细灰轮廓;`blob(circles, value)` 圆的并集(云、树冠),只描外轮廓;`line(pts, width, dark)`;`airbrush(cx, cy, rx, ry, amount)` 喷枪光斑(正提亮、负压暗);`light(pts, amount, soft)` 软边光块(地上的阳光、窗档影子);`pattern(pts, draw_fn, dark)` 小花样(壁纸、波点;dark < 0 提亮)+- 房间:`wall(y1)` 渐变墙纸 + 竖条 + 小枝花 + 踢脚板;`floor(y0, board, vp)` 透视地板、接缝、木纹;`window(x0, y0, x1, y1, bars='sash'|'cross', horizon, valley)` 窗外的早晨(天空、云、远山、树、近山;近山和窗档进 'window' clip),返回几何;`curtain(...)`、`valance(...)` 窗帘和帘头(也从 clip 里减掉);`nightstand(x0, x1, top, bottom, floor_y)` 返回桌面 y;`bed(x0, x1, head_top, sheet_y, front_y, floor_y)` 从床尾看的床(拱形床头、球形柱头、绗缝被、垂下的被边;被子进 'bed' clip);`rug(cx, cy, rx, ry)` 编织地毯;`sampler(x0, y0, x1, y1, lines)` 挂墙的格言框+- clip:`clip(name, add, sub, full)` 建遮罩;角色方法的 `clip=`,或 `using(name)` … `using(None)` 把之后的赛璐璐都放进某个 clip+- 赛璐璐基本件:`shape(pts, fill, ow)`(墨线只在填色外侧;fill=None 只描线);`union(subs, fill, ow)` 几块拼成一块、中间不出线(`('poly', pts)` / `('cap', pts, r)`);`hose(pts, width)` 等粗、没有肘和膝的橡皮管;`stroke(pts, width, taper)`;`text(s, x, y, size, fill, ow, rot)`;`shadow(cx, cy, rx, ry, amount)` 角色脚下的灰影;`guide(pts)` 只出现在铅笔稿里的结构线+- 橡皮管词汇:`hose_path(p0, p1, bend, bend2)` C 形 / S 形四肢;`glove(x, y, angle, size, pose='open'|'point'|'fist'|'palm', flip)` 四指白手套(三道缝线、外翻袖口;(x, y) 是手腕,angle 是手指方向);`shoe(x, y, size, facing, tilt)` 大圆鞋(白高光、灰鞋底);`pie_eye(cx, cy, rx, ry, look, wedge, lid)` 白眼眶 + 切掉一角的黑瞳,lid 是半闭的眼皮;`grin(F, x0, x1, y_top, y_bot)` 张大的笑嘴带舌头;`star()`;`Frame(x, y, s, rot, flip)` 局部坐标+- 角色:`alarm_clock(cx, cy, r, tilt, look, time=(7, 0), arms=[...], legs=[...])` 双铃闹钟(黑表壳、白表盘上的脸、指针、两只铃和甩动的铃锤;arms / legs 给手腕 / 脚踝位置和 bend、pose、facing、tilt),返回局部 Frame,`rh.bells` 是两只铃的位置;`sun(cx, cy, r, arms, ray_style='wavy'|'spiky', clip)` 半睁眼打哈欠、伸懒腰的太阳;`pillow(cx, cy, w, h, arm, clip)` 戴条纹睡帽打呼、举起手套的枕头;`slipper(x, y, size, facing, tilt)` 跳舞的拖鞋+- 特效:`vibration(cx, cy, r, a0, a1, n)` 同心震动弧;`speed_lines([pts])`;`lettering(s, path, size)` 沿曲线蹦跳的粗衬线字(白字黑边,单双号反向倾斜、上下错开);`zzz(x, y, size)`;`slab_font(size)` 找 Superclarendon / Rockwell 这类粗衬线字体(可用 `INKPAINT_FONT_SLAB` 指定)+- 顺序与快照:背景 → `stage('layout', view='layout')`(纸上的背景铅笔稿)→ `stage('background', view='background')` → 画角色(此时是铅笔稿)→ `stage('pencil')` → `ink()` → `stage('ink')` → `paint()` → `stage('paint')` → 特效 → `film(grain, soft, halation, tone='silver'|'sepia'|'neutral', vignette, weave, gate)` → `age(scratches, dust, specks, fibres, hair, stains, flicker)` → `save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**黑白麻胶版画 `Linocut`**:+- 思路:减法。整块麻胶版滚上墨,印出来是一整块黑;画里所有白的地方都是刻刀挖掉的。每块版是一张 ss 倍分辨率的浮雕图(255 = 没刻、吃墨,0 = 刻掉了):黑版一开始是满的,套色版一开始是清空的,只「留下」要印颜色的形状;黑版外圈一道边永远不刻,印出来就是手刻版那圈微微起伏的黑框。每一刀都是一个两头收尖、边缘带碎口的多边形;明暗不靠灰色,靠刀痕的疏密和粗细(黑里刻白线,或白里留黑线)。印的时候按真的手拓算:墨辊滚出的墨层不匀、带几道停辊横纹,木蘑菇压出一圈圈压力;墨层 × 压力压不过纸纹的地方露白(大片实地「发花」),墨被挤到形状边缘,所以边缘始终是实的;先印套色、再叠黑版,两版错开几像素;纸被压进版里,刻掉的地方和页边微微鼓起+- 构造:`Linocut(W, H, block=(x0, y0, x1, y1), seed, paper, ink, ss=2, rim=7)`;`colour_block(颜色, offset=(dx, dy), mottle)` 加一块套色版(颜色写印在这张纸上的样子),返回 `Block`,各工具用 `on=` 指定刻哪块版(默认黑版)+- 遮罩:`poly(pts, smooth)`、`disc(cx, cy, r)`、`rect()` 给 1× 浮点遮罩(可以用 numpy 加减);区域参数也可以直接给多边形点列;`mask_of(polys)` 把一组刀痕多边形变成遮罩+- 一刀:`stroke(pts, width, tool, taper, end)` 返回刀痕多边形;`gouge(pts, width, tool='v'|'u'|'knife'|'brush', cut=True, on, region)`:v 是 V 口刀(尖入、渐宽、提刀收尖),u 是 U 口刀(圆头、碎尾),knife 是等宽刻刀,brush 的宽度从 width 线性变到 end(树枝、留下的线);`cut=False` 是留下一条不刻(白地里的黑线);`jab(x, y, size)` U 刀戳一下+- 成片:`clear(形状, chatter, angle)` 用大 U 刀清掉一片,留下顺下刀方向的残刀印(靠边更多);`leave(形状)` 留住一片;`hatch(region, angle, spacing, width, dash, gap, tool, cut, density, bend)` 一排排平行刀痕:density(x, y) 决定一刀留不留、多粗(这就是明暗),bend(x, y) 把行推弯(漂雪、等高线、衣褶);`flow(region, field, n, length, width)` 沿方向场 field(x, y)→角度 的长刀痕(风、水、毛);`speckle(region, n, size, stars)` 落雪:U 刀戳点加少量三刀交叉的六角雪花,只刻在还有墨的地方;`rings(cx, cy, radii, width, arc, gap, cut, squash)` 断续同心环(月晕、年轮);`outline(形状, width, cut=True)` 在形状外刻一圈白边,黑东西才能从黑底里分出来(cut=False 是留一圈黑边,白东西穿过白底)+- 物件:`moon(cx, cy, r, rings)`;`pine(x, y, h, w, tiers, snow, halo, nicks, region)` 积雪云杉;`bare_tree(x, y, h, lean, spread, width, depth, halo, snow, seed)` 枯树(返回遮罩);`cottage(x, base, fw, wall, roof, side, rise, windows, side_windows, door=(u, w, h, 开着), chimney=(位置, 宽, 高), lit=套色版, attic)` 积雪木屋,返回 `{'apex', 'windows', 'door', 'chimney'}`;`smoke(x, y, rise, drift, width)` 一串卷着飘的烟团;`footprints(path, step, size, side, start, stop, paws)` 脚印 / 爪印+- 印:`pull(blocks)` 印出 PIL 图;`sign(edition, title, name, y)` 页边铅笔:左版次、中题名、右签名;`chop(x, y, size)` 不上墨的钢印+- `stage(name, blocks=None)` 快照(`blocks=[]` 是白纸,`blocks=[L.key]` 只印黑版);`save(path, stages_dir)` 默认 quality 88、4:4:4 色度+- 顺序:和画家算法一样,后刻的盖前面:先清大块白(山、雪野、月亮)→ 天空刀痕 → 远景 → 房子 → 雪地 → 近景人物 → 落雪 → 套色版 → 铅笔++**VHS 家庭录像 `VHSCamcorder`**:+- 思路:不是在画面上盖一层「复古滤镜」(Synthwave 的录像带质感就是这么做的),而是照家庭录像真实的三步出图,每种瑕疵都来自其中一步:+ 1. 房间:颜色画进反照率缓冲,灯罩、烛焰、窗外天空画进自发光缓冲;出图时反照率乘上房间的光(暖色环境光 + 点光源 + 画上去的光斑)再加自发光;镜头前太近的东西画在离焦图层上+ 2. 摄像机:手持微倾和变焦、白平衡停在「室外」拍钨丝灯、软膝高光、泛光、CCD 竖向拖影、拖尾、镜头柔化、暗角、暗处增益噪声;摄像机的字符发生器在这里把 OSD 混进信号,所以 OSD 也跟着上带、跟着糊+ 3. 录像带:降到 480 行 × 760 采样点,分成亮度 Y 和色度 I/Q;亮度低通再加回放锐化(一边亮一边暗的光晕),色度约 6 倍宽的低通、隔行平均、往右延迟(红色往右渗);回放再加条状亮度噪声、横向色度噪声、逐行时基抖动、顶部偏摆、跟踪噪带、磁头切换噪声、掉磁白点、抬高的黑电平,最后放大回输出尺寸+- 构造:`VHSCamcorder(W, H, seed, lines=480, samples=760, ss=2, keep_stages=True)`;`keep_stages=False` 时 `stage()` 不出快照(快)+- 形状 → 遮罩:`poly(pts)`、`shape(pts)` 闭合样条、`rect(x0, y0, x1, y1, r)`、`ellipse(cx, cy, rx, ry, rot)`、`line(pts, width)`、`text(s, x, y, size, style, anchor, rot)`;颜色场 `lin(p0, c0, p1, c1)`、`rad(cx, cy, rx, ry, c0, c1)`+- 上色与光:+ - `paint(mask, colour, alpha, form, form_r, light)`:colour 可以是颜色场;form > 0 把形状打圆(边缘暗、迎光一侧亮)+ - `emit(mask, colour, level)` 自发光(不受房间光影响);`glow(mask, colour, level)` 落在表面上的光斑(乘反照率);`shadow(mask, strength, soft, dx, dy)`;`rim(mask, toward, colour, level, width)` 朝光源一侧的轮廓光+ - `ambient(colour, level)`、`light(x, y, radius, colour, power)` 点光源,1 / (1 + (d/r)²) 衰减+ - `with v.layer(defocus=4.5): ...` 里画的东西整体虚焦(离镜头太近的前景)+- 70 年代客厅:`wallpaper(mask, tile, contrast)` 圆环墙纸带纸幅接缝、`paneling(mask, grooves)` 胡桃木护墙板、`ceiling()` 喷涂天花板、`shag()` 长毛地毯、`window(x0, y0, x1, y1)` 黄昏的窗(剪影、对面一扇亮窗)、`rod()` + `curtain(x0, x1, y0, y1, folds)` 花朵窗帘、`console_tv()` 落地电视柜、`rabbit_ears()`、`floor_lamp(x, y_floor, y_shade)`(自带灯光和墙上的光斑)、`sofa(x0, x1, y_back, y_seat, y_front, y_floor, colour)`+- 派对:`streamer(p0, p1, sag, colour, twists)` 扭转的皱纹纸彩带、`pennants(p0, p1, sag, letters, colours, size)` 字母三角旗(浅色旗自动换深色字)、`balloon(x, y, r, colour, string_to)`、`coffee_table(quad, thick, legs, gloss)`、`cake(cx, cy, rx, ry, h, candles, sprinkles, lean)`(candles = [(角度, 颜色, 'lit' 或 0–1 烟量)],返回火苗位置,每个放一盏 `light`)、`smoke()`、`present()`、`cup()`、`plates()`、`blower()`、`confetti()`、`teddy()`;`child_back(hx, hy, s, lean, glow_from)` 背影的孩子(尖帽、发旋、耳朵、肘),画在离焦图层里+- 三步开关(调用之后的每个阶段都生效):+ - `camera(tilt, zoom, white_balance, exposure, knee, bloom, smear, lag, soft, vignette, gain_noise)`:white_balance 是 RGB 增益,默认 (1.08, 0.94, 0.70) 即「室外档拍钨丝灯」;smear 只对远超满阱的点光源起作用;lag = (dx, dy, 强度) 是高光身后的拖尾+ - `record(luma, chroma, chroma_v, delay, sharpen, sharp_r, saturation)`:亮度 / 色度带宽(采样点 σ)、色度延迟、锐化光晕+ - `wear(noise, chroma_noise, jitter, flagging, tracking=(中心比例, 高度比例), head_switch, dropouts, black, lines)`+- OSD(点阵字、黑边,混进信号上带):`rec(x, y)` 红点 + REC、`battery(x, y, level, of)`、`counter(s, x, y)`、`datestamp(时间, 日期, x, y)`、`zoom_bar(x, y, pos, width)`、`osd_text(s, x, y, px, colour, anchor)`;字库只有大写字母、数字和 `: . - / >`+- `stage(name)` 存一张当前状态的完整渲染;`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**扁平矢量 `FlatVector`**:+- 思路:矢量软件的画板,每样东西是一层。形状边缘干净、没有描边;7 种平涂色,其余颜色都是它们的 `tone` / `mix`;整幅只有一个光源,每样东西分亮面和暗面;每抬起一层,先往已有画面投一道短而柔的夜蓝色阴影(「矢量纸片」的层次),最后加极淡的纤维纹和固定细颗粒(分阶段快照的颗粒一样,动图差分小)+- 构造:`FlatVector(W, H, seed, light=(-0.7, -0.7))`,light 是指向光源的屏幕方向+- 形状:都返回 `Mask`,可以 `|` 并、`&` 交、`-` 减,`moved(dx, dy)`、`scaled(k)`,只算包围盒。有 `circle`、`ellipse(cx, cy, rx, ry, rot)`、`rect(x0, y0, x1, y1, round)`、`poly(pts, round=半径或每角半径)`、`capsule(p0, p1, r0, r1)`、`star(cx, cy, r_out, r_in, n)`、`teardrop(x, bottom, r, h, lean)` 火焰 / 水滴形、`profile(pts, bottom)`(样条顶边往下填满的地块);`half(m, p0, p1)` 取有向直线右侧的部分+- 上色:+ - `backdrop(颜色)`;+ - `fill(m, 颜色, alpha, lift, texture, shadow)`:lift > 0 时先投层间阴影(下移 0.45 × lift,模糊 0.9 × lift,乘夜蓝紫色调),再铺色;+ - `face(m, p0, p1, 颜色)`:把直线右侧改成暗面色;+ - `glow(cx, cy, rx, ry, 颜色, rings, alpha)`:一圈圈平涂半透明光环;+ - `drop(m, lift, strength)`:只投影不铺色;+ - `tone(c, k)`:k < 0 往夜蓝墨色调,k > 0 往奶油色调;`mix(a, b, t)`+- 天空:`moon(cx, cy, r, rays, ray_colour, ray_len, halo, craters)`,月亮外一圈长短交替的三角光芒,加两圈阶梯光晕;`stars(n, box, avoid=[(x, y, r)])`;`sparkle(x, y, r)` 四角星;`shooting_star(head, tail, r)`;`cloud(cx, cy, w, colour, belly)` 平底云+- 地形:+ - `mountain(peak, left, right, 颜色, snow, ridge, lift, shade)`:折线山脊分亮面和暗面,锯齿雪顶;返回 `dict(body, shade, snow)`;+ - `land(pts, 颜色, lift, shadow)`:一层山丘或沙地;+ - `pine(x, base, h, 颜色, tiers, width)`:层层三角,从中间劈成亮暗两半;`round_tree(x, base, r, 颜色, fruit)`;+ - `dashes(box, colours, n, length, thick, horizon)`:沙地上的深浅短横,越近越长;`pebble(x, y, r, 颜色)`、`tuft(x, y, h)`+- 故事道具:+ - `trail(pts, 颜色, width, dash, gap)`:越往下越粗的虚线小路,返回遮罩,可以 `& peak['snow']` 换色;+ - `flag(x, y, h)`、`tent(x, base, w, h, 颜色, depth, inside)`:亮面正面、暗面侧顶、透光的门、掀开的门帘、拉绳和地钉;+ - `campfire(x, base, s)`;`hiker(x, base, h, facing, lamp)`:没有五官的小剪影,带背包、登山杖、头灯光束+- 色板常量 `NIGHT PLUM BERRY EMBER SAND PINE CREAM`;`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**绘本角色动画 `Storybook`**:+- 思路:动画师的一个镜头,不是一张画。一切都是时间 t(秒)的函数:同一个场景既能逐帧出真动画(`frame(t)`、`gif()`),也能出一张「旅程总图」(`journey()`:世界全部画完,角色在关键姿态上多次曝光,配铅笔运动弧)。场景里每样东西都预先画进自己的裁切层,同时记一张「揭示图」:每个像素在这一层自己的画出过程里第几时刻被笔刷/钢笔碰到——墨线按弧长揭示(笔在走),水彩从一点晕开或横扫过去(带一道略深的湿边),小物件放大弹出(0 → 1.1 → 1)。层的进度来自时间窗 `when=(t0, t1)`,或者 `follow=lead`:画到角色已到达的最远 x 前方 lead 像素,所以山坡、花、河岸正好在角色经过时画出来。角色每帧用隐式曲面在自己的局部坐标里现画:整体做保体积的仿射挤压拉伸(沿轴 k、横向 1/√k)再滚转,`rest()` 让最低点正好落在地面上,光照固定在世界里(滚动时高光不跟着转),离地越高接触阴影越小越淡+- 构造:`Storybook(W, H, seed, actor_size=44)`:所有坐标都按 1920×1080 设计坐标给,输出任意尺寸(720×405 动图和 1920×1080 总图就是同一场景的两个实例)+- 编排:`act(t0, t1, fn)`,fn(u, t) → 姿态 dict 或 None(藏起来)。姿态键:`x, y`(坚果中心)、`rot`(度,逆时针)、`k`(>1 拉伸、<1 压扁)、`axis`(拉伸方向,度)、`scale`、`eyes`(0 闭 .. 1 睁)、`lid`('blink' / 'sleep' / 'happy' 闭眼形状)、`look=(dx, dy)`、`brow`('determined' / 'up' / 'worried')、`mouth`('smile' / 'grin' / 'o' / 'flat')、`blush`、`shadow=(gx, gy, 宽, 浓度)`、`clip`(地面 y,以下不画:钻土)、`only='cap'`(只画帽子:树苗顶上)、`lead=False`(不推动 follow 层)、`speed=False` / `speed_min`(自动速度线)。辅助:`rest(gx, gy, rot, k, axis, normal)` 让角色立在地面点上;`anchor(px, py, local, rot, scale)` 让局部点(默认果柄尖)落在某点上(挂在枝头);`ease(u, kind)`(in / out / inout / sine / back 回弹 / elastic)、`spring(u, cycles, damp)` 衰减抖动、`arc(p0, p1, 高, u)` 抛物线跳跃;`pose(t)`、`lead_x(t)`、`when_at(x, lead, dur)`(角色到达 x 时开始的时间窗)+- 场景:`paper()`;`wash(pts, 颜色, reveal='x'|'-x'|'radial'|'pop', origin, dashes)`;`ink(pts, 宽)` / `inks(paths)` 藏青细墨线(压力收笔、轻微手抖);`ground(pts, ticks=True)` 地平线加「v」字小草;`land(top, 颜色, left_edge, right_edge, dashes)` 山坡(顶线样条、毛糙的崖边、蜡笔短线);`hill(top, 颜色, outline)` 远山(只在顶上一条细灰线);`tree(x, base, top, canopy, branch)` 秋天的橡树;`sun(cx, cy, r)`(圆盘弹出,光芒一根根画);`cloud(cx, cy, w)` 厚涂白云带淡紫投影;`water(x0, x1, y)` 小河;`shape(polys, 填色, 描边, pop)` 带细墨边的小物件;`flower(x, y, h, kind)`、`tuft`、`cattail`、`leaf_on_ground`、`mound`(土堆,画在角色上面,能把它埋起来)。通用计时参数:`when`、`follow`、`pre=(t0, t1, upto)`(follow 层左边一段先按时间画)、`xa / xb`(follow 的起止 x)、`z`+- 道具:`sprite(polys, 填色, veins=)` 预画一个小道具;`prop(sprite, t0, t1, fn)`,fn → dict(x, y, rot, sx, sy, alpha, ghost),每帧仿射贴上(飘落的橡叶用 sx 模拟翻面,落水后 sy=0.5 平躺);`oak_leaf(长, 宽, lobes, base, angle)` 模块函数给橡叶轮廓+- 特效:`fx(kind, t0, x, y, ...)`:'impact' 冲击线、'dust' 白色尘团、'ripple' 水波、'specks' 土粒、'sparkle' 四角星、'confetti' 彩纸屑;速度线按速度自动加+- 手写字:`write(text, x, y, size, when, underline=((x0, x1), y), weight)`:文字遮罩 Zhang–Suen 细化成单像素骨架,像手一样走骨架(去斜体后最靠左的端点起笔、路口尽量直走、走到头抬笔跳回),每个墨像素取最近骨架点的时刻+- 输出:`frame(t)`;`gif(path, fps=15, t_end, hold)`:逐帧渲染(一次只留一帧浮点),共用一张加权调色板 + 固定 4×4 Bayer,没变的像素写成品红透明索引;`journey(times, t_world, arc, labels, prop_arcs, world_fx, final, props)` 旅程总图;`stage(name, t)` 存某时刻的关键帧,`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度+- 色板常量 `PAPER INK PENCIL GRASS MINT LAVENDER SUN WATER NUT CAP CONFETTI`+**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。## 三、毛病清单(都真实出现过)@@ -1297,6 +1561,288 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask| 整组徽章太小,画面上方三成空着 | 设计坐标统一乘 1.14 再上移;针单独按画布坐标摆,别跟着放大推出画面 || 动图里金色锁边和营火被量化成橙褐色 | 调色板样本里暖色饱和像素 ×5、亮色 ×2(暖色平均误差 9.5 → 5.6) |+**蓝图工程图**++| 问题 | 改法 |+|---|---|+| 细字和细线在大片区域里糊掉,像对不上焦,备注、标题栏、引出文字整段看不清 | `core.blur` 会把亚像素 sigma 量化成 0 或约 1.4 像素,「压框接触不良」的区域整片被糊了 1.4 像素:改用库里自带的真高斯 `_gauss`,接触好 0.55、接触差 0.9;单笔画字的笔宽至少 1 像素 |+| 「断墨」噪声被做成一大片,一行字的后半截淡掉 | 只在 3 像素尺度细噪声的 0.84–0.96 峰值上断墨,再乘一个 90 像素尺度的门控;断墨只减 45% 墨量 |+| 小数点不见了:17.90 印成 1790 | 句点是 0.08 个单位长的线段,圆头只剩 1 像素:短于 0.2 单位的笔画一律画成实心圆点 |+| 标题栏里的仿宋中文印不出来;加粗后又糊成一团 | 仿宋笔画太细,晒图的 S 曲线把它当成浅铅笔线:先压窄(0.82),再 3×3 最大值滤波、灰度 ×1.35 实化;别用 5×5,会糊 |+| 剖面里的螺旋楼梯像一层层楼板 | 被剖到的踏步是一条条实心白条,远半边只有 fine 线:远半边的踏步前沿、贴墙的踏面—踢面锯齿改用 thin,加一条贴墙的螺旋底面线;被剖到的踏步只留 0.13 m 厚 |+| 剖面墙上的窗洞像裂缝或墙体错位 | 窗洞改成内大外小的八字口(外口 ±0.38 m、内口 ±0.55 m),窗扇退进墙面 0.25 m,画一粗一细两道 |+| 尺寸数字压在剖面线上读不出来 | `dim()` 默认 `clear=True`:写数字前先把它后面的剖面线刮掉——制图员本来就这么做 |+| 比例尺刻度乱了,有一截白条跑到别处 | 把「每格像素」当成了「每单位像素」:接口改成 `scale_bar(x, y, px_per_unit, units)`,刻度用真实数值 |+| 透镜详图里的棱镜像一串叠在一起的飞刀和箭头 | 棱镜画太大了(进光面很长):光路缩短到 L1 0.1 m、L2 0.03 m,棱镜里加 30° 的细剖面线表示玻璃 |+| 详图里的灯室檐口和窗台画成两块大白方块,还盖住了说明文字;穹顶弧线一直伸到图框 | 改成细线框加金属交叉剖面线;穹顶只画起拱的一小段,下面用折断线截断;光束说明挪到详图上方 |+| 平面图的 UP 箭头画成了整整一圈,看不出是箭头,跟铅笔辅助圆混在一起 | 只画约 205° 的弧,起点一个圆点、终点箭头,UP 写在起点;去掉同心的铅笔圆 |+| A–A 剖切符号撞上剖面右侧的引出文字;低处标高(±0.00、−1.80)压在岩石和海浪线上 | 剖切线缩到墙外 0.56 m,两张图整体左移、引出文字列从 806 起;低处两个标高挪到剖面右边,海浪线在标高前截断 |+| 水渍像一块灰色圆饼 | 按「水洇开再分两次干」建模:两道干燥前沿各留一条清晰的褐色潮线,里面只淡化约三成、带斑驳 |+| 折痕交叉点像一颗亮星 | 交叉处磨损半径 7 像素、只淡化 38%,折痕磨白只混 0.2 |+| 动图里红铅笔变成灰蓝色 | 调色板先对全部关键帧中值切分 238 色,再从红铅笔像素里单独切 17 色补上(`claude_drawing/blueprint_work/make_gif_bp.py`) |++**儿童蜡笔画**++| 问题 | 改法 |+|---|---|+| 第一版色块像一层均匀的砂纸,看不出来回涂的笔道,和彩铅、喷砂分不开 | 纸纹先沿笔道方向拖着平均一遍(双线性取样 ±6 px,与原纸纹 0.35 : 0.65 混合)再重新均衡,露白的小坑被拉成顺着笔道的短条;笔道间距 = 笔宽 × (2.3 − 1.6 × density),每道压力 = pressure × (0.84 + 0.36 × 慢噪声);纸纹改细(1.7 / 3.8 / 14 px 三层) |+| 蜡块像橡皮泥浮雕,空白纸像拉毛墙 | 打光时蜡的高度 1.35 → 0.55(再模糊 1.6),纸纹浮雕 1.1 → 0.65 |+| 山坡线从人脸、裙子上横穿过去 | `line(..., avoid=c.grow(OBJ, 10))`:线走到东西背后就停;所有东西的内部遮罩先收进 OBJ |+| 后画的郁金香、蝴蝶、签名压在草地上,红 + 绿发褐、紫字看不清 | 蜡笔是半透明的乘性混色,盖不住底色:东西先勾线,大片(天空、山坡、草地)`avoid=U(OBJ, c.drawn())` 绕着涂(孩子本来就是这么涂的),最后在白纸上给东西上色 |+| 胳膊、手、狗腿、花茎被草地涂没 | avoid 里加上 `drawn()`(已经画过的线);狗腿在身体上完色后再用 17 px 重压一遍,脚加一个圆点 |+| 天空绕着标题涂,蓝笔道还是扫进字里(红字发紫、橙字发绿) | 绕开处的转折要「小心」:停在边界内 0.45 × 笔宽、不过冲;被绕开的东西覆盖率 × (1 − 0.9 × 遮罩);比 0.7 × 笔宽窄的空隙不进笔 |+| 标题像粗黑体,「我」糊成一团、右半边丢了 | 细字体字形先 Zhang–Suen 细化成单像素中心线,再用圆头蜡笔膨胀(默认字号 × 0.068,标题指定 11.5 px);手抖扰动 0.045 × 字号、尺度 0.55 × 字号;字距按字形实际宽度算(西文才不会散开) |+| 签名夹在郁金香的茎叶之间看不清 | 挪到花下面的空处,草地给名字留一圈 18 px 的空白(`c.grow(名字的蜡, 18)`) |+| 纸上的蜡笔:包装纸像理发店转灯 / 条形码,蜡像塑料,第三根竖着像立在纸上 | 包装纸:两头各两道细线 + 一段波浪纹 + 中间浅色标签上一行伪文字(无商标);蜡改哑光(高光指数 12、强度 0.13),断面略亮;半径 22 px(直径约 7 mm,接近真蜡笔放在 1920 px 宽的 A4 上的比例),只放两根:一根用秃的、一根撕了半截纸的断蜡笔 |+| 蝴蝶翅膀圈涂太满,糊成两团还压住身子 | 翅膀离身体 7 px、改来回涂、加黄点;身子和带圆头的触角最后画 |+| 墨镜只是一块灰黑,看不出是玻璃 | `burnish()` 把黑蜡压进纸坑:白点合上、和下面的黄混成深橄榄、带一点蜡光;皮球同样处理 |+| 烟囱的烟是等半径螺旋,像一根弹簧 | 圈越往上越大(9 → 33 px)、往右上飘,灰色轻压 |+| 动图最后一帧 EOFError | 最后一个 `stage()` 和成品相同会被合并:`save()` 前不再调 `stage()`(第四节已有这条) |+| 动图里小面积的紫、粉发灰 | 调色板样本加权:饱和像素 ×5、亮色 ×2(1.47 → 1.33 MB,0 帧对不上) |++**绿屏终端 CRT(荧光字符画)**++| 问题 | 改法 |+|---|---|+| 桶形畸变用的是归一化坐标里的交叉项(u·v²);宽屏下,角上的字被剪切成斜体 | 改成真实像素里的径向畸变 src = p·(1 + k·\|p\|²/hw²),k = 0.065;字不再歪,四边照样外鼓 |+| 反白的 YES 和状态栏里的黑字看不清:点拉伸和视频带宽把 1 个点宽的暗笔画吃掉了 | 点拉伸改在半点分辨率上做,而且放在反白之前;状态栏改用 `dim+rev` |+| 云的内部用 - = + 这类像线的字,远看是一团 `/=-\` 乱码 | 云用 `outline='cloud'`:斜坡一律打 ( ),平顶、平底打 _ . - '。内部只用 . :,亮部靠 dim → normal → bold 提亮,不换更花的字 |+| 剪影成对出现 `//`、`((`,两个格子都当了边 | 剪影只留一格厚:相邻两格是同一个字时,留覆盖率最接近 0.5 的那格,另一格按覆盖率归入里面或外面 |+| 云底是一排扇贝 `(...)(....)` | `puffs(base=整数行)`:底部 `flat` 行内按云的宽度补满,并闭合泡泡之间的小缝;整条云底打成一根 `_` |+| 细线勾的月牙在 5×7 字里像 S 或 < | 月牙不描边,用 bold 的 % # @ 填满(`outline=None`)。内圆半径约等于外圆,向右偏约 0.45r |+| 太阳像六角蜂箱,往下的光芒像腿 | 太阳用 `cloud` 轮廓加径向渐变 . : + * % # @;光芒只画地平线以上那 9 根 |+| 瘦高格子里拿覆盖重心的方向当法线,斜边的字选偏 | 法线按格子尺寸反比换算:nx = −mx/cw,ny = −my/ch |+| 光晕把整屏蒙成灰绿,失去黑底 | 中、远两层光晕只对 L² 做(bold 发光,dim 不发光);亮度底(brightness)降到 0.016 |+| 房子比天气还抢眼;光标块贴着反白的 YES,连成一个框 | 墙和屋顶改 dim,只有夜里的窗户用 bold #;提示符后面打了半条命令 `forecast --tomorrow`,光标停在命令末尾 |+| 动图里挡圈边上振铃出一圈亮边,暗玻璃和窗户倒影出色带 | 缩到 720 宽用 BOX,量化前每帧叠同一张 4×4 Bayer(约 ±2.4),调色板样本里绿色像素 ×4、亮像素 ×2 |+| 峰值内存 834 MB | 拨轮、LED、压纹图标改在局部窗口里算;机壳斜面朝向屏幕的程度缓存起来;不再每次渲染都建整幅 int64 网格。降到约 0.73 GB |++**热成像**++| 问题 | 改法 |+|---|---|+| 地面被底部色标栏挡住,猫只露半身,脚印看不见 | 相机再往下俯(灭点 y 150 → 100,焦距 1900 → 1750),地面留出约 200 px;底栏压到 78 px |+| 自动直方图均衡把 20–24 °C 的房间拉成一大片品红,猫和墙同色 | 改用手调色调曲线 `camera(curve=)`:冰箱内 0–0.05、房间 0.23–0.29、脚印 0.35–0.5、猫 0.6–0.72、锅 0.9、只有火圈到白;直方图均衡只混 0.22,留一点局部对比 |+| 锅和水壶饱和成两个白块,锅像个大马克杯 | 曲线把 100 °C 放在 0.91;锅改宽矮,加卷边和两侧环形把手;抛光锅盖 `emissivity=0.55`,读数比锅身低一档,盖子自己显出来;锅身、壶身、面包加 `limb=`,轮廓处变凉、有体积 |+| 烤箱门是画面正中一块巨大的橙色长方形,抢焦点,还和猫同色 | 烤箱降温(门框 23–26.5 °C、玻璃 26.5–31.5 °C,只有顶部门封 46 °C);把手上搭一条湿抹布(17.5–20 °C,蒸发降温),把大块面打断 |+| 灶后墙面的热晕像一根发光的柱子一直通到画面顶 | `soak` 只取锅后到油烟机下沿这一块,reach 38、strength 0.4,`onto` 限在油烟机下沿以下、挖掉锅壶罩 |+| 冰箱冷坑在地上看不出来:8–18 °C 都挤在色板最暗的一段 | 铁红色板低端提亮(0.14 → #1f0e6e,0.24 → #3d1192),曲线给 2–19 °C 留出 0–0.23;冷坑芯部降到 6.5 °C |+| 冷坑用噪声阈值做边,成了一片迷彩斑块 | `pool()` 改成从源头分出的几条软冷舌:按地面透视压扁、沿舌头衰减、再模糊 |+| 冰箱里一片死黑,格板和瓶子都看不见 | 格板前沿画成 10.5 °C 的细亮线,瓶罐比内壁高 6–8 °C;冷冻抽屉面板改回接近室温(它有保温层),顺着它往下淌的冷气才显得出来 |+| 冰箱侧板压到下柜前面,多出一条斜边 | 侧板只画台面以上那段和下柜前沿以内的 10 cm |+| 冰箱底的压缩机格栅是一道粉色横杠,挨着黑色冷坑像故障 | 删掉 |+| 猫像一块平涂剪影;Sp3 十字盖住了眼睛 | 加 `limb=`(掠射角发射率下降、毛尖更凉),胸口薄毛加 1.4 °C,后腿折线压暗;眼睛 38.6 °C 并把曲线 35–39 °C 段拉陡;Sp3 挪到胸口 |+| 后腿椭圆的轮廓变凉一圈,看着像一盘蚊香 | 后腿的 limb 降到 1.2 °C |+| 线剖面插图的曲线是暗紫色画在暗底上 | 曲线画成白线加黑描边,下面另画一条按色板着色的色带 |+| L1 虚线压在脚印上 | 虚线改成 1 px |+| 动图里蒸汽和墙面热晕出一圈圈色带,OSD 白字被量化成淡黄 | 调色板取样时饱和色 ×5、亮色 ×2,每帧叠同一张 4×4 Bayer(约 ±2.4 级);强制留出纯白、纯黑、REC 红、最冷标记蓝和两级灰 6 个色位 |++**代尔夫特蓝瓷砖**++| 问题 | 改法 |+|---|---|+| 钴蓝像荧光宝蓝,一看就是屏幕色 | 按 Beer–Lambert 逐通道吸收算颜色,k = (2.3, 1.95, 0.95):淡染是灰蓝,浓线是紫藏青(`COBALT_K`) |+| 窗户倒影是一团闪烁的白碎点、边缘起毛,看不出是窗户 | 去掉小尺度橘皮纹,釉面起伏只留约 46 px、幅度 ±0.15 px 的缓波,再加每块砖的鼓起(±0.3 px)和倾斜;窗棂宽度要大于高光柔化宽度(soft 3.5),否则窗格糊成一片白 |+| 高度场求导把 x、y 写反,倒角打光和倒影按错的轴偏移 | `np.gradient` 返回的是 (d/dy, d/dx),要写 `hy, hx = np.gradient(h)` |+| 开片满墙都是,像碎冰 | 每块砖的开片量取 Beta(1, 2.6),线只压暗 13%,多数砖几乎看不见 |+| 一条裂纹穿过好几块砖,像钢笔线 | 裂纹按砖编号裁剪,只在一块砖里、到砖缝就停;只压暗 50% |+| 砖缝 5 px 太宽,整面墙像浮雕网格 | 砖缝 3.6 px(13 cm 砖约 3–4 mm),倒角 3.4 px、高 1.3 px |+| 云是一块扁长方形 | 云是一串圆凸起的上包络:左高右低(风从左来),每个凸起单独一笔、凸起之间留尖角;底线断成两三截,晕染从底边往上变淡 |+| 树冠像一串气球、花椰菜 | 只描外轮廓的扇贝边;里面在背光一侧画两圈缩小的扇贝短弧;第二遍晕染用渐变,不要每团一个月牙 |+| 船上的面粉袋像一排舷窗;披水板像挂着的布袋 | 袋子坐在甲板上、只描上半圈和扎口;披水板画成上窄下宽的扇形木板,先画并 `occlude`,船身排线不穿过它 |+| 远处的树林像一排鸡蛋;烟像电线 | `bushes()`:地平线上一簇簇小扇贝丘配淡晕染;烟是一串越来越大、越来越淡的卷 |+| 人像穿裙子的小孩,狗像腊肠 | 人:头发和发梢往前飘、张嘴、翻袖口、马裤、长袜、带扣鞋,上身前倾、后脚踢起;狗:四脚离地的飞扑,耳朵和尾巴往后飘,背上一块深色斑,不排线(排线像斑马纹) |+| 晾的衣服垂着不动,看不出有风 | 床单、衬衫的下摆几乎水平地往右扬,挪到近岸空地上,不要藏在树后 |+| 窗户倒影放在右侧单块砖上,是几块纯白、边缘锐利的碎片,远看像砖掉了或渲染出错 | 倒影改成按「滤色」叠在釉面上(`img + (白 − img) × s`,s 最大约 0.65),最亮处底下的蓝线仍透出来;柔化宽度 6、窗格缩小到 112 × 150;挪到画面里右上那朵云和天空上,跨两三块砖,在砖缝处断开错位,一眼看出是釉面反光 |+| 崩瓷是几个橙色小点,像锈斑 | 半径 5–11 px,露出灰褐坯体(`BODY`),靠光一侧被釉边投影、背光一侧的坑壁亮 |+| 动图 3.4 MB | 调色板样本里蓝色像素 ×3;和屏上已显示颜色相差 ≤ 10/255 的像素记透明 → 1.7 MB |++**洞穴壁画(赭石颜料)**++| 问题 | 改法 |+|---|---|+| 颜料发灰,像褪色的水彩 | 喷涂内部只剩一半覆盖(rim 0.35 × 斑驳 × 0.32 的烟):主色 density 0.95–0.97、rim ≤ 0.2,空气里的烟降到 0.16,指数色调曲线之后再加对比度 1.18、饱和度 1.18 |+| 岩面像绗缝被、一团团棉花云 | 溶蚀扇贝纹单元 70 px、深 6 px 太规整:放大到 110 px、深 1.8 px、只在一片片区域出现;大起伏用光滑噪声会像云和烟,叠一层脊状噪声 (1−\|2n−1\|)² × 10 px 做岩脊(3 次方、振幅 22 会变成一块块台地) |+| 岩面像砂纸 / 揉皱的纸 | 低角度火光会把逐像素颗粒放大:高度颗粒从 0.55 降到 0.12,40 px 中尺度起伏只给 1.1 px,albedo 颗粒 0.022 |+| 满墙小黑点像波点,改浅后又成了白色亮点 | 小溶蚀坑减到 60 个、深度 0.3 × 半径,坑里 albedo 压暗 30%(积了泥),掠射光下就不会只剩亮边 |+| 墙上一团团「脏影子」 | 是油灯的掠射光把 80 px 的大起伏拉出长影:大起伏降到 46 px,油灯不算投影、只有篝火算,投影最多压暗 70%、soft 5 px |+| 鼓包在火堆对面投下黑团,像污渍 | 小鼓包(18 px)在掠射光下只剩投影:只给要画动物的地方放鼓包、高 26–38 px,而且让动物盖住它的背光面 |+| 折痕末端多出一道刮痕 | 有符号距离在折线末端沿最后一段的延长线翻号:按弧长在两端 220 px 内淡出 |+| 手印喷绘像红色描边的椭圆、甜甜圈 | 用「整只手模糊一次」做喷雾,细手指周围几乎没有颜料、外沿一刀切:改成 11 口气,每口一个高斯团、瞄准指尖和手侧(2/3 瞄上半部),叠加后 1 − exp(−1.8·c),边缘自然淡出,外围撒雾点;前臂只挡一半 |+| 手印被烟熏成灰手套 | 烟熏 0.22、烟柱窄(spread 0.22),手印 density 0.95、spread 26 |+| 后半身两团黑大腿 | 腿的笔画从髋部 0.13 个身长宽起笔,涂黑时把整条大腿涂了:`legs` 部件 = 腿 × (1 − 身体),只剩身体轮廓以下的部分 |+| 野牛头和隆肉糊成一大团黑,看不出脸 | 隆肉吹黑,头用深红 0.62;眼睛先点一个浅色杏仁(kaolin)再点黑瞳 |+| 野牛像长方箱子配桌腿 | 重画轮廓:前高后低的背线、肩上高耸的隆肉、深胸和须、腹线往后收、小屁股、短细腿 |+| 马鬃和脖子之间漏一条白缝;区域(头、腹)漏到腿上 | 鬃毛笔画压在颈脊线上;各区域只和 `body` 求交,不和整个剪影求交 |+| 鹿角像一把小梳子 | 鹿角放大、主干向后扫,5 个分叉,宽 0.04 → 0.012 个身长 |+| 裂缝像吊着的细绳、像小树枝(让上面那匹马像挂在绳上) | 改成细的之字形窄缝:两端收尖、宽度随机、深 4 px、最多一条短分叉;别从动物身上穿过 |+| 篝火是一团白光 | 火焰发光降一半,每条火舌按 2× 超采样画、只糊 1.3 px,15 条,外橙内黄,中心光斑 0.55;篝火功率 1.6、衰减距离 1150 |+| 火堆石头像骨头两头的圆钮、柴像哑铃 | 16 块小石头(11 点不规则轮廓、深色、圆顶幂 0.85)排在火堆两侧和后面;柴从火心朝观者方向辐射,按圆柱打光(顶部被火照亮)加发光裂纹 |+| 研磨好的颜料堆像平的色块 | 堆高 1.3 × 半径、颜色边缘放软,低角度火光才照得出一面亮一面暗 |+| 掉色的小片像彩色纸屑、像白灰尘 | 12 点圆滑小片、1.5–4 px、只掉在覆盖 > 0.6 的地方、28 片;露出的石面 × 0.93,不加高差(否则掠射光给每片一圈亮边) |+| 炭条起稿在动图里看不见 | 起稿线是一条约 2.6 px 宽的带(先按线宽糊一下再取 0.12–0.88 的等值带),强度 0.7,画两遍 |+| 炭笔轮廓像一串珠子 | 覆盖 = 线带 × (0.5 + 0.5 × 抓附),不要全靠岩面「牙口」 |+| 野牛尾巴尖像棒棒糖、火星像雨丝 | 尾尖改成一笔短而粗的黑色笔触;火星减到 11 颗、2–6 px、只在火舌上方 |++**1-bit 早期画图软件**++| 问题 | 改法 |+|---|---|+| 写一行 Shadow 样式的字,整张画被擦成白的 | `Image.fromarray()` 出来的图是只读的,`ImageDraw.floodfill` 在只读图上静默不做事,找字腔的泛填就把整张画都当成了字腔;先 `.copy()` 再填(油漆桶 `bucket` 用的是同一个泛填) |+| 蝴蝶放在格子布窗帘和云前面完全看不见;套索的行军蚁把背后的窗帘图案也框进去,一团乱 | 小东西放到最空的底上(天空的白带);蝴蝶改成白翅膀 + 黑翅尖 + 黑点,1-bit 里白底黑边最好认;成品的选区用矩形选框,套索只在纯白底上用,或把物体自己的遮罩传给 `select(lasso=)` |+| 窗台下的喷枪阴影像一条脏草地,花盆脚边和云底的喷点像乱涂 | 喷枪只在窗台下沿浅喷一道(半径 8、密度 0.22),上面先垫一条 50% 灰图案;花盆投影改成灰图案小椭圆;云底不喷 |+| 窗外的山、草地、栅栏全是图案,花盆糊进背景 | 删栅栏,草地换最稀的 `dots`,山用 25%;花盆加深(盆身 50%、背光侧 75%),盆沿最浅 |+| 天空顶带用 12.5% 太密,窗户反而不比墙亮 | 天空 `mist → faint → 白` 三条带,墙纸用 `sprigs`:窗户(光源)是全画最亮的地方 |+| 窗外的圆树正好在苗或向日葵后面,像花上长了根棒棒糖;窗户竖棂正好在第 14 天那盆苗后面,像插了根支架 | 远景小物不要和前景植物重叠(删了树);盆往旁边挪,避开竖棂 |+| 右边窗帘的坐标没镜像,下半截藏在黑猫后面 | 只画左窗帘,`copy(rect, to, flip=True, mask=窗帘遮罩)` 翻转复制到右边(当年的 Flip Horizontal);带遮罩,背后的墙纸不跟着走;猫挪出窗帘 |+| 正面坐的黑猫是一团,胡子画在窗帘上 | 改成侧面:椭圆臀、斜椭圆胸、前腿、头、口鼻、两只三角耳拼成剪影,再用白线勾腿和臀的分界、项圈、耳内和眼;胡子用 XOR(`invert`),在黑脸上是白、出了脸是黑 |+| 喷壶嘴和水滴压在格子布窗帘上读不出来 | 喷壶挪进窗洞,壶嘴尖对准第 2 天那盆的盆沿,只留一滴水;左边窗台改放种子袋,标签行补上 day 0 |+| 两盆挪近后 day 2 和 day 14 的标签撞在一起 | 标签中心不跟盆走,单独给一组坐标 |+| 放大镜窗压在主窗口标题栏上 | 放在这一阶段还没画的日历位置;放大范围框住眼睛、耳尖和一点墙纸,才看得出「一格一格」 |++**古希腊黑绘陶瓶**++| 问题 | 改法 |+|---|---|+| 马像趴在地线上游泳:肚皮离地只有 0.1 个马高,四条腿水平伸着 | 身体抬高(肚皮 0.43、鬐甲 0.93 个马高);近前腿高高折起、远前腿向前下够地、两条后腿向后下蹬,蹄子落在地线上 |+| 驾车人比马背还矮,像个小玩偶 | 车厢抬到轮轴上方,车夫身高 0.9 个马高、前倾 0.24,头和马耳平齐;胸墙挡住白袍下半截 |+| 白马夹在马队中间,只露几条白腿 | 白马放在最远的一匹,头抬得最高(颈部弯折 0.2),并且给瓶子正面中央的那辆车 |+| 颈部棕榈叶饰像一排电线塔:花瓣是直刺,卷须竖着往上走 | 9 瓣圆头扇形(中间长两边短),红色掌心描一道刻线;卷须改成垂花弧,从掌心下方荡到莲花挂点;莲花一长瓣加两瓣外卷 |+| 左边马队上一大片白雾,像多了一匹白马 | 那是大柔光箱在黑釉上的反射:箱子收窄成一条竖光(反射方位角 -0.90..-0.76)、强度 9 → 6,另加一层很弱的大面积柔光 |+| 圈足正中一个白三角 | 是环境里「天花板」方框光源在圈足顶面的反射,改成一层很柔的穹顶光 |+| 做旧过头:结壳成片白云,根痕太亮,加白剥成斑点狗 | 结壳只在下半身、阈值提高、强度 0.7;根痕透明度 35–75;加白只按大块剥掉约 20%,剥处留 20% 和一层哑光残影 |+| 修补填料是一个太规整的浅米色椭圆,缺口是白色小三角 | 填料轮廓加 0.42 的 fbm 抖动、调成偏暗的赭橙,黑色部分补成灰黑,外面几道胶合裂缝;缺口用 24 点 fbm 轮廓,露出的胎色改成暗橙 #c98a60 |+| 圈足的黑釉像木纹 | 薄釉发红的横向条纹噪声太强:釉厚底数提到 0.78、条纹权重降到 0.08;未烧泥釉的条纹也一起减弱 |+| 把手像两根铁丝;粘土上拉坯横纹太显 | 管径 0.046R → 0.072R;拉坯纹的法线扰动 0.018 → 0.009,只在反光里隐约看得见 |+| 动图里暗墙聚光灯和素坯出一圈圈色带 | 调色板从所有关键帧加权取样(饱和色 ×5、亮色 ×2)再中值切分,每帧量化前叠同一张 4×4 Bayer(约 ±2.4 级),透明占位色用品红 |++**铅笔素描**++| 问题 | 改法 |+|---|---|+| 轮廓线几乎看不见,整幅发白 | 1.5 px 的细线抗锯齿后每个像素覆盖只有一半,纸纹阈值又按覆盖算,线被吃成稀疏的颗粒:笔尖能压进纸纹多深按 √覆盖 算(按压力,不按像素覆盖);勾线的石墨量 ×2(`gain`),散笔 ×1.6,顺形排线 ×1.3 |+| 纸像粗纹水彩纸,满屏一块块斑 | 纸纹以约 1.6 px 的细颗粒为主(细的一层 σ 0.3 倍,粗的一层 σ 1.3 倍),毛毡纹只占 0.05,浮雕光 0.07;细颗粒 σ 到 0.7 就成了砂纸 |+| 侧锋铺调一条条斜带、一块块云斑 | 三遍、每遍角度差 11°,行距 0.42 倍笔宽,压力只抖 ±10%,笔锋边缘柔化 0.22 倍笔宽;侧锋笔画按 8 px 重采样(连同栅格化提速,大面积侧锋快约 3.6 倍) |+| 排线块与块之间的接缝成了一道道亮带 | 收笔渐细只占笔长的 20%(原来 32%),每笔在接缝处多出或缩回 ±3 px,接缝每行漂移一点 |+| 边缘「只剩线稿」像喷枪渐隐 | 调子按 finish^0.6 衰减之外,排线和侧锋按笔画中点的 finish 整笔整笔地丢,越往外越稀;线条在纸边保留 35% 压力 |+| 纸擦笔把画面边上的灰抹到对面去、顶边出黑团 | 拖抹不能用 `np.roll`(会卷绕),改成边缘延伸的平移 |+| 车身周围一圈白边 | 擦笔在遮罩里做归一化模糊(`contain=True`):只匀开遮罩内的石墨,不把车身那块空白「抹」进墙 |+| 墙上的车影像一辆糊掉的幽灵车 | 影子不带辐条,边只模糊 1 px,只用排线不用侧锋铺底,灰泥墙晕染时绕开影子,调子降到 0.4,车本身先被读到 |+| 转角侧墙成了一块奇怪的灰色楔子 | 楼太矮(顶边只到 y −60,相当于 1.6 m 高),顶边斜着落进画面:顶点放到 y −1400(三层楼),侧墙远端用噪声参差地收掉,招牌处挖空 |+| 车架是一条白色剪影,只有两根细线 | 车架当成深色漆管:沿管子顺形排线,越往背光侧越重,最外缘留一点反光,再用纸擦笔顺着管子匀一遍,最后橡皮擦出一道清楚的高光 |+| 法棍几乎全白 | 先侧锋铺一层面包皮的底色,再沿面包长轴两遍交错的顺形排线,下沿压一条 4B;刀口用可塑橡皮提亮,下唇再描一道深线 |+| 门是一整块深灰,抢了车 | 门降到 0.42,做成四块凹板:上沿和左沿一条暗边、下沿和右沿用橡皮擦出亮线;最深的只留门洞左壁和顶 |+| 页边笔记压在石子路上读不出 | 笔记和色阶两块区域不画石子轮廓,也不排线 |+| 色阶下面的 2H–8B 看不清 | 字号 22、用 2B、压力 0.95 |+| 出图 40 秒、峰值 1 GB | 栅格化时每段的宽度和灰度先整体算成列表;遮罩(多边形、粗线)只在包围盒里画;坐标用广播的行列向量而不是满幅 mgrid;纸纹用 float32 的小核卷积;用完的满幅遮罩及时 `del`:11 秒、约 0.72 GB |+| 动图 2.07 MB | 纸纹颗粒每次叠化都整片重编码:叠化帧里和屏上已显示颜色只差 ≤ 7/255 的像素沿用上一帧(透明),1.26 MB |++**X 光片**++| 问题 | 改法 |+|---|---|+| 恐龙骨架是全画的主角,却又淡又小,头骨被箱子圆角切掉一块 | 骨头半径和厚度都 ×1.6(铸的玩具骨头本来就粗),整体放大到 1.02 倍;脖子放低、头骨下移 22 px、后移 6 px,整副骨架挪到圆角以内 |+| 整幅画太暗,物体像沉在墨水里 | 显示曲线满白点从 A=11 降到 8.5、拐点 0.32 → 0.30;荧光辉光 0.35 → 0.5 |+| 毛衣和牛仔裤看着像比空箱子还暗的「黑垫子」 | 量了一下其实比空箱子亮(红通道 35 对 19),是被亮的折边衬暗了;密度提高(毛衣 0.33 → 0.5、牛仔裤 0.9 → 1.15),加针织 / 斜纹纹理,折边才显得是布 |+| 材料伪彩视图整片橙色:橡胶传送带也算有机物 | 真机做空气校准时传送带就在里面:`belt()` 记下自己的衰减,伪彩视图先减掉它,空处才是白的 |+| 骨架里穿的钢销把 Zeff 读数拉高 | 读数先用物体外一圈的中位数扣掉背景,再取逐像素 A_lo/A_hi 比值的中位数(不用总和之比),石膏读 14.4、水读 6.9 |+| 图例「INORGANIC」挤进了 METAL 色块 | 图例按字宽排,不按等分 |+| 结论表的字跑出侧栏 | 每行压到 40 字符以内(16 px 等宽) |+| 放大插图写着「×0.8」:框的是整副骨架,其实是缩小 | 只框头骨和胸腔,放大约 1.4 倍 |+| 1 号标签压在箱子亮边和密码锁上,看不清 | 标签文字下垫深色底板;读数和标签放同一行 |+| 八根伞骨偏移量正负对称,两两重合,看着只有四根棍子;伞面几乎看不见 | 伞骨绕伞杆的相位错开 0.3 格;伞面 14 层、密度 1.3,加弧形折痕 |+| 传送带接头(一列钢钩)挨着侧栏,像一条拉链 | 挪到画面最左边 |+| 动图用一张调色板时,伪彩插图里的绿骨架变成灰蓝,CLEAR / REMOVE 发白 | 调色板分两段切:蓝色胶片像素切 186 色,彩色像素(橙、绿、红、琥珀)切 69 色;每帧叠同一张 4×4 Bayer(约 ±2.4 级) |+| 峰值内存 0.86 GB | 散射雾在 1/4 分辨率上算;模糊改用切片视图(不用 `np.take` 复制);OSD 辉光改用 Pillow 的 uint8 模糊;暗角用广播不用 `mgrid` |++**1930 年代黑白橡皮管动画**++| 问题 | 改法 |+|---|---|+| 画面太干净,像矢量插画套了个滤镜 | 镜头柔焦 0.85 px、四角再糊一档;颗粒 0.07、按 √(v(1−v)) 在中间调最重,再叠一层半分辨率的团粒;黑位抬到 0.075、白位压到 0.93,再加片门晃动和圆角片门 |+| 太阳的拳头像带盖的玻璃罐、盐瓶 | 拳头 = 手掌椭圆 + 顶上一排 4 个小圆(卷起的手指,成扇贝边)+ 指缝短线 + 横在前面的拇指;袖口缩短到 0.36 |+| 睡帽帽檐是一个扁椭圆,横在枕头上像一圈光环 | 帽子扣在枕头右上角,帽身从角上长出来往右下耷拉,帽檐改成沿帽口的一条宽带;角色头顶不要放任何扁椭圆 |+| 枕头像方盒子、像吐司 | 超椭圆指数 0.5 → 0.72,四边中点往里收 13%、四角往外顶(枕头角),不倾斜,四角加折痕短线 |+| 拖鞋像礼帽、像汉堡 | 稍微俯视来画:长椭圆鞋底 + 后半开口露出鞋里(浅色鞋口、中灰内底)+ 只盖住前半的毛绒鞋头 + 绒球,眼睛画在鞋头上 |+| 太阳一圈尖三角像参考帧里的太阳(也像皇冠);改成细波浪线又像睫毛、小虫 | 扇贝边光晕 + 每个凹口一道粗短的放射短线(长短交替、两端略收) |+| 「RRRING!」字母挤在一起 | 字距 0.78 → 0.9 倍字宽;单双号字反向倾斜 ±10°、上下错开 0.12 倍字号 |+| 踢腿的速度线贴着床头柜像裂缝,跳起的拖鞋下面的竖线像钉子 | 去掉贴着家具的速度线,在踮脚的鞋尖外画三道放射短线(敲桌面);跳起的拖鞋下面画两道「︶」弧线 |+| 绗缝被的棋盘格太抢眼 | 深格只压暗 0.17(原来 0.3) |+| 地板一大片空 | 窗户投下一块梯形阳光(软边 9 px、提亮 0.45)和一道窗横档的影子,拖鞋就在阳光里跳 |+| 动图里铅笔稿几乎看不见 | 铅笔画两遍(1.7 px / 1.1 px),强度 0.8 |+| 动图 2.34 MB | 胶片颗粒让每次叠化都改掉大半像素:和屏上已显示的颜色相差 ≤ 8/255 的像素沿用上一帧(记成透明),自检按实际显示的帧比对,1.54 MB |++**黑白麻胶版画**++| 问题 | 改法 |+|---|---|+| 天上的白色风痕又多又宽,夜空成了一片灰白,大块黑白对比没了 | 风痕从 520 条减到 300 条,宽度从 2–6.5 px 改成 1.6–5 px;只在两条斜云带里刻密,月亮 215 px 以内不刻;天空保持六七成是黑的 |+| 月亮上刻的三个黑斑像一张笑脸 | 去掉月海,只在背光一侧留 5 条同心弧做明暗(V 刀,宽 2.2 → 4.2 px,越靠边越粗);光环每段 0.35–1.2 rad、缺口 0.15–0.6 rad,否则像靶心 |+| 炊烟飘过白色雪坡就看不见,只剩两根黑线;改成一串圆团后,又像一串珍珠、像毛毛虫 | 烟是一串互相压住的团:按弧长累计「半径 × 0.8」排开,越往上越大,铺满整条路径;穿过白色的地方留一圈 2 px 黑边(`outline(cut=False)`);每三团留一道黑色卷纹;两股烟的控制点各加随机偏移,免得一模一样 |+| 烟囱像一架梯子 | 不再刻一排横缝,只刻两道短灰缝,顶上加一顶白雪帽 |+| 老树根部是一大块黑三角 | 根部外扩从 1.9 倍干宽降到 1.05 倍 |+| 树梢一截截平头,像修剪过 | 末梢一级的宽度收到 0.5 px(`brush` 的 `end`),高处的分叉改成 1–2 枝 |+| 人物站在黑房子前,头和墙糊成一片;脸挖成一个白圆,像幽灵;雪花刻在脸上,像一颗星 | 人物挪到雪地上(头顶低于雪野边缘);脸改成朝左的侧脸剪影(额头、鼻尖、嘴、下巴),留一个黑点做眼睛;`speckle(region=)` 避开人物、狗、柴堆和灯笼 |+| 雪橇上的柴像长凳、像木箱 | 改成稍从后方看的柴垛:六根原木的截面排成 3-2-1,白色截面上留年轮和一道裂纹;木身是黑的,顺长刻两道树皮缝 |+| 黑版像压了浮雕,每道白刀痕都有一亮一暗的斜边 | 压印凹凸只留一点:法线明暗 × 0.3,限幅 ±3.5% |+| 套色像机器印的,平得发假 | 套色版加 mottle 0.25:浅色油墨更显纸纹和墨层不匀 |+| 清底的残刀印像头发丝、像铅笔划痕 | 改成顺下刀方向的直短线,1–3 条一组平行(相邻几刀之间的刀脊),数量减到原来的约 2/3 |+| 门前的光先是一个规整的梯形,后来又成了靴子形 | 远端用正弦加随机做成参差边,左右都往外张成扇形;套色版上横着用 U 刀挖几道,黑版的雪脊线照样从光上穿过 |+| 动图里的灯黄被量化成米色 | 中值切分 238 色,再从饱和像素(饱和度 > 0.28)里单独切 16 色补进调色板;透明占位色用品红 |++**VHS 家庭录像**++| 问题 | 改法 |+|---|---|+| 落地灯那一列从画面顶到底一整条白,墙面也被冲白 | CCD 竖向拖影改成按列累加「远超满阱」的溢出(阈值 2.2,只有烛焰这种点光源够得上),不再取每列最大值;灯罩墙上的光晕从 0.9 / 0.45 降到 0.38 / 0.2;泛光阈值 0.85 → 1.0、拖尾阈值 0.95 → 1.2 |+| 被烛光照亮的白奶油也越过阈值,拉出一根宽宽的橙色光柱 | 烛光 0.42 → 0.3、半径 300 → 280;拖影只认 2.2 以上的溢出 |+| 灯罩是一块灰白的平方块,被小彩旗压住,看不出是灯 | 灯罩下移 60 px,避开彩旗;自发光带左右明暗,上下加黄铜边、顶上加灯头和顶珠,外面再加一圈暖色辉光 |+| 前景孩子的上身是一块和墙纸同色的芥末黄长方块 | 换青绿色 ringer T 恤,和满屋的橙撞开;轮廓重画:头大、肩斜,上臂单独画到手肘,前臂伸向桌子,肘和身子之间露出背景;加肩胛骨暗线、发旋放射的发丝、两只耳朵、朝蛋糕一侧的暖色轮廓光 |+| 派对帽太小,蓝白条纹被墙纸吃掉 | 帽子放大到头半径的 1.75 倍,红黄螺旋条纹,朝蛋糕歪 24°,顶上一团锡箔绒球,帽子在头上投一点影 |+| 刚吹灭的蜡烛冒出的烟像几根发光的白棍,过了录像带像又多出几根火苗 | 烟改成灰色、不发光:从细到粗、越往上越淡、带卷曲的一缕;另外「烟量 1.0」和「点着」用的是同一个数,蜡烛状态改成 `'lit'` / 0–1 烟量 |+| OSD 的 0 看成 8,W 看成 U / H,PM 看成 PN | 字符发生器把每个点向右加粗,1 点宽的缝会被填死:0 去掉斜线,W、M 改成 7 点宽 |+| 变焦条的刻度和细边框在录像带上糊成一团 | 用和字体同一套点阵画:外框 + 实心填充 + 一根游标,不画刻度 |+| 泰迪熊坐在锈红沙发上,同色看不见 | 沙发改牛油果绿丝绒,熊改蜂蜜色 |+| 圆环墙纸对比太强,满墙抢戏 | `contrast=0.72` 把图案色往底色收;加纸幅接缝和几像素的错位,看着是贴上去的墙纸 |+| 电视屏幕中间一团橙色反光,像屏幕上破了个洞 | 改成窗户在屏幕左上角的一块冷色反光 |+| 黄色小旗上的白字看不见 | 按旗色亮度自动换字色:浅色旗用深棕字 |+| 掉磁白点一样长,满屏像下雨 | 数量 45 → 24,长度按指数分布:多数是一两个采样点,偶尔一长条 |+| 不存阶段快照时 `stage()` 也做一遍完整合成,出图 13 秒;峰值内存 1.15 GB | `keep_stages=False` 时 `stage()` 什么都不做(范例按有没有 `--stages` 设);泛光的两个大半径在 1/4 分辨率上做;大彩色图的模糊逐通道做:6 秒、0.85 GB |++**扁平矢量**++| 问题 | 改法 |+|---|---|+| 旧版「周末书店」被用户否掉:东西堆满一整面墙,无五官的「企业扁平风」人偶比例别扭,满屏单一蓝色显得压抑 | 重做成风景:几层大形状(三角山、波浪丘、圆月)加大片留白的天空;人物只留一个 70 px 的剪影;夜蓝、紫的冷色对橙、黄沙的暖色,一共 7 色 |+| 层内纹理像木纹,月亮和云上一道道竖纹 | 纤维纹幅度 1.6% → 0.8%,条纹改短改细(14 × 2 px 网格),每层取不同偏移;全画颗粒 1.1% |+| 云像一条面包:底座是粗圆角矩形,下面一整条深色底带 | 三四个大小不一的圆坐在同一条平底线上,下面垫一条薄药丸;暗面 = 云减去朝光源挪动后的自己,只剩右下一道月牙 |+| 半透明烟柱压在紫山和品红山丘上,又灰又脏 | 删掉烟;半透明形状只放在单一底色上(沙地上的光圈、头灯光束) |+| 火焰底部被平切,像蜡烛;木柴藏在火后面;围石是突兀的蓝紫色 | 火焰用 `teardrop()`(圆 + 两条切线收成尖),外层加两条侧舌,三层套叠;木柴交叉压在火脚前面,锯口画一圈浅色;石头改成淡紫灰 |+| 背包客的橙色背包、帐篷的橙色尖顶贴着橙色山丘带,就看不见了(没有描边) | 把人和帐篷整个挪到黄沙上,让轮廓四周只有一种对比色 |+| 小路走到雪线就断了:奶油色虚线落在雪顶上看不见 | `trail()` 返回遮罩,把 `path & peak['snow']` 改成紫灰色,路一直通到山顶小旗 |+| 篝火光圈看不见;火星飘到山丘带上,看不出和火有关 | 光圈 4 层,每层 alpha 0.2,颜色 `tone(SAND, 0.5)`;火星只出现在火焰上方 120–190 px |+| 动图里,大块图层交接(夜蓝 → 橙 → 沙)的叠化帧满是粗杂点 | 调色板样本里加上 1/3、2/3 两张叠化帧;叠化帧只在两张关键帧不同的地方叠一张固定的 4×4 Bayer。整帧都叠是 1.5 MB;改用 Floyd–Steinberg 有 1.97 MB,还会抖到品红透明占位色,5 帧对不上 |++**绘本角色动画**++| 问题 | 改法 |+|---|---|+| 远山又高又满,压掉大半天空;两岸之间、水面上面露出一条米色纸缝 | 远山顶线压到 470–660,薄荷远山的底伸到画面底边(藏在两岸后面),淡紫远山的底停在 760(藏在薄荷后面);淡紫的「提前量」比薄荷小(300 对 360),动画里淡紫的下沿永远不会露出来 |+| 总图里关键姿态挤成一团:落地压扁和预备动作在同一个点叠在一起,钻土的残影躲在小树苗后面,终点那片橡叶和漂流时的橡叶重叠成两片 | 只留沿路分得开的六个姿态(下落拉伸、落地压扁、滚动、飞跃、漂流、空翻);终点的发芽用「最后一帧」本身(`final=True` 画出树苗顶上的橡果帽);`props=False` 不画道具终点位置,只画和角色同一时刻的橡叶残影 |+| 落地压扁那一帧头顶冒出几根竖直速度线 | 速度线按前一帧的速度自动加,落地帧前一帧还在高速下落:冲击帧的姿态写 `speed=False` |+| 蜡笔短线一根都没画上 | 「内部」判断写成 blur(a) > 0.97,而水彩层不透明度只有 0.96–0.97:改成相对阈值 0.97 × a.max() |+| 蜡笔短线一出来就碎成麻点,像一行行小字 | 1920 宽时纸纹太细,按纸纹断线就成了点:改用 3.5 px 的粗颗粒,断得少;短线减少、加长加粗(44 × 5 px),透明度 0.55 |+| 河面上的白色反光像潦草的字 | 改成 16 根 80 px 长、略往上拱的白色长笔触,越靠近水面越密(top_bias),再加 9 根往下弯的深蓝波纹 |+| 树冠上的点缀先像圆点病斑,后像迷彩方块 | 换成三十几片小橡叶形「印」上去(两种秋色、半透明),树冠右下的暗面月牙加宽(偏移 40, 46 px) |+| 挂橡果的树枝被树冠盖住,看着像橡果悬在空中 | 缩小右边那团树冠,让树枝梢和挂果的小枝伸出树冠;树干、树枝的层放在树冠下面 |+| 手写字顺序不对:「little」先写了后半截,开头的 l 最后才出现 | 起笔点选「去斜体后最靠左」的端点:键值从 x − 0.3y 改成 x + 0.35y(向右上斜的字母,顶端比底部靠右);720 宽时发丝线断掉,文字遮罩加 1.6 设计像素的笔宽 |+| 跟着角色画出来的远山、山坡,前沿是 120 px 宽的一团雾 | 柔边写成层宽的比例(0.06 × 2000 px):改成最多 14 设计像素,前沿成了一道干脆的湿边 |+| 开场 0.2 秒整块绿色山坡就画出来了,右边一道竖直的「悬崖」挨着树 | 开头只画树和墨线地平线;山坡的绿色和远山放到「看树叶」那一秒(1.95–2.9 秒)先画左边一段(`pre=`),其余跟着角色滚下去再画(`follow=`) |+| 钻土时溅起的土粒一直掉到草地里去 | 土粒落回地面以下就不画 |+| 钻土的头一两帧,橡果被地面裁出一道笔直的横边 | 土堆在钻土开始 0.1 秒就弹出来,把裁切边盖住 |+| 彩纸屑又小又全压在字上 | 纸屑放大(10–19 px),从字下方炸开、横向散得更开(spread 1500、起点宽 640) |+| 12.5 fps 时滚动一帧转四五十度,有点跳 | 改成 15 fps;GIF 延时只能写厘秒,按累计取整写成 7、7、6 厘秒交替,平均正好 15 fps |+## 四、做成动画- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。@@ -1313,6 +1859,10 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 大片渐变、深色上的反光出色带:量化前每帧叠同一张固定的 4×4 Bayer 抖动(约 ±2.4 级)。- 满屏网点或硬边像素(漫画网点、低多边形)缩到 720 宽时用 BOX 不用 LANCZOS,否则网点成摩尔纹、硬边出振铃,体积也更大。- 满屏细纹理(灰泥、石子、玻璃)每次叠化都会改掉大半像素:叠化帧里和屏上已显示颜色只差一点(约 10/255)的像素沿用上一帧、记成透明,自检按实际显示的帧逐帧比对;墓室壁画、马赛克、彩色玻璃花窗都是靠这一条(再加各自的小改动,见第三节)把动图从 3 MB 多压到 2 MB 以下。+- 这一批十五种(蓝图工程图到绘本角色动画)又多了几条:+ - 满屏几乎一种色调(X 光片的蓝胶片)时,补几个色位不够:按「主色调像素 / 其余彩色像素」两段分别中值切分(186 + 69 色);OSD 里必须精确的纯白、纯黑、REC 红这类颜色直接强制占色位(热成像、VHS 家庭录像),否则白字被量化成淡黄。+ - 大块色层整片交接的叠化(扁平矢量的夜蓝 → 橙 → 沙):调色板样本里加上 1/3、2/3 两张叠化帧,Bayer 只叠在两张关键帧不同的地方(整帧都叠更大;Floyd–Steinberg 更大,还会抖出透明占位色)。只有黑白两值的画风(1-bit 早期画图软件)缩小用 BOX、配固定灰阶调色板,不做中值切分。+- 绘本角色动画的动图是真动画,不是阶段叠化:`Storybook.gif()` 按时间逐帧渲染,720×405、15 fps(GIF 延时只能写厘秒,按累计取整写成 7、7、6 厘秒交替),共用一张加权调色板 + 固定 4×4 Bayer,没变的像素记成品红透明,151 帧(动作 9.95 秒 + 末帧停 1.4 秒)约 0.56 MB;范例加 `--gif out.gif` 出这张,`--stages` 的关键帧仍可喂给上面的阶段动图工具。- 形变动画可以直接出真动画:`Morph.at(keys, T)` 给出全局时间 T 的轮廓,逐帧渲染即可。- 更细的逐笔动画:把一组笔画单独画到透明层上导出,再用 Motion Canvas 遮罩按顺序显现。这个还没做成现成接口。@@ -1363,6 +1913,21 @@ lib/lineprinter.py ASCII 字符画(行式打印机:绿条连续纸、按lib/lowpoly.py 低多边形(1999 年代 3D:软件光栅化、平面着色、仿射贴图、逐顶点雾、15 位色抖动、点阵 HUD)lib/stencil.py 喷漆模板涂鸦(清水混凝土墙、卡纸模板与桥、喷雾、滴痕)lib/patch.py 刺绣徽章(牛仔斜纹、填充绣 / 缎面绣、锁边、热切边、手缝针线)+lib/blueprint.py 蓝图工程图(描图布墨线、单笔画字、制图规范、接触晒图、折痕水渍、红蜡笔批注)+lib/crayon.py 儿童蜡笔画(糙纸纸纹、宽头蜡笔来回涂、出界、蜡层堆积与压光、圆头蜡笔写字、纸上的真蜡笔)+lib/crt.py 绿屏终端 CRT(字符内存与 5×7 点阵字库、按材质和边选字、扫描线电子束、荧光余辉与烧屏、桶形畸变与光晕、米色机壳)+lib/thermal.py 热成像(温度场:物体温度、发射率、热晕、热气羽流、冷气舌、余温脚印、釉面反射;热像仪:低分辨率传感器、噪声与竖条纹、细节增强、手调曲线 / 直方图均衡、伪彩色板;读数 OSD)+lib/delft.py 代尔夫特蓝瓷砖(锡釉砖墙:刺孔粉印、钴蓝勾线与晕染、生坯到入窑、逐块错位、单块砖角饰、勾缝、开片、窗户倒影)+lib/cave.py 洞穴壁画(石灰岩洞壁、赭石与炭黑、吹喷与手印、借岩面起伏、篝火与油灯照明、钙华与熊爪痕)+lib/macpaint.py 1-bit 早期画图软件(640×360 黑白帧缓冲、8×8 图案、当年的绘图工具与文字样式、菜单 / 工具栏 / 图案板 / 窗口界面)+lib/blackfigure.py 古希腊黑绘陶瓶(拉坯轮廓 + 展开面、轮制饰带与纹样、泥釉剪影、刻线、加红加白、三段烧成、做旧、博物馆打光、饰带展开图)+lib/graphite.py 铅笔素描(素描纸纹、2H–8B 石墨、起形辅助线、轮廓、分层排线、侧锋铺调、纸擦笔、橡皮提亮、边缘只剩线稿、页边笔记与试笔色阶)+lib/xray.py X 光片(双能衰减图:实心 / 壳体 / 圆棒管子 / 弹簧 / 侧看与正看的圆片 / 拉链螺钉电线 / 叠放衣物;比尔定律、散射、线阵条纹、光子噪声;胶片显示与安检伪彩、Zeff 与体积读数 OSD)+lib/rubberhose.py 1930 年代黑白橡皮管动画(灰色水粉背景、铅笔稿 → 描线 → 平灰上色的赛璐璐、橡皮管四肢 / 白手套 / 饼切眼、黑白胶片:颗粒、片门晃动、圆角片门、划痕灰尘)+lib/linocut.py 黑白麻胶版画(整版减法刻:V 口 / U 口刀痕、清底残刀、留黑线、一块套色错版、手拓发花、压印、铅笔签名编号)+lib/vhs.py VHS 家庭录像(70 年代客厅:反照率 × 灯光 + 自发光、离焦图层;家用摄像机:手持倾斜、钨丝灯偏色、软膝、泛光、CCD 竖向拖影、拖尾、增益噪声、点阵 OSD;录像带:YIQ、亮度带宽与锐化光晕、色度带宽 / 隔行平均 / 延迟、噪声、时基抖动、跟踪噪带、磁头切换、掉磁)+lib/flatvector.py 扁平矢量(分层几何色块、七色限定色板、层间柔和投影、细颗粒)+lib/storybook.py 绘本角色动画(按时间取帧:带揭示图的场景层、follow 边走边画、隐式曲面角色挤压拉伸、动作编排、特效、按骨架笔顺手写、旅程总图)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/blackfigure_games.jpg b/examples/blackfigure_games.jpgnew file mode 100644index 0000000..88e7b56Binary files /dev/null and b/examples/blackfigure_games.jpg differdiff --git a/examples/blackfigure_games.py b/examples/blackfigure_games.pynew file mode 100644index 0000000..ebfe58a--- /dev/null+++ b/examples/blackfigure_games.py@@ -0,0 +1,92 @@+"""Example (Greek black-figure vase / 古希腊黑绘陶瓶): 赛跑与赛车 · Games on a Vase.++An Attic black-figure neck amphora on a museum plinth, and beside it the two friezes that run all the way round+it, unrolled flat on a panel. Upper frieze: a four-horse chariot race -- on the front (the half you can see) the+leader and, right on his tail, the challenger whose far trace horse is white; round the back the turning post, the straggler,+the prize tripod and the official holding the victor's wreath. Lower frieze: the foot race -- five sprinters+on the front, the finish post, the umpire with his forked rod, a table with the prize (a little amphora just+like this one) and two stragglers round the back. Neck: palmettes and lotus; shoulder: black and red tongues;+a running meander between the friezes; rays above the foot.++Draw-on stages: thrown clay pot -> wheel-painted bands -> ornament -> silhouettes in slip -> incision ->+added red and white -> firing (the slip turns glossy black) -> 2,500 years -> the rollout panel. No image model.+python3 blackfigure_games.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from blackfigure import BlackFigure++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'blackfigure_games.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++bf = BlackFigure(1920, 1080, seed=8)+bf.museum(wall='#1c2427', plinth='#cbc2b4')+H = 930+pot = bf.throw(cx=470, foot=990, height=H)+Y = lambda f: f * H # heights on the pot as fractions of its height+bf.stage('thrown')++# ---- on the wheel: lip, neck, foot and the frame lines of every frieze+pot.paint_handles()+for a, b in [(0, .062), (.062, .080), (.212, .244), (.320, .326), (.570, .576), (.601, .606), (.722, .745),+ (.751, .756), (.850, .928), (.940, .994)]:+ pot.band(Y(a), Y(b))+bf.stage('wheel_bands')++# ---- ornament+pot.palmettes(Y(.084), Y(.210), n=5)+pot.tongues(Y(.247), Y(.316))+pot.meander(Y(.578), Y(.600))+pot.rays(Y(.756), Y(.850))+pot.paint()+bf.stage('ornament')++# ---- upper frieze: the chariot race (x = arc length round the pot from the left handle; front half = 0..C/2)+cz = pot.zone(Y(.326), Y(.570))+hw = 146+cz.quadriga(262, hw, white_horse=0, red_manes=(2,), bends=(0.20, -0.06, 0.12, -0.04))+cz.letters('ΗΟ ΠΑΙΣ', 262 - 0.62 * hw, cz.y0 + 16, size=13)+cz.quadriga(700, hw, red_manes=(1, 3), bends=(0.14, -0.04, 0.07, -0.10))+cz.letters('ΚΑΛΟΣ', 700 - 0.55 * hw, cz.y0 + 16, size=13)+cz.column(965, height=(cz.y1 - cz.y0) * 0.9)+cz.letters('ΤΕΡΜΑ', 995, cz.y0 + 40, size=12, vertical=True)+cz.bird(1275, cz.y0 + 34, size=44, facing=1, flap=0.1)+cz.quadriga(1300, hw * 0.97, red_manes=(2,), bends=(0.04, 0.12, -0.05, 0.08))+cz.tripod(1540, height=(cz.y1 - cz.y0) * 0.6)+cz.judge(1665, height=(cz.y1 - cz.y0) * 0.86, facing=-1, holds='wreath')+cz.letters('ΚΑΛΟΣ', 1735, cz.y0 + 40, size=12, vertical=True, retro=True)++# ---- lower frieze: the foot race+rz = pot.zone(Y(.606), Y(.722))+for i, x in enumerate((95, 236, 377, 518, 660)):+ rz.runner(x, phase=i % 2, beard=(i == 2), back_arm='up' if i % 2 else 'down')+rz.column(840, height=(rz.y1 - rz.y0) * 0.78, red=False)+rz.judge(915, height=(rz.y1 - rz.y0) * 0.86, facing=-1, holds='rod')+rz.prize_table(1020)+rz.runner(1240, phase=1, back_arm='up')+rz.runner(1410, phase=0, back_arm='down', beard=True)++pot.paint()+bf.stage('silhouettes')+pot.incise()+bf.stage('incision')+pot.add_colour()+bf.stage('added_colours')+pot.fire()+bf.stage('fired')++# ---- 2,500 years: flaking white, encrustation and root marks, chips, a mended loss, a misfired patch+pot.age(mend=(282, Y(.69), 34, 24), misfire=(pot.TW * 0.6, Y(.47), 70), chips=7, roots=14)+bf.stage('aged')++# ---- the panel: both friezes unrolled, front half and back half+bands = [(Y(.326), Y(.576)), (Y(.576), Y(.606)), (Y(.606), Y(.728))]+bf.panel((905, 52, 1872, 1028), title='赛跑与赛车', subtitle='黑绘颈柄双耳瓶 · 瓶身两圈饰带展开',+ english='Black-figure neck amphora: the two friezes unrolled', greek='ΤΕΘΡΙΠΠΟΝ · ΔΡΟΜΟΣ')+bf.rollout(pot, bands, 1388, 258, scale=0.82, half=0, caption='A 面 · 正面(瓶上看得见的半圈)', ticks=('0°', '180°'))+bf.rollout(pot, bands, 1388, 630, scale=0.82, half=1, caption='B 面 · 背面(转到瓶后才看得见)', ticks=('180°', '360°'))+bf.legend(945, 1003, [('赤陶', 'clay'), ('黑釉', 'black'), ('刻线', 'incision'), ('加红', 'red'), ('加白', 'white')])++bf.save(out, stages)+print(out, f'{time.time() - t0:.1f}s')diff --git a/examples/blueprint_lighthouse.jpg b/examples/blueprint_lighthouse.jpgnew file mode 100644index 0000000..5c5ad31Binary files /dev/null and b/examples/blueprint_lighthouse.jpg differdiff --git a/examples/blueprint_lighthouse.py b/examples/blueprint_lighthouse.pynew file mode 100644index 0000000..904d9ef--- /dev/null+++ b/examples/blueprint_lighthouse.py@@ -0,0 +1,632 @@+"""Example (blueprint / 蓝图工程图): 灯塔剖面 · Halvard Rock Light — sheet 3 of 7 of a (fictional) 1911 lighthouse+contract set, inked on tracing linen and printed as a blueprint. Left: the south elevation (granite courses, the+cylinder shaded with denser lines toward its edge, a bronze ladder up to the entrance, two railed galleries, the lantern+with helical astragals and the lens seen through the glass) and section A-A on the same levels (dovetailed walls+thinning as they rise, a cistern in the base, 120 cantilevered stone steps winding round a hollow newel that is also+the tube for the clockwork weight, the watch room with the clockwork, the lantern with the lens on its rotating table).+Right: plan B-B through the stair at +6.50 with a north point, detail 1 that tells the small story of the drawing --+the lamp flame sits at the focal point, every prism bends its ray level, and the lens sends out one parallel beam --+general notes, graphic scales, revision and title blocks. Then the sheet's life: folded in six, the outside panel+faded and handled, an alkaline water stain, drawing-pin holes, and a site engineer's red pencil: he counted the steps.+Draw-on stages: sheet -> layout -> elevation -> section -> hatching -> plan -> detail -> dimensions -> lettering ->+folded and filed -> red pencil. No image model.+python3 blueprint_lighthouse.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from blueprint import Blueprint+from core import spline as _spl++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'blueprint_lighthouse.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++bp = Blueprint(1920, 1080, seed=11)++# ------------------------------------------------------------------ the tower, in metres+S, G = 19.0, 900.0 # 1:200 -> 19 px per metre; rock datum +-0.00 at y = 900+EX, SX = 276.0, 682.0 # axis of the elevation / of section A-A+Y = lambda h: G - h * S+RISE, PER_TURN, R_NEWEL, R_TUBE = 0.23, 14, 0.36, 0.26+BANDS = [(2.5, 9.0, 2.55), (9.0, 16.0, 2.40), (16.0, 23.0, 2.25), (23.0, 30.0, 2.05)] # inner radius per band+WIN_R, WIN_L, WIN_FRONT = [6.5, 19.4], [12.9, 25.8], [9.7, 16.1, 22.6]+++def Rs(h): # shaft outer radius (straight taper)+ return 4.0 - 1.35 * (h - 2.5) / 26.1+++def Rc(h): # corbel under the gallery+ return 2.65 + 1.1 * ((h - 28.6) / 1.4) ** 2+++def Rout(h):+ return Rs(h) if h <= 28.6 else Rc(min(h, 30.0))+++def Rin(h):+ for a, b, r in BANDS:+ if a <= h < b: return r+ return BANDS[-1][2]+++def profile():+ """right-hand silhouette (R, h), bottom to the ventilator neck"""+ pts = [(4.6, 0.0), (4.6, 2.2), (4.75, 2.2), (4.75, 2.5), (4.0, 2.5), (2.65, 28.6)]+ pts += [(Rc(h), h) for h in np.linspace(28.6, 30.0, 9)[1:]]+ pts += [(3.75, 30.35), (2.3, 30.35), (2.3, 33.0), (2.75, 33.0), (2.75, 33.3), (1.95, 33.3), (1.95, 37.0),+ (2.12, 37.0), (2.12, 37.25), (1.95, 37.25)]+ te = np.arccos(0.28 / 1.95)+ pts += [(1.95 * np.cos(t), 37.25 + 1.7 * np.sin(t)) for t in np.linspace(0, te, 16)[1:]]+ return pts + [(0.28, 39.05)]+++def P(ax, pts, flip=False):+ return [(ax + (-r if flip else r) * S, Y(h)) for r, h in pts]+++def silhouette(ax):+ pr = profile()+ return P(ax, pr) + P(ax, pr[::-1], flip=True)+++def arch(ax, h, w=0.7, sill=0.55, spring=0.2):+ """arched window outline (screen pts), centred on the axis"""+ a = bp.arc_pts(ax, Y(h + spring), w / 2 * S, 180, 0)+ return [(ax - w / 2 * S, Y(h - sill))] + [tuple(p) for p in a] + [(ax + w / 2 * S, Y(h - sill))]+++def densify(pts, step=0.04):+ out = []+ for (x0, h0), (x1, h1) in zip(pts[:-1], pts[1:]):+ n = max(1, int(max(abs(h1 - h0), abs(x1 - x0)) / step))+ for t in np.arange(n) / n: out.append((x0 + (x1 - x0) * t, h0 + (h1 - h0) * t))+ return out + [pts[-1]]+++def split_h(pts, gaps):+ """polyline (r, h), monotone in h -> pieces outside the h-gaps"""+ res, cur = [], []+ for r, h in densify(pts):+ if any(a < h < b for a, b in gaps):+ if len(cur) > 1: res.append(cur)+ cur = []+ else:+ cur.append((r, h))+ if len(cur) > 1: res.append(cur)+ return res+++def steps():+ dth = 2 * np.pi / PER_TURN+ th0 = np.pi + dth * 0.5+ k, out = 0, []+ while True:+ h = 2.5 + (k + 1) * RISE+ if h > 29.95: break+ out.append((k, h, th0 + k * dth))+ k += 1+ return out, dth+++STEPS, DTH = steps()++# ================================================================== 1. the sheet: border, zones, empty blocks+bp.border(56, 30, 1890, 1050)+TB = bp.table(1452, 846, [100, 110, 108, 120], [26, 58, 30, 44, 46], pen='thin', outer='thick')+RB = bp.table(1452, 770, [40, 248, 80, 70], [20, 28, 28], pen='thin', outer='medium')+bp.stage('sheet')++# ================================================================== 2. layout in pencil + centre lines, ground, rock, sea+for h in (0.0, 2.5, 30.0, 33.3, 35.7, 41.2):+ bp.pencil([(70, Y(h)), (950, Y(h))], 0.8)+bp.pencil([(EX, 100), (EX, 975)], 0.8); bp.pencil([(SX, 100), (SX, 975)], 0.8)+for ax in (EX, SX):+ bp.centerline([(ax, Y(41.9)), (ax, Y(-3.6))])+SEA = -1.8+++def rock(ax, seed):+ r = np.random.default_rng(seed)+ top_l = [(ax - 4.9 * S, Y(0.0))] + [(ax - (4.9 + t) * S, Y(-1.8 * (t / 4.0) ** 1.4 + r.normal(0, 0.12)))+ for t in np.linspace(0.6, 4.0, 7)]+ top_r = [(ax + 4.9 * S, Y(0.0))] + [(ax + (4.9 + t) * S, Y(-1.8 * (t / 3.6) ** 1.3 + r.normal(0, 0.12)))+ for t in np.linspace(0.6, 3.6, 7)]+ return top_l[::-1] + top_r, (ax - 8.9 * S, ax + 8.5 * S)+++ROCK = {}+for ax, sd in ((EX, 4), (SX, 4)):+ top, (xl, xr) = rock(ax, sd)+ bot = Y(-3.25)+ poly = top + [(xr, bot), (xl, bot)]+ ROCK[ax] = (top, poly, bot)+ bp.ground(top, depth=8, every=17)+ bp.breakline((xl - 6, bot), (xr + 6, bot))+ bp.line([top[0], (xl, bot)], 'thin'); bp.line([top[-1], (xr, bot)], 'thin')+# the sea at high water and the wave lines under it+for x0, x1 in ((66, ROCK[EX][1][0][0] - 4), (ROCK[EX][1][-4][0] + 4, ROCK[SX][1][0][0] - 4), (ROCK[SX][1][-4][0] + 4, 870)):+ if x1 - x0 < 20: continue+ bp.line([(x0, Y(SEA)), (x1, Y(SEA))], 'thin', pool=False)+ for j, hh in enumerate((-2.25, -2.7)):+ xs = np.arange(x0 + 8 + j * 9, x1 - 10, 26)+ for x in xs: bp.line([(x, Y(hh)), (min(x + 12 - j * 4, x1), Y(hh))], 'fine', pool=False)+bp.stage('layout')++# ================================================================== 3. south elevation+bp.line(silhouette(EX), 'thick', closed=True)+bp.line([(EX - 4.75 * S, Y(2.2)), (EX + 4.75 * S, Y(2.2))], 'medium')+bp.line([(EX - 4.0 * S, Y(2.5)), (EX + 4.0 * S, Y(2.5))], 'medium')+bp.line([(EX - Rc(28.6 + 1e-3) * S, Y(28.6)), (EX + 2.65 * S, Y(28.6))], 'thin')+bp.line([(EX - 3.75 * S, Y(30.0)), (EX + 3.75 * S, Y(30.0))], 'medium')+# plinth ashlar: three courses, joints at equal angles -> crowd toward the edges+for c in range(3):+ h0, h1 = c * 0.733, (c + 1) * 0.733+ if c: bp.line([(EX - 4.6 * S, Y(h0)), (EX + 4.6 * S, Y(h0))], 'fine', pool=False)+ for ph in np.radians(np.arange(-78.75 + (c % 2) * 11.25, 80, 22.5)):+ x = EX + 4.6 * S * np.sin(ph)+ bp.line([(x, Y(h0)), (x, Y(h1))], 'fine', pool=False)+# shaft courses, broken at the windows and the door+win_e = [(h - 0.62, h + 0.62) for h in WIN_FRONT] + [(2.5, 4.75)]+for h in np.arange(2.5 + 0.62, 28.55, 0.62):+ xl, xr = EX - Rs(h) * S, EX + Rs(h) * S+ if any(a < h < b for a, b in win_e):+ bp.line([(xl, Y(h)), (EX - 0.55 * S, Y(h))], 'fine', pool=False)+ bp.line([(EX + 0.55 * S, Y(h)), (xr, Y(h))], 'fine', pool=False)+ else:+ bp.line([(xl, Y(h)), (xr, Y(h))], 'fine', pool=False)+# a round tower: shading lines on the shadow side, closer together toward the edge+for al in (58, 66, 72.5, 77.5, 81.5, 84.5, 87):+ sa = np.sin(np.radians(al))+ bp.line([(EX + 4.0 * S * sa, Y(2.55)), (EX + 2.65 * S * sa, Y(28.55))], 'fine', pool=False)+# door, ladder, windows+bp.line(arch(EX, 3.95, 1.1, 1.45, 0.1), 'medium', closed=True)+bp.arc(EX, Y(4.05), 0.78 * S, 180, 0, 'thin')+bp.line([(EX, Y(2.5)), (EX, Y(4.05))], 'fine', pool=False)+for sx in (-0.32, 0.32):+ bp.line([(EX + sx * S, Y(0.0)), (EX + sx * S, Y(2.55))], 'thin')+for h in np.arange(0.3, 2.5, 0.3):+ bp.line([(EX - 0.32 * S, Y(h)), (EX + 0.32 * S, Y(h))], 'fine', pool=False)+for h in WIN_FRONT:+ bp.line(arch(EX, h), 'medium', closed=True)+ bp.line([(EX - 0.5 * S, Y(h - 0.6)), (EX + 0.5 * S, Y(h - 0.6))], 'thin')+ bp.line([(EX, Y(h - 0.55)), (EX, Y(h + 0.55))], 'fine', pool=False)+ bp.line([(EX - 0.35 * S, Y(h)), (EX + 0.35 * S, Y(h))], 'fine', pool=False)+# galleries and railings (posts at equal angles round the gallery)+for (R, h0, h1, rails, step_deg) in ((3.6, 30.35, 31.6, 3, 15), (2.7, 33.3, 34.25, 2, 20)):+ for ph in np.radians(np.arange(step_deg / 2, 180, step_deg)):+ x = EX + R * S * np.cos(ph)+ bp.line([(x, Y(h0)), (x, Y(h1))], 'fine', pool=False)+ for i in range(1, rails + 1):+ hh = h0 + (h1 - h0) * i / rails+ bp.line([(EX - R * S, Y(hh)), (EX + R * S, Y(hh))], 'medium' if i == rails else 'thin')+ bp.line([(EX - R * S, Y(h0)), (EX - R * S, Y(h1))], 'thin'); bp.line([(EX + R * S, Y(h0)), (EX + R * S, Y(h1))], 'thin')+# watch room portholes (foreshortened toward the sides)+for ph in (90, 38, 142):+ c = np.cos(np.radians(ph)); s_ = np.sin(np.radians(ph))+ bp.circle(EX + 2.3 * S * c, Y(32.1), 0.3 * S * s_, 'thin', ry=0.3 * S)+# lantern pedestal panels and vents+for ph in np.radians(np.arange(30, 180, 30)):+ x = EX + 1.95 * S * np.cos(ph)+ bp.line([(x, Y(33.3)), (x, Y(34.3))], 'fine', pool=False)+bp.line([(EX - 1.95 * S, Y(34.3)), (EX + 1.95 * S, Y(34.3))], 'medium')+for ph in np.radians(np.arange(45, 180, 30)):+ bp.circle(EX + 1.95 * S * np.cos(ph), Y(33.8), 0.12 * S * np.sin(ph) + 0.6, 'fine', ry=0.12 * S)+# the lens seen through the glass (beehive outline and prism rings)+LENS = [(0.60, 34.6), (0.80, 34.9), (0.88, 35.3), (0.92, 35.35), (0.92, 36.05), (0.88, 36.1), (0.82, 36.5), (0.72, 36.8), (0.55, 37.0)]+bp.line(P(EX, LENS) + P(EX, LENS[::-1], True), 'fine', closed=True)+for h in list(np.linspace(34.75, 35.25, 3)) + list(np.linspace(35.45, 35.95, 4)) + list(np.linspace(36.2, 36.9, 4)):+ r = np.interp(h, [p[1] for p in LENS], [p[0] for p in LENS])+ bp.line([(EX - r * S, Y(h)), (EX + r * S, Y(h))], 'fine', pool=False)+# helical astragals: two families of bars winding round the glass, only the near half drawn+for fam in (1, -1):+ for j in range(12):+ hs = np.linspace(34.3, 37.0, 40)+ ph = np.radians(j * 30 + fam * 70 * (hs - 34.3) / 2.7)+ vis = np.sin(ph) > 0+ seg = []+ for h, p_, v in zip(hs, ph, vis):+ if v: seg.append((EX + 1.95 * S * np.cos(p_), Y(h)))+ elif len(seg) > 1: bp.line(seg, 'thin', pool=False); seg = []+ else: seg = []+ if len(seg) > 1: bp.line(seg, 'thin', pool=False)+# dome ribs, ventilator ball, conductor and vane+te = np.arccos(0.28 / 1.95)+for ph in np.radians((35, 62, 90, 118, 145)):+ t = np.linspace(0, te, 16)+ bp.line([(EX + 1.95 * np.cos(tt) * np.cos(ph) * S, Y(37.25 + 1.7 * np.sin(tt))) for tt in t], 'fine', pool=False)+bp.circle(EX, Y(39.42), 0.38 * S, 'medium')+bp.line([(EX, Y(39.8)), (EX, Y(41.2))], 'medium')+bp.line([(EX - 0.95 * S, Y(40.55)), (EX + 0.95 * S, Y(40.55))], 'thin')+bp.arrowhead((EX - 1.05 * S, Y(40.55)), (-1, 0), 9)+bp.fill([(EX + 0.55 * S, Y(40.55)), (EX + 0.95 * S, Y(40.85)), (EX + 0.95 * S, Y(40.25))])+bp.stage('elevation')++# ================================================================== 4. section A-A+WO, WI = 0.38, 0.55 # half-height of a window opening outside / inside (splayed)+gR = [(h - WO, h + WO) for h in WIN_R]; gL = [(h - WO, h + WO) for h in WIN_L]+giR = [(h - WI, h + WI) for h in WIN_R]; giL = [(h - WI, h + WI) for h in WIN_L]+outer = [(Rout(h), h) for h in np.linspace(2.5, 30.0, 120)]+inner = []+for a, b, r in BANDS:+ inner += [(r, a), (r, b)]+for side, go, gi in ((1, gR, giR), (-1, gL, giL)):+ for seg in split_h(outer, go): bp.line([(SX + side * r * S, Y(h)) for r, h in seg], 'thick')+ for seg in split_h(inner, gi): bp.line([(SX + side * r * S, Y(h)) for r, h in seg], 'thick')+ for hc in [g[0] + WO for g in go]:+ xo, xi = SX + side * Rs(hc) * S, SX + side * Rin(hc) * S+ bp.line([(xo, Y(hc + WO)), (xi, Y(hc + WI))], 'thick'); bp.line([(xo, Y(hc - WO)), (xi, Y(hc - WI))], 'thick')+ xg = SX + side * (Rs(hc) - 0.25) * S # the sash, set back from the face+ bp.line([(xg, Y(hc - WO - 0.03)), (xg, Y(hc + WO + 0.03))], 'medium')+ bp.line([(xg - side * 2.5, Y(hc - WO - 0.02)), (xg - side * 2.5, Y(hc + WO + 0.02))], 'fine', pool=False)+# base with the cistern+bp.line([(SX - 4.6 * S, Y(0)), (SX - 4.6 * S, Y(2.2)), (SX - 4.75 * S, Y(2.2)), (SX - 4.75 * S, Y(2.5)), (SX - 2.55 * S, Y(2.5))], 'thick')+bp.line([(SX + 4.6 * S, Y(0)), (SX + 4.6 * S, Y(2.2)), (SX + 4.75 * S, Y(2.2)), (SX + 4.75 * S, Y(2.5)), (SX + 2.55 * S, Y(2.5))], 'thick')+bp.line([(SX - 2.55 * S, Y(2.5)), (SX + 2.55 * S, Y(2.5))], 'thick')+CIS = [(SX - 1.7 * S, Y(0.45)), (SX + 1.7 * S, Y(0.45)), (SX + 1.7 * S, Y(2.05)), (SX - 1.7 * S, Y(2.05))]+bp.line(CIS, 'medium', closed=True)+bp.dashed([(SX - 1.7 * S + 3, Y(1.55)), (SX + 1.7 * S - 3, Y(1.55))], 'fine', (6, 4))+for x in np.arange(SX - 1.45 * S, SX + 1.5 * S, 0.5 * S):+ bp.line([(x, Y(1.32)), (x + 7, Y(1.32))], 'fine', pool=False)+# gallery slab, watch room, lantern floor, pedestal, glazing, cornice, dome+SLAB = [(SX - 3.75 * S, Y(30.0)), (SX + 3.75 * S, Y(30.0)), (SX + 3.75 * S, Y(30.35)), (SX - 3.75 * S, Y(30.35))]+bp.line(SLAB, 'thick', closed=True)+for side in (1, -1):+ bp.line([(SX + side * 2.3 * S, Y(30.35)), (SX + side * 2.3 * S, Y(33.0))], 'thick')+ bp.line([(SX + side * 1.95 * S, Y(30.35 if side > 0 else 32.4)), (SX + side * 1.95 * S, Y(33.0))], 'thick')+bp.line([(SX - 2.3 * S, Y(32.4)), (SX - 1.95 * S, Y(32.4))], 'thick')+bp.line([(SX - 2.3 * S, Y(30.35)), (SX - 2.3 * S, Y(32.4))], 'medium')+bp.line([(SX - 1.95 * S, Y(30.35)), (SX - 1.55 * S, Y(32.2))], 'thin') # door leaf, open+FLOOR = [(SX - 2.75 * S, Y(33.0)), (SX + 2.75 * S, Y(33.0)), (SX + 2.75 * S, Y(33.3)), (SX - 2.75 * S, Y(33.3))]+bp.line(FLOOR, 'thick', closed=True)+for side in (1, -1):+ bp.fill([(SX + side * 1.85 * S, Y(33.3)), (SX + side * 1.97 * S, Y(33.3)), (SX + side * 1.97 * S, Y(34.3)), (SX + side * 1.85 * S, Y(34.3))])+ bp.line([(SX + side * 1.92 * S, Y(34.3)), (SX + side * 1.92 * S, Y(37.0))], 'thin')+ bp.line([(SX + side * 1.98 * S, Y(34.3)), (SX + side * 1.98 * S, Y(37.0))], 'fine', pool=False)+ for hh in (35.0, 35.9, 36.6):+ bp.fill([(SX + side * 1.88 * S, Y(hh - 0.08)), (SX + side * 2.02 * S, Y(hh - 0.08)), (SX + side * 2.02 * S, Y(hh + 0.08)), (SX + side * 1.88 * S, Y(hh + 0.08))])+ bp.fill([(SX + side * 1.85 * S, Y(37.0)), (SX + side * 2.12 * S, Y(37.0)), (SX + side * 2.12 * S, Y(37.25)), (SX + side * 1.85 * S, Y(37.25))])+ for ph in (1, 2): # railings in section+ R = 3.6 if ph == 1 else 2.7+ h0, h1 = (30.35, 31.6) if ph == 1 else (33.3, 34.25)+ bp.line([(SX + side * R * S, Y(h0)), (SX + side * R * S, Y(h1))], 'medium')+ bp.line([(SX + side * (R - 0.15) * S, Y(h1)), (SX + side * (R + 0.05) * S, Y(h1))], 'medium')+dome_o = [(1.95 * np.cos(t), 37.25 + 1.7 * np.sin(t)) for t in np.linspace(0, te, 16)]+dome_i = [(1.85 * np.cos(t), 37.25 + 1.6 * np.sin(t)) for t in np.linspace(0, np.arccos(0.28 / 1.85), 16)]+for side in (1, -1):+ bp.fill(P(SX, dome_o, side < 0) + P(SX, dome_i[::-1], side < 0))+bp.circle(SX, Y(39.42), 0.38 * S, 'medium')+bp.line([(SX, Y(39.8)), (SX, Y(41.2))], 'medium')+bp.line([(SX - 0.28 * S, Y(39.05)), (SX + 0.28 * S, Y(39.05))], 'thin')+# the newel = weight tube, the weight on its cable, the clockwork above+for side in (1, -1):+ bp.fill([(SX + side * R_TUBE * S, Y(2.5)), (SX + side * R_NEWEL * S, Y(2.5)), (SX + side * R_NEWEL * S, Y(30.0)), (SX + side * R_TUBE * S, Y(30.0))])+bp.box(SX - 0.19 * S, Y(15.3), SX + 0.19 * S, Y(14.0), 'thin')+bp.line([(SX - 0.19 * S, Y(14.0)), (SX + 0.19 * S, Y(15.3))], 'fine', pool=False)+bp.line([(SX + 0.19 * S, Y(14.0)), (SX - 0.19 * S, Y(15.3))], 'fine', pool=False)+bp.line([(SX, Y(15.3)), (SX, Y(30.62))], 'fine', pool=False)+bp.box(SX - 0.75 * S, Y(31.6), SX + 0.75 * S, Y(30.35), 'thin')+bp.circle(SX - 0.32 * S, Y(31.08), 0.32 * S, 'thin'); bp.circle(SX + 0.3 * S, Y(31.2), 0.14 * S, 'fine')+bp.circle(SX, Y(30.72), 0.16 * S, 'fine')+bp.line([(SX + 0.75 * S, Y(30.9)), (SX + 1.05 * S, Y(30.9)), (SX + 1.05 * S, Y(30.7))], 'thin')+for side in (1, -1): # drive column + governor+ bp.line([(SX + side * 0.07 * S, Y(31.6)), (SX + side * 0.07 * S, Y(34.3))], 'thin')+bp.line([(SX + 0.5 * S, Y(31.6)), (SX + 0.5 * S, Y(32.2))], 'fine'); bp.dot(SX + 0.36 * S, Y(32.05), 2.0); bp.dot(SX + 0.64 * S, Y(32.05), 2.0)+# lens on its rotating table, lamp at the focal point+bp.fill([(SX - 0.98 * S, Y(34.3)), (SX + 0.98 * S, Y(34.3)), (SX + 0.98 * S, Y(34.45)), (SX - 0.98 * S, Y(34.45))])+for side in (1, -1):+ bp.line(P(SX, LENS, side < 0), 'thin')+ for h in list(np.linspace(34.75, 35.25, 3)) + list(np.linspace(36.2, 36.9, 4)):+ r = np.interp(h, [p[1] for p in LENS], [p[0] for p in LENS])+ bp.fill([(SX + side * (r - 0.02) * S, Y(h + 0.07)), (SX + side * (r + 0.1) * S, Y(h)), (SX + side * (r - 0.02) * S, Y(h - 0.07))])+for h in list(np.linspace(34.75, 35.25, 3)) + list(np.linspace(35.45, 35.95, 4)) + list(np.linspace(36.2, 36.9, 4)):+ r = np.interp(h, [p[1] for p in LENS], [p[0] for p in LENS])+ bp.line([(SX - r * S + 2, Y(h)), (SX + r * S - 2, Y(h))], 'fine', pool=False)+bp.line([(SX - 0.05 * S, Y(34.45)), (SX - 0.05 * S, Y(35.55))], 'fine'); bp.line([(SX + 0.05 * S, Y(34.45)), (SX + 0.05 * S, Y(35.55))], 'fine')+# the stair: the far half seen beyond the cut (nosings, the tread-and-riser zig-zag along the wall, the helical+# soffit under the steps); the steps the cutting plane passes through are inked solid+for k, h, th in STEPS:+ ro = Rin(h) - 0.02+ c0, s0 = np.cos(th), np.sin(th)+ if s0 > 0.02:+ xa, xb = R_NEWEL * np.sign(c0), ro * c0+ if abs(xb) > R_NEWEL + 0.05:+ bp.line([(SX + xa * S, Y(h)), (SX + xb * S, Y(h))], 'thin', pool=False)+ bp.line([(SX + xb * S, Y(h - RISE)), (SX + xb * S, Y(h))], 'thin', pool=False)+ t1 = min(th + DTH, np.ceil(th / np.pi) * np.pi)+ x2 = ro * np.cos(t1)+ bp.line([(SX + xb * S, Y(h)), (SX + x2 * S, Y(h))], 'thin', pool=False)+ a = th % (2 * np.pi)+ for ang, side in ((0.0, 1), (2 * np.pi, 1), (np.pi, -1)):+ if a <= ang <= a + DTH:+ bp.fill([(SX + side * R_NEWEL * S, Y(h)), (SX + side * ro * S, Y(h)), (SX + side * ro * S, Y(h - 0.13)), (SX + side * R_NEWEL * S, Y(h - 0.13))])+th_all = np.linspace(STEPS[0][2], STEPS[-1][2], 4000)+h_all = 2.5 + RISE + (th_all - STEPS[0][2]) / DTH * RISE - 0.42+seg = []+for th, h in zip(th_all, h_all):+ vis = np.sin(th) > 0 and h > 2.55+ x = (Rin(h + 0.42) - 0.02) * np.cos(th)+ if vis: seg.append((SX + x * S, Y(h)))+ elif len(seg) > 1: bp.line(seg, 'thin', pool=False); seg = []+ else: seg = []+if len(seg) > 1: bp.line(seg, 'thin', pool=False)+bp.stage('section')++# ================================================================== 5. hatching: granite, rock, cut iron, glass+HS = 5.0+for side, gi in ((1, giR), (-1, giL)):+ wall = [(SX + side * Rout(h) * S, Y(h)) for h in np.linspace(2.5, 30.0, 120)]+ wall += [(SX + side * r * S, Y(h)) for r, h in inner[::-1]]+ holes = []+ for hc in [g[0] + WI for g in gi]:+ holes.append([(SX + side * (Rs(hc) + 0.3) * S, Y(hc + WO)), (SX + side * Rin(hc) * S, Y(hc + WI)),+ (SX + side * Rin(hc) * S, Y(hc - WI)), (SX + side * (Rs(hc) + 0.3) * S, Y(hc - WO))])+ bp.hatch([wall], 45, HS, holes=holes)+base = [(SX - 4.6 * S, Y(0)), (SX + 4.6 * S, Y(0)), (SX + 4.6 * S, Y(2.2)), (SX + 4.75 * S, Y(2.2)), (SX + 4.75 * S, Y(2.5)),+ (SX - 4.75 * S, Y(2.5)), (SX - 4.75 * S, Y(2.2)), (SX - 4.6 * S, Y(2.2))]+bp.hatch([base], 45, HS, holes=[CIS])+bp.hatch([SLAB], 45, HS)+for side in (1, -1):+ bp.hatch([[(SX + side * 1.95 * S, Y(30.35 if side > 0 else 32.4)), (SX + side * 2.3 * S, Y(30.35 if side > 0 else 32.4)),+ (SX + side * 2.3 * S, Y(33.0)), (SX + side * 1.95 * S, Y(33.0))]], 45, HS)+bp.hatch([FLOOR], 45, 3.2, kind='cross')+for ax in (EX, SX):+ top, poly, bot = ROCK[ax]+ bp.hatch([poly], kind='rock', spacing=9 if ax == SX else 13, pen='fine')+bp.stage('hatching')++# ================================================================== 6. plan B-B at +6.50 (1:100)+PX, PY, K = 1110.0, 300.0, 38.0+Ro, Ri = Rs(6.5), Rin(6.5)+pp = lambda r, th: (PX + r * np.cos(th) * K, PY - r * np.sin(th) * K)+bp.centerline([(PX - 200, PY), (PX + 200, PY)]); bp.centerline([(PX, PY - 200), (PX, PY + 200)])+ring_o = [pp(Ro, t) for t in np.linspace(0, 2 * np.pi, 200)]+ring_i = [pp(Ri, t) for t in np.linspace(0, 2 * np.pi, 160)]+win = [pp(Ro + 0.3, -0.105), pp(Ro + 0.3, 0.105), pp(Ri - 0.05, 0.27), pp(Ri - 0.05, -0.27)]+bp.hatch([ring_o], 45, 4.0, holes=[ring_i, win])+for r0, r1 in ((Ro, Ri),):+ a_o, a_i = 0.093, 0.235+ bp.line([pp(r0, t) for t in np.linspace(a_o, 2 * np.pi - a_o, 220)], 'thick')+ bp.line([pp(r1, t) for t in np.linspace(a_i, 2 * np.pi - a_i, 180)], 'thick')+ for sg in (1, -1):+ bp.line([pp(r0, sg * a_o), pp(r1, sg * a_i)], 'thick')+bp.line([pp(Ro - 0.25, -0.1), pp(Ro - 0.25, 0.1)], 'thin'); bp.line([pp(Ro - 0.35, -0.11), pp(Ro - 0.35, 0.11)], 'fine')+bp.hatch([[pp(R_NEWEL, t) for t in np.linspace(0, 2 * np.pi, 60)]], kind='solid', holes=[[pp(R_TUBE, t) for t in np.linspace(0, 2 * np.pi, 50)]])+bp.dot(PX, PY, 1.4)+kc = max(k for k, h, th in STEPS if h <= 6.5)+thc = STEPS[kc][2]+for k, h, th in STEPS[kc - 13:kc + 1]:+ bp.line([pp(R_NEWEL, th), pp(Ri - 0.02, th)], 'thin', pool=False)+for k, h, th in STEPS[kc + 1:kc + 6]:+ bp.dashed([pp(R_NEWEL + 0.1, th), pp(Ri - 0.1, th)], 'fine', (5, 4))+tb = thc + DTH * 0.55+bp.breakline(pp(R_NEWEL + 0.05, tb), pp(Ri + 0.02, tb), 'thin', zig=6)+rm = (R_NEWEL + Ri) / 2 + 0.15+arc_up = [pp(rm, t) for t in np.linspace(thc - 3.55, thc + DTH * 0.1, 70)]+bp.line(arc_up, 'thin')+bp.arrowhead(arc_up[-1], np.subtract(arc_up[-1], arc_up[-4]), 9)+bp.dot(*arc_up[0], 2.2)+bp.stage('plan')++# ================================================================== 7. detail 1: lens and lamp (1:30)+DX, FY, KD = 1440.0, 290.0, 126.0+yd = lambda h: FY - (h - 35.7) * KD+bp.centerline([(DX, yd(37.45)), (DX, yd(34.1))])+bp.centerline([(1330, FY), (1712, FY)], pattern=(22, 4, 4, 4))+F = np.array([DX, FY])+++def isect(p, d, q, e):+ A = np.array([[d[0], -e[0]], [d[1], -e[1]]], np.float64)+ t = np.linalg.solve(A, np.subtract(q, p))+ return np.asarray(p) + np.asarray(d) * t[0]+++prisms, rays = [], []+for al, xe, L1, L2 in [(31, 0.80, 0.10, 0.03), (39, 0.785, 0.10, 0.03), (47, 0.765, 0.095, 0.03), (55, 0.735, 0.09, 0.028), (62, 0.70, 0.085, 0.026),+ (-31, 0.80, 0.10, 0.03), (-39, 0.785, 0.10, 0.03), (-47, 0.765, 0.095, 0.03), (-54, 0.74, 0.09, 0.028)]:+ r = np.array([np.cos(np.radians(al)), -np.sin(np.radians(al))])+ E = F + r * (xe / np.cos(np.radians(al))) * KD+ M = E + r * L1 * KD+ Xp = M + np.array([L2 * KD, 0])+ m = (np.array([1.0, 0]) - r); m /= np.linalg.norm(m)+ t_m = np.array([-m[1], m[0]]); t_e = np.array([r[1], -r[0]])+ V1 = isect(E, t_e, M, t_m); V2 = isect(M, t_m, Xp, [0, 1]); V3 = isect(Xp, [0, 1], E, t_e)+ prisms.append([V1, V2, V3]); rays.append([F, E, M, Xp])+belt_top, belt_bot = yd(36.1), yd(35.3)+xi, xo = DX + 0.80 * KD, DX + 0.92 * KD+teeth = np.linspace(belt_top, belt_bot, 8)+belt = [(xi, belt_top), (xi, belt_bot)]+for j in range(len(teeth) - 1, 0, -1):+ ya, yb = teeth[j], teeth[j - 1]+ t = ((ya + yb) / 2 - FY) / (belt_bot - FY)+ if abs(t) < 0.2:+ belt += [(xo - 3, ya)] + [(xo + 2 - 5 * abs(s) ** 2, (ya + yb) / 2 + s * (yb - ya) / 2) for s in np.linspace(1, -1, 7)] + [(xo - 3, yb)]+ elif t > 0:+ belt += [(xo - 4, ya), (xo + 1, yb + 2), (xo - 4, yb)]+ else:+ belt += [(xo - 4, ya), (xo + 1, ya - 2), (xo - 4, yb)]+for h in np.linspace(35.3 + 0.8 / 7 * 0.5, 36.1, 7)[:-1]:+ rays.append([F, (xi, yd(h)), (xo, yd(h))])+for pr in prisms:+ bp.hatch([pr], 30, 2.6, kind='lines', pen=0.7) # cut glass+ bp.line(pr, 'thin', closed=True)+bp.hatch([belt], 30, 2.6, kind='lines', pen=0.7)+bp.line(belt, 'thin', closed=True)+# bronze frame: rings holding the prisms, the uprights+frame_o = sorted([max(pr, key=lambda v: v[0]) for pr in prisms], key=lambda v: v[1])+bp.line([(frame_o[0][0] + 3, frame_o[0][1] - 4)] + [(v[0] + 3, v[1]) for v in frame_o[:5]] + [(xo + 4, belt_top - 4)], 'fine')+bp.line([(xo + 4, belt_bot + 4)] + [(v[0] + 3, v[1]) for v in frame_o[5:]], 'fine')+# mirrored outline of the far half, dashed (half section)+ys_o = [v[1] for v in frame_o]; xs_o = [v[0] for v in frame_o]+half = sorted(list(zip(ys_o, xs_o)) + [(belt_top, xo + 1), (belt_bot, xo + 1)])+LH = _spl([(2 * DX - x - 2, y) for y, x in half], 8) # left half: the lens seen from outside+bp.line([(DX, LH[0][1])] + [tuple(p) for p in LH] + [(DX, LH[-1][1])], 'thin')+for y in sorted(ys_o + list(teeth)):+ xl = np.interp(y, LH[:, 1], LH[:, 0])+ bp.line([(xl + 2, y), (DX - 2, y)], 'fine', pool=False)+for ph in (0.38, 0.72): # bronze uprights of the frame+ bp.line([(DX - (DX - x) * np.sin(np.pi / 2 * ph * 1.0) , y) for x, y in LH], 'fine', pool=False)+# lamp and table+TABLE = [(DX - 1.0 * KD, yd(34.3)), (DX + 1.0 * KD, yd(34.3)), (DX + 1.0 * KD, yd(34.43)), (DX - 1.0 * KD, yd(34.43))]+bp.hatch([TABLE], 45, 3.2, kind='cross'); bp.line(TABLE, 'thin', closed=True)+for xr_ in (-0.75, -0.4, 0.4, 0.75):+ bp.circle(DX + xr_ * KD, yd(34.3) + 5, 4.2, 'thin')+bp.line([(DX - 0.95 * KD, yd(34.3) + 9.5), (DX + 0.95 * KD, yd(34.3) + 9.5)], 'medium')+for side in (-1, 1):+ bp.line([(DX + side * 7, yd(34.43)), (DX + side * 7, FY + 12)], 'thin')+bp.line([(DX - 11, FY + 12), (DX + 11, FY + 12)], 'medium')+flame = [(DX, FY - 24), (DX + 5, FY - 10), (DX + 7, FY + 1), (DX + 4, FY + 8), (DX, FY + 10), (DX - 4, FY + 8), (DX - 7, FY + 1), (DX - 5, FY - 10)]+bp.line(_spl(flame + [flame[0]], 6), 'thin', closed=True)+bp.line(_spl([(DX, FY - 12), (DX + 3, FY - 2), (DX, FY + 5), (DX - 3, FY - 2), (DX, FY - 12)], 5), 'fine')+# lantern glass, astragal, cornice, the start of the dome, and the break+XG = DX + 1.95 * KD+bp.line([(XG - 2, yd(37.0)), (XG - 2, yd(34.3))], 'thin'); bp.line([(XG + 2, yd(37.0)), (XG + 2, yd(34.3))], 'thin')+bp.hatch([[(XG - 2, yd(36.3)), (XG + 2, yd(36.3)), (XG + 2, yd(34.9)), (XG - 2, yd(34.9))]], 60, 4, kind='glass')+for hh in (35.0, 36.25): # astragals cut through+ bp.fill([(XG - 4, yd(hh) - 4), (XG + 4, yd(hh) - 4), (XG + 4, yd(hh) + 4), (XG - 4, yd(hh) + 4)])+CORN = [(XG - 8, yd(37.0)), (XG + 16, yd(37.0)), (XG + 16, yd(37.25)), (XG - 8, yd(37.25))]+bp.hatch([CORN], 45, 3.2, kind='cross'); bp.line(CORN, 'thin', closed=True)+SILL = [(XG - 8, yd(34.3)), (XG + 10, yd(34.3)), (XG + 10, yd(34.3) + 14), (XG - 8, yd(34.3) + 14)]+bp.hatch([SILL], 45, 3.2, kind='cross'); bp.line(SILL, 'thin', closed=True)+bp.breakline((1318, yd(34.3) + 34), (1730, yd(34.3) + 34))+# rays: from the flame through each prism, then out level as one beam+XE = 1758+for ry in rays:+ pts = [tuple(p) for p in ry] + [(XE, ry[-1][1])]+ bp.line(pts, 'fine', pool=False)+ bp.arrowhead((XE + 1, ry[-1][1]), (1, 0), 8)+bp.stage('detail')++# ================================================================== 8. dimensions, levels, cut marks, leaders+def ext(x0, y, x1):+ bp.line([(x0, y), (x1, y)], 'fine', pool=False)+++CH = [0.0, 2.5, 30.0, 33.3, 41.2]+for h, xo_ in zip(CH, [EX - 4.6 * S, EX - 4.75 * S, EX - 3.75 * S, EX - 2.75 * S, EX - 0.2 * S]):+ ext(xo_ - 4, Y(h), 118 if h in (0.0, 41.2) else 146)+for a, b in zip(CH[:-1], CH[1:]):+ bp.dim((150, Y(a)), (150, Y(b)), 0, f'{b - a:.2f}', size=10)+bp.dim((122, Y(0.0)), (122, Y(41.2)), 0, '41.20', size=11)+# levels between the elevation and the section+LV = [(2.5, '+2.50', 'ENTRANCE'), (30.0, '+30.00', 'GALLERY'), (33.3, '+33.30', 'LANTERN FLOOR'),+ (35.7, '+35.70', 'FOCAL PLANE'), (41.2, '+41.20', '')]+for h, t, name in LV:+ xr = SX - (Rout(h) if 0 < h <= 30.0 else {33.3: 2.75, 35.7: 1.95, 41.2: 0.1}.get(h, 4.75)) * S - 6+ bp.level(xr, Y(h), t, size=10, length=xr - 470, side='left', mark_at=548)+ if name: bp.text(name, 528, Y(h) + 13, 7, 'rs')+for h, t, name, x0 in ((0.0, '±0.00', 'ROCK DATUM', SX + 4.95 * S), (SEA, '-1.80', 'HIGH WATER', SX + 8.6 * S)):+ bp.level(x0 + 4, Y(h), t, size=10, length=902 - x0, side='right', mark_at=878)+ bp.text(name, 888, Y(h) + 13, 7, 'ls')+# section B-B on the section, section A-A on the plan+bp.cut_mark((SX - 5.2 * S, Y(6.5)), (SX + 5.2 * S, Y(6.5)), 'B', (0, 1), size=13, through=False, arm=18)+bp.cut_mark((PX - 4.35 * K, PY), (PX + 4.35 * K, PY), 'A', (0, -1), size=14, through=False, arm=18)+# wall thickness and plan dimensions+bp.dim((SX - 4.0 * S, Y(3.4)), (SX - 2.55 * S, Y(3.4)), 0, '1.45', size=9, text_off=4)+bp.dim((SX + 2.05 * S, Y(27.2)), (SX + Rs(27.2) * S, Y(27.2)), 0, '0.68', size=9, text_off=4)+bp.dim(pp(Ro, np.pi), pp(Ro, 0), Ro * K + 30, f'Ø{2 * Ro:.2f}', size=11)+bp.dim(pp(Ro, np.radians(212)), pp(Ri, np.radians(212)), 0, f'{Ro - Ri:.2f}', size=9, text_off=4)+bp.text('UP', *pp(rm - 0.42, thc - 3.45), 9, 'mm')+bp.text('120 STEPS', PX, PY + 1.05 * K, 8, 'mm', clear=True)+# leaders on the section+bp.circle(SX, Y(35.75), 2.55 * S, 'thin', dash=(7, 4))+bp.line([(SX + 2.55 * S * 0.72, Y(35.75) - 2.55 * S * 0.69), (858, 214)], 'fine', pool=False)+bp.bubble(872, 205, 15, '1', '3', size=12)+L = 806+bp.leader([(SX + 2, Y(40.4)), (L - 14, Y(40.9))], 'LIGHTNING CONDUCTOR', 8)+bp.leader([(SX + 0.4 * S, Y(39.42)), (L - 14, Y(39.42))], 'VENTILATOR', 8, end='dot')+bp.leader([(SX + 1.95 * S, Y(36.6)), (L - 34, Y(37.9)), (L - 14, Y(37.9))], 'HELICAL ASTRAGALS', 8, end='dot')+bp.leader([(SX + 0.85 * S, Y(31.0)), (L - 14, Y(31.9))], 'CLOCKWORK,\nWIND EVERY 4 H', 8, end='dot')+bp.leader([(SX + 0.2 * S, Y(22.0)), (L - 14, Y(22.6))], 'WEIGHT TUBE\n(HOLLOW NEWEL)', 8, end='dot')+bp.leader([(SX + 0.12 * S, Y(14.6)), (L - 14, Y(15.4))], 'WEIGHT 180 KG,\nFALLS 22 M IN 4 H', 8, end='dot')+bp.leader([(SX + 1.6 * S, Y(10.47)), (L - 14, Y(10.6))], 'STONE STAIR,\n120 STEPS', 8, end='dot')+bp.leader([(SX + 3.3 * S, Y(4.6)), (L - 14, Y(4.9))], 'GRANITE, DOVETAILED\nCOURSES', 8, end='dot')+bp.leader([(SX - 0.9 * S, Y(1.0)), (566, Y(1.0))], 'CISTERN', 8, end='dot')+bp.revision(SX - 3.6 * S - 16, Y(31.2), 'B', 10)+bp.revision(EX - 3.6 * S - 16, Y(31.2), 'B', 10)+# detail labels+def brace(y0, y1, x, label):+ bp.line([(x - 5, y0), (x, y0), (x, y1), (x - 5, y1)], 'fine', pool=False)+ bp.line([(x, (y0 + y1) / 2), (x + 6, (y0 + y1) / 2)], 'fine', pool=False)+ bp.text(label, x + 11, (y0 + y1) / 2, 8, 'lm')+++up_y = [r[-1][1] for r in rays[:5]]; lo_y = [r[-1][1] for r in rays[5:9]]; be_y = [r[-1][1] for r in rays[9:]]+brace(min(up_y) - 3, max(up_y) + 3, 1772, 'CATADIOPTRIC\nPRISMS:\nREFLECT')+brace(min(be_y) - 3, max(be_y) + 3, 1772, 'DIOPTRIC\nBELT:\nREFRACT')+brace(min(lo_y) - 3, max(lo_y) + 3, 1772, 'CATADIOPTRIC\nPRISMS:\nREFLECT')+bp.leader([(DX - 3, FY - 4), (1318, 236)], 'F', 10, end='dot')+bp.leader([(DX - 7, FY + 66), (1318, FY + 104)], 'LAMP', 8, end='dot')+bp.leader([(DX - 0.75 * KD, yd(34.3) + 5), (1318, yd(34.3) + 5)], 'ROLLERS', 8, end='dot')+bp.leader([(XG + 2, yd(34.75)), (XG + 26, yd(34.3) + 2), (XG + 36, yd(34.3) + 2)], 'LANTERN GLASS', 8, end='dot')+bp.text('PARALLEL BEAM · FL.(2) EVERY 10 S · 19 NM', 1860, 76, 8, 'rs')+bp.stage('dimensions')++# ================================================================== 9. lettering: titles, notes, scales, blocks+bp.view_title(EX, 1004, 'SOUTH ELEVATION', '1:200', 15)+bp.view_title(SX, 1004, 'SECTION A–A', '1:200', 15)+bp.view_title(PX, 505, 'PLAN B–B AT +6.50', '1:100', 13)+bp.view_title(1600, 538, 'DETAIL 1 — LENS AND LAMP', '1:30', 13, bubble=('1', '3'))+bp.north(994, 452, 17)+NX, NY = 994, 600+bp.text('GENERAL NOTES', NX, NY, 12, 'ls', pen=1.3)+bp.line([(NX, NY + 5), (NX + bp.text_width('GENERAL NOTES', 12), NY + 5)], 'thin')+NOTES = ['1. DIMENSIONS ARE IN METRES; LEVELS ARE TAKEN FROM ROCK DATUM.',+ '2. TOWER OF DOVETAILED GRANITE COURSES IN LIME MORTAR.',+ '3. STAIR: 120 CANTILEVERED STONE STEPS, RISE 0.23,',+ ' WOUND ROUND A HOLLOW NEWEL.',+ '4. THE NEWEL IS THE WEIGHT TUBE. THE CLOCKWORK WEIGHT',+ ' FALLS 22 M IN 4 H AND TURNS THE LENS ONCE IN 20 S.',+ '5. THE KEEPER WINDS THE CLOCKWORK EVERY 4 HOURS.',+ '6. LIGHT: FIRST ORDER LENS, FOCAL PLANE +35.70,',+ ' FL.(2) EVERY 10 S, RANGE 19 NAUTICAL MILES.',+ '7. LANTERN AND LENS: DETAIL 1, THIS SHEET.']+for i, s in enumerate(NOTES):+ bp.text(s, NX, NY + 28 + i * 19, 8, 'ls', guide=True, spacing=0.2)+bp.scale_bar(1050, 846, S, (0, 2, 4, 6, 8, 10), label='ELEVATION AND SECTION 1:200 — METRES', size=9)+bp.scale_bar(1050, 912, K, (0, 1, 2, 3, 4, 5), label='PLAN 1:100 — METRES', size=9)+bp.scale_bar(1050, 978, KD, (0, 0.5, 1, 1.5), label='DETAIL 1:30 — METRES', size=9)+# revision block+for (x0, y0, x1, y1), t in zip(RB[0], ('REV', 'DESCRIPTION', 'DATE', 'BY')):+ bp.text(t, (x0 + x1) / 2, (y0 + y1) / 2, 7, 'mm')+for row, vals in zip(RB[1:], (('A', 'ISSUED FOR TENDER', '02.1911', 'J.K.'), ('B', 'GALLERY RAIL RAISED TO 1.25', '05.1911', 'R.T.'))):+ for (x0, y0, x1, y1), t in zip(row, vals):+ bp.text(t, (x0 + x1) / 2 if t in vals[:1] + vals[2:] else x0 + 8, (y0 + y1) / 2, 9, 'mm' if t in vals[:1] + vals[2:] else 'lm')+# title block+(x0, y0, x1, y1) = (TB[0][0][0], TB[0][0][1], TB[0][-1][2], TB[0][0][3])+bp.text('COASTAL WORKS OFFICE — LIGHTS DIVISION', (x0 + x1) / 2, (y0 + y1) / 2, 9, 'mm')+(x0, y0, x1, y1) = (TB[1][0][0], TB[1][0][1], TB[1][-1][2], TB[1][0][3])+bp.text('HALVARD ROCK LIGHT', (x0 + x1) / 2, y0 + 30, 21, 'ms', pen=2.0, spacing=0.26)+bp.text('TOWER: ELEVATION, SECTION, PLAN AND LENS DETAIL', (x0 + x1) / 2, y0 + 49, 8, 'ms')+(x0, y0, x1, y1) = (TB[2][0][0], TB[2][0][1], TB[2][-1][2], TB[2][0][3])+bp.cjk('灯塔 立面 · 剖面 · 平面及透镜详图', (x0 + x1) / 2, y1 - 6, 16, 'ms', condense=0.82)+for (cx0, cy0, cx1, cy1), lab, val in zip(TB[3], ('DRAWN', 'TRACED', 'CHECKED', 'APPROVED'), ('J.K.', 'M.O.', 'R.T.', 'H. LUND')):+ bp.text(lab, cx0 + 5, cy0 + 11, 6, 'ls')+ bp.text(val, (cx0 + cx1) / 2, cy1 - 10, 11, 'ms', slant=0.22)+for (cx0, cy0, cx1, cy1), lab, val in zip(TB[4], ('SCALE', 'DATE', 'SHEET', 'DRAWING NO.'), ('AS SHOWN', 'MARCH 1911', '3 OF 7', 'LH-117-03 B')):+ bp.text(lab, cx0 + 5, cy0 + 11, 6, 'ls')+ bp.text(val, (cx0 + cx1) / 2, cy1 - 11, 11 if len(val) < 10 else 10, 'ms')+bp.stage('lettering')++# ================================================================== 10. the sheet's life: folded, filed, handled+bp.fold(xs=[640, 1280], ys=[540])+bp.fade(1280, 540, 1920, 1080, 0.13)+bp.grime(1280, 540, 1920, 1080, 0.9)+bp.fade(0, 0, 640, 540, 0.05)+bp.stain(92, 1012, 62)+for x, y in ((24, 16), (1896, 16), (24, 1064), (1896, 1064)): bp.tack(x, y)+bp.tear(640, 0, (0, 1), 9); bp.tear(1280, 1079, (0, -1), 7); bp.tear(0, 540, (1, 0), 6)+bp.stage('folded')++# ================================================================== 11. the site engineer's red pencil+bp.cloud([(797, Y(10.6) - 23), (915, Y(10.6) - 23), (915, Y(10.6) + 22), (797, Y(10.6) + 22)], bump=19)+bp.red_text('counted:', 836, Y(10.6) + 60, 19, rot=4)+bp.red_text('119 + landing', 826, Y(10.6) + 84, 19, rot=4)+bp.red([(951, Y(10.6) + 70), (957, Y(10.6) + 79), (972, Y(10.6) + 56)], 2.4, smooth=False)+c = TB[3][2]+bp.red([(c[0] + 66, c[1] + 22), (c[0] + 72, c[1] + 30), (c[0] + 90, c[1] + 8)], 2.6, smooth=False)++img = bp.save(out, stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/cave_hunt.jpg b/examples/cave_hunt.jpgnew file mode 100644index 0000000..82c287fBinary files /dev/null and b/examples/cave_hunt.jpg differdiff --git a/examples/cave_hunt.py b/examples/cave_hunt.pynew file mode 100644index 0000000..fb7a2f1--- /dev/null+++ b/examples/cave_hunt.py@@ -0,0 +1,119 @@+"""Example (cave painting, ochre and charcoal by firelight): The Hunt by the Fire / 篝火旁的岩洞 -- a limestone cave+wall painted in red and yellow ochre and charcoal, lit only by a campfire on the floor and a stone fat lamp.+The wall tells one hunt: a great bison, painted on a natural bulge of the rock so the stone gives it its belly and+hump, has turned to face two red hunters running at it with raised spears; two spears already hang in its back. The rest+of the herd runs the other way -- a horse with a black mane, a stag and a hind -- and a second horse above them was+only sketched in charcoal and never coloured. The painters signed with blown hand stencils over the fire (three+red, one black with two fingers bent down); a row of palm dots and a grid sign sit low on the wall. On the floor lie their tools: a flat stone with heaps of ground+ochre, charcoal sticks and a hollow bone for blowing paint. Time: calcite veils, flaked paint, a cave bear's claw+marks and the soot of many fires. No image model.+python3 cave_hunt.py [out.jpg] [--stages DIR]+"""+import os, sys+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from cave import CavePainting++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'cave_hunt.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++cv = CavePainting(1920, 1080, seed=7)++# ---- the wall: limestone, the bulge the bison will stand on, flowstone, cracks, the floor, fire and lamp+cv.wall()+cv.boss(1430, 440, 250, 165, 38) # the bison's bulge+cv.boss(880, 540, 190, 120, 26) # the horse's flank+cv.fold([(-20, 690), (300, 640), (620, 700), (980, 760), (1240, 700)], height=11, soft=26, side=-1)+cv.flowstone(1830, 1935, top=0, length=430)+cv.crack([(1948, 300), (1905, 335), (1890, 380)], width=2.2, depth=7, branches=0)+cv.floor(966, tilt=1.3)+cv.fire(236, 1032, 262)+cv.lamp(1700, 1004, 128)+cv.stone([(540, 996), (660, 984), (780, 992), (812, 1024), (730, 1050), (580, 1048), (522, 1022)], colour='#8c7a66', height=12)+cv.heap(592, 1010, 30, 'red'); cv.heap(668, 1002, 26, 'yellow'); cv.heap(738, 1016, 20, 'darkred')+cv.stick((598, 1036), (676, 1031), 11, 'black'); cv.stick((690, 1040), (752, 1030), 10, 'black')+cv.stick((850, 1052), (1000, 1020), 16, '#d6c9ad', hollow=True, tip='red')+rng = np.random.default_rng(5)+for x in rng.uniform(380, 1880, 26): # rubble along the foot of the wall+ y = 972 + rng.uniform(0, 26); r = rng.uniform(5, 13)+ if 500 < x < 1020 or 1590 < x < 1800: continue+ cv.stone([(x + np.cos(t) * r * rng.uniform(0.8, 1.2), y + np.sin(t) * r * 0.6) for t in np.linspace(0, 6.28, 8, endpoint=False)],+ colour='#7a6a5a', height=r * 0.6, rough=1.2)+cv.stage('firelit_wall')++# ---- draft the animals and sketch them in charcoal+bison = cv.bison(1440, 482, 440, facing=1, head_drop=0.02)+horse = cv.horse(862, 560, 330, facing=-1, gait='run')+ghost = cv.horse(1085, 232, 262, facing=-1, gait='stand')+stag = cv.deer(470, 500, 230, facing=-1, kind='stag', gait='leap')+hind = cv.deer(522, 762, 190, facing=-1, kind='hind', gait='leap')+for f in (bison, horse, stag, hind):+ cv.sketch(f)+cv.sketch(ghost, strength=0.9, passes=3)+cv.stage('charcoal_sketch')++# ---- red ochre: the bison's body (pale belly left bare), the deer+cv.blow(bison.sel('body'), 'red', density=0.97, rim=0.2, gradient=0.15, relief=0.2, exclude=bison.sel('belly'))+cv.blow(bison.sel('belly'), 'orange', density=0.35, edge=6, halo=8, speckle=0.3)+cv.blow(stag.sel('body', 'ears', 'tail', 'legs'), 'red', density=0.95, rim=0.18, gradient=0.15, exclude=stag.sel('belly'))+cv.blow(hind.sel('body', 'ears', 'tail', 'legs'), 'orange', density=0.85, rim=0.15)+cv.stage('red_ochre')++# ---- yellow ochre: the horse, darker along the back+cv.blow(horse.sel('body'), 'yellow', density=0.97, rim=0.15, exclude=horse.sel('belly'), relief=0.2)+cv.blow(horse.sel('back'), 'orange', density=0.6, edge=8, halo=10, speckle=0.4, clip=horse)+cv.stage('yellow_ochre')++# ---- charcoal and manganese black: heads, manes, humps, legs+cv.blow(horse.sel('head', 'mane', 'ears'), 'black', density=0.97, edge=3, clip=horse, soft_clip=1.5)+cv.blow(horse.sel('legs', 'tail'), 'black', density=0.95, edge=1.6, halo=6, halo_amt=0.1, exclude=horse.sel('body'))+cv.blow(bison.sel('head'), 'darkred', density=0.62, edge=6, halo=8, clip=bison)+cv.blow(bison.sel('hump'), 'black', density=0.95, edge=9, halo=12, relief=0.25, clip=bison)+cv.blow(bison.sel('legs', 'horns', 'tail'), 'black', density=0.95, edge=1.6, halo=6, halo_amt=0.1, exclude=bison.sel('body'))+cv.blow(stag.sel('head'), 'darkred', density=0.7, edge=6, clip=stag)+cv.stage('black')++# ---- the contours and details+cv.outline(bison, 'black', width=7.5, top=0.8, gaps=0.1)+cv.outline(horse, 'black', width=5.5, top=0.7, gaps=0.14)+cv.outline(stag, 'manganese', width=4.0, top=0.6, gaps=0.16)+cv.blow(stag.sel('antlers'), 'black', density=0.9, edge=1.2, halo=6)+cv.outline(hind, 'darkred', width=3.5, gaps=0.2, kind='blow')+cv.outline(ghost, 'black', width=4.5, top=0.9, gaps=0.3, strength=0.9) # the horse nobody finished+cv.dots([bison.anchors['eye']], r=9, pigment='white', strength=0.9) # the bison's eye: a pale almond+for f, r in ((bison, 4.5), (horse, 5), (stag, 4), (hind, 3.5)):+ cv.dots([f.anchors['eye']], r=r, pigment='black', strength=0.95)+cv.stage('contours')++# ---- the hunters, their spears, and the spears already in the bison+h1 = cv.hunter(1800, 704, 156, facing=-1, pose='throw')+h2 = cv.hunter(1858, 884, 138, facing=-1, pose='run')+for h in (h1, h2):+ cv.paint(h, 'red', kind='finger')+ g, d = h.anchors['grip'], h.anchors['spear_dir']+ cv.paint(cv.spear(g - d * 70, g + d * 130, 4.0), 'black', kind='charcoal')+cv.paint(cv.spear((1590, 206), (1488, 420), 4.6), 'black', kind='charcoal')+cv.paint(cv.spear((1500, 196), (1432, 404), 4.6), 'black', kind='charcoal')+cv.stage('hunters')++# ---- the painters' hands, palm dots and a grid sign+for (x, y, s, rot, side, pig, fold) in ((104, 372, 124, 16, 'right', 'red', ()), (250, 250, 132, 0, 'left', 'red', ()),+ (128, 168, 108, 10, 'right', 'black', (3, 4)), (118, 590, 112, 24, 'left', 'red', ())):+ cv.stencil(cv.hand(x, y, s, rot=rot, side=side, fold=fold), pig, density=0.95, spread=26)+cv.dots([(610 + i * 54, 872 + 6 * np.sin(i * 0.9)) for i in range(8)], r=13, pigment='red')+g = [(1200, 822), (1246, 816), (1292, 819), (1294, 850), (1290, 880), (1244, 884), (1203, 879), (1199, 850), (1200, 822)]+cv.line(g, 5, 'red', kind='finger')+for k in range(1, 4):+ xk = 1200 + k * 23+ cv.line([(xk, 818), (xk + 2, 850), (xk - 1, 882)], 4, 'red', kind='finger')+cv.stage('hands_and_signs')++# ---- time: calcite veils, flakes, a cave bear's claws, soot of many fires+cv.calcite(1236, 600, 100, 66, amount=0.42)+cv.calcite(660, 830, 80, 52, amount=0.35)+cv.flake(28, size=(1.5, 3.5), min_load=0.6)+cv.claws(1790, 120, angle=-100, n=4, length=190, spread=19)+cv.claws(1715, 760, angle=-80, n=3, length=120, spread=16, depth=2.6, width=5)+cv.soot(236, 820, amount=0.22, drift=0.3, spread=0.22)++cv.save(out, stages)diff --git a/examples/crayon_picnic.jpg b/examples/crayon_picnic.jpgnew file mode 100644index 0000000..c734cc0Binary files /dev/null and b/examples/crayon_picnic.jpg differdiff --git a/examples/crayon_picnic.py b/examples/crayon_picnic.pynew file mode 100644index 0000000..5d59756--- /dev/null+++ b/examples/crayon_picnic.py@@ -0,0 +1,437 @@+"""Example (children's crayon drawing / 儿童蜡笔画): 我的周末 · My Weekend — a six-year-old's crayon picture of a+family picnic, on rough drawing paper. A sun in sunglasses in the corner, the title written in four colours, a kite,+a rainbow coming out from behind the hill, clouds the sky was coloured around; the house with curly chimney smoke+and an apple tree on the hill; Dad (with a tie), Mum (polka-dot dress) and me (pigtails, holding the kite string)+standing hand in hand behind a red gingham blanket with a basket, sandwiches, juice and watermelon; the dog leaping+for a ball; tulips, daisies, a butterfly and the artist's name. Two real crayons (one snapped, its sleeve torn) and+some wax crumbs lie on the paper. Everything is outlined first and the big areas are coloured round what is already+there, the way a child does it.+Draw-on stages: paper -> outlines -> sun, title & name -> rainbow, kite & sky -> hills & meadow -> house & tree ->+family -> picnic & dog -> flowers & kite string -> the crayons (final). No image model.+python3 crayon_picnic.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from crayon import Crayon+from core import spline++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'crayon_picnic.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++c = Crayon(1920, 1080, seed=11)+C = c.C+rng = c.rng+c.paper()+c.stage('paper')+++def arc(cx, cy, rx, ry, a0, a1, n=40):+ """points on an ellipse arc; angles in degrees, 0 = right, 90 = up"""+ t = np.radians(np.linspace(a0, a1, n))+ return np.stack([cx + rx * np.cos(t), cy - ry * np.sin(t)], 1)+++def U(*ms):+ return np.maximum.reduce([np.asarray(m, np.float32) for m in ms])+++def cloud_pts(cx, cy, w, h, bumps=5):+ """a child's cloud: scallops along the top, a flatter bottom"""+ t = np.linspace(0, 2 * np.pi, 220, endpoint=False)+ top = np.sin(t) > 0+ r = 1 + np.where(top, 0.2 * np.abs(np.sin(t * bumps / 2 + 0.3)), 0.06 * np.abs(np.sin(t * bumps)))+ return np.stack([cx + w * np.cos(t) * r, cy - h * np.sin(t) * r * np.where(top, 1.0, 0.55)], 1)+++def hand(x, y, r=12, colour=C['black'], spread=(200, 340)):+ """a hand: a little circle with a rake of fingers"""+ c.line(c.circle(x, y, r, lumpy=0.05, amp=1), colour, width=7, closed=True)+ for a in np.linspace(*spread, 5):+ a = np.radians(a)+ c.line([(x + r * np.cos(a), y - r * np.sin(a)), (x + (r + 13) * np.cos(a), y - (r + 13) * np.sin(a))],+ colour, width=6)+++objects = [] # interiors of everything sketched, so the big fills can colour around them++# ===================================================================== 1. outlines+SX, SY, SR = 190, 172, 98+sun = c.circle(SX, SY, SR, lumpy=0.03)+c.line(sun, C['orange'], width=10, closed=True)++# house on the hill+house = c.rect(150, 482, 430, 690, skew=5)+roof = c.poly([(120, 494), (290, 360), (460, 494)])+chim = c.poly([(365, 425), (366, 384), (399, 386), (399, 450)])+door = c.rect(262, 598, 318, 690, skew=2)+win1, win2 = c.rect(172, 520, 238, 576, skew=3), c.rect(345, 518, 411, 576, skew=3)+for p in (chim, roof, house, door, win1, win2):+ c.line(p, C['black'], width=9, closed=True)+objects += [c.mask(p) for p in (house, roof, chim)]++# apple tree+trunk = c.poly([(570, 488), (602, 488), (608, 700), (622, 716), (556, 716), (566, 700)])+crown = c.circle(588, 418, 112, 96, lumpy=0.12)+c.line(trunk, C['brown'], width=9, closed=True)+c.line(crown, C['darkgreen'], width=10, closed=True)+objects += [c.mask(trunk), c.mask(crown)]++# hills and the meadow line+hillL = spline([(-30, 600), (180, 478), (420, 440), (640, 486), (880, 590), (1010, 668)], 12)+hillR = spline([(740, 676), (1000, 566), (1300, 522), (1620, 534), (1960, 586)], 12)+meadow = spline([(-30, 694), (420, 676), (900, 684), (1400, 664), (1960, 690)], 12)++# the family, hand in hand: Dad, Mum, me+DAD, MUM, ME = 745, 905, 1062+dad_head = c.circle(DAD, 468, 48, lumpy=0.04)+dad_shirt = c.rect(697, 522, 793, 666, skew=4)+dad_legs = [c.rect(704, 664, 738, 790, skew=2), c.rect(752, 664, 786, 790, skew=2)]+mum_head = c.circle(MUM, 486, 45, lumpy=0.04)+mum_hair = c.poly(list(arc(MUM, 492, 64, 66, -12, 192, 30)) + [(MUM - 66, 580), (MUM - 40, 572), (MUM + 40, 572), (MUM + 66, 580)], amp=2.5)+mum_dress = c.poly([(MUM - 16, 532), (MUM + 16, 532), (MUM + 74, 722), (MUM - 74, 722)])+me_head = c.circle(ME, 560, 42, lumpy=0.04)+me_shirt = c.rect(1030, 604, 1094, 676, skew=3)+me_skirt = c.poly([(1028, 672), (1096, 672), (1112, 720), (1012, 720)])+for p in [mum_hair]:+ c.line(p, C['brown'], width=8, closed=True)+for p in [dad_head, dad_shirt, *dad_legs, mum_head, mum_dress, me_head, me_shirt, me_skirt]:+ c.line(p, C['black'], width=8, closed=True)+# arms and hands (holding hands: one round hand between two people)+c.line(spline([(700, 540), (676, 590), (650, 628)], 8), C['black'], width=9)+hand(642, 636, spread=(150, 300))+c.line(spline([(790, 540), (812, 580), (826, 612)], 8), C['black'], width=9)+c.line(spline([(MUM - 26, 566), (MUM - 50, 594), (MUM - 64, 614)], 8), C['black'], width=9)+hand(836, 616, r=13, spread=(250, 290))+c.line(spline([(MUM + 26, 566), (MUM + 52, 600), (MUM + 76, 624)], 8), C['black'], width=9)+c.line(spline([(1034, 620), (1012, 628), (1000, 630)], 8), C['black'], width=9)+hand(990, 630, r=13, spread=(250, 290))+c.line(spline([(1092, 618), (1106, 596), (1114, 574)], 8), C['black'], width=9)+hand(1118, 562, r=12, spread=(20, 160))+for x0, x1, y in [(MUM - 22, MUM - 24, 722), (MUM + 22, MUM + 24, 722), (1048, 1046, 720), (1076, 1078, 720)]:+ c.line([(x0, y), (x1, y + 72)], C['black'], width=9)+objects += [c.mask(p) for p in [dad_head, dad_shirt, *dad_legs, mum_head, mum_hair, mum_dress, me_head, me_shirt, me_skirt]]+objects += [c.mask(c.rect(MUM - 40, 715, MUM + 40, 805, 0)), c.mask(c.rect(1035, 715, 1090, 805, 0)),+ c.mask(c.rect(630, 530, 830, 650, 0)), c.mask(c.rect(975, 550, 1135, 645, 0))]++# the picnic blanket (a child's perspective: wider at the front) and what is on it+TL, TR, BR, BL = np.array([565, 830.]), np.array([1225, 830.]), np.array([1292, 1006.]), np.array([498, 1006.])+blanket = c.poly([TL, TR, BR, BL], amp=2.5)+c.line(blanket, C['red'], width=10, closed=True)+basket = c.poly([(598, 852), (748, 852), (732, 944), (614, 944)])+handle = arc(673, 856, 62, 70, 180, 0, 30)+plate = c.circle(888, 925, 92, 30, lumpy=0.02)+sand1 = c.poly([(828, 920), (880, 866), (902, 928)])+sand2 = c.poly([(904, 924), (934, 864), (962, 916)])+glass = c.poly([(1004, 858), (1046, 858), (1040, 946), (1010, 946)])+mel1 = c.poly(list(arc(1124, 912, 56, 52, 180, 360, 30)))+mel2 = c.poly(list(arc(1206, 940, 46, 42, 170, 350, 26)))+for p, col in [(basket, C['brown']), (plate, C['sky']), (sand1, C['tan']), (sand2, C['tan']), (glass, C['blue']),+ (mel1, C['darkgreen']), (mel2, C['darkgreen'])]:+ c.line(p, col, width=8, closed=True)+c.line(handle, C['brown'], width=11)+objects += [c.mask(blanket)]++# the dog, leaping for the ball+dog_body = c.circle(1446, 862, 90, 40, rot=-0.2, lumpy=0.04)+dog_head = c.circle(1548, 806, 42, lumpy=0.04)+dog_snout = c.circle(1590, 820, 24, 17, lumpy=0.03)+dog_ear = c.circle(1526, 806, 15, 32, rot=0.35, lumpy=0.05)+for p in (dog_body, dog_head, dog_snout):+ c.line(p, C['brown'], width=9, closed=True)+legs = [[(1502, 872), (1532, 888), (1562, 898)], [(1486, 884), (1514, 902), (1540, 918)],+ [(1390, 884), (1364, 902), (1334, 914)], [(1404, 892), (1384, 914), (1364, 934)]]+for lg in legs:+ c.line(spline(lg, 8), C['brown'], width=15)+tail = spline([(1360, 846), (1336, 822), (1322, 792)], 8)+c.line(tail, C['brown'], width=12)+ball = c.circle(1668, 752, 27, lumpy=0.03)+c.line(ball, C['red'], width=8, closed=True)+objects += [c.mask(p) for p in (dog_body, dog_head, dog_snout, ball)]++# the kite and the clouds+KC = np.array([1300, 172.])+KT, KR, KB, KL = KC + (0, -92), KC + (90, -8), KC + (0, 138), KC + (-90, -8)+kite = c.poly([KT, KR, KB, KL], amp=1.5)+c.line(kite, C['black'], width=8, closed=True)+cl1 = c.wobble(cloud_pts(1712, 108, 118, 52, 5), 1.5)+cl2 = c.wobble(cloud_pts(712, 262, 84, 38, 4), 1.5)+for p in (cl1, cl2):+ c.line(p, C['blue'], width=8, closed=True)+objects += [c.mask(kite), c.mask(cl1), c.mask(cl2)]++# flowers and a butterfly in the grass+tulips = []+for (x, y, col) in [(84, 872, 'red'), (190, 900, 'pink'), (300, 868, 'orange'), (1360, 984, 'magenta')]:+ c.line([(x, y), (x + rng.normal(0, 4), y + 96)], C['darkgreen'], width=8)+ leaves = [c.poly([(x, y + 80), (x + s * 30, y + 40), (x + s * 8, y + 62)], amp=0.6) for s in (-1, 1)]+ head = c.poly([(x - 26, y - 4), (x - 28, y - 48), (x - 12, y - 30), (x, y - 54), (x + 12, y - 30), (x + 28, y - 48),+ (x + 26, y - 4), (x, y + 10)], amp=1.0)+ for lf in leaves:+ c.line(lf, C['darkgreen'], width=6, closed=True)+ c.line(head, C[col], width=7, closed=True)+ tulips.append((head, leaves, col))+ objects += [c.mask(head)] + [c.mask(lf) for lf in leaves]+daisies = [(1440, 1046), (1250, 1052), (432, 1000)]+for (x, y) in daisies:+ for k in range(8):+ a = k * np.pi / 4 + 0.2+ pt = c.circle(x + 20 * np.cos(a), y - 20 * np.sin(a), 11, 7, rot=-a, lumpy=0.02, amp=0.5)+ c.line(pt, C['grey'], width=4, closed=True, pressure=0.6)+ objects += [c.mask(c.circle(x, y, 34))]+BX, BY = 500, 780+wings = []+for s in (-1, 1):+ for (dy, rx, ry, col) in [(-17, 32, 25, 'pink'), (17, 24, 19, 'violet')]:+ w = c.circle(BX + s * (rx + 7), BY + dy, rx, ry, rot=s * 0.45)+ c.line(w, C['purple'], width=6, closed=True)+ wings.append((w, col))+ objects += [c.mask(w)]+# the ball's motion lines, the dog's wag lines+for k in range(3):+ y = 736 + k * 16+ c.line([(1602 - k * 6, y), (1630 - k * 4, y - 2)], C['grey'], width=5, pressure=0.7)+for r in (22, 34):+ c.line(arc(1320, 790, r, r, 100, 190, 10), C['brown'], width=5, pressure=0.7)++OBJ = U(*objects)+LINES0 = c.drawn() # every line drawn so far (arms, legs, stems, strings)+c.line(hillL, C['darkgreen'], width=9, avoid=c.grow(OBJ, 10))+c.line(hillR, C['green'], width=9, avoid=c.grow(OBJ, 10))+c.line(meadow, C['darkgreen'], width=8, pressure=0.75, avoid=c.grow(OBJ, 10))+c.stage('outlines')++# ===================================================================== 2. sun and title+c.loops(c.mask(sun), C['yellow'], r=20, width=12, density=0.62, pressure=0.85)+c.scribble(c.mask(sun) * (c.YY > SY + 30) * (c.XX > SX - 20), C['orange'], angle=-30, width=14, density=0.35,+ pressure=0.55, reach=None, mess=0.2)+for k in range(12):+ a = np.radians(k * 30 + 8)+ r0, r1 = SR + 20, SR + (88 if k % 2 else 52)+ c.line([(SX + r0 * np.cos(a), SY - r0 * np.sin(a)), (SX + r1 * np.cos(a), SY - r1 * np.sin(a))],+ C['orange'] if k % 2 else C['yellow'], width=12, pressure=0.95)+# sunglasses, smile, cheeks+lens1 = c.rect(SX - 64, SY - 34, SX - 12, SY + 4, skew=2)+lens2 = c.rect(SX + 12, SY - 34, SX + 64, SY + 4, skew=2)+for p in (lens1, lens2):+ c.line(p, C['black'], width=7, closed=True)+ c.scribble(c.mask(p), C['black'], angle=20, width=10, density=0.9, pressure=0.95, reach=None, mess=0.1)+ c.burnish(c.mask(p), 0.75)+c.line([(SX - 12, SY - 22), (SX + 12, SY - 22)], C['black'], width=7)+c.line(arc(SX, SY + 18, 42, 30, 205, 335, 20), C['red'], width=10)+for dx in (-62, 62):+ c.dab(SX + dx, SY + 26, 11, C['pink'], pressure=0.6)+c.write('我的周末!', 840, 116, 132, [C['red'], C['orange'], C['green'], C['blue'], C['violet']], width=11.5, tilt=8, jumble=0.1)+w0 = c.wax.copy()+c.write('朵朵 6岁', 196, 1032, 64, [C['violet']], width=8, tilt=5, jumble=0.08, spacing=0.95)+NAME = c.grow((c.wax - w0) > 0.05, 18) # the grass will leave a clear patch round my name+c.stage('sun_title')++# ===================================================================== 3. rainbow, kite, sky+RCX, RCY = 1722, 690+for i, col in enumerate(['red', 'orange', 'yellow', 'green', 'blue', 'violet']):+ R = 318 - i * 25+ pts = arc(RCX, RCY, R, R, 8, 172, 160)+ hy = np.interp(pts[:, 0], hillR[:, 0], hillR[:, 1])+ pts = pts[pts[:, 1] < hy - 6]+ if len(pts) > 3:+ c.follow(pts, C[col], width=27, passes=2, crayon=14, pressure=0.9)+quads = [(KT, KR, KC), (KR, KB, KC), (KB, KL, KC), (KL, KT, KC)]+for q, col, ang in zip(quads, ['yellow', 'green', 'blue', 'red'], [30, -40, 60, -20]):+ c.scribble(c.mask(c.poly(q, amp=0.5)), C[col], angle=ang, width=14, density=0.8, pressure=0.9, reach=None, mess=0.35)+c.line([KT, KB], C['black'], width=7)+c.line([KL, KR], C['black'], width=7)+tailp = spline([KB, KB + (38, 44), KB + (90, 34), KB + (140, 72), KB + (192, 62)], 10)+c.line(tailp, C['black'], width=7, pressure=0.95)+for k, col in zip([12, 26, 40], ['magenta', 'orange', 'violet']):+ x, y = tailp[k]+ for s in (-1, 1):+ bow = c.poly([(x, y), (x + s * 22, y - 13), (x + s * 22, y + 13)], amp=0.6)+ c.line(bow, C[col], width=6, closed=True)+ c.scribble(c.mask(bow), C[col], angle=90, width=9, density=0.9, pressure=0.9, reach=None, mess=0.3)+sky = c.mask(c.rect(-40, -40, 1960, 470, 0))+c.scribble(sky, C['sky'], angle=6, width=22, density=0.55, pressure=0.78, reach=300, mess=0.5,+ avoid=U(OBJ, c.drawn()), halo=13, fade=(170, 450))+c.stage('sky')++# ===================================================================== 4. hills and meadow+def below(curve, pad=0):+ return (c.YY > np.interp(c.XX, curve[:, 0], curve[:, 1]) + pad).astype(np.float32)+++mR = below(hillR) * (1 - below(meadow))+mL = below(hillL) * (1 - below(meadow)) * (1 - mR)+mM = below(meadow)+keep_off = U(c.grow(OBJ, 8), LINES0)+c.scribble(mL, C['green'], angle=28, width=22, density=0.62, pressure=0.82, reach=280, mess=0.5, avoid=keep_off, halo=6)+c.scribble(mR, C['yellowgreen'], angle=-24, width=22, density=0.62, pressure=0.85, reach=280, mess=0.5, avoid=keep_off, halo=6)+c.scribble(mM, C['green'], angle=78, width=22, density=0.6, pressure=0.85, reach=240, mess=0.5,+ avoid=U(c.grow(OBJ, 8), c.drawn(), NAME), halo=6, angle_jitter=12)+c.stage('land')++# ===================================================================== 5. house and tree+c.scribble(c.mask(house), C['yellow'], angle=35, width=18, density=0.72, pressure=0.9, reach=None, mess=0.6,+ avoid=U(c.mask(door), c.mask(win1), c.mask(win2)), halo=4)+c.scribble(c.mask(roof), C['red'], angle=-18, width=18, density=0.8, pressure=0.92, reach=None, mess=0.6)+c.scribble(c.mask(chim), C['brown'], angle=80, width=14, density=0.8, pressure=0.9, reach=None, mess=0.4)+c.scribble(c.mask(door), C['brown'], angle=95, width=14, density=0.85, pressure=0.9, reach=None, mess=0.3)+c.dab(306, 646, 6, C['yellow'])+for w in (win1, win2):+ c.scribble(c.mask(w), C['sky'], angle=-30, width=14, density=0.75, pressure=0.85, reach=None, mess=0.3)+for (x0, y0, x1, y1) in [(205, 520, 205, 576), (172, 548, 238, 548), (378, 518, 378, 576), (345, 547, 411, 547)]:+ c.line([(x0, y0), (x1, y1)], C['black'], width=7)+tt = np.linspace(0, 1, 260)+rr = 9 + 24 * tt # a curly line of smoke, its loops growing as it rises+smoke = np.stack([382 + 80 * tt + rr * np.sin(tt * 4.5 * 2 * np.pi), 376 - 150 * tt - rr * (1 - np.cos(tt * 4.5 * 2 * np.pi)) * 0.8], 1)+c.line(smoke, C['grey'], width=7, pressure=0.7)+c.scribble(c.mask(trunk), C['brown'], angle=88, width=14, density=0.8, pressure=0.9, reach=None, mess=0.4)+c.loops(c.mask(crown), C['green'], r=22, width=11, density=0.55, pressure=0.85)+for (x, y) in [(540, 392), (612, 372), (640, 440), (560, 460), (604, 486), (520, 430), (660, 400)]:+ c.dab(x, y, 12, C['red'], pressure=1.0)+c.stage('house_tree')++# ===================================================================== 6. the family+for hx, hy, r in [(DAD, 468, 48), (MUM, 486, 45), (ME, 560, 42)]:+ c.scribble(c.mask(c.circle(hx, hy, r - 3)), C['peach'], angle=20, width=14, density=0.7, pressure=0.6, reach=None, mess=0.2)+# Dad: spiky hair, blue shirt, red tie, brown trousers, black shoes+dad_hair = c.poly(list(arc(DAD, 468, 50, 50, 12, 168, 18)) + [(DAD - 34, 446), (DAD, 452), (DAD + 34, 446)], amp=1.5)+c.scribble(c.mask(dad_hair), C['brown'], angle=80, width=12, density=0.85, pressure=0.95, reach=None, mess=0.5)+for k in range(7):+ a = np.radians(25 + k * 22)+ c.line([(DAD + 48 * np.cos(a), 468 - 48 * np.sin(a)), (DAD + 64 * np.cos(a + 0.08), 468 - 64 * np.sin(a + 0.08))],+ C['brown'], width=9)+c.scribble(c.mask(dad_shirt), C['blue'], angle=-35, width=18, density=0.72, pressure=0.9, reach=None, mess=0.6)+tie = c.poly([(DAD - 8, 526), (DAD + 8, 526), (DAD + 12, 590), (DAD, 606), (DAD - 12, 590)], amp=0.8)+c.line(tie, C['red'], width=6, closed=True)+c.scribble(c.mask(tie), C['red'], angle=90, width=10, density=0.9, pressure=1.0, reach=None, mess=0.2)+for lg in dad_legs:+ c.scribble(c.mask(lg), C['brown'], angle=95, width=14, density=0.78, pressure=0.85, reach=None, mess=0.5)+for x in (712, 778):+ sh = c.circle(x, 798, 26, 12, lumpy=0.03)+ c.line(sh, C['black'], width=7, closed=True)+ c.scribble(c.mask(sh), C['black'], angle=0, width=10, density=0.9, pressure=0.95, reach=None, mess=0.2)+# Mum: long hair, pink polka-dot dress, red shoes+c.scribble(c.mask(mum_hair) * (1 - c.mask(c.circle(MUM, 486, 47))), C['orange'], angle=75, width=13, density=0.8,+ pressure=0.9, reach=None, mess=0.3)+c.scribble(c.mask(mum_dress), C['pink'], angle=55, width=18, density=0.75, pressure=0.9, reach=None, mess=0.6)+for (x, y) in [(MUM - 20, 600), (MUM + 18, 588), (MUM + 2, 640), (MUM - 38, 676), (MUM + 34, 672), (MUM - 4, 700)]:+ c.dab(x, y, 8, C['magenta'])+for x in (MUM - 30, MUM + 30):+ sh = c.circle(x, 800, 22, 11)+ c.line(sh, C['red'], width=6, closed=True)+ c.scribble(c.mask(sh), C['red'], angle=0, width=10, density=0.9, pressure=0.95, reach=None, mess=0.2)+# me: pigtails with red bows, yellow T-shirt with a star, violet skirt, blue shoes+for s in (-1, 1):+ pg = c.circle(ME + s * 52, 540, 18, 22)+ c.line(pg, C['brown'], width=7, closed=True)+ c.scribble(c.mask(pg), C['brown'], angle=70, width=10, density=0.85, pressure=0.9, reach=None, mess=0.3)+ bx, by = ME + s * 40, 516+ for t in (-1, 1):+ bow = c.poly([(bx, by), (bx + t * 18, by - 11), (bx + t * 18, by + 11)], amp=0.5)+ c.scribble(c.mask(bow), C['red'], angle=90, width=9, density=0.95, pressure=1.0, reach=None, mess=0.2)+fringe = c.poly(list(arc(ME, 560, 44, 44, 20, 160, 16)) + [(ME - 20, 534), (ME + 6, 540), (ME + 30, 532)], amp=1.2)+c.scribble(c.mask(fringe), C['brown'], angle=-60, width=11, density=0.85, pressure=0.95, reach=None, mess=0.4)+c.scribble(c.mask(me_shirt), C['yellow'], angle=40, width=16, density=0.8, pressure=0.95, reach=None, mess=0.5)+star = [(ME + 22 * np.sin(a) * (1 if k % 2 == 0 else 0.45), 638 - 22 * np.cos(a) * (1 if k % 2 == 0 else 0.45))+ for k, a in enumerate(np.linspace(0, 2 * np.pi, 10, endpoint=False))]+c.line(c.poly(star, amp=0.5), C['orange'], width=6, closed=True)+c.scribble(c.mask(me_skirt), C['violet'], angle=-20, width=14, density=0.8, pressure=0.9, reach=None, mess=0.5)+for x in (1040, 1084):+ sh = c.circle(x, 800, 20, 11)+ c.line(sh, C['blue'], width=6, closed=True)+ c.scribble(c.mask(sh), C['blue'], angle=0, width=10, density=0.9, pressure=0.95, reach=None, mess=0.2)+# faces+for hx, hy, r, lashes in [(DAD, 468, 48, False), (MUM, 486, 45, True), (ME, 560, 42, False)]:+ for s in (-1, 1):+ c.dab(hx + s * r * 0.36, hy - r * 0.08, 6.5, C['black'])+ if lashes:+ for a in (60, 90, 120):+ ex, ey = hx + s * r * 0.36, hy - r * 0.08+ c.line([(ex + 9 * np.cos(np.radians(a)), ey - 9 * np.sin(np.radians(a))),+ (ex + 17 * np.cos(np.radians(a)), ey - 17 * np.sin(np.radians(a)))], C['black'], width=4)+ c.dab(hx + s * r * 0.58, hy + r * 0.3, 9, C['pink'], pressure=0.55)+ c.line(arc(hx, hy + r * 0.12, r * 0.42, r * 0.36, 200, 340, 16), C['red'], width=7)+c.stage('family')++# ===================================================================== 7. picnic and dog+P = lambda u, v: (1 - v) * ((1 - u) * TL + u * TR) + v * ((1 - u) * BL + u * BR)+food = U(*[c.mask(p) for p in (basket, plate, glass, mel1, mel2)])+stripes = []+for i in range(7):+ u0 = (2 * i + 0.5) / 14; u1 = u0 + 1 / 14+ stripes.append((c.poly([P(u0, 0), P(u1, 0), P(u1, 1), P(u0, 1)], amp=1.0), 90 - (u0 - 0.5) * 22))+for j in range(4):+ v0 = (2 * j + 0.5) / 8; v1 = v0 + 1 / 8+ stripes.append((c.poly([P(0, v0), P(1, v0), P(1, v1), P(0, v1)], amp=1.0), 3))+for q, ang in stripes:+ c.scribble(c.mask(q) * c.mask(blanket), C['red'], angle=ang, width=16, density=0.72, pressure=0.7, reach=260,+ mess=0.3, avoid=food, halo=7)+c.scribble(c.mask(basket), C['tan'], angle=20, width=16, density=0.75, pressure=0.85, reach=None, mess=0.4)+for k in range(5):+ x = 612 + k * 30+ c.line([(x, 856), (x + 10, 940)], C['brown'], width=6)+for y in (878, 908, 934):+ c.line([(604, y), (742, y)], C['brown'], width=6)+for p in (sand1, sand2):+ c.scribble(c.mask(p), C['tan'], angle=0, width=12, density=0.75, pressure=0.85, reach=None, mess=0.3)+c.line([(834, 912), (884, 878), (898, 916)], C['yellowgreen'], width=7)+c.line([(910, 914), (936, 876), (956, 910)], C['yellow'], width=7)+c.scribble(c.mask(glass) * (c.YY > 880), C['orange'], angle=0, width=14, density=0.85, pressure=0.95, reach=None, mess=0.2)+c.line([(1028, 900), (1040, 832), (1060, 820)], C['magenta'], width=7)+for m, (cx, cy, r) in [(mel1, (1124, 912, 56)), (mel2, (1206, 940, 46))]:+ c.scribble(c.mask(m), C['red'], angle=0, width=14, density=0.85, pressure=0.95, reach=None, mess=0.3)+mm1 = arc(1124, 912, 49, 45, 186, 354, 30)+c.line(mm1, C['green'], width=9)+c.line(arc(1206, 940, 40, 36, 174, 346, 26), C['green'], width=8)+for (x, y) in [(1100, 930), (1124, 938), (1146, 928), (1112, 950), (1138, 952), (1190, 954), (1212, 962), (1226, 948)]:+ c.dab(x, y, 4.5, C['black'])+# the dog+c.scribble(U(c.mask(dog_body), c.mask(dog_head), c.mask(dog_snout)), C['tan'], angle=-30, width=16, density=0.75,+ pressure=0.88, reach=None, mess=0.5)+c.scribble(c.mask(dog_ear), C['brown'], angle=70, width=12, density=0.9, pressure=0.95, reach=None, mess=0.3)+c.line(dog_ear, C['brown'], width=7, closed=True)+for (x, y, r) in [(1420, 848, 15), (1470, 872, 11), (1392, 866, 9)]:+ c.loops(c.mask(c.circle(x, y, r, r * 0.8)), C['brown'], r=6, width=8, density=0.9, pressure=0.95)+for lg in legs: # legs pressed in hard over the body colour+ c.line(spline(lg, 8), C['brown'], width=17, pressure=1.0)+for lg in legs:+ c.dab(lg[-1][0] + 4, lg[-1][1] + 2, 8, C['brown'])+c.dab(1556, 794, 7, C['black'])+c.dab(1610, 814, 9, C['black'])+tongue = c.poly([(1584, 832), (1600, 832), (1602, 856), (1590, 862), (1582, 852)], amp=0.6)+c.scribble(c.mask(tongue), C['pink'], angle=90, width=9, density=0.95, pressure=0.95, reach=None, mess=0.3)+c.line(spline([(1518, 822), (1522, 840), (1530, 850)], 8), C['red'], width=11)+c.dab(1532, 858, 7, C['yellow'])+c.loops(c.mask(ball), C['red'], r=10, width=10, density=0.8, pressure=0.95)+c.burnish(c.mask(ball), 0.7)+c.line(arc(1668, 752, 27, 27, 120, 250, 14) + (14, 0), C['yellow'], width=7)+c.stage('picnic')++# ===================================================================== 8. flowers, butterfly, kite string+for head, leaves, col in tulips:+ for s, lf in zip((-1, 1), leaves):+ c.scribble(c.mask(lf), C['darkgreen'], angle=60 * s, width=9, density=0.95, pressure=0.95, reach=None, mess=0.2)+ c.scribble(c.mask(head), C[col], angle=80, width=12, density=0.85, pressure=0.95, reach=None, mess=0.4)+for (x, y) in daisies:+ c.dab(x, y, 10, C['yellow'])+for w, col in wings:+ c.scribble(c.mask(w), C[col], angle=50, width=12, density=0.7, pressure=0.85, reach=None, mess=0.3)+for s in (-1, 1):+ c.dab(BX + s * 42, BY - 20, 7, C['yellow'])+c.line([(BX, BY - 28), (BX + 1, BY + 32)], C['black'], width=11, pressure=1.0)+for s in (-1, 1):+ c.line(spline([(BX, BY - 26), (BX + s * 10, BY - 48), (BX + s * 22, BY - 60)], 6), C['black'], width=5)+ c.dab(BX + s * 23, BY - 62, 5, C['black'])+# kite string, last of all, from the kite to my hand+c.line(spline([KB, (1250, 380), (1180, 470), (1124, 552)], 14), C['black'], width=4, pressure=0.8)+c.stage('flowers')++# ===================================================================== 9. the crayons are still lying on the paper+c.crumbs(1470, 940, 1640, 1040, [C['red'], C['green']], n=22, size=(2, 5))+c.crumbs(1660, 820, 1760, 900, [C['blue']], n=10, size=(2, 4))+c.stick(1712, 1002, 164, C['red'], length=380, radius=23, tip='worn')+c.stick(1790, 890, -28, C['blue'], length=170, radius=23, tip='broken', peel=0.55)++img = c.save(out, stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/crt_weather.jpg b/examples/crt_weather.jpgnew file mode 100644index 0000000..3251debBinary files /dev/null and b/examples/crt_weather.jpg differdiff --git a/examples/crt_weather.py b/examples/crt_weather.pynew file mode 100644index 0000000..5c68ef1--- /dev/null+++ b/examples/crt_weather.py@@ -0,0 +1,197 @@+"""Example (green-screen CRT terminal / 绿屏终端): 今天带伞吗 · Bring an Umbrella? -- a forecast typed into a 1980s+video terminal. Someone at a little harbour weather station asks the terminal for today's forecast and the answer+comes back as ASCII art in glowing P1 phosphor: the day drawn from left to right as one strip over an hour axis --+a low morning sun with its rays, fair-weather cumulus, a storm cloud raining on the town from 14:00 to 17:30, the+sky clearing, a crescent moon, lit windows and a lighthouse beam at night -- then a temperature curve plotted with+the terminal's scan-line bars, rain bars in block eighths, a summary, and the answer: YES, after 14:00.+The tube: scan lines, blooming bold characters, halation, a barrel-curved raster, afterglow trails behind the falling+rain, a double-height headline, a reverse-video status line with an older one burnt into the phosphor; a putty+plastic bezel whose chamfer catches the green glow, a power LED and two thumbwheels.+Draw-on stages: screen off -> power on -> command typed -> header -> the picture streams in row by row -> curve ->+rain bars and axis -> summary and answer. No image model.+python3 crt_weather.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from crt import CRTTerminal++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'crt_weather.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++COLS, ROWS = 120, 36+t = CRTTerminal(1920, 1080, seed=11, cols=COLS, rows=ROWS)+ASP = t.cw / t.ch # a column is this many rows wide+++def X(h):+ """hour of the day -> column (06:00 at column 6, 24:00 at column 114)"""+ return 6 + (h - 6) * 6.0+++# ================================================================ the picture (hidden art map, rows 5-20)+TOP, GROUND = 5, 19.4++# ---- morning: a low sun -- bright core, faint corona, long and short rays above the horizon+t.material('corona', [' ', ' ', ' ', '.', ':'], attrs=['dim'] * 5, outline=None, dither=0.06)+t.material('sun', [' ', '.', ':', '+', '*', '%', '#', '@'],+ attrs=['dim', 'dim', 'normal', 'normal', 'bold', 'bold', 'bold', 'bold'], outline='cloud', edge=1.0, dither=0.10)+t.material('ray', ['.'], edge=0.70)+sx, sy, sr = X(8.6), 12.4, 5.4+t.fill(t.circle(sx, sy, sr * 1.6), 'corona', t.radial_tone(sx, sy, sr * 1.6, 1.0, 0.0, 1.6))+for k in range(9): # the rays: only those above the hills+ a = np.radians(180 + k * 22.5)+ r0, r1 = sr * 1.3, sr * (2.05 if k % 2 == 0 else 1.65) * (0.72 if k == 8 else 1.0)+ t.stroke([(sx + r0 * np.cos(a), sy + r0 * np.sin(a) * ASP), (sx + r1 * np.cos(a), sy + r1 * np.sin(a) * ASP)],+ 'ray', width=1.4)+t.fill(t.circle(sx, sy, sr), 'sun', t.radial_tone(sx, sy, sr, 1.0, 0.28, 1.0))++# ---- late morning: fair-weather cumulus, lit from the sun on the left+t.material('cumulus', [' ', '.', ':', '.', ':', ':', '*'], attrs=['dim', 'dim', 'dim', 'normal', 'normal', 'bold', 'bold'],+ outline='cloud', dither=0.10) # brighter by intensity, not by busier characters+t.puffs([(X(11.05), 11.3, 2.6), (X(11.45), 9.9, 3.4), (X(12.05), 9.3, 3.6), (X(12.55), 10.7, 2.5),+ (X(11.75), 11.6, 3.6)], 'cumulus', light=(-0.85, -0.5, 0.3), amb=0.0, base=13, base_dark=0.5)++# ---- afternoon: the storm -- a towering cloud with an anvil, a dark flat base, rain on the town 14:00-17:30+t.material('storm', [' ', ' ', '.', '.', ':', '.', ':', ':'], attrs=['dim'] * 5 + ['normal', 'normal', 'bold'],+ outline='cloud', dither=0.12)+storm = [(X(13.9), 12.2, 3.2), (X(14.6), 11.0, 3.9), (X(15.3), 9.4, 4.4), (X(15.9), 8.2, 3.8), (X(16.5), 9.2, 4.3),+ (X(17.2), 10.6, 4.0), (X(17.8), 11.8, 3.3), (X(14.7), 12.8, 4.4), (X(15.9), 12.4, 5.0), (X(17.0), 12.8, 4.4),+ (X(18.1), 13.1, 2.6), (X(13.6), 13.6, 2.4), (X(16.0), 13.8, 6.5)]+t.puffs(storm, 'storm', light=(-0.8, -0.55, 0.25), amb=0.0, base=15, base_dark=0.7)+anvil = t.poly([(X(14.9), 7.4), (X(15.5), 5.95), (X(18.6), 5.95), (X(19.3), 6.25), (X(18.2), 6.75), (X(16.9), 7.3),+ (X(16.0), 8.0)])+t.fill(anvil, 'storm', t.ramp_tone((X(15), 6), (X(19), 7), 0.75, 0.35))++# ---- evening: the last ragged cloud breaks up; night: a crescent moon+t.material('wisp', [' ', '.', '-', '~'], attrs=['dim'] * 4, outline=None, dither=0.15)+for (c, r, w, s) in [(X(18.9), 9.8, 3.6, 0.9), (X(19.6), 11.1, 2.8, 0.6), (X(18.6), 12.4, 2.2, 0.45)]:+ t.fill(t.ellipse(c, r, w, 0.42), 'wisp', s)++t.material('moon', [' ', '.', ':', '*', '%', '#', '@'], attrs=['dim', 'dim', 'normal', 'bold', 'bold', 'bold', 'bold'],+ outline=None, dither=0.05)+mx, my, mr = X(21.6), 9.8, 5.8+t.fill(t.circle(mx, my, mr) * (1 - t.circle(mx + 2.6, my - 0.35, mr * 0.97)), 'moon',+ t.radial_tone(mx - 2.0, my, mr * 1.4, 1.0, 0.6, 0.6))++# ---- the land: flat ground for the town, the sea on the right+t.material('hill', [' ', ' ', ' ', '.', ','], attrs=['dim'] * 5, outline='straight', dither=0.25)+t.fill(t.rect(-1, GROUND, 101, 21.0), 'hill', 0.22)+t.material('sea', [' ', ' ', '-', '~'], attrs=['dim'] * 4, outline=None, dither=0.3)+t.fill(t.rect(101, GROUND + 0.5, 121, 21.0), 'sea', t.ramp_tone((101, 0), (121, 0), 0.65, 0.95))++t.compose(region=(TOP, 21, 0, COLS))++# ---- hand-drawn pieces on top of the composed art+rng = np.random.default_rng(4)+for c, r, ch, a in [(2, 6, '.', 'dim'), (5, 8, '·', 'dim'), (9, 5, '.', 'dim'), (13, 7, '·', 'dim'),+ (84, 6, '.', 'dim'), (88, 12, '·', 'dim'), (91, 7, '*', 'normal'), (94, 10, '.', 'dim'),+ (90, 5, '+', 'normal'), (99, 16, '·', 'dim'), (110, 5, '*', 'bold'), (108, 12, '.', 'dim'),+ (111, 9, '+', 'normal'), (114, 5, '.', 'dim'), (116, 11, '*', 'normal'), (118, 7, '·', 'dim'),+ (103, 15, '.', 'dim'), (86, 15, '·', 'dim')]:+ t.put(c, r, ch, a)++# houses along the ground: dark windows by day, lit ones after dusk; the lighthouse on its rock, beam sweeping+H1 = [' /\\ ', ' / \\ ', '/____\\', '|o o|']+H2 = [' ____ ', '/____\\', '|o o|']+H3 = [' _||_ ', ' / \\', ' /______\\', ' |o [] o|']+H4 = [' ___ ', '/___\\', '|o o|']+TREE = [' .:. ', '(:::)', ' | ']+for c0, spr in [(30, TREE), (35, H1), (43, H4), (52, H3), (62, H2), (69, TREE), (74, H1), (84, H4), (90, H3),+ (99, TREE)]:+ night = c0 >= 82+ t.sprite(c0, 20 - len(spr), spr, 'dim', attrs={'o': 'bold' if night else 'dim', '[': 'normal', ']': 'normal'},+ swap={'o': '#' if night else '.'})+LH = [' _ ', ' [@] ', ' |=| ', ' | | ', ' |=| ', '/___\\']+t.sprite(110, 20 - len(LH), LH, 'normal', attrs={'@': 'bold'})+lr = 20 - len(LH) + 1+for k, (c, ch) in enumerate([(109, '-'), (108, '='), (107, '-'), (106, '='), (105, '-'), (104, '-'), (102, '-'), (100, '.')]):+ t.put(c, lr, ch, 'bold' if k < 3 else 'normal' if k < 6 else 'dim')+for c, ch in [(107, '.'), (105, "'"), (102, '.')]:+ t.put(c, lr - 1, ch, 'dim')+for c, ch in [(107, "'"), (105, '.'), (102, "'")]:+ t.put(c, lr + 1, ch, 'dim')++# rain: streaks from the cloud base down to the roofs; each drop leaves the afterglow of where it was a frame ago+RAIN = []+for c in range(int(X(14.0)), int(X(17.7))):+ dens = float(np.interp(c, [X(14.0), X(14.8), X(15.6), X(16.6), X(17.3), X(17.7)], [0.15, 0.55, 0.75, 0.7, 0.4, 0.1]))+ for r in range(15, 18):+ if not t.art_text[r, c] and rng.random() < dens * 0.5: # not over the roofs+ RAIN.append((c, r))+# a lightning bolt out of the base at about 16:10 (no rain, and no afterglow, right next to it)+BOLT = [(66, 15, '/'), (65, 16, '/'), (66, 16, '_'), (66, 17, '/'), (65, 18, '/')]+near = {(c + dc, r + dr) for c, r, _ in BOLT for dc in (-1, 0, 1) for dr in (-1, 0, 1)}+RAIN = [(c, r) for c, r in RAIN if (c, r) not in near]+for c, r in RAIN:+ t.put(c, r, '/', 'normal')+for c, r, ch in BOLT:+ t.put(c, r, ch, 'bold')++# ================================================================ the session+t.stage('off')+t.power()+t.stage('power')++t.write(0, 0, 'wx@lookout:~$ ', 'bold')+t.write(14, 0, 'forecast --town "port wren" --today --art', 'normal')+t.cursor(56, 0)+t.stage('command')++t.big(0, 1, 'PORT WREN THU 14 OCT', 'bold')+t.write(0, 3, 'harbour station 07 sunrise 07:21 sunset 18:24 wind SW 24 km/h model run 06Z', 'dim')+t.box(1, 4, 118, 31, attr='dim', title='TODAY 06-24h')+t.cursor(0, 32)+t.stage('header')++t.reveal(TOP, 12)+t.stage('picture_top')+t.reveal(12, 20)+for c, r in RAIN: # the drops one and two frames back, still glowing+ t.trail(c + 1, r - 1, '/', 0.32)+ t.trail(c + 2, r - 2, '/', 0.10)+t.stage('picture')++# temperature: a curve of scan-line bars (5 heights per row)+HOURS = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]+TEMP = [9.0, 9.1, 9.8, 11.2, 12.8, 14.6, 16.1, 17.0, 16.3, 13.4, 12.2, 12.3, 12.8, 12.4, 11.7, 11.1, 10.6, 10.2, 10.0]+xs = np.linspace(6, 24, 400)+ys = np.interp(xs, HOURS, TEMP)+ys = np.convolve(np.pad(ys, 6, mode='edge'), np.ones(13) / 13, mode='valid') # a smooth curve+at = t.plot(X(6), 22, 108, 5, xs, ys, (6, 24), (8, 18), attr='bold')+for v in (16, 12, 8):+ c, r = at(6, v)+ t.write(2, int(round(r)), '%2d°' % v, 'dim')+c, r = at(13, 17.0)+t.write(int(c) + 2, int(round(r)), '17°', 'bold')+t.stage('curve')++# rain: block-eighth bars, mm per hour+rate_h = [13.9, 14.2, 14.8, 15.5, 16.2, 16.8, 17.3, 17.65]+rate_v = [0.0, 0.6, 1.6, 2.6, 2.4, 1.5, 0.6, 0.0]+vals = [float(np.interp(6 + (c + 0.5 - X(6)) / 6.0, rate_h, rate_v)) for c in range(int(X(6)), int(X(24)))]+t.bars(int(X(6)), 27, 2, vals, 3.0, 'dim')+t.write(2, 28, 'mm', 'dim')+t.write(int(X(17.8)), 28, '6.4 mm', 'normal')+# the hour axis+t.hline(int(X(6)), int(X(24)), 29, 'dim')+for h in range(6, 25, 3):+ c = int(round(X(h)))+ t.write(c, 29, '┴', 'dim')+ t.write(c - 1, 30, '%02d' % h, 'normal')+t.stage('bars')++t.write(0, 32, 'max 17° 13:00 min 9° 06:00 rain 6.4 mm 14:00-17:30 thunder 30% gusts 50 km/h 15:00', 'normal')+t.write(0, 33, 'umbrella? ', 'bold')+t.write(10, 33, ' YES ', 'bold+rev')+t.write(16, 33, ' after 14:00 -- dry again by 18:00', 'bold')+t.write(0, 34, 'wx@lookout:~$ ', 'bold')+t.write(14, 34, 'forecast --tomorrow', 'normal')+t.cursor(33, 34)+t.write(0, 35, (' lookout 9600 8N1 ONLINE LOCAL 06:12').ljust(COLS - 9) + 'F1 help ', 'dim+rev')+t.burn(58, 35, 'SESSION 01 LINE 2 READY', 0.22) # an old status line, years in the phosphor+t.tear(9.7, 5.0, 2) # a two-line horizontal-sync slip through the clouds++t.save(out, stages_dir=stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/delft_canal.jpg b/examples/delft_canal.jpgnew file mode 100644index 0000000..52699beBinary files /dev/null and b/examples/delft_canal.jpg differdiff --git a/examples/delft_canal.py b/examples/delft_canal.pynew file mode 100644index 0000000..52b62b5--- /dev/null+++ b/examples/delft_canal.py@@ -0,0 +1,309 @@+"""运河小镇 · 一阵风 (De Windvlaag) — a Delft tile wall: an 11 x 7 tile picture set among single tiles.++One gust from the west crosses a canal town and everything answers it: the mill's sails turn, the sail barge+loaded with flour sacks runs before it with its pennant streaming, chimney smoke and the washing on the line+blow to the right, the tulips bow, and a man's hat flies off over the water while his dog leaps for it.+The weathervane on the step gable points into the wind.++ python3 examples/delft_canal.py out.jpg [--stages DIR]+"""+import os+import sys+import time++import numpy as np++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from delft import DelftTile, arc, ellipse_pts, _normals, _resample # noqa: E402+from core import spline # noqa: E402+++def limb(t, pts, r0, r1, width=1.7, dens=1.0, tone=None):+ """a limb or sleeve as two outlines that taper from r0 to r1 (px); returns its polygon"""+ P, _ = _resample(spline(np.asarray(pts, np.float32), 8), 2.0)+ nr = _normals(P)+ rr = np.linspace(r0, r1, len(P))[:, None]+ L, R = P + nr * rr, P - nr * rr+ t.trek(L, width, dens, taper=(0.05, 0.2))+ t.trek(R, width, dens, taper=(0.05, 0.2))+ poly = np.vstack([L, R[::-1]])+ if tone: t.wash(poly, tone, slip=0.4, pool=0.5)+ return poly+++def man(t, fx, fy, h):+ """a man in a long coat running to the right, reaching up after his hat; surprised open mouth,+ hair and coat skirts blown forward by the gust"""+ s = h / 100.0+ def P(u, v): return (fx + u * s, fy - v * s)+ w = 1.8+ hx, hy = P(16, 91)+ head = ellipse_pts(hx, hy, 6.4 * s, 7.2 * s, 0.15, 28)+ face = [P(10.5, 96), P(14, 98.5), P(19, 98.4), P(22, 95), P(22.6, 92.5), P(24.4, 90.6), P(22.6, 89.6), P(22.6, 87.5),+ P(20, 84.3), P(15, 84.2), P(10.6, 87.5), P(9.6, 92)]+ t.trek(face + [face[0]], w)+ hair = [P(9.4, 92), P(10.4, 96.6), P(14, 99), P(19.5, 98.8), P(17, 96.5), P(13.5, 95), P(12.4, 91), P(11.6, 87.8), P(9.8, 88.6)]+ t.trek(hair + [hair[0]], 1.3)+ t.wash(hair, 0.55, slip=0.3, pool=0.3)+ t.trek([P(14, 99), P(21, 102.5), P(28, 101.5)], 1.3, taper=(0.1, 0.8)) # strands blown forward+ t.trek([P(17, 98.8), P(24, 100), P(30, 98)], 1.1, 0.85, taper=(0.1, 0.8), pounce=False)+ t.dot(*P(19.6, 93), r=1.3)+ t.trek([P(17.5, 95.5), P(20.5, 96)], 1.1, smooth=False, pounce=False) # raised brow+ t.closed(ellipse_pts(*P(20.6, 87.6), 1.3 * s, 1.5 * s, 0, 10), 1.2) # 'oh!'+ t.trek(arc(*P(13.2, 90.5), 1.6 * s, 2.2 * s, -1.2, 1.6, 8), 1.1, pounce=False) # ear+ t.wash(face, 0.05, slip=0.3)+ t.occlude(face + [P(28, 101.5)])+ # raised front arm with a turned-back cuff and an open hand+ hand = [P(35.5, 101.5), P(37, 106.5), P(38.6, 110.5), P(40, 107), P(41.3, 111), P(42.4, 106.6), P(44.5, 108.8), P(44.4, 104.6),+ P(46.6, 104), P(43.2, 100.5), P(39.4, 99)]+ t.trek(hand + [hand[0]], 1.3)+ t.wash(hand, 0.05, slip=0.2)+ t.occlude(hand)+ cuff = [P(31, 94), P(37.6, 98.6), P(35, 103), P(28.4, 98.6)]+ t.trek(cuff + [cuff[0]], 1.5, smooth=False)+ t.wash(cuff, 0.5, slip=0.2)+ t.occlude(cuff)+ arm = limb(t, [P(18, 79), P(25, 88), P(32, 98)], 4.2 * s, 3.6 * s, w, tone=0.3)+ t.occlude(arm)+ # coat: leaning forward, skirts blown ahead+ coat = [P(8, 83), P(21, 81), P(24, 66), P(25, 54), P(37, 36), P(30, 32.5), P(20, 34.5), P(10, 31), P(-3, 34.5), P(3, 50), P(4.5, 70)]+ t.trek(coat + [coat[0]], w)+ t.trek([P(14.5, 80), P(16, 66), P(17.5, 52), P(21, 35)], 1.2, 0.85, pounce=False)+ for v in (75, 68, 61, 54):+ t.dot(*P(16 + (80 - v) * 0.06, v), r=1.3)+ t.trek([P(3.5, 55), P(24.5, 56)], 1.5, smooth=False)+ t.trek([P(5, 50), P(-1, 40)], 1.0, 0.7, pounce=False)+ t.trek([P(24, 50), P(31, 40)], 1.0, 0.7, pounce=False)+ cravat = [P(17, 83.5), P(22, 82), P(21, 76), P(18, 74.5), P(16.5, 79)]+ t.trek(cravat + [cravat[0]], 1.2)+ t.wash(coat, 0.34, angle=-1.3, slip=0.8, pool=0.6, holes=[cravat])+ t.hatch([P(-3, 34.5), P(3, 50), P(10, 49), P(10, 31)], angle=-1.2, spacing=3.2, width=0.8, dens=0.7)+ t.occlude(coat)+ # back arm swinging behind+ hb = [P(-8.5, 63.5), P(-12.6, 61.5), P(-14.6, 57.6), P(-12, 55.6), P(-8.4, 57.8)]+ t.trek(hb + [hb[0]], 1.3)+ t.occlude(hb)+ cb = [P(-2.5, 67.5), P(-8.5, 64.5), P(-6, 58), P(0.5, 61.5)]+ t.trek(cb + [cb[0]], 1.4, smooth=False)+ t.wash(cb, 0.5, slip=0.2)+ t.occlude(cb)+ limb(t, [P(7, 78), P(3, 70), P(-1, 63)], 3.8 * s, 3.4 * s, w * 0.95, tone=0.3)+ # legs: breeches to the knee, pale stockings, buckled shoes; the back leg kicked up+ for (pts, shoe) in (([P(18, 34), P(23, 22), P(25, 7)], [P(21.5, 7.5), P(28, 7.5), P(35.5, 3.6), P(33, -0.4), P(21.5, -0.4)]),+ ([P(7, 34), P(0, 23), P(-9, 14)], [P(-7.4, 16.2), P(-12.2, 18.8), P(-20, 13.6), P(-18.6, 9.4), P(-9.6, 11)])):+ t.trek(shoe + [shoe[0]], 1.5)+ t.wash(shoe, 0.6, slip=0.1, pool=0.2)+ t.occlude(shoe)+ knee = pts[1]+ br = limb(t, [pts[0], ((pts[0][0] + knee[0]) / 2, (pts[0][1] + knee[1]) / 2), knee], 4.4 * s, 3.4 * s, w, tone=0.45)+ t.occlude(br)+ limb(t, [knee, ((knee[0] + pts[2][0]) / 2, (knee[1] + pts[2][1]) / 2), pts[2]], 2.9 * s, 2.2 * s, w * 0.9)+++def hat(t, x, y, r):+ """a broad-brimmed hat tumbling through the air"""+ rot = -0.45+ brim = ellipse_pts(x, y, r, r * 0.34, rot, 30)+ t.closed(brim, 1.8)+ c, s = np.cos(rot), np.sin(rot)+ def R(u, v): return (x + u * c - v * s, y + u * s + v * c)+ crown = [R(-r * 0.52, -r * 0.08), R(-r * 0.55, -r * 0.55), R(-r * 0.3, -r * 0.85), R(r * 0.3, -r * 0.85), R(r * 0.55, -r * 0.55), R(r * 0.52, -r * 0.08)]+ t.trek(crown, 1.8)+ t.trek([R(-r * 0.53, -r * 0.25), R(0, -r * 0.33), R(r * 0.53, -r * 0.25)], 2.6, 0.95)+ t.wash(crown + [R(0, r * 0.1)], 0.42, slip=0.4)+ t.wash(brim, 0.22, slip=0.4)+ t.occlude(np.vstack([brim, crown]))+++def dog(t, x, y, s=1.0, facing=1, tilt=0.0):+ """a small dog in a flying leap (all four feet off the ground), ears and tail streaming back;+ facing=-1 leaps to the left; tilt (radians) aims the leap upward"""+ c, sn = np.cos(tilt), np.sin(tilt)+ def P(u, v):+ u, v = u * c - (v - 30) * sn, u * sn + (v - 30) * c + 30+ return (x + facing * u * s, y - v * s)+ w = 1.8+ head = [P(23, 52), P(27, 57.5), P(34, 58.5), P(41, 55.5), P(47.5, 53.5), P(49, 50), P(45, 48.5), P(47, 45.5), P(41, 44.5), P(34, 45), P(27, 46)]+ t.trek(head + [head[0]], w)+ t.dot(*P(37, 53), r=1.6)+ t.dot(*P(48.4, 51.6), r=1.8)+ t.trek([P(45.5, 48.5), P(41, 48)], 1.1, smooth=False, pounce=False)+ ear = [P(28, 56.5), P(20, 57.5), P(12, 55), P(15, 50.5), P(23, 51)]+ t.trek(ear + [ear[0]], w * 0.9)+ t.wash(ear, 0.5, slip=0.3, pool=0.4)+ t.wash(head, 0.08, slip=0.3)+ t.occlude(head + ear)+ for leg in ([P(19, 34), P(31, 30), P(43, 28.5)], [P(16, 31), P(27, 24), P(37, 20)]):+ lp = limb(t, leg, 2.7 * s, 2.0 * s, w * 0.85)+ t.occlude(lp)+ body = [P(-22, 31), P(-14, 38.5), P(-2, 41), P(12, 42.5), P(21, 41), P(26, 36), P(21, 29.5), P(7, 26.5), P(-8, 25.5), P(-19, 26.5)]+ t.trek(body + [body[0]], w)+ patch = [P(-12, 38.5), P(2, 41), P(8, 35), P(-4, 31), P(-14, 33)]+ t.wash(body, 0.1, slip=0.6, holes=[patch])+ t.wash(patch, 0.5, slip=0.3, pool=0.4)+ t.occlude(body)+ for leg in ([P(-15, 29), P(-27, 22), P(-39, 19)], [P(-12, 27), P(-21, 16), P(-31, 10)]):+ limb(t, leg, 3.0 * s, 2.0 * s, w * 0.85)+ t.trek([P(-22, 33), P(-33, 38), P(-42, 44), P(-46, 50)], w * 1.4, taper=(0.05, 0.8))+++def laundry(t, x0, x1, y, sag=10):+ """a washing line between two posts; the gust lifts the washing almost level, streaming to the right"""+ t.trek([(x0, y - 3), (x0 - 1, y + 66)], 2.2, smooth=False)+ t.trek([(x1, y - 3), (x1 + 1, y + 66)], 2.2, smooth=False)+ xs = np.linspace(x0, x1, 14)+ yl = lambda x: y + sag * np.sin(np.pi * (x - x0) / (x1 - x0))+ items = [(0.08, 0.3, 40, 'sheet'), (0.42, 0.6, 30, 'shirt'), (0.7, 0.86, 24, 'cloth')]+ for (u0, u1, hh, kind) in items:+ a = (x0 + (x1 - x0) * u0, yl(x0 + (x1 - x0) * u0))+ b = (x0 + (x1 - x0) * u1, yl(x0 + (x1 - x0) * u1))+ wdt = b[0] - a[0]+ if kind == 'shirt':+ q = [a, b, (b[0] + 10, b[1] + 4), (b[0] + 22, b[1] + 10), (b[0] + 18, b[1] + 15), (b[0] + 14, b[1] + 12),+ (b[0] + 20, b[1] + hh * 0.7), (a[0] + wdt * 0.45 + 18, a[1] + hh * 0.9), (a[0] + 12, a[1] + hh * 0.75),+ (a[0] + 6, a[1] + 14), (a[0] - 4, a[1] + 15), (a[0] - 2, a[1] + 8)]+ else:+ k = np.linspace(0, 1, 6)+ hem = [(a[0] + 10 + (b[0] + hh * 0.55 - a[0] - 10) * u, a[1] + hh * (0.72 + 0.12 * np.sin(u * 7.5)) - u * hh * 0.25) for u in k]+ q = [a, (a[0] + wdt * 0.5, a[1] - 3), b, (b[0] + hh * 0.35, b[1] + hh * 0.18), (b[0] + hh * 0.6, b[1] + hh * 0.28)] + hem[::-1]+ t.trek(q + [q[0]], 1.4)+ t.trek([(a[0] + wdt * 0.3, a[1] + 4), (a[0] + wdt * 0.5 + hh * 0.2, a[1] + hh * 0.45)], 0.9, 0.6, pounce=False)+ t.wash(q, 0.12, slip=0.6, angle=0.3, pool=0.7)+ for pc in (a, b):+ t.trek([(pc[0], pc[1] + 2), (pc[0], pc[1] - 5)], 1.8, smooth=False, pounce=False)+ t.occlude(q)+ t.trek(np.stack([xs, yl(xs)], 1), 1.1, 0.9)+++def main(out, stages=None):+ t0 = time.time()+ t = DelftTile(1920, 1080, tile=128, joint=3.6, origin=(0, -36), seed=11)+ R = t.tableau(2, 1, 13, 8) # 11 x 7 tiles: x 256..1664, y 92..988+ # canal edges+ def far_edge(x): return 592 - (x - 299) * 0.008+ def near_edge(x): return 734 - (x - 299) * 0.02++ # ------------------------------------------------------------ the picture, front to back+ t.layer('picture')+ # cartouche reserve at the bottom (kept white, text later)+ cart = [(800, 924), (1120, 924), (1134, 934), (1140, 951), (1134, 968), (1120, 978), (800, 978), (786, 968), (780, 951), (786, 934)]+ t.occlude(cart, grow=0.5)+ man(t, 826, 906, 166)+ hat(t, 958, 690, 22)+ dog(t, 1092, 880, 1.45, facing=-1, tilt=0.3)+ laundry(t, 1250, 1450, 764, sag=12)+ # tulips: a bed on the left, two rows on the right, all bowing to the right+ rng = np.random.default_rng(5)+ for row, (y, x0, x1, hh, n) in enumerate([(940, 316, 704, 56, 12), (904, 334, 690, 46, 12), (934, 1168, 1604, 54, 12), (898, 1186, 1592, 44, 12)]):+ xs = np.linspace(x0, x1, n) + rng.normal(0, 7, n)+ for j, x in enumerate(xs):+ if rng.random() < 0.1: continue # a gap in the row+ t.tulip(x, y + rng.normal(0, 4), hh * rng.uniform(0.78, 1.15), lean=0.3 + rng.normal(0, 0.08), width=1.5,+ tone=0.2 + 0.08 * (row % 2) + rng.normal(0, 0.03), leaves=2 if rng.random() < 0.8 else 1)+ # ground shadows under the running figures+ for (x0, x1, y) in ((786, 868, 910), (1040, 1100, 908)):+ t.trek([(x0, y), ((x0 + x1) / 2, y + 1.5), (x1, y)], 2.2, 0.6, pounce=False, taper=(0.3, 0.3))+ t.trek([(x0 + 8, y + 4), (x1 - 10, y + 4.5)], 1.2, 0.45, pounce=False, taper=(0.3, 0.3))+ # a low post-and-rail fence behind the left bed, leaning a little+ for x in np.arange(318, 720, 46):+ t.trek([(x, 868), (x + 2, 826)], 2.0, smooth=False)+ t.trek([(310, 838), (515, 836), (722, 839)], 1.7)+ t.trek([(310, 856), (515, 853), (722, 857)], 1.5)+ t.grass(310, 760, 870, n=10, h=11, lean=0.5)+ t.grass(1140, 1610, 860, n=10, h=11, lean=0.5)+ t.grass(320, 1600, 790, n=22, h=9, lean=0.5, yspread=20)+ # near bank: boarding along the canal, a path+ xs = np.linspace(299, 1621, 40)+ t.trek(np.stack([xs, near_edge(xs)], 1), 2.2, taper=(0.02, 0.02))+ t.trek(np.stack([xs, near_edge(xs) + 9], 1), 1.3, 0.8, taper=(0.02, 0.02), pounce=False)+ for x in np.arange(312, 1621, 34) + rng.normal(0, 2, 39):+ y = near_edge(x)+ t.trek([(x, y - 3), (x, y + 13)], 1.6, smooth=False, bead=0.05)+ t.wash([(299, near_edge(299)), (1621, near_edge(1621)), (1621, near_edge(1621) + 9), (299, near_edge(299) + 9)], 0.22, slip=0.5)+ for (x0, x1, y) in ((330, 760, 828), (420, 700, 846), (900, 1240, 838), (1470, 1600, 832), (1180, 1260, 852)):+ t.trek([(x0, y), ((x0 + x1) / 2, y - 2), (x1, y + 1)], 1.0, 0.55, pounce=False, taper=(0.3, 0.4))+ for (x, y) in ((760, 820), (1188, 836), (1520, 846), (704, 858)):+ st = ellipse_pts(x, y, 7, 3.5, 0.1, 14)+ t.trek(st[7:], 1.2, 0.8, pounce=False)+ t.wash(st, 0.15, slip=0.3)+ t.occlude([(299, near_edge(299) - 2), (1621, near_edge(1621) - 2), (1621, 945), (299, 945)])+ # the barge, then the water round it+ hull = t.sailboat(636, 676, 300, facing=1, belly=0.5, cargo=7)+ t.occlude(hull)+ for (x, w) in ((1255, 90), (1350, 80), (1452, 96), (1560, 100)):+ t.reflection(x, far_edge(x) + 2, w * 0.8, 70, step=6, width=1.3, dens=0.6)+ t.reflection(470, far_edge(470) + 2, 70, 55, step=6, width=1.3, dens=0.55)+ t.reflection(790, 680, 250, 34, step=5.5, width=1.5, dens=0.75)+ t.water(299, 1621, far_edge(299) + 6, near_edge(1000) - 4, width=1.5, dens=0.8, far=4.2, near=10, avoid=t.occ)+ t.wash([(299, far_edge(299)), (1621, far_edge(1621)), (1621, near_edge(1621)), (299, near_edge(299))], 0.07, angle=0.0, pool=0.3,+ grad=((960, far_edge(960)), (960, near_edge(960)), 1.4, 0.5))+ t.occlude([(299, far_edge(299) + 1), (1621, far_edge(1621) + 1), (1621, near_edge(1621)), (299, near_edge(299))], grow=0)+ # far bank line+ xs = np.linspace(299, 1621, 40)+ t.trek(np.stack([xs, far_edge(xs)], 1), 1.8, taper=(0.02, 0.02))+ t.trek(np.stack([xs, far_edge(xs) - 5], 1), 1.0, 0.7, taper=(0.05, 0.05), pounce=False)+ # houses on the far bank (front to back = left to right is fine, they don't overlap)+ hb = far_edge(1300) - 4+ t.house(1196, 1296, hb, 172, gable='step', gable_h=88, floors=3, chimney=1262, smoke=(70, -18), vane=-1, shade='right')+ t.house(1296, 1392, hb, 146, gable='bell', gable_h=84, floors=3, shade='right')+ t.house(1392, 1500, hb, 186, gable='neck', gable_h=98, floors=3, chimney=1478, smoke=(64, -14), shade='right')+ t.house(1500, 1625, hb, 158, gable='step', gable_h=92, floors=3, shade='right')+ # trees between the barge and the houses+ t.tree(1150, far_edge(1150) - 4, 150, w=104, lean=0.35, clumps=6, seed=3)+ t.tree(1050, far_edge(1050) - 4, 196, w=126, lean=0.4, clumps=8, seed=4)+ # the mill on its dike+ dike = [(299, far_edge(299) - 1), (318, 566), (360, 556), (560, 556), (640, 572), (700, far_edge(700) - 1)]+ t.windmill(455, 560, 232, sails=0.42, squash=0.6, cloth=(1, 3))+ t.trek(dike, 1.8, taper=(0.02, 0.1))+ t.wash(dike + [(299, far_edge(299))], 0.1, angle=0.0, pool=0.5)+ t.grass(320, 690, 566, n=12, h=9, lean=0.6, yspread=6)+ t.occlude(dike + [(700, far_edge(700) + 2), (299, far_edge(299) + 2)])+ # ground on the far bank and the low polder beyond+ t.grass(700, 1040, far_edge(800) - 4, n=8, h=8, lean=0.6)+ t.trek([(560, 538), (760, 534), (1000, 536), (1200, 532)], 1.0, 0.65, pounce=False)+ for (x, hgt) in ((600, 26), (980, 22)):+ t.windmill(x, 512, hgt, sails=0.6, squash=0.7, width=1.1, tone=0.14, gallery=False, door=False, cloth=())+ t.bushes(640, 1190, 511, h=16, gap=[(965, 995)], seed=12)+ t.bushes(304, 340, 511, h=12, seed=13)+ t.trek([(299, 512), (520, 511), (900, 513), (1200, 511)], 1.3, 0.85)+ # sky: clouds and birds+ t.cloud(1000, 215, 430, 120, lean=0.35, seed=8)+ t.cloud(1450, 196, 270, 80, lean=0.35, seed=9)+ t.cloud(690, 196, 180, 60, lean=0.35, seed=10)+ t.birds([(1290, 285), (1318, 270), (1345, 292), (1372, 262), (1400, 280)], size=9, tilt=0.25)+ t.clear_occlusion()+ # inscription in the cartouche+ t.letters('DE WINDVLAAG', 960, 951, 26, font='serif', dens=1.05, spacing=3)++ # ------------------------------------------------------------ the painted frame and the single tiles+ t.layer('frame')+ t.border(R, band=34, inset=9, reserve=[cart])+ t.closed(cart, 2.2)+ for sx in (-1, 1):+ cxs = 960 + sx * 168+ t.trek(arc(cxs, 951, 12, 16, -np.pi / 2, np.pi / 2, 12) if sx > 0 else arc(cxs, 951, 12, 16, np.pi / 2, 3 * np.pi / 2, 12), 1.6)+ t.dot(cxs + sx * 4, 951, 2.4)+ t.layer('single')+ t.field(corners='spin', width=1.35)++ # ------------------------------------------------------------ stages: replay the workshop+ if stages:+ t.stage('tiles', hide=('*',))+ t.stage('pounce', hide=('trek', 'wash'))+ t.stage('outline', hide=('wash', 'frame', 'single'))+ t.stage('wash', hide=('frame', 'single'))+ t.stage('singles')+ t.fire()+ if stages: t.stage('fired')+ t.set_wall()+ if stages: t.stage('set')+ t.age(craze=1.0, chips=12, cracks=[[(1360, 640), (1395, 676), (1440, 700), (1470, 738)]])+ t.light(window=(1488, 178, 112, 150), strength=0.65, soft=6.0) # window glare over the right cloud+ t.save(out, stages_dir=stages)+ print(f'{out} {time.time() - t0:.1f}s')+++if __name__ == '__main__':+ out = sys.argv[1] if len(sys.argv) > 1 else 'delft_canal.jpg'+ st = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+ main(out, st)diff --git a/examples/drawing_blackfigure_games.gif b/examples/drawing_blackfigure_games.gifnew file mode 100644index 0000000..54229feBinary files /dev/null and b/examples/drawing_blackfigure_games.gif differdiff --git a/examples/drawing_blueprint_lighthouse.gif b/examples/drawing_blueprint_lighthouse.gifnew file mode 100644index 0000000..7857da1Binary files /dev/null and b/examples/drawing_blueprint_lighthouse.gif differdiff --git a/examples/drawing_cave_hunt.gif b/examples/drawing_cave_hunt.gifnew file mode 100644index 0000000..f9c0145Binary files /dev/null and b/examples/drawing_cave_hunt.gif differdiff --git a/examples/drawing_crayon_picnic.gif b/examples/drawing_crayon_picnic.gifnew file mode 100644index 0000000..eafb941Binary files /dev/null and b/examples/drawing_crayon_picnic.gif differdiff --git a/examples/drawing_crt_weather.gif b/examples/drawing_crt_weather.gifnew file mode 100644index 0000000..44c9122Binary files /dev/null and b/examples/drawing_crt_weather.gif differdiff --git a/examples/drawing_delft_canal.gif b/examples/drawing_delft_canal.gifnew file mode 100644index 0000000..6adcf93Binary files /dev/null and b/examples/drawing_delft_canal.gif differdiff --git a/examples/drawing_flatvector_night_camp.gif b/examples/drawing_flatvector_night_camp.gifnew file mode 100644index 0000000..4c66559Binary files /dev/null and b/examples/drawing_flatvector_night_camp.gif differdiff --git a/examples/drawing_graphite_bicycle.gif b/examples/drawing_graphite_bicycle.gifnew file mode 100644index 0000000..f603acaBinary files /dev/null and b/examples/drawing_graphite_bicycle.gif differdiff --git a/examples/drawing_linocut_snowy_village.gif b/examples/drawing_linocut_snowy_village.gifnew file mode 100644index 0000000..978934aBinary files /dev/null and b/examples/drawing_linocut_snowy_village.gif differdiff --git a/examples/drawing_macpaint_garden.gif b/examples/drawing_macpaint_garden.gifnew file mode 100644index 0000000..035bab7Binary files /dev/null and b/examples/drawing_macpaint_garden.gif differdiff --git a/examples/drawing_rubberhose_morning.gif b/examples/drawing_rubberhose_morning.gifnew file mode 100644index 0000000..184c8deBinary files /dev/null and b/examples/drawing_rubberhose_morning.gif differdiff --git a/examples/drawing_storybook_acorn.gif b/examples/drawing_storybook_acorn.gifnew file mode 100644index 0000000..c4e9175Binary files /dev/null and b/examples/drawing_storybook_acorn.gif differdiff --git a/examples/drawing_thermal_kitchen.gif b/examples/drawing_thermal_kitchen.gifnew file mode 100644index 0000000..6ecada2Binary files /dev/null and b/examples/drawing_thermal_kitchen.gif differdiff --git a/examples/drawing_vhs_birthday.gif b/examples/drawing_vhs_birthday.gifnew file mode 100644index 0000000..1840001Binary files /dev/null and b/examples/drawing_vhs_birthday.gif differdiff --git a/examples/drawing_xray_luggage.gif b/examples/drawing_xray_luggage.gifnew file mode 100644index 0000000..ea73dfdBinary files /dev/null and b/examples/drawing_xray_luggage.gif differdiff --git a/examples/flatvector_night_camp.jpg b/examples/flatvector_night_camp.jpgnew file mode 100644index 0000000..282d007Binary files /dev/null and b/examples/flatvector_night_camp.jpg differdiff --git a/examples/flatvector_night_camp.py b/examples/flatvector_night_camp.pynew file mode 100644index 0000000..c26020f--- /dev/null+++ b/examples/flatvector_night_camp.py@@ -0,0 +1,105 @@+"""Example (flat vector): 山间夜营 · Night Camp — the last stretch back to camp after a day on the mountain.++A layered flat landscape at night. The moon, crowned with orange rays, hangs over the left; the big snowy peak on+the right still has the little orange flag planted on its summit this afternoon. A dashed trail runs from that+flag down the switchbacks, across the magenta hills and out onto the sand, where one tiny hiker with a head torch+is walking the last few hundred metres. The camp is already lit: an orange A-frame tent with a glowing door and a+campfire whose flat rings of light spread over the sand. Big shapes, seven colours, lots of empty sky.++How it was made, in order: night sky and halo -> moon, rays, stars -> mountain ranges (lit / shade faces, snow+caps) -> clouds -> hill bands -> sand -> trees -> trail and summit flag -> camp (tent, fire, light, smoke) ->+hiker and a shooting star. No image model.+python3 flatvector_night_camp.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from flatvector import FlatVector, tone, mix, NIGHT, PLUM, BERRY, EMBER, SAND, PINE, CREAM++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'flatvector_night_camp.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++W, H = 1920, 1080+MOON = (400, 255, 112)+SUMMIT = (1390, 300)+HORIZON = 772+HIKER = (812, 856)+TENT = (1310, 952)+FIRE = (1040, 962)++fv = FlatVector(W, H, seed=11)++# ---------------------------------------------------------------- 1 sky+fv.backdrop(NIGHT)+fv.stage('sky')++# ---------------------------------------------------------------- 2 moon and stars+fv.moon(*MOON, rays=18)+fv.stars(120, box=(0, 0, W, 560), avoid=[(MOON[0], MOON[1], 265), (1660, 175, 190)])+for x, y, r in ((1010, 110, 9), (1560, 330, 7), (180, 120, 8), (760, 420, 6), (1840, 470, 6)):+ fv.sparkle(x, y, r)+fv.stage('moon_stars')++# ---------------------------------------------------------------- 3 mountains+far = tone(PLUM, -0.3)+fv.mountain((690, 500), (380, 800), (1010, 800), far, lift=5, shade=-0.16, seed=1)+fv.mountain((1080, 470), (780, 800), (1380, 800), far, lift=5, shade=-0.16, seed=2)+fv.mountain((1800, 455), (1540, 800), (2080, 800), far, lift=5, shade=-0.16, seed=3)+fv.mountain((1730, 400), (1390, 800), (2140, 800), PLUM, snow=0.2, lift=8, seed=4)+peak = fv.mountain(SUMMIT, (860, 800), (1930, 800), PLUM, snow=0.22, lift=9, seed=5,+ ridge=[(1418, 390), (1396, 470), (1440, 560), (1425, 820)])+fv.mountain((175, 470), (-260, 800), (600, 800), PLUM, snow=0.2, lift=8, seed=6)+fv.mountain((470, 545), (250, 800), (760, 800), tone(PLUM, 0.06), snow=0.18, lift=8, seed=7)+fv.stage('mountains')++# ---------------------------------------------------------------- 4 clouds+fv.cloud(1660, 172, 330, seed=1)+fv.cloud(860, 230, 190, seed=2)+fv.stage('clouds')++# ---------------------------------------------------------------- 5 hills+fv.land([(-60, 642), (330, 612), (760, 655), (1150, 628), (1560, 664), (1980, 632)], tone(BERRY, -0.18), lift=9)+fv.land([(-60, 694), (420, 668), (880, 704), (1320, 684), (1720, 706), (1980, 690)], BERRY, lift=10)+for x, b, h in ((1490, 694, 70), (1528, 700, 52), (1610, 708, 62), (95, 676, 64), (132, 684, 48)):+ fv.pine(x, b, h, tone(PINE, -0.12), tiers=2, lift=3)+fv.land([(-60, 738), (520, 726), (1180, 744), (1980, 730)], EMBER, lift=10)+fv.stage('hills')++# ---------------------------------------------------------------- 6 sand+fv.land([(-60, HORIZON), (700, HORIZON - 4), (1400, HORIZON + 3), (1980, HORIZON - 2)], SAND, lift=12, shadow=0.42)+fv.dashes((0, HORIZON + 30, W, H - 60), [tone(SAND, 0.3), tone(SAND, -0.16)], n=16, seed=3, horizon=HORIZON)+for x, y, r in ((620, 980, 11), (1610, 1010, 9), (300, 830, 6), (1830, 850, 7)):+ fv.pebble(x, y, r, tone(SAND, -0.25))+for x, y, h in ((520, 1030, 30), (1480, 990, 24), (760, 860, 16), (1720, 905, 18)):+ fv.tuft(x, y, h, tone(PINE, 0.05))+fv.stage('sand')++# ---------------------------------------------------------------- 7 trees+fv.round_tree(255, 915, 92, tone(PINE, 0.1), seed=1)+fv.pine(85, 985, 360, tiers=3)+fv.pine(395, 940, 210, tiers=3)+fv.pine(1700, 965, 300, tiers=3)+fv.pine(1855, 1020, 520, tiers=3)+fv.land([(-60, 1012), (380, 1040), (960, 1060), (1520, 1044), (1980, 1018)], tone(SAND, -0.1), lift=8, shadow=0.3)+fv.stage('trees')++# ---------------------------------------------------------------- 8 trail and flag+path = fv.trail([(SUMMIT[0] - 2, SUMMIT[1] + 14), (1372, 340), (1338, 372), (1432, 420), (1318, 488), (1410, 548), (1262, 612),+ (1080, 650), (860, 680), (680, 708), (668, 760), (730, 818), HIKER])+fv.fill(path & peak['snow'], mix(PLUM, CREAM, 0.25), texture=0) # on the snow the dashes go violet+fv.flag(SUMMIT[0] + 2, SUMMIT[1] + 4, 46)+fv.stage('trail')++# ---------------------------------------------------------------- 9 camp+fv.glow(FIRE[0], FIRE[1] + 6, 400, 118, tone(SAND, 0.5), rings=4, alpha=0.2)+fv.glow(TENT[0] + 4, TENT[1] + 6, 150, 30, tone(SAND, 0.6), rings=3, alpha=0.3)+fv.tent(*TENT, 262, 172)+fv.campfire(*FIRE, s=0.9)+fv.stage('camp')++# ---------------------------------------------------------------- 10 hiker, meteor+fv.hiker(*HIKER, 72, facing=1)+fv.shooting_star((1150, 150), (1360, 62), r=3)++fv.save(out, stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/graphite_bicycle.jpg b/examples/graphite_bicycle.jpgnew file mode 100644index 0000000..c1df250Binary files /dev/null and b/examples/graphite_bicycle.jpg differdiff --git a/examples/graphite_bicycle.py b/examples/graphite_bicycle.pynew file mode 100644index 0000000..99b77ee--- /dev/null+++ b/examples/graphite_bicycle.py@@ -0,0 +1,571 @@+"""Example (graphite pencil drawing): The Bread Run / 老街角的自行车 — a step-through town bicycle leaning against+a plastered wall at an old street corner, a baguette and a paper cone of tulips in its front basket; a bakery's+hanging sign (a loaf, no words) over the side street, a street plate, a bare patch of brick, a deep doorway,+cobbles. Drawn the way a pencil drawing is made: light construction lines (horizon, lines to the vanishing point,+wheel ellipses with their axes), contours, side-of-the-lead tone, hatching built up in layers, the darks pressed+in, a stump to blend, erasers to pull out the light (rims, tube highlights, the lit corner), details last. Only+the middle is finished: toward the edges of the sheet the tone thins out and the drawing is left as bare lines.+Margin notes, the pencil swatches the artist tried, a thumbprint. No image model.+python3 graphite_bicycle.py [out.png] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from PIL import Image, ImageDraw+from graphite import Graphite+from core import spline, blur, shift, smoothstep, noise2d++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'graphite_bicycle.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+T0 = time.time()+tick = lambda name: print(f'{name:12s} {time.time() - T0:5.1f}s') if os.environ.get('GRAPHITE_TIMING') else None++W, H = 1920, 1080+g = Graphite(W, H, seed=11)+rng = g.rng+g.paper()+g.focus(820, 580, 700, 440, soft=0.45, rough=0.22)++HZ, VP = 410.0, np.array([1640.0, 410.0]) # eye level and the vanishing point of the side street+GY, CURB, CX = 790.0, 872.0, 1250.0 # wall base, curb edge, building corner+LIGHT = np.array([-0.6, -0.8]) # towards the sun: upper left+++def toward_vp(p, s):+ p = np.asarray(p, np.float32)+ return p + (VP - p) * s+++def offset(P, d):+ P = spline(P, 10) if len(P) > 2 else np.asarray(P, np.float32)+ t = np.gradient(P, axis=0); t /= (np.linalg.norm(t, axis=1, keepdims=True) + 1e-6)+ n = np.stack([-t[:, 1], t[:, 0]], 1)+ return P + n * d+++def shadow_sign(P):+ """+1 if the left-hand normal of the path points away from the light"""+ P = np.asarray(P, np.float32)+ t = P[-1] - P[0]; n = np.array([-t[1], t[0]])+ return 1.0 if n @ LIGHT < 0 else -1.0+++def angle_field(c):+ yy, xx = np.arange(H, dtype=np.float32)[:, None], np.arange(W, dtype=np.float32)[None, :]+ return np.arctan2(yy - np.float32(c[1]), xx - np.float32(c[0]))+++L = lambda pts, grade='HB', p=0.62, **k: g.line(pts, grade, p, **k)++# ===================================================================== geometry+RH, FH = np.array([520.0, 668.0]), np.array([1060.0, 668.0]) # hubs+RT, RR, RI = 176.0, 160.0, 150.0 # tyre outer, rim outer, rim inner+BB = np.array([745.0, 700.0])+SC = np.array([690.0, 452.0])+HT, HB = np.array([990.0, 444.0]), np.array([1004.0, 506.0])+FRAME_TUBES = { # painted frame: name -> (points, width)+ 'main': ([(996, 468), (950, 500), (870, 568), (800, 640), (756, 690)], 17),+ 'seat': ([(BB[0] - 4, BB[1] - 8), (718, 580), SC], 15),+ 'chainstay': ([BB, (630, 686), RH], 9),+ 'seatstay': ([(SC[0] + 2, SC[1] + 22), (610, 560), RH], 8),+ 'head': ([HT, HB], 19),+ 'fork': ([(HB[0], HB[1] - 4), (1016, 570), (1040, 630), FH], 11),+}+CHROME_TUBES = { # bright parts: seat post, stem, bars, rack, crank+ 'post': ([SC, (682, 414)], 10),+ 'stem': ([HT, (993, 404)], 10),+ 'bar': ([(993, 404), (1012, 396), (990, 386), (950, 388), (918, 394)], 8),+ 'rack': ([(445, 472), (560, 469), (700, 466)], 7),+ 'rackstrut1': ([(452, 474), (500, 560), RH], 5),+ 'rackstrut2': ([(585, 470), (552, 560), RH], 5),+ 'crank': ([BB, (788, 774)], 12),+}+TUBES = {**FRAME_TUBES, **CHROME_TUBES}+SADDLE = [(612, 392), (640, 383), (690, 384), (728, 392), (744, 402), (728, 408), (690, 412), (650, 418), (618, 414)]+BASKET = [(1016, 398), (1192, 392), (1182, 506), (1030, 508)]+BAGUETTE = [(1030, 430), (1268, 306)]+CONE = [(1084, 394), (1170, 384), (1128, 478)]+GRIP = ([(944, 389), (906, 396)], 13)+FLOWERS = [(1094, 346, -14), (1128, 326, 3), (1162, 350, 18)]+FENDERS = [(RH, 160, 302), (FH, 212, 352)]+fend = lambda P0, a0, a1: g.circle_pts(P0[0], P0[1], 188, None, a0, a1)++# opaque silhouette of the bicycle (what hides the wall behind it; spokes are see-through)+opq = np.zeros((H, W), np.float32)+for P0 in (RH, FH):+ np.maximum(opq, g.ring(P0[0], P0[1], RI, RT + 0.5), out=opq)+ np.maximum(opq, g.ellipse(P0[0], P0[1], 18, 18), out=opq)+for name, (P, w) in TUBES.items():+ np.maximum(opq, g.band(P, w), out=opq)+for P0, a0, a1 in FENDERS:+ np.maximum(opq, g.band(fend(P0, a0, a1), 12, smooth=False), out=opq)+for m in (g.poly(SADDLE), g.band(*GRIP), g.poly(BASKET), g.band(BAGUETTE, 34), g.poly(CONE),+ g.ellipse(BB[0], BB[1], 48, 48), g.rect(768, 768, 814, 782)):+ np.maximum(opq, m, out=opq)+for fx, fy, rot in FLOWERS:+ np.maximum(opq, g.ellipse(fx, fy, 17, 23, rot), out=opq)+open_ = 1 - opq++# the hanging sign in front of the side wall+SIGN = (1372, 236, 66, 50)+sign_m = np.maximum(g.ellipse(*SIGN), g.band([(CX + 8, 140), (1446, 140)], 6))++# building masks+front_wall = g.rect(-5, -5, CX, GY, 0.6)+top_c, base_c = np.array([CX, -1400.0]), np.array([CX, GY]) # the building is three storeys tall+SIDE_END = 0.72+side_far = smoothstep(1545, 1360, np.arange(W, dtype=np.float32)[None, :] + 90 * (noise2d(H, W, 70, 2, 5) - 0.5)) # tone stops short, raggedly+side_wall = g.poly([top_c, toward_vp(top_c, SIDE_END), toward_vp(base_c, SIDE_END), base_c]) * (1 - sign_m)+DOOR = (150, 205, 372, GY) # door leaf+FRAME = (118, 172, 404, GY) # stone surround+plaster = front_wall * (1 - g.rect(*FRAME))+tick('geometry')++# ===================================================================== 1. construction+g.guide((0, HZ), (W, HZ), '2H', 0.42, (0, 0))+for p in [(CX, -60), (CX, GY), (CX, CURB), (1318, CURB + 2), (FRAME[2], FRAME[1]), (-200, GY + 40), (1930, 30), (1930, 660)]:+ g.guide(p, VP, '2H', 0.4, (0, 20))+g.guide((CX, 0), (CX, 1000), '2H', 0.4, (0, 0))+for P0 in (RH, FH):+ g.guide_ellipse(P0[0], P0[1], RT, RT, 0, loops=2, pressure=0.42)+g.guide(RH, BB, '2H', 0.4, (8, 20)); g.guide(BB, SC, '2H', 0.4, (8, 30)); g.guide(SC, HT, '2H', 0.36, (10, 30))+g.guide(HT, FH, '2H', 0.4, (10, 20)); g.guide((440, RH[1] + RT), (1140, FH[1] + RT), '2H', 0.38)+g.guide((FRAME[0], FRAME[1]), (FRAME[0], 860), '2H', 0.36)+g.stage('construction')+tick('construction')++# ===================================================================== 2. contours+# corner, wall base, sidewalk, curb+L([(CX, -10), (CX, GY)], 'HB', 0.7, smooth=False, lost=0.15)+L([(-10, GY), (CX, GY)], 'HB', 0.6, smooth=False, lost=0.25)+L([base_c, toward_vp(base_c, SIDE_END)], 'HB', 0.55, smooth=False)+L([toward_vp(top_c, SIDE_END), toward_vp(base_c, SIDE_END)], 'H', 0.45, smooth=False)+L([(-10, CURB), (1270, CURB), (1300, CURB - 8)], 'HB', 0.6)+L([(-10, CURB + 16), (1275, CURB + 16), (1318, CURB + 2)], 'H', 0.5)+L([(1300, CURB - 8), toward_vp((1300, CURB - 8), 0.55)], 'H', 0.45, smooth=False)+L([(1318, CURB + 2), toward_vp((1318, CURB + 2), 0.55)], 'H', 0.45, smooth=False)+# door, frame, step+L([(FRAME[0], GY), (FRAME[0], FRAME[1]), (FRAME[2], FRAME[1]), (FRAME[2], GY)], 'HB', 0.6, smooth=False, searching=1)+L([(DOOR[0], GY), (DOOR[0], DOOR[1]), (DOOR[2], DOOR[1]), (DOOR[2], GY)], 'HB', 0.55, smooth=False)+L([(FRAME[0] - 14, GY + 2), (FRAME[2] + 14, GY + 2), (FRAME[2] + 20, GY + 24), (FRAME[0] - 20, GY + 24)], 'HB', 0.55, smooth=False, closed=True)+PANELS = [(x0, y0, x1, y1) for (y0, y1) in [(236, 470), (520, 760)] for (x0, x1) in [(170, 252), (270, 352)]]+for (x0, y0, x1, y1) in PANELS: # door panels+ L([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], 'HB', 0.55, smooth=False, closed=True)+# window above the door (left unfinished: lines only)+L([(150, -10), (150, 110), (372, 110), (372, -10)], 'H', 0.5, smooth=False)+L([(140, 118), (382, 118), (386, 130), (136, 130)], 'H', 0.45, smooth=False, closed=True)+L([(261, -10), (261, 110)], 'H', 0.4, smooth=False)+# a first-floor window with open louvred shutters above the bike (bare lines toward the top of the sheet)+L([(690, -10), (690, 112), (880, 112), (880, -10)], 'HB', 0.55, smooth=False)+L([(676, 114), (894, 114), (900, 128), (670, 128)], 'HB', 0.6, smooth=False, closed=True)+L([(785, -10), (785, 112)], 'H', 0.45, smooth=False)+for (x0, x1) in [(628, 686), (884, 942)]:+ L([(x0, -10), (x0, 110), (x1, 110), (x1, -10)], 'H', 0.5, smooth=False)+ g.strokes([[(x0 + 4, y), (x1 - 4, y + 3)] for y in np.arange(4, 106, 9)], 'H', 0.45, width=1.2, taper=(0.1, 0.1), fade=0.3)+# quoins on the corner+QUOINS = []+for k, y in enumerate(np.arange(-40, GY - 20, 52)):+ x0 = 1168 if k % 2 == 0 else 1198+ QUOINS.append((x0, y))+ L([(x0, y + 2), (x0, y + 50), (CX, y + 50)], 'H', 0.5, smooth=False, lost=0.3)+# side facade: shop window, door, windows above+sw = [toward_vp((CX, 360), 0.10), toward_vp((CX, 360), 0.30), toward_vp((CX, 720), 0.30), toward_vp((CX, 720), 0.10)]+L(sw + [sw[0]], 'HB', 0.55, smooth=False)+sd = [toward_vp((CX, 420), 0.38), toward_vp((CX, 420), 0.47), toward_vp((CX, GY), 0.47), toward_vp((CX, GY), 0.38)]+L(sd, 'H', 0.5, smooth=False)+for s0, s1 in [(0.08, 0.22), (0.30, 0.42), (0.50, 0.60)]:+ win = [toward_vp((CX, 40), s0), toward_vp((CX, 40), s1), toward_vp((CX, 230), s1), toward_vp((CX, 230), s0)]+ L(win + [win[0]], 'H', 0.5, smooth=False)+# the far buildings beyond the side street (bare lines)+L([(1930, 30), toward_vp((1930, 30), 0.86)], 'H', 0.45, smooth=False)+L([(1930, 660), toward_vp((1930, 660), 0.86)], 'H', 0.45, smooth=False)+for s in (0.18, 0.42, 0.62, 0.78):+ L([toward_vp((1930, 30), s), toward_vp((1930, 660), s)], 'H', 0.45, smooth=False, lost=0.2)+for s0, s1 in [(0.05, 0.14), (0.25, 0.33), (0.48, 0.55)]:+ for (ya, yb) in [(120, 250), (340, 470)]:+ win = [toward_vp((1930, ya), s0), toward_vp((1930, ya), s1), toward_vp((1930, yb), s1), toward_vp((1930, yb), s0)]+ L(win + [win[0]], 'H', 0.4, smooth=False, lost=0.25)+L([(1700, 300), (1700, 240), (1712, 224), (1724, 240), (1724, 300)], 'H', 0.45, smooth=False) # far bell turret+L([(1690, 300), (1734, 300)], 'H', 0.4, smooth=False)+# the hanging bakery sign: iron bracket from the side wall, oval board, a loaf on it+L([(CX + 8, 140), (1446, 140)], '2B', 0.8, smooth=False)+L([(CX + 8, 196), (1290, 170), (1330, 150), (1360, 142)], 'HB', 0.65)+L(g.circle_pts(1300, 166, 15, 15, 180, 520), 'HB', 0.6)+for x in (1336, 1408):+ L([(x, 141), (x, 187)], 'HB', 0.65, smooth=False)+L(g.circle_pts(*SIGN[:2], SIGN[2], SIGN[3]), '2B', 0.75, closed=True)+L(g.circle_pts(*SIGN[:2], SIGN[2] - 7, SIGN[3] - 7), 'H', 0.55, closed=True)+L(g.circle_pts(1372, 238, 40, 17, 0, 360, rot=-8), 'HB', 0.7, closed=True)+# street plate+PLATE = (1022, 206, 1160, 254)+L([(PLATE[0], PLATE[1]), (PLATE[2], PLATE[1]), (PLATE[2], PLATE[3]), (PLATE[0], PLATE[3])], 'HB', 0.6, smooth=False, closed=True)+# bare brick patch: broken plaster edge+patch_pts = np.array([(430, 214), (470, 182), (540, 176), (600, 190), (668, 178), (724, 210), (742, 262),+ (716, 318), (650, 336), (580, 326), (520, 344), (462, 318), (438, 270)], np.float32)+patch = g.poly(spline(np.vstack([patch_pts, patch_pts[:1]]), 8), 0.8)+L(np.vstack([patch_pts, patch_pts[:1]]), 'HB', 0.6, lost=0.1)+# the bicycle: tyres, rims, fenders, frame, saddle, basket and its load+for P0 in (RH, FH):+ L(g.circle_pts(P0[0], P0[1], RT, RT, 0, 360), '2B', 0.75, closed=True, searching=1)+ L(g.circle_pts(P0[0], P0[1], RR, RR, 0, 360), 'HB', 0.6, closed=True)+ L(g.circle_pts(P0[0], P0[1], RI, RI, 0, 360), 'HB', 0.55, closed=True)+for P0, a0, a1 in FENDERS:+ L(g.circle_pts(P0[0], P0[1], 182, 182, a0, a1), 'HB', 0.6)+ L(g.circle_pts(P0[0], P0[1], 194, 194, a0, a1), 'HB', 0.6)+tube_edges = {}+for name, (P, w) in TUBES.items():+ s = shadow_sign(P)+ lit_e, dark_e = offset(P, -s * w / 2), offset(P, s * w / 2)+ tube_edges[name] = (lit_e, dark_e, s)+ L(lit_e, 'HB', 0.55, lost=0.3, smooth=False)+ L(dark_e, '2B', 0.7, smooth=False)+L(np.vstack([SADDLE, SADDLE[:1]]), '2B', 0.7)+L(np.vstack([BASKET, BASKET[:1]]), 'HB', 0.6)+L(offset(BAGUETTE, -17), 'HB', 0.6, lost=0.2); L(offset(BAGUETTE, 17), '2B', 0.65)+for e, c0 in ((BAGUETTE[0], 160), (BAGUETTE[1], -20)):+ L(g.circle_pts(e[0], e[1], 17, 17, c0 - 62, c0 + 118), 'HB', 0.6)+L(np.vstack([CONE, CONE[:1]]), 'HB', 0.6)+L(g.circle_pts(BB[0], BB[1], 46, 46, 0, 360), 'HB', 0.6, closed=True)+L(g.circle_pts(RH[0], RH[1], 20, 20, 0, 360), 'HB', 0.6, closed=True)+L([(768, 768), (814, 768), (814, 782), (768, 782)], '2B', 0.6, smooth=False, closed=True)+g.stage('contours')+tick('contours')++# ===================================================================== 3. block-in: side of the lead+sh_off = (78, 30) # cast shadow of the bike on the wall+spokes_lines = []+for P0, rot0 in ((RH, 3.0), (FH, 8.0)):+ for i in range(32):+ a = np.deg2rad(rot0 + i * 360 / 32)+ sgn = 1 if i % 2 else -1+ h0 = P0 + 21 * np.array([np.cos(a), np.sin(a)])+ b = a + sgn * np.deg2rad(26)+ spokes_lines.append(np.array([h0, P0 + RI * np.array([np.cos(b), np.sin(b)])], np.float32))+spk = g.lines_mask(spokes_lines, 1.5, 0.6)+cast = blur(shift(opq, *sh_off), 1.0)+cast_wall = cast * front_wall * open_+del spk, cast+cast_ground = blur(g.poly([(RH[0] - 40, RH[1] + RT - 2), (RH[0] + 260, RH[1] + RT - 6), (FH[0] + 40, FH[1] + RT - 2),+ (FH[0] + 150, GY + 4), (RH[0] + 70, GY + 4)]), 5) * open_ * (1 - front_wall)+xramp = np.clip((np.arange(W, dtype=np.float32) - CX) / 260, 0, 1)[None, :]+side_tone = (0.46 + 0.1 * xramp) * np.ones((H, 1), np.float32)+g.shade(side_wall * open_ * side_far, side_tone, angle=80, grade='4B', width=10, pressure=0.34)+wall_light = g.linear((300, 100), (1200, 760))+g.shade(plaster * open_, 0.12 + 0.12 * wall_light, angle=12, grade='2B', width=11, pressure=0.22)+dampband = g.poly([(-10, 690), (200, 702), (420, 684), (700, 708), (980, 690), (CX, 702), (CX, GY), (-10, GY)], 14)+g.shade(dampband * plaster * open_, 0.42, angle=8, grade='4B', width=10, pressure=0.3)+door_m = g.rect(DOOR[0], DOOR[1], DOOR[2], GY) * open_+g.shade(door_m, 0.4, angle=88, grade='4B', width=9, pressure=0.3)+for P0 in (RH, FH):+ g.shade(g.ring(P0[0], P0[1], RR, RT), 0.85, angle=30, grade='6B', width=7, pressure=0.45, finish=False)+for name, (P, w) in FRAME_TUBES.items():+ g.shade(g.band(P, w), 0.6, angle=np.degrees(np.arctan2(P[-1][1] - P[0][1], P[-1][0] - P[0][0])), grade='4B', width=6, pressure=0.4, finish=False, passes=2)+g.shade(g.poly(SADDLE), 0.7, angle=10, grade='6B', width=7, pressure=0.4, finish=False)+g.shade(cast_ground, 0.55, angle=5, grade='4B', width=10, pressure=0.33)+sidewalk = g.rect(-5, GY, 1330, CURB, 0.6)+g.shade(sidewalk * open_, 0.16 + 0.12 * g.linear((0, GY), (0, CURB)), angle=4, grade='2B', width=12, pressure=0.22)+g.stage('block_in')+tick('block_in')++# ===================================================================== 4. hatching: middle values+g.hatch(side_wall * open_ * side_far, side_tone, angle=86, grade='2B', spacing=4.0, length=(50, 90), layers=(0, 0, 25))+g.hatch(cast_wall, 0.4, angle=58, grade='2B', spacing=4.0, length=(34, 70), layers=(0, 0, -62))+g.hatch(cast_ground, 0.6, angle=4, grade='2B', spacing=3.6, length=(40, 80), layers=(0, 0, 55))+# plaster: a breath of hatching where the wall turns away from the light, darker near the corner and the damp+g.hatch(plaster * open_ * (1 - patch), 0.2 * wall_light + 0.16 * dampband, angle=62,+ grade='HB', spacing=4.6, length=(40, 80), layers=(0, 0))+cracks = [[(744, 250), (790, 262), (812, 298), (860, 306)], [(812, 298), (820, 340)], [(438, 300), (400, 330), (384, 380)],+ [(1100, 560), (1124, 600), (1118, 640)], [(60, 420), (84, 452), (80, 500), (104, 520)]]+for c in cracks:+ L(c, 'HB', 0.5, lost=0.2)+# bricks in the patch: course by course, each brick its own value; mortar left light+bricks = np.zeros((H, W), np.float32); brick_tone = np.zeros((H, W), np.float32)+for row, y in enumerate(np.arange(160, 360, 39)):+ x = 400 - (59 if row % 2 else 0)+ while x < 760:+ bw = 118 + rng.normal(0, 3)+ m = g.poly([(x + 4 + rng.normal(0, 1), y + 4), (x + bw - 4, y + 4 + rng.normal(0, 1)), (x + bw - 5, y + 35), (x + 5, y + 35 + rng.normal(0, 1))], 0.8)+ np.maximum(bricks, m, out=bricks)+ np.maximum(brick_tone, m * rng.uniform(0.38, 0.66), out=brick_tone)+ x += bw+bricks *= patch; brick_tone *= patch+under_edge = blur(patch * (1 - shift(patch, 6, 8)), 3) * patch # the plaster lip casts a shadow inside+g.hatch(bricks * open_, brick_tone + 0.25 * under_edge, angle=-22, grade='2B', spacing=3.6, length=(30, 60), layers=(0, 0, 70))+g.hatch(patch * (1 - bricks) * open_, 0.22 + 0.4 * under_edge, angle=40, grade='HB', spacing=3.4, length=(20, 40), layers=(0,))+del bricks, brick_tone+# door: vertical planks, darker toward the recess+g.hatch(door_m, 0.42 + 0.18 * g.linear((DOOR[2], 0), (DOOR[0], 0)), angle=90, grade='2B', spacing=4.0, length=(70, 140), layers=(0, 0, 20))+jamb = g.poly([(DOOR[0] - 26, DOOR[1] - 26), (DOOR[0], DOOR[1]), (DOOR[0], GY), (DOOR[0] - 26, GY)]) * open_+soffit = g.poly([(DOOR[0] - 26, DOOR[1] - 26), (DOOR[2] + 4, DOOR[1] - 26), (DOOR[2], DOOR[1]), (DOOR[0], DOOR[1])])+recess = np.maximum(jamb, soffit)+g.hatch(recess, 0.8, angle=70, grade='4B', spacing=3.4, length=(40, 80))+g.hatch(g.poly([(670, 129), (900, 129), (894, 142), (676, 142)]), 0.7, 20, '2B', 3.2, (20, 40), (0, 0)) # under the sill+for (x0, y0, x1, y1) in PANELS:+ lip = np.maximum(g.rect(x0, y0, x1, y0 + 7), g.rect(x0, y0, x0 + 7, y1))+ g.hatch(lip, 0.85, 45, '4B', 3.0, (8, 16), (0, 0))+ L([(x0 + 2, y1 - 2), (x1 - 2, y1 - 2), (x1 - 2, y0 + 2)], 'HB', 0.4, smooth=False)+# shop window on the shaded side wall: dark glass+swm = g.poly(sw) * open_+g.hatch(swm * side_far, 0.85, angle=84, grade='4B', spacing=3.4, length=(40, 90))+# sidewalk slabs: joints toward the vanishing point, light hatching, curb face+for x in np.arange(-140, 1320, 170):+ p0 = np.array([x, CURB]); p1 = p0 + (VP - p0) * ((CURB - GY) / (CURB - HZ))+ L([p0, p1], 'HB', 0.5, smooth=False, lost=0.25)+L([(-10, 828), (1262, 828)], 'H', 0.45, smooth=False, lost=0.35)+g.hatch(sidewalk * open_ * (1 - cast_ground), 0.2, angle=2, grade='HB', spacing=5, length=(60, 120), layers=(0,))+g.hatch(g.rect(-5, CURB, 1290, CURB + 16), 0.55, angle=88, grade='2B', spacing=3.6, length=(14, 18), layers=(0, 0))+# tyres: strokes that run around the wheel; rims and fenders+for P0 in (RH, FH):+ arcs = []+ for r_ in np.arange(RR + 1.5, RT, 2.6):+ a = rng.uniform(0, 360)+ while a < 720:+ da = rng.uniform(28, 55)+ arcs.append(g.circle_pts(P0[0], P0[1], r_, r_, a, a + da))+ a += da + rng.uniform(-3, 4)+ lit = np.clip(np.cos(angle_field(P0) - np.deg2rad(-125)), 0, 1)+ g.contour_hatch(arcs, g.ring(P0[0], P0[1], RR, RT), 0.95 - 0.35 * lit ** 2, '6B', 0.75, finish=False)+ g.contour_hatch([g.circle_pts(P0[0], P0[1], r_, r_, a0, a0 + 70) for r_ in (152, 155.5, 158.5) for a0 in np.arange(0, 360, 66)],+ g.ring(P0[0], P0[1], RI, RR), 0.25 + 0.45 * (1 - lit), 'HB', 0.6, finish=False)+ del lit+for P0, a0, a1 in FENDERS:+ fm = g.band(fend(P0, a0, a1), 12, smooth=False)+ g.contour_hatch([g.circle_pts(P0[0], P0[1], r_, r_, a0, a1) for r_ in (184, 187, 190, 193)], fm, 0.4, '2B', 0.5, finish=False)+ g.contour_hatch([g.circle_pts(P0[0], P0[1], r_, r_, a0, a1) for r_ in (190.5, 192.5)], fm, 0.9, '4B', 0.7, finish=False)+# frame tubes: strokes along the tube, pressing harder toward the side away from the light+for name, (P, w) in TUBES.items():+ lit_e, dark_e, s = tube_edges[name]+ dark = name in FRAME_TUBES+ for f in np.linspace(-0.42, 0.42, max(3, int(w / 2.6))):+ k = smoothstep(-0.35, 0.3, f) * (1 - 0.35 * smoothstep(0.32, 0.45, f)) # reflected light at the far edge+ pr = (0.32 + 0.55 * k) if dark else (0.08 + 0.55 * k ** 2)+ g.strokes([offset(P, s * w * f)], '4B' if dark else '2B', pr, width=2.0, taper=(0.03, 0.06), wobble=0.15, smooth=False, gain=1.2)+g.stage('hatching')+del wall_light, under_edge, swm, jamb, soffit, xramp+tick('hatching')++# ===================================================================== 5. darks+g.hatch(cast_wall * blur(shift(opq, 30, 12), 3), 0.4, angle=-30, grade='2B', spacing=3.8, length=(30, 60), layers=(0, 0))+g.hatch(recess, 0.95, angle=-20, grade='6B', spacing=3.2, length=(40, 80), layers=(0, 0))+contact = np.maximum(g.ellipse(RH[0] + 12, RH[1] + RT - 2, 46, 6, feather=4), g.ellipse(FH[0] + 12, FH[1] + RT - 2, 46, 6, feather=4))+g.shade(contact * open_, 0.9, angle=0, grade='8B', width=6, pressure=0.6, finish=False)+for P0 in (RH, FH):+ g.contour_hatch([g.circle_pts(P0[0], P0[1], r_, r_, 300, 480) for r_ in np.arange(RR + 3, RT - 1, 3)],+ g.ring(P0[0], P0[1], RR, RT), 1.0, '8B', 0.7, finish=False)+g.shade(g.poly(SADDLE) * g.linear((0, 384), (0, 416)), 0.9, angle=8, grade='8B', width=6, pressure=0.5, finish=False)+g.strokes([GRIP[0]], '8B', 0.95, width=11, taper=(0.02, 0.02), wobble=0.2)+for name in ('main', 'seat', 'fork', 'head'):+ P, w = FRAME_TUBES[name]; s = tube_edges[name][2]+ g.strokes([offset(P, s * w * 0.36)], '6B', 0.7, width=2.6, taper=(0.04, 0.08), wobble=0.15, smooth=False)+# the corner: the shaded side wall darkest right at the edge (value contrast against the lit front)+edge_dark = g.poly([top_c, toward_vp(top_c, 0.06), toward_vp(base_c, 0.06), base_c]) * open_ * (1 - sign_m)+g.hatch(edge_dark, 0.85, angle=80, grade='4B', spacing=3.4, length=(60, 120), layers=(0, 0, 30))+g.stage('darks')+del contact, edge_dark+tick('darks')++# ===================================================================== 6. blend with the stump+g.smudge(side_wall * open_ * side_far, 0.7, radius=3.5, direction=86, length=10)+g.smudge(plaster * open_ * (1 - patch) * (cast_wall < 0.05), 0.85, radius=6, direction=10, length=16)+g.smudge(cast_wall, 0.3, radius=1.5)+for name, (P, w) in TUBES.items():+ g.smudge(g.band(P, w * 0.9), 0.6, radius=1.2, finish=False)+g.smudge(cast_ground, 0.7, radius=4, direction=0, length=14)+g.smudge(sidewalk * open_, 0.6, radius=5, direction=0, length=20)+for P0 in (RH, FH):+ g.smudge(g.ring(P0[0], P0[1], RR + 1, RT - 1, feather=1.5), 0.5, radius=2, finish=False)+g.smudge(door_m, 0.45, radius=3, direction=90, length=14)+for (x0, y0, x1, y1) in PANELS:+ g.erase([(x0 + 3, y1 + 3), (x1 + 3, y1 + 3), (x1 + 3, y0 + 3)], 1.8, 0.6)+g.stage('blend')+del side_tone, dampband, cast_ground, sidewalk, door_m, side_wall, side_far, plaster, recess+tick('blend')++# ===================================================================== 7. erasers: pull out the light+for P0 in (RH, FH):+ g.erase(g.circle_pts(P0[0], P0[1], RT - 4.5, RT - 4.5, 196, 262), 2.4, 0.75, soft=0.7) # tyre glint+ g.erase(g.circle_pts(P0[0], P0[1], RR - 4, RR - 4, 180, 300), 2.0, 0.8, soft=0.5) # rim chrome+ g.erase(g.circle_pts(P0[0], P0[1], RR - 4, RR - 4, 20, 60), 1.6, 0.6, soft=0.5)+for P0, a0, a1 in FENDERS:+ g.erase(g.circle_pts(P0[0], P0[1], 186, 186, max(a0, 200), min(a1, 285)), 2.4, 0.85, soft=0.6)+for name, (P, w) in TUBES.items():+ lit_e, dark_e, s = tube_edges[name]+ if w >= 8: g.erase(offset(P, -s * w * 0.2), max(1.6, w * 0.14), 0.85, soft=0.5)+g.lift(g.ellipse(560, 600, 150, 70, rot=-30, feather=40) * front_wall * open_, 0.3) # light on the wall+g.erase([(CX - 2, 60), (CX - 2, 780)], 1.8, 0.7) # lit edge of the corner+for (a0, a1, w_) in [((0.12, 470), (0.2, 380), 5), ((0.16, 600), (0.27, 450), 3), ((0.21, 650), (0.28, 560), 2)]: # glints on the shop glass+ g.erase([toward_vp((CX, a0[1]), a0[0]), toward_vp((CX, a1[1]), a1[0])], w_, 0.7, soft=1.0)+lip = blur(shift(patch, -5, -6) * (1 - patch), 1.0) # the broken plaster's lit edge+g.lift(lip * g.linear((560, 180), (700, 330)), 0.8)+for (x0, y) in QUOINS: # quoin tops catch light+ g.erase([(x0 + 3, y + 3), (CX - 4, y + 3)], 1.4, 0.5)+g.stage('lift')+del patch, front_wall, cast_wall, lip+tick('lift')++# ===================================================================== 8. details+spk_clip = 1 - np.clip(sum(g.band(TUBES[n][0], TUBES[n][1]) for n in ('chainstay', 'seatstay', 'fork', 'rackstrut1', 'rackstrut2')) + g.ellipse(BB[0], BB[1], 48, 48), 0, 1)+g.strokes(spokes_lines, 'HB', 0.75, width=1.2, taper=(0.02, 0.05), wobble=0.08, clip=spk_clip, smooth=False)+del spk_clip+for P0 in (RH, FH):+ hub = g.ellipse(P0[0], P0[1], 18, 18)+ g.hatch(hub, 0.6 * g.linear((P0[0] - 15, P0[1] - 15), (P0[0] + 15, P0[1] + 15)) + 0.2, 60, '2B', 3, (10, 20), finish=False)+ L(g.circle_pts(P0[0], P0[1], 18, 18), '2B', 0.7, closed=True)+ L(g.circle_pts(P0[0], P0[1], 6, 6), '4B', 0.8, closed=True)+ ticks = []+ for i in range(0, 360, 6):+ a = np.deg2rad(i); u = np.array([np.cos(a), np.sin(a)])+ ticks.append([P0 + (RT - 1) * u, P0 + (RT - 5) * u])+ g.strokes(ticks, '6B', 0.5, width=1.4, taper=(0, 0), wobble=0, smooth=False)+# chainring with teeth and spider; chain; cranks; pedal+g.hatch(g.ring(BB[0], BB[1], 30, 46), 0.55, 40, '2B', 3.2, (14, 26), (0, 0, 70), finish=False)+teeth = []+for i in range(44):+ a = np.deg2rad(i * 360 / 44)+ teeth.append([BB + 45 * np.array([np.cos(a), np.sin(a)]), BB + 49 * np.array([np.cos(a + 0.05), np.sin(a + 0.05)])])+g.strokes(teeth, '4B', 0.6, width=2, taper=(0, 0), wobble=0, smooth=False)+for i in range(5):+ a = np.deg2rad(18 + i * 72)+ L([BB + 8 * np.array([np.cos(a), np.sin(a)]), BB + 32 * np.array([np.cos(a), np.sin(a)])], '2B', 0.6, smooth=False)+L(g.circle_pts(BB[0], BB[1], 30, 30), 'HB', 0.55, closed=True)+L(g.circle_pts(BB[0], BB[1], 9, 9), '4B', 0.7, closed=True)+for (pa, pb) in [((BB[0], BB[1] - 47), (RH[0], RH[1] - 18)), ((BB[0], BB[1] + 47), (RH[0], RH[1] + 18))]:+ pa, pb = np.array(pa), np.array(pb); n = int(np.linalg.norm(pb - pa) / 7)+ links = [[pa + (pb - pa) * (k / n), pa + (pb - pa) * ((k + 0.65) / n)] for k in range(n)]+ g.strokes(links, '4B', 0.75, width=3.2, taper=(0.1, 0.1), wobble=0.1, smooth=False)+L(g.circle_pts(RH[0], RH[1], 18, 18), '2B', 0.7, closed=True)+g.strokes([[(703, 626), (BB[0] - 4, BB[1] - 6)]], 'HB', 0.45, width=8, taper=(0.1, 0.1)) # far crank, faint+g.hatch(g.rect(768, 768, 814, 782), 0.8, 0, '4B', 2.6, (20, 40), finish=False)+# saddle springs and rails+for x0 in (628, 652):+ coil = [(x0 + 6 * np.cos(t * 10 * np.pi), 418 + t * 26 + 2.5 * np.sin(t * 10 * np.pi)) for t in np.linspace(0, 1, 60)]+ g.strokes([coil], '4B', 0.75, width=2.2, smooth=False, taper=(0.02, 0.02), wobble=0.1)+L([(626, 444), (700, 420), (726, 410)], '2B', 0.6)+# basket: wicker stakes and weavers going over and under+bk = g.poly(BASKET)+g.shade(bk, 0.32, 0, '2B', 8, pressure=0.24, finish=False)+stakes = []+for k in range(15):+ t = k / 14+ stakes.append([np.array(BASKET[0]) + (np.array(BASKET[1]) - BASKET[0]) * t, np.array(BASKET[3]) + (np.array(BASKET[2]) - BASKET[3]) * t])+g.strokes(stakes, '2B', 0.6, width=1.8, taper=(0.04, 0.04), wobble=0.2, smooth=False)+weav = []+for j, y in enumerate(np.arange(410, 505, 8.5)):+ xs = np.linspace(1020 + (y - 398) * 0.13, 1190 - (y - 398) * 0.09, 15)+ for i in range(len(xs) - 1):+ up = (i + j) % 2+ weav.append([(xs[i], y), ((xs[i] + xs[i + 1]) / 2, y + (-2.5 if up else 2.5)), (xs[i + 1], y)])+g.strokes(weav, '2B', 0.6, width=2.0, taper=(0.15, 0.15), wobble=0.2)+g.hatch(bk * g.linear((1100, 400), (1185, 500)), 0.7, 70, '4B', 3.4, (16, 30), (0, 30), finish=False)+g.strokes([offset([BASKET[0], BASKET[1]], 3)], '4B', 0.8, width=6, taper=(0.05, 0.05)) # rolled rim+del bk+# baguette: crust tone built in two passes along the loaf, darker underside, ends browner, pale scoring slashes+bm = g.band(BAGUETTE, 34)+crust = 0.38 + 0.5 * g.linear(offset(BAGUETTE, -17)[0], offset(BAGUETTE, 17)[0])+g.shade(bm, crust * 0.8, angle=-27, grade='2B', width=6, pressure=0.32, finish=False)+for f0 in (0.0, 1.3):+ g.contour_hatch([offset(BAGUETTE, f) for f in np.arange(-15.5 + f0, 16, 2.6)], bm, crust, '2B', 0.85, finish=False, taper=(0.05, 0.08))+g.smudge(bm, 0.5, 1.5, finish=False)+for k in range(5):+ t = 0.2 + k * 0.155+ c = np.array(BAGUETTE[0]) + (np.array(BAGUETTE[1]) - BAGUETTE[0]) * t+ g.lift(g.ellipse(c[0] - 2, c[1] - 1, 19, 5, rot=-62, feather=1.5), 0.8)+ L(g.circle_pts(c[0], c[1], 20, 5.5, 20, 160, rot=-62), '4B', 0.75)+L(offset(BAGUETTE, 16.5), '4B', 0.7, smooth=False)+del bm, crust+# flowers: paper cone with folds, three tulips, stems and leaves+g.hatch(g.poly(CONE), 0.3 * g.linear((1090, 400), (1160, 470)) + 0.05, 64, 'HB', 4, (20, 40), (0,), finish=False)+L([(1108, 394), (1124, 472)], 'H', 0.55); L([(1142, 390), (1128, 470)], 'H', 0.5)+for (fx, fy, rot) in FLOWERS:+ a = np.deg2rad(rot); up = np.array([np.sin(a), -np.cos(a)]); rt = np.array([np.cos(a), np.sin(a)])+ c = np.array([fx, fy])+ L([c - up * 20, c - up * 30 + rt * (1126 - fx) * 0.2, np.array([fx + (1126 - fx) * 0.6, 392])], '2B', 0.6)+ head = g.ellipse(fx, fy, 16, 22, rot)+ g.hatch(head, 0.3 + 0.45 * g.linear(c - rt * 14 - up * 10, c + rt * 14 + up * 10), 70 + rot, '2B', 3.0, (12, 24), (0, 0, 60), finish=False)+ petal = [c - rt * 16 - up * 2, c - rt * 11 + up * 22, c - rt * 4 + up * 12, c + up * 24, c + rt * 4 + up * 12, c + rt * 11 + up * 22, c + rt * 16 - up * 2]+ L(petal, '2B', 0.7)+ L([c - rt * 16 - up * 2, c - up * 16 - rt * 8, c - up * 22, c - up * 16 + rt * 8, c + rt * 16 - up * 2], '2B', 0.7)+ L([c - rt * 4 + up * 12, c - rt * 2 - up * 10], 'HB', 0.5)+for lf in ([(1102, 396), (1070, 344), (1080, 296)], [(1150, 392), (1190, 338), (1184, 296)]):+ L(lf, 'HB', 0.6)+ L([lf[0], ((lf[1][0] + lf[2][0]) / 2 + 10 * np.sign(lf[1][0] - 1126), lf[1][1] + 6), lf[2]], 'HB', 0.5)+# bell+g.hatch(g.ellipse(962, 380, 11, 8), 0.5, 50, '2B', 3, (10, 18), finish=False)+L(g.circle_pts(962, 380, 11, 8, 180, 360), '2B', 0.7)+L([(951, 381), (973, 381)], '2B', 0.7, smooth=False)+# sign, plate and house-number lettering+g.hatch(g.ellipse(*SIGN) * (1 - g.ellipse(1372, 238, 40, 17, -8)), 0.28, 60, 'HB', 3.6, (20, 40), (0, 0), finish=False)+g.hatch(g.ellipse(1372, 238, 40, 17, -8), 0.5 + 0.35 * g.linear((1372, 222), (1372, 256)), 0, '2B', 3.0, (20, 40), finish=False)+for k in range(3):+ cxk = 1352 + k * 20+ g.erase([(cxk - 7, 241), (cxk + 7, 232)], 2.6, 0.8)+g.hatch(g.rect(PLATE[0] + 4, PLATE[3] + 1, PLATE[2] + 6, PLATE[3] + 7), 0.7, 0, '2B', 2.8, (30, 60))+L([(PLATE[0] + 6, PLATE[1] + 6), (PLATE[2] - 6, PLATE[1] + 6), (PLATE[2] - 6, PLATE[3] - 6), (PLATE[0] + 6, PLATE[3] - 6)], 'H', 0.5, smooth=False, closed=True)+g.write('VIA DEL MULINO', (PLATE[0] + PLATE[2]) / 2, (PLATE[1] + PLATE[3]) / 2 + 1, 17, '2B', 0.75, font='serif', anchor='mm')+L(g.circle_pts(312, 488, 16, 20), 'HB', 0.6, closed=True)+g.write('7', 312, 489, 24, '2B', 0.8, font='serif', anchor='mm')+L(g.circle_pts(172, 500, 7, 7), '2B', 0.75, closed=True) # door knob+# cobbles: irregular rows of rounded stones, a tone on each, dark joints, lit tops+cob = np.zeros((H, W), np.float32)+outlines = []+for row, y in enumerate([896, 924, 956, 994, 1038]):+ hgt = 25 + row * 8; x = -30 - rng.uniform(0, 40)+ while x < W + 20:+ wdt = hgt * rng.uniform(1.25, 2.0)+ cx_, cy_ = x + wdt / 2, y + hgt / 2 + rng.normal(0, 2)+ tt = np.linspace(0, 2 * np.pi, 10)[:-1]+ sq = np.sign(np.cos(tt)) * np.abs(np.cos(tt)) ** 0.7, np.sign(np.sin(tt)) * np.abs(np.sin(tt)) ** 0.7 # squarish+ q = np.stack([cx_ + wdt * 0.47 * sq[0] * (1 + 0.07 * rng.normal(size=9)), cy_ + hgt * 0.44 * sq[1] * (1 + 0.07 * rng.normal(size=9))], 1)+ pts = spline(np.vstack([q, q[:1]]), 6)+ if not ((cx_ < 700 or cx_ > 1450) and cy_ > 965): # keep the margin clear for notes and swatches+ outlines.append(pts)+ x += wdt + rng.uniform(3, 11)+im = Image.new('L', (W, H), 0); dr = ImageDraw.Draw(im)+for pts in outlines: dr.polygon([tuple(map(float, p)) for p in pts], fill=255)+cob = blur(np.asarray(im, np.float32) / 255, 0.8)+del im, dr+street = g.rect(-5, CURB + 18, W + 5, H + 5) * (1 - g.rect(-5, 968, 720, H + 5, 18)) * (1 - g.rect(1450, 968, W + 5, H + 5, 18))+low_r = blur(shift(1 - cob, -9, -7), 4) * cob # the lower right of each stone turns from the light+g.shade(cob * street, 0.22 + 0.5 * low_r, angle=-15, grade='2B', width=8, pressure=0.26)+g.hatch(cob * street, 0.15 + 0.55 * low_r, -25, 'HB', 3.8, (14, 26), (0, 0, 60))+g.hatch((1 - cob) * street, 0.62, 40, '2B', 3.4, (12, 24), (0, 0, -50))+for pts in outlines:+ L(pts, 'HB', 0.5, lost=0.25, fade=0.12)+g.lift(blur(shift(cob, 4, 4) * (1 - shift(cob, 7, 7)) * cob, 1.5) * street, 0.5) # top-left rims catch the light+del cob, low_r+# a sparrow on the sidewalk has found the crumbs that fell from the baguette+SP, K = np.array([1302.0, 838.0]), 1.4+sp = lambda dx, dy: SP + K * np.array([dx, dy], np.float32)+body = g.ellipse(*sp(0, 0), 24 * K, 14 * K, rot=-12)+head = g.ellipse(*sp(-22, -12), 10 * K, 9 * K)+tail = g.poly([sp(18, -6), sp(44, -16), sp(46, -8), sp(20, 6)])+bird = np.clip(body + head + tail, 0, 1)+g.hatch(bird, 0.35 + 0.45 * g.linear(sp(-10, -14), sp(10, 14)), 30, '2B', 3.0, (10, 20), (0, 0, 70), finish=False)+del bird, body, head, tail+g.hatch(g.ellipse(*sp(4, -3), 15 * K, 8 * K, rot=-18), 0.85, -20, '4B', 2.8, (8, 14), (0, 0), finish=False) # wing+g.strokes([[sp(-4 + 5 * k, -8), sp(10 + 5 * k, -2)] for k in range(4)], '6B', 0.7, width=1.6) # wing bars+g.lift(g.ellipse(*sp(-8, 7), 13 * K, 5 * K, rot=-10, feather=3), 0.6) # pale breast+g.hatch(g.ellipse(*sp(-22, -16), 8 * K, 5 * K), 0.8, 10, '4B', 2.6, (6, 12), (0, 0), finish=False) # dark cap+L(np.vstack([g.circle_pts(*sp(-22, -12), 10 * K, 9 * K, 150, 330), [sp(8, -14)], [sp(44, -16)], [sp(46, -8)],+ [sp(20, 8)], [sp(-6, 12)], [sp(-24, -4)]]), '2B', 0.75)+L([sp(-31, -14), sp(-40, -11), sp(-31, -8)], '4B', 0.85, smooth=False) # beak+g.strokes([[sp(-24, -14)]], '8B', 1.0, width=4.0) # eye+for dx in (-4, 6):+ L([sp(dx, 12), sp(dx - 3, 24), sp(dx - 9, 26)], '4B', 0.75, smooth=False)+g.shade(g.ellipse(*sp(4, 27), 30 * K, 4 * K, feather=3) * open_, 0.6, 0, '4B', 5, pressure=0.35, finish=False)+for (cx_, cy_, r_) in [(1240, 866, 3.2), (1229, 860, 2.4), (1254, 872, 2.8), (1217, 868, 2)]:+ L(g.circle_pts(cx_, cy_, r_ * 1.3, r_), 'HB', 0.65, closed=True)+g.stage('details')+tick('details')++# ===================================================================== 9. margins+g.write('Via del Mulino, 8:10 - the bread run', 64, 990, 30, 'HB', 0.75)+g.write('2 . X', 66, 1034, 26, 'HB', 0.65)+g.value_scale(1478, 980, w=56, h=34, gap=8, label_size=22)+g.fingerprint(1852, 64, 25, rot=-30, amount=0.3) # where the sheet was held+g.smear([(1400, 1070), (1700, 1052), (1900, 1062)], 70, 0.05)+tick('margins')++g.save(out, stages_dir=stages)+tick('saved')+print('saved', out)diff --git a/examples/linocut_snowy_village.jpg b/examples/linocut_snowy_village.jpgnew file mode 100644index 0000000..e09f2a6Binary files /dev/null and b/examples/linocut_snowy_village.jpg differdiff --git a/examples/linocut_snowy_village.py b/examples/linocut_snowy_village.pynew file mode 100644index 0000000..9a9d1c7--- /dev/null+++ b/examples/linocut_snowy_village.py@@ -0,0 +1,280 @@+"""Example (linocut / 黑白麻胶版画): 雪夜归途 · Homeward, First Snow -- a two-block linocut of a village on the+first night of snow. Someone is hauling a sled of firewood home by lantern light; their footprints and the sled+runners trail back out of the picture, the snow ahead of them is still untouched. At the cottage the door stands+open, warm light spills onto the snow and the dog has run out to meet them (its paw prints lead back to the+door). Chimney smoke leans with the wind, snow falls across a black sky cut with long wind streaks and a carved+moon with broken rings; a bare tree frames the left side, a spruce wood runs behind the houses.+Key block in black; one spot-colour block (lamp ochre) prints the lit windows, the door, the spill of light and+the lantern glow, slightly out of register. Pencil edition number, title and signature in the margin; blind chop.+Draw-on stages: paper -> inked block -> blocking out -> sky -> hills and wood -> village -> snow field ->+figures -> colour block -> pencil. No image model.+python3 linocut_snowy_village.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from linocut import Linocut+from core import spline++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'linocut_snowy_village.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++BX0, BY0, BX1, BY1 = 100, 56, 1820, 918+L = Linocut(1920, 1080, block=(BX0, BY0, BX1, BY1), seed=11)+rng = np.random.default_rng(5)+lamp = L.colour_block('#e8a33a', offset=(4, -3))+KEY = [L.key]+++def line(ctrl, x0=BX0 - 10, x1=BX1 + 10):+ P = spline(ctrl, 16)+ xs = np.arange(x0, x1 + 1, 4, dtype=np.float32)+ return xs, np.interp(xs, P[:, 0], P[:, 1]).astype(np.float32)+++RX, RY = line([(BX0 - 10, 520), (260, 478), (470, 505), (700, 452), (930, 492), (1180, 438), (1420, 470), (1640, 430), (BX1 + 10, 455)])+FX, FY = line([(BX0 - 10, 596), (380, 588), (700, 606), (1000, 590), (1300, 604), (1600, 586), (BX1 + 10, 598)])+GX, GY = line([(BX0 - 10, 652), (300, 640), (620, 664), (900, 650), (1250, 662), (1560, 646), (BX1 + 10, 656)])+ridge = lambda x: np.interp(x, RX, RY)+wood = lambda x: np.interp(x, FX, FY)+ground = lambda x: np.interp(x, GX, GY)++sky = [(BX0 - 10, BY0 - 10), (BX1 + 10, BY0 - 10)] + list(zip(RX[::-1], RY[::-1]))+hills = list(zip(RX, RY)) + list(zip(FX[::-1], FY[::-1]))+field = list(zip(GX, GY)) + [(BX1 + 10, BY1 + 10), (BX0 - 10, BY1 + 10)]+above_field = [(BX0 - 10, BY0 - 10), (BX1 + 10, BY0 - 10)] + list(zip(GX[::-1], GY[::-1]))+MX, MY, MR = 1532, 196, 74++L.stage('paper', blocks=[])+L.stage('inked', blocks=KEY)++# ---- 1. blocking out: the big whites are cut away first+L.clear(L.poly(hills), chatter=0.35, angle=4)+L.clear(L.poly(field), chatter=0.5, angle=-6)+L.clear(L.disc(MX, MY, MR), chatter=0.2, angle=-30)+L.stage('blocking', blocks=KEY)++# ---- 2. sky: wind streaks with the V-gouge, the moon and its rings, snow clouds+moon_d = lambda x, y: np.hypot(x - MX, y - MY)+++def streak_density(x, y):+ band = max(np.exp(-((y - 150 - 0.05 * (x - 900)) / 40) ** 2), np.exp(-((y - 345 + 0.04 * (x - 900)) / 50) ** 2))+ return (0.12 + 0.88 * band) * np.clip((moon_d(x, y) - 215) / 60, 0, 1)+++L.flow(sky, lambda x, y: 171 + 5 * np.sin(x / 230 + y / 95), n=300, length=(40, 320), width=(1.6, 5.0),+ step=3.0, density=streak_density)+L.moon(MX, MY, MR, rings=(1.42, 1.72, 2.05, 2.42))+L.stage('sky', blocks=KEY)++# ---- 3. hills: drift contours left standing parallel to the ridge, darker on the flanks facing away from the moon+slope = np.gradient(RY) / 4.0+++def hill_density(x, y):+ s = float(np.interp(x, RX, slope))+ depth = (y - ridge(x)) / max(wood(x) - ridge(x), 1)+ return np.clip(0.12 + 2.2 * max(-s, 0) + 0.55 * depth ** 2, 0, 0.95)+++L.hatch(hills, angle=0, spacing=9, width=2.6, dash=(25, 140), gap=(8, 60), cut=False,+ bend=lambda x, y: ridge(x) - ridge(1000), density=hill_density)+# the spruce wood: a black band behind the houses with trees rising out of it+for x in np.arange(BX0 + 12, BX1 - 8, 26.0):+ x = x + rng.uniform(-10, 10)+ h = rng.uniform(55, 120) * (0.85 + 0.3 * np.sin(x / 140) ** 2)+ L.pine(x, wood(x) + 30, h, tiers=int(h / 22) + 2, snow=0.7, halo=2.0, region=L.poly(above_field))+for x, h in ((560, 150), (1180, 165), (1420, 140), (1700, 175)):+ L.pine(x, ground(x) + 14, h, snow=0.85, halo=2.5, region=L.poly(above_field))+L.leave(L.poly(list(zip(FX, FY + 6)) + list(zip(GX[::-1], GY[::-1] + 2)))) # the wood's dark foot+L.stage('hills', blocks=KEY)++# ---- 4. the village: cottages with snow-heavy roofs; lit windows go on the colour block+L.cottage(430, 640, 118, 74, 66, side=104, windows=[(36, 26, 22, 26)], side_windows=[(40, 22, 22, 26)],+ chimney=(0.7, 16, 34), lit=lamp)+home = L.cottage(650, 676, 196, 118, 112, side=176, rise=0.1, windows=[], side_windows=[(36, 40, 34, 40), (106, 40, 34, 40)],+ door=(70, 54, 84, True), chimney=(0.55, 22, 46), lit=lamp, attic=False)+L.cottage(1050, 652, 150, 96, 88, side=130, windows=[(30, 40, 28, 32), (92, 40, 28, 32)], side_windows=[(54, 34, 26, 30)],+ chimney=(0.35, 18, 38), lit=None)+c4 = L.cottage(1290, 634, 108, 70, 64, side=92, windows=[(40, 22, 26, 28)], chimney=(0.6, 14, 30), lit=lamp)+L.smoke(*home['chimney'], rise=190, drift=-200, width=13)+L.smoke(*c4['chimney'], rise=120, drift=-190, width=10)+L.stage('village', blocks=KEY)++# ---- 5. the snow field: drift ridges, the trodden path, a fence going down to the road+path = [(home['door'][0] + 27, 690), (820, 712), (980, 744), (1150, 796), (1290, 860), (1400, 900), (1460, 930)]+P = spline(path, 20)+++def path_dist(x, y):+ return float(np.min(np.hypot(P[:, 0] - x, P[:, 1] - y)))+++def field_density(x, y):+ lowness = max(0.0, (y - ground(x)) / (BY1 - ground(x)))+ tree_shade = np.exp(-((x - 300) / 260) ** 2)+ nearpath = np.clip(1 - path_dist(x, y) / 60, 0, 1)+ return np.clip(0.18 + 0.55 * lowness ** 1.5 + 0.5 * tree_shade - 0.6 * nearpath, 0.02, 0.95)+++L.hatch(field, angle=-2, spacing=12, width=3.0, dash=(40, 240), gap=(10, 90), cut=False,+ bend=lambda x, y: 16 * np.sin(x / 150 + y / 41) + 9 * np.sin(x / 61 - y / 23),+ density=field_density)+# the path: a soft trough; its far edge is a broken ridge, its near side holds a little shadow+tg = np.gradient(P, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True); nr = np.stack([-tg[:, 1], tg[:, 0]], 1)+halfw = np.linspace(12, 34, len(P))[:, None]+L.clear(L.poly(list(P - nr * halfw) + list((P + nr * halfw)[::-1])), chatter=0.25, angle=20)+for a, b in ((0.04, 0.3), (0.36, 0.62), (0.68, 0.98)):+ i0, i1 = int(a * len(P)), int(b * len(P))+ L.gouge(P[i0:i1:3] - nr[i0:i1:3] * (halfw[i0:i1:3] + 2), 2.6, 'v', cut=False, smooth=False)+L.hatch(L.poly(list(P + nr * (halfw * 0.35)) + list((P + nr * halfw)[::-1])), angle=24, spacing=7, width=2.0,+ dash=(6, 16), gap=(5, 18), cut=False, density=lambda x, y: 0.55)+++def post(x, y, h, lean=0.0):+ w = 7 + h * 0.06+ pts = [(x - w / 2, y), (x - w / 2 + lean, y - h), (x + w / 2 + lean, y - h), (x + w / 2, y)]+ L.leave(pts)+ L.clear(L.poly([(x - w / 2 + lean + 1.5, y - h + 1), (x + lean, y - h - 6), (x + w / 2 + lean - 1.5, y - h + 1),+ (x + w / 2 + lean - 1.5, y - h + 5), (x - w / 2 + lean + 1.5, y - h + 5)]), chatter=0)+ L.gouge([(x - w / 2 + lean - 1, y - h + 1), (x + lean, y - h - 7), (x + w / 2 + lean + 1, y - h + 1)], 1.8, 'knife', cut=False)+ # moon shadow falls to the lower left+ L.hatch([(x - w / 2, y), (x + w / 2, y), (x - h * 0.9, y + h * 0.22), (x - h * 0.9 - w, y + h * 0.2)], angle=-14,+ spacing=4.5, width=2.0, dash=(8, 30), gap=(2, 6), cut=False)+++posts = [(1760, 792, 70), (1650, 764, 62), (1548, 740, 55), (1452, 720, 49), (1362, 704, 43), (1280, 692, 38), (1204, 682, 34)]+for (x, y, h), (x2, y2, h2) in zip(posts[:-1], posts[1:]):+ for f in (0.35, 0.7):+ L.gouge(spline([(x, y - h * f), ((x + x2) / 2, (y - h * f + y2 - h2 * f) / 2 + 4), (x2, y2 - h2 * f)], 6), 2.6, 'brush',+ end=2.2, cut=False, smooth=False)+for x, y, h in posts:+ post(x, y, h, lean=rng.uniform(-3, 3))+L.stage('field', blocks=KEY)++# ---- 6. the bare tree, the walker with sled and lantern, the dog; prints in the snow; falling snow+L.bare_tree(262, 912, 730, lean=-0.07, spread=0.95, width=50, depth=6, halo=3.0, seed=7)+L.hatch([(225, 912), (300, 912), (170, 940), (90, 940)], angle=-10, spacing=5, width=2.2, dash=(10, 40), gap=(2, 8),+ cut=False) # the trunk's moon shadow++# tracks first, so the sled and walker stand on them: runner tracks and boot prints come in from the lower right+trk = [(1556, 902), (1610, 914), (1660, 930)]+TP = spline(trk, 20); tt = np.gradient(TP, axis=0); tt /= np.linalg.norm(tt, axis=1, keepdims=True); tn = np.stack([-tt[:, 1], tt[:, 0]], 1)+for side in (-10, 10):+ L.gouge(TP + tn * side, 2.4, 'brush', end=3.4, cut=False, smooth=False)+L.footprints([(1236, 868), (1320, 884), (1400, 900), (1460, 930)], step=27, size=7.5, side=7, start=0.12)++# the sled, seen a little from behind: a pile of split logs whose cut ends face us+sx0, sx1, sy = 1400, 1550, 898+L.outline(L.mask_of([L.stroke([(sx1 + 6, sy), (sx0 + 12, sy), (sx0 - 6, sy - 6), (sx0 - 10, sy - 20), (sx0 - 2, sy - 26)], 4.5, 'brush', end=3.5)]), 2.0)+L.gouge([(sx1 + 6, sy), (sx0 + 12, sy), (sx0 - 6, sy - 6), (sx0 - 10, sy - 20), (sx0 - 2, sy - 26)], 4.5, 'brush', end=3.5, cut=False)+for xx in (sx0 + 22, sx0 + 70, sx1 - 14):+ L.gouge([(xx, sy), (xx + 1, sy - 13)], 5.0, 'knife', cut=False, smooth=False)+L.leave([(sx0 + 2, sy - 19), (sx1 + 8, sy - 19), (sx1 + 8, sy - 12), (sx0 + 2, sy - 12)])+R = 13.0+ends = [(sx1 - 52, sy - 32), (sx1 - 26, sy - 32), (sx1, sy - 32), (sx1 - 39, sy - 54), (sx1 - 13, sy - 54), (sx1 - 26, sy - 76)]+bodies = [L.stroke([(cx - 104 + 6 * (cy < sy - 60), cy), (cx, cy)], 2 * R, 'knife') for cx, cy in ends]+ovals = [np.array([(ex + R * 0.82 * np.cos(t), ey + R * np.sin(t)) for t in np.linspace(0, 2 * np.pi, 28)], np.float32) for ex, ey in ends]+pile = L.mask_of(bodies + ovals)+L.outline(pile, 2.4)+L.leave(pile)+for cx, cy in ends: # bark: long V cuts along the logs+ for f in (-0.45, 0.1):+ a = cx - 100 + rng.uniform(0, 26); b = cx - rng.uniform(16, 40)+ L.gouge([(a, cy + f * R), (b, cy + f * R + rng.uniform(-1.5, 1.5))], 1.8, 'v', smooth=False)+for cx, cy in ends: # end grain: rings and a check+ L.clear(L.poly([(cx + (R - 2.4) * 0.82 * np.cos(t), cy + (R - 2.4) * np.sin(t)) for t in np.linspace(0, 2 * np.pi, 28)]), chatter=0)+ L.rings(cx + 0.5, cy, [R * 0.28, R * 0.55], width=1.5, cut=False, arc=(1.6, 3.4), gap=(0.15, 0.5), squash=1.2)+ a = rng.uniform(0, 2 * np.pi)+ L.gouge([(cx, cy), (cx + np.cos(a) * R * 0.66, cy + np.sin(a) * R * 0.8)], 1.5, 'knife', cut=False, smooth=False)+L.gouge(spline([(sx0 + 40, sy - 92), (sx0 + 60, sy - 50), (sx0 + 74, sy - 16)], 8), 2.4, 'knife', cut=False) # lashing++# the walker: hooded coat, leaning into the pull; lantern held out ahead, rope in the back hand+wx, wy, K = 1236, 872, 1.1+F = lambda pts: [(wx + x * K, wy + y * K) for x, y in pts]+coat = F([(-20, -176), (-6, -186), (10, -184), (20, -170), (20, -152), (24, -128), (32, -80), (44, -30), (24, -24), (0, -22),+ (-22, -24), (-40, -30), (-30, -80), (-24, -128), (-26, -150), (-28, -164)])+legs = [F([(-10, -30), (-22, -14), (-32, -2)]), F([(14, -30), (22, -14), (32, -4)])]+arm_f = F([(-12, -146), (-34, -124), (-56, -112)])+arm_b = F([(12, -144), (26, -118), (38, -98)])+parts = [np.array(spline(coat + [coat[0]], 6), np.float32)]+parts += [L.stroke(lg, 12 * K, 'brush', end=10 * K) for lg in legs]+parts += [L.stroke(arm_f, 12 * K, 'brush', end=9 * K), L.stroke(arm_b, 12 * K, 'brush', end=9 * K)]+parts += [np.array(F([(-48, 0), (-24, 0), (-24, -10), (-38, -10)]), np.float32), np.array(F([(22, -1), (44, 0), (40, -11), (26, -12)]), np.float32)]+scarf = F([(-12, -150), (-30, -154), (-48, -150), (-64, -156)])+parts.append(L.stroke(scarf, 13 * K, 'brush', end=8 * K))+wm = L.mask_of(parts)+L.outline(wm, 2.6)+L.leave(wm)+L.clear(L.poly(F([(-11, -177), (-20, -177), (-24, -171), (-29, -166), (-24, -163), (-23, -159), (-18, -156), (-11, -158)])), chatter=0) # face in the hood+L.leave(L.disc(*F([(-19, -170)])[0], 1.8)) # eye+L.gouge(F([(-6, -182), (8, -170), (12, -150)]), 2.8, 'v', smooth=True) # hood seam+for u in (-30, -42, -54): # scarf stripes+ L.gouge(F([(u + 2, -160), (u - 1, -146)]), 3.2, 'v', smooth=False, taper=(0.2, 0.2))+for u in (-60, -64, -68): # fringe+ L.gouge(F([(-62, -156), (u - 10, -160 + (u + 64) * 0.9)]), 2.0, 'brush', end=1.0, cut=False, smooth=False)+L.gouge(F([(-24, -100), (24, -98)]), 3.0, 'u', smooth=False, taper=(0, 0.15)) # belt+for k, (a, b) in enumerate((((-16, -92), (-30, -32)), ((-2, -92), (-6, -30)), ((12, -92), (24, -34)), ((22, -128), (14, -104)))):+ L.gouge(F([a, b]), 2.4, 'v', smooth=False)+# lantern on a short bail from the front hand+lx, ly = wx - 58 * K, wy - 80 * K+L.gouge([F([(-56, -112)])[0], (lx, ly - 22)], 2.0, 'knife', cut=False, smooth=False)+lant = [(lx - 10, ly - 18), (lx + 10, ly - 18), (lx + 8, ly + 16), (lx - 8, ly + 16)]+L.outline(L.poly(lant), 2.4)+L.leave(lant)+L.leave([(lx - 5, ly - 24), (lx + 5, ly - 24), (lx + 10, ly - 18), (lx - 10, ly - 18)])+L.clear(L.rect(lx - 6, ly - 13, lx - 1, ly + 11), chatter=0); L.clear(L.rect(lx + 1, ly - 13, lx + 6, ly + 11), chatter=0)+# rope from the back hand to the sled's nose+L.gouge(spline([F([(38, -98)])[0], (wx + 70, wy - 60), (sx0 - 18, sy - 34), (sx0 - 2, sy - 26)], 10), 2.2, 'knife', cut=False)+# shadows on the snow, thrown down-left by the moon+L.hatch([(wx - 44, wy), (wx + 44, wy), (wx - 160, wy + 36), (wx - 230, wy + 32)], angle=-12, spacing=4.5, width=2.0,+ dash=(10, 40), gap=(2, 7), cut=False)+L.hatch([(sx0, sy + 2), (sx1 + 8, sy + 2), (sx1 - 60, sy + 28), (sx0 - 90, sy + 26)], angle=-12, spacing=4.5, width=2.0,+ dash=(10, 40), gap=(2, 7), cut=False)++# the dog, run out from the open door to meet them; paw prints lead back to the door+dx, dy = 1030, 752+dog = [(dx - 30, dy - 22), (dx - 10, dy - 27), (dx + 14, dy - 26), (dx + 24, dy - 32), (dx + 30, dy - 42), (dx + 38, dy - 38),+ (dx + 44, dy - 32), (dx + 52, dy - 28), (dx + 46, dy - 22), (dx + 34, dy - 20), (dx + 24, dy - 10), (dx + 4, dy - 9),+ (dx - 20, dy - 9), (dx - 32, dy - 14)]+dparts = [np.array(spline(dog + [dog[0]], 5), np.float32)]+dparts += [L.stroke(p, 5.5, 'brush', end=4.5) for p in ([(dx + 22, dy - 12), (dx + 34, dy - 4), (dx + 44, dy - 2)],+ [(dx + 14, dy - 12), (dx + 18, dy + 2)],+ [(dx - 18, dy - 12), (dx - 34, dy - 2), (dx - 44, dy + 2)],+ [(dx - 24, dy - 12), (dx - 22, dy + 3)],+ [(dx - 30, dy - 20), (dx - 44, dy - 32), (dx - 46, dy - 44)])]+dparts.append(np.array([(dx + 32, dy - 40), (dx + 30, dy - 52), (dx + 38, dy - 42)], np.float32)) # ear up+L.leave(L.mask_of(dparts))+L.jab(dx + 36, dy - 34, 2.4, angle=0)+L.hatch([(dx - 34, dy), (dx + 40, dy), (dx - 40, dy + 16), (dx - 100, dy + 14)], angle=-12, spacing=4.5, width=2.0,+ dash=(10, 30), gap=(2, 7), cut=False)+L.footprints([(home['door'][0] + 27, 700), (860, 718), (960, 740), (1000, 752)], step=20, size=3.6, side=4, paws=True, start=0.05, stop=0.95)++# falling snow over everything still black+busy = np.clip(wm + pile + L.mask_of(dparts) + L.disc(lx, ly, 26), 0, 1) # keep flakes off faces and props+L.speckle(np.clip(L.rect(BX0, BY0, BX1, BY1) - (busy > 0.01), 0, 1), n=1700, size=(1.8, 4.6),+ angle=205, stars=0.012)+L.stage('figures', blocks=KEY)++# ---- 7. the colour block: lantern glow, the spill of light from the door (windows were left on it already)+glow = L.disc(lx, ly, 58)+L.leave(glow, on=lamp)+for k in range(18):+ a = 2 * np.pi * k / 18 + rng.uniform(-0.05, 0.05)+ L.gouge([(lx + np.cos(a) * 18, ly + np.sin(a) * 18), (lx + np.cos(a) * 62, ly + np.sin(a) * 62)], 4.5, 'v',+ on=lamp, smooth=False)+d0, dtop, d1, dbase = home['door']+far = [(d1 + 64 - (d1 - d0 + 120) * f, dbase + 96 + 8 * np.sin(f * 9) + rng.uniform(-5, 5)) for f in np.linspace(0, 1, 9)]+L.leave(L.poly([(d0 + 2, dbase), (d1 - 2, dbase)] + far), on=lamp)+L.hatch([(d0 - 70, dbase + 30), (d1 + 90, dbase + 30), (d1 + 90, dbase + 112), (d0 - 70, dbase + 112)], angle=-4, spacing=11,+ width=4.5, dash=(14, 50), gap=(16, 50), tool='u', on=lamp, density=lambda x, y: np.clip((y - 700) / 70, 0.15, 1))+L.stage('colour')++# ---- 8. pencil and chop+L.sign('7/30', 'Homeward, First Snow', 'E. Vintersol 2026', y=BY1 + 54)+L.chop(BX1 - 18, BY1 + 92, size=30, seed=4)++img = L.save(out, stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/macpaint_garden.jpg b/examples/macpaint_garden.jpgnew file mode 100644index 0000000..11759e4Binary files /dev/null and b/examples/macpaint_garden.jpg differdiff --git a/examples/macpaint_garden.py b/examples/macpaint_garden.pynew file mode 100644index 0000000..a0e50b7--- /dev/null+++ b/examples/macpaint_garden.py@@ -0,0 +1,335 @@+"""Example (1-bit paint program / 1-bit 早期画图软件): 窗台花园 · Windowsill Garden — a picture being made in a+1984-style black-and-white paint program, interface and all.++On the canvas: a four-pane window with gingham curtains tied back (the right one is the left one copied and flipped);+outside, a sky in bands of patterns, a sun, clouds, hills and little houses. On the sill, a seed packet and three+terracotta pots tell forty days of a sunflower: a sprout (day 2), a leafy seedling (day 14) and the full flower+(day 40), labelled underneath with tags and arrows (day 0 -> 2 -> 14 -> 40). The watering can's spout is still over+the day-2 pot, a drop falling in; at the other end a black cat sits on the sill, watching a white butterfly that has+looped in from the flower. A calendar on the wall has the days crossed off.+Draw-on stages follow the tools: frame -> sky -> town -> room -> pots -> can -> cat (with a zoom window on the eye) ->+spray -> type menu -> final (marquee round the butterfly, document saved under its name).+Every pixel is black or white; tone is patterns only.+python3 macpaint_garden.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from macpaint import MacPaint++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'macpaint_garden.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++m = MacPaint(seed=7, title='untitled')+W, H = m.W, m.H # 554 x 246 document pixels+m.use('pencil', 'black', 1)+m.cursor('arrow', 300, 120)+m.stage('blank')++# ---- 1. window frame, sill and rod with the rectangle tool --------------------------------------------------+WX0, WY0, WX1, WY1 = 92, 16, 412, 172 # window opening (outer frame)+GX0, GY0, GX1, GY1 = WX0 + 7, WY0 + 7, WX1 - 7, WY1 # glass+MX, MY = (WX0 + WX1) // 2, 94 # mullion / transom centres+SILL_T, SILL_F, SILL_B = 168, 175, 186 # sill top surface, front face, bottom+m.rect(WX0, WY0, WX1, WY1 + 2, fill='white', line=1)+m.rect(GX0 - 1, GY0 - 1, GX1 + 1, GY1 + 1, fill='white', line=1)+m.use('rect', 'white', 1)+m.cursor('cross', GX1, GY0)+m.stage('frame')++# ---- 2. sky: bands of patterns, a sun with rays, clouds, two birds ---------------------------------------+glass = m.mask_rect(GX0, GY0, GX1, GY1)+m.bands(glass, ['mist', 'faint', 'white'], GY0, GY0 + 84, seed=3)+sx, sy = 140, 50+m.oval(sx, sy, 14, 14, fill='white', line=2)+for k in range(12):+ a = k * np.pi / 6 + 0.13+ r1 = 29 if k % 2 == 0 else 24+ m.line((sx + 18 * np.cos(a), sy + 18 * np.sin(a)), (sx + r1 * np.cos(a), sy + r1 * np.sin(a)), 2)+++def cloud(cx, cy, s=1.0):+ blobs = [(-22, 4, 14, 9), (-8, -4, 15, 12), (10, -2, 14, 11), (24, 4, 12, 8), (0, 6, 26, 8)]+ mask = np.zeros((H, W), np.uint8)+ for dx, dy, rx, ry in blobs:+ mask |= m.mask_oval(cx + dx * s, cy + dy * s, rx * s, ry * s)+ mask &= glass+ m.paint(mask, 'white')+ m.paint(m.border(mask, 1) & (m.YY < GY1 - 1) & (m.XX > GX0) & (m.XX < GX1 - 1), 'black')+ return mask+++c1 = cloud(214, 46, 1.0)+c2 = cloud(281, 34, 0.7)+c3 = cloud(388, 30, 0.55)+for bx, by in [(186, 70), (200, 64)]:+ m.pencil([(bx - 5, by - 2), (bx - 2, by), (bx, by + 1), (bx + 2, by), (bx + 5, by - 3)])+m.use('bucket', 'mist', 1)+m.cursor('bucket', 120, 30)+m.stage('sky')++# ---- 3. outside: hills with a few distant houses, a meadow -----------------------------------------------+HZ = 118 # horizon line+hill = m.mask_poly([(GX0, HZ + 6), (130, HZ - 4), (170, HZ - 10), (215, HZ - 2), (250, HZ - 6), (300, HZ - 16),+ (350, HZ - 8), (390, HZ - 12), (GX1, HZ - 6), (GX1, GY1), (GX0, GY1)], smooth=True) & glass+m.paint(hill, 'light')+m.paint(m.border(hill, 1) & (m.YY < HZ + 14) & (m.XX > GX0) & (m.XX < GX1 - 1), 'black')+meadow = m.mask_poly([(GX0, HZ + 18), (200, HZ + 12), (300, HZ + 16), (GX1, HZ + 10), (GX1, GY1), (GX0, GY1)], smooth=True) & glass+m.paint(meadow, 'dots')+m.paint(m.border(meadow, 1) & (m.YY < HZ + 24) & (m.XX > GX0) & (m.XX < GX1 - 1), 'black')+++def house(x, y, w, h, roof_h, chimney=None):+ body = m.mask_rect(x, y, x + w, y + h) & glass+ m.paint(body, 'white'); m.paint(m.border(body, 1), 'black')+ rf = m.mask_poly([(x - 3, y + 1), (x + w // 2, y - roof_h), (x + w + 3, y + 1)]) & glass+ m.paint(rf, 'shingles'); m.paint(m.border(rf, 1), 'black')+ if chimney:+ cx = x + int(w * chimney)+ m.rect(cx, y - roof_h + 1, cx + 4, y - roof_h + 8, fill='black', line=1)+ m.spray([(cx + 2, y - roof_h - 2), (cx + 6, y - roof_h - 10), (cx + 1, y - roof_h - 18), (cx + 8, y - roof_h - 26)],+ radius=3, density=0.3, seed=11)+ for wx in range(x + 4, x + w - 5, 9):+ m.rect(wx, y + 4, wx + 4, y + 9, fill='black', line=0)+++house(118, HZ - 8, 22, 14, 10, chimney=0.7)+house(150, HZ - 10, 18, 12, 8)+house(352, HZ - 16, 26, 14, 11, chimney=0.25)+m.use('ffree', 'shingles', 1)+m.cursor('cross', 210, 128)+m.stage('town')++# ---- 4. the room: mullions, wallpaper, gingham curtains on a rod, the sill ------------------------------------+m.rect(MX - 3, GY0, MX + 3, GY1, fill='white', line=1)+m.rect(GX0, MY - 3, GX1, MY + 3, fill='white', line=1)+for gx, gy in [(GX0 + 10, GY0 + 22), (MX + 10, MY + 12)]: # glass glints+ m.line((gx, gy), (gx + 9, gy - 9), 1); m.line((gx + 4, gy + 1), (gx + 11, gy - 6), 1)+wall = 1 - m.mask_rect(WX0, WY0, WX1, WY1 + 2)+m.paint(wall, 'sprigs')+m.rect(WX0, WY0, WX1, WY1 + 2, fill=None, line=1)+++CURTAIN = 'gingham'+++def curtain(xo=64, xi=126, tie_y=108):+ """the left curtain: gingham freeform hanging from the rod (outer edge xo, inner edge xi), folds, a tie-back"""+ pts = [(xo, 9), (xi, 9), (xi - 6, 40), (xi - 18, 80), (xo + 34, 106), (xo + 30, 120),+ (xo + 36, 150), (xo + 44, 168), (xo + 4, 168), (xo, 120), (xo - 1, 60)]+ msk = m.shape(pts, fill=CURTAIN, line=1)+ for xx in [xo + 10, xo + 20]: # folds+ m.pencil([(xx, 12), (xx + 4, 60), (xx + 9, tie_y - 2)], smooth=True)+ m.pencil([(xx + 9, tie_y + 6), (xx + 10, 140), (xx + 14, 166)], smooth=True)+ tie = m.mask_rect(xo - 2, tie_y - 3, xo + 42, tie_y + 4, radius=3)+ m.paint(tie & m.pen(msk, 3), 'black')+ return msk+++cl = curtain()+m.copy((56, 4, 136, SILL_T + 1), to=(2 * 252 - 136 + 1, 4), flip=True, mask=m.pen(cl, 5)) # right one: copy, Flip Horizontal+m.rect(52, 4, 452, 8, fill='black', line=0) # rod+m.oval(52, 6, 5, 5, fill='black', line=0); m.oval(452, 6, 5, 5, fill='black', line=0)+for x in range(66, 128, 10): m.oval(x, 9, 3, 3, fill='white', line=1) # rings+for x in range(380, 442, 10): m.oval(x, 9, 3, 3, fill='white', line=1)+# sill: lit top, wood front, dark underside+m.rect(10, SILL_T, W - 10, SILL_F + 1, fill='lighter', line=1)+m.rect(6, SILL_F, W - 6, SILL_B, fill='wood', line=1)+m.rect(16, SILL_B - 1, W - 16, SILL_B + 3, fill='gray', line=1)+m.use('bucket', 'gingham', 1)+m.cursor('bucket', 80, 70)+m.stage('room')+++# ---- 5. three pots: day 2, day 14, day 40 ----------------------------------------------------------------+def pot(cx, top_w, bot_w, h, rim_h=6):+ y1 = SILL_T + 3+ y0 = y1 - h+ m.oval(cx + bot_w // 2 + 2, y1 - 1, bot_w // 2 + 2, 2, fill='gray', line=0) # cast shadow on the sill+ body = m.mask_poly([(cx - top_w // 2 + 2, y0 + rim_h), (cx + top_w // 2 - 2, y0 + rim_h),+ (cx + bot_w // 2, y1), (cx - bot_w // 2, y1)])+ m.paint(body, 'gray')+ shade = body & (m.XX > cx + top_w // 6)+ m.paint(shade, 'dark')+ m.paint(m.border(body, 1), 'black')+ m.rect(cx - top_w // 2, y0, cx + top_w // 2 + 1, y0 + rim_h + 1, fill='lighter', line=1)+ m.rect(cx + top_w // 4, y0 + 1, cx + top_w // 2, y0 + rim_h, fill='light', line=0)+ m.oval(cx, y0 + 1, top_w // 2 - 2, 2, fill='black', line=0) # soil+ return y0+++def leaf(base, tip, width, fill='black', vein=True):+ b, t = np.array(base, float), np.array(tip, float)+ d = t - b; n = np.array([-d[1], d[0]]) / (np.linalg.norm(d) + 1e-6)+ pts = [b, b + d * 0.3 + n * width, b + d * 0.7 + n * width * 0.8, t, b + d * 0.7 - n * width * 0.8, b + d * 0.3 - n * width]+ m.shape(pts, fill=fill, line=1)+ if vein: m.pencil([b + d * 0.12, b + d * 0.5 + n * 0.6, t - d * 0.12], pat='white' if fill == 'black' else 'black')+++P1, P2, P3 = 172, 227, 330+top1 = pot(P1, 30, 22, 24)+m.brush([(P1, top1), (P1 - 1, top1 - 8), (P1 + 1, top1 - 15)], size=2, shape='square')+leaf((P1 + 1, top1 - 15), (P1 - 12, top1 - 22), 4)+leaf((P1 + 1, top1 - 15), (P1 + 13, top1 - 21), 4)+m.oval(P1 + 14, top1 - 22, 3, 2, fill='light', line=1) # seed husk on a leaf++top2 = pot(P2, 34, 26, 28)+m.brush([(P2, top2), (P2 + 2, top2 - 20), (P2 - 1, top2 - 40), (P2 + 1, top2 - 56)], size=2, shape='square')+for (bx, by), (tx, ty) in [((P2 + 1, top2 - 12), (P2 - 18, top2 - 20)), ((P2 + 2, top2 - 22), (P2 + 21, top2 - 31)),+ ((P2, top2 - 36), (P2 - 17, top2 - 47)), ((P2, top2 - 46), (P2 + 15, top2 - 58)),+ ((P2 + 1, top2 - 56), (P2 - 7, top2 - 66))]:+ leaf((bx, by), (tx, ty), 5, fill='gray')++top3 = pot(P3, 42, 30, 34)+FX, FY = P3 - 6, 54 # flower head+m.brush([(P3, top3), (P3 + 3, top3 - 30), (P3 - 1, top3 - 60), (FX + 2, FY + 18)], size=3, shape='square')+for (bx, by), (tx, ty), wd in [((P3 + 1, top3 - 10), (P3 - 26, top3 - 22), 9), ((P3 + 2, top3 - 26), (P3 + 30, top3 - 40), 9),+ ((P3, top3 - 48), (P3 - 24, top3 - 64), 8), ((P3, top3 - 64), (P3 + 22, top3 - 78), 7)]:+ leaf((bx, by), (tx, ty), wd, fill='black')+for k in range(16): # petals+ a = k * 2 * np.pi / 16 + 0.1+ base = (FX + 10 * np.cos(a), FY + 10 * np.sin(a) * 0.95)+ tip = (FX + 25 * np.cos(a), FY + 24 * np.sin(a) * 0.95)+ leaf(base, tip, 4.2, fill='white', vein=False)+m.oval(FX, FY, 12, 12, fill='black', line=1)+m.oval(FX, FY, 9, 9, fill='pebbles', line=1)+m.use('frrect', 'gray', 2)+m.cursor('brush', P2 + 1, top2 - 56)+m.stage('pots')++# ---- 6. the watering can, still dripping into the day-2 pot; the seed packet it all came from ------------------+A, CB = 108, SILL_T + 2 # can: left edge, base+m.brush([(A + 2, 144), (A - 8, 148), (A - 9, 159), (A - 4, 166), (A + 2, 166)], size=3, shape='round') # back handle+m.brush([(A + 6, 138), (A + 11, 127), (A + 24, 125), (A + 31, 131), (A + 32, 138)], size=3, shape='round') # top handle+s0, s1 = np.array([A + 33.0, 161.0]), np.array([P1 - 15.0, top1 - 4.0]) # spout centre line, tip at the rim+d = (s1 - s0) / np.linalg.norm(s1 - s0); n = np.array([-d[1], d[0]])+m.shape([s0 + n * 4, s1 + n * 2, s1 - n * 2, s0 - n * 4], fill='white', line=1, smooth=False)+can = m.rect(A, 136, A + 35, CB, fill='white', line=2, radius=3)+for xa, xb, pat in [(A + 2, A + 6, 'light'), (A + 25, A + 29, 'light'), (A + 29, A + 33, 'gray')]: # cylinder bands+ m.paint(can & (m.XX >= xa) & (m.XX < xb) & (m.YY > 137) & (m.YY < CB - 2), pat)+m.paint(m.border(can, 2), 'black')+m.rect(A, 142, A + 35, 145, fill='black', line=0) # hoops+m.rect(A, CB - 7, A + 35, CB - 4, fill='black', line=0)+rc = s1 + d * 2 # the rose, face-on to the spout+t = np.linspace(0, 2 * np.pi, 24, endpoint=False)+m.shape([rc + n * 8 * np.cos(a) + d * 3 * np.sin(a) for a in t], fill='white', line=1, smooth=False)+for k in (-5, -2, 1, 4):+ m.line(rc + n * k + d, rc + n * k + d, 1)+for (dx, dy) in [(P1 - 7, top1 - 3)]: # a drip falling into the pot+ m.shape([(dx, dy - 5), (dx + 2, dy), (dx + 1, dy + 2), (dx - 1, dy + 2), (dx - 2, dy)], fill='black', line=0, smooth=False)+# seed packet with a crimped top, a flower on the front and a few spilled seeds+pk = m.shape([(16, 128), (20, 124), (24, 128), (28, 124), (32, 128), (36, 124), (40, 128), (44, 124), (48, 128), (52, 124),+ (56, 128), (58, CB), (14, CB)], fill='white', line=1, smooth=False)+m.line((16, 131), (56, 131), 1)+for k in range(8):+ a = k * np.pi / 4+ m.oval(36 + 7 * np.cos(a), 143 + 7 * np.sin(a), 3, 3, fill='white', line=1)+m.oval(36, 143, 4, 4, fill='black', line=0)+m.text('seeds', 36, 164, anchor='m')+for sx_, sy_ in [(63, CB - 1), (68, CB), (72, CB - 1)]:+ m.oval(sx_, sy_, 2, 1, fill='black', line=0)+m.use('frrect', 'white', 2)+m.cursor('cross', A + 35, CB)+m.stage('can')++# ---- 7. the cat on the sill, and the butterfly it is watching --------------------------------------------+KX = 8 # the cat sits clear of the curtain+++def K(*pts):+ """cat coordinates -> document (the cat was laid out with its front paw at x = 455)"""+ return [(x + KX, y) for x, y in pts]+++cat = np.zeros((H, W), np.uint8)+cat |= m.mask_oval(497 + KX, 150, 23, 21) & (m.YY <= SILL_T + 2) # haunch+th = np.linspace(0, 2 * np.pi, 40, endpoint=False)+cat |= m.mask_poly(K(*[(477 + 17 * np.cos(a) * 0.94 - 26 * np.sin(a) * 0.34, 133 + 17 * np.cos(a) * 0.34 + 26 * np.sin(a) * 0.94)+ for a in th])) # chest, leaning forward+cat |= m.mask_poly(K((453, 136), (465, 138), (464, SILL_T + 2), (452, SILL_T + 2))) # front leg+cat |= m.mask_oval(455 + KX, SILL_T + 1, 7, 3) # paw+cat |= m.mask_poly(K((458, 104), (478, 98), (486, 116), (462, 122))) # neck+cat |= m.mask_oval(463 + KX, 96, 14, 12) # head+cat |= m.mask_oval(452 + KX, 101, 7, 6) # muzzle+cat |= m.mask_poly(K((451, 90), (455, 72), (464, 87))) # near ear+cat |= m.mask_poly(K((466, 86), (475, 72), (478, 92))) # far ear+m.paint(cat, 'black')+m.brush(K((516, 166), (528, 170), (532, 182), (529, 197), (521, 204), (516, 198)), size=5, shape='round') # tail+m.pencil(K((455, 86), (456, 79), (459, 84)), pat='white') # inner ear+m.pencil(K((464, 140), (464, SILL_T)), pat='white') # leg against chest+m.pencil(K((471, SILL_T), (472, 152), (480, 139), (495, 132)), smooth=True, pat='white') # haunch+m.brush(K((458, 113), (478, 107)), size=3, shape='square', pat='white') # collar+m.oval(460 + KX, 118, 3, 3, fill='white', line=1) # bell+m.shape(K((453, 94), (457, 91), (462, 92), (459, 96)), fill='white', line=0, smooth=False) # eye, looking up-left+m.line((455 + KX, 92), (455 + KX, 94), 1)+for wy in (97, 101, 105): # whiskers (XOR)+ m.pencil(K((452, 102), (440, wy)), mode='invert')++# butterfly, out in the sky between the flower and the cat: a white with black wing tips+BX, BY = 371, 74+bfly = np.zeros((H, W), np.uint8)+for s in (-1, 1):+ bfly |= m.shape([(BX, BY + 1), (BX + s * 10, BY + 1), (BX + s * 13, BY + 7), (BX + s * 9, BY + 13), (BX + s * 2, BY + 8)],+ fill='white', line=1, smooth=False)+ up = m.shape([(BX, BY - 1), (BX + s * 4, BY - 12), (BX + s * 12, BY - 17), (BX + s * 19, BY - 14), (BX + s * 17, BY - 4),+ (BX + s * 3, BY + 1)], fill='white', line=1, smooth=False)+ bfly |= up+ m.paint(up & (m.mask_oval(BX + s * 17, BY - 15, 7, 6)), 'black') # black tip+ m.oval(BX + s * 9, BY - 6, 2, 2, fill='black', line=0) # spot+ m.oval(BX + s * 7, BY + 6, 1, 1, fill='black', line=0)+ bfly |= m.pencil([(BX, BY - 6), (BX + s * 3, BY - 13), (BX + s * 6, BY - 17), (BX + s * 8, BY - 16)], smooth=True)+bfly |= m.rect(BX - 1, BY - 6, BX + 2, BY + 9, fill='black', line=0)+m.dotted([(FX + 27, FY - 2), (FX + 33, FY - 14), (FX + 42, FY - 14), (FX + 42, FY - 4), (FX + 35, FY - 4),+ (FX + 36, FY + 6), (BX - 16, BY + 8)], gap=5, size=2)+m.zoom(449 + KX, 83, 18, 15, at=(70, 48), fat=6, title='zoom') # fat bits round the eye+m.use('pencil', 'black', 1)+m.cursor('pencil', 455 + KX, 94)+m.stage('cat')+m.zoom(None)++# ---- 8. spray can: the shadow under the sill and the cat's shadow on the wall -------------------------+under = m.mask_rect(0, SILL_B + 4, W, SILL_B + 14)+m.spray([(12, SILL_B + 3), (W - 12, SILL_B + 3)], radius=8, density=0.22, clip=under, seed=5)+behind = (1 - m.pen(cat, 3)) & (m.YY < SILL_T + 3) & (m.XX > 470) # the cat's soft shadow on the wall+m.spray([(500 + KX, 104), (522 + KX, 124), (533 + KX, 150), (535 + KX, 168)], radius=6, density=0.3, clip=behind, seed=9)+m.use('spray', 'black', 1)+m.cursor('spray', 300, SILL_B + 10)+m.stage('spray')++# ---- 9. labels: tags and arrows under the sill; a calendar with the days crossed off -------------------------+TAGS = [36, P1 - 10, P2 + 10, P3] # tag centres (under their pots)+for cx, label in zip(TAGS, ['day 0', 'day 2', 'day 14', 'day 40']):+ tw = len(label) * 7+ m.rect(cx - tw // 2 - 6, 202, cx + tw // 2 + 6, 220, fill='white', line=1, radius=4)+ m.text(label, cx, 215, anchor='m')+for xa, xb in [(TAGS[0] + 26, TAGS[1] - 26), (TAGS[1] + 26, TAGS[2] - 29), (TAGS[2] + 29, TAGS[3] - 29)]:+ m.rect(xa - 2, 207, xb + 2, 216, fill='white', line=0)+ m.line((xa, 211), (xb - 4, 211), 2)+ m.shape([(xb - 6, 206), (xb, 211), (xb - 6, 216)], fill='black', line=0, smooth=False)+CX0, CY0 = 3, 22+m.rect(CX0, CY0, CX0 + 59, CY0 + 52, fill='white', line=1)+m.rect(CX0, CY0, CX0 + 59, CY0 + 10, fill='black', line=0)+for rx in (CX0 + 12, CX0 + 45): m.rect(rx, CY0 - 4, rx + 3, CY0 + 3, fill='white', line=1)+for i in range(35):+ r, c = divmod(i, 7)+ x, y = CX0 + 2 + c * 8, CY0 + 13 + r * 8+ if i < 33:+ m.line((x + 1, y + 1), (x + 5, y + 5), 1); m.line((x + 5, y + 1), (x + 1, y + 5), 1)+ elif i == 33:+ m.oval(x + 3, y + 3, 5, 4, fill=None, line=1)+m.use('text', 'black', 1)+m.menu('Type', ['Plain', 'Bold', 'Italic', 'Underline', 'Outline', 'Shadow'], checked={'Plain'}, hilite='Shadow', styled=True)+m.cursor('arrow', 262, 66)+m.stage('type')++# ---- final: shadow-style title, marquee round the butterfly, saved ---------------------------------------------+m.menu(None)+m.text('watch it grow!', 444, 238, size=19, font='serif', style=('bold', 'shadow'), anchor='m', opaque=True)+m.select(rect=(BX - 23, BY - 22, BX + 23, BY + 17)) # marquee round the butterfly+m.use('marquee', 'black', 1)+m.cursor('arrow', BX + 17, BY + 12)+m.retitle('sill garden')++img = m.save(out, stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/rubberhose_morning.jpg b/examples/rubberhose_morning.jpgnew file mode 100644index 0000000..daf10abBinary files /dev/null and b/examples/rubberhose_morning.jpg differdiff --git a/examples/rubberhose_morning.py b/examples/rubberhose_morning.pynew file mode 100644index 0000000..d9fff4e--- /dev/null+++ b/examples/rubberhose_morning.py@@ -0,0 +1,91 @@+"""Example (1930s black-and-white rubber-hose cartoon): Seven O'Clock / 早晨的闹钟 — a frame from an old cartoon+short, printed on worn film. Seven o'clock in a little bedroom: the twin-bell alarm clock has leapt up on the+nightstand to ring, one shoe on tiptoe and one kicked out, waving a white glove and pointing at the bed; the+striker smears between the bells and "RRRING!" bounces overhead. In the bed a pillow in a striped night-cap snores+on and holds up a glove -- five more minutes. The sun, yawning, stretches its arms over the hills outside the+window, and a pair of slippers on the braided rug is already dancing. Grey gouache background, inked and painted+cels, pie-cut eyes, rubber-hose limbs; then lens softness, grain, gate weave, a rounded gate, scratches, dust and+a hair in the gate. No image model.+python3 rubberhose_morning.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 rubberhose import RubberHose, ellipse_pts, WHITE, LIGHT, BLACK++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'rubberhose_morning.png'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None++rh = RubberHose(1920, 1080, seed=11)++# ---- background: painted once on board, in grey gouache+FLOOR = 720+rh.wall(FLOOR)+rh.floor(FLOOR)+win = rh.window(120, 110, 600, 590, valley=372, horizon=528)+rh.valance(84, 636, 92, 146)+rh.curtain(66, 236, 104, 660, 404, 'left')+rh.curtain(484, 654, 104, 660, 404, 'right')+beam = [(178, 736), (566, 736), (742, 1080), (40, 1080)] # the sunbeam through the window+rh.light(beam, 0.45, 9)+rh.light([(170, 812), (600, 812), (612, 834), (160, 834)], -0.2, 4) # shadow of the sash rail across it+rh.rug(420, 960, 300, 70)+stand_top = rh.nightstand(770, 1090, 640, 830, 862)+bed = rh.bed(1300, 1820, 330, 600, 860, 940)+rh.sampler(1450, 140, 1680, 278, ['RISE &', 'SHINE'])+rh.stage('layout', view='layout')+rh.stage('background', view='background')++# ---- the actors, roughed out in pencil (back to front)+rh.sun(372, 482, 78, clip='window',+ arms=[dict(side=-1, at=(282, 372), bend=-30, pose='fist'), dict(side=1, at=(466, 366), bend=30, pose='fist')])++rh.pillow(1556, 592, 320, 146, tilt=0.0, clip='bed',+ arm=dict(at=(1392, 528), bend=-26, pose='palm', angle=-2.1, flip=-1))++clock = rh.alarm_clock(+ 935, 412, 125, tilt=0.1, look=(0.75, -0.15), time=(7, 0),+ legs=[dict(side=1, at=(990, 590), bend=-18, facing=1, tilt=0.55),+ dict(side=-1, at=(735, 560), bend=34, facing=-1, tilt=-0.35)],+ arms=[dict(side=-1, at=(706, 262), bend=-40, pose='open', angle=-2.3),+ dict(side=1, at=(1176, 372), bend=-26, pose='point', angle=0.05)])++rh.slipper(318, 908, 118, facing=1, tilt=-0.22)+rh.slipper(500, 978, 118, facing=1, tilt=0.06)+rh.stage('pencil')+rh.ink()+rh.stage('ink')+rh.paint()+rh.stage('paint')++# ---- effects: shake, ring, snore, hop+for bc, a in rh.bells:+ out_ang = -np.pi / 2 + a + 0.1+ rh.vibration(bc[0], bc[1], 125 * 0.42, out_ang - 0.55, out_ang + 0.55, n=3, gap=15)+for sgn in (-1, 1):+ p = clock.p(1.18 * sgn, 0.42)+ for k in range(2):+ rh.stroke([(p[0] + sgn * 12 * k, p[1] - 22 + 10 * k), (p[0] + sgn * (12 * k + 16), p[1] + 6 + 10 * k)], 5,+ (0.3, 0.3), effect=True)+rh.star(790, 236, 17, rot=0.2)+rh.star(1088, 226, 14, rot=-0.3)+rh.star(1040, 160, 9, rot=0.5)+rh.lettering('RRRING!', [(690, 150), (935, 92), (1185, 140)], 86)+rh.zzz(1735, 470, 30)+for a in (-0.9, -0.35, 0.2): # tap, tap on the tabletop+ rh.stroke([(1062 + 30 * np.cos(a), 650 + 30 * np.sin(a)), (1062 + 54 * np.cos(a), 650 + 54 * np.sin(a))], 4.5,+ (0.2, 0.5), effect=True)+for k in range(2): # the hop+ rh.stroke([(276 - 8 * k, 968 + 14 * k), (318, 978 + 16 * k), (362 + 8 * k, 968 + 14 * k)], 4.5, (0.35, 0.35),+ effect=True)+rh.shadow(955, 632, 110, 8, 0.5)+rh.shadow(320, 984, 54, 8, 0.4)+rh.shadow(504, 1000, 62, 9, 0.5)+rh.stage('effects')++# ---- shot on black-and-white film, then a hundred runs through the projector+rh.film()+rh.stage('film')+rh.age()+rh.save(out, stages_dir=stages)+print('saved', out)diff --git a/examples/storybook_acorn.jpg b/examples/storybook_acorn.jpgnew file mode 100644index 0000000..4132a62Binary files /dev/null and b/examples/storybook_acorn.jpg differdiff --git a/examples/storybook_acorn.py b/examples/storybook_acorn.pynew file mode 100644index 0000000..461fabd--- /dev/null+++ b/examples/storybook_acorn.py@@ -0,0 +1,367 @@+"""Example (picture-book character animation / 绘本角色动画): 小橡果的秋天 · An Acorn's Autumn.+A sleepy acorn hangs from an oak branch, wakes as the twig snaps, falls (stretch), lands (squash, impact lines,+dust), bounces, blinks and watches a red oak leaf drift away towards the stream. It gathers itself (anticipation:+squash and lean back), rolls down the hillside -- the hill, its ink horizon, flowers, grass and the far hills are+drawn in just as it passes --, leaps onto the leaf that has landed on the water, floats across while the sun and+clouds are painted in, bumps the far bank, somersaults ashore, wiggles itself into the soil and sprouts into a little+oak that still wears its cap. Then "hello, little oak" writes itself in the sky and confetti flies.+The JPG is the journey poster: the whole world, the acorn multiply-exposed at six key poses on a pencil motion arc.+python3 storybook_acorn.py [out.jpg] [--stages DIR] [--gif out.gif]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from core import spline+from storybook import Storybook, oak_leaf, MINT, LAVENDER, GRASS++argv = sys.argv[1:]+out = argv[0] if argv and not argv[0].startswith('--') else 'storybook_acorn.jpg'+stages = argv[argv.index('--stages') + 1] if '--stages' in argv else None+gif = argv[argv.index('--gif') + 1] if '--gif' in argv else None+t_start = time.time()++U = 44 # half-width of the nut, design px+LEFT = [(-40, 604), (140, 598), (330, 594), (480, 592), (575, 598), (660, 620), (750, 660), (840, 716), (915, 774),+ (968, 822), (994, 846)]+LEFT_EDGE = [(1004, 880), (994, 950), (1006, 1020), (998, 1120)]+RIGHT = [(1440, 850), (1490, 823), (1560, 801), (1650, 789), (1760, 791), (1860, 798), (1960, 806)]+RIGHT_EDGE = [(1432, 900), (1444, 980), (1434, 1060), (1442, 1120)]+WATER_Y = 846+LQ, RQ = spline(np.array(LEFT, np.float32), 16), spline(np.array(RIGHT, np.float32), 16)+gy = lambda x: float(np.interp(x, LQ[:, 0], LQ[:, 1])) if x < 1200 else float(np.interp(x, RQ[:, 0], RQ[:, 1]))+slope = lambda x: (gy(x + 2) - gy(x - 2)) / 4++PIVOT = (468, 262) # where the acorn's stem hangs from the twig+X0 = 461 # where it lands+SPOT = 1650 # where it plants itself+STEM = [(1650, 776), (1640, 728), (1656, 672), (1665, 612)]++T_POP, T_SNAP, T_FALL, T_HIT, T_UP, T_HIT2, T_SET = 0.28, 0.58, 0.78, 1.16, 1.28, 1.62, 1.70+T_LOOK, T_ANT, T_ROLL, T_JUMP, T_LEAF, T_FLOAT = 1.90, 2.96, 3.30, 4.46, 4.84, 5.06+T_BUMP, T_HOP, T_LAND, T_DIG, T_GONE, T_SPROUT, T_WRITE, T_END = 6.40, 6.62, 7.00, 7.24, 7.94, 8.00, 8.70, 9.95+LEAF_T0, LEAF_T1, LEAF_X0, LEAF_X1 = 1.90, 4.22, 1150, 1352+++def leaf_pose(t):+ """the red oak leaf: drifts down from the oak in swinging arcs, lands on the stream, gets ridden across"""+ if t < LEAF_T0: return None+ if t < LEAF_T1:+ u = (t - LEAF_T0) / (LEAF_T1 - LEAF_T0)+ ph = 2 * np.pi * 2.3 * u+ x = 418 + (LEAF_X0 - 418) * (u ** 1.15) + 80 * np.sin(ph) * (1 - u)+ y = 300 + (WATER_Y - 4 - 300) * u - 16 * np.abs(np.sin(ph)) * (1 - u)+ land = Storybook.ease((u - 0.86) / 0.14, 'out') if u > 0.86 else 0.0+ rot = 32 * np.cos(ph) * (1 - land)+ sx = (0.55 + 0.45 * abs(np.cos(ph * 0.5 + 0.6))) * (1 - land) + land+ sy = 0.8 * (1 - land) + 0.5 * land+ return dict(x=x, y=y, rot=rot, sx=sx, sy=sy)+ bob = 3.0 * np.sin(2 * np.pi * 1.1 * (t - LEAF_T1))+ rot = 2.2 * np.sin(2 * np.pi * 0.85 * (t - LEAF_T1) + 0.4)+ x = LEAF_X0+ if t >= T_FLOAT:+ u = min(1.0, (t - T_FLOAT) / (T_BUMP - T_FLOAT))+ x = LEAF_X0 + (LEAF_X1 - LEAF_X0) * Storybook.ease(u, 'sine')+ if t >= T_BUMP:+ x = LEAF_X1 - 7 * max(0.0, np.sin(np.pi * min(1, (t - T_BUMP) / 0.35)))+ dip = 0.0+ if T_LEAF <= t: dip += 9 * Storybook.spring((t - T_LEAF) / 0.6, 1.3, 3.2)+ if T_HOP <= t: dip += 7 * Storybook.spring((t - T_HOP) / 0.6, 1.3, 3.2)+ return dict(x=x, y=WATER_Y - 4 + bob + dip, rot=rot, sx=1.0, sy=0.5, ghost=T_LEAF <= t <= T_BUMP)+++def on_leaf(t):+ p = leaf_pose(t)+ return p['x'] + 4, p['y'] - 9+++def shadow_at(x, gyv, height):+ h = np.clip(height / 220, 0, 1)+ return (x, gyv + 2, U * (1.05 - 0.45 * h), 0.24 * (1 - 0.8 * h))+++def build(W, H, seed=21):+ sb = Storybook(W, H, seed=seed, actor_size=U)+ E = sb.ease++ # ---------------------------------------------------------------- choreography+ def hang(u, t):+ sc = E((t - T_POP) / 0.25, 'back') if t < T_POP + 0.25 else 1.0+ if t < T_POP: return None+ rot = 6 * np.sin(2 * np.pi * 0.8 * (t - T_POP))+ if t > T_SNAP:+ rot += 13 * np.sin(2 * np.pi * 6 * (t - T_SNAP)) * min(1, (t - T_SNAP) / 0.08)+ x, y = sb.anchor(*PIVOT, rot=rot, scale=sc)+ return dict(x=x, y=y, rot=rot, scale=sc, eyes=0, lid='sleep', mouth='smile', lead=False)++ hx, hy = sb.anchor(*PIVOT)+ yg_end = sb.rest(X0, gy(X0), k=1.36)[1]++ def fall(u, t):+ y = hy + (yg_end - hy) * u * u+ k = 1 + 0.36 * u ** 1.5+ x = hx + (X0 - hx) * u+ o = 0.0 if u < 0.12 else 1.0+ return dict(x=x, y=y, k=k, eyes=o, lid='sleep', mouth='o' if u > 0.12 else 'smile', brow='up' if u > 0.12 else None,+ look=(0, 0.6), shadow=shadow_at(X0, gy(X0), yg_end - y), lead=False, speed=False)++ def hit(u, t):+ k = 0.62 + (1.12 - 0.62) * E(u, 'out') if u > 0.45 else 0.62+ x, y = sb.rest(X0, gy(X0), k=k)+ return dict(x=x, y=y, k=k, eyes=0.1, lid='blink', mouth='o', shadow=shadow_at(X0, gy(X0), 0), lead=False,+ speed=False)++ def bounce(u, t):+ k = 1 + 0.14 * abs(1 - 2 * u) ** 2+ x, y0 = sb.rest(X0, gy(X0), k=k)+ h = 72 * 4 * u * (1 - u)+ return dict(x=x, y=y0 - h, k=k, eyes=1, mouth='o', brow='up', look=(0, -0.3),+ shadow=shadow_at(X0, gy(X0), h), lead=False)++ def settle(u, t):+ k = 1 - 0.2 * Storybook.spring(u, 1.4, 4.0) if t < T_SET else 1 - 0.08 * Storybook.spring(u, 1.2, 3.0)+ x, y = sb.rest(X0, gy(X0), k=k)+ return dict(x=x, y=y, k=k, eyes=1 if u > 0.15 else 0.15, mouth='flat', shadow=shadow_at(X0, gy(X0), 0), lead=False)++ def look(u, t):+ x, y = sb.rest(X0, gy(X0))+ lp = leaf_pose(t)+ ex, ey = lp['x'] - x, lp['y'] - (y - 10)+ n = np.hypot(ex, ey) + 1e-6+ lk = (ex / n, ey / n)+ blink = 1.0+ for tb in (2.02, 2.62):+ if tb <= t < tb + 0.14: blink = abs(np.cos(np.pi * (t - tb) / 0.14))+ rot = -5 * lk[0]+ k = 1 + 0.03 * np.sin(2 * np.pi * 1.5 * (t - T_LOOK))+ x, y = sb.rest(X0, gy(X0), rot=rot, k=k)+ return dict(x=x, y=y, rot=rot, k=k, eyes=blink, look=lk, brow='up', mouth='flat' if t < 2.45 else 'o',+ shadow=shadow_at(X0, gy(X0), 0), lead=False)++ def anticipate(u, t):+ a = E(min(1, u / 0.62), 'out')+ k = 1 - 0.24 * a+ rot = 13 * a+ jit = 1.3 * np.sin(t * 90) if u > 0.62 else 0.0+ x, y = sb.rest(X0 - 10 * a + jit, gy(X0), rot=rot, k=k)+ return dict(x=x, y=y, rot=rot, k=k, eyes=0.85, look=(1, 0.15), brow='determined', mouth='flat',+ shadow=shadow_at(X0, gy(X0), 0), lead=False)++ XR0, XR1 = X0 - 10, 966++ def roll_at(u):+ f = 0.3 * u + 0.7 * u * u+ x = XR0 + (XR1 - XR0) * f+ m = slope(x)+ n = np.array([m, -1.0]); n /= np.linalg.norm(n)+ rot = 13 - (x - XR0) / U * 57.2958 * 0.7+ sp = (0.3 + 1.4 * u) / 1.7+ k = 1 + 0.12 * sp+ axis = -np.degrees(np.arctan(m))+ cx, cy = sb.rest(x, gy(x), rot=rot, k=k, axis=axis, normal=n)+ return cx, cy, rot, k, axis, x++ def roll(u, t):+ cx, cy, rot, k, axis, x = roll_at(u)+ return dict(x=cx, y=cy, rot=rot, k=k, axis=axis, eyes=1, mouth='grin', brow='up', look=(1, 0.2),+ shadow=shadow_at(x, gy(x), 0), speed_min=420)++ p0 = roll_at(1.0)+ rot0 = p0[2]+ rot_up = -360.0 * np.ceil(-rot0 / 360.0)+ land_leaf = sb.rest(*on_leaf(T_LEAF))++ def leap(u, t):+ x, y = Storybook.arc(p0[:2], land_leaf, 70, u)+ xa, ya = Storybook.arc(p0[:2], land_leaf, 70, max(0, u - 0.03))+ xb, yb = Storybook.arc(p0[:2], land_leaf, 70, min(1, u + 0.03))+ axis = np.degrees(np.arctan2(-(yb - ya), xb - xa))+ k = 1 + 0.2 * abs(1 - 2 * u) ** 1.5+ rot = rot0 + (rot_up - rot0) * E(u, 'out')+ return dict(x=x, y=y, rot=rot, k=k, axis=axis, eyes=1, mouth='grin', brow='up', look=(1, 0.5),+ speed_min=420)++ def ride(u, t):+ lp = leaf_pose(t)+ lp_lag = leaf_pose(t - 0.12)+ if t < T_FLOAT:+ uu = (t - T_LEAF) / (T_FLOAT - T_LEAF)+ k = 1 - 0.3 * Storybook.spring(uu, 1.1, 3.5)+ eyes, mouth = (0.1, 'grin') if uu < 0.35 else (1, 'smile')+ else:+ k = 1 + 0.025 * np.sin(2 * np.pi * 1.1 * (t - T_FLOAT))+ eyes, mouth = 1, 'smile'+ rot = (lp_lag['rot'] if lp_lag else 0) * 1.6+ blink = 1.0+ for tb in (5.55, 6.15):+ if tb <= t < tb + 0.14: blink = abs(np.cos(np.pi * (t - tb) / 0.14))+ x, y = sb.rest(*on_leaf(t), rot=rot, k=k)+ look = (0.55, -0.7) if t > 5.3 else (0.2, 0.3)+ return dict(x=x, y=y, rot=rot, k=k, eyes=eyes * blink, lid='happy', mouth=mouth, look=look, speed=False)++ def bump(u, t):+ if t < T_BUMP + 0.1:+ k = 1 - 0.15 * np.sin(np.pi * u * 2.2)+ rot = -6 * np.sin(np.pi * u * 2.2)+ else:+ a = E((t - T_BUMP - 0.1) / (T_HOP - T_BUMP - 0.1), 'out')+ k = 1 - 0.2 * a; rot = 8 * a+ x, y = sb.rest(*on_leaf(t), rot=rot, k=k)+ return dict(x=x, y=y, rot=rot, k=k, eyes=1, look=(1, -0.2), brow='determined', mouth='flat', speed=False)++ hop0 = sb.rest(*on_leaf(T_HOP), rot=8, k=0.8)+ hop1 = sb.rest(SPOT, gy(SPOT), k=1.2)++ def hop(u, t):+ x, y = Storybook.arc(hop0, hop1, 135, u)+ xa, ya = Storybook.arc(hop0, hop1, 135, max(0, u - 0.03))+ xb, yb = Storybook.arc(hop0, hop1, 135, min(1, u + 0.03))+ axis = np.degrees(np.arctan2(-(yb - ya), xb - xa))+ k = 1 + 0.22 * abs(1 - 2 * u) ** 1.5+ rot = 8 - 368 * E(u, 'inout')+ return dict(x=x, y=y, rot=rot, k=k, axis=axis, eyes=0.1 if 0.2 < u < 0.8 else 1, lid='happy', mouth='grin',+ brow='up', shadow=shadow_at(x, gy(x), gy(x) - y - U * 1.2), speed_min=500)++ def land(u, t):+ k = 1 - 0.34 * Storybook.spring(u, 1.2, 3.2)+ x, y = sb.rest(SPOT, gy(SPOT), k=k)+ return dict(x=x, y=y, k=k, eyes=0.1 if u < 0.25 else 1, lid='happy', mouth='grin' if u < 0.5 else 'smile',+ shadow=shadow_at(SPOT, gy(SPOT), 0), speed=False)++ def dig(u, t):+ tt = t - T_DIG+ if tt < 0.16:+ x, y = sb.rest(SPOT, gy(SPOT))+ return dict(x=x, y=y, eyes=1, look=(0, 1), mouth='smile', shadow=shadow_at(SPOT, gy(SPOT), 0), speed=False)+ v = (tt - 0.16) / (T_GONE - T_DIG - 0.16)+ rot = 15 * np.sin(2 * np.pi * 6.5 * (tt - 0.16)) * (1 - 0.4 * v)+ x, y = sb.rest(SPOT, gy(SPOT), rot=rot)+ return dict(x=x, y=y + 2.95 * U * E(v, 'in2'), rot=rot, eyes=0, lid='happy', mouth='smile',+ clip=gy(SPOT) + 3, speed=False)++ SQ = spline(np.array(STEM, np.float32), 16)+ seg = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(SQ, axis=0).T))])++ def stem_at(p):+ s_ = p * seg[-1]+ return float(np.interp(s_, seg, SQ[:, 0])), float(np.interp(s_, seg, SQ[:, 1]))++ def sprout(u, t):+ p = min(1.0, (t - T_SPROUT) / 0.55)+ tx, ty = stem_at(max(p, 0.02))+ rot = 14 + 9 * Storybook.spring(max(0, t - T_SPROUT - 0.5) / 0.8, 1.5, 3.0) * (t > T_SPROUT + 0.5)+ x, y = sb.anchor(tx, ty + 2, local=(0.0, -0.2), rot=rot, scale=0.62)+ return dict(x=x, y=y, rot=rot, scale=0.62, only='cap', clip=gy(SPOT) - 4 if p < 0.2 else None, speed=False)++ sb.act(0.0, T_FALL, hang)+ sb.act(T_FALL, T_HIT, fall)+ sb.act(T_HIT, T_UP, hit)+ sb.act(T_UP, T_HIT2, bounce)+ sb.act(T_HIT2, T_LOOK, settle)+ sb.act(T_LOOK, T_ANT, look)+ sb.act(T_ANT, T_ROLL, anticipate)+ sb.act(T_ROLL, T_JUMP, roll)+ sb.act(T_JUMP, T_LEAF, leap)+ sb.act(T_LEAF, T_BUMP, ride)+ sb.act(T_BUMP, T_HOP, bump)+ sb.act(T_HOP, T_LAND, hop)+ sb.act(T_LAND, T_DIG, land)+ sb.act(T_DIG, T_GONE, dig)+ sb.act(T_GONE, T_SPROUT, lambda u, t: None)+ sb.act(T_SPROUT, T_END, sprout)++ # ---------------------------------------------------------------- the world, painted in as it is reached+ LEAD = 150+ sb.hill([(-40, 492), (220, 466), (460, 494), (700, 472), (950, 514), (1200, 482), (1460, 510), (1720, 470),+ (1960, 494)], LAVENDER, bottom=760, z=2, follow=300, xa=-40, xb=1960, pre=(1.95, 2.85, 0.3))+ sb.hill([(-40, 560), (260, 544), (540, 574), (800, 626), (1040, 662), (1260, 652), (1480, 624), (1720, 612),+ (1960, 632)], MINT, bottom=1120, z=3, follow=360, xa=-40, xb=1960, pre=(1.95, 2.85, 0.3))+ sb.tree(226, 600, 250, [(160, 190, 125), (285, 150, 118), (368, 202, 76), (105, 290, 92), (250, 262, 108)],+ branch=[[(232, 372), (300, 332), (380, 292), (440, 262), (494, 243)], [(456, 252), (468, 264)],+ [(220, 430), (172, 392), (140, 350)]], when=(0.0, 0.55), z=7.0, trunk=15)+ sb.water(975, 1455, WATER_Y, when=(3.7, 5.3), z=8.5)+ sb.land(LEFT, GRASS, z=12, follow=60, xa=-40, xb=1000, pre=(1.95, 2.9, 0.58), right_edge=LEFT_EDGE, dashes=70)+ sb.ground(LEFT, z=20, follow=LEAD, xa=-40, xb=1000, pre=(0.05, 0.5, 0.6))+ sb.land(RIGHT, GRASS, z=12, follow=230, xa=1430, xb=1960, left_edge=RIGHT_EDGE, dashes=40)+ sb.ground(RIGHT, z=20, follow=300, xa=1430, xb=1960)+ sb.sun(1705, 205, 62, when=(5.2, 5.95))+ sb.cloud(705, 150, 190, when=(3.75, 4.1))+ sb.cloud(1452, 118, 250, when=(5.55, 5.95))+ sb.cloud(1080, 168, 150, when=(4.6, 4.95))+ # little things along the way (the plateau ones while the acorn looks around)+ sb.tuft(355, gy(355) + 2, when=(2.1, 2.35))+ sb.leaf_on_ground(300, gy(300) - 2, 24, '#d9603a', when=(2.25, 2.5))+ sb.tuft(120, gy(120) + 2, when=(2.35, 2.6))+ for x, kind in [(640, 'aster'), (795, 'daisy')]:+ w0 = sb.when_at(x, 40, 0.42)+ sb.flower(x, gy(x) + 2, 80 if kind == 'aster' else 66, kind, '#b48ae0' if kind == 'aster' else '#fdfbf6',+ when=w0, lean=0.06)+ for x in (585, 705, 880):+ sb.tuft(x, gy(x) + 2, when=sb.when_at(x, 50, 0.22))+ for x, c in [(560, '#d9603a'), (858, '#e89a3a')]:+ sb.leaf_on_ground(x, gy(x) - 2, 24, c, when=sb.when_at(x, 40, 0.25))+ sb.cattail(950, gy(950) + 2, 150, when=sb.when_at(900, 0, 0.45), lean=0.1)+ sb.cattail(1482, gy(1482) + 2, 175, when=(5.9, 6.4), lean=-0.06)+ sb.cattail(1515, gy(1515) + 2, 128, when=(6.05, 6.5), lean=0.05)+ sb.tuft(1575, gy(1575) + 2, when=(6.3, 6.5))+ sb.flower(1800, gy(1800) + 2, 74, 'aster', '#e8739b', when=(6.4, 6.85), lean=-0.05)+ sb.tuft(1888, gy(1888) + 2, when=(6.55, 6.8))+ sb.leaf_on_ground(1745, gy(1745) - 2, 24, '#d9603a', when=(6.6, 6.85))+ # the planting+ sb.mound(SPOT, gy(SPOT) + 3, 122, 30, when=(T_DIG + 0.1, T_DIG + 0.4), z=55)+ sb.ink(STEM, 5.2, '#2f5a3c', z=56, when=(T_SPROUT, T_SPROUT + 0.55), taper=(0.0, 0.08), tremor=0.3,+ name='sapling')+ for p, ang, ln in [(0.36, 162, 56), (0.52, 20, 62), (0.72, 152, 52), (0.88, 32, 46)]:+ bx, by = stem_at(p)+ lf, mid = oak_leaf(ln, ln * 0.5, 2, (bx, by), ang, curl=0.05, seed=int(p * 100))+ tl = T_SPROUT + p * 0.55+ sb.shape([lf], '#7cc36a', '#2c4a33', 2.2, z=56.5, when=(tl, tl + 0.28), pop=(bx, by), dark='#4f9a4c',+ name='sapling_leaf')+ # the leaf boat+ out_l, mid_l = oak_leaf(150, 64, 3, (-75, 0), 0, curl=0.04, seed=4)+ veins = [mid_l] + [[(mid_l[i][0], mid_l[i][1]), (mid_l[i][0] + 16, mid_l[i][1] + sgn * 20)]+ for i, sgn in [(25, -1), (40, 1), (55, -1), (68, 1)]]+ veins.append([(-75, 0), (-92, 4)])+ leaf_sp = sb.sprite([out_l], '#e0703a', '#2a1d16', 2.8, veins=veins, dark='#b8452a')+ sb.prop(leaf_sp, LEAF_T0, T_END, lambda u, t: leaf_pose(t), z=45)+ # FX+ sb.fx('impact', T_HIT, X0, gy(X0), r=62, n=7)+ sb.fx('dust', T_HIT, X0, gy(X0), n=6, spread=60)+ sb.fx('dust', T_HIT2, X0, gy(X0), n=4, spread=34, size=8)+ for tt in (T_ROLL, T_ROLL + 0.3, T_ROLL + 0.58, T_ROLL + 0.84):+ x = roll_at((tt - T_ROLL) / (T_JUMP - T_ROLL))[5]+ sb.fx('dust', tt, x - 20, gy(x - 20), n=4, spread=46, size=9, dirs=(-1,))+ sb.fx('ripple', T_LEAF, on_leaf(T_LEAF)[0], WATER_Y + 4, r=110, n=3)+ sb.fx('ripple', LEAF_T1 - 0.05, LEAF_X0, WATER_Y + 2, r=60, n=1, life=0.7)+ for tt in np.arange(T_FLOAT + 0.25, T_BUMP, 0.42):+ sb.fx('ripple', tt, leaf_pose(tt)['x'] - 70, WATER_Y + 6, r=50, n=1, life=0.7)+ sb.fx('ripple', T_HOP, on_leaf(T_HOP)[0], WATER_Y + 4, r=80, n=2)+ sb.fx('impact', T_LAND, SPOT, gy(SPOT), r=60, n=7)+ sb.fx('dust', T_LAND, SPOT, gy(SPOT), n=6, spread=60)+ for tt in (T_DIG + 0.25, T_DIG + 0.45, T_DIG + 0.62):+ sb.fx('specks', tt, SPOT, gy(SPOT) - 4, n=7)+ sb.fx('sparkle', T_SPROUT + 0.5, 1600, 618, r=18)+ sb.fx('sparkle', T_SPROUT + 0.6, 1726, 676, r=14, colour='#ee8a3c')+ sb.fx('sparkle', T_SPROUT + 0.7, 1712, 580, r=12)+ sb.fx('confetti', T_WRITE + 0.6, 1000, 470, n=120, spread=1500, up=1100, life=2.6, stagger=0.3, wide=640)+ sb.write('hello, little oak', 1000, 318, 138, when=(T_WRITE, T_WRITE + 1.0), underline=((700, 1290), 400))+ return sb, stem_at+++if __name__ == '__main__':+ sb, _ = build(1920, 1080)+ if stages:+ for name, t in [('tree', 0.55), ('fall', 1.02), ('squash', 1.18), ('watch_leaf', 2.5), ('ready', 3.2),+ ('roll', 3.95), ('float', 5.7), ('hop', 6.82), ('dig', 7.7), ('sprout', 8.75), ('write', 9.95)]:+ sb.stage(name, t)+ sb.journey([1.0, T_HIT + 0.02, 4.06, 4.66, 5.78, 6.83], t_world=T_END, arc=(0.8, 7.62),+ labels=[('whoa!', 105, -10), ('plop!', -95, -70), ('wheee!', 70, -95), ('hop!', 20, -105),+ ('la la', 0, -110), ('up we go', 0, -118)],+ prop_arcs=[(LEAF_T0, LEAF_T1, lambda u, t: leaf_pose(t))], world_fx=True, props=False)+ sb.save(out, stages)+ print(f'{out} {time.time() - t_start:.1f}s')+ if gif:+ t1 = time.time()+ del sb+ g, _ = build(720, 405)+ n = g.gif(gif, fps=15, t_end=T_END, hold=1.4)+ print(f'{gif} {n} frames {os.path.getsize(gif) / 1e6:.2f} MB {time.time() - t1:.1f}s')diff --git a/examples/thermal_kitchen.jpg b/examples/thermal_kitchen.jpgnew file mode 100644index 0000000..78877caBinary files /dev/null and b/examples/thermal_kitchen.jpg differdiff --git a/examples/thermal_kitchen.py b/examples/thermal_kitchen.pynew file mode 100644index 0000000..fe4fb35--- /dev/null+++ b/examples/thermal_kitchen.py@@ -0,0 +1,376 @@+"""Example (thermal camera / 热成像): 厨房里的温度 · Kitchen Heat Map — a kitchen at dinner time through a thermal+camera. A stock pot boils on the back burner and its steam rolls up into the cooker hood (its polished lid reads+cooler than it is); a kettle on the front burner shoots a jet of steam out of its spout; the oven is still warm and+leaks hot air along its top seal, a damp tea towel hangs cold on its handle; two loaves fresh from the oven steam on+a wire rack next to a cold butter dish. On the left the fridge door has been left open: a black-cold cave of+shelves, and its cold air pours down the freezer drawer and spreads across the floor in tongues. The cat went to the+fridge, walked through the cold puddle and back to the warm tiles in front of the oven -- its paw prints are still on+the floor, fading the older they are. The window is cold night glass. Spot meters, an area box, a line profile along+the paw trail (cold puddle -> warm tiles, one bump per print) and hottest / coldest markers read the temperatures off+the picture.+Draw-on stages: room -> fridge -> stove -> bread -> heat soak -> steam -> cat -> measurements. No image model.+python3 thermal_kitchen.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from thermal import Thermal+from core import spline++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'thermal_kitchen.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++# ---- one-point perspective: camera 1.6 m up, looking at the back wall 4.5 m away, pitched down (shifted VP)+F, VX, VY, EYE = 1750.0, 960.0, 100.0, 1.6+++def P(X, Y, Z):+ return (VX + F * X / Z, VY + F * (EYE - Y) / Z)+++def face(x0, x1, y0, y1, Z):+ """front face (constant depth Z) -> canvas quad"""+ return [P(x0, y1, Z), P(x1, y1, Z), P(x1, y0, Z), P(x0, y0, Z)]+++def top(x0, x1, z0, z1, Y):+ """horizontal face at height Y between depths z0 (front) and z1 (back)"""+ return [P(x0, Y, z1), P(x1, Y, z1), P(x1, Y, z0), P(x0, Y, z0)]+++def ell(X, Y, Z, rx, rz, n=40):+ """horizontal circle (radius rx across, rz in depth) at (X, Y, Z) -> canvas outline"""+ a = np.linspace(0, 2 * np.pi, n, endpoint=False)+ return [P(X + rx * np.cos(t), Y, Z + rz * np.sin(t)) for t in a]+++t = Thermal(1920, 1080, sensor=(480, 270), ss=2, seed=12, ambient=21.0)+# hand-set tone curve: the fridge black, the room deep violet, warm bodies red-orange, the stove yellow, flames white+t.camera(palette='iron', agc=0.22, plateau=2.0, netd=0.24, fpn=0.1, dde=1.6, pixel=0.4,+ curve=[(2, 0.0), (7, 0.05), (12, 0.11), (16, 0.17), (19, 0.23), (22, 0.29), (26, 0.43), (30, 0.59), (35, 0.71),+ (39, 0.78), (60, 0.82), (80, 0.86), (100, 0.91), (160, 1.0)])+WALL, ZC, ZF = 4.5, 3.9, 3.97 # back wall, cabinet fronts, toe kick++# =========================================================== 0. the room at room temperature+t.room(top=24.5, bottom=20.0, y_top=0, y_bottom=900)+floor = t.poly([(0, P(0, 0, ZF)[1]), (1920, P(0, 0, ZF)[1]), (1920, 1080), (0, 1080)])+fy = P(0, 0, ZF)[1]+t.surface(floor, t.ramp((0, fy), 18.6, (0, 1080), 19.4), grain=0.25, grain_scale=60)+for Z in (3.3, 3.6, 3.9): # floor tiles: grout lines+ t.seam([P(-3, 0, Z), P(3, 0, Z)], -0.45, 2.5)+for X in np.arange(-2.1, 2.2, 0.3):+ t.seam([P(X, 0, ZF), P(X, 0, 3.2)], -0.45, 2.5)+# splashback tiles on the back wall between counter and wall cabinets+for Y in np.arange(0.92, 1.62, 0.075):+ t.seam([P(-1.3, Y, WALL), P(1.4, Y, WALL)], -0.22, 1.6)+for i, Y in enumerate(np.arange(0.92, 1.55, 0.075)):+ for X in np.arange(-1.3 + (0.075 if i % 2 else 0), 1.4, 0.15):+ t.seam([P(X, Y, WALL), P(X, Y + 0.075, WALL)], -0.22, 1.6)+# window (cold night glass, glass is opaque to long-wave IR so nothing outside shows)+wx0, wx1, wy0, wy1 = 1.40, 2.40, 1.02, 2.20+t.surface(t.poly(face(wx0 - 0.05, wx1 + 0.05, wy0 - 0.05, wy1 + 0.05, WALL)), 16.2, grain=0.2)+for (a, b) in ((wx0, 1.82), (1.88, wx1)):+ for (c, d) in ((wy0, 1.57), (1.63, wy1)):+ g = t.poly(face(a, b, c, d, WALL))+ t.surface(g, t.ramp(P(0, d, WALL), 12.6, P(0, c, WALL), 8.2), grain=0.25, grain_scale=40)+ t.surface(t.poly(face(a, a + 0.06, c, c + 0.08, WALL)) * g, 6.8, soft=4) # cold corners at the spacer+ t.surface(t.poly(face(b - 0.06, b, c, c + 0.08, WALL)) * g, 6.8, soft=4)+t.surface(t.poly(top(wx0 - 0.08, wx1 + 0.1, 4.40, WALL, wy0 - 0.05)), 17.6) # sill+# wall cabinets+ZU = 4.15+for (a, b, split) in ((-1.22, -0.45, -0.835), (0.45, 1.30, 0.875)):+ m = t.poly(face(a, b, 1.45, 2.6, ZU))+ t.surface(m, t.ramp((0, 0), 24.0, P(0, 1.45, ZU), 22.0), grain=0.25, grain_scale=30)+ t.seam([P(split, 1.45, ZU), P(split, 2.6, ZU)], -0.9, 3)+ for X in (a, b): t.seam([P(X, 1.45, ZU), P(X, 2.6, ZU)], -0.5, 3)+ t.seam([P(a, 1.45, ZU), P(b, 1.45, ZU)], -0.6, 3)+ for X in (split - 0.05, split + 0.05):+ t.surface(t.rect(P(X, 1.52, ZU)[0] - 4, P(X, 1.6, ZU)[1], P(X, 1.52, ZU)[0] + 4, P(X, 1.52, ZU)[1]), 19.5,+ emissivity=0.4) # brushed-steel handles read cooler than the doors+# base cabinets: left run (sink side) and right run+for (a, b, splits) in ((-1.25, -0.40, (-0.83,)), (0.40, 2.4, (0.98, 1.56))):+ m = t.poly(face(a, b, 0.10, 0.88, ZC))+ t.surface(m, t.ramp(P(0, 0.88, ZC), 21.4, P(0, 0.1, ZC), 19.6), grain=0.25, grain_scale=30)+ t.surface(t.poly(face(a, b, 0.0, 0.10, ZF)), 18.2) # toe kick shadow+ t.seam([P(a, 0.72, ZC), P(b, 0.72, ZC)], -0.9, 3) # drawer line+ for X in (a,) + splits + (b,):+ t.seam([P(X, 0.1, ZC), P(X, 0.88, ZC)], -0.9, 3)+ for X0, X1 in zip((a,) + splits, splits + (b,)):+ cx = (X0 + X1) / 2+ hx, hy = P(cx, 0.80, ZC)+ t.surface(t.rect(hx - 26, hy - 3, hx + 26, hy + 3, r=3), 19.4, emissivity=0.4)+# the stone counter top and its front edge+t.surface(t.poly(top(-1.25, 2.4, 3.88, WALL, 0.92)), 20.2, grain=0.35, grain_scale=24) # stone: thermal mass, runs cool+t.surface(t.poly(face(-1.25, 2.4, 0.88, 0.92, 3.88)), 19.4)+t.seam([P(-1.25, 0.92, 3.88), P(2.4, 0.92, 3.88)], 1.2, 2)+# the range body (cold until stage 2) and the hood+rng_front = t.poly(face(-0.40, 0.38, 0.0, 0.92, 3.88))+t.surface(rng_front, 21.0)+hood = t.poly([P(-0.42, 1.50, 4.0), P(0.38, 1.50, 4.0), P(0.26, 1.66, 4.15), P(-0.30, 1.66, 4.15)])+chim = t.poly(face(-0.14, 0.12, 1.64, 2.7, 4.4))+t.surface(chim, 24.0, emissivity=0.6)+t.surface(hood, 22.5, emissivity=0.6)+t.seam([P(-0.42, 1.50, 4.0), P(0.38, 1.50, 4.0)], -0.5, 3)+# outlet on the splashback+ox, oy = P(-1.05, 1.15, WALL)+t.surface(t.rect(ox - 18, oy - 26, ox + 18, oy + 26, r=3), 21.0)+t.statusbar(rec='00:04:51', date='2026-11-14', clock='18:42:07', battery=0.75, emissivity=0.96, mode='MAN', height=50, reflected=21)+t.scalebar(560, 1030, 1360, 1044, height=78)+t.stage('room')++# =========================================================== 1. the fridge, door left open+FZ = 3.80+fr_side = t.poly([P(-1.25, 1.85, FZ), P(-1.25, 1.85, WALL), P(-1.25, 0.92, WALL), P(-1.25, 0.92, 3.88),+ P(-1.25, 0.0, ZC), P(-1.25, 0.0, FZ)])+t.surface(fr_side, 21.2)+t.surface(t.poly(face(-2.2, -1.25, 0.0, 1.85, FZ)), 20.6, grain=0.2) # carcass front+# the open compartment: gasket frame (anti-sweat heater) then the cold inside+t.surface(t.poly(face(-2.2, -1.27, 0.64, 1.82, FZ)), 27.5)+op = t.poly(face(-2.2, -1.31, 0.68, 1.78, FZ))+back = t.poly(face(-2.2, -1.31, 0.70, 1.76, 4.42)) * op+t.surface(op, t.ramp(P(0, 1.78, FZ), 6.4, P(0, 0.68, FZ), 4.2))+t.surface(back, t.ramp(P(0, 1.76, 4.42), 4.0, P(0, 0.7, 4.42), 2.4), grain=0.2)+for Y in (0.98, 1.28, 1.55): # glass shelves+ t.surface(t.poly(top(-2.2, -1.31, 3.84, 4.42, Y)) * op, 6.0)+ t.surface(t.line([P(-2.2, Y, 3.84), P(-1.31, Y, 3.84)], 5) * op, 10.5)+t.surface(t.poly(face(-2.2, -1.31, 0.70, 0.95, 3.86)) * op, 7.5) # crisper drawers+t.seam([P(-1.75, 0.70, 3.86), P(-1.75, 0.95, 3.86)], 1.0, 3)+items = [ # (X, Y, Z, half width, height, temp): bottles, jars, a bowl, a carton+ (-1.50, 1.28, 4.15, 0.040, 0.24, 9.0), (-1.62, 1.28, 4.25, 0.035, 0.20, 8.2), (-1.95, 1.28, 4.2, 0.06, 0.12, 10.0),+ (-1.80, 0.98, 4.10, 0.09, 0.09, 9.5), (-1.45, 0.98, 4.20, 0.05, 0.16, 8.6), (-2.05, 1.55, 4.2, 0.05, 0.14, 9.0),+ (-1.60, 1.55, 4.2, 0.12, 0.08, 10.5)]+for X, Y, Z, hw, h, Tm in items:+ m = t.shape([P(X - hw, Y, Z), P(X - hw, Y + h * 0.75, Z), P(X - hw * 0.6, Y + h, Z), P(X + hw * 0.6, Y + h, Z),+ P(X + hw, Y + h * 0.75, Z), P(X + hw, Y, Z)]) * op+ t.surface(m, Tm + 2.5, grain=0.4)+lx, ly = P(-2.1, 1.74, 4.3)+t.surface(t.ellipse(lx + 30, ly + 4, 20, 7), 27.0, soft=2) # the inside lamp+# freezer drawer (closed)+fd = t.poly(face(-2.2, -1.25, 0.06, 0.62, FZ))+t.surface(fd, t.ramp(P(0, 0.62, FZ), 19.6, P(0, 0.06, FZ), 18.8), grain=0.2)+t.seam([P(-2.2, 0.62, FZ), P(-1.25, 0.62, FZ)], -1.5, 4)+t.seam([P(-2.0, 0.56, FZ - 0.02), P(-1.45, 0.56, FZ - 0.02)], -1.0, 6) # handle recess+# its cold air pours down the drawer front and spreads over the floor+t.plume([P(-1.75, 0.68, FZ - 0.01), P(-1.74, 0.45, FZ - 0.02), P(-1.71, 0.2, FZ - 0.03), P(-1.66, 0.02, 3.7)],+ 5.0, w0=190, w1=250, opacity=0.8, cool=0.5, eddy=0.55, wisp=0.35, puffs=0.15, seed=5, fade_out=0.04)+for i, X in enumerate((-1.98, -1.55)):+ t.plume([P(X, 0.66, FZ - 0.01), P(X + 0.03, 0.4, FZ - 0.02), P(X + 0.06, 0.1, FZ - 0.03), P(X + 0.1, 0.01, 3.7)],+ 4.0, w0=30, w1=70, opacity=0.7, cool=0.5, eddy=0.7, wisp=0.4, puffs=0.3, seed=6 + i, fade_out=0.05)+px_, py_ = P(-1.68, 0, 3.78)+t.pool(px_, py_, 6.5, reach=560, spread=(-15, 150), tongues=9, squash=0.36, width=0.22, soft=10, seed=8)+# a milk bottle and a glass of iced water on the counter+mx, my = P(-1.05, 0.92, 4.25); s = F / 4.25+milk = t.shape([(mx - 0.04 * s, my), (mx - 0.042 * s, my - 0.15 * s), (mx - 0.022 * s, my - 0.20 * s),+ (mx - 0.018 * s, my - 0.24 * s), (mx + 0.018 * s, my - 0.24 * s), (mx + 0.022 * s, my - 0.20 * s),+ (mx + 0.042 * s, my - 0.15 * s), (mx + 0.04 * s, my)])+t.surface(milk, t.ramp((0, my - 0.24 * s), 9.0, (0, my), 6.5))+gx, gy = P(-0.70, 0.92, 4.0); s = F / 4.0+glass = t.poly([(gx - 0.036 * s, gy - 0.125 * s), (gx + 0.036 * s, gy - 0.125 * s), (gx + 0.03 * s, gy), (gx - 0.03 * s, gy)])+t.soak(glass, 4.0, reach=10, strength=0.5, onto=t.poly(top(-1.25, -0.4, 3.88, WALL, 0.92)))+t.surface(glass, t.ramp((0, gy - 0.125 * s), 5.5, (0, gy), 2.2), grain=0.3)+t.surface(t.ellipse(gx, gy - 0.118 * s, 0.033 * s, 5), 1.0) # ice at the top+t.stage('fridge')++# =========================================================== 2. the stove: burners, a stock pot, a kettle, the oven+ZP, ZK = 4.28, 4.02+for X, Z in ((-0.2, ZP), (0.18, ZK)): # lit burners+ t.surface(t.poly(ell(X, 0.93, Z, 0.11, 0.11)), 140.0, soft=2)+for X, Z in ((0.18, 4.3), (-0.2, 4.05)): # cold burners+ t.seam([*ell(X, 0.93, Z, 0.09, 0.09), ell(X, 0.93, Z, 0.09, 0.09)[0]], 1.2, 3)+# stock pot: enamelled, hottest low where the flames lick it+px0, py0 = P(-0.2, 0.95, ZP - 0.16) # base, front+R = 0.175 * F / ZP+rim = P(-0.2, 0.95 + 0.20, ZP)[1]+for sx in (-1, 1): # loop handles at the rim+ hx0 = px0 + sx * (R - 4)+ t.surface(t.line([(hx0, rim + 10), (hx0 + sx * 22, rim + 8), (hx0 + sx * 24, rim + 20), (hx0, rim + 24)], 7), 68.0)+pot = t.poly([(px0 - R, rim), (px0 - R, py0 - 6), (px0 - R + 6, py0), (px0 + R - 6, py0), (px0 + R, py0 - 6), (px0 + R, rim)])+t.surface(pot, t.ramp((0, py0), 104.0, (0, rim), 91.0, ease=0.6), grain=0.6, limb=6, limb_px=14)+t.seam([(px0 - R, rim + 6), (px0 + R, rim + 6)], -4.0, 3) # rolled rim+lid = t.poly(ell(-0.2, 1.16, ZP, 0.172, 0.172))+t.surface(lid, t.ramp((px0 - R, 0), 92.0, (px0 + R, 0), 99.0), emissivity=0.55, grain=0.5) # polished lid: reads cooler+t.seam(ell(-0.2, 1.165, ZP, 0.15, 0.15) + [ell(-0.2, 1.165, ZP, 0.15, 0.15)[0]], -3.0, 2)+kx, ky = P(-0.2, 1.18, ZP)+t.surface(t.ellipse(kx, ky - 3, 15, 7), 52.0) # bakelite knob, cooler+t.surface(t.poly(ell(-0.2, 0.95, ZP, 0.15, 0.06)) * (1 - pot), 260.0, soft=3) # flame ring under the pot+# kettle on the front burner: a dome with the spout to the right and a handle over the top+qx, qy = P(0.18, 0.95, ZK - 0.10)+s = F / ZK+kettle = t.shape([(qx - 0.115 * s, qy - 6), (qx - 0.112 * s, qy - 0.07 * s), (qx - 0.08 * s, qy - 0.15 * s),+ (qx - 0.03 * s, qy - 0.185 * s), (qx + 0.03 * s, qy - 0.185 * s), (qx + 0.08 * s, qy - 0.15 * s),+ (qx + 0.112 * s, qy - 0.07 * s), (qx + 0.115 * s, qy - 6), (qx, qy + 2)], per=8)+spout = t.line([(qx + 0.09 * s, qy - 0.06 * s), (qx + 0.15 * s, qy - 0.11 * s), (qx + 0.19 * s, qy - 0.17 * s)], 0.026 * s)+t.surface(spout, t.ramp((qx + 0.09 * s, 0), 90.0, (qx + 0.19 * s, 0), 80.0))+t.surface(kettle, t.ramp((0, qy), 97.0, (0, qy - 0.185 * s), 86.0), grain=0.5, limb=8, limb_px=12)+handle = t.line([(qx - 0.07 * s, qy - 0.16 * s), (qx - 0.06 * s, qy - 0.25 * s), (qx + 0.06 * s, qy - 0.25 * s), (qx + 0.07 * s, qy - 0.16 * s)], 0.022 * s)+t.surface(handle * (1 - kettle), 41.0)+t.surface(t.ellipse(qx, qy - 0.19 * s, 0.022 * s, 0.012 * s), 62.0)+t.surface(t.poly(ell(0.18, 0.95, ZK, 0.13, 0.05)) * (1 - kettle), 240.0, soft=3)+# oven: control strip, door with its glass, handle, warming drawer; hot air leaks along the top seal+t.surface(t.poly(face(-0.40, 0.38, 0.80, 0.92, 3.88)), t.ramp(P(0, 0.92, 3.88), 25.0, P(0, 0.8, 3.88), 27.5), grain=0.4)+for X in (-0.3, -0.2, -0.1, 0.1, 0.2, 0.3):+ cx, cy = P(X, 0.86, 3.86)+ t.surface(t.ellipse(cx, cy, 10, 10), 22.5)+door = t.poly(face(-0.38, 0.36, 0.14, 0.78, 3.86))+t.surface(door, t.ramp(P(0, 0.78, 3.86), 26.5, P(0, 0.14, 3.86), 23.0), grain=0.5)+win = t.poly(face(-0.28, 0.26, 0.30, 0.66, 3.86))+t.surface(win, t.ramp(P(0, 0.66, 3.86), 31.5, P(0, 0.30, 3.86), 26.5), grain=0.6, soft=3)+t.surface(t.poly(face(-0.38, 0.36, 0.76, 0.79, 3.86)), 46.0, soft=2) # leaking top seal+hy = P(0, 0.72, 3.80)[1]+t.surface(t.rect(P(-0.32, 0, 3.8)[0], hy - 6, P(0.30, 0, 3.8)[0], hy + 6, r=6), 26.0, emissivity=0.7)+t.surface(t.poly(face(-0.38, 0.36, 0.02, 0.12, 3.86)), 23.0)+# a damp tea towel over the handle: evaporation keeps it below room temperature+tw0, tw1 = P(0.10, 0, 3.79)[0], P(0.24, 0, 3.79)[0]+towel = t.shape([(tw0, hy - 8), (tw1, hy - 9), (tw1 + 4, hy + 60), (tw1 + 8, hy + 150), (tw1 - 10, hy + 158),+ ((tw0 + tw1) / 2, hy + 150), (tw0 + 6, hy + 156), (tw0 - 8, hy + 148), (tw0 - 4, hy + 60)], per=8)+t.surface(towel, t.ramp((0, hy), 20.0, (0, hy + 150), 17.5), grain=0.6, grain_scale=8)+t.seam([((tw0 + tw1) / 2 + 4, hy + 4), ((tw0 + tw1) / 2 + 10, hy + 150)], -1.2, 3)+t.stage('stove')++# =========================================================== 3. bread on a wire rack, cold butter+ZB = 4.2+t.surface(t.poly(top(0.50, 1.20, 4.05, 4.36, 0.955)), 38.0, soft=1) # rack (wire, warm)+for X in np.arange(0.52, 1.2, 0.045):+ t.seam([P(X, 0.955, 4.05), P(X, 0.955, 4.36)], 4.0, 2)+bx, by = P(0.68, 0.96, ZB); s = F / ZB+boule = t.shape([(bx - 0.14 * s, by), (bx - 0.135 * s, by - 0.05 * s), (bx - 0.09 * s, by - 0.11 * s),+ (bx, by - 0.13 * s), (bx + 0.09 * s, by - 0.11 * s), (bx + 0.135 * s, by - 0.05 * s), (bx + 0.14 * s, by)])+t.surface(boule, t.radial(bx, by - 0.07 * s, 0.14 * s, 0.07 * s, 82.0, 63.0), grain=1.5, grain_scale=10, soft=1, limb=8, limb_px=14)+for k in (-1, 0, 1): # scoring: thin crust, hotter+ t.seam([(bx - 0.07 * s + k * 0.03 * s, by - 0.09 * s + abs(k) * 0.01 * s),+ (bx + 0.06 * s + k * 0.03 * s, by - 0.105 * s + abs(k) * 0.01 * s)], 9.0, 4)+cx, cy = P(1.02, 0.96, ZB)+batard = t.shape([(cx - 0.16 * s, cy), (cx - 0.15 * s, cy - 0.05 * s), (cx - 0.08 * s, cy - 0.085 * s),+ (cx + 0.08 * s, cy - 0.085 * s), (cx + 0.15 * s, cy - 0.05 * s), (cx + 0.16 * s, cy)])+t.surface(batard, t.radial(cx, cy - 0.045 * s, 0.16 * s, 0.05 * s, 78.0, 58.0), grain=1.5, grain_scale=10, soft=1, limb=8, limb_px=12)+for k in range(3):+ x = cx - 0.09 * s + k * 0.08 * s+ t.seam([(x - 0.03 * s, cy - 0.06 * s), (x + 0.03 * s, cy - 0.075 * s)], 8.0, 4)+dx, dy = P(1.40, 0.92, 4.08); s2 = F / 4.08+t.surface(t.poly([(dx - 0.09 * s2, dy), (dx + 0.09 * s2, dy), (dx + 0.08 * s2, dy - 0.02 * s2), (dx - 0.08 * s2, dy - 0.02 * s2)]), 12.0)+t.surface(t.rect(dx - 0.055 * s2, dy - 0.055 * s2, dx + 0.055 * s2, dy - 0.02 * s2, r=3), t.ramp((0, dy - 0.055 * s2), 10.0, (0, dy), 7.5))+# a herb pot on the sill: leaves run cooler than the room (they evaporate water)+hx, hy = P(1.72, 0.92, 4.32); s3 = F / 4.32+t.surface(t.poly([(hx - 0.06 * s3, hy - 0.11 * s3), (hx + 0.06 * s3, hy - 0.11 * s3), (hx + 0.045 * s3, hy), (hx - 0.045 * s3, hy)]), 19.0)+for i in range(16):+ a = np.radians(-150 + i * 8 + (i % 3) * 5)+ L = (0.12 + 0.09 * ((i * 7) % 5) / 4) * s3+ ex, ey = hx + np.cos(a) * L * 0.8, hy - 0.11 * s3 + np.sin(a) * L+ t.surface(t.ellipse(ex, ey, 9, 5, np.degrees(a)), 16.5, soft=1)+ t.surface(t.line([(hx, hy - 0.11 * s3), (ex, ey)], 2.5), 17.0)+t.stage('bread')++# =========================================================== 4. heat soaks into what is around it+behind = t.poly([P(-0.30, 0.93, WALL), P(0.28, 0.93, WALL), P(0.22, 1.40, WALL), P(-0.24, 1.40, WALL)])+occ = np.clip(pot + lid + kettle + handle + spout + hood + chim, 0, 1)+t.soak(behind, 60.0, reach=38, strength=0.4, onto=(1 - occ) * t.poly([P(-1.25, 0.92, WALL), P(1.4, 0.92, WALL), P(1.4, 1.50, WALL), P(-1.25, 1.50, WALL)]))+t.surface(hood, t.ramp((0, P(0, 1.50, 4.0)[1]), 38.0, (0, P(0, 1.66, 4.15)[1]), 28.0), emissivity=0.8, grain=0.4)+t.surface(chim, t.ramp((0, P(0, 1.66, 4.4)[1]), 25.0, (0, 0), 23.5), emissivity=0.8)+t.seam([P(-0.42, 1.50, 4.0), P(0.38, 1.50, 4.0)], 3.0, 3)+# the cabinets either side of the range and the counter round the hob warm up+oven_face = t.poly(face(-0.40, 0.38, 0.0, 0.92, 3.88))+t.soak(oven_face, 28.0, reach=20, strength=0.35, onto=t.poly(face(-1.25, 2.4, 0.0, 0.92, ZC)) * (1 - oven_face))+t.soak(t.poly(top(-0.40, 0.38, 3.9, WALL, 0.92)), 70.0, reach=22, strength=0.35, onto=t.poly(top(-1.25, 2.4, 3.88, WALL, 0.92)) * (1 - occ - oven_face).clip(0, 1))+# under the bread rack the counter is warm+t.soak(t.poly(top(0.50, 1.20, 4.05, 4.36, 0.93)), 60.0, reach=10, strength=0.6, onto=t.poly(top(0.4, 1.3, 3.88, WALL, 0.92)) * (1 - boule - batard).clip(0, 1))+# the warm patch on the tiles in front of the oven (it radiates onto the floor)+t.warm(floor * t.radial(*P(0.15, 0, 3.5), 420, 90, 1.0, 0.0, power=1.4), 5.5)+# glazed tiles mirror the oven door, faintly+t.reflect(floor * t.ramp(P(-1.2, 0, 3.9), 0.0, P(-0.5, 0, 3.9), 1.0), P(0, 0, ZF)[1], strength=0.22, blur_px=10, fade=70)+t.stage('soak')++# =========================================================== 5. steam and rising air+hood_y = P(0, 1.50, 4.0)[1]+lid_y = P(-0.2, 1.16, ZP)[1]+t.plume([(px0 + R * 0.55, lid_y + 2), (px0 + R * 0.6, lid_y - 40), (px0 + R * 0.3, lid_y - 90), (px0 + R * 0.45, lid_y - 130), (px0 + R * 0.2, hood_y + 4)],+ 99.0, w0=12, w1=70, opacity=0.95, cool=1.1, eddy=0.85, wisp=0.55, puffs=0.35, seed=21, fade_out=0.04)+t.plume([(px0 - R * 0.35, lid_y + 4), (px0 - R * 0.5, lid_y - 50), (px0 - R * 0.2, lid_y - 110), (px0 - R * 0.35, hood_y + 4)],+ 97.0, w0=7, w1=48, opacity=0.8, cool=1.3, eddy=0.85, wisp=0.6, puffs=0.4, seed=22, fade_out=0.04)+# the steam hits the hood and runs along under its lip; some spills out over the front edge+t.plume([(px0 + R * 0.25, hood_y + 6), (px0 - 60, hood_y + 10), (px0 - 160, hood_y + 4)], 62.0, w0=16, w1=24, opacity=0.7, cool=0.8, eddy=0.6, seed=23)+t.plume([(px0 + R * 0.25, hood_y + 6), (px0 + 130, hood_y + 10), (px0 + 250, hood_y + 2)], 60.0, w0=16, w1=24, opacity=0.7, cool=0.8, eddy=0.6, seed=24)+t.plume(t.rise(P(0.36, 1.50, 4.0)[0] - 10, hood_y - 4, 120, sway=22, lean=0.12, seed=25), 40.0, w0=14, w1=60, opacity=0.3, cool=1.4, eddy=0.9, seed=25)+# the kettle's jet: fast and narrow out of the spout, then it turns upward and billows under the wall cabinet+sx, sy = qx + 0.19 * F / ZK, qy - 0.17 * F / ZK+cab_y = P(0, 1.45, ZU)[1]+t.plume([(sx + 2, sy - 2), (sx + 30, sy - 26), (sx + 52, sy - 58), (sx + 62, sy - 100), (sx + 80, cab_y + 30), (sx + 110, cab_y + 8)],+ 100.0, w0=5, w1=58, opacity=0.95, cool=1.2, eddy=0.85, wisp=0.5, puffs=0.3, seed=31, fade_out=0.06)+t.plume([(sx + 100, cab_y + 10), (sx + 180, cab_y + 14), (sx + 260, cab_y + 8)], 50.0, w0=20, w1=26, opacity=0.6, cool=0.9, eddy=0.7, seed=32)+# bread breathes a soft warm haze; the oven's top seal sends a sheet of hot air up the controls+t.plume(t.rise(bx, by - 0.13 * s, 150, sway=18, lean=-0.05, seed=41), 44.0, w0=40, w1=90, opacity=0.45, cool=1.2, eddy=0.9, seed=41)+t.plume(t.rise(cx, cy - 0.085 * s, 140, sway=16, lean=0.08, seed=42), 42.0, w0=50, w1=90, opacity=0.4, cool=1.2, eddy=0.9, seed=42)+t.plume([P(-0.02, 0.79, 3.84), P(-0.02, 0.86, 3.84), P(-0.02, 0.93, 3.88)], 45.0, w0=150, w1=170, opacity=0.35, cool=0.6, eddy=0.7, seed=43)+# the window drops a sheet of cold air onto the counter+t.plume([P(1.9, 1.0, 4.42), P(1.9, 0.94, 4.35), P(1.9, 0.92, 4.1)], 13.0, w0=150, w1=180, opacity=0.5, cool=0.6, eddy=0.4, seed=51)+t.stage('steam')++# =========================================================== 6. the cat, and how it got there+CX, CZ = 0.62, 3.22+cfx, cfy = P(CX, 0, CZ); u = 0.37 * F / CZ # canvas px per cat-height+++def C(a, b):+ """cat coordinates: a to the right (towards the tail), b up, in cat heights; it faces left, to the oven"""+ return (cfx + a * u, cfy - b * u)+++body = t.shape([C(-0.20, 0.62), C(-0.25, 0.42), C(-0.24, 0.12), C(-0.22, 0.0), C(0.05, 0.0), C(0.30, 0.0),+ C(0.38, 0.12), C(0.36, 0.32), C(0.24, 0.54), C(0.08, 0.70), C(-0.08, 0.72)], per=12)+head = t.shape([C(-0.36, 0.80), C(-0.33, 0.70), C(-0.24, 0.64), C(-0.10, 0.66), C(0.01, 0.76), C(0.0, 0.88),+ C(-0.06, 0.95), C(-0.20, 0.97), C(-0.32, 0.90)], per=10)+ear_far = t.poly([C(-0.27, 0.93), C(-0.30, 1.08), C(-0.17, 0.97)])+ear_near = t.poly([C(-0.13, 0.95), C(-0.06, 1.10), C(0.0, 0.90)])+ear_in = t.poly([C(-0.115, 0.955), C(-0.065, 1.06), C(-0.025, 0.925)])+legs = t.shape([C(-0.23, 0.36), C(-0.10, 0.36), C(-0.09, 0.03), C(-0.04, 0.0), C(-0.26, 0.0), C(-0.24, 0.05)], per=6)+haunch = t.ellipse(*C(0.18, 0.20), 0.17 * u, 0.20 * u, rot=-10)+tail_pts = [C(0.33, 0.04), C(0.30, -0.03), C(0.12, -0.06), C(-0.08, -0.06), C(-0.26, -0.035), C(-0.34, 0.02)]+tail = t.line(spline(tail_pts, 8), 0.075 * u)+cat_all = np.clip(body + head + ear_far + ear_near + legs + haunch + tail, 0, 1)+# paw prints first (they lie under the cat): from the cold puddle by the fridge to the warm tiles+steps = [] # (x, y, heading, scale, age)+path = np.array([(-1.62, 3.50), (-1.2, 3.40), (-0.7, 3.32), (-0.2, 3.28), (0.15, 3.24), (0.42, 3.22)])+dist = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(path, axis=0).T))])+n_steps = 18+for i in range(n_steps):+ dd = dist[-1] * i / (n_steps - 1)+ X = np.interp(dd, dist, path[:, 0]); Z = np.interp(dd, dist, path[:, 1])+ Z += 0.035 * (1 if i % 2 else -1)+ xx, yy = P(X, 0, Z)+ age = 0.88 * (1 - i / (n_steps - 1)) ** 0.85 + 0.04+ steps.append((xx, yy, 0, F / Z / 560, age))+t.prints(steps, 33.0, size=32, squash=0.42, spread=0.8)+# the cat: fur insulates, so the coat reads well below body temperature; where the fur is thin (face, inner ear,+# chest, armpit) it runs warmer, the flank facing the oven is warmer, and every rounded edge cools towards the outline+t.surface(tail, t.ramp(C(0.33, 0), 29.5, C(-0.34, 0), 25.0), fuzz=0.5, fuzz_scale=3, limb=1.5, limb_px=5)+t.surface(body, t.ramp(C(-0.25, 0.3), 33.6, C(0.36, 0.55), 28.0), fuzz=0.6, fuzz_scale=4, grain=0.5, grain_scale=7,+ limb=3.0, limb_px=16)+t.surface(haunch, t.ramp(C(-0.05, 0.12), 32.0, C(0.36, 0.32), 27.6), fuzz=0.6, fuzz_scale=4, grain=0.5, grain_scale=7,+ limb=1.2, limb_px=10)+t.seam([C(0.02, 0.05), C(0.05, 0.2), C(0.14, 0.34), C(0.30, 0.38)], -1.6, 4) # where the haunch folds+t.warm(t.ellipse(*C(-0.17, 0.47), 0.06 * u, 0.15 * u) * body, 1.4) # thin fur on the chest+t.surface(legs, t.ramp(C(0, 0.3), 31.5, C(0, 0.0), 27.5), fuzz=0.5, fuzz_scale=3, limb=1.5, limb_px=6)+t.seam([C(-0.165, 0.30), C(-0.16, 0.02)], -1.6, 3)+t.surface(ear_far, 27.5, fuzz=0.3, fuzz_scale=2)+t.surface(head, t.ramp(C(-0.34, 0.8), 35.0, C(0.0, 0.85), 31.5), fuzz=0.45, fuzz_scale=3, grain=0.3, grain_scale=6,+ limb=2.0, limb_px=10)+t.surface(ear_near, 28.5, fuzz=0.3, fuzz_scale=2)+t.surface(ear_in, 34.5, soft=1)+t.surface(t.ellipse(*C(-0.215, 0.84), 0.036 * u, 0.028 * u), 38.6, soft=1) # eye: the hottest spot+t.surface(t.ellipse(*C(-0.355, 0.78), 0.024 * u, 0.02 * u), 26.0, soft=1) # cold nose+t.surface(t.ellipse(*C(-0.29, 0.69), 0.05 * u, 0.025 * u), 35.5, soft=1) # mouth corner+t.reflect(floor * (1 - cat_all) * t.radial(cfx, cfy, 1.2 * u, 0.6 * u, 1.0, 0.0), cfy, strength=0.3, blur_px=6, fade=50)+t.stage('cat')++# =========================================================== 7. measurements+t.spot(px0 - R * 0.35, (rim + py0) / 2 + 6, 'Sp1', name='pot')+t.spot(*P(-1.72, 1.13, 4.42), 'Sp2', name='fridge', side='ne')+t.spot(*C(-0.12, 0.45), 'Sp3', name='cat', side='ne', r=11)+t.box(bx - 0.15 * F / ZB, by - 0.15 * F / ZB, cx + 0.17 * F / ZB, by + 6, 'Bx1', name='bread')+p_a, p_b = P(-1.65, 0, 3.47), P(0.40, 0, 3.22)+t.profile(p_a, p_b, inset=(1500, 452, 390, 170), label='L1', name='floor')+t.hottest()+t.coldest()+t.results(1550, 66, width=350)+t.save(out, stages_dir=stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/vhs_birthday.jpg b/examples/vhs_birthday.jpgnew file mode 100644index 0000000..a7d27e2Binary files /dev/null and b/examples/vhs_birthday.jpg differdiff --git a/examples/vhs_birthday.py b/examples/vhs_birthday.pynew file mode 100644index 0000000..1f27121--- /dev/null+++ b/examples/vhs_birthday.py@@ -0,0 +1,115 @@+"""Example (VHS home video / VHS 家庭录像): 吹蜡烛 · Blow Out the Candles — one frame of a family's home video.+A 1970s living room (avocado-and-orange ring wallpaper, walnut panelling on the side wall, flowered drapes at a dusk+window, a console TV with rabbit ears, a rust velour sofa, gold shag carpet) is dressed for a birthday: crepe+streamers, a pennant string HAPPY BIRTHDAY, balloons tied to the TV, one escaped to the ceiling, a teddy bear guest+in a party hat. On the coffee table: the cake with six candles -- four just blown out and smoking, the last two+still bending away -- paper plates, striped cups, a blower, a present. The birthday child leans in over the cake,+seen from behind, out of focus right in front of the lens: whoever is filming stands just behind and is zooming in.+The camcorder is on 'outdoor' white balance under tungsten light (orange room, blue window); the candles and the+lamp clip, bloom, smear vertically and leave a short lag tail; the OSD is mixed in and goes on tape with the picture;+the tape adds chroma bleed, edge halos, noise, jitter, a tracking band, head-switching noise and dropouts.+Draw-on stages: walls -> window & furniture -> party -> cake -> child -> camera -> tape -> wear -> OSD.+python3 vhs_birthday.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from vhs import VHSCamcorder++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'vhs_birthday.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++# one-point perspective: camera 1.1 m up, back wall 4 m away+F, VX, VY, EYE = 1150.0, 1000.0, 430.0, 1.1+++def P(X, Y, Z):+ return (VX + F * X / Z, VY - F * (Y - EYE) / Z)+++v = VHSCamcorder(1920, 1080, seed=16, keep_stages=stages is not None)+v.ambient('#ffd9a8', 0.34)+v.light(1000, -260, 1500, '#ffe2b8', 0.12) # ceiling bounce++# ================================================================ 1. walls, ceiling, carpet+xb_l, y_ceil = P(-2.6, 2.4, 4.0); _, y_floor = P(0, 0, 4.0)+v.ceiling(v.poly([(0, -300), (1920, -300), (1920, y_ceil), (xb_l, y_ceil), (0, y_ceil - xb_l * 0.5)]))+back = v.rect(xb_l, y_ceil, 1920, y_floor)+v.wallpaper(back, tile=118, x0=xb_l, y0=y_ceil, contrast=0.72)+v.paint(v.rect(xb_l, y_floor - 22, 1920, y_floor), '#d9c9a2', form=0.3, form_r=4) # baseboard+left = v.poly([(0, y_ceil - xb_l * 0.5), (xb_l, y_ceil), (xb_l, y_floor), (0, y_floor + xb_l * 0.423)])+v.paneling(left, [P(-2.6, 0, z)[0] for z in (4.0, 3.75, 3.5, 3.25, 3.02)])+v.shadow(v.rect(xb_l - 4, y_ceil, xb_l + 4, y_floor), 0.5, 10) # the corner+floor = v.poly([(0, y_floor + xb_l * 0.423), (xb_l, y_floor), (1920, y_floor), (1920, 1080), (0, 1080)])+v.shag(floor, '#c8962e')+v.shadow(v.rect(0, y_floor - 4, 1920, y_floor + 6), 0.35, 8)+v.stage('walls')++# ================================================================ 2. window, drapes, TV, lamp, sofa+wx0, wy0 = P(-2.25, 2.05, 4.0); wx1, wy1 = P(-1.15, 0.95, 4.0)+v.window(wx0, wy0, wx1, wy1)+v.light((wx0 + wx1) / 2, (wy0 + wy1) / 2, 360, '#86a2ff', 0.10)+v.rod(wx0 - 70, wx1 + 70, wy0 - 30)+v.curtain(wx0 - 66, wx0 + 44, wy0 - 30, wy1 + 70, folds=3, seed=4)+v.curtain(wx1 - 46, wx1 + 64, wy0 - 30, wy1 + 70, folds=3, seed=9)++tx0, ty0 = P(-0.6, 0.8, 3.55); tx1, ty1 = P(0.75, 0, 3.55)+v.console_tv(tx0, ty0, tx1, ty1)+v.rabbit_ears(tx1 - 90, ty0 - 8)+lx, lf = P(0.95, 0, 3.85)+v.floor_lamp(lx + 6, lf, 296, shade_w=124, shade_h=90)+v.sofa(1352, 2010, 500, 640, 712, 812, colour='#667c30')+v.stage('furniture')++# ================================================================ 3. party: streamers, pennants, balloons, teddy+v.streamer((xb_l + 10, y_ceil + 2), (1010, y_ceil - 8), 46, '#e8702a', width=18, twists=11)+v.streamer((1010, y_ceil - 8), (1925, y_ceil + 4), 52, '#3a7ad0', width=18, twists=12)+v.pennants((372, 92), (1858, 102), 84, 'HAPPY BIRTHDAY', ['#d83a2e', '#f2b51e', '#2f6fc8', '#4aa04a', '#e8702a'], size=96)+tie = (tx0 + 34, ty0 - 4)+for x, y, r, c, rot in ((880, 352, 50, '#d42a22', -12), (968, 300, 48, '#f2c21e', 6), (1052, 362, 46, '#2f6fc8', 14),+ (920, 430, 44, '#3f9a3c', -4)):+ v.balloon(x, y, r, c, string_to=tie, sag=-14 if x < 930 else 18, rot=rot)+v.balloon(1724, 104, 44, '#e85a8c', rot=4) # got away: pressed to the ceiling+v.paint(v.line([(1726, 160), (1716, 260), (1730, 360), (1722, 450)], 1.6), '#d9d2c4', 0.8)+v.teddy(1574, 560, 46, fur='#b0743a')+v.stage('party')++# ================================================================ 4. the table: cake, plates, cups, present+q = [P(-0.7, 0.42, 2.2), P(1.1, 0.42, 2.2), P(1.1, 0.42, 1.6), P(-0.7, 0.42, 1.6)]+v.coffee_table(q, thick=28, legs=[(560, 948, 1080), (1735, 948, 1080)], gloss=(1330, 808))+v.plates(812, 840, 74, 20)+v.blower(1000, 902, colour='#2f6fc8')+v.cup(1372, 842, 46, 64, '#d23a2e')+v.cup(1442, 880, 48, 66, '#2f6fc8')+v.present(1500, 772, 118, 82, 52)+v.confetti((560, 800, 1700, 930), n=70)+cx, ctop = P(0.2, 0.53, 1.95)+candles = [(150, '#e8702a', 1.0), (90, '#2f6fc8', 0.9), (210, '#d83a2e', 0.8), (30, '#4aa04a', 0.7),+ (270, '#f2b51e', 'lit'), (330, '#e85a8c', 'lit')]+tips = v.cake(cx, ctop, 110, 33, 68, candles, sprinkles=['#e04848', '#f2c230', '#3a8ad8', '#5cb85c'], lean=(1.0, -0.2))+for x, y in tips:+ v.light(x, y, 280, '#ffa048', 0.3)+ v.glow(v.ellipse(x - 10, ctop + 110, 300, 70), '#ff9a40', 0.12)+v.stage('cake')++# ================================================================ 5. the birthday child, out of focus in front of the lens+with v.layer(defocus=4.5):+ v.child_back(668, 600, 92, lean=24, glow_from=(cx + 20, ctop - 40))+v.stage('child')++# ================================================================ 6-8. camcorder, tape, playback wear+v.camera(tilt=-1.6, white_balance=(1.06, 0.95, 0.74), exposure=1.07, knee=0.74, lag=(-24, 0, 0.3))+v.stage('camera')+v.record()+v.stage('tape')+v.wear(tracking=(0.94, 0.04))+v.stage('wear')++# ================================================================ 9. the camcorder's OSD (mixed into the signal before the tape)+v.rec(150, 100)+v.battery(150, 178, px=7, level=1)+v.counter('0:14:32', 1770, 100)+v.datestamp('7:42 PM', 'JUN.16.1984', 150, 864)+v.zoom_bar(1300, 934, pos=0.72, px=7, width=300)+v.save(out, stages_dir=stages)+print(f'{out} {time.time() - t0:.1f}s')diff --git a/examples/xray_luggage.jpg b/examples/xray_luggage.jpgnew file mode 100644index 0000000..205c5d1Binary files /dev/null and b/examples/xray_luggage.jpg differdiff --git a/examples/xray_luggage.py b/examples/xray_luggage.pynew file mode 100644index 0000000..281c244--- /dev/null+++ b/examples/xray_luggage.py@@ -0,0 +1,442 @@+"""Example (X-ray / X 光片): 行李安检 · Bag 0417 — a hard-shell suitcase on the belt of a dual-energy baggage+scanner, seen from the top. Everything in it is built as real material along the beam and shot through with+Beer-Lambert, so the case's walls glow at its outline, the aluminium trolley rails show four edges each (two+nested tubes), the wheels show their ball bearings and the axle bolts seen end-on, and everything overlaps+additively. Inside: a compact umbrella (telescopic shaft, eight folded ribs, wrapped canopy, push-button spring),+a travel hairdryer (motor windings, magnets, a coiled-coil heating element on a mica cross, switch, mains cord+and plug), a camera lying on its back (lens barrel rings seen end-on, glass elements, aperture iris, battery, BGA+chips), a key ring with a car fob (coin cell), coins, a folded sweater and jeans (rivets, button, fly zip), a+rolled T-shirt, a bottle of water -- and a toy dinosaur skeleton: a plaster fossil kit with a steel pin through+its spine on a display stand. The scanner flags the skeleton as bone-like and the bottle as a liquid; the side+panel shows the same bag in the material (pseudo-colour) display, a zoom on object 1, and the operator's verdict:+1 is a toy (clear), 2 is over 100 ml (remove). Zeff and volume are measured off the picture.+Draw-on stages: belt -> suitcase -> clothes -> umbrella -> hairdryer -> camera and keys -> skeleton and bottle ->+flags -> material view -> verdict. No image model.+python3 xray_luggage.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from xray import XRay, AMBER, GREEN, RED, CYAN++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'xray_luggage.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+t0 = time.time()++x = XRay(1920, 1080, px_cm=17, seed=417)+CX, CY, ROT = 742.0, 548.0, -1.2 # the case on the belt (case coords u, v: px from its centre)+++def K(P, ox=0.0, oy=0.0, rot=0.0, s=1.0):+ """local points -> case coords (move, rotate, scale) -> canvas"""+ return XRay.poly(XRay.poly(np.asarray(P, np.float32)[:, :2], ox, oy, rot, s), CX, CY, ROT)+++def k(u, v):+ return K([(u, v)])[0]+++def R(u, v, w, h, r=0.0, rot=0.0):+ return K(XRay.rrect(0, 0, w, h, r, rot), u, v)+++def E(u, v, rx, ry, rot=0.0, n=72):+ return K(XRay.ellipse(0, 0, rx, ry, rot, n), u, v)+++def loop(P):+ return np.vstack([P, P[:1]])+++# =========================================================== 1. the belt+x.belt(118, 978, lacing=34)+x.status(['XR-160 DV · LANE 3', 'BAG 0417 VIEW A / TOP 140 kV 0.8 mA'],+ ['07:42:18', '2026-10-02 BELT 0.20 m/s'])+x.stage('belt')++# =========================================================== 2. the suitcase+x.shell(R(0, 0, 1210, 726, 100), 'organic', 425, 5, edge=68, density=1.2) # 25 cm deep polycarbonate+for v in (-300, -235, 235, 300): # moulded ridges in both faces+ x.rod(K([(-520, v), (520, v)]), 'organic', 7, flat=5, density=1.2)+x.rod(loop(R(0, 0, 1194, 710, 92)), 'organic', 3.2, flat=15, ribs=(0.55, 3.4)) # nylon coil zip round the rim+for su in (318, 372): # zip sliders + pull tabs+ x.slab(R(su, -355, 46, 13, 5), 'zinc', 22, edge=5)+ x.slab(R(su + (14 if su > 340 else -14), -347, 40, 4, 2), 'zinc', 40, edge=2)+# TSA-style combination lock in the top wall+x.slab(R(470, -358, 120, 28, 8), 'zinc', 60, edge=10, holes=[R(470, -358, 70, 10, 4)])+for du in (-24, 0, 24):+ x.slab(R(470 + du, -358, 7, 22, 3), 'brass', 22, edge=8)+x.coil(k(420, -352), k(452, -352), 4, 6, 'steel', 0.9)+x.rod(K([(492, -350), (512, -350), (512, -340)]), 'steel', 1.8)+# trolley: two nested aluminium tube stages per rail, lock rods, return springs, rivets, end blocks+for sv in (-1, 1):+ v = sv * 195+ x.shell(R(18, v, 1128, 38, 4), 'aluminium', 22, 2.2, edge=3)+ x.shell(R(42, v, 1106, 29, 3), 'aluminium', 16, 1.8, edge=3)+ x.rod(K([(-520, v), (566, v)]), 'steel', 2.0)+ x.coil(k(-548, v), k(-480, v), 6, 9, 'steel', 1.0)+ for uu in (-530, -40, 548):+ x.disc(*k(uu, v + sv * 26), 5.5, 'steel', 13, rim=(1.5, 3))+ x.slab(R(-538, v, 52, 74, 10), 'organic', 32, edge=8, density=1.1)+# grip at the handle end: plastic shell, push-button spring, release cables to the lock rods+x.shell(R(588, 0, 40, 470, 14), 'organic', 55, 3.5, edge=14, density=1.1)+x.coil(k(588, -34), k(588, 34), 7, 7, 'steel', 1.0)+for sv in (-1, 1):+ x.rod(K([(588, sv * 30), (580, sv * 110), (570, sv * 175), (566, sv * 195)]), 'steel', 1.0)+# top carry handle and its screws (seen from the side)+x.shell(R(60, -378, 260, 32, 16), 'organic', 40, 3, edge=16, density=1.1)+for su in (-48, 168):+ x.slab(R(su, -352, 44, 8, 2), 'steel', 26, edge=3)+ x.screw(k(su, -392), k(su, -347), 3.2, head=(15, 5))+# spinner wheels at the bottom end: front and back units nearly overlap in this view+for sv in (-1, 1):+ x.shell(R(-597, sv * 298, 92, 116, 30), 'organic', 90, 4, edge=28, density=1.1)+ x.slab(R(-612, sv * 298, 70, 96, 22), 'steel', 2.6, edge=1) # fork plates+ for b in range(8):+ x.ball(*k(-585, sv * 298 - 26 + b * 7.4), 2.6, 'steel') # swivel bearing, edge-on+ for (du, dv) in ((0, 0), (6, -sv * 15)):+ c = k(-628 + du, sv * 298 + dv)+ x.disc(*c, 36, 'rubber', 34, hole=22)+ x.disc(*c, 22, 'organic', 28, hole=11, density=1.1)+ x.disc(*c, 11, 'steel', 7, hole=8.6)+ for b in range(7):+ a = 2 * np.pi * b / 7+ x.ball(c[0] + 7.1 * np.cos(a), c[1] + 7.1 * np.sin(a), 1.9, 'steel')+ x.disc(*c, 5.0, 'steel', 7, hole=3.2)+ x.disc(*c, 3.0, 'steel', 70) # axle bolt end-on+x.stage('suitcase')++# =========================================================== 3. clothes+x.fabric(R(300, -175, 560, 320, 50, 1.5), 140, layers=8, sheet=4, density=0.5, weave='knit', scale=7,+ angle=ROT + 1.5, creases=[K([(40, -178), (560, -172)]), K([(140, -320), (146, -30)]),+ K([(462, -322), (458, -28)])])+x.fabric(R(312, 180, 590, 290, 30, -2), 100, layers=8, sheet=2.4, density=1.15, weave='twill', scale=5,+ angle=ROT - 2, creases=[K([(30, 182), (600, 168)]), K([(200, 40), (196, 322)])])+for (u, v) in ((70, 70), (98, 300), (540, 64), (575, 292), (330, 46), (330, 316)):+ x.disc(*k(u, v), 4.2, 'copper', 6, dome=3) # jeans rivets+x.disc(*k(150, 120), 9.5, 'brass', 7, hole=2.4, rim=(2.2, 2.5)) # jeans button+x.zipper(K([(170, 150), (320, 158)]), 'brass', tooth=(7, 4.4), depth=3, tape=11) # fly zip+x.slab(R(520, 118, 64, 40, 4, -2), 'organic', 5, edge=1, density=1.0) # leather patch+# rolled T-shirt: a soft cylinder with the spiral of its layers showing at the ends+x.slab(R(-345, 130, 280, 118, 50, 4), 'organic', 118, density=0.28, texture=x.weave('plain', 4, ROT + 4, 0.2))+for j in range(4):+ x.rod(K([(-480 + 6 * j, 80 + 4 * j), (-484 + 6 * j, 180 - 4 * j)]), 'organic', 2.4, density=0.7)+ x.rod(K([(-210 - 6 * j, 80 + 4 * j), (-206 - 6 * j, 180 - 4 * j)]), 'organic', 2.4, density=0.7)+x.stage('clothes')++# =========================================================== 4. the umbrella (compact, folded)+UA, UB = np.array(k(-575, 305)), np.array(k(-78, 148))+ue = (UB - UA) / np.linalg.norm(UB - UA)+un = np.array([-ue[1], ue[0]])+UL = float(np.linalg.norm(UB - UA))+++def U(s, o=0.0):+ return UA + ue * s + un * o+++x.rod(np.stack([U(0), U(112)]), 'organic', 21, density=1.15) # handle+x.coil(U(18), U(66), 6, 8, 'steel', 1.1) # auto-open button spring+x.rod(np.stack([U(4, -9), U(30, -9)]), 'steel', 1.6) # catch+for (s0, s1, r) in ((70, 300, 6.8), (100, 410, 5.6), (150, 478, 4.5)): # telescopic shaft+ x.tube(np.stack([U(s0), U(s1)]), 'steel', r, 0.75)+x.rod(np.stack([U(250), U(292)]), 'organic', 11, density=1.1) # runner+x.rod(np.stack([U(458), U(492)]), 'organic', 9, density=1.1) # top notch+x.rod(np.stack([U(490), U(UL + 8)]), 'steel', 3.0) # ferrule+offs = [16 * np.cos(2 * np.pi * (j + 0.3) / 8) for j in range(8)] # ribs bundled round the shaft+for j, o in enumerate(offs):+ o1, o2, o3 = o, o * 1.25 + 1.5, o * 1.5 - 1.5+ rib = [U(470, o1), U(262, o1 * 1.05)]+ x.rod(np.stack(rib), 'steel', 1.2) # main rib+ x.rod(np.stack([U(262, o2), U(440, o2)]), 'steel', 1.05) # second section+ x.rod(np.stack([U(440, o3), U(300, o3)]), 'steel', 0.95) # tip section+ x.rod(np.stack([U(285, o * 0.6), U(372, o * 1.0)]), 'steel', 0.8) # stretcher+ for (s, oo) in ((262, (o1 + o2) / 2), (440, (o2 + o3) / 2)):+ x.disc(*U(s, oo), 2.3, 'steel', 5) # joint rivets+ x.ball(*U(300, o3), 2.4, 'organic', density=1.2) # rib tip caps+spindle = np.vstack([U(s, h) for s, h in zip(np.linspace(232, 495, 14), 34 * np.sin(np.linspace(0, np.pi, 14)) ** 0.7 + 7)] ++ [U(s, -h) for s, h in zip(np.linspace(495, 232, 14), 34 * np.sin(np.linspace(np.pi, 0, 14)) ** 0.7 + 7)])+x.fabric(XRay.closed(spindle, 4), 60, layers=14, sheet=1.2, density=1.3, weave=None,+ creases=[x.path([U(244 + 32 * j, -30), U(266 + 32 * j, 0), U(292 + 32 * j, 30)], 6) for j in range(7)])+x.rod(np.stack([U(372, -44), U(372, 44)]), 'organic', 15, flat=5, density=1.0) # strap+x.disc(*U(372, 40), 7, 'brass', 3, hole=2.5, rim=(1.5, 1.5)) # snap+x.stage('umbrella')++# =========================================================== 5. the hairdryer (side view, nozzle to the right)+HO, HR = (-555, -262), 0.0+++def H(P):+ return K(P, *HO, HR)+++def h(a, b):+ return H([(a, b)])[0]+++x.shell(H(XRay.rrect(150, 0, 300, 118, 26)), 'organic', 118, 4, edge=59, density=1.3) # barrel+x.shell(H([(296, -56), (352, -36), (352, 36), (296, 56)]), 'organic', 70, 3, edge=24, density=1.2) # nozzle+x.edgeon(h(10, -54), h(10, 54), 9, 'organic', density=0.7) # intake grille+x.edgeon(h(20, -52), h(20, 52), 1.6, 'steel', density=0.35) # filter mesh+for j in range(7):+ x.edgeon(h(300 + 7 * j, -50 + 2 * j), h(300 + 7 * j, 50 - 2 * j), 1.6, 'organic', density=1.0) # outlet slots+# motor: steel can, ferrite magnets, copper windings, shaft, fan+x.shell(H(XRay.rrect(78, 0, 72, 58, 6)), 'steel', 58, 1.1, edge=29)+for sv in (-1, 1):+ x.slab(H(XRay.rrect(78, sv * 21, 54, 8, 2)), 'ferrite', 42, edge=6)+x.slab(H(XRay.rrect(78, 0, 46, 30, 6)), 'copper', 30, edge=10, density=0.5)+x.rod(H([(34, 0), (152, 0)]), 'steel', 2.3)+x.slab(H(XRay.rrect(122, 0, 10, 22, 2)), 'copper', 22, edge=8, density=0.8) # commutator+x.edgeon(h(150, -50), h(150, 50), 14, 'organic', density=0.6) # fan (edge-on)+for j in range(6):+ x.rod(H([(143 + 2 * j, -46 + 18 * j), (157 - 2 * j, -38 + 18 * j)]), 'organic', 1.5, density=1.2)+# heating element: mica cross (one plate edge-on, one face-on) with a coiled-coil nichrome wire+x.rod(H([(176, 0), (284, 0)]), 'mica', 0.8, flat=96)+x.slab(H(XRay.rrect(230, 0, 108, 96, 2)), 'mica', 1.0, edge=0)+x.coil(h(180, 0), h(282, 0), 44, 7, 'steel', 2.4, ribs=(0.6, 2.7))+x.rod(H([(282, 30), (286, 46), (250, 52), (180, 50), (120, 54), (112, 66)]), 'copper', 1.1) # leads+# handle: shell, switch with brass contacts and spring, rectifier board, strain relief, hanging loop+HG = XRay.rrect(0, 0, 56, 196, 26)+x.shell(K(HG, *np.array(HO) + (118, 156), -8), 'organic', 66, 3, edge=26, density=1.2)+x.slab(H(XRay.rrect(116, 96, 26, 50, 4)), 'organic', 30, edge=4, density=1.1)+for (a, b) in ((106, 80), (126, 80), (106, 112), (126, 112)):+ x.slab(H(XRay.rrect(a, b, 9, 14, 1)), 'brass', 10, edge=2)+x.coil(h(116, 120), h(116, 140), 4, 5, 'steel', 0.8)+x.slab(H(XRay.rrect(126, 172, 34, 24, 2, -8)), 'pcb', 2.6, edge=0)+for (a, b) in ((116, 166), (130, 166), (116, 178), (130, 178)):+ x.disc(*h(a, b), 2.6, 'tin', 2.4)+x.rod(H([(124, 70), (110, 130), (128, 230)]), 'copper', 1.0)+x.rod(H([(132, 70), (132, 130), (138, 230)]), 'copper', 1.0)+x.rod(H([(134, 228), (138, 262)]), 'rubber', np.array([8, 6.5], np.float32), ribs=(0.18, 4.0))+x.rod(loop(H(XRay.ellipse(150, 260, 14, 9, -8))), 'organic', 2.6, density=1.1)+# mains cord and plug+cord = x.path(K([(-417, -2), (-440, 50), (-500, 92), (-548, 70), (-530, 10), (-470, -12), (-392, 40),+ (-300, 90), (-236, 70), (-210, 30)]), 14)+x.cable(cord, 6.0, 2, 1.25)+pl = np.array(k(-208, 2))+x.slab(R(-208, -10, 38, 60, 10), 'organic', 32, edge=10, density=1.15)+for du in (-10, 10):+ x.rod(K([(-208 + du, -40), (-208 + du, -78)]), 'brass', 2.4)+x.stage('hairdryer')++# =========================================================== 6. the camera (on its back, lens up), keys, coins+CC = (-128, -100)+++def cam(u, v):+ return k(CC[0] + u, CC[1] + v)+++x.shell(R(CC[0], CC[1], 208, 124, 16), 'magnesium', 68, 2.4, edge=12)+x.slab(R(CC[0] + 82, CC[1], 46, 118, 16), 'rubber', 40, edge=12, density=0.9) # grip+bat = R(CC[0] + 82, CC[1] + 4, 26, 92, 4)+x.shell(bat, 'steel', 64, 0.6, edge=2)+x.slab(R(CC[0] + 82, CC[1] + 4, 24, 90, 3), 'copper', 62, edge=2, density=0.075)+for j in range(1, 4):+ x.rod(loop(R(CC[0] + 82, CC[1] + 4, 24 - 6 * j, 90 - 6 * j, 3)), 'copper', 0.6, flat=40)+x.slab(R(CC[0] - 10, CC[1] + 6, 150, 96, 6), 'pcb', 2.8, edge=0) # main board+for (du, dv, w, hh) in ((-58, -22, 26, 26), (-58, 26, 22, 16), (40, -26, 30, 30), (36, 26, 20, 20)):+ x.slab(R(CC[0] + du, CC[1] + dv, w, hh, 1), 'glass', 2.0, edge=0)+ n = int(w // 5)+ for a in range(n):+ for b in range(int(hh // 5)):+ x.disc(*cam(du - w / 2 + 2.5 + a * 5, dv - hh / 2 + 2.5 + b * 5), 1.5, 'tin', 2.6) # BGA balls+x.slab(R(CC[0] - 22, CC[1], 60, 42, 3), 'glass', 4, edge=0) # sensor package+x.slab(R(CC[0] - 4, CC[1] + 2, 140, 92, 4), 'glass', 4.5, edge=0) # rear screen+for (du, dv) in ((-96, -52), (-96, 52), (70, -54), (60, 56)):+ x.disc(*cam(du, dv), 2.3, 'steel', 9) # body screws end-on+x.disc(*cam(-22, 50), 6, 'brass', 10, hole=3.2) # tripod socket+x.slab(R(CC[0] - 22, CC[1] - 60, 40, 10, 2), 'steel', 3.4, edge=1) # hot shoe+for du in (-34, -10):+ x.coil(cam(du, -66), cam(du + 6, -66), 2.5, 4, 'steel', 0.6)+for su in (-1, 1): # strap lugs+ c = cam(su * 108, -42)+ x.rod(loop(np.array([c + (-6, 6), c + (6, 6), c + (0, -6)], np.float32)), 'steel', 1.6)+strap = x.path(K([(-236, -144), (-272, -106), (-286, -40), (-262, 16), (-206, 36), (-150, 40)]), 14)+x.rod(strap, 'organic', 17, flat=5, density=0.9)+# lens: barrel rings seen end-on, glass elements, iris, mount+LC = cam(-22, 0)+x.disc(*LC, 56, 'rubber', 26, hole=51.5, density=0.9) # focus ring+x.disc(*LC, 51, 'aluminium', 86, hole=48.6) # outer barrel+x.disc(*LC, 43, 'aluminium', 70, hole=41.0) # inner barrel+x.disc(*LC, 47, 'steel', 7, hole=38) # bayonet mount+for a in range(3):+ th = np.radians(30 + 120 * a)+ x.disc(LC[0] + 44 * np.cos(th), LC[1] + 44 * np.sin(th), 2.4, 'steel', 9) # mount screws+x.disc(*LC, 40, 'glass', 4, dome=14) # front element+x.disc(*LC, 30, 'glass', 5, dome=10)+x.disc(*LC, 30, 'glass', 8, dome=-5) # doublet+x.disc(*LC, 23, 'glass', 4, dome=8)+iris_hole = XRay.poly([(14 * np.cos(np.radians(a)), 14 * np.sin(np.radians(a))) for a in np.arange(0, 360, 360 / 7) + 9], *LC)+x.slab(XRay.ellipse(*LC, 34, 34, n=80), 'steel', 1.4, edge=0, holes=[iris_hole])+# key ring: split ring (two turns), two brass keys, a car fob with a coin cell+KR = np.array(k(-40, 58))+for rr in (24, 26.2):+ x.rod(loop(XRay.ellipse(*KR, rr, rr, n=90)), 'steel', 1.15)+KEY = [(0, -26), (20, -24), (30, -12), (34, -9), (150, -9), (152, -7), (160, 0), (156, 7), (148, 9), (142, 9),+ (138, 5), (132, 9), (124, 4), (116, 9), (108, 5), (100, 9), (92, 3), (84, 9), (34, 9), (30, 12), (20, 24),+ (0, 26), (-14, 16), (-18, 0), (-14, -16)]+for ang, mat in ((52, 'brass'), (78, 'brass')):+ kc = KR + 24 * np.array([np.cos(np.radians(ang)), np.sin(np.radians(ang))])+ x.slab(XRay.poly(KEY, *kc, ang), mat, 3.4, edge=1.0, holes=[XRay.poly(XRay.ellipse(-2, 0, 6.5, 6.5, n=30), *kc, ang)])+ for gy in (-3.5, 3.0): # milled grooves+ x.slab(XRay.poly(XRay.rrect(94, gy, 108, 2.2, 1), *kc, ang), mat, 1.4, edge=0, density=-1.0)+fob_c = KR + 30 * np.array([np.cos(np.radians(150)), np.sin(np.radians(150))])+FA = 150+x.shell(XRay.poly(XRay.rrect(-46, 0, 92, 52, 22), *fob_c, FA), 'organic', 26, 2.4, edge=10, density=1.2)+x.slab(XRay.poly(XRay.rrect(-50, 0, 60, 34, 3), *fob_c, FA), 'pcb', 2.4, edge=0)+x.disc(*XRay.poly([(-56, 0)], *fob_c, FA)[0], 10, 'steel', 5.4, rim=(1.0, 0.6)) # CR2032 coin cell+x.slab(XRay.poly(XRay.rrect(-26, 0, 8, 6, 1), *fob_c, FA), 'glass', 3, edge=0)+x.slab(XRay.poly(XRay.rrect(-120, 2, 60, 12, 3), *fob_c, FA), 'steel', 3, edge=1) # folded blade+for (u, v, r, m) in ((150, 30, 13, 'brass'), (186, 62, 11.5, 'steel'), (128, 78, 12.5, 'brass')):+ x.disc(*k(u, v), r, m, 3.2, rim=(2.0, 1.2), density=0.85 if m == 'steel' else 1.0)+x.stage('camera_keys')++# =========================================================== 7. the toy dinosaur skeleton and the bottle+DO, DR, DS = (208, -212), -3.0, 1.02+BF = 1.6 # cast bones are chunky+++def D(P):+ return K(P, *DO, DR, DS)+++def d(a, b):+ return D([(a, b)])[0]+++SP = [(-250, 34), (-205, 16), (-160, 0), (-115, -12), (-70, -22), (-30, -28), (0, -30), (40, -32), (80, -30),+ (118, -26), (148, -22), (170, -26), (186, -36), (198, -48), (206, -58)]+sp = XRay.path(SP, 16)+segl = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(sp, axis=0), axis=1))])+pos, s = [], 6.0+while s < segl[-1] - 4:+ u_ = np.interp(s, segl, sp[:, 0])+ pos.append(s)+ s += 7 + 6 * float(np.clip((u_ + 250) / 200, 0, 1))+for s in pos:+ c = np.array([np.interp(s, segl, sp[:, 0]), np.interp(s, segl, sp[:, 1])])+ j = min(np.searchsorted(segl, s), len(sp) - 1)+ t = sp[j] - sp[max(j - 1, 0)]+ t = t / (np.linalg.norm(t) + 1e-6)+ n = np.array([t[1], -t[0]]) # up+ u_ = c[0]+ r = 3 + 6 * np.clip((u_ + 250) / 220, 0, 1) - (1.5 if u_ > 160 else 0)+ ang = np.degrees(np.arctan2(t[1], t[0]))+ gap = 7 + 6 * float(np.clip((u_ + 250) / 200, 0, 1))+ x.slab(D(XRay.rrect(c[0], c[1], gap * 0.78, 2 * r, r * 0.55, ang)), 'plaster', 2.2 * r * DS * BF, tag='dino')+ hs = (26 if -40 < u_ < 150 else 18 if u_ <= -40 else 9) * (0.4 + 0.6 * np.clip((u_ + 250) / 120, 0, 1))+ x.rod(D([c + n * r * 0.7, c + n * (r + hs) - t * hs * 0.25]), 'plaster', np.array([r * 0.36, r * 0.24]) * DS * BF,+ tag='dino')+ if u_ < -15:+ hc = 15 * np.clip((u_ + 250) / 200, 0.25, 1)+ x.rod(D([c - n * r * 0.7, c - n * (r + hc) - t * hc * 0.4]), 'plaster',+ np.array([r * 0.3, r * 0.18]) * DS * BF, tag='dino')+x.rod(D([tuple(p) for p in sp[(sp[:, 0] > -180) & (sp[:, 0] < 200)]]), 'steel', 1.1) # steel pin in the spine+SK = np.array([-6, 22], np.float32) # skull offset from the original sketch+skull = XRay.closed(np.array([(206, -94), (226, -108), (256, -112), (292, -106), (320, -97), (335, -86), (333, -74),+ (300, -70), (262, -68), (230, -66), (210, -72)]) + SK, 8)+holes = [XRay.ellipse(*(np.array(c) + SK), *rr_) for c, rr_ in (((241, -96), (9, 8)), ((274, -88), (15, 7, -4)),+ ((218, -86), (6, 9, 10)), ((312, -88), (4, 3)))]+x.slab(D(skull), 'plaster', 54 * DS, edge=18 * DS, holes=[D(hh) for hh in holes], tag='dino')+jaw = XRay.closed(np.array([(220, -63), (262, -60), (300, -61), (327, -69), (324, -58), (292, -50), (252, -48),+ (222, -53)]) + SK, 8)+x.slab(D(jaw), 'plaster', 34 * DS, edge=11 * DS, holes=[D(XRay.ellipse(240, -33, 9, 3))], tag='dino')+for i in range(9):+ a = 232 + i * 11+ ln = 9 - i * 0.35+ yu = -68 - (i * 0.5)+ x.slab(D(np.array([(a - 3, yu), (a + 3, yu), (a + 0.5, yu + ln)]) + SK), 'plaster', 7 * DS, edge=2, tag='dino')+ x.slab(D(np.array([(a + 1, -61 + i * -0.6), (a + 6, -61 + i * -0.6), (a + 3.5, -61 - ln * 0.8)]) + SK),+ 'plaster', 6 * DS, edge=2, tag='dino')+for i, u_ in enumerate(np.linspace(30, 150, 9)): # ribs+ v0 = float(np.interp(u_, sp[:, 0], sp[:, 1]))+ L = 58 + 26 * np.sin(np.pi * (u_ - 30) / 120)+ rib = XRay.path([(u_, v0 + 5), (u_ - 4, v0 + 26), (u_ - 13, v0 + L * 0.75), (u_ - 22, v0 + L)], 8)+ x.rod(D(rib), 'plaster', (np.linspace(4.2, 1.8, len(rib)) * DS) * BF, tag='dino')+for i, u_ in enumerate(np.linspace(42, 138, 6)): # gastralia+ x.rod(D(XRay.path([(u_ - 10, 50), (u_, 56), (u_ + 10, 50)], 6)), 'plaster', (1.3 * DS) * BF, tag='dino')+x.slab(D(XRay.ellipse(5, -46, 44, 13, -3)), 'plaster', 22 * DS, edge=8 * DS, tag='dino') # ilium+x.rod(D([(8, -30), (38, 44)]), 'plaster', (np.array([5.5, 4.0]) * DS) * BF, tag='dino') # pubis+x.slab(D(XRay.ellipse(40, 49, 20, 6, 10)), 'plaster', 12 * DS, tag='dino')+x.rod(D([(-6, -30), (-32, 22)]), 'plaster', (np.array([5.0, 2.4]) * DS) * BF, tag='dino') # ischium+x.slab(D(XRay.ellipse(150, -12, 22, 6, 62)), 'plaster', 12 * DS, tag='dino') # scapula+for (hip, knee, ankle, ball, toe) in (((0, -28), (30, 48), (10, 118), (34, 145), (60, 151)),+ ((-4, -28), (-26, 50), (-52, 112), (-40, 143), (-16, 150))):+ x.rod(D([hip, knee]), 'plaster', (np.array([7.5, 6.0]) * DS) * BF, tag='dino')+ for p in (hip, knee):+ x.slab(D(XRay.ellipse(p[0], p[1], 8.5, 7.5)), 'plaster', 15 * DS, tag='dino')+ x.rod(D([knee, ankle]), 'plaster', (np.array([5.8, 4.4]) * DS) * BF, tag='dino')+ x.rod(D([(knee[0] + 6, knee[1] + 6), (ankle[0] + 6, ankle[1] - 4)]), 'plaster', (1.8 * DS) * BF, tag='dino')+ for dd in (-4, 0, 4):+ x.rod(D([ankle, (ball[0] + dd * 0.6, ball[1] + dd * 0.4)]), 'plaster', (2.7 * DS) * BF, tag='dino')+ for dd in (-4, 0, 3):+ p1 = (ball[0] + 12, ball[1] + 3 + dd)+ x.rod(D([ball, p1, (toe[0], toe[1] + dd * 0.8)]), 'plaster', (np.array([2.4, 2.0, 1.4]) * DS) * BF, tag='dino')+ x.slab(D([(toe[0], toe[1] + dd * 0.8 - 3), (toe[0] + 9, toe[1] + dd * 0.8 + 2), (toe[0], toe[1] + dd * 0.8 + 3)]),+ 'plaster', 5 * DS, edge=1.5, tag='dino')+x.rod(D([(150, -6), (164, 16)]), 'plaster', (3.0 * DS) * BF, tag='dino') # arm+x.rod(D([(164, 16), (176, 26)]), 'plaster', (2.0 * DS) * BF, tag='dino')+x.rod(D([(176, 26), (184, 30)]), 'plaster', (1.3 * DS) * BF, tag='dino')+x.rod(D([(176, 26), (181, 35)]), 'plaster', (1.3 * DS) * BF, tag='dino')+# display stand: steel rod, clamp, wooden base, brass plate, screw+x.rod(D([(5, 4), (5, 176)]), 'steel', 2.6 * DS)+x.slab(D(XRay.rrect(5, 4, 16, 9, 2)), 'steel', 8 * DS, edge=2)+x.slab(D(XRay.rrect(0, 186, 230, 18, 4)), 'organic', 50 * DS, edge=6, density=0.65)+x.slab(D(XRay.rrect(-60, 186, 70, 10, 2)), 'brass', 1.0, edge=0)+x.screw(d(5, 178), d(5, 194), 2.6 * DS, head=(10 * DS, 3))+# bottle of water lying on its side: PET wall with moulded rings, water inside, ribbed cap+BC, BR = (250, 278), -4.0+body = [(-178, -40), (-168, -55), (120, -55), (130, -48), (140, -55), (150, -55), (165, -40), (176, -22),+ (186, -16), (205, -16), (205, 16), (186, 16), (176, 22), (165, 40), (150, 55), (140, 55), (130, 48),+ (120, 55), (-168, 55), (-178, 40)]+x.shell(K(XRay.closed(body, 6), *BC, BR), 'organic', 110, 1.0, edge=50, density=1.35, tag='bottle')+water = [(-174, -38), (-165, -51), (118, -51), (128, -45), (140, -51), (148, -51), (162, -38), (170, -24),+ (170, 24), (162, 38), (148, 51), (140, 51), (128, 45), (118, 51), (-165, 51), (-174, 38)]+x.slab(K(XRay.closed(water, 6), *BC, BR), 'water', 102, edge=50, tag='bottle')+for uu in (-120, -60, 0, 60):+ x.rod(K([(uu, -55), (uu, 55)], *BC, BR), 'organic', 3, flat=5, density=1.3)+x.slab(K(XRay.rrect(214, 0, 22, 40, 4), *BC, BR), 'organic', 40, edge=10, density=1.1,+ texture=x.weave('plain', 3.2, BR, 0.25))+x.stage('skeleton_bottle')++# =========================================================== 8. flags on the picture+dino_pts = np.vstack([D(skull), D(SP), D([(-60, 160), (60, 160), (60, 195)])])+fx0, fy0 = dino_pts.min(0) - (14, 14)+fx1, fy1 = dino_pts.max(0) + (14, 10)+x.flag(fx0, fy0, fx1, fy1, 1, 'BONE-LIKE', 'Zeff {dino.z:.1f}')+bp = K(XRay.closed(body, 6), *BC, BR)+bx0, by0 = bp.min(0) - (12, 12)+bx1, by1 = bp.max(0) + (12, 12)+x.flag(bx0, by0, bx1, by1, 2, 'LIQUID', '{bottle.ml:.0f} ml', side='bottom')+x.stage('flags')++# =========================================================== 9. the side panel: material view, zoom on object 1+x.panel(1452, 76, 1900, 1000, 'MATERIAL VIEW · DUAL ENERGY')+x.inset((96, 150, 1400, 948), (1472, 128, 1880, 378), 'material')+x.legend(1472, 392, 408, 15)+zp = D([(60, -100), (335, -100), (335, 80), (60, 80)])+zx0, zy0 = int(zp[:, 0].min()), int(zp[:, 1].min())+zw = int(zp[:, 0].max() - zx0)+zh = int(zw * 230 / 408)+zy0 = int(zp[:, 1].mean() - zh / 2)+x.inset((zx0, zy0, zx0 + zw, zy0 + zh), (1472, 468, 1880, 698), 'material', 'ZOOM ×%.1f · OBJ 1' % (408 / zw))+x.line([(zx0 + zw, zy0), (1452, 468)], AMBER, 1, dash=7)+x.line([(zx0 + zw, zy0 + zh), (1452, 698)], AMBER, 1, dash=7)+x.stage('material')++# =========================================================== 10. readouts and the verdict+x.text('# CLASS Zeff NOTE', 1472, 726, 16, '#7fa9c2')+x.text('1 BONE-LIKE {dino.z:4.1f} PLASTER CAST', 1472, 754, 16, AMBER)+x.text(' TOY FOSSIL KIT', 1472, 780, 16, CYAN)+x.text('CLEAR', 1872, 780, 16, GREEN, 'ra', True, box=GREEN)+x.text('2 LIQUID {bottle.z:4.1f} {bottle.ml:.0f} ml', 1472, 818, 16, AMBER)+x.text(' OVER 100 ml', 1472, 844, 16, CYAN)+x.text('REMOVE', 1872, 844, 16, RED, 'ra', True, box=RED)+x.scale(1472, 934, 1880, 950, [('Al 2', 'aluminium', 3.4), ('Al 10 mm', 'aluminium', 17), ('Fe 1', 'steel', 1.7),+ ('Fe 3', 'steel', 5.1), ('Cu 10 mm', 'copper', 17)], 14, 'ATTENUATION →')+x.footer([('F1 ORG', '#6f93a8'), ('F2 INORG', '#6f93a8'), ('F3 HI-PEN', '#6f93a8'), ('F4 EDGE+', CYAN),+ ('F5 ZOOM', CYAN)],+ [('0416 CLEAR', '#6f93a8'), ('0417 SECONDARY CHECK', AMBER), ('0418 …', '#6f93a8')])+x.save(out, stages_dir=stages)+print(f'{out} {time.time() - t0:.1f}s', {kk: (round(v.z, 2), round(v.ml)) for kk, v in x.readings.items()})diff --git a/lib/blackfigure.py b/lib/blackfigure.pynew file mode 100644index 0000000..8d99c7d--- /dev/null+++ b/lib/blackfigure.py@@ -0,0 +1,1290 @@+"""blackfigure -- an Attic black-figure vase: thrown, painted, incised, fired, aged and photographed+(numpy + Pillow only).++The pot is made the way a 6th-century BC Athenian workshop made it, and then shown the way a museum shows it:+on a plinth under a spotlight, with the painted friezes unrolled flat on a panel beside it.++Model:+ pot a surface of revolution thrown on the wheel: a profile r(y) (lip, neck, shoulder, belly, foot) and two+ round handles. Everything painted lives on an *unrolled* surface (angle round the pot x height), so the+ same painting is wrapped onto the curved pot and laid flat in the rollout -- they always agree.+ Coordinates: `y` is px from the top of the lip; along a frieze, `x` is arc length in px at that frieze's+ own radius (the painter worked at real size, so figures keep their proportions on the belly and on the+ narrower lower body).+ clay Attic clay is iron-rich: matte buff-tan when dry, orange when fired. It is burnished, so it keeps a+ soft satin sheen. Faint throwing rings ripple the surface (they show up in the reflections).+ slip the "black" is a refined clay slip. Painted on, it is a dull dark brown; only the three-stage firing+ (oxidise - reduce - re-oxidise) turns it into the glossy blue-black glaze. Where it went on thin (brush+ edges, streaks) it fires reddish brown. Wheel bands are painted while the pot spins: dead level, with+ a tiny lap where the brush came off.+ figures silhouettes painted in slip; overlapping parts are told apart only by *incision*: a sharp point+ scratched through the slip before firing shows the orange clay as a hair-thin line (eye, hair line,+ muscles, the outline of a nearer limb or horse over a farther one). Added colours go on last, matte,+ over the black: purple-red (manes, fillets, beards, tongues) and white (charioteers' robes, a white+ horse). Every figure part is z-ordered: a nearer black shape covers farther added colour and+ incisions, then cuts its own contour -- so a four-horse team reads as four horses.+ ornament the canonical bands: lip and foot in black, palmette-lotus chain on the neck, alternating black/red+ tongues on the shoulder, a running meander, rays above the foot.+ text archaic Greek letters painted in slip with a fine brush (kalos inscriptions, labels, nonsense+ inscriptions), left-to-right or retrograde.+ fire switches every material from its raw look to the fired one.+ age 2,500 years: added white flakes off (leaving a dull ghost on the glaze), added red fades, calcareous+ encrustation and root marks, chips on lip and foot (pale fabric), a mended break with a toned plaster+ fill, a misfired patch where the black stayed reddish.+ photo the pot is lit like a museum photograph: a tall softbox upper left and a strip light right reflect as+ long highlights in the glaze, the clay gets a broad satin sheen, the pale plinth reflects in the lower+ glaze. A slight perspective bends every band into an arc. Rollouts are flat and evenly lit.++ from blackfigure import BlackFigure+ bf = BlackFigure(1920, 1080, seed=1)+ bf.museum()+ pot = bf.throw(cx=470, foot=985, height=930)+ pot.paint_handles(); pot.band(0, 60) # wheel-painted lip+ z = pot.zone(300, 530) # a frieze between two y's+ z.runner(200, phase=0); z.quadriga(700) # figures are declared ...+ pot.paint(); pot.incise(); pot.add_colour(); pot.fire() # ... and painted pass by pass+ bf.save('out.png')+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, load_font, text_mask+++def _hex(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _lin(c):+ return np.power(np.clip(c, 0, 1), 2.2).astype(np.float32)+++def _srgb(c):+ return np.power(np.clip(c, 0, 1), 1 / 2.2).astype(np.float32)+++COLOURS = {+ 'clay_raw': '#bb9878', 'slip_raw': '#4f3628', 'red_raw': '#7b3c34', 'white_raw': '#d8d0bf',+ 'clay': '#c96e3c', 'black': '#110e0f', 'thin': '#5c2a17', 'red': '#86303a', 'white': '#ebe1c8',+ 'fabric': '#c98a60', 'fill_clay': '#c27b52', 'fill_black': '#3f3836', 'crust': '#d4cbb8',+ 'misfire': '#6e341f',+}++# profiles: (y, r) as fractions of height / max radius, top of lip -> resting surface+SHAPES = {+ 'neck_amphora': dict(+ profile=[(0.000, 0.372), (0.006, 0.404), (0.020, 0.421), (0.040, 0.418), (0.054, 0.398), (0.062, 0.352),+ (0.074, 0.318), (0.120, 0.300), (0.180, 0.301), (0.212, 0.313), (0.226, 0.333), (0.236, 0.338),+ (0.246, 0.368), (0.270, 0.520), (0.300, 0.680), (0.340, 0.820), (0.390, 0.930), (0.440, 0.985),+ (0.480, 1.000), (0.530, 0.990), (0.580, 0.950), (0.640, 0.870), (0.700, 0.760), (0.760, 0.630),+ (0.820, 0.490), (0.870, 0.370), (0.900, 0.300), (0.915, 0.272), (0.925, 0.268), (0.932, 0.302),+ (0.940, 0.362), (0.960, 0.415), (0.980, 0.426), (0.993, 0.416), (1.000, 0.398)],+ handle=[(0.300, 0.094), (0.400, 0.092), (0.520, 0.106), (0.600, 0.148), (0.640, 0.205), (0.655, 0.255),+ (0.642, 0.302)],+ handle_w=0.072),+}++# archaic Attic letters as brush strokes in a 0.7 x 1 box (y down)+_O = [(0.35 + 0.33 * np.cos(a), 0.5 + 0.42 * np.sin(a)) for a in np.linspace(0, 2 * np.pi, 17)]+GLYPHS = {+ 'Α': [[(0, 1), (0.35, 0), (0.7, 1)], [(0.14, 0.62), (0.56, 0.54)]],+ 'Β': [[(0, 1), (0, 0), (0.42, 0.04), (0.5, 0.24), (0.06, 0.48), (0.55, 0.64), (0.52, 0.92), (0, 1)]],+ 'Γ': [[(0, 1), (0, 0), (0.55, 0.05)]],+ 'Δ': [[(0, 1), (0.35, 0), (0.7, 1), (0, 1)]],+ 'Ε': [[(0.6, 0), (0, 0), (0, 1), (0.6, 1)], [(0, 0.5), (0.45, 0.5)]],+ 'Η': [[(0, 0), (0, 1)], [(0.6, 0), (0.6, 1)], [(0, 0.5), (0.6, 0.5)]],+ 'Θ': [_O, [(0.15, 0.5), (0.55, 0.5)], [(0.35, 0.28), (0.35, 0.72)]],+ 'Ι': [[(0.1, 0), (0.1, 1)]],+ 'Κ': [[(0, 0), (0, 1)], [(0.6, 0), (0.03, 0.5), (0.6, 1)]],+ 'Λ': [[(0, 1), (0.35, 0), (0.7, 1)]],+ 'Μ': [[(0, 1), (0, 0), (0.35, 0.55), (0.7, 0), (0.7, 1)]],+ 'Ν': [[(0, 1), (0, 0), (0.6, 1), (0.6, 0)]],+ 'Ο': [_O],+ 'Π': [[(0, 1), (0, 0), (0.6, 0), (0.6, 1)]],+ 'Ρ': [[(0, 1), (0, 0), (0.45, 0.04), (0.55, 0.22), (0.45, 0.42), (0, 0.47)]],+ 'Σ': [[(0.6, 0), (0, 0), (0.35, 0.5), (0, 1), (0.6, 1)]],+ 'Τ': [[(0, 0), (0.7, 0)], [(0.35, 0), (0.35, 1)]],+ 'Υ': [[(0, 0), (0.35, 0.5), (0.7, 0)], [(0.35, 0.5), (0.35, 1)]],+ 'Φ': [[(0.35 + 0.3 * np.cos(a), 0.5 + 0.25 * np.sin(a)) for a in np.linspace(0, 2 * np.pi, 15)],+ [(0.35, 0), (0.35, 1)]],+ 'Χ': [[(0, 0), (0.7, 1)], [(0.7, 0), (0, 1)]],+}+++# ---------------------------------------------------------------- geometry helpers+def _closed(pts, per=6):+ """closed Catmull-Rom through pts"""+ P = np.asarray(pts, np.float32)+ n = len(P)+ E = np.vstack([P[-1:], P, P[:2]])+ t = np.linspace(0, 1, per, endpoint=False)[:, None]+ t2, t3 = t * t, t * t * t+ out = []+ for i in range(1, n + 1):+ p0, p1, p2, p3 = E[i - 1], E[i], E[i + 1], E[i + 2]+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))+ return np.vstack(out).astype(np.float32)+++def _open(pts, per=6):+ P = np.asarray(pts, np.float32)+ if len(P) == 2:+ return np.linspace(P[0], P[1], per + 1).astype(np.float32)+ return spline(P, per)+++def _ribbon(pts, widths, per=6, caps=True, smooth=True):+ """polygon of a stroke along pts with a width per control point (limbs, tails, tendrils, incisions)"""+ P = _open(pts, per) if smooth else np.asarray(pts, np.float32)+ m = len(pts)+ w = np.interp(np.linspace(0, m - 1, len(P)), np.arange(m), np.broadcast_to(np.asarray(widths, np.float32), (m,)))+ d = np.gradient(P, axis=0)+ d /= (np.linalg.norm(d, axis=1, keepdims=True) + 1e-9)+ nrm = np.stack([-d[:, 1], d[:, 0]], 1)+ L, R = P + nrm * w[:, None] / 2, P - nrm * w[:, None] / 2+ parts = [L]+ a = np.linspace(0, np.pi, 7)[1:-1, None]+ if caps:+ parts.append(P[-1] + (w[-1] / 2) * (np.cos(a) * nrm[-1] + np.sin(a) * d[-1]))+ parts.append(R[::-1])+ if caps:+ parts.append(P[0] + (w[0] / 2) * (np.cos(a) * (-nrm[0]) - np.sin(a) * d[0]))+ return np.vstack(parts).astype(np.float32)+++def _circle(cx, cy, r, n=24, ry=None):+ a = np.linspace(0, 2 * np.pi, n, endpoint=False)+ return np.stack([cx + r * np.cos(a), cy + (ry or r) * np.sin(a)], 1).astype(np.float32)+++def _arc(cx, cy, r, a0, a1, n=10):+ a = np.linspace(a0, a1, n)+ return np.stack([cx + r * np.cos(a), cy + r * np.sin(a)], 1).astype(np.float32)+++def _rot(P, c, ang):+ P = np.asarray(P, np.float32)+ s, k = np.sin(ang), np.cos(ang)+ d = P - c+ return np.stack([c[0] + d[:, 0] * k - d[:, 1] * s, c[1] + d[:, 0] * s + d[:, 1] * k], 1)+++def _bilinear(img, u, v):+ """sample img (H, W[, C]) at float coords, wrapping in u (round the pot)"""+ H, W = img.shape[:2]+ u0f = np.floor(u)+ fu = (u - u0f).astype(np.float32)+ u0 = u0f.astype(np.int64) % W+ u1 = (u0 + 1) % W+ v = np.clip(v, 0, H - 1.001)+ v0 = np.floor(v).astype(np.int64)+ fv = (v - v0).astype(np.float32)+ v1 = np.minimum(v0 + 1, H - 1)+ if img.ndim == 3:+ fu, fv = fu[:, None], fv[:, None]+ return (img[v0, u0] * (1 - fu) * (1 - fv) + img[v0, u1] * fu * (1 - fv) ++ img[v1, u0] * (1 - fu) * fv + img[v1, u1] * fu * fv)+++# ---------------------------------------------------------------- figure builder (local units)+class _Fig:+ """a figure as an ordered list of painting operations in local units (feet at (0, 0), facing +x, y down).+ polygons scale with the figure; line widths are in pixels (a brush or a graver has a fixed width)."""++ def __init__(self):+ self.ops = []++ def slip(self, poly, occlude=True):+ self.ops.append(('poly', 'slip', np.asarray(poly, np.float32), occlude))++ def red(self, poly):+ self.ops.append(('poly', 'red', np.asarray(poly, np.float32), False))++ def white(self, poly):+ self.ops.append(('poly', 'white', np.asarray(poly, np.float32), False))++ def reserve(self, poly):+ """a patch scraped / left free of slip inside a black shape"""+ self.ops.append(('poly', 'inc', np.asarray(poly, np.float32), False))++ def cut(self, pts, w=1.15, closed=False):+ """incision: a sharp point through the slip, tapering in and out"""+ self.ops.append(('line', 'inc', np.asarray(pts, np.float32), w, closed, True))++ def line(self, pts, w=1.4, layer='slip', taper=False, closed=False):+ """a painted line (reins, staff, tendrils, letters)"""+ self.ops.append(('line', layer, np.asarray(pts, np.float32), w, closed, taper))+++def _head(f, cx, cy, r, beard=False, hair='long', fillet=True, red_beard=False, detail=True):+ """archaic profile head facing +x, skull centre (cx, cy), skull radius r"""+ back = ([(-0.30, 1.6), (-0.45, 2.05), (-1.0, 1.95), (-1.18, 0.9), (-1.08, 0.0), (-0.58, -0.88)] if hair == 'long'+ else [(-0.35, 1.6), (-0.70, 0.75), (-1.0, 0.0), (-0.55, -0.85)])+ face = [(0.1, -1.02), (0.75, -0.65), (0.95, -0.22), (0.98, -0.05), (1.30, 0.30), (1.08, 0.42), (1.12, 0.55),+ (1.02, 0.62), (1.10, 0.70)]+ chin = ([(1.10, 1.05), (1.02, 1.48), (0.70, 1.48), (0.38, 1.30), (0.40, 1.6)] if beard else+ [(1.02, 0.95), (0.75, 1.10), (0.30, 1.05), (0.40, 1.6)])+ P = np.array(back + face + chin, np.float32)+ f.slip(np.stack([cx + P[:, 0] * r, cy + P[:, 1] * r], 1))+ S = lambda pts: np.stack([cx + np.asarray(pts)[:, 0] * r, cy + np.asarray(pts)[:, 1] * r], 1)+ hl = [(0.72, -0.62), (0.38, -0.48), (0.18, -0.12), (0.12, 0.30), (-0.18, 0.72), (-0.36, 1.35)]+ f.cut(S(hl if hair == 'long' else hl[:5]))+ if detail:+ f.cut(_circle(cx + 0.60 * r, cy - 0.15 * r, 0.17 * r, 12), closed=True, w=1.0)+ f.cut(S([(0.12, 0.05), (-0.12, 0.10), (-0.14, 0.38), (0.06, 0.42)]), w=0.9)+ else:+ f.cut(S([(0.56, -0.17), (0.66, -0.13)]), w=1.1)+ if beard:+ f.cut(S([(0.28, 0.42), (0.62, 0.62), (0.94, 0.78)]))+ if red_beard:+ f.red(S([(0.30, 0.48), (0.62, 0.68), (1.05, 0.78), (1.05, 1.42), (0.70, 1.44), (0.40, 1.25)]))+ if hair == 'long' and detail:+ for k in range(3):+ f.cut(S([(-0.55 - 0.15 * k, 0.6), (-0.65 - 0.12 * k, 1.1), (-0.62 - 0.1 * k, 1.75)]), w=0.9)+ if fillet:+ f.red(_ribbon(S([(0.74, -0.60), (0.30, -0.90), (-0.30, -0.88), (-0.82, -0.45)]), 0.17 * r))+++def _foot(f, ankle, toe, s=1.0):+ a, t = np.asarray(ankle, np.float32), np.asarray(toe, np.float32)+ mid = a + (t - a) * 0.45 + np.array([0, 0.012 * s])+ f.slip(_ribbon([a, mid, t], [0.036 * s, 0.032 * s, 0.013 * s], per=4))+ f.slip(_circle(a[0] - 0.008 * s, a[1] + 0.008 * s, 0.02 * s, 10))+++def _runner(f, phase=0, var=0.0, beard=False, back_arm='up', rng=None):+ """an archaic sprinter in full stride, chest frontal, head and legs in profile; unit = standing height"""+ rng = rng or np.random.default_rng(0)+ j = lambda p: np.asarray(p, np.float32) + rng.normal(0, 0.008, 2) * var+ fwd = [j((0.06, -0.47)), j((0.235, -0.375)), j((0.215, -0.15))]+ bck = [j((0.00, -0.47)), j((-0.075, -0.255)), j((-0.235, -0.11))]+ fwd_toe, bck_toe = (0.31, -0.118), (-0.165, -0.004)+ legs = [(bck, bck_toe), (fwd, fwd_toe)] if phase == 0 else [(fwd, fwd_toe), (bck, bck_toe)]+ lw = [0.108, 0.07, 0.058, 0.066, 0.032]++ def leg(L, toe, near):+ hip, knee, ank = L+ calf = knee + (ank - knee) * 0.35 + np.array([-0.008, 0], np.float32)+ thigh = hip + (knee - hip) * 0.5+ pts = [hip, thigh, knee, calf, ank]+ poly = _ribbon(pts, lw, per=5)+ f.slip(poly)+ _foot(f, ank, toe)+ if near:+ f.cut(poly[: len(poly) // 2 - 3]) # contour of the near leg over the far one+ f.cut(poly[len(poly) // 2 + 3:])+ f.cut([knee + (-0.02, -0.012), knee + (0.004, 0.006), knee + (0.024, -0.008)], w=1.0)++ leg(*legs[0], near=False)+ torso = [(0.10, -0.79), (0.135, -0.768), (0.168, -0.735), (0.152, -0.69), (0.14, -0.65), (0.105, -0.595),+ (0.085, -0.55), (0.10, -0.50), (0.105, -0.462), (0.06, -0.432), (0.02, -0.428), (-0.035, -0.44),+ (-0.066, -0.48), (-0.05, -0.53), (-0.025, -0.57), (-0.05, -0.64), (-0.078, -0.70), (-0.084, -0.745),+ (-0.05, -0.772), (0.05, -0.79)]+ f.slip(_closed(torso, 4))+ leg(*legs[1], near=True)+ # arms: one flung forward with an open hand, one swung back+ a1 = [j((0.135, -0.745)), j((0.255, -0.685)), j((0.33, -0.772)), j((0.362, -0.812))]+ a2 = ([j((-0.055, -0.75)), j((-0.175, -0.655)), j((-0.262, -0.71)), j((-0.29, -0.742))] if back_arm == 'up' else+ [j((-0.055, -0.75)), j((-0.16, -0.64)), j((-0.262, -0.585)), j((-0.30, -0.57))])+ for arm in (a2, a1):+ poly = _ribbon(arm, [0.058, 0.043, 0.032, 0.022], per=5)+ f.slip(poly)+ f.cut(poly[2:len(poly) // 2 - 6], w=1.0)+ _head(f, 0.115, -0.885, 0.058, beard=beard, hair='long', detail=False)+ for p in ([(-0.03, -0.745), (0.04, -0.722), (0.12, -0.745)], [(-0.04, -0.70), (0.0, -0.664), (0.05, -0.672)],+ [(0.06, -0.672), (0.10, -0.664), (0.142, -0.69)], [(0.0, -0.607), (0.05, -0.59), (0.095, -0.607)],+ [(0.052, -0.655), (0.05, -0.55)], [(0.095, -0.50), (0.06, -0.448)]):+ f.cut(p, w=1.0)+++# horse, galloping, facing +x; unit = withers height; ground y = 0+_H_BODY = [(0.42, -0.70), (0.36, -0.52), (0.20, -0.45), (-0.05, -0.43), (-0.28, -0.46), (-0.40, -0.50), (-0.50, -0.56),+ (-0.60, -0.66), (-0.64, -0.76), (-0.56, -0.87), (-0.36, -0.885), (-0.15, -0.86), (0.10, -0.93),+ (0.23, -1.03), (0.34, -1.16), (0.43, -1.28), (0.53, -1.29), (0.62, -1.17), (0.70, -1.06), (0.722, -1.02),+ (0.70, -0.99), (0.655, -0.995), (0.60, -1.03), (0.545, -1.05), (0.49, -1.10), (0.47, -0.96), (0.45, -0.82)]+# flying gallop: near foreleg folded high, far foreleg reaching for the ground, hind legs driving back+_H_LEGS = {'nf': ([(0.33, -0.66), (0.37, -0.56), (0.55, -0.56), (0.565, -0.39), (0.62, -0.335)], [0.13, 0.10, 0.056, 0.042, 0.05]),+ 'ff': ([(0.30, -0.66), (0.34, -0.54), (0.49, -0.37), (0.65, -0.13), (0.71, -0.07)], [0.12, 0.095, 0.052, 0.04, 0.048]),+ 'nh': ([(-0.47, -0.67), (-0.50, -0.53), (-0.70, -0.38), (-0.86, -0.14), (-0.92, -0.065)], [0.22, 0.135, 0.06, 0.042, 0.05]),+ 'fh': ([(-0.45, -0.65), (-0.46, -0.51), (-0.60, -0.37), (-0.62, -0.13), (-0.575, -0.06)], [0.20, 0.125, 0.056, 0.04, 0.048])}+_H_ROOTS = {'nf': (0.33, -0.66), 'ff': (0.30, -0.66), 'nh': (-0.47, -0.67), 'fh': (-0.45, -0.65)}+_H_TAIL = ([(-0.60, -0.84), (-0.75, -0.865), (-0.89, -0.78), (-0.99, -0.62)], [0.08, 0.072, 0.05, 0.02])+++def _horse_tf(dx, dy, bend):+ """offset + neck bend about the withers (head raised for bend > 0)"""+ c = np.array([0.10, -0.93], np.float32)++ def tf(P):+ P = np.asarray(P, np.float32)+ w = smoothstep(0.12, 0.42, P[:, 0])+ d = P - c+ a = -bend * w+ s, k = np.sin(a), np.cos(a)+ Q = np.stack([c[0] + d[:, 0] * k - d[:, 1] * s, c[1] + d[:, 0] * s + d[:, 1] * k], 1)+ return Q + (dx, dy)+ return tf+++def _horse(f, dx=0.0, dy=0.0, bend=0.0, legs=(0, 0, 0, 0), colour=None, outline=True):+ """one galloping chariot horse (unit = withers height, ground y = 0).+ colour: None (black), 'white' (a white trace horse in added white) or 'red_mane'. Returns the mouth point."""+ tf = _horse_tf(dx, dy, bend)+ far = [_ribbon(tf(_rot(_H_LEGS[k][0], np.array(_H_ROOTS[k]), a)), _H_LEGS[k][1], per=5)+ for k, a in (('ff', legs[1]), ('fh', legs[3]))]+ near = [_ribbon(tf(_rot(_H_LEGS[k][0], np.array(_H_ROOTS[k]), a)), _H_LEGS[k][1], per=5)+ for k, a in (('nf', legs[0]), ('nh', legs[2]))]+ tail = _ribbon(tf(_H_TAIL[0]), _H_TAIL[1], per=6)+ body = _closed(tf(_H_BODY), 5)+ ears = [tf([(0.405, -1.265), (0.412, -1.37), (0.447, -1.28)]), tf([(0.43, -1.28), (0.447, -1.395), (0.482, -1.29)])]+ allp = far + [tail, body] + ears + near+ for p in allp:+ f.slip(p)+ if colour == 'white':+ for p in allp:+ f.white(p)+ if outline:+ f.cut(body, closed=True)+ for p in near:+ n = len(p)+ f.cut(p[1:n // 2 - 4]); f.cut(p[n // 2 + 4:-1])+ f.cut(_circle(*tf([(0.535, -1.205)])[0], 0.022, 12), closed=True, w=1.0) # eye and brow+ f.cut(tf([(0.505, -1.24), (0.535, -1.25), (0.565, -1.232)]), w=0.9)+ f.cut(tf([(0.48, -1.14), (0.52, -1.08), (0.585, -1.04)])) # jaw+ f.cut(tf([(0.718, -1.006), (0.662, -1.0)]), w=1.0) # mouth+ f.cut(tf([(0.683, -1.062), (0.70, -1.047), (0.69, -1.031)]), w=0.9) # nostril+ f.cut(tf([(0.632, -1.105), (0.672, -1.03)]), w=1.0) # noseband+ f.cut(tf([(0.49, -1.235), (0.535, -1.15), (0.635, -1.095)]), w=1.0) # cheekpiece+ inner = tf([(0.41, -1.23), (0.32, -1.11), (0.22, -0.99), (0.13, -0.905)])+ crest = tf([(0.10, -0.93), (0.23, -1.03), (0.34, -1.16), (0.43, -1.28)])+ f.cut(inner) # mane edge+ for t in np.linspace(0.1, 0.9, 7): # mane hair+ a = crest[0] + (crest[-1] - crest[0]) * t+ b = inner[-1] + (inner[0] - inner[-1]) * t+ f.cut([a + (b - a) * 0.15, b], w=0.8)+ f.cut(tf([(0.20, -0.94), (0.31, -0.80), (0.36, -0.64)])) # shoulder+ f.cut(tf([(-0.42, -0.86), (-0.36, -0.72), (-0.45, -0.56)])) # haunch+ f.cut(tf([(0.43, -0.78), (0.33, -0.90), (0.22, -0.96)]), w=1.0) # breastband+ f.cut(tf([(-0.64, -0.82), (-0.78, -0.835), (-0.90, -0.75)]), w=0.9) # tail hair+ f.cut(tf([(-0.10, -0.45), (0.12, -0.46)]), w=0.9) # girth+ if colour == 'red_mane':+ f.red(_closed(np.vstack([crest, inner]), 3))+ return tf([(0.70, -1.0)])[0]+++def _charioteer(f, X, Y, s, lean=0.24):+ """standing charioteer in a long white chiton, leaning into the race. (X, Y): feet; s: height.+ returns (rein hand, goad hand)"""+ def T(P):+ P = np.asarray(P, np.float32)+ return np.stack([X + (P[:, 0] - lean * P[:, 1]) * s, Y + P[:, 1] * s], 1)+ robe = [(-0.06, -0.80), (0.05, -0.83), (0.11, -0.78), (0.12, -0.66), (0.10, -0.50), (0.11, -0.25), (0.12, 0.0),+ (-0.11, 0.0), (-0.10, -0.30), (-0.09, -0.55), (-0.10, -0.72)]+ farm = T([(0.0, -0.77), (0.12, -0.69), (0.27, -0.70)])+ f.slip(_ribbon(farm, [0.065 * s, 0.05 * s, 0.042 * s], per=4))+ rp = _closed(T(robe), 4)+ f.slip(rp)+ f.white(rp)+ hx, hy = T([(0.025, -0.905)])[0]+ _head(f, hx, hy, 0.072 * s, beard=False, hair='long', fillet=True)+ narm = T([(0.035, -0.765), (0.145, -0.655), (0.29, -0.66)])+ poly = _ribbon(narm, [0.07 * s, 0.055 * s, 0.045 * s], per=4)+ f.slip(poly)+ f.cut(poly[2:len(poly) // 2 - 3], w=1.0)+ for x in (-0.06, -0.02, 0.025, 0.07):+ f.cut(T([(x, -0.74), (x + 0.012, -0.45), (x - 0.004, -0.08)]), w=1.0)+ f.cut(T([(-0.095, -0.58), (0.11, -0.60)]), w=1.1)+ f.red(_ribbon(T([(-0.095, -0.58), (0.11, -0.60)]), 0.028 * s, smooth=False))+ f.cut(T([(-0.04, -0.79), (0.04, -0.765), (0.09, -0.79)]), w=1.0)+ return T([(0.30, -0.662)])[0], T([(0.27, -0.70)])[0]+++class Zone:+ """a frieze between two heights of the pot. x = arc length (px) round the pot at this zone's radius,+ 0 at the left handle; the visible front runs 0 .. C/2, the back C/2 .. C."""++ def __init__(self, pot, y0, y1):+ self.pot, self.y0, self.y1 = pot, float(y0), float(y1)+ self.r = float(pot.radius((y0 + y1) / 2))+ self.C = 2 * np.pi * self.r+ self.k = pot.R / self.r+ self.rng = np.random.default_rng(pot._seed())++ def tex(self, Q):+ Q = np.asarray(Q, np.float32)+ return np.stack([Q[:, 0] * self.k * self.pot.ls, Q[:, 1] * self.pot.ls], 1)++ def emit(self, fig, X, G=None, s=1.0, facing=1, jitter=0.22):+ """place a _Fig: local (lx, ly) -> (X + facing * lx * s, G + ly * s)"""+ G = self.y1 if G is None else G+ for op in fig.ops:+ P = op[2]+ Q = np.stack([X + facing * P[:, 0] * s, G + P[:, 1] * s], 1)+ if op[0] == 'poly':+ Q = Q + self.rng.normal(0, jitter, Q.shape).astype(np.float32)+ self.pot.ops.append((op[1], self.tex(Q), op[3]))+ else:+ _, layer, _, w, closed, taper = op+ if closed:+ Q = np.vstack([Q, Q[:1]])+ Q = Q + self.rng.normal(0, 0.18, Q.shape).astype(np.float32)+ wid = np.full(len(Q), w, np.float32)+ if taper and len(Q) >= 2 and not closed:+ wid[0] *= 0.35; wid[-1] *= 0.35+ self.pot.ops.append((layer, self.tex(_ribbon(Q, wid, per=4)), layer == 'slip'))++ # ------------------------------------------------------------ figures+ def runner(self, x, height=None, phase=0, beard=False, back_arm='up', ground=None):+ h = height or (self.y1 - self.y0) * 0.86+ f = _Fig()+ _runner(f, phase, 1.0, beard, back_arm, self.rng)+ self.emit(f, x, ground, h)++ def quadriga(self, x, hw=None, white_horse=None, red_manes=(3,), bends=(0.13, -0.05, 0.08, -0.09), ground=None):+ """a racing four-horse chariot heading +x. x = girth of the nearest horse; hw = withers height px.+ Drawn back to front: pole, charioteer, breastwork and rail, wheel, the team far -> near, reins, goad."""+ hw = hw or (self.y1 - self.y0) * 0.6+ f = _Fig()+ f.slip(_ribbon([(-1.05, -0.585), (-0.60, -0.62), (-0.20, -0.75), (0.10, -0.92)], 0.032, per=5))+ hand, hand2 = _charioteer(f, -1.33, -0.60, 0.90)+ cx0 = -1.04 # front of the car+ f.slip([(cx0, -0.585), (cx0 - 0.01, -0.80), (cx0 - 0.07, -0.845), (cx0 - 0.27, -0.80), (cx0 - 0.30, -0.585)])+ f.slip(_ribbon([(cx0, -0.60), (cx0 + 0.015, -0.80), (cx0 - 0.06, -0.92), (cx0 - 0.20, -0.93),+ (cx0 - 0.33, -0.84), (cx0 - 0.38, -0.66)], 0.034, per=4))+ f.slip([(cx0 - 0.46, -0.555), (cx0 + 0.02, -0.555), (cx0 + 0.02, -0.61), (cx0 - 0.46, -0.61)])+ f.cut([(cx0 - 0.02, -0.59), (cx0 - 0.28, -0.59)], w=1.0)+ f.cut([(cx0 - 0.03, -0.78), (cx0 - 0.09, -0.83), (cx0 - 0.25, -0.79)], w=1.0)+ f.red(_ribbon([(cx0 - 0.01, -0.66), (cx0 - 0.28, -0.66)], 0.04, smooth=False))+ wc = np.array([cx0 - 0.22, -0.345], np.float32)+ rim = _circle(wc[0], wc[1], 0.32, 40)+ f.slip(_ribbon(np.vstack([rim, rim[:2]]), 0.055, per=2, caps=False))+ for a in (0.35, 0.35 + np.pi / 2):+ d = np.array([np.cos(a), np.sin(a)], np.float32) * 0.31+ f.slip(_ribbon([wc - d, wc + d], 0.03, per=2))+ f.slip(_circle(wc[0], wc[1], 0.07, 14))+ f.cut(_circle(wc[0], wc[1], 0.30, 30), closed=True, w=1.0)+ f.cut(_circle(wc[0], wc[1], 0.045, 10), closed=True, w=0.9)+ mouths = []+ legsets = [(0.10, -0.08, -0.06, 0.07), (-0.06, 0.07, 0.05, -0.05), (0.05, -0.03, -0.03, 0.04), (0, 0, 0, 0)]+ for i in range(4):+ colour = 'white' if i == white_horse else ('red_mane' if i in red_manes else None)+ mouths.append(_horse(f, dx=(3 - i) * 0.06, dy=-(3 - i) * 0.022, bend=bends[i], legs=legsets[i],+ colour=colour, outline=i > 0))+ for i, m in enumerate(mouths): # reins, painted with a fine brush+ p0 = hand + np.array([0, 0.006 * i], np.float32)+ mid = (p0 + m) / 2 + np.array([0, 0.05 + 0.015 * i], np.float32)+ f.line([p0, mid, m], w=1.1)+ f.line([hand2, hand2 + np.array([0.24, -0.32], np.float32)], w=1.5, taper=True) # goad+ self.emit(f, x, ground, hw)++ def column(self, x, height=None, ground=None, red=True):+ """a Doric column (turning post / finish post)"""+ h = height or (self.y1 - self.y0) * 0.86+ f = _Fig()+ f.slip([(-0.11, -0.035), (0.11, -0.035), (0.11, 0.0), (-0.11, 0.0)])+ f.slip([(-0.075, -0.03), (0.075, -0.03), (0.062, -0.865), (-0.062, -0.865)])+ f.slip([(-0.062, -0.86), (-0.10, -0.895), (-0.105, -0.91), (0.105, -0.91), (0.10, -0.895), (0.062, -0.86)])+ f.slip([(-0.115, -0.905), (0.115, -0.905), (0.115, -0.955), (-0.115, -0.955)])+ for dx in (-0.038, 0.0, 0.038):+ f.cut([(dx * 1.1, -0.06), (dx, -0.84)], w=1.0)+ f.cut([(-0.065, -0.85), (0.065, -0.85)], w=1.0)+ f.cut([(-0.11, -0.906), (0.11, -0.906)], w=1.0)+ if red:+ f.red([(-0.112, -0.912), (0.112, -0.912), (0.112, -0.95), (-0.112, -0.95)])+ self.emit(f, x, ground, h)++ def judge(self, x, height=None, facing=-1, holds='wreath', ground=None):+ """a bearded official in a himation; holds a wreath (prize) or a forked rod (umpire)"""+ h = height or (self.y1 - self.y0) * 0.88+ f = _Fig()+ f.slip(_ribbon([(-0.15, -1.02), (-0.14, 0.0)], 0.022, per=2)) # staff behind+ if holds == 'rod':+ f.slip(_ribbon([(-0.15, -1.02), (-0.19, -1.10)], 0.018, per=2))+ f.slip(_ribbon([(-0.15, -1.02), (-0.11, -1.10)], 0.018, per=2))+ cloak = [(0.0, -0.85), (0.10, -0.84), (0.125, -0.75), (0.135, -0.55), (0.12, -0.30), (0.15, -0.05),+ (-0.11, -0.05), (-0.115, -0.30), (-0.10, -0.60), (-0.09, -0.78)]+ cp = _closed(cloak, 4)+ f.slip(cp)+ _foot(f, (0.10, -0.035), (0.20, -0.004))+ _foot(f, (-0.06, -0.035), (0.04, -0.004))+ _head(f, 0.06, -0.92, 0.058, beard=True, hair='long', fillet=False, red_beard=True, detail=h > 120)+ arm = _ribbon([(0.08, -0.70), (0.20, -0.665), (0.30, -0.70)], [0.055, 0.042, 0.034], per=4)+ f.slip(arm)+ f.cut(arm[2:len(arm) // 2 - 3], w=1.0)+ f.slip(_circle(-0.13, -0.62, 0.035, 10)) # hand on the staff+ for p in ([(0.11, -0.80), (-0.03, -0.55), (-0.10, -0.33)], [(0.13, -0.62), (0.02, -0.38), (-0.04, -0.12)],+ [(0.12, -0.42), (0.08, -0.08)], [(-0.07, -0.30), (-0.08, -0.07)], [(0.02, -0.25), (0.02, -0.07)]):+ f.cut(p, w=1.0)+ f.red(_ribbon([(0.12, -0.80), (-0.02, -0.56), (-0.10, -0.36)], 0.045, per=4))+ f.red(_ribbon([(-0.11, -0.075), (0.15, -0.075)], 0.03, smooth=False))+ for cx, cy in ((0.05, -0.68), (-0.04, -0.45), (0.07, -0.30), (-0.02, -0.18)):+ for a in (0, 2.1, 4.2):+ f.white(_circle(cx + 0.013 * np.cos(a), cy + 0.013 * np.sin(a), 0.0075, 6))+ if holds == 'wreath':+ ring = np.vstack([_circle(0.35, -0.72, 0.055, 20), _circle(0.35, -0.72, 0.055, 20)[:1]])+ f.slip(_ribbon(ring, 0.012, per=2, caps=False))+ f.red(_ribbon(ring, 0.014, per=2, caps=False))+ for a in np.linspace(0, 2 * np.pi, 12, endpoint=False):+ c = np.array([0.35 + 0.055 * np.cos(a), -0.72 + 0.055 * np.sin(a)])+ d = np.array([np.cos(a + 0.9), np.sin(a + 0.9)]) * 0.016+ f.red(_ribbon([c - d, c + d], 0.012, per=2))+ self.emit(f, x, ground, h, facing)++ def tripod(self, x, height=None, ground=None):+ """a bronze tripod cauldron -- the prize"""+ h = height or (self.y1 - self.y0) * 0.62+ f = _Fig()+ for leg in ([(-0.19, -0.62), (-0.25, -0.30), (-0.30, -0.02)], [(0.19, -0.62), (0.25, -0.30), (0.30, -0.02)],+ [(0.0, -0.58), (0.0, -0.30), (0.0, -0.02)]):+ f.slip(_ribbon(leg, [0.05, 0.04, 0.036], per=4))+ f.slip(_circle(leg[-1][0], -0.02, 0.035, 10, ry=0.022))+ a = np.linspace(0, np.pi, 18)+ bowl = np.vstack([np.stack([0.27 * np.cos(a), -0.70 + 0.19 * np.sin(a)], 1)[::-1], [(-0.27, -0.70)]])+ bowl = np.vstack([[(0.29, -0.76), (0.29, -0.70)], bowl[1:], [(-0.29, -0.70), (-0.29, -0.76)]])+ f.slip(bowl)+ for cx in (-0.14, 0.14):+ ring = np.vstack([_circle(cx, -0.90, 0.085, 24), _circle(cx, -0.90, 0.085, 24)[:1]])+ f.slip(_ribbon(ring, 0.03, per=2, caps=False))+ f.slip(_ribbon([(cx, -0.815), (cx * 1.2, -0.75)], 0.03, per=2))+ f.cut([(-0.28, -0.70), (0.28, -0.70)], w=1.0)+ f.cut([(-0.24, -0.62), (-0.12, -0.56), (0.0, -0.545), (0.12, -0.56), (0.24, -0.62)], w=1.0)+ zz = [(-0.20 + 0.04 * i, -0.665 + (0.025 if i % 2 else 0)) for i in range(11)]+ f.cut(zz, w=0.9)+ f.red([(-0.285, -0.758), (0.285, -0.758), (0.285, -0.72), (-0.285, -0.72)])+ self.emit(f, x, ground, h)++ def prize_table(self, x, height=None, ground=None):+ """a small table with the prize: a miniature amphora and an olive wreath"""+ h = height or (self.y1 - self.y0) * 0.86+ f = _Fig()+ f.slip([(-0.20, -0.36), (0.20, -0.36), (0.20, -0.33), (-0.20, -0.33)])+ for lx in (-0.16, 0.16):+ f.slip(_ribbon([(lx, -0.34), (lx * 1.06, -0.15), (lx * 1.1, -0.01)], [0.03, 0.022, 0.03], per=3))+ f.slip(_ribbon([(-0.17, -0.12), (0.17, -0.12)], 0.014, smooth=False))+ pro = np.array(SHAPES['neck_amphora']['profile'], np.float32)+ ah, ar = 0.36, 0.36 * 0.31+ side = np.stack([pro[:, 1] * ar, -0.36 - ah + pro[:, 0] * ah], 1)+ f.slip(np.vstack([side, side[::-1] * (-1, 1)]) + (-0.06, 0))+ for sgn in (-1, 1):+ hp = np.array(SHAPES['neck_amphora']['handle'], np.float32)+ f.slip(_ribbon(np.stack([-0.06 + sgn * hp[:, 0] * ar, -0.36 - ah + hp[:, 1] * ah], 1), 0.016, per=3))+ f.reserve([(-0.06 - 0.05, -0.36 - ah * 0.62), (-0.06 + 0.05, -0.36 - ah * 0.62),+ (-0.06 + 0.05, -0.36 - ah * 0.40), (-0.06 - 0.05, -0.36 - ah * 0.40)])+ ring = np.vstack([_circle(0.12, -0.395, 0.045, 18), _circle(0.12, -0.395, 0.045, 18)[:1]])+ f.red(_ribbon(ring, 0.016, per=2, caps=False))+ f.slip(_ribbon(ring, 0.006, per=2, caps=False), occlude=False)+ self.emit(f, x, ground, h)++ def bird(self, x, y, size=30, facing=1, flap=0.0):+ """a swallow-like bird in flight (filler)"""+ f = _Fig()+ f.slip(_closed([(0.5, 0.0), (0.3, -0.07), (-0.1, -0.06), (-0.45, -0.02), (-0.1, 0.07), (0.3, 0.06)], 4))+ f.slip([(-0.38, 0.0), (-0.72, -0.18), (-0.55, 0.0), (-0.72, 0.16)])+ f.slip(_ribbon([(0.1, -0.03), (-0.05, -0.35 - flap), (-0.30, -0.55 - flap)], [0.18, 0.12, 0.02], per=4))+ f.slip(_ribbon([(0.15, 0.0), (0.05, -0.25 - flap * 0.6), (-0.12, -0.42 - flap)], [0.14, 0.09, 0.02], per=4))+ f.cut([(0.30, -0.02), (0.36, -0.01)], w=1.0)+ f.cut([(0.1, -0.02), (-0.05, -0.30 - flap)], w=0.9)+ f.red(_ribbon([(0.25, 0.04), (0.0, 0.05)], 0.05, smooth=False))+ self.emit(f, x, y, size, facing)++ def letters(self, text, x, y, size=12, vertical=False, retro=False, w=None):+ """archaic Greek letters painted with a fine brush, starting at (x, y)"""+ f = _Fig()+ pen = 0.0+ for ch in text:+ if ch == ' ':+ pen += 0.6+ continue+ g = GLYPHS.get(ch)+ if g is None:+ continue+ gw = 0.3 if ch == 'Ι' else 0.7+ for stroke in g:+ P = np.asarray(stroke, np.float32)+ if retro:+ P = np.stack([gw - P[:, 0], P[:, 1]], 1) # mirrored letters, written leftwards+ if vertical:+ P = np.stack([P[:, 0], P[:, 1] + pen], 1)+ else:+ P = np.stack([P[:, 0] + (-(pen + gw) if retro else pen), P[:, 1]], 1)+ f.line(P, w=w or max(1.1, size * 0.11), taper=False)+ pen += (1.25 if vertical else gw + 0.32)+ self.emit(f, x, y, size, 1, jitter=0.0)+++class Pot:+ """a thrown pot: profile, handles and the unrolled painting surface (2x supersampled layers)"""++ def __init__(self, cx, foot, height, rmax=None, shape='neck_amphora', seed=0, eye=0.42, persp=0.11):+ sh = SHAPES[shape]+ self.shape = sh+ self.cx, self.H = float(cx), int(height)+ self.R = float(rmax or height * 0.315)+ self.top = float(foot) - self.H+ self.eye, self.persp = eye * self.H, persp+ P = np.array(sh['profile'], np.float32)+ d = spline(P, 14)+ self._py = np.maximum.accumulate(d[:, 0]) * self.H+ self._pr = np.clip(d[:, 1], 0.05, None) * self.R+ self.TW, self.TH, self.ls = int(round(2 * np.pi * self.R)), self.H, 2+ size = (self.TW * self.ls, self.TH * self.ls)+ self.layers = {k: Image.new('L', size, 0) for k in ('slip', 'red', 'white', 'inc')}+ self.draw = {k: ImageDraw.Draw(v) for k, v in self.layers.items()}+ self.ops, self._painted = [], 0+ self.rng = np.random.default_rng(seed)+ self.fired = self.aged = self.handles_painted = False+ self._geo = None+ self._noise = None+ self._agemaps = None+ self._ver, self._mat = 0, None++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ def radius(self, y):+ return np.interp(y, self._py, self._pr).astype(np.float32)++ def zone(self, y0, y1):+ return Zone(self, y0, y1)++ # ------------------------------------------------------------ raw drawing on the unrolled layers+ def _fill(self, layer, poly, val):+ W = self.TW * self.ls+ P = np.asarray(poly, np.float32)+ lo, hi = P[:, 0].min(), P[:, 0].max()+ offs = [0] + ([W] if lo < 0 else []) + ([-W] if hi > W else [])+ self._ver += 1+ for o in offs:+ self.draw[layer].polygon([(float(x) + o, float(y)) for x, y in P], fill=val)++ def _wob(self, amp, seed):+ """periodic wobble round the pot (a hand-held brush on the spinning wheel)"""+ r = np.random.default_rng(seed)+ u = np.linspace(0, 1, 361)+ out = np.zeros_like(u)+ for k in (1, 2, 3, 5):+ out += r.normal(0, amp / k) * np.sin(2 * np.pi * k * u + r.uniform(0, 6.3))+ return u, out++ def band(self, y0, y1, layer='slip'):+ """a band painted while the pot spins: level, with a small lap where the brush lifted off"""+ u, w0 = self._wob(0.35, self._seed())+ _, w1 = self._wob(0.35, self._seed())+ lap = np.exp(-((u - self.rng.uniform(0.55, 0.95)) / 0.012) ** 2) * 0.9+ x = u * self.TW * self.ls+ top = (y0 + w0 - lap * 0.4) * self.ls+ bot = (y1 + w1 + lap) * self.ls+ poly = np.vstack([np.stack([x, top], 1), np.stack([x[::-1], bot[::-1]], 1)])+ self._ver += 1+ self.draw[layer].polygon([(float(a), float(b)) for a, b in poly], fill=255)++ def paint_handles(self):+ self.handles_painted = True++ def tongues(self, y0, y1, n=None, red_every=2):+ """shoulder tongues hanging from the neck: black, every other one overpainted red"""+ z = Zone(self, y0, y1)+ n = n or int(round(z.C / 26))+ P = z.C / n+ h = y1 - y0+ f = _Fig()+ for i in range(n):+ x = i * P+ g = P * 0.09+ a = np.linspace(0, np.pi, 10)+ bottom = np.stack([x + P / 2 + (P / 2 - g) * np.cos(a), y1 - (P / 2 - g) * 0.9 + (P / 2 - g) * 0.9 * np.sin(a)], 1)+ poly = np.vstack([[(x + g, y0), (x + P - g, y0)], bottom])+ f.slip(poly)+ if red_every and i % red_every == 1:+ f.red(poly)+ z.emit(f, 0, 0, 1.0, jitter=0.15)++ def meander(self, y0, y1, n=None):+ """a running key: up, across, down, back, down and on to the next"""+ z = Zone(self, y0, y1)+ h = y1 - y0+ g = h / 4.6+ n = n or int(round(z.C / (g * 5)))+ P = z.C / n+ g = P / 5+ f = _Fig()+ key = [(0, 4), (0, 0), (3, 0), (3, 2), (1, 2), (1, 4), (5, 4)]+ for i in range(n):+ pts = [(i * P + gx * g, y0 + 0.3 * g + gy * g * (h - 0.6 * g) / (4 * g)) for gx, gy in key]+ for a, b in zip(pts[:-1], pts[1:]):+ a, b = np.array(a, np.float32), np.array(b, np.float32)+ d = (b - a) / (np.linalg.norm(b - a) + 1e-6) * g * 0.31 # square joins: overrun by w/2+ f.slip(_ribbon([a - d, b + d], g * 0.62, per=1, caps=False, smooth=False))+ z.emit(f, 0, 0, 1.0, jitter=0.12)++ def rays(self, y0, y1, n=None):+ """tall black rays rising from the foot"""+ z = Zone(self, y0, y1)+ n = n or int(round(z.C / 30))+ P = z.C / n+ f = _Fig()+ for i in range(n):+ x = i * P + P / 2+ f.slip([(x - P * 0.40, y1), (x - P * 0.05, y0 + 2), (x + P * 0.05, y0 + 2), (x + P * 0.40, y1)])+ z.emit(f, 0, 0, 1.0, jitter=0.2)++ def palmettes(self, y0, y1, n=5):+ """neck: upright palmettes sitting in the loops of a festoon, lotus flowers hanging at the joins"""+ z = Zone(self, y0, y1)+ P = z.C / n+ h = y1 - y0+ f = _Fig()+ for i in range(n):+ x = i * P + P * 0.25+ yb = y1 - h * 0.17+ xj, yj = x + P / 2, y0 + h * 0.20 # festoon join (lotus)+ for sgn in (-1, 1): # festoon arcs+ f.line([(x, yb + h * 0.075), (x + sgn * P * 0.22, yb + h * 0.035), (x + sgn * P * 0.40, y0 + h * 0.42),+ (x + sgn * P * 0.5, yj)], w=1.7)+ for a in np.linspace(-0.98, 0.98, 9): # fan of petals+ L = h * (0.60 - 0.24 * (a / 0.98) ** 2)+ d = np.array([np.sin(a), -np.cos(a)])+ base = np.array([x, yb]) + d * h * 0.12+ f.slip(_ribbon([base, base + d * L * 0.62, base + d * L], [h * 0.018, h * 0.07, h * 0.062], per=4))+ heart = np.vstack([_arc(x, yb, h * 0.115, np.pi, 2 * np.pi, 14), [(x + h * 0.115, yb + h * 0.05),+ (x - h * 0.115, yb + h * 0.05)]])+ f.slip(heart)+ f.red(heart)+ f.cut(_arc(x, yb, h * 0.115, np.pi, 2 * np.pi, 12), w=1.0)+ # hanging lotus: calyx, a long central petal and two petals curling outwards+ f.slip([(xj - h * 0.055, y0 + h * 0.06), (xj + h * 0.055, y0 + h * 0.06), (xj + h * 0.045, yj + h * 0.06),+ (xj - h * 0.045, yj + h * 0.06)])+ f.slip(_ribbon([(xj, yj + h * 0.04), (xj, yj + h * 0.30), (xj, yj + h * 0.47)], [h * 0.07, h * 0.075, h * 0.012], per=4))+ for sgn in (-1, 1):+ f.slip(_ribbon([(xj + sgn * h * 0.03, yj + h * 0.05), (xj + sgn * h * 0.14, yj + h * 0.20),+ (xj + sgn * h * 0.24, yj + h * 0.28), (xj + sgn * h * 0.30, yj + h * 0.25)],+ [h * 0.055, h * 0.05, h * 0.03, h * 0.012], per=4))+ f.red([(xj - h * 0.05, y0 + h * 0.10), (xj + h * 0.05, y0 + h * 0.10), (xj + h * 0.047, yj),+ (xj - h * 0.047, yj)])+ f.cut([(xj - h * 0.05, yj + h * 0.02), (xj + h * 0.05, yj + h * 0.02)], w=1.0)+ z.emit(f, 0, 0, 1.0, jitter=0.12)++ # ------------------------------------------------------------ the three painting passes+ def paint(self):+ """brush on the slip for every figure declared since the last call"""+ for layer, poly, occ in self.ops[self._painted:]:+ if layer == 'slip':+ self._fill('slip', poly, 255)+ self._painted = len(self.ops)++ def incise(self):+ """scratch the details through the slip (replayed in depth order: nearer black hides farther lines)"""+ self.draw['inc'].rectangle([0, 0, self.TW * self.ls, self.TH * self.ls], fill=0)+ for layer, poly, occ in self.ops:+ if layer == 'slip' and occ:+ self._fill('inc', poly, 0)+ elif layer == 'inc':+ self._fill('inc', poly, 255)++ def add_colour(self):+ """added red and white over the black, last, in depth order"""+ for k in ('red', 'white'):+ self.draw[k].rectangle([0, 0, self.TW * self.ls, self.TH * self.ls], fill=0)+ for layer, poly, occ in self.ops:+ if layer == 'slip' and occ:+ self._fill('red', poly, 0); self._fill('white', poly, 0)+ elif layer in ('red', 'white'):+ self._fill(layer, poly, 255)++ def fire(self):+ self.fired = True++ def age(self, mend=None, misfire=None, chips=7, roots=14, seed=None):+ """mend: (u, v, rx, ry) restored loss in unrolled px; misfire: (u, v, r)"""+ self.aged = True+ self._age = dict(mend=mend, misfire=misfire, chips=chips, roots=roots, seed=seed or self._seed())+ self._agemaps = None++ # ------------------------------------------------------------ materials on the unrolled surface (1x)+ def _layer(self, k):+ return np.asarray(self.layers[k].resize((self.TW, self.TH), Image.BOX), np.float32) / 255++ def _noises(self):+ if self._noise is None:+ TH, TW = self.TH, self.TW+ r = np.random.default_rng(self._seed())+ streak = np.asarray(Image.fromarray(r.random((TH // 2, TW // 24)).astype(np.float32)).resize((TW, TH), Image.BICUBIC))+ self._noise = dict(lo=noise2d(TH, TW, 160, 3, self._seed()), mid=noise2d(TH, TW, 30, 3, self._seed()),+ fine=r.random((TH, TW)).astype(np.float32), streak=np.clip(streak, 0, 1))+ return self._noise++ def _age_maps(self):+ if self._agemaps is not None:+ return self._agemaps+ TH, TW = self.TH, self.TW+ a = self._age+ r = np.random.default_rng(a['seed'])+ N = self._noises()+ m = {}+ m['flake'] = smoothstep(0.60, 0.66, noise2d(TH, TW, 5, 3, a['seed'] + 1)) * smoothstep(0.35, 0.6, noise2d(TH, TW, 40, 2, a['seed'] + 4))+ V = np.arange(TH, dtype=np.float32)[:, None] / TH+ cn = noise2d(TH, TW, 14, 3, a['seed'] + 2) * 0.6 + noise2d(TH, TW, 60, 2, a['seed'] + 3) * 0.4+ m['crust'] = smoothstep(0.70, 0.84, cn) * (0.08 + 0.92 * smoothstep(0.55, 1.0, V)) * 0.7+ m['crust'] = np.maximum(m['crust'], (N['fine'] > 0.999).astype(np.float32) * 0.45 * V)+ im = Image.new('L', (TW, TH), 0)+ d = ImageDraw.Draw(im)+ for i in range(a['roots']): # root marks: thin wandering lines+ x, y = r.uniform(0, TW), r.uniform(TH * 0.3, TH * 0.95)+ ang = r.uniform(0, 2 * np.pi)+ pts = []+ for s in range(int(r.uniform(30, 90))):+ ang += r.normal(0, 0.35)+ x += np.cos(ang) * 3; y += np.sin(ang) * 3+ pts.append((x % TW, y))+ for p0, p1 in zip(pts[:-1], pts[1:]):+ if abs(p0[0] - p1[0]) < 10:+ d.line([p0, p1], fill=int(r.uniform(35, 75)), width=1)+ m['roots'] = np.asarray(im, np.float32) / 255+ im = Image.new('L', (TW * 2, TH * 2), 0) # chips on the lip and the foot+ d = ImageDraw.Draw(im)+ for i in range(a['chips']):+ u = r.uniform(0, TW)+ v = r.choice([r.uniform(0, 3), r.uniform(TH - 4, TH)]) if i > 1 else (1.0 if i == 0 else TH - 1.5)+ rr = r.uniform(3.0, 7.0)+ ang = np.linspace(0, 2 * np.pi, 24, endpoint=False)+ k = 1 + 0.35 * fbm1d(24, 5, 2, int(r.integers(1 << 30)))+ pts = [((u + np.cos(t) * rr * q * 1.7) * 2, (v + np.sin(t) * rr * q) * 2) for t, q in zip(ang, k)]+ d.polygon(pts, fill=255)+ m['chip'] = np.asarray(im.resize((TW, TH), Image.BOX), np.float32) / 255+ m['fill'] = np.zeros((TH, TW), np.float32)+ m['crack'] = np.zeros((TH, TW), np.float32)+ if a['mend']:+ u, v, rx, ry = a['mend']+ ang = np.linspace(0, 2 * np.pi, 60, endpoint=False)+ k = 1 + 0.42 * fbm1d(60, 10, 4, a['seed'] + 5)+ pts = [((u + np.cos(t) * rx * q) * 2, (v + np.sin(t) * ry * q) * 2) for t, q in zip(ang, k)]+ im = Image.new('L', (TW * 2, TH * 2), 0)+ ImageDraw.Draw(im).polygon(pts, fill=255)+ m['fill'] = np.asarray(im.resize((TW, TH), Image.BOX), np.float32) / 255+ im = Image.new('L', (TW * 2, TH * 2), 0)+ d = ImageDraw.Draw(im)+ d.line(pts + pts[:1], fill=255, width=2)+ for j in range(4): # glued cracks running off the loss+ t = r.uniform(0, 2 * np.pi)+ x, y = u + np.cos(t) * rx, v + np.sin(t) * ry+ ang2 = t+ seg = [(x * 2, y * 2)]+ for s in range(int(r.uniform(14, 34))):+ ang2 += r.normal(0, 0.28)+ x += np.cos(ang2) * 5; y += np.sin(ang2) * 5+ seg.append((x * 2, y * 2))+ d.line(seg, fill=255, width=2)+ m['crack'] = np.asarray(im.resize((TW, TH), Image.BOX), np.float32) / 255+ m['misfire'] = np.zeros((TH, TW), np.float32)+ if a['misfire']:+ u, v, rr = a['misfire']+ U, Vv = np.meshgrid(np.arange(TW, dtype=np.float32), np.arange(TH, dtype=np.float32))+ du = (U - u + TW / 2) % TW - TW / 2+ m['misfire'] = np.exp(-(du ** 2 / (2 * (rr * 1.6) ** 2) + (Vv - v) ** 2 / (2 * rr ** 2))) * \+ (0.6 + 0.4 * N['mid'])+ del U, Vv, du+ self._agemaps = m+ return m++ def materials(self):+ """-> albedo (TH, TW, 3) sRGB, gloss (TH, TW), satin (0..1) for the current state of the pot"""+ key = (self._ver, self.fired, self.aged)+ if self._mat is None or self._mat[0] != key:+ self._mat = (key, self._materials())+ return self._mat[1]++ def _materials(self):+ s, rd, wh, inc = (self._layer(k) for k in ('slip', 'red', 'white', 'inc'))+ N = self._noises()+ se = s * (1 - inc)+ fired = self.fired+ clay = _hex(COLOURS['clay' if fired else 'clay_raw'])+ alb = np.empty((self.TH, self.TW, 3), np.float32)+ var = (0.955 + 0.07 * N['lo'] + 0.03 * N['mid'] + 0.025 * (N['fine'] - 0.5))+ alb[:] = clay * var[..., None]+ if fired:+ thick = np.clip(0.78 + 0.45 * (N['mid'] - 0.5) + 0.08 * (N['streak'] - 0.5), 0, 1)+ thick *= smoothstep(0.25, 0.95, blur(s, 1.2))+ black = _hex(COLOURS['thin']) * (1 - thick[..., None] ** 0.5) + _hex(COLOURS['black']) * thick[..., None] ** 0.5+ else:+ black = _hex(COLOURS['slip_raw']) * (0.94 + 0.04 * N['streak'] + 0.08 * N['mid'])[..., None]+ alb = alb * (1 - se[..., None]) + black * se[..., None]+ gloss = (se * (0.82 + 0.18 * N['streak'])) if fired else np.zeros_like(se)+ if self.aged:+ A = self._age_maps()+ wh = wh * (1 - 0.8 * A['flake'])+ rd = rd * (0.78 + 0.22 * N['mid'])+ ghost = (self._layer('white') - wh) * se+ alb = alb * (1 - 0.35 * ghost[..., None]) + _hex('#3b3633') * 0.35 * ghost[..., None]+ gloss = gloss * (1 - 0.8 * ghost)+ red = _hex(COLOURS['red' if fired else 'red_raw'])+ white = _hex(COLOURS['white' if fired else 'white_raw'])+ rv = (rd * (1 - 0.55 * inc))[..., None]+ wv = (wh * (1 - 0.35 * inc))[..., None]+ alb = alb * (1 - rv) + red * (0.92 + 0.12 * N['mid'])[..., None] * rv+ alb = alb * (1 - wv) + white * (0.93 + 0.08 * N['mid'])[..., None] * wv+ alb = alb * (1 - (wh * inc * 0.3)[..., None])+ gloss = gloss * (1 - np.clip(rd + wh, 0, 1) * 0.92)+ if self.aged:+ A = self._age_maps()+ mf = (A['misfire'] * se)[..., None]+ alb = alb * (1 - 0.6 * mf) + _hex(COLOURS['misfire']) * 0.6 * mf+ fl = A['fill'][..., None]+ dark = se[..., None]+ toned = _hex(COLOURS['fill_clay']) * (1 - dark) + _hex(COLOURS['fill_black']) * dark+ toned = toned * (1 - rv * 0.7) + _hex('#8b5a52') * rv * 0.7+ alb = alb * (1 - fl) + toned * (0.97 + 0.04 * N['fine'][..., None]) * fl+ gloss = gloss * (1 - A['fill'] * 0.9)+ ck = A['crack'][..., None]+ alb = alb * (1 - 0.75 * ck) + (_hex('#2a1810') * (1 - dark) + _hex('#6a5a50') * dark) * 0.75 * ck+ ch = A['chip'][..., None]+ alb = alb * (1 - ch) + _hex(COLOURS['fabric']) * (0.92 + 0.12 * N['fine'][..., None]) * ch+ gloss = gloss * (1 - A['chip'])+ cr = np.clip(A['crust'] * 0.5 + A['roots'] * 0.5, 0, 1)+ alb = alb * (1 - cr[..., None]) + _hex(COLOURS['crust']) * cr[..., None]+ gloss = gloss * (1 - cr) * (0.9 + 0.1 * N['lo'])+ return alb, gloss, (0.55 if fired else 0.12)+++class BlackFigure:+ def __init__(self, W=1920, H=1080, seed=0):+ self.W, self.H = W, H+ self.rng = np.random.default_rng(seed)+ self.pots, self.overlays, self.stages = [], [], []+ self._base = None+ self.img = np.zeros((H, W, 3), np.float32)+ self.museum()++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ the room+ def museum(self, wall='#1c2427', plinth='#cbc2b4', spot=None, plinth_x=None):+ self._room = dict(wall=wall, plinth=plinth, spot=spot, plinth_x=plinth_x)+ self._base = None++ def throw(self, cx, foot, height, rmax=None, shape='neck_amphora', eye=0.42):+ """throw a pot standing on the plinth at screen (cx, foot)"""+ p = Pot(cx, foot, height, rmax, shape, self._seed(), eye=eye)+ self.pots.append(p)+ self._base = None+ return p++ def _build_base(self):+ H, W = self.H, self.W+ rm = self._room+ Y, X = np.mgrid[0:H, 0:W].astype(np.float32)+ p = self.pots[0] if self.pots else None+ sx, sy = rm['spot'] or ((p.cx, p.top + p.H * 0.42) if p else (W / 2, H / 2))+ spot = np.exp(-((X - sx) ** 2 / (2 * 560 ** 2) + (Y - sy) ** 2 / (2 * 470 ** 2)))+ wall = _hex(rm['wall'])+ img = wall * (0.62 + 0.62 * spot[..., None]) * (1 + 0.05 * (noise2d(H, W, 220, 3, self._seed()) - 0.5))[..., None]+ img += np.array([0.035, 0.022, 0.008], np.float32) * spot[..., None] ** 2+ img *= (1 + 0.03 * (noise2d(H, W, 3, 2, self._seed()) - 0.5))[..., None]+ if p:+ foot = p.top + p.H+ rf = float(p.radius(p.H - 1))+ dfront = p.persp * (p.H - p.eye) * rf / p.R+ x0, x1 = rm['plinth_x'] or (p.cx - 330, p.cx + 330)+ t0, t1 = foot - 38, foot + dfront + 34+ pl = _hex(rm['plinth'])+ top = (Y >= t0) & (Y < t1) & (X >= x0) & (X < x1)+ front = (Y >= t1) & (X >= x0) & (X < x1)+ tshade = (0.58 + 0.30 * smoothstep(t0, t1, Y)) * (0.80 + 0.26 * spot)+ fshade = (0.55 - 0.18 * smoothstep(t1, H, Y)) * (0.8 + 0.3 * spot)+ grain = 1 + 0.035 * (noise2d(H, W, 2.5, 2, self._seed()) - 0.5)+ img = np.where(top[..., None], pl * (tshade * grain)[..., None], img)+ img = np.where(front[..., None], pl * (fshade * grain)[..., None], img)+ edge = np.exp(-((Y - t1) / 1.2) ** 2) * ((X >= x0) & (X < x1))+ img += 0.08 * edge[..., None]+ # contact shadow + a soft cast shadow of the pot on the plinth top+ cs = np.exp(-(((X - p.cx) / (rf * 1.08)) ** 2 + ((Y - foot - dfront * 0.35) / (dfront * 1.2 + 8)) ** 2) ** 2)+ cs = blur(np.clip(cs, 0, 1), 4)+ ss = blur(np.exp(-(((X - p.cx - 95) / 300) ** 2 + ((Y - foot - 6) / 22) ** 2)), 6)+ m = top | front+ img *= (1 - (0.75 * cs + 0.38 * ss) * m)[..., None]+ vig = 1 - 0.38 * smoothstep(0.55, 1.25, np.hypot((X - W / 2) / (W / 2), (Y - H / 2) / (H / 2)))+ img *= vig[..., None]+ self._base = np.clip(img, 0, 1)++ # ------------------------------------------------------------ the photograph of the pot+ def _geometry(self, p, ss=2):+ x0, x1 = int(p.cx - p.R * 1.02) - 4, int(p.cx + p.R * 1.02) + 4+ y0, y1 = int(p.top - 30), int(p.top + p.H + 40)+ Hs, Ws = (y1 - y0) * ss, (x1 - x0) * ss+ Ys = ((np.arange(Hs, dtype=np.float32) + 0.5) / ss + y0 - p.top)[:, None]+ Xr = ((np.arange(Ws, dtype=np.float32) + 0.5) / ss + x0 - p.cx)[None, :]+ c, ye = p.persp, p.eye+ yl = np.broadcast_to(Ys, (Hs, Ws)).copy()+ for _ in range(5):+ r = p.radius(yl)+ z = np.sqrt(np.clip(r * r - Xr * Xr, 0, None))+ yl = (Ys + c * ye * z / p.R) / (1 + c * z / p.R)+ r = p.radius(yl)+ inside = (r * r - Xr * Xr > 0) & (yl >= 0) & (yl <= p.H)+ idx = np.flatnonzero(inside)+ yv = yl.ravel()[idx]+ rv = r.ravel()[idx]+ xv = Xr[0, idx % Ws]+ del yl, r, z+ sn = np.clip(xv / rv, -1, 1)+ th = np.arcsin(sn)+ cs = np.cos(th)+ dr = (p.radius(yv + 0.75) - p.radius(yv - 0.75)) / 1.5+ dr = dr + 0.009 * np.sin(2 * np.pi * yv / 8.5 + 2.0 * fbm1d(4096, 300, 3, 7)[np.clip(yv * 3.5, 0, 4095).astype(int)])+ n = np.stack([sn, -dr, cs], 1)+ n /= np.linalg.norm(n, axis=1, keepdims=True)+ g = dict(x0=x0, y0=y0, Hs=Hs, Ws=Ws, ss=ss, idx=idx, tu=(th + np.pi / 2) / (2 * np.pi) * p.TW, tv=yv,+ cmp=1 / np.maximum(cs, 0.05))+ g.update(self._shade(n))+ # ambient occlusion under the overhanging lip+ occ = np.zeros_like(yv)+ for dy in (3, 6, 10, 16, 24):+ occ = np.maximum(occ, (p.radius(yv - dy) - rv) / (dy + 6))+ g['D'] *= 1 - 0.55 * np.clip(occ, 0, 1)+ return g++ def _shade(self, n):+ """lighting terms that depend only on the surface normal"""+ nx, ny, nz = n[:, 0], n[:, 1], n[:, 2]+ Lk = np.array([-0.60, -0.48, 0.64]); Lk /= np.linalg.norm(Lk)+ Lf = np.array([0.75, -0.15, 0.64]); Lf /= np.linalg.norm(Lf)+ D = 0.95 * np.clip(nx * Lk[0] + ny * Lk[1] + nz * Lk[2], 0, 1) + 0.22 * np.clip(nx * Lf[0] + ny * Lf[1] + nz * Lf[2], 0, 1) \+ + 0.10 + 0.06 * np.clip(-ny, 0, 1)+ Rx, Ry, Rz = 2 * nz * nx, 2 * nz * ny, 2 * nz * nz - 1+ az = np.arctan2(Rx, Rz)+ el = np.arcsin(np.clip(-Ry, -1, 1))++ def box(a0, a1, e0, e1, s):+ return (smoothstep(a0 - s, a0 + s, az) * (1 - smoothstep(a1 - s, a1 + s, az)) *+ smoothstep(e0 - s, e0 + s, el) * (1 - smoothstep(e1 - s, e1 + s, el)))++ def env(s):+ return (0.03 + 6.0 * box(-0.90, -0.76, -0.45, 1.0, s) + 0.5 * box(-1.3, -0.3, -0.2, 0.9, s * 3) + 3.0 * box(0.98, 1.08, -0.25, 0.80, s * 0.6)+ + 0.25 * smoothstep(0.75, 1.35, el) + 0.30 * smoothstep(-0.12, -0.45, el))+ F = 0.045 + 0.955 * (1 - np.clip(nz, 0, 1)) ** 5+ return dict(D=D.astype(np.float32), Es=env(0.035).astype(np.float32), Eb=env(0.45).astype(np.float32),+ F=F.astype(np.float32))++ def _handles(self, p, ss=2):+ """the two round handles as glazed tubes standing at the silhouette"""+ hp = np.array(p.shape['handle'], np.float32)+ rt = p.shape['handle_w'] * p.R / 2+ out = []+ for sgn in (-1, 1):+ C = spline(np.stack([p.cx + sgn * hp[:, 0] * p.R, p.top + hp[:, 1] * p.H], 1), 10)+ x0, x1 = int(C[:, 0].min() - rt - 3), int(C[:, 0].max() + rt + 3)+ y0, y1 = int(C[:, 1].min() - rt - 3), int(C[:, 1].max() + rt + 3)+ Hs, Ws = (y1 - y0) * ss, (x1 - x0) * ss+ Y, X = np.mgrid[0:Hs, 0:Ws].astype(np.float32)+ Y = Y / ss + y0 + 0.5 / ss; X = X / ss + x0 + 0.5 / ss+ best = np.full(Y.shape, 1e9, np.float32)+ vx = np.zeros_like(Y); vy = np.zeros_like(Y); tpar = np.zeros_like(Y)+ for i in range(len(C) - 1):+ a, b = C[i], C[i + 1]+ ab = b - a+ t = np.clip(((X - a[0]) * ab[0] + (Y - a[1]) * ab[1]) / (ab @ ab + 1e-9), 0, 1)+ dx, dy = X - (a[0] + ab[0] * t), Y - (a[1] + ab[1] * t)+ dd = dx * dx + dy * dy+ m = dd < best+ best = np.where(m, dd, best); vx = np.where(m, dx, vx); vy = np.where(m, dy, vy)+ tpar = np.where(m, (i + t) / (len(C) - 1), tpar)+ d = np.sqrt(best)+ a = np.clip(d / rt, 0, 1)+ inside = d < rt+ rr = np.maximum(d, 1e-6)+ n = np.stack([vx / rr * a, vy / rr * a, np.sqrt(1 - a * a)], -1)[inside]+ out.append(dict(x0=x0, y0=y0, Hs=Hs, Ws=Ws, ss=ss, idx=np.flatnonzero(inside), **self._shade(n)))+ return out++ def _composite(self, img, g, col):+ """col: linear colour per inside sample -> anti-aliased paste"""+ ss, Hs, Ws = g['ss'], g['Hs'], g['Ws']+ buf = np.zeros((Hs * Ws, 3), np.float32)+ buf[g['idx']] = col+ al = np.zeros(Hs * Ws, np.float32)+ al[g['idx']] = 1+ h, w = Hs // ss, Ws // ss+ buf = buf.reshape(h, ss, w, ss, 3).mean((1, 3))+ al = al.reshape(h, ss, w, ss).mean((1, 3))+ c = _srgb(buf / np.maximum(al, 1e-6)[..., None])+ y0, x0 = g['y0'], g['x0']+ ya, xa = max(0, -y0), max(0, -x0)+ yb, xb = min(h, self.H - y0), min(w, self.W - x0)+ sl = img[y0 + ya:y0 + yb, x0 + xa:x0 + xb]+ a = al[ya:yb, xa:xb, None]+ img[y0 + ya:y0 + yb, x0 + xa:x0 + xb] = sl * (1 - a) + c[ya:yb, xa:xb] * a++ def _render_pot(self, img, p):+ if p._geo is None:+ p._geo = (self._geometry(p), self._handles(p))+ g, hs = p._geo+ alb, gloss, satin = p.materials()+ alb_l = _lin(alb)+ soft_l = blur_h(alb_l, 2.0) # pre-filtered copy for the foreshortened flanks+ n = len(g['idx'])+ col = np.empty((n, 3), np.float32)+ for c0 in range(0, n, 300000): # in chunks: keeps the temporaries small+ sl = slice(c0, min(n, c0 + 300000))+ tu, tv = g['tu'][sl], g['tv'][sl]+ wm = smoothstep(1.8, 4.5, g['cmp'][sl])[:, None]+ a = _bilinear(alb_l, tu, tv) * (1 - wm) + _bilinear(soft_l, tu, tv) * wm+ gl = _bilinear(gloss, tu, tv)+ F, D = g['F'][sl], g['D'][sl]+ col[sl] = a * D[:, None] + (gl * F * g['Es'][sl])[:, None] + ((1 - gl) * satin * 0.6 * F * g['Eb'][sl])[:, None]+ del alb_l, soft_l+ self._composite(img, g, col)+ for h in hs:+ if p.handles_painted:+ ab = _lin(_hex(COLOURS['black'] if p.fired else COLOURS['slip_raw']))+ gh = 0.9 if p.fired else 0.0+ else:+ ab = _lin(_hex(COLOURS['clay'] if p.fired else COLOURS['clay_raw']))+ gh = 0.0+ col = ab[None, :] * h['D'][:, None] + (gh * h['F'] * h['Es'])[:, None] + \+ ((1 - gh) * satin * 0.6 * h['F'] * h['Eb'])[:, None]+ self._composite(img, h, col)++ # ------------------------------------------------------------ the rollout panel+ def panel(self, box, title='', subtitle='', english='', greek='', board='#232b2f'):+ """a dark display board on the wall with a title block"""+ def draw(img, box=box):+ x0, y0, x1, y1 = box+ sh = np.zeros((self.H, self.W), np.float32)+ sh[y0 + 8:y1 + 8, x0 + 6:x1 + 6] = 1+ img *= (1 - 0.45 * blur(sh, 9))[..., None]+ b = _hex(board)+ img[y0:y1, x0:x1] = b * (1 + 0.03 * (noise2d(y1 - y0, x1 - x0, 3, 2, 5) - 0.5))[..., None]+ img[y0:y0 + 1, x0:x1] += 0.05; img[y0:y1, x0:x0 + 1] += 0.04+ cream = _hex('#eadcc0')+ if title:+ self._text(img, title, (x0 + 40, y0 + 70), 'songti', 50, cream)+ if greek:+ self._text(img, greek, (x1 - 40, y0 + 64), 'serif', 17, _hex('#c98a5e'), anchor='rs', spacing=3)+ if subtitle:+ self._text(img, subtitle, (x0 + 42, y0 + 106), 'songti', 21, cream * 0.88)+ if english:+ self._text(img, english, (x0 + 42, y0 + 132), 'serif', 16, cream * 0.62)+ img[y0 + 148:y0 + 149, x0 + 40:x1 - 40] = cream * 0.35+ self.overlays.append(draw)++ def _text(self, img, s, xy, font, size, col, anchor='ls', spacing=0.0):+ if font == 'songti':+ path = '/System/Library/Fonts/Supplemental/Songti.ttc'+ from PIL import ImageFont+ f = ImageFont.truetype(path, size, index=6) if os.path.exists(path) else load_font('cjk', size)+ else:+ f = load_font(font, size)+ m = text_mask(self.H, self.W, s, f, xy, anchor=anchor, spacing=spacing)+ img[:] = img * (1 - m[..., None]) + np.asarray(col, np.float32) * m[..., None]++ def rollout(self, pot, bands, x, y, scale=0.86, half=0, caption='', ticks=('0°', '180°')):+ """the friezes between the y's in `bands` unrolled flat (one row per band, each at its own+ circumference), stacked and centred under each other. half: 0 = front (A), 1 = back (B)."""+ def draw(img):+ al, gl, _ = pot.materials()+ yy = y+ widths = []+ for (b0, b1) in bands:+ z = Zone(pot, b0, b1)+ w, h = int(z.C / 2 * scale), int(round((b1 - b0) * scale))+ widths.append(w)+ jj, ii = np.meshgrid(np.arange(w, dtype=np.float32) + 0.5, np.arange(h, dtype=np.float32) + 0.5)+ u = (jj / scale + half * z.C / 2) * z.k+ v = b0 + ii / scale+ col = _bilinear(al, u.ravel(), v.ravel()).reshape(h, w, 3)+ gs = _bilinear(gl, u.ravel(), v.ravel()).reshape(h, w)+ col = col * 0.97 + 0.05 * gs[..., None] * (0.8 + 0.4 * jj / w)[..., None]+ x0 = int(x - w / 2)+ img[yy:yy + h, x0:x0 + w] = np.clip(col, 0, 1)+ yy += h+ wmax = max(widths)+ x0 = int(x - wmax / 2)+ sh = np.zeros((self.H, self.W), np.float32)+ yy = y+ for w, (b0, b1) in zip(widths, bands):+ h = int(round((b1 - b0) * scale))+ sh[yy:yy + h, int(x - w / 2):int(x - w / 2) + w] = 1+ yy += h+ edge = np.clip(blur(sh, 2.5) - sh, 0, 1)+ img *= (1 - 0.6 * edge)[..., None]+ cream = _hex('#eadcc0')+ if caption:+ self._text(img, caption, (x0, y - 12), 'songti', 18, cream * 0.85)+ if ticks:+ self._text(img, ticks[0], (x0, yy + 22), 'serif', 14, cream * 0.6)+ self._text(img, ticks[1], (x0 + wmax, yy + 22), 'serif', 14, cream * 0.6, anchor='rs')+ img[yy + 4:yy + 9, x0:x0 + 1] = cream * 0.5+ img[yy + 4:yy + 9, x0 + wmax - 1:x0 + wmax] = cream * 0.5+ self.overlays.append(draw)++ def legend(self, x, y, items):+ """technique swatches: [(label, kind)] with kind in clay / black / incision / red / white"""+ def draw(img):+ cream = _hex('#eadcc0')+ xx = x+ for label, kind in items:+ sw = np.zeros((18, 30, 3), np.float32)+ base = _hex(COLOURS['clay']) if kind == 'clay' else _hex(COLOURS['black'])+ sw[:] = base+ if kind == 'incision':+ for k in range(30):+ yk = int(9 + 4 * np.sin(k / 4.0))+ sw[yk, k] = _hex(COLOURS['clay'])+ if kind == 'red':+ sw[:] = _hex(COLOURS['red'])+ if kind == 'white':+ sw[:] = _hex(COLOURS['white'])+ if kind == 'black':+ sw[3:6, :] += 0.18+ img[y - 15:y + 3, xx:xx + 30] = sw+ self._text(img, label, (xx + 40, y), 'songti', 17, cream * 0.8)+ f = load_font('cjk', 17)+ from PIL import ImageFont+ path = '/System/Library/Fonts/Supplemental/Songti.ttc'+ if os.path.exists(path):+ f = ImageFont.truetype(path, 17, index=6)+ xx += 40 + int(f.getlength(label)) + 36+ self.overlays.append(draw)++ # ------------------------------------------------------------ output+ def render(self):+ if self._base is None:+ self._build_base()+ img = self._base.copy()+ for p in self.pots:+ self._render_pot(img, p)+ for o in self.overlays:+ o(img)+ self.img = img+ return img++ def stage(self, name):+ self.stages.append((name, self.image(self.render())))++ def image(self, img=None):+ img = self.render() if img is None else img+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def save(self, path, stages_dir=None, quality=88):+ img = self.image()+ if str(path).lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return img+++def blur_h(a, r):+ """horizontal box blur (wrapping) -- the far side of the pot is seen foreshortened"""+ k = int(max(1, r))+ out = a.copy()+ for d in range(1, k + 1):+ out += np.roll(a, d, axis=1) + np.roll(a, -d, axis=1)+ return out / (2 * k + 1)diff --git a/lib/blueprint.py b/lib/blueprint.pynew file mode 100644index 0000000..05ae481--- /dev/null+++ b/lib/blueprint.py@@ -0,0 +1,872 @@+"""blueprint — engineering blueprints: an inked tracing contact-printed on ferro-prussiate paper (numpy + Pillow only).++Model (how a real blueprint of ~1880-1950 was made, and what happened to it afterwards):+ tracing : the draughtsman inks the drawing on translucent tracing linen with ruling pens of a few fixed widths+ (heavy outlines, medium edges, thin dimension and hatch lines, fine centre lines). Ink pools a little+ where the pen stops, so line ends are a hair fatter. Lettering is single-stroke capitals drawn through a+ lettering guide (`text`: a built-in stroke font, uniform pen width, optional slant), pencil guide lines+ and construction lines stay on the linen faintly (`pencil`). Mistakes are scraped off with a razor+ (`erase`). Everything follows drafting conventions: section hatching clipped to the cut material,+ dimension lines with extension lines and arrowheads, level datums, leaders, cutting-plane marks,+ detail bubbles, a north point, graphic scales, a border with zone marks, a title block.+ print : the tracing is clamped over paper coated with iron salts and exposed to an arc lamp. Ink blocks the+ light, so under every line the salts stay unreduced and wash out WHITE; everywhere else Prussian blue+ forms. Exposure E = transmission x lamp; the density follows an S-curve (a threshold, not a linear+ ramp), so heavy lines print clean white, fine lines print pale blue, and the background saturates.+ Light creeps under the edges of lines (sharp where the glass pressed the tracing flat, softer where+ contact was poor) and a faint halo forms around them. The lamp is stronger in the middle of the frame+ (darker blue there, paler towards the edges); the coating has faint machine streaks and mottle; the+ paper fibres show through. Colour comes from Beer-Lambert absorption of Prussian blue on paper.+ life : the sheet is folded to file size: creases crack the blue coat to a broken white line, the paper on+ each side of a fold catches the light differently, crossings wear through (`fold`). The panel that faced+ outwards fades and gets handled (`fade`, `grime`); alkaline water turns Prussian blue rust-brown inside+ a tide line (`stain`); drawing-pin holes rust (`tack`).+ redline : on site someone marks it up in red wax pencil -- clouds, notes, ticks (`red`, `red_text`, `cloud`).+ Red is the only colour that is not part of the print.++Coordinates are output pixels; drawing happens at `ss` x supersampling. Angles in degrees, counter-clockwise.++ from blueprint import Blueprint+ bp = Blueprint(1920, 1080, seed=3)+ bp.border(56, 30, 1890, 1050)+ bp.line([(300, 900), (300, 200)], 'thick'); bp.centerline([(300, 920), (300, 180)])+ bp.hatch([wall_poly], angle=45, spacing=6)+ bp.dim((200, 900), (400, 900), 30, '10.50')+ bp.text('SECTION A-A', 300, 980, 16, anchor='ms')+ bp.stage('drawn')+ bp.fold(xs=[640, 1280], ys=[540]); bp.stain(150, 980, 70)+ bp.cloud([(500, 300), (700, 300), (700, 360), (500, 360)]); bp.red_text('CHECK ON SITE', 720, 330, 26)+ bp.save('out.jpg')+"""+import glob+import os+import numpy as np+from PIL import Image, ImageDraw, ImageChops, ImageFont+from core import blur, fbm1d, noise2d, smoothstep, polygon_mask, blob_pts, spline, load_font, text_mask, cjk_font++PENS = {'heavy': 3.3, 'thick': 2.5, 'medium': 1.8, 'thin': 1.25, 'fine': 0.9}+PAPER = np.array([0.94, 0.95, 0.93], np.float32) # washed-out (unexposed) paper+ABSORB = np.array([2.85, 1.62, 0.70], np.float32) # Prussian blue: eats red, some green, little blue+RED = np.array([0.90, 0.30, 0.22], np.float32) # red wax pencil+++# ---------------------------------------------------------------- single-stroke lettering (lettering-guide capitals)+def _A(cx, cy, rx, ry, a0, a1, n=None):+ """elliptical arc in glyph units (y down; 0 deg = +x, 90 deg = down)"""+ n = n or max(6, int(abs(a1 - a0) / 10) + 2)+ t = np.radians(np.linspace(a0, a1, n))+ return [(cx + rx * np.cos(a), cy + ry * np.sin(a)) for a in t]+++def _S(*pts):+ """smooth stroke through control points"""+ return ('s', list(pts))+++def _glyphs():+ G = {+ 'A': (4.2, [[(0, 6), (2.1, 0), (4.2, 6)], [(0.75, 4), (3.45, 4)]]),+ 'B': (3.8, [[(0, 3), (2.4, 3)] + _A(2.4, 4.5, 1.4, 1.5, -90, 90) + [(0, 6), (0, 0), (2.2, 0)] + _A(2.2, 1.5, 1.3, 1.5, -90, 90) + [(0, 3)]]),+ 'C': (3.9, [_A(2.1, 3, 2.1, 3, -42, -318, 30)]),+ 'D': (4.0, [[(1.4, 0), (0, 0), (0, 6), (1.4, 6)] + _A(1.4, 3, 2.6, 3, 90, -90, 20)]),+ 'E': (3.5, [[(3.5, 0), (0, 0), (0, 6), (3.5, 6)], [(0, 3), (2.6, 3)]]),+ 'F': (3.4, [[(3.4, 0), (0, 0), (0, 6)], [(0, 3), (2.6, 3)]]),+ 'G': (4.2, [_A(2.1, 3, 2.1, 3, -40, -360, 32) + [(2.5, 3)]]),+ 'H': (4.0, [[(0, 0), (0, 6)], [(4, 0), (4, 6)], [(0, 3), (4, 3)]]),+ 'I': (0.0, [[(0, 0), (0, 6)]]),+ 'J': (3.4, [[(3.4, 0), (3.4, 4.3)] + _A(1.7, 4.3, 1.7, 1.7, 0, 180, 14)]),+ 'K': (3.8, [[(0, 0), (0, 6)], [(3.8, 0), (0, 4.1)], [(1.35, 2.65), (3.8, 6)]]),+ 'L': (3.4, [[(0, 0), (0, 6), (3.4, 6)]]),+ 'M': (4.8, [[(0, 6), (0, 0), (2.4, 6), (4.8, 0), (4.8, 6)]]),+ 'N': (4.0, [[(0, 6), (0, 0), (4, 6), (4, 0)]]),+ 'O': (4.4, [_A(2.2, 3, 2.2, 3, 0, 360, 36)]),+ 'P': (3.8, [[(0, 6), (0, 0), (2.2, 0)] + _A(2.2, 1.6, 1.6, 1.6, -90, 90, 14) + [(0, 3.2)]]),+ 'Q': (4.4, [_A(2.2, 3, 2.2, 3, 0, 360, 36), [(2.6, 4.3), (4.5, 6.4)]]),+ 'R': (3.8, [[(0, 6), (0, 0), (2.2, 0)] + _A(2.2, 1.6, 1.6, 1.6, -90, 90, 14) + [(0, 3.2)], [(2.0, 3.2), (3.8, 6)]]),+ 'S': (3.9, [_A(1.95, 1.5, 1.8, 1.5, -20, -270, 18) + _A(1.95, 4.5, 1.95, 1.5, -90, 160, 18)]),+ 'T': (4.0, [[(0, 0), (4, 0)], [(2, 0), (2, 6)]]),+ 'U': (4.0, [[(0, 0), (0, 4)] + _A(2, 4, 2, 2, 180, 0, 16) + [(4, 0)]]),+ 'V': (4.2, [[(0, 0), (2.1, 6), (4.2, 0)]]),+ 'W': (5.4, [[(0, 0), (1.35, 6), (2.7, 1.2), (4.05, 6), (5.4, 0)]]),+ 'X': (4.0, [[(0, 0), (4, 6)], [(4, 0), (0, 6)]]),+ 'Y': (4.2, [[(0, 0), (2.1, 3.1), (4.2, 0)], [(2.1, 3.1), (2.1, 6)]]),+ 'Z': (4.0, [[(0, 0), (4, 0), (0, 6), (4, 6)]]),+ '0': (3.6, [_A(1.8, 3, 1.8, 3, 0, 360, 34)]),+ '1': (3.6, [[(0.9, 1.1), (2.1, 0), (2.1, 6)]]),+ '2': (3.6, [_A(1.8, 1.75, 1.8, 1.75, -170, 15, 18) + [(0, 6), (3.6, 6)]]),+ '3': (3.6, [_A(1.8, 1.5, 1.7, 1.5, -160, 90, 18) + _A(1.8, 4.5, 1.8, 1.5, -90, 160, 18)]),+ '4': (3.8, [[(2.8, 6), (2.8, 0), (0, 4.2), (3.8, 4.2)]]),+ '5': (3.6, [[(3.4, 0), (0.4, 0), (0.15, 2.75)] + _A(1.8, 4.1, 1.8, 1.9, -142, 150, 20)]),+ '6': (3.6, [_A(2.2, 4.0, 2.2, 4.0, -60, -180, 12), _A(1.8, 4.2, 1.8, 1.8, 0, 360, 26)]),+ '7': (3.6, [[(0, 0), (3.6, 0), (1.2, 6)]]),+ '8': (3.6, [_A(1.8, 1.45, 1.55, 1.45, 90, 450, 26), _A(1.8, 4.45, 1.8, 1.55, -90, 270, 28)]),+ '9': (3.6, [_A(1.8, 1.8, 1.8, 1.8, 0, 360, 26), _A(1.4, 2.0, 2.2, 4.0, 0, 120, 12)]),+ '.': (0.0, [[(0, 5.92), (0, 6)]]),+ ',': (0.5, [[(0.5, 5.6), (0.5, 6.0), (0, 6.9)]]),+ ':': (0.0, [[(0, 2.4), (0, 2.48)], [(0, 5.92), (0, 6)]]),+ ';': (0.5, [[(0.5, 2.4), (0.5, 2.48)], [(0.5, 5.6), (0.5, 6.0), (0, 6.9)]]),+ '-': (2.4, [[(0, 3.1), (2.4, 3.1)]]),+ '–': (3.6, [[(0, 3.1), (3.6, 3.1)]]),+ '—': (5.0, [[(0, 3.1), (5.0, 3.1)]]),+ '_': (4.0, [[(0, 6.8), (4.0, 6.8)]]),+ '/': (3.0, [[(0, 6.4), (3.0, -0.4)]]),+ '(': (1.5, [_S((1.5, -0.4), (0.45, 1.3), (0.05, 3), (0.45, 4.7), (1.5, 6.4))]),+ ')': (1.5, [_S((0, -0.4), (1.05, 1.3), (1.45, 3), (1.05, 4.7), (0, 6.4))]),+ '[': (1.4, [[(1.4, -0.4), (0, -0.4), (0, 6.4), (1.4, 6.4)]]),+ ']': (1.4, [[(0, -0.4), (1.4, -0.4), (1.4, 6.4), (0, 6.4)]]),+ '+': (3.6, [[(0, 3.2), (3.6, 3.2)], [(1.8, 1.4), (1.8, 5.0)]]),+ '=': (3.2, [[(0, 2.3), (3.2, 2.3)], [(0, 4.0), (3.2, 4.0)]]),+ '<': (3.2, [[(3.2, 1.2), (0, 3.2), (3.2, 5.2)]]),+ '>': (3.2, [[(0, 1.2), (3.2, 3.2), (0, 5.2)]]),+ '°': (1.6, [_A(0.8, 0.8, 0.8, 0.8, 0, 360, 16)]),+ '±': (3.6, [[(0, 2.6), (3.6, 2.6)], [(1.8, 0.8), (1.8, 4.4)], [(0, 6), (3.6, 6)]]),+ 'Ø': (4.4, [_A(2.2, 3, 2.2, 3, 0, 360, 34), [(-0.2, 6.5), (4.6, -0.5)]]),+ '×': (3.0, [[(0, 1.7), (3, 4.7)], [(3, 1.7), (0, 4.7)]]),+ '·': (0.0, [[(0, 3.05), (0, 3.15)]]),+ "'": (0.0, [[(0, 0), (0, 1.6)]]),+ '"': (1.0, [[(0, 0), (0, 1.6)], [(1, 0), (1, 1.6)]]),+ '!': (0.0, [[(0, 0), (0, 4.3)], [(0, 5.92), (0, 6)]]),+ '?': (3.4, [_A(1.7, 1.6, 1.7, 1.6, -175, 60, 16) + [(1.7, 3.6), (1.7, 4.3)], [(1.7, 5.92), (1.7, 6)]]),+ '&': (4.2, [_S((4.2, 6), (1.3, 2.1), (1.2, 0.7), (2.0, 0), (2.9, 0.6), (2.8, 1.7), (0.5, 3.6), (0.2, 5.0), (1.2, 6), (2.6, 5.7), (3.9, 3.7))]),+ '#': (4.0, [[(1.2, 0.4), (0.8, 5.6)], [(3.2, 0.4), (2.8, 5.6)], [(0, 2.0), (4, 2.0)], [(0, 4.0), (4, 4.0)]]),+ '%': (4.0, [_A(0.8, 1.0, 0.8, 1.0, 0, 360, 14), _A(3.2, 5.0, 0.8, 1.0, 0, 360, 14), [(0, 6), (4, 0)]]),+ '℄': (4.4, [_A(2.4, 3, 2.0, 2.6, -40, -320, 24), [(2.0, -0.4), (2.0, 6.4), (4.4, 6.4)]]),+ '↑': (2.4, [[(1.2, 6), (1.2, 0)], [(0, 1.4), (1.2, 0), (2.4, 1.4)]]),+ '→': (4.0, [[(0, 3), (4, 3)], [(2.6, 1.8), (4, 3), (2.6, 4.2)]]),+ '✓': (4.0, [[(0, 3.6), (1.4, 6), (4, 0)]]),+ ' ': (2.2, []),+ }+ return G+++GLYPHS = _glyphs()+++def _glyph_polys(ch):+ w, strokes = GLYPHS.get(ch, GLYPHS.get(ch.upper(), GLYPHS['?']))+ out = []+ for st in strokes:+ if isinstance(st, tuple) and st[0] == 's':+ out.append(spline(st[1], per=6))+ else:+ out.append(np.asarray(st, np.float32))+ return w, out+++def _fangsong():+ """a 'long FangSong' face for Chinese title-block text; falls back to the CJK font"""+ env = os.environ.get('INKPAINT_FONT_FANGSONG')+ if env and os.path.exists(env): return env+ for pat in ['/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/STFANGSO.ttf',+ '/System/Library/AssetsV2/PreinstalledAssetsV2/*/com_apple_MobileAsset_Font*/*/AssetData/STFANGSO.ttf',+ '/usr/share/fonts/**/*FangSong*.tt[fc]', '/usr/share/fonts/**/*fangsong*.tt[fc]',+ 'C:/Windows/Fonts/simfang.ttf']:+ fs = glob.glob(pat, recursive=True)+ if fs: return fs[0]+ return cjk_font()+++def _gauss(a, sigma):+ """true small-sigma gaussian (core.blur quantises sub-pixel sigmas to 0 or ~1.4 px)"""+ r = max(1, int(np.ceil(sigma * 3)))+ k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2).astype(np.float32); k /= k.sum()+ out = a.astype(np.float32)+ for ax in (0, 1):+ p = np.pad(out, [(r, r) if i == ax else (0, 0) for i in (0, 1)], mode='edge')+ acc = np.zeros_like(out)+ n = out.shape[ax]+ for i, w in enumerate(k):+ acc += w * (p[i:i + n] if ax == 0 else p[:, i:i + n])+ out = acc+ return out+++def _unit(v):+ v = np.asarray(v, np.float32)+ return v / (np.linalg.norm(v) + 1e-9)+++class Blueprint:+ def __init__(self, W=1920, H=1080, seed=0, ss=3, tracing=None):+ self.W, self.H, self.ss = W, H, ss+ self.rng = np.random.default_rng(seed)+ self._fs = [int(self.rng.integers(1 << 30)) for _ in range(16)] # field seeds, fixed at birth+ self.ink = Image.new('L', (W * ss, H * ss), 0) # ink on the tracing linen+ self.d = ImageDraw.Draw(self.ink)+ self.lead = Image.new('L', (W * ss, H * ss), 0) # pencil left on the linen+ self.dl = ImageDraw.Draw(self.lead)+ self.tracing = tracing or (10, 8, W - 10, H - 8) # linen edge (outside: bare paper)+ self.time = 1.0 # exposure time+ self.contact = 1.0 # how uneven the frame contact is+ self.folds = [] # ('v'|'h', pos, kind, wear)+ self.fades, self.grimes, self.stains, self.tacks, self.tears = [], [], [], [], []+ self.redl = Image.new('L', (W * 2, H * 2), 0) # red wax pencil (2x)+ self.dr = ImageDraw.Draw(self.redl)+ self.stages = []+ self._F = None++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ================================================================ pens+ def _P(self, pts):+ s = self.ss+ return [(float(x) * s, float(y) * s) for x, y in pts]++ def _w(self, pen):+ return PENS[pen] if isinstance(pen, str) else float(pen)++ def line(self, pts, pen='medium', closed=False, pool=True, layer=None):+ """a ruled ink line through `pts`; ink pools a little where the pen stops"""+ pts = [tuple(p) for p in pts]+ if len(pts) < 2: return+ if closed: pts = pts + [pts[0]]+ d = layer or self.d+ ws = max(1, int(round(self._w(pen) * self.ss)))+ P = self._P(pts)+ d.line(P, fill=255, width=ws, joint='curve')+ if not closed:+ r = ws / 2 * (1.18 if pool else 1.0)+ for (x, y) in (P[0], P[-1]):+ d.ellipse((x - r, y - r, x + r, y + r), fill=255)++ def lines(self, polylines, pen='medium'):+ for p in polylines: self.line(p, pen)++ @staticmethod+ def _cut(pts, pattern, phase=0.0, closed=False):+ """split a polyline into dashes; pattern = (on, off, on, off, ...) in px"""+ P = np.asarray(pts, np.float32)+ if closed: P = np.vstack([P, P[:1]])+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)+ s = np.concatenate([[0], np.cumsum(seg)]); L = float(s[-1])+ out, t, i = [], -float(phase), 0+ while t < L:+ l = pattern[i % len(pattern)]+ if i % 2 == 0:+ a, b = max(t, 0.0), min(t + l, L)+ if b > a:+ k = (s > a) & (s < b)+ xs = np.concatenate([[a], s[k], [b]])+ out.append(np.stack([np.interp(xs, s, P[:, 0]), np.interp(xs, s, P[:, 1])], 1))+ t += l; i += 1+ return out++ def dashed(self, pts, pen='thin', dash=(9, 5), phase=0.0, closed=False):+ """hidden / phantom lines"""+ for seg in self._cut(pts, dash, phase, closed): self.line(seg, pen, pool=False)++ def centerline(self, pts, pen='fine', pattern=(28, 5, 4, 5), phase=6.0, closed=False):+ """long-short-long centre line"""+ self.dashed(pts, pen, pattern, phase, closed)++ @staticmethod+ def arc_pts(cx, cy, r, a0, a1, ry=None, n=None):+ """arc in drawing angles (deg, counter-clockwise from +x, y up on paper)"""+ ry = r if ry is None else ry+ n = n or max(8, int(abs(a1 - a0) / 360 * 2 * np.pi * max(r, ry) / 2.5) + 2)+ t = np.radians(np.linspace(a0, a1, n))+ return np.stack([cx + r * np.cos(t), cy - ry * np.sin(t)], 1)++ def circle(self, cx, cy, r, pen='medium', dash=None, ry=None):+ pts = self.arc_pts(cx, cy, r, 0, 360, ry)+ if dash: self.dashed(pts, pen, dash)+ else: self.line(pts, pen, closed=True)++ def arc(self, cx, cy, r, a0, a1, pen='medium', ry=None, dash=None):+ pts = self.arc_pts(cx, cy, r, a0, a1, ry)+ if dash: self.dashed(pts, pen, dash)+ else: self.line(pts, pen)++ def box(self, x0, y0, x1, y1, pen='medium'):+ self.line([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], pen, closed=True)++ def fill(self, pts, layer=None):+ """solid ink (poché: thin cut metal, arrowheads, filled scale blocks)"""+ (layer or self.d).polygon(self._P(pts), fill=255)++ def dot(self, x, y, r=1.6):+ s = self.ss+ self.d.ellipse(((x - r) * s, (y - r) * s, (x + r) * s, (y + r) * s), fill=255)++ def erase(self, pts):+ """razor scraping: take ink (and pencil) off the linen inside a polygon"""+ self.d.polygon(self._P(pts), fill=0)+ self.dl.polygon(self._P(pts), fill=0)++ def pencil(self, pts, width=1.0, closed=False):+ """graphite left on the tracing: construction and guide lines -> print as faint pale lines"""+ pts = [tuple(p) for p in pts]+ if closed: pts = pts + [pts[0]]+ self.dl.line(self._P(pts), fill=255, width=max(1, int(round(width * self.ss))))++ # ================================================================ hatching+ def hatch(self, polys, angle=45, spacing=6.0, pen='fine', holes=(), kind='lines', phase=0.0):+ """section hatching clipped to the cut material. kind: 'lines' (masonry / general), 'cross' (metal),+ 'glass' (short triple strokes), 'rock' (broken fissures), 'stipple' (concrete), 'solid' (poché)"""+ polys = [np.asarray(p, np.float32) for p in polys]+ allp = np.vstack(polys)+ ss = self.ss+ x0 = max(0, int(np.floor(allp[:, 0].min())) - 3); y0 = max(0, int(np.floor(allp[:, 1].min())) - 3)+ x1 = min(self.W, int(np.ceil(allp[:, 0].max())) + 3); y1 = min(self.H, int(np.ceil(allp[:, 1].max())) + 3)+ if x1 <= x0 or y1 <= y0: return+ bw, bh = (x1 - x0) * ss, (y1 - y0) * ss+ mask = Image.new('L', (bw, bh), 0); dm = ImageDraw.Draw(mask)+ loc = lambda p: [((x - x0) * ss, (y - y0) * ss) for x, y in p]+ for p in polys: dm.polygon(loc(p), fill=255)+ for h in holes: dm.polygon(loc(np.asarray(h, np.float32)), fill=0)+ lay = Image.new('L', (bw, bh), 0); dh = ImageDraw.Draw(lay)+ ws = max(1, int(round(self._w(pen) * ss)))+ r = np.random.default_rng(self._seed())+ if kind == 'solid':+ lay = mask+ elif kind in ('lines', 'cross', 'glass'):+ angs = [angle] + ([angle + 90] if kind == 'cross' else [])+ for a in angs:+ u = np.array([np.cos(np.radians(a)), -np.sin(np.radians(a))]) # along the lines+ n = np.array([-u[1], u[0]]) # across+ corners = np.array([[x0, y0], [x1, y0], [x0, y1], [x1, y1]], np.float32)+ c = corners @ n+ k0, k1 = int(np.floor((c.min() - phase) / spacing)), int(np.ceil((c.max() - phase) / spacing))+ Lh = float(np.hypot(x1 - x0, y1 - y0)) + 10+ mid = np.array([(x0 + x1) / 2, (y0 + y1) / 2])+ for k in range(k0, k1 + 1):+ off = k * spacing + phase - mid @ n+ p = mid + n * off+ if kind == 'glass':+ # groups of three short strokes, staggered+ t = -Lh / 2 + (k % 3) * spacing * 1.7+ while t < Lh / 2:+ for j in range(3):+ q = p + n * (j * spacing * 0.28 - spacing * 0.28)+ a0, b0 = q + u * t, q + u * (t + spacing * 1.1 - j * spacing * 0.25)+ dh.line([((a0[0] - x0) * ss, (a0[1] - y0) * ss), ((b0[0] - x0) * ss, (b0[1] - y0) * ss)], fill=255, width=ws)+ t += spacing * 5.5+ continue+ a0, b0 = p - u * Lh / 2, p + u * Lh / 2+ dh.line([((a0[0] - x0) * ss, (a0[1] - y0) * ss), ((b0[0] - x0) * ss, (b0[1] - y0) * ss)], fill=255, width=ws)+ elif kind == 'rock':+ area = (x1 - x0) * (y1 - y0)+ for _ in range(int(area / (spacing * spacing * 9)) + 3):+ cx, cy = r.uniform(x0, x1), r.uniform(y0, y1)+ a = r.uniform(0, np.pi); L = r.uniform(spacing * 1.5, spacing * 4.5)+ pts = [(cx, cy)]+ for _s in range(int(r.integers(2, 4))):+ a += r.normal(0, 0.6)+ cx += np.cos(a) * L / 3; cy += np.sin(a) * L / 3+ pts.append((cx, cy))+ dh.line([((x - x0) * ss, (y - y0) * ss) for x, y in pts], fill=255, width=ws, joint='curve')+ elif kind == 'stipple':+ area = (x1 - x0) * (y1 - y0)+ for _ in range(int(area / (spacing * spacing) * 1.6)):+ cx, cy = r.uniform(x0, x1) - x0, r.uniform(y0, y1) - y0+ rr = r.uniform(0.4, 0.9) * ss * self._w(pen)+ dh.ellipse((cx * ss - rr, cy * ss - rr, cx * ss + rr, cy * ss + rr), fill=255)+ if kind != 'solid':+ lay = ImageChops.multiply(lay, mask)+ box = (x0 * ss, y0 * ss, x1 * ss, y1 * ss)+ self.ink.paste(ImageChops.lighter(self.ink.crop(box), lay), box[:2])++ def ground(self, pts, depth=10, every=14, pen='thin', line_pen='thick'):+ """natural ground line with the usual groups of short ticks below it"""+ P = np.asarray(pts, np.float32)+ self.line(P, line_pen)+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); s = np.concatenate([[0], np.cumsum(seg)])+ for t in np.arange(every * 0.5, s[-1] - 4, every):+ x, y = np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1])+ for j in range(3):+ xx = x + (j - 1) * depth * 0.35+ self.line([(xx, y + 2), (xx - depth * 0.55, y + 2 + depth * (0.9 - 0.18 * abs(j - 1)))], pen, pool=False)++ def breakline(self, p0, p1, pen='thin', zig=7):+ """long break line with a single zig-zag in the middle"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ u = _unit(p1 - p0); n = np.array([-u[1], u[0]]); m = (p0 + p1) / 2+ self.line([p0, m - u * zig * 0.6, m - u * zig * 0.25 + n * zig, m + u * zig * 0.25 - n * zig, m + u * zig * 0.6, p1], pen)++ # ================================================================ lettering+ def text_width(self, s, size, spacing=0.22):+ k = size / 6.0+ w = 0.0+ for ch in s.upper():+ w += GLYPHS.get(ch, GLYPHS['?'])[0] * k + spacing * size+ return max(0.0, w - spacing * size)++ def text(self, s, x, y, size=12, anchor='ls', pen=None, slant=0.0, spacing=0.22, rot=0.0, guide=False,+ line_gap=1.7, clear=False):+ """single-stroke capitals; size = cap height px; anchor: [l|m|r][t|m|s] (s = baseline).+ rot in degrees counter-clockwise; slant e.g. 0.22 for inclined lettering; clear=True scrapes the hatching+ out from behind the text first (as draughtsmen leave hatching out around dimension figures). Returns the width."""+ lines = s.split('\n')+ if len(lines) > 1:+ dy = size * line_gap+ v = anchor[1]+ top = {'t': 0, 'm': -(len(lines) - 1) * dy / 2, 's': -(len(lines) - 1) * dy}.get(v, 0)+ c, sn = np.cos(np.radians(rot)), np.sin(np.radians(rot))+ for i, ln in enumerate(lines):+ o = top + i * dy+ self.text(ln, x - sn * o, y + c * o, size, anchor, pen, slant, spacing, rot, guide, clear=clear)+ return max(self.text_width(ln, size, spacing) for ln in lines)+ k = size / 6.0+ wpx = self.text_width(s, size, spacing)+ ax = {'l': 0.0, 'm': -wpx / 2, 'r': -wpx}[anchor[0]]+ ay = {'t': 0.0, 'a': 0.0, 'm': -3 * k, 's': -6 * k, 'b': -6 * k}[anchor[1]]+ c, sn = np.cos(np.radians(rot)), np.sin(np.radians(rot))++ def T(px, py): # local (x right, y down) -> page+ lx, ly = px + ax, py + ay+ return (x + lx * c + ly * sn, y - lx * sn + ly * c)+ pw = pen if pen is not None else max(1.0, size * 0.11)+ if clear:+ m = size * 0.35+ self.erase([T(-m, -m), T(wpx + m, -m), T(wpx + m, 6 * k + m), T(-m, 6 * k + m)])+ if guide:+ for gy in (0.0, 6 * k):+ self.pencil([T(-size * 0.5, gy), T(wpx + size * 0.5, gy)], 0.8)+ cx = 0.0+ for ch in s.upper():+ gw, polys = _glyph_polys(ch)+ for P in polys:+ pts = [T(cx + (u + slant * (6 - v)) * k, v * k) for u, v in P]+ if len(P) == 2 and np.hypot(*(P[1] - P[0])) < 0.2: # full stops, colons: a round dot+ self.dot(pts[0][0], pts[0][1], max(pw * 0.85, 0.3 * k))+ else:+ self.line(pts, pw, pool=False)+ cx += gw * k + spacing * size+ return wpx++ def cjk(self, s, x, y, size=18, anchor='ls', condense=0.72, font=None):+ """Chinese in long FangSong (narrowed as on engineering drawings), inked into the tracing"""+ path = font or _fangsong()+ ss = self.ss+ f = ImageFont.truetype(path, int(size * ss * 1.25)) if path else load_font('cjk', size * ss * 1.25)+ bb = f.getbbox(s)+ tw, th = bb[2] - bb[0] + 4, bb[3] - bb[1] + 4+ im = Image.new('L', (tw, th), 0)+ ImageDraw.Draw(im).text((-bb[0] + 2, -bb[1] + 2), s, font=f, fill=255)+ im = im.resize((max(1, int(tw * condense)), th), Image.LANCZOS)+ from PIL import ImageFilter # a lettering pen, not a hairline: thicken and solidify+ im = im.filter(ImageFilter.MaxFilter(3)).point(lambda v: min(255, int(v * 1.35)))+ w, h = im.size+ X = x * ss - {'l': 0, 'm': w / 2, 'r': w}[anchor[0]]+ Y = y * ss - {'t': 0, 'a': 0, 'm': h / 2, 's': h, 'b': h}[anchor[1]]+ X, Y = int(round(X)), int(round(Y))+ box = (X, Y, X + w, Y + h)+ self.ink.paste(ImageChops.lighter(self.ink.crop(box), im), box[:2])+ return w / ss++ # ================================================================ drafting conventions+ def arrowhead(self, tip, direction, size=9.0, kind='filled', pen='thin'):+ tip = np.asarray(tip, np.float32); u = _unit(direction); n = np.array([-u[1], u[0]])+ back = tip - u * size+ if kind == 'filled':+ self.fill([tip, back + n * size * 0.2, back - n * size * 0.2])+ elif kind == 'open':+ self.line([back + n * size * 0.3, tip, back - n * size * 0.3], pen)+ elif kind == 'tick':+ d = _unit(u + n) * size * 0.55+ self.line([tip - d, tip + d], 'medium')+ elif kind == 'dot':+ self.dot(tip[0], tip[1], size * 0.2)++ def dim(self, p0, p1, offset, text=None, size=11, pen='fine', arrows='filled', gap=3.0, ext=5.0,+ scale=None, fmt='{:.2f}', text_off=3.0, shift=0.0, clear=True):+ """linear dimension between p0 and p1, dimension line `offset` px to the left of p0->p1 (negative = right).+ text defaults to the length / scale. Text sits above the line, reading from the bottom or the right."""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ d = p1 - p0; L = float(np.linalg.norm(d)); u = d / (L + 1e-9)+ n = np.array([u[1], -u[0]]) # left of travel on the page (y down)+ sg = 1.0 if offset >= 0 else -1.0+ q0, q1 = p0 + n * offset, p1 + n * offset+ if abs(offset) > gap + 1:+ self.line([p0 + n * sg * gap, q0 + n * sg * ext], pen, pool=False)+ self.line([p1 + n * sg * gap, q1 + n * sg * ext], pen, pool=False)+ self.line([q0, q1], pen, pool=False)+ asz = size * 0.8+ if L > asz * 2.6:+ self.arrowhead(q0, -u, asz, arrows); self.arrowhead(q1, u, asz, arrows)+ else: # tight: arrows outside pointing in+ self.line([q0 - u * asz * 1.8, q0], pen, pool=False); self.line([q1, q1 + u * asz * 1.8], pen, pool=False)+ self.arrowhead(q0, u, asz, arrows); self.arrowhead(q1, -u, asz, arrows)+ if text is None:+ text = fmt.format(L / scale) if scale else fmt.format(L)+ if text:+ ang = np.degrees(np.arctan2(-u[1], u[0]))+ if ang > 90.5: ang -= 180+ if ang <= -89.5: ang += 180+ a = np.radians(ang)+ up = np.array([-np.sin(a), -np.cos(a)])+ along = np.array([np.cos(a), -np.sin(a)])+ m = (q0 + q1) / 2 + up * text_off + along * shift+ self.text(text, m[0], m[1], size, 'ms', rot=ang, clear=clear)++ def level(self, x, y, text, size=11, length=70, side='right', pen='thin', mark_at=None):+ """level datum: a horizontal line with the half-filled triangle sitting on it and the level above"""+ sgn = 1 if side == 'right' else -1+ self.line([(x, y), (x + sgn * length, y)], pen, pool=False)+ tx = mark_at if mark_at is not None else x + sgn * length * 0.32+ h = size * 0.85+ tri = [(tx, y), (tx - h * 0.58, y - h), (tx + h * 0.58, y - h)]+ self.line(tri, pen, closed=True)+ self.fill([(tx, y), (tx - h * 0.58, y - h), (tx, y - h)])+ self.text(text, tx + sgn * h * 0.9, y - 3, size, 'ls' if sgn > 0 else 'rs')++ def leader(self, pts, text, size=10, end='arrow', pen='fine', shoulder=12, gap=4):+ """leader from pts[0] (the thing) to pts[-1], a short shoulder, then the note"""+ P = [np.asarray(p, np.float32) for p in pts]+ last = P[-1]+ sgn = 1 if (len(P) < 2 or last[0] >= P[-2][0]) else -1+ sh = last + np.array([sgn * shoulder, 0])+ self.line(P + [sh], pen, pool=False)+ if end == 'arrow': self.arrowhead(P[0], P[0] - P[1], size * 0.8)+ elif end == 'dot': self.dot(P[0][0], P[0][1], max(1.6, size * 0.16))+ self.text(text, sh[0] + sgn * gap, sh[1], size, ('l' if sgn > 0 else 'r') + 'm')++ def cut_mark(self, p0, p1, label, view, size=16, through=True, arm=26):+ """cutting plane: heavy ends, arrows showing the viewing direction, the letter at each end"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ u = _unit(p1 - p0); v = _unit(view)+ if through: self.centerline([p0, p1], 'fine', (26, 4, 6, 4))+ for p, s in ((p0, 1), (p1, -1)):+ self.line([p, p + u * s * arm], 'heavy')+ self.line([p, p + v * size * 1.5], 'thin', pool=False)+ self.arrowhead(p + v * size * 1.6, v, size * 0.75)+ c = p + v * size * 1.0 - u * s * size * 0.9+ self.text(label, c[0], c[1], size, 'mm', pen=max(1.1, size * 0.12))++ def bubble(self, x, y, r, top, bottom=None, size=None, pen='medium'):+ """detail / section callout: a circle, split if it also names the sheet"""+ size = size or r * 0.62+ self.circle(x, y, r, pen)+ if bottom is None:+ self.text(top, x, y, size, 'mm')+ else:+ self.line([(x - r, y), (x + r, y)], 'thin', pool=False)+ self.text(top, x, y - r * 0.47, size * 0.8, 'mm')+ self.text(bottom, x, y + r * 0.47, size * 0.8, 'mm')++ def view_title(self, x, y, title, sub=None, size=16, bubble=None):+ """drawing title: lettering on a heavy + thin double underline, scale underneath"""+ w = self.text(title, x, y, size, 'ms', pen=max(1.2, size * 0.12))+ x0, x1 = x - w / 2 - 6, x + w / 2 + 6+ if bubble:+ bx = x0 - size * 1.4+ self.bubble(bx, y - size * 0.15, size * 1.05, *bubble)+ x0 = bx + size * 1.05+ self.line([(x0, y + 6), (x1, y + 6)], 'thick')+ self.line([(x0, y + 10), (x1, y + 10)], 'fine', pool=False)+ if sub: self.text(sub, x, y + 26, size * 0.62, 'ms')++ def north(self, x, y, r=26, rot=0.0):+ """north point: circle, half-inked arrow, N"""+ self.circle(x, y, r, 'thin')+ a = np.radians(90 + rot)+ u = np.array([np.cos(a), -np.sin(a)]); n = np.array([-u[1], u[0]])+ tip, tail = np.array([x, y]) + u * r * 1.25, np.array([x, y]) - u * r * 0.85+ L, R = np.array([x, y]) - u * r * 0.35 + n * r * 0.38, np.array([x, y]) - u * r * 0.35 - n * r * 0.38+ self.line([tail, L, tip, R, tail], 'thin', closed=True)+ self.fill([tail, L, tip])+ c = np.array([x, y]) + u * r * 1.75+ self.text('N', c[0], c[1], r * 0.55, 'mm', rot=rot, pen=1.3)++ def scale_bar(self, x, y, px_per_unit, units=(0, 1, 2, 3, 4, 5), sub=5, label=None, size=10, h=7):+ """graphic scale: alternate inked / open blocks, one division left of 0 subdivided.+ px_per_unit: drawing px per real unit (metre); units: tick values in real units"""+ xs = [x + (u - units[0]) * px_per_unit for u in units]+ unit_px = (units[1] - units[0]) * px_per_unit+ self.line([(x - unit_px, y), (xs[-1], y)], 'fine', pool=False)+ self.line([(x - unit_px, y + h), (xs[-1], y + h)], 'fine', pool=False)+ for i in range(len(xs) - 1):+ if i % 2 == 0: self.fill([(xs[i], y), (xs[i + 1], y), (xs[i + 1], y + h), (xs[i], y + h)])+ for i in range(sub):+ a = x - unit_px + i * unit_px / sub+ if i % 2 == 0: self.fill([(a, y + h / 2), (a + unit_px / sub, y + h / 2), (a + unit_px / sub, y + h), (a, y + h)])+ for xx in [x - unit_px] + xs:+ self.line([(xx, y - 2), (xx, y + h)], 'fine', pool=False)+ fmt = lambda v: ('%g' % v)+ self.text(fmt(units[1] - units[0]), x - unit_px, y - 5, size * 0.8, 'ms')+ for u, xx in zip(units, xs):+ self.text(fmt(u), xx, y - 5, size * 0.8, 'ms')+ if label: self.text(label, (x - unit_px + xs[-1]) / 2, y + h + size + 6, size, 'ms')++ def border(self, x0, y0, x1, y1, zones=(8, 4), pen='heavy', size=11):+ """drawing frame with zone ticks and zone letters / numbers in the margin"""+ self.box(x0, y0, x1, y1, pen)+ nx, ny = zones+ for i in range(nx + 1):+ xx = x0 + (x1 - x0) * i / nx+ if 0 < i < nx:+ self.line([(xx, y0), (xx, y0 - 10)], 'thin', pool=False); self.line([(xx, y1), (xx, y1 + 10)], 'thin', pool=False)+ if i < nx:+ xm = x0 + (x1 - x0) * (i + 0.5) / nx+ self.text(str(nx - i), xm, (y0) / 2 + 1, size * 0.8, 'mm')+ self.text(str(nx - i), xm, (y1 + self.H) / 2, size * 0.8, 'mm')+ for j in range(ny + 1):+ yy = y0 + (y1 - y0) * j / ny+ if 0 < j < ny:+ self.line([(x0, yy), (x0 - 10, yy)], 'thin', pool=False); self.line([(x1, yy), (x1 + 10, yy)], 'thin', pool=False)+ if j < ny:+ ym = y0 + (y1 - y0) * (j + 0.5) / ny+ L = 'ABCDEFGH'[j]+ self.text(L, x0 / 2, ym, size * 0.8, 'mm'); self.text(L, (x1 + self.W) / 2, ym, size * 0.8, 'mm')++ def table(self, x0, y0, widths, heights, pen='thin', outer='medium'):+ """ruled table (title block / revision block); returns cell rects [row][col]"""+ xs = np.concatenate([[x0], x0 + np.cumsum(widths)]); ys = np.concatenate([[y0], y0 + np.cumsum(heights)])+ for x in xs[1:-1]: self.line([(x, ys[0]), (x, ys[-1])], pen, pool=False)+ for y in ys[1:-1]: self.line([(xs[0], y), (xs[-1], y)], pen, pool=False)+ self.box(xs[0], ys[0], xs[-1], ys[-1], outer)+ return [[(xs[i], ys[j], xs[i + 1], ys[j + 1]) for i in range(len(widths))] for j in range(len(heights))]++ def revision(self, x, y, mark, size=11):+ """revision triangle with its letter"""+ h = size * 1.6+ self.line([(x, y - h * 0.62), (x - h * 0.58, y + h * 0.38), (x + h * 0.58, y + h * 0.38)], 'thin', closed=True)+ self.text(mark, x, y + h * 0.08, size * 0.72, 'mm')++ # ================================================================ the print+ def expose(self, time=1.0, contact=1.0):+ """exposure time (1 = correct; 0.8 under-exposed, paler; 1.3 over) and how uneven the frame contact is"""+ self.time, self.contact = time, contact++ def _fields(self):+ if self._F is not None: return self._F+ H, W, s = self.H, self.W, self._fs+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)+ F = {}+ r2 = ((xx - W * 0.53) / (W * 0.78)) ** 2 + ((yy - H * 0.46) / (H * 0.95)) ** 2+ F['lamp'] = (1.0 - 0.30 * r2) * (0.93 + 0.12 * noise2d(H, W, 380, 3, s[0]))+ streak = fbm1d(H, 5, 4, s[1])[:, None] * (0.6 + 0.4 * noise2d(H, W, 700, 2, s[2]))+ mott = noise2d(H, W, 120, 4, s[3])+ # wash marks: the print hung to dry after the water bath, so faint runs go down the sheet from the top+ runs = fbm1d(W, 9, 4, s[11])[None, :] * fbm1d(W, 60, 3, s[12])[None, :]+ fall = smoothstep(1.0, 0.0, yy / H * (0.8 + 0.5 * noise2d(H, W, 300, 2, s[13])))+ F['coat'] = (1.0 - 0.035 * streak - 0.07 * smoothstep(0.35, 0.9, mott)+ - 0.10 * np.clip(runs * 3.0, 0, 1) * fall).astype(np.float32)+ F['contact'] = smoothstep(0.55, 0.9, noise2d(H, W, 450, 3, s[4])).astype(np.float32)+ g = np.random.default_rng(s[5])+ fib = np.asarray(Image.fromarray(g.random((H // 2, W // 7)).astype(np.float32)).resize((W, H), Image.BICUBIC))+ F['fibre'] = (0.55 * fib + 0.45 * noise2d(H, W, 2.2, 2, s[6])).astype(np.float32)+ F['grain'] = g.normal(0, 1, (H, W)).astype(np.float32)+ sk = noise2d(H, W, 3.0, 2, s[7])+ F['skip'] = (smoothstep(0.84, 0.96, sk) * smoothstep(0.55, 0.85, noise2d(H, W, 90, 2, s[8]))).astype(np.float32)+ F['resid'] = noise2d(H, W, 260, 3, s[9])+ self._F = F+ return F++ def _density(self):+ F = self._fields()+ W, H = self.W, self.H+ A = np.asarray(self.ink.resize((W, H), Image.BOX), np.float32) / 255+ Pn = np.asarray(self.lead.resize((W, H), Image.BOX), np.float32) / 255+ A = A * (1 - 0.45 * F['skip']) # pen starved on the linen here and there+ opaque = 1 - (1 - 0.985 * A) * (1 - 0.5 * Pn * (0.7 + 0.6 * F['fibre']))+ tx0, ty0, tx1, ty1 = self.tracing+ lin = np.full((H, W), 1.0, np.float32)+ lin[ty0:ty1, tx0:tx1] = 0.90 + 0.03 * (F['fibre'][ty0:ty1, tx0:tx1] - 0.5)+ T = (1 - opaque) * lin+ c = np.clip(F['contact'] * self.contact, 0, 1)+ Tb = _gauss(T, 0.55) * (1 - c) + _gauss(T, 0.9) * c # light creeping under the line edges+ Teff = 0.88 * Tb + 0.12 * blur(T, 6.0) # halo+ E = Teff * F['lamp'] * self.time+ e0, w = 0.46, 0.09+ sg = lambda z: 1 / (1 + np.exp(-z))+ D = (sg((E - e0) / w) - sg(-e0 / w)) / (1 - sg(-e0 / w))+ D = D * F['coat']+ return np.clip(D, 0, 1).astype(np.float32), E++ def _fold_profile(self, kind, pos, wear):+ """(crack, slope, worn) maps for one fold"""+ H, W = self.H, self.W+ F = self._fields()+ sd = int(pos * 7 + (13 if kind == 'v' else 29)) % (1 << 30)+ if kind == 'v':+ wob = pos + 1.4 * fbm1d(H, 120, 3, sd)+ d = np.arange(W, dtype=np.float32)[None, :] - wob[:, None]+ along = noise2d(H, 1, 6, 3, sd + 1)[:, 0][:, None] * np.ones((1, W), np.float32)+ else:+ wob = pos + 1.4 * fbm1d(W, 120, 3, sd)+ d = np.arange(H, dtype=np.float32)[:, None] - wob[None, :]+ along = noise2d(1, W, 6, 3, sd + 1)[0][None, :] * np.ones((H, 1), np.float32)+ broken = smoothstep(0.25, 0.65, along) * (0.6 + 0.4 * F['fibre'])+ crack = np.exp(-(d / 0.9) ** 2) * broken * wear+ scuff = np.exp(-(d / 3.2) ** 2) * (0.5 + 0.5 * F['fibre']) * wear+ slope = np.sign(d) * np.exp(-np.abs(d) / 22.0)+ return crack.astype(np.float32), scuff.astype(np.float32), slope.astype(np.float32)++ def render(self):+ H, W = self.H, self.W+ F = self._fields()+ D, E = self._density()+ yy, xx = None, None+ shade = np.zeros((H, W), np.float32)+ wearmap = np.zeros((H, W), np.float32)+ # ---- folds+ vs = [f for f in self.folds if f[0] == 'v']; hs = [f for f in self.folds if f[0] == 'h']+ for kind, pos, mount, wear in self.folds:+ crack, scuff, slope = self._fold_profile(kind, pos, wear)+ D = D * (1 - 0.85 * crack) * (1 - 0.16 * scuff)+ shade += 0.045 * mount * slope * wear+ wearmap = np.maximum(wearmap, crack)+ if vs and hs:+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)+ for _, px, _, w1 in vs:+ for _, py, _, w2 in hs:+ rr = np.hypot(xx - px, (yy - py) * 1.0)+ sp = np.exp(-(rr / 7.0) ** 2) * (0.55 + 0.45 * F['fibre']) * min(w1, w2)+ D = D * (1 - 0.38 * sp)+ wearmap = np.maximum(wearmap, sp)+ # ---- faded panels+ for (x0, y0, x1, y1, amt) in self.fades:+ m = self._rectmask(x0, y0, x1, y1, 2.5)+ D = D * (1 - amt * m * (0.85 + 0.3 * F['resid']))+ # ---- alkali / water stains+ stain_m = np.zeros((H, W), np.float32); tide = np.zeros((H, W), np.float32)+ for (x, y, r, sd, strength) in self.stains:+ # the water spread, then dried back in two fronts: each front leaves a crisp tide line+ for j, (sc, w) in enumerate(((1.0, 1.0), (0.62, 0.55))):+ pts = blob_pts(x + j * r * 0.12, y - j * r * 0.08, r * sc, r * sc * 0.8, rough=0.22 + 0.06 * j, n=160, seed=sd + 7 * j, rot=0.4)+ m = polygon_mask(H, W, pts, ss=2)+ mb = _gauss(m, 1.1)+ ring = smoothstep(0.12, 0.5, mb) * smoothstep(0.95, 0.55, mb)+ tide = np.maximum(tide, ring * w * strength * (0.65 + 0.35 * noise2d(H, W, 9, 2, sd + 3 + j)))+ if j == 0:+ mot = noise2d(H, W, r * 0.3, 3, sd + 1)+ stain_m = np.maximum(stain_m, _gauss(m, 2.0) * (0.35 + 0.65 * mot) * strength)+ D = D * (1 - 0.42 * stain_m)+ # ---- colour: Prussian blue on paper (Beer-Lambert), paper fibres, iron residue in the half-tones+ paper = PAPER[None, None, :] * (0.965 + 0.06 * F['fibre'][..., None])+ dens = 0.90 * D+ img = paper * np.exp(-dens[..., None] * ABSORB[None, None, :])+ resid = (D * (1 - D) * 4) * (0.35 + 0.65 * F['resid'])+ img[..., 2] *= 1 - 0.10 * resid+ img[..., 0] *= 1 + 0.06 * resid+ img *= (1 + 0.018 * F['grain'] * (0.5 + D))[..., None]+ # brown where alkali destroyed the blue, darker at the tide line+ brown = np.array([0.66, 0.52, 0.33], np.float32)+ img = img * (1 - 0.32 * stain_m[..., None]) + brown * paper * 0.32 * stain_m[..., None] * (0.75 + 0.25 * F['fibre'][..., None])+ img = img * (1 - 0.7 * tide[..., None]) + np.array([0.40, 0.28, 0.15], np.float32) * 0.7 * tide[..., None]+ # ---- handled / grubby panels+ for (x0, y0, x1, y1, amt) in self.grimes:+ m = self._rectmask(x0, y0, x1, y1, 3) * (0.6 + 0.4 * F['resid']) * amt+ img *= (1 - m[..., None] * np.array([0.10, 0.14, 0.22], np.float32))+ # ---- paper relief: fold shading, worn fibres at the cracks+ img *= (1 + shade)[..., None]+ img = img + (np.array([0.80, 0.84, 0.86]) - img) * (wearmap * 0.2)[..., None]+ # ---- drawing pins: hole, torn rim, rust halo+ if self.tacks:+ if yy is None: yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)+ for (x, y) in self.tacks:+ rr = np.hypot(xx - x, yy - y)+ halo = np.exp(-(rr / 9.0) ** 2) * (0.6 + 0.4 * F['fibre'])+ img *= (1 - 0.45 * halo[..., None] * np.array([0.2, 0.55, 0.95], np.float32))+ rim = smoothstep(3.6, 2.4, rr) * (0.6 + 0.4 * F['fibre'])+ img = img + (np.array([0.78, 0.80, 0.80]) - img) * rim[..., None] * 0.6+ hole = smoothstep(2.4, 1.4, rr)+ img = img * (1 - hole[..., None]) + np.array([0.07, 0.06, 0.05]) * hole[..., None]+ # ---- small edge tears where folds meet the edge+ for (x, y, dx, dy, L) in self.tears:+ if yy is None: yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)+ t = np.clip(((xx - x) * dx + (yy - y) * dy) / L, 0, 1)+ across = np.abs((xx - x) * -dy + (yy - y) * dx)+ notch = smoothstep(1.4 * (1 - t) + 0.2, 0.0, across) * ((((xx - x) * dx + (yy - y) * dy) >= 0) & (t < 1))+ img = img * (1 - notch[..., None]) + np.array([0.08, 0.07, 0.06]) * notch[..., None]+ # ---- sheet edge: a little darker where it has been handled+ if yy is None: yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)+ edge = np.minimum(np.minimum(xx, W - 1 - xx), np.minimum(yy, H - 1 - yy))+ img *= (1 - 0.10 * np.exp(-edge / 5.0) * (0.6 + 0.4 * F['fibre']))[..., None]+ # ---- red wax pencil on top+ rc = self._red_cover()+ if rc is not None:+ img = img * (1 - rc[..., None] * 0.86) + RED * rc[..., None] * 0.86 * (0.92 + 0.12 * F['fibre'][..., None])+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def _rectmask(self, x0, y0, x1, y1, soft):+ H, W = self.H, self.W+ m = np.zeros((H, W), np.float32)+ m[max(0, int(y0)):min(H, int(y1)), max(0, int(x0)):min(W, int(x1))] = 1+ return blur(m, soft)++ # ================================================================ the life of the sheet+ def fold(self, xs=(), ys=(), wear=1.0, accordion=True):+ """fold the print to file size along vertical lines xs and horizontal lines ys"""+ for i, x in enumerate(xs): self.folds.append(('v', float(x), (1 if (i % 2 == 0 or not accordion) else -1), wear))+ for j, y in enumerate(ys): self.folds.append(('h', float(y), (1 if (j % 2 == 0 or not accordion) else -1), wear))++ def fade(self, x0, y0, x1, y1, amount=0.15):+ """the panel that faced the light (outermost when folded) has faded"""+ self.fades.append((x0, y0, x1, y1, amount))++ def grime(self, x0, y0, x1, y1, amount=1.0):+ """handled panel: grey-brown dirt from fingers and filing"""+ self.grimes.append((x0, y0, x1, y1, amount))++ def stain(self, x, y, r, strength=1.0):+ """alkaline water: blue turns rust-brown inside a darker tide line"""+ self.stains.append((x, y, r, self._seed(), strength))++ def tack(self, x, y):+ self.tacks.append((x, y))++ def tear(self, x, y, direction, length=10):+ """a little split in from the sheet edge (usually where a fold meets it)"""+ u = _unit(direction)+ self.tears.append((x, y, float(u[0]), float(u[1]), float(length)))++ # ================================================================ red wax pencil+ def red(self, pts, width=2.6, smooth=True):+ P = np.asarray(pts, np.float32)+ if smooth and len(P) > 2: P = spline(P, per=8)+ r = np.random.default_rng(self._seed())+ P = P + r.normal(0, 0.25, P.shape).astype(np.float32)+ self.dr.line([(float(x) * 2, float(y) * 2) for x, y in P], fill=255, width=max(1, int(round(width * 2))), joint='curve')++ def cloud(self, pts, bump=22, width=2.4):+ """revision cloud: scalloped arcs bulging outwards along a closed path"""+ P = np.asarray(pts, np.float32)+ P = np.vstack([P, P[:1]])+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1); s = np.concatenate([[0], np.cumsum(seg)])+ L = float(s[-1]); n = max(6, int(L / bump))+ t = np.linspace(0, L, n + 1)+ Q = np.stack([np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1])], 1)+ area = 0.5 * np.sum(P[:-1, 0] * P[1:, 1] - P[1:, 0] * P[:-1, 1])+ out = []+ r = np.random.default_rng(self._seed())+ for i in range(n):+ a, b = Q[i], Q[i + 1]+ m = (a + b) / 2; u = _unit(b - a); nn = np.array([u[1], -u[0]]) * (1 if area > 0 else -1)+ hgt = np.linalg.norm(b - a) * r.uniform(0.38, 0.5)+ for k in np.linspace(0, 1, 7)[:-1]:+ p = a + (b - a) * k + nn * hgt * np.sin(np.pi * k)+ out.append(p)+ out.append(Q[-1] + np.array([3.0, 2.0]))+ self.red(np.array(out), width, smooth=False)++ def red_text(self, s, x, y, size=26, rot=0.0, anchor='ls', font='hand'):+ f = load_font(font, size * 2)+ m = text_mask(self.H * 2, self.W * 2, s, f, (x * 2, y * 2), anchor=anchor, rot=rot)+ self.redl.paste(ImageChops.lighter(self.redl, Image.fromarray((m * 255).astype(np.uint8))), (0, 0))++ def _red_cover(self):+ a = np.asarray(self.redl.resize((self.W, self.H), Image.BOX), np.float32) / 255+ if a.max() <= 0: return None+ F = self._fields()+ tooth = 0.55 * F['fibre'] + 0.45 * noise2d(self.H, self.W, 1.6, 1, self._fs[10])+ return np.clip((a * 1.15 - tooth * 0.55) / 0.6, 0, 1) * smoothstep(0.02, 0.3, a)++ # ================================================================ output+ def stage(self, name):+ self.stages.append((name, self.render()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.render()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/cave.py b/lib/cave.pynew file mode 100644index 0000000..bae5609--- /dev/null+++ b/lib/cave.py@@ -0,0 +1,1249 @@+"""cave -- Ice-Age cave painting: ochre and charcoal on a firelit limestone wall (numpy + Pillow only).++A cave painting is pigment laid on a rock surface in the dark, and seen only by a flame. It is the opposite of a+petroglyph (petroglyph.py), which knocks the dark skin off a sunlit rock: here nothing is cut, the colour sits on top+of pale limestone, the rock's own bulges give the animals their volume, and the only light is a fire on the floor.++Model:+ wall a limestone cave wall is a height field (px) and an albedo. Broad undulations; `boss()` adds the rounded+ bulges the painters chose to put a bison's belly or a horse's flank on; solution scallops (shallow+ spoon-shaped dishes with sharp rims, left by the water that dissolved the cave); grain and small pits.+ The stone is cream to buff with ochre and grey stains and a whiter calcite crust on the convex parts.+ `fold()` lifts the face on one side of a line (where the wall changes plane, with a lit crest);+ `flowstone()` hangs calcite drapery with orange "bacon" bands that stays wet and glints; `crack()` cuts+ fissures; `floor()` puts a packed-clay floor below the wall base (tilted toward the viewer).+ pigment red ochre (hematite), yellow ochre (goethite), brown, charcoal and manganese black. Every deposit is a+ coverage field multiplied into the albedo: the rock's own mottling shows through even a dense coat.+ How it gets there decides how it looks:+ sketch a charcoal stick dragged lightly, twice, round a slightly wandering contour (searching lines);+ line a charcoal stick or a finger loaded with wet paint along a stroke; the dry stick only catches+ the rock's high points (the "tooth"), so it breaks up in the hollows;+ outline the finished contour: a black band inside the silhouette, thicker along the back and at the+ top edges, thinner on the belly, with gaps where the stick skipped;+ blow pigment spat or blown through a hollow bone: a soft-edged coat with a faint halo past the edge,+ a speckle of droplets around it and an uneven density; `rim` makes it denser toward the+ outline, `gradient` darker on the back, `relief` heavier where the wall turns away from the+ fire (the painters used the rock's shape for volume), `exclude` leaves a pale belly;+ daub a fur pad dabbed on: blotchy, more on the rock's high points;+ paint a drafted shape (hunter, spear) filled solid with a finger / stick / brush;+ dots palm-sized red dots;+ stencil a hand held flat on the wall and pigment blown round it: the hand stays bare rock inside a+ sprayed halo; a later stencil cuts its hand out of an earlier halo;+ handprint a paint-covered palm pressed on: only the rock's high points take the paint.+ figures drafted in a unit frame and placed with (x, y, size, facing, rot): bison, horse, deer (stag / hind),+ hunter (red Levantine-style runner with a spear), spear, hand, plus generic `shape()`. A Figure holds+ named masks in a local box (body, legs, tail, horns, antlers, mane, ears + painting regions head, hump,+ belly, back, front); `fig.sel('head', 'mane')` picks some of them; every paint method takes a Figure+ or a selection.+ time `calcite()` a milky veil (moonmilk) over part of a painting, `flake()` paint lost in small flakes,+ `claws()` a cave bear's claw marks scratched into the soft surface (fresh pale grooves through the+ paint), `soot()` the plume of soot the fire laid on the wall and ceiling.+ fire `fire()` a campfire on the floor: ring of stones, ash, glowing logs, layered flame tongues (white-yellow+ core, orange body, red tips), sparks and a smoke plume; `lamp()` a stone fat lamp with a small flame.+ Both are point lights: half-Lambert shading from the height-field normals (raking light from below makes+ every bulge read), inverse-square falloff, shadows marched along the light per pixel, specular glints on+ wet calcite, a little cool ambient in the hollows; then flame emission, bloom, smoke and a filmic+ tone curve. Light is cached and only recomputed when the height field changes.+ props `stone()` a slab or pebble on the floor, `heap()` a mound of ground pigment, `stick()` a charcoal stick+ or a hollow bone blowpipe.+Order: wall -> boss / flowstone / crack -> floor -> fire / lamp / props -> sketch -> colour (blow / daub) ->+black (blow / outline / line) -> hunters, hands, dots -> calcite / flake / claws / soot.+Coordinates are px, y down; angles in degrees, counter-clockwise; facing 1 = right, -1 = left.++ from cave import CavePainting+ cv = CavePainting(1920, 1080, seed=3)+ cv.wall(); cv.boss(1400, 450, 260, 170, 45); cv.floor(965)+ cv.fire(240, 1050, 230); cv.lamp(1690, 1000, 120)+ b = cv.bison(1430, 480, 440, facing=1)+ cv.sketch(b); cv.blow(b.sel('body'), 'red', exclude=b.sel('belly'), rim=0.35)+ cv.blow(b.sel('head', 'hump', 'legs'), 'black', clip=b); cv.outline(b)+ cv.stencil(cv.hand(160, 230, 130, rot=-12), 'red')+ cv.soot(240, 860, amount=0.5)+ cv.save('out.jpg')+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, height_normals, ambient_occlusion++LIMESTONE = '#d3c0a2'+CALCITE = '#e9e0d1'+FLOOR = '#6e5240'+SOOT = '#120d0a'+PIGMENTS = {+ 'red': '#93281a', # red ochre (hematite)+ 'darkred': '#5e1c11',+ 'orange': '#a9592a', # burnt yellow ochre+ 'yellow': '#c4903f', # yellow ochre (goethite)+ 'brown': '#5f3620', # umber+ 'black': '#120e0c', # charcoal+ 'manganese': '#26221f', # manganese oxide, a cooler black+ 'white': '#ddd3c3', # kaolin+}+FIRE = np.array([1.00, 0.60, 0.29], np.float32)+LAMPLIGHT = np.array([1.00, 0.68, 0.36], np.float32)+REGIONS = ('head', 'hump', 'belly', 'back', 'front', 'eye')+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ if isinstance(c, str):+ return hexc(PIGMENTS.get(c, c)) if not c.startswith('#') else hexc(c)+ return np.asarray(c, np.float32)+++def _closed(P, per=8):+ """closed Catmull-Rom through control points"""+ P = np.asarray(P, np.float32)+ Q = np.vstack([P[-1:], P, P[:2]])+ out = []+ for i in range(1, len(Q) - 2):+ p0, p1, p2, p3 = Q[i - 1], Q[i], Q[i + 1], Q[i + 2]+ for t in np.linspace(0, 1, per, endpoint=False):+ t2, t3 = t * t, t * t * t+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))+ return np.array(out, np.float32)+++def _open(P, widths, per=10):+ """open spline through control points + width per sample (widths given at the control points)"""+ P = np.asarray(P, np.float32)+ if len(P) < 3:+ P = np.vstack([P[0], (P[0] + P[-1]) / 2, P[-1]]) if len(P) == 2 else P+ if np.ndim(widths) and len(widths) == 2: widths = [widths[0], (widths[0] + widths[1]) / 2, widths[1]]+ S = spline(P, per)+ w = np.broadcast_to(np.asarray(widths, np.float32), (len(P),)) if np.ndim(widths) else np.full(len(P), widths, np.float32)+ idx = np.arange(len(S), dtype=np.float32) / per+ return S, np.interp(idx, np.arange(len(P)), w).astype(np.float32)+++def _dense(S, w):+ """resample a stroke so circles of radius w/2 overlap smoothly"""+ seg = np.linalg.norm(np.diff(S, axis=0), axis=1)+ s = np.concatenate([[0], np.cumsum(seg)])+ step = max(0.5, float(np.min(w)) * 0.25)+ t = np.arange(0, s[-1] + 1e-3, step)+ return np.stack([np.interp(t, s, S[:, 0]), np.interp(t, s, S[:, 1])], 1), np.interp(t, s, w)+++class Sel:+ """a mask in a local box (x0, y0, x1, y1) -- what every paint method works on"""+ def __init__(self, box, m):+ self.box, self.m = box, m+++class Figure:+ """a drafted shape: named float masks in one local box; anchors are named points in image px"""+ def __init__(self, box, kind=''):+ self.box, self.kind = box, kind+ self.parts, self.anchors = {}, {}++ @property+ def shape(self):+ return self.box[3] - self.box[1], self.box[2] - self.box[0]++ def add(self, name, m):+ self.parts[name] = np.maximum(self.parts[name], m) if name in self.parts else m++ def mask(self, *names):+ names = names or [k for k in self.parts if k not in REGIONS]+ out = np.zeros(self.shape, np.float32)+ for k in names:+ if k in self.parts: np.maximum(out, self.parts[k], out=out)+ return out++ def sel(self, *names):+ return Sel(self.box, self.mask(*names))++ @property+ def m(self):+ return self.mask()+++class CavePainting:+ def __init__(self, W=1920, H=1080, seed=0):+ self.W, self.H, self.seed = W, H, seed+ self.rng = np.random.default_rng(seed)+ self.h = np.zeros((H, W), np.float32)+ self.rock = np.ones((H, W, 3), np.float32) * hexc(LIMESTONE)+ self.alb = self.rock.copy()+ self.load = np.zeros((H, W), np.float32) # how much paint sits on each pixel (flaking takes it off)+ self.wet = np.zeros((H, W), np.float32)+ self.lights, self.fires, self.lamps = [], [], []+ self.floor_line = None+ self._grain = np.zeros((H, W), np.float32)+ self._rock_mean = float(self.rock.mean())+ self._floor_m = np.zeros((H, W), np.float32)+ self.stages = []+ self._lit = None+ self._fx = None+ self._aux = None++ # ------------------------------------------------------------------ helpers+ def _s(self):+ return int(self.rng.integers(1 << 30))++ def _grid(self):+ return np.mgrid[0:self.H, 0:self.W].astype(np.float32)++ def _dirty(self):+ self._lit = None; self._aux = None++ def _box(self, pts, pad=70):+ P = np.asarray(pts, np.float32).reshape(-1, 2)+ x0 = int(max(0, np.floor(P[:, 0].min() - pad))); x1 = int(min(self.W, np.ceil(P[:, 0].max() + pad)))+ y0 = int(max(0, np.floor(P[:, 1].min() - pad))); y1 = int(min(self.H, np.ceil(P[:, 1].max() + pad)))+ return (x0, y0, max(x1, x0 + 2), max(y1, y0 + 2))++ @staticmethod+ def _sl(box):+ return slice(box[1], box[3]), slice(box[0], box[2])++ def _raster(self, box, polys=(), strokes=(), discs=(), ss=2):+ """polygons (closed point lists), strokes ((pts, widths) sampled densely) and discs ((x, y, r)) -> float mask"""+ x0, y0, x1, y1 = box+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ d = ImageDraw.Draw(im)+ for P in polys:+ d.polygon([((float(x) - x0) * ss, (float(y) - y0) * ss) for x, y in P], fill=255)+ for S, w in strokes:+ S, w = _dense(np.asarray(S, np.float32), np.asarray(w, np.float32))+ for (x, y), ww in zip(S, w):+ r = max(0.35, ww / 2) * ss+ cx, cy = (x - x0) * ss, (y - y0) * ss+ d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=255)+ for x, y, r in discs:+ r *= ss; cx, cy = (x - x0) * ss, (y - y0) * ss+ d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=255)+ if ss > 1: im = im.resize((x1 - x0, y1 - y0), Image.BOX)+ return np.asarray(im, np.float32) / 255++ def _target(self, t):+ if isinstance(t, (Sel, Figure)): return t.box, t.m+ raise TypeError('paint target must be a Figure or Figure.sel(...)')++ def _local(self, mask_obj, box):+ """another Figure/Sel's mask re-cut to `box`"""+ if mask_obj is None: return None+ b2, m2 = self._target(mask_obj)+ out = np.zeros((box[3] - box[1], box[2] - box[0]), np.float32)+ ix0, iy0 = max(box[0], b2[0]), max(box[1], b2[1]); ix1, iy1 = min(box[2], b2[2]), min(box[3], b2[3])+ if ix1 > ix0 and iy1 > iy0:+ out[iy0 - box[1]:iy1 - box[1], ix0 - box[0]:ix1 - box[0]] = m2[iy0 - b2[1]:iy1 - b2[1], ix0 - b2[0]:ix1 - b2[0]]+ return out++ def _noise(self, box, scale, octaves=3):+ h, w = box[3] - box[1], box[2] - box[0]+ return noise2d(h, w, scale, octaves, self._s())++ def _auxiliary(self):+ """rock tooth (how much a dry stick catches) and the large-scale wall normal (for relief shading)"""+ if self._aux is None:+ h = self.h+ hp = h - blur(h, 2.5)+ tooth = hp / (hp.std() + 1e-6) + 0.9 * self._grain+ hb = blur(h, 14)+ gy, gx = np.gradient(hb)+ self._aux = (tooth.astype(np.float32), gx.astype(np.float32), gy.astype(np.float32))+ return self._aux++ def _catch(self, box, press):+ """dry pigment on rock: high points take it first; press 0..1"""+ tooth = self._auxiliary()[0][self._sl(box)]+ return smoothstep(-1.4, 0.9, tooth + (press - 0.5) * 2.6)++ def _deposit(self, box, cov, pigment):+ sl = self._sl(box)+ col = _c(pigment)+ rock = self.rock[sl]+ tex = 0.80 + 0.20 * rock.mean(-1, keepdims=True) / self._rock_mean+ g = self._grain[sl][..., None]+ paint = col * tex * (1 + 0.05 * g)+ a = np.clip(cov, 0, 1)[..., None]+ self.alb[sl] = self.alb[sl] * (1 - a) + paint * a+ np.maximum(self.load[sl], np.clip(cov, 0, 1), out=self.load[sl])++ # ------------------------------------------------------------------ the wall+ def wall(self, colour=LIMESTONE, relief=1.0, scallops=1.0, grain=1.0):+ """limestone height field (undulations, scallops, grain, pits) and its stains"""+ H, W = self.H, self.W+ r = self.rng+ big = noise2d(H, W, 460, 3, self._s()) - 0.5+ mid = noise2d(H, W, 120, 4, self._s()) - 0.5+ rid = 1 - np.abs(noise2d(H, W, 240, 3, self._s()) * 2 - 1) # ridged: crests where the rock folds+ h = relief * (big * 46 + mid * 10 + rid ** 2 * 10)+ sc = self._scallops(110, depth=1.8)+ patch = smoothstep(0.45, 0.75, noise2d(H, W, 380, 2, self._s()))+ h += scallops * sc * (0.15 + 0.85 * patch)+ self._grain = blur(r.normal(0, 1, (H, W)).astype(np.float32), 0.7)+ self._grain /= self._grain.std() + 1e-6+ h += grain * (0.12 * self._grain + 0.7 * (noise2d(H, W, 9, 2, self._s()) - 0.5)+ + 1.1 * (noise2d(H, W, 40, 3, self._s()) - 0.5))+ pits = np.zeros((H, W), np.float32)+ for _ in range(int(60 * W * H / 2.07e6)): # small solution pits, clay settles in them+ x, y, rr = r.uniform(0, W), r.uniform(0, H), r.uniform(1.5, 4.0)+ R = int(rr * 2 + 2); ix, iy = int(x), int(y)+ if ix < R or iy < R or ix >= W - R or iy >= H - R: continue+ yy, xx = np.mgrid[-R:R + 1, -R:R + 1]+ d2 = ((xx - (x - ix)) ** 2 + (yy - (y - iy)) ** 2) / (rr * rr)+ h[iy - R:iy + R + 1, ix - R:ix + R + 1] -= np.clip(1 - d2, 0, 1) * rr * 0.3+ np.maximum(pits[iy - R:iy + R + 1, ix - R:ix + R + 1], np.clip(1.2 - d2, 0, 1),+ out=pits[iy - R:iy + R + 1, ix - R:ix + R + 1])+ self.h = h.astype(np.float32)+ # albedo: cream to buff, ochre and grey stains, calcite crust on convex parts+ base = hexc(colour)+ t1 = noise2d(H, W, 300, 4, self._s())[..., None]+ alb = base * (0.86 + 0.24 * t1)+ alb = alb * np.array([1.0, 0.985, 0.96], np.float32) ** (2 * (noise2d(H, W, 160, 3, self._s())[..., None] - 0.5))+ st = smoothstep(0.58, 0.80, noise2d(H, W, 210, 4, self._s()))[..., None]+ alb = alb * (1 - 0.45 * st) + hexc('#c5975c') * 0.45 * st+ gr = smoothstep(0.66, 0.86, noise2d(H, W, 230, 4, self._s()))[..., None]+ alb = alb * (1 - 0.22 * gr) + hexc('#9a9184') * 0.22 * gr+ conv = self.h - blur(self.h, 16)+ cal = (smoothstep(1.0, 7.0, conv) * noise2d(H, W, 60, 3, self._s()))[..., None]+ alb = alb * (1 - 0.45 * cal) + hexc(CALCITE) * 0.45 * cal+ alb *= (1 + 0.022 * self._grain)[..., None]+ alb *= (1 - 0.3 * blur(pits, 0.8))[..., None]+ self.rock = np.clip(alb, 0, 1).astype(np.float32)+ self.alb = self.rock.copy()+ self._rock_mean = float(self.rock.mean())+ self._dirty()++ def _scallops(self, cell=70, depth=6.0):+ """solution scallops: min of paraboloids round jittered seeds -> spoon-shaped dishes with sharp rims"""+ H, W = self.H, self.W+ r = self.rng+ gh, gw = H // cell + 3, W // cell + 3+ sx = (np.arange(gw)[None, :] - 1 + r.uniform(0.15, 0.85, (gh, gw))) * cell+ sy = (np.arange(gh)[:, None] - 1 + r.uniform(0.15, 0.85, (gh, gw))) * cell+ Y, X = self._grid()+ ci = (X // cell).astype(np.int32) + 1; cj = (Y // cell).astype(np.int32) + 1+ best = np.full((H, W), np.inf, np.float32)+ for dj in (-1, 0, 1):+ for di in (-1, 0, 1):+ jj, ii = np.clip(cj + dj, 0, gh - 1), np.clip(ci + di, 0, gw - 1)+ px, py = sx[jj, ii], sy[jj, ii]+ d2 = (X - px) ** 2 + ((Y - py) * 1.3) ** 2 + (X - px) * cell * 0.25 # steeper upstream side+ np.minimum(best, d2, out=best)+ v = np.clip(best / (0.55 * cell * cell), 0, 1.4)+ return ((v - v.mean()) * depth).astype(np.float32)++ def boss(self, x, y, rx, ry, height=40.0, rot=0.0):+ """a rounded bulge of the wall (put an animal's belly or flank on it)"""+ box = self._box([(x - rx, y - ry), (x + rx, y + ry), (x - ry, y - rx), (x + ry, y + rx)], 4)+ Y, X = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ a = np.radians(rot); c, s = np.cos(a), np.sin(a)+ u = ((X - x) * c - (Y - y) * s) / rx; v = ((X - x) * s + (Y - y) * c) / ry+ r2 = u * u + v * v+ self.h[self._sl(box)] += height * np.clip(1 - r2, 0, 1) ** 2+ self._dirty()++ def fold(self, pts, height=14.0, soft=6.0, side=1):+ """a fold where the wall changes plane: the face on one side of the line stands proud by `height` px,+ with a rounded crest (side=1 raises the face below / right of the line's direction)"""+ P = spline(np.asarray(pts, np.float32), 16)+ n = len(P)+ P = P + np.stack([fbm1d(n, 18, 3, self._s()), fbm1d(n, 18, 3, self._s())], 1) * 5+ Y, X = self._grid()+ best = np.full((self.H, self.W), 1e9, np.float32); sgn = np.zeros((self.H, self.W), np.float32)+ arc = np.zeros((self.H, self.W), np.float32)+ cum = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(P, axis=0), axis=1))])+ for i in range(0, n - 1, 2): # signed distance to the polyline (coarse)+ a, b = P[i], P[min(i + 2, n - 1)]+ d = b - a; L2 = float(d @ d) + 1e-6+ t = np.clip(((X - a[0]) * d[0] + (Y - a[1]) * d[1]) / L2, 0, 1)+ qx, qy = X - (a[0] + t * d[0]), Y - (a[1] + t * d[1])+ dist = qx * qx + qy * qy+ closer = dist < best+ best = np.where(closer, dist, best)+ sgn = np.where(closer, np.sign(d[0] * qy - d[1] * qx), sgn)+ arc = np.where(closer, cum[i] + t * (cum[min(i + 2, n - 1)] - cum[i]), arc)+ sd = np.sqrt(best) * sgn * side+ ends = smoothstep(0, 220, arc) * smoothstep(cum[-1], cum[-1] - 220, arc)+ reach = smoothstep(260, 120, np.sqrt(best)) * ends+ self.h += (height * smoothstep(-soft, soft * 2.5, sd) - height * 0.5) * reach+ self._dirty()++ def flowstone(self, x0, x1, top=0, length=420, thick=18.0, folds=44.0):+ """calcite drapery hanging from the top: rounded folds, orange bands, lobed lower edge, wet"""+ H, W = self.H, self.W+ box = (max(0, int(x0) - 20), max(0, int(top)), min(W, int(x1) + 20), min(H, int(top + length * 1.25)))+ Y, X = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ n = box[2] - box[0]+ L = length * (0.55 + 0.45 * (fbm1d(n, 40, 3, self._s()) * 0.5 + 0.5))[None, :]+ warp = fbm1d(box[3] - box[1], 90, 3, self._s())[:, None] * folds * 0.35+ xw = X + warp + folds * 0.9 * fbm1d(n, 60, 2, self._s())[None, :]+ ph = xw / folds * 2 * np.pi+ ridge = (0.5 + 0.5 * np.cos(ph)) ** 0.8+ side = smoothstep(x0 - 10, x0 + 30, X) * smoothstep(x1 + 10, x1 - 30, X)+ drop = smoothstep(L + 8, L - 40, Y - top)+ m = side * drop+ sl = self._sl(box)+ self.h[sl] += m * (thick * 0.7 + thick * 0.3 * ridge)+ band = 0.5 + 0.5 * np.sin((Y - top) / 9.0 + 3 * fbm1d(n, 30, 2, self._s())[None, :])+ col = hexc(CALCITE) * (1 - 0.25 * band[..., None]) + hexc('#c08a55') * 0.25 * band[..., None]+ col *= (0.88 + 0.12 * ridge)[..., None]+ a = m[..., None] * 0.85+ self.rock[sl] = self.rock[sl] * (1 - a) + col * a+ self.alb[sl] = self.alb[sl] * (1 - a) + col * a+ self.wet[sl] = np.maximum(self.wet[sl], m * (0.55 + 0.45 * ridge))+ self._dirty()++ def crack(self, pts, width=2.0, depth=4.0, branches=1):+ """a fissure: a thin zigzag dark slot (jagged at a few px, tapering at both ends), short side branches"""+ P = spline(np.asarray(pts, np.float32), 18)+ n = len(P)+ d = np.gradient(P, axis=0); d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-6+ nrm = np.stack([-d[:, 1], d[:, 0]], 1)+ zig = np.sign(np.sin(np.arange(n) * self.rng.uniform(0.9, 1.4))) * 0.5 + fbm1d(n, 4, 3, self._s())+ P = P + nrm * (zig * width * 1.6)[:, None] + nrm * fbm1d(n, 25, 3, self._s())[:, None] * width * 3+ taper = np.clip(np.minimum(np.arange(n) / (n * 0.2), (n - 1 - np.arange(n)) / (n * 0.35)), 0.1, 1)+ strokes = [(P, width * taper * (0.5 + 0.7 * (fbm1d(n, 8, 3, self._s()) * 0.5 + 0.5)))]+ for _ in range(branches):+ i = int(self.rng.integers(n // 4, n * 3 // 4))+ side = self.rng.choice([-1, 1]); ang = np.radians(self.rng.uniform(30, 60)) * side+ R = np.array([[np.cos(ang), -np.sin(ang)], [np.sin(ang), np.cos(ang)]])+ dd = R @ d[i]+ ln = self.rng.uniform(25, 60)+ B = [P[i], P[i] + dd * ln * 0.5 + self.rng.normal(0, 3, 2), P[i] + dd * ln]+ strokes.append(_open(B, [width * 0.6, width * 0.4, width * 0.15], 8))+ box = self._box(P, 20)+ m = self._raster(box, strokes=strokes)+ sl = self._sl(box)+ self.h[sl] -= blur(m, 0.7) * depth+ a = blur(m, 0.6)[..., None] * 0.85+ self.rock[sl] = self.rock[sl] * (1 - a) + hexc('#2a1f18') * a+ self.alb[sl] = self.alb[sl] * (1 - a) + hexc('#2a1f18') * a+ self._dirty()++ def floor(self, y=965, tilt=1.3, colour=FLOOR, wobble=14.0):+ """packed clay floor below a wavy wall-base line; tilted toward the viewer (height grows downward)"""+ H, W = self.H, self.W+ line = y + fbm1d(W, 260, 4, self._s()) * wobble+ self.floor_line = line.astype(np.float32)+ Y, X = self._grid()+ dy = Y - line[None, :]+ m = smoothstep(-1.5, 1.5, dy)+ rub = (noise2d(H, W, 26, 3, self._s()) - 0.5) * 4 + (noise2d(H, W, 6, 2, self._s()) - 0.5) * 1.2+ self.h += m * (tilt * np.clip(dy, 0, None) + rub)+ col = hexc(colour) * (0.75 + 0.45 * noise2d(H, W, 90, 4, self._s()))[..., None]+ pebble = smoothstep(0.72, 0.8, noise2d(H, W, 7, 2, self._s()))[..., None]+ col = col * (1 - 0.5 * pebble) + hexc('#9a8a76') * 0.5 * pebble+ damp = (smoothstep(-34, -2, dy) * (1 - m))[..., None] # splash line at the wall base+ a = m[..., None]+ self.rock = self.rock * (1 - a) + col * a+ self.rock *= 1 - 0.35 * damp+ self.alb = self.alb * (1 - a) + col * a+ self.alb *= 1 - 0.35 * damp+ self._floor_m = m.astype(np.float32)+ self._dirty()++ def floor_h(self, x, y):+ """floor height at (x, y), for putting things on the floor"""+ if self.floor_line is None: return 0.0+ xi = int(np.clip(x, 0, self.W - 1)); yi = int(np.clip(y, 0, self.H - 1))+ return float(self.h[yi, xi])++ # ------------------------------------------------------------------ props on the floor+ def _dome(self, box, m, height, power=0.85, sigma=None):+ sigma = sigma or max(2.0, min(box[2] - box[0], box[3] - box[1]) / 7)+ b = blur(m, sigma)+ return height * np.clip((b - 0.5) * 2, 0, 1) ** power * (m > 0.02)++ def stone(self, pts, colour='#7d6a58', height=12.0, rough=1.0, wet=0.0):+ """a slab or pebble lying on the floor (any closed outline)"""+ P = _closed(pts, 8)+ box = self._box(P, 10)+ m = self._raster(box, polys=[P])+ sl = self._sl(box)+ n = self._noise(box, 18, 3)+ self.h[sl] += self._dome(box, m, height) + m * (n - 0.5) * 3 * rough+ col = _c(colour) * (0.8 + 0.35 * self._noise(box, 30, 3))[..., None]+ a = blur(m, 0.6)[..., None]+ self.rock[sl] = self.rock[sl] * (1 - a) + col * a+ self.alb[sl] = self.alb[sl] * (1 - a) + col * a+ self.wet[sl] = np.maximum(self.wet[sl], m * wet)+ self._dirty()++ def heap(self, x, y, r, pigment='red', height=None, spill=1.0):+ """a little mound of ground pigment, with powder spilled round it"""+ height = height or r * 1.3+ box = self._box([(x - r * 2, y - r * 1.4), (x + r * 2, y + r)], 6)+ Y, X = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ d = np.sqrt(((X - x) / r) ** 2 + ((Y - y) / (r * 0.55)) ** 2)+ d = d * (1 + 0.12 * (self._noise(box, 6, 2) - 0.5))+ cone = np.clip(1 - d, 0, 1) ** 1.25+ sl = self._sl(box)+ self.h[sl] += cone * height+ dust = np.clip(1.4 - d, 0, 1) * smoothstep(0.45, 0.75, self._noise(box, 4, 2)) * spill+ a = np.clip(smoothstep(0.0, 0.25, cone) + dust * 0.7, 0, 1)[..., None]+ col = _c(pigment) * (0.85 + 0.3 * self._noise(box, 3, 2))[..., None]+ self.rock[sl] = self.rock[sl] * (1 - a) + col * a+ self.alb[sl] = self.alb[sl] * (1 - a) + col * a+ self._dirty()++ def stick(self, p0, p1, width, colour='black', hollow=False, tip=None):+ """a cylinder lying on the floor: a charcoal stick, or a hollow bone blowpipe (hollow=True)"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ box = self._box([p0, p1], width * 2)+ Y, X = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ d = p1 - p0; L = float(np.linalg.norm(d)); u = d / L+ t = np.clip(((X - p0[0]) * u[0] + (Y - p0[1]) * u[1]) / L, 0, 1)+ qx, qy = p0[0] + t * d[0] - X, p0[1] + t * d[1] - Y+ dist = np.sqrt(qx * qx + qy * qy) / (width / 2)+ cyl = np.sqrt(np.clip(1 - dist * dist, 0, 1))+ m = smoothstep(1.05, 0.9, dist)+ sl = self._sl(box)+ self.h[sl] = np.maximum(self.h[sl], self.h[sl] * (1 - m) + (self.h[sl] + cyl * width * 0.5) * m)+ col = _c(colour) * (0.85 + 0.25 * self._noise(box, 10, 2))[..., None]+ if colour in ('black', 'manganese'): # charcoal: a faint satin sheen+ self.wet[sl] = np.maximum(self.wet[sl], m * 0.25)+ a = m[..., None]+ if tip is not None: # pigment stain at the far end+ ta = (smoothstep(0.75, 0.95, t) * m)[..., None]+ col = col * (1 - ta * 0.8) + _c(tip) * ta * 0.8+ self.rock[sl] = self.rock[sl] * (1 - a) + col * a+ self.alb[sl] = self.alb[sl] * (1 - a) + col * a+ if hollow: # the open end of the bone+ r = width * 0.26+ e = np.sqrt((X - p0[0]) ** 2 + (Y - p0[1]) ** 2)+ hole = smoothstep(r + 0.8, r - 0.8, e)+ self.h[sl] -= hole * width * 0.3+ self.alb[sl] *= (1 - 0.8 * hole)[..., None]+ self._dirty()++ # ------------------------------------------------------------------ fire and lamp+ def fire(self, x, y, size=220, power=1.6, reach=1150):+ """campfire on the floor at (x, y) (base of the flames): stones, ash, logs, flames, sparks, smoke + light"""+ r = self.rng+ # ash and charcoal on the floor+ box = self._box([(x - size * 0.9, y - size * 0.3), (x + size * 0.9, y + size * 0.3)], 6)+ Y, X = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ d = np.sqrt(((X - x) / (size * 0.75)) ** 2 + ((Y - y) / (size * 0.2)) ** 2)+ ash = smoothstep(1.0, 0.55, d * (1 + 0.25 * (self._noise(box, 20, 3) - 0.5)))+ sl = self._sl(box)+ col = hexc('#5f5852') * (0.7 + 0.5 * self._noise(box, 5, 2))[..., None]+ a = (ash * 0.8)[..., None]+ self.rock[sl] = self.rock[sl] * (1 - a) + col * a+ self.alb[sl] = self.alb[sl] * (1 - a) + col * a+ # a ring of stones round the front and sides+ for k in range(16):+ ang = np.radians(-30 + k * 240 / 15 + r.uniform(-5, 5))+ sx, sy = x + np.cos(ang) * size * 0.66, y + np.sin(ang) * size * 0.19 + 8+ if sy > self.H + 10: continue+ rr = size * r.uniform(0.05, 0.08)+ wob = 1 + 0.25 * fbm1d(11, 4, 2, int(r.integers(1 << 30)))+ self.stone([(sx + np.cos(t) * rr * w_, sy + np.sin(t) * rr * 0.6 * w_)+ for t, w_ in zip(np.linspace(0, 2 * np.pi, 11, endpoint=False), wob)],+ colour=r.choice(['#4f443a', '#463c34', '#5a4c40']), height=rr * 0.9, rough=1.6)+ fz = self.floor_h(x, y)+ self.fires.append(dict(x=x, y=y, size=size, seed=self._s()))+ self.lights.append(dict(x=x, y=y - size * 0.42, z=fz + size * 0.45, col=FIRE, power=power, reach=reach,+ wrap=0.2, shadow=True))+ self._fx = None; self._dirty()++ def lamp(self, x, y, size=120, power=0.5, reach=560):+ """a stone fat lamp on the floor (red sandstone bowl with a handle, glossy fat, a small flame)"""+ rx, ry = size * 0.42, size * 0.17+ P = [(x + np.cos(t) * rx, y + np.sin(t) * ry) for t in np.linspace(0, 2 * np.pi, 16, endpoint=False)]+ self.stone(P, colour='#8d4e34', height=size * 0.12, rough=0.5)+ self.stick((x + rx * 0.85, y + 2), (x + rx * 1.75, y + ry * 0.55), size * 0.17, colour='#7f452e')+ box = self._box([(x - rx, y - ry), (x + rx, y + ry)], 4)+ Y, X = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ d = np.sqrt(((X - x + rx * 0.05) / (rx * 0.66)) ** 2 + ((Y - y + ry * 0.12) / (ry * 0.58)) ** 2)+ pool = smoothstep(1.0, 0.85, d)+ sl = self._sl(box)+ self.h[sl] -= pool * size * 0.06+ col = hexc('#4a2c12') * (0.85 + 0.3 * self._noise(box, 8, 2))[..., None]+ a = pool[..., None]+ self.alb[sl] = self.alb[sl] * (1 - a) + col * a+ self.wet[sl] = np.maximum(self.wet[sl], pool * 0.9)+ wx, wy = x - rx * 0.42, y - ry * 0.15+ self.stick((wx - size * 0.05, wy + 3), (wx + size * 0.06, wy - 1), size * 0.05, colour='#2b2018')+ fz = self.floor_h(x, y)+ self.lamps.append(dict(x=wx, y=wy, size=size, seed=self._s()))+ self.lights.append(dict(x=wx, y=wy - size * 0.3, z=fz + size * 0.32, col=LAMPLIGHT, power=power, reach=reach,+ wrap=0.4, shadow=False))+ self._fx = None; self._dirty()++ # ------------------------------------------------------------------ figures (drafted in a unit frame)+ def _T(self, x, y, s, facing=1, rot=0.0):+ a = np.radians(rot); c, sn = np.cos(a), np.sin(a)++ def T(P):+ P = np.asarray(P, np.float32).reshape(-1, 2) * s+ u = P[:, 0] * facing; v = P[:, 1]+ return np.stack([x + u * c + v * sn, y - u * sn + v * c], 1)+ return T++ def _build(self, kind, T, s, polys=(), strokes=(), regions=(), discs=(), pad=80):+ """polys: [(part, unit pts)], strokes: [(part, unit pts, unit widths)], regions: [(name, unit polygon)]"""+ allp = [T(P) for _, P in polys] + [T(P) for _, P, _ in strokes]+ box = self._box(np.vstack(allp), pad)+ fig = Figure(box, kind)+ for part, P in polys:+ fig.add(part, self._raster(box, polys=[_closed(T(P), 8)]))+ for part, P, w in strokes:+ S, ww = _open(T(P), np.asarray(w, np.float32) * s, 10)+ fig.add(part, self._raster(box, strokes=[(S, ww)]))+ for part, P, r in discs:+ p = T([P])[0]+ fig.add(part, self._raster(box, discs=[(p[0], p[1], r * s)]))+ body = fig.mask('body')+ if 'legs' in fig.parts: # legs = the part below / outside the body+ fig.parts['legs'] = fig.parts['legs'] * (1 - smoothstep(0.3, 1.0, blur(body, 2.0)))+ for name, P in regions:+ fig.add(name, self._raster(box, polys=[T(P)]) * body)+ return fig++ def shape(self, x, y, size, polys=(), strokes=(), regions=(), facing=1, rot=0.0, kind='shape'):+ """any figure from unit-frame outlines and strokes (see bison / horse for the format)"""+ return self._build(kind, self._T(x, y, size, facing, rot), size, polys, strokes, regions)++ def bison(self, x, y, size, facing=1, rot=0.0, head_drop=0.0):+ """steppe bison in profile: great hump, small low head, short horns, beard, short legs.+ (x, y) = body centre, size = body length (rump to chest) px"""+ hd = head_drop+ body = [(-0.50, -0.08), (-0.42, -0.16), (-0.25, -0.20), (-0.05, -0.27), (0.06, -0.40), (0.18, -0.50),+ (0.30, -0.47), (0.40, -0.36), (0.47, -0.22 + hd * 0.4), (0.53, -0.08 + hd), (0.58, 0.05 + hd),+ (0.61, 0.13 + hd), (0.56, 0.18 + hd), (0.49, 0.16 + hd * 0.6), (0.45, 0.26 + hd * 0.4), (0.39, 0.34),+ (0.33, 0.28), (0.24, 0.29), (0.08, 0.26), (-0.12, 0.22), (-0.30, 0.17), (-0.44, 0.12), (-0.53, 0.02)]+ legs = [((0.28, 0.24), (0.31, 0.42), (0.29, 0.57), [0.10, 0.05, 0.04]),+ ((0.17, 0.25), (0.15, 0.42), (0.11, 0.56), [0.085, 0.045, 0.036]),+ ((-0.40, 0.10), (-0.35, 0.34), (-0.40, 0.56), [0.13, 0.045, 0.036]),+ ((-0.30, 0.15), (-0.24, 0.36), (-0.27, 0.55), [0.10, 0.042, 0.034])]+ strokes = [('legs', [a, b, c], w) for a, b, c, w in legs]+ strokes += [('legs', [(c[0] - 0.012, c[1] - 0.012), (c[0] + 0.028, c[1] + 0.006)], [w[2] * 1.3, w[2] * 1.2])+ for a, b, c, w in legs] # hooves+ strokes += [('horns', [(0.465, -0.21 + hd * 0.4), (0.53, -0.27 + hd * 0.4), (0.575, -0.36 + hd * 0.4), (0.56, -0.42 + hd * 0.4)], [0.04, 0.03, 0.018, 0.008]),+ ('horns', [(0.41, -0.29 + hd * 0.3), (0.425, -0.38 + hd * 0.3), (0.465, -0.44 + hd * 0.3)], [0.034, 0.02, 0.008]),+ ('tail', [(-0.515, -0.06), (-0.575, 0.06), (-0.58, 0.20)], [0.024, 0.018, 0.016]),+ ('tail', [(-0.58, 0.19), (-0.592, 0.25), (-0.585, 0.31)], [0.03, 0.045, 0.012])] # tuft+ discs = []+ regions = [('head', [(0.36, -0.60), (0.80, -0.60), (0.80, 0.50), (0.43, 0.50), (0.41, 0.10)]),+ ('hump', [(-0.04, -0.70), (0.42, -0.70), (0.42, -0.20), (0.28, -0.25), (0.10, -0.25), (-0.04, -0.23)]),+ ('belly', [(-0.46, 0.08), (-0.25, 0.08), (0.00, 0.14), (0.22, 0.17), (0.34, 0.22), (0.34, 0.50), (-0.55, 0.50)]),+ ('back', [(-0.60, -0.60), (0.10, -0.60), (0.10, -0.17), (-0.20, -0.12), (-0.60, -0.03)]),+ ('front', [(0.10, -0.70), (0.80, -0.70), (0.80, 0.60), (0.10, 0.60)])]+ fig = self._build('bison', self._T(x, y, size, facing, rot), size, [('body', body)], strokes, regions, discs)+ T = self._T(x, y, size, facing, rot)+ fig.anchors = {k: T([p])[0] for k, p in dict(eye=(0.505, -0.06 + hd * 0.8), nostril=(0.585, 0.07 + hd),+ shoulder=(0.18, -0.05), flank=(-0.12, 0.02),+ beard=(0.40, 0.24)).items()}+ fig.size, fig.facing = size, facing+ return fig++ def horse(self, x, y, size, facing=1, rot=0.0, gait='run'):+ """small-headed Ice-Age horse with a heavy belly and an upright mane; gait 'run', 'gallop' (flying) or 'stand'"""+ body = [(-0.50, -0.14), (-0.30, -0.20), (-0.05, -0.21), (0.18, -0.25), (0.30, -0.34), (0.40, -0.45),+ (0.46, -0.52), (0.51, -0.50), (0.58, -0.41), (0.655, -0.31), (0.675, -0.25), (0.635, -0.205),+ (0.56, -0.215), (0.495, -0.245), (0.44, -0.17), (0.42, -0.05), (0.40, 0.08), (0.30, 0.17),+ (0.10, 0.24), (-0.12, 0.25), (-0.30, 0.20), (-0.44, 0.11), (-0.54, -0.02)]+ if gait == 'gallop':+ legs = [((0.32, 0.10), (0.48, 0.26), (0.63, 0.30), [0.10, 0.05, 0.034]),+ ((0.25, 0.13), (0.39, 0.30), (0.35, 0.45), [0.09, 0.046, 0.032]),+ ((-0.40, 0.08), (-0.58, 0.24), (-0.76, 0.29), [0.13, 0.05, 0.034]),+ ((-0.33, 0.12), (-0.45, 0.32), (-0.60, 0.42), [0.11, 0.046, 0.032])]+ elif gait == 'run':+ legs = [((0.32, 0.10), (0.45, 0.27), (0.52, 0.44), [0.10, 0.05, 0.034]),+ ((0.25, 0.13), (0.24, 0.31), (0.13, 0.41), [0.09, 0.046, 0.032]),+ ((-0.40, 0.08), (-0.50, 0.28), (-0.64, 0.41), [0.13, 0.05, 0.034]),+ ((-0.32, 0.12), (-0.22, 0.30), (-0.19, 0.46), [0.11, 0.046, 0.032])]+ else:+ legs = [((0.30, 0.12), (0.32, 0.33), (0.30, 0.50), [0.10, 0.05, 0.034]),+ ((0.21, 0.15), (0.20, 0.34), (0.19, 0.50), [0.09, 0.046, 0.032]),+ ((-0.38, 0.10), (-0.33, 0.31), (-0.38, 0.50), [0.13, 0.05, 0.034]),+ ((-0.29, 0.14), (-0.24, 0.33), (-0.27, 0.50), [0.11, 0.046, 0.032])]+ strokes = [('legs', [a, b, c], w) for a, b, c, w in legs]+ strokes += [('legs', [c, (c[0] + 0.02, c[1] + 0.012)], [w[2] * 1.35, w[2] * 1.2]) for a, b, c, w in legs]+ strokes += [('ears', [(0.455, -0.50), (0.44, -0.585)], [0.04, 0.012]),+ ('mane', [(0.15, -0.255), (0.265, -0.345), (0.375, -0.46), (0.445, -0.535)], [0.05, 0.075, 0.07, 0.045]),+ ('tail', [(-0.52, -0.11), (-0.66, -0.05), (-0.80, 0.08), (-0.86, 0.18)] if gait != 'stand'+ else [(-0.52, -0.11), (-0.60, 0.02), (-0.62, 0.20), (-0.60, 0.32)], [0.06, 0.065, 0.045, 0.02])]+ regions = [('head', [(0.42, -0.70), (0.80, -0.70), (0.80, 0.10), (0.46, 0.10), (0.43, -0.12)]),+ ('belly', [(-0.46, 0.07), (-0.30, 0.04), (-0.05, 0.10), (0.20, 0.07), (0.38, 0.02), (0.40, 0.50), (-0.55, 0.50)]),+ ('back', [(-0.60, -0.60), (0.20, -0.60), (0.20, -0.17), (-0.10, -0.13), (-0.40, -0.09), (-0.60, -0.05)]),+ ('front', [(0.20, -0.80), (0.90, -0.80), (0.90, 0.60), (0.20, 0.60)])]+ fig = self._build('horse', self._T(x, y, size, facing, rot), size, [('body', body)], strokes, regions)+ T = self._T(x, y, size, facing, rot)+ fig.anchors = {k: T([p])[0] for k, p in dict(eye=(0.525, -0.425), nostril=(0.655, -0.27), mouth=(0.64, -0.225),+ shoulder=(0.25, -0.05), flank=(-0.15, 0.0)).items()}+ fig.size, fig.facing = size, facing+ return fig++ def deer(self, x, y, size, facing=1, rot=0.0, kind='stag', gait='leap'):+ """red deer: kind 'stag' (antlers) or 'hind' (big ears); gait 'leap' or 'stand'"""+ body = [(-0.48, -0.10), (-0.30, -0.15), (-0.05, -0.16), (0.18, -0.19), (0.30, -0.30), (0.40, -0.46),+ (0.46, -0.575), (0.52, -0.60), (0.62, -0.565), (0.72, -0.505), (0.715, -0.465), (0.63, -0.45),+ (0.55, -0.455), (0.49, -0.41), (0.42, -0.22), (0.37, -0.02), (0.25, 0.09), (0.02, 0.13),+ (-0.24, 0.11), (-0.40, 0.06), (-0.50, -0.02)]+ if gait == 'leap':+ legs = [((0.28, 0.05), (0.47, 0.17), (0.53, 0.37), [0.09, 0.04, 0.026]),+ ((0.23, 0.07), (0.41, 0.24), (0.42, 0.41), [0.08, 0.036, 0.024]),+ ((-0.40, 0.03), (-0.62, 0.20), (-0.89, 0.30), [0.12, 0.04, 0.026]),+ ((-0.35, 0.06), (-0.55, 0.27), (-0.79, 0.41), [0.10, 0.038, 0.024])]+ else:+ legs = [((0.27, 0.06), (0.30, 0.30), (0.28, 0.52), [0.085, 0.035, 0.022]),+ ((0.19, 0.09), (0.18, 0.31), (0.17, 0.52), [0.075, 0.032, 0.02]),+ ((-0.38, 0.04), (-0.31, 0.29), (-0.37, 0.52), [0.11, 0.036, 0.022]),+ ((-0.30, 0.07), (-0.24, 0.31), (-0.27, 0.52), [0.095, 0.034, 0.02])]+ strokes = [('legs', [a, b, c], w) for a, b, c, w in legs]+ strokes += [('tail', [(-0.48, -0.10), (-0.555, -0.135)], [0.035, 0.02])]+ ear = 0.05 if kind == 'stag' else 0.075+ strokes += [('ears', [(0.475, -0.58), (0.43, -0.64), (0.39, -0.67)], [ear * 0.7, ear, 0.012])]+ if kind == 'stag':+ for dx, dy, sc in ((0.0, 0.0, 1.0), (-0.06, 0.02, 0.9)):+ beam = [(0.50 + dx, -0.60 + dy), (0.44 + dx, -0.80 * sc + dy), (0.32 + dx, -0.98 * sc + dy),+ (0.22 + dx, -1.12 * sc + dy), (0.20 + dx, -1.28 * sc + dy)]+ strokes.append(('antlers', beam, [0.04, 0.034, 0.028, 0.022, 0.012]))+ for (bx, by), (tx, ty) in (((0.49, -0.66), (0.63, -0.75)), ((0.44, -0.80), (0.57, -0.93)),+ ((0.33, -0.97), (0.43, -1.13)), ((0.22, -1.13), (0.10, -1.24)),+ ((0.21, -1.25), (0.29, -1.38))):+ strokes.append(('antlers', [(bx + dx, by * sc + dy), ((bx + tx) / 2 + dx + 0.012, (by + ty) / 2 * sc + dy - 0.012),+ (tx + dx, ty * sc + dy)], [0.026, 0.019, 0.009]))+ regions = [('head', [(0.42, -0.80), (0.90, -0.80), (0.90, -0.30), (0.46, -0.30)]),+ ('belly', [(-0.45, 0.03), (-0.20, 0.03), (0.10, 0.06), (0.32, 0.0), (0.40, 0.50), (-0.55, 0.50)]),+ ('back', [(-0.60, -0.60), (0.25, -0.60), (0.25, -0.13), (-0.60, -0.04)]),+ ('front', [(0.25, -0.90), (0.90, -0.90), (0.90, 0.60), (0.25, 0.60)])]+ fig = self._build('deer', self._T(x, y, size, facing, rot), size, [('body', body)], strokes, regions)+ T = self._T(x, y, size, facing, rot)+ fig.anchors = {k: T([p])[0] for k, p in dict(eye=(0.565, -0.535), nostril=(0.705, -0.495),+ shoulder=(0.22, -0.05), flank=(-0.12, 0.0)).items()}+ fig.size, fig.facing = size, facing+ return fig++ def hunter(self, x, y, size, facing=1, rot=0.0, pose='throw'):+ """a running hunter in the red Levantine manner: triangular torso, long legs; pose 'throw' (spear raised+ back over the shoulder) or 'run' (spear held level). (x, y) = feet, size = height. The spear is separate:+ fig.anchors['grip'] and ['spear_dir'] say where it goes."""+ if pose == 'throw':+ P = dict(head=(0.06, -0.90), neck=(0.04, -0.82), sh=(0.02, -0.76), hip=(-0.04, -0.44),+ arm_b=[(0.0, -0.75), (-0.13, -0.82), (-0.20, -0.95)], arm_f=[(0.04, -0.74), (0.18, -0.70), (0.30, -0.72)],+ leg_f=[(-0.02, -0.44), (0.14, -0.26), (0.20, -0.02)], leg_b=[(-0.06, -0.44), (-0.16, -0.24), (-0.34, -0.10)],+ grip=(-0.20, -0.95), sdir=(0.95, -0.30))+ else:+ P = dict(head=(0.12, -0.88), neck=(0.09, -0.80), sh=(0.07, -0.75), hip=(-0.04, -0.44),+ arm_b=[(0.05, -0.74), (-0.08, -0.62), (-0.18, -0.58)], arm_f=[(0.08, -0.73), (0.16, -0.62), (0.26, -0.60)],+ leg_f=[(-0.02, -0.44), (0.18, -0.30), (0.26, -0.06)], leg_b=[(-0.06, -0.44), (-0.18, -0.22), (-0.38, -0.16)],+ grip=(0.10, -0.60), sdir=(1.0, -0.02))+ sh, hip = P['sh'], P['hip']+ torso = [(sh[0] - 0.075, sh[1] - 0.01), (sh[0] + 0.075, sh[1] + 0.01), (hip[0] + 0.03, hip[1]), (hip[0] - 0.03, hip[1])]+ strokes = [('body', [P['neck'], sh], [0.05, 0.06]),+ ('body', P['arm_b'], [0.04, 0.03, 0.025]), ('body', P['arm_f'], [0.04, 0.03, 0.025]),+ ('body', P['leg_f'], [0.055, 0.04, 0.022]), ('body', P['leg_b'], [0.055, 0.04, 0.022]),+ ('body', [(hip[0] - 0.035, hip[1] - 0.02), (hip[0] + 0.035, hip[1] + 0.02)], [0.07, 0.07])]+ T = self._T(x, y, size, facing, rot)+ fig = self._build('hunter', T, size, [('body', torso)], strokes, discs=[('body', P['head'], 0.065)], pad=60)+ a = np.radians(rot)+ sd = np.array([P['sdir'][0] * facing, P['sdir'][1]], np.float32)+ sd = np.array([sd[0] * np.cos(a) + sd[1] * np.sin(a), -sd[0] * np.sin(a) + sd[1] * np.cos(a)])+ fig.anchors = dict(grip=T([P['grip']])[0], spear_dir=sd / np.linalg.norm(sd), head=T([P['head']])[0])+ fig.size, fig.facing = size, facing+ return fig++ def spear(self, p0, p1, width=4.0, point=1.0):+ """a spear from butt p0 to tip p1 with a leaf-shaped point (Figure with parts 'shaft' and 'point')"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ d = p1 - p0; L = float(np.linalg.norm(d)); u = d / L; n = np.array([-u[1], u[0]])+ pl = width * 7 * point+ box = self._box([p0, p1], 40)+ fig = Figure(box, 'spear')+ sway = n * L * 0.01+ S, w = _open([p0, (p0 + p1) / 2 + sway, p1 - u * pl * 0.8], [width * 0.8, width, width * 0.9], 10)+ fig.add('shaft', self._raster(box, strokes=[(S, w)]))+ b = p1 - u * pl+ leaf = [p1, b + u * pl * 0.45 + n * width * 1.5, b + n * width * 0.5, b - n * width * 0.5, b + u * pl * 0.45 - n * width * 1.5]+ fig.add('point', self._raster(box, polys=[leaf]))+ return fig++ def hand(self, x, y, size, rot=0.0, side='left', spread=1.0, fold=(), arm=0.3):+ """a hand flat on the wall, fingers up (rot turns it). (x, y) = wrist, size = wrist to middle fingertip.+ fold: fingers bent down out of sight (0 thumb .. 4 little) -- the short-finger stencils of the old caves"""+ f = 1 if side == 'right' else -1+ palm = [(-0.20, 0.0), (-0.225, -0.22), (-0.205, -0.45), (-0.10, -0.50), (0.02, -0.52), (0.13, -0.50),+ (0.205, -0.44), (0.225, -0.24), (0.19, -0.04)]+ fingers = [((0.13, -0.47), 9, 0.40, 0.088), ((0.035, -0.51), 1, 0.46, 0.094),+ ((-0.06, -0.49), -6, 0.41, 0.09), ((-0.15, -0.43), -15, 0.31, 0.082)]+ strokes = []+ for i, ((bx, by), ang, ln, w) in enumerate(fingers):+ if (i + 1) in fold: ln *= 0.32+ a = np.radians(ang * spread)+ tip = (bx + np.sin(a) * ln, by - np.cos(a) * ln)+ mid = (bx + np.sin(a) * ln * 0.5, by - np.cos(a) * ln * 0.5)+ strokes.append(('hand', [(bx, by + 0.04), mid, tip], [w * 1.05, w * 0.95, w * 0.82]))+ tl = 0.36 * (0.35 if 0 in fold else 1)+ ta = np.radians(48 * spread)+ strokes.append(('hand', [(0.15, -0.12), (0.15 + np.sin(ta) * tl * 0.55, -0.16 - np.cos(ta) * tl * 0.5),+ (0.15 + np.sin(ta) * tl, -0.18 - np.cos(ta) * tl * 0.85)], [0.13, 0.11, 0.085]))+ if arm:+ strokes.append(('arm', [(0.0, -0.05), (0.01, arm * 0.5), (0.02, arm)], [0.36, 0.38, 0.42]))+ T = self._T(x, y, size, f, rot)+ return self._build('hand', T, size, [('hand', palm)], strokes, pad=100)++ # ------------------------------------------------------------------ painting+ def sketch(self, target, pigment='black', width=2.6, passes=2, strength=0.7, wander=3.0):+ """charcoal searching lines round the silhouette (each pass on a slightly wandering contour)"""+ box, m = self._target(target)+ h, w = m.shape+ for k in range(passes):+ dx = (self._noise(box, 60, 2) - 0.5) * 2 * wander+ dy = (self._noise(box, 60, 2) - 0.5) * 2 * wander+ Y, X = np.mgrid[0:h, 0:w]+ mw = m[np.clip(Y + dy, 0, h - 1).astype(np.int32), np.clip(X + dx, 0, w - 1).astype(np.int32)]+ mw = blur(mw, max(0.8, width * 0.55))+ band = smoothstep(0.12, 0.5, mw) * smoothstep(0.88, 0.5, mw) # a line about `width` wide+ press = 0.45 + 0.45 * self._noise(box, 50, 2)+ cov = band * self._catch(box, press) * strength * (0.75 if k else 1.0)+ cov *= smoothstep(0.15, 0.28, self._noise(box, 35, 2)) # lifts between strokes+ self._deposit(box, cov, pigment)++ def line(self, pts, width, pigment='black', end_width=None, kind='charcoal', strength=0.95, smooth=True):+ """a stroke: kind 'charcoal' (dry stick, breaks up in the hollows), 'finger' (wet paint, soft edges) or+ 'brush' (fur brush, even)"""+ P = np.asarray(pts, np.float32)+ w = [width, end_width if end_width is not None else width]+ if smooth and len(P) > 2:+ S, ww = _open(P, np.interp(np.linspace(0, 1, len(P)), [0, 1], w), 10)+ else:+ S = P if len(P) > 1 else P+ ww = np.interp(np.linspace(0, 1, len(S)), [0, 1], w)+ box = self._box(S, width * 2 + 12)+ m = self._raster(box, strokes=[(S, ww)])+ self._stroke_paint(box, m, pigment, kind, strength)+ return Sel(box, m)++ def _stroke_paint(self, box, m, pigment, kind, strength):+ if kind == 'charcoal':+ cov = blur(m, 0.7) * self._catch(box, 0.75) * strength+ elif kind == 'finger':+ mm = blur(m, 1.4)+ cov = mm * (0.72 + 0.28 * self._catch(box, 0.85)) * (0.85 + 0.15 * self._noise(box, 8, 2)) * strength+ else:+ cov = blur(m, 0.9) * (0.85 + 0.15 * self._catch(box, 0.9)) * strength+ self._deposit(box, cov, pigment)++ def paint(self, target, pigment='black', kind='finger', strength=0.95):+ """paint a drafted shape (e.g. a hunter or a spear Figure) solid with a finger / stick / brush"""+ box, m = self._target(target)+ self._stroke_paint(box, m, pigment, kind, strength)++ def blow(self, target, pigment, density=0.85, edge=2.5, halo=16.0, halo_amt=0.18, speckle=1.0, mottle=0.25,+ rim=0.0, gradient=0.0, relief=0.0, clip=None, exclude=None, soft_clip=2.0):+ """pigment spat / blown through a bone tube: soft edge, halo, droplet speckle, uneven density.+ rim: denser toward the outline; gradient: darker on top (back); relief: heavier where the wall turns away+ from the fire; clip: keep inside another Figure/Sel; exclude: leave a region (e.g. a pale belly)"""+ box, m = self._target(target)+ core = blur(m, edge)+ cov = core * density+ if rim:+ inner = blur(m, max(6.0, (box[2] - box[0]) / 22))+ cov *= 1 - rim * smoothstep(0.55, 1.0, inner)+ if gradient:+ rows = np.where(m.max(1) > 0.5)[0]+ if len(rows):+ t = np.clip((np.arange(m.shape[0], dtype=np.float32) - rows[0]) / max(1, rows[-1] - rows[0]), 0, 1)+ cov *= (1 - gradient * t ** 1.2)[:, None]+ if relief:+ _, gx, gy = self._auxiliary()+ sl = self._sl(box)+ L = self.lights[0] if self.lights else dict(x=self.W * 0.2, y=self.H)+ Y, X = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ lx, ly = L['x'] - X, L['y'] - Y+ ll = np.sqrt(lx * lx + ly * ly) + 1e-3+ facing = (-gx[sl] * lx - gy[sl] * ly) / ll # >0 turned toward the fire+ cov *= 1 - relief + relief * smoothstep(0.25, -0.35, facing)+ if exclude is not None:+ cov *= 1 - blur(self._local(exclude, box), 5.0)+ cov *= 1 - mottle + mottle * self._noise(box, 22, 3) * 1.2+ hal = blur(m, halo)+ cov = cov + halo_amt * hal * (1 - core) * density+ if speckle:+ cov = np.maximum(cov, self._speckle(box, hal * (1 - core), speckle) * density)+ if clip is not None:+ cov *= np.clip(blur(self._local(clip, box), soft_clip) * 1.15, 0, 1)+ self._deposit(box, np.clip(cov, 0, 1), pigment)++ def _speckle(self, box, field, amount):+ """droplets of a blown spray: sparse little discs where the halo thins out"""+ h, w = field.shape+ r = self.rng+ n = int(h * w * 0.004 * amount)+ xs, ys = r.uniform(0, w, n), r.uniform(0, h, n)+ p = field[ys.astype(int), xs.astype(int)]+ keep = r.random(n) < np.clip(p * 2.2, 0, 1) * (p > 0.02)+ im = Image.new('L', (w * 2, h * 2), 0)+ d = ImageDraw.Draw(im)+ for x, y, rad, v in zip(xs[keep], ys[keep], r.uniform(0.5, 2.0, keep.sum()), r.uniform(0.45, 0.95, keep.sum())):+ d.ellipse([(x - rad) * 2, (y - rad) * 2, (x + rad) * 2, (y + rad) * 2], fill=int(255 * v))+ return np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255++ def daub(self, target, pigment, density=0.8, blotch=0.4, press=0.6):+ """a fur pad dabbed on: blotchy, more pigment on the rock's high points"""+ box, m = self._target(target)+ n = self._noise(box, 11, 3)+ cov = blur(m, 1.4) * density * (1 - blotch + blotch * n * 1.3) * (0.6 + 0.4 * self._catch(box, press))+ self._deposit(box, np.clip(cov, 0, 1), pigment)++ @staticmethod+ def _inside_dist(m, K):+ """chamfer distance from the outline inward (px), up to K"""+ cur = m > 0.5+ d = np.zeros(m.shape, np.float32)+ for k in range(int(K)):+ d += cur+ e = cur.copy()+ e[1:] &= cur[:-1]; e[:-1] &= cur[1:]; e[:, 1:] &= cur[:, :-1]; e[:, :-1] &= cur[:, 1:]+ if k % 2:+ e[1:, 1:] &= cur[:-1, :-1]; e[:-1, :-1] &= cur[1:, 1:]; e[1:, :-1] &= cur[:-1, 1:]; e[:-1, 1:] &= cur[1:, :-1]+ cur = e+ if not cur.any(): break+ return d++ def outline(self, target, pigment='black', width=6.0, var=0.45, top=0.7, gaps=0.12, kind='charcoal',+ strength=0.95, parts=None):+ """the finished contour: a band inside the silhouette, thicker on top edges / the back, thinner on the+ belly, with gaps where the stick skipped; kind 'charcoal' or 'blow' (sprayed, soft)"""+ if isinstance(target, Figure) and parts:+ target = target.sel(*parts)+ box, m = self._target(target)+ d = self._inside_dist(m, width * 2.6 + 2)+ mb = blur(m, 3.0)+ gy = np.gradient(mb, axis=0)+ up = smoothstep(-0.02, 0.06, gy) # top edges (mask grows downward)+ wv = width * (0.62 + var * 1.1 * self._noise(box, 45, 2)) * (1 - top * 0.45 + top * 0.9 * up)+ band = smoothstep(wv + 1.0, wv - 1.0, d) * (m > 0.5)+ band = np.maximum(band, smoothstep(0.15, 0.5, m) * (m <= 0.5)) # antialiased outer edge+ if gaps:+ band *= smoothstep(gaps - 0.04, gaps + 0.06, self._noise(box, 28, 2))+ if kind == 'blow':+ cov = np.clip(blur(band, 1.6) * 1.2, 0, 1) * strength+ cov = np.maximum(cov, self._speckle(box, blur(band, 6) * 0.5, 0.5) * strength)+ else:+ cov = blur(band, 0.7) * (0.5 + 0.5 * self._catch(box, 0.9)) * strength+ self._deposit(box, cov, pigment)++ def dots(self, pts, r=14.0, pigment='red', press=0.8, strength=0.92):+ """palm / fingertip dots"""+ polys = []+ for i, (x, y) in enumerate(pts):+ rr = r * self.rng.uniform(0.85, 1.12)+ polys.append(_closed([(x + np.cos(t) * rr * (1 + 0.12 * self.rng.normal()), y + np.sin(t) * rr * 0.9 * (1 + 0.12 * self.rng.normal()))+ for t in np.linspace(0, 2 * np.pi, 9, endpoint=False)], 6))+ box = self._box(np.vstack(polys), 10)+ m = self._raster(box, polys=polys)+ cov = blur(m, 1.3) * (0.62 + 0.38 * self._catch(box, press)) * (0.85 + 0.15 * self._noise(box, 6, 2)) * strength+ self._deposit(box, cov, pigment)++ def stencil(self, hand, pigment='red', density=0.9, spread=34.0, puffs=11, speckle=1.0):+ """negative hand: pigment blown round a hand pressed on the wall, in several puffs aimed at the fingertips+ and sides -> a bare-rock hand inside a soft, uneven sprayed halo"""+ box = hand.box+ hm = hand.mask('hand'); am = hand.mask('arm')+ h, w = hm.shape+ r = self.rng+ thick = np.clip(blur(np.maximum(hm, am * 0.3), 6) * 4, 0, 1)+ edge = np.argwhere((thick > 0.3) & (thick < 0.7))+ cloud = np.zeros((h, w), np.float32)+ Y, X = np.mgrid[0:h, 0:w].astype(np.float32)+ top = edge[edge[:, 0] < np.percentile(edge[:, 0], 70)] if len(edge) else edge+ for k in range(puffs):+ src = top if (k % 3 and len(top)) else edge+ if not len(src): break+ cy, cx = src[r.integers(len(src))]+ sg = spread * r.uniform(0.6, 1.25)+ cloud += r.uniform(0.55, 1.0) * np.exp(-((X - cx) ** 2 + (Y - cy) ** 2) / (2 * sg * sg))+ cloud += 0.5 * thick # the hand's own edge always gets some+ cloud = blur(cloud, 3) * (0.75 + 0.5 * self._noise(box, 20, 3))+ cov = density * (1 - np.exp(-1.8 * cloud))+ hard = blur(np.maximum(hm, am * 0.55), 0.9)+ cov *= 1 - hard+ fringe = np.clip(cloud, 0, 1) * (1 - np.clip(cloud * 2.5, 0, 1))+ cov = np.maximum(cov, self._speckle(box, fringe * 1.4, speckle) * density * (1 - hard))+ self._deposit(box, np.clip(cov, 0, 1), pigment)++ def handprint(self, hand, pigment='red', press=0.65, strength=0.9):+ """positive hand: a painted palm pressed on -- only the high points take the paint"""+ box = hand.box+ m = blur(hand.mask('hand'), 1.0)+ cov = m * self._catch(box, press) * strength * (0.8 + 0.2 * self._noise(box, 5, 2))+ self._deposit(box, cov, pigment)++ # ------------------------------------------------------------------ time+ def calcite(self, x, y, rx, ry, amount=0.45, rot=0.0, popcorn=0.6):+ """a milky calcite veil grown over part of the wall (and whatever is painted there)"""+ P = [(x + np.cos(t) * rx, y + np.sin(t) * ry) for t in np.linspace(0, 2 * np.pi, 40, endpoint=False)]+ a_ = np.radians(rot)+ P = [(x + (px - x) * np.cos(a_) + (py - y) * np.sin(a_), y - (px - x) * np.sin(a_) + (py - y) * np.cos(a_)) for px, py in P]+ box = self._box(P, 20)+ m = self._raster(box, polys=[P], ss=1)+ m = blur(m, min(rx, ry) * 0.35) * (0.45 + 0.75 * self._noise(box, 40, 4))+ m = np.clip(m, 0, 1)+ sl = self._sl(box)+ nod = smoothstep(0.62, 0.8, self._noise(box, 5, 2)) * smoothstep(0.25, 0.6, m)+ self.h[sl] += nod * 0.7 * popcorn + m * 0.8+ a = (m * amount)[..., None]+ self.alb[sl] = self.alb[sl] * (1 - a) + hexc('#f2ebe0') * a+ self.alb[sl] = self.alb[sl] * (1 - 0.25 * nod[..., None] * popcorn) + hexc('#f1eadf') * 0.25 * nod[..., None] * popcorn+ self.wet[sl] = np.maximum(self.wet[sl], m * 0.35)+ self._dirty()++ def flake(self, n=40, size=(1.5, 4.0), box=None, min_load=0.5):+ """paint lost in small flakes (only where there is paint), showing the fresher rock underneath"""+ r = self.rng+ x0, y0, x1, y1 = box or (0, 0, self.W, self.H)+ cand = np.argwhere(self.load[y0:y1, x0:x1] > min_load)+ if not len(cand): return+ pick = cand[r.integers(0, len(cand), n)]+ im = Image.new('L', (self.W, self.H), 0)+ d = ImageDraw.Draw(im)+ for yy, xx in pick:+ cx, cy = xx + x0, yy + y0+ rr = r.uniform(*size)+ k = 12+ wob = 1 + 0.22 * fbm1d(k, 4, 2, int(r.integers(1 << 30)))+ pts = [(cx + np.cos(t) * rr * w_, cy + np.sin(t) * rr * w_ * 0.8) for t, w_ in+ zip(np.linspace(0, 2 * np.pi, k, endpoint=False) + r.uniform(0, 6.3), wob)]+ d.polygon(pts, fill=255)+ m = blur(np.asarray(im, np.float32) / 255, 0.7)+ a = m[..., None]+ self.alb = self.alb * (1 - a * 0.85) + self.rock * 0.93 * a * 0.85+ self.load *= 1 - m+ self.h -= m * 0.3+ self._dirty()++ def claws(self, x, y, angle=-75.0, n=4, length=170.0, spread=20.0, depth=3.2, width=6.0, curve=0.12):+ """a cave bear's claw marks: n parallel grooves scratched into the soft surface, pale and fresh"""+ a = np.radians(angle)+ u = np.array([np.cos(a), -np.sin(a)]); nv = np.array([-u[1], u[0]])+ strokes = []+ for i in range(n):+ o = (i - (n - 1) / 2) * spread+ L = length * self.rng.uniform(0.75, 1.05)+ p0 = np.array([x, y]) + nv * o + u * self.rng.uniform(-8, 8)+ P = [p0, p0 + u * L * 0.5 + nv * (L * curve + o * 0.15), p0 + u * L + nv * (L * curve * 0.6 + o * 0.3)]+ strokes.append(_open(P, [width * 0.4, width, width * 0.25], 12))+ box = self._box(np.vstack([s for s, _ in strokes]), 16)+ m = self._raster(box, strokes=strokes)+ sl = self._sl(box)+ mb = blur(m, 1.0)+ rim = np.clip(blur(m, 2.6) - mb, 0, 1)+ self.h[sl] += -mb * depth + rim * depth * 0.6+ fresh = np.clip(self.rock[sl] * 1.05 + 0.04, 0, 1) * 0.6 + hexc(CALCITE) * 0.4+ aa = (mb * 0.85)[..., None]+ self.alb[sl] = self.alb[sl] * (1 - aa) + fresh * aa+ self.load[sl] *= 1 - mb+ self._dirty()++ def soot(self, x, y, amount=0.55, drift=0.22, spread=0.45, ceiling=90.0):+ """soot the fire laid on the wall: a plume rising (and leaning by `drift`) from (x, y), plus the ceiling"""+ H, W = self.H, self.W+ Y, X = self._grid()+ up = np.clip(y - Y, 0, None)+ cx = x + drift * up + 40 * fbm1d(H, 200, 3, self._s())[:, None]+ wid = 50 + spread * up+ plume = np.exp(-((X - cx) / wid) ** 2) * smoothstep(0, 220, up) * (y > Y)+ plume *= 0.55 + 0.45 * smoothstep(0, y, up)+ top = smoothstep(ceiling * 1.6, 0, Y) * 0.7+ n = noise2d(H, W, 70, 4, self._s())+ s = np.clip((plume + top * (0.6 + 0.4 * plume)) * (0.55 + 0.75 * n), 0, 1) * amount+ s *= 1 - self._floor_m+ a = s[..., None]+ self.alb = self.alb * (1 - a) + hexc(SOOT) * a++ # ------------------------------------------------------------------ light+ def _shadow(self, L, dx, dy, dz, reach=140, step=3.0, K=5, soft=5.0):+ """shadow from a point light: march along the in-plane direction to the light, per-pixel climb rate"""+ H, W = self.H, self.W+ dist = np.sqrt(dx * dx + dy * dy) + 1e-3+ slope = dz / dist+ ang = np.arctan2(dy, dx)+ far = dist > 40+ lo, hi = np.percentile(ang[far], [0.5, 99.5]) if far.any() else (-np.pi, np.pi)+ angs = np.linspace(lo, hi, K)+ da = (hi - lo) / max(K - 1, 1) + 1e-6+ R = int(reach + 2)+ hp = np.pad(self.h, R, mode='edge')+ acc = np.zeros((H, W), np.float32); wsum = np.zeros((H, W), np.float32)+ for a in angs:+ wgt = np.clip(1 - np.abs(ang - a) / da, 0, 1)+ if wgt.max() <= 0: continue+ ux, uy = np.cos(a), np.sin(a)+ m = np.full((H, W), -1e9, np.float32)+ t = step+ while t <= reach:+ ox, oy = int(round(ux * t)), int(round(uy * t))+ np.maximum(m, hp[R + oy:R + oy + H, R + ox:R + ox + W] - slope * t, out=m)+ t += step+ acc += wgt * smoothstep(0.0, soft, m - self.h); wsum += wgt+ return acc / (wsum + 1e-6)++ def _lighting(self):+ if self._lit is not None: return self._lit+ H, W = self.H, self.W+ n = height_normals(self.h)+ Y, X = self._grid()+ I = np.zeros((H, W, 3), np.float32); S = np.zeros((H, W, 3), np.float32)+ for L in self.lights:+ dx = L['x'] - X; dy = L['y'] - Y; dz = L['z'] - self.h+ d = np.sqrt(dx * dx + dy * dy + dz * dz) + 1e-3+ lam = (n[..., 0] * dx + n[..., 1] * dy + n[..., 2] * dz) / d+ s = np.clip((lam + L['wrap']) / (1 + L['wrap']), 0, None)+ fall = 1 / (1 + (d / L['reach']) ** 2)+ sh = self._shadow(L, dx, dy, dz) if L['shadow'] else 0.0+ e = s * fall * (1 - 0.7 * sh) * L['power']+ I += e[..., None] * L['col']+ hx, hy, hz = dx / d, dy / d, dz / d + 1+ hn = np.sqrt(hx * hx + hy * hy + hz * hz)+ ndh = np.clip((n[..., 0] * hx + n[..., 1] * hy + n[..., 2] * hz) / hn, 0, 1)+ spec = self.wet * ndh ** 36 * fall * (1 - sh) * L['power'] * 1.6+ S += spec[..., None] * L['col']+ ao = ambient_occlusion(self.h, radii=(3, 10, 30), depth=(3.0, 8.0, 20.0))+ amb = (np.array([0.040, 0.044, 0.056], np.float32) * (1 - ao)[..., None])+ I = I * (1 - 0.45 * ao)[..., None] + amb+ self._lit = (I, S)+ return self._lit++ # ------------------------------------------------------------------ fire layer (in front of the wall)+ def _tongue(self, E, box, x, y, hgt, wid, lean, phase, r):+ n = 36+ t = np.linspace(0, 1, n)+ cx = x + lean * hgt * t ** 1.6 + wid * 0.45 * np.sin(phase + t * 5.2) * t + r.normal(0, 1) * wid * 0.1 * t+ cy = y - hgt * t+ w = wid * (1 - t) ** 0.85 * np.clip(0.55 + t * 4, 0, 1)+ S = np.stack([cx, cy], 1)+ mo = blur(self._raster(box, strokes=[(S, np.maximum(w, 0.6))], ss=2), 1.3)+ k = int(n * 0.6)+ mc = blur(self._raster(box, strokes=[(S[:k], np.maximum(w[:k] * 0.48, 0.6))], ss=2), 1.8)+ E += mo[..., None] * np.array([0.95, 0.26, 0.04], np.float32) * 0.5+ E += mc[..., None] * np.array([1.0, 0.62, 0.20], np.float32) * 0.5++ def _fire_layer(self):+ if self._fx is not None: return self._fx+ H, W = self.H, self.W+ E = np.zeros((H, W, 3), np.float32)+ A = np.zeros((H, W), np.float32); C = np.zeros((H, W, 3), np.float32)+ smoke = np.zeros((H, W), np.float32)+ for f in self.fires:+ r = np.random.default_rng(f['seed'])+ x, y, s = f['x'], f['y'], f['size']+ box = self._box([(x - s * 0.9, y - s * 1.35), (x + s * 0.9, y + s * 0.35)], 30)+ sl = self._sl(box)+ # logs: charred, lit on top by the flames, glowing cracks+ for k in range(4):+ ang = np.radians([205, 335, 240, 300][k] + r.uniform(-6, 6))+ ln = s * r.uniform(0.5, 0.62)+ p1 = np.array([x + np.cos(ang) * ln, y + 10 - np.sin(ang) * s * 0.16])+ p0 = np.array([x + np.cos(ang) * s * 0.05, y - s * 0.06])+ wd = s * r.uniform(0.08, 0.1)+ lm = self._raster(box, strokes=[(np.array([p0, p1]), np.array([wd, wd * 0.9]))], ss=2)+ Yl, Xl = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ d = p1 - p0; L = np.linalg.norm(d); nrm = np.array([-d[1], d[0]]) / L+ if nrm[1] > 0: nrm = -nrm+ across = ((Xl - p0[0]) * nrm[0] + (Yl - p0[1]) * nrm[1]) / (wd / 2) # +1 top edge+ lit = np.clip(across, -1, 1) * 0.5 + 0.5+ cyl = np.sqrt(np.clip(1 - np.clip(across, -1, 1) ** 2, 0, 1))+ bark = 0.75 + 0.5 * self._noise(box, 4, 2)+ col = (np.array([0.035, 0.026, 0.02], np.float32)+ + (cyl * lit ** 1.5 * bark)[..., None] * np.array([0.62, 0.26, 0.08], np.float32))+ ncr = self._noise(box, 6, 2)+ crack = smoothstep(0.66, 0.74, ncr) * smoothstep(0.2, 0.9, lit) * lm+ A[sl] = np.maximum(A[sl], lm)+ C[sl] = C[sl] * (1 - lm[..., None]) + col * lm[..., None]+ E[sl] += crack[..., None] * np.array([1.0, 0.38, 0.08], np.float32) * 1.4+ # ember bed+ Yl, Xl = np.mgrid[box[1]:box[3], box[0]:box[2]].astype(np.float32)+ dd = np.sqrt(((Xl - x) / (s * 0.42)) ** 2 + ((Yl - y - 4) / (s * 0.1)) ** 2)+ emb = smoothstep(1.0, 0.3, dd) * (0.4 + 0.9 * smoothstep(0.45, 0.8, self._noise(box, 7, 2)))+ E[sl] += emb[..., None] * np.array([1.0, 0.32, 0.06], np.float32) * 1.2+ # flame tongues+ Eloc = np.zeros(E[sl].shape, np.float32)+ for k in range(15):+ off = r.uniform(-1, 1)+ bx = x + off * s * 0.3+ hgt = s * r.uniform(0.5, 1.0) * (1 - 0.5 * abs(off))+ self._tongue(Eloc, box, bx, y + 2, hgt, s * r.uniform(0.15, 0.24) * (1 - 0.35 * abs(off)),+ 0.1 + r.uniform(-0.06, 0.08), r.uniform(0, 6.28), r)+ for k in range(5): # detached licks above+ bx = x + r.uniform(-0.18, 0.22) * s; by = y - s * r.uniform(0.75, 1.05)+ self._tongue(Eloc, box, bx, by, s * r.uniform(0.12, 0.25), s * r.uniform(0.03, 0.06), 0.3, r.uniform(0, 6), r)+ core = np.exp(-(((Xl - x) / (s * 0.24)) ** 2 + ((Yl - y + s * 0.15) / (s * 0.18)) ** 2))+ Eloc += core[..., None] * np.array([1.0, 0.82, 0.5], np.float32) * 0.55+ E[sl] += Eloc+ # sparks+ for k in range(11):+ sx = x + r.normal(0, s * 0.18) + r.uniform(0, s * 0.2); sy = y - s * r.uniform(0.85, 1.45)+ ln = r.uniform(2, 6)+ b2 = self._box([(sx, sy), (sx + 3, sy - ln)], 3)+ pm = self._raster(b2, strokes=[(np.array([(sx, sy), (sx + r.uniform(-1, 2), sy - ln)]), np.array([2.2, 1.4]))], ss=2)+ E[self._sl(b2)] += pm[..., None] * np.array([1.0, 0.5, 0.12], np.float32) * r.uniform(1.0, 2.0)+ # smoke: a plume rising from the flame tips, leaning right, widening+ Y, X = self._grid()+ up = np.clip(y - s * 0.7 - Y, 0, None)+ cx = x + 0.18 * up + 50 * fbm1d(H, 260, 3, int(r.integers(1 << 30)))[:, None] * smoothstep(0, 300, up)[:, 0:1]+ wid = s * 0.3 + 0.32 * up+ sm = np.exp(-((X - cx) / wid) ** 2) * smoothstep(-20, 120, up) * smoothstep(y + 40, y - s * 0.5, Y)+ sm *= 0.4 + 0.8 * noise2d(H, W, 90, 4, int(r.integers(1 << 30)))+ smoke = np.maximum(smoke, sm)+ for lp in self.lamps:+ r = np.random.default_rng(lp['seed'])+ x, y, s = lp['x'], lp['y'], lp['size']+ box = self._box([(x - s * 0.3, y - s * 0.6), (x + s * 0.3, y + s * 0.1)], 20)+ sl = self._sl(box)+ Eloc = np.zeros(E[sl].shape, np.float32)+ for k in range(3):+ self._tongue(Eloc, box, x + r.uniform(-2, 2), y, s * r.uniform(0.32, 0.42), s * 0.07, 0.05, r.uniform(0, 6), r)+ E[sl] += Eloc+ # bloom on a quarter-size copy+ Es = np.asarray(Image.fromarray(np.clip(E * 60, 0, 255).astype(np.uint8)).resize((W // 4, H // 4), Image.BOX),+ np.float32) / 60+ g1 = np.stack([blur(Es[..., i], 4) for i in range(3)], -1)+ g2 = np.stack([blur(Es[..., i], 22) for i in range(3)], -1)+ up4 = lambda a: np.stack([np.asarray(Image.fromarray(a[..., i]).resize((W, H), Image.BILINEAR), np.float32)+ for i in range(3)], -1)+ bloom = up4(g1 * 0.5 + g2 * 1.4)+ self._fx = (E, bloom, A, C, np.clip(smoke, 0, 1))+ return self._fx++ # ------------------------------------------------------------------ output+ def composite(self, exposure=1.7, smoke=0.16, vignette=0.55, grain=0.012, contrast=1.18, saturation=1.18):+ I, S = self._lighting()+ R = self.alb * I + S+ if self.fires or self.lamps:+ E, bloom, A, C, sm = self._fire_layer()+ if smoke:+ a = (sm * smoke)[..., None]+ scol = np.array([0.10, 0.085, 0.075], np.float32) + I * 0.22+ R = R * (1 - a) + scol * a+ R = R * (1 - A[..., None]) + C * A[..., None]+ R = R + E + bloom * 0.55+ out = 1 - np.exp(-R * exposure)+ out = np.clip(out, 0, 1) ** contrast+ lum = out.mean(-1, keepdims=True)+ out = np.clip(lum + (out - lum) * saturation, 0, 1)+ Y, X = self._grid()+ v = ((X / self.W - 0.5) * 1.6) ** 2 + ((Y / self.H - 0.5) * 1.5) ** 2+ out *= (1 - vignette * smoothstep(0.25, 1.25, v))[..., None]+ out = np.clip(out, 0, 1) ** 0.95+ gr = np.random.default_rng(self.seed + 101).normal(0, grain, out.shape[:2]).astype(np.float32)+ out += gr[..., None] * (0.5 + out)+ return Image.fromarray((np.clip(out, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=88, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/crayon.py b/lib/crayon.pynew file mode 100644index 0000000..4a3f26f--- /dev/null+++ b/lib/crayon.py@@ -0,0 +1,714 @@+"""crayon — a child's wax-crayon drawing on rough paper (numpy + Pillow only).++Model:+ paper : cheap rough drawing paper. Its tooth is a height field of 2-16 px bumps, histogram-equalised so a+ threshold maps straight to a coverage fraction. Bare paper shows the tooth faintly under a raking light.+ crayon : a fat stick of pigmented wax. Its worn tip is not a point but a flat facet with ridges, so a stroke+ is a bundle of parallel sub-lines (K = width / 3) of uneven strength: white streaks run along every+ stroke. Wax only rubs off onto the *peaks* of the tooth: a pixel gets wax where+ tooth + 0.35 * wax_already_there > 1 - contact * pressure+ so a light stroke leaves a speckle of white pits, a hard one fills the valleys, and every later layer+ catches more easily on the wax of the earlier ones (build-up). The crayon rides from bump to bump in+ the direction it is dragged, so the bare pits are drawn out into short streaks along the stroke+ (the tooth is averaged along the stroke angle before the threshold). `burnish` presses the wax down+ into the pits: the specks close up and the surface turns waxy and shiny.+ colour : wax is semi-opaque. New colour = lerp(under, colour * under^0.6, coverage): on white paper it is the+ crayon colour, over yellow a blue turns green, over a black outline everything stays dark, and the+ same colour twice gets deeper and more saturated.+ the hand: a child colours in by scribbling back and forth. The arm only reaches so far, so a big area is filled+ patch by patch, each patch with its own stroke angle; strokes bow like a wrist arc, turn in sharp V's+ at the outline and overshoot it (or stop short), leave triangle-shaped gaps between passes, and the+ turns are darker because two passes overlap there. Smaller things get circle scribbles (`loops`),+ bands get strokes along their length (`follow`), outlines are one wobbly line whose end runs past+ its start (`line(closed=True)`), and letters are thin glyphs re-drawn with a fat round crayon,+ each character tilted, resized and coloured differently (`write`).+ finish : wax has thickness: it is lit with the paper as one height field (raking light from the top left,+ a faint waxy sheen where it is thick); crayon crumbs sit on top; real crayons can lie on the sheet.++ from crayon import Crayon+ c = Crayon(1920, 1080, seed=3)+ c.paper()+ sun = c.circle(300, 240, 120)+ c.line(sun, c.C['orange'], closed=True) # the outline first+ c.loops(c.mask(sun), c.C['yellow']) # then colour it in with circles+ c.scribble(c.mask(c.rect(0, 0, 1920, 330)), c.C['sky'], angle=4, avoid=c.drawn(), halo=14) # colour round the sun+ c.write('MY DAY', 900, 120, 110, [c.C['red'], c.C['blue']])+ c.stick(1600, 980, -20, c.C['red']) # a real crayon lying on the paper+ c.save('out.jpg')+"""+import os+import glob+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, fbm1d, noise2d, smoothstep, polygon_mask, blob_pts, shift, height_normals, cjk_font+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++# a 24-stick school crayon box (generic names, no brand)+COLOURS = {+ 'red': '#d8302c', 'scarlet': '#ec4a32', 'orange': '#f5821f', 'apricot': '#f9b98a', 'peach': '#f6c7a1',+ 'yellow': '#fcd22e', 'lemon': '#f3e75a', 'yellowgreen': '#9ccc3c', 'green': '#2f9e48', 'darkgreen': '#1f6f3a',+ 'sky': '#5fb1ea', 'blue': '#2a63c9', 'navy': '#253b8a', 'violet': '#7550b0', 'purple': '#9b3f9a',+ 'pink': '#f27aa8', 'magenta': '#df3f8b', 'brown': '#8a5230', 'tan': '#d29a5c', 'black': '#2a2826',+ 'grey': '#8c8c8c', 'white': '#fbfaf5', 'turquoise': '#2fb7b0', 'carmine': '#b3222f',+}++_THIN_CJK = [('/System/Library/Fonts/STHeiti Light.ttc', 0), ('/System/Library/Fonts/Hiragino Sans GB.ttc', 0),+ ('/usr/share/fonts/**/NotoSansCJK*Light*.tt[cf]', 0), ('/usr/share/fonts/**/NotoSansCJK*DemiLight*.tt[cf]', 0),+ ('/usr/share/fonts/**/NotoSansCJK*Regular*.tt[cf]', 0), ('C:/Windows/Fonts/msyhl.ttc', 0),+ ('C:/Windows/Fonts/msyh.ttc', 0)]+++def _thin_font(size):+ """a light-weight sans (CJK + Latin) whose strokes are thin enough to serve as the centre line of a letter.+ $INKPAINT_FONT_CRAYON overrides."""+ env = os.environ.get('INKPAINT_FONT_CRAYON')+ cands = [(env, 0)] if env and os.path.exists(env) else []+ for pat, idx in _THIN_CJK:+ fs = glob.glob(pat, recursive=True)+ if fs: cands.append((fs[0], idx))+ p = cjk_font()+ if p: cands.append((p, 0))+ for path, idx in cands:+ try:+ return ImageFont.truetype(path, int(size), index=idx)+ except OSError:+ continue+ return ImageFont.load_default(int(size))+++def _thin(b):+ """Zhang-Suen thinning: a boolean glyph -> its one-pixel centre line"""+ I = b.astype(np.uint8).copy()+ changed = True+ while changed:+ changed = False+ for step in range(2):+ P = np.pad(I, 1)+ p2, p3, p4, p5 = P[:-2, 1:-1], P[:-2, 2:], P[1:-1, 2:], P[2:, 2:]+ p6, p7, p8, p9 = P[2:, 1:-1], P[2:, :-2], P[1:-1, :-2], P[:-2, :-2]+ nb = [p2, p3, p4, p5, p6, p7, p8, p9, p2]+ B = sum(x.astype(np.int32) for x in nb[:8])+ A = sum(((nb[i] == 0) & (nb[i + 1] == 1)).astype(np.int32) for i in range(8))+ if step == 0:+ c1, c2 = p2 * p4 * p6, p4 * p6 * p8+ else:+ c1, c2 = p2 * p4 * p8, p2 * p6 * p8+ m = (I == 1) & (B >= 2) & (B <= 6) & (A == 1) & (c1 == 0) & (c2 == 0)+ if m.any():+ I[m] = 0; changed = True+ return I.astype(bool)+++class Crayon:+ C = COLOURS++ def __init__(self, W=1920, H=1080, seed=0, paper='#f7f3e9'):+ 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.tone = _c(paper)+ self.img = np.ones((H, W, 3), np.float32) * self.tone+ self.wax = np.zeros((H, W), np.float32)+ self.tooth = np.full((H, W), 0.5, np.float32)+ self.relief = np.zeros((H, W), np.float32)+ self.over = [] # things lying on the paper (crayons), drawn at composite time+ self.crumb = np.zeros((H, W), np.float32)+ self.stages = []++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ def noise(self, scale, octaves=3, seed=None):+ return noise2d(self.H, self.W, scale, octaves, seed if seed is not None else self._seed())++ # ------------------------------------------------------------ paper+ def paper(self, tone=None, grain=1.0, fibres=0.6, scan=0.035):+ """rough drawing paper: a coarse tooth (2-16 px bumps), a few pulp fibres and a faint uneven scan light"""+ if tone is not None: self.tone = _c(tone)+ H, W = self.H, self.W+ t = 0.62 * self.noise(1.7, 2) + 0.28 * self.noise(3.8, 2) + 0.10 * self.noise(14, 2)+ if fibres:+ im = Image.new('L', (W, H), 0); d = ImageDraw.Draw(im)+ for _ in range(int(2600 * fibres)):+ x, y = self.rng.uniform(0, W), self.rng.uniform(0, H)+ a = self.rng.uniform(0, np.pi); L = self.rng.uniform(5, 18)+ bend = self.rng.normal(0, 2.5)+ d.line([(x, y), (x + np.cos(a) * L / 2 - np.sin(a) * bend, y + np.sin(a) * L / 2 + np.cos(a) * bend),+ (x + np.cos(a) * L, y + np.sin(a) * L)], fill=int(self.rng.uniform(60, 160)), width=1)+ t = t + 0.25 * blur(np.asarray(im, np.float32) / 255, 0.6)+ self.relief = blur(t, 0.7)+ # equalise: tooth is uniform on [0, 1], so 1 - threshold = the fraction of paper the wax reaches+ hist, edges = np.histogram(t, 1024)+ cdf = np.cumsum(hist).astype(np.float32); cdf /= cdf[-1]+ self.tooth = np.interp(t, edges[1:], cdf).astype(np.float32) * grain + 0.5 * (1 - grain)+ light = 1 - scan * (0.6 * self.noise(500, 2) + 0.4 * ((self.XX / W - 0.35) ** 2 + (self.YY / H - 0.3) ** 2))+ self.img = np.ones((H, W, 3), np.float32) * self.tone * light[..., None]+ self.img *= (1 - 0.03 * (self.tooth[..., None] - 0.5))++ # ------------------------------------------------------------ shapes (a child's hand: nothing is quite round or square)+ def wobble(self, pts, amp=3.0, closed=True, step=6.0, scale=14):+ """resample a polyline every `step` px and push it sideways by a slow fractal wobble of `amp` px"""+ P = np.asarray(pts, np.float32)+ if closed: P = np.vstack([P, P[:1]])+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ n = max(8, int(s[-1] / step))+ ss = np.linspace(0, s[-1], n, endpoint=not closed)+ x, y = np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])+ tx, ty = np.gradient(x), np.gradient(y)+ tl = np.hypot(tx, ty) + 1e-6+ w = fbm1d(n, scale, 3, self._seed()) * amp+ if closed: # make the wobble wrap so the shape stays closed+ k = max(3, n // 8)+ w[-k:] = w[-k:] * np.linspace(1, 0, k) + w[0] * np.linspace(0, 1, k)+ return np.stack([x - ty / tl * w, y + tx / tl * w], 1)++ def circle(self, cx, cy, rx, ry=None, rot=0.0, lumpy=0.04, amp=2.0):+ """a hand-drawn circle / ellipse outline (points)"""+ ry = rx if ry is None else ry+ n = max(40, int((rx + ry) * 0.5))+ return self.wobble(blob_pts(cx, cy, rx, ry, rough=lumpy, n=n, seed=self._seed(), rot=rot), amp)++ def rect(self, x0, y0, x1, y1, skew=4.0, amp=1.8):+ """a hand-drawn box: corners a little off, sides a little bent"""+ j = lambda: self.rng.normal(0, skew)+ pts = [(x0 + j(), y0 + j()), (x1 + j(), y0 + j()), (x1 + j(), y1 + j()), (x0 + j(), y1 + j())]+ return self.poly(pts, amp=amp)++ def poly(self, pts, amp=1.8):+ return self.wobble(pts, amp, closed=True)++ def mask(self, pts, ss=1):+ return polygon_mask(self.H, self.W, pts, ss=ss)++ def drawn(self, thresh=0.12):+ """mask of everything already on the paper -- pass it as `avoid` to colour round it"""+ return (self.wax > thresh).astype(np.float32)++ # ------------------------------------------------------------ the crayon itself+ def _tip(self, width, worn=0.35):+ """the worn crayon facet: K parallel sub-lines (offset, line width, strength)"""+ K = max(2, int(round(width / 3.0)))+ offs = (np.arange(K) + 0.5) / K - 0.5+ offs = offs * width + self.rng.normal(0, width * 0.04, K)+ lw = max(2, int(round(width / K * 1.55)))+ prof = 1 - 0.28 * (2 * np.abs(offs) / max(width, 1)) ** 2+ st = prof * self.rng.uniform(1 - worn, 1.0, K)+ st[self.rng.random(K) < 0.22] *= 0.4 # a ridge that hardly touches -> white streak+ return offs, lw, st++ def _render(self, passes, nref=None):+ """passes: list of (pts (n,2), pressure, group, tip). Sub-lines are drawn as polylines on one L image per group,+ brightest last (so each group is the max of its strokes); groups then add up like layers of wax."""+ groups = {}+ boxes = []+ for pts, p, g, tip in passes:+ pts = np.asarray(pts, np.float32)+ if len(pts) < 2: continue+ offs, lw, st = tip+ if nref is not None:+ nx = np.full(len(pts), nref[0], np.float32); ny = np.full(len(pts), nref[1], np.float32)+ else:+ tx, ty = np.gradient(pts[:, 0]), np.gradient(pts[:, 1])+ tl = np.hypot(tx, ty) + 1e-6+ nx, ny = -ty / tl, tx / tl+ for o, s in zip(offs, st):+ q = np.stack([pts[:, 0] + nx * o, pts[:, 1] + ny * o], 1)+ v = int(np.clip(255 * p * s, 0, 255))+ if v < 6: continue+ groups.setdefault(g, []).append((v, lw, q))+ boxes.append((pts.min(0), pts.max(0), max(abs(offs).max(), 1) + lw))+ if not groups: return None, None+ lo = np.min([b[0] - b[2] for b in boxes], 0); hi = np.max([b[1] + b[2] for b in boxes], 0)+ x0, y0 = max(0, int(lo[0]) - 4), max(0, int(lo[1]) - 4)+ x1, y1 = min(self.W, int(hi[0]) + 5), min(self.H, int(hi[1]) + 5)+ if x1 <= x0 or y1 <= y0: return None, None+ keep = np.ones((y1 - y0, x1 - x0), np.float32)+ for g, items in groups.items():+ im = Image.new('L', (x1 - x0, y1 - y0), 0); d = ImageDraw.Draw(im)+ items.sort(key=lambda it: it[0])+ for v, lw, q in items:+ d.line([(float(a) - x0, float(b) - y0) for a, b in q], fill=v, width=lw, joint='curve')+ keep *= 1 - np.asarray(im, np.float32) / 255+ return 1 - keep, (x0, y0, x1, y1)++ def _drag(self, sl, angle, reach=6):+ """the tooth as the crayon feels it when dragged along `angle`: it rides from peak to peak, so the bare pits+ are drawn out into short streaks along the stroke (directional average of the tooth, re-equalised)"""+ t = self.tooth[sl]+ if angle is None: return t+ ca, sa = np.cos(np.radians(angle)), np.sin(np.radians(angle))+ P = reach + 2+ tp = np.pad(t, P, mode='edge')+ h, w = t.shape+ acc = np.zeros_like(t)+ ks = np.linspace(-reach, reach, 2 * reach + 1)+ for k in ks:+ dx, dy = k * ca, k * sa+ ix, iy = int(np.floor(dx)), int(np.floor(dy)); fx, fy = dx - ix, dy - iy+ a = tp[P + iy:P + iy + h, P + ix:P + ix + w]; b = tp[P + iy:P + iy + h, P + ix + 1:P + ix + 1 + w]+ c = tp[P + iy + 1:P + iy + 1 + h, P + ix:P + ix + w]; d = tp[P + iy + 1:P + iy + 1 + h, P + ix + 1:P + ix + 1 + w]+ acc += a * (1 - fx) * (1 - fy) + b * fx * (1 - fy) + c * (1 - fx) * fy + d * fx * fy+ acc /= len(ks)+ acc = 0.35 * t + 0.65 * acc+ hist, edges = np.histogram(acc, 256)+ cdf = np.cumsum(hist).astype(np.float32); cdf /= max(cdf[-1], 1)+ return np.interp(acc, edges[1:], cdf).astype(np.float32)++ def deposit(self, cover, box, colour, opacity=0.92, soft=0.6, angle=None):+ """rub wax of `colour` onto the paper where the contact field `cover` (crop at `box`) reaches the tooth;+ angle (deg): the stroke direction, which drags the bare pits out into streaks"""+ x0, y0, x1, y1 = box+ C = blur(cover, soft) if soft else cover+ sl = (slice(y0, y1), slice(x0, x1))+ surf = self._drag(sl, angle) + 0.35 * np.clip(self.wax[sl], 0, 1.4)+ dep = smoothstep(-0.09, 0.09, surf - (1 - C)) * smoothstep(0.03, 0.14, C)+ a = (dep * opacity)[..., None]+ under = self.img[sl]+ mix = _c(colour) * np.clip(under, 0, 1) ** 0.6+ self.img[sl] = under + (mix - under) * a+ self.wax[sl] += dep * (0.35 + 0.65 * C)++ def _pass(self, a, b, bow=0.0, jit=1.2, n=None):+ """one stroke from a to b, bowed sideways (a wrist arc) with a little hand tremor"""+ a, b = np.asarray(a, np.float32), np.asarray(b, np.float32)+ L = float(np.hypot(*(b - a)))+ n = n or max(4, int(L / 22))+ t = np.linspace(0, 1, n)[:, None]+ d = (b - a) / (L + 1e-6); nrm = np.array([-d[1], d[0]], np.float32)+ off = 4 * t * (1 - t) * bow + (fbm1d(n, max(3, n / 2), 2, self._seed())[:, None] * jit if n > 3 else 0)+ return a + (b - a) * t + nrm * off++ # ------------------------------------------------------------ colouring in+ def scribble(self, mask, colour, angle=20, width=20, density=0.7, pressure=0.8, reach=260, mess=0.5,+ angle_jitter=9, avoid=None, halo=12, fade=None, opacity=0.92, bow=0.035):+ """colour a region in by scribbling back and forth.+ angle: stroke direction in degrees (0 = left-right, 90 = up-down); width: crayon contact width (px);+ density 0..1: how close the passes are (low = triangle gaps between them); pressure 0..1: how far the wax+ reaches into the tooth; reach: arm length -- big areas are coloured patch by patch, each patch at its own+ angle (None = one patch); mess 0..1: how far the turns overshoot the outline (or stop short of it);+ avoid / halo: a mask to colour around, leaving a white margin of `halo` px (clouds, letters, a sun);+ fade=(y_full, y_none): pressure dies away downwards and the passes give out (a sky the child got bored of)"""+ Mfull = (np.asarray(mask) > 0.5)+ M = Mfull.copy()+ keep = None+ if avoid is not None:+ keep = np.clip(np.asarray(avoid, np.float32), 0, 1)+ M &= ~(blur(keep, max(1.0, halo * 0.5)) > 0.08) if halo else ~(keep > 0.5)+ ys, xs = np.nonzero(M)+ if len(xs) < 20: return+ x0, x1, y0, y1 = xs.min(), xs.max(), ys.min(), ys.max()+ a0 = np.radians(angle)+ U0 = np.array([np.cos(a0), np.sin(a0)], np.float32); V0 = np.array([-U0[1], U0[0]], np.float32)+ corners = np.array([[x0, y0], [x1, y0], [x0, y1], [x1, y1]], np.float32)+ cu, cv = corners @ U0, corners @ V0+ s = width * (2.3 - 1.6 * density)+ if reach is None:+ nu, nv = 1, 1; Lu, Lv = cu.max() - cu.min() + 4 * width, cv.max() - cv.min() + 4 * width+ else:+ Lu, Lv = reach, reach * 1.3+ nu = max(1, int(np.ceil((cu.max() - cu.min()) / Lu))); nv = max(1, int(np.ceil((cv.max() - cv.min()) / Lv)))+ Lu, Lv = (cu.max() - cu.min()) / nu, (cv.max() - cv.min()) / nv+ tip = self._tip(width)+ passes = []+ order = [(i, j) for i in range(nu) for j in range(nv)]+ for k, (i, j) in enumerate(order):+ uc = cu.min() + (i + 0.5) * Lu + self.rng.normal(0, Lu * 0.06)+ vc = cv.min() + (j + 0.5) * Lv + self.rng.normal(0, Lv * 0.06)+ c = U0 * uc + V0 * vc+ ap = a0 + np.radians(self.rng.normal(0, angle_jitter)) if (nu * nv > 1) else a0 + np.radians(self.rng.normal(0, angle_jitter * 0.3))+ U = np.array([np.cos(ap), np.sin(ap)], np.float32); V = np.array([-U[1], U[0]], np.float32)+ hu = Lu * (0.62 if nu > 1 else 0.6) + (width if nu == 1 else 0)+ hv = Lv * (0.6 if nv > 1 else 0.6) + (width if nv == 1 else 0)+ us = np.arange(-hu, hu, 2.0, dtype=np.float32)+ rows = np.arange(-hv + s * 0.25, hv, s / 2, dtype=np.float32)+ chains, active = [], []+ for r, v in enumerate(rows):+ px = c[0] + us * U[0] + v * V[0]; py = c[1] + us * U[1] + v * V[1]+ ix, iy = np.round(px).astype(int), np.round(py).astype(int)+ ok = (ix >= 0) & (iy >= 0) & (ix < self.W) & (iy < self.H)+ ins = np.zeros(len(us), bool); ins[ok] = M[iy[ok], ix[ok]]+ if not ins.any():+ active = []; continue+ full = np.zeros(len(us), bool); full[ok] = Mfull[iy[ok], ix[ok]]+ dd = np.diff(np.concatenate([[0], ins.astype(np.int8), [0]]))+ st, en = np.nonzero(dd == 1)[0], np.nonzero(dd == -1)[0] - 1+ # run end kinds: 1 = the outline, 2 = something to colour round (careful), 0 = the arm's reach+ kind = lambda i: 0 if (i < 0 or i >= len(us)) else (2 if full[i] else 1)+ minrun = max(2, int(0.35 * width)) # (samples are 2 px) no gaps narrower than 0.7 x width+ runs = [(us[a], us[b], kind(a - 1), kind(b + 1)) for a, b in zip(st, en) if b - a >= minrun]+ new_active = []+ for run in runs:+ hit = None+ for ch in active:+ la, lb = ch[-1][1], ch[-1][2]+ if min(lb, run[1]) - max(la, run[0]) > 0.3 * min(lb - la, run[1] - run[0]) and ch not in new_active:+ hit = ch; break+ if hit is None:+ hit = []; chains.append(hit)+ hit.append((v, run[0], run[1], run[2], run[3]))+ new_active.append(hit)+ active = new_active+ for ch in chains:+ if len(ch) < 2 and (ch[0][2] - ch[0][1]) < width: continue+ side = self.rng.integers(2)+ turns = []+ for r, (v, ua, ub, ea, eb) in enumerate(ch):+ left = (r + side) % 2 == 0+ edge = ea if left else eb+ u = ua if left else ub+ if edge == 1: # a real outline: overshoot it or stop short+ o = float(np.clip(self.rng.normal(mess * 7 - 2.5, 2.5 + mess * 5), -9, 26)) - width * 0.32+ elif edge == 2: # colouring round something: careful, stop short+ o = float(np.clip(self.rng.normal(0, 2.0), -5, 4)) - width * 0.45+ else: # the edge of the arm's reach+ o = self.rng.normal(0, 7)+ u = u - o if left else u + o+ turns.append(c + U * u + V * v)+ pb = bow * self.rng.choice([-1, 1]) * Lu+ prs = pressure * (0.84 + 0.36 * fbm1d(max(len(turns), 4), 5, 2, self._seed()))+ for q in range(len(turns) - 1):+ A, B = turns[q], turns[q + 1]+ pp = prs[q]+ if fade is not None:+ my = (A[1] + B[1]) / 2+ f = float(np.clip((fade[1] - my) / (fade[1] - fade[0]), 0, 1))+ if self.rng.random() > f ** 0.6 + 0.05: continue+ pp *= 0.45 + 0.55 * f+ passes.append((self._pass(A, B, bow=pb), pp, (k % 2) * 2 + q % 2, tip))+ cover, box = self._render(passes)+ if cover is None: return+ if keep is not None: # the things coloured round stay (mostly) clean+ bx0, by0, bx1, by1 = box+ cover = cover * (1 - 0.9 * blur(keep[by0:by1, bx0:bx1], 1.5))+ self.deposit(cover, box, colour, opacity, angle=angle)++ def loops(self, mask, colour, r=16, width=12, density=0.7, pressure=0.8, mess=0.4, avoid=None, halo=10, opacity=0.92):+ """colour a region in with a coiled circle scribble ('eeeee'), the way children fill tree tops, suns and+ bushes; the coil wanders back and forth across the shape; loops near the edge spill over it a little"""+ M = (np.asarray(mask) > 0.5)+ if avoid is not None:+ M &= ~(blur(np.asarray(avoid, np.float32), max(1.0, halo * 0.5)) > 0.08)+ inner = blur(M.astype(np.float32), r * (0.55 - 0.35 * mess)) > 0.5+ if inner.sum() < 30: inner = M+ ys, xs = np.nonzero(inner)+ if len(xs) < 5: return+ s = r * (2.4 - 1.5 * density)+ a = self.rng.uniform(-0.4, 0.4)+ U = np.array([np.cos(a), np.sin(a)], np.float32); V = np.array([-U[1], U[0]], np.float32)+ pts = np.stack([xs, ys], 1).astype(np.float32)+ pu, pv = pts @ U, pts @ V+ tip = self._tip(width)+ passes, k = [], 0+ for r_i, v in enumerate(np.arange(pv.min(), pv.max() + 1, s)):+ sel = np.abs(pv - v) < s * 0.5+ if not sel.any(): continue+ ua, ub = pu[sel].min(), pu[sel].max()+ if (r_i % 2): ua, ub = ub, ua+ L = abs(ub - ua)+ nl = max(1, int(L / (r * 0.75)))+ t = np.linspace(0, 1, nl * 18 + 1)+ ph = t * nl * 2 * np.pi * (1 if r_i % 2 == 0 else -1) + self.rng.uniform(0, 6.3)+ rr = r * (0.85 + 0.3 * fbm1d(len(t), 30, 2, self._seed()))+ cu_ = ua + (ub - ua) * t+ cx = cu_ * U[0] + v * V[0] + rr * np.cos(ph); cy = cu_ * U[1] + v * V[1] + rr * 0.85 * np.sin(ph)+ q = np.stack([cx, cy], 1)+ for j in range(nl): # one group per loop, so the overlaps add up+ seg = q[j * 18:(j + 1) * 18 + 1]+ passes.append((seg, pressure * self.rng.uniform(0.85, 1.08), k % 3, tip)); k += 1+ cover, box = self._render(passes)+ if cover is not None: self.deposit(cover, box, colour, opacity)++ def follow(self, pts, colour, width=26, passes=3, crayon=14, pressure=0.85, back=True, opacity=0.92, spread=1.0):+ """fill a band along a path with strokes that follow it (rainbow arcs, roads, a kite tail, smoke):+ `passes` strokes side by side across `width`, each starting and stopping a bit early or late"""+ P = np.asarray(pts, np.float32)+ tx, ty = np.gradient(P[:, 0]), np.gradient(P[:, 1]); tl = np.hypot(tx, ty) + 1e-6+ nx, ny = -ty / tl, tx / tl+ tip = self._tip(crayon)+ out = []+ n = len(P)+ for k in range(passes):+ o = ((k + 0.5) / passes - 0.5) * (width - crayon * 0.6) * spread + self.rng.normal(0, 1.5)+ a, b = int(self.rng.integers(0, max(1, n // 25) + 1)), n - int(self.rng.integers(0, max(1, n // 25) + 1))+ q = P[a:b] + np.stack([nx[a:b], ny[a:b]], 1) * (o + fbm1d(b - a, 20, 2, self._seed())[:, None] * 1.6)+ if back and k % 2: q = q[::-1]+ out.append((q, pressure * self.rng.uniform(0.88, 1.06), k % 2, tip))+ cover, box = self._render(out)+ if cover is not None: self.deposit(cover, box, colour, opacity)++ # ------------------------------------------------------------ lines+ def line(self, pts, colour, width=9, pressure=0.9, closed=False, overlap=0.07, wobble=1.2, opacity=0.95, lift=True,+ avoid=None):+ """one crayon line: pressure swells and fades along it (lands heavy, lifts light). closed=True draws a shape+ the way a child does: round once, then the end runs on past the start and misses it by a few px.+ avoid: a mask the line stops at (a hill line that goes behind the people instead of through their faces)"""+ P = np.asarray(pts, np.float32)+ if closed:+ seg = np.hypot(*np.diff(np.vstack([P, P[:1]]), axis=0).T)+ k = max(2, int(len(P) * overlap * self.rng.uniform(0.6, 1.4)))+ drift = np.linspace(0, 1, k)[:, None] * self.rng.normal(0, 4.0, 2)[None]+ P = np.vstack([P, P[:1], P[1:k + 1] + drift[:len(P[1:k + 1])]])+ if wobble:+ P = self.wobble(P, wobble, closed=False, step=5, scale=10)+ n = len(P)+ if n < 2: return+ prs = pressure * (0.86 + 0.28 * fbm1d(n, max(4, n / 4), 2, self._seed()))+ if lift:+ t = np.linspace(0, 1, n)+ prs = prs * np.clip(0.75 + 0.25 * np.minimum(t / 0.06, 1), 0, 1.1) * np.clip(1 - 0.35 * smoothstep(0.86, 1, t), 0, 1)+ tip = self._tip(width, worn=0.25)+ out = []+ step = 8+ for i in range(0, n - 1, step):+ out.append((P[i:i + step + 1], float(prs[i]), 0, tip))+ cover, box = self._render(out)+ if cover is None: return+ if avoid is not None:+ x0, y0, x1, y1 = box+ cover = cover * (1 - np.clip(np.asarray(avoid, np.float32)[y0:y1, x0:x1], 0, 1))+ self.deposit(cover, box, colour, opacity, soft=0.5)++ def stroke_mask(self, pts, width, closed=False):+ """a mask of a polyline drawn `width` px wide (to keep fills off arms, legs, stems and strings)"""+ im = Image.new('L', (self.W, self.H), 0)+ P = [tuple(map(float, q)) for q in np.asarray(pts, np.float32)]+ if closed: P = P + P[:1]+ ImageDraw.Draw(im).line(P, fill=255, width=int(width), joint='curve')+ return np.asarray(im, np.float32) / 255++ def grow(self, mask, px):+ """dilate a mask by about `px` pixels"""+ return (blur(np.asarray(mask, np.float32), max(0.8, px * 0.5)) > 0.08).astype(np.float32)++ def lines(self, paths, colour, **kw):+ for p in paths: self.line(p, colour, **kw)++ def dab(self, x, y, r, colour, pressure=1.0, turns=None):+ """a pressed-in dot (eyes, buttons, seeds): a tight spiral ground into the paper"""+ turns = turns or max(1.5, r / 4)+ t = np.linspace(0, 1, int(turns * 24))+ ang = t * turns * 2 * np.pi + self.rng.uniform(0, 6.3)+ rr = r * (0.25 + 0.6 * t)+ pts = np.stack([x + rr * np.cos(ang), y + rr * 0.9 * np.sin(ang)], 1)+ tip = self._tip(max(4, r * 0.8), worn=0.15)+ cover, box = self._render([(pts, pressure, 0, tip), (pts[::-1], pressure * 0.9, 1, tip)])+ if cover is not None: self.deposit(cover, box, colour, 0.96, soft=0.5)++ def burnish(self, mask, strength=0.8):+ """press hard and rub: the wax already there is pushed down into the pits of the tooth, the white specks close+ up, the colour goes deep and the surface turns waxy and shiny (heavy sunglasses, a ball, a roof)"""+ m = np.clip(np.asarray(mask, np.float32), 0, 1)+ ys, xs = np.nonzero(m > 0.01)+ if len(xs) == 0: return+ x0, x1, y0, y1 = max(0, xs.min() - 12), min(self.W, xs.max() + 13), max(0, ys.min() - 12), min(self.H, ys.max() + 13)+ sl = (slice(y0, y1), slice(x0, x1))+ mm = m[sl]+ w = np.clip(self.wax[sl], 0, 1)+ avg = np.stack([blur(self.img[sl][..., k] * w, 3) for k in range(3)], -1) / (blur(w, 3)[..., None] + 1e-4)+ fill = (mm * strength * smoothstep(0.05, 0.3, blur(w, 3)))[..., None]+ self.img[sl] = self.img[sl] * (1 - fill) + np.clip(avg * 0.96, 0, 1) * fill+ self.wax[sl] += mm * strength * 0.8++ # ------------------------------------------------------------ writing+ def write(self, s, x, y, size, colours, width=None, pressure=0.95, tilt=9, jumble=0.12, spacing=0.92, anchor='m'):+ """write like a six-year-old: each character re-drawn with a fat round crayon over the centre line of a thin+ glyph, every one tilted (+-tilt deg), resized and lifted off the baseline (jumble), in its own colour.+ colours: one colour or a list cycled per character; anchor 'l' / 'm' / 'r' on x; y is the middle of the line"""+ if isinstance(colours, str) or (hasattr(colours, 'shape') and np.asarray(colours).ndim == 1):+ colours = [colours]+ width = width or max(5, size * 0.068)+ chars = list(s)+ sizes = [size * (1 + self.rng.normal(0, jumble)) for ch in chars]+ adv = [_thin_font(sz).getlength(ch) * spacing + width * 0.6 for ch, sz in zip(chars, sizes)]+ tot = sum(adv)+ cx = x - tot * {'l': 0, 'm': 0.5, 'r': 1}[anchor]+ for i, (ch, sz) in enumerate(zip(chars, sizes)):+ if ch.strip():+ self._glyph(ch, cx + adv[i] / 2, y + self.rng.normal(0, size * jumble * 0.6), sz,+ colours[i % len(colours)], width, pressure, self.rng.normal(0, tilt))+ cx += adv[i]++ def _glyph(self, ch, cx, cy, size, colour, width, pressure, rot):+ font = _thin_font(size)+ pad = int(size * 0.5 + width * 2)+ S = int(size) + 2 * pad+ im = Image.new('L', (S, S), 0)+ ImageDraw.Draw(im).text((S / 2, S / 2), ch, font=font, fill=255, anchor='mm')+ im = im.rotate(rot, resample=Image.BICUBIC)+ g = np.asarray(im, np.float32) / 255+ # warp the glyph with a slow hand wobble+ n1, n2 = noise2d(S, S, size * 0.55, 2, self._seed()), noise2d(S, S, size * 0.55, 2, self._seed())+ amp = size * 0.045+ yy, xx = np.mgrid[0:S, 0:S].astype(np.float32)+ sx = np.clip(xx + (n1 - 0.5) * 2 * amp, 0, S - 1.001); sy = np.clip(yy + (n2 - 0.5) * 2 * amp, 0, S - 1.001)+ ix, iy = sx.astype(int), sy.astype(int); fx, fy = sx - ix, sy - iy+ g = (g[iy, ix] * (1 - fx) * (1 - fy) + g[iy, ix + 1] * fx * (1 - fy) + g[iy + 1, ix] * (1 - fx) * fy + g[iy + 1, ix + 1] * fx * fy)+ core = _thin((g > 0.4)).astype(np.float32)+ # fat round crayon over the centre line: dilate with a disc+ r = width / 2+ out = core.copy()+ R = int(np.ceil(r))+ for dy in range(-R, R + 1):+ for dx in range(-R, R + 1):+ if dx * dx + dy * dy <= r * r and (dx or dy):+ np.maximum(out, shift(core, dx, dy), out=out)+ out = blur(out, 0.8)+ # streaks along a random stroke direction + pressure patches+ a = self.rng.uniform(0, np.pi)+ proj = (xx * np.cos(a) + yy * np.sin(a)) - (xx * np.cos(a) + yy * np.sin(a)).min()+ st = fbm1d(int(proj.max()) + 2, 4, 2, self._seed())+ streak = 0.84 + 0.16 * st[proj.astype(int)]+ cov = out * streak * (0.8 + 0.25 * noise2d(S, S, 18, 2, self._seed())) * pressure+ x0, y0 = int(cx) - S // 2, int(cy) - S // 2+ X0, Y0, X1, Y1 = max(0, x0), max(0, y0), min(self.W, x0 + S), min(self.H, y0 + S)+ if X1 <= X0 or Y1 <= Y0: return+ self.deposit(cov[Y0 - y0:Y1 - y0, X0 - x0:X1 - x0], (X0, Y0, X1, Y1), colour, 0.95, soft=0)++ # ------------------------------------------------------------ the table top: crumbs and crayons+ def crumbs(self, x0, y0, x1, y1, colours, n=40, size=(2, 6)):+ """flakes of wax rubbed off the crayon, lying on the paper (they catch the light and cast a shadow)"""+ if isinstance(colours, str): colours = [colours]+ for _ in range(n):+ cx, cy = self.rng.uniform(x0, x1), self.rng.uniform(y0, y1)+ r = self.rng.uniform(*size)+ m = self.mask(blob_pts(cx, cy, r, r * self.rng.uniform(0.5, 1.0), rough=0.3, n=12, seed=self._seed(),+ rot=self.rng.uniform(0, 6.3)), ss=2)+ col = _c(colours[int(self.rng.integers(len(colours)))])+ self.img = self.img * (1 - m[..., None]) + col * m[..., None] * (0.92 + 0.08 * self.tooth[..., None])+ self.crumb = np.maximum(self.crumb, m * r * 0.5)++ def stick(self, x, y, angle, colour, length=360, radius=22, wrapper=True, wrap=(0.16, 0.86), tip='worn',+ band=None, peel=0.0, label=True):+ """a real crayon lying on the paper, centred on (x, y), pointing along `angle` (deg, tip end).+ tip: 'worn' (a cone ground flat on one side), 'new' (a sharp cone) or 'broken' (a jagged snapped end);+ wrapper: paper sleeve between wrap=(t0, t1) of the length; band: wrapper print colour; peel: 0..1 of the+ sleeve torn off from the tip end; label: print the sleeve (rules, wavy bands, a line of pseudo-lettering,+ no brand). A real crayon (~8 mm) on an A4 sheet 1920 px wide would be radius ~26 px; 22 keeps it from crowding+ the drawing. Rendered with its own shading (matte wax, satin sheen, paper sleeve) and a soft shadow at+ composite time."""+ self.over.append(dict(x=x, y=y, a=np.radians(angle), col=_c(colour), L=length, r=radius, wrapper=wrapper,+ wrap=wrap, tip=tip, band=_c(band) if band is not None else None, peel=peel,+ label=label, seed=self._seed()))++ def _draw_stick(self, img, s, light):+ H, W = self.H, self.W+ ca, sa = np.cos(s['a']), np.sin(s['a'])+ L, R = s['L'], s['r']+ pad = int(L / 2 + R * 3 + 30)+ x0, y0 = max(0, int(s['x'] - pad)), max(0, int(s['y'] - pad))+ x1, y1 = min(W, int(s['x'] + pad)), min(H, int(s['y'] + pad))+ if x1 <= x0 or y1 <= y0: return img+ XX, YY = self.XX[y0:y1, x0:x1] - s['x'], self.YY[y0:y1, x0:x1] - s['y']+ al = XX * ca + YY * sa # px along the stick, tip end positive+ t = al / L + 0.5 # 0 = butt end .. 1 = tip end+ d = -XX * sa + YY * ca # px across the stick+ # radius along the stick: a cone at the tip, worn flat on one side, or a snapped end+ rad = np.full(t.shape, float(R), np.float32)+ cone = 0.15 # the last 15 % of the stick is the tip+ if s['tip'] in ('new', 'worn'):+ k = np.clip((t - (1 - cone)) / cone, 0, 1)+ rad = R * (1 - k * (0.9 if s['tip'] == 'new' else 0.62))+ end = np.ones_like(t, bool)+ if s['tip'] == 'broken':+ jag = fbm1d(64, 5, 3, s['seed'])+ idx = np.clip(((d / R + 1) * 0.5 * 63).astype(int), 0, 63)+ end = t < 1 - 0.03 * (1.2 + jag[idx])+ butt = np.sqrt(np.clip(1 - (d / R) ** 2, 0, 1)) * 2.5 # the butt end is slightly domed+ inside = (np.abs(d) < rad) & (al > -L / 2 - butt) & (t < 1.0) & end+ m = blur(inside.astype(np.float32), 0.7)+ sl = (slice(y0, y1), slice(x0, x1))+ sh = blur(shift(m, 7, 10), 6) * 0.45 + blur(shift(m, 2, 3), 1.5) * 0.25 # soft shadow + contact shadow+ img[sl] *= (1 - np.clip(sh, 0, 0.6)[..., None])+ u = np.clip(d / np.maximum(rad, 1e-3), -1, 1)+ nz = np.sqrt(np.clip(1 - u * u, 0, 1))+ N = np.stack([-sa * u, ca * u, nz], -1)+ if s['tip'] == 'worn': # the flat wear facet near the tip, facing up and forward+ f = (t > 1 - cone * 0.9) & (u > -0.2)+ N[f] = np.array([0.35 * ca, 0.35 * sa, 0.94]) / np.linalg.norm([0.35, 0.94])+ Ld = np.asarray(light, np.float32); Ld /= np.linalg.norm(Ld)+ diff = np.clip(N @ Ld, 0, 1)+ Hh = Ld + np.array([0, 0, 1], np.float32); Hh /= np.linalg.norm(Hh)+ spec = np.clip(N @ Hh, 0, 1) ** 12+ out = s['col'] * (0.45 + 0.62 * diff[..., None]) + 0.13 * spec[..., None] # matte wax, satin sheen+ rng = np.random.default_rng(s['seed'])+ if s['wrapper']:+ w0, w1 = s['wrap']+ peel_to = w1 - (w1 - w0) * s['peel']+ ragged = 0.015 * fbm1d(64, 8, 3, s['seed'] + 1)[np.clip(((u + 1) * 31.5).astype(int), 0, 63)]+ onw = (t > w0) & (t < peel_to + ragged) & inside+ tt = (t - w0) / (w1 - w0)+ base = s['band'] if s['band'] is not None else np.clip(s['col'] * 0.9, 0, 1)+ ink = np.clip(s['col'] * 0.25, 0, 1)+ wc = np.ones(t.shape + (3,), np.float32) * base+ if s['label']:+ rules = np.zeros(t.shape, bool)+ for r0 in (0.05, 0.085, 0.915, 0.95):+ rules |= np.abs(tt - r0) < 0.008+ wave = (np.abs(((tt * 22 + 0.18 * np.sin(u * 3.0)) % 1.0) - 0.5) < 0.07) & (((tt > 0.13) & (tt < 0.25)) | ((tt > 0.75) & (tt < 0.87)))+ lab = (tt > 0.29) & (tt < 0.71)+ wc = np.where(lab[..., None], np.clip(base * 0.35 + 0.66, 0, 1), wc)+ # one line of pseudo-lettering along the label (no real words)+ ls = tt * (w1 - w0) * L+ word = fbm1d(int((w1 - w0) * L) + 4, 30, 2, s['seed'] + 3)+ inword = word[np.clip(ls.astype(int), 0, len(word) - 1)] > -0.25+ glyph = ((ls / 6.5) % 1.0) < 0.62+ txt = lab & (tt > 0.34) & (tt < 0.66) & (np.abs(u - 0.05) < 0.2) & inword & glyph+ wc = np.where((rules | wave | txt)[..., None], ink, wc)+ wrap_col = wc * (0.5 + 0.56 * diff[..., None]) + 0.03 * spec[..., None]+ out = np.where(onw[..., None], wrap_col, out)+ # torn edge of the sleeve: a thin light lip, and scrape marks on the bare wax beyond it+ lip = onw & ~shift(onw.astype(np.float32), int(round(-ca * 2)), int(round(-sa * 2))).astype(bool)+ out = np.where(lip[..., None], np.clip(out * 0.8 + 0.25, 0, 1), out)+ if s['tip'] == 'broken': # the snapped face is rough and a bit lighter+ face = inside & ~(t < 1 - 0.03 * 3.4)+ out = np.where(face[..., None], np.clip(out * (1.04 + 0.1 * rng.random(t.shape))[..., None], 0, 1), out)+ scr = 0.05 * fbm1d(256, 3, 2, s['seed'] + 2)[np.clip(((u + 1) * 127.5).astype(int), 0, 255)]+ out = np.clip(out * (1 + scr[..., None]), 0, 1)+ img[sl] = img[sl] * (1 - m[..., None]) + out * m[..., None]+ return img++ # ------------------------------------------------------------ output+ def composite(self, light=(-0.55, -0.62, 0.56)):+ """light the paper and the wax as one height field (a raking light from the top left), add the wax sheen,+ then lay the crumbs and the crayons on top"""+ h = self.relief * 0.65 + blur(np.clip(self.wax, 0, 1.6), 1.6) * 0.55 + self.crumb+ n = height_normals(h)+ Ld = np.asarray(light, np.float32); Ld /= np.linalg.norm(Ld)+ diff = n @ Ld+ shade = 1 + 0.55 * (diff - Ld[2])+ Hh = Ld + np.array([0, 0, 1], np.float32); Hh /= np.linalg.norm(Hh)+ spec = np.clip(n @ Hh, 0, 1) ** 40 * smoothstep(0.6, 1.4, self.wax) * 0.10+ img = self.img * shade[..., None] + spec[..., None]+ if self.crumb.any(): # crumbs cast a small shadow+ cs = blur(shift((self.crumb > 0).astype(np.float32), 2, 3), 1.5) * (self.crumb <= 0)+ img = img * (1 - 0.35 * cs[..., None])+ for s in self.over:+ img = self._draw_stick(img, s, light)+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ """snapshot for the draw-on animation"""+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/crt.py b/lib/crt.pynew file mode 100644index 0000000..b6fd764--- /dev/null+++ b/lib/crt.py@@ -0,0 +1,1050 @@+"""crt — a green-screen CRT video terminal showing ASCII art in glowing phosphor (numpy + Pillow only).++Model:+ memory a character terminal: `cols` x `rows` cells of character memory, each with an intensity attribute+ (dim / normal / bold), reverse video and underline. A line can be double-width, or the top / bottom+ half of a double-height line, as on the video terminals of the late 1970s. Nothing is ever drawn+ between cells: everything on the screen is a character.+ ROM the character generator: 5 x 7 dot glyphs (lower case with two descender rows) in a 7 x 10 dot cell,+ plus a graphics set: box drawing, the five 'scan line' bars used for plotting (one scan line each, at+ five heights in the cell), block eighths, shades, degree sign, triangles, arrows.+ art pictures are painted into a hidden map at dot resolution (7 x 10 samples per cell): regions with a+ *material* (which characters and intensities it may use) and a *tone* (how brightly it should glow),+ and strokes. `compose()` picks every cell's character: interior cells from the material's ramp by+ tone (error diffusion inside the material, so ramps blend instead of banding), silhouette cells by the+ direction and position of the edge in real pixels ( _ . - ' / \\ ( ) | ), stroke cells by the+ stroke's direction. On a screen dense means *bright*: a storm cloud is sparse and dim, the sun dense+ and bold -- the opposite of ink on paper.+ beam every character row is 10 scan lines. On each scan line the video signal is the row of dots, every+ dot stretched by half a dot (so one-dot verticals stay visible) and smeared by the video amplifier's+ limited bandwidth (soft rising edge, a short trail to the right). The beam lays down a gaussian spot+ whose size grows with the current: dim lines are thin with dark gaps between them, bright ones swell+ and close the gaps (blooming). The brightness control is up a little, so the whole raster glows+ faintly and its scan lines show even where nothing is written.+ phosphor P1 green (or P3 amber, P4 white). Emission saturates the way a camera sees it: bold cores go pale+ mint. Persistence: whatever moved in the last frames is still fading (`trail`). Burn-in: a status+ line that sat in one place for years has worn the phosphor (`burn`).+ tube the raster is bent by the curved faceplate (barrel: the edges bow out, the corners pull in) and+ falls off toward the edges; light scattered in the thick glass gives bloom and a wide halation halo.+ The unlit face is dark grey-green glass with the room in it (a window, a ceiling sheen) and the bezel's+ shadow along the top.+ case a moulded putty-coloured plastic bezel: stippled texture, a chamfered opening whose slopes catch the+ green spill of the screen, a mould seam, a power LED and two thumbwheels.++ from crt import CRTTerminal+ t = CRTTerminal(1920, 1080, seed=3, cols=120, rows=36)+ t.power()+ t.write(0, 0, 'wx@lookout:~$ ', 'bold'); t.write(14, 0, 'forecast --today')+ t.material('sun', [' ', '.', ':', '+', '*', '#', '@'], attrs=['dim', 'dim', 'normal', 'normal', 'bold', 'bold', 'bold'])+ t.fill(t.circle(20, 12, 6), 'sun', t.sphere_tone(20, 12, 6))+ t.compose(); t.reveal()+ t.cursor(14, 1)+ t.save('out.jpg')+Cell coordinates are (col, row), floats allowed; (c, r) is the top-left corner of cell (c, r).+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, noise2d, smoothstep, spline, height_normals, load_font, fbm1d+++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)+++# ================================================================ character generator ROM+# 5 x 7 glyphs ('#' = dot). Rows 7-8, when given, are descenders. Placed at dots 1-5 of a 7-dot cell,+# rows 1-9 of a 10-line cell (row 0 is the gap between text lines).+_FONT = {+ ' ': ['.....'] * 7,+ '!': ['..#..', '..#..', '..#..', '..#..', '..#..', '.....', '..#..'],+ '"': ['.#.#.', '.#.#.', '.....', '.....', '.....', '.....', '.....'],+ '#': ['.#.#.', '.#.#.', '#####', '.#.#.', '#####', '.#.#.', '.#.#.'],+ '$': ['..#..', '.####', '#.#..', '.###.', '..#.#', '####.', '..#..'],+ '%': ['##...', '##..#', '...#.', '..#..', '.#...', '#..##', '...##'],+ '&': ['.##..', '#..#.', '#.#..', '.#...', '#.#.#', '#..#.', '.##.#'],+ "'": ['..#..', '..#..', '.....', '.....', '.....', '.....', '.....'],+ '(': ['...#.', '..#..', '.#...', '.#...', '.#...', '..#..', '...#.'],+ ')': ['.#...', '..#..', '...#.', '...#.', '...#.', '..#..', '.#...'],+ '*': ['.....', '..#..', '#.#.#', '.###.', '#.#.#', '..#..', '.....'],+ '+': ['.....', '..#..', '..#..', '#####', '..#..', '..#..', '.....'],+ ',': ['.....', '.....', '.....', '.....', '.....', '..#..', '..#..', '.#...'],+ '-': ['.....', '.....', '.....', '#####', '.....', '.....', '.....'],+ '.': ['.....', '.....', '.....', '.....', '.....', '.....', '..#..'],+ '0': ['.###.', '#...#', '#..##', '#.#.#', '##..#', '#...#', '.###.'],+ '1': ['..#..', '.##..', '..#..', '..#..', '..#..', '..#..', '.###.'],+ '2': ['.###.', '#...#', '....#', '...#.', '..#..', '.#...', '#####'],+ '3': ['#####', '...#.', '..#..', '...#.', '....#', '#...#', '.###.'],+ '4': ['...#.', '..##.', '.#.#.', '#..#.', '#####', '...#.', '...#.'],+ '5': ['#####', '#....', '####.', '....#', '....#', '#...#', '.###.'],+ '6': ['..##.', '.#...', '#....', '####.', '#...#', '#...#', '.###.'],+ '7': ['#####', '....#', '...#.', '..#..', '.#...', '.#...', '.#...'],+ '8': ['.###.', '#...#', '#...#', '.###.', '#...#', '#...#', '.###.'],+ '9': ['.###.', '#...#', '#...#', '.####', '....#', '...#.', '.##..'],+ ':': ['.....', '.....', '..#..', '.....', '.....', '..#..', '.....'],+ ';': ['.....', '.....', '..#..', '.....', '.....', '..#..', '..#..', '.#...'],+ '<': ['...#.', '..#..', '.#...', '#....', '.#...', '..#..', '...#.'],+ '=': ['.....', '.....', '#####', '.....', '#####', '.....', '.....'],+ '>': ['.#...', '..#..', '...#.', '....#', '...#.', '..#..', '.#...'],+ '?': ['.###.', '#...#', '....#', '...#.', '..#..', '.....', '..#..'],+ '@': ['.###.', '#...#', '....#', '.##.#', '#.#.#', '#.#.#', '.###.'],+ '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': ['#####', '....#', '...#.', '..#..', '.#...', '#....', '#####'],+ '[': ['.###.', '.#...', '.#...', '.#...', '.#...', '.#...', '.###.'],+ ']': ['.###.', '...#.', '...#.', '...#.', '...#.', '...#.', '.###.'],+ '^': ['..#..', '.#.#.', '#...#', '.....', '.....', '.....', '.....'],+ '`': ['.#...', '..#..', '.....', '.....', '.....', '.....', '.....'],+ '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': ['.....', '.....', '#####', '...#.', '..#..', '.#...', '#####'],+ '{': ['...#.', '..#..', '..#..', '.#...', '..#..', '..#..', '...#.'],+ '}': ['.#...', '..#..', '..#..', '...#.', '..#..', '..#..', '.#...'],+ '~': ['.....', '.....', '.#...', '#.#.#', '...#.', '.....', '.....'],+ '°': ['.#...', '#.#..', '.#...', '.....', '.....', '.....', '.....'],+ '·': ['.....', '.....', '.....', '..#..', '.....', '.....', '.....'],+ '▲': ['.....', '.....', '..#..', '.###.', '.###.', '#####', '.....'],+ '▼': ['.....', '#####', '.###.', '.###.', '..#..', '.....', '.....'],+ '◆': ['.....', '..#..', '.###.', '#####', '.###.', '..#..', '.....'],+ '→': ['.....', '..#..', '...#.', '#####', '...#.', '..#..', '.....'],+ '←': ['.....', '..#..', '.#...', '#####', '.#...', '..#..', '.....'],+ '↑': ['..#..', '.###.', '#.#.#', '..#..', '..#..', '..#..', '..#..'],+ '↓': ['..#..', '..#..', '..#..', '..#..', '#.#.#', '.###.', '..#..'],+ '↗': ['..###', '...##', '..#.#', '.#...', '#....', '.....', '.....'],+ '↘': ['.....', '.....', '#....', '.#...', '..#.#', '...##', '..###'],+}+++def _build_rom():+ rom = {}+ for ch, rows in _FONT.items():+ a = np.zeros((10, 7), np.uint8)+ for g, line in enumerate(rows):+ assert len(line) == 5, ch+ for j, px in enumerate(line):+ if px == '#': a[g + 1, j + 1] = 1+ rom[ch] = a++ def cell():+ return np.zeros((10, 7), np.uint8)+ # art-friendly full-cell strokes: verticals and diagonals run the whole cell height, '_' the whole width,+ # so stacked characters join into lines+ a = cell(); a[:, 3] = 1; rom['|'] = a+ a = cell()+ for r in range(10): a[r, 5 - r // 2] = 1+ rom['/'] = a; rom['\\'] = a[:, ::-1].copy()+ a = cell(); a[9, :] = 1; rom['_'] = a+ # box drawing: horizontals on line 4, verticals on dot 3, meeting in the cell centre+ H, V = 4, 3++ def bx(l, r, u, d):+ a = cell()+ if l: a[H, :V + 1] = 1+ if r: a[H, V:] = 1+ if u: a[:H + 1, V] = 1+ if d: a[H:, V] = 1+ return a+ for ch, k in zip('─│┌┐└┘├┤┬┴┼', [(1, 1, 0, 0), (0, 0, 1, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 1, 1, 0), (1, 0, 1, 0),+ (0, 1, 1, 1), (1, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]):+ rom[ch] = bx(*k)+ # the five scan-line bars of the plotting set (scan 1, 3, 5, 7, 9)+ for ch, r in zip('⎺⎻─⎼⎽', (0, 2, 4, 6, 8)):+ a = cell(); a[r, :] = 1; rom[ch] = a+ for ch, n in zip('▁▂▃▄▅▆▇█', (1, 2, 4, 5, 6, 8, 9, 10)):+ a = cell(); a[10 - n:, :] = 1; rom[ch] = a+ yy, xx = np.mgrid[0:10, 0:7]+ rom['░'] = ((yy % 2 == 0) & (xx % 2 == 0)).astype(np.uint8)+ rom['▒'] = ((yy + xx) % 2 == 0).astype(np.uint8)+ rom['▓'] = (~((yy % 2 == 1) & (xx % 2 == 1))).astype(np.uint8)+ chars = list(rom.keys())+ return chars, np.stack([rom[c] for c in chars]), {c: i for i, c in enumerate(chars)}+++ROM_CHARS, ROM, ROM_INDEX = _build_rom()+SCAN = '⎽⎼─⎻⎺' # plotting bars, lowest to highest+EIGHTHS = ' ▁▂▃▄▅▆▇█'+LEVELS = {'dim': 0.40, 'normal': 0.70, 'bold': 1.0}+PHOSPHORS = { # emission tint (how fast each channel saturates) and the unlit face colour+ 'green': dict(tint=(0.30, 1.0, 0.40), face=(0.036, 0.047, 0.042)), # P1+ 'amber': dict(tint=(1.0, 0.60, 0.14), face=(0.048, 0.042, 0.034)), # P3+ 'white': dict(tint=(0.88, 0.94, 1.0), face=(0.042, 0.045, 0.048)), # P4+}+PUTTY = '#c9c0ac' # the bezel plastic+++def _attr(a):+ """'bold', 'dim+rev', 'normal+ul' ... -> (level, reverse, underline)"""+ parts = (a or 'normal').split('+')+ lvl = LEVELS['normal']+ for p in parts:+ if p in LEVELS: lvl = LEVELS[p]+ return lvl, 'rev' in parts, 'ul' in parts+++class CRTTerminal:+ def __init__(self, W=1920, H=1080, seed=0, cols=120, rows=36, phosphor='green',+ opening=(88, 60, 1832, 958), radius=62, raster=(0.955, 0.93), curve=0.065,+ bezel=PUTTY):+ """opening: the hole in the bezel (glass), px; raster: the undistorted raster size as a fraction of the+ opening; curve: radial barrel strength (the raster's corners pull in by about curve x the half-width)"""+ self.W, self.H, self.cols, self.rows = W, H, cols, rows+ self.rng = np.random.default_rng(seed)+ self.seed = seed+ self.ph = PHOSPHORS[phosphor]+ self.opening, self.radius = opening, radius+ x0, y0, x1, y1 = opening+ self.ocx, self.ocy = (x0 + x1) / 2, (y0 + y1) / 2+ self.rw, self.rh = (x1 - x0) * raster[0], (y1 - y0) * raster[1] # raster, undistorted, 1x px+ self.curve = curve+ self.pad = 1.0 # raster margin round the text, cells+ self.cw = self.rw / (cols + 2 * self.pad) # cell size, px (undistorted)+ self.ch = self.rh / (rows + 2 * self.pad)+ # ---- character memory+ self.text = np.full((rows, cols), ' ', dtype='<U1')+ self.lvl = np.full((rows, cols), LEVELS['normal'], np.float32)+ self.rev = np.zeros((rows, cols), bool)+ self.ul = np.zeros((rows, cols), bool)+ self.mode = [''] * rows # '', 'dw', 'dht' (double height top), 'dhb'+ self.glow = np.zeros((rows * 10, cols * 7), np.float32) # afterglow (persistence) dots+ self.worn = np.zeros((rows * 10, cols * 7), np.float32) # burn-in, 0..1 loss of efficiency+ self.cur = None+ self.on = False+ self.brightness = 0.016 # raster floor: the brightness knob is up a little+ self.tears = []+ # ---- hidden art map at dot resolution+ SY, SX = rows * 10, cols * 7+ self.inst = np.zeros((SY, SX), np.int32)+ self.tone = np.zeros((SY, SX), np.float32)+ self.dirx = np.zeros((SY, SX), np.float32)+ self.diry = np.zeros((SY, SX), np.float32)+ self.items = [None]+ self.materials = {}+ self.art_text = np.full((rows, cols), '', dtype='<U1')+ self.art_lvl = np.zeros((rows, cols), np.float32)+ self.stages = []+ self._case = None+ self._geom = None++ # ================================================================ terminal memory+ def write(self, col, row, s, attr='normal'):+ """put text into character memory at (col, row); attr: 'dim' | 'normal' | 'bold', '+rev', '+ul'"""+ lvl, rev, ul = _attr(attr)+ r = int(row)+ if not 0 <= r < self.rows: return+ step = 2 if self.mode[r] else 1+ for i, chx in enumerate(s):+ c = int(col) + i * step+ if not 0 <= c < self.cols: continue+ self.text[r, c] = chx if chx in ROM_INDEX else '?'+ self.lvl[r, c], self.rev[r, c], self.ul[r, c] = lvl, rev, ul++ def clear(self, c0=0, r0=0, c1=None, r1=None):+ c1 = self.cols if c1 is None else c1; r1 = self.rows if r1 is None else r1+ self.text[r0:r1, c0:c1] = ' '; self.rev[r0:r1, c0:c1] = False; self.ul[r0:r1, c0:c1] = False++ def big(self, col, row, s, attr='bold'):+ """a double-height, double-width line: rows `row` and `row + 1`; every character takes two columns"""+ self.mode[row], self.mode[row + 1] = 'dht', 'dhb'+ self.write(col, row, s, attr); self.write(col, row + 1, s, attr)++ def wide(self, col, row, s, attr='normal'):+ self.mode[row] = 'dw'+ self.write(col, row, s, attr)++ def cursor(self, col, row, shape='block'):+ self.cur = None if col is None else (int(col), int(row), shape)++ def hline(self, c0, c1, row, attr='dim', ch='─'):+ self.write(c0, row, ch * (c1 - c0 + 1), attr)++ def vline(self, col, r0, r1, attr='dim', ch='│'):+ for r in range(r0, r1 + 1): self.write(col, r, ch, attr)++ def box(self, c0, r0, c1, r1, attr='dim', title=None, title_attr='bold'):+ self.hline(c0 + 1, c1 - 1, r0, attr); self.hline(c0 + 1, c1 - 1, r1, attr)+ self.vline(c0, r0 + 1, r1 - 1, attr); self.vline(c1, r0 + 1, r1 - 1, attr)+ for (c, r), ch in zip([(c0, r0), (c1, r0), (c0, r1), (c1, r1)], '┌┐└┘'): self.write(c, r, ch, attr)+ if title:+ self.write(c0 + 2, r0, '┤', attr); self.write(c0 + 3, r0, ' ' + title + ' ', title_attr)+ self.write(c0 + 5 + len(title), r0, '├', attr)++ def trail(self, col, row, s, level=0.3):+ """afterglow: `s` was on screen at (col, row) a frame or two ago and is still fading (persistence).+ level: what is left of a bold character (0.3 one frame back, 0.1 two frames back)"""+ for i, chx in enumerate(s):+ c, r = int(col) + i, int(row)+ if not (0 <= c < self.cols and 0 <= r < self.rows) or chx == ' ': continue+ g = ROM[ROM_INDEX.get(chx, ROM_INDEX['?'])].astype(np.float32) * level+ sl = self.glow[r * 10:r * 10 + 10, c * 7:c * 7 + 7]+ np.maximum(sl, g, out=sl)++ def burn(self, col, row, s, depth=0.3):+ """burn-in: `s` sat at (col, row) for years and wore the phosphor (less light wherever its dots were)"""+ for i, chx in enumerate(s):+ c, r = int(col) + i, int(row)+ if not (0 <= c < self.cols and 0 <= r < self.rows) or chx == ' ': continue+ g = ROM[ROM_INDEX.get(chx, ROM_INDEX['?'])].astype(np.float32) * depth+ sl = self.worn[r * 10:r * 10 + 10, c * 7:c * 7 + 7]+ np.maximum(sl, g, out=sl)++ def tear(self, row, dx=6.0, lines=3):+ """a horizontal-sync slip: from scan line `row * 10 + 5` the beam starts `dx` px late for `lines` lines"""+ self.tears.append((float(row), float(dx), int(lines)))++ def power(self, on=True):+ self.on = on++ def listing(self, path=None):+ s = '\n'.join(''.join(r).rstrip() for r in self.text)+ if path:+ with open(path, 'w') as f: f.write(s + '\n')+ return s++ # ================================================================ hidden art map+ def material(self, name, ramp, attrs=None, outline='round', group=None, edge=None, dither=0.12):+ """a glyph vocabulary for a kind of thing. ramp: characters from faint to bright, e.g. ' .:-=+*#%@';+ attrs: one intensity per ramp entry (default: dim for the faint third, normal, bold for the top);+ outline: 'round' (( ) at upright sides, / \\ on slopes), 'cloud' (( ) on every slope, _ . - ' on flat+ tops and bases), 'straight' (| / \\), or None (no silhouette characters, tone only);+ group: materials in the same group are not outlined against each other;+ edge: fixed intensity for outline characters (default: from the tone at the edge); dither: tone noise"""+ n = len(ramp)+ if attrs is None:+ attrs = ['dim' if i < n / 3 else 'normal' if i < 2 * n / 3 else 'bold' for i in range(n)]+ self.materials[name] = dict(ramp=list(ramp), lv=[LEVELS[a] for a in attrs], outline=outline,+ group=group or name, edge=edge, dither=dither)++ def _grid(self):+ if not hasattr(self, '_gx'):+ SY, SX = self.rows * 10, self.cols * 7+ self._gy = ((np.arange(SY, dtype=np.float32) + 0.5) / 10)[:, None]+ self._gx = ((np.arange(SX, dtype=np.float32) + 0.5) / 7)[None, :]+ return self._gx, self._gy++ def _poly_mask(self, pts):+ SY, SX = self.rows * 10, self.cols * 7+ im = Image.new('L', (SX * 2, SY * 2), 0)+ ImageDraw.Draw(im).polygon([(float(c) * 14, float(r) * 20) for c, r in pts], fill=255)+ return np.asarray(im.resize((SX, SY), Image.BILINEAR), np.float32) / 255++ def ellipse(self, col, row, rx, ry):+ """rx in columns, ry in rows"""+ gx, gy = self._grid()+ d = np.sqrt(((gx - col) / rx) ** 2 + ((gy - row) / ry) ** 2)+ return np.clip((1 - d) * min(rx * 7, ry * 10) * 0.5 + 0.5, 0, 1)++ def circle(self, col, row, r):+ """a round disc of radius r columns (made round in pixels: cells are tall)"""+ return self.ellipse(col, row, r, r * self.cw / self.ch)++ def poly(self, pts):+ return self._poly_mask(pts)++ def shape(self, pts, per=10):+ """smooth closed outline through control points (col, row)"""+ P = np.asarray(pts, np.float32)+ return self._poly_mask(spline(np.vstack([P, P[:2]]), per)[per:-per + 1] if len(P) > 2 else P)++ def rect(self, c0, r0, c1, r1):+ return self._poly_mask([(c0, r0), (c1, r0), (c1, r1), (c0, r1)])++ def sphere_tone(self, col, row, r, light=(-0.5, -0.7, 0.5), amb=0.15, rim=0.0):+ """lit-sphere tone for a disc of radius r columns centred at (col, row)"""+ gx, gy = self._grid()+ ry = r * self.cw / self.ch+ u, v = (gx - col) / r, (gy - row) / ry+ z = np.sqrt(np.clip(1 - u * u - v * v, 0, 1))+ L = np.array(light, np.float32); L /= np.linalg.norm(L)+ t = amb + (1 - amb) * np.clip(u * L[0] + v * L[1] + z * L[2], 0, 1)+ return np.clip(t + rim * (1 - z) ** 2, 0, 1)++ def radial_tone(self, col, row, r, t0=1.0, t1=0.0, power=1.0):+ gx, gy = self._grid()+ d = np.sqrt(((gx - col) / r) ** 2 + ((gy - row) / (r * self.cw / self.ch)) ** 2)+ return t1 + (t0 - t1) * np.clip(1 - d, 0, 1) ** power++ def ramp_tone(self, p0, p1, t0, t1):+ gx, gy = self._grid()+ d = np.array(p1, np.float32) - np.array(p0, np.float32)+ s = ((gx - p0[0]) * d[0] + (gy - p0[1]) * d[1]) / float(d @ d)+ return t0 + (t1 - t0) * np.clip(s, 0, 1)++ def fill(self, mask, material, tone=0.5):+ """paint a region (mask) with a material and tone (scalar or array); later fills cover earlier ones"""+ m = mask > 0.5+ self.items.append(dict(kind='fill', mat=material))+ k = len(self.items) - 1+ self.inst[m] = k+ t = np.broadcast_to(np.asarray(tone, np.float32), m.shape)+ self.tone[m] = t[m]+ return k++ def erase(self, mask):+ self.inst[mask > 0.5] = 0++ def stroke(self, pts, material, width=1.3, glyph=None, smooth=False, tone=0.7):+ """a line through (col, row) points; cells choose | / \\ _ - . ' by its direction, or `glyph` if given"""+ P = np.asarray(pts, np.float32)+ if smooth and len(P) > 2: P = spline(P, 10)+ SY, SX = self.rows * 10, self.cols * 7+ im = Image.new('L', (SX, SY), 0)+ dr = ImageDraw.Draw(im)+ dxy = np.zeros((SY, SX, 2), np.float32)+ for a, b in zip(P[:-1], P[1:]):+ seg = Image.new('L', (SX, SY), 0)+ ImageDraw.Draw(seg).line([(a[0] * 7, a[1] * 10), (b[0] * 7, b[1] * 10)], fill=255,+ width=max(1, int(round(width))))+ m = np.asarray(seg) > 0+ vx, vy = (b[0] - a[0]) * self.cw, (b[1] - a[1]) * self.ch # direction in real pixels+ n = np.hypot(vx, vy) + 1e-6+ dxy[m] = (vx / n, vy / n)+ dr.line([(a[0] * 7, a[1] * 10), (b[0] * 7, b[1] * 10)], fill=255, width=max(1, int(round(width))))+ m = np.asarray(im) > 0+ self.items.append(dict(kind='stroke', mat=material, glyph=glyph))+ k = len(self.items) - 1+ self.inst[m] = k+ self.tone[m] = tone+ self.dirx[m], self.diry[m] = dxy[m, 0], dxy[m, 1]+ return k++ def puffs(self, puffs, material, light=(-0.5, -0.75, 0.45), amb=0.12, base=None, base_dark=0.35, flat=1.2):+ """a cloud made of round puffs [(col, row, r), ...]: one silhouette, each puff lit like a ball.+ base=row: the cloud is cut flat there (use a whole row number so the base prints as '_'), and the+ `flat` rows above it are filled out to the cloud's width (a flat underside, no scallops); the underside+ is shaded darker by base_dark"""+ mask = np.zeros_like(self.tone)+ tone = np.zeros_like(self.tone)+ for c, r, rad in puffs:+ m = self.circle(c, r, rad)+ t = self.sphere_tone(c, r, rad, light, amb)+ tone = np.where(m > 0.5, t, tone) # later puffs sit in front+ mask = np.maximum(mask, m)+ if base is not None:+ gx, gy = self._grid()+ k = int(np.clip((base - flat) * 10, 0, mask.shape[0] - 1))+ k1 = int(np.clip(base * 10, k + 1, mask.shape[0]))+ prof = (mask[k:k1].max(axis=0) > 0.5).astype(np.float32)+ for op, w in ((np.maximum, 9), (np.minimum, 9)): # close small gaps between puffs+ pp = np.pad(prof, w, mode='edge')+ prof = op.reduce([pp[i:i + len(prof)] for i in range(2 * w + 1)])+ prof = prof[None, :]+ band = (gy >= base - flat) & (gy < base)+ tone = np.where(band & (mask < 0.5), np.max(tone[k - 3:k + 1], axis=0, keepdims=True), tone)+ mask = np.where(band, np.maximum(mask, prof), mask)+ tone = tone * (1 - base_dark * smoothstep(base - 3, base, gy))+ mask = mask * (gy < base)+ return self.fill(mask, material, tone)++ def put(self, col, row, s, attr='normal', opaque=False):+ """place characters straight into the art layer (stars, rain, little hand-drawn sprites); they appear+ with the art on `reveal`. Spaces are transparent unless opaque=True (then they blank what is under)"""+ lvl = _attr(attr)[0]+ for i, chx in enumerate(s):+ c, r = int(col) + i, int(row)+ if (chx == ' ' and not opaque) or not (0 <= c < self.cols and 0 <= r < self.rows): continue+ self.art_text[r, c] = chx if chx in ROM_INDEX else '?'+ self.art_lvl[r, c] = lvl++ def sprite(self, col, row, lines, attr='normal', attrs=None, swap=None):+ """a small piece of hand-made ASCII art (list of strings) into the art layer, top-left at (col, row).+ Spaces between a line's first and last character are opaque (a house hides the hill behind it).+ attrs: {character: attr} for single characters; swap: {character: replacement} (lit windows...)"""+ for j, line in enumerate(lines):+ s0, s1 = len(line) - len(line.lstrip()), len(line.rstrip())+ for i in range(s0, s1):+ chx = line[i]+ a = (attrs or {}).get(chx, attr)+ chx = (swap or {}).get(chx, chx)+ self.put(col + i, row + j, chx, a, opaque=True)++ def plot(self, col, row, w, h, xs, ys, xlim, ylim, attr='bold', glyphs=SCAN):+ """a curve plotted the terminal way: one scan-line bar per column, five heights per character row.+ Returns a function (x, y) -> (col, row) for labels"""+ xs, ys = np.asarray(xs, np.float32), np.asarray(ys, np.float32)+ n = len(glyphs)+ for c in range(int(col), int(col + w)):+ x = xlim[0] + (c + 0.5 - col) / w * (xlim[1] - xlim[0])+ if x < xs.min() or x > xs.max(): continue+ y = float(np.interp(x, xs, ys))+ lev = int(np.clip(np.round((y - ylim[0]) / (ylim[1] - ylim[0]) * (h * n - 1)), 0, h * n - 1))+ self.write(c, row + h - 1 - lev // n, glyphs[lev % n], attr)++ def at(x, y):+ return (col + (x - xlim[0]) / (xlim[1] - xlim[0]) * w,+ row + h - 1 - (y - ylim[0]) / (ylim[1] - ylim[0]) * (h - 0.2))+ return at++ def bars(self, col, row, h, values, vmax, attr='normal'):+ """a column of block characters per value (eighths of a row), standing on row + h - 1"""+ for i, v in enumerate(values):+ e = int(round(np.clip(v / vmax, 0, 1) * h * 8))+ for k in range(h):+ q = int(np.clip(e - 8 * k, 0, 8))+ if q: self.write(col + i, row + h - 1 - k, EIGHTHS[q], attr)++ # ================================================================ characters from the art map+ def _edge_glyph(self, nx, ny, py, outline, stroke=False):+ """outward normal (nx, ny) in px, py = where the edge sits in the cell (0 top .. 1 bottom)"""+ tx, ty = -ny, nx+ phi = np.degrees(np.arctan2(abs(ty), abs(tx) + 1e-9))+ if phi < (30 if outline == 'cloud' else 24): # flat+ if py < 0.3: return "'" if not stroke else '-'+ if py < 0.58: return '-'+ if py < 0.82: return '.' if not stroke else '-'+ return '_'+ if outline == 'cloud': # puffs: every slope is a ( or a )+ return '(' if nx < 0 else ')'+ if phi > 64: # upright+ if outline == 'round': return '(' if nx < 0 else ')'+ return '|'+ return '/' if nx * ny > 0 else '\\'++ def compose(self, region=None):+ """turn the hidden art map into characters (stored; `reveal` copies them into character memory).+ Every cell is one of: a stroke cell (the stroke's direction), an edge cell (a silhouette runs through it:+ the edge's direction and height in the cell), a border cell (a silhouette runs along one of its sides),+ or an interior cell (the material's ramp by tone, error diffusion within the material's group)."""+ R, C = self.rows, self.cols+ r0, r1, c0, c1 = region or (0, R, 0, C)+ cw, ch = self.cw, self.ch+ yy, xx = np.mgrid[0:10, 0:7].astype(np.float32)+ yy = (yy + 0.5) / 10; xx = (xx + 0.5) / 7+ I = self.inst.reshape(R, 10, C, 7).transpose(0, 2, 1, 3)+ T = self.tone.reshape(R, 10, C, 7).transpose(0, 2, 1, 3)+ DX = self.dirx.reshape(R, 10, C, 7).transpose(0, 2, 1, 3)+ DY = self.diry.reshape(R, 10, C, 7).transpose(0, 2, 1, 3)+ # coverage of every material group per cell (silhouettes are between groups)+ groups = sorted({m['group'] for m in self.materials.values()})+ gid = {g: i + 1 for i, g in enumerate(groups)}+ inst_g = np.zeros(len(self.items), np.int32)+ for k, it in enumerate(self.items[1:], 1): inst_g[k] = gid[self.materials[it['mat']]['group']]+ G = inst_g[self.inst]+ fills_only = np.array([0] + [it['kind'] == 'fill' for it in self.items[1:]], bool)[self.inst]+ gcov = {g: ((G == g) & fills_only).reshape(R, 10, C, 7).mean(axis=(1, 3)) for g in gid.values()}+ anyart = (self.inst > 0).reshape(R, 10, C, 7).any(axis=(1, 3))+ out = np.full((R, C), '', dtype='<U1'); lv = np.zeros((R, C), np.float32)+ kind = np.zeros((R, C), np.int8) # 1 interior, 2 edge, 3 border, 4 stroke+ who = np.zeros((R, C), np.int32); strength = np.zeros((R, C), np.float32)+ tone = np.zeros((R, C), np.float32)+ cov = np.zeros((R, C), np.float32)+ for r in range(r0, r1):+ for c in range(c0, c1):+ P = I[r, c]+ if not anyart[r, c]: continue+ ids, cnt = np.unique(P, return_counts=True)+ st = [(i, n) for i, n in zip(ids, cnt) if i and self.items[i]['kind'] == 'stroke' and n >= 5]+ if st: # strokes win where they really cross the cell+ i, n = max(st, key=lambda a: a[0])+ it = self.items[i]; mt = self.materials[it['mat']]+ m = P == i+ if it['glyph']:+ g = it['glyph']+ else:+ ax, ay = DX[r, c][m], DY[r, c][m]+ th = 0.5 * np.arctan2(np.mean(2 * ax * ay), np.mean(ax * ax - ay * ay))+ tx, ty = np.cos(th), np.sin(th)+ g = self._edge_glyph(-ty, tx, float(yy[m].mean()), 'straight', stroke=True)+ if len(st) > 1: # two strokes crossing+ j = sorted(st, key=lambda a: -a[0])[1][0]+ bx_, by_ = DX[r, c][P == j], DY[r, c][P == j]+ th2 = 0.5 * np.arctan2(np.mean(2 * bx_ * by_), np.mean(bx_ * bx_ - by_ * by_))+ if abs(np.sin(th - th2)) > 0.6:+ g = 'X' if abs(np.sin(2 * th)) > 0.5 else '+'+ t = float(T[r, c][m].mean())+ out[r, c] = g; lv[r, c] = mt['edge'] or self._lv_for(t)+ kind[r, c] = 4; strength[r, c] = n; who[r, c] = i+ continue+ fl = [(i, n) for i, n in zip(ids, cnt) if i and self.items[i]['kind'] == 'fill']+ if not fl: continue+ big = [i for i, n in fl if n >= 7]+ A = max(big) if big else max(fl, key=lambda a: a[1])[0]+ mA = P == A+ f = float(mA.mean())+ mt = self.materials[self.items[A]['mat']]+ ga = inst_g[A]+ t = float(T[r, c][mA].mean())+ who[r, c] = A; tone[r, c] = t+ same = (G[r * 10:r * 10 + 10, c * 7:c * 7 + 7] == ga) & fills_only[r * 10:r * 10 + 10, c * 7:c * 7 + 7]+ fg = float(same.mean())+ cov[r, c] = fg+ if mt['outline'] is None:+ if fg < 0.3: continue+ tone[r, c] = float(T[r, c][same].mean()) * min(1.0, fg / 0.8)+ kind[r, c] = 1+ continue+ if fg >= 0.86:+ # interior -- unless a side of the cell is a silhouette+ nb = []+ for dc, dr_ in ((0, -1), (0, 1), (-1, 0), (1, 0)):+ rr, cc = r + dr_, c + dc+ if 0 <= rr < R and 0 <= cc < C and gcov[ga][rr, cc] < 0.07:+ nb.append((dc, dr_))+ if not nb:+ kind[r, c] = 1+ continue+ nx = sum(d[0] for d in nb) / cw; ny = sum(d[1] for d in nb) / ch+ if abs(nx) + abs(ny) < 1e-6:+ kind[r, c] = 1+ continue+ nn = np.hypot(nx, ny); nx, ny = nx / nn, ny / nn+ if abs(ny) > 0.9 and ny < 0: # flat top on the cell boundary: '_' in the cell above+ if r - 1 >= r0 and not anyart[r - 1, c] and out[r - 1, c] == '':+ out[r - 1, c] = '_'; lv[r - 1, c] = mt['edge'] or self._lv_for(t)+ kind[r - 1, c] = 3; who[r - 1, c] = A+ kind[r, c] = 1+ continue+ py = 1.0 if ny > 0 else 0.5+ out[r, c] = self._edge_glyph(nx, ny, py, mt['outline'])+ lv[r, c] = mt['edge'] or self._lv_for(t)+ kind[r, c] = 3+ continue+ if f < 0.07: continue+ # an edge runs through the cell: its direction from the first moment of the covered samples+ mx = float((xx * mA).sum() / mA.sum() - 0.5); my = float((yy * mA).sum() / mA.sum() - 0.5)+ nx, ny = -mx / cw, -my / ch # a normal: scales inversely with the cell size+ if abs(nx) + abs(ny) < 1e-3: continue+ nn = np.hypot(nx, ny); nx, ny = nx / nn, ny / nn+ py = (1 - f) if ny < 0 else f+ if ny < -0.9 and py < 0.3 and r - 1 >= r0 and not anyart[r - 1, c] and out[r - 1, c] == '':+ out[r - 1, c] = '_'; lv[r - 1, c] = mt['edge'] or self._lv_for(t)+ kind[r - 1, c] = 3; who[r - 1, c] = A+ kind[r, c] = 1+ continue+ out[r, c] = self._edge_glyph(nx, ny, py, mt['outline'])+ lv[r, c] = mt['edge'] or self._lv_for(t)+ kind[r, c] = 2; strength[r, c] = f+ # a silhouette is one character thick: of two touching edge cells with the same upright / slanted+ # character keep the one the edge runs closest to the middle of; the other becomes inside or outside+ for r in range(r0, r1):+ for c in range(c0, c1 - 1):+ if kind[r, c] in (2, 3) and kind[r, c + 1] in (2, 3) and out[r, c] == out[r, c + 1] and \+ out[r, c] in '/\\()|' and inst_g[who[r, c]] == inst_g[who[r, c + 1]]:+ k = c if abs(cov[r, c] - 0.5) > abs(cov[r, c + 1] - 0.5) else c + 1+ out[r, k] = ''+ kind[r, k] = 1 if cov[r, k] >= 0.5 else 0+ for r in range(r0, r1 - 1):+ for c in range(c0, c1):+ if kind[r, c] in (2, 3) and kind[r + 1, c] in (2, 3) and out[r, c] in "_.-'" and \+ out[r + 1, c] in "_.-'" and inst_g[who[r, c]] == inst_g[who[r + 1, c]]:+ k = r if abs(cov[r, c] - 0.5) > abs(cov[r + 1, c] - 0.5) else r + 1+ out[k, c] = ''+ kind[k, c] = 1 if cov[k, c] >= 0.5 else 0+ # interiors: each material's ramp by tone, Floyd-Steinberg within the group+ err = np.zeros((R + 1, C + 2), np.float32)+ rng = np.random.default_rng(self.seed + 11)+ for r in range(r0, r1):+ for c in range(c0, c1):+ if kind[r, c] != 1: continue+ A = who[r, c]; mt = self.materials[self.items[A]['mat']]; ga = inst_g[A]+ n = len(mt['ramp'])+ x = tone[r, c] * (n - 1) + err[r, c + 1] + rng.normal(0, mt['dither'])+ q = int(np.clip(np.round(x), 0, n - 1))+ e = x - q+ for dc, dr_, w in ((1, 0, 7 / 16), (-1, 1, 3 / 16), (0, 1, 5 / 16), (1, 1, 1 / 16)):+ rr, cc = r + dr_, c + dc+ if rr < R and 0 <= cc < C and kind[rr, cc] == 1 and inst_g[who[rr, cc]] == ga:+ err[rr, cc + 1] += e * w+ g = mt['ramp'][q]+ if g != ' ':+ out[r, c] = g; lv[r, c] = mt['lv'][q]+ # one stroke cell per row across, one per column up: keep the stronger of two touching duplicates+ for r in range(r0, r1):+ for c in range(c0, c1 - 1):+ if kind[r, c] == 4 and kind[r, c + 1] == 4 and who[r, c] == who[r, c + 1] and \+ out[r, c] == out[r, c + 1] and out[r, c] in '|/\\':+ k = c if strength[r, c] < strength[r, c + 1] else c + 1+ out[r, k] = ''; kind[r, k] = 0+ for r in range(r0, r1 - 1):+ for c in range(c0, c1):+ if kind[r, c] == 4 and kind[r + 1, c] == 4 and who[r, c] == who[r + 1, c] and \+ out[r, c] in "_.-'" and out[r + 1, c] in "_.-'":+ k = r if strength[r, c] < strength[r + 1, c] else r + 1+ out[k, c] = ''; kind[k, c] = 0+ sel = (slice(r0, r1), slice(c0, c1))+ self.art_text[sel] = out[sel]+ self.art_lvl[sel] = lv[sel]+ self.art_kind = kind+ return out++ @staticmethod+ def _lv_for(t):+ return LEVELS['bold'] if t > 0.62 else LEVELS['normal'] if t > 0.3 else LEVELS['dim']++ def reveal(self, r0=0, r1=None, c0=0, c1=None):+ """copy composed art into character memory (rows r0..r1); blank art cells leave the text alone"""+ r1 = self.rows if r1 is None else r1; c1 = self.cols if c1 is None else c1+ m = np.zeros((self.rows, self.cols), bool)+ m[r0:r1, c0:c1] = self.art_text[r0:r1, c0:c1] != ''+ self.text[m] = self.art_text[m]+ self.lvl[m] = self.art_lvl[m]+ self.rev[m] = False++ # ================================================================ the beam+ def _dots(self):+ """character memory -> dot raster at half-dot resolution (rows*10, cols*14) of beam levels.+ Dot stretching (each lit dot lasts half a dot longer) happens here, before reverse video, so the dark+ strokes of reversed characters stay as readable as the lit strokes of normal ones"""+ R, C = self.rows, self.cols+ code = np.vectorize(lambda s: ROM_INDEX.get(s, ROM_INDEX['?']))(self.text)+ G = ROM[code].astype(np.float32) # (R, C, 10, 7)+ G[..., 9, :] = np.where(self.ul[..., None], 1.0, G[..., 9, :])+ G = np.repeat(G, 2, axis=3) # half dots: (R, C, 10, 14)+ G[..., 1:] = np.maximum(G[..., 1:], G[..., :-1]) # dot stretching+ if self.cur:+ c, r, shape = self.cur+ if 0 <= r < R and 0 <= c < C:+ if shape == 'block': self.rev[r, c] = not self.rev[r, c]+ else: G[r, c, 8:10, :] = 1+ G = np.where(self.rev[..., None, None], 1 - G, G)+ if self.cur and self.cur[2] == 'block':+ c, r, _ = self.cur+ if 0 <= r < R and 0 <= c < C: self.rev[r, c] = not self.rev[r, c]+ G *= self.lvl[..., None, None]+ for r, md in enumerate(self.mode): # double width / height lines+ if not md: continue+ for c in range(0, C - 1, 2):+ g = G[r, c]+ if md == 'dht': g = g[np.arange(10) // 2]+ elif md == 'dhb': g = g[5 + np.arange(10) // 2]+ g2 = np.repeat(g[:, ::2], 4, axis=1) # (10, 28): every dot twice as wide+ g2[:, 1:] = np.maximum(g2[:, 1:], g2[:, :-1])+ G[r, c], G[r, c + 1] = g2[:, :14], g2[:, 14:]+ D = G.transpose(0, 2, 1, 3).reshape(R * 10, C * 14)+ D = np.maximum(D, np.repeat(self.glow, 2, axis=1))+ return D * (1 - np.repeat(self.worn, 2, axis=1))++ def _raster(self):+ """dot raster -> beam-painted raster at 2x (unwarped), float32 light"""+ D = self._dots()+ p = int(round(self.pad))+ D = np.pad(D, ((p * 10, p * 10), (p * 14, p * 14)))+ Hs, Ws = D.shape+ RW2, RH2 = int(round(self.rw * 2)), int(round(self.rh * 2))+ q = RW2 / Ws * 2 # px per dot+ xs = (np.arange(RW2) + 0.5) / (q / 2)+ S = D[:, np.clip(xs.astype(np.int32), 0, Ws - 1)]+ # video amplifier bandwidth: causal exponential smoothing (soft rise, a trail to the right)+ a = 1 - np.exp(-1.0 / (0.30 * q))+ K = int(4 * 0.30 * q) + 2+ ker = a * (1 - a) ** np.arange(K, dtype=np.float32)+ ker /= ker.sum()+ Sm = np.zeros_like(S)+ for k, w in enumerate(ker):+ Sm[:, k:] += w * S[:, :RW2 - k]+ S = Sm+ for row, dx, lines in self.tears: # sync slips+ k0 = int((row + self.pad) * 10 + 5)+ sh = int(round(dx * 2))+ for k in range(k0, min(Hs, k0 + lines)):+ S[k] = np.concatenate([np.zeros(sh, np.float32), S[k, :-sh]]) + 0.06 * (S[k] > 0.05).mean()+ S = S + self.brightness # the whole raster glows a little+ # the beam: a gaussian spot per scan line that grows with the current (blooming)+ pitch = RH2 / Hs+ y = np.arange(RH2, dtype=np.float32) + 0.5+ k0 = np.floor(y / pitch - 0.5).astype(np.int32)+ out = np.zeros((RH2, RW2), np.float32)+ for n in (-1, 0, 1, 2):+ k = k0 + n+ ok = (k >= 0) & (k < Hs)+ kk = np.clip(k, 0, Hs - 1)+ d = (y - (kk + 0.5) * pitch)[:, None]+ V = S[kk]+ sig = pitch * (0.17 + 0.20 * np.sqrt(np.clip(V, 0, 1.5)))+ out += np.where(ok[:, None], V * np.exp(-0.5 * (d / sig) ** 2), 0)+ return out++ # ================================================================ the tube+ def _geometry(self):+ """per output pixel (2 x 2 sub-samples) inside the opening: where it lands on the raster.+ Radial barrel in real pixels: src = p (1 + k |p|^2 / hw^2), so letters are not sheared sideways"""+ if self._geom is not None: return self._geom+ x0, y0, x1, y1 = self.opening+ H, W = y1 - y0, x1 - x0+ cx, cy = self.ocx - x0, self.ocy - y0+ hw, hh = self.rw / 2, self.rh / 2+ k = self.curve+ subs = []+ for oy in (0.25, 0.75):+ for ox in (0.25, 0.75):+ px = (np.arange(W, dtype=np.float32) + ox - cx)[None, :]+ py = (np.arange(H, dtype=np.float32) + oy - cy)[:, None]+ f = 1 + k * (px * px + py * py) / (hw * hw)+ subs.append(((px * f + hw) * 2 - 0.5, (py * f + hh) * 2 - 0.5))+ u = ((np.arange(W, dtype=np.float32) + 0.5 - cx) / hw)[None, :]+ v = ((np.arange(H, dtype=np.float32) + 0.5 - cy) / hh)[:, None]+ self._geom = (subs, u, v)+ return self._geom++ @staticmethod+ def _bilinear(img, sx, sy):+ Hs, Ws = img.shape+ x0 = np.floor(sx).astype(np.int32); y0 = np.floor(sy).astype(np.int32)+ fx = (sx - x0).astype(np.float32); fy = (sy - y0).astype(np.float32)+ out = np.zeros(np.broadcast(sx, sy).shape, np.float32)+ for dy, wy in ((0, 1 - fy), (1, fy)):+ for dx, wx in ((0, 1 - fx), (1, fx)):+ xx, yy = x0 + dx, y0 + dy+ ok = (xx >= 0) & (xx < Ws) & (yy >= 0) & (yy < Hs)+ out += np.where(ok, img[np.clip(yy, 0, Hs - 1), np.clip(xx, 0, Ws - 1)], 0) * wx * wy+ return out++ def _opening_sdf(self, X, Y):+ x0, y0, x1, y1 = self.opening+ a, b, r = (x1 - x0) / 2, (y1 - y0) / 2, self.radius+ qx = np.abs(X - self.ocx) - (a - r)+ qy = np.abs(Y - self.ocy) - (b - r)+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r++ def _screen_light(self):+ """phosphor light inside the opening at 1x (before glow), and the raster-space coordinates"""+ subs, u, v = self._geometry()+ x0, y0, x1, y1 = self.opening+ if not self.on:+ return np.zeros((y1 - y0, x1 - x0), np.float32)+ R2 = self._raster()+ L = np.zeros((y1 - y0, x1 - x0), np.float32)+ for sx, sy in subs:+ L += self._bilinear(R2, sx, sy)+ L *= 0.25+ # brightness falls off toward the edges of the tube; a faint hum bar rolls through+ f = 1 - 0.10 * (u * u + v * v) - 0.22 * (u * u) * (v * v)+ L *= np.clip(f, 0.4, 1) * (1 + 0.025 * np.sin(2 * np.pi * (v * 0.55 + 0.18)))+ # phosphor grain+ g = self.rng.random(L.shape, dtype=np.float32)+ L *= 1 + 0.10 * (g - 0.5)+ return L++ def _glass(self):+ """the unlit face: tinted glass, room reflections, the bezel's shadow (cached), at 1x inside the opening"""+ if hasattr(self, '_glass_rgb'): return self._glass_rgb+ x0, y0, x1, y1 = self.opening+ H, W = y1 - y0, x1 - x0+ _, u, v = self._geometry()+ face = np.array(self.ph['face'], np.float32)+ r2 = u * u + v * v+ base = face[None, None, :] * (1.0 + 0.35 * (1 - np.clip(r2, 0, 1.6) / 1.6))[..., None]+ # a ceiling sheen bending with the bulge of the glass+ sheen = np.exp(-((v + 0.80 - 0.10 * u * u) / 0.16) ** 2) * (1 - 0.6 * u * u) * 0.020+ # a window over the viewer's left shoulder, shrunk and bent by the convex glass+ wu, wv = u * (1 + 0.22 * r2), v * (1 + 0.22 * r2)+ win = ((wu > -0.86) & (wu < -0.44) & (wv > -0.80) & (wv < -0.28)).astype(np.float32)+ bars = (np.abs(wu + 0.65) < 0.012) | (np.abs(wv + 0.54) < 0.018)+ win = win * (1 - 0.85 * bars)+ win = blur(win, 11) * (0.55 + 0.45 * smoothstep(-0.28, -0.80, wv))+ refl = sheen[..., None] * np.array([0.85, 0.9, 1.0], np.float32) + \+ (win * 0.075)[..., None] * np.array([0.80, 0.86, 0.95], np.float32)+ # specks of dust catch the room light+ n = int(W * H / 9000)+ im = Image.new('L', (W, H), 0); d = ImageDraw.Draw(im)+ for _ in range(n):+ x, y = self.rng.uniform(0, W), self.rng.uniform(0, H)+ rr = self.rng.uniform(0.5, 1.3)+ d.ellipse([x - rr, y - rr, x + rr, y + rr], fill=int(self.rng.uniform(30, 110)))+ dust = blur(np.asarray(im, np.float32) / 255, 0.6) * 0.05+ # the bezel shadows the top of the recessed glass; the corners are darker+ Y, X = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ sd = -self._opening_sdf(X, Y) # distance inside the opening+ top = np.clip((Y - y0) / 36, 0, 1)+ shade = smoothstep(0, 22, sd) * (0.55 + 0.45 * top) * (1 - 0.25 * smoothstep(0.6, 1.3, r2))+ rgb = (base + refl + dust[..., None]) * shade[..., None]+ self._glass_rgb = (rgb.astype(np.float32), shade.astype(np.float32))+ return self._glass_rgb++ # ================================================================ the case+ def _case_rgb(self):+ """the putty plastic bezel, lit by the room (cached, with the static part of the green spill: how much+ each point of the chamfer faces the screen). Small parts (wheels, LED, icons) are worked in local windows"""+ if self._case is not None: return self._case+ H, W = self.H, self.W+ Y = np.arange(H, dtype=np.float32)[:, None]+ X = np.arange(W, dtype=np.float32)[None, :]+ d = self._opening_sdf(X, Y).astype(np.float32)+ bw, depth = 30.0, 17.0+ h = depth * smoothstep(0, 1, np.clip(d / bw, 0, 1)) ** 0.85+ h -= 1.1 * np.exp(-((d - bw - 13) / 1.8) ** 2) # mould seam round the opening+ # moulded stipple and a few sink marks+ h += noise2d(H, W, 2.5, 2, self.seed + 5) * 0.55+ h += noise2d(H, W, 9, 2, self.seed + 6) * 0.35+ h += noise2d(H, W, 220, 3, self.seed + 7) * 2.5+ # controls along the bottom: two thumbwheel slots and the LED's ring+ x0, y0, x1, y1 = self.opening+ by = min(H - 34.0, (y1 + H) / 2 + 16)+ self._wheels = [(W - 300, by), (W - 236, by)]+ self._led = (W - 150, by)+ for wx, wy in self._wheels:+ h[int(wy - 26):int(wy + 26), int(wx - 13):int(wx + 13)] -= 6.0+ lx, ly = self._led+ ys, xs = slice(int(ly - 14), int(ly + 14)), slice(int(lx - 14), int(lx + 14))+ rr = np.hypot(X[:, xs] - lx, Y[ys] - ly)+ h[ys, xs] += 1.6 * smoothstep(9.5, 7.5, rr) - 1.6 * smoothstep(7.5, 6.0, rr)+ n = height_normals(h)+ del h+ Lg = np.array([-0.32, -0.62, 0.72], np.float32); Lg /= np.linalg.norm(Lg)+ Hv = Lg + np.array([0, 0, 1], np.float32); Hv /= np.linalg.norm(Hv)+ lam = np.clip(n @ Lg, 0, 1)+ shade = (0.30 + 0.62 * lam / Lg[2]) * (1.06 - 0.16 * (Y / H)) # nearer the ceiling light at the top+ shade *= 1 + 0.03 * (noise2d(H, W, 300, 2, self.seed + 8) - 0.5) # uneven yellowing+ spec = np.clip(n @ Hv, 0, 1) ** 28 * 0.07+ rgb = _c(PUTTY)[None, None, :] * shade[..., None]+ rgb += spec[..., None]+ del lam, shade, spec+ # how much the chamfer faces the screen centre (for the green spill)+ dxs, dys = self.ocx - X, self.ocy - Y+ dn = np.hypot(dxs, dys) + 1e-3+ self._facing = (np.clip((n[..., 0] * dxs + n[..., 1] * dys) / dn, 0, 1) * (d > 0)).astype(np.float32)+ del n, dxs, dys, dn+ # thumbwheels: knurled discs standing in their slots, lit from above+ for wx, wy in self._wheels:+ ys, xs = slice(int(wy - 26), int(wy + 26)), slice(int(wx - 13), int(wx + 13))+ win = rgb[ys, xs]+ win *= 0.22 # the dark slot+ yy = Y[ys] - wy; xx = X[:, xs] - wx+ m = (np.abs(xx) < 10) & (np.abs(yy) < 23.5)+ vy = np.clip(yy / 25, -0.999, 0.999)+ cyl = np.sqrt(1 - vy * vy)+ ang = np.arcsin(vy)+ ridge = np.abs(np.sin(ang * 13 + 0.6)) # knurls, crowding toward the ends+ face = np.clip(-np.sin(ang * 13 + 0.6) * np.cos(ang * 13 + 0.6) * 2, -1, 1)+ lit = (0.18 + 0.75 * np.clip(-vy * 0.55 + cyl * 0.8, 0, 1)) * (0.62 + 0.38 * ridge) + 0.10 * face * cyl+ lit = np.clip(lit, 0.03, 1.2) * (0.55 + 0.45 * smoothstep(10, 8.5, np.abs(xx)))+ wc = np.array([0.46, 0.44, 0.41], np.float32)+ win[:] = np.where(m[..., None], wc * lit[..., None], win)+ # embossed icons beside the wheels: a sun (brightness) and a half disc (contrast)+ ox, oy = int(self._wheels[0][0] - 60), int(by - 20)+ iw, ih = int(self._wheels[1][0] + 60) - ox, 40+ ic = Image.new('L', (iw, ih), 0); dd = ImageDraw.Draw(ic)+ sx, sy = self._wheels[0][0] - 34 - ox, by - oy+ dd.ellipse([sx - 4, sy - 4, sx + 4, sy + 4], outline=255, width=2)+ for k in range(8):+ a = k * np.pi / 4+ dd.line([(sx + 6.5 * np.cos(a), sy + 6.5 * np.sin(a)), (sx + 9.5 * np.cos(a), sy + 9.5 * np.sin(a))],+ fill=255, width=2)+ cx2 = self._wheels[1][0] + 34 - ox+ dd.ellipse([cx2 - 8, sy - 8, cx2 + 8, sy + 8], outline=255, width=2)+ dd.pieslice([cx2 - 8, sy - 8, cx2 + 8, sy + 8], 90, 270, fill=255)+ icon = blur(np.asarray(ic, np.float32) / 255, 0.6)+ gy_, gx_ = np.gradient(icon)+ rgb[oy:oy + ih, ox:ox + iw] *= ((1 + (-gx_ * 0.6 - gy_ * 1.2) * 1.2) * (1 - 0.05 * icon))[..., None]+ np.clip(rgb, 0, 1, out=rgb)+ self._case = (rgb.astype(np.float32), d)+ return self._case++ # ================================================================ compositing+ def composite(self):+ W, H = self.W, self.H+ case, sdf = self._case_rgb()+ out = case.copy()+ x0, y0, x1, y1 = self.opening+ glass, gshade = self._glass()+ L = self._screen_light()+ tint = np.array(self.ph['tint'], np.float32)+ # light scattered in the faceplate: bloom close in, halation far out+ Lb = L * np.clip(L, 0, 1.6) # the brightest strokes scatter most (bold glows, dim doesn't)+ Lt = 1.25 * L + 0.55 * blur(L, 2.0) + 0.42 * blur(Lb, 13) + 0.24 * blur(Lb, 50)+ del Lb+ emit = 1 - np.exp(-Lt[..., None] * 2.4 * tint[None, None, :])+ del Lt+ scr = 1 - (1 - glass) * (1 - emit * (0.94 + 0.06 * gshade[..., None]))+ del emit+ # the opening: glass inside, a dark gasket line at the edge+ ins = smoothstep(0.5, -0.5, sdf[y0:y1, x0:x1])[..., None]+ gasket = np.exp(-((sdf[y0:y1, x0:x1] + 1.5) / 2.2) ** 2) * 0.75+ reg = out[y0:y1, x0:x1]+ reg[:] = reg * (1 - ins) + scr * ins+ reg *= (1 - gasket)[..., None]+ del scr+ lx, ly = self._led+ ys, xs = slice(int(ly - 40), int(ly + 40)), slice(int(lx - 40), int(lx + 40))+ rr = np.hypot(np.arange(xs.start, xs.stop, dtype=np.float32)[None, :] - lx,+ np.arange(ys.start, ys.stop, dtype=np.float32)[:, None] - ly)+ led = smoothstep(6.0, 4.5, rr)[..., None]+ if self.on:+ # green spill from the screen onto the chamfer (the more it faces the screen, the more) and the face+ big = np.zeros((H, W), np.float32)+ big[y0:y1, x0:x1] = blur(L, 40) + blur(L, 120) * 0.6+ amt = blur(big, 30) * 5.0+ del big+ amt *= (0.20 + 2.2 * self._facing) * (sdf > 0)+ col = 1 - np.exp(-amt[..., None] * 1.6 * tint[None, None, :])+ del amt+ col *= 0.9+ out = 1 - (1 - out) * (1 - col)+ del col+ # the power LED+ lc = np.array([0.45, 1.0, 0.35], np.float32)+ w = out[ys, xs]+ w[:] = w * (1 - led) + (lc * 0.75 + 0.25) * led+ glow = (np.exp(-(rr / 9) ** 2) * 0.5 + np.exp(-(rr / 22) ** 2) * 0.12)[..., None]+ w[:] = 1 - (1 - w) * (1 - glow * lc)+ else:+ w = out[ys, xs]+ w[:] = w * (1 - led) + np.array([0.10, 0.16, 0.10], np.float32) * led+ return Image.fromarray((np.clip(out, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ """snapshot for the draw-on animation"""+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/delft.py b/lib/delft.pynew file mode 100644index 0000000..831a5db--- /dev/null+++ b/lib/delft.py@@ -0,0 +1,1446 @@+"""delft — a wall of Delftware: hand-painted cobalt tiles in tin glaze, with a tile picture (tableau)+set among single tiles (numpy + Pillow only).++Model — the way a Dutch tile wall of about 1650–1800 was made, step by step:+ biscuit every tile is a square of buff earthenware (about 13 cm, so `tile` px on the wall) dipped in a+ tin glaze: opaque white, a little cool or a little creamy from batch to batch; the glaze runs thin+ and round over the edges.+ pounce the design comes from a pricked paper pattern (the spons): charcoal dust tapped through the holes+ leaves dotted outlines on the raw glaze. `trek()` records those dots; they burn off in the kiln.+ trek the outline painter follows the dots with a long fine brush: fluent lines of nearly even width,+ a small bead where the brush lands, a taper where it lifts, a slow hand wobble.+ wash a second hand floods areas with diluted cobalt. Raw glaze is powdery and drinks the water at+ once, so a wash cannot be blended: it shows the bands of the brush, bristle streaks, a darker rim+ where the water dried last, overlaps that darken, and it never sits exactly inside the outline.+ A blue ground painted round a shape leaves that shape white (`reserve` / `holes=`).+ occlusion one transparent pigment, so the painter leaves out what is hidden: draw front to back and call+ `occlude()` with the silhouette of whatever stands in front; later strokes skip it.+ raw/fired unfired pigment is dull grey-black on a matte chalky glaze; in the kiln the glaze melts and turns+ glossy, cobalt develops into blue (pale where thin, deep violet-blue where thick, Beer–Lambert+ absorption per channel) and sinks into the glaze with a soft bleed.+ tile by tile each tile is painted and fired on its own, so in a tableau the lines step a pixel or two at+ every joint, and every tile has its own white and its own strength of blue.+ wall tiles set in lime mortar on a grid that is never quite straight; every tile a little warped and+ tilted, so a window reflects as broken, bent pieces and the rounded edges catch the light.+ age crazing (a fine crack network with dirt in it), pinholes and iron specks, chipped corners that+ show the buff body, nail holes near the corners from the trimming template, a cracked tile.++ from delft import DelftTile+ t = DelftTile(1920, 1080, tile=128, joint=3.6, origin=(0, -36), seed=7)+ R = t.tableau(2, 1, 13, 8) # tiles i 2..12, k 1..7 carry one continuous picture+ t.layer('picture') # front to back: draw, then occlude() what stands in front+ t.tulip(400, 900, 50, lean=0.3) # Delft vocabulary: windmill, sailboat, house, tree, bushes,+ t.windmill(455, 560, 232, sails=0.42) # tulip, cloud, birds, water, reflection, grass, smoke+ t.cloud(1000, 215, 430, 120)+ t.trek(points, 2.0); t.wash(polygon, tone=0.2, angle=0.0); t.hatch(polygon, angle=1.2, spacing=4)+ t.layer('frame'); t.border(R) # painted frame with a reserved white vine+ t.layer('single'); t.field(corners='spin') # every other tile: corner quarters + medallion + motif+ t.stage('outline', hide=('wash', 'single')) # replay the workshop: hide layers or kinds+ t.fire(); t.set_wall(); t.age(); t.light(window=(1752, 318, 150, 200))+ t.save('out.jpg')+"""+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, shift, load_font+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, np.float32)+++COBALT_K = np.array([2.3, 1.95, 0.95], np.float32) # fired cobalt in tin glaze: absorbs red/green, passes blue+RAW_K = np.array([1.62, 1.68, 1.66], np.float32) # unfired pigment: dull grey-black+GLAZE_COOL, GLAZE_WARM, RAW_GLAZE = '#f1f2ed', '#f4ecdb', '#e6e0d5'+MORTAR, BED, BODY = '#d2ccbe', '#5d564e', '#caa086'+++def _resample(P, step):+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)+ s = np.concatenate([[0], np.cumsum(seg)])+ L = float(s[-1])+ n = max(2, int(L / step) + 1)+ u = np.linspace(0, L, n)+ return np.stack([np.interp(u, s, P[:, 0]), np.interp(u, s, P[:, 1])], 1).astype(np.float32), L+++def _normals(P):+ tg = np.gradient(P, axis=0)+ tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6+ return np.stack([-tg[:, 1], tg[:, 0]], 1)+++def arc(cx, cy, rx, ry, a0, a1, n=24, rot=0.0):+ """points on an elliptical arc, angles in radians (y down: 0 = right, pi/2 = down)"""+ t = np.linspace(a0, a1, n)+ x, y = np.cos(t) * rx, np.sin(t) * ry+ c, s = np.cos(rot), np.sin(rot)+ return np.stack([cx + x * c - y * s, cy + x * s + y * c], 1)+++def ellipse_pts(cx, cy, rx, ry, rot=0.0, n=48):+ return arc(cx, cy, rx, ry, 0, 2 * np.pi, n + 1, rot)[:-1]+++def _lerp(p, q, t):+ return (p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t)+++class DelftTile:+ def __init__(self, W=1920, H=1080, seed=0, tile=128, joint=3.6, origin=(0, 0), ss=3,+ glaze=(GLAZE_COOL, GLAZE_WARM), mortar=MORTAR, light=(-0.5, -0.6, 0.63)):+ self.W, self.H, self.p, self.joint, self.ss = W, H, float(tile), float(joint), ss+ self.ox, self.oy = float(origin[0]), float(origin[1])+ self.rng = np.random.default_rng(seed)+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)+ self.Lv = np.asarray(light, np.float32) / np.linalg.norm(light)+ self.glaze_cols = (_c(glaze[0]), _c(glaze[1]))+ self.mortar = _c(mortar)+ self.layers, self.order, self.cur = {}, [], None+ self.P = np.zeros((H, W), np.float32) # pounce dots (charcoal)+ self.occ = np.zeros((H, W), np.float32) # reserved (already painted in front)+ self.tabs = []+ self.fired = self.grouted = False+ self.aged = None+ self.window = None+ self.stages = []+ self._fine = noise2d(H, W, 5, 2, self._seed())+ self._grid()++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ the grid of tiles+ def _grid(self):+ p, r = self.p, self.rng+ self.i0 = int(np.floor(-self.ox / p)) - 1+ self.k0 = int(np.floor(-self.oy / p)) - 1+ ni = int(np.ceil((self.W - self.ox) / p)) - self.i0 + 2+ nk = int(np.ceil((self.H - self.oy) / p)) - self.k0 + 2+ sh = (nk, ni)+ self.jx = np.clip(r.normal(0, 0.55, sh), -1.3, 1.3).astype(np.float32) # set a little off the grid+ self.jy = np.clip(r.normal(0, 0.55, sh), -1.3, 1.3).astype(np.float32)+ self.sz = np.clip(r.normal(0, 0.45, sh), -0.9, 0.9).astype(np.float32) # hand-trimmed size+ self.warm = r.beta(2.0, 3.2, sh).astype(np.float32) # glaze batch: cool .. creamy+ self.bright = r.normal(1.0, 0.011, sh).astype(np.float32)+ self.strength = np.clip(r.normal(1.0, 0.075, sh), 0.85, 1.16).astype(np.float32) # kiln position+ self.pdx = np.clip(np.round(r.normal(0, 1.05, sh)), -2, 2).astype(np.int32) # painted on its own+ self.pdy = np.clip(np.round(r.normal(0, 1.05, sh)), -2, 2).astype(np.int32)+ self.tx = r.normal(0, 0.0048, sh).astype(np.float32) # set slightly tilted+ self.ty = r.normal(0, 0.0048, sh).astype(np.float32)+ self.warp = r.normal(0.25, 0.3, sh).astype(np.float32) # px; + = cushioned+ self.craze = r.beta(1.0, 2.6, sh).astype(np.float32)+ ci = np.floor((self.XX - self.ox) / p).astype(np.int32) - self.i0+ ck = np.floor((self.YY - self.oy) / p).astype(np.int32) - self.k0+ self.ci, self.ck = ci, ck+ cx = self.ox + (ci + self.i0) * p + p / 2 + self.jx[ck, ci]+ cy = self.oy + (ck + self.k0) * p + p / 2 + self.jy[ck, ci]+ lx, ly = self.XX - cx, self.YY - cy+ hs = (p - self.joint) / 2 + self.sz[ck, ci]+ rc = 2.4+ qx, qy = np.abs(lx) - (hs - rc), np.abs(ly) - (hs - rc)+ sdf = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - rc+ edge = noise2d(self.H, self.W, 9, 2, self._seed())+ sdf = sdf + (edge - 0.5) * 1.1 # hand-cut, wavy edge+ self.sdf = sdf.astype(np.float32)+ self.inside = np.clip(0.5 - sdf, 0, 1).astype(np.float32)+ self.lx, self.ly, self.hs = lx, ly, hs+ # glaze surface (px): rounded edge + cushion + tilt + orange peel+ bev, bh = 3.4, 1.3+ e = np.clip(-sdf / bev, 0, 1)+ h = bh * np.sqrt(1 - (1 - e) ** 2)+ u, v = lx / hs, ly / hs+ wav = noise2d(self.H, self.W, 46, 2, self._seed()) - 0.5 # glaze runs a little uneven+ body = self.warp[ck, ci] * (1 - 0.5 * (u * u + v * v)) + self.tx[ck, ci] * lx + self.ty[ck, ci] * ly + 0.3 * wav+ self.h = (h + body * smoothstep(0, 1, e)).astype(np.float32)+ Yi = np.clip(self.YY.astype(np.int32) - self.pdy[ck, ci], 0, self.H - 1)+ Xi = np.clip(self.XX.astype(np.int32) - self.pdx[ck, ci], 0, self.W - 1)+ self.Yi, self.Xi = Yi, Xi+ self.is_tab = np.zeros(sh, bool)++ def rect(self, i, k):+ """nominal glazed face of tile (i, k): (x0, y0, x1, y1)"""+ p, j = self.p, self.joint / 2+ x0, y0 = self.ox + i * p, self.oy + k * p+ return x0 + j, y0 + j, x0 + p - j, y0 + p - j++ def centre(self, i, k):+ x0, y0, x1, y1 = self.rect(i, k)+ return (x0 + x1) / 2, (y0 + y1) / 2++ def visible(self):+ """every tile index (i, k) that shows on the canvas"""+ p = self.p+ out = []+ for k in range(int(np.floor(-self.oy / p)), int(np.ceil((self.H - self.oy) / p))):+ for i in range(int(np.floor(-self.ox / p)), int(np.ceil((self.W - self.ox) / p))):+ out.append((i, k))+ return out++ def tableau(self, i0, k0, i1, k1):+ """tiles i0 <= i < i1, k0 <= k < k1 carry one continuous picture; returns its outer rect in px"""+ self.tabs.append((i0, k0, i1, k1))+ self.is_tab[k0 - self.k0:k1 - self.k0, i0 - self.i0:i1 - self.i0] = True+ return (self.ox + i0 * self.p, self.oy + k0 * self.p, self.ox + i1 * self.p, self.oy + k1 * self.p)++ def in_tableau(self, i, k):+ return any(a <= i < c and b <= k < d for a, b, c, d in self.tabs)++ # ------------------------------------------------------------ paint layers+ def layer(self, name):+ """draw into a named pigment layer; every layer keeps its outlines ('trek') and washes ('wash') apart,+ so stages can replay the painting order (hide 'sky', 'wash', 'sky.wash', ...)"""+ for kind in ('trek', 'wash'):+ if (name, kind) not in self.layers:+ self.layers[(name, kind)] = np.zeros((self.H, self.W), np.float32)+ self.order.append((name, kind))+ self.cur = name++ def occlude(self, shape, grow=1.0):+ """reserve a silhouette: later strokes and washes leave it unpainted (draw front to back)"""+ x0, y0, m = self._mask_local(shape, pad=3)+ if m is None: return+ if grow: m = np.clip(blur(m, grow) * 2.2, 0, 1)+ sl = self.occ[y0:y0 + m.shape[0], x0:x0 + m.shape[1]]+ np.maximum(sl, m[:sl.shape[0], :sl.shape[1]], out=sl)++ def clear_occlusion(self):+ self.occ[:] = 0++ def _add(self, x0, y0, arr, mode):+ if self.cur is None: self.layer('paint')+ h, w = arr.shape+ xa, ya, xb, yb = max(0, x0), max(0, y0), min(self.W, x0 + w), min(self.H, y0 + h)+ if xa >= xb or ya >= yb: return+ sub = arr[ya - y0:yb - y0, xa - x0:xb - x0] * (1 - self.occ[ya:yb, xa:xb])+ L = self.layers[(self.cur, 'trek' if mode == 'trek' else 'wash')][ya:yb, xa:xb]+ if mode == 'trek':+ L += sub * (1 - 0.6 * np.clip(L, 0, 1)) # crossing lines darken a little, not double+ else:+ L += sub++ def _mask_local(self, shape, pad=4, holes=None):+ """polygon / list of polygons / full-size mask -> (x0, y0, local AA mask)"""+ if isinstance(shape, np.ndarray) and shape.ndim == 2 and shape.shape == (self.H, self.W):+ ys, xs = np.nonzero(shape > 0.01)+ if len(xs) == 0: return 0, 0, None+ x0, y0 = max(0, xs.min() - pad), max(0, ys.min() - pad)+ x1, y1 = min(self.W, xs.max() + pad + 1), min(self.H, ys.max() + pad + 1)+ m = shape[y0:y1, x0:x1].astype(np.float32)+ if holes is not None:+ _, _, hm = self._poly_raster(holes, x0, y0, x1, y1)+ m = m * (1 - hm)+ return x0, y0, m+ polys = [np.asarray(shape, np.float32)] if np.asarray(shape[0]).ndim == 1 else [np.asarray(q, np.float32) for q in shape]+ allp = np.vstack(polys)+ x0 = int(max(0, np.floor(allp[:, 0].min()) - pad)); y0 = int(max(0, np.floor(allp[:, 1].min()) - pad))+ x1 = int(min(self.W, np.ceil(allp[:, 0].max()) + pad + 1)); y1 = int(min(self.H, np.ceil(allp[:, 1].max()) + pad + 1))+ if x1 - x0 < 2 or y1 - y0 < 2: return 0, 0, None+ _, _, m = self._poly_raster(polys, x0, y0, x1, y1)+ if holes is not None:+ _, _, hm = self._poly_raster(holes, x0, y0, x1, y1)+ m = m * (1 - hm)+ return x0, y0, m++ def _poly_raster(self, polys, x0, y0, x1, y1, ss=2):+ if len(polys) and np.asarray(polys[0]).ndim == 1: polys = [polys]+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ d = ImageDraw.Draw(im)+ for q in polys:+ q = np.asarray(q, np.float32)+ if len(q) >= 3:+ d.polygon([((x - x0) * ss, (y - y0) * ss) for x, y in q], fill=255)+ a = np.asarray(im, np.float32).reshape(y1 - y0, ss, x1 - x0, ss).mean(axis=(1, 3)) / 255+ return x0, y0, a++ # ------------------------------------------------------------ brushes+ def _pounce(self, P):+ Q, L = _resample(P, 3.3)+ Q = Q + self.rng.normal(0, 0.35, Q.shape)+ v = self.rng.uniform(0.45, 0.95, len(Q)).astype(np.float32)+ ix, iy = np.floor(Q[:, 0]).astype(int), np.floor(Q[:, 1]).astype(int)+ fx, fy = Q[:, 0] - ix, Q[:, 1] - iy+ for dx, dy, wgt in ((0, 0, (1 - fx) * (1 - fy)), (1, 0, fx * (1 - fy)), (0, 1, (1 - fx) * fy), (1, 1, fx * fy)):+ xx, yy = ix + dx, iy + dy+ ok = (xx >= 0) & (yy >= 0) & (xx < self.W) & (yy < self.H)+ np.add.at(self.P, (yy[ok], xx[ok]), (v * wgt)[ok])++ def _raster(self, P, w, d):+ ss = self.ss+ pad = float(w.max()) + 3+ x0 = int(np.floor(P[:, 0].min() - pad)); y0 = int(np.floor(P[:, 1].min() - pad))+ x1 = int(np.ceil(P[:, 0].max() + pad)); y1 = int(np.ceil(P[:, 1].max() + pad))+ x0, y0 = max(x0, -8), max(y0, -8)+ x1, y1 = min(x1, self.W + 8), min(y1, self.H + 8)+ if x1 - x0 < 1 or y1 - y0 < 1: return x0, y0, np.zeros((1, 1), np.float32)+ im = Image.new('F', ((x1 - x0) * ss, (y1 - y0) * ss), 0.0)+ dr = ImageDraw.Draw(im)+ Q = (P - np.array([x0, y0], np.float32)) * ss+ nr = _normals(Q)+ hw = w * ss / 2+ Lp, Rp = Q + nr * hw[:, None], Q - nr * hw[:, None]+ n, step = len(Q), 5+ for a in range(0, n - 1, step):+ b = min(n - 1, a + step)+ poly = [tuple(q) for q in Lp[a:b + 1]] + [tuple(q) for q in Rp[a:b + 1][::-1]]+ dr.polygon(poly, fill=float(d[a:b + 1].mean()))+ for a in list(range(0, n, step)) + [n - 1]:+ r = hw[a]+ if r > 0.3:+ dr.ellipse([Q[a, 0] - r, Q[a, 1] - r, Q[a, 0] + r, Q[a, 1] + r], fill=float(d[a]))+ arr = np.asarray(im, np.float32).reshape(y1 - y0, ss, x1 - x0, ss).mean(axis=(1, 3))+ return x0, y0, arr++ def trek(self, pts, width=2.2, dens=1.0, taper=(0.1, 0.3), wobble=0.75, smooth=True, pounce=True, bead=0.22, step=1.2):+ """an outline stroke with the fine trek brush (width px, dens = pigment load, ~1 for outlines)"""+ P = np.asarray(pts, np.float32)+ if len(P) < 2: return+ if smooth and len(P) >= 3: P = spline(P, per=8)+ P, L = _resample(P, step)+ if L < 0.6: return+ n = len(P)+ t = np.linspace(0, 1, n, dtype=np.float32)+ if pounce: self._pounce(P)+ sd = self._seed()+ if wobble:+ P = P + _normals(P) * (fbm1d(n, max(4.0, 46 / step), 3, sd) * wobble * min(1.0, L / 40 + 0.35))[:, None]+ tg = np.gradient(P, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6+ w = width * (0.84 + 0.16 * fbm1d(n, max(3.0, 28 / step), 2, sd + 1)) * (1 + 0.16 * tg[:, 1]) # heavier on the downstroke+ a, b = max(taper[0], 1e-3), max(taper[1], 1e-3)+ w = w * np.clip(np.minimum(0.62 + 0.38 * t / a, 0.2 + 0.8 * (1 - t) / b), 0.2, 1)+ d = dens * (1.07 - 0.14 * t) * (0.93 + 0.07 * fbm1d(n, max(3.0, 20 / step), 2, sd + 2))+ if bead:+ nb = max(2, int(min(n, 4 + n * 0.03)))+ w[:nb] *= 1 + bead; d[:nb] *= 1.08+ x0, y0, arr = self._raster(P, w.astype(np.float32), d.astype(np.float32))+ self._add(x0, y0, arr, 'trek')++ def line(self, p0, p1, width=2.0, dens=1.0, bend=0.0, **kw):+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ if bend:+ m = (p0 + p1) / 2; d = p1 - p0+ m = m + np.array([-d[1], d[0]]) / (np.linalg.norm(d) + 1e-6) * bend+ self.trek([p0, m, p1], width, dens, **kw)+ else:+ self.trek([p0, p1], width, dens, smooth=False, **kw)++ def closed(self, pts, width=2.0, dens=1.0, **kw):+ P = np.asarray(pts, np.float32)+ self.trek(np.vstack([P, P[:1]]), width, dens, **kw)++ def dot(self, x, y, r=1.6, dens=1.0):+ self._add(*self._raster(np.array([[x, y], [x + 0.01, y]], np.float32), np.array([2 * r, 2 * r], np.float32),+ np.array([dens, dens], np.float32)), 'trek')++ def wash(self, shape, tone=0.2, angle=0.0, pool=0.55, ragged=0.3, slip=1.2, band=11.0, streak=0.35,+ grad=None, holes=None, soft=0.7):+ """a flat wash of diluted cobalt (tone ~0.1 pale .. 0.5 dark) over a polygon / polygons / mask.+ angle: brush direction (radians); grad=((x0, y0), (x1, y1), f0, f1) ramps the tone along a line;+ holes: polygons kept white (reserve)."""+ x0, y0, m = self._mask_local(shape, pad=6, holes=holes)+ if m is None: return+ h, w = m.shape+ if soft: m = blur(m, soft)+ if ragged:+ n = self._fine[y0:y0 + h, x0:x0 + w]+ m = smoothstep(0.3, 0.7, m + (n - 0.5) * ragged)+ if slip:+ m = shift(m, self.rng.uniform(-slip, slip), self.rng.uniform(-slip, slip))+ rim = np.clip(m - blur(m, 3.2), 0, 1) * 2.4+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)+ ca, sa = np.cos(angle), np.sin(angle)+ acr = -xx * sa + yy * ca+ alg = xx * ca + yy * sa+ r = self.rng+ tb = r.random(64).astype(np.float32); tf = r.random(256).astype(np.float32); tl = r.random(64).astype(np.float32)+ bands = np.interp((acr / band + r.uniform(0, 8)) % 63, np.arange(64), tb)+ fine = np.interp((acr / 1.6 + r.uniform(0, 30)) % 255, np.arange(256), tf)+ along = np.interp((alg / 70 + r.uniform(0, 8)) % 63, np.arange(64), tl)+ S = 0.6 * bands + 0.4 * fine * (0.4 + 0.6 * along)+ d = tone * m * (1 - streak * 0.5 + streak * S) * (1 + pool * rim)+ if grad is not None:+ (gx0, gy0), (gx1, gy1), f0, f1 = grad+ vx, vy = gx1 - gx0, gy1 - gy0+ tt = np.clip(((xx + x0 - gx0) * vx + (yy + y0 - gy0) * vy) / (vx * vx + vy * vy + 1e-6), 0, 1)+ d = d * (f0 + (f1 - f0) * tt)+ self._add(x0, y0, d.astype(np.float32), 'wash')++ def hatch(self, shape, angle=0.0, spacing=5.0, width=1.1, dens=0.8, jitter=0.5, shorten=1.5, holes=None, wave=0.0):+ """parallel freehand lines clipped to a shape (shading, sails, thatch, ground)"""+ x0, y0, m = self._mask_local(shape, pad=2, holes=holes)+ if m is None: return+ if self.occ is not None:+ m = m * (1 - self.occ[y0:y0 + m.shape[0], x0:x0 + m.shape[1]])+ h, w = m.shape+ ca, sa = np.cos(angle), np.sin(angle)+ cx, cy = w / 2, h / 2+ R = np.hypot(w, h) / 2 + 2+ tt = np.arange(-R, R, 1.0, dtype=np.float32)+ off = -R + self.rng.uniform(0, spacing)+ while off < R:+ o = off + self.rng.normal(0, jitter)+ px = cx + ca * tt - sa * o; py = cy + sa * tt + ca * o+ ok = (px >= 0) & (py >= 0) & (px < w - 1) & (py < h - 1)+ ins = np.zeros(len(tt), bool)+ ins[ok] = m[py[ok].astype(int), px[ok].astype(int)] > 0.5+ dif = np.diff(np.concatenate([[0], ins.astype(np.int8), [0]]))+ for a, b in zip(np.nonzero(dif == 1)[0], np.nonzero(dif == -1)[0]):+ a2 = a + self.rng.uniform(0, shorten); b2 = b - 1 - self.rng.uniform(0, shorten)+ if b2 - a2 < 2.5: continue+ s = np.linspace(a2, b2, max(2, int((b2 - a2) / 6) + 2))+ sx = np.interp(s, np.arange(len(tt)), px) + x0; sy = np.interp(s, np.arange(len(tt)), py) + y0+ if wave:+ ph = self.rng.uniform(0, 6.3)+ k = np.sin(s * 0.25 + ph) * wave+ sx, sy = sx - sa * k, sy + ca * k+ self.trek(np.stack([sx, sy], 1), width, dens, taper=(0.15, 0.3), wobble=0.35, pounce=False, bead=0.1)+ off += spacing++ def letters(self, s, x, y, size, font='serif', dens=1.0, anchor='mm', spacing=0.0):+ """painted capitals (font outline, softened and wobbled like a brush)"""+ f = load_font(font, size)+ pad = int(size * 0.6)+ tw = int(f.getlength(s) + spacing * len(s)) + 2 * pad+ th = int(size * 1.6) + 2 * pad+ im = Image.new('L', (tw * 2, th * 2), 0)+ d = ImageDraw.Draw(im)+ f2 = load_font(font, size * 2)+ cx = tw; cy = th+ adv = [f2.getlength(ch) + spacing * 2 for ch in s]+ xx = cx - (sum(adv) - spacing * 2) / 2+ for ch, a in zip(s, adv):+ d.text((xx, cy), ch, font=f2, fill=255, anchor='l' + anchor[1]); xx += a+ m = np.asarray(im, np.float32).reshape(th, 2, tw, 2).mean(axis=(1, 3)) / 255+ m = blur(m, 0.5)+ x0, y0 = int(x - tw / 2), int(y - th / 2)+ n = self._fine[max(0, y0):max(0, y0) + th, max(0, x0):max(0, x0) + tw]+ if n.shape == m.shape: m = smoothstep(0.28, 0.72, m + (n - 0.5) * 0.25)+ self._add(x0, y0, (m * dens * (0.95 + 0.1 * (n if n.shape == m.shape else 0.5))).astype(np.float32), 'trek')++ # ------------------------------------------------------------ the Delft vocabulary+ def cloud(self, cx, cy, w, h, lean=0.3, tone=0.14, width=1.8, seed=None):+ """a scalloped cumulus: a dome of bumps (one stroke per bump, cusps between), a flat wavy base,+ a few inner bumps, a pale wash that darkens toward the base. lean > 0: wind from the left+ (the dome sits left of centre, the right end trails off in smaller bumps)."""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ base = cy + h * 0.5+ xl, xr = cx - w / 2, cx + w / 2+ n = max(4, int(w / (h * 0.36)))+ u = np.linspace(0, 1, n)+ u = np.clip(u + r.normal(0, 0.15 / n, n), 0, 1)+ peak = 0.5 - lean * 0.22+ env = np.where(u < peak, np.sin(np.pi / 2 * u / peak), np.cos(np.pi / 2 * (u - peak) / (1 - peak))) ** 0.7+ rad = h * (0.2 + 0.26 * env) * r.uniform(0.85, 1.15, n)+ bx = xl + rad[0] * 0.7 + u * (w - rad[0] * 0.7 - rad[-1] * 0.7)+ by = base - h * 0.95 * env + rad * 0.95+ by = np.minimum(by, base - rad * 0.25)+ xx = np.linspace(xl - 2, xr + 2, 360)+ top = np.full_like(xx, base); owner = np.full(len(xx), -1)+ for j in range(n):+ dy = np.sqrt(np.clip(rad[j] ** 2 - (xx - bx[j]) ** 2, 0, None))+ yv = np.where(dy > 0, by[j] - dy, 1e9)+ better = yv < top+ top[better] = yv[better]; owner[better] = j+ ok = top < base - 0.5+ xx, top, owner = xx[ok], top[ok], owner[ok]+ for j in range(n):+ idx = np.nonzero(owner == j)[0]+ if len(idx) < 3: continue+ seg = np.stack([xx[idx], top[idx]], 1)+ self.trek(seg[::2], width, 0.95, taper=(0.06, 0.3))+ k = np.linspace(0, 1, 30)+ bl = np.stack([xx[0] + 4 + (xx[-1] - xx[0] - 8) * k, base + np.sin(k * 9 + r.uniform(0, 6)) * h * 0.03], 1)+ cut = sorted(r.choice(np.arange(6, 24), 2, replace=False))+ for a_, b_ in ((0, cut[0]), (cut[0] + 2, cut[1]), (cut[1] + 2, 30)):+ if b_ - a_ > 2: self.trek(bl[a_:b_], width * 0.75, 0.7, taper=(0.25, 0.35))+ for j in r.choice(np.arange(1, n - 1), size=max(1, (n - 2) // 2), replace=False):+ rr = rad[j] * 0.62+ self.trek(arc(bx[j] + r.normal(0, rr * 0.2), by[j] + rad[j] * 0.5, rr, rr * 0.75, np.pi * 1.08, np.pi * 1.72, 10),+ width * 0.65, 0.65, taper=(0.15, 0.5), pounce=False)+ poly = np.vstack([np.stack([xx, top], 1)[::3], [[xx[-1], base], [xx[0], base]]])+ mid = base - h * 0.45+ low = np.stack([xx, np.maximum(top, mid + np.sin(xx * 0.035) * h * 0.07)], 1)[::3]+ lower = np.vstack([low, [[xx[-1], base], [xx[0], base]]])+ self.wash(poly, tone * 0.3, angle=0.0, pool=0.35, slip=1.2)+ self.wash(lower, tone * 0.8, angle=0.0, pool=0.45, slip=1.2, ragged=0.5, grad=((cx, mid), (cx, base), 0.3, 1.0))+ for kk in range(3):+ yv = base - 3 - kk * 4.5+ x0_ = xx[0] + w * (0.1 + 0.07 * kk) + r.normal(0, 6)+ x1_ = xx[-1] - w * (0.12 + 0.09 * kk) + r.normal(0, 6)+ self.trek([(x0_, yv), ((x0_ + x1_) / 2, yv - 1.0), (x1_, yv - 0.5)], 0.9, 0.55 - 0.1 * kk, pounce=False, taper=(0.3, 0.4))+ return poly++ def birds(self, pts, size=9.0, width=1.5, tilt=0.15):+ for (x, y) in pts:+ s = size * self.rng.uniform(0.7, 1.15)+ a = tilt + self.rng.normal(0, 0.12)+ c, sn = np.cos(a), np.sin(a)+ L = [(-s, -s * 0.15), (-s * 0.45, -s * 0.5), (0, 0)]+ R = [(0, 0), (s * 0.5, -s * 0.55), (s * 1.05, -s * 0.2)]+ for side in (L, R):+ P = [(x + px * c - py * sn, y + px * sn + py * c) for px, py in side]+ self.trek(P, width, 0.95, taper=(0.1, 0.5), pounce=False)++ def water(self, x0, x1, y0, y1, density=1.0, width=1.5, dens=0.8, far=3.5, near=11.0, avoid=None, waves=0.7):+ """ripples: short wavy dashes, finer and closer together toward the far bank"""+ r = self.rng+ y = y0 + 2+ while y < y1:+ f = (y - y0) / max(1, y1 - y0)+ gap = far + (near - far) * f ** 1.2+ x = x0 + r.uniform(0, 40)+ while x < x1:+ L = r.uniform(10, 26) + f * r.uniform(10, 50)+ if r.random() < 0.62 * density:+ xs = np.linspace(x, min(x1, x + L), 6)+ amp = waves * (1 + 2 * f) * r.uniform(0.5, 1.3)+ ys = y + np.sin(np.linspace(0, np.pi * r.uniform(1.5, 3), 6) + r.uniform(0, 6)) * amp+ if avoid is None or not np.any(avoid[np.clip(ys.astype(int), 0, self.H - 1), np.clip(xs.astype(int), 0, self.W - 1)] > 0.3):+ self.trek(np.stack([xs, ys], 1), width * (0.6 + 0.6 * f), dens * r.uniform(0.75, 1.05),+ taper=(0.25, 0.4), pounce=False, bead=0.1)+ x += L + r.uniform(8, 30) * (1.4 - f)+ y += gap * r.uniform(0.8, 1.2)++ def reflection(self, x, y, w, depth, step=5.0, width=1.4, dens=0.8):+ """a broken reflection under something standing at the water: stacked short dashes"""+ r = self.rng+ k = 0+ yy = y + 3+ while yy < y + depth:+ f = (yy - y) / depth+ ww = w * (1 - 0.5 * f) * r.uniform(0.6, 1.0)+ xc = x + r.normal(0, 3) + (k % 2) * 3+ self.trek([(xc - ww / 2, yy), (xc + ww / 2, yy + r.normal(0, 0.6))], width, dens * (1 - 0.55 * f),+ smooth=False, taper=(0.3, 0.3), pounce=False)+ yy += step * (1 + f); k += 1++ def grass(self, x0, x1, y, n=20, h=10.0, lean=0.3, width=1.2, dens=0.85, yspread=0.0):+ r = self.rng+ for _ in range(n):+ x = r.uniform(x0, x1); yb = y + r.uniform(-yspread, yspread) if np.isscalar(y) else np.interp(x, *y)+ if not np.isscalar(y): yb += r.uniform(-yspread, yspread)+ hh = h * r.uniform(0.6, 1.3)+ for k in range(r.integers(2, 5)):+ a = -np.pi / 2 + lean + (k - 1.5) * 0.35 + r.normal(0, 0.12)+ tip = (x + np.cos(a) * hh + lean * hh * 0.4, yb + np.sin(a) * hh)+ mid = (x + np.cos(a) * hh * 0.5, yb + np.sin(a) * hh * 0.55)+ self.trek([(x + k - 1.5, yb), mid, tip], width, dens, taper=(0.05, 0.7), pounce=False, bead=0.05)++ def tulip(self, x, y, h=60.0, lean=0.0, width=1.6, tone=0.22, leaves=2, wash=True):+ """a tulip on its stem (y = ground); lean > 0 bends it to the right"""+ r = self.rng+ top = (x + lean * h * 0.55, y - h)+ stem = [(x, y), (x + lean * h * 0.08, y - h * 0.45), (top[0] - lean * h * 0.08, top[1] + h * 0.2), top]+ s = h * 0.17+ ang = np.arctan2(*(np.array(top) - np.array(stem[2]))[::-1]) + np.pi / 2+ c, sn = np.cos(ang), np.sin(ang)+ def T(px, py): return (top[0] + px * c - py * sn, top[1] + px * sn + py * c)+ cup = [T(-s * 0.95, -s * 0.2), T(-s * 1.05, -s * 1.3), T(-s * 0.45, -s * 0.95), T(0, -s * 1.65),+ T(s * 0.45, -s * 0.95), T(s * 1.05, -s * 1.3), T(s * 0.95, -s * 0.2), T(0, s * 0.35)]+ outline = [cup[7], cup[0], cup[1], cup[2], cup[3], cup[4], cup[5], cup[6], cup[7]]+ self.trek([cup[0], T(-s * 1.05, -s * 0.8), cup[1]], width, taper=(0.1, 0.4))+ self.trek([cup[1], T(-s * 0.55, -s * 0.85), T(-s * 0.1, -s * 0.3)], width * 0.8, 0.8, taper=(0.1, 0.5))+ self.trek([cup[0], T(-s * 0.4, s * 0.3), cup[7], T(s * 0.4, s * 0.3), cup[6]], width)+ self.trek([cup[6], T(s * 1.05, -s * 0.8), cup[5]], width, taper=(0.1, 0.4))+ self.trek([cup[5], T(s * 0.55, -s * 0.85), T(s * 0.1, -s * 0.3)], width * 0.8, 0.8, taper=(0.1, 0.5))+ self.trek([T(-s * 0.5, -s * 0.6), T(-s * 0.2, -s * 1.3), cup[3], T(s * 0.2, -s * 1.3), T(s * 0.5, -s * 0.6)], width * 0.9)+ if wash:+ self.wash([cup[0], cup[1], cup[2], cup[3], cup[4], cup[5], cup[6], T(0, s * 0.35)], tone, angle=ang - np.pi / 2,+ pool=0.7, slip=0.8, band=5)+ self.wash([T(s * 0.15, -s * 1.2), cup[4], cup[5], cup[6], T(0, s * 0.35)], tone * 0.8, angle=ang, slip=0.6, band=4)+ self.occlude(outline, grow=0.6)+ self.trek(stem, width * 0.95, 0.95, taper=(0.05, 0.1))+ for k in range(leaves):+ side = -1 if k % 2 == 0 else 1+ yb = y - h * (0.05 + 0.18 * k)+ L = h * r.uniform(0.45, 0.6)+ tipx = x + side * L * 0.42 + lean * L * 0.6+ tipy = yb - L+ mid1 = (x + side * L * 0.32 + lean * L * 0.15, yb - L * 0.45)+ self.trek([(x + side, yb), mid1, (tipx, tipy)], width * 0.9, taper=(0.05, 0.6))+ mid2 = (x + side * L * 0.12 + lean * L * 0.3, yb - L * 0.55)+ self.trek([(x + side, yb + 2), mid2, (tipx, tipy)], width * 0.8, 0.85, taper=(0.05, 0.6))+ if wash:+ self.wash([(x + side, yb), mid1, (tipx, tipy), mid2], tone * 0.8, angle=-np.pi / 2, slip=0.7, band=4, pool=0.6)+ return outline++ def _scallops(self, C, clumps, n=220):+ """outer envelope of a union of circles seen from centre C: points, owner index per point"""+ th = np.linspace(-np.pi, np.pi, n, endpoint=False)+ ux, uy = np.cos(th), np.sin(th)+ best = np.zeros(n); own = np.full(n, -1)+ for j, (px, py, rad) in enumerate(clumps):+ dx, dy = px - C[0], py - C[1]+ b = ux * dx + uy * dy+ disc = b * b - (dx * dx + dy * dy - rad * rad)+ tt = np.where(disc >= 0, b + np.sqrt(np.clip(disc, 0, None)), 0)+ better = tt > best+ best[better] = tt[better]; own[better] = j+ return np.stack([C[0] + ux * best, C[1] + uy * best], 1), own, th++ def tree(self, x, y, h=150.0, w=None, lean=0.15, width=1.8, tone=0.2, clumps=7, trunk=None, seed=None):+ """a rounded Dutch tree: a crown of leaf clumps (outer scallops outlined, cusps between), leaf dabs+ crowding on the shade side, a wash dark toward lower right, trunk and forked branches below.+ lean > 0 = wind from the left. Returns the crown polygon."""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ w = w or h * 0.7+ tw = trunk or max(4.0, h * 0.06)+ C = (x + lean * h * 0.3, y - h * 0.6)+ rx, ry = w * 0.5, h * 0.33+ cl = [(C[0], C[1], min(rx, ry) * 0.62)]+ for j in range(clumps - 1):+ a = -np.pi + (j + r.uniform(0.2, 0.8)) * 2 * np.pi / (clumps - 1)+ rr = r.uniform(0.3, 0.42) * min(rx, ry) * 1.5+ px = C[0] + np.cos(a) * (rx - rr * 0.8) + lean * rr * 0.3 * (np.cos(a) > 0)+ py = C[1] + np.sin(a) * (ry - rr * 0.7)+ cl.append((px, py, rr))+ P, own, th = self._scallops(C, cl)+ # outline: one stroke per run of the same clump (lighter along the underside)+ runs, start = [], 0+ for k in range(1, len(own) + 1):+ if k == len(own) or own[k] != own[start]:+ runs.append((start, k)); start = k+ for a0, a1 in runs:+ if a1 - a0 < 3: continue+ seg = P[a0:a1 + 1] if a1 < len(P) else np.vstack([P[a0:a1], P[:1]])+ under = np.mean(np.sin(th[a0:min(a1, len(th) - 1)])) > 0.55+ self.trek(seg[::2] if len(seg) > 7 else seg, width * (0.7 if under else 1.0), 0.65 if under else 0.95, taper=(0.08, 0.3))+ # nested scallop rows inside the crown, on the shade side (light from the upper left)+ for sc in (0.7, 0.42):+ cl2 = [(C[0] + (px - C[0]) * sc + rx * 0.06, C[1] + (py - C[1]) * sc + ry * 0.08, rr * sc) for (px, py, rr) in cl]+ P2, own2, th2 = self._scallops(C, cl2, 160)+ start = 0+ for k in range(1, len(own2) + 1):+ if k == len(own2) or own2[k] != own2[start]:+ a0, a1 = start, k+ start = k+ if a1 - a0 < 4: continue+ mid = th2[(a0 + a1 - 1) // 2]+ if not (-0.5 < mid < 2.4) and r.random() < 0.8: continue+ seg = P2[a0:a1]+ self.trek(seg[::2] if len(seg) > 7 else seg, width * 0.6, 0.75, taper=(0.15, 0.45), pounce=False)+ # leaf dabs, mostly on the shade side+ for _ in range(int(w * h / 600)):+ a = r.uniform(0, 2 * np.pi); d = np.sqrt(r.uniform(0.05, 0.85))+ ux, uy = C[0] + np.cos(a) * d * rx * 0.85, C[1] + np.sin(a) * d * ry * 0.85+ lit = -(np.cos(a) * 0.6 + np.sin(a) * 0.8) * d+ if lit > 0.15 and r.random() < 0.75: continue+ cc = r.uniform(2.2, 4.2) * (w / 110) ** 0.5+ sa = r.uniform(-0.6, 0.6)+ self.trek(arc(ux, uy, cc, cc * 0.7, 0.3 + sa, 2.7 + sa, 5), width * 0.55, 0.7, taper=(0.1, 0.6), pounce=False)+ poly = P[::2]+ self.wash(poly, tone, angle=0.7, pool=0.6, slip=1.0, band=7, grad=((C[0] - rx, C[1] - ry), (C[0] + rx * 0.6, C[1] + ry), 0.35, 1.4))+ sh = [(px + rx * 0.12, py + ry * 0.14, rr * 0.8) for (px, py, rr) in cl] # second wash: the shade side+ P3, _, _ = self._scallops((C[0] + rx * 0.12, C[1] + ry * 0.14), sh, 120)+ self.wash(P3, tone * 0.6, angle=0.7, slip=0.8, pool=0.7, band=6, ragged=0.5,+ grad=((C[0] - rx * 0.5, C[1] - ry * 0.6), (C[0] + rx * 0.5, C[1] + ry * 0.7), 0.0, 1.2))+ self.occlude(poly, grow=1.0)+ # trunk and forked branches, behind the crown+ bend = lean * h * 0.22+ yc = C[1] + ry * 0.4+ self.trek([(x - tw / 2, y), (x - tw * 0.45 + bend * 0.5, y - h * 0.22), (x - tw * 0.3 + bend, yc)], width)+ self.trek([(x + tw / 2, y), (x + tw * 0.5 + bend * 0.5, y - h * 0.22), (x + tw * 0.3 + bend, yc)], width)+ self.hatch([(x - tw / 2, y), (x + tw / 2, y), (x + tw * 0.3 + bend, yc), (x - tw * 0.3 + bend, yc)],+ angle=-np.pi / 2 + 0.1, spacing=max(2.0, tw / 2.5), width=0.8, dens=0.65)+ for k, side in enumerate((-1, 1, -1)):+ yb = y - h * (0.3 + 0.06 * k)+ xb = x + bend * (0.4 + 0.1 * k)+ self.trek([(xb, yb), (xb + side * w * 0.12 + bend * 0.3, yb - h * 0.1), (xb + side * w * 0.2 + bend * 0.4, yb - h * 0.2)],+ width * 0.75, 0.9, taper=(0.05, 0.6))+ return poly++ def bushes(self, x0, x1, y, h=14.0, width=1.0, tone=0.14, gap=(), seed=None):+ """a distant row of trees and hedges: little scalloped humps on the horizon with a pale wash"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ x = x0+ while x < x1:+ n = int(r.integers(2, 5))+ cl = []+ for j in range(n):+ rr = h * r.uniform(0.35, 0.6)+ cl.append((x + j * h * 0.55, y - rr * r.uniform(0.6, 1.3), rr))+ xe = x + n * h * 0.55+ if not any(a <= x <= b or a <= xe <= b for a, b in gap):+ C = (x + (n - 1) * h * 0.27, y)+ P, own, th = self._scallops(C, cl, 120)+ top = P[np.sin(th) < -0.02]+ top = top[np.argsort(top[:, 0])]+ if len(top) > 3:+ self.trek(top[::2], width, 0.8, taper=(0.1, 0.3), pounce=False)+ self.wash(np.vstack([top, [[top[-1, 0], y], [top[0, 0], y]]]), tone, angle=0.0, slip=0.6, pool=0.4)+ if r.random() < 0.4:+ self.trek([(C[0], y), (C[0], y - h * 0.3)], width * 0.8, 0.7, smooth=False, pounce=False)+ x = xe + h * r.uniform(0.6, 3.0)++ def windmill(self, x, base, h, sails=0.35, squash=0.62, cloth=(0, 2), width=2.2, tone=0.16, gallery=True, door=True):+ """a smock mill with a stage: base = ground y, h = hub height above ground.+ sails = angle of the first arm (radians); squash < 1 turns the sail cross toward the left (3/4 view);+ cloth = which arms carry canvas. Returns the silhouette polygon."""+ r = self.rng+ bw, tw = h * 0.25, h * 0.125+ yb, yt = base - h * 0.17, base - h * 0.86+ hub = (x - h * 0.07, base - h * 0.95)+ R = h * 0.8+ # --- sails first (they are in front)+ cloth_polys = []+ for k in range(4):+ a = sails + k * np.pi / 2+ d = np.array([np.cos(a) * squash, np.sin(a)])+ pr = np.array([-np.sin(a) * squash, np.cos(a)])+ def S(s, o): return (hub[0] + d[0] * s + pr[0] * o, hub[1] + d[1] * s + pr[1] * o)+ s0, s1, ww = R * 0.17, R, R * 0.19+ frame = [S(s0, 2), S(s1, 2), S(s1, ww), S(s0 + R * 0.05, ww)]+ if k in cloth:+ cl = [S(s0 + R * 0.02, 2.5), S(s1 - R * 0.03, 2.5), S(s1 - R * 0.05, ww * 0.96), S(s0 + R * 0.08, ww * 0.94)]+ cloth_polys.append(cl)+ self.wash(cl, 0.22, angle=a, pool=0.5, slip=0.8, band=6)+ self.hatch(cl, angle=a, spacing=4.2, width=0.9, dens=0.7)+ self.trek([S(R * 0.06, 0), S(s1 + R * 0.04, 0)], width * 1.15, taper=(0.02, 0.15))+ self.trek([S(R * 0.06, -3.2), S(s1 + R * 0.02, -2.2)], width * 0.6, 0.8, taper=(0.05, 0.3))+ self.trek([frame[1], frame[2]], width * 0.8)+ self.trek([frame[2], frame[3]], width * 0.9)+ for j in range(1, 10):+ s = s0 + (s1 - s0) * j / 10+ self.trek([S(s, 1), S(s, ww * (0.95 if s > s0 + R * 0.05 else 0.6))], width * 0.55, 0.85, smooth=False, taper=(0.1, 0.2), pounce=False)+ self.trek([S(s0 + R * 0.04, ww * 0.5), S(s1, ww * 0.5)], width * 0.5, 0.75, taper=(0.1, 0.2), pounce=False)+ self.occlude([S(R * 0.05, -4), S(s1 + R * 0.04, -4), S(s1 + R * 0.04, 3.5), S(R * 0.05, 3.5)], grow=0.5)+ self.occlude([frame[1], frame[2], (frame[2][0] + 0.1, frame[2][1] + 0.1)], grow=1.6)+ self.occlude([frame[2], frame[3], (frame[3][0] + 0.1, frame[3][1])], grow=1.6)+ for cl in cloth_polys: self.occlude(cl, grow=0.8)+ # hub and cap+ self.trek(ellipse_pts(hub[0], hub[1], 5.5, 6.5), width, 1.05)+ self.wash(ellipse_pts(hub[0], hub[1], 5, 6), 0.5, pool=0.2, slip=0)+ self.occlude(ellipse_pts(hub[0], hub[1], 7, 8))+ cap = [(x - tw * 1.25, yt + 2), (x - tw * 1.1, yt - h * 0.07), (x - tw * 0.5, yt - h * 0.135), (x + tw * 0.3, yt - h * 0.145),+ (x + tw * 0.95, yt - h * 0.09), (x + tw * 1.2, yt + 2)]+ self.trek(cap, width, taper=(0.05, 0.1))+ self.trek([cap[0], (x, yt + 4), cap[-1]], width * 0.9)+ self.wash(cap + [(x, yt + 4)], tone * 1.6, angle=0.3, pool=0.6, grad=((x - tw, yt - h * 0.1), (x + tw, yt), 0.7, 1.3))+ self.hatch(cap + [(x, yt + 4)], angle=0.9, spacing=4.5, width=0.8, dens=0.6)+ # gallery (stage) in front of the smock+ sil = [(x - bw * 1.04, base), (x - bw * 1.04, yb), (x - tw, yt), (x + tw, yt), (x + bw * 1.04, yb), (x + bw * 1.04, base)]+ if gallery:+ yg = base - h * 0.36+ gw = h * 0.43+ half = lambda yy: tw + (bw - tw) * (yy - yt) / (yb - yt)+ self.trek([(x - gw, yg), (x + gw, yg)], width, smooth=False)+ self.trek([(x - gw, yg + 3.5), (x + gw, yg + 3.5)], width * 0.7, 0.85, smooth=False, pounce=False)+ yr = yg - h * 0.075+ self.trek([(x - gw, yr), (x - half(yr) - 1, yr)], width * 0.7, smooth=False)+ self.trek([(x + half(yr) + 1, yr), (x + gw, yr)], width * 0.7, smooth=False)+ for j in range(9):+ f = j / 8+ px = x - gw + 2 * gw * f+ if abs(px - x) < half(yr) - 2: continue+ self.trek([(px, yr), (px, yg)], width * 0.55, 0.9, smooth=False, pounce=False, bead=0)+ for sgn in (-1, 1):+ self.trek([(x + sgn * gw * 0.85, yg + 3), (x + sgn * half(yg + 40) * 0.98, yg + h * 0.17)], width * 0.75, smooth=False)+ self.trek([(x + sgn * gw * 0.45, yg + 3), (x + sgn * half(yg + 30) * 0.98, yg + h * 0.1)], width * 0.6, 0.9, smooth=False)+ self.wash([(x - gw, yg - 1), (x + gw, yg - 1), (x + gw, yg + 4.5), (x - gw, yg + 4.5)], 0.35, slip=0.5, pool=0.2)+ self.occlude([(x - gw - 1, yg - 1.5), (x + gw + 1, yg - 1.5), (x + gw + 1, yg + 5), (x - gw - 1, yg + 5)], grow=0.5)+ self.occlude([(x - gw, yr - 1), (x + gw, yr - 1), (x + gw, yr + 1.2), (x - gw, yr + 1.2)], grow=0.3)+ # door and windows+ if door:+ dw = bw * 0.32+ dp = [(x - dw, base), (x - dw, base - h * 0.1), (x - dw * 0.6, base - h * 0.125), (x, base - h * 0.132),+ (x + dw * 0.6, base - h * 0.125), (x + dw, base - h * 0.1), (x + dw, base)]+ self.trek(dp, width * 0.85)+ self.wash(dp, 0.42, angle=np.pi / 2, slip=0.6)+ self.occlude(dp)+ for (fy, fx) in ((0.55, -0.15), (0.7, 0.18), (0.25, 0.42)):+ yy = base - h * fy+ hw = tw + (bw - tw) * (yy - yt) / (yb - yt)+ wx = x + fx * hw+ q = [(wx - 4.5, yy - 6), (wx + 4.5, yy - 6), (wx + 4.5, yy + 6), (wx - 4.5, yy + 6)]+ self.closed(q, width * 0.7, smooth=False)+ self.wash(q, 0.5, slip=0.4, pool=0.1)+ self.occlude(q)+ # smock body: sides, thatch lines (denser on the shade side), brick base+ self.trek([(x - bw, yb), (x - (bw + tw) / 2 - 2, (yb + yt) / 2), (x - tw, yt)], width)+ self.trek([(x + bw, yb), (x + (bw + tw) / 2 + 2, (yb + yt) / 2), (x + tw, yt)], width)+ for f in np.linspace(-0.85, 0.85, 13):+ if f < -0.2 and r.random() < 0.55: continue+ p0 = (x + f * bw, yb - 2); p1 = (x + f * tw, yt + 3)+ self.trek([p0, _lerp(p0, p1, 0.5), p1], width * (0.45 + 0.25 * (f > 0.2)), 0.75 + 0.2 * (f > 0.2), taper=(0.1, 0.4), pounce=False)+ for f in (0.33, 0.66):+ yy = yb + (yt - yb) * f+ hw = tw + (bw - tw) * (yy - yt) / (yb - yt)+ self.line((x - hw, yy), (x + hw, yy + 1), width * 0.5, 0.6, bend=2, pounce=False)+ smock = [(x - bw, yb), (x - tw, yt), (x + tw, yt), (x + bw, yb)]+ self.wash(smock, tone, angle=-np.pi / 2, pool=0.5, grad=((x - bw, yb), (x + bw, yb), 0.6, 1.6))+ self.trek([(x - bw * 1.04, base), (x - bw * 1.04, yb), (x + bw * 1.04, yb), (x + bw * 1.04, base)], width, smooth=False, taper=(0.03, 0.05))+ base_q = [(x - bw * 1.04, base), (x - bw * 1.04, yb), (x + bw * 1.04, yb), (x + bw * 1.04, base)]+ self.wash(base_q, tone * 1.5, angle=0.0, pool=0.5, grad=((x - bw, base), (x + bw, base), 0.7, 1.4))+ for j in range(5):+ yy = base - (j + 0.5) * (base - yb) / 5+ for k in range(4):+ xx = x - bw + (k + 0.5 * (j % 2)) * bw * 0.5 + r.uniform(-2, 2)+ if xx > x + bw - 6: continue+ self.trek([(xx, yy), (xx + bw * 0.3, yy)], 0.9, 0.7, smooth=False, pounce=False, taper=(0.2, 0.3))+ self.occlude(sil + [(x + bw, base)])+ self.occlude(cap)+ return sil++ def house(self, x0, x1, base, wall, gable='step', gable_h=None, floors=3, cols=None, door=0.5, chimney=None,+ hoist=True, width=1.9, tone=0.1, shade=None, vane=None, smoke=None):+ """a canal house: facade x0..x1 from `base` up `wall` px, then a gable ('step', 'bell', 'neck', 'spout').+ chimney = x of a chimney on the roof behind; smoke = (dx, dy) drift of its smoke; vane = draw a cockerel+ weathervane on the top pointing into the wind (-1 = wind from the left). Returns the silhouette."""+ r = self.rng+ W = x1 - x0+ gh = gable_h or W * 0.75+ top = base - wall+ cx = (x0 + x1) / 2+ if gable == 'step':+ n = 3 if W < 110 else 4+ sw = W * 0.38 / n; sh = gh / (n + 0.6)+ L = [(x0, base), (x0, top)]+ xx, yy = x0, top+ for j in range(n):+ L += [(xx, yy - sh), (xx + sw, yy - sh)]; xx += sw; yy -= sh+ L += [(xx, yy - sh * 0.6)]+ Rr = [(x1 - (pt[0] - x0), pt[1]) for pt in L[::-1]]+ sil = L + Rr[1:]+ elif gable == 'bell':+ sil = [(x0, base), (x0, top), (x0 + W * 0.04, top - gh * 0.35), (x0 + W * 0.2, top - gh * 0.62), (x0 + W * 0.25, top - gh * 0.9),+ (cx - W * 0.18, top - gh * 0.98), (cx, top - gh * 1.12), (cx + W * 0.18, top - gh * 0.98), (x1 - W * 0.25, top - gh * 0.9),+ (x1 - W * 0.2, top - gh * 0.62), (x1 - W * 0.04, top - gh * 0.35), (x1, top), (x1, base)]+ elif gable == 'neck':+ nw = W * 0.24+ sil = [(x0, base), (x0, top), (x0 + W * 0.08, top - gh * 0.08), (x0 + W * 0.14, top - gh * 0.38), (cx - nw, top - gh * 0.42),+ (cx - nw, top - gh * 0.95), (cx, top - gh * 1.12), (cx + nw, top - gh * 0.95), (cx + nw, top - gh * 0.42),+ (x1 - W * 0.14, top - gh * 0.38), (x1 - W * 0.08, top - gh * 0.08), (x1, top), (x1, base)]+ else: # spout: plain pointed gable+ sil = [(x0, base), (x0, top), (cx - W * 0.12, top - gh * 0.9), (cx, top - gh), (cx + W * 0.12, top - gh * 0.9), (x1, top), (x1, base)]+ peak = min(sil, key=lambda q: q[1])+ # weathervane / smoke first (in front of the sky)+ if vane:+ vx, vy = peak[0], peak[1]+ self.trek([(vx, vy), (vx, vy - 30)], 1.3, smooth=False)+ d = -1 if vane < 0 else 1+ arrow = [(vx + d * 15, vy - 22), (vx - d * 13, vy - 22)]+ self.trek(arrow, 1.2, smooth=False)+ self.trek([(vx + d * 15, vy - 22), (vx + d * 10, vy - 25)], 1.1, smooth=False)+ self.trek([(vx + d * 15, vy - 22), (vx + d * 10, vy - 19)], 1.1, smooth=False)+ ck = [(vx - d * 2, vy - 26), (vx + d * 4, vy - 33), (vx + d * 7, vy - 31), (vx + d * 5, vy - 27), (vx + d * 1, vy - 25),+ (vx - d * 6, vy - 29), (vx - d * 9, vy - 36), (vx - d * 9, vy - 27), (vx - d * 3, vy - 24)]+ self.closed(ck, 1.1)+ self.wash(ck, 0.6, pool=0.2, slip=0)+ self.dot(vx, vy - 30.5, 1.6)+ # outline+ self.trek(sil[1:-1], width, taper=(0.02, 0.05), smooth=False)+ self.trek([sil[0], sil[1]], width, smooth=False); self.trek([sil[-2], sil[-1]], width, smooth=False)+ self.trek([(x0 - 2, base), (x1 + 2, base)], width * 0.9, smooth=False)+ if gable == 'step':+ self.trek([(x0 + 1, top + 4), (x1 - 1, top + 4)], width * 0.6, 0.85, smooth=False, pounce=False)+ # windows+ cols = cols or (2 if W < 100 else 3)+ fh = (wall - 8) / floors+ win = []+ for fl in range(floors):+ yy0 = base - fh * (fl + 1) + fh * 0.22+ yy1 = base - fh * fl - fh * 0.18+ for c in range(cols):+ if fl == 0 and door is not None and abs((c + 0.5) / cols - door) < 0.5 / cols: continue+ wx0 = x0 + W * (c + 0.22) / cols; wx1 = x0 + W * (c + 0.78) / cols+ q = [(wx0, yy0), (wx1, yy0), (wx1, yy1), (wx0, yy1)]+ win.append(q)+ gy0 = top - gh * 0.55; gy1 = top - gh * 0.12+ if gh > 40:+ win.append([(cx - W * 0.1, gy0), (cx + W * 0.1, gy0), (cx + W * 0.1, gy1), (cx - W * 0.1, gy1)])+ for q in win:+ self.closed(q, width * 0.7, smooth=False, bead=0.1)+ mx, my = (q[0][0] + q[1][0]) / 2, (q[0][1] + q[2][1]) / 2+ self.trek([(mx, q[0][1]), (mx, q[2][1])], width * 0.5, 0.9, smooth=False, pounce=False)+ self.trek([(q[0][0], my - 1), (q[1][0], my - 1)], width * 0.5, 0.9, smooth=False, pounce=False)+ self.wash(q, 0.36, angle=np.pi / 2, slip=0.6, pool=0.4, holes=[[(mx - 1, my), (q[1][0] - 2, my), (q[1][0] - 2, q[2][1] - 2), (mx - 1, q[2][1] - 2)]])+ self.occlude(q, grow=0.4)+ if door is not None:+ dx = x0 + W * door+ dwid = W * 0.13+ dq = [(dx - dwid, base), (dx - dwid, base - fh * 0.75), (dx, base - fh * 0.85), (dx + dwid, base - fh * 0.75), (dx + dwid, base)]+ self.trek(dq, width * 0.8)+ self.wash(dq, 0.45, angle=np.pi / 2, slip=0.6)+ self.occlude(dq)+ self.trek([(dx - dwid - 4, base - 1), (dx + dwid + 4, base - 1)], width * 0.7, smooth=False, pounce=False)+ if hoist:+ hy = peak[1] + gh * 0.28 if gable != 'neck' else top - gh * 0.78+ self.trek([(cx, hy), (cx, hy - 5), (cx + 9, hy - 5)], 1.4, smooth=False)+ self.trek([(cx + 9, hy - 5), (cx + 9, hy + 3)], 0.9, 0.8, smooth=False, pounce=False)+ # brick: scattered short courses, more on the shade side+ for _ in range(int(W * wall / 380)):+ bx = r.uniform(x0 + 4, x1 - 12); by = r.uniform(top + 4, base - 4)+ if shade == 'right' and bx < cx and r.random() < 0.5: continue+ self.trek([(bx, by), (bx + r.uniform(6, 12), by)], 0.85, 0.6, smooth=False, pounce=False, taper=(0.3, 0.3))+ self.wash(sil, tone, angle=np.pi / 2, pool=0.55, slip=1.0)+ if shade == 'right':+ self.hatch([(x1 - W * 0.18, base), (x1 - W * 0.18, top), (x1, top), (x1, base)], angle=np.pi / 2, spacing=3.6, width=0.8, dens=0.6)+ if chimney is not None:+ chy = peak[1] + gh * 0.25+ q = [(chimney - 5, chy + 14), (chimney - 5, chy - 10), (chimney + 5, chy - 10), (chimney + 5, chy + 14)]+ self.closed(q[:4], 1.4, smooth=False)+ self.wash(q, 0.3, slip=0.4)+ if smoke:+ self.smoke(chimney, chy - 12, *smoke)+ self.occlude(sil)+ return sil++ def sailboat(self, x, water, length, facing=1, mast=None, belly=0.35, width=2.0, tone=0.2,+ cargo=6, skipper=True, pennant=1, leeboard=True):+ """a Dutch sailing barge (tjalk): round bluff hull, leeboard, gaff mainsail and jib, pennant.+ x = stern, facing = +1 sails to the right. Returns the hull polygon (occlude water with it)."""+ r = self.rng+ f = facing+ L = length+ H0 = L * 0.15+ mast = mast or L * 1.05+ def P(u, v): return (x + f * u, water - v)+ hull_top = [P(-L * 0.02, H0 * 1.15), P(L * 0.12, H0 * 0.98), P(L * 0.5, H0 * 0.88), P(L * 0.86, H0 * 1.02), P(L * 1.0, H0 * 1.35)]+ hull_bot = [P(L * 1.0, H0 * 1.35), P(L * 0.99, H0 * 0.6), P(L * 0.93, 0), P(L * 0.5, -H0 * 0.05), P(L * 0.08, 0), P(-L * 0.02, H0 * 0.5),+ P(-L * 0.02, H0 * 1.15)]+ hull = hull_top + hull_bot[1:]+ mx = L * 0.58+ mtop = P(mx, H0 + mast)+ mfoot = P(mx, H0 * 0.9)+ # pennant streaming downwind+ if pennant:+ k = np.linspace(0, 1, 12)+ pp = np.stack([mtop[0] + pennant * k * L * 0.22, mtop[1] + 2 + np.sin(k * 7) * 3 * k], 1)+ self.trek(pp, 1.6, taper=(0.02, 0.7))+ self.trek(pp + [0, 3.5], 1.1, 0.8, taper=(0.02, 0.7), pounce=False)+ # mainsail (gaff): luff on the mast, foot on the boom, gaff up to the peak; bellied leech+ boom_y = H0 * 1.55+ luff0, luff1 = P(mx, boom_y), P(mx, H0 + mast * 0.8)+ clew = P(mx - L * 0.56, boom_y + L * 0.02)+ peak = P(mx - L * 0.3, H0 + mast * 1.08)+ b = belly * L * 0.12+ leech = [peak, (peak[0] - f * b * 0.4, (peak[1] * 2 + clew[1]) / 3), (clew[0] - f * b * 0.5, (peak[1] + 2 * clew[1]) / 3), clew]+ sail = [luff0, luff1] + leech + [clew]+ foot = [clew, ((clew[0] + luff0[0]) / 2, luff0[1] + b * 0.4), luff0]+ # jib+ jtop = P(mx, H0 + mast * 0.8)+ jtack = P(L * 0.99, H0 * 1.4)+ jclew = P(mx + L * 0.12, H0 * 1.9)+ jib = [jtop, (jtop[0] + f * (b * 0.5 + 6), (jtop[1] + jtack[1]) / 2), jtack, jclew]+ # skipper at the tiller (in front of the sail foot)+ if skipper:+ sx, sy = P(L * 0.06, H0 * 1.0)+ self._skipper(sx, sy, L * 0.16, f)+ self.trek([P(-L * 0.02, H0 * 1.2), P(-L * 0.1, H0 * 1.6)], width * 0.9, smooth=False) # tiller+ # sails+ self.trek([luff1, peak], width * 1.1, smooth=False) # gaff+ self.trek(leech, width)+ self.trek(foot, width * 0.9)+ self.trek([clew, P(mx + L * 0.02, boom_y - 1)], width * 1.1, smooth=False) # boom+ self.wash(sail, tone * 0.7, angle=-np.pi / 2 + 0.2 * f, pool=0.6, slip=1.0,+ grad=(luff1, clew, 0.6, 1.25))+ for j in range(1, 7):+ u = j / 7+ a0 = _lerp(luff0, luff1, u)+ a1 = _lerp(clew, peak, u)+ m = ((a0[0] + a1[0]) / 2 - f * b * 0.55 * np.sin(np.pi * u) * 0.7, (a0[1] + a1[1]) / 2 + 4)+ self.trek([a0, m, a1], 0.9, 0.55, taper=(0.2, 0.3), pounce=False)+ self.trek(jib + [jtop], width * 0.9)+ self.wash(jib, tone * 0.6, angle=0.3 * f, slip=0.8, pool=0.6)+ self.occlude(sail, grow=1.0); self.occlude(jib, grow=1.0)+ # mast and rigging+ self.trek([mfoot, (mtop[0], mtop[1] - 4)], width * 1.2, smooth=False, taper=(0.02, 0.1))+ self.trek([mtop, P(L * 1.04, H0 * 1.4)], 0.9, 0.8, smooth=False, pounce=False)+ self.trek([mtop, P(-L * 0.01, H0 * 1.15)], 0.9, 0.8, smooth=False, pounce=False)+ self.occlude([(mfoot[0] - 2.5, mfoot[1]), (mfoot[0] + 2.5, mfoot[1]), (mtop[0] + 2.5, mtop[1]), (mtop[0] - 2.5, mtop[1])])+ # cargo: sacks on deck+ for j in range(cargo):+ u = 0.2 + 0.07 * j + (0.12 if 0.2 + 0.07 * j > 0.5 else 0)+ if u > 0.88: break+ gx, gy = P(L * u, H0 * 0.92)+ sw_, sh_ = L * 0.032, L * 0.05+ sk = [(gx - sw_, gy), (gx - sw_ * 1.05, gy - sh_ * 0.55), (gx - sw_ * 0.6, gy - sh_ * 0.95), (gx - sw_ * 0.15, gy - sh_ * 1.12),+ (gx + sw_ * 0.2, gy - sh_ * 1.0), (gx + sw_ * 0.7, gy - sh_ * 0.9), (gx + sw_ * 1.05, gy - sh_ * 0.5), (gx + sw_, gy)]+ self.trek(sk, 1.3, 0.95, taper=(0.05, 0.1))+ self.trek([(gx - sw_ * 0.45, gy - sh_ * 0.95), (gx - sw_ * 0.1, gy - sh_ * 0.82), (gx + sw_ * 0.35, gy - sh_ * 0.92)], 0.9, 0.8, pounce=False)+ self.wash(sk, 0.1, slip=0.5, pool=0.6)+ self.occlude(sk)+ if leeboard:+ lc = P(L * 0.66, H0 * 0.9)+ lb = [(lc[0] - f * L * 0.022, lc[1] - 3), (lc[0] + f * L * 0.022, lc[1] - 3), (lc[0] + f * L * 0.075, lc[1] + H0 * 0.9),+ (lc[0] + f * L * 0.03, lc[1] + H0 * 0.98), (lc[0] - f * L * 0.03, lc[1] + H0 * 0.98), (lc[0] - f * L * 0.075, lc[1] + H0 * 0.9)]+ self.trek(lb + [lb[0]], width * 0.9)+ self.wash(lb, 0.16, slip=0.5, pool=0.7, angle=np.pi / 2)+ self.dot(lc[0], lc[1] + 2, 1.8)+ for j in (-0.55, 0.0, 0.55): # planks fanning out+ self.trek([(lc[0] + f * L * 0.012 * j, lc[1] + 4), (lc[0] + f * L * 0.07 * j, lc[1] + H0 * 0.92)], 0.8, 0.7, smooth=False, pounce=False)+ self.occlude(lb)+ # hull+ self.trek(hull_top, width * 1.1, taper=(0.02, 0.05))+ self.trek(hull_bot, width, taper=(0.02, 0.05))+ self.trek([P(-L * 0.01, H0 * 0.75), P(L * 0.5, H0 * 0.45), P(L * 0.97, H0 * 0.85)], width * 0.7, 0.9, pounce=False)+ self.wash(hull, tone * 2.0, angle=0.0, pool=0.5, holes=[[P(0, H0 * 0.98), P(L * 0.5, H0 * 0.8), P(L * 0.95, H0 * 1.12), P(L * 0.95, H0 * 0.92), P(L * 0.5, H0 * 0.55), P(0, H0 * 0.78)]])+ self.hatch(hull_bot, angle=0.0, spacing=3.4, width=0.8, dens=0.7)+ self.occlude(hull)+ return hull++ def _skipper(self, x, y, h, f=1):+ """a small figure standing at the tiller (feet hidden by the bulwark)"""+ hy = y - h+ self.trek(ellipse_pts(x, hy, h * 0.11, h * 0.12, 0, 16), 1.4)+ hat = [(x - h * 0.2, hy - h * 0.05), (x + h * 0.2, hy - h * 0.07)]+ self.trek(hat, 1.6, smooth=False)+ self.trek([(x - h * 0.1, hy - h * 0.06), (x - h * 0.07, hy - h * 0.2), (x + h * 0.08, hy - h * 0.2), (x + h * 0.1, hy - h * 0.07)], 1.4)+ body = [(x - h * 0.16, y), (x - h * 0.13, hy + h * 0.2), (x + h * 0.13, hy + h * 0.2), (x + h * 0.18, y)]+ self.trek(body, 1.5)+ self.wash(body, 0.35, slip=0.5)+ self.trek([(x + f * h * 0.1, hy + h * 0.3), (x - f * h * 0.15, hy + h * 0.5), (x - f * h * 0.32, hy + h * 0.55)], 1.3)+ self.occlude(body + [(x, hy - h * 0.25)])++ def smoke(self, x, y, dx, dy, puffs=7, width=1.3):+ """smoke from a chimney blown downwind: a chain of growing curls that fade"""+ for k in range(puffs):+ f = k / max(1, puffs - 1)+ px = x + dx * f + np.sin(f * 7) * 3+ py = y + dy * f - 4 * f+ rr = 2.5 + 6 * f+ a0 = np.pi * (0.75 + 0.2 * np.sin(k))+ self.trek(arc(px, py, rr * 1.25, rr, a0, a0 + np.pi * 1.35, 10), width * (1 - 0.4 * f), 0.9 - 0.45 * f,+ taper=(0.1, 0.5), pounce=False)++ # ------------------------------------------------------------ single tiles: corners, medallion, small motifs+ def corner(self, x, y, sx, sy, style='spin', size=24.0, width=1.5):+ """a quarter ornament in the tile corner at (x, y); (sx, sy) = ±1 points into the tile.+ Four tiles meeting at a joint build the whole ornament between them."""+ d = np.array([sx, sy], np.float32) / np.sqrt(2)+ q = np.array([-d[1], d[0]])+ def P(a, b): return (x + d[0] * a + q[0] * b, y + d[1] * a + q[1] * b)+ s = size+ if style == 'spin': # 'spider': a leaf on the diagonal, curling tendrils, dots+ leaf = [P(s * 0.12, 0), P(s * 0.4, s * 0.16), P(s * 0.78, 0), P(s * 0.4, -s * 0.16)]+ self.trek(leaf + [leaf[0]], width)+ self.wash(leaf, 0.42, slip=0.3, pool=0.3, ragged=0.15)+ self.trek([P(s * 0.78, 0), P(s * 0.92, 0)], width * 0.7, pounce=False)+ for sg in (-1, 1):+ self.trek([P(s * 0.08, sg * s * 0.08), P(s * 0.2, sg * s * 0.42), P(s * 0.42, sg * s * 0.5), P(s * 0.5, sg * s * 0.36),+ P(s * 0.4, sg * s * 0.3)], width * 0.85, taper=(0.1, 0.5))+ self.dot(*P(s * 0.66, sg * s * 0.28), r=width * 0.75)+ self.trek(arc(x, y, s * 0.2, s * 0.2, np.arctan2(d[1], d[0]) - 0.8, np.arctan2(d[1], d[0]) + 0.8, 8), width * 0.8)+ elif style == 'lelie': # a quarter fleur-de-lis+ self.trek([P(s * 0.05, 0), P(s * 0.85, 0)], width)+ for sg in (-1, 1):+ self.trek([P(s * 0.3, 0), P(s * 0.35, sg * s * 0.3), P(s * 0.6, sg * s * 0.38), P(s * 0.62, sg * s * 0.18)], width * 0.85)+ self.wash([P(s * 0.5, -s * 0.1), P(s * 0.85, 0), P(s * 0.5, s * 0.1)], 0.45, slip=0.2)+ else: # 'dot': a plain quarter circle with a dot+ self.trek(arc(x, y, s * 0.35, s * 0.35, np.arctan2(d[1], d[0]) - 0.8, np.arctan2(d[1], d[0]) + 0.8, 10), width)+ self.dot(*P(s * 0.55, 0), r=width)++ def medallion(self, i, k, r=None, width=1.4, tendrils=True):+ cx, cy = self.centre(i, k)+ hs = (self.p - self.joint) / 2+ r = r or hs * 0.72+ self.trek(ellipse_pts(cx, cy, r, r, self.rng.uniform(0, 6), 64), width, 0.95, taper=(0.02, 0.02))+ self.trek(ellipse_pts(cx, cy, r - 3.6, r - 3.6, self.rng.uniform(0, 6), 64), width * 0.7, 0.8, taper=(0.02, 0.02), pounce=False)+ if tendrils:+ for a in (np.pi / 4, 3 * np.pi / 4, 5 * np.pi / 4, 7 * np.pi / 4):+ bx, by = cx + np.cos(a) * r, cy + np.sin(a) * r+ ox, oy = np.cos(a), np.sin(a)+ self.trek([(bx, by), (bx + ox * 6 - oy * 4, by + oy * 6 + ox * 4), (bx + ox * 9, by + oy * 9)], width * 0.8, 0.9, taper=(0.05, 0.5))+ return cx, cy, r++ def vignette(self, i, k, kind, mirror=False, scale=1.0, width=1.35):+ """a small motif in the centre of a single tile: 'tulip', 'ship', 'mill', 'boat', 'fish', 'bird', 'house', 'pot'"""+ cx, cy = self.centre(i, k)+ s = (self.p - self.joint) / 2 * 0.62 * scale+ m = -1 if mirror else 1+ r = self.rng+ def P(u, v): return (cx + m * u * s, cy + v * s)+ w = width+ if kind == 'tulip':+ self.tulip(cx, cy + s * 0.75, s * 1.35, lean=m * 0.1, width=w, tone=0.22, leaves=2)+ self.trek([P(-0.6, 0.78), P(0, 0.68), P(0.6, 0.8)], w * 0.9, pounce=False)+ self.grass(cx - s * 0.6, cx + s * 0.6, cy + s * 0.78, n=3, h=s * 0.18, width=w * 0.7)+ elif kind == 'pot':+ pot = [P(-0.38, 0.25), P(0.38, 0.25), P(0.28, 0.85), P(-0.28, 0.85)]+ self.trek(pot + [pot[0]], w, smooth=False)+ self.trek([P(-0.42, 0.25), P(0.42, 0.25)], w * 1.4, smooth=False)+ self.wash(pot, 0.3, slip=0.5)+ self.occlude(pot)+ for j, (u, hh, ln) in enumerate(((-0.35, 0.95, -0.25), (0.0, 1.15, 0.0), (0.35, 0.9, 0.25))):+ self.tulip(cx + m * u * s * 0.4, cy + s * 0.25, s * hh, lean=m * ln, width=w * 0.85, tone=0.22, leaves=1 if j != 1 else 2)+ elif kind == 'ship':+ hull = [P(-0.75, 0.25), P(0.75, 0.2), P(0.6, 0.45), P(-0.55, 0.45)]+ self.trek(hull + [hull[0]], w)+ self.wash(hull, 0.35, slip=0.5)+ self.occlude(hull)+ for u, hgt in ((-0.4, 0.85), (0.05, 1.05), (0.45, 0.8)):+ for j in range(2):+ y0 = 0.15 - hgt * (0.25 + 0.38 * j); y1 = y0 + hgt * 0.32+ sq = [P(u - 0.17, y0), P(u + 0.17, y0), P(u + 0.2, y1), P(u - 0.2, y1)]+ self.trek([sq[0], sq[1], (sq[2][0] + m * 2, (sq[1][1] + sq[2][1]) / 2), sq[2], sq[3], (sq[3][0] + m * 2, (sq[0][1] + sq[3][1]) / 2), sq[0]], w * 0.8)+ self.wash(sq, 0.12, slip=0.4)+ self.occlude(sq)+ self.trek([P(u, 0.25), P(u, 0.15 - hgt)], w * 0.9, smooth=False)+ self.trek([P(u, 0.15 - hgt), P(u + 0.14, 0.18 - hgt)], w * 0.8, smooth=False, pounce=False)+ self.water(cx - s * 0.85, cx + s * 0.85, cy + s * 0.5, cy + s * 0.75, width=w * 0.8, far=4, near=6)+ elif kind == 'boat':+ hull = [P(-0.55, 0.3), P(0.6, 0.25), P(0.45, 0.48), P(-0.45, 0.48)]+ sail = [P(-0.05, 0.2), P(-0.05, -0.75), P(-0.55, -0.62), P(-0.5, 0.18)]+ self.trek(sail + [sail[0]], w); self.wash(sail, 0.14, slip=0.4); self.occlude(sail)+ self.trek([P(0.0, 0.25), P(0.0, -0.85)], w, smooth=False)+ self.trek([P(0.0, -0.75), P(0.55, 0.22)], w * 0.7, smooth=False, pounce=False)+ self.trek(hull + [hull[0]], w); self.wash(hull, 0.35, slip=0.4); self.occlude(hull)+ self.water(cx - s * 0.8, cx + s * 0.8, cy + s * 0.5, cy + s * 0.75, width=w * 0.8, far=4, near=6)+ elif kind == 'fish':+ body = ellipse_pts(cx, cy, s * 0.55, s * 0.24, m * -0.35, 30)+ self.closed(body, w)+ tail = [P(0.48, -0.15), P(0.85, -0.45), P(0.78, -0.05), P(0.9, 0.2)]+ self.trek(tail + [P(0.48, -0.15)], w)+ self.wash(body, 0.2, slip=0.4, grad=((cx, cy - s * 0.3), (cx, cy + s * 0.3), 1.4, 0.4))+ self.dot(*P(-0.33, 0.08), r=w * 0.9)+ self.trek([P(-0.2, -0.08), P(-0.15, 0.08), P(-0.22, 0.2)], w * 0.7, pounce=False)+ self.water(cx - s * 0.8, cx + s * 0.8, cy + s * 0.45, cy + s * 0.75, width=w * 0.8, far=4, near=6)+ elif kind == 'bird':+ self.trek([P(-0.8, 0.35), P(-0.1, 0.25), P(0.7, 0.4)], w * 1.1)+ for u in (-0.55, 0.45):+ self.trek(arc(*P(u, 0.32), s * 0.12, s * 0.08, 3.6, 5.6, 6), w * 0.7, pounce=False)+ body = [P(-0.35, 0.05), P(-0.15, -0.3), P(0.2, -0.32), P(0.38, -0.1), P(0.2, 0.15), P(-0.1, 0.2)]+ self.closed(body, w)+ self.wash(body, 0.18, slip=0.4)+ self.trek([P(0.2, -0.32), P(0.32, -0.55), P(0.45, -0.5), P(0.43, -0.3)], w)+ self.trek([P(0.45, -0.48), P(0.6, -0.45)], w, smooth=False)+ self.dot(*P(0.37, -0.45), r=w * 0.7)+ self.trek([P(-0.35, 0.05), P(-0.7, -0.05), P(-0.62, 0.12)], w * 0.9)+ self.trek([P(-0.05, -0.15), P(0.2, -0.05), P(0.05, 0.1)], w * 0.7, pounce=False)+ self.trek([P(0.0, 0.2), P(0.0, 0.3)], w * 0.7, smooth=False); self.trek([P(0.1, 0.18), P(0.12, 0.29)], w * 0.7, smooth=False)+ elif kind == 'house':+ self.house(cx + m * s * 0.05 - s * 0.35, cx + m * s * 0.05 + s * 0.35, cy + s * 0.55, s * 0.55, gable='step',+ gable_h=s * 0.5, floors=2, cols=2, door=0.5, width=w, hoist=False, tone=0.08)+ self.tree(cx - m * s * 0.62, cy + s * 0.58, s * 1.0, w=s * 0.6, lean=0, width=w * 0.8, tone=0.18, clumps=3)+ self.trek([P(-0.85, 0.6), P(0.85, 0.56)], w * 0.9, pounce=False)+ elif kind == 'mill':+ self.windmill(cx + m * s * 0.1, cy + s * 0.6, s * 1.0, sails=r.uniform(0, 1.5), squash=0.85, width=w, tone=0.12,+ gallery=False, door=True)+ self.trek([P(-0.85, 0.62), P(0.85, 0.58)], w * 0.9, pounce=False)+ self.grass(cx - s * 0.8, cx + s * 0.8, cy + s * 0.62, n=3, h=s * 0.15, width=w * 0.7)+ self.birds([P(-0.6, -0.55)], size=s * 0.12, width=w * 0.9)+ self.clear_occlusion()++ def field(self, tiles=None, corners='spin', size=None, medallion=True, motifs=('tulip', 'ship', 'mill', 'boat', 'fish', 'bird', 'house', 'pot'),+ width=1.4, skip=()):+ """paint every tile outside the tableaux as a single tile: corner quarters, a medallion and a small motif"""+ tiles = tiles if tiles is not None else [t for t in self.visible() if not self.in_tableau(*t) and t not in skip]+ size = size or self.p * 0.24+ r = self.rng+ chosen = {}+ for (i, k) in tiles:+ x0, y0, x1, y1 = self.rect(i, k)+ for (cx, cy, sx, sy) in ((x0, y0, 1, 1), (x1, y0, -1, 1), (x0, y1, 1, -1), (x1, y1, -1, -1)):+ self.corner(cx - sx * self.joint / 2, cy - sy * self.joint / 2, sx, sy, corners, size, width)+ if medallion: self.medallion(i, k, width=width)+ near = {chosen.get((i - 1, k)), chosen.get((i, k - 1)), chosen.get((i - 1, k - 1)), chosen.get((i + 1, k - 1))}+ kinds = [m for m in motifs if m not in near] or list(motifs)+ kind = kinds[int(r.integers(len(kinds)))]+ chosen[(i, k)] = kind+ self.vignette(i, k, kind, mirror=bool(r.random() < 0.5), width=width)++ def border(self, rect, band=34.0, inset=9.0, width=2.6, tone=0.42, leaf=26.0, reserve=None):+ """a painted frame round a tableau: outer and inner rules, a blue band with a white (reserved) vine+ of leaves and berries, rosettes in the corners. reserve = extra polygons kept white (a cartouche)."""+ X0, Y0, X1, Y1 = rect+ a0 = (X0 + inset, Y0 + inset, X1 - inset, Y1 - inset)+ a1 = (a0[0] + band, a0[1] + band, a0[2] - band, a0[3] - band)+ holes = list(reserve or [])+ r = self.rng+ mid = band / 2+ sides = [((a0[0] + band, a0[1] + mid), (a0[2] - band, a0[1] + mid)), ((a0[2] - mid, a0[1] + band), (a0[2] - mid, a0[3] - band)),+ ((a0[2] - band, a0[3] - mid), (a0[0] + band, a0[3] - mid)), ((a0[0] + mid, a0[3] - band), (a0[0] + mid, a0[1] + band))]+ leaves = []+ for (p0, p1) in sides:+ L = np.hypot(p1[0] - p0[0], p1[1] - p0[1])+ ux, uy = (p1[0] - p0[0]) / L, (p1[1] - p0[1]) / L+ nx, ny = -uy, ux+ n = int(L / leaf)+ t = np.linspace(0, L, n * 8 + 1)+ amp = band * 0.16+ vine = np.stack([p0[0] + ux * t + nx * np.sin(t / leaf * np.pi) * amp, p0[1] + uy * t + ny * np.sin(t / leaf * np.pi) * amp], 1)+ leaves.append(('vine', vine))+ for j in range(n):+ tc = (j + 0.5) * leaf+ side = 1 if j % 2 == 0 else -1+ bx, by = p0[0] + ux * tc + nx * side * amp, p0[1] + uy * tc + ny * side * amp+ ang = np.arctan2(uy, ux) + side * 0.9+ ca, sa = np.cos(ang), np.sin(ang)+ ll = band * 0.36+ lf = [(bx, by), (bx + ca * ll * 0.5 - sa * ll * 0.22, by + sa * ll * 0.5 + ca * ll * 0.22), (bx + ca * ll, by + sa * ll),+ (bx + ca * ll * 0.5 + sa * ll * 0.22, by + sa * ll * 0.5 - ca * ll * 0.22)]+ leaves.append(('leaf', lf))+ bx2, by2 = p0[0] + ux * (tc + leaf * 0.5) - nx * side * amp * 1.6, p0[1] + uy * (tc + leaf * 0.5) - ny * side * amp * 1.6+ if j < n - 1: leaves.append(('berry', (bx2, by2)))+ vine_polys = []+ for kind, g in leaves:+ if kind == 'vine':+ P = np.asarray(g); nr = _normals(P)+ vine_polys.append(np.vstack([P + nr * 2.4, (P - nr * 2.4)[::-1]]))+ elif kind == 'leaf':+ vine_polys.append(g)+ else:+ vine_polys.append(ellipse_pts(g[0], g[1], 3.4, 3.4, 0, 12))+ rosettes = []+ for (cx, cy) in ((a0[0] + mid, a0[1] + mid), (a0[2] - mid, a0[1] + mid), (a0[2] - mid, a0[3] - mid), (a0[0] + mid, a0[3] - mid)):+ ro = []+ for j in range(8):+ a = j * np.pi / 4+ ro.append(ellipse_pts(cx + np.cos(a) * band * 0.22, cy + np.sin(a) * band * 0.22, band * 0.15, band * 0.08, a, 12))+ rosettes.append((cx, cy, ro))+ vine_polys += ro+ outer = [(a0[0], a0[1]), (a0[2], a0[1]), (a0[2], a0[3]), (a0[0], a0[3])]+ inner = [(a1[0], a1[1]), (a1[2], a1[1]), (a1[2], a1[3]), (a1[0], a1[3])]+ ring_mask = np.zeros((self.H, self.W), np.float32)+ _, _, mo = self._poly_raster([outer], 0, 0, self.W, self.H, ss=1)+ _, _, mi = self._poly_raster([inner], 0, 0, self.W, self.H, ss=1)+ ring_mask = np.clip(mo - mi, 0, 1)+ self.wash(ring_mask, tone, angle=0.0, pool=0.5, slip=0.5, holes=vine_polys + holes, ragged=0.2, band=9)+ for kind, g in leaves:+ if kind == 'leaf':+ self.trek(list(g) + [g[0]], 1.2, 0.9, pounce=True, bead=0.1)+ self.trek([g[0], g[2]], 0.8, 0.7, smooth=False, pounce=False)+ for (cx, cy, ro) in rosettes:+ self.dot(cx, cy, 2.6)+ self.trek(outer + [outer[0]], width, smooth=False, taper=(0.01, 0.01))+ self.trek(inner + [inner[0]], width * 0.8, smooth=False, taper=(0.01, 0.01))+ o2 = [(a0[0] - 4.5, a0[1] - 4.5), (a0[2] + 4.5, a0[1] - 4.5), (a0[2] + 4.5, a0[3] + 4.5), (a0[0] - 4.5, a0[3] + 4.5)]+ self.trek(o2 + [o2[0]], width * 0.5, 0.85, smooth=False, taper=(0.01, 0.01), pounce=False)+ return a1++ # ------------------------------------------------------------ kiln, wall, age, light+ def fire(self):+ """kiln: glaze melts glossy, pigment turns cobalt blue and bleeds a little, pounce dust burns off"""+ self.fired = True++ def set_wall(self):+ """set the tiles in lime mortar (joints filled, recessed)"""+ self.grouted = True++ def age(self, craze=1.0, chips=10, specks=1.0, nails=0.5, cracks=(), dirt=1.0, seed=None):+ """crazing, pinholes, iron specks, chipped edges/corners showing the buff body, template nail holes,+ cracked tiles (cracks = list of polylines in px)"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ H, W = self.H, self.W+ # crazing: warped Voronoi edges, per-tile amount+ c = 21.0+ wx = (noise2d(H, W, 40, 2, int(r.integers(1 << 30))) - 0.5) * 14+ wy = (noise2d(H, W, 40, 2, int(r.integers(1 << 30))) - 0.5) * 14+ X, Y = self.XX + wx, self.YY + wy+ gx, gy = int(W / c) + 3, int(H / c) + 3+ jit = r.random((gy, gx, 2)).astype(np.float32)+ bx, by = np.floor(X / c).astype(np.int32), np.floor(Y / c).astype(np.int32)+ d1 = np.full((H, W), 1e9, np.float32); d2 = np.full((H, W), 1e9, np.float32)+ for oy in (-1, 0, 1):+ for ox in (-1, 0, 1):+ cxi = np.clip(bx + ox, 0, gx - 1); cyi = np.clip(by + oy, 0, gy - 1)+ jx_ = jit[cyi, cxi, 0]; jy_ = jit[cyi, cxi, 1]+ d = np.hypot(X - (cxi + jx_) * c, Y - (cyi + jy_) * c)+ lo = d < d1+ d2 = np.where(lo, d1, np.minimum(d2, d))+ d1 = np.where(lo, d, d1)+ edge = smoothstep(1.1, 0.0, d2 - d1)+ broken = noise2d(H, W, 30, 2, int(r.integers(1 << 30)))+ amt = self.craze[self.ck, self.ci] * craze+ cr = edge * smoothstep(0.35, 0.65, broken + amt * 0.5 - 0.25) * (0.35 + 0.65 * amt)+ # specks & pinholes+ sp = np.zeros((H, W), np.float32); pin = np.zeros((H, W), np.float32)+ n = int(W * H / 2600 * specks)+ for arr, cnt, rad in ((sp, n, (0.3, 0.9)), (pin, n // 2, (0.4, 0.8))):+ xs = r.uniform(0, W, cnt); ys = r.uniform(0, H, cnt); rs = r.uniform(*rad, cnt)+ for x, y, rr in zip(xs, ys, rs):+ x0, y0 = int(x) - 3, int(y) - 3+ if x0 < 0 or y0 < 0 or x0 + 7 > W or y0 + 7 > H: continue+ yy, xx = np.mgrid[y0:y0 + 7, x0:x0 + 7]+ arr[y0:y0 + 7, x0:x0 + 7] = np.maximum(arr[y0:y0 + 7, x0:x0 + 7], np.clip(rr + 0.5 - np.hypot(xx - x, yy - y), 0, 1))+ # chips: bites out of the glaze at edges and corners+ chip = np.zeros((H, W), np.float32)+ vis = self.visible()+ for _ in range(chips):+ i, k = vis[int(r.integers(len(vis)))]+ x0, y0, x1, y1 = self.rect(i, k)+ if r.random() < 0.6:+ cx, cy = (x0, x1)[int(r.integers(2))], (y0, y1)[int(r.integers(2))]+ else:+ if r.random() < 0.5: cx, cy = r.uniform(x0 + 15, x1 - 15), (y0, y1)[int(r.integers(2))]+ else: cx, cy = (x0, x1)[int(r.integers(2))], r.uniform(y0 + 15, y1 - 15)+ rr = r.uniform(5.0, 11.0)+ xs0, ys0 = int(cx - rr * 2), int(cy - rr * 2)+ xs1, ys1 = int(cx + rr * 2) + 1, int(cy + rr * 2) + 1+ xs0, ys0, xs1, ys1 = max(0, xs0), max(0, ys0), min(W, xs1), min(H, ys1)+ if xs1 <= xs0 or ys1 <= ys0: continue+ yy, xx = np.mgrid[ys0:ys1, xs0:xs1].astype(np.float32)+ ang = np.arctan2(yy - cy, xx - cx)+ rad = rr * (1 + 0.3 * np.sin(ang * 3 + r.uniform(0, 6)) + 0.15 * np.sin(ang * 7 + r.uniform(0, 6)))+ v = np.clip(rad - np.hypot(xx - cx, yy - cy), 0, 1)+ chip[ys0:ys1, xs0:xs1] = np.maximum(chip[ys0:ys1, xs0:xs1], v)+ chip *= self.inside+ # nail holes from the trimming template, about 5 px in from two or four corners+ nail = np.zeros((H, W), np.float32)+ for (i, k) in vis:+ if r.random() > nails: continue+ x0, y0, x1, y1 = self.rect(i, k)+ for (cx, cy) in ((x0 + 5, y0 + 5), (x1 - 5, y0 + 5), (x0 + 5, y1 - 5), (x1 - 5, y1 - 5)):+ if r.random() < 0.35: continue+ cx += r.normal(0, 0.8); cy += r.normal(0, 0.8)+ xa, ya = int(cx) - 3, int(cy) - 3+ if xa < 0 or ya < 0 or xa + 7 > W or ya + 7 > H: continue+ yy, xx = np.mgrid[ya:ya + 7, xa:xa + 7]+ nail[ya:ya + 7, xa:xa + 7] = np.maximum(nail[ya:ya + 7, xa:xa + 7], np.clip(1.6 - np.hypot(xx - cx, yy - cy), 0, 1))+ # cracks+ crack = np.zeros((H, W), np.float32)+ for pl in cracks: # a crack runs through one tile and stops at the joint+ im = Image.new('L', (W * 2, H * 2), 0); dr = ImageDraw.Draw(im)+ P, _ = _resample(spline(np.asarray(pl, np.float32), 6), 2.0)+ P = P + _normals(P) * (fbm1d(len(P), 8, 3, int(r.integers(1 << 30))) * 2.2)[:, None]+ dr.line([(x * 2, y * 2) for x, y in P], fill=255, width=2)+ m = np.asarray(im, np.float32).reshape(H, 2, W, 2).mean(axis=(1, 3)) / 255+ x0, y0 = int(np.clip(pl[len(pl) // 2][0], 0, W - 1)), int(np.clip(pl[len(pl) // 2][1], 0, H - 1))+ same = (self.ci == self.ci[y0, x0]) & (self.ck == self.ck[y0, x0])+ crack = np.maximum(crack, m * same * self.inside)+ grime = noise2d(H, W, 90, 3, int(r.integers(1 << 30)))+ self.aged = dict(craze=cr.astype(np.float32), speck=sp, pin=pin, chip=chip, nail=nail, crack=crack, grime=grime, dirt=dirt)++ def light(self, window=(420, 290, 110, 150), strength=0.5, panes=(2, 3), soft=8.0, F=2300.0):+ """a window behind the viewer reflected in the glaze: window = (x, y, w, h) where the reflection would sit+ on a perfectly flat wall; tilted, cushioned tiles break it into bent pieces that jump at every joint.+ The reflection is blended over the glaze (screen), so the painting stays visible through it;+ strength ~0.5 = the brightest pane lifts a dark line about half way to white."""+ self.window = dict(rect=window, strength=strength, panes=panes, soft=soft, F=F)++ # ------------------------------------------------------------ rendering+ def _glaze_rgb(self):+ c0, c1 = self.glaze_cols+ wm = self.warm[self.ck, self.ci][..., None]+ g = c0 * (1 - wm) + c1 * wm+ g = g * self.bright[self.ck, self.ci][..., None]+ mott = noise2d(self.H, self.W, 26, 3, 11)+ g = g * (0.985 + 0.03 * mott)[..., None]+ e = np.clip(-self.sdf / 10, 0, 1) # glaze thinner over the rounded edge: a hint of body+ g = g * (1 - 0.035 * (1 - e))[..., None] + _c(BODY) * (0.035 * (1 - e))[..., None]+ return g.astype(np.float32)++ def composite(self, hide=()):+ hide = set(hide)+ none = '*' in hide+ H, W = self.H, self.W+ D = np.zeros((H, W), np.float32)+ if not none:+ for (nm, kind) in self.order:+ if nm in hide or kind in hide or f'{nm}.{kind}' in hide: continue+ D += self.layers[(nm, kind)]+ D = D[self.Yi, self.Xi]+ hy, hx = np.gradient(self.h)+ nz = 1 / np.sqrt(1 + hx * hx + hy * hy)+ ndl = (-hx * self.Lv[0] - hy * self.Lv[1] + self.Lv[2]) * nz+ shade = np.clip(1 + 1.1 * (ndl - self.Lv[2]), 0.55, 1.25)+ if self.fired:+ D = D * self.strength[self.ck, self.ci]+ gran = noise2d(H, W, 1.6, 1, 44) # undissolved cobalt grains speckle the washes+ D = D * (1 + 0.32 * (gran - 0.5) * smoothstep(0.03, 0.25, D) * (1 - smoothstep(0.5, 0.9, D)))+ D = 0.5 * blur(D, 0.55) + 0.33 * blur(D, 1.25) + 0.17 * blur(D, 3.2)+ G = self._glaze_rgb()+ col = G * np.exp(-COBALT_K[None, None, :] * D[..., None])+ else:+ G = _c(RAW_GLAZE) * (0.97 + 0.05 * noise2d(H, W, 3, 2, 5))[..., None] * self.bright[self.ck, self.ci][..., None]+ col = G * np.exp(-RAW_K[None, None, :] * D[..., None])+ if not none and 'pounce' not in hide:+ Pn = np.clip(blur(self.P[self.Yi, self.Xi], 0.45) * 1.4, 0, 1)+ col = col * (1 - 0.75 * Pn)[..., None]+ col = col * shade[..., None]+ ins = self.inside[..., None]+ if self.grouted:+ sand = noise2d(H, W, 2.5, 2, 21)+ mort = self.mortar * (0.9 + 0.12 * sand)[..., None]+ sh = np.clip(blur(shift(self.inside, 1.6, 1.8), 1.2) - self.inside, 0, 1)+ ao = np.clip(blur(self.inside, 2.5), 0, 1)+ J = mort * (1 - 0.45 * sh - 0.22 * ao)[..., None]+ else:+ sh = np.clip(blur(shift(self.inside, 2.5, 3.0), 1.8) - self.inside, 0, 1)+ J = _c(BED) * (1 - 0.5 * sh)[..., None] * (0.9 + 0.15 * noise2d(H, W, 3, 2, 22))[..., None]+ img = col * ins + J * (1 - ins)+ spec_ok = self.inside.copy()+ if self.aged:+ a = self.aged+ dirt = a['dirt']+ img = img * (1 - (0.13 * a['craze'] * dirt)[..., None] * np.array([1.0, 1.03, 1.12], np.float32))+ img = img * (1 - 0.45 * a['speck'])[..., None] + (a['speck'] * 0.45)[..., None] * np.array([0.36, 0.27, 0.2], np.float32)+ pin = a['pin']+ img = img * (1 - 0.45 * pin)[..., None]+ nail = a['nail'] * self.inside+ img = img * (1 - 0.55 * nail)[..., None]+ chip = a['chip']+ if chip.any():+ body = _c(BODY) * (0.8 + 0.2 * noise2d(H, W, 1.5, 2, 33) + 0.08 * noise2d(H, W, 6, 2, 34))[..., None]+ lip = np.clip(chip - shift(chip, 1.5, 1.8), 0, 1) # inside edge toward the light: shadowed by the glaze lip+ rim = np.clip(chip - shift(chip, -1.2, -1.4), 0, 1) # far wall of the bite faces the light+ img = img * (1 - chip[..., None]) + body * chip[..., None]+ img = img * (1 - 0.38 * lip)[..., None] + 0.1 * rim[..., None]+ spec_ok = spec_ok * (1 - chip)+ if a['crack'].any():+ ck = a['crack']+ img = img * (1 - 0.5 * ck)[..., None]+ img = img + 0.05 * np.clip(shift(ck, -1, -1) - ck, 0, 1)[..., None]+ if self.grouted:+ gr = a['grime']+ img = img * (1 - dirt * 0.18 * (1 - ins) * gr[..., None])+ img = img * (1 - dirt * 0.03 * gr)[..., None]+ if self.window and self.fired:+ wv = self.window+ F = wv['F']+ cx, cy = W / 2, H / 2+ vx, vy, vz = cx - self.XX, cy - self.YY, np.full((H, W), F, np.float32)+ vl = np.sqrt(vx * vx + vy * vy + vz * vz); vx /= vl; vy /= vl; vz /= vl+ nx, ny = -hx * nz, -hy * nz+ dn = nx * vx + ny * vy + nz * vz+ rx, ry, rz = 2 * dn * nx - vx, 2 * dn * ny - vy, 2 * dn * nz - vz+ t = F / np.maximum(rz, 1e-3)+ px, py = self.XX + rx * t, self.YY + ry * t+ x, y, w, h = wv['rect']+ hx0, hy0 = 2 * x - cx, 2 * y - cy+ Wx, Wy = 2 * w, 2 * h+ s = wv['soft']+ u = (px - (hx0 - Wx / 2)); v = (py - (hy0 - Wy / 2))+ inside_w = smoothstep(-s, s, u) * smoothstep(-s, s, Wx - u) * smoothstep(-s, s, v) * smoothstep(-s, s, Wy - v)+ bars = np.ones_like(u)+ nxp, nyp = wv['panes']+ for j in range(1, nxp):+ bars *= smoothstep(Wx * 0.05, Wx * 0.05 + s, np.abs(u - Wx * j / nxp))+ for j in range(1, nyp):+ bars *= smoothstep(Wy * 0.03, Wy * 0.03 + s, np.abs(v - Wy * j / nyp))+ fr = Wx * 0.06+ bars *= smoothstep(fr, fr + s, u) * smoothstep(fr, fr + s, Wx - u) * smoothstep(fr, fr + s, v) * smoothstep(fr, fr + s, Wy - v)+ sky = 0.78 + 0.22 * np.clip(1 - v / Wy, 0, 1)+ spec = inside_w * bars * sky * wv['strength']+ room = 0.035 * smoothstep(-400, 400, -(px - hx0)) * (1 - inside_w)+ fres = 1 + 2.5 * (1 - dn) ** 3+ sp = np.clip((spec + room) * fres, 0, 0.85) * spec_ok+ img = img + (np.array([0.985, 0.995, 1.0], np.float32) - img) * sp[..., None] # screen over the glaze+ # room light: brighter toward the window side, soft vignette+ gx = (self.XX / W - 0.25); gy = (self.YY / H - 0.3)+ illum = 1.03 - 0.07 * np.clip(np.hypot(gx * 1.2, gy), 0, 1.2) - 0.08 * ((self.XX / W - 0.5) ** 2 + (self.YY / H - 0.5) ** 2)+ img = img * illum[..., None]+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name, hide=()):+ """snapshot for the drawing animation; hide = layer names (or 'pounce', or '*' for bare tiles)"""+ self.stages.append((name, self.composite(hide)))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ 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+diff --git a/lib/flatvector.py b/lib/flatvector.pynew file mode 100644index 0000000..bf1da6e--- /dev/null+++ b/lib/flatvector.py@@ -0,0 +1,580 @@+"""flatvector — layered flat vector landscape: big simple geometric shapes, a bold but small palette, a soft+ambient shadow where one layer overlaps the next, and a fine print grain (numpy + Pillow only).++Model: an artboard in a vector app where every object is a *layer* stacked in front of the last one -- the look of+modern motion-graphics backgrounds and editorial landscape posters, not of a painting.+ shapes every mark is a closed geometric shape with a crisp anti-aliased edge: circles and ellipses (analytic+ coverage), polygons whose corners can be filleted (`round=`), tapered capsules, smooth land profiles+ (a spline top edge filled down to the bottom of the board), stars. A shape is a `Mask`: a coverage patch+ plus its offset on the board, so union `|`, intersection `&`, difference `-` and `moved()` only touch+ the overlap of bounding boxes. No outlines anywhere: neighbouring layers are told apart by value and+ hue only, so every object is planned against what sits behind it.+ palette five to seven flat hues (here NIGHT navy, PLUM, BERRY magenta, EMBER orange, SAND, PINE teal, CREAM).+ Every other colour is a *tone* of one of them (`tone(c, -k)` toward the night ink, `+k` toward cream)+ or a `mix()` of two of them, so the whole picture stays in one family.+ light one light (here the moon, upper left) for the whole board: every object is split into a lit face and a+ shade face along a straight or kinked line (`face()`), shade faces always on the side away from the+ light. Mountains get a faceted ridge line, pines are split down the middle, clouds get a darker belly+ (the cloud minus itself nudged up). No gradients: glow is a stack of flat translucent rings (`glow()`),+ a beam is one translucent flat polygon.+ layers the "vector paper" depth cue: `fill(..., lift=px)` first drops a soft, short ambient shadow of the shape+ onto whatever is already on the board (a blurred copy, nudged down a little, multiplied by a night-blue+ tint so shadows stay in the palette), then lays the flat colour on top. The shadow shows as a thin+ dark seam above and below every overlap -- under snow caps, along the crest of each hill band, under+ each tier of a pine -- so the landscape reads as stacked layers without a single line.+ texture two quiet textures, both fixed per seed so successive stages keep the same pixels: inside each layer a+ very faint fibrous streak field (sampled at a different offset per layer, so each layer looks like its+ own sheet), and over the finished board a fine monochrome grain. Both are around 1-2 % in value; large+ flat fields must still read as flat.+ rhythm the picture is carried by the rhythm of a few big shapes (triangles of the ranges, waves of the hills,+ the moon disc and its rays) and generous empty sky. Small things (stars, dashes on the sand, pebbles)+ are sparse and tiny, and only one or two warm accents carry the story.+Coordinates are pixels on the board; angles are degrees counter-clockwise.++ from flatvector import FlatVector, NIGHT, PLUM, BERRY, EMBER, SAND, PINE, CREAM+ fv = FlatVector(1920, 1080, seed=3)+ fv.backdrop(NIGHT); fv.moon(420, 260, 110, rays=18); fv.stars(120)+ fv.mountain((1380, 300), (880, 720), (1920, 720), PLUM, snow=0.22)+ fv.land([(0, 640), (600, 610), (1300, 650), (1920, 620)], BERRY, lift=9)+ fv.land([(0, 760), (1920, 750)], SAND, lift=10)+ fv.pine(300, 760, 260)+ fv.tent(1250, 880, 260, 170); fv.campfire(1020, 885, 1.0)+ fv.save('out.jpg')+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, spline, noise2d++NIGHT, PLUM, BERRY, EMBER, SAND, PINE, CREAM = ('#1f2a55', '#8d6bb5', '#b8336b', '#e5733a', '#e7b84e',+ '#2b8f77', '#f4e9cf')+PALETTE = dict(night=NIGHT, plum=PLUM, berry=BERRY, ember=EMBER, sand=SAND, pine=PINE, cream=CREAM)+_MARGIN = 96 # masks may hang this far off the board (for blur and moves)+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ if isinstance(c, str): return hexc(PALETTE.get(c, c))+ return np.asarray(c, np.float32)+++def tone(c, k):+ """k < 0 mixes toward the night ink, k > 0 toward cream: every shade stays inside the palette's family"""+ c = _c(c)+ return c + (_c(NIGHT) * 0.75 - c) * (-k) if k < 0 else c + (_c(CREAM) - c) * k+++def mix(a, b, t):+ a, b = _c(a), _c(b)+ return a + (b - a) * t+++class Mask:+ """a coverage patch `a` (float32 0..1) whose top-left corner sits at (x0, y0) on the board"""+ __slots__ = ('x0', 'y0', 'a')++ def __init__(self, x0, y0, a):+ self.x0, self.y0, self.a = int(x0), int(y0), a.astype(np.float32, copy=False)++ @property+ def x1(self): return self.x0 + self.a.shape[1]++ @property+ def y1(self): return self.y0 + self.a.shape[0]++ def _on(self, x0, y0, x1, y1):+ """this mask resampled onto box (x0, y0, x1, y1), zero outside"""+ out = np.zeros((max(0, y1 - y0), max(0, x1 - x0)), np.float32)+ ix0, iy0, ix1, iy1 = max(x0, self.x0), max(y0, self.y0), min(x1, self.x1), min(y1, self.y1)+ if ix1 > ix0 and iy1 > iy0:+ out[iy0 - y0:iy1 - y0, ix0 - x0:ix1 - x0] = self.a[iy0 - self.y0:iy1 - self.y0, ix0 - self.x0:ix1 - self.x0]+ return out++ def __or__(self, o):+ if o is None: return self+ b = (min(self.x0, o.x0), min(self.y0, o.y0), max(self.x1, o.x1), max(self.y1, o.y1))+ return Mask(b[0], b[1], np.maximum(self._on(*b), o._on(*b)))++ def __and__(self, o):+ b = (max(self.x0, o.x0), max(self.y0, o.y0), min(self.x1, o.x1), min(self.y1, o.y1))+ if b[2] <= b[0] or b[3] <= b[1]: return Mask(self.x0, self.y0, np.zeros((1, 1), np.float32))+ return Mask(b[0], b[1], np.minimum(self._on(*b), o._on(*b)))++ def __sub__(self, o):+ if o is None: return self+ b = (self.x0, self.y0, self.x1, self.y1)+ return Mask(self.x0, self.y0, self.a * (1 - o._on(*b)))++ def moved(self, dx, dy):+ return Mask(self.x0 + int(round(dx)), self.y0 + int(round(dy)), self.a)++ def scaled(self, k):+ return Mask(self.x0, self.y0, np.clip(self.a * k, 0, 1))+++def _fillet(pts, r):+ """round every corner of a closed polygon with radius r (quadratic arcs tangent to both edges)"""+ P = np.asarray(pts, np.float32)+ n = len(P); out = []+ rs = r if np.ndim(r) else [r] * n+ for i in range(n):+ p, a, b = P[i], P[i - 1], P[(i + 1) % n]+ if rs[i] <= 0:+ out.append(p); continue+ u, v = a - p, b - p+ lu, lv = np.linalg.norm(u) + 1e-6, np.linalg.norm(v) + 1e-6+ u, v = u / lu, v / lv+ ang = np.arccos(np.clip(np.dot(u, v), -1, 1))+ t = min(rs[i] / max(np.tan(ang / 2), 1e-3), lu * 0.45, lv * 0.45)+ p0, p1 = p + u * t, p + v * t+ for s in np.linspace(0, 1, 9):+ out.append((1 - s) ** 2 * p0 + 2 * (1 - s) * s * p + s * s * p1)+ return np.array(out, np.float32)+++class FlatVector:+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.7, -0.7)):+ self.W, self.H, self.seed = W, H, seed+ self.rng = np.random.default_rng(seed)+ self.light = np.array(light, np.float32) / (np.hypot(*light) + 1e-6) # screen direction toward the light+ self.img = np.zeros((H, W, 3), np.float32)+ self.stages = []+ self.shadow_tint = mix(NIGHT, PLUM, 0.25) * 0.9 # shadows multiply by this: navy-violet, never grey+ P = 256+ r = np.random.default_rng(seed + 101)+ streak = np.asarray(Image.fromarray(r.random(((H + P) // 14 + 2, (W + P) // 2 + 2)).astype(np.float32))+ .resize((W + P, H + P), Image.BICUBIC), np.float32)+ blot = noise2d(H + P, W + P, 90, 3, seed + 7)+ f = 0.65 * (streak - streak.mean()) / (streak.std() + 1e-6) + 0.35 * (blot - blot.mean()) / (blot.std() + 1e-6)+ self._fibre = f.astype(np.float32)+ g = np.random.default_rng(seed + 202).normal(0, 1, (H, W)).astype(np.float32)+ self._grain = (0.75 * g + 0.6 * blur(g, 0.9) * 2.2).astype(np.float32)++ # ------------------------------------------------------------------ shapes (all return Mask)+ def _box(self, x0, y0, x1, y1):+ M = _MARGIN+ x0, y0 = max(int(np.floor(x0)) - 2, -M), max(int(np.floor(y0)) - 2, -M)+ x1, y1 = min(int(np.ceil(x1)) + 2, self.W + M), min(int(np.ceil(y1)) + 2, self.H + M)+ return x0, y0, max(x1, x0 + 1), max(y1, y0 + 1)++ def _grid(self, x0, y0, x1, y1):+ ys, xs = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ return xs + 0.5, ys + 0.5++ def poly(self, pts, round=0):+ """filled polygon; round = corner radius (one number, or one per vertex)"""+ P = _fillet(pts, round) if np.any(np.asarray(round) > 0) else np.asarray(pts, np.float32)+ x0, y0, x1, y1 = self._box(P[:, 0].min(), P[:, 1].min(), P[:, 0].max(), P[:, 1].max())+ ss = 4+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P], fill=255)+ a = np.asarray(im, np.float32).reshape(y1 - y0, ss, x1 - x0, ss).mean((1, 3)) / 255+ return Mask(x0, y0, a)++ def ellipse(self, cx, cy, rx, ry=None, rot=0):+ ry = rx if ry is None else ry+ R = max(rx, ry)+ x0, y0, x1, y1 = self._box(cx - R, cy - R, cx + R, cy + R)+ X, Y = self._grid(x0, y0, x1, y1)+ c, s = np.cos(np.radians(rot)), np.sin(np.radians(rot))+ u, v = (X - cx) * c - (Y - cy) * s, (X - cx) * s + (Y - cy) * c+ f = np.sqrt((u / rx) ** 2 + (v / ry) ** 2) + 1e-6+ g = np.sqrt((u / rx ** 2) ** 2 + (v / ry ** 2) ** 2) / f + 1e-6+ return Mask(x0, y0, np.clip(0.5 - (f - 1) / g, 0, 1))++ def circle(self, cx, cy, r):+ return self.ellipse(cx, cy, r, r)++ def rect(self, x0, y0, x1, y1, round=0):+ return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], round=round)++ def capsule(self, p0, p1, r0, r1=None):+ """a stroke with round ends from p0 (radius r0) to p1 (radius r1): stems, poles, logs, dashes"""+ r1 = r0 if r1 is None else r1+ (ax, ay), (bx, by) = p0, p1+ R = max(r0, r1)+ x0, y0, x1, y1 = self._box(min(ax, bx) - R, min(ay, by) - R, max(ax, bx) + R, max(ay, by) + R)+ X, Y = self._grid(x0, y0, x1, y1)+ dx, dy = bx - ax, by - ay+ L2 = dx * dx + dy * dy + 1e-6+ t = np.clip(((X - ax) * dx + (Y - ay) * dy) / L2, 0, 1)+ d = np.hypot(X - ax - t * dx, Y - ay - t * dy) - (r0 + (r1 - r0) * t)+ return Mask(x0, y0, np.clip(0.5 - d, 0, 1))++ def star(self, cx, cy, r_out, r_in, n=5, rot=90):+ a = np.radians(rot) + np.arange(2 * n) * np.pi / n+ rr = np.where(np.arange(2 * n) % 2 == 0, r_out, r_in)+ return self.poly(np.stack([cx + rr * np.cos(a), cy - rr * np.sin(a)], 1))++ def profile(self, pts, bottom=None, per=24):+ """land: the area under a smooth top edge through `pts` (x, y), filled down to `bottom`"""+ top = spline(pts, per)+ bottom = self.H + 60 if bottom is None else bottom+ P = np.vstack([top, [[top[-1, 0], bottom], [top[0, 0], bottom]]])+ return self.poly(P)++ def half(self, m, p0, p1):+ """the part of mask m to the right of the directed line p0 -> p1 (screen coordinates, y down)"""+ X, Y = self._grid(m.x0, m.y0, m.x1, m.y1)+ (ax, ay), (bx, by) = p0, p1+ d = ((bx - ax) * (Y - ay) - (by - ay) * (X - ax)) / (np.hypot(bx - ax, by - ay) + 1e-6)+ return Mask(m.x0, m.y0, m.a * np.clip(0.5 - d, 0, 1))++ # ------------------------------------------------------------------ paint+ def _slices(self, m):+ x0, y0, x1, y1 = max(m.x0, 0), max(m.y0, 0), min(m.x1, self.W), min(m.y1, self.H)+ if x1 <= x0 or y1 <= y0: return None+ return (slice(y0, y1), slice(x0, x1)), (slice(y0 - m.y0, y1 - m.y0), slice(x0 - m.x0, x1 - m.x0))++ def backdrop(self, colour):+ self.img[:] = _c(colour)+ self._texture(Mask(0, 0, np.ones((self.H, self.W), np.float32)), 0.6)++ def drop(self, m, lift=8, strength=0.36):+ """the ambient shadow a layer lifted `lift` px off the board throws on what is already there"""+ sig = max(1.0, lift * 0.9)+ pad = int(sig * 3 + lift)+ a = np.pad(m.a, pad, mode='constant')+ a = blur(a, sig)+ sm = Mask(m.x0 - pad, m.y0 - pad, a).moved(0, lift * 0.45)+ sl = self._slices(sm)+ if sl is None: return+ (cy, cx), (my, mx) = sl+ k = (strength * sm.a[my, mx])[..., None]+ self.img[cy, cx] *= 1 - k * (1 - self.shadow_tint)++ def _texture(self, m, amount):+ if amount <= 0: return+ sl = self._slices(m)+ if sl is None: return+ (cy, cx), (my, mx) = sl+ ox, oy = int(self.rng.integers(0, 256)), int(self.rng.integers(0, 256))+ f = self._fibre[cy.start + oy:cy.stop + oy, cx.start + ox:cx.stop + ox]+ self.img[cy, cx] *= (1 + 0.008 * amount * f * m.a[my, mx])[..., None]++ def fill(self, m, colour, alpha=1.0, lift=0, texture=1.0, shadow=0.36):+ """lay one flat layer: its ambient shadow first (if lifted), then the colour, then its faint sheet fibre"""+ if m is None: return m+ if lift: self.drop(m, lift, shadow)+ sl = self._slices(m)+ if sl is None: return m+ (cy, cx), (my, mx) = sl+ k = (m.a[my, mx] * alpha)[..., None]+ self.img[cy, cx] += (_c(colour) - self.img[cy, cx]) * k+ self._texture(m.scaled(alpha), texture)+ return m++ def face(self, m, p0, p1, colour, alpha=1.0):+ """shade face: recolour the part of m to the right of the line p0 -> p1"""+ return self.fill(self.half(m, p0, p1), colour, alpha, texture=0)++ def glow(self, cx, cy, rx, ry, colour, rings=4, alpha=0.13, shrink=0.72):+ """flat light: concentric translucent ellipses, each one a hard-edged step (no gradient)"""+ for i in range(rings):+ k = shrink ** i+ self.fill(self.ellipse(cx, cy, rx * k, ry * k), colour, alpha, texture=0)++ # ------------------------------------------------------------------ sky+ def stars(self, n=120, box=None, avoid=(), size=(1.0, 3.0), colour=CREAM):+ """sparse dots of different sizes and strengths; `avoid` = [(cx, cy, r), ...] keeps them off the moon"""+ x0, y0, x1, y1 = box or (0, 0, self.W, self.H * 0.55)+ placed = 0; tries = 0+ while placed < n and tries < n * 20:+ tries += 1+ x, y = self.rng.uniform(x0, x1), self.rng.uniform(y0, y1)+ if any(np.hypot(x - ax, y - ay) < ar for ax, ay, ar in avoid): continue+ r = size[0] + (size[1] - size[0]) * self.rng.random() ** 3+ self.fill(self.circle(x, y, r), colour, self.rng.uniform(0.45, 1.0), texture=0)+ placed += 1++ def sparkle(self, x, y, r, colour=CREAM, alpha=1.0):+ """four-point star (a bright star)"""+ return self.fill(self.star(x, y, r, r * 0.22, 4, 90), colour, alpha, texture=0)++ def moon(self, cx, cy, r, rays=18, ray_colour=EMBER, ray_len=(0.62, 0.38), halo=True, craters=True):+ """the moon as a flat disc with a crown of alternating long / short triangular rays and stepped halo"""+ if halo:+ for i, k in enumerate((2.15, 1.72)):+ self.fill(self.circle(cx, cy, r * k), tone(NIGHT, 0.045 * (i + 1)), texture=0)+ if rays:+ for i in range(rays):+ a = np.radians(90 + 360 * i / rays)+ L = r * (1.16 + (ray_len[0] if i % 2 == 0 else ray_len[1]))+ w = np.radians(360 / rays * (0.22 if i % 2 == 0 else 0.18))+ base = r * 1.12+ pts = [(cx + base * np.cos(a - w), cy - base * np.sin(a - w)),+ (cx + L * np.cos(a), cy - L * np.sin(a)),+ (cx + base * np.cos(a + w), cy - base * np.sin(a + w))]+ col = ray_colour if i % 2 == 0 else tone(ray_colour, 0.25)+ self.fill(self.poly(pts, round=[2, 4, 2]), col, lift=4, shadow=0.25)+ disc = self.circle(cx, cy, r)+ self.fill(disc, CREAM, lift=7, shadow=0.4)+ self.fill(disc - disc.moved(-r * 0.16, -r * 0.12), tone(CREAM, -0.07), texture=0) # quiet shade crescent+ if craters:+ for dx, dy, k in ((-0.32, -0.18, 0.2), (0.28, 0.22, 0.14), (0.05, 0.42, 0.1), (0.36, -0.3, 0.08)):+ self.fill(self.circle(cx + dx * r, cy + dy * r, k * r), tone(CREAM, -0.06), texture=0)+ return disc++ def shooting_star(self, head, tail, r=3.0, colour=CREAM):+ """a meteor: a tapered streak, brighter at the head, in two flat alpha steps"""+ (hx, hy), (tx, ty) = head, tail+ mid = (hx + (tx - hx) * 0.45, hy + (ty - hy) * 0.45)+ self.fill(self.capsule(mid, tail, r * 0.55, 0.3), colour, 0.35, texture=0)+ self.fill(self.capsule(head, mid, r, r * 0.55), colour, 0.85, texture=0)+ self.sparkle(hx, hy, r * 3.2, colour)++ def cloud(self, cx, cy, w, colour=CREAM, belly=None, alpha=1.0, lift=6, seed=0):+ """flat cloud: three or four circles of different sizes sitting on one flat base line, a thin pill under+ them; the shade is the cloud minus itself nudged toward the light (a crescent on the far lower edge)"""+ g = np.random.default_rng(self.seed * 31 + seed)+ base = cy + w * 0.16+ bumps = [(-0.31, 0.15), (-0.1, 0.25), (0.15, 0.2), (0.33, 0.12)]+ if g.random() < 0.5: bumps = [(-dx, r) for dx, r in bumps]+ m = self.rect(cx - w * 0.46, base - w * 0.13, cx + w * 0.46, base, round=w * 0.065)+ for dx, rr in bumps:+ rr *= w * g.uniform(0.92, 1.08)+ m = m | self.circle(cx + dx * w, base - rr * 0.95, rr)+ m = m & self.rect(cx - w, cy - w, cx + w, base)+ self.fill(m, colour, alpha, lift=lift, shadow=0.3)+ belly = mix(colour, PLUM, 0.3) if belly is None else belly+ k = w * 0.045+ self.fill(m - m.moved(self.light[0] * k, self.light[1] * k), belly, alpha, texture=0)+ return m++ # ------------------------------------------------------------------ land+ def mountain(self, peak, left, right, colour, snow=0.0, ridge=None, lift=7, shade=-0.2, seed=0):+ """a flat triangular peak, lit face toward the light and a faceted shade face, optional zig-zag snow cap.+ ridge: the kinked line from the peak down to the foot that splits the faces (auto if None).+ Returns dict(body, shade, snow) masks, e.g. to recolour a trail where it crosses the snow."""+ r = np.random.default_rng(self.seed * 17 + seed)+ (px, py), (lx, ly), (rx, ry) = peak, left, right+ tri = self.poly([left, peak, right], round=[0, 9, 0])+ self.fill(tri, colour, lift=lift)+ if ridge is None:+ h = ly - py+ ridge = [(px + h * 0.06, py + h * 0.3), (px - h * 0.03, py + h * 0.55), (px + h * 0.09, max(ly, ry) + 40)]+ shade_poly = [peak] + list(ridge) + [(rx + 40, ry + 40), (rx + 40, py - 10)]+ side = self.poly(shade_poly) & tri+ self.fill(side, tone(colour, shade), texture=0)+ if snow:+ def on(edge, t): return (px + (edge[0] - px) * t, py + (edge[1] - py) * t)+ tl, tr = snow * r.uniform(0.85, 1.15), snow * r.uniform(0.85, 1.15)+ a, b = np.array(on(left, tl)), np.array(on(right, tr))+ zig = []+ k = 5+ for i in range(1, k):+ p = a + (b - a) * i / k+ zig.append((p[0] + r.uniform(-6, 6), p[1] + (-1) ** i * (ly - py) * snow * 0.18 + (ly - py) * snow * 0.06))+ cap = self.poly([peak, tuple(b)] + zig[::-1] + [tuple(a)], round=[9] + [3] * (len(zig) + 2)) & tri+ self.fill(cap, CREAM, lift=3, shadow=0.3)+ self.fill(cap & side, mix(CREAM, colour, 0.28), texture=0)+ else:+ cap = None+ return dict(body=tri, shade=side, snow=cap)++ def land(self, pts, colour, lift=9, shadow=0.38, texture=1.0):+ """one hill band: everything under a smooth top edge through pts"""+ m = self.profile(pts)+ return self.fill(m, colour, lift=lift, shadow=shadow, texture=texture)++ def pine(self, x, base, h, colour=PINE, tiers=3, width=0.62, shade=-0.22, trunk=None, lift=5):+ """stacked triangle tiers, split down the middle into lit and shade halves; each tier throws a soft+ shadow on the tier below"""+ trunk = tone(EMBER, -0.6) if trunk is None else trunk+ tw = max(3, h * 0.038)+ self.fill(self.rect(x - tw, base - h * 0.2, x + tw, base), trunk, lift=lift)+ top = base - h+ total = h * 0.9 # the crown stops a little above the ground: trunk shows+ th = total * (0.5 if tiers > 2 else 0.62) # height of one tier; tiers overlap+ step = (total - th) / max(1, tiers - 1)+ for j in range(tiers - 1, -1, -1): # bottom (widest) tier first, each upper tier lies on it+ t0 = top + j * step+ t1 = t0 + th+ half = h * width / 2 * (0.55 + 0.45 * (j + 1) / tiers)+ tri = self.poly([(x - half, t1), (x, t0), (x + half, t1)], round=[4, 5, 4])+ self.fill(tri, colour, lift=lift, shadow=0.42)+ self.face(tri, (x, t0 - 5), (x, t1 + 5), tone(colour, shade))++ def round_tree(self, x, base, r, colour=PINE, shade=-0.22, trunk=None, fruit=None, lift=6, seed=0):+ """a crown of two or three overlapping discs on a short trunk; back disc darker"""+ g = np.random.default_rng(self.seed * 13 + seed)+ trunk = tone(EMBER, -0.6) if trunk is None else trunk+ tw = r * 0.13+ self.fill(self.rect(x - tw, base - r * 1.0, x + tw, base), trunk, lift=lift)+ cy = base - r * 1.55+ back = self.circle(x + r * 0.32, cy - r * 0.18, r * 0.82)+ self.fill(back, tone(colour, shade), lift=lift)+ front = self.circle(x - r * 0.18, cy + r * 0.06, r * 0.9)+ self.fill(front, colour, lift=lift)+ self.fill(front - front.moved(-r * 0.2, -r * 0.2), tone(colour, shade * 0.6), texture=0)+ if fruit is not None:+ for k in range(4):+ a = g.uniform(0, 2 * np.pi); d = g.uniform(0.2, 0.7) * r+ self.fill(self.circle(x - r * 0.18 + d * np.cos(a), cy + d * np.sin(a), r * 0.08), fruit, lift=2)++ def dashes(self, box, colours, n=14, length=(50, 150), thick=(5, 9), seed=0, horizon=None):+ """sparse horizontal capsules (lighter / darker sand strokes); shorter and thinner toward the horizon"""+ g = np.random.default_rng(self.seed * 7 + seed)+ x0, y0, x1, y1 = box+ hz = y0 if horizon is None else horizon+ out = []+ for i in range(n):+ y = y0 + (y1 - y0) * g.random() ** 0.8+ k = 0.4 + 0.6 * (y - hz) / max(1, (y1 - hz))+ L = g.uniform(*length) * k; t = g.uniform(*thick) * k+ x = g.uniform(x0, x1)+ m = self.capsule((x - L / 2, y), (x + L / 2, y), t / 2)+ self.fill(m, colours[i % len(colours)], texture=0)+ out.append(m)+ return out++ def pebble(self, x, y, r, colour, lit=None):+ m = self.ellipse(x, y, r, r * 0.62)+ self.fill(m, colour, lift=2, shadow=0.3)+ self.fill(m - m.moved(r * 0.25, r * 0.3), tone(colour, 0.25) if lit is None else lit, texture=0)++ def tuft(self, x, y, h, colour=PINE):+ """three blades of grass: thin filleted triangles"""+ for dx, k, lean in ((-0.35, 0.7, -0.35), (0, 1.0, 0.0), (0.35, 0.8, 0.3)):+ bx = x + dx * h * 0.5+ self.fill(self.poly([(bx - h * 0.09, y), (bx + lean * h * 0.5, y - h * k), (bx + h * 0.09, y)], round=[0, 1.5, 0]),+ colour, texture=0)++ # ------------------------------------------------------------------ story props+ def trail(self, pts, colour=CREAM, width=(2.5, 5.0), dash=(9, 20), gap=(9, 16), alpha=1.0, per=30):+ """a dashed path through control points; dashes grow with y (nearer = lower on the board = bigger)"""+ P = spline(pts, per)+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ ymin, ymax = P[:, 1].min(), P[:, 1].max()+ at = lambda d: np.array([np.interp(d, s, P[:, 0]), np.interp(d, s, P[:, 1])])+ k = lambda y: (y - ymin) / max(1, ymax - ymin)+ d = 0.0; m = None+ while d < s[-1]:+ y = at(d)[1]; t = k(y)+ L = dash[0] + (dash[1] - dash[0]) * t+ G = gap[0] + (gap[1] - gap[0]) * t+ a, b = at(d), at(min(d + L, s[-1]))+ w = width[0] + (width[1] - width[0]) * t+ m = self.capsule(tuple(a), tuple(b), w / 2) | m+ d += L + G+ self.fill(m, colour, alpha, texture=0)+ return m++ def flag(self, x, y, h, colour=EMBER, pole=CREAM):+ """a small summit flag: pole planted at (x, y), pennant flying right"""+ self.fill(self.capsule((x, y), (x, y - h), max(1.2, h * 0.035)), pole, texture=0)+ self.fill(self.poly([(x + 1, y - h), (x + h * 0.62, y - h * 0.84), (x + 1, y - h * 0.66)], round=[1, 2, 1]),+ colour, lift=2, shadow=0.3)++ def tent(self, x, base, w, h, colour=EMBER, depth=0.42, inside=SAND, door=0.55, lift=10):+ """an A-frame tent seen three-quarter: front triangle (lit), side roof panel receding right (shade),+ a glowing door opening with a folded-back flap, guy lines and stakes"""+ apex = (x, base - h)+ fl, fr = (x - w / 2, base), (x + w / 2, base)+ dx, dy = w * depth, -h * 0.16+ roof = self.poly([apex, (apex[0] + dx, apex[1] + dy), (fr[0] + dx, fr[1] + dy), fr], round=[3, 3, 0, 0])+ front = self.poly([fl, apex, fr], round=[0, 5, 0])+ self.fill(roof | front, tone(colour, -0.28), lift=lift, shadow=0.45)+ self.fill(roof - front, tone(colour, -0.28), texture=0.6)+ self.fill(front, colour)+ dh = h * door+ dw = w * door * 0.42+ opening = self.poly([(x - dw, base), (x, base - dh), (x + dw * 0.9, base)], round=[0, 3, 0])+ self.fill(opening, inside, texture=0)+ self.fill(self.poly([(x - dw * 0.55, base), (x, base - dh * 0.62), (x + dw * 0.5, base)], round=[0, 3, 0]),+ tone(inside, 0.4), texture=0)+ flap = self.poly([(x + dw * 0.9, base), (x, base - dh), (x + dw * 1.55, base)], round=[0, 2, 0])+ self.fill(flap, tone(colour, 0.22), lift=3, shadow=0.3)+ self.fill(self.capsule(apex, (apex[0], apex[1] - h * 0.08), max(1.5, w * 0.012)), tone(colour, -0.5), texture=0)+ for p0, p1 in ((apex, (x - w * 0.66, base + h * 0.02)), ((apex[0] + dx, apex[1] + dy), (fr[0] + dx + w * 0.2, base - h * 0.1))):+ self.fill(self.capsule(p0, p1, 1.1), tone(CREAM, -0.1), 0.85, texture=0)+ self.fill(self.capsule((p1[0], p1[1] - 6), (p1[0], p1[1] + 4), 2), tone(EMBER, -0.6), texture=0)+ return front++ def teardrop(self, x, bottom, r, h, lean=0.0):+ """a flame / drop: a disc of radius r resting on `bottom`, closed by tangents to a tip h above the bottom;+ lean tilts the tip sideways (degrees, + = to the right)"""+ cx, cy = x, bottom - r+ d = h - r+ th = np.arccos(np.clip(r / d, -1, 1))+ a = np.radians(lean)+ tip = (cx + d * np.sin(a), cy - d * np.cos(a))+ pl = (cx + r * np.sin(a - th), cy - r * np.cos(a - th))+ pr = (cx + r * np.sin(a + th), cy - r * np.cos(a + th))+ return self.circle(cx, cy, r) | self.poly([pl, tip, pr], round=[0, r * 0.18, 0])++ def campfire(self, x, base, s=1.0, flame=(EMBER, SAND, CREAM), log=None, stone=None, sparks=6, seed=0):+ """a few stones, a flame of three nested teardrops (outer one with two side tongues), crossed logs in front+ of its foot, and a few sparks"""+ g = np.random.default_rng(self.seed * 5 + seed)+ log = tone(EMBER, -0.55) if log is None else log+ stone = mix(PLUM, CREAM, 0.35) if stone is None else stone+ for sx, sy, sr in ((-54, -4, 11), (-30, 4, 12), (34, 4, 12), (56, -4, 10)):+ self.pebble(x + sx * s, base + sy * s, sr * s, tone(stone, -0.12), lit=stone)+ yb = base - 8 * s+ outer = self.teardrop(x, yb, 36 * s, 128 * s, 4) | self.teardrop(x - 26 * s, yb - 4 * s, 18 * s, 78 * s, -24) | \+ self.teardrop(x + 27 * s, yb - 4 * s, 16 * s, 66 * s, 26)+ self.fill(outer, flame[0], lift=4, shadow=0.22, texture=0)+ self.fill(self.teardrop(x + 2 * s, yb, 24 * s, 88 * s, 2), flame[1], texture=0)+ self.fill(self.teardrop(x + 3 * s, yb, 13 * s, 50 * s, 0), flame[2], texture=0)+ for p0, p1, c in (((x - 52 * s, base + 4 * s), (x + 44 * s, base - 16 * s), log),+ ((x + 52 * s, base + 4 * s), (x - 44 * s, base - 16 * s), tone(log, 0.14))):+ self.fill(self.capsule(p0, p1, 8.5 * s), c, lift=3, shadow=0.3, texture=0)+ self.fill(self.circle(p0[0], p0[1], 6 * s), tone(SAND, -0.08), texture=0) # sawn end+ for i in range(sparks):+ sx = x + g.uniform(-40, 40) * s+ sy = base - (120 + g.uniform(0, 70)) * s+ self.fill(self.circle(sx, sy, g.uniform(2, 3.6) * s), flame[1 + i % 2], g.uniform(0.6, 1.0), texture=0)++ def hiker(self, x, base, h, colour=None, pack=EMBER, facing=1, lamp=True, beam=CREAM, step=0.5):+ """a tiny walking silhouette (no face): leaning into the walk, backpack, stick, head torch with a flat beam"""+ colour = tone(NIGHT, -0.15) if colour is None else colour+ f = facing; u = h / 10.0+ hip = (x, base - 4.6 * u)+ head = (x + f * 0.9 * u, base - 8.9 * u)+ if lamp:+ lx, ly = head[0] + f * 0.9 * u, head[1] - 0.1 * u+ self.fill(self.poly([(lx, ly), (lx + f * 9 * u, ly + 3.6 * u), (lx + f * 8.2 * u, ly + 6.3 * u)]), beam, 0.22, texture=0)+ stride = 1.9 * u * (0.6 + step * 0.4)+ m = self.capsule(hip, (x - f * stride * 0.7, base - 2.2 * u), 0.75 * u, 0.6 * u) | \+ self.capsule((x - f * stride * 0.7, base - 2.2 * u), (x - f * stride * 1.1, base - 0.3 * u), 0.6 * u, 0.5 * u)+ m = m | self.capsule(hip, (x + f * stride * 0.8, base - 2.4 * u), 0.75 * u, 0.6 * u) | \+ self.capsule((x + f * stride * 0.8, base - 2.4 * u), (x + f * stride * 0.95, base - 0.3 * u), 0.6 * u, 0.5 * u)+ m = m | self.capsule(hip, (x + f * 0.55 * u, base - 7.4 * u), 1.05 * u, 1.2 * u)+ m = m | self.circle(*head, 1.05 * u)+ m = m | self.capsule((x + f * 0.5 * u, base - 7.0 * u), (x + f * 2.1 * u, base - 5.0 * u), 0.45 * u, 0.4 * u)+ self.fill(self.capsule((x + f * 2.2 * u, base - 5.6 * u), (x + f * 3.0 * u, base - 0.1 * u), 0.22 * u), tone(CREAM, -0.2), texture=0)+ self.fill(m, colour, lift=3, shadow=0.3, texture=0)+ bp = self.poly([(x - f * 1.9 * u, base - 7.6 * u), (x - f * 0.2 * u, base - 7.9 * u), (x - f * 0.0 * u, base - 4.9 * u),+ (x - f * 1.7 * u, base - 4.7 * u)], round=0.6 * u)+ self.fill(bp, pack, texture=0)+ self.fill(self.half(bp, (x - f * 0.9 * u, base - 9 * u), (x - f * 0.9 * u, base - 4 * u)) if f > 0 else+ self.half(bp, (x - f * 0.9 * u, base - 4 * u), (x - f * 0.9 * u, base - 9 * u)), tone(pack, -0.25), texture=0)+ if lamp:+ self.fill(self.circle(head[0] + f * 0.85 * u, head[1] - 0.15 * u, 0.42 * u), beam, texture=0)++ # ------------------------------------------------------------------ output+ def render(self):+ img = self.img * (1 + 0.011 * self._grain)[..., None]+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.render()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.render()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/graphite.py b/lib/graphite.pynew file mode 100644index 0000000..5e060a2--- /dev/null+++ b/lib/graphite.py@@ -0,0 +1,643 @@+"""graphite — a pencil drawing in graphite on cartridge paper: tone built from hatching and the side of the lead,+blended with a stump, lifted with erasers, fading out to bare construction lines at the edges (numpy + Pillow only).++Model:+ paper off-white cartridge paper. Its `tooth` is a height field (0 valley .. 1 peak) of small bumps about+ 2 px across with a faint felt texture; under raking light the bumps show a little even where nothing+ is drawn. The sheet is lit from the top left, so there is a very soft light falloff across it.+ graphite a pencil stroke shaves graphite onto the paper. How much sticks is pressure x the grade's softness, and+ it only sticks where the lead actually touches: light pressure grazes the peaks of the tooth (a grainy,+ sparkly grey with white valleys between), heavy pressure and soft leads reach into the valleys and+ fill them. Graphite is a mass field `m`; the visible value is Dmax (1 - exp(-m)), so layers add up but+ never reach black. Graphite is grey, not black: dark passages are a cool slate grey, and hard+ pressure polishes them (`b`), which in raking light gives the slight silvery sheen of graphite.+ grades 4H .. 8B (`GRADES`): mass per stroke, how deep into the tooth the lead reaches, and the line width.+ Hard leads give thin, pale, crisp lines that leave the tooth white; soft leads give broad dark lines.+ hand `guide` long light construction lines that overshoot (perspective lines to a vanishing point,+ plumb lines), `guide_ellipse` loose two-loop ellipses with their axes; `line` a contour stroke whose+ pressure swells and fades along it (heavier on the shadow side, `lost` gaps where light eats the+ edge), optionally searched for twice before it settles; `hatch` patches of parallel strokes laid by+ the wrist (all bowed the same way, heavy at the start and flicked off at the end, rows sharing+ staggered breaks) and built up in layers: first one direction, then interleaved, then crossed at a+ second and a third angle -- each layer only where the tone asks for it; `contour_hatch` strokes+ that follow the form (around a tyre, along a tube); `shade` the side of a blunt soft lead, broad+ grainy strokes that leave the tooth white.+ stump `smudge` with a paper stump or a finger: graphite is pushed into the valleys and sideways (local+ blur, optionally dragged in one direction), a little is picked up; grain disappears, tone softens and+ creeps a few px past where it was drawn.+ erasers `lift` a kneaded eraser dabbed on to pull out soft highlights; `erase` a hard eraser edge cutting+ crisp white lines through tone (spokes catching light, rim highlights); erasing a construction line+ leaves a ghost.+ margins `focus` sets where the drawing is finished: tone (hatching, shading, smudging) fades out with an+ irregular edge, lines get lighter, so the edges of the sheet are left as bare line drawing.+ `write` pencil handwriting, `value_scale` a strip of grade swatches the artist tried in the margin,+ `fingerprint` a graphite thumbprint, `smear` the grey haze where the side of the hand dragged.+Angles are screen degrees, clockwise (y points down): 0 runs left to right, 60 runs down to the right.++ from graphite import Graphite+ g = Graphite(1920, 1080, seed=3)+ g.paper()+ g.focus(960, 560, 700, 420) # tone only near the middle+ g.guide((100, 800), (1800, 800)) # a light construction line+ m = g.ellipse(960, 540, 220, 220)+ g.hatch(m, tone=g.radial(900, 480, 260), angle=60, grade='2B')+ g.smudge(m, 0.6, radius=4)+ g.lift(g.ellipse(900, 470, 40, 30, feather=12), 0.8) # kneaded-eraser highlight+ g.line(g.circle_pts(960, 540, 220), grade='4B', pressure=0.8, closed=True)+ g.save('sphere.jpg')+"""+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, load_font, text_mask++# mass per full-pressure stroke, tooth reach at full pressure, line width (px)+GRADES = {+ '4H': (0.30, 0.40, 0.95),+ '2H': (0.45, 0.48, 1.05),+ 'H': (0.62, 0.54, 1.15),+ 'HB': (0.85, 0.62, 1.30),+ '2B': (1.20, 0.70, 1.55),+ '4B': (1.65, 0.80, 1.85),+ '6B': (2.20, 0.90, 2.20),+ '8B': (2.90, 1.00, 2.60),+}+PAPER = '#f1efe9'+GRAPHITE = (0.205, 0.212, 0.235) # the darkest polished graphite: a cool slate, never black+SHEEN = (0.62, 0.65, 0.71) # what polished graphite reflects in raking light+++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 _gblur(a, sigma):+ """small-radius gaussian blur in float32 with a separable kernel (low memory; for the paper tooth)"""+ r = max(1, int(np.ceil(3 * sigma)))+ k = np.exp(-0.5 * (np.arange(-r, r + 1, dtype=np.float32) / sigma) ** 2); k /= k.sum()+ out = a.astype(np.float32)+ for ax in (0, 1):+ p = np.pad(out, [(r, r), (0, 0)] if ax == 0 else [(0, 0), (r, r)], mode='edge')+ acc = np.zeros_like(out)+ n = out.shape[ax]+ for i, w in enumerate(k):+ acc += w * (p[i:i + n] if ax == 0 else p[:, i:i + n])+ out = acc+ return out+++def _resample(P, step):+ """polyline -> points every `step` px along its length"""+ P = np.asarray(P, np.float32)+ if len(P) < 2: return P+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ if s[-1] < 1e-3: return P[:1]+ n = max(2, int(s[-1] / step) + 1)+ t = np.linspace(0, s[-1], n)+ return np.stack([np.interp(t, s, P[:, 0]), np.interp(t, s, P[:, 1])], 1).astype(np.float32)+++class Graphite:+ def __init__(self, W=1920, H=1080, seed=0, ss=2):+ self.W, self.H, self.ss = W, H, ss+ self.rng = np.random.default_rng(seed)+ self.m = np.zeros((H, W), np.float32) # graphite mass+ self.b = np.zeros((H, W), np.float32) # burnish (polish) of the graphite+ self.tooth = np.full((H, W), 0.5, np.float32)+ self.base = np.ones((H, W, 3), np.float32) * hexc(PAPER)+ self.finish = np.ones((H, W), np.float32)+ self.dmax = 0.9+ self.stages = []++ def _grid(self):+ """broadcastable pixel coordinates (H, 1) and (1, W) -- no full-size index arrays"""+ return (np.arange(self.H, dtype=np.float32)[:, None], np.arange(self.W, dtype=np.float32)[None, :])++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ def _box(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1)) + 1), min(self.H, int(np.ceil(y1)) + 1)+ if x1 <= x0 or y1 <= y0: return None+ return (slice(y0, y1), slice(x0, x1))++ def _mask_box(self, M, pad=2, thr=0.01):+ rows = np.nonzero((M > thr).any(1))[0]+ if not len(rows): return None+ cols = np.nonzero((M[rows[0]:rows[-1] + 1] > thr).any(0))[0]+ return self._box(cols[0] - pad, rows[0] - pad, cols[-1] + pad, rows[-1] + pad)++ # ------------------------------------------------------------ paper+ def paper(self, tone=PAPER, tooth=1.6, felt=0.05, mottle=0.012):+ """cartridge paper: tooth height field (bumps ~`tooth` px), faint felt texture, very soft light falloff"""+ H, W = self.H, self.W+ r = np.random.default_rng(self._seed())+ t = _gblur(r.random((H, W), dtype=np.float32), tooth * 0.3)+ t -= t.mean(); t /= (t.std() + 1e-6)+ t2 = _gblur(r.random((H, W), dtype=np.float32), tooth * 1.3)+ t2 -= t2.mean(); t2 /= (t2.std() + 1e-6)+ t *= 0.74; t += 0.26 * t2; del t2+ fe = noise2d(H, W, 14, 2, self._seed()) - 0.5+ t += felt * fe / (fe.std() + 1e-6); del fe+ t /= (t.std() + 1e-6)+ self.tooth = np.clip(0.5 + t * 0.2, 0, 1).astype(np.float32); del t+ base = hexc(tone)+ gy, gx = np.gradient(_gblur(self.tooth, 0.7))+ emboss = (-gx * 0.6 - gy * 0.8) * 0.07 # raking light from the top left on the bumps+ mot = (noise2d(H, W, 260, 3, self._seed()) - 0.5) * mottle * 2+ YY, XX = self._grid()+ light = 1.0 - 0.035 * ((XX / W) * 0.6 + (YY / H) * 0.8) # brighter top left+ f = (1 + emboss + mot) * light+ self.base = (base[None, None, :] * f[..., None]).astype(np.float32)++ # ------------------------------------------------------------ masks and tone fields+ def _local(self, P, pad):+ """bounding box of points (+pad) on the canvas -> (slices, x0, y0, w, h), or None"""+ P = np.asarray(P, np.float32).reshape(-1, 2)+ sl = self._box(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)+ if sl is None: return None+ return sl, sl[1].start, sl[0].start, sl[1].stop - sl[1].start, sl[0].stop - sl[0].start++ def _paint(self, P_all, pad, feather, draw):+ """rasterise a mask only inside its bounding box (2x supersampled) -> full-size float mask"""+ M = np.zeros((self.H, self.W), np.float32)+ loc = self._local(P_all, pad + 3 * feather + 3)+ if loc is None: return M+ sl, x0, y0, w, h = loc+ im = Image.new('L', (w * 2, h * 2), 0)+ draw(ImageDraw.Draw(im), lambda p: (float(p[0] - x0) * 2, float(p[1] - y0) * 2))+ a = np.asarray(im.resize((w, h), Image.BILINEAR), np.float32) / 255+ M[sl] = blur(a, feather) if feather else a+ return M++ def poly(self, pts, feather=0.7):+ P = np.asarray(pts, np.float32)+ return self._paint(P, 2, feather, lambda d, T: d.polygon([T(p) for p in P], fill=255))++ def ellipse(self, cx, cy, rx, ry=None, rot=0.0, feather=1.0):+ ry = rx if ry is None else ry+ sl = self._box(cx - max(rx, ry) - 4 * feather - 2, cy - max(rx, ry) - 4 * feather - 2, cx + max(rx, ry) + 4 * feather + 2, cy + max(rx, ry) + 4 * feather + 2)+ M = np.zeros((self.H, self.W), np.float32)+ if sl is None: return M+ yy, xx = np.mgrid[sl].astype(np.float32)+ a = np.deg2rad(rot); c, s = np.cos(a), np.sin(a)+ u, v = (xx - cx) * c + (yy - cy) * s, -(xx - cx) * s + (yy - cy) * c+ d = (np.sqrt((u / rx) ** 2 + (v / ry) ** 2) - 1) * min(rx, ry)+ M[sl] = np.clip(0.5 - d / max(feather, 0.5), 0, 1)+ return M++ def ring(self, cx, cy, r0, r1, ry_scale=1.0, feather=0.8):+ return np.clip(self.ellipse(cx, cy, r1, r1 * ry_scale, feather=feather) - self.ellipse(cx, cy, r0, r0 * ry_scale, feather=feather), 0, 1)++ def band(self, pts, width, feather=0.7, smooth=True):+ """mask of a thick polyline (a tube, a rod, a strap)"""+ P = spline(pts, 10) if (smooth and len(pts) > 2) else np.asarray(pts, np.float32)++ def draw(d, T):+ Q = [T(p) for p in P]+ d.line(Q, fill=255, width=max(1, int(round(width * 2))), joint='curve')+ for q in (Q[0], Q[-1]):+ d.ellipse([q[0] - width, q[1] - width, q[0] + width, q[1] + width], fill=255)+ return self._paint(P, width, feather, draw)++ def lines_mask(self, lines, width=1.5, feather=0.5):+ """mask of many thin polylines at once (spokes, wires, chain)"""+ allp = np.concatenate([np.asarray(P, np.float32) for P in lines])++ def draw(d, T):+ for P in lines:+ d.line([T(p) for p in P], fill=255, width=max(1, int(round(width * 2))), joint='curve')+ return self._paint(allp, width, feather, draw)++ def rect(self, x0, y0, x1, y1, feather=0.6):+ return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], feather)++ def linear(self, p0, p1, gamma=1.0):+ """tone field 0 at p0 rising to 1 at p1 (clamped beyond)"""+ YY, XX = self._grid()+ d = np.array(p1, np.float32) - np.array(p0, np.float32)+ t = ((XX - p0[0]) * d[0] + (YY - p0[1]) * d[1]) / float(d @ d)+ return np.clip(t, 0, 1) ** gamma++ def radial(self, cx, cy, r, gamma=1.0):+ """tone field 0 at (cx, cy) rising to 1 at distance r -- light falling off a rounded form"""+ YY, XX = self._grid()+ return np.clip(np.hypot(XX - cx, YY - cy) / r, 0, 1) ** gamma++ @staticmethod+ def circle_pts(cx, cy, rx, ry=None, a0=0.0, a1=360.0, rot=0.0, n=None):+ """points on an ellipse arc (degrees, clockwise on screen)"""+ ry = rx if ry is None else ry+ n = n or max(8, int(abs(a1 - a0) / 360 * 2 * np.pi * max(rx, ry) / 4))+ t = np.deg2rad(np.linspace(a0, a1, n))+ x, y = rx * np.cos(t), ry * np.sin(t)+ a = np.deg2rad(rot); c, s = np.cos(a), np.sin(a)+ return np.stack([cx + x * c - y * s, cy + x * s + y * c], 1).astype(np.float32)++ def focus(self, cx, cy, rx, ry, soft=0.38, rough=0.16):+ """where the drawing is finished: 1 inside an irregular oval, falling to 0 past its edge.+ Tone (hatch / shade / smudge) is multiplied by it; lines get lighter outside"""+ YY, XX = self._grid()+ ang = np.arctan2((YY - cy) / ry, (XX - cx) / rx)+ wob = np.interp(ang, np.linspace(-np.pi, np.pi, 181), fbm1d(181, 18, 4, self._seed()) * rough + 1.0)+ rr = np.hypot((XX - cx) / rx, (YY - cy) / ry) / wob+ rr = rr + (noise2d(self.H, self.W, 60, 3, self._seed()) - 0.5) * rough * 0.8+ self.finish = smoothstep(1 + soft, 1 - soft * 0.3, rr).astype(np.float32)+ return self.finish++ # ------------------------------------------------------------ strokes -> graphite+ def _raster(self, strokes):+ """strokes [(P (n,2), width (n,), pressure (n,))] -> (coverage, slices); drawn ss x, box-filtered.+ Lighter strokes are drawn first so a heavier one wins where two cross"""+ strokes = [s for s in strokes if len(s[0])]+ if not strokes: return None, None+ allp = np.concatenate([s[0] for s in strokes])+ pad = max(float(np.max(s[1])) for s in strokes) + 3+ sl = self._box(allp[:, 0].min() - pad, allp[:, 1].min() - pad, allp[:, 0].max() + pad, allp[:, 1].max() + pad)+ if sl is None: return None, None+ ss = self.ss+ x0, y0 = sl[1].start, sl[0].start+ bw, bh = sl[1].stop - x0, sl[0].stop - y0+ im = Image.new('L', (bw * ss, bh * ss), 0)+ d = ImageDraw.Draw(im)+ off = np.array([x0, y0], np.float32)+ strokes.sort(key=lambda s: float(np.mean(s[2])))+ for P, w, v in strokes:+ Q = (P - off) * ss+ n = len(Q)+ if n == 1:+ r_ = w[0] * ss / 2+ d.ellipse([Q[0, 0] - r_, Q[0, 1] - r_, Q[0, 0] + r_, Q[0, 1] + r_], fill=int(255 * min(1, v[0])))+ continue+ ww = np.maximum(1, np.round((w[:-1] + w[1:]) * 0.5 * ss)).astype(int).tolist()+ vv = np.round(255 * np.clip((v[:-1] + v[1:]) * 0.5, 0, 1)).astype(int).tolist()+ q = Q.tolist()+ for i in range(n - 1):+ if vv[i] <= 0: continue+ d.line([tuple(q[i]), tuple(q[i + 1])], fill=vv[i], width=ww[i])+ cov = np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255+ return cov, sl++ def _deposit(self, cov, sl, grade, clip=None, polish=1.0, gain=1.0):+ """coverage (pressure x footprint) -> graphite, through the paper tooth. `gain`: a point pressed into a+ line leaves more graphite per px than the same pressure spread over hatching"""+ mass, reach, _ = GRADES[grade]+ mass = mass * gain+ if clip is not None: cov = cov * clip[sl]+ t = self.tooth[sl]+ r = reach * (0.42 + 0.78 * np.sqrt(np.clip(cov, 0, 1))) # how deep into the tooth the lead gets (by pressure,+ # so the anti-aliased rim of a line is not all grain)+ resp = smoothstep(1.0 - r - 0.16, 1.0 - r + 0.16, t)+ dm = cov * mass * resp+ self.m[sl] += dm+ self.b[sl] += dm * np.clip(cov, 0, 1) * mass * polish++ def _prep(self, pts, grade, pressure, width=None, taper=(0.12, 0.22), smooth=True, wobble=0.35, step=2.0,+ swell=0.22, fade=None):+ """one hand stroke: smoothed, resampled, wobbled; pressure eases in, swells and lifts off"""+ P = np.asarray(pts, np.float32)+ if smooth and len(P) > 2: P = spline(P, 8)+ P = _resample(P, step)+ n = len(P)+ if n < 2: return P, np.full(n, width or GRADES[grade][2], np.float32), np.full(n, pressure, np.float32)+ if wobble:+ tan = np.gradient(P, axis=0); tan /= (np.linalg.norm(tan, axis=1, keepdims=True) + 1e-6)+ nrm = np.stack([-tan[:, 1], tan[:, 0]], 1)+ P = P + nrm * (fbm1d(n, max(3, n / 3), 3, self._seed()) * wobble)[:, None]+ t = np.linspace(0, 1, n, dtype=np.float32)+ a, b = taper+ prof = np.ones(n, np.float32)+ if a > 0: prof *= 0.25 + 0.75 * smoothstep(0, a, t)+ if b > 0: prof *= 0.08 + 0.92 * (1 - smoothstep(1 - b, 1, t))+ prof *= 1 + swell * fbm1d(n, max(4, n / 2), 2, self._seed())+ v = pressure * prof+ if fade is not None:+ ix = np.clip(P[:, 0].astype(int), 0, self.W - 1); iy = np.clip(P[:, 1].astype(int), 0, self.H - 1)+ v = v * (fade + (1 - fade) * self.finish[iy, ix])+ w = (width or GRADES[grade][2]) * (0.75 + 0.25 * np.clip(prof, 0, 1.2))+ return P, w.astype(np.float32), v.astype(np.float32)++ def strokes(self, lines, grade='HB', pressure=0.6, width=None, taper=(0.12, 0.22), wobble=0.35, clip=None,+ smooth=True, fade=None, polish=1.0, gain=1.6):+ """deposit a batch of free strokes (each a list of points)"""+ S = [self._prep(p, grade, pressure, width, taper, smooth, wobble, fade=fade) for p in lines if len(p) >= 2]+ cov, sl = self._raster(S)+ if sl is not None: self._deposit(cov, sl, grade, clip, polish, gain)++ def line(self, pts, grade='HB', pressure=0.7, width=None, closed=False, searching=0, lost=0.0, weight=None,+ wobble=0.45, smooth=True, taper=(0.06, 0.12), fade=0.35, gain=2.0):+ """a contour line: pressure swells and fades along it; `lost` (0..1) lets light eat parts of the edge;+ `weight` an optional field (0..1, e.g. a shadow-side map) that makes the line heavier where it is high;+ `searching` lighter exploratory strokes laid first, slightly off the final line"""+ P = np.asarray(pts, np.float32)+ if closed: P = np.vstack([P, P[:1]])+ if smooth and len(P) > 2: P = spline(P, 8)+ P = _resample(P, 2.0)+ for k in range(searching):+ n = len(P)+ i0 = int(self.rng.uniform(0, 0.15) * n); i1 = n - int(self.rng.uniform(0, 0.2) * n)+ tan = np.gradient(P, axis=0); tan /= (np.linalg.norm(tan, axis=1, keepdims=True) + 1e-6)+ off = np.stack([-tan[:, 1], tan[:, 0]], 1) * (fbm1d(n, max(4, n / 4), 3, self._seed()) * 2.6 + self.rng.normal(0, 1.0))[:, None]+ self.strokes([(P + off)[i0:i1]], 'H' if grade not in ('4H', '2H') else '4H', pressure * 0.5, None, (0.15, 0.2), wobble, smooth=False, fade=fade, gain=1.3)+ S = self._prep(P, grade, pressure, width, taper, False, wobble, fade=fade)+ Q, w, v = S+ if lost > 0:+ n = len(Q)+ g = (fbm1d(n, max(6, n / 5), 3, self._seed()) + 1) / 2+ v = v * (0.08 + 0.92 * smoothstep(lost - 0.12, lost + 0.12, g))+ if weight is not None:+ ix = np.clip(Q[:, 0].astype(int), 0, self.W - 1); iy = np.clip(Q[:, 1].astype(int), 0, self.H - 1)+ k = weight[iy, ix]+ v = v * (0.6 + 0.65 * k); w = w * (0.85 + 0.55 * k)+ cov, sl = self._raster([(Q, w, v)])+ if sl is not None: self._deposit(cov, sl, grade, gain=gain)++ def guide(self, p0, p1, grade='2H', pressure=0.35, overshoot=(20, 60), wobble=0.25):+ """a long light construction line that overshoots both ends (perspective line, plumb line, horizon)"""+ p0, p1 = np.array(p0, np.float32), np.array(p1, np.float32)+ d = p1 - p0; L = np.linalg.norm(d) + 1e-6; d /= L+ a = p0 - d * self.rng.uniform(*overshoot); b = p1 + d * self.rng.uniform(*overshoot)+ P = _resample(np.array([a, b]), 4.0)+ Q, w, v = self._prep(P, grade, pressure, None, (0.05, 0.08), False, wobble, swell=0.3)+ cov, sl = self._raster([(Q, w, v)])+ if sl is not None: self._deposit(cov, sl, grade, gain=1.3)++ def guide_ellipse(self, cx, cy, rx, ry=None, rot=0.0, loops=2, grade='2H', pressure=0.32, axes=True):+ """an ellipse blocked in the way a hand does it: two or three loose loops, plus its axes"""+ ry = rx if ry is None else ry+ for k in range(loops):+ a0 = self.rng.uniform(0, 360)+ drx, dry = self.rng.normal(0, 0.012) * rx, self.rng.normal(0, 0.012) * ry+ P = self.circle_pts(cx + self.rng.normal(0, 1.2), cy + self.rng.normal(0, 1.2), rx + drx, ry + dry, a0, a0 + self.rng.uniform(330, 400), rot)+ self.strokes([P], grade, pressure, None, (0.08, 0.12), 0.6, smooth=False, gain=1.3)+ if axes:+ a = np.deg2rad(rot); u = np.array([np.cos(a), np.sin(a)]); v = np.array([-np.sin(a), np.cos(a)])+ c = np.array([cx, cy])+ self.guide(c - u * rx * 1.08, c + u * rx * 1.08, grade, pressure * 0.8, (4, 14))+ self.guide(c - v * ry * 1.08, c + v * ry * 1.08, grade, pressure * 0.8, (4, 14))++ # ------------------------------------------------------------ hatching+ def _tone(self, mask, tone, finish):+ M = np.asarray(mask, np.float32)+ T = M * (tone if np.ndim(tone) else np.float32(tone))+ if finish: T = T * self.finish ** 0.6+ return T++ def hatch(self, mask, tone=0.5, angle=60.0, grade='2B', spacing=4.2, length=(36, 80), layers=(0, 0, 58, -38),+ pressure=0.62, width=None, bow=0.05, finish=True, zigzag=0.0, jitter=1.6, edge=0.6):+ """patches of parallel strokes, built up in layers. `tone` (number or field) 0 paper .. 1 darkest; layer k+ of `layers` (angle offsets; a repeated angle interleaves between the earlier lines) is laid only where+ tone > k / len(layers), and its strokes press harder where the tone is darker.+ `zigzag` (0..1): share of strokes laid back-and-forth as one connected scribble."""+ T = self._tone(mask, tone, finish)+ sl = self._mask_box(T, pad=2, thr=0.02)+ if sl is None: return+ y0, x0 = sl[0].start, sl[1].start+ Tb = T[sl]+ h, w = Tb.shape+ n_l = len(layers)+ seen = {}+ cx, cy = x0 + w / 2, y0 + h / 2+ corners = np.array([[x0, y0], [x0 + w, y0], [x0, y0 + h], [x0 + w, y0 + h]], np.float32) - [cx, cy]+ r = self.rng+ for k, off in enumerate(layers):+ lo = k / n_l+ Wk = smoothstep(lo, lo + 1.0 / n_l, Tb)+ if Wk.max() < 0.02: continue+ ang = np.deg2rad(angle + off + r.normal(0, 2.5))+ d = np.array([np.cos(ang), np.sin(ang)], np.float32)+ nv = np.array([-np.sin(ang), np.cos(ang)], np.float32)+ rep = seen.get(off, 0); seen[off] = rep + 1+ phase = (0.5 if rep % 2 else 0.0) * spacing+ on, od = corners @ nv, corners @ d+ Lb = r.uniform(*length)+ ucut = od.min() + r.uniform(0, Lb)+ k0, k1 = int(np.floor((od.min() - ucut) / Lb)) - 1, int(np.ceil((od.max() - ucut) / Lb)) + 1+ sign = 1 if r.random() < 0.5 else -1+ c = np.array([cx, cy], np.float32)+ S = [] # (points, row, patch, weight)+ o = on.min() + phase + r.uniform(0, spacing * 0.3)+ row = 0+ drift = r.normal(0, Lb * 0.05, k1 - k0 + 2) # the seams between patches wander a little+ while o < on.max():+ drift += r.normal(0, Lb * 0.012, len(drift))+ cuts = ucut + Lb * np.arange(k0, k1 + 2) + drift + r.normal(0, Lb * 0.03, len(drift))+ for j in range(len(cuts) - 1):+ s0, s1 = cuts[j] - r.uniform(-1.5, 3.0), cuts[j + 1] + r.uniform(-1.5, 3.5)+ if s1 - s0 < 4 or s1 < od.min() or s0 > od.max(): continue+ wm = 0.0+ for q in (0.5, 0.2, 0.8):+ p = c + nv * o + d * (s0 + (s1 - s0) * q)+ jx, jy = int(p[0]) - x0, int(p[1]) - y0+ if 0 <= jx < w and 0 <= jy < h: wm = max(wm, Wk[jy, jx])+ if wm <= r.uniform(0.0, 0.3): continue+ if finish: # toward the unfinished margin whole strokes drop out+ p = c + nv * o + d * (s0 + s1) / 2+ fm = self.finish[int(np.clip(p[1], 0, self.H - 1)), int(np.clip(p[0], 0, self.W - 1))]+ if fm < r.uniform(0.05, 0.85): continue+ tt = np.linspace(0, 1, 6, dtype=np.float32)[:, None]+ bend = sign * bow * (s1 - s0) * r.uniform(0.6, 1.3)+ base = c + nv * (o + r.normal(0, jitter * 0.25))+ P = base + d * (s0 + (s1 - s0) * tt) + nv * (4 * tt * (1 - tt) * bend)+ S.append((P, row, j, 0.55 + 0.45 * wm))+ o += spacing * r.uniform(0.86, 1.14)+ row += 1+ if not S: continue+ if zigzag:+ # neighbouring rows of one patch laid back-and-forth without lifting the pencil+ by = {}+ for P, rw, j, pw in S: by.setdefault(j, []).append((rw, P, pw))+ prepped = []+ for j, lst in by.items():+ lst.sort(key=lambda e: e[0])+ chain, last = [], None+ for rw, P, pw in lst:+ if chain and rw == last + 1 and r.random() < zigzag and len(chain) < 8:+ chain.append((P if len(chain) % 2 == 0 else P[::-1], pw))+ else:+ if chain: prepped.append(chain)+ chain = [(P, pw)]+ last = rw+ if chain: prepped.append(chain)+ prepped = [self._prep(np.concatenate([q[0] for q in ch]), grade, pressure * float(np.mean([q[1] for q in ch])),+ width, (0.04, 0.08), True, 0.3, step=2.0, swell=0.15) for ch in prepped]+ else:+ prepped = [self._prep(P, grade, pressure * pw * r.uniform(0.9, 1.08), width, (0.07, 0.2), False, 0.25, step=3.0, swell=0.1)+ for P, rw, j, pw in S]+ cov, ssl = self._raster(prepped)+ if ssl is None: continue+ clip = np.zeros((self.H, self.W), np.float32)+ clip[sl] = np.clip(Wk * (1.0 / max(edge, 0.05)), 0, 1)+ self._deposit(cov, ssl, grade, clip)++ def contour_hatch(self, lines, mask=None, tone=1.0, grade='2B', pressure=0.6, width=None, finish=True, taper=(0.15, 0.3), gain=1.3):+ """strokes that follow the form (given as polylines), kept only where mask x tone is, pressing harder+ where the tone is darker"""+ M = np.ones((self.H, self.W), np.float32) if mask is None else mask+ T = self._tone(M, tone, finish)+ S = []+ for p in lines:+ Q, w, v = self._prep(p, grade, pressure, width, taper, False, 0.3, swell=0.15)+ ix = np.clip(Q[:, 0].astype(int), 0, self.W - 1); iy = np.clip(Q[:, 1].astype(int), 0, self.H - 1)+ v = v * (0.35 + 0.65 * np.clip(T[iy, ix] * 1.3, 0, 1)) * (T[iy, ix] > 0.02)+ S.append((Q, w, v))+ cov, sl = self._raster(S)+ if sl is not None: self._deposit(cov, sl, grade, np.clip(T * 3, 0, 1), gain=gain)++ def shade(self, mask, tone=0.5, angle=20.0, grade='4B', width=9.0, spacing=None, length=(120, 260), pressure=0.32,+ finish=True, passes=3):+ """the side of a blunt soft lead: broad, soft-edged strokes at light pressure, laid in overlapping passes+ at slightly different angles. The lead only grazes the tooth peaks, so it leaves an even, grainy grey+ with the white valleys showing -- the base tone before smudging. Darker tone = harder pressure"""+ T = self._tone(mask, tone, finish)+ sl = self._mask_box(T, pad=int(width), thr=0.02)+ if sl is None: return+ spacing = spacing or width * 0.42+ y0, x0 = sl[0].start, sl[1].start+ Tb = T[sl]; h, w = Tb.shape+ cx, cy = x0 + w / 2, y0 + h / 2+ corners = np.array([[x0, y0], [x0 + w, y0], [x0, y0 + h], [x0 + w, y0 + h]], np.float32) - [cx, cy]+ r = self.rng+ clip = np.zeros((self.H, self.W), np.float32); clip[sl] = Tb+ for p in range(passes):+ ang = np.deg2rad(angle + r.normal(0, 4) + (p - (passes - 1) / 2) * 11)+ d = np.array([np.cos(ang), np.sin(ang)], np.float32); nv = np.array([-np.sin(ang), np.cos(ang)], np.float32)+ on, od = corners @ nv, corners @ d+ S = []+ o = on.min() + r.uniform(0, spacing)+ while o < on.max():+ u = od.min() - r.uniform(0, length[1])+ while u < od.max():+ L = r.uniform(*length)+ tt = np.linspace(0, 1, 8, dtype=np.float32)[:, None]+ P = np.array([cx, cy]) + nv * o + d * (u + L * tt) + nv * (4 * tt * (1 - tt) * r.normal(0, L * 0.03))+ if finish: # toward the unfinished margin whole strokes drop out+ pm = P[4]+ fm = self.finish[int(np.clip(pm[1], 0, self.H - 1)), int(np.clip(pm[0], 0, self.W - 1))]+ if fm < r.uniform(0.02, 0.7):+ u += L * r.uniform(0.6, 0.85); continue+ S.append(self._prep(P, grade, pressure * r.uniform(0.88, 1.08), width * r.uniform(0.9, 1.1), (0.12, 0.16), False, 0.6, step=8.0, swell=0.12))+ u += L * r.uniform(0.6, 0.85)+ o += spacing * r.uniform(0.85, 1.15)+ cov, ssl = self._raster(S)+ if ssl is None: continue+ cov = blur(cov, width * 0.22) # the flat of the lead has soft edges+ self._deposit(cov, ssl, grade, clip, polish=0.3)++ # ------------------------------------------------------------ stump and erasers+ def smudge(self, mask, amount=0.7, radius=4.0, direction=None, length=0.0, pickup=0.06, finish=True, contain=True):+ """blending stump / finger: graphite pushed into the valleys and sideways (blur), optionally dragged+ `length` px toward `direction` (degrees); a little is picked up. contain=True keeps the stump inside the+ mask (graphite from outside is not dragged in and the area does not pale against an untouched neighbour)"""+ M = np.asarray(mask, np.float32) * (self.finish if finish else 1)+ pad = int(radius * 3 + length + 4)+ sl = self._mask_box(M, pad=pad, thr=0.01)+ if sl is None: return+ src = self.m[sl]+ Mw = (np.asarray(mask, np.float32)[sl] > 0.3).astype(np.float32) if contain else None++ def drag(a):+ if direction is None or length <= 0: return a+ ang = np.deg2rad(direction); acc = np.zeros_like(a); n = max(2, int(length / 2))+ for k in range(n):+ t = k / (n - 1) * length+ dx, dy = int(round(np.cos(ang) * t)), int(round(np.sin(ang) * t))+ acc += np.pad(a, ((max(dy, 0), max(-dy, 0)), (max(dx, 0), max(-dx, 0))), mode='edge')[+ max(-dy, 0):max(-dy, 0) + a.shape[0], max(-dx, 0):max(-dx, 0) + a.shape[1]]+ return acc / n+ if contain:+ sm = blur(drag(src * Mw), radius) / np.maximum(blur(drag(Mw), radius), 1e-3)+ else:+ sm = blur(drag(src), radius)+ Mb = M[sl] * amount+ self.m[sl] = (src + Mb * (sm - src)) * (1 - pickup * M[sl])+ self.b[sl] = blur(self.b[sl], radius * 0.5) * (1 - 0.5 * Mb) + self.b[sl] * 0.5 * Mb++ def lift(self, mask, amount=0.7):+ """kneaded eraser dabbed on: pulls graphite off softly (highlights, glints, the lit side of a form)"""+ M = np.asarray(mask, np.float32)+ sl = self._mask_box(M, pad=1, thr=0.005)+ if sl is None: return+ k = 1 - amount * M[sl]+ self.m[sl] *= k; self.b[sl] *= k++ def erase(self, pts, width=4.0, amount=0.88, smooth=False, soft=0.5):+ """hard eraser edge: a crisp white line through tone; a ghost of what was there stays"""+ P = np.asarray(pts, np.float32)+ if smooth and len(P) > 2: P = spline(P, 8)+ P = _resample(P, 2.0)+ v = np.full(len(P), 1.0, np.float32); w = np.full(len(P), width, np.float32)+ cov, sl = self._raster([(P, w, v)])+ if sl is None: return+ if soft: cov = blur(cov, soft)+ k = 1 - amount * cov+ self.m[sl] *= k; self.b[sl] *= k++ # ------------------------------------------------------------ margins and accidents+ def write(self, s, x, y, size=30, grade='HB', pressure=0.75, rot=0.0, font='hand', anchor='la'):+ """pencil handwriting: glyphs as graphite, through the tooth, with a slight wobble of pressure"""+ f = load_font(font, size)+ M = text_mask(self.H, self.W, s, f, (x, y), anchor=anchor, rot=rot)+ sl = self._mask_box(M, pad=2, thr=0.02)+ if sl is None: return+ cov = blur(M[sl], 0.45) * pressure * (0.8 + 0.4 * noise2d(sl[0].stop - sl[0].start, sl[1].stop - sl[1].start, 30, 2, self._seed()))+ self._deposit(cov, sl, grade)++ def value_scale(self, x, y, w=62, h=40, grades=('2H', 'HB', '2B', '4B', '6B', '8B'), gap=8, label_size=20):+ """the strip of swatches an artist scribbles in the margin to try the pencils: one grade per box, labelled"""+ for i, gname in enumerate(grades):+ x0 = x + i * (w + gap)+ m = self.rect(x0, y, x0 + w, y + h, 0.5)+ self.hatch(m, 0.9, angle=self.rng.uniform(48, 62), grade=gname, spacing=2.8, length=(w * 0.9, w * 1.3),+ layers=(0, 0), pressure=0.95, finish=False, zigzag=0.9, edge=0.3)+ self.write(gname, x0 + w / 2, y + h + 8, label_size, '2B', 0.95, anchor='mt')++ def fingerprint(self, x, y, r=26, rot=20.0, amount=0.16, period=2.6):+ """a graphite thumbprint: whorled ridges inside an oval, strongest in the middle"""+ sl = self._box(x - r * 1.6, y - r * 1.6, x + r * 1.6, y + r * 1.6)+ if sl is None: return+ yy, xx = np.mgrid[sl].astype(np.float32)+ a = np.deg2rad(rot); c, s = np.cos(a), np.sin(a)+ u, v = (xx - x) * c + (yy - y) * s, -(xx - x) * s + (yy - y) * c+ rr = np.hypot(u / 0.72, v)+ wob = (noise2d(yy.shape[0], yy.shape[1], 14, 2, self._seed()) - 0.5) * 6+ ridge = 0.5 + 0.5 * np.sin(2 * np.pi * (rr + wob + 0.12 * u) / period)+ env = np.clip(1 - rr / r, 0, 1) ** 0.7 * (0.6 + 0.4 * noise2d(yy.shape[0], yy.shape[1], 20, 2, self._seed()))+ self.m[sl] += amount * ridge ** 1.5 * env++ def smear(self, pts, width=60.0, amount=0.05):+ """the grey haze where the side of the hand dragged across the sheet"""+ M = self.band(pts, width, feather=width * 0.35)+ sl = self._mask_box(M, pad=1, thr=0.01)+ if sl is None: return+ h, w = M[sl].shape+ self.m[sl] += amount * M[sl] * (0.5 + noise2d(h, w, 40, 3, self._seed()))++ # ------------------------------------------------------------ output+ def composite(self):+ D = self.dmax * (1 - np.exp(-self.m))+ g = np.array(GRAPHITE, np.float32)+ img = self.base * (1 - D[..., None]) + g * D[..., None]+ pol = smoothstep(0.25, 1.6, self.b) * D+ H, W = self.H, self.W+ YY, XX = self._grid()+ glare = 0.6 + 0.4 * (1 - (XX / W * 0.5 + YY / H * 0.5))+ img = img + (np.array(SHEEN, np.float32) - img) * (pol * 0.16 * glare)[..., None]+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if str(path).lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ import os+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/linocut.py b/lib/linocut.pynew file mode 100644index 0000000..8ed56bb--- /dev/null+++ b/lib/linocut.py@@ -0,0 +1,845 @@+"""linocut — a black-and-white linoleum-block print with one spot-colour block (numpy + Pillow only).++Model:+ block : a sheet of linoleum glued to a board. Rolled up with ink, the uncut block prints one solid black+ rectangle; everything white in the print is lino the carver *removed*. So the picture is made by+ subtraction: every block is a relief map (uint8, `ss`x the canvas) where 255 = surface that takes+ ink and 0 = cut away. The key block starts solid; a spot-colour block starts cleared and only the+ shapes that should print in colour are left standing. A rim around the key block is never cut, so the+ print has the slightly wobbly black frame of a hand-cut block.+ tools : every cut is a tapered polygon with a crumbly edge (lino tears a little):+ 'v' V-gouge / liner: starts at a point as the tool dips in, widens with depth, thins out as it is+ lifted -- leaf- and comma-shaped marks (sky streaks, hatching, needles, outlines);+ 'u' U-gouge / scoop: a round head where it bites, a ragged tail where the chip breaks off (snowflakes,+ snow on branches, clearing);+ 'knife' constant-width cut with clean ends (window frames, planks);+ 'brush' width runs linearly from `width` to `end` (branches, smoke, things you *leave* standing).+ Every tool can also *leave* (cut=False): a line of standing lino in a cleared area prints black.+ Clearing a big area with a wide gouge never leaves a perfectly flat floor: low ridges and islands+ ("chatter") catch a little ink and print as faint broken marks along the gouging direction.+ Shading is never grey: it is the density and width of cuts (white lines in black) or of ridges left+ standing (black lines in white).+ print : each block is inked with a brayer (an ink film that varies, with faint stop-lines across) and+ burnished by hand with a baren (circular pressure swirls). Ink only reaches the paper where film x+ pressure beats the paper's tooth, so big blacks are "salty": pin-holes where the paper fibres stay+ bare, more of them where the pressure was low, and the swirls of the baren show through. Ink is+ squeezed to the edges of every shape, so edges stay solid even where the middle is salty.+ Overprint: the colour block is printed first, slightly out of register (`offset`), and the key block+ on top -- colour under black disappears, colour that misses a carved window leaves a cream sliver.+ The paper is pressed into the block, so carved (white) areas and the margin stand slightly proud+ and catch the light (a faint emboss around every shape and the plate edge).+ finish : pencil in the bottom margin (edition number, title, signature) in graphite that only catches+ the top of the paper's tooth, and an optional blind chop (an un-inked embossed seal).++ from linocut import Linocut+ L = Linocut(1920, 1080, block=(100, 56, 1820, 918), seed=3)+ sky = [(100, 56), (1820, 56), (1820, 500), (100, 520)]+ field = [(100, 520), (1820, 500), (1820, 918), (100, 918)]+ L.flow(sky, lambda x, y: 172, n=300, length=(60, 300), width=(2, 6)) # wind streaks cut into the black+ L.moon(1500, 200, 70)+ L.clear(L.poly(field), chatter=0.5) # the snow field cut away+ L.hatch(field, angle=0, spacing=14, width=3, cut=False, # drift ridges left standing+ bend=lambda x, y: 12 * np.sin(x / 150 + y / 40), density=lambda x, y: 0.4)+ lamp = L.colour_block('#e8a33a', offset=(4, -3)) # one spot colour, out of register+ L.cottage(800, 600, 180, 110, 100, side=160, side_windows=[(40, 36, 32, 38)], chimney=(0.5, 20, 40), lit=lamp)+ L.speckle(None, n=1200) # falling snow+ L.sign('7/30', 'Title', 'Signature 2026'); L.chop(1800, 1010)+ L.save('out.jpg')+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, curve, noise2d, smoothstep, polygon_mask, shift, 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)+++def _resample(pts, step):+ P = np.asarray(pts, np.float32)+ if len(P) < 2: return P, 0.0+ d = np.linalg.norm(np.diff(P, axis=0), axis=1)+ s = np.concatenate([[0], np.cumsum(d)])+ L = float(s[-1])+ if L < 1e-3: return P[:1], 0.0+ n = max(2, int(L / step) + 1)+ u = np.linspace(0, L, n)+ return np.stack([np.interp(u, s, P[:, 0]), np.interp(u, s, P[:, 1])], 1).astype(np.float32), L+++def _soft(m):+ """tiny separable [1 2 1] blur (sub-2px softening; core.blur is a no-op below sigma ~1.2)"""+ p = np.pad(m, 1, mode='edge')+ m = (p[:, :-2] + 2 * p[:, 1:-1] + p[:, 2:]) / 4+ return (m[:-2] + 2 * m[1:-1] + m[2:]) / 4+++class Block:+ """one carved block: relief map `a` (uint8, ss x canvas; 255 = uncut surface that takes ink)"""++ def __init__(self, name, colour, shape, offset=(0, 0), seed=0):+ self.name, self.colour, self.offset, self.seed = name, colour, offset, seed+ self.a = np.zeros(shape, np.uint8)+++class Linocut:+ def __init__(self, W=1920, H=1080, block=(100, 56, 1820, 918), seed=0, paper='#eee7d4', ink='#1c1a19',+ ss=2, rim=7):+ self.W, self.H, self.ss = W, H, ss+ self.box = tuple(int(v) for v in block)+ self.rng = np.random.default_rng(seed)+ self.paper_c = _c(paper)+ self.stages = []+ self.chatter = np.zeros((H, W), np.float32) # faint ink caught by ridges left in cleared areas+ self.pencil = np.zeros((H, W), np.float32)+ self.relief = np.zeros((H, W), np.float32) # blind emboss (chop)+ self._make_paper()+ self._make_block(rim)+ self.key = Block('key', _c(ink), (H * ss, W * ss), seed=self._seed())+ self.key.a[:] = self._outer+ self.blocks = [self.key]++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ paper and block+ def _make_paper(self):+ H, W, r = self.H, self.W, self.rng+ g = r.random((H, W)).astype(np.float32)+ g = 0.55 * _soft(_soft(g)) + 0.45 * noise2d(H, W, 5, 3, self._seed())+ lo, hi = np.percentile(g[::7, ::7], (2, 98))+ self.grain = np.clip((g - lo) / (hi - lo), 0, 1) # paper tooth, 1 = fibre tops+ tone = noise2d(H, W, 420, 3, self._seed())+ fib = Image.new('L', (W, H), 0); d = ImageDraw.Draw(fib)+ for _ in range(2600): # short wandering fibres+ x, y = r.uniform(0, W), r.uniform(0, H)+ a = r.uniform(0, np.pi); L = r.uniform(6, 26)+ pts = curve((x, y), (x + np.cos(a) * L, y + np.sin(a) * L), r.uniform(-4, 4), 6)+ d.line([tuple(p) for p in pts], fill=int(r.uniform(40, 120)), width=1)+ fib = np.asarray(fib, np.float32) / 255+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)+ vig = ((xx / W - 0.5) ** 2 + (yy / H - 0.5) ** 2)+ base = self.paper_c[None, None, :] * (0.985 + 0.03 * tone[..., None] - 0.05 * vig[..., None])+ base = base * (1 - 0.035 * fib[..., None]) * (0.985 + 0.03 * self.grain[..., None])+ self.paper = base.astype(np.float32)+ n = r.random((H, W)).astype(np.float32)+ self.crumble = _soft(_soft(n)) # edge tear noise+ self.crumble = (self.crumble - self.crumble.mean()) / (self.crumble.std() + 1e-6)++ def _make_block(self, rim):+ """outer edge of the lino (sawn, slightly wavy, rounded corners) and the inner edge of the uncut rim"""+ S, (x0, y0, x1, y1) = self.ss, self.box++ def edge(inset, amp, seed):+ pts = []+ sides = [((x0, y0), (x1, y0)), ((x1, y0), (x1, y1)), ((x1, y1), (x0, y1)), ((x0, y1), (x0, y0))]+ for k, (a, b) in enumerate(sides):+ a, b = np.array(a, np.float32), np.array(b, np.float32)+ L = np.linalg.norm(b - a); n = int(L / 6) + 2+ t = np.linspace(0, 1, n)[:-1]+ dvec = (b - a) / L; nrm = np.array([-dvec[1], dvec[0]]) # points inward (clockwise sides)+ w = fbm1d(n, 40, 4, seed + k)[:-1] * amp+ for ti, wi in zip(t, w):+ p = a + (b - a) * ti+ pts.append(p + nrm * (inset + wi))+ return [(float(px) * S, float(py) * S) for px, py in pts]++ im = Image.new('L', (self.W * S, self.H * S), 0)+ ImageDraw.Draw(im).polygon(edge(0.0, 0.8, self._seed()), fill=255)+ self._outer = np.asarray(im).copy()+ im = Image.new('L', (self.W * S, self.H * S), 0)+ ImageDraw.Draw(im).polygon(edge(rim, 2.2, self._seed()), fill=255)+ self._inside = np.asarray(im).copy() # cuttable area++ def colour_block(self, colour, offset=(3, -2), mottle=0.25):+ """a second block for one spot colour; `colour` is how the ink looks printed on this paper.+ It starts cleared: `leave()` the shapes that should print. offset = misregistration in px; mottle = how+ much a light ink shows the paper's tooth and the uneven film (0 = flat)."""+ ink = np.clip(_c(colour) / self.paper_c.mean(), 0, 1)+ b = Block('colour', ink, self.key.a.shape, offset, self._seed())+ b.mottle = mottle+ self.blocks.insert(len(self.blocks) - 1, b) # printed before the key block+ return b++ # ------------------------------------------------------------ masks+ def poly(self, pts, smooth=False):+ """1x float mask of a polygon (smooth=True runs a Catmull-Rom spline through the points first)"""+ P = spline(list(pts) + [pts[0]], 8) if smooth else pts+ return polygon_mask(self.H, self.W, P, ss=2)++ def disc(self, cx, cy, r):+ yy, xx = np.ogrid[0:self.H, 0:self.W]+ return np.clip(r + 0.5 - np.sqrt((xx - cx) ** 2 + (yy - cy) ** 2), 0, 1).astype(np.float32)++ def rect(self, x0, y0, x1, y1):+ return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])++ def _bbox(self, region, pad=2):+ if region is None:+ x0, y0, x1, y1 = self.box+ elif isinstance(region, np.ndarray) and region.shape == (self.H, self.W):+ ys, xs = np.nonzero(region > 0.01)+ if len(xs) == 0: return None+ x0, x1, y0, y1 = xs.min(), xs.max() + 1, ys.min(), ys.max() + 1+ else:+ P = np.asarray(region, np.float32)+ x0, y0 = P.min(0); x1, y1 = P.max(0)+ x0 = int(max(0, np.floor(x0) - pad)); y0 = int(max(0, np.floor(y0) - pad))+ x1 = int(min(self.W, np.ceil(x1) + pad)); y1 = int(min(self.H, np.ceil(y1) + pad))+ if x1 <= x0 or y1 <= y0: return None+ return x0, y0, x1, y1++ def _region(self, region, box):+ """uint8 crop (ss) of a region over `box`: None = whole block, polygon points, or a 1x float mask"""+ S, (x0, y0, x1, y1) = self.ss, box+ if region is None:+ return self._inside[y0 * S:y1 * S, x0 * S:x1 * S]+ if isinstance(region, np.ndarray) and region.shape == (self.H, self.W):+ c = Image.fromarray((np.clip(region[y0:y1, x0:x1], 0, 1) * 255).astype(np.uint8))+ return np.asarray(c.resize(((x1 - x0) * S, (y1 - y0) * S), Image.BILINEAR))+ im = Image.new('L', ((x1 - x0) * S, (y1 - y0) * S), 0)+ P = (np.asarray(region, np.float32) - (x0, y0)) * S+ ImageDraw.Draw(im).polygon([tuple(p) for p in P], fill=255)+ return np.asarray(im)++ def _apply(self, t, box, cut, on, region=None):+ blk = on or self.key+ S, (x0, y0, x1, y1) = self.ss, box+ sl = (slice(y0 * S, y1 * S), slice(x0 * S, x1 * S))+ if region is not None: t = np.minimum(t, self._region(region, box))+ t = np.minimum(t, self._inside[sl])+ a = blk.a[sl]+ if cut: np.minimum(a, 255 - t, out=a)+ else: np.maximum(a, t, out=a)++ def _draw(self, polys, cut, on=None, region=None):+ polys = [p for p in polys if p is not None and len(p) >= 3]+ if not polys: return+ allp = np.concatenate(polys)+ box = self._bbox(allp, 3)+ if region is not None and box is not None:+ rb = self._bbox(region, 2)+ if rb is None: return+ box = (max(box[0], rb[0]), max(box[1], rb[1]), min(box[2], rb[2]), min(box[3], rb[3]))+ if box[2] <= box[0] or box[3] <= box[1]: return+ if box is None: return+ S, (x0, y0, x1, y1) = self.ss, box+ im = Image.new('L', ((x1 - x0) * S, (y1 - y0) * S), 0); d = ImageDraw.Draw(im)+ for p in polys:+ q = (p - (x0, y0)) * S+ d.polygon([tuple(v) for v in q], fill=255)+ self._apply(np.asarray(im), box, cut, on, region)++ # ------------------------------------------------------------ one cut+ def stroke(self, pts, width, tool='v', taper=None, end=None, jitter=0.12, smooth=False):+ """polygon (canvas px) of one gouge mark along `pts`; see the module docstring for the tools"""+ r = self.rng+ P = spline(pts, 10) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)+ P, L = _resample(P, max(0.7, min(2.5, width * 0.35)))+ n = len(P)+ if n < 2: return None+ t = np.linspace(0, 1, n, dtype=np.float32); s = t * L+ if tool == 'v':+ ta, tb = taper if taper else (r.uniform(0.12, 0.42), r.uniform(0.08, 0.3))+ w = width * np.clip(t / max(ta, 1e-3), 0, 1) ** 0.7 * np.clip((1 - t) / max(tb, 1e-3), 0, 1) ** 0.55+ elif tool == 'u':+ rad = width / 2+ head = np.sqrt(np.clip(1 - np.clip(1 - s / max(rad, 1e-3), 0, 1) ** 2, 0, 1))+ tb = taper[1] if taper else r.uniform(0.12, 0.4)+ w = width * head * np.clip((1 - t) / max(tb, 1e-3), 0, 1) ** 0.7+ elif tool == 'brush':+ e = width * 0.2 if end is None else end+ w = width + (e - width) * t+ cap = min(0.5, 0.8 * width / max(L, 1))+ w = w * np.clip(t / max(cap, 1e-3), 0, 1) ** 0.35+ else: # knife+ e = min(0.5, 1.0 / max(L, 1))+ w = width * np.clip(np.minimum(t, 1 - t) / e, 0, 1) ** 0.4+ tg = np.gradient(P, axis=0); tg /= (np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6)+ nr = np.stack([-tg[:, 1], tg[:, 0]], 1)+ k = int(r.integers(1 << 30))+ jl = fbm1d(n, max(3, n / 5), 3, k) * jitter * width+ jr = fbm1d(n, max(3, n / 5), 3, k + 1) * jitter * width+ fade = np.clip(w / max(width, 1e-3) * 3, 0, 1)+ hl = np.maximum(w / 2 + jl * fade, 0); hr = np.maximum(w / 2 + jr * fade, 0)+ return np.concatenate([P + nr * hl[:, None], (P - nr * hr[:, None])[::-1]])++ def gouge(self, pts, width, tool='v', cut=True, on=None, taper=None, end=None, smooth=True, jitter=0.12,+ region=None):+ """one cut (or, cut=False, one line of lino left standing) along `pts`"""+ self._draw([self.stroke(pts, width, tool, taper, end, jitter, smooth)], cut, on, region)++ def jab(self, x, y, size, angle=200, cut=True, on=None):+ """a single short poke of the U-gouge (snowflakes, stipple)"""+ a = np.radians(angle + self.rng.uniform(-25, 25)); L = size * self.rng.uniform(1.0, 1.9)+ self._draw([self.stroke([(x, y), (x + np.cos(a) * L, y + np.sin(a) * L)], size, 'u')], cut, on)++ # ------------------------------------------------------------ many cuts+ def leave(self, shape, on=None):+ """keep a shape standing (prints solid): polygon points or a 1x mask"""+ box = self._bbox(shape)+ if box: self._apply(self._region(shape, box), box, False, on)++ def clear(self, shape, on=None, chatter=0.35, angle=0.0):+ """cut a whole area away with a wide gouge; chatter = how many low ridges and islands survive to+ catch a little ink (gouging direction `angle`, more of them near the edges of the area)"""+ box = self._bbox(shape)+ if not box: return+ t = self._region(shape, box)+ self._apply(t, box, True, on)+ if not chatter or (on is not None and on is not self.key): return+ r, (x0, y0, x1, y1) = self.rng, box+ S = self.ss+ m = np.asarray(Image.fromarray(t).resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ near = np.clip((1 - blur(m, 9)) * 2.2, 0, 1) * m # close to the edge of the area+ prob = (0.25 + 0.75 * near) * (m > 0.95)+ n = int(prob.sum() * chatter / 420)+ if n <= 0: return+ flat = prob.ravel() / prob.sum()+ idx = r.choice(flat.size, size=n, p=flat)+ ys, xs = np.divmod(idx, x1 - x0)+ im = Image.new('L', (x1 - x0, y1 - y0), 0); d = ImageDraw.Draw(im)+ for x, y in zip(xs, ys):+ a = np.radians(angle + r.normal(0, 14)); L = r.uniform(6, 30)+ if r.random() < 0.15: # an island the gouge skipped+ rx, ry = r.uniform(1, 3.5), r.uniform(1, 2.5)+ d.ellipse([x - rx, y - ry, x + rx, y + ry], fill=int(r.uniform(90, 200)))+ continue+ nrm = np.array([-np.sin(a), np.cos(a)])+ for q in range(int(r.choice([1, 1, 2, 3]))): # neighbouring passes of the gouge+ o = nrm * q * r.uniform(3, 6); Lq = L * r.uniform(0.5, 1.0)+ pts = curve((x + o[0], y + o[1]), (x + o[0] + np.cos(a) * Lq, y + o[1] + np.sin(a) * Lq), r.uniform(-1, 1), 5)+ d.line([tuple(p) for p in pts], fill=int(r.uniform(60, 170)), width=int(r.choice([1, 2, 2])))+ c = np.asarray(im, np.float32) / 255 * m+ sl = self.chatter[y0:y1, x0:x1]+ np.maximum(sl, c, out=sl)++ def hatch(self, region, angle=0.0, spacing=8, width=3, dash=(30, 120), gap=(4, 30), tool='v', cut=True,+ on=None, density=None, bend=None, jitter=0.12, wobble=0.0, box=None):+ """rows of parallel gouge strokes across `region` at `angle` degrees.+ density(x, y) -> 0..1: chance a stroke survives (its width scales with it too) -- this is how a+ linocut shades. bend(x, y) -> px pushed across the row (curved hatching: drifts, contours, folds)."""+ r = self.rng+ box = box or self._bbox(region)+ if not box: return+ x0, y0, x1, y1 = box+ th = np.radians(angle); dv = np.array([np.cos(th), np.sin(th)], np.float32)+ nv = np.array([-dv[1], dv[0]], np.float32)+ c = np.array([(x0 + x1) / 2, (y0 + y1) / 2], np.float32)+ R = 0.5 * np.hypot(x1 - x0, y1 - y0) + 4+ polys = []+ for v in np.arange(-R, R, spacing):+ v = v + r.uniform(-0.2, 0.2) * spacing+ u = -R - r.uniform(0, dash[1])+ while u < R:+ Ld = r.uniform(*dash)+ us = np.linspace(u, u + Ld, max(3, int(Ld / 5)))+ base = c + dv * us[:, None] + nv * v+ off = np.zeros(len(us), np.float32)+ if bend is not None: off = off + bend(base[:, 0], base[:, 1])+ if wobble: off = off + fbm1d(len(us), max(3, len(us) / 3), 2, int(r.integers(1 << 30))) * wobble+ pts = base + nv * off[:, None]+ mx, my = pts[len(pts) // 2]+ if x0 - 40 <= mx <= x1 + 40 and y0 - 40 <= my <= y1 + 40:+ dn = float(np.clip(density(mx, my), 0, 1)) if density else 1.0+ if r.random() < dn:+ polys.append(self.stroke(pts, width * (0.55 + 0.45 * dn), tool, jitter=jitter))+ u += Ld + r.uniform(*gap)+ self._draw(polys, cut, on, region)++ def flow(self, region, field, n=200, length=(40, 200), width=(2, 5), tool='v', cut=True, on=None, step=3.0,+ density=None, seeds=None, jitter=0.12, taper=None):+ """strokes that follow a direction field: field(x, y) -> angle in degrees (wind, smoke, fur, water)"""+ r = self.rng+ box = self._bbox(region)+ if not box: return+ x0, y0, x1, y1 = box+ polys = []+ for i in range(n if seeds is None else len(seeds)):+ if seeds is not None:+ x, y = seeds[i]+ else:+ for _ in range(30):+ x, y = r.uniform(x0, x1), r.uniform(y0, y1)+ if density is None or r.random() < density(x, y): break+ else:+ continue+ L = r.uniform(*length); pts = [(x, y)]+ for _ in range(max(2, int(L / step))):+ a = np.radians(field(x, y)); x += np.cos(a) * step; y += np.sin(a) * step+ pts.append((x, y))+ polys.append(self.stroke(pts, r.uniform(*width), tool, taper=taper, jitter=jitter))+ self._draw(polys, cut, on, region)++ def speckle(self, region=None, n=500, size=(2, 6), angle=200, stars=0.015, on_ink=True):+ """falling snow / stipple: U-gouge pokes, a few six-point flakes made of three crossing V nicks.+ on_ink: only bother where the block still has surface (a poke in a cleared area prints nothing)"""+ r, S = self.rng, self.ss+ box = self._bbox(region)+ if not box: return+ x0, y0, x1, y1 = box+ polys = []+ for _ in range(n):+ for _ in range(20):+ x, y = r.uniform(x0, x1), r.uniform(y0, y1)+ if not on_ink or self.key.a[int(y * S), int(x * S)] > 128: break+ else:+ continue+ if r.random() < stars:+ s = r.uniform(size[1] * 1.3, size[1] * 2.4); a0 = r.uniform(0, 60)+ for k in range(3):+ a = np.radians(a0 + 60 * k)+ polys.append(self.stroke([(x - np.cos(a) * s, y - np.sin(a) * s), (x + np.cos(a) * s, y + np.sin(a) * s)],+ s * 0.32, 'v', taper=(0.45, 0.45), jitter=0.05))+ else:+ sz = r.uniform(*size); a = np.radians(angle + r.uniform(-25, 25)); L = sz * r.uniform(0.9, 1.8)+ polys.append(self.stroke([(x, y), (x + np.cos(a) * L, y + np.sin(a) * L)], sz, 'u'))+ self._draw(polys, True, None, region)++ def rings(self, cx, cy, radii, width=3.0, arc=(0.5, 1.8), gap=(0.06, 0.35), tool='v', cut=True, on=None,+ squash=1.0):+ """broken concentric cuts (a halo of rings round a moon or a lamp, ripples, growth rings)"""+ r = self.rng+ polys = []+ for R in radii:+ a = r.uniform(0, 2 * np.pi); end = a + 2 * np.pi+ while a < end:+ da = min(r.uniform(*arc), end - a)+ if da > 0.08:+ t = np.linspace(a, a + da, max(4, int(R * da / 4)))+ rr = R * (1 + 0.012 * fbm1d(len(t), 8, 2, int(r.integers(1 << 30))))+ polys.append(self.stroke(np.stack([cx + np.cos(t) * rr, cy + np.sin(t) * rr * squash], 1),+ width * r.uniform(0.7, 1.15), tool))+ a += da + r.uniform(*gap)+ self._draw(polys, cut, on)++ def outline(self, shape, width=3.0, on=None, cut=True):+ """cut a thin white contour round a shape so a black thing still reads against a black ground+ (the classic linocut halo); then leave() or draw the shape itself. cut=False leaves a black contour+ instead (a white thing crossing a white ground)"""+ box = self._bbox(shape, int(width) + 4)+ if not box: return+ S = self.ss+ t = self._region(shape, box).astype(np.float32) / 255+ dil = blur(t, max(0.8, width * S * 0.55)) > 0.04+ ring = (dil & (t < 0.5)).astype(np.uint8) * 255+ self._apply(ring, box, cut, on)++ def mask_of(self, polys):+ """1x float mask of a list of stroke polygons (to outline or clip a group of strokes)"""+ im = Image.new('L', (self.W * 2, self.H * 2), 0); d = ImageDraw.Draw(im)+ for p in polys:+ if p is not None and len(p) >= 3: d.polygon([tuple(v * 2) for v in p], fill=255)+ return np.asarray(im.resize((self.W, self.H), Image.BOX), np.float32) / 255++ # ------------------------------------------------------------ things+ def moon(self, cx, cy, r, rings=(1.45, 1.8, 2.2, 2.65), shade=True):+ """a carved-out moon: the disc cleared, a crescent of curved ridges left on the shadow side, a few+ maria, broken rings cut round it"""+ self.clear(self.disc(cx, cy, r), chatter=0.25, angle=-30)+ if shade:+ k = 0+ for f in np.linspace(1.02, 1.4, 5):+ t = np.linspace(-0.4, 2.0, 60)+ ox, oy = cx - r * 0.42, cy - r * 0.36+ P = np.stack([ox + np.cos(t) * r * f, oy + np.sin(t) * r * f], 1)+ self.gouge(P, 2.2 + 2.0 * k / 4, 'v', cut=False, smooth=False, region=self.disc(cx, cy, r - 1.5))+ k += 1+ self.rings(cx, cy, [r * f for f in rings], width=3.0, arc=(0.35, 1.2), gap=(0.15, 0.6))++ def pine(self, x, y, h, w=None, tiers=None, snow=0.8, halo=2.5, nicks=0.5, region=None):+ """a snow-loaded spruce left standing: stacked drooping tiers, white snow bands cut along the top of+ each tier, V nicks for needles on the lit side, an optional white halo against a black ground"""+ r = self.rng+ w = w or h * 0.46+ k = tiers or max(3, int(h / 24))+ polys, edges = [], []+ for i in range(k):+ yt = y - h + h * 0.86 * i / k+ yb = y - h + h * 0.86 * (i + 1.55) / k+ hw = w / 2 * (0.22 + 0.78 * (i + 1) / k) * r.uniform(0.9, 1.08)+ tips = int(np.clip(hw / 9, 2, 7))+ low = []+ for j in range(tips + 1):+ fx = -1 + 2 * j / tips+ ty = yb + r.uniform(-0.12, 0.08) * (yb - yt) - abs(fx) * 0.12 * (yb - yt)+ low.append((x + fx * hw, ty))+ if j < tips:+ low.append((x + (fx + 1 / tips) * hw * 0.98, ty - r.uniform(0.18, 0.32) * (yb - yt)))+ P = [(x, yt)] + [(x + hw * 0.55, yt + (yb - yt) * 0.55)] + low[::-1] + [(x - hw * 0.55, yt + (yb - yt) * 0.55)]+ polys.append(np.array(P, np.float32)); edges.append((low, yb - yt))+ polys.append(np.array([(x - w * 0.05, y - h * 0.15), (x + w * 0.05, y - h * 0.15), (x + w * 0.06, y), (x - w * 0.06, y)], np.float32))+ m = self.mask_of(polys)+ if region is not None: m = m * (region if isinstance(region, np.ndarray) else self.poly(region))+ if halo: self.outline(m, halo)+ self.leave(m)+ if snow:+ cuts = []+ for i in range(1, k):+ low, th = edges[i - 1]+ band = np.array(low, np.float32)+ band = band[np.argsort(band[:, 0])]+ for j in range(len(band) - 1):+ if r.random() > snow: continue+ a, b = band[j], band[j + 1]+ mid = (a + b) / 2 + (0, th * r.uniform(0.18, 0.3))+ cuts.append(self.stroke([a + (0, th * 0.16), mid, b + (0, th * 0.16)], th * r.uniform(0.16, 0.26), 'u',+ smooth=True))+ sm = self.mask_of(cuts) * m+ self._apply_mask(sm, True)+ if nicks:+ cuts = []+ for i in range(k):+ yt = y - h + h * 0.86 * i / k; yb = y - h + h * 0.86 * (i + 1.55) / k+ for _ in range(int(nicks * 5)):+ fy = r.uniform(0.45, 0.85); yy = yt + (yb - yt) * fy+ hw = w / 2 * (0.22 + 0.78 * (i + 1) / k) * fy+ xx = x + r.uniform(0.15, 0.85) * hw+ cuts.append(self.stroke([(xx, yy), (xx + hw * 0.3, yy + (yb - yt) * 0.18)], r.uniform(1.6, 2.6), 'v'))+ self._apply_mask(self.mask_of(cuts) * m, True)++ def _apply_mask(self, m, cut, on=None):+ box = self._bbox(m)+ if box: self._apply(self._region(m, box), box, cut, on)++ def bare_tree(self, x, y, h, lean=0.0, spread=1.0, width=None, depth=6, halo=3.0, snow=True, seed=None):+ """a leafless tree left standing as tapered branches; a halo where it crosses black, snow cut along+ the top of the thicker branches. Returns the 1x mask of the tree."""+ r = np.random.default_rng(seed if seed is not None else self._seed())+ width = width or h * 0.05+ segs = []++ def grow(p, ang, L, wd, d):+ if d > depth or wd < 0.9 or L < 6: return+ bend = r.uniform(-0.18, 0.18) * L+ q = (p[0] + np.cos(ang) * L, p[1] + np.sin(ang) * L)+ pts = curve(p, q, bend, 14, wig=L * 0.03, seed=int(r.integers(1 << 30)))+ tip = d >= depth or wd * 0.62 < 0.9+ segs.append((pts, wd, 0.5 if tip else wd * 0.62))+ nb = 2 if d < 2 else int(r.choice([2, 2, 3])) if d < 4 else int(r.choice([1, 2, 2]))+ for j in range(nb):+ da = (j - (nb - 1) / 2) * r.uniform(0.45, 0.8) * spread + r.normal(0, 0.12)+ if d == 0 and nb == 2: da *= 1.25+ grow(q, ang + da - 0.12 * np.sign(np.cos(ang + da)) * (d > 1), L * r.uniform(0.62, 0.8), wd * 0.62, d + 1)++ grow((x, y), -np.pi / 2 + lean, h * 0.36, width, 0)+ polys = [self.stroke(pts, w0, 'brush', end=w1, jitter=0.06) for pts, w0, w1 in segs]+ rootw = width * 1.05 # flare into the ground+ polys.append(np.array([(x - rootw, y + 4), (x - width * 0.45, y - h * 0.08), (x + width * 0.45, y - h * 0.08), (x + rootw, y + 4)], np.float32))+ m = self.mask_of(polys)+ if halo: self.outline(m, halo)+ self.leave(m)+ if snow:+ cuts = []+ for pts, w0, w1 in segs:+ if w0 < 4: continue+ P = np.asarray(pts)+ dx, dy = P[-1] - P[0]+ if abs(dy) > abs(dx) * 1.6: continue # snow sits on the flatter limbs+ lift = np.array([0, -w0 * 0.28], np.float32)+ cuts.append(self.stroke(P[2:-2] + lift, w0 * 0.34, 'u', taper=(0, 0.35)))+ self._apply_mask(self.mask_of(cuts) * m, True)+ return m++ def cottage(self, x, base, fw, wall, roof, side=0.0, rise=0.1, windows=(), side_windows=(), door=None,+ chimney=None, lit=None, planks=8.0, snow=14.0, icicles=True, attic=False):+ """a snowy cottage, gable end to the viewer: black front with vertical boards cut in, a side wall+ receding to the right with horizontal boards, roofs heavy with snow (cleared white) and a few drift+ ridges, icicles cut under the eave. windows: (u, v, w, h) in px from the front's bottom-left corner;+ side_windows: (u, v, w, h) along the side wall. door: (u, w, h, open). lit: a colour block -> lit+ windows print in it. Returns a dict of geometry (apex, chimney top, door rect, window rects)."""+ r = self.rng+ k = -rise+ ax, ay = x + fw / 2, base - wall - roof+ eL, eR = (x, base - wall), (x + fw, base - wall)+ dv = np.array([side, side * k], np.float32)+ front = [(x, base), (x, base - wall), (ax, ay), (x + fw, base - wall), (x + fw, base)]+ sidew = [(x + fw, base), (x + fw + side, base + side * k), (x + fw + side, base - wall + side * k), (x + fw, base - wall)]+ roofp = [(ax, ay), (ax + dv[0], ay + dv[1]), (eR[0] + dv[0] + 6, eR[1] + dv[1] + 4), (eR[0] + 6, eR[1] + 4)]+ self.outline(self.poly(front), 2.5)+ self.leave(front)+ if side > 0:+ self.leave(sidew)+ # boards on the side wall: horizontal knife cuts, broken+ for i in range(1, int(wall / planks)):+ yy = base - wall + i * planks+ p0 = np.array([x + fw + 3, yy]); p1 = np.array([x + fw + side - 3, yy + side * k])+ f0 = r.uniform(0, 0.25); f1 = r.uniform(0.6, 1.0)+ self.gouge([p0 + (p1 - p0) * f0, p0 + (p1 - p0) * f1], r.uniform(1.4, 2.2), 'v', smooth=False,+ region=sidew)+ # vertical boards on the front+ for xx in np.arange(x + 8, x + fw - 4, planks * 1.25):+ top = base - wall + 4 if abs(xx - ax) > fw * 0.3 else ay + roof * 0.35 + abs(xx - ax) * roof / (fw / 2) * 0.6+ yb = base - r.uniform(2, 10); yt = top + r.uniform(4, 30)+ self.gouge([(xx, yt), (xx + r.uniform(-1, 1), yb)], r.uniform(1.3, 2.0), 'v', smooth=False, region=front)+ geo = {'apex': (ax, ay), 'windows': [], 'door': None}+ # roof snow: side plane cleared, thick snow lip along the front gable edges+ if side > 0:+ lip = [(ax, ay - snow * 0.8), (ax + dv[0], ay + dv[1] - snow * 0.8)]+ bulge = []+ n = 9+ for i in range(n + 1):+ f = i / n+ p = np.array(eR) + dv * f+ bulge.append((p[0] + 6, p[1] + 5 + snow * 0.25 * np.sin(np.pi * f * 3 + r.uniform(0, 1)) ** 2))+ snowp = lip + bulge[::-1]+ self.clear(self.poly(snowp, smooth=False), chatter=0.2, angle=np.degrees(np.arctan2(eR[1] - ay, eR[0] - ax)))+ # drift ridges on the roof running down the slope, sparse+ slope = np.degrees(np.arctan2(eR[1] - ay, eR[0] - ax))+ self.hatch(snowp, angle=slope, spacing=9, width=2.2, dash=(18, 60), gap=(20, 70), cut=False,+ density=lambda xx, yy: 0.45)+ self.gouge([(eR[0] + 4, eR[1] + 7), (eR[0] + dv[0] + 6, eR[1] + dv[1] + 7)], 3.0, 'knife', cut=False,+ smooth=False)+ lipL = [(x - 10, base - wall + 4), (ax, ay - snow), (ax + 3, ay + snow * 0.7), (x + 2, base - wall + snow * 0.6)]+ self.clear(self.poly(lipL), chatter=0.0)+ lipR = [(ax - 3, ay - snow), (x + fw + 10, base - wall + 2), (x + fw - 2, base - wall + snow * 0.6), (ax, ay + snow * 0.7)]+ self.clear(self.poly(lipR), chatter=0.0)+ # eave line left standing under the snow lips+ self.gouge([(x - 6, base - wall + snow * 0.62 + 1), (ax, ay + snow * 0.78)], 2.4, 'knife', cut=False, smooth=False)+ self.gouge([(ax, ay + snow * 0.78), (x + fw + 6, base - wall + snow * 0.62 + 1)], 2.4, 'knife', cut=False, smooth=False)+ if icicles and side > 0:+ for i in range(int(side / 9)):+ f = (i + r.uniform(0.2, 0.8)) / (side / 9)+ p = np.array(eR) + dv * f + (6, 10)+ L = r.uniform(5, 18)+ self.gouge([p, p + (r.uniform(-1, 1), L)], r.uniform(2.2, 3.6), 'v', taper=(0.05, 0.9), smooth=False)+ if attic:+ self.clear(self.disc(ax, ay + roof * 0.55, roof * 0.12), chatter=0)+ self.leave([(ax - 1.3, ay + roof * 0.43), (ax + 1.3, ay + roof * 0.43), (ax + 1.3, ay + roof * 0.67), (ax - 1.3, ay + roof * 0.67)])+ for (u, v, ww, wh) in windows:+ geo['windows'].append(self._window(x + u, base - v - wh, ww, wh, lit))+ for (u, v, ww, wh) in side_windows:+ x0 = x + fw + u; y0 = base - v - wh + u * k+ geo['windows'].append(self._window(x0, y0, ww, wh, lit, skew=k))+ if door:+ u, dw, dh, op = door+ d0, d1 = x + u, x + u + dw+ rect = [(d0, base - dh), (d1, base - dh), (d1, base + 1), (d0, base + 1)]+ if op:+ self.clear(self.poly(rect), chatter=0)+ if lit is not None: self.leave(self.poly([(d0 - 1, base - dh - 1), (d1 + 1, base - dh - 1), (d1 + 1, base + 2), (d0 - 1, base + 2)]), on=lit)+ self.leave([(d0, base - dh), (d0 + dw * 0.3, base - dh + 6), (d0 + dw * 0.3, base + 3), (d0, base + 1)]) # door leaf swung in+ self.gouge([(d0 + dw * 0.12, base - dh * 0.55), (d0 + dw * 0.2, base - dh * 0.53)], 2.2, 'knife', smooth=False)+ else:+ self.gouge([(d0, base - dh), (d1, base - dh)], 2, 'knife', smooth=False)+ self.gouge([(d0, base - dh), (d0, base)], 2, 'knife', smooth=False)+ self.gouge([(d1, base - dh), (d1, base)], 2, 'knife', smooth=False)+ geo['door'] = (d0, base - dh, d1, base)+ if chimney:+ u, cw, ch = chimney+ cx0 = ax + dv[0] * u+ cy = ay + dv[1] * u + (eR[1] - ay) * 0.3+ cp = [(cx0, cy - ch), (cx0 + cw, cy - ch), (cx0 + cw, cy + 12), (cx0, cy + 12)]+ self.outline(self.poly(cp), 2.5)+ self.leave(cp)+ self.clear(self.poly([(cx0 - 4, cy - ch + 2), (cx0 + cw / 2, cy - ch - 8), (cx0 + cw + 4, cy - ch + 2), (cx0 + cw + 3, cy - ch + 6), (cx0 - 3, cy - ch + 6)]), chatter=0)+ for yy in (cy - ch + 16, cy - ch + 30):+ xa = cx0 + r.uniform(2, cw * 0.4)+ self.gouge([(xa, yy), (xa + cw * 0.45, yy + r.uniform(-1, 1))], 1.5, 'v', smooth=False)+ geo['chimney'] = (cx0 + cw / 2, cy - ch - 6)+ return geo++ def _window(self, x0, y0, w, h, lit, skew=0.0):+ quad = [(x0, y0), (x0 + w, y0 + w * skew), (x0 + w, y0 + h + w * skew), (x0, y0 + h)]+ if lit is not None:+ self.clear(self.poly(quad), chatter=0)+ self.leave(self.poly([(x0 - 0.5, y0 - 0.5), (x0 + w + 0.5, y0 + w * skew - 0.5), (x0 + w + 0.5, y0 + h + w * skew + 0.5), (x0 - 0.5, y0 + h + 0.5)]), on=lit)+ else:+ self.clear(self.poly(quad), chatter=0)+ for f in (0.3, 0.55, 0.8): # a dark window: ridges left+ self.gouge([(x0, y0 + h * f), (x0 + w, y0 + h * f + w * skew)], 2.0, 'knife', cut=False, smooth=False)+ cx = x0 + w / 2+ self.gouge([(cx, y0 + w / 2 * skew), (cx, y0 + h + w / 2 * skew)], max(2.2, w * 0.1), 'knife', cut=False, smooth=False)+ self.gouge([(x0, y0 + h * 0.45), (x0 + w, y0 + h * 0.45 + w * skew)], max(2.2, w * 0.1), 'knife', cut=False, smooth=False)+ # snow on the sill+ self.gouge([(x0 - 3, y0 + h + 3), (x0 + w + 3, y0 + h + 3 + w * skew)], 4.0, 'u', taper=(0, 0.2), smooth=False)+ return quad++ def smoke(self, x, y, rise=160, drift=-220, width=10, edge=2.2):+ """chimney smoke cut out of the sky as a chain of billows that rise, lean with the wind and grow; each+ billow keeps a curl of black ridge on its shadow side; where it crosses something white a thin black+ edge is left standing so it still reads"""+ r = self.rng+ j = lambda k: r.normal(0, 0.09) * rise # no two plumes alike+ ctrl = [(x, y), (x + drift * 0.04 + j(0) * 0.3, y - rise * 0.35), (x + drift * 0.25 + j(1), y - rise * 0.72 + j(1) * 0.5),+ (x + drift * 0.6 + j(2), y - rise * 0.92 + j(2)), (x + drift, y - rise + j(3))]+ P, L = _resample(spline(ctrl, 12), 1.0)+ polys, curls = [], []+ rad = [] # billows grow; spaced to overlap+ while sum(rad) * 0.8 < L and len(rad) < 60:+ f = min(1.0, sum(rad) * 0.8 / max(L, 1))+ rad.append(width * (0.5 + 1.25 * f) * r.uniform(0.85, 1.15))+ pos = np.cumsum([0.0] + [q * 0.8 for q in rad[:-1]])+ pos = pos * (L - rad[-1] * 0.5) / max(pos[-1], 1)+ for rr, sp in zip(rad, pos):+ c = P[min(len(P) - 1, int(sp))] + r.uniform(-0.12, 0.12, 2) * rr+ polys.append(np.array(_blob(c[0], c[1], rr, r, 22), np.float32))+ t = np.linspace(-0.2, 1.5, 14) + r.uniform(-0.2, 0.2) # curl on the lower right of the billow+ curls.append((np.stack([c[0] + np.cos(t) * rr * 0.62, c[1] + np.sin(t) * rr * 0.62], 1), max(1.6, rr * 0.13)))+ m = self.mask_of(polys)+ self.outline(m, edge, cut=False) # black edge where it crosses white+ self._apply_mask(m, True)+ for pts, w in curls[3::3]:+ self.gouge(pts, w, 'v', cut=False, smooth=False, region=m)++ def footprints(self, path, step=24, size=7.0, side=5.0, start=0.0, stop=1.0, paws=False):+ """boot prints (or paw prints) left standing as small dark ovals in a cleared snow field"""+ r = self.rng+ P, L = _resample(spline(path, 12), 1.0)+ tg = np.gradient(P, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6+ polys = []+ s = start * L; i = 0+ while s < stop * L:+ j = int(s); p, d = P[j], tg[j]; nrm = np.array([-d[1], d[0]])+ sd = side if i % 2 else -side+ c = p + nrm * sd+ sz = size * r.uniform(0.85, 1.1)+ if paws:+ for q in range(2):+ cc = c + d * q * sz * 1.4 + nrm * (q - 0.5) * sz * 0.8+ polys.append(np.array(_blob(cc[0], cc[1], sz * 0.5, r), np.float32))+ else:+ a = c - d * sz; b = c + d * sz+ polys.append(self.stroke([a, b], sz * 0.95, 'u', taper=(0, 0.3), jitter=0.15))+ s += step * r.uniform(0.9, 1.1); i += 1+ self._draw(polys, False)++ # ------------------------------------------------------------ printing+ def _print_fields(self, blk):+ """brayer film and baren pressure for one pull of one block (fixed per block)"""+ if hasattr(blk, 'film'): return+ H, W = self.H, self.W+ r = np.random.default_rng(blk.seed)+ film = 1 + 0.07 * (noise2d(H, W, 260, 3, int(r.integers(1 << 30))) - 0.5) * 2+ yy = np.arange(H, dtype=np.float32)[:, None]+ for _ in range(4): # brayer stop-lines across the block+ y0 = r.uniform(self.box[1], self.box[3]); wd = r.uniform(2, 6)+ band = np.exp(-((yy - y0) / wd) ** 2) * r.uniform(0.06, 0.12)+ fade = 0.5 + 0.5 * noise2d(1, W, 300, 2, int(r.integers(1 << 30)))[0][None, :]+ film = film - band * fade+ # baren: many small circular passes, summed at quarter resolution+ h4, w4 = H // 4, W // 4+ acc = np.zeros((h4, w4), np.float32)+ x0, y0, x1, y1 = [v / 4 for v in self.box]+ for _ in range(900):+ cx, cy, rad = r.uniform(x0, x1), r.uniform(y0, y1), r.uniform(5, 16)+ t = np.linspace(0, 2 * np.pi * r.uniform(0.6, 1.0), 40) + r.uniform(0, 6.3)+ xs = np.clip((cx + np.cos(t) * rad).astype(int), 0, w4 - 1); ys = np.clip((cy + np.sin(t) * rad).astype(int), 0, h4 - 1)+ np.add.at(acc, (ys, xs), 1.0)+ acc = blur(acc, 1.6); acc = acc / (acc.mean() + 1e-6)+ acc = np.asarray(Image.fromarray(acc).resize((W, H), Image.BILINEAR))+ patch = noise2d(H, W, 380, 2, int(r.integers(1 << 30)))+ press = 1 + 0.07 * np.clip(acc - 1, -1.5, 1.5) - 0.26 * smoothstep(0.55, 0.92, patch)+ blk.film, blk.press = film.astype(np.float32), press.astype(np.float32)++ def _coverage(self, blk):+ self._print_fields(blk)+ m = np.asarray(Image.fromarray(blk.a).resize((self.W, self.H), Image.BOX), np.float32) / 255+ m = smoothstep(0.22, 0.78, _soft(m) + self.crumble * 0.09)+ if blk.offset != (0, 0): m = shift(m, *blk.offset)+ contact = blk.film * blk.press+ if blk.offset != (0, 0): contact = shift(contact, *blk.offset) + (contact == 0)+ t = smoothstep(0.45, 0.72, contact * 0.70 + self.grain * 0.36)+ edge = np.clip(m - blur(m, 1.6), 0, 1) # ink squeezed to the edges+ cov = m * np.maximum(t, smoothstep(0.02, 0.3, edge))+ if blk is self.key:+ cov = np.maximum(cov, self.chatter * (1 - m) * t * 0.8)+ else: # a light ink shows every unevenness+ mot = getattr(blk, 'mottle', 0.0)+ cov = cov * (1 - mot + mot * smoothstep(0.75, 1.15, contact * 0.6 + self.grain * 0.5))+ return np.clip(cov, 0, 1), m++ def pull(self, blocks=None):+ """print the blocks (default: all) onto the paper and return a PIL image"""+ img = self.paper.copy()+ blocks = self.blocks if blocks is None else blocks+ mk = None+ for blk in blocks:+ if blk is not self.key and not blk.a.any(): continue+ cov, m = self._coverage(blk)+ ink = blk.colour[None, None, :]+ img *= 1 - cov[..., None] * (1 - ink)+ if blk is self.key: mk = m+ # emboss: paper pressed onto the inked surface; carved areas and the margin stand proud+ h = (1 - (mk if mk is not None else 0)) * 1.0 + self.relief+ if mk is not None or self.relief.any():+ h = blur(np.asarray(h, np.float32) * np.ones((self.H, self.W), np.float32), 1.3)+ gy, gx = np.gradient(h)+ sh = np.clip(-(gx * -0.6 + gy * -0.7) * 0.3, -0.035, 0.035)+ img *= (1 + sh)[..., None]+ if self.pencil.any():+ a = self.pencil[..., None]+ img = img * (1 - a) + np.array([0.33, 0.32, 0.31], np.float32) * a+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8))++ def sign(self, edition='7/30', title='Untitled', name='', y=None, size=30, gap=8):+ """pencil in the margin under the print: edition left, title centred, signature right"""+ x0, _, x1, y1 = self.box+ y = y or y1 + 48+ hand = _pencil_font(size)+ script = _script_font(int(size * 1.25))+ m = text_mask(self.H, self.W, edition, hand, (x0 + gap, y), 'ls')+ m = np.maximum(m, text_mask(self.H, self.W, title, hand, ((x0 + x1) / 2, y), 'ms'))+ if name: m = np.maximum(m, text_mask(self.H, self.W, name, script, (x1 - gap, y + 2), 'rs'))+ g = 0.42 + 0.58 * self.grain+ self.pencil = np.maximum(self.pencil, m * g * 0.78)++ def chop(self, x, y, size=34, seed=None):+ """a blind chop: the printer's seal pressed into the margin without ink"""+ r = np.random.default_rng(seed if seed is not None else self._seed())+ sq = self.rect(x - size / 2, y - size / 2, x + size / 2, y + size / 2)+ inner = np.zeros_like(sq)+ for _ in range(5): # a few glyph-ish bars+ if r.random() < 0.5:+ yy = y + r.uniform(-0.3, 0.3) * size; a = r.uniform(-0.32, -0.05) * size; b = r.uniform(0.05, 0.32) * size+ inner = np.maximum(inner, self.rect(x + a, yy - 1.6, x + b, yy + 1.6))+ else:+ xx = x + r.uniform(-0.3, 0.3) * size; a = r.uniform(-0.32, -0.05) * size; b = r.uniform(0.05, 0.32) * size+ inner = np.maximum(inner, self.rect(xx - 1.6, y + a, xx + 1.6, y + b))+ border = sq - self.rect(x - size / 2 + 3, y - size / 2 + 3, x + size / 2 - 3, y + size / 2 - 3)+ self.relief = np.maximum(self.relief, np.clip(border + inner, 0, 1) * 0.9)++ # ------------------------------------------------------------ output+ def stage(self, name, blocks=None):+ """snapshot for the draw-on animation (blocks=[] -> blank paper)"""+ self.stages.append((name, self.pull(blocks)))++ def save(self, path, stages_dir=None, quality=88):+ img = self.pull()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return img+++def _blob(cx, cy, r, rng, n=18):+ n = int(n)+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)+ rr = r * (1 + 0.18 * (rng.random(n) - 0.5))+ return [(cx + np.cos(a) * q, cy + np.sin(a) * q) for a, q in zip(t, rr)]+++def _pencil_font(size):+ """a light handwriting face for pencil (Noteworthy on macOS), else core's 'hand' style"""+ from PIL import ImageFont+ for p, i in (('/System/Library/Fonts/Noteworthy.ttc', 0), ('/System/Library/Fonts/Supplemental/Bradley Hand Bold.ttf', 0)):+ if os.path.exists(p):+ try: return ImageFont.truetype(p, size, index=i)+ except OSError: pass+ return load_font('hand', size)+++def _script_font(size):+ return load_font('script', size)diff --git a/lib/macpaint.py b/lib/macpaint.pynew file mode 100644index 0000000..b75ae53--- /dev/null+++ b/lib/macpaint.py@@ -0,0 +1,957 @@+"""macpaint — a 1984-style 1-bit paint program: the picture and the program it is being painted in (numpy + Pillow).++The look is a screen, not a print: a 640 x 360 framebuffer with exactly two values, ink and paper, blown up x3 with+no smoothing, so every pixel is a hard square. Nothing is grey; tone only ever comes from *8 x 8 patterns*.++Model:+ framebuffer `doc` is the document bitmap (1 = black). Everything you draw goes into it with the program's own+ tools and their rules, and the interface is drawn around it at render time, so the same picture can be+ snapshotted with a different tool, pattern, cursor or menu showing (draw-on stages for free).+ patterns each pattern is 8 bytes (8 x 8 bits) and is anchored to the document origin, not to the shape: two+ shapes filled with the same pattern line up seamlessly, and the pattern does not follow a curve or a+ perspective. Shading = picking a lighter or darker pattern for a region; gradients = bands of+ patterns (`bands`), never dithering noise. 38 of them live in the palette along the bottom.+ shapes every tool is a rasteriser with the era's habits: lines are Bresenham with a square pen of 1-4 px+ (so diagonals are staircases and curves have jaggies), rectangles / rounded rectangles / ovals /+ freeforms are a pattern fill plus a border of the current line width drawn *inside* the outline,+ polygons and freeforms go through a non-antialiased scan fill.+ bucket flood fill of the 4-connected run of same-coloured pixels under the cursor; a one-pixel gap in an+ outline leaks, and a fill clicked on a patterned area only fills one speck. Outlines must be closed.+ brush a brush shape (round, square, slash, back-slash, bar, dot) stamped along the path, painting the+ current pattern opaquely; `spray` drops random pixels in a disc along the path, OR-ed in, so it can+ build shading and haze over anything.+ type the text tool stamps bitmap glyphs: a built-in bold system face (9-px capitals, 2-px stems) and any+ TrueType face rendered with antialiasing *off*; styles are bitmap operations on the glyph mask:+ bold (smear right by 1), italic (shear in steps), underline, outline (dilate minus self) and shadow+ (outline plus a second dilation pushed down-right).+ editing `copy(rect, to, flip, mask)` is select + option-drag (Flip Horizontal with flip=True; `mask` makes it a+ lasso selection, so a shape travels without its patterned background); `invert` is XOR (white+ whiskers on a black cat, black where they leave it); `erase` is the eraser; `dotted` a dotted trail.+ selection marquee and lasso are overlays, not ink: marching ants, i.e. the outline pixels coloured by+ ((x + y) // 4) % 2. The lasso shrink-wraps around the black pixels it encloses, as the real one did+ (on a patterned background it wraps the pattern too: pass the object's own mask, or use the marquee).+ interface menu bar with a small app glyph and invented menu names, rounded black screen corners, tool palette+ (2 x 10 tools, the active one inverted), line-width box with a check mark, pattern palette with the+ current-fill box, one document window: striped title bar with close box, centred title, scroll bars+ with a 50 % grey track, arrows, thumbs and size box, 1-px drop shadow. Pull-down menus have a 1-px+ shadow and inverted highlight; a zoom window shows a patch of the document at x`fat` with white gaps+ between the fat bits; cursors (arrow, cross, I-beam, bucket, spray, brush, pencil) have a white halo.++ from macpaint import MacPaint+ m = MacPaint(seed=1, title='untitled')+ m.rect(20, 20, 200, 120, fill='bricks', line=2)+ m.oval(300, 80, 60, 40, fill='gray')+ m.bucket(100, 200, 'scales')+ m.text('hello', 40, 150, size=24, font='serif', style=('shadow',))+ m.use('spray', pattern='black'); m.cursor('spray', 320, 160)+ m.stage('first')+ m.save('out.jpg')+Coordinates: document pixels (0, 0 = top-left of the window's content area), y down; the screen is 640 x 360 and+the output is `scale` times that (default 3 -> 1920 x 1080). Only numpy + Pillow.+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import spline, load_font+++# ---------------------------------------------------------------- patterns (8 x 8, 1 = ink)+def _rows(*rows):+ w = max(len(r) for r in rows)+ return np.array([[1 if c == '#' else 0 for c in r.ljust(w, '.')] for r in rows], np.uint8)+++def _fn(f):+ y, x = np.mgrid[0:8, 0:8]+ return f(x, y).astype(np.uint8)+++PATTERNS = {+ # flat tones+ 'white': np.zeros((8, 8), np.uint8),+ 'black': np.ones((8, 8), np.uint8),+ 'gray': _fn(lambda x, y: (x + y) % 2 == 0), # 50 %+ 'light': _rows('#...#...', '..#...#.', '#...#...', '..#...#.', '#...#...', '..#...#.', '#...#...', '..#...#.'), # 25 %+ 'lighter': _rows('#...#...', '........', '..#...#.', '........', '#...#...', '........', '..#...#.', '........'), # 12.5 %+ 'mist': _rows('#.......', '........', '....#...', '........', '#.......', '........', '....#...', '........'), # 6 %+ 'faint': _rows('#.......', '........', '........', '........', '....#...', '........', '........', '........'), # 3 %+ # dots and lines+ 'dots': _rows('........', '.#...#..', '........', '...#...#', '........', '.#...#..', '........', '...#...#'),+ 'polka': _rows('.##.....', '####....', '.##.....', '........', '.....##.', '....####', '.....##.', '........'),+ 'hlines': _fn(lambda x, y: y % 4 == 0),+ 'vlines': _fn(lambda x, y: x % 4 == 0),+ 'diag': _fn(lambda x, y: (x + y) % 4 == 3),+ 'rdiag': _fn(lambda x, y: (x - y) % 4 == 0),+ 'wide_diag': _fn(lambda x, y: (x + y) % 8 == 7),+ 'thick_diag': _fn(lambda x, y: (x + y) % 4 < 2),+ 'grid': _fn(lambda x, y: (x == 0) | (y == 0)),+ 'fine_grid': _fn(lambda x, y: (x % 4 == 0) | (y % 4 == 0)),+ 'xhatch': _fn(lambda x, y: ((x + y) % 8 == 0) | ((x - y) % 8 == 0)),+ 'hstripes': _fn(lambda x, y: y % 4 < 2),+ 'vstripes': _fn(lambda x, y: x % 4 < 2),+ # textures+ 'bricks': _rows('########', '#.......', '#.......', '#.......', '########', '....#...', '....#...', '....#...'),+ 'scales': _rows('...#....', '...#....', '..#.#...', '##...###', '.......#', '.......#', '#.....#.', '.#####..'),+ 'weave': _rows('####.#.#', '.....#.#', '####.#.#', '.....#.#', '.#.#####', '.#.#....', '.#.#####', '.#.#....'),+ 'basket': _fn(lambda x, y: np.where((x // 4 + y // 4) % 2 == 0, y % 2 == 0, x % 2 == 0)),+ 'diamonds': _fn(lambda x, y: (np.abs(x - 3.5) + np.abs(y - 3.5)).astype(int) == 3),+ 'shingles': _rows('########', '#.......', '#.......', '.#.....#', '..#####.', '....#...', '....#...', '...#.#..'),+ 'waves': _rows('........', '..##....', '.#..#...', '#....###', '........', '..##....', '.#..#...', '#....###'),+ 'zigzag': _fn(lambda x, y: (y - np.abs(x - 4)) % 4 == 0),+ 'stars': _rows('..#.....', '.###....', '..#.....', '........', '........', '......#.', '.....###', '......#.'),+ 'sprigs': _rows('........', '..#.....', '.#.#....', '........', '........', '......#.', '.....#.#', '........'),+ 'checker': _fn(lambda x, y: (x // 4 + y // 4) % 2 == 0),+ 'gingham': _fn(lambda x, y: ((x // 4 % 2 == 0) & (y // 4 % 2 == 0))+ | (((x // 4 % 2 == 0) ^ (y // 4 % 2 == 0)) & ((x + y) % 2 == 0))),+ 'wood': _rows('######..', '........', '..#####.', '........', '#....###', '........', '.######.', '........'),+ 'grass': _rows('........', '#.......', '#..#....', '.#.#....', '........', '....#...', '....#..#', '.....#.#'),+ 'pebbles': _rows('.##.....', '#..#..#.', '#..#.#.#', '.##...#.', '....##..', '.#.#..#.', '#.##..#.', '.#..##..'),+ 'circles': _rows('..###...', '.#...#..', '#.....#.', '#.....#.', '#.....#.', '.#...#..', '..###...', '........'),+ 'plus': _rows('...#....', '...#....', '.#####..', '...#....', '...#....', '........', '........', '........'),+ 'confetti': _rows('#.......', '.....#..', '..#.....', '.......#', '...#....', '#.......', '......#.', '.#......'),+ 'denim': _fn(lambda x, y: (x + 2 * y) % 4 < 2),+}+PATTERNS['dark'] = 1 - PATTERNS['light'] # 75 %+PATTERNS['darker'] = 1 - PATTERNS['lighter'] # 87.5 %++PALETTE = ['white', 'black', 'gray', 'light', 'dark', 'lighter', 'mist', 'faint', 'dots', 'polka', 'hlines', 'vlines',+ 'diag', 'rdiag', 'wide_diag', 'thick_diag', 'grid', 'fine_grid', 'xhatch',+ 'bricks', 'scales', 'weave', 'diamonds', 'shingles', 'waves', 'zigzag', 'stars', 'sprigs', 'checker',+ 'gingham', 'hstripes', 'vstripes', 'wood', 'grass', 'pebbles', 'circles', 'basket', 'darker']++# ---------------------------------------------------------------- the system face: bold, 9-px capitals, 2-px stems+# each glyph: (top row, rows); cap height 9 rows (0..8), baseline under row 8, descenders on rows 9..10+_G = {}+++def _g(chars, top, *rows):+ _G[chars] = (top, rows)+++_g('A', 0, '.####.', '##..##', '##..##', '##..##', '######', '##..##', '##..##', '##..##', '##..##')+_g('B', 0, '#####.', '##..##', '##..##', '##..##', '#####.', '##..##', '##..##', '##..##', '#####.')+_g('C', 0, '.####.', '##..##', '##....', '##....', '##....', '##....', '##....', '##..##', '.####.')+_g('D', 0, '#####.', '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '#####.')+_g('E', 0, '######', '##....', '##....', '##....', '#####.', '##....', '##....', '##....', '######')+_g('F', 0, '######', '##....', '##....', '##....', '#####.', '##....', '##....', '##....', '##....')+_g('G', 0, '.####.', '##..##', '##....', '##....', '##.###', '##..##', '##..##', '##..##', '.#####')+_g('H', 0, '##..##', '##..##', '##..##', '##..##', '######', '##..##', '##..##', '##..##', '##..##')+_g('I', 0, '##', '##', '##', '##', '##', '##', '##', '##', '##')+_g('J', 0, '....##', '....##', '....##', '....##', '....##', '....##', '##..##', '##..##', '.####.')+_g('K', 0, '##...##', '##..##.', '##.##..', '####...', '###....', '####...', '##.##..', '##..##.', '##...##')+_g('L', 0, '##....', '##....', '##....', '##....', '##....', '##....', '##....', '##....', '######')+_g('M', 0, '##.....##', '###...###', '####.####', '##.###.##', '##..#..##', '##.....##', '##.....##', '##.....##', '##.....##')+_g('N', 0, '##...##', '###..##', '####.##', '##.####', '##..###', '##...##', '##...##', '##...##', '##...##')+_g('O', 0, '.####.', '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '.####.')+_g('P', 0, '#####.', '##..##', '##..##', '##..##', '#####.', '##....', '##....', '##....', '##....')+_g('Q', 0, '.####.', '##..##', '##..##', '##..##', '##..##', '##..##', '##.###', '##..##', '.##.##')+_g('R', 0, '#####.', '##..##', '##..##', '##..##', '#####.', '##.##.', '##..##', '##..##', '##..##')+_g('S', 0, '.####.', '##..##', '##....', '.##...', '..##..', '...##.', '....##', '##..##', '.####.')+_g('T', 0, '######', '..##..', '..##..', '..##..', '..##..', '..##..', '..##..', '..##..', '..##..')+_g('U', 0, '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '.####.')+_g('V', 0, '##..##', '##..##', '##..##', '##..##', '##..##', '##..##', '.####.', '.####.', '..##..')+_g('W', 0, '##.....##', '##.....##', '##.....##', '##..#..##', '##.###.##', '####.####', '###...###', '##.....##', '#.......#')+_g('X', 0, '##..##', '##..##', '.####.', '..##..', '..##..', '.####.', '##..##', '##..##', '##..##')+_g('Y', 0, '##..##', '##..##', '##..##', '.####.', '..##..', '..##..', '..##..', '..##..', '..##..')+_g('Z', 0, '######', '....##', '....##', '...##.', '..##..', '.##...', '##....', '##....', '######')+_g('a', 3, '.####.', '....##', '.#####', '##..##', '##..##', '.#####')+_g('b', 0, '##....', '##....', '##....', '#####.', '##..##', '##..##', '##..##', '##..##', '#####.')+_g('c', 3, '.####.', '##..##', '##....', '##....', '##..##', '.####.')+_g('d', 0, '....##', '....##', '....##', '.#####', '##..##', '##..##', '##..##', '##..##', '.#####')+_g('e', 3, '.####.', '##..##', '######', '##....', '##..##', '.####.')+_g('f', 0, '..###', '.##..', '.##..', '#####', '.##..', '.##..', '.##..', '.##..', '.##..')+_g('g', 3, '.#####', '##..##', '##..##', '##..##', '##..##', '.#####', '....##', '.####.')+_g('h', 0, '##....', '##....', '##....', '#####.', '##..##', '##..##', '##..##', '##..##', '##..##')+_g('i', 1, '##', '..', '##', '##', '##', '##', '##', '##')+_g('j', 1, '..##', '....', '..##', '..##', '..##', '..##', '..##', '..##', '..##', '###.')+_g('k', 0, '##....', '##....', '##....', '##..##', '##.##.', '####..', '####..', '##.##.', '##..##')+_g('l', 0, '##', '##', '##', '##', '##', '##', '##', '##', '##')+_g('m', 3, '#########.', '##..##..##', '##..##..##', '##..##..##', '##..##..##', '##..##..##')+_g('n', 3, '#####.', '##..##', '##..##', '##..##', '##..##', '##..##')+_g('o', 3, '.####.', '##..##', '##..##', '##..##', '##..##', '.####.')+_g('p', 3, '#####.', '##..##', '##..##', '##..##', '##..##', '#####.', '##....', '##....')+_g('q', 3, '.#####', '##..##', '##..##', '##..##', '##..##', '.#####', '....##', '....##')+_g('r', 3, '##.###', '####..', '###...', '##....', '##....', '##....')+_g('s', 3, '.#####', '##....', '.####.', '....##', '....##', '#####.')+_g('t', 1, '.##..', '.##..', '#####', '.##..', '.##..', '.##..', '.##..', '..###')+_g('u', 3, '##..##', '##..##', '##..##', '##..##', '##..##', '.#####')+_g('v', 3, '##..##', '##..##', '##..##', '.####.', '.####.', '..##..')+_g('w', 3, '##......##', '##..##..##', '##..##..##', '##..##..##', '##..##..##', '.###..###.')+_g('x', 3, '##..##', '.####.', '..##..', '..##..', '.####.', '##..##')+_g('y', 3, '##..##', '##..##', '##..##', '##..##', '##..##', '.#####', '....##', '.####.')+_g('z', 3, '######', '...##.', '..##..', '.##...', '##....', '######')+_g('0', 0, '.####.', '##..##', '##..##', '##.###', '######', '###.##', '##..##', '##..##', '.####.')+_g('1', 0, '.##.', '###.', '.##.', '.##.', '.##.', '.##.', '.##.', '.##.', '####')+_g('2', 0, '.####.', '##..##', '....##', '....##', '...##.', '..##..', '.##...', '##....', '######')+_g('3', 0, '.####.', '##..##', '....##', '....##', '..###.', '....##', '....##', '##..##', '.####.')+_g('4', 0, '...###', '..####', '.##.##', '##..##', '##..##', '######', '....##', '....##', '....##')+_g('5', 0, '######', '##....', '##....', '#####.', '....##', '....##', '....##', '##..##', '.####.')+_g('6', 0, '.####.', '##....', '##....', '#####.', '##..##', '##..##', '##..##', '##..##', '.####.')+_g('7', 0, '######', '....##', '....##', '...##.', '..##..', '..##..', '.##...', '.##...', '.##...')+_g('8', 0, '.####.', '##..##', '##..##', '##..##', '.####.', '##..##', '##..##', '##..##', '.####.')+_g('9', 0, '.####.', '##..##', '##..##', '##..##', '.#####', '....##', '....##', '....##', '.####.')+_g(' ', 0, '....')+_g('.', 7, '##', '##')+_g(',', 7, '##', '##', '.#', '#.')+_g(':', 3, '##', '##', '..', '..', '##', '##')+_g('-', 4, '#####')+_g("'", 0, '##', '##', '#.')+_g('!', 0, '##', '##', '##', '##', '##', '##', '..', '##', '##')+_g('?', 0, '.####.', '##..##', '....##', '...##.', '..##..', '..##..', '......', '..##..', '..##..')+_g('/', 0, '....##', '....##', '...##.', '...##.', '..##..', '.##...', '.##...', '##....', '##....')+_g('(', 0, '..##', '.##.', '##..', '##..', '##..', '##..', '##..', '.##.', '..##')+_g(')', 0, '##..', '.##.', '..##', '..##', '..##', '..##', '..##', '.##.', '##..')+_g('%', 0, '.#...##', '#.#.##.', '.#..##.', '...##..', '..##...', '.##..#.', '.##.#.#', '##...#.', '.......')+_g('>', 1, '##....', '.##...', '..##..', '...##.', '..##..', '.##...', '##....')+_g('…', 7, '##.##.##', '##.##.##') # ellipsis+_g('✓', 2, '......#', '.....##', '#...##.', '##.##..', '.###...', '..#....') # check mark+_g('→', 2, '....#...', '....##..', '#######.', '########', '#######.', '....##..', '....#...') # arrow+_g('×', 3, '##..##', '.####.', '..##..', '.####.', '##..##') # times+++def system_text_mask(s, style=()):+ """bitmap of string `s` in the system face (rows 0..10, baseline under row 8), padded by 3 px for the styles"""+ cols = []+ for ch in s:+ top, rows = _G.get(ch, _G['?'])+ w = len(rows[0])+ g = np.zeros((11, w), np.uint8)+ g[top:top + len(rows)] = _rows(*rows)+ cols.append(g)+ cols.append(np.zeros((11, 1), np.uint8))+ m = np.concatenate(cols[:-1] or [np.zeros((11, 1), np.uint8)], axis=1)+ return _style(m, style)+++def _dilate(m, r=1, square=True):+ out = m.copy()+ for dy in range(-r, r + 1):+ for dx in range(-r, r + 1):+ if not square and abs(dx) + abs(dy) > r: continue+ out |= _shift(m, dx, dy)+ return out+++def _erode(m, r=1, square=False):+ return 1 - _dilate(1 - m, r, square)+++def _shift(m, dx, dy):+ H, W = m.shape+ out = np.zeros_like(m)+ 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)] = m[max(-dy, 0):H + min(-dy, 0), max(-dx, 0):W + min(-dx, 0)]+ return out+++def _style(m, style):+ """bitmap type styles, applied the way the old toolbox did it: on the glyph mask"""+ style = tuple(style or ())+ p = 3+ m = np.pad(m, p)+ if 'bold' in style:+ m = m | _shift(m, 1, 0)+ if 'italic' in style:+ H = m.shape[0]+ out = np.zeros_like(m)+ for y in range(H):+ out[y] = np.roll(m[y], (H - 1 - y) // 4 - 1)+ m = out+ if 'outline' in style or 'shadow' in style:+ d = _dilate(m, 1, square=True)+ ring = d & (1 - m)+ if 'shadow' in style:+ sh = _shift(d, 1, 1) | _shift(d, 2, 2)+ ring = ring | (sh & (1 - d))+ m = ring+ if 'underline' in style:+ ys = np.nonzero(m.any(1))[0]+ if len(ys):+ m[min(ys[-1] + 1, m.shape[0] - 1), p:-p] = 1+ return m+++# ---------------------------------------------------------------- tool icons (16 x 16) and cursors+ICONS = {+ 'marquee': ('................', '................', '.##.##.##.##.##.', '................', '.#............#.',+ '................', '.#............#.', '................', '.#............#.', '................',+ '.#............#.', '................', '.##.##.##.##.##.', '................', '................',+ '................'),+ 'lasso': ('................', '.....######.....', '...##......##...', '..#..........#..', '.#............#.',+ '.#............#.', '..#..........#..', '...##......##...', '.....###.###....', '........#.......',+ '.......#.#......', '.......#........', '........#.......', '.........##.....', '...........#....',+ '................'),+ 'zoom': ('................', '....####........', '..##....##......', '.#........#.....', '.#...##...#.....',+ '#...#.....#.....', '#..#......#.....', '#.........#.....', '.#........#.....', '.#.......#......',+ '..##....###.....', '....####.###....', '..........###...', '...........###..', '............##..',+ '................'),+ 'text': ('................', '.......##.......', '......####......', '......####......', '.....##.###.....',+ '.....##.###.....', '....##...###....', '....##...###....', '...#########....', '...##.....###...',+ '..##......###...', '..##.......###..', '.####.....#####.', '................', '................',+ '................'),+ 'bucket': ('................', '.....#..........', '....#.#.........', '....#..#........', '...##...#.......',+ '..#.#....#......', '.#..#.....#.....', '#...##.....#....', '#..#.#......#...', '#.#..#.....#.#..',+ '.#....#...#..#..', '..#....#.#...#..', '...#....#....##.', '....#..#.....##.', '.....##.......#.',+ '..............#.'),+ 'spray': ('.....##.........', '....#..#..#.#...', '...######.......', '...#....#.#.#.#.', '...#....#.......',+ '...#....#..#.#..', '...#....#.......', '...#....#.#.....', '...#....#.......', '...#....#.......',+ '...#....#.......', '...#....#.......', '...#....#.......', '...#....#.......', '...######.......',+ '................'),+ 'brush': ('............##..', '...........#.##.', '..........#..##.', '.........#..#...', '........#..#....',+ '.......#..#.....', '......#..#......', '.....##.#.......', '....####........', '...#####........',+ '...####.........', '..####..........', '..###...........', '.##.............', '.#..............',+ '................'),+ 'pencil': ('............##..', '...........#..#.', '..........#..##.', '.........#..#.#.', '........#..#.#..',+ '.......#..#.#...', '......#..#.#....', '.....#..#.#.....', '....#..#.#......', '...#..#.#.......',+ '...##.#.#.......', '..#.###.........', '..##.#..........', '.###............', '.##.............',+ '................'),+ 'line': ('................', '.............#..', '............#...', '...........#....', '..........#.....',+ '.........#......', '........#.......', '.......#........', '......#.........', '.....#..........',+ '....#...........', '...#............', '..#.............', '................', '................',+ '................'),+ 'eraser': ('................', '................', '.......########.', '......#......##.', '.....#......#.#.',+ '....#......#..#.', '...#......#...#.', '..#......#...#..', '.########...#...', '.#......#..#....',+ '.#......#.#.....', '.#......##......', '.########.......', '................', '................',+ '................'),+}+CURSORS = { # (rows, hotspot) ; '#' ink, 'o' white halo+ 'arrow': (('#..........', '##.........', '#o#........', '#oo#.......', '#ooo#......', '#oooo#.....', '#ooooo#....',+ '#oooooo#...', '#ooooooo#..', '#oooooooo#.', '#ooooo#####', '#oo#oo#....', '#o#.#oo#...', '##..#oo#...',+ '#....#oo#..', '.....#oo#..', '......##...'), (0, 0)),+ 'cross': (('.....ooo.....', '.....o#o.....', '.....o#o.....', '.....o#o.....', '.....o#o.....', 'oooooo#oooooo',+ '#############', 'oooooo#oooooo', '.....o#o.....', '.....o#o.....', '.....o#o.....', '.....o#o.....',+ '.....ooo.....'), (6, 6)),+ 'ibeam': (('o##.##o', '.oo#oo.', '..o#o..', '..o#o..', '..o#o..', '..o#o..', 'oo###oo', '..o#o..', '..o#o..',+ '..o#o..', '..o#o..', '.oo#oo.', 'o##.##o'), (3, 7)),+ 'bucket': (('.....#..........', '....#o#.........', '....#oo#........', '...##ooo#.......', '..#o#oooo#......',+ '.#oo#ooooo#.....', '#ooo##ooooo#....', '#oo#o#oooooo#...', '#o#oo#ooooo#o#..', '.#oooo#ooo#oo#..',+ '..#oooo#o#ooo#..', '...#oooo#oooo##.', '....#oo#.....##.', '.....##.......#.', '..............#.',+ '..............#.'), (14, 15)),+ 'spray': (('.....##.........', '....#oo#..#.#...', '...######.......', '...#oooo#.#.#.#.', '...#oooo#.......',+ '...#oooo#..#.#..', '...#oooo#.......', '...#oooo#.#.....', '...#oooo#.......', '...#oooo#.......',+ '...######.......'), (12, 3)),+ 'brush': (('..ooo..', '.o###o.', 'o#####o', 'o#####o', 'o#####o', '.o###o.', '..ooo..'), (3, 3)),+ 'pencil': (('............##..', '...........#oo#.', '..........#oo##.', '.........#oo#o#.', '........#oo#o#..',+ '.......#oo#o#...', '......#oo#o#....', '.....#oo#o#.....', '....#oo#o#......', '...#oo#o#.......',+ '...##o#o#.......', '..#o###........', '..##.#..........', '.##.............', '.#..............',+ '................'), (1, 14)),+}+++def _bitmap(rows):+ """'#' -> 1 ink, 'o' -> 2 white halo, '.' -> 0 transparent"""+ w = max(len(r) for r in rows)+ return np.array([[{'#': 1, 'o': 2}.get(c, 0) for c in r.ljust(w, '.')] for r in rows], np.uint8)+++# ---------------------------------------------------------------- the program+class MacPaint:+ TOOLS = ['marquee', 'lasso', 'zoom', 'text', 'bucket', 'spray', 'brush', 'pencil', 'line', 'eraser',+ 'rect', 'frect', 'rrect', 'frrect', 'oval', 'foval', 'free', 'ffree', 'poly', 'fpoly']++ def __init__(self, seed=0, title='untitled', menus=('Paper', 'Tools', 'Brushes', 'Patterns', 'Type', 'Zoom'),+ screen=(640, 360), scale=3, ink='#000000', paper='#ffffff', doc=None, scroll=(0.0, 0.0)):+ self.SW, self.SH = screen+ self.scale = scale+ self.rng = np.random.default_rng(seed)+ self.title, self.menus = title, list(menus)+ self.ink, self.paper = ink, paper+ # ---- layout (screen px)+ self.tools_box = (4, 25, 57, 226) # 2 x 10 cells of 26 x 20+ self.lines_box = (4, 234, 57, 300)+ self.pat_box = (4, 313, 57, 355) # current fill+ self.pats_box = (62, 313, 635, 355) # 2 x 19 swatches+ self.win = (62, 24, 633, 305) # outer frame incl. title bar and scroll bars+ x0, y0, x1, y1 = self.win+ self.view = (x0 + 1, y0 + 19, x1 - 16, y1 - 16) # content rect (x0, y0, x1, y1) exclusive ends+ vw, vh = self.view[2] - self.view[0], self.view[3] - self.view[1]+ self.VW, self.VH = vw, vh+ dw, dh = doc or (vw, vh)+ self.W, self.H = dw, dh+ self.doc = np.zeros((dh, dw), np.uint8)+ self.scroll = scroll+ self.YY, self.XX = np.mgrid[0:dh, 0:dw]+ # ---- interface state+ self.state = dict(tool='pencil', pattern='black', line=1, cursor=None, select=None, menu=None, zoom=None,+ title=title)+ self.stages = []+ self._tiles = {}++ # ------------------------------------------------------------ patterns+ def tile(self, pat):+ """the pattern as a full-document bitmap, anchored to the document origin (as the real patterns were)"""+ key = pat if isinstance(pat, str) else id(pat)+ if key not in self._tiles:+ p = PATTERNS[pat] if isinstance(pat, str) else np.asarray(pat, np.uint8)+ self._tiles[key] = np.tile(p, (self.H // 8 + 1, self.W // 8 + 1))[:self.H, :self.W]+ return self._tiles[key]++ def paint(self, mask, pat='black', mode='opaque'):+ """put pattern `pat` through `mask` (bool/0-1 array). mode: opaque (replace), or (ink only), erase, invert"""+ m = np.asarray(mask).astype(bool)+ if mode == 'opaque': self.doc[m] = self.tile(pat)[m]+ elif mode == 'or': self.doc[m] |= self.tile(pat)[m]+ elif mode == 'erase': self.doc[m] = 0+ elif mode == 'invert': self.doc[m] ^= 1+ return m++ # ------------------------------------------------------------ masks (no antialiasing anywhere)+ def _canvas(self):+ return Image.new('L', (self.W, self.H), 0)++ def mask_poly(self, pts, smooth=False):+ P = spline(pts, 10) if smooth else np.asarray(pts, np.float32)+ im = self._canvas()+ ImageDraw.Draw(im).polygon([(float(x), float(y)) for x, y in P], fill=1)+ return np.asarray(im, np.uint8)++ def mask_oval(self, cx, cy, rx, ry):+ im = self._canvas()+ ImageDraw.Draw(im).ellipse([cx - rx, cy - ry, cx + rx - 1, cy + ry - 1], fill=1)+ return np.asarray(im, np.uint8)++ def mask_rect(self, x0, y0, x1, y1, radius=0):+ im = self._canvas()+ if radius: ImageDraw.Draw(im).rounded_rectangle([x0, y0, x1 - 1, y1 - 1], radius=radius, fill=1)+ else: ImageDraw.Draw(im).rectangle([x0, y0, x1 - 1, y1 - 1], fill=1)+ return np.asarray(im, np.uint8)++ def mask_path(self, pts, width=1, smooth=False, closed=False):+ """1-px Bresenham path (PIL's line rasteriser draws no antialiasing) widened by a square pen"""+ P = spline(pts, 10) if smooth else np.asarray(pts, np.float32)+ if closed: P = np.vstack([P, P[:1]])+ im = self._canvas()+ d = ImageDraw.Draw(im)+ Q = [(int(round(x)), int(round(y))) for x, y in P]+ if len(Q) == 1: d.point(Q, fill=1)+ else: d.line(Q, fill=1, width=1)+ m = np.asarray(im, np.uint8)+ if width > 1:+ m = self.pen(m, width)+ return m++ def pen(self, m, w):+ """thicken a mask with a w x w square pen (how the era widened lines; also handy to pad a selection)"""+ out = m.copy()+ a = -(w // 2)+ for dy in range(a, a + w):+ for dx in range(a, a + w):+ out |= _shift(m, dx, dy)+ return out++ @staticmethod+ def border(mask, width=1):+ """the frame of a shape, drawn inside its outline, `width` px thick"""+ m = np.asarray(mask, np.uint8)+ return m & (1 - _erode(m, width, square=True))++ # ------------------------------------------------------------ shape tools+ def _shape(self, m, fill, line, line_pat='black'):+ if fill is not None: self.paint(m, fill)+ if line: self.paint(self.border(m, line), line_pat)+ return m++ def rect(self, x0, y0, x1, y1, fill=None, line=1, radius=0, line_pat='black'):+ """rectangle / rounded rectangle tool: pattern fill + border of `line` px inside the outline"""+ return self._shape(self.mask_rect(x0, y0, x1, y1, radius), fill, line, line_pat)++ def oval(self, cx, cy, rx, ry, fill=None, line=1, line_pat='black'):+ return self._shape(self.mask_oval(cx, cy, rx, ry), fill, line, line_pat)++ def shape(self, pts, fill=None, line=1, smooth=True, line_pat='black'):+ """freeform (smooth=True, a Catmull-Rom through the points) or polygon tool"""+ return self._shape(self.mask_poly(pts, smooth), fill, line, line_pat)++ def line(self, p0, p1, width=1, pat='black'):+ return self.paint(self.mask_path([p0, p1], width), pat)++ def pencil(self, pts, smooth=False, pat='black', mode='opaque'):+ """1-px freehand line through the points"""+ return self.paint(self.mask_path(pts, 1, smooth), pat, mode)++ def brush(self, pts, size=4, shape='round', pat='black', smooth=True, mode='opaque'):+ """brush shape stamped along the path, painting the pattern. shape: round, square, slash, backslash,+ bar (horizontal), vbar, dot (scatter of single pixels)"""+ path = self.mask_path(pts, 1, smooth)+ k = self._brush_kernel(size, shape)+ out = np.zeros_like(path)+ r = k.shape[0] // 2+ for dy, dx in zip(*np.nonzero(k)):+ out |= _shift(path, int(dx) - r, int(dy) - r)+ return self.paint(out, pat, mode)++ @staticmethod+ def _brush_kernel(size, shape):+ n = max(1, int(size))+ y, x = np.mgrid[0:n, 0:n] - (n - 1) / 2+ if shape == 'round': k = x * x + y * y <= (n / 2) ** 2 + 0.3+ elif shape == 'square': k = np.ones((n, n), bool)+ elif shape == 'slash': k = np.abs(x + y) <= 0.6+ elif shape == 'backslash': k = np.abs(x - y) <= 0.6+ elif shape == 'bar': k = np.abs(y) <= 0.6+ elif shape == 'vbar': k = np.abs(x) <= 0.6+ elif shape == 'dot': k = ((x.astype(int) + y.astype(int)) % 2 == 0) & (x * x + y * y <= (n / 2) ** 2)+ else: raise ValueError(shape)+ return k.astype(np.uint8)++ def dotted(self, pts, gap=4, size=1, smooth=True, pat='black'):+ """a dotted trail (a motion path, a seam): single dots (size x size) every `gap` px along the path"""+ 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)+ s = np.concatenate([[0], np.cumsum(seg)])+ ss = np.arange(0, s[-1], gap)+ m = np.zeros((self.H, self.W), np.uint8)+ xs = np.round(np.interp(ss, s, P[:, 0])).astype(int); ys = np.round(np.interp(ss, s, P[:, 1])).astype(int)+ ok = (xs >= 0) & (xs < self.W - size) & (ys >= 0) & (ys < self.H - size)+ for dy in range(size):+ for dx in range(size):+ m[ys[ok] + dy, xs[ok] + dx] = 1+ return self.paint(m, pat)++ def bucket(self, x, y, pat='black'):+ """paint bucket: flood the 4-connected run of same-coloured pixels under (x, y) with the pattern"""+ im = Image.fromarray(self.doc * 1).copy() # (a fromarray image is read-only: floodfill would be a no-op)+ ImageDraw.floodfill(im, (int(x), int(y)), 7)+ m = np.asarray(im) == 7+ self.paint(m, pat)+ return m++ def spray(self, pts, radius=9, density=0.35, pat='black', clip=None, smooth=True, seed=None):+ """spray can along a path: random single pixels inside a disc, OR-ed onto the picture.+ density ~ fraction of the disc's pixels hit per diameter of travel"""+ rng = np.random.default_rng(seed) if seed is not None else self.rng+ P = spline(pts, 12) if (smooth and len(pts) > 2) else np.asarray(pts, np.float32)+ if len(P) > 1:+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)+ s = np.concatenate([[0], np.cumsum(seg)])+ n = max(2, int(s[-1] / 2) + 1)+ ss = np.linspace(0, s[-1], n)+ P = np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1)+ per = max(1, int(np.pi * radius * radius * density * 2 / (2 * radius)))+ m = np.zeros((self.H, self.W), np.uint8)+ for cx, cy in P:+ a = rng.random(per) * 2 * np.pi+ r = radius * np.sqrt(rng.random(per))+ xs = np.round(cx + r * np.cos(a)).astype(int); ys = np.round(cy + r * np.sin(a)).astype(int)+ ok = (xs >= 0) & (xs < self.W) & (ys >= 0) & (ys < self.H)+ m[ys[ok], xs[ok]] = 1+ if clip is not None: m &= np.asarray(clip, np.uint8)+ t = self.tile(pat)+ self.doc |= (m & t)+ return m++ def bands(self, mask, pats, y0, y1, edge='spray', seed=None):+ """a 'gradient' the 1984 way: horizontal bands of patterns from y0 to y1 inside mask; the band seams are+ broken up with a little spray so they do not read as ruled lines"""+ m = np.asarray(mask).astype(bool)+ n = len(pats)+ cuts = np.linspace(y0, y1, n + 1)+ for i, p in enumerate(pats):+ band = m & (self.YY >= (cuts[i] if i else -1)) & (self.YY < (cuts[i + 1] if i < n - 1 else 10 ** 6))+ self.paint(band, p)+ if edge == 'spray':+ rng = np.random.default_rng(seed) if seed is not None else self.rng+ for i in range(1, n):+ y = cuts[i]+ below = m & (self.YY >= y) & (self.YY < y + 5)+ above = m & (self.YY < y) & (self.YY >= y - 5)+ ta, tb = self.tile(pats[i - 1]), self.tile(pats[i])+ # interleave the two patterns ragged-edge across the seam+ r = rng.random(m.shape) < np.clip(1 - np.abs(self.YY - y) / 5.5, 0, 1) * 0.5+ self.doc[below & r] = ta[below & r]+ self.doc[above & r] = tb[above & r]+ return m++ def erase(self, mask_or_rect):+ m = self.mask_rect(*mask_or_rect) if isinstance(mask_or_rect, (tuple, list)) else mask_or_rect+ return self.paint(m, mode='erase')++ def invert(self, mask_or_rect):+ m = self.mask_rect(*mask_or_rect) if isinstance(mask_or_rect, (tuple, list)) else mask_or_rect+ return self.paint(m, mode='invert')++ def copy(self, rect, to, flip=False, mask=None, mode='opaque'):+ """select a rectangle and option-drag a copy of it to `to` (its new top-left); flip=True mirrors it+ left-right (the Flip Horizontal of the era). mask: only the pixels inside it travel, like a lasso selection,+ so a shape can be copied off a patterned background without dragging the background along"""+ x0, y0, x1, y1 = rect+ piece = self.doc[y0:y1, x0:x1].copy()+ keep = np.ones_like(piece) if mask is None else np.asarray(mask, np.uint8)[y0:y1, x0:x1].copy()+ if flip: piece, keep = piece[:, ::-1], keep[:, ::-1]+ tx, ty = to+ h, w = piece.shape+ tgt = self.doc[ty:ty + h, tx:tx + w]+ piece, keep = piece[:tgt.shape[0], :tgt.shape[1]], keep[:tgt.shape[0], :tgt.shape[1]].astype(bool)+ if mode == 'opaque': tgt[keep] = piece[keep]+ else: tgt[keep] |= piece[keep]++ # ------------------------------------------------------------ type+ def text_mask(self, s, x, y, size=12, font='system', style=(), anchor='l'):+ """glyph mask for text tool. font='system' is the built-in bold bitmap face (size ignored; style still+ applies); any other value is a core.load_font style (serif, sans_bold, rounded, ...) rendered without+ antialiasing at `size` px. (x, y): baseline-left for 'l', baseline-centre for 'm', baseline-right for 'r'."""+ if font == 'system':+ g = system_text_mask(s, style) # padded by 3 on every side+ base = 3 + 9 # row under the baseline in the padded mask+ else:+ f = load_font(font, size)+ asc, desc = f.getmetrics()+ w = int(f.getlength(s)) + 8+ im = Image.new('L', (w + 6, asc + desc + 6), 0)+ d = ImageDraw.Draw(im)+ d.fontmode = '1'+ d.text((3, 3 + asc), s, font=f, fill=255, anchor='ls')+ g = (np.asarray(im) > 127).astype(np.uint8)+ if style: g = _style(g, style)[3:-3, 3:-3] # the canvas already has a 3-px margin for the styles+ base = 3 + asc+ cols = np.nonzero(g.any(0))[0]+ if len(cols) == 0: return np.zeros((self.H, self.W), np.uint8)+ g = g[:, cols[0]:cols[-1] + 1]+ h, w = g.shape+ ox = int(x) - {'l': 0, 'm': w // 2, 'r': w}[anchor]+ oy = int(y) - base+ m = np.zeros((self.H, self.W), np.uint8)+ xa, ya = max(ox, 0), max(oy, 0)+ xb, yb = min(ox + w, self.W), min(oy + h, self.H)+ if xb > xa and yb > ya:+ m[ya:yb, xa:xb] = g[ya - oy:yb - oy, xa - ox:xb - ox]+ return m++ def text(self, s, x, y, size=12, font='system', style=(), anchor='l', opaque=False):+ """text tool. opaque=True first clears the glyphs' bounding box (+2 px), like typing into white"""+ m = self.text_mask(s, x, y, size, font, style, anchor)+ if opaque:+ ys, xs = np.nonzero(m)+ if len(xs): self.erase((xs.min() - 2, ys.min() - 2, xs.max() + 3, ys.max() + 3))+ if 'outline' in style or 'shadow' in style:+ # outline styles are hollow: clear the inside of the letters first+ inner = _fill_holes(m)+ self.paint(inner & (1 - m), mode='erase')+ self.paint(m, 'black')+ return m++ # ------------------------------------------------------------ interface state+ def use(self, tool=None, pattern=None, line=None):+ """select a tool / pattern / line width in the palettes (shown in the next snapshot)"""+ if tool: self.state['tool'] = tool+ if pattern: self.state['pattern'] = pattern+ if line: self.state['line'] = line++ def cursor(self, kind=None, x=0, y=0):+ """put the mouse cursor (arrow, cross, ibeam, bucket, spray, brush, pencil) at document (x, y); None hides it"""+ self.state['cursor'] = None if kind is None else (kind, int(x), int(y))++ def select(self, rect=None, lasso=None):+ """marching-ants selection: rect=(x0, y0, x1, y1), or lasso=mask -> shrink-wrapped around its ink"""+ if rect is not None:+ self.state['select'] = ('rect', tuple(int(v) for v in rect))+ elif lasso is not None:+ m = np.asarray(lasso, np.uint8) & self.doc+ self.state['select'] = ('lasso', m)+ else:+ self.state['select'] = None++ def menu(self, name=None, items=(), checked=(), hilite=None, styled=False):+ """pull down menu `name` with `items` ('-' is a dotted separator); `hilite` is the item under the mouse;+ styled=True draws each item in the type style it names (Bold in bold, Outline in outline, ...)"""+ self.state['menu'] = None if name is None else (name, list(items), set(checked), hilite, styled)++ def zoom(self, x=None, y=None, w=13, h=11, at=(470, 40), fat=7, title='zoom'):+ """a small window showing document pixels (x..x+w, y..y+h) as fat bits, top-left at screen `at`"""+ self.state['zoom'] = None if x is None else (int(x), int(y), w, h, at, fat, title)++ def retitle(self, title):+ self.state['title'] = title++ # ------------------------------------------------------------ render the screen+ def render(self):+ S = np.zeros((self.SH, self.SW), np.uint8)+ st = self.state+ self._menubar(S, st)+ self._tools(S, st)+ self._lines(S, st)+ self._patterns(S, st)+ self._window(S, st)+ if st['zoom']: self._zoom(S, st['zoom'])+ if st['menu']: self._pulldown(S, st)+ if st['cursor']: self._cursor(S, *st['cursor'])+ self._corners(S)+ return S++ # -- primitives on the screen buffer+ @staticmethod+ def _box(S, x0, y0, x1, y1, fill=0, border=1):+ """rect with exclusive ends; fill 0 white / 1 black / pattern array"""+ if isinstance(fill, np.ndarray):+ yy, xx = np.mgrid[y0:y1, x0:x1]+ S[y0:y1, x0:x1] = fill[yy % 8, xx % 8]+ else:+ S[y0:y1, x0:x1] = fill+ if border:+ S[y0, x0:x1] = 1; S[y1 - 1, x0:x1] = 1; S[y0:y1, x0] = 1; S[y0:y1, x1 - 1] = 1++ @staticmethod+ def _blit(S, bm, x, y, value=None):+ """paste bitmap: value None -> '#'=1 ink and 'o'=2 white; else set ink pixels to value"""+ h, w = bm.shape+ x, y = int(x), int(y)+ xa, ya, xb, yb = max(x, 0), max(y, 0), min(x + w, S.shape[1]), min(y + h, S.shape[0])+ if xb <= xa or yb <= ya: return+ sub = bm[ya - y:yb - y, xa - x:xb - x]+ tgt = S[ya:yb, xa:xb]+ if value is None:+ tgt[sub == 1] = 1; tgt[sub == 2] = 0+ else:+ tgt[sub == 1] = value++ def _str(self, S, s, x, y, value=1, style=()):+ """system text with baseline-left at screen (x, y)"""+ g = system_text_mask(s, style)+ cols = np.nonzero(g.any(0))[0]+ if len(cols) == 0: return 0+ g = g[:, cols[0]:]+ self._blit(S, g, x, y - 12, value)+ return g.shape[1] - 3++ @staticmethod+ def _str_w(s, style=()):+ g = system_text_mask(s, style)+ cols = np.nonzero(g.any(0))[0]+ return int(cols[-1] - cols[0] + 1) if len(cols) else 0++ # -- pieces of the interface+ def _menubar(self, S, st):+ S[0:20, :] = 0+ S[19, :] = 1+ self._menu_x = []+ # app glyph: a seedling in a pot (stands where a system glyph would be)+ sprout = _rows('...##.##', '..####.#', '..###..#', '...#.##.', '....#...', '..#####.', '..#####.', '...###..', '...###..')+ self._blit(S, sprout, 14, 5)+ x = 40+ for name in self.menus:+ w = self._str_w(name)+ self._menu_x.append((name, x - 8, x + w + 8))+ open_ = st['menu'] and st['menu'][0] == name+ if open_: S[1:19, x - 8:x + w + 8] = 1+ self._str(S, name, x, 14, 0 if open_ else 1)+ x += w + 20++ def _tools(self, S, st):+ x0, y0, x1, y1 = self.tools_box+ self._box(S, x0, y0, x1, y1)+ cw, chh = 26, 20+ for i, name in enumerate(self.TOOLS):+ cx, cy = x0 + (i % 2) * cw, y0 + (i // 2) * chh+ if i % 2 == 0 and i: S[cy, x0:x1] = 1+ if i % 2 == 1: S[cy:cy + chh, cx] = 1+ icon = self._icon(name)+ on = st['tool'] == name+ if on: S[cy + 1:cy + chh, cx + (1 if i % 2 else 1):cx + cw] = 1+ self._blit(S, icon, cx + 5, cy + 2, 0 if on else 1)++ def _icon(self, name):+ if name in ICONS: return _rows(*ICONS[name])+ gray = PATTERNS['gray']+ yy, xx = np.mgrid[0:16, 0:16]+ filled = name in ('frect', 'frrect', 'foval', 'ffree', 'fpoly')+ base = name[1:] if filled else name+ im = Image.new('L', (16, 16), 0); d = ImageDraw.Draw(im)+ if base == 'rect': d.rectangle([1, 3, 14, 12], fill=1)+ elif base == 'rrect': d.rounded_rectangle([1, 3, 14, 12], radius=3, fill=1)+ elif base == 'oval': d.ellipse([1, 3, 14, 12], fill=1)+ elif base == 'free': d.polygon([(3, 3), (8, 2), (13, 5), (11, 8), (14, 12), (6, 13), (2, 10), (5, 7)], fill=1)+ elif base == 'poly': d.polygon([(2, 12), (5, 3), (10, 6), (14, 2), (13, 12)], fill=1)+ m = np.asarray(im, np.uint8)+ b = self.border(m, 1)+ if filled: ic = np.where(m.astype(bool), gray[yy % 8, xx % 8], 0).astype(np.uint8) | b+ else: ic = b+ return ic++ def _lines(self, S, st):+ x0, y0, x1, y1 = self.lines_box+ self._box(S, x0, y0, x1, y1)+ rows = [('dash', 0), (1, 1), (2, 2), (3, 3), (4, 4)]+ for i, (key, w) in enumerate(rows):+ cy = y0 + 8 + i * 12+ if key == 'dash':+ S[cy, x0 + 14:x1 - 6:2] = 1+ else:+ S[cy - w // 2:cy - w // 2 + w, x0 + 14:x1 - 6] = 1+ if st['line'] == key:+ ck = _rows('....#', '...##', '#.##.', '###..', '.#...')+ self._blit(S, ck, x0 + 4, cy - 3)++ def _patterns(self, S, st):+ x0, y0, x1, y1 = self.pat_box+ self._box(S, x0, y0, x1, y1)+ cur = PATTERNS[st['pattern']] if isinstance(st['pattern'], str) else st['pattern']+ # current fill: a pattern-filled card with a little drop shadow+ self._box(S, x0 + 7, y0 + 6, x1 - 9, y1 - 8, cur, 1)+ S[y0 + 8:y1 - 7, x1 - 9] = 1; S[y1 - 8, x0 + 9:x1 - 8] = 1+ px0, py0, px1, py1 = self.pats_box+ n = len(PALETTE); per = (n + 1) // 2+ cw = (px1 - px0 - 1) / per+ ch = (py1 - py0 - 1) // 2+ for i, name in enumerate(PALETTE):+ r, c = divmod(i, per)+ a, b = int(round(px0 + c * cw)), int(round(px0 + (c + 1) * cw))+ self._box(S, a, py0 + r * ch, b + 1, py0 + (r + 1) * ch + 1, PATTERNS[name], 1)+ S[py1 - 1, px0:px1] = 1++ def _window(self, S, st):+ x0, y0, x1, y1 = self.win+ vx0, vy0, vx1, vy1 = self.view+ self._box(S, x0, y0, x1, y1, 0, 1)+ S[y0 + 1:y1 + 1, x1] = 1; S[y1, x0 + 1:x1 + 1] = 1 # 1-px drop shadow+ # title bar: six fine stripes, a close box, the title in a white gap+ S[y0 + 18, x0:x1] = 1+ for k in range(6):+ S[y0 + 4 + 2 * k, x0 + 2:x1 - 2] = 1+ S[y0 + 3:y0 + 16, x0 + 8:x0 + 23] = 0+ self._box(S, x0 + 9, y0 + 4, x0 + 22, y0 + 15, 0, 1)+ t = st['title']+ tw = self._str_w(t)+ tx = (x0 + x1) // 2 - tw // 2+ S[y0 + 3:y0 + 16, tx - 7:tx + tw + 7] = 0+ self._str(S, t, tx, y0 + 14, 1)+ # content+ sx, sy = int(self.scroll[0] * max(0, self.W - self.VW)), int(self.scroll[1] * max(0, self.H - self.VH))+ part = self.doc[sy:sy + self.VH, sx:sx + self.VW]+ S[vy0:vy0 + part.shape[0], vx0:vx0 + part.shape[1]] = part+ sel = st['select']+ if sel: self._ants(S, sel, vx0 - sx, vy0 - sy, (vx0, vy0, vx1, vy1))+ # scroll bars+ S[vy0 - 1:y1, vx1] = 1; S[vy1, x0:x1] = 1+ gray = PATTERNS['gray']+ self._box(S, vx1, vy0 - 1, x1, vy1 + 1, gray, 1)+ self._box(S, x0, vy1, vx1 + 1, y1, gray, 1)+ up = _rows('....#....', '...#.#...', '..#...#..', '.#.....#.', '###...###', '..#...#..', '..#...#..', '..#####..')+ self._box(S, vx1, vy0 - 1, x1, vy0 + 15, 0, 1); self._blit(S, up, vx1 + 4, vy0 + 3)+ self._box(S, vx1, vy1 - 16, x1, vy1 + 1, 0, 1); self._blit(S, up[::-1], vx1 + 4, vy1 - 12)+ lt = up.T+ self._box(S, x0, vy1, x0 + 16, y1, 0, 1); self._blit(S, lt, x0 + 4, vy1 + 4)+ self._box(S, vx1 - 15, vy1, vx1 + 1, y1, 0, 1); self._blit(S, lt[:, ::-1], vx1 - 12, vy1 + 4)+ # thumbs+ ty = vy0 + 15 + int((vy1 - vy0 - 47) * self.scroll[1])+ self._box(S, vx1, ty, x1, ty + 17, 0, 1)+ tx2 = x0 + 15 + int((vx1 - x0 - 47) * self.scroll[0])+ self._box(S, tx2, vy1, tx2 + 17, y1, 0, 1)+ # size box+ self._box(S, vx1, vy1, x1, y1, 0, 1)+ self._box(S, vx1 + 6, vy1 + 6, x1 - 2, y1 - 2, 0, 1)+ self._box(S, vx1 + 3, vy1 + 3, vx1 + 10, vy1 + 10, 0, 1)++ def _ants(self, S, sel, ox, oy, clip):+ cx0, cy0, cx1, cy1 = clip+ if sel[0] == 'rect':+ x0, y0, x1, y1 = sel[1]+ m = np.zeros((self.H, self.W), np.uint8)+ m[max(y0, 0):y1, max(x0, 0):x1] = 1+ edge = self.border(m, 1)+ else:+ m = _dilate(sel[1], 1, square=True)+ edge = m & (1 - _erode(m, 1, square=False))+ ys, xs = np.nonzero(edge)+ X, Y = xs + ox, ys + oy+ ok = (X >= cx0) & (X < cx1) & (Y >= cy0) & (Y < cy1)+ S[Y[ok], X[ok]] = (((X[ok] + Y[ok]) // 4) % 2 == 0).astype(np.uint8)++ def _pulldown(self, S, st):+ name, items, checked, hilite, styled = st['menu']+ hit = [m for m in self._menu_x if m[0] == name]+ if not hit: return+ _, mx0, _ = hit[0]+ widths = [self._str_w(it, (it.lower(),) if styled and it.lower() in ('bold', 'italic', 'underline', 'outline', 'shadow') else ())+ for it in items if it != '-']+ w = max(widths + [40]) + 34+ h = sum(6 if it == '-' else 16 for it in items) + 4+ x0, y0 = mx0, 19+ self._box(S, x0, y0, x0 + w, y0 + h, 0, 1)+ S[y0 + 2:y0 + h + 1, x0 + w] = 1; S[y0 + h, x0 + 2:x0 + w + 1] = 1 # shadow+ y = y0 + 2+ for it in items:+ if it == '-':+ S[y + 3, x0 + 1:x0 + w - 1:2] = 1+ y += 6; continue+ on = it == hilite+ if on: S[y:y + 16, x0 + 1:x0 + w - 1] = 1+ v = 0 if on else 1+ style = (it.lower(),) if styled and it.lower() in ('bold', 'italic', 'underline', 'outline', 'shadow') else ()+ self._str(S, it, x0 + 18, y + 13, v, style)+ if it in checked:+ ck = _rows('......#', '.....##', '#...##.', '##.##..', '.###...', '..#....')+ self._blit(S, ck, x0 + 5, y + 5, v)+ y += 16++ def _zoom(self, S, z):+ x, y, w, h, at, fat, title = z+ ax, ay = at+ W, H = w * fat + 3, h * fat + 3 + 18+ self._box(S, ax, ay, ax + W, ay + H, 0, 1)+ S[ay + 1:ay + H + 1, ax + W] = 1; S[ay + H, ax + 1:ax + W + 1] = 1+ S[ay + 18, ax:ax + W] = 1+ for k in range(6): S[ay + 4 + 2 * k, ax + 2:ax + W - 2] = 1+ tw = self._str_w(title)+ tx = ax + W // 2 - tw // 2+ S[ay + 3:ay + 16, tx - 5:tx + tw + 5] = 0+ self._str(S, title, tx, ay + 14, 1)+ patch = self.doc[y:y + h, x:x + w]+ for j in range(patch.shape[0]):+ for i in range(patch.shape[1]):+ if patch[j, i]:+ px, py = ax + 2 + i * fat, ay + 20 + j * fat+ S[py:py + fat - 1, px:px + fat - 1] = 1++ def _cursor(self, S, kind, x, y):+ rows, (hx, hy) = CURSORS[kind]+ bm = _bitmap(rows)+ # every cursor gets a white halo so it reads over any pattern+ ink = (bm == 1).astype(np.uint8)+ halo = _dilate(np.pad(ink, 1), 1, square=True)+ full = np.where(np.pad(ink, 1) == 1, 1, np.where((halo == 1) | (np.pad(bm, 1) == 2), 2, 0)).astype(np.uint8)+ sx, sy = self.view[0] + x - int(self.scroll[0] * max(0, self.W - self.VW)), \+ self.view[1] + y - int(self.scroll[1] * max(0, self.H - self.VH))+ self._blit(S, full, sx - hx - 1, sy - hy - 1)++ def _corners(self, S):+ r = 6+ yy, xx = np.mgrid[0:r, 0:r]+ outside = (xx - r + 0.5) ** 2 + (yy - r + 0.5) ** 2 > r * r+ S[:r, :r][outside] = 1+ S[:r, -r:][outside[:, ::-1]] = 1+ S[-r:, :r][outside[::-1]] = 1+ S[-r:, -r:][outside[::-1, ::-1]] = 1++ # ------------------------------------------------------------ output+ def image(self, S=None):+ S = self.render() if S is None else S+ big = np.repeat(np.repeat(S, self.scale, 0), self.scale, 1)+ ink = np.array(Image.new('RGB', (1, 1), self.ink).getpixel((0, 0)), np.uint8)+ pap = np.array(Image.new('RGB', (1, 1), self.paper).getpixel((0, 0)), np.uint8)+ rgb = np.where(big[..., None] == 1, ink, pap).astype(np.uint8)+ im = Image.fromarray(rgb, 'RGB')+ if self.ink in ('#000000', 'black') and self.paper in ('#ffffff', 'white'): im = im.convert('L')+ return im++ def stage(self, name):+ self.stages.append((name, self.image()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.image()+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return img+++def _fill_holes(m):+ """pixels enclosed by m (the inside of outlined letters)"""+ H, W = m.shape+ im = Image.fromarray(np.pad(m, 1) * 1).copy()+ ImageDraw.floodfill(im, (0, 0), 7)+ outside = (np.asarray(im) == 7)[1:-1, 1:-1]+ return (~outside).astype(np.uint8)diff --git a/lib/rubberhose.py b/lib/rubberhose.pynew file mode 100644index 0000000..b12bf00--- /dev/null+++ b/lib/rubberhose.py@@ -0,0 +1,1394 @@+"""rubberhose — a frame from a 1930s black-and-white "rubber hose" cartoon, printed on old film (numpy + Pillow only).++Model: one frame of an early-sound-era cartoon, made the way the studios made it, then photographed and aged.+ background painted once by the background artist on board in grey gouache: flat tonal washes with a dry-brush+ streak, soft airbrushed pools of light and shade, contact shadows under furniture, and outlines in a+ thin dark-grey line -- thinner and greyer than the characters' ink, so the actors sit in front.+ Things the actors pass *behind* (a hill, a window bar, a blanket) are painted as overlays: they are+ stored as clip masks and cut the character cels (`clip=` on every cel method).+ pencil the animator's rough on paper: thin grey lines drawn twice and a little off, construction circles,+ cross-hairs on the face and a line of action through the body.+ cel traced in black ink on clear celluloid (an even, heavy line, a few per cent thicker and thinner along+ its length as the pen pressure drifts), then painted on the back in a handful of flat greys -- white,+ light, mid, dark, black. No shading on a cel. Everything is opaque and drawn back to front, so a fill+ knocks out the lines behind it.+ vocabulary the rubber-hose look: arms and legs are bendy tubes of constant width with no elbows or knees+ (`hose`), white four-fingered gloves with three stitch lines and a flared, rolled cuff (`glove`), big+ oval shoes with a white shine (`shoe`), white eyes with black pie-cut pupils (`pie_eye`), wide open+ grins with a tongue, and props that are alive -- clocks, suns, pillows and slippers get faces, gloves+ and shoes.+ effects vibration arcs, shake ticks, impact stars, speed lines, snore Zs and bouncing slab-serif lettering+ ("RRRING!") inked and painted like everything else.+ camera the cel stack shot on black-and-white negative and printed: lens softness (softer in the corners),+ halation round bright paint, a print tone curve (blacks lifted, whites held, a silvery-warm tone),+ grain clumps strongest in the mid-greys, uneven density, vignette, gate weave (the frame sits a few+ pixels off and a hair rotated) and the rounded projector gate with a soft black edge.+ aging a print after a hundred runs: vertical scratches (white through the emulsion, dark in the base) that+ come and go along their length, white specks (dirt on the negative) and black specks (dirt on the+ print), lint fibres, a hair caught in the gate, faint processing stains, and a little extra+ density at one side (flicker).++ from rubberhose import RubberHose, WHITE, BLACK+ rh = RubberHose(1920, 1080, seed=3)+ rh.wall(720); rh.floor(720) # background, painted on board+ rh.stage('background')+ c = rh.alarm_clock(930, 390, 135, tilt=0.1) # pencil rough of a character+ rh.stage('pencil'); rh.ink(); rh.stage('ink'); rh.paint(); rh.stage('paint')+ rh.lettering('RRRING!', [(700, 130), (930, 70), (1170, 120)], 90)+ rh.film(); rh.age()+ rh.save('out.jpg')+"""+import glob+import os+import numpy as np+from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageChops+from core import blur, fbm1d, noise2d, smoothstep, load_font++INK = 0.035+WHITE, LIGHT, PALE, MID, DARK, BLACK = 0.96, 0.84, 0.70, 0.55, 0.36, 0.07++_SLAB = [('/System/Library/Fonts/Supplemental/SuperClarendon.ttc', 7), # Clarendon black: old title cards+ ('/System/Library/Fonts/Supplemental/Rockwell.ttc', 2),+ ('/usr/share/fonts/**/DejaVuSerif-Bold.ttf', 0), ('C:/Windows/Fonts/ROCKB.TTF', 0),+ ('C:/Windows/Fonts/georgiab.ttf', 0)]+++def slab_font(size):+ """a heavy slab / Clarendon face for 1930s cartoon lettering (falls back to core.load_font('serif'))"""+ env = os.environ.get('INKPAINT_FONT_SLAB')+ cands = ([(env, 0)] if env else []) + _SLAB+ for pat, idx in cands:+ for f in glob.glob(pat, recursive=True):+ try:+ return ImageFont.truetype(f, int(size), index=idx)+ except OSError:+ pass+ return load_font('serif', size)+++def ellipse_pts(cx, cy, rx, ry, rot=0.0, a0=0.0, a1=2 * np.pi, n=None):+ """points on an ellipse (closed loop if a0..a1 is the full turn, else an arc)"""+ if n is None:+ n = int(max(20, min(240, (abs(rx) + abs(ry)) * 0.9 * (a1 - a0) / (2 * np.pi))))+ full = abs(a1 - a0) >= 2 * np.pi - 1e-6+ t = np.linspace(a0, a1, n, endpoint=not full)+ x, y = np.cos(t) * rx, np.sin(t) * ry+ c, s = np.cos(rot), np.sin(rot)+ return np.stack([cx + x * c - y * s, cy + x * s + y * c], 1).astype(np.float32)+++def bezier(p0, p1, p2, p3, n=48):+ t = np.linspace(0, 1, n, dtype=np.float32)[:, None]+ p0, p1, p2, p3 = [np.asarray(p, np.float32) for p in (p0, p1, p2, p3)]+ return (1 - t) ** 3 * p0 + 3 * (1 - t) ** 2 * t * p1 + 3 * (1 - t) * t ** 2 * p2 + t ** 3 * p3+++def hose_path(p0, p1, bend=0.0, bend2=None, out0=None, n=48):+ """a rubber-hose limb from p0 to p1: one smooth C-curve (bend px to the right of travel), or an S-curve when+ bend2 has the other sign. out0 = optional unit direction the limb leaves p0 in (from the body)"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ d = p1 - p0; L = float(np.hypot(*d)) + 1e-6+ nrm = np.array([-d[1], d[0]], np.float32) / L+ b2 = bend if bend2 is None else bend2+ c1 = p0 + d / 3 + nrm * bend * 1.33+ if out0 is not None:+ c1 = p0 + np.asarray(out0, np.float32) * L * 0.38 + nrm * bend * 0.6+ c2 = p0 + d * 2 / 3 + nrm * b2 * 1.33+ return bezier(p0, c1, c2, p1, n)+++def _resample(P, step, closed=False):+ P = np.asarray(P, np.float32)+ if closed:+ P = np.vstack([P, P[:1]])+ seg = np.hypot(*np.diff(P, axis=0).T)+ L = float(seg.sum())+ if L < 1e-3:+ return P[:1], np.zeros(1, np.float32), 0.0+ s = np.concatenate([[0], np.cumsum(seg)])+ n = max(2, int(np.ceil(L / step)) + 1)+ u = np.linspace(0, L, n)+ return np.stack([np.interp(u, s, P[:, 0]), np.interp(u, s, P[:, 1])], 1), (u / L).astype(np.float32), L+++class Frame:+ """local drawing frame: unit `s` px, rotated by `rot` (clockwise on screen, radians), mirrored when flip=-1"""++ def __init__(self, x, y, s=1.0, rot=0.0, flip=1):+ self.o = np.array([x, y], np.float32); self.s = float(s); self.rot = rot; self.f = flip+ self.c, self.sn = np.cos(rot), np.sin(rot)++ def __call__(self, pts):+ P = np.atleast_2d(np.asarray(pts, np.float32)).copy()+ P[:, 0] *= self.f+ x = P[:, 0] * self.c - P[:, 1] * self.sn+ y = P[:, 0] * self.sn + P[:, 1] * self.c+ return np.stack([x, y], 1) * self.s + self.o++ def p(self, x, y):+ return self([(x, y)])[0]++ def ang(self, a):+ """world angle of a local direction"""+ v = self([(np.cos(a), np.sin(a))])[0] - self.o+ return float(np.arctan2(v[1], v[0]))+++class RubberHose:+ def __init__(self, W=1920, H=1080, seed=0, ss=2, ink_w=5.5):+ self.W, self.H, self.ss = W, H, ss+ self.rng = np.random.default_rng(seed)+ self.ink_w = ink_w+ H2, W2 = H * ss, W * ss+ self.bg = np.full((H2, W2), 0.78, np.float32)+ blot = noise2d(H2 // 2, W2 // 2, 200, 4, self._seed()) - 0.5+ streak = self.rng.random((H2 // 6 + 1, W2 // 60 + 1)).astype(np.float32) - 0.5+ tex = np.array(Image.fromarray(blot * 0.8).resize((W2, H2), Image.BICUBIC), np.float32)+ tex += np.asarray(Image.fromarray(streak).resize((W2, H2), Image.BICUBIC), np.float32) * 0.9+ self.tex = tex+ self.layout = Image.new('L', (W2, H2), 0)+ self.clips = {}+ self.prims = []+ self.state = 'pencil'+ self.film_opts = None+ self.age_opts = None+ self.stages = []+ self._cache = None++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ================================================================ background (painted on board)+ def _bbox(self, P, pad):+ S = self.ss+ x0 = int(max(0, np.floor(P[:, 0].min() * S - pad))); y0 = int(max(0, np.floor(P[:, 1].min() * S - pad)))+ x1 = int(min(self.W * S, np.ceil(P[:, 0].max() * S + pad))); y1 = int(min(self.H * S, np.ceil(P[:, 1].max() * S + pad)))+ if x1 <= x0 or y1 <= y0:+ return None+ return x0, y0, x1, y1++ def _field(self, value, value2, axis, x0, y0, x1, y1):+ if value2 is None:+ return np.float32(value)+ S = self.ss+ (ax, ay), (bx, by) = axis+ X = (np.arange(x0, x1, dtype=np.float32) + 0.5) / S+ Y = (np.arange(y0, y1, dtype=np.float32) + 0.5) / S+ dx, dy = bx - ax, by - ay; L2 = dx * dx + dy * dy + 1e-6+ t = np.clip(((X[None, :] - ax) * dx + (Y[:, None] - ay) * dy) / L2, 0, 1)+ return value + (value2 - value) * t++ def _apply_mask(self, m, bb, value, value2=None, axis=None, tex=1.0):+ x0, y0, x1, y1 = bb+ v = self._field(value, value2, axis, x0, y0, x1, y1) + self.tex[y0:y1, x0:x1] * 0.03 * tex+ sl = self.bg[y0:y1, x0:x1]+ sl += (v - sl) * m++ def wash(self, pts, value, value2=None, axis=None, tex=1.0, line=2.2, dark=0.7, layout=True):+ """a flat (or graded: value -> value2 along axis=((x0, y0), (x1, y1))) gouache wash inside a polygon,+ outlined in the background's thin dark-grey line"""+ P = np.asarray(pts, np.float32); S = self.ss+ bb = self._bbox(P, 4)+ if bb is None:+ return+ x0, y0, x1, y1 = bb+ im = Image.new('L', (x1 - x0, y1 - y0), 0)+ ImageDraw.Draw(im).polygon([(float(x * S - x0), float(y * S - y0)) for x, y in P], fill=255)+ self._apply_mask(np.asarray(im, np.float32) / 255, bb, value, value2, axis, tex)+ if layout:+ ImageDraw.Draw(self.layout).polygon([(float(x * S), float(y * S)) for x, y in P], fill=0)+ if line:+ self.line(P, line, dark, closed=True, layout=layout)++ def blob(self, circles, value, line=2.2, dark=0.7, tex=1.0, layout=True):+ """a union of circles (clouds, tree crowns, puffs) washed in one value; outline only round the union"""+ C = np.asarray(circles, np.float32); S = self.ss+ P = np.concatenate([C[:, :2] - C[:, 2:3], C[:, :2] + C[:, 2:3]])+ bb = self._bbox(P, 8)+ if bb is None:+ return+ x0, y0, x1, y1 = bb+ im = Image.new('L', (x1 - x0, y1 - y0), 0); d = ImageDraw.Draw(im)+ for x, y, r in C:+ d.ellipse([x * S - r * S - x0, y * S - r * S - y0, x * S + r * S - x0, y * S + r * S - y0], fill=255)+ m = np.asarray(im, np.float32) / 255+ self._apply_mask(m, bb, value, tex=tex)+ if line:+ k = int(round(line * S)) | 1+ edge = np.asarray(ImageChops.subtract(im.filter(ImageFilter.MaxFilter(k)), im.filter(ImageFilter.MinFilter(3))),+ np.float32) / 255+ sl = self.bg[y0:y1, x0:x1]; sl *= 1 - dark * edge+ if layout:+ lay = self.layout.crop((x0, y0, x1, y1))+ lay.paste(0, mask=im)+ e2 = ImageChops.subtract(im.filter(ImageFilter.MaxFilter(3)), im)+ lay.paste(255, mask=e2)+ self.layout.paste(lay, (x0, y0))++ def line(self, pts, width=2.2, dark=0.7, closed=False, layout=True):+ """the background painter's outline: an even, thin, dark-grey line"""+ P = np.asarray(pts, np.float32); S = self.ss+ bb = self._bbox(P, width * S + 4)+ if bb is None:+ return+ x0, y0, x1, y1 = bb+ Q = [(float(x * S - x0), float(y * S - y0)) for x, y in P]+ if closed:+ Q = Q + Q[:1]+ im = Image.new('L', (x1 - x0, y1 - y0), 0); d = ImageDraw.Draw(im)+ w = max(1, int(round(width * S)))+ d.line(Q, fill=255, width=w, joint='curve')+ r = w / 2+ for q in (Q[0], Q[-1]):+ d.ellipse([q[0] - r, q[1] - r, q[0] + r, q[1] + r], fill=255)+ m = np.asarray(im, np.float32) / 255+ sl = self.bg[y0:y1, x0:x1]; sl *= 1 - dark * m+ if layout:+ ImageDraw.Draw(self.layout).line([(q[0] + x0, q[1] + y0) for q in Q], fill=255, width=max(2, S + 1))++ def airbrush(self, cx, cy, rx, ry, amount, rot=0.0):+ """a soft airbrushed pool: amount > 0 lightens (light from a window), < 0 darkens (contact shadow)"""+ S = self.ss+ P = ellipse_pts(cx, cy, rx * 2.2, ry * 2.2, rot, n=16)+ bb = self._bbox(P, 2)+ if bb is None:+ return+ x0, y0, x1, y1 = bb+ X = (np.arange(x0, x1, dtype=np.float32) + 0.5) / S - cx+ Y = (np.arange(y0, y1, dtype=np.float32) + 0.5) / S - cy+ c, s = np.cos(rot), np.sin(rot)+ u = (X[None, :] * c + Y[:, None] * s) / rx; v = (-X[None, :] * s + Y[:, None] * c) / ry+ g = np.exp(-(u * u + v * v) * 1.4)+ sl = self.bg[y0:y1, x0:x1]+ if amount >= 0:+ sl += (1 - sl) * g * amount+ else:+ sl *= 1 + g * amount++ def light(self, pts, amount=0.2, soft=14.0):+ """a soft-edged patch of light (sunbeam on the floor) airbrushed over the background; amount < 0 for a+ soft shade"""+ S = self.ss; P = np.asarray(pts, np.float32)+ bb = self._bbox(P, soft * S * 3)+ if bb is None:+ return+ x0, y0, x1, y1 = bb+ im = Image.new('L', (x1 - x0, y1 - y0), 0)+ ImageDraw.Draw(im).polygon([(float(x * S - x0), float(y * S - y0)) for x, y in P], fill=255)+ m = np.asarray(im.filter(ImageFilter.GaussianBlur(soft * S)), np.float32) / 255+ sl = self.bg[y0:y1, x0:x1]+ if amount >= 0:+ sl += (1 - sl) * m * amount+ else:+ sl *= 1 + m * amount++ def pattern(self, pts, draw_fn, dark=0.15):+ """paint a small repeat pattern (wallpaper sprigs, polka dots) inside a polygon: draw_fn(ImageDraw, S)+ draws motifs in canvas px * S on a full-size sheet"""+ S = self.ss; P = np.asarray(pts, np.float32)+ bb = self._bbox(P, 2)+ if bb is None:+ return+ x0, y0, x1, y1 = bb+ im = Image.new('L', (self.W * S, self.H * S), 0)+ draw_fn(ImageDraw.Draw(im), S)+ im = im.crop(bb)+ mk = Image.new('L', im.size, 0)+ ImageDraw.Draw(mk).polygon([(float(x * S - x0), float(y * S - y0)) for x, y in P], fill=255)+ m = np.asarray(im, np.float32) / 255 * np.asarray(mk, np.float32) / 255+ sl = self.bg[y0:y1, x0:x1]; sl *= 1 - dark * m++ # ---------------------------------------------------------------- clip masks (overlays the actors pass behind)+ def clip(self, name, add=None, sub=None, full=False):+ """build a named clip mask for cels: add / sub are lists of polygons; full=True starts from everything"""+ S = self.ss+ if name not in self.clips:+ self.clips[name] = Image.new('L', (self.W * S, self.H * S), 255 if full else 0)+ d = ImageDraw.Draw(self.clips[name])+ for pts in (add or []):+ d.polygon([(float(x * S), float(y * S)) for x, y in pts], fill=255)+ for pts in (sub or []):+ d.polygon([(float(x * S), float(y * S)) for x, y in pts], fill=0)+ return name++ # ---------------------------------------------------------------- the room+ def wall(self, y1, value=0.8, value_top=0.62, stripes=0.022, sprigs=True, base=40):+ """papered wall down to y1: a graded wash (dark at the ceiling), soft vertical stripes, rows of little+ sprigs, and a skirting board"""+ W, S = self.W, self.ss+ self.wash([(0, 0), (W, 0), (W, y1), (0, y1)], value_top, value, ((0, 0), (0, y1 * 0.85)), line=0)+ if stripes:+ X = np.arange(W * S, dtype=np.float32) / S+ band = smoothstep(-0.25, 0.25, np.sin(2 * np.pi * X / 76.0)).astype(np.float32) - 0.5+ self.bg[:int(y1 * S)] += band[None, :] * stripes+ if sprigs:+ rng = np.random.default_rng(self._seed())++ def motif(d, S):+ for j, y in enumerate(np.arange(46, y1 - base, 76)):+ for x in np.arange(38 * (j % 2), W + 40, 76):+ x2, y2 = x + rng.normal(0, 1.2), y + rng.normal(0, 1.2)+ for a in (0, 2.1, 4.2):+ px, py = x2 + 5 * np.cos(a - 1.57), y2 + 5 * np.sin(a - 1.57)+ d.ellipse([(px - 3.6) * S, (py - 3.6) * S, (px + 3.6) * S, (py + 3.6) * S], fill=255)+ d.line([(x2 * S, (y2 + 4) * S), ((x2 - 3) * S, (y2 + 15) * S)], fill=255, width=int(2 * S))+ d.ellipse([(x2 + 2) * S, (y2 + 9) * S, (x2 + 9) * S, (y2 + 13) * S], fill=255)+ self.pattern([(0, 0), (W, 0), (W, y1 - base), (0, y1 - base)], motif, dark=0.14)+ self.wash([(0, y1 - base), (W, y1 - base), (W, y1), (0, y1)], 0.56, 0.5, ((0, y1 - base), (0, y1)))+ self.line([(0, y1 - base + 8), (W, y1 - base + 8)], 1.6, 0.45)++ def floor(self, y0, value_back=0.44, value_front=0.62, board=104, vp=(960, -1500)):+ """wooden floor from y0 down: planks converging on a far vanishing point, butt joints, faint grain"""+ W, H = self.W, self.H+ rng = np.random.default_rng(self._seed())+ self.wash([(0, y0), (W, y0), (W, H), (0, H)], value_back, value_front, ((0, y0), (0, H)), line=0)+ vx, vy = vp+ seams = []+ for k in range(-30, 60):+ xs = -1500 + k * board+ xb = vx + (xs - vx) * (H + 20 - vy) / (y0 - vy)+ if max(xs, xb) < -50 or min(xs, xb) > W + 50:+ continue+ seams.append(((xs, y0), (xb, H + 20)))+ for a, b in seams:+ self.line([a, b], 1.7, 0.42)+ for (a, b), (c, d) in zip(seams[:-1], seams[1:]):+ for _ in range(rng.integers(1, 3)):+ t = rng.uniform(0.08, 0.95)+ ya = y0 + (H - y0) * t+ xa = a[0] + (b[0] - a[0]) * (ya - y0) / (H + 20 - y0); xc = c[0] + (d[0] - c[0]) * (ya - y0) / (H + 20 - y0)+ self.line([(xa, ya), (xc, ya)], 1.5, 0.35, layout=False)+ for _ in range(2):+ t0 = rng.uniform(0, 0.6); n = 12+ ys = y0 + (H - y0) * np.linspace(t0, min(1, t0 + rng.uniform(0.2, 0.5)), n)+ f = rng.uniform(0.25, 0.75)+ xa = a[0] + (b[0] - a[0]) * (ys - y0) / (H + 20 - y0); xc = c[0] + (d[0] - c[0]) * (ys - y0) / (H + 20 - y0)+ xg = xa + (xc - xa) * f + fbm1d(n, 6, 2, self._seed()) * 4+ self.line(np.stack([xg, ys], 1), 1.0, 0.12, layout=False)+ self.airbrush(W / 2, y0 + 6, W * 0.8, 26, -0.28)++ def window(self, x0, y0, x1, y1, frame=24, bar=14, horizon=None, bars='sash', valley=None, clip='window'):+ """a sash window with a morning landscape outside: graded sky, two clouds, far hill with a tree and grass+ ticks, a near hill (an overlay: anything clipped to `clip` -- the sun -- rises behind it), white painted+ frame, glazing bars and a sill. Returns geometry (glass, panes, hill polygon)"""+ rng = np.random.default_rng(self._seed())+ gx0, gy0, gx1, gy1 = x0 + frame, y0 + frame, x1 - frame, y1 - frame+ hz = horizon if horizon is not None else gy1 - (gy1 - gy0) * 0.16+ self.wash([(gx0, gy0), (gx1, gy0), (gx1, gy1), (gx0, gy1)], 0.66, 0.88, ((0, gy0), (0, hz)), line=0, tex=0.6)+ for cx, cy, s in ((gx0 + (gx1 - gx0) * 0.24, gy0 + 62, 1.0), (gx0 + (gx1 - gx0) * 0.8, gy0 + 120, 0.75)):+ self.blob([(cx - 34 * s, cy + 6 * s, 24 * s), (cx - 6 * s, cy - 12 * s, 32 * s), (cx + 28 * s, cy, 26 * s),+ (cx + 2 * s, cy + 14 * s, 24 * s)], 0.93, line=2.0, dark=0.55)+ xs = np.linspace(gx0 - 10, gx1 + 10, 60)+ far = hz - 40 + 22 * np.sin((xs - gx0) / (gx1 - gx0) * 3.4 + 0.6) + fbm1d(60, 20, 2, self._seed()) * 4+ far_poly = np.vstack([np.stack([xs, far], 1), [(gx1 + 10, gy1 + 5), (gx0 - 10, gy1 + 5)]])+ self.wash(far_poly, 0.72, 0.66, ((0, hz - 60), (0, gy1)), line=2.0, dark=0.6)+ tx = gx0 + (gx1 - gx0) * 0.2; ty = float(np.interp(tx, xs, far))+ self.wash([(tx - 6, ty + 6), (tx + 6, ty + 6), (tx + 4, ty - 46), (tx - 4, ty - 46)], 0.4, line=1.8, dark=0.6)+ self.blob([(tx - 18, ty - 58, 20), (tx + 2, ty - 74, 24), (tx + 20, ty - 56, 19), (tx, ty - 50, 18)], 0.46,+ line=2.0, dark=0.6)+ for gx in rng.uniform(gx0 + 20, gx1 - 20, 9):+ gy = float(np.interp(gx, xs, far)) + rng.uniform(14, 40)+ self.line([(gx - 5, gy + 3), (gx, gy - 5), (gx + 5, gy + 3)], 1.4, 0.45, layout=False)+ vx = valley if valley is not None else (gx0 + gx1) / 2+ near = hz + 24 * np.cos((xs - vx) / (gx1 - gx0) * 2 * np.pi * 0.85) + fbm1d(60, 20, 2, self._seed()) * 3+ near_poly = np.vstack([np.stack([xs, near], 1), [(gx1 + 10, gy1 + 5), (gx0 - 10, gy1 + 5)]])+ self.wash(near_poly, 0.6, 0.54, ((0, hz), (0, gy1)), line=2.0, dark=0.6)+ for gx in rng.uniform(gx0 + 20, gx1 - 20, 7):+ gy = float(np.interp(gx, xs, near)) + rng.uniform(12, 30)+ if gy < gy1 - 6:+ self.line([(gx - 5, gy + 3), (gx, gy - 5), (gx + 5, gy + 3)], 1.4, 0.45, layout=False)+ # painted frame and glazing bars+ mx, my = (gx0 + gx1) / 2, (gy0 + (gy1 - gy0) * 0.42 if bars == 'sash' else (gy0 + gy1) / 2)+ fr = [[(x0, y0), (x1, y0), (x1, gy0), (x0, gy0)], [(x0, gy1), (x1, gy1), (x1, y1), (x0, y1)],+ [(x0, gy0), (gx0, gy0), (gx0, gy1), (x0, gy1)], [(gx1, gy0), (x1, gy0), (x1, gy1), (gx1, gy1)]]+ for p in fr:+ self.wash(p, 0.9, line=0)+ self.line([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], 2.2, 0.7, closed=True)+ self.line([(gx0, gy0), (gx1, gy0), (gx1, gy1), (gx0, gy1)], 2.0, 0.7, closed=True)+ rails = [[(gx0, my - bar / 2), (gx1, my - bar / 2), (gx1, my + bar / 2), (gx0, my + bar / 2)]]+ if bars == 'cross':+ rails.append([(mx - bar / 2, gy0), (mx + bar / 2, gy0), (mx + bar / 2, gy1), (mx - bar / 2, gy1)])+ for p in rails:+ self.wash(p, 0.88, line=0)+ for p in rails:+ self.line(p, 1.8, 0.62, closed=True)+ self.wash([(x0 - 26, y1 - 2), (x1 + 26, y1 - 2), (x1 + 26, y1 + 20), (x0 - 26, y1 + 20)], 0.88, 0.8,+ ((0, y1), (0, y1 + 20)))+ self.airbrush((x0 + x1) / 2, y1 + 30, (x1 - x0) * 0.55, 14, -0.25)+ self.clip(clip, add=[[(gx0, gy0), (gx1, gy0), (gx1, gy1), (gx0, gy1)]], sub=[near_poly] + rails)+ return dict(glass=(gx0, gy0, gx1, gy1), mid=(mx, my), hill=near_poly, horizon=hz)++ def curtain(self, x_rod0, x_rod1, top, bottom, tie_y, side='left', value=0.6, clip='window'):+ """a gathered curtain hanging from a rod, tied back at tie_y, with polka dots and fold lines; it also cuts+ the window clip (the sun goes behind it)"""+ a, b = x_rod0, x_rod1; w = b - a+ if side == 'left':+ tie = (a + w * 0.12, a + w * 0.52); foot = (a - w * 0.06, a + w * 0.95)+ else:+ tie = (a + w * 0.48, a + w * 0.88); foot = (a + w * 0.05, b + w * 0.06)+ n = 24+ t = np.linspace(0, 1, n)+ def side_x(top_x, tie_x, foot_x):+ up = top_x + (tie_x - top_x) * np.sin(t * np.pi / 2)+ dn = tie_x + (foot_x - tie_x) * (1 - np.cos(t * np.pi / 2))+ return up, dn+ lu, ld = side_x(a, tie[0], foot[0]); ru, rd = side_x(b, tie[1], foot[1])+ yu = top + (tie_y - top) * t; yd = tie_y + (bottom - tie_y) * t+ left = np.vstack([np.stack([lu, yu], 1), np.stack([ld, yd], 1)])+ right = np.vstack([np.stack([ru, yu], 1), np.stack([rd, yd], 1)])+ hem = np.stack([np.linspace(left[-1, 0], right[-1, 0], 20),+ bottom + 6 * np.abs(np.sin(np.linspace(0, 4 * np.pi, 20)))], 1)+ poly = np.vstack([left, hem, right[::-1]])+ self.wash(poly, value + 0.06, value - 0.04, ((0, top), (0, bottom)))+ rng = np.random.default_rng(self._seed())++ def dots(d, S):+ for j, y in enumerate(np.arange(top + 18, bottom, 34)):+ for x in np.arange(a - 40 + 17 * (j % 2), b + 40, 34):+ r = 5.0+ d.ellipse([(x - r) * S, (y - r) * S, (x + r) * S, (y + r) * S], fill=255)+ self.pattern(poly, dots, dark=-0.35)+ for f in (0.3, 0.55, 0.78):+ fx_u = lu + (ru - lu) * f; fx_d = ld + (rd - ld) * f+ P = np.vstack([np.stack([fx_u, yu], 1)[2:], np.stack([fx_d, yd], 1)[:-3]])+ self.line(P, 1.5, 0.45)+ tx0, tx1 = tie[0] - 6, tie[1] + 6+ self.wash([(tx0, tie_y - 9), (tx1, tie_y - 9), (tx1, tie_y + 9), (tx0, tie_y + 9)], 0.4)+ self.clip(clip, sub=[poly])+ return poly++ def valance(self, x0, x1, y0, y1, scallops=7, value=0.5, clip='window'):+ """a rod and a scalloped pelmet across the top of the window"""+ self.wash([(x0 - 30, y0 - 12), (x1 + 30, y0 - 12), (x1 + 30, y0 - 4), (x0 - 30, y0 - 4)], 0.3)+ for x in (x0 - 34, x1 + 34):+ self.wash(ellipse_pts(x, y0 - 8, 11, 11), 0.34)+ xs = np.linspace(x0, x1, scallops * 12 + 1)+ ys = y1 - 4 + 20 * np.abs(np.sin(np.linspace(0, scallops * np.pi, xs.size)))+ poly = np.vstack([[(x0, y0)], [(x1, y0)], np.stack([xs, ys], 1)[::-1]])+ self.wash(poly, value + 0.04, value - 0.06, ((0, y0), (0, y1 + 16)))+ self.line([(x0 + 4, y0 + 14), (x1 - 4, y0 + 14)], 1.4, 0.4)+ self.line([(x0 + 4, y0 + 22), (x1 - 4, y0 + 22)], 1.4, 0.4)+ self.clip(clip, sub=[poly])++ def nightstand(self, x0, x1, top, bottom, floor_y, value=0.42):+ """a bedside table: lit top, front with a drawer and knob, tapered legs, a contact shadow"""+ self.airbrush((x0 + x1) / 2, floor_y + 2, (x1 - x0) * 0.62, 18, -0.42)+ for lx in (x0 + 16, x1 - 16):+ self.wash([(lx - 12, bottom - 2), (lx + 12, bottom - 2), (lx + 6, floor_y), (lx - 6, floor_y)], value - 0.06)+ self.wash([(x0, top + 20), (x1, top + 20), (x1, bottom), (x0, bottom)], value, value - 0.06,+ ((0, top), (0, bottom)))+ self.wash([(x0 + 18, top + 40), (x1 - 18, top + 40), (x1 - 18, top + 108), (x0 + 18, top + 108)],+ value + 0.05)+ self.line([(x0 + 26, top + 48), (x1 - 26, top + 48), (x1 - 26, top + 100), (x0 + 26, top + 100)], 1.2, 0.3,+ closed=True)+ kx = (x0 + x1) / 2+ self.wash(ellipse_pts(kx, top + 74, 10, 10), 0.82)+ self.wash([(x0 + 12, top - 16), (x1 - 12, top - 16), (x1 + 10, top), (x0 - 10, top)], 0.6, 0.66,+ ((0, top - 16), (0, top)))+ self.wash([(x0 - 10, top), (x1 + 10, top), (x1 + 10, top + 20), (x0 - 10, top + 20)], value + 0.08)+ self.line([(x0 + 4, top + 128), (x1 - 4, top + 128)], 1.2, 0.25, layout=False)+ return top - 8++ def bed(self, x0, x1, head_top, sheet_y, front_y, floor_y, wood=0.38, clip='bed'):+ """a bed seen from the foot: arched headboard with ball finials, a sheet, a quilted blanket folded back at+ the top and draped over the front, short front posts. The blanket is an overlay: cels clipped to `clip`+ (the pillow) sit behind it"""+ rng = np.random.default_rng(self._seed())+ pw = 44+ self.airbrush((x0 + x1) / 2, floor_y + 4, (x1 - x0) * 0.6, 20, -0.4)+ # headboard+ arch = ellipse_pts((x0 + x1) / 2, head_top + 60, (x1 - x0) / 2 - pw, 60, a0=np.pi, a1=2 * np.pi, n=60)+ hb = np.vstack([[(x0 + pw, sheet_y + 60)], arch, [(x1 - pw, sheet_y + 60)]])+ self.wash(hb, wood + 0.04, wood - 0.04, ((0, head_top), (0, sheet_y)))+ inset = ellipse_pts((x0 + x1) / 2, head_top + 86, (x1 - x0) / 2 - pw - 34, 46, a0=np.pi, a1=2 * np.pi, n=50)+ self.line(np.vstack([[(x0 + pw + 34, sheet_y - 6)], inset, [(x1 - pw - 34, sheet_y - 6)]]), 1.4, 0.35)+ for k in range(1, 6):+ sx = x0 + pw + 34 + (x1 - x0 - 2 * pw - 68) * k / 6+ self.line([(sx, head_top + 60 + 12 * abs(k - 3)), (sx, sheet_y - 8)], 1.2, 0.25, layout=False)+ for px in (x0, x1 - pw):+ self.wash([(px, head_top + 30), (px + pw, head_top + 30), (px + pw, sheet_y + 120), (px, sheet_y + 120)],+ wood + 0.02, wood - 0.06, ((px, 0), (px + pw, 0)))+ self.wash(ellipse_pts(px + pw / 2, head_top + 18, 22, 22), wood + 0.1)+ self.airbrush(px + pw / 2 - 7, head_top + 11, 7, 6, 0.35)+ # sheet band+ self.wash([(x0 + pw, sheet_y), (x1 - pw, sheet_y), (x1 - pw + 6, sheet_y + 60), (x0 + pw - 6, sheet_y + 60)],+ 0.9, 0.84, ((0, sheet_y), (0, sheet_y + 60)))+ # blanket: folded-back sheet hem, quilt squares, front drape+ top_y = sheet_y + 44+ fold = [(x0 + 4, top_y), (x1 - 4, top_y), (x1, top_y + 30), (x0, top_y + 30)]+ body = [(x0, top_y + 28), (x1, top_y + 28), (x1 + 22, front_y), (x0 - 22, front_y)]+ hem_x = np.linspace(x0 - 22, x1 + 22, 61)+ hem_y = front_y + 52 + 10 * np.abs(np.sin(np.linspace(0, 10 * np.pi, 61)))+ drape = np.vstack([[(x0 - 22, front_y)], [(x1 + 22, front_y)], np.stack([hem_x, hem_y], 1)[::-1]])+ self.wash(body, 0.7, 0.76, ((0, top_y), (0, front_y)))++ def quilt(d, S):+ nx, ny = 6, 4+ for i in range(nx):+ for j in range(ny):+ if (i + j) % 2:+ continue+ t0, t1 = j / ny, (j + 1) / ny+ y_a, y_b = top_y + 28 + (front_y - top_y - 28) * t0, top_y + 28 + (front_y - top_y - 28) * t1+ wa = (x1 - x0) + 44 * t0; wb = (x1 - x0) + 44 * t1+ xa0, xb0 = x0 - 22 * t0, x0 - 22 * t1+ q = [(xa0 + wa * i / nx, y_a), (xa0 + wa * (i + 1) / nx, y_a),+ (xb0 + wb * (i + 1) / nx, y_b), (xb0 + wb * i / nx, y_b)]+ d.polygon([(x * S, y * S) for x, y in q], fill=255)+ self.pattern(body, quilt, dark=0.17)+ for k in range(1, 6):+ self.line([(x0 + (x1 - x0) * k / 6, top_y + 28), (x0 - 22 + (x1 - x0 + 44) * k / 6, front_y)], 1.2, 0.3,+ layout=False)+ for k in range(1, 4):+ t = k / 4+ self.line([(x0 - 22 * t, top_y + 28 + (front_y - top_y - 28) * t), (x1 + 22 * t, top_y + 28 + (front_y - top_y - 28) * t)],+ 1.2, 0.3, layout=False)+ self.line(body, 2.0, 0.7, closed=True)+ self.wash(drape, 0.6, 0.5, ((0, front_y), (0, front_y + 60)))+ for k in range(1, 10):+ self.line([(x0 - 22 + (x1 - x0 + 44) * k / 10, front_y + 4), (x0 - 22 + (x1 - x0 + 44) * k / 10, front_y + 48)],+ 1.2, 0.25, layout=False)+ self.wash(fold, 0.92, 0.86, ((0, top_y), (0, top_y + 30)))+ # front posts+ for px in (x0 - 40, x1 + 4):+ self.wash([(px, front_y - 30), (px + 36, front_y - 30), (px + 32, floor_y), (px + 4, floor_y)],+ wood + 0.02, wood - 0.08, ((px, 0), (px + 36, 0)))+ self.wash(ellipse_pts(px + 18, front_y - 42, 19, 19), wood + 0.1)+ self.airbrush(px + 12, front_y - 48, 6, 5, 0.35)+ self.clip(clip, full=True, sub=[body, fold, drape])+ return dict(top=top_y, front=front_y)++ def rug(self, cx, cy, rx, ry, rings=5):+ """an oval braided rug: concentric bands of alternating grey with braid ticks along each band"""+ self.airbrush(cx, cy + ry * 0.2, rx * 1.02, ry * 1.1, -0.22)+ vals = [0.5, 0.7, 0.42, 0.66, 0.78]+ for k in range(rings):+ f = 1 - k / rings+ self.wash(ellipse_pts(cx, cy, rx * f, ry * f), vals[k % len(vals)], line=1.6, dark=0.5)+ n = int(60 * f) + 12+ for a in np.linspace(0, 2 * np.pi, n, endpoint=False):+ fm = f - 0.5 / rings+ px, py = cx + np.cos(a) * rx * fm, cy + np.sin(a) * ry * fm+ tx, ty = -np.sin(a) * rx, np.cos(a) * ry+ tl = np.hypot(tx, ty)+ self.line([(px - tx / tl * 5 - 2, py - ty / tl * 2 - 3), (px + tx / tl * 5 + 2, py + ty / tl * 2 + 3)],+ 1.1, 0.22, layout=False)++ def sampler(self, x0, y0, x1, y1, lines, value=0.9):+ """a framed embroidered motto hung on a nail: dark moulding, light cloth, lettering, a stitched border"""+ cx = (x0 + x1) / 2+ self.line([(x0 + 40, y0 + 4), (cx, y0 - 50), (x1 - 40, y0 + 4)], 1.4, 0.55)+ self.wash(ellipse_pts(cx, y0 - 50, 5, 5), 0.3)+ self.airbrush(cx + 10, y1 + 8, (x1 - x0) * 0.5, 10, -0.25)+ self.wash([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], 0.34, 0.28, ((x0, y0), (x1, y1)))+ b = 18+ self.wash([(x0 + b, y0 + b), (x1 - b, y0 + b), (x1 - b, y1 - b), (x0 + b, y1 - b)], value)+ self.line([(x0 + b + 9, y0 + b + 9), (x1 - b - 9, y0 + b + 9), (x1 - b - 9, y1 - b - 9), (x0 + b + 9, y1 - b - 9)],+ 1.0, 0.35, closed=True, layout=False)+ S = self.ss; n = len(lines)+ x0i, y0i, x1i, y1i = x0 + b + 18, y0 + b + 14, x1 - b - 18, y1 - b - 14+ size = min((y1i - y0i) / n * 0.86, 999)+ im = Image.new('L', (self.W * S, self.H * S), 0); d = ImageDraw.Draw(im)+ for i, s in enumerate(lines):+ f = slab_font(size * S)+ while f.getlength(s) > (x1i - x0i) * S and size > 8:+ size *= 0.94; f = slab_font(size * S)+ d.text((cx * S, (y0i + (y1i - y0i) * (i + 0.5) / n) * S), s, font=f, fill=255, anchor='mm')+ m = np.asarray(im, np.float32) / 255+ self.bg *= 1 - 0.62 * m+ ImageDraw.Draw(self.layout).bitmap((0, 0), ImageChops.subtract(im.filter(ImageFilter.MaxFilter(3)), im), fill=255)++ # ================================================================ cels: primitives+ def _add(self, **p):+ p.setdefault('clip', self._clip)+ p.setdefault('seed', self._seed())+ self.prims.append(p)+ self._cache = None+ return p++ _clip = None++ def using(self, clip):+ """send the following cels to a clip mask (None = no clip). Use as: rh.using('window'); ...; rh.using(None)"""+ self._clip = clip++ def shape(self, pts, fill=WHITE, ow=None, closed=True):+ """a closed inked-and-painted shape. ow = ink width (outside the fill); fill None = line only"""+ return self._add(k='shape', pts=np.asarray(pts, np.float32), fill=fill,+ ow=self.ink_w if ow is None else ow, closed=closed)++ def union(self, subs, fill=WHITE, ow=None):+ """several pieces painted as one (no ink between them): subs = [('poly', pts) | ('cap', pts, radius)]"""+ return self._add(k='union', subs=subs, fill=fill, ow=self.ink_w if ow is None else ow)++ def stroke(self, pts, width=4.0, taper=(0.0, 0.0), value=INK, effect=False):+ """an inked line: width px, tapering over the first / last fraction of its length"""+ return self._add(k='stroke', pts=np.asarray(pts, np.float32), w=width, taper=taper, value=value, fx=effect)++ def hose(self, pts, width, fill=BLACK, ow=None):+ """a rubber-hose limb along pts: a tube of constant width, no elbow, no knee"""+ return self._add(k='hose', pts=np.asarray(pts, np.float32), w=width, fill=fill,+ ow=self.ink_w * 0.8 if ow is None else ow)++ def guide(self, pts, closed=False):+ """a construction line that only shows in the pencil rough"""+ return self._add(k='guide', pts=np.asarray(pts, np.float32), closed=closed)++ def shadow(self, cx, cy, rx, ry, amount=0.35):+ """a painted cast shadow (grey, soft-edged) under a character"""+ return self._add(k='shadow', pts=ellipse_pts(cx, cy, rx, ry), a=amount, clip=None)++ def text(self, s, x, y, size, fill=WHITE, ow=None, rot=0.0, font=None, effect=True):+ """one run of inked lettering centred at (x, y), rotated rot degrees (counter-clockwise)"""+ return self._add(k='text', s=s, x=x, y=y, size=size, fill=fill, ow=self.ink_w if ow is None else ow,+ rot=rot, font=font, fx=effect)++ # ================================================================ cels: the rubber-hose vocabulary+ def glove(self, x, y, angle, size, pose='open', flip=1, ow=None):+ """a white four-fingered cartoon glove. (x, y) = wrist (where the hose goes in), angle = direction the+ fingers point (radians, screen), size ~ palm-to-tip length / 1.6. pose: open | point | fist | palm (stop).+ flip=-1 mirrors it (left / right hand: which side the thumb is on)."""+ ow = self.ink_w * 0.9 if ow is None else ow+ F = Frame(x, y, size, angle + np.pi / 2, flip) # local: -y = toward the fingertips+ palm_c = (0.0, -0.78)+ subs = [('poly', F(ellipse_pts(*palm_c, 0.5, 0.44)))]+ seps = []+ if pose in ('open', 'palm'):+ spread = [-0.62, -0.2, 0.2, 0.58] if pose == 'open' else [-0.3, -0.1, 0.1, 0.3]+ lens = [0.78, 0.98, 0.94, 0.74]+ prev = None+ for a, L in zip(spread, lens):+ d = np.array([np.sin(a), -np.cos(a)])+ b = np.array(palm_c) + d * 0.2; t = np.array(palm_c) + d * (0.38 + L * 0.62)+ subs.append(('cap', F([b, t]), 0.155 * size))+ if prev is not None and pose == 'palm':+ m = (prev + t) / 2+ seps.append(F([m, m + (np.array(palm_c) - m) * 0.35]))+ prev = t+ subs.append(('cap', F([(-0.3, -0.62), (-0.78, -0.98)]), 0.16 * size))+ elif pose == 'point':+ subs.append(('cap', F([(0.04, -0.9), (0.06, -1.82)]), 0.155 * size))+ for k, (bx, by) in enumerate([(0.2, -1.04), (0.32, -0.86), (0.36, -0.66)]):+ subs.append(('cap', F([(bx - 0.08, by), (bx + 0.08, by + 0.04)]), 0.15 * size))+ subs.append(('cap', F([(-0.34, -0.66), (-0.08, -1.02)]), 0.15 * size))+ elif pose == 'fist':+ subs = [('poly', F(ellipse_pts(0.0, -0.78, 0.5, 0.42)))]+ for bx in (-0.3, -0.1, 0.1, 0.3): # four curled fingers: a scalloped knuckle edge+ subs.append(('cap', F([(bx, -1.0), (bx, -1.1)]), 0.135 * size))+ self.union(subs, WHITE, ow)+ if pose == 'open':+ for sx in (-0.16, 0.0, 0.16):+ self.stroke(F([(sx, -0.62), (sx * 1.15, -0.92)]), ow * 0.55, (0.3, 0.3))+ elif pose == 'point':+ for k in range(1, 3):+ self.stroke(F([(-0.32 + 0.22 * k, -1.02), (-0.3 + 0.22 * k, -0.9)]), ow * 0.5, (0.3, 0.3))+ elif pose == 'fist':+ for sx in (-0.2, 0.0, 0.2):+ self.stroke(F([(sx, -1.08), (sx, -0.94)]), ow * 0.5, (0.1, 0.5))+ self.union([('cap', F([(-0.46, -0.76), (-0.16, -0.88)]), 0.13 * size)], WHITE, ow * 0.9)+ for s in seps:+ self.stroke(s, ow * 0.5, (0.2, 0.4))+ cuff = np.vstack([[(0.32, -0.36), (-0.32, -0.36)], ellipse_pts(0, 0.06, 0.5, 0.12, a0=np.pi, a1=0, n=20)])+ self.shape(F(cuff), WHITE, ow)+ self.stroke(F(ellipse_pts(0, 0.06, 0.5, 0.12, a0=np.pi, a1=2 * np.pi, n=20)), ow * 0.6)+ for sx in (-0.18, 0.16):+ self.stroke(F([(sx * 1.3, 0.0), (sx, -0.24)]), ow * 0.45, (0.2, 0.5))+ return F++ def shoe(self, x, y, size, facing=1, tilt=0.0, ow=None):+ """a big oval cartoon shoe; (x, y) = the ankle, facing +-1, tilt rotates it (toe up < 0 < toe down)"""+ ow = self.ink_w if ow is None else ow+ F = Frame(x, y, size, tilt * facing, facing)+ toe = ellipse_pts(0.55, 0.3, 0.66, 0.42); heel = ellipse_pts(-0.22, 0.38, 0.4, 0.34)+ sole = np.vstack([ellipse_pts(0.5, 0.62, 0.78, 0.16, a0=0, a1=np.pi, n=30), [(-0.6, 0.68), (-0.6, 0.5)]])+ self.shape(F(sole), DARK, ow)+ self.union([('poly', F(toe)), ('poly', F(heel))], BLACK, ow)+ self.shape(F(ellipse_pts(0.72, 0.12, 0.26, 0.09, rot=-0.25)), WHITE, 0)+ self.shape(F(ellipse_pts(0.36, 0.06, 0.07, 0.05)), WHITE, 0)+ return F++ def pie_eye(self, cx, cy, rx, ry, look=(0.0, 0.0), wedge=-0.9, lid=0.0, face=WHITE, rot=0.0, ow=None):+ """a white oval eye with a black pie-cut pupil (a wedge cut out toward `wedge`, radians). look = (x, y) in+ -1..1 moves the pupil; lid 0..1 closes a top lid painted in the face colour"""+ ow = self.ink_w * 0.75 if ow is None else ow+ self.shape(ellipse_pts(cx, cy, rx, ry, rot), WHITE, ow)+ px = cx + look[0] * rx * 0.36; py = cy + look[1] * ry * 0.3 + ry * 0.1+ prx, pry = rx * 0.6, ry * 0.66+ half = 0.42+ t = np.linspace(wedge + half, wedge + 2 * np.pi - half, 60)+ tip = (px + np.cos(wedge) * prx * 0.12, py + np.sin(wedge) * pry * 0.12)+ arc = np.stack([px + np.cos(t) * prx, py + np.sin(t) * pry], 1)+ # keep the pupil inside the eye white+ ex, ey = (arc[:, 0] - cx) / (rx * 0.94), (arc[:, 1] - cy) / (ry * 0.94)+ r = np.maximum(1.0, np.hypot(ex, ey))+ arc = np.stack([cx + ex / r * rx * 0.94, cy + ey / r * ry * 0.94], 1)+ self.shape(np.vstack([[tip], arc]), BLACK, 0)+ if lid > 0:+ yl = cy - ry + 2 * ry * lid+ a = np.arcsin(np.clip((yl - cy) / ry, -1, 1))+ arc2 = ellipse_pts(cx, cy, rx * 1.02, ry * 1.02, a0=np.pi - a, a1=2 * np.pi + a, n=40)+ self.shape(arc2, face, 0)+ self.stroke(np.stack([np.linspace(arc2[0, 0], arc2[-1, 0], 12), np.full(12, yl)], 1), ow * 1.1)+ self.shape(ellipse_pts(cx, cy, rx, ry, rot), None, ow)++ def grin(self, F, x0, x1, y_top, y_bot, curve=0.06, tongue=MID, ow=None):+ """a wide open laughing mouth in frame F (local coords): smiling upper lip, deep lower jaw, a tongue"""+ ow = self.ink_w * 0.8 if ow is None else ow+ xs = np.linspace(x0, x1, 30)+ u = (xs - x0) / (x1 - x0)+ top = y_top + curve * (1 - (2 * u - 1) ** 2)+ bot = y_top + (y_bot - y_top) * np.sqrt(np.clip(1 - (2 * u - 1) ** 2, 0, 1)) ** 0.9 + curve * 0.3+ mouth = np.vstack([np.stack([xs, top], 1), np.stack([xs, bot], 1)[::-1]])+ self.shape(F(mouth), BLACK, ow)+ if tongue is not None:+ k = (u > 0.22) & (u < 0.82)+ bl = np.stack([xs[k], bot[k] - 0.012], 1)+ tx = np.linspace(xs[k][-1], xs[k][0], 20)+ ty = y_bot - (y_bot - y_top) * 0.4 + 0.035 * np.abs(np.sin(np.linspace(0, 2 * np.pi, 20)))+ self.shape(F(np.vstack([bl, np.stack([tx, ty], 1)])), tongue, 0)+ self.stroke(F([((x0 + x1) / 2 + 0.01, y_bot - (y_bot - y_top) * 0.3), ((x0 + x1) / 2 + 0.02, y_bot - 0.06)]),+ ow * 0.45, (0.3, 0.3))+ for xe, sgn in ((x0, -1), (x1, 1)):+ c = F([(xe + sgn * 0.02, y_top - 0.06), (xe + sgn * 0.07, y_top + 0.0), (xe + sgn * 0.06, y_top + 0.07)])+ self.stroke(c, ow * 0.8, (0.3, 0.3))+ return mouth++ def star(self, x, y, r, points=5, rot=0.0, fill=WHITE, ow=None):+ """a little impact star"""+ t = np.linspace(0, 2 * np.pi, points * 2, endpoint=False) + rot - np.pi / 2+ rr = np.where(np.arange(points * 2) % 2 == 0, r, r * 0.45)+ return self.shape(np.stack([x + np.cos(t) * rr, y + np.sin(t) * rr], 1), fill,+ self.ink_w * 0.7 if ow is None else ow)++ # ================================================================ cels: characters+ def alarm_clock(self, cx, cy, r, tilt=0.0, look=(0.6, -0.1), time=(7, 0), arms=(), legs=(), ring=True):+ """a twin-bell alarm clock that has jumped up to ring: black drum body, white dial with a face (pie-cut+ eyes, open grin), hands at `time`, two bells and a striker; rubber-hose arms and legs.+ arms: [dict(at=(x, y) wrist, side=-1|1, pose, angle, bend)], legs: [dict(at=(x, y) ankle, side, facing,+ tilt, bend)]. Returns the body Frame (local unit = r)."""+ F = Frame(cx, cy, r, tilt)+ ow = self.ink_w+ self.guide(F(ellipse_pts(0, 0, 1, 1)), True)+ self.guide(F([(0, -1.25), (0, 1.1)])); self.guide(F([(-1.05, -0.05), (1.05, -0.05)]))+ self.guide(F([(-0.9, 1.5), (-0.2, 0.6), (0.3, -0.6), (0.2, -1.6)]))+ for leg in legs:+ side = leg.get('side', 1)+ hip = F.p(0.36 * side, 0.86)+ path = hose_path(hip, leg['at'], leg.get('bend', 0.0), leg.get('bend2'))+ self.hose(path, r * 0.13)+ self.shoe(leg['at'][0], leg['at'][1], r * leg.get('shoe', 0.5), leg.get('facing', side), leg.get('tilt', 0.0))+ for arm in arms:+ side = arm.get('side', 1)+ sh = F.p(0.96 * side, 0.12)+ path = hose_path(sh, arm['at'], arm.get('bend', 0.0), arm.get('bend2'))+ self.hose(path, r * 0.105)+ d = path[-1] - path[-4]+ ang = arm.get('angle', float(np.arctan2(d[1], d[0])))+ self.glove(arm['at'][0], arm['at'][1], ang, r * arm.get('glove', 0.44), arm.get('pose', 'open'),+ arm.get('flip', side))+ # bells, posts and striker (behind the drum)+ bells = []+ for side in (-1, 1):+ a = side * 0.66+ bc = F.p(np.sin(a) * 1.1, -np.cos(a) * 1.1)+ post0 = F.p(np.sin(a) * 0.8, -np.cos(a) * 0.8)+ self.hose(np.stack([np.linspace(post0[0], bc[0], 8), np.linspace(post0[1], bc[1], 8)], 1), r * 0.07, DARK,+ ow * 0.7)+ B = Frame(bc[0], bc[1], r * 0.4, tilt + a)+ dome = np.vstack([[(-1.1, 0.2)], ellipse_pts(0, 0.05, 1.0, 1.05, a0=np.pi, a1=2 * np.pi, n=50), [(1.1, 0.2)],+ ellipse_pts(0, 0.2, 1.1, 0.16, a0=0, a1=np.pi, n=20)])+ self.shape(B(dome), LIGHT, ow)+ self.shape(B(np.vstack([ellipse_pts(0, 0.2, 1.1, 0.16, a0=0, a1=np.pi, n=20),+ ellipse_pts(0, 0.02, 1.02, 0.13, a0=np.pi, a1=0, n=20)])), DARK, ow * 0.6)+ self.shape(B(ellipse_pts(-0.45, -0.5, 0.14, 0.36, rot=0.6)), WHITE, 0)+ self.shape(B(ellipse_pts(0, -1.08, 0.2, 0.16)), DARK, ow * 0.7)+ bells.append((bc, a))+ top = F.p(0, -0.96)+ for k, (a, fill) in enumerate(((-0.42, DARK), (0.42, None))):+ tip = F.p(np.sin(a) * 1.5, -0.96 - np.cos(a) * 0.5)+ if fill is None:+ self.stroke(np.stack([np.linspace(top[0], tip[0], 6), np.linspace(top[1], tip[1], 6)], 1), ow * 0.5)+ self.shape(ellipse_pts(tip[0], tip[1], r * 0.09, r * 0.09), None, ow * 0.5)+ else:+ self.hose(np.stack([np.linspace(top[0], tip[0], 6), np.linspace(top[1], tip[1], 6)], 1), r * 0.04, DARK,+ ow * 0.6)+ self.shape(ellipse_pts(tip[0], tip[1], r * 0.1, r * 0.1), DARK, ow * 0.7)+ sw = F([(np.sin(a) * 1.62, -0.96 - np.cos(a) * 0.62) for a in np.linspace(-0.5, 0.5, 14)])+ self.stroke(sw, ow * 0.45, (0.4, 0.4))+ # drum, shine, dial+ self.shape(F(ellipse_pts(0, 0, 1, 1)), BLACK, ow)+ self.shape(F(np.vstack([ellipse_pts(0, 0, 0.95, 0.95, a0=3.55, a1=4.35, n=16),+ ellipse_pts(0, 0, 0.86, 0.86, a0=4.35, a1=3.55, n=16)])), WHITE, 0)+ self.shape(F(ellipse_pts(0.62, 0.62, 0.05, 0.05)), WHITE, 0)+ self.shape(F(ellipse_pts(0, 0, 0.79, 0.79)), WHITE, ow * 0.8)+ for k in range(12):+ if k in (0, 3, 9, 5, 6, 7):+ continue+ a = k / 12 * 2 * np.pi+ self.stroke(F([(np.sin(a) * 0.66, -np.cos(a) * 0.66), (np.sin(a) * 0.73, -np.cos(a) * 0.73)]), ow * 0.6)+ fsz = r * 0.17+ for s, (lx, ly) in (('12', (0, -0.62)), ('3', (0.64, -0.02)), ('9', (-0.64, -0.02))):+ p = F.p(lx, ly)+ self.text(s, p[0], p[1], fsz, INK, 0, rot=-np.degrees(tilt), font=slab_font, effect=False)+ # face: brows, eyes, grin, then the hands on top+ for sgn in (-1, 1):+ ex = 0.27 * sgn+ self.stroke(F([(ex - 0.13, -0.5 - 0.04 * sgn * 0), (ex, -0.58), (ex + 0.13, -0.52)]), ow * 1.1, (0.3, 0.3))+ for sgn in (-1, 1):+ p = F.p(0.27 * sgn, -0.21)+ self.pie_eye(p[0], p[1], r * 0.15, r * 0.22, look=look, rot=tilt)+ self.grin(F, -0.42, 0.44, 0.24, 0.66, curve=0.07)+ hm = (time[0] % 12 + time[1] / 60) / 12 * 2 * np.pi; mm = time[1] / 60 * 2 * np.pi+ for a, L, w in ((mm, 0.5, 0.05), (hm, 0.3, 0.07)):+ d = np.array([np.sin(a), -np.cos(a)]); n = np.array([-d[1], d[0]])+ hand = [n * w, d * L, -n * w, -d * 0.08]+ self.shape(F(hand), BLACK, 0)+ self.shape(F(ellipse_pts(0, 0, 0.065, 0.065)), BLACK, 0)+ self.shape(F(ellipse_pts(-0.015, -0.015, 0.02, 0.02)), WHITE, 0)+ self.bells = bells+ return F++ def sun(self, cx, cy, r, mood='yawn', arms=(), rays=12, ray_style='wavy', clip=None):+ """a cartoon sun with a face (sleepy lids, a yawn) and stretching rubber-hose arms. ray_style 'wavy' =+ inked S-curved rays with a pale corona, 'spiky' = a crown of pointed rays"""+ prev = self._clip+ if clip is not None:+ self._clip = clip+ F = Frame(cx, cy, r)+ ow = self.ink_w * 0.9+ self.guide(F(ellipse_pts(0, 0, 1, 1)), True)+ for arm in arms:+ side = arm.get('side', 1)+ sh = F.p(0.92 * side, 0.05)+ path = hose_path(sh, arm['at'], arm.get('bend', 0.0), arm.get('bend2'))+ self.hose(path, r * 0.12)+ d = path[-1] - path[-4]+ self.glove(arm['at'][0], arm['at'][1], float(np.arctan2(d[1], d[0])), r * 0.42, arm.get('pose', 'fist'),+ arm.get('flip', side))+ if ray_style == 'spiky':+ t = np.linspace(0, 2 * np.pi, rays * 2 * 12, endpoint=False)+ tri = 1 - np.abs(((t * rays / (2 * np.pi)) % 1) * 2 - 1)+ rr = 1.18 + 0.42 * tri ** 1.7 + 0.03 * np.sin(t * rays * 3)+ rr = np.where((np.arange(t.size) // 24) % 2 == 0, rr, 1.18 + (rr - 1.18) * 0.7)+ self.shape(F(np.stack([np.cos(t) * rr, np.sin(t) * rr], 1)), LIGHT, ow)+ else:+ t = np.linspace(0, 2 * np.pi, rays * 20, endpoint=False)+ rr = 1.1 + 0.11 * np.abs(np.sin(t * rays / 2)) ** 0.6 # a scalloped corona+ self.shape(F(np.stack([np.cos(t) * rr, np.sin(t) * rr], 1)), LIGHT, ow * 0.9)+ for i in range(rays):+ a = (i + 0.5) / rays * 2 * np.pi # a short ray in every notch+ L = 0.34 if i % 2 == 0 else 0.22+ rad = np.array([1.3, 1.3 + L])+ pts = np.stack([np.cos(a) * rad, np.sin(a) * rad], 1)+ self.stroke(F(pts), ow * (2.2 if i % 2 == 0 else 1.8), (0.15, 0.3))+ self.shape(F(ellipse_pts(0, 0, 1, 1)), WHITE, ow)+ for sgn in (-1, 1):+ p = F.p(0.33 * sgn, -0.2)+ self.pie_eye(p[0], p[1], r * 0.16, r * 0.2, look=(0.1 * sgn, -0.5), lid=0.5, face=WHITE)+ self.stroke(F([(0.33 * sgn - 0.15, -0.5), (0.33 * sgn, -0.55), (0.33 * sgn + 0.15, -0.48)]), ow, (0.3, 0.3))+ mouth = ellipse_pts(0, 0.36, 0.2, 0.24)+ self.shape(F(mouth), BLACK, ow * 0.8)+ self.shape(F(ellipse_pts(0, 0.48, 0.13, 0.08)), MID, 0)+ for sgn in (-1, 1):+ self.shape(F(ellipse_pts(0.58 * sgn, 0.2, 0.12, 0.07)), PALE, 0)+ self._clip = prev+ return F++ def pillow(self, cx, cy, w, h, tilt=0.0, arm=None, clip=None):+ """a sleeping pillow: pinched corners, closed eyes with lashes, a snoring 'o', a striped night-cap, and+ one rubber-hose arm out of the bedclothes holding up a glove ("five more minutes")"""+ prev = self._clip+ if clip is not None:+ self._clip = clip+ F = Frame(cx, cy, 1.0, tilt)+ ow = self.ink_w+ if arm:+ sh = F.p(-w * 0.44, h * 0.22)+ path = hose_path(sh, arm['at'], arm.get('bend', 0.0), arm.get('bend2'))+ self.hose(path, h * 0.12)+ d = path[-1] - path[-4]+ self.glove(arm['at'][0], arm['at'][1], arm.get('angle', float(np.arctan2(d[1], d[0]))), h * 0.4,+ arm.get('pose', 'palm'), arm.get('flip', 1))+ t = np.linspace(0, 2 * np.pi, 160, endpoint=False)+ ct, st = np.cos(t), np.sin(t)+ x = np.sign(ct) * np.abs(ct) ** 0.72 * w / 2; y = np.sign(st) * np.abs(st) ** 0.72 * h / 2+ pinch = 1 - 0.13 * (np.cos(4 * t) + 1) / 2 + 0.06 * (1 - np.cos(4 * t)) / 2+ body = np.stack([x * pinch, y * pinch], 1)+ self.guide(F(ellipse_pts(0, 0, w / 2, h / 2)), True)+ self.shape(F(body), WHITE, ow)+ for sx in (-1, 1):+ for sy in (-1, 1):+ self.stroke(F([(sx * w * 0.42, sy * h * 0.36), (sx * w * 0.34, sy * h * 0.26)]), ow * 0.5, (0.2, 0.5))+ for sgn in (-1, 1):+ ex = w * 0.17 * sgn+ arc = ellipse_pts(ex, -h * 0.02, w * 0.075, h * 0.07, a0=0.15, a1=np.pi - 0.15, n=20)+ self.stroke(F(arc), ow * 1.0, (0.15, 0.15))+ for a in (0.7, 1.57, 2.4):+ p0 = (ex + np.cos(a) * w * 0.075, -h * 0.02 + np.sin(a) * h * 0.07)+ self.stroke(F([p0, (p0[0] + np.cos(a) * w * 0.035, p0[1] + np.sin(a) * h * 0.06)]), ow * 0.5)+ self.shape(F(ellipse_pts(w * 0.03, h * 0.22, w * 0.045, h * 0.075)), BLACK, ow * 0.6)+ for sgn in (-1, 1):+ self.shape(F(ellipse_pts(w * 0.3 * sgn, h * 0.15, w * 0.05, h * 0.04)), PALE, 0)+ # night-cap: a floppy striped cone over the right corner+ spine = np.array([(w * 0.33, -h * 0.36), (w * 0.47, -h * 0.82), (w * 0.64, -h * 0.84), (w * 0.72, -h * 0.5),+ (w * 0.72, -h * 0.22)], np.float32)+ from core import spline+ sp = spline(spine, 10)+ n = len(sp)+ hw = w * (0.19 * (1 - np.linspace(0, 1, n)) ** 0.9 + 0.016)+ tg = np.gradient(sp, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6+ nr = np.stack([-tg[:, 1], tg[:, 0]], 1)+ L_, R_ = sp + nr * hw[:, None], sp - nr * hw[:, None]+ brim_c = sp[0]+ seg = max(2, n // 7)+ for i in range(0, n - 1, seg):+ j = min(n - 1, i + seg)+ q = np.vstack([L_[i:j + 1], R_[i:j + 1][::-1]])+ self.shape(F(q), DARK if (i // seg) % 2 == 0 else WHITE, 0)+ self.shape(F(np.vstack([L_, R_[::-1]])), None, ow)+ t0 = tg[0]; ext = (L_[0] - R_[0]) * 0.06+ band = np.vstack([L_[0] + ext - t0 * h * 0.06, R_[0] - ext - t0 * h * 0.06,+ R_[0] - ext + t0 * h * 0.13, L_[0] + ext + t0 * h * 0.13])+ self.shape(F(band), LIGHT, ow * 0.8)+ tip = sp[-1]+ self.shape(F(ellipse_pts(tip[0], tip[1] + h * 0.06, w * 0.05, w * 0.05)), WHITE, ow * 0.8)+ self._clip = prev+ return F++ def slipper(self, x, y, size, facing=1, tilt=0.0, mood='happy'):+ """a fuzzy bedroom slipper that dances: sole, domed upper, pom-pom, pie-cut eyes and a smile"""+ F = Frame(x, y, size, tilt * facing, facing)+ ow = self.ink_w * 0.85+ self.shape(F(ellipse_pts(0.0, 0.08, 0.66, 0.2)), DARK, ow)+ self.shape(F(ellipse_pts(-0.2, 0.03, 0.42, 0.15)), LIGHT, ow * 0.8)+ self.shape(F(ellipse_pts(-0.22, 0.05, 0.32, 0.09)), MID, ow * 0.5)+ toe = np.vstack([ellipse_pts(0.3, 0.1, 0.38, 0.44, a0=np.pi, a1=2 * np.pi, n=40),+ ellipse_pts(0.3, 0.1, 0.38, 0.1, a0=0, a1=np.pi, n=20)])+ self.shape(F(toe), LIGHT, ow)+ for k in range(8):+ a = np.pi + 0.25 + k * 0.37+ p = (0.3 + np.cos(a) * 0.32, 0.1 + np.sin(a) * 0.36)+ self.stroke(F([p, (p[0] + 0.02, p[1] + 0.05)]), ow * 0.35)+ self.shape(F(ellipse_pts(0.52, -0.3, 0.12, 0.11)), WHITE, ow * 0.8)+ for ex in (0.2, 0.4):+ p = F.p(ex, -0.1)+ self.pie_eye(p[0], p[1], size * 0.065, size * 0.095, look=(0.5, -0.3), ow=ow * 0.6)+ self.stroke(F(ellipse_pts(0.31, 0.04, 0.09, 0.05, a0=0.2, a1=np.pi - 0.2, n=12)), ow * 0.7, (0.2, 0.2))+ return F++ # ================================================================ cels: effects+ def vibration(self, cx, cy, r, a0, a1, n=3, gap=None, width=None):+ """concentric shake arcs (')))') outside a ringing thing, between angles a0..a1"""+ gap = gap or r * 0.28; width = width or self.ink_w * 0.9+ for k in range(n):+ rr = r + gap * (k + 1)+ self.stroke(ellipse_pts(cx, cy, rr, rr, a0=a0 + 0.05 * k, a1=a1 - 0.05 * k, n=24), width, (0.3, 0.3), effect=True)++ def speed_lines(self, pts_list, width=None):+ for P in pts_list:+ self.stroke(P, width or self.ink_w * 0.9, (0.0, 0.7), effect=True)++ def lettering(self, s, path, size, fill=WHITE, ow=None, wobble=10.0, bounce=0.12, spacing=0.9):+ """bouncing slab-serif lettering along a curve (spline through `path`), each letter tilted the other way"""+ from core import spline+ sp = spline(np.asarray(path, np.float32), 30)+ seg = np.hypot(*np.diff(sp, axis=0).T); cum = np.concatenate([[0], np.cumsum(seg)])+ f = slab_font(size)+ adv = [f.getlength(ch) * spacing + size * 0.06 for ch in s]+ total = sum(adv); start = (cum[-1] - total) / 2+ pos = start+ for i, ch in enumerate(s):+ u = pos + adv[i] / 2+ x = float(np.interp(u, cum, sp[:, 0])); y = float(np.interp(u, cum, sp[:, 1]))+ j = min(len(sp) - 2, int(np.searchsorted(cum, u)))+ ang = np.degrees(np.arctan2(sp[j + 1, 1] - sp[j, 1], sp[j + 1, 0] - sp[j, 0]))+ rot = -ang + (wobble if i % 2 else -wobble)+ dy = size * bounce * (1 if i % 2 else -1)+ sz = size * (1.0 + 0.08 * ((i % 3) - 1))+ self.text(ch, x, y + dy, sz, fill, ow, rot)+ pos += adv[i]++ def zzz(self, x, y, size, n=3, dx=46, dy=-52):+ for k in range(n):+ self.text('Z', x + dx * k, y + dy * k, size * (1 + 0.32 * k), WHITE, self.ink_w * 0.8, rot=12 - 10 * k)++ # ================================================================ rendering the cels+ def _stamp(self, draws, vals, P, rad, closed=False, wobble=0.0, seed=0):+ S = self.ss+ Q, u, L = _resample(P * S, max(0.7, float(np.min(rad)) * S * 0.22), closed)+ n = len(Q)+ if np.ndim(rad):+ r = np.interp(u, np.linspace(0, 1, len(rad)), rad) * S+ else:+ r = np.full(n, rad * S, np.float32)+ if wobble and n > 2:+ r = r * (1 + wobble * fbm1d(n, max(4.0, n / max(1.0, L / (70.0 * S))), 3, seed))+ for (x, y), rr in zip(Q, r):+ if rr < 0.4:+ continue+ bb = [x - rr, y - rr, x + rr, y + rr]+ for d, v in zip(draws, vals):+ d.ellipse(bb, fill=v)++ def _poly(self, draws, vals, P):+ S = self.ss+ Q = [(float(x * S), float(y * S)) for x, y in P]+ for d, v in zip(draws, vals):+ d.polygon(Q, fill=v)++ def _draw(self, p, imgs, shadow_d):+ """draw one primitive into the (val, alpha, line) cel images"""+ D = [ImageDraw.Draw(im) for im in imgs]+ k = p['k']; inkv = int(INK * 255)+ if k == 'guide':+ return+ if k == 'shadow':+ self._poly([shadow_d], [int(255 * p['a'])], p['pts'])+ return+ if k == 'shape':+ P, fill, ow = p['pts'], p['fill'], p['ow']+ if fill is None:+ self._stamp(D, [inkv, 255, 255], P, ow / 2, closed=p['closed'], wobble=0.1, seed=p['seed'])+ return+ if ow > 0:+ self._poly(D, [inkv, 255, 255], P)+ self._stamp(D, [inkv, 255, 255], P, ow, closed=True, wobble=0.1, seed=p['seed'])+ self._poly(D, [int(fill * 255), 255, 0], P)+ if ow <= 0:+ self._stamp(D[2:], [255], P, 0.9, closed=True)+ return+ if k == 'union':+ fill, ow = p['fill'], p['ow']+ for i, sub in enumerate(p['subs']):+ if sub[0] == 'poly':+ self._poly(D, [inkv, 255, 255], sub[1])+ self._stamp(D, [inkv, 255, 255], sub[1], ow, closed=True, wobble=0.1, seed=p['seed'] + i)+ else:+ self._stamp(D, [inkv, 255, 255], sub[1], sub[2] + ow)+ for sub in p['subs']:+ if sub[0] == 'poly':+ self._poly(D, [int(fill * 255), 255, 0], sub[1])+ else:+ self._stamp(D, [int(fill * 255), 255, 0], sub[1], sub[2])+ return+ if k == 'hose':+ P, w, ow = p['pts'], p['w'], p['ow']+ self._stamp(D, [inkv, 255, 255], P, w / 2 + ow, wobble=0.05, seed=p['seed'])+ self._stamp(D, [int(p['fill'] * 255), 255, 0], P, w / 2)+ return+ if k == 'stroke':+ P, w = p['pts'], p['w']+ t0, t1 = p['taper']+ u = np.linspace(0, 1, 64)+ prof = np.ones_like(u)+ if t0 > 0:+ prof = np.minimum(prof, 0.25 + 0.75 * np.clip(u / t0, 0, 1))+ if t1 > 0:+ prof = np.minimum(prof, 0.25 + 0.75 * np.clip((1 - u) / t1, 0, 1))+ self._stamp(D, [int(p['value'] * 255), 255, 255], P, prof * w / 2, wobble=0.08, seed=p['seed'])+ return+ if k == 'text':+ S = self.ss+ fnt = (p['font'] or slab_font)(p['size'] * S)+ sw = int(round(p['ow'] * S))+ pad = sw + int(p['size'] * S * 0.3)+ bx = fnt.getbbox(p['s'], anchor='mm')+ w_, h_ = bx[2] - bx[0] + 2 * pad, bx[3] - bx[1] + 2 * pad+ outer = Image.new('L', (w_, h_), 0); inner = Image.new('L', (w_, h_), 0)+ c = (w_ / 2 - (bx[0] + bx[2]) / 2, h_ / 2 - (bx[1] + bx[3]) / 2)+ ImageDraw.Draw(outer).text(c, p['s'], font=fnt, fill=255, anchor='mm', stroke_width=sw, stroke_fill=255)+ ImageDraw.Draw(inner).text(c, p['s'], font=fnt, fill=255, anchor='mm')+ if p['rot']:+ outer = outer.rotate(p['rot'], Image.BICUBIC, expand=True)+ inner = inner.rotate(p['rot'], Image.BICUBIC, expand=True)+ ox, oy = int(round(p['x'] * S - outer.width / 2)), int(round(p['y'] * S - outer.height / 2))+ val, al, ln = imgs+ val.paste(inkv, (ox, oy), outer); al.paste(255, (ox, oy), outer); ln.paste(255, (ox, oy), outer)+ if sw > 0:+ val.paste(int(p['fill'] * 255), (ox, oy), inner); ln.paste(0, (ox, oy), inner)+ else:+ val.paste(int(p['fill'] * 255), (ox, oy), inner)+ return++ def _render_paint(self):+ key = ('paint', len(self.prims))+ if self._cache and self._cache[0] == key:+ return self._cache[1]+ S = self.ss; size = (self.W * S, self.H * S)+ L = [Image.new('L', size, 0) for _ in range(3)]+ sh = Image.new('L', size, 0); shd = ImageDraw.Draw(sh)+ cur, tmp = None, None++ def flush(tmp, name):+ m = ImageChops.multiply(tmp[1], self.clips[name])+ for a, b in zip(L, tmp):+ a.paste(b, (0, 0), m)++ for p in self.prims:+ c = p.get('clip')+ if p['k'] == 'shadow':+ c = cur+ if c != cur:+ if tmp is not None:+ flush(tmp, cur)+ tmp = [Image.new('L', size, 0) for _ in range(3)] if c else None+ cur = c+ tgt = tmp if tmp is not None else L+ self._draw(p, tgt, shd)+ if tmp is not None:+ flush(tmp, cur)+ out = (L, sh.filter(ImageFilter.GaussianBlur(2 * S)))+ self._cache = (key, out)+ return out++ def _render_pencil(self):+ S = self.ss; size = (self.W * S, self.H * S)+ pen = Image.new('L', size, 0); d = ImageDraw.Draw(pen)+ rng = np.random.default_rng(12345)++ def outline(P, closed, val, w, j):+ Q = (np.asarray(P, np.float32) + j) * S+ Q = [tuple(map(float, q)) for q in Q]+ if closed:+ Q = Q + Q[:1]+ if len(Q) > 1:+ d.line(Q, fill=val, width=w, joint='curve')++ def fillpoly(P, j):+ Q = [tuple(map(float, q)) for q in (np.asarray(P, np.float32) + j) * S]+ if len(Q) > 2:+ d.polygon(Q, fill=0)++ def hose_sides(P, w):+ P = np.asarray(P, np.float32)+ tg = np.gradient(P, axis=0); tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6+ nr = np.stack([-tg[:, 1], tg[:, 0]], 1)+ return P + nr * w / 2, P - nr * w / 2++ for p in self.prims:+ if p.get('fx') or p['k'] in ('shadow', 'text', 'guide'):+ continue+ j0 = rng.normal(0, 1.1, 2).astype(np.float32)+ for ps, (val, w) in enumerate(((235, max(3, int(1.7 * S))), (150, max(2, int(1.1 * S))))):+ j = j0 * (1 if ps == 0 else -0.8) + rng.normal(0, 0.5, 2).astype(np.float32)+ k = p['k']+ if k == 'shape':+ if p['fill'] is not None and ps == 0:+ fillpoly(p['pts'], j)+ outline(p['pts'], p['closed'], val, w, j)+ elif k == 'union':+ if ps == 0:+ for sub in p['subs']:+ if sub[0] == 'poly':+ fillpoly(sub[1], j)+ for sub in p['subs']:+ if sub[0] == 'poly':+ outline(sub[1], True, val, w, j)+ else:+ a, b = hose_sides(sub[1], sub[2] * 2)+ outline(a, False, val, w, j); outline(b, False, val, w, j)+ outline(ellipse_pts(*sub[1][-1], sub[2], sub[2]), True, val, w, j)+ elif k == 'hose':+ a, b = hose_sides(p['pts'], p['w'])+ outline(a, False, val, w, j); outline(b, False, val, w, j)+ elif k == 'stroke':+ outline(p['pts'], False, val, w, j)+ for p in self.prims:+ if p['k'] == 'guide':+ outline(p['pts'], p['closed'], 110, max(1, int(1.0 * S)), np.zeros(2, np.float32))+ return pen++ # ================================================================ state changes+ def ink(self):+ """trace the pencil roughs onto cels in black ink (snapshots now show the ink lines only)"""+ self.state = 'ink'++ def paint(self):+ """paint the backs of the cels in flat greys (snapshots now show the finished cels)"""+ self.state = 'paint'++ def film(self, grain=0.07, soft=0.85, halation=0.1, tone='silver', vignette=0.42, weave=(3.0, -2.0, 0.15),+ gate=(22, 16, 70), lift=0.075, white=0.93):+ """photograph the cel set-up onto black-and-white film and print it: lens softness, halation, print tone+ curve, grain, uneven density, vignette, gate weave, rounded projector gate"""+ self.film_opts = dict(grain=grain, soft=soft, halation=halation, tone=tone, vignette=vignette, weave=weave,+ gate=gate, lift=lift, white=white)++ def age(self, scratches=7, dust=90, specks=60, fibres=4, hair=True, stains=3, flicker=0.05, seed=None):+ """wear the print: scratches, white dust and black specks, lint fibres, a hair in the gate, stains and a+ frame of flicker"""+ self.age_opts = dict(scratches=scratches, dust=dust, specks=specks, fibres=fibres, hair=hair, stains=stains,+ flicker=flicker, seed=self._seed() if seed is None else seed)++ # ================================================================ compositing, film and aging+ def _down(self, a):+ S = self.ss+ if isinstance(a, Image.Image):+ a = np.asarray(a, np.uint8)+ return a.reshape(self.H, S, self.W, S).mean(axis=(1, 3), dtype=np.float32) / 255+ return a.reshape(self.H, S, self.W, S).mean(axis=(1, 3), dtype=np.float32)++ def _compose(self, view=None):+ if view == 'layout':+ paper = 0.95 + self._down(self.tex) * 0.012+ return paper * (1 - 0.55 * self._down(self.layout))+ v = np.clip(self._down(self.bg), 0, 1)+ if view == 'background':+ return v+ if self.state == 'pencil':+ return v * (1 - 0.8 * self._render_pencil_cached())+ (val, al, ln), sh = self._render_paint()+ if self.state == 'ink':+ l1 = self._down(ln)+ return v * (1 - l1) + INK * l1+ v = v * (1 - 0.9 * self._down(sh))+ a1 = self._down(al)+ pv = self._down(ImageChops.multiply(val, al))+ return v * (1 - a1) + pv++ def _render_pencil_cached(self):+ key = ('pencil', len(self.prims))+ if self._cache and self._cache[0] == key:+ return self._cache[1]+ out = self._down(self._render_pencil())+ self._cache = (key, out)+ return out++ def _film_pass(self, v):+ o = self.film_opts; H, W = self.H, self.W+ rng = np.random.default_rng(777)+ YY, XX = np.mgrid[0:H, 0:W].astype(np.float32)+ r2 = ((XX - W / 2) / (W / 2)) ** 2 + ((YY - H / 2) / (H / 2)) ** 2+ # lens: soft overall, softer toward the corners, halation round bright paint+ v = blur(v, o['soft'])+ e = np.clip(r2 * 0.5, 0, 1)+ v = v * (1 - e) + blur(v, 1.8) * e+ v = v + o['halation'] * blur(np.clip(v - 0.78, 0, 1), 6) * 3+ # gate weave: the frame sits a little off and a hair rotated in the gate+ dx, dy, rot = o['weave']+ im = Image.fromarray(v.astype(np.float32), 'F')+ im = im.rotate(rot, Image.BICUBIC, center=(W / 2, H / 2), translate=(dx, dy), fillcolor=0.02)+ v = np.asarray(im, np.float32)+ # print tone curve+ t = np.clip(v, 0, 1)+ t = t ** 1.1+ t = np.clip(0.5 + (t - 0.5) * 1.1, 0, 1)+ t = t * t * (3 - 2 * t) * 0.35 + t * 0.65+ out = o['lift'] + (o['white'] - o['lift']) * t+ # uneven density, grain+ out *= 1 + (noise2d(H // 4, W // 4, 90, 3, 31).repeat(4, 0).repeat(4, 1)[:H, :W] - 0.5) * 0.06+ g = rng.standard_normal((H, W)).astype(np.float32)+ g = blur(g, 0.7) * 2.2 + rng.standard_normal((H, W)).astype(np.float32) * 0.25+ clump = blur(rng.standard_normal((H // 2, W // 2)).astype(np.float32), 1.0).repeat(2, 0).repeat(2, 1)[:H, :W]+ g = g + clump * 1.6+ amp = o['grain'] * (0.45 + 1.6 * np.sqrt(np.clip(out * (1 - out), 0, 0.25)))+ out = out + g * amp * 0.5+ return out, r2, (XX, YY)++ def _age_pass(self, out, XX, YY):+ a = self.age_opts; H, W = self.H, self.W+ rng = np.random.default_rng(a['seed'])+ # stains: faint drying marks with a darker rim+ for _ in range(a['stains']):+ cx, cy = rng.uniform(150, W - 150), rng.uniform(100, H - 100)+ rx, ry = rng.uniform(40, 120), rng.uniform(30, 90)+ d = np.sqrt(((XX - cx) / rx) ** 2 + ((YY - cy) / ry) ** 2)+ ring = np.exp(-((d - 1) / 0.06) ** 2) * 0.025 - (d < 1) * 0.012+ out -= ring * (1 + 0.5 * np.sin(np.arctan2(YY - cy, XX - cx) * 3))+ # scratches: long vertical lines that wander and come and go+ for k in range(a['scratches']):+ x0 = rng.uniform(80, W - 80)+ white = k % 3 != 2+ wid = rng.uniform(0.6, 1.6) if white else rng.uniform(1.0, 2.2)+ xs = x0 + fbm1d(H, 400, 3, int(rng.integers(1 << 30))) * rng.uniform(4, 14) + np.arange(H) * rng.uniform(-0.01, 0.01)+ on = np.clip(fbm1d(H, rng.uniform(150, 600), 3, int(rng.integers(1 << 30))) * 3 + rng.uniform(0.2, 1.2), 0, 1)+ y0 = int(rng.uniform(0, H * 0.5)) if rng.random() < 0.4 else 0+ on[:y0] = 0+ for dxk in range(-3, 4):+ cols = np.clip((xs + dxk).astype(int), 0, W - 1)+ cov = np.clip(1 - np.abs(cols + 0.5 - xs) / wid, 0, 1) * on+ rows = np.arange(H)+ if white:+ out[rows, cols] += (0.97 - out[rows, cols]) * cov * rng.uniform(0.55, 0.85)+ else:+ out[rows, cols] *= 1 - cov * 0.45+ # white dust (dirt on the negative) and black specks (dirt on the print), fibres, a hair+ S = 2+ wim = Image.new('L', (W * S, H * S), 0); bim = Image.new('L', (W * S, H * S), 0)+ dw, db = ImageDraw.Draw(wim), ImageDraw.Draw(bim)+ for n, d in ((a['dust'], dw), (a['specks'], db)):+ for _ in range(n):+ x, y = rng.uniform(0, W), rng.uniform(0, H)+ r = rng.uniform(0.5, 1.6) if rng.random() < 0.85 else rng.uniform(2.0, 4.5)+ pts = [((x + np.cos(t) * r * rng.uniform(0.6, 1.3)) * S, (y + np.sin(t) * r * rng.uniform(0.6, 1.3)) * S)+ for t in np.linspace(0, 2 * np.pi, 7, endpoint=False)]+ d.polygon(pts, fill=int(rng.uniform(150, 255)))+ for k in range(a['fibres'] + (1 if a['hair'] else 0)):+ hair = a['hair'] and k == a['fibres']+ n = 40+ if hair:+ x, y = rng.uniform(W * 0.78, W * 0.92), H - 40+ L = 210+ else:+ x, y = rng.uniform(100, W - 100), rng.uniform(80, H - 80)+ L = rng.uniform(18, 60)+ ang = np.cumsum(rng.normal(0, 0.35, n)) + rng.uniform(0, 2 * np.pi) if not hair else \+ np.cumsum(rng.normal(0, 0.22, n)) - 1.9+ px = x + np.cumsum(np.cos(ang)) * L / n; py = y + np.cumsum(np.sin(ang)) * L / n+ (db if hair else dw).line([(float(a_ * S), float(b_ * S)) for a_, b_ in zip(px, py)],+ fill=255 if hair else 200, width=3 if hair else 2, joint='curve')+ wm = np.asarray(wim, np.uint8).reshape(H, S, W, S).mean(axis=(1, 3), dtype=np.float32) / 255+ bm = np.asarray(bim, np.uint8).reshape(H, S, W, S).mean(axis=(1, 3), dtype=np.float32) / 255+ out = out + (0.98 - out) * wm+ out = out * (1 - 0.85 * bm)+ # flicker: this frame came out a touch dense on one side+ out *= 1 - a['flicker'] * np.clip((XX / W - 0.35), 0, 1)+ return out++ def _finish(self, v):+ if self.film_opts is None:+ g = np.clip(v, 0, 1)+ return Image.fromarray((np.stack([g, g, g], -1) * 255 + 0.5).astype(np.uint8))+ o = self.film_opts; H, W = self.H, self.W+ out, r2, (XX, YY) = self._film_pass(v)+ if self.age_opts is not None:+ out = self._age_pass(out, XX, YY)+ out *= 1 - o['vignette'] * np.clip(r2 / 2, 0, 1) ** 1.3+ out = np.clip(out, 0, 1)+ if o['tone'] == 'sepia':+ rgb = np.stack([out ** 0.88, out ** 0.97, out ** 1.18], -1)+ elif o['tone'] == 'neutral':+ rgb = np.stack([out, out, out], -1)+ else:+ rgb = np.stack([out ** 0.95, out ** 0.985, out ** 1.07], -1)+ # rounded projector gate, soft edge, slightly irregular+ gx, gy, rad = o['gate']+ m = Image.new('L', (W * 2, H * 2), 0)+ ImageDraw.Draw(m).rounded_rectangle([gx * 2, gy * 2, (W - gx) * 2, (H - gy) * 2], radius=rad * 2, fill=255)+ m = m.resize((W, H), Image.BILINEAR).filter(ImageFilter.GaussianBlur(2.2))+ gm = np.asarray(m, np.float32)[..., None] / 255+ edge = 0.025 + 0.01 * (noise2d(H // 8, W // 8, 20, 2, 5).repeat(8, 0).repeat(8, 1)[:H, :W, None])+ rgb = rgb * gm + edge * (1 - gm)+ return Image.fromarray((np.clip(rgb, 0, 1) * 255 + 0.5).astype(np.uint8))++ def composite(self, view=None):+ return self._finish(self._compose(view))++ def stage(self, name, view=None):+ """snapshot for the draw-on animation. view='layout' shows only the background layout pencil on paper,+ view='background' the painted background without cels; otherwise the current state (pencil / ink / paint,+ filmed and aged once film() / age() were called)"""+ self.stages.append((name, self.composite(view)))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return imgdiff --git a/lib/storybook.py b/lib/storybook.pynew file mode 100644index 0000000..c62bc93--- /dev/null+++ b/lib/storybook.py@@ -0,0 +1,1567 @@+"""storybook — picture-book character animation: one tiny character with two eyes acts out a little journey and+the world is painted in around it as it goes (numpy + Pillow only).++Model: an animator's shot, not a still. Everything is a function of time t (seconds), so the same scene renders a+real animation (`frame(t)`, `gif()`) and a single "journey" poster (`journey()`: the finished world with the+character multiply-exposed at its key poses on a pencil motion arc).+ paper warm beige drawing paper: big soft cloudy mottling, a slight vignette, fine tooth and a few fibres.+ The tooth multiplies the whole frame at the end and never moves, so a still background costs nothing+ between frames of the GIF.+ world every piece of scenery is pre-painted once into its own cropped layer (colour, alpha) together with a+ REVEAL MAP: for every pixel, the moment (0..1) within that layer's own draw-on at which the brush or+ pen reaches it. Ink lines reveal along their arc length (the pen travels), washes spread from a point+ or sweep sideways with a ragged, slightly darker wet front, small props pop in with an overshoot+ (scale 0 -> 1.1 -> 1). A layer's progress comes either from a time window `when=(t0, t1)` or from+ `follow=lead`: it is drawn up to `lead` px ahead of the furthest x the character has reached, which is+ what makes the hills, flowers and banks appear just as the character passes.+ materials washes are transparent watercolour/gouache: mottled pigment, granulation in the paper tooth, a darker+ dried edge, a light-to-dark vertical gradient and optional coloured-pencil dashes inside (the short+ crayon strokes on a picture-book hill). Ink is a dark navy fine-liner with pressure taper and a little+ hand tremor; distant hills only get a thin grey contour on top. Clouds are thick white paint with a+ lavender shadow; the sun is a yellow wash disc with crayon rays drawn one by one.+ character `acorn` -- a nut with a scaly cap, drawn per frame from implicit shapes in its own local frame:+ the whole body is transformed by an affine squash/stretch along any axis (volume-preserving:+ k along the axis, 1/sqrt(k) across) and a roll angle, positioned so its lowest point sits exactly on+ the ground (`rest()`), lit by one world-fixed light (so the highlight stays put while it rolls) and+ given a soft contact shadow that shrinks as it leaves the ground. The face rides on the body: eyes+ with an openness (blink / sleepy / happy lids), pupils that look anywhere, brows, mouth, blush.+ acting choreography is a list of `act(t0, t1, fn)` segments, fn(u, t) -> pose dict; helpers give the+ Disney basics: ease in / out, back (overshoot) and spring settles, ballistic arcs, impact squash.+ FX are timed events: impact lines, dust puffs (white circles with a grey rim), water ripples, dirt+ specks, sparkles and confetti; speed lines are added automatically when the character moves fast.+ lettering a cursive line is written stroke by stroke: the text mask is thinned to a one-pixel skeleton+ (Zhang-Suen), the skeleton is walked like a pen (left-most stroke first, keep going straight at+ junctions, lift and jump at dead ends), and every inked pixel takes the time of its nearest skeleton+ pixel -- so loops, ascenders and joins fill in the order a hand would write them.+Coordinates are given in design pixels on a 1920 x 1080 canvas at any output size (y down; angles in degrees,+counter-clockwise). A 720 x 405 GIF and the 1920 x 1080 poster are just two instances of the same scene.++ from storybook import Storybook+ sb = Storybook(720, 405, seed=1)+ sb.paper()+ sb.ground([(0, 700), (960, 690), (1920, 700)], when=(0, 0.6))+ sb.act(0, 1.2, lambda u, t: dict(x=600 + 600 * sb.ease(u), y=sb.rest(600 + 600 * sb.ease(u), 690)[1]))+ sb.gif('walk.gif', fps=12.5, t_end=1.2)+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, load_font++PAPER = '#efe7da'+INK = '#1f2534'+PENCIL = '#8b8a92'+WHITE = '#fdfbf6'+GRASS, GRASS_DARK = '#93cf86', '#6db466'+MINT, LAVENDER = '#a7dcc9', '#b9bfe6'+SUN, SUN_RAY = '#f5c548', '#ee8c3a'+WATER = '#8ccbe2'+NUT, CAP, CAP_LINE = '#d39050', '#8a5634', '#58321e'+CONFETTI = ('#ee8a3c', '#f2c14e', '#d9534f', '#3fae8c', '#8c7ae6', '#5bb8dc', '#e8739b', '#7cc36a')+++def hexc(h):+ if not isinstance(h, str): return np.asarray(h, np.float32)+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def mix(a, b, t):+ return hexc(a) * (1 - t) + hexc(b) * t+++def _resample(P, step, closed=False):+ P = np.asarray(P, np.float32)+ if closed: P = np.vstack([P, P[:1]])+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ if s[-1] < 1e-6: return P[:1].copy()+ n = max(2, int(s[-1] / step) + 1)+ ss = np.linspace(0, s[-1], n)+ Q = np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1)+ return Q[:-1] if closed else Q+++def _normals(P, closed=False):+ if closed: d = np.roll(P, -1, 0) - np.roll(P, 1, 0)+ else: d = np.gradient(P, axis=0)+ d /= np.hypot(d[:, 0], d[:, 1])[:, None] + 1e-6+ return np.stack([-d[:, 1], d[:, 0]], 1)+++def _closed_spline(pts, per=10):+ P = np.asarray(pts, np.float32)+ Q = spline(np.vstack([P[-1:], P, P[:2]]), per)+ return Q[per:-per - 1]+++def oak_leaf(length, width=None, lobes=3, base=(0.0, 0.0), angle=-90.0, curl=0.0, seed=0):+ """outline of a lobed oak leaf, stalk at `base`, pointing at `angle` (deg ccw); returns (outline, midrib)"""+ width = width or length * 0.36+ r = np.random.default_rng(seed)+ s = np.linspace(0, 1, 90)+ prof = np.sin(np.pi * np.clip(s * 1.04, 0, 1)) ** 0.75+ lobe = 0.72 + 0.28 * np.abs(np.cos(np.pi * (lobes + 0.5) * s + r.uniform(-0.15, 0.15))) ** 0.6+ half = width * 0.5 * prof * lobe+ mid = np.stack([s * length, curl * length * np.sin(np.pi * s)], 1)+ left = mid + np.stack([np.zeros_like(s), -half], 1)+ right = mid + np.stack([np.zeros_like(s), half], 1)+ out = np.vstack([left, right[::-1]])+ a = np.deg2rad(angle)+ R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]], np.float32)+ f = lambda P: P @ R + np.asarray(base, np.float32)+ return f(out), f(mid)+++class _Layer:+ """a pre-painted piece of scenery: crop origin (x0, y0) in px, colour, alpha, reveal map and timing"""++ def __init__(self, x0, y0, rgb, a, rev=None, z=10.0, when=(0.0, 0.0), follow=None, soft=0.06, pop=None,+ wet=0.0, ease='inout', name=''):+ self.x0, self.y0, self.rgb, self.a, self.rev = x0, y0, rgb, a, rev+ self.z, self.when, self.follow, self.soft, self.pop, self.wet, self.ease, self.name = \+ z, when, follow, soft, pop, wet, ease, name+ self.pre = None+++class Storybook:+ PAPER, INK = PAPER, INK++ def __init__(self, W=1920, H=1080, seed=0, actor_size=44.0):+ self.W, self.H, self.s = W, H, W / 1920.0+ self.rng = np.random.default_rng(seed)+ self.seed = seed+ self.layers, self.acts, self.props, self.fxs, self.stages = [], [], [], [], []+ self.actor_size = actor_size # half-width of the nut in design px+ self.light = np.array([-0.5, -0.62, 0.6], np.float32); self.light /= np.linalg.norm(self.light)+ self._lead = None+ self.canvas = None+ self.paper()++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------------ easing and motion helpers+ @staticmethod+ def ease(u, kind='inout'):+ u = float(np.clip(u, 0, 1))+ if kind == 'linear': return u+ if kind == 'in': return u ** 3+ if kind == 'in2': return u * u+ if kind == 'out': return 1 - (1 - u) ** 3+ if kind == 'out2': return 1 - (1 - u) ** 2+ if kind == 'sine': return 0.5 - 0.5 * np.cos(np.pi * u)+ if kind == 'back': # overshoot then settle+ c1 = 1.70158; c3 = c1 + 1+ return 1 + c3 * (u - 1) ** 3 + c1 * (u - 1) ** 2+ if kind == 'elastic':+ return 1 - np.exp(-6.5 * u) * np.cos(3.2 * np.pi * u) if u < 1 else 1.0+ return 4 * u ** 3 if u < 0.5 else 1 - (-2 * u + 2) ** 3 / 2++ @staticmethod+ def spring(u, cycles=2.0, damp=5.0):+ """a decaying wobble that starts at 1 and dies out: multiply by an amplitude"""+ u = max(0.0, u)+ return float(np.exp(-damp * u) * np.cos(2 * np.pi * cycles * u))++ @staticmethod+ def arc(p0, p1, height, u):+ """ballistic hop from p0 to p1 peaking `height` px above the higher end"""+ u = float(np.clip(u, 0, 1))+ x = p0[0] + (p1[0] - p0[0]) * u+ top = min(p0[1], p1[1]) - height+ # parabola through p0, apex, p1 with apex at the u where it would be for constant gravity+ a0, a1 = np.sqrt(max(p0[1] - top, 1e-6)), np.sqrt(max(p1[1] - top, 1e-6))+ ua = a0 / (a0 + a1)+ y = top + (p0[1] - top) * ((u - ua) / ua) ** 2 if u < ua else top + (p1[1] - top) * ((u - ua) / (1 - ua)) ** 2+ return x, y++ @staticmethod+ def lerp(a, b, u):+ return a + (b - a) * u++ # ------------------------------------------------------------------ paper+ def paper(self, colour=PAPER, mottle=1.0, grain=1.0, fibres=220):+ H, W, s = self.H, self.W, self.s+ base = hexc(colour)+ m1 = noise2d(H, W, 520 * s + 8, 3, self.seed + 11)+ m2 = noise2d(H, W, 120 * s + 4, 3, self.seed + 12)+ yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)+ r2 = ((xx / W - 0.5) * 1.6) ** 2 + ((yy / H - 0.47) * 1.5) ** 2+ tone = (m1 - 0.5) * 0.07 * mottle + (m2 - 0.5) * 0.025 * mottle - 0.045 * r2+ rgb = base[None, None, :] * (1 + tone[..., None])+ rgb[..., 2] -= (m1 - 0.5) * 0.012 * mottle # warmer in the darker clouds+ self.tooth = noise2d(H, W, max(1.2, 2.0 * s), 2, self.seed + 13)+ fib = Image.new('L', (W, H), 0); d = ImageDraw.Draw(fib)+ r = np.random.default_rng(self.seed + 14)+ for _ in range(int(fibres)):+ x, y = r.uniform(0, W), r.uniform(0, H)+ L = r.uniform(8, 26) * s; a = r.uniform(0, np.pi)+ pts = [(x + np.cos(a) * L * t + np.sin(t * 3) * 2 * s, y + np.sin(a) * L * t) for t in np.linspace(-0.5, 0.5, 6)]+ d.line(pts, fill=int(r.uniform(60, 140)), width=1)+ fib = blur(np.asarray(fib, np.float32) / 255, 0.6 * s)+ rgb *= (1 - 0.035 * fib[..., None])+ self.base = np.clip(rgb, 0, 1).astype(np.float32)+ self.grain = (1 + 0.05 * grain * (self.tooth - 0.5)).astype(np.float32)[..., None]+ self.canvas = self.base.copy()++ # ------------------------------------------------------------------ low-level raster helpers+ def _px(self, pts):+ return np.asarray(pts, np.float32) * self.s++ def _bbox(self, P, pad):+ x0 = int(np.floor(P[:, 0].min() - pad)); y0 = int(np.floor(P[:, 1].min() - pad))+ x1 = int(np.ceil(P[:, 0].max() + pad)); y1 = int(np.ceil(P[:, 1].max() + pad))+ return x0, y0, max(x1, x0 + 2), max(y1, y0 + 2)++ def _poly(self, polys, box, ss=3):+ """union of polygons (px) -> antialiased mask over box"""+ x0, y0, x1, y1 = box+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0); d = ImageDraw.Draw(im)+ for P in polys:+ d.polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P], fill=255)+ im = im.resize((x1 - x0, y1 - y0), Image.BOX)+ return np.asarray(im, np.float32) / 255++ def _wobble(self, P, amp, closed=True, scale=None):+ """displace an outline along its normals by 1D fractal noise (hand-cut, hand-painted edges)"""+ if amp <= 0: return P+ Q = _resample(P, max(1.5, 3 * self.s), closed)+ n = _normals(Q, closed)+ w = fbm1d(len(Q), scale or max(8, len(Q) / 18), 3, self._seed()) * amp+ return Q + n * w[:, None]++ def _strokes(self, strokes, box, ss=3):+ """variable-width pen strokes -> (alpha, reveal). strokes: list of (P px (n,2), widths px (n,), r0, r1).+ The reveal map keeps the EARLIEST moment the nib touches each pixel."""+ x0, y0, x1, y1 = box+ w, h = x1 - x0, y1 - y0+ im = Image.new('L', (w * ss, h * ss), 0); d = ImageDraw.Draw(im)+ rv = Image.new('F', (w, h), 9.0); dr = ImageDraw.Draw(rv)+ for P, wd, r0, r1 in strokes:+ n = len(P)+ for i in range(n):+ x, y = (P[i, 0] - x0) * ss, (P[i, 1] - y0) * ss+ rr = max(0.35, wd[i] * 0.5) * ss+ d.ellipse((x - rr, y - rr, x + rr, y + rr), fill=255)+ for P, wd, r0, r1 in reversed(strokes):+ n = len(P)+ vals = np.linspace(r0, r1, n)+ for i in range(n - 1, -1, -1):+ x, y = P[i, 0] - x0, P[i, 1] - y0+ rr = wd[i] * 0.5 + 1.6+ dr.ellipse((x - rr, y - rr, x + rr, y + rr), fill=float(vals[i]))+ a = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255+ rev = np.minimum(np.asarray(rv, np.float32), 1.0)+ return a, rev++ def _pen(self, pts, width, taper=(0.12, 0.2), tremor=0.6, smooth=True, press=0.16, step=None):+ """design-space polyline -> (px points, px widths) with pressure taper and a little tremor"""+ P = self._px(pts)+ if smooth and len(P) > 2: P = spline(P, 10)+ P = _resample(P, step or max(0.5, 0.9 * self.s))+ n = len(P)+ if n < 2: P = np.vstack([P, P + 0.1]); n = 2+ t = np.linspace(0, 1, n)+ L = float(np.hypot(*np.diff(P, axis=0).T).sum()) + 1e-6+ ta, tb = taper+ env = np.clip(np.minimum(t / max(ta, 1e-3), (1 - t) / max(tb, 1e-3)), 0, 1) ** 0.6+ env = 0.3 + 0.7 * env if (ta or tb) else np.ones(n)+ wob = 1 + press * fbm1d(n, max(6, n / 6), 3, self._seed())+ wd = width * self.s * env * wob+ if tremor:+ P = P + _normals(P) * (fbm1d(n, max(6, L / (40 * self.s + 1)), 2, self._seed()) * tremor * self.s)[:, None]+ return P.astype(np.float32), wd.astype(np.float32)++ def _x_rev(self, box, xa, xb, noise=26.0, wave=0.0):+ """reveal map that sweeps left to right between design x = xa and xb, with a ragged front (noise: design px)"""+ x0, y0, x1, y1 = box+ X = (np.arange(x0, x1, dtype=np.float32) + 0.5) / self.s+ rev = np.clip((X - xa) / max(xb - xa, 1e-3), 0, 1)[None, :].repeat(y1 - y0, 0)+ if noise:+ rev = rev + (noise2d(y1 - y0, x1 - x0, 40 * self.s + 2, 2, self._seed()) - 0.5) * 2 * noise / max(xb - xa, 1)+ if wave:+ Y = (np.arange(y0, y1, dtype=np.float32)[:, None] + 0.5) / self.s+ rev = rev + wave * (Y - Y.min()) / max(1.0, float(Y.max() - Y.min()))+ return np.clip(rev, 0, 1).astype(np.float32)++ def _radial_rev(self, box, origin, noise=0.08):+ x0, y0, x1, y1 = box+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ ox, oy = origin[0] * self.s, origin[1] * self.s+ d = np.hypot(xx - ox, yy - oy)+ rev = d / max(float(d.max()), 1.0)+ if noise:+ rev = rev + (noise2d(y1 - y0, x1 - x0, 30 * self.s + 2, 3, self._seed()) - 0.5) * 2 * noise+ return np.clip(rev, 0, 1).astype(np.float32)++ def _add(self, box, rgb, a, rev=None, z=10.0, when=(0.0, 0.0), follow=None, soft=0.06, pop=None, wet=0.0,+ ease='inout', name='', xa=None, xb=None, rev_noise=26.0, pre=None):+ x0, y0, x1, y1 = box+ if follow is not None:+ xa = x0 / self.s if xa is None else xa+ xb = x1 / self.s if xb is None else xb+ if rev is None or rev == 'x':+ rev = self._x_rev(box, xa, xb, rev_noise)+ follow = (follow, xa, xb)+ soft = min(soft, 14.0 / max(xb - xa, 1.0)) # a crisp wet front, not a fog bank+ if isinstance(rev, str):+ if rev == 'x': rev = self._x_rev(box, x0 / self.s, x1 / self.s, rev_noise)+ elif rev == '-x': rev = 1 - self._x_rev(box, x0 / self.s, x1 / self.s, rev_noise)+ else: raise ValueError(rev)+ soft = min(soft, 14.0 * self.s / max(x1 - x0, 1.0))+ L = _Layer(x0, y0, rgb.astype(np.float32), a.astype(np.float32),+ None if rev is None else rev.astype(np.float32), z + len(self.layers) * 1e-4, when, follow, soft,+ pop, wet, ease, name)+ L.pre = pre+ self.layers.append(L)+ return L++ # ------------------------------------------------------------------ materials+ def _wash_rgb(self, box, a, colour, light=0.12, edge=0.5, mottle=1.0, dark=None):+ """watercolour / gouache: mottled pigment, granulation in the tooth, darker dried edge, vertical light"""+ x0, y0, x1, y1 = box+ h, w = y1 - y0, x1 - x0+ s = self.s+ n1 = noise2d(h, w, 80 * s + 3, 3, self._seed())+ n2 = noise2d(h, w, 16 * s + 2, 2, self._seed())+ tooth = self._crop(self.tooth, box)+ rim = np.clip(a - blur(a, 3.5 * s + 0.6), 0, 1) * 2.2+ yy = np.linspace(-1, 1, h, dtype=np.float32)[:, None]+ dens = (1 + 0.16 * mottle * (n1 - 0.5) + 0.08 * mottle * (n2 - 0.5) + edge * np.clip(rim, 0, 1)+ + 0.10 * (tooth - 0.5) + light * yy)+ c = hexc(colour)+ dk = hexc(dark) if dark is not None else c * 0.8+ t = np.clip((dens - 1) * 1.6, -1, 1)[..., None]+ rgb = np.where(t > 0, c + (dk - c) * t, c + (np.minimum(c * 1.08 + 0.04, 1) - c) * (-t))+ return rgb.astype(np.float32)++ def _crop(self, arr, box):+ """crop of a full-frame array (zero outside the frame)"""+ x0, y0, x1, y1 = box+ out = np.zeros((y1 - y0, x1 - x0) + arr.shape[2:], arr.dtype)+ ax0, ay0, ax1, ay1 = max(x0, 0), max(y0, 0), min(x1, self.W), min(y1, self.H)+ if ax1 > ax0 and ay1 > ay0:+ out[ay0 - y0:ay1 - y0, ax0 - x0:ax1 - x0] = arr[ay0:ay1, ax0:ax1]+ return out++ def _dashes(self, rgb, a, box, colour, n=40, length=26, width=3.2, angle=0.0, alpha=0.75, inset=6, seed=None,+ sag=0.0, top_bias=0.0):+ """coloured-pencil dashes inside a wash (the short crayon strokes on a picture-book hill).+ sag: px the middle of each dash bows (a ripple on water); top_bias > 0 crowds them toward the top"""+ x0, y0, x1, y1 = box+ s = self.s+ r = np.random.default_rng(seed if seed is not None else self._seed())+ inner = blur(a, inset * s + 0.5) > 0.97 * float(a.max())+ ys, xs = np.nonzero(inner)+ if len(xs) == 0: return rgb+ wgt = None+ if top_bias:+ v = (ys - ys.min()) / max(1.0, float(ys.max() - ys.min()))+ wgt = (1 - v) ** top_bias + 0.05; wgt = wgt / wgt.sum()+ ss = 3+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0); d = ImageDraw.Draw(im)+ for i in r.choice(len(xs), min(n, len(xs)), replace=False, p=wgt):+ cx, cy = xs[i], ys[i]+ L = length * s * r.uniform(0.6, 1.3); ang = np.deg2rad(angle + r.uniform(-5, 5))+ ca, sa = np.cos(ang), np.sin(ang)+ sg = (sag * r.uniform(0.6, 1.2) if sag else r.uniform(-1, 1)) * s+ pts = [(cx + ca * L * (t - 0.5), cy - sa * L * (t - 0.5) - sg * 4 * t * (1 - t)) for t in np.linspace(0, 1, 7)]+ d.line([(px * ss, py * ss) for px, py in pts], fill=255, width=max(1, int(width * s * ss)), joint='curve')+ m = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ grain = noise2d(y1 - y0, x1 - x0, max(1.5, 3.5 * s), 2, int(r.integers(1 << 30)))+ m = m * np.clip(0.35 + (grain - 0.25) * 1.6, 0.15, 1) * a / max(float(a.max()), 1e-3) * alpha+ return rgb * (1 - m[..., None]) + hexc(colour) * m[..., None]++ # ------------------------------------------------------------------ scenery+ def wash(self, pts, colour, z=10.0, when=(0.0, 0.0), follow=None, reveal='x', origin=None, light=0.12, edge=0.5,+ wobble=2.2, dashes=0, dash_colour=None, dash_angle=0.0, dash_len=26, opacity=0.97, dark=None, smooth=True,+ wet=0.18, name='wash', xa=None, xb=None, pre=None):+ """a watercolour / gouache shape. reveal: 'x', '-x', 'radial' (from origin) or 'pop' (scale in)"""+ P = self._px(pts)+ if smooth and len(P) > 3: P = _closed_spline(P, 6)+ P = self._wobble(P, wobble * self.s)+ box = self._bbox(P, 6 * self.s + 3)+ a = self._poly([P], box) * opacity+ rgb = self._wash_rgb(box, a, colour, light, edge, dark=dark)+ if dashes: rgb = self._dashes(rgb, a, box, dash_colour or mix(colour, INK, 0.25), dashes, dash_len,+ angle=dash_angle)+ pop = None+ rev = None+ if follow is None:+ if reveal == 'radial':+ rev = self._radial_rev(box, origin if origin is not None else P.mean(0) / self.s)+ elif reveal == 'pop':+ o = origin if origin is not None else (P.mean(0) / self.s)+ pop = (o[0] * self.s, o[1] * self.s)+ elif reveal in ('x', '-x'):+ rev = reveal+ return self._add(box, rgb, a, rev, z, when, follow, 0.08, pop, wet, name=name, xa=xa, xb=xb, pre=pre)++ def ink(self, pts, width=4.0, colour=INK, z=20.0, when=(0.0, 0.0), follow=None, taper=(0.06, 0.12), tremor=0.6,+ smooth=True, name='ink', alpha=1.0, xa=None, xb=None, pre=None):+ """a fine-liner stroke drawn on along its length"""+ return self.inks([pts], width, colour, z, when, follow, taper, tremor, smooth, name, alpha, xa=xa, xb=xb,+ pre=pre)++ def inks(self, paths, width=4.0, colour=INK, z=20.0, when=(0.0, 0.0), follow=None, taper=(0.06, 0.12),+ tremor=0.6, smooth=True, name='ink', alpha=1.0, widths=None, xa=None, xb=None, pre=None):+ """several strokes drawn one after another inside one time window"""+ strokes = []+ pens = [self._pen(p, (widths[i] if widths else width), taper, tremor, smooth) for i, p in enumerate(paths)]+ lens = [float(np.hypot(*np.diff(P, axis=0).T).sum()) + 1 for P, _ in pens]+ tot = sum(lens); acc = 0.0+ for (P, wd), L in zip(pens, lens):+ strokes.append((P, wd, acc / tot, (acc + L) / tot)); acc += L+ allP = np.vstack([P for P, _ in pens])+ box = self._bbox(allP, max(float(np.max(w)) for _, w in pens) + 4)+ a, rev = self._strokes(strokes, box)+ a = a * alpha+ tex = 0.9 + 0.1 * self._crop(self.tooth, box) # ink catches a little tooth+ rgb = np.broadcast_to(hexc(colour), a.shape + (3,)).astype(np.float32) * (2 - tex[..., None]) ** 0.4+ return self._add(box, rgb, a * tex, None if follow is not None else rev, z, when, follow, 0.03,+ name=name, ease='linear', xa=xa, xb=xb, pre=pre, rev_noise=4.0)++ def ground(self, pts, width=4.6, z=20.0, when=(0.0, 0.0), follow=None, ticks=True, tick_every=(70, 120),+ tick_h=15, name='ground', xa=None, xb=None, pre=None):+ """the black horizon / ground line with little 'v' grass ticks standing on it"""+ P = self._px(pts)+ P = spline(P, 10) if len(P) > 2 else P+ Pd = P / self.s+ paths = [Pd]+ if ticks:+ r = np.random.default_rng(self._seed())+ Q = _resample(Pd, 2.0)+ s_ = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(Q, axis=0).T))])+ pos = r.uniform(*tick_every) * 0.5+ while pos < s_[-1] - 20:+ i = int(np.searchsorted(s_, pos))+ x, y = Q[i]+ h = tick_h * r.uniform(0.7, 1.3); sp = h * r.uniform(0.35, 0.55)+ paths.append([(x - sp, y - h), (x, y - 1)]); paths.append([(x, y - 1), (x + sp * 0.8, y - h * 0.9)])+ pos += r.uniform(*tick_every)+ widths = [width] + [width * 0.55] * (len(paths) - 1)+ return self.inks(paths, width, INK, z, when, follow, (0.03, 0.05), 0.5, False, name, widths=widths, xa=xa,+ xb=xb, pre=pre)++ def land(self, top, colour=GRASS, bottom=None, z=12.0, when=(0.0, 0.0), follow=None, dashes=60, dash_colour=None,+ reveal='x', name='land', wobble=1.5, left_edge=None, right_edge=None, xa=None, xb=None, pre=None):+ """a hill body: wash from a top contour (Catmull-Rom through the points) down to the bottom of the frame+ (or `bottom` y), crayon dashes inside. left_edge / right_edge: ragged cliff points, top to bottom"""+ top = [tuple(p) for p in (spline(np.asarray(top, np.float32), 8) if len(top) > 2 else top)]+ bottom = 1080 + 40 if bottom is None else bottom+ R = [tuple(p) for p in right_edge] if right_edge else [(top[-1][0], bottom)]+ Lf = [tuple(p) for p in left_edge] if left_edge else [(top[0][0], bottom)]+ poly = top + R + [(R[-1][0], bottom), (Lf[-1][0], bottom)] + Lf[::-1]+ P = self._px(poly)+ P = self._wobble(P, wobble * self.s)+ box = self._bbox(P, 4)+ a = self._poly([P], box) * 0.97+ rgb = self._wash_rgb(box, a, colour, light=0.10, edge=0.25)+ if dashes: rgb = self._dashes(rgb, a, box, dash_colour or GRASS_DARK, dashes, 44, 5.0, angle=0, alpha=0.55,+ inset=12)+ rev = None if follow is not None else reveal+ return self._add(box, rgb, a, rev, z, when, follow, 0.06, None, 0.15, name=name, xa=xa, xb=xb, pre=pre)++ def hill(self, top, colour=MINT, bottom=None, z=5.0, when=(0.0, 0.0), follow=None, outline='#7d8496',+ line=2.4, name='hill', xa=None, xb=None, pre=None):+ """a distant hill: a flat pale wash with a thin grey contour along its top only"""+ L = self.land(top, colour, bottom, z, when, follow, dashes=0, name=name, xa=xa, xb=xb, pre=pre)+ if outline:+ self.ink(top, line, outline, z + 0.5, when, follow, (0.02, 0.06), 0.4, True, name + '_line', xa=xa, xb=xb,+ pre=pre)+ return L++ def tree(self, x, base, top, canopy, colour='#eaa23d', shade='#d9782f', branch=None, when=(0.0, 0.6), z=8.0,+ trunk=13.0, ticks=7):+ """a storybook oak: navy ink trunk and branches, a canopy of overlapping wash circles with a darker+ crescent and a few leaf ticks. canopy: list of (cx, cy, r). branch: list of polylines."""+ t0, t1 = when+ tm = t0 + (t1 - t0) * 0.45+ hgt = base - top+ self.inks([[(x, base), (x - 7, base - hgt * 0.35), (x + 1, base - hgt * 0.72), (x + 10, top)]] + (branch or []),+ trunk, INK, z - 0.3, (t0, tm), taper=(0.0, 0.5), tremor=0.8,+ widths=[trunk] + [trunk * 0.5] * len(branch or []), name='trunk')+ polys = [np.stack([cx + r * np.cos(a), cy + r * np.sin(a)], 1)+ for cx, cy, r in canopy for a in [np.linspace(0, 2 * np.pi, 72, endpoint=False)]]+ P = [self._wobble(self._px(p), 2.2 * self.s) for p in polys]+ box = self._bbox(np.vstack(P), 8 * self.s + 3)+ a = self._poly(P, box) * 0.98+ rgb = self._wash_rgb(box, a, colour, light=0.18, edge=0.6, dark=shade)+ # darker crescent: canopy minus itself shifted toward the light+ sh = self._poly([p + np.array([-40, -46], np.float32) * self.s for p in P], box)+ cres = np.clip(a - sh, 0, 1)+ cres = blur(cres, 10 * self.s + 0.5) * a+ rgb = rgb * (1 - 0.8 * cres[..., None]) + hexc(shade) * 0.8 * cres[..., None]+ # clumps of foliage in a second and third autumn colour, dabbed on with a round brush+ r = np.random.default_rng(self._seed())+ x0, y0, x1, y1 = box+ dab = Image.new('L', ((x1 - x0) * 2, (y1 - y0) * 2), 0); dd = ImageDraw.Draw(dab)+ dab2 = Image.new('L', dab.size, 0); dd2 = ImageDraw.Draw(dab2)+ for _ in range(34): # little oak leaves stamped on with a loaded brush+ c = canopy[r.integers(len(canopy))]+ ang = r.uniform(0, 2 * np.pi); dist = r.uniform(0.1, 0.82) * c[2]+ lx, ly = c[0] + np.cos(ang) * dist, c[1] + np.sin(ang) * dist+ lf, _ = oak_leaf(r.uniform(22, 34), None, 2, (lx, ly), r.uniform(0, 360), seed=int(r.integers(1 << 20)))+ q = [((u - x0 / self.s) * self.s * 2, (v - y0 / self.s) * self.s * 2) for u, v in lf]+ (dd if r.random() < 0.55 else dd2).polygon(q, fill=255)+ for im_, col, k in ((dab, '#d4592f', 0.5), (dab2, '#f8cf62', 0.55)):+ m = np.asarray(im_.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ m = blur(m, 0.6 * self.s) * a * k * np.clip(0.6 + 0.8 * self._crop(self.tooth, box), 0, 1)+ rgb = rgb * (1 - m[..., None]) + hexc(col) * m[..., None]+ rgb = self._dashes(rgb, a, box, mix(colour, '#fff2c9', 0.5), 14, 18, 3.0, angle=35, alpha=0.5)+ cx = np.mean([c[0] for c in canopy]); cy = np.mean([c[1] for c in canopy])+ rev = self._radial_rev(box, (cx, cy + 40), 0.1)+ self._add(box, rgb, a, rev, z, (t0 + (t1 - t0) * 0.25, t1), soft=0.1, wet=0.2, name='canopy')+ if ticks:+ r = np.random.default_rng(self._seed())+ paths = []+ for _ in range(ticks):+ c = canopy[r.integers(len(canopy))]+ ang = r.uniform(0, 2 * np.pi); d = r.uniform(0.2, 0.7) * c[2]+ px, py = c[0] + np.cos(ang) * d, c[1] + np.sin(ang) * d+ paths.append([(px, py), (px + 7, py + 12)])+ self.inks(paths, 3.0, mix(shade, INK, 0.45), z + 0.2, (t1 - 0.15, t1), taper=(0.2, 0.3), name='leafticks')++ def sun(self, cx, cy, r, when=(0.0, 1.0), rays=12, z=4.0, colour=SUN, ray_colour=SUN_RAY):+ """a yellow wash disc that pops in, then crayon rays drawn round one by one"""+ t0, t1 = when+ tm = t0 + (t1 - t0) * 0.4+ ang = np.linspace(0, 2 * np.pi, 80, endpoint=False)+ P = self._wobble(self._px(np.stack([cx + r * np.cos(ang), cy + r * np.sin(ang)], 1)), 1.4 * self.s)+ pad = r * 0.5 * self.s + 6+ box = self._bbox(P, pad)+ a = self._poly([P], box)+ x0, y0, x1, y1 = box+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ d = np.hypot(xx - (cx - r * 0.25) * self.s, yy - (cy - r * 0.3) * self.s) / (r * self.s * 1.25)+ c0, c1 = hexc('#fbe48f'), hexc('#efa93a')+ g = np.clip(d, 0, 1)[..., None] ** 1.6+ rgb = c0 * (1 - g) + c1 * g+ rgb = rgb * (1 + 0.06 * (noise2d(y1 - y0, x1 - x0, 14 * self.s + 2, 2, self._seed()) - 0.5)[..., None])+ halo = np.exp(-np.clip(np.hypot(xx - cx * self.s, yy - cy * self.s) / (r * self.s) - 1, 0, None) * 3.2) * 0.22+ aa = np.maximum(a, halo * (1 - a))+ rgb = np.where(a[..., None] > 0.02, rgb, hexc('#f8d77a'))+ self._add(box, rgb, aa, None, z, (t0, tm), pop=(cx * self.s, cy * self.s), ease='linear', name='sun')+ r_ = np.random.default_rng(self._seed())+ paths, w = [], []+ for i in range(rays):+ a_ = -np.pi / 2 + 2 * np.pi * i / rays + r_.uniform(-0.06, 0.06)+ r0 = r * 1.32; r1 = r * (1.72 if i % 2 == 0 else 1.55)+ paths.append([(cx + r0 * np.cos(a_), cy + r0 * np.sin(a_)), (cx + r1 * np.cos(a_), cy + r1 * np.sin(a_))])+ w.append(7.5)+ L = self.inks(paths, 7.5, ray_colour, z + 0.1, (tm, t1), taper=(0.25, 0.35), tremor=0.3, smooth=False,+ name='rays', widths=w)+ L.rgb = self._crayon_tex(L)+ return L++ def _crayon_tex(self, L):+ box = (L.x0, L.y0, L.x0 + L.a.shape[1], L.y0 + L.a.shape[0])+ tooth = self._crop(self.tooth, box)+ L.a = L.a * np.clip(0.35 + (tooth - 0.2) * 1.6, 0.25, 1)+ return L.rgb++ def cloud(self, cx, cy, w, when=(0.0, 0.4), z=6.0, colour=WHITE, shadow='#bcc0e6'):+ """thick white paint: three or four bumps on a flat-ish bottom, a lavender shadow under the right side"""+ r = np.random.default_rng(self._seed())+ bumps = [(-0.30, 0.05, 0.26), (-0.05, -0.12, 0.34), (0.24, -0.02, 0.27), (0.40, 0.08, 0.17), (-0.45, 0.12, 0.15)]+ polys = []+ for bx, by, br in bumps:+ br *= r.uniform(0.92, 1.08)+ a = np.linspace(0, 2 * np.pi, 60, endpoint=False)+ polys.append(np.stack([cx + bx * w + br * w * np.cos(a), cy + by * w + br * w * 0.9 * np.sin(a)], 1))+ polys.append(np.array([(cx - 0.52 * w, cy + 0.08 * w), (cx + 0.52 * w, cy + 0.08 * w),+ (cx + 0.5 * w, cy + 0.2 * w), (cx - 0.5 * w, cy + 0.2 * w)]))+ P = [self._wobble(self._px(p), 1.0 * self.s) for p in polys]+ off = np.array([7, 9], np.float32) * self.s+ box = self._bbox(np.vstack(P + [p + off for p in P]), 6 * self.s + 4)+ a = self._poly(P, box)+ a = np.clip(blur(a, 0.9 * self.s), 0, 1)+ sh = self._poly([p + off for p in P], box)+ x0, y0, x1, y1 = box+ yy = np.linspace(0, 1, y1 - y0, dtype=np.float32)[:, None]+ streak = noise2d(y1 - y0, x1 - x0, 10 * self.s + 2, 2, self._seed())+ streak = blur(streak, 0.5) if self.s > 0.6 else streak+ base = hexc(colour)+ inner = np.clip(a - np.roll(np.roll(a, int(-8 * self.s), 0), int(-6 * self.s), 1), 0, 1)+ shade = np.clip(0.06 + 0.10 * yy + 0.35 * blur(inner, 4 * self.s + 0.5), 0, 0.5)+ body = base * (1 - shade[..., None]) + hexc('#d7dbf2') * shade[..., None]+ body = body * (0.97 + 0.06 * streak[..., None])+ shc = hexc(shadow)+ rgb = np.where(a[..., None] > 0.01, body, shc)+ alpha = np.maximum(a, sh * 0.85)+ rgb = (body * a[..., None] + shc * (alpha - a)[..., None]) / np.maximum(alpha, 1e-4)[..., None]+ return self._add(box, rgb, alpha, None, z, when, pop=(cx * self.s, (cy + 0.15 * w) * self.s), name='cloud')++ def shape(self, polys, fill, outline=INK, line=2.6, z=30.0, when=(0.0, 0.3), pop=None, reveal=None, origin=None,+ light=0.08, name='shape', dark=None, wobble=0.8):+ """filled wash shapes with a thin ink outline (petals, leaves, mushrooms): pops in from `pop` (design xy)"""+ P = [self._wobble(self._px(p), wobble * self.s) for p in polys]+ lw = line * self.s+ box = self._bbox(np.vstack(P), lw + 4)+ a = self._poly(P, box)+ rgb = self._wash_rgb(box, a, fill, light=light, edge=0.35, dark=dark)+ if outline and line > 0:+ x0, y0, x1, y1 = box+ ss = 3+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0); d = ImageDraw.Draw(im)+ for p in P:+ q = [((x - x0) * ss, (y - y0) * ss) for x, y in np.vstack([p, p[:1]])]+ d.line(q, fill=255, width=max(1, int(round(lw * ss))), joint='curve')+ o = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ rgb = rgb * (1 - o[..., None]) + hexc(outline) * o[..., None]+ a = np.maximum(a, o)+ popxy = None if pop is None else (pop[0] * self.s, pop[1] * self.s)+ rev = None+ if reveal == 'radial': rev = self._radial_rev(box, origin)+ return self._add(box, rgb, a, rev, z, when, None, 0.08, popxy, 0.0, name=name)++ def flower(self, x, y, h=70, kind='aster', colour='#b48ae0', centre='#f4c242', when=(0.0, 0.5), z=30.0, lean=0.0,+ petals=None):+ """stem drawn up from the ground, then the head pops open with an overshoot"""+ t0, t1 = when+ tm = t0 + (t1 - t0) * 0.45+ hx, hy = x + lean * h, y - h+ self.ink([(x, y), (x + lean * h * 0.3 + 3, y - h * 0.5), (hx, hy)], 3.2, '#2f5a3c', z, (t0, tm), taper=(0, 0.2),+ name='stem')+ lf, _ = oak_leaf(h * 0.32, h * 0.13, 1, (x + 1, y - h * 0.35), 35, seed=self._seed())+ self.shape([lf], '#7cc36a', INK, 2.0, z - 0.1, (tm - 0.05, tm + 0.15), pop=(x, y - h * 0.35), name='stemleaf')+ rr = h * 0.17+ polys = []+ n = petals or (12 if kind == 'aster' else 8)+ for i in range(n):+ a = 2 * np.pi * i / n+ pl = rr * (1.0 if kind == 'aster' else 1.1); pw = rr * (0.32 if kind == 'aster' else 0.55)+ t = np.linspace(0, 2 * np.pi, 24, endpoint=False)+ ex = pl * 0.55 + pl * 0.55 * np.cos(t); ey = pw * 0.5 * np.sin(t)+ polys.append(np.stack([hx + ex * np.cos(a) - ey * np.sin(a), hy + ex * np.sin(a) + ey * np.cos(a)], 1))+ self.shape(polys, colour, INK, 1.8, z + 0.1, (tm, t1), pop=(hx, hy), name='petals')+ t = np.linspace(0, 2 * np.pi, 30, endpoint=False)+ self.shape([np.stack([hx + rr * 0.42 * np.cos(t), hy + rr * 0.42 * np.sin(t)], 1)], centre, INK, 1.8, z + 0.2,+ (tm + 0.04, t1), pop=(hx, hy), name='centre')++ def tuft(self, x, y, h=26, when=(0.0, 0.25), z=29.0, colour='#3e7a4a'):+ """a little fan of grass blades flicked up from the ground"""+ r = np.random.default_rng(self._seed())+ paths = []+ for k in range(r.integers(3, 6)):+ a = np.deg2rad(r.uniform(-35, 35)); L = h * r.uniform(0.6, 1.1)+ paths.append([(x + k * 2 - 4, y), (x + np.sin(a) * L * 0.5, y - L * 0.55), (x + np.sin(a) * L, y - L)])+ return self.inks(paths, 3.2, colour, z, when, taper=(0.0, 0.6), name='tuft')++ def cattail(self, x, y, h=150, when=(0.0, 0.5), z=31.0, lean=0.08):+ t0, t1 = when+ tm = t0 + (t1 - t0) * 0.55+ top = (x + lean * h, y - h)+ self.ink([(x, y), (x + lean * h * 0.4, y - h * 0.5), top], 3.4, '#2f5a3c', z, (t0, tm), taper=(0, 0.15))+ self.ink([(x - 2, y), (x - 26, y - h * 0.45), (x - 46, y - h * 0.62)], 5.0, '#5f9d58', z - 0.1, (t0, tm),+ taper=(0, 0.8), name='blade')+ hx, hy = x + lean * h * 0.86, y - h * 0.82+ t = np.linspace(0, 2 * np.pi, 40, endpoint=False)+ ang = np.arctan2(-h, lean * h)+ ca, sa = np.cos(ang), np.sin(ang)+ ex, ey = 0.11 * h * np.cos(t), 0.035 * h * np.sin(t)+ P = np.stack([hx + ex * ca - ey * sa, hy + ex * sa + ey * ca], 1)+ self.shape([P], '#7a4a2c', INK, 2.0, z + 0.1, (tm, t1), pop=(hx, hy), dark='#4c2b19', name='cattail')++ def leaf_on_ground(self, x, y, size=26, colour='#d9603a', angle=None, when=(0.0, 0.25), z=29.0):+ r = np.random.default_rng(self._seed())+ ang = angle if angle is not None else r.uniform(-30, 30)+ out, mid = oak_leaf(size, size * 0.45, 2, (0, 0), ang, seed=self._seed())+ out = out * np.array([1.0, 0.55]) + np.array([x, y]); mid = mid * np.array([1.0, 0.55]) + np.array([x, y])+ L = self.shape([out], colour, INK, 1.6, z, when, pop=(x, y), name='fallen')+ return L++ def mound(self, x, y, w=120, h=34, when=(0.0, 0.4), z=55.0, colour='#a46a3e'):+ """a heap of fresh soil pushed up around a hole (drawn over the character, so it can bury it)"""+ t = np.linspace(0, np.pi, 40)+ top = np.stack([x - w / 2 + w * (1 - np.cos(t)) / 2, y - h * np.sin(t) ** 0.8 - 2], 1)+ P = np.vstack([top, [(x + w / 2 + 6, y + 6), (x - w / 2 - 6, y + 6)]])+ L = self.shape([P], colour, INK, 2.4, z, when, pop=(x, y + 4), dark='#6d4224', name='mound')+ # soil crumbs+ box = (L.x0, L.y0, L.x0 + L.a.shape[1], L.y0 + L.a.shape[0])+ r = np.random.default_rng(self._seed())+ im = Image.new('L', (L.a.shape[1] * 3, L.a.shape[0] * 3), 0); d = ImageDraw.Draw(im)+ for _ in range(16):+ px = (x + r.uniform(-0.4, 0.4) * w) * self.s; py = (y - r.uniform(0.1, 0.7) * h) * self.s+ rr = r.uniform(1.2, 2.6) * self.s * 3+ d.ellipse(((px - box[0]) * 3 - rr, (py - box[1]) * 3 - rr, (px - box[0]) * 3 + rr, (py - box[1]) * 3 + rr),+ fill=255)+ m = np.asarray(im.resize((L.a.shape[1], L.a.shape[0]), Image.BOX), np.float32)[..., None] / 255+ L.rgb = L.rgb * (1 - 0.8 * m) + hexc('#4a2c18') * 0.8 * m+ return L++ def water(self, x0, x1, y, depth=260, when=(0.0, 1.0), z=9.0, follow=None, colour=WATER):+ """a stream between two banks: blue wash, darker with depth, white glints and ink-blue ripple dashes"""+ top = [(x0 + (x1 - x0) * u, y + 3 * np.sin(u * 9)) for u in np.linspace(0, 1, 16)]+ poly = top + [(x1, y + depth), (x0, y + depth)]+ P = self._px(poly)+ box = self._bbox(P, 4)+ a = self._poly([P], box) * 0.96+ rgb = self._wash_rgb(box, a, colour, light=0.35, edge=0.2, dark='#5c9fc4')+ r = np.random.default_rng(self._seed())+ rgb = self._dashes(rgb, a, box, '#f7fcff', 16, 80, 5.0, 0, 0.9, inset=14, seed=self._seed(), sag=-3,+ top_bias=2.0)+ rgb = self._dashes(rgb, a, box, '#4a82ad', 9, 60, 3.6, 0, 0.6, inset=14, seed=self._seed(), sag=5,+ top_bias=1.0)+ L = self._add(box, rgb, a, None if follow is not None else 'x', z, when, follow, 0.08, None, 0.12,+ name='water')+ self.ink(top, 2.4, '#3d6f94', z + 0.2, when, follow, (0.02, 0.04), 0.3, True, 'waterline')+ return L++ def write(self, text, x, y, size=130, when=(0.0, 1.2), colour=INK, font='script', z=80.0, anchor='mm',+ underline=None, weight=1.6):+ """a handwritten line that writes itself stroke by stroke (see `_write_order`). weight: extra pen width in+ design px (keeps the hairlines of a script font alive in a small GIF)"""+ ss = 2+ s = self.s+ ft = load_font(font, size * s * ss)+ W2, H2 = self.W * ss, self.H * ss+ im = Image.new('L', (W2, H2), 0)+ ImageDraw.Draw(im).text((x * s * ss, y * s * ss), text, font=ft, fill=255, anchor=anchor,+ stroke_width=int(round(weight * 0.5 * s * ss)), stroke_fill=255)+ m2 = np.asarray(im, np.float32) / 255+ ys, xs = np.nonzero(m2 > 0.02)+ if len(xs) == 0: return None+ bx0, by0 = max(0, xs.min() - 6), max(0, ys.min() - 6)+ bx1, by1 = min(W2, xs.max() + 7), min(H2, ys.max() + 7)+ bx0 -= bx0 % ss; by0 -= by0 % ss; bx1 += (-bx1) % ss; by1 += (-by1) % ss+ sub = m2[by0:by1, bx0:bx1]+ T = self._write_order(sub > 0.5, sub > 0.02)+ T = np.where(sub > 0.02, T, 9.0)+ h, w = sub.shape[0] // ss, sub.shape[1] // ss+ a = sub.reshape(h, ss, w, ss).mean((1, 3))+ rev = T.reshape(h, ss, w, ss).min((1, 3))+ rev = np.where(rev > 1.5, 1.0, rev)+ box = (bx0 // ss, by0 // ss, bx0 // ss + w, by0 // ss + h)+ tooth = self._crop(self.tooth, box)+ a = a * (0.9 + 0.1 * tooth)+ rgb = np.broadcast_to(hexc(colour), a.shape + (3,)).astype(np.float32).copy()+ L = self._add(box, rgb, a, rev, z, when, None, 0.012, ease='linear', name='write')+ if underline:+ (u0, u1), uy = underline+ t0, t1 = when+ self.ink([(u0, uy + 6), ((u0 + u1) / 2, uy - 4), (u1, uy + 2)], 3.4, colour, z, (t1, t1 + 0.35),+ taper=(0.1, 0.5), name='underline')+ return L++ @staticmethod+ def _thin(m):+ """Zhang-Suen thinning of a boolean mask -> one-pixel skeleton"""+ img = np.pad(m.astype(np.uint8), 1)+ while True:+ changed = False+ for step in (0, 1):+ P = img+ p2, p3, p4 = P[:-2, 1:-1], P[:-2, 2:], P[1:-1, 2:]+ p5, p6, p7 = P[2:, 2:], P[2:, 1:-1], P[2:, :-2]+ p8, p9 = P[1:-1, :-2], P[:-2, :-2]+ c = P[1:-1, 1:-1]+ B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9+ seq = [p2, p3, p4, p5, p6, p7, p8, p9, p2]+ A = sum(((seq[i] == 0) & (seq[i + 1] == 1)).astype(np.uint8) for i in range(8))+ if step == 0: k1, k2 = p2 * p4 * p6, p4 * p6 * p8+ else: k1, k2 = p2 * p4 * p8, p2 * p6 * p8+ rm = (c == 1) & (B >= 2) & (B <= 6) & (A == 1) & (k1 == 0) & (k2 == 0)+ if rm.any():+ c[rm] = 0; changed = True+ if not changed: break+ return img[1:-1, 1:-1].astype(bool)++ def _write_order(self, m, fill=None):+ """time 0..1 at which a pen reaches each inked pixel: walk the skeleton like a hand would"""+ sk = self._thin(m)+ fill = m if fill is None else fill+ ys, xs = np.nonzero(sk)+ n = len(xs)+ if n == 0: return np.zeros(m.shape, np.float32)+ idx = -np.ones(m.shape, np.int64); idx[ys, xs] = np.arange(n)+ H, W = m.shape+ nb = []+ for i in range(n):+ y, x = ys[i], xs[i]+ l = []+ for dy in (-1, 0, 1):+ for dx in (-1, 0, 1):+ if dx == 0 and dy == 0: continue+ yy, xx = y + dy, x + dx+ if 0 <= yy < H and 0 <= xx < W and idx[yy, xx] >= 0: l.append(int(idx[yy, xx]))+ nb.append(l)+ comp = -np.ones(n, np.int64); comps = []+ for i in range(n):+ if comp[i] >= 0: continue+ st = [i]; comp[i] = len(comps); mem = []+ while st:+ j = st.pop(); mem.append(j)+ for k in nb[j]:+ if comp[k] < 0: comp[k] = len(comps); st.append(k)+ comps.append(mem)+ # small marks (i-dots, commas, cross-bars) are written right after the stroke they sit on+ comps.sort(key=lambda c: xs[c].min() + (0.6 * (xs[c].max() - xs[c].min()) if len(c) < 60 else 0))+ T = np.full(n, -1.0)+ seen = np.zeros(n, bool)+ clock = 0.0+ for c in comps:+ ends = [j for j in c if len(nb[j]) == 1]+ pool = ends if ends else c+ start = min(pool, key=lambda j: (xs[j] + 0.35 * ys[j], ys[j])) # de-slanted left-most end+ cur = start; seen[cur] = True; T[cur] = clock; prev = None; stack = []+ while True:+ cand = [k for k in nb[cur] if not seen[k]]+ if cand:+ if len(cand) > 1: stack.append(cur)+ if prev is None:+ nxt = min(cand, key=lambda k: (ys[k] - ys[cur]) + 0.5 * (xs[k] - xs[cur]))+ else:+ dv = (xs[cur] - xs[prev], ys[cur] - ys[prev])+ nxt = max(cand, key=lambda k: (xs[k] - xs[cur]) * dv[0] + (ys[k] - ys[cur]) * dv[1])+ step = 1.414 if (xs[nxt] != xs[cur] and ys[nxt] != ys[cur]) else 1.0+ prev, cur = cur, nxt+ seen[cur] = True; clock += step; T[cur] = clock+ else:+ while stack and not any(not seen[k] for k in nb[stack[-1]]): stack.pop()+ if not stack: break+ cur = stack.pop(); prev = None; clock += 2.0+ clock += 12.0+ T /= max(clock, 1.0)+ # spread the skeleton times over the whole stroke width (nearest skeleton pixel)+ Tm = np.full(m.shape, np.inf, np.float32); Tm[ys, xs] = T+ for _ in range(int(max(m.shape) * 0.06) + 4):+ P = np.pad(Tm, 1, constant_values=np.inf)+ nbmin = np.minimum.reduce([P[1 + dy:1 + dy + m.shape[0], 1 + dx:1 + dx + m.shape[1]]+ for dy in (-1, 0, 1) for dx in (-1, 0, 1)])+ new = np.where(fill & ~np.isfinite(Tm), nbmin, Tm)+ if np.array_equal(np.isfinite(new), np.isfinite(Tm)): Tm = new; break+ Tm = new+ Tm[~np.isfinite(Tm)] = 1.0+ return Tm++ # ------------------------------------------------------------------ props (moving sprites: the leaf boat)+ def sprite(self, polys, fill, outline=INK, line=2.4, veins=None, dark=None):+ """pre-paint a small prop at design scale around its own origin (0, 0); returns a sprite dict"""+ allp = np.vstack(polys)+ pad = 6+ ox, oy = allp[:, 0].min() - pad, allp[:, 1].min() - pad+ w = int(np.ceil((allp[:, 0].max() - ox + pad) * self.s)) + 2+ h = int(np.ceil((allp[:, 1].max() - oy + pad) * self.s)) + 2+ P = [(np.asarray(p, np.float32) - [ox, oy]) * self.s for p in polys]+ box = (0, 0, w, h)+ a = self._poly(P, box)+ rgb = self._wash_rgb(box, a, fill, light=0.1, edge=0.45, dark=dark)+ ss = 3+ im = Image.new('L', (w * ss, h * ss), 0); d = ImageDraw.Draw(im)+ for p in P:+ d.line([(x * ss, y * ss) for x, y in np.vstack([p, p[:1]])], fill=255, width=max(1, int(line * self.s * ss)),+ joint='curve')+ for v in (veins or []):+ q = (np.asarray(v, np.float32) - [ox, oy]) * self.s+ d.line([(x * ss, y * ss) for x, y in q], fill=255, width=max(1, int(line * 0.8 * self.s * ss)), joint='curve')+ o = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255+ rgb = rgb * (1 - o[..., None]) + hexc(outline) * o[..., None]+ a = np.maximum(a, o)+ return dict(rgb=rgb.astype(np.float32), a=a.astype(np.float32), origin=(-ox * self.s, -oy * self.s))++ def prop(self, sprite, t0, t1, fn, z=45.0):+ """a moving prop: fn(u, t) -> dict(x, y, rot=0, sx=1, sy=1, alpha=1) in design units, or None"""+ self.props.append((sprite, t0, t1, fn, z))++ def _prop_pose(self, t0, t1, fn, t):+ if t < t0: return None+ u = 1.0 if t1 <= t0 else min(1.0, (t - t0) / (t1 - t0))+ return fn(u, t)++ def _affine(self, cv, rgb, a, origin, M, pos, alpha=1.0):+ """draw a pre-painted sprite through a 2x2 matrix M (sprite px -> canvas px) at canvas pixel pos"""+ h, w = a.shape+ ox, oy = origin+ corners = np.array([[-ox, -oy], [w - ox, -oy], [w - ox, h - oy], [-ox, h - oy]], np.float32) @ M.T + pos+ x0, y0 = int(np.floor(corners[:, 0].min())) - 1, int(np.floor(corners[:, 1].min())) - 1+ x1, y1 = int(np.ceil(corners[:, 0].max())) + 2, int(np.ceil(corners[:, 1].max())) + 2+ x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, self.W), min(y1, self.H)+ if x1 <= x0 or y1 <= y0: return+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ Mi = np.linalg.inv(M)+ dx, dy = xx + 0.5 - pos[0], yy + 0.5 - pos[1]+ sx = Mi[0, 0] * dx + Mi[0, 1] * dy + ox - 0.5+ sy = Mi[1, 0] * dx + Mi[1, 1] * dy + oy - 0.5+ i0 = np.floor(sx).astype(np.int64); j0 = np.floor(sy).astype(np.int64)+ fx, fy = (sx - i0).astype(np.float32), (sy - j0).astype(np.float32)+ pm = np.concatenate([rgb * a[..., None], a[..., None]], -1)+ pm = np.pad(pm, ((1, 1), (1, 1), (0, 0)))+ i0c = np.clip(i0 + 1, 0, w + 1); i1c = np.clip(i0 + 2, 0, w + 1)+ j0c = np.clip(j0 + 1, 0, h + 1); j1c = np.clip(j0 + 2, 0, h + 1)+ out = (pm[j0c, i0c] * ((1 - fx) * (1 - fy))[..., None] + pm[j0c, i1c] * (fx * (1 - fy))[..., None]+ + pm[j1c, i0c] * ((1 - fx) * fy)[..., None] + pm[j1c, i1c] * (fx * fy)[..., None])+ out *= alpha+ sl = cv[y0:y1, x0:x1]+ sl *= (1 - out[..., 3:4]); sl += out[..., :3]++ def _draw_prop(self, cv, sprite, p):+ if p is None: return+ rot = np.deg2rad(p.get('rot', 0.0))+ c, s_ = np.cos(rot), np.sin(rot)+ R = np.array([[c, s_], [-s_, c]], np.float32)+ S = np.diag([p.get('sx', 1.0), p.get('sy', 1.0)]).astype(np.float32)+ M = R @ S+ self._affine(cv, sprite['rgb'], sprite['a'], sprite['origin'], M,+ np.array([p['x'] * self.s, p['y'] * self.s], np.float32), p.get('alpha', 1.0))++ # ------------------------------------------------------------------ the character+ def act(self, t0, t1, fn):+ """a piece of choreography: fn(u, t) -> pose dict (see `_actor`) or None (hidden)"""+ self.acts.append((t0, t1, fn))+ self._lead = None++ def pose(self, t):+ best = None+ for t0, t1, fn in self.acts:+ if t0 <= t: best = (t0, t1, fn)+ if best is None: return None+ t0, t1, fn = best+ u = 1.0 if t1 <= t0 else min(1.0, (t - t0) / (t1 - t0))+ return fn(u, t)++ def lead_x(self, t):+ """the furthest x (design) the character has reached by time t"""+ if self._lead is None:+ ts = np.arange(0, max(a[1] for a in self.acts) + 1, 0.01) if self.acts else np.zeros(1)+ xs = []+ for tt in ts:+ p = self.pose(tt)+ xs.append(p['x'] if p and p.get('lead', True) else -1e9)+ self._lead = (ts, np.maximum.accumulate(np.array(xs)))+ ts, xm = self._lead+ return float(np.interp(t, ts, xm))++ _OUT = None++ def _outline_local(self):+ if Storybook._OUT is None:+ t = np.linspace(0, 2 * np.pi, 90, endpoint=False)+ nut = []+ for a in t:+ x, y = np.cos(a), np.sin(a)+ y = y * (1.12 if y >= 0 else 0.95)+ x = x * (1 - 0.17 * max(0.0, y / 1.12))+ nut.append((x, y))+ cap = [(1.13 * np.cos(a), -0.5 + 0.68 * np.sin(a)) for a in t if np.sin(a) < -0.2]+ Storybook._OUT = np.array(nut + cap + [(0.0, 1.2), (0.16, -1.48)], np.float32)+ return Storybook._OUT++ def _matrix(self, rot=0.0, k=1.0, axis=90.0, scale=1.0, flip=False):+ u = self.actor_size * self.s * scale+ ph = np.deg2rad(axis)+ av = np.array([np.cos(ph), -np.sin(ph)], np.float32)+ S = k * np.outer(av, av) + k ** -0.5 * (np.eye(2, dtype=np.float32) - np.outer(av, av))+ r = np.deg2rad(rot)+ c, s_ = np.cos(r), np.sin(r)+ R = np.array([[c, s_], [-s_, c]], np.float32)+ F = np.diag([-1.0, 1.0]).astype(np.float32) if flip else np.eye(2, dtype=np.float32)+ return (u * S @ R @ F).astype(np.float32)++ def rest(self, gx, gy, rot=0.0, k=1.0, axis=90.0, scale=1.0, normal=(0.0, -1.0)):+ """centre (design) that puts the character's lowest point exactly on the ground point (gx, gy)"""+ M = self._matrix(rot, k, axis, scale) / self.s+ n = np.asarray(normal, np.float32); n /= np.linalg.norm(n)+ P = self._outline_local() @ M.T+ d = float((-(P @ n)).max())+ return gx + n[0] * d, gy + n[1] * d++ def anchor(self, px, py, local=(0.16, -1.46), rot=0.0, k=1.0, axis=90.0, scale=1.0):+ """centre that puts the character's local point (default: the tip of the stem) at design point (px, py)"""+ M = self._matrix(rot, k, axis, scale) / self.s+ o = M @ np.asarray(local, np.float32)+ return px - float(o[0]), py - float(o[1])++ def when_at(self, x, lead=0.0, dur=0.35, delay=0.0):+ """time window that starts when the character (plus `lead`) first reaches design x"""+ if self.acts: self.lead_x(0)+ ts, xm = self._lead+ i = int(np.searchsorted(xm, x - lead))+ t = float(ts[min(i, len(ts) - 1)]) + delay+ return (t, t + dur)++ def _actor(self, cv, pose, alpha=1.0):+ """render the acorn at a pose. pose keys: x, y (centre of the nut, design px), rot (deg, ccw), k (stretch+ along `axis`, <1 squash), axis (deg), scale, eyes (0 closed .. 1 open), lid ('blink' | 'sleep' | 'happy'),+ look (dx, dy in -1..1), brow (None | 'determined' | 'up' | 'worried'), mouth (None | 'smile' | 'grin' |+ 'o' | 'flat'), blush, clip (ground y in design px: hide everything below), only ('cap')"""+ s = self.s+ M = self._matrix(pose.get('rot', 0.0), pose.get('k', 1.0), pose.get('axis', 90.0), pose.get('scale', 1.0))+ if abs(np.linalg.det(M)) < 1e-6: return+ Mi = np.linalg.inv(M)+ cx, cy = pose['x'] * s, pose['y'] * s+ corners = np.array([[-1.3, -1.65], [1.3, -1.65], [1.3, 1.4], [-1.3, 1.4]], np.float32) @ M.T + [cx, cy]+ x0, y0 = max(int(corners[:, 0].min()) - 2, 0), max(int(corners[:, 1].min()) - 2, 0)+ x1, y1 = min(int(corners[:, 0].max()) + 3, self.W), min(int(corners[:, 1].max()) + 3, self.H)+ if x1 <= x0 or y1 <= y0: return+ ss = 2+ yy, xx = np.mgrid[0:(y1 - y0) * ss, 0:(x1 - x0) * ss].astype(np.float32)+ px = x0 + (xx + 0.5) / ss - cx; py = y0 + (yy + 0.5) / ss - cy+ X = Mi[0, 0] * px + Mi[0, 1] * py+ Y = Mi[1, 0] * px + Mi[1, 1] * py+ sv = np.linalg.svd(M, compute_uv=False)+ pu = 1.0 / (float(sv.min()) * ss) # local units per (super)pixel+ cov = lambda d: np.clip(0.5 - d / pu, 0, 1)+ rot = np.deg2rad(pose.get('rot', 0.0))+ cr, sr = np.cos(rot), np.sin(rot)+ Lx, Ly, Lz = self.light+ Hn = self.light + np.array([0, 0, 1], np.float32); Hn /= np.linalg.norm(Hn)+ rgb = np.zeros(X.shape + (3,), np.float32); A = np.zeros(X.shape, np.float32)++ def over(c, col):+ nonlocal rgb, A+ c = c[..., None] if c.ndim == 2 else c+ rgb = rgb * (1 - c) + col * c+ A[:] = A + c[..., 0] * (1 - A)++ def lit(nx, ny, nz):+ wx, wy = cr * nx + sr * ny, -sr * nx + cr * ny+ diff = np.clip(wx * Lx + wy * Ly + nz * Lz, 0, 1)+ spec = np.clip(wx * Hn[0] + wy * Hn[1] + nz * Hn[2], 0, 1) ** 24+ return diff, spec, wy++ only = pose.get('only')+ if only != 'cap':+ yb = np.where(Y >= 0, Y / 1.12, Y / 0.95)+ xs = X / (1 - 0.17 * np.clip(Y / 1.12, 0, 1))+ r = np.hypot(xs, yb)+ c_nut = cov(r - 1)+ z = np.sqrt(np.clip(1 - r * r, 0, 1))+ nn = np.sqrt(xs * xs + yb * yb + z * z) + 1e-6+ diff, spec, wy = lit(xs / nn, yb / nn, z / nn)+ base = hexc(pose.get('body', NUT))+ col = base * (0.55 + 0.58 * diff)[..., None]+ col = col + hexc('#f0b070') * (0.14 * np.clip(wy, 0, 1) * (1 - diff))[..., None] # warm bounce+ col = col * (1 - 0.16 * smoothstep(0.8, 1.0, r))[..., None]+ stripes = smoothstep(0.82, 1.0, np.cos(xs * np.pi * 3.3)) * (1 - smoothstep(0.6, 0.95, r)) * (Y > -0.1)+ col = col * (1 + 0.06 * stripes)[..., None]+ col = col * (1 - 0.6 * spec[..., None]) + 0.6 * spec[..., None]+ over(c_nut, col)+ over(cov(np.hypot(X, Y - 1.13) - 0.09) * c_nut, hexc('#6d4224'))+ self._face(pose, X, Y, cov, over, c_nut)+ # cap+ rc = np.hypot(X / 1.13, (Y + 0.5) / 0.68)+ rim = -0.28 + 0.15 * (1 - np.clip(X / 1.13, -1, 1) ** 2)+ c_cap = cov(rc - 1) * cov(Y - rim)+ z = np.sqrt(np.clip(1 - rc * rc, 0, 1))+ nx_, ny_ = X / 1.13, (Y + 0.5) / 0.68+ nn = np.sqrt(nx_ ** 2 + ny_ ** 2 + z ** 2) + 1e-6+ diff, spec, wy = lit(nx_ / nn, ny_ / nn, z / nn)+ col = hexc(pose.get('cap', CAP)) * (0.55 + 0.6 * diff)[..., None]+ g1, g2 = (X + Y) * 4.4, (X - Y) * 4.4+ dl = np.minimum(np.abs(g1 - np.round(g1)), np.abs(g2 - np.round(g2))) / 4.4+ c_line = cov(dl - 0.032) * cov(Y - (rim - 0.1))+ col = col * (1 - 0.45 * c_line[..., None]) + hexc(CAP_LINE) * 0.45 * c_line[..., None]+ band = cov(-(Y - (rim - 0.11)))+ col = col * (1 - 0.5 * band[..., None]) + (hexc('#b07a4a') * (0.7 + 0.4 * diff)[..., None]) * 0.5 * band[..., None]+ col = col * (1 - 0.35 * spec[..., None]) + 0.35 * spec[..., None]+ over(c_cap, col)+ # stem+ ax_, ay_, bx_, by_ = 0.03, -1.12, 0.16, -1.46+ t = np.clip(((X - ax_) * (bx_ - ax_) + (Y - ay_) * (by_ - ay_)) / ((bx_ - ax_) ** 2 + (by_ - ay_) ** 2), 0, 1)+ d = np.hypot(X - ax_ - t * (bx_ - ax_), Y - ay_ - t * (by_ - ay_))+ over(cov(d - 0.085), hexc('#5e3820') * (1 + 0.25 * (t < 0.35))[..., None])+ if pose.get('brow') and only != 'cap': self._brows(pose, X, Y, cov, over)+ # downsample, clip under the ground+ h, w = y1 - y0, x1 - x0+ prem = (rgb * A[..., None]).reshape(h, ss, w, ss, 3).mean((1, 3))+ A = A.reshape(h, ss, w, ss).mean((1, 3))+ if pose.get('clip') is not None:+ gy = pose['clip'] * s+ rows = np.arange(y0, y1, dtype=np.float32) + 0.5+ keep = np.clip(gy - rows, 0, 1)[:, None]+ prem *= keep[..., None]; A = A * keep+ A = A * alpha; prem = prem * alpha+ sl = cv[y0:y1, x0:x1]+ sl *= (1 - A[..., None]); sl += prem++ def _face(self, pose, X, Y, cov, over, c_nut):+ if pose.get('blush', True):+ for sx in (-1, 1):+ d = np.hypot((X - sx * 0.6) / 0.17, (Y - 0.56) / 0.09) - 1+ over(np.clip(0.5 - d * 2.5, 0, 1) * 0.35 * c_nut, hexc('#e9776a'))+ o = float(pose.get('eyes', 1.0))+ lx, ly = pose.get('look', (0.0, 0.0))+ lid = pose.get('lid', 'blink')+ for sx in (-1, 1):+ ex, ey = sx * 0.36, 0.30+ if o > 0.22:+ ry = 0.255 * o+ d = np.hypot((X - ex) / 0.19, (Y - ey) / ry) - 1+ ce = cov(d * 0.19) * c_nut+ white = np.ones(X.shape + (3,), np.float32) * hexc('#fffdf8')+ white = white * (1 - 0.12 * np.clip((Y - ey) / ry, 0, 1))[..., None]+ over(ce, white)+ pxc, pyc = ex + lx * 0.075, ey + ly * 0.09 * o+ dp = np.hypot(X - pxc, (Y - pyc) / max(min(1.0, o * 1.1), 0.3)) - 0.118+ over(cov(dp) * ce, hexc('#161a26'))+ dh = np.hypot(X - (pxc - 0.04), Y - (pyc - 0.05)) - 0.042+ over(cov(dh) * ce, hexc('#ffffff'))+ else:+ w = 0.17+ tt = np.clip((X - ex) / w, -1, 1)+ if lid == 'sleep': yc = ey + 0.05 * (1 - tt * tt)+ elif lid == 'happy': yc = ey + 0.06 - 0.09 * (1 - tt * tt)+ else: yc = ey + 0.02 * np.ones_like(tt)+ d = np.maximum(np.abs(Y - yc), (np.abs(X - ex) - w) * 3) - 0.035+ over(cov(d) * c_nut, hexc('#2a1d14'))+ mouth = pose.get('mouth')+ if mouth == 'smile' or mouth == 'flat':+ w, dep = 0.17, (0.08 if mouth == 'smile' else 0.0)+ tt = np.clip(X / w, -1, 1)+ yc = 0.64 + dep * (1 - tt * tt)+ d = np.maximum(np.abs(Y - yc), (np.abs(X) - w) * 3) - 0.032+ over(cov(d) * c_nut, hexc('#3a2216'))+ elif mouth == 'grin':+ d = np.maximum(np.hypot(X / 0.2, (Y - 0.6) / 0.17) - 1, -(Y - 0.6) / 0.17) * 0.17+ over(cov(d) * c_nut, hexc('#4a2018'))+ dt = np.hypot((X + 0.02) / 0.1, (Y - 0.72) / 0.05) - 1+ over(cov(np.maximum(dt * 0.05, d)) * c_nut, hexc('#e0736a'))+ elif mouth == 'o':+ d = np.hypot(X / 0.085, (Y - 0.66) / 0.11) - 1+ over(cov(d * 0.085) * c_nut, hexc('#4a2018'))++ def _brows(self, pose, X, Y, cov, over):+ b = pose['brow']+ for sx in (-1, 1):+ if b == 'determined': (ax_, ay_), (bx_, by_) = (sx * 0.62, -0.04), (sx * 0.16, 0.07)+ elif b == 'worried': (ax_, ay_), (bx_, by_) = (sx * 0.6, 0.06), (sx * 0.18, -0.04)+ else: (ax_, ay_), (bx_, by_) = (sx * 0.58, -0.05), (sx * 0.16, -0.08)+ t = np.clip(((X - ax_) * (bx_ - ax_) + (Y - ay_) * (by_ - ay_)) / ((bx_ - ax_) ** 2 + (by_ - ay_) ** 2), 0, 1)+ d = np.hypot(X - ax_ - t * (bx_ - ax_), Y - ay_ - t * (by_ - ay_))+ over(cov(d - 0.05 * (1 - 0.4 * t)), hexc('#2a1a10'))++ def _shadow(self, cv, x, y, w, strength=0.22):+ s = self.s+ rx, ry = w * s, w * 0.2 * s+ x0, x1 = max(int(x * s - rx * 1.6), 0), min(int(x * s + rx * 1.6) + 1, self.W)+ y0, y1 = max(int(y * s - ry * 2.2), 0), min(int(y * s + ry * 2.2) + 1, self.H)+ if x1 <= x0 or y1 <= y0: return+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ d = ((xx + 0.5 - x * s) / rx) ** 2 + ((yy + 0.5 - y * s) / ry) ** 2+ a = strength * np.exp(-d * 1.6)+ cv[y0:y1, x0:x1] *= (1 - a[..., None] * (1 - hexc('#6f6457')))++ # ------------------------------------------------------------------ FX (timed events, drawn per frame)+ def fx(self, kind, t0, x, y, **kw):+ """timed effect at design point (x, y): 'impact', 'dust', 'ripple', 'specks', 'sparkle', 'confetti'"""+ kw.setdefault('seed', self._seed())+ if kind == 'confetti':+ r = np.random.default_rng(kw['seed'])+ n = kw.get('n', 60)+ kw['pieces'] = [dict(kind=r.choice(['rect', 'rect', 'squig', 'dot', 'tri']),+ col=CONFETTI[r.integers(len(CONFETTI))],+ vx=r.uniform(-1, 1) * kw.get('spread', 520), vy=-r.uniform(0.4, 1.0) * kw.get('up', 900),+ x0=x + r.uniform(-1, 1) * kw.get('wide', 20), y0=y,+ size=r.uniform(10, 19) * kw.get('size', 1.0), spin=r.uniform(-9, 9),+ flip=r.uniform(5, 13),+ ph=r.uniform(0, 6.28), sway=r.uniform(8, 26), delay=r.uniform(0, kw.get('stagger', 0.25)),+ life=r.uniform(1.1, 1.8) * kw.get('life', 1.0), th=r.uniform(0, 6.28))+ for _ in range(n)]+ self.fxs.append((kind, t0, x, y, kw))++ def _fx_draw(self, d, ss, t, only=None, exclude=()):+ s = self.s * ss+ ink = tuple(int(c * 255) for c in hexc(INK))+ for kind, t0, x, y, kw in self.fxs:+ if only is not None and kind not in only: continue+ if kind in exclude: continue+ tau = t - t0+ if tau < 0: continue+ if kind == 'impact':+ life = kw.get('life', 0.26)+ if tau > life: continue+ u = tau / life+ r = np.random.default_rng(kw['seed'])+ n = kw.get('n', 7); R0 = kw.get('r', 60)+ for i in range(n):+ a = np.deg2rad(kw.get('a0', 195) + (kw.get('a1', 345) - kw.get('a0', 195)) * i / (n - 1)+ + r.uniform(-6, 6))+ ri = R0 * (0.95 + 0.55 * self.ease(u, 'out'))+ L = R0 * 0.32 * (1 - u) * r.uniform(0.7, 1.2)+ p0 = (x + np.cos(a) * ri, y + np.sin(a) * ri)+ p1 = (x + np.cos(a) * (ri + L), y + np.sin(a) * (ri + L))+ d.line([(p0[0] * s, p0[1] * s), (p1[0] * s, p1[1] * s)], fill=ink + (255,),+ width=max(1, int(3.2 * s)))+ elif kind == 'dust':+ life = kw.get('life', 0.5)+ if tau > life: continue+ r = np.random.default_rng(kw['seed'])+ n = kw.get('n', 6); spread = kw.get('spread', 70); size = kw.get('size', 13)+ dirs = kw.get('dirs', (-1, 1))+ for i in range(n):+ dl = r.uniform(0, 0.08)+ u = (tau - dl) / (life - dl)+ if u < 0 or u > 1: continue+ sd = dirs[i % len(dirs)]+ ex = self.ease(u, 'out')+ px = x + sd * (14 + spread * r.uniform(0.5, 1.1) * ex)+ py = y - 4 - r.uniform(4, 22) * ex+ rr = size * r.uniform(0.6, 1.2) * np.sin(np.pi * min(1, u * 1.15)) ** 0.6+ if rr < 0.6: continue+ bb = [(px - rr) * s, (py - rr) * s, (px + rr) * s, (py + rr) * s]+ d.ellipse(bb, fill=(253, 251, 246, 255), outline=(128, 132, 156, 255), width=max(1, int(1.8 * s)))+ elif kind == 'ripple':+ life = kw.get('life', 0.8)+ if tau > life: continue+ for j in range(kw.get('n', 2)):+ u = tau / life - j * 0.22+ if u < 0 or u > 1: continue+ rx = 16 + kw.get('r', 90) * self.ease(u, 'out'); ry = rx * 0.2+ al = int(255 * (1 - u) ** 1.2)+ d.ellipse([(x - rx) * s, (y - ry) * s, (x + rx) * s, (y + ry) * s],+ outline=(61, 111, 148, al), width=max(1, int(2.6 * s)))+ elif kind == 'specks':+ life = kw.get('life', 0.55)+ if tau > life: continue+ r = np.random.default_rng(kw['seed'])+ col = tuple(int(c * 255) for c in hexc(kw.get('colour', '#6d4224')))+ for i in range(kw.get('n', 9)):+ vx = r.uniform(-1, 1) * 260; vy = -r.uniform(250, 520)+ px = x + vx * tau; py = y + vy * tau + 0.5 * 2200 * tau * tau+ rr = r.uniform(2.8, 5.5)+ if py > y + 4: continue # landed back on the ground+ d.ellipse([(px - rr) * s, (py - rr) * s, (px + rr) * s, (py + rr) * s], fill=col + (255,))+ elif kind == 'sparkle':+ life = kw.get('life', 0.5)+ if tau > life: continue+ u = tau / life+ R = kw.get('r', 14) * np.sin(np.pi * u) ** 0.7+ col = tuple(int(c * 255) for c in hexc(kw.get('colour', '#f2b632')))+ k = 0.28+ pts = []+ for i in range(8):+ a = np.pi / 4 * i+ rr = R if i % 2 == 0 else R * k+ pts.append(((x + np.cos(a) * rr) * s, (y + np.sin(a) * rr) * s))+ d.polygon(pts, fill=col + (255,))+ elif kind == 'confetti':+ for pc in kw['pieces']:+ tt = tau - pc['delay']+ if tt < 0 or tt > pc['life']: continue+ c_ = 3.2+ e = (1 - np.exp(-c_ * tt)) / c_+ vt = 120.0+ px = pc['x0'] + pc['vx'] * e + pc['sway'] * np.sin(pc['flip'] * 0.5 * tt + pc['ph'])+ py = pc['y0'] + (pc['vy'] - vt) * e + vt * tt + 160 * tt * tt+ al = int(255 * min(1, (pc['life'] - tt) / 0.3))+ col = tuple(int(c * 255) for c in hexc(pc['col'])) + (al,)+ th = pc['th'] + pc['spin'] * tt+ fl = np.cos(pc['flip'] * tt + pc['ph'])+ sz = pc['size']+ ca, sa = np.cos(th), np.sin(th)+ if pc['kind'] == 'rect':+ loc = [(-sz * 0.5 * fl, -sz * 0.22), (sz * 0.5 * fl, -sz * 0.22), (sz * 0.5 * fl, sz * 0.22),+ (-sz * 0.5 * fl, sz * 0.22)]+ d.polygon([((px + lx * ca - ly * sa) * s, (py + lx * sa + ly * ca) * s) for lx, ly in loc], fill=col)+ elif pc['kind'] == 'tri':+ loc = [(0, -sz * 0.45), (sz * 0.42 * fl, sz * 0.3), (-sz * 0.42 * fl, sz * 0.3)]+ d.polygon([((px + lx * ca - ly * sa) * s, (py + lx * sa + ly * ca) * s) for lx, ly in loc], fill=col)+ elif pc['kind'] == 'dot':+ rr = sz * 0.28+ d.ellipse([(px - rr) * s, (py - rr) * s, (px + rr) * s, (py + rr) * s], fill=col)+ else:+ loc = [(-sz * 0.7 + sz * 0.35 * i, sz * 0.18 * (1 if i % 2 else -1)) for i in range(5)]+ d.line([((px + lx * ca - ly * sa) * s, (py + lx * sa + ly * ca) * s) for lx, ly in loc], fill=col,+ width=max(1, int(2.2 * s)), joint='curve')++ def _speedlines(self, d, ss, t, pose):+ dt = 1 / 30+ p0 = self.pose(t - dt)+ if p0 is None or pose.get('speed') is False: return+ vx, vy = (pose['x'] - p0['x']) / dt, (pose['y'] - p0['y']) / dt+ v = np.hypot(vx, vy)+ thr = pose.get('speed_min', 650)+ if v < thr: return+ s = self.s * ss+ ux, uy = vx / v, vy / v+ nx, ny = -uy, ux+ u = self.actor_size * pose.get('scale', 1.0)+ k = min(1.0, (v - thr) / 500)+ r = np.random.default_rng(int(t * 1000) % 100000)+ col = tuple(int(c * 255) for c in hexc('#77767f'))+ for off in (-0.75, -0.1, 0.6):+ o = off * u + r.uniform(-4, 4)+ st = 1.0 * u + r.uniform(0, 10)+ L = u * (0.9 + 1.0 * k) * r.uniform(0.7, 1.2)+ a = (pose['x'] - ux * st + nx * o, pose['y'] - uy * st + ny * o)+ b = (a[0] - ux * L, a[1] - uy * L)+ d.line([(a[0] * s, a[1] * s), (b[0] * s, b[1] * s)], fill=col + (int(220 * (0.55 + 0.45 * k)),),+ width=max(1, int(3.0 * s)))++ def _overlay(self, cv, t, pose=None, fx=True, only=None):+ ss = 2+ im = Image.new('RGBA', (self.W * ss, self.H * ss), (0, 0, 0, 0))+ d = ImageDraw.Draw(im)+ if fx: self._fx_draw(d, ss, t, only)+ if pose is not None: self._speedlines(d, ss, t, pose)+ bb = im.getbbox()+ if not bb: return+ x0, y0 = bb[0] // ss, bb[1] // ss+ x1, y1 = min(self.W, -(-bb[2] // ss)), min(self.H, -(-bb[3] // ss))+ crop = im.crop((x0 * ss, y0 * ss, x1 * ss, y1 * ss)).resize((x1 - x0, y1 - y0), Image.BOX)+ o = np.asarray(crop, np.float32) / 255+ a = o[..., 3:4]+ sl = cv[y0:y1, x0:x1]+ sl *= (1 - a); sl += o[..., :3] * a++ # ------------------------------------------------------------------ compositing+ def _draw_layer(self, cv, L, t, full=False):+ p = 1.0 if full else self._progress(L, t)+ if p <= 0: return+ a, rgb = L.a, L.rgb+ if p < 1 and L.pop is not None:+ sc = max(1e-3, self.ease(p, 'back'))+ M = np.eye(2, dtype=np.float32) * sc+ org = (L.pop[0] - L.x0, L.pop[1] - L.y0)+ self._affine(cv, rgb, a, org, M, np.array(L.pop, np.float32), min(1.0, p * 3))+ return+ if p < 1 and L.rev is not None:+ q = p * (1 + L.soft)+ m = np.clip((q - L.rev) / L.soft, 0, 1)+ if L.wet:+ front = (m * (1 - m) * 4)[..., None]+ rgb = rgb * (1 - L.wet * front)+ a = a * m+ elif p < 1 and L.rev is None:+ a = a * p+ h, w = a.shape+ x0, y0 = L.x0, L.y0+ ax0, ay0, ax1, ay1 = max(x0, 0), max(y0, 0), min(x0 + w, self.W), min(y0 + h, self.H)+ if ax1 <= ax0 or ay1 <= ay0: return+ aa = a[ay0 - y0:ay1 - y0, ax0 - x0:ax1 - x0, None]+ cc = rgb[ay0 - y0:ay1 - y0, ax0 - x0:ax1 - x0]+ sl = cv[ay0:ay1, ax0:ax1]+ sl *= (1 - aa); sl += cc * aa++ def _progress(self, L, t):+ if L.follow is not None:+ lead, xa, xb = L.follow+ p = float(np.clip((self.lead_x(t) + lead - xa) / max(xb - xa, 1e-3), 0, 1))+ if L.pre is not None: # the part left of the start is drawn by time+ t0, t1, upto = L.pre+ p = max(p, upto * self.ease((t - t0) / max(t1 - t0, 1e-3), 'sine') if t > t0 else 0.0)+ return p+ t0, t1 = L.when+ if t <= t0: return 0.0 if t1 > t0 or t < t0 else 1.0+ if t >= t1: return 1.0+ return self.ease((t - t0) / (t1 - t0), L.ease)++ def _compose(self, t, actor=True, fx=True, full=False, ghosts=None, props=True):+ cv = self.base.copy()+ pose = self.pose(t) if actor else None+ items = [(L.z, 0, L) for L in self.layers]+ if props: items += [(z, 1, (sp, t0, t1, fn)) for sp, t0, t1, fn, z in self.props]+ items.append((50.0, 2, None))+ items.sort(key=lambda it: it[0])+ for z, kind, obj in items:+ if kind == 0: self._draw_layer(cv, obj, t, full)+ elif kind == 1:+ sp, t0, t1, fn = obj+ self._draw_prop(cv, sp, self._prop_pose(t0, t1, fn, t))+ elif kind == 2:+ if ghosts: ghosts(cv)+ if pose is not None:+ if pose.get('shadow'):+ gx, gy, wsh, st = pose['shadow']+ self._shadow(cv, gx, gy, wsh, st)+ self._actor(cv, pose)+ for extra in pose.get('also', []):+ self._actor(cv, extra)+ if fx or pose is not None: self._overlay(cv, t, pose, fx)+ return cv++ def _to_image(self, cv):+ return Image.fromarray((np.clip(cv * self.grain, 0, 1) * 255 + 0.5).astype(np.uint8), 'RGB')++ def frame(self, t):+ """the animation frame at time t (seconds) as a PIL image"""+ return self._to_image(self._compose(t))++ # ------------------------------------------------------------------ outputs+ def gif(self, path, fps=15.0, t_end=None, hold=1.6, colours=255, sample_every=5, bayer=2.4, start=0.0):+ """render the animation frame by frame into a looping GIF: one shared palette (sampled from every+ `sample_every`-th frame, saturated pixels weighted x4), a fixed 4x4 Bayer dither, unchanged pixels written+ as a transparent magenta index so LZW only pays for what moves. Only one frame is held as floats at a time."""+ t_end = t_end if t_end is not None else max(a[1] for a in self.acts)+ times = np.arange(start, t_end + 1e-6, 1 / fps)+ if times[-1] < t_end - 1e-6: times = np.append(times, t_end)+ B = np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]], np.float32) / 16 - 0.5+ dith = np.tile(B, (self.H // 4 + 1, self.W // 4 + 1))[:self.H, :self.W, None] * bayer++ def render(t):+ a = np.asarray(self.frame(t), np.float32) + dith+ return Image.fromarray(np.clip(a + 0.5, 0, 255).astype(np.uint8), 'RGB')++ samples = []+ for t in list(times[::sample_every]) + [times[-1]]:+ px = np.asarray(render(t)).reshape(-1, 3)+ samples.append(px[::3])+ px = np.concatenate(samples)+ sat = px.max(1).astype(int) - px.min(1).astype(int)+ px = np.concatenate([px] + [px[sat > 70]] * 4)+ wq = 512+ px = px[:(len(px) // wq) * wq].reshape(-1, wq, 3)+ pal_im = Image.fromarray(px, 'RGB').quantize(colors=colours, method=Image.Quantize.MEDIANCUT,+ dither=Image.Dither.NONE)+ palette = pal_im.getpalette()[:colours * 3]+ palette += palette[:3] * (256 - colours) # spare slots repeat colour 0 while quantizing ...+ pal_im.putpalette(palette)+ palette = palette[:765] + [255, 0, 255] # ... and 255 becomes the magenta 'unchanged' marker+ idx, prev = [], None+ for t in times:+ q = np.asarray(render(t).quantize(palette=pal_im, dither=Image.Dither.NONE)).copy()+ q[q == 255] = 0+ o = q.copy()+ if prev is not None: o[q == prev] = 255+ prev = q+ idx.append(o)+ frames = []+ for o in idx:+ im = Image.fromarray(o.astype(np.uint8), 'P'); im.putpalette(palette); frames.append(im)+ cs = [int(round(100 * (i + 1) / fps)) - int(round(100 * i / fps)) for i in range(len(frames))]+ dur = [10 * c for c in cs] # GIF delays are centiseconds: 15 fps -> 7, 7, 6, ...+ dur[-1] = int(hold * 1000)+ frames[0].save(path, save_all=True, append_images=frames[1:], duration=dur, loop=0, optimize=False,+ transparency=255, disposal=1)+ _strip_local_tables(path)+ return len(frames)++ def journey(self, times, t_world=None, arc=None, arc_colour=PENCIL, ghost_alpha=None, labels=None, label_font='hand',+ prop_arcs=(), world_fx=False, final=True, props=True, prop_arc_colour='#e39a62'):+ """the finished world with the character multiply-exposed at the poses `times` on a pencil motion arc.+ arc = (t0, t1) of the path to trace; ghost_alpha: list of alphas (default rising 0.62 -> 1);+ labels: list of (text, dx, dy) sound-words in pencil next to each pose; prop_arcs: [(t0, t1, fn)] faint+ dotted paths for moving props"""+ t_world = t_world if t_world is not None else max(a[1] for a in self.acts)+ n = len(times)+ ghost_alpha = ghost_alpha or list(np.linspace(0.62, 1.0, n))+ s = self.s++ def ghosts(cv):+ ss = 2+ im = Image.new('RGBA', (self.W * ss, self.H * ss), (0, 0, 0, 0)); d = ImageDraw.Draw(im)+ col = tuple(int(c * 255) for c in hexc(arc_colour))+ pcol = tuple(int(c * 255) for c in hexc(prop_arc_colour))+ for (pt0, pt1, fn) in prop_arcs:+ pts = [fn(min(1, (tt - pt0) / (pt1 - pt0)), tt) for tt in np.arange(pt0, pt1, 1 / 120)]+ self._dotted(d, [(p['x'], p['y']) for p in pts if p], ss, pcol + (150,), 11, 2.2)+ if arc:+ pts = [self.pose(tt) for tt in np.arange(arc[0], arc[1], 1 / 200)]+ pts = [(p['x'], p['y']) for p in pts if p is not None and p.get('clip') is None]+ self._dotted(d, pts, ss, col + (210,), 15, 3.0, chevrons=6)+ self._paste_overlay(cv, im, ss)+ for i, tt in enumerate(times):+ p = self.pose(tt)+ for sp, t0, t1, fn, z in self.props:+ pp = self._prop_pose(t0, t1, fn, tt)+ if pp is not None and pp.get('ghost', False):+ self._draw_prop(cv, sp, dict(pp, alpha=ghost_alpha[i] * pp.get('alpha', 1.0)))+ if p is None: continue+ if p.get('shadow'):+ gx, gy, wsh, st = p['shadow']+ self._shadow(cv, gx, gy, wsh, st * ghost_alpha[i])+ im2 = Image.new('RGBA', (self.W * ss, self.H * ss), (0, 0, 0, 0)); d2 = ImageDraw.Draw(im2)+ self._fx_draw(d2, ss, tt, exclude=('confetti',))+ self._speedlines(d2, ss, tt, p)+ self._paste_overlay(cv, im2, ss, ghost_alpha[i])+ self._actor(cv, p, ghost_alpha[i])+ for extra in p.get('also', []):+ self._actor(cv, extra, ghost_alpha[i])+ if final:+ p = self.pose(t_world)+ if p is not None: self._actor(cv, p)+ if labels:+ im = Image.new('RGBA', (self.W * ss, self.H * ss), (0, 0, 0, 0)); d = ImageDraw.Draw(im)+ ft = load_font(label_font, 34 * s * ss)+ col = tuple(int(c * 255) for c in hexc('#6f6e78'))+ for i, lab in enumerate(labels):+ if not lab: continue+ txt, dx, dy = lab+ p = self.pose(times[i])+ d.text(((p['x'] + dx) * s * ss, (p['y'] + dy) * s * ss), txt, font=ft, fill=col + (235,),+ anchor='mm')+ self._paste_overlay(cv, im, ss)++ self.canvas = self._compose(t_world, actor=False, fx=False, full=True, ghosts=ghosts, props=props)+ if world_fx:+ ss = 2+ im = Image.new('RGBA', (self.W * ss, self.H * ss), (0, 0, 0, 0))+ self._fx_draw(ImageDraw.Draw(im), ss, t_world, only=('confetti',))+ self._paste_overlay(self.canvas, im, ss)+ return self._to_image(self.canvas)++ def _dotted(self, d, pts, ss, col, gap, r, chevrons=0):+ if len(pts) < 2: return+ P = _resample(np.asarray(pts, np.float32), 1.0)+ s = self.s * ss+ cum = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))])+ for g in np.arange(gap / 2, cum[-1], gap):+ i = int(np.searchsorted(cum, g))+ x, y = P[min(i, len(P) - 1)]+ d.ellipse([(x - r) * s, (y - r) * s, (x + r) * s, (y + r) * s], fill=col)+ if chevrons:+ for g in np.linspace(0, cum[-1], chevrons + 2)[1:-1]:+ i = int(np.searchsorted(cum, g))+ i = min(max(i, 2), len(P) - 3)+ x, y = P[i]; tx, ty = P[i + 2] - P[i - 2]; tl = np.hypot(tx, ty) + 1e-6; tx, ty = tx / tl, ty / tl+ k = 11+ a = (x - tx * k + ty * k * 0.7, y - ty * k - tx * k * 0.7)+ b = (x - tx * k - ty * k * 0.7, y - ty * k + tx * k * 0.7)+ d.line([(a[0] * s, a[1] * s), (x * s, y * s), (b[0] * s, b[1] * s)], fill=col,+ width=max(1, int(2.8 * s)), joint='curve')++ def _paste_overlay(self, cv, im, ss, alpha=1.0):+ bb = im.getbbox()+ if not bb: return+ x0, y0 = bb[0] // ss, bb[1] // ss+ x1, y1 = min(self.W, -(-bb[2] // ss)), min(self.H, -(-bb[3] // ss))+ o = np.asarray(im.crop((x0 * ss, y0 * ss, x1 * ss, y1 * ss)).resize((x1 - x0, y1 - y0), Image.BOX),+ np.float32) / 255+ a = o[..., 3:4] * alpha+ sl = cv[y0:y1, x0:x1]+ sl *= (1 - a); sl += o[..., :3] * a++ def stage(self, name, t=None):+ """keyframe snapshot for the stage tools: frame(t), or the current poster canvas when t is None"""+ img = self.frame(t) if t is not None else self._to_image(self.canvas)+ self.stages.append((name, img))++ def save(self, path, stages_dir=None, quality=88):+ img = self._to_image(self.canvas)+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=quality, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return img+++def _strip_local_tables(path):+ """Pillow repeats the palette as a local colour table on every frame; drop copies equal to the global table"""+ b = bytearray(open(path, 'rb').read())+ flags = b[10]; gsize = 2 << (flags & 7); gct = bytes(b[13:13 + 3 * gsize]) if flags & 0x80 else None+ out = b[:13 + (3 * gsize if gct else 0)]; i = len(out)+ while i < len(b):+ t = b[i]+ if t == 0x21:+ j = i + 2+ while b[j]: j += b[j] + 1+ out += b[i:j + 1]; i = j + 1+ elif t == 0x2C:+ pf = b[i + 9]; desc = bytearray(b[i:i + 10]); i += 10+ if pf & 0x80:+ n = 3 * (2 << (pf & 7)); tab = bytes(b[i:i + n])+ if tab == gct: desc[9] = pf & 0x78; i += n+ else: desc += tab; i += n+ j = i + 1+ while b[j]: j += b[j] + 1+ out += desc + b[i:j + 1]; i = j + 1+ else:+ out += b[i:]; break+ open(path, 'wb').write(bytes(out))diff --git a/lib/thermal.py b/lib/thermal.pynew file mode 100644index 0000000..8655cc8--- /dev/null+++ b/lib/thermal.py@@ -0,0 +1,708 @@+"""thermal — a thermal-camera (long-wave infrared) picture: paint a temperature field, then look at it through an+uncooled microbolometer camera (numpy + Pillow only).++A thermal camera sees no colour and no light, only how warm every surface is, so the picture is never painted in RGB.+It is built in three passes, the same way the real thing works:++ 1. scene (degrees C) a float field at 2x the sensor resolution. The room sits at ambient, with warm air+ layered under the ceiling and a cooler floor (`room`). Every object is painted at its own+ temperature with its own gradients (`surface`): a pot is hottest at the base, a cat's nose+ and ears run cooler than its eyes, window glass is coldest at the bottom. Shiny metal does+ not show its own temperature but the room it reflects: apparent T = e*T + (1-e)*T_reflected+ (`emissivity=`). Heat then leaks out of hot things:+ soak conduction / radiation stains nearby surfaces (the splashback behind a stove);+ plume buoyant hot air and steam rise along a wavering path, widen, cool while they+ mix and break into eddies and wisps; the same call with a downward path is cold+ air pouring out of an open fridge;+ pool cold air spreading over the floor in soft tongues;+ prints warm feet leave prints that fade and spread out with age;+ reflect glazed tiles mirror warm things (blurred, faint, fading with distance).+ 2. camera the field goes through the optics (blur), is box-sampled onto the sensor grid (640 x 360 by+ default), gets temporal noise (NETD) and fixed-pattern column / row stripes and the+ centre-cool "narcissus" vignette; a detail enhancer boosts small differences (seams, tile+ grout, fur edges) while leaving big steps alone; automatic gain control maps degrees to+ 0..1 as a mix of a linear span and plateau histogram equalisation, so a room at 18-24 C+ still gets most of the colours while the stove saturates; the 0..1 image is upscaled+ (bilinear, a touch of the pixel grid kept) and coloured through a false-colour palette+ (iron, rainbow, white_hot, black_hot, arctic).+ 3. OSD drawn crisp at output resolution on top: translucent status bars (REC timer, date,+ battery, emissivity), spot meters, boxes, hottest / coldest markers, a line profile inset and+ a scale bar whose ticks sit where the (non-linear) AGC puts them. Every number is read off+ the sensor image of that stage, so the readings always agree with the colours.++Stages are cheap: `stage(name)` keeps a copy of the field and the OSD items so far; `save()` renders every stage+with the final gain settings, so colours do not jump between snapshots.++Canvas coordinates (px of the output picture) are used everywhere; temperatures in degrees C.++ from thermal import Thermal+ t = Thermal(1920, 1080, seed=1, ambient=21)+ t.room(top=25, bottom=19)+ pot = t.rect(860, 380, 1000, 470, r=8)+ t.soak(pot, 95, reach=60, strength=0.4) # the wall behind warms up+ t.surface(pot, t.ramp((0, 470), 98, (0, 380), 88)) # hottest at the base+ t.plume(t.rise(960, 380, 300, sway=30), 99, w0=10, w1=90)+ t.statusbar(rec='00:01:12'); t.scalebar(560, 1018, 1360, 1034)+ t.spot(930, 430, 'Sp1'); t.hottest()+ t.save('out.jpg')+"""+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, load_font, blob_pts+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++# false-colour palettes: (position 0..1, colour) stops+PALETTES = {+ 'iron': [(0.00, '#000005'), (0.06, '#0d0a40'), (0.14, '#1f0e6e'), (0.24, '#3d1192'), (0.36, '#6a14a0'),+ (0.47, '#9c1c94'), (0.57, '#c92f72'), (0.66, '#e64d45'), (0.75, '#f57322'), (0.84, '#faa012'),+ (0.92, '#fdd23a'), (0.97, '#fff38f'), (1.00, '#fffff0')],+ 'rainbow': [(0.00, '#000000'), (0.10, '#16106a'), (0.24, '#1d4fd6'), (0.38, '#13b8d4'), (0.50, '#1fbf5a'),+ (0.62, '#c9dc1e'), (0.74, '#f7a215'), (0.87, '#e8301c'), (1.00, '#fff0ee')],+ 'white_hot': [(0.0, '#000000'), (1.0, '#ffffff')],+ 'black_hot': [(0.0, '#ffffff'), (1.0, '#000000')],+ 'arctic': [(0.00, '#030719'), (0.25, '#0d2f7c'), (0.50, '#2a92cf'), (0.66, '#9fb7b0'), (0.80, '#e8a62a'),+ (1.00, '#fff3c4')],+}++WHITE, BLACK, RED, BLUE = (255, 255, 255), (0, 0, 0), (235, 40, 40), (70, 150, 255)+++def lut(name, n=1024):+ stops = PALETTES[name]+ pos = np.array([p for p, _ in stops], np.float32)+ cols = np.stack([hexc(c) for _, c in stops])+ x = np.linspace(0, 1, n, dtype=np.float32)+ return np.stack([np.interp(x, pos, cols[:, i]) for i in range(3)], 1)+++class Thermal:+ def __init__(self, W=1920, H=1080, sensor=(640, 360), ss=2, seed=0, ambient=21.0):+ self.W, self.H = W, H+ self.sw, self.sh = sensor+ self.ss = ss+ self.fw, self.fh = self.sw * ss, self.sh * ss+ self.kx, self.ky = self.fw / W, self.fh / H+ self.k = 0.5 * (self.kx + self.ky)+ self.amb = float(ambient)+ self.seed = seed+ self.rng = np.random.default_rng(seed)+ yy, xx = np.mgrid[0:self.fh, 0:self.fw].astype(np.float32)+ self.X = (xx + 0.5) / self.kx+ self.Y = (yy + 0.5) / self.ky+ self.T = np.full((self.fh, self.fw), self.amb, np.float32)+ r = np.random.default_rng(seed + 7919)+ self._netd = r.normal(0, 1, (self.sh, self.sw)).astype(np.float32)+ self._col = r.normal(0, 1, self.sw).astype(np.float32)+ self._row = r.normal(0, 1, self.sh).astype(np.float32)+ self._cache = {}+ self.osd, self.stages = [], []+ self._lastfit = None+ self.camera()++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------------ shapes -> masks (field resolution)+ def _fpts(self, pts):+ P = np.asarray(pts, np.float32).reshape(-1, 2)+ return np.stack([P[:, 0] * self.kx, P[:, 1] * self.ky], 1)++ def _draw(self, P, pad, fn, ss=3):+ """rasterise in a supersampled bounding-box tile only (fast for small shapes)"""+ m = np.zeros((self.fh, self.fw), np.float32)+ x0, y0 = np.floor(P.min(0) - pad).astype(int)+ x1, y1 = np.ceil(P.max(0) + pad).astype(int) + 1+ x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, self.fw), min(y1, self.fh)+ if x1 <= x0 or y1 <= y0: return m+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ fn(ImageDraw.Draw(im), [((x - x0) * ss, (y - y0) * ss) for x, y in P], ss)+ m[y0:y1, x0:x1] = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ return m++ def poly(self, pts):+ """filled polygon (canvas px) -> anti-aliased mask"""+ return self._draw(self._fpts(pts), 1, lambda d, q, ss: d.polygon(q, fill=255))++ @staticmethod+ def closed(pts, per=10):+ """closed Catmull-Rom outline through control points"""+ P = np.asarray(pts, np.float32)+ Q = np.vstack([P[-1:], P, P[:2]])+ return spline(Q, per)[per:-per - 1] if len(P) > 2 else P++ def shape(self, pts, per=10):+ """smooth closed shape through control points"""+ return self.poly(self.closed(pts, per))++ def rect(self, x0, y0, x1, y1, r=0):+ if r <= 0: return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])+ r = min(r, (x1 - x0) / 2, (y1 - y0) / 2)+ a = np.linspace(0, np.pi / 2, 8)+ pts = []+ for cx, cy, a0 in ((x1 - r, y0 + r, -np.pi / 2), (x1 - r, y1 - r, 0), (x0 + r, y1 - r, np.pi / 2), (x0 + r, y0 + r, np.pi)):+ pts += [(cx + r * np.cos(a0 + t), cy + r * np.sin(a0 + t)) for t in a]+ return self.poly(pts)++ def ellipse(self, cx, cy, rx, ry, rot=0.0, n=72):+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)+ c, s = np.cos(np.radians(rot)), np.sin(np.radians(rot))+ x, y = rx * np.cos(t), ry * np.sin(t)+ return self.poly(np.stack([cx + x * c - y * s, cy + x * s + y * c], 1))++ def blob(self, cx, cy, rx, ry, rough=0.15, seed=None, rot=0.0, n=120):+ return self.poly(blob_pts(cx, cy, rx, ry, rough, n, self._seed() if seed is None else seed, np.radians(rot)))++ def line(self, pts, width):+ """stroke along a polyline (canvas px), round joints"""+ P = self._fpts(pts); w = width * self.k++ def fn(d, q, ss):+ d.line(q, fill=255, width=max(1, int(round(w * ss))), joint='curve')+ for x, y in (q[0], q[-1]):+ d.ellipse((x - w * ss / 2, y - w * ss / 2, x + w * ss / 2, y + w * ss / 2), fill=255)+ return self._draw(P, w + 2, fn)++ # ------------------------------------------------------------------ temperature fields+ def ramp(self, p0, t0, p1, t1, ease=1.0):+ """linear temperature ramp from canvas point p0 (t0) to p1 (t1), clamped beyond the ends"""+ dx, dy = p1[0] - p0[0], p1[1] - p0[1]+ u = ((self.X - p0[0]) * dx + (self.Y - p0[1]) * dy) / (dx * dx + dy * dy + 1e-9)+ u = np.clip(u, 0, 1) ** ease+ return (t0 + (t1 - t0) * u).astype(np.float32)++ def radial(self, cx, cy, rx, ry, t0, t1, power=1.0):+ """t0 at (cx, cy) falling to t1 at the ellipse rx, ry (and beyond)"""+ u = np.clip(np.hypot((self.X - cx) / rx, (self.Y - cy) / ry), 0, 1) ** power+ return (t0 + (t1 - t0) * u).astype(np.float32)++ def texture(self, scale, seed=0, octaves=3):+ """value noise in -0.5..0.5 at canvas feature size `scale` (cached)"""+ key = ('tex', int(scale), seed, octaves)+ if key not in self._cache:+ self._cache[key] = noise2d(self.fh, self.fw, max(2.0, scale * self.k), octaves, seed) - 0.5+ return self._cache[key]++ def room(self, top=25.0, bottom=19.0, y_top=0, y_bottom=None, wobble=0.25):+ """the background: still air layers warm under the ceiling and cool over the floor"""+ y_bottom = self.H if y_bottom is None else y_bottom+ self.T = self.ramp((0, y_top), top, (0, y_bottom), bottom) + wobble * 2 * self.texture(260, 11)++ def surface(self, mask, temp, emissivity=1.0, reflected=None, grain=0.0, grain_scale=14, soft=0.0, fuzz=0.0,+ fuzz_scale=6, limb=0.0, limb_px=12.0, seed=None):+ """paint an object: mask (0..1) at `temp` (a number or a field from ramp / radial).+ emissivity < 1 pulls it towards `reflected` (default ambient): polished metal reads like the room.+ grain: material non-uniformity in degrees; soft: blurred edge (px); fuzz: ragged fur edge (0..1);+ limb: degrees lost towards the silhouette of a rounded body (emissivity falls at grazing angles, and fur+ tips are cooler), over `limb_px` px."""+ m = mask+ if soft: m = blur(m, soft * self.k)+ if fuzz:+ n = self.texture(fuzz_scale, 101 if seed is None else seed, 2)+ m = smoothstep(0.5 - 0.22 * fuzz, 0.5 + 0.22 * fuzz, blur(m, 0.9 * fuzz_scale * self.k * fuzz) + 1.6 * fuzz * n)+ m = m * (blur(mask, 1.2 * fuzz_scale * self.k) > 0.02)+ T = np.asarray(temp, np.float32)+ if grain: T = T + 2 * grain * self.texture(grain_scale, 37 if seed is None else seed)+ if limb:+ inner = smoothstep(0.5, 0.97, blur(mask, limb_px * self.k))+ T = T - limb * (1 - inner)+ if emissivity < 1:+ Tr = self.amb if reflected is None else np.asarray(reflected, np.float32)+ T = emissivity * T + (1 - emissivity) * Tr+ self.T += m * (T - self.T)+ return m++ def warm(self, mask, dT):+ """add (or with dT < 0 remove) heat under a mask"""+ self.T += mask * np.asarray(dT, np.float32)++ def seam(self, pts, dT=-0.6, width=3.0):+ """a gap, joint or grout line: a thin line a little cooler (or warmer) than its surroundings"""+ self.T += self.line(pts, width) * dT++ def soak(self, mask, temp, reach=40.0, strength=0.5, onto=None):+ """heat soaking out of a hot (or cold) object into the surfaces around it: a blurred halo of its excess+ temperature. Call it before painting the object itself so the object keeps its own temperature."""+ ex = mask * (np.asarray(temp, np.float32) - self.amb)+ h = blur(ex, reach * self.k) * strength+ if onto is not None: h = h * onto+ self.T += h++ # ------------------------------------------------------------------ moving air: plumes and pools+ def _tex(self, seed, n=512):+ key = ('ptex', seed)+ if key not in self._cache: self._cache[key] = noise2d(n, n, 40, 4, seed)+ return self._cache[key]++ @staticmethod+ def _sample(tex, u, v):+ n = tex.shape[0] - 1+ u = np.mod(u, n); v = np.mod(v, n)+ i = u.astype(np.int32); j = v.astype(np.int32)+ fu, fv = u - i, v - j+ a, b, c, d = tex[j, i], tex[j, i + 1], tex[j + 1, i], tex[j + 1, i + 1]+ return (a * (1 - fu) + b * fu) * (1 - fv) + (c * (1 - fu) + d * fu) * fv++ def rise(self, x, y, height, sway=25.0, lean=0.0, n=9, seed=None):+ """control points of a buoyant plume rising from (x, y) by `height` px, swaying sideways, leaning (px/px)"""+ s = self._seed() if seed is None else seed+ w = fbm1d(n, 3, 3, s)+ hs = np.linspace(0, 1, n)+ return [(x + lean * h * height + sway * w[i] * h ** 0.8, y - h * height) for i, h in enumerate(hs)]++ def plume(self, path, temp, w0=8.0, w1=80.0, opacity=0.9, cool=1.7, eddy=0.8, puffs=0.4, wisp=0.5, seed=None,+ fade_in=0.04, fade_out=0.25):+ """a column of hot air / steam (temp > ambient) or cold air (temp < ambient) along a path (canvas control+ points, source first). It widens from w0 to w1 px, cools towards ambient as it mixes (`cool`), breaks+ into eddies (`eddy`) and wisps (`wisp`) the further it goes and pulses in puffs along its length."""+ s0 = self._seed() if seed is None else seed+ P = self._fpts(spline(path, 12))+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)+ S = np.concatenate([[0], np.cumsum(seg)]); L = float(S[-1])+ if L < 2: return+ m = max(4, int(L / 3)); ss = np.linspace(0, L, m)+ P = np.stack([np.interp(ss, S, P[:, 0]), np.interp(ss, S, P[:, 1])], 1); S = ss+ W0, W1 = w0 * self.k, w1 * self.k+ pad = W1 * 1.8 + 4+ x0, y0 = np.floor(P.min(0) - pad).astype(int); x1, y1 = np.ceil(P.max(0) + pad).astype(int)+ x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, self.fw), min(y1, self.fh)+ if x1 <= x0 or y1 <= y0: return+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ best = np.full(xx.shape, 1e9, np.float32); s_at = np.zeros_like(best); n_at = np.zeros_like(best)+ 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(((xx - a[0]) * d[0] + (yy - a[1]) * d[1]) / l2, 0, 1)+ px, py = a[0] + t * d[0] - xx, a[1] + t * d[1] - yy+ dist = px * px + py * py+ sel = dist < best+ best = np.where(sel, dist, best)+ s_at = np.where(sel, S[i] + t * np.sqrt(l2), s_at)+ n_at = np.where(sel, (d[0] * (yy - a[1]) - d[1] * (xx - a[0])) / np.sqrt(l2), n_at)+ u = np.clip(s_at / L, 0, 1)+ w = W0 + (W1 - W0) * u ** 0.85+ lam = 0.55 * w + 3+ ta, tb = self._tex(s0 % 997), self._tex(s0 % 991 + 3)+ q = self._sample(tb, s_at * 40 / (lam * 2.2) + 17, n_at * 40 / (lam * 2.2) + 91) - 0.5+ e = self._sample(ta, s_at * 40 / lam + 60 * q + 113, n_at * 40 / lam + 60 * q + 29)+ n2 = n_at + (e - 0.5) * w * 1.1 * u ** 0.6+ across = np.exp(-2.2 * (n2 / w) ** 2)+ along = smoothstep(0, fade_in, u) * (1 - smoothstep(1 - fade_out, 1.0, u))+ th = 0.30 + 0.32 * u+ wisps = smoothstep(th - 0.16, th + 0.16, e)+ brk = np.clip(u * 2.5, 0, 1) * eddy+ dens = across * along * (1 - brk + brk * wisps)+ if wisp:+ fil = self._sample(ta, s_at * 40 / (lam * 0.45) + 300, n_at * 40 / (lam * 0.32) + 200)+ dens = dens * (1 - wisp * u * (1 - smoothstep(0.35, 0.65, fil)))+ if puffs:+ pf = fbm1d(1024, 90, 3, s0 % 9973)+ dens = dens * (1 - puffs * 0.5 * (1 + np.interp(s_at / (lam * 4 + 1) * 6, np.arange(1024), pf)) * u)+ dens = dens * (best < (w * 2.4) ** 2)+ Tp = self.amb + (temp - self.amb) * np.exp(-cool * u)+ a = np.clip(opacity * dens, 0, 1)+ sub = self.T[y0:y1, x0:x1]+ if temp >= self.amb: sub += a * np.maximum(Tp - sub, 0)+ else: sub += a * np.minimum(Tp - sub, 0)++ def pool(self, x, y, temp, reach=300.0, spread=(-30, 210), tongues=7, squash=0.42, width=0.35, soft=14.0,+ seed=None):+ """air that has fallen to the floor and spreads out over it in soft tongues from (x, y): cold air from+ an open fridge (temp < ambient) or warm air under a heater. reach: tongue length (px, on the floor);+ spread: range of directions in degrees on the floor plane (0 = right, 90 = towards the camera);+ squash: how flat the floor looks; strength falls off along each tongue"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ m = np.zeros((self.fh, self.fw), np.float32)+ for a in np.linspace(spread[0], spread[1], tongues) + r.uniform(-8, 8, tongues):+ L = reach * r.uniform(0.55, 1.0)+ c, s_ = np.cos(np.radians(a)), np.sin(np.radians(a))+ ts = np.linspace(0, 1, 14)+ half = L * width * (0.35 + 0.65 * np.sin(np.pi * np.clip(ts * 0.85 + 0.15, 0, 1)))+ cen = [(x + c * L * t_, y + s_ * L * t_ * squash) for t_ in ts]+ left = [(px - s_ * h, py + c * h * squash) for (px, py), h in zip(cen, half)]+ right = [(px + s_ * h, py - c * h * squash) for (px, py), h in zip(cen, half)]+ tongue = self.poly(left + right[::-1])+ dist = np.hypot(self.X - x, (self.Y - y) / squash) / L+ m = np.maximum(m, tongue * np.clip(1.15 - dist, 0, 1) ** 0.8)+ m = np.clip(blur(m, soft * self.k) * 1.3, 0, 1)+ d = np.asarray(temp, np.float32) - self.T+ self.T += m * (np.minimum(d, 0) if temp < self.amb else np.maximum(d, 0))++ # ------------------------------------------------------------------ traces+ def paw(self, x, y, size, heading=0.0, squash=0.45):+ """outline mask of one paw print (main pad + four toes) on a floor seen at an angle; heading in degrees+ (0 = walking to the right on the floor), squash = how flat the floor looks"""+ h = np.radians(heading)+ fx, fy = np.cos(h), np.sin(h)+ m = np.zeros((self.fh, self.fw), np.float32)+ parts = [(0.0, 0.0, 0.42, 0.36)] + [(0.5 * np.cos(a) - 0.0, 0.5 * np.sin(a), 0.15, 0.13)+ for a in np.radians([-62, -22, 22, 62])]+ for ax, ay, rx, ry in parts:+ cx = x + (ax * fx - ay * fy) * size+ cy = y + (ax * fy + ay * fx) * size * squash+ m = np.maximum(m, self.ellipse(cx, cy, rx * size, ry * size * squash * 1.2, n=24))+ return m++ def prints(self, steps, temp, size=16.0, squash=0.45, spread=1.0, kind='paw'):+ """footprints that cool and spread with age. steps: [(x, y, heading_deg, scale, age 0 fresh .. 1 gone)]"""+ for x, y, hd, sc, age in steps:+ if age >= 1: continue+ m = self.paw(x, y, size * sc, hd, squash) if kind == 'paw' else self.ellipse(x, y, size * sc * 0.5, size * sc * squash, hd)+ m = blur(m, (0.6 + 4.5 * age * spread) * self.k * sc)+ m = m / (m.max() + 1e-6)+ a = (1 - age) ** 1.4+ self.T += a * m * np.maximum(temp - self.T, 0)++ def reflect(self, region, axis_y, strength=0.25, blur_px=8.0, fade=160.0):+ """a glossy surface below `axis_y` (canvas px) mirrors whatever is warmer above it"""+ ay = axis_y * self.ky+ rows = np.arange(self.fh, dtype=np.float32) + 0.5+ src = np.clip(np.round(2 * ay - rows).astype(int), 0, self.fh - 1)+ R = blur(self.T[src, :], blur_px * self.k)+ f = (np.exp(-np.maximum(rows - ay, 0) / (fade * self.ky)) * (rows > ay))[:, None]+ self.T += np.maximum(R - self.T, 0) * strength * f * region++ # ------------------------------------------------------------------ camera+ def camera(self, palette='iron', span=None, agc=0.6, plateau=3.0, curve=None, netd=0.07, fpn=0.05, optics=0.7,+ dde=1.2, dde_clip=1.0, narcissus=0.35, pixel=0.25, saturate=None):+ """palette: iron / rainbow / white_hot / black_hot / arctic. span=(lo, hi) degrees or None (auto from the+ final scene); agc: 0 = plain linear span .. 1 = full plateau histogram equalisation; curve: optional manual+ tone curve [(degrees, level 0..1), ...] used instead of the linear span (agc still mixes HE on top) -- the+ hand-set level / span an operator dials in to give the room, the cat and the stove each their own colours;+ netd / fpn: temporal noise and column-stripe strength (degrees); optics: lens blur (sensor px); dde: detail+ enhancement gain for differences up to dde_clip degrees; narcissus: centre-cool vignette (degrees); pixel:+ how much of the sensor's pixel grid survives the upscale (0 smooth .. 1 hard blocks); saturate: a colour+ for everything above the span (off by default: the palette's white end)"""+ self.cam = dict(palette=palette, span=span, agc=agc, plateau=plateau, curve=curve, netd=netd, fpn=fpn, optics=optics,+ dde=dde, dde_clip=dde_clip, narcissus=narcissus, pixel=pixel, saturate=saturate)++ def _sense(self, T):+ c = self.cam+ Tb = blur(T, c['optics'] * self.ss) if c['optics'] else T+ S = Tb.reshape(self.sh, self.ss, self.sw, self.ss).mean((1, 3))+ S = S + c['netd'] * self._netd + c['fpn'] * self._col[None, :] + 0.4 * c['fpn'] * self._row[:, None]+ yy, xx = np.mgrid[0:self.sh, 0:self.sw].astype(np.float32)+ r2 = ((xx / self.sw - 0.5) ** 2 + (yy / self.sh - 0.5) ** 2) / 0.5+ return (S - c['narcissus'] * (1 - r2)).astype(np.float32)++ def _enhance(self, S):+ g, cl = self.cam['dde'], self.cam['dde_clip']+ if not g: return S+ d = S - blur(S, 1.6)+ return S + g * d / (1 + np.abs(d) / cl)++ def _fit(self, S):+ c = self.cam+ if c['span']: lo, hi = c['span']+ elif c['curve']: lo, hi = c['curve'][0][0], c['curve'][-1][0]+ else: lo, hi = float(np.percentile(S, 0.2)), float(np.percentile(S, 99.8))+ edges = np.linspace(lo, hi, 513)+ h, _ = np.histogram(np.clip(S, lo, hi), edges)+ h = np.minimum(h.astype(np.float64), c['plateau'] * h.mean())+ cdf = np.concatenate([[0], np.cumsum(h)]); cdf /= cdf[-1]+ return dict(lo=lo, hi=hi, edges=edges.astype(np.float32), cdf=cdf.astype(np.float32))++ def level(self, v, fit=None):+ """where temperature v lands on the palette (0..1) under the current gain"""+ f = fit or self._lastfit+ v = np.asarray(v, np.float32)+ c = self.cam['curve']+ if c: lin = np.interp(v, [a for a, _ in c], [b for _, b in c])+ else: lin = np.clip((v - f['lo']) / (f['hi'] - f['lo']), 0, 1)+ he = np.interp(np.clip(v, f['lo'], f['hi']), f['edges'], f['cdf'])+ return (1 - self.cam['agc']) * lin + self.cam['agc'] * he++ def _colour(self, S, fit):+ t = self.level(self._enhance(S), fit).astype(np.float32)+ a = Image.fromarray(t, 'F')+ up = np.asarray(a.resize((self.W, self.H), Image.BILINEAR), np.float32)+ if self.cam['pixel']:+ nn = np.asarray(a.resize((self.W, self.H), Image.NEAREST), np.float32)+ up = up + self.cam['pixel'] * (nn - up)+ L = lut(self.cam['palette'])+ rgb = L[np.clip((up * (len(L) - 1)).astype(np.int32), 0, len(L) - 1)]+ if self.cam['saturate'] is not None:+ hot = np.asarray(Image.fromarray(((S > fit['hi']) * 255).astype(np.uint8)).resize((self.W, self.H), Image.NEAREST)) > 127+ rgb[hot] = hexc(self.cam['saturate'])+ return Image.fromarray((rgb * 255).astype(np.uint8))++ # ------------------------------------------------------------------ readings (sensor image of a stage)+ def _s(self, x, y):+ return x * self.sw / self.W, y * self.sh / self.H++ def _read(self, S, x, y, r=1):+ sx, sy = self._s(x, y)+ i, j = int(sx), int(sy)+ return float(S[max(j - r, 0):j + r + 1, max(i - r, 0):i + r + 1].mean())++ def _box(self, S, x0, y0, x1, y1):+ a, b = self._s(x0, y0); c, d = self._s(x1, y1)+ sub = S[int(b):int(d) + 1, int(a):int(c) + 1]+ j, i = np.unravel_index(np.argmax(sub), sub.shape)+ return float(sub.max()), float(sub.min()), float(sub.mean()), ((int(a) + i + 0.5) * self.W / self.sw, (int(b) + j + 0.5) * self.H / self.sh)++ def _extreme(self, S, kind, region):+ x0, y0, x1, y1 = region or (0, 0, self.W, self.H)+ a, b = self._s(x0, y0); c, d = self._s(x1, y1)+ sub = S[int(b):int(d), int(a):int(c)]+ idx = np.argmax(sub) if kind == 'max' else np.argmin(sub)+ j, i = np.unravel_index(idx, sub.shape)+ return float(sub[j, i]), ((int(a) + i + 0.5) * self.W / self.sw, (int(b) + j + 0.5) * self.H / self.sh)++ def _profile(self, S, p0, p1, n=160):+ t = np.linspace(0, 1, n)+ xs = (p0[0] + (p1[0] - p0[0]) * t) * self.sw / self.W+ ys = (p0[1] + (p1[1] - p0[1]) * t) * self.sh / self.H+ Sb = blur(S, 0.8)+ return self._sample_plain(Sb, xs, ys)++ @staticmethod+ def _sample_plain(A, xs, ys):+ h, w = A.shape+ xs = np.clip(xs - 0.5, 0, w - 1.001); ys = np.clip(ys - 0.5, 0, h - 1.001)+ i, j = xs.astype(int), ys.astype(int); fx, fy = xs - i, ys - j+ return (A[j, i] * (1 - fx) + A[j, i + 1] * fx) * (1 - fy) + (A[j + 1, i] * (1 - fx) + A[j + 1, i + 1] * fx) * fy++ # ------------------------------------------------------------------ OSD (recorded now, drawn at render time)+ def statusbar(self, rec='00:00:00', date='2026-01-01', clock='12:00:00', battery=0.8, emissivity=0.95,+ mode='AUTO', height=58, reflected=None):+ """translucent top bar: red REC dot and timer, date / time, reflected temperature, emissivity, gain mode,+ SD card, battery"""+ self.osd.append(('status', dict(rec=rec, date=date, clock=clock, battery=battery, emissivity=emissivity,+ mode=mode, height=height, reflected=reflected)))++ def scalebar(self, x0, y0, x1, y1, ticks=None, unit='°C', label=None, height=None):+ """the colour scale with the AGC's tick positions; horizontal if wider than tall. A translucent bottom+ band is drawn under it when `height` is given"""+ self.osd.append(('scale', dict(box=(x0, y0, x1, y1), ticks=ticks, unit=unit, label=label, height=height)))++ def spot(self, x, y, label='Sp1', r=15, name=None, side='ne'):+ """spot meter: crosshair + label; its reading goes in the results table"""+ self.osd.append(('spot', dict(x=x, y=y, label=label, r=r, name=name, side=side)))++ def box(self, x0, y0, x1, y1, label='Bx1', name=None):+ """area meter: max / avg of a rectangle; marks the hottest pixel inside"""+ self.osd.append(('box', dict(b=(x0, y0, x1, y1), label=label, name=name)))++ def hottest(self, region=None):+ """red triangle + value on the hottest sensor pixel (in region=(x0, y0, x1, y1) or the whole frame)"""+ self.osd.append(('ext', dict(kind='max', region=region)))++ def coldest(self, region=None):+ """blue triangle + value on the coldest sensor pixel"""+ self.osd.append(('ext', dict(kind='min', region=region)))++ def profile(self, p0, p1, inset, label='L1', name=None, dash=12):+ """line profile: dashed line on the picture + an inset graph (x, y, w, h) of the temperature along it,+ the curve coloured through the palette"""+ self.osd.append(('profile', dict(p0=p0, p1=p1, inset=inset, label=label, name=name, dash=dash)))++ def results(self, x, y, width=330):+ """the measurement table (spots, boxes, profile) with their readings"""+ self.osd.append(('table', dict(x=x, y=y, width=width)))++ def reticle(self, x=None, y=None, r=26):+ """the centre crosshair with its live reading beside it"""+ self.osd.append(('reticle', dict(x=self.W / 2 if x is None else x, y=self.H / 2 if y is None else y, r=r)))++ def text(self, s, x, y, size=24, anchor='la', fill=WHITE, bold=False):+ self.osd.append(('text', dict(s=s, x=x, y=y, size=size, anchor=anchor, fill=fill, bold=bold)))++ # ------------------------------------------------------------------ OSD drawing+ def _font(self, size, bold=False):+ key = ('font', size, bold)+ if key not in self._cache: self._cache[key] = load_font('sans_bold' if bold else 'sans', size)+ return self._cache[key]++ def _t(self, d, xy, s, size, fill=WHITE, anchor='la', bold=False, stroke=2):+ d.text(xy, s, font=self._font(size, bold), fill=fill, anchor=anchor, stroke_width=stroke, stroke_fill=BLACK)++ @staticmethod+ def _ln(d, pts, w=2, fill=WHITE, outline=BLACK):+ d.line(pts, fill=outline, width=w + 2)+ d.line(pts, fill=fill, width=w)++ def _cross(self, d, x, y, r, fill=WHITE):+ g = r * 0.35+ for a, b in (((x - r, y), (x - g, y)), ((x + g, y), (x + r, y)), ((x, y - r), (x, y - g)), ((x, y + g), (x, y + r))):+ self._ln(d, [a, b], 2, fill)++ def _tri(self, d, x, y, up, fill):+ s = 13+ pts = [(x, y), (x - s * 0.7, y + s), (x + s * 0.7, y + s)] if up else [(x, y), (x - s * 0.7, y - s), (x + s * 0.7, y - s)]+ d.polygon(pts, fill=fill, outline=BLACK)++ def _draw_osd(self, img, S, items, fit):+ base = img.convert('RGBA')+ over = Image.new('RGBA', img.size, (0, 0, 0, 0))+ d = ImageDraw.Draw(over)+ rows = []+ for kind, p in items: # translucent bands first+ if kind == 'status':+ d.rectangle((0, 0, self.W, p['height']), fill=(0, 0, 0, 105))+ if kind == 'scale' and p['height']:+ d.rectangle((0, self.H - p['height'], self.W, self.H), fill=(0, 0, 0, 105))+ for kind, p in items:+ if kind == 'status':+ h = p['height']; cy = h / 2+ d.ellipse((26, cy - 10, 46, cy + 10), fill=RED + (255,), outline=BLACK)+ self._t(d, (58, cy), 'REC', 26, anchor='lm', bold=True)+ self._t(d, (124, cy), p['rec'], 26, anchor='lm')+ self._t(d, (self.W / 2, cy), f"{p['date']} {p['clock']}", 24, anchor='mm')+ bx = self.W - 120+ d.rectangle((bx, cy - 12, bx + 54, cy + 12), outline=WHITE + (255,), width=2)+ d.rectangle((bx + 54, cy - 5, bx + 59, cy + 5), fill=WHITE + (255,))+ for i in range(4):+ if i < round(p['battery'] * 4):+ d.rectangle((bx + 4 + i * 12.5, cy - 8, bx + 13 + i * 12.5, cy + 8), fill=WHITE + (255,))+ sx = bx - 52+ d.polygon([(sx, cy - 13), (sx + 16, cy - 13), (sx + 22, cy - 7), (sx + 22, cy + 13), (sx, cy + 13)], outline=WHITE + (255,), width=2)+ for i in range(3): d.line([(sx + 5 + i * 5, cy - 9), (sx + 5 + i * 5, cy - 3)], fill=WHITE + (255,), width=2)+ self._t(d, (sx - 26, cy), p['mode'], 24, anchor='rm', bold=True)+ self._t(d, (sx - 120, cy), f"ε {p['emissivity']:.2f}", 24, anchor='rm')+ if p.get('reflected') is not None:+ self._t(d, (sx - 230, cy), f"Tr {p['reflected']:.0f}°C", 24, anchor='rm')+ elif kind == 'scale':+ self._draw_scale(d, p, fit)+ elif kind == 'spot':+ v = self._read(S, p['x'], p['y'])+ self._cross(d, p['x'], p['y'], p['r'])+ dx, dy = {'ne': (1, -1), 'nw': (-1, -1), 'se': (1, 1), 'sw': (-1, 1)}[p['side']]+ self._t(d, (p['x'] + dx * (p['r'] * 0.55 + 4), p['y'] + dy * (p['r'] * 0.55 + 4)), p['label'], 20,+ anchor=('l' if dx > 0 else 'r') + ('d' if dy < 0 else 'a'), bold=True)+ rows.append((p['label'], p['name'], f'{v:5.1f}'))+ elif kind == 'box':+ x0, y0, x1, y1 = p['b']+ mx, mn, av, (hx, hy) = self._box(S, x0, y0, x1, y1)+ for seg in (((x0, y0), (x1, y0)), ((x1, y0), (x1, y1)), ((x1, y1), (x0, y1)), ((x0, y1), (x0, y0))):+ self._ln(d, list(seg), 2)+ self._t(d, (x0 + 4, y0 - 4), p['label'], 20, anchor='ld', bold=True)+ self._cross(d, hx, hy, 8)+ rows.append((p['label'], p['name'], f'max {mx:.1f} avg {av:.1f}'))+ elif kind == 'ext':+ v, (x, y) = self._extreme(S, p['kind'], p['region'])+ up = p['kind'] == 'max'+ self._tri(d, x, y + (3 if up else -3), up, (RED if up else BLUE) + (255,))+ self._t(d, (x + 14, y + (20 if up else -20)), f'{v:.1f}', 20, anchor='lm', bold=True)+ elif kind == 'profile':+ self._draw_profile(d, S, p, fit)+ pr = self._profile(S, p['p0'], p['p1'])+ rows.append((p['label'], p['name'], f'min {pr.min():.1f} max {pr.max():.1f}'))+ elif kind == 'reticle':+ v = self._read(S, p['x'], p['y'])+ self._cross(d, p['x'], p['y'], p['r'])+ self._t(d, (p['x'] + p['r'] + 8, p['y'] - p['r'] * 0.4), f'{v:.1f}', 22, anchor='ls', bold=True)+ elif kind == 'text':+ self._t(d, (p['x'], p['y']), p['s'], p['size'], p['fill'] + (255,) if len(p['fill']) == 3 else p['fill'],+ p['anchor'], p['bold'])+ for kind, p in items:+ if kind == 'table' and rows:+ x, y, w = p['x'], p['y'], p['width']+ lh = 34+ d.rectangle((x, y, x + w, y + 12 + lh * len(rows)), fill=(0, 0, 0, 110))+ for i, (lab, name, val) in enumerate(rows):+ yy = y + 6 + lh * i + lh / 2+ self._t(d, (x + 12, yy), lab, 21, anchor='lm', bold=True, stroke=1)+ if name: self._t(d, (x + 66, yy), name, 19, anchor='lm', stroke=1)+ self._t(d, (x + w - 12, yy), val + ('' if 'max' in val else ' °C'), 21, anchor='rm', stroke=1)+ return Image.alpha_composite(base, over).convert('RGB')++ def _draw_scale(self, d, p, fit):+ x0, y0, x1, y1 = p['box']+ horiz = (x1 - x0) >= (y1 - y0)+ L = lut(self.cam['palette'], 512)+ n = int(x1 - x0) if horiz else int(y1 - y0)+ for i in range(n):+ c = tuple(int(v * 255) for v in L[int(i / max(n - 1, 1) * 511) if horiz else int((1 - i / max(n - 1, 1)) * 511)]) + (255,)+ if horiz: d.line([(x0 + i, y0), (x0 + i, y1)], fill=c)+ else: d.line([(x0, y0 + i), (x1, y0 + i)], fill=c)+ d.rectangle((x0 - 1, y0 - 1, x1 + 1, y1 + 1), outline=BLACK + (255,), width=1)+ d.rectangle((x0 - 2, y0 - 2, x1 + 2, y1 + 2), outline=WHITE + (200,), width=1)+ lo, hi = fit['lo'], fit['hi']+ ticks = p['ticks'] or [v for v in (0, 10, 20, 30, 40, 60, 80, 100, 150, 200) if lo < v < hi]+ last = -1e9+ for v in ticks:+ u = float(self.level(v, fit))+ if horiz:+ x = x0 + u * (x1 - x0)+ if x - last < 44: continue+ last = x+ d.line([(x, y1 + 2), (x, y1 + 9)], fill=WHITE + (255,), width=2)+ self._t(d, (x, y1 + 11), f'{v:g}', 19, anchor='ma', stroke=1)+ else:+ y = y1 - u * (y1 - y0)+ if abs(y - last) < 24: continue+ last = y+ d.line([(x0 - 9, y), (x0 - 2, y)], fill=WHITE + (255,), width=2)+ self._t(d, (x0 - 12, y), f'{v:g}', 19, anchor='rm', stroke=1)+ if horiz:+ self._t(d, (x0 - 14, (y0 + y1) / 2), f'{lo:.1f}', 22, anchor='rm', bold=True)+ self._t(d, (x1 + 14, (y0 + y1) / 2), f'{hi:.1f} {p["unit"]}', 22, anchor='lm', bold=True)+ if p['label']: self._t(d, (x0, y0 - 6), p['label'], 18, anchor='ld', stroke=1)+ else:+ self._t(d, ((x0 + x1) / 2, y0 - 10), f'{hi:.1f}', 22, anchor='md', bold=True)+ self._t(d, ((x0 + x1) / 2, y1 + 10), f'{lo:.1f}', 22, anchor='ma', bold=True)++ def _draw_profile(self, d, S, p, fit):+ (ax, ay), (bx, by) = p['p0'], p['p1']+ L = np.hypot(bx - ax, by - ay); dash = p['dash']+ k = 0+ while k * dash < L:+ t0, t1 = k * dash / L, min((k + 0.6) * dash / L, 1)+ self._ln(d, [(ax + (bx - ax) * t0, ay + (by - ay) * t0), (ax + (bx - ax) * t1, ay + (by - ay) * t1)], 1)+ k += 1+ self._t(d, (ax - 6, ay - 4), p['label'], 20, anchor='rd', bold=True)+ for (x, y) in (p['p0'], p['p1']): d.ellipse((x - 4, y - 4, x + 4, y + 4), fill=WHITE + (255,), outline=BLACK)+ x, y, w, h = p['inset']+ d.rectangle((x, y, x + w, y + h), fill=(0, 0, 0, 120), outline=WHITE + (150,))+ pr = self._profile(S, p['p0'], p['p1'])+ lo, hi = float(np.floor(pr.min() - 1)), float(np.ceil(pr.max() + 1))+ gx0, gx1, gy0, gy1 = x + 52, x + w - 12, y + 34, y + h - 22+ for v in (lo, (lo + hi) / 2, hi):+ yy = gy1 - (v - lo) / (hi - lo) * (gy1 - gy0)+ d.line([(gx0, yy), (gx1, yy)], fill=(255, 255, 255, 60), width=1)+ self._t(d, (gx0 - 6, yy), f'{v:.0f}', 16, anchor='rm', stroke=1)+ Lp = lut(self.cam['palette'], 512)+ xs = gx0 + np.linspace(0, 1, len(pr)) * (gx1 - gx0)+ ys = gy1 - (pr - lo) / (hi - lo) * (gy1 - gy0)+ lev = self.level(pr, fit)+ for i in range(len(pr) - 1): # the palette colour of every sample, as a strip+ c = tuple(int(v * 255) for v in Lp[int(np.clip(lev[i], 0, 1) * 511)]) + (255,)+ d.rectangle((xs[i], gy1 + 4, xs[i + 1] + 1, gy1 + 12), fill=c)+ pts = list(zip(xs, ys))+ d.line(pts, fill=BLACK + (255,), width=5, joint='curve')+ d.line(pts, fill=WHITE + (255,), width=2, joint='curve')+ self._t(d, (x + 10, y + 6), p['label'] + (f' {p["name"]}' if p['name'] else ''), 18, anchor='la', bold=True, stroke=1)+ self._t(d, (x + w - 10, y + 6), '°C', 16, anchor='ra', stroke=1)++ # ------------------------------------------------------------------ output+ def _render(self, T, n_osd, fit=None):+ S = self._sense(T)+ fit = fit or self._fit(S)+ self._lastfit = fit+ img = self._colour(S, fit)+ return self._draw_osd(img, S, self.osd[:n_osd], fit) if n_osd else img++ def render(self):+ S = self._sense(self.T)+ self._lastfit = self._fit(S)+ return self._render(self.T, len(self.osd), self._lastfit)++ def stage(self, name):+ self.stages.append((name, self.T.copy(), len(self.osd)))++ def save(self, path, stages_dir=None, quality=88):+ fit = self._fit(self._sense(self.T))+ img = self._render(self.T, len(self.osd), fit)+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, T, n) in enumerate(self.stages):+ self._render(T, n, fit).save(f'{stages_dir}/{i:02d}_{name}.png')+ img.save(f'{stages_dir}/{len(self.stages):02d}_final.png')+ return imgdiff --git a/lib/vhs.py b/lib/vhs.pynew file mode 100644index 0000000..553ad83--- /dev/null+++ b/lib/vhs.py@@ -0,0 +1,1199 @@+"""vhs — a home-video frame: a 1970s living room shot on a consumer camcorder and played back off VHS tape+(numpy + Pillow only).++This is not a 'retro filter' laid over a picture (that is what synthwave does with its neon scene): the picture is+made the way a real home-video frame was made, in three passes, and every artefact comes out of one of them.++ 1. the room surfaces are painted as albedo (what colour the thing is) into one buffer and self-lit things+ (lamp shade, candle flames, dusk sky in the window, glints) into an emission buffer. At render time+ the albedo is multiplied by the lighting of the room -- a dim warm ambient, a few point lights with+ a soft 1/(1+d^2) fall-off (`light`) and painted light patches (`glow`: the scallops a drum shade+ throws on the wall, the pool a candle throws on the table). Things right in front of the lens are+ painted on a defocus layer (`layer(defocus=)`), because the camcorder focused on the cake, not on+ the child's head between it and the cake.+ 2. the camera an 80s CCD camcorder held by hand: a slight roll and zoom (`tilt`), the white balance left on+ 'outdoor' under tungsten bulbs (the room goes orange, the window goes blue), auto-exposure that+ lets the flames and the lamp shade clip, a soft knee, bloom, CCD vertical smear -- a faint vertical+ streak through the whole frame wherever a point is far over-exposed --, a short lag tail behind the+ highlights (the camera was still panning), lens softness, vignetting and gain noise that is worst+ in the dark corners. The camera's character generator mixes its OSD into the signal right here+ (REC, battery, tape counter, date stamp, zoom bar in a chunky dot-matrix font with a black edge),+ so the OSD goes onto the tape with the picture and smears with it.+ 3. the tape the frame is box-sampled to 480 lines x `samples` and split into luma Y and chroma I/Q (NTSC YIQ).+ VHS records luma at ~3 MHz (~240 TV lines) and chroma 'colour-under' at ~0.6 MHz, so+ luma is low-passed along each line, then the playback 'sharpness' circuit adds edge+ enhancement: a bright halo on one side of every dark edge and a dark one on the other;+ chroma is smeared over ~6x the luma width, averaged over two lines (comb filter) and delayed a+ few samples to the right -- saturated reds bleed out of their outlines to the right;+ playback then adds streaky luma noise, horizontal chroma noise streaks, line-by-line timebase+ jitter, 'flagging' (the top lines bend sideways), a tracking-error band (displaced lines, white+ noise streaks, ragged edges), head-switching noise in the last lines, dropouts (short white+ flecks), a lifted black level and slightly lower saturation; the 480-line frame is scaled back up.++Stages: `stage(name)` keeps a full render of what is there so far: room stages render clean, `camera()`,+`record()`, `wear()` switch on their pass for every later stage, OSD items show from the stage they are added.++Canvas coordinates are output pixels; colours are '#rrggbb' or 0..1 RGB triples.++ from vhs import VHSCamcorder+ v = VHSCamcorder(1920, 1080, seed=3)+ v.ambient('#ffd7a8', 0.35)+ v.wallpaper(v.rect(0, 0, 1920, 760), tile=120)+ v.shag(v.rect(0, 760, 1920, 1080), '#c9962e')+ v.floor_lamp(1500, 760, 300) # brings its own light+ tips = v.cake(960, 700, 110, 33, 68, [(270, '#f2b51e', 'lit'), (90, '#2f6fc8', 1.0)])+ for x, y in tips: v.light(x, y, 280, '#ffa048', 0.3)+ v.stage('room')+ v.camera(tilt=-1.4) # default white balance: 'outdoor' under tungsten+ v.record(); v.wear(tracking=(0.94, 0.04))+ v.rec(150, 100); v.datestamp('7:42 PM', 'JUN.16.1984', 150, 864)+ v.save('out.jpg')+"""+import os+from contextlib import contextmanager+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, spline, noise2d, smoothstep, load_font, shift++f32 = np.float32+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], f32) / 255+++def _c(c):+ return hexc(c) if isinstance(c, str) else np.asarray(c, f32)+++def _blur_axis(a, sigma, axis):+ """gaussian-ish blur along one axis only (three box passes via cumulative sums)"""+ if sigma <= 0.05: return a.astype(f32, copy=True)+ if a.ndim == 3 and axis < 2 and a.shape[0] * a.shape[1] > 500000: # big colour images: one channel at a time+ return np.stack([_blur_axis(a[..., k], sigma, axis) for k in range(a.shape[2])], -1)+ out = a.astype(f32)+ w = int(np.sqrt(12 * sigma * sigma / 3 + 1)); w += (w % 2 == 0)+ if w < 2:+ k = np.exp(-0.5 * (np.arange(-2, 3) / sigma) ** 2); k /= k.sum()+ pad = [(0, 0)] * out.ndim; pad[axis] = (2, 2)+ p = np.pad(out, pad, mode='edge'); n = out.shape[axis]+ return sum(k[i] * np.take(p, np.arange(i, i + n), axis=axis) for i in range(5)).astype(f32)+ r = w // 2+ for _ in range(3):+ pad = [(0, 0)] * out.ndim; pad[axis] = (r + 1, r)+ c = np.cumsum(np.pad(out, pad, mode='edge'), axis=axis, dtype=np.float64)+ n = c.shape[axis]+ out = ((np.take(c, np.arange(w, n), axis=axis) - np.take(c, np.arange(0, n - w), axis=axis)) / w).astype(f32)+ return out+++def _gb(a, sigma):+ """gaussian-ish blur over the first two axes of a 2D or (H, W, C) array"""+ return _blur_axis(_blur_axis(a, sigma, 0), sigma, 1)+++def _rowshift(a, off, fill=0.0):+ """shift every row of a (L, S[, C]) by off[row] samples (positive = right), linear interpolation, blank = fill"""+ L, S = a.shape[:2]+ xs = np.arange(S, dtype=f32)[None, :] - off[:, None].astype(f32)+ x0 = np.floor(xs); fr = xs - x0; x0 = x0.astype(np.int32)+ ok = (xs >= 0) & (xs <= S - 1)+ a0 = np.clip(x0, 0, S - 1); a1 = np.clip(x0 + 1, 0, S - 1)+ rows = np.arange(L)[:, None]+ if a.ndim == 3:+ out = a[rows, a0] * (1 - fr)[..., None] + a[rows, a1] * fr[..., None]+ return np.where(ok[..., None], out, f32(fill)).astype(f32)+ out = a[rows, a0] * (1 - fr) + a[rows, a1] * fr+ return np.where(ok, out, f32(fill)).astype(f32)+++def _resize(a, w, h, method=Image.BICUBIC):+ """resize an (H, W) or (H, W, C) float array"""+ if a.ndim == 2:+ return np.asarray(Image.fromarray(a.astype(f32), 'F').resize((w, h), method), f32)+ return np.stack([_resize(a[..., i], w, h, method) for i in range(a.shape[2])], -1)+++# ------------------------------------------------------------------ the character generator's dot-matrix font+_GLYPHS = {+ 'A': '01110 10001 10001 11111 10001 10001 10001', 'B': '11110 10001 10001 11110 10001 10001 11110',+ 'C': '01110 10001 10000 10000 10000 10001 01110', 'D': '11110 10001 10001 10001 10001 10001 11110',+ 'E': '11111 10000 10000 11110 10000 10000 11111', 'F': '11111 10000 10000 11110 10000 10000 10000',+ 'G': '01110 10001 10000 10111 10001 10001 01111', 'H': '10001 10001 10001 11111 10001 10001 10001',+ 'I': '01110 00100 00100 00100 00100 00100 01110', 'J': '00111 00010 00010 00010 00010 10010 01100',+ 'K': '10001 10010 10100 11000 10100 10010 10001', 'L': '10000 10000 10000 10000 10000 10000 11111',+ 'M': '1000001 1100011 1010101 1001001 1000001 1000001 1000001', 'N': '10001 10001 11001 10101 10011 10001 10001',+ 'O': '01110 10001 10001 10001 10001 10001 01110', 'P': '11110 10001 10001 11110 10000 10000 10000',+ 'Q': '01110 10001 10001 10001 10101 10010 01101', 'R': '11110 10001 10001 11110 10100 10010 10001',+ 'S': '01111 10000 10000 01110 00001 00001 11110', 'T': '11111 00100 00100 00100 00100 00100 00100',+ 'U': '10001 10001 10001 10001 10001 10001 01110', 'V': '10001 10001 10001 10001 10001 01010 00100',+ 'W': '1000001 1000001 1000001 1001001 1001001 1010101 0100010', 'X': '10001 10001 01010 00100 01010 10001 10001',+ 'Y': '10001 10001 01010 00100 00100 00100 00100', 'Z': '11111 00001 00010 00100 01000 10000 11111',+ '0': '01110 10001 10001 10001 10001 10001 01110', '1': '00100 01100 00100 00100 00100 00100 01110',+ '2': '01110 10001 00001 00010 00100 01000 11111', '3': '11111 00010 00100 00010 00001 10001 01110',+ '4': '00010 00110 01010 10010 11111 00010 00010', '5': '11111 10000 11110 00001 00001 10001 01110',+ '6': '00110 01000 10000 11110 10001 10001 01110', '7': '11111 00001 00010 00100 01000 01000 01000',+ '8': '01110 10001 10001 01110 10001 10001 01110', '9': '01110 10001 10001 01111 00001 00010 01100',+ ':': '00000 01100 01100 00000 01100 01100 00000', '.': '00000 00000 00000 00000 00000 01100 01100',+ '-': '00000 00000 00000 11111 00000 00000 00000', '/': '00001 00010 00010 00100 01000 01000 10000',+ ' ': '00000 00000 00000 00000 00000 00000 00000', '>': '10000 11000 11100 11110 11100 11000 10000',+}+++def _glyph_bitmap(s, bold=True):+ """string -> (7, n) 0/1 dot array; bold doubles every dot to the right like a camcorder character generator"""+ cols = []+ for ch in s.upper():+ g = np.array([[int(b) for b in row] for row in _GLYPHS.get(ch, _GLYPHS[' ']).split()], np.uint8)+ if bold: g = np.concatenate([g, np.zeros((7, 1), np.uint8)], 1); g[:, 1:] |= g[:, :-1]+ cols += [g, np.zeros((7, 1), np.uint8)]+ return np.concatenate(cols, 1) if cols else np.zeros((7, 1), np.uint8)+++class VHSCamcorder:+ def __init__(self, W=1920, H=1080, seed=0, lines=480, samples=760, ss=2, keep_stages=True):+ self.W, self.H, self.ss = W, H, ss+ self.keep_stages = keep_stages # False: stage() is free (no snapshot renders)+ self.lines, self.samples = lines, samples+ self.seed0 = seed+ self.rng = np.random.default_rng(seed)+ self.alb = np.zeros((H, W, 3), f32) # surface colour+ self.em = np.zeros((H, W, 3), f32) # self-lit+ self.patch = np.zeros((H, W, 3), f32) # painted light patches (add to the lighting)+ self.amb = (_c('#ffffff'), 1.0)+ self.lights = []+ self.cam = None; self.rec_ = None; self.wear_ = None+ self.osd = []+ self.stages = []+ self._layer = None+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(f32)++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ================================================================ masks (full frame, drawn only inside the bbox)+ def _mask(self, bbox, draw):+ x0, y0, x1, y1 = bbox+ x0, y0 = max(int(np.floor(x0)) - 2, 0), max(int(np.floor(y0)) - 2, 0)+ x1, y1 = min(int(np.ceil(x1)) + 2, self.W), min(int(np.ceil(y1)) + 2, self.H)+ m = np.zeros((self.H, self.W), f32)+ if x1 <= x0 or y1 <= y0: return m+ ss = self.ss+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ T = lambda pts: [((float(x) - x0) * ss, (float(y) - y0) * ss) for x, y in pts]+ draw(ImageDraw.Draw(im), T, ss)+ m[y0:y1, x0:x1] = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), f32) / 255+ return m++ def poly(self, pts):+ P = np.asarray(pts, f32)+ return self._mask((P[:, 0].min(), P[:, 1].min(), P[:, 0].max(), P[:, 1].max()),+ lambda d, T, ss: d.polygon(T(P), fill=255))++ def shape(self, pts, per=10):+ """closed smooth outline through control points"""+ P = np.asarray(pts, f32)+ return self.poly(spline(np.vstack([P, P[:1]]), per))++ def rect(self, x0, y0, x1, y1, r=0):+ if r <= 0: return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])+ return self._mask((x0, y0, x1, y1), lambda d, T, ss: d.rounded_rectangle(+ [T([(x0, y0)])[0], T([(x1, y1)])[0]], radius=r * ss, fill=255))++ def ellipse(self, cx, cy, rx, ry, rot=0.0, n=120):+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)+ c, s = np.cos(np.radians(rot)), np.sin(np.radians(rot))+ x, y = np.cos(t) * rx, np.sin(t) * ry+ return self.poly(np.stack([cx + x * c - y * s, cy + x * s + y * c], 1))++ def line(self, pts, width):+ P = np.asarray(pts, f32); r = width / 2+ def dr(d, T, ss):+ Q = T(P)+ d.line(Q, fill=255, width=max(1, int(round(width * ss))), joint='curve')+ for q in (Q[0], Q[-1]): d.ellipse([q[0] - r * ss, q[1] - r * ss, q[0] + r * ss, q[1] + r * ss], fill=255)+ return self._mask((P[:, 0].min() - r, P[:, 1].min() - r, P[:, 0].max() + r, P[:, 1].max() + r), dr)++ def text(self, s, x, y, size, style='sans_bold', anchor='mm', rot=0.0):+ font = load_font(style, size * self.ss)+ def dr(d, T, ss):+ q = T([(x, y)])[0]+ if not rot:+ d.text(q, s, font=font, fill=255, anchor=anchor); return+ tmp = Image.new('L', d.im.size, 0)+ ImageDraw.Draw(tmp).text(q, s, font=font, fill=255, anchor=anchor)+ d.bitmap((0, 0), tmp.rotate(rot, resample=Image.BICUBIC, center=q), fill=255)+ R = size * (len(s) * 0.7 + 1.5)+ return self._mask((x - R, y - R, x + R, y + R), dr)++ # ================================================================ fields (colour gradients) and painting+ def lin(self, p0, c0, p1, c1, ease=None):+ """linear colour gradient from p0 (colour c0) to p1 (colour c1)"""+ d = np.array(p1, f32) - np.array(p0, f32)+ t = np.clip(((self.XX - p0[0]) * d[0] + (self.YY - p0[1]) * d[1]) / (d @ d + 1e-6), 0, 1)+ if ease: t = t ** ease+ return _c(c0) + (_c(c1) - _c(c0)) * t[..., None]++ def rad(self, cx, cy, rx, ry, c0, c1, power=1.0):+ t = np.clip(np.hypot((self.XX - cx) / rx, (self.YY - cy) / ry), 0, 1) ** power+ return _c(c0) + (_c(c1) - _c(c0)) * t[..., None]++ @staticmethod+ def _bbox(m):+ r = np.flatnonzero(m.any(1)); c = np.flatnonzero(m.any(0))+ if not len(r): return None+ return slice(r[0], r[-1] + 1), slice(c[0], c[-1] + 1)++ def paint(self, mask, colour, alpha=1.0, form=0.0, form_r=24.0, light=(-0.55, -0.83)):+ """lay a colour (or colour field) over the surfaces. form > 0 rounds the shape: darker towards its outline,+ lighter on the side facing `light` (a direction in the picture plane)"""+ bb = self._bbox(mask)+ if bb is None: return+ ys, xs = bb+ m = mask[ys, xs] * alpha+ col = colour if isinstance(colour, np.ndarray) and colour.ndim == 3 else np.broadcast_to(_c(colour), (1, 1, 3))+ col = col[ys, xs] if col.shape[0] == self.H and col.shape[1] == self.W else np.broadcast_to(col, m.shape + (3,))+ if form:+ pad = int(form_r * 3)+ Y0, Y1 = max(ys.start - pad, 0), min(ys.stop + pad, self.H)+ X0, X1 = max(xs.start - pad, 0), min(xs.stop + pad, self.W)+ s = blur(mask[Y0:Y1, X0:X1], form_r)+ gy, gx = np.gradient(s)+ lx, ly = light+ sh = 1 + form * (np.clip(-(gx * lx + gy * ly) * form_r * 2.2, -1, 1) * 0.6 - (1 - np.clip(s * 2 - 0.2, 0, 1)) * 0.9)+ sh = sh[ys.start - Y0:ys.stop - Y0, xs.start - X0:xs.stop - X0]+ col = col * sh[..., None]+ if self._layer is not None:+ la, lc = self._layer+ lc[ys, xs] += (col - lc[ys, xs]) * m[..., None]+ la[ys, xs] += (1 - la[ys, xs]) * m+ return+ self.alb[ys, xs] += (col - self.alb[ys, xs]) * m[..., None]+ self.em[ys, xs] *= (1 - m[..., None])+ self.patch[ys, xs] *= (1 - m[..., None] * 0.6)++ def emit(self, mask, colour, level=1.0):+ """self-lit: adds light that the room lighting does not touch (flames, lamp shade, sky)"""+ bb = self._bbox(mask)+ if bb is None: return+ ys, xs = bb+ col = colour[ys, xs] if isinstance(colour, np.ndarray) and colour.ndim == 3 else _c(colour)+ self.em[ys, xs] += mask[ys, xs, None] * col * level++ def glow(self, mask, colour, level=0.5):+ """a painted patch of light falling on surfaces (multiplies their colour, unlike emit)"""+ bb = self._bbox(mask)+ if bb is None: return+ ys, xs = bb+ col = colour[ys, xs] if isinstance(colour, np.ndarray) and colour.ndim == 3 else _c(colour)+ self.patch[ys, xs] += mask[ys, xs, None] * col * level++ def shadow(self, mask, strength=0.4, soft=8.0, dx=0.0, dy=0.0):+ """darken the surfaces under a (shifted, blurred) mask: contact and cast shadows"""+ bb = self._bbox(mask)+ if bb is None: return+ ys, xs = bb+ pad = int(soft * 3 + abs(dx) + abs(dy) + 4)+ Y0, Y1 = max(ys.start - pad, 0), min(ys.stop + pad, self.H)+ X0, X1 = max(xs.start - pad, 0), min(xs.stop + pad, self.W)+ s = blur(shift(mask[Y0:Y1, X0:X1], dx, dy), soft) * strength+ tgt = self._layer[1] if self._layer is not None else self.alb+ tgt[Y0:Y1, X0:X1] *= (1 - np.clip(s, 0, 0.95))[..., None]++ def rim(self, mask, toward, colour, level=0.6, width=6.0):+ """edge light on the side of a shape that faces a light source at `toward` (x, y)"""+ cx, cy = toward+ bb = self._bbox(mask)+ if bb is None: return+ ys, xs = bb+ my = (self.YY[ys, xs] * mask[ys, xs]).sum() / (mask[ys, xs].sum() + 1e-6)+ mx = (self.XX[ys, xs] * mask[ys, xs]).sum() / (mask[ys, xs].sum() + 1e-6)+ d = np.array([cx - mx, cy - my], f32); d /= np.linalg.norm(d) + 1e-6+ edge = np.clip(mask - shift(mask, d[0] * width, d[1] * width), 0, 1)+ edge = blur(edge, width * 0.35) * mask+ target = self._layer[1] if self._layer is not None else None+ if target is not None:+ target += edge[..., None] * _c(colour) * level+ else:+ self.em += edge[..., None] * _c(colour) * level++ @contextmanager+ def layer(self, defocus=4.0):+ """paint near objects on their own layer and blur it: out of the camcorder's focus"""+ self._layer = (np.zeros((self.H, self.W), f32), np.zeros((self.H, self.W, 3), f32))+ try:+ yield self+ finally:+ la, lc = self._layer+ self._layer = None+ a = blur(la, defocus); c = _gb(lc * la[..., None], defocus)+ self.alb = self.alb * (1 - a[..., None]) + c+ self.em *= (1 - a[..., None]); self.patch *= (1 - a[..., None] * 0.6)++ # ================================================================ lighting+ def ambient(self, colour='#ffffff', level=0.4):+ self.amb = (_c(colour), level)++ def light(self, x, y, radius, colour='#ffd9a0', power=1.0):+ """a point light with a soft 1 / (1 + (d / radius)^2) fall-off"""+ self.lights.append((x, y, radius, _c(colour), power))++ def _lit(self):+ L = np.broadcast_to(self.amb[0] * self.amb[1], (self.H, self.W, 3)).astype(f32).copy()+ for x, y, r, col, p in self.lights:+ d2 = ((self.XX - x) ** 2 + (self.YY - y) ** 2) / (r * r)+ L += (p / (1 + d2))[..., None] * col+ L += self.patch+ return self.alb * L + self.em++ # ================================================================ the 70s room+ def wallpaper(self, mask, tile=120, base='#e9d8ad', ring='#d4702a', core='#6e3a1c', leaf='#8d8b34',+ dot='#e0a42c', seam=3, x0=0.0, y0=0.0, contrast=0.8):+ """a 1970s repeat: big orange rings with brown centres staggered with avocado discs, small gold dots;+ printed on paper strips: a faint seam (and a slight drop mismatch) every `seam` tiles"""+ S = 3; T = int(tile * S)+ im = Image.new('RGB', (T, T), tuple(int(v * 255) for v in _c(base)))+ d = ImageDraw.Draw(im)+ col = lambda h: tuple(int(v * 255) for v in (_c(base) + (_c(h) - _c(base)) * contrast))+ def disc(cx, cy, r, c): d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=c)+ for cx, cy in ((0, 0), (T, 0), (0, T), (T, T)):+ disc(cx, cy, 0.24 * T, col(leaf)); disc(cx, cy, 0.135 * T, col(base)); disc(cx, cy, 0.07 * T, col(leaf))+ c = T / 2+ disc(c, c, 0.33 * T, col(ring)); disc(c, c, 0.245 * T, col(base)); disc(c, c, 0.175 * T, col(ring))+ disc(c, c, 0.105 * T, col(core)); disc(c, c, 0.035 * T, col(base))+ for cx, cy in ((c, 0), (0, c), (T, c), (c, T)):+ disc(cx, cy, 0.05 * T, col(dot))+ t = np.asarray(im.resize((tile, tile), Image.LANCZOS), f32) / 255+ ny, nx = self.H // tile + 3, self.W // tile + 3+ big = np.tile(t, (ny, nx, 1))+ ox, oy = int(x0) % tile, int(y0) % tile+ pap = big[tile - oy:tile - oy + self.H, tile - ox:tile - ox + self.W]+ # strip seams and a small drop mismatch+ strip = int(tile * seam)+ k = ((self.XX - x0) // strip).astype(np.int32)+ pap = np.where((k % 2 == 1)[..., None], np.roll(pap, 3, axis=0), pap)+ sx = np.abs(((self.XX - x0) % strip))+ seamline = np.exp(-(np.minimum(sx, strip - sx) ** 2) / 1.2)+ pap = pap * (1 - 0.12 * seamline[..., None])+ pap = pap * (0.97 + 0.06 * noise2d(self.H, self.W, 180, 3, self._seed()))[..., None]+ self.paint(mask, pap)++ def paneling(self, mask, grooves, base='#6b4226', dark='#2a170c', grain=0.22):+ """dark walnut wall panels: vertical grain, boards a shade apart, V-grooves at the x positions given"""+ H, W = self.H, self.W+ g = noise2d(H // 8 + 2, W, 3, 3, self._seed())[:H // 8 + 2]+ g = np.asarray(Image.fromarray(g).resize((W, H), Image.BICUBIC), f32)+ tone = np.ones((H, W), f32)+ xs = sorted(grooves)+ for i in range(len(xs) + 1):+ a = xs[i - 1] if i else -1e9; b = xs[i] if i < len(xs) else 1e9+ tone[(self.XX >= a) & (self.XX < b)] = 0.86 + 0.24 * self.rng.random()+ col = _c(base) * (tone * (1 - grain + grain * 2 * g))[..., None]+ self.paint(mask, col)+ for x in xs:+ w = max(1.5, 4.0 * min(1.0, (300 - x) / 200 + 0.4))+ self.paint(mask * self.rect(x - w / 2, 0, x + w / 2, H), dark, 0.85)+ self.paint(mask * self.rect(x + w / 2, 0, x + w / 2 + 2, H), _c(base) * 1.35, 0.5)++ def ceiling(self, mask, colour='#e8dcc4'):+ """popcorn ceiling: off-white with a fine stipple"""+ n = noise2d(self.H, self.W, 6, 2, self._seed())+ self.paint(mask, _c(colour) * (0.9 + 0.12 * n)[..., None])++ def shag(self, mask, colour='#c48f2c', y_far=None, y_near=None):+ """shag carpet: mottled pile with tufts that get bigger towards the camera"""+ H, W = self.H, self.W+ lo = noise2d(H, W, 140, 3, self._seed())+ hi = noise2d(H, W, 5, 2, self._seed())+ mid = noise2d(H, W, 22, 2, self._seed())+ tuft = noise2d(H, W, 2.2, 1, self._seed())+ v = 0.74 + 0.24 * lo + 0.3 * (mid - 0.5) + 0.3 * (hi - 0.5) + 0.22 * (tuft - 0.5)+ self.paint(mask, _c(colour) * v[..., None])++ def curtain(self, x0, x1, y0, y1, colour='#c8561e', motif='#f0b44a', folds=5, gather=0.0, seed=None):+ """lined drapes: sinusoidal folds shaded across, a loose flower motif that follows the folds"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ w = x1 - x0+ hem = fbm1d(64, 10, 2, int(r.integers(1 << 30))) * 6+ pts = [(x0, y0), (x1, y0)] + [(x1 - w * i / 63, y1 + hem[i]) for i in range(64)]+ m = self.poly(pts)+ u = (self.XX - x0) / max(w, 1)+ ph = u * folds * 2 * np.pi + 0.6 * np.sin(self.YY / 90 + r.random() * 6)+ fold = 0.5 + 0.5 * np.cos(ph)+ col = _c(colour) * (0.62 + 0.5 * fold)[..., None]+ self.paint(m, col)+ # flower motif: five-petal daisies on a staggered grid, squeezed in the fold shadows+ step = w / 2.2+ petals, centres = [], []+ for j in range(int((y1 - y0) / step) + 2):+ for i in range(4):+ cx = x0 + (i + 0.5 * (j % 2)) * step * 0.95 + r.normal(0, 4)+ cy = y0 + 40 + j * step * 0.9 + r.normal(0, 4)+ if not (x0 + 8 < cx < x1 - 8 and cy < y1 - 20): continue+ rr = step * 0.2+ for a in np.linspace(0, 2 * np.pi, 5, endpoint=False) + r.uniform(0, 1):+ t = np.linspace(0, 2 * np.pi, 24, endpoint=False)+ ex, ey = np.cos(t) * rr * 0.75, np.sin(t) * rr * 0.5+ petals.append(np.stack([cx + np.cos(a) * rr + ex * np.cos(a) - ey * np.sin(a),+ cy + np.sin(a) * rr + ex * np.sin(a) + ey * np.cos(a)], 1))+ t = np.linspace(0, 2 * np.pi, 20, endpoint=False)+ centres.append(np.stack([cx + np.cos(t) * rr * 0.45, cy + np.sin(t) * rr * 0.45], 1))+ bb = (x0, y0, x1, y1 + 10)+ pm = self._mask(bb, lambda d, T, ss: [d.polygon(T(q), fill=255) for q in petals])+ cm = self._mask(bb, lambda d, T, ss: [d.polygon(T(q), fill=255) for q in centres])+ self.paint(pm * m, _c(motif) * (0.62 + 0.5 * fold)[..., None], 0.85)+ self.paint(cm * m, _c('#6b2e12') * (0.62 + 0.5 * fold)[..., None], 0.9)+ self.shadow(m, 0.25, 10, 8, 4)+ return m++ def window(self, x0, y0, x1, y1, sky=('#1d2e63', '#3d5fa0', '#c98a6a'), frame='#efe6d2', bars=(1, 1)):+ """a sash window at dusk: emissive sky gradient, a neighbour's roof and a tree as silhouettes, one lit+ window across the street, white-painted frame and glazing bars"""+ glass = self.rect(x0, y0, x1, y1)+ h = y1 - y0+ skyc = self.lin((0, y0), sky[0], (0, y0 + h * 0.62), sky[1])+ lowc = self.lin((0, y0 + h * 0.62), sky[1], (0, y1), sky[2])+ skyf = np.where((self.YY < y0 + h * 0.62)[..., None], skyc, lowc)+ self.paint(glass, '#000000')+ self.emit(glass, skyf, 0.8)+ r = self.rng+ # silhouettes: a roof line with a chimney, a round tree+ roof_y = y0 + h * 0.66+ roof = self.poly([(x0, y1), (x0, roof_y + 20), (x0 + (x1 - x0) * 0.35, roof_y - 30),+ (x0 + (x1 - x0) * 0.72, roof_y + 15), (x1, roof_y + 10), (x1, y1)]) * glass+ tree = np.clip(sum(self.ellipse(x1 - (x1 - x0) * 0.18 + r.normal(0, 18), y0 + h * 0.5 + r.normal(0, 22),+ r.uniform(28, 48), r.uniform(30, 50)) for _ in range(7)), 0, 1) * glass+ self.paint(np.clip(roof + tree, 0, 1), '#000000')+ self.em *= (1 - np.clip(roof + tree, 0, 1)[..., None] * 0.92)+ lw = self.rect(x0 + (x1 - x0) * 0.22, roof_y + 34, x0 + (x1 - x0) * 0.30, roof_y + 64) * glass+ self.emit(lw, '#ffc86a', 0.9)+ # frame and bars+ fw = 16+ fr = np.clip(self.rect(x0 - fw, y0 - fw, x1 + fw, y1 + fw) - glass, 0, 1)+ nx, ny = bars+ for i in range(1, nx + 1):+ x = x0 + (x1 - x0) * i / (nx + 1); fr = np.maximum(fr, self.rect(x - 5, y0, x + 5, y1))+ for j in range(1, ny + 1):+ y = y0 + (y1 - y0) * j / (ny + 1); fr = np.maximum(fr, self.rect(x0, y - 6, x1, y + 6))+ self.paint(fr, frame, form=0.25, form_r=4)+ sill = self.rect(x0 - fw - 14, y1 + fw - 2, x1 + fw + 14, y1 + fw + 14, r=3)+ self.paint(sill, frame, form=0.3, form_r=5)+ self.shadow(sill, 0.35, 6, 0, 8)+ return glass++ def rod(self, x0, x1, y, colour='#b98a3e'):+ m = self.rect(x0, y - 6, x1, y + 6, r=6)+ self.paint(m, colour, form=0.6, form_r=4)+ for x in (x0, x1):+ self.paint(self.ellipse(x, y, 14, 14), colour, form=0.6, form_r=6)++ def console_tv(self, x0, y0, x1, y1, top=12, wood='#6a3f1f', screen_frac=0.62, legs=46, glow=None):+ """a 70s console colour TV: walnut cabinet on splayed legs, curved dark screen in a chrome bezel with a+ reflection, speaker grille and two knobs on the right; `glow` (x, y) puts a warm reflection on the glass"""+ r = self.rng+ yb = y1 - legs+ cab = self.rect(x0, y0, x1, yb, r=6)+ g = noise2d(self.H, self.W // 6 + 2, 2.5, 3, self._seed())+ g = np.asarray(Image.fromarray(g[:, :self.W // 6 + 2]).resize((self.W, self.H), Image.BICUBIC), f32)+ self.paint(cab, _c(wood) * (0.85 + 0.3 * g)[..., None], form=0.25, form_r=8)+ topm = self.poly([(x0 + 4, y0), (x1 - 4, y0), (x1 - 14, y0 - top), (x0 + 14, y0 - top)])+ self.paint(topm, _c(wood) * 1.25)+ for lx, sk in ((x0 + 30, -10), (x1 - 30, 10)):+ self.paint(self.poly([(lx - 7, yb), (lx + 7, yb), (lx + sk + 3, y1), (lx + sk - 3, y1)]), '#2b170a')+ self.shadow(self.rect(x0, yb, x1, y1 + 6), 0.45, 10, 0, 4)+ # screen+ sw = (x1 - x0) * screen_frac+ sx0, sy0, sx1, sy1 = x0 + 22, y0 + 22, x0 + sw, yb - 26+ bez = self.rect(sx0 - 8, sy0 - 8, sx1 + 8, sy1 + 8, r=26)+ self.paint(bez, '#b9b4a8', form=0.5, form_r=5)+ scr = self.rect(sx0, sy0, sx1, sy1, r=30)+ cx, cy = (sx0 + sx1) / 2, (sy0 + sy1) / 2+ self.paint(scr, self.rad(cx - 20, cy - 20, (sx1 - sx0) * 0.7, (sy1 - sy0) * 0.75, '#4a524c', '#161a18'))+ hl = self.shape([(sx0 + 20, sy0 + 30), (sx0 + (sx1 - sx0) * 0.45, sy0 + 14), (sx0 + (sx1 - sx0) * 0.5, sy0 + 26),+ (sx0 + 24, sy0 + (sy1 - sy0) * 0.4)]) * scr+ self.emit(blur(hl, 4), '#dfe8e0', 0.12)+ refl = self.rect(sx0 + (sx1 - sx0) * 0.08, sy0 + (sy1 - sy0) * 0.12, sx0 + (sx1 - sx0) * 0.3, sy0 + (sy1 - sy0) * 0.5, r=8) * scr+ self.emit(blur(refl, 6), '#7f97d8', 0.1)+ if glow is not None:+ gx, gy = glow+ self.emit(self.ellipse(gx, gy, 26, 16) * scr, '#ffb060', 0.35)+ self.emit(blur(self.ellipse(gx, gy, 60, 38) * scr, 10), '#ff9040', 0.12)+ # speaker grille + knobs+ gx0, gx1 = sx1 + 26, x1 - 20+ grille = self.rect(gx0, y0 + 110, gx1, yb - 26, r=4)+ stripes = 0.75 + 0.25 * (np.sin(self.XX * 1.3) > 0)+ self.paint(grille, _c('#3b2a1c') * stripes[..., None])+ for k, ky in enumerate((y0 + 42, y0 + 84)):+ kx = (gx0 + gx1) / 2+ self.paint(self.ellipse(kx, ky, 17, 17), '#cfc8b8', form=0.7, form_r=6)+ self.paint(self.rect(kx - 2, ky - 15, kx + 2, ky - 2), '#2b2420')+ self.paint(self.rect(gx0, y0 + 102, gx1, y0 + 106), '#d9cfb8', 0.8)+ return scr++ def rabbit_ears(self, x, y, spread=(-70, 60), height=160, colour='#d8d4cc'):+ base = self.ellipse(x, y - 8, 30, 12)+ self.paint(base, '#2a2420', form=0.6, form_r=5)+ for i, dx in enumerate(spread):+ tip = (x + dx * height / 140, y - height * (1 - 0.06 * i))+ self.paint(self.line([(x, y - 14), tip], 3), colour)+ self.paint(self.ellipse(tip[0], tip[1], 4, 4), colour)++ def floor_lamp(self, x, y_floor, y_shade, shade_w=130, shade_h=92, pole='#b58a3a', shade='#f3dfb0', power=1.0):+ """a floor lamp with a drum shade: brass pole, weighted base, the shade glows and throws a scallop of light+ up and down the wall"""+ self.paint(self.line([(x, y_shade + shade_h), (x, y_floor - 6)], 6), pole, form=0.5, form_r=3)+ self.paint(self.ellipse(x, y_floor - 4, 46, 11), '#4a3a22', form=0.5, form_r=5)+ self.shadow(self.ellipse(x, y_floor, 60, 12), 0.5, 7)+ # light scallops on the wall above and below the shade+ up = self.poly([(x - shade_w * 0.4, y_shade), (x + shade_w * 0.4, y_shade), (x + shade_w * 1.6, y_shade - 420),+ (x - shade_w * 1.6, y_shade - 420)])+ up = blur(up * smoothstep(y_shade - 430, y_shade - 10, self.YY), 26)+ dn = self.poly([(x - shade_w * 0.5, y_shade + shade_h), (x + shade_w * 0.5, y_shade + shade_h),+ (x + shade_w * 1.5, y_floor), (x - shade_w * 1.5, y_floor)])+ dn = blur(dn * smoothstep(y_floor + 40, y_shade + shade_h, self.YY), 30)+ self.glow(up, '#ffcf8a', 0.38 * power)+ self.glow(dn, '#ffcf8a', 0.2 * power)+ sm = self.poly([(x - shade_w / 2 + 12, y_shade), (x + shade_w / 2 - 12, y_shade),+ (x + shade_w / 2, y_shade + shade_h), (x - shade_w / 2, y_shade + shade_h)])+ lum = self.lin((0, y_shade), '#ffe9bf', (0, y_shade + shade_h), '#fff6dc')+ seams = 1 - 0.08 * (np.abs(((self.XX - x) / (shade_w / 5)) % 1 - 0.5) < 0.04)+ self.paint(sm, _c(shade) * 0.45 * seams[..., None])+ self.emit(sm, lum * seams[..., None] * self.lin((x - shade_w / 2, 0), '#d8b890', (x + shade_w / 2, 0), '#ffffff'), 1.25 * power)+ self.emit(blur(sm, 20), '#ffc070', 0.25 * power)+ for yy in (y_shade, y_shade + shade_h - 7): # brass trim bands+ k = (yy - y_shade) / shade_h+ ww = shade_w / 2 - 12 + 12 * k+ self.paint(self.rect(x - ww - 1, yy, x + ww + 1, yy + 7), '#7a4e22')+ self.paint(self.line([(x, y_shade - 18), (x, y_shade)], 4), pole)+ self.paint(self.ellipse(x, y_shade - 20, 6, 6), pole, form=0.5, form_r=3)+ self.emit(self.rect(x - shade_w / 2, y_shade + shade_h - 5, x + shade_w / 2, y_shade + shade_h), '#ffffff', 0.5 * power)+ self.light(x, y_shade + shade_h * 0.5, 520, '#ffc98a', 0.45 * power)+ return sm++ def sofa(self, x0, x1, y_back, y_seat, y_front, y_floor, colour='#a8481f', cushions=3, arm=70):+ """a velour three-seater seen from the front: rolled arms, tufted back cushions, seat cushions with front+ faces, a dark skirt; returns the seat line y for things sitting on it"""+ c = _c(colour)+ body = self.rect(x0, y_back + 30, x1, y_floor - 8, r=18)+ self.paint(body, c * 0.72)+ w = (x1 - x0 - 2 * arm) / cushions+ for i in range(cushions):+ a = x0 + arm + i * w+ back = self.rect(a + 3, y_back + 8 * (i % 2), a + w - 3, y_seat + 12, r=26)+ self.paint(back, c, form=0.55, form_r=18)+ for bx in (a + w * 0.33, a + w * 0.66):+ for by in (y_back + 50, y_back + 100):+ if by < y_seat - 10:+ self.paint(self.ellipse(bx, by, 5, 4), c * 0.5)+ self.shadow(self.ellipse(bx, by, 9, 7), 0.25, 4)+ seat = self.rect(a + 2, y_seat, a + w - 2, y_front, r=14)+ self.paint(seat, c * 1.06, form=0.45, form_r=14)+ self.paint(self.rect(a + 6, y_seat + 6, a + w - 6, y_seat + 18, r=6), c * 1.18, 0.6)+ for ax in (x0, x1 - arm):+ armm = self.rect(ax, y_back + 70, ax + arm, y_front + 6, r=30)+ self.paint(armm, c * 0.98, form=0.6, form_r=16)+ skirt = self.rect(x0 + 6, y_front, x1 - 6, y_floor - 8)+ self.paint(skirt, c * 0.55)+ self.shadow(self.rect(x0, y_floor - 12, x1, y_floor + 4), 0.6, 9, 0, 3)+ return y_seat++ def balloon(self, x, y, r, colour, string_to=None, sag=30, rot=0.0):+ """a latex balloon: egg-shaped body, tied knot, soft shading, a window-shaped specular glint, string"""+ c = _c(colour)+ if string_to is not None:+ p0 = np.array([x + np.sin(np.radians(rot)) * r * 1.2, y + r * 1.25]); p1 = np.array(string_to, f32)+ mid = (p0 + p1) / 2 + np.array([sag, 0])+ self.paint(self.line(spline([p0, mid, p1], 12), 1.6), '#d9d2c4', 0.8)+ body = self.ellipse(x, y, r, r * 1.16, rot=rot)+ sh = self.rad(x - r * 0.35, y - r * 0.45, r * 1.5, r * 1.6, c * 1.25, c * 0.45, 1.3)+ self.paint(body, sh)+ self.shadow(body, 0.25, 14, 16, 22)+ kx, ky = x + np.sin(np.radians(rot)) * r * 1.16, y + np.cos(np.radians(rot)) * r * 1.16+ self.paint(self.poly([(kx - 7, ky + 9), (kx + 7, ky + 9), (kx, ky - 3)]), c * 0.7)+ g = self.ellipse(x - r * 0.38, y - r * 0.48, r * 0.16, r * 0.24, rot=30)+ self.emit(blur(g, 2), '#ffffff', 0.55)++ def streamer(self, p0, p1, sag, colour, width=16, twists=9, hang=0.0):+ """a twisted crepe-paper streamer hung between two points: the band narrows and flips at every half-turn"""+ P = spline([p0, ((p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 + sag), p1], 40)+ n = len(P)+ tan = np.gradient(P, axis=0); tan /= np.linalg.norm(tan, axis=1, keepdims=True) + 1e-6+ nrm = np.stack([-tan[:, 1], tan[:, 0]], 1)+ ph = np.linspace(0, twists * np.pi, n)+ hw = width / 2 * (0.15 + 0.85 * np.abs(np.cos(ph)))+ c = _c(colour)+ quads, faces = [], []+ for i in range(n - 1):+ quads.append([P[i] + nrm[i] * hw[i], P[i + 1] + nrm[i + 1] * hw[i + 1], P[i + 1] - nrm[i + 1] * hw[i + 1],+ P[i] - nrm[i] * hw[i]])+ faces.append(0.72 + 0.4 * (np.cos(ph[i]) > 0) * np.abs(np.cos(ph[i])))+ bb = (P[:, 0].min() - width, P[:, 1].min() - width, P[:, 0].max() + width, P[:, 1].max() + width)+ cov = self._mask(bb, lambda d, T, ss: [d.polygon(T(q), fill=255) for q in quads])+ val = self._mask(bb, lambda d, T, ss: [d.polygon(T(q), fill=int(255 * f / 1.2)) for q, f in zip(quads, faces)])+ self.paint(cov, c * (val / (cov + 1e-4) * 1.2)[..., None])+ self.shadow(self.line(P, width * 0.6), 0.18, 8, 6, 12)++ def pennants(self, p0, p1, sag, letters, colours, size=96, letter='#fff6e0', dark_letter='#4a2412', seed=None):+ """a string of paper pennants with one hand-cut letter each, hanging along a sagging cord; the cord+ casts a soft shadow on the wall"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ n = len(letters)+ P = spline([p0, ((p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 + sag), p1], 60)+ s = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(P, axis=0), axis=1))])+ L = s[-1]+ cord = self.line(P, 2.2)+ self.shadow(cord, 0.25, 4, 5, 9)+ self.paint(cord, '#efe8d8')+ slot = L / n+ k = 0+ for i, ch in enumerate(letters):+ if ch == ' ': continue+ sa, sb = (i + 0.08) * slot, (i + 0.92) * slot+ a = np.array([np.interp(sa, s, P[:, 0]), np.interp(sa, s, P[:, 1])])+ b = np.array([np.interp(sb, s, P[:, 0]), np.interp(sb, s, P[:, 1])])+ mid = (a + b) / 2+ d = b - a; ang = np.arctan2(d[1], d[0]) + r.normal(0, 0.05)+ dn = np.array([-np.sin(ang), np.cos(ang)])+ tip = mid + dn * size + np.array([r.normal(0, 4), 0])+ tri = self.poly([a, b, tip])+ col = _c(colours[k % len(colours)]); k += 1+ self.shadow(tri, 0.3, 7, 7, 12)+ self.paint(tri, self.lin(tuple(mid), col * 1.08, tuple(tip), col * 0.82), form=0.15, form_r=6)+ cpos = mid + dn * size * 0.36+ tm = self.text(ch, cpos[0], cpos[1], size * 0.42, 'rounded', rot=-np.degrees(ang) + r.normal(0, 4))+ lum = col @ np.array([0.299, 0.587, 0.114], f32)+ self.paint(tm * tri, dark_letter if lum > 0.55 else letter)++ def coffee_table(self, quad, thick=16, wood='#7b4a24', legs=None, gloss=None):+ """a teak coffee table top seen from above-front: quad = [back-left, back-right, front-right, front-left];+ grain runs left-right, a soft sheen where the lamp reflects (gloss = (x, y))"""+ bl, br, fr, fl = [np.array(p, f32) for p in quad]+ top = self.poly([bl, br, fr, fl])+ g = noise2d(self.H // 10 + 2, self.W, 4, 3, self._seed())[:self.H // 10 + 2]+ g = np.asarray(Image.fromarray(g).resize((self.W, self.H), Image.BICUBIC), f32)+ g2 = noise2d(self.H, self.W, 60, 2, self._seed())+ col = _c(wood) * (0.8 + 0.28 * g + 0.12 * g2)[..., None]+ col = col * self.lin((0, bl[1]), '#d0d0d0', (0, fl[1]), '#ffffff')+ self.paint(top, col)+ if gloss is not None:+ self.glow(blur(self.ellipse(gloss[0], gloss[1], 260, 34) * top, 24), '#ffd9a8', 0.7)+ edge = self.poly([fl, fr, fr + [0, thick], fl + [0, thick]])+ self.paint(edge, _c(wood) * 0.55)+ if legs:+ for lx, ly0, ly1 in legs:+ self.paint(self.poly([(lx - 9, ly0), (lx + 9, ly0), (lx + 5, ly1), (lx - 5, ly1)]), _c(wood) * 0.5)+ return top++ def cake(self, cx, cy, rx, ry, h, candles, frosting='#fbf1e2', piping='#f08aa6', sprinkles=None, plate='#e6e2dc',+ lean=(1.0, -0.2), seed=None):+ """a round frosted cake on a plate: cylinder side shaded around, top ellipse, piped rosettes on the top and+ bottom rims, sprinkles, candles in a ring. candles: [(angle deg, colour, state)], state 'lit' = burning+ (the flame bends along `lean`), a number 0..1 = just blown out, trailing that much smoke (0 = cold).+ Returns the flame centres (put a `light` on each)."""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ fc = _c(frosting)+ plt = self.ellipse(cx, cy + h + 4, rx * 1.28, ry * 1.3)+ self.shadow(plt, 0.5, 10, 0, 8)+ self.paint(plt, self.lin((cx - rx, 0), _c(plate) * 0.8, (cx + rx, 0), _c(plate)))+ self.emit(blur(self.ellipse(cx - rx * 0.6, cy + h + 4 + ry * 0.75, rx * 0.35, 4) * plt, 2), '#ffffff', 0.25)+ side = np.clip(self.rect(cx - rx, cy, cx + rx, cy + h) + self.ellipse(cx, cy + h, rx, ry), 0, 1)+ u = np.clip((self.XX - cx) / rx, -1, 1)+ shade = 0.55 + 0.45 * np.sqrt(np.clip(1 - u ** 2, 0, 1)) * (1 - 0.25 * u)+ self.paint(side, fc * shade[..., None])+ topm = self.ellipse(cx, cy, rx, ry)+ self.paint(topm, self.lin((cx - rx, cy - ry), fc * 1.05, (cx + rx, cy + ry), fc * 0.9))+ # piped rosettes: bottom rim (front half), top rim (all round, back ones first)+ def rosette(x, y, s):+ m = self.ellipse(x, y, s, s * 0.8)+ self.paint(m, _c(piping), form=0.7, form_r=max(2, s * 0.6))+ for a in np.linspace(0.08, np.pi - 0.08, 15):+ rosette(cx + np.cos(a) * rx, cy + h + np.sin(a) * ry, rx * 0.075)+ for a in sorted(np.linspace(0, 2 * np.pi, 22, endpoint=False), key=lambda a: np.sin(a)):+ rosette(cx + np.cos(a) * rx * 0.97, cy + np.sin(a) * ry * 0.97 - 2, rx * 0.06)+ if sprinkles:+ for _ in range(46):+ a, rr = r.uniform(0, 2 * np.pi), np.sqrt(r.uniform(0, 0.7))+ sx, sy = cx + np.cos(a) * rx * rr, cy + np.sin(a) * ry * rr+ ang = r.uniform(0, 180)+ self.paint(self.ellipse(sx, sy, 5, 1.8, rot=ang, n=16), sprinkles[r.integers(len(sprinkles))])+ tips = []+ order = sorted(candles, key=lambda c: np.sin(np.radians(c[0])))+ for ang, ccol, state in order:+ a = np.radians(ang)+ bx, by = cx + np.cos(a) * rx * 0.6, cy + np.sin(a) * ry * 0.6+ ch = h * 0.62+ body = self.rect(bx - 4.5, by - ch, bx + 4.5, by)+ stripe = (np.sin((self.XX - bx) * 0.9 + (self.YY - by) * 0.55) > 0)+ self.paint(body, np.where(stripe[..., None], _c(ccol), _c('#fff4e4')) * self.lin((bx - 5, 0), '#c8c8c8', (bx + 5, 0), '#ffffff'))+ self.paint(self.ellipse(bx, by - ch, 4.5, 1.8), '#fff4e4')+ self.paint(self.line([(bx, by - ch), (bx + 0.5, by - ch - 7)], 1.6), '#1c1410')+ wick = (bx + 0.5, by - ch - 7)+ if state == 'lit' or state is True:+ lx, ly = lean+ fl = 30+ tip = (wick[0] + lx * fl * 0.55, wick[1] - fl + abs(ly) * 4)+ mid = (wick[0] + lx * fl * 0.2, wick[1] - fl * 0.45)+ outer = self.shape([(wick[0] - 5, wick[1] + 1), (mid[0] - 7, mid[1]), tip, (mid[0] + 7, mid[1] + 3),+ (wick[0] + 5, wick[1] + 1)], per=8)+ inner = self.shape([(wick[0] - 2.5, wick[1] - 1), (mid[0] - 3, mid[1] + 2),+ (wick[0] + lx * fl * 0.42, wick[1] - fl * 0.72), (mid[0] + 3, mid[1] + 4),+ (wick[0] + 2.5, wick[1] - 1)], per=8)+ self.emit(blur(outer, 1.2), '#ff9a3a', 1.6)+ self.emit(blur(inner, 1.0), '#fff2c0', 3.2)+ self.emit(blur(self.ellipse(wick[0], wick[1] + 1, 4, 3), 1), '#5a7cff', 0.6)+ tips.append(((wick[0] + tip[0]) / 2, (wick[1] + tip[1]) / 2))+ elif state:+ self.smoke(wick[0], wick[1], 170 * state, drift=lean[0] * 46, seed=int(r.integers(1 << 30)))+ self.emit(self.ellipse(wick[0], wick[1], 1.6, 1.6), '#ff6a20', 0.9)+ return tips++ def smoke(self, x, y, height, drift=30.0, width=2.8, opacity=0.62, seed=None):+ """a thin wisp from a just-blown-out wick: a hair-thin ribbon that rises, drifts, starts to curl, widens and+ thins out (grey, not lit -- it must not read as another flame)"""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ n = 48+ t = np.linspace(0, 1, n)+ ph = r.uniform(0, 6.3)+ wob = fbm1d(n, 9, 3, int(r.integers(1 << 30))) * 20 * t ** 1.2 + np.sin(t * 9 + ph) * 9 * t ** 1.5+ pts = np.stack([x + drift * t ** 1.3 + wob, y - height * t], 1)+ x0, y0 = pts.min(0) - 20; x1, y1 = pts.max(0) + 20+ op = opacity * smoothstep(0.0, 0.12, t) * (1 - t) ** 1.3+ def dr(d, T, ss):+ Q = T(pts)+ for i in range(n - 1):+ d.line([Q[i], Q[i + 1]], fill=int(255 * op[i]), width=max(1, int(width * (0.6 + 2.6 * t[i]) * ss)))+ m = self._mask((x0, y0, x1, y1), dr)+ self.paint(blur(m, 1.3), '#cfc9c2')++ def present(self, x, y, w, h, d, paper='#c8302a', stripe='#f4e6c8', ribbon='#f2c230'):+ """a wrapped box seen slightly from above and the left: front face, lid, right side; diagonal stripes,+ ribbon crossing over, a looped bow"""+ p = _c(paper); s = _c(stripe)+ front = self.rect(x, y, x + w, y + h)+ top = self.poly([(x, y), (x + w, y), (x + w + d * 0.6, y - d * 0.55), (x + d * 0.6, y - d * 0.55)])+ side = self.poly([(x + w, y), (x + w + d * 0.6, y - d * 0.55), (x + w + d * 0.6, y + h - d * 0.55), (x + w, y + h)])+ st = (((self.XX + self.YY) / 22) % 1) < 0.42+ for m, k in ((front, 0.95), (top, 1.12), (side, 0.66)):+ self.paint(m, np.where(st[..., None], s, p) * k)+ self.shadow(np.clip(front + side, 0, 1), 0.5, 9, 10, 8)+ rb = _c(ribbon)+ self.paint(self.rect(x + w * 0.45, y, x + w * 0.55, y + h) * front, rb * 0.95)+ self.paint(self.poly([(x + w * 0.45, y), (x + w * 0.55, y), (x + w * 0.55 + d * 0.6, y - d * 0.55),+ (x + w * 0.45 + d * 0.6, y - d * 0.55)]) * top, rb * 1.1)+ self.paint(self.poly([(x + w * 0.3 + d * 0.33, y - d * 0.33), (x + w * 0.3 + d * 0.22, y - d * 0.2),+ (x + w + d * 0.6, y - d * 0.3), (x + w + d * 0.6, y - d * 0.4)]) * top, rb * 1.05)+ bx, by = x + w * 0.5 + d * 0.3, y - d * 0.3+ for sgn in (-1, 1):+ loop = self.ellipse(bx + sgn * 20, by - 12, 22, 13, rot=-sgn * 25)+ self.paint(loop, rb, form=0.6, form_r=6)+ self.paint(self.ellipse(bx + sgn * 21, by - 12, 9, 4, rot=-sgn * 25), rb * 0.55)+ self.paint(self.ellipse(bx, by - 6, 9, 8), rb * 0.9, form=0.6, form_r=4)++ def cup(self, x, y, w, h, colour='#d23a2e', stripe='#f6efe0', stripes=6):+ """a striped paper party cup, slightly tapered, with a dark inside at the rim"""+ m = self.poly([(x - w / 2, y - h), (x + w / 2, y - h), (x + w * 0.38, y), (x - w * 0.38, y)])+ u = (self.XX - x) / (w / 2)+ st = (np.sin((u * 1.25 + 1) * stripes * np.pi / 2) > 0)+ col = np.where(st[..., None], _c(colour), _c(stripe)) * (0.6 + 0.45 * np.sqrt(np.clip(1 - u ** 2, 0, 1)))[..., None]+ self.shadow(m, 0.4, 6, 8, 6)+ self.paint(m, col)+ self.paint(self.ellipse(x, y - h, w / 2, w * 0.14), '#f6efe0')+ self.paint(self.ellipse(x, y - h + 1, w / 2 - 3, w * 0.11), '#3a2216')++ def plates(self, x, y, rx, ry, n=4, colour='#fbf6ea', rim='#e8a23a'):+ for i in range(n):+ yy = y - i * 3+ self.paint(self.ellipse(x, yy, rx, ry), _c(colour) * (0.86 + 0.04 * i))+ self.paint(self.ellipse(x, y - (n - 1) * 3, rx * 0.93, ry * 0.9) - self.ellipse(x, y - (n - 1) * 3, rx * 0.8, ry * 0.76), rim)+ self.shadow(self.ellipse(x, y + 4, rx, ry), 0.4, 7, 6, 4)++ def blower(self, x, y, length=90, colour='#2f6fc8', curl=3.0, seed=None):+ """a party blower lying on the table: mouthpiece and a curled paper tube"""+ t = np.linspace(0, 1, 50)+ rr = 18 * (1 - t * 0.55)+ a = t * curl * np.pi+ pts = np.stack([x + length * 0.45 + rr * np.sin(a) + t * 30, y - rr * (1 - np.cos(a)) * 0.6], 1)+ self.paint(self.line([(x, y), (x + length * 0.45, y)], 9), colour, form=0.4, form_r=3)+ self.paint(self.line(pts, 8), colour, form=0.4, form_r=3)+ self.paint(self.line([(x - 18, y), (x, y)], 7), '#f0e0b0')++ def confetti(self, region, n=60, colours=('#e04848', '#f2c230', '#3a8ad8', '#5cb85c', '#f08ab0'), size=4.0):+ x0, y0, x1, y1 = region+ r = self.rng+ for _ in range(n):+ x, y = r.uniform(x0, x1), r.uniform(y0, y1)+ self.paint(self.ellipse(x, y, size, size * 0.6, rot=r.uniform(0, 180), n=12), colours[r.integers(len(colours))])++ def teddy(self, cx, cy, s, fur='#9a6a3a', muzzle='#d9b48a', hat=('#3a8ad8', '#f2c230')):+ """a plush bear sitting up (a toy: button eyes are fine), wearing a little party hat"""+ f = _c(fur)+ body = self.ellipse(cx, cy + s * 0.9, s * 0.72, s * 0.8)+ self.shadow(body, 0.4, 12, 10, 14)+ self.paint(body, f, form=0.6, form_r=s * 0.3)+ self.paint(self.ellipse(cx, cy + s * 1.0, s * 0.42, s * 0.48), _c(muzzle) * 0.95, form=0.4, form_r=s * 0.2)+ for sx in (-1, 1):+ self.paint(self.ellipse(cx + sx * s * 0.62, cy + s * 0.75, s * 0.2, s * 0.42, rot=sx * 25), f * 0.92,+ form=0.6, form_r=s * 0.12)+ self.paint(self.ellipse(cx + sx * s * 0.45, cy + s * 1.62, s * 0.3, s * 0.22), f, form=0.6, form_r=s * 0.12)+ self.paint(self.ellipse(cx + sx * s * 0.47, cy + s * 1.66, s * 0.17, s * 0.13), _c(muzzle))+ self.paint(self.ellipse(cx + sx * s * 0.52, cy - s * 0.42, s * 0.2, s * 0.2), f, form=0.6, form_r=s * 0.1)+ self.paint(self.ellipse(cx + sx * s * 0.52, cy - s * 0.42, s * 0.1, s * 0.1), _c(muzzle) * 0.9)+ head = self.ellipse(cx, cy, s * 0.55, s * 0.5)+ self.paint(head, f, form=0.6, form_r=s * 0.25)+ self.paint(self.ellipse(cx, cy + s * 0.16, s * 0.22, s * 0.16), _c(muzzle), form=0.4, form_r=s * 0.1)+ self.paint(self.ellipse(cx, cy + s * 0.08, s * 0.08, s * 0.06), '#24160c')+ for sx in (-1, 1):+ self.paint(self.ellipse(cx + sx * s * 0.2, cy - s * 0.06, s * 0.055, s * 0.055), '#140c08')+ ha, hb = hat+ cone = self.poly([(cx - s * 0.26, cy - s * 0.4), (cx + s * 0.22, cy - s * 0.44), (cx + s * 0.1, cy - s * 1.05)])+ st = ((self.XX * 0.6 - self.YY) / 14 % 1) < 0.5+ self.paint(cone, np.where(st[..., None], _c(ha), _c(hb)), form=0.3, form_r=6)+ self.paint(self.ellipse(cx + s * 0.1, cy - s * 1.06, s * 0.09, s * 0.09), '#f4eee0', form=0.5, form_r=3)++ def child_back(self, hx, hy, s, hair='#3e2414', shirt='#2f8a84', collar='#e9dcc0', skin='#c88e66',+ hat=('#e23d5a', '#ffd23a'), pom='#f2efe6', lean=24.0, glow_from=None, seed=None):+ """a small child seen from behind, leaning towards the cake: sloping shoulders in a ringer tee, the back of a+ round head of hair with a crown whorl, both ears, a striped cone party hat tipped towards the cake with its+ elastic; rim-lit on the side that faces the candles (`glow_from`). Paint it on a defocus layer."""+ r = np.random.default_rng(self._seed() if seed is None else seed)+ yb = self.H + 80+ sc = _c(shirt)+ for sx in (-1, 1): # upper arms hang to the elbows; forearms go forward+ arm = self.poly(spline([(hx + sx * 0.95 * s, hy + 1.25 * s), (hx + sx * 1.45 * s, hy + 1.35 * s),+ (hx + sx * 1.72 * s, hy + 1.9 * s), (hx + sx * 1.8 * s, hy + 2.55 * s),+ (hx + sx * 1.62 * s, hy + 2.95 * s), (hx + sx * 1.3 * s, hy + 2.75 * s),+ (hx + sx * 1.12 * s, hy + 2.1 * s), (hx + sx * 0.95 * s, hy + 1.25 * s)], 8))+ self.paint(arm, sc * 0.92, form=0.6, form_r=s * 0.22, light=(0.7, -0.7))+ body = [(hx - 1.25 * s, yb), (hx - 1.22 * s, hy + 2.4 * s), (hx - 1.3 * s, hy + 1.6 * s), (hx - 1.05 * s, hy + 1.22 * s),+ (hx - 0.42 * s, hy + 1.02 * s), (hx + 0.42 * s, hy + 1.0 * s), (hx + 1.08 * s, hy + 1.18 * s),+ (hx + 1.34 * s, hy + 1.58 * s), (hx + 1.26 * s, hy + 2.4 * s), (hx + 1.3 * s, yb)]+ torso = self.poly(spline(body, 10))+ self.paint(torso, sc, form=0.5, form_r=s * 0.4, light=(0.7, -0.7))+ for sx in (-1, 1): # shoulder blades+ self.paint(blur(self.line(spline([(hx + sx * 0.35 * s, hy + 1.55 * s), (hx + sx * 0.62 * s, hy + 2.05 * s),+ (hx + sx * 0.5 * s, hy + 2.45 * s)], 8), s * 0.05), s * 0.08), sc * 0.7, 0.6)+ neck = self.rect(hx - 0.3 * s, hy + 0.55 * s, hx + 0.3 * s, hy + 1.12 * s, r=s * 0.12)+ self.paint(neck, skin, form=0.5, form_r=s * 0.12)+ ring = np.clip(self.ellipse(hx, hy + 1.07 * s, 0.5 * s, 0.13 * s) - self.ellipse(hx, hy + 1.0 * s, 0.37 * s, 0.09 * s), 0, 1)+ self.paint(ring * torso, collar)+ for sx in (-1, 1):+ ear = self.ellipse(hx + sx * 0.95 * s, hy + 0.14 * s, 0.2 * s, 0.28 * s, rot=-sx * 14)+ self.paint(ear, skin, form=0.6, form_r=s * 0.08)+ self.paint(self.ellipse(hx + sx * 0.99 * s, hy + 0.14 * s, 0.08 * s, 0.16 * s, rot=-sx * 14), _c(skin) * 0.72)+ head = self.ellipse(hx, hy, 0.9 * s, 1.0 * s)+ hc = _c(hair)+ self.paint(head, hc, form=0.65, form_r=s * 0.4, light=(0.6, -0.8))+ # strands spiralling out of the crown whorl, then a ragged nape+ wx, wy = hx + 0.12 * s, hy - 0.42 * s+ dark, light = [], []+ for k in range(70):+ a0 = r.uniform(0, 2 * np.pi); L = r.uniform(0.5, 1.15) * s+ t = np.linspace(0, 1, 12)+ ang = a0 + 0.9 * t+ pts = np.stack([wx + np.cos(ang) * L * t, wy + np.sin(ang) * L * t * 1.1], 1)+ (dark if k % 3 else light).append(pts)+ for lst, col, k in ((dark, hc * 0.5, 0.9), (light, hc * 2.1, 0.7)):+ m = self._mask((hx - s, hy - s, hx + s, hy + s), lambda d, T, ss, lst=lst: [d.line(T(q), fill=255, width=max(1, int(s * 0.035 * ss))) for q in lst])+ self.paint(m * head, col, k)+ for k in range(9):+ tx = hx - 0.62 * s + k * 0.155 * s + r.normal(0, 0.02 * s)+ tuft = self.poly([(tx - 0.1 * s, hy + 0.66 * s), (tx + 0.1 * s, hy + 0.66 * s), (tx + 0.02 * s, hy + (0.93 + 0.06 * r.random()) * s)])+ self.paint(tuft, hc * 0.95)+ # cone hat tipped towards the cake+ a = np.radians(lean)+ ax_ = np.array([np.sin(a), -np.cos(a)]); px_ = np.array([-ax_[1], ax_[0]])+ tb = np.array([hx + 0.2 * s, hy - 0.72 * s]); hw, hl = 0.6 * s, 1.75 * s+ tip = tb + ax_ * hl+ rim = [tb - px_ * hw + ax_ * 0.0, tb - px_ * hw * 0.5 - ax_ * 0.12 * s, tb - ax_ * 0.16 * s,+ tb + px_ * hw * 0.5 - ax_ * 0.12 * s, tb + px_ * hw]+ cone = self.poly(list(spline(rim, 6)) + [tip])+ u = ((self.XX - tb[0]) * px_[0] + (self.YY - tb[1]) * px_[1]) / hw+ v = ((self.XX - tb[0]) * ax_[0] + (self.YY - tb[1]) * ax_[1]) / hl+ st = ((v * 4.5 + u * 0.55) % 1) < 0.5+ conec = np.where(st[..., None], _c(hat[0]), _c(hat[1])) * (0.62 + 0.42 * np.sqrt(np.clip(1 - u ** 2, 0, 1)) + 0.1 * u)[..., None]+ self.shadow(cone, 0.35, s * 0.08, -s * 0.05, s * 0.1)+ self.paint(cone, conec)+ fr = []+ for k in range(16):+ ang = k / 16 * 2 * np.pi+ fr.append([tuple(tip), tuple(tip + np.array([np.cos(ang), np.sin(ang)]) * s * r.uniform(0.18, 0.28))])+ pm = self._mask((tip[0] - s * 0.4, tip[1] - s * 0.4, tip[0] + s * 0.4, tip[1] + s * 0.4),+ lambda d, T, ss: [d.line(T(q), fill=255, width=max(1, int(s * 0.07 * ss))) for q in fr])+ self.paint(np.clip(pm + self.ellipse(tip[0], tip[1], s * 0.12, s * 0.12), 0, 1), pom, form=0.4, form_r=s * 0.06)+ for sx in (-1, 1):+ el = spline([tuple(tb + sx * px_ * hw * 0.92), (hx + sx * 0.88 * s, hy - 0.1 * s), (hx + sx * 0.72 * s, hy + 0.62 * s)], 10)+ self.paint(self.line(el, max(1.5, s * 0.025)), '#ece6da', 0.9)+ if glow_from is not None:+ for m in (head, cone, torso, arm):+ self.rim(m, glow_from, '#ffb070', 0.9, width=s * 0.11)+ return head++ # ================================================================ camera, tape, OSD switches+ def camera(self, tilt=-1.4, zoom=1.0, white_balance=(1.08, 0.94, 0.70), exposure=1.0, knee=0.72,+ bloom=0.5, smear=0.22, lag=(-26, 0, 0.35), soft=1.2, vignette=0.26, gain_noise=0.035, seed=None):+ """switch on the camcorder for every later stage.+ tilt: hand-held roll (deg); white_balance: RGB gains (outdoor setting under tungsten = orange);+ knee: where highlights start to roll off; bloom: glow around clipped points; smear: CCD vertical smear+ strength; lag: (dx, dy, strength) comet tail behind highlights; gain_noise: noise in the shadows."""+ self.cam = dict(tilt=tilt, zoom=zoom, wb=np.asarray(white_balance, f32), exposure=exposure, knee=knee,+ bloom=bloom, smear=smear, lag=lag, soft=soft, vignette=vignette, gain_noise=gain_noise,+ seed=self._seed() if seed is None else seed)++ def record(self, luma=1.1, chroma=7.0, chroma_v=1.0, delay=4.5, sharpen=1.1, sharp_r=2.6, saturation=0.9):+ """put it on tape: luma low-pass (sigma in samples), chroma low-pass + vertical comb + delay to the right,+ playback edge enhancement (white / dark halos), lower saturation"""+ self.rec_ = dict(luma=luma, chroma=chroma, chroma_v=chroma_v, delay=delay, sharpen=sharpen, sharp_r=sharp_r,+ saturation=saturation)++ def wear(self, noise=0.03, chroma_noise=0.05, jitter=0.45, flagging=7.0, tracking=(0.84, 0.045), head_switch=7,+ dropouts=24, black=0.06, lines=0.035, seed=None):+ """playback faults: tracking = (centre as a fraction of the height, band height fraction) or None;+ head_switch = number of ruined lines at the bottom; flagging = sideways bend of the top lines (samples)"""+ self.wear_ = dict(noise=noise, chroma_noise=chroma_noise, jitter=jitter, flagging=flagging, tracking=tracking,+ head_switch=head_switch, dropouts=dropouts, black=black, lines=lines,+ seed=self._seed() if seed is None else seed)++ # ---- OSD items (character generator)+ def osd_text(self, s, x, y, px=7, colour='#f4f4ee', anchor='l'):+ self.osd.append(('text', s, x, y, px, _c(colour), anchor))++ def rec(self, x, y, px=7):+ """red dot + REC"""+ self.osd.append(('rec', x, y, px))++ def battery(self, x, y, px=7, level=2, of=4):+ self.osd.append(('battery', x, y, px, level, of))++ def counter(self, s, x, y, px=7, anchor='r'):+ self.osd_text(s, x, y, px, anchor=anchor)++ def datestamp(self, time_s, date_s, x, y, px=7, anchor='l'):+ """the burned-in date stamp: time over date"""+ self.osd_text(time_s, x, y, px, anchor=anchor)+ self.osd_text(date_s, x, y + px * 10, px, anchor=anchor)++ def zoom_bar(self, x, y, pos=0.7, px=7, width=300):+ """W [=====|----] T while zooming"""+ self.osd.append(('zoom', x, y, px, pos, width))++ def _osd_layer(self, n):+ """(alpha, colour) of the first n OSD items: dot-matrix glyphs with a black edge"""+ H, W = self.H, self.W+ fg = np.zeros((H, W), f32); fgc = np.zeros((H, W, 3), f32)+ def put(bits, x, y, px, col, anchor='l'):+ dw, dh = px * 0.8, px+ hh, ww = bits.shape+ tw = ww * dw+ if anchor == 'r': x = x - tw+ elif anchor == 'm': x = x - tw / 2+ im = Image.new('L', (int(tw + 2), int(hh * dh + 2)), 0)+ d = ImageDraw.Draw(im)+ for j, i in zip(*np.nonzero(bits)):+ d.rectangle([i * dw, j * dh, (i + 1) * dw - 0.5, (j + 1) * dh - 0.5], fill=255)+ m = np.asarray(im, f32) / 255+ self._put_mask(fg, fgc, m, x, y, col)+ for it in self.osd[:n]:+ kind = it[0]+ if kind == 'text':+ _, s, x, y, px, col, anchor = it+ put(_glyph_bitmap(s), x, y, px, col, anchor)+ elif kind == 'rec':+ _, x, y, px = it+ r = px * 2.6+ m = self.ellipse(x + r, y + px * 3.5, r, r)+ fg[:] = np.maximum(fg, m); fgc += (hexc('#ff2a1e') - fgc) * m[..., None]+ put(_glyph_bitmap('REC'), x + r * 2 + px * 2, y, px, hexc('#f4f4ee'))+ elif kind == 'battery':+ _, x, y, px, level, of = it+ cols = 3 * of + 3+ b = np.zeros((7, cols), np.uint8)+ b[0, :cols - 2] = 1; b[6, :cols - 2] = 1; b[:, 0] = 1; b[:, cols - 3] = 1; b[2:5, cols - 2:] = 1+ for k in range(level): b[2:5, 2 + 3 * k:4 + 3 * k] = 1+ put(b, x, y, px, hexc('#f4f4ee'))+ elif kind == 'zoom':+ _, x, y, px, pos, width = it+ n = max(12, int(width / (px * 0.8)))+ bar = np.zeros((7, n), np.uint8)+ bar[1, :] = 1; bar[5, :] = 1; bar[1:6, 0] = 1; bar[1:6, -1] = 1+ k = int(round(pos * (n - 1)))+ bar[2:5, :k] = 1+ bar[0:7, max(k - 1, 0):k + 1] = 1+ wdots = _glyph_bitmap('W ')+ put(np.concatenate([wdots, bar, np.zeros((7, 2), np.uint8), _glyph_bitmap('T')], 1), x, y, px, hexc('#f4f4ee'))+ # black edge: dilate the glyphs a few px+ e = fg.copy()+ for dx, dy in ((-3, 0), (3, 0), (0, -3), (0, 3), (-2, -2), (2, 2), (-2, 2), (2, -2), (3, 2), (2, 3)):+ e = np.maximum(e, shift(fg, dx, dy))+ edge = np.clip(e, 0, 1)+ return fg, fgc, edge++ def _put_mask(self, fg, fgc, m, x, y, col):+ h, w = m.shape+ x0, y0 = int(round(x)), int(round(y))+ xa, ya = max(x0, 0), max(y0, 0)+ xb, yb = min(x0 + w, self.W), min(y0 + h, self.H)+ if xb <= xa or yb <= ya: return+ sub = m[ya - y0:yb - y0, xa - x0:xb - x0]+ fg[ya:yb, xa:xb] = np.maximum(fg[ya:yb, xa:xb], sub)+ fgc[ya:yb, xa:xb] += (col - fgc[ya:yb, xa:xb]) * sub[..., None]++ # ================================================================ render passes+ def _camera(self, img):+ c = self.cam+ H, W = self.H, self.W+ r = np.random.default_rng(c['seed'])+ th = np.radians(c['tilt'])+ s = (np.cos(abs(th)) + (W / H) * np.sin(abs(th))) * c['zoom']+ # hand-held roll + zoom about the centre (inverse affine for PIL)+ ca, sa = np.cos(th) / s, np.sin(th) / s+ cx, cy = W / 2, H / 2+ A = (ca, -sa, cx - ca * cx + sa * cy, sa, ca, cy - sa * cx - ca * cy)+ img = np.stack([np.asarray(Image.fromarray(img[..., k], 'F').transform((W, H), Image.AFFINE, A, Image.BILINEAR), f32)+ for k in range(3)], -1)+ img *= c['wb'] * c['exposure']+ lum = img.max(-1)+ if c['lag'] and c['lag'][2] > 0:+ dx, dy, k = c['lag']+ hi = img * (np.clip(lum - 1.2, 0, None) / (lum + 1e-6))[..., None]+ tail = np.zeros_like(img)+ for i in range(1, 9):+ tail = np.maximum(tail, shift(hi, dx * i / 8, dy * i / 8) * (1 - i / 9))+ img += _gb(tail, 2.0) * k+ if c['bloom'] > 0:+ hot = img * (np.clip(lum - 1.0, 0, None) / (lum + 1e-6))[..., None]+ h4 = _resize(hot, W // 4, H // 4, Image.BOX) # wide radii at quarter resolution+ wide = _resize(_gb(h4, 22 / 4) * 0.35 + _gb(h4, 70 / 4) * 0.25, W, H, Image.BILINEAR)+ img += (_gb(hot, 6) * 0.5 + wide) * c['bloom']+ if c['smear'] > 0:+ hot = np.clip(img - 2.2, 0, None) # only point sources far over full-well+ col = _blur_axis(hot.sum(0) / H * 30.0, 0.8, 0) # the charge spilled while the column is read out+ prof = 0.55 + 0.45 * np.exp(-((self.YY[:, :1] - (np.argmax(hot.max(-1), 0)[None, :])) / 260.0) ** 2)+ img += col[None, :, :] * prof[..., None] * c['smear']+ if c['soft'] > 0:+ img = _gb(img, c['soft'])+ rr = ((self.XX - cx) / cx) ** 2 + ((self.YY - cy) / cy) ** 2+ img *= (1 - c['vignette'] * np.clip(rr / 2, 0, 1) ** 1.3)[..., None]+ # gain noise, worse in the dark, a little blotchy+ lum = img.mean(-1)+ n = blur(r.normal(0, 1, (H, W)).astype(f32), 1.0) * 1.8+ nc = _gb(r.normal(0, 1, (H, W, 2)).astype(f32), 2.0) * 2.0+ amt = c['gain_noise'] * (0.35 + 0.65 * np.clip(1 - lum * 1.6, 0, 1))+ img += (n * amt)[..., None]+ img[..., 0] += nc[..., 0] * amt * 0.6; img[..., 2] += nc[..., 1] * amt * 0.6+ return self._knee(img, c['knee'])++ @staticmethod+ def _knee(x, k):+ x = np.clip(x, 0, None)+ y = np.where(x < k, x, k + (1 - k) * (1 - np.exp(-(x - k) / (1 - k))))+ return np.clip(y, 0, 1).astype(f32)++ def _tape(self, img):+ L, S = self.lines, self.samples+ rc, wr = self.rec_, self.wear_+ a = _resize(img, S, L, Image.BOX)+ R, G, B = a[..., 0], a[..., 1], a[..., 2]+ Y = 0.299 * R + 0.587 * G + 0.114 * B+ I = 0.596 * R - 0.274 * G - 0.322 * B+ Q = 0.211 * R - 0.523 * G + 0.312 * B+ # luma: band-limited, then the playback sharpness circuit+ Y = _blur_axis(Y, rc['luma'], 1)+ if rc['sharpen']:+ Y = Y + rc['sharpen'] * (Y - _blur_axis(Y, rc['sharp_r'], 1))+ # chroma: colour-under bandwidth, comb filter over neighbouring lines, delay to the right+ C = np.stack([I, Q], -1)+ C = _blur_axis(C, rc['chroma'], 1)+ if rc['chroma_v']: C = _blur_axis(C, rc['chroma_v'], 0)+ C = _rowshift(C, np.full(L, rc['delay'], f32), 0.0)+ C *= rc['saturation']+ if wr:+ r = np.random.default_rng(wr['seed'])+ # streaky luma noise and horizontal chroma noise+ n = _blur_axis(r.normal(0, 1, (L, S)).astype(f32), 1.1, 1) * 1.6+ Y = Y + n * wr['noise'] * (0.6 + 0.8 * np.clip(1 - Y, 0, 1))+ cn = _blur_axis(r.normal(0, 1, (L, S, 2)).astype(f32), 9.0, 1) * 4.0+ C = C + cn * wr['chroma_noise']+ # timebase jitter + flagging at the top+ off = fbm1d(L, 40, 4, int(r.integers(1 << 30))) * wr['jitter'] * 2 + r.normal(0, wr['jitter'] * 0.35, L)+ top = np.arange(L, dtype=f32)+ off += wr['flagging'] * np.exp(-top / 7.0)+ # tracking band+ band = np.zeros(L, f32)+ if wr['tracking']:+ yc, bh = wr['tracking'][0] * L, wr['tracking'][1] * L+ band = np.exp(-((top - yc) / (bh * 0.5)) ** 4).astype(f32)+ off += band * r.normal(0, 1, L) * 9 + band * 6+ # head switching: the last lines slide to the right and tear+ hs = wr['head_switch']+ if hs:+ k = np.clip((top - (L - hs)) / hs, 0, 1)+ off += k ** 1.5 * (18 + r.normal(0, 5, L) * k)+ YC = _rowshift(np.concatenate([Y[..., None], C], -1), off.astype(f32), 0.0)+ Y, C = YC[..., 0], YC[..., 1:]+ # noise inside the tracking band: white streaks, grey hash, ragged+ if wr['tracking']:+ for j in np.flatnonzero(band > 0.05):+ b = band[j]+ hsh = _blur_axis(r.normal(0, 1, S).astype(f32)[None, :], 0.8, 1)[0]+ Y[j] = Y[j] * (1 - 0.45 * b) + 0.45 * b * (0.45 + 0.3 * hsh)+ for _ in range(int(r.poisson(4.0 * b))):+ x0 = int(r.integers(0, S)); ln = int(r.integers(6, 70))+ Y[j, x0:x0 + ln] = np.maximum(Y[j, x0:x0 + ln], r.uniform(0.75, 1.05))+ if j + 1 < L and r.random() < 0.5:+ Y[j + 1, x0:x0 + ln] = np.maximum(Y[j + 1, x0:x0 + ln], r.uniform(0.5, 0.8))+ C[j] *= (1 - 0.6 * b)+ if hs:+ for j in range(L - hs, L):+ Y[j] = Y[j] * 0.8 + 0.2 * (0.45 + 0.3 * r.normal(0, 1, S).astype(f32))+ # dropouts: short white flecks (with a dark tail)+ for _ in range(int(wr['dropouts'])):+ j = int(r.integers(4, L - 4)); x0 = int(r.integers(0, S - 4)); ln = int(np.clip(r.exponential(9) + 1, 1, 60))+ Y[j, x0:x0 + ln] = r.uniform(0.85, 1.1)+ Y[j, x0 + ln:x0 + ln + 6] *= 0.6+ C[j, x0:x0 + ln] *= 0.2+ # blanking at the left edge (follows the jitter) and a lifted black level+ ledge = np.clip(off, 0, None) + 3 + r.normal(0, 0.6, L)+ Y = np.where(np.arange(S)[None, :] < ledge[:, None], 0.0, Y)+ Y = wr['black'] + Y * (1 - wr['black'] * 0.8)+ Y = Y.astype(f32)+ Ii, Qi = C[..., 0], C[..., 1]+ R = Y + 0.956 * Ii + 0.621 * Qi+ G = Y - 0.272 * Ii - 0.647 * Qi+ B = Y - 1.106 * Ii + 1.703 * Qi+ out = np.clip(np.stack([R, G, B], -1), 0, 1.1)+ up = _resize(out, self.W, self.H, Image.BICUBIC)+ if wr and wr['lines']:+ yy = self.YY[:, :1] * L / self.H+ up *= (1 - wr['lines'] * (0.5 + 0.5 * np.cos(2 * np.pi * yy)))[..., None]+ return np.clip(up, 0, 1)++ def composite(self, n_osd=None):+ img = self._lit()+ if self.cam is not None:+ img = self._camera(img)+ else:+ img = self._knee(img, 0.8)+ n = len(self.osd) if n_osd is None else n_osd+ if n:+ fg, fgc, edge = self._osd_layer(n)+ img = img * (1 - edge * 0.85)[..., None]+ img = img * (1 - fg[..., None]) + fgc * fg[..., None]+ if self.rec_ is not None:+ img = self._tape(img)+ return Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8), 'RGB')++ def stage(self, name):+ if self.keep_stages:+ self.stages.append((name, self.composite()))++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, im) in enumerate(self.stages):+ im.save(f'{stages_dir}/{i:02d}_{name}.png')+ img.save(f'{stages_dir}/{len(self.stages):02d}_final.png')+ return imgdiff --git a/lib/xray.py b/lib/xray.pynew file mode 100644index 0000000..527d171--- /dev/null+++ b/lib/xray.py@@ -0,0 +1,900 @@+"""xray — an X-ray transmission picture (baggage scanner / radiograph): every object is built as real material+measured along the beam, the beam goes through it by Beer-Lambert, and the result is seen through a line-scan+detector and a display (numpy + Pillow only).++Nothing is painted as a picture of an object. The picture is built in four passes, the way the real thing works:++ 1. material every object adds its *path length along the beam* times its attenuation to two maps, one per+ beam energy (a dual-energy scanner: A_lo at ~60 keV, A_hi at ~120 keV):+ A_E += mu_E(material) * density * length+ All lengths are canvas px, including depths along the beam; `px_cm` sets the physical scale, so+ 1 cm of steel is ~9.5 at low energy and 1 cm of plastic ~0.2 (MATERIALS, approximate values from+ mass attenuation tables). There is no draw order: overlapping things simply add, as on a real film.+ Shapes are 3D bodies, not flat fills:+ slab a solid with rounded edges over a closed outline (key, coin, circuit board, plaster bone);+ shell a hollow body with a wall (suitcase, hairdryer housing, camera body). Near its outline+ the beam runs along the side wall, so the path through material is long there: X-ray+ outlines glow for a physical reason and the middle stays faint;+ rod a round wire or rod along a path (chord 2*sqrt(r^2 - d^2)); with `wall` it is a tube+ (bright edges, darker core). A path may carry depth z per point: where a wire dives along+ the beam (the turning points of a spring) the chord is longer, so coils show bright+ turning points and the zig-zag of their near and far halves;+ coil, zipper, screw, cable, ball, disc (seen face-on: coin with a raised rim, washer, lens whose+ glass is thickest in the middle, a barrel ring seen end-on is all wall), fabric (folded+ layers whose turned-over edges read as soft rims, knit / twill / plain weave, creases).+ 2. detector transmission I_E = exp(-A_E). Compton scatter adds a low-frequency haze of the surrounding flux+ (dense objects lose edge contrast and the air around them lifts a little); focal-spot blur; the+ line-scan detector (one column of pixels, the belt drags the bag past it) has its own gain per row,+ so the picture carries faint horizontal streaks and a seam every 64 rows (one detector module);+ quantum (Poisson) noise grows where few photons get through, so metal is grainy and the densest+ parts are photon-starved. Measured A'_E = -ln(I').+ 3. display 'film' (radiograph look): dense = bright. Log compression of a mix of both energies, unsharp edge+ enhancement (a bright rim on the inside of every edge, a dark undershoot just outside), phosphor+ glow around bright parts, a blue-steel LUT. 'material' (security pseudo-colour): Zeff from the+ ratio A'_lo / A'_hi -> organic orange, inorganic green, metal blue, opaque black, white where the+ beam went through nothing; the thicker, the deeper the colour.+ 4. OSD crisp monospace overlay at output resolution: status bar, numbered flag boxes, insets of any+ region in either display, a material legend, an attenuation scale whose ticks are computed through+ the same display curve, and text whose readings ({tag.z}, {tag.ml}, {tag.cm2}) are measured from+ that stage's detector image, background-subtracted around the tagged object -- so the numbers+ always agree with the picture.++Stages are cheap: `stage(name)` keeps a float16 copy of both maps and the OSD so far; `save()` runs the detector+and the display for every stage with the same noise, so snapshots differ only where something was added.++ from xray import XRay+ x = XRay(1920, 1080, px_cm=17, seed=1)+ x.belt(120, 980)+ case = x.rrect(700, 550, 1190, 714, 90)+ x.shell(case, 'organic', depth=425, wall=5, edge=70, density=1.2) # 25 cm deep polycarbonate case+ x.rod(x.path([(300, 300), (600, 360)]), 'steel', 4, wall=0.7) # a thin steel tube+ x.coil((320, 420), (560, 420), 22, 9, 'steel', 1.2) # a spring+ x.slab(x.ellipse(800, 600, 60, 40), 'plaster', 30, tag='rock')+ x.flag(730, 550, 870, 650, 1, 'BONE-LIKE Zeff {rock.z:.1f}')+ x.save('out.jpg')++Coordinates are canvas px, y down; angles in degrees, clockwise on screen.+"""+import os+import string+import numpy as np+from PIL import Image, ImageDraw, ImageFilter, ImageFont+from core import fbm1d, spline, noise2d, smoothstep, load_font+++def blur(a, sigma):+ """same 3-box gaussian as core.blur, but slices views instead of np.take copies (half the transient memory+ on full-frame passes)"""+ if sigma <= 0:+ return np.array(a, np.float32)+ out = np.asarray(a, np.float32)+ w = int(np.sqrt(12 * sigma * sigma / 3 + 1))+ w += (w % 2 == 0)+ r = w // 2+ for _ in range(3):+ for ax in (0, 1):+ pad = [(0, 0), (0, 0)]+ pad[ax] = (r + 1, r)+ c = np.cumsum(np.pad(out, pad, mode='edge'), axis=ax, dtype=np.float64)+ d = (c[w:] - c[:-w]) if ax == 0 else (c[:, w:] - c[:, :-w])+ del c+ d /= w+ out = d.astype(np.float32)+ del d+ return out++# linear attenuation coefficients (1/cm) at nominal density, (~60 keV, ~120 keV). Rounded from mass attenuation+# tables x density; good enough that steel, plaster and plastic separate the way they do on a real scanner.+MATERIALS = {+ 'organic': (0.200, 0.158), # plastics, fibre, wood, food, paper (rho ~1)+ 'water': (0.206, 0.162),+ 'rubber': (0.235, 0.180),+ 'pvc': (0.350, 0.215), # chlorine pushes it toward 'inorganic'+ 'pcb': (0.420, 0.265), # glass-epoxy board+ 'magnesium': (0.420, 0.265),+ 'mica': (0.620, 0.355),+ 'glass': (0.670, 0.380),+ 'aluminium': (0.750, 0.420),+ 'bone': (0.600, 0.320),+ 'plaster': (0.690, 0.360), # gypsum casting plaster: bone-like+ 'ferrite': (4.50, 1.05),+ 'zinc': (11.0, 2.30), # die-cast zinc alloy (zip sliders, padlocks)+ 'steel': (9.50, 2.30),+ 'brass': (12.6, 2.75),+ 'copper': (14.2, 3.00),+ 'tin': (30.0, 6.0), # solder+ 'lead': (57.0, 44.0),+}++# A_lo / A_hi ratio -> effective atomic number (calibrated on the table above)+_R_K = np.array([1.10, 1.25, 1.31, 1.56, 1.79, 1.92, 2.60, 4.13, 4.75], np.float32)+_Z_K = np.array([5.0, 7.0, 7.6, 11.0, 13.0, 14.5, 18.5, 26.0, 29.5], np.float32)++FILM = [(0.00, '#03070d'), (0.05, '#071420'), (0.16, '#123049'), (0.32, '#2a5d80'), (0.50, '#5d9cc2'),+ (0.68, '#a6d4ec'), (0.84, '#def3fd'), (1.00, '#ffffff')]+RAMPS = { # security pseudo-colour: thin -> thick for each material class+ 'organic': [(0, '#ffffff'), (0.10, '#fdebcf'), (0.35, '#f5b25e'), (0.65, '#cf7419'), (1.0, '#5a2a05')],+ 'inorganic': [(0, '#ffffff'), (0.10, '#e6f3d2'), (0.35, '#9fd07a'), (0.65, '#4b9638'), (1.0, '#123d10')],+ 'metal': [(0, '#ffffff'), (0.10, '#dce8fa'), (0.35, '#86b0ec'), (0.65, '#3460c4'), (1.0, '#0b1a55')],+}+CYAN, AMBER, GREEN, RED, INK = '#bfe6fa', '#ffb347', '#79e3a0', '#ff6f59', '#06101a'+++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 _rgb8(h):+ return tuple(int(c * 255 + 0.5) for c in hexc(h))+++def lut(stops, n=1024):+ xs = np.array([s for s, _ in stops], np.float32)+ cs = np.stack([hexc(c) for _, c in stops])+ t = np.linspace(0, 1, n, dtype=np.float32)+ return np.stack([np.interp(t, xs, cs[:, k]) for k in range(3)], 1).astype(np.float32)+++def _mono(size, bold=False):+ cands = [('/System/Library/Fonts/Menlo.ttc', 1 if bold else 0), ('/System/Library/Fonts/SFNSMono.ttf', 0),+ ('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf' if bold else+ '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', 0),+ ('C:/Windows/Fonts/consolab.ttf' if bold else 'C:/Windows/Fonts/consola.ttf', 0)]+ env = os.environ.get('INKPAINT_FONT_MONO')+ if env: cands.insert(0, (env, 0))+ for p, i in cands:+ if os.path.exists(p):+ try:+ return ImageFont.truetype(p, int(size), index=i)+ except OSError:+ pass+ return load_font('typewriter', size)+++class _Reading:+ """what the scanner measures for one tagged object (background-subtracted)"""+ def __init__(self, z=0.0, ml=0.0, cm2=0.0, a=0.0):+ self.z, self.ml, self.cm2, self.a = z, ml, cm2, a+++class XRay:+ def __init__(self, W=1920, H=1080, px_cm=17.0, seed=0):+ self.W, self.H, self.px = W, H, float(px_cm)+ self.seed = seed+ self.rng = np.random.default_rng(seed)+ self.Alo = np.zeros((H, W), np.float32)+ self.Ahi = np.zeros((H, W), np.float32)+ self.tags, self.osd, self.stages = {}, [], []+ self._noise, self._calib = None, None+ self.scan()+ self.film()++ def _seed(self):+ return int(self.rng.integers(1 << 30))++ # ------------------------------------------------------------ outlines and paths (canvas px)+ @staticmethod+ def _place(P, cx, cy, rot):+ a = np.radians(rot)+ c, s = np.cos(a), np.sin(a)+ P = np.asarray(P, np.float32)+ return np.stack([cx + P[:, 0] * c - P[:, 1] * s, cy + P[:, 0] * s + P[:, 1] * c], 1).astype(np.float32)++ @classmethod+ def rrect(cls, cx, cy, w, h, r=0.0, rot=0.0, n=10):+ """rounded-rectangle outline"""+ r = float(min(max(r, 0), w / 2, h / 2))+ pts = []+ for sx, sy, a0 in [(1, 1, 0), (-1, 1, 90), (-1, -1, 180), (1, -1, 270)]:+ ox, oy = sx * (w / 2 - r), sy * (h / 2 - r)+ for a in (np.linspace(a0, a0 + 90, n) if r > 0.5 else [a0 + 45]):+ if r > 0.5:+ pts.append((ox + r * np.cos(np.radians(a)), oy + r * np.sin(np.radians(a))))+ else:+ pts.append((sx * w / 2, sy * h / 2))+ return cls._place(pts, cx, cy, rot)++ @classmethod+ def ellipse(cls, cx, cy, rx, ry, rot=0.0, n=96):+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)+ return cls._place(np.stack([np.cos(t) * rx, np.sin(t) * ry], 1), cx, cy, rot)++ @classmethod+ def poly(cls, pts, cx=0.0, cy=0.0, rot=0.0, scale=1.0):+ """a local outline (list of points) scaled, rotated and moved onto the canvas"""+ return cls._place(np.asarray(pts, np.float32) * scale, cx, cy, rot)++ @staticmethod+ def path(ctrl, per=12):+ """smooth path through control points (Catmull-Rom); points may carry a 3rd value (depth z)"""+ ctrl = np.asarray(ctrl, np.float32)+ if len(ctrl) < 3:+ return ctrl+ return spline(ctrl, per)++ @staticmethod+ def closed(ctrl, per=10):+ """smooth closed outline through control points"""+ c = np.asarray(ctrl, np.float32)+ P = spline(np.vstack([c[-1:], c, c[:2]]), per)+ return P[per:per * (len(c) + 1)]++ @staticmethod+ def offset(P, d):+ """path shifted sideways by d px (positive = to the right of the direction of travel, y down)"""+ P = np.asarray(P, np.float32)+ g = np.gradient(P[:, :2], axis=0)+ g /= np.linalg.norm(g, axis=1, keepdims=True) + 1e-6+ out = P.copy()+ out[:, 0] -= g[:, 1] * d+ out[:, 1] += g[:, 0] * d+ return out++ # ------------------------------------------------------------ geometry kernels+ def _box(self, pts, pad):+ x0 = int(max(0, np.floor(pts[:, 0].min() - pad)))+ y0 = int(max(0, np.floor(pts[:, 1].min() - pad)))+ x1 = int(min(self.W, np.ceil(pts[:, 0].max() + pad) + 1))+ y1 = int(min(self.H, np.ceil(pts[:, 1].max() + pad) + 1))+ return None if x1 <= x0 or y1 <= y0 else (x0, y0, x1, y1)++ def _sdf(self, loops, band):+ """signed distance (px, + inside) to a shape of closed loops (first the outline, then holes; even-odd),+ exact within `band` of an edge, clamped to +-band further away. Returns (x0, y0, D) or None."""+ loops = [np.asarray(L, np.float32)[:, :2] for L in loops]+ b = self._box(np.vstack(loops), 3)+ if b is None:+ return None+ x0, y0, x1, y1 = b+ im = Image.new('L', (x1 - x0, y1 - y0), 0)+ d = ImageDraw.Draw(im)+ for i, L in enumerate(loops):+ d.polygon([(float(x - x0), float(y - y0)) for x, y in L], fill=255 if i == 0 else 0)+ m = np.asarray(im, np.float32) / 255+ bm = blur(np.pad(m, 4), max(1.0, band / 2.4))[4:-4, 4:-4]+ near = (bm > 0.0015) & (bm < 0.9985)+ D = np.where(m > 0.5, band, -band).astype(np.float32)+ ys, xs = np.nonzero(near)+ if len(xs):+ px = (xs + x0).astype(np.float32)+ py = (ys + y0).astype(np.float32)+ d2 = np.full(px.shape, np.inf, np.float32)+ cross = np.zeros(px.shape, np.int32)+ for L in loops:+ A, B = L, np.roll(L, -1, 0)+ for k in range(0, len(A), 16):+ a, bb = A[k:k + 16], B[k:k + 16]+ dx, dy = bb[:, 0] - a[:, 0], bb[:, 1] - a[:, 1]+ l2 = dx * dx + dy * dy + 1e-9+ for c0 in range(0, len(px), 65536):+ qx = px[c0:c0 + 65536, None] - a[None, :, 0]+ qy = py[c0:c0 + 65536, None] - a[None, :, 1]+ t = np.clip((qx * dx + qy * dy) / l2, 0, 1)+ ex, ey = qx - t * dx, qy - t * dy+ np.minimum(d2[c0:c0 + 65536], (ex * ex + ey * ey).min(1), out=d2[c0:c0 + 65536])+ up = (a[None, :, 1] > py[c0:c0 + 65536, None]) != (bb[None, :, 1] > py[c0:c0 + 65536, None])+ xi = a[None, :, 0] + qy * dx / np.where(np.abs(dy) < 1e-9, 1e-9, dy)+ cross[c0:c0 + 65536] += (up & (px[c0:c0 + 65536, None] < xi)).sum(1)+ D[ys, xs] = np.minimum(np.sqrt(d2), band) * np.where(cross % 2 == 1, 1, -1)+ return x0, y0, D++ def _nearest(self, P, px, py):+ """distance from points to the polyline P, plus arc length and segment index of the nearest point"""+ if len(P) == 1:+ P = np.vstack([P, P + 1e-3])+ A, B = P[:-1], P[1:]+ dx, dy = B[:, 0] - A[:, 0], B[:, 1] - A[:, 1]+ ln = np.sqrt(dx * dx + dy * dy)+ s0 = np.concatenate([[0], np.cumsum(ln)]).astype(np.float32)+ l2 = dx * dx + dy * dy + 1e-9+ d2 = np.full(px.shape, np.inf, np.float32)+ sb = np.zeros(px.shape, np.float32)+ ib = np.zeros(px.shape, np.int32)+ for k in range(0, len(A), 16):+ a = A[k:k + 16]+ for c0 in range(0, len(px), 65536):+ sl = slice(c0, c0 + 65536)+ qx = px[sl, None] - a[None, :, 0]+ qy = py[sl, None] - a[None, :, 1]+ t = np.clip((qx * dx[None, k:k + 16] + qy * dy[None, k:k + 16]) / l2[None, k:k + 16], 0, 1)+ ex, ey = qx - t * dx[None, k:k + 16], qy - t * dy[None, k:k + 16]+ e2 = ex * ex + ey * ey+ j = e2.argmin(1)+ m = e2[np.arange(len(j)), j]+ better = m < d2[sl]+ d2[sl] = np.where(better, m, d2[sl])+ sb[sl] = np.where(better, s0[k + j] + t[np.arange(len(j)), j] * ln[k + j], sb[sl])+ ib[sl] = np.where(better, k + j, ib[sl])+ return np.sqrt(d2), sb, ib, s0++ @staticmethod+ def _ext(x, h, rc):+ """extent along the beam of a slab of height h with edges rounded at radius rc, at x px inside its outline"""+ rc = float(min(max(rc, 0.0), h / 2))+ if h <= 0:+ return np.zeros_like(x)+ if rc < 0.05:+ return np.where(x > 0, h, 0).astype(np.float32)+ xc = np.clip(x, 0, rc)+ e = h - 2 * (rc - np.sqrt(np.clip(rc * rc - (rc - xc) ** 2, 0, None)))+ return np.where(x > 0, e, 0).astype(np.float32)++ @staticmethod+ def _aa(D, fn):+ return (fn(D - 0.33) + fn(D) + fn(D + 0.33)) / 3++ def _add(self, x0, y0, t, material, density=1.0, tag=None):+ lo, hi = MATERIALS[material] if isinstance(material, str) else material+ k = density / self.px+ h, w = t.shape+ self.Alo[y0:y0 + h, x0:x0 + w] += t * (lo * k)+ self.Ahi[y0:y0 + h, x0:x0 + w] += t * (hi * k)+ if tag:+ self.tags.setdefault(tag, []).append((x0, y0, t > 0.3))++ # ------------------------------------------------------------ bodies+ def slab(self, outline, material, depth, edge=None, holes=(), density=1.0, tag=None, texture=None):+ """solid `depth` px thick along the beam over a closed outline; edges rounded at radius `edge`+ (default depth/2: a pebble / round bar edge; 0: a sawn edge). holes: outlines cut right through."""+ edge = depth / 2 if edge is None else edge+ r = self._sdf([outline, *holes], band=edge + 2)+ if r is None:+ return+ x0, y0, D = r+ t = self._aa(D, lambda d: self._ext(d, depth, edge))+ if texture is not None:+ t *= texture(x0, y0, t.shape)+ self._add(x0, y0, t, material, density, tag)++ def shell(self, outline, material, depth, wall, edge=None, density=1.0, tag=None, holes=()):+ """hollow body (case, housing): walls `wall` px thick, `depth` px deep along the beam, rounded edges.+ Seen through, the outline is where the beam runs along the wall -> a bright rim, a faint inside."""+ edge = depth / 2 if edge is None else edge+ r = self._sdf([outline, *holes], band=edge + wall + 2)+ if r is None:+ return+ x0, y0, D = r+ fn = lambda d: self._ext(d, depth, edge) - self._ext(d - wall, depth - 2 * wall, edge - wall)+ self._add(x0, y0, self._aa(D, fn), material, density, tag)++ def rod(self, P, material, r, wall=None, density=1.0, tag=None, ribs=None, flat=None):+ """round wire / rod along a path P ((N,2), or (N,3) with depth z in px); r: radius, scalar or per point.+ wall: tube wall thickness (hollow). ribs=(amount, period px): thread / coiled-coil / twisted-strand ripple.+ flat: a flat strip of that thickness instead of a round section (umbrella rib, key blade seen edge-on);+ may be a function of arc length s (px from the first point)."""+ P = np.asarray(P, np.float32)+ z = P[:, 2] if P.shape[1] > 2 else None+ P2 = np.ascontiguousarray(P[:, :2])+ rr = np.broadcast_to(np.asarray(r, np.float32), (len(P2),)).astype(np.float32)+ b = self._box(P2, rr.max() + 3)+ if b is None:+ return+ x0, y0, x1, y1 = b+ im = Image.new('L', (x1 - x0, y1 - y0), 0)+ dr = ImageDraw.Draw(im)+ q = [(float(x - x0), float(y - y0)) for x, y in P2]+ wd = int(np.ceil(2 * rr.max() + 4))+ if len(q) > 1:+ dr.line(q, fill=255, width=wd, joint='curve')+ for x, y in (q[0], q[-1]):+ dr.ellipse([x - wd / 2, y - wd / 2, x + wd / 2, y + wd / 2], fill=255)+ ys, xs = np.nonzero(np.asarray(im))+ if not len(xs):+ return+ d, s, idx, s0 = self._nearest(P2, (xs + x0).astype(np.float32), (ys + y0).astype(np.float32))+ R = np.interp(s, s0, rr)+ if flat is not None:+ fl = flat(s) if callable(flat) else float(flat)+ chord = lambda dd, RR: np.where(np.abs(dd) < RR, fl, 0.0)+ else:+ chord = lambda dd, RR: 2 * np.sqrt(np.clip(RR * RR - dd * dd, 0, None))+ t = (chord(d - 0.33, R) + chord(d, R) + chord(d + 0.33, R)) / 3+ if wall is not None:+ Ri = np.maximum(R - wall, 0)+ t -= (chord(d - 0.33, Ri) + chord(d, Ri) + chord(d + 0.33, Ri)) / 3+ if z is not None:+ seg2 = np.linalg.norm(np.diff(P2, axis=0), axis=1) + 1e-6+ seg3 = np.sqrt(seg2 ** 2 + np.diff(z) ** 2)+ k = np.clip(seg3 / seg2, 1, 7) if len(seg2) else np.ones(1)+ t *= k[np.clip(idx, 0, len(k) - 1)]+ if ribs is not None:+ t *= 1 + ribs[0] * np.cos(2 * np.pi * s / ribs[1])+ tt = np.zeros((y1 - y0, x1 - x0), np.float32)+ tt[ys, xs] = np.maximum(t, 0)+ self._add(x0, y0, tt, material, density, tag)++ def edgeon(self, p0, p1, thick, material, hole=0.0, **kw):+ """a disc or ring seen edge-on (fan, grille, filter, washer on its side): a strip p0 -> p1 `thick` px wide+ whose depth along the beam is the disc's chord at each point"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ R = float(np.linalg.norm(p1 - p0)) / 2++ def f(s):+ out = 2 * np.sqrt(np.clip(R * R - (s - R) ** 2, 0, None))+ if hole:+ out = out - 2 * np.sqrt(np.clip(hole * hole - (s - R) ** 2, 0, None))+ return out+ self.rod(np.stack([p0, p1]), material, thick / 2, flat=f, **kw)++ def tube(self, P, material, r, wall, **kw):+ self.rod(P, material, r, wall=wall, **kw)++ def coil(self, p0, p1, R, turns, material, r_wire, phase=0.0, per=28, density=1.0, tag=None, ribs=None):+ """helical spring / heating coil wound round the axis p0 -> p1 with radius R, seen from the side"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ n = int(turns * per) + 1+ th = np.radians(phase) + np.linspace(0, 2 * np.pi * turns, n)+ u = np.linspace(0, 1, n)[:, None]+ e = (p1 - p0) / (np.linalg.norm(p1 - p0) + 1e-6)+ nrm = np.array([-e[1], e[0]], np.float32)+ P = p0 + (p1 - p0) * u + nrm * (R * np.sin(th))[:, None]+ self.rod(np.column_stack([P, R * np.cos(th)]), material, r_wire, density=density, tag=tag, ribs=ribs)++ def ball(self, cx, cy, r, material, density=1.0, tag=None):+ """a sphere (bearing ball, bead)"""+ self.disc(cx, cy, r, material, 0, dome=2 * r, sphere=True, density=density, tag=tag)++ def disc(self, cx, cy, r, material, depth, hole=0.0, rim=None, dome=0.0, sphere=False, density=1.0, tag=None):+ """round thing seen face-on: coin (rim=(width, extra depth)), washer / ring seen end-on (hole), lens+ (dome > 0: that much thicker in the middle; < 0: concave)"""+ b = self._box(np.array([[cx - r, cy - r], [cx + r, cy + r]], np.float32), 2)+ if b is None:+ return+ x0, y0, x1, y1 = b+ yy, xx = np.mgrid[y0:y1, x0:x1].astype(np.float32)+ rr = np.hypot(xx - cx, yy - cy)+ cov = np.clip(r - rr + 0.5, 0, 1)+ if hole:+ cov *= np.clip(rr - hole + 0.5, 0, 1)+ if sphere:+ t = 2 * np.sqrt(np.clip(r * r - rr * rr, 0, None)) + cov * 0+ else:+ u = np.clip(rr / max(r, 1e-3), 0, 1)+ t = depth + dome * (1 - u * u)+ if rim is not None:+ t = t + rim[1] * smoothstep(r - rim[0] - 1.2, r - rim[0], rr)+ t = np.maximum(t, 0) * cov+ self._add(x0, y0, t.astype(np.float32), material, density, tag)++ def zipper(self, P, material='brass', tooth=(8.0, 5.0), pitch=None, depth=4.0, tape=12.0, tag=None):+ """zip: interlocking teeth alternating either side of the path on a woven tape"""+ P = np.asarray(P, np.float32)[:, :2]+ self.rod(P, 'organic', tape / 2, flat=1.6, density=0.8)+ pitch = pitch or tooth[1] * 0.95+ L = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(P, axis=0), axis=1))])+ for i, s in enumerate(np.arange(pitch / 2, L[-1], pitch)):+ x, y = np.interp(s, L, P[:, 0]), np.interp(s, L, P[:, 1])+ j = min(np.searchsorted(L, s), len(P) - 1)+ g = P[j] - P[max(j - 1, 0)]+ ang = np.degrees(np.arctan2(g[1], g[0]))+ side = 1 if i % 2 else -1+ nx, ny = -np.sin(np.radians(ang)), np.cos(np.radians(ang))+ ox = side * tooth[0] * 0.18+ self.slab(self.rrect(x + nx * ox, y + ny * ox, tooth[1] * 0.82, tooth[0], 1.6, rot=ang), material,+ depth, edge=1.2, tag=tag)++ def screw(self, p0, p1, r, material='steel', head=None, pitch=None, tag=None):+ """machine screw seen from the side: threaded shank p0 -> p1 and a head at p0 (head=(width, height))"""+ p0, p1 = np.asarray(p0, np.float32), np.asarray(p1, np.float32)+ self.rod(np.stack([p0, p1]), material, r, ribs=(0.16, pitch or r * 0.9), tag=tag)+ if head:+ e = (p1 - p0) / (np.linalg.norm(p1 - p0) + 1e-6)+ ang = np.degrees(np.arctan2(e[1], e[0]))+ c = p0 - e * head[1] / 2+ self.slab(self.rrect(c[0], c[1], head[1], head[0], head[1] * 0.4, rot=ang), material, head[0] * 0.9,+ edge=head[0] * 0.3, tag=tag)++ def cable(self, P, r=6.0, cores=2, core_r=1.3, jacket='pvc', core='copper', tag=None):+ """mains / USB cable: insulation jacket with stranded copper cores side by side"""+ P = np.asarray(P, np.float32)+ self.rod(P, jacket, r, tag=tag)+ for k in range(cores):+ off = (k - (cores - 1) / 2) * r * 0.95+ self.rod(self.offset(P, off), core, core_r, ribs=(0.22, 3.2), tag=tag)++ # ------------------------------------------------------------ textiles and the belt+ def weave(self, kind='plain', scale=6.0, angle=0.0, amount=0.25, seed=None):+ """texture multiplier for slab(texture=...): 'plain', 'twill' (denim), 'knit' (chevron columns)"""+ sd = self._seed() if seed is None else seed++ def tex(x0, y0, shape):+ h, w = shape+ yy, xx = np.mgrid[y0:y0 + h, x0:x0 + w].astype(np.float32)+ a = np.radians(angle)+ u = (xx * np.cos(a) + yy * np.sin(a)) / scale+ v = (-xx * np.sin(a) + yy * np.cos(a)) / scale+ if kind == 'twill':+ p = np.cos(2 * np.pi * (u + v * 0.5))+ elif kind == 'knit':+ p = np.cos(2 * np.pi * (u + 0.7 * np.abs((v / 1.3) % 1 - 0.5))) * (0.7 + 0.3 * np.cos(2 * np.pi * v / 1.3))+ else:+ p = np.cos(2 * np.pi * u) * np.cos(2 * np.pi * v)+ slub = noise2d(h, w, max(30, 9 * scale), 3, sd) * 2 - 1+ return (1 + amount * p + amount * 0.8 * slub).astype(np.float32)+ return tex++ def fabric(self, outline, depth, layers=6, sheet=2.0, density=0.5, weave='plain', scale=6.0, angle=0.0,+ creases=(), material='organic', tag=None):+ """folded garment: `layers` sheets `sheet` px thick, stacked `depth` px high. Where the cloth turns over+ at a fold the beam runs along it, so fold edges read as soft brighter rims; creases add a ridge."""+ wall = layers * sheet / 2+ tex = self.weave(weave, scale, angle) if weave else None+ r = self._sdf([outline], band=depth / 2 + wall + 2)+ if r is None:+ return+ x0, y0, D = r+ fn = lambda d: self._ext(d, depth, depth / 2) - self._ext(d - wall, depth - 2 * wall, depth / 2 - wall)+ t = self._aa(D, fn)+ if tex is not None:+ t *= tex(x0, y0, t.shape)+ self._add(x0, y0, t, material, density, tag)+ for c in creases:+ self.rod(c, material, 3.0, density=density * 1.6)++ def belt(self, y0, y1, material='rubber', depth=8.0, cords=True, guides=True, lacing=None):+ """the conveyor belt (rubber with lengthwise cords), steel side guides, an optional steel-hook splice"""+ h = y1 - y0+ t = np.full((h, self.W), depth, np.float32)+ if cords:+ yy = np.arange(h, dtype=np.float32)[:, None]+ t *= 1 + 0.06 * np.cos(2 * np.pi * yy / 7.0) + 0.04 * (noise2d(h, self.W, 200, 3, self._seed()) - 0.5)+ self._add(0, int(y0), t, material)+ lo, hi = MATERIALS[material]+ self._calib = (int(y0), (t * (lo / self.px)).astype(np.float32), (t * (hi / self.px)).astype(np.float32))+ if guides:+ for yg, sgn in ((y0 - 14, -1), (y1 + 14, 1)):+ self.rod(np.array([[-10, yg], [self.W + 10, yg]], np.float32), 'steel', 7, wall=1.2)+ self.rod(np.array([[-10, yg + sgn * 10], [self.W + 10, yg + sgn * 10]], np.float32), 'steel', 3,+ flat=24)+ for xb in np.arange(60, self.W, 240):+ self.disc(xb, yg + sgn * 20, 6, 'steel', 14, hole=2.5)+ if lacing is not None:+ for yk in np.arange(y0 + 6, y1 - 4, 11.0):+ v = np.array([[lacing - 7, yk - 3], [lacing + 1, yk + 1], [lacing - 7, yk + 5]], np.float32)+ self.rod(v, 'steel', 1.3)+ self.rod(v * [-1, 1] + [2 * lacing + 6, 0], 'steel', 1.3)+ self.rod(np.array([[lacing + 3, y0], [lacing + 3, y1]], np.float32), 'steel', 1.6)++ # ------------------------------------------------------------ detector and display settings+ def scan(self, kv=140, ma=0.8, flux=(1700.0, 5000.0), scatter=0.07, scatter_px=55.0, focal=0.6,+ streak=0.004, module=64):+ """detector: photons per pixel at each energy (noise), scatter fraction and reach, focal-spot blur,+ per-row gain spread of the line-scan detector and its module size"""+ self.det = dict(kv=kv, ma=ma, flux=flux, scatter=scatter, scatter_px=scatter_px, focal=focal,+ streak=streak, module=module)+ self._noise = None++ def film(self, a0=0.30, amax=8.5, mix=0.35, edge=(0.9, 0.3), glow=0.5, vignette=0.22, stops=FILM):+ """radiograph display: log curve (a0: knee, amax: full white), energy mix, edge enhancement (fine,+ broad), phosphor glow, vignette, LUT"""+ self.disp = dict(a0=a0, amax=amax, mix=mix, edge=edge, glow=glow, vignette=vignette)+ self._lut = lut(stops)++ def _fixed_noise(self):+ if self._noise is None:+ r = np.random.default_rng(self.seed * 7919 + 13)+ H, W, m = self.H, self.W, self.det['module']+ g = 1 + self.det['streak'] * r.standard_normal(H).astype(np.float32)+ mod = np.repeat(1 + self.det['streak'] * 1.6 * r.standard_normal(H // m + 1).astype(np.float32), m)[:H]+ col = 1 + self.det['streak'] * 0.5 * fbm1d(W, 40, 3, int(r.integers(1 << 30)))+ self._noise = (r.standard_normal((H, W), dtype=np.float32), r.standard_normal((H, W), dtype=np.float32),+ (g * mod).astype(np.float32), col.astype(np.float32))+ return self._noise++ def detect(self, Alo=None, Ahi=None):+ """attenuation maps -> what the detector measures (A'_lo, A'_hi)"""+ Alo = self.Alo if Alo is None else Alo+ Ahi = self.Ahi if Ahi is None else Ahi+ nlo, nhi, grow, gcol = self._fixed_noise()+ dt = self.det+ out = []+ for A, N0, nz in ((Alo, dt['flux'][0], nlo), (Ahi, dt['flux'][1], nhi)):+ I = np.exp(-A.astype(np.float32))+ if dt['focal']:+ I = blur(I, dt['focal'])+ if dt['scatter']: # low-frequency haze: work at 1/4 resolution+ I *= 1 - dt['scatter']+ I += dt['scatter'] / (1 - dt['scatter']) * self._lowpass(I, dt['scatter_px'])+ I *= grow[:, None]+ I *= gcol[None, :]+ I += nz * np.sqrt(np.maximum(I, 0) / N0)+ np.maximum(I, 0.6 / N0, out=I)+ np.log(I, out=I)+ I *= -1+ out.append(np.maximum(I, -0.05, out=I))+ return out++ @staticmethod+ def _lowpass(I, sigma, f=4):+ h, w = I.shape+ hh, ww = max(1, h // f), max(1, w // f)+ small = I[:hh * f, :ww * f].reshape(hh, f, ww, f).mean((1, 3))+ small = blur(small, sigma / f)+ return np.asarray(Image.fromarray(small.astype(np.float32)).resize((w, h), Image.BILINEAR), np.float32)++ def _v(self, A):+ dp = self.disp+ return np.log1p(np.maximum(A, 0) / dp['a0']) / np.log1p(dp['amax'] / dp['a0'])++ def show_film(self, Lo, Hi, vignette=True):+ """film display: dense = bright, edge-enhanced, glowing, blue-steel LUT -> float RGB"""+ dp = self.disp+ v = self._v(dp['mix'] * Lo + (1 - dp['mix']) * Hi).astype(np.float32)+ e1, e2 = dp['edge']+ v = v + e1 * (v - blur(v, 1.4)) + e2 * (v - blur(v, 7))+ if dp['glow']:+ v = v + dp['glow'] * blur(np.clip(v - 0.32, 0, None), 9) + dp['glow'] * 0.35 * blur(np.clip(v - 0.5, 0, None), 28)+ if vignette and dp['vignette']:+ h, w = v.shape+ yy = ((np.arange(h, dtype=np.float32) - h / 2) / (h * 0.62)) ** 2+ xx = ((np.arange(w, dtype=np.float32) - w / 2) / (w * 0.62)) ** 2+ r2 = yy[:, None] + xx[None, :]+ v = v * (1 - dp['vignette'] * np.clip(r2, 0, 1.6) * 0.55) + 0.012 * (1 - np.clip(r2, 0, 1))+ idx = np.clip(v * (len(self._lut) - 1), 0, len(self._lut) - 1).astype(np.int32)+ return self._lut[idx]++ @staticmethod+ def zeff(Lo, Hi):+ R = Lo / np.maximum(Hi, 1e-4)+ Z = np.interp(R, _R_K, _Z_K).astype(np.float32)+ return Z++ def show_material(self, Lo, Hi, k=0.6):+ """security pseudo-colour: hue from Zeff (orange organic, green inorganic, blue metal), depth from how+ much was absorbed, black where nothing got through, white where nothing was"""+ bl, bh = blur(Lo, 0.8), blur(Hi, 0.8)+ Z = self.zeff(bl, bh)+ thin = smoothstep(0.01, 0.07, bh)+ Z = Z * thin + 7.0 * (1 - thin)+ w_org = 1 - smoothstep(9.0, 10.8, Z)+ w_met = smoothstep(17.0, 20.5, Z)+ w_ino = np.clip(1 - w_org - w_met, 0, 1)+ t = 1 - np.exp(-np.maximum(bh, 0) * k)+ idx = np.clip(t * 1023, 0, 1023).astype(np.int32)+ rgb = sum(w[..., None] * lut(RAMPS[c])[idx] for c, w in (('organic', w_org), ('inorganic', w_ino),+ ('metal', w_met)))+ opaque = smoothstep(4.0, 6.0, bh)[..., None]+ return rgb * (1 - opaque) + hexc('#0c0d10') * opaque++ def _measure(self, tag, Lo, Hi, nparts=None):+ parts = self.tags.get(tag, [])[:nparts]+ if not parts:+ return _Reading()+ x0 = max(0, min(p[0] for p in parts) - 30)+ y0 = max(0, min(p[1] for p in parts) - 30)+ x1 = min(self.W, max(p[0] + p[2].shape[1] for p in parts) + 30)+ y1 = min(self.H, max(p[1] + p[2].shape[0] for p in parts) + 30)+ m = np.zeros((y1 - y0, x1 - x0), np.float32)+ for px, py, mk in parts:+ sl = m[py - y0:py - y0 + mk.shape[0], px - x0:px - x0 + mk.shape[1]]+ np.maximum(sl, mk, out=sl)+ inner = m > 0.5+ near = blur(m, 5) > 0.01+ ring = (blur(m, 16) > 0.01) & ~near+ lo, hi = Lo[y0:y1, x0:x1], Hi[y0:y1, x0:x1]+ if ring.sum() < 10 or inner.sum() < 5:+ return _Reading()+ olo = lo[inner] - np.median(lo[ring])+ ohi = hi[inner] - np.median(hi[ring])+ sh = max(float(ohi.sum()), 1e-3)+ ok = ohi > 0.04+ R = float(np.median(olo[ok] / ohi[ok])) if ok.sum() > 20 else float(olo.sum()) / sh+ z = float(np.interp(R, _R_K, _Z_K))+ ml = sh / MATERIALS['water'][1] / self.px ** 2+ return _Reading(z, ml, inner.sum() / self.px ** 2, float(np.median(ohi)))++ # ------------------------------------------------------------ OSD+ def text(self, s, x, y, size=22, colour=CYAN, anchor='la', bold=False, box=None):+ """overlay text; {tag.z} / {tag.ml} / {tag.cm2} are filled with readings of that tag"""+ self.osd.append(('text', s, x, y, size, colour, anchor, bold, box))++ def status(self, left, right=(), y=0, h=58, size=21):+ """top bar: lines of text left and right"""+ self.osd.append(('bar', 0, y, self.W, y + h))+ for i, s in enumerate(left):+ self.text(s, 26, y + 8 + i * 25, size, CYAN if i == 0 else '#8fb9cf', bold=(i == 0))+ for i, s in enumerate(right):+ self.text(s, self.W - 26, y + 8 + i * 25, size, CYAN if i == 0 else '#8fb9cf', 'ra', bold=(i == 0))++ def footer(self, left=(), right=(), h=52, size=19):+ self.osd.append(('bar', 0, self.H - h, self.W, self.H))+ x = 26+ for s, col in left:+ self.text(s, x, self.H - h / 2, size, col, 'lm', box=col if col in (AMBER, GREEN, RED) else None)+ x += _mono(size).getlength(s) + 34+ x = self.W - 26+ for s, col in reversed(list(right)):+ self.text(s, x, self.H - h / 2, size, col, 'rm', box=col if col in (AMBER, GREEN, RED) else None)+ x -= _mono(size).getlength(s) + 30++ def panel(self, x0, y0, x1, y1, title=None, alpha=0.86):+ self.osd.append(('panel', x0, y0, x1, y1, title, alpha))++ def flag(self, x0, y0, x1, y1, n, label, note=None, colour=AMBER, side='top'):+ """numbered alert box: corner brackets, a filled number tag and a label (readings allowed in label/note)"""+ self.osd.append(('flag', x0, y0, x1, y1, n, label, note, colour, side))++ def inset(self, src, dst, mode='material', title=None, frame=CYAN):+ """show region src=(x0, y0, x1, y1) of the scan in dst=(x0, y0, x1, y1) as 'film' or 'material'"""+ self.osd.append(('inset', tuple(src), tuple(dst), mode, title, frame))++ def legend(self, x, y, w, size=17):+ """material classes of the pseudo-colour display"""+ self.osd.append(('legend', x, y, w, size))++ def scale(self, x0, y0, x1, y1, marks, size=16, title=None):+ """attenuation bar in the film display; marks: (label, material, thickness px) placed by the display curve"""+ self.osd.append(('scale', x0, y0, x1, y1, marks, size, title))++ def line(self, pts, colour=CYAN, width=2, dash=None):+ self.osd.append(('line', [tuple(map(float, p)) for p in pts], colour, width, dash))++ def _fmt(self, s, R):+ if '{' not in s:+ return s++ class _Tags(dict):+ def __missing__(self, k):+ return _Reading()+ return string.Formatter().vformat(s, (), _Tags(R))++ @staticmethod+ def _dash(d, pts, col, width, dash):+ for (xa, ya), (xb, yb) in zip(pts[:-1], pts[1:]):+ if not dash:+ d.line([(xa, ya), (xb, yb)], fill=col, width=width)+ continue+ L = float(np.hypot(xb - xa, yb - ya))+ for s in np.arange(0, L, dash * 2):+ e = min(L, s + dash)+ d.line([(xa + (xb - xa) * s / L, ya + (yb - ya) * s / L), (xa + (xb - xa) * e / L, ya + (yb - ya) * e / L)],+ fill=col, width=width)++ def _draw_osd(self, base, items, Lo, Hi, R):+ W, H = self.W, self.H+ bg = Image.new('RGBA', (W, H), (0, 0, 0, 0))+ fg = Image.new('RGBA', (W, H), (0, 0, 0, 0))+ db, df = ImageDraw.Draw(bg), ImageDraw.Draw(fg)+ pastes = []+ for it in items:+ k = it[0]+ if k == 'bar':+ _, x0, y0, x1, y1 = it+ db.rectangle([x0, y0, x1, y1], fill=(3, 9, 15, 205))+ yl = y1 if y0 == 0 else y0+ df.line([(x0, yl), (x1, yl)], fill=_rgb8('#2f5d78') + (255,), width=1)+ elif k == 'panel':+ _, x0, y0, x1, y1, title, alpha = it+ db.rectangle([x0, y0, x1, y1], fill=(3, 9, 15, int(255 * alpha)))+ df.rectangle([x0, y0, x1, y1], outline=_rgb8('#3c7193') + (255,), width=1)+ if title:+ f = _mono(17, True)+ df.text((x0 + 14, y0 + 10), title, font=f, fill=_rgb8(CYAN) + (255,))+ df.line([(x0 + 14, y0 + 36), (x1 - 14, y0 + 36)], fill=_rgb8('#2f5d78') + (255,), width=1)+ elif k == 'text':+ _, s, x, y, size, col, anchor, bold, box = it+ s = self._fmt(s, R)+ f = _mono(size, bold)+ if box:+ l, t, r, b = df.textbbox((x, y), s, font=f, anchor=anchor)+ df.rectangle([l - 7, t - 5, r + 7, b + 5], fill=_rgb8(box) + (255,))+ df.text((x, y), s, font=f, fill=_rgb8(INK) + (255,), anchor=anchor)+ else:+ df.text((x, y), s, font=f, fill=_rgb8(col) + (255,), anchor=anchor)+ elif k == 'line':+ _, pts, col, width, dash = it+ self._dash(df, pts, _rgb8(col) + (255,), width, dash)+ elif k == 'flag':+ _, x0, y0, x1, y1, n, label, note, col, side = it+ c = _rgb8(col) + (255,)+ L = int(min(30, (x1 - x0) / 4, (y1 - y0) / 4))+ for (cx, cy, sx, sy) in ((x0, y0, 1, 1), (x1, y0, -1, 1), (x0, y1, 1, -1), (x1, y1, -1, -1)):+ df.line([(cx, cy + sy * L), (cx, cy), (cx + sx * L, cy)], fill=c, width=3)+ self._dash(df, [(x0 + L + 6, y0), (x1 - L - 6, y0)], c, 1, 6)+ self._dash(df, [(x0 + L + 6, y1), (x1 - L - 6, y1)], c, 1, 6)+ f, fb = _mono(19), _mono(20, True)+ ty = y0 - 34 if side == 'top' else y1 + 8+ df.rectangle([x0, ty, x0 + 30, ty + 28], fill=c)+ df.text((x0 + 15, ty + 14), str(n), font=fb, fill=_rgb8(INK) + (255,), anchor='mm')+ lab = self._fmt(label, R)+ nt = self._fmt(note, R) if note else ''+ wtxt = fb.getlength(lab) + (22 + f.getlength(nt) if nt else 0)+ db.rectangle([x0 + 31, ty, x0 + 52 + wtxt, ty + 28], fill=(3, 9, 15, 215)) # backing plate+ df.text((x0 + 40, ty + 14), lab, font=fb, fill=c, anchor='lm')+ if nt:+ df.text((x0 + 40 + fb.getlength(lab) + 22, ty + 14), nt, font=f,+ fill=_rgb8('#ffd9a0') + (255,), anchor='lm')+ elif k == 'inset':+ _, (sx0, sy0, sx1, sy1), (dx0, dy0, dx1, dy1), mode, title, frame = it+ lo, hi = Lo[sy0:sy1, sx0:sx1], Hi[sy0:sy1, sx0:sx1]+ if mode == 'material' and self._calib is not None: # belt is part of the air calibration+ cy0, clo, chi = self._calib+ lo, hi = lo.copy(), hi.copy()+ a, b = max(sy0, cy0), min(sy1, cy0 + clo.shape[0])+ if b > a:+ lo[a - sy0:b - sy0] -= clo[a - cy0:b - cy0, sx0:sx1]+ hi[a - sy0:b - sy0] -= chi[a - cy0:b - cy0, sx0:sx1]+ rgb = self.show_material(lo, hi) if mode == 'material' else self.show_film(lo, hi, vignette=False)+ im = Image.fromarray((np.clip(rgb, 0, 1) * 255 + 0.5).astype(np.uint8))+ pastes.append((im.resize((dx1 - dx0, dy1 - dy0), Image.LANCZOS), (dx0, dy0)))+ df.rectangle([dx0 - 1, dy0 - 1, dx1, dy1], outline=_rgb8(frame) + (255,), width=2)+ if title:+ df.text((dx0, dy0 - 8), title, font=_mono(16, True), fill=_rgb8(frame) + (255,), anchor='ld')+ elif k == 'legend':+ _, x, y, w, size = it+ f = _mono(size)+ items_ = [('ORGANIC', lut(RAMPS['organic'])[440]), ('INORGANIC', lut(RAMPS['inorganic'])[440]),+ ('METAL', lut(RAMPS['metal'])[440]), ('OPAQUE', hexc('#0c0d10'))]+ tw = sum(30 + f.getlength(nm) for nm, _ in items_)+ gap = max(10.0, (w - tw) / (len(items_) - 1))+ xx = x+ for nm, cc in items_:+ df.rectangle([xx, y, xx + 20, y + 20], fill=tuple(int(v * 255) for v in cc) + (255,),+ outline=_rgb8('#7fa9c2') + (255,))+ df.text((xx + 28, y + 10), nm, font=f, fill=_rgb8('#a9cfe3') + (255,), anchor='lm')+ xx += 28 + f.getlength(nm) + gap+ elif k == 'scale':+ _, x0, y0, x1, y1, marks, size, title = it+ n = int(x1 - x0)+ v = np.linspace(0, 1, n, dtype=np.float32)+ strip = self._lut[np.clip((v * (len(self._lut) - 1)).astype(int), 0, len(self._lut) - 1)]+ im = Image.fromarray((np.repeat(strip[None], int(y1 - y0), 0) * 255).astype(np.uint8))+ pastes.append((im, (int(x0), int(y0))))+ df.rectangle([x0 - 1, y0 - 1, x1, y1], outline=_rgb8('#7fa9c2') + (255,))+ f = _mono(size)+ dp = self.disp+ for i, (lab, mat, th) in enumerate(marks):+ lo, hi = MATERIALS[mat]+ A = (dp['mix'] * lo + (1 - dp['mix']) * hi) * th / self.px+ xv = x0 + float(np.clip(self._v(np.float32(A)), 0, 1)) * (x1 - x0)+ up = i % 2 == 0+ df.line([(xv, y0 - (7 if up else 0)), (xv, y1 + (0 if up else 7))], fill=_rgb8(CYAN) + (255,), width=2)+ df.text((xv, y0 - 9 if up else y1 + 9), lab, font=f, fill=_rgb8('#a9cfe3') + (255,),+ anchor='md' if up else 'ma')+ if title:+ df.text((x0, y0 - 34), title, font=_mono(size, True), fill=_rgb8(CYAN) + (255,), anchor='ld')+ out = Image.alpha_composite(base.convert('RGBA'), bg)+ for im, xy in pastes:+ out.paste(im, xy)+ fa = np.asarray(fg)+ a = fa[..., 3:].astype(np.float32) / 255+ pm = fa[..., :3] * a # premultiplied: monitor glow round the OSD+ g = np.asarray(Image.fromarray((pm + 0.5).astype(np.uint8)).filter(ImageFilter.GaussianBlur(3.5)), np.float32)+ o = np.asarray(out.convert('RGB'), np.float32)+ o *= 1 - a+ o += pm + 0.45 * g * (1 - a)+ return Image.fromarray(np.clip(o + 0.5, 0, 255).astype(np.uint8))++ # ------------------------------------------------------------ output+ def composite(self, Alo=None, Ahi=None, n_osd=None, tagparts=None):+ Lo, Hi = self.detect(Alo, Ahi)+ rgb = self.show_film(Lo, Hi)+ base = Image.fromarray((np.clip(rgb, 0, 1) * 255 + 0.5).astype(np.uint8))+ items = self.osd if n_osd is None else self.osd[:n_osd]+ tp = tagparts if tagparts is not None else {k: len(v) for k, v in self.tags.items()}+ need = set()+ for it in items:+ for s in it[1:]:+ if isinstance(s, str) and '{' in s:+ need |= {f.split('.')[0] for _, f, _, _ in string.Formatter().parse(s) if f}+ R = {t: self._measure(t, Lo, Hi, tp.get(t, 0)) for t in need if tp.get(t, 0)}+ self.readings = R+ return self._draw_osd(base, items, Lo, Hi, R)++ def stage(self, name):+ self.stages.append((name, self.Alo.astype(np.float16), self.Ahi.astype(np.float16), len(self.osd),+ {k: len(v) for k, v in self.tags.items()}))++ def save(self, path, stages_dir=None):+ img = self.composite()+ if path.lower().endswith(('.jpg', '.jpeg')):+ img.save(path, quality=88, subsampling=0)+ else:+ img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, lo, hi, n, tp) in enumerate(self.stages):+ self.composite(lo.astype(np.float32), hi.astype(np.float32), n, tp).save(f"{stages_dir}/{i:02d}_{name}.png")+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")+ return img