<?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 Devin Horsman on Medium]]></title>
        <description><![CDATA[Stories by Devin Horsman on Medium]]></description>
        <link>https://medium.com/@horsman?source=rss-c39dc3a9e320------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S6shHpm8FK1K9FWbxMbX7g.jpeg</url>
            <title>Stories by Devin Horsman on Medium</title>
            <link>https://medium.com/@horsman?source=rss-c39dc3a9e320------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:19:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@horsman/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[Lenses: A way to uncouple shared state]]></title>
            <link>https://medium.com/@horsman/lenses-a-way-to-uncouple-shared-state-f6318951cad8?source=rss-c39dc3a9e320------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6318951cad8</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Devin Horsman]]></dc:creator>
            <pubDate>Mon, 26 Sep 2016 21:50:37 GMT</pubDate>
            <atom:updated>2016-09-26T21:50:37.292Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We’ve touched on the concept of lenses before [</em><a href="http://twistedoakstudios.com/blog/Post1823_decoupling-shared-control"><em>here</em></a><em>, </em><a href="http://twistedoakstudios.com/blog/Post3484_a-visit-to-execution-labs-in-montreal"><em>here</em></a><em>]. This post aims to cover the concept in detail and offer a general programmatic implementation.</em></p><p>Lenses are a generic way to handle <em>shared state</em>. Shared state is some piece of state (member variable, static variable or whatever) that is mutated by more than one process (module, piece of code, thread, etc.) and observed by one or more processes. The term shared state is often used to describe things mutated by multiple operating system processes (threads). It also applies to situations where a program’s internal processes can be thought of as unordered; for instance, when processes are dependent on incoming user input events or when using a time slicing mechanism (as in update functions per entity in a video game). Three examples of shared state in a video game might be:</p><ul><li>Is the game paused? This value might be mutated by a cutscene, tutorial, disconnected controller, or menu.</li><li>What actions can the player take (e.g. use grenade, cast spell, jump, fly)? This value might be mutated by items, progress, tutorials, etc.</li><li>How much damage does the player do? This value might be mutated by a variety of items, temporary power ups, levelling, etc.</li></ul><p>The key thing here is that the values or sets of values are changed by multiple processes in your application, and then read by one or more processes. This example code illustrates the type of bug shared state typically leads to:</p><pre>class Game{ <br>  static bool paused; <br>}</pre><pre>…</pre><pre>tutorial_prompt(){ <br>  Game.paused = true;<br>  show_tutorial().then(<br>    () =&gt; Game.paused = false<br>  ); <br>}</pre><pre>…</pre><pre>clicked_menu(){<br>  Game.paused = true;<br>  open_menu();<br>}</pre><pre>clicked_exit(){<br>  Game.paused = false;<br>  close_menu();<br>}</pre><p>Here we have a tutorial prompt that sets the game to paused; we also have functions that open and close the menu, which set the game to paused or unpaused. What happens if the menu is opened <em>and then</em> the tutorial kicks off? Well, when the tutorial prompt closes the game will become unpaused and the menu will still be open. This is a contrived example but a very common problem nonetheless. A simple solution might look something like:</p><pre>tutorial_prompt(){<br>  Game.paused = true;<br>  show_tutorial().then(<br>   () =&gt; Game.paused = Menu.open? true:false<br>  ); <br>}<br> …</pre><pre>clicked_menu(){<br>  Game.paused = true;<br>  open_menu(); <br>}</pre><pre>clicked_exit(){<br>  Game.paused = Tut.open? true:false;<br>  close_menu();<br>}</pre><p>We check to see if the menu was open and don’t set paused back to false if it was. Easy.</p><p>But wait! Now the tutorial system knows about the fact that there are menus in the game and vice versa. We also had to expose the menu and tutorial open states as public properties. If we remove either of those features from the game or change them significantly we’ll need to edit the others. Add in a cutscene or input system who can also pause the game and you can see we have a problem (n bool checks at each read of pause). This is called coupling, and it’s <em>poopey</em> (a very technical term) for your project.</p><p>Here’s one more example that comes up a lot in games: How much damage does the player do? Often we start by describing the damage as a simple floating point number. Then when you get an item you add to it or multiply it. Pretty soon we figure out that the order in which additions and multipliers are applied matters and then we start sorting items by the type of damage they do. Then we decide you might also get buffs so we need to make sure that the buffs are also sorted into that list and so on.</p><p>Let’s look at how lenses solve both of these problems. Conceptually in both of these cases you are dealing with a value (a bool, a list, a float or whatever) that has multiple observers (processes that want that value at an arbitrary time) and multiple mutators (processes that statefully affect the value at an arbitrary time).</p><p>Some of the existing solutions for dealing with shared state are <em>semaphores</em> (resource use locks) and <em>reactive programming.</em></p><p>Semaphores work really well and are efficient but only work for problems that can be modelled as locking resources (like the pause problem, called idempotent problems). They don’t work for problems where ordering of the mutator’s actions matters or in problems where the value can be modified in arbitrary ways by a mutator.</p><p>With reactive programming, modules receive events whenever a value is modified, and observers get notifications (and usually a reference to who modified it). Usually the observers then do some internal bookkeeping to track the state of the variable. This sort of code often ends up being much more complicated and has a number of variables local to the modules that track the shared state in some way.</p><h3>So what’s a lens?</h3><p>Lets call a piece of shared state a <em>lensed value</em>. Imagine the lensed value as a physical object and the mutating modules as <em>lenses.</em> When you look through the lens between at the object, it looks different than it did by itself. What’s more, you can stack multiple lenses in different configurations and they all contribute to a different representation of the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*OxiJk4Q6I7tvroXe." /><figcaption>In our analogy, the shared state is rendered through the lenses placed by mutators and read by the observers</figcaption></figure><p>Lens ordering and how a lens transforms the state is dependent on the specific application. Lenses can be generally implemented as an ordered collection of transformations to a state variable. Many specific cases can be implemented more efficiently.</p><p>How? Here’s a generic C# implementation:</p><pre>using UnityEngine;<br>using System.Collections;<br>using System.Collections.Generic;<br>using System;</pre><pre>// This is the part mutating modules apply to the LensedValue <br>public class Lens&lt;T&gt;{<br>  public int priority;<br>  public Func&lt;T,T&gt; transformation;</pre><pre>  public Lens(int priority, Func&lt;T,T&gt; transformation){<br>    this.priority = priority;<br>    this.transformation = transformation;<br>  }<br>}</pre><p>Then we have the LensedValue class itself:</p><pre>// This class represents the shared state and has the GetValue() <br>// method that returns the value rendered through the lenses.<br>class LensedValue&lt;T&gt; {</pre><pre>T value;<br>  List&lt;Lens&lt;T&gt;&gt; lenses;<br> <br>  public LensedValue(T initialValue){<br>    this.value = initialValue;<br>    this.lenses = new List&lt;Lens&lt;T&gt;&gt;();<br>  }<br> <br>  public LensToken AddLens(Lens&lt;T&gt; lens){<br>    lenses.Add(lens);<br>    lenses.Sort((x,y)=&gt; x.priority - y.priority);<br>    return new LensToken(<br>      () =&gt; lenses.Remove(lens)<br>    );<br>  }<br> <br>  public T GetValue(){<br>    T tmp = value;<br>    foreach(var lens in lenses){<br>      tmp = lens.transformation(tmp);<br>    }<br>    return tmp;<br>  }<br>}</pre><p>and LensToken for removing lenses when they are no longer useful:</p><pre>// LensToken is a simple class used to keep a token to remove<br>// a Lens from a LensedValue<br>class LensToken{<br> <br>  Action action;<br> <br>  public LensToken(Action action){<br>    this.action = action;<br>  }<br> <br>  public void Remove(){<br>    action();<br>  }<br>}</pre><p>And here’s an example of how you might use it for the toy problem of tracking a player’s dealt damage we discussed earlier:</p><pre>class Player{<br>    public static LensedValue&lt;float&gt; damage = <br>        new LensedValue&lt;float&gt;(10);<br>}</pre><pre>public class LensExampleDamage : MonoBehaviour {</pre><pre>enum DamageType{<br>        Base = 0,<br>        Multiplier = 1,<br>        Percentage = 2<br>    }</pre><pre>void Start () {<br>        Debug.Log(Player.damage.GetValue()); // 10<br>        <br>        var multDmgLensToken = Player.damage.AddLens(<br>            new Lens&lt;float&gt;(<br>                (int)DamageType.Multiplier, (dmg)=&gt; dmg * 2)<br>            );<br>            <br>        Debug.Log(Player.damage.GetValue()); // 20<br>        <br>        var baseDmgLensToken = Player.damage.AddLens(<br>            new Lens&lt;float&gt;(<br>                (int)DamageType.Base, (dmg)=&gt; dmg + 5)<br>            );<br>            <br>        Debug.Log(Player.damage.GetValue()); // 30<br>        <br>        <br>        var multDmgLensToken2 = Player.damage.AddLens(<br>            new Lens&lt;float&gt;(<br>                (int)DamageType.Multiplier, (dmg)=&gt; dmg * 1.5f)<br>            );<br>            <br>        Debug.Log(Player.damage.GetValue()); // 45</pre><pre>        multDmgLensToken.Remove();<br>        Debug.Log(Player.damage.GetValue()); // 22.5<br>    }<br>}</pre><p>Of course this is a toy example (the two other examples discussed above are <a href="https://github.com/TwistedOakStudios/TOUnityUtilities/blob/master/Assets/Lenses/LensExamplePause.cs">here</a> and <a href="https://github.com/TwistedOakStudios/TOUnityUtilities/blob/master/Assets/Lenses/LensExampleActions.cs">here</a>), but it shows how easily multiple modules can mutate and read a LensedValue without concern for each other.</p><p>There are some obvious extensions we can make:</p><ul><li>use atomic operations to add/remove lenses, so many threads can add lenses without blocking reads or corrupting data</li><li>add optional caching of the LensedValue for Lenses that only use <em>pure functions </em>for their transformations.</li><li>add special types of LensedValue (say IdempotentLensedValue) to support particular optimizations (i.e. if lens rendering order doesn’t matter or mutations can be replaced with a simple counter as in the <a href="https://github.com/TwistedOakStudios/TOUnityUtilities/blob/master/Assets/Lenses/LensExamplePause.cs">pause example</a>).</li></ul><p>To summarize, we’ve looked at Lenses as a way of decoupling shared state between software processes, and a few examples from game development. There’s lots of improvements and optimizations to make, and I’d love for you to share yours with the community!</p><p>If you have any comments or questions, feel free to post here or get in touch <a href="https://twitter.com/horsman">on Twitter</a> and if you need some help with a technical project, <a href="http://www.twistedoak.co/">check out Twisted Oak</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6318951cad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applications of the Vector Dot Product for Game Programming]]></title>
            <link>https://medium.com/hackernoon/applications-of-the-vector-dot-product-for-game-programming-12443ac91f16?source=rss-c39dc3a9e320------2</link>
            <guid isPermaLink="false">https://medium.com/p/12443ac91f16</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[game-programming]]></category>
            <dc:creator><![CDATA[Devin Horsman]]></dc:creator>
            <pubDate>Tue, 20 Sep 2016 14:50:13 GMT</pubDate>
            <atom:updated>2019-06-21T13:58:32.719Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I wrote this 5 years ago but never posted it anywhere. A friend’s tweet reminded me it was in my drafts and I figured it could be useful to someone.</em></p><p>The dot product is a function that can be applied to two equal dimension vectors and is sometimes referred to as the scalar or inner product by people of lower moral fiber. Typically you’ll see the dot product defined as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/0*Up336WJl5thSJNEt.png" /><figcaption>bold letters are vectors, ||‘s surrounding a vector means the magnitude or length of the vector, and 𝜃 (pronounced “theta”) is the angle between the two vectors.</figcaption></figure><p>Look scary? In other words the dot product is the cosine of the angle between two vectors multiplied by their lengths. Initially it seems to be of pretty limited use but in practice it pops up all over. Let us look at a few:</p><h3>Measuring direction</h3><p>If you looked closely the first thing you may have noticed is that you can get the cosine of the angle between two vectors with a bit of rearranging:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/0*rWZs0HYpPAi3ByC4.png" /></figure><p>And then use <em>arccos </em>function (also known as <em>cos^-1</em>)to get the angle or just test against cosine values for typical angles if you want to be cheaper than <a href="https://hackernoon.com/tagged/ikea">IKEA</a> furniture with your <a href="https://hackernoon.com/tagged/cpu">CPU</a> cycles. If both vectors <strong>x</strong> and <strong>y</strong> are unit length (we usually indicate this by putting a ^ symbol above the vector, but I’ve omitted the ^’s in the paragraphs here since medium doesn’t support it) then we don’t need the division or calculation of the vector’s length and can save square roots. If we look a little closer at this equation and the properties of the cosine we can see some shortcuts we can take:</p><ul><li>Since the only way a negative number can be introduced to this equation is the cosine function, the result of the dot product is negative if and only if the vectors point in a direction greater than pi/2 radians (90 degrees) apart from one another. The simple takeaway: negative dot product means the vectors point in different directions.</li><li>If the dot product is zero the two vectors are orthogonal (perpendicular).</li><li>If the vectors are unit length and the result of the dot product is 1, the vectors are equal.</li></ul><h3>Projecting Vectors</h3><p>Say we want to know how much a vector is displacing in a certain direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*8mSAMcSuGR-E-nmH.png" /></figure><p>Example uses include calculating the speed at which a character is moving in the direction of a slope or wall, finding how much of a character’s velocity is in the direction of gravity, finding how long until a movement crosses a threshold, and more.</p><p>When at least one vector is of unit length the dot product is the length of the projection of the non-unit length vector onto the axis of the normalized vector (When they are both unit length, they are both moving the same amount in the direction of each other).</p><p>A reader pointed out that the term <em>normalized vector </em>(referring to a vector that is unit length pointing in the same direction of some vector, an operation called normalizing) and a <em>normal vector </em>(referring to a vector perpendicular to a surface’s local plane) can be confusing for people newer to vector math. Its an unfortunate naming collision, but now you know — they are two different things. Ok. Let’s move on, because I’m about to refer to the other one now.</p><h3>Planes (aka walls/slopes/triangles)</h3><p>Given a plane defined by a unit normal vector <strong>n </strong>and point <strong>p</strong>, we can find which side of the plane a vector <strong>x</strong> is by seeing if the result of the following equation is positive, zero or negative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*zCLUoe--kLSR3EYK.png" /><figcaption>positive indicates in front of the plane, negative behind, and zero indicates the point is coincident with the plane.</figcaption></figure><p>We might also want to reflect a vector about a plane. Say we have a point mass at point <strong>x</strong> travelling with velocity <strong>v</strong>. We test whether a collision will occur in time slice <em>dt</em> by checking if <strong>x + v</strong><em>dt</em><strong><em> </em></strong>is on the opposite side of the plane as <strong>x</strong>. Once we have confirmed a collision (for our purposes it will be an elastic collision), we need to find out where the point mass has ended up. Assuming the plane is fixed (has a weight of infinity) the point mass will reflect with the same velocity about the normal of the plane. The new velocity is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/0*3L_U0ZPkIfGPkyOm.png" /></figure><p>The new position is given by the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/0*kC2iKNPAHgZKxO03.png" /></figure><p>This diagram shows the relationships above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*DU1G90Snix-lvq-owZPc7w.png" /></figure><h3>Can I see it?</h3><p>We frequently want to know if some object is in the field of view of some observer in our game. Given an observer at point <strong>p</strong>, an object at point <strong>o</strong>, and assuming the object is not obstructed from view (test this with one or several raycasts), take the dot product of the observers viewing direction <strong>v </strong>with the normalized vector from the observer to the object. The result is the cosine of the angle between them. Test against the cosine of the max viewing angle <em>cphi</em> of the observer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*orFBpuv2R_ua2IoE.png" /></figure><h3>Next Steps</h3><p>Here’s a few dot product tricks but there are many more to discover. Drop a comment if you have a useful trick or interpretation. If you’re feeling confident maybe you’d like to venture on to the <a href="https://en.wikipedia.org/wiki/Cross_product">cross product</a> next?</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><a href="https://goo.gl/Ahtev1"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></a></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12443ac91f16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/applications-of-the-vector-dot-product-for-game-programming-12443ac91f16">Applications of the Vector Dot Product for Game Programming</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>