<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexey Volkov on Medium]]></title>
        <description><![CDATA[Stories by Alexey Volkov on Medium]]></description>
        <link>https://medium.com/@asgalex?source=rss-6226a9368ab5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NeNrLfe-n6HSMmGUkIp_Kw.jpeg</url>
            <title>Stories by Alexey Volkov on Medium</title>
            <link>https://medium.com/@asgalex?source=rss-6226a9368ab5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:54:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asgalex/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Speeding up HashSet, HashMap and loops in Dart]]></title>
            <link>https://asgalex.medium.com/speeding-up-hashset-hashmap-and-loops-in-dart-d587663daefa?source=rss-6226a9368ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d587663daefa</guid>
            <category><![CDATA[dart-programming-language]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Alexey Volkov]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 15:02:47 GMT</pubDate>
            <atom:updated>2023-12-01T15:12:49.704Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been profiling your application, you have probably experienced a mixture of frustration and excitement when looking at a particularly “fat” method in the CPU Flame Chart. Frustration — because your program is still not perfect in terms of speed. Excitement — that you can get to the cause of the problem and squeeze some more free time for the processor for more useful calculations. At least, I regularly fall victim to both of these feelings, to which this article owes its appearance.</p><p>My case is an attempt to squeeze more speed and features out of the Flame game engine than it can “out of the box”. Game development has its own peculiarities in comparison with “parsing large JSON” or eliminating the glitch when playing an animation once. At least because potentially voluminous calculations are performed on absolutely every frame in games. So, my experience probably won’t resonate much with the problems most Flutter developers encounter.</p><p>However, I would like to note that the approaches described here can work not only for Dart, but for any language, especially high-level ones — you just need to specify the details of how certain data structures are implemented in your language, and based on this choose the optimal method of working with them.</p><h3>Visualize the problem</h3><p>So, let’s say you opened Flame Chart and saw some huge forEach, inefficient HashSet and HashMap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*GaY4tj4TFAVimtwH-cwNqQ.png" /><figcaption>Long access to HashMap items</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5x5BDeC41Wl2uSVkiZ1Tsg.png" /><figcaption>Long access to HashMap and resource costs for adding items to HashSet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKCQiuQnRh2A_cOvoHuWDQ.png" /><figcaption>Iterating over a HashSet takes a very long time</figcaption></figure><p>Note that these functions are mostly the last in the call stack. That is, slow operation is not caused by some custom logic inside the loop, but by the very number of these loops.</p><p>Of course, when the engine’s “internals” and private methods of built-in data structures come to the fore, the first step is to see if we can somehow reduce the number of loops. Here the decision depends on your particular case. The trouble is that it may not solve the problem, and filling an array with a lot of elements and then repeatedly looping through them may be simply necessary for the logic of your application. As, for example, in a game engine — there it is simply impossible to throw some game objects out of processing for a long time without creating noticeable bugs.</p><p>And now it’s the end of everything? Are we going to fork Dart and rewrite its “slow libraries”? Or should we throw away this language altogether and start rewriting the whole program in another “trendy modern and exactly the fastest language in the world”? No. Instead, I suggest that you just do a little work with your head, especially since some of the solutions are right on the surface, but because of their triviality they may simply go unnoticed.</p><h3>Deceptive Iterable</h3><p>High-level languages are great. They take care of a lot of minor headaches, allowing you to concentrate on the main things. But if you have to do deep optimization, you will have to give up some of these conveniences.</p><p>Take Iterable, for example. It is the same for List, Map, and Set, but only at the interface level. And the implementations are not identical at all. So, if you have a set of data inside a HashSet or HashMap, and you have to loop over it many times, it’s worth making one extra pass to save this data into a regular List. Iterating over a simple list will be the cheapest. And yes, it would be better to make this list unmodifiable <em>(List.filled(emptyObject, growable: false))</em>, and add items to it by rewriting indexes in the for loop — in case the code for filling the list is also in the performance-critical zone.</p><p>Here’s an illustrative example from the bowels of Dart sources. Compare the work of a regular list iterator and HashSet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*Jsvd6slWFTwpvZfxMa5xcg.png" /><figcaption>A pice of Dart sources</figcaption></figure><p>You can verufy it personally <a href="https://github.com/dart-lang/sdk/blob/2cb00aad5c035b75aa12608207e252217277fd99/sdk/lib/_internal/vm_shared/lib/collection_patch.dart#L859C5-L859C5">here</a> and <a href="https://github.com/dart-lang/sdk/blob/3ba4c37734ce6f521ef06b36f2541a820140a9cf/sdk/lib/internal/iterable.dart#L345C11-L345C11">here</a>.</p><p>In an ordinary list iterator moves over a single list, which is expected, but inside a HashSet there are many lists on which the iterator jumps according to some logic. The kind of logic is not important for now, but the fact that this logic is more than just index increment — this is most important.</p><p>A similar picture will be shown in case of a battle between access by key for HashSet and access by index for List. The latter obviously will produce the result faster.</p><h3>How to use List instead of Map.</h3><p>Attention! Too obvious things described here!!!</p><p>Look at data that stored in your Map. What is its lifecycle? At what point do you know exact number of items in collection? When do you fill out the collection and when do you check the result? Because the process can be significantly accelerated if:</p><ol><li>You know collection length before using it or filling with data.</li><li>You can store data in simple indexed lists, which are unmodifiable while you working with them.</li><li>Your code requires a lot of Map access operations. That calls should take significant space in Flame Chart. Otherwise, there are no point in optimization, because it will produce additional loop over Map’s elements that will make your code even slower.</li></ol><p>If everything fits together, then you can do optimization steps:</p><ol><li>Collect Map “keys” into unmodifiable List&lt;T&gt;</li><li>Create another unmodifiable List&lt;T&gt; to store your Map’s values. Both arrays length must be equal.</li><li>Then access both arrays just by index, as long as both of them stay unmodified. This should be much faster than access by key for Map data structure.</li></ol><p>The description is very abstract just because real-life cases could be very different and I do not know exactly, which one you have. Next, I’ll try to show an example of code, but it still is too abstract and does not have any sense itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nTCD_fDgaHcdowfjfvk0g.png" /><figcaption>before and after</figcaption></figure><p>Benchmark’s results look very predictable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6df625b372cc8bbde83869913216b6a/href">https://medium.com/media/a6df625b372cc8bbde83869913216b6a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*zoAtAEjmIGNmJtXwj1dN2Q.png" /><figcaption>List vs HashMap</figcaption></figure><p>It seems that for the sake of a 15-fold increase, it is worth both bothering and rolling back from a complex data structure to a simple one, from “sexy iterators” to the grandfather’s “for(i=0….”</p><h3>Accelerating Set and Map without giving them up</h3><p>But what if the conditions of the task do not allow you to roll back to the lists? Even in this case, we still have the opportunity to increase performance.</p><p>It’s all about hash functions. Set and Map uses hashCode, the field which exists in every Dart object. But the trick is same as with iterators: only interface is similar, but realizations are different. If we would make googling again, we will find out that there are several bug-reports to dart developers about significant difference between hash algorithms of different data types. For example, here you can see a commit that enhances hashCode function for integer data type: <a href="https://github.com/dart-lang/sdk/commit/8c0df46887744e229b74bfb8c6bfc05df67f67eb">https://github.com/dart-lang/sdk/commit/8c0df46887744e229b74bfb8c6bfc05df67f67eb</a> . But there is still an open discussion that Object.hashCode could work faster (but this is not accurate): <a href="https://github.com/dart-lang/sdk/issues/24206">https://github.com/dart-lang/sdk/issues/24206</a></p><p>From what we have read, a simple conclusion suggests itself: if we cannot identify an object in the collection simply by its ordinal number, then at least we will try to identify it simply by some unique integer identifier. What will happen? Let’s look at next benchmark:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/655534e641db891dcd937ce4db70f0bc/href">https://medium.com/media/655534e641db891dcd937ce4db70f0bc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*LQBbAtAcH3UKL6BUrD0zUQ.png" /><figcaption>int.hashCode is 2 times faster than Object.hashCode</figcaption></figure><p>Also, here is a fragment of more optimal code:</p><pre>int mapAccessHashSetByIndex(int objectsCount) {<br>  final objects = MyObject.createObjects(objectsCount, true);<br><br>  final keyValueMap = &lt;int, bool&gt;{}; // &lt;--- Key is integer, not object!!!<br>  for (var i = 0; i &lt; objects.length; i++) {<br>    final object = objects[i];<br>    if (int.parse(object.data) &lt; 1000) {<br>      keyValueMap[i] = true;<br>    }<br>  }<br><br>  ///<br>  /// Performance-critical part: working with data, checking a result that was<br>  /// previously calculated<br>  ///<br>  final sw = Stopwatch();<br>  sw.start();<br>  for (var i = 0; i &lt; objects.length; i++) {<br>    for (var j = 0; j &lt; objects.length; j++) {<br>      if (i == j) continue;<br>      if (keyValueMap[i] == keyValueMap[j]) { // &lt;-- access by int index, not object itself!<br>        // any useful logic here<br>      }<br>    }<br>  }<br>  sw.stop();<br>  return sw.elapsedMicroseconds;<br>}</pre><p>Well, it is not 15 times faster, just 2 times. Still a good result, still worth it to mess around a little!</p><h3>When every microsecond matters</h3><p>Imagine, you can’t to rewrite your code by described recipes, but still want to improve performance. Will you have any choice between approaches? Yes, you will! But from this point you will need data structures of special kind, bitwise operations magic, and also you will struggle with probability of inaccurate results.</p><p>Let’s see a simplest case:</p><ol><li>You have pairs of objects.</li><li>You need to save and access data foreach pair relation</li></ol><p>If you won’t think a lot about the task, you will simply create <em>Map&lt;Object, Map&lt;Object, ObjectData&gt;&gt;</em> data structure and work with this heavy and slow monster. But it will solve your task anyway.</p><p>In some cases, you can to rewrite this to lists as I described previously. But if you can’t, there are another solution: store your data in structure like <em>Map&lt;int, Data&gt;</em>. The key of map is integer and you can obtain it using bitwise AND operation, for example: <em>final key = a.hashCode &amp; b.hashCode</em>.</p><p>However, this magic is not too black, this is simplest level of arcane. If we will dig deeper, we will find more advanced data structures for more specific cases.</p><p>Let’s look at two of them: BloomFilter and XorFilter. These structures allow to check, if a set of objects do NOT contain specified object. Or to check, if a set of objects DO contain specified object with high probability (but with some probability of false-positive result). These structures claim to work faster than Hash Sets, but are slower while filling with data.</p><p>In the repository <a href="https://github.com/FastFilter/">https://github.com/FastFilter/</a> you can find a lot of implementations for wide variety of languages… except Dart. I’d like to use XorFilter in my own application, because it claims to be faster than BloomFilter, but there is no any existing library for Dart. But for Bloom Filter there are two implementations. I chose this one for my experiments: <a href="https://pub.dev/packages/dart_bloom_filter">https://pub.dev/packages/dart_bloom_filter</a></p><p>I going to show another portion of benchmarks but before let me do some important notices:</p><ol><li>In these cases, performance changes are very… tiny. So, if you have another ineffective code in performance-critical part, this tiny optimization will be useless</li><li>For the same reason, on small amounts of data / numbers of runs / debug modes, the difference may be at the level of computational error.</li></ol><p>Actually, when running the benchmark on 10,000 elements in VM mode, I got identical performance for both the HashSet and the BloomFilter. But having compiled the application for Windows and increased the number of elements and iterations to 10,000,000, the difference immediately became visible:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1d9de911afd24df373ab1afe8b55a09/href">https://medium.com/media/b1d9de911afd24df373ab1afe8b55a09/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*CAuKjmezwh2SOljVYxzQaA.png" /><figcaption>+20% to performance</figcaption></figure><p>Well, we squeezed out a little more… 20% faster than the already fast one… whether it’s worth it for your task, taking into account the side effect — the probability of a false positive test result — is up to you to decide. But it’s good that there is some possibility at all.</p><p>Below I posted HashSet and BloomFilter benchmark implementations.</p><p>HashSet:</p><pre>int hashSetCheck(int elementsCount) {<br>  ///<br>  /// Preparing data. No need to benchmark here<br>  ///<br>  final objects = MyObject.createObjects(elementsCount, false);<br><br>  final random = Random();<br>  final objectsSet = &lt;int&gt;{};<br><br>  for (var i = 0; i &lt; objects.length; i++) {<br>    if (random.nextBool()) {<br>      objectsSet.add(i);<br>    }<br>  }<br><br>  ///<br>  /// Performance-critical part: working with data, checking a result that was<br>  /// previously calculated<br>  ///<br>  final sw = Stopwatch();<br>  sw.start();<br>  for (var i = 0; i &lt; objects.length; i++) {<br>    if (objectsSet.contains(i)) {<br>      // do something<br>    }<br>  }<br><br>  sw.stop();<br>  return sw.elapsedMicroseconds;<br>}</pre><p>BloomFilter:</p><pre>int bloomCheck(int elementsCount) {<br>  ///<br>  /// Preparing data. No need to benchmark here<br>  ///<br>  final objects = MyObject.createObjects(elementsCount, false);<br><br>  final random = Random();<br><br>  final bloomTrue = BloomFilter&lt;int&gt;(objects.length, 0.1);<br><br>  for (var i = 0; i &lt; objects.length; i++) {<br>    if (random.nextBool()) {<br>      bloomTrue.add(item: i);<br>    }<br>  }<br><br>  ///<br>  /// Performance-critical part: working with data, checking a result that was<br>  /// previously calculated<br>  ///<br>  final sw = Stopwatch();<br>  sw.start();<br>  for (var i = 0; i &lt; objects.length; i++) {<br>    if (bloomTrue.contains(item: i)) {<br>      // do something<br>    }<br>  }<br>  sw.stop();<br>  return sw.elapsedMicroseconds;<br>}</pre><h3>I rewrote my code following the article’s recommendations, but it didn’t get any faster!</h3><p>And yes, I will not mislead you: if you rewrite a couple of loops to a more optimal algorithm, it may not affect the speed of your application at all. Or it may affect it somehow. It depends on how often this code block is used and what other performance-affecting methods there are around it.</p><p>In my case, there were at least eight rewriting and re-profiling cycles, although I didn’t count them on purpose. Each change itself did not increase the perceived speed of the application, but it removed a block with “long” code from the Flame Chart, or significantly reduced it.</p><p>In the end, the effect became noticeable only when all the optimizations started working together. Namely the effect was expressed in the fact that instead of 28 FPS my game engine demo began to produce stable 60, processing collisions simultaneously for 161 moving objects. In Flame Chart it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6FbCct-ErC1Y1Wz269z1w.png" /><figcaption>I have no idea how to optimize Vector2.x :-)</figcaption></figure><p>Yes, BloomFilter is quite small, but it still glows. Although HashSet.[] was glowing even more. Otherwise, there are no more “particularly long” cycles, as it was on the screens at the beginning of the article, which, in general, can be considered a success.</p><h3>Why not use Isolates?</h3><p>Some people may ask, why bother with performance in a single thread, if theoretically it is possible to spread computations across different isolates? But sadly, Dart has big problems here:</p><ol><li>Copying a large amount of data between isolates per frame is 100% too expensive, and shared memory is not available to us (in fact, we have a workaround with ffi, C++ and integer representation of a pointer to shared memory area — for native. But this is too tricky and in fact requires to use other language a lot. And in pure JS we can use SharedArrayBuffer, but this solution also does not cross-platform and requires separate implementation).</li><li>Well, to speed-up communication between isolates we can to convert our data into binary format. We even have great library to make it faster in runtime and save our own time: FlatBuffers library <a href="https://github.com/google/flatbuffers">https://github.com/google/flatbuffers</a>. But with a large number of objects, it is still too expensive to serialize into binary form. The lack of support for launching some necessary libraries inside isolates, the presence of callbacks in class variables, the need to rewrite everything separately in order to be able to launch an isolate on the web — all this makes the task extremely spicy, complex, tricky and unpredictable.<br> But I have implemented this part in my project, it works successfully and gives a visible performance gain. But was it easy, fast and simple? No.</li><li>Your code becomes asynchronous, although for the game engine logic to work correctly, it is simply necessary that some calculations finish before the next one starts.</li><li>As a result, we come to a situation when code execution from the previous frame overlaps with the code from the next frame, and the heavier the calculations are, the more layers of such “overlapping” we get.</li><li>As a result, more resources are spent not even on your code itself, but on maintaining async-await, and you will have fast-executing functions on dart and veeery looong-running code of native libraries of the platform in your Flame Chart.</li></ol><p>In summary, it is more reliable and easier to optimize work in one thread than to spread it over several threads. That’s how it is, our praised Dart, what can you do about it… But the issue of parsing large JSON has been considered up and down 😊</p><h3>Useful links</h3><p>You can find complete benchmarks code in the repository and poke around yourself: <a href="https://github.com/ASGAlex/dart_iterables_benchmarks">https://github.com/ASGAlex/dart_iterables_benchmarks</a></p><p>Important note: it is better to run each test separately, because if you just run the functions sequentially within one application, you don’t know at what moment Garbage Collector will come and ruin all your measurements by cleaning up the memory after the previous test.</p><p>If anyone is interested in poking what kind of game engine I have, please visit the source code at <a href="https://github.com/ASGAlex/flame_spatial_grid">https://github.com/ASGAlex/flame_spatial_grid</a> and the demo on the web: <a href="https://asgalex.github.io/flame_spatial_grid/">https://asgalex.github.io/flame_spatial_grid/</a> .</p><p>In the article I mentioned using flat buffers to speed up communication with the isolate and running isolates on the web via web-workers. In general, this is an extensive topic, so I won’t dive into it here, but if anyone is interested in seeing examples of use, please do:</p><ol><li><a href="https://github.com/ASGAlex/flame_spatial_grid/tree/f870122ca6177bd7fb3f8c3a10da0f5ac3f929cb/lib/src/collisions/optimizer/isolate/flat_buffers">Schemas for flat buffers and generated code with some manual additions.</a></li><li><a href="https://github.com/ASGAlex/flame_spatial_grid/blob/f870122ca6177bd7fb3f8c3a10da0f5ac3f929cb/lib/src/collisions/optimizer/collision_optimizer.dart#L78C35-L78C35">Data convertation into binary buffer, sending to isolate (in 4 parallel threads), getting results in binary format with decoding “under the hood” into readable format</a>.</li><li><a href="https://github.com/ASGAlex/flame_spatial_grid/blob/f870122ca6177bd7fb3f8c3a10da0f5ac3f929cb/lib/src/collisions/optimizer/isolate/entry_point.dart">Isolate itself, adapted for work in the web</a>.</li></ol><p>I hope, one day I will be able to tell you a success-story about truly parallel computations in Dart, or at least a partial-success story… 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d587663daefa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Flame 32 times faster with collision detection and additional tricks]]></title>
            <link>https://asgalex.medium.com/make-flame-32-times-faster-with-collision-detection-and-additional-tricks-3c212404b0b0?source=rss-6226a9368ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c212404b0b0</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-game]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Alexey Volkov]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 21:28:30 GMT</pubDate>
            <atom:updated>2022-12-11T18:56:00.529Z</atom:updated>
            <content:encoded><![CDATA[<p>Flame rendering performance is strictly dependent on how fast your CPU is and how many operations it must perform at each rendering cycle. I already described it in detail <a href="https://asgalex.medium.com/flutter-flame-simplest-optimization-techniques-372dbe6815f">in my previous article</a> about optimization techniques.</p><p>But if you have a lot of interacting objects, the most expensive operation in your game would be collision detection. It might be so expansive that you would not see anything else except slow collision calculation on the performance-monitoring screen. It will hide all other unoptimized things and become the most painful problem.</p><p>By default, Flame uses “Sweep and prune” algorithm at broad phase of collision detection. It works fast enough if you have less than 100 collideable components. In other case you will have big performance problems.</p><p>But not since Flame 1.4.0 release. Since this release you can change broad phase algorithm to more efficient one: “Quad tree”.</p><h3>Quad Tree implementation problems</h3><p>I’ll skip detail description of “what broad phase is?” — it is already well described in <a href="https://docs.flame-engine.org/1.3.0/flame/collision_detection.html#broad-phase">official Flame documentation</a> and many other articles about collision detection.</p><p>I’ll also skip detailed description of “how does Quad Tree work?” — this is very common thing for gamedev ant there are a lot of articles about.</p><p>Here I want to describe Flame’s implementation features, why it would work faster with this engine than anything you’ll find in internet.</p><p>For Dart we already have implementation of the algorithm: <a href="https://pub.dev/packages/quadtree_dart">quadtree_dart</a>. It works nice, it even has spectacular demo, but it shares problems of many other implementations — no matter what language was used:</p><ol><li>Authors of algorithms firstly think about objects that constantly moves. So that’s why they do not bother about state preservation, they just recalculate whole map every calculation tick, every time rebuild quadrants from scratch. As the advantage of such approach, they highlight that a map would be divided into quadrants in most optimal way for collision calculation.</li><li>But in many games, there are a lot of static objects, at least temporary static. In such situation it worth to divide the map into quadrants once and then only receive updates for moved objects, and to create new sections if needed. And to skip resource-heavy step of removing unnecessary quadrants.</li><li>As a consequence of 1st point, many algorithms do not save relation between object and quadrant, instead it is calculated every time by object’s coordinates. This is also too expensive, at least for Dart.</li></ol><p>So, many of “algorithmic guys” prefer to run calculations over and over instead saving state in something like HashMap and just update it incrementally in cause if something would change. It absolutely worth to spend a little more memory, to create additional data structures but increase performance a lot.</p><p>Flame’s implementation is based on one of such algorithms (to be concrete, on this one: <a href="https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374">https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374</a> ), but all mentioned problems are solved.</p><h3>Benchmarks</h3><p>A month before “QuadTree feature” become a part of Flame, I wrote small benchmark app to demonstrate difference between “Sweep and prune” and “Quad tree”. <a href="https://github.com/ASGAlex/flame_quad_tree/tree/main/example">You can to try it here</a>. It uses Quad Tree from external library, still not refactored and merged into “main”. But it does not matter, if there is some difference in performance — it would be absolutely small.</p><p>At this example you can compare performance in 3 modes:</p><ol><li>Standard Flame’s “Sweep” algorithm</li><li>New “Quad Tree” algorithm</li><li>New “Quad Tree” algorithm with avoiding of unnecessary “updateTree” and “renderTree” calls</li></ol><p>Here is what I saw in first mode, with “TestGameStandard” launched:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsOSWwIn_XZwuokSjXVEng.png" /><figcaption>D means disappointment</figcaption></figure><p>Very disappointing picture. The most of application time is spend on calculating collisions, and this can not pe playable at all.</p><p>Let’s change “TestGameStandard” to “TestGameQuadTree” but let’s additionally remove the mixin “UpdateOnce” from “Brick” class. Most probably you would see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYvLea-yqwJgBqk-fq0YEQ.png" /><figcaption>Nice but still not ideal.</figcaption></figure><p>Well, new collision system works 2x faster than “Sweep”! But we still did not achieve our goal: at least 60 FPS. What’s a problem?</p><p>As we can see at CPU Flame Chart, collision detection system does not spend so much time as before, and it reveals for us another bottleneck: useless “updateTree” calls. If you would explore this example, you will notice that it does not render every Brick individually. Instead, Bricks are pre-rendered into “LayerComponent” and this cached picture is displayed every game tick. Brick’s state is never changed. So, what actually does updateTree then? Nothing. It just spends our recources, running unnecesary loops and calling functions withought any real effect.</p><p>Well, let’s bring “UpdateOnce” mixin back into its place at Brick class. And launch example at this mode. The result should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUEkC-zNrTHV9fO1zjVjyA.png" /><figcaption>This is how a “success” looks like</figcaption></figure><p>Congratulations, we got it!</p><p>This is more precise benchmark results for better evaluation of effectivity of every used solution:</p><p><strong>Microseconds spend on “update()”:</strong></p><ul><li>with “Sweep and Prune”: average 80 000</li><li>with “Quad Tree”: average 2500</li></ul><p><strong>Objects pairs which are potentially collided:</strong></p><ul><li>with “Sweep and Prune”: 19–150</li><li>with “Quad Tree”: 13–60, and 0 with additional check of minimal distance.</li></ul><p>As we can see, “Quad Tree” is faster than “Sweep and prune” and works a bit more effective. However, unnecessary updateTree() calls are your another greatest enemy. Combining these two approaches we reached <strong>32 times performance improvement!</strong></p><h3>Problems</h3><p>You might to think that this algorithm is something like “silver bullet” for collision performance problem. But this would not be a truth.</p><p>Here is a list of problems:</p><p><strong>1. Quadrants recursive searching. </strong>We can not just check one quadrant. Some objects are “on edge” between quadrants, it means that we should check wider range of objects. Let’s look at following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*NLlP2d75nKOxK3z2NVEKMg.png" /></figure><p>Objects, marked by red lines, are “objects on the edge”, such objects belong to multiple quadrants. It makes us to gather objects from “parent” quadrants. In worst cause collision check could be performed between target object and all objects on the map.</p><p><strong>2. We should know game field size.</strong> If you game field will grow up dynamically, you will need to clear all QuadTree and rebuild it from scratch, again and again. This operation isn’t cheap.</p><p>So, QuadTree still is very basic and general optimization approach. It just increases possible amount of collideable game objects, but it is still limited.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c212404b0b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Flame: simplest optimization techniques]]></title>
            <link>https://asgalex.medium.com/flutter-flame-simplest-optimization-techniques-372dbe6815f?source=rss-6226a9368ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/372dbe6815f</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[flutter-game]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Alexey Volkov]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 01:20:12 GMT</pubDate>
            <atom:updated>2022-08-25T01:45:01.384Z</atom:updated>
            <content:encoded><![CDATA[<p>I described some problems of Bonfire <a href="https://asgalex.medium.com/flutter-games-exploring-bonfire-1190938f3020">in my previous article</a> and argued, why it might be bad choice for you new game. Despite “vanilla Flame” is much more lightweight, it also does not provide enough performance. So now I try to share some my recipes of performance tuning of flame-game and describe reasons why it ever works.</p><h3>General optimization strategy</h3><p>Talking about game’s speed we look at FPS firstly. It is first and easiest measurable parameter, most of people looks on it to make decisions. That’s why I want to take a closer look on it’s nature (again!) and tell that in Flutter it is a bit more complex that “rendering speed”. In Flutter and Flame FPS is calculated from “game logic layer” and does not show your graphical adapter’s speed, but the CPU’s performance. So, if we have any problems, we should take a look on our game logic — this literally means “<em>updateTree()</em>” and “<em>renderTree()</em>” functions. If these functions will to calculate game logic too slow, the graphical layer will receive updates rarely and we will see “slideshow” instead smooth animations. Another important thing is that not only your’s game code would be problem-maker. Do not hesitate to look into framework’s source code to find a roots of your problem. It might be very helpful to explore library’s sources to locate you own mistake and fix it.</p><p><strong>So, our general approach will be reducing “updateTree” and “renderTree” time.</strong> Let’s look in details, what exactly does it mean.</p><h3>Optimization methods</h3><p>One of the easiest ways to make you app faster is to reduce its computations and cache results of repeating ones. And one of the sources of such computations is our game map, loaded and rendered through the library “<a href="https://pub.dev/packages/flame_tiled">flame_tiled</a>”.</p><h4>Map rendering optimization</h4><p><strong>1. Speed up the render of static layers</strong></p><p>“flame_tiled” renders tiles using <a href="https://pub.dev/documentation/flame/latest/sprite/SpriteBatch-class.html">SpriteBatch</a> and <em>Canvas.drawAtlas</em>. This approach is faster than rendering each tile individually but it still not very effective. It still performs repeating computations on every tile: searching for corresponding image rectangle, its position and angle on destination surface, rite all commands into batch. And then on every frame it runs saved batch to generate static map image.</p><p>But why not to perform it operation just once? We could create and run a batch while loading a map and just save resulting image into “Image” class.</p><p>This can be implemented very easily:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5814cbe5c12c90ce040bdc658e93977/href">https://medium.com/media/a5814cbe5c12c90ce040bdc658e93977/href</a></iframe><p>Simple yet effective. If you map is small, most probably you would not notice any changes, but than more the map become than more resources you save.</p><p>This solution is very basic but we will use it as a core for more complex optimizations.</p><p><strong>2. Speed up rendering of animated tiles</strong></p><p>Some tiles are not statical. And most probably a set of animated tiles would have such features:</p><ol><li>The map would have many animated objects of similar type, spread on different map’s zones or grouped. For example, rivers, lakes, sands, lava, torches on walls and so on.</li><li>Every class of such tiles might have its own animation, one for every type.</li><li>Animation’s frames might be played synchronically for objects group, starting at same time and switching frames simultaneously.</li></ol><p>If you have exactly same case, and such animated objects are relatively large, it would be worth to spend your time to join separate animations into one big <em>SpriteAnimation </em>component. Why it would be better? Firstly, we draw a big static picture only once instead creating it from small puzzle every time — like in previous optimization example. And at second, it is too expensive to handle a lot of identical <em>SpriteAnimation </em>component if we really need just one. Every new animated tile will do “<em>updateTree()</em>” call and waste our processor’s time to calculate already calculated animation values.</p><h4>Add new components faster</h4><p>In Flame every component has “<em>priority</em>” property which allows to determine object’s “z-index”: what to display at top and what at bottom.</p><p>Suppose you map contains earth, water and trees. Earth is most bottom, water is upper, then we draw player, and at top of all — trees, to hide players under them.</p><p>To achieve this behavior, you should to specify “<em>priority</em>” value for each game entity. And everything should work fine while you have constant number of in-game objects. But suppose you have 20 players or NPCs and every player/NPC firing a lot of bullets. Every bullet is additional object and provides its own “<em>priority</em>”. Every bullet lives just several seconds and then disappears — after timeout or after hitting the target.</p><p>What happens inside of engine?</p><ol><li>Every new bullet has own “<em>priority</em>” value.</li><li>Flame figures out that it needs to redraw set of components according to its “priority” value. Flame marks parent component of bullet to be recalculated</li><li>At next “<em>update()</em>” call Flame will work under all child components of marked parent and resort them according to new “<em>priority</em>” values.</li></ol><p>It seems to me that the reason of non-effectivity is obvious. When adding new objects directly to <em>FlameGame </em>we force engine to sort all game objects. But recalculating all objects is not necessary, all we need is recalculation of limited set inside layer. Steps to achieve this:</p><ol><li>Create components-layers for each class of objects: ground, water, players, trees, bullets…. Add these components directly into <em>FlameGame</em>. Specify corresponding “<em>priority</em>” for every layer.</li><li>New components of every type should be added to corresponding layer. New component will inherit parent’s priority, you do not need to specify it anymore.</li></ol><p>With this approach Flame will not recalculate priority for all components tree. If you add a new bullet, Flame will recalculate only components from bullets layer.</p><h4>Avoid feature-rich components when you do not need them</h4><p>Keep in mind that any component except basic “Component” class contains any update or render logic. If you have component with extended functionality, but use only basics — check its source code, it might be worth to downgrade component to simpler one or to reimplement any of its expensive methods.</p><p>For example, suppose you need to hide PositionComponent or use it as utility class. Let’s check its renderTree function then. You will see that it contains vary expensive <em>canvas.save()</em>, <em>canvas.transform()</em> and <em>canvas.restore()</em> functions, which will be called anyway, no matter do you have any code in <em>render()</em> or not.</p><p>So, I urge to review all your code and additionally review how external libraries work. Unfortunately, Flame is not so optimized that you can to forget everything except your game’s logic.</p><h3>Useful tools</h3><p>To make things easier I made a small library: <a href="https://pub.dev/packages/flame_tiled_utils">flame_tiled_utils</a>.</p><p>How to use it?</p><p>At first, load the map as you usually do:</p><pre>final tiledComponent = await TiledComponent.load(mapFile, Vector2.all(8));</pre><p>After it, call special class to merge statical layers into single sprite component:</p><pre>final imageCompiler = ImageBatchCompiler();</pre><pre>final ground = await imageCompiler.compileMapLayer(tileMap: tiledComponent.tileMap, layerNames: [&#39;ground&#39;]);</pre><pre>ground.priority = 10;</pre><pre>add(ground);</pre><p>Done! We just made map rendering mush more effective.</p><p>Now let’s optimize animated tiles. Look at this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0721023501b9741c04636bcafd18a0c/href">https://medium.com/media/c0721023501b9741c04636bcafd18a0c/href</a></iframe><p><strong>TileProcessor</strong> helps you to convert every tile to your custom object, mapping it by “Type” in Tiled editor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*4uHypykhpfbcDq0drH2eKQ.png" /></figure><p>With <em>TileProcessor </em>we can get tile’s sprite, animation and collision area. I’d prefer to see such functionality in Flame itself, but it is disappointingly absent. With <em>TileProcessor </em>we collect animated tiles into <em>AnimationBatchCompiler </em>class. Then we call “<em>compile()</em>” method which make one animated component instead hundreds. Isn’t it a cool?</p><h4>Benchmarks</h4><p>I wrote small <a href="https://github.com/ASGAlex/flame_tiled_utils/tree/main/example">example app</a> to compare FPS in three modes:</p><ol><li>With flutter build-in API (which do not allow animations)</li><li>Optimized map rendering except animated layer: every tile is displayed as individual component (like Bonfire does)</li><li>Fully optimized variant</li></ol><p>To make the difference more noticeable, I made relatively big map, 300x300 tiles, 8px every tile.</p><p>Here are results in vanilla mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUstnMENEPx677-IyGrRSw.png" /><figcaption>19 FPS</figcaption></figure><p>Not fine but still usable. But here we have no animations because flame_tiled does not work with them.</p><p>Here is benchmark of second mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOYHcPwM3Xswq-zkvcX-zg.png" /><figcaption>4 FPS</figcaption></figure><p>As we can see, it is totally unusable, because processing individual animation for every tile is very expensive. Unfortunately, it is exactly how Bonfire works with animated maps, so you can not expect fine performance from it unless you map is small enough.</p><p>And finally, benchmark of optimized render:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZBJtBjFXkwreBNptewiuA.png" /><figcaption>58–60 FPS</figcaption></figure><p>Shall I to comment anything here?</p><h3>Conclusion</h3><p>As we can see, not every “ready-made” solution can offer you the best functionality. Flutter is very new in gaming; engines are too young and many aspects needs optimization and even realization from scratch.</p><p>Are all available optimization methods listed in this article? Definitely no, it is just beginning. In real game you have a lot of mechanics, graphical effects, game objects, collisions… and just few milliseconds for computations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=372dbe6815f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart as a backend: real experience]]></title>
            <link>https://asgalex.medium.com/dart-as-a-backend-real-experience-9e27f133b2cf?source=rss-6226a9368ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e27f133b2cf</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Alexey Volkov]]></dc:creator>
            <pubDate>Mon, 15 Aug 2022 15:11:44 GMT</pubDate>
            <atom:updated>2022-08-15T15:11:44.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*9zrf_vJaaYv4QS04FvGROg.png" /></figure><h3>Prolog</h3><p>Dart is awesome language which going to be multi-purpose like Python is. It can work on every platform without significant changes, it can use relatively-native components and interact with external libraries using “ffi”. Sounds too cool to be true maybe? I tried to check it last year and here is my experience, feelings and thoughts.</p><p>I planned to write a telegram-bot and a REST server for my pet project — a cooperative card game, a mix of RPG and story-telling. Cards are like random events and should be picked by the player. I thought to write client-agnostic server to bring a random card for the player.</p><h3>Tools and libraries</h3><p>As experienced PHP developer I expect a number of build-in functions from every REST-ready framework:</p><ul><li>Flexible routing system</li><li>Native JSON support</li><li>Configurable validation rules</li><li>Mapping JSON to objects and vice-versa</li></ul><p>Also, it is common thing for a backend developer to have nice build-in support of any relational SQL database for persistent data storage and any in-memory database for caching.</p><p>So, my first step was to find something from this list in Dart’s ecosystem. Here are results of my research.</p><p><strong>Databases.</strong></p><p>For basic MySQL support I found <strong>Mysql1</strong> package (<a href="https://pub.dev/packages/mysql1">https://pub.dev/packages/mysql1</a>). Sadly, this library does not provide full MySQL support. If you habit to use powerful ORM solutions — you will be rather disappointed. With this library you will be able to write only raw SQL requests without any significant abstraction level. But I have met problems even with this basic functionality: the library has lack of data types support; in my case it was BLOB. Such data columns are simply ignored in SELECT requests.</p><p>Another problem of this library was speed and working asynchronically with rest of dart code. Many times I catch unexpected exceptions and waited too long while a simple request would be processed.</p><p>So, this MySQL library was (and is) generally not for production use. And there is not any perspective that situation would be changed soon: just look at the library’s changelog, where the distance between minor fixes is about a year!</p><p>I see that now there is a “successor” of <strong>mysql1</strong> — <strong>mysql_client</strong> (<a href="https://pub.dev/packages/mysql_client">https://pub.dev/packages/mysql_client</a>). I did not test it and have not plans to, but look to it’s changelog: it also is… at deep alpha I suppose.</p><p>Of course, there are alternatives with Postgres, where you have even 2 actively maintained libraries: <strong>postgresql2</strong> (<a href="https://pub.dev/packages/postgresql2">https://pub.dev/packages/postgresql2</a>) and <strong>postgres</strong> (<a href="https://pub.dev/packages/postgres">https://pub.dev/packages/postgres</a>).</p><p>Similar situation is with in-memory storage. In backend development I usually choose Redis because it is simple enough for any team member, it can automatically remove outdated data and it can save data on hard drive when there is not enough of memory.</p><p>It the moment of working under my application I have found <strong>Dartis</strong> library (<a href="https://pub.dev/packages/dartis">https://pub.dev/packages/dartis</a>). It worked perfectly, but looks like discontinued. And now it is approximately 2 years passed from last update!</p><p><strong>Dartis</strong> also have alternative: <strong>Redis</strong> (<a href="https://pub.dev/packages/redis">https://pub.dev/packages/redis</a>). It looks like being still alive but who dare to predict the future whereas so many libraries were partially done, become popular and successful and was abandoned after all?</p><p>Finally, I found a compromise solution: <strong>Parse server</strong> with it’s SDK (<a href="https://pub.dev/packages/parse_server_sdk">https://pub.dev/packages/parse_server_sdk</a>). This is not a database itself, but it has SQL database underneath. Also, it is not an unique service hosted by any corporation, like Firebase is — I don’t like such solution because I want to be free to migrate to my own hardware.</p><p>So, despite of fact that I found necessary toolset, I think this case in not success: a very popular database for backend is barely supported yet, and you have no confidence with existing and actively maintained libraries: how long would it be alive? I wiped out any Redis support from my project to avoid an “legacy” dependency at future. It means that I need to save all runtime data at application’s variables, that mean possibility of partial data loss between “points” where data is saved into Parse server (which is slow operation to perform it too often). Well, I thing it would be disaster for real-life business application in production. Too sad that you have not an easy way and tool to solve this.</p><p><strong>Requests handling.</strong></p><p>The second core part of server application is how it works with requests, parse incoming data and how fast and flexible newborn API could be.</p><p>Here I should notice that writing APIs today is much more important part for backend developer than integrating markup, writing parsers and so on. PHP is not Wordpress, right? So, looking at Dart I dreamed about some powerful and flexible tool like Laravel/Lumen/Symfony…</p><p>Firstly, I found Aqueduct. I even tried it — it works really fast on local machine, spawning multiple isolates for parallel requests handling. But again, a typical disappointment: the library is abandoned, the code even does not support null-safety.</p><p>I also googled several small libraries aimed to reproduce some features from more mature frameworks, but finally I put my eye on <strong>Shelf</strong> (<a href="https://pub.dev/packages/shelf">https://pub.dev/packages/shelf</a>) — it seems to be well-supported library and most probably it would not be abandoned at future. The second reason was that its library is used by <a href="https://datagrok.io/">https://datagrok.ai</a> — a serious and complex service, written fully on Dart, both frontend and backend.</p><p>So, what are my impressions about shelf after PHP development? Its functionality is very minimal. You should care about everything: how to implement desired routes, how to read requests from raw data to JSON and then how to validate it and how to convert into objects… Some of those tasks could be solved by using external library (hopefully would not be abandoned at future), but I decided again not to rely on it.</p><p>In other hand, Dart allows to write short and clean code so I think I made nice solution and even enjoyed by the process. Here is the code: <a href="https://github.com/litgame/rest-server/tree/main/lib/service/api">https://github.com/litgame/rest-server/tree/main/lib/service/api</a> Validators, controllers, actions… I felt myself like I creating a fork of Yii2 on Dart. Should you every time do it in you work, should you invent a new unique framework for every yours’s project again and again? Definitely not. But with pure Dart’s ecosystem you need to.</p><h3>Client application</h3><p>I planned to create three clients for the game:</p><ol><li>Telegram bot</li><li>Android application</li><li>Web build of Android application</li></ol><p>Because this article is focused on backend, I going to tell only about telegram bot.</p><p>There is awesome library: <strong>TeleDart</strong> (<a href="https://pub.dev/packages/teledart">https://pub.dev/packages/teledart</a>). It supports a lot of features and well-maintained. The library works either in long-polling mode and in web-hook mode. It also is friendly for inventors like me, who tries to create a complex framework to solve tasks gracefully.</p><p>The client is much more complex application than server: it should interact with user, build interfaces, send messages, validate input and so on. Also, it stores much more information about game’s state and should keep it in sync with server. Looking at server application, I was absolutely sure that there would not be any memory leak or slow operation. But I was not so sure about the bot application. So, I performed a little check.</p><h4>Stress test: stability and memory consumption</h4><p>I implemented the bot using “long-polling” approach. This means that it could not be actually “highload” because the bot takes a fixed number of messages from queue, it does not matter how much messages still pending. As result, the REST server would not be “highload” too. Additionally, if we talking about performance testing, we should to have something to compare with, but I’m not ready to implement all mechanics twice, on PHP or node.js…</p><p>That’s why we will focus only on memory consumption. Firstly, here are data from TICK monitoring on production server after two months of uptime:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YM9jBm75GZzlOgoWLGTwFQ.png" /></figure><p>As we can see, memory consumption stays in fixed bounds. The fall on top graph most probably was triggered by rebuilding and restarting the docker container of the bot. But in most causes telegram bot need only 60–70 megabytes of memory.</p><p>The “ladder” at bottom graph is rest-server’s data. It is much lighter and consumes less memory and here you can see how garbage collector (GC) works: GC does not attempt to clean the memory unless there were too high change of consumption.</p><p>To illustrate GC work more clearly, I created a fake telegram-server which started 100 games with 5 players simultaneously. Virtual players played a bit and then all games had been finished. My expectations were that GC should be started after finishing all games (when a lot of clear() functions are called)</p><p>Here is the graph from DevTools Memory Page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEk_ZxDjopVYlaQGoEeltw.png" /></figure><p>Let’s see at selected position on timeline. In first implementation of stress-test all games had been finished at this position, but GC did not call, memory stayed full of dead data. Looking at this I decided to make “second pass”: to start new test just after previous. This led the application to allocate more memory, consumption become too high and GC was called.</p><p>It evidently illustrates that RAM would not be freed after some memory expensive operations. Service already would not be under load, but will consume resources. And only another “highload session” will trigger GC to free memory… to consume it again immediately.</p><p>Is it good or bad? Depends on point of view. For server-side applications working concurrently on resource-limited server it is not nice behavior. There is no any memory leak, of course. But resources are consumed whereas service do not need them really. But any other service at this machine could be starving for memory. You can’t to control memory consumption manually. You can’t call GC from production code. You can only hope that your machine has enough memory and there is no another service pretending on it.</p><p>GC behavior is not constant, it changes from time to time, may be depending on other processes launched on the machine. For example, I started test again and found memory graph a bit different from previous launch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rk3gBB_4GNs8QnFllaCAMQ.png" /></figure><p>The picture is similar for REST server. But this application is much lighter itself and GC triggers very rarely. You can see again, how the application holds a lot of memory without using it. I waited a long time, if GC will come, but hopeless… After all, I triggered GC manually from DevTools and you can see how much memory become freed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjVtyZyg3M0Aq70UdqICsg.png" /></figure><p>Here is memory snapshot before manual GC call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*_ydyHh573B9fvO1u9vVavQ.png" /></figure><p>Highlighted entities are not used already, but Dart still keeps it in memory. All these entities disappearing after manual GC triggering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*2wJcLc_7t7b30nb6wNF3Lg.png" /></figure><p>Two highlighted entities are not a memory leak. These were specially cached.</p><h3>Conclusion</h3><p>After all, here is my personal opinion about writing a server application on Dart:</p><ol><li>You will be limited by libraries, tools and framework functionality.</li><li>You also should examine carefully every package you going to use. Because a lot of libraries are unsupported or provide very minimal functionality.</li><li>Keep in mind that even very popular library might be discontinued. It is true for all opensource of cause, but especially for Dart ecosystem at back-end.</li><li>Your application should be very-very simple. In other cause you’ll have to reinvent a lot of bicycles. Maybe you like to. But perhaps you time is worth more?</li><li>GC is not fine for long-running server-side daemons.</li><li>You should implement multi-threaded requests handling yourself. The Dart could be super-fast at single process but every production service could be super-loaded. In PHP world it usually solved by CGI manager. In Dart… the Aqueduct is abandoned and I did not find any other solution which would care about that. So, you might choose a very fast programming language and create a very slow application on it 😊</li></ol><p>Of cause, the Dart is awesome technology, I really like it. But let’s be honest and objective. Every modern application does not consist of programming language only. Modern applications consist of ecosystem around programming language, and ecosystem is exactly what makes a language powerful and useful. With pure ecosystem even most powerful language become weak and produce problems and challenges. Sadly, this is exactly what’s happens with Dart on server now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e27f133b2cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter & games: exploring Bonfire]]></title>
            <link>https://asgalex.medium.com/flutter-games-exploring-bonfire-1190938f3020?source=rss-6226a9368ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1190938f3020</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-performance]]></category>
            <dc:creator><![CDATA[Alexey Volkov]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 21:31:14 GMT</pubDate>
            <atom:updated>2022-07-10T00:50:56.026Z</atom:updated>
            <content:encoded><![CDATA[<p>The new toolkit “<a href="https://flutter.dev/games">Flutter Casual Gmes Toolkit</a>” had been announced with Flutter 3.0. It does not pretend to be an universal solution for any issue, but we see how was made the first “official” step toward games development.</p><p>There are other instruments and the most powerful of them is Flame framework. And on top of the Flame is built “<a href="https://bonfire-engine.github.io/">Bonfire</a>” — a game development framework. It looks the easiest framework for developing RPG games at least.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*-TmIzGdq6-pELSdOKZufVw.png" /></figure><p>In this article I want to share my experience with Bonfire and show its good and dark sides… I hope my article would be helpful if you still not sure about framework to use in you first game project.</p><h3>First look</h3><p>The Bonfire’s author has made a lot of documentation, added a numerous of well-done examples and also recorded some video tutorials (unfortunately not in English).</p><p>Let’s summarize the framework key functionality in the short list:</p><ol><li>Ready control layer: keyboard and virtual gamepad support.</li><li>Entities “Player”, “Enemy”, “Follower” are ready to use.</li><li>Entity for creating “flying attack objects” such as bullets. Melee attack mechanics.</li><li>Mixins and functions to implement NPC’s movement towards the player to attack him.</li><li>Pathfinding for player’s character to the point on the screen you had clicked by mouse.</li><li>Tiled map editor support, animated tiles, collisions with tiles, reading tiles properties. Placing tiles on different levels of height.</li><li>Mapping objects defined in Tiled into classes in Dart to implement custom behavior.</li><li>Lighting, full screen color effects.</li><li>Smooth camera moving.</li><li>User interface, dialogs.</li><li>Mini map.</li><li>…maybe something else I missed or was implemented while I preparing this article.</li></ol><p>The toolkit looks very cool, right? Really, the framework allows us to build most of the game just in Tiled, to set up all required parameters using object’s properties, to read them later in you code and implement missing game logic in custom classes by inheriting predefined entities.</p><p>After setting up a project everything is really clean and evident: we have a game object, objects have callbacks to receive damage, to handle collisions with other objects, functions to be called on movement and so on. You have everything, just go to implement your idea! And I tried to do so…</p><h3>Our experimental game</h3><p>I decided not to do yet another RPG game: at first because I didn’t have any an inspirational idea; at second because with Bonfire it would be too easy, you will do about 80% of work in Tiled. It is not what you need when you want to explore the framework, it’s abilities and bounds.</p><p>Do you remember an old game, “Battle City 1990”? On the dark background with buildings made of bricks your tank protects “eagle” from other tanks and bricks are destroyable. If at that “ancient” times people was able to create such game, it should be very easy to implement the same with all power of modern toolkits! Isn’t it? Really?..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*3YIAPWR4pUw4vHTCUBW4nA.png" /><figcaption>How it was in original game</figcaption></figure><h3>1. Controller</h3><p>With the framework we have bundled class to configure game controller — virtual joystick for mobile devices and WASD for desktop. But in my cause movement should be allowed only in 4th directions. In Bonfire movement is available in every direction, so we need to cut unnecessary functionality. Here I haven’t any another solution but just to copy-paste and rewrite contents of whole mixin “<em>MovementByDirection</em>”. It is not good practice, but still “ok” — just one complete reimplemented entity, not a problem! Let’s go forward…</p><h3>2. Ready entity Enemy</h3><p>Here we facing the similar situation: we need to bound NPC for 4-directional movement. At this situation we needn’t to copy-paste anything, but to implement desired behavior you should be familiar with Bonfire’s function call order: when you should use “<em>update()</em>”, how it differs from “<em>onMove()</em>” and what is “<em>moveLeft</em>”, “<em>moveRight</em>” and so on. It is not a problem to learn internal framework structure, deep class/mixins hierarchy, etc, but it is not something you could call “easy” or “intuitive”. Here is the place where Bonfire began to show you its complexity.</p><h3>3. Ready entities for bullets, damage taking and receiving</h3><p>Here is the first place we meet a conflict between functionality implemented in Bonfire and functionality required to implement game mechanics.</p><p>In Bonfire a bullet is implemented through class “<em>FlyingAttackObject</em>”. It explodes at moment on collision with any game component (of cause if it has any information about collisions). Damage is received only by objects of “<em>Attackable</em>” type. Looks useful. Let’s compare with “Battletank” original game mechanics:</p><ol><li>There are tanks, which receive damage. Standard Bonfire’s mechanics should work nice here.</li><li>There are destructible bricks, and I have no idea how to use Bonfire’s mechanics here without modification, because bricks are not disappearing after first hit — only a part of brick should be deleted.</li><li>Finally, we have water on a map. Water tiles should be collidable because tanks can’t swim, but a bullet should fly freely above water.</li></ol><p>How should we solve this problem? I decided to use the following approach:</p><ol><li>There is everything OK with tanks, let’s keep standard mechanics.</li><li>For walls — the first idea was to build the map by small tiles, but it means a lot of crazy handwork because the smallest tile size is 4px. Also, it would be ineffective to process so many tile objects by engine. Then I chose another approach: when a bullet hits a wall, we calculate bullet’s flight vector and shrinks the tile’s size in this direction for half of tile’s full size. If the size is zero the tile should be removed. The solution works fine but all standard mechanics from “<em>onCollision()</em>” function should be rewritten from scratch.</li><li>Water. Here we need to rewrite “<em>onCollision()</em>” function of Bullet class again to ignore collision with water.</li></ol><p>This does not look too complex, but one difficulty calls another one: Bonfire does not see any difference between tiles of different types. To make the engine to see that water is water and brick is brick we should do some additional work in its core… I’ll describe it at part 7.</p><h3>4 and 5. Enemy’s movement towards player. Pathfinding.</h3><p>At this point all framework’s “out of the box” solutions become useless. Enemy’s movement is possible only in 4th directions. Also, there are a lot of obstacles that need to be quite accurately bypassed in order to get somewhere purposefully.</p><p>Bundled pathfinding has surprised, too. Firstly, it is implemented only for Player. For any another game object you should implement everything yourself. Bonfire’s author used third-party package <a href="https://pub.dev/packages/a_star_algorithm">https://pub.dev/packages/a_star_algorithm</a> and it is simple enough to use it directly, without additional framework interface. But then we face with other problem: if the map has complex relief and distance between points is long the algorithm slows down whole game and we see low FPS. All operations are single-threaded, so the more tanks are on the display it will be the slower the game will be. That’s why I finally stopped on simple algorithm of random movement and changing direction on corners, plus firing when player is on the line of sight. It is not exactly what I want to do, but still more clever behavior than in original game.</p><h3>6. Tiled support, different height levels for game objects.</h3><p>I’ve already mentioned the Tiled maps support. Now let’s describe what I mean about object’s height. Sometimes one kind of objects should be rendered above another. For example, imagine a dungeon from an RPG game and a torch or cornice there. These objects are higher than player stays on the floor, so it should be drawn above the player when he moves under them.</p><p>In the Flame we have a special parameter to control this: “priority” property of the game object. It is integer, the higher it is, the higher corresponding object is placed. It was surprisingly that Bonfire does not allow you to use this functionality! The only way you could do to influence on object’s placement height by to specifying “above” as a tile type of name in Tiled editor. With “above” this tile will be rendered above all the objects in the game. I also found a new type “dynamicAbove” in the last commits, but it seems there is no way to control the “priority” directly.</p><p>Bonfire takes a full control over “priority” because it is oriented on games, where camera is placed at 45 or 70 degrees. It does not simple watching vertically from top to bottom. Thus, one object potentially could overlap another one just only because it is lower on Y axis. Maybe the author will extend the framework to allow the uss of multiple height levels, but right now all available levels are hardcoded in the “LayerPriority” class and the only way to add your own layer is to edit the framework’s code.</p><p>Why did I even start to explore this? In the original game background is just a simple dark color and after destruction walls simply disappear. I decided to add a ground texture instead of dark background and add ash texture in place of destructed wall. Thus, ash should be placed upper than ground but lower than any other game objects. Unfortunately, I didn’t have any tool to achieve this goal and finally I forked the framework and added a desired logic directly into it.</p><p>It’s not good news when you expected just simple using of ready “out-of-the-box” solution.</p><h3>7. Mapping objects and tiles from map into custom classes in Dart</h3><p>This was next part required to be rewritten to achieve my goals.</p><p>I was surprised the Bonfire does not allow to see differences between tiles for framework’s user. This feature is available only for Tiled “objects”, but it’s very different entity then “tile”. Tiled “object” have no sprite or animation, it only could be positioned and resized on the map. Simplest description is than “objects” are just squares on map with individual names. So, my expectations that it is possible to create separate class to handle “brick” tiles in the Bonfire were not met. In fact, Bonfire’s logic is as follows:</p><ul><li>All objects, intended to be interactive in game, should be created in Tiled as “object” entity. Objects can be transformed into custom class while map loading, but you should manually do sprite or animation loading.</li><li>All environment objects like walls, floor, non-interactive decorations should be created as tiles. But you can specify that some tiles should be collideable though.</li></ul><p>You can see this in documentation and tutorials. First time it was the cause of my bewilderment, why does the author not map tiles directly in desired class, but as you can see this functionality hasn’t been implemented yet.</p><p>In my cause this functionality was critical because:</p><ul><li>I need to know the tile type while processing bullet’s game logic: to differ water’s tiles from brick’s tiles.</li><li>I need to control every brick tile to shrink its size in case of hitting by a bullet.</li><li>Finally, I want to implement additional mechanics: allow player to hide in the forest, becoming invisible for computer enemy.</li></ul><p>So, if stay limited to Bonfire’s build-in functionality, we probably should draw additional layer of objects above tiles layer. This looks much more difficult handwork then exploring and modifying framework’s source code.</p><p>Finally, I implemented additional builders — “tileBuilder” and “decorationBuilder”. Along with built-in “objectBuilder” it becomes possible to create every required class for any Tiled object. Here is my code example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*TWhTG90jLs-70MdKHg0l3g.png" /><figcaption>Now every Brick or Tree have own class with custom behavior</figcaption></figure><p>And a bulk on knowledge about internal Bonfire’s structure was an additional bonus… The bonus I wouldn’t like to achieve to…</p><h3>The biggest disappointment.</h3><p>At last, I had all necessary tools to implement a game logic — thanks to forking and deep modification of the framework.</p><p>And then I faced another surprise: the performance was around 20–30 FPS on desktop and just 12–15 FPS on mobile!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*AHfAxY3A9UrO4xn_jbPsfA.png" /><figcaption>6 enemies, a lake, a forest — and no performance</figcaption></figure><p>I began to explore the problem disabling every game logic I previously write, but FPS always was around 30. After that I tried to remove layers with collisions and decorative tiles. It had better effect, but still not 60 FPS. Finally, I disabled all graphics, players tank stands on absolutely black screen with tiny square of bricks around game field. Well, with such configuration 60 FPS was achieved. But only till you try to move or to fire or to spawn an enemy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjb1ospkOJ8Ukvdj0Z33yg.png" /></figure><p>“Maybe I forked anything wrong?” — I had thought and began to build and launch Bonfire’s demo apps. And — surprise-surprise! — it also works only at 30 FPS!!!</p><p>At this point I finished my attempts do to anything with framework or with the game written on this framework. Before abandon everything I look again into source code of Bonfire and compared it internal logic with Flame. And now I think I can show a list of reasons why Bonfire is so slow (and, I’m sure’ will be slow in future without any radical architecture changes):</p><h4>Background operations</h4><p>Nothing happens in the Flame in background unless you write your own logic in “update”. Only collisions would be calculated if you enabled it. That’s all.</p><p>In the Bonfire at least 3 background tasks are launched permanently:</p><ol><li>A loop through all game objects and determining not visible ones. Objects not in viewport would not be processed. I sure it is dubious solution: if we want to avoid unnecessary render — this is work the graphical engine should handle, and I believe it will do that much faster and more effective.</li><li>Another loop through all game objects to calculate every object’s “priority”. As I said at part 6, Bonfire calculates this parameter automatically to implement “angled camera” view. But implementation looks not optimized: for example, there would be additional layers with objects never overlaps each other. Or, for example, do not recalculate if positions did not change.</li><li>Collision detection. The author tried to optimize this by passing objects not currently in viewport. With this behavior you can easily find NPCs stuck inside textures or even out of the game field, because NPC can travel through walls while it is not visible on screen.</li></ol><p>All these operations generate constant background load on you game even if no line of custom game logic was written. The amount of load is just determined by number of objects you draw in the Tiled editor.</p><p>Background operations intervals (but all operations are in single thread):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*BFkYB4tMjjBjeUMCtuPrjA.png" /><figcaption>Intervals for calling background operations. But anyway it all in one thread</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*qeqDTtocrYiEhYrnvNsqEQ.png" /><figcaption>Corresponding functions calls</figcaption></figure><h4>Tile’s rendering</h4><p>Flame does not create any additional entities while rendering tiles. Tiles are not game objects and does not processed by game loop events. Flame uses <em>SpriteBatch </em>(<a href="https://pub.dev/documentation/flame/latest/sprite/SpriteBatch-class.html">https://pub.dev/documentation/flame/latest/sprite/SpriteBatch-class.html</a>) to optimize map rendering. It might be more optimized I think, but anyway it still faster than Bonfire’s approach.</p><p>Bonfire treats each tile as game object. For every tile Bonfire do calculations, does the tile visible or not? Every tile potentially could contain collisions so every tile is also checked for this. And finally, the “priority” parameter calculated for every tile too. It is rather expensive.</p><h4>Collision handling.</h4><p>Flame divides all collision objects on two categories:</p><ol><li>Passive objects, like walls. Such objects simple spay on its place and does not collide each other.</li><li>Active objects, like player, bullets or enemies. Such objects actively move, it can collide between each other and also with passive objects.</li></ol><p>Such approach allows to reduce computation time for passive objects. I’m sure passive objects is a main component of most of typical game maps.</p><p>In Bonfire case there is no difference between object type. Every object is equal, every is calculated. The system would check and report you every time about collision ow two static walls — the information you newer need to (most probably). Additional overhead is Bonfire’s movement system. On each “<em>update()</em>” call for moving object Bonfire virtually move the object to its position at next tick and do additional collision calculations. As result, the system become slower the more moving objects you add.</p><p>Do not forget that everything is calculated on single thread, no additional “isolates” used here — so resuorces are very limited.</p><h4>Loading animations.</h4><p>This is probably most harmless problem, but anyway. In Bonfire most of animations always created from scratch: you pass the file name, framework cuts image and makes separate frames from it… Only image itself is cached but it would be useful to cache prepared frames too. I think, this approach potentially can lead to short “freezes” in moments when a new animation should be created.</p><h3>Resume.</h3><p>My own decision is not to use Bonfire at all. Firstly, I thought it might be useful if you fork it and rewrite its internal logic for your game purposes. But such performance bottlenecks are very disappointing.</p><p>Nonetheless, there are still a lot of useful things you could take from Bonfire to your project. A joystick component for example. Or fullscreen animated color filter. But you should be careful and always analyze what you going to copy.</p><p>Does Bonfire have a chance to overcome these problems? I think there is no evolutional way. Too many code already written, there is a lot of dependencies between different parts of system and very radical changes required to make engine more performant and flexible. Even if the author decides to rework everything, it already will be completely another framework.</p><p>Finally, do Bonfire really have its application area? I believe, you could use it if you project is not complex: small map, low number of objects on it, easy game logic. If you know that 90% of work could be made in Tiled — Bonfire is definitely your choice!</p><p>Would the Flame itself be more performant? Definitely yes! But do not expect that if you create thousands of objects the engine will process them easily. This mistake will lead you to Bonfire’s performance problems.</p><p>If you really want to make you Flutter game faster, even with Flame you need to develop special optimizations, suitable for you game mechanics. And I already have a number of nice recipes and strategies that really works! I looking forward to share it in my future article.</p><p>If somebody interested, here is the source csode of the project on which I experimented with Bonfire: <a href="https://github.com/ASGAlex/battletank_game">https://github.com/ASGAlex/battletank_game</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1190938f3020" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>