更新于 

三维模型

加载三维模型

加载三维模型一般流程
OperateDataType
Step1读入顶点数据verticesFloat32Array
Step2读入颜色数据colorsFloat32Array
Step3读入法线数据normalsFloat32Array
Step4读入顶点索引数据indicesUnit16Array/Unit8Array
  • Step5 数据写入缓冲区
  • Step6 gl.drawElements()

OBJ文件格式

OBJ文件格式简介

一个简单的绘制了立方体的obj文件

cube.obj绘制的立方体
cube.obj绘制的立方体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Blender v2.60 (sub 0) OBJ File: ''
# www.blender.org
mtllib cube.mtl
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -1.000000
v 1.000000 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
usemtl Material
f 1 2 3 4
f 5 8 7 6
f 2 6 7 3
f 3 7 8 4
f 5 1 4 8
usemtl Material.001
f 1 5 6 2
1
# 开头行表示注释
1
2
# Blender v2.60 (sub 0) OBJ File: ''
# www.blender.org
1
mtllib <外部材质文件名>
1
mtllib cube.mtl # 引用一个外部材质文件
1
<模型名称>
1
v x y z [w] # w值可选,没有默认为1.0
1
2
3
4
5
6
7
8
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -1.000000
v 1.000000 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
1
usemtl <材质名>
1
2
usemtl Material
usemtl Material.001

表面是由顶点、纹理坐标和法线的 索引序列 定义的
注意: 索引值从1开始

1
f v1 v2 v3 v4
1
2
3
4
5
6
7
8
usemtl Material
f 1 2 3 4
f 5 8 7 6
f 2 6 7 3
f 3 7 8 4
f 5 1 4 8
usemtl Material.001
f 1 5 6 2

包含了法线的表面的定义稍有不同
顶点索引/法线向量索引 的格式
法线向量索引也是从1开始

1
f v1//vn1 v2//vn2 v3//vn3

MTL文件格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Blender MTL File: ''
# Material Count: 2
newmtl Material
Ka 0.000000 0.000000 0.000000
Kd 1.000000 0.000000 0.000000
Ks 0.000000 0.000000 0.000000
Ns 96.078431
Ni 1.000000
d 1.000000
illum 0
newmtl Material.001
Ka 0.000000 0.000000 0.000000
Kd 1.000000 0.450000 0.000000
Ks 0.000000 0.000000 0.000000
Ns 96.078431
Ni 1.000000
d 1.000000
illum 0
1
newmtl <材质名>

表示定义一个新材质
即obj文件引用的材质名

1
usemtl 材质名
1
newmtl Material
1
2
3
4
5
6
7
Ka # 环境色
Kd # 漫射色
Ks # 高光色
Ns # 高光色权重
Ni # 表面光学密度
d # 透明度
illum # 光照模型

Ka|Kd|Ks都使用了RGB格式定义,
每个分量取值区间为 [0.0, 1.0]

1
2
3
4
5
6
7
Ka 0.000000 0.000000 0.000000
Kd 1.000000 0.000000 0.000000
Ks 0.000000 0.000000 0.000000
Ns 96.078431
Ni 1.000000
d 1.000000
illum 0

OBJViewer.js

简单步骤

Step1

准备一个空缓冲区

Step2

读取OBJ文件中的内容

Step3

对读取的内容进行解析

Step4

将解析出的数据写入缓冲区

Step5

进行绘制

自定义OBJ文件解析类

OBJ文件解析的内部结构
OBJ文件解析的内部结构
Souce Code
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

//------------------------------------------------------------------------------
// OBJParser
//------------------------------------------------------------------------------

// OBJDoc object
// Constructor
var OBJDoc = function(fileName) {
this.fileName = fileName;
this.mtls = new Array(0); // Initialize the property for MTL
this.objects = new Array(0); // Initialize the property for Object
this.vertices = new Array(0); // Initialize the property for Vertex
this.normals = new Array(0); // Initialize the property for Normal
}

// Parsing the OBJ file
OBJDoc.prototype.parse = function(fileString, scale, reverse) {
var lines = fileString.split('\n'); // Break up into lines and store them as array
lines.push(null); // Append null
var index = 0; // Initialize index of line

var currentObject = null;
var currentMaterialName = "";

// Parse line by line
var line; // A string in the line to be parsed
var sp = new StringParser(); // Create StringParser
while ((line = lines[index++]) != null) {
sp.init(line); // init StringParser
var command = sp.getWord(); // Get command
if(command == null) continue; // check null command

switch(command){
case '#':
continue; // Skip comments
case 'mtllib': // Read Material chunk
var path = this.parseMtllib(sp, this.fileName);
var mtl = new MTLDoc(); // Create MTL instance
this.mtls.push(mtl);
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status != 404) {
onReadMTLFile(request.responseText, mtl);
}else{
mtl.complete = true;
}
}
}
request.open('GET', path, true); // Create a request to acquire the file
request.send(); // Send the request
continue; // Go to the next line
case 'o':
case 'g': // Read Object name
var object = this.parseObjectName(sp);
this.objects.push(object);
currentObject = object;
continue; // Go to the next line
case 'v': // Read vertex
var vertex = this.parseVertex(sp, scale);
this.vertices.push(vertex);
continue; // Go to the next line
case 'vn': // Read normal
var normal = this.parseNormal(sp);
this.normals.push(normal);
continue; // Go to the next line
case 'usemtl': // Read Material name
currentMaterialName = this.parseUsemtl(sp);
continue; // Go to the next line
case 'f': // Read face
var face = this.parseFace(sp, currentMaterialName, this.vertices, reverse);
currentObject.addFace(face);
continue; // Go to the next line
}
}

return true;
}

OBJDoc.prototype.parseMtllib = function(sp, fileName) {
// Get directory path
var i = fileName.lastIndexOf("/");
var dirPath = "";
if(i > 0) dirPath = fileName.substr(0, i+1);

return dirPath + sp.getWord(); // Get path
}

OBJDoc.prototype.parseObjectName = function(sp) {
var name = sp.getWord();
return (new OBJObject(name));
}

OBJDoc.prototype.parseVertex = function(sp, scale) {
var x = sp.getFloat() * scale;
var y = sp.getFloat() * scale;
var z = sp.getFloat() * scale;
return (new Vertex(x, y, z));
}

OBJDoc.prototype.parseNormal = function(sp) {
var x = sp.getFloat();
var y = sp.getFloat();
var z = sp.getFloat();
return (new Normal(x, y, z));
}

OBJDoc.prototype.parseUsemtl = function(sp) {
return sp.getWord();
}

OBJDoc.prototype.parseFace = function(sp, materialName, vertices, reverse) {
var face = new Face(materialName);
// get indices
for(;;){
var word = sp.getWord();
if(word == null) break;
var subWords = word.split('/');
if(subWords.length >= 1){
var vi = parseInt(subWords[0]) - 1;
face.vIndices.push(vi);
}
if(subWords.length >= 3){
var ni = parseInt(subWords[2]) - 1;
face.nIndices.push(ni);
}else{
face.nIndices.push(-1);
}
}

// calc normal
var v0 = [
vertices[face.vIndices[0]].x,
vertices[face.vIndices[0]].y,
vertices[face.vIndices[0]].z];
var v1 = [
vertices[face.vIndices[1]].x,
vertices[face.vIndices[1]].y,
vertices[face.vIndices[1]].z];
var v2 = [
vertices[face.vIndices[2]].x,
vertices[face.vIndices[2]].y,
vertices[face.vIndices[2]].z];

// 面の法線を計算してnormalに設定
var normal = calcNormal(v0, v1, v2);
// 法線が正しく求められたか調べる
if (normal == null) {
if (face.vIndices.length >= 4) { // 面が四角形なら別の3点の組み合わせで法線計算
var v3 = [
vertices[face.vIndices[3]].x,
vertices[face.vIndices[3]].y,
vertices[face.vIndices[3]].z];
normal = calcNormal(v1, v2, v3);
}
if(normal == null){ // 法線が求められなかったのでY軸方向の法線とする
normal = [0.0, 1.0, 0.0];
}
}
if(reverse){
normal[0] = -normal[0];
normal[1] = -normal[1];
normal[2] = -normal[2];
}
face.normal = new Normal(normal[0], normal[1], normal[2]);

// Devide to triangles if face contains over 3 points.
if(face.vIndices.length > 3){
var n = face.vIndices.length - 2;
var newVIndices = new Array(n * 3);
var newNIndices = new Array(n * 3);
for(var i=0; i<n; i++){
newVIndices[i * 3 + 0] = face.vIndices[0];
newVIndices[i * 3 + 1] = face.vIndices[i + 1];
newVIndices[i * 3 + 2] = face.vIndices[i + 2];
newNIndices[i * 3 + 0] = face.nIndices[0];
newNIndices[i * 3 + 1] = face.nIndices[i + 1];
newNIndices[i * 3 + 2] = face.nIndices[i + 2];
}
face.vIndices = newVIndices;
face.nIndices = newNIndices;
}
face.numIndices = face.vIndices.length;

return face;
}

// Analyze the material file
function onReadMTLFile(fileString, mtl) {
var lines = fileString.split('\n'); // Break up into lines and store them as array
lines.push(null); // Append null
var index = 0; // Initialize index of line

// Parse line by line
var line; // A string in the line to be parsed
var name = ""; // Material name
var sp = new StringParser(); // Create StringParser
while ((line = lines[index++]) != null) {
sp.init(line); // init StringParser
var command = sp.getWord(); // Get command
if(command == null) continue; // check null command

switch(command){
case '#':
continue; // Skip comments
case 'newmtl': // Read Material chunk
name = mtl.parseNewmtl(sp); // Get name
continue; // Go to the next line
case 'Kd': // Read normal
if(name == "") continue; // Go to the next line because of Error
var material = mtl.parseRGB(sp, name);
mtl.materials.push(material);
name = "";
continue; // Go to the next line
}
}
mtl.complete = true;
}

// Check Materials
OBJDoc.prototype.isMTLComplete = function() {
if(this.mtls.length == 0) return true;
for(var i = 0; i < this.mtls.length; i++){
if(!this.mtls[i].complete) return false;
}
return true;
}

// Find color by material name
OBJDoc.prototype.findColor = function(name){
for(var i = 0; i < this.mtls.length; i++){
for(var j = 0; j < this.mtls[i].materials.length; j++){
if(this.mtls[i].materials[j].name == name){
return(this.mtls[i].materials[j].color)
}
}
}
return(new Color(0.8, 0.8, 0.8, 1));
}

//------------------------------------------------------------------------------
// Retrieve the information for drawing 3D model
OBJDoc.prototype.getDrawingInfo = function() {
// Create an arrays for vertex coordinates, normals, colors, and indices
var numIndices = 0;
for(var i = 0; i < this.objects.length; i++){
numIndices += this.objects[i].numIndices;
}
var numVertices = numIndices;
var vertices = new Float32Array(numVertices * 3);
var normals = new Float32Array(numVertices * 3);
var colors = new Float32Array(numVertices * 4);
var indices = new Uint16Array(numIndices);

// Set vertex, normal and color
var index_indices = 0;
for(var i = 0; i < this.objects.length; i++){
var object = this.objects[i];
for(var j = 0; j < object.faces.length; j++){
var face = object.faces[j];
var color = this.findColor(face.materialName);
var faceNormal = face.normal;
for(var k = 0; k < face.vIndices.length; k++){
// Set index
indices[index_indices] = index_indices;
// Copy vertex
var vIdx = face.vIndices[k];
var vertex = this.vertices[vIdx];
vertices[index_indices * 3 + 0] = vertex.x;
vertices[index_indices * 3 + 1] = vertex.y;
vertices[index_indices * 3 + 2] = vertex.z;
// Copy color
colors[index_indices * 4 + 0] = color.r;
colors[index_indices * 4 + 1] = color.g;
colors[index_indices * 4 + 2] = color.b;
colors[index_indices * 4 + 3] = color.a;
// Copy normal
var nIdx = face.nIndices[k];
if(nIdx >= 0){
var normal = this.normals[nIdx];
normals[index_indices * 3 + 0] = normal.x;
normals[index_indices * 3 + 1] = normal.y;
normals[index_indices * 3 + 2] = normal.z;
}else{
normals[index_indices * 3 + 0] = faceNormal.x;
normals[index_indices * 3 + 1] = faceNormal.y;
normals[index_indices * 3 + 2] = faceNormal.z;
}
index_indices ++;
}
}
}

return new DrawingInfo(vertices, normals, colors, indices);
}

//------------------------------------------------------------------------------
// MTLDoc Object
//------------------------------------------------------------------------------
var MTLDoc = function() {
this.complete = false; // MTL is configured correctly
this.materials = new Array(0);
}

MTLDoc.prototype.parseNewmtl = function(sp) {
return sp.getWord(); // Get name
}

MTLDoc.prototype.parseRGB = function(sp, name) {
var r = sp.getFloat();
var g = sp.getFloat();
var b = sp.getFloat();
return (new Material(name, r, g, b, 1));
}

//------------------------------------------------------------------------------
// Material Object
//------------------------------------------------------------------------------
var Material = function(name, r, g, b, a) {
this.name = name;
this.color = new Color(r, g, b, a);
}

//------------------------------------------------------------------------------
// Vertex Object
//------------------------------------------------------------------------------
var Vertex = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}

//------------------------------------------------------------------------------
// Normal Object
//------------------------------------------------------------------------------
var Normal = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}

//------------------------------------------------------------------------------
// Color Object
//------------------------------------------------------------------------------
var Color = function(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}

//------------------------------------------------------------------------------
// OBJObject Object
//------------------------------------------------------------------------------
var OBJObject = function(name) {
this.name = name;
this.faces = new Array(0);
this.numIndices = 0;
}

OBJObject.prototype.addFace = function(face) {
this.faces.push(face);
this.numIndices += face.numIndices;
}

//------------------------------------------------------------------------------
// Face Object
//------------------------------------------------------------------------------
var Face = function(materialName) {
this.materialName = materialName;
if(materialName == null) this.materialName = "";
this.vIndices = new Array(0);
this.nIndices = new Array(0);
}

//------------------------------------------------------------------------------
// DrawInfo Object
//------------------------------------------------------------------------------
var DrawingInfo = function(vertices, normals, colors, indices) {
this.vertices = vertices;
this.normals = normals;
this.colors = colors;
this.indices = indices;
}

//------------------------------------------------------------------------------
// Constructor
var StringParser = function(str) {
this.str; // Store the string specified by the argument
this.index; // Position in the string to be processed
this.init(str);
}
// Initialize StringParser object
StringParser.prototype.init = function(str){
this.str = str;
this.index = 0;
}

// Skip delimiters
StringParser.prototype.skipDelimiters = function() {
for(var i = this.index, len = this.str.length; i < len; i++){
var c = this.str.charAt(i);
// Skip TAB, Space, '(', ')
if (c == '\t'|| c == ' ' || c == '(' || c == ')' || c == '"') continue;
break;
}
this.index = i;
}

// Skip to the next word
StringParser.prototype.skipToNextWord = function() {
this.skipDelimiters();
var n = getWordLength(this.str, this.index);
this.index += (n + 1);
}

// Get word
StringParser.prototype.getWord = function() {
this.skipDelimiters();
var n = getWordLength(this.str, this.index);
if (n == 0) return null;
var word = this.str.substr(this.index, n);
this.index += (n + 1);

return word;
}

// Get integer
StringParser.prototype.getInt = function() {
return parseInt(this.getWord());
}

// Get floating number
StringParser.prototype.getFloat = function() {
return parseFloat(this.getWord());
}

// Get the length of word
function getWordLength(str, start) {
var n = 0;
for(var i = start, len = str.length; i < len; i++){
var c = str.charAt(i);
if (c == '\t'|| c == ' ' || c == '(' || c == ')' || c == '"')
break;
}
return i - start;
}

//------------------------------------------------------------------------------
// Common function
//------------------------------------------------------------------------------
function calcNormal(p0, p1, p2) {
// v0: a vector from p1 to p0, v1; a vector from p1 to p2
var v0 = new Float32Array(3);
var v1 = new Float32Array(3);
for (var i = 0; i < 3; i++){
v0[i] = p0[i] - p1[i];
v1[i] = p2[i] - p1[i];
}

// The cross product of v0 and v1
var c = new Float32Array(3);
c[0] = v0[1] * v1[2] - v0[2] * v1[1];
c[1] = v0[2] * v1[0] - v0[0] * v1[2];
c[2] = v0[0] * v1[1] - v0[1] * v1[0];

// Normalize the result
var v = new Vector3(c);
v.normalize();
return v.elements;
}

读入部分程序

OBJViewer Code
OBJViewer运行结果
OBJViewer运行结果
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
let VSHADER_SOURCE = `
attribute vec4 a_Position;
attribute vec4 a_Color;
attribute vec4 a_Normal;
uniform mat4 u_MvpMatrix;
uniform mat4 u_NormalMatrix;
varying vec4 v_Color;
void main(){
gl_Position = u_MvpMatrix * a_Position;
vec3 normal = normalize(vec3(u_NormalMatrix * a_Normal));
vec3 lightDirection = vec3(-0.35, 0.35, 0.87);
float nDotL = max(dot(normal, lightDirection), 0.0);
v_Color = vec4(nDotL*a_Color.rgb, a_Color.a);
}
`;

let FSHADER_SOURCE = `
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 v_Color;
void main(){
gl_FragColor = v_Color;
}
`
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
function main(){ 
let canvas = document.getElementById('webgl')
let gl = getWebGLContext(canvas)
if (!gl) {
console.log('failed to get webgl context')
return
}
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('failed to init shaders')
return
}
gl.clearColor(0.3, 0.3, 0.4, 1)
gl.enable(gl.DEPTH_TEST)
let program = gl.program
program.a_Position = gl.getAttribLocation(program,'a_Position')
program.a_Color = gl.getAttribLocation(program,'a_Color')
program.a_Normal = gl.getAttribLocation(program, 'a_Normal')
program.u_MvpMatrix = gl.getUniformLocation(program,'u_MvpMatrix')
program.u_NormalMatrix = gl.getUniformLocation(program,'u_NormalMatrix')

if (program.a_Postion < 0 ||
program.a_Color < 0 ||
program.a_Normal < 0 ||
!program.u_MvpMatrix ||
!program.u_NormalMatrix
) {
console.log('failed to get attribute or uniform location')
return
}
let model = initVertexBuffers(gl, program)
if (!model) {
console.log('failed to init vertex buffers')
return
}

let viewProjMatrix = new Matrix4()
viewProjMatrix.setPerspective(
30.0, canvas.width/canvas.height,1.0,5000.0
).lookAt(
0.0, 500.0, 200.0,
0, 0, 0,
0, 1, 0
)

readOBJFile('../img/cube.obj', gl, model, 60, true)

let currentAngle = 0.0
let tick = function () {
currentAngle = animate(currentAngle)
draw(gl, program, currentAngle, viewProjMatrix, model)
window.requestAnimationFrame(tick)
}
tick()
}

发起读取文件请求

1
2
3
4
5
6
7
8
9
10
11
12
let g_objDoc = null
let g_draingInfo = null
function readOBJFile(fileName, gl, model, scale, reverse) {
let request = new XMLHttpRequest()
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status !== 404) {
onReadOBJFile(request.responseText, fileName, gl, model, scale, reverse)
}
}
request.open('GET', fileName, true)
request.send()
}

文件读取结束

1
2
3
4
5
6
7
8
9
10
11
function onReadOBJFile(fileString, fileName, gl, o, scale, reverse) {
let objDoc = new OBJDoc(fileName)
let result = objDoc.parse(fileString, scale, reverse)
if (!result) {
g_objDoc = null
g_drawingInfo = null
console.log('OBJ file parsing error')
return
}
g_objDoc = objDoc
}

对读取内容解析并写入缓冲区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function onReadComplete(gl, model, objDoc) {
let drawingInfo = objDoc.getDrawingInfo()
gl.bindBuffer(gl.ARRAY_BUFFER, model.vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.vertices, gl.STATIC_DRAW)

gl.bindBuffer(gl.ARRAY_BUFFER, model.colorBuffer)
gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.colors, gl.STATIC_DRAW)

gl.bindBuffer(gl.ARRAY_BUFFER, model.normalBuffer)
gl.bufferData(gl.ARRAY_BUFFER, drawingInfo.normals, gl.STATIC_DRAW)

gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.indexBUffer)
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, drawingInfo.indices, gl.STATIC_DRAW)

return drawingInfo
}

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
let g_modelMatrix = new Matrix4()
let g_mvpMatrix = new Matrix4()
let g_normalMatrix = new Matrix4()
function draw(gl, program, angle, vpMatrix, model) {
if (g_objDoc != null && g_objDoc.isMTLComplete()) {
g_drawingInfo = onReadComplete(gl, model, g_objDoc)
g_objDoc = null
}

if (!g_drawingInfo) {
return
}

gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)


g_modelMatrix.setRotate(angle, 1, 1, 1)
g_normalMatrix.setInverseOf(g_modelMatrix)
g_normalMatrix.transpose()
gl.uniformMatrix4fv(program.u_NormalMatrix,false,g_normalMatrix.elements)
g_mvpMatrix.set(vpMatrix).multiply(g_modelMatrix)
gl.uniformMatrix4fv(program.u_MvpMatrix,false,g_mvpMatrix.elements)


gl.drawElements(gl.TRIANGLES, g_drawingInfo.indices.length, gl.UNSIGNED_SHORT, 0)
}
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
function initVertexBuffers(gl, program) {
let o = new Object()
o.vertexBuffer = createEmptyArrayBuffer(gl, program.a_Position, 3, gl.FLOAT)
o.colorBuffer = createEmptyArrayBuffer(gl, program.a_Color, 4, gl.FLOAT)
o.normalBuffer = createEmptyArrayBuffer(gl, program.a_Normal, 3, gl.FLOAT)
o.indexBUffer = gl.createBuffer()
if (!o.vertexBuffer ||
!o.colorBuffer ||
!o.normalBuffer ||
!o.indexBUffer
) {
return null
}
gl.bindBuffer(gl.ARRAY_BUFFER, null)
return o
}

function createEmptyArrayBuffer(gl,a_attribute,num,type) {
let buffer = gl.createBuffer()
if (!buffer) {
console.log('failed to create buffer')
return null
}
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.vertexAttribPointer(a_attribute, num, type, false, 0, 0)
gl.enableVertexAttribArray(a_attribute)
return buffer

}
1
2
3
4
5
6
7
8
9
10
11
var ANGLE_STEP = 30;   // The increments of rotation angle (degrees)

var last = Date.now(); // Last time that this function was called
function animate(angle) {
var now = Date.now(); // Calculate the elapsed time
var elapsed = now - last;
last = now;
// Update the current rotation angle (adjusted by the elapsed time)
var newAngle = angle + (ANGLE_STEP * elapsed) / 1000.0;
return newAngle % 360;
}