Skip to content

kfahn22/Persian-Rug

Repository files navigation

Persian Rug using Recursion

From Wikipedia:

"Recursion is the process a procedure goes through when one of the steps of the procedure involves invoking the procedure itself."

To learn more about recusion, I highly recommend Daniel Shiffman's newly updated The Nature of Code book or his Recursion Coding Challenge.

In Recursion in Nature, Mathematics and Art, Anne Burns discusses using the mid-point algorithm to generate patterns that resemble Persian rugs. The essential idea is to draw a border around a square, and then draw lines connecting the midpoints of the opposite border in a new color which is a function of the colors, $x_i$, in the four corners of the square. This process was illustrated in Figure 10 of the paper.

Midpoint algorithm

Figure 10 from Recursion in Nature, Mathematics and Art

The sketch is an adapted version of this code. I have used a method suggested by Dr. Eric Gossett in Persian Rugs to compute the next color. In this approach, we select colors from a palette based on the index. We first initialize an empty array to hold the indexes.

 colorIndexArray = Array(canvasSize)
    .fill()
    .map(() => Array(canvasSize).fill(0));

We draw a border using palette[0]. We then retrieve the palette index from the colorIndexArry and calculate then new index using the following formula, where shift is an integer to add more variation to the rug generation.

$f(x_1 + x_2 + x_3 + x_4) = (i_1 + i_2+ i_3 + i_4$ + shift) % palette.length

We use the newIndex to pick the color from the palette for the new middle lines.

let col = palette[newIndex];
let midCol = floor((left + right) / 2);
let midRow = floor((top + bottom) / 2);

// Draw middle lines
stroke(col);
line(left + 1, midRow, right - 1, midRow); // Horizontal
line(midCol, top + 1, midCol, bottom - 1); // Vertical

We also pass the newIndex to the colorIndexArray and continue this process recursively.

  colorIndexArray[midCol][midRow] = newIndex;

I have found that the best images are created from a palette with a large number of colors. Luckily, I found a really nice website where you can obtain palettes with 12 and more different colors.

You can play with the p5 sketch here. I also have a version that chooses colors randomly here. Assuming you have Processing downloaded, you can open the Processing sketch by downloading from here.

Gallery

Rug with color palette

Rug with color palette

Rug with color palette

Rug with color palette