DEADSOFTWARE

Update version script
[cavedroid.git] / core / src / ru / deadsoftware / cavedroid / misc / utils / RenderingUtils.kt
1 package ru.deadsoftware.cavedroid.misc.utils
3 import com.badlogic.gdx.Gdx
4 import com.badlogic.gdx.graphics.Color
5 import com.badlogic.gdx.graphics.GL20
6 import com.badlogic.gdx.graphics.g2d.GlyphLayout
7 import com.badlogic.gdx.graphics.g2d.SpriteBatch
8 import com.badlogic.gdx.math.Rectangle
9 import ru.deadsoftware.cavedroid.MainConfig
10 import ru.deadsoftware.cavedroid.misc.Assets
12 private fun Rectangle.shifted(shift: Float) = Rectangle(x + shift, y, width, height)
14 private fun Rectangle.getLazyShifts(worldWidthPx: Float)
15 = Triple(
16 first = lazy { shifted(0f) },
17 second = lazy { shifted(-worldWidthPx) },
18 third = lazy { shifted(worldWidthPx) }
19 )
21 fun Rectangle.cycledInsideWorld(
22 viewport: Rectangle,
23 worldWidthPx: Float,
24 ): Rectangle? {
25 val (notShifted, shiftedLeft, shiftedRight) = getLazyShifts(worldWidthPx)
27 return when {
28 viewport.overlaps(notShifted.value) -> notShifted.value
29 viewport.overlaps(shiftedLeft.value) -> shiftedLeft.value
30 viewport.overlaps(shiftedRight.value) -> shiftedRight.value
31 else -> null
32 }
33 }
35 fun forEachBlockInArea(
36 area: Rectangle,
37 func: (x: Int, y: Int) -> Unit,
38 ) {
39 val startMapX = area.x.bl
40 val endMapX = (area.x + area.width - 1f).bl
41 val startMapY = area.y.bl
42 val endMapY = (area.y + area.height - 1f).bl
44 for (x in startMapX..endMapX) {
45 for (y in startMapY..endMapY) {
46 func(x, y)
47 }
48 }
49 }
51 @JvmOverloads
52 fun SpriteBatch.drawString(str: String, x: Float, y: Float, color: Color = Color.WHITE): GlyphLayout {
53 Assets.minecraftFont.color = color
54 return Assets.minecraftFont.draw(this, str, x, y)
55 }
57 /**
58 * Parses hex color string into [Color]
59 * Format is strictly #FFFFFF
60 */
61 fun colorFromHexString(hex: String): Color {
62 if (hex[0] != '#' || hex.length != 7) {
63 return Color.WHITE
64 }
66 var rgba = try {
67 hex.substring(1).toInt(16)
68 } catch (e: NumberFormatException) {
69 0xffffff
70 }
72 rgba = (rgba shl 8) or 0xFF
73 return Color(rgba)
74 }
76 fun SpriteBatch.withScissors(
77 mainConfig: MainConfig,
78 x: Float,
79 y: Float,
80 width: Float,
81 height: Float,
82 block: () -> Unit
83 ) {
84 val scaleX = Gdx.graphics.width / mainConfig.width
85 val scaleY = Gdx.graphics.height / mainConfig.height
87 flush()
88 Gdx.gl.glEnable(GL20.GL_SCISSOR_TEST)
89 Gdx.gl.glScissor(
90 /* x = */ (x * scaleX).toInt(),
91 /* y = */ ((mainConfig.height - y - height) * scaleY).toInt(),
92 /* width = */ (width * scaleX).toInt(),
93 /* height = */ (height * scaleY).toInt()
94 )
95 block.invoke()
96 flush()
97 Gdx.gl.glDisable(GL20.GL_SCISSOR_TEST)
98 }