184 lines
7.8 KiB
Python
184 lines
7.8 KiB
Python
"""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
|
|
local = np.clip(delta/max(d.continuity,1e-8), -np.pi, np.pi)
|
|
folded = radius*(np.cos(local)+np.sin(angle)*1.45*z*np.sin(local))
|
|
score = folded-1+depth
|
|
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)
|