Custom actions update method in Cocos2dx 2.0 - cocos2d-iphone

In my C++/Cocos2d-x code I have some custom Cocos2d actions; in my case, classes inheriting CCActionInterval or CCActionInstant. I notice a difference between Cocos2d-x version 1.0.1 and version 2.0 in how update methods of these classes are called . Before the upgrade, the update methods were always called at least once with time=1.0. From what I see now, in version 2.0, the update method of the instant actions is called only once with time=0. Is it always so? Can I assume that, in version 2.0, in classes inheriting CCActionInstant, the update method will be called only once and the time value will always be zero?

I'll say this first, I don't think you should be worrying about such implementation detail. When you subclass CCActionInstant, you can always assume that your subclass is an instant action. If the implementation details changed in the future, they'll probably be made to make the class even better, and your subclass should perform better.
With that being said, you might have your reason to worry about this implementation detail, so, here is an extended answer.
You can assume it is always called at time 0 as long as you don't update your library. Cocos2d-x is very dynamic, and changing according to the cocos2d-iphone version, so changes are bound to happen.
In cocos2d v2.0, all actions are managed by the CCActionManager class. So, by checking that class, you can see:
// main loop
void CCActionManager::update(float dt)
{
...
if (m_pCurrentTarget->currentAction->isDone())
{
m_pCurrentTarget->currentAction->stop();
CCAction *pAction = m_pCurrentTarget->currentAction;
// Make currentAction nil to prevent removeAction from salvaging it.
m_pCurrentTarget->currentAction = NULL;
removeAction(pAction);
}
}
As you can see, removeAction is called when the isDone() is true. Not surprisingly, the isDone() method in CCActionInstant always returns true, hence always gets removed after excuting once :).

Related

Programming pattern for components that are toggleable at runtime

I'm wondering if there is some kind of logical programming pattern or structure that I should be using if sometimes during runtime a component should be used and other times not. The obvious simple solution is to just use if-else statements everywhere. I'm trying to avoid littering my code with if-else statements since once the component is toggled on, it will more than likely be on for a while and I wonder if its worth it to recheck if the same component is active all over the place when the answer will most likely not have changed between checks.
Thanks
A brief example of what I'm trying to avoid
class MainClass
{
public:
// constructors, destructors, etc
private:
ComponentClass m_TogglableComponent;
}
// somewhere else in the codebase
if (m_TogglableComponent.IsActive())
{
// do stuff
}
// somewhere totally different in the codebase
if (m_TogglableComponent.IsActive())
{
// do some different stuff
}
Looks like you're headed towards a feature toggle. This is a common occurrence when there's a piece of functionality that you need to be able to toggle on or off at run time. The key piece of insight with this approach is to use polymorphism instead of if/else statements, leveraging object oriented practices.
Martin Fowler details an approach here, as well as his rationale: http://martinfowler.com/articles/feature-toggles.html
But for a quick answer, instead of having state in your ComponentClass that tells observers whether it's active or not, you'll want to make a base class, AbstractComponentClass, and two base classes ActiveComponentClass and InactiveComponentClass. Bear in mind that m_TogglableComponent is currently an automatic member, and you'll need to make it a pointer under this new setup.
AbstractComponentClass will define pure virtual methods that both need to implement. In ActiveComponentClass you will put your normal functionality, as if it were enabled. In InactiveComponentClass you do as little as possible, enough to make the component invisible as far as MainClass is concerned. Void functions will do nothing and functions return values will return neutral values.
The last step is creating an instance of one of these two classes. This is where you bring in dependency injection. In your constructor to MainClass, you'll take a pointer of type AbstractComponentClass. From there on it doesn't care if it's Active or Inactive, it just calls the virtual functions. Whoever owns or controls MainClass is the one that injects the kind that you want, either active or inactive, which could be read by configuration or however else your system decides when to toggle.
If you need to change the behaviour at run time, you'll also need a setter method that takes another AbstractComponentClass pointer and replaces the one from the constructor.

Where does a generic List<> implement Reset?

when I go to the definition of List<> I can see it has a public struct Enumerator that implements the interfaces IEnumerator<T>, IDisposable and IEnumerator.
IEnumerator should force the implementation of Reset - besides Current and MoveNext. Yet only Current and MoveNext are implemented.
How can that be?
Where do I find the Reset() of List<>?
var list = new List<int>();
list.Add(23);
list.Add(44);
var Enumerator = list.GetEnumerator();
while (Enumerator.MoveNext())
{
Console.WriteLine(Enumerator.Current);
}
Enumerator.
And when I try it in code there is no Reset():
Ok - I tried to show a screenshot, but they don't let me.
But copying above code shows no Reset-Method after the Dot-operator (.) of Enumerator.
Would someone know and throw some light on this?
I see it calls the Reset of IEnumerator which is part of mscorlib.
var list = new List<int>();
list.Add(23);
list.Add(44);
var Enumerator = list.GetEnumerator();
Enumerator.MoveNext();
Enumerator.MoveNext();
Console.WriteLine(Enumerator.Current);
((IEnumerator<int>)Enumerator).Reset();
Enumerator.MoveNext();
And yet as IEnumerator is an interface how can code be called by it?
Reset() in IEnumerator should just be a definition and the implementation left to whoever uses the interface.
But somehow here actual functionality is provided by just defining the interface to be implemented. Nowhere do I see the actual implementation - and that part I do not understand.
It's explicitly implemented, as shown in the documentation, as is IEnumerator.Current. In other words, you can only call the method on a value with a compile-time type of IEnumerator.
So you could use:
// Casing changed to be more conventional
var enumerator = list.GetEnumerator();
((IEnumerator)enumerator).Reset();
However, that would then box the value anyway (as List<T>.Enumerator is a struct) which would make it pointless. It's not clear whether you're just interested in the apparent lack of a Reset method, but in general I would strongly advise you not to rely on IEnumerator.Reset - it's very often not implemented, and IMO it shouldn't have been part of the interface to start with...
You think you are using the IEnumerator<> interface, but you are not. Type inference is getting the better of you, the type of your Enumerator variable is actually List.Enumerator<>, a structure type. Use the interface and you'll have no trouble:
IEnumerator<int> Enumerator = list.GetEnumerator();
while (Enumerator.MoveNext()) {
Console.WriteLine(Enumerator.Current);
}
Enumerator.Reset(); // Fine
It doesn't work on List.Enumerator<> because Microsoft intentionally hid the Reset() method implementation by making it private. Note how iterators for other collection classes like Dictionary and HashSet behave this way as well.
That could use an explanation. IEnumerator encapsulates a forward-only iterator and is the foundation upon which the house of Linq was built. The Reset() method is a problem, that's no longer strictly forward-only. You move the iterator back. In practice, you'll find out that in many cases trying to call Reset() produces a NotImplementedException. Not a problem for List, easy to go back. Big problem for Linq.
IEnumerator should have been designed without a Reset() method. But it wasn't the .NET designers' choice, this was nailed down before 1996, long before anybody started working on .NET. Iterators were an existing concept in COM Automation. Which was the extension model for Visual Basic version 4, it replaced the 16-bit VBX model.
Wildly popular, almost any language runtime on Windows implements it. And still very heavily used in .NET programs. Skillfully hidden in most cases, no way to tell that you are using it when you put a WebBrowser on your UI for example. The .NET designers were forced to implement it as well to have a shot at getting programmers to move to .NET. Also the source of the very troublesome ICloneable interface.

Which is the design pattern for easy maintanace of backward compatibility of data files?

We develop a desktop application which goes into versions. We save the data in a file (which has version in which it is saved) and open it lateron to work on it. Since our data model keeps changing over versions, we keep adding APIs like upgrade_from_ver1_to_ver2. This is getting chiotic, since we are now in version 10.0. We also slowly stop supporting older versions (say files saved before 4.0). Can you suggest a better way or a design pattern to save and provide backward compatibility?
It will be good if this can be designed as a seperate utility, called during import/opening of data files. It shall also be called seperately just to get current data model from old data files.
How about you just implement an upgrade function from the version before to the new version? Then you can chain those together to upgrade from an older version.
This seems to me the minimal implementation effort, while always allowing to upgrades from any prior version. The downside is, that you might loose information in the conversion chain, e.g. if the possible values of one property is reduced in one version and later extended again.
The first important thing to do is to have a separate class(es) for saving your data so your data objects aren't burdened with the responsibility of saving.
Next I would use the template pattern, defining the basics of your read/open operation. Your AbstractReader class might just define a single Read method. You could then create classes inheriting from the AbstractReader - potentially one for each file version. You could then use the abstract factory pattern to detect the version of file being opened, then return the corresponding Reader implementation for that version.
You can use ParallelChange Design Pattern here.
To give you a little bit idea, this pattern has 3 phases expand, migrate, and contract.
Let say you have method1 in your file and you want to update the method structure.
public void method1(Obj1 obj1) {
...
}
1. Expand
Now you need to support different data structure with backward compatibility. Then add new method keeping the old one as is.
public void method1(Obj1 obj1) {
...
}
public void method1(Obj2 obj2) {
...
}
After this release, all your clients will still use the method1(Obj1 obj1). You have just added capability to call a different method which will use now onwards.
2. Migrate
In this phase, you need to upgrade your all clients to new method structure ie method1(Obj2 obj2). Sometimes we need to force the client to use the new method structure and sometimes the client moves gradually. We generally stop to give new features to deprecated methods. Like after the first Expand, we found a bug in method1(Obj1 obj1), we say this will be solved in method1(Obj2 obj2).
3. Contract
Once your all clients are moved, it's totally safe to remove your method1(Obj1 obj1) implementation.
Eventually, you will upgrade your system from version to version with backward compatibility.
The only downfall that I personally feel is, it will take at least 3 release before you remove your whole code. But without a doubt, this would be surely hassle-free.

Testing a custom PolicyViolationHandler in FluentSecurity

I have written a custom policy in FluentSecurity (implement ISecurityPolicy) and a corresponding PolicyViolationHandler by implementing IPolicyViolationHandler. Everything is working perfectly with the policy and the handler, however I'm doing some back-filling by writing some unit tests to test my implementation of IPolicyViolationHandler.Handle(PolicyViolationException exception).
I know I'm doing it backwards writing the test after the implementation (admission to avoid flames).
My question is: Is there a way to generate a PolicyViolationException object as a mock that I can pass in for my test? PolicyViolationException doesn't have any public constructors (so I can't new an object), nor an abstract base, or interface to mock against (using Moq).
I took a look through the API but didn't see anything to generate one. I know I could do some reflection magic to get one, but wanted to check if I was missing something.
In releases up to and including version 2.0-alpha4 this is not possible. However, this issue will be resolved in the upcoming 2.0-beta1 release of FluentSecurity where the constructor will be made public.
https://github.com/kristofferahl/FluentSecurity/commit/09e9b69ef5a297d242f8a813babbeebd47b54818
Thanks for bringing this to my attention!

Is creating a base class for all applications of a particular type good design?

I am trying to write a graphics application in C++. It currently uses OGRE for display, but I'd like it to work with Irrlicht or any other engine, even a custom rendering engine which supports my needs. This is a rather long question, so I'd appreciate help on re-tagging/ cleanup (if necessary). I'll start with a little background.
The application has three major states:
1. Display rasterized scene
2. Display a ray traced version of the same scene
3. Display a hybrid version of the scene
Clearly, I can divide my application into four major parts:
1. A state management system to switch between the above modes.
2. An input system that can receive both keyboard and mouse input.
3. The raster engine used for display.
4. The ray tracing system.
Any application encompassing the above needs to be able to:
1. Create a window.
2. Do all the steps needed to allow rendering in that window.
3. Initialize the input system.
4. Initialize the state manager.
5. Start looping (and rendering!).
I want to be able to change the rendering engine/state manager/input system/ ray tracing system at any time, so long as certain minimum requirements are met. Imho, this requires separating the interface from the implementation. With that in mind, I created the interfaces for the above systems.
At that point, I noticed that the application has a common 'interface' as well. So I thought to abstract it out into an ApplicationBase class with virtual methods. A specific application, such as one which uses OGRE for window creation, rendering etc would derive from this class and implement it.
My first question is - is it a good idea to design like this?
Here is the code for the base class:
#ifndef APPLICATION_H
#define APPLICATION_H
namespace Hybrid
{
//Forward declarations
class StateManager;
class InputSystem;
//Base Class for all my apps using hybrid rendering.
class Application
{
private:
StateManager* state_manager;
InputSystem* input_system;
public:
Application()
{
try
{
//Create the state manager
initialise_state_manager();
//Create the input system
initialise_input_system();
}
catch(...) //Change this later
{
//Throw another exception
}
}
~Application()
{
delete state_manager;
delete input_system;
}
//If one of these fails, it throws an
//exception.
virtual void initialise_state_manager() = 0;
virtual void initialise_input_system() = 0;
virtual void create_window() = 0;
//Other methods.
};
#endif
When I use OGRE, I rely on OGRE to create the window. This requires OGRE to be initialised before the createWindow() function is called in my derived class. Of course, as it is, createWindow is going to be called first! That leaves me with the following options:
1. Leave the base class constructor empty.
2. In the derived class implementation, make initialising OGRE part of the createWindow function.
3. Add an initialize render system pure virtual function to my base class. This runs the risk of forcing a dummy implementation in derived classes which have no use for such a method.
My second question is- what are your recommendations on the choice of one of these strategies for initialising OGRE?
You are mixing two unrelated functions in one class here. First, it serves as a syntactic shortcut for declaring and initializing StateManager and InputSystem members. Second, it declares abstract create_window function.
If you think there should be a common interface - write an interface (pure abstract class).
Additionally, write something like OgreManager self-contained class with initialization (looping etc) methods and event callbacks. Since applications could create and initialize this object at any moment, your second question is solved automatically.
Your design may save a few lines of code for creating new application objects, but the price is maintaining soup-like master object with potentially long inheritance line.
Use interfaces and callbacks.
P.S.: not to mention that calling virtual functions in constructor doesn't mean what you probably expect.
Yes, that is a good design, and it is one that I use myself.
For your second question, I would remove anything from the base constructor that has any possibility of not being applicable to a derived class. If OGRE wants to create the window itself then you need to allow it to do that, and I don't think that it makes sense to initialize OGRE in createWindow (it's misleading).
You could add an initialize render system virtual method, but I think you should just leave that task to the derived class's constructor. Application initialization is always a tricky task, and really, really difficult to abstract. From my experience, it's best not to make any assumptions about what the derived class might want to do, and just let it do the work itself in any way that it wants.
That said, if you can think of something that will absolutely apply to any conceivable derived class then feel free to add that to the base constructor.