Improve textures management

This commit is contained in:
2021-02-16 11:39:10 +01:00
parent 499e232e17
commit a307939de5
3 changed files with 33 additions and 5 deletions

View File

@@ -9,6 +9,8 @@ import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import static java.lang.String.format;
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@@ -18,13 +20,19 @@ public class DefaultTextureManager implements TextureManager {
@Override
public Texture loadTexture(String textureFileName) {
var texture = loadedTextures.get(textureFileName);
return loadTexture(textureFileName, 1, 1);
}
@Override
public Texture loadTexture(String textureFileName, int rows, int columns) {
var key = format("%dx%d__%s", rows, columns, textureFileName);
var texture = loadedTextures.get(key);
if (texture == null) {
log.info("Loading [{}] texture to cache", textureFileName);
log.info("Loading [{}] texture to cache under the key: [{}]", textureFileName, key);
var buffer = resourcesManager.loadResourceAsByteBuffer(textureFileName);
texture = new Texture(textureFileName, buffer);
loadedTextures.put(textureFileName, texture);
texture = new Texture(textureFileName, buffer, rows, columns);
loadedTextures.put(key, texture);
}
return texture;

View File

@@ -3,6 +3,7 @@ package com.bartlomiejpluta.base.core.gl.object.texture;
import com.bartlomiejpluta.base.core.error.AppException;
import com.bartlomiejpluta.base.core.gc.Disposable;
import lombok.Getter;
import org.joml.Vector2f;
import org.lwjgl.system.MemoryStack;
import java.nio.ByteBuffer;
@@ -27,7 +28,20 @@ public class Texture implements Disposable {
@Getter
private final int height;
Texture(String textureFilename, ByteBuffer buffer) {
@Getter
private final int rows;
@Getter
private final int columns;
@Getter
private final Vector2f spriteFragment;
@Getter
private final Vector2f spriteSize;
Texture(String textureFilename, ByteBuffer buffer, int rows, int columns) {
try (var stack = MemoryStack.stackPush()) {
var widthBuffer = stack.mallocInt(1);
var heightBuffer = stack.mallocInt(1);
@@ -51,6 +65,11 @@ public class Texture implements Disposable {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
fileName = textureFilename;
this.rows = rows;
this.columns = columns;
this.spriteFragment = new Vector2f(1 / (float) columns, 1 / (float) rows);
this.spriteSize = new Vector2f(width, height).mul(spriteFragment);
}
}

View File

@@ -4,4 +4,5 @@ import com.bartlomiejpluta.base.core.gc.Cleanable;
public interface TextureManager extends Cleanable {
Texture loadTexture(String textureFileName);
Texture loadTexture(String textureFileName, int rows, int columns);
}