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 dry-brush blocks and twilight storybook styles (69 total)
cloveric86adbe1b41e0
diff --git a/README.md b/README.mdindex 3226009..4bebacf 100644--- a/README.md+++ b/README.md@@ -1,7 +1,7 @@# Claude Drawing · Claude 绘图-**Claude paints with code — no image model.** Sixty-seven 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 and a Jiangnan water garden in spring.-**不用生图模型,Claude 用代码一笔一笔作画。** 六十七种画风,从水墨、油画到黏土、蓝晒、彩色玻璃花窗、罗马马赛克、代尔夫特蓝瓷砖、赛博朋克、光线追踪的小球海、低多边形 3D、热成像、X 光片、VHS 录像带、Synthwave 落日、产品发布片式的粉彩界面、红笔批改的答题卡、油灯下的皮影戏、钢笔淡彩的速写小卡、复古水粉的绘本大头像、蓝调绘本的雨天跨页和江南园林的春水园景。+**Claude paints with code — no image model.** Sixty-nine 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 and a dusk picture-book page where the sky turns to stars.+**不用生图模型,Claude 用代码一笔一笔作画。** 六十九种画风,从水墨、油画到黏土、蓝晒、彩色玻璃花窗、罗马马赛克、代尔夫特蓝瓷砖、赛博朋克、光线追踪的小球海、低多边形 3D、热成像、X 光片、VHS 录像带、Synthwave 落日、产品发布片式的粉彩界面、红笔批改的答题卡、油灯下的皮影戏、钢笔淡彩的速写小卡、复古水粉的绘本大头像、蓝调绘本的雨天跨页、江南园林的春水园景、干刷色块的 mid-century 海报和暮色微缩绘本里转入星空的黄昏。[English](#english) · [中文](#中文)@@ -52,6 +52,8 @@|  |  |  || **Retro gouache · 复古水粉** | **Blue picture book · 蓝调绘本** | **Jiangnan garden · 江南园林** ||  |  |  |+| **Dry-brush blocks · 干刷色块** | **Twilight storybook · 暮色微缩绘本** | **Ink wash · 水墨(月印万川)** |+|  |  |  |### Gallery · 画廊@@ -125,8 +127,10 @@| <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%"> |-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, and a spring garden built leaf by leaf, its tiled roofs and willows mirrored in a jade lake. 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.+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, and a dusk sky going over to stars above thousands of tiny wildflowers. 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.---@@ -134,7 +138,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 sixty-seven styles:+A [Claude Code](https://claude.com/claude-code) skill and a small painting library with sixty-nine styles:| Style | Module | What makes it read as the real medium ||---|---|---|@@ -205,6 +209,8 @@ A [Claude Code](https://claude.com/claude-code) skill and a small painting libra| **Retro gouache (复古水粉)** | `lib/gouache.py` · `GouachePortrait` | picture-book character portraits in opaque gouache, painted the way a gouache painter works, dark to light and big to small: a warm imprimatura scrubbed onto the board, an umber underdrawing, a background laid solid and then scumbled with a nearly dry brush in lighter and darker mixes, flat masses, forms modelled in a few value steps, textures, features and dry-brush highlights, then the grain of the printed page. Every coat is opaque (it replaces what is under it), and a wet brush picks up a little of the layer below. One stroke is a flat brush dragged along a short arc: the hairs carry different loads, so streaks run along it; the paint runs out as it goes, so the tail breaks into specks where only the tooth of the board catches it; the sides are ragged and the head is rounded. Edges are crisp but wander and break on the tooth. Forms are inflated into a dome (an exact ellipsoid for noses, bobbles and pearls), lit from the upper left, quantised into soft steps and mapped onto five mixed colours, then brushed over with short strokes that follow the form, so the steps meet in brushy seams; core shadows under a brim, a nose or a beard are thin multiply glazes, and cheeks are powdery blush. Knit is modelled stitch by stitch (V-shaped legs with twisted plies, cables twisting in a column, ribbing with sunken purl columns) and multiplied onto the paint, so the large value steps survive. Hair, brows, beards, curls and bobbles are thousands of tapered strands that follow a flow field and are sorted by the light. Felt is mottle, fibres and a fuzzy silhouette. Helpers for goofy faces: round eyes with lids and catchlights (a `look` that can go cross-eyed), big bulbous noses with nostrils and a glint, big ears || **Blue picture book (蓝调绘本)** | `lib/bluebook.py` · `BlueBook` | a page of a soft-blue modern picture book, drawn the way the illustrator works and then printed: colour blocks, a loose ink line, dark masses scribbled in, small accents, chalk whites, weather, print. The palette is held to three blues (powder, cornflower, a deep teal-blue), black ink and paper white, with only a little coral, flesh pink and mustard. Every tool works on one paper tooth, equalised so that "the tool reaches where the tooth is higher than 1 − contact" turns a pressure straight into a coverage fraction, and pre-dragged in eight directions so the bare specks a dry tool skips are drawn out along its stroke. An ink stroke is a brush or ink-pencil line: the path wobbles and trembles, the pressure lands fast, lifts slowly and swells and thins on the way, the hairs carry different loads and run dry along the stroke so the line breaks into dry white streaks, and its edge wanders with the tooth; every pixel knows its arc length and its offset across the mark (Pillow rasterises segment ids, numpy projects exactly). Closed shapes are not closed: a contour is one to three strokes that stop short or run past the join, now and then gone over again a couple of px off. Dark masses are zigzag scribbles that turn past the outline, one wrist-sized patch at a time. Colour is dry crayon, pastel or dry gouache laid loosely after the idea of the shape: the region slips a few px, its edge wanders, its border dries out, it goes on in stroke lanes with a mottled density, and white specks of paper show through; wax is semi-opaque (over white it is the colour, over ink it stays dark, blue over blue goes deeper) and the line always stays on top. The background is a rough-sided block that stops short of the page edge, its border brushed along itself and dragged dry. White chalk sits only on the tooth peaks over the blue; rain is short dry strokes with splashes, ripples, flicked spatter and fine speckle. Character helpers: big round heads drawn open, dot eyes with a white glint, tiny smiles, stippled blush and freckles, and fluffy white animals whose outline is a run of scalloped ink tufts with chalk fur crossing into the blue. The print step adds a slight softness, lifted blacks, paper speck, a centre gutter fold and tiny page numbers || **Jiangnan garden (江南园林)** | `lib/jiangnan.py` · `JiangnanGarden` | a lush, finely painted spring garden in the manner of a contemporary digital-gouache illustration, painted back to front the way a landscape painter works: sky, far hills, haze, the trees behind, the buildings, the far bank, the water, things on the water, the foreground, the hanging frame, the seal. Every painting call takes a `far` value that pulls colours toward a pale blue-green haze and flattens their contrast, and haze bands separate the depth planes. The unit of paint is a dab — a pointed leaf, a round petal, a sword blade — and thousands of them are laid at once: Pillow fills every polygon with its own id into a 2× supersampled id map (later ids cover earlier ones), numpy looks the ids up in a colour/alpha table and box-averages back down, so a dab costs well under a microsecond. Trees are sets of clumps, each lit as a dome by one sun from the upper left; a dab takes its colour from a ramp of mixed greens by the light of the clump it sits on, and the tree is built as a gouache painter builds it: a leafy dark underpaint, a mid-dark body, leaves breaking out across the silhouette, small clusters of lit leaves where the light is high, and a few palest dabs on top. Blossom trees are clusters of round petals sorted dark to light over shadowed petals and green leaves, with branches showing through; near branches carry individual five-petal flowers and buds. A weeping willow is a domed crown over hidden boughs with hundreds of hair-thin strands hanging in tresses, darker and bluer behind, lighter and yellower in front. The roof is a real surface S(u, v): concave slope, widening toward the eave, flaring, sharply upturned corners; it is rasterised as a quad mesh and every pixel's (u, v) is recovered by Newton steps, so roll and pan tiles, course lips, tile ends, drip tiles, the soffit with rafter ends, the eave shadow, an openwork ridge with curled ends and hip ridges running up into the flying corners are all shaded analytically. Lattice (grid, lantern frame, cracked ice) is drawn at 3× and lit on its edges; the zigzag bridge, its slabs, piers, posts and pierced panels are projected through a pinhole camera and shaded face by face. The lake mirrors the canvas above the bank line, rippled sideways, blurred vertically, darkened and mixed with the jade body colour toward the viewer; the bridge, a boat and an egret get their own reflections, and lily pads lie foreshortened on the water plane. Dappled leaf shade, a red lantern, a gilded plaque, a tiny worn seal, and a finish of slight softness, a glow around the lights and fine grain complete it |+| **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 |Ask Claude to *"draw it yourself"*, *"paint this with code"*, or *"claude绘图"*, and name a style if you like. Claude then:@@ -341,6 +347,18 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages- a flying egret with one narrow upright wing is a feather;- a pale empty band on a far bank is a wall of fog — plant it down to the water.Finish with dappled leaf shade on the sunlit walls and a soft glow, and keep the seal tiny.+- **Dry-brush blocks**: build the picture from a few big blocks and keep to the poster's six or seven colours; no outlines and no gradients — forms read from the edges and overlaps of the blocks. Make the texture with the stroke, not on top of it: work in the block's own brush frame so streaks and dry ends follow the stroke, let coverage come only from contact pressure against the paper's tooth, and keep the sides nearly straight while the ends comb out. The noise behind that tooth must be stationary and periodic (blurred white noise, wrapped): an upsampled coarse grid thresholds into rungs that read as crayon hatching, and zero-padded tiles leave empty columns. A big backdrop wants a roller (flat, clustered speckle, dry only along the sides), not bristle streaks, or it rains; a solid object over a dark ground (a porcelain bowl) needs an overloaded brush (`load` > 1), or the dark shows through its specks. Break long passes into strokes of different lengths and tones, or a jacket turns into stripes. Watch for accidental reads:+ - wisps of low-load strokes are wire, a scumbled band is grey fog — leave the steam out;+ - lenses tinted much darker than about a fifth (0.45 did it) turn glasses into sunglasses;+ - a nose whose shadow side matches the cheek disappears, and its warm tip becomes a mouth;+ - a dry fringe on a small object reads as motion lines.+ Put one small vermilion square in the empty paper, and print last.+- **Twilight storybook**: set the night field first and paint everything that is lit through it, so the dusk side and the night side share one light — a white daisy goes moonlit blue, not grey — and keep emissive things (stars, fireflies, the lantern) and the plate unlit. The transition must pass through mauve, violet and indigo: re-saturate it, but gently, or it becomes a neon wall; let it arc in like a dome rather than run as a straight diagonal, and keep the dusk pale enough that the clouds still read against it. Keep the four-point sparkles few and small, deep in the night. Let perspective set the meadow: specks at the crest, whole flowers at the bottom, far flowers sunk into the hazy ground, or the crest turns into a bright band. Put a coloured prop (the kite) where the night grade will not grey it. Watch for accidental reads:+ - thin unbroken lines in the sky are wires, not clouds — clouds are soft lenses with flatter bottoms;+ - a hard tan stripe along a figure's sunset side is a band, not a rim light;+ - patchwork stripes in saturated, contrasting colours read as flags;+ - a marker ring in a mid tone vanishes on a coral kite — draw markers and leaders in dark ink.+ In the inset, keep labels inside the disc and numbers off the lines, and call `finish()` before the first stroke so the stage snapshots match the final.### Roadmap@@ -352,7 +370,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,加上一个小巧的绘图库,内置六十九种画风:| 画风 | 模块 | 为什么看起来像真的 ||---|---|---|@@ -423,6 +441,8 @@ Every style has a complete example: `python3 examples/<name>.py out.png --stages| **复古水粉** | `lib/gouache.py` · `GouachePortrait` | 用不透明水粉画复古绘本里的大头像,照水粉画家的顺序从暗到亮、从大到小:画板上先刷一层暖色托底,用赭色起稿;背景先满载铺平,再用半干的笔蘸亮一点、暗一点的同色皴擦;然后平涂大块,用几阶色值塑形,再上质感、五官和干笔高光,最后是印刷书页的颗粒。每一层都不透明(盖住下面),湿笔会带起一点底色。一笔是扁笔沿短弧拖过去:鬃毛含色不同,所以顺着笔有条纹;颜料越拖越少,笔尾只在纸纹凸起上留下断续的丝和点;两侧毛边,落笔处圆头。边缘利落,但会游走、在纸纹上断开。形体先鼓成穹顶(鼻子、绒球、珍珠用精确的椭球),左上方一盏灯,受光分成几个软台阶、映射到五个调出来的颜色,再用顺着形体的短笔一笔笔盖上去,台阶之间是带笔触的接缝;帽檐、鼻子、胡子下面的暗部是一层薄薄的正片叠底,腮红是粉状的。毛衣一针一针地算:V 字两条带捻股的纱线、交替在前的麻花、凹下去的反针罗纹,乘到已有的颜料上,大的明暗不丢。头发、眉毛、胡子、卷发、绒球是成千上万根锥形细线,沿流向场走、按受光分档。毛毡是斑驳、短纤维和毛茸茸的轮廓。呆萌五官:带眼皮和高光的圆眼(`look` 可以对成斗鸡眼)、带鼻孔和亮点的大鼻子、大耳朵 || **蓝调绘本** | `lib/bluebook.py` · `BlueBook` | 一页软蓝色调的现代绘本,照绘本画家的顺序画、再印出来:先上色块,再松松地勾墨线,乱线排出暗部,加一点点睛色,压白粉笔,然后是天气,最后印刷。颜色守在三阶蓝(粉蓝、矢车菊蓝、深青蓝)、黑墨和纸白,只点一点珊瑚红、粉色腮红和芥末黄。所有工具都落在同一张纸纹上:纸纹做过直方图均衡,「工具碰到纸纹高于 1 − 接触压力的地方」就直接等于覆盖率;纸纹还预先沿八个方向拖开,干的工具漏掉的白点会顺着笔拉成短道。一笔墨线是毛笔或墨铅笔:路径带手抖和细颤,落笔快、收笔慢,沿途粗细起伏;几根笔毛含墨不同、越画越干,线会断成顺着笔的干白道,边缘随纸纹游走;每个像素都知道自己在这一笔上的弧长和横向偏移(Pillow 画线段序号,numpy 精确投影)。闭合的形状不闭合:一个轮廓分一到三笔,在接头前停下或冲过接头,偶尔再描一遍、偏开一两 px。暗部是转折冲出轮廓的之字乱线,一次一个手腕的范围。颜色是干蜡笔、粉彩或干水粉,按大概的形状松松地涂:整体错开几 px,边缘游走,靠边处变干,一道道笔道、浓淡斑驳,纸纹白点透出来;蜡是半透明的(白纸上是本色,墨上仍是黑,蓝上加蓝更深),墨线永远在颜色上面。背景是一块毛边、不到纸边的色块,边缘顺着边刷、拖干。白粉笔只挂在纸纹凸起上,压在蓝上;雨是短的干笔,加水花、水纹、甩点和细尘。角色部件:开口的大圆脑袋、带白高光的点点眼、小小的笑、点彩腮红和雀斑,白色毛绒动物的轮廓是一串扇贝形的墨线小弧,白毛越过边缘压在蓝上。印刷一步加轻微柔化、抬黑、细纸点、中缝折痕和小页码 || **江南园林** | `lib/jiangnan.py` · `JiangnanGarden` | 一幅繁茂、细腻的园林春景,像当代的数字水粉插画,照风景插画家的顺序从后往前画:天空、远山、雾、屋后的树、建筑、对岸、水、水上的东西、前景、垂挂的画框、印章。每个画法都带 `far`,越远颜色越往淡青绿的雾色靠、对比越低,深度层之间再铺雾带。颜料的单位是一笔:尖叶、圆花瓣、剑形叶;成千上万笔一次画完:Pillow 把每个多边形按序号填进 2 倍超采样的 id 图(后画的盖住先画的),numpy 按 id 查颜色和透明度再缩回来,一笔不到 1 微秒。树是一组团块,每块当成被左上方太阳照亮的穹顶;每一笔按它所在团块的光从一条混好的绿色色阶取色,整棵树照水粉画家的画法堆出来:叶片打的暗底、中暗的叶、穿出轮廓的叶、光强处一簇簇亮叶、顶上几笔最亮的。繁花树是一簇簇圆花瓣按明暗排序压在暗花瓣和绿叶上,枝条从缝里露出来;近处花枝是一朵朵五瓣花和花苞。垂柳是盖住枝的垂叶树冠,加几百根发丝细的柳丝一绺一绺垂下,后排暗、偏蓝,前排亮、偏黄。屋顶是一张真的曲面 S(u, v):上陡下缓、越往下越宽、翼角外甩、檐角急翘;曲面拆成网格画进 id 图,每个像素用牛顿迭代反求 (u, v),于是筒瓦板瓦、瓦口亮边、瓦当滴水、椽头和檐底、檐影、镂空花脊和卷起的脊头、一直通到翼角尖的戗脊都按解析式上色。槅扇(方格、灯笼锦、冰裂纹)在 3 倍图上画、棂条边上有明暗;九曲桥的石板、桥墩、望柱和镂空栏板经针孔相机投影、逐面上色。湖面按岸线镜像岸上的画面,横向被细浪推开、竖向模糊、压暗,越往近处越多地混进碧绿的本色;桥、船和白鹭各有自己的倒影,睡莲叶按透视压扁躺在水面上。再加墙上桥上的叶影、红灯笼、描金匾额、一方磨损的小红印,最后轻微柔化、亮部光晕和细颗粒 |+| **干刷色块** | `lib/drybrush.py` · `DryBrushBlocks` | mid-century 海报 / 水粉拼贴式的编辑插画:米白纸上几大块干笔刷出的色块,颜色严格限定:森林绿、鼠尾草绿、青蓝、藏蓝、近黑、朱红,外加一点天蓝和淡青瓷。每块颜色在自己的笔刷坐标系里刷:把遮罩转到笔触方向沿 +u,在里面用普通数组算覆盖率、明暗和混色,再转回去,所以鬃毛纹、笔道和干笔收尾永远顺着笔走。一块颜色是一道道平行的宽笔或滚筒,每道起笔饱满、往收笔各干各的,也可以打断成长短不一、各有明暗的短笔;两侧几乎是直边,两端梳成长短不一的毛齿,干的一端更长。颜料只在接触压力够的地方挂上纸纹的齿——纸纹做过直方图均衡,压力直接就是覆盖率——于是有皴擦的斑和干擦的边,露出纸色或下层颜色;蘸满的笔照样实。主体背后的大色板用滚筒刷(近乎平涂、成簇细点、起笔边干净、干的两侧、几道细刮痕);撕纸片只有部分轮廓是撕口,带一圈浅色纤维边。人物是几块面:亮暗两半朝不同方向刷的外套,几块肤色平面拼的头(更暗的鼻侧、暖色鼻头),粗黑框眼镜,干笔皴擦的白胡子,从拇指一侧看的手;瓶子是竖刷的深色剪影,一道高光、一小块标签。一旁一个小朱红方块,最后像这幅画的胶印:轻微柔化、纸纹、暗部零星白点、一点细尘 |+| **暮色微缩绘本** | `lib/twilight.py` · `TwilightStorybook` | 一页温柔的黄昏绘本,满是微缩细节,画的是白天转入黑夜的那一刻。黄昏天空是六段渐变(薰衣草紫、丁香、玫瑰、蜜桃、杏、金),分段位置被横向拉长的噪声扰动,颜色一层层是软的;云是透镜形的带(顶上软而起伏,底部更平更清),加细细的光线和一轮低垂的淡日。一条游走的边界在整幅画上定出带羽化的夜度场 N(0 黄昏 – 1 夜):夜空渐变、银河、星星和月亮按 N 当透明度铺上去,星星越过边界慢慢变稀,不会停在一条线上;交界带补饱和度,黄昏经过淡紫、紫、靛蓝再到黑,不发灰。之后画的受光的东西(山、花、人物)都按同一个场经一个 3×3 线性变换(先降饱和、再偏冷)着色,夜的一侧的白雏菊成了月光蓝;发光的东西和图版不受影响。银河是解析的带,云状密度、一条暗带,几千颗暗星按它的密度抽样;星星是幂律亮度、亚像素溅射,最亮的几颗加四芒星。山是带雾的远山和越近越宽的拼布条纹,切成斜的田,有细垄和树篱线,点着小圆树。花坡按透视拒绝采样:大小随离坡顶的深度增长,密度按覆盖率定,所以坡顶是几千个色点、底边是几十朵八种大花;所有形状按根部的 y 排序,一次光栅化进超采样的 id 图。里面坐着扁平可爱的角色:小斗篷角色、一罐萤火虫、一只四片的风筝,风筝线跟着天色从深变银。上面叠一层科学图版的语言:3 倍图上画的细墨线、排线、制图尺寸标注、比例尺和圆形的「detail a」放大图,再加逐个字母排的细手写体小写英文;最后是柔化、光晕、颗粒、梅紫色暗角和一道撕纸边 |对 Claude 说「claude绘图」「你自己画」「用代码画」,也可以指定画风。它会:1. **先定构图**:层次、焦点、留白,而且画面要图解内容本身;@@ -519,6 +539,8 @@ python3 examples/penwash_neighbours.py out.jpg --stages stages/ # 钢笔淡python3 examples/gouache_rainy_day.py out.jpg --stages stages/ # 复古水粉:雨天三人像python3 examples/bluebook_shared_umbrella.py out.jpg --stages stages/ # 蓝调绘本:借伞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/ # 暮色微缩绘本:夜的边上```### 作画要点(Claude 交图前逐条自查)@@ -604,6 +626,18 @@ python3 examples/jiangnan_spring_water.py out.jpg --stages stages/ # 江南园- 只有一只窄而竖的翅膀的飞鹭是一根羽毛;- 对岸一条发白的空带是一堵雾墙,要种满到水边。最后在受光的墙上加叶影、整体加一点光晕,印章要小。+- **干刷色块**:几块大色块撑起整张画,颜色守住海报的六七种;不勾线、不做渐变,形体全靠色块的边和叠压。纹理要「刷出来」而不是事后撒上去:每块在自己的笔刷坐标系里刷,鬃毛纹和干尾才顺着笔走;覆盖率只由接触压力和纸纹的齿决定;两侧几乎是直边,两端梳开。纸纹背后的噪声要平稳、能循环(白噪声模糊、循环边界):放大粗网格一阈值化就是一道道横档,像蜡笔排线;补零的纹理块边缘会空出整列。大背景色板用滚筒(平涂、成簇细点、只在两侧发干),用鬃毛条纹就像在下雨;压在深色上的实心东西(瓷碗)要用蘸满的笔(`load` > 1),不然深色从细点里透出来。长的笔道要打断成长短、明暗不一的短笔,不然外套成了条纹。小心看错:+ - 低压力的细笔是铁丝,皴擦带是一团灰雾,热气干脆不画;+ - 镜片里的暗色明显超过两成(0.45 那版),眼镜就成了墨镜;+ - 鼻子的暗面和脸颊一样深就不见了,暖色鼻头还会被看成嘴;+ - 小东西边上的干笔毛齿像速度线。+ 在空白的纸上放一个小朱红方块,印刷放到最后。+- **暮色微缩绘本**:先定夜度场,所有受光的东西都按它着色,黄昏和夜才是同一束光——白雏菊到夜里是月光蓝,不是灰;星星、萤火虫、灯和图版不受它影响。交界要经过淡紫、紫和靛蓝:补饱和度,但要轻,不然成了一堵霓虹墙;边界要像穹顶一样弧着压过来,别是一条直斜线;黄昏要够浅,云才看得出来。四芒星少而小,只放在夜深处。花坡交给透视:坡顶是色点、底边是整朵的花,远处的花沉进雾色,不然坡顶是一条又密又亮的带。有颜色的道具(风筝)放在夜度着色压不灰的地方。小心看错:+ - 天上一条条连续的细线是电线,不是云——云是底部更平的柔和透镜;+ - 角色夕阳一侧一道硬的棕色条是一条带子,不是边光;+ - 饱和、对比强的拼布条纹像一面面旗;+ - 中间色调的标记圈落在珊瑚色风筝上就看不见了,标记圈和引线用深墨色。+ 放大图里标签不出圆片、数字不压线;`finish()` 在画第一笔之前调用,阶段快照才和成品一致。### 计划diff --git a/SKILL.md b/SKILL.mdindex a3a74f6..047909f 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(细笔园林春景,数字水粉插画:成千上万片叶形小笔触按一个太阳堆出树冠,暗芯、亮边、一簇簇的高光;白色和淡粉的繁花是一簇簇圆点花瓣,枝条从缝里露出来;垂柳是一绺一绺发丝般的细枝挂满小叶;黛瓦飞檐是真的瓦垄:筒瓦板瓦一行行、檐口瓦当滴水、翘起的翼角和卷起的脊头;粉墙月洞门、冰裂纹漏窗、翡翠绿槅扇和挂落、红灯笼、匾额;九曲石桥、石阶、小木船;碧绿湖面倒映岸上的一切,更柔、更暗,加涟漪和细竖纹;睡莲、白鹭;从前景花枝到雾里青山层层退远,墙上桥上落着叶影;最后一方小红印)。用户说「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 窗口、界面卡片、讲解片界面页、小图标探头、阅卷、阅卷批改、批改、判卷、改卷、改作业、答题卡、试卷、考卷、测验卷、红笔批改、红笔打分、打分数、盖章批改、朱红印章、标准答案卡、长尾夹、讲解片评测 / 打分页、皮影、皮影戏、影子戏、驴皮影、灯影戏、皮影人偶、雕花戏台、戏台牌匾、亮相、钢笔淡彩、淡彩、淡彩速写、钢笔淡彩小人、针管笔、勾线笔、针管笔加水彩、线稿上色、速写卡片、速写本小人、水彩小卡、城市速写、街头速写、水笔、自来水笔、复古水粉、水粉、水粉画、不透明水粉、哑光丙烯、复古绘本、绘本插画、绘本大头像、童书插画、复古童书、大头像、大鼻子人物、针织毛衣、麻花毛衣、毛线帽、毛毡帽、卷发、胡子、蓝调绘本、蓝色绘本、软蓝绘本、蓝调童书、软蓝童书插画、蓝色童书插画、蓝色系绘本、限色绘本、蓝白绘本、现代绘本跨页、手绘绘本跨页、绘本跨页、绘本内页、干笔墨线、墨铅笔线、粉彩蜡笔质感绘本、白色毛绒动物、毛绒白熊、点彩腮红、江南园林、园林春景、春水园林、中式园林插画、古典园林插画、国风园林插画、苏式园林、细笔园林、园林风景插画、水榭、临水茶榭、亭台楼阁、粉墙黛瓦、黛瓦白墙、飞檐翘角、翼角起翘、月洞门、漏窗、冰裂纹窗、槅扇、挂落、九曲桥、曲桥、垂柳园林、碧水倒影、园林倒影、睡莲池、数字水粉风景、细腻厚涂风景),或 "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 without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。单独说「剪纸」指剪纸拼贴、「刺绣」指十字绣、「丝网印刷 / screen print」指包豪斯几何;「打马赛克」是打码,不是马赛克画风;单说「蓝图」指蓝图工程图,「蓝晒 / 晒图」仍指蓝晒;「铅笔 / 素描」指铅笔素描,「彩铅」指韩国彩铅;「像素」仍指像素风,「1-bit / 黑白画图软件」指 1-bit 早期画图软件;「霓虹」仍指赛博朋克;「喷漆 / 街头涂鸦」仍指喷漆模板涂鸦,「圆珠笔 / 随手涂鸦 / 页边涂鸦」指圆珠笔涂鸦;「描图纸 / 硫酸纸 / 叠片 / 灯箱」指描图纸叠层(蓝图工程图那张描图布是晒成蓝图的,不是叠片);「Dot 风 / 粉彩界面 / 窗口卡片 / 发布会界面」指粉彩界面(纯色底 + 白色实心窗口卡片),要磨砂玻璃和弥散渐变仍用弥散玻璃;「阅卷 / 批改 / 答题卡 / 判卷 / 红笔打分」指阅卷批改,实验记录里的红笔圈和便利贴仍用实验笔记本,带「已付」橡皮章的小票拼贴仍用贴纸拼贴 · 小票;「皮影 / 皮影戏 / 影子戏」指皮影戏(透光的彩色驴皮人偶),黑纸剪出的侧影小像仍用剪影,彩纸剪贴仍用剪纸拼贴。「钢笔淡彩 / 淡彩速写 / 针管笔加水彩 / 线稿上色的速写小卡」指钢笔淡彩;单说「水彩」仍指水彩(风景、花卉的大片晕染),蓝铅笔稿 + 毛笔线 + 赛璐璐阴影的拟人小物仍用卡通手绘,「素描 / 铅笔」仍指铅笔素描。「水粉 / 复古水粉 / 绘本大头像 / 复古童书插画」指复古水粉(不透明水粉画的特写大头像);梵高式厚涂的风景、名画感仍用油画厚涂,扁平矢量、会挤压拉伸的小角色动画(「绘本动画」)仍用绘本角色动画,针管笔线稿加淡彩的速写小卡仍用钢笔淡彩,撞色多格的头像仍用波普丝网。「蓝调绘本 / 软蓝绘本 / 蓝色童书插画 / 绘本跨页」指蓝调绘本(软蓝限色的现代绘本跨页:干笔墨线 + 干蜡笔粉彩上色 + 白粉笔痕);单说「绘本」仍指绘本角色动画,「水粉 / 绘本大头像」仍指复古水粉,「编辑风 / 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」放大图,细墨线、排线、尺寸标注、标签和比例尺,几行灰色的小写英文手写字;最后是细颗粒、光晕、暗角和底边一道撕纸边)。用户说「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 without an image model" 时使用;也用于需要逐步画出(draw-on)动画的插画。单独说「剪纸」指剪纸拼贴、「刺绣」指十字绣、「丝网印刷 / screen print」指包豪斯几何;「打马赛克」是打码,不是马赛克画风;单说「蓝图」指蓝图工程图,「蓝晒 / 晒图」仍指蓝晒;「铅笔 / 素描」指铅笔素描,「彩铅」指韩国彩铅;「像素」仍指像素风,「1-bit / 黑白画图软件」指 1-bit 早期画图软件;「霓虹」仍指赛博朋克;「喷漆 / 街头涂鸦」仍指喷漆模板涂鸦,「圆珠笔 / 随手涂鸦 / 页边涂鸦」指圆珠笔涂鸦;「描图纸 / 硫酸纸 / 叠片 / 灯箱」指描图纸叠层(蓝图工程图那张描图布是晒成蓝图的,不是叠片);「Dot 风 / 粉彩界面 / 窗口卡片 / 发布会界面」指粉彩界面(纯色底 + 白色实心窗口卡片),要磨砂玻璃和弥散渐变仍用弥散玻璃;「阅卷 / 批改 / 答题卡 / 判卷 / 红笔打分」指阅卷批改,实验记录里的红笔圈和便利贴仍用实验笔记本,带「已付」橡皮章的小票拼贴仍用贴纸拼贴 · 小票;「皮影 / 皮影戏 / 影子戏」指皮影戏(透光的彩色驴皮人偶),黑纸剪出的侧影小像仍用剪影,彩纸剪贴仍用剪纸拼贴。「钢笔淡彩 / 淡彩速写 / 针管笔加水彩 / 线稿上色的速写小卡」指钢笔淡彩;单说「水彩」仍指水彩(风景、花卉的大片晕染),蓝铅笔稿 + 毛笔线 + 赛璐璐阴影的拟人小物仍用卡通手绘,「素描 / 铅笔」仍指铅笔素描。「水粉 / 复古水粉 / 绘本大头像 / 复古童书插画」指复古水粉(不透明水粉画的特写大头像);梵高式厚涂的风景、名画感仍用油画厚涂,扁平矢量、会挤压拉伸的小角色动画(「绘本动画」)仍用绘本角色动画,针管笔线稿加淡彩的速写小卡仍用钢笔淡彩,撞色多格的头像仍用波普丝网。「蓝调绘本 / 软蓝绘本 / 蓝色童书插画 / 绘本跨页」指蓝调绘本(软蓝限色的现代绘本跨页:干笔墨线 + 干蜡笔粉彩上色 + 白粉笔痕);单说「绘本」仍指绘本角色动画,「水粉 / 绘本大头像」仍指复古水粉,「编辑风 / Riso」仍指编辑风手绘,针管笔线稿加淡彩的速写小卡仍用钢笔淡彩,小孩自己画的蜡笔画仍用儿童蜡笔画。「江南园林 / 园林春景 / 中式园林插画 / 粉墙黛瓦 / 飞檐 / 月洞门 / 九曲桥」指江南园林(细笔数字水粉的园林春景:叶形小笔触堆出的繁茂树冠、繁花、垂柳、黛瓦飞檐、碧水倒影、层层远山);单说「水墨 / 山水」仍指水墨,单说「水彩」仍指水彩,动漫背景 / 赛璐璐天空仍指日本动漫,浮世绘仍是浮世绘;梵高式厚涂的风景仍用油画厚涂,皮影人偶的一场戏仍用皮影戏。「干刷色块 / 干笔色块 / 滚筒色块 / mid-century 海报插画」指干刷色块(米白纸上几大块干笔或滚筒刷出的限色色块,人物拆成几个大块面,背后一块纯色板、一旁一个小红方块);单说「水粉 / 绘本大头像」仍指复古水粉,「剪纸 / 彩纸拼贴」仍指剪纸拼贴,「丝网印刷 / screen print」仍指包豪斯几何,「Riso / 编辑风」仍指编辑风手绘,没有笔触的平滑几何色块仍用扁平矢量。「暮色微缩绘本 / 暮色绘本 / 黄昏转夜 / 昼夜交界 / 野花坡 / 细节放大图」指暮色微缩绘本(粉彩黄昏转入银河夜空、拼布山丘、几万朵小野花、很小的原创角色,加圆形放大图和手写小字);单说「绘本」仍指绘本角色动画,「蓝调绘本 / 软蓝绘本」仍指蓝调绘本,赛璐璐天空和夏日少年感仍用日本动漫,大片晕染的风景仍用水彩,整页的机械分解手稿仍用达·芬奇手稿,剖面和施工图仍用蓝图工程图。---# Claude 绘图@@ -81,6 +81,8 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型| 复古水粉 · Retro Gouache | `lib/gouache.py` · `GouachePortrait` | `examples/gouache_rainy_day.py` 雨天三人像 · Rainy-Day Portraits(米色画板上并排三幅竖长的绘本大头像,每幅一块刷出来的单色背景:浅海玻璃绿底上的老渔夫,黄色防水雨帽上还挂着雨珠、帽檐尖上吊着一滴水,巨大的红鼻子、白色浓眉、大耳朵、一圈白色下巴胡子,藏青麻花毛衣配罗纹领,胸前毛毡口袋里探出一条银色小鱼、张着「O」字嘴,他眯着眼往下看它;绿底上被一顶巨大的芥末黄毛线帽和红白条纹围巾埋住的小孩,橙色大绒球,两只毛线手套捧着一杯冒热气的可可,杯里漂着两块棉花糖,他盯着棉花糖看成了斗鸡眼;蓝到黄渐变底上的高个女士,橙色小卷堆成一座高塔发型,蓝眼影、珍珠耳坠、红色高领、钴蓝大衣配青绿毛毡翻领,斜眼瞟着爬上她肩膀的蜗牛,蜗牛身后的大衣上还有一道发亮的黏液;不透明水粉从暗到亮:托底色、赭色起稿、背景干笔皴擦、平涂大块、几阶色值塑形(鼻子、脸颊、帽子)、帽檐和鼻子下的软投影、粉状腮红、V 字平针与麻花、罗纹、一根根发丝和胡子、毛毡、受光处的干笔高光,最后是印刷书页的纸纹;`--stages` 出 8 个阶段:托底色、起稿、背景、平涂、塑形、质感、五官与道具、高光) | 约 7 秒(成品)/ 约 8 秒(含阶段) || 蓝调绘本 · Blue Picture Book | `lib/bluebook.py` · `BlueBook` | `examples/bluebook_shared_umbrella.py` 借伞 · The Shared Umbrella(软蓝雨天里的一张绘本跨页,背景蓝块毛边、不到纸边:左页是一个小小的公交站,玻璃候车亭里的长椅空着,只有一只蜗牛独占整条干燥的长椅,旁边是画着小巴士的圆站牌、亮着芥末黄灯的路灯,路灯下的大水洼里一只鸭妈妈带着两只小鸭玩得正欢;右页一个穿钴蓝雨衣、扎两个珊瑚红小揪揪的小女孩,双臂伸到最高,把一把珊瑚红小伞举向一只巨大、害羞、毛茸茸的白熊——伞只遮住了它的鼻子,雨落在它的耳朵和头顶,也落在小女孩自己的头发上,她一点也不在意,仰着头冲它笑;白熊低头看着自己并在一起的爪子,脸红了;水洼里映着一点红伞,蓝黑乱线的灌木里开着几朵珊瑚红小花;照绘本画家的顺序:空白纸、蓝色色块(天空块、雾里的远树、灌木、雨衣、候车亭、水洼)、松的墨线(线不闭合、偶尔描两遍)、乱线排出的暗部、珊瑚红点缀和点彩腮红、白粉笔(云、白毛、水纹、玻璃反光)、雨丝 / 水花 / 甩点 / 细尘,最后印在书上(中缝、页码、印刷的柔化);`--stages` 出 7 个阶段加成品:空白纸、蓝色色块、墨线、暗部、点缀色、粉笔白、雨) | 约 5 秒 || 江南园林 · Jiangnan Garden | `lib/jiangnan.py` · `JiangnanGarden` | `examples/jiangnan_spring_water.py` 春水园林 · Spring Water Garden(一幅横幅的江南园林春景,从前景的花枝和柳丝之间望进去:画面中间是一池碧绿的春水,岸上的一切都倒映在里面,更柔、更暗,带涟漪和细竖纹;一座带镂空石栏板的九曲石桥折了三折,穿过水面通向一道粉墙,墙上的月洞门里露出另一个洒满阳光的小院(竹子、粉色花树、一块湖石、远处又一道白墙),旁边一扇冰裂纹漏窗,墙上落着叶影;粉墙旁是一座临水茶榭,黛瓦歇山顶、翼角高高翘起、脊头卷起,翡翠绿的槅扇门和灯笼锦窗、檐下挂落、一对红灯笼、一块写着「听雨」的小匾,台基上几盆花;茶榭右边一棵开满白花的树下,一条小木船系在石阶边;左岸一棵大垂柳,墙后一棵层层托盘的松树和一片深浅不一的树冠,再后面是雾里的青山;近处水面上一丛丛睡莲叶和几朵粉色睡莲,一只白鹭站在水中的石头上,另一只从松树前掠过;前景左下是深绿的灌木、白色小花和弯弯的鸢尾叶,右下一丛粉色杜鹃,左上垂下几缕近处的柳丝,右上一枝粉色花枝,花瓣在空中飘、在水面上漂;右下角一方小红印「春水」;照风景插画家的顺序从后往前画:天空和远山、远树和雾、建筑、对岸的园子、水和倒影、桥和船、睡莲和白鹭、前景草木、垂挂的画框,最后是印章和收尾的柔化、光晕、颗粒;`--stages` 出 9 个阶段加成品:天空和远山、远树、建筑、对岸、水、桥和船、睡莲和白鹭、前景、画框) | 约 6 秒 |+| 干刷色块 · 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 秒 |各画风共用 `lib/core.py` 里的底层工具:噪声、模糊、样条曲线、多边形遮罩、有机轮廓 `blob_pts`、毛笔 `bristle_stroke`、中文字体查找;新四种还用到补零平移 `shift`、文字遮罩 `text_mask`、西文字体查找 `latin_font`/`load_font`,以及高度图打光 `height_normals`、`height_shadow`(沿光线步进的投影)、`ambient_occlusion`。@@ -151,7 +153,9 @@ description: Claude 绘图 / Claude Drawing —— 不借助任何生图模型- 人物小品、街坊邻居与日常小事(送信、浇花、骑车、买面包)、一组角色卡 / 人设卡、旅行和城市速写里「一个人在做一件小事」、轻松幽默的配图,讲解片里「一组用户 / 角色 / 团队成员」的介绍页 → 钢笔淡彩(要蓝铅笔稿、毛笔线和赛璐璐阴影的拟人小物用卡通手绘;要风景和花卉的大片晕染用水彩;要真的动起来的角色用绘本角色动画;要草稿纸上的随手涂鸦用圆珠笔涂鸦);- 人物大头像、角色特写、一组人设的「封面像」、温暖怀旧的复古童书 / 绘本插画,要有摸得着的手感(毛衣针脚、毛线帽、胡子和卷发、毛毡),讲解片里「这个人登场」的特写页 → 复古水粉(要线稿加淡彩、「一个人在做一件小事」的速写小卡用钢笔淡彩;要真的动起来的扁平小角色用绘本角色动画;要梵高式厚涂的风景用油画厚涂;要撞色多格的头像用波普丝网);- 温柔又好笑的小故事、绘本跨页或内页、童书封面和插页、「一个小角色帮另一个」这类有情节的一幕,下雨、下雪、夜晚这类安静的天气,要一眼就是「手画的现代绘本」,颜色只要一种主色(软蓝)加一点点睛色 → 蓝调绘本(要单人特写大头像、看得见毛衣针脚用复古水粉;要速写小卡上的针管笔线稿加淡彩用钢笔淡彩;要真的动起来的扁平小角色用绘本角色动画;要小孩自己画的蜡笔画用儿童蜡笔画;要网点和套色的观点插画用编辑风手绘);-- 中国古典园林、江南春景、亭台楼阁和水、旅行与城市文化里的「园林 / 古镇 / 春天」,节气和节日(春分、清明、谷雨)的配图和海报,要繁茂、细腻、一眼就是「精心画出来的插画」的风景,讲解片里的「中国传统 / 生活美学 / 春天」页 → 江南园林(要留白的写意山水用水墨;要大片松散的晕染用水彩;要赛璐璐天空和夏日少年感用日本动漫;要木版套色和海浪用浮世绘;要皮影人物的一场戏用皮影戏)。+- 中国古典园林、江南春景、亭台楼阁和水、旅行与城市文化里的「园林 / 古镇 / 春天」,节气和节日(春分、清明、谷雨)的配图和海报,要繁茂、细腻、一眼就是「精心画出来的插画」的风景,讲解片里的「中国传统 / 生活美学 / 春天」页 → 江南园林(要留白的写意山水用水墨;要大片松散的晕染用水彩;要赛璐璐天空和夏日少年感用日本动漫;要木版套色和海浪用浮世绘;要皮影人物的一场戏用皮影戏);+- 人物和日常小场景(吃一碗面、喝茶、做手艺、街坊小店)、杂志 / 书籍 / 唱片的复古封面、餐饮和饮品海报,要「色少而准、有手感、有态度」的编辑插画和 mid-century 海报感,讲解片里「这个人 / 这家店 / 这一口」的特写页 → 干刷色块(要剪刀剪的彩纸童趣用剪纸拼贴;要不透明水粉一层层塑形的大头像用复古水粉;要 Riso 网点和套色错版用编辑风手绘;要三原色几何的丝网海报用包豪斯几何;要干净、没有笔触的矢量色块用扁平矢量);+- 温柔、怀旧、带一点点孤独的小故事和情绪(「一天结束了」「出发」「再走一点点」),晚安故事、童书封面和插页,季节和节日的夜晚(夏夜、萤火虫、星空、七夕、中秋),原创小角色或吉祥物的「远方」主视觉,要在一张画里同时放「风景 + 一个零件 / 一个结 / 一处构造的放大图 + 手写小字」的讲解页 → 暮色微缩绘本(要软蓝限色、乱线墨线的绘本跨页用蓝调绘本;要真的动起来的小角色用绘本角色动画;要赛璐璐天空和夏日少年感用日本动漫;要大片松散晕染的风景用水彩;要整页的机械分解手稿用达·芬奇手稿)。每种画风一幅范例作为质量基准(范例都不用禅意主题);水墨另加一幅「月印万川」(留白托月、水面倒影)。@@ -1136,6 +1140,46 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 收尾:`seal(x, y, w, h, text)`;`grain(amount)`;`render()`、`composite()`、`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度。- 颜色用 `PAINTS` 里的名字(sky sky_low haze cloud plaster coral jade jade_dark jade_light lacquer beam interior paper stone tile board gold wood lantern seal bark bark_light water water_deep water_far terracotta porcelain egret)或 '#rrggbb';色阶用 `RAMPS` 里的名字(spring jade deep olive willow far white pink azalea tile stone rock pad)或自己给一串颜色;常量 `LIGHT`。+**干刷色块 `DryBrushBlocks`**:+- 思路:照参考海报的做法,先铺最大的色块,再用几块面拼出人物,最后是细节和一个小红方块;不勾线、不做渐变,形体全靠色块的边和叠压。+ - 笔刷坐标系:每块颜色在自己的坐标系里刷:把遮罩(Pillow)旋转到笔触方向沿 +u,在里面用横平竖直的数组算覆盖率、明暗和混色,再转回去,所以鬃毛纹、笔道和干笔收尾永远顺着笔走。+ - 纹理:每张画布只生成一次几张周期纹理,每块颜色取随机位置的一窗:鬃毛条纹(沿笔长约 40 px、横向 1–3 px);干笔齿(鬃毛条纹 + 更粗的拖痕 + 纸纹,直方图均衡到 0..1,于是「齿 > 1 − 接触压力的地方上色」直接把压力变成覆盖率);滚筒齿(成簇的各向同性细点);梳齿边的噪声;笔道明暗;拉长的斑驳。噪声都是白噪声按方向模糊(循环边界)得来的,不是放大粗网格。+ - 笔道:大色块是一道道平行的宽笔或滚筒(`lane` 宽,每道略宽略窄),每道起笔饱满、往收笔越来越干,各干各的(`dry`、`dry_from`);`stroke_len` 把每道打断成长短不一、各有明暗和干尾的短笔;`passes=2` 再盖一层,块身合拢、两端仍是毛的;`direction` 定走向(+1 / −1 同向、0 随机、2 来回)。+ - 边:横向只稍微柔化(`side`,两侧是略抖的直边),顺笔方向柔化很多(`fringe`),再拿鬃毛纹阈值化:两侧近乎直,两端梳成长短不一的毛齿,干的一端更长(`tines`),毛齿只从柔化带里长出来。+ - 皴擦:斑驳高的地方接触压力下降(`scumble`),颜料只挂在纸纹的齿上,露出纸色或下层颜色;`edge` 是沿轮廓几段干擦的边,只放在顺笔的两侧。`load` 大于 1 是蘸满的笔,快干的地方也照样实(瓷碗)。+ - 叠色:默认不透明水粉(新 = 旧 + (颜色 − 旧) × 覆盖率),干笔扫过另一块颜色时下层从缝里透出来;`mode='multiply'` 像丝网油墨套印(玻璃杯、茶);`mix=(颜色, 比例)` 让同一支笔里带第二种颜色的条纹。+ - 收尾 `printed()`:像这幅画的胶印:轻微柔化、细纸纹、暗部零星的纸色白点、纸上零星的灰尘(在 render 里加)。+- 构造:`DryBrushBlocks(W, H, seed, keep_stages=True, stages_dir=None)`(总像素不超过 4096²);`paper(tone)` 铺米白纸并生成纹理。画布坐标是像素,角度是度(0 向右、90 向下)。+- 形状(画布大小的浮点遮罩):`rect(x0, y0, x1, y1, rot)`、`poly(pts, smooth)`、`ellipse(cx, cy, rx, ry, rot)`、`tube(path, w0, w1)`、`quad(pts)`。+- 色块:`slab(shape, colour, angle, load, dry, lane, fringe, side, tines, scumble, streak, vary, direction, passes, seam, edge, stagger, dry_from, stroke_len, tooth='brush'|'roller', mix, mode, alpha, avoid, clip)` 返回覆盖率,shape 可以是遮罩、(x0, y0, x1, y1) 或多边形点;`piece(shape, colour, torn, cut, rim, …)` 撕 / 剪的纸片:只有一部分轮廓是撕口(`cut` 是留作直切的比例),撕口可带一圈浅色纤维边;`backdrop(box, colour, angle, rough, scratches)` 主体背后的滚筒大色板(几乎平涂、成簇细点、起笔边干净、干的两侧、几道细刮痕);`accent(x, y, size, colour, rot)` 小方块(x, y 是左上角);`scratches(mask, colour, n, length, width)`。+- 笔:`stroke(path, width, colour, load, dry, taper, wobble, square, mode, alpha, clip)` 沿路径的一笔干刷(每个像素都知道自己的弧长和横向偏移,纹理顺着曲线走,扁笔头、越画越干);`scumble(mask, colour, n, length, width, angle, spread, load, dry)` 在遮罩里撒短干笔(胡子、头发、高光),angle 可以是函数 f(x, y)。+- 人物:`head(cx, cy, w, h, tilt, turn, light, skin, lit, shade, warm, ear, hair, crown)` 返回锚点字典(眼睛、鼻子、嘴、下巴和遮罩);`glasses(head, colour, lens, frame)`;`beard(head, colour, shade, length, width)`;`jacket(neck, shoulders, bottom, lit, shade, dark, shirt, collar, light)`;`sleeve(path, w0, w1, colour)`;`hand(x, y, size, angle, grip, cuff)`。都在局部单位坐标里(中心、大小、倾斜),一个姿势就是几个数;`light=-1` 是光从观者左边来。+- 器物:`bottle(x, base, w, h, colour, shoulder, neck, neck_w, dark, light, label, label2, cap, glass)`;`bowl(cx, rim_y, w, h, colour, band, inside, shade)` 返回(碗身, 碗口里面);`cup(cx, base, w, h, colour, glass, level, tea)`。+- 收尾:`printed(amount)`;`render()`、`composite()`、`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度。+- 颜色用 `PAINTS` 里的名字(paper cream bone white ink black forest green slab sage leaf ash celadon mint khaki teal lagoon tealblue navy deep sky ice vermilion tomato coral blush ochre tan skin skin_light terracotta umber brown mustard)或 '#rrggbb'。++**暮色微缩绘本 `TwilightStorybook`**:+- 思路:照绘本的顺序画:黄昏天空 → 夜 → 山 → 花坡 → 角色和风筝 → 发光的东西 → 图版和手写字;先定一块「夜度」场,后面受光的东西都按它着色。+ - 黄昏天空:六段渐变(薰衣草紫 → 丁香 → 玫瑰 → 蜜桃 → 杏 → 金,按地平线定位),分段位置被横向拉长的低频噪声扰动,颜色是一层层软的,不是尺子拉的直色带,再叠几个百分点的细斑驳。云是透镜形的带:一条扁透镜加几团圆块(中间高),轮廓模糊,底部更平更清,越往下越浓,半透明;云下有细光线;太阳是带两层光晕的淡圆,先于山画,山把它切掉。+ - 夜:`night_split()` 由一条游走的边界线定出整幅画的夜度场 N(0 黄昏 – 1 夜),过渡带很宽、带羽化;夜空渐变、银河、星星、月亮都按 N 当透明度铺上去,星星越过边界慢慢变稀、变淡,不会停在一条线上;靠近边界时夜色偏靛蓝,交界带再补饱和度(`richness`),黄昏 → 淡紫 → 靛蓝 → 黑,不发灰。+ - 之后所有「受光」的东西(山、花草、人物)都按同一个 N 着色:颜色经一个 3×3 线性变换(先降饱和、再偏冷)按 N 混过去,白雏菊在夜的一侧成了淡淡的月光蓝,草成了深石板色。自发光的(星星、萤火虫、灯、流星)和图版放在 `with t.unlit():` 里画,不受影响。+ - 银河:两点之间、带弯曲和游走中心线的解析带,密度是横截面的高斯 × 两个尺度的云状噪声,中间一条更窄的暗带;几千颗暗星按带的密度抽样。星星:均匀位置、幂律亮度(多数暗、少数亮),少数偏暖或偏蓝,亚像素精度地溅到画布上(大星用圆盘覆盖核,小星用保质量的高斯,bincount 累加);最亮的几颗加四芒星(长的渐细光芒加短对角线),只放在夜深处、离地平线远的地方。+ - 山:远山是填充的山脊(每列解析抗锯齿的边),越往山脚越淡(谷里积雾);条纹山丘是顺着山脊的一层层带,越近越宽(透视),每条带切成斜的拼布田,部分田有平行的细垄,带与带、田与田之间一道深一点的树篱线,坡顶一道淡亮边;`trees()` 放小圆树(影子、树干、树冠、左上亮面)。+ - 花坡:地面是鼠尾草绿到橄榄绿的渐变加斑驳和细点,坡顶一道亮边(越过交界从金变银)。花和草按透视用拒绝采样放:大小随离坡顶的深度按幂次增长(默认 t²),密度 ≈ 覆盖率 / (π · 大小²),所以坡顶是几千个色点、最底下是几十朵大花;花种按低频噪声成片漂移(一片雏菊、一片矢车菊);远处的花沉进带雾的地色。按大小是一个色点、一朵带花心的小花或一朵完整的花头(雏菊、矢车菊、虞美人、波斯菊、金盏花、毛茛、羽扇豆、勿忘我),各有细茎,大的带一片叶;花头按透视压扁,朝后的花瓣先画。所有多边形按根部的 y 排序,一次光栅化进超采样的整数 id 图(画家顺序 = id 顺序),查色表再缩回来,几万个抗锯齿形状不到一秒。+ - 角色:扁平可爱的绘本角色,用平滑多边形拼:`wanderer()` 是坐着的小斗篷角色(毡子质感的斗篷、软塌的帽尖和绒球、奶油色圆脸、带高光的点点眼、腮红、手套和靴子,夕阳一侧一道暖色柔边,一圈断续的深色细轮廓);`jar_lantern()` 是一罐萤火虫,会发光、照亮周围的草;`kite()` 四片的菱形风筝,有骨架、提线和一串蝴蝶结尾巴;`kite_string()` 略下垂,跟着身后的天空从深(黄昏)变银(夜)。`fireflies()`、`butterfly()`、`dragonfly()`、`seeds()`(蒲公英种子)、`birds()` 是留给细看的小东西。+ - 图版:细墨线在 3 倍图上画成折线(略带手抖、可渐细)再缩回来,0.8 px 的发丝线也是平滑的;`hatch()` 在形状里排平行的手绘线(换个角度再调一次就是交叉排线),`dimension()` 画延伸线、带建筑式斜短线的尺寸线和小标签(`across=True` 横跨一根伸出画外的杆件,引到外面写「ø 6」这类),`ruler()` 小比例尺,`wash()` 平的水彩底色加一道深边;`inset()` 是圆形放大图:带淡阴影的纸圆片、裁在里面的 `draw(t, cx, cy, r)` 回调、细双圈、目标上的标记圈和引线、标签。+ - 手写字:细手写体(macOS 上是 Noteworthy Light,或设 `INKPAINT_FONT_HAND_LIGHT`)逐个字母排:每个字母各有一点旋转、基线起伏、间距和轻重,在 2 倍图上画再缩小,叠一层淡淡的铅笔纹。+ - 收尾 `finish()`:轻微柔化、亮处光晕、细颗粒加大一点的柔和斑驳、偏梅紫的淡暗角,可选底边一道米色撕纸边;只记参数、在 render 里加,所以在画第一笔之前调用,每张阶段快照都和成品一致。+- 构造:`TwilightStorybook(W, H, seed, keep_stages=True, stages_dir=None)`(总像素不超过 4096²);`with t.clipped(mask):` 只画在遮罩里(放大图里面),`with t.unlit():` 不受夜度着色。画布坐标是像素;角度除注明外用弧度(`hatch()` 用度)。+- 底层:`lines(paths, width, colour, alpha, wobble, taper)`;`fill(mask, colour, alpha)`;`shapes(polys, colours, alpha)`;`poly(pts)`、`ellipse(cx, cy, rx, ry)` 返回遮罩;`glow(x, y, r, colour, strength)`;`splat(xs, ys, rad, colours, alpha)`。+- 天空:`dusk_sky(stops, horizon, mottle)`;`cloud(x0, x1, y, h, colour, alpha)`;`streak(x0, x1, y)`;`sun(x, y, r)`;`mist(y0, y1, y2, colour, strength)`;`birds(pts, size)`;`seeds(pts, size)`。+- 夜:`night_split(edge, soft, ground)`(edge 是从上到下的折线,夜在它右边;在 `dusk_sky()` 之后调);`night_sky(top, low, indigo, richness)`;`milky_way(p0, p1, width, bend, rift, stars)`;`stars(n, region, sparkles, dusk)`;`sparkle(x, y, size)`;`moon(x, y, r, phase, tilt)`;`shooting_star(p0, p1)`。+- 地面:`hills(ridge, colour, base, fade, rim)`;`striped_hill(ridge, colours, stripe, grow, fields, rows, hedge)` 返回 info(ridge、bounds,用来放树);`trees(pts, size)`;`meadow(crest, size, density, grass, kinds, drifts, haze)` 返回 info(crest);`grass_heads(x0, x1, base, n, height, lean)` 坡顶衬着天空的带穗高草。+- 角色和小东西:`wanderer(x, y, s, facing, reach)` 返回手的位置;`jar_lantern(x, y, s)`;`kite(cx, cy, size, tilt, tail)` 返回提线结的位置;`kite_string(p0, p1, sag)`;`nightline(path, width)` 跟着天色变色的细线;`fireflies(pts, size, trails)`;`butterfly(x, y, s, colour)`;`dragonfly(x, y, s)`。+- 图版和字:`hatch(shape, angle, spacing, width)`;`dimension(p0, p1, text, offset, across, lead)`;`ruler(x0, y, x1, labels)`;`wash(pts, colour)`;`leader(p0, p1)`;`inset(cx, cy, r, draw, target, label, sub, leader_colour)`;`caption(x, y, text, size, colour, anchor, rot)`。+- 收尾:`finish(grain, vignette, bloom, soft, edge)`;`render()`、`composite()`、`stage(name)`、`save(path, stages_dir)`;`save('x.jpg')` 默认 quality 88、4:4:4 色度。+- 颜色用 `COLOURS` 里的名字(天空 lavender lilac rose peach apricot gold sun cloud cloud_low streak;夜 night night_low indigo star moon milk;地面 mauve mauve_dark haze rim silver meadow meadow_far meadow_near grass tree tree_light trunk field_sage field_lav field_wheat field_green field_rose;线和纸 ink pencil caption paper pale;花 daisy cornflower poppy cosmos marigold buttercup lupine forgetmenot eye stem;角色 cloak cloak_dark face cheek boot mitten kite kite_cream spar string lantern firefly glass)或 '#rrggbb';花种见 `SPECIES`。+**顺序**:都是先远后近、先大后小,文字最后叠加。水墨的雾要画在它该吞没的东西之后;水彩的叶梗要先画,并且只画在叶子外面。## 三、毛病清单(都真实出现过)@@ -2203,6 +2247,51 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask| 所有树都一个样 | 墙后加一棵托盘松(针叶用细叶片、几乎不下垂);前景加白色小花和弯曲、带受光边的鸢尾叶(原来是直挺挺的绿刺) || 墙和水面太干净,像矢量图 | 墙上叠一层淡笔触(alpha 0.6,明暗浮动 −3.5% 到 +2.5%);收尾加轻微柔化、亮部光晕、暗部偏青 |+**干刷色块**++| 问题 | 改法 |+|---|---|+| 色块里全是垂直于笔触的「梯子横档」,像蜡笔排线,不像干笔 | 各向异性噪声原来是把粗网格放大,格点对齐的列一阈值化就成横档:改成白噪声按方向模糊(沿笔方向在 1/f 分辨率上做再拉回去);干笔齿改成鬃毛条纹 + 粗拖痕 + 纸纹的混合,干掉的地方才是成簇、宽窄不一的点,不是发丝线 |+| 某些位置空出一整列 | 一维模糊用补零边界,纹理块边缘变暗,色块或绕回的笔触碰到边缘就空一列:纹理改用循环边界 |+| 弯的笔触上还是有横档 | Pillow 的粗线 `line()` 把线段方向量化了,约六成像素记到了错的线段上:改成每段一个垂直于线段的浮点四边形加圆形接头,再修半像素偏移(中位偏差 −0.7 px) |+| 笔触末端一圈圈同心环 | 末端的纹理坐标被钉死:让纹理沿弧长一直延伸过笔端;干笔开始得更晚(`dry_from`),起笔更钝、更饱满 |+| 毛齿伸得太远,拖出一根根长尾巴 | 毛齿只从柔化带里长出来,块身的皴擦也减轻 |+| 外套是一条条整齐的平行条纹,近看像排线 | 每道笔打断成长短不一、各有明暗的短笔(`stroke_len`);暗的一半几乎实色(`load` 1.02),暗半边上拖过的藏青笔 4 → 3 笔;亮暗两半朝不同方向刷 |+| 第一版有一块颜色是 NaN | 酱油瓶传了 `dark=None`,混色时拿它去算:没有 dark 就不混 |+| 帽子像毛线帽,胡子像巫师的山羊胡,碗又小又扁 | 换成平头白发(顶上和鬓角干笔皴擦,暗侧另一种颜色)、更宽更短的白胡子、更大更深的碗 |+| 白发太高,像一顶发套 | 头发轮廓的顶往下压(−1.12 → −1.06);交付时白发仍有一点发套感 |+| 热气是一根根细铁丝,改成皴擦带后又是一团灰雾 | 低压力的笔只碰到几行长齿,所以成了线;最后去掉热气 |+| 背景大色板像在下雨,满是竖向条纹 | 两遍原来共用同一窗纹理,缝对着缝:每一遍取自己的一窗;参考图那块是滚筒的平涂细点,不是鬃毛条纹:加 `tooth='roller'` 和 `scratches()`,`backdrop()` 默认用滚筒 |+| 背景色板干的细点落在起笔的顶边上 | 干擦的边按方向加权,只放在顺笔的两侧,起笔边保持干净 |+| 眼镜像墨镜 | 镜片里的暗色 0.45 → 0.22 |+| 近处的胳膊和外套混成一片 | 袖子改用藏青、混一点青蓝,和外套亮的那半分开 |+| 手先像面包、又像软木塞 | 改成从拇指一侧看:亮的手背、四条明暗交替的手指(最下面一条在暗部)、指间暗线、上面一根拇指、指节一笔干高光,手腕加一截米色袖口和袖子分开;交付时手仍是最弱的地方 |+| 碗边的干笔毛齿像速度线 | 碗身毛齿 14 → 5 px,色带 16 → 6 px |+| 瓷碗上有深色条纹,透出后面的黑外套 | 接触压力约 0.97 时纹理窗口的起伏留下约 7% 的空隙,压在深色上很显眼:`load` 允许大于 1(上限 1.08),碗身用 1.05 |+| 鼻子看不见,鼻头像嘴 | 脸颊暗面的边界往外推(0.18 → 0.34),鼻侧用更深的褐色,加一笔亮的鼻梁、更小的暖色鼻头和鼻下阴影 |+| 青蓝色块里的皴擦太花 | 皴擦 0.2 → 0.07,干笔推迟到每道的后段(`dry_from` 0.72–0.95) |+| `jacket(light=+1)` 直接报错 | 暗半边那几笔的 x 范围上下限写反了:改成按光的方向取暗半边 |++**暮色微缩绘本**++| 问题 | 改法 |+|---|---|+| 第一版天空里漏出 NaN | 云的包络 `sin(πu)` 在两端略小于 0,再开 0.55 次方:先截到 0..1 |+| 云是一条条细线 | 重写成透镜形:一条扁透镜加 4–5 团圆块(中间高),轮廓模糊,底部更平更清,上浅下浓 |+| 昼夜交界是一片灰雾 | 交界带补饱和度(`richness`),夜空靠边界的一侧偏靛蓝(靛蓝提亮),边界羽化的噪声尺度 90 → 170、幅度减半:黄昏 → 淡紫 → 靛蓝 → 黑 |+| 补了饱和度以后,交界成了一堵霓虹紫墙 | `richness` 0.9 → 0.5,靛蓝压回一点 |+| 昼夜边界是一条直的斜线 | 边界折线改成六个点的弧(夜像穹顶一样压过来),过渡带 150 → 185 px |+| 天空的薰衣草紫太深太艳,云融进天里 | 六个色标都提亮、降饱和;云色压暗一点,云顶往浅色混的比例 0.4 → 0.22 |+| 银河的暗带太弱 | 加一个更亮更窄的内核,暗带收窄、加深(`rift` 0.65 → 0.8);交付时银河仍偏烟雾、暗带仍比参考图弱 |+| 四芒星太多、太大,靠近交界和地平线也有 | 9 颗 → 6 颗,大小 9–17 → 7–13 px,只放在夜度 > 0.8、离地平线 180 px 以上的地方 |+| 远处坡顶的花是一条又密又亮的带 | 覆盖率改成越远越低(0.24 + 0.32 t,t 从坡顶 0 到底边 1),远处的花沉进带雾的地色(`haze`) |+| 风筝在深夜里,被夜度着色压成了灰蓝 | 风筝挪进交界带,珊瑚色才保得住 |+| 角色夕阳一侧的边光是灰的;改暖以后又成了一道硬的棕色带 | 边光用暖杏色,从轮廓往里 3 px、模糊 1.4 px、最多 0.6,越往下越淡 |+| 放大图的目标标记圈落在珊瑚色风筝上看不见 | 标记圈和引线固定用深墨色(`leader_colour`) |+| 放大图的标签越出圆片,尺寸数字压在线上 | `dimension()` 的数字按字的「上方」放到背离物体的一侧;横跨杆件的「14」还撞上提线:去掉,改成 `across=True` 的「ø 6」直径标注,引到杆件外面写 |+| 拼布条纹田像一面面旗 | 田的颜色降饱和、彼此更接近,山脊起伏加大,树篱线 0.45,底部渐隐 |+| 阶段快照没有颗粒、暗角和撕纸边,和成品对不上 | `finish()` 只记参数、在 render 里加,改到画第一笔之前调用 |+## 四、做成动画- 各画风都有 `stage(name)` 和 `save(path, stages_dir)`,按阶段依次淡入叠化,就是「一幅画被逐步画出来」。README 里的动图就是这样做的。@@ -2242,6 +2331,21 @@ from core import spline, curve, blob_pts, fbm1d, blur, polygon_mask- 调色板:第一帧(天空渐变和远山)给 40 色;200 色从和它不同的像素切(末帧 ×3),按满屏叶子和繁花的需要加权:绿色 ×2.5、白和浅色 ×2、其他饱和色(灯笼、睡莲、杜鹃)×3,满屏的绿才不出色带、白花不发灰;再留 14 色,其中 3 个是强制的深中性色(瓦缝、树皮、窗格空隙),另外 11 色只从末帧误差最大(> 16 级)的像素里切。- 固定 4×4 Bayer。和屏上已显示颜色差不到 7 级(叠化帧)或 4 级(关键帧)的像素沿用上一帧,末帧精确发送。- 结果:55 帧、14.75 秒、约 1.57 MB,按解码结果逐帧自检,末帧 p99 误差 18。+- 干刷色块的动图(脚本在 `claude_drawing/drybrush_work/make_gif_drybrush.py`):+ - 画幅:范例是 4:3(1600×1200),墙上的动图都是 16:9。不裁画面,用纸本身把画幅加宽:左右离颜料还有 130 px 左右的空白纸,把这条纸来回镜像铺出去,纸纹和印刷颗粒接得上、看不出接缝,再缩到 720×405(画面本身在中间占 540 px 宽)。+ - 阶段:空白米色纸 → 两块大色块(滚筒刷的绿色板、青蓝色块)→ 外套和袖子 → 头(几块肤色平面、鼻子、腮红、耳朵、平头白发)→ 眼镜、胡子、筷子、近处的手 → 静物(柜台、碗和面、扶碗的手、两个瓶子、一杯茶)→ 朱红小方块 → 印刷(成品)。每段 900 毫秒 + 5 帧叠化。+ - 调色板:第一帧几乎只有纸色,只给 12 色;230 色从和它不同的像素切(饱和 ×3、末帧 ×3);再留 12 色,其中 3 个是强制的深色(近黑的外套暗半边、眼镜框、柜台下沿的墨线),另外 9 色只从末帧误差最大(> 18 级)的像素里切。+ - 固定 4×4 Bayer。和屏上已显示颜色差不到 7 级(叠化帧)或 4 级(关键帧)的像素沿用上一帧,末帧精确发送。+ - 结果:43 帧、12.05 秒、约 0.38 MB(画面只占中间四分之三、四周多是纸,所以比别的小),按解码结果逐帧自检,末帧 p99 误差 17。+- 暮色微缩绘本的动图(脚本在 `claude_drawing/twilight_work/make_gif_twilight.py`):+ - 画幅:范例是 2000×1100(20:11),左右各裁 22 px(只有天空和花坡,宽度的 2.2%)成 16:9,再缩到 720×405。+ - 阶段:黄昏天空(渐变、云带、光线、淡日、飞鸟、蒲公英种子)→ 夜从右边进来(夜空渐变、银河、星星、弯月、流星)→ 山(远山、拼布条纹山丘、小圆树、小屋)→ 野花坡 → 小斗篷角色、萤火虫罐和风筝 → 萤火虫 → 放大图和两行手写字(成品)。颗粒、光晕、暗角和撕纸边在 render 里加,每个阶段都有。每段 900 毫秒 + 5 帧叠化。+ - 两大片渐变(黄昏天空、昼夜交界)最容易出色带。照前面的做法(各段中值切分 + 4×4 Bayer + Pillow 按调色板量化)出的第一版,交界处是一圈圈紫 / 粉 / 黄的等高线;交界带的像素到最近调色板色的距离 p90 有 13.6 级。改法:+ - 天空一起切 136 色:一份样本里放第一帧(只有黄昏天空)、夜改动的像素(交界带,即亮度 > 0.13 的部分 ×8,比纯黑重得多)和天空 → 夜那次叠化的中间帧(×0.5);黄昏和夜分开切时,两份调色板在交界处接不上,留下一块锯齿边的紫斑。其余 104 色从后面的阶段切(末帧 ×3、饱和 ×3),再留 14 色给末帧误差最大(> 14 级)的像素。每份都是中值切分后再做 10 步 k-means。+ - 不用 Pillow 的 quantize(palette=…),numpy 逐像素找精确最近色(同一张调色板,天空的 p90 误差 8 → 6)。+ - 8×8 Bayer:别处 ±2.4 级,交界带(夜改动过、又不是近黑的天空)加到 ±6.4 级,调色板再密也还差几级的地方靠它抹平。+ - 和屏上已显示颜色差不到 7 级(叠化帧)或 4 级(关键帧)的像素沿用上一帧,末帧精确发送。+ - 结果:37 帧、10.7 秒、约 0.87 MB,按解码结果逐帧自检,末帧 p99 误差 16;交界带模糊 1.5 px 后和原图比 p99 7 级。- 绘本角色动画的动图是真动画,不是阶段叠化:`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 遮罩按顺序显现。这个还没做成现成接口。@@ -2317,6 +2421,8 @@ lib/penwash.py 钢笔淡彩(冷压水彩小卡:受光纸纹、不直lib/gouache.py 复古水粉(托底色的画板与纸纹;不透明水粉:鬃毛条纹、越用越干、挂在纸纹上的干笔,湿笔带起底色;毛边;穹顶光照的几阶色值塑形与球体塑形;软投影、粉状腮红、干笔高光;圆眼、大鼻子、大耳朵;V 字平针、麻花、罗纹;顺着流向的发丝、胡子、绒球、卷发;毛毡;印刷书页的颗粒)lib/bluebook.py 蓝调绘本(直方图均衡的纸纹与 8 个方向拖开的纸纹;毛笔 / 墨铅笔线:手抖、落笔收笔、粗细起伏、笔毛含墨、越画越干、顺笔的干白道、不闭合的轮廓与再描一遍;之字乱线暗部、平行短排线、草叶;干蜡笔 / 粉彩 / 干水粉上色:错位、游走的边、干边、笔道、纸纹白点、半透明混色,墨线始终在上;毛边、不到纸边的背景色块;白粉笔;雨丝、水花、水纹、甩点、细尘;大圆脑袋、点点眼、点彩腮红、雀斑、扇贝形毛边和白毛;印刷:柔化、抬黑、中缝、页码)lib/jiangnan.py 江南园林(叶形小笔触的 id 图光栅化:Pillow 按序号填多边形、numpy 查色表、2 倍超采样;按团块穹顶光照取色的树冠:暗底、穿出轮廓的叶、成簇的高光、最亮的几笔;花簇按明暗排序的繁花树、五瓣花的近景花枝;一绺绺细枝的垂柳、托盘松、弯曲的鸢尾叶;网格反求 (u, v) 的歇山瓦顶:筒瓦板瓦、瓦当滴水、飞檐翼角、卷脊头、檐下阴影;粉墙、叶影、方格 / 灯笼锦 / 冰裂纹槅扇、挂落、月洞门和漏窗、石作、台阶、针孔相机投影的九曲桥;湖面、按岸线镜像的倒影、自带倒影的桥船白鹭、横向笔触、涟漪和细竖纹、睡莲;红灯笼、匾额、小红印;柔化、光晕、颗粒)+lib/drybrush.py 干刷色块(笔刷坐标系:遮罩转到笔触方向再算、再转回;周期的鬃毛条纹 / 干笔齿 / 滚筒细点 / 梳齿边 / 笔道 / 斑驳纹理;一道道平行的笔或打断的短笔:起笔饱满、收笔干枯、梳齿般的两端、近直的两侧、皴擦、顺笔两侧的干擦边、多遍覆盖、同笔混色、蘸满的笔;滚筒大色板和细刮痕;部分撕口带纤维边的纸片;沿路径的干笔和散撒的短干笔;几块面拼的人物:头、眼镜、白胡子、外套、袖子、手;瓶、碗、杯;朱红小方块;胶印收尾:柔化、纸纹、暗部白点、细尘)+lib/twilight.py 暮色微缩绘本(被噪声扰动成软层的六段黄昏渐变、透镜形云带、光线和淡日;羽化的夜度场:按它铺夜空、银河、星星和月亮,交界补饱和度,后面受光的东西按它压成月光蓝,发光的东西不受影响;解析的银河带和暗带、幂律星场、亚像素溅射、四芒星、弯月、流星;远山、拼布条纹山丘、细垄、树篱、小圆树;按透视拒绝采样的花坡:八种花和草叶,按根部排序一次光栅化进 id 图;小斗篷角色、萤火虫罐、风筝和随天色变色的风筝线、萤火虫、蝴蝶、蜻蜓、蒲公英种子、飞鸟、带穗高草;3 倍图上的细墨线、排线、尺寸标注、比例尺、淡彩、圆形放大图;逐字母抖动的手写小字;柔化、光晕、颗粒、暗角、撕纸边)examples/*.py 范例脚本;*.jpg 成品;drawing_*.gif 逐步画出的动图中文字体:自动找 Kaiti/Songti(macOS)、Noto CJK(Linux)、KaiTi/SimSun(Windows),或设 INKPAINT_FONT西文字体(后来新增的画风用):core.latin_font(style) 按 sans / sans_bold / rounded / script / hand / typewriter 等找系统字体,可用 INKPAINT_FONT_<STYLE> 指定;字体文件不要放进仓库diff --git a/examples/drawing_drybrush_noodle_counter.gif b/examples/drawing_drybrush_noodle_counter.gifnew file mode 100644index 0000000..bea92a9Binary files /dev/null and b/examples/drawing_drybrush_noodle_counter.gif differdiff --git a/examples/drawing_twilight_paper_kite.gif b/examples/drawing_twilight_paper_kite.gifnew file mode 100644index 0000000..8061fb6Binary files /dev/null and b/examples/drawing_twilight_paper_kite.gif differdiff --git a/examples/drybrush_noodle_counter.jpg b/examples/drybrush_noodle_counter.jpgnew file mode 100644index 0000000..3a5543cBinary files /dev/null and b/examples/drybrush_noodle_counter.jpg differdiff --git a/examples/drybrush_noodle_counter.py b/examples/drybrush_noodle_counter.pynew file mode 100644index 0000000..9735336--- /dev/null+++ b/examples/drybrush_noodle_counter.py@@ -0,0 +1,125 @@+"""Example (dry-brush blocks): 面馆 · Noodle Counter -- a mid-century poster / gouache-collage illustration.++An old man with cropped white hair, rough black glasses and a white beard, in a navy work jacket, bent over a bowl+of noodles at a small eatery counter: one hand lifts the noodles with chopsticks, the other steadies the bowl.+Behind him a big sage-green roller slab; to his right, on the same counter, a vinegar bottle, a soy-sauce bottle and+a glass of tea in front of a teal block. A small vermilion square sits off to the side on the cream paper.++Painted the way the reference works: cream paper -> big slabs (green backdrop, teal block) -> the figure in a few+planes (jacket halves, sleeves) -> the head (skin planes, nose, cheek, ear, hair) -> details (glasses, beard,+chopsticks, the near hand) -> the still life (counter, bowl, noodles, the other hand, bottles, glass) -> the red+accent -> printed.+--stages writes those steps as snapshots for the draw-on. No image model.+python3 drybrush_noodle_counter.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from drybrush import DryBrushBlocks++W, H = 1600, 1200+COUNTER = 846 # y of the counter top+++class Scene:+ def __init__(self, d):+ self.d = d++ # ------------------------------------------------------------ 1 the big slabs+ def slabs(self):+ d = self.d+ d.backdrop((190, 78, 1132, 860), 'slab', seed=11)+ d.piece((1078, 372, 1336, 852), 'tealblue', torn=5, cut=0.7, angle=-90, load=1.0, dry=0.3, lane=60,+ scumble=0.07, direction=1, dry_from=(0.72, 0.95), seed=12)++ # ------------------------------------------------------------ 2 the figure in planes+ def figure(self):+ d = self.d+ self.J = d.jacket(neck=(640, 470), shoulders=(292, 528, 994, 540), bottom=COUNTER + 8, lit='tealblue',+ shade='navy', dark='ink', shirt='cream', collar='navy', light=-1, lapel=0.18, open_=0.07, seed=21)+ # near arm (viewer's left): shoulder -> elbow on the counter -> hand up at the chopsticks+ d.sleeve([(350, 580), (300, 730), (330, 818), (420, 742), (458, 660)], 136, 96, 'navy', angle=-65,+ mix=('tealblue', 0.22), stroke_len=120, passes=2, seed=22)+ # far arm (viewer's right): shoulder -> elbow -> forearm along the counter to the bowl+ d.sleeve([(946, 590), (1000, 750), (986, 826), (900, 834)], 130, 100, 'ink', angle=-112, mix=('navy', 0.3),+ stroke_len=110, passes=2, seed=23)++ def head(self):+ d = self.d+ self.Hd = d.head(640, 300, 250, 300, tilt=3, turn=0.16, light=-1, skin='tan', lit='skin_light', shade='umber',+ warm='tomato', ear='terracotta', hair='bone', hair_shade='ash', seed=31)++ def details(self):+ d = self.d+ d.glasses(self.Hd, colour='ink', lens=(0.34, 0.19), frame=0.07, seed=41)+ d.beard(self.Hd, colour='white', shade='bone', length=0.12, width=0.96, seed=42)+ # chopsticks from the near hand down into the bowl, then the hand over them+ d.stroke([(432, 628), (700, 752)], 9, 'bone', load=0.97, dry=0.2, square=0.9, seed=43)+ d.stroke([(450, 656), (708, 760)], 8, 'cream', load=0.97, dry=0.2, square=0.9, seed=44)+ d.hand(506, 680, 120, angle=30, cuff='cream', seed=45)++ # ------------------------------------------------------------ 3 the still life+ def still_life(self):+ d = self.d+ # counter top+ d.slab(d.poly([(140, COUNTER - 6), (1480, COUNTER - 10), (1482, COUNTER + 24), (138, COUNTER + 26)]), 'celadon',+ 0, load=0.985, dry=0.5, lane=14, fringe=40, side=2, scumble=0.3, seed=51)+ d.slab(d.poly([(150, COUNTER + 24), (1470, COUNTER + 22), (1468, COUNTER + 32), (152, COUNTER + 34)]), 'ink', 0,+ load=0.9, dry=0.6, lane=8, fringe=50, side=1.5, scumble=0.4, alpha=0.85, seed=52)+ # the bowl, noodles, chili oil, scallion+ body, inner = d.bowl(716, 736, 344, 116, colour='white', band='teal', inside='ochre', shade='bone', seed=53)+ r = np.random.default_rng(54)+ for k in range(11):+ x = 600 + k * 22 + r.normal(0, 4)+ d.stroke([(x, 744 + r.normal(0, 3)), (x + r.normal(0, 22), 730), (x + 34 + r.normal(0, 10), 742)], 8,+ 'cream', load=0.92, dry=0.4, seed=55 + k)+ d.piece(d.poly([(668, 732), (740, 724), (786, 736), (730, 748), (660, 744)], smooth=True), 'vermilion', torn=5,+ cut=0.2, seed=66)+ for (x, y) in [(632, 734), (652, 742), (760, 730), (800, 738), (706, 728), (590, 740)]:+ d.accent(x, y - 4, 11, 'leaf', rot=r.uniform(-30, 30), h=8, seed=x)+ d.hand(860, 800, 104, angle=188, grip=False, seed=46) # the other hand steadies the bowl+ # noodles hanging from the chopsticks+ for k, dx in enumerate((-8, -2, 4, 10)):+ d.stroke([(694 + dx, 744), (698 + dx + k, 730), (700 + dx, 714)], 5, 'cream', load=0.95, dry=0.3,+ seed=70 + k)+ # bottles and a glass of tea in front of the teal block+ d.bottle(1152, COUNTER, 94, 372, 'forest', shoulder=0.4, neck=0.3, neck_w=0.36, dark='ink', light='sage',+ label=('cream', 0.22, 0.5), label2=('vermilion', 0.18, 0.48, 0.18, 0.62), cap='ink', seed=80)+ d.bottle(1262, COUNTER, 84, 300, 'ink', shoulder=0.38, neck=0.3, neck_w=0.36, dark=None, light='teal',+ label=('bone', 0.2, 0.42), label2=('vermilion', 0.55, 0.85, 0.2, 0.8), cap='vermilion', seed=81)+ d.cup(1378, COUNTER, 84, 164, 'celadon', glass=True, level=0.6, tea='khaki', seed=82)++ # ------------------------------------------------------------ 4 the accent+ def accents(self):+ d = self.d+ d.accent(1406, 950, 62, 'vermilion', seed=95)++ def finish(self):+ self.d.printed(1.0)+++PHASES = ('slabs', 'figure', 'head', 'details', 'still_life', 'accents')+++def main():+ out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'drybrush_noodle_counter.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:12s} {time.time() - T0:5.1f}s')) if os.environ.get('DB_TIMING') else (lambda n: None)+ d = DryBrushBlocks(W, H, seed=7, keep_stages=bool(stages), stages_dir=stages)+ d.paper()+ d.stage('paper')+ sc = Scene(d)+ tick('setup')+ for ph in PHASES:+ getattr(sc, ph)()+ tick(ph)+ d.stage(ph)+ sc.finish()+ d.save(out, stages_dir=stages)+ tick('saved')+ print('saved', out)+++if __name__ == '__main__':+ main()diff --git a/examples/twilight_paper_kite.jpg b/examples/twilight_paper_kite.jpgnew file mode 100644index 0000000..4f611faBinary files /dev/null and b/examples/twilight_paper_kite.jpg differdiff --git a/examples/twilight_paper_kite.py b/examples/twilight_paper_kite.pynew file mode 100644index 0000000..52f1b79--- /dev/null+++ b/examples/twilight_paper_kite.py@@ -0,0 +1,250 @@+"""Example (twilight storybook): 夜的边上 · The Kite at the Edge of Night -- one dreamy dusk picture-book page.++A small hooded wanderer in a blue felt cloak sits on the crest of a wildflower hill at dusk, flying a paper kite+toward the place where the sky turns to night. Left: a big pastel dusk (lavender, rose, peach, gold) with soft cloud+bands, thin streaks of light, a low pale sun sinking behind misty mauve ranges, a flock of birds and drifting+dandelion seeds. Right: the night has already come -- a field of stars, the Milky Way with its dark rift, a crescent+moon, a shooting star, one lit window in a cottage on the far hill. Between them, patchwork hills in pastel stripes+with tiny round trees, and in front a meadow of thousands of wildflowers that turns moonlit-blue on the night side.+A jar of fireflies glows beside the wanderer; fireflies drift up toward the dark. A circular "detail a" inset shows+the kite's lashed spar crossing and bridle knot as a fine technical drawing (hatching, a dimension, labels, a scale),+and two tiny lowercase captions: "the evening waits for us." and "just a little further."++Painted in order: dusk sky -> night -> hills -> meadow -> figures and kite -> lights -> the plate overlay and captions.+--stages writes those steps as snapshots for the draw-on. No image model.+python3 twilight_paper_kite.py [out.jpg] [--stages DIR]+"""+import os, sys, time+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))+import numpy as np+from twilight import TwilightStorybook, hexc++W, H = 2000, 1100+HORIZON = 700+CREST = [(-20, 838), (300, 816), (650, 792), (950, 765), (1150, 750), (1255, 746), (1370, 751), (1600, 773),+ (1850, 797), (2020, 808)]+SEAT = (1255, 748)+KITE = (1436, 292)+KITE_SIZE, KITE_TILT = 120, 0.34+INSET = (930, 322, 132)+++class Page:+ def __init__(self, t):+ self.t = t+ self.r = np.random.default_rng(5)++ # ------------------------------------------------------------ 1 the dusk sky+ def sky(self):+ t = self.t+ t.dusk_sky(horizon=HORIZON, seed=1)+ clouds = [(-60, 520, 104, 46, 'cloud', 0.62), (600, 1150, 70, 34, 'cloud', 0.55), (60, 700, 262, 30, 'cloud', 0.55),+ (840, 1250, 228, 24, 'cloud', 0.5), (-40, 380, 392, 22, 'cloud_low', 0.5), (480, 980, 432, 24, 'cloud_low', 0.5),+ (120, 640, 548, 14, 'cloud_low', 0.42), (780, 1180, 586, 12, 'cloud_low', 0.38)]+ for i, (x0, x1, y, h, c, a) in enumerate(clouds):+ t.cloud(x0, x1, y, h, c, a, seed=10 + i)+ for i, (x0, x1, y) in enumerate([(130, 470, 432), (610, 740, 436), (470, 650, 514), (60, 310, 562), (760, 1010, 590),+ (300, 540, 612), (900, 1060, 470)]):+ t.streak(x0, x1, y, seed=30 + i)+ t.sun(470, 674, 36)+ r = self.r+ flock = [(650 + 18 * i + r.normal(0, 6), 300 - 6 * i + r.normal(0, 5)) for i in range(7)]+ t.birds(flock + [(300, 212), (322, 204), (338, 216)], size=6.5, seed=40)+ seeds = [(r.uniform(140, 1150), r.uniform(470, 660)) for _ in range(12)] + [(1170, 640), (1205, 610), (1140, 700)]+ t.seeds(seeds, size=8.5, seed=41)++ # ------------------------------------------------------------ 2 night comes in from the right+ def night(self):+ t = self.t+ t.night_split([(1200, -60), (1330, 120), (1440, 300), (1530, 520), (1575, 720), (1590, 1100)], soft=185, ground=0.88, seed=50)+ t.night_sky(seed=51)+ t.milky_way((1575, -70), (2060, 640), width=150, bend=-40, stars=3800, seed=52)+ t.stars(2300, sparkles=6, dusk=0.025, seed=53)+ t.moon(1838, 196, 25, phase=0.27, tilt=-0.4)+ t.shooting_star((1988, 318), (1878, 372))++ # ------------------------------------------------------------ 3 hills+ def hills(self):+ t = self.t+ t.hills([(-20, 676), (220, 660), (470, 668), (720, 650), (980, 664), (1240, 646), (1520, 662), (1780, 648), (2020, 660)],+ colour='#c9b1a8', base=780, fade=0.45, seed=60)+ t.hills([(-20, 700), (180, 684), (400, 694), (650, 676), (900, 690), (1150, 678), (1420, 690), (1700, 672), (2020, 688)],+ colour='mauve_dark', base=800, fade=0.4, rim='rim', rim_alpha=0.25, seed=61)+ t.mist(652, 698, 760, 'haze', 0.3, seed=62)+ info = t.striped_hill([(-20, 748), (230, 722), (470, 740), (720, 712), (980, 734), (1200, 708), (1440, 726), (1660, 704),+ (1900, 728), (2020, 716)], base=H, fade=0.35, hedge=0.45, seed=63)+ # tiny round trees along the field edges, a few standing alone+ r = self.r+ ry, b = info['ridge'], info['bounds']+ pts = []+ for k in range(1, 6):+ for x in r.uniform(0, W, 9 - k):+ pts.append((x, ry[int(x)] + b[k] + r.uniform(-1, 2)))+ for x in (120, 182, 420, 455, 760, 1040, 1080, 1610, 1835, 1870):+ pts.append((x, ry[x] + r.uniform(4, 10)))+ t.trees(pts, size=6.0, seed=64)+ self.cottage(1702, ry[1702] + 9)++ def cottage(self, x, y):+ """a tiny cottage on the night-side hill with one lit window"""+ t = self.t+ w, h = 16, 10+ t.shapes([np.array([(x - w / 2, y), (x + w / 2, y), (x + w / 2, y - h), (x - w / 2, y - h)])], '#d8c9bb', 1)+ t.shapes([np.array([(x - w / 2 - 2, y - h), (x + w / 2 + 2, y - h), (x + 2, y - h - 8), (x - 2, y - h - 8)])], '#8a5a52', 1)+ t.shapes([np.array([(x + 4, y - h - 4), (x + 6.5, y - h - 4), (x + 6.5, y - h - 10), (x + 4, y - h - 10)])], '#6e5f5c', 1)+ with t.unlit():+ t.shapes([np.array([(x - 4, y - 3), (x - 0.5, y - 3), (x - 0.5, y - 7), (x - 4, y - 7)])], '#ffd98a', 1)+ t.glow(x - 2.2, y - 5, 9, 'lantern', 0.35)++ # ------------------------------------------------------------ 4 the meadow+ def meadow(self):+ t = self.t+ info = t.meadow(CREST, density=1.0, grass=1.0, seed=70)+ crest = info['crest']+ t.grass_heads(1060, 1240, lambda x: crest[x.astype(int)], n=16, height=(26, 58), lean=0.12, seed=73)+ t.grass_heads(1330, 1520, lambda x: crest[x.astype(int)], n=18, height=(26, 62), lean=0.18, seed=74)+ t.grass_heads(600, 900, lambda x: crest[x.astype(int)], n=10, height=(14, 30), lean=0.1, width=0.7, seed=75)+ t.butterfly(420, 905, 9, '#e99a3d', angle=0.25, seed=71)+ t.butterfly(790, 958, 8, '#f2d67a', tip='#7c6a3c', angle=-0.35, open_=0.8, seed=72)+ t.butterfly(1120, 880, 7, '#a9c4ef', tip='#3f4f7a', angle=0.1, seed=76)+ t.dragonfly(612, 872, 22, angle=0.18)+ t.dragonfly(1010, 1000, 26, angle=-0.25)++ # ------------------------------------------------------------ 5 the wanderer, the lantern, the kite+ def figures(self):+ t = self.t+ sx, sy = SEAT+ shoulder = np.array([sx + 0.2 * 88, sy - 0.36 * 88])+ reach = np.array(KITE) - shoulder+ t.jar_lantern(1322, 752, 30, seed=80)+ self.hand = t.wanderer(sx, sy, 88, facing=1, reach=reach, seed=81)+ self.knot = t.kite(KITE[0], KITE[1], KITE_SIZE, KITE_TILT, seed=82)+ t.kite_string(self.hand, self.knot, sag=46)++ # ------------------------------------------------------------ 6 lights: fireflies, the lantern pool+ def lights(self):+ t = self.t+ r = self.r+ pts = []+ for _ in range(46):+ pts.append((r.normal(1450, 230), r.normal(840, 110)))+ for _ in range(14):+ pts.append((r.uniform(1250, 1760), r.uniform(430, 700)))+ for _ in range(8):+ pts.append((r.normal(1320, 50), r.normal(720, 40)))+ for _ in range(7):+ pts.append((r.uniform(200, 1150), r.uniform(820, 1060)))+ pts = [(x, y) for x, y in pts if 0 < x < W and 380 < y < H - 30]+ t.fireflies(pts, size=1.0, trails=4, seed=90)++ # ------------------------------------------------------------ 7 the plate: detail a, captions+ def plate(self):+ t = self.t+ cx, cy, R = INSET+ t.inset(cx, cy, R, draw=draw_knot, target=KITE, label='detail a', sub='not to scale', size=26, leader_colour='#3d383f')+ t.caption(112, 162, 'the evening waits for us.', 34, 'caption', 0.9, seed=100)+ t.caption(1892, 94, 'just a little further.', 27, '#d9d1d4', 0.85, anchor='r', seed=101)+++def draw_knot(t, cx, cy, r):+ """detail a: the lashed spar crossing and the bridle knot, as a fine technical drawing at the kite's tilt"""+ a = -0.38+ ca, sa = np.cos(a), np.sin(a)+ K = np.array([cx + 4, cy - 10], np.float32) # where the spars cross+ L = lambda u, v: K + np.array([u * ca - v * sa, u * sa + v * ca], np.float32)+ poly = lambda *uv: np.array([L(u, v) for u, v in uv], np.float32)+ ink, wood, cordc = '#4a4248', '#6b4f3a', '#f1e8d4'+ big = r + 70+ deg = np.degrees(a)+ # the paper sail behind: four panels in faint washes; the coral ones hatched like a plate+ quads = [poly((0, 0), (-big, 0), (-big, -big), (0, -big)), poly((0, 0), (0, -big), (big, -big), (big, 0)),+ poly((0, 0), (big, 0), (big, big), (0, big)), poly((0, 0), (0, big), (-big, big), (-big, 0))]+ for q, c in zip(quads, ('#f2e1c4', '#eca58f', '#e8d6b9', '#e6957f')):+ t.wash(q, c, alpha=0.45, seed=200)+ for i, q in ((1, quads[1]), (3, quads[3])):+ t.hatch(q, angle=deg + 45, spacing=6.5, width=0.5, colour='#9a5a50', alpha=0.38, seed=201 + i)+ t.hatch(quads[3], angle=deg - 45, spacing=9, width=0.45, colour='#9a5a50', alpha=0.22, seed=205)+ # a dowel: tan wash, outline, a few axis-parallel shading lines on the shadow flank, faint grain+ def dowel(along_v, half, lines_at):+ if along_v:+ body = poly((-half, -big), (half, -big), (half, big), (-half, big))+ edge = [poly((-half, -big), (-half, big)), poly((half, -big), (half, big))]+ shade = [poly((o, -big), (o, big)) for o in lines_at]+ grain = [poly((-half * 0.5 + k * half * 0.45, -big), (-half * 0.45 + k * half * 0.45, big)) for k in range(2)]+ else:+ body = poly((-big, -half), (big, -half), (big, half), (-big, half))+ edge = [poly((-big, -half), (big, -half)), poly((-big, half), (big, half))]+ shade = [poly((-big, o), (big, o)) for o in lines_at]+ grain = [poly((-big, -half * 0.4 + k * half * 0.5), (big, -half * 0.45 + k * half * 0.5)) for k in range(2)]+ t.wash(body, '#dcbb8f', alpha=0.9, edge=0.2, seed=210 + int(along_v))+ t.lines(grain, 0.45, '#8a6a4e', 0.4, wobble=0.9)+ t.lines(shade, 0.55, wood, 0.6, wobble=0.15)+ t.lines(edge, 1.15, ink, 0.9, wobble=0.25)+ dowel(True, 7.5, (3.6, 5.0, 6.0, 6.7))+ dowel(False, 6.5, (2.8, 4.1, 5.0, 5.7))+ # the lashing: four wraps each way across the crossing, each a cord with twist ticks+ def cord(p0, p1, w=4.0, ticks=True):+ p0 = np.asarray(p0, np.float32); p1 = np.asarray(p1, np.float32)+ u = (p1 - p0) / (np.linalg.norm(p1 - p0) + 1e-6); n = np.array([-u[1], u[0]], np.float32)+ t.shapes([np.array([p0 + n * w / 2, p1 + n * w / 2, p1 - n * w / 2, p0 - n * w / 2], np.float32)], cordc, 1, lit=False)+ t.lines([[p0 + n * w / 2, p1 + n * w / 2], [p0 - n * w / 2, p1 - n * w / 2]], 0.7, ink, 0.85)+ if ticks:+ Ln = float(np.linalg.norm(p1 - p0))+ t.lines([[p0 + u * s_ - n * w * 0.42 - u * 1.1, p0 + u * s_ + n * w * 0.42 + u * 1.1] for s_ in np.arange(2.4, Ln - 1, 2.9)],+ 0.42, ink, 0.5)+ for k in (-1.5, -0.5, 0.5, 1.5):+ cord(L(-15 + k * 4.2, -13 - k * 4.2), L(15 + k * 4.2, 13 - k * 4.2))+ for k in (-1.5, -0.5, 0.5, 1.5):+ cord(L(-15 + k * 4.2, 13 + k * 4.2), L(15 + k * 4.2, -13 + k * 4.2))+ # the finishing knot: two small loops and the cut tails+ kn = L(19, 17)+ for ang in (0.5, -0.9):+ th = np.linspace(0, 2 * np.pi, 30)+ lp_ = np.stack([kn[0] + np.cos(th) * 5.5 * np.cos(ang) - np.sin(th) * 3 * np.sin(ang),+ kn[1] + np.cos(th) * 5.5 * np.sin(ang) + np.sin(th) * 3 * np.cos(ang)], 1)+ t.lines([lp_], 2.6, ink, 0.85); t.lines([lp_], 1.2, cordc, 1.0)+ cord(kn + (3, 4), kn + (10, 16), w=3.2); cord(kn + (5, 1), kn + (17, 6), w=3.2)+ # the bridle: a leg from the crossing to a lark's-head loop; the flying line leaves toward the flyer+ lp = L(-46, 74)+ cord(L(-3, 9), lp + np.array([5, -7], np.float32), w=3.2)+ th = np.linspace(0, 2 * np.pi, 40)+ loop = np.stack([lp[0] + np.cos(th) * 10 * np.cos(1.0) - np.sin(th) * 5 * np.sin(1.0),+ lp[1] + np.cos(th) * 10 * np.sin(1.0) + np.sin(th) * 5 * np.cos(1.0)], 1)+ t.lines([loop], 3.0, ink, 0.85)+ t.lines([loop], 1.4, cordc, 1.0)+ cord(lp + np.array([-4, 8], np.float32), lp + np.array([-70, 130], np.float32), w=3.2)+ # labels, a diameter callout, a dimension and a scale, like a plate+ s_ = L(7.5, -84)+ t.lines([[s_ + (2, -1), s_ + (22, -14)]], 0.6, ink, 0.8)+ t.caption(float(s_[0] + 25), float(s_[1] - 12), 'spar', 16, ink, 0.9, seed=220)+ q = L(15, -14)+ t.lines([[q + (2, -3), (cx + 22, cy - 52)]], 0.6, ink, 0.8)+ t.caption(cx + 24, cy - 52, 'lashing, ×4', 16, ink, 0.9, seed=221)+ t.dimension(L(-7.5, -60), L(7.5, -60), 'ø 6', tick=4.4, colour=ink, width=0.65, size=15, across=True, lead=26)+ t.lines([[lp + (-9, -2), (cx - 36, cy + 56)]], 0.6, ink, 0.8)+ t.caption(cx - 38, cy + 61, 'bridle knot', 15, ink, 0.9, anchor='r', seed=222)+ t.ruler(cx + 22, cy + r * 0.5, cx + 70, h=8, step=4, colour=ink, labels=[(0, '0'), (10, '1 cm')], size=12)+++PHASES = ('sky', 'night', 'hills', 'meadow', 'figures', 'lights', 'plate')+++def main():+ out = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else 'twilight_paper_kite.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:10s} {time.time() - T0:5.1f}s')) if os.environ.get('TW_TIMING') else (lambda n: None)+ t = TwilightStorybook(W, H, seed=12, keep_stages=bool(stages), stages_dir=stages)+ t.finish(grain=1.0, vignette=1.0, bloom=0.8, edge=14) # applied at render, so every snapshot matches+ pg = Page(t)+ for ph in PHASES:+ getattr(pg, ph)()+ tick(ph)+ if ph != PHASES[-1]: t.stage(ph)+ t.save(out, stages_dir=stages)+ tick('saved')+ print('saved', out)+++if __name__ == '__main__':+ main()diff --git a/lib/drybrush.py b/lib/drybrush.pynew file mode 100644index 0000000..20351fb--- /dev/null+++ b/lib/drybrush.py@@ -0,0 +1,1107 @@+"""drybrush — 干刷色块 / Dry-Brush Blocks: a mid-century poster / gouache-collage illustration built from a few big+dry-brushed blocks of colour on cream paper (numpy + Pillow only).++The look: a confident editorial illustration in a strictly limited palette (forest and sage green, teal-blue, navy,+a near-black, vermilion, a little sky blue and pale celadon, cream). Every form is a handful of big flat-ish planes+laid with a dry, loaded brush or a roller: ragged, combed ends where the brush lifted, streaky drag marks and+scratchy scumble inside the block, paper showing through. Blocks overlap like layered screenprint or torn-paper+collage; a solid slab of colour stands behind the subject; one small red square sits off to the side. No outlines,+no gradients. Nothing here is a filter on flat shapes: every block is laid by a modelled brush on a modelled sheet.++Physical model+ brush frame Each block is painted in its own frame: the mask is rotated (Pillow) so the stroke direction runs+ along +u, everything is computed there with axis-aligned arrays, and the coverage, value and+ colour-mix fields are rotated back. So bristle streaks, lanes and dry ends always follow the stroke.+ textures Four tiles are made once per canvas in the brush frame: a bristle streak texture (noise grids that+ are ~40 px long and ~1 px across, upsampled), a dry tooth (those streaks + an isotropic paper grain,+ histogram-equalised to 0..1, so "paint reaches the tooth where tooth > 1 - contact" turns a contact+ pressure straight into a coverage fraction), broad lanes (value variation of the brush passes) and a+ stretched mottle (where a dry, scumbled pass skips). Every block reads them at a random offset.+ lanes A big block is laid in parallel passes of a wide brush or roller (`lane` px, each a little wider or+ narrower). A pass starts loaded where it enters the shape and runs dry toward its end (`dry`), so the+ ends break into streaks; `direction` says which way the passes run (+1, -1, 0 random, 2 back and+ forth). Passes differ a little in value (`vary`) and leave faint seams (`seam`); `passes=2` lays a+ second set over the first so the body closes up while the ends stay streaky.+ edges The mask is softened a little across the stroke (`side`: a slightly wobbly cut edge) and a lot along+ it (`fringe`), then thresholded against the bristle streaks: the sides come out nearly straight, the+ ends come out as a comb of tines of different lengths, longer at the dry end (`tines`).+ scumble Inside the block the contact pressure dips where the mottle is high (`scumble`), so paint only+ catches the tooth there: scratchy patches with paper (or the colour below) showing through. Dry+ stretches along the outline (`edge`) sit mostly on the sides that run along the stroke.+ roller `tooth='roller'` swaps the bristle tooth for a roller / sponge one (isotropic speckle in clusters),+ so a big slab stays nearly flat with stippled dry sides; `backdrop()` uses it, starts each pass loaded+ at the top and adds a few fine `scratches()` (thin lines a little paler than the paint).+ colour Opaque gouache by default: new = old + (colour - old) * coverage, so a dry pass over another block+ lets the block below show through its streaks. `mode='multiply'` overprints like screen ink (two pale+ pieces make a darker overlap). A second colour can ride in the same brush (`mix`), as streaks.+ pieces `piece()` is a torn / cut paper piece: the outline is displaced by fractal noise only along some+ stretches (the rest stays a clean cut), with an optional pale fibrous rim on the torn bits; inside it+ is painted paper (a dry block with a full load).+ strokes `stroke()` lays one dry brush mark along a path: every pixel knows its arc length and offset across+ (Pillow rasterises segment ids, then exact projection), so the tooth streaks run along the curve,+ the brush tapers and runs dry along its length. `scumble()` scatters short dry strokes in a mask+ (beards, hair, steam, highlights).+ figures `head()`, `glasses()`, `beard()`, `jacket()`, `sleeve()`, `hand()` build a person from a few big+ planes: a warm tan head with a lit plane, a shadow plane, a darker nose side with a warm tip, a warm+ cheek and ear, cropped hair (or a bald crown); rough black glasses; a white beard and moustache as dry+ scumble; a jacket whose lit and dark halves are brushed in different directions, lapels, a shirt V+ and a collar; sleeves brushed along the arm; a hand seen from the thumb side as stacked finger+ bands. Every helper works in a local unit frame (centre, size, tilt), so poses are a few numbers.+ vessels `bottle()` is a silhouette (body, shoulder, neck, lip) brushed vertically with a dark side and one+ light streak, a label as a small block (or two), a cap; `bowl()` and `cup()` are side views.+ accents `accent()` is a small, nearly solid square (vermilion by default) with a clean cut edge.+ print `printed()` finishes like an offset print of the painting: a slight softness, a fine paper grain,+ sparse paper-coloured specks knocked out of the darks and sparse dust on the paper.++API (canvas px; angles in degrees, 0 = to the right, 90 = down; colours are names in PAINTS or '#rrggbb')+ paper DryBrushBlocks(W, H, seed, keep_stages, stages_dir); paper(tone)+ shapes rect(x0, y0, x1, y1, rot), poly(pts, smooth), ellipse(cx, cy, rx, ry, rot), tube(path, w0, w1),+ quad(pts) -> canvas-size float masks+ blocks slab(shape, colour, angle, load, dry, lane, fringe, side, tines, scumble, streak, vary, direction,+ passes, seam, edge, stagger, dry_from, stroke_len, tooth, mix, mode, alpha, avoid, clip)+ the dry-brushed block (returns its coverage)+ piece(shape, colour, torn, cut, rim, angle, load, mode, ...) torn / cut paper piece+ backdrop(box, colour, angle, rough, scratches, ...) the big roller slab behind the subject;+ accent(x, y, size, colour, rot) the small solid square; scratches(mask, colour, n, length, width)+ marks stroke(path, width, colour, load, dry, taper, wobble, square, mode, alpha, clip); scumble(mask, colour,+ n, length, width, angle, spread, load, dry, clip)+ figures head(cx, cy, w, h, tilt, turn, light, skin, lit, shade, warm, ear, hair, crown) -> dict;+ glasses(head, colour, lens, frame); beard(head, colour, shade, length, width); jacket(neck, shoulders,+ bottom, lit, shade, dark, shirt, collar, light); sleeve(path, w0, w1, colour); hand(x, y, size, angle,+ grip, cuff)+ vessels bottle(x, base, w, h, ...), bowl(cx, rim_y, w, h, ...), cup(cx, base, w, h, ...)+ finish printed(amount); render(); composite(); stage(name); save(path, stages_dir)++ import sys; sys.path.insert(0, 'lib')+ from drybrush import DryBrushBlocks+ d = DryBrushBlocks(1600, 1200, seed=3)+ d.paper()+ d.backdrop((180, 90, 1120, 820), 'slab') # the green roller slab behind the subject+ d.slab(d.poly([(380, 520), (900, 500), (980, 830), (330, 830)]), 'navy', angle=-70, dry=0.4, stroke_len=180)+ H = d.head(640, 330, 230, 280, hair='bone'); d.glasses(H); d.beard(H)+ d.bottle(1250, 830, 110, 380, 'forest', label=('cream', 0.45, 0.7))+ d.accent(1380, 930, 58)+ d.printed(); d.save('drybrush.jpg')+"""+import io+import os+import numpy as np+from PIL import Image, ImageDraw+from core import blur, fbm1d, noise2d, smoothstep, spline, polygon_mask, blob_pts+++PAINTS = {+ 'paper': '#f2eee5', 'cream': '#efe8d6', 'bone': '#e2d9c3', 'white': '#f6f2e8',+ 'ink': '#0c1611', 'black': '#101310',+ 'forest': '#1d5636', 'green': '#2a7a4b', 'slab': '#5a865f', 'sage': '#77a26f', 'leaf': '#4f9a52',+ 'ash': '#bdb7a6', 'celadon': '#c4dabf', 'mint': '#a9cdb4', 'khaki': '#8d8b66',+ 'teal': '#0d6b67', 'lagoon': '#14919a', 'tealblue': '#14566b', 'navy': '#173a57', 'deep': '#0f2b3a',+ 'sky': '#a2cadb', 'ice': '#d4e5e6',+ 'vermilion': '#e0431f', 'tomato': '#e65a37', 'coral': '#ec8a68', 'blush': '#f0b7a0',+ 'ochre': '#9b7f56', 'tan': '#bf9a6c', 'skin': '#c88f62', 'skin_light': '#dcb48a', 'terracotta': '#bc6845',+ 'umber': '#5a3521', 'brown': '#3b2417', 'mustard': '#d2a13e',+}+++def hexc(c):+ """'#rrggbb', a PAINTS name or an RGB triple -> float32 RGB 0..1"""+ if not isinstance(c, str): return np.asarray(c, np.float32)+ h = PAINTS.get(c, c).lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def _equalise(t, bins=1024):+ hist, edges = np.histogram(t, bins)+ cdf = np.cumsum(hist).astype(np.float32); cdf /= cdf[-1]+ return np.interp(t, edges[1:], cdf).astype(np.float32)+++def _blur1(a, sigma, axis, mode='constant'):+ """1D gaussian-ish blur along one axis (3 box passes via cumulative sums); mode 'constant' (zero outside, for+ masks) or 'wrap' (periodic, for noise tiles)"""+ if sigma <= 0.3: return a+ out = a.astype(np.float32)+ w = int(np.sqrt(12 * sigma * sigma / 3 + 1)); w += (w % 2 == 0)+ r = w // 2+ for _ in range(3):+ pad = [(0, 0), (0, 0)]; pad[axis] = (r + 1, r)+ c = np.cumsum(np.pad(out, pad, mode=mode), axis=axis, dtype=np.float64)+ hi = np.take(c, np.arange(w, c.shape[axis]), axis=axis)+ lo = np.take(c, np.arange(0, c.shape[axis] - w), axis=axis)+ out = ((hi - lo) / w).astype(np.float32)+ return out+++def _aniso(N, cu, cv, rng):+ """N x N periodic, stationary noise (z-scored) whose features are ~cu px long along x (u) and ~cv px across+ (v): white noise blurred anisotropically with wrap-around, made at 1/f resolution along u and stretched back+ (no grid alignment, so thresholding it never makes rungs; periodic, so tiles can be indexed mod N)"""+ f = int(max(1, min(8, cu // 8)))+ while N % f: f -= 1+ n = N // f+ a = rng.random((N, n)).astype(np.float32)+ a = _blur1(a, max(0.35, cu / f / 2.6), 1, 'wrap')+ if cv > 1.1: a = _blur1(a, cv / 2.6, 0, 'wrap')+ if f > 1:+ a = np.concatenate([a[:, -1:], a, a[:, :1]], 1)+ a = np.asarray(Image.fromarray(a, 'F').resize(((n + 2) * f, N), Image.BILINEAR), np.float32)+ a = a[:, f:f + N]+ return ((a - a.mean()) / (a.std() + 1e-6)).astype(np.float32)+++def _rot(a, angle, resample=Image.BILINEAR):+ """rotate a float array counter-clockwise by `angle` deg with expand (a stroke at canvas angle -> +u)"""+ if abs(angle) % 360 < 1e-6: return np.ascontiguousarray(a, np.float32)+ return np.asarray(Image.fromarray(np.ascontiguousarray(a, np.float32), 'F').rotate(angle, resample=resample, expand=True),+ np.float32)+++def _unrot(a, angle, h, w, resample=Image.BICUBIC):+ """inverse of _rot, cropped back to the original (h, w)"""+ if abs(angle) % 360 < 1e-6: return a[:h, :w]+ b = np.asarray(Image.fromarray(np.ascontiguousarray(a, np.float32), 'F').rotate(-angle, resample=resample, expand=True),+ np.float32)+ y0, x0 = (b.shape[0] - h) // 2, (b.shape[1] - w) // 2+ return b[y0:y0 + h, x0:x0 + w]+++def _closed_spline(P, per=8):+ P = np.asarray(P, np.float32)+ n = len(P)+ ext = np.vstack([P[-1:], P, P[:2]])+ out = []+ for i in range(1, n + 1):+ p0, p1, p2, p3 = ext[i - 1], ext[i], ext[i + 1], ext[i + 2]+ for t in np.linspace(0, 1, per, endpoint=False):+ t2, t3 = t * t, t * t * t+ out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3))+ return np.array(out, np.float32)+++def _resample(P, step):+ P = np.asarray(P, np.float32)+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ if s[-1] < 1e-3: return P[:1]+ n = max(2, int(np.ceil(s[-1] / step)) + 1)+ ss = np.linspace(0, s[-1], n)+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)+++class DryBrushBlocks:+ PAINTS = PAINTS++ def __init__(self, W=1600, H=1200, seed=0, keep_stages=True, stages_dir=None):+ if W * H > 4096 * 4096: raise ValueError('canvas larger than 4096 x 4096')+ self.W, self.H, self.seed = W, H, seed+ self.rng = np.random.default_rng(seed)+ self.keep_stages, self.stages_dir = keep_stages, stages_dir+ self.stages, self._n_stages = [], 0+ self.C = np.empty((H, W, 3), np.float32)+ self.C[:] = hexc('paper')+ self.print_amt = 0.0+ self._tex = None++ def _r(self, seed=None):+ return np.random.default_rng(int(self.rng.integers(1 << 30)) if seed is None else seed)++ # ================================================================== paper and brush-frame textures+ def paper(self, tone='paper'):+ """cream paper: the colour with a faint fibre mottle (the grain itself is added in printed())"""+ H, W = self.H, self.W+ mot = noise2d(H, W, 220, 3, self.seed + 104) - 0.5+ fib = _blur1(np.random.default_rng(self.seed + 105).normal(0, 1, (H, W)).astype(np.float32), 3.0, 1)+ self.C[:] = hexc(tone) * (1 + 0.012 * mot[..., None] + 0.004 * fib[..., None])+ self._textures()++ def _textures(self):+ if self._tex is not None: return+ N = int(max(1024, np.ceil((np.hypot(self.W, self.H) + 24) / 64) * 64))+ r = np.random.default_rng(self.seed + 900)+ z = lambda a: (a - a.mean()) / (a.std() + 1e-6)+ # bristle streaks: long along u, 1-3 px across+ sb = 0.5 * _aniso(N, 40, 1.0, r) + 0.2 * _aniso(N, 14, 0.8, r) + 0.3 * _aniso(N, 90, 3.0, r)+ SB = _equalise(sb)+ # the dry tooth: bristle streaks + chunkier drag streaks + paper grain, so the voids of a dry pass are+ # streaky specks of many widths that cluster, not hairlines+ g = z(_blur1(_blur1(r.random((N, N)).astype(np.float32), 0.8, 0, 'wrap'), 0.8, 1, 'wrap'))+ TD = _equalise(0.34 * z(sb) + 0.36 * _aniso(N, 44, 4.5, r) + 0.22 * _aniso(N, 130, 13, r) + 0.2 * g)+ # roller / sponge tooth: isotropic speckle in clusters, a hint of drag+ RT = _equalise(0.42 * g + 0.3 * _aniso(N, 3.5, 3.0, r) + 0.18 * _aniso(N, 14, 5, r) + 0.22 * _aniso(N, 40, 30, r))+ # edge noise for the combed ends: tines 2-10 px wide, of many lengths+ EN = _equalise(0.4 * _aniso(N, 70, 2.6, r) + 0.4 * _aniso(N, 160, 9, r) + 0.2 * z(sb)) * 2 - 1+ # broad lanes (value of the passes) and a stretched mottle (where a dry pass skips)+ SL = _equalise(0.6 * _aniso(N, 320, 10, r) + 0.4 * _aniso(N, 90, 3.5, r))+ MO = _equalise(0.55 * _aniso(N, 300, 80, r) + 0.3 * _aniso(N, 100, 28, r) + 0.15 * _aniso(N, 34, 9, r))+ LO = _equalise(0.7 * _aniso(N, 220, 60, r) + 0.3 * _aniso(N, 60, 14, r))+ self._tex = dict(N=N, SB=SB, TD=TD, RT=RT, EN=EN, SL=SL, MO=MO, LO=LO)++ def _tile(self, h, w, r):+ """random window of the brush-frame textures, (h, w) <= N"""+ self._textures()+ T = self._tex+ N = T['N']+ if h > N or w > N:+ reps = (int(np.ceil(h / N)), int(np.ceil(w / N)))+ return {k: np.tile(v, reps)[:h, :w] for k, v in T.items() if k != 'N'}+ y0, x0 = int(r.integers(0, N - h + 1)), int(r.integers(0, N - w + 1))+ return {k: v[y0:y0 + h, x0:x0 + w] for k, v in T.items() if k != 'N'}++ # ================================================================== shapes (canvas-size masks)+ def _grid(self, sl):+ ys = np.arange(sl[0].start, sl[0].stop, dtype=np.float32)[:, None]+ xs = np.arange(sl[1].start, sl[1].stop, dtype=np.float32)[None, :]+ return xs, ys++ def _clip_box(self, x0, y0, x1, y1):+ x0, y0 = max(0, int(np.floor(x0))), max(0, int(np.floor(y0)))+ x1, y1 = min(self.W, int(np.ceil(x1))), min(self.H, int(np.ceil(y1)))+ if x1 <= x0 or y1 <= y0: return None+ return (slice(y0, y1), slice(x0, x1))++ def _bbox(self, m, pad=0, thr=0.004):+ rows = np.flatnonzero(m.max(1) > thr)+ if not len(rows): return None+ cols = np.flatnonzero(m.max(0) > thr)+ pad = int(np.ceil(pad))+ return (slice(max(0, rows[0] - pad), min(self.H, rows[-1] + 1 + pad)),+ slice(max(0, cols[0] - pad), min(self.W, cols[-1] + 1 + pad)))++ def poly(self, pts, smooth=False, per=8):+ pts = np.asarray(pts, np.float32)+ if smooth and len(pts) > 2: pts = _closed_spline(pts, per)+ return polygon_mask(self.H, self.W, pts, ss=2)++ def quad(self, pts):+ return self.poly(pts, smooth=False)++ def rect(self, x0, y0, x1, y1, rot=0.0):+ """axis-aligned box, or rotated by `rot` deg about its centre"""+ if not rot:+ return self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2+ a = np.deg2rad(rot); c, s = np.cos(a), np.sin(a)+ P = np.array([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], np.float32) - (cx, cy)+ return self.poly(np.stack([cx + P[:, 0] * c - P[:, 1] * s, cy + P[:, 0] * s + P[:, 1] * c], 1))++ def ellipse(self, cx, cy, rx, ry=None, rot=0.0):+ ry = rx if ry is None else ry+ R = max(rx, ry) + 3+ out = np.zeros((self.H, self.W), np.float32)+ sl = self._clip_box(cx - R, cy - R, cx + R + 1, cy + R + 1)+ if sl is None: return out+ X, Y = self._grid(sl)+ X, Y = X - cx, Y - cy+ if rot:+ a = np.deg2rad(rot); c, s = np.cos(a), np.sin(a)+ X, Y = X * c + Y * s, -X * s + Y * c+ d = np.sqrt((X / rx) ** 2 + (Y / ry) ** 2)+ e = 1.0 / max(2.0, min(rx, ry))+ out[sl] = smoothstep(1 + e, 1 - e, d)+ return out++ @staticmethod+ def tube_pts(path, w0, w1=None, per=8):+ """outline polygon of a thick path (width w0 -> w1), squarish ends"""+ P = np.asarray(path, np.float32)+ Q = spline(P, per) if len(P) > 2 else _resample(P, 4.0)+ w1 = w0 if w1 is None else w1+ d = np.gradient(Q, axis=0); d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-6+ nrm = np.stack([-d[:, 1], d[:, 0]], 1)+ hw = np.linspace(w0, w1, len(Q))[:, None] / 2+ return np.vstack([Q + nrm * hw, (Q - nrm * hw)[::-1]]).astype(np.float32)++ def tube(self, path, w0, w1=None):+ return self.poly(self.tube_pts(path, w0, w1))++ def _mask(self, shape):+ if isinstance(shape, np.ndarray) and shape.shape == (self.H, self.W): return shape.astype(np.float32)+ a = np.asarray(shape, np.float32)+ if a.ndim == 1 and len(a) == 4: return self.rect(*a)+ return self.poly(a)++ # ================================================================== laying paint+ def _lay(self, sl, cov, col, mode='opaque'):+ C = self.C[sl]+ a = np.clip(cov, 0, 1)[..., None]+ if mode == 'multiply':+ self.C[sl] = C * (1 - a + a * col)+ elif mode == 'screen':+ self.C[sl] = 1 - (1 - C) * (1 - a * col)+ else:+ self.C[sl] = C + (col - C) * a++ def _brush(self, M, sl, angle, load, dry, lane, fringe, side, tines, scumble, streak, vary, direction, passes,+ seam, mix_amt, edge, stagger, dry_from, stroke_len, tooth, r):+ """the dry-brush coverage, value and mix fields of a block, computed in its brush frame"""+ crop = M[sl]+ h0, w0 = crop.shape+ R = _rot(crop, angle)+ h, w = R.shape+ T = self._tile(h, w, r)+ inside = R > 0.5+ rows_in = inside.any(1)+ if not rows_in.any(): return None+ first = np.where(rows_in, inside.argmax(1), 0)+ last = np.where(rows_in, w - 1 - inside[:, ::-1].argmax(1), 0)+ ext_u = float(np.median((last - first)[rows_in]))+ ext_v = float(rows_in.sum())+ fr = float(min(fringe, 0.3 * ext_u))+ sd = float(min(side, 0.2 * ext_v))+ lane = float(min(lane, max(6.0, ext_v)))+ # ---- shape: nearly straight sides, combed ends+ Mi = blur(R, max(0.5, sd * 0.6)) if sd > 0.3 else R+ Mb = _blur1(Mi, max(0.4, fr * 0.5), 1) if fr > 0.6 else Mi+ U = np.arange(w, dtype=np.float32)[None, :]+ Vv = np.arange(h, dtype=np.float32)[:, None]+ patch = smoothstep(0.58, 0.95, T['MO'])+ # dry stretches along the outline (a side where the brush only grazed the paper)+ if edge:+ ew = max(3.0, min(lane * 0.35, ext_v * 0.15, ext_u * 0.15))+ inner = blur(R, ew)+ stretch = smoothstep(0.55, 0.8, T['LO'])+ gv, gu = np.gradient(inner) # sides run along u, ends across it+ side_w = np.abs(gv) / (np.abs(gu) + np.abs(gv) + 1e-6)+ side_w = 0.25 + 0.75 * smoothstep(0.35, 0.8, blur(side_w, ew))+ edge_drop = edge * stretch * side_w * (1 - smoothstep(0.5, 0.97, inner))+ else:+ edge_drop = 0.0++ cov_total = np.zeros((h, w), np.float32)+ val = np.zeros((h, w), np.float32)+ t_dry = np.zeros((h, w), np.float32)+ shift = np.zeros((h, w), np.float32)+ for p in range(max(1, passes)):+ key = 'RT' if tooth == 'roller' else 'TD'+ TDp = T[key] if p == 0 else self._tile(h, w, r)[key] # each pass drags its own bristle pattern+ # lanes across v, with wobbly borders+ lw = lane * r.uniform(0.9, 1.1)+ bounds = [float(r.uniform(-lw, 0))]+ while bounds[-1] < h + lw:+ bounds.append(bounds[-1] + lw * r.uniform(0.6, 1.4))+ B = np.array(bounds, np.float32)+ nl = len(B) - 1+ wob = (fbm1d(w, max(40.0, lane * 2.5), 3, int(r.integers(1 << 30))) * lane * 0.12)[None, :]+ vq = Vv + wob+ lid = np.clip(np.searchsorted(B, vq) - 1, 0, nl - 1)+ frac = (vq - B[lid]) / (B[lid + 1] - B[lid])+ # lane extents along u from the rows it covers+ row_lane = np.clip(np.searchsorted(B, np.arange(h, dtype=np.float32)) - 1, 0, nl - 1)+ u0 = np.full(nl, np.inf, np.float32); u1 = np.full(nl, -np.inf, np.float32)+ np.minimum.at(u0, row_lane[rows_in], first[rows_in].astype(np.float32))+ np.maximum.at(u1, row_lane[rows_in], last[rows_in].astype(np.float32))+ bad = ~np.isfinite(u0)+ u0[bad], u1[bad] = 0, w+ if direction == 2:+ sgn = np.where(np.arange(nl) % 2 == 0, 1.0, -1.0) * (1 if r.random() < 0.5 else -1)+ elif direction in (1, -1):+ sgn = np.full(nl, float(direction))+ else:+ sgn = r.choice([-1.0, 1.0], nl)+ # each lane is one pass, or (stroke_len) a row of overlapping strokes of different lengths+ if stroke_len:+ K = int(np.ceil((w + 2 * stroke_len) / (stroke_len * 0.6))) + 2+ st = np.full((nl, K), np.inf, np.float32)+ for i in range(nl):+ a_, c = float(u0[i]) - stroke_len * r.uniform(0.0, 0.6), []+ while a_ < u1[i] and len(c) < K:+ c.append(a_); a_ += stroke_len * r.uniform(0.55, 1.45)+ c.append(max(a_, float(u1[i]) + 1)); c = c[:K]+ st[i, :len(c)] = c+ j = np.clip((U[..., None] >= st[lid]).sum(-1) - 1, 0, K - 2)+ s0 = np.take_along_axis(st[lid], j[..., None], -1)[..., 0]+ s1 = np.take_along_axis(st[lid], (j + 1)[..., None], -1)[..., 0]+ s1 = np.where(np.isfinite(s1), s1, s0 + stroke_len)+ ov = stroke_len * 0.12 # strokes overlap a little+ t = (U - s0 + ov) / np.maximum(s1 - s0 + 2 * ov, 6.0)+ sid = lid * K + j+ nsid = nl * K+ else:+ L = np.maximum(u1 - u0, 8.0)+ t = (U - u0[lid]) / L[lid]+ sid, nsid = lid, nl+ sgn_s = np.repeat(sgn, nsid // nl) if stroke_len else sgn+ if stroke_len and direction == 0:+ sgn_s = r.choice([-1.0, 1.0], nsid)+ t = np.where(sgn_s[sid] > 0, t, 1 - t)+ # each pass / stroke runs dry toward its end by its own amount (some hardly at all)+ dl = (dry * r.uniform(0.0, 1.6, nsid) ** 1.2).astype(np.float32)+ ld = (load * r.uniform(0.985, 1.01, nsid)).astype(np.float32)+ dstart = r.uniform(*dry_from, nsid).astype(np.float32)+ lane_load = ld[sid] * (1 - dl[sid] * smoothstep(dstart[sid], 1.08, t) ** 1.1)+ if seam:+ lane_load = lane_load * (1 - seam * smoothstep(0.84, 1.0, np.abs(frac - 0.5) * 2))+ contact = np.clip(lane_load * (1 - scumble * patch) * (1 - edge_drop), 0, 1.08)+ paint = smoothstep(-0.04, 0.04, TDp - (1 - contact))+ cov_total = 1 - (1 - cov_total) * (1 - paint)+ off = r.normal(0, 1, nsid).astype(np.float32)+ val = val + off[sid] / max(1, passes)+ # the comb only matters where a pass ends at the outline, so t_dry follows the lane, not the stroke+ tl = (U - u0[lid]) / np.maximum(u1 - u0, 8.0)[lid]+ tl = np.where(sgn[lid] > 0, tl, 1 - tl)+ t_dry = np.maximum(t_dry, smoothstep(0.5, 1.0, tl) * (0.6 + 0.4 * (dry > 0)))+ shift = shift + (r.normal(0, 1, nl).astype(np.float32))[lid] / max(1, passes)+ amp = tines * (0.3 + 0.7 * t_dry)+ reach = smoothstep(0.03, 0.3, Mb) # tines only grow out of the fringe, never far beyond+ en = T['EN'] if tooth != 'roller' else (T['RT'] - 0.5) * 2 * 0.6 + (T['LO'] - 0.5) * 2 * 0.4+ shape = smoothstep(0.47, 0.53, Mb + reach * (amp * en * 0.42 + stagger * 0.16 * shift))+ cov = shape * cov_total+ if tooth == 'roller':+ V = 1 + vary * val + streak * 0.05 * (T['LO'] - 0.5) * 2 + streak * 0.03 * (T['RT'] - 0.5) * 2+ else:+ V = 1 + vary * val + streak * 0.10 * (T['SL'] - 0.5) * 2 + streak * 0.045 * (T['SB'] - 0.5) * 2+ Mx = None+ if mix_amt:+ q = 0.65 * T['SL'] + 0.35 * T['MO']+ Mx = smoothstep(1 - mix_amt - 0.05, 1 - mix_amt + 0.05, q)+ cov = np.clip(_unrot(cov, angle, h0, w0), 0, 1)+ V = _unrot(V, angle, h0, w0, Image.BILINEAR)+ if Mx is not None: Mx = np.clip(_unrot(Mx, angle, h0, w0, Image.BILINEAR), 0, 1)+ return cov, V, Mx++ def slab(self, shape, colour, angle=0.0, load=0.99, dry=0.45, lane=90.0, fringe=30.0, side=3.0, tines=0.8,+ scumble=0.25, streak=0.6, vary=0.025, direction=0, passes=1, seam=0.03, edge=0.35, stagger=1.0,+ dry_from=(0.5, 0.8), stroke_len=None, tooth='brush', mix=None, mode='opaque', alpha=1.0, avoid=None,+ halo=0.0, clip=None, seed=None):+ """a dry-brushed block of colour. shape: canvas mask | (x0, y0, x1, y1) | polygon points.+ angle: stroke direction (deg); load: contact of a loaded brush (0.97 leaves fine specks, 0.7 is scratchy,+ above 1 is an overloaded brush that stays solid even where it starts to run dry);+ dry: how much the passes run out toward their ends (each by its own amount); lane: brush / roller width (px);+ dry_from: where along a pass (0..1) it starts to run dry; stroke_len: break every pass into overlapping+ strokes of about this length (px), each with its own tone and dry end (None: one stroke per pass); tooth:+ 'brush' (bristle streaks along the stroke) or 'roller' (a roller / sponge: clustered speckle); edge: dry stretches along the outline; stagger: how+ much the ends of neighbouring passes differ; fringe: length of the+ combed ends (px); side: wobble of the sides along the stroke (px); tines: strength of the comb; scumble:+ scratchy patches inside; streak: value streaks along the stroke; vary: value difference between passes;+ direction: +1 / -1 / 0 random / 2 back and forth; passes: 2 closes up the body; seam: faint pass seams;+ mix: (colour2, amount) streaks of a second colour in the same brush; mode: 'opaque' | 'multiply' | 'screen'.+ Returns the coverage (canvas-size)."""+ r = self._r(seed)+ self._textures()+ M = self._mask(shape)+ sl = self._bbox(M, fringe * 1.6 + side * 3 + 6)+ out = np.zeros((self.H, self.W), np.float32)+ if sl is None: return out+ res = self._brush(M, sl, angle, load, dry, lane, fringe, side, tines, scumble, streak, vary, direction,+ passes, seam, (mix[1] if mix else 0.0), edge, stagger, dry_from, stroke_len, tooth, r)+ if res is None: return out+ cov, V, Mx = res+ cov = cov * alpha+ if avoid is not None:+ av = avoid[sl]+ if halo: av = smoothstep(0.1, 0.5, blur(av, halo))+ cov = cov * (1 - av)+ if clip is not None: cov = cov * clip[sl]+ c1 = hexc(colour)+ col = c1[None, None, :] * np.ones_like(cov)[..., None]+ if Mx is not None:+ col = col + (hexc(mix[0]) - c1)[None, None, :] * Mx[..., None]+ col = np.clip(col * V[..., None], 0, 1)+ self._lay(sl, cov, col, mode)+ out[sl] = cov+ return out++ def backdrop(self, box, colour='slab', angle=-90.0, rough=(6, 14), scratches=40, seed=None, **kw):+ """the big colour slab behind the subject, laid with a roller: nearly flat colour with clustered speckle,+ a crisp loaded start, stippled dry stretches along the sides and a few fine scratches.+ box = (x0, y0, x1, y1); angle: direction of the passes (-90 = upward, so the top is where it starts)"""+ r = self._r(seed)+ x0, y0, x1, y1 = box+ a, b = rough+ P = np.array([(x0 + r.normal(0, a * 0.3), y0 + r.normal(0, a * 0.3)), (x1 + r.normal(0, a * 0.3), y0 + r.normal(0, a * 0.3)),+ (x1 + r.normal(0, a * 0.3), y1 + r.normal(0, a * 0.3)), (x0 + r.normal(0, a * 0.3), y1 + r.normal(0, a * 0.3))])+ kw.setdefault('load', 1.0); kw.setdefault('dry', 0.35); kw.setdefault('lane', 160)+ kw.setdefault('fringe', b); kw.setdefault('side', a * 0.5); kw.setdefault('scumble', 0.12)+ kw.setdefault('streak', 0.6); kw.setdefault('vary', 0.012); kw.setdefault('passes', 2)+ kw.setdefault('dry_from', (0.8, 0.97)); kw.setdefault('tines', 0.35); kw.setdefault('edge', 0.6)+ kw.setdefault('tooth', 'roller'); kw.setdefault('direction', -1); kw.setdefault('seam', 0.0)+ cov = self.slab(self.poly(P), colour, angle, seed=int(r.integers(1 << 30)), **kw)+ if scratches:+ self.scratches(cov, colour, n=scratches, seed=int(r.integers(1 << 30)))+ return cov++ def scratches(self, mask, colour, n=40, length=(20, 120), width=(0.8, 1.8), angle=None, lift=0.22, seed=None):+ """fine scratches scraped into dry paint: thin lines a little paler than the paint (lift toward the+ paper), at loose random angles (or around `angle`), only inside the mask"""+ r = self._r(seed)+ yy, xx = np.nonzero(mask > 0.8)+ if not len(yy): return+ base = hexc(colour)+ col = base + (hexc('paper') - base) * lift+ for i in r.integers(0, len(yy), n):+ x, y = xx[i] + r.random(), yy[i] + r.random()+ a = np.deg2rad(r.uniform(0, 180) if angle is None else angle + r.normal(0, 12))+ L = r.uniform(*length) / 2+ p = [(x - np.cos(a) * L, y - np.sin(a) * L), (x + np.cos(a) * L * 0.1 + r.normal(0, 1), y + np.sin(a) * L * 0.1),+ (x + np.cos(a) * L, y + np.sin(a) * L)]+ self.stroke(p, r.uniform(*width), col, load=0.85, dry=0.6, taper=(0.2, 0.4), wobble=0.3, rough=0.3,+ clip=mask, seed=int(r.integers(1 << 30)))++ def piece(self, shape, colour, torn=7.0, cut=0.5, rim=0.0, rim_colour='paper', angle=0.0, load=0.985, dry=0.12,+ lane=70.0, scumble=0.1, streak=0.45, mode='opaque', alpha=1.0, avoid=None, clip=None, seed=None, **kw):+ """a torn / cut paper piece: torn = amplitude of the tear (px); cut = fraction of the outline left as a+ clean cut; rim = width of a pale fibrous rim on the torn stretches (px). Inside it is painted paper."""+ r = self._r(seed)+ M = self._mask(shape)+ sl = self._bbox(M, torn * 3 + 6)+ if sl is None: return np.zeros((self.H, self.W), np.float32)+ m = M[sl]+ h, w = m.shape+ if torn > 0:+ mb = blur(m, max(1.0, torn * 0.55))+ nz = (0.55 * (noise2d(h, w, max(6.0, torn * 3.5), 3, int(r.integers(1 << 30))) - 0.5)+ + 0.45 * (noise2d(h, w, max(2.0, torn * 0.9), 2, int(r.integers(1 << 30))) - 0.5)) * 2+ stretch = smoothstep(cut - 0.08, cut + 0.08, noise2d(h, w, max(40.0, np.sqrt(h * w) * 0.35), 2,+ int(r.integers(1 << 30))))+ mt = smoothstep(0.46, 0.54, mb + 0.42 * nz * stretch + (m - mb) * (1 - stretch))+ else:+ mt, stretch = m, np.zeros_like(m)+ Mt = np.zeros((self.H, self.W), np.float32); Mt[sl] = mt+ if rim > 0 and torn > 0:+ band = smoothstep(0.08, 0.5, blur(mt, rim * 0.5)) * (1 - smoothstep(0.5, 0.92, blur(mt, rim * 0.5)))+ band = band * stretch * smoothstep(0.35, 0.65, noise2d(h, w, 18, 2, int(r.integers(1 << 30))))+ self._lay(sl, band * 0.85 * alpha, hexc(rim_colour)[None, None, :], 'opaque')+ kw.setdefault('fringe', 0.0); kw.setdefault('side', 0.8); kw.setdefault('tines', 0.3)+ return self.slab(Mt, colour, angle, load=load, dry=dry, lane=lane, scumble=scumble, streak=streak, mode=mode,+ alpha=alpha, avoid=avoid, clip=clip, seed=int(r.integers(1 << 30)), **kw)++ def accent(self, x, y, size=56.0, colour='vermilion', rot=0.0, h=None, seed=None):+ """the small solid accent square (x, y = top-left corner), a clean cut edge and a faint print grain"""+ h = size if h is None else h+ r = self._r(seed)+ return self.slab(self.rect(x, y, x + size, y + h, rot), colour, angle=rot + r.choice([0.0, 90.0]), load=1.03,+ dry=0.05, lane=size * 2, fringe=0, side=0.6, tines=0.15, scumble=0.04, streak=0.12,+ vary=0.0, seam=0.0, edge=0.05, seed=int(r.integers(1 << 30)))++ # ================================================================== a dry stroke along a path+ def _footprint(self, Q, reach):+ """pixels within `reach` of polyline Q with the index of the segment they belong to: round joins first,+ then one float quad per segment, perpendicular to it, on top (Pillow fills ids into an int image)"""+ x0 = max(0, int(np.floor(Q[:, 0].min() - reach - 2))); x1 = min(self.W, int(np.ceil(Q[:, 0].max() + reach + 3)))+ y0 = max(0, int(np.floor(Q[:, 1].min() - reach - 2))); y1 = min(self.H, int(np.ceil(Q[:, 1].max() + reach + 3)))+ if x1 <= x0 or y1 <= y0: return None+ im = Image.new('I', (x1 - x0, y1 - y0), 0)+ d = ImageDraw.Draw(im)+ q = Q - [x0 - 0.5, y0 - 0.5]+ n = len(q)+ rr = reach + 0.5+ for k in range(n):+ j = min(k, n - 2) + 1+ d.ellipse([q[k][0] - rr, q[k][1] - rr, q[k][0] + rr, q[k][1] + rr], fill=int(j))+ seg = q[1:] - q[:-1]+ L = np.hypot(seg[:, 0], seg[:, 1]) + 1e-6+ t = seg / L[:, None]+ nr = np.stack([-t[:, 1], t[:, 0]], 1) * rr+ e = t * 0.6+ A, B = q[:-1] - e, q[1:] + e+ quads = np.stack([A + nr, B + nr, B - nr, A - nr], 1)+ for k in range(n - 1):+ d.polygon([tuple(p) for p in quads[k].tolist()], fill=k + 1)+ a = np.asarray(im, np.int32)+ yy, xx = np.nonzero(a)+ if not len(yy): return None+ return yy + y0, xx + x0, a[yy, xx] - 1++ def stroke(self, path, width, colour, load=0.95, dry=0.45, taper=(0.06, 0.25), wobble=1.0, smooth=True,+ streak=0.5, rough=1.0, square=0.6, mode='opaque', alpha=1.0, clip=None, seed=None):+ """one dry brush mark along a path: streaks along the curve, a flat brush (square = how blunt the ends+ are), tapering and running dry along its length"""+ r = self._r(seed)+ self._textures()+ P = np.asarray(path, np.float32).reshape(-1, 2)+ if len(P) < 2: return+ if smooth and len(P) > 2: P = spline(P, 8)+ Q = _resample(P, 2.0)+ n = len(Q)+ if wobble and n > 3:+ d = np.gradient(Q, axis=0); d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-6+ nrm = np.stack([-d[:, 1], d[:, 0]], 1)+ Q = Q + nrm * (fbm1d(n, 40, 3, int(r.integers(1 << 30))) * 1.2 * wobble)[:, None]+ seg = Q[1:] - Q[:-1]+ sL = np.hypot(seg[:, 0], seg[:, 1]) + 1e-6+ cum = np.concatenate([[0], np.cumsum(sL)])+ L = float(cum[-1])+ if L < 1.0: return+ reach = width * 0.5 + 2 + rough+ fp = self._footprint(Q, reach)+ if fp is None: return+ ys, xs, k = fp+ k = np.clip(k, 0, len(seg) - 1)+ dx, dy = seg[k, 0] / sL[k], seg[k, 1] / sL[k]+ rx, ry = xs - Q[k, 0], ys - Q[k, 1]+ p = rx * dx + ry * dy+ u = np.clip(p, 0, sL[k])+ over = np.where(k == 0, np.maximum(0, -p), 0) + np.where(k == len(seg) - 1, np.maximum(0, p - sL[k]), 0)+ px, py = rx - p * dx, ry - p * dy # offset across the stroke (no round caps)+ dist = np.hypot(px, py)+ side = np.sign(-rx * dy + ry * dx)+ s = cum[k] + np.where(over > 0, p, u) # texture runs on past the ends+ s01 = np.clip((cum[k] + u) / L, 0, 1)+ prof = np.clip(np.minimum(s01 / max(taper[0], 1e-3), (1 - s01) / max(taper[1], 1e-3)), 0, 1)+ prof = square + (1 - square) * prof ** 0.7+ hw = 0.5 * width * prof+ T = self._tex+ N = T['N']+ oy, ox = int(r.integers(0, N)), int(r.integers(0, N))+ iv = (np.round(side * dist).astype(np.int64) + oy) % N+ iu = (np.round(s).astype(np.int64) + ox) % N+ Td, Sb, Sl = T['TD'][iv, iu], T['SB'][iv, iu], T['SL'][iv, iu]+ e = dist - hw - rough * 1.3 * (Sb - 0.5) * 2+ body = smoothstep(0.7, -0.7, e) * smoothstep(0.7, -0.7, over * 1.6 - (0.5 + 2.2 * rough) * (T['EN'][iv, iu] + 0.4))+ contact = load * (1 - dry * smoothstep(0.15, 1.0, s01) ** 1.2) * (1 - 0.25 * smoothstep(0.6, 1.0, dist / (hw + 1e-3)))+ dep = body * smoothstep(-0.05, 0.05, Td - (1 - contact)) * alpha+ if clip is not None: dep = dep * clip[ys, xs]+ keep = dep > 0.003+ if not keep.any(): return+ ys, xs, dep = ys[keep], xs[keep], dep[keep]+ col = hexc(colour)[None, :] * (1 + streak * 0.12 * (Sl[keep] - 0.5) * 2)[:, None]+ idx = (ys, xs)+ C = self.C[idx]+ a = dep[:, None]+ if mode == 'multiply': self.C[idx] = C * (1 - a + a * col)+ else: self.C[idx] = C + (np.clip(col, 0, 1) - C) * a++ def scumble(self, mask, colour, n=40, length=(30, 90), width=(8, 20), angle=0.0, spread=25.0, load=0.8,+ dry=0.55, bend=0.15, alpha=1.0, clip=None, seed=None):+ """short dry strokes scattered in a mask (white beard, hair, steam, highlights); angle may be a number or+ a function f(x, y) -> deg"""+ r = self._r(seed)+ yy, xx = np.nonzero(mask > 0.5)+ if not len(yy): return+ for i in r.integers(0, len(yy), n):+ x, y = xx[i] + r.random(), yy[i] + r.random()+ a0 = angle(x, y) if callable(angle) else angle+ a = np.deg2rad(a0 + r.normal(0, spread * 0.5))+ Lh = r.uniform(*length) / 2+ d = np.array([np.cos(a), np.sin(a)]); nr = np.array([-d[1], d[0]])+ b = r.uniform(-bend, bend) * Lh+ pts = [(x - d[0] * Lh, y - d[1] * Lh), (x + nr[0] * b, y + nr[1] * b), (x + d[0] * Lh, y + d[1] * Lh)]+ self.stroke(pts, r.uniform(*width), colour, load * r.uniform(0.9, 1.05), dry * r.uniform(0.7, 1.3),+ (0.05, 0.4), 0.6, alpha=alpha, clip=clip if clip is not None else None,+ seed=int(r.integers(1 << 30)))++ # ================================================================== figures (a person from a few big planes)+ @staticmethod+ def _frame(cx, cy, w, h, tilt=0.0):+ """local unit frame of a part: (-1..1, -1..1) -> canvas, rotated by tilt (deg)"""+ a = np.deg2rad(tilt); c, s = np.cos(a), np.sin(a)++ def P(pts):+ q = np.asarray(pts, np.float32).reshape(-1, 2) * (w / 2, h / 2)+ return np.stack([cx + q[:, 0] * c - q[:, 1] * s, cy + q[:, 0] * s + q[:, 1] * c], 1)+ return P++ def head(self, cx, cy, w, h, tilt=0.0, turn=0.0, light=-1, skin='tan', lit='skin_light', shade='umber',+ warm='tomato', ear='terracotta', highlight='cream', crown=None, hair=None, hair_shade='bone', seed=None):+ """a head from planes: base skin, a shadow plane on the side away from the light (light=-1: light from the+ viewer's left), a pale lit plane, a warm cheek, a warm ear on the shadow side, a nose plane with a warm tip+ and a shadow under it, a few dry highlights. turn (-1..1) moves the features toward one side; crown: colour+ of a bald, lit crown; hair: colour of short cropped hair (a flat-top scumbled over the top and down the+ temples, hair_shade on the shadow side). Returns a dict of anchor points and masks for+ glasses(), beard() and the like."""+ r = self._r(seed)+ P = self._frame(cx, cy, w, h, tilt)+ ls = float(light)+ out = [(-0.80, -0.78), (-0.35, -0.98), (0.1, -1.0), (0.55, -0.92), (0.86, -0.62), (0.96, -0.18), (0.92, 0.28),+ (0.74, 0.66), (0.42, 0.92), (0.02, 1.0), (-0.42, 0.92), (-0.74, 0.66), (-0.92, 0.28), (-0.96, -0.2)]+ face = self.poly(P(out), smooth=True)+ ang = tilt - 90+ self.slab(face, skin, ang, load=0.99, dry=0.25, lane=w * 0.3, fringe=6, side=2.5, scumble=0.15, edge=0.25,+ mix=(lit, 0.18), seed=int(r.integers(1 << 30)))+ # shadow plane on the side away from the light: a jagged inner boundary down the cheek+ sx = -ls+ tb = 0.34 * sx + turn * 0.3+ sh = [(tb + 0.12 * sx, -0.95), (1.1 * sx, -0.95), (1.1 * sx, 0.95), (0.25 * sx + turn * 0.2, 1.05),+ (tb + 0.02 * sx, 0.55), (tb + 0.14 * sx, 0.25), (tb - 0.02 * sx, -0.05), (tb + 0.1 * sx, -0.4)]+ shadow = self.poly(P(sh)) * face+ self.slab(shadow, shade, tilt - 90 + 8 * sx, load=0.97, dry=0.45, lane=w * 0.16, fringe=10, side=3,+ scumble=0.3, edge=0.5, mix=(skin, 0.15), seed=int(r.integers(1 << 30)))+ # brow shadow band across the eyes+ bw = [(-0.9, -0.3), (0.9, -0.3), (0.9, -0.06), (-0.9, -0.02)]+ self.slab(self.poly(P(bw)) * face, shade, tilt + 0, load=0.9, dry=0.5, lane=h * 0.08, fringe=14, side=2,+ scumble=0.4, alpha=0.75, seed=int(r.integers(1 << 30)))+ # lit plane: forehead and cheek on the light side+ lp = [(-0.15 * sx + turn * 0.3, -0.9), (-0.85 * sx, -0.7), (-0.9 * sx, 0.15), (-0.55 * sx, 0.45),+ (-0.2 * sx + turn * 0.3, 0.2), (-0.12 * sx + turn * 0.3, -0.35)]+ lit_m = self.poly(P(lp), smooth=True) * face+ self.slab(lit_m, lit, tilt - 90 - 10 * sx, load=0.86, dry=0.55, lane=w * 0.14, fringe=12, side=3,+ scumble=0.45, edge=0.6, seed=int(r.integers(1 << 30)))+ # warm cheek on the light side, warm ear on the shadow side+ ck = [(-0.66 * sx, 0.14), (-0.42 * sx + turn * 0.2, 0.1), (-0.36 * sx + turn * 0.2, 0.3), (-0.5 * sx, 0.42),+ (-0.68 * sx, 0.36)]+ self.slab(self.poly(P(ck), smooth=True) * face, warm, tilt - 70, load=0.86, dry=0.55, lane=w * 0.06, fringe=10,+ side=5, scumble=0.45, edge=0.6, alpha=0.8, seed=int(r.integers(1 << 30)))+ ex = 0.97 * sx+ er = [(ex - 0.06 * sx, -0.22), (ex + 0.16 * sx, -0.28), (ex + 0.2 * sx, 0.1), (ex + 0.08 * sx, 0.32),+ (ex - 0.06 * sx, 0.26)]+ ear_m = self.poly(P(er), smooth=True)+ if ear:+ self.slab(ear_m, ear, tilt - 90, load=0.97, dry=0.35, lane=w * 0.1, fringe=6, side=2, scumble=0.2,+ mix=(warm, 0.3), seed=int(r.integers(1 << 30)))+ self.slab(self.poly(P([(ex + 0.02 * sx, -0.12), (ex + 0.12 * sx, -0.1), (ex + 0.1 * sx, 0.16),+ (ex + 0.0 * sx, 0.12)])), shade, tilt - 90, load=0.9, dry=0.4, lane=8, fringe=4,+ side=1.5, alpha=0.8, seed=int(r.integers(1 << 30)))+ # nose: a darker shadow side than the cheek plane, a lit bridge, a small warm tip, the shadow under it+ nx = turn * 0.32+ ns = [(nx + 0.0 * sx, -0.22), (nx + 0.1 * sx, -0.2), (nx + 0.2 * sx, 0.12), (nx + 0.22 * sx, 0.36),+ (nx + 0.02 * sx, 0.4), (nx + 0.02 * sx, 0.1)]+ self.slab(self.poly(P(ns), smooth=True), 'brown', tilt - 90, load=0.98, dry=0.35, lane=w * 0.06, fringe=6,+ side=2, scumble=0.2, mix=(shade, 0.3), seed=int(r.integers(1 << 30)))+ self.stroke([P([(nx - 0.03 * sx, -0.16)])[0], P([(nx - 0.05 * sx, 0.1)])[0], P([(nx - 0.08 * sx, 0.3)])[0]],+ w * 0.06, lit, load=0.9, dry=0.45, taper=(0.15, 0.3), seed=int(r.integers(1 << 30)))+ tip = self.ellipse(*P([(nx + 0.04 * sx, 0.34)])[0], w * 0.075, h * 0.045, rot=tilt)+ self.slab(tip, warm, tilt, load=0.92, dry=0.35, lane=10, fringe=5, side=2, alpha=0.9,+ seed=int(r.integers(1 << 30)))+ self.slab(self.poly(P([(nx - 0.1 * sx, 0.4), (nx + 0.24 * sx, 0.38), (nx + 0.18 * sx, 0.46), (nx - 0.06 * sx, 0.47)])),+ 'brown', tilt, load=0.92, dry=0.4, lane=8, fringe=6, side=1.5, alpha=0.9, seed=int(r.integers(1 << 30)))+ if crown:+ cr = [(-0.7, -0.75), (-0.2, -0.97), (0.35, -0.95), (0.72, -0.72), (0.4, -0.55), (-0.3, -0.58)]+ self.slab(self.poly(P(cr), smooth=True) * face, crown, tilt - 10 * sx, load=0.84, dry=0.6, lane=w * 0.12,+ fringe=20, side=4, scumble=0.5, edge=0.6, seed=int(r.integers(1 << 30)))+ if hair:+ hp = [(-1.0, -0.2), (-0.98, -0.7), (-0.82, -0.96), (-0.3, -1.06), (0.3, -1.06), (0.82, -0.96), (0.98, -0.7),+ (1.0, -0.2), (0.9, -0.22), (0.86, -0.55), (0.5, -0.66), (0.0, -0.7), (-0.5, -0.66), (-0.86, -0.55),+ (-0.9, -0.22)]+ hm_ = self.poly(P(hp), smooth=True)+ self.slab(hm_, hair, tilt - 90 - 12 * sx, load=0.92, dry=0.5, lane=w * 0.06, fringe=h * 0.06, side=5,+ tines=1.0, scumble=0.4, edge=0.6, stroke_len=h * 0.16, passes=2, direction=1,+ seed=int(r.integers(1 << 30)))+ hs = hm_ * self.poly(P([(0.3 * sx, -1.3), (1.3 * sx, -1.3), (1.3 * sx, 0.0), (0.45 * sx, 0.0)]))+ self.slab(hs, hair_shade, tilt - 80 * sx, load=0.86, dry=0.6, lane=w * 0.06, fringe=w * 0.05, side=4,+ scumble=0.5, alpha=0.9, seed=int(r.integers(1 << 30)))+ self.scumble(hm_, hair, n=10, length=(0.08 * w, 0.2 * w), width=(0.02 * w, 0.04 * w), angle=tilt - 90,+ spread=40, load=0.8, dry=0.6, seed=int(r.integers(1 << 30)))+ if highlight:+ hm = self.poly(P([(-0.7 * sx, -0.62), (-0.35 * sx, -0.75), (-0.3 * sx, -0.45), (-0.62 * sx, -0.38)]))+ self.scumble(hm * face, highlight, n=5, length=(0.12 * w, 0.3 * w), width=(0.03 * w, 0.06 * w),+ angle=tilt - 80 * sx, spread=20, load=0.8, dry=0.6, seed=int(r.integers(1 << 30)))+ hc = self.poly(P([(-0.75 * sx, 0.0), (-0.55 * sx, -0.05), (-0.5 * sx, 0.12), (-0.72 * sx, 0.16)]))+ self.scumble(hc * face, highlight, n=3, length=(0.08 * w, 0.18 * w), width=(0.025 * w, 0.045 * w),+ angle=tilt - 75 * sx, spread=15, load=0.75, dry=0.6, seed=int(r.integers(1 << 30)))+ return dict(P=P, face=face, shadow=shadow, ear=ear_m, nose=P([(nx, 0.3)])[0], eyes=P([(-0.42 + turn * 0.25, -0.12),+ (0.42 + turn * 0.25, -0.12)]), mouth=P([(nx, 0.6)])[0], chin=P([(0.0, 1.0)])[0], w=w, h=h,+ tilt=tilt, turn=turn, light=ls)++ def glasses(self, H, colour='ink', lens=(0.36, 0.2), frame=0.07, brow=1.6, tint='umber', glint='cream', seed=None):+ """rough black glasses on a head() dict: thick dry-brushed frames (a heavier top bar), a bridge, the arm+ running to the ear, a faint tint in the lenses and one dry glint"""+ r = self._r(seed)+ P, w, tilt = H['P'], H['w'], H['tilt']+ fw = frame * w+ (lx, ly), (rx_, ry_) = H['eyes']+ lens_px = (lens[0] * w, lens[1] * H['h'])+ for k, (ex, ey) in enumerate(((lx, ly), (rx_, ry_))):+ far = (k == 1) == (H['light'] < 0)+ sc = 0.86 if far else 1.0+ lw, lh = lens_px[0] * sc, lens_px[1]+ Q = self._frame(ex, ey, lw, lh, tilt)+ box = Q([(-1, -1), (1, -1), (1, 0.75), (0.6, 1), (-0.6, 1), (-1, 0.75)])+ inner = self.poly(Q([(-0.78, -0.62), (0.78, -0.62), (0.8, 0.5), (0.5, 0.74), (-0.5, 0.74), (-0.8, 0.5)]), smooth=True)+ if tint:+ self.slab(inner, tint, tilt - 90, load=0.8, dry=0.5, lane=12, fringe=4, side=2, scumble=0.5, alpha=0.22,+ mode='multiply', seed=int(r.integers(1 << 30)))+ outer = self.poly(box, smooth=True)+ ring = np.clip(outer - self.poly(Q([(-0.8, -0.52), (0.8, -0.52), (0.82, 0.52), (0.52, 0.78), (-0.52, 0.78),+ (-0.82, 0.52)]), smooth=True), 0, 1)+ topbar = self.poly(Q([(-1.08, -1.12), (1.08, -1.12), (1.04, -1 + 0.5 * brow * fw / max(lh, 1)), (-1.04, -1 + 0.5 * brow * fw / max(lh, 1))]))+ self.slab(np.maximum(ring, topbar), colour, tilt + r.uniform(-8, 8), load=0.985, dry=0.4, lane=fw * 1.2,+ fringe=6, side=1.2, tines=0.5, scumble=0.2, seed=int(r.integers(1 << 30)))+ if glint and not far:+ self.stroke([Q([(-0.5, -0.25)])[0], Q([(-0.05, -0.38)])[0]], fw * 0.8, glint, load=0.8, dry=0.6,+ seed=int(r.integers(1 << 30)))+ # bridge and the arm toward the ear+ self.stroke([(lx + lens_px[0] * 0.45, ly - lens_px[1] * 0.35), ((lx + rx_) / 2, (ly + ry_) / 2 - lens_px[1] * 0.5),+ (rx_ - lens_px[0] * 0.4, ry_ - lens_px[1] * 0.35)], fw * 0.9, colour, load=0.97, dry=0.3,+ seed=int(r.integers(1 << 30)))+ ex, ey = (rx_, ry_) if H['light'] < 0 else (lx, ly)+ sgn = 1 if H['light'] < 0 else -1+ a0 = (ex + sgn * lens_px[0] * 0.48, ey - lens_px[1] * 0.4)+ a1 = P([(0.98 * -H['light'], -0.18)])[0]+ self.stroke([a0, a1], fw * 0.85, colour, load=0.95, dry=0.45, seed=int(r.integers(1 << 30)))++ def beard(self, H, colour='white', shade='bone', length=0.42, width=0.95, moustache=True, density=1.0, seed=None):+ """a white beard and moustache as dry scumble over a head() dict: a ragged pale block brushed downward,+ dry strokes that fan out past its edge, a grey shadow side and a moustache under the nose"""+ r = self._r(seed)+ P, w, h, tilt, sx = H['P'], H['w'], H['h'], H['tilt'], -H['light']+ nx = H['turn'] * 0.32+ bd = [(-0.9 * width, 0.25), (-0.5 * width + nx, 0.5), (nx, 0.56), (0.5 * width + nx, 0.5), (0.9 * width, 0.25),+ (0.82 * width, 0.7), (0.45 * width, 1.0 + length * 0.7), (0.0 + nx * 0.5, 1.0 + length),+ (-0.45 * width, 1.0 + length * 0.7), (-0.82 * width, 0.7)]+ bm = self.poly(P(bd), smooth=True)+ self.slab(bm, colour, tilt + 90, load=0.9, dry=0.6, lane=w * 0.1, fringe=w * 0.14, side=6, tines=1.0,+ scumble=0.45, edge=0.6, direction=1, dry_from=(0.3, 0.6), seed=int(r.integers(1 << 30)))+ shm = bm * self.poly(P([(0.35 * sx + nx, 0.3), (1.2 * sx, 0.3), (1.2 * sx, 1.6), (0.2 * sx, 1.6)]))+ self.slab(shm, shade, tilt + 90, load=0.85, dry=0.6, lane=w * 0.08, fringe=w * 0.1, side=4, scumble=0.5,+ alpha=0.85, direction=1, seed=int(r.integers(1 << 30)))+ def fan(x, y):+ dx = (x - P([(nx, 0.5)])[0][0]) / (w * 0.5)+ return tilt + 90 - 28 * np.clip(dx, -1, 1)+ self.scumble(bm, colour, n=int(26 * density), length=(0.1 * w, 0.32 * w), width=(0.025 * w, 0.06 * w),+ angle=fan, spread=14, load=0.85, dry=0.55, bend=0.12, seed=int(r.integers(1 << 30)))+ self.scumble(shm, shade, n=int(8 * density), length=(0.08 * w, 0.22 * w), width=(0.02 * w, 0.04 * w),+ angle=fan, spread=14, load=0.8, dry=0.6, seed=int(r.integers(1 << 30)))+ if moustache:+ for k in (-1, 1):+ p0 = P([(nx + 0.04 * k, 0.48)])[0]; p1 = P([(nx + 0.42 * k, 0.6)])[0]; pm = P([(nx + 0.24 * k, 0.5)])[0]+ self.stroke([p0, pm, p1], w * 0.12, colour, load=0.92, dry=0.55, taper=(0.05, 0.5), seed=int(r.integers(1 << 30)))+ return bm++ def jacket(self, neck, shoulders, bottom, lit='tealblue', shade='navy', dark='ink', shirt='cream', collar=None,+ light=-1, lapel=0.32, open_=0.16, seed=None):+ """a jacket from planes: neck = (x, y) of the throat, shoulders = (xl, yl, xr, yr), bottom = y of the+ lowest edge. The lit half is brushed one way, the shadow half (near-black with streaks of the jacket colour)+ another; a shirt V, two lapel blocks, an optional stand collar. Returns the jacket mask."""+ r = self._r(seed)+ nxp, nyp = neck+ xl, yl, xr, yr = shoulders+ Wd = xr - xl+ body = [(xl + Wd * 0.08, yl - Wd * 0.02), (nxp - Wd * 0.12, nyp - Wd * 0.03), (nxp + Wd * 0.12, nyp - Wd * 0.03),+ (xr - Wd * 0.08, yr - Wd * 0.02), (xr + Wd * 0.03, yr + Wd * 0.12), (xr + Wd * 0.06, bottom),+ (xl - Wd * 0.06, bottom), (xl - Wd * 0.03, yl + Wd * 0.12)]+ J = self.poly(body, smooth=False)+ ls = float(light)+ midx = nxp + Wd * 0.02 * -ls+ lit_side = [(midx, nyp - 40), (xl - 60 if ls < 0 else xr + 60, nyp - 40), (xl - 60 if ls < 0 else xr + 60, bottom + 5),+ (midx, bottom + 5)]+ Ml = J * self.poly(lit_side)+ Ms = J * (1 - self.poly(lit_side))+ self.slab(Ms, dark, -90 + 22 * -ls, load=1.02, dry=0.35, lane=Wd * 0.08, fringe=22, side=5, scumble=0.12,+ edge=0.35, mix=(shade, 0.07), passes=2, stroke_len=Wd * 0.34, seed=int(r.integers(1 << 30)))+ self.slab(Ml, lit, -90 - 25 * -ls, load=0.993, dry=0.4, lane=Wd * 0.07, fringe=34, side=5, scumble=0.2,+ edge=0.45, mix=(shade, 0.14), passes=2, stroke_len=Wd * 0.26, seed=int(r.integers(1 << 30)))+ # streaks of the jacket colour dragged over the dark half+ for _ in range(3):+ x0 = midx - ls * r.uniform(0.1, 0.42) * Wd # on the dark half, whichever side it is+ y0 = r.uniform(nyp + 0.1 * Wd, bottom - 0.1 * Wd)+ a = np.deg2rad(r.uniform(-120, -60))+ Lh = r.uniform(0.08, 0.2) * Wd+ self.stroke([(x0 - np.cos(a) * Lh, y0 - np.sin(a) * Lh), (x0 + np.cos(a) * Lh, y0 + np.sin(a) * Lh)],+ r.uniform(0.03, 0.06) * Wd, shade, load=0.8, dry=0.7, clip=Ms, seed=int(r.integers(1 << 30)))+ # shirt V and lapels+ vh = lapel * Wd * 0.9+ sv = [(nxp - open_ * Wd, nyp - 6), (nxp + open_ * Wd, nyp - 6), (nxp + 0.01 * Wd, nyp + vh)]+ self.slab(self.poly(sv), shirt, -90, load=0.97, dry=0.4, lane=open_ * Wd, fringe=10, side=3, scumble=0.3,+ seed=int(r.integers(1 << 30)))+ for k in (-1, 1):+ lp = [(nxp + k * open_ * Wd, nyp - 8), (nxp + k * (open_ + 0.12) * Wd, nyp + 0.02 * Wd),+ (nxp + k * 0.05 * Wd, nyp + vh * 1.08), (nxp + k * 0.01 * Wd, nyp + vh * 0.98)]+ col = shade if (k < 0) == (ls < 0) else dark+ self.slab(self.poly(lp), col, -90 + k * 25, load=0.98, dry=0.35, lane=0.05 * Wd, fringe=10, side=2.5,+ scumble=0.2, mix=(lit, 0.15), seed=int(r.integers(1 << 30)))+ if collar:+ cl = [(nxp - (open_ + 0.06) * Wd, nyp - 0.07 * Wd), (nxp + (open_ + 0.06) * Wd, nyp - 0.07 * Wd),+ (nxp + (open_ + 0.04) * Wd, nyp + 0.01 * Wd), (nxp - (open_ + 0.04) * Wd, nyp + 0.01 * Wd)]+ self.slab(self.poly(cl), collar, 0, load=0.98, dry=0.4, lane=0.04 * Wd, fringe=8, side=2,+ seed=int(r.integers(1 << 30)))+ return J++ def sleeve(self, path, w0, w1=None, colour='navy', angle=None, mix=None, seed=None, **kw):+ """an arm / sleeve: a tapering band brushed along its own direction"""+ P = np.asarray(path, np.float32)+ a = np.degrees(np.arctan2(P[-1, 1] - P[0, 1], P[-1, 0] - P[0, 0])) if angle is None else angle+ kw.setdefault('load', 0.98); kw.setdefault('dry', 0.5); kw.setdefault('lane', max(10.0, w0 * 0.35))+ kw.setdefault('fringe', 14); kw.setdefault('side', 4); kw.setdefault('scumble', 0.25)+ kw.setdefault('tines', 0.6)+ return self.slab(self.tube(P, w0, w1), colour, a, mix=mix, seed=seed, **kw)++ def hand(self, x, y, size, angle=0.0, skin='tan', lit='skin_light', shade='umber', grip=True, cuff=None,+ seed=None):+ """a hand seen from the thumb side in a few planes: the lit back of the hand, four stacked finger bands of+ alternating tone (the lowest in shadow) with a dark line between them, a thumb along the top, a dry+ highlight on the knuckles and an optional cuff at the wrist. (x, y) is the centre, angle the direction the+ fingers point (deg); grip=True curls the fingers into a fist (chopsticks), False lays them out longer+ (holding a bowl). Returns the hand mask."""+ r = self._r(seed)+ P = self._frame(x, y, size, size * 0.85, angle)+ reach = 0.92 if grip else 1.35+ back = [(-1.0, -0.4), (-0.2, -0.56), (0.45, -0.56), (0.45, 0.62), (-0.2, 0.55), (-0.95, 0.38)]+ Mb = self.poly(P(back), smooth=True)+ self.slab(Mb, lit, angle, load=0.985, dry=0.4, lane=size * 0.14, fringe=8, side=3, scumble=0.3, edge=0.35,+ mix=(skin, 0.3), seed=int(r.integers(1 << 30)))+ M = Mb+ bands = ((-0.44, -0.14), (-0.14, 0.16), (0.16, 0.46), (0.46, 0.76))+ cols = (skin, lit, skin, shade)+ for i, (v0, v1) in enumerate(bands):+ x1 = reach - 0.06 * i * (1 if grip else -1)+ f = [(0.28, v0 + 0.02), (x1 - 0.12, v0), (x1, v0 + 0.06), (x1 + 0.04, (v0 + v1) / 2), (x1, v1 - 0.04),+ (x1 - 0.12, v1), (0.28, v1 - 0.02)]+ Mf = self.poly(P(f), smooth=True)+ self.slab(Mf, cols[i], angle, load=0.98, dry=0.4, lane=size * 0.08, fringe=6, side=2, scumble=0.3,+ mix=(shade, 0.25) if i == 2 else None, seed=int(r.integers(1 << 30)))+ if i:+ self.stroke([P([(0.34, v0)])[0], P([(x1 - 0.08, v0 + 0.01)])[0]], size * 0.04, 'brown', load=0.85,+ dry=0.45, taper=(0.1, 0.35), seed=int(r.integers(1 << 30)))+ M = np.maximum(M, Mf)+ # thumb along the top, a crease, a dry knuckle highlight+ th = [(-0.6, -0.46), (0.1, -0.7), (0.6, -0.72), (0.74, -0.58), (0.3, -0.44), (-0.4, -0.3)]+ Mt = self.poly(P(th), smooth=True)+ self.slab(Mt, lit, angle - 8, load=0.96, dry=0.4, lane=size * 0.08, fringe=6, side=2, mix=(skin, 0.3),+ seed=int(r.integers(1 << 30)))+ self.stroke([P([(-0.2, -0.44)])[0], P([(0.55, -0.56)])[0]], size * 0.035, shade, load=0.8, dry=0.5,+ seed=int(r.integers(1 << 30)))+ self.stroke([P([(0.3, -0.3)])[0], P([(0.36, 0.4)])[0]], size * 0.07, 'cream', load=0.7, dry=0.65,+ seed=int(r.integers(1 << 30)))+ M = np.maximum(M, Mt)+ if cuff:+ cf = [(-1.14, -0.46), (-0.88, -0.5), (-0.86, 0.5), (-1.12, 0.46)]+ self.slab(self.poly(P(cf)), cuff, angle + 90, load=0.97, dry=0.4, lane=size * 0.1, fringe=6,+ side=2, scumble=0.3, seed=int(r.integers(1 << 30)))+ return M++ # ================================================================== vessels+ def bottle(self, x, base, w, h, colour='forest', shoulder=0.42, neck=0.3, neck_w=0.34, lip=0.05,+ dark='ink', light='sage', label=None, label2=None, cap=None, glass=False, angle=-90.0, seed=None):+ """a bottle silhouette standing on y = base: body, curved shoulder, neck and lip, brushed vertically, with a+ dark side, one light streak, an optional label block ((colour, y0, y1) as fractions of the height from the+ base), a second small block on the label and a cap colour. glass=True paints it as pale glass (multiply)."""+ r = self._r(seed)+ hw, nw = w / 2, w * neck_w / 2+ ys = base - h * (1 - shoulder - neck - lip) # top of the straight body+ yn = base - h * (1 - neck - lip) # bottom of the neck+ yt = base - h+ pts = [(x - hw, base), (x - hw, ys)]+ for t in np.linspace(0, 1, 9)[1:]:+ pts.append((x - hw + (hw - nw) * (1 - np.cos(t * np.pi / 2)) ** 1.0 * 1.0 - 0 * t,+ ys + (yn - ys) * np.sin(t * np.pi / 2)))+ pts += [(x - nw, yt + h * lip), (x - nw * 1.15, yt + h * lip * 0.9), (x - nw * 1.15, yt), (x + nw * 1.15, yt),+ (x + nw * 1.15, yt + h * lip * 0.9), (x + nw, yt + h * lip)]+ for t in np.linspace(0, 1, 9)[::-1][1:]:+ pts.append((x + hw - (hw - nw) * (1 - np.cos(t * np.pi / 2)), ys + (yn - ys) * np.sin(t * np.pi / 2)))+ pts += [(x + hw, ys), (x + hw, base)]+ B = self.poly(pts)+ mode = 'multiply' if glass else 'opaque'+ self.slab(B, colour, angle, load=0.985, dry=0.4, lane=w * 0.22, fringe=10, side=2.5, tines=0.6, scumble=0.25,+ edge=0.3, mix=(dark, 0.12) if (dark and not glass) else None, mode=mode, direction=1,+ seed=int(r.integers(1 << 30)))+ if not glass and dark:+ ds = B * self.poly([(x + hw * 0.35, yt - 5), (x + hw + 20, yt - 5), (x + hw + 20, base + 5), (x + hw * 0.3, base + 5)])+ self.slab(ds, dark, angle, load=0.95, dry=0.5, lane=w * 0.12, fringe=12, side=2, scumble=0.3, alpha=0.9,+ direction=1, seed=int(r.integers(1 << 30)))+ if light:+ lx = x - hw * 0.45+ self.stroke([(lx, base - h * 0.08), (lx + 1, ys + h * 0.02), (x - nw * 0.4, yn + h * 0.04)],+ max(4.0, w * 0.09), light, load=0.9, dry=0.55, taper=(0.1, 0.3), seed=int(r.integers(1 << 30)))+ if cap:+ self.slab(self.rect(x - nw * 1.2, yt - 2, x + nw * 1.2, yt + h * (lip + 0.04)), cap, 0, load=0.98, dry=0.3,+ lane=8, fringe=4, side=1.5, seed=int(r.integers(1 << 30)))+ if label:+ col, f0, f1 = label+ y0, y1 = base - h * f1, base - h * f0+ self.slab(self.rect(x - hw * 0.98, y0, x + hw * 0.98, y1), col, 0, load=0.985, dry=0.3, lane=(y1 - y0) * 0.5,+ fringe=8, side=1.5, scumble=0.2, seed=int(r.integers(1 << 30)))+ if label2:+ col2, fx0, fx1, fy0, fy1 = label2+ self.slab(self.rect(x - hw + w * fx0, y0 + (y1 - y0) * fy0, x - hw + w * fx1, y0 + (y1 - y0) * fy1), col2,+ 90, load=0.99, dry=0.2, lane=w, fringe=0, side=0.8, scumble=0.1, seed=int(r.integers(1 << 30)))+ return B++ def bowl(self, cx, rim_y, w, h, colour='white', band='teal', inside='bone', shade='bone', foot=0.42, seed=None):+ """a bowl seen a little from above: the rim ellipse with what is inside, a body that curves in to a foot,+ a band of colour under the rim and a shadow side. Returns (body mask, inside mask)."""+ r = self._r(seed)+ ry = h * 0.16+ top = self.ellipse(cx, rim_y, w / 2, ry)+ body = [(cx - w / 2, rim_y)]+ n = 16+ for k in range(n + 1):+ s = k / n+ xs = (w / 2) * (1 - (1 - foot) * s ** 1.6)+ body.append((cx - xs, rim_y + h * s * 0.92))+ body += [(cx - w * foot / 2, rim_y + h), (cx + w * foot / 2, rim_y + h)]+ for k in range(n, -1, -1):+ s = k / n+ xs = (w / 2) * (1 - (1 - foot) * s ** 1.6)+ body.append((cx + xs, rim_y + h * s * 0.92))+ Bm = self.poly(body)+ self.slab(Bm, colour, -6, load=1.05, dry=0.12, lane=h * 0.22, fringe=4, side=2, scumble=0.06, edge=0.08,+ tines=0.4, seed=int(r.integers(1 << 30)))+ sd = Bm * self.poly([(cx + w * 0.14, rim_y - 5), (cx + w, rim_y - 5), (cx + w, rim_y + h + 5), (cx + w * 0.02, rim_y + h + 5)])+ self.slab(sd, shade, -78, load=1.0, dry=0.45, lane=h * 0.16, fringe=10, side=2, scumble=0.3, edge=0.5,+ seed=int(r.integers(1 << 30)))+ if band:+ bd = Bm * self.poly([(cx - w, rim_y + h * 0.14), (cx + w, rim_y + h * 0.14), (cx + w, rim_y + h * 0.3),+ (cx - w, rim_y + h * 0.3)])+ self.slab(bd, band, 0, load=0.975, dry=0.4, lane=h * 0.16, fringe=6, side=1.5, scumble=0.25,+ seed=int(r.integers(1 << 30)))+ inner = self.ellipse(cx, rim_y + ry * 0.12, w / 2 * 0.94, ry * 0.8)+ self.slab(top, colour, 0, load=1.04, dry=0.2, lane=ry, fringe=6, side=1.5, seed=int(r.integers(1 << 30)))+ self.slab(inner, inside, 0, load=1.0, dry=0.35, lane=ry * 0.6, fringe=8, side=1.5, scumble=0.25,+ seed=int(r.integers(1 << 30)))+ return Bm, inner++ def cup(self, cx, base, w, h, colour='celadon', glass=True, level=0.62, tea='khaki', rim='white', seed=None):+ """a tall drinking glass / cup: a tapering block (pale glass is laid as multiply), the tea level, a rim"""+ r = self._r(seed)+ pts = [(cx - w * 0.5, base - h), (cx + w * 0.5, base - h), (cx + w * 0.42, base), (cx - w * 0.42, base)]+ G = self.poly(pts)+ self.slab(G, colour, -90, load=0.97, dry=0.4, lane=w * 0.25, fringe=10, side=2, scumble=0.35, edge=0.4,+ mode='multiply' if glass else 'opaque', seed=int(r.integers(1 << 30)))+ if tea:+ tl = base - h * level+ T_ = G * self.poly([(cx - w, tl), (cx + w, tl), (cx + w, base + 4), (cx - w, base + 4)])+ self.slab(T_, tea, 0, load=0.95, dry=0.45, lane=w * 0.2, fringe=8, side=2, scumble=0.35, alpha=0.75,+ mode='multiply', seed=int(r.integers(1 << 30)))+ if rim:+ self.stroke([(cx - w * 0.48, base - h + 3), (cx + w * 0.48, base - h + 3)], max(3.0, w * 0.05), rim, load=0.9,+ dry=0.5, seed=int(r.integers(1 << 30)))+ self.stroke([(cx - w * 0.3, base - h * 0.85), (cx - w * 0.26, base - h * 0.2)], max(3.0, w * 0.06), rim,+ load=0.8, dry=0.6, seed=int(r.integers(1 << 30)))+ return G++ # ================================================================== finish+ def printed(self, amount=1.0):+ """reproduce like an offset print of the painting: slight softness, paper grain, sparse knocked-out specks+ in the darks and sparse dust on the paper (applied in render())"""+ self.print_amt = float(amount)++ def render(self):+ out = self.C.copy()+ p = self.print_amt+ if p:+ soft = np.stack([blur(out[..., i], 0.65) for i in range(3)], -1)+ out = out * (1 - 0.35 * p) + soft * 0.35 * p+ if not hasattr(self, '_print'):+ r = np.random.default_rng(self.seed + 7)+ H, W = self.H, self.W+ g = r.normal(0, 1, (H, W)).astype(np.float32)+ g = 0.55 * g + 0.45 * blur(g, 1.0) * 2.2+ fib = _blur1(r.normal(0, 1, (H, W)).astype(np.float32), 4.0, 1) * 1.6+ # knocked-out specks: small clusters, sparse; dust: sparser, smaller+ sp = blur((r.random((H, W)) < 0.0016).astype(np.float32), 0.8)+ sp = smoothstep(0.05, 0.22, sp) * smoothstep(0.35, 0.7, noise2d(H, W, 90, 2, self.seed + 8))+ du = smoothstep(0.08, 0.3, blur((r.random((H, W)) < 0.00025).astype(np.float32), 0.6))+ self._print = (g, fib, sp, du)+ g, fib, sp, du = self._print+ lum = out.mean(-1, keepdims=True)+ dark = smoothstep(0.75, 0.3, lum)+ out = out * (1 + p * (0.016 * g + 0.006 * fib)[..., None])+ out = out + (hexc('paper') - out) * (p * 0.75 * sp[..., None] * dark)+ out = out + (hexc('#3b3a33') - out) * (p * 0.45 * du[..., None] * (1 - dark))+ return np.clip(out, 0, 1)++ def composite(self):+ return Image.fromarray((self.render() * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ if not self.keep_stages: return+ im = self.composite()+ if self.stages_dir:+ os.makedirs(self.stages_dir, exist_ok=True)+ im.save(f'{self.stages_dir}/{self._n_stages:02d}_{name}.png', compress_level=1)+ else:+ b = io.BytesIO(); im.save(b, 'PNG', compress_level=1)+ self.stages.append((name, b.getvalue()))+ self._n_stages += 1++ 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)+ sd = stages_dir or self.stages_dir+ if sd and self.keep_stages:+ os.makedirs(sd, exist_ok=True)+ for i, (name, b) in enumerate(self.stages):+ with open(f'{sd}/{i:02d}_{name}.png', 'wb') as f: f.write(b)+ img.save(f'{sd}/{self._n_stages:02d}_final.png', compress_level=1)+ return imgdiff --git a/lib/twilight.py b/lib/twilight.pynew file mode 100644index 0000000..1af28ee--- /dev/null+++ b/lib/twilight.py@@ -0,0 +1,1490 @@+"""twilight — 暮色绘本 / Twilight Storybook: a dreamy dusk picture-book page full of miniature detail (numpy + Pillow only).++The look: a tender, wistful picture-book illustration of the hour when day turns to night. A big pastel dusk sky+(lavender at the top, rose and peach in the middle, warm gold at the horizon) with soft, flat-bottomed cloud bands+and a low pale sun; on one side the sky gives way to a deep night with a field of stars, a Milky Way band with its+dark rift, a crescent moon and a shooting star. Below, rolling hills in soft stacked pastel stripes (patchwork+fields, crop rows, tiny round trees) and in front a meadow made of thousands of tiny wildflowers -- specks near+the crest, then small rosettes, then big daisies, cornflowers, poppies, cosmos and lupins at the bottom edge --+with grass ticks between them. Very small, flat, cute characters. Over it all the language of a scientific plate:+a circular magnified "detail a" inset drawn in fine ink linework with hatching, dimension ticks and labels, and+tiny lowercase handwritten captions in grey. Soft grain, a gentle vignette, a torn paper edge.++Physical model+ dusk sky A vertical gradient through six stops measured against the horizon row. The stop positions are+ warped by a horizontally stretched low-frequency noise, so the colours lie in soft horizontal layers,+ not a ruler-straight ramp, and a fine mottle (a few percent) gives the airbrushed paper softness.+ Clouds are lens-shaped bands: a lumpy, soft top that fades out and a flatter, sharper bottom, denser+ (darker) toward the bottom, half transparent; thin pale light streaks lie under them. The sun is a pale+ disc with a two-scale glow, painted before the hills so they cut it.+ night `night_split()` defines a field N (0 dusk .. 1 night) across the canvas from a wandering boundary line+ with a wide, feathered transition. Night paint (gradient, Milky Way, stars, moon) is laid with N as its+ alpha, so stars thin out and fade across the boundary instead of stopping at a line; near the boundary+ the night colour leans indigo, so dusk peach -> mauve -> indigo -> black. Every later "lit" paint+ call (hills, meadow, figures) is shaded by the same field: the colour is pulled toward a desaturated,+ moonlit blue by a linear 3x3 grade (luminance desaturation then a cool tint) weighted by N, so a+ white daisy on the night side becomes a pale moonlit blue and the grass a dark slate. Emissive things+ (stars, fireflies, the lantern, the shooting star) and the plate overlay are painted unlit.+ milky way An analytic band between two points with a gentle bend and a wandering centre; its density is a+ gaussian across the band times two scales of cloudy noise; a narrower dark rift wanders inside it; a few+ thousand faint stars are sampled with probability proportional to the band density.+ stars Positions uniform, brightness from a power law (many faint, few bright), a few warm and a few blue.+ Every star is splatted with sub-pixel accuracy: a disc-coverage kernel for big stars, a mass-preserving+ gaussian for sub-pixel ones, accumulated with bincount. The brightest get a little glow; `sparkle()` adds+ the four-point cross with long tapered rays and short diagonals.+ hills Distant ranges are filled ridges (analytic anti-aliased edge per column) going lighter toward their base+ (mist pooled in the valleys). Striped hills are layered bands that follow the ridge, getting wider toward+ the viewer (perspective); each band is cut into slanted patchwork fields of pastel colours, some fields+ carry fine crop rows parallel to the band, there are thin darker hedge lines between bands and fields and+ a pale rim of light along the crest. `trees()` puts tiny round trees (shadow, trunk, crown, highlight).+ meadow The ground is a sage-to-olive gradient with mottle and fine flecks, and a lit rim along the crest that+ goes gold -> silver across the night boundary. Plants are sampled by rejection so that the screen+ coverage follows perspective: size grows with depth below the crest (size ~ t^1.9), density ~ coverage /+ (pi size^2), so the crest is thousands of specks and the bottom a few dozen big flowers. The species mix+ drifts across the meadow with low-frequency noise (patches of daisies, a blue drift of cornflowers). By+ size a flower is a speck (one dot), a rosette with an eye, or a full head: daisy (12-16 elongated+ petals, yellow eye), cornflower (toothed wedge florets), poppy (four cupped round petals, dark eye with+ stamens), cosmos (notched petals), marigold (two rings), buttercup, lupin spike (florets shrinking up the+ spike), forget-me-not cluster -- each with a thin stem and, when big, a leaf. Heads are foreshortened+ (squashed vertically) and petals pointing away are painted first. Grass blades are sampled the same way+ (tiny ticks far, long blades near). Everything is collected as polygons, sorted by the y of its base and+ rasterised in one go into a supersampled integer id map (painter's order = id order), coloured through a+ lookup table and box-averaged back, so tens of thousands of anti-aliased shapes cost well under a second.+ figures Flat, cute picture-book characters built from smooth polygons: `wanderer()` is a small hooded child in a+ felt-textured cloak with a floppy hood tip and pompom, a round cream face, dot eyes with a glint, blush,+ mittens and boots, a warm rim on the sunset side and a thin darker outline; `jar_lantern()` is a glass jar+ of fireflies that glows and lights the grass round it; `kite()` is a four-panel diamond kite with spars,+ bridle and a streaming tail of bows; `kite_string()` sags a little and goes from dark (dusk) to silver+ (night) along its length. `fireflies()`, `butterfly()`, `dragonfly()`, `seeds()` (dandelion parachutes)+ and `birds()` are the small things that reward a close look.+ plate Fine ink lines are polylines drawn at 3x into a mask with a slight hand wobble and optional taper, then+ box-reduced, so a 0.8 px hairline stays smooth. `hatch()` lays parallel hand lines clipped to a shape+ (cross-hatch by calling twice), `dimension()` draws extension lines, a dimension line with architect's+ ticks and a small label, `ruler()` a little scale, `wash()` a flat watercolour tint with a darker edge.+ `inset()` is the circular magnified view: a paper disc with a faint shadow, whatever the callback draws+ inside it (clipped), a thin double ring, a marker ring on the target and a leader line, and the label.+ captions Tiny lowercase handwriting from a thin hand font (Noteworthy Light on macOS, or $INKPAINT_FONT_HAND_LIGHT)+ set glyph by glyph: each letter gets its own small rotation, baseline wobble, spacing and pressure, the+ strokes are rendered at 2x and reduced, and a faint pencil texture runs through them.+ finish `finish()`: a slight softness, bloom around the light sources, fine film / paper grain and a larger soft+ mottle, a gentle vignette leaning plum, and optionally a torn cream paper strip along the bottom edge.++API (canvas px; colours are names in COLOURS or '#rrggbb'; angles in radians unless noted)+ surface TwilightStorybook(W, H, seed, keep_stages, stages_dir); clipped(mask) / unlit() contexts+ low level lines(paths, width, colour, alpha, wobble, taper); fill(mask, colour, alpha); ellipse(cx, cy, rx, ry);+ poly(pts); glow(x, y, r, colour, strength); splat(xs, ys, rad, colours, alpha)+ sky dusk_sky(stops, horizon, mottle); cloud(x0, x1, y, h, colour, alpha); streak(x0, x1, y); sun(x, y, r);+ mist(y0, y1, y2, colour, strength); birds(pts, size); seeds(pts, size)+ night night_split(edge, soft, ground); night_sky(top, low); milky_way(p0, p1, width, bend, rift, stars);+ stars(n, region, sparkles, dusk); sparkle(x, y, size); moon(x, y, r, phase); shooting_star(p0, p1)+ land hills(ridge, colour, base, fade, rim); striped_hill(ridge, colours, stripe, grow, fields, rows) -> info;+ trees(pts, size); meadow(crest, size, density, grass, kinds, drifts) -> info+ figures wanderer(x, y, s, facing, reach) -> hand xy; jar_lantern(x, y, s); kite(cx, cy, size, tilt, tail) -> bridle+ xy; kite_string(p0, p1, sag); fireflies(pts, size, trails); butterfly(x, y, s, colour); dragonfly(x, y, s)+ plate hatch(shape, angle, spacing, width); dimension(p0, p1, text, offset); ruler(x0, y, x1); wash(pts, colour);+ leader(p0, p1); inset(cx, cy, r, draw, target, label, sub)+ text caption(x, y, text, size, colour, anchor, rot)+ finish finish(grain, vignette, bloom, edge); render(); composite(); stage(name); save(path, stages_dir)++ import sys; sys.path.insert(0, 'lib')+ from twilight import TwilightStorybook+ t = TwilightStorybook(2000, 1100, seed=3)+ t.dusk_sky(horizon=700); t.sun(480, 670, 34)+ t.night_split([(1350, 0), (1500, 700)], soft=160)+ t.night_sky(); t.milky_way((1500, -40), (2000, 600)); t.stars(1600)+ t.striped_hill([(0, 740), (1000, 715), (2000, 730)])+ t.meadow([(0, 830), (1250, 745), (2000, 805)])+ hand = t.wanderer(1250, 748, 90)+ t.caption(120, 170, 'the evening waits for us.')+ t.finish(); t.save('twilight.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, fbm1d, spline, noise2d, smoothstep, load_font+++COLOURS = {+ # dusk sky+ 'lavender': '#b3afd0', 'lilac': '#c9bcd6', 'rose': '#dcbfca', 'peach': '#e9bba6', 'apricot': '#efc9a8',+ 'gold': '#f2d8ae', 'sun': '#fcf2df', 'cloud': '#9c8ba9', 'cloud_low': '#c09798', 'streak': '#f8e8cf',+ # night+ 'night': '#121219', 'night_low': '#2d2a3f', 'indigo': '#38346a', 'star': '#f8f5ee', 'moon': '#f5efdc',+ 'milk': '#c2bccd',+ # land+ 'mauve': '#bea59f', 'mauve_dark': '#a48c8e', 'haze': '#ead2b8', 'rim': '#f6e1b4', 'silver': '#c9cde0',+ 'meadow': '#5c6242', 'meadow_far': '#8d8a6a', 'meadow_near': '#4a5134', 'grass': '#3a4329', 'tree': '#55693f',+ 'tree_light': '#8da363', 'trunk': '#5a4636',+ 'field_sage': '#a8a886', 'field_lav': '#ab9fbd', 'field_wheat': '#cbb594', 'field_green': '#8c946c',+ 'field_rose': '#c4a3a0',+ # line, paper, captions+ 'ink': '#3d383f', 'pencil': '#6e6670', 'caption': '#75687a', 'paper': '#f4ecdf', 'pale': '#d9d2d4',+ # flowers+ 'daisy': '#f8f4ec', 'cornflower': '#5072cc', 'poppy': '#d9442f', 'cosmos': '#e899b4', 'marigold': '#ee9a33',+ 'buttercup': '#f2c94b', 'lupine': '#8f77c8', 'forgetmenot': '#86a7e4', 'eye': '#e5b03a', 'stem': '#3f4b2c',+ # figures+ 'cloak': '#5f80c2', 'cloak_dark': '#3f5891', 'face': '#f7ecdb', 'cheek': '#ec9690', 'boot': '#3a3335',+ 'mitten': '#e9b44c', 'kite': '#e2705c', 'kite_cream': '#f6e6ca', 'spar': '#8b6b4d', 'string': '#5d5360',+ 'lantern': '#ffd27a', 'firefly': '#f1f59a', 'glass': '#efe4cf',+}++SPECIES = ('daisy', 'cornflower', 'poppy', 'cosmos', 'marigold', 'buttercup', 'lupine', 'forgetmenot')+MIX = {'daisy': 0.24, 'cornflower': 0.15, 'poppy': 0.09, 'cosmos': 0.13, 'marigold': 0.08, 'buttercup': 0.12,+ 'lupine': 0.07, 'forgetmenot': 0.12}+PETALS = { # per species: list of (colour, weight) for the petals+ 'daisy': [('#f8f4ec', 6), ('#f4eee6', 3), ('#efe2ee', 1)],+ 'cornflower': [('#5072cc', 4), ('#5d80d9', 3), ('#4561b5', 2), ('#7393de', 1)],+ 'poppy': [('#d9442f', 4), ('#e3563a', 3), ('#c9372b', 2), ('#ea6f3f', 1)],+ 'cosmos': [('#e899b4', 4), ('#dc7aa0', 2), ('#f2c3d2', 2), ('#f6ebee', 1)],+ 'marigold': [('#ee9a33', 4), ('#f1ab3e', 3), ('#e5822a', 2)],+ 'buttercup': [('#f2c94b', 4), ('#f5d660', 2), ('#eab73b', 1)],+ 'lupine': [('#8f77c8', 4), ('#a48fd6', 2), ('#7a63b6', 2), ('#d394bd', 1)],+ 'forgetmenot': [('#86a7e4', 4), ('#9cb8ec', 2), ('#a99ad9', 1)],+}+EYES = {'daisy': '#e5b03a', 'cornflower': '#2c2f5a', 'poppy': '#2a1e22', 'cosmos': '#e3b23d', 'marigold': '#9c4f1d',+ 'buttercup': '#d99a22', 'lupine': None, 'forgetmenot': '#f3e27a'}+GRASS = ['#3b4429', '#47512f', '#56613a', '#6c7445', '#8b9156', '#a3a263']++_LUMA = np.array([0.3, 0.59, 0.11], np.float32)+++def hexc(c):+ """'#rrggbb', a COLOURS name or an RGB triple -> float32 RGB 0..1"""+ if not isinstance(c, str): return np.asarray(c, np.float32)+ h = COLOURS.get(c, c).lstrip('#')+ return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255+++def mix(a, b, t):+ a, b = hexc(a), hexc(b)+ return (a + (b - a) * t).astype(np.float32)+++def _night_matrix(tint=(0.24, 0.27, 0.43), desat=0.6):+ S = (1 - desat) * np.eye(3, dtype=np.float32) + desat * np.ones((3, 1), np.float32) @ _LUMA[None]+ return (np.diag(np.asarray(tint, np.float32)) @ S).astype(np.float32)+++def _resample(P, step):+ P = np.asarray(P, np.float32)+ seg = np.hypot(*np.diff(P, axis=0).T)+ s = np.concatenate([[0], np.cumsum(seg)])+ if s[-1] < 1e-3: return P[:1]+ n = max(2, int(np.ceil(s[-1] / step)) + 1)+ ss = np.linspace(0, s[-1], n)+ return np.stack([np.interp(ss, s, P[:, 0]), np.interp(ss, s, P[:, 1])], 1).astype(np.float32)+++def _ell(cx, cy, rx, ry=None, n=14, rot=0.0):+ ry = rx if ry is None else ry+ t = np.linspace(0, 2 * np.pi, n, endpoint=False)+ x, y = np.cos(t) * rx, np.sin(t) * ry+ c, s = np.cos(rot), np.sin(rot)+ return np.stack([cx + x * c - y * s, cy + x * s + y * c], 1).astype(np.float32)+++def _tube(path, w0, w1=None, per=6):+ """outline polygon of a thick path (width w0 -> w1)"""+ P = np.asarray(path, np.float32)+ Q = spline(P, per) if len(P) > 2 else _resample(P, max(1.0, np.hypot(*(P[-1] - P[0])) / 6))+ w1 = w0 if w1 is None else w1+ d = np.gradient(Q, axis=0); d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-6+ nrm = np.stack([-d[:, 1], d[:, 0]], 1)+ hw = np.linspace(w0, w1, len(Q))[:, None] / 2+ return np.vstack([Q + nrm * hw, (Q - nrm * hw)[::-1]]).astype(np.float32)+++def _grid_sample(G, u, v):+ """bilinear sample of a small grid G (gh, gw) at u, v in 0..1"""+ gh, gw = G.shape+ x = np.clip(u, 0, 1) * (gw - 1); y = np.clip(v, 0, 1) * (gh - 1)+ x0 = np.minimum(x.astype(int), gw - 2); y0 = np.minimum(y.astype(int), gh - 2)+ fx, fy = x - x0, y - y0+ return (G[y0, x0] * (1 - fx) * (1 - fy) + G[y0, x0 + 1] * fx * (1 - fy) ++ G[y0 + 1, x0] * (1 - fx) * fy + G[y0 + 1, x0 + 1] * fx * fy)+++def _pick(r, table, n):+ cols = np.stack([hexc(c) for c, _ in table]); w = np.array([w for _, w in table], np.float32)+ return cols[r.choice(len(table), n, p=w / w.sum())]+++class _Polys:+ """collects polygons with colour, alpha and a sort key (painter's order)"""+ def __init__(self):+ self.P, self.c, self.a, self.k = [], [], [], []++ def add(self, pts, colour, alpha=1.0, key=0.0):+ self.P.append(np.asarray(pts, np.float32)); self.c.append(hexc(colour)); self.a.append(alpha); self.k.append(key)++ def group(self, sort=True):+ if not self.P: return None+ idx = np.argsort(np.asarray(self.k), kind='stable') if sort else np.arange(len(self.P))+ return ([self.P[i] for i in idx], np.stack(self.c)[idx], np.asarray(self.a, np.float32)[idx])+++class TwilightStorybook:+ COLOURS = COLOURS++ def __init__(self, W=2000, H=1100, seed=0, keep_stages=True, stages_dir=None):+ if W * H > 4096 * 4096: raise ValueError('canvas larger than 4096 x 4096')+ self.W, self.H, self.seed = W, H, seed+ self.rng = np.random.default_rng(seed)+ self.keep_stages, self.stages_dir = keep_stages, stages_dir+ self.stages, self._n_stages = [], 0+ self.C = np.empty((H, W, 3), np.float32); self.C[:] = hexc('gold')+ r = np.random.default_rng(seed + 11)+ t = blur(r.random((H, W)).astype(np.float32), 0.6)+ self.TX = ((t - t.mean()) / (t.std() + 1e-6)).astype(np.float32) # fine tooth inside the paint+ self.N = np.zeros((H, W), np.float32) # 0 dusk .. 1 night (land: x ground)+ self._Nsky = self.N+ self.NM = _night_matrix()+ self.horizon = H * 0.64+ self._clip, self._lit = None, True+ self.fin = None++ def _r(self, seed=None):+ return np.random.default_rng(int(self.rng.integers(1 << 30)) if seed is None else seed)++ # ================================================================== light, clip, composite+ @contextmanager+ def clipped(self, mask):+ """paint only inside a full-canvas mask (the inside of the detail inset)"""+ old = self._clip+ self._clip = mask if old is None else mask * old+ try: yield+ finally: self._clip = old++ @contextmanager+ def unlit(self):+ """paint without the night grade (emissive things, the plate overlay)"""+ old = self._lit; self._lit = False+ try: yield+ finally: self._lit = old++ def _light(self, P, ys, xs):+ """pull colours (or premultiplied colours) toward moonlit blue by the night field"""+ n = self.N[ys, xs]+ if float(n.max()) < 1e-3: return P+ return P + (P @ self.NM.T - P) * n[..., None]++ def _comp(self, A, colour, sl, lit=None):+ lit = self._lit if lit is None else lit+ ys, xs = sl+ if self._clip is not None: A = A * self._clip[ys, xs]+ Cs = self.C[ys, xs]+ if isinstance(colour, np.ndarray) and colour.ndim == 3: col = colour+ else: col = np.broadcast_to(hexc(colour), Cs.shape)+ if lit: col = self._light(col, ys, xs)+ Cs += (col - Cs) * A[..., None]++ def fill(self, mask, colour, alpha=1.0, sl=None, lit=None):+ """flat paint through a float mask (full canvas, or a local mask placed at the region sl)"""+ sl = sl or (slice(None), slice(None))+ A = mask[sl] * alpha if mask.shape[:2] == self.C.shape[:2] and sl != (slice(None), slice(None)) else mask * alpha+ self._comp(A, colour, sl, lit)++ def _paint(self, groups, ss=2, tex=0.03, lit=None):+ """rasterise groups of polygons in order: [(P, colours, alpha), ...]; P is (N, k, 2) or a list of (k, 2)"""+ lit = self._lit if lit is None else lit+ groups = [g for g in groups if g is not None and len(g[0])]+ if not groups: return+ lo = np.array([1e9, 1e9]); hi = np.array([-1e9, -1e9])+ for P, _, _ in groups:+ if isinstance(P, np.ndarray):+ lo = np.minimum(lo, P.reshape(-1, 2).min(0)); hi = np.maximum(hi, P.reshape(-1, 2).max(0))+ else:+ allp = np.concatenate([np.asarray(p, np.float32).reshape(-1, 2) for p in P])+ lo = np.minimum(lo, allp.min(0)); hi = np.maximum(hi, allp.max(0))+ x0, y0 = max(0, int(np.floor(lo[0])) - 1), max(0, int(np.floor(lo[1])) - 1)+ x1, y1 = min(self.W, int(np.ceil(hi[0])) + 2), min(self.H, int(np.ceil(hi[1])) + 2)+ if x1 <= x0 or y1 <= y0: return+ w, h = x1 - x0, y1 - y0+ im = Image.new('I', (w * ss, h * ss), 0)+ d = ImageDraw.Draw(im)+ cols_all, alph_all = [np.zeros((1, 3), np.float32)], [np.zeros(1, np.float32)]+ idx = 1+ off = np.array([x0, y0], np.float32)+ for P, cols, alpha in groups:+ if isinstance(P, np.ndarray): Q = ((P - off) * ss).reshape(len(P), -1).tolist()+ else: Q = [((np.asarray(p, np.float32) - off) * ss).ravel().tolist() for p in P]+ n = len(Q)+ for q in Q:+ if len(q) >= 6: d.polygon(q, fill=idx)+ idx += 1+ cols_all.append(np.broadcast_to(np.asarray(cols, np.float32), (n, 3)))+ alph_all.append(np.broadcast_to(np.asarray(alpha, np.float32), (n,)))+ cols = np.concatenate(cols_all); alph = np.concatenate(alph_all)+ pal = np.empty((idx, 4), np.float32)+ pal[:, :3] = np.clip(cols, 0, 1) * alph[:, None]; pal[:, 3] = alph+ ids = np.asarray(im)+ for r0 in range(0, h, 128):+ r1 = min(h, r0 + 128)+ look = pal[ids[r0 * ss:r1 * ss]].reshape(r1 - r0, ss, w, ss, 4).mean((1, 3))+ A = look[..., 3]; Pm = look[..., :3]+ ys, xs = slice(y0 + r0, y0 + r1), slice(x0, x1)+ if self._clip is not None:+ f = self._clip[ys, xs]; A = A * f; Pm = Pm * f[..., None]+ if tex: Pm = Pm * (1 + tex * self.TX[ys, xs, None])+ if lit: Pm = self._light(Pm, ys, xs)+ self.C[ys, xs] = self.C[ys, xs] * (1 - A[..., None]) + Pm++ def shapes(self, polys, colours, alpha=1.0, ss=3, tex=0.03, lit=None):+ """paint a list of polygons (one colour each, or one for all)"""+ n = len(polys)+ cols = np.broadcast_to(np.asarray(colours if not isinstance(colours, str) else hexc(colours), np.float32), (n, 3))+ self._paint([(list(polys), cols, alpha)], ss, tex, lit)++ def poly(self, pts, ss=2):+ """full-canvas anti-aliased polygon mask"""+ im = Image.new('L', (self.W * ss, self.H * ss), 0)+ ImageDraw.Draw(im).polygon([(float(x) * ss, float(y) * ss) for x, y in pts], fill=255)+ if ss > 1: im = im.resize((self.W, self.H), Image.BOX)+ return np.asarray(im, np.float32) / 255++ def _local(self, polys, ss=3, pad=3):+ """union of polygons -> (local mask, (slice y, slice x)) over their bounding box"""+ allp = np.concatenate([np.asarray(p, np.float32) for p in polys])+ x0 = max(0, int(allp[:, 0].min()) - pad); y0 = max(0, int(allp[:, 1].min()) - pad)+ x1 = min(self.W, int(allp[:, 0].max()) + pad + 1); y1 = min(self.H, int(allp[:, 1].max()) + pad + 1)+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ d = ImageDraw.Draw(im)+ for p in polys:+ q = (np.asarray(p, np.float32) - [x0, y0]) * ss+ d.polygon([tuple(v) for v in q], fill=255)+ m = np.asarray(im.reduce(ss), np.float32) / 255+ return m, (slice(y0, y1), slice(x0, x1))++ def ellipse(self, cx, cy, rx, ry=None):+ """full-canvas anti-aliased ellipse mask"""+ ry = rx if ry is None else ry+ yy = np.arange(self.H, dtype=np.float32)[:, None]; xx = np.arange(self.W, dtype=np.float32)[None, :]+ dd = np.sqrt(((xx - cx) / rx) ** 2 + ((yy - cy) / ry) ** 2)+ e = 0.8 / max(1.0, min(rx, ry))+ return smoothstep(1 + e, 1 - e, dd).astype(np.float32)++ def _ridge(self, pts):+ """ridge given as control points, a per-column array or a function of x -> y per column"""+ X = np.arange(self.W, dtype=np.float32)+ if callable(pts): return np.asarray(pts(X), np.float32)+ P = np.asarray(pts, np.float32)+ if P.ndim == 1: return P+ Q = spline(P, 24)+ return np.interp(X, Q[:, 0], Q[:, 1]).astype(np.float32)++ # ================================================================== fine lines, glows, splats+ def lines(self, paths, width=1.2, colour='ink', alpha=1.0, wobble=0.0, taper=0.0, ss=3, lit=None, caps=True, seed=None):+ """fine pen lines: polylines drawn at ss x into one mask and box-reduced. width per call or per path;+ wobble = px of slow hand wander; taper = fraction of the length that thins at each end"""+ r = self._r(seed)+ P = []+ for p in paths:+ p = np.asarray(p, np.float32)+ if len(p) < 2: continue+ if wobble or taper:+ p = _resample(p, 2.0)+ if wobble and len(p) > 3:+ dd = np.gradient(p, axis=0); dd /= np.linalg.norm(dd, axis=1, keepdims=True) + 1e-6+ nrm = np.stack([-dd[:, 1], dd[:, 0]], 1)+ off = fbm1d(len(p), max(4.0, len(p) / 2.5), 3, int(r.integers(1 << 30))) * wobble+ p = p + nrm * off[:, None]+ P.append(p)+ if not P: return+ widths = np.broadcast_to(np.asarray(width, np.float32), (len(P),))+ allp = np.concatenate(P); pad = float(widths.max()) * 2 + 3+ x0, y0 = max(0, int(allp[:, 0].min() - pad)), max(0, int(allp[:, 1].min() - pad))+ x1, y1 = min(self.W, int(allp[:, 0].max() + pad) + 1), min(self.H, int(allp[:, 1].max() + pad) + 1)+ if x1 <= x0 or y1 <= y0: return+ im = Image.new('L', ((x1 - x0) * ss, (y1 - y0) * ss), 0)+ d = ImageDraw.Draw(im)+ for p, w in zip(P, widths):+ q = (p - [x0, y0]) * ss+ wp = float(w) * ss+ if taper:+ n = len(q); t = np.linspace(0, 1, n)+ prof = 0.18 + 0.82 * np.clip(np.minimum(t, 1 - t) / taper, 0, 1) ** 0.8+ for i in range(n - 1):+ wi = max(1, int(round(wp * 0.5 * (prof[i] + prof[i + 1]))))+ d.line([tuple(q[i]), tuple(q[i + 1])], fill=255, width=wi)+ if wi >= 3:+ rr = wi / 2; d.ellipse([q[i + 1][0] - rr, q[i + 1][1] - rr, q[i + 1][0] + rr, q[i + 1][1] + rr], fill=255)+ else:+ wi = max(1, int(round(wp)))+ d.line(q.ravel().tolist(), fill=255, width=wi, joint='curve')+ if caps and wi >= 3:+ rr = wi / 2+ for e in (q[0], q[-1]): d.ellipse([e[0] - rr, e[1] - rr, e[0] + rr, e[1] + rr], fill=255)+ m = np.asarray(im.reduce(ss), np.float32) / 255 * alpha+ self._comp(m, colour, (slice(y0, y1), slice(x0, x1)), lit)++ def glow(self, x, y, r, colour='lantern', strength=0.5, squash=1.0):+ """emissive soft light (screen blend, never graded)"""+ R = int(r * 2.6) + 2+ x0, x1 = max(0, int(x) - R), min(self.W, int(x) + R + 1)+ y0, y1 = max(0, int(y) - R), min(self.H, int(y) + R + 1)+ if x1 <= x0 or y1 <= y0: return+ yy = np.arange(y0, y1, dtype=np.float32)[:, None]; xx = np.arange(x0, x1, dtype=np.float32)[None]+ g = strength * np.exp(-(((xx - x) / r) ** 2 + ((yy - y) / (r * squash)) ** 2))+ if self._clip is not None: g = g * self._clip[y0:y1, x0:x1]+ Cs = self.C[y0:y1, x0:x1]+ Cs[:] = 1 - (1 - Cs) * (1 - hexc(colour) * g[..., None])++ def splat(self, xs, ys, rad, colours, alpha=1.0, lit=False):+ """sub-pixel dots (stars, specks, firefly cores): disc coverage for r >= 1, mass-preserving gaussian below"""+ xs = np.asarray(xs, np.float32); ys = np.asarray(ys, np.float32); n = len(xs)+ if n == 0: return+ rad = np.broadcast_to(np.asarray(rad, np.float32), (n,))+ cols = np.broadcast_to(np.asarray(colours if not isinstance(colours, str) else hexc(colours), np.float32), (n, 3))+ al = np.broadcast_to(np.asarray(alpha, np.float32), (n,))+ R = int(np.ceil(float(rad.max()) * 1.6 + 1.5))+ bx0, bx1 = max(0, int(xs.min()) - R - 1), min(self.W, int(xs.max()) + R + 2)+ by0, by1 = max(0, int(ys.min()) - R - 1), min(self.H, int(ys.max()) + R + 2)+ if bx1 <= bx0 or by1 <= by0: return+ bw, bh = bx1 - bx0, by1 - by0+ ix = np.floor(xs).astype(np.int64); iy = np.floor(ys).astype(np.int64)+ fx, fy = xs - ix, ys - iy+ sig = np.maximum(0.42, rad * 0.62)+ mass = np.pi * rad * rad+ LI, KK, CI = [], [], []+ for dy in range(-R, R + 1):+ for dx in range(-R, R + 1):+ d = np.sqrt((dx + 0.5 - fx) ** 2 + (dy + 0.5 - fy) ** 2)+ disc = np.clip(rad + 0.5 - d, 0, 1)+ gau = np.minimum(1.0, mass * np.exp(-d * d / (2 * sig * sig)) / (2 * np.pi * sig * sig))+ k = np.where(rad >= 1.0, disc, gau) * al+ X = ix + dx; Y = iy + dy+ ok = (k > 0.003) & (X >= bx0) & (X < bx1) & (Y >= by0) & (Y < by1)+ if not ok.any(): continue+ LI.append((Y[ok] - by0) * bw + (X[ok] - bx0)); KK.append(k[ok]); CI.append(np.nonzero(ok)[0])+ if not LI: return+ li = np.concatenate(LI); kk = np.concatenate(KK); ci = np.concatenate(CI)+ A = np.bincount(li, kk, bw * bh).reshape(bh, bw).astype(np.float32)+ P = np.stack([np.bincount(li, kk * cols[ci, c], bw * bh).reshape(bh, bw) for c in range(3)], -1).astype(np.float32)+ sc = np.where(A > 1, 1 / np.maximum(A, 1e-6), 1.0)+ A = A * sc; P = P * sc[..., None]+ ys_, xs_ = slice(by0, by1), slice(bx0, bx1)+ if self._clip is not None: A = A * self._clip[ys_, xs_]; P = P * self._clip[ys_, xs_, None]+ if lit: P = self._light(P, ys_, xs_)+ Cs = self.C[ys_, xs_]+ Cs[:] = Cs * (1 - A[..., None]) + P++ # ================================================================== dusk sky+ def dusk_sky(self, stops=None, horizon=None, mottle=1.0, seed=None):+ """the big pastel gradient: lavender -> lilac -> rose -> peach -> apricot -> gold at the horizon"""+ r = self._r(seed)+ H, W = self.H, self.W+ hz = self.horizon if horizon is None else float(horizon)+ self.horizon = hz+ stops = stops or [(0.0, 'lavender'), (0.24, 'lilac'), (0.45, 'rose'), (0.65, 'peach'), (0.84, 'apricot'), (1.0, 'gold')]+ pos = np.array([s[0] for s in stops], np.float32); cols = np.stack([hexc(s[1]) for s in stops])+ # horizontally stretched noise: the colours lie in soft layers+ k = 5+ n1 = np.asarray(Image.fromarray(noise2d(H, W // k, 120, 3, int(r.integers(1 << 30)))).resize((W, H), Image.BICUBIC))+ n2 = noise2d(H, W, 260, 2, int(r.integers(1 << 30)))+ yy = np.arange(H, dtype=np.float32)[:, None] / hz+ t = np.clip(yy + (n1 - 0.5) * 0.07 * mottle + (n2 - 0.5) * 0.05 * mottle, 0, 1)+ out = np.stack([np.interp(t, pos, cols[:, c]) for c in range(3)], -1).astype(np.float32)+ m = noise2d(H, W, 46, 4, int(r.integers(1 << 30)))+ out *= (1 + 0.022 * mottle * (m - 0.5) * 2)[..., None]+ self.C[:] = out++ def cloud(self, x0, x1, y, h, colour='cloud', alpha=0.7, light='lilac', soft=4.0, lumps=5, seed=None):+ """a soft lens-shaped cloud: a flat lens plus a few rounded lumps on top (taller in the middle), the outline+ blurred soft, the bottom kept flatter and a little crisper; lighter at the top, denser at the bottom"""+ r = self._r(seed)+ w = float(x1 - x0)+ pad = int(3 * soft) + 4+ bx0, bx1 = max(0, int(x0) - pad), min(self.W, int(x1) + pad)+ by0, by1 = max(0, int(y - h * 1.3) - pad), min(self.H, int(y + h * 0.4) + pad)+ if bx1 <= bx0 or by1 <= by0: return+ X = np.arange(bx0, bx1, dtype=np.float32)[None]; Y = np.arange(by0, by1, dtype=np.float32)[:, None]+ m = (((X - (x0 + w / 2)) / (w / 2)) ** 2 + ((Y - y) / (h * 0.32)) ** 2 < 1).astype(np.float32)+ for _ in range(lumps):+ c = r.uniform(0.15, 0.85); env = np.sin(np.pi * c) ** 0.7+ rx = w * r.uniform(0.09, 0.2); ry = h * env * r.uniform(0.7, 1.1)+ cxl = x0 + c * w+ m = np.maximum(m, (((X - cxl) / rx) ** 2 + ((Y - (y - ry * 0.25)) / ry) ** 2 < 1).astype(np.float32))+ u = np.clip((X - x0) / w, 0, 1)+ yb = y + h * 0.16 * np.clip(np.sin(np.pi * u), 0, 1) ** 0.6+ ms = blur(m, soft) * smoothstep(yb + 1.4, yb - 1.4, Y)+ top = np.where(m.any(1))[0]+ ytop = by0 + (top.min() if len(top) else 0)+ k = np.clip((Y - ytop) / max(1.0, (y + h * 0.16) - ytop), 0, 1)+ col = mix(colour, light, 0.22)[None, None] * (1 - k[..., None] ** 0.7) + hexc(colour)[None, None] * k[..., None] ** 0.7+ nz = noise2d(by1 - by0, bx1 - bx0, 20, 3, int(r.integers(1 << 30)))+ self._comp(ms * alpha * (0.88 + 0.24 * (nz - 0.5)), col.astype(np.float32), (slice(by0, by1), slice(bx0, bx1)))++ def streak(self, x0, x1, y, colour='streak', width=1.8, alpha=0.7, seed=None):+ """a thin pale line of light lying in the sky (tapered both ends)"""+ r = self._r(seed)+ xs = np.linspace(x0, x1, 12)+ ys = y + fbm1d(12, 6, 2, int(r.integers(1 << 30))) * 0.8+ self.lines([np.stack([xs, ys], 1)], width, colour, alpha, taper=0.3)++ def sun(self, x, y, r, colour='sun', halo=1.0):+ """a low pale sun: wide warm glow, close glow, soft-edged disc (paint before the hills that cut it)"""+ self.glow(x, y, r * 8, 'gold', 0.32 * halo, squash=0.5)+ self.glow(x, y, r * 2.6, '#fff1dc', 0.4 * halo)+ m = self.ellipse(x, y, r)+ yy = np.arange(self.H, dtype=np.float32)[:, None]+ col = np.broadcast_to(hexc(colour), (self.H, self.W, 3)) * (1 + 0.025 * np.clip((y - yy) / r, -1, 1))[..., None]+ self._comp(m * 0.96, col.astype(np.float32), (slice(None), slice(None)), lit=False)++ def mist(self, y0, y1, y2=None, colour='haze', strength=0.3, seed=None):+ """a soft horizontal veil: rises from y0, strongest at y1, gone by y2"""+ r = self._r(seed)+ y2 = y1 + (y1 - y0) if y2 is None else y2+ yy = np.arange(self.H, dtype=np.float32)[:, None]+ a = smoothstep(y0, y1, yy) * smoothstep(y2, y1, yy)+ lo, hi = max(0, int(y0)), min(self.H, int(y2) + 1)+ n = noise2d(hi - lo, self.W, 140, 3, int(r.integers(1 << 30)))+ A = (a[lo:hi] * strength * (0.75 + 0.5 * n)).astype(np.float32)+ self._comp(A, colour, (slice(lo, hi), slice(None)))++ def birds(self, pts, size=7.0, colour='#6d6172', alpha=0.75, seed=None):+ """tiny far birds: two little arcs each"""+ r = self._r(seed)+ paths = []+ for x, y in pts:+ s = size * r.uniform(0.7, 1.25); f = r.uniform(-0.25, 0.35)+ paths.append(np.array([(x - s, y - s * (0.15 + f)), (x - s * 0.45, y - s * 0.38), (x, y)]))+ paths.append(np.array([(x, y), (x + s * 0.45, y - s * 0.36), (x + s * 0.95, y - s * (0.2 + f))]))+ self.lines([spline(p, 6) for p in paths], 1.0, colour, alpha)++ def seeds(self, pts, size=9.0, colour='#5f5763', alpha=0.7, seed=None):+ """floating dandelion parachutes: a seed, a thin beak and a little fan of hairs"""+ r = self._r(seed)+ paths = []; dots = []+ for x, y in pts:+ s = size * r.uniform(0.75, 1.2); a = r.uniform(-0.6, 0.6)+ ux, uy = np.sin(a), -np.cos(a) # up the beak+ top = (x + ux * s, y + uy * s)+ paths.append(np.array([(x, y), top]))+ for k in range(9):+ b = a + np.deg2rad(-75 + 150 * k / 8) + r.normal(0, 0.05)+ L = s * r.uniform(0.55, 0.8)+ paths.append(np.array([top, (top[0] + np.sin(b) * L, top[1] - np.cos(b) * L)]))+ dots.append((x - ux * 1.2, y - uy * 1.2))+ self.lines(paths, 0.65, colour, alpha)+ d = np.array(dots)+ self.splat(d[:, 0], d[:, 1], 1.0, hexc(colour), alpha, lit=True)++ # ================================================================== night+ def night_split(self, edge, soft=160.0, ground=0.9, wander=40.0, feather=0.25, seed=None):+ """the boundary between dusk and night: edge is a top -> bottom polyline [(x, y), ...] and night lies to its+ right. N = 0 dusk .. 1 night across a feathered band of +-soft px; below the horizon the land is shaded by+ N * ground. Call after dusk_sky() (it uses the horizon)."""+ r = self._r(seed)+ H, W = self.H, self.W+ E = np.asarray(edge, np.float32)+ ys = np.arange(H, dtype=np.float32)+ ex = np.interp(ys, E[:, 1], E[:, 0]) + fbm1d(H, 260, 3, int(r.integers(1 << 30))) * wander+ n2 = noise2d(H, W, 170, 3, int(r.integers(1 << 30)))+ d = np.arange(W, dtype=np.float32)[None] - ex[:, None] + (n2 - 0.5) * soft * feather+ N = smoothstep(-soft, soft, d)+ g = 1 - (1 - ground) * smoothstep(self.horizon - 30, self.horizon + 30, ys)[:, None]+ self.N = (N * g).astype(np.float32)+ self._Nsky = N.astype(np.float32)++ def night_sky(self, top='night', low='night_low', indigo='indigo', mottle=1.0, richness=0.5, seed=None):+ """the night gradient laid with the night field as alpha; it leans indigo near the boundary, and the+ transition band is re-saturated (richness) so dusk -> night passes through mauve and violet, not grey"""+ r = self._r(seed)+ H, W = self.H, self.W+ N = self._Nsky+ yy = np.arange(H, dtype=np.float32)[:, None, None]+ t = np.clip(yy / self.horizon, 0, 1) ** 1.7+ col = hexc(top) * (1 - t) + hexc(low) * t+ col = col + (hexc(indigo) - col) * (0.8 * (1 - N) ** 0.9)[..., None]+ m = noise2d(H, W, 120, 4, int(r.integers(1 << 30)))+ col = col * (1 + 0.08 * mottle * (m - 0.5))[..., None]+ with self.unlit():+ self._comp(N, col.astype(np.float32), (slice(None), slice(None)))+ if richness:+ hz = int(min(H, self.horizon + 40))+ w = (4 * N[:hz] * (1 - N[:hz]))[..., None]+ Cs = self.C[:hz]+ lum = (Cs @ _LUMA)[..., None]+ Cs[:] = np.clip(lum + (Cs - lum) * (1 + richness * w), 0, 1)++ def milky_way(self, p0, p1, width=150.0, bend=50.0, rift=0.8, stars=3500, colour='milk', alpha=0.45, seed=None):+ """a cloudy luminous band from p0 to p1 with a dark rift and a dense dust of faint stars"""+ r = self._r(seed)+ H, W = self.H, self.W+ p0 = np.asarray(p0, np.float32); p1 = np.asarray(p1, np.float32)+ L = float(np.linalg.norm(p1 - p0)); u = (p1 - p0) / L; nv = np.array([-u[1], u[0]], np.float32)+ hz = int(min(H, self.horizon + 10))+ yy = np.arange(hz, dtype=np.float32)[:, None]; xx = np.arange(W, dtype=np.float32)[None]+ s = (xx - p0[0]) * u[0] + (yy - p0[1]) * u[1]+ dd = (xx - p0[0]) * nv[0] + (yy - p0[1]) * nv[1]+ sn = np.clip(s / L, -0.2, 1.2)+ k = 256; grid = np.linspace(-0.2, 1.2, k)+ wander = np.interp(sn, grid, fbm1d(k, 40, 3, int(r.integers(1 << 30)))) * width * 0.35+ wid = width * (0.8 + 0.3 * np.interp(sn, grid, fbm1d(k, 30, 2, int(r.integers(1 << 30)))))+ c = bend * np.sin(np.pi * np.clip(sn, 0, 1)) + wander+ x = dd - c+ core = np.exp(-(x / wid) ** 2 * 1.6)+ inner = np.exp(-(x / (wid * 0.42)) ** 2 * 1.6)+ n1 = noise2d(hz, W, 70, 4, int(r.integers(1 << 30))); n2 = noise2d(hz, W, 16, 3, int(r.integers(1 << 30)))+ cloud = np.clip(0.15 + 1.0 * n1 + 0.45 * n2 - 0.45, 0, 1.2)+ ends = smoothstep(-0.15, 0.1, sn) * smoothstep(1.15, 0.9, sn)+ dens = ((0.7 * core + 0.55 * inner) * cloud * ends).astype(np.float32)+ lane_c = width * 0.08 * np.sin(sn * 7.0) + np.interp(sn, grid, fbm1d(k, 20, 3, int(r.integers(1 << 30)))) * width * 0.1+ lw = width * 0.075 * (0.55 + 0.9 * n1)+ lane = np.exp(-((x - lane_c) / lw) ** 2) * (0.8 * inner + 0.3 * core) * ends * rift * (0.55 + 0.6 * n2)+ N = self._Nsky[:hz]+ sl = (slice(0, hz), slice(None))+ with self.unlit():+ self._comp(np.clip(dens * alpha, 0, 1) * N, colour, sl)+ self._comp(np.clip(lane, 0, 0.92) * N * 0.9, '#0b0a10', sl)+ # the dust of faint stars inside the band+ M = stars * 6+ px = r.uniform(0, W, M); py = r.uniform(0, hz, M)+ dv = dens[py.astype(int), px.astype(int)] * N[py.astype(int), px.astype(int)]+ ok = r.random(M) < dv * 1.6+ px, py = px[ok][:stars], py[ok][:stars]+ b = r.uniform(0.25, 0.85, len(px)) ** 1.5+ self.splat(px, py, r.uniform(0.3, 0.7, len(px)), hexc('star'), b, lit=False)++ def stars(self, n=1600, region=None, sparkles=6, dusk=0.0, size=(0.35, 1.45), sparkle_size=(7, 13), seed=None):+ """a star field (power-law brightness, some warm, some blue) that thins out across the night boundary"""+ r = self._r(seed)+ x0, y0, x1, y1 = region or (0, 0, self.W, self.horizon)+ xs = r.uniform(x0, x1, n).astype(np.float32); ys = r.uniform(y0, y1, n).astype(np.float32)+ Nv = self._Nsky[np.clip(ys.astype(int), 0, self.H - 1), np.clip(xs.astype(int), 0, self.W - 1)]+ vis = np.maximum(Nv, dusk)+ keep = r.random(n) < vis ** 1.4+ b = np.clip(r.pareto(2.4, n) * 0.33 + 0.12, 0.08, 1.8)+ rad = size[0] + (size[1] - size[0]) * np.clip(b / 1.6, 0, 1) ** 0.8+ al = np.clip(0.3 + 0.62 * b, 0, 1) * vis ** 0.6 * (0.45 + 0.55 * smoothstep(self.horizon, self.horizon - 160, ys))+ cols = np.tile(hexc('star'), (n, 1))+ k = r.random(n)+ cols[k < 0.1] = hexc('#ffdcb3'); cols[(k >= 0.1) & (k < 0.2)] = hexc('#d2ddff')+ self.splat(xs[keep], ys[keep], rad[keep], cols[keep], al[keep], lit=False)+ with self.unlit():+ bright = np.where(keep & (b > 1.0))[0]+ for i in bright:+ self.glow(xs[i], ys[i], 3.0 + 2.0 * b[i], cols[i], 0.10 * al[i])+ cand = np.where(keep & (Nv > 0.8) & (ys < y1 - 180))[0]+ if sparkles and len(cand):+ pick = cand[np.argsort(-b[cand])[:max(sparkles * 3, sparkles)]]+ pick = r.choice(pick, min(sparkles, len(pick)), replace=False)+ for i in pick:+ self.sparkle(xs[i], ys[i], r.uniform(*sparkle_size), alpha=0.85 * Nv[i])++ def sparkle(self, x, y, size=12.0, colour='star', alpha=0.9):+ """four-point star: long tapered cross, short faint diagonals, a bright core and a little glow"""+ with self.unlit():+ self.glow(x, y, size * 0.32, colour, 0.35 * alpha)+ self.lines([[(x - size, y), (x + size, y)], [(x, y - size * 1.1), (x, y + size * 1.1)]], 1.25, colour, alpha, taper=0.5)+ d = size * 0.34+ self.lines([[(x - d, y - d), (x + d, y + d)], [(x - d, y + d), (x + d, y - d)]], 0.7, colour, alpha * 0.55, taper=0.5)+ self.splat([x], [y], [1.3], hexc(colour), alpha, lit=False)++ def moon(self, x, y, r, phase=0.3, tilt=-0.6, colour='moon', earthshine=0.22, glow=1.0):+ """a crescent: a lit disc minus an offset dark disc, faint earthshine on the rest, a soft glow"""+ R = int(r * 1.5) + 3+ x0, x1 = max(0, int(x) - R), min(self.W, int(x) + R + 1)+ y0, y1 = max(0, int(y) - R), min(self.H, int(y) + R + 1)+ yy = np.arange(y0, y1, dtype=np.float32)[:, None]; xx = np.arange(x0, x1, dtype=np.float32)[None]+ disc = smoothstep(r + 0.7, r - 0.7, np.hypot(xx - x, yy - y))+ off = r * 2 * (1 - phase)+ sx, sy = x + np.cos(tilt) * off * 0.62, y + np.sin(tilt) * off * 0.62+ shadow = smoothstep(r * 0.98 + 0.7, r * 0.98 - 0.7, np.hypot(xx - sx, yy - sy))+ lit = disc * (1 - shadow)+ sl = (slice(y0, y1), slice(x0, x1))+ with self.unlit():+ self.glow(x, y, r * 3.2, colour, 0.16 * glow)+ self._comp(disc * earthshine, '#4a4a58', sl)+ rr = np.random.default_rng(self.seed + 41)+ mott = 1 - 0.07 * noise2d(y1 - y0, x1 - x0, max(3, r / 3), 2, int(rr.integers(1 << 30)))+ col = hexc(colour)[None, None] * mott[..., None]+ self._comp(lit * 0.97, col.astype(np.float32), sl)++ def shooting_star(self, p0, p1, width=1.5, colour='star', alpha=0.95):+ """a thin streak that brightens toward its head (p1)"""+ p0 = np.asarray(p0, np.float32); p1 = np.asarray(p1, np.float32)+ k = 26+ with self.unlit():+ for i in range(k):+ a, b = i / k, (i + 1) / k+ self.lines([[p0 + (p1 - p0) * a, p0 + (p1 - p0) * b]], width * (0.35 + 0.65 * b), colour, alpha * b ** 1.6, caps=False)+ self.glow(p1[0], p1[1], 4.5, colour, 0.45 * alpha)+ self.splat([p1[0]], [p1[1]], [1.4], hexc(colour), alpha, lit=False)++ # ================================================================== land+ def hills(self, ridge, colour='mauve', base=None, haze='haze', fade=0.35, rim=None, rim_alpha=0.45, texture=0.03, seed=None):+ """a distant range: filled ridge, lighter toward its misty base, faint texture, optional lit rim"""+ r = self._r(seed)+ ry = self._ridge(ridge)+ y0 = max(0, int(ry.min()) - 2); y1 = self.H if base is None else min(self.H, int(base))+ Y = np.arange(y0, y1, dtype=np.float32)[:, None]+ D = Y - ry[None]+ A = smoothstep(-0.8, 0.8, D)+ depth = np.clip(D / max(1.0, (y1 - ry.min()) * 0.8), 0, 1)[..., None]+ col = hexc(colour) * (1 - fade * depth) + hexc(haze) * fade * depth+ n = noise2d(y1 - y0, self.W, 50, 3, int(r.integers(1 << 30)))+ col = col * (1 + texture * (n - 0.5) * 2)[..., None]+ self._comp(A, col.astype(np.float32), (slice(y0, y1), slice(None)))+ if rim:+ self._comp(np.exp(-((D - 1.2) / 1.0) ** 2) * rim_alpha, rim, (slice(y0, y1), slice(None)))+ return ry++ def striped_hill(self, ridge, colours=('field_sage', 'field_lav', 'field_wheat', 'field_green', 'field_rose'), base=None,+ stripe=(9.0, 20.0), grow=2.2, fields=(150, 470), slant=0.7, rows=0.45, hedge=0.35, rim='rim',+ rim_alpha=0.6, texture=0.035, haze='haze', fade=0.25, seed=None):+ """rolling hill in soft stacked pastel stripes: bands follow the ridge and widen toward the viewer, each band+ cut into slanted patchwork fields, some with fine crop rows; hedge lines; a pale rim along the crest.+ Returns {'ridge': per-column y, 'bounds': stripe boundaries below the ridge (px)}"""+ r = self._r(seed)+ W = self.W+ ry = self._ridge(ridge)+ y0 = max(0, int(ry.min()) - 2); y1 = self.H if base is None else min(self.H, int(base))+ hgt = y1 - y0+ X = np.arange(W, dtype=np.float32)[None]+ Y = np.arange(y0, y1, dtype=np.float32)[:, None]+ D = Y - ry[None]+ Dw = D + (noise2d(hgt, W, 180, 2, int(r.integers(1 << 30))) - 0.5) * 7 * np.clip(D / 30, 0, 1)+ b = [0.0]+ while b[-1] < hgt + 60:+ b.append(b[-1] + r.uniform(*stripe) * (1 + grow * b[-1] / max(1, hgt)))+ b = np.array(b, np.float32); ns = len(b) - 1+ k = np.clip(np.searchsorted(b, Dw) - 1, 0, ns - 1)+ loc = Dw - b[k]+ nf = int(W / fields[0]) + 6+ cuts = np.cumsum(r.uniform(*fields, (ns, nf)), 1) - r.uniform(0, fields[1], (ns, 1))+ slants = r.uniform(-slant, slant, ns)+ fidx = np.zeros(k.shape, np.int64); dcut = np.full(k.shape, 99.0, np.float32)+ for i in range(ns):+ m = k == i+ if not m.any(): continue+ xe = (X + loc * slants[i])[m]+ j = np.clip(np.searchsorted(cuts[i], xe), 1, nf - 1)+ fidx[m] = j+ dcut[m] = np.minimum(xe - cuts[i][j - 1], cuts[i][j] - xe)+ pal = np.stack([hexc(c) for c in colours])+ lut = pal[r.integers(0, len(colours), (ns, nf))] * r.uniform(0.94, 1.05, (ns, nf, 1))+ col = lut[k, fidx].astype(np.float32)+ rowflag = r.random((ns, nf)) < rows; sp = r.uniform(2.6, 4.0, (ns, nf))+ rl = (np.mod(loc, sp[k, fidx]) < 0.95) & rowflag[k, fidx] & (loc > 1.5)+ col = col * (1 - 0.07 * rl)[..., None]+ hd = (np.exp(-(loc / 0.75) ** 2) + np.exp(-(dcut / 0.7) ** 2) * 0.8) * hedge * np.clip(D / 4, 0, 1)+ col = col * (1 - 0.35 * np.clip(hd, 0, 1))[..., None]+ depth = np.clip(D / max(1.0, hgt * 0.9), 0, 1)+ col = col + (hexc(haze) - col) * (fade * (1 - depth) ** 2)[..., None]+ n = noise2d(hgt, W, 30, 3, int(r.integers(1 << 30)))+ col = col * (1 + texture * (n - 0.5) * 2 + 0.012 * self.TX[y0:y1])[..., None]+ sl = (slice(y0, y1), slice(None))+ self._comp(smoothstep(-0.8, 0.8, D), col.astype(np.float32), sl)+ if rim: self._comp(np.exp(-((D - 1.3) / 1.1) ** 2) * rim_alpha, rim, sl)+ return {'ridge': ry, 'bounds': b}++ def trees(self, pts, size=7.0, colour='tree', light='tree_light', trunk='trunk', shadow=0.22, ss=3, seed=None):+ """tiny round picture-book trees: a soft shadow, a trunk, a round crown and a lit top-left"""+ r = self._r(seed)+ G = _Polys()+ for x, y in sorted(pts, key=lambda p: p[1]):+ s = size * r.uniform(0.75, 1.3)+ G.add(_ell(x + s * 0.55, y + s * 0.05, s * 0.95, s * 0.22, 12), '#2f2b2c', shadow, y)+ G.add(np.array([(x - s * 0.09, y), (x + s * 0.09, y), (x + s * 0.06, y - s), (x - s * 0.06, y - s)]), trunk, 1, y + 0.01)+ c = hexc(colour) * r.uniform(0.85, 1.12)+ G.add(_ell(x + r.normal(0, 0.06) * s, y - s * 1.2, s * 0.82, s * 0.78, 14), c, 1, y + 0.02)+ G.add(_ell(x - s * 0.24, y - s * 1.42, s * 0.42, s * 0.34, 12), mix(light, c, 0.25), 0.85, y + 0.03)+ self._paint([G.group()], ss)++ # ================================================================== the meadow+ def meadow(self, crest, bottom=None, colour='meadow', far_colour='meadow_far', near_colour='meadow_near',+ size=(1.0, 30.0), power=2.0, density=1.0, grass=1.0, kinds=None, drifts=0.8, haze=0.5, rim='rim', rim_alpha=0.6,+ ss=3, seed=None):+ """the wildflower meadow below a crest line: ground, lit rim, thousands of flowers and grass blades in+ perspective (specks at the crest, big heads at the bottom). kinds = {species: weight} (see MIX).+ Returns {'crest': per-column y, 'y0': top row, 'y1': bottom row}"""+ r = self._r(seed)+ W, H = self.W, self.H+ cy = self._ridge(crest)+ y0 = max(0, int(np.floor(cy.min())) - 2); y1 = H if bottom is None else int(bottom)+ hgt = y1 - y0+ Y = np.arange(y0, y1, dtype=np.float32)[:, None]+ D = Y - cy[None]+ span = np.maximum(y1 - cy, 1.0)[None]+ t = np.clip(D / span, 0, 1)+ # ---- ground+ cf, cm, cn = hexc(far_colour), hexc(colour), hexc(near_colour)+ tt = t[..., None]+ base = np.where(tt < 0.3, cf + (cm - cf) * (tt / 0.3) ** 0.8, cm + (cn - cm) * np.clip((tt - 0.3) / 0.7, 0, 1))+ n1 = noise2d(hgt, W, 40, 3, int(r.integers(1 << 30)))+ base = base * (1 + 0.07 * (n1 - 0.5) + 0.03 * self.TX[y0:y1])[..., None]+ sl = (slice(y0, y1), slice(None))+ self._comp(smoothstep(-0.8, 0.8, D), base.astype(np.float32), sl)+ # flecks in the ground (darker and lighter specks)+ nfk = int(W * hgt * 0.02 * density)+ fx = r.uniform(0, W, nfk); fy = r.uniform(y0, y1, nfk)+ okf = fy > cy[fx.astype(int)] + 1+ fx, fy = fx[okf], fy[okf]+ tv = np.clip((fy - cy[fx.astype(int)]) / (y1 - cy[fx.astype(int)]), 0, 1)+ fc = np.where(r.random(len(fx))[:, None] < 0.6, hexc('#3d4529'), hexc('#7d8350'))+ self.splat(fx, fy, 0.5 + 1.4 * tv, fc, 0.5, lit=True)+ # ---- plants: rejection sampling so that coverage follows perspective+ s0, s1 = size+ sc_of = lambda tv: s0 + (s1 - s0) * tv ** power+ cov = lambda tv: (0.24 + 0.32 * tv) * density+ dmax = cov(0.0) / (np.pi * s0 * s0)+ M = int(W * hgt * dmax * 1.05)+ px = r.uniform(0, W, M).astype(np.float32); py = r.uniform(y0, y1, M).astype(np.float32)+ cyx = cy[px.astype(int)]+ tv = np.clip((py - cyx) / (y1 - cyx), 0, 1); sc = sc_of(tv)+ ok = (py > cyx + 0.8) & (r.random(M) < cov(tv) / (np.pi * sc * sc) / dmax)+ px, py, tv, sc = px[ok], py[ok], tv[ok], sc[ok]+ sc = sc * r.uniform(0.7, 1.3, len(sc))+ # species with drifting patches+ kinds = kinds or MIX+ names = [k for k in SPECIES if kinds.get(k, 0) > 0]+ wts = np.array([kinds[k] for k in names], np.float32)+ u = px / W; v = (py - y0) / max(1, hgt)+ P = np.stack([wts[i] * np.exp(drifts * 2.2 * (_grid_sample(r.random((5, 9)), u, v) - 0.5)) for i in range(len(names))], 1)+ P /= P.sum(1, keepdims=True)+ sp = (P.cumsum(1) < r.random(len(px))[:, None]).sum(1)+ sp = np.minimum(sp, len(names) - 1)+ G = _Polys()+ stemc = np.stack([hexc('stem'), hexc('#4f5b35'), hexc('#5d6a3d')])+ self._mhaze = (cf, float(haze))+ for i in range(len(px)):+ self._plant(G, names[sp[i]], float(px[i]), float(py[i]), float(sc[i]), float(tv[i]), r, stemc)+ # grass blades, sampled the same way+ g0 = 0.9+ gl = lambda tv: g0 + (s1 * 2.1 - g0) * tv ** power+ gw = lambda tv: 0.5 + 1.3 * tv ** power+ gden = lambda tv: 0.2 * grass / (gl(tv) * np.maximum(gw(tv), 0.55))+ gmax = float(gden(0.0))+ Mg = int(W * hgt * gmax)+ gx = r.uniform(0, W, Mg).astype(np.float32); gy = r.uniform(y0, y1, Mg).astype(np.float32)+ cyg = cy[gx.astype(int)]+ tg = np.clip((gy - cyg) / (y1 - cyg), 0, 1)+ okg = (gy > cyg + 0.6) & (r.random(Mg) < gden(tg) / gmax)+ gx, gy, tg = gx[okg], gy[okg], tg[okg]+ L = gl(tg) * r.uniform(0.6, 1.4, len(gx)); Wd = np.maximum(0.45, gw(tg) * r.uniform(0.7, 1.3, len(gx)))+ lean = r.normal(0, 0.28, len(gx)); bend = r.normal(0, 0.18, len(gx))+ gpal = np.stack([hexc(c) for c in GRASS])+ gi = np.clip((r.random(len(gx)) * 0.85 + 0.15 * (1 - tg)) * len(GRASS), 0, len(GRASS) - 1).astype(int)+ gcol = gpal[gi] * (1 + 0.15 * (1 - tg))[:, None]+ for i in range(len(gx)):+ x, y, l, w, ln, bd = float(gx[i]), float(gy[i]), float(L[i]), float(Wd[i]), float(lean[i]), float(bend[i])+ tip = (x + ln * l, y - l)+ mid = (x + ln * l * 0.45 + bd * l * 0.3, y - l * 0.5)+ G.add([(x - w / 2, y), (mid[0] - w * 0.3, mid[1]), tip, (mid[0] + w * 0.3, mid[1]), (x + w / 2, y)],+ gcol[i], 0.92, y + 0.001)+ self._paint([G.group()], ss, tex=0.03)+ # the lit rim along the crest: gold on the dusk side, silver under the night+ rimA = np.exp(-((D - 1.0) / 1.15) ** 2) * rim_alpha+ if rim:+ Nl = self._Nsky[y0:y1]+ rc = hexc(rim)[None, None] * (1 - Nl[..., None]) + hexc('silver')[None, None] * Nl[..., None]+ with self.unlit():+ self._comp(rimA * (1 - 0.45 * Nl), rc.astype(np.float32), sl)+ return {'crest': cy, 'y0': y0, 'y1': y1}++ def _plant(self, G, kind, x, y, s, tv, r, stemc):+ """one wildflower into the polygon list G (stem, leaf, head), keyed by the y of its base"""+ cols = PETALS[kind]+ base = _pick(r, cols, 1)[0] * r.uniform(0.92, 1.05)+ hc, ha = self._mhaze+ hz = ha * (1 - tv) ** 2.5 # far flowers sink into the hazy ground colour+ base = base * (1 - hz) + hc * hz+ if s < 1.9: # a speck+ G.add(_ell(x, y, s, s * 0.8, 7, r.uniform(0, 3)), base, 0.88, y)+ return+ stem_len = s * r.uniform(2.6, 4.2) * (1.35 if kind in ('poppy', 'cosmos') else 1.0)+ lean = r.normal(0, 0.18) * stem_len+ key = y + stem_len+ sw = max(0.5, s * 0.085)+ sc_ = stemc[r.integers(0, 3)]+ stem = np.array([(x - sw / 2, y), (x + sw / 2, y), (x + lean + sw * 0.7, y + stem_len), (x + lean - sw * 0.7, y + stem_len)])+ G.add(stem, sc_, 0.95, key - 0.01)+ if s > 7 and r.random() < 0.8: # a leaf on the stem+ ly = y + stem_len * r.uniform(0.45, 0.8); lx = x + lean * (ly - y) / stem_len+ side = r.choice([-1, 1]); L = s * r.uniform(1.2, 2.0); a = side * r.uniform(0.5, 1.0) - np.pi / 2+ G.add(self._leaf(lx, ly, L, L * 0.22, a), sc_ * 1.08, 0.95, key - 0.009)+ sq = r.uniform(0.62, 0.92)+ rot = r.uniform(0, 2 * np.pi)+ if s < 4.2 or kind == 'forgetmenot':+ if kind == 'lupine':+ for j in range(5):+ rr = s * (0.42 - 0.06 * j)+ G.add(_ell(x + (j % 2 - 0.5) * s * 0.25, y - j * s * 0.45, rr, rr * 0.85, 7), base * (1 + 0.04 * j), 1, key)+ return+ if kind == 'forgetmenot':+ for j in range(r.integers(3, 6) if s > 3 else 2):+ ox, oy = r.normal(0, s * 0.45), r.normal(0, s * 0.3)+ self._rosette(G, x + ox, y + oy, s * 0.42, 5, base * r.uniform(0.95, 1.05), sq, r.uniform(0, 6), key, EYES[kind] if s > 3 else None)+ return+ npet = {'daisy': 8, 'cornflower': 7, 'poppy': 4, 'cosmos': 8, 'marigold': 10, 'buttercup': 5}[kind]+ self._rosette(G, x, y, s, npet, base, sq, rot, key, EYES[kind] if s > 2.6 else None)+ return+ self._head(G, kind, x, y, s, base, sq, rot, key, r)++ def _rosette(self, G, x, y, s, n, colour, sq, rot, key, eye):+ th = np.linspace(0, 2 * np.pi, n * 4, endpoint=False)+ rad = s * (0.62 + 0.38 * np.abs(np.cos(th * n / 2)))+ pts = np.stack([x + np.cos(th + rot) * rad, y + np.sin(th + rot) * rad * sq], 1)+ G.add(pts, colour, 1, key)+ if eye: G.add(_ell(x, y, s * 0.3, s * 0.3 * sq, 8), eye, 1, key)++ @staticmethod+ def _leaf(x, y, L, w, a):+ T = np.array([(0, 0), (0.25, -0.42), (0.6, -0.48), (1, 0), (0.6, 0.42), (0.25, 0.36)], np.float32)+ c, s = np.cos(a), np.sin(a)+ return np.stack([x + T[:, 0] * L * c - T[:, 1] * w * 2 * s, y + T[:, 0] * L * s + T[:, 1] * w * 2 * c], 1)++ def _petals(self, G, T, x, y, n, length, width, rot, sq, cols, key, start=0.0, jit=0.08, r=None):+ """n petals of template T (pointing +x from the origin), squashed by sq; back petals first"""+ th = rot + 2 * np.pi * np.arange(n) / n + (r.normal(0, jit, n) if r is not None else 0)+ order = np.argsort(np.sin(th))+ for i in order:+ c, s = np.cos(th[i]), np.sin(th[i])+ lx = start + T[:, 0] * length; ly = T[:, 1] * width+ G.add(np.stack([x + lx * c - ly * s, y + (lx * s + ly * c) * sq], 1), cols[i], 1, key)++ def _head(self, G, kind, x, y, s, base, sq, rot, key, r):+ cols = lambda n, v=0.05: _pick(r, PETALS[kind], n) * r.uniform(1 - v, 1 + v, (n, 1))+ if kind == 'daisy':+ n = int(r.integers(12, 17))+ T = np.array([(0, 0), (0.15, -0.5), (0.6, -0.55), (0.95, -0.3), (1, 0), (0.95, 0.3), (0.6, 0.55), (0.15, 0.5)], np.float32)+ pc = np.clip(base[None] * r.uniform(0.9, 1.02, (n, 1)), 0, 1)+ self._petals(G, T, x, y, n, s * 0.82, s * 0.2, rot, sq, pc, key, start=s * 0.18, r=r)+ G.add(_ell(x, y, s * 0.3, s * 0.3 * sq, 12), EYES['daisy'], 1, key)+ G.add(_ell(x + s * 0.06, y + s * 0.06 * sq, s * 0.17, s * 0.17 * sq, 10), '#c98f22', 1, key)+ elif kind == 'cornflower':+ n = int(r.integers(8, 11))+ T = np.array([(0, -0.1), (0.7, -0.36), (1.0, -0.5), (0.9, -0.24), (1.02, -0.08), (0.88, 0.06), (1.0, 0.22),+ (0.9, 0.34), (1.0, 0.5), (0.7, 0.38), (0, 0.1)], np.float32)+ self._petals(G, T, x, y, n, s * 0.95, s * 0.42, rot, sq, cols(n), key, start=s * 0.05, r=r)+ G.add(_ell(x, y, s * 0.2, s * 0.2 * sq, 8), EYES['cornflower'], 1, key)+ elif kind == 'poppy':+ n = 4+ T = np.stack([0.5 + 0.5 * np.cos(np.linspace(0, 2 * np.pi, 14, endpoint=False)),+ 0.55 * np.sin(np.linspace(0, 2 * np.pi, 14, endpoint=False))], 1).astype(np.float32)+ th = rot + np.arange(n) * np.pi / 2+ cs = cols(n, 0.06)+ sqp = sq * 0.85+ for i in np.argsort(np.sin(th)):+ c, s_ = np.cos(th[i]), np.sin(th[i])+ lx = T[:, 0] * s * 1.0; ly = T[:, 1] * s * 1.0+ shade = 0.82 if np.sin(th[i]) < 0 else 1.0+ G.add(np.stack([x + lx * c - ly * s_, y + (lx * s_ + ly * c) * sqp - s * 0.1], 1), cs[i] * shade, 1, key)+ G.add(_ell(x, y - s * 0.1, s * 0.24, s * 0.22 * sqp, 10), EYES['poppy'], 1, key)+ for j in range(8):+ a = j * np.pi / 4 + rot+ G.add(_ell(x + np.cos(a) * s * 0.3, y - s * 0.1 + np.sin(a) * s * 0.3 * sqp, s * 0.05 + 0.3, s * 0.05 + 0.3, 6), '#241a1e', 1, key)+ elif kind == 'cosmos':+ n = 8+ T = np.array([(0, -0.12), (0.45, -0.46), (0.92, -0.52), (1.0, -0.28), (0.84, 0.0), (1.0, 0.28), (0.92, 0.52),+ (0.45, 0.46), (0, 0.12)], np.float32)+ self._petals(G, T, x, y, n, s * 0.9, s * 0.36, rot, sq, np.clip(base[None] * r.uniform(0.93, 1.04, (n, 1)), 0, 1), key, start=s * 0.08, r=r)+ G.add(_ell(x, y, s * 0.2, s * 0.2 * sq, 10), EYES['cosmos'], 1, key)+ elif kind == 'marigold':+ T = np.stack([0.5 + 0.5 * np.cos(np.linspace(0, 2 * np.pi, 10, endpoint=False)),+ 0.5 * np.sin(np.linspace(0, 2 * np.pi, 10, endpoint=False))], 1).astype(np.float32)+ n1, n2 = 16, 11+ self._petals(G, T, x, y, n1, s * 0.9, s * 0.34, rot, sq, cols(n1), key, start=s * 0.1, r=r)+ self._petals(G, T, x, y, n2, s * 0.6, s * 0.3, rot + 0.3, sq, cols(n2) * 0.9, key, start=s * 0.05, r=r)+ G.add(_ell(x, y, s * 0.18, s * 0.18 * sq, 8), EYES['marigold'], 1, key)+ elif kind == 'buttercup':+ T = np.stack([0.5 + 0.5 * np.cos(np.linspace(0, 2 * np.pi, 12, endpoint=False)),+ 0.52 * np.sin(np.linspace(0, 2 * np.pi, 12, endpoint=False))], 1).astype(np.float32)+ self._petals(G, T, x, y, 5, s * 0.85, s * 0.78, rot, sq, cols(5, 0.04), key, start=s * 0.05, r=r)+ G.add(_ell(x, y, s * 0.2, s * 0.2 * sq, 8), EYES['buttercup'], 1, key)+ elif kind == 'lupine':+ n = int(r.integers(10, 16)); hgt = s * r.uniform(2.6, 3.6)+ bend = r.normal(0, 0.12) * hgt+ for j in range(n):+ f = j / (n - 1)+ cx_ = x + bend * f * f + (1 if j % 2 else -1) * s * 0.2 * (1 - 0.6 * f)+ cy_ = y - f * hgt+ rr = s * (0.36 - 0.22 * f)+ col = np.clip(base * (0.88 + 0.22 * f), 0, 1)+ G.add(_ell(cx_, cy_, rr, rr * 0.8, 9, r.uniform(0, 3)), col, 1, key)+ if f < 0.75: G.add(_ell(cx_ - rr * 0.25, cy_ - rr * 0.3, rr * 0.4, rr * 0.3, 6), np.clip(col * 1.18, 0, 1), 0.9, key)++ def grass_heads(self, x0, x1, base, n=30, height=(30, 70), colour='#5b4a45', head='#7a6250', lean=0.15, width=0.9, seed=None):+ """tall wild-grass stems with small seed heads, rising from a ground line (base: y or f(x)), e.g. along a crest+ against the sky"""+ r = self._r(seed)+ xs = r.uniform(x0, x1, n)+ ys = base(xs) if callable(base) else np.full(n, float(base))+ paths, heads, hcols = [], [], []+ for x, y in zip(xs, ys):+ hgt = r.uniform(*height); ln = r.normal(lean, 0.12)+ P = spline(np.array([(x, y + 2), (x + ln * hgt * 0.35, y - hgt * 0.5), (x + ln * hgt, y - hgt)]), 8)+ paths.append(P)+ tip = P[-1]; d = P[-1] - P[-4]; a = np.arctan2(d[1], d[0])+ for k in range(int(r.integers(4, 8))):+ f = k * r.uniform(2.2, 3.0)+ cxk = tip[0] - np.cos(a) * f; cyk = tip[1] - np.sin(a) * f+ side = 1 if k % 2 else -1+ heads.append(_ell(cxk + np.cos(a + side * 0.5) * 1.2, cyk + np.sin(a + side * 0.5) * 1.2, 2.2 - 0.12 * k, 1.1, 8, a + side * 0.45))+ hcols.append(hexc(head) * r.uniform(0.85, 1.1))+ self.lines(paths, width, colour, 0.85)+ if heads: self.shapes(heads, np.stack(hcols), 0.95)++ # ================================================================== small living things+ def fireflies(self, pts, size=1.0, colour='firefly', trails=0, faint=0.3, seed=None):+ """glowing fireflies (unlit): a warm halo, a bright core; a few leave a dotted trail of their path"""+ r = self._r(seed)+ pts = np.asarray(pts, np.float32)+ n = len(pts)+ with self.unlit():+ core_r = r.uniform(0.8, 1.7, n) * size+ st = np.where(r.random(n) < faint, r.uniform(0.08, 0.16, n), r.uniform(0.2, 0.42, n))+ for i in range(n):+ self.glow(pts[i, 0], pts[i, 1], r.uniform(5, 12) * size, colour, st[i])+ self.splat(pts[:, 0], pts[:, 1], core_r, hexc('#fffbe0'), np.clip(st * 2.6, 0.4, 1.0), lit=False)+ for i in range(min(trails, n)):+ a = r.uniform(0, 2 * np.pi); L = r.uniform(40, 90) * size+ ctrl = [(pts[i, 0] - np.cos(a) * L * k + np.sin(a) * L * 0.3 * np.sin(k * 3), pts[i, 1] - np.sin(a) * L * k + np.cos(a) * L * 0.3 * np.sin(k * 3)) for k in np.linspace(0, 1, 5)]+ Q = _resample(spline(np.array(ctrl), 8), 6.0)[1:]+ al = np.linspace(0.55, 0.05, len(Q))+ self.splat(Q[:, 0], Q[:, 1], 0.7 * size, hexc(colour), al, lit=False)++ def butterfly(self, x, y, s=8.0, colour='#e99a3d', tip='#3a2c2a', angle=0.0, open_=1.0, seed=None):+ """a small flat butterfly: fore and hind wings, dark tips, a thin body"""+ r = self._r(seed)+ G = _Polys()+ c, sn = np.cos(angle), np.sin(angle)+ R = lambda P: np.stack([x + P[:, 0] * c - P[:, 1] * sn, y + P[:, 0] * sn + P[:, 1] * c], 1)+ col = hexc(colour)+ for side in (-1, 1):+ fw = np.array([(0, 0), (side * 0.9, -1.0), (side * 1.25, -0.75), (side * 1.05, -0.1)], np.float32) * s * np.array([open_, 1])+ hw = np.array([(0, 0.05), (side * 0.95, 0.15), (side * 0.85, 0.75), (side * 0.25, 0.7)], np.float32) * s * np.array([open_, 1])+ G.add(R(spline(np.vstack([hw, hw[:1]]), 4)), col * 0.9, 1)+ G.add(R(spline(np.vstack([fw, fw[:1]]), 4)), col, 1)+ G.add(R(_ell(side * 1.0 * s * open_, -0.78 * s, 0.22 * s, 0.17 * s, 8)), tip, 1)+ G.add(R(_ell(0, 0.1 * s, 0.1 * s, 0.6 * s, 8)), '#2c2426', 1)+ self._paint([G.group(sort=False)], 3)+ self.lines([R(np.array([(0, -0.5 * s), (-0.3 * s, -1.2 * s)])), R(np.array([(0, -0.5 * s), (0.3 * s, -1.2 * s)]))], 0.5, '#2c2426', 0.8)++ def dragonfly(self, x, y, s=14.0, angle=0.0, colour='#5d8f9a', seed=None):+ """a dragonfly: a slim body, four long glassy wings with a fine edge"""+ c, sn = np.cos(angle), np.sin(angle)+ R = lambda P: np.stack([x + P[:, 0] * c - P[:, 1] * sn, y + P[:, 0] * sn + P[:, 1] * c], 1)+ wings = []+ for side in (-1, 1):+ for off, L in ((-0.1, 1.0), (0.12, 0.9)):+ wings.append(R(_ell(side * L * 0.5 * s, off * s, L * 0.5 * s, 0.12 * s, 14, side * 0.12)))+ self.shapes(wings, '#f1eef4', 0.45)+ self.lines([np.vstack([w, w[:1]]) for w in wings], 0.5, '#4f4a55', 0.55)+ self.shapes([R(_ell(0, 0.55 * s, 0.05 * s + 0.4, 0.62 * s, 8)), R(_ell(0, -0.12 * s, 0.11 * s, 0.14 * s, 8))], colour, 1)++ # ================================================================== characters and props+ def wanderer(self, x, y, s=90.0, facing=1, reach=(0.7, -0.7), colour='cloak', dark='cloak_dark', face='face',+ mitten='mitten', warm='#f7bf8c', warm_side=-1, seed=None):+ """a small hooded wanderer sitting on the ground (x, y = bottom centre, s = height): felt cloak with a+ floppy hood tip and pompom, round face, dot eyes, blush, one mitten raised toward `reach`. Returns the+ mitten position (to tie a kite string to)."""+ r = self._r(seed)+ f = float(facing)+ P = lambda pts: np.stack([x + np.asarray(pts, np.float32)[:, 0] * s * f, y + np.asarray(pts, np.float32)[:, 1] * s], 1)+ body = spline(np.array([(-0.47, 0.0), (-0.44, -0.2), (-0.37, -0.46), (-0.3, -0.66), (-0.2, -0.8), (-0.04, -0.88),+ (0.13, -0.86), (0.26, -0.76), (0.34, -0.57), (0.41, -0.32), (0.47, -0.1), (0.49, 0.0),+ (0.3, 0.03), (0.0, 0.04), (-0.3, 0.03), (-0.47, 0.0)]), 8)+ tip = spline(np.array([(-0.06, -0.86), (-0.22, -0.9), (-0.38, -0.86), (-0.5, -0.75), (-0.55, -0.66),+ (-0.47, -0.69), (-0.36, -0.76), (-0.22, -0.78), (-0.14, -0.74)]), 6)+ rim_ = _ell(0.08, -0.55, 0.245, 0.225, 30)+ face_ = _ell(0.085, -0.545, 0.2, 0.185, 30)+ # shadow on the grass, boots+ self.shapes([P(_ell(0.1, 0.03, 0.62, 0.1, 20))], '#26222a', 0.28)+ self.shapes([P(_ell(-0.14, 0.0, 0.12, 0.065, 14)), P(_ell(0.24, 0.01, 0.12, 0.065, 14))], 'boot', 1, ss=4)+ # cloak: flat, then felt texture, soft shading, warm rim on the sunset side+ self.shapes([P(tip), P(body)], [hexc(colour) * 0.93, hexc(colour)], 1, ss=4)+ m, sl = self._local([P(body), P(tip)], ss=4)+ h_, w_ = m.shape+ yy = np.linspace(0, 1, h_, dtype=np.float32)[:, None]; xx = np.linspace(0, 1, w_, dtype=np.float32)[None]+ shade = np.clip(0.55 * yy + 0.45 * (xx if f > 0 else 1 - xx) - 0.45, 0, 1)+ self.fill(m * shade * 0.7, dark, sl=sl)+ tex = blur(r.random((h_, w_)).astype(np.float32), 0.7)+ tex = (tex - tex.mean()) / (tex.std() + 1e-6)+ self.fill(m * np.clip(tex - 0.9, 0, 1) * 0.35, dark, sl=sl)+ self.fill(m * np.clip(-tex - 1.1, 0, 1) * 0.25, '#9fb4e0', sl=sl)+ self.lines([P(body)[:-3], P(tip)], max(0.8, s * 0.012), '#2e3a5e', 0.45, wobble=0.25)+ if warm_side:+ edge = np.clip(m - np.roll(m, int(-3 * warm_side), axis=1), 0, 1)+ edge = blur(edge, 1.4) * m * (1 - 0.8 * np.linspace(0, 1, h_)[:, None])+ self.fill(np.clip(edge * 1.2, 0, 0.6), warm, sl=sl)+ # pompom+ pp = P(np.array([(-0.55, -0.66)]))[0]+ self.shapes([_ell(pp[0], pp[1], s * 0.065, s * 0.06, 14)], '#f1e6d6', 1, ss=4)+ # hood rim and face+ self.shapes([P(rim_)], dark, 1, ss=4)+ self.shapes([P(face_)], face, 1, ss=4)+ fm, fsl = self._local([P(face_)], ss=4)+ fy = np.linspace(0, 1, fm.shape[0], dtype=np.float32)[:, None]+ self.fill(fm * np.clip(0.9 - fy * 3, 0, 1) * 0.25, '#7f6a6a', sl=fsl) # hood shadow on the brow+ # eyes, glints, blush+ e1, e2 = P(np.array([(0.03, -0.555)]))[0], P(np.array([(0.15, -0.555)]))[0]+ er = max(1.4, s * 0.026)+ self.shapes([_ell(e1[0], e1[1], er, er * 1.15, 10), _ell(e2[0], e2[1], er, er * 1.15, 10)], '#2a2226', 1, ss=4)+ self.splat([e1[0] - er * 0.3, e2[0] - er * 0.3], [e1[1] - er * 0.4, e2[1] - er * 0.4], max(0.45, er * 0.32), hexc('#ffffff'), 0.9, lit=True)+ c1, c2 = P(np.array([(-0.03, -0.5)]))[0], P(np.array([(0.21, -0.5)]))[0]+ self.shapes([_ell(c1[0], c1[1], s * 0.045, s * 0.026, 10), _ell(c2[0], c2[1], s * 0.045, s * 0.026, 10)], 'cheek', 0.6, ss=4)+ mo = P(np.array([(0.075, -0.49), (0.09, -0.482), (0.105, -0.49)]))+ self.lines([spline(mo, 4)], max(0.7, s * 0.009), '#5a3d3d', 0.8)+ # arm and mitten toward reach+ rv = np.asarray(reach, np.float32); rv = rv / (np.linalg.norm(rv) + 1e-6)+ sh = np.array([0.2, -0.36], np.float32)+ hand = sh + np.array([rv[0], rv[1]]) * 0.36+ mid = (sh + hand) / 2 + np.array([0.03, 0.03])+ arm = _tube(P(np.array([sh, mid, hand])), s * 0.12, s * 0.1)+ self.shapes([arm], hexc(colour) * 0.8, 1, ss=4)+ self.lines([np.vstack([arm, arm[:1]])], max(0.7, s * 0.01), '#2e3a5e', 0.4)+ hp = P(np.array([hand]))[0]+ self.shapes([_ell(hp[0], hp[1], s * 0.068, s * 0.062, 14)], mitten, 1, ss=4)+ return (float(hp[0]), float(hp[1]))++ def jar_lantern(self, x, y, s=34.0, light='lantern', strength=1.0, flies=4, seed=None):+ """a glass jar of fireflies on the grass (x, y = bottom centre, s = height): glass, lid, wire handle, a warm+ glow inside and a pool of light on the ground"""+ r = self._r(seed)+ w = s * 0.62+ body = spline(np.array([(-0.5, -0.06), (-0.52, -0.5), (-0.46, -0.78), (-0.36, -0.84), (0.36, -0.84), (0.46, -0.78),+ (0.52, -0.5), (0.5, -0.06), (0.42, 0.0), (-0.42, 0.0), (-0.5, -0.06)]) * [w, s] + [x, y], 6)+ with self.unlit():+ self.glow(x, y - s * 0.1, s * 4.2, light, 0.26 * strength, squash=0.45) # pool of light on the grass+ self.glow(x, y - s * 0.4, s * 1.8, light, 0.3 * strength)+ self.shapes([_ell(x + s * 0.12, y + 1, s * 0.45, s * 0.07, 16)], '#26222a', 0.25)+ self.shapes([body], 'glass', 0.35)+ with self.unlit():+ self.shapes([_ell(x, y - s * 0.4, w * 0.4, s * 0.32, 20)], '#ffe7a6', 0.85)+ self.glow(x, y - s * 0.42, s * 0.75, light, 0.7 * strength)+ fx = x + r.normal(0, w * 0.18, flies); fy = y - s * 0.42 + r.normal(0, s * 0.14, flies)+ self.splat(fx, fy, 1.1, hexc('#fffef0'), 1.0)+ self.lines([np.vstack([body, body[:1]])], 1.0, '#fbf1da', 0.75)+ self.lines([[(x - w * 0.36, y - s * 0.66), (x - w * 0.38, y - s * 0.2)]], 1.4, '#ffffff', 0.55, taper=0.4)+ lid = np.array([(-0.4, -0.84), (0.4, -0.84), (0.42, -0.98), (-0.42, -0.98)]) * [w, s] + [x, y]+ self.shapes([lid], '#6b6066', 1, ss=4)+ self.lines([[(x - w * 0.4, y - s * 0.9), (x + w * 0.4, y - s * 0.9)]], 0.7, '#9a8e92', 0.8)+ th = np.linspace(np.pi, 2 * np.pi, 20)+ handle = np.stack([x + np.cos(th) * w * 0.42, y - s * 0.95 + np.sin(th) * s * 0.42], 1)+ self.lines([handle], 1.1, '#5b5157', 0.9)++ def kite(self, cx, cy, size=120.0, tilt=0.25, colours=('kite_cream', 'kite'), tail=None, bows=('kite', 'kite_cream', 'lupine'),+ seed=None):+ """a four-panel diamond kite (cx, cy = where the spars cross) with spars, a fine outline, a bridle and a+ streaming tail of bows. tail = list of (dx, dy) control offsets from the bottom point (default: streaming+ down and to the right). Returns the bridle knot (to tie the string to)."""+ r = self._r(seed)+ h = size+ c, s_ = np.cos(tilt), np.sin(tilt)+ R = lambda P: np.stack([cx + np.asarray(P, np.float32)[:, 0] * c - np.asarray(P, np.float32)[:, 1] * s_,+ cy + np.asarray(P, np.float32)[:, 0] * s_ + np.asarray(P, np.float32)[:, 1] * c], 1)+ top, right, bottom, left, o = (0, -0.36 * h), (0.31 * h, 0.0), (0, 0.66 * h), (-0.31 * h, 0.0), (0, 0)+ tri = [R([o, left, top]), R([o, top, right]), R([o, right, bottom]), R([o, bottom, left])]+ cA, cB = hexc(colours[0]), hexc(colours[1])+ cols = [cA * 1.02, cB, cA * 0.9, cB * 0.84]+ self.shapes(tri, np.clip(np.stack(cols), 0, 1), 1, ss=4, tex=0.04)+ # a faint paper texture: a few fibres and the crease where the paper folds over the spar+ self.lines([R([(left[0] * 0.92, 0), (right[0] * 0.92, 0)]), R([(0, top[1] * 0.9), (0, bottom[1] * 0.94)])], max(1.2, h * 0.016), 'spar', 0.85)+ outline = R([top, right, bottom, left, top])+ self.lines([outline], max(0.8, h * 0.009), '#5a3f3a', 0.7, wobble=0.2)+ hem = R(np.array([top, right, bottom, left, top], np.float32) * 0.9)+ self.lines([hem], 0.6, '#8d4f45', 0.35)+ # bridle: from the top and the low spar point to the knot in front+ knot = R([(-0.16 * h, 0.2 * h)])[0]+ self.lines([[R([(0, -0.25 * h)])[0], knot], [R([(0, 0.42 * h)])[0], knot]], 0.7, '#4c4246', 0.75)+ # tail+ b = R([bottom])[0]+ tail = tail or [(0, 0), (0.12, 0.35), (0.02, 0.7), (0.2, 1.05), (0.12, 1.4), (0.32, 1.75)]+ T = spline(np.asarray(tail, np.float32) * h + b, 10)+ self.lines([T], max(0.8, h * 0.008), '#4c4246', 0.8, wobble=0.5)+ Ts = _resample(T, h * 0.26)[1:]+ bow_polys, bow_cols = [], []+ for i, p in enumerate(Ts):+ dvec = T[min(len(T) - 1, np.argmin(np.linalg.norm(T - p, axis=1)) + 2)] - p+ ang = np.arctan2(dvec[1], dvec[0]) + np.pi / 2+ bs = h * 0.07 * r.uniform(0.85, 1.15)+ ca, sa = np.cos(ang), np.sin(ang)+ for side in (-1, 1):+ pts = np.array([(0, 0), (side * bs, -bs * 0.55), (side * bs * 1.05, bs * 0.55)], np.float32)+ bow_polys.append(np.stack([p[0] + pts[:, 0] * ca - pts[:, 1] * sa, p[1] + pts[:, 0] * sa + pts[:, 1] * ca], 1))+ bow_cols.append(hexc(bows[i % len(bows)]) * (0.9 if side < 0 else 1.0))+ if bow_polys: self.shapes(bow_polys, np.stack(bow_cols), 1, ss=4)+ return (float(knot[0]), float(knot[1]))++ def nightline(self, path, width=0.9, dusk='string', night='#d8d6e2', alpha=0.85, pieces=16):+ """a fine line whose ink follows the sky behind it: dark against dusk, silver against night"""+ Q = _resample(np.asarray(path, np.float32), 2.0)+ k = max(1, min(pieces, len(Q) // 3))+ cut = np.linspace(0, len(Q) - 1, k + 1).astype(int)+ with self.unlit():+ for a, b in zip(cut[:-1], cut[1:]):+ seg = Q[a:b + 1]+ xy = seg[len(seg) // 2]+ n = float(self._Nsky[int(np.clip(xy[1], 0, self.H - 1)), int(np.clip(xy[0], 0, self.W - 1))])+ self.lines([seg], width, mix(dusk, night, min(1.0, n * 1.3)), alpha, caps=False)++ def kite_string(self, p0, p1, sag=40.0, width=0.9, dusk='string', night='#d8d6e2', alpha=0.85):+ """the flying line from the hand to the bridle: a slight sag; dark against dusk, silver against night"""+ p0 = np.asarray(p0, np.float32); p1 = np.asarray(p1, np.float32)+ m = (p0 + p1) / 2 + np.array([0, sag], np.float32)+ t = np.linspace(0, 1, 160)[:, None]+ Q = (1 - t) ** 2 * p0 + 2 * (1 - t) * t * m + t ** 2 * p1+ self.nightline(Q, width, dusk, night, alpha)++ # ================================================================== plate: hatching, dimensions, inset+ def leader(self, p0, p1, colour='ink', width=0.8, alpha=0.8, lit=False):+ self.lines([[p0, p1]], width, colour, alpha, lit=lit)++ def wash(self, pts, colour, alpha=0.55, edge=0.35, lit=False, seed=None):+ """a flat watercolour tint inside a polygon, a little darker at its edge, faintly mottled"""+ r = self._r(seed)+ m, sl = self._local([pts], ss=3)+ e = np.clip(m - blur(m, 2.5), 0, 1) * 2+ n = noise2d(m.shape[0], m.shape[1], 14, 2, int(r.integers(1 << 30)))+ self._comp(m * alpha * (0.85 + edge * e + 0.15 * (n - 0.5)), colour, sl, lit)++ def hatch(self, shape, angle=45.0, spacing=5.0, width=0.8, colour='ink', alpha=0.75, jitter=0.6, lit=False, seed=None):+ """parallel hand lines clipped to a shape (polygon points or a full-canvas mask); angle in degrees.+ Call twice with different angles to cross-hatch."""+ r = self._r(seed)+ if isinstance(shape, np.ndarray) and shape.shape == (self.H, self.W):+ ys_, xs_ = np.where(shape > 0.5)+ if not len(ys_): return+ m, oy, ox = shape, 0, 0+ bx0, bx1, by0, by1 = xs_.min(), xs_.max() + 1, ys_.min(), ys_.max() + 1+ else:+ m, sl = self._local([shape], ss=2)+ oy, ox = sl[0].start, sl[1].start+ bx0, by0, bx1, by1 = ox, oy, ox + m.shape[1], oy + m.shape[0]+ a = np.deg2rad(angle); u = np.array([np.cos(a), np.sin(a)]); nv = np.array([-u[1], u[0]])+ corners = np.array([(bx0, by0), (bx1, by0), (bx0, by1), (bx1, by1)], np.float32)+ on = corners @ nv; ou = corners @ u+ paths = []+ k = on.min() + r.uniform(0, spacing)+ while k < on.max():+ o = k + r.normal(0, jitter * 0.3)+ ts = np.arange(ou.min(), ou.max(), 1.0)+ P = ts[:, None] * u + o * nv+ ix = np.clip(P[:, 0].astype(int) - ox, 0, m.shape[1] - 1); iy = np.clip(P[:, 1].astype(int) - oy, 0, m.shape[0] - 1)+ inb = (P[:, 0] >= bx0) & (P[:, 0] < bx1) & (P[:, 1] >= by0) & (P[:, 1] < by1)+ ins = inb & (m[iy, ix] > 0.5)+ dif = np.diff(np.concatenate([[0], ins.astype(int), [0]]))+ for s0, s1 in zip(np.where(dif == 1)[0], np.where(dif == -1)[0]):+ if s1 - s0 < 2: continue+ e0 = s0 + r.uniform(0, 1.2) ; e1 = s1 - 1 - r.uniform(0, 1.2)+ paths.append(np.array([P[0] + u * (e0 + r.normal(0, 0.3)), P[0] + u * (e1 + r.normal(0, 0.3))]))+ k += spacing * r.uniform(0.85, 1.15)+ if paths: self.lines(paths, width, colour, alpha, lit=lit)++ def dimension(self, p0, p1, text=None, offset=16.0, tick=5.0, colour='ink', width=0.8, size=15, alpha=0.85, lit=False,+ across=False, lead=26.0):+ """a drafting dimension: extension lines, the dimension line with architect's ticks, a small label.+ across=True measures across a member that runs out of view (a spar, a stem): the line crosses it from p0 to+ p1 with ticks on both flanks and is carried out `lead` px beyond p0 to the label (e.g. 'ø 6')."""+ p0 = np.asarray(p0, np.float32); p1 = np.asarray(p1, np.float32)+ u = (p1 - p0) / (np.linalg.norm(p1 - p0) + 1e-6); nv = np.array([-u[1], u[0]], np.float32)+ if across:+ tv = (u + nv) * tick * 0.5+ self.lines([[p0 - u * lead, p1 + u * 6], [p0 - tv, p0 + tv], [p1 - tv, p1 + tv]], width, colour, alpha, lit=lit)+ if text:+ e = p0 - u * (lead + 3)+ self.caption(float(e[0]), float(e[1] + size * 0.32), text, size, colour, alpha, anchor='r' if u[0] >= 0 else 'l',+ jitter=0.5, lit=lit)+ return+ q0, q1 = p0 + nv * offset, p1 + nv * offset+ paths = [[p0 + nv * 3, q0 + nv * 4], [p1 + nv * 3, q1 + nv * 4], [q0 - u * 3, q1 + u * 3]]+ tv = (u + nv) * tick * 0.5+ paths += [[q0 - tv, q0 + tv], [q1 - tv, q1 + tv]]+ self.lines(paths, width, colour, alpha, lit=lit)+ if text:+ ang = np.degrees(np.arctan2(u[1], u[0]))+ if ang > 90: ang -= 180+ if ang < -90: ang += 180+ th = np.deg2rad(-ang) # caption rotation (ccw)+ up = np.array([-np.sin(th), -np.cos(th)], np.float32) # where the letters stand up to+ away = nv * (1.0 if offset >= 0 else -1.0) # the side away from the object+ centre = (q0 + q1) / 2 + away * (3 + size * 0.42)+ base = centre - up * size * 0.3+ self.caption(float(base[0]), float(base[1]), text, size, colour, alpha, anchor='m', rot=-ang, jitter=0.5, lit=lit)++ def ruler(self, x0, y, x1, h=12.0, step=4.0, colour='ink', fill='#ebe3d6', labels=None, size=11, lit=False):+ """a little scale bar: a light strip, mm ticks, long ticks every five, optional numbers"""+ box = np.array([(x0, y), (x1, y), (x1, y + h), (x0, y + h)], np.float32)+ self.shapes([box], fill, 0.9, lit=lit)+ self.lines([np.vstack([box, box[:1]])], 0.8, colour, 0.85, lit=lit)+ paths = []+ n = int((x1 - x0) / step)+ for i in range(n + 1):+ x = x0 + i * step+ L = h * (0.62 if i % 10 == 0 else 0.45 if i % 5 == 0 else 0.28)+ paths.append([(x, y), (x, y + L)])+ self.lines(paths, 0.6, colour, 0.8, lit=lit)+ if labels:+ for i, lab in labels:+ self.caption(x0 + i * step, y + h + size * 1.2, lab, size, colour, 0.85, anchor='m', jitter=0.4, lit=lit)++ def inset(self, cx, cy, r, draw=None, target=None, label='detail a', sub='not to scale', paper='paper', ring='ink',+ label_colour='caption', size=26, marker=13.0, leader_colour=None, seed=None):+ """the circular magnified view: a paper disc with a faint shadow, `draw(t, cx, cy, r)` clipped inside it, a+ thin double ring, a marker ring on the target with a leader line, and a small handwritten label below"""+ rr = self._r(seed)+ with self.unlit():+ disc = self.ellipse(cx, cy, r)+ sh = blur(np.roll(np.roll(disc, 5, 0), 3, 1), 9)+ self.fill(np.clip(sh - disc, 0, 1) * 0.22, '#2a2032')+ self.fill(disc, paper)+ box = (slice(max(0, int(cy - r - 2)), min(self.H, int(cy + r + 3))), slice(max(0, int(cx - r - 2)), min(self.W, int(cx + r + 3))))+ n = noise2d(box[0].stop - box[0].start, box[1].stop - box[1].start, 9, 3, int(rr.integers(1 << 30)))+ self._comp(disc[box] * (n - 0.5) * 0.12, '#b9a68f', box)+ if draw:+ with self.clipped(disc):+ draw(self, cx, cy, r)+ th = np.linspace(0, 2 * np.pi, 240)+ circ = lambda R: np.stack([cx + np.cos(th) * R, cy + np.sin(th) * R], 1)+ self.lines([circ(r)], 2.0, ring, 0.9)+ self.lines([circ(r - 5)], 0.7, ring, 0.55)+ if target is not None:+ tx, ty = target+ v = np.array([cx - tx, cy - ty], np.float32); d = float(np.linalg.norm(v)); v /= d + 1e-6+ mk = np.stack([tx + np.cos(th) * marker, ty + np.sin(th) * marker], 1)+ lead = np.array([(tx + v[0] * marker, ty + v[1] * marker), (cx - v[0] * (r + 1), cy - v[1] * (r + 1))], np.float32)+ if leader_colour:+ self.lines([mk], 0.9, leader_colour, 0.85); self.lines([lead], 0.8, leader_colour, 0.8)+ else:+ self.nightline(mk, 0.9, ring, 'pale', 0.85, pieces=12); self.nightline(lead, 0.8, ring, 'pale', 0.8)+ if label: self.caption(cx, cy + r + size * 1.5, label, size, label_colour, 0.92, anchor='m')+ if sub: self.caption(cx + size * 0.4, cy + r + size * 2.45, sub, size * 0.66, label_colour, 0.8, anchor='m')++ # ================================================================== handwriting+ _FONT_CACHE = {}++ @staticmethod+ def _hand_font(size):+ key = int(size)+ if key in TwilightStorybook._FONT_CACHE: return TwilightStorybook._FONT_CACHE[key]+ f = None+ env = os.environ.get('INKPAINT_FONT_HAND_LIGHT')+ cands = ([(env, 0)] if env else []) + [('/System/Library/Fonts/Noteworthy.ttc', 0),+ ('/System/Library/Fonts/Supplemental/Noteworthy.ttc', 0),+ ('/usr/share/fonts/**/*Caveat*Regular*.ttf', 0),+ ('/usr/share/fonts/**/*Kalam*Light*.ttf', 0),+ ('C:/Windows/Fonts/segoepr.ttf', 0)]+ for pat, idx in cands:+ hits = glob.glob(pat, recursive=True) if pat else []+ if hits:+ try:+ f = ImageFont.truetype(hits[0], key, index=idx); break+ except OSError:+ pass+ f = f or load_font('hand', key)+ TwilightStorybook._FONT_CACHE[key] = f+ return f++ def caption(self, x, y, text, size=30, colour='caption', alpha=0.88, anchor='l', jitter=1.0, tracking=0.05, rot=0.0,+ lit=False, seed=None):+ """tiny lowercase handwriting: thin hand font set glyph by glyph (own tilt, baseline wobble, spacing and+ pressure per letter), rendered at 2x, faint pencil texture. (x, y) is the baseline; anchor l / m / r;+ rot in degrees counter-clockwise."""+ r = self._r(seed)+ ss = 2+ S = size * ss+ F = self._hand_font(S)+ adv = [F.getlength(ch) + tracking * S + r.normal(0, 0.02 * S * jitter) for ch in text]+ total = float(sum(adv))+ pad = int(S)+ w = int(total + 2 * pad); h = int(S * 2.4)+ by = int(S * 1.5)+ arr = np.zeros((h, w), np.float32)+ cx = float(pad)+ for ch, a in zip(text, adv):+ if ch.strip():+ gw = int(a + S)+ g = Image.new('L', (gw, h), 0)+ ImageDraw.Draw(g).text((S * 0.5, by + r.normal(0, 0.03 * S * jitter)), ch, font=F, fill=255, anchor='ls')+ ang = r.normal(0, 2.2 * jitter)+ if abs(ang) > 0.05: g = g.rotate(ang, resample=Image.BICUBIC, center=(S * 0.5 + a / 2, by))+ ga = np.asarray(g, np.float32) / 255 * r.uniform(0.78, 1.0)+ xo = int(round(cx - S * 0.5))+ a0, a1 = max(0, xo), min(w, xo + gw)+ arr[:, a0:a1] = np.maximum(arr[:, a0:a1], ga[:, a0 - xo:a1 - xo])+ cx += a+ im = Image.fromarray((np.clip(arr, 0, 1) * 255).astype(np.uint8))+ ax = {'l': 0.0, 'm': 0.5, 'r': 1.0}[anchor]+ if rot: im = im.rotate(rot, resample=Image.BICUBIC, center=(pad + total * ax, by))+ m = np.asarray(im.reduce(ss), np.float32) / 255+ hh, ww = m.shape+ tx = blur(r.random((hh, ww)).astype(np.float32), 0.6)+ m = m * (0.82 + 0.3 * (tx - 0.5))+ X0 = int(round(x - (pad + total * ax) / ss)); Y0 = int(round(y - by / ss))+ x0, y0 = max(0, X0), max(0, Y0); x1, y1 = min(self.W, X0 + ww), min(self.H, Y0 + hh)+ if x1 <= x0 or y1 <= y0: return+ self._comp(m[y0 - Y0:y1 - Y0, x0 - X0:x1 - X0] * alpha, colour, (slice(y0, y1), slice(x0, x1)), lit)++ # ================================================================== finish and output+ def finish(self, grain=1.0, vignette=1.0, bloom=1.0, soft=1.0, edge=0.0, paper='paper'):+ """slight softness, bloom round the lights, grain and paper mottle, a gentle plum vignette and optionally+ a torn paper strip `edge` px tall along the bottom (applied in render)"""+ self.fin = dict(grain=grain, vignette=vignette, bloom=bloom, soft=soft, edge=edge, paper=paper)++ def render(self):+ out = self.C.copy()+ f = self.fin+ if f:+ H, W = self.H, self.W+ if f['soft']:+ sb = np.stack([blur(out[..., i], 0.75) for i in range(3)], -1)+ out = out * (1 - 0.28 * f['soft']) + sb * 0.28 * f['soft']+ if f['bloom']:+ lum = out @ _LUMA+ g = blur(np.clip(lum - 0.74, 0, 1), 14) * 1.3 + blur(np.clip(lum - 0.6, 0, 1), 5) * 0.5+ out = 1 - (1 - out) * (1 - f['bloom'] * g[..., None] * hexc('#fff1d6'))+ if f['grain']:+ if not hasattr(self, '_grain'):+ r = np.random.default_rng(self.seed + 7)+ g = r.normal(0, 1, (H, W)).astype(np.float32)+ g = 0.65 * g + 0.35 * blur(g, 1.0) * 2.0+ mot = noise2d(H, W, 22, 3, self.seed + 8) - 0.5+ self._grain = (0.016 * g + 0.03 * mot).astype(np.float32)+ lum = out @ _LUMA+ out = out * (1 + f['grain'] * self._grain * (0.6 + 0.6 * (1 - lum)))[..., None]+ if f['vignette']:+ yy = (np.arange(H, dtype=np.float32)[:, None] / H - 0.5) / 0.62+ xx = (np.arange(W, dtype=np.float32)[None] / W - 0.5) / 0.62+ v = smoothstep(0.35, 1.45, xx * xx + yy * yy) * 0.2 * f['vignette']+ out = out * (1 - v[..., None] * (1 - 0.35 * hexc('#5a3a5c')))+ if f['edge']:+ r = np.random.default_rng(self.seed + 9)+ e = f['edge'] + fbm1d(W, 40, 4, self.seed + 10) * 3.0 + fbm1d(W, 6, 2, self.seed + 12) * 0.9+ yy = np.arange(H, dtype=np.float32)[:, None]+ m = smoothstep(H - e[None] - 0.8, H - e[None] + 0.8, yy)+ pc = hexc(f['paper']) * (1 + 0.025 * (noise2d(H, W, 6, 2, self.seed + 13) - 0.5))[..., None]+ sh = smoothstep(H - e[None] - 5, H - e[None], yy) * (1 - m) * 0.25+ out = out * (1 - sh[..., None])+ out = out * (1 - m[..., None]) + pc * m[..., None]+ return np.clip(out, 0, 1)++ def composite(self):+ return Image.fromarray((self.render() * 255 + 0.5).astype(np.uint8))++ def stage(self, name):+ if not self.keep_stages: return+ im = self.composite()+ if self.stages_dir:+ os.makedirs(self.stages_dir, exist_ok=True)+ im.save(f'{self.stages_dir}/{self._n_stages:02d}_{name}.png', compress_level=1)+ else:+ b = io.BytesIO(); im.save(b, 'PNG', compress_level=1)+ self.stages.append((name, b.getvalue()))+ self._n_stages += 1++ 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)+ sd = stages_dir or self.stages_dir+ if sd and self.keep_stages:+ os.makedirs(sd, exist_ok=True)+ for i, (name, b) in enumerate(self.stages):+ with open(f'{sd}/{i:02d}_{name}.png', 'wb') as f: f.write(b)+ img.save(f'{sd}/{self._n_stages:02d}_final.png', compress_level=1)+ return img