Datasets:
File size: 6,153 Bytes
89592d6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | """Render a supplied GSAP program with MoVer and the benchmark's GSAP runtime."""
from __future__ import annotations
import asyncio
import json
from importlib.metadata import version
from pathlib import Path
from typing import Any
from mover.converter.mover_converter import capture_frames_server_driven
from mover.converter.render_session import RenderSession
GSAP_VERSION = "3.14.1"
GSAP_ROOT = Path(__file__).resolve().parents[1] / "node_modules" / "gsap"
RUNTIME_FILES = (
"gsap.min.js",
"MotionPathPlugin.min.js",
"EasePack.min.js",
"MotionPathHelper.min.js",
"DrawSVGPlugin.min.js",
"MorphSVGPlugin.min.js",
"CustomEase.min.js",
"CustomBounce.min.js",
)
PLUGIN_GLOBALS = (
"MotionPathPlugin", "SlowMo", "RoughEase", "ExpoScaleEase",
"MotionPathHelper", "DrawSVGPlugin", "MorphSVGPlugin", "CustomEase", "CustomBounce",
)
def assemble_html(svg: str, program: str) -> str:
if not program.strip() or "</script" in program.lower():
raise ValueError("the GSAP program must be nonempty and contain no closing </script> tag")
manifest = GSAP_ROOT / "package.json"
installed = json.loads(manifest.read_text(encoding="utf-8"))["version"]
if installed != GSAP_VERSION:
raise RuntimeError(f"GSAP {GSAP_VERSION} is required, found {installed}; run npm ci")
scripts = []
for name in RUNTIME_FILES:
source = (GSAP_ROOT / "dist" / name).read_text(encoding="utf-8")
if "</script" in source.lower():
raise ValueError(f"GSAP runtime file cannot be safely inlined: {name}")
scripts.append(f'<script data-gsap-runtime="{name}">\n{source}\n</script>')
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'self' http://localhost:* http://127.0.0.1:*; media-src 'none'; object-src 'none'; frame-src 'none'; worker-src 'none'; base-uri 'none'; form-action 'none'">
<meta name="gsap-runtime-version" content="{GSAP_VERSION}">
<title>MotionGraphicsBench animation</title>
<style>html,body{{margin:0;padding:0;background:transparent}}</style>
</head>
<body>
{svg}
{"".join(scripts)}
<script>
(() => {{
const names = {json.dumps(PLUGIN_GLOBALS)};
const missing = names.filter(name => typeof window[name] === "undefined");
if (missing.length) throw new Error(`Missing GSAP plugins: ${{missing.join(", ")}}`);
gsap.registerPlugin(...names.map(name => window[name]));
const errors = [];
Object.defineProperty(window, "__benchmark_errors", {{get: () => errors.slice()}});
window.addEventListener("error", event => errors.push(event.error?.stack || event.message));
window.addEventListener("unhandledrejection", event => errors.push(String(event.reason)));
const blocked = name => () => {{ throw new Error(`${{name}} is disabled by the benchmark harness`); }};
const nativeFetch = window.fetch.bind(window);
Object.defineProperty(window, "fetch", {{configurable: false, writable: false, value: (input, init) => {{
const raw = input && typeof input === "object" && "url" in input ? input.url : String(input);
const url = new URL(raw, window.location.href);
if (!["localhost", "127.0.0.1", "::1"].includes(url.hostname) ||
url.protocol !== "http:" || url.port !== window.location.port) {{
return Promise.reject(new Error("fetch is restricted to the active MoVer loopback port"));
}}
return nativeFetch(input, init);
}}}});
for (const name of ["XMLHttpRequest", "WebSocket", "EventSource", "Worker", "SharedWorker"]) {{
Object.defineProperty(window, name, {{configurable: false, writable: false, value: blocked(name)}});
}}
Object.defineProperty(window, "open", {{configurable: false, writable: false, value: blocked("window.open")}});
Object.defineProperty(navigator, "sendBeacon", {{configurable: false, writable: false, value: blocked("sendBeacon")}});
}})();
</script>
<script id="svg-script">
{program}
</script>
<script src="./convert.js"></script>
</body>
</html>
"""
async def _capture(
html: Path, output: Path, fps: float, capture_duration: float | None,
) -> tuple[list[str], dict[str, Any]]:
async with RenderSession(html, output_dir=output, capture_duration=capture_duration) as session:
errors: list[str] = []
session.page.on("pageerror", lambda error: errors.append(str(error)))
initial_errors = await session.page.evaluate("window.__benchmark_errors")
if initial_errors:
raise RuntimeError("GSAP execution failed:\n" + "\n".join(initial_errors))
info = await session.get_animation_info(fps)
frames_dir = output / "svg_frames"
await capture_frames_server_driven(
session.page, str(frames_dir), fps=fps, output_format="svg",
capture_duration=capture_duration,
)
errors.extend(await session.page.evaluate("window.__benchmark_errors"))
if errors:
raise RuntimeError("GSAP execution failed:\n" + "\n".join(errors))
paths = sorted(frames_dir.glob("frame_*.svg"))
frames = [path.read_text(encoding="utf-8").strip() for path in paths]
browser = session.page.context.browser
assert browser is not None
return frames, {
"mover_version": version("mover"),
"gsap_version": GSAP_VERSION,
"chromium": browser.version,
"fps": fps,
"duration": float(info["animDuration"]),
"frame_count": len(frames),
}
def render_frames(
svg: str, program: str, output: Path, *, fps: float,
capture_duration: float | None = None, timeout: float = 900,
) -> tuple[list[str], dict[str, Any]]:
html_source = assemble_html(svg, program)
output.mkdir(parents=True, exist_ok=False)
html = output / "animation.html"
html.write_text(html_source, encoding="utf-8")
return asyncio.run(asyncio.wait_for(_capture(html, output, fps, capture_duration), timeout=timeout))
|