Hello, everyone!

This monthly update is for the programmers out there so if you're not into tech stuff or modding I recommend you skip it.

(This started out short but got longer when I realized that I can steal parts of it for modding documentation later on. Two birds, one stone!)

Loading and Unloading



As you all know there's no loading or unloading of levels in FRONTIERS, there's just one continuous world that gets loaded and unloaded in pieces as you move through it.

When the player is moving around very quickly (like they do during Fast Travel) this can get complicated. Unloading something takes time - you have to destroy objects, save the states of objects to disk and so on, and this workload has to be spread out over several seconds to avoid making the game choppy. As the player moves, an area which has been asked to unload and is halfway through unloading might suddenly find itself needed again, or vice versa. How to handle this?

Who's responsible?

First I have to figure out who's responsible for loading and unloading stuff. Nearly everything in the world of FRONTIERS is either a WorldItem or a WIGroup (World Item Group). Think of them roughly as files and directories - WorldItems are things (characters, sausages, pottery) and WIGroups are containers that hold the things. Most WIGroups are attached to / owned by WorldItems - Cities, for instance, are a kind of WorldItem that creates & uses a group to hold all the structures and characters that live in them.

WIGroups are stupid and don't know when they're near or far from the player or anything like that, so they can't be bothered to keep track of when they're needed. But WorldItems know all that and more, plus they're the ones that ask for the groups to be created in the first place. So it makes sense for them to be responsible for loading and unloading as well. There are a few rare cases where a WIGroup isn't created & used by a WorldItem - WorldChunks are like meta-groups which manage all the WIGroups & WorldItems in a square-shaped area, and they create and use some WIGroups that aren't attached to WorldItems. But what's important is that WIGroups still have no responsibility for loading and unloading themselves in these cases.

So the bulk of the responsibility falls on WorldItems. But WorldItems have parts - each WorldItem has any number of WIScript (World Item Script) components attached to it to define its behavior, and since each script operates independently they all potentially have a say in when to load and unload WIGroups. For instance, a City has a Spawner WIScript, a Location WIScript and a Visitable WIScript all attached to it. What if the Spawner wants to unload a group but Location and Visitable both want to load it? Each WIScript could potentially check for the other's existence to resolve conflicts but it's simpler and cleaner to avoid doing so.

To avoid cross-checking I rely on a few loose conventions. First, any WIGroups attached to a WorldItem share that WorldItem's name by default. Spawner and Location both require a WIGroup and ask for one to be created on startup, but regardless of who asks first they both receive & use the same group because they share the same WorldItem.

Second, I try to limit the number of scripts that manage the loading and unloading of WIGroups to one per WorldItem. This usually means assigning that task to the 'least generic' WIScript. The Location WIScript is highly generic and used for every location (Structures, Cities, Forests, Districts, etc.) so it can't be expected to handle WIGroups in a way that serves every location type's needs. But a Spawner is only used by a few location types and it can be programmed to handle its WIGroups in a specific way. So it makes sense to delegate loading and unloading to Spawner over Location. I occasionally break this rule, but on the whole I don't find more than one WIGroup-managing script is necessary.

When should it happen?

Each WIScript will handle things a little differently but 95% of WIGroup loading and unloading is motivated by its WorldItem's ActiveState. This state is determined by its distance from the player so it's changing all the time. A WorldItem can be either Inactive (invisible and non-interactive - really far away), Visible (visible but non-interactive - kinda close) or Active (visible and interactive - really close). Each WorldItem has the power to define its active radius, and its visible radius is its active radius multiplied by a global view distance. When a WorldItem's ActiveState changes actions are invoked - OnVisible, OnInvisible, OnActive, OnInactive, etc. Each WIScript can subscribe to these actions on startup if they want to be told what's going on with the WorldItem they're attached to.

For instance, when a Structure WIScript receives the message that its WorldItem is visible, it creates an 'Exterior' WIGroup and fills it with its exterior geometry and any exterior WorldItems (like porch lights) that its template might have. When the player opens a door or window - something it learns without the use of the WorldItem's ActiveState - the Structure then creates an 'Interior' WIGroup and does the same for interior WorldItems and geometry. While the player is visiting the structure it ignores any ActiveState messages since we never want to unload a structure while the player is inside it. But once the player has exited the structure & the WorldItem's active radius the Structure script unloads the interior WIGroup, followed by the Exterior group upon exiting the visible radius.

OK so we know who's responsible for loading & unloading and when it's going to take place script-by-script. So what actually happens when a WIScript calls group.Load ( ) or group.Unload ( )?



The Process of Loading

WIGroups are nested so loading is pretty straightforward. Each WIGroup is saved to disk as a directory plus a properties file - that properties file is loaded first and given to the WIGroup. It contains a list of the names of every child WorldItem that it held the last time it was saved, so the WIGroup uses this list to load the saved state of each child item from disk. (A WorldItem's save state is called a StackItem because that's what they're converted to when they're put in an inventory stack.) Each StackItem is loaded by name from the directory corresponding to the WIGroup - the hierarchy of WIGroups is reflected as actual directories in the player's profile - and then it is converted into an actual WorldItem.



Once a WorldItem is initialized its ActiveState is evaluated and its WIScripts all get their messages as usual. If a WorldItem is in a position where it needs to load more WIGroups it does so at this time. Since WIGroup loading is usually based on a WorldItem's ActiveState most WorldItems peter out and don't load anything else, but anything near the Player will continue to load WIGroups until there's nothing left to load.

The First (Minor) Complication - Unique Names

WorldItem names are like file names - they have to be unique. Every WorldItem has a default filename (eg 'Bread') and that filename is incremented when they are added to a WIGroup. ('Bread-0', 'Bread-1' etc).

There are some gotchas here. As each StackItem is loaded from disk the WIGroup checks to see if a WorldItem with that name already exists in its list of child items. If it does the StackItem is discarded since it will always be less up-to-date than an actual WorldItem.

Meanwhile totally new WorldItems can be added to the WIGroup while it's in the middle loading StackItems. These new WorldItems are set aside internally and then properly added to the WIGroup after the rest of the loading is done. This prevents the WIGroup from thinking it has already loaded one of the child items in its list - if a breand-new 'Bread' was added to the WIGroup between loading StackItems 'Bread-0' and 'Bread-1', the new WorldItem would be renamed to 'Bread-1' and the StackItem 'Bread-1' would be ignored, resulting in 2 WorldItems where there should be 3.

This isn't so bad on its own. But it means that some WorldItems will be stuck in a holding pattern while waiting to be added to their WIGroup. (By design they're not allowed to do anything until they're in a WIGroup so they wait for their OnAddedToGroup action to be invoked before doing anything important.) This means breaking up their otherwise straightforward initialization to accommodate a long wait, something that will come back to haunt us later.

Handling Interruptions

I don't bother to interrupt loading - if something is asked to load and then becomes unnecessary, I just let it finish loading and then start unloading it once it's done. That's because the consequences of accidentally having something loaded when it shouldn't be are minor.

But when something is unloading and it turns out it's still needed that can be disastrous. Imagine arriving via fast travel in a town that's halfway through unloading and being unable to stop it - you'd have to wait for all the structures and districts to disappear one by one, then reappear one by one. It would be weird.



So unloading has to be interruptable. And this changes it from a straightforward load-in-reverse operation - start at the bottom, unload till you hit the top - into a weird hybrid of unloading from the top and bottom simultaneously.

WIGroups are nested, but that nesting is organizational - a request to unload up top doesn't offer any guarantee that all of the child WorldItems in nested subgroups are actually ready to be unloaded. What if the player is interacting with a WorldItem that positively must remain loaded and its WIGroup is suddenly asked to unload? This would be equally weird.

To prevent this, all WorldItems must consent to being unloaded, and if even one says 'Hang on, I have business to take care of first' then the WIGroup just has to wait. The simplest form of this would be the group.Unload ( ) function calling something like worlditem.CanBeUnloaded ( ) on every child WorldItem, and if any of them return false then the unloading would be canceled.

The Second Complication - Remembering Requests

But what happens to the request to unload? We can't just let it go away and be completely forgotten, because we can't guarantee that the WIScript that asked for it to be unloaded will know enough to ask a second time. (It may even have been destroyed after asking.) If something asked for a WIGroup to unload, that request must be honored eventually unless it's canceled with a Load request.

Until this point WIGroups could have remained stateless (which is how I would have preferred them) but since they need to remember that they've been asked to unload, each WIGroup is given a LoadState:

Uninitialized

Loading

Loaded

PreparingToUnload - can be cancelled with a Load call

Unloading - point of no return

Unloaded - Load call starts loading from scratch

PreparingToUnload is a grey area between Loaded and Unloaded. In this state a WIGroup behaves just as it normally would - it allows WorldItems to be added or removed, and so on - the only difference is that its child items are periodically asked to PrepareToUnload ( ), and are subsequently asked worlditem.ReadyToUnload. When ReadyToUnload returns true for all child WorldItems...



The Third Complication - Duplicated Effort



...that WIGroup still isn't ready to unload, because it has child WIGroups, and those have to wait for their child WorldItems to consent to being unloaded as well. Meanwhile, other WIGroups may be asked to load or unload, and those groups may contain child WIGroups that have already been asked to unload. Are they all going to check their child WorldItems autonomously? Are they going to try and coordinate with each other?

This is the point where a WIGroup manager (WIGroups) becomes necessary, because otherwise it becomes too difficult to prevent WIGroups within the same heirarchy from duplicating the efforts of other unloading WIGroups. (It's possible, just difficult.) The manager already existed as a WIGroup factory to ensure that WIGroups were always created, initialized and destroyed properly so making it an unloading coordinator isn't a huge leap.

When a WIGroup is told to unload it passes that request along to the manager. The first thing the manager checks is whether that WIGroup has a parent WIGroup which is already being asked to unload - if it does, it's assumed that the parent WIGroup has the child group covered and the request is ignored. If it doesn't then a new WIGroupUnloader is created. This object's sole purpose is to check in on a WIGroup once in a while to see if it's ready to unload, then report back to the manager when it can be safely destroyed. Along the way it handles the business of asking each child WorldItem in the WIGroup's heirarchy (including child WIGroups) if it's ReadyToUnload.

This setup makes it easy to 'merge' WIGroupUnloaders. Say two districts in one city are asked to unload. Their parent WIGroup - the city - is still loaded, so each district's WIGroup is assigned a separate WIGroupUnloader. Then as the player gets farther away, the city's WIGroup is told to unload. Suddenly both earlier WIGroupUnloaders are irrelevant - the city's WIGroupUnloader will handle unloading all three WIGroups - so the previous two are merged into a third dedicated to the city WIGroup. (This is the kind of thing that's difficult to keep track of with totally autonomous WIGroups.)

Doing the Least Possible Damage

Okay, we're finally ready to unload this damn thing. The WIGroupUnloader reports that every child item under the shallowest parent group is ready to unload. Now it's just a matter of slowly breaking down each WIGroup, saving each WorldItem along the way, until they're all gone.

At this stage we could set the LoadState of the WIGroups under the shallowest parent group to Unloading, which would seal their collective fates and ensure that we could do this uninterrupted. But since we want to be able to reverse our decision for as long as possible this is where we start working from the bottom up instead of top-down.

The first thing a WIGroupUnloader does now is sort all of the child WIGroups it's managing by hierarchy depth. Then it sets the LoadState of all child WIGroups at the greatest shared depth to 'Unloading.' For them there's no return - they're going to disappear no matter what. But for every WIGroup at a higher depth there's still a chance to cancel.

Once every child WIGroup at that depth has been totally unloaded the WIGroupUnloader does a bit of housecleaning to verify that the children at the next greatest depth are still good to go. After all their LoadState is still set to PreparingToUnload - other WorldItems could have been added in the meantime, and they might not be ready to unload. But ideally that won't happen and child WIGroups will disappear depth-by-depth up until we hit the WIGroup that put in the initial Unload request.

This way if the order comes down to Load at any point we can still cancel with a minimum amount of damage done.

Aw, Crap. Multiplayer.

Okay, it's not too bad. But a weird wrinkle that multiplayer introduces is the concept of player ownership.

Speaking generally if a player causes a WIGroup to load, that player is now responsible for updating the contents of that WIGroup for everyone. For instance, if player2 joins a game and enters a wolf den - one far away from the player1 - that wolf den's WIGroup will be tagged as 'belonging' to player2. From that point forward, as long as player2 remains connected, the contents of that WIGroup will be determined by player2's game. So if player1 should follow in player2's footsteps and load the wolf den WIGroup on their end, the game will use player2's data as a source for StackItems, and any WorldItems (like wolves) that are loaded will by synced up to player2's wolves.

If player2 logs off then ownership of this group reverts back to player1, who is the 'game owner' - ie the one who started the game. And if player2's game unloads a WIGroup and player1 later loads it outside of their presence, the initial state will be pulled from player2, but from that point forward ownership and control of contents reverts back to player1.



Why not simply have player1 be responsible for all the WIGroups ever? Because in that scenario player1 wouldn't be able to unload any WIGroups that player2 (or player3, or player4) were keeping loaded locally, even if they were on opposite ends of the world. For performance reasons that's a bad way to go. One alternative would be some kind of WIGroup 'ghost' loading where the responsibilities of loading a WIGroup and updating its contents can be handled without actually fully loading the WorldItems in it, but I wouldn't know where to begin decoupling those responsibilities. Another option would be to restrict player movement to the same chunk or something, but that seems like a terrible restriction on an open world game.

In conclusion

Did anyone actually make it this far? This has got to be like Nyquill for most of you.

Anway - can you believe how much bloody work it takes to make something so simple happen? o_O These days when I play a game I find myself admiring rapid load speeds as often as graphics. Speaking of which, next month I'll be back with more screenshots.

Cheers

- L