Skip to content

Entity Scripts

Aadi Poddar edited this page Jun 20, 2023 · 1 revision

image

A script is a brain of the entity.

image

Entity class is the base for entity script which is base for all other scripts.

If we add a script component we need 2 pieces of information -

  • Entity (What Entity This Script belongs to)
  • Creation function (That will create an instance of the script class and allocate memory)

Each script component will have a pointer to the game code script.

Double - Indexed Arrays

image

If we use an array with holes like this than we would have to check for each slot whether it has a valid pointer to an instance of a script class.

Problems

It works fine but has 2 disadvantages -

  • Cache Misses

The CPU reads a limited amount of memory each time it needs some data. EG- First 4 slots would be fetched by the CPU and only 2 of them contain useful information. Each time this occurs the CPU has to go to the main memory and fetch more data which is slow.

  • Branch Mispredictions

There does not have to be a regulatory in what slots contain valid pointers the CPU will often be unable to predict if this branch will be taken or not. If CPU predicts that this branch will be taken then update function is called and the CPU is running it in the pipeline and then it turns our that it was not a good prediction then all that work need to be thrown away.

Solution

image

We have a script array that is separate from this array of holes. Scripts are Game Code and not components. The Script array is a tight array as it does not have any empty slots.

We keep track of things by using the previous array as an ID mapping to the array of script pointers. The Script IDs are indices into these ID mapping. For the ID mapping we will use generational IDs that we use for Game Entities as well.


Tight Packing

We ensure that there are no empty spaces in the array by swapping the script pointer which we want to delete with the last one in the array. Then we delete the last script and update the indices.

EG -

image

Suppose we want to Delete the Triangle script. If we would remove this in here then there would be an empty spot in here which we don't want.

image

  • We swap the triangle script pointer with the last one.
  • We delete the triangle script.
  • We update the indices.

We are left with a tightly packed array of script pointers and an ID mapping that tells us for what script ID what script pointer should be used. We have ID mapping and Script IDs that why we call it double indexing.

Clone this wiki locally