GUI design issues using C++ , Qt on Windows (Vista) - c++

This concerns C++ (MinGW), Qt, Windows Vista:
all this while i's developing non-GUI applications in C++. Recently i decided to try a GUI one in Qt and am having some design issues.
Here's the problem:
step 1: Load and display a background gif Animation using QMovie...
step 2: process huge dump files (over 2GB's)....so when i reached step 2 expectedly my GUI froze..
i was using while(getline(inputFileStream,stringLine)) {...} so i placed QCoreApplication::processEvents(); inside the loop.
The application became really slow. So i placed a counter which only if it reaches a particular value will QCoreApplication::processEvents(); be executed.
Now the gif animation has become more like series of frames with visible transition from one to another.
Any faster triggering of processEvents() slows the application down (which anyway is nowhere near the non-GUI execution time).
As i see from Windows Task Manager one core has high utilization while other has low during the execution period.
So what approach should i take? Should i delve into mutithreading (i'v never used it before)?
Stripping down everything to explain the question the program looks like this:
class Animation;
class FileProcessing;
main(int argc,char** argv) {
QApplication* app=new QApplication(argc,argv);
QLabel* label1=new QLabel(...);
QLabel* label2=new QLabel(...);
Animation* objAnim=new Animation(...); //QMovie plays gif
objAnim->show();
//fileDialogs --> ask for files..this is modal so animation is fine till this point
FileProcessing* objFileProcessing=new FileProcessing(...);
objFileProcessing->processFiles(label1,label2); //process >2GB files
//in this i repeatedly call processEvents() as written above
//delete labels,objAnim and objFileProcessing;
delete app;
return 0;
}

It's time for you to grow some balls and learn how to use threads. The GUI freezes because it runs within the same thread as the functions that deal with those large files. If you separate these tasks to be executed in different threads, the GUI can continue to be useable.
Since you have an interested in Qt, I suggest reading about QThread:
An Introduction to QThreads
Starting Threads with QThread
How To Really, Truly Use QThreads; The Full Explanation

You need to use a separate thread for the processing step.
You can have the processing thread periodically check a cancellation status variable. Should the user wish to cancel, set the variable to true. The processing thread can then exit gracefully.

Related

C++ Disable Busy/Waiting Cursor

Im creating a small program that runs in background and does some custom tasks for me like copying certain files, removing, showing and hiding files. Anyways its not important.
The problem is that when some tasks are performed my cursor changes to that busy/waiting cursor (rotating circle thingy in win7). Its not critical problem but I was wondering if I can disable it in C++.
TL:DR - I want to disable/remove the busy cursor (using C++) at least for duration of my program.
The busy cursor occurs to me most of the time when Sleep() is being run on main thread. If that's the case in your situation as well, try postponing actions with timer instead, if not, the option I can think of is to add all these tasks on another thread using CreateThread.

C++ - Execute function every X milliseconds

I can't seem to find a good answer to this:
I'm making a game, and I want the logic loop to be separate from the graphics loop. In other words I want the game to go through a loop every X milliseconds regardless of how many frames/second it is displaying.
Obviously they will both be sharing a lot of variables, so I can't have a thread/timer passing one variable back and forth... I'm basically just looking for a way to have a timer in the background that every X milliseconds sends out a flag to execute the logic loop, regardless of where the graphics loop is.
I'm open to any suggestions. It seems like the best option is to have 2 threads, but I'm not sure what the best way to communicate between them is, without constantly synchronizing large amounts of data.
You can very well do multithreading by having your "world view" exchanged every tick. So here is how it works:
Your current world view is pointed to by a single smart pointer and is read only, so no locking is necessary.
Your logic creates your (first) world view, publishes it and schedules the renderer.
Your renderer grabs a copy of the pointer to your world view and renders it (remember, read-only)
In the meantime, your logic creates a new, slightly different world view.
When it's done it exchanges the pointer to the current world view, publishing it as the current one.
Even if the renderer is still busy with the old world view there is no locking necessary.
Eventually the renderer finishes rendering the (old) world. It grabs the new world view and starts another run.
In the meantime, ... (goto step 4)
The only locking you need is for the time when you publish or grab the pointer to the world. As an alternative you can do atomic exchange but then you have to make sure you use smart pointers that can do that.
Most toolkits have an event loop (built above some multiplexing syscall like poll(2) -or the obsolete select-...), e.g. GTK has g_application_run (which is above:) gtk_main which is built above Glib main event loop (which in fact does a poll or something similar). Likewise, Qt has QApplication and its exec methods.
Very often, you can register timers within the event loop. For GTK, use GTimers, g_timeout_add etc. For Qt learn about its timers.
Very often, you can also register some idle or background processing, which is one of your function which is started by the event loop after other events and timeouts have been processed. Your idle function is expected to run quickly (usually it does a small step of some computation in a few milliseconds, to keep the GUI responsive). For GTK, use g_idle_add etc. IIRC, in Qt you can use a timer with a 0 delay.
So you could code even a (conceptually) single threaded application, using timeouts and idle processing.
Of course, you could use multi-threading: generally the main thread is running the event loop, and other threads can do other things. You have synchronization issues. On POSIX systems, a nice synchronization trick could be to use a pipe(7) to self: you set up a pipe before running the event loop, and your computation threads may write a few bytes on it, while the main event loop is "listening" on it (with GTK, using g_source_add_poll or async IO or GUnixInputStream etc.., with Qt, using QSocketNotifier etc....). Then, in the input handler running in the main loop for that pipe, you could access traditional global data with mutexes etc...
Conceptually, read about continuations. It is a relevant notion.
You could have a Draw and Update Method attached to all your game components. That way you can set it that while your game is running the update is called and the draw is ignored or any combination of the two. It also has the benefit of keeping logic and graphics completely separate.
Couldn't you just have a draw method for each object that needs to be drawn and make them globals. Then just run your rendering thread with a sleep delay in it. As long as your rendering thread doesn't write any information to the globals you should be fine. Look up sfml to see an example of it in action.
If you are running on a unix system you could use usleep() however that is not available on windows so you might want to look here for alternatives.

What is the trick to run a member function in the back-end without slowing down the main application?

Sorry I don't know how to phrase this in the title, maybe someone could help me.
I am starting to make a Qt application, let's say, the application will first show N points on the screen. Then we have a function now, called movePoints, when it is called, these points will be moved according to some algorithms.
Now when N is small, everything looks very smooth, it works very well without any problem. But if N is very large, the whole GUI sucks because movePoints is running. So whenever I touch the application window now, it becomes unresponding. But I know lots of programs seem to be able to let the movePoints function run in the back-end (with a progress bar in the status bar or something) without slowing down the main application. How can I achieve this effect?
To keep your application responsive to user interactions, you should use the processEvents function. (http://qt-project.org/doc/qt-4.8/qcoreapplication.html#processEvents)
If you'd rather have the operation occur in the background you can use the QtConcurrent module and use the asynchronous run function (http://qt-project.org/doc/qt-4.8/qtconcurrentrun.html).
Use a QTimer for an interrupt or a QThread to bring the calculation out of the main loop. See: http://qt-project.org/doc/qt-4.8/threads.html
You can use a separate thread to perform calculations in the background without blocking the Qt event loop. See QThread and QConcurrent. It's common practice in processing-intensive Qt applications to have the main thread handle the GUI while "back-end" calculations are done in "worker" threads.
If rendering the data (rather than just calculating the next state) is also an intensive operation, you can also use your worker thread(s) to create a QImage, QGraphicsScene, or similar type of object, and send it pre-built to the UI thread.
If you're limited to a single thread (e.g. your platform doesn't really support threads), then you can take your algorithm and intersperse calls to QCoreApplication::proccessEvents, which will make the GUI more responsive while the activity runs. I find that using actual threads tends to be the simpler and more maintainable approach, though.

wxWidgets - multitasking with single thread

I have a GUI app that I am creating with wxWidgets. As part of the functionality, I have to run "tasks" simultaneously with manipulation of the GUI window. For example, I may run the code:
long currentTime = wxGetLocalTime();
long stopTime = wxGetLocalTime() + 3;
while (wxGetLocalTime() != stopTime) {}
wxMessageBox("DONE IN APP");
For the duration of those 3 seconds, my application would essentially be frozen until the wxMessageBox is shown. Is there a way to have this run in the background without the use of multiple threads? It creates problems for the application that I've developing.
I was wondering if there are some types of event handling that could be used. Any sort of help is greatly appreciated.
There are 3 ways to run time-consuming tasks in GUI wx applications:
By far the most preferred is to use a different thread. The explanation of the application being "very GUI intensive" really doesn't make any sense to me, I think you should seriously reconsider your program design if its GUI intensity (whatever it is) prevents you from using background worker threads. If you do use this approach, it's pretty simple but pay special attention to the thread/program termination issues. In particular, you will need to either wait for the thread to finish (acceptable if it doesn't take a long time to run) or cancel it explicitly before exiting the program.
Use EVT_IDLE event to perform your task whenever there are no other events to process. This is not too bad for small tasks which can be broken in small enough pieces as you need to be able to resume processing in your handler. Don't forget to call event.RequestMore() to continue getting idle events even when nothing is happening otherwise.
The worst and most dangerous was is to call wxYield() as suggested by another answer. This can seem simple initially but you will regret doing it later because this can create extremely difficult to debug reentrancy problems in your code. If you do use it, you need to guard against reentrancy everywhere yourself and you should really understand what exactly this function does.
Try this:
long currentTime = wxGetLocalTime();
long stopTime = wxGetLocalTime() + 3;
while (wxGetLocalTime() != stopTime) {
wxYield();
}
wxMessageBox("DONE IN APP");
I know this is late to the game, but...
I've successfully used the EVT_IDLE method for YEARS (back in the 90's with Motif originally). The main idea is to break your task up into small pieces, where each piece calls the next piece (think linked-list). The mechanism to do this is using the CallAfter() method (using C++, of course). You just "CallAfter()" as the last step in the piece and that will allow the GUI main loop to run another iteration and possibly update GUI elements and such before calling your next piece. Just remember to keep the pieces small.
Using a background thread is really nice, but can be trickier than you imagine... eventually. As long as you know the data you're working on in the background won't be touched/viewed by anything else, you're OK. If you know this is the case, then that is the way to go. This method allows the GUI to remain fully responsive during background calculations (resizing/moving the window, etc.)
In either case, just don't forget to desensitize appropriate GUI elements as the first step so you won't accidentally launch the same background task multiple times (for example, accidentally clicking a push button multiple times in succession that launches the background thread).

Game main loop logic

I'm writing a game in c++ using allegro 5. Allegro 5 has events which are stacked in an event queue(like mouse clicked or timer ticked after 1/FSP time). So my question is how should be the logic of the main loop of my game, or since it's event based I can implement it without the main loop??
Any ideas how real games do it? Links will be good.
I have no experience with Allegro, but when using SFML and rendering a game with OpenGL, I myself poll the event queue as part of my main loop. Something like the below pseudo-code (but more abstracted):
while(game_on)
{
auto events = poll_occured_events();
for_each(events, do_somewithng_with_event);
render_game();
}
Seems to work fine so far... I'd guess something similar is possible in Allegro. Event driven games are tricky, since you need to continually update the game.
You could (possibly) have the main loop in another thread and then synchronize between event thread and game thread...
I don't have any experiences with Allegro too but logic would be the same.
(so called) Real games also have game loops but the diference is they use threads which are working parallel but within different time intervals. For instance there are different threads for physic calculations, AI, gameplay, sound, rendering... as user events are usually concers gameplay events are getting collected before it (as Max suggests) and consumed until the next frame (actually some collects it in for instance 5 frames).
As a frame might get too long, all the events coming from OS are getting collected by the game for that reason these inputs are called buffered input. There is also one another method which is called unbuffered input which doesn't work discrete but instead you test it during gameloop at the very instances it is queried.
If the user input is very important and you dont want to loose any inputs at all then you can use buffered otherwise unbuffered. However unbuffered might be tricky especially during debug.
here are some links
book excerpt game engine
Game Loops on IOS