data_preferences.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. .. _doc_data_preferences:
  2. Data preferences
  3. ================
  4. Ever wondered whether one should approach problem X with data structure
  5. Y or Z? This article covers a variety of topics related to these dilemmas.
  6. .. note::
  7. This article makes references to "[something]-time" operations. This
  8. terminology comes from algorithm analysis'
  9. `Big O Notation <https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/>`_.
  10. Long-story short, it describes the worst-case scenario of runtime length.
  11. In laymen's terms:
  12. "As the size of a problem domain increases, the runtime length of the
  13. algorithm..."
  14. - Constant-time, ``O(1)``: "...does not increase."
  15. - Logarithmic-time, ``O(log n)``: "...increases at a slow rate."
  16. - Linear-time, ``O(n)``: "...increases at the same rate."
  17. - Etc.
  18. Imagine if one had to process 3 million data points within a single frame. It
  19. would be impossible to craft the feature with a linear-time algorithm since
  20. the sheer size of the data would increase the runtime far beyond the time allotted.
  21. In comparison, using a constant-time algorithm could handle the operation without
  22. issue.
  23. By and large, developers want to avoid engaging in linear-time operations as
  24. much as possible. But, if one keeps the scale of a linear-time operation
  25. small, and if one does not need to perform the operation often, then it may
  26. be acceptable. Balancing these requirements and choosing the right
  27. algorithm / data structure for the job is part of what makes programmers'
  28. skills valuable.
  29. Array vs. Dictionary vs. Object
  30. -------------------------------
  31. Godot stores all variables in the scripting API in the
  32. `Variant <https://docs.godotengine.org/en/latest/development/cpp/variant_class.html>`_
  33. class. Variants can store Variant-compatible data structures such as
  34. :ref:`Array <class_Array>` and :ref:`Dictionary <class_Dictionary>` as well as
  35. :ref:`Object <class_Object>` s.
  36. Godot implements Array as a ``Vector<Variant>``. The engine stores the Array
  37. contents in a contiguous section of memory, i.e. they are in a row adjacent
  38. to each other.
  39. .. note::
  40. For those unfamiliar with C++, a Vector is the name of the
  41. array object in traditional C++ libraries. It is a "templated"
  42. type, meaning that its records can only contain a particular type (denoted
  43. by angled brackets). So, for example, a
  44. :ref:`PackedStringArray <class_PackedStringArray>` would be something like
  45. a ``Vector<String>``.
  46. Contiguous memory stores imply the following operation performance:
  47. - **Iterate:** Fastest. Great for loops.
  48. - Op: All it does is increment a counter to get to the next record.
  49. - **Insert, Erase, Move:** Position-dependent. Generally slow.
  50. - Op: Adding/removing/moving content involves moving the adjacent records
  51. over (to make room / fill space).
  52. - Fast add/remove *from the end*.
  53. - Slow add/remove *from an arbitrary position*.
  54. - Slowest add/remove *from the front*.
  55. - If doing many inserts/removals *from the front*, then...
  56. 1. invert the array.
  57. 2. do a loop which executes the Array changes *at the end*.
  58. 3. re-invert the array.
  59. This makes only 2 copies of the array (still constant time, but slow)
  60. versus copying roughly 1/2 of the array, on average, N times (linear time).
  61. - **Get, Set:** Fastest *by position*. Ex. can request 0th, 2nd, 10th record, etc.
  62. but cannot specify which record you want.
  63. - Op: 1 addition operation from array start position up to desired index.
  64. - **Find:** Slowest. Identifies the index/position of a value.
  65. - Op: Must iterate through array and compare values until one finds a match.
  66. - Performance is also dependent on whether one needs an exhaustive
  67. search.
  68. - If kept ordered, custom search operations can bring it to logarithmic
  69. time (relatively fast). Laymen users won't be comfortable with this
  70. though. Done by re-sorting the Array after every edit and writing an
  71. ordered-aware search algorithm.
  72. Godot implements Dictionary as an ``OrderedHashMap<Variant, Variant>``. The engine
  73. stores a giant array (initialized to 1000 records) of key-value pairs. When
  74. one attempts to access a value, they provide it a key. It then *hashes* the
  75. key, i.e. converts it into a number. The "hash" becomes the index into the
  76. array, giving the OHM a quick lookup for the value within the conceptual
  77. "table" of keys mapped to values.
  78. Hashes are to reduce the chance of a key collision. If one occurs, the table
  79. must recalculate another index for the value that takes the previous position
  80. into account. In all, this results in constant-time access to all records at
  81. the expense of memory and some minor operational efficiency.
  82. 1. Hashing every key an arbitrary number of times.
  83. - Hash operations are constant-time, so even if an algorithm must do more
  84. than one, as long as the number of hash calculations doesn't become
  85. too dependent on the density of the table, things will stay fast.
  86. Which leads to...
  87. 2. Maintaining a huge size for the table.
  88. - The reason it starts with 1000 records, and the reason it forces
  89. large gaps of unused memory interspersed in the table is to
  90. minimize hash collisions and maintain the speed of the accesses.
  91. As one might be able to tell, Dictionaries specialize in tasks that Arrays
  92. aren't. An overview of their operational details is as follows:
  93. - **Iterate:** Fast.
  94. - Op: Iterate over the map's internal vector of hashes. Return each key.
  95. Afterwards, users then use the key to jump to and return the desired
  96. value.
  97. - **Insert, Erase, Move:** Fastest.
  98. - Op: Hash the given key. Do 1 addition operation to look up the
  99. appropriate value (array start + offset). Move is two of these
  100. (one insert, one erase). The map must do some maintenance to preserve
  101. its capabilities:
  102. - update ordered List of records.
  103. - determine if table density mandates a need to expand table capacity.
  104. - The Dictionary remembers in what
  105. order users inserted its keys. This enables it to execute reliable iterations.
  106. - **Get, Set:** Fastest. Same as a lookup *by key*.
  107. - Op: Same as insert/erase/move.
  108. - **Find:** Slowest. Identifies the key of a value.
  109. - Op: Must iterate through records and compare the value until a match is
  110. found.
  111. - Note that Godot does not provide this feature out-of-the-box (because
  112. they aren't meant for this task).
  113. Godot implements Objects as stupid, but dynamic containers of data content.
  114. Objects query data sources when posed questions. For example, to answer
  115. the question, "do you have a property called, 'position'?", it might ask
  116. its :ref:`script <class_Script>` or the :ref:`ClassDB <class_ClassDB>`.
  117. One can find more information about what objects are and how they work in
  118. the :ref:`doc_what_are_godot_classes` article.
  119. The important detail here is the complexity of the Object's task. Every time
  120. it performs one of these multi-source queries, it runs through *several*
  121. iteration loops and HashMap lookups. What's more, the queries are linear-time
  122. operations dependent on the Object's inheritance hierarchy size. If the class
  123. the Object queries (its current class) doesn't find anything, the request
  124. defers to the next base class, all the way up until the original Object class.
  125. While these are each fast operations in isolation, the fact that it must make
  126. so many checks is what makes them slower than both of the alternatives for
  127. looking up data.
  128. .. note::
  129. When developers mention how slow the scripting API is, it is this chain
  130. of queries they refer to. Compared to compiled C++ code where the
  131. application knows exactly where to go to find anything, it is inevitable
  132. that scripting API operations will take much longer. They must locate the
  133. source of any relevant data before they can attempt to access it.
  134. The reason GDScript is slow is because every operation it performs passes
  135. through this system.
  136. C# can process some content at higher speeds via more optimized bytecode.
  137. But, if the C# script calls into an engine class'
  138. content or if the script tries to access something external to it, it will
  139. go through this pipeline.
  140. NativeScript C++ goes even further and keeps everything internal by default.
  141. Calls into external structures will go through the scripting API. In
  142. NativeScript C++, registering methods to expose them to the scripting API is
  143. a manual task. It is at this point that external, non-C++ classes will use
  144. the API to locate them.
  145. So, assuming one extends from Reference to create a data structure, like
  146. an Array or Dictionary, why choose an Object over the other two options?
  147. 1. **Control:** With objects comes the ability to create more sophisticated
  148. structures. One can layer abstractions over the data to ensure the external
  149. API doesn't change in response to internal data structure changes. What's
  150. more, Objects can have signals, allowing for reactive behavior.
  151. 2. **Clarity:** Objects are a reliable data source when it comes to the data
  152. that scripts and engine classes define for them. Properties may not hold the
  153. values one expects, but one doesn't need to worry about whether the property
  154. exists in the first place.
  155. 3. **Convenience:** If one already has a similar data structure in mind, then
  156. extending from an existing class makes the task of building the data
  157. structure much easier. In comparison, Arrays and Dictionaries don't
  158. fulfill all use cases one might have.
  159. Objects also give users the opportunity to create even more specialized data
  160. structures. With it, one can design their own List, Binary Search Tree, Heap,
  161. Splay Tree, Graph, Disjoint Set, and any host of other options.
  162. "Why not use Node for tree structures?" one might ask. Well, the Node
  163. class contains things that won't be relevant to one's custom data structure.
  164. As such, it can be helpful to construct one's own node type when building
  165. tree structures.
  166. .. tabs::
  167. .. code-tab:: gdscript GDScript
  168. extends Object
  169. class_name TreeNode
  170. var _parent : TreeNode = null
  171. var _children : = [] setget
  172. func _notification(p_what):
  173. match p_what:
  174. NOTIFICATION_PREDELETE:
  175. # Destructor.
  176. for a_child in _children:
  177. a_child.free()
  178. .. code-tab:: csharp
  179. // Can decide whether to expose getters/setters for properties later
  180. public class TreeNode : Object
  181. {
  182. private TreeNode _parent = null;
  183. private object[] _children = new object[0];
  184. public override void Notification(int what)
  185. {
  186. if (what == NotificationPredelete)
  187. {
  188. foreach (object child in _children)
  189. {
  190. TreeNode node = child as TreeNode;
  191. if (node != null)
  192. node.Free();
  193. }
  194. }
  195. }
  196. }
  197. From here, one can then create their own structures with specific features,
  198. limited only by their imagination.
  199. Enumerations: int vs. string
  200. ----------------------------
  201. Most languages offer an enumeration type option. GDScript is no different,
  202. but unlike most other languages, it allows one to use either integers or
  203. strings for the enum values. The question then arises, "which should one
  204. use?"
  205. The short answer is, "whichever you are more comfortable with." This
  206. is a feature specific to GDScript and not Godot scripting in general;
  207. The languages prioritizes usability over performance.
  208. On a technical level, integer comparisons (constant-time) will happen
  209. faster than string comparisons (linear-time). If one wants to keep
  210. up other languages' conventions though, then one should use integers.
  211. The primary issue with using integers comes up when one wants to *print*
  212. an enum value. As integers, attempting to print MY_ENUM will print
  213. ``5`` or what-have-you, rather than something like ``"MyEnum"``. To
  214. print an integer enum, one would have to write a Dictionary that maps the
  215. corresponding string value for each enum.
  216. If the primary purpose of using an enum is for printing values and one wishes
  217. to group them together as related concepts, then it makes sense to use them as
  218. strings. That way, a separate data structure to execute on the printing is
  219. unnecessary.
  220. AnimatedTexture vs. AnimatedSprite vs. AnimationPlayer vs. AnimationTree
  221. ------------------------------------------------------------------------
  222. Under what circumstances should one use each of Godot's animation classes?
  223. The answer may not be immediately clear to new Godot users.
  224. :ref:`AnimatedTexture <class_AnimatedTexture>` is a texture that
  225. the engine draws as an animated loop rather than a static image.
  226. Users can manipulate...
  227. 1. the rate at which it moves across each section of the texture (fps).
  228. 2. the number of regions contained within the texture (frames).
  229. Godot's :ref:`VisualServer <class_VisualServer>` then draws
  230. the regions in sequence at the prescribed rate. The good news is that this
  231. involves no extra logic on the part of the engine. The bad news is
  232. that users have very little control.
  233. Also note that AnimatedTexture is a :ref:`Resource <class_Resource>` unlike
  234. the other :ref:`Node <class_Node>` objects discussed here. One might create
  235. a :ref:`Sprite <class_Sprite>` node that uses AnimatedTexture as its texture.
  236. Or (something the others can't do) one could add AnimatedTextures as tiles
  237. in a :ref:`TileSet <class_TileSet>` and integrate it with a
  238. :ref:`TileMap <class_TileMap>` for many auto-animating backgrounds that
  239. all render in a single batched draw call.
  240. The AnimatedSprite node, in combination with the
  241. :ref:`SpriteFrames <class_SpriteFrames>` resource, allows one to create a
  242. variety of animation sequences through spritesheets, flip between animations,
  243. and control their speed, regional offset, and orientation. This makes them
  244. well-suited to controlling 2D frame-based animations.
  245. If one needs trigger other effects in relation to animation changes (for
  246. example, create particle effects, call functions, or manipulate other
  247. peripheral elements besides the frame-based animation), then will need to use
  248. an :ref:`AnimationPlayer <class_AnimationPlayer>` node in conjunction with
  249. the AnimatedSprite.
  250. AnimationPlayers are also the tool one will need to use if they wish to design
  251. more complex 2D animation systems, such as...
  252. 1. **Cut-Out animations:** editing sprites' transforms at runtime.
  253. 2. **2D Mesh animations:** defining a region for the sprite's texture and
  254. rigging a skeleton to it. Then one animates the bones which
  255. stretch and bend the texture in proportion to the bones' relationships to
  256. each other.
  257. 3. A mix of the above.
  258. While one needs an AnimationPlayer to design each of the individual
  259. animation sequences for a game, it can also be useful to combine animations
  260. for blending, i.e. enabling smooth transitions between these animations. There
  261. may also be a hierarchical structure between animations that one plans out for
  262. their object. These are the cases where the :ref:`AnimationTree <class_AnimationTree>`
  263. shines. One can find an in-depth guide on using the AnimationTree
  264. :ref:`here <doc_animation_tree>`.