Sunday, September 25, 2011

Class 4: Arrays, Functions and using Images

Today's class will cover two very important concepts: Arrays and Functions. Afterwards, I will show you how use images in your sketches.

An array is a list or group of data. You can have an array of any type of data. For example, you want to move 10 rectangles around the screen using random incremental movements between -1 and 1(brownian motion). Instead of creating 10 variables for the x location and 10 for the y location, you can use two arrays, one for the x locations and 1 for the y locations. All of the variables are the same type and their purpose is the same.

Each variable(variables in an array are referred to as elements) in an array is associated with an index number that describes in position in the array. The first element in an array is [0] and the second is [1] and so on. When you create an array you must identify the length or number of elements in the array. You cannot access a value higher than the length of an array. If you try you will receive the Null Pointer error.

Arrays are a little different to create than normal variables. Here are a few ways to create them:
int[] numbers = new int[3];// creates an int array of 3 empty elements
int[] numbers = {10,20,30};// creates an int array of 3 elements and sets values

The power of arrays really comes to life when you use them in combination with for loops. A for loop can increment which element is being accessed/used and you can set the 'test' of the for loop to the length of the array. Every array has a variable that stores its length, the total number of elements. It can be accessed like this, arrayName.length.
int[] numbers = {10,20,30};// creates an int array of 3 elements and sets values
for(int i = 0; i < numbers.length; i++){
    println(numbers[i]);
}
// prints 10 20 30 each on their own line

Functions
Functions are a way of compartmentalizing code. Functions allow you to reuse code without having to copy and paste lines in multiple areas of your code. For example, switching back and forth from a white stroke and black fill to a black stroke and white fill.
stroke(255);
fill(0);
// to…
stroke(0);
fill(255);
Instead of having to copy and paste two lines of code each time, you could write two functions and call those commands in one line of code.
void whiteStrokeBlackFill(){
stroke(255);
fill(0);
}
// and…
void blackStrokeWhiteFill(){
stroke(0);
fill(255);
}
// to execute the functions…
whiteStrokeBlackFill();// turns the stroke to white and the fill to black
blackStrokeWhiteFill();// turns the stroke to black and the fill to white
();// turns the stroke to white and the fill to black

You can increase the usefulness of a function by setting values when you run the function. These values are called parameters. Parameters can be any data type. Here is an example:
void printNumber(int num){
println("number = " + num);
}

Sunday, September 18, 2011

Class 3: For Loops, new Shapes and more Math!!!

Hello 3rdWard! I hope you had a great week and are ready of another action packed class of Processing.

Today we are going to be focusing on a very important concept: For Loops.

What is a for loop? A for loop is a way of repeating the same commands a specified number of times.
What does it look like? It looks like this:
for(init; test; update){
statements
}
How does a for loop work? The parenthesis setup the structure of a for loop by defining the init, test, and update. The statements inside the block(a block is defined as the arguments inside curly braces{}) run continously as long as the test evaluates as true. The init assigns the initial value of the variable used in the test. The update is used to modify the variable after each iteration of the block. A for loop works like this:
1. The init statement is run
2. The test is evaluated to true or false
3. If the test is true, continue to step 4. If the test is false, jump to step 6
4. Run the statements within the block
5. Run the update statement and jump to step 2
6. Exit the structure and continue running the program

For Loops are very useful in programming graphics as they allow you to make many many iterations very easily.

Shapes:

Here are some cheat sheets that will break down the order in which you need to state your vertices to create a shape the way you want to.


Sunday, September 11, 2011

Processing Class 2: Variables, Math, and Logic

Hello everybody. I want to start off this week by taking a look at the awesome self portraits and monsters you all made. Congratulations, you are officially programmers now :) You successfully created compositions using the shape primitives, changing both the stroke(outline) and fill(shape) colors and mastered the idea of the coordinate system that is in place in Processing. This is not trivial, you have created meaning and subject with math as your tools. The reason I wanted all of you to create an annoyingly tedious character is so you develop an understanding of the coordinate system as well as the way in which order of commands changes composition and a familiarity with the shape building blocks. Next weeks homework will be to add a level of interaction to your monster/self portrait. I will go into this in more detail later….muwahhhahh.

Break down for what you will understand at the end of this class:
You will understand how to setup your sketches to allow for animation and interaction.
You will understand how to create variables, assign values to them and recall those values.
You will understand how to use mathematical operators(+,-,/,*,%, and more) allowing you to use math to arrive at values.
You will understand how to use conditional structures to control the flow of your programs.

As with last week, we are going to take a look at examples that come with Processing. This way you will be able to review when you are home as well as follow along on your machine in class.

Setting up your sketch
Last week we learned how to create a basic sketch in Processing. These sketches only display one frame that never changes. From now on we are going to be interested in multiple frames, because that way we can create animation and interaction.

Here is how I want you to setup your sketches from now on:

/*****************************************
* Header Title: elaborate the title here
* more details of sketch here
* include any credits to other people
* Your Name - date when created
*****************************************/

// declare your variables here

// setup() only happens once at the beginning of the sketch
void setup(){
// this is where you set the initial properties
size( 400, 400 );// size() should always go inside setup()
smooth();// smooth() usually only needs to go here
}

// draw() happens over and over and over
void draw(){
background(0);// apply the background first
// now draw or evaluate anything you want
}

* note: blogger lost the rest of lesson so I will be borrowing from Ben and Casey for the short term. I will go back and change this so as to not be directly using there words. But for now...
Data and Variables
What is data? Data often consists of measurements of physical characteristics. For example, Casey’s California driver’s license states his sex is M, his hair is BRN, and his eyes are HZL. The values M, BRN, and HZL are items of data associated with Casey. Data can be the population of a country, the average annual rainfall in Los Angeles, or your current heart rate. In software, data is stored as numbers and characters. Examples of digital data include a photograph of a friend stored on your hard drive, a song downloaded from the Internet, and a news article loaded through a web browser. Less obvious is the data continually created and exchanged between computers and other devices. For example, computers are continually receiving data from the mouse and keyboard. When writing a program, you might create a data element to save the location of a shape, to store a color for later use, or to continuously measure changes in cursor position.

Data types
Processing can store and modify many different kinds of data, including numbers, letters, words, colors, images, fonts, and boolean values (true, false). The computer stores each in a different way, so it has to know which type of data is being used to know how to manage it. For example, storing a word takes more room than storing one letter; therefore, storing the word Cincinnati requires more space than storing the letter C. If space has been allocated for only one letter, trying to store a word in the same space will cause an error. Every data element is represented as sequences of bits (0s and 1s) in the computer’s memory. For example, 01000001 can be interpreted as the letter A, and it can also be interpreted as the number 65. It’s necessary to specify the type of data so the computer knows how to correctly interpret the bits.
Numeric data is the first type of data encountered in the following sections of this book. There are two types of numeric data used in Processing: integer and floating- point. Integers are whole numbers such as 12, -120, 8, and 934. Processing represents integer data with the int data type. Floating-point numbers have a decimal point for creating fractions of whole numbers such as 12.8, -120.75, 8.125, and 934.82736. Processing represents floating-point data with the float data type. Floating-point numbers are often used to approximate analog or continuous values because they have decimal
37resolution. For example, using integer values, there is only one number between 3 and 5, but floating-point numbers allow us to express myriad numbers between such as 4.0, 4.5, 4.75, 4.825, etc. Both int and float values may be positive, negative, or zero.
The simplest data element in Processing is a boolean variable. Variables of this type can have only one of two values—true or false. The name boolean refers to the mathematician George Boole (b. 1815), the inventor of Boolean algebra—the foundation for how digital computers work. A boolean variable is often used to make decisions about which lines of code are run and which are ignored.
The following table compares the capacities of the data types mentioned above with other common data types:
Name Size Value Range
boolean 1 bit true or false
byte 8 bits -128 to 127
char 16 bits 0 to 65535
int 32 bits -2,147,483,648 to 2,147,483,647
float 32 bits 3.40282347E+38 to -3.40282347E+38
color 32 bits 16,777,216 colors

Variables
A variable is a container for storing data. Variables allow a data element to be reused many times within a program. Every variable has two parts, a name and a value. If the number 21 is stored in the variable called age, every time the word age appears in the program, it will be replaced with the value 21 when the code is run. In addition to its name and value, every variable has a data type that defines the category of data it can hold.
A variable must be declared before it is used. A variable declaration states the data type and variable name. The following lines declare variables and then assign values to the variables:
int x;// Declare the variable x of type int
float y;// Declare the variable y of type float
boolean b;// Declare the variable b of type boolean
x = 50;// Assign the value 50 to x
y = 12.6;// Assign the value 12.6 to y
b = true;// Assign the value true to b

As a shortcut, a variable can be declared and assigned on the same line:
int x = 50;
float y = 12.6;
boolean b = true;

More than one variable can be declared in one line, and the variables can then be assigned separately:
float x, y, z;
x = -3.9;
y = 10.1;
z = 124.23;
When a variable is declared, it is necessary to state the data type before its name; but after it’s declared, the data type cannot be changed or restated. If the data type is included again for the same variable, the computer will interpret this as an attempt to make a new variable with the same name, and this will cause an error:

int x = 69; // Assign 69 to x
x = 70; // Assign 70 to x
int x = 71; // ERROR! The data type for x is duplicated

The = symbol is called the assignment operator. It assigns the value from the right side of the = to the variable on its left. Values can be assigned only to variables. Trying to assign a constant to another constant produces an error:
// Error! The left side of an assignment must be a variable
5 = 12;
When working with variables of different types in the same program, be careful not to mix types in a way that causes an error. For example, it’s not possible to fit a floating- point number into an integer variable:
// Error! It’s not possible to fit a floating-point number into an int
int x = 24.8;

float f = 12.5;
// Error! It’s not possible to fit a floating-point number into an int
int y = f;

Variables should have names that describe their content. This makes programs easier to read and can reduce the need for verbose commenting. It’s up to the programmer to decide how she will name variables. For example, a variable storing the room temperature could logically have the following names:
t
temp
temperature
roomTemp
roomTemperature

Processing also includes a few variables that are specific to the sketch. Two we will be using are width and height. Width stores the value of the width of the sketch and height stores the height of the sketch.

Math: Arithmetic

In programming, the visual properties of an image on the screen are defined by numbers, which means that the image can be controlled mathematically. For example, a rectangle might have a horizontal position of 10, a vertical position of 10, a width and height of 55, and a gray value of 153. If the gray value is stored in the variable grayVal and 102 is added to this variable, the gray value will become 255 and the shape will appear white on screen.


The +, -, *, /, and = symbols are probably familiar, but the % is more exotic. The % operator calculates the remainder when one number is divided by another. The %, the code notation for modulus, returns the integer remainder after dividing the number to the left of the symbol by the number to the right.


Modulus can be explained with an anecdote. After a hard day of work, Casey and Ben were hungry. They went to a restaurant to eat dumplings, but there were only 9 dumplings left so they had to share. If they share equally, how many dumplings can they each eat and how many will remain? It’s obvious each can have 4 dumplings and 1 will remain. If there are 4 people and 35 dumplings, each can eat 8 and 3 will remain. In these examples, the modulus value is the number of remaining dumplings.

The modulus operator is often used to keep numbers within a desired range. For example, if a variable is continually increasing (0, 1, 2, 3, 4, 5, 6, 7, etc.), applying the modulus operator can transform this sequence. A continually increasing number can be made to cycle continuously between 0 and 3 by applying %4:
x 0 1 2 3 4 5 6 7 8 9 10
x%4 0 1 2 3 0 1 2 3 0 1 2


When working with mathematical operators and variables, it’s important to be
aware of the data types of the variables you’re using. The combination of two integers will always result in an int. The combination of two floating-point numbers will always result in a float, but when an int and float are operated on, the result is a float.

Integer values can be assigned to floating-point variables, but not vice versa. Assigning a float to an int makes the number less accurate, so Processing requires that you do so explicitly. Working with an int and a float will upgrade the int and treat both numbers as floating-point values, but the result won’t fit into an int variable.


Operator precedence, Grouping
The order of operations determines which math operators perform their calculations before others. For example, multiplication is always evaluated before addition regardless of the sequence of the elements. The expression 3 + 4 * 5 evaluates to 23 because 4 is first multiplied by 5 to yield 20 and then 3 is added to yield 23. The order of operations specifies that multiplication always precedes addition regardless of the order in which they appear in the expression. The order of operations for evaluating expressions may be changed by adding parentheses. For example, if an addition operation appears in parentheses, it will be performed prior to multiplication. The expression (3 + 4) * 5 evaluates to 35 because 3 is first added to 4 to yield 7, which is then multiplied by 5 to yield 35. This is more concisely expressed in code:
x = 3 + 4 * 5; // Assign 23 to x
y = (3 + 4) * 5; // Assign 35 to y
In many cases, parentheses are necessary to force elements of an expression to evaluate before others, but sometimes they are used only to clarify the order of operations. The following lines calculate the same result because multiplication always happens before addition, but you may find the second line more clear.
x = 10 * 20 + 5; // Assign 205 to x
y = (10 * 20) + 5; // Assign 205 to y
The following table shows the operator precedence for the operators introduced so far. Items at the top precede those toward the bottom.

Multiplicative * / %
Additive + -
Assignment =

Decisions and Controlling Flow of Programs

The programs we’ve seen so far run each line of code in sequence. They run the first line, then the second, then the third, etc. The program stops when the last line is run. It’s often beneficial to change this order—sometimes skipping lines or repeating lines many times to perform a repetitive action. Although the lines of code that comprise a program are always positioned in an order from top to bottom on the page, this doesn’t necessarily define the order in which each line is run. This order is called the flow of the program. Flow can be changed by adding elements of code called control structures.
Relational expressions
What is truth? It’s easy to answer this difficult philosophical question in the context of programming because the logical notions of true and false are well defined. Code elements called relational expressions evaluate to true and false. A relational expression is made up of two values that are compared with a relational operator. In Processing, two values can be compared with relational operators as follows:

Expression Evaluation
3> 5 false
3< 5 true
5< 3 false
5> 3 true

Each of these statements can be converted to English. Using the first row as an example, we can say, “Is three greater than five?” The answer “no” is expressed with the value false. The next row can be converted to “Is three less than five?” The answer is “yes” and is expressed with the value true. A relational expression, two values compared with a relational operator, evaluates to true or false—there are no other possible values. The relational operators are defined as follows:

Operator Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equivalent to
!= not equivalent to

The following lines of code show the results of comparing the same group of numbers with different relational operators:
println(3 > 5); // Prints "false"
println(5 > 3); // Prints "true"
println(5 > 5); // Prints "false"
println(3 < 5); // Prints "true"
println(5 < 3); // Prints "false"
println(5 < 5); // Prints "false"
println(3 >= 5); // Prints "false"
println(5 >= 3); // Prints "true"
println(5 >= 5); // Prints "true"
println(3 <= 5); // Prints "true"
println(5 <= 3); // Prints "false"
println(5 <= 5); // Prints "true"

The equality operator, the == symbol, determines whether two values are equivalent. It is different from the = symbol, which assigns a value, but the two are often used erroneously in place of each other. The only way to avoid this mistake is to be careful. It’s similar to using “their” instead of “there” when writing in English—a mistake that even experienced writers sometimes make. The != symbol is the opposite of == and determines whether two values are not equivalent.
println(3 == 5); // Prints "false"
println(5 == 3); // Prints "false"
println(5 == 5); // Prints "true"



println(3 != 5); // Prints "true"
println(5 != 3); // Prints "true"
println(5 != 5); // Prints "false"


Conditionals
Conditionals allow a program to make decisions about which lines of code run and which do not. They let actions take place only when a specific condition is met. Conditionals allow a program to behave differently depending on the values of their variables. For example, the program may draw a line or an ellipse depending on the value of a variable. The if structure is used in Processing to make these decisions:
if (test) { statements
}
The test must be an expression that resolves to true or false. When the test expression evaluates to true, the code inside the { (left brace) and } (right brace) is run. If the expression is false, the code is ignored. Code inside a set of braces is called a block.


Logical operators
Logical operators are used to combine two or more relational expressions and to invert logical values. They allow for more than one condition to be considered simultaneously. The logical operators are symbols for the logical concepts of AND, OR, and NOT:
Operator Meaning
&& AND
|| OR
! NOT

The following table outlines all possible combinations and the results.
Expression Evaluation
true && true true
true && false false
false && false false
true || true true
true || false true
false || false false
!true false
!false true

Sunday, September 4, 2011

Processing Class 1: Hello World!

Let me start off by saying I am super excited to teach you all Processing. I have been wanting to teach Processing to a group for awhile now and I am finally getting the chance. That said, lets get to it.

Getting Started:
What is Processing? Processing is an environment for programming graphics that was designed to be friendly to non programmers, yet still offer power to advanced users. It was originally created by Ben Fry and Casey Reas but has been contributed to by hundreds of users world wide. Under the hood, Processing is based on Java and any Java code can be implemented along with Processing code. In fact, Processing handles wrapping a ton of Java to make it super easy for you to get up and running without a lot of hassle. For this reason Processing files are called sketches, to relay the ideology of a quick coding attempt at a problem or idea. Don't let the term sketch fool you, a Processing sketch can be a full fledged application written in thousands of lines of code, but it can also only be one line.

What are we going to cover today:
Get to know the Processing Website and all it has to offer.

After we review the website we will get to know the Processing development environment. This is where you will create your Processing sketches.

Then we will get our hands wet with Processing by going over the examples that I have loaded to your Documents/Processing/Class_1 folder.

These images correspond to the sketches that we will be reviewing. The orange notes were included using illustrator and will not reflect in the sketch when you run it.

  1. background(0);
  2. ellipse(250, 250, 200, 200);
  3. rect(200, 200, 100, 100);



  1. point(50, 50);
  2. line(100, 50, 200, 50);
  3. curve(200, 50, 300, 50, 450, 100, 450, 300);
  4. rect(50, 100, 200, 300);
  5. ellipse(350, 150, 100, 100);
  6. triangle(300, 400, 300, 250, 450, 325);
  7. quad(38, 431, 486, 420, 469, 463, 30, 476);



  1. white/black
  2. black/white
  3. none/black
  4. red/none
  5. green/red
  6. blue/green
  7. olive/mint green
  8. brown/white
  9. khaki/orange



  1. strokeWeight(0.1);
  2. strokeWeight(5);
  3. strokeWeight(20);
  4. strokeJoin(MITER);
  5. strokeJoin(BEVEL);
  6. strokeJoin(ROUND);
  7. strokeCap(SQUARE);
  8. strokeCap(PROJECT);
  9. strokeCap(ROUND);




For further learning I highly recommend the book that was written by the creators, Processing: A Programming Handbook for Visual Designers and Artists.

For homework, please post at least one sketch to the class group on OpenProcessing.org. The requirements are to make a self portrait or a monster. Here is the class group.