mischief-ecs
Safe HaskellNone
LanguageGHC2024

Mischief.ECS.Tutorial.Guides.MonadicQueries

Description

Synopsis

    Learn You an ECS for Great Mischief! - 2.4. Monadic Queries

    Finally we get to talk about the most powerful querying tool: monadic queries.

    Reasoning

    Querying and manipulating data can look and feel very messy in an imperative context. You'd generally access the data, and then iterate through it to perform certain effects:

    players <- query [q|Name, Position / With Player|]
    for_ players $ \(name, Position p) -> do
      ...
    

    Similarly, you may want to access a resource which may not exist. You're forced to either take the risk, or make all following logic depend on the resource existing:

    r <- res @SomeRes
    for_ r $ \r -> do
      ...
    

    This may seem fine in a short example but the nesting becomes unwieldy and unmaintainbale very quickly as the logic gets more complex.

    Queries provide an alternate access mode, letting you expand vertically instead of nesting:

    query_ $ do
      r <- qres @SomeRes
      (name, Position p) <- [q|Name, Position / With Player|]
      ...
    

    This mode isn't meant to replace the imperative one, but to be used in conjuction with it. You go into queries to grab data, and then write systems to modify it.

    Binding

    Monadic queries are usually written by using one of the query runners (query_, query, single), followed by a do:

    query_ $ do
      playerName <- [q|Name / With Player|]
      pure ()
    

    When you bind a value out of a query (the <- above), you are immediately iterating over all elements of a query and applying operations to them. It is in a way similar to the List monad if you are familiar with it.

    The main rule to be aware of, is that each time you bind a new value, you are creating a new loop inside the previous one. For instance, this code:

    query_ $ do
      playerName <- [q|Name / With Player|]
      enemyName <- [q|Name / With Enemy|]
      ...
    

    Is, in essence:

    for playerName in [q|Name / With Player|]:
      for enemyName in [q|Name / With Enemy|]:
        ...
    

    Similarly, grabbing a resource using qres creates a loop over a list of either one or no elements.

    query_ $ do
      r <- qres @SomeRes
      ...
    
    for r in res @SomeRes:
      ...
    

    A nice and extrmely useful consequence of this is that iterating over nothing, such as when grabbing a resource that doesn't exist, will naturally stop the execution of all following instructions, since they are placed inside the empty loop.

    You can also stop a query from progressing at any point by using empty which will create a loop over an empty list and nullify everything downwards. guard can be used to stop it conditionally. As you've seen a long time ago, this is how we can only pick some entities to apply an effect over:

    query_ $ do
      (e, name) <- [q|E, Name / With Person|]
      guard $ name == Name Florian
      qinsert (Name Florianne) e
    

    Lifting

    Effects can be applied inside a Query by lifting back to a System:

    query_ $ do
      (e, Position p, Velocity v) <- [q|E, Position, Velocity|]
      qlift $ insert (Position $ p + v) e
    

    A lot of common System functions have lifted equivalents: qinsert, qinfo, qwarn, qremove, to name a few. They are only a convenience however; don't be afraid to use qlift when such a function isn't provided.

    Up and Down

    You've seen that binding with <- pushes you to a deeper nest level. It takes you down.

    The opposite operation is one that collects the results of a deeper query, lifting them up to your previous level:

    playerPos <- [q|Position / With Player|]
    enemies <- qcollect $ do
      (name, pos) <- [q|Name, Position / With Enemy|]
      guard $ pos == playerPos
      pure name
    

    Here you go to the level of iterating over players. You then go to each enemy, and if they are at the same position as the player, you give back their name. This is all caught by qcollect and gathered into a list of names that you have access to at the player level.

    Another powerful primitive is qiter, which does the opposite: it takes something you can iterate over (such as a list or a Maybe) and attaches it to the query, creating a deeper nest:

    name <- qiter enemies
    qinfo [i|Enemy name: #{name}|]
    

    A trivial but handy function is qlifter, which lifts a System action and then performs qiter on it. Imagine that you have a System:

    f :: Entity -> System (Maybe Entity)
    

    You can grab its value from within a query like this:

    query_ $ do
      player <- [q|E / With Player|]
      x <- qlifter player
    

    Getting More Components

    Assuming you already have an entity and you want to grab more of its components, you can use this shortcut:

    query_ $ do
      player <- [q|E / With Player|]
      (name, pos) <- [q|player. Name, Position|]
    

    The player. at the start of the quasi-query means it will directly access the place where that entity is stored and grab its components in O(1). If it doesn't have those components, the query will stop early.

    Traversals

    You can use the aforementioned qlifter function to easily traverse hierarchies. Mischief provides useful functions in these two modules:

    import Mischief.ECS.Relationships.Graph qualified as Graph
    import Mischief.ECS.Relationships.Tree qualified as Tree
    

    Graph provides the incoming and outgoing functions. Tree provides some more specific functions for working with tree-like hierarchies, such as descendants and root.

    You can iterate over all players and then their children like this:

    player <- [q|E / With Player|]
    child <- qlifter $ Graph.incoming player
    

    We can find the root of each enemy like this:

    enemy <- [q|E / With Enemy|]
    root <- qlifter $ Tree.root enemy
    

    Next Chapter: Quasi-Query Conversion