Pull shader code into main #1

Merged
YourWishes merged 4 commits from shader into main 2026-03-22 15:46:37 +00:00
19 changed files with 205 additions and 142 deletions
Showing only changes of commit ca0e9fc3b2 - Show all commits

View File

@@ -156,7 +156,7 @@ class Map:
newTopLeftChunkY = y // CHUNK_HEIGHT - (MAP_HEIGHT // 2) newTopLeftChunkY = y // CHUNK_HEIGHT - (MAP_HEIGHT // 2)
newTopLeftChunkZ = z // CHUNK_DEPTH - (MAP_DEPTH // 2) newTopLeftChunkZ = z // CHUNK_DEPTH - (MAP_DEPTH // 2)
if (newTopLeftChunkX != self.topLeftX or if(newTopLeftChunkX != self.topLeftX or
newTopLeftChunkY != self.topLeftY or newTopLeftChunkY != self.topLeftY or
newTopLeftChunkZ != self.topLeftZ): newTopLeftChunkZ != self.topLeftZ):
@@ -166,7 +166,7 @@ class Map:
chunkWorldX = chunk.x chunkWorldX = chunk.x
chunkWorldY = chunk.y chunkWorldY = chunk.y
chunkWorldZ = chunk.z chunkWorldZ = chunk.z
if (chunkWorldX < newTopLeftChunkX or if(chunkWorldX < newTopLeftChunkX or
chunkWorldX >= newTopLeftChunkX + MAP_WIDTH or chunkWorldX >= newTopLeftChunkX + MAP_WIDTH or
chunkWorldY < newTopLeftChunkY or chunkWorldY < newTopLeftChunkY or
chunkWorldY >= newTopLeftChunkY + MAP_HEIGHT or chunkWorldY >= newTopLeftChunkY + MAP_HEIGHT or

View File

@@ -45,13 +45,63 @@ void cameraInitOrthographic(camera_t *camera) {
camera->_2d.zoom = 1.0f; camera->_2d.zoom = 1.0f;
} }
void cameraPushMatrix(camera_t *camera) { void cameraGetProjectionMatrix(camera_t *camera, mat4 dest) {
assertNotNull(camera, "Invalid camera"); assertNotNull(camera, "Not a camera component");
cameraPushMatrixPlatform(camera); assertNotNull(dest, "Destination matrix must not be null");
if(
camera->projType == CAMERA_PROJECTION_TYPE_PERSPECTIVE ||
camera->projType == CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED
) {
glm_mat4_identity(dest);
glm_perspective(
camera->perspective.fov,
SCREEN.aspect,
camera->nearClip,
camera->farClip,
dest
);
if(camera->projType == CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED) {
dest[1][1] *= -1.0f;
}
} else if(camera->projType == CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC) {
glm_mat4_identity(dest);
glm_ortho(
camera->orthographic.left,
camera->orthographic.right,
camera->orthographic.top,
camera->orthographic.bottom,
camera->nearClip,
camera->farClip,
dest
);
}
} }
void cameraPopMatrix(void) { void cameraGetViewMatrix(camera_t *camera, mat4 dest) {
#ifdef cameraPopMatrixPlatform assertNotNull(camera, "Not a camera component");
cameraPopMatrixPlatform(); assertNotNull(dest, "Destination matrix must not be null");
#endif
if(camera->viewType == CAMERA_VIEW_TYPE_MATRIX) {
glm_mat4_copy(camera->view, dest);
} else if(camera->viewType == CAMERA_VIEW_TYPE_LOOKAT) {
glm_mat4_identity(dest);
glm_lookat(
camera->lookat.position,
camera->lookat.target,
camera->lookat.up,
dest
);
} else if(camera->viewType == CAMERA_VIEW_TYPE_2D) {
glm_mat4_identity(dest);
glm_lookat(
(vec3){ camera->_2d.position[0], camera->_2d.position[1], 0.5f },
(vec3){ camera->_2d.position[0], camera->_2d.position[1], 0.0f },
(vec3){ 0.0f, 1.0f, 0.0f },
dest
);
} else if(camera->viewType == CAMERA_VIEW_TYPE_LOOKAT_PIXEL_PERFECT) {
assertUnreachable("LOOKAT_PIXEL_PERFECT view type is not implemented yet");
}
} }

View File

@@ -86,13 +86,17 @@ void cameraInitPerspective(camera_t *camera);
void cameraInitOrthographic(camera_t *camera); void cameraInitOrthographic(camera_t *camera);
/** /**
* Pushes the camera's view matrix onto the matrix stack. * Gets the projection matrix for a camera.
* *
* @param id The ID of the camera entity to use. * @param camera Camera to get the projection matrix for
* @param dest Matrix to store the projection matrix in
*/ */
void cameraPushMatrix(camera_t *camera); void cameraGetProjectionMatrix(camera_t *camera, mat4 dest);
/** /**
* Pops the camera's view matrix off the matrix stack. * Gets the view matrix for a camera.
*
* @param camera Camera to get the view matrix for
* @param dest Matrix to store the view matrix in
*/ */
void cameraPopMatrix(void); void cameraGetViewMatrix(camera_t *camera, mat4 dest);

View File

@@ -57,67 +57,27 @@ errorret_t displayUpdate(void) {
errorChain(shaderBind(&SHADER_UNLIT)); errorChain(shaderBind(&SHADER_UNLIT));
mat4 proj; camera_t camera;
glm_mat4_identity(proj); cameraInitOrthographic(&camera);
glm_ortho(0.0f, (float_t)SCREEN.width, (float_t)SCREEN.height, 0.0f, -1.0f, 1.0f, proj); camera.orthographic.left = 0.0f;
camera.orthographic.right = SCREEN.width;
camera.orthographic.top = SCREEN.height;
camera.orthographic.bottom = 0.0f;
mat4 view; mat4 proj, view, model;
glm_mat4_identity(view); cameraGetProjectionMatrix(&camera, proj);
cameraGetViewMatrix(&camera, view);
mat4 model;
glm_mat4_identity(model); glm_mat4_identity(model);
glm_translate(model, (vec3){
sinf(TIME.time * 10.0f) * 30.0f + 100.0f,
cosf(TIME.time * 10.0f) * 50.0f + 100.0f,
0.0f
});
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj)); errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj));
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, view)); errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, view));
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, model)); errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, model));
meshvertex_t verts[6] = { errorChain(spriteBatchPush(
{ NULL,
.pos = { 0.0f, 0.0f, 0.0f }, TIME.time * 2.0f, TIME.time * 3.0f, 100, 100, COLOR_WHITE, 0, 0, 1, 1
.uv = { 0.0f, 0.0f }, ));
.color = COLOR_WHITE errorChain(spriteBatchFlush());
},
{
.pos = { 100.0f, 0.0f, 0.0f },
.uv = { 1.0f, 0.0f },
.color = COLOR_WHITE
},
{
.pos = { 100.0f, 100.0f, 0.0f },
.uv = { 1.0f, 1.0f },
.color = COLOR_WHITE
},
{
.pos = { 100.0f, 100.0f, 0.0f },
.uv = { 1.0f, 1.0f },
.color = COLOR_WHITE
},
{
.pos = { 0.0f, 100.0f, 0.0f },
.uv = { 0.0f, 1.0f },
.color = COLOR_WHITE
},
{
.pos = { 0.0f, 0.0f, 0.0f },
.uv = { 0.0f, 0.0f },
.color = COLOR_WHITE
}
};
mesh_t mesh;
meshInit(&mesh, MESH_PRIMITIVE_TYPE_TRIANGLES, 6, verts);
meshDraw(&mesh, 0, -1);
meshDispose(&mesh);
// errorCatch(errorPrint(sceneRender())); // errorCatch(errorPrint(sceneRender()));

View File

@@ -25,6 +25,29 @@ errorret_t meshInit(
errorOk(); errorOk();
} }
errorret_t meshFlush(
mesh_t *mesh,
const int32_t vertexOffset,
const int32_t vertexCount
) {
#ifdef meshFlushPlatform
assertNotNull(mesh, "Mesh cannot be NULL");
assertTrue(vertexOffset >= 0, "Vertex offset must be non-negative.");
assertTrue(vertexCount == -1 || vertexCount > 0, "Vertex count incorrect.");
int32_t vertCount = meshGetVertexCount(mesh);
assertTrue(vertexOffset < (vertCount - 1), "Need at least one vert to draw");
int32_t drawCount = vertexCount;
if(vertexCount == -1) {
drawCount = vertCount - vertexOffset;
}
errorChain(meshFlushPlatform(mesh, vertexOffset, vertexCount));
#endif
errorOk();
}
errorret_t meshDraw( errorret_t meshDraw(
const mesh_t *mesh, const mesh_t *mesh,
const int32_t vertexOffset, const int32_t vertexOffset,
@@ -32,7 +55,7 @@ errorret_t meshDraw(
) { ) {
assertNotNull(mesh, "Mesh cannot be NULL"); assertNotNull(mesh, "Mesh cannot be NULL");
assertTrue(vertexOffset >= 0, "Vertex offset must be non-negative"); assertTrue(vertexOffset >= 0, "Vertex offset must be non-negative");
assertTrue(vertexCount >= -1, "Vertex count must be -1 or non-negative"); assertTrue(vertexCount == -1 || vertexCount > 0, "Incorrect vert count");
int32_t vertDrawCount = vertexCount; int32_t vertDrawCount = vertexCount;
if(vertexCount == -1) { if(vertexCount == -1) {

View File

@@ -40,6 +40,22 @@ errorret_t meshInit(
const meshvertex_t *vertices const meshvertex_t *vertices
); );
/**
* Instructs the mesh to flush the vertices to the GPU. This is surprisingly
* only really necessary on modern devices, as we tend to let older devices
* read the vertices from the main memory directly.
*
* @param mesh Mesh to flush the vertices for.
* @param vertexOffset Start vertex to flush.
* @param vertexCount Count of vertices to flush, set to -1 for all.
* @return Error state.
*/
errorret_t meshFlush(
mesh_t *mesh,
const int32_t vertexOffset,
const int32_t vertexCount
);
/** /**
* Draws a mesh. * Draws a mesh.
* *

View File

@@ -9,6 +9,7 @@
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "display/mesh/quad.h" #include "display/mesh/quad.h"
#include "display/shader/shaderunlit.h"
screen_t SCREEN; screen_t SCREEN;
@@ -370,10 +371,18 @@ errorret_t screenRender() {
FRAMEBUFFER_CLEAR_COLOR | FRAMEBUFFER_CLEAR_DEPTH, FRAMEBUFFER_CLEAR_COLOR | FRAMEBUFFER_CLEAR_DEPTH,
COLOR_BLACK COLOR_BLACK
); );
cameraPushMatrix(&SCREEN.framebufferCamera);
errorChain(textureBind(&SCREEN.framebuffer.texture)); shaderBind(&SHADER_UNLIT);
mat4 proj, view, model;
cameraGetProjectionMatrix(&SCREEN.framebufferCamera, proj);
cameraGetViewMatrix(&SCREEN.framebufferCamera, view);
glm_mat4_identity(model);
shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj);
shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, view);
shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, model);
// errorChain(textureBind(&SCREEN.framebuffer.texture));
errorChain(meshDraw(&SCREEN.frameBufferMesh, 0, -1)); errorChain(meshDraw(&SCREEN.frameBufferMesh, 0, -1));
cameraPopMatrix();
errorOk(); errorOk();
}; };

View File

@@ -19,7 +19,7 @@ errorret_t spriteBatchInit() {
&SPRITEBATCH.mesh, &SPRITEBATCH.mesh,
QUAD_PRIMITIVE_TYPE, QUAD_PRIMITIVE_TYPE,
SPRITEBATCH_VERTEX_COUNT, SPRITEBATCH_VERTEX_COUNT,
&SPRITEBATCH_VERTICES[0] SPRITEBATCH_VERTICES
)); ));
errorOk(); errorOk();
} }
@@ -83,10 +83,10 @@ errorret_t spriteBatchFlush() {
errorOk(); errorOk();
} }
size_t vertexCount = QUAD_VERTEX_COUNT * SPRITEBATCH.spriteCount;
errorChain(meshFlush(&SPRITEBATCH.mesh, 0, vertexCount));
errorChain(textureBind(SPRITEBATCH.currentTexture)); errorChain(textureBind(SPRITEBATCH.currentTexture));
errorChain(meshDraw( errorChain(meshDraw(&SPRITEBATCH.mesh, 0, vertexCount));
&SPRITEBATCH.mesh, 0, QUAD_VERTEX_COUNT * SPRITEBATCH.spriteCount
));
spriteBatchClear(); spriteBatchClear();
errorOk(); errorOk();
} }

View File

@@ -9,7 +9,7 @@
#include "display/mesh/quad.h" #include "display/mesh/quad.h"
#include "display/texture/texture.h" #include "display/texture/texture.h"
#define SPRITEBATCH_SPRITES_MAX 16 #define SPRITEBATCH_SPRITES_MAX 1
#define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT) #define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT)

View File

@@ -69,8 +69,6 @@ void moduleCamera(scriptcontext_t *context) {
// Methods // Methods
lua_register(context->luaState, "cameraCreate", moduleCameraCreate); lua_register(context->luaState, "cameraCreate", moduleCameraCreate);
lua_register(context->luaState, "cameraPushMatrix", moduleCameraPushMatrix);
lua_register(context->luaState, "cameraPopMatrix", moduleCameraPopMatrix);
} }
int moduleCameraCreate(lua_State *L) { int moduleCameraCreate(lua_State *L) {
@@ -118,26 +116,7 @@ int moduleCameraCreate(lua_State *L) {
return 1; return 1;
} }
int moduleCameraPushMatrix(lua_State *L) { int moduleCameraIndex(lua_State *l) {
assertNotNull(L, "Lua state cannot be NULL.");
assertTrue(lua_gettop(L) >= 1, "cameraPushMatrix requires 1 arg.");
assertTrue(lua_isuserdata(L, 1), "cameraPushMatrix arg must be userdata.");
// Camera should be provided (pointer to camera_t).
camera_t *cam = (camera_t *)luaL_checkudata(L, 1, "camera_mt");
assertNotNull(cam, "Camera pointer cannot be NULL.");
cameraPushMatrix(cam);
return 0;
}
int moduleCameraPopMatrix(lua_State *L) {
assertNotNull(L, "Lua state cannot be NULL.");
cameraPopMatrix();
return 0;
}
int moduleCameraIndex(lua_State *l) {
assertNotNull(l, "Lua state cannot be NULL."); assertNotNull(l, "Lua state cannot be NULL.");
const char_t *key = luaL_checkstring(l, 2); const char_t *key = luaL_checkstring(l, 2);

View File

@@ -23,22 +23,6 @@ void moduleCamera(scriptcontext_t *context);
*/ */
int moduleCameraCreate(lua_State *L); int moduleCameraCreate(lua_State *L);
/**
* Script binding for pushing the camera matrix onto the matrix stack.
*
* @param L The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleCameraPushMatrix(lua_State *L);
/**
* Script binding for popping the camera matrix from the matrix stack.
*
* @param L The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleCameraPopMatrix(lua_State *L);
/** /**
* Getter for camera structure fields. * Getter for camera structure fields.
* *

View File

@@ -19,7 +19,7 @@ int moduleSceneSet(lua_State *L) {
assertNotNull(L, "Lua state cannot be NULL"); assertNotNull(L, "Lua state cannot be NULL");
// Need string // Need string
if (!lua_isstring(L, 1)) { if(!lua_isstring(L, 1)) {
luaL_error(L, "sceneSet requires a string argument"); luaL_error(L, "sceneSet requires a string argument");
return 0; return 0;
} }

View File

@@ -26,12 +26,12 @@ int moduleSysPrint(lua_State *L) {
luaL_Buffer b; luaL_Buffer b;
luaL_buffinit(L, &b); luaL_buffinit(L, &b);
for (int i = 1; i <= n; ++i) { for(int i = 1; i <= n; ++i) {
size_t len; size_t len;
const char *s = luaL_tolstring(L, i, &len); // converts any value to string const char *s = luaL_tolstring(L, i, &len); // converts any value to string
luaL_addlstring(&b, s, len); luaL_addlstring(&b, s, len);
lua_pop(L, 1); // pop result of luaL_tolstring lua_pop(L, 1); // pop result of luaL_tolstring
if (i < n) luaL_addlstring(&b, "\t", 1); if(i < n) luaL_addlstring(&b, "\t", 1);
} }
luaL_pushresult(&b); luaL_pushresult(&b);

View File

@@ -30,11 +30,11 @@ void uiRender(void) {
UI.camera.orthographic.right = SCREEN.width; UI.camera.orthographic.right = SCREEN.width;
UI.camera.orthographic.top = SCREEN.height; UI.camera.orthographic.top = SCREEN.height;
cameraPushMatrix(&UI.camera); // cameraPushMatrix(&UI.camera);
spriteBatchClear(); spriteBatchClear();
spriteBatchFlush(); spriteBatchFlush();
cameraPopMatrix(); // cameraPopMatrix();
} }
void uiDispose(void) { void uiDispose(void) {

View File

@@ -21,9 +21,10 @@ errorret_t meshInitGL(
mesh->primitiveType = primitiveType; mesh->primitiveType = primitiveType;
mesh->vertexCount = vertexCount; mesh->vertexCount = vertexCount;
mesh->vertices = vertices;
#ifdef DUSK_OPENGL_LEGACY #ifdef DUSK_OPENGL_LEGACY
mesh->vertices = vertices; // Nothing needed.
#else #else
// Generate Vertex Buffer Object // Generate Vertex Buffer Object
glGenBuffers(1, &mesh->vboId); glGenBuffers(1, &mesh->vboId);
@@ -34,7 +35,7 @@ errorret_t meshInitGL(
GL_ARRAY_BUFFER, GL_ARRAY_BUFFER,
vertexCount * sizeof(meshvertex_t), vertexCount * sizeof(meshvertex_t),
vertices, vertices,
GL_STATIC_DRAW GL_DYNAMIC_DRAW
); );
errorChain(errorGLCheck()); errorChain(errorGLCheck());
@@ -93,6 +94,27 @@ errorret_t meshInitGL(
errorOk(); errorOk();
} }
errorret_t meshFlushGL(
meshgl_t *mesh,
const int32_t vertOffset,
const int32_t vertCount
) {
#ifdef DUSK_OPENGL_LEGACY
// Nothing doing, we use the glClientState stuff.
#else
glBindBuffer(GL_ARRAY_BUFFER, mesh->vboId);
errorChain(errorGLCheck());
glBufferData(
GL_ARRAY_BUFFER,
vertCount * sizeof(meshvertex_t),
&mesh->vertices[vertOffset],
GL_DYNAMIC_DRAW
);
errorChain(errorGLCheck());
#endif
errorOk();
}
errorret_t meshDrawGL( errorret_t meshDrawGL(
const meshgl_t *mesh, const meshgl_t *mesh,
const int32_t offset, const int32_t offset,

View File

@@ -18,9 +18,10 @@ typedef enum {
typedef struct { typedef struct {
int32_t vertexCount; int32_t vertexCount;
meshprimitivetypegl_t primitiveType; meshprimitivetypegl_t primitiveType;
const meshvertex_t *vertices;
#ifdef DUSK_OPENGL_LEGACY #ifdef DUSK_OPENGL_LEGACY
const meshvertex_t *vertices; // Nothing needed
#else #else
GLuint vaoId; GLuint vaoId;
GLuint vboId; GLuint vboId;
@@ -43,6 +44,20 @@ errorret_t meshInitGL(
const meshvertex_t *vertices const meshvertex_t *vertices
); );
/**
* Flushes the vertices (stored in memory) to the GPU.
*
* @param mesh Mesh to flush vertices for.
* @param vertOffset First vertice index to flush.
* @param vertCount Count of vertices to flush.
* @return Error state.
*/
errorret_t meshFlushGL(
meshgl_t *mesh,
const int32_t vertOffset,
const int32_t vertCount
);
/** /**
* Draws a mesh using OpenGL. * Draws a mesh using OpenGL.
* *

View File

@@ -12,6 +12,7 @@ typedef meshprimitivetypegl_t meshprimitivetypeplatform_t;
typedef meshgl_t meshplatform_t; typedef meshgl_t meshplatform_t;
#define meshInitPlatform meshInitGL #define meshInitPlatform meshInitGL
#define meshFlushPlatform meshFlushGL
#define meshDrawPlatform meshDrawGL #define meshDrawPlatform meshDrawGL
#define meshGetVertexCountPlatform meshGetVertexCountGL #define meshGetVertexCountPlatform meshGetVertexCountGL
#define meshDisposePlatform meshDisposeGL #define meshDisposePlatform meshDisposeGL

View File

@@ -19,7 +19,7 @@ void logDebug(const char_t *message, ...) {
// print to file // print to file
FILE *file = fopen("ms0:/PSP/GAME/Dusk/debug.log", "a"); FILE *file = fopen("ms0:/PSP/GAME/Dusk/debug.log", "a");
if (file) { if(file) {
va_copy(copy, args); va_copy(copy, args);
vfprintf(file, message, copy); vfprintf(file, message, copy);
va_end(copy); va_end(copy);
@@ -41,7 +41,7 @@ void logError(const char_t *message, ...) {
// print to file // print to file
FILE *file = fopen("ms0:/PSP/GAME/Dusk/error.log", "a"); FILE *file = fopen("ms0:/PSP/GAME/Dusk/error.log", "a");
if (file) { if(file) {
va_copy(copy, args); va_copy(copy, args);
vfprintf(file, message, copy); vfprintf(file, message, copy);
va_end(copy); va_end(copy);

View File

@@ -247,13 +247,13 @@
// Draw red grid lines for tile boundaries // Draw red grid lines for tile boundaries
ctx.strokeStyle = 'rgba(255,0,0,1)'; ctx.strokeStyle = 'rgba(255,0,0,1)';
for (let x = v.scaledTileWidth; x < elOutputPreview.width; x += v.scaledTileWidth) { for(let x = v.scaledTileWidth; x < elOutputPreview.width; x += v.scaledTileWidth) {
ctx.beginPath(); ctx.beginPath();
ctx.moveTo(x, 0); ctx.moveTo(x, 0);
ctx.lineTo(x, elOutputPreview.height); ctx.lineTo(x, elOutputPreview.height);
ctx.stroke(); ctx.stroke();
} }
for (let y = v.scaledTileHeight; y < elOutputPreview.height; y += v.scaledTileHeight) { for(let y = v.scaledTileHeight; y < elOutputPreview.height; y += v.scaledTileHeight) {
ctx.beginPath(); ctx.beginPath();
ctx.moveTo(0, y); ctx.moveTo(0, y);
ctx.lineTo(elOutputPreview.width, y); ctx.lineTo(elOutputPreview.width, y);
@@ -289,7 +289,7 @@
btnBackgroundGreen.addEventListener('click', () => document.body.style.background = 'green'); btnBackgroundGreen.addEventListener('click', () => document.body.style.background = 'green');
elDefineBySize.addEventListener('change', () => { elDefineBySize.addEventListener('change', () => {
if (elDefineBySize.checked) { if(elDefineBySize.checked) {
elTileSizes.style.display = ''; elTileSizes.style.display = '';
elTileCounts.style.display = 'none'; elTileCounts.style.display = 'none';
} }
@@ -297,7 +297,7 @@
}); });
elDefineByCount.addEventListener('change', () => { elDefineByCount.addEventListener('change', () => {
if (elDefineByCount.checked) { if(elDefineByCount.checked) {
elTileSizes.style.display = 'none'; elTileSizes.style.display = 'none';
elTileCounts.style.display = ''; elTileCounts.style.display = '';
} }
@@ -332,7 +332,7 @@
elOutputError.style.display = 'none'; elOutputError.style.display = 'none';
pixels = null; pixels = null;
if (!elFileInput.files.length) { if(!elFileInput.files.length) {
elOutputError.textContent = 'No file selected'; elOutputError.textContent = 'No file selected';
elOutputError.style.display = 'block'; elOutputError.style.display = 'block';
return; return;
@@ -340,18 +340,18 @@
const file = elFileInput.files[0]; const file = elFileInput.files[0];
if (file.name.endsWith('.dpt')) { if(file.name.endsWith('.dpt')) {
// Load DPT file // Load DPT file
const reader = new FileReader(); const reader = new FileReader();
reader.onload = () => { reader.onload = () => {
const arrayBuffer = reader.result; const arrayBuffer = reader.result;
const data = new Uint8Array(arrayBuffer); const data = new Uint8Array(arrayBuffer);
if (data[0] !== 'D'.charCodeAt(0) || data[1] !== 'P'.charCodeAt(0) || data[2] !== 'T'.charCodeAt(0)) { if(data[0] !== 'D'.charCodeAt(0) || data[1] !== 'P'.charCodeAt(0) || data[2] !== 'T'.charCodeAt(0)) {
elOutputError.textContent = 'Invalid DPT file'; elOutputError.textContent = 'Invalid DPT file';
elOutputError.style.display = 'block'; elOutputError.style.display = 'block';
return; return;
} else if (data[3] !== 0x01) { } else if(data[3] !== 0x01) {
elOutputError.textContent = 'Unsupported DPT version'; elOutputError.textContent = 'Unsupported DPT version';
elOutputError.style.display = 'block'; elOutputError.style.display = 'block';
return; return;
@@ -381,15 +381,15 @@
} }
const uniqueIndexes = []; const uniqueIndexes = [];
for (let i = 0; i < width * height; i++) { for(let i = 0; i < width * height; i++) {
const colorIndex = data[12 + i]; const colorIndex = data[12 + i];
if (!uniqueIndexes.includes(colorIndex)) { if(!uniqueIndexes.includes(colorIndex)) {
uniqueIndexes.push(colorIndex); uniqueIndexes.push(colorIndex);
} }
} }
const adhocPalette = []; const adhocPalette = [];
for (let i = 0; i < uniqueIndexes.length; i++) { for(let i = 0; i < uniqueIndexes.length; i++) {
const index = uniqueIndexes[i]; const index = uniqueIndexes[i];
// Get the most different possible color for this index // Get the most different possible color for this index
const color = [ const color = [
@@ -402,7 +402,7 @@
} }
pixels = new Uint8Array(width * height * 4); pixels = new Uint8Array(width * height * 4);
for (let i = 0; i < width * height; i++) { for(let i = 0; i < width * height; i++) {
const colorIndex = data[12 + i]; const colorIndex = data[12 + i];
const color = adhocPalette[colorIndex]; const color = adhocPalette[colorIndex];
pixels[i * 4] = color[0]; pixels[i * 4] = color[0];
@@ -487,13 +487,13 @@
input.accept = '.dtf'; input.accept = '.dtf';
input.addEventListener('change', (e) => { input.addEventListener('change', (e) => {
const files = e?.target?.files; const files = e?.target?.files;
if (!files || !files.length || !files[0]) { if(!files || !files.length || !files[0]) {
alert('No file selected'); alert('No file selected');
return; return;
} }
const file = files[0]; const file = files[0];
if (!file.name.endsWith('.dtf')) { if(!file.name.endsWith('.dtf')) {
alert('Invalid file type. Please select a .dtf file.'); alert('Invalid file type. Please select a .dtf file.');
return; return;
} }
@@ -502,12 +502,12 @@
reader.onload = () => { reader.onload = () => {
const arrayBuffer = reader.result; const arrayBuffer = reader.result;
const data = new Uint8Array(arrayBuffer); const data = new Uint8Array(arrayBuffer);
if (data[0] !== 'D'.charCodeAt(0) || data[1] !== 'T'.charCodeAt(0) || data[2] !== 'F'.charCodeAt(0)) { if(data[0] !== 'D'.charCodeAt(0) || data[1] !== 'T'.charCodeAt(0) || data[2] !== 'F'.charCodeAt(0)) {
alert('Invalid DTF file'); alert('Invalid DTF file');
return; return;
} }
if (data[3] !== 0x00) { if(data[3] !== 0x00) {
alert('Unsupported DTF version'); alert('Unsupported DTF version');
return; return;
} }