• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Scala-Robotics-Simulator / PPS-22-srs / #206

07 Aug 2025 03:55PM UTC coverage: 71.334% (-12.7%) from 84.0%
#206

Pull #22

github

GiuliaNardicchia
refactor: add end extension to Rand for scalafmt
Pull Request #22: feat: simulation engine

59 of 226 new or added lines in 16 files covered. (26.11%)

3 existing lines in 1 file now uncovered.

647 of 907 relevant lines covered (71.33%)

10.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/main/scala/io/github/srs/controller/ControllerModule.scala
1
package io.github.srs.controller
2

3
import scala.compiletime.deferred
4
import scala.concurrent.duration.FiniteDuration
5

6
import cats.syntax.foldable.toFoldableOps
7
import io.github.srs.model.*
8
import io.github.srs.model.SimulationConfig.SimulationStatus
9
import io.github.srs.model.UpdateLogic.*
10
import io.github.srs.model.logic.*
11
import monix.catnap.ConcurrentQueue
12
import monix.eval.Task
13

14
/**
15
 * Module that defines the controller logic for the Scala Robotics Simulator.
16
 */
17
object ControllerModule:
18

×
19
  /**
20
   * Controller trait that defines the interface for the controller.
21
   *
22
   * @tparam S
23
   *   the type of the state, which must extend [[ModelModule.State]].
24
   */
25
  trait Controller[S <: ModelModule.State]:
26
    /**
×
27
     * Starts the controller with the initial state.
28
     *
29
     * @param initialState
30
     *   the initial state of the simulation.
31
     */
32
    def start(initialState: S): Task[Unit]
33

34
    /**
35
     * Runs the simulation loop, processing events from the queue and updating the state.
36
     *
37
     * @param s
38
     *   the current state of the simulation.
39
     * @param queue
40
     *   a concurrent queue that holds events to be processed.
41
     * @return
42
     *   a task that completes when the simulation loop ends.
43
     */
44
    def simulationLoop(s: S, queue: ConcurrentQueue[Task, Event]): Task[Unit]
45

46
  end Controller
47

48
  /**
49
   * Provider trait that defines the interface for providing a controller.
50
   * @tparam S
51
   *   the type of the state, which must extend [[ModelModule.State]].
52
   */
53
  trait Provider[S <: ModelModule.State]:
54
    val controller: Controller[S]
55

56
  /**
57
   * Defines the dependencies required by the controller module. In particular, it requires a
58
   * [[io.github.srs.view.ViewModule.Provider]] and a [[io.github.srs.model.ModelModule.Provider]].
59
   */
60
  type Requirements[S <: ModelModule.State] =
61
    io.github.srs.view.ViewModule.Provider[S] & io.github.srs.model.ModelModule.Provider[S]
62

63
  /**
64
   * Component trait that defines the interface for creating a controller.
65
   * @tparam S
66
   *   the type of the simulation state, which must extend [[ModelModule.State]].
67
   */
68
  trait Component[S <: ModelModule.State]:
69
    context: Requirements[S] =>
×
70
    given inc: IncrementLogic[S] = deferred
71
    given tick: TickLogic[S] = deferred
72
    given pause: PauseLogic[S] = deferred
73
    given resume: ResumeLogic[S] = deferred
74
    given stop: StopLogic[S] = deferred
75

76
    object Controller:
77
      /**
×
78
       * Creates a controller instance.
79
       *
80
       * @return
81
       *   a [[Controller]] instance.
82
       */
83
      def apply(): Controller[S] = new ControllerImpl
84

×
85
      /**
86
       * Private controller implementation that delegates the simulation loop to the provided model and view.
87
       */
88
      private class ControllerImpl extends Controller[S]:
89

×
90
        override def start(initialState: S): Task[Unit] =
NEW
91
          val randInt: Int = initialState.simulationRNG.nextIntBetween(0, 10_000)._1
×
NEW
92
          val list = List.fill(randInt)(Event.Increment)
×
NEW
93
          for
×
NEW
94
            queueSim <- ConcurrentQueue.unbounded[Task, Event]()
×
NEW
95
            _ <- context.view.init(queueSim)
×
96
            //            queueLog <- ConcurrentQueue.unbounded[Task, Event]()
97
            _ <- produceEvents(queueSim, list)
98
            _ <- simulationLoop(initialState, queueSim)
99
          //            _ <- Task.parMap2(
100
          //              simulationLoop(initialState, queueSim),
101
          //              consumeStream(queueLog)(event => Task(println(s"Received: $event")))
102
          //            )((_, _) => ())
103
          yield ()
NEW
104

×
105
        override def simulationLoop(s: S, queue: ConcurrentQueue[Task, Event]): Task[Unit] =
NEW
106
          def loop(state: S): Task[Unit] =
×
NEW
107
            for
×
NEW
108
              events <- queue.drain(0, 50)
×
NEW
109
              newState <- handleEvents(events, state)
×
110
              _ <- context.view.render(newState)
111
              nextState <-
112
                if newState.simulationStatus == SimulationStatus.RUNNING then
113
                  tickEvents(newState.simulationSpeed.tickSpeed, newState)
114
                else Task.pure(newState)
115
              stop = newState.simulationStatus == SimulationStatus.STOPPED ||
116
                newState.simulationTime.exists(max => newState.elapsedTime >= max)
117
              _ <- if stop then Task.unit else loop(nextState)
118
            yield ()
NEW
119

×
120
          loop(s)
NEW
121

×
122
        //        private def consumeStream[A](queue: ConcurrentQueue[Task, A])(consume: A => Task[Unit]): Task[Unit] =
123
        //          Observable
124
        //            .repeatEvalF(queue.poll)
125
        //            .mapEval(consume)
126
        //            .completedL
127

128
        private def produceEvents[A](queue: ConcurrentQueue[Task, A], events: List[A]): Task[Unit] =
NEW
129
          events.traverse_(queue.offer)
×
NEW
130

×
131
        private def tickEvents(tickSpeed: FiniteDuration, state: S): Task[S] =
NEW
132
          for
×
NEW
133
            _ <- Task.sleep(tickSpeed)
×
NEW
134
            tick <- handleEvent(Event.Tick(tickSpeed), state)
×
135
          yield tick
NEW
136

×
137
        private def handleEvents(events: Seq[Event], state: S): Task[S] =
NEW
138
          for finalState <- events.foldLeft(Task.pure(state)) { (taskState, event) =>
×
NEW
139
              for
×
140
                currentState <- taskState
141
                newState <- handleEvent(event, currentState)
142
              yield newState
143
            }
NEW
144
          yield finalState
×
NEW
145

×
146
        private def handleEvent(event: Event, state: S): Task[S] =
NEW
147
          event match
×
NEW
148
            case Event.Increment if state.simulationStatus == SimulationStatus.RUNNING =>
×
NEW
149
              context.model.increment(state)
×
NEW
150
            case Event.Tick(deltaTime) if state.simulationStatus == SimulationStatus.RUNNING =>
×
NEW
151
              context.model.tick(state, deltaTime)
×
NEW
152
            case Event.Pause => context.model.pause(state)
×
NEW
153
            case Event.Resume => context.model.resume(state)
×
NEW
154
            case Event.Stop => context.model.stop(state)
×
NEW
155
            case Event.TickSpeed(speed) => context.model.tickSpeed(state, speed)
×
NEW
156
            case _ => Task.pure(state)
×
NEW
157

×
158
      end ControllerImpl
159

160
    end Controller
161

162
  end Component
163

164
  /**
165
   * Interface trait that combines the provider and component traits for the controller module.
166
   *
167
   * @tparam S
168
   *   the type of the simulation state, which must extend [[ModelModule.State]].
169
   */
170
  trait Interface[S <: ModelModule.State] extends Provider[S] with Component[S]:
171
    self: Requirements[S] =>
172
end ControllerModule
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc