Programming Fundamentals with Processing
© 2012-2018 Mithat Konar.
All rights reserved.
Part One
Part Two
Part Three
- Action
- Interaction
- Bundling Stuff Up II
Misc and cruft
- Needs a place
- strings and string processing (Appendix?)
© 2012-2018 Mithat Konar.
All rights reserved.
Program structure and output
In programming, the stuff you “write” when you “write” a program is called source code. It almost always consists of plain, simple text.1) The source code you write is stored in files called source code files—sometimes shortened to simply sources or code. Thus, source code files are text files made up of sets of instructions written in a particular programming language that express what you'd like the program to do.
Some languages start executing a program at the first bit of program text that is in the program's source code file. Other languages start a program's execution at some magical point in the code that someone needs to tell you about—that is, they begin at a predefined entry point. Processing is actually both.
Below is one of the simplest Processing programs you can write. When executed, it will print an important message about cranberries.2)
println("Cranberries are high in antioxidants.");
This is an example of a program written in what Processing calls its Basic Mode. In Basic Mode, the program's execution will begin at the first statement in the source code file. It will then continue statement-by-statement until it reaches the end of the file.
Here's a program with two statements:
println("Cranberries are high in antioxidants."); println("Some blueberries too.");
Processing's Basic Mode is an extremely easy way to program. However, the rules of Basic Mode state that you are not allowed to define any functions in Basic Mode—which as we shall see later is quite a serious limitation. Therefore, for the remainder of this text we are going to pretend that Processing's Basic Mode doesn't exist and focus entirely on what Processing calls its Continuous Mode. We describe that next.
Processing will automatically switch to Continuous Mode when you define at least one function in your program. (This is why you are not allowed to define functions in Basic Mode.) In Continuous Mode, Processing will look for a definition of a function called setup
, and it will use this function as the point where the program's execution begins. Below is the Continuous Mode equivalent of the Basic Mode example above.
void setup() { println("Cranberries are high in antioxidants."); }
This program consists of a definition of the setup
function that has only one statement in it. If you run this program, you will discover that it too prints out an important message about cranberries.
The basic structure of the setup
function definition without any other code is:
void setup() { }
The code that is written between the pair of curly braces is called the body of the setup
function.
We will talk in greater depth about functions in a few chapters. For now, what you need to know is that in a typical Processing program, while you might find program code before the line
void setup() {
and/or after the matching }
,
the program will actually start at the first statement in the setup
function's body, that is, the first bit of code after
void setup() {
The line
println("Cranberries are high in antioxidants.");
is an example of a program statement. A program statement is the smallest complete executable element in a programming language.3) Program statements are analogous to sentences in natural languages. In Processing, a semicolon is used to mark the end of a statement. If you try executing any of the programs above without the semicolons at the end of the statements, the Processing compiler won't know that it has reached the end of a statement and will get confused when it tries to understand the remainder of the code.
In the above example, the setup
function has only one statement in it. Typically, your program's setup
function will have many more:
void setup() { println("Cranberries are high in antioxidants."); println("Chickpeas are high in tryptophan."); println("Tomatoes are high in lycopene."); }
If a statement is the programming equivalent of a sentence, why are semicolons used to mark the end of statements rather than periods?
The biggest reason for this is that the language of the platform in which Processing is built, Java, uses semicolons to mark the end of statements. But why does Java do this? Because the language on which a lot of Java syntax is based, C++, also uses semicolons. Why does C++ do this? Because … , you get the idea.
The language ALGOL, whose development began in the late 1950's, may have been the first language to use the semicolon as the statement terminator. While the semicolon is widely used for this purpose, you should note that this is by no means universal.
One of the things that makes the semicolon well-suited to marking the end of statements is that the semicolon has little semantic value otherwise. A period, as used by many languages to mark the end of sentences, is commonly also used with floating point numbers (e.g., 3.14159, 22.5, 98.6), and so marking the end of program statements with a period would mean that whatever tries to understand the code you're written would have to do additional work to figure out whether the dot means “end of statement” or “decimal point.”4)
You might now be asking why you need to mark the end of a statement all. Isn't it obvious that the statement ends at the end of the line? Some languages actually do this. There are advantages and disadvantages either way, which you might gain an appreciation for when we cover the subject of whitespace. The debate over which is indeed “better” can be counted as one of the many religious wars in programming.
Program statements and other things written a programming language are well-suited for getting your program to do what you want. That's their whole purpose! And if you write your programs using good style, which we hope you'll learn how to do throughout this book, your programs should be relatively straight-forward for someone with a decent knowledge of the programming language to understand.
However, there will be times when you will want to include text in your code just to help human readers. For example, you might want to include some information about who authored the program, when it was written, licensing information, etc. That is what comments are for.
There are three ways to write comments in Processing: the “standard” comment, the multi line comment, and the doc comment.
The most common syntax for creating comments in Processing is to use a double forward slash: //
. Anything that comes after a double slash up to the end of the line is a comment and will be ignored by the Processing compiler. Here a version of the cranberries2.pde
program with some added some comments to identify the author and other information and explain some of the code:
// The Most Spectacular Program Ever // Mithat Konar // Aug 19, 2017 void setup() { // advise the user about nutrition: println("Cranberries are high in antioxidants."); println("Chickpeas are high in tryptophan."); println("Tomatoes are high in lycopene."); println("OK?"); // confirm with the user. }
This comment type also sometimes called the single line comment.
The limitation with the “standard” comment above is that its awkward to use it to write a comment that should cover many lines.
// A really awesome program // by Sora Antimony // Creates a pretty picture with lots of // unicorns and rainbows. The unicorns // dance.
For situations like this, the multiline comment is often a better option. A multiline comment starts with /*
and ends with */
— even if the closing */
is several lines down.
/* A really awesome program
by Sora Antimony
Creates a pretty picture with lots of
unicorns and rainbows. The unicorns
dance. */
A bit of formatting can make it pretty:
/* A really awesome program
by Sora Antimony
Creates a pretty picture with lots of
unicorns and rainbows. The unicorns
dance.
*/
or
/*
* A really awesome program
* by Sora Antimony
* Creates a pretty picture with lots of
* unicorns and rainbows. The unicorns
* dance.
*/
The doc comment is a special case of the multiline comment. It's short for “documentation comment.” Its rules and behavior are identical to the multiline comment with one important difference: There is a tool available to Java programs (the platform on which Processing is based) called javadoc
that when applied to a source file will find all the doc comments and produce nicely formatted and pretty documentation from them.
To turn a mutiline comment into a doc comment, just add an additional *
in the opening tag:
/* I'm a multiline comment, even though I really only take up one line. */ /** I'm a doc comment. I'm so special that the javadoc tool will read me and extract my precious info. */
We won't go any deeper into the when and why of doc comments as it's a bit of an advanced subject. But it's important to mention them here as you will probably see other people's code that uses them.
Programmers call the results produced by a program its output. Processing renders output primarily to two different places: the console and the canvas. We discuss each of these below.
A console in computing is a window or some other entity that is used for text-based interaction. About the time dinosaurs were being converted to oil, text-based interfaces using consoles were the dominant sort of user interfaces used in computing. In modern computing, the graphical user interface has replaced the console as the dominant form of interaction with the user. However, it is something of a dirty little secret that consoles still exist for many GUI programs—they are just hidden by default.
People who write GUI-based programs typically use the console as a place to show extra information that normally wouldn't interest a user, for example additional error and warning messages. Such messages can often help to diagnose a problem with the program.5)
There is a console built into the Processing IDE should you want to use it. It's the dark box toward the bottom of the window. If it ever becomes hidden, you can activate it by clicking on the “Console” tab. This means when you run a Processing program from the Processing IDE, you will be able to see and use the console without having to do any extra work.
Sending text messages to the console can be accomplished with two predefined Processing functions: print
and println
.
Here is an example of a Processing program that uses println
to output a message to the console:
void setup() { println("Cranberries are high in antioxidants."); }
The above code consists of a definition of the setup
function in which there is a call to or invocation of the println
function. The program will produce the following console output when you run it:
Cranberries are high in antioxidants.
Notice the double quotation marks around the text. These are important. They tell println
that everything between them is a string of text characters that should be treated as a unit.
The println
function will print what you ask it to print and then move the cursor (the point where the next bit of text will be printed) to the beginning of a new line. In other words, println
is short for “print line”. The print
function on the other hand prints what you ask it to print and then places the cursor immediately at the end of what it printed.
The difference between println
and print
can be readily understood by examining the examples below.
Using println
:
void setup() { println("Cranberries "); println("are "); println("high in "); println("antioxidants."); }
will output:
Cranberries are high in antioxidants.
Using print
:
void setup() { print("Cranberries "); print("are "); print("high in "); print("antioxidants."); }
produces the following console output:
Cranberries are high in antioxidants.
The functions print
and println
can also be used to print out numbers and the results of calculations:
void setup() { println(63); }
or
void setup() { println(63+11); }
You can mix things up:
void setup() { print("Sixty-three plus eleven"); print(" is "); print(63+11); }
Notice that when you place double quotes around a calculation, it does not do the math:
void setup() { print("63+11"); print(" is "); print(63+11); }
You are probably used to using computer programs where you enter some data and the program does something with it. For example, you might have used a program that outputs your astrological chart based on what you have entered as your birth date and time. While text-based user interaction is a common feature in programming languages, Processing wasn't really designed for this kind interaction. As a result, doing this kind of thing in Processing isn't nearly as straightforward as it is in most other languages.
But don't take this to mean that Processing wasn't designed for writing interactive programs! There are many kinds of interaction that Processing makes very simple–text-based interaction just isn't one of them.
Because text-based input is as involved as it is in Processing, we will avoid it in this text. We will, however, work with some of the interaction features that Processing makes very easy when we cover event handling.
The console in Processing is typically used for printing out diagnostic and similar information; rarely is it used as the primary form of output. Most people who use Processing use do so because they want graphical output. Processing uses its canvas for this.6)
You will recognize the canvas as the inner box that's inside the window that has been popping up when you've been working with console output.
The Processing canvas consists of a two-dimensional space that is addressed using x and y coordinates. The origin of the canvas (0, 0) is in the upper left corner. A positive x value moves the referenced point to the right, and positive y values move the point down.
You can draw rectangles on the canvas with the rect
function.
The rect
function is an example of a function that accepts multiple parameters or arguments—values that are passed into a function for it to use. In Processing, parameters are placed inside the parenthesis of a function call and if there is more than one parameter, they must be separated with commas.
The rect
function takes four parameters: the first two specify where to draw it; that is, the x and y coordinates of the upper left corner on the canvas. The next two specify the size as width and height in pixels.7)
The following code will draw a rectangle whose upper left corner is in the upper left corner of the canvas. The rectangle will be 40 pixels wide and 20 pixels high.
void setup() { rect(0, 0, 20, 10); }
To draw a larger rectangle, you might write:
void setup() { rect(0, 0, 48, 24); }
To draw the same rectangle 5 pixels to the right and 10 pixels lower, you would write:
void setup() { rect(5, 10, 48, 24); }
To draw more than one rectangle, just make more than one call to the rect
function. They will be drawn in the order you write them.
void setup() { rect(0, 0, 48, 24); rect(5, 10, 48, 24); }
or
void setup() { rect(0, 0, 48, 24); rect(5, 10, 48, 24); rect(10, 20, 48, 24); }
We have used integers only as parameters above. However, Processing will also accept floating-point numbers (e.g., 16.67
) for any of the parameter values as well.
Processing's ellipse
function is used to draw ellipses and circles. The order and meaning of parameters is essentially the same as for the rect
function: x position, y position, width, and height. However, in the ellipse
function, the x and y position values refer to where the origin (i.e., center) of the ellipse is.8)
Thus, to draw a circle with diameter of 40 pixels so that it fits into the top corner of the canvas, you would write:
void setup() { ellipse(20, 20, 40, 40); }
To change this to an ellipse that is 48 pixels wide and 24 pixel tall:
void setup() { ellipse(24, 12, 48, 24); }
To move the origin of the ellipse to the upper-left corner of the canvas (i.e,. 3/4 of the ellipse is off the canvas):
void setup() { ellipse(0, 0, 48, 24); }
To draw more than one ellipse, just make more than one call to the ellipse
function. They will be drawn in the order you write them.
void setup() { ellipse(20, 20, 24, 24); ellipse(25, 25, 24, 24); ellipse(30, 30, 24, 24); }
or
void setup() { ellipse(24, 12, 48, 24); ellipse(24, 12, 32, 16); ellipse(24, 12, 16, 8); }
Again, parameter values may be integers of floating-point numbers.
To draw lines, you can use, you Processing's, guessed it, line
function. The line
function has four parameters: starting x coordinate, starting y coordinate, ending x coordinate, ending y coordinate.9)
void setup() { line(10, 10, 20, 40); line(30, 10, 40, 40); line(50, 10, 60, 40); line(70, 10, 80, 40); }
As was the case for rectangle
and ellipse
, the parameter values you provide to the line
function can be floating point values as well.
Processing provides a lot more control over what you can draw and how (including rendering images and graphic versions of text), but for the remainder of this text we will limit ourselves to the above elements.
You will have noticed that so far everything that Processing has drawn has been on a grey background using one pixel wide black lines and white filling. All of these can be changed.
The color of the canvas' background can be changed by using the background
function. The width, color and other properties of lines and borders is set with the strokeWeight
, stroke
and noStroke
functions. You can change the way shapes are filled with the fill
and noFill
functions. To change any of these, call the functions with the desired parameters before calling the function that draws the shape.
The following program draws a red and green circles with 2 pixel borders on a blue background.
void setup() { // set the background color using an RGB values background(64, 64, 128); // make the pen two pixels wide strokeWeight(2); // make the pen red color using RGB values stroke(255, 0, 0); // make shapes fill with a dark red color using RGB values fill(192, 0, 0); ellipse(30, 30, 50, 50); // make the pen red color using RGB values stroke(0, 255, 0); // make shapes fill with a dark green color using RGB values fill(0, 192, 0); ellipse(70, 70, 50, 50); }
In keeping with the spirit of this text being about programming concepts rather than the Processing language, we will not delve into this any further at this point. If you want to learn more, everything you need to know about these (and more!) is simply and concisely documented on the Processing reference Web pages (http://processing.org/reference/) under the Color and Attributes headings.
The default size of Processing's canvas is 100 by 100 pixels. This is rarely the size you actually want the canvas to be. Fortunately, it's really easy to change the size of the canvas to something else using Processing's built-in size
function. The most common way to invoke the size
function is with two parameters: the first specifies the width (in pixels) of the canvas, the second the height (in pixels):
void setup() { size(320,180); // The rest of your code goes here ... // }
Aaah … that's better. Now we have some room to work.
The call to the size
function doesn't need to be the first statement in the setup
function, but in this case it makes it easier for the reader if it is.
rectMode()
function.
ellipseMode()
function.