webgl/src/client/main.ts

464 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';
import $ from 'jquery';
2020-11-24 12:53:30 +00:00
import {initBuffers, deleteBuffers} from './buffers';
import {initShaderProgram} from './shaders';
import {changeFragmentShader} from './changeshader';
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
*/
2020-11-24 12:53:30 +00:00
async function main() {
2020-11-22 14:09:28 +00:00
const canvas: any = document.querySelector('#glCanvas')!;
const gl = canvas.getContext('webgl');
2020-11-22 14:09:28 +00:00
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() {
vec3 n = normalize(vec3(-50000., 100000., 50000.) - vPosition);
float diffuse = max(dot(normalize(vNormal.xyz), n), 0.);
2020-11-23 19:40:51 +00:00
float specular = pow(
max(dot(
reflect(n, normalize(vNormal.xyz)),
2020-11-23 19:40:51 +00:00
normalize(vec3(0., 0., -50.) - vPosition)),
0.), 10.);
2020-11-24 12:53:30 +00:00
vec3 tmp = extremize(mod(vPosition.xyz + vec3(1000.), vec3(2.)), 2.);
float texture = (tmp.x + tmp.y + tmp.z) / 6.;
gl_FragColor = vec4((texture * diffuse * 0.8) + (texture * vec3(0.2)) + (specular * vec3(1.)), 1.0);
2020-11-23 12:47:44 +00:00
}`;
const fsSource2 = `
precision highp float;
varying highp vec4 vColor;
varying highp vec4 vNormal;
varying highp vec3 vPosition;
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;
}
void main() {
vec3 n = normalize(vec3(-50000., 100000., 50000.) - vPosition);
float diffuse = max(dot(normalize(vNormal.xyz), n), 0.);
float specular = pow(
max(dot(
reflect(n, normalize(vNormal.xyz)),
normalize(vec3(0., 0., -50.) - vPosition)),
0.), 10.);
2020-11-24 12:53:30 +00:00
vec3 texture = extremize(mod(vPosition.xyz + vec3(1000.), vec3(2.)), 2.) / vec3(2);
gl_FragColor = vec4((texture * diffuse * 0.8) + (texture * vec3(0.2)) + (specular * vec3(1.)), 1.0);
}`;
const fsSource3 = `
precision highp float;
varying highp vec4 vColor;
varying highp vec4 vNormal;
varying highp vec3 vPosition;
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;
}
void main() {
vec3 n = normalize(vec3(-50000., 100000., 50000.) - vPosition);
float diffuse = max(dot(normalize(vNormal.xyz), n), 0.);
float specular = pow(
max(dot(
reflect(n, normalize(vNormal.xyz)),
normalize(vec3(0., 0., -50.) - vPosition)),
0.), 10.);
vec3 texture = extremize(mod(vPosition.xyz + vec3(1000.), vec3(2.)), 2.) / vec3(2);
gl_FragColor = vec4((diffuse * 0.8) + (vec3(0.2)) + (specular * vec3(1.)), 1.0);
}`;
2020-11-23 16:07:53 +00:00
/* eslint-enable */
2020-11-24 12:53:30 +00:00
/**
* Fetch an obj file
* @param {string} url the url to fetch the object from
* @return {string} the raw data of the obj file
*/
async function getObj(url: string) {
const response = await fetch(url);
const data = await response.text();
return data;
}
2020-11-24 14:05:35 +00:00
const data = await getObj('/static/objs/teapot.obj');
2020-11-24 12:53:30 +00:00
let distance: any = $('#input1').val();
let circleSize: any = $('#input2').val();
2020-11-24 12:53:30 +00:00
distance = parseFloat(distance);
circleSize = parseFloat(circleSize);
2020-11-24 12:53:30 +00:00
const [
positions,
normals,
uvs,
indices,
] = convert(data);
let length = indices.length;
console.log(uvs);
let [shaderProgram, fragmentShader]: any = initShaderProgram(gl,
vsSource,
fsSource3);
2020-11-24 12:53:30 +00:00
let programInfo: any = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram,
'aVertexPosition'),
vertexColor: gl.getAttribLocation(shaderProgram,
'aVertexColor'),
vertexNormal: gl.getAttribLocation(shaderProgram,
'aVertexNormal'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram, 'uProjectionMatrix'),
viewMatrix: gl.getUniformLocation(
shaderProgram, 'uviewMatrix'),
modelMatrix: gl.getUniformLocation(
shaderProgram, 'umodelMatrix'),
},
};
let buffers = initBuffers(gl, positions, indices, normals);
let then = 0;
let changed = false;
/**
* Draws the scene repeatedly
* @param {number} now the current time
*/
function render(now: any) {
now *= 0.001;
const deltaTime = now - then;
if (now >= 1 && changed == false) {
changed = true;
2020-11-22 14:09:28 +00:00
}
2020-11-24 12:53:30 +00:00
then = now;
drawScene(gl,
programInfo,
buffers,
deltaTime,
length,
distance,
circleSize);
2020-11-24 12:53:30 +00:00
requestAnimationFrame(render);
}
/**
* Pushes a new obj file to the gl buffer
* @param {string} data the obj file to push
*/
function updateObj(data: string) {
const [
positions,
normals,
uvs,
indices,
] = convert(data);
console.log(uvs);
length = indices.length;
deleteBuffers(gl, buffers);
buffers = initBuffers(gl, positions, indices, normals);
}
2020-11-24 12:53:30 +00:00
$(function() {
$('#input1').on('keypress', function(event: any) {
if (event.which === 13) {
event.preventDefault();
$('#button3').click();
}
});
$('#input2').on('keypress', function(event: any) {
if (event.which === 13) {
event.preventDefault();
$('#button4').click();
}
});
2020-11-24 12:53:30 +00:00
$('#button1').on('click', function() {
[programInfo, fragmentShader] = changeFragmentShader(gl,
shaderProgram, fragmentShader, fsSource, vsSource);
});
$('#button2').on('click', function() {
[programInfo, fragmentShader] = changeFragmentShader(gl,
shaderProgram, fragmentShader, fsSource2, vsSource);
});
$('#button3').on('click', function() {
[programInfo, fragmentShader] = changeFragmentShader(gl,
shaderProgram, fragmentShader, fsSource3, vsSource);
});
2020-11-24 12:53:30 +00:00
$('#button3').on('click', function() {
distance = $('#input1').val();
distance = parseFloat(distance);
});
$('#button4').on('click', function() {
circleSize = $('#input2').val();
circleSize = parseFloat(circleSize);
});
2020-11-24 12:53:30 +00:00
$('#sphere').on('click', async function() {
const data = await getObj('/static/objs/sphere.obj');
updateObj(data);
2020-11-24 12:53:30 +00:00
});
$('#teapot').on('click', async function() {
const data = await getObj('/static/objs/teapot.obj');
updateObj(data);
});
$('#fox').on('click', async function() {
const data = await getObj('/static/objs/fox.obj');
updateObj(data);
});
2020-11-23 12:47:44 +00:00
});
2020-11-24 12:53:30 +00:00
requestAnimationFrame(render);
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
* @param {number} distance distance of camera
* @param {number} circleSize size of circle the object is rotating around
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,
distance: number,
circleSize: 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;
const zFar = 1000.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) * circleSize,
Math.sin(squareRotation) * circleSize,
0,
]);
2020-11-23 19:40:51 +00:00
2020-11-23 16:07:53 +00:00
mat4.translate(
viewMatrix,
viewMatrix,
[0.0, 0.0, -distance]);
2020-11-23 16:07:53 +00:00
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-24 14:05:35 +00:00
2020-11-23 16:07:53 +00:00
{
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
}