Skip to content

Cell and CellProvider

abbie edited this page May 20, 2023 · 1 revision

To support both pixel art and tile maps, Rawky has a concept of interchangeable cell types along with a provider to give us the right cells. These give us the functionality to define how to store and represent data in the cell

Examples

Break Down

To begin with we'll need a plugin to work with. If you don't have one, please follow this guide. To keep things easy, we'll extend the CellProvider class for our plugin object. We'll need to provide a generic type for what our cell stores. In this case, we'll just use an char. We'll also need to override the cell provider's name and current value as well as register it to the CellProvider registry

@Plugin(...)
object MyCellProvider : CellProvider<Char>() {
    override val name = "Char"
    override lateinit var current: Char

    init {
        registry[name] = this
    }
}

Next we'll also make an internal class that extends from the Cell class, passing it a generic type for what the cell stores. We'll need to override some variables and here we can also specify a default value for our cell's content

@Plugin(...)
object MyCellProvider : CellProvider<Char>() {
    ...

    data class MyCell(
        override val row: Int,
        override val column: Int,
        override val content: Int = ' '
    ) : Cell<Char>()
}

Back to our cell provider. We'll want to override a few methods to hand out and render our cell and it's content

@Plugin(...)
object MyCellProvider : CellProvider<Char>() {
    ...

    override fun provide(
        row: Int, column: Int,
    ): MyCell = MyCell(row, column)

    override fun perform(
        cell: Cell<Any>,
        button: Int, dragged: Boolean,
        clickCount: Int
    ) {
        when (button) {
            0 -> cell.content = current
        }
    }

    override fun redact(
        cell: Cell<Any>,
        button: Int, dragged: Boolean,
        clickCount: Int
    ) {
        when (button) {
            0 -> cell.content = ' '
        }
    }

    override fun cleanup(
        cache: Any,
        cell: Cell<Any>,
        button: Int,
        dragged: Boolean,
        clickCount: Int
    ) {
        cell.content = cache
    }

    override fun paintGrid(
        g: Graphics2D,
        cell: Cell<@Contextual Any>
    ) {
        g.drawString(
            (cell.content as Char).toString(),
            cell.polygon.x, cell.polygon.y,
        )
    }

    override fun paintHover(
        g: Graphics2D,
        cell: Cell<@Contextual Any>
    ) {
        paintGrid(g, cell)
    }
}

We should then start seeing characters being drawn in the cells if we were to some how set the content of the cell to something other than a space, perhaps by providing a palette component

Clone this wiki locally