Get WebGL texture/buffer/shader count - javascript

Is there a way to get the count of the currently existing textures, buffers or shaders of a WebGL context? Like the numbers you can get in Firefox if you look at about:memory.
I'd like to check if all these are deleted successfully when my application closes.

There is no way to get that info directly from the WebGLRenderingContext but you could easily augment the context yourself something like
var numTextures = 0;
var originalCreateTextureFn = gl.createTexture;
var originalDeleteTextureFn = gl.deleteTexture;
gl.createTexture = function() {
++numTextures;
return originalCreateTextureFn.call(gl);
};
gl.deleteTexture = function(texture) {
--numTextures;
originalDeleteTextureFn.call(gl, texture);
};
You can write similar functions for other resources.
Of course if you want to be perfect you'd probably need to add a flag to each object just incase you try to delete something twice and also check the object passed in is actually the right kind. Something like
var numTextures = 0;
var originalCreateTextureFn = gl.createTexture;
var originalDeleteTextureFn = gl.deleteTexture;
gl.createTexture = function() {
++numTextures;
var texture = originalCreateTextureFn.call(gl);
texture.__deleted__ = false;
};
gl.deleteTexture = function(texture) {
if (texture && texture instanceof WebGLTexture && !texture.__deleted__) {
texture.__deleted__ = true;
--numTextures;
}
originalDeleteTextureFn.call(gl, texture);
};

Related

Why does every other object I create in a loop turns out blank on old version of Chrome?

It's something that's really bothering me, and it's also kind of important since it's part of my job.
I made an object that basically parses a hostname and puts labels on the different parts of that name.
Sounds pretty straightforward, right? HOWEVER, when I create several instances of that object in a row, every other instance turns out blank, with nothing but _proto and a few functions. No data whatsoever.
It might be important to note that I'm using an old version of Chrome (which I have to use, since the network at work is closed-circuit and it's impossible to update the software beyond what's on the net). The same code works at home.
WHAT AM I DOING WRONG, THEN?
Thanks in advance.
var reg = /([A,B,C,D,E])(\d{3})(\d{2})([F,G,H])(\d{2})/i;
var hostParser = function(hostname) {
var parsed = reg.exec(hostname);
if (parsed) {
this.prefix = parsed[1];
this.arena = parsed[2];
this.waitingRoom = parsed[3];
this.adminStatus = parsed[4];
this.ID = parsed[5];
this.hostname = hostname.toUpperCase();
return this;
}
return false;
};
Array.prototype.eliminateDuplicates = function() {
var r = [];
this.forEach(function(n) {
if (r.indexOf(n) < 0)
r.push(n);
});
return r;
};
Array.prototype.trim = function() {
var r = [];
this.forEach(function (n) {
if (!/^\s?$/.test(n))
r.push(n);
});
return r;
};
var list = [
'A40800G01',
'A40800G02',
'A40800G03',
'A40800G04',
'A40800G05',
'A40800G06',
'A40800G07',
'A40800G08',
'A40800G09'
];
list.trim().eliminateDuplicates().forEach(function (item) {
var itemParser = new hostParser(item);
console.log(itemParser);
});
This was indeed a bug with that particular Chrome version. Not being able to update, I duplicated array items on purpose and it worked.

Plain OOP Javascript: Treating localStorage as an Array doesn't work?

I am trying to implement localStorage with my simple OOP todo list.
The fiddle is here: https://jsfiddle.net/b81t2789/
I thought I could just treat the local storage like an array and copy the logic I used with my actual array but that doesn't work.
Here, right after pushing the task into the array, I added a line that stores the task in the local storage and stringifies it:
// function that adds new task to the array
function pushArray(){
var newtask = new Task(toDo.value, "No note yet");
taskItems.push(newtask);
var storedTask = localStorage.setItem(newtask, JSON.stringify(newtask));
displayStorage(result2, storedTask);
displayArray(result, newtask.Name);
appendNote(result, newtask);
}
Then right below the function that displays the new array element I added one that retrieves the item from local storage, parses it, then creates a DOM element with the new task and appends it to another container.
//function that displays array elements
function displayArray(parent,obj){
var task = make("div","class","taskitem",obj);
parent.appendChild(task);
fadeIn(task);
}
//function that displays storage elements
function displayStorage(parent,obj){
var retrieveObject = localStorage.getItem(obj);
var parseTask = JSON.parse(retrieveObject);
var newDiv = make("div", "class", "newdiv", parseTask);
parent.appendChild(newDiv);
fadeIn(newDiv);
}
This doesn't work at all, not sure why, and then if I were to be able to get this to work how would I continue to go about storing and updating notes like I did in the array with local Storage? I thought this would be easy as I figured out how to make a todo with objects and arrays pretty quickly (when I thought it would be super difficult, but it's been a week now and I've made no progress!)
I guess these are the pitfalls of learning to code by yourself, any help would be much appreciated thank you!
Here is the full javascript code:
//getElementById shortcut
function grab(id) {
return document.getElementById(id);
}
// add eventlistener shortcut
var when = function() {
return function(obj, event, func) {
obj.addEventListener(event, func, false);
};
}();
//Custom function to create DOM elements and set their contents
function make(el,type,name,content){
var theElement = document.createElement(el);
theElement.setAttribute(type, name);
theElement.innerHTML = content;
return theElement;
}
//compute style shortcut
function setStyle(theElement){
return window.getComputedStyle(theElement);
}
//fade in shortcut.
function fadeIn(theElement){
var compute = setStyle(theElement).opacity;
theElement.style.opacity = 1;
}
/*****************************************************/
var toDo = grab("todo");
var result = grab("demo");
var demolist = grab("demolist");
var button = grab("btn");
// submit input on enter which fires function that pushes task into the array.
when(toDo, "keypress", function(event){
if (event.key == "Enter" || event.keyCode == 13) {
pushArray();
toDo.value = "";
}
});
// "SHOW ARRAY" FUNCTION to verify that the array is being updated (I like this better than using the console);
when(button, "click", function(event){
demolist.innerHTML = "";
for(i=0; i< taskItems.length; i++){
demolist.innerHTML += taskItems[i].Name + " " + taskItems[i].Note + "<br>";
}
});
function showNotes(theNote){
var defaultNote = "No note yet";
if(theNote){
}
}
var taskItems = [];
/*********************************************************/
//create Task object
function Task(name, note){
this.Name = name;
this.Note = note;
this.completed = false;
}
// function that adds new task to the array
function pushArray(){
var newtask = new Task(toDo.value, "No note yet");
taskItems.push(newtask);
displayArray(result, newtask.Name);
appendNote(result, newtask);
}
//function that displays array elements
function displayArray(parent,obj){
var task = make("div","class","taskitem",obj);
parent.appendChild(task);
fadeIn(task);
}
//function that displays notes
function appendNote(theElement,obj){
var newClassItem = make("input","class","tasknote");
theElement.appendChild(newClassItem);
when(newClassItem, "keypress", submitNote.bind(null, obj, newClassItem));
}
//function for submitting notes
function submitNote(task,noteInput){
if (event.key == "Enter" || event.keyCode == 13) {
task.Note = noteInput.value;
var newNote = make("div", "class", "hasNote", task.Note);
noteInput.parentNode.replaceChild(newNote, noteInput);
fadeIn(newNote);
when(newNote,"dblclick", function(){
newNote.parentNode.replaceChild(noteInput, newNote);
});
}
}
Being localStorage a key-value storage, depending on your needs, you are better off serializing (stringifying, whatever) the array and saving in a single index.
var tasks = [
'post the question on SO',
'describe it carefully',
'get a nice reply',
'implement the suggested solution'
];
If you really need to split it for performance reasons, you have to index them by a arbitrary index. If you have reordering it gets tricky and you can either reflush the whole set of tasks every time someone adds/edits/deletes/reorder the tasks (memory-efficient, but very CPU intensive) or save the indexes in a different key so you can reconstruct the order later, like:
var tasks = {
'task1': 'implement the suggested solution',
'task2': 'describe it carefully',
'task4': 'get a nice reply',
'task9': 'post the question on SO'
};
var tasksOrder = [9, 2, 4, 1];
The first idea is very simple to implement, but will give you problems with arbitrarily long lists, the second one is much more easy on the CPU but much harder to implement (and uses more memory). It depends on the specifics of your case.

three.js textureloader multiple images

So I have a website that does a few things in webgl w/ three.js, and I noticed that loadTexture is going away soon, and that I should probably switch to using textureloaders. Basically, i'd like to preload all my textures before any code executes at the start of my code. I was thinking about doing something like below, which will allow me to load any number of images, and assign them to a texture object that can be called when needed.
var loadedtex = {}
var to_load = ['images/a.png','images/b.png','images/c.png']
var texture_loader = new THREE.TextureLoader();
for(var i=0;i<to_load.length;i++){
texture_loader.load(to_load[i],function(tex){
loadedtex[to_load[i]] = tex
})
}
I'm probably missing something obvious, but I can't quite get it to work correctly. When I use the code above, loadedtex will fill up loadedtex['images/c.png'] every time, instead of properly looping and remember which "i" value it should be using.
Proper result should be something like:
loadedtex['images/a.png'] = Three.Texture{}...
loadedtex['images/b.png'] = Three.Texture{}...
loadedtex['images/c.png'] = Three.Texture{}...
but what i really get is:
loadedtex['images/c.png'] = Three.Texture{}
I know its because the "i" variable will always be max value by the time anything loads, but i'm not sure how to accomplish what i want.
Thanks.
---edit---
This is what I ended up with. Seems to work well. Thanks for the advice.
var loadedtex = {}
var textureloaded = 0
var to_load = ['images/a.png','images/b.png','images/c.png']
var texture_loader = new THREE.TextureLoader();
load_textures = function(){
if (textureloaded == to_load.length){return}
var texture = to_load[textureloaded]
texture_loader.load(texture,function(tex){
loadedtex[texture] = tex
textureloaded += 1
load_textures()
})
}
load_textures()
If you're using ES6:
let assets = [
{ name:'img1', url:'img/img1.png' },
{ name:'img2', url:'img/img2.png' },
{ name:'img3', url:'img/img3.png' },
];
this.textures = {};
for ( let img of assets ) {
this.loader.load(img.url, ( texture ) => {
this.textures[img.name] = texture;
assets.splice( assets.indexOf(img), 1);
if ( !assets.length ) {
this.init()
}
console.log('[TextureLoader] Loaded %o', img.name);
});
}
Try to make a closure function for it like,
for(var i=0;i<to_load.length;i++){
(function(tl){
texture_loader.load(tl,function(tex){
loadedtex[tl] = tex
})
})(to_load[i]);
}

D3 dispatch pass in arguments and calling context

I understand that in D3, dispatch can be used to fire events to multiple visualisations according to this example.
I also understand that if I want to call a dispatch from an object and pass in the context, I can use apply as shown here.
However, I'm having a hard time combining the arguments from a D3 dispatch and the context that I want.
// create my dispatcher
var probeDispatch = d3.dispatch("probeLoad");
var line_count = 0;
// load a file with a bunch of JSON and send one entry every 50 ms
var lines = [[0,1],[1,2],[2,0]];
var parse_timer = window.setInterval(
function () {
parse_dispatch();
}, 50
);
function parse_dispatch(){
// send two arguments with my dispatch
probeDispatch.probeLoad(lines[line_count][0], lines[line_count][1]);
line_count += 1;
if(line_count >= lines.length){
//line_count = 0
window.clearInterval(parse_timer);
}
}
// my chart object
var genChart = function(label){
this.label = label;
// assume I've drawn my chart somewhere here
probeDispatch.on(("probeLoad."+this.label), this.probeParse);
// this next line isn't working, since the
// console.log in probeLoad still returns undefined
probeDispatch.probeLoad.apply(this);
};
genChart.prototype = {
probeParse: function(probeData, simTime) {
// How do I get the context from the object that's calling probeParse
// into the probeParse scope?
var self = this;
console.log(self.label);
}
};
new genChart("pants");
new genChart("shirt");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
It does set the context properly when you see "pants" in the console.
But then there are 3 undefined's logged, because you also call
// send two arguments with my dispatch
probeDispatch.probeLoad(lines[line_count][0], lines[line_count][1]);
without supplying context.
You need
probeDispatch.probeLoad.apply(instanceOfGenChart, [lines[line_count][0], lines[line_count][1]]);
But enabling that also requires moveing parse_dispatch down the page.
// create my dispatcher
var probeDispatch = d3.dispatch("probeLoad");
var line_count = 0;
// load a file with a bunch of JSON and send one entry every 50 ms
var lines = [[0,1],[1,2],[2,0]];
var parse_timer = window.setInterval(
function () {
parse_dispatch();
}, 50
);
// my chart object
var genChart = function(label){
this.label = label;
// assume I've drawn my chart somewhere here
probeDispatch.on(("probeLoad."+this.label), this.probeParse);
// this next line isn't working, but I don't know what to do
probeDispatch.probeLoad.apply(this);
};
genChart.prototype = {
probeParse: function(probeData, simTime) {
// How do I get the context from the object that's calling probeParse
// into the probeParse scope?
var self = this;
console.log(self.label);
}
};
var instanceOfGenChart = new genChart("pants");
function parse_dispatch(){
// send two arguments with my dispatch
probeDispatch.probeLoad.apply(instanceOfGenChart, [lines[line_count][0], lines[line_count][1]]);
line_count += 1;
if(line_count >= lines.length){
//line_count = 0
window.clearInterval(parse_timer);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
So it turns out to bring the context into the function, I have to bind() it for reasons I'm not too clear on.
// create my dispatcher
var probeDispatch = d3.dispatch("probeLoad");
var line_count = 0;
// load a file with a bunch of JSON and send one entry every 50 ms
var lines = [[0,1],[1,2],[2,0]];
var parse_timer = window.setInterval(
function () {
parse_dispatch();
}, 50
);
function parse_dispatch(){
// send two arguments with my dispatch
probeDispatch.probeLoad(lines[line_count][0], lines[line_count][1]);
line_count += 1;
if(line_count >= lines.length){
//line_count = 0
window.clearInterval(parse_timer);
}
}
// my chart object
var genChart = function(label){
this.label = label;
// assume I've drawn my chart somewhere here
probeDispatch.on(("probeLoad."+this.label), this.probeParse.bind(this));
};
genChart.prototype = {
probeParse: function(probeData, simTime) {
// How do I get the context from the object that's calling probeParse
// into the probeParse scope?
var self = this;
console.log(self.label);
}
};
new genChart("pants");
new genChart("shirt");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Added by meetamit
Bind is the solution here, because it locks a scope to an "instance" of genChart.prototype. probeParse. This way parse_dispatch (the invoker) doesn't need to know anything about scope. It's equivalent to this:
// my chart object
var genChart = function(label){
this.label = label;
var self = this;
var probeParseBound = function() { self.probeParse(); };
probeDispatch.on(("probeLoad."+this.label), probeParseBound);
};

JavaScript new objects inside objects duplicating

I'm taking an adventure into the depths of JavaScript and have come across a little problem that I can't get my head around.
Everything I know about programming is self taught, this problem might have some terminology behind it I have never heard of, so I don't know what it would be called.
I'll explain the problem I am experiencing.
I've been writing a framework for HTML5 canvas for displaying 2d and 3d graphics.
As you might expect, I have designed an element class, these elements have positions on the canvas which are built from a vector class I put together.
The problem I'm having is, if I make two "Text" objects, then call a function inside their position object, all the positions of the "Text" objects change to this value:
var usernameLabel = new C.Text('Username:');
usernameLabel.position.set(30,30)
var username = new C.Text('Hello World');
username.position.set(0,70)
console.log(usernameLabel.position.x) // 0 when it should be 30
I'm sure there is something I missed, I just can't figure out what.
C.Text.prototype = new C.Element();
C.Element.position = new JC.Vector();
Any help would be most appreciated!
This is my full Element class
C.elements = 0;
C.Element = function()
{
this.id = C.elements ++;
this.position = new C.Vector();
this.rotation = new C.Vector();
this.style = new C.Style();
this.children = [];
}
C.Element.prototype = {
constructor : C.Element,
addChildObject : function( o )
{
return this.children.push(o);
},
removeChildObject : function( o )
{
this.children.splice(o,1);
}
}
Text class
C.Text = function(string)
{
this.string = string || '';
}
C.Text.prototype = new C.Element();
C.Text.prototype.constructor = C.Text();
I also have more classes built from C.Element obviously, for example:
C.Rectangle = function(width, height)
{
this.style.setSize(width,height);
}
C.Rectangle.prototype = new C.Element();
C.Rectangle.prototype.constructor = new C.Rectangle();
var usernameLabel = new C.Text('Username:');
usernameLabel.position.set(30,30) // 0,70?
var username = new C.Text('');
username.position.set(0,70) // 0,70
var rect = new C.Rectangle(20,0);
rect.position.set(30,80) // 90,80?
var rect2 = new C.Rectangle(20,0);
rect2.position.set(90,80) // 90,80
From the looks of it, you are declaring position as a 'static' variable on the object, which means it will change. To make it change only on a specific object you need one of the following:
C.Element.prototype.position = new JC.Vector();
or inside a function within the object
this.position = new JC.Vector();
These declarations are for items that are specific to the object, where as the C.Element.position declaration is for something that will be the same in all instances of the object.
Update
Instead of declaring C.Text.prototype = new C.Element(). Try using C.Text.prototype = C.Element.prototype. Hopefully that will fix your problem. Instead of creating a new object to base it on, it bases it directly on the prototype of C.Element
I found the answer! Thanks for the help! The solution was to make the parent object do a call
for a reason I don't fully understand.
C.Text = function(string)
{
C.Object.call(this)
this.string = string || '';
return this;
}
C.Text.prototype = new C.Object();
C.Text.prototype.constructor = C.Text;

Categories