Eideren 10 months ago
parent
commit
18189a8de1
1 changed files with 64 additions and 37 deletions
  1. 64 37
      en/manual/scripts/best-practice.md

+ 64 - 37
en/manual/scripts/best-practice.md

@@ -1,4 +1,5 @@
 # TODO: ADD EXAMPLES OF HOW TO AVOID ISSUES I AM RAISING
+# TODO: DO NOT FIGHT ECS, WORK WITH IT, IF YOU REALLY WANT TO DO WITHOUT, MAKE SURE THAT YOUR OTHER SYSTEM IS FINISHED BEFORE WRITING ANY LOGIC FOR IT
 
 # Best Practices
 
@@ -8,45 +9,44 @@ Tips to build a robust and maintainable CodeBase for your Stride Project
 
 Before starting on larger systems, make sure it would integrate with the rest of the existing systems, would it play well with saving and reloading, with the multiplayer architecture, when the game is paused, would it leak into other scenes ...
 
-Having this in mind ensures you avoid bugs and rewrites down the line because you hadn't thought of the above.
+Having this in mind ensures you won't write yourself into a corner, creating a system that needs to be patched up to work properly within your project, increasing your project's technical debt.
 
-## Implement custom assets
+A trap you may fall into is to then over design your systems, supporting features that your game will never need, convincing yourself that you could re-use that system for another game, that you could share or sell it.
+The vast majority of systems in games are purpose built for that game, your next game will require other features you could not support, let alone predict. You will also acquire a significant amount of experience working on this one, seeing issues it had and wanting to rewrite a better one.
 
-Some of the systems you will build make far more sense as assets rather than entities, consider making them an asset when any of the following is true:
-- It survives between multiple scenes
-- It is read only
-- It is not part of the definition of an entity, doesn't exist within your game world
-- It should be editable within the editor, by a designer
+### Figuring out your system's lifetime
 
-Examples of such are:
-- Player Input Configuration, defining actions in the source, assigning buttons in editor, saving and loading to disk when initializing the game
-- Balance settings, tweaking constants and formulas from the editor to improve iteration when testing your game
-- Mission/quest, referencing quests inside of components to unlock spots in game when they are completed, giving the ability for your designer to set those up
-- Loot tables, having a list of `UrlReference<Prefab>` with a probability of drop to easily re-use across multiple mobs
-- As an all-purpose robust 'key' or 'identifier' type, see [this section](#strings-as-keys-or-identifiers)
+What is the scope of the system you're writing;
+- Should the same instance be used throughout the entire lifetime of the application ?
+- Only while playing a game session ?
+- Only for the duration of the currently loaded game session ? 
+- Within a single map ?
+- For a specific game mode ?
+- ...
 
-### Do not mutate Assets
-To that point, make sure to only mutate assets when it makes sense to do so. Remember that a single asset may be referenced by hundreds of components and systems, those may not expect them to change at runtime. Adhering strictly to this idea also ensures that your game's state does not leak through them when loading a new session, game mode, or whatever else.
-For example, let's say you have an Axe Asset which has a list of modifier, you save the game, progress for a bit then add a modifier, but end up reloading ot the previous save, the modifier will carry over to that previous game state.
+This will set some expectation as to where the system you're building should reside, how it interacts with other systems, and when it should be started and disposed ...
 
-### Scene quirk
-The default scene the game spawns for you is the instance stored in the content manager, when running the game you mutate that very instance, meaning that if you want to retrieve the scene in its initial state, you must force the content manager to unload it, and then reload it.
-This makes it a bit counterintuitive when you just want to re-spawn the current scene to roll back your changes.
+Some entry and exit points to manage your systems' lifetime:
+- On demand by getting and setting it in the Services
+- System as a [singleton script](#Statics-singletons-and-other-global-like-writes) with the `Start()` and `Cancel()` 
+- Through your game's `BeginRun()` and `EndRun()`
+- As a component processor when associated component types are added to the scene
 
 ## Statics, singletons and other global-like writes
 We strongly advise you to make sure that the entirety of your game's state is implemented as instance properties on components inside the root scene's hierarchy. Avoid static properties and static objects.
 
-This is essential to reduce bugs that come in when implementing all encompassing systems, like the saving system, or the multiplayer layer. Those systems can then be implemented with the expectation that everything they may care about is within the root scene, they can replace this root scene and expect the game state to be completely reset, they can serialize or monitor those entities for changes, etc.
-If you do not follow this, part of your game's state will leak between play sessions, creating issues that are really hard to reproduce.
+This is essential to reduce bugs that come in when implementing systems that manage the game's state, like the saving system, or the multiplayer layer.
+Those systems can then be implemented with the expectation that everything they may care about is within the root scene, they can replace this root scene and expect the game state to be completely reset, they can serialize or monitor those entities for changes, etc. without the risk of your game's state leaking between play sessions and creating issues that are really hard to reproduce.
 
-Some systems were this wouldn't make sense, in that case see #Singletons
+Some systems may not make sense as part of the scene when:
 - The functionality and variables saved by such systems persist for the duration of the program, or across all sessions
-    - Saving, loading systems, meta-progression trackers, like achievements and roguelite progression
+    - Saving, loading systems, meta-progression trackers or achievements
 - The system is read-only
-    - Multiplayer server browser or matchmaking back-end. Once you are connected it's a different story though, now you must hold a bunch of states that are only valid to this session, it should not leak to the rest of the program, and so is best left as a component on an entity in the scene.
+    - Multiplayer server browser or matchmaking back-end. Once connected to a session it's a different story though, now you must hold a bunch of states that are only valid to this session, it should not leak to the rest of the program, and so is best left as a component on an entity in the scene.
 
-Singletons can be entirely replaced by using your game's `ServiceRegistry` which can be accessed from any `ScriptComponent`;
+Those restrictions do not prevent you from using the singleton pattern, you can use the `ServiceRegistry` which can be accessed from any `ScriptComponent`;
 ```cs
+// Here's a basic singleton class
 public class MySingleton : IService
 {
     public static IService NewInstance(IServiceRegistry r) => new MySingleton();
@@ -54,13 +54,13 @@ public class MySingleton : IService
     public void DoStuff(){}
 }
 
-// You may now access this singleton from any of your components:
+// You can create and get this singleton from any of your components:
 public override void Update()
 {
     Services.GetOrCreate<MySingleton>().DoStuff();
 }
 
-// If you need this singleton to live inside the scene, you just have to add a couple of calls
+// Here's a singleton implementation when you need its lifetime to be limited to the scene's:
 public class MySingleton : SyncScript, IService
 {
     public override void Start()
@@ -89,6 +89,29 @@ public class MySingleton : SyncScript, IService
 }
 ```
 
+## Implement custom assets
+
+Some of the systems you will build make far more sense as assets rather than entities, consider making them an asset when any of the following is true:
+- It survives between multiple scenes
+- It is read only
+- It is not part of the definition of an entity, doesn't exist within your game world
+- It should be editable within the editor, by a designer
+
+Examples of such are:
+- Player Input Configuration, defining actions in the source, assigning buttons in editor, saving and loading to disk when initializing the game
+- Balance settings, tweaking constants and formulas from the editor to improve iteration when testing your game
+- Mission/quest, referencing quests inside of components to unlock spots in game when they are completed, giving the ability for your designer to set those up
+- Loot tables, having a list of `UrlReference<Prefab>` with a probability of drop to easily re-use across multiple mobs
+- As an all-purpose robust 'key' or 'identifier' type, see [this section](#strings-as-keys-or-identifiers)
+
+### Do not mutate Assets
+To that point, make sure to only mutate assets when it makes sense to do so. Remember that a single asset may be referenced by hundreds of components and systems, those may not expect them to change at runtime. Adhering strictly to this idea also ensures that your game's state does not leak through them when loading a new session, game mode, or whatever else.
+For example, let's say you have an Axe Asset which has a list of modifier, you save the game, progress for a bit then add a modifier, but end up reloading ot the previous save, the modifier will carry over to that previous game state.
+
+### Scene quirks
+The default scene the game spawns for you is the instance stored in the content manager, when running the game you mutate that very instance, meaning that if you want to retrieve the scene in its initial state, you must force the content manager to unload it, and then reload it.
+This makes it a bit counterintuitive when you just want to re-spawn the current scene to roll back your changes.
+
 ## Strings as Keys or Identifiers
 This is a very popular anti-pattern, strings that are used as keys or identifiers shows up all over the place, here's a short example describing such a usage:
 The quest you're implementing requires the player to gather 10 bear arses, your check for that is to loop through the list of items the player has and check that the item's name match `bear arses`.
@@ -107,7 +130,7 @@ There are a couple ways to avoid this, one of the more robust ones is to rely on
 public class Item { }
 
 // Now in your component ...
-public Item ItemToCheck;
+public Item ItemToCheck; // You would assign this reference in the editor
 public int AmountRequired = 10;
 
 public bool HasTheItem()
@@ -117,11 +140,11 @@ public bool HasTheItem()
     return false;
 }
 ```
-- Robust; you can change its name and its path, as long as you do not delete it or change its internal id all components referencing it will keep that reference.
-- Easy to use and understand; If a component requires a specific asset you don't have an infinite amount of possibilities, you can either set it to an existing one or create a new one. It's far more foolproof too now that typos are out of the equation.
+- Robust; you can change its name and its path, as long as you do not delete it or change its internal id, all components referencing it will keep that reference.
+- Easy to use and understand; If a component requires a specific asset, you don't have an infinite amount of possibilities, you can either set it to an existing one or create a new one. It's far more foolproof too now that typos are out of the equation.
 - Easy to keep track of; each type has a unique extension which you can search for in your file explorer, they exist on disk, and so can be organized into the same directory.
-  - The editor's reference window lists all assets that use the selection, this greatly helps when you need to swap the identifier for another or remove it altogether, just go through all the assets that refer to it.
-  - you won't need to keep a document going over each identifier you might have in game, one just has to look at the directory were they are stored in the editor.
+    - The editor's reference window lists all assets that use the selection, this greatly helps when you need to swap the identifier for another or remove it altogether, just go through all the assets that refer to it.
+    - you won't need to keep a document going over each identifier you might have in game, one just has to look at the directory were they are stored in the editor.
 - Easy to extend; your identifier can now be more than just that, you can attach properties to it, perhaps a description to keep more information about this key.
 
 ## Avoid writing extension methods for access shortcuts
@@ -134,16 +157,20 @@ static void AddAsFirstChild(this Entity Entity, Entity entity) => Entity.Transfo
 ```
 
 It's a double-edged sword:
-- You are reducing the skill floor required for users not accustomed to the API, but you're also hindering their growth as they now rely on your shortcut instead of seeking it for themselves, making them aware of concepts and objects neighboring that one, giving them a clearer view of how all the objects fit together. What if they need to access all children, from this extension method they would not be aware that the transform component stores them, that he could just access it directly for that.
+- You are reducing the skill floor required for users not accustomed to the API, but you're also hindering their growth as they now rely on your shortcut instead of discovering the API for themselves, making them aware of concepts and objects neighboring that one, giving them a clearer view of how all the objects fit together. What if they need to access all children, from this extension method they would not be aware that the transform component stores them, that they could access it directly for that.
 - Make sure that accessing what you are hiding is never error-prone, even more so if the name of the method does not make that obvious. You may be reducing the time wasted from typing, but you could very well increase the time you would take to debug it when it does create issues.
 - It may very well be a slippery slope to introduce even more shortcuts to other properties or methods of the object you are presenting, how about creating an extension for the second child of the entity, the third ...
 - Polluting intellisense; in most cases this is a non-issue, but collection types are a prime example of this. Discoverability for extension methods through intellisense is nigh-on-impossible, there are just far too many extension methods introduced by linq.
-- It might imply to the user that your shortcut is somehow different compared to accessing it without the shortcut.
+- It might imply to the user that your shortcut is somehow different from the source.
+
+## Avoid EventKeys, async and other systems with large levels of indirection when mutating the game state
+Event keys and async methods carry a lot of implicit complexity as they may not complete when signaled/called. When the async resumed/the event key is received, the game may not be in a state where the logic you run is still valid. Some entities might have been removed from the scene, the inventory might no longer hold the item, the player character may be incapacitated ...
+
+This quirk also means that their execution are not part of their callers' stack, making debugging issues with them far harder to figure out.
 
-## static EventKeys
+Their lifetime is also far harder to reason about as EventKeys will carry the signal even if the scene was replaced in the meantime, while async will continue running when running outside your AsyncScript's `Execute()`
 
-Do not use them, they don't generate useful stacktraces when exceptions are thrown, making debugging harder than necessary. They do not provide direct mapping between callers and callees,
-Their lifetime is very complex to reason about, i.e.: we recommend making them static, but messages only make sense in the context of a scene, not across the whole process. So, if for example, some system signals the key, the whole scene unloads and reloads, the signal can still be received by systems that just came into this new scene.
+Prefer using c# events instead of EventKeys, and restructure your async into synchronous calls if you can avoid introducing any latency, otherwise, try to avoid touching the game state if at all possible.
 
 ## Object definition, ownership, a hierarchical idea