-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaterial.js
97 lines (83 loc) · 2.87 KB
/
material.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
function Material(gl, vertURL, fragURL){
this.gl = gl;
this.ready = false;
this.progId = gl.createProgram();
this.shaders = [];
var obj = this;
this.queue = {textures: []};
this.textureUnits = [];
var onShaderLoaded = function(src, type){
var handle = gl.createShader(type);
gl.shaderSource(handle, src);
gl.compileShader(handle);
if (!obj.gl.getShaderParameter(handle, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(handle));
} else {
obj.shaders.push(handle);
}
if(obj.shaders.length == 2){
gl.attachShader(obj.progId, obj.shaders[0]);
gl.attachShader(obj.progId, obj.shaders[1]);
gl.linkProgram(obj.progId);
if (!gl.getProgramParameter(obj.progId, gl.LINK_STATUS)) {
console.error(gl.getProgramInfoLog(obj.progId));
return;
}
gl.validateProgram(obj.progId);
gl.detachShader(obj.progId, obj.shaders[0]);
gl.detachShader(obj.progId, obj.shaders[1]);
gl.deleteShader(obj.shaders[0]);
gl.deleteShader(obj.shaders[1]);
obj.ready = true;
obj.commitQueue();
}
};
$.get(vertURL, function(src){
onShaderLoaded(src, gl.VERTEX_SHADER);
});
$.get(fragURL, function(src){
onShaderLoaded(src, gl.FRAGMENT_SHADER);
});
this.attributes = {};
}
Material.prototype = {
use : function(){
if(this.ready)
this.gl.useProgram(this.progId);
},
getAttribLocation : function(name){
return this.gl.getAttribLocation(this.progId, name);
},
uniform1f : function(locName, value){
this.gl.uniform1f(this.gl.getUniformLocation(this.progId, locName), value);
},
uniform2f : function(locName, x, y){
this.use();
this.gl.uniform2f(this.gl.getUniformLocation(this.progId, locName), x, y);
},
uniform3f : function(locName, x, y, z){
this.gl.uniform3f(this.gl.getUniformLocation(this.progId, locName), x, y, z);
},
uniform4f : function(locName, x, y, z, w){
this.gl.uniform4f(this.gl.getUniformLocation(this.progId, locName), x, y, z, w);
},
texture : function(locName, tex){
this.use();
var textureUnit = this.textureUnits.indexOf(tex.id);
if(textureUnit == -1){
this.textureUnits.push(tex.id);
textureUnit = this.textureUnits.length - 1;
}
this.queue.textures[locName] = { texture : tex, unit : textureUnit};
},
commitQueue : function(){
var progId = this.progId;
this.use();
for(var loc in this.queue.textures){
var entry = this.queue.textures[loc];
this.gl.activeTexture(this.gl.TEXTURE0 + entry.unit);
this.gl.bindTexture(this.gl.TEXTURE_2D, entry.texture.getId());
this.gl.uniform1i(this.gl.getUniformLocation(progId, loc), entry.unit);
}
}
};