-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathGLUtils.pas
More file actions
465 lines (392 loc) · 11.9 KB
/
GLUtils.pas
File metadata and controls
465 lines (392 loc) · 11.9 KB
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
unit GLUtils;
interface
uses
MemoryBuffer, Mat4, GLTypes,
BrowserConsole, Web, WebGL, JS,
Types, Math, SysUtils;
type
TShader = class
public
constructor Create (context: TJSWebGLRenderingContext; vertexShaderSource, fragmentShaderSource: string);
procedure Compile;
procedure Link;
procedure Use;
function GetAttribLocation (name: string): GLint;
procedure BindAttribLocation (index: GLuint; name: string);
procedure SetUniformMat4 (name: string; value: TMat4);
procedure SetUniformVec3 (name: string; value: TVec3);
procedure SetUniformFloat (name: string; value: GLfloat);
private
gl: TJSWebGLRenderingContext;
vertexShader: TJSWebGLShader;
fragmentShader: TJSWebGLShader;
programID: TJSWebGLProgram;
function GetUniformLocation (name: string): TJSWebGLUniformLocation;
function CreateShader (theType: GLenum; source: string): TJSWebGLShader;
end;
type
TModelData = record
verticies: TJSFloat32Array; // GLfloat
// NOTE: it's not clear if WebGL supports GLuint
// https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawElements
indicies: TJSUint16Array; // GLushort
floatsPerVertex: integer;
end;
const
kModelVertexFloats = 3 + 2 + 3;
type
TModelVertex = record
pos: TVec3;
texCoord: TVec2;
normal: TVec3;
end;
procedure ModelVertexAddToBuffer(vertex: TModelVertex; buffer: TMemoryBuffer);
procedure ModelVertexAddToArray (vertex: TModelVertex; list: TJSArray);
type
TModel = class
public
constructor Create(context: TJSWebGLRenderingContext; modelData: TModelData); overload;
procedure Draw;
private
gl: TJSWebGLRenderingContext;
data: TModelData;
vertexBuffer: TJSWebGLBuffer;
indexBuffer: TJSWebGLBuffer;
elementCount: integer;
procedure EnableAttributes;
procedure Load;
end;
function LoadOBJFile (text: TJSString): TModelData;
function GLSizeof(glType: NativeInt): integer;
procedure GLFatal (gl: TJSWebGLRenderingContext; messageString: string = 'Fatal OpenGL error');
implementation
{=============================================}
{@! ___Utilities___ }
{=============================================}
procedure Fatal (messageString: string); overload;
begin
writeln('*** FATAL: ', messageString);
raise Exception.Create('FATAL');
end;
// TODO: toll free bridge to FPC strings
procedure Fatal (messageString: TJSString); overload;
begin
writeln('*** FATAL: ', messageString);
raise Exception.Create('FATAL');
end;
procedure GLFatal (gl: TJSWebGLRenderingContext; messageString: string = 'Fatal OpenGL error');
var
error: integer;
begin
error := gl.getError();
if error <> TJSWebGLRenderingContext.NO_ERROR then
begin
// TODO: case doesn't work?
case error of
TJSWebGLRenderingContext.INVALID_VALUE:
messageString := messageString+' (GL_INVALID_VALUE)';
TJSWebGLRenderingContext.INVALID_OPERATION:
messageString := messageString+' (GL_INVALID_OPERATION)';
TJSWebGLRenderingContext.INVALID_ENUM:
messageString := messageString+' (GL_INVALID_ENUM)';
otherwise
messageString := messageString+' '+IntToStr(error);
end;
Fatal(messageString);
end;
end;
function GLSizeof(glType: NativeInt): integer;
begin
case glType of
TJSWebGLRenderingContext.UNSIGNED_BYTE, TJSWebGLRenderingContext.BYTE:
result := 1;
TJSWebGLRenderingContext.SHORT, TJSWebGLRenderingContext.UNSIGNED_SHORT:
result := 2;
TJSWebGLRenderingContext.INT, TJSWebGLRenderingContext.UNSIGNED_INT:
result := 4;
TJSWebGLRenderingContext.FLOAT:
result := 4;
otherwise
Fatal('GLSizeof type is invalid.');
end;
end;
{=============================================}
{@! ___Model___ }
{=============================================}
procedure ModelVertexAddToBuffer(vertex: TModelVertex; buffer: TMemoryBuffer);
begin
buffer.AddFloats(kModelVertexFloats, [
vertex.pos.x, vertex.pos.y, vertex.pos.z,
vertex.texCoord.x, vertex.texCoord.y,
vertex.normal.x, vertex.normal.y, vertex.normal.z
]);
end;
procedure ModelVertexAddToArray (vertex: TModelVertex; list: TJSArray);
begin
list.push(vertex.pos.x);
list.push(vertex.pos.y);
list.push(vertex.pos.z);
list.push(vertex.texCoord.x);
list.push(vertex.texCoord.y);
list.push(vertex.normal.x);
list.push(vertex.normal.y);
list.push(vertex.normal.z);
end;
constructor TModel.Create(context: TJSWebGLRenderingContext; modelData: TModelData);
begin
gl := context;
data := modelData;
Load;
end;
procedure TModel.Draw;
begin
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
EnableAttributes;
gl.drawElements(gl.TRIANGLES, data.indicies.length, gl.UNSIGNED_SHORT, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, nil);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, nil);
end;
procedure TModel.EnableAttributes;
var
offset: integer;
stride: integer;
begin
// NOTE: we don't have VAO's yet so we need to enable vertex attributes for shader
// before every draw call (unless the array buffer hasn't changed between calls)
offset := 0;
stride := data.floatsPerVertex * GLSizeof(TJSWebGLRenderingContext.FLOAT);
// position
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, offset);
offset += GLSizeof(TJSWebGLRenderingContext.FLOAT) * 3;
// texture
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, stride, offset);
offset += GLSizeof(TJSWebGLRenderingContext.FLOAT) * 2;
// normal
gl.enableVertexAttribArray(2);
gl.vertexAttribPointer(2, 3, gl.FLOAT, false, stride, offset);
offset += GLSizeof(TJSWebGLRenderingContext.FLOAT) * 3;
end;
procedure TModel.Load;
begin
indexBuffer := gl.createBuffer;
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data.indicies, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, nil);
vertexBuffer := gl.createBuffer;
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, data.verticies, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, nil);
end;
type
TOBJVertex = record
position: TVec3;
textureIndex: integer;
normalIndex: integer;
end;
function ProcessFace (verticies: TJSArray; indices: TJSArray; face: TStringDynArray): TOBJVertex;
var
index: integer;
vertex: TOBJVertex;
begin
index := StrToInt(face[0]) - 1;
vertex := TOBJVertex(verticies[index]);
// NOTE: see TOBJData
// index can't exceed GLushort
if index > 65536 then
Fatal('overflowed indices array');
if face[1] <> '' then
vertex.textureIndex := StrToInt(face[1]) - 1
else
vertex.textureIndex := -1;
if face[2] <> '' then
vertex.normalIndex := StrToInt(face[2]) - 1
else
vertex.normalIndex := -1;
indices.push(index);
verticies[index] := vertex;
result := vertex;
end;
function LoadOBJFile (text: TJSString): TModelData;
const
kLineEnding = #10;
kSpace = ' '; // what code is space?
var
lines: TStringDynArray;
parts: TStringDynArray;
indices: TJSArray;
positions: TJSArray;
normals: TJSArray;
textures: TJSArray;
verticies: TJSArray;
mesh: TJSFloat32Array;
i: integer;
line: TJSString;
vertex: TOBJVertex;
vertexIndex: integer;
data: TModelData;
pos: TVec3;
texCoord: TVec2;
normal: TVec3;
begin
positions := TJSArray.new;
normals := TJSArray.new;
textures := TJSArray.new;
indices := TJSArray.new;
verticies := TJSArray.new;
lines := text.split(kLineEnding);
for i := 0 to high(lines) do
begin
line := TJSString(lines[i]);
parts := line.split(kSpace);
if line.startsWith('v ') then
begin
pos := V3(StrToFloat(parts[1]), StrToFloat(parts[2]), StrToFloat(parts[3]));
positions.push(pos);
// add new vertex
vertex.position := pos;
vertex.textureIndex := -1;
vertex.normalIndex := -1;
verticies.push(pos);
end
else if line.startsWith('vn ') then
begin
normals.push(V3(StrToFloat(parts[1]), StrToFloat(parts[2]), StrToFloat(parts[3])));
end
else if line.startsWith('vt ') then
begin
textures.push(V2(StrToFloat(parts[1]), 1 - StrToFloat(parts[2])));
end
else if line.startsWith('f ') then
begin
ProcessFace(verticies, indices, TJSString(parts[1]).split('/'));
ProcessFace(verticies, indices, TJSString(parts[2]).split('/'));
ProcessFace(verticies, indices, TJSString(parts[3]).split('/'));
end;
end;
// vec3 (position) + vec2 (texCoord) + vec3 (normal)
data.floatsPerVertex := kModelVertexFloats;
mesh := TJSFloat32Array.New(data.floatsPerVertex * verticies.length);
for i := 0 to verticies.length - 1 do
begin
vertex := TOBJVertex(verticies[i]);
vertexIndex := i * data.floatsPerVertex;
// position
pos := TVec3(positions[i]);
mesh[vertexIndex + 0] := pos.x;
mesh[vertexIndex + 1] := pos.y;
mesh[vertexIndex + 2] := pos.z;
// texture
if vertex.textureIndex <> -1 then
begin
texCoord := TVec2(textures[vertex.textureIndex]);
mesh[vertexIndex + 3] := texCoord.x;
mesh[vertexIndex + 4] := texCoord.y;
end
else
begin
mesh[vertexIndex + 3] := 0;
mesh[vertexIndex + 4] := 0;
end;
// normal
if vertex.normalIndex <> -1 then
begin
normal := TVec3(normals[vertex.normalIndex]);
mesh[vertexIndex + 5] := normal.x;
mesh[vertexIndex + 6] := normal.y;
mesh[vertexIndex + 7] := normal.z;
end;
end;
//writeln('floats: ', mesh.length);
//writeln('positions:', positions.length);
//writeln('indices:', indices.length);
data.verticies := mesh;
data.indicies := TJSUint16Array.New(TJSObject(indices));
result := data;
end;
{=============================================}
{@! ___Shader___ }
{=============================================}
function TShader.GetUniformLocation (name: string): TJSWebGLUniformLocation;
begin
// TODO: cache these. how do we use dictionarys from JS in Pascal?
result := gl.getUniformLocation(programID, name);
GLFatal(gl, 'gl.getUniformLocation');
end;
procedure TShader.SetUniformFloat (name: string; value: GLfloat);
begin
gl.uniform1f(GetUniformLocation(name), value);
GLFatal(gl, 'gl.uniform1f');
end;
procedure TShader.SetUniformVec3 (name: string; value: TVec3);
begin
//gl.uniform3fv(GetUniformLocation(name), ToFloats(value));
gl.uniform3f(GetUniformLocation(name), value.x, value.y, value.z);
GLFatal(gl, 'gl.uniform3fv');
end;
procedure TShader.SetUniformMat4 (name: string; value: TMat4);
var
list: TJSFloat32List;
begin
// TODO: fix mat4 to use flat arrays
list := TJSFloat32List(value.CopyList);
gl.uniformMatrix4fv(GetUniformLocation(name), false, list);
GLFatal(gl, 'gl.uniformMatrix4fv');
end;
function TShader.GetAttribLocation (name: string): GLint;
begin
result := gl.getAttribLocation(programID, name);
end;
procedure TShader.BindAttribLocation (index: GLuint; name: string);
begin
gl.bindAttribLocation(programID, index, name);
//GLFatal('glBindAttribLocation '+IntToStr(index)+':'+name);
end;
constructor TShader.Create (context: TJSWebGLRenderingContext; vertexShaderSource, fragmentShaderSource: string);
begin
gl := context;
vertexShader := CreateShader(gl.VERTEX_SHADER, vertexShaderSource);
fragmentShader := CreateShader(gl.FRAGMENT_SHADER, fragmentShaderSource);
end;
function TShader.CreateShader(theType: GLenum; source: string): TJSWebGLShader;
var
shader: TJSWebGLShader;
begin
shader := gl.createShader(theType);
if shader = nil then
Fatal('create shader failed');
gl.shaderSource(shader, source);
gl.compileShader(shader);
if gl.getShaderParameter(shader, gl.COMPILE_STATUS) then
begin
//writeln('loaded shader ', theType);
exit(shader);
end
else
begin
Fatal(gl.getShaderInfoLog(shader));
//gl.deleteShader(shader);
end;
end;
procedure TShader.Compile;
begin
programID := gl.createProgram;
gl.attachShader(programID, vertexShader);
gl.attachShader(programID, fragmentShader);
end;
procedure TShader.Link;
begin
gl.linkProgram(programID);
if not gl.getProgramParameter(programID, gl.LINK_STATUS) then
begin
Fatal(gl.getProgramInfoLog(programID));
//gl.deleteProgram(programID);
end;
end;
procedure TShader.Use;
begin
gl.useProgram(programID);
end;
end.