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/compiler.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Strict, data-only JSON episode compiler. No imports, eval or code execution."""
|
|
2
|
+
import json
|
|
3
|
+
from dataclasses import fields
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .audio import AudioCue
|
|
7
|
+
from .camera import Camera2D
|
|
8
|
+
from .catalog import catalog
|
|
9
|
+
from .characters import Face, Action
|
|
10
|
+
from .effects import Key, Track
|
|
11
|
+
from .environments import Environment
|
|
12
|
+
from .layout import Rect
|
|
13
|
+
from .rig import Appearance, Character, Prop, Transform, Attachment
|
|
14
|
+
from .scene_graph import Node, SceneGraph
|
|
15
|
+
from .timeline import Scene, Transition, Video
|
|
16
|
+
from .typography import AnimatedText
|
|
17
|
+
from .visual_effects import effects_registry
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ManifestError(ValueError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _object(value,allowed,context):
|
|
25
|
+
if not isinstance(value,dict): raise ManifestError(f'{context}: expected object')
|
|
26
|
+
unknown=value.keys()-set(allowed)
|
|
27
|
+
if unknown: raise ManifestError(f'{context}: unknown fields {sorted(unknown)}')
|
|
28
|
+
return value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _track(value):
|
|
32
|
+
if not isinstance(value,dict): return value
|
|
33
|
+
_object(value,{'keys'},'track')
|
|
34
|
+
if not isinstance(value.get('keys'),list) or not value['keys']: raise ManifestError('track.keys: expected nonempty array')
|
|
35
|
+
keys=[]
|
|
36
|
+
for key in value['keys']:
|
|
37
|
+
_object(key,{'time','value','ease'},'key')
|
|
38
|
+
v=key['value']; v=tuple(v) if isinstance(v,list) else v
|
|
39
|
+
keys.append(Key(key['time'],v,key.get('ease','smooth')))
|
|
40
|
+
return Track(*keys)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _animated(cls,spec):
|
|
44
|
+
_object(spec,{f.name for f in fields(cls)},cls.__name__)
|
|
45
|
+
values={name:_track(value) for name,value in spec.items()}
|
|
46
|
+
def at(t):
|
|
47
|
+
return cls(**{name:value(t) if callable(value) else value for name,value in values.items()})
|
|
48
|
+
at(0)
|
|
49
|
+
return at if any(callable(v) for v in values.values()) else at(0)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _preset(spec,presets):
|
|
53
|
+
spec=dict(spec)
|
|
54
|
+
name=spec.pop('preset_ref',None)
|
|
55
|
+
if name is None: return spec
|
|
56
|
+
if name not in presets: raise ManifestError(f'Unknown preset: {name}')
|
|
57
|
+
base=presets[name]
|
|
58
|
+
if not isinstance(base,dict) or 'preset_ref' in base: raise ManifestError('Presets must be plain objects without recursive references')
|
|
59
|
+
return {**base,**spec}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def compile_episode(manifest,*,base_dir='.',registry=catalog):
|
|
63
|
+
"""Compile schema_version=1. Paths are resolved relative to the manifest."""
|
|
64
|
+
try:
|
|
65
|
+
return _compile(manifest,Path(base_dir).resolve(),registry)
|
|
66
|
+
except ManifestError: raise
|
|
67
|
+
except (ValueError,TypeError,KeyError,OSError) as error:
|
|
68
|
+
raise ManifestError(f'Invalid manifest: {error}') from error
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _compile(manifest,base,registry):
|
|
72
|
+
_object(manifest,{'schema_version','video','scenes','audio','presets'},'manifest')
|
|
73
|
+
if type(manifest.get('schema_version')) is not int or manifest['schema_version']!=1:
|
|
74
|
+
raise ManifestError('schema_version must be 1')
|
|
75
|
+
settings=_object(manifest.get('video',{}),{'width','height','fps','background'},'video')
|
|
76
|
+
presets=manifest.get('presets',{})
|
|
77
|
+
if not isinstance(presets,dict): raise ManifestError('presets: expected object')
|
|
78
|
+
scene_specs=manifest.get('scenes')
|
|
79
|
+
if not isinstance(scene_specs,list) or not scene_specs: raise ManifestError('scenes: expected nonempty array')
|
|
80
|
+
scenes=[]
|
|
81
|
+
for index,scene_spec in enumerate(scene_specs):
|
|
82
|
+
context=f'scenes[{index}]'
|
|
83
|
+
spec=_object(scene_spec,{'name','seconds','transition','still','nodes','camera','environment'},context)
|
|
84
|
+
nodes=[]; attachments=[]
|
|
85
|
+
if 'environment' in spec:
|
|
86
|
+
config=dict(spec['environment'])
|
|
87
|
+
config.setdefault('width',settings.get('width',1024)); config.setdefault('height',settings.get('height',576))
|
|
88
|
+
env=Environment(**config); nodes.extend(env.nodes())
|
|
89
|
+
node_specs=spec.get('nodes',[])
|
|
90
|
+
if not isinstance(node_specs,list): raise ManifestError(f'{context}.nodes: expected array')
|
|
91
|
+
for k,node_spec in enumerate(node_specs):
|
|
92
|
+
config=_preset(node_spec,presets)
|
|
93
|
+
_object(config,{'id','type','transform','visible','opacity','z_index','parent','bounds','clip','screen_space','effects',
|
|
94
|
+
'appearance','face','perform','asset','parameters','text','attach'},f'{context}.nodes[{k}]')
|
|
95
|
+
kind=config.get('type','group'); content=None
|
|
96
|
+
bounds=Rect(*config['bounds']) if 'bounds' in config else None
|
|
97
|
+
if kind=='character':
|
|
98
|
+
appearance=Appearance(**config.get('appearance',{}))
|
|
99
|
+
content=Character(appearance,face=_animated(Face,config.get('face',{})))
|
|
100
|
+
if 'perform' in config:
|
|
101
|
+
perform=_object(config['perform'],{'body','arms','head','gaze'},'perform')
|
|
102
|
+
channels={name:Action(**value) if isinstance(value,dict) else value for name,value in perform.items() if name!='gaze'}
|
|
103
|
+
content.perform(**channels,face=content.face,**({'gaze':tuple(perform['gaze'])} if 'gaze' in perform else {}))
|
|
104
|
+
elif kind=='prop':
|
|
105
|
+
asset=registry.get(config['asset']); content=Prop(asset,**config.get('parameters',{}))
|
|
106
|
+
elif kind=='text':
|
|
107
|
+
content=AnimatedText(**config['text']); bounds=bounds or content.bounds
|
|
108
|
+
elif kind!='group': raise ManifestError(f'Unknown node type: {kind}')
|
|
109
|
+
if 'attach' in config:
|
|
110
|
+
if kind!='prop' or config.get('parent') or config.get('screen_space'):
|
|
111
|
+
raise ManifestError('Attachments require a root world-space prop')
|
|
112
|
+
attachments.append((config['id'],config['attach']))
|
|
113
|
+
effect_specs=config.get('effects',[])
|
|
114
|
+
effects=[]
|
|
115
|
+
for effect in effect_specs:
|
|
116
|
+
_object(effect,{'name','parameters'},'effect')
|
|
117
|
+
effects.append(effects_registry.create(effect['name'],**effect.get('parameters',{})))
|
|
118
|
+
nodes.append(Node(config['id'],content,_animated(Transform,config.get('transform',{})),
|
|
119
|
+
_track(config.get('visible',True)),_track(config.get('opacity',1)),config.get('z_index',0),
|
|
120
|
+
config.get('parent'),bounds,Rect(*config['clip']) if 'clip' in config else None,
|
|
121
|
+
config.get('screen_space',False),tuple(effects),'text' if kind=='text' else kind))
|
|
122
|
+
graph=SceneGraph(nodes,camera=_animated(Camera2D,spec['camera']) if 'camera' in spec else None)
|
|
123
|
+
attachment_ids={id for id,_ in attachments}
|
|
124
|
+
for id,config in attachments:
|
|
125
|
+
_object(config,{'target','anchor','child_anchor','start','release'},'attach')
|
|
126
|
+
target=config['target']
|
|
127
|
+
if target in attachment_ids: raise ManifestError('Attachment targets must be independent nodes')
|
|
128
|
+
node=graph.nodes[id]; target_node=graph.nodes[target]
|
|
129
|
+
# Screen-space and world-space constraints cannot mix.
|
|
130
|
+
root=target_node
|
|
131
|
+
while root.parent: root=graph.nodes[root.parent]
|
|
132
|
+
if root.screen_space or not hasattr(target_node.content,'world_transform'):
|
|
133
|
+
raise ManifestError('Attachment target must be a world-space drawable')
|
|
134
|
+
node.content.transform=node.transform
|
|
135
|
+
node.transform=Transform()
|
|
136
|
+
bound=graph.bind(target)
|
|
137
|
+
bound.local_anchor(config['anchor'],0)
|
|
138
|
+
node.content.local_anchor(config['child_anchor'],0)
|
|
139
|
+
node.content=Attachment(node.content,config['child_anchor'],bound,config['anchor'],
|
|
140
|
+
start=config.get('start',0),release=config.get('release'))
|
|
141
|
+
transition=Transition(**spec['transition']) if spec.get('transition') else None
|
|
142
|
+
scenes.append(Scene(spec.get('name',f'Scene {index+1}'),spec['seconds'],graph,transition,spec.get('still')))
|
|
143
|
+
audio=[]
|
|
144
|
+
for cue in manifest.get('audio',[]):
|
|
145
|
+
cue=_object(cue,{f.name for f in fields(AudioCue)},'audio cue')
|
|
146
|
+
config=dict(cue); path=Path(config['path']); config['path']=path if path.is_absolute() else base/path
|
|
147
|
+
audio.append(AudioCue(**config))
|
|
148
|
+
return Video(scenes,audio=audio,**settings)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def load_manifest(path,*,registry=catalog):
|
|
152
|
+
path=Path(path).resolve()
|
|
153
|
+
def pairs(items):
|
|
154
|
+
result={}
|
|
155
|
+
for key,value in items:
|
|
156
|
+
if key in result: raise ManifestError(f'Duplicate JSON key: {key}')
|
|
157
|
+
result[key]=value
|
|
158
|
+
return result
|
|
159
|
+
from .manifest import resolve_manifest
|
|
160
|
+
try: data=resolve_manifest(path)
|
|
161
|
+
except (TypeError,ValueError,KeyError,OSError) as error: raise ManifestError(f'{path}: {error}') from error
|
|
162
|
+
return compile_episode(data,base_dir=path.parent,registry=registry)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Responsive safe insets, fit/arrange helpers and bounding-box diagnostics."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from math import isfinite
|
|
4
|
+
|
|
5
|
+
from .layout import Rect
|
|
6
|
+
from .rig import Transform
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class SafeZone:
|
|
11
|
+
left: float = .06
|
|
12
|
+
top: float = .06
|
|
13
|
+
right: float = .06
|
|
14
|
+
bottom: float = .06
|
|
15
|
+
|
|
16
|
+
def rect(self,width,height):
|
|
17
|
+
if not all(isfinite(v) and v>=0 for v in (self.left,self.top,self.right,self.bottom)) or self.left+self.right>=1 or self.top+self.bottom>=1:
|
|
18
|
+
raise ValueError('Invalid fractional safe insets')
|
|
19
|
+
if width<=0 or height<=0: raise ValueError('Positive canvas required')
|
|
20
|
+
return Rect(width*self.left,height*self.top,width*(1-self.left-self.right),height*(1-self.top-self.bottom))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def overlaps(a,b):
|
|
24
|
+
return a.x<b.x+b.width and b.x<a.x+a.width and a.y<b.y+b.height and b.y<a.y+a.height
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def fit(bounds,target,*,padding=0):
|
|
28
|
+
if min(bounds.width,bounds.height,target.width-2*padding,target.height-2*padding)<=0 or padding<0:
|
|
29
|
+
raise ValueError('Invalid fit bounds')
|
|
30
|
+
scale=min((target.width-2*padding)/bounds.width,(target.height-2*padding)/bounds.height)
|
|
31
|
+
return Transform(target.x+target.width/2-(bounds.x+bounds.width/2)*scale,
|
|
32
|
+
target.y+target.height/2-(bounds.y+bounds.height/2)*scale,scale)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def arrange(count,region,*,columns=None,gap=12):
|
|
36
|
+
if type(count) is not int or count<1 or gap<0: raise ValueError('Invalid arrangement')
|
|
37
|
+
columns=columns or count
|
|
38
|
+
if type(columns) is not int or columns<1: raise ValueError('Invalid columns')
|
|
39
|
+
rows=(count+columns-1)//columns
|
|
40
|
+
width=(region.width-(columns-1)*gap)/columns
|
|
41
|
+
height=(region.height-(rows-1)*gap)/rows
|
|
42
|
+
if min(width,height)<=0: raise ValueError('Gap exceeds available region')
|
|
43
|
+
return tuple(Rect(region.x+(i%columns)*(width+gap),region.y+(i//columns)*(height+gap),width,height) for i in range(count))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def composition(name,width,height,*,safe=SafeZone()):
|
|
47
|
+
area=safe.rect(width,height)
|
|
48
|
+
if name=='close_up': return (area,)
|
|
49
|
+
if name in {'two_shot','split'}: return arrange(2,area,gap=width*.04 if name=='two_shot' else 0)
|
|
50
|
+
raise ValueError(f'Unknown composition: {name}')
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Stateless spatial constraints and deterministic grid navigation."""
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
from heapq import heappop, heappush
|
|
4
|
+
from math import hypot, isfinite, ceil
|
|
5
|
+
|
|
6
|
+
from .layout import Rect
|
|
7
|
+
from .rig import Transform
|
|
8
|
+
from .composition import overlaps
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def align(bounds,target,*,anchor=(.5,.5),target_anchor=(.5,.5),offset=(0,0)):
|
|
12
|
+
a=bounds.anchor(*anchor); b=target.anchor(*target_anchor)
|
|
13
|
+
return Transform(b[0]-a[0]+offset[0],b[1]-a[1]+offset[1])
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def contain(bounds,region):
|
|
17
|
+
if bounds.width>region.width or bounds.height>region.height:
|
|
18
|
+
raise ValueError('Object cannot fit region')
|
|
19
|
+
x=min(max(bounds.x,region.x),region.x+region.width-bounds.width)
|
|
20
|
+
y=min(max(bounds.y,region.y),region.y+region.height-bounds.height)
|
|
21
|
+
return Transform(x-bounds.x,y-bounds.y)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def collisions(graph,t):
|
|
25
|
+
ids=list(graph.nodes); result=[]
|
|
26
|
+
for i,a in enumerate(ids):
|
|
27
|
+
ba=graph.world_bounds(a,t)
|
|
28
|
+
for b in ids[i+1:]:
|
|
29
|
+
bb=graph.world_bounds(b,t)
|
|
30
|
+
if ba and bb and overlaps(ba,bb): result.append((a,b))
|
|
31
|
+
return result
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class MotionPath:
|
|
35
|
+
"""Constant-speed polyline. Clamp at endpoints; no history dependency."""
|
|
36
|
+
def __init__(self,points,*,speed=100,start=0):
|
|
37
|
+
self.points=tuple(tuple(p) for p in points)
|
|
38
|
+
if not self.points or not all(len(p)==2 and all(isfinite(v) for v in p) for p in self.points):
|
|
39
|
+
raise ValueError('Finite 2D path required')
|
|
40
|
+
if not isfinite(speed) or speed<=0 or not isfinite(start): raise ValueError('Invalid path timing')
|
|
41
|
+
self.speed,self.start=speed,start
|
|
42
|
+
self.lengths=tuple(hypot(b[0]-a[0],b[1]-a[1]) for a,b in zip(self.points,self.points[1:]))
|
|
43
|
+
self.duration=sum(self.lengths)/speed
|
|
44
|
+
|
|
45
|
+
def __call__(self,t):
|
|
46
|
+
if not isfinite(t): raise ValueError('Finite path time required')
|
|
47
|
+
distance=max(0,(t-self.start)*self.speed)
|
|
48
|
+
for a,b,length in zip(self.points,self.points[1:],self.lengths):
|
|
49
|
+
if distance<length:
|
|
50
|
+
p=distance/length
|
|
51
|
+
return tuple(x+(y-x)*p for x,y in zip(a,b))
|
|
52
|
+
distance-=length
|
|
53
|
+
return self.points[-1]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def find_path(start,end,region,obstacles=(),*,cell=10,clearance=0):
|
|
57
|
+
"""Four-neighbor A*. Obstacles include clearance; endpoints must lie on grid.
|
|
58
|
+
|
|
59
|
+
Grid anchored at region origin; returned segments are axis aligned, preventing
|
|
60
|
+
diagonal corner cutting. Bounds of obstacles are treated as closed.
|
|
61
|
+
"""
|
|
62
|
+
if not isfinite(cell) or cell<=0 or clearance<0: raise ValueError('Invalid navigation parameters')
|
|
63
|
+
def index(p):
|
|
64
|
+
q=tuple(round((v-o)/cell) for v,o in zip(p,(region.x,region.y)))
|
|
65
|
+
if hypot(*(a-b for a,b in zip(point(q),p)))>1e-7: raise ValueError('Endpoints must be grid aligned')
|
|
66
|
+
return q
|
|
67
|
+
def point(q): return region.x+q[0]*cell,region.y+q[1]*cell
|
|
68
|
+
expanded=[Rect(b.x-clearance,b.y-clearance,b.width+2*clearance,b.height+2*clearance) for b in obstacles]
|
|
69
|
+
def valid(q):
|
|
70
|
+
p=point(q)
|
|
71
|
+
return region.contains(p) and not any(b.contains(p) for b in expanded)
|
|
72
|
+
a,b=index(start),index(end)
|
|
73
|
+
if not valid(a) or not valid(b): raise ValueError('Endpoint outside walkable space')
|
|
74
|
+
queue=[(0,a)]; costs={a:0}; parents={}
|
|
75
|
+
while queue:
|
|
76
|
+
_,q=heappop(queue)
|
|
77
|
+
if q==b:
|
|
78
|
+
path=[q]
|
|
79
|
+
while q!=a: q=parents[q]; path.append(q)
|
|
80
|
+
return tuple(point(v) for v in reversed(path))
|
|
81
|
+
for n in ((q[0]+1,q[1]),(q[0]-1,q[1]),(q[0],q[1]+1),(q[0],q[1]-1)):
|
|
82
|
+
if not valid(n): continue
|
|
83
|
+
# Check the whole segment, including obstacles thinner than a cell.
|
|
84
|
+
p0,p1=point(q),point(n)
|
|
85
|
+
segment=Rect(min(p0[0],p1[0])-1e-9,min(p0[1],p1[1])-1e-9,abs(p1[0]-p0[0])+2e-9,abs(p1[1]-p0[1])+2e-9)
|
|
86
|
+
if any(overlaps(segment,o) for o in expanded): continue
|
|
87
|
+
cost=costs[q]+1
|
|
88
|
+
if cost<costs.get(n,float('inf')):
|
|
89
|
+
costs[n]=cost; parents[n]=q
|
|
90
|
+
heappush(queue,(cost+abs(n[0]-b[0])+abs(n[1]-b[1]),n))
|
|
91
|
+
raise ValueError('No walkable path')
|
motionkit2d/cues.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Named seconds shared by choreography, attachment and audio."""
|
|
2
|
+
from math import isfinite
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Cues:
|
|
6
|
+
def __init__(self, **times):
|
|
7
|
+
if any(not isfinite(v) or v<0 for v in times.values()):
|
|
8
|
+
raise ValueError('Cue times must be finite, nonnegative seconds')
|
|
9
|
+
self._times=dict(times)
|
|
10
|
+
|
|
11
|
+
def __getitem__(self,name):
|
|
12
|
+
return self._times[name]
|
|
13
|
+
|
|
14
|
+
def at(self,name,offset=0):
|
|
15
|
+
return self[name]+offset
|