Debian Codegraph @

texmf-dist/tex/latex/svg-animate/svg-animate.sty

raw
1 %% svg-animate — Animated SVG diagrams with TikZ
2 %% Copyright (C) 2026 Sébastien Gross
3 %%
4 %% This program is free software: you can redistribute it and/or modify
5 %% it under the terms of the GNU Affero General Public License as published by
6 %% the Free Software Foundation, either version 3 of the License, or
7 %% (at your option) any later version.
8 %%
9 %% This program is distributed in the hope that it will be useful,
10 %% but WITHOUT ANY WARRANTY; without even the implied warranty of
11 %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 %% GNU Affero General Public License for more details.
13 %%
14 %% You should have received a copy of the GNU Affero General Public License
15 %% along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17 \NeedsTeXFormat{LaTeX2e}
18 \def\svganimateversion{v1.1}
19 \def\svganimatedate{2026/04/28}
20 \ProvidesPackage{svg-animate}[\svganimatedate\space\svganimateversion\space Generate animated SVG diagrams with TikZ]
21
22 %% ── Engine detection ─────────────────────────────────────────────────────────
23 %% Must come before \RequirePackage{tikz}.
24 %% Only latex in DVI output mode needs the dvisvgm PGF and graphicx drivers.
25 %%
26 %% \pdfoutput is defined by pdfTeX (latex/pdflatex) and LuaTeX, with value:
27 %% 0 → DVI output (latex in DVI-compat mode) → needs dvisvgm
28 %% 1 → PDF output → default drivers are fine
29 %%
30 %% XeTeX does not define \pdfoutput at all, so the \ifdefined guard silently
31 %% skips the block for xelatex without any explicit \XeTeXversion check.
32 %%
33 %% \if@anim@svgmode is true only in DVI/SVG mode (latex → dvisvgm).
34 %% Use it to conditionalize content: \reveal is suppressed when false,
35 %% and \noanimate renders its argument only when false (static PDF).
36 \newif\if@anim@svgmode
37 \newif\if@anim@dvisvgm@old %% true = dvisvgm < 3.4; set in SVG mode only
38 %% Set by the /anim/noanimate key on \reveal to force rendering in PDF mode
39 %% even when \noanimate is present in the animate body.
40 \newif\if@anim@reveal@static
41 %% True while the animate environment's begin code is executing.
42 %% Used by \animstep to detect misuse outside animate.
43 \newif\if@anim@inside
44 %% True when the animation should loop (default).
45 %% Set to false via loop=false to produce a one-shot animation.
46 \newif\if@anim@loop \@anim@looptrue
47 %% True when the animate environment's static=true key was set.
48 %% When true, \reveal renders content at full opacity without keyframe animation.
49 \newif\if@anim@envstatic
50 %%
51 %% When running under latex in DVI mode (pdfoutput=0), configure three things:
52 %%
53 %% 1. \@anim@svgmodetrue
54 %% Activates SVG-specific behaviour throughout the package: \reveal emits
55 %% SMIL keyframe animations, \noanimate is suppressed, etc.
56 %%
57 %% 2. \def\pgfsysdriver{pgfsys-dvisvgm.def}
58 %% Tells PGF/TikZ to use the dvisvgm backend instead of the default dvips
59 %% backend. This must be set BEFORE \RequirePackage{tikz} because PGF
60 %% reads \pgfsysdriver at load time to select the system layer. Without
61 %% this, TikZ would emit PostScript specials (dvips) instead of SVG-aware
62 %% specials, and dvisvgm would not produce a valid animated SVG.
63 %%
64 %% 3. \PassOptionsToPackage{dvisvgm}{graphicx}
65 %% Ensures the graphicx package (loaded by \RequirePackage below) also
66 %% uses the dvisvgm driver for \includegraphics. Without this, graphicx
67 %% would default to dvips and any raster image included in the document
68 %% would not survive the DVI→SVG conversion.
69 %%
70 \ifdefined\pdfoutput
71 \ifnum\pdfoutput=0
72 \@anim@svgmodetrue
73 \def\pgfsysdriver{pgfsys-dvisvgm.def}
74 \PassOptionsToPackage{dvisvgm}{graphicx}
75 \fi
76 \fi
77
78 \RequirePackage{tikz}
79 \RequirePackage{graphicx}
80 \usetikzlibrary{animations}
81
82 %% ── Bitmap inclusion override (SVG mode only) ────────────────────────────────
83 %%
84 %% WHY we override \Ginclude@bitmap
85 %% ----------------------------------
86 %% The graphicx dvisvgm driver (graphics-def/dvisvgm.def) implements bitmap
87 %% inclusion via \special{dvisvgm:raw ...}, injecting a literal SVG fragment:
88 %%
89 %% <g transform="translate({?x},{?y})">
90 %% <svg ...><image width="W" height="H" xlink:href="file.png"/></svg>
91 %% </g>
92 %%
93 %% dvisvgm copies this verbatim into the output SVG, leaving xlink:href as an
94 %% external file reference. The dvisvgm flag --embed-bitmaps only operates on
95 %% \special{dvisvgm:img} specials — it has no effect on xlink:href attributes
96 %% inside dvisvgm:raw fragments.
97 %%
98 %% VERSION REQUIREMENT: dvisvgm >= 3.4 (2024-07-24, TeX Live 2025).
99 %% --embed-bitmaps support for dvisvgm:img was added in 3.4. With earlier
100 %% versions dvisvgm:img produces an external xlink:href regardless of
101 %% --embed-bitmaps, so bitmaps remain as separate files.
102 %%
103 %% We detect the dvisvgm version at compile time (via io.popen in LuaTeX) and
104 %% choose between two code paths:
105 %%
106 %% dvisvgm >= 3.4 -> override \Ginclude@bitmap to emit \special{dvisvgm:img}
107 %% (no \raise; dvisvgm:img uses TeX bottom-left anchor).
108 %% With --embed-bitmaps the output SVG is self-contained.
109 %%
110 %% dvisvgm < 3.4 -> keep the stock \Ginclude@bitmap (dvisvgm:raw + \raise).
111 %% Bitmaps remain as external file references.
112 %% A package warning is emitted at compile time.
113 %%
114 %% If the version cannot be detected (shell escape disabled), modern behaviour
115 %% (>= 3.4) is assumed since TeX Live 2025+ is current.
116 %%
117 %% WHY no \raise in the dvisvgm:img path
118 %% ---------------------------------------
119 %% The stock \Ginclude@bitmap uses \raise\height\hbox{...} to compensate for
120 %% the SVG top-left coordinate convention used by dvisvgm:raw ({?x},{?y}).
121 %% \special{dvisvgm:img} uses the TeX bottom-left baseline convention instead,
122 %% so no \raise is needed. Adding \raise would shift the image UP by its own
123 %% height — exactly the wrong direction.
124 %%
125 %% WHY explicit "pt" units in dvisvgm:img
126 %% ----------------------------------------
127 %% Without an explicit unit, dvisvgm reads the next characters as the unit; a
128 %% path like "icons/foo.png" causes it to read "ic", which is invalid.
129 %% \strip@pt gives a bare number; appending "pt" produces e.g. "42.52pt".
130 \if@anim@svgmode
131 \ifdefined\directlua
132 \directlua{
133 local ok, f = pcall(io.popen, 'dvisvgm --version')
134 if ok and f then
135 local s = f:read('*a')
136 f:close()
137 local p = string.char(37)
138 local maj, min = s:match('dvisvgm (' ..p.. 'd+)' ..p.. '.(' ..p.. 'd+)')
139 if maj then
140 maj, min = tonumber(maj), tonumber(min)
141 if not (maj > 3 or (maj == 3 and min >= 4)) then
142 tex.print('\\@anim@dvisvgm@oldtrue')
143 texio.write_nl('(svg-animate) Warning: dvisvgm '
144 .. tostring(maj) .. '.' .. tostring(min)
145 .. ' < 3.4 detected -- --embed-bitmaps does not support'
146 .. ' dvisvgm:img in this version; bitmaps will remain as'
147 .. ' external file references.')
148 end
149 end
150 end
151 }
152 \fi
153 \if@anim@dvisvgm@old\else
154 %% dvisvgm >= 3.4 (or undetected): override \Ginclude@bitmap so that
155 %% --embed-bitmaps inlines bitmaps as base64 data URIs.
156 \def\Ginclude@bitmap#1{%
157 \special{dvisvgm:bbox \strip@pt\Gin@req@width pt \strip@pt\Gin@req@height pt transform}%
158 \hbox{%
159 \special{dvisvgm:img \strip@pt\Gin@req@width pt \strip@pt\Gin@req@height pt #1}%
160 }%
161 }%
162 \fi
163 \fi
164
165 %% ── Animation ────────────────────────────────────────────────────────────────
166 %%
167 %% /anim/.cd keys:
168 %%
169 %% duration=2 seconds per step (default)
170 %% active opacity=1 opacity when the step is active
171 %% inactive opacity=0 opacity when inactive (\reveal)
172 %%
173 \tikzset{
174 /anim/.cd,
175 duration/.initial = 2, %% seconds per step (default)
176 active opacity/.initial = 1, %% opacity when the step is active
177 inactive opacity/.initial = 0, %% opacity when inactive (\reveal)
178 blink on opacity/.initial = 1, %% opacity during blink "on" half-periods
179 blink off opacity/.initial = 0, %% opacity during blink "off" half-periods
180 noanimate/.code = { \@anim@reveal@statictrue },
181 %% force this \reveal to render in PDF even when
182 %% \noanimate is present in the animate body
183 loop/.is if = @anim@loop,
184 loop/.default = true,
185 %% true (default): animation loops indefinitely
186 %% false: animation plays once and freezes on the last frame
187 static/.code = { \csname @anim@envstatic#1\endcsname },
188 static/.default = true,
189 %% true: all \reveal render at full opacity (no animation)
190 %% shorthand for the "show all steps simultaneously" idiom
191 }
192
193 %% ── Epsilon for instantaneous opacity snaps ──────────────────────────────────
194 %%
195 %% SVG SMIL interpolates linearly between consecutive keyframes. To produce
196 %% an instantaneous jump (no cross-fade between steps), each transition is
197 %% represented as two keyframes separated by a very short interval:
198 %%
199 %% (t - ε) s = "old_value"
200 %% t s = "new_value"
201 %%
202 %% Without this gap, setting two keyframes at exactly the same time leaves the
203 %% transition behaviour implementation-defined: some SVG engines treat it as
204 %% instantaneous, others as undefined. The explicit ε makes the intent clear
205 %% and consistent across renderers.
206 %%
207 %% Why 0.001 s (1 ms)?
208 %%
209 %% • Perceptually invisible: at 60 fps one frame lasts ≈ 16.7 ms, so 1 ms is
210 %% well below the threshold of visibility even on high-refresh displays.
211 %% • Numerically safe: even for long animations (e.g. total = 3600 s) the
212 %% normalised keyTime (3600 − 0.001) / 3600 ≈ 0.999 999 7 is distinct
213 %% from 1.0 in double precision, so keyframes never collapse.
214 %% • Practical lower bound: values much smaller than 1 ms (e.g. 1 μs) could
215 %% be rounded away by some SVG renderers working in millisecond precision.
216 %%
217 %% Known limit: if a step duration is ≤ ε (e.g. duration=0.001) the epsilon
218 %% boundary equals or exceeds the step end, producing degenerate keyframes.
219 %% Such durations are not meaningful in practice.
220 %%
221 %% \anim@eps is a plain macro (expanded by \pgfmathsetmacro before evaluation).
222 %%
223 \def\anim@eps{0.001}
224
225 %% ════════════════════════════════════════════════════════════════════════════════
226 %% CATCODES — what they are, how they work, why they matter here
227 %% ════════════════════════════════════════════════════════════════════════════════
228 %%
229 %% ── What is a catcode? ────────────────────────────────────────────────────────
230 %%
231 %% TeX reads the source file one character at a time. Before it can interpret
232 %% anything — before it knows whether '{' opens a group or '$' switches to maths
233 %% — it must assign a *syntactic role* to every character it reads. That role
234 %% is the **category code** (catcode), an integer from 0 to 15.
235 %%
236 %% Each character has exactly one catcode at any given moment. The full table:
237 %%
238 %% 0 escape \ begins a control sequence name
239 %% 1 begin-group { opens a TeX group
240 %% 2 end-group } closes a TeX group
241 %% 3 math-shift $ enters/exits math mode
242 %% 4 alignment & column separator in tabular/array/…
243 %% 5 end-of-line ↵ treated as a space (or ignored, depending on state)
244 %% 6 parameter # introduces a macro argument: #1, #2, …
245 %% 7 superscript ^ exponent in math mode
246 %% 8 subscript _ subscript in math mode (also used by expl3)
247 %% 9 ignored (none) character is discarded, produces no token
248 %% 10 space ⎵ \t produces a space token (multiple → one)
249 %% 11 letter a-z A-Z part of a control-sequence name
250 %% 12 other @ ! 1 ;… produces a "character token", NOT part of a name
251 %% 13 active ~ the character itself IS a macro (one-token command)
252 %% 14 comment % discards from here to end of line
253 %% 15 invalid (rare) triggers an error if encountered
254 %%
255 %% ── The critical rule: control-sequence names ────────────────────────────────
256 %%
257 %% When TeX reads '\', it scans subsequent characters to build a name.
258 %% It keeps reading as long as characters have catcode 11 (letter), and stops
259 %% at the first character with any other catcode.
260 %%
261 %% Source Catcodes of a,n,i,m,… Result
262 %% ────────────── ──────────────────────── ─────────────────────────────────────
263 %% \animstep all 11 one token: control sequence \animstep
264 %% \animstep{x} all 11, then { = cc 1 \animstep + \bgroup + x + \egroup
265 %% \@anim@foo @ = cc 12 \@ + anim + @ + foo (FOUR tokens!)
266 %% \@anim@foo @ = cc 11 one token: \@anim@foo ✓
267 %%
268 %% This is the entire reason \makeatletter exists: it changes '@' from catcode 12
269 %% to 11, allowing names like \if@anim@svgmode to be single tokens.
270 %% In a .sty file '@' is *always* catcode 11 (LaTeX sets it automatically before
271 %% loading any package), so \makeatletter is never needed in a .sty.
272 %%
273 %% ── Tokenisation is final ─────────────────────────────────────────────────────
274 %%
275 %% TeX converts the character stream into tokens exactly ONCE, when it reads each
276 %% line. A token is a pair (character-code, catcode) and is immutable thereafter.
277 %% Changing a catcode later has no effect on tokens already read.
278 %%
279 %% The processing pipeline is:
280 %%
281 %% Source file characters
282 %% │
283 %% ▼ catcodes applied HERE — one pass, irreversible
284 %% Token stream (each token carries its catcode permanently)
285 %% │
286 %% ▼
287 %% Macro expansion (tokens substituted according to \def rules)
288 %% │
289 %% ▼
290 %% TeX execution (grouping, typesetting, conditionals, …)
291 %%
292 %% Consequence: a \def whose body contains a space token (catcode 10) will
293 %% always carry that space token when the macro expands — even if the macro
294 %% is *called* inside an \ExplSyntaxOn block where spaces are catcode 9.
295 %% The body was tokenised at definition time (outside \ExplSyntaxOn), so the
296 %% space token is already baked in. This is exactly the technique used by the
297 %% wrapper macros \@anim@get@active@opacity below.
298 %%
299 %% ── What \ExplSyntaxOn changes ────────────────────────────────────────────────
300 %%
301 %% expl3 (the modern LaTeX programming layer) needs its own naming conventions:
302 %% function names like \__anim_reveal_multistep:n embed '_' and ':' as
303 %% structural separators. To make those characters legal inside names,
304 %% \ExplSyntaxOn reassigns four catcodes:
305 %%
306 %% character normal catcode inside \ExplSyntaxOn effect
307 %% ─────────── ──────────────── ───────────────────── ──────────────────────────
308 %% _ 8 (subscript) 11 (letter) part of a cs name
309 %% : 12 (other) 11 (letter) part of a cs name
310 %% space 10 (space) 9 (ignored) source whitespace ignored
311 %% ~ 13 (active) 10 (space) explicit space substitute
312 %%
313 %% \ExplSyntaxOn does NOT touch '@', '#', '{', '}', or any other character.
314 %%
315 %% The space→9 and :→11 changes are the source of the three pitfalls documented
316 %% below. Each pitfall arises because some LaTeX2e/pgf mechanism was designed
317 %% assuming the *normal* catcodes for those characters.
318 %%
319 %% ════════════════════════════════════════════════════════════════════════════════
320 %%
321 %% ── PITFALL A — pgfkeys paths with internal spaces inside \ExplSyntaxOn ───────
322 %%
323 %% \ExplSyntaxOn changes the catcode of the space character from 10 (space)
324 %% to 9 (ignored). This is intentional: it lets expl3 code be written with
325 %% generous whitespace for readability, and that whitespace is silently dropped
326 %% during tokenisation rather than producing spurious space tokens.
327 %%
328 %% The consequence is that ANY space literal written in the SOURCE inside an
329 %% \ExplSyntaxOn block is discarded at tokenisation time — before any macro
330 %% expansion or execution takes place.
331 %%
332 %% pgfkeys stores and looks up keys by their *exact* path string, including any
333 %% spaces that are part of the key name. The keys declared in this package are:
334 %%
335 %% /anim/active opacity ← space is part of the key name
336 %% /anim/inactive opacity ← idem
337 %%
338 %% Inside \ExplSyntaxOn, writing:
339 %%
340 %% \pgfkeysvalueof{/anim/active opacity}
341 %%
342 %% causes the space between "active" and "opacity" to be catcode 9 at the
343 %% moment the source is tokenised. TeX therefore never sees a space token
344 %% there; instead it reads the path string as "/anim/activeopacity" — a key
345 %% that has never been declared.
346 %%
347 %% The failure mode is NOT obvious:
348 %% - No "undefined key" warning is emitted by pgfkeys in this context.
349 %% - The undefined key returns an empty string.
350 %% - That empty string is then passed to \pgfmathsetmacro, which tries to
351 %% evaluate it as an arithmetic expression.
352 %% - pgfmath fails internally on an empty expression, producing:
353 %% ! Undefined control sequence: \pgfmath@dimen@
354 %% which points into the depths of the pgfmath internals and gives no hint
355 %% about the real cause (a missing space in a key path).
356 %%
357 %% Fix: define wrapper macros HERE, outside \ExplSyntaxOn, so the space token
358 %% in "/anim/active opacity" is tokenised at catcode 10 (normal) and baked
359 %% permanently into the macro body. Calling the wrapper from inside
360 %% \ExplSyntaxOn is safe because TeX expands the macro body, not the source
361 %% text — the space token stored in the body retains its original catcode 10.
362 %%
363 \def\@anim@get@active@opacity{\pgfkeysvalueof{/anim/active opacity}}
364 \def\@anim@get@inactive@opacity{\pgfkeysvalueof{/anim/inactive opacity}}
365 \def\@anim@get@blink@on@opacity{\pgfkeysvalueof{/anim/blink on opacity}}
366 \def\@anim@get@blink@off@opacity{\pgfkeysvalueof{/anim/blink off opacity}}
367
368 %% ── PITFALL B — TikZ animation-spec parser requires ':' at catcode 12 ─────────
369 %%
370 %% \ExplSyntaxOn also changes the catcode of ':' from 12 (other) to 11 (letter).
371 %% This allows ':' to appear in expl3 function names as a separator between the
372 %% base name and the argument signature, e.g. \__anim_reveal_multistep:n.
373 %%
374 %% TikZ's animation library (tikzlibraryanimations.code.tex) parses the
375 %% animate= key value using the following idiom to locate the ':' separator
376 %% between the target entity and the attribute:
377 %%
378 %% \expandafter\pgfutil@in@\expandafter:\expandafter{\tikz@key}
379 %%
380 %% \pgfutil@in@ performs a token-level search: it looks for a token whose
381 %% *character code AND catcode* both match the searched-for token. The ':'
382 %% hardcoded in the source above has catcode 12 (it was tokenised outside any
383 %% \ExplSyntaxOn block). A ':' that was tokenised inside \ExplSyntaxOn carries
384 %% catcode 11 — a different token — and is NOT found by \pgfutil@in@.
385 %%
386 %% Consequence: if the macro body
387 %%
388 %% \begin{scope}[animate={myself : opacity = {#1}}]
389 %%
390 %% is tokenised inside \ExplSyntaxOn, the ':' in "myself : opacity" becomes
391 %% catcode 11. TikZ's parser then fails to find the entity:attribute boundary,
392 %% the spec is not recognised, and control falls through to an error path deep
393 %% inside pgfmath:
394 %%
395 %% ! Undefined control sequence: \pgfmath@dimen@
396 %%
397 %% (same symptom as Pitfall A — completely unrelated-looking error).
398 %%
399 %% Fix: define this helper macro BEFORE \ExplSyntaxOn so that ':' in the macro
400 %% body is tokenised at catcode 12. The function uses an expl3-style name
401 %% (__anim_emit_mf_scope:nn) which normally requires ':' to be catcode 11.
402 %% We resolve this tension with \csname...\endcsname: that construct assembles
403 %% a control-sequence name from arbitrary character tokens regardless of their
404 %% catcodes, so we can write the name without needing ':' or '_' to be letters.
405 %%
406 %% Why \long?
407 %%
408 %% Argument #2 is the raw TikZ content of a \reveal{...} block. Users may
409 %% write blank lines inside a \reveal for readability:
410 %%
411 %% \reveal{
412 %%
413 %% \draw ...;
414 %% \node ...;
415 %% }
416 %%
417 %% A blank line produces a \par token in the token stream. TeX normally
418 %% forbids \par inside macro arguments: if a macro is not declared \long,
419 %% scanning for its argument stops at the first \par and raises:
420 %%
421 %% ! Paragraph ended before <macro> was complete.
422 %%
423 %% All callers up the chain (\reveal uses +m, expl3 functions are implicitly
424 %% long) already accept \par — this macro is the only non-expl3 link in the
425 %% chain, so \long must be declared here explicitly.
426 %%
427 %% The \long prefix is placed before the \expandafter chain. TeX sets the
428 %% long-flag when it reads \long and the flag persists through the two
429 %% \expandafter expansions that resolve \csname...\endcsname, so the final
430 %% definition is effectively \long\protected\def <cs>#1#2{...}.
431 %%
432 \long\expandafter\protected\expandafter\def
433 \csname __anim_emit_mf_scope:nn\endcsname#1#2{%
434 \begin{scope}[animate={myself : opacity = {#1}}]%
435 #2%
436 \end{scope}%
437 }%
438
439 %% ── High-level animate environment ───────────────────────────────────────────
440 %%
441 %% ── The problem ──────────────────────────────────────────────────────────────
442 %%
443 %% Each \reveal needs to know its own window of activity as absolute times:
444 %%
445 %% step 1 active from 0 s to 1 s (out of 3 s total)
446 %% step 2 active from 1 s to 2 s
447 %% step 3 active from 2 s to 3 s
448 %%
449 %% But to compute those numbers we first need to know the total duration —
450 %% and we are still in the middle of reading the body. A naive single pass
451 %% cannot work because we must know the total before we emit any keyframe.
452 %%
453 %% ── Step 1: collect the whole body without executing it (+b) ─────────────────
454 %%
455 %% The +b argument spec in \NewDocumentEnvironment tells LaTeX to grab
456 %% everything up to \end{animate} as a single token list (#2) and hand it
457 %% to us verbatim, without executing a single command inside it.
458 %% Given:
459 %%
460 %% \begin{animate}[duration=1]
461 %% \reveal{\node (vm1)...}
462 %% \animstep
463 %% \reveal{\node (vm2)...}
464 %% \animstep[duration=3]
465 %% \reveal{\node (vm3)...}
466 %% \end{animate}
467 %%
468 %% #2 is the raw token sequence:
469 %% \reveal{\node (vm1)...} \animstep \reveal{\node (vm2)...}
470 %% \animstep[duration=3] \reveal{\node (vm3)...}
471 %%
472 %% ── Step 2: split into per-step segments ─────────────────────────────────────
473 %%
474 %% \seq_set_split:Nnn cuts #2 everywhere the token \animstep appears,
475 %% producing a sequence of three token lists (still not executed):
476 %%
477 %% seg 1: \reveal{\node (vm1)...}
478 %% seg 2: \reveal{\node (vm2)...}
479 %% seg 3: [duration=3] \reveal{\node (vm3)...} <- note the leading [opts]
480 %%
481 %% The \animstep tokens themselves are consumed as delimiters and discarded.
482 %%
483 %% ── Step 3: peel off per-step [opts] ─────────────────────────────────────────
484 %%
485 %% When the user writes \animstep[duration=3], the [duration=3] tokens end
486 %% up at the front of the next segment (seg 3 above). Before we can use
487 %% the segment content as TikZ code we must extract those options first.
488 %% \__anim_pop_opts:NN does this with a regex: if the segment starts with
489 %% [...], it captures the content and strips it from the token list.
490 %%
491 %% ── Step 4 (pass 1): sum up the total duration ───────────────────────────────
492 %%
493 %% We iterate over all segments without executing their TikZ content.
494 %% For each segment we temporarily apply its options inside a TeX group
495 %% (so they don't spill into the next step) and read /anim/duration.
496 %% After the loop: total = 1 + 1 + 3 = 5 s.
497 %%
498 %% ── Step 5 (pass 2): render each step with the correct timing ─────────────────
499 %%
500 %% We iterate again, this time executing each segment's TikZ code.
501 %% Before executing, we set three global FP variables:
502 %% \g__anim_step_start_fp e.g. 2.0
503 %% \g__anim_step_end_fp e.g. 5.0
504 %% \g__anim_total_fp 5.0 (constant across all steps)
505 %%
506 %% When \reveal{...} runs inside the segment, it reads those globals and
507 %% passes them to \__anim_reveal_simple:n, which emits the SVG opacity keyframes.
508 %% After execution, start advances to end, ready for the next step.
509 %%
510 %% ── User interface ────────────────────────────────────────────────────────────
511 %%
512 %% \begin{animate}[options]
513 %% \reveal[opts]{...} active opacity when active, inactive opacity otherwise
514 %% \animstep[opts] step separator; opts apply to all elements of this step
515 %% ...
516 %% \end{animate}
517 %%
518 %% Options cascade: animate-level → \animstep-level → per-element.
519 %% Inner options override outer ones.
520 %%
521 %% /anim/.cd keys:
522 %% duration=2 seconds per step
523 %% active opacity=1 opacity when active
524 %% inactive opacity=0 opacity when inactive (0=hidden, >0=dimmed)
525 %% blink on opacity=1 opacity during blink "on" half-periods within active step
526 %% blink off opacity=0 opacity during blink "off" half-periods within active step
527 %% (between steps the element uses inactive opacity as usual)
528 %% static render all \reveal at full opacity (no animation)
529 %%
530 %% Note: 'duration' on \reveal is accepted but silently ignored.
531 %%
532 %% Global defaults:
533 %% \tikzset{/anim/duration=2}
534 %% \tikzset{/anim/inactive opacity=0.3}
535 %%
536 %% ── PITFALL C — \ExplSyntaxOn does NOT change the catcode of '@' ──────────────
537 %%
538 %% \ExplSyntaxOn modifies exactly four catcodes: '_' (11), ':' (11),
539 %% space (9), '~' (10). It deliberately leaves '@' unchanged.
540 %%
541 %% In a .sty file this is a non-issue: LaTeX sets '@' to catcode 11
542 %% (letter) before loading any package and restores it afterwards.
543 %% So '@' is always catcode 11 throughout a .sty file, even inside
544 %% \ExplSyntaxOn, with no \makeatletter needed.
545 %%
546 %% In a .tex document the situation is different: '@' is normally
547 %% catcode 12 (other) outside \makeatletter...\makeatother blocks.
548 %% If a user writes \ExplSyntaxOn directly in a .tex file without a
549 %% preceding \makeatletter, '@' stays catcode 12. Then:
550 %%
551 %% \if@anim@svgmode → \if @ a n i m @ s v g m o d e
552 %% ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
553 %% \if primitive individual "other" tokens
554 %%
555 %% TeX executes \if (primitive token comparison) instead of the boolean
556 %% flag set by \newif. The two tokens compared are '@' (catcode 12) and
557 %% 'a' (catcode 11) — different, so \if is ALWAYS false. SVG mode is
558 %% silently disabled with no error.
559 %%
560 %% This pitfall does not affect this package (we are in a .sty), but it
561 %% would affect any .tex file that mixes \ExplSyntaxOn with @-names.
562 %%
563 \ExplSyntaxOn
564
565 %% ── expl3 naming conventions ─────────────────────────────────────────────────
566 %%
567 %% expl3 is the modern LaTeX programming layer. Everything follows a strict
568 %% naming scheme that encodes type, scope, and module in the name itself.
569 %%
570 %% Data types (prefix before the first _):
571 %% \fp_... floating-point scalar (decimal arithmetic)
572 %% \seq_... ordered list of items
573 %% \tl_... token list (an arbitrary chunk of LaTeX code stored as a value)
574 %%
575 %% Scope and visibility (prefix of the variable name after the type):
576 %% \g__anim_... global variable, private to this module (__ = private)
577 %% \l__anim_... local variable, private to this module
578 %% Global variables persist across TeX groups; local ones are restored.
579 %%
580 %% Function signatures (suffix after the last :):
581 %% :N one unbraced token argument e.g. \fp_new:N \myfp
582 %% :Nn one token + one braced argument e.g. \tl_set:Nn \mytl {hello}
583 %% :Ne token + e-expanded braced arg (content fully expanded before use)
584 %% :NV token + V-expanded arg (variable replaced by its value)
585 %% :NTF token + true branch + false branch (conditional)
586
587 %% Absolute timing of the step currently being rendered (seconds).
588 %% Set by animate before executing each step's content; read by \reveal.
589 \fp_new:N \g__anim_step_start_fp %% start time of the active step
590 \fp_new:N \g__anim_step_end_fp %% end time of the active step
591 \fp_new:N \g__anim_total_fp %% total animation duration (all steps summed)
592 \fp_new:N \g__anim_step_dur_fp %% scratch: duration of the current step
593
594 %% List of per-step token lists produced by splitting the body at \animstep.
595 \seq_new:N \l__anim_steps_seq
596 \seq_new:N \l__anim_pop_seq %% scratch: regex capture groups
597
598 %% Scratch token lists used inside the animate loops.
599 \tl_new:N \l__anim_step_opts_tl %% options extracted from \animstep[...]
600 \tl_new:N \l__anim_seg_tl %% one step's body (copy, modified in place)
601 \tl_new:N \l__anim_dur_tl %% string value of /anim/duration for FP arithmetic
602
603 %% True when the current animate body contains at least one \noanimate token.
604 %% Set by the animate environment before pass 2; checked by \reveal in PDF mode.
605 %% When true: \reveal is suppressed in PDF and \noanimate provides the static content.
606 %% When false: \reveal renders normally in PDF (all steps stacked, legacy behaviour).
607 \bool_new:N \g__anim_has_noanimate_bool
608
609 %% Per-step timing table: item N (1-based) = "start/end" decimal string.
610 %% Populated during pass 1; read by \__anim_reveal_multistep:n.
611 \seq_new:N \g__anim_step_times_seq
612 %% Running time cursor used during pass 1 to build \g__anim_step_times_seq.
613 \fp_new:N \g__anim_cursor_fp
614
615 %% Blink period for the current \reveal call (0 = no blink).
616 %% Set by the /anim/blink key; reset to 0 at the top of each \reveal group.
617 \fp_new:N \l__anim_blink_period_fp
618 \fp_new:N \l__anim_blink_h_fp %% scratch: half-period = blink_period / 2
619
620 %% step= spec for the current \reveal call (empty = use current step).
621 %% Set by the /anim/step key; cleared at the top of each \reveal group.
622 \tl_new:N \l__anim_step_spec_tl
623 %% The /anim/step key must be declared here (inside \ExplSyntaxOn) so that
624 %% _ and : carry expl3 catcodes when the .code value is tokenised.
625 \tikzset{
626 /anim/step/.code = { \tl_set:Nn \l__anim_step_spec_tl { #1 } },
627 /anim/blink/.code = { \fp_set:Nn \l__anim_blink_period_fp { #1 } },
628 }
629
630 %% Generate the nVNTF variant of \regex_extract_once to allow passing the
631 %% search string as a tl variable (V-expansion) rather than a literal brace group.
632 \cs_generate_variant:Nn \regex_extract_once:nnNTF { nVNTF }
633
634 %% \int_step_inline:nnnn loops {start}{step}{stop}{body}.
635 %% The 'eeen' variant e-expands start, step, stop so \seq_item:Nn results are
636 %% evaluated before the loop begins; the body is passed as-is.
637 \cs_generate_variant:Nn \int_step_inline:nnnn { eeen }
638
639 %% Scratch variables used by \__anim_reveal_multistep:n.
640 \seq_new:N \l__anim_windows_seq %% raw "start/end" windows, one per step
641 \seq_new:N \l__anim_merged_seq %% merged windows (adjacent steps collapsed)
642 \seq_new:N \l__anim_step_items_seq %% items split from frame spec on ","
643 \seq_new:N \l__anim_match_seq %% regex capture groups
644 \tl_new:N \l__anim_kf_tl %% keyframe token list being built
645 \tl_new:N \l__anim_ws_tl %% scratch: window start time string
646 \tl_new:N \l__anim_we_tl %% scratch: window end time string
647 \tl_new:N \l__anim_mstart_tl %% scratch: current merged window start
648 \tl_new:N \l__anim_mend_tl %% scratch: current merged window end
649 \tl_new:N \l__anim_next_tl %% scratch: next window string
650 \bool_new:N \l__anim_merge_bool %% scratch: true = active merged window exists
651
652 %% \animstep[options] — step delimiter; [options] apply to all elements of the next step.
653 %% When inside animate its body is collected verbatim (+b) so \animstep is consumed as
654 %% a split token by \seq_set_split and never actually executed — the error check below
655 %% can therefore only fire when \animstep is (incorrectly) used outside animate.
656 \NewDocumentCommand \animstep { } {
657 \if@anim@inside \else
658 \PackageError{svg-animate}
659 {\string\animstep\space used outside animate environment}
660 {%
661 \string\animstep\space is a step separator and only makes sense%
662 \MessageBreak inside \string\begin{animate}...\string\end{animate}.%
663 }%
664 \fi
665 }
666
667 %% \__anim_pop_opts:NN {#1} {#2}
668 %% Extract a leading [opts] group from token list variable #2 into #1.
669 %% If #2 starts with [...] (after trimming spaces), #1 receives the content
670 %% between the brackets and the [...] is removed from #2.
671 %% If there is no leading [...], #1 is cleared and #2 is left unchanged.
672 %%
673 %% The regex \A \[ ([^\]]*) \] means:
674 %% \A start of string
675 %% \[ literal [
676 %% ([^\]]*) capture group: any characters except ]
677 %% \] literal ]
678 \cs_new_protected:Npn \__anim_pop_opts:NN #1 #2 {
679 \tl_trim_spaces:N #2 %% remove surrounding spaces
680 \regex_extract_once:nVNTF { \A \[ ([^\]]*) \] } #2 \l__anim_pop_seq {
681 %% Match found: capture group 2 holds the content between [ and ]
682 \tl_set:Ne #1 { \seq_item:Nn \l__anim_pop_seq { 2 } } %% #1 = captured opts
683 \regex_replace_once:nnN { \A \[ [^\]]* \] } { } #2 %% strip [...] from #2
684 \tl_trim_spaces:N #2 %% trim again after strip
685 } {
686 \tl_clear:N #1 %% no match: #1 = empty
687 }
688 }
689
690 %% \__anim_reveal_multistep:n {content}
691 %% Called by \reveal when the step= key is set.
692 %% Reads \l__anim_step_spec_tl for the step specification (e.g. "2,5-8,10"),
693 %% looks up per-step timings from \g__anim_step_times_seq, merges adjacent
694 %% windows, then emits a single TikZ scope with multi-window SMIL keyframes.
695 %%
696 %% Step timings are stored as "start/end" decimal strings (e.g. "1.5/2.0").
697 %% Steps are 1-based.
698 %%
699 \cs_new_protected:Npn \__anim_reveal_multistep:n #1 {
700 %% ── 1. Parse frame spec → raw windows sequence ───────────────────────────
701 %% Split "2,5-8,10" on "," into items; expand each range into individual steps;
702 %% look up each step's "start/end" timing from \g__anim_step_times_seq.
703 \seq_clear:N \l__anim_windows_seq
704 \seq_set_split:NnV \l__anim_step_items_seq { , } \l__anim_step_spec_tl
705 \seq_map_inline:Nn \l__anim_step_items_seq {
706 \regex_extract_once:nnNTF
707 { \A \s* (\d+) \s* \- \s* (\d+) \s* \Z }
708 { ##1 } \l__anim_match_seq
709 {
710 %% ── PITFALL D — '#' doubling in nested inline functions ──────────────────
711 %%
712 %% In a standard LaTeX macro definition, '#1' refers to the first argument.
713 %% When one macro definition is *nested inside* another, every '#' must be
714 %% doubled to reach the intended nesting level, because TeX halves the count
715 %% of '#' characters each time it processes a definition body.
716 %%
717 %% The nesting here is three levels deep:
718 %%
719 %% Level 0 — \cs_new_protected:Npn \__anim_reveal_multistep:n #1 { ... }
720 %% Parameter: #1 = TikZ content
721 %%
722 %% Level 1 — \seq_map_inline:Nn \l__anim_step_items_seq { ... ##1 ... }
723 %% Inline function body; ##1 = current step spec item (e.g. "5-8").
724 %% TeX reduces '##' → '#' when scanning the level-0 body,
725 %% so '##1' in the source becomes '#1' at run time.
726 %%
727 %% Level 2 — \int_step_inline:eeen { }{ }{ }{ ... ####1 ... }
728 %% Inline function nested inside the seq_map body.
729 %% We need the step counter to appear as '#1' inside this body
730 %% at run time. Working backwards:
731 %% - level 1 reduces '##' → '#', so we need '##1' to survive
732 %% level 1; that means we must write '##1' at level 1.
733 %% - But we are *writing inside* level 0, so level 0 will also
734 %% halve our '#' count. To have '##1' survive level 0 we
735 %% must write '####1' in the source.
736 %% Reduction chain: ####1 →(L0)→ ##1 →(L1)→ #1 ✓
737 %%
738 %% General rule: N levels of inline nesting → 2^N '#' signs in source.
739 %%
740 %% N=1: ##1 (one seq_map_inline or one int_step_inline, standalone)
741 %% N=2: ####1 (seq_map_inline → int_step_inline, as here)
742 %% N=3: ########1
743 %%
744 %% Using the wrong count silently produces the WRONG value with no error:
745 %% '##1' at level 2 would evaluate to the seq_map's loop variable, i.e. the
746 %% current step spec item ("5-8"), not the numeric step counter.
747 %% \seq_item:Nn with a string index falls back to item 0 (empty), so every
748 %% step in the range would get an empty timing string and produce garbage
749 %% keyTimes in the SVG without any TeX diagnostic.
750 %%
751 %% \int_step_inline:nnnn {start}{step}{stop}{body} — four arguments.
752 %% The 'eeen' variant e-expands arguments 1, 2, 3 before starting the loop,
753 %% so \seq_item:Nn \l__anim_match_seq { 2 } is evaluated once to the integer
754 %% string (e.g. "5") rather than being re-evaluated on every iteration.
755 %% Argument 4 (the body) is not expanded — it contains '####1' which must
756 %% remain as literal parameter tokens until the loop executes.
757 %%
758 %% Validate range bounds before looping.
759 %% \l_tmpa_int = range start (A), \l_tmpb_int = range end (B).
760 %% All three error conditions are checked independently so the user
761 %% sees every problem in a single compilation pass.
762 \int_set:Nn \l_tmpa_int { \seq_item:Nn \l__anim_match_seq { 2 } }
763 \int_set:Nn \l_tmpb_int { \seq_item:Nn \l__anim_match_seq { 3 } }
764 \int_compare:nNnT { \l_tmpa_int } > { \l_tmpb_int } {
765 \PackageError{svg-animate}
766 {step=~range~(\int_use:N\l_tmpa_int-\int_use:N\l_tmpb_int)~is~invalid:~start~must~be~<=~end}
767 {The~start~of~a~range~must~be~<=~its~end.}
768 }
769 \int_compare:nNnT { \l_tmpa_int } < { 1 } {
770 \PackageError{svg-animate}
771 {step=~range~start~(\int_use:N\l_tmpa_int)~is~out~of~range~(steps~start~at~1)}
772 {The~step=~key~accepts~positive~integers~only.}
773 }
774 \int_compare:nNnT { \l_tmpb_int } > { \seq_count:N \g__anim_step_times_seq } {
775 \PackageError{svg-animate}
776 {step=~range~end~(\int_use:N\l_tmpb_int)~exceeds~the~number~of~steps~(\seq_count:N\g__anim_step_times_seq)}
777 {This~animate~environment~has~\seq_count:N\g__anim_step_times_seq~
778 step(s),~numbered~1~to~\seq_count:N\g__anim_step_times_seq.}
779 }
780 \int_step_inline:eeen
781 { \seq_item:Nn \l__anim_match_seq { 2 } }
782 { 1 }
783 { \seq_item:Nn \l__anim_match_seq { 3 } }
784 { \seq_put_right:Ne \l__anim_windows_seq
785 { \seq_item:Nn \g__anim_step_times_seq { ####1 } } }
786 } {
787 %% Single step: validate then look up timing.
788 %% \l_tmpa_int holds the step number for use in error messages.
789 \tl_set:Ne \l__anim_dur_tl { \tl_trim_spaces:n { ##1 } }
790 \int_set:Nn \l_tmpa_int { \l__anim_dur_tl }
791 \int_compare:nNnT { \l_tmpa_int } < { 1 } {
792 \PackageError{svg-animate}
793 {step=~value~(\int_use:N\l_tmpa_int)~is~out~of~range~(steps~start~at~1)}
794 {The~step=~key~accepts~positive~integers~only.}
795 }
796 \int_compare:nNnTF { \l_tmpa_int } > { \seq_count:N \g__anim_step_times_seq } {
797 \PackageError{svg-animate}
798 {step=~value~(\int_use:N\l_tmpa_int)~exceeds~the~number~of~steps~(\seq_count:N\g__anim_step_times_seq)}
799 {This~animate~environment~has~\seq_count:N\g__anim_step_times_seq~
800 step(s),~numbered~1~to~\seq_count:N\g__anim_step_times_seq.}
801 } {
802 \seq_put_right:Ne \l__anim_windows_seq
803 { \seq_item:Nn \g__anim_step_times_seq { \l__anim_dur_tl } }
804 }
805 }
806 }
807
808 %% ── 2. Merge adjacent windows ─────────────────────────────────────────────
809 %% Consecutive steps share a boundary (step N end == step N+1 start).
810 %% Keeping them separate would produce conflicting keyframes at the junction,
811 %% so we merge them into a single window: [step_A_start, step_B_end].
812 \seq_clear:N \l__anim_merged_seq
813 \bool_set_false:N \l__anim_merge_bool
814 \seq_map_inline:Nn \l__anim_windows_seq {
815 \regex_extract_once:nnNTF
816 { \A ([0-9.]+) \/ ([0-9.]+) \Z }
817 { ##1 } \l__anim_match_seq
818 {
819 \tl_set:Ne \l__anim_ws_tl { \seq_item:Nn \l__anim_match_seq { 2 } }
820 \tl_set:Ne \l__anim_we_tl { \seq_item:Nn \l__anim_match_seq { 3 } }
821 \bool_if:NTF \l__anim_merge_bool {
822 \tl_if_eq:NNTF \l__anim_mend_tl \l__anim_ws_tl {
823 %% Adjacent: extend the current merged window
824 \tl_set_eq:NN \l__anim_mend_tl \l__anim_we_tl
825 } {
826 %% Gap: flush current window and start a new one
827 \seq_put_right:Ne \l__anim_merged_seq
828 { \l__anim_mstart_tl / \l__anim_mend_tl }
829 \tl_set_eq:NN \l__anim_mstart_tl \l__anim_ws_tl
830 \tl_set_eq:NN \l__anim_mend_tl \l__anim_we_tl
831 }
832 } {
833 %% First window ever
834 \bool_set_true:N \l__anim_merge_bool
835 \tl_set_eq:NN \l__anim_mstart_tl \l__anim_ws_tl
836 \tl_set_eq:NN \l__anim_mend_tl \l__anim_we_tl
837 }
838 } { }
839 }
840 \bool_if:NT \l__anim_merge_bool {
841 \seq_put_right:Ne \l__anim_merged_seq
842 { \l__anim_mstart_tl / \l__anim_mend_tl }
843 }
844
845 %% ── 3. Build SMIL keyframe token list ────────────────────────────────────
846 %% Opacity values and total duration (same pgfmathsetmacro idiom as \__anim_reveal_simple:n).
847 \pgfmathsetmacro\animft@opA { \@anim@get@active@opacity }
848 \pgfmathsetmacro\animft@opI { \@anim@get@inactive@opacity }
849 %% Pre-expand \fp_to_decimal:N into a plain decimal string before pgfmath sees it,
850 %% because pgfmath cannot call expl3 functions that take arguments.
851 \tl_set:Ne \l__anim_dur_tl { \fp_to_decimal:N \g__anim_total_fp }
852 \pgfmathsetmacro\animft@totale { \l__anim_dur_tl - \anim@eps }
853 \tl_clear:N \l__anim_kf_tl
854
855 %% Initial keyframe at t=0: active if first window starts at 0, else inactive.
856 \tl_set:Ne \l__anim_ws_tl {
857 \seq_item:Nn \l__anim_merged_seq { 1 }
858 }
859 \regex_extract_once:nVNTF
860 { \A ([0-9.]+) \/ }
861 \l__anim_ws_tl \l__anim_match_seq
862 {
863 \tl_set:Ne \l__anim_ws_tl { \seq_item:Nn \l__anim_match_seq { 2 } }
864 \fp_compare:nNnTF { \l__anim_ws_tl } = { 0 } {
865 \tl_put_right:Ne \l__anim_kf_tl { 0s = "\animft@opA", }
866 } {
867 \pgfmathsetmacro\animft@wse { \l__anim_ws_tl - \anim@eps }
868 \tl_put_right:Ne \l__anim_kf_tl {
869 0s = "\animft@opI",
870 \animft@wse s = "\animft@opI",
871 \l__anim_ws_tl s = "\animft@opA",
872 }
873 }
874 } { }
875
876 %% Per-window end keyframes, plus inter-window transitions where needed.
877 \int_step_inline:nn { \seq_count:N \l__anim_merged_seq } {
878 \tl_set:Ne \l__anim_seg_tl { \seq_item:Nn \l__anim_merged_seq { ##1 } }
879 \regex_extract_once:nVNTF
880 { \A ([0-9.]+) \/ ([0-9.]+) \Z }
881 \l__anim_seg_tl \l__anim_match_seq
882 {
883 \tl_set:Ne \l__anim_ws_tl { \seq_item:Nn \l__anim_match_seq { 2 } }
884 \tl_set:Ne \l__anim_we_tl { \seq_item:Nn \l__anim_match_seq { 3 } }
885 \pgfmathsetmacro\animft@wee { \l__anim_we_tl - \anim@eps }
886 %% Snap off at window end
887 \tl_put_right:Ne \l__anim_kf_tl {
888 \animft@wee s = "\animft@opA",
889 \l__anim_we_tl s = "\animft@opI",
890 }
891 %% Transition to next window if there is one
892 \int_compare:nNnT { ##1 } < { \seq_count:N \l__anim_merged_seq } {
893 \tl_set:Ne \l__anim_next_tl
894 { \seq_item:Nn \l__anim_merged_seq { ##1 + 1 } }
895 \regex_extract_once:nVNTF
896 { \A ([0-9.]+) \/ }
897 \l__anim_next_tl \l__anim_match_seq
898 {
899 \tl_set:Ne \l__anim_ws_tl { \seq_item:Nn \l__anim_match_seq { 2 } }
900 \pgfmathsetmacro\animft@wse { \l__anim_ws_tl - \anim@eps }
901 \tl_put_right:Ne \l__anim_kf_tl {
902 \animft@wse s = "\animft@opI",
903 \l__anim_ws_tl s = "\animft@opA",
904 }
905 } { }
906 }
907 } { }
908 }
909 %% Stay inactive until end; append repeats unless loop=false.
910 \tl_put_right:Ne \l__anim_kf_tl { \animft@totale s = "\animft@opI" }
911 \if@anim@loop \tl_put_right:Nn \l__anim_kf_tl { ,repeats, } \fi
912
913 %% ── 4. Emit TikZ scope with assembled keyframes ───────────────────────────
914 %% \__anim_emit_mf_scope:Vn expands \l__anim_kf_tl to its string value before
915 %% passing it to the scope, ensuring TikZ receives literal keyframe tokens.
916 \__anim_emit_mf_scope:Vn \l__anim_kf_tl { #1 }
917 }
918
919 %% :Vn variant: value-expands \l__anim_kf_tl before passing it as #1,
920 %% guaranteeing the keyframe token list is fully resolved when TikZ
921 %% processes the animate= key.
922 \cs_generate_variant:Nn \__anim_emit_mf_scope:nn { Vn }
923
924 %% \__anim_reveal_simple:n {content}
925 %% Called by \reveal when neither blink= nor step= is set.
926 %% Builds the keyframe token list
927 %% entirely in expl3 (using \tl_set:Ne + \if@anim@loop outside the spec) before
928 %% passing it to TikZ via \__anim_emit_mf_scope:Vn.
929 %%
930 %% This avoids the "doesn't match its definition" error caused by putting
931 %% \if@anim@loop or any not-fully-expanded macro inside the animate={} spec.
932 %%
933 \cs_new_protected:Npn \__anim_reveal_simple:n #1 {
934 %% Opacity values (wrappers defined before \ExplSyntaxOn — PITFALL A)
935 \pgfmathsetmacro\animft@opA { \@anim@get@active@opacity }
936 \pgfmathsetmacro\animft@opI { \@anim@get@inactive@opacity }
937 %% Pre-expand FP globals to decimal strings before pgfmath sees them (PITFALL A)
938 \tl_set:Ne \l__anim_dur_tl { \fp_to_decimal:N \g__anim_total_fp }
939 \tl_set:Ne \l__anim_ws_tl { \fp_to_decimal:N \g__anim_step_start_fp }
940 \tl_set:Ne \l__anim_we_tl { \fp_to_decimal:N \g__anim_step_end_fp }
941 %% Epsilon boundaries
942 \pgfmathsetmacro\animft@starte { max(\l__anim_ws_tl - \anim@eps, 0) }
943 \pgfmathsetmacro\animft@ende { \l__anim_we_tl - \anim@eps }
944 \pgfmathsetmacro\animft@totale { \l__anim_dur_tl - \anim@eps }
945 %% Build keyframe token list — \tl_set:Ne fully expands macros, so the
946 %% resulting tl contains only literal decimal strings and punctuation.
947 %% TikZ receives a pre-resolved string with no conditionals.
948 \tl_clear:N \l__anim_kf_tl
949 \fp_compare:nNnTF { \g__anim_step_start_fp } = { 0 } {
950 %% Step starts at t=0 — active immediately.
951 \tl_set:Ne \l__anim_kf_tl {
952 0s = "\animft@opA",
953 \animft@ende s = "\animft@opA",
954 \l__anim_we_tl s = "\animft@opI",
955 \animft@totale s = "\animft@opI"
956 }
957 } {
958 %% Step starts after t=0 — inactive first.
959 \tl_set:Ne \l__anim_kf_tl {
960 0s = "\animft@opI",
961 \animft@starte s = "\animft@opI",
962 \l__anim_ws_tl s = "\animft@opA",
963 \animft@ende s = "\animft@opA",
964 \l__anim_we_tl s = "\animft@opI",
965 \animft@totale s = "\animft@opI"
966 }
967 }
968 %% Append repeats modifier outside the spec — \if@anim@loop is evaluated here
969 %% in expl3 code, not inside the TikZ animate= value (which would confuse
970 %% TikZ's animation parser and trigger "doesn't match its definition").
971 \if@anim@loop \tl_put_right:Nn \l__anim_kf_tl { ,repeats, } \fi
972 \__anim_emit_mf_scope:Vn \l__anim_kf_tl { #1 }
973 }
974
975 %% \__anim_reveal_blink:n {content}
976 %% Called by \reveal when blink= key is set (period > 0).
977 %%
978 %% Opacity rules:
979 %% - Frame inactive (before/after active step): inactive opacity
980 %% - Frame active, blink "on" half-periods: blink on opacity
981 %% - Frame active, blink "off" half-periods: blink off opacity
982 %%
983 %% blink on/off opacity govern ONLY the intra-step oscillation.
984 %% Between steps the element follows inactive opacity, exactly like
985 %% a non-blink \reveal. Use inactive opacity=0 on a blink element to
986 %% hide it between steps; the static key on the animate environment
987 %% overrides all per-element opacity settings.
988 %%
989 %% Half-period h = blink_period / 2.
990 %% Number of half-periods: n_h = floor((e - s) / h), minimum 1.
991 %% For k = 0 .. n_h-1:
992 %% hold blink on opacity when k is even (first half = visible)
993 %% hold blink off opacity when k is odd (second half = hidden)
994 %% Before/after the step: hold inactive opacity.
995 %%
996 %% The epsilon trick applies at each half-period boundary just as in
997 %% Epsilon trick: (t_next - ε) holds the current opacity, then t_next snaps.
998 %%
999 \cs_new_protected:Npn \__anim_reveal_blink:n #1 {
1000 %% Opacity values (wrapper macros defined before \ExplSyntaxOn — PITFALL A).
1001 %% opI = inactive opacity: used OUTSIDE the active step (before/after).
1002 %% opBon = blink on opacity: used for even (on) half-periods within the step.
1003 %% opBoff = blink off opacity: used for odd (off) half-periods within the step.
1004 \pgfmathsetmacro\animft@opI { \@anim@get@inactive@opacity }
1005 \pgfmathsetmacro\animft@opBon { \@anim@get@blink@on@opacity }
1006 \pgfmathsetmacro\animft@opBoff { \@anim@get@blink@off@opacity }
1007 %% Total duration and epsilon-before-total
1008 \tl_set:Ne \l__anim_dur_tl { \fp_to_decimal:N \g__anim_total_fp }
1009 \pgfmathsetmacro\animft@totale { \l__anim_dur_tl - \anim@eps }
1010 %% Step bounds as decimal strings (for keyframe timestamps)
1011 \tl_set:Ne \l__anim_ws_tl { \fp_to_decimal:N \g__anim_step_start_fp } %% s
1012 \tl_set:Ne \l__anim_we_tl { \fp_to_decimal:N \g__anim_step_end_fp } %% e
1013 %% Half-period h = period / 2
1014 \fp_set:Nn \l__anim_blink_h_fp { \l__anim_blink_period_fp / 2 }
1015 %% n_h = floor((e - s) / h): number of complete half-periods in the step.
1016 %% floor() = trunc() for positive values. Minimum 1 so the loop runs at least once
1017 %% (handles the case where the step is shorter than one full period).
1018 \int_set:Nn \l_tmpa_int {
1019 \fp_to_int:n { floor(
1020 ( \g__anim_step_end_fp - \g__anim_step_start_fp ) / \l__anim_blink_h_fp
1021 ) }
1022 }
1023 \int_compare:nNnT { \l_tmpa_int } < { 1 } { \int_set:Nn \l_tmpa_int { 1 } }
1024 %% Build keyframe token list
1025 \tl_clear:N \l__anim_kf_tl
1026 %% Initial inactive phase: hold opI from 0 to (s - ε), if s > 0.
1027 \fp_compare:nNnT { \g__anim_step_start_fp } > { 0 } {
1028 \pgfmathsetmacro\animft@starte { \l__anim_ws_tl - \anim@eps }
1029 \tl_put_right:Ne \l__anim_kf_tl {
1030 0s = "\animft@opI",
1031 \animft@starte s = "\animft@opI",
1032 }
1033 }
1034 %% ── PITFALL D: one level of \int_step_inline nesting inside \cs_new_protected
1035 %% → ##1 in source becomes #1 in the stored definition = loop counter at runtime.
1036 %%
1037 %% Loop k = 0 .. n_h-1. \int_decr:N brings \l_tmpa_int to n_h-1 as the stop value.
1038 \int_decr:N \l_tmpa_int
1039 \int_step_inline:eeen { 0 } { 1 } { \int_use:N \l_tmpa_int } {
1040 %% t_start = s + k*h (decimal string via FP)
1041 \tl_set:Ne \l__anim_mstart_tl {
1042 \fp_to_decimal:n { \g__anim_step_start_fp + ##1 * \l__anim_blink_h_fp }
1043 }
1044 %% t_end = min(s + (k+1)*h, e) — caps the last half-period at the step boundary
1045 \tl_set:Ne \l__anim_mend_tl {
1046 \fp_to_decimal:n {
1047 min( \g__anim_step_start_fp + ( ##1 + 1 ) * \l__anim_blink_h_fp ,
1048 \g__anim_step_end_fp )
1049 }
1050 }
1051 %% Epsilon before t_end
1052 \pgfmathsetmacro\animft@wee { \l__anim_mend_tl - \anim@eps }
1053 %% Opacity for this half-period: blink on if k even, blink off if k odd.
1054 %% \tl_set:Ne expands \animft@opBon/opBoff to the decimal string immediately.
1055 \int_if_odd:nTF { ##1 } {
1056 \tl_set:Ne \l__anim_next_tl { \animft@opBoff }
1057 } {
1058 \tl_set:Ne \l__anim_next_tl { \animft@opBon }
1059 }
1060 %% Emit hold keyframes: opacity fixed at op for the interval [t_start, t_end - ε].
1061 %% The snap at t_end is handled either by the next iteration's t_start keyframe
1062 %% or by the final "e s = opI" keyframe below.
1063 \tl_put_right:Ne \l__anim_kf_tl {
1064 \l__anim_mstart_tl s = "\l__anim_next_tl",
1065 \animft@wee s = "\l__anim_next_tl",
1066 }
1067 }
1068 %% Snap to inactive opacity at step end; hold until total; optionally repeat.
1069 \tl_put_right:Ne \l__anim_kf_tl {
1070 \l__anim_we_tl s = "\animft@opI",
1071 \animft@totale s = "\animft@opI"
1072 }
1073 \if@anim@loop \tl_put_right:Nn \l__anim_kf_tl { ,repeats, } \fi
1074 %% Emit scope (PITFALL B: ':' at catcode 12 ensured by pre-ExplSyntaxOn helper)
1075 \__anim_emit_mf_scope:Vn \l__anim_kf_tl { #1 }
1076 }
1077
1078 %% \reveal[options]{content}
1079 %% Wraps content in an opacity animation.
1080 %%
1081 %% The key invariant: \g__anim_has_noanimate_bool is ALWAYS false in SVG mode
1082 %% (the scan that sets it is skipped when \if@anim@svgmode is true). Therefore
1083 %% \bool_if:NTF below always takes the animation path in SVG mode — no explicit
1084 %% SVG/PDF branch needed, and the original animation behaviour is preserved.
1085 %%
1086 %% PDF mode, no \noanimate in body: bool=false → animation emitted, but TikZ
1087 %% animation keys are silently ignored by the PDF driver, so #2 is rendered at
1088 %% full opacity (all steps stacked — legacy behaviour).
1089 %% PDF mode, \noanimate present: bool=true → animation suppressed.
1090 %% Render #2 only if this element carries the /anim/noanimate key.
1091 %%
1092 %% 'duration' in [options] is accepted but silently ignored (per-element timing
1093 %% has no meaning; duration is a step-level concept).
1094 \NewDocumentCommand \reveal { O{} +m } {
1095 \@anim@reveal@staticfalse %% reset per-element flag
1096 \group_begin: %% isolate option scope
1097 \tl_clear:N \l__anim_step_spec_tl %% reset step= spec
1098 \fp_set:Nn \l__anim_blink_period_fp { 0 } %% reset blink period
1099 \tikzset{ /anim/.cd, #1 } %% may set flags/step spec
1100 \bool_if:NTF \g__anim_has_noanimate_bool {
1101 %% \noanimate present in body (PDF only — bool is always false in SVG mode).
1102 %% Render #2 only if this element explicitly carries the noanimate key.
1103 \if@anim@reveal@static #2 \fi
1104 } {
1105 %% Normal path: SVG mode (always) or PDF without \noanimate.
1106 %% static mode: render content at full opacity without any keyframe animation.
1107 \if@anim@envstatic #2 \else
1108 \fp_compare:nNnTF { \l__anim_blink_period_fp } > { 0 } {
1109 %% blink= set: oscillate during the current step.
1110 %% Warn if step= was also given — the combination is undefined and blink= wins.
1111 \tl_if_empty:NF \l__anim_step_spec_tl {
1112 \PackageWarning{svg-animate}
1113 {blink= and step= are mutually exclusive;\MessageBreak
1114 blink= takes priority; step= is ignored}
1115 }
1116 \__anim_reveal_blink:n { #2 }
1117 } {
1118 \tl_if_empty:NTF \l__anim_step_spec_tl {
1119 %% No step= spec: single window from current step globals (existing behaviour).
1120 \__anim_reveal_simple:n { #2 }
1121 } {
1122 %% step= spec present: multi-window reveal.
1123 \__anim_reveal_multistep:n { #2 }
1124 }
1125 }
1126 \fi %% end \if@anim@envstatic
1127 }
1128 \group_end:
1129 }
1130
1131 %% \noanimate{content}
1132 %% PDF mode: renders content as a static element (no animation wrapper).
1133 %% SVG mode: completely ignored.
1134 %% Must be used inside \begin{animate}...\end{animate}; using it outside
1135 %% is an error because its meaning (fallback for which animation?) would
1136 %% be ambiguous.
1137 \NewDocumentCommand \noanimate { +m } {
1138 \if@anim@inside \else
1139 \PackageError{svg-animate}
1140 {\string\noanimate\space used outside animate environment}
1141 {%
1142 \string\noanimate\space provides a static PDF fallback for a specific%
1143 \MessageBreak animate environment. Use it inside%
1144 \MessageBreak \string\begin{animate}...\string\end{animate}.%
1145 }%
1146 \fi
1147 \if@anim@svgmode
1148 \else
1149 #1
1150 \fi
1151 }
1152
1153 \NewDocumentEnvironment { animate } { O{} +b } {
1154 %% #1 = animate-level options (e.g. "duration=1, inactive opacity=0")
1155 %% #2 = full body collected verbatim by +b, not yet executed
1156 \@anim@insidetrue %% guard: detect \animstep outside animate
1157 \@anim@envstaticfalse %% reset for each new environment
1158 \tikzset{ /anim/.cd, #1 } %% apply animate-level options globally
1159
1160 %% PDF mode: scan the body for \noanimate before executing anything.
1161 %% \tl_if_in:NnTF var {tokens} {true} {false}
1162 %% Checks whether the token \noanimate appears anywhere in the body.
1163 %% When found, \reveal will be suppressed so that only \noanimate is rendered.
1164 %% When absent, \reveal renders normally (legacy: all steps stacked in PDF).
1165 %% The flag is reset first so multiple animate environments are independent.
1166 \bool_gset_false:N \g__anim_has_noanimate_bool
1167 \if@anim@svgmode \else
1168 \tl_set:Nn \l__anim_seg_tl { #2 }
1169 \tl_if_in:NnT \l__anim_seg_tl { \noanimate } {
1170 \bool_gset_true:N \g__anim_has_noanimate_bool
1171 }
1172 \fi
1173
1174 %% \seq_set_split:Nnn target-seq {delimiter-token} {token-list}
1175 %% Cuts #2 everywhere \animstep appears; stores the pieces in \l__anim_steps_seq.
1176 %% Example result for 3 steps separated by two \animstep tokens:
1177 %% item 1: \reveal{\node (vm1)...}
1178 %% item 2: \reveal{\node (vm2)...}
1179 %% item 3: [duration=3] \reveal{\node (vm3)...}
1180 %% None of the items has been executed yet — they are inert token lists.
1181 \seq_set_split:Nnn \l__anim_steps_seq { \animstep } { #2 }
1182
1183 %%
1184 %% Pass 1: sum up all step durations to get the total — without executing
1185 %% any TikZ content.
1186 %%
1187 \fp_gzero:N \g__anim_total_fp %% total = 0.0
1188 \fp_gzero:N \g__anim_cursor_fp %% time cursor for building step timing table
1189 \seq_gclear:N \g__anim_step_times_seq %% reset per-step timing table
1190 %%
1191 %% \seq_map_inline:Nn seq { body using ##1 }
1192 %% Loops over every item in the sequence. Inside the body, ##1 is the
1193 %% current item. (Double # because we are already inside \NewDocumentEnvironment
1194 %% which uses single # for its own arguments.)
1195 \seq_map_inline:Nn \l__anim_steps_seq {
1196 %%
1197 %% \tl_set:Nn var {value} — assign a token list variable.
1198 %% We copy ##1 into a named variable so \__anim_pop_opts:NN can modify it
1199 %% (seq items are read-only; a local copy is needed).
1200 \tl_set:Nn \l__anim_seg_tl { ##1 }
1201 %%
1202 %% Strip the leading [opts] (e.g. [duration=3]) from \l__anim_seg_tl.
1203 %% The extracted opts string goes into \l__anim_step_opts_tl.
1204 %% If there were no [opts], \l__anim_step_opts_tl is left empty.
1205 \__anim_pop_opts:NN \l__anim_step_opts_tl \l__anim_seg_tl
1206 %%
1207 %% \group_begin: / \group_end: — standard TeX grouping ({ ... }).
1208 %% Any \tikzset inside is local and does not leak into the next step.
1209 \group_begin:
1210 %%
1211 %% \tl_if_empty:NF var {code} — run {code} only if var is NOT empty (:NF = N, False).
1212 \tl_if_empty:NF \l__anim_step_opts_tl {
1213 %% \exp_args:Ne cmd {arg} — fully expand {arg} before passing it to cmd.
1214 %% \tl_use:N \l__anim_step_opts_tl expands to the string content of the variable,
1215 %% e.g. "duration=3". Without :Ne, \tikzset would receive the unexpanded macro
1216 %% name instead of the string it holds.
1217 \exp_args:Ne \tikzset { /anim/.cd, \tl_use:N \l__anim_step_opts_tl }
1218 }
1219 %%
1220 %% \tl_set:Ne var {expr} — assign var to the fully-expanded value of {expr}.
1221 %% Reads the current /anim/duration key (possibly just overridden by step opts)
1222 %% and stores it as a plain string like "3" or "1".
1223 \tl_set:Ne \l__anim_dur_tl { \pgfkeysvalueof{/anim/duration} }
1224 %%
1225 %% \exp_args:NNV cmd arg1 var — call cmd with arg1 unchanged and var
1226 %% replaced by its value (:V expansion). Equivalent here to:
1227 %% \fp_gadd:Nn \g__anim_total_fp {"3"} (the string "3" parsed as a number)
1228 %% \fp_gadd:Nn fp-var {fp-expr} — adds the expression to the fp variable.
1229 %%
1230 %% Store "start/end" for this step before advancing the cursor.
1231 %% Item index N (1-based) in \g__anim_step_times_seq holds the timing of step N.
1232 \exp_args:NNV \fp_gset:Nn \g__anim_step_dur_fp \l__anim_dur_tl
1233 \seq_gput_right:Ne \g__anim_step_times_seq {
1234 \fp_to_decimal:N \g__anim_cursor_fp /
1235 \fp_eval:n { \g__anim_cursor_fp + \g__anim_step_dur_fp }
1236 }
1237 \fp_gadd:Nn \g__anim_cursor_fp { \g__anim_step_dur_fp } %% advance cursor
1238 \exp_args:NNV \fp_gadd:Nn \g__anim_total_fp \l__anim_dur_tl
1239 \group_end: %% step opts are rolled back; total remains (it is global \g_...)
1240 }
1241 %% After the loop, \g__anim_total_fp holds the sum of all step durations, e.g. 5.0.
1242
1243 %%
1244 %% Pass 2: iterate again, this time executing each step's TikZ content.
1245 %% We maintain a timing cursor (start) that advances step by step.
1246 %%
1247 \fp_gzero:N \g__anim_step_start_fp %% cursor starts at t = 0.0
1248 \seq_map_inline:Nn \l__anim_steps_seq {
1249 \tl_set:Nn \l__anim_seg_tl { ##1 }
1250 \__anim_pop_opts:NN \l__anim_step_opts_tl \l__anim_seg_tl
1251 \group_begin:
1252 \tl_if_empty:NF \l__anim_step_opts_tl {
1253 \exp_args:Ne \tikzset { /anim/.cd, \tl_use:N \l__anim_step_opts_tl }
1254 }
1255 \tl_set:Ne \l__anim_dur_tl { \pgfkeysvalueof{/anim/duration} }
1256 %%
1257 %% Store the step duration as an FP variable so we can use it in an FP expression.
1258 %% (:NNV passes the value of \l__anim_dur_tl, e.g. the string "3", to \fp_gset:Nn.)
1259 \exp_args:NNV \fp_gset:Nn \g__anim_step_dur_fp \l__anim_dur_tl
1260 %%
1261 %% \fp_gset:Nn fp-var {fp-expr} — evaluate an FP expression and store the result.
1262 %% FP variables (prefixed \g__ or \l__) are referenced directly in expressions.
1263 %% e.g. if start=2.0 and dur=3.0, this sets end=5.0.
1264 \fp_gset:Nn \g__anim_step_end_fp
1265 { \g__anim_step_start_fp + \g__anim_step_dur_fp }
1266 %%
1267 %% \tl_use:N var — expand and execute the token list.
1268 %% This is where the TikZ code (\reveal{...} etc.) actually runs.
1269 %% At this point the three timing globals hold the correct values for this step,
1270 %% so every \reveal inside will emit keyframes for the right time window.
1271 \tl_use:N \l__anim_seg_tl
1272 %%
1273 %% \fp_gset_eq:NN a b — set a = b (both are FP variables).
1274 %% Advance the cursor: next step starts where this one ended.
1275 %% This is global, so it survives the upcoming \group_end:.
1276 \fp_gset_eq:NN \g__anim_step_start_fp \g__anim_step_end_fp
1277 \group_end:
1278 }
1279 } { \@anim@insidefalse }
1280
1281 \ExplSyntaxOff