Научная статья на тему 'ASYMPTOTE-BASED SCIENTIFIC ANIMATION'

ASYMPTOTE-BASED SCIENTIFIC ANIMATION Текст научной статьи по специальности «Компьютерные и информационные науки»

CC BY
16
8
i Надоели баннеры? Вы всегда можете отключить рекламу.
Ключевые слова
VECTOR GRAPHICS / TEX / ASYMPTOTE / SCIENTIFIC GRAPHICS

Аннотация научной статьи по компьютерным и информационным наукам, автор научной работы — Gevorkyan Migran N., Korolkova Anna V., Kulyabov Dmitry S.

This article discusses a universal way to create animation using Asymptote the language for vector graphics. The Asymptote language itself has a built-in library for creating animations, but its practical use is complicated by an extremely brief description in the official documentation and unstable execution of existing examples. The purpose of this article is to eliminate this gap. The method we describe is based on creating a PDF-file with frames using Asymptote, with further converting it into a set of PNG images and merging them into a video using FFmpeg. All stages are described in detail, which allows the reader to use the described method without being familiar with the used utilities.

i Надоели баннеры? Вы всегда можете отключить рекламу.
iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.
i Надоели баннеры? Вы всегда можете отключить рекламу.

Текст научной работы на тему «ASYMPTOTE-BASED SCIENTIFIC ANIMATION»

Discrete & Continuous Models

#& Applied Computational Science 2023, 31 (2) 139-149

ISSN 2658-7149 (online), 2658-4670 (print) http://journals-rudn-ru/miph

Research article

UDC 004.92:004.928:519.67

DOI: 10.22363/2658-4670-2023-31-2-139-149

EDN: XKNIYV

Asymptote-based scientific animation

Migran N. Gevorkyan1, Anna V. Korolkova1, Dmitry S. Kulyabov1,2

1 RUDN University, 6, Miklukho-Maklaya St., Moscow, 117198, Russian Federation 2 Joint Institute for Nuclear Research, 6, Joliot-Curie St., Dubna, Moscow Region, 141980, Russian Federation

(received: April 5, 2023; revised: May 5, 2023; accepted: June 26, 2023)

Abstract. This article discusses a universal way to create animation using Asymptote the language for vector graphics. The Asymptote language itself has a built-in library for creating animations, but its practical use is complicated by an extremely brief description in the official documentation and unstable execution of existing examples. The purpose of this article is to eliminate this gap. The method we describe is based on creating a PDF-file with frames using Asymptote, with further converting it into a set of PNG images and merging them into a video using FFmpeg. All stages are described in detail, which allows the reader to use the described method without being familiar with the used utilities.

Key words and phrases: vector graphics, TeX, asymptote, scientific graphics

1. Introduction

In this paper we study the creation of animation animation using the vector graphics language Asymptote [1-4].

Asymptote is an interpreted language, that is a translator into the PostScript vector graphics language. Designed to create vector images for mathematical publications. It is closely integrated with the TeX system and is an integral part of the TeX Live [5] distribution. It has a C-like syntax, supports the creation of functions, custom data structures, and comes with an extensive set of modules for various tasks. Unlike PGF/TikZ [6], Asymptote is more imperative, so it is easier to implement complex program logic on it.

In the official documentation of this language, only a few paragraphs are devoted to the animation creation process and the user is referred to the source code examples located in the animations directory. Asymptote creates animation in two steps. At the first step, a multi-page PDF-file is created containing images that will become frames of future animation. Then, using the external utility ImageMagick [7] (command convert), this PDF-file is

© Gevorkyan M.N., Korolkova A. V., Kulyabov D.S., 2023

This work is licensed under a Creative Commons Attribution 4.0 International License https://creativecommons.org/licenses/by-nc/4.0/legalcode

converted into a GIF image. If the ImageMagick utility is not installed on the user's system, all examples will stop at creating a multi-page PDF-file with a set of images and a GIF image with animation will not be received.

In this article, we are considering a universal way to create animation in video format using the ffmpeg [8, 9] and Ghostscript [10] utilities. All external programs will be called explicitly from the command line. With the help of Asymptote, only a multi-page PDF-file with frames for the future video will be created.

The reader should be familiar with the basic capabilities of the Asymptote language. For an introduction to the basics of the language, we recommend the manual [11]. The information from it will be enough to understand this work. As an example, we chose the animation of the process of constructing epitrochoids and hypotrochoids. In the first part of the work, we will recall the definitions of these curves, some of their properties and reduce their construction to a composition of two rotations. In the second part of the article, we will describe in detail the implementation of their construction using Asymptote. And in the third part we will focus on the technical side of the issue and describe the process of creating a multi-page PDF-file, converting it into PNG images using Ghostscript and converting these images into video using ffmpeg.

Consider the task of animating the process of constructing cycloidal curves, namely hypotrochoids and epitrochoids. We will not use the parametric equation of these curves, but will reduce everything to the composition of two rotations applied to the starting point of the curve. This will better illustrate the capabilities of the Asymptote language.

Epitrochoid is defined as a trajectory plotted by a fixed point P lying on a radial line of circle with radius r, which rolls along the outer side of the circle with radius R (figure 1). The parametric equation of the curve has the following form:

where d is the distance from the center of the rolling circle to the point of the curve, p is the angle of rotation of the rolling circle relative to the axis Ox.

Let us introduce the coefficient k = r/R, then it will possible to change the parameterization and the equation will take the form:

2. Task description

2.1. Definition of epitrochoids

jx(t) = R(k+l) cos(kt) - d cos((k + 1)t) \y(t) = R(k + l) sin(kt) - dsin((k + 1)t),

where the parameters t and p are related as p = kt.

2,5

-2,5

/ / N £

"R- - r

l{

\

-2,5 0 2,5

Figure 1. R = 3, r = 1, d = 1/2

4 2 0

-2 4

>—r ! —>L !

/A N\

/ - - -- a A

- -- r

1

l\ ! /! 1

\ -- -- - -- --~ r ~ -

J ;

r^ 1 ^^

-5 0 5 Figure 2. R = 4, r = 2, d = 2

Some special cases of epitrochoids have proper names. So for r = R,

Pascal's snail is obtained, for d = R + r — rosy curve or rose, and for d = r — epicycloid (figure 2).

2.2. Definition of a hypotrochoid

Hypotrochoid is the trajectory described by a fixed point P on a radial straight circle of radius r, which rolls along the inner side of the circle of radius R (figure 3). The parametric equation of the curve has the following form:

x(t) = (R-r) cos(p) + d cos (--p) ,

y(t) = (R-r) sin(^) — d sin —-'¿i) ,

where, as in the case of the epitrochoid, d is the distance from the center of the rolling circle to the point P. In particular, for d = r, hypocycloid is obtained (figure 4).

Figure 3. R = 4,r = 2,d=1

' r

d

\ ^ T

-2,5 0 2,5 Figure 4. R = 4,r = 2,d= 2

It is also possible to parameterize p = kt, where k = r/R, then the equation will take the form:

jx(t) = R(1 - k) cos(kt) + d cos((l - k)t), \y(t) = R(i - k) sin(kt) - dsin((1 - k)t).

2.3. Reducing the problem to a composition of turns

The construction of cycloidal curves begins by specifying two circles: a fixed circle of radius R centered at point 0R and a moving circle of radius r centered at point Or.

A fixed circle will be conventionally called "large", and a moving one — "small", since usually R > r. On the radial line of a small circle, we fix the point of the curve P0.

From the definition of hypotrochoids and epitrochoids, it follows that a motion T(^>) is performed over the point P0, consisting of a composition of two turns (figures 5-10):

1. Tx (p) — rotation around the point 0R by the angle at which the point Or turns into O', and the point P0 into the point Px/2 ;

2. T2(9(^>)) — rotation around the point 0'r by the angle 9, at which Px/2 turns into Px.

Pi/2

v

Pi f I jr e„ V —

\ /

7

-A <p \ it r

o* \ /

,___

\ /

Po

0 12 3 4

Figure 5. Hypocycloid d = r

p.

f I

V!

J f L )r nN

u 6, ' h

\ /

/

/ ^ \ f c r

0R \ I /

V ,___

\ 1 /

0 12 3 4

Figure 6. Hypotrochoid d > r

0 12 3 4

Figure 7. Hypotrochoid d < r

The rotation angle 9 is related to the angle A small circle must travel a distance equal to the length of the arc PP1/2, which means that the lengths of the arcs PPi/2 and Pi/2Pi are equal.

lPP1/21 =R<p = \P\/2 Pi I = 9r^9=^ = ^, k = r/R.

V K

Thus, to construct a curve, it is enough to set the parameters R, r and d, the initial positions of the circles and the points P0. It is usually assumed that the center of 0R coincides with the origin, and the center of Or lies on the Ox axis.

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

0 12 3

5 6

0 1

5 6

' ) r 1

-- N P1 - - — —

\

\

V \

/ \ { L. r \

c R /

\

1

0 1

5 6

Figure 8. Epicycloid d = r Figure 9. Epitrochoid d> r Figure 10. Epitrochoid d < r

Then the coordinates of the center Or are calculated as:

^ f+1, if epitrochoid, , x

= + (R+s.r,0V, if hylJ0tr^cll0id. (1)

And the coordinates of the curve point are P0: OP0 = OOr + (d, 0)T.

Now, to find any point of the curve, it is enough to act on P0 by converting T(p) = T2 (p/k) °TX (p) setting the required value to If it is necessary to construct a set of points, then taking a sufficiently small step one can consistently act on the point P0 by transformations T(i^>), i = 1,2,... ,n:

Pn

T(2<p)

T(Zv)

P\, Pq ^ 2, PQ ^ P3, PQ ^ P4, , ■■■, PQ 3. Implementation on Asymptote

T(nV)

P

± n, '

Below we present the source code of the program in the Asymptote language and comment on its key points:

include "config.asy";

0

import animation;

import graph;

unitsize(lcm); size(10cm, 10cm);

string ssign(int d) {

return d > 0 ? " + " : "-";

}

transform T1(real phi, pair O_R) { // (2) return rotate(angle=phi, z=O_R);

}

transform T2(real phi, int sign, real k, pair O_r) { // (4)

return rotate(angle=sign*phi/k, z=O_r);

}

pen BigCircle = blue;

pen littleCircle = deepgreen;

pen curve = red;

int sign = -1; // (6)

real R = 4.0;

real r = 2.0;

real d = 2.0;

real k = r/R;

int N = 100; // (8)

pair O_R = (0, 0);

int turns = 1; // (10)

usersetting(); // (12)

pair O_r = O_R + polar(R + sign * r, 0); // (14)

pair P = O_r + polar(d, 0); // (16)

pair Q = O_r - sign * polar(r, 0); // (18)

guide xcycloid; transform T;

animation A; // (20) A.global = true;

draw(circle(c=O_R, r=R), p=BigCircle); // (22) dot(O_R, p=BigCircle);

for(real phi: uniform(0, 360turns, N)) { save(); // (24)

T = T1(phi, O_R) * T2(phi, sign, k, O_r); // (26)

xcycloid = xcycloid -- T*P; // (28)

draw(xcycloid, p=1bp+curve); // (30)

dot(T*P, L=Label("P", align=NW)); // (32)

draw(O_R -- T*O_r, L=Label("R"+ssign(sign)+"r")); // (34)

draw(T*O_r -- T*P, L=Label("d"));

draw(circle(c=T*O_r, r=r), p=littleCircle); // (36)

dot(T*O_r, p=littleCircle);

dot(T1(phi, O_R)*Q, p=littleCircle); // (38)

include "axes.asy"; // (40)

A.add(); // (42) restore(); // (44)

}

A.movie(); // (46) currentpicture.erase();

This program creates a multi-page PDF-file, each page of which is a future frame of the video. The main work on calculating the points of the curve is performed by the functions T1 (2) and T2 (4). These functions are defined for convenience, so that the code reflects the above formulas as much as possible. All the work is done by the built-in function rotate, which allows you to determine rotation around an arbitrary point (argument z) by an arbitrary angle value in degrees (argument angle).

Next, we set a set of variables-parameters (6). The variable sign is s from the formula (1), and the rest correspond to their mathematical notation. The variable N (8) sets the number of calculated points and, as a result, frames in the future video. The variable turns (10) sets the number of complete turns around the center of 0R. Calling the built-in function usersetting (12) to override the value of any variable specified above via the command line argument -u.

Then, based on the above-defined parameters, the coordinates of the initial position of the center of the moving circle Or (14), the points of the curve P (16) and the point of tangency Q of the moving circle with the stationary (18) are calculated.

Next, an object A (20) is created, into which animation frames will be recorded (objects of the type picture or frame). A has several fields, in particular the global field of the bool type allows you to enable and disable saving the created images as an array in RAM and writing them as files to disk only after they are all built.

The curve points are calculated in a loop, but before that, a fixed circle (22) and its center are drawn. Then, at the beginning of each iteration of the cycle, all the current stationary elements of the image are saved (object picture) (24), all movable elements are built, the resulting image is added to the structure A (42) and the image state is reset (44) to the one that was at the time of (24). The process continues until all frames are drawn and saved to A.

As the cycle progresses, the angle p changes from 0 to 2nn (in degrees). At each step, the rotation transformation T(^>) is calculated (28), applied to the starting point of P and added to the path (guide) xcycloid (28). With each iteration of the loop, new points are added to the path xcycloid and the curve grows.

The following drawing commands follow:

— of the already calculated part of the curve (30);

— of the new point position P (32);

— of a segment of length R + s ■ r (34) connecting the center of 0R to the new position of the center of Or, as well as a segment of length d connecting the new center of Or to the point P of the curve;

— directly the moving circle itself in its new position (36) and its center;

— touch point Q (38);

— coordinate grid, the settings of which are placed in a separate file (40).

Finally, after working out the loop, all created frames are recorded in a PDF-file. To do this, Asymptote sequentially creates separate PDF-files for each frame, then adds text processed by LTEX (in our case LuaLIEX) to them.

It is this procedure that takes the main time of the program, the calculations themselves practically do not take up time in comparison with this.

We also note the peculiarity of the Asymptote syntax, which allows omitting the * operator when multiplying numeric literal constants and variables, for example 360turn (24).

4. Creating a video clip 4.1. Launching Asymptote

To run the program discussed above, run the following command

asy -noV -nobatchView -f pdf -globalwrite -u ^ 'R=3;r=1;d=1;N=100' xcycloid.asy -o video/xcycloid.pdf

The source code file xcycloid.asy is started for execution and as a result the file xcycloid.pdf will be created. Consider the options used:

— Options -noV and -nobatchView prevent the newly created image from opening automatically. The -noV option disables this function when executed from the command line, and -nobatchView when executing the script (as in our case).

— Option -f pdf indicates that you should immediately create a PDF-file, bypassing the postscript-file stage.

— Option -globalwrite makes it possible to save the file xcycloid.pdf to any directory (in our case video), and not only to the one where the source file xcycloid.asy is located.

— Option -u allows you to interact with the usersetting() function and pass the values of variables inside the program. So we pass the values R=3, r=1, d=1 and N=100. This feature allows you to use a single source code file to build multiple images, flexibly adjusting any parameters. Note that this parameter takes exactly a text string, which is then processed by the usersetting() function, so the passed parameters must be taken in quotation marks.

4.2. Converting to PNG using GhostScript

To convert the resulting multipage file into a video format, it is necessary to convert its pages into bitmaps. To do this, we suggest using the GhostScript [10] program. It is available for both Windows and Unix systems (GNU/Linux, macOS). It also comes with the TEXLive [5] distribution, as does Asymptote.

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

To convert a PDF-file, run the command

gs -sDEVICE=png16m -r600 -o video/xcycloid-%04d.png ^ video/xcycloid.pdf

In the case of using GhostScript from the TEXLive distribution, you should call gs using the rungs script, which is located:

— in the directory texlive\2023\bin\win32 in the case of Windows OS,

— in the texlive/2023/bin/x86_64-linux in the case of GNU/Linux.

The 2023 directory corresponds to the version of the TEXLive distribution and may differ.

4.3. Creating a video using FFmpeg

The process of gluing the resulting bitmap images into one video clip is carried out using FFmpeg [9]. This program is a command-line utility and has extensive functionality and, as a result, a huge number of options and settings. Let's give an example of creating a video clip from the PNG images generated in the previous step and give an explanation of the parameters used:

ffmpeg -r 30 -f image2 -start_number 1 -i ^ video/xcycloid-%04d.png -c:v libx264 -vf ^ "pad=ceil(iw/2)*2:ceil(ih/2)*2" video/xcycloid.mp4

— Parameter -r sets the frame rate.

— Parameter -f sets the format of the input file.

— Since a lot of files are submitted to the input, you should specify the format of their names. The same notation is used as in the case of gs. The -start_number parameter sets the starting number.

— Parameter -c:v allows you to specify the video encoder used. In our case libx264, but many other formats are supported.

— The important parameter -vf sets the filter that is applied to the processed frame. In our case, we round the width and height of the frame in pixels to an even number. After converting to PNG, the width and height of the image may be odd, which is unacceptable for the vast majority of encoders. The specified filter allows you to avoid this error and rescale the frame by ffmpeg.

At the output we will get a video packed in a container mp4. The x264 format we have chosen is widespread and can be played by any browser.

5. Conclusion

We have analyzed in detail the way to create vector graphics animation on a plane using the Asymptote language. This aspect of this language is poorly covered in the official manual and, in our opinion, this article fills this gap. Although the result is a video clip containing bitmaps, but thanks to the vector source (PDF), you can increase the resolution of the video almost limitlessly. It should also be noted that this method of creating animation is universal, since almost any data visualization tool can be used to create a set of image frames. FFmpeg does all the work on creating a video file.

Acknowledgments

This paper has been supported by the RUDN University Strategic Academic Leadership Program.

References

[1] O. Shardt and J. C. Bowman, "Surface parameterization of nonsimply connected planar Bezier regions," Computer-Aided Design, vol. 44, no. 5, 484.e1-484.e10, May 2012. DOI: 10.1016/j.cad.2011.05.010.

[2] J. C. Bowman, "Asymptote: Interactive TEX-aware 3D vector graphics," TUGboat, vol. 31, no. 2, pp. 203-205, 2010.

[3] J. C. Bowman and A. Hammerlindl, "Asymptote: A vector graphics language," TUGboat, vol. 29, no. 2, pp. 288-294, 2008.

[4] J. C. Bowman. "Asymptote: The Vector Graphics Language." (May 2023), [Online]. Available: https://asymptote.sourceforge.io/.

[5] "TeX Live." (2023), [Online]. Available: https : / /www . tug . org/ texlive/.

[6] T. Tantau and H. Menke. "PGF/TikZ." (2023), [Online]. Available: https://ctan.org/pkg/pgf.

[7] "ImageMagick." (Jun. 12, 2020), [Online]. Available: https : / / imagemagick.org.

[8] S. Tomar, "Converting video formats with FFmpeg," Linux Journal, vol. 2006, no. 146, p. 10, 2006.

[9] "FFmpeg Website." (2023), [Online]. Available: https://ffmpeg.org/.

[10] "Ghostscript Website." (2023), [Online]. Available: https ://www . ghostscript.com/.

[11] C. I. Staats. "An Asymptote tutorial." (2015), [Online]. Available: https: //math.uchicago.edu/~cstaats/Charles_Staats_III/Notes_and_ papers_files/asymptote_tutorial.pdf.

For citation:

M. N. Gevorkyan, A. V. Korolkova, D. S. Kulyabov, Asymptote-based scientific animation, Discrete and Continuous Models and Applied Computational Science 31 (2) (2023) 139-149. DOI: 10.22363/2658-4670-2023-31-2-139-149.

Information about the authors:

Migran N. Gevorkyan — Candidate of Sciences in Physics and Mathematics, Associate Professor of Department of Applied Probability and Informatics of Peoples' Friendship University of Russia named after Patrice Lumumba (RUDN University) (e-mail: gevorkyan-mn@rudn.ru, phone: +7 (495) 955-09-27, ORCID: https://orcid.org/0000-0002-4834-4895)

Anna V. Korolkova — Candidate of Sciences in Physics and Mathematics, Associate Professor of Department of Applied Probability and Informatics of Peoples' Friendship University of Russia named after Patrice Lumumba (RUDN University) (e-mail: korolkova-av@rudn.ru, phone: +7(495) 952-02-50, ORCID: https://orcid.org/0000-0001-7141-7610) Dmitry S. Kulyabov — Doctor of Sciences in Physics and Mathematics, Professor of the Department of Applied Probability and Informatics of Peoples' Friendship University of Russia named after Patrice Lumumba (RUDN University); Senior Researcher of Laboratory of Information Technologies, Joint Institute for Nuclear Research (e-mail: kulyabov-ds@rudn.ru, phone: +7 (495) 952-02-50, ORCID: https://orcid.org/0000-0002-0877-7063)

УДК 004.92:004.928:519.67

DOI: 10.22363/2658-4670-2023-31-2-139-149

EDN: XKNIYV

Научная анимация на основе Asymptote

М. Н. Геворкян1, А. В. Королькова1, Д. С. Кулябов1,2

1 Российский университет дружбы народов, ул. Миклухо-Маклая, д. 6, Москва, 117198, Россия 2 Объединённый институт ядерных исследований, ул. Жолио-Кюри, д. 6, Дубна, Московская область, 141980, Россия

Аннотация. В статье рассматривается универсальный способ создания анимации с помощью языка для создания векторной графики Asymptote. В сам язык Asymptote встроена библиотека для создания анимации, однако практическое её использование осложнено крайне кратким описанием в официальной документации и нестабильной работой существующих примеров. Целью статьи является устранение данного пробела. Излагаемый нами способ основывается на создании PDF-файла с кадрами с помощью Asymptote с дальнейшей конвертацией его в набор PNG-изображений и склейкой их в видео с помощью FFmpeg. Все этапы подробно описываются, что даёт возможность читателю использовать изложенный метод, не будучи знакомым с используемыми утилитами.

Ключевые слова: векторная графика, TeX, asymptote, научная графика

i Надоели баннеры? Вы всегда можете отключить рекламу.