preventing bad and needed recursion - c

I have a problem with here:
void DrawState(){
char statevar[1000] = {0};
//bla bla bla
something = showmenu(); // or showscreen() or showinput()
if(something){
// change state
state = new_state;
}else{
// return to previous state
state = return_state;
}
// draw new state here.
DrawState();
}
I need this function to run when state changes. But when I do write like this recursively, it consumes too much memory and eventually it crashes the system. When I don't do this, I don't have any idea how to call itself from outside.
Does someone have any idea?
Edit: This is a library that runs over a manager software, like a plugin. Background jobs need to work too with this implementation. Maybe I should run this on some event.

It sounds like what you want doesn't involve recursion, per se, but rather simply a callback.
When you need to run some code whenever something in your code changes, you want to implement the Observer pattern. A simple C implementation might use a function pointer to hold the function that will be run when the data monitored is updated.
For example, you could separate your update function:
void DrawState() {
// ...
}
And then, you could maintain a pointer to it
int (*updateDraw)() = DrawState
And then do...
if (updated) {
// when updated
updateDraw()
}

Related

Movie Clip through Display Object Not working correctly

Hey everyone so I have a movie Clip called popEffect that i want to show on the current bubbles that are being clicked by the mouse. Now Whenever I click on a Bubble everything works correctly they get removed from the stage, but the problem I am having is that the popEffect is not positioned to the current bubbles that are being clicked. Instead they are positioned at a different bubble that shows on the screen in the display object array.
Here is how I have it all set up:
private function addBubbles(e:TimerEvent):void
{
bubbles = new mcBubbles();
stage.addChild(bubbles);
aBubbleArray.push(bubbles);
bubbles.addEventListener(MouseEvent.CLICK, bubblesBeingClicked);
}
Then the BubblesBeingClicked function:
private function bubblesBeingClicked(e:MouseEvent):void
{
var BubblePop:DisplayObject = e.target as DisplayObject; // HERE is your clicked square
var i:int = aBubbleArray.indexOf(BubblePop); // and HERE is your index in the array
if (i < 0)
{
// the MC is out of the array
//trace("Pop Clicked");
onBubbleIsClicked(BubblePop);
aBubbleArray.splice(i, 1);
BubblePop.parent.removeChild(BubblePop);
//Remove Listeners!!!
BubblePop.removeEventListener(MouseEvent.MOUSE_DOWN, onBubbleIsClicked);
// Null
BubblePop = null;
}
}
Finally my onBubbleIsClicked function where i have the popEffect located:
private function onBubbleIsClicked(bubblePop:DisplayObject):void
{
nScore++;
updateHighScore();
//Pop Effect
popEffect = new mcBubblePop();
stage.addChild(popEffect);
popEffect.x = bubbles.x;
popEffect.y = bubbles.y;
}
Can anyone see why the popEffect wont position on the current bubble that is being popped? Its acting really weird.
The reason is this:
popEffect.x = bubbles.x;
popEffect.y = bubbles.y;
As far as I can understand, bubbles is a member variable in the class (you are using it in the addBubbles function. Inside onBubbleIsClicked, you provide bubblePop, but do not use it. You are using bubbles instead, which is actually the last instance you've created inside the tick function!
So every time you create popEffect, you actually assign the x and y to the latest created bubblePop.
Some advises:
Do not use member variables that often. They are used WHEN you need to use a variable between functions. In your case, bubbles is a variable that is used only inside the creational function. You even put them into an array! And because you override it with a new one every time you create an instance, your member variables just saves the last one. Is this really needed? Same with popEffect, does anyone else uses it, as it's again just the last one? Such things create mistakes, as you see..
I truly don't understand what this means: if (i < 0). You search if the object you've clicked is not in the array? Well if it is not (how come?!), then what's the meaning of aBubbleArray.splice(i, 1);? Since i < 0, you actually splice with negative value, so you splice some other element! Plan what you want to do, thing logically and then do the actual code. If the object is not in the array, then why do you remove anything from the array?
Start formatting your code better. Read about camel case and variables scope.
Try to manage your logic better. For example this is pretty awkward: BubblePop.parent.removeChild(BubblePop);, as long as you've added it by using stage.addChild(bubbles);. So isn't it more simple to use stage.removeChild(child);? There are some rules in programming (especially in Flash), like 'what added it should remove it'. This will keep you safe in future.
Good luck!

What is the best way to break a very big C function with around 50 local variables into smaller functions?

I have a 3500 lines long C function written by someone else that i need to break it apart without causing any regression. Since it is in C, the main problem i face is maintaining the state of the variables. For example if i break a small part of the code into another function, i will need to pass 10 arguments. Some of them will actually change inside the code of the new function. So effectively i will need to pass a pointer to them. It becomes very messy. Is there is better way of dealing with such refactoring? Any "best practice"?
Unit testing. Extract small portions of the code that depend on 3 variables or less (1 variable best) and test the hell out of it. Replace that code in original function with a call to new function.
Each function should do one thing that is easy to figure out from examining the code.
Instead of passing 10 variables around, put them into a structure and pass that around.
In my opinion, the best thing you can do is to thoroughly study that function, and fully understand its internals. It is more than probable that this function has a lot of anitpatterns inside it, so I'd not try to refactor it: once I knew how it works (which I understand this can suppose a lot of time) I'd throw it away and rewrite the equivalent smaller functions needed, from scratch.
Pack the local variables that are shared between multiple of the sub-functions into a struct and hand the struct around?
Are you stuck with C? I have sometimes converted such functions into a C++ class, where I convert the some (or all) local variables into member variables. Once this step has been done, you can easily break out part of the code into methods that work on the member variables.
In practice this means that a function like:
... do_xxx(...)
{
.. some thousand lines of code...
}
can be converted into:
class xxx_handler
{
public:
xxx_handler(...);
... run(...)
{
part1();
part2();
part3();
return ...;
}
private:
// Member variables goes here.
};
// New replacement function.
... do_xxx(...)
{
xxx_handler handler(...);
return handler.run(...);
}
One thing to start with, as a first step to taking out parts of the function as independent functions, is to move "function global" temp variables to be in tighter scope, something like:
int temp;
temp = 5;
while(temp > 0) {...}
...
temp = open(...);
if (temp < 0) {...}
converted to
{
int temp = 5;
while(temp > 0) {...}
}
...
{
int temp = open(...);
if (temp < 0) {...}
}
After that, it's easier to move each {} block into a separate function, which does one well-defined thing.
But then, most important guideline after having unit tests:
Use version control which supports "cherry-picking" (like git). Commit often, basically whenever it compiles after refactoring something, then commit again (or amend the previous commit if you don't want to have the first commit version around) when it actually works. Learn to use version control's diff tool, and cherry-picking, when you need to roll back after breaking something.

Dealing with game states with different resources in C

I am trying to write a simple game to see how it's done. In my current implementation, I am using array of function pointer's, and my main game loop (stripped) looks like this;
while (stateid != STATE_EXIT) {
handle_events[stateid] ();
logic[stateid] ();
render[stateid]();
change_state(); // change state id, and load new state
}
This way, I can call different functions, depending on the game state. A game state may be something like title, menu or level1 etc. Since each state has different resources, I also have load, and unload functions for each state, here is how change_state looks (stripped)
if (nextstate != STATE_NULL) {
unload_level[stateid] ();
load_level[nextstate]();
stateid = nextstate;
nextstate = STATE_NULL;
}
To handle different resources on different game states, I have made a global void pointer. This global may point to a struct game or struct title depending on the game state. For example, when load_level[STATE_TITLE] is called, a struct title gets created, and global void pointer is set to it's address. So, game state functions can use it like this:
void logic_game()
{
struct game *resources = (struct game *) globalvoidpointer;
// do stuff with resources...
}
But, this whole thing doesn't feel right. It feels overengineered and compilcated to me. How would you suggest I should manage game resources and states? (or say so if this is not overly complicated, and I should stick with it.)
I suspect the design is over-thought.
Set this aspect of the architecture aside for awhile. Then put some effort into sketching out what two different stateid implementations will do for handle_events(), logic(), and render(). You will probably discover that abstractions for resources are not necessary. The stateid itself is probably more than enough to distinguish between what needs to be done.

How to share constant state throughout code without globals

I have a program that uses an external API which uses its own state. The program stores the initial state at the beginning. Afterwards, dozens of functions are invoked using a dispatcher depending on the input. Each of them alters the current state using the API. One of the functions should be able to reset the current state to the initial. Although, that would require access to the variable/constant set at the beginning, which is out of scope in the function.
One solution would be a global, which is considered evil. Another solution could be a function with a static variable to store the initial state at its first call. Calling it again would return the static state. Although, this is not really an improvement.
Is there any clean, maintainable solution to this problem?
Edit: OK, let's say I'll use a const global after all. To illustrate it, I'll use the following code:
extern int get_state();
extern void set_state(int);
const int initial_state = get_state();
int main()
{
while(1) {
// call dispatcher, eventually
break;
}
set_state(initial_state);
return 0;
}
The problem is that the initializer of initial_state must be constant, which get_state() apparently isn't. Is there any way to work around this?
Globals aren't evil (especially if constant).
Any other solution would likely be ugly and would have a better chance of introducing bugs.
You can make use of Singleton design pattern. With this you can share the common state in a cleaner and controlled manner.
Here is the Code for your reference.
In State.h
State *getState(void);
In State.c
static State *g_state;
State* getState(void)
{
if(g_state == NULL) // not initialized
{
// Allocate Memory and initialize it
}
else
{
// operate on it if necessary. Can have mutex, semaphore based on your Use Case.
return g_state;
}
}
Here even though common state is a Global Variable, it is not accessible outside getState() function, hence no evil of using Global variable!!
Shash

State machines in C

What is the best way to write a state machine in C?
I usually write a big switch-case statement in a for(;;), with callbacks to re-enter the state machine when an external operation is finished.
Do you know a more efficient way?
I like the Quantum Leaps approach.
The current state is a pointer to a function that takes an event object as argument. When an event happens, just call the state function with that event; The function can then do its work and transition to another state by just setting the state to another function.
E.g.:
// State type and variable, notice that it's a function pointer.
typedef void (*State)(int);
State state;
// A couple of state functions.
void state_xyz(int event) { /*...*/ }
void state_init(int event) {
if (event == E_GO_TO_xyz) {
// State transition done simply by changing the state to another function.
state = state_xyz;
}
}
// main contains the event loop here:
int main() {
int e;
// Initial state.
state = state_init;
// Receive event, dispatch it, repeat... No 'switch'!
while ((e = wait_for_event()) != E_END) {
state(e);
}
return 0;
}
The QL frameworks provides helpers for extra things like entry/exit/init actions, hierarchical state machines, etc. I highly recommend the book for a deeper explanation and good implementation of this.
The best way is largely subjective, but a common way is to use a "table-based" approach where you map state codes (enums or some other integral type) to function pointers. The function returns your next state and other associated data and you loop through this until the terminal state is reached. This might in fact be what you are describing as your approach above.
That's pretty much the standard approach. If you're interested in studying a well considered library and comparing specifics, take a look at Ragel:
Ragel compiles executable finite state machines from regular languages. Ragel targets C, C++, Objective-C, D, Java and Ruby. Ragel state machines can not only recognize byte sequences as regular expression machines do, but can also execute code at arbitrary points in the recognition of a regular language. Code embedding is done using inline operators that do not disrupt the regular language syntax.
Switch statements are a good way to get started, but they tend to get unwieldy when the FSM gets larger.
A couple related (or duplicate) SO questions with great information and ideas:
state machines tutorials
C state-machine design
I used this pattern. Is there a typical state machine implementation pattern? (check best answer).
But i also add some features
1. Information about previous state.
2. Parameter passing
3. Adding external events like global timeout and "resseting SM"
I found state machines little less cryptic and maintainable.
Anyway, I still think state machines are most difficult and annoying programming task.(I got so far)
An alternative approach is a 2D array that describes for each state/event combination the actions to execute and the next state to go to. This can get trickier to manage when you need to transition to different states depending on 'circumstances', but it can be made to work well. You have an event recognizer function which returns the next event; you have the table where each entry in the table identifies the function to call on receiving the event and the next state to go to - unless the called function overrides that state.
Actually generating such code is fiddlier - it depends on how the FSM is described in the first place. Spotting duplicate actions is often important. Often, you can rely on 'sparse matrix' techniques that do not record error handling explicitly: if the entry logically exists in the sparse matrix, you act on that event/state information, but if the entry does not exist you fall back onto appropriate error reporting and resynchronization code.
A 2D array of pointers to structures can be passed into a generic FSM function; the fact that you write a triple-pointer is enough to make you cautious about what is going on. (I wrote one of those back in March 1986 - I don't have the source for that on disk any more, though I do still have a printout of the document that described it.)
Have a look here: http://code.google.com/p/fwprofile/
It's an open source version (GNU GPLv3) of the state machine implemented
in C. The concept and implementation is well-suited for use in
mission-critical applications. There are deployments in industrial
applications.
I use function pointers and a 2d look-up table where I use the state for one parameter and the event as the other.
I use excel (or any spreadsheet tool) to map a function to every state/event combination.
When an event occurs, I que it up, so then I have something that looks like this
int main(void)
{
StateList currentState = start_up;
EventList currentEvent;
uint8_t stateArray[STATE_COUNT][EVENT_COUNT];
InitializeStateArray(stateArray);
InitializeEventQue();
while(1)
{
currentEvent = GetPriorityEvent();
currentState = (StateList)(*(stateArray[currentState][currentEvent]))();
}
return 1; //should never get here
}
This method essentially forces the developer to consider all possible events in each state, and in my experience makes debugging a little easier.
You can use minimalist uml-state-machine framework implemented in c. It supports both finite and hierarchical state machine. The framework is very minimalist. It has only 3 API's, 2 structures and 1 enumeration.
The State machine is represented by state_machine_t structure. It is an abstract structure that can be inherited to create a state machine.
//! Abstract state machine structure
struct state_machine_t
{
uint32_t Event; //!< Pending Event for state machine
const state_t* State; //!< State of state machine.
};
State is represented by pointer to state_t structure in the framework.
If framework is configured for finite state machine then state_t contains,
typedef struct finite_state_t state_t;
// finite state structure
typedef struct finite_state_t{
state_handler Handler; //!< State handler function (function pointer)
state_handler Entry; //!< Entry action for state (function pointer)
state_handler Exit; //!< Exit action for state (function pointer)
}finite_state_t;
If framework is configured to support hierarchical state machine. It contains additional three members to represent the hierarchical relation between the states.
typedef struct hierarchical_state_t state_t;
//! Hierarchical state structure
typedef struct hierarchical_state_t
{
state_handler Handler; //!< State handler function
state_handler Entry; //!< Entry action for state
state_handler Exit; //!< Exit action for state.
const state_t* const Parent; //!< Parent state of the current state.
const state_t* const Node; //!< Child states of the current state.
uint32_t Level; //!< Hierarchy level from the top state.
}hierarchical_state_t;
The framework provides an API dispatch_event to dispatch the event to the state machine and two API's for the state traversal.
state_machine_result_t dispatch_event(state_machine_t* const pState_Machine[], uint32_t quantity);
state_machine_result_t switch_state(state_machine_t* const pState_Machine, const state_t* pTarget_State);
state_machine_result_t traverse_state(state_machine_t* const pState_Machine, const state_t* pTarget_State);
For more details refer to GitHub project.
check this out "https://github.com/knor12/NKFSMCompiler" it helps generate C Language code for a state machine defined in an scxml or csv file. an example is provided.

Resources