-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
406 lines (358 loc) · 14.4 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
function main(){
var canvas = document.getElementById("Canvas");
var gl = canvas.getContext("webgl");
var vertices = [];
var indices = [...indicesKanan, ...indicesCube, ...indicesKiri, ...planeIndices];
// Create a linked-list for storing the vertices data
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Create a linked-list for storing the indices data
var indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
var vertexShaderSource = `
attribute vec3 aPosition;
attribute vec3 aColor;
attribute vec3 aNormal;
attribute float aShininessConstant;
varying vec3 vColor;
varying vec3 vNormal;
varying vec3 vPosition;
varying float vShininessConstant;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProjection;
void main() {
gl_Position = uProjection * uView * uModel * (vec4(aPosition * 2. / 3., 0.5));
vColor = aColor;
vNormal = aNormal;
vPosition = (uModel * (vec4(aPosition * 2. / 3., 0.5))).xyz;
vShininessConstant = aShininessConstant;
}
`;
var fragmentShaderSource = `
precision mediump float;
varying vec3 vColor;
varying vec3 vNormal;
varying vec3 vPosition;
varying float vShininessConstant;
uniform vec3 uLightConstant; // It represents the light color
uniform float uAmbientIntensity; // It represents the light intensity
// uniform vec3 uLightDirection;
uniform vec3 uLightPosition;
uniform mat3 uNormalModel;
uniform vec3 uViewerPosition;
uniform float uLightOn;
void main() {
vec3 ambient = uLightConstant * uAmbientIntensity;
vec3 lightDirection = uLightPosition - vPosition;
vec3 normalizedLight = normalize(lightDirection); // [2., 0., 0.] becomes a unit vector [1., 0., 0.]
vec3 normalizedNormal = normalize(uNormalModel * vNormal);
float cosTheta = dot(normalizedNormal, normalizedLight);
vec3 diffuse = vec3(0., 0., 0.);
if (uLightOn == 1. && cosTheta > 0.) {
float diffuseIntensity = cosTheta;
diffuse = uLightConstant * diffuseIntensity;
}
vec3 reflector = reflect(-lightDirection, normalizedNormal);
vec3 normalizedReflector = normalize(reflector);
vec3 normalizedViewer = normalize(uViewerPosition - vPosition);
float cosPhi = dot(normalizedReflector, normalizedViewer);
vec3 specular = vec3(0., 0., 0.);
if (uLightOn == 1. && cosPhi > 0.) {
float specularIntensity = pow(cosPhi, vShininessConstant);
specular = uLightConstant * specularIntensity;
}
vec3 phong = ambient + diffuse + specular;
gl_FragColor = vec4(phong * vColor, 1.);
}
`;
// Create .c in GPU
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
// Compile .c into .o
gl.compileShader(vertexShader);
gl.compileShader(fragmentShader);
let compiled = gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)
if (!compiled) {
console.error(gl.getShaderInfoLog(vertexShader))
}
// Prepare a .exe shell (shader program)
var shaderProgram = gl.createProgram();
// Put the two .o files into the shell
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
// Link the two .o files, so together they can be a runnable program/context.
gl.linkProgram(shaderProgram);
// Start using the context (analogy: start using the paints and the brushes)
gl.useProgram(shaderProgram);
// Teach the computer how to collect
// the positional values from ARRAY_BUFFER
// to each vertex being processed
var aPosition = gl.getAttribLocation(shaderProgram, "aPosition");
gl.vertexAttribPointer(
aPosition,
3,
gl.FLOAT,
false,
10 * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.enableVertexAttribArray(aPosition);
var aColor = gl.getAttribLocation(shaderProgram, "aColor");
gl.vertexAttribPointer(
aColor,
3,
gl.FLOAT,
false,
10 * Float32Array.BYTES_PER_ELEMENT,
6 * Float32Array.BYTES_PER_ELEMENT
);
gl.enableVertexAttribArray(aColor);
var aNormal = gl.getAttribLocation(shaderProgram, "aNormal");
gl.vertexAttribPointer(
aNormal,
3,
gl.FLOAT,
false,
10 * Float32Array.BYTES_PER_ELEMENT,
3 * Float32Array.BYTES_PER_ELEMENT
);
gl.enableVertexAttribArray(aNormal);
var aShininessConstant = gl.getAttribLocation(shaderProgram, "aShininessConstant");
gl.vertexAttribPointer(
aShininessConstant,
1,
gl.FLOAT,
false,
10 * Float32Array.BYTES_PER_ELEMENT,
9 * Float32Array.BYTES_PER_ELEMENT
);
gl.enableVertexAttribArray(aShininessConstant);
// Connect the uniform transformation matrices
var uModel = gl.getUniformLocation(shaderProgram, "uModel");
var uView = gl.getUniformLocation(shaderProgram, "uView");
var uProjection = gl.getUniformLocation(shaderProgram, "uProjection");
// Set the projection matrix in the vertex shader
var projection = glMatrix.mat4.create();
glMatrix.mat4.perspective(
projection,
Math.PI / 3, // field of view
1, // ratio
0.5, // near clip
10 // far clip
);
gl.uniformMatrix4fv(uProjection, false, projection);
// Set the view matrix in the vertex shader
var view = glMatrix.mat4.create();
var camera = [0, 0, 3];
var camupdate = [0, 0, 0];
glMatrix.mat4.lookAt(
view,
camera, // camera position
camupdate, // the point where camera looks at
[0, 1, 0] // up vector of the camera
);
gl.uniformMatrix4fv(uView, false, view);
// Define the lighting and shading
var uLightConstant = gl.getUniformLocation(shaderProgram, "uLightConstant");
var uAmbientIntensity = gl.getUniformLocation(shaderProgram, "uAmbientIntensity");
gl.uniform3fv(uLightConstant, [1.0, 1.0, 1.0]); // orange light
gl.uniform1f(uAmbientIntensity, 0.311) // light intensity: 40%
//var uLightDirection = gl.getUniformLocation(shaderProgram, "uLightDirection");
//gl.uniform3fv(uLightDirection, [2.0, 0.0, 0.0]); // light comes from the right side
var uLightPosition = gl.getUniformLocation(shaderProgram, "uLightPosition");
var lightPosition = [0.025, 0.11, -0.025];
gl.uniform3fv(uLightPosition, lightPosition);
var uNormalModel = gl.getUniformLocation(shaderProgram, "uNormalModel");
var uViewerPosition = gl.getUniformLocation(shaderProgram, "uViewerPosition");
gl.uniform3fv(uViewerPosition, camera);
//untuk putar
var lastPointOnTrackBall, currentPointOnTrackBall;
var lastQuat = glMatrix.quat.create();
function computeCurrentQuat() {
// Secara berkala hitung quaternion rotasi setiap ada perubahan posisi titik pointer mouse
var axisFromCrossProduct = glMatrix.vec3.cross(glMatrix.vec3.create(), lastPointOnTrackBall, currentPointOnTrackBall);
var angleFromDotProduct = Math.acos(glMatrix.vec3.dot(lastPointOnTrackBall, currentPointOnTrackBall));
var rotationQuat = glMatrix.quat.setAxisAngle(glMatrix.quat.create(), axisFromCrossProduct, angleFromDotProduct);
glMatrix.quat.normalize(rotationQuat, rotationQuat);
return glMatrix.quat.multiply(glMatrix.quat.create(), rotationQuat, lastQuat);
}
// Memproyeksikan pointer mouse agar jatuh ke permukaan ke virtual trackball
function getProjectionPointOnSurface(point) {
var radius = canvas.width/3; // Jari-jari virtual trackball kita tentukan sebesar 1/3 lebar kanvas
var center = glMatrix.vec3.fromValues(canvas.width/2, canvas.height/2, 0); // Titik tengah virtual trackball
var pointVector = glMatrix.vec3.subtract(glMatrix.vec3.create(), point, center);
pointVector[1] = pointVector[1] * (-1); // Flip nilai y, karena koordinat piksel makin ke bawah makin besar
var radius2 = radius * radius;
var length2 = pointVector[0] * pointVector[0] + pointVector[1] * pointVector[1];
if (length2 <= radius2) pointVector[2] = Math.sqrt(radius2 - length2); // Dapatkan nilai z melalui rumus Pytagoras
else { // Atur nilai z sebagai 0, lalu x dan y sebagai paduan Pytagoras yang membentuk sisi miring sepanjang radius
pointVector[0] *= radius / Math.sqrt(length2);
pointVector[1] *= radius / Math.sqrt(length2);
pointVector[2] = 0;
}
return glMatrix.vec3.normalize(glMatrix.vec3.create(), pointVector);
}
var dragging, rotation = glMatrix.mat4.create();
function onMouseDown(event) { //saat mouse di drag ke bawah
var x = event.clientX;
var y = event.clientY;
var rect = event.target.getBoundingClientRect();
if(
rect.left <= x &&
rect.right >= x &&
rect.top <= y &&
rect.bottom >= y
) {
dragging = true;
}
lastPointOnTrackBall = getProjectionPointOnSurface(glMatrix.vec3.fromValues(x,y,0));
currentPointOnTrackBall = lastPointOnTrackBall;
}
function onMouseUp(event){
dragging = false;
if(currentPointOnTrackBall != lastPointOnTrackBall){
lastQuat = computeCurrentQuat();
}
}
function onMouseMove(event) {
if (dragging){
var x = event.clientX;
var y = event.clientY;
currentPointOnTrackBall = getProjectionPointOnSurface(glMatrix.vec3.fromValues(x,y,0));
glMatrix.mat4.fromQuat(rotation,computeCurrentQuat());
// var xaxis = [1,0,0,0];
// var yaxis = [0,1,0,0];
// var inverseRotation = glMatrix.mat4.create();
// glMatrix.mat4.invert(inverseRotation, rotation);
// glMatrix.vec4.transformMat4(xaxis, xaxis, inverseRotation);
// glMatrix.vec4.transformMat4(yaxis, yaxis, inverseRotation);
// var dx = (x - lastx)/60;
// var dy = (y - lasty)/60;
// var radx = glMatrix.glMatrix.toRadian(dy);
// var rady = glMatrix.glMatrix.toRadian(dx);
// glMatrix.mat4.rotate(rotation, rotation, radx, xaxis);
// glMatrix.mat4.rotate(rotation, rotation, rady, yaxis);
// }
}
}
document.addEventListener("mousedown", onMouseDown, false);
document.addEventListener("mouseup", onMouseUp, false);
document.addEventListener("mousemove", onMouseMove, false);
var cubes = [...cubeLight];
var cameraTurn = 90;
var cameraDistance = 3;
//BUKA LAMPU
var uLightOnValue = 1.;
var uLightOn = gl.getUniformLocation(shaderProgram, "uLightOn");
function onKeyPressed(event) {
if(event.keyCode == 32) { //tekan spasi
if(uLightOnValue == 0.) {
uLightOnValue = 1.;
} else if(uLightOnValue == 1.) {
uLightOnValue = 0.;
}
gl.uniform1f(uLightOn, uLightOnValue);
}
// atur cube dan kamera
else if(event.keyCode == 83) { //ini tombol S
for(let i=0;i<cubes.length;i+=10) {
cubes[i+2] += 0.0111; //mengganti arah lampu
}
lightPosition[2] += 0.0111 * 0.06;
}
else if(event.keyCode == 87) { // ini tombol W
for(let i=0;i<cubes.length;i+=10) {
cubes[i+2] -= 0.0111;
}
lightPosition[2] -= 0.0111 * 0.06;
}
else if(event.keyCode == 65) { // ini tombol A
for(let i=0;i<cubes.length;i+=10) {
cubes[i] -= 0.0111; //mengganti arah lampu
}
lightPosition[1] -= 0.0111 * 0.06;
}
else if(event.keyCode == 68) { //ini tombol D
for(let i=0;i<cubes.length;i+=10) {
cubes[i] += 0.0111; //mengganti arah lampu
}
lightPosition[1] += 0.0111 * 0.06;
}
else if(event.keyCode == 38) { //ini tombol Up
camera[2] -= 0.0111;
camupdate[2] -= 0.0111; //mengganti linear
glMatrix.mat4.lookAt(
view,
camera, // camera position
camupdate, // the point where camera looks at
[0, 1, 0] // up vector of the camera
);
gl.uniformMatrix4fv(uView, false, view);
}
else if(event.keyCode == 40) { //ini tombol Down
camera[2] += 0.0111;
camupdate[2] += 0.0111; //mengganti linear
glMatrix.mat4.lookAt(
view,
camera, // camera position
camupdate, // the point where camera looks at
[0, 1, 0] // up vector of the camera
);
gl.uniformMatrix4fv(uView, false, view);
}
else if(event.keyCode == 37) { //ini tombol Left
cameraTurn += 0.5;
let cos = Math.cos(cameraTurn*Math.PI/180.0);
let sin = Math.sin(cameraTurn*Math.PI/180.0);
camera = [cameraDistance*cos, 0, cameraDistance*sin];
glMatrix.mat4.lookAt(
view,
camera, // camera position
camupdate, // the point where camera looks at
[0, 1, 0] // up vector of the camera
);
gl.uniformMatrix4fv(uView, false, view);
}
else if(event.keyCode == 39) { //ini tombol Right
cameraTurn -= 0.5;
let cos = Math.cos(cameraTurn*Math.PI/180.0);
let sin = Math.sin(cameraTurn*Math.PI/180.0);
camera = [cameraDistance*cos, 0, cameraDistance*sin];
glMatrix.mat4.lookAt(
view,
camera, // camera position
camupdate, // the point where camera looks at
[0, 1, 0] // up vector of the camera
);
gl.uniformMatrix4fv(uView, false, view);
}
}
document.addEventListener("keydown", onKeyPressed);
//geser dan zoom in zoom out
function render() {
vertices = [...penghapusKanan, ...cubes, ...penghapusKiri, ...planeVertices,];
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
gl.uniform3fv(uLightPosition, lightPosition);
// Init the model matrix
var model = glMatrix.mat4.create();
glMatrix.mat4.multiply(model, model, rotation);
gl.uniformMatrix4fv(uModel, false, model);
// Set the model matrix for normal vector
var normalModel = glMatrix.mat3.create();
glMatrix.mat3.normalFromMat4(normalModel, model);
gl.uniformMatrix3fv(uNormalModel, false, normalModel);
// Reset the frame buffer
gl.enable(gl.DEPTH_TEST);
gl.clearColor(0.52, 0.1, 0.1, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}