egslava

Scala/Akka particle system 2

Sep 26th, 2014
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 5.02 KB | None | 0 0
  1. import akka.event.Logging
  2. import akka.actor.{Actor, ActorSystem, Props}
  3. import org.scalatest.time.Milliseconds
  4. import org.scalatest.time.Milliseconds
  5. import scala.concurrent.duration._
  6. import akka.actor.OneForOneStrategy
  7. import akka.actor.SupervisorStrategy._
  8. import scala.util.Random
  9. import scala.collection.immutable.Range
  10. import scala.collection.mutable.MutableList
  11. import scala.collection.mutable.ListBuffer
  12. import Messages._
  13. import akka.routing.Router
  14. import akka.routing.RoundRobinRouter
  15. import akka.routing.RoundRobinRoutingLogic
  16. import akka.routing.ActorRefRoutee
  17. import akka.io._
  18. import akka.routing._
  19. import akka.actor.Terminated
  20. import akka.actor.ActorLogging
  21.  
  22. object Messages{
  23.   /** from ParticleSystemManager to Worker update its particles */
  24.   val Process = "process"
  25.    
  26.   /** Request from ParticleSystemManager to Worker to grab its stats. */
  27.   val DoStats =     "stats"
  28.    
  29.   /** An answer from Worker to ParticleSystemManager about its stats */
  30.   case class ReadyStats( slowest: Particle, fastest: Particle )
  31. }
  32.  
  33. // Configuration parameters for Point class
  34. object Particle{
  35.   val MAX_LIFE = 1024
  36.   val START_X = 0
  37.   val START_Y = 0
  38.   val START_VX  = 0
  39.   val START_VY  = 0
  40.   val START_AX  = 0
  41.   val START_AY  = 0
  42.   val MAX_DIFRACTION = 5
  43. }
  44.  
  45. // Configuration for Workers
  46. object Worker {
  47.   val PARTICLES_PER_WORKER = 64
  48. }
  49.  
  50. // Just another configuration object
  51. object ParticleSystemManager {
  52.   val ACTORS_COUNT  = 64
  53. }
  54.  
  55. /** Representation of Particle class -  
  56.  *  position, velocity, acceleration, "life"-time and toString-"rendering"
  57.  */
  58. class Particle{
  59.   protected var x: Int = 0
  60.   protected var y: Int  = Particle.START_Y
  61.   protected var vX: Int = Particle.START_VX
  62.   protected var vY: Int = Particle.START_VY
  63.   protected var aX: Int = Particle.START_AX
  64.   protected var aY: Int = Particle.START_AY
  65.   protected var life: Int = 0   // times of processing (countdown to 0)
  66.  
  67.   reset
  68.  
  69.   override def toString = s"($x, $y, $vX, $vY, $aX, $aY, $life)"
  70.  
  71.   def process(){
  72.    
  73.     if (life >= Particle.MAX_LIFE){
  74.       reset()
  75.     }
  76.    
  77.     vX  += aX
  78.     vY  += aY
  79.     x   += vX
  80.     y   += vY
  81.     life += 1
  82.   }
  83.  
  84.   def reset(){
  85.     life = 0;
  86.     x   = Particle.START_X + distortion
  87.     y   = Particle.START_Y + distortion
  88.     vX  = Particle.START_VX + distortion
  89.     vY  = Particle.START_VY + distortion
  90.     aX  = Particle.START_AX + distortion
  91.     aY  = Particle.START_AY + distortion
  92.   }
  93.  
  94.   def v = Math.abs(Math.sqrt(vX * vX + vY * vY)).toInt
  95.  
  96.   protected def distortion = Random.nextInt(Particle.MAX_DIFRACTION) - Particle.MAX_DIFRACTION / 2
  97. }
  98.  
  99. /**
  100.  * Worker - is a particles buffer (@see Particle) and processor.
  101.  * Receives messages from ParticleSystemManager and updates data.
  102.  * Also can grab some stats and send them to manager
  103.  */
  104. class Worker extends Actor {
  105.  
  106.   val points = Array.fill(Worker.PARTICLES_PER_WORKER){ new Particle() }
  107.  
  108.   def receive = {
  109.     case Process => {
  110.       points.foreach { _.process };
  111.     }
  112.    
  113.     case DoStats => {
  114.       sender ! ReadyStats(points.minBy( _.v ), points.maxBy { _.v } )  
  115.     }
  116.   }
  117.  
  118.   implicit val timeout = 1 second
  119. }
  120.  
  121. /** Manager of all workers. Send update messages to workers (@see Messages#Process).
  122.  *  Also sends "grab stat"-messages (@see Messages#DoStat) and print stats
  123.  */
  124. class ParticleSystemManager extends Actor with ActorLogging{
  125.  
  126.   val router = context.actorOf( Props[ Worker ].withRouter(BroadcastRouter(ParticleSystemManager.ACTORS_COUNT)), "router" )
  127.  
  128.   val slowestAndFastests = ListBuffer[Particle]()
  129.   var actorsAnsweredStatistics = 0
  130.  
  131.   def receive = {
  132.     case Process => {
  133.  
  134.       router ! Process
  135.     }
  136.    
  137.     case DoStats => {
  138.       router ! DoStats
  139.       actorsAnsweredStatistics = ParticleSystemManager.ACTORS_COUNT
  140.     }
  141.    
  142.     case ReadyStats(slowest, fastest) => stats(slowest, fastest)
  143.   }
  144.  
  145.   def stats(slowest: Particle, fastest: Particle){
  146.       slowestAndFastests    += slowest += fastest
  147.      
  148.       actorsAnsweredStatistics -= 1
  149.       if ( actorsAnsweredStatistics <= 0){
  150.         printAndClearStats();
  151.       }
  152.   }
  153.  
  154.   def printAndClearStats(){
  155.     val slowest = slowestAndFastests.minBy(_.v)
  156.     val fastest = slowestAndFastests.maxBy(_.v)
  157.     log.info(s"Stats. Total particles count: ${ParticleSystemManager.ACTORS_COUNT * Worker.PARTICLES_PER_WORKER}. Particle with min speed: ${slowest}, particle with max speed: ${fastest}");
  158.     slowestAndFastests.clear
  159.   }
  160.  
  161.   override val supervisorStrategy =
  162.           OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 millisecond) {
  163.     case _: Exception                => Restart
  164.   }
  165. }
  166.  
  167.  
  168. object Main extends App {
  169.   Random.setSeed(System.currentTimeMillis() )
  170.   val system = ActorSystem("particlesystem");
  171.   val actor = system.actorOf( Props[ParticleSystemManager], name = "manager" );
  172.  
  173.   val frameTime = (1000 / 1) milliseconds
  174.  
  175.   import system.dispatcher
  176.   system.scheduler.schedule ( 0 milliseconds, frameTime, actor, Process)
  177.   system.scheduler.schedule ( 0 milliseconds, 3 seconds, actor, DoStats)
  178. }
Advertisement
Add Comment
Please, Sign In to add comment