Skip to content

Instantly share code, notes, and snippets.

@cdflynn

cdflynn/Drop.kt Secret

Created November 13, 2020 18:32
Show Gist options
  • Select an option

  • Save cdflynn/df4e96cc475b77ad94b9b26ee91c3121 to your computer and use it in GitHub Desktop.

Select an option

Save cdflynn/df4e96cc475b77ad94b9b26ee91c3121 to your computer and use it in GitHub Desktop.
fun ripples(
rippleImage: Bitmap,
sourceImage: Bitmap,
b1: FloatArray,
b2: FloatArray
) {
for (x in 3 until rippleImage.width -3) {
for (y in 1 until rippleImage.height -1) {
val lastHeight = b1[index2d(x, y)]
val nowHeight = b2[index2d(x, y)]
if (lastHeight == nowHeight) continue
if (nowHeight == 0F) {
val sourceColor = sourceImage[x, y]
rippleImage[x, y] = sourceColor
continue
}
val xOffset = b2[index2d(x - 1, y)] - b2[index2d(x + 1, y)]
val yOffset = b2[index2d(x, y - 1)] - b2[index2d(x, y + 1)]
val newX = (x + xOffset).clamp(3F, (rippleImage.width - 3).toFloat())
val newY = (y + yOffset).clamp(0F, (rippleImage.height -1).toFloat())
val newColor = sourceImage[newX, newY]
val newColor2 = sourceImage[newX+1, newY]
val newColor3 = sourceImage[newX+2, newY]
rippleImage[x, y] = newColor
rippleImage[x+1, y] = newColor2
rippleImage[x+2, y] = newColor3
}
}
}
private fun calculateNewHeightMap(
b1: FloatArray,
b2: FloatArray
) {
for (x in 1 until width - 1) {
for (y in 1 until height - 1) {
val i2d = index2d(x, y)
val current = b2[i2d]
val avg = (
b1[index2d(x - 1, y)] +
b1[index2d(x + 1, y)] +
b1[index2d(x, y - 1)] +
b1[index2d(x, y + 1)]
) / 2 - current
b2[i2d] = (avg * damping).zero()
}
}
}
private fun index2d(x: Int, y: Int): Int {
return x + (width * y)
}
private fun Float.clamp(min: Float, max: Float): Int {
return max(min, min(max, this)).toInt()
}
private fun Float.zero(): Float {
return if (this > -1F && this < 1F) 0F else this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment