Search code examples
javascript3dprocessingp5.js

Create solid 3D shape in p5.js


I am trying to make an apple surface in 3D using in p5.js, similar as the images on this page (Ctrl+F "Apple Surface"):

apple surface wireframe

apple surface filled.

What I currently have is (interactive version in p5 editor):

function setup() {
  createCanvas(500, 500, WEBGL);
  setAttributes('antialias', true);
  fill(237, 34, 93);
  strokeWeight(3);
}

function draw() {
  background(200);
  normalMaterial();
  rotateY(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  rotateZ(frameCount * 0.01);
  apple();
}


function apple() {
  beginShape(TRIANGLE_FAN);

  size = 20;

  for (let u = 0; u < TWO_PI; u += 0.1) {
      for (let v = -PI; v < PI; v += 0.1) {
    x = cos(u) * (4 + 3.8 * cos(v))
    y = sin(u) * (4 + 3.8 * cos(v))     
    z = (cos(v) + sin(v) -1) * (1+sin(v)) * log(1-PI * v/10)+7.5 * sin(v)
    //point(size * x, size * y, size * z);
    vertex(size * x, size * y, size * z);
      }
  }

  endShape(CLOSE);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>

How do I make my shape solid as in the second apple picture above?


Solution

  • Just create triangle strip primitives (TRIANGLE_STRIP - see beginShape()):

    0        2       4        6
     +-------+-------+-------+---
     | \     | \     | \     | \
     |   \   |   \   |   \   |   \
     |     \ |     \ |     \ |
     +-------+-------+-------+---
    1        3       5        7
    

    function setup() {
      createCanvas(500, 500, WEBGL);
      setAttributes('antialias', true);
      fill(237, 34, 93);
      strokeWeight(3);
    }
    
    function draw() {
      background(200);
      normalMaterial();
      rotateY(frameCount * 0.01);
      rotateY(frameCount * 0.01);
      rotateZ(frameCount * 0.01);
      apple();
    }
    
    function apple() {
    
      size = 20;
      for (let u = 0; u < TWO_PI; u += 0.1) {
          beginShape(TRIANGLE_STRIP);
          for (let v = -PI; v < PI; v += 0.1) {
            x = cos(u) * (4 + 3.8 * cos(v))
            y = sin(u) * (4 + 3.8 * cos(v))     
            z = (cos(v) + sin(v) -1) * (1+sin(v)) * log(1-PI * v/10)+7.5 * sin(v)
            vertex(size * x, size * y, size * z);
    
            x = cos(u+0.1) * (4 + 3.8 * cos(v))
            y = sin(u+0.1) * (4 + 3.8 * cos(v)) 
            vertex(size * x, size * y, size * z);
          }
          endShape(CLOSE);
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>