NSTimer in Cocos2d Application - cocos2d-iphone

In Cocos2d documents it is written that it is not a good idea to use NSTimer. Why is it not recommended to use NSTimer. I know there is a schedule method of Cocos2d.

Try NOT to use Cocoa’s NSTimer. Instead use cocos2d’s own scheduler.
If you use cocos2d scheduler, you will have:
automatic pause/resume.
when the
CCLayer (CCScene, CCSprite, CCNode)
enters the stage the timer will be
automatically activated, and when it
leaves the stage it will be
automatically deactivated. Your
target/selector will be called with a
delta time
from here (old broken link)
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:best_practices
updated link
http://ec2-50-16-191-191.compute-1.amazonaws.com/wiki/doku.php/prog_guide:best_practices
I would add you are adding some unwanted overhead too. If you have a lot of timers that could be a good bit of overhead.

Related

Building 'multi interface' using wxWidget

I have read several demos given by the wxWidget package, but none of them is 'multi interface'. Say I want to write a simple game using wxWidget, I may need a menu interface, a game interface, a setting interface and so on. My question is how can I build them into a single App? Do I need several wxFrame and Close and Show them from time to time? (However when I close it the application is terminated) Or is there an another way?
You can indeed have multiple frames, but by default closing the last frame terminates the application. You can use SetExitOnFrameDelete(false) to prevent this from happening or just make sure that you create the new/next frame (without necessarily showing it) before closing the previous one.
It is also possible to simply show different contents inside the same frame, e.g. by creating and showing different wxPanels inside it. wxSimplebook can be useful for this.

PyQt alarm clock: best practice for triggering alarm

I am programming a pyqt alarm clock that I would like to run in the background on my system, and show a popup whenever the specified time is met. My question is what would be the best way to handle the alarm triggering itself? I could use a QTimer but that seems really messy. Or I could have a function run every minute to check if any of my alarms match the current time (like this), but that seems wasteful considering I don't really need to check EVERY minute of the day if I don't have to, and it is less accurate.
I can post a code snippet if needed (I have the GUI built) but I don't think it's necessary. I don't need anyone to write my program for me, just point me in the right direction! I'm guessing there is some great Qt function for this already that I just don't know about yet (there always seems to be something...)

ARAnimation rendering stop working without any code change

Could there be any reason why sendARAnimationObject should stop working without any change in the code? Does rendering of bitmaps in a timer depend on any external state like battery level or sensor state etc?
Another issue is that if I use sendARAnimationObjectWithCallback the callback method in the listener onResultSendAnimationObject is never called as stated in the documentation. Could there be any other dependency causing this callback method not called at all?
It works much better with the official SDK v1.0
Now I belive I found the main reason behind. I was not calling disableARAnimationRequest anywhere in my app. Now I am calling it in onPause and it works much better next time I start the app and call enableARAnimationRequest. But I would need someone at sony to confirm this kind of behaviour. Maybe the disable method should be called in some SDK method without putting that burden on the developer. Or some kind of cleanup in SDK when you start your app and enable animation request.

Multiple Qt widgets depicting different OpenSceneGraph nodes without performance loss

We are currently facing the following problem: We have an application that needs to display a multitude of separate OpenSceneGraph scenes in different Qt widgets. For example, we might have one Qt widget depicting a sphere, while another widget depicts an icosahedron. Since we are using OpenSceneGraph 3.0.1, we followed the osgViewerQt example from the official documentation for implementing this.
The example code uses a QTimer in order to force updates for the viewer widget:
connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
_timer.start( 10 );
The problems now begin when we want to create and show multiple widgets. Since each widget comes with its own timer, performance rapidly decreases with the number of open widgets. Not only is the interaction with the OSG widgets very slow, also the interaction with other Qt widgets noticeably lags. Even a halfway recent quad-core system is almost overwhelmed when approximately 5 windows are open. This issue is definitely not related to our graphics hardware. Other applications may render much larger scenes (Blender, Meshlab etc.) without any negative performance impact.
So, to summarize: What would be the best way of creating multiple Qt widgets showing different OpenSceneGraph scenes without a performance impact?
What we already tried:
We already considered using a single osgViewer::CompositeViewer for
rendering all scene objects. However, we discarded this idea for
now because it will probably make interactions with a single widget
very complicated.
We tried putting the rendering portion of each osgViewer::CompositeViewer in a separate thread as detailed by the osgQtWidgets example.
Our second try (using threads) looked roughly like this:
class ViewerFrameThread : public OpenThreads::Thread
{
public:
ViewerFrameThread(osgViewer::ViewerBase* viewerBase):
_viewerBase(viewerBase) {}
~ViewerFrameThread()
{
cancel();
while(isRunning())
{
OpenThreads::Thread::YieldCurrentThread();
}
}
int cancel()
{
_viewerBase->setDone(true);
return 0;
}
void run()
{
int result = _viewerBase->run();
}
osg::ref_ptr<osgViewer::ViewerBase> _viewerBase;
};
However, this also resulted in a remarkable performance decrease. Each thread still requires much CPU time (which is not surprising as the basic interaction is still handled with a timer). The only advantage of this approach is that at least interaction with other Qt widgets remain possible.
The ideal solution for us would be a widget that only fires redraw requests whenever the user interacts with it, for example by clicking, double-clicking, scrolling etc. More precisely, this widget should remain idle until there is a need for an update. Is something akin to this possible at all? We would welcome any suggestions.
Having tried out several models for this problem, I am happy to report that I found one that is working perfectly. I am using a QThread (similar to the thread described above) that essentially wraps an osgViewer::ViewerBase object and simply calls viewer->run().
The trick to keep CPU usage low is to force OpenSceneGraph to render on demand only. Having tried out the various options, I found the following two settings to work best:
viewer->setRunFrameScheme( osgViewer::ViewerBase::ON_DEMAND );
viewer->setThreadingModel( osgViewer::ViewerBase::CullDrawThreadPerContext );
A viewer that is modified like this will not use spurious CPU cycles for continuous updates while still using multiple threads for culling and drawing. Other threading models might of course perform better in some cases, but for me, this was sufficient.
If any one else attempts a similar solution, be warned that some operations now require explicit redraw requests. For example, when handling interactions with OSG objects or when you are writing your own CameraManipulator class, it doesn't hurt to call viewer->requestRedraw() after changing viewer settings. Else, the viewer will only refresh when the widget requires a repaint.
In short, here's what I learned:
Don't use timers for rendering
Don't give up on multiple threads just yet
Nothing beats reading the source code (the official OSG examples were sometimes scarce on details, but the source never lies...)
It should be possible. I can't believe they used a timer running at 100Hz to update the widgets -- it's really not the right way to do it.
I don't know about OSG's architecture, but you need to figure a way to obtain a callback from OSG when the data has been changed. In the callback, you simply queue an update event to the appropriate widget like so:
void OSGCallbackForWidgetA()
{
QCoreApplication::postEvent(widgetA, new QEvent(QEvent::UpdateRequest),
Qt::LowEventPriority);
}
This callback code is thread safe and you can invoke it in any thread, whether it has been started by QThread or not. The event will be compressed, that means that it acts like a flag. Posting it sets the flag, and the flag will be reset when the widget finishes with the update. Posting it multiple times when the update is pending does not add any events to the event queue, and does not imply multiple updates.
I met similar problem when I have multiple OSG viewers in one Qt application, where one of them works well, while the rest are very "slow".
By turning on the rendering stats (press "s" on the viewer), I found that the "slow" actually is not caused by the rendering, actually the rendering is fast.
The reason why the viewers are "slow" is that many gui events are not handled. For example, whey you drag the scene, many drag events are generated by Qt, but only few are passed to the OSG viewer, so the viewers response "slowly".
The events dropping actually is due to that the rendering is too fast...in Viewer::eventTraversal(), only those relative new events are processed, and the "relative new" is measured by cutOffTime = _frameStamp->getReferenceTime(). So if Qt generates the events slower than the rendering, many events will be cut off, and thus not processed.
And finally, after I found the root cause, the solution is easy. Let's cheat a bit on the reference time of _frameStamp used in the Viewer::eventTraversal():
class MyViewer : public osgViewer::Viewer
{
...
virtual void eventTraversal();
...
}
void MyViewer::eventTraversal()
{
double reference_time = _frameStamp->getReferenceTime();
_frameStamp->setReferenceTime(reference_time*100);
osgViewer::Viewer::eventTraversal();
_frameStamp->setReferenceTime(reference_time);
return;
}
I spent also quite some time to figure out how to make this work.
I think that the answer from Gnosophilon cannot work with Qt5, as the rules for switching context thread are more strict than with Qt4 (ie, a call to moveToThread() is required on the OpenGL context object). At time of writing, OSG doesn't satisfy this rules.
(At least I couldn't make it work)
I haven't figure out how to do it in a separate thread, however, to render the scene smoothly in the UI thread, without use of fixed interval timer, one may do the following
viewer_->setRunFrameScheme(osgViewer::ViewerBase::ON_DEMAND);
viewer_->setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
osgQt::initQtWindowingSystem();
osgQt::setViewer(viewer_.get());
osgQt::setViewer() handle with global variables, so only one viewer at a time can be used.
(which can be a CompositeViewer of course)

How do I create a timer run my program repeatedly? C++

I want create timer in my program so that I can cause it to rerun every minute and I don't know how to do it in a C++ Application. In C# I could just create a timer but I'm struggling here now...
sleep(); is not an option because as far as I know it makes your program inactive for X seconds, I need my app to be active and working, calculating all the time. This is because my code is used to constantly input information into a MS Access table. I was able to create the necessary components of my code to connect and perform the insert/update to the table but this is just on of the many components to the code that I am creating. Please help me with this little (or big?) problem, I'm very new to C++ and learning ATM, but I am developing a fast learning curve. Thanks
I suppose you work on Windows, since you mentioned C#. So take a look at SetTimer, and if it is a MFC app, then look at CWnd::SetTimer.
Every platform provides api for creating a timer, which will give you a callback usually after timer expires. You can just search for the api available on your platform.
If you are using windows use setTimer function.
If you're using C++ .NET, you can use the same Timer class(es) as C#, just use the C++ syntax (using gcnew instead of new, use the ^ for GC references).
Otherwise you could just have a loop:
while (should_keep_looping) {
// do what you need to do
// if necessary:
sleep(1);
}
See here: http://www.cplusplus.com/forum/beginner/317/
There is on built in "timer" in C++, and you are correct about the behavior of sleep(). The above thread describes a custom implementation.
if you have a window you can use its message queue, as suggested by Als and Marius in their answers
you can use some task dispatcher and some timer to register a callback, e.g. functionality provided by Boost.Asio and its deadline_timer (example)
you can check if timer expired between your tasks manually as proposed in BlackJack's link
or you can create separate thread and make it call your callback when time came. Pros: you can use sleep() there and you callback will be called in parallel with your main thread. Cons: worry about synchronization