Skip to content

Commit

Permalink
Merge pull request #550 from JD557/surface-tabulate
Browse files Browse the repository at this point in the history
Add Surface#tabulate helpers
  • Loading branch information
JD557 authored Dec 28, 2024
2 parents 60d16a4 + 0266f90 commit a4da678
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,16 @@ trait MutableSurface extends Surface {
blit(f(this.view).toRamSurface())(0, 0)
}
}

object MutableSurface {

/** Produces a mutable surface containing values of a given function
* over ranges of integer values starting from 0.
*
* @param width the surface width
* @param height the surface height
* @param f the function computing the element values
*/
def tabulate(width: Int, height: Int)(f: (Int, Int) => Color): MutableSurface =
RamSurface.tabulate(width, height)(f)
}
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ trait Plane extends Function2[Int, Int, Color] { outer =>
* @param height surface height
*/
final def toRamSurface(width: Int, height: Int): RamSurface =
toSurfaceView(width, height).toRamSurface()
RamSurface.tabulate(width, height)(getPixel)
}

object Plane {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,34 @@ final class RamSurface(val dataBuffer: Vector[Array[Color]]) extends MutableSurf
}
}
}

object RamSurface {

/** Produces a RAM surface containing values of a given function
* over ranges of integer values starting from 0.
*
* @param width the surface width
* @param height the surface height
* @param f the function computing the element values
*/
def tabulate(width: Int, height: Int)(f: (Int, Int) => Color): RamSurface = {
val b = Vector.newBuilder[Array[Color]]
b.sizeHint(height)
var y = 0
while (y < height) {
if (width <= 0) {
b += Array.empty[Color]
} else {
val array = new Array[Color](width)
var x = 0
while (x < width) {
array(x) = f(x, y)
x += 1
}
b += array
}
y += 1
}
new RamSurface(b.result())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,16 @@ trait Surface {
/** Copies this surface into a new surface stored in RAM. */
final def toRamSurface(): RamSurface = new RamSurface(getPixels())
}

object Surface {

/** Produces a surface containing values of a given function
* over ranges of integer values starting from 0.
*
* @param width the surface width
* @param height the surface height
* @param f the function computing the element values
*/
def tabulate(width: Int, height: Int)(f: (Int, Int) => Color): Surface =
MutableSurface.tabulate(width, height)(f)
}

0 comments on commit a4da678

Please sign in to comment.