data_preferences.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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:`PoolStringArray <class_PoolStringArray>` 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 small array (initialized to 2^3 or 8 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" is used to calculate the index
  76. into the array. As an array, the OHM then has a quick lookup within the "table"
  77. of keys mapped to values. When the HashMap becomes too full, it increases to
  78. the next power of 2 (so, 16 records, then 32, etc.) and rebuilds the structure.
  79. Hashes are to reduce the chance of a key collision. If one occurs, the table
  80. must recalculate another index for the value that takes the previous position
  81. into account. In all, this results in constant-time access to all records at
  82. the expense of memory and some minor operational efficiency.
  83. 1. Hashing every key an arbitrary number of times.
  84. - Hash operations are constant-time, so even if an algorithm must do more
  85. than one, as long as the number of hash calculations doesn't become
  86. too dependent on the density of the table, things will stay fast.
  87. Which leads to...
  88. 2. Maintaining an ever-growing size for the table.
  89. - HashMaps maintain gaps of unused memory interspersed in the table
  90. on purpose to reduce hash collisions and maintain the speed of
  91. accesses. This is why it constantly increases in size quadratically by
  92. powers of 2.
  93. As one might be able to tell, Dictionaries specialize in tasks that Arrays
  94. do not. An overview of their operational details is as follows:
  95. - **Iterate:** Fast.
  96. - Op: Iterate over the map's internal vector of hashes. Return each key.
  97. Afterwards, users then use the key to jump to and return the desired
  98. value.
  99. - **Insert, Erase, Move:** Fastest.
  100. - Op: Hash the given key. Do 1 addition operation to look up the
  101. appropriate value (array start + offset). Move is two of these
  102. (one insert, one erase). The map must do some maintenance to preserve
  103. its capabilities:
  104. - update ordered List of records.
  105. - determine if table density mandates a need to expand table capacity.
  106. - The Dictionary remembers in what
  107. order users inserted its keys. This enables it to execute reliable iterations.
  108. - **Get, Set:** Fastest. Same as a lookup *by key*.
  109. - Op: Same as insert/erase/move.
  110. - **Find:** Slowest. Identifies the key of a value.
  111. - Op: Must iterate through records and compare the value until a match is
  112. found.
  113. - Note that Godot does not provide this feature out-of-the-box (because
  114. they aren't meant for this task).
  115. Godot implements Objects as stupid, but dynamic containers of data content.
  116. Objects query data sources when posed questions. For example, to answer
  117. the question, "do you have a property called, 'position'?", it might ask
  118. its :ref:`script <class_Script>` or the :ref:`ClassDB <class_ClassDB>`.
  119. One can find more information about what objects are and how they work in
  120. the :ref:`doc_what_are_godot_classes` article.
  121. The important detail here is the complexity of the Object's task. Every time
  122. it performs one of these multi-source queries, it runs through *several*
  123. iteration loops and HashMap lookups. What's more, the queries are linear-time
  124. operations dependent on the Object's inheritance hierarchy size. If the class
  125. the Object queries (its current class) doesn't find anything, the request
  126. defers to the next base class, all the way up until the original Object class.
  127. While these are each fast operations in isolation, the fact that it must make
  128. so many checks is what makes them slower than both of the alternatives for
  129. looking up data.
  130. .. note::
  131. When developers mention how slow the scripting API is, it is this chain
  132. of queries they refer to. Compared to compiled C++ code where the
  133. application knows exactly where to go to find anything, it is inevitable
  134. that scripting API operations will take much longer. They must locate the
  135. source of any relevant data before they can attempt to access it.
  136. The reason GDScript is slow is because every operation it performs passes
  137. through this system.
  138. C# can process some content at higher speeds via more optimized bytecode.
  139. But, if the C# script calls into an engine class'
  140. content or if the script tries to access something external to it, it will
  141. go through this pipeline.
  142. NativeScript C++ goes even further and keeps everything internal by default.
  143. Calls into external structures will go through the scripting API. In
  144. NativeScript C++, registering methods to expose them to the scripting API is
  145. a manual task. It is at this point that external, non-C++ classes will use
  146. the API to locate them.
  147. So, assuming one extends from Reference to create a data structure, like
  148. an Array or Dictionary, why choose an Object over the other two options?
  149. 1. **Control:** With objects comes the ability to create more sophisticated
  150. structures. One can layer abstractions over the data to ensure the external
  151. API doesn't change in response to internal data structure changes. What's
  152. more, Objects can have signals, allowing for reactive behavior.
  153. 2. **Clarity:** Objects are a reliable data source when it comes to the data
  154. that scripts and engine classes define for them. Properties may not hold the
  155. values one expects, but one doesn't need to worry about whether the property
  156. exists in the first place.
  157. 3. **Convenience:** If one already has a similar data structure in mind, then
  158. extending from an existing class makes the task of building the data
  159. structure much easier. In comparison, Arrays and Dictionaries don't
  160. fulfill all use cases one might have.
  161. Objects also give users the opportunity to create even more specialized data
  162. structures. With it, one can design their own List, Binary Search Tree, Heap,
  163. Splay Tree, Graph, Disjoint Set, and any host of other options.
  164. "Why not use Node for tree structures?" one might ask. Well, the Node
  165. class contains things that won't be relevant to one's custom data structure.
  166. As such, it can be helpful to construct one's own node type when building
  167. tree structures.
  168. .. tabs::
  169. .. code-tab:: gdscript GDScript
  170. extends Object
  171. class_name TreeNode
  172. var _parent : TreeNode = null
  173. var _children : = [] setget
  174. func _notification(p_what):
  175. match p_what:
  176. NOTIFICATION_PREDELETE:
  177. # Destructor.
  178. for a_child in _children:
  179. a_child.free()
  180. .. code-tab:: csharp
  181. // Can decide whether to expose getters/setters for properties later
  182. public class TreeNode : Object
  183. {
  184. private TreeNode _parent = null;
  185. private object[] _children = new object[0];
  186. public override void Notification(int what)
  187. {
  188. switch (what)
  189. {
  190. case NotificationPredelete:
  191. foreach (object child in _children)
  192. {
  193. TreeNode node = child as TreeNode;
  194. if (node != null)
  195. node.Free();
  196. }
  197. break;
  198. default:
  199. break;
  200. }
  201. }
  202. }
  203. From here, one can then create their own structures with specific features,
  204. limited only by their imagination.
  205. Enumerations: int vs. string
  206. ----------------------------
  207. Most languages offer an enumeration type option. GDScript is no different, but
  208. unlike most other languages, it allows one to use either integers or strings for
  209. the enum values (the latter only when using the ``export`` keyword in GDScript).
  210. The question then arises, "which should one use?"
  211. The short answer is, "whichever you are more comfortable with." This
  212. is a feature specific to GDScript and not Godot scripting in general;
  213. The languages prioritizes usability over performance.
  214. On a technical level, integer comparisons (constant-time) will happen
  215. faster than string comparisons (linear-time). If one wants to keep
  216. up other languages' conventions though, then one should use integers.
  217. The primary issue with using integers comes up when one wants to *print*
  218. an enum value. As integers, attempting to print MY_ENUM will print
  219. ``5`` or what-have-you, rather than something like ``"MyEnum"``. To
  220. print an integer enum, one would have to write a Dictionary that maps the
  221. corresponding string value for each enum.
  222. If the primary purpose of using an enum is for printing values and one wishes
  223. to group them together as related concepts, then it makes sense to use them as
  224. strings. That way, a separate data structure to execute on the printing is
  225. unnecessary.
  226. AnimatedTexture vs. AnimatedSprite vs. AnimationPlayer vs. AnimationTree
  227. ------------------------------------------------------------------------
  228. Under what circumstances should one use each of Godot's animation classes?
  229. The answer may not be immediately clear to new Godot users.
  230. :ref:`AnimatedTexture <class_AnimatedTexture>` is a texture that
  231. the engine draws as an animated loop rather than a static image.
  232. Users can manipulate...
  233. 1. the rate at which it moves across each section of the texture (fps).
  234. 2. the number of regions contained within the texture (frames).
  235. Godot's :ref:`VisualServer <class_VisualServer>` then draws
  236. the regions in sequence at the prescribed rate. The good news is that this
  237. involves no extra logic on the part of the engine. The bad news is
  238. that users have very little control.
  239. Also note that AnimatedTexture is a :ref:`Resource <class_Resource>` unlike
  240. the other :ref:`Node <class_Node>` objects discussed here. One might create
  241. a :ref:`Sprite <class_Sprite>` node that uses AnimatedTexture as its texture.
  242. Or (something the others can't do) one could add AnimatedTextures as tiles
  243. in a :ref:`TileSet <class_TileSet>` and integrate it with a
  244. :ref:`TileMap <class_TileMap>` for many auto-animating backgrounds that
  245. all render in a single batched draw call.
  246. The AnimatedSprite node, in combination with the
  247. :ref:`SpriteFrames <class_SpriteFrames>` resource, allows one to create a
  248. variety of animation sequences through spritesheets, flip between animations,
  249. and control their speed, regional offset, and orientation. This makes them
  250. well-suited to controlling 2D frame-based animations.
  251. If one needs trigger other effects in relation to animation changes (for
  252. example, create particle effects, call functions, or manipulate other
  253. peripheral elements besides the frame-based animation), then will need to use
  254. an :ref:`AnimationPlayer <class_AnimationPlayer>` node in conjunction with
  255. the AnimatedSprite.
  256. AnimationPlayers are also the tool one will need to use if they wish to design
  257. more complex 2D animation systems, such as...
  258. 1. **Cut-Out animations:** editing sprites' transforms at runtime.
  259. 2. **2D Mesh animations:** defining a region for the sprite's texture and
  260. rigging a skeleton to it. Then one animates the bones which
  261. stretch and bend the texture in proportion to the bones' relationships to
  262. each other.
  263. 3. A mix of the above.
  264. While one needs an AnimationPlayer to design each of the individual
  265. animation sequences for a game, it can also be useful to combine animations
  266. for blending, i.e. enabling smooth transitions between these animations. There
  267. may also be a hierarchical structure between animations that one plans out for
  268. their object. These are the cases where the :ref:`AnimationTree <class_AnimationTree>`
  269. shines. One can find an in-depth guide on using the AnimationTree
  270. :ref:`here <doc_animation_tree>`.