Do I need to elimate extra calls to `glUseProgram()`? - ios

Say I have a bit of code that calls glUseProgram(programId) at different points, but sometimes ends up calling glUseProgram(1) twice, with the same argument (ie program1 is asked for twice).
Should I eliminate the spurious calls to glUseProgram or does glUseProgram already perform that check internally?

As suggested in OpenGL ES Programming Guide for iOS you should prevent redundant calls for glEnable state changes. So an assumption could be made that the same applies to the glUseProgram. Even if this assumption is incorrect, it is still a good idea to order your drawing calls by program and uniform setting if possible.

On my computer, if I use gluseprogram(PROGRAMID) with the same ID twice, without setting to something else in between, the display driver crashes. So I wouldn't.
(edit) Sorry, that was not true. It was actually something to do with the SFML windowing environment. Had wrong settings so was closing the window (and thus the OpenGL environment) before the OpenGL functions were able to 'clean house'.

Related

WebGL is it possible to emulate an asynchronous call to gl.finish()

WebGL is nice and asynchronous in that you can send off a long list of rendering commands without waiting for them to complete. However, if for some reason you do need to wait for the rendering to complete, you have to do it synchronously with gl.finish(). Surely it would be better if gl.finish accepted a callback and returned immediately?
Question: Is there any way to emulate this reliably?
Usage case: I am rendering a large number of vertices to a large off-screen canvas and then using drawImage to copy sections of this large canvas to small canvases on the page. I don't actually use gl.finish() but drawImage() seems to have the same effect. In my application, re-rendering is only triggered when the user performs an action (e.g. clicking a button), and it may take several hundred milliseconds. It would be nice if during rendering the browser was still responsive allowing scrolling etc. I am looking in particular for a Chrome solution, though something that also works in Firefox and Safari would be good.
Possible (bad) answer: You could try and estimate how long rendering is going to take and then set a timeout that begins with the call to gl.finish(). However, reliably doing this estimation for all sizes of vertex buffer and all users is going to be pretty tricky and inaccurate.
Possible (non-)answer: requestAnimationFrame does what I'm looking for...it doesn't though, does it?
Possible answer in 2018: Perhaps the ImageBitmap API solves this problem - see MDN docs.
You've already partially hit on your answer: drawImage() does indeed have finish-like behavior in that it forces all outstanding drawing commands to complete before it reads back the image data. The problem is that even if gl.finish() did what you wanted it to, wait for rendering to complete, you would still have the same behavior using it as you do now. The main thread would be blocked while the rendering finishes, interrupting the user's ability to interact with the page.
Ideally what you would want in this scenario is some sort of callback that indicates when a set of draw commands have been completed without actually blocking to wait for them. Unfortunately no such callback exists (and it would be surprisingly difficult to provide one, given the way the browser's internals work!)
A decent middle-ground in your case may be to do some intelligent estimations of when you feel the image may be ready. For example, once you have dispatched your draw call spin through 3 or 4 requestAnimationFrames before you call drawImage. If you consistently observe it taking longer (10 frames?) then spin for longer. This would allow users to continue interacting with the page normally and either produce no delay when doing the draw image, because the contents have finished rendering, or much less delay because you do the synchronous step mid-way through the render. Depending on the intended usage of your site non-realtime rendering could probably even stand to spin for a full second or so before presenting.
This certainly isn't a perfect solution, and I wish I had a better answer for you. Perhaps WebGL will gain the ability to query this type of status in the future, because it would be valuable in cases like yours, but for now this is likely the best you can do.

How to get notified when glTexImage2D finished upload?

I want to render after a texture is uploaded to OpenGL, but I cannot get notified about the completition.
I do want to avoid using animation, or any kind of repetitive rendering.
Is glTexImage2D asynchronous at all? As far as I know, almost every OpenGL call is async.
It would be great anyway, if I could be informed about a glDrawArrays completition as well.
The answer is, just continue after the call to glTexImage2D returns. From your point of view it is a synchronous call in the sense that everything is properly set up after it returns. You can make texture uploads asynchronous by using PBOs as intermediate storage, but even then everything is managed by the driver for you and all you need to know is that when glTexImage2D returns you can assume the texture data to be properly uploaded and start rendering. If the texture data is not yet uploaded internally your things won't get rendered anyway and will wait for the texture to be set up.
You are correct that most OpenGL calls can be seen as asynchronous in the sense that they only schedule commands to be sent to the graphics card and the driver decides when to finally send them to the hardware and the hardware is free to decide when to process them, not to speak of the fact that nobody knows when they're actually finished. But you know what, you usually just don't care. If anything needs to block in order to wait for some previous operation to complete (like an asynchronous texture upload), then it will be managed for you automagically and once an OpenGL function returned you can be sure it has done its work from your point of view.
disclaimer: There are indeed situations when you really need to know when an actual operation has finally finished its work on the device. Though your scenario isn't one of those. One of the few situations when you might really want to synchronize operations is, when you are timing something for debugging or profiling reasons. And since OpenGL ES probably lacks ARB_timer_query, issuing a glFinish (like suggested in BlueVoodoo's answer) might be an option in this case.
EDIT: In the same way you don't get notified when your things drawn with glDrawArrays are finally rendered to screen, but you just don't care about it.
I guess you meant it's an asynchronous call? Otherwise, why do you need to get notified? If you need it to be synchronous, have a look at glFinish(). I don't know of any notifications for openGL methods.

stack corruption checking method

1) how to initialize the stack with some unique pattern? so i can check it on the exit? sample program plz
2) how to add values in prolog and check it in epilog ? sample program plz
valgrind and electric fence doesnt work with my multithreaded app it is too bulky i want some simple trick like
add const value in prolog
check it back in epilog
thanks,
Vj
In your first question I think you are talking about preventing the execution stack from being overran. There are different technique to archive this, but I think the one closest to "some unique pattern" is the canary.
Theory:
The canary is a (random) check value that is placed just below the functions return address. Before returning from the function, the system checks if the canary has the same value as before. If not, the stack has been overran, since the memory is written from lower to higher addresses, and you can't trust the return address.
How it's done:
When the return address are placed
on the stack, the canary is placed
there as well.
When the function exits, the canary is checked. If the canary has been altered, terminate the program (or whatever you find appropriate).
More information about canary values can be found here.
This (or some other stack overrun prevention technique) are generally implemented in modern compilers.
I have no idea about your second question.

Clone a lua state

Recently, I have encountered many difficulties when I was developing using C++ and Lua. My situation is: for some reason, there can be thousands of Lua-states in my C++ program. But these states should be same just after initialization. Of course, I can do luaL_loadlibs() and lua_loadfile() for each state, but that is pretty heavy(in fact, it takes a rather long time for me even just initial one state). So, I am wondering the following schema: What about keeping a separate Lua-state(the only state that has to be initialized) which is then cloned for other Lua-states, is that possible?
When I started with Lua, like you I once wrote a program with thousands of states, had the same problem and thoughts, until I realized I was doing it totally wrong :)
Lua has coroutines and threads, you need to use these features to do what you need. They can be a bit tricky at first but you should be able to understand them in a few days, it'll be well worth your time.
take a look to the following lua API call I think it is what you exactly need.
lua_State *lua_newthread (lua_State *L);
This creates a new thread, pushes it on the stack, and returns a pointer to a lua_State that represents this new thread. The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack.
There is no explicit function to close or to destroy a thread. Threads are subject to garbage collection, like any Lua object.
Unfortunately, no.
You could try Pluto to serialize the whole state. It does work pretty well, but in most cases it costs roughly the same time as normal initialization.
I think it will be hard to do exactly what you're requesting here given that just copying the state would have internal references as well as potentially pointers to external data. One would need to reconstruct those internal references in order to not just have multiple states pointing to the clone source.
You could serialize out the state after one starts up and then load that into subsequent states. If initialization is really expensive, this might be worth it.
I think the closest thing to doing what you want that would be relatively easy would be to put the states in different processes by initializing one state and then forking, however your operating system supports it:
http://en.wikipedia.org/wiki/Fork_(operating_system)
If you want something available from within Lua, you could try something like this:
How do you construct a read-write pipe with lua?

Overlapped serial port and Blue Screen of Death

I created a class that handles serial port asynchronously. I use it to communicate with a modem. I have no idea why, but sometimes, when I close my application, I get the Blue Screen and my computer restarts. I logged my code step by step, but when the BSOD appeared, and my computer restarted, the file into which I was logging data contained only white spaces. Therefore I have no idea, what the reason of the BSOD could be.
I looked through my code carefully and I found several possible reasons of the problem (I was looking for all that could lead to accessing unallocated memory and causing AV exceptions).
When I rethought the idea of asynchronous operations, a few things came to my mind. Please verify whether these are right:
1) WaitCommEvent() takes a pointer to the overlapped structure. Therefore, if I call WaitCommEvent() inside a function and then leave the function, the overlapped structure cannot be a local variable, right? The event mask variable and event handle too, right?
2) ReadFile() and WriteFile() also take references or pointers to variables. Therefore all these variables have to be accessible until the overlapped read or write operations finish, right?
3) I call WaitCommEvent() only once and check for its result in a loop, in the mean time doing other things. Because I have no idea how to terminate asynchronous operations (is it possible?), when I destroy my class that keeps a handle to a serial port, I first close the handle, and then wait for the event in the overlapped structure that was used when calling the WaitCommEvent() function. I do this to be sure that the thread that waits asynchronously for a comm event does not access any fields of my class which is destroyed. Is it a good idea or is it stupid?
try
CloseHandle(FSerialPortHandle);
if Assigned(FWaitCommEvent) then
FWaitCommEvent.WaitFor(INFINITE);
finally
FSerialPortHandle := INVALID_HANDLE_VALUE;
FreeAndNil(FWaitCommEvent);
end;
Before I noticed all these, most of the variables mentioned in point one and two were local variables of the functions that called the three methods above. Could it be the reason of the BSOD or should I look for some other mistakes in my code?
When I corrected the code, the BSOD stopped occuring, but It might be a coincidence. How do you think?
Any ideas will be appreciated. Thanks in advance.
I read the CancelIo() function documentation and it states that this method cancells all I/O operations issued by the calling thread. Is it OK to wait for the FWaitCommEvent after calling CancelIo() if I know that WaitCommEvent() was issued by a different thread than the one that calls CancelIo()?
if Assigned(FWaitCommEvent) and CancelIo(FSerialPortHandle) then
begin
FWaitCommEvent.WaitFor(INFINITE);
FreeAndNil(FWaitCommEvent);
end;
I checked what happens in such case and the thread calling this piece of code didn't get deadlocked even though it did not issue WaitCommEvent(). I tested in on Windows 7 (if it matters). May I leave the code as is or is it dangerous? Maybe I misunderstood the documentation and this is the reason of my question. I apologize for asking so many questions, but I really need to be sure about that.
Thanks.
An application running as a standard user should never be able to cause a bug check (a.k.a. BSOD). (And an application running as an Administrator should have to go well out of its way to do so.) Either you ran into a driver bug or you have bad hardware.
By default, Windows is configured to save a minidump in %SystemRoot%\minidump whenever a bug check occurs. You may be able to determine more information about the crash by loading the minidump file in WinDbg, configuring WinDbg to use the Microsoft public symbol store, and running the !analyze -v command in WinDbg. At the very least, this should identify what driver is probably at fault (though I would guess it's your modem driver).
Yes, you do need to keep the TOverlapped structure available for the duration of the overlapped operation. You're going to call GetOverlappedResult at some point, and GetOverlappedResult says it should receive a pointer to a structure that was used when starting the overlapped operation. The event mask and handle can be stored in local variables if you want; you're going to have a copy of them in the TOverlapped structure anyway.
Yes, the buffers that ReadFile and WriteFile use must remain valid. They do not make their own local copies to use internally. The documentation for ReadFile even says so:
This buffer must remain valid for the duration of the read operation. The caller must not use this buffer until the read operation is completed.
If you weren't obeying that rule, then you were likely reading into unreserved stack space, which could easily cause all sorts of unexpected behavior.
To cancel an overlapped I/O operation, use CancelIo. It's essential that you not free the memory of your TOverlapped record until you're sure the associated operation has terminated. Likewise for the buffer you're reading or writing. CancelIo does not cancel the operation immediately, so your buffers might still be in use even after you call it.

Resources