Just trying to wrap my head around QTouchEvent. Any help/advice is appreciated.
Specifically I'm a bit confused when a touch event is fired (for e.g. TouchBegin); does this represent only one unique touch point? If so why is there a list of touch points inside QTouchEvent?
If not, is it the case that Qt will group together several TouchBegin instances that happen in a given time fraction and deliver it as one event, with the list of points encapsulated in the event? Likewise a QTouchUpdate event will contain information about several touch points that are being updated at that time?
Also I assume that;
QTouchEvent::TouchPoint::id
will remain consistent throughout TouchBegin, TouchUpdate and TouchEnd. Meaning that in different touch events if I see a point with the same id, it is the same touch point that both events are referring to. Is this assumption correct?
FYI: I've been working with TUIO for sometime, so if someone is familiar with both Qt and TUIO a comparative explanation would be much easier for me to understand. I've read through Qt documentation as well, but wasn't able to find an answer to my question.
Still I'd really appreciate any help at all.
Thank you.
How exactly the events are reported seem to differ in different platforms. If you press it with two fingers, it can start with a single touch point (TouchBegin), and immediately follow that with a new QTouchEvent with two TouchUpdate points. But it can also group two touch points into the TouchBegin QTouchEvent. But I have also witnessed two TouchBegin events, event though this is kind of forbidden (see "Touch Point Grouping" in the QTouchEvent doc).
After the begin, there are again differences in the TouchUpdates. Sometimes you always get two points (or the amount you have fingers down) even if you lift one finger. In this case the pressure is 0 for the lifted finger "id". Alternatively you'll get the amount of touchpoint ids that are actually down.
The best way to understand how these are generated is to install an eventfilter and observe the events while you press them.
Related
for quite some time I've been working on an application. As programming is just a hobby this project is already taking way too long, but that's besides the point. I'm now at a point where every "problem" becomes terribly difficult to solve. And I'm thinking of refactoring the code, however that would result in a "complete" rewrite.
Let me explain the problem, and how I solved it currently. Basically I have data, and I let things to happen over this data (well I described about every program didn't I?). What happens is:
Data -> asks viewer to display -> viewer displays data based on actual data
viewer returns user input -> data -> asks "executor" to execute it -> new data
Now this used to work very well, and I was thinking originally "hey I might for example change command prompt by qt, or windows - or even take that external (C#) and simply call this program".
However as the program grew it became more and more tiresome. As the most important thing is that the data is displayed in different manners depending on what the data is and -more importantly- where it is located. So I went back to the tree & added someway to "track" what the parent-line is". Then the general viewer would search for the most specific actual widget.
It uses has a list with [location; widget] values, and finds the best matching location.
The problems starts when updating for new "data" - I have to go through all the assets - viewer, saver etc etc. Updating the check-mechanism gave me a lot of errors.. Things like "hey why is it displaying the wrong widget now again?".
Now I can completely swap this around. And instead of the tree datastructure calling to a generic viewer. I would use OO "internal" tree capabilities. The nodes would be childs (& when a new viewer or save-mechanism is needed a new child is formed).
This would remove the difficult checking mechanism, where I check the location in the tree. However it might open up a whole other can of worms.
And I'd like some comments on this? Should I keep the viewer completely separate - having difficulty checking for data? Or is the new approach better, yet it combines data & execution into a single node. (So if I wish to change from qt to say cli/C# it becomes almost impossible)
What method should I pursue in the end? Also is there something else I can do? To keep the viewer separate, yet prevent having to do checks to see what widget should be displayed?
EDIT, just to show some "code" and how my program works. Not sure if this is any good as I said already it has become quite a clusterfuck of methodologies.
It is meant to merge several "gamemaker projects" together (as GM:studio strangely lacks that feature). Gamemaker project files are simply sets of xml-files. (Main xml file with only links to other xml files, and an xml file for each resource -object, sprite, sound, room etc-). However there are some 'quirks' which make it not really possible to read with something like boost property trees or qt: 1) order of attributes/child nodes is very important at certain parts of the files. and 2) white space is often ignored however at other points it is very important to preserve it.
That being said there are also a lot of points where the node is exactly the same.. Like how a background can have <width>200</width> and a room too can have that. Yet for the user it is quite important which width he is talking about.
Anyways, so the "general viewer" (AskGUIFn) has the following typedefs to handle this:
typedef int (AskGUIFn::*MemberFn)(const GMProject::pTree& tOut, const GMProject::pTree& tIn, int) const;
typedef std::vector<std::pair<boost::regex, MemberFn> > DisplaySubMap_Ty;
typedef std::map<RESOURCE_TYPES, std::pair<DisplaySubMap_Ty, MemberFn> > DisplayMap_Ty;
Where "GMProject::pTree" is a tree node, RESOURCE_TYPES is an constant to keep track in what kind of resource I am at the moment (sprite, object etc). The "memberFn" will here simply be something that loads a widget. (Though AskGUIFn is not the only general viewer of course, this one is only opened if other "automatic" -overwrite, skip, rename- handlers have failed).
Now to show how these maps are initialized (everything in namespace "MW" is a qt widget):
AskGUIFn::DisplayMap_Ty AskGUIFn::DisplayFunctionMap_INIT() {
DisplayMap_Ty t;
DisplaySubMap_Ty tmp;
tmp.push_back(std::pair<boost::regex, AskGUIFn::MemberFn> (boost::regex("^instances "), &AskGUIFn::ExecuteFn<MW::RoomInstanceDialog>));
tmp.push_back(std::pair<boost::regex, AskGUIFn::MemberFn> (boost::regex("^code $"), &AskGUIFn::ExecuteFn<MW::RoomStringDialog>));
tmp.push_back(std::pair<boost::regex, AskGUIFn::MemberFn> (boost::regex("^(isometric|persistent|showcolour|enableViews|clearViewBackground) $"), &AskGUIFn::ExecuteFn<MW::ResourceBoolDialog>));
//etc etc etc
t[RT_ROOM] = std::pair<DisplaySubMap_Ty, MemberFn> (tmp, &AskGUIFn::ExecuteFn<MW::RoomStdDialog>);
tmp.clear();
//repeat above
t[RT_SPRITE] = std::pair<DisplaySubMap_Ty, MemberFn>(tmp, &AskGUIFn::ExecuteFn<MW::RoomStdDialog>);
//for each resource type.
Then when the tree datastructure tells the general viewer it wishes to be displayed the viewer executes the following function:
AskGUIFn::MemberFn AskGUIFn::FindFirstMatch() const {
auto map_loc(DisplayFunctionMap.find(res_type));
if (map_loc != DisplayFunctionMap.end()) {
std::string stack(CallStackSerialize());
for (auto iter(map_loc->second.first.begin()); iter != map_loc->second.first.end(); ++iter) {
if (boost::regex_search(stack, iter->first)) {
return iter->second;
}
}
return map_loc->second.second;
}
return BackupScreen;
}
And this is where the problems began to be frank. The CallStackSerialize() function depends on a call-stack.. However that call_stack is stored inside a "handler". I stored it there because everything starts FROM a handler. I'm not really sure where I ought to store this "call_stack". Introduce another object that keeps track of what's going on?
I tried going the route where I store the parent with the node itself. (Preventing the need for a call-stack). However that didn't go as well as I wished: each node simply has a vector containing its child nodes. So using pointers is out of the question to point to the parent note...
(PS: maybe I should reform this in another question..)
Refactoring/rewriting this complicated location checking mechanism out of the viewer into a dedicated class makes sense, so you can improve your solution without affecting the rest of your program. Lets call this NodeToWidgetMap.
Architecture
Seems your heading towards a Model-View-Controller architecture which is a good thing IMO. Your tree structure and its nodes are the models, where as the viewer and the "widgets" are views, and the logic selecting widgets depending on the node would be part of a controller.
The main question remains when and how you choose the widget wN for a given node N and how to store this choice.
NodeToWidgetMap: When to choose
If you can assume that wN does not change during its lifetime even though nodes are moved, you could choose it right when creating the node . Otherwise you'll need to know the location (or path through the XML) and, in consequence, find the parent of a node when requesting it.
Finding Parent Nodes
My solution would be to store pointers to instead of the node instances themselves, perhaps using boost::shared_ptr. This has drawbacks, for example copying nodes forces you to implement your own copy-constructors that uses recursion to create a deep-copy of your sub-tree. (Moving however will not affect the child nodes.)
Alternatives exist, such as keeping child nodes uptodate whenever touching the parent node respective the grandfathers vector. Or you can define a Node::findParentOf(node) function knowing that certain nodes can only (or frequently) be found as child of certain nodes. This is brute but will work reasonably well for small trees, just does not scale very well.
NodeToWidgetMap: How to choose
Try writing down the rules how to choose wN on piece of paper, perhaps just partially. Then try to translate these rules into C++. This might slightly longer in terms of code but will be easier to understand and maintain.
Your current approach is to use regular expressions for matching the XML path (stack).
My idea would be to create a lookup graph whose edges are labelled by the XML element names and whose nodes indicate which widget shall be used. This way your XML path (stack) describes a route through the graph. Then the question becomes whether to explicitly model a graph or whether a group of function calls could be used to mirror this graph.
NodeToWidgetMap: Where to store choice
Associating a unique, numeric id to each node, record the widget choice using a map from node id to widget inside the NodeToWidgetMap.
Rewriting vs Refactoring
If you rewrite you might get good leverage tieing to an existing framework such as Qt in order to focus on your program instead of rewriting the wheels. It can be easier to port a well-written program from on framework to another than to abstract around the pecularities of each platform. Qt is a nice framework for gaining experience and good understanding of the MVC-architectures.
A complete rewrite gives you a chance to rethink everything but implies the risk that you start from scratch and will be without a new version for a good amount of time. And who knows whether you will have enough time to finish? If you choose to refactor the existing structures you will improve it step by step, having a useable version after each step. But there is small risk to remain trapped in old ways of thinking, where as rewriting nearly forces you to rethink everything. So both approaches have their merits, if you enjoy programming I would rewrite. More programming, more joy.
Welcome to the world of programming!
What you describe is the typical life cycle of an application, starts as a small simple app, then it gets more and more features until it is no longer maintainable. You can't imagine how many projects I've seen in this last collapsing phase!
Do you need to refactor? Of course you do! All the time! Do you need to rewrite everything? Not so sure.
In fact the good solution is to work by cycles: you design what you need to code, you code it, you need more functionality, you design this new functionality, you refactor the code so you can integrate the new code, etc. If you don't do it like this then you will arrive to the point where its less expensive to rewrite then to refactor. Get this book: Refactoring - Martin Fowler. If you like it then get this one: Refactoring to Patterns.
As Pedro NF said, Martin Fowler "Refactoring" is the nice place to get familiar with it.
I recommend buying a copy of Robert Martins "Agile Principles, Patterns and Practices in C#" He goes over some very practical case studies that show how to overcome maintenance problems like this.
I'm trying to implement a custom widget in wxWidgets (version 2.8.12), essentially a modified single line wxTextCtrl. It takes a text input that consists of two sets of 8-digit hexadecimal numbers separated by a space, and I want the control to automatically handle that space. For example, if the user types 1-8 in twice (no press of the space bar required), the resulting contents of the text control should be:
12345678 12345678
If the user were to then place their cursor after the first '3' and backspace three times, that space should automatically adjust as they edit, resulting in:
45678123 45678
Essentially, the space should be completely transparent to the user.
I have this, for the most part, done. The code is a bit long to paste here, so here is a Gist:
https://gist.github.com/036c1a90f77521a8653c
There is one bug, however, that I can't seem to fix- upon typing the ninth digit, it automatically inserts the space, but the cursor ends up right after the space, right behind the ninth digit.
All attempts to use wxTextCtrl::SetInsertionPoint() and wxTextCtrl::SetInsertionPointEnd() have shown no success, so I've come here as a last resort in hopes that somebody can point out what I'm doing wrong.
To assist in testing this widget out, I've prepared a very quick and dirty application containing the widget:
https://gist.github.com/cf3219eb47e2bfe85b38
Or click here to download the code as a tarball:
https://gist.github.com/gists/cf3219eb47e2bfe85b38/download
Just run make to clean, compile, and run the code all at once. You'll need wxWidgets 2.8.12 installed to compile, of course.
Mostly every other facet of this widget works exactly as I want it to- it is just this one very large problem that is keeping this from working. There is, however, one tiny bug that I'm curious about, and though it isn't a major concern I'd like to fix it some time.
The space will be automatically handled even upon deleting characters, even if you delete a selection- however, if the selection that you delete ends on the ninth digit, it won't reformat the contents of the control after the deletion.
If anybody can pinpoint the cause of that it would be appreciated, but the insertion point problem is obviously my main concern.
Thanks to anybody willing to help, I tried to provide as much information and explanation as possible- if I missed anything, please let me know.
Generally speaking, it's difficult to modify the input handling of a native control as it behaves differently under different platforms. I don't know if you tested your code under all (or at least more than one) of them already but I fully expect you to find more problems.
Instead of trying to do it on your own, I'd recommend that you look at wxMaskedEdit proposed for the addition to wxWidgets itself. It's not final yet but there is a preliminary version already and I think it could work with 2.8 too (although it's developed with 2.9, of course).
Almost every game use keyboard as input. I have been searching for 2 days on this topic and found quite much about it. Keyboards have many disadvantages, but main problems I found are different layouts and second that if you are pressing 3 keys at time, it can lead to corruption (row-column error). If you don't know what I'm talking about, keyboard is made as grid and it checks which row and column has connected. But if you press E,D (row 1,2 column 3)
and R (row 1, column 4), keyboard can show even F because it find it pressed(row 2, column 4 both pressed).
So I think we can't do anything about that second, but if anyone got idea how to solve it better then use keys that don't form L, I'd be glad :)
But my main problem are different keyboard layouts which is real pain. I'm slovak so Slovak layout of numbers look like this:
+ľščťžýáíé and with shift 1234567890, we also got QWERTZ but you can use QWERTY.
You all know how the English look like but just for sure:
1234567890 and shift !##$%^&*()
Most of time I'm using english one because I got used to it when programming. Anyway there are different people using different layouts. When you are making game that depend on which key is pressed, for example good old WASD pattern, you can't use that on french one which is AZERTY layout. It would be strange. Same as using numbers for choosing gun in action game. As you can see slovak would have to press shift to get it work.
I'm also using OpeGL. There is problem when you are mapping which keys are pressed. For example widely used solution to make map of 256 bools for each charakter, is suffering from SHIFT. You press a, SHIFT and release a you got: a down, A up. So I thought about binding some keys together, as A and a, 1 and !, but then I realized I'll just change layout and everything is wrong.
So what is solution for that? I think there is someone out there that is in game industry or made some game and had to solve this. Only solution that comes on my mind is to force english layout for UI (and choosen layout for chat).
After next searching I found what I need but I need cross-platform one:
virtual key codes
And next search revealed SDL key
Result: Don't ever start with GLUT if you go making games, use SFML or SDL
Thanks to everyone for helping me, there were more problems in this so idea of key binding/mapping, SDL and so on, each helped me alot.
If you're getting a "character" every time user presses something, then your keyboard routines aren't suitable for game input - only for text entry.
You need to use input routines that completely ignore keyboard layout switching and operate on some kind of raw keycodes (so when user presses shift+a, you'll know that shift is pressed and that "a" key is pressed, but you won't get "A" character). Also, routines should allow you to query if a key is pressed or not.
For windows that is DirectInput or XInput. For cross-platform this is libsdl and SDL_GetKeyState. And you'll need to provide keymapping options for the user. Glut probably isn't suitable for your task.
The common approach seems to be to ignore the problem. Worse-is-better in its early stage.
Unfortunately I'm using svorak keyboard layout so it really doesn't just work for me.
I've been approaching this same problem by binding into multiple keys on the keyboard. So that player jumps from both x and j -keys. It doesn't do so well in something that isn't shoot-jump -kind of game.
Nice stuff would be if you could just find row/col or some driver-near interface to your keyboard.
Some auto-keyboard configuration software would be neat though I've not yet seen anything like that. Maybe we should write one?
First up, separate keypresses from text entry. You shouldn't care what letter or number comes up when you press a key with shift as well - the operating system should handle that and generate an event you can use in the rare times you need the text. Usually, you should just look for the key press and any shift presses and act on those.
Second, load the bindings from keys to commands from a data file, rather than hardcoding it. Distribute default bindings for QWERTY and whatever default layout you have. If the data format is quite straightforward then people won't mind customising it to fit their keyboard and preferences. You can also add an in-game keybinding editor later.
This isn't really about OpenGL since by default that doesn't care about keypresses. Perhaps you are using an addon library or extension that handles keys for you - ensure that whatever you're using can give you individual key values and the state of shift/alt/ctrl independently, and that it also provides text input via an independent system.
Allow your users to define the keys to use for each action ...
or use the arrow keys .. that should be pretty universal :)
Turn the keyboard input into metadata, so you could allow users to configure at their will but also provide different keyboard shortcuts depending on the keyboard layout used in a config file .
I need to create a function that undoes the previous task/addition/change. How do I do this in Borland C++?
(The program stores strings of text in a text file using "list". It is stored and then erased unless I use the save-function I've created.)
I meant creating an undo function in a simple console application by the way.
I'll give yet another answer, but I think that the coverage has been insufficient so far.
The subject is far from trivial, and googling it returns a good number of results. Many applications implement a "undo" operation, and there are many variants.
There are 2 design patterns which can help us out here:
Command: it's a reification of an action
Memento: which consists in storing state (usually implies some form of serialization)
The Command pattern is heavily used in graphic environments because there is usually various ways to accomplish an action. Think of save in Microsoft Word for example:
you can click on the save icon
you can go into File menu and click on Save
you use the shortcut, typically CTRL+S
And of course save is probably implemented in term of save as.
The advantage of the Command pattern here is twofold:
you can create a stack of objects
you can ask every object to implement an undo operation
Now, there are various issues proper to undo:
some operations cannot be undone (for example, consider rm on Linux or the empty trash bin action on Windows)
some operations are difficult to undo, or it may not be natural (you need to store some state, the object is normally destroyed but here you would need to actually store it within the command for the undo action)
generally we think of undo/redo as a stack, some software (graphics mainly) propose to undo items without actually undoing what has been done afterward, this is much more difficult to achieve, especially when the newer actions have been built on top of the to-undo one...
Because there are various problems, there are various strategies:
For a simple Command, you might consider implementing an undo (for example, adding a character can be undone by removing it)
For a more complex Command, you might consider implementing the undo as restoring the previous state (that's where Memento kick in)
If you have lots of complex Command, that could mean lots of Mementos which consumes space, you can then use an approach which consists in only memorizing one Snapshot every 10 or 20 commands, and then redoing the commands from the latest snapshot up to the undone command
In fact, you can probably mix Command and Memento at leisure, depending on the specifics of your system and thus the complexity of either.
I would only considering undoing the last action executed to begin with (using a stack of action then). The functionality of undoing whatever action the user wishes is much more complicated.
To implement Undo, you need to create an "action stack" in your application. There are two basic approaches, though:
Knowing your baseline (the last time the file was saved, or since the file was created), remember every single change that was made so that when something needs to be undone you just throw away the "top-most" item and regenerate the current view from the baseline plus all of the changes. Clicking "Redo" then just puts that item back on the stack. This has a side benefit of being able to trivially remove items anywhere in the stack without messing up other undo/redo options, although there will be special care needed to make sure that the application of "higher" states is as the user intended.
For each action, store off the change that was made to the previous state as well as the change that would be necessary to restore that previous state if you were to undo. Now when the user clicks "Undo," just do the "undo" steps. When clicking "Redo," reapply the changes that were made. In some cases the "Undo" steps will be "here's what the thing looked like before," but that can cause havoc if you want to allow users to remove items that are not on the top of the stack and then need to remove something above it.
The proper choice depends on a lot of factors, including how much data you can/will carry around. Option #1 is in some sense easier but it could become very slow to undo anything if the action stack is large.
You should check out Command Pattern.
Another reference: Using the Command pattern for undo functionality
Also see the memento pattern. Sometimes the intelligence that must go into a command to undo an operation is pretty involved. Drawing objects in a paint program for example. It can be easier just to store a memento and then restore from that memento to implement undo.
You can store snapshots of state. State is the set of data that an action can modify. When you click undo, the current state is replaced by previous. Actually it is not a trivial task, especially if the state is complex.
I've been experimenting lately on that subject. In case you don't need binary compatibility, check out https://github.com/d-led/undoredo-cpp
First, some backstory:
I'm making what may amount to be a "roguelike" game so i can exersize some interesting ideas i've got floating around in my head. The gameplay isn't going to be a dungeon crawl, but in any case, the display is going to be done in a similar fasion, with simple ascii characters.
Being that this is a self exercise, I endeavor to code most of it myself.
Eventually I'd like to have the game runnable on arbitrarily large game worlds. (to the point where i envision havening the game networked and span over many monitors in a computer lab).
Right now, I've got some code that can read and write to arbitrary sections of a text console, and a simple partitioning system set up so that i can path-find efficiently.
And now the question:
I've ran some benchmarks, and the biggest bottleneck is the re-drawing of text consoles.
Having a game world that large will require an intelligent update of the display. I don't want to have to re-push my entire game buffer every frame... I need some pointers on how to set it up so that it only draws sections of the game have have been updated. (and not just individual characters as I've got now)
I've been manipulating the windows console via windows.h, but I would also be interested in getting it to run on linux machines over a puTTY client connected to the server.
I've tried adapting some video-processing routines, as there is nearly a 1:1 ratio between pixel and character, but I had no luck.
Really I want a simple explanation of some of the principles behind it. But some example (psudo)code would be nice too.
Use Curses, or if you need to be doing it yourself, read about the VTnnn control codes. Both of these should work on windows and on *nix terms and consoles (and Windows). You can also consult the nethack source code for hints. This will let you change characters on the screen wherever changes have happened.
I am not going to claim to understand this, but I believe this is close to the issue behind James Gosling's legendary Gosling Emacs redrawing code. See his paper, titled appropriately, "A Redisplay Algorithm", and also the general string-to-string correction problem.
Having a game world that large will
require an intelligent update of the
display. I don't want to have to
re-push my entire game buffer every
frame... I need some pointers on how
to set it up so that it only draws
sections of the game have have been
updated. (and not just individual
characters as I've got now)
The size of the game world isn't really relevant, as all you need to do is work out the visible area for each client and send that data. If you have a typical 80x25 console display then you're going to be sending just 2 or 3 kilobytes of data each time, even if you add in colour codes and the like. This is typical of most online games of this nature: update what the person can see, not everything in the world.
If you want to experiment with trying to find a way to cut down what you send, then feel free to do that for learning purposes, but we're about 10 years past the point where it is inefficient to update a console display in something approaching real time and it would be a shame to waste time fixing a problem that doesn't need fixing. Note that the PDF linked above gives an O(ND) solution whereas simply sending the entire console is half of O(N), where N is defined as the sum of the lengths of A and B and D.