motionkit2d 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- motionkit2d/__init__.py +49 -0
- motionkit2d/__main__.py +115 -0
- motionkit2d/acceleration.py +121 -0
- motionkit2d/assets.py +319 -0
- motionkit2d/audio.py +87 -0
- motionkit2d/audio_analysis.py +55 -0
- motionkit2d/camera.py +56 -0
- motionkit2d/catalog.py +79 -0
- motionkit2d/characters/__init__.py +4 -0
- motionkit2d/characters/actions.py +125 -0
- motionkit2d/characters/builder.py +15 -0
- motionkit2d/characters/expressions.py +81 -0
- motionkit2d/compiler.py +162 -0
- motionkit2d/composition.py +50 -0
- motionkit2d/constraints.py +91 -0
- motionkit2d/cues.py +15 -0
- motionkit2d/draw.py +416 -0
- motionkit2d/dynamics.py +109 -0
- motionkit2d/effects.py +131 -0
- motionkit2d/environments.py +86 -0
- motionkit2d/export.py +235 -0
- motionkit2d/fonts/LICENSE.txt +130 -0
- motionkit2d/fonts/LiberationSans-Regular.ttf +0 -0
- motionkit2d/fonts/LiberationSerif-Bold.ttf +0 -0
- motionkit2d/fonts/LiberationSerif-Regular.ttf +0 -0
- motionkit2d/gpu.py +512 -0
- motionkit2d/layout.py +89 -0
- motionkit2d/manifest.py +96 -0
- motionkit2d/mixer.py +92 -0
- motionkit2d/preset_library.py +41 -0
- motionkit2d/presets.py +33 -0
- motionkit2d/props.py +126 -0
- motionkit2d/qc.py +78 -0
- motionkit2d/quality.py +122 -0
- motionkit2d/rig.py +325 -0
- motionkit2d/scene_graph.py +154 -0
- motionkit2d/timeline.py +174 -0
- motionkit2d/transitions.py +51 -0
- motionkit2d/typography.py +118 -0
- motionkit2d/visual_effects.py +104 -0
- motionkit2d-1.0.0.dist-info/METADATA +140 -0
- motionkit2d-1.0.0.dist-info/RECORD +45 -0
- motionkit2d-1.0.0.dist-info/WHEEL +5 -0
- motionkit2d-1.0.0.dist-info/entry_points.txt +2 -0
- motionkit2d-1.0.0.dist-info/top_level.txt +1 -0
motionkit2d/draw.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""Deterministic vector-style drawing and compositing primitives."""
|
|
2
|
+
import math as m
|
|
3
|
+
import random
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from unicodedata import normalize
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from PIL import Image, ImageColor, ImageDraw, ImageFilter, ImageFont
|
|
10
|
+
|
|
11
|
+
S = 2
|
|
12
|
+
WHITE, GRAY, MINT = '#ECEAE3', '#B7B9B2', '#65E595'
|
|
13
|
+
PINK, BLUE, YELLOW, RED = '#F294AF', '#98AFE2', '#F9C54C', '#FF405D'
|
|
14
|
+
GOLD, BRASS = '#F5CC69', '#CEC79A'
|
|
15
|
+
FONT_DIR = Path(__file__).resolve().parent / 'fonts'
|
|
16
|
+
FONT_REGISTRY = {}
|
|
17
|
+
|
|
18
|
+
def register_font(name,path):
|
|
19
|
+
path=Path(path).resolve()
|
|
20
|
+
if not name or name in {'regular','bold','sans'} or name in FONT_REGISTRY:
|
|
21
|
+
raise ValueError('Font alias must be unique')
|
|
22
|
+
ImageFont.truetype(str(path),16) # Validate before publishing alias.
|
|
23
|
+
FONT_REGISTRY[name]=path
|
|
24
|
+
font.cache_clear()
|
|
25
|
+
|
|
26
|
+
def clamp(x):
|
|
27
|
+
return max(0., min(1., x))
|
|
28
|
+
|
|
29
|
+
def ease(x):
|
|
30
|
+
x = clamp(x)
|
|
31
|
+
return x*x*(3-2*x)
|
|
32
|
+
|
|
33
|
+
def ramp(t, a, b):
|
|
34
|
+
return ease((t-a)/(b-a))
|
|
35
|
+
|
|
36
|
+
def lerp(a, b, t):
|
|
37
|
+
return a+(b-a)*t
|
|
38
|
+
|
|
39
|
+
@lru_cache(maxsize=1024)
|
|
40
|
+
def rgb(color):
|
|
41
|
+
return ImageColor.getrgb(color)
|
|
42
|
+
|
|
43
|
+
def mix(a, b, t):
|
|
44
|
+
return '#%02x%02x%02x' % tuple(round(lerp(x,y,t)) for x,y in zip(rgb(a),rgb(b)))
|
|
45
|
+
|
|
46
|
+
def rgba(c, a):
|
|
47
|
+
return (*rgb(c), round(255*clamp(a)))
|
|
48
|
+
|
|
49
|
+
def px(points):
|
|
50
|
+
return [(round(x*S), round(y*S)) for x,y in points]
|
|
51
|
+
|
|
52
|
+
def box(x,y,rx,ry):
|
|
53
|
+
return tuple(round(v*S) for v in (x-rx,y-ry,x+rx,y+ry))
|
|
54
|
+
|
|
55
|
+
def polygon(d, points, c):
|
|
56
|
+
if getattr(d,'_motionkit_gpu',False):
|
|
57
|
+
return d.polygon(points,c)
|
|
58
|
+
d.polygon(px(points), fill=c)
|
|
59
|
+
|
|
60
|
+
def oval(d,x,y,rx,ry,c,outline=None,width=1):
|
|
61
|
+
if getattr(d,'_motionkit_gpu',False):
|
|
62
|
+
return d.oval(x,y,rx,ry,c,outline,width)
|
|
63
|
+
d.ellipse(box(x,y,rx,ry),fill=c,outline=outline,width=max(1,round(width*S)))
|
|
64
|
+
|
|
65
|
+
def line(d, points, c, width=1, round_ends=False):
|
|
66
|
+
if getattr(d,'_motionkit_gpu',False):
|
|
67
|
+
return d.line(points,c,width,round_ends)
|
|
68
|
+
d.line(px(points),fill=c,width=max(1,round(width*S)),joint='curve')
|
|
69
|
+
if round_ends:
|
|
70
|
+
for x,y in (points[0],points[-1]):
|
|
71
|
+
oval(d,x,y,width/2,width/2,c)
|
|
72
|
+
|
|
73
|
+
def rect(d,x,y,w,h,r,c,outline=None,width=1):
|
|
74
|
+
if getattr(d,'_motionkit_gpu',False):
|
|
75
|
+
return d.rect(x,y,w,h,r,c,outline,width)
|
|
76
|
+
d.rounded_rectangle(box(x+w/2,y+h/2,w/2,h/2),radius=round(r*S),fill=c,
|
|
77
|
+
outline=outline,width=max(1,round(width*S)))
|
|
78
|
+
|
|
79
|
+
def draw(im):
|
|
80
|
+
if getattr(im,'_motionkit_gpu',False):
|
|
81
|
+
return im
|
|
82
|
+
return ImageDraw.Draw(im, 'RGBA') if im.mode == 'RGB' else ImageDraw.Draw(im)
|
|
83
|
+
|
|
84
|
+
def alpha(im, amount):
|
|
85
|
+
return im.point(lambda x: round(x*clamp(amount)))
|
|
86
|
+
|
|
87
|
+
def paste(im, layer, xy=(0,0), amount=1):
|
|
88
|
+
if getattr(im,'_motionkit_gpu',False):
|
|
89
|
+
return im.paste(layer,xy,amount)
|
|
90
|
+
if layer.mode != 'RGBA':
|
|
91
|
+
layer = layer.convert('RGBA')
|
|
92
|
+
mask = layer.getchannel('A')
|
|
93
|
+
if amount < 1:
|
|
94
|
+
mask = alpha(mask,amount)
|
|
95
|
+
if im.mode == 'RGBA':
|
|
96
|
+
if amount < 1:
|
|
97
|
+
layer = layer.copy()
|
|
98
|
+
layer.putalpha(mask)
|
|
99
|
+
im.alpha_composite(layer, xy)
|
|
100
|
+
else:
|
|
101
|
+
im.paste(layer, xy, mask)
|
|
102
|
+
|
|
103
|
+
@lru_cache(maxsize=24)
|
|
104
|
+
def halo_asset(rx, ry, c):
|
|
105
|
+
w,h = 2*rx*S+1, 2*ry*S+1
|
|
106
|
+
y,x = np.ogrid[-1:1:complex(0,h),-1:1:complex(0,w)]
|
|
107
|
+
values = np.maximum(0, np.exp(-4.6*(x*x+y*y))-.01)
|
|
108
|
+
mask = Image.fromarray((values*255).astype('uint8'))
|
|
109
|
+
layer = Image.new('RGBA',(w,h),rgb(c))
|
|
110
|
+
layer.putalpha(mask)
|
|
111
|
+
return layer
|
|
112
|
+
|
|
113
|
+
def halo(im, x,y,rx,ry,c,amount):
|
|
114
|
+
rx,ry = max(1,round(rx)),max(1,round(ry))
|
|
115
|
+
layer=halo_asset(rx,ry,c)
|
|
116
|
+
paste(im,layer,(round((x-rx)*S),round((y-ry)*S)),amount)
|
|
117
|
+
|
|
118
|
+
THEMES = {
|
|
119
|
+
'green': ('#07090B', '#0B2A22'),
|
|
120
|
+
'warm': ('#07090B', '#191B15'),
|
|
121
|
+
'plum': ('#09080D', '#26151F'),
|
|
122
|
+
'blue': ('#06090F', '#1A2A49'),
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@lru_cache(maxsize=12)
|
|
126
|
+
def _gradient(size, edge, center, focus):
|
|
127
|
+
width,height = size
|
|
128
|
+
y,x = np.ogrid[:height,:width]
|
|
129
|
+
distance = ((x-width*focus[0])/(width*.61))**2 + ((y-height*focus[1])/(height*.71))**2
|
|
130
|
+
weight = np.exp(-2.35*distance).astype('float32')
|
|
131
|
+
low = np.asarray(rgb(edge), dtype='float32')
|
|
132
|
+
high = np.asarray(rgb(center), dtype='float32')
|
|
133
|
+
data = low+weight[:,:,None]*(high-low)
|
|
134
|
+
dither = np.random.default_rng(17).uniform(-.6,.6,size[::-1]).astype('float32')
|
|
135
|
+
return Image.fromarray(np.uint8(np.clip(np.rint(data+dither[:,:,None]),0,255)))
|
|
136
|
+
|
|
137
|
+
def gradient(im, edge, center, *, focus=(.5,.5)):
|
|
138
|
+
"""Fill the canvas with an elliptical radial gradient."""
|
|
139
|
+
if getattr(im,'_motionkit_gpu',False):
|
|
140
|
+
return im.gradient(edge,center,focus)
|
|
141
|
+
im.paste(_gradient(im.size,edge,center,tuple(focus)))
|
|
142
|
+
|
|
143
|
+
@lru_cache(maxsize=32)
|
|
144
|
+
def _dust(seed,count):
|
|
145
|
+
rng = random.Random(seed)
|
|
146
|
+
return tuple((rng.random(),rng.random(),rng.uniform(.48,1.36),rng.uniform(0,m.tau),
|
|
147
|
+
rng.uniform(.13,.39),rng.randrange(6)==0) for _ in range(count))
|
|
148
|
+
|
|
149
|
+
def particles(im,t,*,seed=541,count=60,color='#B5D7B8',opacity=.8):
|
|
150
|
+
"""Draw deterministic drifting background particles at time t in seconds."""
|
|
151
|
+
d = draw(im)
|
|
152
|
+
w,h = (dimension/S for dimension in im.size)
|
|
153
|
+
for x,y,r,phase,a,dash in _dust(seed,count):
|
|
154
|
+
x = x*w+3.6*m.sin(phase+t*.43)
|
|
155
|
+
y = y*h+2.4*m.cos(phase+t*.62)
|
|
156
|
+
c = rgba(color,opacity*a*(.69+.31*m.sin(phase+t*1.02)))
|
|
157
|
+
if dash:
|
|
158
|
+
line(d,[(x-r,y+r),(x+r,y-r*.8)],c,.65)
|
|
159
|
+
else:
|
|
160
|
+
oval(d,x,y,r,r,c)
|
|
161
|
+
|
|
162
|
+
def stage(im,t,*,theme='green',floor=None,seed=541,dust=60,focus=(.5,.5)):
|
|
163
|
+
"""Paint a preset stage. floor is an optional y coordinate in design pixels."""
|
|
164
|
+
gradient(im,*THEMES[theme],focus=focus)
|
|
165
|
+
particles(im,t,seed=seed,count=dust,color='#D7C9A7' if theme=='warm' else '#B5D7B8')
|
|
166
|
+
if floor is not None:
|
|
167
|
+
floorline(im,'#90815D' if theme=='warm' else '#397760',.41,y=floor)
|
|
168
|
+
|
|
169
|
+
def floorline(im,c,a,*,y=512):
|
|
170
|
+
d=draw(im)
|
|
171
|
+
for index in range(-5,6):
|
|
172
|
+
opacity=a*(.9 if index==0 else .14*m.exp(-abs(index)/2))
|
|
173
|
+
line(d,[(0,y+index),(im.size[0]/S,y+index)],rgba(c,opacity),1)
|
|
174
|
+
|
|
175
|
+
@lru_cache(maxsize=100)
|
|
176
|
+
def font(size,style):
|
|
177
|
+
faces = {'regular':'LiberationSerif-Regular.ttf','bold':'LiberationSerif-Bold.ttf',
|
|
178
|
+
'sans':'LiberationSans-Regular.ttf'}
|
|
179
|
+
path = FONT_DIR / faces[style] if style in faces else FONT_REGISTRY.get(style,Path(style))
|
|
180
|
+
return ImageFont.truetype(str(path),max(1,round(size*S)))
|
|
181
|
+
|
|
182
|
+
@lru_cache(maxsize=128)
|
|
183
|
+
def text_asset(parts,size,style,tracking,glow):
|
|
184
|
+
f=font(size,style)
|
|
185
|
+
widths=[f.getlength(s)+max(0,len(s)-1)*tracking*S for s,c in parts]
|
|
186
|
+
width=round(sum(widths))
|
|
187
|
+
ascent,descent=f.getmetrics()
|
|
188
|
+
pad=22*S
|
|
189
|
+
layer=Image.new('RGBA',(max(1,width+2*pad),ascent+descent+2*pad))
|
|
190
|
+
d=draw(layer)
|
|
191
|
+
if glow:
|
|
192
|
+
g=Image.new('RGBA',layer.size)
|
|
193
|
+
gd=draw(g)
|
|
194
|
+
x=pad
|
|
195
|
+
for (value,c),advance in zip(parts,widths):
|
|
196
|
+
glyphs=[(value,x)]
|
|
197
|
+
if tracking:
|
|
198
|
+
glyphs=[]
|
|
199
|
+
cursor=x
|
|
200
|
+
for char in value:
|
|
201
|
+
glyphs.append((char,cursor))
|
|
202
|
+
cursor+=f.getlength(char)+tracking*S
|
|
203
|
+
for glyph,xx in glyphs:
|
|
204
|
+
d.text((xx,pad+ascent),glyph,font=f,fill=c,anchor='ls')
|
|
205
|
+
if glow:
|
|
206
|
+
glow_color=glow if isinstance(glow,str) else c
|
|
207
|
+
gd.text((xx,pad+ascent),glyph,font=f,fill=rgba(glow_color,.91),anchor='ls')
|
|
208
|
+
x+=advance
|
|
209
|
+
if glow:
|
|
210
|
+
blurred=g.convert('RGBa').filter(ImageFilter.GaussianBlur(5.3*S)).convert('RGBA')
|
|
211
|
+
blurred.putalpha(alpha(blurred.getchannel('A'),.86))
|
|
212
|
+
layer=Image.alpha_composite(blurred,layer)
|
|
213
|
+
return layer,width,pad,ascent
|
|
214
|
+
|
|
215
|
+
def text(im,x,y,value,size=36,*,c=WHITE,style='regular',align='center',amount=1,glow=False,tracking=0,focus=1):
|
|
216
|
+
if getattr(im,'_motionkit_gpu',False):
|
|
217
|
+
return im.text(x,y,value,size,c=c,style=style,align=align,amount=amount,
|
|
218
|
+
glow=glow,tracking=tracking,focus=focus)
|
|
219
|
+
if amount<=.003:
|
|
220
|
+
return
|
|
221
|
+
parts=((value,c),) if isinstance(value,str) else tuple(value)
|
|
222
|
+
parts=tuple((normalize('NFC',run),color) for run,color in parts)
|
|
223
|
+
layer,w,pad,ascent=text_asset(parts,size,style,tracking,glow)
|
|
224
|
+
if focus < .985:
|
|
225
|
+
blur=8*(1-focus)
|
|
226
|
+
if blur>.45:
|
|
227
|
+
# Blur all channels in premultiplied space for a gradual focus pull.
|
|
228
|
+
layer=layer.convert('RGBa').filter(ImageFilter.GaussianBlur(blur*S)).convert('RGBA')
|
|
229
|
+
xx=x*S-pad-(w/2 if align=='center' else w if align=='right' else 0)
|
|
230
|
+
yy=y*S-pad-ascent+size*.33*S
|
|
231
|
+
paste(im,layer,(round(xx),round(yy)),amount)
|
|
232
|
+
|
|
233
|
+
def say(im,t,start,x,y,value,size=36,*,duration=.32,amount=1,**kwargs):
|
|
234
|
+
progress=ramp(t,start,start+duration) if duration else float(t>=start)
|
|
235
|
+
text(im,x,y,value,size,amount=amount*progress,focus=progress,**kwargs)
|
|
236
|
+
|
|
237
|
+
def heart(im,x,y,s,c=RED,cracked=False):
|
|
238
|
+
d=draw(im)
|
|
239
|
+
points=[]
|
|
240
|
+
for i in range(76):
|
|
241
|
+
a=2*m.pi*i/76
|
|
242
|
+
xx=16*m.sin(a)**3/32
|
|
243
|
+
yy=-(13*m.cos(a)-5*m.cos(2*a)-2*m.cos(3*a)-m.cos(4*a))/32
|
|
244
|
+
points.append((x+s*xx,y+s*yy+s*.06))
|
|
245
|
+
if not cracked:
|
|
246
|
+
polygon(d,points,c)
|
|
247
|
+
return
|
|
248
|
+
def fragment(side,shift):
|
|
249
|
+
# Clip the outline to each side of the central fracture.
|
|
250
|
+
part=[p for p in points if (p[0]-x)*side >= -.1]
|
|
251
|
+
if side<0:
|
|
252
|
+
part=part[::-1]
|
|
253
|
+
seam=[(x-.03*s,y+.52*s),(x+.07*s,y+.14*s),
|
|
254
|
+
(x-.1*s,y-.015*s),(x+.04*s,y-.35*s)]
|
|
255
|
+
if part[0][1] > part[-1][1]:
|
|
256
|
+
seam=seam[::-1]
|
|
257
|
+
polygon(d,[(a+shift,b) for a,b in part+seam],c)
|
|
258
|
+
fragment(1,2)
|
|
259
|
+
fragment(-1,-2)
|
|
260
|
+
|
|
261
|
+
def person(im,x,y,s=1,kind='female',color=PINK,pose=False,has_heart=True,hair=True,light=0):
|
|
262
|
+
if light:
|
|
263
|
+
halo(im,x,y-134*s,max(1,int(123*s)),max(1,int(158*s)),color,light)
|
|
264
|
+
d=draw(im)
|
|
265
|
+
def p(points):
|
|
266
|
+
return [(x+a*s,y+b*s) for a,b in points]
|
|
267
|
+
def stroke(points,w,c=color):
|
|
268
|
+
line(d,p(points),c,w*s,True)
|
|
269
|
+
def disc(a,b,rx,ry,c):
|
|
270
|
+
oval(d,x+a*s,y+b*s,rx*s,ry*s,c)
|
|
271
|
+
if kind=='male':
|
|
272
|
+
disc(0,-275,18,18,color)
|
|
273
|
+
stroke([(0,-258),(0,-242)],12)
|
|
274
|
+
for dx in [-13,13]:
|
|
275
|
+
stroke([(dx,-143),(dx,-10)],20)
|
|
276
|
+
polygon(d,p([(-26,-249),(27,-250),(22,-141),(-20,-138)]),color)
|
|
277
|
+
stroke([(-24,-243),(-37,-202),(-62,-151)] if pose else [(-24,-243),(-35,-203),(-41,-155)],14)
|
|
278
|
+
stroke([(24,-245),(37,-202),(41,-156)],14)
|
|
279
|
+
return
|
|
280
|
+
if hair:
|
|
281
|
+
disc(0,-194,20,21,'#39232D')
|
|
282
|
+
stroke([(-17,-196),(-17,-175),(-20,-166)],3.5,'#39232D')
|
|
283
|
+
stroke([(17,-196),(17,-175),(20,-166)],3.5,'#39232D')
|
|
284
|
+
points=[(16*m.cos(m.pi*i/28),-194+16*m.sin(m.pi*i/28)) for i in range(29)]
|
|
285
|
+
polygon(d,p(points),color)
|
|
286
|
+
else:
|
|
287
|
+
disc(0,-194,17,18,color)
|
|
288
|
+
for dx in [-10,10]:
|
|
289
|
+
stroke([(dx,-94),(dx,-3.5)],7)
|
|
290
|
+
polygon(d,p([(-12,-176),(12,-176),(37,-90),(-37,-90)]),color)
|
|
291
|
+
stroke([(-12,-172),(-22,-147),(-32,-126)],7)
|
|
292
|
+
stroke([(12,-172),(26,-152),(61,-141)] if pose else [(12,-172),(22,-147),(32,-126)],7)
|
|
293
|
+
if has_heart:
|
|
294
|
+
heart(im,x,y-137*s,17*s)
|
|
295
|
+
|
|
296
|
+
@lru_cache(maxsize=1)
|
|
297
|
+
def beam():
|
|
298
|
+
w,h=572*S,470*S
|
|
299
|
+
yy,xx=np.ogrid[:h,:w]
|
|
300
|
+
y=(yy/S-7)/449
|
|
301
|
+
x=xx/S-286
|
|
302
|
+
half=7+243*np.maximum(y,0)
|
|
303
|
+
envelope=np.exp(-2.1*(x/half)**2)*np.clip((1.25-abs(x)/half)*2.7,0,1)
|
|
304
|
+
power=np.clip(y*25,0,1)*np.clip((1.035-y)*29,0,1)
|
|
305
|
+
mask=Image.fromarray((69*envelope*power*(1-.25*np.clip(y,0,1))).astype('uint8'))
|
|
306
|
+
result=Image.new('RGBA',(w,h),rgb('#CFB879'))
|
|
307
|
+
result.putalpha(mask.filter(ImageFilter.GaussianBlur(3*S)))
|
|
308
|
+
return result
|
|
309
|
+
|
|
310
|
+
def lamp(im,amount=1,*,x=476,y=64,floor=512,pole=180,spread=1):
|
|
311
|
+
"""Draw a street lamp with a beam that reaches the supplied floor height."""
|
|
312
|
+
if floor <= y or spread <= 0:
|
|
313
|
+
raise ValueError('lamp requires floor > y and spread > 0')
|
|
314
|
+
d=draw(im)
|
|
315
|
+
line(d,[(x-pole,floor),(x-pole,y-7),(x,y-7)],'#36413F',4,True)
|
|
316
|
+
rect(d,x-21,y-14,42,13,3,'#495050')
|
|
317
|
+
light=beam()
|
|
318
|
+
w=round(light.width*spread)
|
|
319
|
+
h=round(light.height*(floor-y)/448)
|
|
320
|
+
if (w,h)!=light.size:
|
|
321
|
+
light=light.resize((max(1,w),max(1,h)),Image.Resampling.BILINEAR)
|
|
322
|
+
paste(im,light,(round(x*S-light.width/2),round((y-7)*S)),amount)
|
|
323
|
+
halo(im,x,floor-8,302*spread,42,'#BF9F59',.43*amount)
|
|
324
|
+
halo(im,x,y+1,92,58,'#FFC775',.68*amount)
|
|
325
|
+
oval(d,x,y,18.5,6,mix('#39352C','#FFF4CB',amount))
|
|
326
|
+
floorline(im,'#9C8855',.34*amount,y=floor)
|
|
327
|
+
|
|
328
|
+
def cubic(p0,p1,p2,p3,n=92):
|
|
329
|
+
return [tuple((1-q)**3*a+3*(1-q)**2*q*b+3*(1-q)*q*q*c+q**3*d
|
|
330
|
+
for a,b,c,d in zip(p0,p1,p2,p3))
|
|
331
|
+
for q in np.linspace(0,1,n)]
|
|
332
|
+
|
|
333
|
+
def almond(x,y,half,height):
|
|
334
|
+
return cubic((x-half,y),(x-half*.44,y-height*1.333),(x+half*.44,y-height*1.333),(x+half,y))+cubic(
|
|
335
|
+
(x+half,y),(x+half*.44,y+height*1.333),(x-half*.44,y+height*1.333),(x-half,y))[1:]
|
|
336
|
+
|
|
337
|
+
iris_rng=random.Random(4490)
|
|
338
|
+
IRIS=[(iris_rng.uniform(-.013,.013),iris_rng.uniform(.34,.78),iris_rng.uniform(.8,1),
|
|
339
|
+
iris_rng.uniform(.25,.9),iris_rng.randrange(4)) for _ in range(365)]
|
|
340
|
+
|
|
341
|
+
@lru_cache(maxsize=16)
|
|
342
|
+
def iris_asset(radius,green,title):
|
|
343
|
+
r=radius
|
|
344
|
+
layer=Image.new('RGBA',((2*r+4)*S,)*2)
|
|
345
|
+
d=draw(layer)
|
|
346
|
+
x=y=r+2
|
|
347
|
+
dark=mix('#59331D','#17452C',green)
|
|
348
|
+
bright=mix('#D9A44B','#82E36A',green)
|
|
349
|
+
if title:
|
|
350
|
+
dark,bright='#103126','#3D815C'
|
|
351
|
+
for i in range(r,0,-1):
|
|
352
|
+
q=i/r
|
|
353
|
+
strength=.88*m.exp(-9*(q-.64)**2)*min(1,max(.13,(1-q)*14))
|
|
354
|
+
oval(d,x,y,i,i,mix(dark,bright,strength))
|
|
355
|
+
for i,(j,start,end,a,k) in enumerate(IRIS):
|
|
356
|
+
theta=i*2*m.pi/len(IRIS)+j
|
|
357
|
+
shade=mix(dark,bright,[.04,.3,.63,.92][k]*a)
|
|
358
|
+
points=[(x+r*z*m.cos(theta+.027*m.sin(z*9+i)),y+r*z*m.sin(theta+.027*m.sin(z*9+i)))
|
|
359
|
+
for z in np.linspace(start,end,6)]
|
|
360
|
+
line(d,points,shade,.44+(i%7==0)*.6)
|
|
361
|
+
oval(d,x,y,r,r,None,'#102018' if title else mix('#30251F','#10432C',green),2.6)
|
|
362
|
+
return layer
|
|
363
|
+
|
|
364
|
+
def _eye_image(green,reflection):
|
|
365
|
+
w,h=872,334
|
|
366
|
+
x,y=436,167
|
|
367
|
+
coords=almond(x,y,416,149)
|
|
368
|
+
layer=Image.new('RGBA',(w*S,h*S))
|
|
369
|
+
d=draw(layer)
|
|
370
|
+
polygon(d,coords,mix('#BDB7A6','#C5D9BF',green))
|
|
371
|
+
for i in range(1,11):
|
|
372
|
+
poly=almond(x,y,415-i*3,147-i*2.7)
|
|
373
|
+
polygon(d,poly,mix(mix('#BDB7A6','#C5D9BF',green),'#E4DFCF',i/12))
|
|
374
|
+
if green>.04:
|
|
375
|
+
for side in [-1,1]:
|
|
376
|
+
for i in range(4):
|
|
377
|
+
a=(x+side*(377-i*18),y+(i-1.5)*11)
|
|
378
|
+
b=(x+side*(199+i*4),y+(i-1.5)*54)
|
|
379
|
+
vein=cubic(a,(a[0]-side*95,a[1]+24), (b[0]+side*45,b[1]-26),b,25)
|
|
380
|
+
line(d,vein,mix('#CFD8C2','#689479',.54*green),.8)
|
|
381
|
+
ax,ay=vein[12]
|
|
382
|
+
line(d,[(ax,ay),(ax+side*21,ay+(-1)**i*14),(ax+side*50,ay+(-1)**i*20)],
|
|
383
|
+
mix('#CFD8C2','#689479',.42*green),.65)
|
|
384
|
+
iris=iris_asset(136,round(green*45)/45,False)
|
|
385
|
+
paste(layer,iris,((x-138)*S,(y-138)*S))
|
|
386
|
+
pupil_height=lerp(64,116,green)
|
|
387
|
+
pupil_half=lerp(64,25,green)
|
|
388
|
+
slit=[]
|
|
389
|
+
for i in range(100):
|
|
390
|
+
angle=i*m.tau/100
|
|
391
|
+
vert=m.sin(angle)
|
|
392
|
+
side=m.cos(angle)*(1-abs(vert)*green*.58)
|
|
393
|
+
slit.append((x+pupil_half*side,y+pupil_height*vert))
|
|
394
|
+
polygon(d,slit,'#09110D')
|
|
395
|
+
oval(d,x-lerp(29,8,green),y-lerp(30,55,green),lerp(10,5,green),lerp(10,13,green),'#F3F4DF')
|
|
396
|
+
if reflection and green<.86:
|
|
397
|
+
person(layer,x-9,y+25,.145,color=mix('#DBB9A5','#0B140E',green),has_heart=False,hair=False)
|
|
398
|
+
person(layer,x+10,y+25,.13,kind='male',color=mix('#C7C7B2','#0B140E',green))
|
|
399
|
+
line(d,coords+[coords[0]],mix('#232C26','#69DA92',green),3)
|
|
400
|
+
return layer
|
|
401
|
+
|
|
402
|
+
@lru_cache(maxsize=12)
|
|
403
|
+
def _cached_eye(green,reflection):
|
|
404
|
+
return _eye_image(green,reflection)
|
|
405
|
+
|
|
406
|
+
def eye(im,x,y,*,scale=1,opening=1,green=0,opacity=1,reflection=False):
|
|
407
|
+
"""Composite the geometric eye. opening and green range from 0 to 1."""
|
|
408
|
+
if scale <= 0 or opening <= 0 or opacity <= 0:
|
|
409
|
+
return
|
|
410
|
+
shade=round(clamp(green)*36)/36
|
|
411
|
+
layer=_cached_eye(shade,reflection)
|
|
412
|
+
size=(max(1,round(layer.width*scale)),max(1,round(layer.height*scale*clamp(opening))))
|
|
413
|
+
if size!=layer.size:
|
|
414
|
+
layer=layer.resize(size,Image.Resampling.LANCZOS)
|
|
415
|
+
paste(im,layer,(round(x*S-layer.width/2),round(y*S-layer.height/2)),opacity)
|
|
416
|
+
|
motionkit2d/dynamics.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Deterministic particles, polygon interpolation and small 2D dynamics."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from math import exp, cos, sin, sqrt, isfinite, floor
|
|
4
|
+
import random
|
|
5
|
+
|
|
6
|
+
from . import draw
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def morph_polygon(before,after,progress):
|
|
10
|
+
a,b=tuple(before),tuple(after)
|
|
11
|
+
if len(a)!=len(b) or len(a)<3: raise ValueError('Matching polygon vertices required')
|
|
12
|
+
if any(len(p)!=2 or not all(isfinite(v) for v in p) for p in (*a,*b)) or not isfinite(progress):
|
|
13
|
+
raise ValueError('Finite polygon coordinates required')
|
|
14
|
+
p=max(0,min(1,progress))
|
|
15
|
+
return tuple(tuple(x+(y-x)*p for x,y in zip(v,w)) for v,w in zip(a,b))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Ballistic:
|
|
20
|
+
position: tuple = (0,0)
|
|
21
|
+
velocity: tuple = (0,0)
|
|
22
|
+
gravity: tuple = (0,980)
|
|
23
|
+
|
|
24
|
+
def __post_init__(self):
|
|
25
|
+
if any(len(p)!=2 or not all(isfinite(v) for v in p) for p in (self.position,self.velocity,self.gravity)):
|
|
26
|
+
raise ValueError('Finite 2D vectors required')
|
|
27
|
+
|
|
28
|
+
def __call__(self,t):
|
|
29
|
+
if not isfinite(t) or t<0: raise ValueError('Time must be finite and nonnegative')
|
|
30
|
+
return tuple(p+v*t+.5*g*t*t for p,v,g in zip(self.position,self.velocity,self.gravity))
|
|
31
|
+
|
|
32
|
+
def bounce(self,t,*,floor_y,restitution=.6,radius=0,step=1/240):
|
|
33
|
+
"""Fixed-step replay with ground contact. Never advances mutable state."""
|
|
34
|
+
if not all(isfinite(v) for v in (t,restitution,radius,step,floor_y)) or t<0 or not 0<=restitution<=1 or radius<0 or step<=0:
|
|
35
|
+
raise ValueError('Invalid collision parameters')
|
|
36
|
+
x,y=self.position; vx,vy=self.velocity
|
|
37
|
+
for i in range(int(t/step)+1):
|
|
38
|
+
dt=min(step,max(0,t-i*step))
|
|
39
|
+
x+=vx*dt+.5*self.gravity[0]*dt*dt
|
|
40
|
+
y+=vy*dt+.5*self.gravity[1]*dt*dt
|
|
41
|
+
vx+=self.gravity[0]*dt; vy+=self.gravity[1]*dt
|
|
42
|
+
if y>floor_y-radius:
|
|
43
|
+
y=floor_y-radius
|
|
44
|
+
if vy>0: vy=-vy*restitution
|
|
45
|
+
return x,y
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def spring(t,*,initial=0,target=1,velocity=0,frequency=3,damping=.5):
|
|
49
|
+
"""Analytical underdamped/critical/overdamped spring with initial velocity."""
|
|
50
|
+
if not all(isfinite(v) for v in (t,initial,target,velocity,frequency,damping)) or t<0 or frequency<=0 or damping<0:
|
|
51
|
+
raise ValueError('Invalid spring parameters')
|
|
52
|
+
w=frequency*6.283185307179586; x=initial-target
|
|
53
|
+
if damping<1:
|
|
54
|
+
wd=w*sqrt(1-damping*damping)
|
|
55
|
+
return target+exp(-damping*w*t)*(x*cos(wd*t)+(velocity+damping*w*x)/wd*sin(wd*t))
|
|
56
|
+
if damping==1: return target+exp(-w*t)*(x+(velocity+w*x)*t)
|
|
57
|
+
r1=-w*(damping-sqrt(damping*damping-1)); r2=-w*(damping+sqrt(damping*damping-1))
|
|
58
|
+
a=(velocity-r2*x)/(r1-r2)
|
|
59
|
+
return target+a*exp(r1*t)+(x-a)*exp(r2*t)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class Emitter:
|
|
64
|
+
position: object = (0,0)
|
|
65
|
+
rate: float = 10
|
|
66
|
+
lifetime: float = 1
|
|
67
|
+
velocity: tuple = (0,-40)
|
|
68
|
+
spread: float = 30
|
|
69
|
+
gravity: tuple = (0,20)
|
|
70
|
+
radius: float = 3
|
|
71
|
+
color: str = '#F294AF'
|
|
72
|
+
seed: int = 0
|
|
73
|
+
start: float = 0
|
|
74
|
+
stop: float | None = None
|
|
75
|
+
burst: int = 0
|
|
76
|
+
shape: str = 'disc'
|
|
77
|
+
|
|
78
|
+
def __post_init__(self):
|
|
79
|
+
if not all(isfinite(v) for v in (self.rate,self.lifetime,self.spread,self.radius,self.start)) or self.rate<=0 or self.lifetime<=0 or self.spread<0 or self.radius<=0:
|
|
80
|
+
raise ValueError('Invalid emitter parameters')
|
|
81
|
+
if self.stop is not None and (not isfinite(self.stop) or self.stop<self.start): raise ValueError('Invalid emitter stop')
|
|
82
|
+
if type(self.burst) is not int or self.burst<0 or self.shape not in {'disc','heart'}: raise ValueError('Invalid burst or shape')
|
|
83
|
+
Ballistic((0,0),self.velocity,self.gravity)
|
|
84
|
+
|
|
85
|
+
def particles(self,t):
|
|
86
|
+
if not isfinite(t): raise ValueError('Finite time required')
|
|
87
|
+
end=min(t,self.stop) if self.stop is not None else t
|
|
88
|
+
last=floor((end-self.start)*self.rate)
|
|
89
|
+
first=max(0,floor((t-self.start-self.lifetime)*self.rate))
|
|
90
|
+
births=[(i,self.start+i/self.rate) for i in range(first,last+1)]
|
|
91
|
+
births.extend((-i-1,self.start) for i in range(self.burst))
|
|
92
|
+
result=[]
|
|
93
|
+
for id,born in births:
|
|
94
|
+
age=t-born
|
|
95
|
+
if not 0<=age<self.lifetime: continue
|
|
96
|
+
rng=random.Random(f'{self.seed}:{id}')
|
|
97
|
+
origin=self.position(born) if callable(self.position) else self.position
|
|
98
|
+
velocity=tuple(v+rng.uniform(-self.spread,self.spread) for v in self.velocity)
|
|
99
|
+
result.append((Ballistic(origin,velocity,self.gravity)(age),1-age/self.lifetime))
|
|
100
|
+
return tuple(result)
|
|
101
|
+
|
|
102
|
+
def draw(self,image,t):
|
|
103
|
+
d=draw.draw(image)
|
|
104
|
+
for (x,y),opacity in self.particles(t):
|
|
105
|
+
if self.shape=='heart':
|
|
106
|
+
points=[(x+self.radius*16*sin(i/20*6.283)**3/17,
|
|
107
|
+
y-self.radius*(13*cos(i/20*6.283)-5*cos(2*i/20*6.283)-2*cos(3*i/20*6.283)-cos(4*i/20*6.283))/17) for i in range(20)]
|
|
108
|
+
draw.polygon(d,points,draw.rgba(self.color,opacity))
|
|
109
|
+
else: draw.oval(d,x,y,self.radius,self.radius,draw.rgba(self.color,opacity))
|
motionkit2d/effects.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Sample motion and composite art at an arbitrary timestamp."""
|
|
2
|
+
from bisect import bisect_right
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from math import cos, pi, sin, exp, isfinite
|
|
5
|
+
|
|
6
|
+
from PIL import Image
|
|
7
|
+
|
|
8
|
+
from .draw import S, box, clamp, draw, mix, paste, rgba
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def curve(progress, easing='smooth'):
|
|
12
|
+
"""Return eased progress for linear, smooth, in, out, or in_out."""
|
|
13
|
+
p=clamp(progress)
|
|
14
|
+
match easing:
|
|
15
|
+
case 'linear':
|
|
16
|
+
return p
|
|
17
|
+
case 'smooth':
|
|
18
|
+
return p*p*(3-2*p)
|
|
19
|
+
case 'in':
|
|
20
|
+
return p*p
|
|
21
|
+
case 'out':
|
|
22
|
+
return 1-(1-p)**2
|
|
23
|
+
case 'in_out':
|
|
24
|
+
return (1-cos(pi*p))/2
|
|
25
|
+
case 'back':
|
|
26
|
+
return 1+2.70158*(p-1)**3+1.70158*(p-1)**2
|
|
27
|
+
case 'bounce':
|
|
28
|
+
if p<1/2.75: return 7.5625*p*p
|
|
29
|
+
if p<2/2.75: return 7.5625*(p-1.5/2.75)**2+.75
|
|
30
|
+
if p<2.5/2.75: return 7.5625*(p-2.25/2.75)**2+.9375
|
|
31
|
+
return 7.5625*(p-2.625/2.75)**2+.984375
|
|
32
|
+
case 'elastic':
|
|
33
|
+
return p if p in (0,1) else 2**(-10*p)*sin((p*10-.75)*2*pi/3)+1
|
|
34
|
+
case 'spring':
|
|
35
|
+
return p if p in (0,1) else (1-exp(-7*p)*cos(12*p))/(1-exp(-7)*cos(12))
|
|
36
|
+
case _:
|
|
37
|
+
raise ValueError(f'Unknown easing {easing!r}')
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _interpolate(start,end,p):
|
|
41
|
+
if isinstance(start,str) and isinstance(end,str):
|
|
42
|
+
return mix(start,end,clamp(p))
|
|
43
|
+
if isinstance(start,tuple) and isinstance(end,tuple):
|
|
44
|
+
return tuple(_interpolate(a,b,p) for a,b in zip(start,end,strict=True))
|
|
45
|
+
return start+(end-start)*p
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def tween(t,start,end,before=0,after=1,*,ease='smooth'):
|
|
49
|
+
"""Interpolate numbers, tuples, or RGB color strings over seconds."""
|
|
50
|
+
if end<start:
|
|
51
|
+
raise ValueError('end must be at or after start')
|
|
52
|
+
if t<start:
|
|
53
|
+
return before
|
|
54
|
+
if t>=end:
|
|
55
|
+
return after
|
|
56
|
+
return _interpolate(before,after,curve((t-start)/(end-start),ease))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class Key:
|
|
61
|
+
time: float
|
|
62
|
+
value: object
|
|
63
|
+
ease: str = 'smooth'
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Track:
|
|
67
|
+
"""Keyframes sampled in seconds. An outgoing segment uses its first key's ease."""
|
|
68
|
+
|
|
69
|
+
def __init__(self,*keys):
|
|
70
|
+
self.keys=tuple(keys)
|
|
71
|
+
self.times=tuple(key.time for key in self.keys)
|
|
72
|
+
if not keys or any(not isfinite(t) for t in self.times) or any(a>=b for a,b in zip(self.times,self.times[1:])):
|
|
73
|
+
raise ValueError('Track requires one or more keys in strictly increasing order')
|
|
74
|
+
for key in self.keys:
|
|
75
|
+
curve(0,key.ease)
|
|
76
|
+
|
|
77
|
+
def __call__(self,t):
|
|
78
|
+
offset=bisect_right(self.times,t)
|
|
79
|
+
if offset==0:
|
|
80
|
+
return self.keys[0].value
|
|
81
|
+
if offset==len(self.keys):
|
|
82
|
+
return self.keys[-1].value
|
|
83
|
+
start,end=self.keys[offset-1:offset+1]
|
|
84
|
+
return tween(t,start.time,end.time,start.value,end.value,ease=start.ease)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def layer(width,height):
|
|
88
|
+
"""Make a transparent, 2× supersampled group for vector drawing."""
|
|
89
|
+
return Image.new('RGBA',(round(width*S),round(height*S)))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def sprite(canvas,image,x,y,*,scale=1,rotation=0,opacity=1,anchor=(.5,.5)):
|
|
93
|
+
"""Composite a PIL image using design-pixel coordinates and a fractional pivot."""
|
|
94
|
+
if getattr(canvas,'_motionkit_gpu',False):
|
|
95
|
+
return canvas.sprite(image,x,y,scale=scale,rotation=rotation,opacity=opacity,anchor=anchor)
|
|
96
|
+
if scale<=0 or opacity<=0:
|
|
97
|
+
return
|
|
98
|
+
source=image.convert('RGBA') if image.mode!='RGBA' else image
|
|
99
|
+
if scale!=1:
|
|
100
|
+
source=source.resize(tuple(max(1,round(v*scale)) for v in source.size),Image.Resampling.LANCZOS)
|
|
101
|
+
ax,ay=(dimension*fraction for dimension,fraction in zip(source.size,anchor,strict=True))
|
|
102
|
+
if rotation:
|
|
103
|
+
# Rotation preserves the anchor by moving it relative to the rotated center.
|
|
104
|
+
from math import radians
|
|
105
|
+
angle=radians(rotation)
|
|
106
|
+
dx,dy=ax-source.width/2,ay-source.height/2
|
|
107
|
+
source=source.rotate(rotation,expand=True,resample=Image.Resampling.BICUBIC)
|
|
108
|
+
ax=source.width/2+dx*cos(angle)+dy*sin(angle)
|
|
109
|
+
ay=source.height/2-dx*sin(angle)+dy*cos(angle)
|
|
110
|
+
paste(canvas,source,(round(x*S-ax),round(y*S-ay)),opacity)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def ripple(im,x,y,t,*,start=0,duration=1,radii=(12,125),color='#65E595',width=1.5,
|
|
114
|
+
count=3,gap=.14,opacity=.6):
|
|
115
|
+
"""Draw concentric rings with staggered starts and a sinusoidal fade."""
|
|
116
|
+
if duration<=0:
|
|
117
|
+
raise ValueError('ripple duration must be positive')
|
|
118
|
+
d=draw(im)
|
|
119
|
+
for index in range(count):
|
|
120
|
+
p=(t-start-index*gap)/duration
|
|
121
|
+
if 0<p<1:
|
|
122
|
+
r=tween(p,0,1,*radii,ease='out')
|
|
123
|
+
d.ellipse(box(x,y,r,r),outline=rgba(color,opacity*sin(pi*p)),
|
|
124
|
+
width=max(1,round(width*S)))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def wash(im,color,opacity):
|
|
128
|
+
"""Blend the entire canvas toward a solid color in place."""
|
|
129
|
+
if getattr(im,'_motionkit_gpu',False):
|
|
130
|
+
return im.wash(color,opacity)
|
|
131
|
+
im.paste(Image.blend(im,Image.new(im.mode,im.size,color),clamp(opacity)))
|