-
Notifications
You must be signed in to change notification settings - Fork 682
/
Copy pathwebgl-load-obj.html
308 lines (267 loc) · 7.86 KB
/
webgl-load-obj.html
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
<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>WebGL - load obj</title>
<link type="text/css" href="resources/webgl-tutorials.css" rel="stylesheet" />
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See https://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="resources/webgl-utils.js"></script>
<script src="resources/m4.js"></script>
<script>
"use strict";
// This is not a full .obj parser.
// see http://paulbourke.net/dataformats/obj/
function parseOBJ(text) {
// because indices are base 1 let's just fill in the 0th data
const objPositions = [[0, 0, 0]];
const objTexcoords = [[0, 0]];
const objNormals = [[0, 0, 0]];
// same order as `f` indices
const objVertexData = [
objPositions,
objTexcoords,
objNormals,
];
// same order as `f` indices
let webglVertexData = [
[], // positions
[], // texcoords
[], // normals
];
const materialLibs = [];
const geometries = [];
let geometry;
let groups = ['default'];
let material = 'default';
let object = 'default';
const noop = () => {};
function newGeometry() {
// If there is an existing geometry and it's
// not empty then start a new one.
if (geometry && geometry.data.position.length) {
geometry = undefined;
}
}
function setGeometry() {
if (!geometry) {
const position = [];
const texcoord = [];
const normal = [];
webglVertexData = [
position,
texcoord,
normal,
];
geometry = {
object,
groups,
material,
data: {
position,
texcoord,
normal,
},
};
geometries.push(geometry);
}
}
function addVertex(vert) {
const ptn = vert.split('/');
ptn.forEach((objIndexStr, i) => {
if (!objIndexStr) {
return;
}
const objIndex = parseInt(objIndexStr);
const index = objIndex + (objIndex >= 0 ? 0 : objVertexData[i].length);
webglVertexData[i].push(...objVertexData[i][index]);
});
}
const keywords = {
v(parts) {
objPositions.push(parts.map(parseFloat));
},
vn(parts) {
objNormals.push(parts.map(parseFloat));
},
vt(parts) {
// should check for missing v and extra w?
objTexcoords.push(parts.map(parseFloat));
},
f(parts) {
setGeometry();
const numTriangles = parts.length - 2;
for (let tri = 0; tri < numTriangles; ++tri) {
addVertex(parts[0]);
addVertex(parts[tri + 1]);
addVertex(parts[tri + 2]);
}
},
s: noop, // smoothing group
mtllib(parts, unparsedArgs) {
// the spec says there can be multiple filenames here
// but many exist with spaces in a single filename
materialLibs.push(unparsedArgs);
},
usemtl(parts, unparsedArgs) {
material = unparsedArgs;
newGeometry();
},
g(parts) {
groups = parts;
newGeometry();
},
o(parts, unparsedArgs) {
object = unparsedArgs;
newGeometry();
},
};
const keywordRE = /(\w*)(?: )*(.*)/;
const lines = text.split('\n');
for (let lineNo = 0; lineNo < lines.length; ++lineNo) {
const line = lines[lineNo].trim();
if (line === '' || line.startsWith('#')) {
continue;
}
const m = keywordRE.exec(line);
if (!m) {
continue;
}
const [, keyword, unparsedArgs] = m;
const parts = line.split(/\s+/).slice(1);
const handler = keywords[keyword];
if (!handler) {
console.warn('unhandled keyword:', keyword); // eslint-disable-line no-console
continue;
}
handler(parts, unparsedArgs);
}
// remove any arrays that have no entries.
for (const geometry of geometries) {
geometry.data = Object.fromEntries(
Object.entries(geometry.data).filter(([, array]) => array.length > 0));
}
return {
geometries,
materialLibs,
};
}
async function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
const canvas = document.querySelector("#canvas");
const gl = canvas.getContext("webgl");
if (!gl) {
return;
}
const vs = `
attribute vec4 a_position;
attribute vec3 a_normal;
uniform mat4 u_projection;
uniform mat4 u_view;
uniform mat4 u_world;
varying vec3 v_normal;
void main() {
gl_Position = u_projection * u_view * u_world * a_position;
v_normal = mat3(u_world) * a_normal;
}
`;
const fs = `
precision mediump float;
varying vec3 v_normal;
uniform vec4 u_diffuse;
uniform vec3 u_lightDirection;
void main () {
vec3 normal = normalize(v_normal);
float fakeLight = dot(u_lightDirection, normal) * .5 + .5;
gl_FragColor = vec4(u_diffuse.rgb * fakeLight, u_diffuse.a);
}
`;
// compiles and links the shaders, looks up attribute and uniform locations
const meshProgramInfo = webglUtils.createProgramInfo(gl, [vs, fs]);
const response = await fetch('resources/models/chair/chair.obj'); /* webglfundamentals: url */
const text = await response.text();
const obj = parseOBJ(text);
const parts = obj.geometries.map(({data}) => {
// Because data is just named arrays like this
//
// {
// position: [...],
// texcoord: [...],
// normal: [...],
// }
//
// and because those names match the attributes in our vertex
// shader we can pass it directly into `createBufferInfoFromArrays`
// from the article "less code more fun".
// create a buffer for each array by calling
// gl.createBuffer, gl.bindBuffer, gl.bufferData
const bufferInfo = webglUtils.createBufferInfoFromArrays(gl, data);
return {
material: {
u_diffuse: [Math.random(), Math.random(), Math.random(), 1],
},
bufferInfo,
};
});
const cameraTarget = [0, 0, 0];
const cameraPosition = [0, 0, 4];
const zNear = 0.1;
const zFar = 50;
function degToRad(deg) {
return deg * Math.PI / 180;
}
function render(time) {
time *= 0.001; // convert to seconds
webglUtils.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
const fieldOfViewRadians = degToRad(60);
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const projection = m4.perspective(fieldOfViewRadians, aspect, zNear, zFar);
const up = [0, 1, 0];
// Compute the camera's matrix using look at.
const camera = m4.lookAt(cameraPosition, cameraTarget, up);
// Make a view matrix from the camera matrix.
const view = m4.inverse(camera);
const sharedUniforms = {
u_lightDirection: m4.normalize([-1, 3, 5]),
u_view: view,
u_projection: projection,
};
gl.useProgram(meshProgramInfo.program);
// calls gl.uniform
webglUtils.setUniforms(meshProgramInfo, sharedUniforms);
// compute the world matrix once since all parts
// are at the same space.
const u_world = m4.yRotation(time);
for (const {bufferInfo, material} of parts) {
// calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
webglUtils.setBuffersAndAttributes(gl, meshProgramInfo, bufferInfo);
// calls gl.uniform
webglUtils.setUniforms(meshProgramInfo, {
u_world,
u_diffuse: material.u_diffuse,
});
// calls gl.drawArrays or gl.drawElements
webglUtils.drawBufferInfo(gl, bufferInfo);
}
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>
</html>