Rasterize Triangle

rasterizeTriangle() #

Rasterize the triangle defined by vertices (row0, col0), (row1, col1), and (row2, col2), using barycentric coordinates. The user provided software rendered (fragment) shader is a function parameterized with the object literal { array: interpolated_data_array, row: i, col: j } and that should return a p5.Color. Refer to the colorizeTriangle() method for an example.

Example #

(press any or mouse click)

code
const ROWS = 20;
const COLS = 20;
const LENGTH = 20;
let quadrille;
let row0, col0, row1, col1, row2, col2;

function setup() {
  createCanvas(COLS * LENGTH, ROWS * LENGTH);
  quadrille = createQuadrille(20, 20);
  update();
}

function draw() {
  background(0);
  drawQuadrille(quadrille, { cellLength: LENGTH, outline: 'green' });
  hint();
}

function mouseClicked() {
  update();
}

function keyPressed() {
  update();
}

function update() {
  randomize();
  quadrille.clear();
  quadrille.rasterizeTriangle(row0, col0, row1, col1, row2, col2,
                              colorizeShader,
                              [255, 0, 0], [0, 255, 0], [0, 0, 255]);
}

function hint() {
  push();
  stroke('cyan');
  strokeWeight(3);
  noFill();
  triangle(col0 * LENGTH + LENGTH / 2, row0 * LENGTH + LENGTH / 2,
           col1 * LENGTH + LENGTH / 2, row1 * LENGTH + LENGTH / 2,
           col2 * LENGTH + LENGTH / 2, row2 * LENGTH + LENGTH / 2);
  pop();
}

function colorizeShader({ array: rgb }) {
  return color(rgb);
}

function randomize() {
  col0 = int(random(0, COLS));
  row0 = int(random(0, ROWS));
  col1 = int(random(0, COLS));
  row1 = int(random(0, ROWS));
  col2 = int(random(0, COLS));
  row2 = int(random(0, ROWS));
}

Syntax #

rasterizeTriangle(row0, col0, row1, col1, row2, col2, shader, array0, [array1], [array2])

Parameters #

parameterdescription
row0Number: vertex0 row coordinate
col0Number: vertex0 col coordinate
row1Number: vertex1 row coordinate
col1Number: vertex1 col coordinate
row2Number: vertex2 row coordinate
col2Number: vertex2 col coordinate
shaderFunction: taking { array: interpolated_data_array, row: i, col: j } params and returning a p5.Color
array0Array: vertex0 attributes to be interpolated
array1Array: vertex1 attributes to be interpolated default is array0
array2Array: vertex2 attributes to be interpolated default is array0