Advertisement
KrunoSaho

Thermel Erosion

Jun 8th, 2014
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.24 KB | None | 0 0
  1. class ThermalErosion(val noise: Noise, val talusAngle: Double) extends NoiseOp {
  2.   val DEFAULT_DECAY = 0L
  3.   val cache = TrieMap[(Int, Int), Double]()
  4.   var tDecay = new AtomicLong(DEFAULT_DECAY)
  5.  
  6.   final def apply(x: Double, y: Double) = {
  7.     val i = x.toInt
  8.     val j = y.toInt
  9.  
  10.     if (tDecay.get() > 0) {
  11.       tDecay.decrementAndGet()
  12.       noise(i, j) + cache.getOrElse((i, j), 0.0)
  13.     }
  14.     else {
  15.       tDecay.set(DEFAULT_DECAY)
  16.  
  17.       val mask = Array(
  18.         (-1,-1), (0,-1), (1,-1),
  19.         (-1, 0), (0, 0), (1, 0),
  20.         (-1, 1), (0, 1), (1, 1)
  21.       )
  22.       val data = mask.par.map(t => noise(x + t._1, y + t._2))
  23.  
  24.       val cachedVal = cache.getOrElse((i, j), 0.0)
  25.  
  26.       val height = data(4) + cachedVal
  27.       val maxSlope = data.reduce((res, x) => math.max(res, x))
  28.       val minSlope = data.reduce((res, x) => math.min(res, x))
  29.       val minSlopeCoords = (mask zip data).reduce((res, e) => if (math.abs(e._2 - minSlope) <= 1e-13) e else res)._1
  30.  
  31.       if (maxSlope > talusAngle) {
  32.         val newHeight = (height + maxSlope) * 0.5
  33.  
  34.         cache.update(minSlopeCoords, cachedVal + newHeight)
  35.         cache.update((i, j), newHeight)
  36.  
  37.         newHeight
  38.       }
  39.       else {
  40.         height
  41.       }
  42.     }
  43.   }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement