npm run format

This commit is contained in:
Dennis Postma 2024-12-21 22:51:08 +01:00
parent eb2648d31f
commit 23c437f0bc
4 changed files with 52 additions and 55 deletions

View File

@ -110,4 +110,4 @@ router.get('/assets/:type/:spriteId?/:file', (req: Request, res: Response) => {
}) })
}) })
export default router export default router

View File

@ -87,4 +87,4 @@ router.post('/new-password', async (req: Request, res: Response) => {
return res.status(400).json({ message: 'Failed to set new password' }) return res.status(400).json({ message: 'Failed to set new password' })
}) })
export default router export default router

View File

@ -4,12 +4,9 @@ import fs from 'fs'
import path from 'path' import path from 'path'
async function addHttpRoutes(app: Application) { async function addHttpRoutes(app: Application) {
const routeFiles = fs.readdirSync(__dirname) const routeFiles = fs.readdirSync(__dirname).filter((file) => {
.filter(file => { return file !== 'index.ts' && file !== 'index.js' && (file.endsWith('.ts') || file.endsWith('.js'))
return file !== 'index.ts' && })
file !== 'index.js' &&
(file.endsWith('.ts') || file.endsWith('.js'))
})
for (const file of routeFiles) { for (const file of routeFiles) {
const route = await import(path.join(__dirname, file)) const route = await import(path.join(__dirname, file))
@ -21,4 +18,4 @@ async function addHttpRoutes(app: Application) {
httpLogger.info('Web routes added') httpLogger.info('Web routes added')
} }
export { addHttpRoutes } export { addHttpRoutes }

View File

@ -71,17 +71,14 @@ export default class SpriteUpdateEvent {
private async handleSpriteUpdate(payload: UpdatePayload, callback: (success: boolean) => void): Promise<void> { private async handleSpriteUpdate(payload: UpdatePayload, callback: (success: boolean) => void): Promise<void> {
try { try {
if (!await this.validateGameMasterAccess()) { if (!(await this.validateGameMasterAccess())) {
return callback(false) return callback(false)
} }
const parsedActions = this.validateSpriteActions(payload.spriteActions) const parsedActions = this.validateSpriteActions(payload.spriteActions)
const processedActions = await this.processSprites(parsedActions) const processedActions = await this.processSprites(parsedActions)
await Promise.all([ await Promise.all([this.updateDatabase(payload.id, payload.name, processedActions), this.saveSpritesToDisk(payload.id, processedActions)])
this.updateDatabase(payload.id, payload.name, processedActions),
this.saveSpritesToDisk(payload.id, processedActions)
])
callback(true) callback(true)
} catch (error) { } catch (error) {
@ -107,23 +104,25 @@ export default class SpriteUpdateEvent {
} }
private async processSprites(actions: SpriteActionInput[]): Promise<ProcessedSpriteAction[]> { private async processSprites(actions: SpriteActionInput[]): Promise<ProcessedSpriteAction[]> {
return Promise.all(actions.map(async (action) => { return Promise.all(
const spriteBuffers = await this.convertBase64ToBuffers(action.sprites) actions.map(async (action) => {
const frameWidth = ISOMETRIC_CONFIG.tileWidth const spriteBuffers = await this.convertBase64ToBuffers(action.sprites)
const frameHeight = await this.calculateOptimalHeight(spriteBuffers) const frameWidth = ISOMETRIC_CONFIG.tileWidth
const processedFrames = await this.normalizeFrames(spriteBuffers, frameWidth, frameHeight) const frameHeight = await this.calculateOptimalHeight(spriteBuffers)
const processedFrames = await this.normalizeFrames(spriteBuffers, frameWidth, frameHeight)
return { return {
...action, ...action,
frameWidth, frameWidth,
frameHeight, frameHeight,
buffersWithDimensions: processedFrames buffersWithDimensions: processedFrames
} }
})) })
)
} }
private async convertBase64ToBuffers(sprites: string[]): Promise<Buffer[]> { private async convertBase64ToBuffers(sprites: string[]): Promise<Buffer[]> {
return sprites.map(sprite => Buffer.from(sprite.split(',')[1], 'base64')) return sprites.map((sprite) => Buffer.from(sprite.split(',')[1], 'base64'))
} }
private async normalizeFrames(buffers: Buffer[], frameWidth: number, frameHeight: number): Promise<ProcessedFrame[]> { private async normalizeFrames(buffers: Buffer[], frameWidth: number, frameHeight: number): Promise<ProcessedFrame[]> {
@ -141,7 +140,7 @@ export default class SpriteUpdateEvent {
private async calculateOptimalHeight(buffers: Buffer[]): Promise<number> { private async calculateOptimalHeight(buffers: Buffer[]): Promise<number> {
const heights = await Promise.all( const heights = await Promise.all(
buffers.map(async buffer => { buffers.map(async (buffer) => {
const bounds = await this.findContentBounds(buffer) const bounds = await this.findContentBounds(buffer)
return bounds.height return bounds.height
}) })
@ -180,12 +179,14 @@ export default class SpriteUpdateEvent {
background: { r: 0, g: 0, b: 0, alpha: 0 } background: { r: 0, g: 0, b: 0, alpha: 0 }
} }
}) })
.composite([{ .composite([
input: processedInput, {
left: offset, input: processedInput,
top: 0, left: offset,
blend: 'over' top: 0,
}]) blend: 'over'
}
])
.png({ .png({
compressionLevel: 9, compressionLevel: 9,
adaptiveFiltering: false, adaptiveFiltering: false,
@ -249,17 +250,14 @@ export default class SpriteUpdateEvent {
} }
private findSpinePosition(density: number[]): number { private findSpinePosition(density: number[]): number {
return density.reduce((maxIdx, curr, idx, arr) => curr > arr[maxIdx] ? idx : maxIdx, 0) return density.reduce((maxIdx, curr, idx, arr) => (curr > arr[maxIdx] ? idx : maxIdx), 0)
} }
private calculateWeightedMassCenter(columnDensity: number[], upperBodyDensity: number[]): number { private calculateWeightedMassCenter(columnDensity: number[], upperBodyDensity: number[]): number {
const upperMassCenter = this.calculateMassCenter(upperBodyDensity) const upperMassCenter = this.calculateMassCenter(upperBodyDensity)
const lowerMassCenter = this.calculateMassCenter(columnDensity) const lowerMassCenter = this.calculateMassCenter(columnDensity)
return Math.round( return Math.round(upperMassCenter * ISOMETRIC_CONFIG.bodyRatios.weightUpper + lowerMassCenter * ISOMETRIC_CONFIG.bodyRatios.weightLower)
upperMassCenter * ISOMETRIC_CONFIG.bodyRatios.weightUpper +
lowerMassCenter * ISOMETRIC_CONFIG.bodyRatios.weightLower
)
} }
private calculateMassCenter(density: number[]): number { private calculateMassCenter(density: number[]): number {
@ -271,10 +269,7 @@ export default class SpriteUpdateEvent {
} }
private async findContentBounds(buffer: Buffer) { private async findContentBounds(buffer: Buffer) {
const { data, info } = await sharp(buffer) const { data, info } = await sharp(buffer).raw().ensureAlpha().toBuffer({ resolveWithObject: true })
.raw()
.ensureAlpha()
.toBuffer({ resolveWithObject: true })
const width = info.width const width = info.width
const height = info.height const height = info.height
@ -288,7 +283,8 @@ export default class SpriteUpdateEvent {
for (let y = 0; y < height; y++) { for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) { for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4 const idx = (y * width + x) * 4
if (data[idx + 3] > 0) { // If pixel is not transparent if (data[idx + 3] > 0) {
// If pixel is not transparent
left = Math.min(left, x) left = Math.min(left, x)
right = Math.max(right, x) right = Math.max(right, x)
top = Math.min(top, y) top = Math.min(top, y)
@ -309,10 +305,12 @@ export default class SpriteUpdateEvent {
const publicFolder = getPublicPath('sprites', id) const publicFolder = getPublicPath('sprites', id)
await mkdir(publicFolder, { recursive: true }) await mkdir(publicFolder, { recursive: true })
await Promise.all(actions.map(async (action) => { await Promise.all(
const spritesheet = await this.createSpritesheet(action.buffersWithDimensions) actions.map(async (action) => {
await writeFile(getPublicPath('sprites', id, `${action.action}.png`), spritesheet) const spritesheet = await this.createSpritesheet(action.buffersWithDimensions)
})) await writeFile(getPublicPath('sprites', id, `${action.action}.png`), spritesheet)
})
)
} }
private async createSpritesheet(frames: ProcessedFrame[]): Promise<Buffer> { private async createSpritesheet(frames: ProcessedFrame[]): Promise<Buffer> {
@ -335,12 +333,14 @@ export default class SpriteUpdateEvent {
.toBuffer() .toBuffer()
return sharp(background) return sharp(background)
.composite(frames.map((frame, index) => ({ .composite(
input: frame.buffer, frames.map((frame, index) => ({
left: index * ISOMETRIC_CONFIG.tileWidth, input: frame.buffer,
top: 0, left: index * ISOMETRIC_CONFIG.tileWidth,
blend: 'over' top: 0,
}))) blend: 'over'
}))
)
.png({ .png({
compressionLevel: 9, compressionLevel: 9,
adaptiveFiltering: false, adaptiveFiltering: false,
@ -387,4 +387,4 @@ export default class SpriteUpdateEvent {
private getErrorMessage(error: unknown): string { private getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error) return error instanceof Error ? error.message : String(error)
} }
} }