Variables

Sometimes you want to use one value in multiple places in your expression. It's not necessary to write that value twice. Instead you give it a name by which you can refer to it. Let's say we want to produce an image like this:

As you can see, the pixels from the original image fade to black with the distance from the center. They reach the black color at the top and bottom edges of the image.

The variable r which holds the distance from the center of the image is measured in pixels, so its value at the centers of the top and bottom edges is half the height of the image, i.e. H/2. If we scale this down to 1, it's much easier to work with, so we'll use r/(H/2). This expression's value is 0 at the center of the image and increases with the distance from the center. It reaches 1 exactly where we want the color to be solid black. However, at greater distances from the center it grows larger than 1, which we don't want, so we limit it with the function min. This function takes two arguments and returns the smaller of the two. Hence, min(r/(H/2),1) never exceeds 1. (There's also a function max, which returns the larger of its two arguments.)

Given the color of a pixel in the original image and its transformed (as above) distance from the center, we can now figure out what to do. If the transformed distance is 0 (in the center) we want the original color unchanged. If it's 1, we want the color black. We can reach that effect by multiplying the three color components of the pixel by 1 minus the transformed distance, i.e. 1-min(r/(H/2),1).

We can use the functions red, green, and blue to access the components of a color. Now we could write the red component of our output image as red(origValXY(x,y))*(1-min(r/(H/2),1)). We'd have to use equivalent expressions for the green and blue components and then use them as arguments to rgbColor. By assigning the values origValXY(x,y) and 1-min(r/(H/2),1) to variables, which we call p and d (you can choose any name you like, as long as it's not the name of a built-in constant or variable or a keyword; consult the MathMap reference for the names of all those), we can write the resulting expression as rgbColor(red(p)*d,green(p)*d,blue(p)*d). The complete expression is:

p=origValXY(x,y);
d=1-min(r/(H/2),1);
rgbColor(red(p)*d,green(p)*d,blue(p)*d)

As you can see, assigning values to variables is very straightforward. You must separate variable assignments and other expressions with semicola.

By the way: Using more advanced features of MathMap you can write an expression equivalent to the above as

lerp(r/Y,origVal(xy),grayColor(0))

So, please go on reading, there's more to come.

Next topic: User Values