<h2 id="intro">Intro</h2>
<p>Last time we looked how to model technology and research. This time we’ll do some actual research. I’m skipping over some of the details as the episode is long enough as it is. Hopefully it’s still possible to follow with the show notes.</p>
<p>Main concepts that I’m mentioning: Technology allows usage of specific buildings, ship components and such. Research unlock technologies and may have antecedents that has to be completed before the research can be started. Research cost is measure of how expensive a research is in terms of research points, which are produced by different buildings.</p>
<p>Earlier I modeled tech tree as Map that had Technology as keys and Research as values. I realized that this is suboptimal and will replace it at some point in the future.</p>
<h2 id="server-api">Server API</h2>
<p>There’s three resources that client can connect to. First one is for retrieving list of available research, second one for manipulating current research and last one for retrieving info on how much research points is being produced.</p>
<pre><code>/api/research/available     ApiAvailableResearchR       GET
/api/research/current       ApiCurrentResearchR         GET POST DELETE
/api/research/production    ApiResearchProductionR      GET</code></pre>
<h2 id="simulation">Simulation</h2>
<p>Simulation of research is done by <code>handleFactionResearch</code>, which does simulation for one faction for a given date. After calculating current research point production and retrieving list of current research, function calculates progress of current researches. Unfinished ones are written back to database, while completed are moved into <code>completed_research</code> table. Final step is updating what research will be available in the next turn.</p>
<pre><code>handleFactionResearch date faction = do
    production &lt;- totalProduction $ entityKey faction
    current &lt;- selectList [ CurrentResearchFactionId ==. entityKey faction ] []
    let updated = updateProgress production &lt;$&gt; current
    _ &lt;- updateUnfinished updated
    _ &lt;- handleCompleted date updated $ entityKey faction
    _ &lt;- updateAvailableResearch $ entityKey faction
    return ()</code></pre>
<h2 id="research-point-production">Research point production</h2>
<p>Research points are produced by buildings. So first step is to load all planets owned by the faction and buildings on those planets. Applying <code>researchOutput</code> function to each building yields a list of <code>TotalResearchScore</code>, which is then summed up by <code>mconcat</code>. We can use <code>mconcat</code> as <code>TotalResearchScore</code> is a monoid (I talked about these couple episodes ago).</p>
<pre><code>totalProduction fId = do
    pnbs &lt;- factionBuildings fId
    let buildings = join $ fmap snd pnbs
    return $ mconcat $ researchOutput . entityVal &lt;$&gt; buildings</code></pre>
<p><code>researchOutput</code> function below uses pattern matching. Instead of writing one function definition and case expression inside of it, we’re writing multiple definitions. Each of them matches building of different type. First example is definition that is used for <code>ResearchComplex</code>, while second one is for <code>ParticleAccelerator</code>. Final case uses underscore to match anything and indicate that we’re not even interested on the particular value being matched. <code>mempty</code> is again from our monoid definition. It is empty or unit value of monoid, which in case of <code>TotalResearchScore</code> is zero points in all research categories.</p>
<pre><code>researchOutput Building { buildingType = ResearchComplex } =
    TotalResearchScore
    { totalResearchScoreEngineering = ResearchScore 10
    , totalResearchScoreNatural = ResearchScore 10
    , totalResearchScoreSocial = ResearchScore 10
    }

researchOutput Building { buildingType = ParticleAccelerator } =
    TotalResearchScore
    { totalResearchScoreEngineering = ResearchScore 15
    , totalResearchScoreNatural = ResearchScore 15
    , totalResearchScoreSocial = ResearchScore 0
    }

researchOutput _ = mempty</code></pre>
<h2 id="updating-progress">Updating progress</h2>
<p>Moving research forward is more complex looking function. There’s bunch of filtering and case expressions going on, but the idea is hopefully clear after a bit of explanation.</p>
<p><code>updateProgress</code> takes two parameters, total production of research points and current research that is being modified. This assumes that there are only one of each categories of research going on at any given time. If there were more, we would have to divide research points between them by some logic. Function calculates effect of research points on current research and produces a new current research that is the end result.</p>
<p>Perhaps the most interesting part is use of lenses. For example, line <code>entityValL . currentResearchProgressL +~ engResearch $ curr</code> means that <code>curr</code> (which is <code>Entity CurrentResearch</code>) is used as starting point. First we reach to data part of <code>Entity</code> and then we focus on <code>currentResearchProgress</code> and add <code>engResearch</code> to it. This results a completely new <code>Entity CurrentResearch</code> being constructed, which is otherwise identical with the original, but the <code>currentResearchProgress</code> has been modified. Without lenses we would have to do this destructuring and restructuring manually.</p>
<pre><code>updateProgress :: TotalResearchScore ResearchProduction -&gt; Entity CurrentResearch -&gt; Entity CurrentResearch
updateProgress prod curr =
    case researchCategory &lt;$&gt; research of
        Just (Engineering _) -&gt;
            entityValL . currentResearchProgressL +~ engResearch $ curr

        Just (NaturalScience _) -&gt;
            entityValL . currentResearchProgressL +~ natResearch $ curr

        Just (SocialScience _) -&gt;
            entityValL . currentResearchProgressL +~ socResearch $ curr

        Nothing -&gt;
            curr
    where
        research = Map.lookup (currentResearchType . entityVal $ curr) techMap
        engResearch = unResearchScore $ totalResearchScoreEngineering prod
        natResearch = unResearchScore $ totalResearchScoreNatural prod
        socResearch = unResearchScore $ totalResearchScoreSocial prod</code></pre>
<p>Writing unfinished research back to database is short function. First we find ones that hasn’t been finished by filtering with <code>(not . researchReady . entityVal)</code> and then we apply <code>replace</code> to write them back one by one.</p>
<pre><code>updateUnfinished updated = do
    let unfinished = filter (not . researchReady . entityVal) updated
    mapM (\x -&gt; replace (entityKey x) (entityVal x)) unfinished</code></pre>
<p>Handling finished research starts by finding out which ones were actually completed by filtering with <code>(researchReady . entityVal)</code> and their research type with <code>currentResearchType . entityVal</code>. Rest of the function is all about database actions: creating entries into <code>completed_research</code> and adding news entries for each completed research, then removing entries from <code>current_research</code> and <code>available_research</code>.</p>
<pre><code>handleCompleted date updated fId = do
    let finished = filter (researchReady . entityVal) updated
    let finishedTech = currentResearchType . entityVal &lt;$&gt; finished
    insertMany_ $ currentToCompleted date . entityVal &lt;$&gt; finished
    insertMany_ $ researchCompleted date fId . (currentResearchType . entityVal) &lt;$&gt; finished
    deleteWhere [ CurrentResearchId &lt;-. fmap entityKey finished ]
    deleteWhere [ AvailableResearchType &lt;-. finishedTech
                , AvailableResearchFactionId ==. fId ]</code></pre>
<h2 id="available-research">Available research</h2>
<p>Figuring out what researches will be available for the next turn takes several steps. I won’t be covering random numbers in detail, they’re interesting enough for an episode on their own. It’s enough to know that <code>g &lt;- liftIO getStdGen</code> gets us a new random number generator that is seeded by current time.</p>
<p><code>updateAvailableResearch</code> starts by loading available research and current research for the faction and initializing a new random number generator. <code>g</code> can be used multiple times, but it’ll always return same sequence of numbers. Here it doesn’t matter, but in some cases it might. <code>getR</code> is helper function I wrote that uses random number generator to pick <code>n</code> entries from a given list. <code>n</code> in our case is hard coded to 3, but later on I’ll add possibility for player to research technologies that raise this limit. <code>newAvailableResearch</code> (we’ll look into its implementation closer just in a bit) produces a list of available research for specific research category. These lists are combined with <code>&lt;&gt;</code> operator and written into database with <code>rewriteAvailableResearch</code>.</p>
<pre><code>updateAvailableResearch fId = do
    available &lt;- selectList [ AvailableResearchFactionId ==. fId ] []
    completed &lt;- selectList [ CompletedResearchFactionId ==. fId ] []
    g &lt;- liftIO getStdGen
    let maxAvailable = ResearchLimit 3
    -- reusing same g should not have adverse effect here
    let engCand = getR g (unResearchLimit maxAvailable) $ newAvailableResearch isEngineering maxAvailable available completed
    let natCand = getR g (unResearchLimit maxAvailable) $ newAvailableResearch isNaturalScience maxAvailable available completed
    let socCand = getR g (unResearchLimit maxAvailable) $ newAvailableResearch isSocialScience maxAvailable available completed
    rewriteAvailableResearch fId $ engCand &lt;&gt; natCand &lt;&gt; socCand</code></pre>
<p><code>newAvailableResearch</code> is in charge of figuring out what, if any, new research should be available in the next turn. In case where amount of currently available research is same or greater than research limit, empty list is returned, otherwise function calculates candidates and returns them. Logic for that is following:</p>
<ul>
<li>candidates are research of specific category of those that has been unlock and unresearched</li>
<li>unlocked and unresearched are unlocked ones that are in list of known technology</li>
<li>unlocked research are ones with antecedents available in tech tree</li>
<li>known technology are ones in list of completed research</li>
</ul>
<p>and complete definition of the function is shown below:</p>
<pre><code>newAvailableResearch selector limit available completed =
    if ResearchLimit (length specificCategory) &gt;= limit
        then []
        else candidates
    where
        specificCategory = filter (availableResearchFilter selector) available
        candidates = filter (selector . researchCategory) unlockedAndUnresearched
        unlockedAndUnresearched = filter (\x -&gt; researchType x `notElem` knownTech) unlockedResearch
        unlockedResearch = filter (antecedentsAvailable knownTech) $ unTechTree techTree
        knownTech = completedResearchType . entityVal &lt;$&gt; completed


availableResearchFilter f x =
    maybe False (f . researchCategory) res
    where
        res = Map.lookup (availableResearchType $ entityVal x) techMap</code></pre>
<p>Final step of the simulation of research is to update database with new available research. <code>mkUniq</code> is helper function that removes duplicate elements from a list. It’s used in <code>rewriteAvailableResearch</code> function to make a list that contains all unique top research categories (engineering, natural sciences and social sciences). If the resulting list isn’t empty, we’ll use it to remove all available research for those top categories and insert new available research.</p>
<pre><code>rewriteAvailableResearch fId res = do
    let cats = mkUniq $ fmap (topCategory . researchCategory) res
    unless (null cats) $ do
        deleteWhere [ AvailableResearchFactionId ==. fId
                    , AvailableResearchCategory &lt;-. cats ]
        insertMany_ $ researchToAvailable fId &lt;$&gt; res</code></pre>
<p>Now everything is ready for next round of simulation.</p>
