Gamestudio Links
Zorro Links
Newest Posts
IG plugin initial release
by sodiumchloride. 09/22/20 20:53
Using STL in Zorro strategies
by AndrewAMD. 09/22/20 17:01
Rubbish data from Yahoo
by DanielX. 09/22/20 14:37
assert
by Grat. 09/22/20 12:14
MT4 - use more Zorro script
by Grat. 09/22/20 06:49
Single advise model for portfolio
by jmlocatelli. 09/21/20 19:41
AUM Magazine
Latest Screens
The Space Between
Pogostuck: Rage With Your Friends
Worst Case Z
AckCon'18 - Lotter vs the World 2 - Preview Release
Who's Online Now
4 registered members (Dooley, kvm, AndrewAMD, jmlocatelli), 445 guests, and 3 spiders.
Key: Admin, Global Mod, Mod
Newest Members
NewBorn, 3dvg, secretagentman, distribution, EditeY
18515 Registered Users
Previous Thread
Next Thread
Print Thread
Rate Thread
Page 2 of 3 1 2 3
Re: Reducing Function Times [Re: Dooley] #481202
08/13/20 06:23
08/13/20 06:23
Joined: May 2009
Posts: 5,293
Caucasus
3run Offline
Senior Expert
3run  Offline
Senior Expert

Joined: May 2009
Posts: 5,293
Caucasus
Switching from while to for loop won't indeed have any impact on frame rate. You need to get rid of while loops with wait per each entity by switching to on_frame and EVENT_FRAME and also you need to avoid cycling through all entities on the level. Add entities into separate lists and cycle through via for loop (or while if you like it, but for is more suitable for counter/fixed amount of cycling loops).


Looking for free stuff?? Take a look here: http://badcom.at.ua
Re: Reducing Function Times [Re: Dooley] #481208
08/13/20 11:13
08/13/20 11:13
Joined: Jun 2007
Posts: 1,334
Hiporope and its pain
txesmi Offline
Serious User
txesmi  Offline
Serious User

Joined: Jun 2007
Posts: 1,334
Hiporope and its pain
Originally Posted by 3run
Switching from while to for loop won't indeed have any impact on frame rate.

As far as I have read, compilers do normally compile both instructions to the very same thing.

Originally Posted by Dooley
Do you have any general tips on reducing function complexity?

One thing you can try is to replace local variables of actions by entity skills. Acknex do restore and save actions stack memory each frame. It has a significant impact on execution when there are a lot. Entity skills are slower to read and write, so it is not a fire-written law but something to take into account in reference to variables usage. I did a messurement of the impact of 'wait' and stack size in my oldy computer some time ago: https://opserver.de/ubb7/ubbthreads.php?ubb=showflat&Number=474652#Post474652

Recursively accesing array members by its index is a little waste of resurces that can be avoided by getting the proper pointer. I mean:
Code
var array[100];

// acces array members by its index
int i = 0;
for(; i<100; ++i)
   array[i] = random(1); // it performs an addition each loop in order to access the array member: *(array + i) = ... 

// faster approach
var *ptr = array;
var *ptrLast = ptr + 100;
for(; ptr<ptrLast; ++ptr)
   *ptr = random(1); // No extra additions. The more accesses to array members, the more additions it avoids.


The use of var type as indexes on arrays also have a little penalty since the program have to cast them to long type. It is just a 10 bits right shift, but you know, dunes grow grain by grain.

I will always recomend the use of function pointers on complex state machines. Function pointers let you atomize the execution and avoid the whole switch/case block commonly used to build state machines. I do normally set the function scheduler and state machines into the same system. Something like the following:
Code
#include <acknex.h>
#include <default.c>

//-------------------------------------------------------------------------------------------

#define ITEMS_MAX              1000

typedef struct SCHEDULER_ITEM
{
	void *object;
	void *state(void *item);
	void remover(void *item);
} SCHEDULER_ITEM;

SCHEDULER_ITEM items[ITEMS_MAX];
int itemCount = 0;

SCHEDULER_ITEM *itemAdd(void* object, void *remover, void *state)
{
	SCHEDULER_ITEM *item = items + itemCount;
	itemCount += 1;
	
	item->object = object;
	item->state = state;
	item->remover = remover;
	
	return item;
}

void itemRemoveAll()
{
	SCHEDULER_ITEM *item = items;
	SCHEDULER_ITEM *itemLast = item + itemCount;
	for(; item < itemLast; ++item)
		item->remover(item->object);
	itemCount = 0;
}

//-------------------------------------------------------------------------------------------

// Prototypes
void *stMoveUp(ENTITY *ent);

// States
void *stWaitDown(ENTITY *ent)
{
	ent->skill2 += time_step;
	if(ent->skill2 > ent->skill1)
	{
		ent->skill4 += 1;
		if(ent->skill4 > ent->skill3)
		{
			return NULL;
		}
		
		ent->skill1 = random(200);
		ent->skill2 = 0;
		
		return stMoveUp;
	}
	
	return stWaitDown;
}

void *stMoveDown(ENTITY *ent)
{
	ent->z -= time_step * 10;
	
	if(ent->z < ent->skill1)
	{
		ent->skill1 = 4 + random(16);
		ent->skill2 = 0;
		return stWaitDown;
	}
	
	return stMoveDown;
}

void *stWaitOnTop(ENTITY *ent)
{
	ent->skill2 += time_step;
	
	if(ent->skill2 > ent->skill1)
	{
		ent->skill1 = -random(200);
		ent->skill2 = 0;
		
		return stMoveDown;
	}
	
	return stWaitOnTop;
}

void *stMoveUp(ENTITY *ent)
{
	ent->z += time_step * 10;
	
	if(ent->z > ent->skill1)
	{
		ent->skill1 = 4 + random(16);
		ent->skill2 = 0;
		return stWaitOnTop;
	}
	
	return stMoveUp;
}

void sphereCreate()
{
	if(itemCount > ITEMS_MAX - 1)
		return;
	ENTITY *ent = ent_create(SPHERE_MDL, vector(0, random(600) - 300, -random(200)), NULL);
	ent->skill1 = random(200); // limit
	ent->skill2 = 0; // limit counter
	ent->skill3 = 1 + random(4); // Count of loops
	ent->skill4 = 0; // loop counter
	
	itemAdd(ent, ent_remove, stMoveUp);
}

//-------------------------------------------------------------------------------------------

void scheduler()
{
	int index = 0;
	SCHEDULER_ITEM *item = items;
	for(; index < itemCount; ++index, ++item)
	{
		item->state = item->state(item->object);
		if(item->state != NULL)
			continue;
		item->remover(item->object);
		itemCount -= 1;
		memcpy(item, items + itemCount, sizeof(SCHEDULER_ITEM)); // The fastest deletion but sorting gets broken.
		index -= 1;
		item -= 1;
	}
}

//-------------------------------------------------------------------------------------------

void createMultipleEntities()
{
	int i = 0;
	for(; i<ITEMS_MAX; i+=1)
		sphereCreate();
}

void main()
{
	max_entities = maxv(ITEMS_MAX, 5000);
	wait(3);
	level_load("");
	camera->x = -600;
	
	createMultipleEntities();
	
	on_esc = NULL;
	on_space = sphereCreate;
	
	while(!key_esc)
	{
		scheduler();
		wait(1);
	}
	
	itemRemoveAll();
	sys_exit(NULL);
}


Hope it helps...
Salud!

Re: Reducing Function Times [Re: Dooley] #481212
08/13/20 12:50
08/13/20 12:50
Joined: May 2005
Posts: 785
Chicago, IL
Dooley Online OP
User
Dooley  Online OP
User

Joined: May 2005
Posts: 785
Chicago, IL
@3run Thanks I am planning to try EVENT_FRAME for some of my game objects to see how it works.

@txesmi Your stuff is pretty advanced for me. I don't know if I have anything where those solutions will actually work, but I will look more carefully. I appreciate the input!

Re: Reducing Function Times [Re: Dooley] #481216
08/13/20 16:25
08/13/20 16:25
Joined: May 2005
Posts: 785
Chicago, IL
Dooley Online OP
User
Dooley  Online OP
User

Joined: May 2005
Posts: 785
Chicago, IL
@3run Wow! EVENT_FRAME made a huge impact. Almost 10 fps in some areas. I will be applying this to more game objects asap!

Re: Reducing Function Times [Re: Dooley] #481217
08/13/20 17:00
08/13/20 17:00
Joined: Jun 2007
Posts: 1,334
Hiporope and its pain
txesmi Offline
Serious User
txesmi  Offline
Serious User

Joined: Jun 2007
Posts: 1,334
Hiporope and its pain
@Dooley
I am sorry, I suspected such a circumstance but thrown the code same xP

Let me explain. The point is that if you want to get rid of engines entity action scheduler, as 3Run suggested, you have to build your own which involves some sort of object and function management. That is basically what my example do. It happens that once you have a function scheduler working, with little changes you get a state machines manager by the same prize. I have cleaned, commented and formatted the code above so now it works as a little transparent module to include in any project:

scheduler.h

Code
#ifndef _SCHEDULER_H_
#define _SCHEDULER_H_

//-------------------------------------------------------------------------------------------

#define SCHEDULER_MAX_ITEMS    1000 // Maximum amount of simultaneous objects into the scheduler

//-------------------------------------------------------------------------------------------

typedef struct SCHEDULER_ITEM
{
	void *object;               // A generic pointer to an object of an undetermined type
	void remover(void *item);   // A function pointer that removes the pointed object
	void *state(void *item);    // A function pointer to the current state function
} SCHEDULER_ITEM;

// Static scheduler items
SCHEDULER_ITEM schItems[SCHEDULER_MAX_ITEMS];
int schItemCount = 0;

//-------------------------------------------------------------------------------------------

/* Add an object to the scheduler
 *  object:  a pointer to an object of any kind. It can be NULL.
 *  remover: function that removes the object. It can be NULL, but the object will not be removed.
 *  state:   function to be called each frame with the object as parameter. Mandatory!
 *           void *myAction(TypeOfTheObject *object) 
 *           {
 *	             ...
 *	             return myAction; // Return NULL in order to remove the object and the scheduler item
 *           }
 */
void schItemAdd(void *object, void *remover, void *state)
{
	if(schItemCount == SCHEDULER_MAX_ITEMS) // No space enough?
		return;
	
	SCHEDULER_ITEM *item = schItems + schItemCount; // Get a pointer to the next last scheduler item
	schItemCount += 1; // Increase the item counter;
	
	item->object = object; // Init the scheduler item 
	item->state = state;
	item->remover = remover;
}

//-------------------------------------------------------------------------------------------

/* Remove all the objects and items in the scheduler
 *  
 */
void schItemRemoveAll()
{
	SCHEDULER_ITEM *item = schItems;
	SCHEDULER_ITEM *itemLast = item + schItemCount;
	for(; item < itemLast; ++item)
		if(item->remover != NULL)
			item->remover(item->object);
	schItemCount = 0;
}

//-------------------------------------------------------------------------------------------

/* Scheduler
 *  
 */
void scheduler()
{
	int index = 0;
	SCHEDULER_ITEM *item = schItems;
	for(; index < schItemCount; ++index, ++item) // Loop through the whole list of scheduled items
	{
		// Call the state function with the object as parameter and save the return on itself, so next time will call the current return
		item->state = item->state(item->object); 
		
		// Continue through the list when the return is not NULL
		if(item->state != NULL)
			continue;
		
		// Otherway, proceed to delete the object
		if(item->remover != NULL) // Call the object remover function stated at itemAdd function call
			item->remover(item->object); 
		
		// Decrease the item counter
		schItemCount -= 1; 
		
		// Copy the last scheduled item to the place where the deleted one is
		memcpy(item, schItems + schItemCount, sizeof(SCHEDULER_ITEM)); 
		// This is the fastest deletion but sorting gets messed. 
		// In case the sorting is important, it will need to copy the whole tail down instead.
		// memcpy(item, item + 1, sizeof(SCHEDULER_ITEM) * (schItemCount - index))
		
		// Decrease the for loop variables, so it computes the same item again, the item overwritten by the memcpy instruction
		index -= 1;
		item -= 1;
	}
}

#endif



You don't really need to understand what is going on, but there you go:

The basis is the SCHEDULER_ITEM data structure which saves each scheduled objects data. The scheduler works over a static list of SCHEDULER_ITEM and loops through it each frame. The list starts empty. The objects are added to the scheduler through 'schItemAdd' which adds a new SCHEDULER_ITEM to the list. The list items are deleted when their state function call returns NULL. The object can also be removed at the same time.

You would only need to include 'scheduler.h', set 'scheduler' function as 'on_frame' event and set 'schItemRemoveAll' as 'on_exit' event. You might, of course, call this functions differently. f.e: as a part of larger looping and close functions.
Code
#include <acknex.h>
#include "scheduler.h"
...
void main()
{
   on_frame = scheduler;
   on_exit = schItemRemoveAll;
}


At this point, you can start adding objects to the scheduler. Lets imagine we want to make an entity on WED be managed by the scheduler. It will need assign an action to it, as it is commonly done, so the engine would call the action on level load.

An action is usually composed by three blocks that can be built as three functions:
- initialization
- loop
- deletion

The initialization remains in the action, but the loop content and the deletion are passed to the scheduler as parameters of 'schItemAdd' in the form of functions. Something like this:
Code
void *crazyLoop(ENTITY *ent)
{
	ent->x = random(100) - 50;
	ent->y = random(100) - 50;
	ent->z = random(100) - 50;
	
	if (key_space)
		return NULL;
	
	return crazyLoop;
}

void crazyRemove(ENTITY *ent)
{
	str_remove((STRING*)ent->skill1);
	ent_remove(ent);
}

action actCrazy()
{ 
	my->skill1 = str_create("my crazy name");
	
	schItemAdd(me, crazyRemove, crazyLoop);
}


This setup will start by the action asociated to an entity in WED which creates a string, saves it into a skill, and includes the entity into the scheduler list with its removing and looping functions.

The removing function removes the string created on initialization and the entity itself.

The looping funtion needs to be of a particular signature:
Code
void *loopingFunction(TypeOfTheObject *object)
{
	...
	return loopingFunction;
}


The return of the function must be a function (void* or NULL) and the parameter should be of the type of the object, an 'ENTITY*' in the example. As far as a function returns its function name, it will act as a loop with a 'wait'. When NULL is returned, the scheduler calls the object deletion function and also deletes the scheduler item from its internal list.

You will need to call 'schItemRemoveAll' before level changes.

That is all the basics. That is how you can delete all the loops from the entity actions. As far as I know there is no way to make it faster.

All this function returning stuff might sound strange but it is mandatory because the scheduler function is running over the static array and it should not be modified by other functions while its execution, which executes every scheduled object function. That is why the looping function must return something in order to make the scheduler know that the list have to be shortened when removing an an object and modify the list localy inside the scheduler. Once you need to take care of the return of the looping functions, it can return pointers to functions by the same prize which acts as object oriented state machine.

The returning function pointer is the function that will be called next frame. This way you can build each state as a separate function and control the execution flux by the return of the functions, as I did in the first example where every state runs for a while until certain condition.

Notice that you can include items in the scheduler with no object or remover function. If there is no object, the scheduler will call the looping function same, but with a null parameter. It might serve to manage global variable changes or whatever. If there is no remover function, the scheduler will not remove the object asociated.

Also notice that the object can be of any kind, entities, panels, bitmaps, custom structs, whatever you need. It is like having engine actions for everything.


Last edited by txesmi; 08/14/20 10:27. Reason: Bug fix
Re: Reducing Function Times [Re: Dooley] #481218
08/13/20 18:18
08/13/20 18:18
Joined: May 2009
Posts: 5,293
Caucasus
3run Offline
Senior Expert
3run  Offline
Senior Expert

Joined: May 2009
Posts: 5,293
Caucasus
@txesmi awesome code and explanation, thank you man! :>


Looking for free stuff?? Take a look here: http://badcom.at.ua
Re: Reducing Function Times [Re: Dooley] #481222
08/13/20 21:47
08/13/20 21:47
Joined: May 2005
Posts: 785
Chicago, IL
Dooley Online OP
User
Dooley  Online OP
User

Joined: May 2005
Posts: 785
Chicago, IL
I will have to try this. Maybe I will test it on a smaller project until I understand it. It sounds like it has a lot of potential!

Re: Reducing Function Times [Re: Dooley] #481228
08/14/20 12:13
08/14/20 12:13
Joined: Jun 2007
Posts: 1,334
Hiporope and its pain
txesmi Offline
Serious User
txesmi  Offline
Serious User

Joined: Jun 2007
Posts: 1,334
Hiporope and its pain
Thank you! Hope it is of help laugh

I uploaded the code and explanation to GitHub for convenience. There was a bug in 'schItemRemoveAll'.

--edited--
Forgot to mention that calling 'schItemAdd' inside a scheduled function is totally safe.

Last edited by txesmi; 08/14/20 12:19.
Re: Reducing Function Times [Re: txesmi] #481231
08/14/20 15:16
08/14/20 15:16
Joined: Feb 2005
Posts: 42
Hamburg, Germany
Jerome8911 Offline
Newbie
Jerome8911  Offline
Newbie

Joined: Feb 2005
Posts: 42
Hamburg, Germany
Thank you txesmi!

I never really recognized any issues with the wait-command and loops, but with this it is way easier to create for example behaviour trees or letting different objects share the same function etc. etc.
Thinking of all the bad workarounds I build for those things, I really regret that I only learned about this now.

Last edited by Jerome8911; 08/14/20 15:18.

Want to know more about Tactics of World War One?
Join me on Discord
Visit me on Indie DB

Re: Reducing Function Times [Re: Dooley] #481235
08/15/20 04:05
08/15/20 04:05
Joined: Apr 2002
Posts: 1,229
ny
jumpman Offline
Serious User
jumpman  Offline
Serious User

Joined: Apr 2002
Posts: 1,229
ny
Why does while(1) and wait(1); cause so many problems for lots of entities in their own loop?

Page 2 of 3 1 2 3

Moderated by  HeelX, Lukas, rayp, Rei_Ayanami, Superku, Tobias, TWO, VeT 

Gamestudio download | chip programmers | Zorro platform | shop | Data Protection Policy

oP group Germany GmbH | Birkenstr. 25-27 | 63549 Ronneburg / Germany | info (at) opgroup.de

Powered by UBB.threads™ PHP Forum Software 7.7.1