Jekyll2022-05-22T10:38:21+00:00http://seanballais.github.io/feed.xmlSean BallaisThe personal website and blog of Sean Ballais, a programmer and CS student from Tacloban City, Philippines.Computing Elapsed Time in SDL 22020-06-13T22:50:00+00:002020-06-13T22:50:00+00:00http://seanballais.github.io/blog/computing-elapsed-time-in-sdl2<p>Elapsed time is one of the fundamental aspects of games. It determines the time between two snapshots (i.e. frames) of a game, used in the physics subsystems, and a whole lot more. Computing the elapsed time incorrectly may lead to inaccurate simulations and/or unsatisfying gaming experiences. SDL 2, a cross-platform library used to build games, provides functions to help us compute our elapsed time.</p>
<p>The basic mechanism from SDL 2 that can be used for computing elapsed time is <code class="language-plaintext highlighter-rouge">SDL_GetTicks()</code>. This function returns the amount of time that has lapsed since the SDL library has been initialized in milliseconds. Note that <code class="language-plaintext highlighter-rouge">SDL_GetTicks()</code> returns an unsigned 32-bit integer. With this function, we can get the elapsed time in seconds through:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>uint32_t startTime = SDL_GetTicks();
// Do awesome stuff here, like figuring out if the girl at the bar you're in who
// glanced briefly at you and does a quick hair flip is into you. You actually
// really can't tell from this example since she could just be adjusting her
// hair, and looking at someone behind you.
uint32_t currTime = SDL_GetTicks();
double elapsedTime = (currTime - startTime) / 1000.0; // Convert to seconds.
</code></pre></div></div>
<p>I’m using seconds here since it’s the SI unit for time, and I find it easier to perform calculations with the unit (Thanks, PSHS-EVC, my high school, for drilling SI units into me!). This is should be enough for many cases, including computing for the elapsed time between frames. However, <code class="language-plaintext highlighter-rouge">SDL_GetTicks()</code> is not enough when you want higher precision times. Tasks like profiling will benefit from higher precision. For that, we have <code class="language-plaintext highlighter-rouge">SDL_GetPerformanceFrequency()</code> and <code class="language-plaintext highlighter-rouge">SDL_GetPerformanceCounter()</code>.</p>
<p><strong>Quick Aside</strong>: If you want to store a large amount of time, like the total running time of the game, do not use <code class="language-plaintext highlighter-rouge">float</code>. The precision of the <code class="language-plaintext highlighter-rouge">float</code> type decreases fast, especially compared to a <code class="language-plaintext highlighter-rouge">double</code>, as the value increases. Prefer using a <code class="language-plaintext highlighter-rouge">double</code> or an integer (if you want microsecond precision that would be viable for ~5,843.02 <strong>centuries</strong>, use a 64-bit unsigned integer) to store the time. <a href="https://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/">This blog post</a> by Bruce Dawson delves into the problem.</p>
<p><code class="language-plaintext highlighter-rouge">SDL_GetPerformanceCounter()</code> and <code class="language-plaintext highlighter-rouge">SDL_GetPerformanceFrequency()</code> gets the current value and frequency of the high resolution counter, which is a register present on modern CPUs, at least the x86 ones. We can get high precision timings from those two functions. Both functions return a 64-bit unsigned integer. Getting the elapsed is actually just similar to using <code class="language-plaintext highlighter-rouge">SDL_GetTicks()</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// Code based from here:
// https://gamedev.stackexchange.com/a/110831/93942
uint64_t startTime = SDL_GetPerformanceCounter();
// Do other awesome stuff, like converting between pixels in screen space and
// meters in physics world space. Here's an article to learn how to do that:
// https://seanballais.github.io/blog/box2d-and-the-pixel-per-meter-ratio/
uint64_t currTime = SDL_GetPerformanceCounter();
double elapsedTime = static_cast<double>(
(currTime - startTime) / static_cast<double>(SDL_GetPerformanceFrequency())
);
</code></pre></div></div>
<p>This should give us a high-precision elapsed time in seconds. A variation of this is actually what I use in my game engine. I previously struggled understanding this, so I’ll explain how this works. Performing <code class="language-plaintext highlighter-rouge">currTime - startTime</code> will give us the number of ticks there are between the two calls to <code class="language-plaintext highlighter-rouge">SDL_GetPerformanceCounter()</code>, which gets the current number of ticks there are on call to the function. Now, we have to convert those number of ticks to seconds. <code class="language-plaintext highlighter-rouge">SDL_GetPerformanceFrequency()</code> provides the number of ticks per second (i.e. the frequency). We can use that function to convert <code class="language-plaintext highlighter-rouge">currTime - startTime</code> into seconds. To convert to seconds, we just simply divide <code class="language-plaintext highlighter-rouge">currTime - startTime</code> by <code class="language-plaintext highlighter-rouge">SDL_GetPerformanceFrequency()</code>. We have to cast the latter to a <code class="language-plaintext highlighter-rouge">double</code> to prevent integer clamping, since both operands are integers. And that’s it! Here’s a little SI conversion to show that that division operation actually converts the number of ticks to seconds, where \(t_{1}\) represents <code class="language-plaintext highlighter-rouge">currTime</code>, \(t_{0}\) represents <code class="language-plaintext highlighter-rouge">startTime</code>, and \(n\) represents the number of ticks per second of the high resolution counter.:</p>
\[\begin{align}
\frac{(t_{1} - t_{0}) \text{ ticks}}{1} \cdot \frac{1 \text{ seconds}}{n \text{ ticks}} &= \frac{(t_{1} - t_{0}) \text{ }\cancel{\text{ticks}}}{1} \cdot \frac{1 \text{ seconds}}{n \text{ }\cancel{\text{ticks}}} \\
&= \frac{t_{1} - t_{0}}{1} \cdot \frac{1 \text{ seconds}}{n} \\
&= \frac{t_{1} - t_{0}}{n} \text{ seconds}
\end{align}\]
<p>We’ve just learned that SDL 2 provides functions to help us compute the elapsed time. Choosing which to use will depend on your use case. Actually, we can take this up a notch by creating a <code class="language-plaintext highlighter-rouge">Timer</code> class that will handle computing the elapsed time. But, that’s on you. At the very least, I hope this provides you with guidance with regards to computing the elapsed time.</p>
<h1 id="references-and-additional-readings">References and Additional Readings</h1>
<ul>
<li><a href="https://gamedev.stackexchange.com/q/110825/93942">c++ - How to calculate delta time with SDL? - Game Development Stack Exchange</a></li>
<li><a href="https://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/">Don’t Store That in a Float | Random ASCII - tech blog of Bruce Dawson</a></li>
<li><a href="https://wiki.libsdl.org/SDL_GetTicks">SDL_GetTicks - SDL Wiki’</a></li>
<li><a href="https://www.libsdl.org/">Simple DirectMedia Layer - Homepage</a></li>
<li><a href="https://bduvenhage.me/performance/2019/06/22/high-performance-timer.html">The High Performance Time-Stamp Counter | Bernardt Duvenhage’s Blog</a></li>
<li><a href="https://en.wikipedia.org/wiki/Time_Stamp_Counter">Time Stamp Counter - Wikipedia</a></li>
</ul>
<h1 id="credits">Credits</h1>
<p>Header image used is owned by Ansgar Koreng, obtained from <a href="https://wikipedia.org/">Wikipedia</a> (image is obtainable via this <a href="https://en.wikipedia.org/wiki/Stopwatch#/media/File:Stopwatch,_1810201155,_ako.jpg">link</a>), and used under the <a href="https://creativecommons.org/licenses/by-sa/4.0/legalcode">CC BY-SA 4.0</a>.</p>Sean Francis N. BallaisElapsed time is one of the fundamental aspects of games. It determines the time between two snapshots (i.e. frames) of a game, used in the physics subsystems, and a whole lot more. Computing the elapsed time incorrectly may lead to inaccurate simulations and/or unsatisfying gaming experiences. SDL 2, a cross-platform library used to build games, provides functions to help us compute our elapsed time.Settling with Pixel Art For My Game2020-05-25T20:05:00+00:002020-05-25T20:05:00+00:00http://seanballais.github.io/blog/settling-with-pixel-art-for-my-game<p>One of the most important aspects of any game is the graphics. It is the medium in which the game communicates the story, the actions, and the events to the player. Most games typically use a graphical style, as opposed to text style, which old games like Zork use. The game I am currently working on, and is in pre-production, is no exception. A graphical style easily allows anyone to immerse themselves into the game world, and may more easily communicate about the world to the player than text-style games. As they say, a picture is worth a thousand words. However, a graphical style comes with its own caveats. You can’t slap any art asset into the game. It must fit well with the entire theme of the game. Not only that, but games tend to have a lot of art assets, from static objects to spritesheets. And that amount is a problem for me when it comes to making my game.</p>
<p>My game is a 2D game, and I’m working on it solo. I initially thought of using a cartoon style for the visual aspects of it. Think of River City Girls (except the gameplay portions, since they were in pixel art), Steven Universe, and The Interactive Adventures of Dog Mendonça & Pizzaboy. I love their artstyle, and the original artstyle I envisioned for my game was similar to the three. However, as I said earlier, games have a lot of art assets. I will have to draw the environments, static objects, characters stills, and, perhaps the toughest of all, animations. Since I’m working on the game solo, art is not only my task. I also have to worry about programming, sound, story, and music, among other things. Not only that, I am also not confident in producing high-quality works in the style of the aforementioned peices of art. I believe I can, but I think it will take me longer to produce artworks, and thus, I would be less productive. What do I do?</p>
<table>
<thead>
<tr>
<th style="text-align: center"><img src="/static/img/posts/settling-with-pixel-art-for-my-game/pixel-art-games.png" alt="Three Games Using Pixel Art" /></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center"><em>Three games using pixel art. From left to right: Hyper Light Drifter, Stardew Valley, and Celeste.</em></td>
</tr>
</tbody>
</table>
<p>Fortunately, there is another medium I can use to bring my game to life: pixel art. Pixel art is a form of art where pixels are more visible and there are fewer details. Modern games such as Celeste, Stardew Valley, and Hotline Miami (both 1 and 2) use pixel art. There are various reasons to use pixel art. Some games, like Shovel Knight, use it to pay homage to older generation video games and systems such as the Nintendo Entertainment System (SNES). Others use pixel art for aesthetic purposes, like Dead Cells. In cases like that of Hyper Light Drifter’s, pixel art was used due to technical reasons. In an interview with Gamasutra’s Kris Ligman, Alex Preston, the development lead for Hyper Light Drifter, found that it was more efficient to work with pixel art because he was the only one working on the art. This is also the very reason why I am settling with pixel art for my game — it is way more productive for me, working on a game solo, to utilize pixel art for the game’s visuals, compared to taking too much time on illustrations. One aspect of the beauty of pixel art, especially from the artist’s perspective, is that artists do not have to put in as much detail in pixel as in other forms of art. The brain tends to fills in the details in pixel art. This means that part of the artist’s work has already been cut out by the brain. This, however, does put a constraint on artists, in that there are only a few pixels to work with; every pixel counts. Artists will have to be creative to ensure that their artworks still properly convey its intended message. Though, that’s just part of the beauty of pixel art.</p>
<p>At the time of writing, I have only started working with pixel art for a few days through <a href="https://www.aseprite.org/">Aseprite</a>. It is challenging for me, but perhaps it is too for many others as well. But, working with it has been fun. Pixel art has been the conveyer of fictional worlds and stories for many games. It has enabled many players to enjoy new experiences that could not have been made possible without pixel art. I never expected the start of my indie game development journey to involve pixel art. But, I am glad that it is an option for me to use to bring my game into reality, especially given the circumstances.</p>
<h1 id="references-and-additional-readings">References and Additional Readings</h1>
<ul>
<li><a href="https://nicepixel.se/what-is-pixel-art/">What is Pixel Art?</a></li>
<li><a href="https://yachtclubgames.com/shovel-knight-of-hope-press-kit/">Shovel Knight: Shovel of Hope Press Kit</a></li>
<li><a href="https://www.youtube.com/watch?v=m48xthwkpI0&t=312s">Why is every indie game made with Pixel Art?</a></li>
<li><a href="https://www.gamasutra.com/blogs/KrisLigman/20131030/203652/The_ultramodern_stylings_of_Hyper_Light_Drifter.php">The ultra-modern stylings of Hyper Light Drifter</a></li>
</ul>Sean Francis N. BallaisOne of the most important aspects of any game is the graphics. It is the medium in which the game communicates the story, the actions, and the events to the player. Most games typically use a graphical style, as opposed to text style, which old games like Zork use. The game I am currently working on, and is in pre-production, is no exception. A graphical style easily allows anyone to immerse themselves into the game world, and may more easily communicate about the world to the player than text-style games. As they say, a picture is worth a thousand words. However, a graphical style comes with its own caveats. You can’t slap any art asset into the game. It must fit well with the entire theme of the game. Not only that, but games tend to have a lot of art assets, from static objects to spritesheets. And that amount is a problem for me when it comes to making my game.Why is the Dot Product of Two Perpendicular Vectors Zero?2020-05-03T18:38:00+00:002020-05-03T18:38:00+00:00http://seanballais.github.io/blog/why-is-the-dot-product-of-two-perpendicular-vectors-zero<p>Since last week, I have been teaching myself some linear algebra through Eric Lengyel’s’ book, <em>Mathematics for 3D Game Programming and Computer Graphics</em>. One of the topics I have recently learned is about the dot product of vectors. The dot product is simply the length of the projection of one vector onto the other vector. You could think of a projection as a shadow of the vector being projected, on the other vector where the light source is perpendicular and is pointing to the other vector. The picture below shows a visualization of what I just described. In the image below, \(P\) and \(Q\) are 2D vectors. Note that the projection is also another vector.</p>
<p><img src="/static/img/posts/why-is-the-dot-product-of-two-perpendicular-vectors-zero/projection.png" alt="Visualization of a Projection of A Vector Onto Another" /></p>
<p>The dot product is defined as:</p>
\[P \cdot Q = \sum_{i=1}^{n} P_{i}Q_{i}\]
<p>where \(P\) and \(Q\) are \(n\)-dimensional vectors. From the definition alone, we can see that the dot product is just a summation of the products of each component from each vector. For example, let’s say we have two 2D vectors, \(P = \langle 2, 3 \rangle\) and \(Q = \langle 4, 2 \rangle\). The dot product of those two vectors would go as follows.</p>
\[\begin{align}
P \cdot Q & = \sum_{i=1}^{n} P_{i}Q_{i} \\
& = P_{1}Q_{1} + P_{2}Q_{2} \\
& = (2)(4) + (3)(2) \\
& = 8 + 6 \\
P \cdot Q & = 14
\end{align}\]
<p>One property that we can obtain from the dot product is that, whenever we get the dot product of two perpendicular vectors, the result is zero. Why is it so? We can use the basic definition of the dot product to answer that, but using another definition will provide us with another perspective that will give us a slightly more in-depth understanding why it is so. But, what is that other definition?</p>
<p>Before I directly answer that, let’s try something else first. Let’s take two vectors again, \(P\) and \(Q\). Let’s make a vector that starts from the head of \(P\) and ends at the head of \(Q\). Noticeably, we get a vector that is just \(P - Q\), and a triangle made from the three vectors.</p>
<p><img src="/static/img/posts/why-is-the-dot-product-of-two-perpendicular-vectors-zero/vector-triangle.png" alt="A Triangle Made of Three Vectors" /></p>
<p>Now, let’s play with the length, also known as the magnitude of the vector \(P - Q\). Remember that the magnitude of a vector \(P\) is symbolized as \(\left | \left | P \right |\right |\), and is defined by the equation below. Some texts use \(| P |\) for the magnitude. I do not recommend using that notation because it might be confused with the absolute value. Also, looking closely at the equation below, you will notice that the magnitude definition is based off of the Pythagorean theorem.</p>
\[\left \| P \right \| = \sqrt{\sum_{i=1}^{n} P_{i}^{2}}\]
<p>Interestingly, the above is not the only equation for the length of \(P - Q\). Since we got a triangle, we can actually utilize trigonometry to get the length. <a href="[https://www.mathsisfun.com/algebra/trig-cosine-law.html]">The Law of Cosines</a> allows us to obtain another equation for the length. Utilizing said law would give us the equation.</p>
\[\left \| P - Q \right \| = \sqrt{\left \| P \right \|^{2} + \left \| Q \right \|^{2} - 2\left \| P \right \|\left \| Q \right \|\cos(\alpha)}\]
<p>\(\alpha\) in the equation is simply the angle between vectors, \(P\) and \(Q\). To make the equation easier to play with, let’s remove the square root from the equation.</p>
\[\left \| P - Q \right \|^{2} = \left \| P \right \|^{2} + \left \| Q \right \|^{2} - 2\left \| P \right \|\left \| Q \right \|\cos(\alpha)\]
<p>Let’s play around with the equation further.</p>
\[\begin{align}
\left \| P - Q \right \|^{2} & = \left \| P \right \|^{2} + \left \| Q \right \|^{2} - 2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\left (\sqrt{\sum_{i=1}^{n}(P_{i} - Q_{i})^{2}} \; \right )^{2} & = \left (\sqrt{\sum_{i=1}^{n}P_{i}^{2}} \; \right )^{2} + \left (\sqrt{\sum_{i=1}^{n}Q_{i}^{2}} \; \right)^{2} - 2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}(P_{i} - Q_{i})^{2} & = \sum_{i=1}^{n}P_{i}^{2} + \sum_{i=1}^{n}Q_{i}^{2} - 2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
& = \sum_{i=1}^{n}(P_{i}^{2} + Q_{i}^{2}) - 2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}(P_{i}^{2} - 2P_{i}Q_{i} + Q_{i}^{2}) & = \sum_{i=1}^{n}(P_{i}^{2} + Q_{i}^{2}) - 2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}(P_{i}^{2} - 2P_{i}Q_{i} + Q_{i}^{2}) - \sum_{i=1}^{n}(P_{i}^{2} + Q_{i}^{2}) & = -2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}(P_{i}^{2} - 2P_{i}Q_{i} + Q_{i}^{2}) - (P_{i}^{2} + Q_{i}^{2}) & = -2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}(P_{i}^{2} - 2P_{i}Q_{i} + Q_{i}^{2} - P_{i}^{2} - Q_{i}^{2}) & = -2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}(-2P_{i}Q_{i}) & = -2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
-2\sum_{i=1}^{n}P_{i}Q_{i} & = -2\left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}P_{i}Q_{i} & = \left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
\sum_{i=1}^{n}P_{i}Q_{i} & = \left \| P \right \|\left \| Q \right \|\cos(\alpha)
\end{align}\]
<p>Remember that \(\sum_{i=1}^{n}P_{i}Q_{i} = P \cdot Q\), as per the definition of the dot product we discussed earlier.</p>
\[\begin{align}
\sum_{i=1}^{n}P_{i}Q_{i} & = \left \| P \right \|\left \| Q \right \|\cos(\alpha) \\
P \cdot Q & = \left \| P \right \|\left \| Q \right \|\cos(\alpha)
\end{align}\]
<p>(We can actually make the above simpler by using the dot product property, \(P \cdot P = \left | \left | P \right | \right |^{2}\).)</p>
<p>As you can see from the expressions above, we were able to produce another definition of the dot product, \(P \cdot Q = \left |\left | P \right |\right |\left |\left | Q \right |\right |\cos(\alpha)\). This is where things get interesting. Remember that whenever two lines or vectors are perpendicular to each other, the angle between them will always be \(90°\). Thus, for two perpendicular vectors, \(\alpha = 90\). Now, take a look at the \(\cos(\alpha)\) part of the equation. Let’s substitute \(\alpha\) in \(\cos(\alpha)\) with \(90\). This gives us, \(\cos(90°)\), whose result is \(0\). Applying that knowledge into the second definition of the dot product we have, we get:</p>
\[\begin{align}
P \cdot Q & = \left \| P \right \| \left \| Q \right \|\cos(\alpha) \\
& = \left \| P \right \| \left \| Q \right \|\cos(0) \\
& = \left \| P \right \| \left \| Q \right \| \cdot 0 \\
P \cdot Q & = 0
\end{align}\]
<p>And thus, the reason why two perpendicular vectors have a dot product of \(0\). If you are not yet convinced, here’s an alternative way of looking at it. Let’s utilize the shadow analogy we have from the beginning of this article. As usual, we have a light source that is perpendicular to the vector being projected on. However, as shown in the image below, since the vector we are projecting is parallel to the light source, no shadow will be cast onto the other vector. No shadow means that the projection has a length of zero. Thus, the dot product of two perpendicular vectors is zero — answering our question.</p>
<p><img src="/static/img/posts/why-is-the-dot-product-of-two-perpendicular-vectors-zero/perpendicular.png" alt="Visualization of a Projection of A Vector Onto A Perpendicular Vector" /></p>
<p>In many instances in mathematics, a mathematical concept does not necessarily only have one formula describing it. Through the use of laws and logically-sounding mathematical gymnastics, we can conjure up formulas that define the same concept. We have witnessed such phenomenon in this article with the dot product. We have seen that there is another definition for the dot product. And through it, we were able to figure out an explanation to why perpendicular vectors have a dot product of zero. The new definition we obtained will help us understand more advanced linear algebra concepts. For those of us learning linear algebra, this knowledge is another stepping stone that will lead us to a better understanding of linear algebra. It’s time for us to trek unto other linear algebra topics. And as for those who stumbled upon this just out of curiousity, hey, you learned something new today (I hope), and it’s nice to learn something new.</p>
<h1 id="references-and-additional-readings">References and Additional Readings</h1>
<ul>
<li><a href="http://tutorial.math.lamar.edu/Classes/CalcII/DotProduct.aspx">Calculus II | Dot Product</a></li>
<li><a href="https://math.stackexchange.com/questions/3487466/can-a-projection-vector-be-0-0-0">can a projection be 0, 0, 0? - Mathematics Stack Exchange</a></li>
<li><a href="https://www.youtube.com/watch?v=bbBGgHDhmVg">Dot product and angle between two vectors proof (YouTube)</a></li>
<li><a href="https://www.youtube.com/watch?v=LyGKycYT2v0">Dot products and duality | Essence of linear algebra, chapter 9 (YouTube)</a></li>
<li><a href="https://math.stackexchange.com/questions/805954/what-does-the-dot-product-of-two-vectors-represent">geometry - What does the dot product of two vectors represent? - Mathematics Stack Exchange</a></li>
<li><a href="https://www.mathsisfun.com/algebra/trig-cosine-law.html">The Law of Cosines</a></li>
<li><a href="https://www.youtube.com/watch?v=WNuIhXo39_k">Vector dot product and vector length | Vectors and spaces | Linear Algebra | Khan Academy (YouTube)</a></li>
</ul>Sean Francis N. BallaisSince last week, I have been teaching myself some linear algebra through Eric Lengyel’s’ book, Mathematics for 3D Game Programming and Computer Graphics. One of the topics I have recently learned is about the dot product of vectors. The dot product is simply the length of the projection of one vector onto the other vector. You could think of a projection as a shadow of the vector being projected, on the other vector where the light source is perpendicular and is pointing to the other vector. The picture below shows a visualization of what I just described. In the image below, \(P\) and \(Q\) are 2D vectors. Note that the projection is also another vector.Comic Strip #3 - When You Add a New Feature Without Enough Tests2018-06-03T22:06:00+00:002018-06-03T22:06:00+00:00http://seanballais.github.io/blog/comic-strip-3-when-you-add-a-new-feature-without-enough-tests<p><img src="/static/img/posts/comic-strip-3-when-you-add-a-new-feature-without-enough-tests/comic-strip.jpeg" alt="When You Add a New Feature Without Enough Tests" width="75%" /></p>
<p><em>Do check out <a href="http://www.commitstrip.com">CommitStrip</a>, the website that inspired me to create the strip. They have excellent and hilarious strips that, as they say in their site, relate to the lives of web agency developers.</em></p>
<p><em>What software projects have you worked on that doesn’t have tests? How was the experience? Let me know in the comments below.</em></p>Sean Francis N. BallaisImplementing a Simple Message Bus in C++2017-01-03T14:33:00+00:002017-01-03T14:33:00+00:00http://seanballais.github.io/blog/implementing-a-simple-message-bus-in-cpp<p>Starting late December of 2016, I have been working on creating a 2D game engine for fun (and profit). It is not done yet. Most of the systems have not yet been implemented. <a href="/blog/box2d-and-the-pixel-per-meter-ratio/">Integration between graphics and physics</a> is nonexistent. Key core components are nothing but ideas of the mind. What I recently finished working on was the message bus. It is already functional but it still needs improvement.</p>
<p>A message bus acts like the communication gateway between two or more components in a program, may it be business-oriented applications, or games. Without it, components can tend to couple themselves, and create a messy looking architecture.</p>
<p>In this article, we will be implementing a game-oriented message bus that you can use in your own project. Many applications, game engines, and games are written in C++ so we will be using that language. I recommend using C++14 because it is the latest C++ standard but this will compile in C++11 too.</p>
<h4 id="whats-a-message-bus">What’s a Message Bus?</h4>
<p>Applications and games normally are composed of multiple components. Each component is responsible for a task or a feature of the application. Sometimes, a component needs to ‘talk’ to another component. For example, your input system would need to “tell” your entity system that the player needs to be moved forward because the <code class="language-plaintext highlighter-rouge">W</code> key has been pressed. In code, you might implement it in this manner.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// Somewhere in the depths of your Input system.
if (Input.isPressed(Keys.W)) {
Log.add("Siopao! Siopao! Siopao! Do not do it this way! Siopao! Siopao! Siopao!");
player.move(10, 10);
...
}
</code></pre></div></div>
<p>Now, your input system is now informing the player to move forward. Game runs perfectly but there is a problem. Doing so couples your code. Coupled code is hard to maintain and is messy. Adding and removing certain parts would be more difficult as one change could entail changes in the other components. Creating a diagram on the overall system could result in each component connected to each other component. It looks messy.</p>
<p><img src="/static/img/posts/implementing-a-simple-message-bus-in-cpp/messy-coupling.jpg" alt="Coupled components" /></p>
<p>To solve this issue, we would need to decouple the components from each other. A system that will allow communication between these components is what we need. This system is what we call a message bus.</p>
<p>A <strong>message bus</strong> is basically a modified large-scale <a href="http://gameprogrammingpatterns.com/observer.html">Observer pattern</a>. In the Observer pattern, there would be <strong>observers</strong> to receive notifications and <strong>subjects</strong> to send those notifications.</p>
<p>In a message bus, you have components sending and receiving messages to it. The message bus’s job is to route these messages to every component connected to it. <strong>Messages</strong> that each component send are basically events that happened. For example, a component may send a <code class="language-plaintext highlighter-rouge">W_PRESSED</code> message and the message bus will send that message to other components. The receipient is responsible with what it will do with the message.</p>
<p><img src="/static/img/posts/implementing-a-simple-message-bus-in-cpp/messagebus.jpg" alt="Architecture based around a message bus" /></p>
<p>One cool thing about message buses is that the sender does not even need to know if the message was received by another component or not. Heck! The sender should only be aware of the existence of itself and the message bus. It should not know the existence of the other components. The sent message can be silently ignored by the receivers (if there are any).</p>
<h4 id="implementing-a-message-bus">Implementing a Message Bus</h4>
<p>Time to for the part you have been waiting for - implementing the message bus. The code here is adapted from the <code class="language-plaintext highlighter-rouge">MessageBus</code> component I have in my engine. We would start with implementing the <code class="language-plaintext highlighter-rouge">Message</code> class. We can implement it like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>class Message
{
public:
Message(const std::string event)
{
messageEvent = event;
}
std::string getEvent()
{
return messageEvent;
}
private:
std::string messageEvent;
};
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">Message</code> constructor accepts the string parameter <code class="language-plaintext highlighter-rouge">event</code> that contains the event that happened. The value of <code class="language-plaintext highlighter-rouge">messageEvent</code> can be something like <code class="language-plaintext highlighter-rouge">W_PRESSED</code> or <code class="language-plaintext highlighter-rouge">PLAYER_FELL</code>. Note that this implementation may differ from yours depending on your needs.</p>
<p>Next, we will implement the message bus itself where all components are connected to. This is how we can implement the message bus.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include <functional>
#include <queue>
#include <vector>
class MessageBus
{
public:
MessageBus() {};
~MessageBus() {};
void addReceiver(std::function<void (Message)> messageReceiver)
{
receivers.push_back(messageReceiver);
}
void sendMessage(Message message)
{
messages.push(message);
}
void notify()
{
while(!messages.empty()) {
for (auto iter = receivers.begin(); iter != receivers.end(); iter++) {
(*iter)(messages.front());
}
messages.pop();
}
}
private:
std::vector<std::function<void (Message)>> receivers;
std::queue<Message> messages;
};
</code></pre></div></div>
<p>Well, that’s aplenty! Let’s explain what each function does.</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">addReceiver()</code> <br />
This function adds a new receiver to the list of receivers <code class="language-plaintext highlighter-rouge">notify()</code> will loop through. A receiver is basically another component connected to the message bus. All receivers are stored in the <code class="language-plaintext highlighter-rouge">receivers</code> vector. This function should be called during the initialization of your program. We are accepting <code class="language-plaintext highlighter-rouge">std::function</code> objects so that we will be able to accept receivers that do not inherit from some sort of an <code class="language-plaintext highlighter-rouge">Observer</code> class. Also, the function name we pass can be different as long as the function has the same signature.</li>
<li><code class="language-plaintext highlighter-rouge">sendMessage()</code> <br />
Adds a new message that the message bus will send to each component. All messages are added in a queue (<code class="language-plaintext highlighter-rouge">messages</code> in our case). We are using a queue so that we are guaranteed that messages are sent using FIFO (first in, first out). You do not want to be killed by an enemy first even though you killed him first, don’t you? This function is invoked by the component itself that has a reference to the message bus.</li>
<li><code class="language-plaintext highlighter-rouge">notify()</code> <br />
This function sends all messages to each component. The first message in the queue is the first to be sent to each component and then popped off the message queue and so on. This function should be called during the game loop.</li>
</ul>
<p>Next, we would need a base class where all components that uses the message bus will be based on. We will call this base class, <code class="language-plaintext highlighter-rouge">BusNode</code>.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include <iostream>
#include <functional>
class BusNode
{
public:
BusNode(MessageBus *messageBus)
{
this->messageBus = messageBus;
this->messageBus->addReceiver(this->getNotifyFunc());
}
virtual void update() {};
protected:
MessageBus *messageBus;
std::function<void (Message)> getNotifyFunc()
{
auto messageListener = [=](Message message) -> void {
this->onNotify(message);
};
return messageListener;
}
void send(Message message)
{
messageBus->sendMessage(message);
}
virtual void onNotify(Message message)
{
// Do something here. Your choice. You could do something like this.
// std::cout << "Siopao! Siopao! Siopao! (Someone forgot to implement onNotify().)" << std::endl;
}
};
</code></pre></div></div>
<p>Upon construction of a <code class="language-plaintext highlighter-rouge">BusNode</code> object, it will add its receiver function, <code class="language-plaintext highlighter-rouge">onNotify</code>, to the message bus so that it can begin receiving messages automatically. We have to use <code class="language-plaintext highlighter-rouge">getNotifyFunc()</code> to pass a <code class="language-plaintext highlighter-rouge">std::function</code> object containing a lambda function that calls our object’s <code class="language-plaintext highlighter-rouge">onNotify()</code>. The <code class="language-plaintext highlighter-rouge">update()</code> function is where we would perform update routines in our component.</p>
<p>We have now implemented a rudimentary message bus. You can now use this in your project and remix it according to your needs. But to finish this section on a high note, let’s create a simple example using those three classes we have built. Don’t forget to compile this under C++11 or C++14.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include <iostream>
#include <functional>
#include <queue>
#include <vector>
class Message
{
public:
Message(const std::string event)
{
messageEvent = event;
}
std::string getEvent()
{
return messageEvent;
}
private:
std::string messageEvent;
};
class MessageBus
{
public:
MessageBus() {};
~MessageBus() {};
void addReceiver(std::function<void (Message)> messageReceiver)
{
receivers.push_back(messageReceiver);
}
void sendMessage(Message message)
{
messages.push(message);
}
void notify()
{
while(!messages.empty()) {
for (auto iter = receivers.begin(); iter != receivers.end(); iter++) {
(*iter)(messages.front());
}
messages.pop();
}
}
private:
std::vector<std::function<void (Message)>> receivers;
std::queue<Message> messages;
};
class BusNode
{
public:
BusNode(MessageBus *messageBus)
{
this->messageBus = messageBus;
this->messageBus->addReceiver(this->getNotifyFunc());
}
virtual void update() {}
protected:
MessageBus *messageBus;
std::function<void (Message)> getNotifyFunc()
{
auto messageListener = [=](Message message) -> void {
this->onNotify(message);
};
return messageListener;
}
void send(Message message)
{
messageBus->sendMessage(message);
}
virtual void onNotify(Message message)
{
// Do something here. Your choice. But you could do this.
// std::cout << "Siopao! Siopao! Siopao! (Someone forgot to implement onNotify().)" << std::endl;
}
};
// This class will receive a message from ComponentB.
class ComponentA : public BusNode
{
public:
ComponentA(MessageBus* messageBus) : BusNode(messageBus) {}
private:
void onNotify(Message message)
{
std::cout << "I received: " << message.getEvent() << std::endl;
}
};
// This class will send a message to ComponentA.
class ComponentB : public BusNode
{
public:
ComponentB(MessageBus* messageBus) : BusNode(messageBus) {}
void update()
{
Message greeting("Hi!");
send(greeting);
}
private:
void onNotify(Message message)
{
std::cout << "I received: " << message.getEvent() << std::endl;
}
};
int main()
{
MessageBus messageBus;
ComponentA compA(&messageBus);
ComponentB compB(&messageBus);
// This is supposed to act like a game loop.
for (int ctr = 0; ctr < 50; ctr++) {
compA.update();
compB.update();
messageBus.notify();
}
return 0;
}
</code></pre></div></div>
<p>The output would look like this.</p>
<p><img src="/static/img/posts/implementing-a-simple-message-bus-in-cpp/example-output.jpg" alt="Message Bus example output" /></p>
<h4 id="conclusion">Conclusion</h4>
<p>We have implemented a message bus that allows intercomponent communication and decoupling of our system. Our message bus consists of three classes: <code class="language-plaintext highlighter-rouge">BusNode</code>, the base class for our components depending on the message bus; <code class="language-plaintext highlighter-rouge">Message</code>, the class the messages we send depends on; and <code class="language-plaintext highlighter-rouge">MessageBus</code>, the message bus implementation itself.</p>
<p>What we created is just a basic message bus. The message bus is usable but it surely needs improvements. One way you can build upon this is by adding a mechanism where receivers can subscribe to specific messages. To allow comparison between messages, we can use message IDs. The IDs should be hashed (try FNV-1A) to allow fast comparisons.</p>
<p>For further reference, you may want to check out OpTank’s <a href="http://optank.org/2013/04/02/game-development-design-3-message-bus/">article</a> on message buses. Michael Kissner’s <a href="http://gamasutra.com/blogs/MichaelKissner/20151027/257369/Writing_a_Game_Engine_from_Scratch__Part_1_Messaging.php">article</a> about messaging in a game engine in Gamasutra can be helpful as well.</p>
<p>Do not take what we have created as is. I intended it as a foundation from which you can build your own message bus. I recommend deviating from the code here. Do not forget to <a href="/blog/5-lessons-learned-from-developing-a-school-election-system/">plan before you code</a>. Adapt what you have learned here and apply it in your own message bus or any project you have at hand.</p>
<p><em>Are you currently working on a project? How did you process communication between your project’s components? Do you have something to share? Let us know in the comments below.</em></p>Sean Francis N. BallaisStarting late December of 2016, I have been working on creating a 2D game engine for fun (and profit). It is not done yet. Most of the systems have not yet been implemented. Integration between graphics and physics is nonexistent. Key core components are nothing but ideas of the mind. What I recently finished working on was the message bus. It is already functional but it still needs improvement.Box2D and the Pixel Per Meter Ratio2016-12-17T12:27:00+00:002016-12-17T12:27:00+00:00http://seanballais.github.io/blog/box2d-and-the-pixel-per-meter-ratio<p>When you develop a 2D game that has physics, chances are that you will be using Box2D. Box2D is an open source physics engine for 2D rigid bodies. It can integrate with any 2D game engine or library. Many games, such as Angry Birds and even the game I recently made with my classmates called <a href="https://github.com/seanballais/push-em-over/">Push ‘Em Over</a>, use Box2D for their physics. However, when you integrate the physics world of Box2D into the graphics world of your 2D library or engine for the first time, it might come as a surprise to you that your bodies are moving slowly.</p>
<p><img src="/static/img/posts/box2d-and-the-pixel-per-meter-ratio/1-ppm.gif" alt="A body moving slowly due to a 1 PPM ratio." /></p>
<p>According to Box2D’s <a href="http://box2d.org/2011/12/pixels/">website</a>, Box2D uses the MKS system and radians for angles. As you would usually have learned from your Physics class, the MKS system uses meters (M) for length, kilograms (K) for mass, and seconds (S) for time.</p>
<p>By default, Box2D assumes that one pixel on the screen is equal to one meter to the physics world. This was one of the first hurdles I encountered when I was using Box2D for the first time. From this premise, we can infer that the cause of the slowdown of the movement of your bodies is that your bodies are traveling large distances. This means that if you have a character at <code class="language-plaintext highlighter-rouge">(0, 0)</code> moving towards <code class="language-plaintext highlighter-rouge">(1024, 0)</code> in your screen, your character would be traveling a total distance of 1.024 kilometers.</p>
<p><img src="/static/img/posts/box2d-and-the-pixel-per-meter-ratio/default-box2d-travel.jpg" alt="1024 pixels equals to 1024 meters in Box2D by default!" /></p>
<p>Fortunately, solving this problem is easy. We would just need to come up with a reasonable conversion factor for the pixels on the screen, and the meters in the physics world. This conversion factor is called the <strong>pixel per meter (PPM) ratio</strong>. This pixel per meter ratio would set how many pixels a meter is equal to in your physics world in Box2D.</p>
<p>For example, if you set your PPM ratio to 32, then it would mean that one meter in Box2D would equal to 32 pixels in your screen. A character traveling from <code class="language-plaintext highlighter-rouge">(0, 0)</code> to <code class="language-plaintext highlighter-rouge">(1024, 0)</code> would only be traveling 32 meters, instead of 1024 meters if you are using the default pixel per meter ratio of 1 pixel to 1 meter. That’s a 96.875% decrease in distance traveled! This will result in faster movement and a stabler simulation.</p>
<p><img src="/static/img/posts/box2d-and-the-pixel-per-meter-ratio/32-ppm.gif" alt="A body moving fast due to a 32 PPM ratio" /></p>
<p>It is suggested in the Box2D website that you base your PPM ratio on the size of your characters. If you have a character 100 pixels tall and his “physical” height is 1 meter, then you should set your PPM ratio to 100 pixels to 1 meter (100:1). The next question is how you would apply the pixel per meter ratio to your code. Your approach might be different but this is what I would suggest.</p>
<p>You would first need to set a global static class where you would store your constants. You could call the class <code class="language-plaintext highlighter-rouge">Constants</code> but the name is arbitrary. Store the constant variable <code class="language-plaintext highlighter-rouge">PPM</code> there and give it a value of your choice. Remember that the value of <code class="language-plaintext highlighter-rouge">PPM</code> can differ from game to game. My game might have a PPM ratio of 32 while yours might have a ratio of 100. Make sure that <code class="language-plaintext highlighter-rouge">PPM</code> is a <code class="language-plaintext highlighter-rouge">float</code> to preserve precision and to prevent the value from being casted into an <code class="language-plaintext highlighter-rouge">int</code> when you convert to meters or pixels. Box2D works with decimal values in its physics world.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>class Constants {
...
const float PPM = 32f;
...
}
</code></pre></div></div>
<p>The tricky part deciding where you would convert between pixels to meters. One of the key places where you would want to convert pixels to meters is where you would create the <a href="http://www.iforce2d.net/b2dtut/bodies">physics bodies</a> and its fixtures. Box2D talks in meters so to modify properties in your bodies and fixtures, you must translate pixels into meters as shown in the code below.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BodyDef bodyDef = new BodyDef ();
...
// x and y refers to your character's position relative to the screen
bodyDef.position.set ( x / Constants.PPM, y / Constants.PPM );
...
...
PolygonShape bodyBounds = new PolygonShape ();
// width and height refers to the width and height of your character in pixels
bodyBounds.setAsBox ( ( width / Constants.PPM ) / 2, ( height / Constants.PPM ) / 2 );
...
</code></pre></div></div>
<p>Another place where you would want to convert meters to pixels is the part where you would set your character’s position every time a frame is updated. Box2D bodies would give their positions in meters. You must convert the values into pixels to properly position your characters on-screen. The code will look similar to the one below.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>...
character.setXPos ( Math.round ( character.getPlayerPhysicsBody ().getPosition ().x * Constants.PPM ) );
...
</code></pre></div></div>
<p>To wrap up things, you should convert pixels to meters (<code class="language-plaintext highlighter-rouge">n / Constants.PPM</code> where <code class="language-plaintext highlighter-rouge">n</code> is in pixels) whenever you need set Box2D properties. On the other hand, you should convert meters to pixels (<code class="language-plaintext highlighter-rouge">n * Constants.PPM</code> where <code class="language-plaintext highlighter-rouge">n</code> is in meters) whenever you need to get values from Box2D for use on-screen. For example, if you need to set the position of your character on screen, you need to get the character’s position from Box2D’s physics world first and then convert the retrieved values to pixels so that they would be properly placed on-screen. Otherwise, your character will be placed on the wrong position on the screen. Worse, using Box2D’s values without converting them first could result in unexpected outputs such as the one below.</p>
<p><img src="/static/img/posts/box2d-and-the-pixel-per-meter-ratio/a-box2d-mess.jpg" alt="A mess in converting between pixels and meters." /></p>
<p>Box2D is a powerful physics engine. When done right, it will produce wonderful simulations that you and your friends can enjoy. But integrating it into your game can be a tricky process. Meters and pixels are two different units with no standard conversion factor between the two. Using a pixel per meter ratio will solve this ordeal and let you integrate physics with your graphics. This reduces the number of problems that you will encounter, and lets you focus on the more important aspects of your game.</p>
<p><em>Have you used Box2D before? Are you currently working on a game that uses Box2D? Do you have anything to share? Let us know in the comments below.</em></p>Sean Francis N. BallaisWhen you develop a 2D game that has physics, chances are that you will be using Box2D. Box2D is an open source physics engine for 2D rigid bodies. It can integrate with any 2D game engine or library. Many games, such as Angry Birds and even the game I recently made with my classmates called Push ‘Em Over, use Box2D for their physics. However, when you integrate the physics world of Box2D into the graphics world of your 2D library or engine for the first time, it might come as a surprise to you that your bodies are moving slowly.Out With The Old, and In With The New2016-12-16T14:58:00+00:002016-12-16T14:58:00+00:00http://seanballais.github.io/blog/out-with-the-old-and-in-with-the-new<p>I have to admit. I have not stuck with my usually one or two articles per month since this year. Worse, I have not been blogging since June of 2016.</p>
<p>I apologize for that. Starting next year, I promise that I will be churning out one or two articles per month. One hurdle that stopped me from writing is that I wanted to redesign this site before I write new articles. The original design just does not feel satisfying for me and the files of the old design were a mess, further discouraging me from writing for a while. University life and the election system I was developing for was taking a lot of my time from blogging. Fortunately, after a “hiatus” of a few months, I am finally back to blogging. My return is signified by the redesign of my website.</p>
<p>The old design of my blog was based on the <a href="https://github.com/BlackrockDigital/startbootstrap-clean-blog-jekyll">Clean Blog</a> theme for Jekyll. When I started this website in 2015, I was looking for a theme that resembles Medium. Clean Blog was the closest theme I could find. So, I stuck with the theme, and began blogging on this website. A few months later, the design felt uninspired. I want a design that I personally made. So, on December of 2015, I began working on the homepage and the blog page.</p>
<p><img src="/static/img/posts/out-with-the-old-and-in-with-the-new/old-design.jpg" alt="Old Design of the website" /></p>
<p>Working around the current theme is a pain in the ass to handle. I have to make sure I do not mess up the old design and made sure what I was trying to make was built without problems. However, progress halted. I became busy with other projects I needed to do. I was just starting on my Youtube during this time.</p>
<p>My first year of university ended and I was planning to do the redesign again. Sadly, I was only able to write one article on June 2016 as I needed to study for my removal examination in my Calculus class of which I failed (I have to retake my Calculus class during the second semester of my sophomore year), and I needed to complete the election system in time for the student government election in my high school alma mater.</p>
<p>Months went by and I finally finished my first semester of my sophomore year. On the very day my semester ended, I decided to work on redesigning the website and finish it up in a few days. I initially started with a design similar to my previous design.</p>
<p><img src="/static/img/posts/out-with-the-old-and-in-with-the-new/mid-design.jpg" alt="The first iteration of my redesign of the website" /></p>
<p>However, the first iteration felt empty in content. I was feeling a bit burnt out during that time since I recently just finished my final project for our Computer Science class. I started from scratch and deleted most of the original files, saving just the posts and the static files the posts depend on. I searched across the Internet in the hopes of finding inspiration for the new design. Fortunately, I stumbled upon a WordPress theme called <a href="https://colorlib.com/wp/best-minimalist-wordpress-themes/">Soledad</a> at <a href="https://colorlib.com">Colorlib</a>.</p>
<p><img src="/static/img/posts/out-with-the-old-and-in-with-the-new/soledad.jpg" alt="The Soledad WordPress theme" /></p>
<p>I initially dismissed it for another design but soon came back knowing that it was a perfect fit for the new redesign. I based the new design of this website around Soledad but taking in some design decisions I see from the <a href="http://hanselman.com">website</a> of Scott Hanselman, and <a href="http://apple.com">Apple</a>.</p>
<p>The “Sean Ballais” banner you see just below the navigational bar was clearly inspired from Soledad. The banner was created using GIMP and uses Jenna Sue as its font. For the navigational menu, I went with Montserrat for the font as I needed something elegant, easy to read, and fitting with the overall theme. Most of the content uses Raleway (for the title and headings), and Lusitana (for the text). The rest is the <em>code-fu</em> of HTML5, CSS3, Jekyll, Markdown, Bootstrap, and jQuery. In four days, I was finished the redesign. It would have actually taken only three days if not for a form handling bug in Opera that pushed me back by a day.</p>
<p><img src="/static/img/posts/out-with-the-old-and-in-with-the-new/new-design.jpg" alt="The homepage of my newly redesigned website" /></p>
<p>With the cleanup of my website, I am now able to write new articles properly. In the coming months, I will be updating the website with new articles and even page updates. I will do my best to push two articles per month but I could settle with one post per month.</p>
<p>That’s it for now. See you soon!</p>Sean Francis N. BallaisI have to admit. I have not stuck with my usually one or two articles per month since this year. Worse, I have not been blogging since June of 2016.Date a Pisay Boy2016-06-17T15:06:00+00:002016-06-17T15:06:00+00:00http://seanballais.github.io/blog/date-a-pisay-boy<p><em>This blog post has been inspired by Quina Baterna’s <a href="https://theperksofbeingexceptionallyordinary.wordpress.com/2012/06/13/date-a-pisay-girl/">Date a Pisay Girl</a>. You may want to check her article as well as both this and her article have similarities. This is not representative of all Pisay boys.</em></p>
<p>Date a Pisay boy. Date the weird boy that is stressed more about his grades than what fashion trend to follow. He would be more concerned with having an amazing mind than a handsome face. Be ready though for a Pisay boy may randomly share nuggets of knowledge he has acquired, expecting that you have a fun conversation.</p>
<p>Date a Pisay boy. Date a Pisay boy for he will be simple when you go out. He will most likely wear jeans and a shirt. In some cases, shorts will replace jeans. In times he is able, he will wear something more fashionable than he is used to wearing. Even though he would not admit it, he hopes that you appreciate it.</p>
<p><img src="/static/img/posts/date-a-pisay-boy/example.jpg" alt="A Pisay boy" /></p>
<p>Date a Pisay boy. Date a Pisay boy for he is independent. Being used to the pressures of being in one of the most prestigious schools in the Philippines, he knows how to manage his time well and cope up with failed marks. When stress hits him, expect thay he will be shooting hoops or play Dota 2 with his friends. There’s a good chance that a Pisay boy may be far away from his family. He has to endure homesickness and missing his family.</p>
<p>Date a Pisay boy. Date a Pisay boy for he knows how to value people and his things. Having a math class almost everyday, a Pisay boy knows that his scientific calculator is his life line. He gets a mini-heart attack every time he thought he lost it. Even though a Pisay boy is a busy man, he will still look for ways to spend some time with you. It may come as a conversation thread in Twitter, a long-thought comment in a Facebook post, or a quick casual chat or greeting when you meet each other in a hall. His methods may be mundane but he values every second he engages with you. He will do his best to appear calm even though he is nervous deep inside and is thinking of the right words to say to you.</p>
<p><img src="/static/img/posts/date-a-pisay-boy/spongegar.jpg" width="500" height="308" /></p>
<p>Date a Pisay boy. Date a Pisay boy for he is adaptable. His rigorous training from <em>that</em> prestigious school allows him to hone his skills in adapting between shifting schedules, working on projects and papers, and managing his time with extra-curricular activities. He will try his best to speak your ‘language,’ and keep up with your craziness.</p>
<p>Date a Pisay boy. Date a Pisay boy for he is bound to achieve amazing feats. He did not study just for the sake of studying. A Pisay boy studies to help him trek to somewhere great. He works hard for what he wants achieve. He is a curious being. Quantum physics, video games, computer science, chemistry, dance, arts, literature, sports, a painting of a meadow, and a lot more that interests him makes him tick may it be inside or outside the classroom.</p>
<p>Date a Pisay boy. Date a Pisay boy for he will inspire you to achieve your goals. He is simple but has a broad imagination complemented by child-like curiousity. Let him take you to his wonderful world, and be astonished and get lost in it.</p>
<p><img src="/static/img/posts/date-a-pisay-boy/imagination.jpg" alt="Imagination" /></p>
<p><em>What do you think of Pisay boys? Or Pisay in general? Do you know a Pisay boy? Or do you have an opinion to share? Let us know in the comments below.</em></p>Sean Francis N. BallaisThis blog post has been inspired by Quina Baterna’s Date a Pisay Girl. You may want to check her article as well as both this and her article have similarities. This is not representative of all Pisay boys.Developing Basyang Server Part 12016-03-26T20:49:00+00:002016-03-26T20:49:00+00:00http://seanballais.github.io/blog/developing-basyang-server-part-1<p>Late December 2015, two of my friends (<a href="https://twitter.com/wechuuuuu">Warren Chu</a> and <a href="https://web.facebook.com/profile.php?id=1679863886&ref=br_rs">Ray Mart Montesclaros</a>) and I formed a startup called <a href="https://web.facebook.com/CreatomivStudios/">Creatomiv</a> with <a href="https://twitter.com/TheFrancisPlaza">Francis Plaza</a> as our mentor and advisor. It is a tech startup that aims to develop mobile apps of different categories. Recently, we are currently working on first product called Basyang, an app that lets you create stories with friends. I was charged with developing the server application and developing it is quite fun and frustrating.</p>
<p>Initially, we were planning to develop Basyang Server in Go for its speed, its similarity to C, and appeal for back-end web development. I tried it out for nearly a month and found it quite a joy to use. However, I hated the project structure of each Go project. I just don’t get it at times. I prefer to have freedom in structuring my project. Realizing that I would spend more time learning Go than developing the server itself, I opted to use Python instead.</p>
<p>I opted for Python because I am more experienced with it. I started learning it just days before <a href="/blog/remembering-haiyan/">Typhoon Haiyan struck the country</a>. I was quite impressed with the language. It was fun to work with and things were easier in Python land except those nasty misplaced white spaces.</p>
<p>In an internship Ray Mart, another friend of mine, <a href="https://twitter.com/CapiliLimher">Dennis Limher Capili</a>, and I attended in the University of the Philippines Diliman, we used Python and Django to develop a room reservation system. My research thesis that utilized <a href="http://opencv.org/">OpenCV</a> was originally written in Python before porting it to C++. A year later after our internship, I was asked by my high school, Philippine Science High School Eastern Visayas Campus, to <a href="/blog/5-lessons-learned-from-developing-a-school-election-system/">build an election system</a> for them.</p>
<p>I designed the server around the <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC design pattern</a> because it creates a clear border between the logic and presentation. The MVC pattern is a design pattern that, as mentioned before, separates the logic of your application from the presentation. The pattern has three components: model, view, and controller.</p>
<p>The <strong>model</strong> is where the logic and data resides. This is where you do data manipulation such as creating a user.</p>
<p>The <strong>view</strong> is what the user sees. It is the user interface in web apps. In Basyang Server, our view is the REST API that lets the Basyang app communicate with the server. One general rule is that the view should never directly talk to the model and vice versa. This is where the third and last component of the MVC pattern comes in - the controller.</p>
<p>The <strong>controller</strong> is the glue that binds the view and model together. It accepts input and converts it to commands for the model or view.</p>
<p><img src="/static/img/posts/developing-basyang-server-part-1/mvc-pattern.png" alt="The MVC Pattern" /></p>
<p>To make things easier on our end, we used a microframework called Bottle for our server. It is easy to use, requires little space, and it is only one file. We used a microframework because we do not want to use a full framework because we do not need the functionality brought by a full framework and it would just be a waste of space if we do so.</p>
<p>Since we are storing passwords, we utilized the <code class="language-plaintext highlighter-rouge">pprp</code> package to hash our passwords using SHA512 and PBKDF2 before we store the passwords.</p>
<p>For handling the data, we used <code class="language-plaintext highlighter-rouge">PyMySQL</code> for directly talking to our MySQL database. We talked to our MySQL database through SQL commands instead of using an ORM because I was already directly talking to our database before I thought of using an ORM instead.</p>
<p>We also utilize unit testing through Python’s <code class="language-plaintext highlighter-rouge">unittest</code> library. A lot of bugs were catched thanks to unit testing.</p>
<p>My text editor of choice and the one I used for developing Basyang server is Atom. I love the user interface and the feature set is comparable with Sublime Text. In conjunction with Atom, I use Flare8 for linting my Python code. For testing the API, I use the REST Client package available for Atom.</p>
<p>Our Git repository is stored privately over at GitLab. We used it to save money because private repositories are free at GitLab (Hooray for GitLab!). BitBucket was an option but it only limited private repositories to 5 users. We also use GitLab CI as our build server. PythonAnywhere was also used as our test server.</p>
<p>Initial development started in February 12, 2016 after I finished my contract with a client. Getting started to work with Basyang Server was a relief for me. The recent contract had me developing a WordPress site that was very slow. I even had to download the site and develop it locally because of its speed.</p>
<p>The structure of Basyang Server is inspired from Django. I had experience with developing Django web apps before and love the structure of a Django app. I even have a separate <code class="language-plaintext highlighter-rouge">settings.py</code> file that is inspired from the framework for the people with deadlines.</p>
<p><img src="/static/img/posts/developing-basyang-server-part-1/structure.png" alt="The Basyang Server Structure" /></p>
<p>Later on, I added unit testing to aid debugging. I hated the dots, <code class="language-plaintext highlighter-rouge">E</code>s, and <code class="language-plaintext highlighter-rouge">F</code>s when tests fail, raise an error, or pass. So, when I had the primary functionality running, I modified the unit test results to use ✔ for pass, • for errors, and ✗ for errors. The first unit test I made was for the test view function that lets the client test if there is a connection to the server.</p>
<p>The model was originally just a file full of functions. I merged the functions into a class called <code class="language-plaintext highlighter-rouge">UserManager</code> and pretty much finished adding all the user related functions such authenticating a user and deleting users.</p>
<p>But a major hurdle I encountered while developing the <code class="language-plaintext highlighter-rouge">UserManager</code> was the hashing the password part. I, of course, utilize <code class="language-plaintext highlighter-rouge">pprp</code> for hashing the passwords but there was a time that there was a hashing bug that hashed the password the wrong way. My tests tell me so. But eventually I fixed but I no longer remember how I did it.</p>
<p>After finishing the model, I worked on the view and the controller. The view was pretty much just using the <code class="language-plaintext highlighter-rouge">@route</code> decorator of Bottle in which its input would be sent to the controller where it will then send it to the model. I refactored and everything is finished. It was ready for the initial testing.</p>
<p>Right now, I am planning to refactor the model to use SQLAlchemy instead of relying on talking directly to the database to make things easier. Some parts of the code are still in need of refactoring.</p>
<p><img src="/static/img/posts/developing-basyang-server-part-1/atom.png" alt="The custom unittest in Basyang Server" /></p>
<p>Generally, developing Basyang Server has been fun. Now that I have more time developing the application unlike in the previous weeks, I will be able to continue developing Basyang Server and bump into multiple bugs again.</p>
<p><em>Are you currently working in a startup? What have you been developing lately? Let us know in the comments below.</em></p>Sean Francis N. BallaisLate December 2015, two of my friends (Warren Chu and Ray Mart Montesclaros) and I formed a startup called Creatomiv with Francis Plaza as our mentor and advisor. It is a tech startup that aims to develop mobile apps of different categories. Recently, we are currently working on first product called Basyang, an app that lets you create stories with friends. I was charged with developing the server application and developing it is quite fun and frustrating.A Job Offer from Madrid2016-01-30T21:48:00+00:002016-01-30T21:48:00+00:00http://seanballais.github.io/blog/a-job-offer-from-madrid<p>On January 15, 2016, a peculiar email dropped in my inbox. I received a message from a developer relations engineer in source{d}, a company based in Madrid, Spain (I did not mention his name for his safety). The subject line read, “Senior Python Engineer at KnC.” With my interest piqued, I read the email. Seconds later, I was jumping in joy (figuratively).</p>
<p><img src="/static/img/posts/a-job-offer-from-madrid/email.png" alt="The email of the offer" /></p>
<p>I was offered a job as a senior python developer! A chance to be a professional. Surprisingly, the job would be in Sweden. Admittedly, I am quite a fan of the aforementioned country. It is the motherland of Felix Kjellberg (yes, I am a bro), Notch (the creator of Minecraft), and Roomie (a singer). My inner fan boy was screaming in joy.</p>
<p>A job in Sweden is also an opportunity for me to experience winter. I have been living in the Philippines all my life where we only have two seasons - wet and dry. The closest cold season I could experience is when I went to Japan in early November 2014 to present a research paper. The season was already autumn so the scenery was a beautiful thing to look at.</p>
<p>However, I rejected the offer.</p>
<p>I told a few of my friends about the job offer and the rejection. And they scolded me. My friend Kyle has a response that gave me a giggle.</p>
<blockquote class="twitter-tweet tw-align-center" data-conversation="none" lang="en"><p lang="tl" dir="ltr"><a href="https://twitter.com/seanballais">@seanballais</a> nigga dafuq u doin, quit school XD<br />kappa</p>— Kyle Alelis (@asdfghjklkappa) <a href="https://twitter.com/asdfghjklkappa/status/687992690646974469">January 15, 2016</a></blockquote>
<script async="" src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<p>The rejection was simply a reply to the message in the email. No formal letters. Just a simple email reply.</p>
<p><img src="/static/img/posts/a-job-offer-from-madrid/email-reply.png" alt="The rejection" /></p>
<p>As it can be derived from the email message itself, I have two reasons why I rejected the offer.</p>
<ul>
<li>
<p><strong>Education is a priority</strong> <br />
Even though I have been programming for nearly 5 years already, I still feel my knowledge is inadequate. I feel that I am a <a href="http://www.hanselman.com/blog/ImAPhonyAreYou.aspx">phony</a>. There are still many topics to learn - may it be science, mathematics, or humanities. Family and friends will also be missed if I accepted the offer.</p>
</li>
<li>
<p><strong>Just founded a startup</strong> <br />
I have founded a startup, called <a href="https://www.facebook.com/CreatomivStudios/">Creatomiv</a>, in late December 2015 together with two high school friends. Aside from being designated as CTO of the startup, we are already working on a project that I find really fun and enjoyable. If I took the offer, I might not be able to focus on the project we are already working on.</p>
</li>
</ul>
<p>I see the job offer as a opportunity that is not the right time for me to grab. There are many other opportunities waiting for me. As they would say, when one door closes, another door opens. I just need to properly choose which door to open. As for now, I will be focusing on my studies and my startup.</p>
<p><em>Have you been given a job offer before but you rejected it? Why or why not? Or do you have an opinion to share? Let us know in the comments below.</em></p>Sean Francis N. BallaisOn January 15, 2016, a peculiar email dropped in my inbox. I received a message from a developer relations engineer in source{d}, a company based in Madrid, Spain (I did not mention his name for his safety). The subject line read, “Senior Python Engineer at KnC.” With my interest piqued, I read the email. Seconds later, I was jumping in joy (figuratively).