@taptap/maker 0.0.41-beta.1 → 0.0.41-beta.2

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.
@@ -0,0 +1,407 @@
1
+ """Bake a reviewed scene recipe into portable assets and optional canvas previews."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ import math
6
+ import re
7
+ import shutil
8
+ import zipfile
9
+ from pathlib import Path
10
+ from PIL import Image, ImageChops, ImageDraw, ImageEnhance
11
+
12
+
13
+ def write_json(path, value):
14
+ path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
15
+
16
+
17
+ def number(value, minimum, maximum, name):
18
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not minimum <= value <= maximum:
19
+ raise ValueError('Invalid ' + name)
20
+ return value
21
+
22
+
23
+ def source_path(root, name):
24
+ root = root.resolve()
25
+ if not isinstance(name, str) or not name or Path(name).is_absolute():
26
+ raise ValueError('Sources must be relative to --source-root')
27
+ path = (root / name).resolve()
28
+ if not path.is_relative_to(root) or not path.is_file():
29
+ raise ValueError('Missing source or path outside source root: ' + name)
30
+ return path
31
+
32
+
33
+ def box(value, name, bounds=None, integer=False):
34
+ if not isinstance(value, list) or len(value) != 4:
35
+ raise ValueError('Expected xywh: ' + name)
36
+ x, y, w, h = [number(n, -100000, 100000, name) for n in value]
37
+ if w <= 0 or h <= 0 or (integer and any(int(n) != n for n in value)):
38
+ raise ValueError('Invalid dimensions: ' + name)
39
+ if bounds and (x < 0 or y < 0 or x+w > bounds[0] or y+h > bounds[1]):
40
+ raise ValueError('Box outside image: ' + name)
41
+ return value
42
+
43
+
44
+ def pose(progress, motion):
45
+ if progress >= 1:
46
+ return 1., 1., 0.
47
+ growth = 1 - math.exp(-7*progress)*math.cos(13*progress)
48
+ if motion == 'unfurl':
49
+ return 1., max(.03, growth), 0.
50
+ if motion == 'hang':
51
+ return 1., 1., -.25*(1-progress)**2 + .05*math.sin(12*progress)*(1-progress)
52
+ return (max(.04, growth+.15*math.exp(-5*progress)*math.sin(17*progress)),
53
+ max(.03, growth), -.18*math.sin(math.pi*progress)*math.exp(-2*progress))
54
+
55
+
56
+ def load_recipe(root, filename):
57
+ recipe = json.loads(filename.read_text(encoding='utf-8'))
58
+ if recipe.get('version') != 1:
59
+ raise ValueError('Expected recipe version 1')
60
+ size = recipe['size']
61
+ if len(size) != 2 or any(type(n) is not int or not 0 < n <= 8192 for n in size):
62
+ raise ValueError('Invalid scene size')
63
+ for field in ('background', 'reference'):
64
+ with Image.open(source_path(root, recipe[field])) as image:
65
+ if list(image.size) != size:
66
+ raise ValueError(field + ' dimensions differ from scene size')
67
+ objects = recipe['objects']
68
+ if not isinstance(objects, list) or not 1 <= len(objects) <= 200:
69
+ raise ValueError('Expected 1..200 instances')
70
+ specs = {}
71
+ for item in objects:
72
+ ident = item['id']
73
+ if not isinstance(ident, str) or not re.fullmatch(r'[a-zA-Z0-9_-]{1,80}', ident) or ident.casefold() in specs:
74
+ raise ValueError('Unsafe or duplicate instance ID')
75
+ specs[ident.casefold()] = item
76
+ box(item['bbox'], ident, size, integer=True)
77
+ item.setdefault('speed', 1)
78
+ item.setdefault('parent', None)
79
+ item.setdefault('category', 'furniture')
80
+ number(item['speed'], .01, 100, 'instance speed')
81
+ number(item['start'], 0, 86400, 'start seconds')
82
+ number(item['zIndex'], -100000, 100000, 'zIndex')
83
+ if not item.get('reuseOf'):
84
+ source_path(root, item['source'])
85
+ if item['motion'] not in ('spring', 'rock', 'slide', 'unfurl', 'hang', 'roll', 'sequence'):
86
+ raise ValueError('Unsupported motion: ' + item['motion'])
87
+ if item['motion'] == 'sequence':
88
+ sequence = item['sequence']
89
+ source_path(root, sequence['image'])
90
+ frames = sequence['frames']
91
+ if not isinstance(frames, list) or not 1 <= len(frames) <= 120:
92
+ raise ValueError('Sequence requires 1..120 explicit frames')
93
+ for frame in frames:
94
+ number(frame['durationMs'], 1, 86400000, 'frame duration')
95
+ box(item['animationBox'], ident + ' animationBox')
96
+ else:
97
+ number(item['duration'], .05, 6, 'duration seconds')
98
+ number(item.get('fps', 20), 1, 30, 'fps')
99
+ if len(item['pivot']) != 2:
100
+ raise ValueError('Expected pivot [x, y]')
101
+ for n in item['pivot']:
102
+ number(n, 0, 1, 'pivot')
103
+ by_id = {item['id']: item for item in objects}
104
+ for item in objects:
105
+ owner = by_id.get(item.get('reuseOf')) if item.get('reuseOf') else item
106
+ if not owner or owner.get('reuseOf') or (owner is not item and not item.get('reuseReason')):
107
+ raise ValueError('Reuse needs a canonical asset and reviewed reason: ' + item['id'])
108
+ if owner is not item:
109
+ for key in ('motion', 'duration', 'pivot', 'sequence', 'fps'):
110
+ if key in item and item[key] != owner.get(key, 20 if key == 'fps' else None):
111
+ raise ValueError('Reuse cannot redefine animation: ' + item['id'])
112
+ if owner['motion'] == 'sequence':
113
+ box(item['animationBox'], item['id'] + ' animationBox')
114
+ seen = {item['id']}
115
+ parent = item.get('parent')
116
+ while parent is not None:
117
+ if parent not in by_id or parent in seen:
118
+ raise ValueError('Unknown or cyclic support: ' + item['id'])
119
+ if by_id[parent]['zIndex'] >= item['zIndex']:
120
+ raise ValueError('Props must draw above their support: ' + item['id'])
121
+ seen.add(parent)
122
+ parent = by_id[parent].get('parent')
123
+ number(recipe.get('playback', {}).get('speed', 1), .01, 100, 'scene speed')
124
+ return recipe
125
+
126
+
127
+ def static_image(root, spec):
128
+ with Image.open(source_path(root, spec['source'])) as source:
129
+ image = source.convert('RGBA')
130
+ if 'extractRect' in spec:
131
+ x1, y1, x2, y2 = spec['extractRect']
132
+ box([x1, y1, x2-x1, y2-y1], 'extractRect', image.size, integer=True)
133
+ image = image.crop((x1, y1, x2, y2))
134
+ if spec.get('clipPolygon'):
135
+ mask = Image.new('L', image.size)
136
+ points = []
137
+ for x, y in spec['clipPolygon']:
138
+ number(x, 0, 1, 'clip x'); number(y, 0, 1, 'clip y')
139
+ points.append((round(x*image.width), round(y*image.height)))
140
+ ImageDraw.Draw(mask).polygon(points, fill=255)
141
+ image.putalpha(ImageChops.darker(image.getchannel('A'), mask))
142
+ bounds = image.getchannel('A').point(lambda a: 255 if a > 30 else 0).getbbox()
143
+ if not bounds:
144
+ raise ValueError('Empty asset: ' + spec['id'])
145
+ return image.crop(bounds).resize(tuple(spec['bbox'][2:]), Image.Resampling.LANCZOS)
146
+
147
+
148
+ def bake(image, spec):
149
+ duration = round(spec['duration']*1000)
150
+ count = max(2, round(spec['duration']*spec.get('fps', 20)))
151
+ if count > 120:
152
+ raise ValueError('Animation exceeds 120 frames: ' + spec['id'])
153
+ if spec['motion'] == 'roll':
154
+ return bake_roll(image, duration, count)
155
+ if spec['motion'] in ('rock', 'slide'):
156
+ return bake_sway(image, spec, duration, count)
157
+ w, h = image.size
158
+ px, py = spec['pivot']
159
+ positions = []
160
+ for i in range(count):
161
+ sx, sy, dy = pose(i/(count-1), spec['motion'])
162
+ rw, rh = max(1, round(w*sx)), max(1, round(h*sy))
163
+ positions.append((round((w-rw)*px), round((h-rh)*py+dy*h), rw, rh))
164
+ left, top = min(0, min(p[0] for p in positions))-2, min(0, min(p[1] for p in positions))-2
165
+ right, bottom = max(w, max(p[0]+p[2] for p in positions))+2, max(h, max(p[1]+p[3] for p in positions))+2
166
+ size = (right-left, bottom-top)
167
+ if max(size) > 4096:
168
+ raise ValueError('Frame exceeds 4096 pixels: ' + spec['id'])
169
+ frames = []
170
+ for i, (x, y, rw, rh) in enumerate(positions):
171
+ frame = Image.new('RGBA', size)
172
+ frame.alpha_composite(image.resize((rw, rh), Image.Resampling.LANCZOS), (x-left, y-top))
173
+ # Distribute rounding over frames so arbitrary durations remain exact.
174
+ frames.append((frame, round((i+1)*duration/count)-round(i*duration/count)))
175
+ return frames, [-left, -top, w, h]
176
+
177
+
178
+ def sway_pose(t, motion):
179
+ if t >= 1:
180
+ return 1., 1., 0., 0.
181
+ if motion == 'rock':
182
+ growth = 1-(1-min(1, t/.45))**3
183
+ return (1+.04*math.sin(10*t)*math.exp(-4*t),
184
+ .1+.9*growth, 0., 12*(1-t)**2*math.cos(3*math.pi*t))
185
+ growth = 1-(1-min(1, t/.35))**3
186
+ return (.75+.25*growth, .3+.7*growth+.08*math.sin(10*t)*math.exp(-4*t),
187
+ -.3*math.exp(-5*t)*math.cos(3*math.pi*t)*(1-t),
188
+ 4*math.exp(-3*t)*math.sin(4*math.pi*t)*(1-t))
189
+
190
+
191
+ def bake_sway(image, spec, duration, count):
192
+ """Bake pivoted rocking/sliding, including rotation in the shared frame bounds."""
193
+ w, h = image.size
194
+ px, py = w*spec['pivot'][0], h*spec['pivot'][1]
195
+ transforms, corners = [], [(0, 0), (w, h)]
196
+ for i in range(count):
197
+ sx, sy, dx, degrees = sway_pose(i/(count-1), spec['motion'])
198
+ angle = math.radians(degrees)
199
+ a, b = math.cos(angle)*sx, -math.sin(angle)*sy
200
+ c, d = math.sin(angle)*sx, math.cos(angle)*sy
201
+ tx, ty = px+dx*w-a*px-b*py, py-c*px-d*py
202
+ transforms.append((a, b, c, d, tx, ty))
203
+ corners.extend((a*x+b*y+tx, c*x+d*y+ty) for x,y in [(0,0),(w,0),(0,h),(w,h)])
204
+ left = math.floor(min(x for x,y in corners))-2
205
+ top = math.floor(min(y for x,y in corners))-2
206
+ size = (math.ceil(max(x for x,y in corners))-left+2,
207
+ math.ceil(max(y for x,y in corners))-top+2)
208
+ if max(size) > 4096:
209
+ raise ValueError('Frame exceeds 4096 pixels: ' + spec['id'])
210
+ frames = []
211
+ for i,(a,b,c,d,tx,ty) in enumerate(transforms):
212
+ frame = Image.new('RGBA', size)
213
+ if i == count-1:
214
+ frame.alpha_composite(image, (-left, -top))
215
+ elif i > 0:
216
+ determinant = a*d-b*c
217
+ # Pillow maps output pixels back to the source, including union padding.
218
+ inverse = (d/determinant, -b/determinant,
219
+ (d*(left-tx)-b*(top-ty))/determinant,
220
+ -c/determinant, a/determinant,
221
+ (-c*(left-tx)+a*(top-ty))/determinant)
222
+ frame = image.transform(size, Image.Transform.AFFINE, inverse, Image.Resampling.BICUBIC)
223
+ frames.append((frame, round((i+1)*duration/count)-round(i*duration/count)))
224
+ return frames, [-left, -top, w, h]
225
+
226
+
227
+ def bake_roll(image, duration, count):
228
+ """Unroll toward image bottom, preserving revealed pixels and the exact final image."""
229
+ w, h = image.size
230
+ padding = max(4, round(h*.48))
231
+ size = (w+4, h+padding+4)
232
+ if max(size) > 4096:
233
+ raise ValueError('Roll frame exceeds 4096 pixels')
234
+ alpha = image.getchannel('A').point(lambda value: 255 if value > 128 else 0)
235
+ frames = []
236
+ for i in range(count):
237
+ frame = Image.new('RGBA', size)
238
+ if i == count-1:
239
+ frame.alpha_composite(image, (2, padding))
240
+ elif i > 0:
241
+ progress = i/(count-1)
242
+ travel = progress*progress*(3-2*progress)
243
+ front = min(h-1, max(1, round(h*travel)))
244
+ frame.alpha_composite(image.crop((0, 0, w, front)), (2, padding))
245
+ remaining = alpha.crop((0, front, w, h)).getbbox()
246
+ if remaining:
247
+ left, _, right, _ = remaining
248
+ # Remaining cloth winds around a shrinking cylinder. Sampling arcs
249
+ # moves its texture while already laid cloth stays fixed in place.
250
+ radius = max(1, round(h*.22*math.sqrt(1-travel)))
251
+ roll_height = 2*radius
252
+ cap_width = min(max(1, round(radius*.5)), max(1, (right-left)//4))
253
+ for row in range(roll_height):
254
+ theta = math.acos(1-2*(row+.5)/roll_height)
255
+ source_y = min(h-1, front+round(theta*radius*.35))
256
+ bounds = alpha.crop((0, source_y, w, source_y+1)).getbbox()
257
+ if not bounds:
258
+ continue
259
+ strip = image.crop((bounds[0], source_y, bounds[2], source_y+1))
260
+ inset = round(cap_width*(1-math.sin(theta)))
261
+ strip = strip.resize((max(1, right-left-2*inset), 1), Image.Resampling.BICUBIC)
262
+ strip = ImageEnhance.Brightness(strip).enhance(.62+.48*math.sin(theta))
263
+ frame.alpha_composite(strip, (left+2+inset, padding+front-roll_height+row))
264
+ sample_y = min(h-1, front+radius//2)
265
+ sample_bounds = alpha.crop((0, sample_y, w, sample_y+1)).getbbox()
266
+ if not sample_bounds:
267
+ frames.append((frame, round((i+1)*duration/count)-round(i*duration/count)))
268
+ continue
269
+ sample_x = min(sample_bounds[2]-1, sample_bounds[0]+max(1, round((sample_bounds[2]-sample_bounds[0])*.04)))
270
+ sample = image.getpixel((sample_x, sample_y))
271
+ color = tuple(round(c*.8) for c in sample[:3])+(255,)
272
+ outline = tuple(round(c*.55) for c in sample[:3])+(255,)
273
+ draw = ImageDraw.Draw(frame)
274
+ for cx in (left+2+cap_width, right+2-cap_width):
275
+ cy = padding+front-radius
276
+ draw.ellipse((cx-cap_width, cy-radius, cx+cap_width, cy+radius-1), fill=color, outline=outline)
277
+ if radius > 4:
278
+ draw.arc((cx-cap_width//2, cy-radius//2, cx+cap_width//2, cy+radius//2), 30, 330, fill=outline, width=1)
279
+ frames.append((frame, round((i+1)*duration/count)-round(i*duration/count)))
280
+ return frames, [2, padding, w, h]
281
+
282
+
283
+ def extract(root, spec):
284
+ sequence = spec['sequence']
285
+ with Image.open(source_path(root, sequence['image'])) as source:
286
+ atlas = source.convert('RGBA')
287
+ frames = []
288
+ for frame in sequence['frames']:
289
+ x, y, w, h = box(frame['rect'], 'sequence frame', atlas.size, integer=True)
290
+ if frames and frames[0][0].size != (w, h):
291
+ raise ValueError('Sequence frames must have equal untrimmed sizes')
292
+ frames.append((atlas.crop((x, y, x+w, y+h)), frame['durationMs']))
293
+ return frames, None
294
+
295
+
296
+ def preview(frames, folder, ident):
297
+ cell, columns = 256, min(8, len(frames))
298
+ rows = math.ceil(len(frames)/columns)
299
+ sheet = Image.new('RGBA', (columns*cell, rows*cell))
300
+ info, elapsed = [], 0
301
+ for i, (frame, duration) in enumerate(frames):
302
+ thumb = frame.copy(); thumb.thumbnail((cell, cell), Image.Resampling.LANCZOS)
303
+ x, y = i % columns * cell, i // columns * cell
304
+ sheet.alpha_composite(thumb, (x+(cell-thumb.width)//2, y+(cell-thumb.height)//2))
305
+ info.append(dict(index=i, time=elapsed/1000, x=x, y=y, width=cell, height=cell, duration=duration))
306
+ elapsed += duration
307
+ sheet.save(folder/(ident+'.png'))
308
+ return dict(fps=min(30, max(1, 1000*len(frames)/elapsed)), frameCount=len(frames),
309
+ width=sheet.width, height=sheet.height, columns=columns, rows=rows, frames=info)
310
+
311
+
312
+ def export(root, recipe_path, output, preview_dir=None):
313
+ root, recipe_path, output = root.resolve(), recipe_path.resolve(), output.resolve()
314
+ preview_dir = preview_dir.resolve() if preview_dir else None
315
+ recipe = load_recipe(root, recipe_path)
316
+ archive = output.with_name(output.name+'.zip')
317
+ for path in [output, archive] + ([preview_dir] if preview_dir else []):
318
+ if path.exists():
319
+ raise FileExistsError('Choose a new output path: ' + str(path))
320
+ if preview_dir and (preview_dir == output or preview_dir.is_relative_to(output) or output.is_relative_to(preview_dir)):
321
+ raise ValueError('Preview and final output must be separate directories')
322
+ output.mkdir(parents=True)
323
+ incomplete = output/'.incomplete'; incomplete.touch()
324
+ if preview_dir:
325
+ preview_dir.mkdir(parents=True); (preview_dir/'.incomplete').touch()
326
+ (output/'background').mkdir()
327
+ for field in ('background', 'reference'):
328
+ with Image.open(source_path(root, recipe[field])) as image:
329
+ image.convert('RGBA').save(output/'background'/(field+'.png'))
330
+ assets, animations, preview_items = {}, {}, []
331
+ for spec in recipe['objects']:
332
+ if spec.get('reuseOf'):
333
+ continue
334
+ ident = spec['id']
335
+ folder = output/'furniture'/ident
336
+ (folder/'frames').mkdir(parents=True)
337
+ image = static_image(root, spec); image.save(folder/'image.png')
338
+ frames, image_rect = extract(root, spec) if spec['motion'] == 'sequence' else bake(image, spec)
339
+ entries = []
340
+ for i, (frame, duration) in enumerate(frames):
341
+ file = 'frames/frame_%04d.png' % (i+1)
342
+ frame.save(folder/file)
343
+ entries.append(dict(file=file, durationMs=duration))
344
+ data = dict(version=1, frameSize=list(frames[0][0].size), frameCount=len(frames),
345
+ durationMs=sum(f['durationMs'] for f in entries), loop=False, endBehavior='hold', frames=entries)
346
+ if image_rect:
347
+ data['finalImageRect'] = image_rect
348
+ write_json(folder/'animation.json', data)
349
+ animations[ident] = data
350
+ assets[ident] = dict(id=ident, label=spec.get('label', ident), category=spec['category'],
351
+ directory='furniture/'+ident, image='furniture/'+ident+'/image.png',
352
+ animation='furniture/'+ident+'/animation.json')
353
+ if preview_dir:
354
+ preview_items.append(dict(assetId=ident, title=spec.get('label', ident), category=spec['category'],
355
+ file=ident+'.png', frameSetInfo=preview(frames, preview_dir, ident)))
356
+ instances = []
357
+ for spec in recipe['objects']:
358
+ asset_id = spec.get('reuseOf', spec['id']); animation = animations[asset_id]
359
+ x, y, w, h = spec['bbox']
360
+ if 'finalImageRect' in animation:
361
+ ox, oy, iw, ih = animation['finalImageRect']; fw, fh = animation['frameSize']
362
+ animation_box = [x-ox*w/iw, y-oy*h/ih, fw*w/iw, fh*h/ih]
363
+ else:
364
+ animation_box = spec['animationBox']
365
+ instances.append(dict(id=spec['id'], assetId=asset_id, label=spec.get('label', spec['id']),
366
+ imageBox=spec['bbox'], animationBox=animation_box, startMs=round(spec['start']*1000),
367
+ speed=spec['speed'], parent=spec['parent'], zIndex=spec['zIndex']))
368
+ scene = dict(version=2, size=recipe['size'], coordinates=dict(origin='top-left', unit='px', box='xywh'),
369
+ viewport=dict(fit='contain', align='center', clip=True),
370
+ playback=dict(speed=recipe.get('playback', {}).get('speed', 1), autoplay=False, endBehavior='hold'),
371
+ background='background/background.png', reference='background/reference.png',
372
+ assets=list(assets.values()), instances=instances)
373
+ write_json(output/'scene.json', scene)
374
+ shutil.copy2(Path(__file__).parent.parent/'references/game-integration.md', output/'README.md')
375
+ for ident, animation in animations.items():
376
+ for frame in animation['frames']:
377
+ with Image.open(output/assets[ident]['directory']/frame['file']) as image:
378
+ if list(image.size) != animation['frameSize'] or image.mode != 'RGBA':
379
+ raise ValueError('Exported frame mismatch: ' + ident)
380
+ image.load()
381
+ with zipfile.ZipFile(archive, 'x', zipfile.ZIP_DEFLATED) as bundle:
382
+ for file in sorted(output.rglob('*')):
383
+ if file.is_file() and file != incomplete:
384
+ bundle.write(file, file.relative_to(output).as_posix())
385
+ with zipfile.ZipFile(archive) as bundle:
386
+ if bundle.testzip():
387
+ raise ValueError('ZIP integrity check failed')
388
+ incomplete.unlink()
389
+ if preview_dir:
390
+ write_json(preview_dir/'manifest.json', dict(items=preview_items))
391
+ (preview_dir/'.incomplete').unlink()
392
+ receipt = dict(directory=str(output), archive=str(archive), uniqueAssets=len(assets), instances=len(instances),
393
+ frames=sum(a['frameCount'] for a in animations.values()),
394
+ recipeSha256=hashlib.sha256(recipe_path.read_bytes()).hexdigest())
395
+ print(json.dumps(receipt, ensure_ascii=False))
396
+ return scene
397
+
398
+
399
+ if __name__ == '__main__':
400
+ parser = argparse.ArgumentParser(description=__doc__)
401
+ parser.add_argument('--source-root', type=Path, required=True)
402
+ parser.add_argument('--recipe', type=Path, required=True)
403
+ parser.add_argument('--output', type=Path, required=True)
404
+ parser.add_argument('--preview-dir', type=Path)
405
+ args = parser.parse_args()
406
+ export(args.source_root.resolve(), args.recipe.resolve(), args.output.resolve(),
407
+ args.preview_dir.resolve() if args.preview_dir else None)
@@ -0,0 +1,137 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ import tempfile
5
+ import unittest
6
+ import zipfile
7
+ from pathlib import Path
8
+ from PIL import Image, ImageDraw
9
+ from scene_assets import bake, export, load_recipe, sway_pose
10
+
11
+
12
+ class SceneAssetsTest(unittest.TestCase):
13
+ def setUp(self):
14
+ self.temp = tempfile.TemporaryDirectory()
15
+ self.addCleanup(self.temp.cleanup)
16
+ self.root = Path(self.temp.name)
17
+ Image.new('RGBA', (160, 90), 'white').save(self.root/'room.png')
18
+ Image.new('RGBA', (12, 18), 'red').save(self.root/'object.png')
19
+ self.recipe = dict(version=1, size=[160, 90], background='room.png', reference='room.png',
20
+ objects=[dict(id='stool', source='object.png', bbox=[10,20,12,18], motion='spring',
21
+ duration=.375, pivot=[.5,1], start=0, zIndex=1),
22
+ dict(id='copy', reuseOf='stool', reuseReason='same shape', bbox=[80,20,24,36],
23
+ start=.5, speed=2, zIndex=2)])
24
+ self.path = self.root/'recipe.json'
25
+
26
+ def save(self):
27
+ self.path.write_text(json.dumps(self.recipe))
28
+
29
+ def test_export_dedup_exact_duration_and_scaled_padding(self):
30
+ self.save()
31
+ with contextlib.redirect_stdout(io.StringIO()):
32
+ scene = export(self.root, self.path, self.root/'output', self.root/'preview')
33
+ self.assertEqual(len(scene['assets']), 1)
34
+ animation = json.loads((self.root/'output/furniture/stool/animation.json').read_text())
35
+ self.assertEqual(sum(f['durationMs'] for f in animation['frames']), 375)
36
+ a,b = scene['instances']
37
+ self.assertEqual(b['animationBox'][2], 2*a['animationBox'][2])
38
+ self.assertEqual(b['speed'], 2)
39
+ self.assertEqual(scene['playback']['autoplay'], False)
40
+ self.assertFalse((self.root/'output/.incomplete').exists())
41
+ self.assertTrue((self.root/'output/README.md').is_file())
42
+ self.assertTrue((self.root/'preview/manifest.json').is_file())
43
+ self.assertFalse((self.root/'preview/.incomplete').exists())
44
+ with zipfile.ZipFile(self.root/'output.zip') as bundle:
45
+ self.assertIsNone(bundle.testzip())
46
+ self.assertIn('README.md', bundle.namelist())
47
+ self.assertIn('scene.json', bundle.namelist())
48
+ with self.assertRaises(FileExistsError):
49
+ export(self.root, self.path, self.root/'output')
50
+
51
+ def test_rejects_cycles_missing_assets_and_conflicting_reuse(self):
52
+ self.recipe['objects'][0]['parent'] = 'copy'
53
+ self.recipe['objects'][1]['parent'] = 'stool'
54
+ self.save()
55
+ with self.assertRaises(ValueError): load_recipe(self.root, self.path)
56
+ for item in self.recipe['objects']: item.pop('parent')
57
+ self.recipe['objects'][1]['motion'] = 'hang'
58
+ self.save()
59
+ with self.assertRaises(ValueError): load_recipe(self.root, self.path)
60
+ self.recipe['objects'][1].pop('motion')
61
+ self.recipe['objects'][0]['source'] = '../outside.png'
62
+ self.save()
63
+ with self.assertRaises(ValueError): load_recipe(self.root, self.path)
64
+
65
+ def test_sequence_is_generic_and_preserves_variable_durations(self):
66
+ Image.new('RGBA', (24,18), 'blue').save(self.root/'atlas.png')
67
+ obj = self.recipe['objects'][0]
68
+ obj.update(motion='sequence', animationBox=[8,18,16,24],
69
+ sequence=dict(image='atlas.png',frames=[dict(rect=[0,0,12,18],durationMs=60),
70
+ dict(rect=[12,0,12,18],durationMs=130)]))
71
+ self.recipe['objects'][1]['animationBox'] = [76,16,32,48]
72
+ self.save()
73
+ with contextlib.redirect_stdout(io.StringIO()):
74
+ scene = export(self.root,self.path,self.root/'output')
75
+ animation = json.loads((self.root/'output/furniture/stool/animation.json').read_text())
76
+ self.assertEqual(animation['durationMs'], 190)
77
+ self.assertEqual(scene['instances'][1]['animationBox'], [76,16,32,48])
78
+
79
+ def test_roll_preserves_laid_texture_and_exact_final_image(self):
80
+ rug = Image.new('RGBA', (120, 80))
81
+ for y in range(80):
82
+ for x in range(120):
83
+ rug.putpixel((x,y), (x*2, y*3, 90, 255))
84
+ frames, rect = bake(rug, dict(motion='roll', duration=1.5, fps=20))
85
+ x,y,w,h = rect
86
+ self.assertEqual(sum(duration for _,duration in frames),1500)
87
+ self.assertIsNone(frames[0][0].getbbox())
88
+ self.assertEqual(len({frame.size for frame,_ in frames}),1)
89
+ middle = frames[len(frames)//2][0]
90
+ self.assertEqual(middle.getpixel((x+30,y+5)),rug.getpixel((30,5)))
91
+ self.assertEqual(middle.getpixel((x+30,y+75))[3],0)
92
+ self.assertEqual(frames[-1][0].crop((x,y,x+w,y+h)).tobytes(),rug.tobytes())
93
+
94
+ def test_oval_roll_does_not_use_transparent_black_for_end_caps(self):
95
+ rug = Image.new('RGBA', (120, 40))
96
+ ImageDraw.Draw(rug).ellipse((0,0,119,39), fill=(80,150,190,255))
97
+ frames, _ = bake(rug, dict(motion='roll', duration=1.5, fps=20))
98
+ for frame, _ in frames:
99
+ for r,g,b,a in frame.getdata():
100
+ if a > 128:
101
+ self.assertGreater(r+g+b, 100)
102
+
103
+ def test_sway_keeps_padding_exact_final_pose_and_distinct_motion(self):
104
+ image = Image.new('RGBA', (80, 120), (180, 80, 30, 255))
105
+ ImageDraw.Draw(image).rectangle((0,0,20,25), fill=(255,220,40,255))
106
+ for motion in ('rock', 'slide'):
107
+ frames, rect = bake(image, dict(id='furniture', motion=motion,
108
+ duration=1.5, fps=20, pivot=[.5,1]))
109
+ self.assertIsNone(frames[0][0].getbbox())
110
+ self.assertEqual(sum(ms for _,ms in frames), 1500)
111
+ self.assertEqual(len({f.size for f,_ in frames}), 1)
112
+ for frame,_ in frames[1:]:
113
+ x1,y1,x2,y2 = frame.getchannel('A').getbbox()
114
+ self.assertGreater(x1, 0); self.assertGreater(y1, 0)
115
+ self.assertLess(x2, frame.width); self.assertLess(y2, frame.height)
116
+ x,y,w,h = rect
117
+ self.assertEqual(frames[-1][0].crop((x,y,x+w,y+h)).tobytes(), image.tobytes())
118
+ poses = [sway_pose(i/29, 'rock') for i in range(30)]
119
+ self.assertTrue(all(p[2] == 0 for p in poses))
120
+ self.assertGreater(max(p[3] for p in poses), 5)
121
+ self.assertLess(min(p[3] for p in poses), -3)
122
+ slides = [sway_pose(i/29, 'slide') for i in range(30)]
123
+ self.assertLess(min(p[2] for p in slides), -.2)
124
+ self.assertGreater(max(p[2] for p in slides), 0)
125
+
126
+ def test_new_motions_validate_and_reuse_cannot_change_them(self):
127
+ for motion in ('rock', 'slide'):
128
+ self.recipe['objects'][0]['motion'] = motion
129
+ self.save()
130
+ self.assertEqual(load_recipe(self.root,self.path)['objects'][0]['motion'],motion)
131
+ self.recipe['objects'][1]['motion'] = 'rock'
132
+ self.save()
133
+ with self.assertRaises(ValueError): load_recipe(self.root,self.path)
134
+
135
+
136
+ if __name__ == '__main__':
137
+ unittest.main()
@@ -22,17 +22,17 @@ Maker CLI/bundle, not an unversioned package or another installation's documenta
22
22
  Read only the matching section or guide. An unavailable provider, blocked card or missing
23
23
  template search result does not establish that the whole feature is unsupported.
24
24
 
25
- | User goal | UI / CLI support | Read next |
26
- | -------------------------------------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------- |
27
- | Create/edit a canvas or custom workflow | Both; CLI supports advertised card types and editable fields | [Canvas editing](#canvas-editing) |
28
- | Reuse templates, save personal templates | Both add copies; library save/replace and ZIP exchange are UI-only | [Templates](#templates) |
29
- | Import/replace images, set references, generate images | Both, subject to the selected provider | [Images and references](#images-and-references) |
30
- | First-frame / first-last-frame / multi-reference video | Both; mode and source order matter | [Canvas Video](canvas-video.md) |
31
- | Extract frames, configure and export animation | Both for advertised settings/export; brush and per-frame editing are UI-only | [Sequences](#sequences) |
32
- | Slice an atlas and export PNG resources | Both through existing resource cards; review before confirmation | [Atlases and UI](#atlases-and-ui) |
33
- | Recognize UI, prepare Bbox batches, assemble editable UI | Existing Bbox workflow and CLI; follow linked Skills | [Atlases and UI](#atlases-and-ui) |
34
- | Character views and 3D generation | Both; review before model confirmation | [Models](#models) |
35
- | Query tasks, recover saving, export results | CLI supports these; no generic task/draft unlock | [Recovery and delivery](#recovery-and-delivery) |
25
+ | User goal | UI / CLI support | Read next |
26
+ | -------------------------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------- |
27
+ | Create/edit a canvas or custom workflow | Both; CLI supports advertised card types and editable fields | [Canvas editing](#canvas-editing) |
28
+ | Reuse templates, save personal templates | Both add copies; CLI supports ZIP import/export, library save/replace uses UI | [Templates](#templates) |
29
+ | Import/replace images, set references, generate images | Both, subject to the selected provider | [Images and references](#images-and-references) |
30
+ | First-frame / first-last-frame / multi-reference video | Both; mode and source order matter | [Canvas Video](canvas-video.md) |
31
+ | Extract frames, configure and export animation | Both for advertised settings/export; brush and per-frame editing are UI-only | [Sequences](#sequences) |
32
+ | Slice an atlas and export PNG resources | Both through existing resource cards; review before confirmation | [Atlases and UI](#atlases-and-ui) |
33
+ | Recognize UI, prepare Bbox batches, assemble editable UI | Existing Bbox workflow and CLI; follow linked Skills | [Atlases and UI](#atlases-and-ui) |
34
+ | Character views and 3D generation | Both; review before model confirmation | [Models](#models) |
35
+ | Query tasks, recover saving, export results | CLI supports these; no generic task/draft unlock | [Recovery and delivery](#recovery-and-delivery) |
36
36
 
37
37
  ## Canvas editing
38
38
 
@@ -52,8 +52,11 @@ Copies can be edited independently. AI can also assemble custom workflows from s
52
52
  To save one to My Templates, select at least two cards with an internal connection and use
53
53
  the UI's Save as Template menu. External connections are excluded; unresolved tasks and
54
54
  missing dependencies can block saving. Personal templates belong to the current project.
55
- Library save/replace and ZIP import/export are UI-only; `canvas save` saves the canvas,
56
- not a template. Builtin templates cannot be overwritten. Do not write template JSON directly.
55
+ Library save/replace uses the UI; `canvas save` saves the canvas, not a template. For ZIP
56
+ exchange without a file picker, use `canvas import-template --target-dir PATH --file ABSOLUTE_ZIP`
57
+ and `canvas export-template --target-dir PATH --id ID --revision N --output-dir EXISTING_DIRECTORY`.
58
+ Import returns a new templateId for add-template; associated Skills are not installed automatically.
59
+ Builtin templates cannot be overwritten. Do not write template JSON directly.
57
60
 
58
61
  ## Images and references
59
62
 
@@ -120,7 +120,7 @@ request/correlation ID, reproduction steps, visible Maker tools, client version,
120
120
  Do not include the complete conversation. Send that JSON through stdin, never argv, while running:
121
121
 
122
122
  ```text
123
- npx -y --package @taptap/maker@0.0.41-beta.1 taptap-maker mcp report --ide <client> --target-dir <project> --context-stdin --consent --json
123
+ npx -y --package @taptap/maker@0.0.41-beta.2 taptap-maker mcp report --ide <client> --target-dir <project> --context-stdin --consent --json
124
124
  ```
125
125
 
126
126
  Prefer the active client's exact Maker MCP `command` plus ordered `args`, then append the `mcp