4230-hw-1/Pendulum/Pendulum.js

113 lines
2.4 KiB
JavaScript
Raw Normal View History

// RotatingTranslatedTriangle.js (c) 2012 matsuda
2022-07-01 05:38:54 +00:00
// Pendulum.js
// John Breaux 2022-06-30
// Simulates a pendulum in a frictionless vacuum with no gravity
"use strict"
const vertex_shader = `
attribute vec4 a_Position;
uniform mat4 u_ModelMatrix;
void main()
{
gl_Position = u_ModelMatrix * a_Position;
2022-07-01 05:38:54 +00:00
gl_PointSize = 5.0;
} `;
const fragment_shader = `
void main()
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
} `;
// Point size of the anchor
var POINT_SIZE = 5;
// Radius of the bob
var BOB_RADIUS = 0.1;
// length of the wire
var PEN_LENGTH = 0.8;
// Rotation angle (degrees/second)
var A_VELOCITY = 45.0;
2022-07-01 05:38:54 +00:00
// Common functions:
// acquire_buffer: Get a vertex buffer object from gl
function acquire_buffer(gl) {
// Create a buffer object
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return -1;
}
2022-07-01 05:38:54 +00:00
return vertexBuffer;
}
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, vertex_shader, fragment_shader)) {
console.log('Failed to intialize shaders.');
return;
}
// create a pendulum object
2022-07-01 05:38:54 +00:00
var pendulum = new Pendulum({ angle: 0, length: PEN_LENGTH, radius: BOB_RADIUS });
init(gl, pendulum);
// Specify the color for clearing <canvas>
gl.clearColor(0, 0, 0, 1);
// Get storage location of u_ModelMatrix
var u_ModelMatrix = gl.getUniformLocation(gl.program, 'u_ModelMatrix');
if (!u_ModelMatrix) {
console.log('Failed to get the storage location of u_ModelMatrix');
return;
}
// Model matrix
var modelMatrix = new Matrix4();
2022-07-01 05:38:54 +00:00
// Set it to the I matrix
modelMatrix.setIdentity();
// Start drawing
var tick = function () {
2022-07-01 05:38:54 +00:00
// Tick the pendulum
pendulum.tick();
// Draw the pendulum
draw(gl, pendulum, modelMatrix, u_ModelMatrix);
// Request that the browser ?calls tick
requestAnimationFrame(tick, canvas);
};
tick();
}
2022-07-01 05:38:54 +00:00
function init(gl, pendulum) {
pendulum.init(gl);
}
2022-07-01 05:38:54 +00:00
function draw(gl, pendulum, modelMatrix, u_ModelMatrix) {
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
2022-07-01 05:38:54 +00:00
// Draw the pendulum
pendulum.draw(gl, modelMatrix, u_ModelMatrix);
}
function up() {
A_VELOCITY += 10;
}
function down() {
A_VELOCITY -= 10;
}