gl2helper = function (options = {}) {
const {
vertexShader = `#version 300 es
layout(location=0) in vec4 position;
layout(location=1) in vec2 texCoord;
out vec2 uv;
void main() {
uv = texCoord;
gl_Position = position;
}`,
fragmentShader = `#version 300 es
precision highp float;
in vec2 uv;
out vec4 fragColor;
void main() {
fragColor = vec4(vec3(length(uv)/sqrt(2.)),1.);
}`,
textures = {},
attributes = {
position: [
[-1, -1],
[-1, 1],
[1, 1],
[1, -1]
],
texCoord: [
[0, 0],
[0, 1],
[1, 1],
[1, 0]
]
},
fbos = null,
primitive = "triangle_fan",
count = 4
} = options;
const canvas = options.canvas
? options.canvas
: options.app
? options.app.canvas
: DOM.canvas(800, 600);
const app =
options.app || picogl.createApp(canvas, { preserveDrawingBuffer: true });
const attributeBuffers = {};
const vertexArray = app.createVertexArray();
let attrCount = 0;
for (let attr of Object.keys(attributes)) {
const avalue = attributes[attr];
const elsize = avalue[0].length || 1;
const floatArray = new Float32Array(avalue.flat());
attributeBuffers[attr] = app.createVertexBuffer(
picogl.FLOAT,
elsize,
floatArray
);
vertexArray.vertexAttributeBuffer(attrCount++, attributeBuffers[attr]);
}
const program = app.createProgram(vertexShader, fragmentShader);
const drawCall = app.createDrawCall(program, vertexArray);
const textureObjects = {};
for (let texName of Object.keys(textures)) {
textureObjects[texName] = app.createTexture2D(textures[texName], {
flipY: true,
maxAnisotropy: picogl.WEBGL_INFO.MAX_TEXTURE_ANISOTROPY,
minFilter: app.gl.LINEAR,
maxFilter: app.gl.LINEAR
});
drawCall.texture(texName, textureObjects[texName]);
}
let fboObjects = [];
if (fbos) {
for (let iFbo = 0; iFbo < fbos.length; iFbo++) {
fboObjects[iFbo] = app.createFramebuffer();
for (let iTarget = 0; iTarget < fbos[iFbo]; iTarget++) {
let colorTarget = app.createTexture2D(app.width, app.height, {
minFilter: app.gl.LINEAR,
maxFilter: app.gl.LINEAR
});
fboObjects[iFbo].colorTarget(iTarget, colorTarget);
}
}
}
drawCall.primitive(
{
triangle_fan: app.gl.TRIANGLE_FAN,
points: app.gl.POINTS,
lines: app.gl.LINES,
line_strip: app.gl.LINE_STRIP,
triangles: app.gl.TRIANGLES,
triangle_strip: app.gl.TRIANGLE_STRIP
}[primitive]
);
const bundle = {
useFbo: (iFbo) => {
if (iFbo === 0 || iFbo > 0) app.drawFramebuffer(fboObjects[iFbo]);
else app.defaultDrawFramebuffer();
return bundle;
},
depthTest: (flag) => {
if (flag) app.enable(picogl.DEPTH_TEST);
else app.disable(picogl.DEPTH_TEST);
return bundle;
},
app,
drawCall,
program,
fboObjects,
textureObjects,
canvas
};
for (let func of ["texture", "uniform", "draw"])
bundle[func] = (...args) => {
drawCall[func](...args);
return bundle;
};
for (let func of ["clear", "clearColor"])
bundle[func] = (...args) => {
app[func](...args);
return bundle;
};
return bundle;
}