Skip to content

Instantly share code, notes, and snippets.

@nea89o
Created March 31, 2023 01:26
Show Gist options
  • Save nea89o/5eafe375cac1d9c4576d9952cfdb7935 to your computer and use it in GitHub Desktop.
Save nea89o/5eafe375cac1d9c4576d9952cfdb7935 to your computer and use it in GitHub Desktop.
reimplementation of the minecraft 1.8.9 font renderer
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.io.File
import java.util.*
import javax.imageio.ImageIO
/**
* Copyright 2022 Linnea Gräf
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
object LoreRenderer {
val fontFolder = File("texturepacks/vanilla/assets/minecraft/textures/font")
val fontCache = fontFolder.listFiles()!!.associate { it.name to ImageIO.read(it) }
val FUNKY_ASCII_ALPHABET =
"ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ\u0000\u0000\u0000\u0000\u0000\u0000\u0000 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u0000ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u0000"
val GLYPH_SIZE = 8
val glyphWidth = File("texturepacks/vanilla/assets/minecraft/font/glyph_sizes.bin").let {
val glyphWidths = it.readBytes()
if (glyphWidths.size != 65536) {
error("Invalid glyph size: ${glyphWidths.size}")
}
glyphWidths
}
val glyphCache = Collections.synchronizedMap(mutableMapOf<Char, Glyph>())
interface Glyph {
fun renderOnto(graphics: Graphics2D, xPos: Int, yPos: Int, scale: Int, bold: Boolean)
val width: Int
}
data class RealGlyph(
val texture: BufferedImage,
val xOffset: Int,
val yOffset: Int,
override val width: Int,
val scale: Int,
) : Glyph {
val thinTexture = texture.getSubimage(xOffset, yOffset, GLYPH_SIZE * scale, GLYPH_SIZE * scale)
override fun renderOnto(
graphics: Graphics2D,
xPos: Int,
yPos: Int,
scale: Int,
bold: Boolean
) {
val actualScale = scale / this.scale
for (x in 0 until GLYPH_SIZE * this.scale) {
for (y in 0 until GLYPH_SIZE * this.scale) {
val isSet = thinTexture.getRGB(x, y) shr 24 and 0xFF != 0x00
if (isSet) {
graphics.fillRect(xPos + x * actualScale, yPos + y * actualScale, actualScale, actualScale)
}
}
}
}
}
object SpaceGlyph : Glyph {
override fun renderOnto(
graphics: Graphics2D,
xPos: Int,
yPos: Int,
scale: Int,
bold: Boolean
) {
}
override val width: Int get() = 4
}
object GlyphMissing : Glyph {
override fun renderOnto(
graphics: Graphics2D,
xPos: Int,
yPos: Int,
scale: Int,
bold: Boolean
) {
graphics.drawRect(xPos, yPos, GLYPH_SIZE * scale, GLYPH_SIZE * scale)
}
override val width: Int
get() = GLYPH_SIZE
}
fun getGlyph(char: Char): Glyph {
return glyphCache.computeIfAbsent(char, ::getGlyph0)
}
fun getGlyph0(char: Char): Glyph {
if (char == ' ') return SpaceGlyph
val funkyIndex = FUNKY_ASCII_ALPHABET.indexOf(char)
if (funkyIndex != -1) {
val fontImage = fontCache["ascii.png"] ?: return GlyphMissing
return createGlyph(fontImage, funkyIndex)
}
val code = char.code
val lastByte = code and 0xFF
val page = code shr 8 and 0xFF
val pageName = "unicode_page_" + "%02x".format(page)
val fontImage: BufferedImage = fontCache["$pageName.png"] ?: return GlyphMissing
return createGlyph(fontImage, lastByte)
}
private fun createGlyph(fontImage: BufferedImage, index: Int): RealGlyph {
val xOffset = (index % 16) * (fontImage.width / 16)
val yOffset = (index / 16) * (fontImage.height / 16)
val scale = fontImage.width / 16 / GLYPH_SIZE
return RealGlyph(
fontImage,
xOffset,
yOffset,
findGlyphWidth(fontImage, xOffset, yOffset, scale),
scale,
)
}
private fun findGlyphWidth(fontImage: BufferedImage, xOffset: Int, yOffset: Int, scale: Int): Int {
for (i in scale * GLYPH_SIZE - 1 downTo 0) {
if ((0 until scale * GLYPH_SIZE).any() {
fontImage.getRGB(
xOffset + i,
yOffset + it
) shr 24 and 0xFF != 0
}) {
return Math.ceil((i.toDouble() + 2) / scale).toInt()
}
}
return GLYPH_SIZE
}
fun renderLore(
loreLines: List<String>,
scale: Int,
margin: Int,
defaultColor: MinecraftColors.Color
): BufferedImage {
require(scale % 2 == 0) { "Must provide an even scale" }
require(loreLines.isNotEmpty()) { "Must provide at least one line" }
val formattedLines = loreLines.map {
val parts = it.split("§").toMutableList()
parts[0] = "r" + parts[0]
parts
}
val width = formattedLines.maxOf { it.sumOf { it.drop(1).sumOf { getGlyph(it).width } } } * scale
val height = formattedLines.size * GLYPH_SIZE * scale
val image = BufferedImage(
width + margin * 2,
height + margin * 2,
BufferedImage.TYPE_INT_ARGB
)
val graphics = image.createGraphics()
var y = margin
for (line in formattedLines) {
var x = margin
var bold = false
graphics.color = defaultColor.awtColor
for (part in line) {
val colorCode = part.first()
val text = part.drop(1)
when (colorCode.lowercaseChar()) {
'l' -> bold = true
'r' -> {
bold = false
graphics.color = defaultColor.awtColor
}
else -> {
val color = MinecraftColors.byColorCode[colorCode]
if (color == null) {
println("Ignoring color char: $colorCode")
} else
graphics.color = color.awtColor
}
}
for (ch in text) {
val glpyh = getGlyph(ch)
if (bold) {
glpyh.renderOnto(graphics, x + scale, y, scale, false)
}
glpyh.renderOnto(graphics, x, y, scale, false)
x += glpyh.width * scale
if (bold) {
x += scale
}
}
}
y += GLYPH_SIZE * scale
}
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment