commonMain.ru.casperix.multiplatform.text.impl.AbstractTextRenderer.kt Maven / Gradle / Ivy
package ru.casperix.multiplatform.text.impl
import ru.casperix.multiplatform.font.FontReference
import ru.casperix.multiplatform.font.localize.CharacterSets
import ru.casperix.multiplatform.font.pixel.PixelFont
import ru.casperix.multiplatform.font.pixel.PixelFontPacker
import ru.casperix.math.color.Color
import ru.casperix.math.quad_matrix.float32.Matrix3f
import ru.casperix.math.vector.float32.Vector2f
import ru.casperix.renderer.Renderer2D
import ru.casperix.multiplatform.text.TextLayout
import ru.casperix.multiplatform.text.TextRenderConfig
import ru.casperix.multiplatform.text.TextRendererApi
@ExperimentalUnsignedTypes
abstract class AbstractTextRenderer : TextRendererApi {
abstract fun buildFont(reference: FontReference, chars: Set): PixelFont
private val fontCache = mutableMapOf()
private var cacheConfig = TextRenderConfig.actualLanguages
override fun getPixelFont(reference: FontReference): PixelFont {
if (cacheConfig != TextRenderConfig.actualLanguages) {
cacheConfig = TextRenderConfig.actualLanguages
fontCache.clear()
}
return fontCache.getOrPut(reference) {
val alphabetChars = CharacterSets.all
.filter { cacheConfig.contains(it.language) }
.flatMap { it.charSet }
.toSet()
val font = buildFont(reference, CharacterSets.COMMON_CHARACTER_SET + alphabetChars)
PixelFontPacker.packFont(font)
}
}
override fun createTextLayout(text: String, areaSize: Vector2f, font: PixelFont): TextLayout {
return TextLayoutBuilder.layout(text, areaSize, font)
}
override fun drawText(
renderer:Renderer2D,
text: String,
reference: FontReference,
matrix: Matrix3f,
availableArea: Vector2f,
color: Color,
backgroundColor: Color?
): TextLayout {
val pixelFont = getPixelFont(reference)
val layout = createTextLayout(text, availableArea, pixelFont)
TextLayoutRender.drawTextLayout(renderer, matrix, color, layout)
return layout
}
override fun drawTextLayout( renderer:Renderer2D,matrix: Matrix3f, color: Color, layout: TextLayout) {
TextLayoutRender.drawTextLayout(renderer, matrix, color, layout)
}
override fun drawTextLayoutMetrics(renderer:Renderer2D, matrix: Matrix3f, font: PixelFont, layout: TextLayout) {
TextLayoutRender.drawTextLayoutMetrics(renderer, matrix, font, layout)
}
}