webgl/src/client/main.ts

436 lines
11 KiB
TypeScript
Raw Normal View History

2020-11-22 14:09:28 +00:00
// @ts-ignore
import mat4 from 'gl-mat4';
2020-11-23 12:47:44 +00:00
// @ts-ignore
import convert from './objparser';
2020-11-22 14:09:28 +00:00
2020-11-22 14:16:08 +00:00
let squareRotation = 0.0;
2020-11-22 14:09:28 +00:00
main();
/**
* The program purpose is encapsulated in a main function
*/
function main() {
const canvas: any = document.querySelector('#glCanvas')!;
const gl = canvas.getContext('webgl');
if (gl == null) {
canvas.parentNode.removeChild(canvas);
document.getElementById('root')!.insertAdjacentHTML('beforeend',
`<p>Unable to initialize WebGL. Your browser or machine may not
support it.</p>`);
}
2020-11-23 16:07:53 +00:00
/* eslint-disable */
2020-11-22 14:09:28 +00:00
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec4 aVertexColor;
2020-11-23 16:07:53 +00:00
attribute vec4 aVertexNormal;
2020-11-22 14:09:28 +00:00
uniform mat4 uProjectionMatrix;
2020-11-23 16:07:53 +00:00
uniform mat4 uviewMatrix;
uniform mat4 umodelMatrix;
2020-11-22 14:09:28 +00:00
2020-11-23 19:50:43 +00:00
varying highp vec4 vColor;
varying highp vec4 vNormal;
varying highp vec3 vPosition;
2020-11-23 12:47:44 +00:00
void main()
{
2020-11-22 14:09:28 +00:00
gl_Position = uProjectionMatrix *
2020-11-23 16:07:53 +00:00
uviewMatrix *
umodelMatrix *
2020-11-22 14:09:28 +00:00
aVertexPosition;
2020-11-23 16:07:53 +00:00
vPosition = vec3(aVertexPosition);
2020-11-22 14:09:28 +00:00
vColor = aVertexColor;
2020-11-23 16:07:53 +00:00
vNormal = umodelMatrix * aVertexNormal;
2020-11-22 14:09:28 +00:00
}
`;
2020-11-23 12:47:44 +00:00
const fsSource = `
2020-11-23 19:50:43 +00:00
precision highp float;
2020-11-23 16:07:53 +00:00
2020-11-23 19:50:43 +00:00
varying highp vec4 vColor;
varying highp vec4 vNormal;
varying highp vec3 vPosition;
2020-11-23 12:47:44 +00:00
2020-11-23 19:40:51 +00:00
vec3 extremize(vec3 v, float n) {
if (v.x > n / 2.)
v.x = n;
else
v.x = 0.;
if (v.y > n / 2.)
v.y = n;
else
v.y = 0.;
if (v.z > n / 2.)
v.z = n;
else
v.z = 0.;
return v;
}
2020-11-23 12:47:44 +00:00
void main() {
2020-11-23 19:40:51 +00:00
vec3 n = normalize(vec3(-500., 1000., 500.) - vPosition);
2020-11-23 16:07:53 +00:00
float diffuse = max(dot(vNormal.xyz, n), 0.);
2020-11-23 19:40:51 +00:00
float specular = pow(
max(dot(
reflect(n, vNormal.xyz),
normalize(vec3(0., 0., -50.) - vPosition)),
0.), 10.);
vec3 tmp = extremize(mod(vPosition.xyz + vec3(100.), vec3(3.)), 3.);
float texture = (tmp.x + tmp.y + tmp.z) / 9.;
2020-11-23 20:16:36 +00:00
gl_FragColor = vec4((texture * diffuse * 0.9) + (texture * 0.1) + (specular * vec3(1.)), 1.0);
2020-11-23 12:47:44 +00:00
}`;
2020-11-23 16:07:53 +00:00
/* eslint-enable */
fetch('/static/objs/teapot_normals.obj').then((response) => {
2020-11-23 12:47:44 +00:00
return response.text();
}).then((data: any) => {
2020-11-23 16:07:53 +00:00
const [
convertedPositions,
convertedNormals,
uvs,
indices,
] = convert(data);
2020-11-23 12:47:44 +00:00
console.log(uvs);
2020-11-23 16:07:53 +00:00
console.log(squareRotation);
const normals = [];
const positions = [];
for (let i = 0; i < convertedNormals.length; i++) {
if (i % 4 != 0) {
normals.push(convertedNormals[i]);
}
}
for (let i = 0; i < convertedPositions.length; i++) {
if (i % 4 != 0) {
positions.push(convertedPositions[i]);
}
}
2020-11-23 12:47:44 +00:00
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const programInfo: any = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram,
'aVertexPosition'),
vertexColor: gl.getAttribLocation(shaderProgram,
'aVertexColor'),
2020-11-23 16:07:53 +00:00
vertexNormal: gl.getAttribLocation(shaderProgram,
'aVertexNormal'),
2020-11-23 12:47:44 +00:00
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram, 'uProjectionMatrix'),
2020-11-23 16:07:53 +00:00
viewMatrix: gl.getUniformLocation(
shaderProgram, 'uviewMatrix'),
modelMatrix: gl.getUniformLocation(
shaderProgram, 'umodelMatrix'),
2020-11-23 12:47:44 +00:00
},
};
2020-11-23 16:07:53 +00:00
const buffers = initBuffers(gl, positions, indices, normals);
2020-11-23 12:47:44 +00:00
let then = 0;
/**
* Draws the scene repeatedly
* @param {number} now the current time
*/
function render(now: any) {
now *= 0.001;
const deltaTime = now - then;
then = now;
drawScene(gl, programInfo, buffers, deltaTime, indices.length);
requestAnimationFrame(render);
2020-11-22 14:09:28 +00:00
}
2020-11-22 14:16:08 +00:00
requestAnimationFrame(render);
2020-11-23 12:47:44 +00:00
});
2020-11-22 14:09:28 +00:00
}
/**
* Initialize a shader program, so WebGL knows how to draw our data
* @param {any} gl the WebGL context
* @param {string} vsSource the vertex shader source
* @param {string} fsSource the fragment shader source
* @return {any} the shader program
*/
function initShaderProgram(gl: any, vsSource: string, fsSource: string) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' +
gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
/**
* load a GL shader
* @param {any} gl the WebGL context
* @param {any} type type of shader to load
* @param {string} source source code of shader
* @return {any} the loaded shader
*/
function loadShader(gl: any, type: any, source: string) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('An error occurred compiling the shaders: ' +
gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
/**
* init buffers to create a square
* @param {any} gl the web gl context
2020-11-23 12:47:44 +00:00
* @param {Array<number>} positions the position buffer to be loaded
* @param {Array<number>} indices the index buffer to be loaded
2020-11-23 16:07:53 +00:00
* @param {Array<number>} normals the normal buffer to be loaded
2020-11-22 14:09:28 +00:00
* @return {any} the buffer
*/
2020-11-23 12:47:44 +00:00
function initBuffers(
gl: any,
positions: Array<number>,
2020-11-23 16:07:53 +00:00
indices: Array<number>,
normals: Array<number>) {
2020-11-22 14:09:28 +00:00
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(positions),
gl.STATIC_DRAW);
2020-11-23 16:07:53 +00:00
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(normals),
gl.STATIC_DRAW);
2020-11-23 05:38:10 +00:00
const myColors = [
2020-11-22 19:56:56 +00:00
[1.0, 1.0, 1.0, 1.0],
[1.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 0.0, 1.0],
[0.0, 0.0, 1.0, 1.0],
[1.0, 1.0, 0.0, 1.0],
[1.0, 0.0, 1.0, 1.0],
2020-11-23 05:38:10 +00:00
[0.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 1.0, 1.0],
2020-11-22 14:09:28 +00:00
];
2020-11-23 05:38:10 +00:00
let faceColors: any = [];
for (let i = 0; i < 70; i++) {
faceColors = faceColors.concat(myColors);
}
2020-11-22 19:56:56 +00:00
// Convert the array of colors into a table for all the vertices.
2020-11-23 12:47:44 +00:00
const colors: any = [];
2020-11-22 19:56:56 +00:00
2020-11-23 12:47:44 +00:00
for (let j = 0; j < indices.length; ++j) {
2020-11-23 05:38:10 +00:00
const c = [
2020-11-23 12:47:44 +00:00
myColors[Math.floor(Math.random() * 8)],
2020-11-23 05:38:10 +00:00
faceColors[Math.floor(Math.random() * 8)],
faceColors[Math.floor(Math.random() * 8)],
faceColors[Math.floor(Math.random() * 8)],
];
2020-11-22 19:56:56 +00:00
// Repeat each color four times for the four vertices of the face
2020-11-23 12:47:44 +00:00
// colors = colors.concat([1.0, 1.0, 1.0, 1.0]);
colors.push(c[0][0]);
colors.push(c[0][1]);
colors.push(c[0][2]);
colors.push(c[0][3]);
2020-11-22 19:56:56 +00:00
}
2020-11-22 14:09:28 +00:00
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
2020-11-22 19:56:56 +00:00
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices), gl.STATIC_DRAW);
2020-11-23 12:47:44 +00:00
// Now send the element array to GL
2020-11-22 19:56:56 +00:00
2020-11-22 14:09:28 +00:00
return {
position: positionBuffer,
color: colorBuffer,
2020-11-22 19:56:56 +00:00
indices: indexBuffer,
2020-11-23 16:07:53 +00:00
normals: normalBuffer,
2020-11-22 14:09:28 +00:00
};
}
/**
* Draw a webgl scene
* @param {any} gl the WebGL context
* @param {any} programInfo WebGL program information
* @param {any} buffers the buffers to draw
2020-11-22 14:16:08 +00:00
* @param {number} deltaTime the difference in time since last call
2020-11-23 12:47:44 +00:00
* @param {number} length the index buffer length
2020-11-22 14:09:28 +00:00
*/
2020-11-23 12:47:44 +00:00
function drawScene(gl: any,
programInfo: any,
buffers: any,
deltaTime: number,
length: number) {
2020-11-22 14:09:28 +00:00
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = 45 * Math.PI / 180;
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
2020-11-23 16:07:53 +00:00
const zFar = 70.0;
2020-11-22 14:09:28 +00:00
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(
projectionMatrix,
fieldOfView,
aspect,
zNear,
zFar);
2020-11-23 16:07:53 +00:00
const modelMatrix = mat4.create();
mat4.rotate(modelMatrix,
modelMatrix,
2020-11-22 14:16:08 +00:00
squareRotation,
2020-11-23 12:47:44 +00:00
[
2020-11-23 16:07:53 +00:00
0,
1,
2020-11-23 12:47:44 +00:00
0,
]);
2020-11-22 14:16:08 +00:00
2020-11-23 16:07:53 +00:00
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const viewMatrix = mat4.create();
2020-11-23 19:40:51 +00:00
mat4.translate(
viewMatrix,
viewMatrix,
[Math.cos(squareRotation) * 5, Math.sin(squareRotation) * 5, 0]);
2020-11-23 16:07:53 +00:00
mat4.translate(
viewMatrix,
viewMatrix,
[0.0, 0.0, -50.0]);
2020-11-22 14:09:28 +00:00
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
{
2020-11-22 19:56:56 +00:00
const numComponents = 3;
2020-11-22 14:09:28 +00:00
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
programInfo.attribLocations.vertexPosition);
}
2020-11-23 16:07:53 +00:00
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
{
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normals);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexNormal,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
programInfo.attribLocations.vertexNormal);
}
2020-11-22 14:09:28 +00:00
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
{
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
programInfo.attribLocations.vertexColor);
}
2020-11-22 19:56:56 +00:00
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
2020-11-22 14:09:28 +00:00
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix);
gl.uniformMatrix4fv(
2020-11-23 16:07:53 +00:00
programInfo.uniformLocations.viewMatrix,
false,
viewMatrix);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelMatrix,
2020-11-22 14:09:28 +00:00
false,
2020-11-23 16:07:53 +00:00
modelMatrix);
2020-11-22 14:09:28 +00:00
{
2020-11-23 12:47:44 +00:00
const vertexCount = length;
2020-11-22 19:56:56 +00:00
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
2020-11-22 14:16:08 +00:00
squareRotation += deltaTime;
2020-11-22 14:09:28 +00:00
}