# Processing Basics

### **What is Processing?**

Processing was designed specifically for use with audiovisual media and arts. It has been developed since 2001 at MIT (Boston/USA) under the direction of Ben Fry and Casey Reas (later also Daniel Shiffman). Processing represents a simplified form of the programming language Java, and was developed to program visual elements and interaction. Accordingly, Processing's target audience consists primarily of designers and artists, who are first and foremost artists and only secondarily programmers. Over the years, several other projects have emerged from Processing, the best known of which is certainly the Arduino hardware project, whose programming environment is based on Processing. Recent updates in Processing itself represent special modes of the development environment, which make it possible to develop for web browsers in [JavaScript-Modus](http://processingjs.org/), for [→ Android-Devices](http://android.processing.org/) or in [→ Python](http://py.processing.org/).



<figure><img src="https://510937649-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjQUmn9q3i7gpMtKYvCss%2Fuploads%2Fzu6lLg6ni43HSVx4i0zs%2Fprocessing-ecosystem.png?alt=media&#x26;token=4378fb63-ebd6-40ee-872f-60928a8fa5ec" alt="" width="375"><figcaption><p>Figure: History of the Processing projects</p></figcaption></figure>

**Pros**

* Open Source
* Availability, accessability
* Based on Java, the knowledge learned can therefore also be used in Java and Android devices
* Available on all major desktop operating systems
* Exists for over 20 years, therefore many libraries and good documentation

**Cons**

* Some things are not available "out of the box" and you might have to develop them yourself
* Java needs its runtime environment and is less fast than e.g. C++

### **The IDE (integrated development environment) of Processing**

#### The sketch window



<figure><img src="https://510937649-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjQUmn9q3i7gpMtKYvCss%2Fuploads%2FCFmfa5hZFtjNDgu5z2rt%2Fsketchfenster.png?alt=media&#x26;token=97a4f2bc-c171-49d1-a2f6-29851e4b0904" alt="" width="375"><figcaption><p>Figure – Processing's sketch window</p></figcaption></figure>

An overview of the basic functions can also be found here on the Processing website: [→ Environment](https://processing.org/environment)



<figure><img src="https://510937649-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjQUmn9q3i7gpMtKYvCss%2Fuploads%2FnUHE9ubd4dX83GHlkThL%2Fausgabefentster.png?alt=media&#x26;token=d917076b-579b-446c-8a7a-3c6834a30c2b" alt=""><figcaption><p>Figure – Processing's default output window</p></figcaption></figure>

#### The output window

Besides the sketch window, Processing provides an output window, which opens automatically when you press the Run button. It shows the program that was previously created in the sketch window, in the example below these are just two simple lines:

The size of the output window is defined by the function `size()`. \
\
Fullscreen output is achieved by `fullScreen(DISPLAY);` where DISPLAY is an integer indicating if the sketch should run in fullscreen on the internal screen or on a second screen/video-projector.



### Basic structure **of a processing sketch**

Processing programs are called "sketches". Each sketch sits in its own folder. This folder is created automatically by Processing and is given the same name that was defined for the sketch when it was saved.

Starting coding with Processing ist easy. To write a program you can just type some lines of code:

```java
size(690, 200);  
// Set the canvas size to 690 pixels wide and 200 pixels high

background(255); 
// Set the background color to white (255 is the maximum brightness for white)

noFill();        
// Disable filling shapes (any shapes drawn won't have an interior color)

stroke(150);     
// Set the stroke (outline) color to gray (150 is a medium shade of gray)

strokeWeight(1); 
// Set the thickness of the stroke (outline) to 1 pixel

rect(0, 0, 690, 199); 
// Draw a rectangle starting at the top-left corner (0,0)
// with a width of 690 and height of 199 pixels

fill(100, 200, 0, 100); 
// Set the fill color to a semi-transparent green 
// (RGB: 100, 200, 0) and 100 is the alpha value (transparency)

stroke(0);        
// Set the stroke (outline) color to black

strokeWeight(20); 
// Set the thickness of the stroke (outline) to 20 pixels

ellipse(345, 100, 80, 80); 
// Draw a circle (ellipse) with a center at (345, 100)
// and a width and height (diameter) of 80 pixels

```



However, a typical program in Processing consists of the two functions `setup()` and `draw()` (an explanation of what functions exactly are follows below):



```java
void setup() 
// The setup() function runs once when the program starts
{
   println("start"); 
   // Print the word "start" to the console when the program begins
}

void draw() 
// The draw() function continuously executes the lines of code inside it
// It runs repeatedly in a loop until the program is stopped
{
   println("loop"); 
   // Print the word "loop" to the console on every frame
}

```

### Basic programming strategies in Processing – Overview

#### **Variables**

```java
int integer;  
// This declares an integer variable named 'integer'.
// 'int' is a data type for whole numbers (without decimal points).
// Example values for 'int': 5, -3, 1000.

float floating;  
// This declares a float variable named 'floating'.
// 'float' is a data type for numbers with decimal points (floating-point numbers).
// Example values for 'float': 3.14, -0.5, 100.123.

String Strings;  
// This declares a String variable named 'Strings'.
// 'String' is a data type for text or sequences of characters.
// Example values for 'String': "Hello", "Processing", "123".

char character;  
// This declares a char (character) variable named 'character'.
// 'char' is a data type for storing a single character (a single letter, number, or symbol).
// Example values for 'char': 'A', '3', '?' (note that characters are enclosed in single quotes).
```



#### **Iteration**

```java
for (int i = 0; i < 10; i++){
// This is a 'for' loop, which repeats the code inside the curly braces a specific number of times.
// 1. 'int i = 0;' initializes the variable 'i' to 0. This is the starting point of the loop.
// 2. 'i < 10;' is the condition that must be true for the loop to continue. 
//    As long as 'i' is less than 10, the loop keeps running.
// 3. 'i++' increments (adds 1 to) 'i' after each loop iteration.
//    The loop repeats 10 times, with 'i' taking values from 0 to 9.

  // The code inside this block will run once for each value of 'i'.

}

// while loop
int i = 0;  
// Declare and initialize the variable 'i' to 0. 
// This variable will be used to control how long the loop runs.

while (i < 10){
// This is a 'while' loop. It keeps running the code inside the curly braces 
// as long as the condition (i < 10) is true.
// If 'i' is 10 or more, the loop will stop.

    i++;  
    // This increments (adds 1 to) 'i' after each loop iteration.
    // Without this line, the loop would run forever because 'i' would always be less than 10.
}


```

#### **Conditionals**

```java
if (integer == 1){  
// This is an if statement. It checks if the variable 'integer' is equal to 1.
// If the condition (integer == 1) is true, the code inside the curly braces will run.

}

switch (integer){  
// A switch statement checks the value of 'integer' and compares it to multiple cases.
// It is useful when you need to perform different actions based on multiple values of a variable.

   case 1:  
   // If 'integer' equals 1, this case will run.
     println("It's a one!");  
     // Print "It's a one!" to the console if the value of 'integer' is 1.
     break;  
     // The break statement ends the case, so the program doesn't check further cases.
   
   case 2:  
   // If 'integer' equals 2, this case will run.
     println("It's a two!");  
     // Print "It's a two!" to the console if the value of 'integer' is 2.
     break;  
     // The break statement ends the case, so the program doesn't check further cases.
}

```

* **If statement**:
  * Used to check if a specific condition is true (e.g., `integer == 1`). If the condition is true, the code inside the curly braces `{}` will execute.
* **Switch statement**:
  * Used when you want to compare a variable (like `integer`) against several different values (e.g., `1`, `2`).
  * Each `case` represents a possible value for the variable, and the code under that case runs if the variable matches the value.
  * The `break` statement ensures that once a case is executed, the program doesn't continue checking the other cases.

#### **Functions**

```java
println(returnFunction(5));  
// This calls the function 'returnFunction' with the argument 5, and then prints the result.
// The function will calculate and return a value, which gets printed to the console.

void myFunction(){  
// This is a basic function declaration. The keyword 'void' means that this function
// does not return any value. It performs a task but doesn't give a result back.
  
  // Code to perform some action would go here (e.g., drawing shapes, printing text).
  
}  
// The function does not return anything and doesn't take any input, 
// it's just a block of reusable code that can be executed when called.

int returnFunction(int parameter){  
// This is a function that takes an input (called a 'parameter') and returns an integer.
// 'int' means the function will return an integer value when called.
// 'parameter' is a variable passed to the function that can be used inside it.

   return 10 * parameter;  
   // This line multiplies the input 'parameter' by 10 and returns the result to the place 
   // where the function was called (like in the println above).

}
```

### Recursion

<figure><img src="https://510937649-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjQUmn9q3i7gpMtKYvCss%2Fuploads%2FYIojbpJeWoIl8Jkbarfq%2Frecursion-tree.png?alt=media&#x26;token=33ede871-8cc8-4a04-ba19-28ba1f66c60e" alt="" width="563"><figcaption></figcaption></figure>

{% code overflow="wrap" lineNumbers="true" %}
```java
void setup() {
  size(600, 600);
  background(255);  // Set the background to white
  stroke(0);        // Set the stroke color to black
  translate(width / 2, height);  // Move the origin to the bottom center of the canvas
  drawBranch(150);  // Start the recursive tree with an initial branch length
}

void drawBranch(float len) {
  // Draw a line representing a branch
  line(0, 0, 0, -len);  // Draw from the current position (0,0) to (0,-len)
  
  // Move to the end of the branch
  translate(0, -len);
  
  // Reduce the branch length for the next recursion
  len *= 0.65;  // Reduce the length by a factor for smaller branches
  
  // Recursive case: draw more branches if the length is greater than 2
  if (len > 2) {
    pushMatrix();  // Save the current transformation state
    rotate(radians(45));  // Rotate to the right
    drawBranch(len);  // Recursively draw the right branch
    popMatrix();  // Restore the transformation state

    pushMatrix();  // Save the current transformation state
    rotate(radians(-45));  // Rotate to the left
    drawBranch(len);  // Recursively draw the left branch
    popMatrix();  // Restore the transformation state
  }
}
```
{% endcode %}



<details>

<summary>Interactive variation (coded/adapted in the lecture)</summary>

{% code overflow="wrap" lineNumbers="true" %}
```java
void setup() {
  size(600, 600);
  background(255);  // Set the background to white
  stroke(0);        // Set the stroke color to black
  translate(width / 2, height);  // Move the origin to the bottom center of the canvas
  frameRate(5);
  drawBranch(150);  // Start the recursive tree with an initial branch length
}

void draw(){
  background(255);
  translate(width / 2, height);
  drawBranch(150);
}

void drawBranch(float len) {
  // Draw a line representing a branch
  line(0, 0, 0, -len);  // Draw from the current position (0,0) to (0,-len)
  
  // Move to the end of the branch
  translate(0, -len);
  
  // Reduce the branch length for the next recursion
  len *= 0.65;  // Reduce the length by a factor for smaller branches
  
  // Recursive case: draw more branches if the length is greater than 2
  if (len > 2) {
    float m = mouseX;
    pushMatrix();  // Save the current transformation state
      float mappedMouse1 = map(m, 0, width, -20, -80);
      float r1 = random(mappedMouse1, -20);
      rotate(radians(r1));  // Rotate to the right
      drawBranch(len);  // Recursively draw the right branch
    popMatrix();  // Restore the transformation state

    pushMatrix();  // Save the current transformation state
      float mappedMouse2 = map(m, 0, width, 20, 80);
      float r2 = random(20,mappedMouse2);
      rotate(radians(r2));  // Rotate to the left
      drawBranch(len);  // Recursively draw the left branch
    popMatrix();  // Restore the transformation state
  }
}

```
{% endcode %}

</details>

* **Recursion**: The `drawBranch()` function calls itself inside the function to create smaller and smaller branches.
* **Base Case**: The recursion stops when the branch length (`len`) becomes less than or equal to 2.
* **Transformations**: Each time the function is called, the position is moved to the end of the current branch using `translate()`. The `rotate()` function turns the drawing direction to create branches on either side.
* **Fractal Structure**: Since each recursive call generates two smaller branches, this creates a fractal-like tree structure that becomes increasingly detailed with each recursion.



<figure><img src="https://510937649-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjQUmn9q3i7gpMtKYvCss%2Fuploads%2F6DmT5sAtWezWJwIQvJbE%2Fl-systems.png?alt=media&#x26;token=f739e0e5-439a-4054-95c0-c825103e6d48" alt=""><figcaption><p>Iterations of a visually slightly more complex recursive process. <a href="http://andreaspirchner.com/museums-in-the-digital-space/">http://andreaspirchner.com/museums-in-the-digital-space/</a> </p></figcaption></figure>

#### L-Systems

[https://www.youtube.com/watch?v=1eNHrRe4Sqk](https://www.youtube.com/watch?v=1eNHrRe4Sqk)

[https://en.wikipedia.org/wiki/L-system](https://en.wikipedia.org/wiki/L-system)

### **Working with external libraries**

#### Peasy Cam

{% code overflow="wrap" lineNumbers="true" %}
```java

  import peasy.PeasyCam;

  PeasyCam cam;
  
  float camspeed = 0.01;
  
  void setup(){
    size(800,600, P3D);
    cam = new PeasyCam(this, 400);
    
    //fullScreen(P3D);
     colorMode(HSB);
     
    background(0);
    stroke(255,100); 
  }
```
{% endcode %}
