diff --git a/brand/ribbon-study/field/README.md b/brand/ribbon-study/field/README.md new file mode 100644 index 0000000..e9b59fa --- /dev/null +++ b/brand/ribbon-study/field/README.md @@ -0,0 +1,28 @@ +# 色带生成器 + +此目录可以独立使用。Python 依赖为 NumPy 和 Pillow。运行以下命令生成一枚五圈的窄带螺旋: + +```sh +python3 generate.py --layout spiral --faces 5 --width .35 --continuity .94 --twist 38 --tilt -20 --palette '#ff967e' '#f9d2b0' '#b5c5c5' --background '#461646' --size 512 --output spiral.png +``` + +| 参数 | 含义 | +| --- | --- | +| `--layout` | `rings` 为球面纬带,`spiral` 为绕球的一条螺旋,`petals` 为绕中心分布的瓣 | +| `--faces` | 1 至 16,分别表示纬带数、螺旋圈数或瓣数;投影后可见的色块还受遮挡影响 | +| `--continuity` | 0 至 1,沿带长保留的范围。0 为纯背景,1 取消沿长度方向的裁切 | +| `--width` | 大于 0 且不超过 1,控制纬带及螺旋的相对宽度,或花瓣从外缘向内延伸的深度 | +| `--twist` | 扭转角度,正负改变形变方向 | +| `--tilt` | 整枚图形在画面内的旋转角度 | +| `--palette` | 一个或多个十六进制基色。环与瓣依序循环使用,螺旋沿带长平滑换色 | +| `--background` | 背景色,也参与背面色的计算 | + +`--size` 控制单枚图像的像素尺寸,`--output` 指定 PNG 输出路径。相同参数可重复得到相同图形。 + +```sh +python3 generate.py --study --size 124 --output study.png +``` + +参数对照图前三行分别只改面数(2、3、4、6)、连续性(0.28、0.52、0.76、1)、扭转角(−55°、−15°、25°、65°)。第四行依次展示纬带、螺旋、四瓣及三瓣组合。 + +每个像素沿视线与单位球壳相交两次。生成器在两个交点分别计算色带的覆盖情况,再根据基色、面内渐变和背景色绘制正面、背面与重叠部分。图形完全由参数生成。 diff --git a/brand/ribbon-study/field/generate.py b/brand/ribbon-study/field/generate.py new file mode 100644 index 0000000..9386433 --- /dev/null +++ b/brand/ribbon-study/field/generate.py @@ -0,0 +1,183 @@ +"""Generate ribbon fields with NumPy and Pillow. Run --help for the design controls.""" +import argparse +from dataclasses import dataclass, replace +from pathlib import Path + +import numpy as np +from PIL import Image, ImageColor + +HERE = Path(__file__).resolve().parent + + +@dataclass(frozen=True) +class Design: + layout: str = "spiral" + faces: int = 4 + continuity: float = .88 + width: float = .46 + twist: float = 24 + tilt: float = -14 + palette: tuple = ("#ff967e", "#f9d2b0", "#b5c5c5") + background: str = "#461646" + + +def rgb(code): + if len(code) != 7 or not code.startswith("#"): + raise ValueError("colours must use #RRGGBB") + return np.array(ImageColor.getrgb(code), dtype=float) + + +def check(d): + if d.layout not in ("rings", "spiral", "petals"): + raise ValueError("layout must be rings, spiral or petals") + if not 1 <= d.faces <= 16: + raise ValueError("faces must be 1..16") + if not 0 <= d.continuity <= 1 or not 0 < d.width <= 1: + raise ValueError("continuity must be 0..1 and width must be greater than 0 and at most 1") + if not np.isfinite([d.twist, d.tilt]).all(): + raise ValueError("angles must be finite") + if not d.palette: + raise ValueError("supply at least one base colour") + + +def mix(a, b, weight): + return a + (b-a)*weight + + +def coverage(along, continuity): + """Angular half-length of a round-ended arc; 1 closes the whole loop.""" + if continuity == 1: + return np.ones_like(along) + distance = np.abs((along + np.pi) % (2*np.pi) - np.pi) / np.pi + shoulder = min(.12, continuity) + inside = np.clip((continuity-distance)/max(shoulder, 1e-8), 0, 1) + return np.sqrt(inside*(2-inside)) + + +def face(d, x, y, z, palette): + angle = np.deg2rad(d.twist) + if d.layout == "petals": + # Radial sectors on the shell. Opposite depths shear the two sides + # of each petal in opposite directions and create the crossing. + frequency = d.faces/(2*np.pi) + turn = np.arctan2(x, y) + radius = np.hypot(x,y) + best = np.full_like(x,-np.inf) + index = np.zeros_like(x,dtype=int) + along = np.zeros_like(x) + for sector in range(d.faces): + orientation = sector/frequency + delta = (turn-orientation+np.pi)%(2*np.pi)-np.pi + # Scale each cap with angular spacing so higher face counts + # still leave a legible opening between neighbouring lobes. + half_span = min(np.pi/2, np.pi/d.faces) + depth = (1-np.cos(half_span))*d.width + taper = coverage(delta*min(d.faces,4)/2, d.continuity) + folded = radius*(np.cos(delta)+np.sin(angle)*1.45*z*np.sin(delta)) + score = np.where(taper > 0, folded-1+depth*taper, -np.inf) + active = score > best + index = np.where(active,sector,index) + along = np.where(active,np.sin(delta),along) + best = np.maximum(best,score) + visible = (best > 0) & (d.continuity > 0) + else: + # Rotate latitude circles by a longitude-dependent angle. This + # deformation stays on the unit sphere for either sign of depth. + bend = angle*x + v = y*np.cos(bend) + z*np.sin(bend) + w = z*np.cos(bend) - y*np.sin(bend) + longitude = np.arctan2(w, x) + latitude = np.arcsin(np.clip(v,-1,1))/np.pi+.5 + phase = latitude*d.faces-.5 + if d.layout == "spiral": + phase -= longitude/(2*np.pi) + index = np.floor(phase+.5).astype(int) + along = np.sin(longitude) + # Spiral sectors use a periodic cut at the same meridian every turn. + # Separate rings can stagger their cuts without a seam. + offset = 0 if d.layout == "spiral" else index*2.39996 + taper = coverage(longitude+offset, d.continuity) + visible = (np.abs(phase-index) < .5*d.width*taper) & (taper > 0) + if d.layout == "spiral": + # Vary pigment continuously with latitude, including across the seam + # where the spiral's integer winding number changes. + pigment = latitude*d.faces + band = np.floor(pigment).astype(int) + f = pigment-band + f = f*f*(3-2*f) + color = mix(palette[band%len(palette)], palette[(band+1)%len(palette)], f[...,None]) + else: + color = palette[index%len(palette)] + glow = np.clip(.09-.13*x+.12*y+.09*along, 0, .42) + return visible, mix(color, 255., glow[...,None]) + + +def render(d, size=256): + check(d) + if not 16 <= size <= 2048: + raise ValueError("size must be 16..2048") + palette = np.array([rgb(c) for c in d.palette]) + bg = rgb(d.background) + axis = (np.arange(size*3)+.5) * 2.16/(size*3)-1.08 + output = np.empty((size,size,3), dtype=np.uint8) + roll = np.deg2rad(d.tilt) + for start in range(0,size,16): + stop = min(start+16,size) + xx, yy = np.meshgrid(axis,-axis[start*3:stop*3]) + x = xx*np.cos(roll) - yy*np.sin(roll) + y = xx*np.sin(roll) + yy*np.cos(roll) + radius2 = x*x+y*y + z = np.sqrt(np.maximum(0,1-radius2)) + front, ink = face(d,x,y,z,palette) + back, reverse = face(d,x,y,-z,palette) + # Back faces receive less light. The same base pigments determine + # the rear and overlap colours even when the palette is changed. + rear = mix(bg,reverse,.44) + both = mix(ink,reverse,.24) + both = mix(both,255.,(.06+.18*z)[...,None]) + paint = np.where(front[...,None],np.where(back[...,None],both,ink),rear) + paint = np.where(((front|back)&(radius2<=1))[...,None],paint,bg) + block = paint.reshape(stop-start,3,size,3,3).mean(axis=(1,3)) + output[start:stop] = np.rint(block).astype(np.uint8) + return Image.fromarray(output) + + +def study(d, size): + # The first three rows isolate one control; the last shows layout examples. + rows = [("faces",(2,3,4,6)), ("continuity",(.28,.52,.76,1)), + ("twist",(-55,-15,25,65)), ("layout",("rings","spiral","petals","petals"))] + gap = max(6, size//6) + cell = size+gap + canvas = Image.new("RGB",(4*cell+gap,4*cell+gap),d.background) + for row,(key,values) in enumerate(rows): + for col,value in enumerate(values): + variant = replace(d,**{key:value}) + if row==3 and col==3: + variant = replace(variant,faces=3, width=.65, twist=38, tilt=0, continuity=1) + canvas.paste(render(variant,size),(gap+col*cell,gap+row*cell)) + return canvas + + +if __name__ == "__main__": + defaults = Design() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--layout", choices=("rings","spiral","petals"), default=defaults.layout) + parser.add_argument("--faces",type=int,default=defaults.faces,help="rings, spiral turns or petals (1..16)") + parser.add_argument("--continuity",type=float,default=defaults.continuity,help="arc coverage (0..1)") + parser.add_argument("--width",type=float,default=defaults.width,help="fraction of spacing filled (0..1]") + parser.add_argument("--twist",type=float,default=defaults.twist,help="spherical deformation in degrees") + parser.add_argument("--tilt",type=float,default=defaults.tilt,help="image-plane rotation in degrees") + parser.add_argument("--palette",nargs="+",default=defaults.palette,help="one or more #RRGGBB colours") + parser.add_argument("--background",default=defaults.background,help="#RRGGBB") + parser.add_argument("--size",type=int,default=256) + parser.add_argument("--output",required=True,type=Path) + parser.add_argument("--study",action="store_true",help="render a 4 by 4 parameter comparison") + args = parser.parse_args() + design = Design(**{key:getattr(args,key) for key in Design.__dataclass_fields__}) + try: + if not 16 <= args.size <= 2048: + raise ValueError("size must be 16..2048") + img = study(design,args.size) if args.study else render(design,args.size) + except ValueError as error: + parser.error(str(error)) + img.save(args.output) diff --git a/brand/ribbon-study/field/study.png b/brand/ribbon-study/field/study.png new file mode 100644 index 0000000..6b1314c Binary files /dev/null and b/brand/ribbon-study/field/study.png differ