Forth and shaders

this time we will focus on poetry. Minimalist programming language Forth and the beauty of the images demoscene pushed programmer brad Nelson to the idea Forth Haiku. In imitation of Japanese haiku, brad wrote his first program of the three lines, they consisted of five, seven, and again five words. But in contrast to the traditional Japanese genre poetry in the Forth language created the picture is not in the imagination of the reader, and visibly, on the screen of the computer. This idea could be a quirk of lone fan of computer retro (a Forth is strongly associated with good old seventies), if brad hasn't made it on the most modern platform (WebGL) and I would not do the online editor available to the public.

Here is an example of Forth Haiku code and the image that this code creates: "Light Drop" by Brad Nelson.

the
: iii x y z*
Sin ; x 5 * x y
- iii exp iii y

Light Drop by BradN

Ahead of us a lot of amazing (including "real") pictures, but first a bit of theory.

Major concepts


safety. Apparently to the paragraph "Warning" no one has time to read, instead just go to the online editor and try to do something. Effects of sad: the server failed, database works have scored a broken haiku. Please scroll down a bit and read the rules of behavior on the water, before embarking on an independent voyage. Thank you!

Forth — stack programming language. To perform an action on multiple numbers, you must first load them into a stack. This is done by simple enumeration of numbers separated by spaces. Then indicate the action to be performed on numbers from the stack. Teams are also separated by spaces and may be mixed in any desired computation order. Arifmeticheskie normal actions are removed from the top of stack operands and put the result instead.
1 2 3 + /
Example 1: load the stack of numbers 1, 2 and 3, then perform the addition of two upper numbers (the stack becomes 1, 5) and then divide one number by another. In the end, the stack contains the answer: the number 0.2
1 2 + 3 /
Example 2: another course of action. Loaded in stack number 1 and 2, fold. The result on the stack 3. Downloadable to stack another number 3 and dividing. Answer: the number 1 on top of the stack.

Shader — here we will focus on the pixel Shader, also called fragment. It is a program executed by the graphics card for every texture, as in our case — for each point of a square window of size 256x256. Thus, the canvas on which we paint their paintings, consists of 65536 points, and that is how many times will be performed by the Shader program. Output the program should output the color of the point. It would seem that if the same program is run for all points, and look these points have the same — we will get a big square of Malevich (black, red, whatever). All the way. But fortunately, the Shader program can read the coordinates x and y the point which draws in the moment. And this changes everything.

coordinate System
the coordinate system of the Forth Haiku
Upon completion of our program, the Shader (Forth Haiku) should leave the stack in three numbers: red component of color, green component and blue. Very convenient that the brightness RGB-components is measured on the same scale as the geometric size of the window. Just put in the stack x or y (it is in fact different for each point, right?), get a smooth transition of color from black to bright through all our linen.

Time
In addition to x and y, we are one global variable t time. However, in browsers that support WebGL deprived, it is always zero. The countdown began in ancient times, to the present time the time is already an incredible amount of seconds, so practical use is, perhaps, only a fractional part of the variable t and a periodic function like sin(t), as it produces values in the range from -1 to +1.
Minimal animation
the
x
y
t
sin 1 + 2 /

Primer the most simple animation. Put in the stack the coordinate x and leave unchanged, it will reflect the red component of the color. In second place on the stack put a green component, it will be y (so, greens zakolositsya from the bottom up). As the blue component put the time t. Now put performed over the last number of a number of operations. First, take from him sine. Then add 1 and divide by 2. All. We had a sine in the range [-1,1], and became [0,1] — as it should be component of the color. And here went a nice ripple on the blue component, and so lit up more than before the point, tinted red and green component — a beauty!
For comparison, here is the same Shader GLSL
the
void main(void)
{
vec2 uv = gl_FragCoord.xy / iResolution.xy;
gl_FragColor = vec4(uv,0.5+0.5*sin(iGlobalTime),1.0);
}

To code Forth seems simpler and more understandable, it offers a very low entry threshold in the subject. See animation made (from scratch) my 9 year old son, after watching just a couple of days for my experiment with Haiku Forth. I think this indicator.

Time, forward!


Well, with the theory over, let's get to practice. In the gallery Forth Programming Salon full of easel painting beautiful still images. But we are more interested in animation.
Warning (safety): when You start to pick other people's work ("Create a derived work") or create a new one ("Create a Haiku", "Haiku Editor"), Your hand will be pulled to the button "Submit". In no case do not press it, because it does not what You thought! View your program by clicking another button — "Update". A button "Submit" will post in the General gallery of Your zabagovannuyu nedopisan the program, and even with the user name "Anonymous". Such hockey is not necessary, base the already zaspamlena broken fragments of programs and clones (brad Nelson promised to clean the database and to improve the interface). So only "Update". Inhale-exhale, a 15-minute break for gymnastics, with fresh eyes evaluate your program, and only if 146% sure about her — then give her a name, enter the author and "Submit".

Golden Bump by Manwe Coffee by Manwe Pacman by Manwe
Click on pictures. It is moving there! (in Chrome, Firefox, IE11)

My programs, of course, terribly unreadable. First, only recently (thanks to the boy, who poked Forth this JavaScript translator) I learned about the existence of undocumented features to fit in the program comments (in parenthesis should be separated by a space from the text of the comment). Secondly, and this is important — I tried to reduce the size of the program. There is a sport — optimized, very popular on the demoscene. Could in 256 bytes? Well done! Now let's put in 128. So the first thing I do is override the commands of the Forth language.
the
: q dup * ;

The colon is a statement of language of Forth (actually, in the environment Fort of programmers to say "word" instead of "operator" and "dictionary" instead of "a set of commands and functions", but let's not complicate things). The operator "colon" is like defining a function. Followed by a colon (with a space as usual) is the name of the new operator, in this example "q" (from the word "square"). After the name with a space written a small programm, which is the body of our newly-operator "q". The last statement — "semicolon", the end of the definition (in fact, he takes out a special stack of returns, the return address and moves back to the counter, but again — let's keep it simple).
the
x ' r / z * lx m
y ' r / z * ly m

Here x and y — global constants, and everything else specified by the programmer. The operator of "touch" takes us in a different coordinate system, the operator "r" calculates the length of the vector, the operator z calculates the normal, "lx" and "ly" give the coordinates of the light source, "m" normalizes a vector (more precisely, one of its coordinates). If we want the multiplication after "z" can make to the body of the operator "z" (will save a few bytes). And the division before the "z" you can add to it (or the previous operator, "r"). When optimizing these intermediate steps crawl into the dictionary, and in the body of the program remains only the bare essence: x, y, t .
It's beautiful. But a week later it's completely unreadable, of course.

Want an example of a simple program in which You will be able to deal with vocabulary Forth Haiku? Dictionary this dictionary is much poorer than classical Forth, and this is intentional. Click on the operator itself and read more about it.
Candy Waterfall by Manwe
the
: y r dup 12 ** * t + sin swap x * cos + 1 mod ;
18 r
25 r dup
12 r /

In the first line determined by the operator "r" (from the word "render"), which swallowed a number of the top of the stack, carefully chewing, eating x and y, and then spits out the result on the stack in the range [0,1]. The operator "r" three times fed different numbers, and the output three RGB components. In order to duplicate the color correction of the green component and divide it by blue. Now we have a new blue component, thus contributing to the overall picture turned out caramel.
"1 mod" is getting the fractional part of the number. True, it works not everywhere (Forth Haiku, in fact, are drawn, and in the absence of WebGL in pure JavaScript, but with some restrictions). Instead of "mod 1" it is better to use "dup floor". But when You chase the size less than 128 bytes, you have to sacrifice compatibility in favor of brevity.

For fans of hardcore — drawing the sprites in the absence of binary operations and still a little bit of all:
PONG by Manwe Invaders by Manwe Lava Lamp by Trisomie21 and Manwe

Opinion


Forth Haiku are very simple and very limited. If desired, squeeze him quite a lot, but none of which compete with GLSL out of the question. It's not that goal. Program in Forth beautiful by itself. The course of human thought, programming in Forth, and even programming pixel shaders is interesting in itself. A great way to distract and entertain yourself, a great exercise for children. I would set up the course of Forth Haiku in school, honestly. At least one-quarter to push the children think different is cool.

Links


Projects brad Nelson, devoted to the Forth language.
photo dump — the "back door" to the gallery.
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

New web-interface for statistics and listen to the calls for IP PBX Asterisk

The use of Lisp in production

As we did a free Noodle for iOS and how we plan to earn