Claude paints with code: a Claude Code skill for procedural illustration in 83 styles, from ink wash (水墨), watercolour and ukiyo-e to stained glass, Roman mosaic, Art Deco, shadow puppets, pastel UI, sketchbook doodles, spot illustrations, grainy picture books, dreamy hills, sunlit greenery. No image model: numpy + Pillow on a CPU, draw-on GIFs.
Python agent-skillsanimechinese-paintingclaudeclaude-codeclaude-skillscolored-pencilcreative-codingcross-stitcheditorial-illustrationgenerative-artink-wash-paintingoil-paintingpaper-collagepixel-artprocedural-generationrisographshanshuiukiyo-ewatercolor
Add Obsidian UI, Canvas Board and Flexoki Paper styles (73 total)
cloveric9f42f175b216
diff --git a/README.md b/README.mdindex 2274966..c8fb52e 100644--- a/README.md+++ b/README.md@@ -1,7 +1,7 @@# Claude Drawing · Claude 绘图-**Claude paints with code — no image model.** Seventy styles, from ink wash and impasto oil to clay, cyanotype, stained glass, a Roman mosaic, Delft tiles, a cyberpunk street, a ray-traced ball pit, low-poly 3D, a thermal camera, an X-ray, a VHS tape, a synthwave sunset, a pastel product-film UI, an answer sheet marked in red, a lamp-lit shadow-puppet play, pen-and-wash sketch cards, retro gouache picture-book portraits, a soft-blue picture-book spread, a Jiangnan water garden in spring, a dry-brushed mid-century poster, a dusk picture-book page where the sky turns to stars and a hatched night print of lava meeting the sea.-**不用生图模型,Claude 用代码一笔一笔作画。** 七十种画风,从水墨、油画到黏土、蓝晒、彩色玻璃花窗、罗马马赛克、代尔夫特蓝瓷砖、赛博朋克、光线追踪的小球海、低多边形 3D、热成像、X 光片、VHS 录像带、Synthwave 落日、产品发布片式的粉彩界面、红笔批改的答题卡、油灯下的皮影戏、钢笔淡彩的速写小卡、复古水粉的绘本大头像、蓝调绘本的雨天跨页、江南园林的春水园景、干刷色块的 mid-century 海报、暮色微缩绘本里转入星空的黄昏和排线夜景里流进海里的熔岩。+**Claude paints with code — no image model.** Seventy-three styles, from ink wash and impasto oil to clay, cyanotype, stained glass, a Roman mosaic, Delft tiles, a cyberpunk street, a ray-traced ball pit, low-poly 3D, a thermal camera, an X-ray, a VHS tape, a synthwave sunset, a pastel product-film UI, an answer sheet marked in red, a lamp-lit shadow-puppet play, pen-and-wash sketch cards, retro gouache picture-book portraits, a soft-blue picture-book spread, a Jiangnan water garden in spring, a dry-brushed mid-century poster, a dusk picture-book page where the sky turns to stars, a hatched night print of lava meeting the sea, a dark note-taking app rendering its diagram, an infinite canvas of cards and a five-diagram sheet on warm Flexoki paper.+**不用生图模型,Claude 用代码一笔一笔作画。** 七十三种画风,从水墨、油画到黏土、蓝晒、彩色玻璃花窗、罗马马赛克、代尔夫特蓝瓷砖、赛博朋克、光线追踪的小球海、低多边形 3D、热成像、X 光片、VHS 录像带、Synthwave 落日、产品发布片式的粉彩界面、红笔批改的答题卡、油灯下的皮影戏、钢笔淡彩的速写小卡、复古水粉的绘本大头像、蓝调绘本的雨天跨页、江南园林的春水园景、干刷色块的 mid-century 海报、暮色微缩绘本里转入星空的黄昏、排线夜景里流进海里的熔岩、深色笔记应用里渲染出的流程图、卡片铺开的无限白板和 Flexoki 暖纸上的五图图解。[English](#english) · [中文](#中文)@@ -54,6 +54,8 @@|  |  |  || **Dry-brush blocks · 干刷色块** | **Twilight storybook · 暮色微缩绘本** | **Hatched nocturne · 排线夜景** ||  |  |  |+| **Obsidian UI · 笔记应用界面** | **Canvas board · 白板卡片** | **Flexoki paper · Flexoki 纸面** |+|  |  |  |### Gallery · 画廊@@ -61,76 +63,78 @@|---|---|| **八万四千法门** · *Many Paths, One Summit*<br><sub>Ink wash · 水墨</sub> | **月印万川** · *One Moon in Ten Thousand Rivers*<br><sub>Ink wash · 水墨</sub> || <img src="examples/bawansiqian.jpg" width="100%"> | <img src="examples/moon_river.jpg" width="100%"> |-| **秋日湖畔** · *Autumn Lake*<br><sub>Watercolour · 水彩</sub> | **水彩底纹** · *Watercolour Washes*<br><sub>Watercolour · 水彩 — a background for explainer videos · 讲解视频的背景</sub> |-| <img src="examples/watercolor_autumn.jpg" width="100%"> | <img src="examples/watercolor_washes.jpg" width="100%"> |-| **热气球小镇** · *Balloon Day*<br><sub>Paper collage · 剪纸拼贴</sub> | **午后甜点** · *Afternoon Dessert*<br><sub>Coloured pencil · 韩国彩铅</sub> |-| <img src="examples/papercut_balloons.jpg" width="100%"> | <img src="examples/colorpencil_dessert.jpg" width="100%"> |-| **夏空** · *Summer Sky*<br><sub>Anime · 日本动漫</sub> | **灵感生长** · *Growing Ideas*<br><sub>Editorial · 编辑风手绘</sub> |-| <img src="examples/anime_summer.jpg" width="100%"> | <img src="examples/editorial_ideas.jpg" width="100%"> |-| **麦田星空** · *Swirling Sky over the Wheat Field*<br><sub>Impasto oil · 油画厚涂</sub> | **富士曙** · *Fuji at Dawn*<br><sub>Ukiyo-e · 浮世绘</sub> |-| <img src="examples/oil_wheatfield.jpg" width="100%"> | <img src="examples/ukiyoe_fuji.jpg" width="100%"> |-| **雨夜咖啡店** · *Rainy Night Cafe*<br><sub>Pixel art · 像素风</sub> | **灯塔岛** · *Lighthouse Island*<br><sub>Stop-motion clay · 黏土定格</sub> |-| <img src="examples/pixel_rainy_cafe.png" width="100%"> | <img src="examples/clay_lighthouse.jpg" width="100%"> |-| **蓝晒植物** · *Sun-Print Botanicals*<br><sub>Cyanotype · 蓝晒</sub> | **家** · *Home Sampler*<br><sub>Cross-stitch · 十字绣</sub> |-| <img src="examples/cyanotype_botanicals.jpg" width="100%"> | <img src="examples/stitch_sampler.jpg" width="100%"> |-| **Aurora 64 收音机** · *Aurora 64 Radio*<br><sub>Vintage instrument panel · 复古仪器面板</sub> | **周末市集** · *Weekend Market*<br><sub>Sticker collage × receipt · 贴纸拼贴 · 小票</sub> |-| <img src="examples/panel_radio.jpg" width="100%"> | <img src="examples/sticker_market.jpg" width="100%"> |-| **咖啡萃取实验** · *Coffee Brewing Experiment*<br><sub>Lab notebook × stickers · 实验笔记本 · 贴纸</sub> | **为什么天空是蓝的** · *Why Is the Sky Blue?*<br><sub>Chalkboard · 黑板板书</sub> |-| <img src="examples/notebook_brewing.jpg" width="100%"> | <img src="examples/chalk_lesson.jpg" width="100%"> |-| **霓虹不夜城** · *Neon District*<br><sub>Cyberpunk · 赛博朋克</sub> | **早安吐司** · *Good Morning, Toast*<br><sub>Hand-drawn cartoon · 卡通手绘</sub> |-| <img src="examples/cyberpunk_neon_street.jpg" width="100%"> | <img src="examples/cartoon_toaster.jpg" width="100%"> |-| **岛上的气象站** · *Island Weather Station*<br><sub>Isometric 2.5D · 等轴 2.5D</sub> | **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> |-| <img src="examples/isometric_weather_island.jpg" width="100%"> | <img src="examples/lineart_paper_plane.jpg" width="100%"> |-| **浮出** · *Rise*<br><sub>Soft 3D · 柔光 3D</sub> | **一滴水的旅程** · *A Drop's Round Trip*<br><sub>Shape morph · 形变动画</sub> |-| <img src="examples/soft3d_rise.jpg" width="100%"> | <img src="examples/morph_water_cycle.jpg" width="100%"> |-| **好奇心周刊 · 拆开看看** · *Curiosity Weekly · Take It Apart*<br><sub>Newspaper collage · 报刊拼贴</sub> | **晨间计划** · *Morning Plan*<br><sub>Aurora glassmorphism · 弥散玻璃</sub> |-| <img src="examples/newscollage_curiosity.jpg" width="100%"> | <img src="examples/aurora_morning.jpg" width="100%"> |-| **形与色** · *Form & Colour*<br><sub>Bauhaus geometric · 包豪斯几何</sub> | **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> |-| <img src="examples/bauhaus_form_colour.jpg" width="100%"> | <img src="examples/synthwave_coastline.jpg" width="100%"> |-| **草莓杯垫** · *Strawberry Coaster*<br><sub>Perler beads · 拼豆</sub> | **迁徙季** · *Migration Season*<br><sub>Petroglyph · 岩画</sub> |-| <img src="examples/perler_strawberry_coaster.jpg" width="100%"> | <img src="examples/petroglyph_migration.jpg" width="100%"> |-| **尼罗河丰收** · *Harvest on the Nile*<br><sub>Egyptian tomb painting · 古埃及墓室壁画</sub> | **港口渔获** · *The Day's Catch*<br><sub>Roman mosaic · 罗马马赛克</sub> |-| <img src="examples/tomb_harvest.jpg" width="100%"> | <img src="examples/mosaic_harbor.jpg" width="100%"> |-| **四季之窗** · *Window of the Seasons*<br><sub>Stained glass · 彩色玻璃花窗</sub> | **星辰之书** · *Liber Stellarum*<br><sub>Illuminated manuscript · 泥金手抄本</sub> |-| <img src="examples/stainedglass_seasons.jpg" width="100%"> | <img src="examples/illuminated_starchart.jpg" width="100%"> |-| **扑翼机** · *The Ornithopter*<br><sub>Leonardo codex · 达·芬奇手稿</sub> | **剪影小像** · *Shades of the Wren Household*<br><sub>Silhouette · 剪影</sub> |-| <img src="examples/codex_ornithopter.jpg" width="100%"> | <img src="examples/silhouette_family.jpg" width="100%"> |-| **马戏团来了** · *The Circus Is Coming*<br><sub>Letterpress poster · 凸版印刷海报</sub> | **无线电** · *Radio*<br><sub>Soviet constructivism · 苏联构成主义</sub> |-| <img src="examples/letterpress_circus.jpg" width="100%"> | <img src="examples/constructivism_radio.jpg" width="100%"> |-| **夜行快车** · *Night Express*<br><sub>Art Deco · 装饰艺术</sub> | **火箭小队** · *Rocket Squad*<br><sub>Golden-age comic · 黄金时代漫画</sub> |-| <img src="examples/artdeco_express.jpg" width="100%"> | <img src="examples/comic_rocket.jpg" width="100%"> |-| **猫的六种心情** · *Six Moods of a Cat*<br><sub>Pop silkscreen · 波普丝网</sub> | **发射记录** · *Liftoff Trace*<br><sub>ASCII art (line printer) · ASCII 字符画(行式打印机)</sub> |-| <img src="examples/popart_cat_moods.jpg" width="100%"> | <img src="examples/lineprinter_launch.jpg" width="100%"> |-| **峡谷飞行** · *Canyon Run*<br><sub>Low poly · 低多边形</sub> | **放风筝** · *Hold On*<br><sub>Stencil graffiti · 喷漆模板涂鸦</sub> |-| <img src="examples/lowpoly_canyon.jpg" width="100%"> | <img src="examples/stencil_kite.jpg" width="100%"> |-| **三晚露营** · *Three Nights Out*<br><sub>Embroidered patches · 刺绣徽章</sub> | **灯塔剖面** · *Halvard Rock Light*<br><sub>Blueprint · 蓝图工程图</sub> |-| <img src="examples/patch_camping.jpg" width="100%"> | <img src="examples/blueprint_lighthouse.jpg" width="100%"> |-| **我的周末** · *My Weekend*<br><sub>Children's crayon · 儿童蜡笔画</sub> | **今天带伞吗** · *Bring an Umbrella?*<br><sub>Green-screen CRT terminal · 绿屏终端(荧光字符画)</sub> |-| <img src="examples/crayon_picnic.jpg" width="100%"> | <img src="examples/crt_weather.jpg" width="100%"> |-| **厨房里的温度** · *Kitchen Heat Map*<br><sub>Thermal camera · 热成像</sub> | **一阵风** · *The Gust*<br><sub>Delft tiles · 代尔夫特蓝瓷砖</sub> |-| <img src="examples/thermal_kitchen.jpg" width="100%"> | <img src="examples/delft_canal.jpg" width="100%"> |-| **篝火旁的岩洞** · *The Hunt by the Fire*<br><sub>Cave painting · 洞穴壁画</sub> | **窗台花园** · *Windowsill Garden*<br><sub>1-bit paint program · 1-bit 早期画图软件</sub> |-| <img src="examples/cave_hunt.jpg" width="100%"> | <img src="examples/macpaint_garden.jpg" width="100%"> |-| **赛跑与赛车** · *Games on a Vase*<br><sub>Greek black-figure vase · 古希腊黑绘陶瓶</sub> | **老街角的自行车** · *The Bread Run*<br><sub>Graphite pencil · 铅笔素描</sub> |-| <img src="examples/blackfigure_games.jpg" width="100%"> | <img src="examples/graphite_bicycle.jpg" width="100%"> |-| **行李安检** · *Security Check*<br><sub>X-ray · X 光片</sub> | **早晨的闹钟** · *Seven O'Clock*<br><sub>1930s rubber hose · 1930 年代黑白橡皮管动画</sub> |-| <img src="examples/xray_luggage.jpg" width="100%"> | <img src="examples/rubberhose_morning.jpg" width="100%"> |-| **雪夜归途** · *Homeward, First Snow*<br><sub>Linocut · 黑白麻胶版画</sub> | **吹蜡烛** · *Blow Out the Candles*<br><sub>VHS home video · VHS 家庭录像</sub> |-| <img src="examples/linocut_snowy_village.jpg" width="100%"> | <img src="examples/vhs_birthday.jpg" width="100%"> |-| **山间夜营** · *Night Camp*<br><sub>Flat vector · 扁平矢量</sub> | **小橡果的秋天** · *An Acorn's Autumn*<br><sub>Storybook animation · 绘本角色动画</sub> |-| <img src="examples/flatvector_night_camp.jpg" width="100%"> | <img src="examples/storybook_acorn.jpg" width="100%"> |-| **蛇梯棋大冒险** · *Snakes & Ladders, Round 7*<br><sub>Ballpoint doodle · 圆珠笔涂鸦</sub> | **海港步行图** · *Larkhaven on Foot*<br><sub>Overlay sheets · 描图纸叠层</sub> |-| <img src="examples/ballpoint_board_game.jpg" width="100%"> | <img src="examples/overlay_city_map.jpg" width="100%"> |-| **出发前,再查一遍行李** · *Pack Check*<br><sub>Pastel UI · 粉彩界面</sub> | **数学单元测验** · *Unit Test, Graded*<br><sub>Exam grading · 阅卷批改</sub> |-| <img src="examples/pastelui_packing.jpg" width="100%"> | <img src="examples/grading_math_quiz.jpg" width="100%"> |-| **蹴鞠** · *Cuju by Lamplight*<br><sub>Shadow puppetry · 皮影戏</sub> | **街角速写** · *Sketchbook Neighbours*<br><sub>Pen & wash · 钢笔淡彩</sub> |-| <img src="examples/shadowpuppet_cuju.jpg" width="100%"> | <img src="examples/penwash_neighbours.jpg" width="100%"> |-| **雨天三人像** · *Rainy-Day Portraits*<br><sub>Retro gouache · 复古水粉</sub> | **借伞** · *The Shared Umbrella*<br><sub>Blue picture book · 蓝调绘本</sub> |-| <img src="examples/gouache_rainy_day.jpg" width="100%"> | <img src="examples/bluebook_shared_umbrella.jpg" width="100%"> |-| **春水园林** · *Spring Water Garden*<br><sub>Jiangnan garden · 江南园林</sub> | **面馆** · *Noodle Counter*<br><sub>Dry-brush blocks · 干刷色块</sub> |-| <img src="examples/jiangnan_spring_water.jpg" width="100%"> | <img src="examples/drybrush_noodle_counter.jpg" width="100%"> |-| **夜的边上** · *The Kite at the Edge of Night*<br><sub>Twilight storybook · 暮色微缩绘本</sub> | **熔岩入海** · *Lava Meets the Sea*<br><sub>Hatched nocturne · 排线夜景</sub> |-| <img src="examples/twilight_paper_kite.jpg" width="100%"> | <img src="examples/nocturne_lava_sea.jpg" width="100%"> |+| **秋日湖畔** · *Autumn Lake*<br><sub>Watercolour · 水彩</sub> | **热气球小镇** · *Balloon Day*<br><sub>Paper collage · 剪纸拼贴</sub> |+| <img src="examples/watercolor_autumn.jpg" width="100%"> | <img src="examples/papercut_balloons.jpg" width="100%"> |+| **午后甜点** · *Afternoon Dessert*<br><sub>Coloured pencil · 韩国彩铅</sub> | **夏空** · *Summer Sky*<br><sub>Anime · 日本动漫</sub> |+| <img src="examples/colorpencil_dessert.jpg" width="100%"> | <img src="examples/anime_summer.jpg" width="100%"> |+| **灵感生长** · *Growing Ideas*<br><sub>Editorial · 编辑风手绘</sub> | **麦田星空** · *Swirling Sky over the Wheat Field*<br><sub>Impasto oil · 油画厚涂</sub> |+| <img src="examples/editorial_ideas.jpg" width="100%"> | <img src="examples/oil_wheatfield.jpg" width="100%"> |+| **富士曙** · *Fuji at Dawn*<br><sub>Ukiyo-e · 浮世绘</sub> | **雨夜咖啡店** · *Rainy Night Cafe*<br><sub>Pixel art · 像素风</sub> |+| <img src="examples/ukiyoe_fuji.jpg" width="100%"> | <img src="examples/pixel_rainy_cafe.png" width="100%"> |+| **灯塔岛** · *Lighthouse Island*<br><sub>Stop-motion clay · 黏土定格</sub> | **蓝晒植物** · *Sun-Print Botanicals*<br><sub>Cyanotype · 蓝晒</sub> |+| <img src="examples/clay_lighthouse.jpg" width="100%"> | <img src="examples/cyanotype_botanicals.jpg" width="100%"> |+| **家** · *Home Sampler*<br><sub>Cross-stitch · 十字绣</sub> | **Aurora 64 收音机** · *Aurora 64 Radio*<br><sub>Vintage instrument panel · 复古仪器面板</sub> |+| <img src="examples/stitch_sampler.jpg" width="100%"> | <img src="examples/panel_radio.jpg" width="100%"> |+| **周末市集** · *Weekend Market*<br><sub>Sticker collage × receipt · 贴纸拼贴 · 小票</sub> | **咖啡萃取实验** · *Coffee Brewing Experiment*<br><sub>Lab notebook × stickers · 实验笔记本 · 贴纸</sub> |+| <img src="examples/sticker_market.jpg" width="100%"> | <img src="examples/notebook_brewing.jpg" width="100%"> |+| **为什么天空是蓝的** · *Why Is the Sky Blue?*<br><sub>Chalkboard · 黑板板书</sub> | **霓虹不夜城** · *Neon District*<br><sub>Cyberpunk · 赛博朋克</sub> |+| <img src="examples/chalk_lesson.jpg" width="100%"> | <img src="examples/cyberpunk_neon_street.jpg" width="100%"> |+| **早安吐司** · *Good Morning, Toast*<br><sub>Hand-drawn cartoon · 卡通手绘</sub> | **岛上的气象站** · *Island Weather Station*<br><sub>Isometric 2.5D · 等轴 2.5D</sub> |+| <img src="examples/cartoon_toaster.jpg" width="100%"> | <img src="examples/isometric_weather_island.jpg" width="100%"> |+| **从这扇窗到那扇窗** · *From Window to Window*<br><sub>Continuous line art · 单线画</sub> | **浮出** · *Rise*<br><sub>Soft 3D · 柔光 3D</sub> |+| <img src="examples/lineart_paper_plane.jpg" width="100%"> | <img src="examples/soft3d_rise.jpg" width="100%"> |+| **一滴水的旅程** · *A Drop's Round Trip*<br><sub>Shape morph · 形变动画</sub> | **好奇心周刊 · 拆开看看** · *Curiosity Weekly · Take It Apart*<br><sub>Newspaper collage · 报刊拼贴</sub> |+| <img src="examples/morph_water_cycle.jpg" width="100%"> | <img src="examples/newscollage_curiosity.jpg" width="100%"> |+| **晨间计划** · *Morning Plan*<br><sub>Aurora glassmorphism · 弥散玻璃</sub> | **形与色** · *Form & Colour*<br><sub>Bauhaus geometric · 包豪斯几何</sub> |+| <img src="examples/aurora_morning.jpg" width="100%"> | <img src="examples/bauhaus_form_colour.jpg" width="100%"> |+| **海岸线 1987** · *Coastline 1987*<br><sub>Retro synthwave · 复古 Synthwave</sub> | **草莓杯垫** · *Strawberry Coaster*<br><sub>Perler beads · 拼豆</sub> |+| <img src="examples/synthwave_coastline.jpg" width="100%"> | <img src="examples/perler_strawberry_coaster.jpg" width="100%"> |+| **迁徙季** · *Migration Season*<br><sub>Petroglyph · 岩画</sub> | **尼罗河丰收** · *Harvest on the Nile*<br><sub>Egyptian tomb painting · 古埃及墓室壁画</sub> |+| <img src="examples/petroglyph_migration.jpg" width="100%"> | <img src="examples/tomb_harvest.jpg" width="100%"> |+| **港口渔获** · *The Day's Catch*<br><sub>Roman mosaic · 罗马马赛克</sub> | **四季之窗** · *Window of the Seasons*<br><sub>Stained glass · 彩色玻璃花窗</sub> |+| <img src="examples/mosaic_harbor.jpg" width="100%"> | <img src="examples/stainedglass_seasons.jpg" width="100%"> |+| **星辰之书** · *Liber Stellarum*<br><sub>Illuminated manuscript · 泥金手抄本</sub> | **扑翼机** · *The Ornithopter*<br><sub>Leonardo codex · 达·芬奇手稿</sub> |+| <img src="examples/illuminated_starchart.jpg" width="100%"> | <img src="examples/codex_ornithopter.jpg" width="100%"> |+| **剪影小像** · *Shades of the Wren Household*<br><sub>Silhouette · 剪影</sub> | **马戏团来了** · *The Circus Is Coming*<br><sub>Letterpress poster · 凸版印刷海报</sub> |+| <img src="examples/silhouette_family.jpg" width="100%"> | <img src="examples/letterpress_circus.jpg" width="100%"> |+| **无线电** · *Radio*<br><sub>Soviet constructivism · 苏联构成主义</sub> | **夜行快车** · *Night Express*<br><sub>Art Deco · 装饰艺术</sub> |+| <img src="examples/constructivism_radio.jpg" width="100%"> | <img src="examples/artdeco_express.jpg" width="100%"> |+| **火箭小队** · *Rocket Squad*<br><sub>Golden-age comic · 黄金时代漫画</sub> | **猫的六种心情** · *Six Moods of a Cat*<br><sub>Pop silkscreen · 波普丝网</sub> |+| <img src="examples/comic_rocket.jpg" width="100%"> | <img src="examples/popart_cat_moods.jpg" width="100%"> |+| **发射记录** · *Liftoff Trace*<br><sub>ASCII art (line printer) · ASCII 字符画(行式打印机)</sub> | **峡谷飞行** · *Canyon Run*<br><sub>Low poly · 低多边形</sub> |+| <img src="examples/lineprinter_launch.jpg" width="100%"> | <img src="examples/lowpoly_canyon.jpg" width="100%"> |+| **放风筝** · *Hold On*<br><sub>Stencil graffiti · 喷漆模板涂鸦</sub> | **三晚露营** · *Three Nights Out*<br><sub>Embroidered patches · 刺绣徽章</sub> |+| <img src="examples/stencil_kite.jpg" width="100%"> | <img src="examples/patch_camping.jpg" width="100%"> |+| **灯塔剖面** · *Halvard Rock Light*<br><sub>Blueprint · 蓝图工程图</sub> | **我的周末** · *My Weekend*<br><sub>Children's crayon · 儿童蜡笔画</sub> |+| <img src="examples/blueprint_lighthouse.jpg" width="100%"> | <img src="examples/crayon_picnic.jpg" width="100%"> |+| **今天带伞吗** · *Bring an Umbrella?*<br><sub>Green-screen CRT terminal · 绿屏终端(荧光字符画)</sub> | **厨房里的温度** · *Kitchen Heat Map*<br><sub>Thermal camera · 热成像</sub> |+| <img src="examples/crt_weather.jpg" width="100%"> | <img src="examples/thermal_kitchen.jpg" width="100%"> |+| **一阵风** · *The Gust*<br><sub>Delft tiles · 代尔夫特蓝瓷砖</sub> | **篝火旁的岩洞** · *The Hunt by the Fire*<br><sub>Cave painting · 洞穴壁画</sub> |+| <img src="examples/delft_canal.jpg" width="100%"> | <img src="examples/cave_hunt.jpg" width="100%"> |+| **窗台花园** · *Windowsill Garden*<br><sub>1-bit paint program · 1-bit 早期画图软件</sub> | **赛跑与赛车** · *Games on a Vase*<br><sub>Greek black-figure vase · 古希腊黑绘陶瓶</sub> |+| <img src="examples/macpaint_garden.jpg" width="100%"> | <img src="examples/blackfigure_games.jpg" width="100%"> |+| **老街角的自行车** · *The Bread Run*<br><sub>Graphite pencil · 铅笔素描</sub> | **行李安检** · *Security Check*<br><sub>X-ray · X 光片</sub> |+| <img src="examples/graphite_bicycle.jpg" width="100%"> | <img src="examples/xray_luggage.jpg" width="100%"> |+| **早晨的闹钟** · *Seven O'Clock*<br><sub>1930s rubber hose · 1930 年代黑白橡皮管动画</sub> | **雪夜归途** · *Homeward, First Snow*<br><sub>Linocut · 黑白麻胶版画</sub> |+| <img src="examples/rubberhose_morning.jpg" width="100%"> | <img src="examples/linocut_snowy_village.jpg" width="100%"> |+| **吹蜡烛** · *Blow Out the Candles*<br><sub>VHS home video · VHS 家庭录像</sub> | **山间夜营** · *Night Camp*<br><sub>Flat vector · 扁平矢量</sub> |+| <img src="examples/vhs_birthday.jpg" width="100%"> | <img src="examples/flatvector_night_camp.jpg" width="100%"> |+| **小橡果的秋天** · *An Acorn's Autumn*<br><sub>Storybook animation · 绘本角色动画</sub> | **蛇梯棋大冒险** · *Snakes & Ladders, Round 7*<br><sub>Ballpoint doodle · 圆珠笔涂鸦</sub> |+| <img src="examples/storybook_acorn.jpg" width="100%"> | <img src="examples/ballpoint_board_game.jpg" width="100%"> |+| **海港步行图** · *Larkhaven on Foot*<br><sub>Overlay sheets · 描图纸叠层</sub> | **出发前,再查一遍行李** · *Pack Check*<br><sub>Pastel UI · 粉彩界面</sub> |+| <img src="examples/overlay_city_map.jpg" width="100%"> | <img src="examples/pastelui_packing.jpg" width="100%"> |+| **数学单元测验** · *Unit Test, Graded*<br><sub>Exam grading · 阅卷批改</sub> | **蹴鞠** · *Cuju by Lamplight*<br><sub>Shadow puppetry · 皮影戏</sub> |+| <img src="examples/grading_math_quiz.jpg" width="100%"> | <img src="examples/shadowpuppet_cuju.jpg" width="100%"> |+| **街角速写** · *Sketchbook Neighbours*<br><sub>Pen & wash · 钢笔淡彩</sub> | **雨天三人像** · *Rainy-Day Portraits*<br><sub>Retro gouache · 复古水粉</sub> |+| <img src="examples/penwash_neighbours.jpg" width="100%"> | <img src="examples/gouache_rainy_day.jpg" width="100%"> |+| **借伞** · *The Shared Umbrella*<br><sub>Blue picture book · 蓝调绘本</sub> | **春水园林** · *Spring Water Garden*<br><sub>Jiangnan garden · 江南园林</sub> |+| <img src="examples/bluebook_shared_umbrella.jpg" width="100%"> | <img src="examples/jiangnan_spring_water.jpg" width="100%"> |+| **面馆** · *Noodle Counter*<br><sub>Dry-brush blocks · 干刷色块</sub> | **夜的边上** · *The Kite at the Edge of Night*<br><sub>Twilight storybook · 暮色微缩绘本</sub> |+| <img src="examples/drybrush_noodle_counter.jpg" width="100%"> | <img src="examples/twilight_paper_kite.jpg" width="100%"> |+| **熔岩入海** · *Lava Meets the Sea*<br><sub>Hatched nocturne · 排线夜景</sub> | **小王子 · 读书笔记** · *Reading Notes*<br><sub>Obsidian UI · 笔记应用界面</sub> |+| <img src="examples/nocturne_lava_sea.jpg" width="100%"> | <img src="examples/obsidianui_reading_notes.jpg" width="100%"> |+| **搬家计划** · *Moving Plan*<br><sub>Canvas board · 白板卡片</sub> | **一杯手冲咖啡** · *Pour-over, in Five Diagrams*<br><sub>Flexoki paper · Flexoki 纸面</sub> |+| <img src="examples/canvasboard_moving_plan.jpg" width="100%"> | <img src="examples/flexoki_pour_over.jpg" width="100%"> |Every mark above is computed: paper fibres, ink washes and mist, dry-brush strokes, pigment granulation and blooms, torn-paper edges, pencil wax on paper tooth, cel-shaded clouds, risograph grain and halftones, lit impasto relief, woodblock grain and bokashi, dithered pixels, plasticine lit like a film set, sunlight through leaves on Prussian blue, twisted thread on Aida cloth, machined knobs behind a backlit dial, die-cut vinyl with a laminate gloss, streaky thermal print, graphite catching the tooth of graph paper, highlighter pooling at the start of a swipe, chalk dust settling under half-erased lessons, rain-lit neon glass mirrored in a wet street, a blue-pencil rough under boiling brush ink, an island ray-traced under one soft sun, a single unbroken gold line, candy balls with softbox glints, one outline morphing through six shapes, halftone photos cut out with scissors, frosted glass blurring the real pixels behind it, screen-printed primaries out of register, a slit sun sinking behind a neon grid played off tape, hollow fuse beads on a pegboard melting together under an iron, pits knocked through desert varnish, a red grid showing through flaking plaster, stones laid row by row along an outline, daylight through leaded glass, burnished gold that mirrors the room, left-handed hatching in iron-gall ink, black paper cut with scissors, wood type printed a hair out of register, red and black plates slipping apart, airbrush fades inside knife-cut friskets, Ben-Day dots on yellowed newsprint, one photo key pulled across hand-painted colour, characters struck through a fading ribbon, flat-shaded triangles dithered to 15 bits, spray drifting past cut card, satin stitches catching the light by their angle, ink lines printed white on Prussian blue, wax scribbles skipping the paper's pits, phosphor glowing behind curved glass, heat leaking out of a kitchen, cobalt fired into tin glaze tile by tile, ochre blown onto rock lit by a fire, 1-bit patterns in an old paint program, slip silhouettes incised to the clay, graphite that never quite reaches black, X-rays adding up through a suitcase, grey cels shot on scratched film, gouge marks in a rolled-up block, a birthday smeared onto tape, seven flat colours lifting off each other, an acorn squashing and stretching through a world drawn as it goes, ballpoint ink blobbing at every corner of a hand-drawn game, inks multiplying through tracing paper on a light box, window cards floating on a pastel field over shadows tinted by it, a vermilion stamp running dry at one end, red ink pooling where the pen slowed down, dyed donkey hide glowing on a lamp-lit screen, gouache scumbled dry over a toned board, knit stitch by stitch, dry pastel blue under a scratchy brush line, with chalk rain on top, a spring garden built leaf by leaf, its tiled roofs and willows mirrored in a jade lake, a roller and a dry brush running out across cream paper, a dusk sky going over to stars above thousands of tiny wildflowers, and a night sea laid stroke by stroke under the one warm light of lava meeting the water. No diffusion model, no API, no stock art. It is just Python with **numpy + Pillow** on a CPU: from 0.1 s (pixel art) to about 45 s (the soft 3D ray tracer) per 1920×1080 image.@@ -140,7 +144,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 seventy styles:+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with seventy-three styles:| Style | Module | What makes it read as the real medium ||---|---|---|@@ -214,6 +218,9 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra| **Dry-brush blocks (干刷色块)** | `lib/drybrush.py` · `DryBrushBlocks` | a mid-century poster / gouache-collage illustration built from a few big dry-brushed blocks of colour on cream paper, in a strictly limited palette: forest and sage green, teal-blue, navy, a near-black, vermilion, a touch of sky blue and celadon. Every block is painted in its own brush frame: the mask is rotated so the stroke runs along +u, coverage, value and colour mix are computed there with plain arrays and rotated back, so bristle streaks, lanes and dry ends always follow the stroke. A block is laid in parallel passes of a wide brush or roller, each starting loaded and running dry toward its end by its own amount, optionally broken into overlapping strokes of different lengths and tones; the sides come out nearly straight and the ends as a comb of tines, longer at the dry end. Paint only reaches the paper's tooth where the contact pressure is high enough — the tooth texture is histogram-equalised, so pressure maps straight to coverage — which gives scumbled patches and dry stretches with the paper or the colour below showing through; an overloaded brush stays solid. The backdrop slab behind the subject is laid with a roller tooth (nearly flat, clustered speckle, a crisp loaded edge, stippled dry sides, a few fine scratches); torn-paper pieces tear only along some stretches of their outline, with a pale fibrous rim. A person is a few planes — a jacket whose lit and dark halves are brushed in different directions, a head of skin planes with a darker nose side and a warm tip, rough black glasses, a white beard in dry scumble, a hand seen from the thumb side — and bottles are vertically brushed silhouettes with one light streak and a block label. One small vermilion square sits off to the side, and the finish reproduces the painting like an offset print: slight softness, paper grain, specks knocked out of the darks, a little dust || **Twilight storybook (暮色微缩绘本)** | `lib/twilight.py` · `TwilightStorybook` | a tender dusk picture-book page full of miniature detail, at the hour when day turns to night. The dusk sky is a six-stop gradient (lavender, lilac, rose, peach, apricot, gold) whose stops are warped by horizontally stretched noise, so the colours lie in soft layers, with lens-shaped clouds (soft lumpy tops, flatter and crisper bottoms), thin light streaks and a pale low sun. A feathered night field N (0 dusk – 1 night) is laid across the canvas from a wandering boundary: the night gradient, the Milky Way, the stars and the moon are painted with N as their alpha, so the stars thin out across the boundary instead of stopping at a line, and the band between is re-saturated so dusk passes through mauve, violet and indigo rather than grey. Every lit thing painted later — hills, flowers, figures — is shaded by the same field through a linear 3×3 grade (desaturate, then a cool tint), so a white daisy on the night side turns moonlit blue; emissive things and the plate are painted unlit. The Milky Way is an analytic band with cloudy density, a dark rift and thousands of faint stars sampled from it; stars follow a power law, are splatted with sub-pixel accuracy, and the brightest few get four-point sparkles. Hills are misty ranges and patchwork stripes that widen toward the viewer, cut into slanted fields with crop rows and hedge lines, dotted with tiny round trees. The meadow is placed by perspective with rejection sampling — size grows with depth below the crest, density follows coverage — so the crest is thousands of specks and the bottom a few dozen big flowers of eight species, all sorted by the y of their base and rasterised in one pass into a supersampled id map. Flat, cute figures sit in it: a hooded wanderer, a jar of fireflies, a four-panel kite whose string turns from dark to silver against the sky. Over it all lies the language of a scientific plate: fine ink lines drawn at 3×, hatching, drafting dimensions, a scale bar and a circular "detail a" inset, plus tiny lowercase captions set glyph by glyph from a thin hand font; the finish adds softness, bloom, grain, a plum vignette and a torn paper edge || **Hatched nocturne (排线夜景)** | `lib/nocturne.py` · `Nocturne` | a small night print built entirely from short directional strokes, the way a pastel or coloured-pencil artist hatches a nocturne, then mounted on cream paper. The sheet has an equalised tooth, mottling and fibres; the picture is underpainted dark and every mark is clipped to it like a taped edge. A stroke is a centreline integrated through an orientation field (angles mod π, so it never flips halfway), bent a little, with a blunt landing and a tapering tail; tens of thousands are rasterised at once by filling each outline with its own id into a 2× supersampled integer map, then, for every covered pixel, numpy looks up that stroke's colour, start, direction, length and width, recovers the position along and across it, and from that its bristle lane — six lanes per stroke with their own value and load, running dry toward the tail, the pigment only catching the paper where the tooth (dragged along the stroke's own direction) is below the pressure — so every stroke is streaky and grainy and the dark ground shows in hairline gaps. Fields set the "wind": the sky streams diagonally, steam rises with its column and curls only at the rims of its billows, slopes follow the fall lines of the cone, the sea drags in long horizontals that lengthen toward the viewer. Each stroke jitters a little in value and in hue (a true rotation about the grey axis). There is one warm light: point and emissive lights sum into a light map, and the glow is laid as strokes whose landing probability follows light × receptivity — added (screen) for air and glare, painted as light × receptivity for lit surfaces, so a blue-grey cloud turns red-orange rather than pink, and the hottest strokes whiten toward warm white. The hot source is a fan of yellow-white, orange and red strokes round a tiny core. Lava runs as braided rivulets — a walk with momentum that keeps turning toward its end and down the fall line, strands drifting apart, low-angle branches fading out or stopping in a bead — drawn as emission with a tight halo and light strokes on the slope; sparks fly on ballistic arcs. The sea reflects the picture above the waterline as horizontal strokes, stretched, rippled, darkened and laid only where the mirror is bright, plus a glitter column under the light. Two tiny seated figures with a red scarf and a warm rim give the scale; a plate mark, a pencilled title and a smaller note in a thin plain face, a restrained bloom and fine grain finish the print |+| **Obsidian UI (笔记应用界面)** | `lib/obsidianui.py` · `ObsidianUI` | a dark note-taking app the way an explainer film shows it: a near-black page with a soft violet glow and the app window on it — a tab bar with the traffic lights (the active tab open at the bottom so it runs into the note), a slim icon ribbon, a file explorer with folders, indent guides and the open note highlighted, a breadcrumb, a source / reading switch, a right sidebar and a floating status bar. In the note: a heavy H1 with a short glowing violet bar, a properties block with #tags, body lines laid out from runs (bold, internal links in violet, inline code on a dark chip, highlights), a dark code block in SF Mono with syntax colours and a block caret, a quote callout with a violet edge, task checkboxes; the reading view's flowchart as flat dark nodes with 2 px grey borders, thin edges with small filled arrowheads and an edge-label chip, one node lit violet inside a focus ring; and the graph view — grey nodes and links, the notes linked to this one lit violet with a soft radial glow, labels outlined in the pane colour so links stop short of the words. One accent (violet by default, switchable), everything else greys; every shape is a signed-distance field with analytic 1 px anti-aliasing, shadows and glows follow CSS box-shadow, and everything is drawn into named layers with a pose (offset, scale, opacity, a reveal left to right, top down or as a circle growing from a point), so the same drawing raises the window, types a code line with the caret riding its end, flips the switch, pops the flowchart node by node and grows the graph out of the current note |+| **Canvas board (白板卡片)** | `lib/canvasboard.py` · `CanvasBoard` | the canvas view of a dark note-taking app, as a product film shows it: a dark page with a faint violet glow, the app window (traffic lights and a `.canvas` tab in the tab bar, a ribbon of line icons, the zoom buttons top right) and in it an infinite board of grey dots seen through a camera. Nothing is rasterised when you draw: every shape is recorded in board coordinates into a named node — a group, a card, an edge — and `render()` draws every node again through the camera, so the board can be panned and zoomed with crisp edges and type at any scale; the dot grid lives on the board and moves with it, the chrome does not. Rounded rectangles, discs, rings and strokes are signed-distance fields with 1 px analytic anti-aliasing, polylines are measured segment by segment inside their own bounds (a 64-segment edge or a sketch of hundreds of segments stays cheap), arrowheads and the pointer are 4× supersampled polygons, shadows follow CSS box-shadow. Groups are rounded frames with their labels floating above; cards have a 2 px border in one of six card colours with a 5 % tint of it, a soft shadow, a file-name label, a violet halo when selected and a big shadow when lifted. Cards hold inline Markdown laid out again at every zoom — headings, ==violet highlights==, `mono code`, bold — task lists that tick (the box pops violet, the check draws on, a strike runs through, the text greys), quotes with a violet bar, tag pills, colour chips and progress bars; image cards hold a picture drawn in hand-drawn strokes (each segment slightly bowed and overshooting, drawn twice) with notes in a handwriting face. Edges are cubics that leave and enter along the sides' normals, with an arrowhead and a label on a board-coloured pill. Every node has a pose (offset, scale, opacity) and named progress vars that its shapes read — fade, draw, reveal or pop — and `tween()` writes the in-between stages: cards dropping in with a little bounce, edges drawing on, the camera panning and zooming, a sketch drawn stroke by stroke, the pointer clicking "fit". One accent: violet |+| **Flexoki paper (Flexoki 纸面)** | `lib/flexoki.py` · `FlexokiPaper` | an explainer sheet the way a docs site themed with the Flexoki palette shows its diagrams: warm paper #FFFCF0, ink-black type, a ladder of warm greys (surface, track, hairline, border, faint and muted text) and eight accents in two shades. Light-grey rounded panels with no border and no shadow carry a heavy CJK title, a grey English tag and a mono index; inside them the diagrams are drawn the way a lightweight Mermaid-style renderer draws them — boxes one step off their ground with a 2 px grey border (rect, round, stadium, exact rhombus, cylinder, circle), 2.4 px ink lines ending in small filled triangular heads, plain semibold labels on a patch of ground colour, dashed lifelines, activation bars, replies and notes, pies with paper-coloured gaps, bar charts on hairline grids, tables with a tinted header and accent dots — plus an orange focus ring, ink chips, step chips and big tight-tracked numbers. Every shape is a signed-distance field with 1 px analytic anti-aliasing; polylines carry their arc length, so an edge can be drawn on to any fraction (the cut end keeps its round cap), dashed along its length and trimmed under its head; a node (fill, border, label) is composited as one group, so it pops in and fades as a whole. Layers with poses, plus `layer(name, fresh=True)` to redraw a progress state, make the draw-on animation: panels rise dim and light up one by one, edges draw on one by one and land their heads, messages fly, a timer and the bar values roll, the pie sweeps, table rows slide in |Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:@@ -369,6 +376,19 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages- a rim light on a far rock reads as more lava — keep it faint;- a reflection that samples beyond the picture pulls the cream margin into the sea.Keep the people a few dozen pixels tall with one small accent, and the captions small, grey and in a thin plain face.+- **Obsidian UI**: show one operation in a window that looks like the real app — a note being written, a code block flipping into a rendered chart, the graph lighting up — rather than chrome for its own sake. Keep to one accent: the H1 bar, tags, internal links, the selected switch segment, the one lit node and the linked notes in the graph; everything else is the theme's greys, with hairline borders rather than shadows inside the window. In the graph view, outline each label in the pane colour so links stop short of the words, and never set two nodes on opposite sides of a third on one straight line (it reads as a single line through it). A violet click ring disappears on a violet button — use a very pale ring. Draw each state of a thing as its own layer (source / reading, grey / lit) and switch them; for the draw-on GIF, give anything that moves a few in-between poses, type code with the caret riding the line end, and grow the graph from the current note with a circular reveal. No official logos.+- **Canvas board**: keep it one dark app with one accent — violet for the selection, the ticks, the highlights, the tags, the quote bar and the main edge — and use the six card colours only as category marks on borders and chips, with a faint tint (5 %; at 7 % a red card turns brown). Let a card's height follow its content (lay the Markdown out first, then size the card): half-empty cards and a last line on the border both read as broken. Edges leave and enter along the sides' normals; keep labels to a word or a time, or they swallow a short edge. In a sketch card keep the strokes rough but the plan legible, the notes in a handwriting face and next to what they mean, not on top of a line. Watch for accidental reads:+ - a drop eased with an overshoot reaches 78 % in the first in-between and reads as a pop — let the card fall (accelerate), then bounce a little;+ - a camera that eases like the card it moves with bounces too — ease the camera on its own;+ - text revealed with a bouncing card shrinks back — write it after the card lands;+ - a timeline spine in mid-grey disappears when zoomed out — give it 3 px.+ In the GIF, let camera frames re-send everything that differs by more than a level: the group fill and the card shadows are only a few levels off the board and leave ghost frames behind a looser tolerance.+- **Flexoki paper**: one sheet, one subject, several diagrams — each panel answers one question (the steps, the timeline, the shares, the comparison), so give it a content title and let the grey English tag name the chart type. Keep paper and panels flat: no borders on the panels, no shadows, no gradients; the diagrams carry the detail. Fill a box one step off its ground (paper boxes on a grey panel, grey boxes on paper), or it is only a border. Let accents mean something — one chosen bar, one ringed column, green for yes and red for no — and leave everything else ink and grey. Watch for:+ - panel gutters that don't line up between rows — let the narrower column share one gutter with the row above;+ - edges of very different lengths in one row, and arrows shorter than about twice their head;+ - the faintest grey (#B7B5AC) on information — keep it for index numbers and axis ticks;+ - a mono face for values with units ("30 g") — mono is for ids, times on an axis and code.+ For the draw-on GIF, redraw progress states (`fresh=True`) and cut them as real motion; never cross-fade a line that is drawing on.### Roadmap@@ -380,7 +400,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,加上一个小巧的绘图库,内置七十三种画风:| 画风 | 模块 | 为什么看起来像真的 ||---|---|---|@@ -454,6 +474,9 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages| **干刷色块** | `lib/drybrush.py` · `DryBrushBlocks` | mid-century 海报 / 水粉拼贴式的编辑插画:米白纸上几大块干笔刷出的色块,颜色严格限定:森林绿、鼠尾草绿、青蓝、藏蓝、近黑、朱红,外加一点天蓝和淡青瓷。每块颜色在自己的笔刷坐标系里刷:把遮罩转到笔触方向沿 +u,在里面用普通数组算覆盖率、明暗和混色,再转回去,所以鬃毛纹、笔道和干笔收尾永远顺着笔走。一块颜色是一道道平行的宽笔或滚筒,每道起笔饱满、往收笔各干各的,也可以打断成长短不一、各有明暗的短笔;两侧几乎是直边,两端梳成长短不一的毛齿,干的一端更长。颜料只在接触压力够的地方挂上纸纹的齿——纸纹做过直方图均衡,压力直接就是覆盖率——于是有皴擦的斑和干擦的边,露出纸色或下层颜色;蘸满的笔照样实。主体背后的大色板用滚筒刷(近乎平涂、成簇细点、起笔边干净、干的两侧、几道细刮痕);撕纸片只有部分轮廓是撕口,带一圈浅色纤维边。人物是几块面:亮暗两半朝不同方向刷的外套,几块肤色平面拼的头(更暗的鼻侧、暖色鼻头),粗黑框眼镜,干笔皴擦的白胡子,从拇指一侧看的手;瓶子是竖刷的深色剪影,一道高光、一小块标签。一旁一个小朱红方块,最后像这幅画的胶印:轻微柔化、纸纹、暗部零星白点、一点细尘 || **暮色微缩绘本** | `lib/twilight.py` · `TwilightStorybook` | 一页温柔的黄昏绘本,满是微缩细节,画的是白天转入黑夜的那一刻。黄昏天空是六段渐变(薰衣草紫、丁香、玫瑰、蜜桃、杏、金),分段位置被横向拉长的噪声扰动,颜色一层层是软的;云是透镜形的带(顶上软而起伏,底部更平更清),加细细的光线和一轮低垂的淡日。一条游走的边界在整幅画上定出带羽化的夜度场 N(0 黄昏 – 1 夜):夜空渐变、银河、星星和月亮按 N 当透明度铺上去,星星越过边界慢慢变稀,不会停在一条线上;交界带补饱和度,黄昏经过淡紫、紫、靛蓝再到黑,不发灰。之后画的受光的东西(山、花、人物)都按同一个场经一个 3×3 线性变换(先降饱和、再偏冷)着色,夜的一侧的白雏菊成了月光蓝;发光的东西和图版不受影响。银河是解析的带,云状密度、一条暗带,几千颗暗星按它的密度抽样;星星是幂律亮度、亚像素溅射,最亮的几颗加四芒星。山是带雾的远山和越近越宽的拼布条纹,切成斜的田,有细垄和树篱线,点着小圆树。花坡按透视拒绝采样:大小随离坡顶的深度增长,密度按覆盖率定,所以坡顶是几千个色点、底边是几十朵八种大花;所有形状按根部的 y 排序,一次光栅化进超采样的 id 图。里面坐着扁平可爱的角色:小斗篷角色、一罐萤火虫、一只四片的风筝,风筝线跟着天色从深变银。上面叠一层科学图版的语言:3 倍图上画的细墨线、排线、制图尺寸标注、比例尺和圆形的「detail a」放大图,再加逐个字母排的细手写体小写英文;最后是柔化、光晕、颗粒、梅紫色暗角和一道撕纸边 || **排线夜景** | `lib/nocturne.py` · `Nocturne` | 一张全部由短方向笔触叠成的小幅夜景版画,像粉彩或彩铅画家排线画夜景,最后装在米白纸上。纸有直方图均衡过的纸纹、斑驳和纤维;画心先铺深色底,每一笔都裁在画心里,像贴了胶带。一笔是在方向场里积分出来的中心线(方向按 mod π 处理,中途不会掉头),带一点弯,落笔钝、收笔尖;几万笔一次画完:每一笔的轮廓按序号填进 2 倍超采样的整数 id 图,numpy 再对每个像素查出那一笔的颜色、起点、方向、长和宽,算出它在笔上的沿笔和横向位置,从而得到笔毛道——每笔 6 道,各有深浅和含量,越往笔尾越干,颜料只落在纸纹(沿这一笔自己的方向拖开)低于压力的地方——所以每一笔都有条纹和颗粒,深色的底从细缝里透出来。方向场定下「风」:天空斜着流,蒸汽顺着柱子往上、只在团块边上卷,山坡顺着锥形山的坡向,海面横着长拖、越近越长。每一笔的明度和色相(绕灰轴真正转色相)都抖一点。全画只有一个暖光:点光源和发光遮罩合成一张光照图,光用笔触铺,落笔的概率跟着「光 × 受光」走——空气和眩光用加光,被照亮的表面直接按「光 × 受光」上色,所以蓝灰的云变成红橙而不是粉,离热源最近的笔再偏向暖白。热源是一小撮黄白、外圈橙红的放射笔触,中间一个很小的白芯。熔岩是分股的细流:带惯性、一直转向终点并顺坡而下的游走,分股越往下分得越开,小角度的支流渐隐或停在一颗亮珠上,画成带紧贴光晕的发光线,再在山坡上铺光笔触;火星沿抛物线飞。海面把水线以上的画面镜像成横向笔触,被浪拉长、被涟漪推开、压暗,只在镜像亮的地方落笔,光源下面再拉一条碎的光柱。两个围着红围巾、带暖色轮廓光的坐着的小人给出尺度;压印的版痕、细体铅笔小标题和更小的说明、克制的辉光和细颗粒收尾 |+| **笔记应用界面** | `lib/obsidianui.py` · `ObsidianUI` | 讲解片里的一个深色笔记应用:近黑页面上一团淡紫光晕,上面是应用窗口——标签栏和红黄绿三点(当前标签底边打开,和笔记连成一片)、细长的图标栏、带文件夹和缩进线的文件列表(打开的笔记高亮)、面包屑、源码 / 阅读开关、右侧边栏和右下角浮着的状态栏;笔记里是粗黑 H1 和一道带辉光的紫色短条、带 #标签的属性块、按片段排出来的正文(加粗、紫色的内部链接、压在深色小底上的行内代码、高亮)、SF Mono 写的深色代码块(语法色、块状光标)、紫色左边的引用标注、任务勾选框;阅读视图里的流程图是扁平深色节点、2 px 灰边、细线加小实心三角箭头和边上的小标签,其中一个节点亮成紫色、套一圈外环;关系图谱是灰点灰线,这篇笔记链接到的几篇亮成紫色、带柔和的径向光,标签描一圈栏底色,连线到字前就断开。只有一个强调色(默认紫,可换),其余全是灰;所有形状都是有符号距离场、1 px 解析抗锯齿,阴影和辉光按 CSS box-shadow 算;一切画进带姿态(位移、缩放、不透明度、从左往右 / 从上往下 / 从一点往外长成圆的揭开)的图层,同一套画面既能让窗口升起、逐行敲代码而光标跟着行尾走、点开关切到阅读,也能让流程图一个节点一个节点弹出、关系图谱从当前笔记往外长出来 |+| **白板卡片** | `lib/canvasboard.py` · `CanvasBoard` | 深色笔记应用的白板视图,像产品片里拍的那样:深色页面左上一片淡紫光,一扇应用窗口(标签栏上红黄绿三点和「.canvas」标签页、左边一列线性图标、右上角缩放按钮),里面是一块透过镜头看的灰点阵无限白板。画的时候什么都不栅格化:每个形状都按白板坐标记进一个有名字的节点(分组、卡片、连线),`render()` 按镜头把所有节点重画一遍,所以白板可以任意平移缩放,边和字始终锐利;点阵长在白板上跟着动,窗口不动。圆角矩形、圆、环和线条是有符号距离场、1 px 解析抗锯齿,折线逐段只在自己的包围盒里算(64 段的连线、几百段的草图都很快),箭头和指针是 4 倍超采样多边形,阴影按 CSS box-shadow 算。分组是圆角框,组名浮在框上方;卡片是 2 px 的卡片色边(六种卡片色)加 5 % 同色底、软阴影、上方的文件名,选中时一圈淡紫光,举起时一层大阴影。卡片里是每次缩放都重新排版的行内 Markdown——标题、紫色高亮、等宽行内代码、粗体——会打勾的清单(紫色方框弹出、对勾画出、删除线划过、文字变灰)、紫色竖条的引用、标签胶囊、颜色胶囊和进度条;图片卡片里是手绘笔触画的图(每段略弯、两头出头、画两遍)和手写体批注。连线是沿两条边的法线出入的三次曲线,末端箭头,中间一块白板底色的标签。每个节点有位姿(位移、缩放、不透明度)和有名字的进度变量,形状按 淡入 / 画出 / 揭开 / 弹出 读它;`tween()` 写出中间阶段:卡片掉落、回弹落定,连线画出来,镜头平移缩放,草图一笔笔画,指针点「适合窗口」。只有一个强调色:紫 |+| **Flexoki 纸面** | `lib/flexoki.py` · `FlexokiPaper` | 照用 Flexoki 配色的文档站那样摆一页图解:暖白纸 #FFFCF0、墨黑字、一串暖灰(卡片底、轨道、细线、边框、最淡和次要的字),八种强调色各两档。不描边、不投影的浅灰圆角卡片,粗黑中文标题、灰色英文、等宽编号;卡片里的图照轻量的 Mermaid 式渲染器画——比底色差一级的框和 2 px 灰边(直角、圆角、胶囊、精确菱形、圆柱、圆),2.4 px 墨线末端一个小的实心三角箭头,普通半粗体标签垫一块底色,虚线生命线、激活条、回复和便签,带纸色缝的饼图,细网格上的柱状图,表头着色、带强调色小圆点的表格;还有橙色聚焦框、黑底胶囊、步骤胶囊和字距收紧的大数字。所有形状都是有符号距离场、1 px 解析抗锯齿;折线带弧长,一条边能画到任意几成(切口仍是圆头)、沿弧长画虚线、在箭头下面截短;一个框(底、边、字)先合成一组再放下,所以弹出和淡入是整个一起的。带姿态的图层加上 `layer(name, fresh=True)` 按进度重画,就是逐边画出的动图:卡片暗着升起、一张张亮起,线一条条画过去再落下箭头,消息飞过去,计时器和柱顶数字滚动,饼图扫开,表格一行行滑进来 |对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;@@ -553,6 +576,9 @@ python3 examples/jiangnan_spring_water.py out.jpg --stages stages/ # 江南园python3 examples/drybrush_noodle_counter.py out.jpg --stages stages/ # 干刷色块:面馆python3 examples/twilight_paper_kite.py out.jpg --stages stages/ # 暮色微缩绘本:夜的边上python3 examples/nocturne_lava_sea.py out.jpg --stages stages/ # 排线夜景:熔岩入海+python3 examples/obsidianui_reading_notes.py out.jpg --stages stages/ # 笔记应用界面:小王子读书笔记+python3 examples/canvasboard_moving_plan.py out.jpg --stages stages/ # 白板卡片:搬家计划+python3 examples/flexoki_pour_over.py out.jpg --stages stages/ # Flexoki 纸面:一杯手冲咖啡```### 作画要点(Claude 交图前逐条自查)@@ -657,6 +683,19 @@ python3 examples/nocturne_lava_sea.py out.jpg --stages stages/ # 排线夜景- 远处礁石上的轮廓光会被看成也有熔岩——要很淡;- 倒影取样跑出画心,会把米白纸边拉进海里。小人几十像素高、只有一点亮色,题字要小、灰、用细的普通字体。+- **笔记应用界面**:在一个像真应用的窗口里演示一件事——写一篇笔记、代码块切换成渲染好的图、关系图谱亮起来——不是为了堆界面而堆界面。只用一个强调色:H1 下的短条、标签、内部链接、开关选中的那一段、亮起的那个节点、图谱里被链接的笔记;其余都是主题的几级灰,窗口里面用发丝分隔线,不用阴影。关系图谱的标签描一圈栏底色,让连线到字前就断开;不要把两个节点摆在第三个节点两侧的同一条直线上(看着像一根线横穿过去)。紫色的点击环压在紫色按钮上看不见,要用很浅的环。同一样东西的不同状态(源码 / 阅读、灰 / 亮)各画一层再切换;做动图时,会动的东西给几个中间姿态,代码逐行敲出、光标跟着行尾走,图谱用圆形揭开从当前笔记长出来。不画官方 logo。+- **白板卡片**:守住「一个深色应用、一个强调色」——选中、勾、高亮、标签、引用竖条和主连线都是紫色,六种卡片色只当分类记号用在边框和胶囊上,底色只淡淡染一层(5 %;7 % 时红卡发褐)。卡片高度跟着内容走(先排 Markdown,再定卡片高):空了半张的卡和压在边框上的最后一行看着都像坏了。连线沿两条边的法线出入,标签只写一个词或一个时间,不然短连线整条被标签吞掉。草图卡片里笔触要毛,但平面图要读得懂,批注用手写体、放在它说的东西旁边,不要压在线上。小心看错:+ - 带回弹的缓动第一张中间帧就走完 78 %,卡片是「弹出来」——让它加速落下,再回弹一点;+ - 镜头和掉落的卡片共用一个缓动,镜头也会回弹——镜头单独缓动;+ - 跟着回弹揭开的字会缩回去——卡片落定后再写字;+ - 中灰的时间线竖线拉远就没了——给 3 px。+ 动图里镜头在动的帧,和屏上差一级以上的像素都要重发:分组框的底和卡片影子只比白板亮几级,容差一松就留下残影。+- **Flexoki 纸面**:一页讲一件事、放几张图——每张卡片回答一个问题(步骤、时间线、占比、对比),中文标题写内容,灰色英文写图的类型。纸和卡片保持平:卡片不描边、不投影、不渐变,细节交给图。框要比它的底色差一级(灰卡片上用纸色框,纸上用灰框),否则只剩一圈边。强调色要有意义——选中的一根柱、圈起来的一列、绿色是「是」、红色是「否」——其余都是墨和灰。小心:+ - 两行卡片的缝对不上——让窄的那一列和上一行共用一条缝;+ - 同一行里的边一长一短,箭头短到不到箭头本身的两倍;+ - 最淡的灰(#B7B5AC)用在信息上——它只给编号和坐标刻度;+ - 带单位的数值用等宽字(「30 g」)——等宽只给编号、坐标上的时间和代码。+ 做动图时按进度重画(`fresh=True`),当成真的运动硬切,线画出来的过程不要叠化。### 计划diff --git a/SKILL.md b/SKILL.mdindex 7e8b0f8..d512d3c 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,6 +1,6 @@---name: claude绘图-description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置七十种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)、拼豆(钉板上的熔珠小管、熨烫熔合)、岩画(沙漠漆上凿出的凹坑图形、新旧凿痕、剥落)、古埃及墓室壁画(灰泥墙、红格起稿、分栏叙事、象形文字、剥落)、罗马马赛克(石子与玻璃沿轮廓一排排铺、灰缝、燕尾铭牌)、彩色玻璃花窗(哥特尖拱窗、通体着色玻璃、grisaille 彩绘与银染、铅条、透光)、泥金手抄本(羊皮纸、鹅毛笔哥特体、朱红标题、打磨金箔首字母)、达·芬奇手稿(铁胆墨水、左手排线、红粉笔、镜像手写、机械分解图)、剪影(黑纸剪出的侧影小像、薄金粉、椭圆金框)、凸版印刷海报(木活字、红黑双色错版、木刻插图)、苏联构成主义(红黑两版、斜条与楔形、西里尔大字、网点照片拼贴)、装饰艺术 Art Deco(1930 年代喷枪流线型海报、交替射线、阶梯高楼、金色 Deco 字)、黄金时代漫画(毛笔墨线、Ben-Day 网点、四色错版、新闻纸)、波普丝网(多格撞色平涂 + 错位的照相黑版)、ASCII 字符画(行式打印机、绿条连续纸、叠打)、低多边形(1999 年代 3D:平面着色、仿射贴图、逐顶点雾、15 位色抖动)、喷漆模板涂鸦(混凝土墙上多层卡纸模板喷绘、雾化与滴痕)、刺绣徽章(牛仔布上的机绣徽章:填充绣、缎面绣、锁边)、蓝图工程图(描图墨线晒成蓝底白线)、儿童蜡笔画(小孩在糙纸上的蜡笔涂抹)、绿屏终端 CRT(荧光字符画、扫描线、余辉)、热成像(先画温度场再上伪彩色)、代尔夫特蓝瓷砖(锡釉砖上的钴蓝手绘)、洞穴壁画(火光下的赭石、吹喷手印)、1-bit 早期画图软件(黑白整屏、8×8 图案填充)、古希腊黑绘陶瓶(黑釉剪影、刻线、饰带展开图)、铅笔素描(石墨排线、擦笔、边缘只剩线稿)、X 光片(安检透视、轮廓发亮、伪彩)、1930 年代黑白橡皮管动画(白手套、饼切眼、老胶片)、黑白麻胶版画(刻刀减法、手拓发花、套色错版)、VHS 家庭录像(钨丝灯偏色、色度渗色、REC)、扁平矢量(分层几何色块、七色、层间投影)、绘本角色动画(小角色挤压拉伸的真动画)、圆珠笔涂鸦(蓝红圆珠笔线稿、墨团、彩铅、页边涂鸦)、描图纸叠层(灯箱上的黑线底图 + 一张张单色描图纸叠片:正片叠底、套准十字、定位钉、绘图胶带)、粉彩界面 · Pastel UI(产品发布片式的界面画面:纯色粉彩底与大光斑、macOS 窗口卡片、胶囊与粗黑标题色条、状态标签与 ✓ / ✗ 徽章、放大镜、从卡片边探头的扁平小图标)、阅卷批改 · Exam Grading(绿毛毡桌上被红笔批改的答题卡:定位黑块、考号涂卡、得分格与阅卷栏、长尾夹夹住的标准答案卡、油墨不均的朱红印章、立体红笔、波浪线 / 圈 / 引线 / 批注 / 叉 / 圈起来的分数)、皮影戏 · Shadow Puppetry(油灯照亮的幕布上,雕空、透明染色的驴皮关节人偶:镂空纹样、阳刻空脸、雉翎盔头、线结与操纵杆、离幕时虚化的双影;雕花戏台、红漆金字牌匾、红灯笼)、钢笔淡彩 · Pen & Wash(速写小卡上的针管笔线稿 + 松散淡彩:线条抖、出头、不闭合,颜色错位出线、留白缝、干边与颗粒,不铺满的背景色块;大头、圆眼镜、点点眼、红鼻子的呆萌小人;卡片拍在木桌上,旁边放着针管笔和水笔)、复古水粉 · Retro Gouache(复古绘本风的水粉大头像:不透明水粉从暗到亮一层层盖上去,单色背景用干笔皴擦;大红鼻子、腮红、圆眼和大耳朵用几阶色值塑出来;看得见针脚的毛衣和毛线帽,一根根的头发和胡子,毛毡;最后是印刷书页的纸纹)、蓝调绘本 · Blue Picture Book(软蓝色调的现代绘本跨页:几乎只用粉蓝、矢车菊蓝、深青蓝三阶蓝加黑墨和纸白,只点一点珊瑚红、粉色腮红和芥末黄;毛笔 / 墨铅笔线干、抖、断,粗细不匀,线不闭合,暗部用快速来回的乱线排出来;颜色是干蜡笔、粉彩、干水粉,错位出线,纸纹的白点透出来;白粉笔痕压在蓝上,甩点和细尘;背景蓝块毛边、不到纸边;大圆脑袋、带高光的点点眼、点彩腮红和雀斑、火柴腿穿靴子的小人,乱线毛边的白色毛绒动物;最后印在书上:中缝和页码)、江南园林 · Jiangnan Garden(细笔园林春景,数字水粉插画:成千上万片叶形小笔触按一个太阳堆出树冠,暗芯、亮边、一簇簇的高光;白色和淡粉的繁花是一簇簇圆点花瓣,枝条从缝里露出来;垂柳是一绺一绺发丝般的细枝挂满小叶;黛瓦飞檐是真的瓦垄:筒瓦板瓦一行行、檐口瓦当滴水、翘起的翼角和卷起的脊头;粉墙月洞门、冰裂纹漏窗、翡翠绿槅扇和挂落、红灯笼、匾额;九曲石桥、石阶、小木船;碧绿湖面倒映岸上的一切,更柔、更暗,加涟漪和细竖纹;睡莲、白鹭;从前景花枝到雾里青山层层退远,墙上桥上落着叶影;最后一方小红印)、干刷色块 · Dry-Brush Blocks(mid-century 海报 / 水粉拼贴式的编辑插画:米白纸上几大块干笔或滚筒刷出的色块,颜色严格限定在森林绿、鼠尾草绿、青蓝、藏蓝、近黑和朱红,外加一点天蓝、淡青瓷和米色;每块颜色在自己的笔刷坐标系里刷:一道道平行的笔,起笔饱满、收笔干枯,两侧几乎是直边,两端梳成长短不一的毛齿,块里有顺笔的鬃毛纹、皴擦斑和露出来的纸色;背后的大色板用滚筒:近乎平涂、成簇的细点、干的两侧和几道细刮痕;色块像丝网套印或撕纸拼贴一样叠起来,撕口带一圈浅色纤维边;人物拆成几个大块面:亮暗两半朝不同方向刷的外套、几块肤色平面拼的头、粗黑框眼镜、干笔皴擦的白胡子;瓶子是竖刷的深色剪影加一道高光和小块标签;一旁一个小朱红方块;不勾线、不做渐变;最后像胶印:轻微柔化、纸纹、暗部零星白点、纸上细尘)、暮色微缩绘本 · Twilight Storybook(温柔、怀旧的黄昏绘本单页,满是微缩细节:大片粉彩黄昏天空,从顶上的薰衣草紫经玫瑰、蜜桃到地平线的暖金,柔和的平底云带、细细的光线和一轮低垂的淡日;一侧天空已经入夜:星空、带暗带的银河、弯月、流星,昼夜交界经过淡紫和靛蓝,不发灰;下面是一层层粉彩条纹的起伏山丘,拼布似的田、细细的垄、小圆树;前景是几万朵小野花铺成的坡,坡顶是色点,越往下越大:雏菊、矢车菊、虞美人、波斯菊、金盏花、毛茛、羽扇豆、勿忘我,夜的一侧整片变成月光蓝;很小、扁平、可爱的原创角色;上面叠一层科学图版的语言:圆形的「detail a」放大图,细墨线、排线、尺寸标注、标签和比例尺,几行灰色的小写英文手写字;最后是细颗粒、光晕、暗角和底边一道撕纸边)、排线夜景 · Hatched Nocturne(彩铅 / 色粉排线式的小幅夜景版画:天空、云、山和海全由密密的短笔触叠成,每片区域的笔触顺着同一股「风」走——天空斜着流、蒸汽绕着云团卷、山坡顺着坡向、海面横着长拖,每一笔色相和明度都差一点,笔毛分道、拖干的笔尾、纸纹里漏出的细缝,没有一处平滑渐变;深靛蓝、藏青、冷灰蓝的夜色里只有一个暖色光源,光是一层层加上去的发光笔触:核心黄白、外圈橙红、再外是被照亮的笔触,被照亮的蒸汽按「光 × 受光」上色,所以是红橙而不是粉;发光的细丝(会蜿蜒、分股、末端亮珠)、火星、星点;海面上被横向笔触打碎的倒影和光柱;几十像素高的小人靠一点亮色(围巾)点出来;最后装裱成小版画:米白纸边、压印的版痕、左下铅笔小标题、右下更小的说明,用细的普通字体)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古、拼豆、拼拼豆、熔珠、熨豆、豆豆画、钉板、烫豆、岩画、岩刻、凿刻、石刻、沙漠漆、史前壁刻、大角羊、古埃及、埃及壁画、墓室壁画、法老时代、象形文字、尼罗河、底比斯、罗马马赛克、马赛克镶嵌、镶嵌画、石子拼画、地砖画、古罗马地板、彩色玻璃、彩绘玻璃、花窗、玻璃花窗、教堂花窗、哥特花窗、铅条玻璃、泥金手抄本、手抄本、彩饰手抄本、中世纪手稿、羊皮纸、哥特体、花体首字母、泥金、贴金、星盘、达芬奇、达·芬奇、达芬奇手稿、手稿风、文艺复兴手稿、发明手稿、镜像字、镜像书写、扑翼机、红粉笔、钢笔排线、机械草图、分解图、剪影、剪影肖像、侧影、侧面像、黑纸剪影、剪影小像、椭圆金框、乔治时代肖像、摄政时期肖像、凸版印刷、活版印刷、木活字、铅字海报、马戏团海报、复古海报、老海报、19 世纪海报、双色套印、错版、套色错位、木刻插图、构成主义、苏联海报、苏联构成主义、俄国先锋派、罗德琴科风、红黑海报、照片蒙太奇、照片拼贴海报、西里尔字、装饰艺术、装饰风、流线型、流线型海报、1930 年代海报、旅行海报、铁路海报、火车海报、喷枪画、喷笔画、阶梯高楼、射线背景、盖茨比风、黄金时代漫画、老漫画、复古漫画、美漫封面、漫画封面、Ben-Day 网点、本戴点、网点上色、四色印刷、四色错版、新闻纸、对白框、拟声字、1940 年代漫画、波普、波普艺术、波普丝网、沃霍尔风、丝网版画头像、撞色头像、多格重复头像、六宫格撞色头像、ASCII、字符画、字符艺术、文字画、行式打印机、绿条纸、连续打印纸、针孔打印纸、老电脑打印、叠打、低多边形、低面数、低模、多边形风、千禧年 3D、90 年代 3D、复古 3D 游戏、老游戏截图、PS1 风、N64 风、平面着色、线框、游戏 HUD、飞行游戏、穿环、喷漆、模板涂鸦、镂空模板、喷漆模板、模板喷绘、街头涂鸦、街头艺术、墙绘、滴漆、班克西风格、刺绣徽章、徽章、布章、臂章、刺绣贴、绣标、锁边、牛仔外套徽章、户外徽章、营地徽章、弧形条章、蓝图、工程图、施工图、蜡笔画、儿童画、绿屏终端、CRT、显像管、热成像、热像仪、温度图、代尔夫特、荷兰蓝瓷砖、洞穴壁画、史前壁画、赭石、1-bit、黑白画图软件、MacPaint 风、黑绘、古希腊陶瓶、希腊瓶画、铅笔素描、素描、铅笔画、X 光、X 光片、安检图像、橡皮管动画、黑白卡通、老动画、麻胶版画、黑白版画、藏书票、VHS、家庭录像、录像带、扁平插画、扁平风、矢量插画、绘本动画、角色动画、挤压拉伸、圆珠笔、圆珠笔涂鸦、原子笔、页边涂鸦、课本涂鸦、手画棋盘、描图纸、硫酸纸、叠片、叠层、分色片、灯箱、拷贝台、透光台、套准、定位钉、粉彩界面、粉彩 UI、Dot 风、Dot 那种风格、产品发布会界面、发布会质感、窗口卡片、macOS 窗口、界面卡片、讲解片界面页、小图标探头、阅卷、阅卷批改、批改、判卷、改卷、改作业、答题卡、试卷、考卷、测验卷、红笔批改、红笔打分、打分数、盖章批改、朱红印章、标准答案卡、长尾夹、讲解片评测 / 打分页、皮影、皮影戏、影子戏、驴皮影、灯影戏、皮影人偶、雕花戏台、戏台牌匾、亮相、钢笔淡彩、淡彩、淡彩速写、钢笔淡彩小人、针管笔、勾线笔、针管笔加水彩、线稿上色、速写卡片、速写本小人、水彩小卡、城市速写、街头速写、水笔、自来水笔、复古水粉、水粉、水粉画、不透明水粉、哑光丙烯、复古绘本、绘本插画、绘本大头像、童书插画、复古童书、大头像、大鼻子人物、针织毛衣、麻花毛衣、毛线帽、毛毡帽、卷发、胡子、蓝调绘本、蓝色绘本、软蓝绘本、蓝调童书、软蓝童书插画、蓝色童书插画、蓝色系绘本、限色绘本、蓝白绘本、现代绘本跨页、手绘绘本跨页、绘本跨页、绘本内页、干笔墨线、墨铅笔线、粉彩蜡笔质感绘本、白色毛绒动物、毛绒白熊、点彩腮红、江南园林、园林春景、春水园林、中式园林插画、古典园林插画、国风园林插画、苏式园林、细笔园林、园林风景插画、水榭、临水茶榭、亭台楼阁、粉墙黛瓦、黛瓦白墙、飞檐翘角、翼角起翘、月洞门、漏窗、冰裂纹窗、槅扇、挂落、九曲桥、曲桥、垂柳园林、碧水倒影、园林倒影、睡莲池、数字水粉风景、细腻厚涂风景、干刷色块、干笔色块、干刷、干刷插画、干笔插画、滚筒刷、滚筒色块、色块插画、大色块插画、毛边色块、刷痕色块、粗刷笔触、mid-century、世纪中期插画、中世纪现代插画、复古编辑插画、复古海报插画、水粉拼贴、撕纸色块、限色海报、暮色微缩绘本、暮色绘本、黄昏绘本、微缩绘本、黄昏转夜、昼夜交界、日夜交界、半边黄昏半边星空、粉彩黄昏、粉紫晚霞、黄昏星空、银河插画、野花坡、野花草坡、花海插画、萤火虫、放风筝插画、拼布山丘、条纹田野、小圆树、细节放大图、局部放大图、技术细节小窗、科学图版风插画、手写英文小字、晚安绘本、治愈系绘本插画、排线夜景、排线风夜景、彩铅夜景、色粉夜景、粉彩排线、短笔触夜景、笔触夜空、方向笔触、夜景版画、小版画、限量版画风、版画装裱、版痕、纸边标题、铅笔题字、夜景插画、夜空插画、深蓝夜景、靛蓝夜空、冷暖对比夜景、唯一暖光、夜里的火光、发光的云、被照亮的云、红色精灵闪电、精灵闪电、火山夜景、熔岩入海、熔岩、岩浆、火山喷发插画、海上风暴、海面倒影、光柱倒影、火星飞溅、星点、看海的人、礁石上的人、远处的小人、小人比例尺、雪夜篝火、渔火),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun / perler beads / hama beads / artkal / fuse beads / melty beads / pegboard beads / petroglyph / rock art / rock carving / desert varnish / Egyptian tomb painting / ancient Egypt / hieroglyphs / Theban tomb / Roman mosaic / floor mosaic / tesserae / opus vermiculatum / Pompeii mosaic / stained glass / leaded glass / church window / Gothic window / grisaille / illuminated manuscript / medieval manuscript / book of hours / gold leaf / illuminated initial / blackletter / vellum / astrolabe / da Vinci notebook / Leonardo codex / Renaissance sketchbook / mirror writing / iron-gall ink / red chalk / sanguine / ornithopter / exploded view / inventor's sketch / silhouette / silhouette portrait / cut-paper profile / shade portrait / Georgian portrait / Regency portrait / oval gilt frame / letterpress / wood type / playbill / circus poster / Victorian poster / two-colour misregistration / woodcut poster / constructivism / constructivist poster / Soviet avant-garde / Russian avant-garde / Rodchenko style / photomontage poster / art deco / streamline moderne / 1930s travel poster / railway poster / airbrush poster / sunburst rays / Gatsby style / golden age comic / vintage comic book / comic cover / Ben-Day dots / four-color printing / newsprint / speech balloon / pulp cover / pop art / Warhol-style / pop silkscreen / silkscreen portrait / repeated pop portrait grid / ASCII art / text art / typewriter art / line printer / greenbar / fanfold paper / tractor feed / overstrike / printer plot / low poly / low-poly / retro 3D / 90s 3D game / PS1 style / N64 style / software rasterizer / flat shading / affine texture mapping / vertex fog / game HUD / stencil / stencil graffiti / spray paint stencil / street art / drips and overspray / Banksy-style stencil / embroidered patch / embroidery patch / iron-on patch / sew-on patch / merit badge / camp badge / merrow border / rocker patch / denim jacket patches / blueprint / technical drawing / crayon / kid's drawing / CRT terminal / green screen / thermal camera / thermal imaging / Delft tiles / Delft blue / cave painting / ochre / Lascaux-style / 1-bit / MacPaint-style / black-figure / Greek vase / pencil drawing / graphite / X-ray / baggage scanner / rubber hose / 1930s cartoon / linocut / lino print / VHS / home video / flat vector / flat illustration / storybook animation / squash and stretch / ballpoint / biro / ballpoint doodle / margin doodles / hand-drawn board game / overlay sheets / tracing-paper overlays / light box / colour separations / registration marks / acetate overlay / pastel UI / Dot-style product film / launch-film interface / macOS window cards / exam grading / grading an answer sheet / red-pen marking / graded test paper / rubber-stamped answer sheet / shadow puppet / shadow puppetry / Chinese shadow play / leather shadow puppets / backlit puppet screen / pen and wash / pen & wash / line and wash / ink and watercolour / ink and watercolor / fineliner sketch / fineliner and watercolour / sketchbook characters / sketch cards / urban sketching / water brush / gouache / retro gouache / gouache portrait / gouache illustration / opaque gouache / matte acrylic / picture-book portrait / vintage picture book / retro children's book illustration / mid-century children's book / big-nosed character portrait / cable-knit sweater / knitted bobble hat / blue picture book / soft blue picture book / soft-blue children's book illustration / modern picture book / limited-palette picture book / picture-book spread / scratchy ink line / dry-brush ink line / ink pencil line / crayon and pastel texture / chalky white marks / blue and coral palette / fluffy white bear / Jiangnan garden / Chinese garden / classical Chinese garden illustration / Chinese water garden / spring garden illustration / lush painterly garden / waterside pavilion / moon gate / lattice windows / zigzag bridge / weeping willow garden / upturned eaves / grey-tiled roof / blossom trees and reflections / lily pond with egrets / digital gouache landscape / dry-brush blocks / dry brush illustration / dry-brushed colour blocks / roller texture / brush-textured shapes / mid-century illustration / mid-century modern poster / mid-century editorial illustration / gouache collage / torn-paper collage poster / limited palette poster / scumbled texture / vintage book cover illustration / twilight storybook / dusk picture book / dusk to night sky / day and night split sky / pastel sunset sky / Milky Way illustration / wildflower meadow / wildflower hill / patchwork hills / tiny round trees / fireflies / paper kite / magnified detail inset / detail callout circle / scientific plate overlay / handwritten lowercase captions / cozy miniature illustration / bedtime story illustration / hatched nocturne / hatched night scene / pastel hatching night / coloured-pencil nocturne / directional strokes / short brush strokes sky / night print with margins / small art print / plate mark / pencilled title and caption / indigo night with one warm light / glowing cloud lit from below / red sprites / lava entering the sea / volcano at night / glowing threads and sparks / broken reflection on the sea / tiny figures for scale without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。单独说「剪纸」指剪纸拼贴、「刺绣」指十字绣、「丝网印刷 / screen print」指包豪斯几何;「打马赛克」是打码,不是马赛克画风;单说「蓝图」指蓝图工程图,「蓝晒 / 晒图」仍指蓝晒;「铅笔 / 素描」指铅笔素描,「彩铅」指韩国彩铅;「像素」仍指像素风,「1-bit / 黑白画图软件」指 1-bit 早期画图软件;「霓虹」仍指赛博朋克;「喷漆 / 街头涂鸦」仍指喷漆模板涂鸦,「圆珠笔 / 随手涂鸦 / 页边涂鸦」指圆珠笔涂鸦;「描图纸 / 硫酸纸 / 叠片 / 灯箱」指描图纸叠层(蓝图工程图那张描图布是晒成蓝图的,不是叠片);「Dot 风 / 粉彩界面 / 窗口卡片 / 发布会界面」指粉彩界面(纯色底 + 白色实心窗口卡片),要磨砂玻璃和弥散渐变仍用弥散玻璃;「阅卷 / 批改 / 答题卡 / 判卷 / 红笔打分」指阅卷批改,实验记录里的红笔圈和便利贴仍用实验笔记本,带「已付」橡皮章的小票拼贴仍用贴纸拼贴 · 小票;「皮影 / 皮影戏 / 影子戏」指皮影戏(透光的彩色驴皮人偶),黑纸剪出的侧影小像仍用剪影,彩纸剪贴仍用剪纸拼贴。「钢笔淡彩 / 淡彩速写 / 针管笔加水彩 / 线稿上色的速写小卡」指钢笔淡彩;单说「水彩」仍指水彩(风景、花卉的大片晕染),蓝铅笔稿 + 毛笔线 + 赛璐璐阴影的拟人小物仍用卡通手绘,「素描 / 铅笔」仍指铅笔素描。「水粉 / 复古水粉 / 绘本大头像 / 复古童书插画」指复古水粉(不透明水粉画的特写大头像);梵高式厚涂的风景、名画感仍用油画厚涂,扁平矢量、会挤压拉伸的小角色动画(「绘本动画」)仍用绘本角色动画,针管笔线稿加淡彩的速写小卡仍用钢笔淡彩,撞色多格的头像仍用波普丝网。「蓝调绘本 / 软蓝绘本 / 蓝色童书插画 / 绘本跨页」指蓝调绘本(软蓝限色的现代绘本跨页:干笔墨线 + 干蜡笔粉彩上色 + 白粉笔痕);单说「绘本」仍指绘本角色动画,「水粉 / 绘本大头像」仍指复古水粉,「编辑风 / Riso」仍指编辑风手绘,针管笔线稿加淡彩的速写小卡仍用钢笔淡彩,小孩自己画的蜡笔画仍用儿童蜡笔画。「江南园林 / 园林春景 / 中式园林插画 / 粉墙黛瓦 / 飞檐 / 月洞门 / 九曲桥」指江南园林(细笔数字水粉的园林春景:叶形小笔触堆出的繁茂树冠、繁花、垂柳、黛瓦飞檐、碧水倒影、层层远山);单说「水墨 / 山水」仍指水墨,单说「水彩」仍指水彩,动漫背景 / 赛璐璐天空仍指日本动漫,浮世绘仍是浮世绘;梵高式厚涂的风景仍用油画厚涂,皮影人偶的一场戏仍用皮影戏。「干刷色块 / 干笔色块 / 滚筒色块 / mid-century 海报插画」指干刷色块(米白纸上几大块干笔或滚筒刷出的限色色块,人物拆成几个大块面,背后一块纯色板、一旁一个小红方块);单说「水粉 / 绘本大头像」仍指复古水粉,「剪纸 / 彩纸拼贴」仍指剪纸拼贴,「丝网印刷 / screen print」仍指包豪斯几何,「Riso / 编辑风」仍指编辑风手绘,没有笔触的平滑几何色块仍用扁平矢量。「暮色微缩绘本 / 暮色绘本 / 黄昏转夜 / 昼夜交界 / 野花坡 / 细节放大图」指暮色微缩绘本(粉彩黄昏转入银河夜空、拼布山丘、几万朵小野花、很小的原创角色,加圆形放大图和手写小字);单说「绘本」仍指绘本角色动画,「蓝调绘本 / 软蓝绘本」仍指蓝调绘本,赛璐璐天空和夏日少年感仍用日本动漫,大片晕染的风景仍用水彩,整页的机械分解手稿仍用达·芬奇手稿,剖面和施工图仍用蓝图工程图。「排线夜景 / 彩铅或色粉夜景 / 短笔触夜空 / 夜景小版画 / 熔岩入海 / 精灵闪电 / 被照亮的云」指排线夜景(满画面顺着风向的短笔触、深蓝夜色里只有一个暖光、发光的丝和火星、碎的倒影、很小的人,装成带纸边和铅笔字的小版画);梵高式的厚涂漩涡和颜料浮雕仍用油画厚涂,明亮可爱的彩铅甜品仍用韩国彩铅,黑白石墨排线仍用铅笔素描,粉彩黄昏转入银河星空、满坡小野花仍用暮色微缩绘本,霓虹雨夜街道仍用赛博朋克。+description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型,由 Claude 用代码一笔一笔「画」出图片(程序化绘画)。内置七十三种画风:中国水墨、水彩、剪纸拼贴、韩国彩铅、日本动漫、编辑风手绘(Riso)、油画厚涂(梵高式流向笔触+颜料浮雕打光)、浮世绘木版画(晕色、木纹、墨线主版、青海波)、像素风(低分辨率+Bayer 抖动+像素字体)、黏土定格(高度图捏出的彩泥+影棚打光)、蓝晒(普鲁士蓝日光晒图,植物剪影透光)、十字绣(Aida 布十字绣+回针绣+缎面绣+法式结)、复古仪器面板(60 年代收音机/仪器正面:柚木、拉丝铝、旋钮、刻度窗、指示灯)、贴纸拼贴·小票(模切乙烯贴纸、热敏小票、和纸胶带、吊牌、橡皮章)、实验笔记本·贴纸(线圈方格本、铅笔图表、荧光笔、红笔圈、便利贴)、黑板板书(墨绿石板、粉笔颗粒、板擦残影、示意图与公式)、赛博朋克(雨夜霓虹街道、玻璃管霓虹招牌、全息广告、湿路面倒影)、卡通手绘(蓝铅笔稿、毛笔线、错位平涂、赛璐璐阴影、逐帧抖线)、等轴 2.5D(正等轴微缩模型、一个太阳照出三面明暗、悬浮数据卡)、单线画(一根不断开的线一笔画完、唯一点睛色)、柔光 3D(光线追踪的糖果色小球海和鼓鼓的软字、景深)、形变动画(一条轮廓依次变形、洋葱皮残影、缓动曲线)、报刊拼贴(牛皮纸、手撕旧报纸、网点老照片、勒索信拼贴字)、弥散玻璃(弥散渐变、磨砂玻璃卡片界面)、包豪斯几何(三原色几何、丝网印刷海报)、复古 Synthwave(切口落日、霓虹网格、镀铬字、录像带质感)、拼豆(钉板上的熔珠小管、熨烫熔合)、岩画(沙漠漆上凿出的凹坑图形、新旧凿痕、剥落)、古埃及墓室壁画(灰泥墙、红格起稿、分栏叙事、象形文字、剥落)、罗马马赛克(石子与玻璃沿轮廓一排排铺、灰缝、燕尾铭牌)、彩色玻璃花窗(哥特尖拱窗、通体着色玻璃、grisaille 彩绘与银染、铅条、透光)、泥金手抄本(羊皮纸、鹅毛笔哥特体、朱红标题、打磨金箔首字母)、达·芬奇手稿(铁胆墨水、左手排线、红粉笔、镜像手写、机械分解图)、剪影(黑纸剪出的侧影小像、薄金粉、椭圆金框)、凸版印刷海报(木活字、红黑双色错版、木刻插图)、苏联构成主义(红黑两版、斜条与楔形、西里尔大字、网点照片拼贴)、装饰艺术 Art Deco(1930 年代喷枪流线型海报、交替射线、阶梯高楼、金色 Deco 字)、黄金时代漫画(毛笔墨线、Ben-Day 网点、四色错版、新闻纸)、波普丝网(多格撞色平涂 + 错位的照相黑版)、ASCII 字符画(行式打印机、绿条连续纸、叠打)、低多边形(1999 年代 3D:平面着色、仿射贴图、逐顶点雾、15 位色抖动)、喷漆模板涂鸦(混凝土墙上多层卡纸模板喷绘、雾化与滴痕)、刺绣徽章(牛仔布上的机绣徽章:填充绣、缎面绣、锁边)、蓝图工程图(描图墨线晒成蓝底白线)、儿童蜡笔画(小孩在糙纸上的蜡笔涂抹)、绿屏终端 CRT(荧光字符画、扫描线、余辉)、热成像(先画温度场再上伪彩色)、代尔夫特蓝瓷砖(锡釉砖上的钴蓝手绘)、洞穴壁画(火光下的赭石、吹喷手印)、1-bit 早期画图软件(黑白整屏、8×8 图案填充)、古希腊黑绘陶瓶(黑釉剪影、刻线、饰带展开图)、铅笔素描(石墨排线、擦笔、边缘只剩线稿)、X 光片(安检透视、轮廓发亮、伪彩)、1930 年代黑白橡皮管动画(白手套、饼切眼、老胶片)、黑白麻胶版画(刻刀减法、手拓发花、套色错版)、VHS 家庭录像(钨丝灯偏色、色度渗色、REC)、扁平矢量(分层几何色块、七色、层间投影)、绘本角色动画(小角色挤压拉伸的真动画)、圆珠笔涂鸦(蓝红圆珠笔线稿、墨团、彩铅、页边涂鸦)、描图纸叠层(灯箱上的黑线底图 + 一张张单色描图纸叠片:正片叠底、套准十字、定位钉、绘图胶带)、粉彩界面 · Pastel UI(产品发布片式的界面画面:纯色粉彩底与大光斑、macOS 窗口卡片、胶囊与粗黑标题色条、状态标签与 ✓ / ✗ 徽章、放大镜、从卡片边探头的扁平小图标)、阅卷批改 · Exam Grading(绿毛毡桌上被红笔批改的答题卡:定位黑块、考号涂卡、得分格与阅卷栏、长尾夹夹住的标准答案卡、油墨不均的朱红印章、立体红笔、波浪线 / 圈 / 引线 / 批注 / 叉 / 圈起来的分数)、皮影戏 · Shadow Puppetry(油灯照亮的幕布上,雕空、透明染色的驴皮关节人偶:镂空纹样、阳刻空脸、雉翎盔头、线结与操纵杆、离幕时虚化的双影;雕花戏台、红漆金字牌匾、红灯笼)、钢笔淡彩 · Pen & Wash(速写小卡上的针管笔线稿 + 松散淡彩:线条抖、出头、不闭合,颜色错位出线、留白缝、干边与颗粒,不铺满的背景色块;大头、圆眼镜、点点眼、红鼻子的呆萌小人;卡片拍在木桌上,旁边放着针管笔和水笔)、复古水粉 · Retro Gouache(复古绘本风的水粉大头像:不透明水粉从暗到亮一层层盖上去,单色背景用干笔皴擦;大红鼻子、腮红、圆眼和大耳朵用几阶色值塑出来;看得见针脚的毛衣和毛线帽,一根根的头发和胡子,毛毡;最后是印刷书页的纸纹)、蓝调绘本 · Blue Picture Book(软蓝色调的现代绘本跨页:几乎只用粉蓝、矢车菊蓝、深青蓝三阶蓝加黑墨和纸白,只点一点珊瑚红、粉色腮红和芥末黄;毛笔 / 墨铅笔线干、抖、断,粗细不匀,线不闭合,暗部用快速来回的乱线排出来;颜色是干蜡笔、粉彩、干水粉,错位出线,纸纹的白点透出来;白粉笔痕压在蓝上,甩点和细尘;背景蓝块毛边、不到纸边;大圆脑袋、带高光的点点眼、点彩腮红和雀斑、火柴腿穿靴子的小人,乱线毛边的白色毛绒动物;最后印在书上:中缝和页码)、江南园林 · Jiangnan Garden(细笔园林春景,数字水粉插画:成千上万片叶形小笔触按一个太阳堆出树冠,暗芯、亮边、一簇簇的高光;白色和淡粉的繁花是一簇簇圆点花瓣,枝条从缝里露出来;垂柳是一绺一绺发丝般的细枝挂满小叶;黛瓦飞檐是真的瓦垄:筒瓦板瓦一行行、檐口瓦当滴水、翘起的翼角和卷起的脊头;粉墙月洞门、冰裂纹漏窗、翡翠绿槅扇和挂落、红灯笼、匾额;九曲石桥、石阶、小木船;碧绿湖面倒映岸上的一切,更柔、更暗,加涟漪和细竖纹;睡莲、白鹭;从前景花枝到雾里青山层层退远,墙上桥上落着叶影;最后一方小红印)、干刷色块 · Dry-Brush Blocks(mid-century 海报 / 水粉拼贴式的编辑插画:米白纸上几大块干笔或滚筒刷出的色块,颜色严格限定在森林绿、鼠尾草绿、青蓝、藏蓝、近黑和朱红,外加一点天蓝、淡青瓷和米色;每块颜色在自己的笔刷坐标系里刷:一道道平行的笔,起笔饱满、收笔干枯,两侧几乎是直边,两端梳成长短不一的毛齿,块里有顺笔的鬃毛纹、皴擦斑和露出来的纸色;背后的大色板用滚筒:近乎平涂、成簇的细点、干的两侧和几道细刮痕;色块像丝网套印或撕纸拼贴一样叠起来,撕口带一圈浅色纤维边;人物拆成几个大块面:亮暗两半朝不同方向刷的外套、几块肤色平面拼的头、粗黑框眼镜、干笔皴擦的白胡子;瓶子是竖刷的深色剪影加一道高光和小块标签;一旁一个小朱红方块;不勾线、不做渐变;最后像胶印:轻微柔化、纸纹、暗部零星白点、纸上细尘)、暮色微缩绘本 · Twilight Storybook(温柔、怀旧的黄昏绘本单页,满是微缩细节:大片粉彩黄昏天空,从顶上的薰衣草紫经玫瑰、蜜桃到地平线的暖金,柔和的平底云带、细细的光线和一轮低垂的淡日;一侧天空已经入夜:星空、带暗带的银河、弯月、流星,昼夜交界经过淡紫和靛蓝,不发灰;下面是一层层粉彩条纹的起伏山丘,拼布似的田、细细的垄、小圆树;前景是几万朵小野花铺成的坡,坡顶是色点,越往下越大:雏菊、矢车菊、虞美人、波斯菊、金盏花、毛茛、羽扇豆、勿忘我,夜的一侧整片变成月光蓝;很小、扁平、可爱的原创角色;上面叠一层科学图版的语言:圆形的「detail a」放大图,细墨线、排线、尺寸标注、标签和比例尺,几行灰色的小写英文手写字;最后是细颗粒、光晕、暗角和底边一道撕纸边)、排线夜景 · Hatched Nocturne(彩铅 / 色粉排线式的小幅夜景版画:天空、云、山和海全由密密的短笔触叠成,每片区域的笔触顺着同一股「风」走——天空斜着流、蒸汽绕着云团卷、山坡顺着坡向、海面横着长拖,每一笔色相和明度都差一点,笔毛分道、拖干的笔尾、纸纹里漏出的细缝,没有一处平滑渐变;深靛蓝、藏青、冷灰蓝的夜色里只有一个暖色光源,光是一层层加上去的发光笔触:核心黄白、外圈橙红、再外是被照亮的笔触,被照亮的蒸汽按「光 × 受光」上色,所以是红橙而不是粉;发光的细丝(会蜿蜒、分股、末端亮珠)、火星、星点;海面上被横向笔触打碎的倒影和光柱;几十像素高的小人靠一点亮色(围巾)点出来;最后装裱成小版画:米白纸边、压印的版痕、左下铅笔小标题、右下更小的说明,用细的普通字体)、笔记应用界面 · Obsidian UI(讲解片里的深色笔记应用窗口:近黑页面上一团淡紫光晕,窗口里有标签栏、细长图标栏、带缩进线的文件列表、粗黑 H1 下一道紫色短条、属性块和 #标签、紫色的内部链接和行内代码、带语法色的 mermaid 代码块——点「阅读」后渲染成扁平深色的流程图,一个节点亮紫——紫色左边的引用标注,右栏关系图谱里被链接的笔记亮成紫色光点;全画只有一个紫色强调色,不画官方 logo)、白板卡片 · Canvas Board(深色笔记应用的白板视图:深色页面上一扇应用窗口——红黄绿三点和「.canvas」标签页的标签栏、左边一列线性图标——里面是一块随镜头平移缩放的灰点阵无限白板;分组框和浮在框上方的组名,深色圆角卡片带 2 px 的卡片色边(红、橙、黄、绿、青、紫)和一层很淡的同色底,卡片之间是从边的中点沿法线弯出去的曲线连线,末端实心箭头、中间一块白板底色的标签;卡片里是 Markdown:标题、正文、紫色高亮、等宽行内代码、勾选清单(勾上时紫色方框弹出、对勾画出、文字变灰加删除线)、紫色竖条的引用、紫色标签胶囊、颜色编号胶囊;图片卡片上方写文件名,里面可以用手绘笔触画草图(每笔画两遍、略弯、出头,手写体批注);右上角一列缩放按钮;全画只有一个紫色强调色加卡片色;所有东西都记在白板坐标里、每次按镜头重画,任意缩放都锐利,镜头能平移缩放、卡片能掉落、连线能一点点画出来)、Flexoki 纸面 · Flexoki Paper(文档站式的图解页:暖白纸 #FFFCF0 上的墨黑字和一串暖灰,几张不描边、不投影的浅灰圆角卡片,粗黑中文标题、灰色英文类型名、等宽编号;卡片里的图照轻量图表渲染器的样子画——比底色差一级的框和 2 px 灰边(直角、圆角、胶囊、菱形、圆柱、圆)、墨线末端一个小的实心三角箭头、普通半粗体标签垫一块底色,虚线生命线和回复、带纸色缝的饼图、细网格上的柱状图、表头着色的对比表;Flexoki 的橙、红、蓝、绿、紫、青只放在有意义的地方,橙色聚焦框、黑底胶囊、字距收紧的大数字;能做成图一边一边画出来、数字滚动的动图)。用户说「claude绘图」「用代码画」「你自己画」「不用生图模型画」「程序化绘画」,或点名以上任一画风(含黏土、彩泥、定格动画、蓝晒、晒图、十字绣、刺绣、复古面板、老式收音机、贴纸、小票、收据、手帐拼贴、实验笔记本、方格本、荧光笔、便利贴、黑板、板书、粉笔、赛博朋克、霓虹、雨夜街道、卡通、手绘卡通、逐帧手绘、抖线、等轴、2.5D、微缩模型、单线画、一笔画、线条动画、柔光 3D、3D 渲染、C4D 风、软糖字、小球海、形变、变形动画、报刊拼贴、剪报、达达、勒索信字、网点印刷、弥散渐变、玻璃拟态、毛玻璃、包豪斯、几何构成、丝网印刷、Synthwave、蒸汽波、合成器浪潮、80 年代复古、拼豆、拼拼豆、熔珠、熨豆、豆豆画、钉板、烫豆、岩画、岩刻、凿刻、石刻、沙漠漆、史前壁刻、大角羊、古埃及、埃及壁画、墓室壁画、法老时代、象形文字、尼罗河、底比斯、罗马马赛克、马赛克镶嵌、镶嵌画、石子拼画、地砖画、古罗马地板、彩色玻璃、彩绘玻璃、花窗、玻璃花窗、教堂花窗、哥特花窗、铅条玻璃、泥金手抄本、手抄本、彩饰手抄本、中世纪手稿、羊皮纸、哥特体、花体首字母、泥金、贴金、星盘、达芬奇、达·芬奇、达芬奇手稿、手稿风、文艺复兴手稿、发明手稿、镜像字、镜像书写、扑翼机、红粉笔、钢笔排线、机械草图、分解图、剪影、剪影肖像、侧影、侧面像、黑纸剪影、剪影小像、椭圆金框、乔治时代肖像、摄政时期肖像、凸版印刷、活版印刷、木活字、铅字海报、马戏团海报、复古海报、老海报、19 世纪海报、双色套印、错版、套色错位、木刻插图、构成主义、苏联海报、苏联构成主义、俄国先锋派、罗德琴科风、红黑海报、照片蒙太奇、照片拼贴海报、西里尔字、装饰艺术、装饰风、流线型、流线型海报、1930 年代海报、旅行海报、铁路海报、火车海报、喷枪画、喷笔画、阶梯高楼、射线背景、盖茨比风、黄金时代漫画、老漫画、复古漫画、美漫封面、漫画封面、Ben-Day 网点、本戴点、网点上色、四色印刷、四色错版、新闻纸、对白框、拟声字、1940 年代漫画、波普、波普艺术、波普丝网、沃霍尔风、丝网版画头像、撞色头像、多格重复头像、六宫格撞色头像、ASCII、字符画、字符艺术、文字画、行式打印机、绿条纸、连续打印纸、针孔打印纸、老电脑打印、叠打、低多边形、低面数、低模、多边形风、千禧年 3D、90 年代 3D、复古 3D 游戏、老游戏截图、PS1 风、N64 风、平面着色、线框、游戏 HUD、飞行游戏、穿环、喷漆、模板涂鸦、镂空模板、喷漆模板、模板喷绘、街头涂鸦、街头艺术、墙绘、滴漆、班克西风格、刺绣徽章、徽章、布章、臂章、刺绣贴、绣标、锁边、牛仔外套徽章、户外徽章、营地徽章、弧形条章、蓝图、工程图、施工图、蜡笔画、儿童画、绿屏终端、CRT、显像管、热成像、热像仪、温度图、代尔夫特、荷兰蓝瓷砖、洞穴壁画、史前壁画、赭石、1-bit、黑白画图软件、MacPaint 风、黑绘、古希腊陶瓶、希腊瓶画、铅笔素描、素描、铅笔画、X 光、X 光片、安检图像、橡皮管动画、黑白卡通、老动画、麻胶版画、黑白版画、藏书票、VHS、家庭录像、录像带、扁平插画、扁平风、矢量插画、绘本动画、角色动画、挤压拉伸、圆珠笔、圆珠笔涂鸦、原子笔、页边涂鸦、课本涂鸦、手画棋盘、描图纸、硫酸纸、叠片、叠层、分色片、灯箱、拷贝台、透光台、套准、定位钉、粉彩界面、粉彩 UI、Dot 风、Dot 那种风格、产品发布会界面、发布会质感、窗口卡片、macOS 窗口、界面卡片、讲解片界面页、小图标探头、阅卷、阅卷批改、批改、判卷、改卷、改作业、答题卡、试卷、考卷、测验卷、红笔批改、红笔打分、打分数、盖章批改、朱红印章、标准答案卡、长尾夹、讲解片评测 / 打分页、皮影、皮影戏、影子戏、驴皮影、灯影戏、皮影人偶、雕花戏台、戏台牌匾、亮相、钢笔淡彩、淡彩、淡彩速写、钢笔淡彩小人、针管笔、勾线笔、针管笔加水彩、线稿上色、速写卡片、速写本小人、水彩小卡、城市速写、街头速写、水笔、自来水笔、复古水粉、水粉、水粉画、不透明水粉、哑光丙烯、复古绘本、绘本插画、绘本大头像、童书插画、复古童书、大头像、大鼻子人物、针织毛衣、麻花毛衣、毛线帽、毛毡帽、卷发、胡子、蓝调绘本、蓝色绘本、软蓝绘本、蓝调童书、软蓝童书插画、蓝色童书插画、蓝色系绘本、限色绘本、蓝白绘本、现代绘本跨页、手绘绘本跨页、绘本跨页、绘本内页、干笔墨线、墨铅笔线、粉彩蜡笔质感绘本、白色毛绒动物、毛绒白熊、点彩腮红、江南园林、园林春景、春水园林、中式园林插画、古典园林插画、国风园林插画、苏式园林、细笔园林、园林风景插画、水榭、临水茶榭、亭台楼阁、粉墙黛瓦、黛瓦白墙、飞檐翘角、翼角起翘、月洞门、漏窗、冰裂纹窗、槅扇、挂落、九曲桥、曲桥、垂柳园林、碧水倒影、园林倒影、睡莲池、数字水粉风景、细腻厚涂风景、干刷色块、干笔色块、干刷、干刷插画、干笔插画、滚筒刷、滚筒色块、色块插画、大色块插画、毛边色块、刷痕色块、粗刷笔触、mid-century、世纪中期插画、中世纪现代插画、复古编辑插画、复古海报插画、水粉拼贴、撕纸色块、限色海报、暮色微缩绘本、暮色绘本、黄昏绘本、微缩绘本、黄昏转夜、昼夜交界、日夜交界、半边黄昏半边星空、粉彩黄昏、粉紫晚霞、黄昏星空、银河插画、野花坡、野花草坡、花海插画、萤火虫、放风筝插画、拼布山丘、条纹田野、小圆树、细节放大图、局部放大图、技术细节小窗、科学图版风插画、手写英文小字、晚安绘本、治愈系绘本插画、排线夜景、排线风夜景、彩铅夜景、色粉夜景、粉彩排线、短笔触夜景、笔触夜空、方向笔触、夜景版画、小版画、限量版画风、版画装裱、版痕、纸边标题、铅笔题字、夜景插画、夜空插画、深蓝夜景、靛蓝夜空、冷暖对比夜景、唯一暖光、夜里的火光、发光的云、被照亮的云、红色精灵闪电、精灵闪电、火山夜景、熔岩入海、熔岩、岩浆、火山喷发插画、海上风暴、海面倒影、光柱倒影、火星飞溅、星点、看海的人、礁石上的人、远处的小人、小人比例尺、雪夜篝火、渔火、笔记应用界面、笔记软件界面、笔记 App 界面、Obsidian 风、Obsidian 界面、Obsidian 风格、黑曜石笔记、深色笔记界面、暗色主题界面、Markdown 笔记、Markdown 编辑器、双链笔记、内部链接、关系图谱、知识图谱界面、图谱视图、局部图谱、反向链接、文件列表、侧边栏、标签页、属性栏、行内代码、代码块、mermaid、mermaid 流程图、代码块渲染成图、源码 / 阅读切换、阅读视图、引用标注、callout、读书笔记界面、知识库界面、第二大脑、讲解片里的笔记应用、应用窗口演示、白板卡片、无限白板、白板视图、画布视图、Canvas 视图、Obsidian Canvas、Obsidian 白板、笔记应用白板、卡片白板、卡片和连线、节点和连线、带箭头的连线、弯曲连线、连线标签、分组框、点阵背景、点阵白板、深色白板、深色界面卡片、彩色边卡片、勾选清单卡片、待办卡片、引用卡片、图片卡片、草图卡片、手绘平面图、缩放按钮、镜头平移、镜头缩放、卡片掉落动画、连线画出来、搬家计划、旅行计划白板、活动计划白板、头脑风暴白板、项目拆解白板、计划白板、Flexoki、Flexoki 纸面、Flexoki 配色、Flexoki 风、暖白纸、米白纸面、墨黑字、文档站风格、文档页图解、技术文档配图、图解页、一页图解、讲解片图表页、几张图讲清楚、流程图、画流程图、时序图、序列图、饼图、柱状图、条形图、对比表、参数对比、图表合集、图表墙、Mermaid 风、Mermaid 图、图表渲染器、灰底圆角框、小三角箭头、橙色聚焦框、数字滚动、计时器大数字、配方图解、步骤图解、手冲咖啡图解、菜谱图解、工作流程图解),或 "draw it yourself", "paint with code", "procedural painting", "watercolor / collage / colored pencil / anime / editorial / impasto oil / ukiyo-e / pixel art / clay / claymation / cyanotype / sun print / cross-stitch / embroidery / retro instrument panel / vintage radio / sticker collage / receipt / lab notebook / graph paper / chalkboard / blackboard / cyberpunk / neon city / cartoon / hand-drawn animation / isometric / 2.5D / continuous line / one-line drawing / soft 3D / 3D render / puffy letters / ball pit / shape morph / morphing / newspaper collage / Dada / ransom note / halftone / glassmorphism / aurora gradient / Bauhaus / geometric poster / screen print / synthwave / retrowave / outrun / perler beads / hama beads / artkal / fuse beads / melty beads / pegboard beads / petroglyph / rock art / rock carving / desert varnish / Egyptian tomb painting / ancient Egypt / hieroglyphs / Theban tomb / Roman mosaic / floor mosaic / tesserae / opus vermiculatum / Pompeii mosaic / stained glass / leaded glass / church window / Gothic window / grisaille / illuminated manuscript / medieval manuscript / book of hours / gold leaf / illuminated initial / blackletter / vellum / astrolabe / da Vinci notebook / Leonardo codex / Renaissance sketchbook / mirror writing / iron-gall ink / red chalk / sanguine / ornithopter / exploded view / inventor's sketch / silhouette / silhouette portrait / cut-paper profile / shade portrait / Georgian portrait / Regency portrait / oval gilt frame / letterpress / wood type / playbill / circus poster / Victorian poster / two-colour misregistration / woodcut poster / constructivism / constructivist poster / Soviet avant-garde / Russian avant-garde / Rodchenko style / photomontage poster / art deco / streamline moderne / 1930s travel poster / railway poster / airbrush poster / sunburst rays / Gatsby style / golden age comic / vintage comic book / comic cover / Ben-Day dots / four-color printing / newsprint / speech balloon / pulp cover / pop art / Warhol-style / pop silkscreen / silkscreen portrait / repeated pop portrait grid / ASCII art / text art / typewriter art / line printer / greenbar / fanfold paper / tractor feed / overstrike / printer plot / low poly / low-poly / retro 3D / 90s 3D game / PS1 style / N64 style / software rasterizer / flat shading / affine texture mapping / vertex fog / game HUD / stencil / stencil graffiti / spray paint stencil / street art / drips and overspray / Banksy-style stencil / embroidered patch / embroidery patch / iron-on patch / sew-on patch / merit badge / camp badge / merrow border / rocker patch / denim jacket patches / blueprint / technical drawing / crayon / kid's drawing / CRT terminal / green screen / thermal camera / thermal imaging / Delft tiles / Delft blue / cave painting / ochre / Lascaux-style / 1-bit / MacPaint-style / black-figure / Greek vase / pencil drawing / graphite / X-ray / baggage scanner / rubber hose / 1930s cartoon / linocut / lino print / VHS / home video / flat vector / flat illustration / storybook animation / squash and stretch / ballpoint / biro / ballpoint doodle / margin doodles / hand-drawn board game / overlay sheets / tracing-paper overlays / light box / colour separations / registration marks / acetate overlay / pastel UI / Dot-style product film / launch-film interface / macOS window cards / exam grading / grading an answer sheet / red-pen marking / graded test paper / rubber-stamped answer sheet / shadow puppet / shadow puppetry / Chinese shadow play / leather shadow puppets / backlit puppet screen / pen and wash / pen & wash / line and wash / ink and watercolour / ink and watercolor / fineliner sketch / fineliner and watercolour / sketchbook characters / sketch cards / urban sketching / water brush / gouache / retro gouache / gouache portrait / gouache illustration / opaque gouache / matte acrylic / picture-book portrait / vintage picture book / retro children's book illustration / mid-century children's book / big-nosed character portrait / cable-knit sweater / knitted bobble hat / blue picture book / soft blue picture book / soft-blue children's book illustration / modern picture book / limited-palette picture book / picture-book spread / scratchy ink line / dry-brush ink line / ink pencil line / crayon and pastel texture / chalky white marks / blue and coral palette / fluffy white bear / Jiangnan garden / Chinese garden / classical Chinese garden illustration / Chinese water garden / spring garden illustration / lush painterly garden / waterside pavilion / moon gate / lattice windows / zigzag bridge / weeping willow garden / upturned eaves / grey-tiled roof / blossom trees and reflections / lily pond with egrets / digital gouache landscape / dry-brush blocks / dry brush illustration / dry-brushed colour blocks / roller texture / brush-textured shapes / mid-century illustration / mid-century modern poster / mid-century editorial illustration / gouache collage / torn-paper collage poster / limited palette poster / scumbled texture / vintage book cover illustration / twilight storybook / dusk picture book / dusk to night sky / day and night split sky / pastel sunset sky / Milky Way illustration / wildflower meadow / wildflower hill / patchwork hills / tiny round trees / fireflies / paper kite / magnified detail inset / detail callout circle / scientific plate overlay / handwritten lowercase captions / cozy miniature illustration / bedtime story illustration / hatched nocturne / hatched night scene / pastel hatching night / coloured-pencil nocturne / directional strokes / short brush strokes sky / night print with margins / small art print / plate mark / pencilled title and caption / indigo night with one warm light / glowing cloud lit from below / red sprites / lava entering the sea / volcano at night / glowing threads and sparks / broken reflection on the sea / tiny figures for scale / Obsidian UI / Obsidian-style note app / dark note-taking app / dark-theme Markdown editor / note app window / file explorer sidebar / wiki links / backlinks / graph view / local graph / knowledge graph UI / properties and tags / inline code / mermaid code block / mermaid flowchart rendered / source vs reading view / callout block / reading notes app / second brain UI / knowledge base screen / canvas board / infinite whiteboard / dotted board / note-app canvas view / Obsidian-style canvas / cards and connectors / curved arrows between cards / edge labels / group frames / coloured card borders / task-list card / quote card / image card with a sketch / hand-drawn floor plan / zoom controls / camera pan and zoom / cards dropping in / moving plan board / Flexoki / Flexoki paper / Flexoki palette / warm paper and ink / docs-site diagrams / explainer sheet / diagram sheet / Mermaid-style diagrams / lightweight diagram renderer / flowchart / sequence diagram / pie chart / bar chart / comparison table / diagram wall / grey-bordered boxes / small triangular arrowheads / orange focus ring / rolling numbers / recipe explainer without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。单独说「剪纸」指剪纸拼贴、「刺绣」指十字绣、「丝网印刷 / screen print」指包豪斯几何;「打马赛克」是打码,不是马赛克画风;单说「蓝图」指蓝图工程图,「蓝晒 / 晒图」仍指蓝晒;「铅笔 / 素描」指铅笔素描,「彩铅」指韩国彩铅;「像素」仍指像素风,「1-bit / 黑白画图软件」指 1-bit 早期画图软件;「霓虹」仍指赛博朋克;「喷漆 / 街头涂鸦」仍指喷漆模板涂鸦,「圆珠笔 / 随手涂鸦 / 页边涂鸦」指圆珠笔涂鸦;「描图纸 / 硫酸纸 / 叠片 / 灯箱」指描图纸叠层(蓝图工程图那张描图布是晒成蓝图的,不是叠片);「Dot 风 / 粉彩界面 / 窗口卡片 / 发布会界面」指粉彩界面(纯色底 + 白色实心窗口卡片),要磨砂玻璃和弥散渐变仍用弥散玻璃;「阅卷 / 批改 / 答题卡 / 判卷 / 红笔打分」指阅卷批改,实验记录里的红笔圈和便利贴仍用实验笔记本,带「已付」橡皮章的小票拼贴仍用贴纸拼贴 · 小票;「皮影 / 皮影戏 / 影子戏」指皮影戏(透光的彩色驴皮人偶),黑纸剪出的侧影小像仍用剪影,彩纸剪贴仍用剪纸拼贴。「钢笔淡彩 / 淡彩速写 / 针管笔加水彩 / 线稿上色的速写小卡」指钢笔淡彩;单说「水彩」仍指水彩(风景、花卉的大片晕染),蓝铅笔稿 + 毛笔线 + 赛璐璐阴影的拟人小物仍用卡通手绘,「素描 / 铅笔」仍指铅笔素描。「水粉 / 复古水粉 / 绘本大头像 / 复古童书插画」指复古水粉(不透明水粉画的特写大头像);梵高式厚涂的风景、名画感仍用油画厚涂,扁平矢量、会挤压拉伸的小角色动画(「绘本动画」)仍用绘本角色动画,针管笔线稿加淡彩的速写小卡仍用钢笔淡彩,撞色多格的头像仍用波普丝网。「蓝调绘本 / 软蓝绘本 / 蓝色童书插画 / 绘本跨页」指蓝调绘本(软蓝限色的现代绘本跨页:干笔墨线 + 干蜡笔粉彩上色 + 白粉笔痕);单说「绘本」仍指绘本角色动画,「水粉 / 绘本大头像」仍指复古水粉,「编辑风 / Riso」仍指编辑风手绘,针管笔线稿加淡彩的速写小卡仍用钢笔淡彩,小孩自己画的蜡笔画仍用儿童蜡笔画。「江南园林 / 园林春景 / 中式园林插画 / 粉墙黛瓦 / 飞檐 / 月洞门 / 九曲桥」指江南园林(细笔数字水粉的园林春景:叶形小笔触堆出的繁茂树冠、繁花、垂柳、黛瓦飞檐、碧水倒影、层层远山);单说「水墨 / 山水」仍指水墨,单说「水彩」仍指水彩,动漫背景 / 赛璐璐天空仍指日本动漫,浮世绘仍是浮世绘;梵高式厚涂的风景仍用油画厚涂,皮影人偶的一场戏仍用皮影戏。「干刷色块 / 干笔色块 / 滚筒色块 / mid-century 海报插画」指干刷色块(米白纸上几大块干笔或滚筒刷出的限色色块,人物拆成几个大块面,背后一块纯色板、一旁一个小红方块);单说「水粉 / 绘本大头像」仍指复古水粉,「剪纸 / 彩纸拼贴」仍指剪纸拼贴,「丝网印刷 / screen print」仍指包豪斯几何,「Riso / 编辑风」仍指编辑风手绘,没有笔触的平滑几何色块仍用扁平矢量。「暮色微缩绘本 / 暮色绘本 / 黄昏转夜 / 昼夜交界 / 野花坡 / 细节放大图」指暮色微缩绘本(粉彩黄昏转入银河夜空、拼布山丘、几万朵小野花、很小的原创角色,加圆形放大图和手写小字);单说「绘本」仍指绘本角色动画,「蓝调绘本 / 软蓝绘本」仍指蓝调绘本,赛璐璐天空和夏日少年感仍用日本动漫,大片晕染的风景仍用水彩,整页的机械分解手稿仍用达·芬奇手稿,剖面和施工图仍用蓝图工程图。「排线夜景 / 彩铅或色粉夜景 / 短笔触夜空 / 夜景小版画 / 熔岩入海 / 精灵闪电 / 被照亮的云」指排线夜景(满画面顺着风向的短笔触、深蓝夜色里只有一个暖光、发光的丝和火星、碎的倒影、很小的人,装成带纸边和铅笔字的小版画);梵高式的厚涂漩涡和颜料浮雕仍用油画厚涂,明亮可爱的彩铅甜品仍用韩国彩铅,黑白石墨排线仍用铅笔素描,粉彩黄昏转入银河星空、满坡小野花仍用暮色微缩绘本,霓虹雨夜街道仍用赛博朋克。「Obsidian 风 / 笔记应用界面 / 深色笔记软件 / 双链笔记 / 关系图谱 / mermaid 代码块渲染成图」指笔记应用界面(深色主题的笔记应用窗口:文件列表、Markdown 正文、代码块切到阅读视图渲染成流程图、亮紫光点的关系图谱,只有一个紫色强调色);明亮的粉彩底和白色窗口卡片仍用粉彩界面,点阵无限白板上的卡片和弯曲连线用白板卡片,暖白纸面上的浅灰卡片图表用 Flexoki 纸面,磨砂玻璃和弥散渐变仍用弥散玻璃,绿屏荧光字符的老终端仍用绿屏终端 CRT,霓虹全息的未来界面仍用赛博朋克。「白板卡片 / 无限白板 / Canvas 视图 / 卡片和连线 / 点阵白板 / 分组框 / 带箭头的弯曲连线」指白板卡片(深色应用窗口里随镜头平移缩放的点阵白板:分组框、彩色边卡片、带箭头和标签的弯曲连线、清单 / 引用 / 草图卡片、右上角缩放按钮);笔记正文页、文件列表和关系图谱仍用笔记应用界面,暖白纸上的流程图、时序图和图表仍用 Flexoki 纸面,明亮的粉彩产品界面和检查结果仍用粉彩界面,一层层叠起来的图解仍用描图纸叠层。「Flexoki / Flexoki 纸面 / 暖白纸上的图解页 / Mermaid 那样的流程图、时序图、饼图、柱状图、对比表 / 讲解片里的图表页」指 Flexoki 纸面(暖白纸、墨黑字、不描边的浅灰圆角卡片,卡片里的图照轻量图表渲染器画:灰边框、墨线小三角箭头、普通标签,强调色只点在有意义的地方);手写粉笔的示意图仍用黑板板书,铅笔图表、荧光笔和便利贴仍用实验笔记本,彩色粉彩底、macOS 窗口和 ✓ / ✗ 徽章的产品界面仍用粉彩界面,深色笔记应用窗口仍用笔记应用界面,点阵无限白板上的卡片和连线仍用白板卡片,系统的微缩模型仍用等轴 2.5D,剖面和施工图仍用蓝图工程图。---# Claude 绘图@@ -84,6 +84,9 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型| 干刷色块 · Dry-Brush Blocks | `lib/drybrush.py` · `DryBrushBlocks` | `examples/drybrush_noodle_counter.py` 面馆 · Noodle Counter(一张 4:3 的 mid-century 海报:小面馆柜台前,一位白色平头、粗黑框眼镜、白胡子的老人,穿藏青工装,一手用筷子从碗里挑起面,一手扶着碗;外套亮的一半是青蓝、暗的一半近黑,两半朝不同方向刷,袖子顺着胳膊刷;头是几块肤色平面:亮面、本色、暗面,更暗的鼻侧和暖色鼻头、腮红、暖色的耳朵;手是从拇指一侧看的几条手指,手腕露一截米色袖口;碗里是面、一块红油和葱花;身后一大块滚筒刷的鼠尾草绿色板,右边柜台上一个醋瓶、一个酱油瓶和一杯茶,衬着一块青蓝色块;米白纸上大片留白,右下一个小朱红方块;照参考海报的做法画:纸 → 大色块 → 几块面的外套和袖子 → 头 → 眼镜、胡子、筷子、近处的手 → 静物 → 红方块 → 印刷;`--stages` 出 7 个阶段加成品:纸、色块、外套、头、细节、静物、红方块) | 约 5 秒 || 暮色微缩绘本 · Twilight Storybook | `lib/twilight.py` · `TwilightStorybook` | `examples/twilight_paper_kite.py` 夜的边上 · The Kite at the Edge of Night(2000×1100 的一页黄昏绘本:一个穿蓝色毡子斗篷、软帽尖带绒球、圆脸点点眼、戴黄手套的原创小角色坐在野花坡顶上,把一只纸风筝放向天空入夜的地方;左边是粉彩黄昏:薰衣草紫、玫瑰、蜜桃、暖金,柔和的云带、细细的光线,一轮淡日正落到雾紫色的远山后面,一群飞鸟、几颗飘着的蒲公英种子;右边已经入夜:满天星、带暗带的银河、弯月、一颗流星,远山上一间小屋亮着一扇窗;中间是粉彩条纹的拼布山丘和小圆树,前景几万朵野花,入夜的一侧变成月光蓝,坡顶衬着天空几丛带穗的高草,花间有蝴蝶和蜻蜓;角色身边一罐萤火虫照亮一圈草,萤火虫往暗处飘;天空中间一个圆形「detail a」放大图,引线连到风筝上,用细技术图的画法画风筝骨架交叉处的绑扎和提线结(排线、ø 6 标注、标签、比例尺);两行小写手写字「the evening waits for us.」「just a little further.」;照顺序画:黄昏天空 → 夜 → 山 → 花坡 → 角色和风筝 → 萤火虫 → 图版和手写字;`--stages` 出 6 个阶段加成品:黄昏天空、夜、山、花坡、角色和风筝、萤火虫) | 约 2 秒 || 排线夜景 · Hatched Nocturne | `lib/nocturne.py` · `Nocturne` | `examples/nocturne_lava_sea.py` 熔岩入海 · Lava Meets the Sea(一张装在米白纸边里的 16:9 小幅夜景版画:黎明前的火山海岸,熔岩从深色的火山坡上一缕缕淌下来,蜿蜒、分股,到海边散成一片细流,流进海里的地方是全画唯一的暖光——海水被激成蒸汽,一柱云团往上翻、顺风往左歪,从下往上被照亮:水边黄白,往上橙红,再往上是暖灰,到顶上是冷的石板蓝;火星往上飞,坡上几处停住的熔岩前锋还亮着小珠;海面上一条被横向笔触打碎的暖色光柱一直拉到画面底边,云团的红光也碎碎地映在水里;远处一座低矮的岛,海中间的一块小礁石上坐着两个看它的人(四十来像素高),其中一个围着红围巾;靛蓝的天空顺着风斜着流,零星几颗星;天、云、山、海全是顺着各自方向的短笔触,每笔色相明度都差一点,留着底色的细缝;画心外一道压印的版痕,左下铅笔小字「Forty seconds」,右下更小的「lava meeting the sea before dawn」;照画家的顺序画:纸和深色底、天空、远岛和火山、冷色的蒸汽、亮光(被照亮的云、天空和山坡上的光笔触、热源)、熔岩细流和火星、海、倒影、礁石和小人、装裱和题字;`--stages` 出 9 个阶段加成品) | 约 9 秒 |+| 笔记应用界面 · Obsidian UI | `lib/obsidianui.py` · `ObsidianUI` | `examples/obsidianui_reading_notes.py` 小王子 · 读书笔记 · Reading Notes(讲解片里的一帧笔记应用:#161616 的近黑页面,左上一团淡紫光晕;窗口里是标签栏「小王子 · 狐狸」(当前标签底边打开,和笔记连成一片)、细长图标栏、文件列表(展开的「2026 读书」挂一条缩进线,「小王子」高亮)、面包屑「2026 读书 / 小王子」和右侧边栏;笔记里粗黑 H1「小王子」下一道带辉光的紫色短条,属性块「标签 #童话 #读书笔记」「读完 2026-10-12」,两行正文:紫色的内部链接「狐狸」「驯养」、行内代码「建立联系」、加粗的「彼此需要」;一个 mermaid 代码块逐行敲出(语法色、紫色块状光标跟着行尾走),指针点「源码 / 阅读」切到阅读视图,渲染成流程图「陌生 —花时间→ 驯养 → 彼此需要 → 独一无二」,「驯养」亮紫并加一圈外环;下面是紫色左边的引用标注「狐狸说」;右栏「局部关系图谱」:书里的人物和地点是灰点灰线,这篇笔记链接到的四篇(小王子、狐狸、玫瑰、驯养)亮成紫色光点、连线变紫,下面三条反向链接,右下角浮着状态栏;`--accent` 可换强调色;`--stages` 出 93 个阶段加成品,会动的东西拆成中间姿态) | 约 0.5 秒(加 `--stages` 约 5 秒) |+| 白板卡片 · Canvas Board | `lib/canvasboard.py` · `CanvasBoard` | `examples/canvasboard_moving_plan.py` 搬家计划 · Moving Plan(深色页面左上一片淡紫光,一扇深色应用窗口:标签栏上红黄绿三点和标签页「搬家计划.canvas ×」,左边一列线性图标,右上角一列缩放按钮 + − 适合窗口 ?;窗口里是灰点阵的无限白板,三个分组框,组名浮在框上方。「收拾 · 第 1 周」:紫边、带淡紫光圈的选中卡片「搬家计划」——老城区 → 河边新家,「11 月 8 日 · 周六 · 还有 12 天」里后半句压着紫色高亮,三个紫色标签胶囊;红边清单「先清掉的东西」,三项打了紫色勾、变灰加删除线,两项还空着;组外一张散放的采购卡和紫色进度条「已买 2/3」。「搬家当天 · 11/8」:时间线卡,一根竖线串起 08:00 → 13:30 四个时间点,最后一个是紫点、「新家卸货」压紫色高亮;黄边卡片「箱子编号」,四个颜色胶囊 厨房 K1–K6(橙)、书房 S1–S9(青)、卧室 B1–B5(绿)、易碎 ×4(红)。「新家 · 河边 3 楼」:图片卡片「新家平面图.png」,深色方格纸上手绘的平面图——墙、门的开启弧线、窗、卧室里绿色的床、客厅里青色的书桌、厨房橙色的台面、手写体房间名,一条紫色虚线从大门画到床边,旁边手写「床先进卧室」;紫色竖条的引用卡「先把床装好,其他的明天再说。」;绿边清单「第一晚要用的」,底下一行「都装在 `B1` 箱」。四条弯曲连线带箭头和标签:紫色「当天」、灰色「装箱」「13:30」、绿色「B1 先开」;`--stages` 出 121 个阶段加成品:卡片一张张掉落、打勾、连线画出、镜头平移到下一组、平面图一笔笔画出、指针点「适合窗口」后拉远到整块白板) | 约 0.6 秒(`--stages` 约 26 秒) |+| Flexoki 纸面 · Flexoki Paper | `lib/flexoki.py` · `FlexokiPaper` | `examples/flexoki_pour_over.py` 一杯手冲咖啡 · Pour-over, in Five Diagrams(暖白纸 #FFFCF0 上的一页图解:左上黑底胶囊「图解 · 手冲咖啡」、粗黑大标题「一杯手冲咖啡」和灰色英文 Pour-over, in five diagrams,右上灰胶囊「总时长」和大字 2:30;五张不描边的浅灰圆角卡片排成两行(右边一列和上一行共用一条缝),每张有粗黑中文标题、灰色英文类型名和等宽编号:① 流程图「从豆子到一杯」:称豆 15 g → 研磨 · 中细 → 冲洗滤纸 → 闷蒸 30 g 水,往下到菱形「鼓包平了?」,绿色「是」→ 分两段注水 → 胶囊形「出杯」,红色「否」沿一条倒圆角的折线绕回闷蒸;② 时序图「两分半里发生了什么」:水壶 / 滤杯 / 分享壶三条虚线生命线、滤杯上的激活条、左边一列等宽时间 0:00 0:45 1:15 2:30、三次注水、浅黄便签「排气 · 45 s」、虚线回复「约 210 g 咖啡液」;③ 柱状图「磨多细,滴多久」:粗 / 中 / 中细 / 细四根青色柱,选中的中细是橙色,柱顶写时间;④ 饼图「240 g 水分三次」:30 / 120 / 90 g 三块(橙、蓝、绿),块之间是纸色的缝,块上写 1/8 1/2 3/8,旁边图例;⑤ 对比表「三种冲法」:手冲 / 法压壶 / 意式(表头前橙、紫、青三个小圆点)× 方式、研磨、时间、口感,手冲一列套橙色圆角框;底下一行灰色小字写配方并注明数字是示意;`--stages` 出 151 个阶段加成品:标题升起,五张卡片暗着升起,再一张张亮起、套上橙色聚焦框,图一边一边画出来——框弹出,线画过去再落下箭头,消息飞过去,右上的计时器从 0:00 走到 2:30,柱子长高、数字跟着滚,饼图顺时针扫开,表格一行行滑进来) | 约 0.3 秒 |各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。@@ -157,7 +160,10 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型- 中国古典园林、江南春景、亭台楼阁和水、旅行与城市文化里的「园林 / 古镇 / 春天」,节气和节日(春分、清明、谷雨)的配图和海报,要繁茂、细腻、一眼就是「精心画出来的插画」的风景,讲解片里的「中国传统 / 生活美学 / 春天」页 → 江南园林(要留白的写意山水用水墨;要大片松散的晕染用水彩;要赛璐璐天空和夏日少年感用日本动漫;要木版套色和海浪用浮世绘;要皮影人物的一场戏用皮影戏);- 人物和日常小场景(吃一碗面、喝茶、做手艺、街坊小店)、杂志 / 书籍 / 唱片的复古封面、餐饮和饮品海报,要「色少而准、有手感、有态度」的编辑插画和 mid-century 海报感,讲解片里「这个人 / 这家店 / 这一口」的特写页 → 干刷色块(要剪刀剪的彩纸童趣用剪纸拼贴;要不透明水粉一层层塑形的大头像用复古水粉;要 Riso 网点和套色错版用编辑风手绘;要三原色几何的丝网海报用包豪斯几何;要干净、没有笔触的矢量色块用扁平矢量);- 温柔、怀旧、带一点点孤独的小故事和情绪(「一天结束了」「出发」「再走一点点」),晚安故事、童书封面和插页,季节和节日的夜晚(夏夜、萤火虫、星空、七夕、中秋),原创小角色或吉祥物的「远方」主视觉,要在一张画里同时放「风景 + 一个零件 / 一个结 / 一处构造的放大图 + 手写小字」的讲解页 → 暮色微缩绘本(要软蓝限色、乱线墨线的绘本跨页用蓝调绘本;要真的动起来的小角色用绘本角色动画;要赛璐璐天空和夏日少年感用日本动漫;要大片松散晕染的风景用水彩;要整页的机械分解手稿用达·芬奇手稿);-- 夜里的一个瞬间:一处火光、闪电、极光、篝火、渔火、熔岩、烟花,配一大片深蓝的天和水,要一眼就是「手画的小幅版画」、有满画面的笔触感和一点孤独,讲解片里的「一个极短的瞬间」「远处发生的大事」「自然现象」页,文章配图和海报 → 排线夜景(要梵高式厚涂漩涡和颜料浮雕用油画厚涂;要粉彩黄昏转入银河、满坡野花用暮色微缩绘本;要霓虹雨夜街道用赛博朋克;要黑白石墨排线用铅笔素描;要明亮可爱的彩铅小物用韩国彩铅)。+- 夜里的一个瞬间:一处火光、闪电、极光、篝火、渔火、熔岩、烟花,配一大片深蓝的天和水,要一眼就是「手画的小幅版画」、有满画面的笔触感和一点孤独,讲解片里的「一个极短的瞬间」「远处发生的大事」「自然现象」页,文章配图和海报 → 排线夜景(要梵高式厚涂漩涡和颜料浮雕用油画厚涂;要粉彩黄昏转入银河、满坡野花用暮色微缩绘本;要霓虹雨夜街道用赛博朋克;要黑白石墨排线用铅笔素描;要明亮可爱的彩铅小物用韩国彩铅);+- 讲解片里讲「笔记 / 知识库 / 双链 / Markdown / 代码块怎么变成图」的那一页,或任何要「在一个像真的深色应用窗口里演示一个操作」的画面:文件列表、标题和正文、代码块切到阅读视图渲染、关系图谱亮起来,一屏讲清一件事 → 笔记应用界面(要明亮的粉彩底和白色窗口卡片用粉彩界面;要点阵白板上的卡片和连线用白板卡片;要暖白纸面上的图表用 Flexoki 纸面;要磨砂玻璃和弥散渐变用弥散玻璃;要绿屏荧光字符用绿屏终端 CRT);+- 计划和想法之间的关系,「把几张卡片摆在一块白板上、用箭头连起来」的整理:旅行 / 搬家 / 活动计划、读书和研究笔记的脉络、头脑风暴、项目拆解、评论区里的一问一答,讲解片里「白板上一步步摆出来、镜头跟着移过去」的页 → 白板卡片(要笔记正文、文件列表和关系图谱用笔记应用界面;要暖白纸上的流程图和图表用 Flexoki 纸面;要明亮的粉彩产品界面用粉彩界面;要一层层叠起来的图解用描图纸叠层);+- 讲解片、文档、教程里的「图表页」:步骤和流程、时间线上的往来、占比、对比,要像文档站或技术博客里的图——暖白纸、墨黑字、浅灰圆角卡片,图像 Mermaid 渲染出来那样干净(灰边框、墨线小三角箭头、普通标签),一页放几张图讲清一件事(一份配方、一个工作流程、一次部署、一组产品数字),还能做成「图一边一边画出来、数字滚动」的动图 → Flexoki 纸面(要手写粉笔的示意图用黑板板书;要铅笔图表和便利贴的实验记录用实验笔记本;要彩色粉彩底和 macOS 窗口的产品界面用粉彩界面;要深色笔记应用窗口用笔记应用界面;要点阵白板上的卡片和连线用白板卡片;要系统的微缩模型用等轴 2.5D)。每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。@@ -1204,6 +1210,45 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 收尾:`mount(plate, depth)`、`caption(text, x, y, size, anchor, weight='light'|'thin', alpha, jitter)`、`bloom(amount)`、`grain(amount)`;`render()`、`composite()`、`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度。- 颜色用 `PAINTS` 里的名字(paper pencil ground night indigo navy dusk haze starlight mist slate steam steam_lit rock rock_lit sea sea_deep glint blood ember lava flame core scarf star warmstar)或 '#rrggbb';色阶用 `RAMPS` 里的名字(fire ember sky sea steam land isle)或自己给一串颜色。+**笔记应用界面 `ObsidianUI`**:+- 思路:讲解片里的一帧笔记应用(默认深色主题)。近黑页面(#161616)上一两团淡紫光晕;窗口是一整套深灰(笔记区 #1e1e1e、边栏和标题栏 #202020、发丝分隔线 #363636),只有一个强调色(默认紫 #8a5cf5,浅色字用 #a88bfa):H1 下的短条、#标签、内部链接、开关选中的那一段、亮起的流程图节点、关系图谱里被链接的笔记。所有圆角矩形、圆、环、线和线性图标都是有符号距离场,1 px 解析抗锯齿(像素中心取 i + 0.5,整数坐标的边是锐利的);自由多边形(鼠标指针、箭头、菱形节点)4 倍超采样再 BOX 缩小。阴影按 CSS box-shadow 的语义算(偏移、模糊半径 σ = blur / 2、扩展、颜色、不透明度,只画在元素外面),偏移为 0 就是亮卡片和 H1 短条的紫色辉光;`halo()` 是柔和的径向光(图谱亮点)+- 图层:和粉彩界面一样,一切画进有名字的图层(预乘 RGBA,收尾时裁到画过的范围),`layer(name, z)` 开始往某层画(再次调用会重新打开),z 小的在后面,`end()` 之后画在页面上。每层有姿态 `pose(name, dx, dy, scale, alpha, reveal, mode, origin, feather)`:位移、绕 origin 缩放、不透明度、揭开(reveal 0–1,软边 feather px)——`mode='x'` 从左往右(敲字)、`'y'` 从上往下、`'r'` 从 origin 往外长成一个圆(关系图谱从当前笔记长出来);`show / hide` 只改不透明度;`bounds(name)`。同一样东西的两种状态(源码 / 阅读的开关、灰 / 亮的图谱、普通 / 亮起的节点)画成两层,用 show / hide 切换。`stage(name)` 按当前姿态合成快照(PNG 压缩存在内存里)+- 构造:`ObsidianUI(W, H, seed, keep_stages=True, accent='violet'|'blue'|'teal'|'amber'|'rose'|(强调色, 浅色字))`;`page(colour, glows=[(cx, cy, rx, ry, alpha), …])` 页面和光晕(closest-side 的线性衰减,用强调色)+- 形状:`rrect(x0, y0, x1, y1, r, fill, alpha, ring, inset)`(ring=w 只画边)、`circle(cx, cy, r, fill, alpha, ring)`、`line(pts, width, fill, alpha, closed)`、`poly(pts, fill, alpha)`、`shadow(x0, y0, x1, y1, r, dx, dy, blur_px, spread, colour, alpha, shape=(cx, cy, r))`、`soft_shadow(cov, box, dx, dy, blur_px, colour, alpha)`(任意遮罩的 drop-shadow)、`halo(cx, cy, r, colour, alpha, power)`、`with clip(x0, y0, x1, y1, r):` 把里面画的东西裁进圆角矩形+- 文字:`text(s, x, y, size, fill, weight='regular'|'medium'|'semibold'|'bold'|'heavy', anchor, alpha, spacing, family='sans'|'mono', halo, halo_fill)`,返回宽度;中英文自动分段(macOS:中文苹方、H1 的 heavy 用兰亭黑 Heavy、西文 SF Pro 可变字重、代码 SF Mono;其他系统 Noto Sans CJK / 微软雅黑;可用 `INKPAINT_FONT_OBSIDIAN_<CJK|HEAVY|LATIN|MONO>` 指定);anchor 的第二个字母 s 基线 / m 中文字身中线 / t 字身顶;`halo=px` 先描一圈 halo_fill 色的边(图谱标签:连线到字前就断开);`measure(…)` 量宽度;`rich(x, base, runs, size, fill)` 排一行笔记正文:runs 是 `[(文字, 样式), …]`,样式 None 正文 / 'b' 加粗提亮 / 'link' 内部链接(强调色字)/ 'code' 行内代码(等宽红字压在圆角深色小底上)/ 'hl' 强调色高亮 / 'faint' / 'accent' / 'tag',返回行尾 x+- 窗口:`window(x, y, w, h, tabs, active, side=300, right=0, bar=52, ribbon=52, radius=14, ribbon_icons, lit_icon)` 返回 Box(`.bar`、`.explorer`、`.note`、`.right`、`.tabs`):阴影和 1 px 外圈、标题栏红黄绿三点、标签页(当前标签上圆角、底边打开,和笔记区连成一片;后面一个 +)、图标栏(底部帮助和设置)、文件列表栏(side 含图标栏,0 = 没有)和右侧边栏(right 宽,0 = 没有)的底色与分隔线;`explorer(win, items, active, size, row)` 文件列表:顶上一排小工具图标,items 是 `(名字, 层级, 'open'|'folder'|'file')`,展开的文件夹下挂一条缩进线,`active` 那行高亮;`view_header(win, crumbs)` 前进后退箭头、居中的面包屑(最后一节提亮)和右端更多;`toggle(x, y, w, h, labels=('源码', '阅读'), on)` 分段开关;`sidebar_tools(win, icons, lit)` 右栏顶上的小图标,返回下面的 y;`status_bar(win, items)` 窗口右下角浮着的状态栏+- 笔记:`h1(x, base, s, size, bar, bar_w, bar_gap, draw_text)`(粗黑标题 + 带辉光的紫色短条,bar=False / draw_text=False 只画一样,好分两层);`heading(x, base, s, size, marker)` H2(marker=True 带灰色 ##);`tag(x, cy, s, size)` #标签胶囊,返回右边缘;`prop(x, cy, glyph, key, key_w)` 属性行的图标和键名,返回值的起点;`code_block(x, y, w, lines, size, lang='mermaid', pad, lh, draw)` 深色代码块(1 px 边、圆角 10、右上角语言名),返回 Box,带 `.bases`(各行基线)、`.tx`、`.lh`,`draw=False` 只画框;`code_line(x, base, toks, size)` 一行代码,toks 是 `[(文字, 'kw'|'str'|'num'|'op'|'cm'|'fence'|'text' 或 '#rrggbb'), …]`,返回行尾 x;`caret(x, base, size)` 块状光标;`callout(x, y, w, title, lines, size, title_size, colour, glyph='quote')` 引用标注(16 % 底色、4 px 左边、图标和粗体标题,正文每行是 rich 的 runs),返回 Box;`checkbox(x, y, size, checked)` 任务勾选框+- 阅读视图里的图:`dnode(cx, cy, w, h, label, shape='rect'|'round'|'stadium'|'diamond', hi, size, focus)` 扁平深色节点(2 px 灰边、文字居中;hi 是强调色那一个,focus 再加一圈外环和辉光),返回 Box;`dedge(pts, width, colour, head, label, size, label_at)` 灰线加小实心三角箭头,可在 label_at 处放一个深色小标签(mermaid 的 `-->|标签|`)+- 关系图谱:`graph(nodes, links, lit, label_size, only='grey'|'lit', bg)`:nodes 是 `(x, y, r, 名字)`,links 是 `(i, j)`,lit 里的节点亮成强调色、带径向光,两端都亮的连线才变紫、加粗;only 只画灰的或亮的那一半,放两层好淡入;单个用 `gnode(x, y, r, label, lit, label_size, glow, bg)`、`glink(a, b, lit)`+- 指针:`cursor(x, y, scale=1.4, click)` 白色鼠标指针(深色描边、软投影),click 0–1 画一圈扩散的点击环+- 线性图标:`glyph(name, cx, cy, size, fill, sw)`(`GLYPHS`:menu search file files plus grid graph canvas calendar terminal gear help back fwd chev_d chev_r edit folder_plus sort collapse list layout bars link tag hash book eye quote more check x star)+- 色板常量 `PAGE BG BG2 BG3 SIDE BORDER BORDER2 TEXT BRIGHT MUTED FAINT ACCENT ACCENT2 CODE_BG CODE_TEXT INLINE SYNTAX NODE_FILL NODE_EDGE NODE_LINE LINK GNODE ACCENTS`;`render()`、`composite()`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度++**白板卡片 `CanvasBoard`**:+- 思路:深色笔记应用的白板视图(片子里那种 Canvas 的样子,不画任何官方 logo)。和别的画风不同,调用画图方法时什么都不栅格化:每个形状都按**白板坐标**记进一个有名字的节点(分组、卡片、连线……),`render()` 时按镜头把所有节点重画一遍,所以任意平移缩放都是锐利的矢量和字。点阵长在白板上(跟着镜头移动、缩放),窗口、标签栏、图标栏和右上角的缩放按钮不动。圆角矩形、圆、环和线条是有符号距离场、1 px 解析抗锯齿;折线逐段只算自己的包围盒,一条 64 段的连线、几百段的手绘草图也很快;箭头和指针是 4 倍超采样的多边形;阴影按 CSS box-shadow 的语义算。+- 节点和动画:`node(name, kind, z)` 开始往某节点记(再次调用就重新打开;z 默认 分组 0、连线 5、卡片 10、其他 20)。`pose(name, dx, dy, scale, alpha, origin)`:位移(白板像素)、绕中心缩放、不透明度(小于 1 时整个节点先画进一层再合成);`set(name, **vars)` 设进度变量、`reset(name)` 清掉(没设的变量默认 1 = 已完成,卡片的 `lift` 默认 0);`show / hide`。每个形状都可以带 `var='名字'` 或 `var=('名字', a, b)`(变量从 a 到 b 映射成它自己的 0–1),`mode` 决定进度做什么:fade 淡入 / draw 沿长度画出 / reveal 从左往右揭开 / pop 回弹放大。+- `tween(tag, n, ease, moves=[(节点, 起, 止)], cam=(起镜头, 止镜头), cam_ease='io', between, last)` 出 n 个阶段:中间帧 `mv_<tag>1 …` 和最后的 `<tag>`;起止字典里位姿键(dx dy scale alpha)和变量混着写,止为 None 就是归位、完成;镜头 x、y 线性,缩放按几何插值。缓动 `EASE`:linear out io back drop(drop 先加速落下、再回弹 6 % 落定,卡片掉落用它)。+- 构造:`CanvasBoard(W, H, seed, keep_stages=True, stages_dir=None, window=(x, y, w, h), tab='xx.canvas', ribbon=True, controls=True, glow=True)`(给了 `stages_dir`,`stage()` 当场写 PNG);`camera(x, y, z)` 白板上的点 (x, y) 在窗格正中、缩放 z;`fit(x0, y0, x1, y1, pad, right)` 返回刚好装下这块区域的镜头(right 给缩放按钮多留的像素);`to_screen(x, y)` 白板点 → 画布像素;`control(i)` 第 i 个缩放按钮的中心(0 加、1 减、2 适合窗口、3 问号),`hover = i` 高亮它;`cursor(x, y, click, alpha, press)` 鼠标指针(click 0–1 是紫色点击波纹),`cursor()` 收起。+- 白板对象:`group(name, x, y, w, h, label, colour)` 分组框(圆角 20、2 px 线、极淡的一层白,组名浮在左上角上方;变量 frame / label);`card(name, x, y, w, h, colour, label, selected, pad=(24, 22), fill, tint=0.05)` 卡片:圆角 12、2 px 卡片色边(`CARD_COLOURS`:red orange yellow green cyan purple,也可以 'accent' 或十六进制,None 是灰边)加 5 % 同色底、软阴影,`label` 是写在卡片上方的文件名;`selected=True` 紫边加一圈淡紫光(变量 sel);变量 `lift` 加一层「举在白板上方」的大阴影。`image_card(name, x, y, w, h, label, bg, grid)` 图片卡片(没有内边距、深色方格纸),画里面的图:`cb.node(name)` 后 `with cb.clip(card):`。`edge(name, a, b, colour, width=4, label, dashed, arrow, bend)` 连线:锚点是 (卡片名, 'l' 'r' 't' 'b'[, 沿边的位置 0–1]) 或 (x, y, 边),三次曲线沿两条边的法线出入(控制距离 = 两端距离 × 0.45,夹在 50–240),末端实心箭头,正中一块白板底色的标签;变量 p 把它画出来,最后 14 % 长出箭头,过半后标签淡入。+- 卡片里的 Markdown(`card()` 返回 `Card`,从上往下排,`Card.y` 是下一块的顶):`h1`、`h2(glyph=)`、`p(s, size, fill, weight, hl, x)` 一行行内 Markdown(`==高亮==` 是紫色底、`` `代码` `` 是深底等宽、`**粗体**`;`hl=` 一个变量让高亮扫过去)、`task(s, done, key, lh)` 勾选清单(key 变量 0 → 1:紫色方框弹出、对勾画出、删除线划过、文字变灰)、`quote(lines, size, by)` 紫色竖条的引用、`tags([...])` 紫色标签胶囊、`chips([(名, 编号, 颜色)])` 颜色编号胶囊、`bar(frac, label)` 进度条、`rule()` 分隔线、`gap(px)`。这些也能用 `cb.rich / task / tag / chip` 直接画在任意位置(比如时间线卡里自己排)。+- 形状(白板坐标,记进当前节点):`rrect(x0, y0, x1, y1, r, fill, alpha, ring, inset)`(拉远时细线不细过 1 屏幕像素)、`circle`、`line(pts, width, fill, dash=(实, 虚))`、`poly`、`shadow`、`text(s, x, y, size, fill, weight, anchor, family='sans'|'mono'|'hand')`(anchor 第二个字母 s 基线 / m 中文字身中线 / t 顶,返回宽度)、`glyph(name, cx, cy, size)`(`GLYPHS`:menu search file plus minus grid fit help check x link image)、`measure`、`with clip(...)`。手绘:`rough(pts, width, fill, closed, rough, passes=2, dash)` 每段是一条略弯、两头出头一点的线,画两遍(第二遍淡一些);`rough_rect`、`rough_ellipse(cx, cy, rx, ry, a0, sweep)`(圆或弧,收笔处略微搭过头)、`arrow_head(tip, 方向角)`。+- 字体:苹方 + SF Pro 可变字重 + SF Mono,中西文自动分段;family='hand' 用手札体(Hannotate SC,没有就退回苹方);字号是浮点的,镜头拉近拉远时字连续变大变小;可用 `INKPAINT_FONT_CANVASBOARD_<CJK|BOLD|LATIN|MONO|HAND>` 指定。+- 色板常量 `PAGE BG BG2 BG3 SIDE BORDER BORDER2 TEXT BRIGHT MUTED FAINT ACCENT ACCENT2 BOARD DOT EDGE CODE_BG CODE_FG DONE CARD_COLOURS`;`render()`、`composite()`、`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度。++**Flexoki 纸面 `FlexokiPaper`**:+- 思路:文档站式的图解页,配色是 Flexoki(「墨在纸上」的一套配色):暖白纸 #FFFCF0、墨黑 #100F0F 的字、一串暖灰(50 #F2F0E5 卡片底、100 #E6E4D9 轨道和表头、150 #DAD8CE 细线、200 #CECDC3 边框、300 #B7B5AC 最淡的字、500 / 600 次要的字),八种强调色各两档(600 写字、400 填色)。纸上是不描边、不投影的浅灰圆角卡片(半径 28),粗黑中文标题、灰色英文类型名、等宽编号;卡片里的图照轻量图表渲染器(Mermaid 那一类)的画法:框比它的底色差一级、2 px 灰边,2.4 px 墨线末端一个小的实心三角箭头,普通半粗体标签。强调色只放在有意义的地方。+ - 形状:圆角矩形、圆、环、胶囊、菱形(精确的菱形距离场)、圆柱(身子加上下两个椭圆,顶上椭圆的下沿也描边)、饼图扇形和折线都是有符号距离场,1 px 解析抗锯齿(像素中心取 i + 0.5);箭头和其他自由多边形 4 倍超采样再 BOX 缩小。+ - 线:折线带弧长——`p` 画到全长的几成(切口仍是圆头),`dash` 沿弧长画虚线(平头),在箭头下面截短一截,箭头的尖就是最后一个点。`curve(a, b, da, db, k)` 是渲染器那种按切线方向出入的三次曲线,`rounded(pts, r)` 是拐角倒圆的折线(回环边),`bezier(p0, p1, p2, p3)` 直接给控制点。+ - 组:一个框(底、边、字)先合成一组再按不透明度放下,弹出时(0.85 → 1 倍、淡入)字和框一起缩放、一起变淡,像 SVG 的 `<g opacity>`。+ - 字:中文苹方(粗黑用 Semibold 加 size/50 px 的描边假粗,接近思源黑 Black 那种标题),西文 SF Pro 可变字重(大数字字距收紧 0.03 em),等宽 SF Mono;其他系统冬青黑体 / Noto Sans CJK / 微软雅黑和 Helvetica / DejaVu;可用 `INKPAINT_FONT_FLEXOKI_<CJK|HEAVY|LATIN|MONO>` 指定。字重 regular / medium / semibold / bold / heavy。+ - 图层:和粉彩界面一样,一切画进有名字的图层(预乘 RGBA,收尾时裁到画过的范围),每层有姿态 `pose(name, dx, dy, scale, alpha, reveal, origin, feather)`、`show / hide`、`bounds(name)`、`with clip(...)`;`layer(name, z, fresh=True)` 先清空再画,用来按进度重画(线画到一半、数字滚到中间、饼图扫到一半、柱子长到一半),逐边画出的动图就是这样做的。`fresh=True` 不改姿态:开头 `hide()` 过的层要 `show()` 才看得见。+- 构造:`FlexokiPaper(W, H, seed, keep_stages=True, theme='light'|'dark')`,先 `paper()`。`ground` 是图画在什么颜色上(边上标签垫的底、饼图的缝、框的默认底色都看它):`paper()` 设成纸色,`panel()` / `window()` 设成卡片色;框的默认底色比 `ground` 差一级(纸上用浅灰,浅灰卡片上用纸色)。+- 页面部件:`chip(x, cy, text, fg, bg, size, anchor, weight, glyph=None|'dot'|'check')` 胶囊(默认黑底纸色字),返回 Box;`heading(x, base, zh, en, size, en_size)` 粗黑中文加同一基线的灰色英文;`number(x, base, s, size=104, fill, anchor, track=-0.03)` 大数字(计数、计时、度量);`panel(x, y, w, h, r=28, tone='surface'|'paper'|'dark', title, tag, num, title_size, pad)` 卡片和标题行,返回带 `.inner`(标题下面的内容区)的 Box;`focus(box, colour=ORANGE4, width=4, r, out)` 内嵌的聚焦框;`step(x, cy, label, lit, size, accent, mute)` 步骤胶囊(暗 → 亮,勾随 lit 画出来);`meter(x0, x1, cy, frac, colour, h)` 胶囊轨道和填充;`window(x, y, w, h)` 纸色窗口(3 px 灰边、浅灰标题栏、三个灰点),返回带 `.body` 的 Box;`dashed_rect(x0, y0, x1, y1, r)` 虚线圆角框;`dimension(x0, x1, y, label)` 宽度标注(两端虚线,中间标签垫底色);`code(x, base, tokens, size, mark)` 一行等宽代码((文字, 颜色) 片段,mark 那段垫一块浅橙)。+- 渲染器:`node(cx, cy, w, h, label, shape='rect'|'round'|'stadium'|'diamond'|'cyl'|'circle', size=22, p, fill, stroke, sw=2, fg, weight)`,w × h 是整个外框(菱形是两条对角线),label 里 `\n` 换行,p 是弹出进度;返回 Node(`side('l'|'r'|'t'|'b', gap)` 边的中点 / 菱形的顶点,`toward(x, y, gap)` 朝某点出边的位置)。`edge(pts, p, head=True, dash, width=2.4, colour, head_len=11, head_w=10.4, label, label_t, label_size, label_fill, label_bg)`:线过了 label_t 才出标签,p 过 0.94 才落下箭头。另有 `head(x, y, deg)`、`line(pts, width, fill, alpha, p, dash, cap)`、`rrect`、`circle`、`poly`、`shadow`(CSS box-shadow,只给一张抬起的卡片用)、`text`、`measure`。+- 时序图:`lifeline(x, y0, y1, p)`、`activation(x, y0, y1, w=14, p)`、`message(x0, x1, y, label, p, reply)`(标签居中写在线上方,reply 是虚线)、`note(x0, y0, x1, y1, text, p)`(浅黄便签)。+- 图表:`pie(cx, cy, r, values, colours, sweep, gap=3, labels, label_r)` 从十二点顺时针,`sweep` 0–1 扫开,块之间是 gap px 的底色缝;`legend(x, y, items=[(颜色, 名字, 数值)], size, pitch, value_x, alpha)`(alpha 可以每行一个);`bars(x0, y0, x1, y1, values, labels, colours, vmax, ticks, tick_fmt, p, value_fmt, bar_w, value_colours)`(p 可以每根一个,柱顶数值按 p 滚动);`table(x, y, widths, n_rows, row_h, head_h, header, dots)` 画框和表头,返回 Table(`cell(i, j)`、`col(j)`、`box`),`table_row(t, i, cells, colours, weights)` 画一行(每行可以放一层)。+- 色板常量 `PAPER BG2 UI UI2 UI3 TX3 TX2 TX1B INK`、`BASE50 … BASE950 BLACK`、`RED RED4 ORANGE ORANGE4 YELLOW YELLOW4 GREEN GREEN4 CYAN CYAN4 BLUE BLUE4 PURPLE PURPLE4 MAGENTA MAGENTA4`、`ACCENTS SERIES THEMES PALETTE`;颜色也可以写强调色的名字('orange' 是 400 档,'orange6' 是 600 档);`mix(a, b, t)`;`render()`、`composite()`、`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度。+**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。## 三、毛病清单(都真实出现过)@@ -2337,6 +2382,45 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask| 两个小人在深色海面上看不出来 | 他们身后加一小片浅色波光(横向短笔,只在礁石外),剪影才立起来;小人 40–44 px,围巾是唯一的亮色 || 熔岩路径有 NaN | float32 里 sin(π) 是一个很小的负数,`** 0.8` 得到 NaN:先 clip 到 0–1 |+**笔记应用界面**++| 问题 | 改法 |+|---|---|+| 关系图谱里连线从标签字上穿过去(「狐狸」「B612」「点灯人」),字发花 | 标签先描一圈 3 px 的栏底色再写字(`text(halo=3)`),连线到字前就断开;节点尽量摆在让连线从上方或侧面进来的地方 |+| 「六颗星球—小王子—蛇」两条边几乎在一条直线上,看着像一根线横穿中心节点 | 中心两侧的节点不要摆在同一条直线上:两边都往下挪(+40 / +22 px),两条边成一个浅 V |+| 关系图谱「长出来」时第二帧就铺满七成,像直接冒出来 | 圆形揭开的缓动从 ease-out 改成 ease-in-out,6 步 → 7 步,软边 40 px |+| 动图里点「阅读」看不出点了一下:紫色的点击环压在紫色按钮上 | 点击环改成很浅的淡紫白(#ece4ff)、半径 34、3.5 px,三帧从 0.4 倍放大到 1.15 倍渐隐;按钮同时轻压(0.97)再弹起(1.06) |+| 动图脚本自检报 EOFError | 最后一个阶段(状态栏)和成品完全一样,Pillow 把相同的帧合并了:量化后和屏上完全相同的帧不单独存,时长并到上一帧 |++**白板卡片**++| 问题 | 改法 |+|---|---|+| 红边卡片的底发褐,像一块旧木板 | 卡片色底从 7 % 降到 5 %(`tint`),边框才是颜色的主角 |+| 卡片下半截空着一大块,另一张卡的最后一行压到了边框外 | 卡片高度跟着内容走:`Card` 每块返回顶边、`Card.y` 是下一块的位置,先排内容再定高度;清单行距 1.62 → 1.72 |+| 时间线的竖线看不见 | #4a4a4a、2.5 px 拉远到 0.72 倍就没了:改成 #4d4d4d、3 px,灰点 #6a6a6a,最后一个点紫色加一圈淡紫 |+| 「13:30 到」这样的连线标签盖住了大半条短连线 | 组和组之间只有 120–160 白板像素:标签缩成「13:30」,连线两端挪到卡片边的 0.84 / 0.7 处,让它弯出一段 S 形 |+| 平面图的手写批注「床先进卧室」压在虚线路线的弯道上;挪到书桌旁边,又像在说书桌 | 放到路线起点旁边(大门外、平面图底边下面),和左下角的「约 68 m²」排在同一行 |+| 卡片「掉落」用回弹缓动,第一张中间帧就走完 78 %,看着是弹出来不是掉下来 | 新缓动 drop:先按 (u / 0.72)² 加速落下,再回弹 6 % 落定;起点抬高 110、放大 5 %、半透明、带大阴影 |+| 散放卡片掉落时镜头一起下移,镜头也跟着回弹 | `tween()` 的镜头单独用 `cam_ease`(默认 io) |+| 引用卡的字跟着回弹一起揭开,回弹那一下字又缩回去一点 | 卡片落定后再单独把两行字写出来(`quote` 阶段) |+| 动图里镜头平移的帧留下一块块淡淡的残影和竖条 | 分组框的底(#212121)、卡片的影子和白板(#1c1c1c)只差约 5 级,落在「没变」的 7 级容差里,镜头移开后这些像素没重发:镜头在动的帧容差 1 级,其他中间帧 6 级、关键帧 2 级 |+| 动图 1.51 MB,超了 | 固定 Bayer 抖动让每个镜头帧整片重编:白板是平的、没有色带,去掉 Bayer;平移 7 → 6 帧、下移 5 → 4 帧、拉远 8 → 7 帧,1.36 MB;修残影后 1.47 MB |+| 出阶段时峰值内存 0.78 GB | 拉远时每一帧都要一个新的浮点字号,字体缓存一直长:超过 160 个就清空,峰值约 0.62 GB |++**Flexoki 纸面**++| 问题 | 改法 |+|---|---|+| 粗黑标题用苹方 Semibold 太细,不像那种黑体 Black 的标题;兰亭黑 Heavy 够粗但字形不一样 | 苹方 Semibold 加 size/50 px 的描边假粗(62 px 的标题约 1.2 px),西文用 SF Pro 800 |+| 图例数值用 SF Mono,「30 g」读成「30 g」,数字和单位隔得太开 | 图例数值默认用普通字体,等宽只留给编号、时间刻度和代码 |+| 时序图左边的时间列用最淡的 #B7B5AC,像装饰而不是信息 | 改成 #878580、medium;最淡的灰只留给编号和坐标刻度 |+| 两行卡片的缝对不上(第一行分在 1000 / 1024,第二行分在 616 / 640 和 1136 / 1160),满屏的缝东一条西一条 | 时序图卡片和对比表卡片都做成 640 宽,右边一列共用 1136 / 1160 这一条缝;流程图卡片因此宽到 1016,第一行框间距从 50 px 放到约 89 px |+| 流程图第二行两条边一长一短(122 / 158 px) | 「分两段注水」放在「出杯」右边和菱形左顶点的正中,两条边一样长 |+| 动图自检报 EOFError:动作做完后的停留阶段和最后一个动作帧一模一样,Pillow 把相同的帧合并了 | 量化后整帧都没变的帧不单独发,把它的时长加到上一帧上 |+| 动图里大片纸色差几级(末帧误差中位数 2) | Pillow 按调色板量化时查的是缩减过的色立方:改成 numpy 精确找最近色(每种颜色算一次、缓存),离 Flexoki 色 2 级以内的直接用那个颜色 |+| 动图里红色「否」、浅黄便签、紫色小圆点的边缘变成橙色和灰色(单点误差到 49 级) | 这些饱和的中间色面积太小,中值切分分不到:留 60 个色位只从饱和、又不贴近 Flexoki 色的像素里切;误差超过 20 级的像素 478 → 166 |+## 四、做成动画- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。@@ -2396,6 +2480,21 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 调色板:第一帧(纸和平涂的深色底)只给 12 色;228 色从和它不同的像素切(末帧 ×3),按夜景的需要加权:深蓝 ×2(占满画面,色位不够时排线变成一块块平色、天顶到地平线出色带)、饱和的暖色 ×3(熔岩、被照亮的云、倒影)、浅米色 ×1.5(题字后面的纸);再留 14 色,其中 3 个是强制的(最深的底色藏青、题字的铅笔灰、白热的芯),另外 11 色只从末帧误差最大(> 16 级)的像素里切。- 固定 4×4 Bayer。和屏上已显示颜色差不到 7 级(叠化帧)或 4 级(关键帧)的像素沿用上一帧,末帧精确发送。- 结果:55 帧、14.75 秒、约 1.18 MB,按解码结果逐帧自检,末帧 p99 误差 18。+- 笔记应用界面的动图(脚本在 `claude_drawing/obsidianui_work/make_gif_obsidianui.py`):+ - 阶段:近黑页面和光晕 → 窗口带回弹升起 → 文件列表 → 面包屑、源码 / 阅读开关、右栏图标 → H1 从左往右写出、紫条拉出 → 属性块 → 两行正文逐行揭开 → 代码块的框 → 五行 mermaid 逐行敲出、紫色块状光标跟着行尾走 → 指针滑到「阅读」、点下(点击环扩散,按钮轻压再弹起,开关切到阅读)→ 源码淡出 → 流程图一个个弹出节点、连线从左往右画出 → 「驯养」亮紫、加外环 → 引用标注升起 → 关系图谱从当前笔记往外长出来(圆形揭开)→ 被链接的四个节点和连线亮成紫色 → 反向链接 → 状态栏。+ - 会动的东西不用叠化:范例里 `move()` 给每样东西几个缓动 / 回弹的中间姿态,存成 `mv_*` 阶段,动图里硬切(一般 50 毫秒一帧,敲代码 70、写正文 60、亮紫 80);其余阶段用 70 毫秒的帧叠化。+ - 调色板:先强制放进主题的 38 个精确色(各级深灰、紫色和它在深灰上的几种叠色、语法色、红黄绿三点),其余 217 色按加权样本中值切分(成品 ×8、饱和像素 ×5);固定 4×4 Bayer(近黑页面上的淡紫光晕不出色带),没变的像素记成品红透明;量化后和屏上完全相同的帧并进上一帧的时长。+ - 结果:116 帧、14.78 秒、约 0.33 MB,按解码结果逐帧自检,末帧 p99 误差 10。+- 白板卡片的动图(脚本在 `claude_drawing/canvasboard_work/make_gif_canvasboard.py`):+ - 阶段:空的点阵白板 → 分组框淡入 → 卡片一张张掉落(举起时抬高、放大 5 %、半透明、带大阴影,加速落下、回弹落定)→ 高亮扫过、清单逐条打勾 → 镜头下移,采购卡落下、进度条走满 → 镜头平移到「搬家当天」,紫色连线先画出来、分组框淡入,时间线卡落在箭头上,四个时间点依次出现 → 第二条连线画出、箱子编号卡落下、四个颜色胶囊依次出现 → 镜头平移并拉近到平面图,图片卡落下,平面图按 墙 → 门窗 → 家具 → 手写房间名 → 紫色虚线路线和批注 一笔笔画出 → 镜头下移,引用卡落下、两行字写出,绿色连线画出、清单卡落下、打勾 → 指针移到右上角「适合窗口」按钮、按下(按钮高亮、紫色波纹)→ 镜头拉远到整块白板(成品)。+ - 会动的东西都是 `tween()` 出的 `mv_*` 阶段,动图里硬切(50–95 毫秒,镜头帧 65 毫秒);关键阶段停 100–520 毫秒,成品停 2.6 秒。+ - 调色板:48 个界面色强制占位(白板、点、卡片底和四种淡色底、边框、几种文字灰、紫色、六种卡片色、草图墨色、颜色胶囊的底);其余按加权样本中值切分(饱和像素 ×5、末帧 ×6),再从饱和像素里单独切 40 色。不用 Bayer。没变的像素记成品红透明;「没变」的容差:镜头在动的帧 1 级、其他中间帧 6 级、关键帧 2 级、成品 0。+ - 结果:122 帧、14.62 秒、约 1.47 MB,按解码结果逐帧自检。+- Flexoki 纸面的动图(脚本在 `claude_drawing/flexoki_work/make_gif_flexoki.py`):+ - 阶段:空纸 → 黑底胶囊和大标题升起 → 灰色的「0:00」和「总时长」→ 五张卡片暗着(42 % 不透明)两帧一张地升起,配方小字淡入 → 第一张亮起、套上橙色聚焦框,流程图一边一边画出来(框弹出:0.85 → 1 倍并淡入;线顺着弧长画过去,到头再落下箭头;「是」「否」在线经过时出现)→ 聚焦框移到时序图:三个参与者弹出、生命线往下画、消息一条条飞过去、激活条跟着长、便签弹出,右上的计时器跟着消息从 0:00 走到 2:30 → 柱状图:四根柱错开长高,柱顶的时间跟着滚 → 饼图顺时针扫开,图例一行行淡入、克数滚上去 → 对比表升起,四行从左往右滑进来,手冲一列的橙框缩进来 → 聚焦框淡出 → 成品。+ - 会动的都是真的中间帧:范例按进度重画内容层(`layer(name, fresh=True)`),阶段名带 `~` 的每帧 60 毫秒硬切、不叠化,带 `@毫秒` 的是停留,成品停 2.6 秒。+ - 调色板:28 个 Flexoki 色强制占位,离它们 2 级以内的像素直接用它们(大片纸色和卡片色一级不差,也不闪);167 色按全部关键帧(末帧 ×6)中值切分,不贴近 Flexoki 色的像素(文字和线的抗锯齿边)×3;60 色只从饱和的中间色里切。最近色用 numpy 精确查(Pillow 的查表差几级)。不加抖动(纸面上没有渐变)。没变的像素记成品红透明,整帧没变的帧并进上一帧的时长。+ - 结果:138 帧、13.73 秒、约 0.58 MB,按解码结果逐帧自检,末帧 p99 误差 4。- 绘本角色动画的动图是真动画,不是阶段叠化:`Storybook.gif()` 按时间逐帧渲染,720×405、15 fps(GIF 延时只能写厘秒,按累计取整写成 7、7、6 厘秒交替),共用一张加权调色板 + 固定 4×4 Bayer,没变的像素记成品红透明,151 帧(动作 9.95 秒 + 末帧停 1.4 秒)约 0.56 MB;范例加 `--gif out.gif` 出这张,`--stages` 的关键帧仍可喂给上面的阶段动图工具。- 形变动画可以直接出真动画:`Morph.at(keys, T)` 给出全局时间 T 的轮廓,逐帧渲染即可。- 更细的逐笔动画:把一组笔画单独画到透明层上导出,再用 Motion Canvas 遮罩按顺序显现。这个还没做成现成接口。@@ -2474,6 +2573,9 @@ lib/jiangnan.py 江南园林(叶形小笔触的 id 图光栅化:Pillolib/drybrush.py 干刷色块(笔刷坐标系:遮罩转到笔触方向再算、再转回;周期的鬃毛条纹 / 干笔齿 / 滚筒细点 / 梳齿边 / 笔道 / 斑驳纹理;一道道平行的笔或打断的短笔:起笔饱满、收笔干枯、梳齿般的两端、近直的两侧、皴擦、顺笔两侧的干擦边、多遍覆盖、同笔混色、蘸满的笔;滚筒大色板和细刮痕;部分撕口带纤维边的纸片;沿路径的干笔和散撒的短干笔;几块面拼的人物:头、眼镜、白胡子、外套、袖子、手;瓶、碗、杯;朱红小方块;胶印收尾:柔化、纸纹、暗部白点、细尘)lib/twilight.py 暮色微缩绘本(被噪声扰动成软层的六段黄昏渐变、透镜形云带、光线和淡日;羽化的夜度场:按它铺夜空、银河、星星和月亮,交界补饱和度,后面受光的东西按它压成月光蓝,发光的东西不受影响;解析的银河带和暗带、幂律星场、亚像素溅射、四芒星、弯月、流星;远山、拼布条纹山丘、细垄、树篱、小圆树;按透视拒绝采样的花坡:八种花和草叶,按根部排序一次光栅化进 id 图;小斗篷角色、萤火虫罐、风筝和随天色变色的风筝线、萤火虫、蝴蝶、蜻蜓、蒲公英种子、飞鸟、带穗高草;3 倍图上的细墨线、排线、尺寸标注、比例尺、淡彩、圆形放大图;逐字母抖动的手写小字;柔化、光晕、颗粒、暗角、撕纸边)lib/nocturne.py 排线夜景(直方图均衡的纸纹与沿 8 个方向拖开的纸纹;在方向场里积分出中心线的短笔触:落笔钝、收笔尖、带一点弯;id 图光栅化:Pillow 按序号填轮廓、2 倍超采样,numpy 逐像素查回这一笔的位置和方向,算出沿笔 / 横向坐标、6 道笔毛的深浅与含量、越往笔尾越干、颜料只落在纸纹低于压力处;每笔的明度抖动和绕灰轴的色相旋转;风向、放射、等高线方向场与双倍角混合;点光源和发光遮罩合成光照图,加光(screen)或「光 × 受光」上色的光笔触,暖白化;放射笔触的热源;带惯性游走的蜿蜒细流、分股、支流、结壳的亮度和前锋亮珠,2 倍浮点发光缓冲与紧贴的光晕;抛物线火星、零星火星、星点;镜像取样的碎倒影、光柱;笔触画的剪影和朝光轮廓光、几十像素高的坐着的小人和围巾;米白纸边、纤维、胶带边、压印版痕、细体铅笔小字;画心内的克制辉光、细颗粒)+lib/obsidianui.py 笔记应用界面(近黑页面与淡紫光晕;距离场抗锯齿的应用窗口:标签页、图标栏、带缩进线的文件列表、面包屑、分段开关、浮动状态栏;CSS 式多层阴影与零偏移辉光;苹方 / 兰亭黑 Heavy / SF Pro / SF Mono 自动分段,带底色描边的标签字;一行正文的富文本(加粗、内部链接、行内代码、高亮、#标签)与属性行;带语法色的代码块、逐行图层和块状光标;引用标注、任务勾选框;阅读视图的扁平流程图节点与带标签的箭头连线;关系图谱的灰点灰线与紫色亮点径向光;鼠标指针与点击环;可换的单一强调色;带姿态的图层:位移、缩放、不透明度、横向 / 纵向 / 圆形揭开)+lib/canvasboard.py 白板卡片(保留式绘制:所有形状按白板坐标记进有名字的节点,每次按镜头重画;距离场抗锯齿的圆角矩形、圆、环,逐段只算包围盒的折线和虚线,4 倍超采样的多边形,CSS box-shadow;节点的位姿和进度变量(fade / draw / reveal / pop),tween 出中间阶段,drop 缓动;随镜头移动缩放的点阵;应用窗口、标签栏、图标栏、缩放按钮、鼠标指针和点击波纹;分组框、卡片色边和淡色底、选中光圈、举起的大阴影、图片卡片和方格纸;行内 Markdown(高亮、行内代码、粗体)、会打勾的清单、引用、标签胶囊、颜色胶囊、进度条;沿法线出入的三次曲线连线、箭头和标签;手绘抖线、椭圆和弧、箭头;苹方 + SF Pro + SF Mono + 手札体,浮点字号)+lib/flexoki.py Flexoki 纸面(Flexoki 色板与角色名、浅色 / 深色主题;有符号距离场的圆角矩形、圆、环、精确菱形、圆柱、扇形与折线,1 px 解析抗锯齿;带弧长的折线:按进度画出、沿弧长虚线、在箭头下截短,三次曲线、按切线出入的曲线、倒圆角折线;4 倍超采样的小三角箭头;先合成再放下的节点组;苹方加假粗的粗黑标题、SF Pro 可变字重、SF Mono;带姿态的图层与 fresh 重画;卡片、聚焦框、胶囊、步骤胶囊、大数字、轨道条、窗口、虚线框、宽度标注、代码行;流程图的框和边、时序图的生命线 / 激活条 / 消息 / 便签、饼图、图例、柱状图、表格)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/canvasboard_moving_plan.jpg b/examples/canvasboard_moving_plan.jpgnew file mode 100644index 0000000..57afa7cBinary files /dev/null and b/examples/canvasboard_moving_plan.jpg differdiff --git a/examples/canvasboard_moving_plan.py b/examples/canvasboard_moving_plan.pynew file mode 100644index 0000000..e2bef20--- /dev/null+++ b/examples/canvasboard_moving_plan.py@@ -0,0 +1,230 @@+"""Example (canvas board): 搬家计划 / Moving Plan — a dark, dotted infinite whiteboard in a note app's canvas view.++The app window (tab 「搬家计划.canvas」, a ribbon of line icons) and in it a board of grey dots seen through a camera.+Three groups, labels floating above them: 「收拾 · 第 1 周」 holds the plan card (violet, selected: 搬家计划, 老城区 → 河边新家,+the date with a highlight, tag pills), a red checklist of what goes before the move (three ticked and struck through,+two still open) and a small shopping card with a progress bar; 「搬家当天 · 11/8」 holds a timeline (08:00 → 13:30, a+violet dot on the last stop) and a yellow card of box numbers -- colour chips 厨房 K1–K6, 书房 S1–S9, 卧室 B1–B5, 易碎 ×4;+「新家 · 河边 3 楼」 holds an image card 「新家平面图.png」 (a floor plan sketched with hand-drawn strokes on dark grid paper:+walls, doors, windows, a bed in the bedroom's green, a desk in the study's cyan, the kitchen counter in orange, a violet+dashed route from the front door to the bed), a quote card (先把床装好,其他的明天再说。) and a green checklist for the+first night. Curved edges with arrowheads and labels tie the cards together; the zoom buttons sit top right.+The stages drop the cards in one by one, tick the tasks, draw the edges on while the camera pans from group to group,+sketch the floor plan stroke by stroke, and finally click 「fit」 and zoom out to the whole board. No image model.+python3 canvasboard_moving_plan.py [out.jpg] [--stages DIR]+"""+import os, sys, time+import numpy as np+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from canvasboard import (CanvasBoard, ACCENT, ACCENT2, TEXT, BRIGHT, MUTED, FAINT, EDGE, BORDER2, CARD_COLOURS as CC)++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'canvasboard_moving_plan.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+T0 = time.time()+tick = lambda name: print(f'{name:14s} {time.time() - T0:5.1f}s') if os.environ.get('CANVASBOARD_TIMING') else None++cb = CanvasBoard(1920, 1080, seed=8, keep_stages=bool(stages), stages_dir=stages, window=(40, 34, 1840, 1012),+ tab='搬家计划.canvas')+ROOM = {'kitchen': 'orange', 'study': 'cyan', 'bed': 'green', 'fragile': 'red'}++# ===================================================================== group 1 · 收拾 (and a loose card under it)+cb.group('gA', 0, 0, 640, 724, '收拾 · 第 1 周')+A1 = cb.card('A1', 30, 36, 580, 262, colour='purple', selected=True)+A1.h1('搬家计划', 54)+A1.gap(2)+A1.p('老城区 → 河边新家', 30, BRIGHT, 'medium')+A1.p('11 月 8 日 · 周六 · ==还有 12 天==', 26, MUTED, hl='hl')+A1.gap(12)+A1.tags(['#搬家', '#待办', '#11月'])++A2 = cb.card('A2', 30, 338, 580, 356, colour='red')+A2.h2('先清掉的东西')+A2.gap(2)+for i, (s, done) in enumerate([('旧书 → 捐给社区图书馆', True), ('书桌 → 挂到二手群', True), ('冬衣 → 真空压缩袋', True),+ ('冰箱提前一天断电', False), ('宽带、水电改到新地址', False)]):+ A2.task(s, done, key=f't{i}', lh=1.72)++A3 = cb.card('A3', 30, 808, 580, 114)+A3.p('纸箱 30 个 · 胶带 6 卷 · 记号笔', 26, TEXT)+A3.gap(8)+A3.bar(2 / 3, 10, ACCENT, label='已买 2/3', var='buy')++# ===================================================================== group 2 · 搬家当天+cb.group('gB', 800, 170, 620, 836, '搬家当天 · 11/8')+B1 = cb.card('B1', 830, 206, 560, 452)+B1.h2('时间线')+TL = [('08:00', '搬家师傅到楼下'), ('09:30', '先搬大件:床、沙发、冰箱'), ('11:00', '装车,按编号点箱子'), ('13:30', '==新家卸货==')]+ty0, tdy = B1.y + 36, 78+cb.node('B1')+cb.line([(B1.left + 9, ty0), (B1.left + 9, ty0 + tdy * 3)], 3, '#4d4d4d', var=('tl', 0.0, 0.85))+for i, (tm, what) in enumerate(TL):+ y = ty0 + i * tdy+ last = i == len(TL) - 1+ v = ('tl', i / 4, (i + 1) / 4)+ if last:+ cb.circle(B1.left + 9, y, 16, ACCENT, 0.25, var=v, mode='pop')+ cb.circle(B1.left + 9, y, 8.5, ACCENT if last else '#6a6a6a', var=v, mode='pop')+ cb.text(tm, B1.left + 40, y, 24, ACCENT2 if last else MUTED, 'medium', 'lm', family='mono', var=v, mode='fade')+ cb.rich(what, B1.left + 136, y, 28, TEXT, var=v, hl=('hl', 0, 1))+cb.end()+B1.y = ty0 + tdy * 3 + 30+B1.rule(10)+B1.p('4 位师傅 · 1 辆厢式车 · 约 3 小时', 24, MUTED)++B2 = cb.card('B2', 830, 702, 560, 270, colour='yellow')+B2.h2('箱子编号')+B2.gap(6)+B2.chips([('厨房', 'K1–K6', ROOM['kitchen']), ('书房', 'S1–S9', ROOM['study']),+ ('卧室', 'B1–B5', ROOM['bed']), ('易碎', '×4', ROOM['fragile'])], 26, var=[('chip', i / 4, (i + 1) / 4) for i in range(4)])+B2.p('一共 24 箱,两面都写上编号', 22, MUTED)++# ===================================================================== group 3 · 新家+cb.group('gC', 1580, 0, 740, 1050, '新家 · 河边 3 楼')+C1 = cb.image_card('C1', 1610, 64, 680, 430, label='新家平面图.png')+X0, Y0 = C1.x0, C1.y0+U = lambda u, v: (X0 + u, Y0 + v)+INK, INK2 = '#d4d4d4', '#9a9a9a'+strokes = [] # (fn, weight in the drawing order)+++def S(fn, w=1.0):+ strokes.append((fn, w))+++# outer walls (with gaps for the front door and two windows), inner walls, doors, windows, furniture, labels, route+S(lambda v: cb.rough([U(250, 372), U(50, 372), U(50, 50), U(110, 50)], 4.2, INK, seed=1, rough=1.35, var=v), 1.4)+S(lambda v: cb.rough([U(282, 50), U(430, 50)], 4.2, INK, seed=2, rough=1.35, var=v), 0.6)+S(lambda v: cb.rough([U(562, 50), U(612, 50), U(612, 372), U(318, 372)], 4.2, INK, seed=3, rough=1.35, var=v), 1.4)+S(lambda v: cb.rough([U(362, 50), U(362, 150)], 3.4, INK, seed=4, rough=1.35, var=v), 0.4)+S(lambda v: cb.rough([U(362, 202), U(362, 268)], 3.4, INK, seed=5, rough=1.35, var=v), 0.4)+S(lambda v: cb.rough([U(362, 330), U(362, 372)], 3.4, INK, seed=6, rough=1.35, var=v), 0.3)+S(lambda v: cb.rough([U(362, 222), U(612, 222)], 3.4, INK, seed=7, rough=1.35, var=v), 0.6)+S(lambda v: cb.rough([U(492, 222), U(492, 290)], 3.4, INK, seed=8, rough=1.35, var=v), 0.3)+S(lambda v: cb.rough([U(492, 336), U(492, 372)], 3.4, INK, seed=9, rough=1.35, var=v), 0.3)+for (u0, u1, sd) in [(110, 282, 10), (430, 562, 11)]: # windows: a double thin line in the gap+ S(lambda v, u0=u0, u1=u1, sd=sd: (cb.rough([U(u0, 45), U(u1, 45)], 1.6, INK2, seed=sd, passes=1, var=v),+ cb.rough([U(u0, 55), U(u1, 55)], 1.6, INK2, seed=sd + 20, passes=1, var=v)), 0.5)+S(lambda v: (cb.rough([U(318, 372), U(318, 318)], 2.2, INK2, seed=12, passes=1, var=v), # front door + swing+ cb.rough_ellipse(*U(318, 372), 66, 54, 1.6, INK2, a0=180, sweep=90, passes=1, seed=13, var=v)), 0.5)+S(lambda v: (cb.rough([U(362, 150), U(410, 150)], 2.2, INK2, seed=14, passes=1, var=v), # bedroom door+ cb.rough_ellipse(*U(362, 150), 48, 52, 1.6, INK2, a0=0, sweep=90, passes=1, seed=15, var=v)), 0.4)+S(lambda v: cb.rough_rect(*U(480, 74), *U(592, 186), width=3.2, fill=CC['green'], seed=16, var=v), 0.8) # bed+S(lambda v: (cb.rough([U(480, 100), U(592, 100)], 2.2, CC['green'], seed=17, passes=1, var=v),+ cb.rough_rect(*U(492, 81), *U(530, 96), width=2.0, fill=CC['green'], passes=1, seed=18, var=v),+ cb.rough_rect(*U(542, 81), *U(580, 96), width=2.0, fill=CC['green'], passes=1, seed=19, var=v)), 0.5)+S(lambda v: cb.rough_rect(*U(70, 74), *U(190, 116), width=3.0, fill=CC['cyan'], seed=20, var=v), 0.6) # desk+S(lambda v: cb.rough_ellipse(*U(130, 140), 15, 15, 2.4, CC['cyan'], seed=21, var=v), 0.3) # chair+S(lambda v: cb.rough([U(376, 240), U(376, 356), U(470, 356)], 3.0, CC['orange'], seed=22, var=v), 0.6) # counter+S(lambda v: cb.rough([U(398, 240), U(398, 334), U(470, 334)], 2.0, CC['orange'], seed=23, passes=1, var=v), 0.4)+S(lambda v: (cb.rough_rect(*U(80, 286), *U(222, 338), width=2.6, fill=INK2, seed=24, var=v), # sofa+ cb.rough([U(80, 300), U(222, 300)], 1.8, INK2, seed=25, passes=1, var=v)), 0.6)+S(lambda v: cb.rough_ellipse(*U(150, 236), 24, 24, 2.2, INK2, seed=26, var=v), 0.3) # tea table+for (s, u, v_, sz) in [('客厅', 222, 178, 30), ('卧室', 410, 104, 28), ('厨房', 430, 296, 26), ('卫', 552, 296, 26),+ ('书桌', 130, 96, 22), ('床', 536, 146, 24)]:+ S(lambda v, s=s, u=u, v_=v_, sz=sz: cb.text(s, *U(u, v_), sz, INK2 if len(s) > 1 or s == '卫' else BRIGHT, 'regular',+ 'mm', family='hand', var=v), 0.25)+ROUTE = [U(300, 412), U(300, 340), U(292, 262), U(318, 196), U(376, 176), U(432, 166), U(470, 150)]+S(lambda v: cb.rough(ROUTE, 3.0, ACCENT2, seed=27, passes=1, rough=0.6, dash=(14, 10), var=v), 1.4)+S(lambda v: (cb.arrow_head(U(474, 148), -22, 16, ACCENT2, var=v),+ cb.text('床先进卧室', *U(324, 404), 26, ACCENT2, 'regular', 'lm', family='hand', var=v)), 0.4)+S(lambda v: cb.text('约 68 m² · 朝南', *U(54, 404), 22, FAINT, 'regular', 'lm', family='hand', var=v), 0.3)++cb.node('C1')+with cb.clip(C1.x0 + 2, C1.y0 + 2, C1.x1 - 2, C1.y1 - 2, 10):+ tot, acc = sum(w for _, w in strokes), 0.0+ for fn, w in strokes:+ fn(('ink', acc / tot, (acc + w) / tot))+ acc += w+cb.end()++C2 = cb.card('C2', 1610, 538, 680, 178)+C2.gap(6)+C2.quote(['先把床装好,', '其他的明天再说。'], 34, BRIGHT, by='写给搬家那天晚上的自己', var='q')++C3 = cb.card('C3', 1610, 760, 680, 262, colour='green')+C3.h2('第一晚要用的')+for i, (s, done) in enumerate([('床单、枕头', True), ('牙刷、毛巾', True), ('手机充电器、台灯', False)]):+ C3.task(s, done, key=f't{i}')+C3.p('都装在 `B1` 箱,最后一个上车', 24, MUTED)++# ===================================================================== edges+cb.edge('e1', ('A1', 'r', 0.5), ('B1', 'l', 0.16), colour=ACCENT, label='当天')+cb.edge('e2', ('A2', 'r', 0.6), ('B2', 'l', 0.3), colour=EDGE, label='装箱')+cb.edge('e3', ('B1', 'r', 0.84), ('C1', 'l', 0.7), colour=EDGE, label='13:30')+cb.edge('e4', ('B2', 'r', 0.62), ('C3', 'l', 0.5), colour=CC['green'], label='B1 先开')+tick('drawn')++# ===================================================================== cameras+OVER = cb.fit(-30, -64, 2320, 1050, pad=36, right=40) # the whole board (the final frame)+K_A = (430, 300, 1.15) # the plan card and the checklist+K_A3 = (470, 560, 1.0) # down to the loose shopping card+K_B = (1110, 590, 1.0) # the day of the move+K_C1 = (1950, 286, 1.22) # close on the floor plan+K_C = (1960, 590, 1.0) # the quote and the first-night list+cb.camera(*OVER)++# ===================================================================== stage by stage (the draw-on GIF), then the final frame+# Things that move get a few in-between stages (names 'mv_*': the GIF shows them as quick hard cuts -- real motion);+# everything else cross-fades. A card drops in from above: held up (big shadow, 5 % larger, half transparent), it falls,+# bounces a little and settles.+CARDS = ['A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'C3']+GROUPS = ['gA', 'gB', 'gC']+EDGES = ['e1', 'e2', 'e3', 'e4']+LIFT = dict(dy=-110, scale=1.05, alpha=0.55, lift=1.0)+++def drop(name, tag, n=5, also=(), cam=None):+ cb.tween(tag, n, 'drop', moves=[(name, LIFT, None)] + list(also), cam=cam)+++if stages:+ for n in CARDS + GROUPS: cb.hide(n)+ for n in EDGES: cb.set(n, p=0.0)+ cb.set('A1', hl=0.0); cb.set('A2', t0=0.0, t1=0.0, t2=0.0); cb.set('A3', buy=0.0)+ cb.set('B1', tl=0.0, hl=0.0); cb.set('B2', chip=0.0); cb.set('C1', ink=0.0); cb.set('C2', q=0.0)+ cb.set('C3', t0=0.0, t1=0.0)+ cb.camera(*K_A); cb.stage('board')+ cb.tween('grpA', 3, 'out', moves=[('gA', dict(alpha=0.0), None)])+ drop('A1', 'A1')+ cb.tween('hl', 3, 'io', moves=[('A1', dict(hl=0.0), None)])+ drop('A2', 'A2')+ for i in range(3):+ cb.tween(f'tick{i}', 3, 'out', moves=[('A2', {f't{i}': 0.0}, None)])+ drop('A3', 'A3', n=5, cam=(K_A, K_A3), also=[('A3', dict(buy=0.0), None)])+ # pan to the day of the move: the violet edge leads, the group frame fades in, then the timeline drops onto it+ cb.tween('panB', 6, 'io', moves=[('e1', dict(p=0.0), None), ('gB', dict(alpha=0.0), None)], cam=(K_A3, K_B))+ drop('B1', 'B1')+ cb.tween('tl', 4, 'linear', moves=[('B1', dict(tl=0.0, hl=0.0), None)])+ cb.tween('e2', 5, 'io', moves=[('e2', dict(p=0.0), None)])+ drop('B2', 'B2')+ cb.tween('chips', 4, 'linear', moves=[('B2', dict(chip=0.0), None)])+ # pan to the new flat, closing in on the floor plan; then sketch it stroke by stroke+ cb.tween('panC', 6, 'io', moves=[('e3', dict(p=0.0), None), ('gC', dict(alpha=0.0), None)], cam=(K_B, K_C1))+ drop('C1', 'C1')+ cb.tween('ink', 8, 'linear', moves=[('C1', dict(ink=0.0), None)])+ cb.tween('downC', 4, 'io', cam=(K_C1, K_C))+ drop('C2', 'C2')+ cb.tween('quote', 4, 'linear', moves=[('C2', dict(q=0.0), None)])+ cb.tween('e4', 5, 'io', moves=[('e4', dict(p=0.0), None)])+ drop('C3', 'C3')+ for i in range(2):+ cb.tween(f'tick_c{i}', 3, 'out', moves=[('C3', {f't{i}': 0.0}, None)])+ # the pointer comes up to the zoom buttons and clicks 'fit': the camera pulls back to the whole board+ fx, fy = cb.control(2)+ sx, sy = cb.to_screen(2120, 980)+ cb.tween('pointer', 5, 'io', between=lambda u: cb.cursor(sx + (fx - sx) * u, sy + (fy - sy) * u - 90 * np.sin(np.pi * u),+ alpha=min(1.0, 3 * u)))+ cb.hover = 2+ cb.cursor(fx, fy, click=0.3, press=True); cb.stage('mv_click1')+ cb.cursor(fx, fy, click=0.65); cb.stage('click')+ cb.tween('zoom', 7, 'io', cam=(K_C, OVER), last=False,+ between=lambda u: cb.cursor(fx, fy, alpha=max(0.0, 1 - 1.6 * u)))++# final: everything at rest and finished, the whole board+cb.cursor(); cb.hover = None+for n in cb.nodes:+ cb.pose(n); cb.reset(n)+cb.camera(*OVER)+cb.save(out, stages_dir=stages)+tick('saved')+print('saved', out)diff --git a/examples/drawing_canvasboard_moving_plan.gif b/examples/drawing_canvasboard_moving_plan.gifnew file mode 100644index 0000000..530313aBinary files /dev/null and b/examples/drawing_canvasboard_moving_plan.gif differdiff --git a/examples/drawing_flexoki_pour_over.gif b/examples/drawing_flexoki_pour_over.gifnew file mode 100644index 0000000..cb416d3Binary files /dev/null and b/examples/drawing_flexoki_pour_over.gif differdiff --git a/examples/drawing_obsidianui_reading_notes.gif b/examples/drawing_obsidianui_reading_notes.gifnew file mode 100644index 0000000..61bd86dBinary files /dev/null and b/examples/drawing_obsidianui_reading_notes.gif differdiff --git a/examples/flexoki_pour_over.jpg b/examples/flexoki_pour_over.jpgnew file mode 100644index 0000000..be645ffBinary files /dev/null and b/examples/flexoki_pour_over.jpg differdiff --git a/examples/flexoki_pour_over.py b/examples/flexoki_pour_over.pynew file mode 100644index 0000000..932ed13--- /dev/null+++ b/examples/flexoki_pour_over.py@@ -0,0 +1,283 @@+"""Example (Flexoki paper): 一杯手冲咖啡,拆成五张图 / Pour-over, in five diagrams — an explainer sheet on warm paper.++Warm Flexoki paper (#FFFCF0); an ink chip, a heavy heading with a grey English tag, a big timer at the top right+(2:30, from bloom to cup). Five light-grey rounded panels, each with a heavy title, a grey chart-type tag and a mono+index number, each holding one diagram drawn the way a lightweight diagram renderer draws it:+ 01 flowchart 从豆子到一杯: 称豆 -> 研磨 -> 冲洗滤纸 -> 闷蒸, down to a diamond 「鼓包平了?」, 是 -> 分两段注水+ -> 出杯, 否 loops back to 闷蒸 (a filleted orthogonal edge); paper-filled boxes with grey borders,+ ink lines, small triangular heads, green / red edge labels on a patch of panel colour;+ 02 sequence 两分半里发生了什么: 水壶 / 滤杯 / 分享壶, dashed lifelines, an activation bar, three pours with a+ time column (0:00 0:45 1:15), a note 「排气 · 45 s」, the dashed reply 「约 210 g 咖啡液」 at 2:30;+ 03 bar chart 磨多细,滴多久: drawdown time by grind on a hairline grid, the chosen grind in orange;+ 04 pie 240 g 水分三次: 30 / 120 / 90 g with paper gaps, fractions on the slices, a legend;+ 05 table 三种冲法: pour-over / French press / espresso, a tinted header with accent dots, the pour-over+ column ringed in orange.+A footnote with the recipe. No logos, no image model.+--stages DIR writes the draw-on sequence: the heading rises, the panels rise dim, then one by one each panel lights+up with an orange focus ring while its diagram draws -- nodes pop, edges draw on edge by edge and land their heads,+messages fly, the timer rolls 0:00 -> 2:30, bars grow with their values rolling, the pie sweeps, table rows slide in.+Stage names: 'x~nn' = an in-between frame of something moving (hard cut), 'x@ms' = hold, the rest cross-fade.+python3 flexoki_pour_over.py [out.jpg] [--stages DIR]+"""+import os, sys, time+import numpy as np+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from flexoki import (FlexokiPaper, Node, rounded, PAPER, INK, UI, TX1B, TX2, TX3, ORANGE4, RED4, GREEN4, BLUE4,+ CYAN4, PURPLE4)++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'flexoki_pour_over.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+T0 = time.time()+fx = FlexokiPaper(1920, 1080, seed=3, keep_stages=bool(stages))+fx.paper()++ease_out = lambda u: 1 - (1 - min(1.0, max(0.0, u))) ** 3+ease_io = lambda u: (lambda v: 3 * v * v - 2 * v ** 3)(min(1.0, max(0.0, u)))+q = lambda p, a, b: min(1.0, max(0.0, (p - a) / (b - a))) # progress of a sub-interval [a, b] of p+mmss = lambda s: f'{int(s) // 60}:{int(s) % 60:02d}'++# ===================================================================== layout+X0, X1 = 120, 1800+PANELS = { # name: (x0, y0, x1, y1, title, tag, index)+ 'p1': (120, 208, 1136, 622, '从豆子到一杯', 'Flowchart', '01'),+ 'p2': (1160, 208, 1800, 622, '两分半里发生了什么', 'Sequence', '02'),+ 'p3': (120, 646, 616, 1004, '磨多细,滴多久', 'Bar chart', '03'),+ 'p4': (640, 646, 1136, 1004, '240 g 水分三次', 'Pie', '04'),+ 'p5': (1160, 646, 1800, 1004, '三种冲法', 'Compare', '05'),+}+BOX = {}++# ===================================================================== header: chip, heading, timer, footnote+fx.layer('chip', z=10)+fx.chip(X0, 78, '图解 · 手冲咖啡', size=24)+fx.layer('heading', z=10)+fx.heading(X0 - 3, 170, '一杯手冲咖啡', 'Pour-over, in five diagrams', size=62, en_size=31)+TIMER_W = fx.measure('2:30', 108, 'heavy', spacing=-0.03 * 108)+fx.layer('timer_label', z=10)+fx.chip(X1 - TIMER_W - 22, 170 - 108 * 0.36, '总时长', fg=INK, bg=UI, size=24, anchor='r')+++def draw_timer(sec, dim=False):+ fx.layer('timer', z=10, fresh=True)+ fx.number(X1 + 2, 170, mmss(sec), 108, TX3 if dim else INK, anchor='rs')+++draw_timer(150)+fx.layer('foot', z=10)+fx.text('配方:15 g 咖啡粉 · 240 g 热水(93 °C,粉水比 1 : 16)· 中细研磨。时间和数字是示意,换了豆子要再调。',+ X0, 1050, 20, TX2, 'medium')++# ===================================================================== the five panels (and their focus rings)+for k, (name, (x0, y0, x1, y1, title, tag, num)) in enumerate(PANELS.items()):+ fx.layer(name, z=1)+ BOX[name] = fx.panel(x0, y0, x1 - x0, y1 - y0, title=title, tag=tag, num=num, title_size=32, pad=30)+ fx.layer('ring' + name[1], z=3)+ fx.focus(BOX[name], ORANGE4, 4)+fx.end()+print(f'panels {time.time() - T0:5.1f}s') if os.environ.get('FLEXOKI_TIMING') else None++# ===================================================================== 01 flowchart (snake: row 1 left -> right, row 2 right -> left)+R1Y, R2Y = 352, 532+ROW1 = [('称豆 15 g', 144, 'rect'), ('研磨 · 中细', 160, 'rect'), ('冲洗滤纸', 148, 'round'), ('闷蒸 30 g 水', 168, 'rect')]+FL0, FL1 = 152, 1038+gap = (FL1 - FL0 - sum(w for _, w, _ in ROW1)) / 3+xs, x = [], FL0+for _, w, _ in ROW1:+ xs.append(x + w / 2); x += w + gap+N1 = [Node(cx, R1Y, w, 56, sh) for cx, (_, w, sh) in zip(xs, ROW1)]+ND = Node(xs[3], R2Y, 204, 104, 'diamond')+N6 = Node(xs[0], R2Y, 120, 56, 'stadium')+N5 = Node((N6.x1 + ND.x0) / 2, R2Y, 172, 56, 'rect') # equal edges either side+LX = ND.x1 + 34 # the 否 loop runs up this x+FLOW = [ # in drawing order: ('n', node, label) or ('e', points, kwargs)+ ('n', N1[0], ROW1[0][0]), ('e', [N1[0].side('r'), N1[1].side('l')], {}),+ ('n', N1[1], ROW1[1][0]), ('e', [N1[1].side('r'), N1[2].side('l')], {}),+ ('n', N1[2], ROW1[2][0]), ('e', [N1[2].side('r'), N1[3].side('l')], {}),+ ('n', N1[3], ROW1[3][0]), ('e', [N1[3].side('b'), ND.side('t')], {}),+ ('n', ND, '鼓包平了?'), ('e', [ND.side('l'), N5.side('r')], dict(label='是', label_fill=GREEN4)),+ ('n', N5, '分两段注水'), ('e', [N5.side('l'), N6.side('r')], {}),+ ('n', N6, '出杯'),+ ('e', rounded([ND.side('r'), (LX, R2Y), (LX, R1Y), N1[3].side('r')], 16), dict(label='否', label_fill=RED4)),+]+++def draw_flow(p):+ fx.layer('flow', z=5, fresh=True)+ n = len(FLOW)+ for i, (kind, obj, arg) in enumerate(FLOW):+ a = i / (n - 1) * 0.86+ t = q(p, a, a + 0.14)+ if t <= 0: continue+ if kind == 'n':+ fx.node(obj.cx, obj.cy, obj.w, obj.h, arg, obj.shape, size=22, p=ease_out(t))+ else:+ fx.edge(obj, p=ease_io(t), **arg)+++# ===================================================================== 02 sequence diagram (+ the timer)+LL = [1330, 1518, 1704] # lifelines: 水壶 滤杯 分享壶+PART = ['水壶', '滤杯', '分享壶']+PY, LY1 = 318, 600+ACT = (380, 584) # activation on 滤杯+MSG = [ # (y, from, to, label, time, reply)+ (386, 0, 1, '闷蒸 30 g', 0, False), (476, 0, 1, '注水至 150 g', 45, False),+ (526, 0, 1, '注水至 240 g', 75, False), (576, 1, 2, '约 210 g 咖啡液', 150, True),+]+NOTE = (1538, 398, 1672, 436, '排气 · 45 s')+MSG_T = [(0.30, 0.42), (0.50, 0.62), (0.62, 0.74), (0.78, 0.92)] # when each message flies (in p)+++def tip(i, j):+ """message end x: the edge of the activation bar on 滤杯, the lifeline elsewhere"""+ if j == 1: return LL[1] - 7 if i < j else LL[1] + 7+ return LL[j]+++def draw_seq(p):+ fx.layer('seq', z=5, fresh=True)+ for k, x in enumerate(LL):+ fx.lifeline(x, PY + 22, LY1, p=ease_io(q(p, 0.08 + 0.04 * k, 0.3 + 0.04 * k)))+ fx.activation(LL[1], ACT[0], ACT[1], 14, p=q(p, MSG_T[0][0], MSG_T[3][1]))+ for k, (x, s) in enumerate(zip(LL, PART)):+ fx.node(x, PY, 132, 44, s, size=21, p=ease_out(q(p, 0.04 * k, 0.12 + 0.04 * k)))+ for (y, i, j, lab, sec, rep), (a, b) in zip(MSG, MSG_T):+ t = q(p, a, b)+ if t <= 0: continue+ x0 = LL[i] + (7 if i == 1 else 0)+ fx.message(x0, tip(i, j), y, lab, ease_io(t), reply=rep, size=19)+ fx.text(mmss(sec), 1236, y, 19, TX2, 'medium', 'rm', min(1.0, 2 * t), family='mono')+ fx.note(*NOTE, size=18, p=ease_out(q(p, 0.42, 0.5)))+++def seq_clock(p):+ """the timer while the sequence draws: 0:00 at the first pour, then each message's time as it lands"""+ keys = [(MSG_T[0][0], 0), (MSG_T[0][1], 0)] + [(b, MSG[k][4]) for k, (a, b) in enumerate(MSG_T) if k]+ ps, vs = zip(*keys)+ return float(np.interp(p, ps, vs))+++# ===================================================================== 03 bar chart+GRIND = ['粗', '中', '中细', '细']+DRAW_S = [110, 135, 150, 200] # drawdown seconds (illustrative)+B3 = BOX['p3']+PLOT = (B3.x0 + 92, B3.y0 + 104, B3.x1 - 30, B3.y1 - 62)+++def draw_bars(p):+ fx.layer('bars', z=5, fresh=True)+ ps = [ease_out(q(p, 0.1 * i, 0.1 * i + 0.62)) for i in range(4)]+ fx.bars(*PLOT, DRAW_S, GRIND, [CYAN4, CYAN4, ORANGE4, CYAN4], vmax=240, ticks=[0, 60, 120, 180, 240],+ tick_fmt=mmss, p=ps, value_fmt=mmss, bar_w=0.5, size=20, value_colours=[INK, INK, ORANGE4, INK])+++# ===================================================================== 04 pie+B4 = BOX['p4']+POUR = [('闷蒸', 30, ORANGE4), ('第一段', 120, BLUE4), ('第二段', 90, GREEN4)]+PC = (B4.x0 + 148, B4.y0 + 210)+++def draw_pie(p):+ fx.layer('pie', z=5, fresh=True)+ fx.pie(*PC, 112, [v for _, v, _ in POUR], [c for _, _, c in POUR], sweep=ease_io(q(p, 0, 0.72)), gap=3,+ labels=['1/8', '1/2', '3/8'], label_size=21, label_r=0.64)+ al = [ease_out(q(p, 0.3 + 0.16 * i, 0.5 + 0.16 * i)) for i in range(3)]+ items = [(c, s, f'{round(v * a)} g') for (s, v, c), a in zip(POUR, al)]+ fx.legend(B4.x0 + 296, B4.y0 + 158, items, size=21, pitch=52, swatch=22, value_x=B4.x1 - 30, alpha=al,+ value_family='sans')+++# ===================================================================== 05 comparison table+B5 = BOX['p5']+fx.layer('tbl', z=5)+TB = fx.table(B5.x0 + 30, B5.y0 + 82, [114, 156, 156, 154], 4, row_h=50, head_h=50,+ header=['', '手冲', '法压壶', '意式'], dots=[None, ORANGE4, PURPLE4, CYAN4], size=21)+ROWS = [['方式', '滴滤', '浸泡', '9 bar 加压'], ['研磨', '中细', '粗', '极细'], ['时间', '2:30', '4:00', '0:30'],+ ['口感', '干净明亮', '醇厚', '浓厚']]+for i, row in enumerate(ROWS):+ fx.layer(f'tbl_r{i}', z=6)+ fx.table_row(TB, i, row, size=21)+fx.layer('tbl_ring', z=7)+fx.focus(TB.col(1), ORANGE4, 3, r=10)+fx.end()++# everything in its final state+draw_flow(1); draw_seq(1); draw_bars(1); draw_pie(1)+fx.end()+print(f'drawn {time.time() - T0:5.1f}s') if os.environ.get('FLEXOKI_TIMING') else None++# ===================================================================== the draw-on sequence+REST = dict(dx=0.0, dy=0.0, scale=1.0, alpha=1.0, reveal=1.0)+DIM = 0.42+RINGS = ['ring1', 'ring2', 'ring3', 'ring4', 'ring5']+if stages:+ for n in fx.layers: fx.hide(n)+ fx.stage('paper@400')+ for k in range(1, 6): # chip and heading rise, a frame apart+ u1, u2 = ease_out(k / 4), ease_out((k - 1) / 4)+ fx.pose('chip', dy=18 * (1 - u1), alpha=u1)+ fx.pose('heading', dy=24 * (1 - u2), alpha=u2)+ fx.stage(f'head~{k}')+ draw_timer(0, dim=True)+ for k in range(1, 4):+ u = ease_out(k / 3)+ fx.pose('timer', dy=16 * (1 - u), alpha=u); fx.pose('timer_label', dy=16 * (1 - u), alpha=u)+ fx.stage(f'timer~{k}')+ fx.stage('header@250')+ names = list(PANELS)+ for k in range(1, 15): # the five panels rise dim, two frames apart+ for i, n in enumerate(names):+ u = ease_out((k - 2 * i) / 5)+ fx.pose(n, dy=26 * (1 - u), alpha=DIM * u)+ fx.pose('foot', alpha=ease_out((k - 8) / 5))+ fx.stage(f'panels~{k:02d}')+ fx.stage('panels@300')++ def light(i, steps=3):+ """panel i comes up to full strength and takes the ring; the previous ring fades"""+ if i < 4: fx.show(['flow', 'seq', 'bars', 'pie'][i]) # its content layer (redrawn as it draws on)+ for k in range(1, steps + 1):+ u = k / steps+ fx.pose(names[i], alpha=DIM + (1 - DIM) * u)+ fx.show(RINGS[i], alpha=u)+ if i: fx.show(RINGS[i - 1], alpha=1 - u)+ fx.stage(f'light{i + 1}~{k}')++ light(0)+ for k in range(1, 29):+ draw_flow(k / 28); fx.stage(f'flow~{k:02d}')+ fx.stage('flow@350')+ light(1)+ for k in range(1, 31):+ p = k / 30+ draw_seq(p)+ if p >= MSG_T[0][0]: draw_timer(seq_clock(p))+ fx.stage(f'seq~{k:02d}')+ draw_timer(150); fx.stage('seq@350')+ light(2)+ for k in range(1, 15):+ draw_bars(k / 14); fx.stage(f'bars~{k:02d}')+ fx.stage('bars@300')+ light(3)+ for k in range(1, 15):+ draw_pie(k / 14); fx.stage(f'pie~{k:02d}')+ fx.stage('pie@300')+ light(4)+ for k in range(1, 4):+ u = ease_out(k / 3); fx.pose('tbl', dy=14 * (1 - u), alpha=u); fx.stage(f'tbl~{k}')+ for i in range(4):+ for k in range(1, 4):+ u = ease_io(k / 3); fx.pose(f'tbl_r{i}', reveal=u, feather=60); fx.stage(f'row{i}~{k}')+ for k, (sc, al) in enumerate([(1.06, 0.4), (1.03, 0.8), (1.0, 1.0)], 1):+ fx.pose('tbl_ring', scale=sc, alpha=al); fx.stage(f'colring~{k}')+ fx.stage('table@300')+ for k in range(1, 3):+ fx.show('ring5', alpha=1 - k / 2); fx.stage(f'unfocus~{k}')++# final poses: everything drawn, no panel ring+for n in fx.layers:+ fx.pose(n)+fx.hide(*RINGS)+draw_flow(1); draw_seq(1); draw_bars(1); draw_pie(1); draw_timer(150)+fx.save(out, stages_dir=stages)+print(f'saved {time.time() - T0:5.1f}s') if os.environ.get('FLEXOKI_TIMING') else None+print('saved', out)diff --git a/examples/obsidianui_reading_notes.jpg b/examples/obsidianui_reading_notes.jpgnew file mode 100644index 0000000..8d26109Binary files /dev/null and b/examples/obsidianui_reading_notes.jpg differdiff --git a/examples/obsidianui_reading_notes.py b/examples/obsidianui_reading_notes.pynew file mode 100644index 0000000..d6ab39f--- /dev/null+++ b/examples/obsidianui_reading_notes.py@@ -0,0 +1,255 @@+"""Example (Obsidian UI): 小王子 · 读书笔记 / Reading Notes — a dark note-taking app window with one book's notes.++A near-black page with a soft violet glow; on it the app window: tab bar (小王子 · 狐狸), icon ribbon, a file explorer+(the folder 2026 读书 open, the note 小王子 highlighted), the note pane and a right sidebar. In the note: the H1 「小王子」+with a short violet bar, a properties block (#童话 #读书笔记, the date it was finished), two lines of body text with+internal links in violet, **bold** and `inline code`; a ```mermaid block typed line by line -- a click flips the note+from 源码 to 阅读 and the block renders as a flowchart, 陌生 -花时间-> 驯养 -> 彼此需要 -> 独一无二, with 驯养 lit violet;+then the fox's line in a quote callout. In the sidebar the local graph: grey nodes and links for the book's+characters and places, the four notes linked from this one (小王子, 狐狸, 玫瑰, 驯养) lit violet with a soft glow, and the+backlinks under it; a status bar in the corner. One accent (violet), everything else greys. No logos, no image model.+python3 obsidianui_reading_notes.py [out.jpg] [--stages DIR] [--accent violet|blue|teal|amber|rose]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+from obsidianui import ObsidianUI, BORDER, TEXT, BRIGHT, MUTED, FAINT++out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'obsidianui_reading_notes.jpg'+stages = sys.argv[sys.argv.index('--stages') + 1] if '--stages' in sys.argv else None+ACC = sys.argv[sys.argv.index('--accent') + 1] if '--accent' in sys.argv else 'violet'+T0 = time.time()+tick = lambda name: print(f'{name:14s} {time.time() - T0:5.1f}s') if os.environ.get('OBSIDIANUI_TIMING') else None++ob = ObsidianUI(1920, 1080, seed=3, keep_stages=bool(stages), accent=ACC)+ob.page()++# ===================================================================== layout+WX, WY, WW, WH, SIDE, RIGHT = 120, 96, 1680, 884, 300, 470+PAD = 64+FILES = [('2026 读书', 0, 'open'), ('小王子', 1, 'file'), ('狐狸', 1, 'file'), ('玫瑰', 1, 'file'), ('驯养', 1, 'file'),+ ('人物', 0, 'folder'), ('摘抄', 0, 'folder'), ('每日笔记', 0, 'folder'), ('模板', 0, 'folder'),+ ('附件', 0, 'folder'), ('读书清单', 0, 'file'), ('想读的书', 0, 'file')]+H1_BASE, H1_SIZE = 290, 76+PROP_Y = [358, 398]+BODY, BODY_LH, BODY_Y0 = 28, 48, 476+CODE_Y, CODE_SIZE = 554, 25+CODE = [+ [('```mermaid', 'fence')],+ [('flowchart', 'kw'), (' LR', 'op')],+ [(' A', 'text'), ('[陌生]', 'str'), (' -->', 'op'), ('|花时间|', 'cm'), (' B', 'text'), ('[驯养]', 'str')],+ [(' B', 'text'), (' -->', 'op'), (' C', 'text'), ('[彼此需要]', 'str'), (' -->', 'op'), (' D', 'text'), ('([独一无二])', 'str')],+ [('```', 'fence')],+]++# ===================================================================== the window chrome+ob.layer('window', z=10)+win = ob.window(WX, WY, WW, WH, tabs=['小王子', '狐狸'], active=0, side=SIDE, right=RIGHT)+N, E, R = win.note, win.explorer, win.right+CX0, CX1 = N.x0 + PAD, N.x1 - PAD # note column+CW = CX1 - CX0++ob.layer('explorer', z=12)+ob.explorer(win, FILES, active=1)+ob.rrect(E.x0 + 14, E.y1 - 58, E.x1 - 14, E.y1 - 57, 0, BORDER)+ob.text('读书笔记', E.x0 + 26, E.y1 - 29, 18, MUTED, 'semibold', 'lm')+ob.glyph('collapse', E.x1 - 34, E.y1 - 29, 16, FAINT, 2.0)++ob.layer('header', z=12)+ob.view_header(win, ['2026 读书', '小王子'])+tick('chrome')++# ===================================================================== the note+TOG = (CX1 - 196, H1_BASE - H1_SIZE * 0.37 - 23, 196, 46)+for name, on in [('toggle_src', 0), ('toggle_read', 1)]:+ ob.layer(name, z=14)+ ob.toggle(*TOG, on=on)++ob.layer('h1', z=14)+ob.h1(CX0, H1_BASE, '小王子', H1_SIZE, bar=False)+ob.layer('h1_bar', z=14)+ob.h1(CX0, H1_BASE, '小王子', H1_SIZE, bar_w=150, bar_gap=20, draw_text=False)++ob.layer('props', z=14)+vx = ob.prop(CX0, PROP_Y[0], 'tag', '标签', 128)+x = ob.tag(vx, PROP_Y[0], '#童话', 18) + 10+ob.tag(x, PROP_Y[0], '#读书笔记', 18)+vx = ob.prop(CX0, PROP_Y[1], 'calendar', '读完', 128)+x = vx + ob.text('2026-10-12', vx, PROP_Y[1], 19, TEXT, 'regular', 'lm') + 18+ob.text('· 第 21 章重读', x, PROP_Y[1], 19, FAINT, 'regular', 'lm')+ob.rrect(CX0, PROP_Y[1] + 30, CX1, PROP_Y[1] + 31, 0, BORDER)++PARA = [+ [('第 21 章,', None), ('狐狸', 'link'), ('教小王子什么叫', None), ('驯养', 'link'), (':', None)],+ [('不是占有,而是', None), ('建立联系', 'code'), (',从此', None), ('彼此需要', 'b'), ('。', None)],+]+for i, runs in enumerate(PARA):+ ob.layer(f'para{i}', z=14)+ ob.rich(CX0, BODY_Y0 + i * BODY_LH, runs, BODY)++# the mermaid block (source view): the box, then each line in its own layer (typed), a caret per line+ob.layer('code_box', z=13)+cb = ob.code_block(CX0, CODE_Y, CW, CODE, size=CODE_SIZE, draw=False)+CODE_W = []+for i, toks in enumerate(CODE):+ ob.layer(f'code{i}', z=14)+ CODE_W.append(ob.code_line(cb.tx, cb.bases[i], toks, CODE_SIZE) - cb.tx)+ ob.layer(f'caret{i}', z=15)+ ob.caret(cb.tx + CODE_W[i], cb.bases[i], CODE_SIZE)+tick('note')++# the rendered flowchart (reading view), centred where the block was+DY = cb.cy + 4+WIDTHS, GAPS = [108, 122, 156, 156], [120, 60, 60]+xs, x = [], CX0 + (CW - sum(WIDTHS) - sum(GAPS)) / 2+for w_, g_ in zip(WIDTHS, GAPS + [0]):+ xs.append(x + w_ / 2); x += w_ + g_+NODES = [('陌生', 'stadium'), ('驯养', 'rect'), ('彼此需要', 'rect'), ('独一无二', 'round')]+NH = 80+for k, (lab, shape) in enumerate(NODES):+ ob.layer(f'dg{k}', z=14)+ ob.dnode(xs[k], DY, WIDTHS[k], NH, lab, shape, size=26)+ob.layer('dg1_hi', z=15)+ob.dnode(xs[1], DY, WIDTHS[1], NH, '驯养', 'rect', hi=True, size=26, focus=True)+for k in range(3):+ ob.layer(f'dge{k}', z=13)+ a, b = xs[k] + WIDTHS[k] / 2 + 3, xs[k + 1] - WIDTHS[k + 1] / 2 - (17 if k == 0 else 3)+ ob.dedge([(a, DY), (b, DY)], label='花时间' if k == 0 else None, label_at=0.47)++# the fox's line+ob.layer('callout', z=14)+CALL_Y = cb.y1 + 30+ob.callout(CX0, CALL_Y, CW, '狐狸说', [[('“你在你的', None), ('玫瑰', 'link'), ('身上花的时间,使她变得这么重要。”', None)]],+ size=BODY, title_size=24)+tick('diagram')++# ===================================================================== the right sidebar: local graph + backlinks+ob.layer('side_tools', z=12)+ty = ob.sidebar_tools(win, lit=1)+ob.layer('graph_head', z=12)+ob.text('局部关系图谱', R.x0 + 28, ty + 40, 21, BRIGHT, 'bold', 'lm')+ob.text('深度 2', R.x1 - 28, ty + 40, 16, FAINT, 'regular', 'rm')++GC = (R.cx - 4, ty + 250) # the current note sits in the middle+G = lambda dx, dy, r, lab: (GC[0] + dx, GC[1] + dy, r, lab)+GN = [G(0, 0, 12, '小王子'), # 0 (lit: this note and what it links to)+ G(-122, -78, 9, '狐狸'), G(112, -100, 9, '玫瑰'), G(-70, 104, 9, '驯养'),+ G(126, 78, 7, '飞行员'), G(186, 22, 6, '蛇'), G(36, -170, 7, 'B612'), G(176, -176, 5, '猴面包树'),+ G(196, 150, 6, '沙漠'), G(-194, 40, 7, '六颗星球'), G(-206, 128, 5, '国王'), G(-200, -108, 5, '点灯人'),+ G(-118, 184, 5, '商人'), G(46, 176, 5, '地理学家')]+GL = [(0, 1), (0, 2), (0, 3), (1, 3), (1, 2), (0, 4), (0, 5), (6, 2), (6, 7), (4, 8), (5, 8), (0, 9),+ (9, 10), (9, 11), (9, 12), (4, 13), (6, 0)]+LIT = [0, 1, 2, 3]+ob.layer('graph_grey', z=13)+ob.graph(GN, GL, LIT, label_size=15, only='grey')+ob.layer('graph_lit', z=14)+ob.graph(GN, GL, LIT, label_size=15, only='lit')++ob.layer('backlinks', z=12)+BY = GC[1] + 226+ob.rrect(R.x0 + 20, BY, R.x1 - 20, BY + 1, 0, BORDER)+ob.glyph('chev_d', R.x0 + 34, BY + 36, 15, FAINT, 2.2)+ob.text('反向链接', R.x0 + 50, BY + 36, 19, TEXT, 'semibold', 'lm')+ob.rrect(R.x0 + 142, BY + 24, R.x0 + 170, BY + 48, 12, '#2e2e2e')+ob.text('3', R.x0 + 156, BY + 36, 15, MUTED, 'semibold', 'mm')+BACK = [('狐狸', [('……他就是这样被', None), ('小王子', 'link'), ('驯养的。', None)]),+ ('玫瑰', [('……', None), ('小王子', 'link'), ('每晚给她罩上玻璃罩。', None)]),+ ('驯养', [('出自', None), ('小王子', 'link'), ('第 21 章,狐狸的话。', None)])]+for i, (name, runs) in enumerate(BACK):+ y = BY + 66 + i * 66+ ob.glyph('file', R.x0 + 36, y + 10, 17, FAINT, 1.9)+ ob.text(name, R.x0 + 54, y + 10, 18, TEXT, 'semibold', 'lm')+ ob.rich(R.x0 + 54, y + 44, runs, 16, MUTED)++ob.layer('status', z=16)+ob.status_bar(win, ['3 个反向链接', '268 字', '阅读视图'])+tick('sidebar')++# ===================================================================== the pointer (GIF only)+TX_READ = (TOG[0] + TOG[2] * 0.74, TOG[1] + TOG[3] * 0.62)+ob.layer('cursor', z=50)+ob.cursor(*TX_READ)+ob.layer('ring', z=49) # the click ring (scaled up as it fades)+ob.circle(TX_READ[0], TX_READ[1], 34, '#ece4ff', 0.95, ring=3.5)+ob.end()+tick('drawn')++# ===================================================================== stage by stage (the draw-on GIF), then the final frame+# Things that move get in-between poses (stage names 'mv_*': the GIF shows them as quick hard cuts, i.e. real motion);+# everything else cross-fades from stage to stage.+ALL = list(ob.layers)+ease_out = lambda u: 1 - (1 - u) ** 3+ease_back = lambda u: 1 + 2.4 * (u - 1) ** 3 + 1.4 * (u - 1) ** 2 # overshoots ~6 % and settles+ease_io = lambda u: 3 * u * u - 2 * u ** 3+lin = lambda u: u+REST = dict(dx=0.0, dy=0.0, scale=1.0, alpha=1.0, reveal=1.0)+++def move(names, frm, to=REST, n=5, tag='', ease=ease_out, last=True, origin=None, mode='x', feather=14.0, between=None):+ """pose one or more layers from `frm` to `to` over n stages; the last stage is named `tag`"""+ names = [names] if isinstance(names, str) else names+ for k in range(1, n + 1):+ u = ease(k / n)+ p = {key: frm.get(key, REST[key]) + (to.get(key, REST[key]) - frm.get(key, REST[key])) * u for key in REST}+ p['alpha'] = min(1.0, max(0.0, p['alpha']))+ if between: between(p, k / n)+ for nm in names: ob.pose(nm, origin=origin, mode=mode, feather=feather, **p)+ if k < n: ob.stage(f'mv_{tag}{k}')+ elif last: ob.stage(tag)+++def pop(name, tag, cx, cy, n=3):+ move(name, dict(scale=0.85, alpha=0.0), n=n, tag=tag, ease=ease_back, origin=(cx, cy))+++if stages:+ for n in ALL: ob.hide(n)+ ob.stage('page')+ move('window', dict(dy=60, scale=0.97, alpha=0.0), n=6, tag='window', ease=ease_back)+ ob.show('explorer'); ob.stage('explorer')+ ob.show('header', 'toggle_src', 'side_tools'); ob.stage('header')+ move('h1', dict(reveal=0.0), n=3, tag='h1', ease=ease_io)+ move('h1_bar', dict(reveal=0.0), n=3, tag='bar')+ ob.show('props'); ob.stage('props')+ for i in range(2):+ move(f'para{i}', dict(reveal=0.0), n=4, tag=f'para{i}', ease=lin)+ ob.show('code_box'); ob.stage('code_box')+ for i in range(len(CODE)): # typed: the line reveals and the caret rides its end+ w_ = CODE_W[i]+ ob.show(f'caret{i}')+ if i: ob.hide(f'caret{i - 1}')+ steps = 2 if w_ < 200 else 4+ move([f'code{i}'], dict(reveal=0.0), n=steps, tag=f'code{i}', ease=lin, feather=2.0,+ between=lambda p, u, w_=w_, i=i: ob.pose(f'caret{i}', dx=-(1 - u) * (w_ + 4)))+ # the pointer glides to 阅读 and clicks: the toggle flips, the source fades, the chart renders node by node+ sx, sy = cb.tx + CODE_W[-1] + 260 - TX_READ[0], cb.bases[-1] - 30 - TX_READ[1]+ move('cursor', dict(dx=sx, dy=sy, alpha=0.0), n=6, tag='cursor', ease=ease_io,+ between=lambda p, u: p.update(alpha=min(1.0, 3 * u)))+ TC = (TOG[0] + TOG[2] / 2, TOG[1] + TOG[3] / 2)+ ob.show('ring'); ob.pose('ring', scale=0.4, alpha=1.0, origin=TX_READ)+ ob.pose('toggle_src', scale=0.97, origin=TC); ob.stage('mv_click1')+ ob.hide('toggle_src'); ob.pose('toggle_read', scale=1.06, origin=TC)+ ob.pose('ring', scale=0.8, alpha=0.8, origin=TX_READ); ob.stage('mv_click2')+ ob.pose('toggle_read'); ob.pose('ring', scale=1.15, alpha=0.35, origin=TX_READ); ob.stage('click')+ ob.hide('ring', *[f'code{i}' for i in range(len(CODE))], 'code_box', f'caret{len(CODE) - 1}'); ob.stage('reading')+ move('cursor', dict(), dict(dx=40, dy=40, alpha=0.0), n=2, tag='cursor_out', last=False)+ ob.hide('cursor')+ pop('dg0', 'node0', xs[0], DY)+ for k in range(3):+ move(f'dge{k}', dict(reveal=0.0), n=3, tag=f'edge{k}', ease=lin, feather=6.0)+ pop(f'dg{k + 1}', f'node{k + 1}', xs[k + 1], DY)+ move('dg1_hi', dict(alpha=0.0, scale=1.08), n=3, tag='node_hi', origin=(xs[1], DY))+ move('callout', dict(dy=28, alpha=0.0), n=5, tag='callout', ease=ease_back)+ ob.show('graph_head'); ob.stage('graph_head')+ move('graph_grey', dict(reveal=0.0), n=7, tag='graph', ease=ease_io, mode='r', origin=GC[:2], feather=40.0)+ move('graph_lit', dict(alpha=0.0), n=4, tag='lit', ease=ease_io)+ ob.show('backlinks'); ob.stage('backlinks')+ ob.show('status'); ob.stage('status')++# final poses: everything finished, in reading view+for n in ALL:+ ob.pose(n)+for n in ['toggle_src', 'code_box', 'cursor', 'ring'] + [f'code{i}' for i in range(len(CODE))] + [f'caret{i}' for i in range(len(CODE))]:+ ob.hide(n)+ob.save(out, stages_dir=stages)+tick('saved')+print('saved', out)diff --git a/lib/canvasboard.py b/lib/canvasboard.pynew file mode 100644index 0000000..0adc36e--- /dev/null+++ b/lib/canvasboard.py@@ -0,0 +1,1342 @@+"""canvasboard — 白板卡片 / Canvas Board: a dark, dotted, infinite whiteboard in a note app's window (numpy + Pillow only).++The look of a dark note-taking app's canvas view, the way a product film shows it: a dark page with a faint violet glow,+the app window (tab bar with the traffic lights and a `.canvas` tab, a ribbon of line icons on the left), and in it a+board of grey dots that pans and zooms with a camera. On the board: group frames with their labels floating above,+cards (dark, rounded, 2 px borders in the card colours -- red, orange, yellow, green, cyan, purple -- with a faint tint+of that colour), curved edges with arrowheads and labels, Markdown inside the cards (headings, body, ==highlights==,+`inline code`, task lists that tick, quotes with a violet bar, tag pills, colour chips), image cards with their file+name above them, a sketch drawn with hand-drawn strokes, and the zoom buttons in the top-right corner. One accent: violet.++ retained nothing is rasterised when you call the drawing methods: every shape is recorded, in board (world)+ coordinates, into a named node (a group, a card, an edge ...). `render()` draws every node through the+ camera, so the board can be shown at any pan and zoom with crisp edges and type -- a real canvas.+ camera `camera(x, y, z)`: the board point at the centre of the pane, and the zoom. The dot grid lives on the+ board (it moves and scales with the camera); the window chrome and the zoom buttons do not.+ shapes rounded rectangles, discs, rings and strokes are signed-distance fields with 1 px analytic anti-aliasing+ (pixel centres at i + 0.5); polygons (arrowheads, the pointer) are rasterised 4x and box-filtered. Strokes+ are measured per segment, so a long curved edge or a sketch with hundreds of segments stays cheap.+ Shadows follow CSS box-shadow (offset, blur radius = 2 sigma, spread, colour, opacity; outside only).+ poses each node has a pose -- offset, scale about its centre, opacity -- and named progress values (vars)+ that its shapes read: an edge draws on with `p`, a task ticks with its key, a highlight sweeps, a sketch+ is drawn stroke by stroke. A shape takes `var='name'` or `var=('name', a, b)` (its own 0..1 progress is+ the var mapped from a..b), and `mode` says what that progress does: fade / draw / reveal / pop.+ type PingFang SC (CJK) + SF Pro (Latin, variable weight) + SF Mono, split into runs automatically; a 'hand'+ family (Hannotate SC, falling back to PingFang) for sketch notes; float sizes, so type zooms smoothly.+ Elsewhere Noto Sans CJK / Microsoft YaHei and the core fonts.+ Override with $INKPAINT_FONT_CANVASBOARD_<CJK|BOLD|LATIN|MONO|HAND>.++ import sys; sys.path.insert(0, 'lib')+ from canvasboard import CanvasBoard, ACCENT+ cb = CanvasBoard(1920, 1080, seed=1, tab='计划.canvas')+ cb.group('g', 0, 0, 700, 600, '第一周')+ a = cb.card('a', 30, 40, 640, 240, colour='purple')+ a.h1('计划'); a.p('先做 ==最重要的== 一件事'); a.task('列清单', key='t0')+ b = cb.card('b', 900, 80, 520, 200)+ b.h2('然后'); b.p('`v2` 上线')+ cb.edge('e', ('a', 'r'), ('b', 'l'), colour=ACCENT, label='下周')+ cb.camera(*cb.fit(-40, -80, 1460, 640))+ cb.pose('b', dy=-60, scale=1.05, alpha=0); cb.set('e', p=0); cb.stage('before')+ cb.pose('b'); cb.set('e', p=1); cb.save('out.jpg')+"""+import glob+import io+import os+import re+from contextlib import contextmanager+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, load_font++# ---------------------------------------------------------------- palette (dark note app, one violet accent)+PAGE = '#161616' # the page behind the window+BG, BG2, BG3, SIDE = '#1e1e1e', '#262626', '#2e2e2e', '#202020'+BORDER, BORDER2 = '#363636', '#444444'+TEXT, BRIGHT, MUTED, FAINT = '#dadada', '#f2f2f2', '#a3a3a3', '#6b6b6b'+ACCENT, ACCENT2 = '#8a5cf5', '#a88bfa'+BOARD, DOT, EDGE = '#1c1c1c', '#3a3a3a', '#7d7d7d'+GROUP_LINE = '#3d3d3d'+CODE_BG, CODE_FG = '#2e2e2e', '#e06c75'+DONE = '#7c7c7c' # a ticked task's text and strike+WHITE = '#ffffff'+CARD_COLOURS = {'red': '#fb464c', 'orange': '#e9973f', 'yellow': '#e0de71', 'green': '#44cf6e', 'cyan': '#53dfdd',+ 'purple': '#a882ff', 'accent': ACCENT}+LIGHTS = ('#ff5f57', '#febc2e', '#28c840')++# line icons on a 24-unit grid: ('p', points[, closed]) polyline, ('c', cx, cy, r) circle, ('a', cx, cy, r, a0, a1) arc+# (degrees, 0 = +x, 90 = down), ('d', cx, cy, r) filled dot, ('r', x0, y0, x1, y1, radius) rounded rectangle+GLYPHS = {+ 'menu': [('p', [(4, 6), (20, 6)]), ('p', [(4, 12), (20, 12)]), ('p', [(4, 18), (20, 18)])],+ 'search': [('c', 11, 11, 7), ('p', [(16.2, 16.2), (21, 21)])],+ 'file': [('p', [(6, 3), (15, 3), (18, 6), (18, 21), (6, 21)], True)],+ 'plus': [('p', [(12, 5), (12, 19)]), ('p', [(5, 12), (19, 12)])],+ 'plus_wide': [('p', [(12, 3), (12, 21)]), ('p', [(3, 12), (21, 12)])],+ 'minus': [('p', [(5, 12), (19, 12)])],+ 'grid': [('r', 5, 5, 11, 11, 0.5), ('r', 13, 13, 19, 19, 0.5), ('r', 13, 5, 19, 11, 0.5), ('r', 5, 13, 11, 19, 0.5)],+ 'fit': [('p', [(4, 9), (4, 4), (9, 4)]), ('p', [(20, 9), (20, 4), (15, 4)]), ('p', [(4, 15), (4, 20), (9, 20)]),+ ('p', [(20, 15), (20, 20), (15, 20)])],+ 'help': [('a', 12, 9, 3, 180, 395), ('p', [(14.3, 10.9), (12.6, 12.2), (12, 13.6)]), ('d', 12, 17.2, 1.15)],+ 'check': [('p', [(6.8, 12.6), (10.2, 15.9), (17.2, 8.7)])],+ 'x': [('p', [(7, 7), (17, 17)]), ('p', [(17, 7), (7, 17)])],+ 'link': [('a', 9, 15, 4, 45, 315), ('a', 15, 9, 4, 225, 495), ('p', [(9.5, 14.5), (14.5, 9.5)])],+ 'image': [('r', 3.5, 4.5, 20.5, 19.5, 2), ('c', 8.5, 9.5, 1.6), ('p', [(4, 17), (10, 12), (14, 15.5), (16.5, 13.5), (20, 16.5)])],+}+CONTROLS = ['plus', 'minus', 'fit', 'help']+RIBBON = ['menu', 'search', 'file', 'plus_wide', 'grid']+POINTER = [(2, 2), (2, 31), (9.5, 24), (14.5, 36), (19.5, 34), (14.6, 22.4), (25, 22.4)] # the mouse pointer (30 x 40)+++def hexc(h):+ h = h.lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _c(c):+ if isinstance(c, str):+ return hexc(CARD_COLOURS[c]) if c in CARD_COLOURS else hexc(c)+ return np.asarray(c, np.float32)+++def mix(a, b, t):+ """mix two colours (hex / names / rgb) -> rgb array"""+ return _c(a) * (1 - t) + _c(b) * t+++def tohex(c):+ c = np.clip(np.asarray(c, np.float32), 0, 1)+ return '#' + ''.join(f'{int(round(v * 255)):02x}' for v in c)+++# ---------------------------------------------------------------- signed distances (negative inside)+def sdf_rrect(u, v, hw, hh, r):+ r = max(0.0, min(r, hw, hh))+ qx, qy = np.abs(u) - (hw - r), np.abs(v) - (hh - r)+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r+++def sdf_segment(X, Y, a, b):+ ax, ay = float(a[0]), float(a[1]); bx, by = float(b[0]), float(b[1])+ dx, dy = bx - ax, by - ay+ l2 = dx * dx + dy * dy + 1e-9+ t = np.clip(((X - ax) * dx + (Y - ay) * dy) / l2, 0, 1)+ return np.hypot(X - (ax + t * dx), Y - (ay + t * dy))+++def _cov(d):+ return np.clip(0.5 - d, 0, 1).astype(np.float32)+++def _arc_pts(cx, cy, r, a0, a1, step=9.0):+ n = max(6, int(abs(a1 - a0) / step))+ t = np.deg2rad(np.linspace(a0, a1, n))+ return np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)+++def _arclen(P):+ seg = np.hypot(*np.diff(P, axis=0).T) if len(P) > 1 else np.zeros(0)+ return np.concatenate([[0.0], np.cumsum(seg)])+++def _cut(P, frac):+ """the first `frac` (0..1) of polyline P by arc length"""+ if frac >= 1 or len(P) < 2: return P+ s = _arclen(P); L = s[-1] * max(0.0, frac)+ i = int(np.searchsorted(s, L, side='right'))+ if i >= len(P): return P+ if i == 0: return P[:1]+ u = (L - s[i - 1]) / max(s[i] - s[i - 1], 1e-9)+ return np.vstack([P[:i], P[i - 1] + (P[i] - P[i - 1]) * u])+++def _dashes(P, on, off, phase=0.0):+ """split polyline P into dash pieces (on / off along the arc length)"""+ s = _arclen(P); L = s[-1]+ if L <= 0: return []+ out, t = [], -phase+ while t < L:+ a, b = max(t, 0.0), min(t + on, L)+ if b > a:+ m = (s > a) & (s < b)+ pa = np.array([np.interp(a, s, P[:, 0]), np.interp(a, s, P[:, 1])])+ pb = np.array([np.interp(b, s, P[:, 0]), np.interp(b, s, P[:, 1])])+ out.append(np.vstack([pa, P[m], pb]))+ t += on + off+ return out+++def bezier(p0, c0, c1, p1, n=48):+ t = np.linspace(0, 1, n)[:, None]+ p0, c0, c1, p1 = (np.asarray(q, np.float64) for q in (p0, c0, c1, p1))+ return (1 - t) ** 3 * p0 + 3 * (1 - t) ** 2 * t * c0 + 3 * (1 - t) * t ** 2 * c1 + t ** 3 * p1+++EASE = {+ 'linear': lambda u: u,+ 'out': lambda u: 1 - (1 - u) ** 3,+ 'io': lambda u: 3 * u * u - 2 * u ** 3,+ 'back': lambda u: 1 + 2.4 * (u - 1) ** 3 + 1.4 * (u - 1) ** 2, # overshoots ~6 % and settles+ 'drop': lambda u: (u / 0.72) ** 2 if u < 0.72 else 1 - 0.06 * np.sin(np.pi * (u - 0.72) / 0.28), # falls, bounces 6 %+}++# ---------------------------------------------------------------- fonts+_AD = '/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/'+_CJK_FACES = [ # (glob, {weight: face index or file-name token}); first hit wins -- macOS, Linux, Windows+ (_AD + 'PingFang.ttc', {'regular': 3, 'medium': 7, 'bold': 11, 'heavy': 11}),+ ('/System/Library/Fonts/PingFang.ttc', {'regular': 3, 'medium': 7, 'bold': 11, 'heavy': 11}),+ ('/System/Library/Fonts/Hiragino Sans GB.ttc', {'regular': 0, 'medium': 0, 'bold': 2, 'heavy': 2}),+ ('/usr/share/fonts/**/NotoSansCJK*-{W}.tt[cf]', {'regular': 'Regular', 'medium': 'Medium', 'bold': 'Bold', 'heavy': 'Black'}),+ ('/usr/share/fonts/**/NotoSansSC-{W}.[ot]tf', {'regular': 'Regular', 'medium': 'Medium', 'bold': 'Bold', 'heavy': 'Black'}),+ ('C:/Windows/Fonts/msyh{W}.ttc', {'regular': '', 'medium': '', 'bold': 'bd', 'heavy': 'bd'}),+]+_HEAVY_FACES = [(_AD + 'Lantinghei.ttc', 2), ('/System/Library/Fonts/Lantinghei.ttc', 2)]+_HAND_FACES = [(_AD + 'Hannotate.ttc', {'regular': 0, 'medium': 0, 'bold': 2, 'heavy': 2}),+ (_AD + 'Hanzipen.ttc', {'regular': 0, 'medium': 0, 'bold': 2, 'heavy': 2})]+_LATIN_W = {'regular': 400, 'medium': 520, 'bold': 700, 'heavy': 860}+_MONO_W = {'regular': 420, 'medium': 520, 'bold': 680, 'heavy': 800}+_FONTS = {}+++def _find(pat):+ fs = sorted(glob.glob(pat, recursive=True))+ return fs[0] if fs else None+++def _truetype(path, size, idx):+ for i in ([idx, 0] if idx else [0]):+ try:+ return ImageFont.truetype(path, size, index=i)+ except OSError:+ continue+ return None+++def _env(kind):+ p = os.environ.get('INKPAINT_FONT_CANVASBOARD_' + kind)+ return p if p and os.path.exists(p) else None+++def _cjk(weight, size):+ """-> (font, faux-bold stroke px)"""+ env = _env('BOLD') if weight in ('bold', 'heavy') else None+ env = env or _env('CJK')+ if env: return ImageFont.truetype(env, size), 0+ if weight == 'heavy':+ for pat, idx in _HEAVY_FACES:+ p = _find(pat)+ f = p and _truetype(p, size, idx)+ if f: return f, 0+ for pat, faces in _CJK_FACES:+ tok = faces[weight]+ p = _find(pat.replace('{W}', tok)) if isinstance(tok, str) else _find(pat)+ if not p: continue+ f = _truetype(p, size, 2 if (isinstance(tok, str) and p.endswith('.ttc') and 'Noto' in p) else (tok if isinstance(tok, int) else 0))+ if f: return f, 0+ return load_font('cjk_sans', int(size)), (max(1, round(size / 40)) if weight in ('bold', 'heavy') else 0)+++def _hand(weight, size):+ env = _env('HAND')+ if env: return ImageFont.truetype(env, size), 0+ for pat, faces in _HAND_FACES:+ p = _find(pat)+ f = p and _truetype(p, size, faces[weight])+ if f: return f, 0+ return _cjk(weight, size)+++def _latin(weight, size, mono=False):+ env = _env('MONO' if mono else 'LATIN')+ if env: return ImageFont.truetype(env, size)+ p = '/System/Library/Fonts/SFNSMono.ttf' if mono else '/System/Library/Fonts/SFNS.ttf'+ if os.path.exists(p):+ try:+ f = ImageFont.truetype(p, size)+ if mono:+ w = _MONO_W[weight]; f.set_variation_by_axes([w, w])+ else:+ f.set_variation_by_axes([100, float(np.clip(size * 0.75, 17, 96)), 400, _LATIN_W[weight]])+ return f+ except (OSError, ValueError):+ pass+ if mono:+ for q, i in [('/System/Library/Fonts/Menlo.ttc', 1 if weight in ('bold', 'heavy') else 0),+ ('/usr/share/fonts/**/DejaVuSansMono*.ttf', 0), ('C:/Windows/Fonts/consola.ttf', 0)]:+ pp = _find(q)+ if pp:+ f = _truetype(pp, size, i)+ if f: return f+ return load_font('typewriter', int(size))+ if os.path.exists('/System/Library/Fonts/HelveticaNeue.ttc'):+ return ImageFont.truetype('/System/Library/Fonts/HelveticaNeue.ttc', size,+ index={'regular': 0, 'medium': 10, 'bold': 1, 'heavy': 1}[weight])+ return load_font('sans_bold' if weight in ('bold', 'heavy') else 'sans', int(size))+++def _font(kind, weight, size):+ size = max(1.0, round(size * 4) / 4)+ key = (kind, weight, size)+ if key not in _FONTS:+ if len(_FONTS) > 160: _FONTS.clear() # a zoom asks for a new size every frame: keep the cache small+ if kind == 'cjk': _FONTS[key] = _cjk(weight, size)+ elif kind == 'hand': _FONTS[key] = _hand(weight, size)+ else: _FONTS[key] = (_latin(weight, size, kind == 'mono'), 0)+ return _FONTS[key]+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++def spans(s):+ """inline Markdown of one line -> [(text, style)]: ==highlight== `code` **bold**, everything else plain"""+ out = []+ for t in re.split(r'(==.+?==|`.+?`|\*\*.+?\*\*)', s):+ if not t: continue+ if t.startswith('==') and t.endswith('==') and len(t) > 4: out.append((t[2:-2], 'hl'))+ elif t.startswith('`') and t.endswith('`') and len(t) > 2: out.append((t[1:-1], 'code'))+ elif t.startswith('**') and t.endswith('**') and len(t) > 4: out.append((t[2:-2], 'b'))+ else: out.append((t, ''))+ return out+++# ---------------------------------------------------------------- data holders+class Box:+ """a rectangle in board coordinates (cards, groups); .anchor(side, frac) gives an edge anchor on its border"""++ def __init__(self, x0, y0, x1, y1, r=0.0):+ self.x0, self.y0, self.x1, self.y1, self.r = x0, y0, x1, y1, r+ self.w, self.h = x1 - x0, y1 - y0+ self.cx, self.cy = (x0 + x1) / 2, (y0 + y1) / 2++ def __iter__(self):+ return iter((self.x0, self.y0, self.x1, self.y1))++ def anchor(self, side, frac=0.5):+ return {'l': (self.x0, self.y0 + self.h * frac), 'r': (self.x1, self.y0 + self.h * frac),+ 't': (self.x0 + self.w * frac, self.y0), 'b': (self.x0 + self.w * frac, self.y1)}[side]+++class Prim:+ __slots__ = ('fn', 'box', 'var', 'clip')++ def __init__(self, fn, box, var, clip):+ self.fn, self.box, self.var, self.clip = fn, box, var, clip+++class Node:+ def __init__(self, name, kind, z, order):+ self.name, self.kind, self.z, self.order = name, kind, z, order+ self.prims = []+ self.box = None # union of what was drawn (board coords)+ self.rect = None # the card / group Box+ self.pose = dict(dx=0.0, dy=0.0, scale=1.0, alpha=1.0, origin=None)+ self.vars, self.defaults = {}, {}++ def var(self, name):+ return self.vars.get(name, self.defaults.get(name, 1.0))+++def _vspec(var):+ if var is None: return None+ if isinstance(var, str): return (var, 0.0, 1.0)+ return (var[0], float(var[1]), float(var[2]))+++def _union(a, b):+ if a is None: return tuple(b)+ return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))+++class _Target:+ """where the pen draws: an RGB buffer (opaque) or a premultiplied RGBA layer, at pane offset (tx, ty)"""++ def __init__(self, rgb, a=None, tx=0, ty=0):+ self.rgb, self.a, self.tx, self.ty = rgb, a, tx, ty+ self.H, self.W = rgb.shape[:2]+++# ---------------------------------------------------------------- a card's Markdown, laid out top to bottom+class Card(Box):+ """returned by CanvasBoard.card(): Markdown blocks stacked from the top (padding 24 / 22 inside a 2 px border).+ Every block takes var= (see CanvasBoard) and returns the y of its top; `self.y` is the next free y"""++ def __init__(self, cb, name, x0, y0, x1, y1, r, pad):+ super().__init__(x0, y0, x1, y1, r)+ self.cb, self.name = cb, name+ self.left, self.right = x0 + 2 + pad[0], x1 - 2 - pad[0]+ self.y = y0 + 2 + pad[1]++ def _go(self):+ return self.cb._at(self.name)++ def gap(self, px):+ self.y += px+ return self.y++ def h1(self, s, size=52, fill=BRIGHT, var=None, lh=1.3):+ top = self.y+ with self._go(): self.cb.text(s, self.left, top + lh * size / 2, size, fill, 'bold', 'lm', var=var)+ self.y += lh * size+ return top++ def h2(self, s, size=34, fill=BRIGHT, var=None, lh=1.45, glyph=None, glyph_fill=MUTED):+ top = self.y+ x = self.left+ with self._go():+ if glyph:+ self.cb.glyph(glyph, x + size * 0.45, top + lh * size / 2, size * 0.9, glyph_fill, 2.0, var=var)+ x += size * 1.2+ self.cb.text(s, x, top + lh * size / 2, size, fill, 'bold', 'lm', var=var)+ self.y += lh * size+ return top++ def p(self, s, size=28, fill=TEXT, weight='regular', var=None, hl=None, lh=1.55, x=None):+ """one line of inline Markdown (==highlight== `code` **bold**); hl= var that sweeps the highlights"""+ top = self.y+ with self._go(): self.cb.rich(s, self.left if x is None else x, top + lh * size / 2, size, fill, weight, var=var, hl=hl)+ self.y += lh * size+ return top++ def task(self, s, done=True, key=None, size=28, lh=1.62, var=None):+ """a task-list line; done=True draws it ticked. key= a var (0 -> 1) that animates the tick: the box fills+ violet, the check draws on, a strike runs through the text and the text greys"""+ top = self.y+ with self._go(): self.cb.task(s, self.left, top + lh * size / 2, size, done, key, var=var)+ self.y += lh * size+ return top++ def quote(self, lines, size=34, fill=BRIGHT, by=None, by_size=22, var=None, lh=1.45, bar=ACCENT):+ """a blockquote: a 4 px violet bar and the lines beside it; `by` = a small grey line underneath"""+ top = self.y+ lines = [lines] if isinstance(lines, str) else lines+ h = lh * size * len(lines)+ with self._go():+ self.cb.rrect(self.left, top + 4, self.left + 4, top + h - 4, 2, bar, var=var)+ for i, s in enumerate(lines):+ self.cb.rich(s, self.left + 24, top + lh * size * (i + 0.5), size, fill, 'medium', var=var)+ if by:+ self.cb.text(by, self.left + 24, top + h + by_size * 0.95, by_size, MUTED, 'regular', 'lm', var=var)+ self.y += h + (by_size * 1.9 if by else 0)+ return top++ def tags(self, tags, size=22, var=None, gap=10):+ top = self.y+ x = self.left+ with self._go():+ for t in tags:+ x = self.cb.tag(t, x, top + size * 0.85, size, var=var) + gap+ self.y += size * 1.9+ return top++ def chips(self, items, size=26, var=None, gap=14, per_row=2, row_h=None):+ """colour chips in rows: items = [(label, code, colour)], e.g. ('厨房', 'K1–K6', 'orange')"""+ top = self.y+ row_h = row_h or size * 2.3+ cw = (self.right - self.left - gap * (per_row - 1)) / per_row+ with self._go():+ for i, (label, code, colour) in enumerate(items):+ r, c = divmod(i, per_row)+ v = var[i] if isinstance(var, list) else var+ self.cb.chip(self.left + c * (cw + gap), top + r * row_h, cw, size * 1.85, label, code, colour, size, var=v)+ self.y += row_h * ((len(items) + per_row - 1) // per_row)+ return top++ def bar(self, frac, h=10, fill=ACCENT, var=None, label=None, size=22):+ top = self.y+ with self._go():+ x1 = self.right+ if label:+ self.cb.text(label, self.right, top + h / 2, size, MUTED, 'medium', 'rm', family='mono', var=var)+ x1 = self.right - self.cb.measure(label, size, 'medium', family='mono') - 16+ self.cb.rrect(self.left, top, x1, top + h, h / 2, '#333333', var=var)+ self.cb.rrect(self.left, top, self.left + (x1 - self.left) * frac, top + h, h / 2, fill, var=var,+ mode='reveal')+ self.y += h+ return top++ def rule(self, pad=14, fill=BORDER, var=None):+ self.y += pad+ with self._go(): self.cb.rrect(self.left, self.y, self.right, self.y + 1.5, 0, fill, var=var)+ self.y += pad + 1.5+ return self.y+++# ---------------------------------------------------------------- the board+class CanvasBoard:+ GLYPHS = GLYPHS+ CARD_COLOURS = CARD_COLOURS++ def __init__(self, W=1920, H=1080, seed=0, keep_stages=True, stages_dir=None, window=None, tab='未命名.canvas',+ ribbon=True, controls=True, glow=True):+ self.W, self.H = W, H+ self.seed = seed+ self.rng = np.random.default_rng(seed)+ self.keep_stages, self.stages_dir = keep_stages, stages_dir+ self.stages, self._nstage = [], 0+ if stages_dir: os.makedirs(stages_dir, exist_ok=True)+ wx, wy, ww, wh = window or (round(W * 0.0208), round(H * 0.0315), W - 2 * round(W * 0.0208), H - 2 * round(H * 0.0315))+ self.win = Box(wx, wy, wx + ww, wy + wh, 14)+ self.tab, self.ribbon, self.controls, self.glow = tab, ribbon, controls, glow+ self.bar_h, self.rib_w = 52, (52 if ribbon else 0)+ self.pane = Box(wx + self.rib_w, wy + self.bar_h, wx + ww, wy + wh)+ self.VW, self.VH = int(self.pane.w), int(self.pane.h)+ self.cam = (0.0, 0.0, 1.0)+ self.grid, self.dot_r = 28.0, 1.6+ self.nodes = {}+ self.cur = None+ self._clip = None+ self._chrome = None+ self.hover = None # index of a highlighted zoom button+ self._cursor = None+ g = np.random.default_rng(seed + 7).random((H, W)).astype(np.float32)+ self._grain = (g - 0.5) * (1.2 / 255)+ # pen state (set while rendering)+ self._tg = None+ self._k, self._ox, self._oy = 1.0, 0.0, 0.0+ self._clip_s = None++ # ------------------------------------------------------------ nodes, poses, vars+ def node(self, name, kind='shape', z=None):+ """start recording into node `name` (re-opens it if it exists). z: depth (default by kind: groups 0, edges 5,+ cards 10, everything else 20); lower z is drawn first"""+ if name not in self.nodes:+ zz = {'group': 0, 'edge': 5, 'card': 10}.get(kind, 20) if z is None else z+ self.nodes[name] = Node(name, kind, zz, len(self.nodes))+ elif z is not None:+ self.nodes[name].z = z+ self.cur = self.nodes[name]+ return self.cur++ def end(self):+ self.cur = None++ @contextmanager+ def _at(self, name):+ old = self.cur+ self.cur = self.nodes[name]+ try:+ yield+ finally:+ self.cur = old++ def pose(self, name, dx=0.0, dy=0.0, scale=1.0, alpha=1.0, origin=None):+ """how node `name` is shown: offset (board px), scale about `origin` (default: its centre) and opacity.+ pose(name) = at rest"""+ self.nodes[name].pose = dict(dx=dx, dy=dy, scale=scale, alpha=alpha, origin=origin)++ def set(self, name, **vars):+ """set progress vars of node `name` (unset vars read their default: 1 = finished, or what the node set)"""+ self.nodes[name].vars.update(vars)++ def reset(self, name):+ self.nodes[name].vars.clear()++ def show(self, *names, alpha=1.0):+ for n in names: self.nodes[n].pose['alpha'] = alpha++ def hide(self, *names):+ for n in names: self.nodes[n].pose['alpha'] = 0.0++ def rect(self, name):+ N = self.nodes[name]+ return N.rect or Box(*N.box)++ @contextmanager+ def clip(self, x0, y0=None, x1=None, y1=None, r=0.0):+ """shapes recorded inside are clipped to this rounded rectangle (board coords); clip(box) takes a Box"""+ if isinstance(x0, Box): x0, y0, x1, y1, r = x0.x0, x0.y0, x0.x1, x0.y1, x0.r+ old = self._clip+ self._clip = (x0, y0, x1, y1, r)+ try:+ yield+ finally:+ self._clip = old++ def _rec(self, fn, box, var=None):+ N = self.cur+ if N is None: raise ValueError('open a node first: node(name), group(), card() or edge()')+ N.prims.append(Prim(fn, box, _vspec(var), self._clip))+ N.box = _union(N.box, box)++ # ------------------------------------------------------------ camera+ def camera(self, x, y, z=1.0):+ """the board point (x, y) at the centre of the pane, zoom z"""+ self.cam = (float(x), float(y), float(z))++ def fit(self, x0, y0, x1, y1, pad=60, zmax=2.0, right=0):+ """-> (x, y, z): the camera that shows the board box with `pad` screen px around it (`right`: extra px+ kept free on the right, e.g. for the zoom buttons)"""+ z = min((self.VW - 2 * pad - right) / (x1 - x0), (self.VH - 2 * pad) / (y1 - y0), zmax)+ return ((x0 + x1) / 2 + right / 2 / z, (y0 + y1) / 2, z)++ def to_screen(self, x, y, cam=None):+ """board point -> canvas pixel (for a cursor over a card)"""+ cx, cy, z = cam or self.cam+ return self.pane.x0 + self.VW / 2 + (x - cx) * z, self.pane.y0 + self.VH / 2 + (y - cy) * z++ def control(self, i):+ """canvas-pixel centre of zoom button i (0 +, 1 -, 2 fit, 3 ?)"""+ x0 = self.pane.x1 - 18 - 50+ return x0 + 25, self.pane.y0 + 18 + 8 + 13 + i * 40++ def cursor(self, x=None, y=None, click=None, alpha=1.0, press=False):+ """the mouse pointer (tip at canvas pixel x, y); click = 0..1 progress of the violet click ring;+ cursor() hides it"""+ self._cursor = None if x is None else (x, y, click, alpha, press)++ # ------------------------------------------------------------ the pen (board coords -> current target)+ def _S(self, x, y):+ return x * self._k + self._ox, y * self._k + self._oy++ def _grid(self, x0, y0, x1, y1):+ T = self._tg+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(T.W, int(np.ceil(x1)) + 1), min(T.H, int(np.ceil(y1)) + 1)+ if x1 <= x0 or y1 <= y0: return None+ X = np.arange(x0, x1, dtype=np.float32)[None, :] + 0.5+ Y = np.arange(y0, y1, dtype=np.float32)[:, None] + 0.5+ return (slice(y0, y1), slice(x0, x1)), X, Y++ def _over(self, sl, cov, col):+ cov = np.clip(cov, 0, 1).astype(np.float32)+ if self._clip_s is not None:+ cx0, cy0, cx1, cy1, cr = self._clip_s+ X = np.arange(sl[1].start, sl[1].stop, dtype=np.float32)[None, :] + 0.5+ Y = np.arange(sl[0].start, sl[0].stop, dtype=np.float32)[:, None] + 0.5+ cov = cov * _cov(sdf_rrect(X - (cx0 + cx1) / 2, Y - (cy0 + cy1) / 2, (cx1 - cx0) / 2, (cy1 - cy0) / 2, cr))+ col = col if (isinstance(col, np.ndarray) and col.ndim == 3) else _c(col)+ c3 = cov[..., None]+ T = self._tg+ T.rgb[sl] = T.rgb[sl] * (1 - c3) + col * c3+ if T.a is not None:+ T.a[sl] = T.a[sl] * (1 - cov) + cov++ def _w(self, w, floor=0.0):+ return max(w * self._k, floor)++ # screen-space primitives (already transformed coordinates)+ def _s_rrect(self, x0, y0, x1, y1, r, fill, alpha=1.0, ring=0.0, inset=True, reveal=1.0):+ g = self._grid(x0 - ring - 2, y0 - ring - 2, x1 + ring + 2, y1 + ring + 2)+ if not g or alpha <= 0: return+ sl, X, Y = g+ d = sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, r)+ if ring:+ d = np.abs(d + ring / 2) - ring / 2 if inset else np.abs(d - ring / 2) - ring / 2+ cov = _cov(d) * alpha+ if reveal < 1:+ cov = cov * np.clip((x0 + (x1 - x0) * reveal - X) + 0.5, 0, 1)+ self._over(sl, cov, fill)++ def _s_circle(self, cx, cy, r, fill, alpha=1.0, ring=0.0):+ g = self._grid(cx - r - 2, cy - r - 2, cx + r + 2, cy + r + 2)+ if not g or alpha <= 0 or r <= 0: return+ sl, X, Y = g+ d = np.hypot(X - cx, Y - cy) - r+ if ring: d = np.abs(d + ring / 2) - ring / 2+ self._over(sl, _cov(d) * alpha, fill)++ def _s_line(self, P, width, fill, alpha=1.0):+ P = np.asarray(P, np.float32)+ if len(P) < 2 or alpha <= 0: return+ pad = width / 2 + 2+ g = self._grid(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)+ if not g: return+ sl, X, Y = g+ gx0, gy0 = sl[1].start, sl[0].start+ cov = np.zeros((sl[0].stop - gy0, sl[1].stop - gx0), np.float32)+ for a, b in zip(P[:-1], P[1:]):+ sx0 = max(gx0, int(np.floor(min(a[0], b[0]) - pad))) - gx0+ sx1 = min(sl[1].stop, int(np.ceil(max(a[0], b[0]) + pad)) + 1) - gx0+ sy0 = max(gy0, int(np.floor(min(a[1], b[1]) - pad))) - gy0+ sy1 = min(sl[0].stop, int(np.ceil(max(a[1], b[1]) + pad)) + 1) - gy0+ if sx1 <= sx0 or sy1 <= sy0: continue+ d = sdf_segment(X[:, sx0:sx1], Y[sy0:sy1, :], a, b) - width / 2+ np.maximum(cov[sy0:sy1, sx0:sx1], _cov(d), out=cov[sy0:sy1, sx0:sx1])+ self._over(sl, cov * alpha, fill)++ def _s_poly(self, P, fill, alpha=1.0, ss=4):+ P = np.asarray(P, np.float32)+ x0, y0 = int(np.floor(P[:, 0].min())) - 1, int(np.floor(P[:, 1].min())) - 1+ x1, y1 = int(np.ceil(P[:, 0].max())) + 2, int(np.ceil(P[:, 1].max())) + 2+ g = self._grid(x0, y0, x1 - 1, y1 - 1)+ if not g or alpha <= 0: return+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P.tolist()], fill=255)+ m = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ sl = g[0]+ m = m[sl[0].start - y0:sl[0].stop - y0, sl[1].start - x0:sl[1].stop - x0]+ self._over(sl, m * alpha, fill)++ def _s_shadow(self, x0, y0, x1, y1, r, dx, dy, blur_px, spread, colour, alpha):+ sig = blur_px / 2+ pad = 3 * sig + abs(spread) + 3+ g = self._grid(min(x0, x0 + dx) - pad, min(y0, y0 + dy) - pad, max(x1, x1 + dx) + pad, max(y1, y1 + dy) + pad)+ if not g or alpha <= 0: return+ sl, X, Y = g+ sx0, sy0, sx1, sy1 = x0 - spread + dx, y0 - spread + dy, x1 + spread + dx, y1 + spread + dy+ if sx1 <= sx0 or sy1 <= sy0: return+ m = _cov(sdf_rrect(X - (sx0 + sx1) / 2, Y - (sy0 + sy1) / 2, (sx1 - sx0) / 2, (sy1 - sy0) / 2, max(0.0, r + spread)))+ own = _cov(sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, r))+ if sig > 0.3: m = blur(m, sig)+ self._over(sl, m * (1 - own) * alpha, colour)++ def _glyphs(self, s, size, weight, spacing, family):+ out, x = [], 0.0+ if family == 'hand':+ f, fake = _font('hand', weight, size)+ return [(f, s, 0.0, fake)], f.getlength(s)+ runs = []+ for ch in s:+ k = _is_cjk(ch)+ if runs and runs[-1][1] == k: runs[-1][0] += ch+ else: runs.append([ch, k])+ for piece, k in runs:+ f, fake = _font('cjk' if k else ('mono' if family == 'mono' else 'latin'), weight, size)+ if spacing:+ for ch in piece:+ out.append((f, ch, x, fake)); x += f.getlength(ch) + spacing+ else:+ out.append((f, piece, x, fake)); x += f.getlength(piece)+ return out, (x - spacing if (spacing and s) else x)++ def _s_text(self, s, x, y, size, fill, weight='regular', anchor='ls', alpha=1.0, spacing=0.0, family='sans',+ reveal=1.0, feather=10.0):+ if size < 3 or not s:+ return self._glyphs(s, max(size, 3), weight, spacing, family)[1] if s else 0.0+ gl, tw = self._glyphs(s, size, weight, spacing, family)+ x0 = x - tw * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ base = y + {'s': 0.0, 'm': 0.37 * size, 't': 0.86 * size}[anchor[1]]+ if alpha <= 0 or reveal <= 0: return tw+ bx0, by0 = int(np.floor(x0)) - 6, int(np.floor(base - size * 1.25))+ bw, bh = int(tw) + 14, int(size * 1.7) + 8+ g = self._grid(bx0, by0, bx0 + bw - 1, by0 + bh - 1)+ if not g: return tw+ im = Image.new('L', (bw, bh), 0)+ dr = ImageDraw.Draw(im)+ for f, piece, off, fake in gl:+ dr.text((x0 - bx0 + off, base - by0), piece, font=f, fill=255, anchor='ls', stroke_width=fake, stroke_fill=255)+ m = np.asarray(im, np.float32) / 255+ if reveal < 1:+ xs = np.arange(bw, dtype=np.float32) + bx0 + 0.5+ m = m * np.clip((x0 - 4 + (tw + 8) * reveal - xs) / max(feather, 1) + 0.5, 0, 1)[None, :]+ sl = g[0]+ m = m[sl[0].start - by0:sl[0].stop - by0, sl[1].start - bx0:sl[1].stop - bx0]+ self._over(sl, m * alpha, fill)+ return tw++ def _s_glyph(self, name, cx, cy, size, fill, sw=1.8, alpha=1.0, draw=1.0):+ k = size / 24.0+ pad = size * 0.6 + 2+ g = self._grid(cx - pad, cy - pad, cx + pad, cy + pad)+ if not g or alpha <= 0: return+ sl, X, Y = g+ u, v = (X - cx) / k + 12, (Y - cy) / k + 12+ d = np.full(np.broadcast(u, v).shape, 1e9, np.float32)+ for p in GLYPHS[name]:+ kind = p[0]+ if kind == 'p':+ P = np.asarray(p[1], np.float32)+ if len(p) > 2 and p[2]: P = np.vstack([P, P[:1]])+ if draw < 1: P = _cut(P, draw)+ e = np.full(d.shape, 1e9, np.float32)+ for a, b in zip(P[:-1], P[1:]):+ e = np.minimum(e, sdf_segment(u, v, a, b))+ e = e - sw / 2+ elif kind == 'c':+ e = np.abs(np.hypot(u - p[1], v - p[2]) - p[3]) - sw / 2+ elif kind == 'a':+ P = _arc_pts(*p[1:])+ e = np.full(d.shape, 1e9, np.float32)+ for a, b in zip(P[:-1], P[1:]):+ e = np.minimum(e, sdf_segment(u, v, a, b))+ e = e - sw / 2+ elif kind == 'd':+ e = np.hypot(u - p[1], v - p[2]) - p[3]+ else:+ x0, y0, x1, y1, rr = p[1:]+ e = np.abs(sdf_rrect(u - (x0 + x1) / 2, v - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, rr)) - sw / 2+ d = np.minimum(d, e)+ self._over(sl, _cov(d * k) * alpha, fill)++ # ------------------------------------------------------------ recorded shapes (board coords)+ @staticmethod+ def _amt(t, mode):+ """(alpha factor, draw fraction, reveal fraction, pop scale) for progress t under `mode`"""+ if mode == 'fade': return t, 1.0, 1.0, 1.0+ if mode == 'draw': return (1.0 if t > 0 else 0.0), t, 1.0, 1.0+ if mode == 'reveal': return (1.0 if t > 0 else 0.0), 1.0, t, 1.0+ if mode == 'pop': return min(1.0, 2.2 * t), 1.0, 1.0, (EASE['back'](t) * 0.7 + 0.3 if t > 0 else 0.0)+ return t, 1.0, 1.0, 1.0++ def rrect(self, x0, y0, x1, y1, r=0.0, fill=TEXT, alpha=1.0, ring=0.0, inset=True, var=None, mode='fade', hair=True):+ """rounded rectangle; ring=w draws only a w px line along the edge (inside if inset). hair: rings never get+ thinner than 1 screen px when zoomed out"""+ def fn(t):+ al, _, rv, sc = self._amt(t, mode)+ if al <= 0: return+ a, b = self._S(x0, y0); c, d = self._S(x1, y1)+ if sc != 1:+ mx, my = (a + c) / 2, (b + d) / 2+ a, c, b, d = mx + (a - mx) * sc, mx + (c - mx) * sc, my + (b - my) * sc, my + (d - my) * sc+ rw = self._w(ring, min(ring, 1.0) if hair else 0) if ring else 0.0+ self._s_rrect(a, b, c, d, r * self._k * sc, fill, alpha * al, rw, inset, rv)+ self._rec(fn, (x0 - ring - 2, y0 - ring - 2, x1 + ring + 2, y1 + ring + 2), var)++ def circle(self, cx, cy, r, fill=TEXT, alpha=1.0, ring=0.0, var=None, mode='fade'):+ def fn(t):+ al, _, _, sc = self._amt(t, mode)+ if al <= 0: return+ x, y = self._S(cx, cy)+ self._s_circle(x, y, r * self._k * sc, fill, alpha * al, self._w(ring, min(ring, 1.0)) * sc if ring else 0.0)+ self._rec(fn, (cx - r - ring - 2, cy - r - ring - 2, cx + r + ring + 2, cy + r + ring + 2), var)++ def line(self, pts, width=2.0, fill=TEXT, alpha=1.0, var=None, mode='draw', dash=None, closed=False, floor=0.9):+ """polyline with round caps and joins; mode 'draw' draws it on along its length; dash=(on, off) board px"""+ P = np.asarray(pts, np.float64)+ if closed: P = np.vstack([P, P[:1]])++ def fn(t):+ al, dr, _, _ = self._amt(t, mode)+ if al <= 0 or dr <= 0: return+ Q = _cut(P, dr) * self._k + np.array([self._ox, self._oy])+ w = self._w(width, floor)+ if dash:+ for piece in _dashes(Q, dash[0] * self._k, dash[1] * self._k):+ self._s_line(piece, w, fill, alpha * al)+ else:+ self._s_line(Q, w, fill, alpha * al)+ self._rec(fn, (P[:, 0].min() - width - 2, P[:, 1].min() - width - 2, P[:, 0].max() + width + 2, P[:, 1].max() + width + 2), var)++ def poly(self, pts, fill=TEXT, alpha=1.0, var=None, mode='fade'):+ P = np.asarray(pts, np.float64)++ def fn(t):+ al, _, _, sc = self._amt(t, mode)+ if al <= 0: return+ Q = P * self._k + np.array([self._ox, self._oy])+ if sc != 1:+ m = Q.mean(0); Q = m + (Q - m) * sc+ self._s_poly(Q, fill, alpha * al)+ self._rec(fn, (P[:, 0].min() - 2, P[:, 1].min() - 2, P[:, 0].max() + 2, P[:, 1].max() + 2), var)++ def shadow(self, x0, y0, x1, y1, r=0.0, dx=0.0, dy=0.0, blur_px=0.0, spread=0.0, colour='#000000', alpha=0.3,+ var=None, mode='fade'):+ """CSS box-shadow of a rounded rectangle (board px; painted outside the element only)"""+ def fn(t):+ al = self._amt(t, mode)[0]+ if al <= 0: return+ a, b = self._S(x0, y0); c, d = self._S(x1, y1); k = self._k+ self._s_shadow(a, b, c, d, r * k, dx * k, dy * k, blur_px * k, spread * k, colour, alpha * al)+ p = 1.5 * blur_px + abs(spread) + max(abs(dx), abs(dy)) + 4+ self._rec(fn, (x0 - p, y0 - p, x1 + p, y1 + p), var)++ def text(self, s, x, y, size, fill=TEXT, weight='regular', anchor='ls', alpha=1.0, spacing=0.0, family='sans',+ var=None, mode='reveal'):+ """text at board (x, y); anchor [l m r] + [s baseline, m middle of the CJK body, t top]. weight: regular /+ medium / bold / heavy; family: sans / mono / hand. Returns the width (board px)"""+ tw = self.measure(s, size, weight, spacing, family)++ def fn(t):+ al, _, rv, _ = self._amt(t, mode)+ if al <= 0: return+ sx, sy = self._S(x, y)+ self._s_text(s, sx, sy, size * self._k, fill, weight, anchor, alpha * al, spacing * self._k, family, rv)+ x0 = x - tw * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ self._rec(fn, (x0 - 4, y - size * 1.4, x0 + tw + 4, y + size * 1.4), var)+ return tw++ def glyph(self, name, cx, cy, size=24, fill=MUTED, sw=1.8, alpha=1.0, var=None, mode='fade'):+ def fn(t):+ al, dr, _, sc = self._amt(t, mode)+ if al <= 0: return+ x, y = self._S(cx, cy)+ self._s_glyph(name, x, y, size * self._k * sc, fill, sw, alpha * al, dr)+ self._rec(fn, (cx - size, cy - size, cx + size, cy + size), var)++ def measure(self, s, size, weight='regular', spacing=0.0, family='sans'):+ """advance width in board px"""+ return self._glyphs(s, size, weight, spacing, family)[1]++ # ------------------------------------------------------------ Markdown pieces (used by Card, usable directly)+ def rich(self, s, x, y, size=28, fill=TEXT, weight='regular', var=None, hl=None):+ """one line of inline Markdown at board (x, y = middle of the line): ==highlight== (violet, sweeps with var+ `hl`), `code` (mono on a dark pill), **bold**. Laid out again at every zoom, so runs never drift apart"""+ sp = spans(s)+ hls = _vspec(hl)+ tw = 0.0+ for t, st in sp:+ tw += self._run_w(t, st, size, weight)++ def fn(t):+ al, _, rv, _ = self._amt(t, 'reveal')+ if al <= 0: return+ N = self._drawing+ q = 1.0+ if hls:+ v = N.var(hls[0]); q = float(np.clip((v - hls[1]) / max(hls[2] - hls[1], 1e-6), 0, 1))+ k = self._k+ sx, sy = self._S(x, y)+ fs = size * k+ cx = sx+ right = None if rv >= 1 else sx - 4 + (tw * k + 8) * rv # a line being written, left to right+ for txt, st in sp:+ w = self._run_w(txt, st, fs, weight)+ rr = 1.0 if right is None else float(np.clip((right - cx) / max(w, 1e-6), 0, 1))+ if rr <= 0: break+ if st == 'hl' and q > 0:+ self._s_rrect(cx - 3 * k, sy - 0.66 * fs, cx + (w + 3 * k) * q * rr, sy + 0.62 * fs, 6 * k,+ ACCENT, 0.45 * al)+ if st == 'code':+ self._s_rrect(cx, sy - 0.62 * fs, cx + w, sy + 0.58 * fs, 6 * k, CODE_BG, al, reveal=rr)+ self._s_text(txt, cx + 8 * k, sy, fs * 0.88, CODE_FG, 'regular', 'lm', al, family='mono', reveal=rr)+ else:+ col = BRIGHT if (st == 'b' or (st == 'hl' and q > 0.35)) else fill+ self._s_text(txt, cx, sy, fs, col, 'bold' if st == 'b' else weight, 'lm', al, reveal=rr)+ cx += w+ self._rec(fn, (x - 6, y - size, x + tw + 6, y + size), var)+ return tw++ def _run_w(self, txt, st, size, weight):+ if st == 'code':+ return self._glyphs(txt, size * 0.88, 'regular', 0.0, 'mono')[1] + 16 * size / 28+ return self._glyphs(txt, size, 'bold' if st == 'b' else weight, 0.0, 'sans')[1]++ def task(self, s, x, y, size=28, done=True, key=None, var=None):+ """a task-list line at board (x, y = middle): a checkbox and the text. done=True is ticked; key= a var+ (0..1) that animates the tick (fill pops, check draws, strike runs, text greys). Returns the text width"""+ bs = size * 0.8+ tx = x + bs + size * 0.55+ tw = self.measure(s, size)+ ks = _vspec(key)++ def fn(t):+ al = self._amt(t, 'fade')[0]+ if al <= 0: return+ N = self._drawing+ u = 1.0 if ks is None else float(np.clip((N.var(ks[0]) - ks[1]) / max(ks[2] - ks[1], 1e-6), 0, 1))+ if not done: u = 0.0+ k = self._k+ bx, by = self._S(x, y)+ S = bs * k+ pop = EASE['back'](min(1.0, u * 1.7)) if u > 0 else 0.0+ self._s_rrect(bx, by - S / 2, bx + S, by + S / 2, S * 0.24, FAINT, al * (1 - min(1, u * 2.5)), self._w(2.0, 1.0))+ if pop > 0:+ m = S / 2 * pop+ self._s_rrect(bx + S / 2 - m, by - m, bx + S / 2 + m, by + m, S * 0.24 * pop, ACCENT, al * min(1, u * 2.2))+ ck = float(np.clip(u * 1.6 - 0.35, 0, 1))+ if ck > 0:+ self._s_glyph('check', bx + S / 2, by, S * 1.05, WHITE, 2.9, al, ck)+ col = mix(TEXT, DONE, float(np.clip((u - 0.25) / 0.6, 0, 1)))+ sx, _ = self._S(tx, y)+ w = self._s_text(s, sx, by, size * k, col, 'regular', 'lm', al)+ st = float(np.clip((u - 0.3) / 0.7, 0, 1))+ if st > 0:+ self._s_rrect(sx - 2 * k, by - 0.06 * size * k - max(1.0, 1.1 * k), sx - 2 * k + (w + 4 * k) * st,+ by - 0.06 * size * k + max(1.0, 1.1 * k), 1.2 * k, DONE, al)+ self._rec(fn, (x - 4, y - size, tx + tw + 8, y + size), var)+ return tw++ def tag(self, s, x, y, size=22, var=None):+ """a #tag pill (violet text on a faint violet capsule), left edge at x, middle at y. Returns the right edge"""+ tw = self.measure(s, size, 'medium')+ h = size * 1.55+ x1 = x + tw + size * 1.1+ self.rrect(x, y - h / 2, x1, y + h / 2, h / 2, ACCENT, 0.16, var=var)+ self.text(s, x + size * 0.55, y, size, ACCENT2, 'medium', 'lm', var=var, mode='fade')+ return x1++ def chip(self, x, y, w, h, label, code=None, colour='orange', size=26, var=None):+ """a colour-coded chip (box labels, categories): tinted fill, coloured ring, a dot, the label and a mono code"""+ col = _c(colour)+ self.rrect(x, y, x + w, y + h, 10, tohex(mix(BG3, col, 0.12)), var=var)+ self.rrect(x, y, x + w, y + h, 10, tohex(col), 0.55, ring=2.0, var=var)+ self.circle(x + size * 0.85, y + h / 2, size * 0.24, tohex(col), var=var)+ lw = self.text(label, x + size * 1.45, y + h / 2, size, BRIGHT, 'medium', 'lm', var=var, mode='fade')+ if code:+ self.text(code, x + w - size * 0.7, y + h / 2, size * 0.9, tohex(col), 'medium', 'rm', family='mono', var=var,+ mode='fade')+ return lw++ # ------------------------------------------------------------ canvas objects+ def group(self, name, x, y, w, h, label=None, colour=None, z=None, label_size=34):+ """a group frame (radius 20, 2 px line, a whisper of fill) with its label floating above the top-left+ corner, like the app. colour= tints the frame with a card colour"""+ self.node(name, 'group', z)+ line = tohex(mix(GROUP_LINE, colour, 0.75)) if colour else GROUP_LINE+ fill = tohex(_c(colour)) if colour else WHITE+ self.rrect(x, y, x + w, y + h, 20, fill, 0.045 if colour else 0.025, var='frame')+ self.rrect(x, y, x + w, y + h, 20, line, ring=2.0, var='frame')+ if label:+ self.text(label, x + 6, y - 18, label_size, tohex(mix(MUTED, colour, 0.6)) if colour else MUTED, 'bold', 'ls',+ var='label', mode='fade')+ self.cur.rect = Box(x, y, x + w, y + h, 20)+ self.end()+ return self.nodes[name].rect++ def card(self, name, x, y, w, h, colour=None, label=None, z=None, pad=(24, 22), fill=None, selected=False,+ shadow=True, tint=0.05):+ """a card: dark rounded body (radius 12), a 2 px border in a card colour (red orange yellow green cyan purple,+ 'accent', a hex, or None = grey) with a faint tint of it (5 %), a soft drop shadow, an optional file-name label above.+ selected=True: violet border and a faint violet halo (also var 'sel'). var 'lift' (default 0) adds the big+ shadow of a card held above the board. Returns a Card for its Markdown"""+ self.node(name, 'card', z)+ N = self.cur+ N.defaults.update(lift=0.0, sel=1.0 if selected else 0.0)+ col = _c(colour) if colour else None+ body = fill or (tohex(mix(BG2, col, tint)) if col is not None else BG2)+ edge = tohex(col) if col is not None else BORDER2+ x1, y1 = x + w, y + h+ if shadow:+ self.shadow(x, y, x1, y1, 12, 0, 20, 40, -24, '#000000', 0.8)+ self.shadow(x, y, x1, y1, 12, 0, 46, 70, -18, '#000000', 0.75, var='lift')+ self.rrect(x - 6, y - 6, x1 + 6, y1 + 6, 17, ACCENT, 0.18, var='sel')+ self.rrect(x, y, x1, y1, 12, body)+ self.rrect(x, y, x1, y1, 12, edge, ring=2.0)+ self.rrect(x, y, x1, y1, 12, ACCENT, ring=2.0, var='sel')+ if label:+ self.text(label, x + 4, y - 16, 28, MUTED, 'bold', 'ls', mode='fade')+ c = Card(self, name, x, y, x1, y1, 12, pad)+ N.rect = Box(x, y, x1, y1, 12)+ self.end()+ return c++ def image_card(self, name, x, y, w, h, label=None, bg='#191919', grid=22, grid_colour='#222222', z=None):+ """an image card (no padding, the picture fills it, file name above): returns the Card; draw the picture with+ `with cb.clip(card): ...` into node `name` (cb.node(name))"""+ c = self.card(name, x, y, w, h, None, label, z, (0, 0), fill=bg)+ self.node(name)+ if grid:+ with self.clip(x + 2, y + 2, x + w - 2, y + h - 2, 10):+ for gx in np.arange(x + grid, x + w, grid):+ self.rrect(gx - 0.5, y, gx + 0.5, y + h, 0, grid_colour, hair=False)+ for gy in np.arange(y + grid, y + h, grid):+ self.rrect(x, gy - 0.5, x + w, gy + 0.5, 0, grid_colour, hair=False)+ self.rrect(x, y, x + w, y + h, 12, BORDER2, ring=2.0)+ self.end()+ return c++ def _anchor(self, a):+ """(node, side[, frac]) or (x, y, side) -> (x, y, side)"""+ if isinstance(a[0], str):+ side = a[1]; frac = a[2] if len(a) > 2 else 0.5+ return (*self.rect(a[0]).anchor(side, frac), side)+ return a++ def edge(self, name, a, b, colour=EDGE, width=4.0, label=None, dashed=False, arrow=True, z=None, label_size=24,+ bend=1.0):+ """a curved edge between two anchors -- (card name, side 'l' 'r' 't' 'b'[, frac along the side]) or+ (x, y, side) -- a cubic that leaves and enters along the sides' normals, an arrowhead on the end, an optional+ label on a board-coloured pill at its middle. var 'p' (0..1) draws it on: the arrow grows over the last 14 %,+ the label fades in after half. Returns the board-coordinate polyline"""+ self.node(name, 'edge', z)+ ax, ay, sa = self._anchor(a)+ bx, by, sb = self._anchor(b)+ NV = {'l': (-1, 0), 'r': (1, 0), 't': (0, -1), 'b': (0, 1)}+ dist = np.hypot(bx - ax, by - ay)+ c = float(np.clip(dist * 0.45, 50, 240)) * bend+ P = bezier((ax, ay), (ax + NV[sa][0] * c, ay + NV[sa][1] * c), (bx + NV[sb][0] * c, by + NV[sb][1] * c), (bx, by), 64)+ nx, ny = NV[sb]+ ang = np.arctan2(-ny, -nx)+ head = np.array([(2, 0), (-18, -10), (-18, 10)], np.float64) * (width / 4) ** 0.5+ rot = np.array([[np.cos(ang), -np.sin(ang)], [np.sin(ang), np.cos(ang)]])+ line_end = P.copy()+ if arrow: # stop the line under the arrowhead so its round cap never peeks past the tip+ line_end = _cut(P, 1 - 10 * (width / 4) ** 0.5 / max(_arclen(P)[-1], 1))+ lab_box = None+ if label:+ mid = P[len(P) // 2]+ lw = self.measure(label, label_size, 'medium')+ lab_box = (mid[0] - lw / 2 - 12, mid[1] - label_size * 0.85, mid[0] + lw / 2 + 12, mid[1] + label_size * 0.85)++ def fn(t):+ if t <= 0: return+ k, o = self._k, np.array([self._ox, self._oy])+ Q = _cut(line_end, min(1.0, t / 0.97)) * k + o+ w = self._w(width, 1.0)+ if dashed:+ for piece in _dashes(Q, 12 * k, 12 * k):+ self._s_line(piece, w, colour)+ else:+ self._s_line(Q, w, colour)+ hp = float(np.clip((t - 0.86) / 0.14, 0, 1))+ if arrow and hp > 0:+ H = (head * hp) @ rot.T + np.array([bx, by])+ self._s_poly(H * k + o, colour, hp)+ la = float(np.clip((t - 0.5) / 0.3, 0, 1))+ if label and la > 0:+ x0, y0 = self._S(lab_box[0], lab_box[1]); x1, y1 = self._S(lab_box[2], lab_box[3])+ self._s_rrect(x0, y0, x1, y1, 8 * k, BOARD, la)+ mx, my = self._S((lab_box[0] + lab_box[2]) / 2, (lab_box[1] + lab_box[3]) / 2)+ self._s_text(label, mx, my, label_size * k, MUTED, 'medium', 'mm', la)+ bb = (P[:, 0].min() - 24, P[:, 1].min() - 24, P[:, 0].max() + 24, P[:, 1].max() + 24)+ if lab_box: bb = _union(bb, lab_box)+ self._rec(fn, bb, 'p')+ self.end()+ return P++ # ------------------------------------------------------------ hand-drawn strokes (sketch cards)+ def _rough_seg(self, p0, p1, rng, rough):+ p0, p1 = np.asarray(p0, np.float64), np.asarray(p1, np.float64)+ d = p1 - p0; L = float(np.hypot(*d)) + 1e-6; u = d / L; nrm = np.array([-u[1], u[0]])+ o = rough * min(2.4, 0.5 + L * 0.008)+ a = p0 - u * rng.uniform(-0.5, 3.0) * rough + nrm * rng.normal(0, o * 0.45)+ b = p1 + u * rng.uniform(-0.5, 3.0) * rough + nrm * rng.normal(0, o * 0.45)+ bow = nrm * rng.normal(0, rough * min(L * 0.01, 3.2))+ c0 = a + (b - a) * rng.uniform(0.25, 0.4) + bow + rng.normal(0, o * 0.35, 2)+ c1 = a + (b - a) * rng.uniform(0.6, 0.75) + bow + rng.normal(0, o * 0.35, 2)+ return bezier(a, c0, c1, b, max(6, int(L / 10)))++ def rough(self, pts, width=3.0, fill=TEXT, closed=False, rough=1.0, passes=2, seed=None, var=None, alpha=1.0,+ dash=None, second=0.55):+ """a hand-drawn polyline (sketch look): every segment is a slightly bowed, overshooting stroke drawn `passes`+ times with fresh jitter (the second pass at `second` x opacity). Draws on with var (mode 'draw')"""+ rng = np.random.default_rng(self.seed * 7919 + (seed if seed is not None else int(self.rng.integers(1 << 30))))+ P = [tuple(p) for p in pts] + ([tuple(pts[0])] if closed else [])+ for k in range(passes):+ segs = [self._rough_seg(a, b, rng, rough) for a, b in zip(P[:-1], P[1:])]+ Q = np.vstack(segs)+ self.line(Q, width * (1 if k == 0 else 0.8), fill, alpha * (1 if k == 0 else second), var=var, dash=dash)++ def rough_rect(self, x0, y0, x1, y1, **kw):+ self.rough([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], closed=True, **kw)++ def rough_ellipse(self, cx, cy, rx, ry, width=3.0, fill=TEXT, rough=1.0, passes=2, seed=None, var=None, alpha=1.0,+ a0=None, sweep=None, second=0.55, dash=None):+ """a hand-drawn ellipse (or arc: a0 degrees, sweep degrees), closing with a little overlap like a pen"""+ rng = np.random.default_rng(self.seed * 7907 + (seed if seed is not None else int(self.rng.integers(1 << 30))))+ for k in range(passes):+ s0 = np.deg2rad(rng.uniform(0, 360) if a0 is None else a0 + rng.normal(0, 2))+ sw = np.deg2rad(sweep if sweep is not None else 372 + rng.uniform(0, 14))+ n = max(24, int(abs(sw) * max(rx, ry) / 6))+ t = s0 + np.linspace(0, sw, n)+ wob = 1 + rough * 0.025 * np.sin(t * rng.uniform(1.5, 2.5) + rng.uniform(0, 6)) + rough * rng.normal(0, 0.004, n)+ P = np.stack([cx + rx * wob * np.cos(t), cy + ry * wob * np.sin(t)], 1)+ self.line(P, width * (1 if k == 0 else 0.8), fill, alpha * (1 if k == 0 else second), var=var, dash=dash)++ def arrow_head(self, tip, direction, size=14, fill=TEXT, var=None, mode='fade'):+ """a filled arrowhead at board point `tip` pointing along `direction` (degrees, 0 = right, 90 = down)"""+ a = np.deg2rad(direction)+ R = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])+ P = (np.array([(1.5, 0), (-size, -size * 0.55), (-size * 0.75, 0), (-size, size * 0.55)]) @ R.T) + np.asarray(tip)+ self.poly(P, fill, var=var, mode=mode)++ # ------------------------------------------------------------ the window (screen space, drawn once)+ def _screen_target(self, rgb):+ self._tg = _Target(rgb)+ self._k, self._ox, self._oy = 1.0, 0.0, 0.0+ self._clip_s = None++ def _build_chrome(self):+ out = np.ones((self.H, self.W, 3), np.float32) * hexc(PAGE)+ self._screen_target(out)+ if self.glow: # a faint violet pool of light on the page, top left+ g = self._grid(0, 0, self.W, self.H)+ sl, X, Y = g+ t = np.hypot((X - 400) / 700, (Y + 150) / 650)+ self._over(sl, 0.2 * np.clip(1 - t, 0, 1), ACCENT)+ W_ = self.win+ x, y, x1, y1 = W_.x0, W_.y0, W_.x1, W_.y1+ self._s_shadow(x, y, x1, y1, 14, 0, 40, 90, -30, '#000000', 0.8)+ self._s_rrect(x, y, x1, y1, 14, '#3a3a3a', 1.0, 1.0, inset=False)+ self._s_rrect(x, y, x1, y1, 14, BG)+ self._clip_s = (x, y, x1, y1, 14)+ bh = self.bar_h+ self._s_rrect(x, y, x1, y + bh, 0, SIDE)+ self._s_rrect(x, y + bh - 1, x1, y + bh, 0, BORDER)+ if self.ribbon:+ rw = self.rib_w+ self._s_rrect(x, y + bh, x + rw, y1, 0, SIDE)+ self._s_rrect(x + rw - 1, y + bh, x + rw, y1, 0, BORDER)+ for i, gname in enumerate(RIBBON):+ self._s_glyph(gname, x + rw / 2, y + bh + 20 + 12 + i * 44, 24, FAINT, 1.8)+ for i, c in enumerate(LIGHTS):+ self._s_circle(x + 18 + 6.5 + i * 22, y + bh / 2, 6.5, c)+ if self.tab:+ tx = x + 18 + 57 + 22 + 30+ tw = self._glyphs(self.tab, 20, 'medium', 0, 'sans')[1]+ xw = self._glyphs('×', 18, 'medium', 0, 'sans')[1]+ tx1 = tx + 22 + tw + 12 + xw + 22+ ty0 = y + bh - 40+ self._s_rrect(tx, ty0, tx1, y + bh + 12, 10, BORDER)+ self._s_rrect(tx + 1, ty0 + 1, tx1 - 1, y + bh + 12, 9, BG)+ self._s_rrect(tx + 1, y + bh - 1, tx1 - 1, y + bh + 12, 0, BG)+ self._s_text(self.tab, tx + 22, ty0 + 20, 20, TEXT, 'medium', 'lm')+ self._s_text('×', tx + 22 + tw + 12, ty0 + 20, 18, FAINT, 'medium', 'lm')+ self._clip_s = None+ m = np.zeros((self.VH, self.VW), np.float32)+ p = self.pane+ X = np.arange(self.VW, dtype=np.float32)[None, :] + 0.5 + p.x0+ Y = np.arange(self.VH, dtype=np.float32)[:, None] + 0.5 + p.y0+ m[:] = _cov(sdf_rrect(X - (x + x1) / 2, Y - (y + y1) / 2, (x1 - x) / 2, (y1 - y) / 2, 14))+ self._pane_mask = m[..., None]+ self._chrome = out++ def _draw_controls(self, out):+ self._screen_target(out)+ x0 = self.pane.x1 - 18 - 50+ y0 = self.pane.y0 + 18+ h = 8 + 4 * 26 + 3 * 14 + 8+ self._s_shadow(x0, y0, x0 + 50, y0 + h, 10, 0, 10, 24, -12, '#000000', 0.8)+ self._s_rrect(x0, y0, x0 + 50, y0 + h, 10, BG2)+ self._s_rrect(x0, y0, x0 + 50, y0 + h, 10, BORDER, 1.0, 1.0)+ for i, gname in enumerate(CONTROLS):+ cx, cy = x0 + 25, y0 + 8 + 13 + i * 40+ if self.hover == i:+ self._s_rrect(cx - 19, cy - 17, cx + 19, cy + 17, 7, BG3)+ self._s_glyph(gname, cx, cy, 26, BRIGHT if self.hover == i else MUTED, 1.9)++ def _draw_cursor(self, out):+ x, y, click, alpha, press = self._cursor+ self._screen_target(out)+ if click is not None and 0 < click < 1:+ self._s_circle(x, y, 26 * (0.4 + click), ACCENT2, alpha * (1 - click), ring=3.0)+ s = 0.88 if press else 1.0+ P = (np.array(POINTER, np.float32) - 2) * s + np.array([x, y])+ sh = P + np.array([0, 4])+ g = self._grid(sh[:, 0].min() - 10, sh[:, 1].min() - 10, sh[:, 0].max() + 10, sh[:, 1].max() + 10)+ if g:+ sl, X, Y = g+ im = Image.new('L', (sl[1].stop - sl[1].start, sl[0].stop - sl[0].start), 0)+ ImageDraw.Draw(im).polygon([(px - sl[1].start, py - sl[0].start) for px, py in sh.tolist()], fill=255)+ m = blur(np.asarray(im, np.float32) / 255, 3)+ self._over(sl, m * 0.45 * alpha, '#000000')+ self._s_poly(P, '#111111', alpha)+ c = P.mean(0)+ self._s_poly(c + (P - c) * 0.86 + np.array([0.0, -0.2]), WHITE, alpha)++ # ------------------------------------------------------------ compositing+ def _board(self):+ """the pane: board colour and the dot grid for the current camera"""+ cx, cy, z = self.cam+ P = np.empty((self.VH, self.VW, 3), np.float32)+ P[:] = hexc(BOARD)+ g = self.grid+ X = (np.arange(self.VW, dtype=np.float32) + 0.5 - self.VW / 2) / z + cx+ Y = (np.arange(self.VH, dtype=np.float32) + 0.5 - self.VH / 2) / z + cy+ dx = ((X + g / 2) % g - g / 2) * z+ dy = ((Y + g / 2) % g - g / 2) * z+ r = max(self.dot_r * z, 1.05)+ d = np.sqrt(dx[None, :] ** 2 + dy[:, None] ** 2)+ cov = np.clip(r + 0.5 - d, 0, 1) * min(1.0, 0.55 + 0.45 * z)+ P += (hexc(DOT) - hexc(BOARD)) * cov[..., None]+ return P++ def _xf(self, N):+ p = N.pose+ s = p['scale']+ if p['origin'] is not None: ox, oy = p['origin']+ elif N.rect is not None: ox, oy = N.rect.cx, N.rect.cy+ elif N.box is not None: ox, oy = (N.box[0] + N.box[2]) / 2, (N.box[1] + N.box[3]) / 2+ else: ox = oy = 0.0+ cx, cy, z = self.cam+ return s * z, self.VW / 2 + (ox * (1 - s) + p['dx'] - cx) * z, self.VH / 2 + (oy * (1 - s) + p['dy'] - cy) * z++ def _draw_node(self, N):+ for pr in N.prims:+ if pr.var is None: t = 1.0+ else:+ v = N.var(pr.var[0]); t = float(np.clip((v - pr.var[1]) / max(pr.var[2] - pr.var[1], 1e-6), 0, 1))+ if pr.clip is not None:+ x0, y0 = self._S(pr.clip[0], pr.clip[1]); x1, y1 = self._S(pr.clip[2], pr.clip[3])+ self._clip_s = (x0, y0, x1, y1, pr.clip[4] * self._k)+ else:+ self._clip_s = None+ pr.fn(t)+ self._clip_s = None++ def render(self):+ """composite the page, the window and the board under the current camera and poses -> float RGB"""+ if self._chrome is None: self._build_chrome()+ out = self._chrome.copy()+ P = self._board()+ for N in sorted(self.nodes.values(), key=lambda q: (q.z, q.order)):+ al = N.pose['alpha']+ if al <= 0 or N.box is None: continue+ k, ox, oy = self._xf(N)+ bx0, by0, bx1, by1 = N.box[0] * k + ox, N.box[1] * k + oy, N.box[2] * k + ox, N.box[3] * k + oy+ if bx1 < 0 or by1 < 0 or bx0 > self.VW or by0 > self.VH: continue+ self._drawing = N+ if al >= 0.999:+ self._tg = _Target(P)+ self._k, self._ox, self._oy = k, ox, oy+ self._draw_node(N)+ else:+ X0, Y0 = max(0, int(np.floor(bx0))), max(0, int(np.floor(by0)))+ X1, Y1 = min(self.VW, int(np.ceil(bx1)) + 1), min(self.VH, int(np.ceil(by1)) + 1)+ if X1 <= X0 or Y1 <= Y0: continue+ L = _Target(np.zeros((Y1 - Y0, X1 - X0, 3), np.float32), np.zeros((Y1 - Y0, X1 - X0), np.float32), X0, Y0)+ self._tg = L+ self._k, self._ox, self._oy = k, ox - X0, oy - Y0+ self._draw_node(N)+ P[Y0:Y1, X0:X1] = P[Y0:Y1, X0:X1] * (1 - L.a[..., None] * al) + L.rgb * al+ p = self.pane+ sl = (slice(int(p.y0), int(p.y0) + self.VH), slice(int(p.x0), int(p.x0) + self.VW))+ out[sl] = out[sl] * (1 - self._pane_mask) + P * self._pane_mask+ if self.controls: self._draw_controls(out)+ if self._cursor: self._draw_cursor(out)+ self._tg = None+ return out++ def composite(self):+ I = self.render() + self._grain[..., None]+ return Image.fromarray((np.clip(I, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ """snapshot the current camera and poses (written to stages_dir at once if given, else kept PNG-compressed)"""+ if not self.keep_stages: return+ img = self.composite()+ if self.stages_dir:+ img.save(f'{self.stages_dir}/{self._nstage:03d}_{name}.png', compress_level=1)+ else:+ buf = io.BytesIO(); img.save(buf, 'PNG', compress_level=1)+ self.stages.append((name, buf.getvalue()))+ self._nstage += 1++ def tween(self, tag, n=5, ease='out', moves=(), cam=None, last=True, between=None, cam_ease='io'):+ """n stages of a motion: 'mv_<tag>1' .. 'mv_<tag>{n-1}' (in-betweens) and '<tag>' (unless last=False).+ moves: [(names, frm, to)]; frm / to are dicts of pose keys (dx dy scale alpha) and vars; to=None = at rest+ and finished. ease: a name in EASE (linear out io back drop) or a function. cam: (from, to) cameras (x, y, z),+ zoom interpolated geometrically, eased with cam_ease. between(u) is called with the eased progress before+ each stage"""+ E = EASE[ease] if isinstance(ease, str) else ease+ CE = EASE[cam_ease] if isinstance(cam_ease, str) else cam_ease+ REST = dict(dx=0.0, dy=0.0, scale=1.0, alpha=1.0)+ for i in range(1, n + 1):+ u = E(i / n)+ for names, frm, to in moves:+ names = [names] if isinstance(names, str) else names+ to = to or {}+ for nm in names:+ N = self.nodes[nm]+ pose = dict(N.pose)+ for key in REST:+ if key in frm or key in to:+ a = frm.get(key, REST[key]); b = to.get(key, REST[key])+ pose[key] = a + (b - a) * u+ pose['alpha'] = float(np.clip(pose['alpha'], 0, 1))+ N.pose = pose+ for key in set(frm) | set(to):+ if key in REST: continue+ a = frm.get(key, N.defaults.get(key, 1.0)); b = to.get(key, N.defaults.get(key, 1.0))+ N.vars[key] = a + (b - a) * u+ if cam:+ (x0, y0, z0), (x1, y1, z1) = cam+ c = CE(i / n)+ self.camera(x0 + (x1 - x0) * c, y0 + (y1 - y0) * c, z0 * (z1 / z0) ** c)+ if between: between(u)+ if i < n: self.stage(f'mv_{tag}{i}')+ elif last: self.stage(tag)++ def save(self, path, stages_dir=None, quality=88):+ img = self.composite()+ if str(path).lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir and not self.stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, png) in enumerate(self.stages):+ with open(f'{stages_dir}/{i:03d}_{name}.png', 'wb') as fh:+ fh.write(png)+ img.save(f'{stages_dir}/{len(self.stages):03d}_final.png')+ elif self.stages_dir:+ img.save(f'{self.stages_dir}/{self._nstage:03d}_final.png')+ return imgdiff --git a/lib/flexoki.py b/lib/flexoki.pynew file mode 100644index 0000000..5a15c35--- /dev/null+++ b/lib/flexoki.py@@ -0,0 +1,1076 @@+"""flexoki — Flexoki 纸面 / Flexoki Paper: explainer sheets on warm paper, with diagrams drawn the way a lightweight+diagram renderer draws them (numpy + Pillow only).++The look of a documentation site themed with the Flexoki palette (an "inky" scheme for prose and code): warm paper+#FFFCF0, ink-black type, a ladder of warm greys for surfaces, borders and muted text, and eight accents in two shades+(600 for text, 400 for fills). On the paper sit light-grey rounded panels (#F2F0E5, radius 28, no border, no shadow)+with a heavy CJK title, a grey English tag and a mono index number. Inside them, diagrams drawn the way a small+Mermaid-compatible renderer draws them: boxes filled one step off their ground with a 2 px grey border (rect r 5,+round r 14, stadium, diamond, cylinder, circle), 2.4 px ink lines ending in small filled triangular heads, plain+semibold sans labels on a patch of ground colour, dashed lifelines and replies, pies with paper-coloured gaps, bar+charts on hairline grids, tables with a tinted header row. Accents only where they mean something; no texture, no+gradients, no shadows (one optional CSS-style shadow for a lifted card).++ shapes signed-distance fields with 1 px analytic anti-aliasing (pixel centres at i + 0.5): rounded rectangles,+ discs, rings, capsules, rhombi, cylinders, pie sectors, polylines; arrowheads and other free polygons are+ rasterised 4x and box-filtered.+ lines a polyline knows its arc length, so a line can be drawn on to any fraction p (the cut end keeps its round+ cap), dashed along its length, and trimmed under its arrowhead. `bezier`, `curve` (tangent-directed+ cubic) and `rounded` (an orthogonal route with filleted corners) make the polylines.+ groups a node (fill, border, label) is composited as one group, so a node popping in at 40 % opacity fades as a+ whole (SVG <g opacity>), and its scale-in (0.85 -> 1) scales the label too.+ type PingFang SC for CJK (the heavy weight is Semibold with a hairline of faux bold -- close to the black+ headings of the film), SF Pro for Latin (variable weight; big numbers tracked tight), SF Mono for index+ numbers and code; elsewhere Hiragino / Noto Sans CJK / Microsoft YaHei and Helvetica / DejaVu. Override+ with $INKPAINT_FONT_FLEXOKI_<CJK|HEAVY|LATIN|MONO>.+ layers as in pastelui: named layers (premultiplied RGBA, cropped when closed) with a depth and a pose (offset,+ scale about an origin, opacity, left-to-right reveal). `layer(name, fresh=True)` empties a layer so it+ can be redrawn at the next progress value -- an edge drawing on, a number rolling, a pie sweeping, a bar+ growing -- which is how the draw-on animation is made. `stage()` composites the current poses.++ import sys; sys.path.insert(0, 'lib')+ from flexoki import FlexokiPaper, ORANGE4, GREEN4, curve+ fx = FlexokiPaper(1920, 1080, seed=1)+ fx.paper()+ fx.layer('head')+ fx.chip(120, 84, '图解')+ fx.heading(120, 170, '一张流程图', 'Flowchart')+ fx.layer('panel')+ box = fx.panel(120, 220, 900, 420, title='从想法到上线', tag='Flowchart', num='01')+ fx.layer('flow')+ a = fx.node(300, 430, 150, 56, 'Idea')+ b = fx.node(560, 430, 150, 100, 'Go?', shape='diamond')+ fx.edge([a.side('r'), b.side('l')], label='yes', label_fill=GREEN4)+ for p in (0.2, 0.6, 1.0): # draw it on, stage by stage+ fx.layer('e', fresh=True); fx.edge([b.side('r'), (820, 430)], p=p); fx.stage(f'e{p}')+ fx.save('out.jpg')+"""+import glob+import io+import os+from contextlib import contextmanager+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, load_font++# ---------------------------------------------------------------- the Flexoki palette+PAPER = '#FFFCF0'+BASE50, BASE100, BASE150, BASE200 = '#F2F0E5', '#E6E4D9', '#DAD8CE', '#CECDC3'+BASE300, BASE500, BASE600 = '#B7B5AC', '#878580', '#6F6E69'+BASE800, BASE900, BASE950, BLACK = '#403E3C', '#282726', '#1C1B1A', '#100F0F'+# roles (the names the site's CSS uses): surface, ui borders, faint / muted text, ink+BG2, UI, UI2, UI3, TX3, TX2, TX1B, INK = BASE50, BASE100, BASE150, BASE200, BASE300, BASE500, BASE600, BLACK+RED, RED4 = '#AF3029', '#D14D41'+ORANGE, ORANGE4 = '#BC5215', '#DA702C'+YELLOW, YELLOW4 = '#AD8301', '#D0A215'+GREEN, GREEN4 = '#66800B', '#879A39'+CYAN, CYAN4 = '#24837B', '#3AA99F'+BLUE, BLUE4 = '#205EA6', '#4385BE'+PURPLE, PURPLE4 = '#5E409D', '#8B7EC8'+MAGENTA, MAGENTA4 = '#A02F6F', '#CE5D97'+ACCENTS = {'red': (RED, RED4), 'orange': (ORANGE, ORANGE4), 'yellow': (YELLOW, YELLOW4), 'green': (GREEN, GREEN4),+ 'cyan': (CYAN, CYAN4), 'blue': (BLUE, BLUE4), 'purple': (PURPLE, PURPLE4), 'magenta': (MAGENTA, MAGENTA4)}+SERIES = [BLUE4, ORANGE4, GREEN4, PURPLE4, CYAN4, RED4, YELLOW4, MAGENTA4] # chart series, in this order+THEMES = { # what a diagram is drawn with, on light paper and on the dark (950) ground+ 'light': dict(bg=PAPER, surface=BG2, border=UI3, line=INK, fg=INK, muted=TX1B, faint=TX3, track=UI, hair=UI2),+ 'dark': dict(bg=BASE950, surface=BASE900, border=BASE800, line=UI2, fg=UI, muted=TX2, faint=BASE600,+ track=BASE800, hair=BASE800),+}+PALETTE = [PAPER, BASE50, BASE100, BASE150, BASE200, BASE300, BASE500, BASE600, BASE800, BASE900, BASE950, BLACK,+ RED, RED4, ORANGE, ORANGE4, YELLOW, YELLOW4, GREEN, GREEN4, CYAN, CYAN4, BLUE, BLUE4, PURPLE, PURPLE4,+ MAGENTA, MAGENTA4]+++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):+ """colour: '#rrggbb', an accent name ('orange' -> the 400 shade, 'orange6' -> the 600 shade) or rgb 0..1"""+ if isinstance(c, str):+ if c in ACCENTS: return hexc(ACCENTS[c][1])+ if c[:-1] in ACCENTS and c[-1] == '6': return hexc(ACCENTS[c[:-1]][0])+ return hexc(c)+ return np.asarray(c, np.float32)+++def mix(a, b, t):+ """a colour between a and b (hex string out)"""+ v = _c(a) * (1 - t) + _c(b) * t+ return '#' + ''.join(f'{int(round(x * 255)):02x}' for x in np.clip(v, 0, 1))+++# ---------------------------------------------------------------- distances (negative inside)+def sdf_rrect(u, v, hw, hh, r):+ r = max(0.0, min(r, hw, hh))+ qx, qy = np.abs(u) - (hw - r), np.abs(v) - (hh - r)+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r+++def sdf_rhombus(u, v, hw, hh):+ """exact distance to a rhombus with half-diagonals hw, hh"""+ px, py = np.abs(u), np.abs(v)+ bb = hw * hw + hh * hh+ h = np.clip(((hw - 2 * px) * hw - (hh - 2 * py) * hh) / bb, -1, 1)+ d = np.hypot(px - 0.5 * hw * (1 - h), py - 0.5 * hh * (1 + h))+ return d * np.sign(px * hh + py * hw - hw * hh)+++def sdf_ellipse(u, v, rx, ry):+ """first-order distance to an ellipse (exact enough for 1 px anti-aliasing)"""+ g = np.hypot(u / rx, v / ry)+ grad = np.hypot(u / (rx * rx), v / (ry * ry)) + 1e-6+ return (g - 1) * g / grad+++def sdf_segment(X, Y, a, b):+ ax, ay = float(a[0]), float(a[1]); bx, by = float(b[0]), float(b[1])+ dx, dy = bx - ax, by - ay+ l2 = dx * dx + dy * dy + 1e-9+ t = np.clip(((X - ax) * dx + (Y - ay) * dy) / l2, 0, 1)+ return np.hypot(X - (ax + t * dx), Y - (ay + t * dy)), t+++def sdf_polyline(X, Y, P):+ """-> (distance, arc length at the nearest point) to the polyline P (n, 2)"""+ shape = np.broadcast(X, Y).shape+ d = np.full(shape, 1e9, np.float32); s = np.zeros(shape, np.float32)+ acc = 0.0+ for a, b in zip(P[:-1], P[1:]):+ L = float(np.hypot(b[0] - a[0], b[1] - a[1]))+ e, t = sdf_segment(X, Y, a, b)+ m = e < d+ d = np.where(m, e, d); s = np.where(m, acc + t * L, s)+ acc += L+ return d, s+++def _cov(d):+ return np.clip(0.5 - d, 0, 1).astype(np.float32)+++def _clip01(x):+ return float(min(1.0, max(0.0, x)))+++# ---------------------------------------------------------------- paths+def bezier(p0, p1, p2, p3, n=40):+ """cubic Bezier p0 -> p3 with control points p1, p2, sampled into n + 1 points"""+ t = np.linspace(0, 1, n + 1)[:, None]+ P = [np.asarray(p, np.float32) for p in (p0, p1, p2, p3)]+ return ((1 - t) ** 3 * P[0] + 3 * (1 - t) ** 2 * t * P[1] + 3 * (1 - t) * t * t * P[2] + t ** 3 * P[3]).astype(np.float32)+++def curve(a, b, da=(1, 0), db=(1, 0), k=None, n=40):+ """the renderer's curved edge: leaves a along direction da, arrives at b along direction db (k: handle length,+ default 0.45 x the distance)"""+ a, b = np.asarray(a, np.float32), np.asarray(b, np.float32)+ k = 0.45 * float(np.hypot(*(b - a))) if k is None else k+ da = np.asarray(da, np.float32) / (np.hypot(*da) + 1e-9); db = np.asarray(db, np.float32) / (np.hypot(*db) + 1e-9)+ return bezier(a, a + da * k, b - db * k, b, n)+++def rounded(pts, r=14.0, n=8):+ """an orthogonal (or any) route through pts with every inner corner filleted by radius r"""+ P = [np.asarray(p, np.float32) for p in pts]+ out = [P[0]]+ for i in range(1, len(P) - 1):+ a, c, b = P[i - 1], P[i], P[i + 1]+ u = (a - c) / (np.hypot(*(a - c)) + 1e-9); w = (b - c) / (np.hypot(*(b - c)) + 1e-9)+ rr = min(r, np.hypot(*(a - c)) / 2, np.hypot(*(b - c)) / 2)+ p0, p1 = c + u * rr, c + w * rr+ out += list(bezier(p0, c + u * rr * 0.45, c + w * rr * 0.45, p1, n))+ out.append(P[-1])+ return np.array(out, np.float32)+++def _length(P):+ return float(np.hypot(*np.diff(P, axis=0).T).sum()) if len(P) > 1 else 0.0+++def _cut(P, L0, L1):+ """the part of polyline P between arc lengths L0 and L1"""+ seg = np.hypot(*np.diff(P, axis=0).T)+ cum = np.concatenate([[0], np.cumsum(seg)])+ L1 = min(L1, cum[-1]); L0 = max(0.0, L0)+ if L1 <= L0: return P[:1]++ def at(L):+ i = int(np.clip(np.searchsorted(cum, L) - 1, 0, len(seg) - 1))+ t = (L - cum[i]) / (seg[i] + 1e-9)+ return P[i] + (P[i + 1] - P[i]) * t++ inner = [P[i] for i in range(len(P)) if L0 < cum[i] < L1]+ return np.array([at(L0)] + inner + [at(L1)], np.float32)+++def _point_at(P, L):+ return _cut(P, 0, L)[-1]+++# ---------------------------------------------------------------- fonts+_AD = '/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/'+_CJK_FACES = [ # (glob, {weight: face index or file-name token}) -- first hit wins: macOS, Linux, Windows+ (_AD + 'PingFang.ttc', {'regular': 3, 'medium': 7, 'semibold': 11, 'bold': 11, 'heavy': 11}),+ ('/System/Library/Fonts/PingFang.ttc', {'regular': 3, 'medium': 7, 'semibold': 11, 'bold': 11, 'heavy': 11}),+ ('/System/Library/Fonts/Hiragino Sans GB.ttc', {'regular': 0, 'medium': 0, 'semibold': 2, 'bold': 2, 'heavy': 2}),+ ('/usr/share/fonts/**/NotoSansCJK*-{W}.tt[cf]', {'regular': 'Regular', 'medium': 'Medium', 'semibold': 'Bold',+ 'bold': 'Bold', 'heavy': 'Black'}),+ ('/usr/share/fonts/**/NotoSansSC-{W}.[ot]tf', {'regular': 'Regular', 'medium': 'Medium', 'semibold': 'Bold',+ 'bold': 'Bold', 'heavy': 'Black'}),+ ('C:/Windows/Fonts/msyh{W}.ttc', {'regular': '', 'medium': '', 'semibold': 'bd', 'bold': 'bd', 'heavy': 'bd'}),+]+_LATIN_W = {'regular': 400, 'medium': 510, 'semibold': 600, 'bold': 700, 'heavy': 800}+_MONO_W = {'regular': 400, 'medium': 500, 'semibold': 600, 'bold': 700, 'heavy': 800}+_FONTS = {}+++def _find(pat):+ fs = sorted(glob.glob(pat, recursive=True))+ return fs[0] if fs else None+++def _truetype(path, size, idx):+ for i in ([idx, 0] if idx else [0]):+ try:+ return ImageFont.truetype(path, size, index=i)+ except OSError:+ continue+ return None+++def _cjk(weight, size):+ """-> (font, faux-bold stroke px)"""+ env = os.environ.get('INKPAINT_FONT_FLEXOKI_HEAVY' if weight == 'heavy' else 'INKPAINT_FONT_FLEXOKI_CJK')+ if env and os.path.exists(env):+ return ImageFont.truetype(env, size), 0+ for pat, faces in _CJK_FACES:+ tok = faces[weight]+ p = _find(pat.replace('{W}', tok)) if isinstance(tok, str) else _find(pat)+ if not p: continue+ f = _truetype(p, size, 2 if (isinstance(tok, str) and p.endswith('.ttc') and 'Noto' in p)+ else (tok if isinstance(tok, int) else 0))+ if f:+ fake = size / 50 if (weight == 'heavy' and 'Black' not in p) else 0+ return f, fake+ return load_font('cjk_sans', size), (size / 40 if weight in ('bold', 'heavy') else 0)+++def _latin(weight, size, mono=False):+ env = os.environ.get('INKPAINT_FONT_FLEXOKI_' + ('MONO' if mono else 'LATIN'))+ if env and os.path.exists(env):+ return ImageFont.truetype(env, size)+ p = '/System/Library/Fonts/SFNSMono.ttf' if mono else '/System/Library/Fonts/SFNS.ttf'+ if os.path.exists(p):+ try:+ f = ImageFont.truetype(p, size)+ if mono:+ w = float(np.clip(_MONO_W[weight], 294, 900)); f.set_variation_by_axes([w, w])+ else:+ f.set_variation_by_axes([100, float(np.clip(size * 0.75, 17, 96)), 400, _LATIN_W[weight]])+ return f+ except (OSError, ValueError):+ pass+ if mono:+ for q, i in [('/System/Library/Fonts/Menlo.ttc', 1 if weight in ('bold', 'heavy') else 0),+ ('/usr/share/fonts/**/DejaVuSansMono*.ttf', 0), ('C:/Windows/Fonts/consola.ttf', 0)]:+ pp = _find(q)+ if pp:+ f = _truetype(pp, size, i)+ if f: return f+ return load_font('typewriter', size)+ if os.path.exists('/System/Library/Fonts/HelveticaNeue.ttc'):+ return ImageFont.truetype('/System/Library/Fonts/HelveticaNeue.ttc', size,+ index={'regular': 0, 'medium': 10, 'semibold': 10, 'bold': 1, 'heavy': 1}[weight])+ return load_font('sans_bold' if weight in ('semibold', 'bold', 'heavy') else 'sans', size)+++def _font(kind, weight, size):+ key = (kind, weight, int(size))+ if key not in _FONTS:+ _FONTS[key] = _cjk(weight, int(size)) if kind == 'cjk' else (_latin(weight, int(size), kind == 'mono'), 0)+ return _FONTS[key]+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++# ---------------------------------------------------------------- data holders+class Box:+ """a rectangle in canvas pixels"""++ def __init__(self, x0, y0, x1, y1, r=0.0):+ self.x0, self.y0, self.x1, self.y1, self.r = x0, y0, x1, y1, r+ self.w, self.h = x1 - x0, y1 - y0+ self.cx, self.cy = (x0 + x1) / 2, (y0 + y1) / 2++ def __iter__(self):+ return iter((self.x0, self.y0, self.x1, self.y1))+++class Node(Box):+ """a diagram node: its box plus where edges attach"""++ def __init__(self, cx, cy, w, h, shape):+ super().__init__(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2, 0)+ self.shape = shape++ def side(self, s, gap=0.0):+ """mid-point of a side ('l' 'r' 't' 'b'; for a diamond its vertices), pushed out by gap px"""+ dx, dy = {'l': (-1, 0), 'r': (1, 0), 't': (0, -1), 'b': (0, 1)}[s]+ return (self.cx + dx * (self.w / 2 + gap), self.cy + dy * (self.h / 2 + gap))++ def toward(self, x, y, gap=0.0):+ """where the ray from the centre toward (x, y) leaves the node (+ gap px)"""+ ux, uy = x - self.cx, y - self.cy+ n = np.hypot(ux, uy) + 1e-9; ux, uy = ux / n, uy / n+ hw, hh = self.w / 2, self.h / 2+ if self.shape == 'diamond':+ t = 1 / (abs(ux) / hw + abs(uy) / hh)+ elif self.shape == 'circle':+ t = hw+ else:+ t = min(hw / abs(ux) if abs(ux) > 1e-6 else 1e9, hh / abs(uy) if abs(uy) > 1e-6 else 1e9)+ return (self.cx + ux * (t + gap), self.cy + uy * (t + gap))+++class Table:+ """geometry of a table: x, y, column widths, header height, row height, number of body rows"""++ def __init__(self, x, y, widths, head_h, row_h, n_rows, r):+ self.x, self.y, self.widths, self.head_h, self.row_h, self.n, self.r = x, y, list(widths), head_h, row_h, n_rows, r+ self.xs = [x + sum(widths[:i]) for i in range(len(widths) + 1)]+ self.box = Box(x, y, self.xs[-1], y + head_h + row_h * n_rows, r)++ def cell(self, i, j):+ """cell box: row i (-1 = the header), column j"""+ y0 = self.y if i < 0 else self.y + self.head_h + i * self.row_h+ return Box(self.xs[j], y0, self.xs[j + 1], y0 + (self.head_h if i < 0 else self.row_h))++ def col(self, j):+ return Box(self.xs[j], self.y, self.xs[j + 1], self.box.y1)+++class Layer:+ def __init__(self, name, z, order, W, H):+ self.name, self.z, self.order = name, z, order+ self.rgb = np.zeros((H, W, 3), np.float32) # premultiplied+ self.a = np.zeros((H, W), np.float32)+ self.x0 = self.y0 = 0+ self.open = True+ self.pose = dict(dx=0.0, dy=0.0, scale=1.0, alpha=1.0, reveal=1.0, origin=None, feather=14.0)+++# ---------------------------------------------------------------- the canvas+class FlexokiPaper:+ THEMES = THEMES++ def __init__(self, W=1920, H=1080, seed=0, keep_stages=True, theme='light'):+ self.W, self.H = W, H+ self.seed = seed+ self.rng = np.random.default_rng(seed)+ self.keep_stages = keep_stages+ self.stages = []+ self.th = dict(THEMES[theme])+ self.base = np.ones((H, W, 3), np.float32) * hexc(self.th['bg'])+ self.ground = self.th['bg'] # what diagrams are drawn on (label patches, pie gaps, node fill)+ self.layers = {}+ self.cur = None+ self._clip = None+ g = np.random.default_rng(seed + 7).random((H, W)).astype(np.float32)+ self._grain = (g - 0.5) * (1.0 / 255) # sub-level dither only++ # ------------------------------------------------------------ layers (as in pastelui)+ def layer(self, name, z=None, fresh=False):+ """start drawing into layer `name` (re-opens it if it exists; fresh=True empties it first, for redrawing+ a progress state). z: depth (default: creation order); lower z is further back"""+ self._close()+ if name in self.layers and not fresh:+ L = self.layers[name]+ full_rgb = np.zeros((self.H, self.W, 3), np.float32); full_a = np.zeros((self.H, self.W), np.float32)+ h, w = L.a.shape+ full_rgb[L.y0:L.y0 + h, L.x0:L.x0 + w] = L.rgb; full_a[L.y0:L.y0 + h, L.x0:L.x0 + w] = L.a+ L.rgb, L.a, L.x0, L.y0, L.open = full_rgb, full_a, 0, 0, True+ if z is not None: L.z = z+ elif name in self.layers:+ L = self.layers[name]+ L.rgb = np.zeros((self.H, self.W, 3), np.float32); L.a = np.zeros((self.H, self.W), np.float32)+ L.x0 = L.y0 = 0; L.open = True+ if z is not None: L.z = z+ else:+ n = len(self.layers)+ L = Layer(name, n if z is None else z, n, self.W, self.H)+ self.layers[name] = L+ self.cur = L+ return name++ def end(self):+ """stop drawing into the current layer (later drawing goes onto the paper)"""+ self._close()++ @staticmethod+ def _view(L):+ if not L.open: return L.rgb, L.a, L.x0, L.y0+ rows = np.nonzero(L.a.max(1) > 0.5 / 255)[0]+ cols = np.nonzero(L.a.max(0) > 0.5 / 255)[0]+ if not len(cols): return L.rgb[:1, :1], L.a[:1, :1] * 0, 0, 0+ y0, y1, x0, x1 = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1+ return L.rgb[y0:y1, x0:x1], L.a[y0:y1, x0:x1], int(x0), int(y0)++ def _close(self):+ L = self.cur+ self.cur = None+ if L is None or not L.open: return+ rgb, a, x0, y0 = self._view(L)+ L.rgb, L.a, L.x0, L.y0, L.open = rgb.copy(), a.copy(), x0, y0, False++ def pose(self, name, dx=0.0, dy=0.0, scale=1.0, alpha=1.0, reveal=1.0, origin=None, feather=14.0):+ """how layer `name` is shown: offset, scale about `origin` (default its centre), opacity, left-to-right+ reveal (0..1, soft edge `feather` px). pose(name) = as drawn"""+ self.layers[name].pose = dict(dx=dx, dy=dy, scale=scale, alpha=alpha, reveal=reveal, origin=origin,+ feather=feather)++ def show(self, *names, alpha=1.0):+ for n in names: self.layers[n].pose['alpha'] = alpha++ def hide(self, *names):+ for n in names: self.layers[n].pose['alpha'] = 0.0++ def bounds(self, name):+ rgb, a, x0, y0 = self._view(self.layers[name])+ return x0, y0, x0 + a.shape[1], y0 + a.shape[0]++ @contextmanager+ def clip(self, x0, y0, x1, y1, r=0.0):+ """everything drawn inside is clipped to this rounded rectangle"""+ old = self._clip+ self._clip = (x0, y0, x1, y1, r)+ try:+ yield+ finally:+ self._clip = old++ # ------------------------------------------------------------ low level+ def _grid(self, x0, y0, x1, y1):+ """clipped pixel box -> (slices, X (1, w), Y (h, 1)) with pixel centres at i + 0.5, or None"""+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1)) + 1), min(self.H, int(np.ceil(y1)) + 1)+ if x1 <= x0 or y1 <= y0: return None+ X = np.arange(x0, x1, dtype=np.float32)[None, :] + 0.5+ Y = np.arange(y0, y1, dtype=np.float32)[:, None] + 0.5+ return (slice(y0, y1), slice(x0, x1)), X, Y++ def _over(self, sl, cov, col):+ """paint colour `col` (rgb or an (h, w, 3) array) with coverage `cov` over the current target"""+ cov = np.clip(cov, 0, 1).astype(np.float32)+ if self._clip is not None:+ cx0, cy0, cx1, cy1, cr = self._clip+ X = np.arange(sl[1].start, sl[1].stop, dtype=np.float32)[None, :] + 0.5+ Y = np.arange(sl[0].start, sl[0].stop, dtype=np.float32)[:, None] + 0.5+ cov = cov * _cov(sdf_rrect(X - (cx0 + cx1) / 2, Y - (cy0 + cy1) / 2, (cx1 - cx0) / 2, (cy1 - cy0) / 2, cr))+ col = col if (isinstance(col, np.ndarray) and col.ndim == 3) else _c(col)+ c3 = cov[..., None]+ if self.cur is None:+ self.base[sl] = self.base[sl] * (1 - c3) + col * c3+ else:+ L = self.cur+ L.rgb[sl] = L.rgb[sl] * (1 - c3) + col * c3+ L.a[sl] = L.a[sl] * (1 - cov) + cov++ def _group(self, sl, paints, alpha=1.0):+ """composite several (coverage, colour) paints into one group first, then lay the group down at `alpha`"""+ h, w = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start+ rgb = np.zeros((h, w, 3), np.float32); a = np.zeros((h, w), np.float32)+ for cov, col in paints:+ if cov is None: continue+ cov = np.broadcast_to(np.clip(cov, 0, 1), (h, w)).astype(np.float32)+ rgb = rgb * (1 - cov[..., None]) + _c(col) * cov[..., None]+ a = a * (1 - cov) + cov+ self._over(sl, a * alpha, rgb / np.maximum(a, 1e-6)[..., None])++ # ------------------------------------------------------------ the page+ def paper(self, colour=None):+ """flat warm paper (#FFFCF0, or the theme's ground)"""+ colour = colour or self.th['bg']+ self.base[:] = _c(colour)+ self.ground = colour++ # ------------------------------------------------------------ shapes+ def rrect(self, x0, y0, x1, y1, r=0.0, fill=None, alpha=1.0, ring=0.0, inset=True):+ """rounded rectangle; ring=w draws only a w px line along the edge (inside if inset, else outside)"""+ fill = fill or self.th['surface']+ g = self._grid(x0 - ring - 2, y0 - ring - 2, x1 + ring + 2, y1 + ring + 2)+ if not g: return None+ sl, X, Y = g+ d = sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, r)+ if ring:+ d = np.abs(d + ring / 2) - ring / 2 if inset else np.abs(d - ring / 2) - ring / 2+ self._over(sl, _cov(d) * alpha, fill)++ def circle(self, cx, cy, r, fill=INK, alpha=1.0, ring=0.0):+ """disc (or with ring=w a circular line w px wide, inside radius r)"""+ g = self._grid(cx - r - 2, cy - r - 2, cx + r + 2, cy + r + 2)+ if not g: return None+ sl, X, Y = g+ d = np.hypot(X - cx, Y - cy) - r+ if ring: d = np.abs(d + ring / 2) - ring / 2+ self._over(sl, _cov(d) * alpha, fill)++ def poly(self, pts, fill=INK, alpha=1.0, ss=4):+ """filled polygon, rasterised ss x and box-filtered"""+ P = np.asarray(pts, np.float32)+ x0, y0 = int(np.floor(P[:, 0].min())) - 1, int(np.floor(P[:, 1].min())) - 1+ x1, y1 = int(np.ceil(P[:, 0].max())) + 2, int(np.ceil(P[:, 1].max())) + 2+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P.tolist()], fill=255)+ m = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ g = self._grid(x0, y0, x1 - 1, y1 - 1)+ if not g: return+ sl = g[0]+ m = m[sl[0].start - y0:sl[0].stop - y0, sl[1].start - x0:sl[1].stop - x0]+ self._over(sl, m * alpha, fill)++ def line(self, pts, width=2.4, fill=None, alpha=1.0, p=1.0, dash=None, phase=0.0, cap='round'):+ """polyline with round caps and joins. p: draw it on to this fraction of its length (the cut end keeps+ its cap); dash=(on, off) px along the length (butt ends). Returns the drawn polyline"""+ fill = fill or self.th['line']+ P = np.asarray(pts, np.float32)+ if p < 1: P = _cut(P, 0, _length(P) * max(0.0, p))+ if p <= 0 or len(P) < 2: return P+ pad = width / 2 + 2+ g = self._grid(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)+ if not g: return P+ sl, X, Y = g+ d, s = sdf_polyline(X, Y, P)+ cov = _cov(d - width / 2)+ if cap == 'butt': # cut square at both ends: half-planes through the end points+ u0 = (P[1] - P[0]) / (np.hypot(*(P[1] - P[0])) + 1e-9)+ un = (P[-1] - P[-2]) / (np.hypot(*(P[-1] - P[-2])) + 1e-9)+ cov = cov * np.clip(0.5 + (X - P[0][0]) * u0[0] + (Y - P[0][1]) * u0[1], 0, 1) \+ * np.clip(0.5 - (X - P[-1][0]) * un[0] - (Y - P[-1][1]) * un[1], 0, 1)+ if dash:+ on, off = dash+ sm = np.mod(s + phase, on + off)+ cov = cov * np.clip(0.5 + np.minimum(sm, on - sm), 0, 1)+ self._over(sl, cov * alpha, fill)+ return P++ def head(self, x, y, deg, fill=None, length=11.0, width=10.4, alpha=1.0):+ """small filled triangular arrowhead, tip at (x, y), pointing along `deg` (0 = right, 90 = down)"""+ fill = fill or self.th['line']+ a = np.deg2rad(deg); c, s = np.cos(a), np.sin(a)+ P = [(0, 0), (-length, -width / 2), (-length, width / 2)]+ self.poly([(x + px * c - py * s, y + px * s + py * c) for px, py in P], fill, alpha)++ def shadow(self, x0, y0, x1, y1, r=0.0, dx=0.0, dy=0.0, blur_px=0.0, spread=0.0, colour=BASE600, alpha=0.2):+ """CSS box-shadow of a rounded rectangle, painted only outside it (for one lifted card, if any)"""+ sig = blur_px / 2+ pad = 3 * sig + abs(spread) + 3+ g = self._grid(min(x0, x0 + dx) - pad, min(y0, y0 + dy) - pad, max(x1, x1 + dx) + pad, max(y1, y1 + dy) + pad)+ if not g: return+ sl, X, Y = g+ sx0, sy0, sx1, sy1 = x0 - spread + dx, y0 - spread + dy, x1 + spread + dx, y1 + spread + dy+ m = _cov(sdf_rrect(X - (sx0 + sx1) / 2, Y - (sy0 + sy1) / 2, (sx1 - sx0) / 2, (sy1 - sy0) / 2, max(0.0, r + spread)))+ own = _cov(sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, r))+ if sig > 0.3: m = blur(m, sig)+ self._over(sl, m * (1 - own) * alpha, colour)++ # ------------------------------------------------------------ text+ def _glyphs(self, s, size, weight, spacing, family):+ out, x = [], 0.0+ 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])+ for piece, k in runs:+ f, fake = _font('cjk' if k else ('mono' if family == 'mono' else 'latin'), weight, size)+ if spacing:+ for ch in piece:+ out.append((f, ch, x, fake)); x += f.getlength(ch) + spacing+ else:+ out.append((f, piece, x, fake)); x += f.getlength(piece)+ return out, (x - spacing if (spacing and s) else x)++ def measure(self, s, size, weight='regular', spacing=0.0, family='sans'):+ """advance width of a string in px"""+ return self._glyphs(s, int(round(size)), weight, spacing, family)[1]++ def _text_mask(self, s, x, y, size, weight='regular', anchor='ls', spacing=0.0, family='sans'):+ """-> (coverage mask, left, top, width) of a string; anchor [l m r] + [s baseline, m middle of the CJK+ body, t top of the CJK body]"""+ size = int(round(size))+ gl, tw = self._glyphs(s, size, weight, spacing, family)+ x0 = x - tw * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ base = y + {'s': 0.0, 'm': 0.36 * size, 't': 0.86 * size}[anchor[1]]+ bx0, by0 = int(np.floor(x0)) - 6, int(np.floor(base - size * 1.25))+ bw, bh = int(tw) + 14, int(size * 1.65) + 8+ im = Image.new('L', (bw, bh), 0)+ dr = ImageDraw.Draw(im)+ for f, piece, off, fake in gl:+ try:+ dr.text((x0 - bx0 + off, base - by0), piece, font=f, fill=255, anchor='ls', stroke_width=fake,+ stroke_fill=255)+ except (TypeError, ValueError):+ dr.text((x0 - bx0 + off, base - by0), piece, font=f, fill=255, anchor='ls',+ stroke_width=int(round(fake)), stroke_fill=255)+ return np.asarray(im, np.float32) / 255, bx0, by0, tw++ def text(self, s, x, y, size, fill=None, weight='regular', anchor='ls', alpha=1.0, spacing=0.0, family='sans'):+ """text (CJK / Latin runs split automatically). weight: regular / medium / semibold / bold / heavy;+ family: sans / mono. anchor: [l m r] + [s baseline, m middle, t top]. Returns the width"""+ fill = fill or self.th['fg']+ m, bx0, by0, tw = self._text_mask(s, x, y, size, weight, anchor, spacing, family)+ g = self._grid(bx0, by0, bx0 + m.shape[1] - 1, by0 + m.shape[0] - 1)+ if not g: return tw+ sl = g[0]+ m = m[sl[0].start - by0:sl[0].stop - by0, sl[1].start - bx0:sl[1].stop - bx0]+ self._over(sl, m * alpha, fill)+ return tw++ @staticmethod+ def _paste(mask, bx0, by0, sl):+ """a text mask placed into the grid `sl` (cropped / padded)"""+ h, w = sl[0].stop - sl[0].start, sl[1].stop - sl[1].start+ out = np.zeros((h, w), np.float32)+ ys, xs = by0 - sl[0].start, bx0 - sl[1].start+ y0, x0 = max(0, ys), max(0, xs)+ y1, x1 = min(h, ys + mask.shape[0]), min(w, xs + mask.shape[1])+ if y1 > y0 and x1 > x0:+ out[y0:y1, x0:x1] = mask[y0 - ys:y1 - ys, x0 - xs:x1 - xs]+ return out++ # ------------------------------------------------------------ page parts+ def heading(self, x, base, zh, en=None, size=62, en_size=None, fill=None, en_fill=TX2, gap=None, alpha=1.0):+ """a heavy CJK heading with a grey English tag on the same baseline. Returns the right edge"""+ w = self.text(zh, x, base, size, fill, 'heavy', alpha=alpha)+ if en:+ es = en_size or round(size * 0.5)+ w += (gap if gap is not None else size * 0.36)+ w += self.text(en, x + w, base, es, en_fill, 'semibold', alpha=alpha)+ return x + w++ def number(self, x, base, s, size=104, fill=None, anchor='ls', track=-0.03, alpha=1.0, weight='heavy'):+ """a big number (Latin heavy, tracked tight): a counter, a timer, a measurement. Returns the width"""+ return self.text(s, x, base, size, fill, weight, anchor, alpha, spacing=track * size)++ def chip(self, x, cy, text, fg=None, bg=None, size=24, anchor='l', weight='bold', glyph=None, alpha=1.0):+ """capsule label: ink with paper text by default (a section tag), or any fg / bg. glyph 'check' / 'dot'+ puts a mark in front. Returns its Box"""+ fg = fg or self.th['bg']; bg = bg or self.th['fg']+ tw = self.measure(text, size, weight)+ gw = size * 0.95 if glyph else 0+ px, py = size * 0.6, size * 0.28+ h = size * 1.36 + 2 * py+ w = tw + gw + 2 * px+ x0 = x - w * {'l': 0, 'm': 0.5, 'r': 1}[anchor]+ self.rrect(x0, cy - h / 2, x0 + w, cy + h / 2, h / 2, bg, alpha)+ tx = x0 + px+ if glyph == 'dot':+ self.circle(tx + size * 0.28, cy, size * 0.22, fg, alpha)+ elif glyph == 'check':+ self.circle(tx + size * 0.34, cy, size * 0.36, fg, alpha, ring=size * 0.08)+ self.line([(tx + size * 0.17, cy + size * 0.01), (tx + size * 0.3, cy + size * 0.14),+ (tx + size * 0.52, cy - size * 0.12)], size * 0.1, fg, alpha)+ self.text(text, tx + gw, cy, size, fg, weight, 'lm', alpha)+ return Box(x0, cy - h / 2, x0 + w, cy + h / 2, h / 2)++ def step(self, x, cy, label, lit=1.0, size=26, accent=ORANGE4, mute=False):+ """a step chip: dim (ui ground, faint text, empty circle) -> lit (accent ground, paper text, a check drawn+ on as lit goes 0 -> 1). mute=True: the neutral variant (ui2 ground, a minus). Returns the right edge"""+ on = _clip01(lit)+ bg = (UI2 if mute else accent) if on > 0.5 else UI+ fg = (INK if mute else PAPER) if on > 0.5 else TX3+ tw = self.measure(label, size, 'bold')+ h = size * 1.36 + size * 0.52+ cs = size * 0.9+ w = size * 0.42 + cs + 10 + tw + size * 0.62+ self.rrect(x, cy - h / 2, x + w, cy + h / 2, h / 2, bg)+ ccx = x + size * 0.42 + cs / 2+ self.circle(ccx, cy, cs * 10.5 / 24 + cs * 1.1 / 24, fg, ring=cs * 2.2 / 24)+ k = cs / 24+ if mute:+ self.line([(ccx - 4.5 * k, cy), (ccx + 4.5 * k, cy)], 2.6 * k, fg, on)+ elif on > 0:+ self.line([(ccx - 5 * k, cy + 0.4 * k), (ccx - 1.4 * k, cy + 4 * k), (ccx + 5.4 * k, cy - 3.4 * k)],+ 2.6 * k, fg, p=on)+ self.text(label, ccx + cs / 2 + 10, cy, size, fg, 'bold', 'lm')+ return x + w++ def panel(self, x, y, w, h, r=28, tone='surface', title=None, tag=None, num=None, title_size=34, pad=32,+ alpha=1.0):+ """a rounded panel: tone 'surface' (#F2F0E5, no border), 'paper' (paper with a 2 px ui2 border) or 'dark'+ (950). Optional header: heavy CJK title, grey English tag, mono index number at the top right.+ Sets the ground for what is drawn next. Returns a Box with .inner (the content area under the header)"""+ fill = {'surface': BG2, 'paper': PAPER, 'dark': BASE950}[tone]+ if tone == 'paper':+ self.rrect(x, y, x + w, y + h, r, UI2, alpha)+ self.rrect(x + 2, y + 2, x + w - 2, y + h - 2, r - 2, fill, alpha)+ else:+ self.rrect(x, y, x + w, y + h, r, fill, alpha)+ self.ground = fill+ fg = UI if tone == 'dark' else INK+ top = y+ if title:+ base = y + pad + title_size * 0.86+ tx = self.text(title, x + pad, base, title_size, fg, 'heavy', alpha=alpha)+ if tag:+ self.text(tag, x + pad + tx + title_size * 0.4, base, round(title_size * 0.68), TX2, 'semibold',+ alpha=alpha)+ if num:+ self.text(num, x + w - pad + 2, base - 2, round(title_size * 0.66), TX3, 'regular', 'rs', alpha,+ family='mono')+ top = base + title_size * 0.5+ b = Box(x, y, x + w, y + h, r)+ b.inner = Box(x + pad, top, x + w - pad, y + h - pad * 0.8)+ b.fill = fill+ return b++ def focus(self, box, colour=ORANGE4, width=4.0, alpha=1.0, r=None, out=0.0):+ """the focus ring: an inset accent line along a box's rounded edge (out > 0 pushes it outside)"""+ x0, y0, x1, y1 = box+ rr = (box.r if r is None else r) + out+ self.rrect(x0 - out, y0 - out, x1 + out, y1 + out, rr, colour, alpha, ring=width)++ def meter(self, x0, x1, cy, frac, colour=ORANGE4, h=22, track=None, min_w=None):+ """a capsule track (ui) with a filled part (a size, a share, a range on a common scale)"""+ self.rrect(x0, cy - h / 2, x1, cy + h / 2, h / 2, track or self.th['track'])+ if frac > 0:+ self.rrect(x0, cy - h / 2, x0 + max(min_w or h, (x1 - x0) * frac), cy + h / 2, h / 2, colour)++ def window(self, x, y, w, h, r=22, bar=34, fill=None):+ """the screen a diagram is shown in: paper body, 3 px ui3 border, a surface title bar with three grey+ dots. Returns a Box with .body (the area under the bar)"""+ fill = fill or self.th['bg']+ self.rrect(x, y, x + w, y + h, r, UI3)+ self.rrect(x + 3, y + 3, x + w - 3, y + h - 3, r - 3, fill)+ with self.clip(x + 3, y + 3, x + w - 3, y + h - 3, r - 3):+ self.rrect(x, y, x + w, y + 3 + bar, 0, BG2)+ self.rrect(x, y + 3 + bar - 2, x + w, y + 3 + bar, 0, UI2)+ for i in range(3):+ self.circle(x + 3 + 18.5 + i * 20, y + 3 + bar / 2, 5.5, UI3)+ b = Box(x, y, x + w, y + h, r)+ b.body = Box(x + 3, y + 3 + bar, x + w - 3, y + h - 3)+ self.ground = fill+ return b++ def dashed_rect(self, x0, y0, x1, y1, r=16, colour=ORANGE4, width=3.0, dash=(10, 8), alpha=1.0):+ """a dashed rounded rectangle (a container boundary, 'element')"""+ k = min(r, (x1 - x0) / 2, (y1 - y0) / 2)+ pts = rounded([(x0 + k, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0), (x0 + k + 0.01, y0)], k, 10)+ self.line(pts, width, colour, alpha, dash=dash)++ def dimension(self, x0, x1, y, label, colour=ORANGE4, size=28, tick=52, width=3.0):+ """a width dimension: a line between two dashed end ticks, the label on a patch of ground in the middle"""+ self.line([(x0, y), (x1, y)], width, colour, cap='butt')+ for xx in (x0, x1):+ self.line([(xx, y - 14), (xx, y + tick)], width, colour, dash=(8, 6), cap='butt')+ tw = self.measure(label, size, 'heavy')+ self.rrect((x0 + x1) / 2 - tw / 2 - 16, y - size * 0.7, (x0 + x1) / 2 + tw / 2 + 16, y + size * 0.7, 4,+ self.ground)+ self.text(label, (x0 + x1) / 2, y, size, colour, 'heavy', 'mm')++ def code(self, x, base, tokens, size=28, mark=None, mark_colour=ORANGE4):+ """one line of code in SF Mono from (text, colour) tokens; mark = index of a token to sit on a tinted+ highlight. Returns the right edge"""+ cx = x+ for i, (s, col) in enumerate(tokens):+ w = self.measure(s, size, 'regular', family='mono')+ if mark == i:+ self.rrect(cx - 4, base - size * 0.95, cx + w + 4, base + size * 0.32, 5, mark_colour, 0.2)+ self.text(s, cx, base, size, col, 'regular', 'ls', family='mono')+ cx += w+ return cx++ # ------------------------------------------------------------ the renderer: nodes and edges+ def _node_fill(self):+ """a node is filled one step off its ground: surface on paper, paper on a surface panel"""+ return self.th['bg'] if _c(self.ground).tolist() == _c(self.th['surface']).tolist() else self.th['surface']++ def node(self, cx, cy, w, h, label='', shape='rect', size=22, p=1.0, fill=None, stroke=None, sw=2.0, fg=None,+ weight='semibold', lh=None, r=None):+ """a diagram node centred at (cx, cy), w x h its full box (a diamond's diagonals). shape: rect (r 5), round+ (r 14), stadium, diamond, cyl, circle. label: a string ('\\n' for more lines). p: pop-in 0..1 (scale+ 0.85 -> 1 and fade, as one group). Returns a Node (side(), toward() for edges)"""+ n = Node(cx, cy, w, h, shape)+ if p <= 0.001: return n+ th = self.th+ fill = fill or self._node_fill()+ stroke = stroke or th['border']+ fg = fg or th['fg']+ s = 0.85 + 0.15 * _clip01(p)+ al = min(1.0, 1.6 * p)+ W_, H_ = w * s, h * s+ pad = sw + 3+ g = self._grid(cx - W_ / 2 - pad, cy - H_ / 2 - pad, cx + W_ / 2 + pad, cy + H_ / 2 + pad)+ if not g: return n+ sl, X, Y = g+ u, v = X - cx, Y - cy+ rim = None+ if shape == 'diamond':+ d = sdf_rhombus(u, v, W_ / 2, H_ / 2)+ elif shape == 'circle':+ d = np.hypot(u, v) - min(W_, H_) / 2+ elif shape == 'cyl':+ ry = min(H_ * 0.16, 11 * s)+ body = sdf_rrect(u, v, W_ / 2, H_ / 2 - ry, 0)+ top = sdf_ellipse(u, v + H_ / 2 - ry, W_ / 2, ry)+ bot = sdf_ellipse(u, v - H_ / 2 + ry, W_ / 2, ry)+ d = np.minimum(np.minimum(body, top), bot)+ rim = _cov(np.abs(top) - sw * s / 2)+ else:+ rr = {'rect': 5, 'round': 14, 'stadium': H_ / 2}.get(shape, 5) if r is None else r * s+ d = sdf_rrect(u, v, W_ / 2, H_ / 2, rr)+ paints = [(_cov(d), fill), (_cov(np.abs(d) - sw * s / 2), stroke), (rim, stroke)]+ lines = label.split('\n') if label else []+ if lines:+ fs = size * s+ L = (lh or size * 1.28) * s+ y0 = cy - (len(lines) - 1) * L / 2 + (4 * s if shape == 'cyl' else 0)+ for i, t in enumerate(lines):+ m, bx0, by0, _ = self._text_mask(t, cx, y0 + i * L, fs, weight, 'mm')+ paints.append((self._paste(m, bx0, by0, sl), fg))+ self._group(sl, paints, al)+ return n++ def edge(self, pts, p=1.0, head=True, dash=None, width=2.4, colour=None, head_len=11.0, head_w=10.4,+ label=None, label_t=0.5, label_size=19, label_fill=None, label_bg=None, label_weight='semibold'):+ """an edge along the polyline pts (use curve() / rounded() / bezier() for bends), ending in a small+ filled triangular head whose tip is the last point (the line stops under it). p: drawn on to this+ fraction (the head lands at the end). dash=(on, off) for dotted links and replies. label: drawn on a patch+ of ground at label_t along the edge, once the line has passed it. Returns the full polyline"""+ colour = colour or self.th['line']+ P = np.asarray(pts, np.float32)+ L = _length(P)+ if L < 1 or p <= 0: return P+ trim = head_len * 0.7 if head else 0.0+ self.line(_cut(P, 0, min(L * p, L - trim)), width, colour, dash=dash, cap='round' if not dash else 'butt')+ if head and p > 0.94:+ tail = _point_at(P, max(0.0, L - head_len))+ ang = np.degrees(np.arctan2(P[-1][1] - tail[1], P[-1][0] - tail[0]))+ self.head(P[-1][0], P[-1][1], ang, colour, head_len, head_w, alpha=_clip01((p - 0.94) / 0.06))+ if label and p > label_t:+ a = _clip01((p - label_t) / 0.12)+ lx, ly = _point_at(P, L * label_t)+ tw = self.measure(label, label_size, label_weight)+ self.rrect(lx - tw / 2 - 7, ly - label_size * 0.72, lx + tw / 2 + 7, ly + label_size * 0.72, 5,+ label_bg or self.ground, a)+ self.text(label, lx, ly, label_size, label_fill or self.th['fg'], label_weight, 'mm', a)+ return P++ # ------------------------------------------------------------ sequence diagrams+ def lifeline(self, x, y0, y1, p=1.0, colour=None, width=2.0, dash=(6, 6)):+ """a dashed lifeline from y0 down to y1 (drawn on with p)"""+ self.line([(x, y0), (x, y1)], width, colour or self.th['border'], p=p, dash=dash, cap='butt')++ def activation(self, x, y0, y1, w=14, p=1.0):+ """an activation bar on a lifeline (grows down with p)"""+ if p <= 0: return+ y1 = y0 + (y1 - y0) * _clip01(p)+ self.rrect(x - w / 2, y0, x + w / 2, y1, 0, self.th['border'])+ self.rrect(x - w / 2 + 2, y0 + 2, x + w / 2 - 2, y1 - 2, 0, self.th['track'])++ def message(self, x0, x1, y, label=None, p=1.0, reply=False, size=19, label_fill=None, gap=10, width=2.2):+ """a message arrow from lifeline x0 to x1 at height y (a dashed reply if reply), its label centred above"""+ self.edge([(x0, y), (x1, y)], p, dash=(7, 6) if reply else None, width=width)+ if label and p > 0.3:+ self.text(label, (x0 + x1) / 2, y - gap, size, label_fill or self.th['muted'], 'medium', 'ms',+ _clip01((p - 0.3) / 0.4))++ def note(self, x0, y0, x1, y1, text, size=18, fill=None, stroke=None, colour=None, p=1.0):+ """a note box (yellow-tinted surface, grey border) with centred text; p pops it in"""+ if p <= 0: return+ al = min(1.0, 1.6 * p)+ self.rrect(x0, y0, x1, y1, 4, stroke or UI3, al)+ self.rrect(x0 + 2, y0 + 2, x1 - 2, y1 - 2, 3, fill or mix(PAPER, YELLOW4, 0.16), al)+ self.text(text, (x0 + x1) / 2, (y0 + y1) / 2, size, colour or self.th['fg'], 'medium', 'mm', al)++ # ------------------------------------------------------------ charts+ def pie(self, cx, cy, r, values, colours=None, sweep=1.0, gap=3.0, gap_colour=None, labels=None,+ label_size=20, label_fill=PAPER, label_r=0.62):+ """a pie, slices clockwise from twelve o'clock, separated by gap px of ground colour (paper by default).+ sweep 0..1 draws it on clockwise. labels: one string per slice (e.g. percentages), shown once swept"""+ colours = colours or SERIES+ v = np.asarray(values, np.float32); fr = v / v.sum()+ edges = np.concatenate([[0], np.cumsum(fr)]) * 2 * np.pi+ A = 2 * np.pi * _clip01(sweep)+ if A <= 1e-3: return+ g = self._grid(cx - r - 2, cy - r - 2, cx + r + 2, cy + r + 2)+ sl, X, Y = g+ u, v_ = X - cx, Y - cy+ th = np.mod(np.arctan2(u, -v_), 2 * np.pi)+ disc = _cov(np.hypot(u, v_) - r)+ if A < 2 * np.pi - 1e-3: # the swept sector, with anti-aliased straight edges+ def ray(a):+ return sdf_segment(X, Y, (cx, cy), (cx + (r + 3) * np.sin(a), cy - (r + 3) * np.cos(a)))[0]+ inside = th < A+ dr = np.minimum(ray(0.0), ray(A))+ sect = np.where(inside, np.clip(0.5 + dr, 0, 1), np.clip(0.5 - dr, 0, 1))+ disc = disc * sect+ idx = np.clip(np.searchsorted(edges, th, side='right') - 1, 0, len(fr) - 1)+ cols = np.stack([_c(colours[i % len(colours)]) for i in range(len(fr))])+ self._over(sl, disc, cols[idx])+ gc = gap_colour or self.ground+ if gap > 0:+ for a in list(edges[:-1]) + ([A] if A < 2 * np.pi - 1e-3 else []):+ if a > A + 1e-4: continue+ self.line([(cx, cy), (cx + (r + 2) * np.sin(a), cy - (r + 2) * np.cos(a))], gap, gc, cap='butt')+ if labels:+ for i, t in enumerate(labels):+ if not t: continue+ a = (edges[i] + edges[i + 1]) / 2+ al = _clip01((A - edges[i + 1]) / 0.35 + 1)+ if al <= 0: continue+ self.text(t, cx + r * label_r * np.sin(a), cy - r * label_r * np.cos(a), label_size, label_fill,+ 'bold', 'mm', al)++ def legend(self, x, y, items, size=21, pitch=44, swatch=22, value_x=None, alpha=1.0, value_family='sans'):+ """legend rows from (colour, label[, value]) at (x, y = middle of the first row); values right-aligned at+ value_x. alpha: one number or one per row"""+ als = alpha if isinstance(alpha, (list, tuple)) else [alpha] * len(items)+ for i, it in enumerate(items):+ col, lab = it[0], it[1]+ a = als[i]+ if a <= 0: continue+ cy = y + i * pitch+ self.rrect(x, cy - swatch / 2, x + swatch, cy + swatch / 2, 4, col, a)+ self.text(lab, x + swatch + 12, cy, size, self.th['fg'], 'semibold', 'lm', a)+ if len(it) > 2 and value_x is not None:+ self.text(it[2], value_x, cy, size - 1, self.th['muted'], 'regular', 'rm', a, family=value_family)++ def bars(self, x0, y0, x1, y1, values, labels=None, colours=None, vmax=None, ticks=None, tick_fmt=str, p=1.0,+ value_fmt=None, bar_w=0.56, size=20, r=5, value_colours=None):+ """a bar chart in the plot box (x0, y0)-(x1, y1): hairline grid at `ticks` with mono labels left of x0,+ a ui3 baseline, bars (round top, square foot) growing with p (one number or one per bar), the value rolling+ above each bar (value_fmt(v)), category labels under the baseline. Returns the bar Boxes"""+ n = len(values)+ colours = colours or [BLUE4] * n+ ps = p if isinstance(p, (list, tuple)) else [p] * n+ vmax = vmax or max(values) * 1.15+ sy = lambda val: y1 - (y1 - y0) * val / vmax+ for t in (ticks or []):+ yy = sy(t)+ if t > 0: self.line([(x0, yy), (x1, yy)], 2, self.th['track'], cap='butt')+ self.text(tick_fmt(t), x0 - 12, yy, size - 3, self.th['faint'], 'regular', 'rm', family='mono')+ self.line([(x0, y1), (x1, y1)], 2, self.th['border'], cap='butt')+ pitch = (x1 - x0) / n+ boxes = []+ for i, val in enumerate(values):+ cxb = x0 + pitch * (i + 0.5)+ bw = pitch * bar_w+ q = _clip01(ps[i])+ top = sy(val * q)+ boxes.append(Box(cxb - bw / 2, sy(val), cxb + bw / 2, y1))+ if q > 0 and y1 - top > 0.5:+ rr = min(r, (y1 - top) / 2)+ self.rrect(cxb - bw / 2, top, cxb + bw / 2, y1 - 1, rr, colours[i % len(colours)])+ self.rrect(cxb - bw / 2, max(top + rr, y1 - 1 - rr), cxb + bw / 2, y1 - 1, 0, colours[i % len(colours)])+ if value_fmt and q > 0:+ vc = (value_colours or [self.th['fg']] * n)[i]+ self.text(value_fmt(val * q), cxb, top - 12, size, vc, 'semibold', 'ms', min(1.0, 2 * q))+ if labels:+ self.text(labels[i], cxb, y1 + 14 + size * 0.86, size, self.th['muted'], 'medium', 'ms')+ return boxes++ def table(self, x, y, widths, n_rows, row_h=52, head_h=None, header=None, size=21, r=12, fill=None,+ head_fill=None, border=None, line=None, dots=None, head_colour=None, align=None):+ """a renderer table: a rounded frame (1.5 px border) on paper, a tinted header row with bold labels+ (optional accent dots in front), hairlines between rows. Body rows are drawn with table_row(), so they+ can live in their own layers. Returns a Table (cell(i, j), col(j), box)"""+ head_h = head_h or row_h+ t = Table(x, y, widths, head_h, row_h, n_rows, r)+ x1, y1 = t.box.x1, t.box.y1+ self.rrect(x, y, x1, y1, r, border or self.th['border'])+ self.rrect(x + 1.5, y + 1.5, x1 - 1.5, y1 - 1.5, r - 1.5, fill or self.th['bg'])+ with self.clip(x + 1.5, y + 1.5, x1 - 1.5, y1 - 1.5, r - 1.5):+ self.rrect(x, y, x1, y + head_h, 0, head_fill or self.th['track'])+ self.rrect(x, y + head_h - 1.5, x1, y + head_h, 0, border or self.th['border'])+ for i in range(1, n_rows):+ yy = y + head_h + i * row_h+ self.rrect(x + 1.5, yy - 0.75, x1 - 1.5, yy + 0.75, 0, line or self.th['hair'])+ if header:+ for j, s in enumerate(header):+ if not s: continue+ c = t.cell(-1, j)+ a = (align or ['l'] + ['m'] * (len(widths) - 1))[j]+ tx = c.x0 + 18 if a == 'l' else c.cx+ if dots and dots[j]:+ tw = self.measure(s, size, 'bold')+ dx = (tx - tw / 2 - 9) if a == 'm' else tx + 4+ self.circle(dx, c.cy, 5.5, dots[j])+ tx += 7 if a == 'm' else 16+ self.text(s, tx, c.cy, size, head_colour or self.th['fg'], 'bold', a + 'm')+ return t++ def table_row(self, t, i, cells, colours=None, weights=None, size=21, align=None, alpha=1.0):+ """the contents of body row i: first column muted (row names), the rest ink; colours / weights per cell"""+ for j, s in enumerate(cells):+ if not s: continue+ c = t.cell(i, j)+ a = (align or ['l'] + ['m'] * (len(cells) - 1))[j]+ col = (colours[j] if colours and colours[j] else (self.th['muted'] if j == 0 else self.th['fg']))+ wt = (weights[j] if weights and weights[j] else ('semibold' if j == 0 else 'medium'))+ self.text(s, c.x0 + 18 if a == 'l' else c.cx, c.cy, size, col, wt, a + 'm', alpha)++ # ------------------------------------------------------------ compositing+ def _posed(self, L):+ p = L.pose+ rgb, a, lx0, ly0 = self._view(L)+ h, w = a.shape+ x0, y0 = float(lx0), float(ly0)+ s = p['scale']+ if abs(s - 1) > 1e-4:+ ox, oy = p['origin'] or (lx0 + w / 2, ly0 + h / 2)+ nw, nh = max(1, int(round(w * s))), max(1, int(round(h * s)))+ rs = lambda ch: np.asarray(Image.fromarray(np.ascontiguousarray(ch), 'F').resize((nw, nh), Image.BILINEAR), np.float32)+ rgb = np.stack([rs(rgb[..., k]) for k in range(3)], -1)+ a = rs(a)+ x0, y0 = ox + (x0 - ox) * s, oy + (y0 - oy) * s+ w, h = nw, nh+ if p['reveal'] < 1:+ cut = w * p['reveal']+ xs = np.arange(w, dtype=np.float32)+ m = np.clip((cut - xs) / max(p['feather'], 1) + 0.5, 0, 1) if p['reveal'] > 0 else np.zeros(w, np.float32)+ rgb = rgb * m[None, :, None]; a = a * m[None, :]+ return rgb, a, int(round(x0 + p['dx'])), int(round(y0 + p['dy']))++ def render(self):+ """composite the paper and every layer under its current pose -> float RGB"""+ out = self.base.copy()+ for L in sorted(self.layers.values(), key=lambda q: (q.z, q.order)):+ al = L.pose['alpha']+ if al <= 0: continue+ rgb, a, x0, y0 = self._posed(L)+ h, w = a.shape+ X0, Y0 = max(0, x0), max(0, y0)+ X1, Y1 = min(self.W, x0 + w), min(self.H, y0 + h)+ if X1 <= X0 or Y1 <= Y0: continue+ cr = rgb[Y0 - y0:Y1 - y0, X0 - x0:X1 - x0]; ca = a[Y0 - y0:Y1 - y0, X0 - x0:X1 - x0]+ out[Y0:Y1, X0:X1] = out[Y0:Y1, X0:X1] * (1 - ca[..., None] * al) + cr * al+ return out++ def composite(self):+ I = self.render() + self._grain[..., None]+ return Image.fromarray((np.clip(I, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ """snapshot the current poses (kept PNG-compressed in memory)"""+ if self.keep_stages:+ buf = io.BytesIO()+ self.composite().save(buf, 'PNG', compress_level=1)+ self.stages.append((name, buf.getvalue()))++ def save(self, path, stages_dir=None, quality=88):+ self._close()+ img = self.composite()+ if str(path).lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, png) in enumerate(self.stages):+ with open(f'{stages_dir}/{i:03d}_{name}.png', 'wb') as fh:+ fh.write(png)+ img.save(f'{stages_dir}/{len(self.stages):03d}_final.png')+ return imgdiff --git a/lib/obsidianui.py b/lib/obsidianui.pynew file mode 100644index 0000000..7eb21ce--- /dev/null+++ b/lib/obsidianui.py@@ -0,0 +1,1005 @@+"""obsidianui — 笔记应用界面 / Obsidian UI: a dark note-taking app drawn in code (numpy + Pillow only).++The look of a Markdown note app in its default dark theme, as an explainer film shows it: a near-black page with a+soft violet glow, and on it the app window -- a tab bar with the traffic lights, a slim icon ribbon, a file explorer+(folders, indent guides, the open note highlighted), the note pane and a right sidebar. In the note: a big heavy H1+with a short violet bar under it, a properties block with #tags, body text with **bold**, internal links in violet and+`inline code`, a dark ```mermaid code block typed in mono with syntax colours -- which, flipped from 源码 to 阅读, renders+as a flowchart of flat dark boxes, thin grey edges with small arrowheads and one violet node -- and a callout with a+violet edge. In the sidebar, the graph view: grey nodes and links, the notes linked to this one lit violet with a soft+glow. ONE accent (violet), everything else greys. No logos.++ shapes rounded rectangles, discs, rings, capsules and icon strokes are signed-distance fields with 1 px analytic+ anti-aliasing (pixel centres at i + 0.5, so integer coordinates give crisp edges); free polygons (the+ pointer, arrowheads, diamonds) are rasterised 4x and box-filtered.+ shadows CSS box-shadow semantics (offset, blur radius, spread, colour, opacity), painted only outside the+ element; with zero offset it is the violet glow of a lit card. `halo()` is a soft radial glow (graph+ nodes, the H1 bar).+ window `window()` draws the chrome: shadow and 1 px ring, title bar with lights and tabs (the active tab is+ open at the bottom and joins the note), ribbon icons, explorer and sidebar panes with hairline borders.+ It returns a Box with .note / .explorer / .right panes; contents are drawn with explorer(),+ view_header(), toggle(), sidebar_tools(), status_bar().+ type PingFang SC (CJK; Lantinghei SC Heavy for the heavy H1), SF Pro (Latin, variable weight, slight negative+ tracking when large), SF Mono for code; script runs split automatically. Elsewhere Noto Sans CJK /+ Microsoft YaHei and the core fonts. Override with $INKPAINT_FONT_OBSIDIAN_<CJK|HEAVY|LATIN|MONO>.+ `rich()` lays out one line of note text from runs: plain, 'b', 'link', 'code', 'hl', 'faint', 'tag'.+ layers everything is drawn into named layers (premultiplied RGBA, cropped to what was drawn). A layer has a+ depth and a pose -- offset, scale about an origin, opacity, a reveal (left to right, top to bottom, or a+ circle growing from the origin) -- so one drawing can be shown in many states: the window rising, a code+ line being typed, a node popping in, the graph growing out of the current note. `stage()` composites.++ import sys; sys.path.insert(0, 'lib')+ from obsidianui import ObsidianUI+ ob = ObsidianUI(1920, 1080, seed=1)+ ob.page()+ ob.layer('window')+ win = ob.window(120, 96, 1680, 880, tabs=['小王子', '狐狸'], side=300, right=480)+ ob.explorer(win, [('读书笔记', 0, 'open'), ('小王子', 1, 'file'), ('狐狸', 1, 'file')], active=1)+ ob.layer('note')+ ob.h1(win.note.x0 + 56, 300, '小王子')+ ob.rich(win.note.x0 + 56, 380, [('狐狸教他什么叫 ', None), ('驯养', 'code'), ('。', None)])+ ob.save('out.jpg')+"""+import glob+import io+import os+from contextlib import contextmanager+import numpy as np+from PIL import Image, ImageDraw, ImageFont+from core import blur, load_font++# ---------------------------------------------------------------- palette (the app's default dark theme)+PAGE = '#161616' # the film's page behind the window+BG, BG2, BG3, SIDE = '#1e1e1e', '#262626', '#2e2e2e', '#202020'+BORDER, BORDER2, RING = '#363636', '#444444', '#3a3a3a'+TEXT, BRIGHT, MUTED, FAINT = '#dadada', '#f2f2f2', '#a3a3a3', '#6b6b6b'+ACCENT, ACCENT2 = '#8a5cf5', '#a88bfa' # the one accent and its lighter text tone+CODE_BG, CODE_TEXT, INLINE = '#1b1b1b', '#d4d4d4', '#e06c75'+SYNTAX = {'kw': '#c792ea', 'str': '#c3e88d', 'num': '#f78c6c', 'op': '#89ddff', 'cm': '#6b6b6b', 'fence': '#6b6b6b',+ 'text': CODE_TEXT}+NODE_FILL, NODE_EDGE, NODE_LINE = '#2b2b2b', '#505050', '#b9b9b9' # rendered diagram parts+LINK, GNODE = '#4a4a4a', '#8f8f8f' # graph view+LIGHTS = ('#ff5f57', '#febc2e', '#28c840')+WHITE = '#ffffff'+ACCENTS = { # the app lets you pick the accent: (accent, lighter text tone)+ 'violet': (ACCENT, ACCENT2), 'blue': ('#3b82f6', '#7aa7f9'), 'teal': ('#14b8a6', '#5fd4c8'),+ 'amber': ('#e59a16', '#f2bd5e'), 'rose': ('#e5486e', '#f08aa3'),+}++# line icons on a 24-unit grid (stroked): ('p', points, closed) polyline, ('c', cx, cy, r) circle, ('a', cx, cy, r, a0, a1)+# arc (degrees, 0 = +x, 90 = down), ('d', cx, cy, r) filled dot, ('r', x0, y0, x1, y1, radius) rounded rectangle+_EYE = [(3, 12), (5.2, 9.4), (8.2, 7.5), (12, 6.8), (15.8, 7.5), (18.8, 9.4), (21, 12)]+GLYPHS = {+ 'menu': [('p', [(4, 6), (20, 6)]), ('p', [(4, 12), (20, 12)]), ('p', [(4, 18), (20, 18)])],+ 'search': [('c', 11, 11, 6.5), ('p', [(16, 16), (20.5, 20.5)])],+ 'file': [('p', [(6, 3), (14.5, 3), (18.5, 7), (18.5, 21), (6, 21)], True), ('p', [(14.5, 3), (14.5, 7), (18.5, 7)])],+ 'files': [('p', [(8, 3), (15.5, 3), (19, 6.5), (19, 17), (8, 17)], True), ('p', [(5, 7), (5, 21), (15, 21)])],+ 'plus': [('p', [(12, 5), (12, 19)]), ('p', [(5, 12), (19, 12)])],+ 'grid': [('r', 4, 4, 10.5, 10.5, 1.5), ('r', 13.5, 4, 20, 10.5, 1.5), ('r', 4, 13.5, 10.5, 20, 1.5), ('r', 13.5, 13.5, 20, 20, 1.5)],+ 'graph': [('c', 6, 7, 2.6), ('c', 18, 6, 2.6), ('c', 12, 18.5, 2.8), ('p', [(8.6, 6.8), (15.4, 6.2)]),+ ('p', [(7.3, 9.3), (10.6, 16.1)]), ('p', [(16.8, 8.4), (13.4, 16.1)])],+ 'canvas': [('r', 3, 4, 21, 20, 2.5), ('r', 6.5, 7.5, 11.5, 12, 1), ('r', 12.5, 12, 17.5, 16.5, 1), ('p', [(11.5, 9.75), (15, 9.75), (15, 12)])],+ 'calendar': [('r', 4, 5, 20, 20, 2), ('p', [(4, 9.5), (20, 9.5)]), ('p', [(8, 3), (8, 6.5)]), ('p', [(16, 3), (16, 6.5)])],+ 'terminal': [('r', 3, 4, 21, 20, 2.5), ('p', [(7, 9), (10, 12), (7, 15)]), ('p', [(12.5, 15), (17, 15)])],+ 'gear': [('c', 12, 12, 3), ('c', 12, 12, 7)] + [('p', [(12 + 7 * np.cos(a), 12 + 7 * np.sin(a)), (12 + 9.5 * np.cos(a), 12 + 9.5 * np.sin(a))])+ for a in np.arange(8) * np.pi / 4 + np.pi / 8],+ 'help': [('c', 12, 12, 9), ('a', 12, 9.6, 2.6, 180, 395), ('p', [(13.1, 12), (12, 13.6)]), ('d', 12, 16.8, 1.1)],+ 'back': [('p', [(14.5, 5.5), (8, 12), (14.5, 18.5)])],+ 'fwd': [('p', [(9.5, 5.5), (16, 12), (9.5, 18.5)])],+ 'chev_d': [('p', [(7.5, 10), (12, 14.5), (16.5, 10)])],+ 'chev_r': [('p', [(10, 7.5), (14.5, 12), (10, 16.5)])],+ 'edit': [('p', [(4.5, 19.5), (5.2, 15.6), (15.5, 5.3), (18.7, 8.5), (8.4, 18.8)], True), ('p', [(13.4, 7.4), (16.6, 10.6)])],+ 'folder_plus': [('p', [(3, 6), (3, 19), (21, 19), (21, 8.5), (11, 8.5), (9, 6)], True), ('p', [(12, 11.5), (12, 16.5)]), ('p', [(9.5, 14), (14.5, 14)])],+ 'sort': [('p', [(7.5, 4.5), (7.5, 19.5)]), ('p', [(4.5, 16.5), (7.5, 19.5), (10.5, 16.5)]), ('p', [(16.5, 19.5), (16.5, 4.5)]),+ ('p', [(13.5, 7.5), (16.5, 4.5), (19.5, 7.5)])],+ 'collapse': [('p', [(7.5, 4.5), (12, 9), (16.5, 4.5)]), ('p', [(7.5, 19.5), (12, 15), (16.5, 19.5)])],+ 'list': [('p', [(4, 6), (20, 6)]), ('p', [(7.5, 12), (20, 12)]), ('p', [(11, 18), (20, 18)])],+ 'layout': [('r', 4, 4, 20, 20, 2.5), ('p', [(4, 10), (20, 10)])],+ 'bars': [('p', [(6, 19), (6, 10)]), ('p', [(12, 19), (12, 5)]), ('p', [(18, 19), (18, 13)])],+ 'link': [('a', 8.5, 15.5, 4.2, 45, 225), ('a', 15.5, 8.5, 4.2, 225, 405), ('p', [(5.53, 12.53), (11.47, 6.6)]),+ ('p', [(12.53, 17.4), (18.47, 11.47)]), ('p', [(9.5, 14.5), (14.5, 9.5)])],+ 'tag': [('p', [(4, 4), (11, 4), (20, 13), (13, 20), (4, 11)], True), ('d', 8.5, 8.5, 1.2)],+ 'hash': [('p', [(9.5, 4), (7.5, 20)]), ('p', [(16.5, 4), (14.5, 20)]), ('p', [(4.5, 9), (20, 9)]), ('p', [(4, 15), (19.5, 15)])],+ 'book': [('p', [(5, 19.5), (5, 5.5)]), ('a', 6.5, 5.5, 1.5, 180, 270), ('p', [(6.5, 4), (18, 4), (18, 18), (6.5, 18)]),+ ('a', 6.5, 19.5, 1.5, 90, 270), ('p', [(6.5, 21), (18, 21), (18, 18)])],+ 'eye': [('p', _EYE), ('p', [(x, 24 - y) for x, y in _EYE]), ('c', 12, 12, 3)],+ 'quote': [('d', 7.5, 9.5, 2.7), ('p', [(10.1, 10), (9.4, 13.4), (6.6, 16.6)]),+ ('d', 15.5, 9.5, 2.7), ('p', [(18.1, 10), (17.4, 13.4), (14.6, 16.6)])],+ 'more': [('d', 5, 12, 1.3), ('d', 12, 12, 1.3), ('d', 19, 12, 1.3)],+ 'check': [('p', [(5, 12.5), (9.5, 17), (19, 7)])],+ 'x': [('p', [(7, 7), (17, 17)]), ('p', [(17, 7), (7, 17)])],+ 'star': [('p', [(12, 3.5), (14.5, 9), (20.5, 9.5), (16, 13.5), (17.4, 19.6), (12, 16.4), (6.6, 19.6), (8, 13.5), (3.5, 9.5), (9.5, 9)], True)],+}+RIBBON = ['files', 'search', 'graph', 'canvas', 'calendar', 'terminal']+CURSOR = [(1, 1), (1, 25), (7.5, 19.5), (12, 30), (16, 28.3), (11.6, 18), (20, 18)] # pointer, tip at (1, 1)+++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)+++# ---------------------------------------------------------------- signed distances (negative inside)+def sdf_rrect(u, v, hw, hh, r):+ r = min(r, hw, hh)+ qx, qy = np.abs(u) - (hw - r), np.abs(v) - (hh - r)+ return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - r+++def sdf_segment(X, Y, a, b):+ ax, ay = float(a[0]), float(a[1]); bx, by = float(b[0]), float(b[1])+ dx, dy = bx - ax, by - ay+ l2 = dx * dx + dy * dy + 1e-9+ t = np.clip(((X - ax) * dx + (Y - ay) * dy) / l2, 0, 1)+ return np.hypot(X - (ax + t * dx), Y - (ay + t * dy))+++def sdf_polyline(X, Y, pts, closed=False):+ P = [tuple(p) for p in pts]+ if closed: P = P + [P[0]]+ d = np.full(np.broadcast(X, Y).shape, 1e9, np.float32)+ for a, b in zip(P[:-1], P[1:]):+ d = np.minimum(d, sdf_segment(X, Y, a, b))+ return d+++def _cov(d):+ return np.clip(0.5 - d, 0, 1).astype(np.float32)+++def _arc_pts(cx, cy, r, a0, a1):+ n = max(6, int(abs(a1 - a0) / 9))+ t = np.deg2rad(np.linspace(a0, a1, n))+ return np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)+++# ---------------------------------------------------------------- fonts+_AD = '/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/'+_CJK_FACES = [ # (glob, {weight: face index or file-name token}); first hit wins -- macOS, Linux, Windows+ (_AD + 'PingFang.ttc', {'regular': 3, 'medium': 7, 'semibold': 11, 'bold': 11, 'heavy': 11}),+ ('/System/Library/Fonts/PingFang.ttc', {'regular': 3, 'medium': 7, 'semibold': 11, 'bold': 11, 'heavy': 11}),+ ('/System/Library/Fonts/Hiragino Sans GB.ttc', {'regular': 0, 'medium': 0, 'semibold': 2, 'bold': 2, 'heavy': 2}),+ ('/usr/share/fonts/**/NotoSansCJK*-{W}.tt[cf]', {'regular': 'Regular', 'medium': 'Medium', 'semibold': 'Bold', 'bold': 'Bold', 'heavy': 'Black'}),+ ('/usr/share/fonts/**/NotoSansSC-{W}.[ot]tf', {'regular': 'Regular', 'medium': 'Medium', 'semibold': 'Bold', 'bold': 'Bold', 'heavy': 'Black'}),+ ('C:/Windows/Fonts/msyh{W}.ttc', {'regular': '', 'medium': '', 'semibold': 'bd', 'bold': 'bd', 'heavy': 'bd'}),+]+_HEAVY_FACES = [(_AD + 'Lantinghei.ttc', 2), ('/System/Library/Fonts/Lantinghei.ttc', 2)]+_LATIN_W = {'regular': 400, 'medium': 510, 'semibold': 590, 'bold': 680, 'heavy': 790}+_MONO_W = {'regular': 400, 'medium': 500, 'semibold': 600, 'bold': 680, 'heavy': 800}+_FONTS = {}+++def _find(pat):+ fs = sorted(glob.glob(pat, recursive=True))+ return fs[0] if fs else None+++def _truetype(path, size, idx):+ for i in ([idx, 0] if idx else [0]):+ try:+ return ImageFont.truetype(path, size, index=i)+ except OSError:+ continue+ return None+++def _cjk(weight, size):+ """-> (font, faux-bold stroke px)"""+ env = os.environ.get('INKPAINT_FONT_OBSIDIAN_HEAVY' if weight == 'heavy' else 'INKPAINT_FONT_OBSIDIAN_CJK')+ if env and os.path.exists(env):+ return ImageFont.truetype(env, size), 0+ if weight == 'heavy':+ for pat, idx in _HEAVY_FACES:+ p = _find(pat)+ f = p and _truetype(p, size, idx)+ if f: return f, 0+ for pat, faces in _CJK_FACES:+ tok = faces[weight]+ p = _find(pat.replace('{W}', tok)) if isinstance(tok, str) else _find(pat)+ if not p: continue+ f = _truetype(p, size, 2 if (isinstance(tok, str) and p.endswith('.ttc') and 'Noto' in p) else (tok if isinstance(tok, int) else 0))+ if f:+ fake = max(1, round(size / 46)) if weight == 'heavy' and 'Black' not in p else 0+ return f, fake+ return load_font('cjk_sans', size), (max(1, round(size / 40)) if weight in ('semibold', 'bold', 'heavy') else 0)+++def _latin(weight, size, mono=False):+ env = os.environ.get('INKPAINT_FONT_OBSIDIAN_' + ('MONO' if mono else 'LATIN'))+ if env and os.path.exists(env):+ return ImageFont.truetype(env, size)+ p = '/System/Library/Fonts/SFNSMono.ttf' if mono else '/System/Library/Fonts/SFNS.ttf'+ if os.path.exists(p):+ try:+ f = ImageFont.truetype(p, size)+ if mono:+ w = _MONO_W[weight]; f.set_variation_by_axes([w, w])+ else:+ f.set_variation_by_axes([100, float(np.clip(size * 0.75, 17, 96)), 400, _LATIN_W[weight]])+ return f+ except (OSError, ValueError):+ pass+ if mono:+ for q, i in [('/System/Library/Fonts/Menlo.ttc', 1 if weight in ('bold', 'heavy') else 0),+ ('/usr/share/fonts/**/DejaVuSansMono*.ttf', 0), ('C:/Windows/Fonts/consola.ttf', 0)]:+ pp = _find(q)+ if pp:+ f = _truetype(pp, size, i)+ if f: return f+ return load_font('typewriter', size)+ if os.path.exists('/System/Library/Fonts/HelveticaNeue.ttc'):+ return ImageFont.truetype('/System/Library/Fonts/HelveticaNeue.ttc', size,+ index={'regular': 0, 'medium': 10, 'semibold': 10, 'bold': 1, 'heavy': 1}[weight])+ return load_font('sans_bold' if weight in ('semibold', 'bold', 'heavy') else 'sans', size)+++def _font(kind, weight, size):+ key = (kind, weight, int(size))+ if key not in _FONTS:+ _FONTS[key] = _cjk(weight, int(size)) if kind == 'cjk' else (_latin(weight, int(size), kind == 'mono'), 0)+ return _FONTS[key]+++def _is_cjk(ch):+ return ord(ch) >= 0x2e80+++# ---------------------------------------------------------------- data holders+class Box:+ """a rectangle in canvas pixels (window, panes, blocks, nodes)"""++ def __init__(self, x0, y0, x1, y1, r=0.0):+ self.x0, self.y0, self.x1, self.y1, self.r = x0, y0, x1, y1, r+ self.w, self.h = x1 - x0, y1 - y0+ self.cx, self.cy = (x0 + x1) / 2, (y0 + y1) / 2++ def __iter__(self):+ return iter((self.x0, self.y0, self.x1, self.y1))+++class Layer:+ def __init__(self, name, z, order, W, H):+ self.name, self.z, self.order = name, z, order+ self.rgb = np.zeros((H, W, 3), np.float32) # premultiplied+ self.a = np.zeros((H, W), np.float32)+ self.x0 = self.y0 = 0+ self.open = True+ self.pose = dict(dx=0.0, dy=0.0, scale=1.0, alpha=1.0, reveal=1.0, mode='x', origin=None, feather=14.0)+++# ---------------------------------------------------------------- the canvas+class ObsidianUI:+ GLYPHS = GLYPHS+ ACCENTS = ACCENTS++ def __init__(self, W=1920, H=1080, seed=0, keep_stages=True, accent='violet'):+ self.W, self.H = W, H+ self.seed = seed+ self.rng = np.random.default_rng(seed)+ self.keep_stages = keep_stages+ self.stages = []+ self.accent, self.accent2 = ACCENTS[accent] if isinstance(accent, str) else accent+ self.base = np.ones((H, W, 3), np.float32) * hexc(PAGE)+ self.layers = {}+ self.cur = None+ self._clip = None+ g = np.random.default_rng(seed + 7).random((H, W)).astype(np.float32)+ self._grain = (g - 0.5) * (1.4 / 255) # fixed sub-level dither: no banding in the dark glows++ # ------------------------------------------------------------ layers+ def layer(self, name, z=None):+ """start drawing into layer `name` (re-opens it if it exists). z: depth (default: creation order)"""+ self._close()+ if name in self.layers:+ L = self.layers[name]+ full_rgb = np.zeros((self.H, self.W, 3), np.float32); full_a = np.zeros((self.H, self.W), np.float32)+ h, w = L.a.shape+ full_rgb[L.y0:L.y0 + h, L.x0:L.x0 + w] = L.rgb; full_a[L.y0:L.y0 + h, L.x0:L.x0 + w] = L.a+ L.rgb, L.a, L.x0, L.y0, L.open = full_rgb, full_a, 0, 0, True+ if z is not None: L.z = z+ else:+ n = len(self.layers)+ L = Layer(name, n if z is None else z, n, self.W, self.H)+ self.layers[name] = L+ self.cur = L+ return name++ def end(self):+ """stop drawing into the current layer (later drawing goes onto the page)"""+ self._close()++ @staticmethod+ def _view(L):+ if not L.open: return L.rgb, L.a, L.x0, L.y0+ rows = np.nonzero(L.a.max(1) > 0.5 / 255)[0]+ cols = np.nonzero(L.a.max(0) > 0.5 / 255)[0]+ if not len(cols): return L.rgb[:1, :1], L.a[:1, :1] * 0, 0, 0+ y0, y1, x0, x1 = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1+ return L.rgb[y0:y1, x0:x1], L.a[y0:y1, x0:x1], int(x0), int(y0)++ def _close(self):+ L = self.cur+ self.cur = None+ if L is None or not L.open: return+ rgb, a, x0, y0 = self._view(L)+ L.rgb, L.a, L.x0, L.y0, L.open = rgb.copy(), a.copy(), x0, y0, False++ def pose(self, name, dx=0.0, dy=0.0, scale=1.0, alpha=1.0, reveal=1.0, mode='x', origin=None, feather=14.0):+ """how layer `name` is shown: offset, scale about `origin` (default: its centre), opacity and a reveal+ 0..1 with a soft edge `feather` px -- mode 'x' left to right (typing), 'y' top to bottom, 'r' a circle+ growing from `origin` (the graph growing out of a node). pose(name) = drawn as is"""+ self.layers[name].pose = dict(dx=dx, dy=dy, scale=scale, alpha=alpha, reveal=reveal, mode=mode, origin=origin,+ feather=feather)++ def show(self, *names, alpha=1.0):+ for n in names: self.layers[n].pose['alpha'] = alpha++ def hide(self, *names):+ for n in names: self.layers[n].pose['alpha'] = 0.0++ def bounds(self, name):+ rgb, a, x0, y0 = self._view(self.layers[name])+ return x0, y0, x0 + a.shape[1], y0 + a.shape[0]++ @contextmanager+ def clip(self, x0, y0, x1, y1, r=0.0):+ """everything drawn inside is clipped to this rounded rectangle"""+ old = self._clip+ self._clip = (x0, y0, x1, y1, r)+ try:+ yield+ finally:+ self._clip = old++ # ------------------------------------------------------------ low level+ def _grid(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1)) + 1), min(self.H, int(np.ceil(y1)) + 1)+ if x1 <= x0 or y1 <= y0: return None+ X = np.arange(x0, x1, dtype=np.float32)[None, :] + 0.5+ Y = np.arange(y0, y1, dtype=np.float32)[:, None] + 0.5+ return (slice(y0, y1), slice(x0, x1)), X, Y++ def _over(self, sl, cov, col):+ cov = np.clip(cov, 0, 1).astype(np.float32)+ if self._clip is not None:+ cx0, cy0, cx1, cy1, cr = self._clip+ X = np.arange(sl[1].start, sl[1].stop, dtype=np.float32)[None, :] + 0.5+ Y = np.arange(sl[0].start, sl[0].stop, dtype=np.float32)[:, None] + 0.5+ cov = cov * _cov(sdf_rrect(X - (cx0 + cx1) / 2, Y - (cy0 + cy1) / 2, (cx1 - cx0) / 2, (cy1 - cy0) / 2, cr))+ col = col if (isinstance(col, np.ndarray) and col.ndim == 3) else _c(col)+ c3 = cov[..., None]+ if self.cur is None:+ self.base[sl] = self.base[sl] * (1 - c3) + col * c3+ else:+ L = self.cur+ L.rgb[sl] = L.rgb[sl] * (1 - c3) + col * c3+ L.a[sl] = L.a[sl] * (1 - cov) + cov++ # ------------------------------------------------------------ the page+ def page(self, colour=PAGE, glows=((400, 150, 700, 550, 0.20), (1670, 1030, 650, 550, 0.12))):+ """the dark page behind the window, with soft violet glows: (cx, cy, rx, ry, alpha) ellipses fading+ linearly to nothing at their edge (CSS radial-gradient closest-side)"""+ self.base[:] = hexc(colour)+ old, self.cur = self.cur, None+ for cx, cy, rx, ry, al in glows or ():+ g = self._grid(cx - rx, cy - ry, cx + rx, cy + ry)+ if not g: continue+ sl, X, Y = g+ t = np.hypot((X - cx) / rx, (Y - cy) / ry)+ self._over(sl, al * np.clip(1 - t, 0, 1), self.accent)+ self.cur = old++ # ------------------------------------------------------------ shapes+ def rrect(self, x0, y0, x1, y1, r=0.0, fill=BG, alpha=1.0, ring=0.0, inset=True):+ """rounded rectangle; ring=w draws only a w px line along the edge (inside if inset, else outside)"""+ g = self._grid(x0 - ring - 2, y0 - ring - 2, x1 + ring + 2, y1 + ring + 2)+ if not g: return None+ sl, X, Y = g+ d = sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, r)+ if ring:+ d = np.abs(d + ring / 2) - ring / 2 if inset else np.abs(d - ring / 2) - ring / 2+ self._over(sl, _cov(d) * alpha, fill)++ def circle(self, cx, cy, r, fill=GNODE, alpha=1.0, ring=0.0):+ g = self._grid(cx - r - 2, cy - r - 2, cx + r + 2, cy + r + 2)+ if not g: return None+ sl, X, Y = g+ d = np.hypot(X - cx, Y - cy) - r+ if ring: d = np.abs(d + ring / 2) - ring / 2+ self._over(sl, _cov(d) * alpha, fill)++ def line(self, pts, width=2.0, fill=TEXT, alpha=1.0, closed=False):+ """polyline with round caps and joins"""+ P = np.asarray(pts, np.float32)+ pad = width / 2 + 2+ g = self._grid(P[:, 0].min() - pad, P[:, 1].min() - pad, P[:, 0].max() + pad, P[:, 1].max() + pad)+ if not g: return None+ sl, X, Y = g+ self._over(sl, _cov(sdf_polyline(X, Y, P, closed) - width / 2) * alpha, fill)++ def poly(self, pts, fill=TEXT, alpha=1.0, ss=4):+ """filled polygon, rasterised ss x and box-filtered"""+ P = np.asarray(pts, np.float32)+ x0, y0 = int(np.floor(P[:, 0].min())) - 1, int(np.floor(P[:, 1].min())) - 1+ x1, y1 = int(np.ceil(P[:, 0].max())) + 2, int(np.ceil(P[:, 1].max())) + 2+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ ImageDraw.Draw(im).polygon([((x - x0) * ss, (y - y0) * ss) for x, y in P.tolist()], fill=255)+ m = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ g = self._grid(x0, y0, x1 - 1, y1 - 1)+ if not g: return None+ sl = g[0]+ m = m[sl[0].start - y0:sl[0].stop - y0, sl[1].start - x0:sl[1].stop - x0]+ self._over(sl, m * alpha, fill)+ return m++ def shadow(self, x0, y0, x1, y1, r=0.0, dx=0.0, dy=0.0, blur_px=0.0, spread=0.0, colour='#000000', alpha=0.5,+ shape=None):+ """CSS box-shadow of a rounded rectangle, painted only outside the element (zero offset = a glow).+ shape=(cx, cy, r) casts the shadow of a disc instead"""+ sig = blur_px / 2+ pad = 3 * sig + abs(spread) + 3+ if shape is not None:+ cx, cy, rr = shape+ x0, y0, x1, y1 = cx - rr, cy - rr, cx + rr, cy + rr+ g = self._grid(min(x0, x0 + dx) - pad, min(y0, y0 + dy) - pad, max(x1, x1 + dx) + pad, max(y1, y1 + dy) + pad)+ if not g: return+ sl, X, Y = g+ if shape is not None:+ m = _cov(np.hypot(X - cx - dx, Y - cy - dy) - (rr + spread))+ own = _cov(np.hypot(X - cx, Y - cy) - rr)+ else:+ sx0, sy0, sx1, sy1 = x0 - spread + dx, y0 - spread + dy, x1 + spread + dx, y1 + spread + dy+ if sx1 <= sx0 or sy1 <= sy0: return+ m = _cov(sdf_rrect(X - (sx0 + sx1) / 2, Y - (sy0 + sy1) / 2, (sx1 - sx0) / 2, (sy1 - sy0) / 2, max(0.0, r + spread)))+ own = _cov(sdf_rrect(X - (x0 + x1) / 2, Y - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, r))+ if sig > 0.3: m = blur(m, sig)+ self._over(sl, m * (1 - own) * alpha, colour)++ def soft_shadow(self, cov, box, dx=0.0, dy=4.0, blur_px=6.0, colour='#000000', alpha=0.6):+ """drop shadow of any coverage mask `cov` whose top-left pixel is at box[:2] (CSS drop-shadow)"""+ sig = blur_px / 2+ pad = int(3 * sig + 3 + max(abs(dx), abs(dy)))+ h, w = cov.shape+ m = np.zeros((h + 2 * pad, w + 2 * pad), np.float32)+ m[pad:pad + h, pad:pad + w] = cov+ if sig > 0.3: m = blur(m, sig)+ x0, y0 = int(box[0]) - pad + int(round(dx)), int(box[1]) - pad + int(round(dy))+ g = self._grid(x0, y0, x0 + m.shape[1] - 1, y0 + m.shape[0] - 1)+ if not g: return+ sl = g[0]+ self._over(sl, m[sl[0].start - y0:sl[0].stop - y0, sl[1].start - x0:sl[1].stop - x0] * alpha, colour)++ def halo(self, cx, cy, r, colour=None, alpha=0.5, power=2.0):+ """soft radial glow fading to nothing at radius r (lit graph nodes, the glow under a bar)"""+ g = self._grid(cx - r, cy - r, cx + r, cy + r)+ if not g: return+ sl, X, Y = g+ t = np.clip(1 - np.hypot(X - cx, Y - cy) / r, 0, 1)+ self._over(sl, alpha * t ** power, colour or self.accent)++ # ------------------------------------------------------------ text+ def _glyphs(self, s, size, weight, spacing, family):+ out, x = [], 0.0+ 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])+ for piece, k in runs:+ f, fake = _font('cjk' if k else ('mono' if family == 'mono' else 'latin'), weight, size)+ if spacing:+ for ch in piece:+ out.append((f, ch, x, fake)); x += f.getlength(ch) + spacing+ else:+ out.append((f, piece, x, fake)); x += f.getlength(piece)+ return out, (x - spacing if (spacing and s) else x)++ def measure(self, s, size, weight='regular', spacing=0.0, family='sans'):+ """advance width of a string in px"""+ return self._glyphs(s, int(round(size)), weight, spacing, family)[1]++ def text(self, s, x, y, size, fill=TEXT, weight='regular', anchor='ls', alpha=1.0, spacing=0.0, family='sans',+ halo=0, halo_fill=SIDE):+ """text (CJK / Latin runs split automatically). weight: regular / medium / semibold / bold / heavy;+ family: sans / mono. anchor: [l m r] + [s baseline, m middle of the CJK body, t top of the CJK body].+ halo=px first lays a halo_fill outline that px wide (graph labels: links stop short of the words).+ Returns the width"""+ size = int(round(size))+ gl, tw = self._glyphs(s, size, weight, spacing, family)+ x0 = x - tw * {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor[0]]+ base = y + {'s': 0.0, 'm': 0.37 * size, 't': 0.86 * size}[anchor[1]]+ bx0, by0 = int(np.floor(x0)) - 6 - halo, int(np.floor(base - size * 1.25)) - halo+ bw, bh = int(tw) + 14 + 2 * halo, int(size * 1.65) + 8 + 2 * halo+ g = self._grid(bx0, by0, bx0 + bw - 1, by0 + bh - 1)+ if not g: return tw+ sl = g[0]+ for extra, col in ([(halo, halo_fill)] if halo else []) + [(0, fill)]:+ im = Image.new('L', (bw, bh), 0)+ dr = ImageDraw.Draw(im)+ for f, piece, off, fake in gl:+ dr.text((x0 - bx0 + off, base - by0), piece, font=f, fill=255, anchor='ls', stroke_width=fake + extra,+ stroke_fill=255)+ m = np.asarray(im, np.float32) / 255+ m = m[sl[0].start - by0:sl[0].stop - by0, sl[1].start - bx0:sl[1].stop - bx0]+ self._over(sl, m * alpha, col)+ return tw++ def rich(self, x, base, runs, size=26, fill=TEXT, weight='regular', alpha=1.0):+ """one line of note text from runs [(text, style), ...] on baseline `base`; style None (body), 'b' (bold,+ bright), 'link' (internal link, accent text), 'code' (inline code: mono on a rounded dark chip), 'hl'+ (accent highlight behind bright bold words), 'faint', 'accent', 'tag' (#tag pill). Returns the end x"""+ for s, st in runs:+ if st is None:+ x += self.text(s, x, base, size, fill, weight, alpha=alpha)+ elif st == 'b':+ x += self.text(s, x, base, size, BRIGHT, 'semibold', alpha=alpha)+ elif st == 'link':+ x += self.text(s, x, base, size, self.accent2, weight, alpha=alpha)+ elif st == 'faint':+ x += self.text(s, x, base, size, FAINT, weight, alpha=alpha)+ elif st == 'accent':+ x += self.text(s, x, base, size, self.accent2, 'semibold', alpha=alpha)+ elif st == 'code':+ cs = size * 0.86+ tw = self.measure(s, cs, family='mono')+ self.rrect(x + 3, base - size * 0.9, x + 3 + tw + 16, base + size * 0.3, 6, BG3, alpha)+ self.text(s, x + 11, base - size * 0.02, cs, INLINE, family='mono', alpha=alpha)+ x += tw + 22+ elif st == 'hl':+ tw = self.measure(s, size, 'semibold')+ self.rrect(x + 2, base - size * 0.98, x + tw + 18, base + size * 0.3, 8, self.accent, 0.5 * alpha)+ self.text(s, x + 10, base, size, BRIGHT, 'semibold', alpha=alpha)+ x += tw + 20+ elif st == 'tag':+ x = self.tag(x, base - size * 0.37, s, size * 0.8) + 8+ return x++ # ------------------------------------------------------------ icons+ def glyph(self, name, cx, cy, size=22, fill=FAINT, sw=1.8, alpha=1.0):+ """a line icon from GLYPHS (24-unit grid, stroke sw in grid units), centred on (cx, cy)"""+ k = size / 24.0+ pad = size * 0.6 + 2+ g = self._grid(cx - pad, cy - pad, cx + pad, cy + pad)+ if not g: return+ sl, X, Y = g+ u, v = (X - cx) / k + 12, (Y - cy) / k + 12+ d = np.full(np.broadcast(u, v).shape, 1e9, np.float32)+ for p in GLYPHS[name]:+ kind = p[0]+ if kind == 'p':+ e = sdf_polyline(u, v, p[1], len(p) > 2 and p[2]) - sw / 2+ elif kind == 'c':+ e = np.abs(np.hypot(u - p[1], v - p[2]) - p[3]) - sw / 2+ elif kind == 'a':+ e = sdf_polyline(u, v, _arc_pts(*p[1:])) - sw / 2+ elif kind == 'd':+ e = np.hypot(u - p[1], v - p[2]) - p[3]+ else: # 'r'+ x0, y0, x1, y1, rr = p[1:]+ e = np.abs(sdf_rrect(u - (x0 + x1) / 2, v - (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2, rr)) - sw / 2+ d = np.minimum(d, e)+ self._over(sl, _cov(d * k) * alpha, fill)++ # ------------------------------------------------------------ the app window+ def lights(self, x, cy, d=13, gap=9):+ for i, c in enumerate(LIGHTS):+ self.circle(x + d / 2 + i * (d + gap), cy, d / 2, c)++ def window(self, x, y, w, h, tabs=('未命名',), active=0, side=300, right=0, bar=52, ribbon=52, radius=14,+ ribbon_icons=RIBBON, lit_icon=None, tab_x=None):+ """the app window: shadow and 1 px ring, title bar (lights, tabs -- the active one open at the bottom so it+ joins the note -- and a + for a new tab), the icon ribbon, an explorer pane `side` px from the left edge+ (ribbon included; 0 = none) and a right sidebar `right` px wide (0 = none). Returns a Box with .bar (y of+ the title bar's bottom), .explorer, .note, .right (pane Boxes) and .tabs (tab Boxes)"""+ self.shadow(x, y, x + w, y + h, radius, 0, 40, 90, -30, '#000000', 0.8)+ self.rrect(x, y, x + w, y + h, radius, RING, ring=1.0, inset=False)+ self.rrect(x, y, x + w, y + h, radius, BG)+ yb = y + bar+ with self.clip(x, y, x + w, y + h, radius):+ self.rrect(x, y, x + w, yb, 0, SIDE)+ self.rrect(x, yb - 1, x + w, yb, 0, BORDER)+ self.rrect(x, yb, x + ribbon, y + h, 0, SIDE)+ self.rrect(x + ribbon - 1, yb, x + ribbon, y + h, 0, BORDER)+ if side:+ self.rrect(x + ribbon, yb, x + side, y + h, 0, SIDE)+ self.rrect(x + side - 1, yb, x + side, y + h, 0, BORDER)+ if right:+ self.rrect(x + w - right, yb, x + w, y + h, 0, SIDE)+ self.rrect(x + w - right, yb, x + w - right + 1, y + h, 0, BORDER)+ self.lights(x + 18, y + bar / 2)+ # tabs+ tx = tab_x if tab_x is not None else (x + side + 14 if side else x + 150)+ boxes = []+ for i, t in enumerate(tabs):+ on = i == active+ tw = self.measure(t, 19, 'semibold')+ x1 = tx + 22 + tw + 14 + 16 + 18+ b = Box(tx, yb - 40, x1, yb)+ if on:+ with self.clip(tx - 1, yb - 41, x1 + 1, yb + 1):+ self.rrect(tx - 1, yb - 41, x1 + 1, yb + 12, 11, BORDER)+ self.rrect(tx, yb - 40, x1, yb + 12, 10, BG)+ elif i and i - 1 != active:+ self.rrect(tx - 1, yb - 29, tx, yb - 11, 0, BORDER)+ self.text(t, tx + 22, yb - 20, 19, TEXT if on else MUTED, 'semibold', 'lm')+ self.glyph('x', x1 - 26, yb - 20, 15, FAINT if on else '#575757', 2.2)+ boxes.append(b)+ tx = x1 + 2+ self.glyph('plus', tx + 22, yb - 20, 19, FAINT, 2.0)+ self.glyph('chev_d', x + w - 34, y + bar / 2, 18, FAINT, 2.0)+ # ribbon+ for i, nm in enumerate(ribbon_icons):+ self.glyph(nm, x + ribbon / 2, yb + 30 + i * 46, 22, self.accent2 if nm == lit_icon else FAINT, 1.8)+ for i, nm in enumerate(['help', 'gear']):+ self.glyph(nm, x + ribbon / 2, y + h - 74 + i * 44, 22, FAINT, 1.8)+ B = Box(x, y, x + w, y + h, radius)+ B.bar, B.tabs = yb, boxes+ B.explorer = Box(x + ribbon, yb, x + side, y + h) if side else None+ B.note = Box(x + (side or ribbon), yb, x + w - right, y + h)+ B.right = Box(x + w - right, yb, x + w, y + h) if right else None+ return B++ def explorer(self, win, items, active=None, size=20, row=40, top=None, tools=True):+ """the file explorer in win.explorer: a row of small tool icons, then items (label, depth, kind) with kind+ 'open' (expanded folder), 'folder' (collapsed) or 'file'; the `active` index gets the highlight. Nested items+ hang off a faint indent guide. Returns a list of the rows' Boxes"""+ E = win.explorer+ if tools:+ names = ['edit', 'folder_plus', 'sort', 'collapse']+ for i, nm in enumerate(names):+ self.glyph(nm, E.cx + (i - 1.5) * 42, E.y0 + 30, 19, FAINT, 1.8)+ y = (top if top is not None else E.y0 + 66)+ rows, stack = [], []+ for i, (label, depth, kind) in enumerate(items):+ ix = E.x0 + 16 + depth * 20+ b = Box(E.x0 + 10, y, E.x1 - 10, y + row - 4, 6)+ if i == active:+ self.rrect(b.x0 + depth * 20, b.y0, b.x1, b.y1, 6, BG3)+ cy = b.cy+ if kind in ('open', 'folder'):+ self.glyph('chev_d' if kind == 'open' else 'chev_r', ix + 8, cy, 16, FAINT, 2.2)+ self.text(label, ix + 24, cy, size, MUTED, 'medium', 'lm')+ else:+ self.text(label, ix + 24, cy, size, BRIGHT if i == active else MUTED, 'medium' if i == active else 'regular', 'lm')+ rows.append(b)+ y += row+ # indent guides: from under each open folder's chevron down to its last child+ for i, (label, depth, kind) in enumerate(items):+ if kind != 'open': continue+ j = i + 1+ while j < len(items) and items[j][1] > depth: j += 1+ if j > i + 1:+ gx = E.x0 + 16 + depth * 20 + 8+ self.rrect(gx - 0.5, rows[i + 1].y0 + 2, gx + 0.5, rows[j - 1].y1 - 2, 0, BORDER2, 0.8)+ return rows++ def view_header(self, win, crumbs, size=17, h=56):+ """the note's view header: back / forward arrows and a breadcrumb (last crumb bright), with a more-icon+ at the right end. Returns the header Box"""+ N = win.note+ cy = N.y0 + h / 2+ self.glyph('back', N.x0 + 26, cy, 19, FAINT, 2.0)+ self.glyph('fwd', N.x0 + 56, cy, 19, '#4e4e4e', 2.0)+ parts = list(crumbs)+ widths = [self.measure(c, size, 'medium') for c in parts]+ sep = self.measure(' / ', size)+ total = sum(widths) + sep * (len(parts) - 1)+ x = N.cx - total / 2+ for i, c in enumerate(parts):+ last = i == len(parts) - 1+ x += self.text(c, x, cy, size, TEXT if last else FAINT, 'medium', 'lm')+ if not last: x += self.text(' / ', x, cy, size, '#555555', 'regular', 'lm')+ self.glyph('more', N.x1 - 28, cy, 19, FAINT, 1.8)+ return Box(N.x0, N.y0, N.x1, N.y0 + h)++ def toggle(self, x, y, w, h=44, labels=('源码', '阅读'), on=1, size=19):+ """segmented switch (source / reading): dark track with a 1 px ring, the `on` segment filled with the accent+ and white text, the other muted"""+ self.rrect(x, y, x + w, y + h, 11, BG3)+ self.rrect(x, y, x + w, y + h, 11, BORDER2, ring=1.0)+ n = len(labels)+ sw = (w - 8 - 4 * (n - 1)) / n+ for i, t in enumerate(labels):+ sx = x + 4 + i * (sw + 4)+ if i == on:+ self.shadow(sx, y + 4, sx + sw, y + h - 4, 8, 0, 0, 14, 0, self.accent, 0.35)+ self.rrect(sx, y + 4, sx + sw, y + h - 4, 8, self.accent)+ self.text(t, sx + sw / 2, y + h / 2, size, WHITE if i == on else MUTED, 'semibold', 'mm')+ return Box(x, y, x + w, y + h, 11)++ def sidebar_tools(self, win, icons=('link', 'graph', 'list'), lit=1, h=56):+ """the right sidebar's header row: small tab icons (the `lit` one in the accent) over a hairline"""+ R = win.right+ for i, nm in enumerate(icons):+ self.glyph(nm, R.x0 + 38 + i * 44, R.y0 + h / 2, 21, self.accent2 if i == lit else FAINT, 1.9)+ self.rrect(R.x0 + 20, R.y0 + h - 1, R.x1 - 20, R.y0 + h, 0, BORDER)+ return R.y0 + h++ def status_bar(self, win, items, size=15):+ """the floating status bar in the window's bottom-right corner (rounded top-left, hairline edge)"""+ gap = 22+ widths = [self.measure(t, size) for t in items]+ w = sum(widths) + gap * (len(items) - 1) + 32+ x1, y1 = win.x1, win.y1+ x0, y0 = x1 - w, y1 - 34+ with self.clip(win.x0, win.y0, win.x1, win.y1, win.r):+ self.rrect(x0 - 1, y0 - 1, x1 + 20, y1 + 20, 9, BORDER)+ self.rrect(x0, y0, x1 + 20, y1 + 20, 8, SIDE)+ x = x0 + 16+ for t, tw in zip(items, widths):+ self.text(t, x, y0 + 17, size, FAINT, 'regular', 'lm')+ x += tw + gap+ return Box(x0, y0, x1, y1)++ # ------------------------------------------------------------ note content+ def h1(self, x, base, s, size=80, fill=BRIGHT, bar=True, bar_w=None, bar_gap=18, weight='heavy', draw_text=True):+ """the note's H1 (heavy, slightly tight tracking for Latin) with a short accent bar and its glow under it.+ bar=False / draw_text=False draw only one of the two (put them in two layers to animate the bar).+ Returns (width, bar Box or None)"""+ latin = not any(_is_cjk(c) for c in s)+ sp = -size * 0.02 if latin else 0.0+ tw = self.measure(s, size, weight, sp)+ if draw_text:+ self.text(s, x, base, size, fill, weight, spacing=sp)+ bb = None+ if bar:+ bw = bar_w or min(tw, 230)+ y0 = base + bar_gap+ self.shadow(x, y0, x + bw, y0 + 7, 3.5, 0, 0, 18, 0, self.accent, 0.55)+ self.rrect(x, y0, x + bw, y0 + 7, 3.5, self.accent)+ bb = Box(x, y0, x + bw, y0 + 7, 3.5)+ return tw, bb++ def heading(self, x, base, s, size=40, fill=BRIGHT, marker=False):+ """an H2 / H3 (marker=True also shows the faint ## of the source view)"""+ if marker:+ x += self.text('## ', x, base, size * 0.7, FAINT, 'semibold') + 4+ return self.text(s, x, base, size, fill, 'bold')++ def tag(self, x, cy, s, size=20):+ """#tag pill: accent text on a 20 % accent capsule. Returns the right edge"""+ tw = self.measure(s, size, 'medium')+ h = size * 1.5+ self.rrect(x, cy - h / 2, x + tw + size * 1.2, cy + h / 2, h / 2, self.accent, 0.2)+ self.text(s, x + size * 0.6, cy, size, self.accent2, 'medium', 'lm')+ return x + tw + size * 1.2++ def prop(self, x, cy, glyph, key, key_w=150, size=19):+ """one row of the properties block: icon + key in faint grey; the value starts at the returned x"""+ self.glyph(glyph, x + 10, cy, size, FAINT, 1.9)+ self.text(key, x + 32, cy, size, MUTED, 'regular', 'lm')+ return x + key_w++ def code_line(self, x, base, toks, size=24):+ """one line of a code block: toks = [(text, kind), ...], kind in SYNTAX (kw str num op cm fence text) or a+ hex colour. Returns the end x"""+ for t, k in toks:+ col = SYNTAX.get(k, k) if k else CODE_TEXT+ x += self.text(t, x, base, size, col, 'regular', family='mono')+ return x++ def code_block(self, x, y, w, lines=(), size=24, lang='mermaid', pad=(26, 30), lh=1.6, n_lines=None, draw=True):+ """dark code block (1 px border, radius 10, language label top right). lines: list of token lists for+ code_line; draw=False only draws the block (lines go in other layers). Returns a Box with .bases (line+ baselines), .tx (text x) and .lh"""+ n = n_lines or len(lines)+ step = size * lh+ h = pad[0] * 2 + step * n - (step - size * 1.15)+ self.rrect(x, y, x + w, y + h, 10, BORDER, ring=1.0)+ self.rrect(x + 1, y + 1, x + w - 1, y + h - 1, 9, CODE_BG)+ if lang:+ self.text(lang, x + w - 18, y + 26, 16, FAINT, 'bold', 'rm', family='mono')+ b = Box(x, y, x + w, y + h, 10)+ b.tx, b.lh = x + pad[1], step+ b.bases = [y + pad[0] + size * 0.95 + i * step for i in range(n)]+ if draw:+ for toks, base in zip(lines, b.bases):+ self.code_line(b.tx, base, toks, size)+ return b++ def caret(self, x, base, size=24, colour=None):+ """the block caret at the end of a typed line"""+ self.rrect(x + 3, base - size * 0.9, x + 3 + size * 0.5, base + size * 0.22, 1.5, colour or self.accent2)++ def callout(self, x, y, w, title, lines=(), size=26, title_size=None, colour=None, glyph='quote', lh=1.6, pad=(20, 26)):+ """callout (> [!quote]): tinted 16 % with a 4 px left edge in the callout colour (default: the accent), an+ icon and a bold title in the light tone, then body lines (each a runs list for rich(), or a string).+ Returns its Box"""+ c = colour or self.accent+ light = self.accent2 if colour is None else colour+ ts = title_size or size+ h = pad[0] * 2 + ts * 1.1 + len(lines) * size * lh + (6 if lines else 0)+ self.rrect(x, y, x + w, y + h, 8, c, 0.16)+ with self.clip(x, y, x + w, y + h, 8):+ self.rrect(x, y, x + 4, y + h, 0, c)+ tb = y + pad[0] + ts * 0.92+ gx = x + pad[1] + 4+ if glyph:+ self.glyph(glyph, gx + ts * 0.42, tb - ts * 0.37, ts * 0.95, light, 2.0)+ gx += ts * 0.95 + 10+ self.text(title, gx, tb, ts, light, 'bold')+ for i, ln in enumerate(lines):+ base = tb + 6 + (i + 1) * size * lh+ self.rich(x + pad[1] + 4, base, ln if isinstance(ln, (list, tuple)) else [(ln, None)], size)+ return Box(x, y, x + w, y + h, 8)++ def checkbox(self, x, y, size=30, checked=True):+ """task-list checkbox, top-left at (x, y): accent fill with a white tick, or an empty faint ring"""+ r = size * 0.24+ if checked:+ self.rrect(x, y, x + size, y + size, r, self.accent)+ self.glyph('check', x + size / 2, y + size / 2, size * 0.78, WHITE, 3.4)+ else:+ self.rrect(x, y, x + size, y + size, r, FAINT, ring=size * 0.075)++ # ------------------------------------------------------------ rendered diagram (reading view)+ def dnode(self, cx, cy, w, h, label, shape='rect', hi=False, size=24, focus=False):+ """a diagram node centred on (cx, cy): shape rect (r 5) / round (r 14) / stadium / diamond; flat dark fill,+ 2 px grey border, text centred; hi = the accent node (accent tint, light border); focus adds a soft+ accent ring 14 px outside. Returns its Box"""+ x0, y0, x1, y1 = cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2+ edge = self.accent2 if hi else NODE_EDGE+ if focus:+ rr = {'rect': 5, 'round': 14, 'stadium': h / 2}.get(shape, 14) + 13+ self.shadow(x0 - 14, y0 - 14, x1 + 14, y1 + 14, rr, 0, 0, 30, 0, self.accent, 0.35)+ self.rrect(x0 - 14, y0 - 14, x1 + 14, y1 + 14, rr, self.accent, 0.75, ring=2.5)+ if shape == 'diamond':+ P = [(cx, y0), (x1, cy), (cx, y1), (x0, cy)]+ self.poly(P, NODE_FILL)+ if hi: self.poly(P, self.accent, 0.24)+ self.line(P, 2.0, edge, closed=True)+ else:+ r = {'rect': 5, 'round': 14, 'stadium': h / 2}[shape]+ self.rrect(x0, y0, x1, y1, r, NODE_FILL)+ if hi: self.rrect(x0, y0, x1, y1, r, self.accent, 0.24)+ self.rrect(x0, y0, x1, y1, r, edge, ring=2.0)+ self.text(label, cx, cy, size, BRIGHT if hi else TEXT, 'medium', 'mm')+ return Box(x0, y0, x1, y1)++ def dedge(self, pts, width=2.6, colour=None, head=11.0, label=None, size=17, label_at=0.5):+ """a diagram edge along pts (2+ points) with a small filled arrowhead at the end; optional label in a+ dark chip at fraction `label_at` of the way (a mermaid -->|label| edge)"""+ col = colour or NODE_LINE+ P = np.asarray(pts, np.float32)+ d = P[-1] - P[-2]; d = d / (np.hypot(*d) + 1e-9); n = np.array([-d[1], d[0]])+ tip = P[-1]; back = tip - d * head+ self.line(np.vstack([P[:-1], back + d * 1.0]), width, col)+ self.poly([tuple(tip), tuple(back + n * head * 0.47), tuple(back - n * head * 0.47)], col)+ if label:+ seg = np.cumsum(np.r_[0, np.hypot(*np.diff(P, axis=0).T)])+ s = seg[-1] * label_at+ i = min(int(np.searchsorted(seg, s)) - 1, len(P) - 2); i = max(i, 0)+ t = (s - seg[i]) / max(seg[i + 1] - seg[i], 1e-6)+ lx, ly = P[i] + (P[i + 1] - P[i]) * t+ tw = self.measure(label, size, 'medium')+ self.rrect(lx - tw / 2 - 9, ly - size * 0.8, lx + tw / 2 + 9, ly + size * 0.8, 6, BG2)+ self.rrect(lx - tw / 2 - 9, ly - size * 0.8, lx + tw / 2 + 9, ly + size * 0.8, 6, BORDER2, ring=1.0)+ self.text(label, lx, ly, size, MUTED, 'medium', 'mm')++ # ------------------------------------------------------------ graph view+ def glink(self, a, b, lit=False, alpha=1.0):+ """a graph-view link between two points: thin grey, or the accent (thicker) when both ends are lit"""+ self.line([a, b], 2.6 if lit else 1.6, self.accent if lit else LINK, alpha)++ def gnode(self, x, y, r=8.0, label=None, lit=False, label_size=16, glow=1.0, bg=SIDE):+ """a graph-view node: grey disc, or (lit) the light accent with a soft glow round it; label under it with a+ thin outline in the pane colour `bg`, so links stop short of the words"""+ if lit:+ self.halo(x, y, r * 4.2, self.accent, 0.42 * glow, 1.6)+ self.circle(x, y, r * 1.9, self.accent, 0.16 * glow)+ self.circle(x, y, r, self.accent2 if lit else GNODE)+ if label:+ self.text(label, x, y + r + 8 + label_size * 0.86, label_size, BRIGHT if lit else MUTED,+ 'semibold' if lit else 'regular', 'ms', halo=3 if bg else 0, halo_fill=bg)++ def graph(self, nodes, links, lit=(), label_size=16, only=None, bg=SIDE):+ """a whole graph view: nodes [(x, y, r, label), ...], links [(i, j), ...]; `lit` = indices drawn in the accent+ (a link is lit when both ends are). only='grey' / 'lit' draws just one half (two layers to fade between)"""+ lit = set(lit)+ for i, j in links:+ on = i in lit and j in lit+ if only == 'lit' and not on: continue+ if only == 'grey' and on: on = False+ self.glink(nodes[i][:2], nodes[j][:2], on)+ for k, (x, y, r, lab) in enumerate(nodes):+ on = k in lit+ if only == 'lit' and not on: continue+ self.gnode(x, y, r, lab, on and only != 'grey', label_size, bg=bg)++ # ------------------------------------------------------------ pointer+ def cursor(self, x, y, scale=1.4, click=0.0):+ """the white mouse pointer (dark outline, soft drop shadow), tip at (x, y); click 0..1 draws the expanding+ accent ring of a click"""+ if click > 0:+ self.circle(x, y, 8 + 26 * click, self.accent2, 1 - click, ring=3.0)+ P = [(x + (px - 1) * scale, y + (py - 1) * scale) for px, py in CURSOR]+ P_ = np.asarray(P, np.float32)+ x0, y0 = int(np.floor(P_[:, 0].min())) - 1, int(np.floor(P_[:, 1].min())) - 1+ x1, y1 = int(np.ceil(P_[:, 0].max())) + 2, int(np.ceil(P_[:, 1].max())) + 2+ im = Image.new('L', ((x1 - x0) * 4, (y1 - y0) * 4), 0)+ ImageDraw.Draw(im).polygon([((px - x0) * 4, (py - y0) * 4) for px, py in P], fill=255)+ m = np.asarray(im.resize((x1 - x0, y1 - y0), Image.BOX), np.float32) / 255+ self.soft_shadow(m, (x0, y0), 0, 4, 8, '#000000', 0.6)+ self.poly(P, WHITE)+ self.line(P, 1.6 * scale, '#111111', closed=True)++ # ------------------------------------------------------------ compositing+ def _posed(self, L):+ p = L.pose+ rgb, a, lx0, ly0 = self._view(L)+ h, w = a.shape+ x0, y0 = float(lx0), float(ly0)+ s = p['scale']+ if abs(s - 1) > 1e-4:+ ox, oy = p['origin'] or (lx0 + w / 2, ly0 + h / 2)+ nw, nh = max(1, int(round(w * s))), max(1, int(round(h * s)))+ rs = lambda ch: np.asarray(Image.fromarray(np.ascontiguousarray(ch), 'F').resize((nw, nh), Image.BILINEAR), np.float32)+ rgb = np.stack([rs(rgb[..., k]) for k in range(3)], -1)+ a = rs(a)+ x0, y0 = ox + (x0 - ox) * s, oy + (y0 - oy) * s+ w, h = nw, nh+ if p['reveal'] < 1:+ fe = max(p['feather'], 1)+ if p['mode'] == 'r':+ ox, oy = p['origin'] or (x0 + w / 2, y0 + h / 2)+ xs = np.arange(w, dtype=np.float32)[None, :] + x0 + 0.5 - ox+ ys = np.arange(h, dtype=np.float32)[:, None] + y0 + 0.5 - oy+ dist = np.hypot(xs, ys)+ far = max(np.hypot(x0 - ox, y0 - oy), np.hypot(x0 + w - ox, y0 - oy), np.hypot(x0 - ox, y0 + h - oy),+ np.hypot(x0 + w - ox, y0 + h - oy))+ m = np.clip((far * p['reveal'] - dist) / fe + 0.5, 0, 1) if p['reveal'] > 0 else np.zeros((h, w), np.float32)+ rgb = rgb * m[..., None]; a = a * m+ else:+ n = w if p['mode'] == 'x' else h+ cut = n * p['reveal']+ xs = np.arange(n, dtype=np.float32)+ m = np.clip((cut - xs) / fe + 0.5, 0, 1) if p['reveal'] > 0 else np.zeros(n, np.float32)+ if p['mode'] == 'x':+ rgb = rgb * m[None, :, None]; a = a * m[None, :]+ else:+ rgb = rgb * m[:, None, None]; a = a * m[:, None]+ return rgb, a, int(round(x0 + p['dx'])), int(round(y0 + p['dy']))++ def render(self):+ """composite the page and every layer under its current pose -> float RGB"""+ out = self.base.copy()+ for L in sorted(self.layers.values(), key=lambda q: (q.z, q.order)):+ al = L.pose['alpha']+ if al <= 0: continue+ rgb, a, x0, y0 = self._posed(L)+ h, w = a.shape+ X0, Y0 = max(0, x0), max(0, y0)+ X1, Y1 = min(self.W, x0 + w), min(self.H, y0 + h)+ if X1 <= X0 or Y1 <= Y0: continue+ cr = rgb[Y0 - y0:Y1 - y0, X0 - x0:X1 - x0]; ca = a[Y0 - y0:Y1 - y0, X0 - x0:X1 - x0]+ out[Y0:Y1, X0:X1] = out[Y0:Y1, X0:X1] * (1 - ca[..., None] * al) + cr * al+ return out++ def composite(self):+ I = self.render() + self._grain[..., None]+ return Image.fromarray((np.clip(I, 0, 1) * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ """snapshot the current poses (kept PNG-compressed in memory)"""+ if self.keep_stages:+ buf = io.BytesIO()+ self.composite().save(buf, 'PNG', compress_level=1)+ self.stages.append((name, buf.getvalue()))++ def save(self, path, stages_dir=None, quality=88):+ self._close()+ img = self.composite()+ if str(path).lower().endswith(('.jpg', '.jpeg')): img.save(path, quality=quality, subsampling=0)+ else: img.save(path)+ if stages_dir:+ os.makedirs(stages_dir, exist_ok=True)+ for i, (name, png) in enumerate(self.stages):+ with open(f'{stages_dir}/{i:03d}_{name}.png', 'wb') as fh:+ fh.write(png)+ img.save(f'{stages_dir}/{len(self.stages):03d}_final.png')+ return img