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

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

28 Aug 2025 03:19PM UTC coverage: 47.202% (-0.2%) from 47.411%
#426

Pull #70

github

GiuliaNardicchia
refactor: enhance simulation closing and elapsed time handling in CLI, GUI and controller
Pull Request #70: refactor: simulation view closing and elapsed time

0 of 33 new or added lines in 9 files covered. (0.0%)

5 existing lines in 4 files now uncovered.

1282 of 2716 relevant lines covered (47.2%)

6.69 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.concurrent.duration.{ DurationInt, FiniteDuration, MILLISECONDS }
4
import scala.language.postfixOps
5

6
import cats.effect.std.Queue
7
import cats.effect.{ Clock, IO }
8
import cats.syntax.all.*
9
import io.github.srs.controller.message.RobotProposal
10
import io.github.srs.controller.protocol.Event
11
import io.github.srs.model.*
12
import io.github.srs.model.SimulationConfig.SimulationStatus.*
13
import io.github.srs.model.entity.dynamicentity.Robot
14
import io.github.srs.model.entity.dynamicentity.behavior.BehaviorContext
15
import io.github.srs.model.entity.dynamicentity.sensor.Sensor.senseAll
16
import io.github.srs.model.logic.*
17
import io.github.srs.utils.EqualityGivenInstances.given_CanEqual_Event_Event
18
import io.github.srs.utils.SimulationDefaults.debugMode
19

20
/**
21
 * Module that defines the controller logic for the Scala Robotics Simulator.
22
 */
23
object ControllerModule:
24

×
25
  /**
26
   * Controller trait that defines the interface for the controller.
27
   *
28
   * @tparam S
29
   *   the type of the state, which must extend [[ModelModule.State]].
30
   */
31
  trait Controller[S <: ModelModule.State]:
32
    /**
×
33
     * Starts the controller with the initial state.
34
     *
35
     * @param initialState
36
     *   the initial state of the simulation.
37
     */
38
    def start(initialState: S): IO[S]
39

40
    /**
41
     * Runs the simulation loop, processing events from the queue and updating the state.
42
     *
43
     * @param s
44
     *   the current state of the simulation.
45
     * @param queue
46
     *   a concurrent queue that holds events to be processed.
47
     * @return
48
     *   an [[IO]] task that completes when the simulation loop ends.
49
     */
50
    def simulationLoop(s: S, queue: Queue[IO, Event]): IO[S]
51

52
  end Controller
53

54
  /**
55
   * Provider trait that defines the interface for providing a controller.
56
   *
57
   * @tparam S
58
   *   the type of the state, which must extend [[ModelModule.State]].
59
   */
60
  trait Provider[S <: ModelModule.State]:
61
    val controller: Controller[S]
62

63
  /**
64
   * Defines the dependencies required by the controller module. In particular, it requires a
65
   * [[io.github.srs.view.ViewModule.Provider]] and a [[io.github.srs.model.ModelModule.Provider]].
66
   */
67
  type Requirements[S <: ModelModule.State] =
68
    io.github.srs.view.ViewModule.Provider[S] & io.github.srs.model.ModelModule.Provider[S]
69

70
  /**
71
   * Component trait that defines the interface for creating a controller.
72
   *
73
   * @tparam S
74
   *   the type of the simulation state, which must extend [[ModelModule.State]].
75
   */
76
  trait Component[S <: ModelModule.State]:
77
    context: Requirements[S] =>
×
78

79
    object Controller:
80

×
81
      /**
82
       * Creates a controller instance.
83
       *
84
       * @return
85
       *   a [[Controller]] instance.
86
       */
87
      def apply()(using bundle: LogicsBundle[S]): Controller[S] = new ControllerImpl
88

×
89
      /**
90
       * Private controller implementation that delegates the simulation loop to the provided model and view.
91
       */
92
      private class ControllerImpl(using bundle: LogicsBundle[S]) extends Controller[S]:
93

×
94
        /**
95
         * Starts the controller with the initial state.
96
         * @param initialState
97
         *   the initial state of the simulation.
98
         * @return
99
         *   an [[IO]] task that completes when the controller is started.
100
         */
101
        override def start(initialState: S): IO[S] =
102
          for
×
103
            queueSim <- Queue.unbounded[IO, Event]
×
104
            _ <- context.view.init(queueSim)
×
105
            _ <- runBehavior(queueSim, initialState)
106
            result <- simulationLoop(initialState, queueSim)
107
          yield result
108

×
109
        /**
110
         * Runs the simulation loop, processing events from the queue and updating the state.
111
         * @param s
112
         *   the current state of the simulation.
113
         * @param queue
114
         *   a concurrent queue that holds events to be processed.
115
         * @return
116
         *   an [[IO]] task that completes when the simulation loop ends.
117
         */
118
        override def simulationLoop(s: S, queue: Queue[IO, Event]): IO[S] =
119
          def loop(state: S): IO[S] =
×
120
            for
×
121
              startTime <- Clock[IO].realTime.map(_.toMillis)
×
122
              _ <- runBehavior(queue, state).whenA(state.simulationStatus == RUNNING)
×
123
              events <- queue.tryTakeN(Some(50))
×
124
              newState <- handleEvents(state, events)
125
              _ <- context.view.render(newState)
126
              result <- handleStopCondition(newState) match
127
                case Some(io) => io
128
                case None =>
129
                  for
130
                    nextState <- nextStep(newState, startTime)
131
                    endTime <- Clock[IO].realTime.map(_.toMillis)
132
                    _ <- if debugMode then IO.println(s"Simulation loop took ${endTime - startTime} ms") else IO.unit
133
                    res <- loop(nextState)
134
                  yield res
135
            yield result
136

×
137
          loop(s)
138

×
139
        end simulationLoop
140

141
        private def handleStopCondition(state: S): Option[IO[S]] =
NEW
142
          state.simulationStatus match
×
NEW
143
            case STOPPED =>
×
NEW
144
              Some(context.view.close() *> IO.pure(state))
×
NEW
145
            case ELAPSED_TIME =>
×
NEW
146
              Some(context.view.timeElapsed(state) *> IO.pure(state))
×
NEW
147
            case _ =>
×
NEW
148
              None
×
UNCOV
149

×
150
        /**
151
         * Processes the next step in the simulation based on the current state and start time.
152
         * @param state
153
         *   the current state of the simulation.
154
         * @param startTime
155
         *   the start time of the current simulation step in milliseconds.
156
         * @return
157
         *   the next state of the simulation wrapped in an [[IO]] task.
158
         */
159
        private def nextStep(state: S, startTime: Long): IO[S] =
160
          state.simulationStatus match
×
161
            case RUNNING =>
×
162
              tickEvents(startTime, state.simulationSpeed.tickSpeed, state)
×
163

×
164
            case PAUSED =>
165
              IO.sleep(50.millis).as(state)
×
166

×
167
            case _ =>
168
              IO.pure(state)
×
169

×
170
        /**
171
         * Runs the behavior of all robots in the environment and collects their action proposals.
172
         * @param queue
173
         *   the queue to which the proposals will be offered through the [[Event.RobotActionProposals]] event.
174
         * @param state
175
         *   the current state of the simulation.
176
         * @return
177
         *   an [[IO]] task that completes when the behavior has been run.
178
         */
179
        private def runBehavior(queue: Queue[IO, Event], state: S): IO[Unit] =
180
          for
×
181
            proposals <- state.environment.entities.collect { case robot: Robot => robot }.toList.parTraverse { robot =>
×
182
              for
×
183
                sensorReadings <- robot.senseAll[IO](state.environment)
184
                ctx = BehaviorContext(sensorReadings, state.simulationRNG)
185
                (action, rng) = robot.behavior.run[IO](ctx)
186
                _ <- queue.offer(Event.Random(rng))
187
              yield RobotProposal(robot, action)
188
            }
189
            _ <- queue.offer(Event.RobotActionProposals(proposals))
×
190
          yield ()
191

×
192
        /**
193
         * Processes tick events, adjusting the tick speed based on the elapsed time since the last tick.
194
         * @param start
195
         *   the start time of the current tick in milliseconds.
196
         * @param tickSpeed
197
         *   the speed of the tick in [[FiniteDuration]].
198
         * @param state
199
         *   the current state of the simulation.
200
         * @return
201
         *   the next state of the simulation wrapped in an [[IO]] task.
202
         */
203
        private def tickEvents(start: Long, tickSpeed: FiniteDuration, state: S): IO[S] =
204
          for
×
205
            now <- Clock[IO].realTime.map(_.toMillis)
×
206
            timeToNextTick = tickSpeed.toMillis - (now - start)
×
207
            adjustedTickSpeed = if timeToNextTick > 0 then timeToNextTick else 0L
208
            sleepTime = FiniteDuration(adjustedTickSpeed, MILLISECONDS)
209
            _ <- IO.sleep(sleepTime)
×
210
            tick <- handleEvent(state, Event.Tick(state.dt))
211
          yield tick
212

×
213
        /**
214
         * Handles a sequence of events, processing them in the order they were received.
215
         * @param state
216
         *   the current state of the simulation.
217
         * @param events
218
         *   the sequence of events to be processed.
219
         * @return
220
         *   the final state of the simulation after processing all events, wrapped in an [[IO]] task.
221
         */
222
        private def handleEvents(state: S, events: Seq[Event]): IO[S] =
223
          for finalState <- events.foldLeft(IO.pure(state)) { (taskState, event) =>
×
224
              for
×
225
                currentState <- taskState
226
                newState <- handleEvent(currentState, event)
227
              yield newState
228
            }
229
          yield finalState
×
230

×
231
        /**
232
         * Handles a single event and updates the state accordingly.
233
         * @param state
234
         *   the current state of the simulation.
235
         * @param event
236
         *   the event to be processed.
237
         * @return
238
         *   the updated state of the simulation after processing the event, wrapped in an [[IO]] task.
239
         */
240
        private def handleEvent(state: S, event: Event): IO[S] =
241
          event match
×
242
            case Event.Tick(deltaTime) =>
×
243
              context.model.update(state)(using s => bundle.tickLogic.tick(s, deltaTime))
×
244
            case Event.TickSpeed(speed) =>
×
245
              context.model.update(state)(using s => bundle.tickLogic.tickSpeed(s, speed))
×
246
            case Event.Random(rng) =>
×
247
              context.model.update(state)(using s => bundle.randomLogic.random(s, rng))
×
248
            case Event.Pause =>
×
249
              context.model.update(state)(using s => bundle.pauseLogic.pause(s))
×
250
            case Event.Resume =>
×
251
              context.model.update(state)(using s => bundle.resumeLogic.resume(s))
×
252
            case Event.Stop =>
×
253
              context.model.update(state)(using s => bundle.stopLogic.stop(s))
×
254
            case Event.RobotActionProposals(proposals) =>
×
255
              context.model.update(state)(using s => bundle.robotActionsLogic.handleRobotActionsProposals(s, proposals))
×
256

×
257
      end ControllerImpl
258

259
    end Controller
260

261
  end Component
262

263
  /**
264
   * Interface trait that combines the provider and component traits for the controller module.
265
   *
266
   * @tparam S
267
   *   the type of the simulation state, which must extend [[ModelModule.State]].
268
   */
269
  trait Interface[S <: ModelModule.State] extends Provider[S] with Component[S]:
270
    self: Requirements[S] =>
271
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