Skip to content

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.

Add sticker-collage × receipt and lab-notebook × stickers styles (15 styles); gallery 8×2

clovericdde030107ef3
diff --git a/README.md b/README.md
index 50373c6..93cdd03 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# Claude Drawing · Claude 绘图
-**Claude paints with code — no image model.** Thirteen styles, from ink wash and impasto oil to clay, cyanotype and cross-stitch.
-**不用生图模型,Claude 用代码一笔一笔作画。** 十三种画风,从水墨、油画到黏土、蓝晒和十字绣。
+**Claude paints with code — no image model.** Fifteen styles, from ink wash and impasto oil to clay, cyanotype, cross-stitch, sticker collage and a lab notebook.
+**不用生图模型,Claude 用代码一笔一笔作画。** 十五种画风,从水墨、油画到黏土、蓝晒、十字绣、贴纸小票和实验笔记本。
[English](#english) · [中文](#中文)
@@ -15,6 +15,10 @@
| **Stop-motion clay · 黏土定格** | **Cyanotype · 蓝晒** | **Cross-stitch · 十字绣** | **Retro panel · 复古仪器面板** |
| ![clay](examples/drawing_clay_lighthouse.gif) | ![cyanotype](examples/drawing_cyanotype_botanicals.gif) | ![stitch](examples/drawing_stitch_sampler.gif) | ![panel](examples/drawing_panel_radio.gif) |
+| Sticker collage × receipt · 贴纸拼贴 · 小票 | Lab notebook × stickers · 实验笔记本 · 贴纸 |
+|---|---|
+| ![sticker](examples/drawing_sticker_market.gif) | ![notebook](examples/drawing_notebook_brewing.gif) |
+
### Gallery · 画廊
| | |
@@ -33,10 +37,10 @@
| <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%"> |
-| **水彩底纹** · *Watercolour Washes*<br><sub>Watercolour · 水彩 — a background for explainer videos · 讲解视频的背景</sub> | |
-| <img src="examples/watercolor_washes.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%"> |
-Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 30 s per 1920×1080 image.
+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. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 30 s per 1920×1080 image.
---
@@ -44,7 +48,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 thirteen styles:
+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with fifteen styles:
| Style | Module | What makes it read as the real medium |
|---|---|---|
@@ -61,6 +65,8 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra
| **Cyanotype (sun print)** | `lib/cyanotype.py` · `Cyanotype` | emulsion brushed on in strokes with dry-brush ends; objects *block UV* (transmissions multiply): translucent leaves with whiter veins, fluff lifted off the paper with a soft penumbra, light scattering under edges; a Prussian-blue density curve; white handwriting printed in, pencil notes on the margin |
| **Cross-stitch embroidery** | `lib/stitch.py` · `Stitch` | Aida cloth with a hole at every block corner; one X per cell, lit as round twisted thread with a shadow, in hand-made variants; half stitches; back-stitch snapped hole to hole; padded glossy satin stitch; French knots; ASCII charts and a 5×7 sampler alphabet; a sewn-on woven label |
| **Vintage instrument panel** | `lib/panel.py` · `Panel` | teak veneer, brushed aluminium, moulded plastic, grille cloth with lurex floats, perforated metal; bevels, wells and drop shadows from one key light; machined knobs, piano keys, toggle switch, jewel lamp, magic-eye tube, meter; silkscreened scales and a backlit dial behind glass |
+| **Sticker collage × receipt** | `lib/sticker.py` · `Sticker` | cream card board with grain, mottling and fibres; flat-vector art die-cut into *vinyl stickers* (rounded white border, cut-edge thickness, laminate gloss rim and sheen, contact + drop shadow, peeled corners showing the pale backing); a thermal receipt with serrated tear edges, grey streaky thermal print, dotted leaders, a printed strike-through, a fold crease and curl; translucent washi tape with torn ends; price tags with grommets on baker's twine; a round rubber stamp in translucent, unevenly pressed ink; red ballpoint ticks |
+| **Lab notebook × stickers** | `lib/notebook.py` · `Notebook` | a wire-o graph-paper notebook on a graphite desk (hard back cover, stepped page stack, divider tabs, dog-ear, wire loops lit as metal tubes); graphite that only catches the paper tooth, with pressure, taper and hand wobble; ruled lines, hatching, pencil charts and check boxes; multiply highlighter swipes with pooled starts, felt streaks and dry tails; red felt-pen loops that overshoot instead of closing; curling sticky notes, die-cut vinyl stickers, embossed label-maker tape, a coffee ring; a hexagonal pencil with a scalloped sharpened edge |
Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:
@@ -140,7 +146,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,加上一个小巧的绘图库,内置十五种画风:
| 画风 | 模块 | 为什么看起来像真的 |
|---|---|---|
@@ -157,6 +163,8 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages
| **蓝晒** | `lib/cyanotype.py` · `Cyanotype` | 药水一笔笔刷上去,笔尾是干刷的断续刷丝;放上去的东西**挡紫外线**(透过率相乘):薄叶透一点光、叶脉更白,蒲公英绒毛离纸有距离、边缘柔和,边缘下还有散射;按普鲁士蓝的显影曲线上色;白色手写字一起晒出来,纸边再加铅笔字 |
| **十字绣** | `lib/stitch.py` · `Stitch` | Aida 布,每个布块四角有孔;每格一个 X,线按扭绞的圆线打光并投下小影子,还有几种手工误差;半针;回针沿孔走、一针从孔到孔;鼓起有光泽的缎面绣;法式结;字符图样和 5×7 刺绣字母;缝上去的织标 |
| **复古仪器面板** | `lib/panel.py` · `Panel` | 柚木贴皮、拉丝铝、注塑塑料、带金丝的喇叭布、冲孔网;同一盏主光照出倒角、凹槽和投影;车削旋钮、琴键、拨杆开关、宝石指示灯、绿色魔眼管、指针表;丝印刻度、玻璃后面的背光刻度窗 |
+| **贴纸拼贴 · 小票** | `lib/sticker.py` · `Sticker` | 奶油卡纸底板,带纸纹、斑驳和纤维;平面矢量图模切成**乙烯贴纸**:圆角白边、切口厚度、覆膜光泽和斜向反光、贴地阴影加投影,翻起一角露出浅色背面;热敏小票:锯齿撕边、灰色断针热敏字、点线引导、删除线、折痕和卷翘;半透明和纸胶带;麻绳吊牌;油墨不匀的圆形橡皮章;红色圆珠笔勾选 |
+| **实验笔记本 · 贴纸** | `lib/notebook.py` · `Notebook` | 石墨蓝灰桌面上的线圈方格本:硬封底、错开的页边、分隔标签、折角,线圈按金属管打光;石墨只挂在纸纹凸起上,有压力、收笔和手抖;靠尺直线、排线、铅笔折线图、勾选框;荧光笔正片叠底,起笔积墨、纤维条纹、尾部干涩;红笔圈故意不闭合;翘角便利贴、模切贴纸、标签机压印胶带、咖啡杯印;六棱铅笔 |
对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:
1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;
@@ -199,6 +207,8 @@ python3 examples/clay_lighthouse.py out.png # 黏土定
python3 examples/cyanotype_botanicals.py out.png # 蓝晒:蓝晒植物
python3 examples/stitch_sampler.py out.png # 十字绣:家
python3 examples/panel_radio.py out.png # 复古仪器面板:Aurora 64 收音机
+python3 examples/sticker_market.py out.png # 贴纸拼贴 · 小票:周末市集
+python3 examples/notebook_brewing.py out.png # 实验笔记本 · 贴纸:咖啡萃取实验
```
### 作画要点(Claude 交图前逐条自查)
diff --git a/SKILL.md b/SKILL.md
index 4e9a6f8..b304e64 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,6 +1,6 @@
---
name: claude绘图
-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置十三种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置十五种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。
---
# Claude 绘图
@@ -27,6 +27,8 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
| 蓝晒 | `lib/cyanotype.py` · `Cyanotype` | `examples/cyanotype_botanicals.py` 蓝晒植物(蕨叶、银杏、蒲公英、飘散的种子、白色手写标注) | 约 6 秒 |
| 十字绣 | `lib/stitch.py` · `Stitch` | `examples/stitch_sampler.py` 家(H♥ME 字母、缎面绣爱心、小屋、苹果树、松树、花边、缝上的布标) | 约 20 秒 |
| 复古仪器面板 | `lib/panel.py` · `Panel` | `examples/panel_radio.py` Aurora 64 收音机(柚木机壳、喇叭布、背光刻度窗、琴键、魔眼管、拨杆、旋钮) | 约 7 秒 |
+| 贴纸拼贴 · 小票 | `lib/sticker.py` · `Sticker` | `examples/sticker_market.py` 周末市集(热敏小票、模切贴纸:酸种面包/传家番茄/郁金香花束/咖啡豆、贴纸大字、波浪边促销贴、麻绳吊牌、和纸胶带、「已付」橡皮章) | 约 3 秒 |
+| 实验笔记本 · 贴纸 | `lib/notebook.py` · `Notebook` | `examples/notebook_brewing.py` 咖啡萃取实验(线圈方格笔记本、铅笔表格与折线图、排线标出最佳区间、荧光笔、没闭合的红笔圈、便利贴结论、模切贴纸、标签机日期、桌上的六棱铅笔) | 约 3 秒 |
各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。
@@ -43,7 +45,9 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型
- 童趣立体、讲故事、手作感、定格动画 → 黏土定格;
- 植物、标本、自然科学、复古工艺感的蓝色海报 → 蓝晒;
- 家、温馨、手作礼物、贺卡、名字和字母 → 十字绣;
-- 设备、仪表、音响收音机、复古科技与产品感 → 复古仪器面板。
+- 设备、仪表、音响收音机、复古科技与产品感 → 复古仪器面板;
+- 清单、账单、价格、购物、市集、活动海报、轻松但成熟的讲解片封面 → 贴纸拼贴 · 小票;
+- 实验记录、数据对比、复盘笔记、讲解片里的「算账 / 结论」页 → 实验笔记本 · 贴纸。
每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。
@@ -167,6 +171,28 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
- 控件:`knob(x, y, r, angle)` 车削旋钮、`button()` 琴键(`pressed=True` 按下)、`toggle()` 拨杆开关、`lamp()` 宝石指示灯、`magic_eye()` 绿色魔眼调谐管、`meter()` 指针表、`screw()` 螺丝、`grille()` 冲孔网、`badge()` 镀铬草书铭牌
- 印刷:`text(s, x, y, size, spacing=)` 丝印字、`scale_arc()` 圆弧刻度、`scale_linear()` 直尺刻度、`glass(mask)` 玻璃反光
+**贴纸拼贴 · 小票 `Sticker`**:
+- 思路:每样东西先在自己的透明小画纸 `Art` 上画成平面矢量图,再决定材质:`stick()` 做成模切贴纸,`lay()` 当纸平放
+- `board(颜色, kind='cream'|'kraft')`:奶油色或浅牛皮纸底板,带纸纹、斑驳、纤维和杂点
+- `art(w, h)` 返回 `Art`:遮罩 `circle/ring/ellipse/rrect/poly/blob/line/text`(中西文混排,`stroke` 加粗);上色 `fill(mask, 颜色, alpha, clip)`、`gradient()`、`radial()`;`crescent(mask, dx, dy)` 明暗月牙;`speckle()` 撒面粉、籽粒;`cut()` 打孔;`texture('kraft')` 牛皮纸纹
+- `stick(art, cx, cy, rot, border=14, peel='tr'|'tl'|'br'|'bl', peel_size, lift, gloss)`:模切贴纸。白边按圆角外扩,有切口厚度、覆膜高光和斜向反光,贴地阴影加柔和投影;`peel` 翻起一角,露出浅色背面和它自己的影子
+- `lay(art, cx, cy, rot, curl, lift)`:纸张平放(小票、吊牌),两端微翘、翘起处影子更长;返回局部→画面坐标映射 `T(x, y)`,用来在纸上落笔、盖章
+- `receipt(w, h)` 返回 `Receipt`:锯齿撕边、热敏灰字(断针竖纹、走纸浓淡、小掉点);`centre()` 居中打印、`row(y, 名称, 金额, was='旧价')` 带点线引导和删除线、`rule('dash'|'stars'|'double')`、`barcode()`、`crease(y)` 折痕
+- `tape(cx, cy, 长, rot, 颜色, pattern='stripe'|'dot'|'grid'|'plain')` 半透明和纸胶带,两头手撕锯齿;`tag_art(w, h, 颜色, 金属扣颜色)` 吊牌(`.hole` 是孔位),`twine(点列)` 双色面包师麻绳
+- `stamp(cx, cy, r, 环形字, 中心字, 小字, 颜色, rot)` 圆形橡皮章(油墨半透明、压力不匀、字边积墨、漏印小坑);`pen(点列, 颜色, width)` 红色圆珠笔(打勾、圈总价、划掉)
+- 现成贴纸:`lettering_art([(文字, 颜色), ...], size)` 大字、`label_art()` 胶囊标签、`badge_art(r, 颜色, '-20%', top, bottom)` 波浪边促销贴
+
+**实验笔记本 · 贴纸 `Notebook`**:
+- 场景:`desk()` 石墨蓝灰桌面;`notebook(x0, y0, x1, y1, tabs, stack, ear, margin, header, grid, major)` 一整本笔记本(硬封底、分隔标签、错开的页边、青色方格纸、红色双边线、打孔、折角);`binding()` 线圈(按金属管打光,带投影)
+- 铅笔:`pencil(pts, width, pressure, jitter)` 手绘一笔(样条平滑、手抖、起笔轻收笔提);`pencils([...])`;`rule(x0, y0, x1, y1)` 靠尺直线;`hatch(mask, angle, spacing, pressure)` 排线;`checkbox(x, y, size, checked)`;`arrowhead(tip, 方向)`;`axes(x0, y0, x1, y1, xlim, ylim, xticks, yticks, xlabels, ylabels)` 返回 `to_px(x, y)`
+- 石墨只挂在纸纹凸起上:pressure 小是颗粒状浅灰,大才填满;线宽约 2–3.5 px
+- 荧光笔 `highlight(x0, x1, y, h, tilt, alpha)`:正片叠底,斜切起笔并积墨、边缘毛、纵向纤维条纹、尾部断续,两遍重叠处更深
+- 红笔:`pen(pts, width)`、`pen_loop(cx, cy, rx, ry, rot, turns=1.12)` 不闭合的圈、`pen_arrow(pts, head)`、`pen_underline(x0, x1, y, double)`
+- 文字 `text(s, x, y, size, colour, font, anchor, rot, spacing, weight, medium)`:font 用 sans / sans_bold / typewriter / cjk_sans(中英混排自动换字体),medium 可选 ink、print、typed(打字机,每字浓淡和基线略不同)、pencil、opaque;`text_width()` 量宽度
+- 纸片:`sticky(cx, cy, w, h, rot, colour)` 便利贴(上端平贴、下端翘起投影),返回 Frame,用 `f.pt(lx, ly)` 和 `rot=f.rot` 往上写字;`sticker(cx, cy, w, h, rot, colour, shape='rrect'|'circle', lines=[...])` 模切贴纸;`label_tape(s, x, y, size, rot)` 标签机胶带;`stain(cx, cy, r)` 咖啡杯印
+- 道具:`pencil_prop(x, y, angle, length, width, label, end='eraser'|'plain')` 六棱铅笔
+- 角度:`rot` 逆时针为正(同 PIL);`angle`(铅笔、箭头方向)是屏幕角度,顺时针为正。常用色:`INK SOFT LEAD RED HI MINT MINTD`
+
**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。
## 三、毛病清单(都真实出现过)
@@ -290,6 +316,36 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask
| 浅色字印在浅色喇叭布上看不见 | 丝印颜色要和底材拉开明度 |
| 一大片喇叭布太平、太假 | 布是半透明的:把后面喇叭的圆形暗影淡淡透出来 |
+**贴纸拼贴 · 小票**
+
+| 问题 | 改法 |
+|---|---|
+| 面包只有一道长割口,像红薯或叶脉 | 三道斜向交叠的割口:浅色裂口加深色翘边,再撒面粉 |
+| 花束的花用同心圆画,像靶心或棒棒糖 | 侧面郁金香:两片带尖的外瓣,前面一片浅色瓣 |
+| 印章小字压在内圈线上 | 中心字上移,分隔线放在 +0.16r,小字写短,全部收在内圈以内 |
+| 小票字太黑,像打字机不像热敏纸 | 灰色油墨 #4f525a、浓度约 0.8、边缘微糊,加断针竖纹和走纸浓淡 |
+| 小票右半边整条发灰 | 横向卷曲压到很小,只让长边两端翘起 |
+| 纸边的贴地阴影像描了一圈黑线 | 纸张接触阴影降到约 0.26 |
+| 印章盖在条码上看不清 | 盖在金额和星号一带的稀疏处,只压一点字,更像真的 |
+| 印章墨色太匀,像电脑填色 | 加压力倾斜、大块浓淡和漏印小坑 |
+| 标签上的字溢出圆标 | 文字改短、字号调小 |
+| 右下角空出一大块 | 加摊位号圆贴纸,第二个吊牌用长绳垂下来 |
+
+**实验笔记本 · 贴纸**
+
+| 问题 | 改法 |
+|---|---|
+| 铅笔线像干净的矢量墨线:细、匀、太黑 | 手绘线宽约 3 px、抖动约 1.6;石墨只挂在纸纹凸起上,重压也保留一点颗粒 |
+| 轻压的排线、表格横线断成一串点点 | 覆盖率保留约四成连续的浅灰,颗粒只调制剩下的部分(`_graphite` 已处理) |
+| 折线图数据点画成小圆圈,像字母 o、c | 用压实的小铅笔点(很小的螺旋,pressure 1) |
+| 曲线一笔画成,太完美 | 分两笔画,接头处稍错开、稍重叠 |
+| 标注字压在曲线上,单位和刻度撞在一起 | 标注放到曲线下方空白处,用铅笔小箭头指过去;单位放到轴端上方 |
+| 贴纸孤零零浮在图下面,看不出指什么 | 从最佳点画铅笔虚线到横轴,贴纸贴在同一个 x 上 |
+| 标签机胶带两端剪成 V 形缺口,像彩带横幅 | 两端直剪、略斜、小圆角 |
+| 咖啡渍像肥皂泡或透镜 | 外缘一圈细而深的水痕线,内部几乎均匀的淡色;圈有断口、一侧更深 |
+| 红笔箭头被后贴的便利贴盖住 | 箭头停在便利贴边缘外,或先贴便利贴再画箭头 |
+| 标题上的荧光笔起笔压到了前一个字 | 起点按字宽算,落在目标字的左边缘 |
+
## 四、做成动画
- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。
@@ -313,6 +369,8 @@ lib/clay.py 黏土定格
lib/cyanotype.py 蓝晒
lib/stitch.py 十字绣
lib/panel.py 复古仪器面板
+lib/sticker.py 贴纸拼贴 · 小票
+lib/notebook.py 实验笔记本 · 贴纸
examples/*.py 范例脚本;*.jpg 成品;drawing_*.gif 逐步画出的动图
中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT
西文字体(新四种用):core.latin_font(style) 按 sans / sans_bold / rounded / script / hand / typewriter 等找系统字体,可用 INKPAINT_FONT_<STYLE> 指定;字体文件不要放进仓库
diff --git a/examples/drawing_notebook_brewing.gif b/examples/drawing_notebook_brewing.gif
new file mode 100644
index 0000000..2b7fe30
Binary files /dev/null and b/examples/drawing_notebook_brewing.gif differ
diff --git a/examples/drawing_sticker_market.gif b/examples/drawing_sticker_market.gif
new file mode 100644
index 0000000..d39da7f
Binary files /dev/null and b/examples/drawing_sticker_market.gif differ
diff --git a/examples/notebook_brewing.jpg b/examples/notebook_brewing.jpg
new file mode 100644
index 0000000..82a83bc
Binary files /dev/null and b/examples/notebook_brewing.jpg differ
diff --git a/examples/notebook_brewing.py b/examples/notebook_brewing.py
new file mode 100644
index 0000000..8d881e8
--- /dev/null
+++ b/examples/notebook_brewing.py
@@ -0,0 +1,124 @@
+"""Example (lab notebook x stickers): 咖啡萃取实验 / Coffee Brewing Experiment — a page of a wire-o lab notebook
+lying on a graphite desk: a filled-in header with a label-maker date, a pencil-ruled table of six pour-over
+trials (grind, water temperature, brew time, taste score), a pencil chart of brew time against score with a
+hatched sweet spot, the best trial highlighted and looped in red pen, a mint sticky note with the conclusion,
+die-cut stickers for the key numbers, an old coffee ring in the margin, and a pencil lying beside the notebook.
+No image model.
+python3 notebook_brewing.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 notebook import Notebook, INK, SOFT, LEAD, RED, MINT, MINTD
+from core import polygon_mask
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'notebook_brewing.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+nb = Notebook(1920, 1080, seed=27)
+PX0, PY0, PX1, PY1 = 112, 100, 1796, 1018
+
+# ---- desk, notebook, binding
+nb.desk()
+nb.stage('desk')
+nb.notebook(PX0, PY0, PX1, PY1)
+nb.stain(182, 912, 60, strength=0.3) # an old mug ring in the margin
+nb.binding()
+nb.stage('notebook')
+
+# ---- header form, filled in; title
+for (x, w, lab) in [(300, 330, '实验编号 EXP. NO.'), (690, 350, '日期 DATE'), (1100, 470, '方法 METHOD'), (1630, 110, '页 PAGE')]:
+ nb.text(lab, x, 176, 15, SOFT, 'sans_bold', spacing=2.5, medium='print')
+ nb.rule(x, 228, x + w, 228, 2.0, 0.55)
+nb.text('CB-07', 302, 214, 32, INK, 'typewriter', medium='typed')
+nb.text('手冲 Pour-over · 15 g : 240 g', 1102, 214, 27, INK, 'sans_bold')
+nb.text('07', 1632, 214, 32, INK, 'typewriter', medium='typed')
+nb.text('COFFEE BREWING EXPERIMENT', 304, 296, 19, MINTD, 'sans_bold', spacing=5)
+nb.text('咖啡萃取实验', 298, 404, 104, INK, 'cjk_sans', weight=1.6)
+nb.text('同一包豆子,六组对照 · one bag of beans, six trials', 304, 452, 25, SOFT, 'sans')
+nb.stage('header')
+
+# ---- trial table: pencil-ruled, typed values
+TRIALS = [('01', '1000', '90', '2:15', '6.1'), ('02', '850', '92', '2:40', '7.2'), ('03', '700', '93', '3:05', '8.1'),
+ ('04', '600', '93', '3:20', '8.8'), ('05', '500', '94', '3:45', '7.6'), ('06', '400', '96', '4:20', '6.0')]
+COLS = [326, 470, 632, 792, 955]
+for x, cn, en in zip(COLS, ['#', '研磨', '水温', '时间', '评分'], ['TRIAL', 'GRIND µm', 'TEMP °C', 'TIME min', 'SCORE /10']):
+ nb.text(cn, x, 508, 19, SOFT, 'sans_bold', 'ms', medium='print')
+ nb.text(en, x, 532, 12, SOFT, 'sans_bold', 'ms', spacing=2, medium='print')
+nb.rule(300, 548, 1040, 548, 2.2, 0.8)
+nb.rule(300, 553, 1040, 553, 1.6, 0.55)
+ROW0, RH = 590, 60
+for i, row in enumerate(TRIALS):
+ y = ROW0 + i * RH
+ for x, val in zip(COLS, row):
+ nb.text(val, x, y + 12, 33, INK, 'typewriter', 'ms', medium='typed')
+ if i < len(TRIALS) - 1:
+ nb.rule(304, y + RH / 2, 1036, y + RH / 2, 1.8, 0.45)
+nb.rule(300, ROW0 + 5.5 * RH, 1040, ROW0 + 5.5 * RH, 2.2, 0.8)
+nb.rule(378, 516, 378, ROW0 + 5.5 * RH, 1.8, 0.45)
+for i, (x, lab, done) in enumerate([(300, '滤纸预湿 rinse', True), (556, '闷蒸 30 s bloom', True), (830, '下次试 92 °C', False)]):
+ nb.checkbox(x, 952, 22, checked=done)
+ nb.text(lab, x + 34, 971, 21, INK, 'sans')
+nb.stage('table')
+
+# ---- chart: brew time vs score, pencil on graph paper
+X0, X1, Y0, Y1 = 1200, 1690, 290, 620
+to_px = nb.axes(X0, Y0, X1, Y1, (2.0, 4.5), (5, 10), [2.0, 2.5, 3.0, 3.5, 4.0, 4.5], [5, 6, 7, 8, 9, 10],
+ ['2:00', '2:30', '3:00', '3:30', '4:00', '4:30'], ['5', '6', '7', '8', '9', '10'], size=18)
+nb.text('评分 SCORE', X0 + 22, Y0 - 8, 16, SOFT, 'sans_bold', medium='print')
+nb.text('min', X1 + 24, Y1 - 16, 16, SOFT, 'sans_bold', 'ms', medium='print')
+nb.text('FIG. 1 时间 vs 评分', X0, 700, 16, SOFT, 'sans_bold', spacing=1, medium='print')
+tt = np.array([2.25, 2.667, 3.083, 3.333, 3.75, 4.333]); sc = np.array([6.1, 7.2, 8.1, 8.8, 7.6, 6.0])
+fit = np.polyfit(tt, sc, 2)
+ts = np.linspace(2.12, 4.45, 30)
+curve = [to_px(t, np.polyval(fit, t)) for t in ts]
+band = [to_px(3.0, 5.0)] + [to_px(t, np.polyval(fit, t) - 0.12) for t in np.linspace(3.0, 3.5, 12)] + [to_px(3.5, 5.0)]
+nb.hatch(polygon_mask(nb.H, nb.W, band, 2), angle=50, spacing=7.5, pressure=0.5, width=1.8)
+nb.pencil(curve[:17], 3.2, 0.8, 1.6) # drawn in two strokes that overlap a little
+nb.pencil([(x + 0.8, y + 1.2) for x, y in curve[15:]], 3.2, 0.8, 1.6)
+for t, s in zip(tt, sc): # data points: small pressed-in dots
+ x, y = to_px(t, s)
+ nb.pencil([(x + r * np.cos(a), y + r * np.sin(a)) for r, a in zip(np.linspace(3.8, 0.6, 18), np.linspace(0, 4 * np.pi, 18))], 2.8, 1.0, 0.15)
+bx, by = to_px(3.333, 8.8)
+nb.pencils([[(X0 + 8 + k * 14, by), (X0 + 16 + k * 14, by)] for k in range(int((bx - X0 - 24) / 14))], 1.8, 0.55, 0.2, smooth=False)
+nb.pencils([[(bx, by + 14 + k * 14), (bx, by + 22 + k * 14)] for k in range(int((Y1 - by - 20) / 14))], 2.0, 0.7, 0.2, smooth=False)
+nb.text('SWEET SPOT', 1532, 598, 16, LEAD, 'typewriter', medium='typed')
+nb.pencil([(1526, 590), (1510, 584), (1490, 582)], 2.0, 0.7, 0.4)
+nb.arrowhead((1488, 582), 182, 10, 2.0)
+nb.stage('chart')
+
+# ---- highlighter: the best trial, and the key phrase of the title
+YB = ROW0 + 3 * RH
+nb.highlight(306, 1034, YB + 1, 46, tilt=-3)
+nb.highlight(298 + 2 * 104 - 2, 298 + 4 * 104 + 14, 372, 50, tilt=-2, alpha=0.7)
+nb.stage('highlighter')
+
+# ---- red pen: loop the best row and the best point, arrows to the conclusion
+nb.pen_loop(668, YB + 1, 392, 38, rot=-1.0)
+nb.pen_loop(bx, by, 24, 22, rot=8, a0=150, width=3.6)
+nb.pen_arrow([(1066, YB + 14), (1104, YB + 52), (1150, YB + 74)], 3.8, 18)
+nb.pen_arrow([(bx + 22, by - 18), (bx + 52, by - 40), (bx + 78, by - 48)], 3.6, 15)
+nb.stage('red_pen')
+
+# ---- paper bits: sticky note with the conclusion, die-cut stickers, label-maker date
+f = nb.sticky(1376, 858, 392, 200, rot=1.6)
+nb.text('结论 CONCLUSION', *f.pt(26, 40), 16, MINTD, 'sans_bold', rot=f.rot, spacing=3)
+nb.text('中细研磨 600 µm', *f.pt(26, 94), 34, INK, 'sans_bold', rot=f.rot)
+nb.text('93 °C · 3:20 · 8.8 / 10', *f.pt(26, 138), 27, INK, 'sans_bold', rot=f.rot)
+nb.text('酸甜平衡,回甘最长', *f.pt(26, 176), 23, SOFT, 'sans', rot=f.rot)
+u0 = 26 + nb.text_width('中细研磨 ', 34, 'sans_bold'); u1 = 26 + nb.text_width('中细研磨 600 µm', 34, 'sans_bold')
+nb.pen([f.pt(u0 - 4, 107), f.pt((u0 + u1) / 2, 109.5), f.pt(u1 + 8, 105)], 3.6)
+nb.sticker(1618, 322, 146, 84, rot=-6, colour=RED, radius=16,
+ lines=[('BEST', 73, 29, 16, 'sans_bold', '#ffffff'), ('8.8', 73, 72, 44, 'sans_bold', '#ffffff')])
+nb.sticker(1016, 356, 118, 118, rot=8, colour=MINT, shape='circle',
+ lines=[('粉水比 RATIO', 59, 40, 13, 'sans_bold', MINTD), ('1:16', 59, 82, 40, 'sans_bold', INK)])
+nb.sticker(bx, 690, 96, 40, rot=-4, colour='#2c3846', radius=20,
+ lines=[('3:20', 48, 30, 25, 'sans_bold', '#ffffff')])
+nb.label_tape('2026.09.27', 692, 204, 22, rot=-1.2)
+nb.stage('stickers')
+
+# ---- a pencil lying beside the notebook
+nb.pencil_prop(1872, 262, angle=88.6, length=1000, width=32, label='HB')
+
+nb.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/examples/sticker_market.jpg b/examples/sticker_market.jpg
new file mode 100644
index 0000000..5c64b98
Binary files /dev/null and b/examples/sticker_market.jpg differ
diff --git a/examples/sticker_market.py b/examples/sticker_market.py
new file mode 100644
index 0000000..563eb14
--- /dev/null
+++ b/examples/sticker_market.py
@@ -0,0 +1,269 @@
+"""Example (sticker collage x receipt): 周末市集 / Weekend Market — a market haul as a flat-lay on a cream
+board: a folded thermal receipt taped down (grey thermal print, dotted leaders, a struck-through old price,
+a barcode, red-pen ticks and a circled total), die-cut vinyl stickers of a sourdough loaf, heirloom
+tomatoes, a tulip bouquet and a bag of coffee beans (three with a peeled corner), bold sticker lettering, a
+scalloped sale badge, a stall-number sticker, two price tags hanging on baker's twine, washi tape, and a
+round PAID / 已付 rubber stamp. No image model.
+python3 sticker_market.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 sticker import Sticker, measure, _resample
+from core import blob_pts, spline, blur, smoothstep
+
+out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'sticker_market.png'
+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None
+
+s = Sticker(1920, 1080, seed=26)
+TOMATO, MUSTARD, MINT, MINTD = '#E04A2F', '#E8AC2C', '#8FD2B5', '#2F8F6C'
+NAVY, NAVY2, KRAFT, CREAM, PEN = '#1B2745', '#26355C', '#D9C7A3', '#FBF3E4', '#C9302A'
+
+# ---- board
+s.board('#EFE5D1', 'cream')
+s.stage('board')
+
+# ---- the receipt
+r = s.receipt(480, 960, margin=36)
+r.centre(78, 'WEEKEND MARKET', 30, bold=True, spacing=2)
+r.centre(116, '周末市集 · STALL 12', 21, font='typewriter')
+r.centre(146, 'SAT 26 SEP 2026 09:42', 19)
+r.rule(172, 'dash')
+ITEMS = [(222, 'SOURDOUGH LOAF', '38.00', None), (262, 'HEIRLOOM TOMATO', '', None),
+ (292, ' 1.2 kg @ 22.00', '26.40', None), (334, 'FLOWERS, BOUQUET', '45.00', None),
+ (376, 'COFFEE BEANS 250g', '54.40', '68.00'), (406, ' WEEKEND SALE -20%', '', None)]
+for y, name, amt, was in ITEMS:
+ r.row(y, name, amt, 21 if not name.startswith(' ') else 19, was=was)
+r.rule(436, 'dash')
+r.row(486, 'TOTAL', '¥163.80', 30, bold=True, leader=False)
+r.row(528, 'CASH', '170.00', 20)
+r.row(558, 'CHANGE', '6.20', 20)
+r.rule(592, 'stars')
+r.centre(646, '4 ITEMS · THANK YOU', 19)
+r.centre(676, 'SEE YOU NEXT SATURDAY', 19)
+r.barcode(712, 74, seed=5)
+r.centre(812, '0926 0942 0012', 17, spacing=2)
+r.crease(505, 498)
+RX, RY, RR = 345, 548, -2.2
+T = s.lay(r, RX, RY, RR, curl=0.8)
+s.stage('receipt')
+
+# ---- washi tape holding it down
+s.tape(*T(240, 8), 230, rot=RR + 5, colour=MUSTARD, width=46, pattern='stripe', alpha=0.82)
+s.tape(*T(462, 948), 150, rot=RR - 42, colour=MINT, width=40, pattern='dot', alpha=0.8)
+s.stage('tape')
+
+
+# ---- produce stickers (flat vector on transparent sheets, then die-cut)
+def lens_score(a, P, up_w, lo_w, clip_to):
+ """a slash scored into the crust that opened in the oven: pale lens under a dark raised ear"""
+ P = np.asarray(P, np.float32)
+ 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)
+ w = np.sin(np.pi * np.linspace(0, 1, len(P))) ** 0.7
+ up, lo = P + nrm * (up_w * w)[:, None], P - nrm * (lo_w * w)[:, None]
+ lens = a.poly(np.vstack([up, lo[::-1]])) * clip_to
+ a.gradient(lens, '#F6DDA8', '#DDA964', P[0] - nrm[0] * 30, P[0] + nrm[0] * 10, clip=True)
+ a.fill(a.line(up, 4.0) * clip_to, '#5E2E10', 0.9, clip=True)
+ a.fill(a.line(up + nrm * 4.5, 2.2) * clip_to, '#F4C98A', 0.8, clip=True)
+
+
+def bread():
+ a = s.art(450, 250)
+ cx, cy = 225, 126
+ pts = blob_pts(cx, cy, 205, 86, rough=0.02, n=160, seed=5, rot=np.deg2rad(-5))
+ pts[:, 1] = np.minimum(pts[:, 1], cy + 68) # the loaf sits flat on its base
+ body = a.poly(pts)
+ a.gradient(body, '#D8913F', '#99521F', (cx, cy - 90), (cx, cy + 75))
+ a.fill(a.crescent(body, -8, -22), '#723912', 0.8, clip=True)
+ a.fill(a.crescent(body, 10, 15), '#EFB66C', 0.6, clip=True)
+ a.fill(a.blob(cx - 10, cy - 34, 170, 44, 0.25, seed=9) * body, '#FFF6E6', 0.22, clip=True) # flour dust
+ for x0 in (70, 170, 270): # three overlapping slashes along the loaf
+ lens_score(a, spline([(x0, cy + 22), (x0 + 55, cy - 6), (x0 + 118, cy - 26)], 20), 4, 17, body)
+ a.speckle(body * (a.YY < cy + 20), '#FFF9EE', 260, (0.7, 1.7), (0.35, 0.8), seed=3)
+ a.speckle(body, '#5E2E10', 30, (1.0, 2.0), (0.3, 0.55), seed=4)
+ return a
+
+
+def tomato(a, cx, cy, R, base, dark, light, ph):
+ t = np.linspace(0, 2 * np.pi, 260, endpoint=False)
+ rr = R * (1 + 0.035 * np.cos(6 * t + ph) + 0.015 * np.cos(10 * t + 2 * ph))
+ dt = ((t + np.pi / 2 + np.pi) % (2 * np.pi)) - np.pi
+ rr = rr - R * 0.12 * np.exp(-(dt / 0.42) ** 2)
+ body = a.poly(np.stack([cx + np.cos(t) * rr * 1.07, cy + np.sin(t) * rr * 0.87], 1))
+ a.radial(body, light, base, cx - R * 0.4, cy - R * 0.35, R * 1.35)
+ a.fill(a.crescent(body, -R * 0.14, -R * 0.15), dark, 0.8, clip=True)
+ for k in (-0.8, -0.38, 0.38, 0.8):
+ rib = a.line([(cx + k * R * 0.08, cy - R * 0.6), (cx + k * R * 0.6, cy - R * 0.36), (cx + k * R * 1.0, cy + R * 0.2)], R * 0.035, smooth=True)
+ a.fill(rib * body, dark, 0.35, clip=True)
+ a.fill(a.ellipse(cx - R * 0.5, cy - R * 0.36, R * 0.24, R * 0.11, -28), '#FFFFFF', 0.25, clip=True)
+ a.fill(a.ellipse(cx - R * 0.52, cy - R * 0.4, R * 0.13, R * 0.05, -28), '#FFFFFF', 0.85, clip=True)
+ sx, sy = cx, cy - R * 0.64 # star-shaped calyx seen from the side
+ for i, ang in enumerate(np.linspace(0, 2 * np.pi, 6, endpoint=False) + ph):
+ L = R * (0.46 + 0.08 * np.cos(i * 2.3))
+ tip = (sx + np.cos(ang) * L, sy + np.sin(ang) * L * 0.42 + R * 0.05)
+ side = np.array([-np.sin(ang), np.cos(ang) * 0.42]) * R * 0.075
+ leaf = [(sx + side[0], sy + side[1]), ((sx + tip[0]) / 2 + side[0] * 0.6, (sy + tip[1]) / 2 + side[1] * 0.6 - R * 0.03),
+ tip, ((sx + tip[0]) / 2 - side[0] * 0.6, (sy + tip[1]) / 2 - side[1] * 0.6 - R * 0.03), (sx - side[0], sy - side[1])]
+ a.fill(a.poly(leaf), '#3D7A46' if np.sin(ang) > -0.2 else '#4F9152')
+ a.fill(a.line([(sx, sy), (sx + R * 0.03, sy - R * 0.2), (sx + R * 0.11, sy - R * 0.27)], R * 0.07, smooth=True), '#4A7A3C')
+
+
+def tomatoes():
+ a = s.art(380, 270)
+ tomato(a, 262, 158, 80, MUSTARD, '#C27F17', '#F6CD6A', 1.1)
+ tomato(a, 148, 146, 104, TOMATO, '#B3321D', '#F0775A', 0.3)
+ return a
+
+
+def closed(pts, per=12):
+ """smooth closed outline through pts"""
+ P = [pts[-1]] + list(pts) + [pts[0], pts[1]]
+ return spline(P, per)[per:-per]
+
+
+def tulip(a, x, y, r, col, dark, tilt=0.0):
+ """side view: two outer petals with pointed tips, a front petal in the lighter colour"""
+ t = np.deg2rad(tilt); c, sn = np.cos(t), np.sin(t)
+ tr = lambda P: [(x + (px * c - py * sn) * r, y + (px * sn + py * c) * r) for px, py in P]
+ a.fill(a.line(tr([(0, 0.6), (0.05, 1.6), (0.1, 3.4)]), 3.4), '#4F7F68')
+ back = [(-0.6, -0.98), (-0.72, -0.3), (-0.56, 0.3), (-0.24, 0.62), (0.24, 0.62), (0.56, 0.3), (0.72, -0.3), (0.6, -0.98), (0.3, -0.6), (0, -0.7), (-0.3, -0.6)]
+ a.fill(a.poly(closed(tr(back))), dark)
+ front = [(0, -1.06), (-0.3, -0.5), (-0.44, 0.08), (-0.3, 0.5), (0, 0.63), (0.3, 0.5), (0.44, 0.08), (0.3, -0.5)]
+ fm = a.poly(closed(tr(front)))
+ a.fill(fm, col)
+ a.fill(a.crescent(fm, r * 0.1 * c, -r * 0.1 * sn) * fm, '#FFFFFF', 0.22, clip=True)
+
+
+def daisy(a, x, y, r, petal, centre, n=13, rot=0.0):
+ for ang in np.linspace(0, 360, n, endpoint=False) + rot:
+ t = np.deg2rad(ang)
+ a.fill(a.ellipse(x + np.cos(t) * r * 0.55, y + np.sin(t) * r * 0.55, r * 0.46, r * 0.15, ang), petal)
+ a.fill(a.circle(x, y, r * 0.27), centre)
+ a.fill(a.crescent(a.circle(x, y, r * 0.27), -2, -3), '#9A6410', 0.6, clip=True)
+
+
+def bouquet():
+ a = s.art(390, 530)
+ a.fill(a.poly([(46, 230), (118, 138), (268, 118), (344, 200), (212, 505), (178, 505)]), '#CDB48A')
+ rng = np.random.default_rng(11)
+ for (p1, p2, p3) in [((190, 300), (120, 180), (58, 96)), ((200, 300), (262, 170), (318, 78)),
+ ((210, 310), (300, 230), (362, 176)), ((180, 310), (90, 250), (30, 196)), ((196, 300), (190, 160), (196, 40))]:
+ P = spline([p1, p2, p3], 30)
+ a.fill(a.line(P, 3.2), '#4F7F68')
+ x, y, *_ = _resample(P, 21)
+ for i, (lx, ly) in enumerate(zip(x[3:], y[3:])):
+ side = 1 if i % 2 else -1
+ j = min(i + 4, len(x) - 1)
+ ang = np.degrees(np.arctan2(y[j] - y[j - 1], x[j] - x[j - 1])) + 90 * side
+ o = np.deg2rad(ang)
+ a.fill(a.ellipse(lx + np.cos(o) * 10, ly + np.sin(o) * 10, 11.5, 9, ang), MINT if rng.random() < 0.6 else '#6DB597')
+ for (x, y) in [(172, 92), (320, 122), (86, 150)]: # billy buttons on thin stems
+ a.fill(a.line([(x, y), (x + (190 - x) * 0.4, y + 120)], 2.4), '#4F7F68')
+ a.fill(a.circle(x, y, 15), MUSTARD)
+ a.speckle(a.circle(x, y, 14), '#B97C12', 26, (1.0, 1.6), (0.5, 0.8), seed=int(x))
+ a.fill(a.circle(x - 5, y - 5, 5), '#FFFFFF', 0.25, clip=True)
+ tulip(a, 196, 118, 50, '#F08A6C', '#C9573A', 2)
+ tulip(a, 118, 170, 48, TOMATO, '#A82D1A', -16)
+ tulip(a, 276, 166, 46, TOMATO, '#A82D1A', 14)
+ daisy(a, 318, 240, 38, CREAM, MUSTARD, 13, 8)
+ daisy(a, 72, 258, 34, CREAM, MUSTARD, 12, 0)
+ tulip(a, 200, 222, 44, '#F08A6C', '#C9573A', -4)
+ cone = a.poly([(20, 262), (358, 232), (214, 508), (176, 510)])
+ a.gradient(cone, '#E6D5AF', '#C6AB7C', (40, 250), (330, 330))
+ a.fill(a.poly([(20, 262), (150, 251), (196, 508), (176, 510)]), '#EFE3C6', 0.9, clip=True)
+ a.fill(a.line([(20, 262), (358, 232)], 3), '#B8996A', 0.9)
+ a.fill(a.poly([(96, 392), (290, 382), (282, 404), (104, 414)]), NAVY) # ribbon band and bow
+ for sgn in (-1, 1):
+ a.fill(a.ellipse(194 + sgn * 34, 386, 34, 15, sgn * 16), NAVY)
+ a.fill(a.ellipse(194 + sgn * 32, 386, 18, 6, sgn * 16), '#0F1830', 0.9)
+ a.fill(a.poly([(194, 398), (194 + sgn * 18, 402), (194 + sgn * 44, 470), (194 + sgn * 30, 474)]), NAVY)
+ a.fill(a.circle(194, 393, 12), NAVY2)
+ return a
+
+
+def coffee():
+ a = s.art(300, 390)
+ body = smoothstep(0.3, 0.7, blur(a.poly([(42, 76), (258, 76), (270, 368), (30, 368)]), 3))
+ a.gradient(body, NAVY2, NAVY, (42, 76), (258, 368))
+ a.fill(a.poly([(42, 76), (70, 76), (62, 368), (30, 368)]), '#3A4D82', 0.55, clip=True) # lit side gusset
+ a.fill(a.poly([(230, 76), (258, 76), (270, 368), (238, 368)]), '#0E1528', 0.55, clip=True)
+ a.fill(a.crescent(body, 0, -14), '#0B1122', 0.5, clip=True)
+ zz = [(38 + i * 7.5, 34 if i % 2 else 40) for i in range(30)]
+ top = a.poly(zz + [(261, 40), (262, 80), (38, 80)])
+ a.fill(top, '#33477C')
+ for x in np.arange(44, 256, 6.0):
+ a.fill(a.line([(x, 44), (x, 62)], 1.4), '#5A6FA8', 0.5, clip=True)
+ a.fill(a.rrect(24, 78, 276, 92, 5), '#D8B869') # tin tie
+ a.fill(a.rrect(26, 79, 274, 83, 2), '#F3DD9E', 0.8)
+ a.fill(a.rrect(24, 88, 276, 92, 3), '#9C7B32', 0.8)
+ a.fill(a.circle(218, 124, 10), '#101830'); a.fill(a.ring(218, 124, 10, 3), '#4A5C92') # one-way valve
+ lab = a.circle(150, 226, 80)
+ a.fill(lab, MUSTARD)
+ a.fill(a.ring(150, 226, 70, 2.2), NAVY)
+ a.fill(a.ellipse(150, 196, 25, 17, -28), NAVY)
+ a.fill(a.line(spline([(131, 206), (146, 196), (154, 197), (169, 186)], 10), 3.2), MUSTARD)
+ a.fill(a.text('COFFEE', 150, 244, 22, 'sans_bold', 'mm', spacing=4), NAVY)
+ a.fill(a.text('250 g · 中烘', 150, 272, 15, 'sans_bold', 'mm', spacing=1), NAVY)
+ a.fill(a.line([(88, 110), (82, 340)], 12) * body, '#FFFFFF', 0.07, clip=True)
+ return a
+
+
+s.stick(bread(), 860, 478, rot=-5, border=15, peel='bl', peel_size=34)
+s.stick(tomatoes(), 1248, 452, rot=6, border=15)
+s.stage('produce')
+s.stick(coffee(), 900, 808, rot=-4, border=15)
+s.stick(bouquet(), 1405, 772, rot=5, border=15, peel='tr', peel_size=38)
+s.stage('bouquet_coffee')
+
+# ---- price tags on baker's twine, taped to the top edge
+tags = []
+for (cx, cy, rot, w, h, colour, grom, en, zh, price, ink) in [
+ (1592, 318, 5, 170, 290, KRAFT, '#C9A55C', 'SOURDOUGH', '酸种面包', '¥38', TOMATO),
+ (1796, 668, -4, 150, 262, MUSTARD, '#C8C8C3', 'FLOWERS', '鲜花一束', '¥45', NAVY)]:
+ t = s.tag_art(w, h, colour, grom)
+ t.fill(t.text(en, w / 2, h * 0.43, 17, 'sans_bold', 'mm', spacing=2.5), NAVY, 0.92)
+ t.fill(t.text(zh, w / 2, h * 0.54, 23, 'sans_bold', 'mm'), NAVY, 0.92)
+ dots = np.maximum.reduce([t.circle(x, h * 0.63, 1.5) for x in np.arange(22, w - 20, 9.0)])
+ t.fill(dots, NAVY, 0.6)
+ t.fill(t.text(price, w / 2, h * 0.8, 76 if w > 160 else 68, 'condensed', 'mm'), ink, 0.95)
+ Tt = s.lay(t, cx, cy, rot, curl=0.15, lift=2.2)
+ tags.append((Tt(*t.hole), cx))
+for (hx, hy), cx in tags:
+ top = (hx + (6 if cx < 1700 else -8), 26)
+ s.twine([top, ((top[0] + hx) / 2 + (9 if cx < 1700 else -12), (top[1] + hy) / 2), (hx, hy - 2)], width=4.2)
+s.tape(1690, 30, 420, rot=-1.5, colour=MINT, width=48, pattern='stripe', alpha=0.8)
+s.stage('tags')
+
+# ---- lettering
+s.stick(s.lettering_art([('周末', NAVY), ('市集', TOMATO)], 150, 'cjk_sans', weight=4), 1000, 148, rot=-2, border=20, gloss=0.8)
+s.stick(s.label_art('WEEKEND MARKET · SAT 26 SEP', 25, NAVY, CREAM, dot=MINT, spacing=1.5), 940, 272, rot=1.5, border=10)
+s.stage('title')
+
+# ---- sale badge and a small label
+s.stick(s.badge_art(118, TOMATO, '-20%', top='SALE', bottom='咖啡豆', big_size=62), 1148, 930, rot=-9, border=14, peel='br', peel_size=30)
+s.stick(s.label_art('FRESH · 新鲜', 24, MINT, '#17503C', spacing=1), 1342, 318, rot=8, border=10)
+stall = s.art(190, 190)
+stall.radial(stall.circle(95, 95, 92), NAVY2, NAVY, 60, 55, 140)
+stall.fill(stall.ring(95, 95, 80, 2), MUSTARD, 0.8)
+stall.fill(stall.text('STALL', 95, 52, 17, 'sans_bold', 'mm', spacing=4), CREAM)
+stall.fill(stall.text('12', 95, 100, 70, 'condensed', 'mm'), MUSTARD)
+stall.fill(stall.text('摊位', 95, 146, 19, 'sans_bold', 'mm', spacing=4), CREAM)
+s.stick(stall, 1742, 952, rot=10, border=12)
+s.stage('sale')
+
+# ---- rubber stamp and red pen on the receipt
+s.stamp(*T(352, 626), 96, 'WEEKEND MARKET · 周末市集 · 26.09.2026 · ', '已付', 'PAID', TOMATO, rot=-14, strength=0.85)
+for y, name, amt, was in ITEMS:
+ if amt and not name.startswith(' ') or name.startswith('HEIRLOOM'):
+ x0, yy = 16, y - 6
+ s.pen([T(x0 - 6, yy - 6), T(x0, yy + 1), T(x0 + 12, yy - 16)], PEN, 2.6, smooth=False)
+wt = measure('¥163.80', 30, 'typewriter') + 6
+cxl, cyl = 480 - 36 - wt / 2, 476
+rng = np.random.default_rng(3)
+loop = [(cxl + np.cos(a) * (wt / 2 + 20) * (1 + rng.normal(0, .02)), cyl + np.sin(a) * 30 * (1 + rng.normal(0, .03)) - 3 * np.sin(a / 2))
+ for a in np.linspace(-2.6, -2.6 + 2 * np.pi + 0.55, 16)]
+s.pen([T(x, y) for x, y in loop], PEN, 2.8)
+
+s.save(out, stages_dir=stages)
+print('saved', out)
diff --git a/lib/notebook.py b/lib/notebook.py
new file mode 100644
index 0000000..58656bf
--- /dev/null
+++ b/lib/notebook.py
@@ -0,0 +1,795 @@
+"""notebook — a lab notebook lying on a desk: graph paper, graphite pencil, highlighter, red pen, sticky notes,
+label-maker tape and die-cut stickers (numpy + Pillow only).
+
+Model: every mark is made the way the real tool makes it, on real paper.
+ desk graphite blue-grey board, soft light from the upper left, fine grain, vignette;
+ notebook hard back cover, divider tabs that peek out between the pages, a stack of pages whose edges step
+ down, the top page (cream graph paper: fine cyan grid, stronger every 5 squares, a header rule, a red
+ double margin line, punched holes), a dog-eared corner showing the page beneath, and a wire-o binding
+ (twin wire loops lit as metal tubes, casting shadows onto the page);
+ paper a per-pixel "tooth" field: graphite catches only the tops of the tooth, so light pencil is grainy
+ and broken while heavy pencil fills in; liquid inks (highlighter, felt pen) ignore most of it;
+ pencil strokes are resampled, get a slow hand wobble plus a little shake, and a pressure profile (light
+ touch-down, uneven middle, lift-off taper); pressure sets both width and how deep the graphite
+ gets into the tooth. Ruled lines use less wobble; hatching is many short strokes clipped to a mask
+ with over/under-shoot at the ends;
+ highlighter a chisel-nib swipe blended with multiply: ragged long edges, a slanted start, ink pooling where the
+ nib lands and stops, lengthwise streaks from the felt, a streaky tail, darker wherever passes overlap;
+ red pen felt-tip ink (multiply, slightly soaked into the paper): loops that run past a full turn and drift so
+ they never close, underlines, arrows with two-stroke heads; overlaps get darker;
+ paper bits sticky notes (flat adhesive strip, the rest curls up: soft corner shadows), die-cut vinyl stickers
+ (white cut margin, gloss, thin shadow), label-maker tape (dark embossed tape, stress-whitened raised
+ letters, scissor-cut ends), a coffee-ring stain;
+ props a hexagonal pencil lying on the desk: lit facets, a scalloped paint edge where it was sharpened, a
+ wood cone with grain and a shiny graphite point, cast shadow.
+Lettering uses sans / sans_bold / typewriter (CJK falls back to the CJK sans), never handwriting fonts.
+Rotations are in degrees, counter-clockwise (like PIL).
+
+ from notebook import Notebook
+ nb = Notebook(1920, 1080, seed=1)
+ nb.desk()
+ nb.notebook(112, 100, 1796, 1018)
+ nb.text('Trial log', 310, 330, 80, font='sans_bold')
+ nb.rule(310, 520, 1040, 520) # a ruled pencil line
+ nb.highlight(316, 1010, 736, 46) # a highlighter swipe
+ nb.pen_loop(663, 737, 380, 40) # a red-pen loop that doesn't quite close
+ f = nb.sticky(1370, 850, 380, 220, rot=1.8) # a mint sticky note; f.pt(lx, ly) -> canvas point
+ nb.text('600 um', *f.pt(28, 90), 32, rot=f.rot)
+ nb.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, fbm1d, spline, noise2d, smoothstep, shift, load_font
+
+INK, SOFT, LEAD = '#25303d', '#5b697a', '#3a4758'
+RED, HI, MINT, MINTD = '#d1382d', '#f7e92b', '#abe4d0', '#1b8466'
+
+
+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(P, step):
+ P = np.asarray(P, np.float32)
+ seg = np.hypot(*np.diff(P, axis=0).T)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ if s[-1] < 1e-3: return P[:1]
+ n = max(2, int(s[-1] / step) + 1)
+ ss = np.linspace(0, s[-1], n)
+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)
+
+
+def _is_cjk(ch):
+ return ord(ch) >= 0x2e80
+
+
+def _periodic(th, k=8, seed=0, falloff=1.2):
+ """smooth random function of an angle (no seam at +-pi), roughly in [-1, 1]"""
+ r = np.random.default_rng(seed)
+ out = np.zeros_like(th)
+ tot = 0
+ for i in range(1, k + 1):
+ a = 1 / i ** falloff
+ out += a * np.sin(i * th + r.uniform(0, 2 * np.pi))
+ tot += a
+ return out / tot * 1.6
+
+
+class Frame:
+ """a rotated rectangle on the page (sticky note, sticker, tape). pt(lx, ly) maps a point measured from the
+ rectangle's top-left corner (in its own rotated axes) to canvas coordinates; rot is the text rotation to use."""
+
+ def __init__(self, cx, cy, w, h, rot):
+ self.cx, self.cy, self.w, self.h, self.rot = cx, cy, w, h, rot
+
+ def pt(self, lx, ly):
+ u, v = lx - self.w / 2, ly - self.h / 2
+ t = np.deg2rad(self.rot)
+ return (self.cx + u * np.cos(t) + v * np.sin(t), self.cy - u * np.sin(t) + v * np.cos(t))
+
+
+class Notebook:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.45, -0.6, 0.66)):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.L = np.asarray(light, np.float32) / np.linalg.norm(light)
+ self.img = np.ones((H, W, 3), np.float32) * 0.4
+ g = blur(self.rng.random((H, W)).astype(np.float32), 0.6) # paper tooth: ~1-2 px grain ...
+ m = noise2d(H, W, 4.0, 2, self._seed()) # ... in slightly clumpy patches
+ fib = np.asarray(Image.fromarray(self.rng.random((H // 2, W // 14)).astype(np.float32)).resize((W, H), Image.BILINEAR))
+ t = 0.62 * (g - g.mean()) / (g.std() + 1e-6) + 0.3 * (m - m.mean()) / (m.std() + 1e-6) + 0.2 * (fib - 0.5) / 0.29
+ self.tooth = np.clip(0.5 + t / 3.4, 0, 1).astype(np.float32)
+ self.page = None
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ # ------------------------------------------------------------ low-level compositing
+ def _box(self, x0, y0, x1, y1):
+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))
+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))
+ if x1 <= x0 or y1 <= y0: return None
+ return (slice(y0, y1), slice(x0, x1))
+
+ def _mul(self, sl, a, colour):
+ """transparent media (graphite, ink, highlighter): multiply, so overlaps get darker"""
+ self.img[sl] *= 1 - np.clip(a, 0, 1)[..., None] * (1 - _c(colour))
+
+ def _over(self, sl, a, colour):
+ """opaque media (stickers, white letters): normal blend; colour may be an (h, w, 3) array"""
+ a = np.clip(a, 0, 1)[..., None]
+ col = colour if isinstance(colour, np.ndarray) and colour.ndim == 3 else _c(colour)
+ self.img[sl] = self.img[sl] * (1 - a) + col * a
+
+ def _shadow(self, sl, mask, dist, soft, strength, tint='#0e1620'):
+ """soft shadow of `mask` (already cropped to sl) cast away from the light"""
+ d = -self.L[:2] / (np.linalg.norm(self.L[:2]) + 1e-6)
+ sh = blur(shift(mask, d[0] * dist, d[1] * dist), soft) if soft > 0 else shift(mask, d[0] * dist, d[1] * dist)
+ self._mul(sl, sh * strength, tint)
+
+ def _rbox(self, cx, cy, hw, hh, rot, pad):
+ """bounding slices for a rotated rectangle and the local (u, v) coords of every pixel in it"""
+ R = np.hypot(hw, hh) + pad
+ sl = self._box(cx - R, cy - R, cx + R, cy + R)
+ if sl is None: return None, None, None
+ t = np.deg2rad(rot)
+ dx, dy = self.XX[sl] - cx, self.YY[sl] - cy
+ return sl, dx * np.cos(t) - dy * np.sin(t), dx * np.sin(t) + dy * np.cos(t)
+
+ @staticmethod
+ def _sdf_rrect(u, v, hw, hh, r):
+ qx, qy = np.abs(u) - (hw - r), np.abs(v) - (hh - r)
+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r
+
+ # ------------------------------------------------------------ stroke rasteriser (pencil, pen)
+ def _raster(self, strokes, ss=3):
+ """strokes: [(P (n,2), width (n,), value (n,) 0..1)] -> (mask, slices); drawn at ss x then box-filtered"""
+ allp = np.concatenate([s[0] for s in strokes])
+ pad = max(float(s[1].max()) 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
+ x0, y0 = sl[1].start, sl[0].start
+ bw, bh = sl[1].stop - x0, sl[0].stop - y0
+ im = Image.new('L', (bw * ss, bh * ss), 0)
+ d = ImageDraw.Draw(im)
+ for P, w, v in strokes:
+ Q = (P - np.array([x0, y0], np.float32)) * 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 * v[0]))
+ continue
+ for i in range(0, n - 1, 3):
+ j = min(n - 1, i + 3)
+ ww = float(w[i:j + 1].mean()) * ss
+ vv = int(round(255 * float(np.clip(v[i:j + 1].mean(), 0, 1))))
+ r = ww / 2
+ d.ellipse([Q[i, 0] - r, Q[i, 1] - r, Q[i, 0] + r, Q[i, 1] + r], fill=vv)
+ d.line([(float(q[0]), float(q[1])) for q in Q[i:j + 1]], fill=vv, width=max(1, int(round(ww))))
+ r = w[-1] * ss / 2
+ d.ellipse([Q[-1, 0] - r, Q[-1, 1] - r, Q[-1, 0] + r, Q[-1, 1] + r], fill=int(255 * np.clip(v[-1], 0, 1)))
+ m = np.asarray(im.resize((bw, bh), Image.BOX), np.float32) / 255
+ return m, sl
+
+ def _prep(self, pts, width, pressure, jitter, smooth=True, taper=(14, 24), step=1.5):
+ """resample a hand stroke, add wobble + shake and a pressure profile -> (P, widths, pressures)"""
+ P = np.asarray(pts, np.float32)
+ if smooth and len(P) > 2: P = spline(P, 10)
+ P = _resample(P, step)
+ n = len(P)
+ if n < 2: return P, np.array([width], np.float32), np.array([pressure], np.float32)
+ tg = np.gradient(P, axis=0)
+ tg /= np.linalg.norm(tg, axis=1, keepdims=True) + 1e-6
+ nrm = np.stack([-tg[:, 1], tg[:, 0]], 1)
+ s = self._seed()
+ wob = fbm1d(n, max(4, 110 / step), 3, s) * jitter + fbm1d(n, max(2, 9 / step), 2, s + 1) * jitter * 0.22
+ P = P + nrm * wob[:, None]
+ L = n * step
+ t = np.linspace(0, 1, n)
+ env = 0.4 + 0.6 * smoothstep(0, min(0.3, taper[0] / L), t) * smoothstep(0, min(0.35, taper[1] / L), 1 - t)
+ flow = 1 + 0.16 * fbm1d(n, max(4, 70 / step), 2, s + 2)
+ press = np.clip(pressure * env * flow, 0.02, 1).astype(np.float32)
+ w = (width * (0.72 + 0.28 * press / max(pressure, 1e-3))).astype(np.float32)
+ return P, w, press
+
+ def _graphite(self, m, sl, colour=LEAD, strength=0.9):
+ """graphite deposit: light pressure only catches the tops of the paper tooth, heavy pressure fills in;
+ even a heavy line keeps some grain (the valleys stay paler)"""
+ t = self.tooth[sl]
+ thr = 1.0 - 1.3 * m
+ dep = smoothstep(thr - 0.2, thr + 0.2, t)
+ a = smoothstep(0.0, 0.1, m) * (0.22 + 0.78 * np.clip(m, 0, 1)) * (0.38 + 0.62 * dep) * (0.86 + 0.14 * t) * strength
+ self._mul(sl, a, colour)
+
+ # ------------------------------------------------------------ pencil
+ def pencils(self, strokes, width=2.4, pressure=0.7, jitter=0.8, colour=LEAD, smooth=True, strength=0.88):
+ """many graphite strokes in one pass (a list of point lists); overlapping strokes of one call don't stack"""
+ prepared = [self._prep(p, width, pressure, jitter, smooth) for p in strokes if len(p) >= 1]
+ prepared = [p for p in prepared if len(p[0])]
+ if not prepared: return
+ m, sl = self._raster(prepared)
+ if sl is not None: self._graphite(m, sl, colour, strength)
+
+ def pencil(self, pts, width=2.4, pressure=0.7, jitter=0.8, colour=LEAD, smooth=True, strength=0.88):
+ """one freehand graphite stroke through `pts` (Catmull-Rom smoothed unless smooth=False)"""
+ self.pencils([pts], width, pressure, jitter, colour, smooth, strength)
+
+ def rule(self, x0, y0, x1, y1, width=2.0, pressure=0.6, colour=LEAD, overshoot=4):
+ """a line ruled with a straight-edge: straight, tiny wobble, uneven pressure, ends not exactly on target"""
+ r = self.rng
+ d = np.array([x1 - x0, y1 - y0], np.float32); d /= np.linalg.norm(d) + 1e-6
+ a = np.array([x0, y0], np.float32) - d * r.uniform(-overshoot * 0.5, overshoot)
+ b = np.array([x1, y1], np.float32) + d * r.uniform(-overshoot * 0.5, overshoot)
+ self.pencil([a, b], width, pressure, 0.3, colour, smooth=False)
+
+ def hatch(self, mask, angle=45, spacing=7, pressure=0.5, width=1.5, jitter=0.4, colour=LEAD, overshoot=3):
+ """pencil hatching inside a mask: parallel short strokes, each slightly bowed, ends over/under-shooting"""
+ ys, xs = np.nonzero(mask > 0.5)
+ if len(xs) == 0: return
+ a = np.deg2rad(angle)
+ d = np.array([np.cos(a), -np.sin(a)], np.float32)
+ nv = np.array([np.sin(a), np.cos(a)], np.float32)
+ cx, cy = xs.mean(), ys.mean()
+ corners = np.array([[xs.min(), ys.min()], [xs.max(), ys.min()], [xs.min(), ys.max()], [xs.max(), ys.max()]], np.float32) - [cx, cy]
+ on, od = corners @ nv, corners @ d
+ r = self.rng
+ strokes = []
+ o = on.min()
+ while o < on.max():
+ ts = np.arange(od.min() - 2, od.max() + 2, 1.0)
+ px = cx + nv[0] * o + d[0] * ts; py = cy + nv[1] * o + d[1] * ts
+ ix, iy = np.round(px).astype(int), np.round(py).astype(int)
+ ok = (ix >= 0) & (iy >= 0) & (ix < self.W) & (iy < self.H)
+ inside = np.zeros(len(ts), bool)
+ inside[ok] = mask[iy[ok], ix[ok]] > 0.5
+ edges = np.diff(np.concatenate([[0], inside.astype(int), [0]]))
+ for s0, s1 in zip(np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0]):
+ if s1 - s0 < 4: continue
+ t0 = ts[s0] - r.uniform(-overshoot * 0.6, overshoot)
+ t1 = ts[s1 - 1] + r.uniform(-overshoot * 0.8, overshoot * 1.3)
+ p0 = np.array([cx, cy]) + nv * o + d * t0
+ p1 = np.array([cx, cy]) + nv * o + d * t1
+ mid = (p0 + p1) / 2 + nv * r.uniform(-1, 1) * (t1 - t0) * 0.012
+ strokes.append([p0, mid, p1])
+ o += spacing * r.uniform(0.85, 1.15)
+ self.pencils(strokes, width, pressure, jitter, colour, smooth=True)
+
+ def checkbox(self, x, y, size=24, checked=True, pressure=0.7, check_colour=LEAD):
+ """a pencil box (four ruled sides that overshoot at the corners) and an optional tick"""
+ s = size
+ for p0, p1 in [((x, y), (x + s, y)), ((x + s, y), (x + s, y + s)), ((x + s, y + s), (x, y + s)), ((x, y + s), (x, y))]:
+ self.rule(p0[0], p0[1], p1[0], p1[1], 1.9, pressure * 0.85, overshoot=2.5)
+ if checked:
+ self.pencil([(x + s * 0.18, y + s * 0.5), (x + s * 0.42, y + s * 0.8), (x + s * 1.05, y - s * 0.3)], 2.8, 0.95, 0.5,
+ check_colour, strength=0.95)
+
+ def arrowhead(self, tip, direction_deg, size=14, width=2.2, pressure=0.75, colour=LEAD):
+ """two short pencil flicks forming an arrow head at `tip` pointing along direction_deg (screen, clockwise from +x)"""
+ a = np.deg2rad(direction_deg)
+ for side in (1, -1):
+ b = a + side * np.deg2rad(152)
+ self.pencil([(tip[0] + np.cos(b) * size, tip[1] + np.sin(b) * size), tip], width, pressure, 0.3, colour, smooth=False)
+
+ def axes(self, x0, y0, x1, y1, xlim, ylim, xticks, yticks, xlabels=None, ylabels=None, size=18, colour=LEAD,
+ label_colour=SOFT, font='typewriter', tick=9):
+ """pencil-ruled chart axes (origin at bottom-left x0, y1) with ticks and typed labels -> to_px(xv, yv)"""
+ def to_px(xv, yv):
+ return (x0 + (xv - xlim[0]) / (xlim[1] - xlim[0]) * (x1 - x0), y1 - (yv - ylim[0]) / (ylim[1] - ylim[0]) * (y1 - y0))
+ self.rule(x0 - 6, y1, x1 + 22, y1, 2.3, 0.8, colour, overshoot=2)
+ self.rule(x0, y1 + 6, x0, y0 - 22, 2.3, 0.8, colour, overshoot=2)
+ self.arrowhead((x1 + 24, y1), 0, 13, colour=colour)
+ self.arrowhead((x0, y0 - 24), -90, 13, colour=colour)
+ tk = []
+ for i, xv in enumerate(xticks):
+ px, _ = to_px(xv, ylim[0])
+ tk.append([(px, y1 - tick * 0.4), (px, y1 + tick)])
+ if xlabels: self.text(xlabels[i], px, y1 + tick + size * 1.35, size, label_colour, font, 'ms', medium='typed')
+ for i, yv in enumerate(yticks):
+ _, py = to_px(xlim[0], yv)
+ tk.append([(x0 - tick, py), (x0 + tick * 0.4, py)])
+ if ylabels: self.text(ylabels[i], x0 - tick - 10, py, size, label_colour, font, 'rm', medium='typed')
+ self.pencils(tk, 2.0, 0.7, 0.2, colour, smooth=False)
+ return to_px
+
+ # ------------------------------------------------------------ highlighter
+ def highlight(self, x0, x1, y, h=40, colour=HI, tilt=-3, alpha=0.8, slant=0.35):
+ """a fluorescent chisel-nib swipe from x0 to x1 (centre line y; the end sits `tilt` px lower/higher),
+ multiplied onto the page: ragged edges, pooled ink where the nib lands and stops, felt streaks,
+ a streaky tail; overlapping swipes get darker."""
+ L = float(np.hypot(x1 - x0, tilt)); ang = np.arctan2(tilt, x1 - x0)
+ pad = h + abs(tilt) + 24
+ sl = self._box(min(x0, x1) - 24, y - pad, max(x0, x1) + 24, y + pad)
+ if sl is None: return
+ X, Y = self.XX[sl] - x0, self.YY[sl] - y
+ u = X * np.cos(ang) + Y * np.sin(ang)
+ v = -X * np.sin(ang) + Y * np.cos(ang)
+ s = self._seed()
+ nU = int(L + 60); nV = int(h * 2 + 20)
+ ui = np.clip(u + 30, 0, nU - 1); vi = np.clip(v + h + 10, 0, nV - 1)
+ top = np.interp(ui, np.arange(nU), fbm1d(nU, 45, 3, s) * 2.4 + fbm1d(nU, 6, 2, s + 1) * 0.7)
+ bot = np.interp(ui, np.arange(nU), fbm1d(nU, 45, 3, s + 2) * 2.4 + fbm1d(nU, 6, 2, s + 3) * 0.7)
+ vt, vb = -h / 2 + top, h / 2 + bot
+ us = (v / h) * h * slant # chisel start: a slanted edge
+ ragged = np.interp(vi, np.arange(nV), fbm1d(nV, 5, 2, s + 4))
+ ue = L + (v / h) * h * slant * 0.6 + ragged * 7
+ sm = lambda q: np.clip(q / 1.4 + 0.5, 0, 1)
+ cov = sm(v - vt) * sm(vb - v) * sm(u - us) * sm(ue - u)
+ streak = np.interp(vi, np.arange(nV), fbm1d(nV, 3, 2, s + 5))
+ flow = np.interp(ui, np.arange(nU), fbm1d(nU, 120, 2, s + 6))
+ dens = (0.9 + 0.09 * streak) * (1 + 0.04 * flow)
+ dens *= 1 + 0.28 * np.exp(-((u - us - 5) / 7) ** 2) + 0.16 * np.exp(-((u - ue + 6) / 6) ** 2)
+ dens *= 1 + 0.12 * (np.exp(-((v - vt) / 2.2) ** 2) + np.exp(-((vb - v) / 2.2) ** 2))
+ tail = smoothstep(ue - 46, ue - 4, u) # the nib runs dry: rows drop out near the end
+ keep = np.interp(vi, np.arange(nV), (fbm1d(nV, 2.5, 2, s + 7) + 1) / 2)
+ cov *= 1 - tail * (1 - smoothstep(tail * 0.8 - 0.12, tail * 0.8 + 0.12, keep)) * 0.85
+ a = cov * dens * alpha * (0.97 + 0.03 * self.tooth[sl])
+ self._mul(sl, a, colour)
+
+ # ------------------------------------------------------------ red pen
+ def pen(self, pts, width=4.0, colour=RED, alpha=0.9, jitter=0.7, smooth=True):
+ """a felt-tip stroke: even, slightly soaked-in ink, a blob where the pen touched down"""
+ P, w, press = self._prep(pts, width, 1.0, jitter, smooth, taper=(6, 10))
+ w = width * (0.86 + 0.14 * press)
+ w[:4] *= 1.12
+ m, sl = self._raster([(P, w.astype(np.float32), np.ones(len(P), np.float32))])
+ if sl is None: return
+ m = blur(m, 0.5)
+ self._mul(sl, m * alpha * (0.93 + 0.07 * self.tooth[sl]), colour)
+
+ def pen_loop(self, cx, cy, rx, ry, rot=-1.5, turns=1.12, a0=196, width=4.2, colour=RED):
+ """a hand-drawn red loop: a bit more than one turn, drifting outward so the ends pass each other"""
+ N = 160
+ t = np.linspace(0, 1, N)
+ a = np.deg2rad(a0 + t * 360 * turns)
+ s = self._seed()
+ k = 1 + fbm1d(N, 30, 2, s) * 0.02 + (t - 0.5) * 0.07
+ x, y = rx * k * np.cos(a), ry * (k + (t - 0.5) * 0.05) * np.sin(a)
+ r = np.deg2rad(-rot)
+ P = np.stack([cx + x * np.cos(r) - y * np.sin(r), cy + x * np.sin(r) + y * np.cos(r)], 1)
+ cut = int(N * 0.56)
+ self.pen(P[:cut + 1], width, colour, jitter=0.6, smooth=False) # two strokes: the overlap stacks darker
+ self.pen(P[cut:], width * 0.95, colour, jitter=0.6, smooth=False)
+
+ def pen_arrow(self, pts, width=4.0, head=20, colour=RED):
+ """a curved red arrow through control points, with a two-stroke head at the last point"""
+ P = spline(np.asarray(pts, np.float32), 12)
+ self.pen(P, width, colour, smooth=False)
+ d = P[-1] - P[-4]
+ a = np.arctan2(d[1], d[0])
+ for side in (1, -1):
+ b = a + side * np.deg2rad(150)
+ self.pen([P[-1] + np.array([np.cos(b), np.sin(b)]) * head, P[-1]], width * 0.95, colour, jitter=0.3, smooth=False)
+
+ def pen_underline(self, x0, x1, y, width=4.0, colour=RED, double=False, sag=2.0):
+ r = self.rng
+ self.pen([(x0, y + r.uniform(-1, 1)), ((x0 + x1) / 2, y + sag), (x1, y - r.uniform(0, 3))], width, colour)
+ if double:
+ self.pen([(x0 + 14, y + 13), ((x0 + x1) / 2, y + 13 + sag), (x1 - 24, y + 11)], width * 0.75, colour)
+
+ # ------------------------------------------------------------ lettering
+ def _font(self, style, size, s):
+ if style in ('sans', 'sans_bold', 'typewriter', 'condensed', 'rounded') and any(_is_cjk(ch) for ch in s):
+ return load_font('cjk_sans', size)
+ return load_font(style, size)
+
+ def _runs(self, s, style):
+ """split into runs of CJK / non-CJK so Latin keeps its own font next to Chinese"""
+ runs = []
+ for ch in s:
+ k = _is_cjk(ch)
+ if runs and runs[-1][1] == k: runs[-1][0] += ch
+ else: runs.append([ch, k])
+ return [(t, 'cjk_sans' if k else style) for t, k in runs]
+
+ def _tmask(self, s, x, y, size, style='sans_bold', anchor='ls', spacing=0.0, rot=0.0, weight=0, typed=False, ss=2):
+ """text -> (mask, slices); mixed CJK/Latin, faux-bold `weight` (px), letter `spacing`, rotation about (x, y).
+ typed=True: every character gets its own ink density and a small baseline wobble (typewriter / label printer)"""
+ runs = self._runs(s, style) if style not in ('cjk', 'cjk_sans') else [(s, style)]
+ fonts = {st: load_font(st, size * ss) for _, st in runs}
+ items = [] # (char or run, font, advance)
+ for t, st in runs:
+ f = fonts[st]
+ if typed or spacing:
+ for ch in t: items.append((ch, f, f.getlength(ch) + spacing * ss))
+ else:
+ items.append((t, f, f.getlength(t)))
+ total = sum(a for _, _, a in items) - (spacing * ss if (typed or spacing) else 0)
+ latin = [st for _, st in runs if st not in ('cjk', 'cjk_sans')]
+ f0 = fonts[latin[0]] if latin else fonts[runs[0][1]]
+ capH = -f0.getbbox('H', anchor='ls')[1]
+ desc = f0.getbbox('g', anchor='ls')[3]
+ dyb = {'s': 0, 'm': capH / 2, 'a': capH * 1.12, 't': capH * 1.12, 'd': -desc, 'b': -desc}.get(anchor[1], 0)
+ R = int(np.hypot(total / ss, size * 1.4) + weight + 8)
+ ox, oy = int(np.floor(x)) - R, int(np.floor(y)) - R # local image origin (may be off-canvas)
+ sl = self._box(ox, oy, ox + 2 * R, oy + 2 * R)
+ if sl is None: return None, None
+ im = Image.new('L', (2 * R * ss, 2 * R * ss), 0)
+ d = ImageDraw.Draw(im)
+ cx = (x - ox) * ss - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]
+ by = (y - oy) * ss + dyb
+ r = self.rng
+ for t, f, adv in items:
+ if typed:
+ fill = int(255 * r.uniform(0.82, 1.0)); jy = r.normal(0, 0.45) * ss; jx = r.normal(0, 0.25) * ss
+ else:
+ fill, jy, jx = 255, 0, 0
+ d.text((cx + jx, by + jy), t, font=f, fill=fill, anchor='ls', stroke_width=int(round(weight * ss)), stroke_fill=fill)
+ cx += adv
+ if rot:
+ im = im.rotate(rot, resample=Image.BICUBIC, center=((x - ox) * ss, (y - oy) * ss))
+ im = im.resize((2 * R, 2 * R), Image.BOX)
+ m = np.asarray(im, np.float32) / 255
+ ys0, xs0 = sl[0].start - oy, sl[1].start - ox
+ m = m[ys0:ys0 + (sl[0].stop - sl[0].start), xs0:xs0 + (sl[1].stop - sl[1].start)]
+ return m, sl
+
+ def text_width(self, s, size, font='sans_bold', spacing=0.0):
+ w = 0.0
+ for t, st in self._runs(s, font):
+ f = load_font(st, size)
+ w += sum(f.getlength(ch) + spacing for ch in t) if spacing else f.getlength(t)
+ return w - (spacing if spacing else 0)
+
+ def text(self, s, x, y, size, colour=INK, font='sans_bold', anchor='ls', rot=0.0, spacing=0.0, weight=0,
+ medium='ink', alpha=0.95):
+ """lettering on the page. medium: 'ink' (fine-liner, multiply), 'print' (pre-printed form text),
+ 'typed' (typewriter / label printer: uneven strikes), 'pencil' (graphite grain), 'opaque' (white on stickers)"""
+ m, sl = self._tmask(s, x, y, size, font, anchor, spacing, rot, weight, typed=(medium == 'typed'))
+ if sl is None: return
+ if medium == 'pencil':
+ self._graphite(m * alpha, sl, colour, 0.92)
+ elif medium == 'opaque':
+ self._over(sl, m * alpha, colour)
+ elif medium == 'typed':
+ m = blur(m, 0.35)
+ self._mul(sl, m * alpha * (0.84 + 0.16 * self.tooth[sl]), colour)
+ elif medium == 'print':
+ self._mul(sl, m * alpha * (0.95 + 0.05 * self.tooth[sl]), colour)
+ else:
+ m = np.maximum(m, blur(m, 0.6) * 0.9)
+ self._mul(sl, m * alpha * (0.9 + 0.1 * self.tooth[sl]), colour)
+
+ # ------------------------------------------------------------ desk and notebook
+ def desk(self, colour='#56616c', light='#77838e', dark='#3a434d'):
+ """graphite blue-grey desk: light pooled at the upper left, fine grain, faint board fibres"""
+ r = np.hypot((self.XX - 0.28 * self.W) / (0.95 * self.W), (self.YY - 0.16 * self.H) / (0.85 * self.H))
+ t1 = smoothstep(0.0, 0.55, r)[..., None]; t2 = smoothstep(0.5, 1.15, r)[..., None]
+ base = _c(light) * (1 - t1) + _c(colour) * t1
+ base = base * (1 - t2) + _c(dark) * t2
+ grain = noise2d(self.H, self.W, 1.6, 2, self._seed())
+ fib = np.asarray(Image.fromarray(self.rng.random((self.H // 3, self.W // 90)).astype(np.float32)).resize((self.W, self.H), Image.BICUBIC))
+ mott = noise2d(self.H, self.W, 260, 3, self._seed())
+ self.img = base * (1 + 0.05 * (grain - 0.5) + 0.03 * (fib - 0.5) + 0.05 * (mott - 0.5))[..., None]
+
+ def _grid(self, sl, gx0, gy0, grid, major):
+ X, Y = self.XX[sl] - gx0, self.YY[sl] - gy0
+ def lines(c, g, w):
+ d = np.abs(((c + g / 2) % g) - g / 2)
+ return np.clip(w / 2 - d + 0.5, 0, 1)
+ minor = np.maximum(lines(X, grid, 1.0), lines(Y, grid, 1.0))
+ maj = np.maximum(lines(X, grid * major, 1.5), lines(Y, grid * major, 1.5))
+ return minor, maj
+
+ def notebook(self, x0, y0, x1, y1, tabs=((MINT, 250), ('#efe596', 372), ('#e9a79f', 494)), stack=5, ear=58,
+ margin=150, header=48, grid=24, major=5, cover='#2c3846', paper='#f8f8f4', grid_colour='#3f8fb8',
+ margin_colour='#d6483e', holes=True):
+ """a top-bound wire-o notebook lying on the desk; the top page spans (x0, y0)-(x1, y1)"""
+ self.page = (x0, y0, x1, y1)
+ self.page_margin = x0 + margin
+ self.page_header = y0 + header
+ s = self._seed()
+ # hard back cover + its shadow on the desk
+ sl, u, v = self._rbox((x0 + x1) / 2 + 1, (y0 + y1) / 2 + 10, (x1 - x0) / 2 + 17, (y1 - y0) / 2 + 12, 0, 120)
+ cm = np.clip(0.5 - self._sdf_rrect(u, v, (x1 - x0) / 2 + 17, (y1 - y0) / 2 + 12, 14), 0, 1)
+ self._shadow(sl, cm, 44, 40, 0.5)
+ self._shadow(sl, cm, 12, 10, 0.35)
+ g = np.clip((u / (x1 - x0) + v / (y1 - y0)) + 0.5, 0, 1)[..., None]
+ cc = _c('#3b4858') * (1 - g) + _c(cover) * g
+ cc = cc * (1 + 0.035 * (self.tooth[sl] - 0.5))[..., None]
+ rim = np.clip(cm - shift(cm, 2, 2), 0, 1)
+ self._over(sl, cm, cc)
+ self.img[sl] += (rim * 0.12)[..., None]
+ # divider tabs, peeking out on the right between the pages
+ for i, (tc, ty) in enumerate(tabs or []):
+ tsl, tu, tv = self._rbox(x1 + 6, ty + 52, 44, 52, 0, 20)
+ tm = np.clip(0.5 - self._sdf_rrect(tu, tv, 44, 52, 11), 0, 1) * (tu > -40)
+ self._shadow(tsl, tm, 4, 3, 0.35)
+ shade = 1 - 0.08 * smoothstep(-44, 0, -tu) + 0.1 * np.exp(-((tu - 14) / 14) ** 2) - 0.06 * smoothstep(30, 44, tu)
+ tcol = _c(tc)[None, None, :] * (shade * (0.97 + 0.04 * self.tooth[tsl]))[..., None]
+ self._over(tsl, tm, tcol)
+ # the stack of pages under the top one: each edge steps down a little
+ for i in range(stack, 0, -1):
+ dx, dy = i * 0.7, i * 3.0
+ psl, pu, pv = self._rbox((x0 + x1) / 2 + dx, (y0 + y1) / 2 + dy, (x1 - x0) / 2, (y1 - y0) / 2, 0, 6)
+ pm = np.clip(0.5 - self._sdf_rrect(pu, pv, (x1 - x0) / 2, (y1 - y0) / 2, 5), 0, 1)
+ self._shadow(psl, pm, 1.2, 1.0, 0.3)
+ shade = (0.955 - 0.018 * i) * (0.985 + 0.02 * self.tooth[psl])
+ col = _c(paper)[None, None, :] * shade[..., None]
+ if i == 1: # the page right under shows in the dog-ear
+ mi, ma = self._grid(psl, x0 + dx, y0 + header + dy, grid, major)
+ col = col * (1 - (np.maximum(mi * 0.2, ma * 0.36))[..., None] * (1 - _c(grid_colour)))
+ self._over(psl, pm, col)
+ # the top page
+ psl = self._box(x0 - 2, y0 - 2, x1 + 2, y1 + 2)
+ X, Y = self.XX[psl], self.YY[psl]
+ pm = np.clip(0.5 - self._sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, 5), 0, 1)
+ cut = ((X - (x1 - ear)) + (Y - (y1 - ear)) - ear) / np.sqrt(2) # > 0 beyond the fold line
+ pm = pm * np.clip(0.5 - cut, 0, 1)
+ self._shadow(psl, pm, 1.5, 1.2, 0.25)
+ glow = 0.045 * np.exp(-(((X - x0 - 0.22 * (x1 - x0)) / (0.75 * (x1 - x0))) ** 2 + ((Y - y0 - 0.1 * (y1 - y0)) / (0.7 * (y1 - y0))) ** 2))
+ fall = 0.06 * np.clip(((X - x0) / (x1 - x0) * 0.35 + (Y - y0) / (y1 - y0) * 0.65 - 0.4) / 0.6, 0, 1)
+ edge = np.minimum.reduce([X - x0, x1 - X, Y - y0, y1 - Y])
+ inset = 0.06 * (1 - smoothstep(0, 34, edge))
+ curl = 0.035 * np.exp(-np.clip(Y - y0, 0, None) / 22)
+ light = 1 + glow - fall - inset - curl + 0.03 * (self.tooth[psl] - 0.5)
+ col = _c(paper)[None, None, :] * light[..., None]
+ mi, ma = self._grid(psl, x0, y0 + header, grid, major)
+ ga = np.maximum(mi * 0.2, ma * 0.36) * (Y > y0 + header + 0.5) * (0.8 + 0.2 * self.tooth[psl])
+ col = col * (1 - ga[..., None] * (1 - _c(grid_colour)))
+ hl = np.clip(1.1 - np.abs(Y - (y0 + header)) + 0.5, 0, 1) * 0.42
+ col = col * (1 - hl[..., None] * (1 - _c(grid_colour)))
+ mx = x0 + margin
+ mg = (np.clip(1.2 - np.abs(X - mx) + 0.5, 0, 1) * 0.62 + np.clip(0.5 - np.abs(X - mx - 6) + 0.5, 0, 1) * 0.35) * (Y > y0 + header)
+ col = col * (1 - (mg * (0.85 + 0.15 * self.tooth[psl]))[..., None] * (1 - _c(margin_colour)))
+ self._over(psl, pm, col)
+ # punched holes (the dark cover shows through)
+ self.holes = []
+ if holes:
+ n = int((x1 - x0 - 76) / 39.6) + 1
+ xs = x0 + 38 + np.arange(n) * (x1 - x0 - 76) / (n - 1)
+ for hx in xs:
+ hsl, hu, hv = self._rbox(hx, y0 + 21.5, 7, 9.5, 0, 3)
+ hm = np.clip(0.5 - self._sdf_rrect(hu, hv, 7, 9.5, 5), 0, 1)
+ hc = _c('#232c36')[None, None, :] * (0.75 + 0.35 * smoothstep(-9.5, 4, hv))[..., None]
+ self._over(hsl, hm, hc)
+ self.holes.append(hx)
+ # dog-ear: the corner folded back over the page (its back shows a faint mirror of the grid)
+ fsl = self._box(x1 - ear - 6, y1 - ear - 6, x1 + 6, y1 + 6)
+ X, Y = self.XX[fsl], self.YY[fsl]
+ du, dv = X - (x1 - ear), Y - (y1 - ear)
+ fm = np.clip(0.5 - (du + dv - ear) / np.sqrt(2), 0, 1) * np.clip(du + 0.5, 0, 1) * np.clip(dv + 0.5, 0, 1)
+ dist_fold = (ear - du - dv) / np.sqrt(2)
+ under = np.clip(0.5 + (du + dv - ear) / np.sqrt(2), 0, 1) * np.clip(x1 - X, 0, 1) * np.clip(y1 - Y, 0, 1)
+ self._mul(fsl, under * 0.35 * np.exp(-np.clip(-dist_fold, 0, None) / 10), '#0e1620')
+ self._shadow(fsl, fm, 2.5, 2.2, 0.28)
+ ft = np.clip(dist_fold / (ear / np.sqrt(2)), 0, 1)
+ fcol = _c('#f4f4ef')[None, None, :] * (1.02 - 0.09 * ft + 0.05 * np.exp(-(dist_fold / 5) ** 2))[..., None]
+ mi, ma = self._grid(fsl, x1 + 3, y1 + 3, grid, major)
+ fcol = fcol * (1 - (np.maximum(mi, ma) * 0.05)[..., None])
+ self._over(fsl, fm, fcol)
+
+ def binding(self, colour='#b9c2cb', r=2.2):
+ """wire-o twin loops through every punched hole, lit as metal tubes, with shadows on the page"""
+ if not self.page: return
+ x0, y0, x1, y1 = self.page
+ paths = []
+ for hx in self.holes:
+ for o in (-3.4, 3.4):
+ p0 = np.array([hx + o, y0 + 25]); p3 = np.array([hx + o * 0.15, y0 - 28])
+ c1 = np.array([hx + o, y0 - 6]); c2 = np.array([hx + o * 0.7, y0 - 22])
+ t = np.linspace(0, 1, 26)[:, None]
+ paths.append(((1 - t) ** 3) * p0 + 3 * ((1 - t) ** 2) * t * c1 + 3 * (1 - t) * t * t * c2 + t ** 3 * p3)
+ sl = self._box(x0 - 20, y0 - 40, x1 + 20, y0 + 40)
+ sh = np.zeros((sl[0].stop - sl[0].start, sl[1].stop - sl[1].start), np.float32)
+ im = Image.new('L', (sh.shape[1] * 2, sh.shape[0] * 2), 0); d = ImageDraw.Draw(im)
+ for P in paths:
+ Q = (P - [sl[1].start, sl[0].start]) * 2
+ d.line([tuple(q) for q in Q], fill=255, width=int(r * 2 * 2 + 2))
+ sh = np.asarray(im.resize((sh.shape[1], sh.shape[0]), Image.BOX), np.float32) / 255
+ self._shadow(sl, sh, 8, 2.8, 0.5)
+ for P in paths:
+ self._tube(P, r, colour, deep=(y0 + 12, y0 + 30))
+
+ def _tube(self, P, r, colour, spec=0.9, shine=36, deep=None):
+ """a round metal wire along polyline P, shaded from its cross-section normals"""
+ P = np.asarray(P, np.float32)
+ sl = self._box(P[:, 0].min() - r - 2, P[:, 1].min() - r - 2, P[:, 0].max() + r + 2, P[:, 1].max() + r + 2)
+ if sl is None: return
+ X, Y = self.XX[sl], self.YY[sl]
+ best = np.full(X.shape, 1e9, np.float32); vx = np.zeros_like(X); vy = np.zeros_like(X); tt = np.zeros_like(X)
+ for i in range(len(P) - 1):
+ a, b = P[i], P[i + 1]
+ ab = b - a; l2 = float(ab @ ab) + 1e-6
+ t = np.clip(((X - a[0]) * ab[0] + (Y - a[1]) * ab[1]) / l2, 0, 1)
+ qx, qy = X - (a[0] + t * ab[0]), Y - (a[1] + t * ab[1])
+ dd = qx * qx + qy * qy
+ k = dd < best
+ best = np.where(k, dd, best); vx = np.where(k, qx, vx); vy = np.where(k, qy, vy); tt = np.where(k, (i + t) / (len(P) - 1), tt)
+ dist = np.sqrt(best)
+ cov = np.clip(r - dist + 0.5, 0, 1)
+ nx, ny = np.clip(vx / r, -1, 1), np.clip(vy / r, -1, 1)
+ nz = np.sqrt(np.clip(1 - nx * nx - ny * ny, 0, 1))
+ dif = np.clip(nx * self.L[0] + ny * self.L[1] + nz * self.L[2], 0, 1)
+ Hh = self.L + np.array([0, 0, 1], np.float32); Hh /= np.linalg.norm(Hh)
+ sp = np.clip(nx * Hh[0] + ny * Hh[1] + nz * Hh[2], 0, 1) ** shine
+ col = _c(colour)[None, None, :] * (0.28 + 0.8 * dif)[..., None] + (sp * spec)[..., None]
+ col = col * (0.75 + 0.25 * nz)[..., None]
+ if deep is not None: # inside the hole the wire is in shadow
+ yy = Y
+ col = col * (1 - 0.55 * smoothstep(deep[0], deep[1], yy))[..., None]
+ col = col * (1 - 0.35 * smoothstep(0.85, 1.0, tt))[..., None] # turning down behind the page edge
+ self._over(sl, cov, np.clip(col, 0, 1))
+
+ # ------------------------------------------------------------ paper bits
+ def sticky(self, cx, cy, w, h, rot=0.0, colour=MINT, curl=1.0):
+ """a sticky note: the adhesive strip lies flat, the rest curls up, so the shadow grows toward the bottom
+ corners. Returns a Frame to write on."""
+ sl, u, v = self._rbox(cx, cy, w / 2, h / 2, rot, 40)
+ if sl is None: return Frame(cx, cy, w, h, rot)
+ m = np.clip(0.5 - self._sdf_rrect(u, v, w / 2, h / 2, 1.5), 0, 1)
+ vn = (v + h / 2) / h
+ lift = smoothstep(0.22, 1.0, vn) ** 1.6 * (0.55 + 0.45 * (np.abs(u) / (w / 2)) ** 2) * curl
+ self._shadow(sl, m, 1.6, 1.4, 0.3)
+ self._shadow(sl, m * lift, 9 * curl + 2, 8, 0.42)
+ col = _c(colour)
+ shade = 1 + 0.035 * (1 - smoothstep(0, 0.22, vn)) - 0.07 * smoothstep(0.35, 1.0, vn) + 0.04 * np.clip(1 - (u / w + vn) * 1.4, 0, 1)
+ shade = shade + 0.025 * (self.tooth[sl] - 0.5) + 0.05 * np.exp(-((v - h / 2 + 1.5) / 1.4) ** 2)
+ self._over(sl, m, col[None, None, :] * shade[..., None])
+ return Frame(cx, cy, w, h, rot)
+
+ def sticker(self, cx, cy, w, h, rot=0.0, colour=RED, radius=None, border=7, lines=(), shape='rrect'):
+ """a die-cut vinyl sticker: printed face, white cut margin, gloss, thin shadow.
+ lines: [(text, lx, ly, size, font, colour, anchor)] in the sticker's own frame (from its top-left)."""
+ hw, hh = w / 2 + border, h / 2 + border
+ sl, u, v = self._rbox(cx, cy, hw, hh, rot, 30)
+ if sl is None: return Frame(cx, cy, w, h, rot)
+ if shape == 'circle':
+ d_in = np.hypot(u, v) - w / 2
+ else:
+ rr = min(w, h) / 2 if radius is None else radius
+ d_in = self._sdf_rrect(u, v, w / 2, h / 2, rr)
+ outer = np.clip(0.5 - (d_in - border), 0, 1)
+ inner = np.clip(0.5 - d_in, 0, 1)
+ self._shadow(sl, outer, 1.5, 1.3, 0.35)
+ self._shadow(sl, outer, 7, 8, 0.22)
+ vinyl = _c('#fdfdfb')[None, None, :] * (0.97 + 0.03 * self.tooth[sl])[..., None]
+ self._over(sl, outer, vinyl)
+ face = _c(colour)[None, None, :] * (1 + 0.02 * (self.tooth[sl] - 0.5))[..., None]
+ self._over(sl, inner, face)
+ f = Frame(cx, cy, w, h, rot)
+ for ln in lines:
+ s, lx, ly, size, font, col = ln[:6]
+ anchor = ln[6] if len(ln) > 6 else 'ms'
+ px, py = f.pt(lx, ly)
+ self.text(s, px, py, size, col, font, anchor, rot=rot, medium='opaque', alpha=1.0)
+ gl = np.clip(1 - ((u + hw) / (2 * hw) * 0.6 + (v + hh) / (2 * hh)) * 1.1, 0, 1) ** 1.5 * 0.3
+ rim = np.clip(outer - np.clip(0.5 - (d_in - border + 1.6), 0, 1), 0, 1)
+ side = np.clip(-(u * self.L[0] + v * self.L[1]) / (np.hypot(u, v) + 1e-3), -1, 1)
+ self.img[sl] = np.clip(self.img[sl] + (outer * gl)[..., None] - (rim * 0.12 * (1 - side))[..., None], 0, 1)
+ return f
+
+ def label_tape(self, s, x, y, size=24, rot=-0.8, colour='#27313c', letters='#e8edf1', anchor='l', spacing=None):
+ """label-maker tape: dark embossed plastic, scissor-cut ends, stress-whitened raised letters.
+ (x, y): left end (anchor 'l') or centre (anchor 'm') of the tape's centre line. Returns a Frame."""
+ sp = size * 0.22 if spacing is None else spacing
+ tw = self.text_width(s, size, 'sans_bold', sp)
+ w, h = tw + size * 1.6, size * 1.75
+ t = np.deg2rad(rot)
+ cx = x + (w / 2 * np.cos(t) if anchor == 'l' else 0)
+ cy = y - (w / 2 * np.sin(t) if anchor == 'l' else 0)
+ sl, u, v = self._rbox(cx, cy, w / 2, h / 2, rot, 16)
+ if sl is None: return Frame(cx, cy, w, h, rot)
+ skew = self.rng.uniform(-0.12, 0.12) # scissor cut: ends not quite square
+ m = np.clip(0.5 - self._sdf_rrect(u + v * skew * np.sign(u), v, w / 2, h / 2, 2.5), 0, 1)
+ self._shadow(sl, m, 2.2, 2.2, 0.4)
+ vn = (v + h / 2) / h
+ grad = 1.2 - 0.3 * vn + 0.25 * np.exp(-((vn - 0.2) / 0.1) ** 2) - 0.12 * np.exp(-((vn - 0.97) / 0.05) ** 2)
+ ridges = 1 + 0.03 * np.sin(v * 3.1) + 0.05 * (self.tooth[sl] - 0.5)
+ self._over(sl, m, _c(colour)[None, None, :] * (grad * ridges)[..., None])
+ tm, tsl = self._tmask(s, cx, cy, size, 'sans_bold', 'mm', sp, rot, 0)
+ if tsl is not None:
+ hmap = blur(tm, 1.0) * 3.0
+ gy, gx = np.gradient(hmap)
+ lit = np.clip(1 - 0.9 * (gx * self.L[0] + gy * self.L[1]), 0.45, 1.5)
+ stress = 0.84 + 0.16 * noise2d(tm.shape[0], tm.shape[1], 3, 2, self._seed())
+ col = _c(letters)[None, None, :] * (stress * lit)[..., None]
+ self._over(tsl, np.clip(tm * 1.05, 0, 1), np.clip(col, 0, 1))
+ self._mul(tsl, np.clip(shift(blur(tm, 0.8), 1, 1) - tm, 0, 1) * 0.5, '#000000')
+ return Frame(cx, cy, w, h, rot)
+
+ def stain(self, cx, cy, r, colour='#8a5a2b', strength=0.2, gaps=0.35):
+ """a coffee-ring stain: a faint fill with the darker tide line at the rim (partly broken)"""
+ sl = self._box(cx - r - 12, cy - r - 12, cx + r + 12, cy + r + 12)
+ if sl is None: return
+ dx, dy = self.XX[sl] - cx, self.YY[sl] - cy
+ th = np.arctan2(dy, dx); d = np.hypot(dx, dy)
+ s = self._seed()
+ rr = r * (1 + 0.035 * _periodic(th, 10, s) + 0.02 * np.cos(th - 0.8))
+ inside = np.clip(rr - d + 0.5, 0, 1)
+ rim = np.exp(-((d - rr + 1.0) / 1.15) ** 2) * 1.3 + 0.28 * np.exp(-((d - rr + 4.5) / 3.0) ** 2) * inside
+ keep = (0.12 + 0.88 * smoothstep(gaps - 0.15, gaps + 0.15, 0.5 + 0.5 * _periodic(th, 6, s + 1, 0.8))) * (0.75 + 0.25 * np.cos(th - 0.8))
+ tide = 0.14 * np.exp(-((d - rr * 0.84) / 1.2) ** 2) * np.clip(0.7 * _periodic(th, 5, s + 2), 0, 1)
+ fill = inside * 0.08 * (0.6 + 0.4 * noise2d(d.shape[0], d.shape[1], 30, 2, s + 3))
+ self._mul(sl, strength * (rim * keep + tide + fill), colour)
+
+ # ------------------------------------------------------------ desk props
+ def pencil_prop(self, x, y, angle=90, length=1100, width=34, body='#56677a', wood='#e2c298', lead='#2a3038',
+ label=None, label_colour='#d9c78c', end='eraser', eraser='#d39a90', ferrule='#c8c2b2'):
+ """a hexagonal pencil lying on the desk, point at (x, y), body running along `angle`
+ (screen degrees, clockwise from +x); end='eraser' adds a crimped ferrule and a rubber, 'plain' a cut end"""
+ a = np.deg2rad(angle); ca, sa = np.cos(a), np.sin(a)
+ Rh = width / 2; cone = Rh * 5.4
+ ex, ey = x + ca * length, y + sa * length
+ sl = self._box(min(x, ex) - Rh - 40, min(y, ey) - Rh - 40, max(x, ex) + Rh + 40, max(y, ey) + Rh + 40)
+ if sl is None: return
+ X, Y = self.XX[sl] - x, self.YY[sl] - y
+ u = X * ca + Y * sa; v = -X * sa + Y * ca
+ rad = np.where(u < cone, Rh * np.clip(u / cone, 0, 1), Rh)
+ if end == 'eraser':
+ fl, el, rE = width * 1.25, width * 0.85, Rh * 0.55
+ uf0, ue0 = length - el - fl, length - el
+ cap = Rh * 0.88 * np.sqrt(np.clip(1 - ((u - (length - rE)) / rE) ** 2, 0, 1))
+ rad = np.where(u >= ue0, np.where(u > length - rE, cap, Rh * 0.88), np.where(u >= uf0, Rh * 0.96, rad))
+ m = np.clip(rad - np.abs(v) + 0.5, 0, 1) * np.clip(u + 0.5, 0, 1) * np.clip(length - u + 0.5, 0, 1)
+ self._shadow(sl, m, Rh * 0.9 + 5, 6, 0.5)
+ self._shadow(sl, m, 2, 2, 0.35)
+ Lu = self.L[0] * ca + self.L[1] * sa; Lv = -self.L[0] * sa + self.L[1] * ca; Lz = self.L[2]
+ Hh = np.array([Lu, Lv, Lz + 1]); Hh /= np.linalg.norm(Hh)
+ # painted hexagonal body: three facets seen from above
+ side = np.where(v < -Rh / 2, -1, np.where(v > Rh / 2, 1, 0))
+ nv = side * 0.866; nz = np.where(side == 0, 1.0, 0.5)
+ dif = np.clip(nv * Lv + nz * Lz, 0, 1)
+ sp = np.clip(nv * Hh[1] + nz * Hh[2], 0, 1) ** 50
+ paint = _c(body)[None, None, :] * (0.42 + 0.72 * dif)[..., None] + (sp * 0.28)[..., None]
+ ridge = np.exp(-((np.abs(v) - Rh / 2) / 0.8) ** 2) * 0.12
+ paint = paint + ridge[..., None]
+ streak = np.interp(np.clip(u, 0, length), np.linspace(0, length, 400), fbm1d(400, 30, 2, self._seed()))
+ paint = paint * (1 + 0.02 * streak)[..., None]
+ # scalloped paint edge where the sharpener cut into each facet
+ sface = np.where(side == 0, v, (np.abs(v) - 0.75 * Rh) / 0.5)
+ u_paint = cone * np.sqrt(0.75 + (sface / Rh) ** 2)
+ # sharpened cone (round): wood, then the graphite point
+ rc = np.maximum(Rh * np.clip(u / cone, 1e-3, 1), 1e-3)
+ cnv = np.clip(v / rc, -1, 1); cnz = np.sqrt(np.clip(1 - cnv ** 2, 0, 1))
+ k = Rh / cone
+ cn = np.stack([-k * cnz, cnv, cnz], -1); cn /= np.linalg.norm(cn, axis=-1, keepdims=True)
+ cdif = np.clip(cn[..., 0] * Lu + cn[..., 1] * Lv + cn[..., 2] * Lz, 0, 1)
+ csp = np.clip(cn[..., 0] * Hh[0] + cn[..., 1] * Hh[1] + cn[..., 2] * Hh[2], 0, 1)
+ grain = 0.5 + 0.5 * np.sin(cnv * 7 + 1.5 * noise2d(u.shape[0], u.shape[1], 18, 2, self._seed()) * 3 + u * 0.02)
+ woodc = _c(wood)[None, None, :] * (0.55 + 0.6 * cdif - 0.08 * grain)[..., None]
+ leadc = _c(lead)[None, None, :] * (0.6 + 0.6 * cdif)[..., None] + (csp ** 30 * 0.55)[..., None]
+ tip = u < cone * 0.24
+ col = np.where((u < u_paint)[..., None], np.where(tip[..., None], leadc, woodc), paint)
+ edge = np.clip(1 - np.abs(u - u_paint) / 1.2, 0, 1) * (u > cone * 0.5)
+ col = col * (1 - 0.25 * edge)[..., None]
+ if end == 'eraser': # round parts: crimped metal ferrule, rubber
+ rr = np.maximum(rad, 1e-3)
+ rnv = np.clip(v / rr, -1, 1); rnz = np.sqrt(np.clip(1 - rnv ** 2, 0, 1))
+ rnu = np.where(u > length - rE, np.clip((u - (length - rE)) / rE, 0, 1), 0)
+ rn = np.stack([rnu, rnv, rnz], -1); rn /= np.linalg.norm(rn, axis=-1, keepdims=True)
+ rdif = np.clip(rn[..., 0] * Lu + rn[..., 1] * Lv + rn[..., 2] * Lz, 0, 1)
+ rsp = np.clip(rn[..., 0] * Hh[0] + rn[..., 1] * Hh[1] + rn[..., 2] * Hh[2], 0, 1)
+ crimp = np.cos(2 * np.pi * (u - uf0) / 6.0) * ((u - uf0 < fl * 0.3) | (u - uf0 > fl * 0.7))
+ fcol = _c(ferrule)[None, None, :] * (0.4 + 0.7 * rdif - 0.12 * crimp)[..., None] + (rsp ** 40 * 0.7)[..., None]
+ ecol = _c(eraser)[None, None, :] * (0.5 + 0.6 * rdif + 0.03 * (self.tooth[sl] - 0.5))[..., None]
+ col = np.where((u >= ue0)[..., None], ecol, np.where((u >= uf0)[..., None], fcol, col))
+ self._over(sl, m, np.clip(col, 0, 1))
+ if label:
+ lx, ly = x + ca * (cone + 150), y + sa * (cone + 150)
+ self.text(label, lx, ly, width * 0.42, label_colour, 'sans_bold', 'lm', rot=-angle, spacing=2, medium='opaque', alpha=0.85)
+
+ # ------------------------------------------------------------ output
+ def composite(self, vignette=0.2):
+ r = np.hypot((self.XX - self.W * 0.45) / self.W, (self.YY - self.H * 0.42) / self.H)
+ img = self.img * (1 - vignette * r ** 2 * 2.2)[..., None]
+ return Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8))
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite(); img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img
diff --git a/lib/sticker.py b/lib/sticker.py
new file mode 100644
index 0000000..cf6405c
--- /dev/null
+++ b/lib/sticker.py
@@ -0,0 +1,824 @@
+"""sticker — sticker collage x thermal receipt: die-cut vinyl stickers, washi tape, a receipt, hanging price
+tags, a rubber stamp and pen marks on a cream board (numpy + Pillow only).
+
+Model: a flat-lay photographed from straight above under one soft key light from the upper left.
+ board cream or light-kraft card: fine paper grain, low-frequency mottling, pale and dark fibres, a few
+ flecks, a warm fall-off of the light toward the corners.
+ art every object is first drawn as a flat-vector picture on its own transparent sheet (`Art`): masks
+ (circle, ellipse, rrect, poly, blob, line, text) filled with flat colours, gradients and hard-edged
+ shade/light crescents, like a vector illustration.
+ sticker `stick(art)` turns a sheet into a die-cut vinyl sticker: the silhouette is dilated with rounded
+ corners into a thick white border (small gaps and notches fill in, as a die would cut them); the
+ vinyl has thickness (a darker cut edge on the far side, a lit edge toward the light), a glossy
+ laminate (a thin specular rim along the lit edges plus a faint diagonal sheen), a tight contact
+ shadow plus a soft drop shadow, a slight rotation, and optionally a peeled corner folded back to
+ show the paler backing side, with its own small shadow on the sticker.
+ paper `lay(art)` places paper that is not vinyl (receipt, tag): matte, no border; the paper curls a
+ little (the ends of the long axis lift and turn toward or away from the light) and the lifted
+ parts throw a longer, softer shadow.
+ receipt `Receipt` — thermal paper with serrated tear edges top and bottom; the print is grey rather than
+ black and uneven the way a thermal head prints (weak head elements leave faint vertical streaks,
+ density drifts along the paper feed, tiny dropouts); rows with dotted leaders, rules, a printed
+ strike-through of an old price, emphasised (double-struck) totals, a barcode.
+ tape washi tape: translucent tinted paper (what is under it shows through), fibres running along its
+ length, a printed pattern (stripes, dots, grid), hand-torn zigzag ends, a hair-line shadow.
+ tag `tag_art` — a card price tag with clipped top corners and a metal grommet around the hole; laid
+ with more lift (it hangs), strung on twisted baker's twine (`twine`) drawn as a curve with ply
+ stripes, a cylinder shade and a shadow of its own.
+ stamp a round rubber stamp: rings, text set around the circle, a centre word; the ink is translucent
+ (it multiplies with whatever is under it), pools at the edges of the letters, is lighter where
+ the stamp was pressed less and broken where the paper tooth did not take ink.
+ pen ballpoint marks (ticks, loops, strike-throughs) with pressure variation and tapered ends.
+
+ from sticker import Sticker
+ s = Sticker(1920, 1080, seed=1)
+ s.board('#EFE5D1')
+ a = s.art(300, 300)
+ a.fill(a.circle(150, 150, 120), '#E04A2F')
+ a.fill(a.text('SALE', 150, 150, 70, 'sans_bold'), '#FBF3E4')
+ s.stick(a, 960, 540, rot=-6, border=16, peel='tr')
+ s.tape(960, 380, 220, rot=8, colour='#E8AC2C', pattern='stripe')
+ s.stamp(700, 700, 110, 'PAID · PAID · PAID · ', '已付', 'PAID', '#D8412B', rot=-12)
+ s.save('out.png')
+"""
+import numpy as np
+from PIL import Image, ImageDraw
+from core import blur, fbm1d, spline, noise2d, smoothstep, polygon_mask, shift, load_font, height_normals, blob_pts
+
+SHADOW = '#3A2710' # warm brown: shadows on a cream board are never grey
+
+
+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)
+
+
+# ---------------------------------------------------------------- small helpers (kept inside this module)
+_FONTS = {}
+
+
+def _font(style, size):
+ k = (style, int(round(size)))
+ if k not in _FONTS:
+ _FONTS[k] = load_font(style, max(4, int(round(size))))
+ return _FONTS[k]
+
+
+def _is_cjk(ch):
+ o = ord(ch)
+ return 0x2E80 <= o <= 0x9FFF or 0xF900 <= o <= 0xFAFF or 0xFF00 <= o <= 0xFFEF or 0x3000 <= o <= 0x303F
+
+
+def _runs(s, font, cjk, size):
+ """split a string into runs that share a font (Latin / CJK)"""
+ out = []
+ for ch in s:
+ f = _font(cjk, size) if _is_cjk(ch) else _font(font, size)
+ if out and out[-1][1] is f:
+ out[-1][0] += ch
+ else:
+ out.append([ch, f])
+ return out
+
+
+def measure(s, size, font='sans_bold', spacing=0.0, cjk='cjk_sans'):
+ """advance width of `s` in px (mixed Latin / CJK)"""
+ w = 0.0
+ for run, f in _runs(s, font, cjk, size):
+ w += sum(f.getlength(ch) + spacing for ch in run) if spacing else f.getlength(run)
+ return w - (spacing if s and spacing else 0)
+
+
+def text_mask(w, h, s, x, y, size, font='sans_bold', anchor='mm', stroke=0, spacing=0.0, rot=0.0, cjk='cjk_sans'):
+ """mixed Latin / CJK text -> float mask (h, w). anchor: first letter l/m/r, second m (cap middle),
+ s (baseline), t (cap top), b (descender). stroke thickens the glyphs (bold); rot degrees clockwise."""
+ total = measure(s, size, font, spacing, cjk) + 2 * stroke
+ x0 = x - total * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]] + stroke
+ base = y + {'m': 0.36, 's': 0.0, 't': 0.72, 'b': -0.22}[anchor[1]] * size
+ im = Image.new('L', (int(w), int(h)), 0)
+ d = ImageDraw.Draw(im)
+ for run, f in _runs(s, font, cjk, size):
+ if spacing:
+ for ch in run:
+ d.text((x0, base), ch, font=f, fill=255, anchor='ls', stroke_width=int(stroke), stroke_fill=255)
+ x0 += f.getlength(ch) + spacing
+ else:
+ d.text((x0, base), run, font=f, fill=255, anchor='ls', stroke_width=int(stroke), stroke_fill=255)
+ x0 += f.getlength(run)
+ if rot:
+ im = im.rotate(-rot, resample=Image.BICUBIC, center=(x, y))
+ return np.asarray(im, np.float32) / 255
+
+
+def _glyph(ch, size, font, cjk, stroke=0):
+ """one character centred in a small square mask"""
+ f = _font(cjk, size) if _is_cjk(ch) else _font(font, size)
+ n = int(size * 1.6 + 2 * stroke + 4)
+ im = Image.new('L', (n, n), 0)
+ ImageDraw.Draw(im).text((n / 2, n / 2 + 0.36 * size), ch, font=f, fill=255, anchor='ms', stroke_width=int(stroke), stroke_fill=255)
+ return im
+
+
+def _rotate(a, deg):
+ """rotate a float array by `deg` clockwise about its centre; the canvas grows to fit"""
+ if abs(deg) < 1e-3:
+ return a
+ im = Image.fromarray(np.ascontiguousarray(a, np.float32), 'F')
+ return np.asarray(im.rotate(-deg, resample=Image.BICUBIC, expand=True), np.float32)
+
+
+def _sample(a, x, y):
+ """bilinear lookup of a at float coords (zero outside)"""
+ H, W = a.shape
+ x0 = np.floor(x).astype(np.int32); y0 = np.floor(y).astype(np.int32)
+ fx = x - x0; fy = y - y0
+
+ def g(yy, xx):
+ ok = (xx >= 0) & (xx < W) & (yy >= 0) & (yy < H)
+ return np.where(ok, a[np.clip(yy, 0, H - 1), np.clip(xx, 0, W - 1)], 0)
+ return (g(y0, x0) * (1 - fx) * (1 - fy) + g(y0, x0 + 1) * fx * (1 - fy)
+ + g(y0 + 1, x0) * (1 - fx) * fy + g(y0 + 1, x0 + 1) * fx * fy)
+
+
+def _resample(P, step):
+ """polyline -> points evenly spaced by arc length, plus tangent angles"""
+ P = np.asarray(P, np.float32)
+ seg = np.linalg.norm(np.diff(P, axis=0), axis=1)
+ s = np.concatenate([[0], np.cumsum(seg)])
+ n = max(2, int(s[-1] / step) + 1)
+ t = np.linspace(0, s[-1], n)
+ x = np.interp(t, s, P[:, 0]); y = np.interp(t, s, P[:, 1])
+ ang = np.arctan2(np.gradient(y), np.gradient(x))
+ return x, y, ang, s[-1]
+
+
+# ================================================================ Art: a flat-vector sheet
+class Art:
+ """A transparent sheet in local pixels (origin top-left). Draw with masks + fill; then hand it to
+ Sticker.stick() (becomes a die-cut vinyl sticker) or Sticker.lay() (paper). Colour is stored
+ premultiplied, so partial coverage composites correctly."""
+
+ def __init__(self, w, h, seed=0):
+ self.w, self.h = int(np.ceil(w)), int(np.ceil(h))
+ self.rgb = np.zeros((self.h, self.w, 3), np.float32)
+ self.a = np.zeros((self.h, self.w), np.float32)
+ self.YY, self.XX = np.mgrid[0:self.h, 0:self.w].astype(np.float32)
+ self.rng = np.random.default_rng(seed)
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def _pil(self, fn, ss=3):
+ im = Image.new('L', (self.w * ss, self.h * ss), 0)
+ fn(ImageDraw.Draw(im), ss)
+ return np.asarray(im.resize((self.w, self.h), Image.BOX), np.float32) / 255
+
+ # ---- masks
+ def circle(self, cx, cy, r):
+ return np.clip(r - np.hypot(self.XX - cx, self.YY - cy) + 0.5, 0, 1)
+
+ def ring(self, cx, cy, r, width):
+ return np.clip(width / 2 - np.abs(np.hypot(self.XX - cx, self.YY - cy) - r) + 0.5, 0, 1)
+
+ def ellipse(self, cx, cy, rx, ry, rot=0.0):
+ t = np.deg2rad(rot); c, s = np.cos(t), np.sin(t)
+ x = (self.XX - cx) * c + (self.YY - cy) * s; y = -(self.XX - cx) * s + (self.YY - cy) * c
+ d = np.sqrt((x / rx) ** 2 + (y / ry) ** 2)
+ return np.clip((1 - d) * min(rx, ry) + 0.5, 0, 1)
+
+ def rrect(self, x0, y0, x1, y1, r):
+ return self._pil(lambda d, k: d.rounded_rectangle((x0 * k, y0 * k, x1 * k, y1 * k), r * k, fill=255))
+
+ def poly(self, pts):
+ return self._pil(lambda d, k: d.polygon([(float(x) * k, float(y) * k) for x, y in pts], fill=255))
+
+ def blob(self, cx, cy, rx, ry, rough=0.06, rot=0.0, seed=None):
+ return self.poly(blob_pts(cx, cy, rx, ry, rough, 120, self._seed() if seed is None else seed, rot))
+
+ def line(self, pts, width, smooth=False):
+ P = spline(pts, 12) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+
+ def fn(d, k):
+ q = [(float(x) * k, float(y) * k) for x, y in P]
+ d.line(q, fill=255, width=max(1, int(round(width * k))), joint='curve')
+ for x, y in (q[0], q[-1]):
+ r = width * k / 2
+ d.ellipse((x - r, y - r, x + r, y + r), fill=255)
+ return self._pil(fn)
+
+ def text(self, s, x, y, size, font='sans_bold', anchor='mm', stroke=0, spacing=0.0, rot=0.0, cjk='cjk_sans'):
+ return text_mask(self.w, self.h, s, x, y, size, font, anchor, stroke, spacing, rot, cjk)
+
+ def crescent(self, mask, dx, dy):
+ """the rim of `mask` left uncovered by a copy shifted by (dx, dy): a shade or light crescent"""
+ return np.clip(mask - shift(mask, dx, dy), 0, 1)
+
+ # ---- paint
+ def _over(self, m, col, clip):
+ m = np.clip(m, 0, 1)
+ if clip: # paint inside what is already there, keep the silhouette
+ self.rgb = self.rgb * (1 - m[..., None]) + col * (m * self.a)[..., None]
+ else:
+ self.rgb = self.rgb * (1 - m[..., None]) + col * m[..., None]
+ self.a = self.a * (1 - m) + m
+
+ def fill(self, mask, colour, alpha=1.0, clip=False):
+ self._over(mask * alpha, _c(colour), clip)
+
+ def gradient(self, mask, c0, c1, p0, p1, alpha=1.0, clip=False):
+ """linear gradient c0 at p0 -> c1 at p1"""
+ d = np.array(p1, np.float32) - np.array(p0, np.float32)
+ t = np.clip(((self.XX - p0[0]) * d[0] + (self.YY - p0[1]) * d[1]) / (d @ d + 1e-6), 0, 1)[..., None]
+ self._over(mask * alpha, _c(c0) * (1 - t) + _c(c1) * t, clip)
+
+ def radial(self, mask, c0, c1, cx, cy, r, alpha=1.0, clip=False):
+ """radial gradient c0 at (cx, cy) -> c1 at distance r"""
+ t = np.clip(np.hypot(self.XX - cx, self.YY - cy) / r, 0, 1)[..., None]
+ self._over(mask * alpha, _c(c0) * (1 - t) + _c(c1) * t, clip)
+
+ def cut(self, mask):
+ """punch a hole (the board shows through)"""
+ m = np.clip(mask, 0, 1)
+ self.rgb *= (1 - m)[..., None]; self.a *= (1 - m)
+
+ def speckle(self, mask, colour, n, r=(0.8, 1.8), alpha=(0.35, 0.8), stretch=1.0, rot=0.0, seed=None):
+ """n small dots scattered inside mask (flour, seeds, sugar); stretch > 1 makes short dashes"""
+ rng = np.random.default_rng(self._seed() if seed is None else seed)
+ ys, xs = np.nonzero(mask > 0.5)
+ if len(xs) == 0: return
+ pick = rng.integers(0, len(xs), n)
+ m = np.zeros((self.h, self.w), np.float32)
+ for i in pick:
+ rr = rng.uniform(*r)
+ e = self.ellipse(xs[i] + rng.uniform(-.5, .5), ys[i] + rng.uniform(-.5, .5), rr * stretch, rr, rot + rng.uniform(-25, 25))
+ m = np.maximum(m, e * rng.uniform(*alpha))
+ self.fill(m, colour, clip=True)
+
+ def texture(self, kind='kraft', strength=1.0, seed=None):
+ """card / paper tooth inside the sheet: fine grain, mottling, and (kraft) dark fibre flecks"""
+ s = self._seed() if seed is None else seed
+ h, w = self.h, self.w
+ t = 1 + strength * (0.05 * (noise2d(h, w, 1.3, 2, s) - 0.5) + 0.06 * (noise2d(h, w, 45, 3, s + 1) - 0.5))
+ if kind == 'kraft':
+ rng = np.random.default_rng(s + 2)
+ im = Image.new('L', (w * 2, h * 2), 0); d = ImageDraw.Draw(im)
+ for _ in range(int(w * h / 900 * strength)):
+ x, y = rng.uniform(0, w * 2), rng.uniform(0, h * 2)
+ a, L = rng.uniform(0, np.pi), rng.uniform(3, 14)
+ d.line((x, y, x + np.cos(a) * L, y + np.sin(a) * L), fill=int(rng.uniform(60, 200)), width=1)
+ fl = np.asarray(im.resize((w, h), Image.BOX), np.float32) / 255
+ t = t * (1 - 0.22 * fl)
+ self.rgb *= t[..., None]
+
+
+# ================================================================ Receipt: thermal paper
+class Receipt(Art):
+ """A thermal-paper receipt: serrated tear edges, grey thermal print with head streaks and feed drift.
+ Coordinates are local to the receipt; lay it with Sticker.lay(), which returns a local->global mapping
+ for pen marks and stamps."""
+
+ def __init__(self, w, h, seed=0, paper='#FDFCF9', ink='#4f525a', font='typewriter', tooth=15, depth=7, margin=34):
+ super().__init__(w, h, seed)
+ r = self.rng
+ self.font, self.margin, self.ink = font, margin, _c(ink)
+ n = int(w / tooth)
+ xs = np.linspace(0, w, 2 * n + 1)
+ top = [(x, (depth if i % 2 == 0 else 0.5) + r.uniform(-1.2, 1.2)) for i, x in enumerate(xs)]
+ bot = [(x, h - (depth if i % 2 == 0 else 0.5) + r.uniform(-1.2, 1.2)) for i, x in enumerate(xs)][::-1]
+ self.fill(self.poly(top + bot), paper)
+ s = self._seed()
+ tex = 1 + 0.016 * (noise2d(self.h, self.w, 1.4, 2, s) - 0.5) + 0.02 * (noise2d(self.h, self.w, 140, 3, s + 1) - 0.5)
+ self.rgb *= tex[..., None]
+ # thermal head: every column is one heating element; some are weak -> faint vertical streaks
+ colv = np.interp(np.arange(self.w), np.linspace(0, self.w - 1, self.w // 2), r.random(self.w // 2))
+ weak = np.zeros(self.w, np.float32)
+ for c in r.integers(0, self.w, 3):
+ weak[c:c + 1] = r.uniform(0.3, 0.5)
+ feed = fbm1d(self.h, 70, 3, s + 2)
+ dens = 0.8 + 0.08 * (colv[None, :] - 0.5) + 0.08 * feed[:, None]
+ dens = dens * (1 - weak[None, :])
+ dens = dens * smoothstep(0.04, 0.14, noise2d(self.h, self.w, 1.1, 1, s + 3))
+ self.dens = np.clip(dens, 0, 1).astype(np.float32)
+
+ def _ink(self, m, k=1.0, colour=None):
+ m = blur(m, 0.35) # heated dots spread a little: soft edges
+ self._over(np.clip(m * self.dens * k, 0, 1), self.ink if colour is None else _c(colour), clip=True)
+
+ def print(self, s, x, y, size, anchor='ls', bold=False, spacing=0.0, k=1.0, font=None):
+ """print a line of text; bold = emphasised mode (struck twice, one dot apart)"""
+ m = self.text(s, x, y, size, font or self.font, anchor, 0, spacing)
+ if bold:
+ m = np.maximum(m, shift(m, 1, 0))
+ self._ink(m, k)
+ return measure(s, size, font or self.font, spacing)
+
+ def centre(self, y, s, size=20, bold=False, spacing=0.0, k=1.0, font=None):
+ self.print(s, self.w / 2, y, size, 'ms', bold, spacing, k, font)
+
+ def row(self, y, left, right='', size=21, bold=False, leader=True, indent=0, was=None, k=1.0):
+ """item row: name on the left, amount right-aligned, dotted leader between;
+ was = an old price printed before the amount and struck through"""
+ x0, x1 = self.margin + indent, self.w - self.margin
+ wl = self.print(left, x0, y, size, 'ls', bold, k=k)
+ wr = self.print(right, x1, y, size, 'rs', bold, k=k) if right else 0
+ end = x1 - wr - 12
+ if was:
+ ww = measure(was, size * 0.86, self.font)
+ xw = end - ww + 2
+ self.print(was, end + 2, y, size * 0.86, 'rs', k=0.8 * k)
+ self._ink(self.line([(xw - 3, y - size * 0.3), (end + 5, y - size * 0.3)], 1.8), 0.9 * k)
+ end = xw - 12
+ if leader and right:
+ m = np.zeros((self.h, self.w), np.float32)
+ for x in np.arange(x0 + wl + 10, end, 8.0):
+ m = np.maximum(m, self.circle(x, y - 3, 1.25))
+ self._ink(m, 0.85 * k)
+
+ def rule(self, y, kind='dash', k=1.0):
+ x0, x1 = self.margin, self.w - self.margin
+ m = np.zeros((self.h, self.w), np.float32)
+ if kind == 'dash':
+ for x in np.arange(x0, x1 - 6, 13.0):
+ m = np.maximum(m, self.rrect(x, y - 1, x + 7, y + 1, 0))
+ elif kind == 'stars':
+ n = int((x1 - x0) / 22)
+ for i in range(n + 1):
+ m = np.maximum(m, self.text('*', x0 + (x1 - x0) * i / n, y + 8, 22, self.font, 'ms'))
+ elif kind == 'double':
+ m = np.maximum(self.rrect(x0, y - 3, x1, y - 1.5, 0), self.rrect(x0, y + 1.5, x1, y + 3, 0))
+ else:
+ m = self.rrect(x0, y - 1, x1, y + 1, 0)
+ self._ink(m, k)
+
+ def crease(self, y0, y1=None, strength=1.0):
+ """a fold line across the paper (it was folded once): a lit ridge on the light side, a soft dark
+ valley on the other, slightly wavy"""
+ y1 = y0 if y1 is None else y1
+ yl = y0 + (y1 - y0) * self.XX / max(1, self.w) + 1.5 * np.interp(self.XX[0], np.linspace(0, self.w, 9), self.rng.normal(0, 1, 9))[None, :]
+ d = self.YY - yl
+ t = 1 + strength * (0.05 * np.exp(-((d + 2.5) / 2.2) ** 2) - 0.07 * np.exp(-((d - 1.5) / 1.4) ** 2) - 0.025 * np.exp(-((d - 8) / 7) ** 2))
+ self.rgb *= t[..., None]
+
+ def barcode(self, y, h, x0=None, x1=None, seed=None, k=1.0):
+ rng = np.random.default_rng(self._seed() if seed is None else seed)
+ x0 = self.margin + 20 if x0 is None else x0
+ x1 = self.w - self.margin - 20 if x1 is None else x1
+ widths = [2, 1, 1, 2] + list(rng.integers(1, 5, 64)) + [2, 1, 1, 2]
+ u = (x1 - x0) / sum(widths)
+ m = np.zeros((self.h, self.w), np.float32); x = x0
+ for i, wd in enumerate(widths):
+ if i % 2 == 0:
+ m = np.maximum(m, np.clip(np.minimum(self.XX - x, x + wd * u - self.XX) + 0.5, 0, 1) * (self.YY >= y) * (self.YY <= y + h))
+ x += wd * u
+ self._ink(m, k)
+
+
+# ================================================================ Sticker: the board and everything on it
+class Sticker:
+ def __init__(self, W=1920, H=1080, seed=0, light=(-0.5, -0.62, 0.6)):
+ self.W, self.H = W, H
+ self.rng = np.random.default_rng(seed)
+ self.YY, self.XX = np.mgrid[0:H, 0:W].astype(np.float32)
+ self.L = np.asarray(light, np.float32) / np.linalg.norm(light)
+ d = np.array([-self.L[0], -self.L[1]]); self.away = d / np.linalg.norm(d) # shadows fall this way
+ self.img = np.ones((H, W, 3), np.float32) * _c('#EFE5D1')
+ self.stages = []
+
+ def _seed(self):
+ return int(self.rng.integers(1 << 30))
+
+ def art(self, w, h):
+ return Art(w, h, self._seed())
+
+ def receipt(self, w, h, **kw):
+ return Receipt(w, h, self._seed(), **kw)
+
+ # ------------------------------------------------------------ board
+ def board(self, colour='#EFE5D1', kind='cream', fibres=None):
+ """cream / light-kraft card: grain, mottling, pale and dark fibres, flecks"""
+ H, W = self.H, self.W
+ s = self._seed()
+ mott = noise2d(H, W, 320, 4, s); blot = noise2d(H, W, 70, 3, s + 1); grain = noise2d(H, W, 1.4, 2, s + 2)
+ k = 1.6 if kind == 'kraft' else 1.0
+ t = 1 + k * (0.08 * (mott - 0.5) + 0.03 * (blot - 0.5)) + 0.035 * (grain - 0.5)
+ img = _c(colour)[None, None, :] * t[..., None]
+ img = img + ((mott - 0.5) * 0.03 * k)[..., None] * np.array([0.4, 0.1, -0.6], np.float32) # darker patches warmer
+ rng = np.random.default_rng(s + 3)
+ n = fibres if fibres is not None else (520 if kind == 'kraft' else 380)
+ lit = Image.new('L', (W, H), 0); dk = Image.new('L', (W, H), 0)
+ dl, dd = ImageDraw.Draw(lit), ImageDraw.Draw(dk)
+ for i in range(n):
+ x, y = rng.uniform(-20, W + 20), rng.uniform(-20, H + 20)
+ L, a = rng.uniform(14, 70), rng.uniform(0, np.pi)
+ P = spline([(x, y), (x + np.cos(a) * L / 2 + rng.normal(0, 6), y + np.sin(a) * L / 2 + rng.normal(0, 6)),
+ (x + np.cos(a + rng.normal(0, .5)) * L, y + np.sin(a + rng.normal(0, .5)) * L)], 8)
+ dark = rng.random() < (0.45 if kind == 'kraft' else 0.25)
+ (dd if dark else dl).line([tuple(p) for p in P], fill=int(rng.uniform(70, 200)), width=1)
+ for _ in range(int(n * (1.2 if kind == 'kraft' else 0.5))):
+ x, y, r = rng.uniform(0, W), rng.uniform(0, H), rng.uniform(0.5, 1.3)
+ dd.ellipse((x - r, y - r, x + r, y + r), fill=int(rng.uniform(90, 220)))
+ fl = blur(np.asarray(lit, np.float32) / 255, 0.5); fd = blur(np.asarray(dk, np.float32) / 255, 0.5)
+ img = img + (fl * 0.16)[..., None] * (1 - img)
+ img = img * (1 - (fd * 0.22)[..., None] * (1 - _c('#6b4a22')))
+ self.img = np.clip(img, 0, 1).astype(np.float32)
+
+ # ------------------------------------------------------------ placement plumbing
+ def _region(self, shape, cx, cy):
+ h, w = shape[:2]
+ x0 = int(round(cx - w / 2)); y0 = int(round(cy - h / 2))
+ gx0, gy0, gx1, gy1 = max(0, x0), max(0, y0), min(self.W, x0 + w), min(self.H, y0 + h)
+ if gx0 >= gx1 or gy0 >= gy1:
+ return None, None
+ return (slice(gy0, gy1), slice(gx0, gx1)), (slice(gy0 - y0, gy1 - y0), slice(gx0 - x0, gx1 - x0))
+
+ @staticmethod
+ def mapping(art, cx, cy, rot):
+ """local art coords -> global board coords for an art laid/stuck at (cx, cy) with rotation rot"""
+ t = np.deg2rad(rot); c, s = np.cos(t), np.sin(t)
+
+ def T(x, y):
+ dx, dy = x - art.w / 2, y - art.h / 2
+ return (cx + dx * c - dy * s, cy + dx * s + dy * c)
+ return T
+
+ def _shade(self, reg, amount):
+ """darken a region by a shadow amount (0..1), tinted warm"""
+ return reg * (1 - amount[..., None] * (1 - _c(SHADOW)))
+
+ # ------------------------------------------------------------ vinyl sticker
+ def stick(self, art, cx, cy, rot=0.0, border=14, edge='#FBFAF6', peel=None, peel_size=44, lift=1.0,
+ gloss=1.0, shadow=1.0, sheen=None):
+ """die-cut vinyl sticker from an Art sheet, centred at (cx, cy), rot degrees clockwise.
+ border: white die-cut margin in px (0 = cut on the art's own edge); peel: 'tr'|'tl'|'br'|'bl' folds
+ that corner back; lift: how far it stands off (shadow length); gloss: laminate highlight strength;
+ sheen: position 0..1 of the diagonal gloss streak (None = random)."""
+ p = int(border * 2 + 18 + 10 * lift)
+ A = np.pad(np.clip(art.a, 0, 1), p)
+ P = np.pad(art.rgb, ((p, p), (p, p), (0, 0)))
+ h, w = A.shape
+ if border > 0: # rounded dilation = the die line
+ sg = border / 1.65
+ b = blur(smoothstep(0.02, 0.3, A), sg)
+ D = np.clip((b - 0.05) / (0.103 / sg * 1.5) + 0.5, 0, 1)
+ D = np.maximum(D, A)
+ else:
+ D = A
+ face = P + _c(edge) * (1 - A)[..., None] # art printed over the white vinyl
+ K, layers = D, None
+ if peel:
+ YY, XX = np.mgrid[0:h, 0:w].astype(np.float32)
+ u = np.array({'tr': (1, -1), 'tl': (-1, -1), 'br': (1, 1), 'bl': (-1, 1)}[peel], np.float32) / np.sqrt(2)
+ proj = XX * u[0] + YY * u[1]
+ sd = proj - (proj[D > 0.5].max() - peel_size) # > 0 inside the lifted corner
+ K = D * np.clip(0.5 - sd, 0, 1)
+ f = 0.78 # the flap is curled up: seen foreshortened
+ along = XX * -u[1] + YY * u[0]
+ ac = (along * (sd > -peel_size) * (sd < 0)).sum() / max(1, ((sd > -peel_size) * (sd < 0)).sum())
+ bend = 1 + 0.25 * ((along - ac) / (peel_size * 1.6)) ** 2 # edges of the flap roll back more
+ d = np.clip(-sd, 0, None)
+ k = d * (1 + 1 / (f * bend))
+ F = _sample(D, XX + u[0] * k, YY + u[1] * k) * np.clip(-sd * 2, 0, 1)
+ tt = np.clip(d / (peel_size * f), 0, 1)
+ Fs = 1.0 - 0.16 * tt ** 0.7 + 0.05 * np.exp(-d / 2.0)
+ layers = (F, F * Fs)
+ stack = [K, face[..., 0] * K, face[..., 1] * K, face[..., 2] * K]
+ if layers: stack += list(layers)
+ R = [_rotate(l, rot) for l in stack]
+ K = np.clip(R[0], 0, 1)
+ col = np.clip(np.stack(R[1:4], -1) / np.maximum(K, 1e-4)[..., None], 0, 1)
+ F = np.clip(R[4], 0, 1) if layers else None
+ U = np.clip(K + F, 0, 1) if layers else K
+ gsl, lsl = self._region(K.shape, cx, cy)
+ if gsl is None: return self.mapping(art, cx, cy, rot)
+ ax, ay = self.away
+ dist = 6 * lift
+ soft = blur(shift(U, ax * dist, ay * dist), 4 + 4 * lift) * 0.30 * shadow
+ cont = blur(shift(U, ax * 1.2, ay * 1.2), 1.3) * 0.40 * shadow
+ sh = 1 - (1 - soft) * (1 - cont)
+ # vinyl thickness: lit edge toward the light, darker cut edge away from it
+ n = height_normals(blur(K, 1.0) * 2.4)
+ lam = 1 + 1.0 * (n @ self.L - self.L[2])
+ rim = np.clip(K - smoothstep(0.55, 0.95, blur(K, 1.3)), 0, 1)
+ # laminate: specular rim on the lit edges and a faint diagonal sheen
+ ng = height_normals(blur(K, 3.2) * 5.0)
+ Hv = self.L + np.array([0, 0, 1], np.float32); Hv /= np.linalg.norm(Hv)
+ spec = np.clip((ng @ Hv - Hv[2]) / (1 - Hv[2]), 0, 1) ** 1.4 * 0.7 * gloss
+ spec *= smoothstep(0.4, 0.9, K)
+ YY, XX = np.mgrid[0:K.shape[0], 0:K.shape[1]].astype(np.float32)
+ q = XX * 0.78 + YY
+ qs = q[K > 0.5]
+ if qs.size:
+ pos = self.rng.uniform(0.25, 0.6) if sheen is None else sheen
+ q0 = qs.min() + (qs.max() - qs.min()) * pos
+ wd = (qs.max() - qs.min()) * 0.12
+ band = smoothstep(wd, wd * 0.35, np.abs(q - q0)) * 0.09 + np.exp(-((q - q0 - wd * 1.6) / (wd * 0.18)) ** 2) * 0.06
+ else:
+ band = 0
+ glow = np.clip(spec + band * gloss * K, 0, 1)
+ fc = col * lam[..., None]
+ fc = fc * (1 - (rim * 0.30)[..., None] * (1 - _c('#B9AE98')))
+ fc = 1 - (1 - fc) * (1 - glow[..., None])
+ reg = self._shade(self.img[gsl], sh[lsl])
+ Kl = K[lsl][..., None]
+ reg = reg * (1 - Kl) + np.clip(fc[lsl], 0, 1) * Kl
+ if layers: # the folded-back corner: pale backing side
+ fsh = blur(shift(F, ax * 4, ay * 4), 3) * 0.45 * K * (1 - F)
+ reg = self._shade(reg, fsh[lsl])
+ shade = np.clip(R[5] / np.maximum(F, 1e-4), 0.5, 1.1)
+ nf = height_normals(blur(F, 1.0) * 1.6)
+ lf = 1 + 0.8 * (nf @ self.L - self.L[2])
+ back = _c('#EEEBE3')[None, None, :] * (shade * lf)[..., None]
+ frim = np.clip(F - smoothstep(0.55, 0.95, blur(F, 1.2)), 0, 1)
+ back = back * (1 - (frim * 0.25)[..., None])
+ Fl = F[lsl][..., None]
+ reg = reg * (1 - Fl) + np.clip(back[lsl], 0, 1) * Fl
+ self.img[gsl] = np.clip(reg, 0, 1)
+ return self.mapping(art, cx, cy, rot)
+
+ # ------------------------------------------------------------ paper laid on the board
+ def lay(self, art, cx, cy, rot=0.0, curl=0.5, lift=1.0, shadow=1.0):
+ """matte paper (receipt, tag): the ends of the long axis lift by `curl` (0..1), `lift` > 1 for a
+ hanging tag. Returns the local -> global mapping."""
+ p = int(34 + 16 * lift + 18 * curl)
+ A = np.pad(np.clip(art.a, 0, 1), p)
+ P = np.pad(art.rgb, ((p, p), (p, p), (0, 0)))
+ h, w = A.shape
+ YY, XX = np.mgrid[0:h, 0:w].astype(np.float32)
+ if art.h >= art.w:
+ v = (YY - h / 2) / (art.h / 2); u = (XX - w / 2) / (art.w / 2)
+ else:
+ v = (XX - w / 2) / (art.w / 2); u = (YY - h / 2) / (art.h / 2)
+ hm = curl * (11 * np.clip(-v, 0, None) ** 3 + 7 * np.clip(v, 0, None) ** 3 + 0.5 * u ** 2)
+ R = [_rotate(l, rot) for l in (A, P[..., 0], P[..., 1], P[..., 2], hm * A)]
+ A = np.clip(R[0], 0, 1)
+ col = np.clip(np.stack(R[1:4], -1) / np.maximum(A, 1e-4)[..., None], 0, 1)
+ Hm = R[4] / np.maximum(A, 1e-3) * (A > 0.01)
+ gsl, lsl = self._region(A.shape, cx, cy)
+ if gsl is None: return self.mapping(art, cx, cy, rot)
+ ax, ay = self.away
+ hn = np.clip(Hm / (Hm.max() + 1e-6), 0, 1)
+ cont = blur(shift(A, ax * 1.2, ay * 1.2), 1.6) * 0.26
+ soft = blur(shift(A, ax * 4 * lift, ay * 4 * lift), 3 + 4 * lift) * 0.20
+ up = blur(shift(A * smoothstep(0.15, 1.0, hn), ax * 14 * lift, ay * 14 * lift), 9 * lift + 4) * 0.22 * (curl > 0)
+ sh = (1 - (1 - cont) * (1 - soft) * (1 - up)) * shadow
+ n = height_normals(blur(Hm * A, 3))
+ lam = 1 + 1.7 * (n @ self.L - self.L[2])
+ ne = height_normals(blur(A, 0.8) * 1.2) # paper thickness at the cut edge
+ lam = lam * (1 + 0.6 * (ne @ self.L - self.L[2]))
+ reg = self._shade(self.img[gsl], sh[lsl])
+ Al = A[lsl][..., None]
+ reg = reg * (1 - Al) + np.clip(col * lam[..., None], 0, 1)[lsl] * Al
+ self.img[gsl] = np.clip(reg, 0, 1)
+ return self.mapping(art, cx, cy, rot)
+
+ # ------------------------------------------------------------ washi tape
+ def tape(self, cx, cy, length, rot=0.0, colour='#E8AC2C', width=44, pattern='stripe', ink='#FFFFFF',
+ alpha=0.8, seed=None):
+ """a strip of washi tape; pattern: stripe | dot | grid | plain; ink = pattern colour"""
+ rng = np.random.default_rng(self._seed() if seed is None else seed)
+ m = int(width * 0.4 + 14)
+ w, h = int(length + 2 * m), int(width + 2 * m)
+ n = max(4, int(width / 6))
+
+ def end(x0, sgn):
+ ys = np.linspace(m, m + width, 2 * n + 1)
+ tooth = np.where(np.arange(len(ys)) % 2 == 1, rng.uniform(2.5, 7.5, len(ys)), 0.0)
+ return [(x0 + sgn * (t + rng.normal(0, 1.0)), y) for t, y in zip(tooth, ys)]
+ left, right = end(m + 6, -1), end(m + length - 6, 1)
+ M = polygon_mask(h, w, right + left[::-1], ss=3)
+ YY, XX = np.mgrid[0:h, 0:w].astype(np.float32)
+ fib = np.asarray(Image.fromarray(rng.random((h // 2 + 2, max(2, w // 16))).astype(np.float32)).resize((w, h), Image.BICUBIC), np.float32)
+ fib = 0.94 + 0.09 * fib + 0.03 * (noise2d(h, w, 1.2, 1, int(rng.integers(1 << 30))) - 0.5)
+ if pattern == 'stripe':
+ q = (XX + YY) / (width * 0.42)
+ pm = smoothstep(0.42, 0.58, np.abs((q % 1) - 0.5) * 2)
+ pm = pm * 0.75
+ elif pattern == 'dot':
+ sp = width / 3.3
+ row = np.round(YY / sp); xo = (row % 2) * sp / 2
+ pm = np.clip(sp * 0.2 - np.hypot(XX - (np.round((XX - xo) / sp) * sp + xo), YY - row * sp) + 0.5, 0, 1) * 0.9
+ elif pattern == 'grid':
+ sp = width / 4.0
+ gx = np.abs(((XX + 0.5 * sp) % sp) - 0.5 * sp); gy = np.abs(((YY + 0.5 * sp) % sp) - 0.5 * sp)
+ pm = np.clip(1.4 - np.minimum(gx, gy), 0, 1) * 0.7
+ else:
+ pm = np.zeros((h, w), np.float32)
+ col = _c(colour)[None, None, :] * fib[..., None]
+ col = col * (1 - pm[..., None]) + _c(ink) * pm[..., None]
+ edge_in = np.minimum(XX - m, m + length - XX)
+ a = M * alpha * (0.93 + 0.07 * fib) * (0.82 + 0.18 * smoothstep(2, 10, edge_in)) # torn fibres thinner
+ R = [_rotate(l, rot) for l in (a, col[..., 0] * a, col[..., 1] * a, col[..., 2] * a)]
+ a = np.clip(R[0], 0, 1)
+ col = np.clip(np.stack(R[1:4], -1) / np.maximum(a, 1e-4)[..., None], 0, 1)
+ gsl, lsl = self._region(a.shape, cx, cy)
+ if gsl is None: return
+ ax, ay = self.away
+ sh = blur(shift(a, ax * 1.3, ay * 1.3), 1.3) * 0.25
+ reg = self._shade(self.img[gsl], sh[lsl])
+ al = a[lsl][..., None]
+ reg = reg * (1 - al) + al * col[lsl] * (0.55 + 0.45 * reg) # translucent: dark things show through
+ self.img[gsl] = np.clip(reg, 0, 1)
+
+ # ------------------------------------------------------------ twine
+ def twine(self, pts, width=4.2, colours=('#F4EEE2', '#D0402E'), shadow=0.32, drop=7, smooth=True):
+ """twisted baker's twine along a curve through pts (drawn on top; put tape over its end)"""
+ P = spline(pts, 30) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ x, y, ang, L = _resample(P, width * 0.42)
+ mg = int(width * 3 + drop + 12)
+ x0, y0 = int(np.floor(x.min())) - mg, int(np.floor(y.min())) - mg
+ x1, y1 = int(np.ceil(x.max())) + mg, int(np.ceil(y.max())) + mg
+ pw, ph = x1 - x0, y1 - y0
+ ss = 3
+ ci = Image.new('RGB', (pw * ss, ph * ss)); mi = Image.new('L', (pw * ss, ph * ss), 0)
+ dc, dm = ImageDraw.Draw(ci), ImageDraw.Draw(mi)
+ q = [((a - x0) * ss, (b - y0) * ss) for a, b in zip(x, y)]
+ dm.line(q, fill=255, width=int(width * ss), joint='curve')
+ for a, b in (q[0], q[-1]):
+ r = width * ss / 2; dm.ellipse((a - r, b - r, a + r, b + r), fill=255)
+ cols = [tuple(int(v * 255) for v in _c(c)) for c in colours]
+ t = np.linspace(0, 2 * np.pi, 10, endpoint=False)
+ for i, (a, b, th) in enumerate(zip(x, y, ang)):
+ ph_ = th + 0.95
+ ex, ey = np.cos(t) * width * 0.78, np.sin(t) * width * 0.30
+ px = (a - x0 + ex * np.cos(ph_) - ey * np.sin(ph_)) * ss
+ py = (b - y0 + ex * np.sin(ph_) + ey * np.cos(ph_)) * ss
+ dc.polygon(list(zip(px, py)), fill=cols[(i // 2) % len(cols)])
+ col = np.asarray(ci.resize((pw, ph), Image.BOX), np.float32) / 255
+ M = np.asarray(mi.resize((pw, ph), Image.BOX), np.float32) / 255
+ n = height_normals(blur(M, width * 0.3) * width * 0.9)
+ lam = 1 + 1.3 * (n @ self.L - self.L[2])
+ ax, ay = self.away
+ sd = blur(shift(M, ax * drop, ay * drop), 2.2) * shadow
+ cxm, cym = x0 + pw / 2, y0 + ph / 2
+ gsl, lsl = self._region(M.shape, cxm, cym)
+ if gsl is None: return
+ reg = self._shade(self.img[gsl], sd[lsl])
+ Ml = M[lsl][..., None]
+ reg = reg * (1 - Ml) + np.clip(col * lam[..., None], 0, 1)[lsl] * Ml
+ self.img[gsl] = np.clip(reg, 0, 1)
+
+ # ------------------------------------------------------------ rubber stamp
+ def stamp(self, cx, cy, r, ring='', centre='', sub='', colour='#D8412B', rot=0.0, strength=0.9,
+ font='sans_bold', cjk='cjk_sans', centre_size=None, seed=None):
+ """round rubber-stamp impression in translucent ink (multiplies with what is under it)"""
+ rng = np.random.default_rng(self._seed() if seed is None else seed)
+ S = int(r * 2 + 24); c = S / 2
+ a = Art(S, S)
+ m = np.maximum(a.ring(c, c, r * 0.965, r * 0.07), a.ring(c, c, r * 0.845, r * 0.02))
+ m = np.maximum(m, a.ring(c, c, r * 0.575, r * 0.022))
+ if ring:
+ size = r * 0.155
+ rt = r * 0.705
+ adv = np.array([measure(ch, size, font, 0, cjk) + size * 0.18 for ch in ring])
+ angs = np.cumsum(adv) - adv / 2
+ angs = angs / adv.sum() * 360.0
+ im = Image.new('L', (S, S), 0)
+ for ch, ag in zip(ring, angs):
+ if ch == ' ': continue
+ g = _glyph(ch, size, font, cjk).rotate(-ag, resample=Image.BICUBIC)
+ t = np.deg2rad(ag)
+ px, py = c + np.sin(t) * rt - g.width / 2, c - np.cos(t) * rt - g.height / 2
+ im.paste(255, (int(round(px)), int(round(py))), g)
+ m = np.maximum(m, np.asarray(im, np.float32) / 255)
+ if centre:
+ cs = centre_size or r * 0.34
+ m = np.maximum(m, a.text(centre, c, c - (r * 0.08 if sub else 0), cs, font, 'mm', stroke=max(1, int(cs * 0.03))))
+ if sub:
+ m = np.maximum(m, a.rrect(c - r * 0.3, c + r * 0.155, c + r * 0.3, c + r * 0.175, 0))
+ m = np.maximum(m, a.text(sub, c, c + r * 0.32, r * 0.115, font, 'mm', stroke=1, spacing=r * 0.03))
+ # ink: uneven pressure, paper tooth, pooled edges, slight bleed
+ s0 = int(rng.integers(1 << 30))
+ YY, XX = a.YY, a.XX
+ phi = rng.uniform(0, 2 * np.pi)
+ tilt = ((XX - c) * np.cos(phi) + (YY - c) * np.sin(phi)) / S
+ press = 0.58 + 0.6 * (noise2d(S, S, S * 0.35, 2, s0) - 0.5) - 1.1 * tilt
+ tooth = noise2d(S, S, 1.25, 2, s0 + 1)
+ cover = smoothstep(0.24, 0.56, 0.6 * tooth + 0.6 * press)
+ cover *= smoothstep(0.1, 0.24, noise2d(S, S, 2.2, 2, s0 + 3)) # pits where the rubber missed
+ pool = np.clip(m - blur(m, 1.1), 0, 1)
+ ink = m * cover * (0.78 + 0.22 * noise2d(S, S, 6, 2, s0 + 2)) + 0.35 * pool * cover
+ ink = np.clip(blur(ink, 0.55), 0, 1)
+ ink = np.clip(_rotate(ink, rot), 0, 1)
+ gsl, lsl = self._region(ink.shape, cx, cy)
+ if gsl is None: return
+ k = (ink[lsl] * strength)[..., None]
+ self.img[gsl] = self.img[gsl] * (1 - k * (1 - _c(colour)))
+
+ # ------------------------------------------------------------ ballpoint pen
+ def pen(self, pts, colour='#C9302A', width=3.0, smooth=True, strength=0.88, seed=None):
+ """a ballpoint line through pts (global coords): tapered ends, pressure wobble, rare skips"""
+ rng = np.random.default_rng(self._seed() if seed is None else seed)
+ P = spline(pts, 14) if smooth and len(pts) > 2 else np.asarray(pts, np.float32)
+ x, y, _, L = _resample(P, 0.6)
+ n = len(x)
+ t = np.linspace(0, 1, n)
+ press = (0.78 + 0.22 * fbm1d(n, 60, 3, int(rng.integers(1 << 30)))) * np.clip(np.minimum(t * L / 7, (1 - t) * L / 10), 0.25, 1) ** 0.5
+ gate = fbm1d(n, 25, 2, int(rng.integers(1 << 30))) > -0.62
+ mg = int(width * 2 + 4)
+ x0, y0 = int(np.floor(x.min())) - mg, int(np.floor(y.min())) - mg
+ pw, ph = int(np.ceil(x.max())) + mg - x0, int(np.ceil(y.max())) + mg - y0
+ ss = 3
+ im = Image.new('L', (pw * ss, ph * ss), 0); d = ImageDraw.Draw(im)
+ for a, b, pr, g in zip(x, y, press, gate):
+ rr = width / 2 * pr * ss
+ v = int(255 * (0.55 + 0.45 * pr) * (1 if g else 0.35))
+ X, Y = (a - x0) * ss, (b - y0) * ss
+ d.ellipse((X - rr, Y - rr, X + rr, Y + rr), fill=v)
+ M = np.asarray(im.resize((pw, ph), Image.BOX), np.float32) / 255
+ gsl, lsl = self._region(M.shape, x0 + pw / 2, y0 + ph / 2)
+ if gsl is None: return
+ k = (np.clip(M[lsl] * 1.15, 0, 1) * strength)[..., None]
+ self.img[gsl] = self.img[gsl] * (1 - k * (1 - _c(colour)))
+
+ # ------------------------------------------------------------ ready-made sheets
+ def lettering_art(self, parts, size, font='cjk_sans', weight=None, spacing=0.0, pad=None):
+ """bold sticker lettering: parts = [(text, colour), ...] set on one line"""
+ weight = max(1, int(size * 0.028)) if weight is None else weight
+ pad = size * 0.12 if pad is None else pad
+ ws = [measure(t, size, font, spacing) for t, _ in parts]
+ a = self.art(sum(ws) + 2 * pad + 2 * weight + spacing * (len(parts) - 1), size * 1.12 + 2 * pad)
+ x = pad + weight
+ for (t, col), wd in zip(parts, ws):
+ a.fill(a.text(t, x, a.h / 2, size, font, 'lm', stroke=weight, spacing=spacing), col)
+ x += wd + spacing
+ return a
+
+ def label_art(self, s, size, bg, fg, font='sans_bold', dot=None, spacing=0.0, padx=None, height=None, radius=None):
+ """pill-shaped label sticker (optional coloured dot before the text)"""
+ tw = measure(s, size, font, spacing)
+ padx = size * 0.75 if padx is None else padx
+ hh = size * 1.9 if height is None else height
+ dw = size * 0.85 if dot else 0
+ a = self.art(tw + 2 * padx + dw, hh)
+ a.fill(a.rrect(0, 0, a.w - 1, a.h - 1, hh / 2 if radius is None else radius), bg)
+ if dot:
+ a.fill(a.circle(padx + size * 0.22, hh / 2, size * 0.2), dot)
+ a.fill(a.text(s, padx + dw, hh / 2, size, font, 'lm', spacing=spacing), fg)
+ return a
+
+ def badge_art(self, r, colour, big, top='', bottom='', ink='#FBF3E4', scallops=24, depth=0.035,
+ big_size=None, font='sans_bold', light=None):
+ """round sale badge with a scalloped rim, a dotted inner ring and three lines of text"""
+ S = int(2 * r + 6); c = S / 2
+ a = self.art(S, S)
+ th = np.arctan2(a.YY - c, a.XX - c); rr = np.hypot(a.XX - c, a.YY - c)
+ R = r * (1 - depth + depth * np.cos(scallops * th))
+ m = np.clip(R - rr + 0.5, 0, 1)
+ lc = light or tuple(np.clip(_c(colour) * 1.12 + 0.04, 0, 1))
+ a.radial(m, lc, colour, c - r * 0.35, c - r * 0.4, r * 1.5)
+ dots = np.zeros((S, S), np.float32)
+ for t in np.linspace(0, 2 * np.pi, 44, endpoint=False):
+ dots = np.maximum(dots, a.circle(c + np.cos(t) * r * 0.82, c + np.sin(t) * r * 0.82, r * 0.016))
+ a.fill(dots, ink, 0.9, clip=True)
+ a.fill(a.text(big, c, c + r * 0.02, big_size or r * 0.44, font, 'mm', stroke=max(1, int(r * 0.012))), ink)
+ if top:
+ a.fill(a.text(top, c, c - r * 0.42, r * 0.13, font, 'mm', spacing=r * 0.035), ink)
+ if bottom:
+ a.fill(a.text(bottom, c, c + r * 0.45, r * 0.15, font, 'mm', spacing=r * 0.01), ink)
+ return a
+
+ def tag_art(self, w, h, colour='#D9C7A3', grommet='#C9A55C', clip=None, hole_r=8.0, kind='kraft'):
+ """card price tag: clipped top corners, a hole near the top with a metal grommet; .hole = (x, y)"""
+ a = self.art(w, h)
+ c = clip or w * 0.28
+ m = a.poly([(c, 1), (w - 1 - c, 1), (w - 1, c), (w - 1, h - 1), (1, h - 1), (1, c)])
+ m = smoothstep(0.3, 0.7, blur(m, 2.2))
+ a.fill(m, colour)
+ a.texture(kind, 1.0)
+ hx, hy = w / 2, c * 0.92
+ ro = hole_r * 1.95
+ rim = np.clip(a.circle(hx, hy, ro) - a.circle(hx, hy, hole_r), 0, 1)
+ lit = np.clip(-((a.XX - hx) * self.L[0] + (a.YY - hy) * self.L[1]) / ro, -1, 1)
+ rr = np.hypot(a.XX - hx, a.YY - hy)
+ inner = np.clip(1 - (rr - hole_r) / (ro - hole_r), 0, 1)
+ g = 0.82 + 0.35 * lit * (1 - inner) - 0.35 * lit * inner ** 3
+ gcol = np.clip(_c(grommet)[None, None, :] * g[..., None], 0, 1)
+ a.fill(np.clip(blur(rim, 1.2) * 0.5 * (1 - rim), 0, 1), '#5a4a30', 0.6, clip=True) # the rolled lip's shadow on the card
+ a._over(rim, gcol, clip=False)
+ a.cut(a.circle(hx, hy, hole_r))
+ a.hole = (hx, hy)
+ return a
+
+ # ------------------------------------------------------------ output
+ def composite(self, vignette=0.16):
+ g = np.exp(-(((self.XX - self.W * 0.3) / (self.W * 0.7)) ** 2 + ((self.YY - self.H * 0.2) / (self.H * 0.9)) ** 2))
+ r = np.hypot((self.XX - self.W / 2) / self.W, (self.YY - self.H / 2) / self.H)
+ img = self.img * (0.95 + 0.07 * g)[..., None] * (1 - vignette * r ** 2 * 2.2)[..., None]
+ return Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8))
+
+ def stage(self, name):
+ self.stages.append((name, self.composite()))
+
+ def save(self, path, stages_dir=None):
+ img = self.composite(); img.save(path)
+ if stages_dir:
+ import os
+ os.makedirs(stages_dir, exist_ok=True)
+ for i, (name, im) in enumerate(self.stages):
+ im.save(f"{stages_dir}/{i:02d}_{name}.png")
+ img.save(f"{stages_dir}/{len(self.stages):02d}_final.png")
+ return img