I need to show two animations using WebGL on the page. Do I need to instantiate multiple shaders, or is there a way to reuse one shader? They are using the same program (so not entirely different animations). They both need to react to mouse events.
something like this
window.onload = function() {
main('canvas1');
main('canvas2');
}
function main(element) {
// Get A WebGL context
var canvas = document.getElementById(element);
var gl = getWebGLContext(canvas);
if (!gl) {
return;
}
// setup GLSL program
vertexShader = createShaderFromScriptElement(gl, "2d-vertex-shader");
fragmentShader = createShaderFromScriptElement(gl, "2d-fragment-shader");
program = createProgram(gl, [vertexShader, fragmentShader]);
gl.useProgram(program);
...
}
I don't understand the derogaratory remarks. I asked a theoretical question about webgl, not particular code.
I ran this code and it works. So now all I need to know is if I can use mouse events on both. I'd be surprised if that didn't work.
This was already answered by someone else:
Is it possible to have two WebGL contexts on the same page?
WebGL cannot share resources over multiple contexts. But you can create an object with its own gl variable, and then have multiple contexts on the page. The only limit I see now is that somehow it's intensive for the system and it won't allow more than 16 concurrent contexts.
Related
So I've been working on a small game project in js for a few months now, and I've realized that the way I've structured my game loop doesn't allow for the game to jump ahead a frame if there is lag.
This means that if the game uses up the cpu, it will start to slow down and run slower, rather than just skipping frames
This is the way I implemented it
<script src="./processing.js"></script>
<script>
var canvas = document.getElementById("mycanvas"),
ctx = canvas.getContext("2d");
var sketchProc = function(processingInstance) {
with (processingInstance) {
size(2560, 1800);
frameRate(30);
var draw = function(){
runGame();
}
}}
var canvas = document.getElementById("mycanvas");
var processingInstance = new Processing(canvas, sketchProc);
I now know that the better way to do this is to calculate how much time has passed between every loop, and then passing that value into the game update function, Eg
tFrame = calculateTimeframe();
updateGame(tFrame);
However, I didn't realize this when I started the project. Meaning that nothing is structured in a way that will allow me to update this.
Is there any way for me to fix this without manually rewriting thousands of lines of code?
(also I am using the processing.js library for this, I know it is outdated, im looking into swapping to p5js in the future)
I wrote the following JS code:
var main=function() {
var CANVAS=document.getElementById("your_canvas");
CANVAS.width=window.innerWidth;
CANVAS.height=window.innerHeight;
//ctx=CANVAS.getContext("2d");
//ctx.fillText("Hello World",10,50);
/*========================= GET WEBGL CONTEXT ========================= */
var GL;
try {
GL = CANVAS.getContext("experimental-webgl", {antialias: true});
} catch (e) {
alert("You are not webgl compatible :(") ;
return false;
}
var CUBE_VERTEX= GL.createBuffer ();
};
If I uncomment the two commented lines, then the webgl context is NULL. Is this expected ? It's not possible to use 2D context and webgl context on the same canvas ?
This is expected, as webgl basically is a wrapper around opengl, primarily used for accelerated 3D rendering. getContext("experimental-webgl") is essentially telling the browser, that the defined canvas is to be used exclusively by OpenGL/WebGL. (It is possible to use OpenGL/WebGL for 2D, but unless you know what you are doing, you're giving yourself a hard time in doing so.)
If you are trying to render text on top of a 3D view, you will have to overlay two different DOM-elements (or render the text with the correct projection in 3D, again hard time-territory).
I can't figure out what to do in case of webgl loss in my application (written with electron js) with three js. We have these two functions
// renderer is THREE.WebGLRenderer
renderer.context.canvas.addEventListener("webglcontextlost", contextLostFunction);
renderer.context.canvas.addEventListener("webglcontextrestored", contextRestoredFunction);
When I simulate context loss using something like this
var canvas = document.getElementById("playground").childNodes[0].childNodes[0];
var gl = canvas.getContext("webgl");
var WEBGL_lose_context = gl.getExtension('WEBGL_lose_context');
WEBGL_lose_context.loseContext();
Then webglcontextrestored event fires and everything restores as should be.
When webgl is killed for real or using something like this
renderer.context.getExtension( 'WEBGL_lose_context' ).loseContext();
Then this event webglcontextrestored never has been fired.
What is going ? What to do to catch that context has been lost.
Thanks for any ideas.
You should use same extension reference you use to loose the context to restore the context with the restoreContext() method of the object:
var canvas = document.getElementById("playground").childNodes[0].childNodes[0];
var gl = canvas.getContext("webgl");
var WEBGL_lose_context = gl.getExtension('WEBGL_lose_context');
WEBGL_lose_context.loseContext();
window.setTimeout(()=> {
WEBGL_lose_context.restoreContext();
}, 2000);
you can also do it from the inspector to simulate it in an iterative way...
I wonder, how can I obtain any WebGL program instance (WebGLProgram) from any desired WebGL context?
To fetch the WebGL context is NOT a problem. You are searching the DOM of the current page for the canvas element using document.getElementsByTagName() or document.getElementById(), if you know the exact canvas id:
let canvas = document.getElementById( "canvasId" );
let context = canvas.getContext( "webgl" );
Here we fetch the current context as I suppose, but if I want to get some shader parameters or get certain value from already running vertex/fragment shader - I need to have a WebGL program, which is associated with the current WebGL rendering context.
But I can't find any method in WebGL API like context.getAttachedProgram() or context.getActiveProgram().
So what is the way get the active WebGL program which is used for the rendering process?
Maybe, there is some special WebGL parameter?
There is no way to get all the programs or any other resources from a WebGL context. If the context is already existing the best you can do is look at the current resources with things like gl.getParameter(gl.CURRENT_PROGRAM) etc..
What you can do instead is wrap the WebGL context
var allPrograms = [];
someContext.createProgram = (function(oldFunc) {
return function() {
// call the real createProgram
var prg = oldFunc.apply(this, arguments);
// if a program was created save it
if (prg) {
allPrograms.push(prg);
}
return prg;
};
}(someContext.createProgram));
Of course you'd need to wrap gl.deleteProgram as well to remove things from the array of all programs.
someContext.deleteProgram = (function(oldFunc) {
return function(prg) {
// call the real deleteProgram
oldFunc.apply(this, arguments);
// remove the program from allPrograms
var ndx = allPrograms.indexOf(prg);
if (ndx >= 0) {
allPrograms.splice(ndx, 1);
}
};
}(someContext.deleteProgram));
These are the techniques used by things like the WebGL Inspector and the WebGL Shader Editor Extension.
If you want to wrap all contexts you can use a similar technique to wrap getContext.
HTMLCanvasElement.prototype.getContext = (function(oldFunc) {
return function(type) {
var ctx = oldFunc.apply(this, arguments);
if (ctx && (type === "webgl" || type === "experimental-webgl")) {
ctx = wrapTheContext(ctx);
}
return ctx;
};
}(HTMLCanvasElement.prototype.getContext));
gl.getParameter(gl.CURRENT_PROGRAM). Check out https://www.khronos.org/files/webgl/webgl-reference-card-1_0.pdf pg 2 to the right.
using Processing.js, I would like to know if what I'm trying to do is even possible. I've looked on Pomax's tutorials, Processing.js the quick start of JS developers page, PJS the Google group, here, and I can't seem to find an answer to the question, "Can you have multiple canvases, such that they all use the same processing sketch (in my example below, engine.pde) each canvas passing variables to the sketch with the result being processing opens different images in each canvas, but edits them the same way.
So to sum up, I would like to use only 1 processing sketch, with many canvases, with each canvas telling the processing sketch a different name, and having a corresponding background image open in the sketch in each canvas.
<!DOCTYPE html><html><head><meta charset="utf-8">
<script src="../../../processingjs/processing.js"></script>
<script>
// Tell sketch what counts as JavaScript per Processing on the Web tutorial
var bound = false;
function bindJavascript(instance) { // Can I pass 'instance' like this?
var pjs = Processing.getInstanceById(instance);
if(pjs!=null) {
pjs.bindJavascript(this);
bound = true; }
if(!bound) setTimeout(bindJavascript, 250); }
bindJavascript('B104');
bindJavascript('B105');
function drawSomeImages(instance) {
// This is where I am trying to tell processing that each canvas has a number, and the number is assigned to a corresponding image.
var pjs = Processing.getInstanceById(instance);
var imageName = document.getElementById(instance);
pjs.setup(instance);
}
drawSomeImages('B104');
drawSomeImages('B105');
// Where is the Mouse?
function showXYCoordinates(x, y) { ... this is working ... }
// Send images back to server
function postAjax(canvasID) { ... AJAX Stuff is working ...}
</script>
</head>
<body>
<canvas id="B104" data-processing-sources="engine.pde" onmouseout="postAjax('B104')"></canvas>
<canvas id="B105" data-processing-sources="engine.pde" onmouseout="postAjax('B105')"></canvas>
</body>
</html>
And on the processing side:
/* #pjs preload=... this is all working ; */
// Tell Processing about JavaScript, straight from the tutorial...
interface JavaScript {
void showXYCoordinates(int x, int y);
}
void bindJavascript(JavaScript js) {
javascript = js;
}
JavaScript javascript;
// Declare Variables
PImage img;
... some other variables related to the functionality ...
void setup(String instance) {
size(300,300);
img = loadImage("data/"+instance+".png");
//img = loadImage("data/B104.png"); Example of what it should open if canvas 104 using engine.pde
background(img);
smooth();
}
void draw() { ... this is fine ... }
void mouseMoved(){ ... just calls draw and checks if mouse is in canvas, fine... }
if(javascript!=null){
javascript.showXYCoordinates(mouseX, mouseY);
}}
Just add a million canvas elements to your page all with the same data-processing-sources attribute, so they all load the same file. Processing.js will build as many sketches as you ask for, it doesn't care that the sketch files are the same for each one =)
(Note that what you described, one sketch instance rendering onto multiple canvases, giving each a different image, is not how sketches work. A sketch is tied to a canvas as its drawing surface. However, you can make a million "slave" sketches whose sole responsibility is to draw images when so instructed from JavaScript, and making the master sketch tell JavaScript to tell slave sketches to draw. Note that this is very, very silly. Just make JavaScript set the image, you don't need Processing if you're just showing images really)