KITASENJU DESIGN BLOG

memo, html, javascript, unity

shader on p5js

I made https://editor.p5js.org/kitasenjudesign/sketches/vCGvyK5Ag

referance

js

// a shader variable
let theShader;

function preload(){
  // load the shader
  theShader = loadShader('shader.vert', 'shader.frag');
}

function setup() {
  // shaders require WEBGL mode to work
  createCanvas(windowWidth, windowHeight, WEBGL);
  noStroke();
}

function draw() {  
  // shader() sets the active shader with our shader
  
  for(var i=-5;i<5;i++){
    for(var j=-5;j<5;j++){
      shader(theShader);
      theShader.setUniform('color', [0.5+0.5*random(),random(),random(),1]);  
      theShader.setUniform('color2', [random(),random(),0.5+0.5*random(),1]);
      theShader.setUniform('pos', [i*0.2,j*0.2,0.2, 0.2]);  
      rect(0,0,1,1);  // rect gives us some geometry on the screen      
    }
  }

  
}

function windowResized(){
  resizeCanvas(windowWidth, windowHeight);
}

vert

// vert file and comments from adam ferriss
// https://github.com/aferriss/p5jsShaderExamples

uniform vec4 pos; // This is passed in as a uniform from the sketch.js file

// our vertex data
attribute vec3 aPosition;

// our texcoordinates
attribute vec2 aTexCoord;

// this is a variable that will be shared with the fragment shader
// we will assign the attribute texcoords to the varying texcoords to move them from the vert shader to the frag shader
// it can be called whatever you want but often people prefix it with 'v' to indicate that it is a varying
varying vec2 vTexCoord;

void main() {

  // copy the texture coordinates
  vTexCoord = aTexCoord;

  // copy the position data into a vec4, using 1.0 as the w component
  vec4 positionVec4 = vec4(aPosition, 1.0);
  //positionVec4.xy = positionVec4.xy * 2.0 - 1.0;
  positionVec4.xy = pos.xy + positionVec4.xy * pos.zw;

  
  // send the vertex information on to the fragment shader
  gl_Position = positionVec4;
}

frag

precision mediump float;

// this is the same variable we declared in the vertex shader
// we need to declare it here too!
varying vec2 vTexCoord;

uniform vec4 color;
uniform vec4 color2;

void main() {

  // copy the vTexCoord
  // vTexCoord is a value that goes from 0.0 - 1.0 depending on the pixels location
  // we can use it to access every pixel on the screen
  vec2 coord = vTexCoord;
  
  // x values for red, y values for green, both for blue
  gl_FragColor = mix(color,color2,coord.y);
    //vec4(coord.x, coord.y, (coord.x+coord.y), 1.0 );
}
"FOOTER"