diff --git a/.vscode/settings.json b/.vscode/settings.json index e8e2447..dd290fb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,7 +9,7 @@ "editor.tabSize": 2, - "[josn,ts]": { + "[josn,typescript]": { "editor.defaultFormatter": "denoland.vscode-deno" } } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 810e3b4..ed3ab40 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -145,6 +145,20 @@ }, "problemMatcher": ["$deno"] }, + { + "label": "Run Version", + "group": { + "kind": "none", + "isDefault": true + }, + "type": "deno", + "command": "task", + "args": ["run:version"], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": ["$deno"] + }, { "type": "deno", "command": "task", diff --git a/License.txt b/License.txt index e121bf8..de451b9 100644 --- a/License.txt +++ b/License.txt @@ -1,5 +1,5 @@ MIT License -Copyright (c) 2022 Zachary Snow +Copyright (c) 2024 Zachary Snow Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Readme.md b/Readme.md index c6df7d7..81e2121 100644 --- a/Readme.md +++ b/Readme.md @@ -17,7 +17,12 @@ Currently working via [deno](https://deno.land/) on Windows, Linux, and mac OS u ## Non Goals -- Creating a higher level API or Game Framework. This library's only purpose is to expose the SDL API to deno. +- Creating a higher level API or Game Framework. This library's only purpose is to expose the SDL API to TypeScript. + +## Versioning + +This library's version number will match the SDL major and minor version against which it is currently tested. The patch +number will be specifici to this library. I.E. ## Getting Started @@ -58,19 +63,9 @@ brew install sdl2 sdl2_image sdl2_ttf ### Creating a Project -To aid in creating a new project which uses `SDL_ts` there is an `init.ts` script to aid in getting your project set up: - -```bash -deno run --allow-net --allow-read=/path/to/project --allow-write=/path/to/project --import-map https://deno.land/x/sdl_ts@0.0.4/imports.deno.json https://deno.land/x/sdl_ts@0.0.4/init.ts /path/to/project -``` - -Replace `/path/to/project` with the desired project path. After that the new project can be started via a deno task: - -```bash -deno task start -``` - -You should be presented with a window titled "SDL_ts". +Located in the directory [examples/getting-started](examples/getting-started/) are a minimal set of files needed to get +a project up and running. Copy these files onto your computer and start the project with `deno task start`. You should +see a window with `SDL_ts` as the title. ### Loading only required functions diff --git a/VERSION b/VERSION deleted file mode 100644 index 05b19b1..0000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.0.4 \ No newline at end of file diff --git a/deno.json b/deno.json index 2c54107..b4422d6 100644 --- a/deno.json +++ b/deno.json @@ -1,4 +1,7 @@ { + "name": "@smack0007/sdl-ts", + "version": "2.30.1", + "exports": "./mod.ts", "compilerOptions": { "lib": ["deno.window", "deno.unstable"] }, @@ -14,7 +17,12 @@ "exclude": ["no-inferrable-types"] } }, - "importMap": "imports.json", + "imports": { + "SDL_ts": "./mod.ts", + "@std/assert": "jsr:@std/assert@1.0.0", + "@std/colors": "jsr:@std/fmt@0.225.6/colors", + "@std/path": "jsr:@std/path@1.0.1" + }, "tasks": { "build": "cd ./scripts && deno run --allow-read --allow-run ./build.ts", "build:ci": "deno task build --ci", @@ -28,6 +36,7 @@ "run:play-wav": "cd ./examples/play-wav && SDL_TS_ENV_DIR=$INIT_CWD deno run --unstable-ffi --allow-env --allow-ffi --allow-read=../.. $DENO_FLAGS ./main.ts", "run:renderer": "cd ./examples/renderer && SDL_TS_ENV_DIR=$INIT_CWD deno run --unstable-ffi --allow-env --allow-ffi --allow-read=../.. $DENO_FLAGS ./main.ts", "run:same-game": "cd ./examples/same-game && SDL_TS_ENV_DIR=$INIT_CWD deno run --unstable-ffi --allow-env --allow-ffi --allow-read=../.. $DENO_FLAGS ./main.ts", + "run:version": "cd ./examples/version && SDL_TS_ENV_DIR=$INIT_CWD deno run --unstable-ffi --allow-env --allow-ffi --allow-read=../.. $DENO_FLAGS ./main.ts", "test": "deno test --unstable-ffi --allow-ffi" } } diff --git a/deps.ts b/deps.ts deleted file mode 100644 index c293a62..0000000 --- a/deps.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * as asserts from "https://deno.land/std@0.215.0/testing/asserts.ts"; -export * as dotenv from "https://deno.land/std@0.215.0/dotenv/mod.ts"; -export * as colors from "https://deno.land/std@0.215.0/fmt/colors.ts"; -export * as fs from "https://deno.land/std@0.215.0/fs/mod.ts"; -export * as path from "https://deno.land/std@0.215.0/path/mod.ts"; diff --git a/examples/doom-fire/main.ts b/examples/doom-fire/main.ts index 69695e0..c2c36e3 100644 --- a/examples/doom-fire/main.ts +++ b/examples/doom-fire/main.ts @@ -1,7 +1,7 @@ import { IMG, SDL } from "SDL_ts"; import { IMG_FUNCTIONS, SDL_FUNCTIONS } from "./sdlConfig.ts"; import { ASSETS_PATH } from "../../shared/constants.ts"; -import { path } from "../../deps.ts"; +import { join } from "@std/path"; const WINDOW_WIDTH = 1024; const WINDOW_HEIGHT = 768; @@ -11,43 +11,13 @@ const FIRE_WIDTH = 1024; const FIRE_HEIGHT = 120; const FIRE_COLORS = [ - 0x00000000, - 0xC0070707, - 0xC007071F, - 0xC0070F2F, - 0xC0070F47, - 0xC0071757, - 0xC0071F67, - 0xC0071F77, - 0xC007278F, - 0xC0072F9F, - 0xC0073FAF, - 0xC00747BF, - 0xC00747C7, - 0xC0074FDF, - 0xC00757DF, - 0xC00757DF, - 0xC0075FD7, - 0xC00F67D7, - 0xC00F6FCF, - 0xC00F77CF, - 0xC00F7FCF, - 0xC01787CF, - 0xC01787C7, - 0xC0178FC7, - 0xC01F97C7, - 0xC01F9FBF, - 0xC01F9FBF, - 0xC027A7BF, - 0xC027A7BF, - 0xC02FAFBF, - 0xC02FAFB7, - 0xC02FB7B7, - 0xC037B7B7, - 0xC06FCFCF, - 0xC09FDFDF, - 0xC0C7EFEF, - 0xC0FFFFFF, + 0x00000000, 0xc0070707, 0xc007071f, 0xc0070f2f, 0xc0070f47, 0xc0071757, + 0xc0071f67, 0xc0071f77, 0xc007278f, 0xc0072f9f, 0xc0073faf, 0xc00747bf, + 0xc00747c7, 0xc0074fdf, 0xc00757df, 0xc00757df, 0xc0075fd7, 0xc00f67d7, + 0xc00f6fcf, 0xc00f77cf, 0xc00f7fcf, 0xc01787cf, 0xc01787c7, 0xc0178fc7, + 0xc01f97c7, 0xc01f9fbf, 0xc01f9fbf, 0xc027a7bf, 0xc027a7bf, 0xc02fafbf, + 0xc02fafb7, 0xc02fb7b7, 0xc037b7b7, 0xc06fcfcf, 0xc09fdfdf, 0xc0c7efef, + 0xc0ffffff, ]; function main(): number { @@ -61,7 +31,9 @@ function main(): number { return 1; } - console.info(`SDL_image Version: ${version.major}.${version.minor}.${version.patch}`); + console.info( + `SDL_image Version: ${version.major}.${version.minor}.${version.patch}` + ); const window = SDL.CreateWindow( "Doom Fire", @@ -69,7 +41,7 @@ function main(): number { SDL.WindowPos.CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, - SDL.WindowFlags.SHOWN, + SDL.WindowFlags.SHOWN ); if (window == null) { @@ -84,14 +56,20 @@ function main(): number { return 1; } - const denoSurfaceUnoptimized = IMG.Load(path.join(ASSETS_PATH, "jurassicDeno.png")); + const denoSurfaceUnoptimized = IMG.Load( + join(ASSETS_PATH, "jurassicDeno.png") + ); if (denoSurfaceUnoptimized == null) { console.error("Failed to load jurassicDeno.png."); return 1; } - const denoSurface = SDL.ConvertSurface(denoSurfaceUnoptimized, frontBuffer.format, 0); + const denoSurface = SDL.ConvertSurface( + denoSurfaceUnoptimized, + frontBuffer.format, + 0 + ); if (denoSurface == null) { console.error("Failed to convert surface format of jurassicDeno.png."); @@ -107,10 +85,10 @@ function main(): number { FIRE_HEIGHT, 32, 4 * FIRE_WIDTH, - 0x000000FF, - 0x0000FF00, - 0x00FF0000, - 0xFF000000, + 0x000000ff, + 0x0000ff00, + 0x00ff0000, + 0xff000000 ); if (fireSurface == null) { @@ -118,12 +96,18 @@ function main(): number { return 1; } - const flamesRect = new SDL.Rect(0, HALF_WINDOW_HEIGHT, frontBuffer.w, HALF_WINDOW_HEIGHT); + const flamesRect = new SDL.Rect( + 0, + HALF_WINDOW_HEIGHT, + frontBuffer.w, + HALF_WINDOW_HEIGHT + ); firePixels.fill(0x00000000); for (let x = 0; x < FIRE_WIDTH; x += 1) { - firePixels[(FIRE_HEIGHT - 1) * FIRE_WIDTH + x] = FIRE_COLORS[FIRE_COLORS.length - 1]; + firePixels[(FIRE_HEIGHT - 1) * FIRE_WIDTH + x] = + FIRE_COLORS[FIRE_COLORS.length - 1]; } let lastFrame = SDL.GetTicks64(); diff --git a/examples/getting-started/deno.json b/examples/getting-started/deno.json new file mode 100644 index 0000000..9c13520 --- /dev/null +++ b/examples/getting-started/deno.json @@ -0,0 +1,6 @@ +{ + "imports": { "@smack0007/sdl-ts": "jsr:@smack0007/sdl-ts" }, + "tasks": { + "start": "deno run --unstable-ffi --allow-env --allow-ffi --allow-read=. ./main.ts" + } +} diff --git a/tools/init/main.ts b/examples/getting-started/main.ts similarity index 62% rename from tools/init/main.ts rename to examples/getting-started/main.ts index 4b841f3..533bc85 100644 --- a/tools/init/main.ts +++ b/examples/getting-started/main.ts @@ -1,4 +1,4 @@ -import { SDL } from "SDL_ts"; +import { SDL } from "@smack0007/sdl-ts"; function main(): number { SDL.Init(SDL.InitFlags.VIDEO); @@ -9,14 +9,24 @@ function main(): number { SDL.WindowPos.CENTERED, 1024, 768, - SDL.WindowFlags.SHOWN | SDL.WindowFlags.RESIZABLE, + SDL.WindowFlags.SHOWN | SDL.WindowFlags.RESIZABLE ); if (window == null) { console.error(`Failed to create window: ${SDL.GetError()}`); - Deno.exit(1); + return 1; } + const renderer = SDL.CreateRenderer(window, 0, SDL.RendererFlags.ACCELERATED); + + if (renderer === null) { + console.error(`Failed to create window: ${SDL.GetError()}`); + return 1; + } + + SDL.RenderClear(renderer); + SDL.RenderPresent(renderer); + const event = new SDL.Event(); let done = false; diff --git a/examples/hello-world/main.ts b/examples/hello-world/main.ts index 6ef36ae..ff6e936 100644 --- a/examples/hello-world/main.ts +++ b/examples/hello-world/main.ts @@ -5,11 +5,6 @@ SDL.Init(SDL.InitFlags.VIDEO, { functions: SDL_FUNCTIONS }); console.info("SDL Initialized."); -const version = new SDL.version(); -SDL.GetVersion(version); -console.info(`SDL Version: ${version.major}.${version.minor}.${version.patch}`); -console.info(`SDL Revision: ${SDL.GetRevision()}`); - console.info(`${SDL.GetSystemRAM()} MB RAM available.`); const createWindowResult = SDL.CreateWindow( diff --git a/examples/hello-world/sdlConfig.ts b/examples/hello-world/sdlConfig.ts index 86d1ec1..5abc0af 100644 --- a/examples/hello-world/sdlConfig.ts +++ b/examples/hello-world/sdlConfig.ts @@ -10,10 +10,8 @@ export const SDL_FUNCTIONS = [ SDL.DestroyWindow, SDL.FillRect, SDL.GetError, - SDL.GetRevision, SDL.GetScancodeName, SDL.GetSystemRAM, - SDL.GetVersion, SDL.GetWindowSurface, SDL.Init, SDL.MapRGB, diff --git a/examples/play-wav/main.ts b/examples/play-wav/main.ts index e3da875..6344c19 100644 --- a/examples/play-wav/main.ts +++ b/examples/play-wav/main.ts @@ -1,9 +1,9 @@ // Adapted from https://gigi.nullneuron.net/gigilabs/playing-a-wav-file-using-sdl2/ -import { Box, Pointer, SDL, U32, U8, u32, u8 } from "SDL_ts"; +import { Box, Pointer, SDL, U32, u32, u8 } from "SDL_ts"; import { SDL_FUNCTIONS } from "./sdlConfig.ts"; import { ASSETS_PATH } from "../../shared/constants.ts"; -import { path } from "../../deps.ts"; +import { join } from "@std/path"; const main = (): number => { if (SDL.Init(SDL.InitFlags.AUDIO, { functions: SDL_FUNCTIONS }) < 0) { @@ -18,7 +18,7 @@ const main = (): number => { if ( SDL.LoadWav( - path.join(ASSETS_PATH, "powerup.wav"), + join(ASSETS_PATH, "powerup.wav"), wavSpec, wavBufferBox, wavLengthBox diff --git a/examples/renderer/main.ts b/examples/renderer/main.ts index cdcd0ed..bb80097 100644 --- a/examples/renderer/main.ts +++ b/examples/renderer/main.ts @@ -1,7 +1,7 @@ import { Box, BoxArray, Int, int, Memory, Pointer, SDL } from "SDL_ts"; import { SDL_FUNCTIONS } from "./sdlConfig.ts"; import { ASSETS_PATH } from "../../shared/constants.ts"; -import { path } from "../../deps.ts"; +import { join } from "@std/path"; const WINDOW_WIDTH = 1024; const WINDOW_HEIGHT = 768; @@ -46,7 +46,7 @@ function main(): number { SDL.RenderPresent(renderer); SDL.RenderFlush(renderer); - const denoSurface = SDL.LoadBMP(path.join(ASSETS_PATH, "jurassicDeno.bmp")); + const denoSurface = SDL.LoadBMP(join(ASSETS_PATH, "jurassicDeno.bmp")); if (denoSurface == null) { console.error("Failed to load jurassicDeno.bmp."); diff --git a/examples/renderer/sdlConfig.ts b/examples/renderer/sdlConfig.ts index 0a92a28..698075a 100644 --- a/examples/renderer/sdlConfig.ts +++ b/examples/renderer/sdlConfig.ts @@ -5,6 +5,9 @@ import { SDL } from "SDL_ts"; export const SDL_FUNCTIONS = [ SDL.CreateTextureFromSurface, SDL.CreateWindowAndRenderer, + SDL.DestroyRenderer, + SDL.DestroyTexture, + SDL.DestroyWindow, SDL.Delay, SDL.FreeSurface, SDL.GetError, diff --git a/examples/same-game/fonts.ts b/examples/same-game/fonts.ts index 336c972..d3cc678 100644 --- a/examples/same-game/fonts.ts +++ b/examples/same-game/fonts.ts @@ -17,7 +17,7 @@ export type FontAtlas = { export function createFontAtlas( renderer: Pointer, fontPath: string, - fontSize: number, + fontSize: number ): FontAtlas { const fg = new SDL.Color(255, 255, 255, 255); const bg = new SDL.Color(0, 0, 0, 0); @@ -25,16 +25,32 @@ export function createFontAtlas( const font = TTF.OpenFont(fontPath, fontSize); if (font === null) { - throw new Error(`Failed to open font in ${createFontAtlas.name}: ${SDL.GetError()}`); + throw new Error( + `Failed to open font in ${createFontAtlas.name}: ${SDL.GetError()}` + ); } - const surface = SDL.CreateRGBSurfaceWithFormat(0, FONT_TEXTURE_SIZE, FONT_TEXTURE_SIZE, 32, SDL.PIXELFORMAT_RGBA8888); + const surface = SDL.CreateRGBSurfaceWithFormat( + 0, + FONT_TEXTURE_SIZE, + FONT_TEXTURE_SIZE, + 32, + SDL.PIXELFORMAT_RGBA8888 + ); if (surface === null) { - throw new Error(`Failed to create font surface in ${createFontAtlas.name}: ${SDL.GetError()}`); + throw new Error( + `Failed to create font surface in ${ + createFontAtlas.name + }: ${SDL.GetError()}` + ); } - SDL.FillRect(surface, null, SDL.MapRGBA(surface.format, bg.r, bg.g, bg.b, bg.a)); + SDL.FillRect( + surface, + null, + SDL.MapRGBA(surface.format, bg.r, bg.g, bg.b, bg.a) + ); const glyphs: GlyphData[] = []; let maxGlyphHeight = 0; @@ -45,12 +61,21 @@ export function createFontAtlas( const glyphSurface = TTF.RenderUTF8_Blended(font, character, fg); if (glyphSurface === null) { - throw new Error(`Failed to create glyph surface in ${createFontAtlas.name}: ${SDL.GetError()}`); + throw new Error( + `Failed to create glyph surface in ${ + createFontAtlas.name + }: ${SDL.GetError()}` + ); } // TODO(idea): Can we allow structs to return pointers to their members? const glyphSizeBox = new BoxArray(Int, 2); - TTF.SizeUTF8(font, character, glyphSizeBox.pointers.at(0), glyphSizeBox.pointers.at(1)); + TTF.SizeUTF8( + font, + character, + glyphSizeBox.pointersAt(0), + glyphSizeBox.pointersAt(1) + ); const glyphWidth = glyphSizeBox.at(0); const glyphHeight = glyphSizeBox.at(1); @@ -80,7 +105,9 @@ export function createFontAtlas( destination.y += maxGlyphHeight + 1; if (destination.y + destination.h >= FONT_TEXTURE_SIZE) { - throw new Error(`Ran out of glyph space in font atlas in ${createFontAtlas.name}`); + throw new Error( + `Ran out of glyph space in font atlas in ${createFontAtlas.name}` + ); } } @@ -98,7 +125,11 @@ export function createFontAtlas( const texture = SDL.CreateTextureFromSurface(renderer, surface); if (texture === null) { - throw new Error(`Failed to create font texture in ${createFontAtlas.name}: ${SDL.GetError()}`); + throw new Error( + `Failed to create font texture in ${ + createFontAtlas.name + }: ${SDL.GetError()}` + ); } SDL.SetTextureBlendMode(texture, SDL.BlendMode.BLEND); @@ -117,7 +148,7 @@ export function drawString( renderer: Pointer, font: FontAtlas, destination: SDL.Point, - text: string, + text: string ): void { const destRect = new SDL.Rect(destination.x, destination.y, 0, 0); @@ -139,7 +170,7 @@ export function drawString( export function measureString( font: FontAtlas, - text: string, + text: string ): { width: number; height: number } { let width = 0; let height = 0; diff --git a/examples/same-game/main.ts b/examples/same-game/main.ts index dbc9982..93367db 100644 --- a/examples/same-game/main.ts +++ b/examples/same-game/main.ts @@ -1,6 +1,6 @@ import { Box, IMG, Pointer, SDL, SDLError, TTF, u64 } from "SDL_ts"; import { IMG_FUNCTIONS, SDL_FUNCTIONS, TTF_FUNCTIONS } from "./sdlConfig.ts"; -import { path } from "../../deps.ts"; +import { join } from "@std/path"; import { Board } from "./logic/board.ts"; import { Random } from "./logic/random.ts"; import { drawBoard } from "./rendering/board.ts"; @@ -25,21 +25,32 @@ function main(): number { WINDOW_HEIGHT, SDL.WindowFlags.SHOWN, windowBox, - rendererBox, + rendererBox ); - const window = windowBox.unboxNotNull(() => `Failed to create window: ${SDL.GetError()}`); - const renderer = rendererBox.unboxNotNull(() => `Failed to create renderer: ${SDL.GetError()}`); + const window = windowBox.unboxNotNull( + () => `Failed to create window: ${SDL.GetError()}` + ); + const renderer = rendererBox.unboxNotNull( + () => `Failed to create renderer: ${SDL.GetError()}` + ); SDL.SetWindowTitle(window, "Same Game"); - const blockTexture = IMG.LoadTexture(renderer, path.join(ASSETS_PATH, "blocks.png")); + const blockTexture = IMG.LoadTexture( + renderer, + join(ASSETS_PATH, "blocks.png") + ); if (blockTexture == null) { throw new SDLError("Failed to create texture for block.png"); } - const font = createFontAtlas(renderer, path.join(ASSETS_PATH, "Hack.ttf"), FONT_SIZE); + const font = createFontAtlas( + renderer, + join(ASSETS_PATH, "Hack.ttf"), + FONT_SIZE + ); const board = new Board(new Random(12345)); @@ -87,10 +98,7 @@ function main(): number { return 0; } -function update( - elapsed: u64, - board: Board, -): void { +function update(elapsed: u64, board: Board): void { board.update(elapsed); } @@ -98,19 +106,24 @@ function draw( renderer: Pointer, board: Board, blockTexture: SDL.Texture, - font: FontAtlas, + font: FontAtlas ): void { SDL.SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL.RenderClear(renderer); drawBoard(renderer, board, blockTexture); - drawString(renderer, font, new SDL.Point(0, Board.HeightInPixels + 2), `Score: ${board.score}`); + drawString( + renderer, + font, + new SDL.Point(0, Board.HeightInPixels + 2), + `Score: ${board.score}` + ); drawString( renderer, font, new SDL.Point(0, Board.HeightInPixels + FONT_SIZE + 2), - `Selected: ${board.selectedBlockCount}`, + `Selected: ${board.selectedBlockCount}` ); SDL.RenderPresent(renderer); diff --git a/examples/version/main.ts b/examples/version/main.ts new file mode 100644 index 0000000..5d5642a --- /dev/null +++ b/examples/version/main.ts @@ -0,0 +1,11 @@ +import { SDL } from "SDL_ts"; +import { SDL_FUNCTIONS } from "./sdlConfig.ts"; + +SDL.Init(SDL.InitFlags.VIDEO, { functions: SDL_FUNCTIONS }); + +const version = new SDL.version(); +SDL.GetVersion(version); +console.info(`SDL Version: ${version.major}.${version.minor}.${version.patch}`); +console.info(`SDL Revision: ${SDL.GetRevision()}`); + +SDL.Quit(); diff --git a/examples/version/sdlConfig.ts b/examples/version/sdlConfig.ts new file mode 100644 index 0000000..6f3a88e --- /dev/null +++ b/examples/version/sdlConfig.ts @@ -0,0 +1,10 @@ +import { SDL } from "SDL_ts"; + +// This file contains the list of functions that are used in the project. + +export const SDL_FUNCTIONS = [ + SDL.Init, + SDL.GetRevision, + SDL.GetVersion, + SDL.Quit, +] as const; diff --git a/imports.json b/imports.json deleted file mode 100644 index a08aae7..0000000 --- a/imports.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "imports": { - "SDL_ts": "./mod.ts" - } -} diff --git a/init.ts b/init.ts deleted file mode 100644 index 275473e..0000000 --- a/init.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { main } from "./tools/init.ts"; - -Deno.exit(await main(Deno.args)); diff --git a/scripts/build.ts b/scripts/build.ts index 05885d5..d020547 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -1,30 +1,27 @@ -import { EXAMPLES_PATH, ROOT_PATH, TOOLS_PATH } from "../shared/constants.ts"; -import { colors, path } from "../deps.ts"; +import { EXAMPLES_PATH, TOOLS_PATH } from "../shared/constants.ts"; +import { green } from "@std/colors"; +import { join } from "@std/path"; async function main(): Promise { let failure = false; - if (!await typeCheck(path.join(ROOT_PATH, "init.ts"))) { + if (!(await typeCheck(join(TOOLS_PATH, "codegen.ts")))) { failure = true; } - if (!await typeCheck(path.join(TOOLS_PATH, "codegen.ts"))) { - failure = true; - } - - if (!await typeCheck(path.join(TOOLS_PATH, "codegen-scraper.ts"))) { + if (!(await typeCheck(join(TOOLS_PATH, "codegen-scraper.ts")))) { failure = true; } for await (const entry of Deno.readDir(EXAMPLES_PATH)) { if (entry.isDirectory) { - if (!await typeCheck(path.join(EXAMPLES_PATH, entry.name, "main.ts"))) { + if (!(await typeCheck(join(EXAMPLES_PATH, entry.name, "main.ts")))) { failure = true; } } } - if (!await runTests()) { + if (!(await runTests())) { failure = true; } @@ -32,17 +29,25 @@ async function main(): Promise { } async function typeCheck(filePath: string): Promise { - console.info(`${colors.green("Type checking:")} ${filePath}`); - return (await Deno.run({ - cmd: ["deno", "task", "-q", "check", filePath], - }).status()).code === 0; + console.info(`${green("Type checking:")} ${filePath}`); + return ( + ( + await Deno.run({ + cmd: ["deno", "task", "-q", "check", filePath], + }).status() + ).code === 0 + ); } async function runTests(): Promise { - console.info(`${colors.green("Running tests...")}`); - return (await Deno.run({ - cmd: ["deno", "task", "-q", "test"], - }).status()).code === 0; + console.info(`${green("Running tests...")}`); + return ( + ( + await Deno.run({ + cmd: ["deno", "task", "-q", "test"], + }).status() + ).code === 0 + ); } Deno.exit(await main()); diff --git a/shared/constants.ts b/shared/constants.ts index b8c68d9..8a5fae6 100644 --- a/shared/constants.ts +++ b/shared/constants.ts @@ -1,4 +1,4 @@ -import { path } from "../deps.ts"; +import { join, SEPARATOR } from "@std/path"; const IS_WINDOWS = Deno.build.os === "windows"; @@ -7,16 +7,16 @@ export const REPO_URL = "https://deno.land/x/sdl_ts"; export const ROOT_PATH = new URL(import.meta.url).pathname .replaceAll("/", IS_WINDOWS ? "\\" : "/") .substring(IS_WINDOWS ? 1 : 0) - .split(path.SEPARATOR) + .split(SEPARATOR) .slice(0, -2) - .join(path.SEPARATOR); + .join(SEPARATOR); -export const ASSETS_PATH = path.join(ROOT_PATH, "assets"); +export const ASSETS_PATH = join(ROOT_PATH, "assets"); -export const EXAMPLES_PATH = path.join(ROOT_PATH, "examples"); +export const EXAMPLES_PATH = join(ROOT_PATH, "examples"); -export const EXT_PATH = path.join(ROOT_PATH, "ext"); +export const EXT_PATH = join(ROOT_PATH, "ext"); -export const SRC_PATH = path.join(ROOT_PATH, "src"); +export const SRC_PATH = join(ROOT_PATH, "src"); -export const TOOLS_PATH = path.join(ROOT_PATH, "tools"); +export const TOOLS_PATH = join(ROOT_PATH, "tools"); diff --git a/src/SDL/pixels.ts b/src/SDL/pixels.ts index 4e4b657..8ca09c1 100644 --- a/src/SDL/pixels.ts +++ b/src/SDL/pixels.ts @@ -1,4 +1,5 @@ // deno-fmt-ignore-file +import { u32 } from "../types.ts"; import { ArrayOrder, BitmapOrder, @@ -18,44 +19,44 @@ function SDL_DEFINE_PIXELFORMAT( ((layout) << 16) | ((bits) << 8) | ((bytes) << 0)); } -export const PIXELFORMAT_UNKNOWN = 0; -export const PIXELFORMAT_INDEX1LSB = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX1, BitmapOrder._4321, 0, 1, 0); -export const PIXELFORMAT_INDEX1MSB = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX1, BitmapOrder._1234, 0, 1, 0); -export const PIXELFORMAT_INDEX4LSB = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX4, BitmapOrder._4321, 0, 4, 0); -export const PIXELFORMAT_INDEX4MSB = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX4, BitmapOrder._1234, 0, 4, 0); -export const PIXELFORMAT_INDEX8 = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX8, 0, 0, 8, 1); -export const PIXELFORMAT_RGB332 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED8, PackedOrder.XRGB, PackedLayout._332, 8, 1); -export const PIXELFORMAT_XRGB4444 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XRGB, PackedLayout._4444, 12, 2); -export const PIXELFORMAT_RGB444 = PIXELFORMAT_XRGB4444; -export const PIXELFORMAT_XBGR4444 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XBGR, PackedLayout._4444, 12, 2); -export const PIXELFORMAT_BGR444 = PIXELFORMAT_XBGR4444; -export const PIXELFORMAT_XRGB1555 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XRGB, PackedLayout._1555, 15, 2); -export const PIXELFORMAT_RGB555 = PIXELFORMAT_XRGB1555; -export const PIXELFORMAT_XBGR1555 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XBGR, PackedLayout._1555, 15, 2); -export const PIXELFORMAT_BGR555 = PIXELFORMAT_XBGR1555; -export const PIXELFORMAT_ARGB4444 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ARGB, PackedLayout._4444, 16, 2); -export const PIXELFORMAT_RGBA4444 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.RGBA, PackedLayout._4444, 16, 2); -export const PIXELFORMAT_ABGR4444 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ABGR, PackedLayout._4444, 16, 2); -export const PIXELFORMAT_BGRA4444 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.BGRA, PackedLayout._4444, 16, 2); -export const PIXELFORMAT_ARGB1555 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ARGB, PackedLayout._1555, 16, 2); -export const PIXELFORMAT_RGBA5551 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.RGBA, PackedLayout._5551, 16, 2); -export const PIXELFORMAT_ABGR1555 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ABGR, PackedLayout._1555, 16, 2); -export const PIXELFORMAT_BGRA5551 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.BGRA, PackedLayout._5551, 16, 2); -export const PIXELFORMAT_RGB565 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XRGB, PackedLayout._565, 16, 2); -export const PIXELFORMAT_BGR565 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XBGR, PackedLayout._565, 16, 2); -export const PIXELFORMAT_RGB24 = SDL_DEFINE_PIXELFORMAT(PixelType.ARRAYU8, ArrayOrder.RGB, 0, 24, 3); -export const PIXELFORMAT_BGR24 = SDL_DEFINE_PIXELFORMAT(PixelType.ARRAYU8, ArrayOrder.BGR, 0, 24, 3); -export const PIXELFORMAT_XRGB8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.XRGB, PackedLayout._8888, 24, 4); -export const PIXELFORMAT_RGB888 = PIXELFORMAT_XRGB8888; -export const PIXELFORMAT_RGBX8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.RGBX, PackedLayout._8888, 24, 4); -export const PIXELFORMAT_XBGR8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.XBGR, PackedLayout._8888, 24, 4); -export const PIXELFORMAT_BGR888 = PIXELFORMAT_XBGR8888; -export const PIXELFORMAT_BGRX8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.BGRX, PackedLayout._8888, 24, 4); -export const PIXELFORMAT_ARGB8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.ARGB, PackedLayout._8888, 32, 4); -export const PIXELFORMAT_RGBA8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.RGBA, PackedLayout._8888, 32, 4); -export const PIXELFORMAT_ABGR8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.ABGR, PackedLayout._8888, 32, 4); -export const PIXELFORMAT_BGRA8888 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.BGRA, PackedLayout._8888, 32, 4); -export const PIXELFORMAT_ARGB2101010 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.ARGB, PackedLayout._2101010, 32, 4); +export const PIXELFORMAT_UNKNOWN: u32 = 0; +export const PIXELFORMAT_INDEX1LSB: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX1, BitmapOrder._4321, 0, 1, 0); +export const PIXELFORMAT_INDEX1MSB: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX1, BitmapOrder._1234, 0, 1, 0); +export const PIXELFORMAT_INDEX4LSB: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX4, BitmapOrder._4321, 0, 4, 0); +export const PIXELFORMAT_INDEX4MSB: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX4, BitmapOrder._1234, 0, 4, 0); +export const PIXELFORMAT_INDEX8: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.INDEX8, 0, 0, 8, 1); +export const PIXELFORMAT_RGB332: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED8, PackedOrder.XRGB, PackedLayout._332, 8, 1); +export const PIXELFORMAT_XRGB4444: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XRGB, PackedLayout._4444, 12, 2); +export const PIXELFORMAT_RGB444: u32 = PIXELFORMAT_XRGB4444; +export const PIXELFORMAT_XBGR4444: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XBGR, PackedLayout._4444, 12, 2); +export const PIXELFORMAT_BGR444: u32 = PIXELFORMAT_XBGR4444; +export const PIXELFORMAT_XRGB1555: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XRGB, PackedLayout._1555, 15, 2); +export const PIXELFORMAT_RGB555: u32 = PIXELFORMAT_XRGB1555; +export const PIXELFORMAT_XBGR1555: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XBGR, PackedLayout._1555, 15, 2); +export const PIXELFORMAT_BGR555: u32 = PIXELFORMAT_XBGR1555; +export const PIXELFORMAT_ARGB4444: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ARGB, PackedLayout._4444, 16, 2); +export const PIXELFORMAT_RGBA4444: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.RGBA, PackedLayout._4444, 16, 2); +export const PIXELFORMAT_ABGR4444: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ABGR, PackedLayout._4444, 16, 2); +export const PIXELFORMAT_BGRA4444: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.BGRA, PackedLayout._4444, 16, 2); +export const PIXELFORMAT_ARGB1555: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ARGB, PackedLayout._1555, 16, 2); +export const PIXELFORMAT_RGBA5551: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.RGBA, PackedLayout._5551, 16, 2); +export const PIXELFORMAT_ABGR1555: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.ABGR, PackedLayout._1555, 16, 2); +export const PIXELFORMAT_BGRA5551: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.BGRA, PackedLayout._5551, 16, 2); +export const PIXELFORMAT_RGB565: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XRGB, PackedLayout._565, 16, 2); +export const PIXELFORMAT_BGR565: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED16, PackedOrder.XBGR, PackedLayout._565, 16, 2); +export const PIXELFORMAT_RGB24: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.ARRAYU8, ArrayOrder.RGB, 0, 24, 3); +export const PIXELFORMAT_BGR24: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.ARRAYU8, ArrayOrder.BGR, 0, 24, 3); +export const PIXELFORMAT_XRGB8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.XRGB, PackedLayout._8888, 24, 4); +export const PIXELFORMAT_RGB888: u32 = PIXELFORMAT_XRGB8888; +export const PIXELFORMAT_RGBX8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.RGBX, PackedLayout._8888, 24, 4); +export const PIXELFORMAT_XBGR8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.XBGR, PackedLayout._8888, 24, 4); +export const PIXELFORMAT_BGR888: u32 = PIXELFORMAT_XBGR8888; +export const PIXELFORMAT_BGRX8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.BGRX, PackedLayout._8888, 24, 4); +export const PIXELFORMAT_ARGB8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.ARGB, PackedLayout._8888, 32, 4); +export const PIXELFORMAT_RGBA8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.RGBA, PackedLayout._8888, 32, 4); +export const PIXELFORMAT_ABGR8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.ABGR, PackedLayout._8888, 32, 4); +export const PIXELFORMAT_BGRA8888: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.BGRA, PackedLayout._8888, 32, 4); +export const PIXELFORMAT_ARGB2101010: u32 = SDL_DEFINE_PIXELFORMAT(PixelType.PACKED32, PackedOrder.ARGB, PackedLayout._2101010, 32, 4); /* #if SDL_BYTEORDER == SDL_BIG_ENDIAN SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_RGBA8888, diff --git a/src/_constants.ts b/src/_constants.ts index ecd8ca2..d243004 100644 --- a/src/_constants.ts +++ b/src/_constants.ts @@ -1,2 +1 @@ -export const ENV_ENV_DIR = "SDL_TS_ENV_DIR"; export const ENV_LIBRARY_PATH = "SDL_TS_LIBRARY_PATH"; diff --git a/src/boxes.test.ts b/src/boxes.test.ts index 1eab79d..dae75e2 100644 --- a/src/boxes.test.ts +++ b/src/boxes.test.ts @@ -1,12 +1,10 @@ -import { asserts } from "../deps.ts"; +import { assertEquals } from "@std/assert"; import { Box, BoxValueFactory } from "./boxes.ts"; import { Pointer } from "./pointers.ts"; import { F32, F64, I16, I32, I8, Int, U16, U32, U8 } from "./types.ts"; import { PlatformDataView, PlatformPointer } from "./_types.ts"; -const { assertEquals } = asserts; - -(, keyof PlatformDataView, number]>> [ +(, keyof PlatformDataView, number]>>[ [I8, "setI8", -42], [U8, "setU8", 42], [I16, "setI16", -256], @@ -17,7 +15,10 @@ const { assertEquals } = asserts; ]).forEach((testData) => { Deno.test(`${testData[0].name} can be boxed`, () => { const box = new Box(testData[0]); - const setter = (box._view[testData[1]]) as (arg1: number, arg2: number) => void; + const setter = box._view[testData[1]] as ( + arg1: number, + arg2: number + ) => void; setter.apply(box._view, [0, testData[2]]); const result = box.value; @@ -26,13 +27,16 @@ const { assertEquals } = asserts; }); }); -(, keyof PlatformDataView, number]>> [ +(, keyof PlatformDataView, number]>>[ [F32, "setF32", 12.34], [F64, "setF64", 12.34], ]).forEach((testData) => { Deno.test(`${testData[0].name} can be boxed`, () => { const box = new Box(testData[0]); - const setter = (box._view[testData[1]]) as (arg1: number, arg2: number) => void; + const setter = box._view[testData[1]] as ( + arg1: number, + arg2: number + ) => void; setter.apply(box._view, [0, testData[2]]); const result = box.value; @@ -42,7 +46,9 @@ const { assertEquals } = asserts; }); Deno.test(`Pointer can be boxed`, () => { - const pointerValue = new Pointer(Deno.UnsafePointer.create(12345n) as unknown as PlatformPointer); + const pointerValue = new Pointer( + Deno.UnsafePointer.create(12345n) as unknown as PlatformPointer + ); const box = new Box>(Pointer); box._view.setPointer(0, pointerValue); diff --git a/src/boxes.ts b/src/boxes.ts index 5474d83..b7cf92d 100644 --- a/src/boxes.ts +++ b/src/boxes.ts @@ -30,13 +30,22 @@ export type BoxValueConstructor = Constructor; export type BoxValueFactory = Factory; -type BoxValueTransformer = (data: Uint8Array, view: PlatformDataView, offset: number) => T; +type BoxValueTransformer = ( + data: Uint8Array, + view: PlatformDataView, + offset: number +) => T; function sizeof( - factoryOrConstructor: BoxValueFactory | BoxValueConstructor, + factoryOrConstructor: BoxValueFactory | BoxValueConstructor ): number { - if ("SIZE_IN_BYTES" in (factoryOrConstructor as unknown as AllocatableStructConstructor)) { - return (factoryOrConstructor as unknown as AllocatableStructConstructor).SIZE_IN_BYTES; + if ( + "SIZE_IN_BYTES" in + (factoryOrConstructor as unknown as AllocatableStructConstructor) + ) { + return ( + factoryOrConstructor as unknown as AllocatableStructConstructor + ).SIZE_IN_BYTES; } switch (factoryOrConstructor) { @@ -65,48 +74,62 @@ function sizeof( return Platform.POINTER_SIZE_IN_BYTES; } - throwError(`${(factoryOrConstructor)?.name} is not boxable. sizeof not implemented.`); + throwError( + `${factoryOrConstructor?.name} is not boxable. sizeof not implemented.` + ); } export function getTransformer( - factoryOrConstructor: BoxValueFactory | BoxValueConstructor, + factoryOrConstructor: BoxValueFactory | BoxValueConstructor ): BoxValueTransformer { switch (factoryOrConstructor) { case I8: - return ((_, view, offset) => view.getI8(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getI8(offset)) as BoxValueTransformer; case U8: - return ((_, view, offset) => view.getU8(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getU8(offset)) as BoxValueTransformer; case I16: - return ((_, view, offset) => view.getI16(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getI16(offset)) as BoxValueTransformer; case U16: - return ((_, view, offset) => view.getU16(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getU16(offset)) as BoxValueTransformer; case I32: - return ((_, view, offset) => view.getI32(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getI32(offset)) as BoxValueTransformer; case U32: - return ((_, view, offset) => view.getU32(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getU32(offset)) as BoxValueTransformer; case F32: - return ((_, view, offset) => view.getF32(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getF32(offset)) as BoxValueTransformer; case I64: - return ((_, view, offset) => view.getI64(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getI64(offset)) as BoxValueTransformer; case U64: - return ((_, view, offset) => view.getU64(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getU64(offset)) as BoxValueTransformer; case F64: - return ((_, view, offset) => view.getF64(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getF64(offset)) as BoxValueTransformer; case Int: // TODO: Does this need to be platform dependent? - return ((_, view, offset) => view.getI32(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getI32(offset)) as BoxValueTransformer; case Pointer as unknown as BoxValueFactory: - return ((_, view, offset) => view.getPointer(offset)) as BoxValueTransformer; + return ((_, view, offset) => + view.getPointer(offset)) as BoxValueTransformer; } if ("of" in factoryOrConstructor) { @@ -114,7 +137,7 @@ export function getTransformer( } throw new Error( - `${(factoryOrConstructor)?.name} is not boxable. getTransformer not implemented.`, + `${factoryOrConstructor?.name} is not boxable. getTransformer not implemented.` ); } @@ -123,7 +146,9 @@ export class Box { public readonly _data: Uint8Array; public readonly _view: PlatformDataView; - public constructor(factoryOrConstructor: BoxValueFactory | BoxValueConstructor) { + public constructor( + factoryOrConstructor: BoxValueFactory | BoxValueConstructor + ) { const dataLength = sizeof(factoryOrConstructor); this._transformer = getTransformer(factoryOrConstructor); @@ -132,24 +157,19 @@ export class Box { } public static isBox(value: unknown): value is Box { - return (value instanceof Box); + return value instanceof Box; } public get value(): T { return this._transformer(this._data, this._view, 0); } - public unbox( - predicate: Predicate, - errorMessage: OrFactory, - ): T { + public unbox(predicate: Predicate, errorMessage: OrFactory): T { const value = this.value; return predicate(value) ? value : throwError(errorMessage); } - public unboxNotNull( - errorMessage: OrFactory, - ): T { + public unboxNotNull(errorMessage: OrFactory): T { return this.unbox((value) => value != 0, errorMessage); } } @@ -162,7 +182,7 @@ export class BoxArray { public constructor( factoryOrConstructor: BoxValueFactory | BoxValueConstructor, - length: number, + length: number ) { if (length <= 0) { throw new Error("length must be > 0."); @@ -180,22 +200,26 @@ export class BoxArray { } public at(index: number): T { - return this._transformer(this._data, this._view, this.sizeOfElementInBytes * index); + return this._transformer( + this._data, + this._view, + this.sizeOfElementInBytes * index + ); } public unboxAt( index: number, predicate: Predicate, - errorMessage: string, + errorMessage: string ): T { const value = this.at(index); return predicate(value) ? value : throwError(errorMessage); } - // TODO: This is terrible. Just replace this with a funciton named pointersAt(index: number) - public readonly pointers = { - at: (index: number) => { - return Pointer.ofTypedArray(this._data, this.sizeOfElementInBytes * index); - }, - }; + public pointersAt(index: number): Pointer { + return Pointer.ofTypedArray( + this._data, + this.sizeOfElementInBytes * index + ); + } } diff --git a/src/deno/_library.ts b/src/deno/_library.ts index 6651502..7724e79 100644 --- a/src/deno/_library.ts +++ b/src/deno/_library.ts @@ -1,20 +1,20 @@ -import { dotenv, path } from "../../deps.ts"; +import { join } from "@std/path"; import { SDLError } from "../error.ts"; import { DynamicLibrary, DynamicLibraryInterface } from "../_library.ts"; -import { ENV_ENV_DIR, ENV_LIBRARY_PATH } from "../_constants.ts"; +import { ENV_LIBRARY_PATH } from "../_constants.ts"; const IS_WINDOWS = Deno.build.os === "windows"; const IS_MAC = Deno.build.os === "darwin"; const WINDOWS_LIBRARY_PATHS: string[] = []; -const UNIX_LIBRARY_PATHS: string[] = [ +const UNIX_LIBRARY_PATHS: string[] = ["/usr/local/lib", "/usr/lib64"]; + +const MACOS_LIBRARY_PATHS: string[] = [ "/usr/local/lib", - "/usr/lib64", + "/System/Volumes/Data/opt/homebrew/lib", ]; -const MACOS_LIBRARY_PATHS: string[] = ["/usr/local/lib", "/System/Volumes/Data/opt/homebrew/lib"]; - function getLibrarySuffix(): string { switch (Deno.build.os) { case "windows": @@ -38,57 +38,22 @@ function getLibraryPaths(libraryName: string, libraryPath?: string): string[] { const arch = "x64"; // TODO: Detect this somehow. if (libraryPath) { - libraryPaths.push(path.join( - libraryPath, - os, - arch, - fullLibraryName, - )); + libraryPaths.push(join(libraryPath, os, arch, fullLibraryName)); } - libraryPaths.push(path.join(".", fullLibraryName)); + libraryPaths.push(join(".", fullLibraryName)); if (!IS_WINDOWS && !IS_MAC) { // On Debain libSDL2_image and libSDL2_ttf only have symbolic links with this format. - libraryPaths.push(libraryPrefix + libraryName + "-2.0" + librarySuffix + ".0"); - } - - try { - const envDir = Deno.env.get(ENV_ENV_DIR) ?? "."; - - const env = dotenv.loadSync({ - envPath: path.join(envDir, `.env.${Deno.build.os}`), - }); - - libraryPath = env[ENV_LIBRARY_PATH]; - - if (libraryPath) { - // If the path in the .env file starts with a . then replace it with - // the directory of the .env file. - if (libraryPath.startsWith(".")) { - libraryPath = path.join(envDir, libraryPath.substring(1)); - } - - libraryPaths.push(path.join( - libraryPath, - os, - arch, - fullLibraryName, - )); - } - } catch { - // If we can't load the .env than just ignore it. + libraryPaths.push( + libraryPrefix + libraryName + "-2.0" + librarySuffix + ".0" + ); } libraryPath = Deno.env.get(ENV_LIBRARY_PATH); if (libraryPath) { - libraryPaths.push(path.join( - libraryPath, - os, - arch, - fullLibraryName, - )); + libraryPaths.push(join(libraryPath, os, arch, fullLibraryName)); } if (!IS_WINDOWS) { @@ -98,7 +63,7 @@ function getLibraryPaths(libraryName: string, libraryPath?: string): string[] { libraryPaths.push( ...ldLibraryPath .split(":") - .map((libraryPath) => path.join(libraryPath, fullLibraryName)), + .map((libraryPath) => join(libraryPath, fullLibraryName)) ); } } @@ -120,7 +85,7 @@ function getLibraryPaths(libraryName: string, libraryPath?: string): string[] { } libraryPaths.push( - ...searchPaths.map((libraryPath) => path.join(libraryPath, fullLibraryName)), + ...searchPaths.map((libraryPath) => join(libraryPath, fullLibraryName)) ); return libraryPaths; @@ -129,7 +94,7 @@ function getLibraryPaths(libraryName: string, libraryPath?: string): string[] { export function denoLoadLibrary( libraryName: string, symbols: T, - libraryPath?: string, + libraryPath?: string ): DynamicLibrary { const libraryPaths = getLibraryPaths(libraryName, libraryPath); const errors: Record = {}; @@ -145,8 +110,12 @@ export function denoLoadLibrary( } throw new SDLError( - `Failed to load library "${libraryName}" from "${libraryPaths.join(", ")}"\n` + - Object.entries(errors).map(([libraryPath, error]) => `\t=> ${libraryPath}: ${error.message}`).join("\n"), - new AggregateError(Object.values(errors)), + `Failed to load library "${libraryName}" from "${libraryPaths.join( + ", " + )}"\n` + + Object.entries(errors) + .map(([libraryPath, error]) => `\t=> ${libraryPath}: ${error.message}`) + .join("\n"), + new AggregateError(Object.values(errors)) ); } diff --git a/tools/codegen/SDL.ts b/tools/codegen/SDL.ts index cce3f93..1ebda14 100644 --- a/tools/codegen/SDL.ts +++ b/tools/codegen/SDL.ts @@ -1,4 +1,4 @@ -import { path } from "../../deps.ts"; +import { join } from "@std/path"; import { SRC_PATH } from "../../shared/constants.ts"; import { writeCallbacks, @@ -15,7 +15,7 @@ import { events } from "./SDL/events.ts"; import { functions } from "./SDL/functions.ts"; import { opaqueStructs, structs } from "./SDL/structs.ts"; -const SDL_SRC_PATH = path.join(SRC_PATH, "SDL"); +const SDL_SRC_PATH = join(SRC_PATH, "SDL"); export async function codegenSDL(): Promise { await writeEnums(`${SDL_SRC_PATH}/enums.ts`, enums, []); diff --git a/tools/codegen/SDL_image.ts b/tools/codegen/SDL_image.ts index 3e8deec..f139044 100644 --- a/tools/codegen/SDL_image.ts +++ b/tools/codegen/SDL_image.ts @@ -1,13 +1,19 @@ -import { path } from "../../deps.ts"; +import { join } from "@std/path"; import { SRC_PATH } from "../../shared/constants.ts"; -import { writeCallbacks, writeEnums, writeFunctions, writeStructs, writeSymbols } from "./generators.ts"; +import { + writeCallbacks, + writeEnums, + writeFunctions, + writeStructs, + writeSymbols, +} from "./generators.ts"; import { callbacks } from "./SDL_image/callbacks.ts"; import { enums } from "./SDL_image/enums.ts"; import { functions } from "./SDL_image/functions.ts"; import { opaqueStructs, structs } from "./SDL_image/structs.ts"; import { structs as SDL_structs } from "./SDL/structs.ts"; -const SDL_IMAGE_SRC_PATH = path.join(SRC_PATH, "SDL_image"); +const SDL_IMAGE_SRC_PATH = join(SRC_PATH, "SDL_image"); export async function codegenSDL_image(): Promise { const allStructs = { @@ -32,7 +38,14 @@ export async function codegenSDL_image(): Promise { await writeEnums(`${SDL_IMAGE_SRC_PATH}/enums.ts`, enums, []); // await writeStructs(`${SDL_IMAGE_SRC_PATH}/structs.ts`, structs, opaqueStructs); - await writeSymbols(`${SDL_IMAGE_SRC_PATH}/_symbols.ts`, functions, callbacks, enums, allStructs, opaqueStructs); + await writeSymbols( + `${SDL_IMAGE_SRC_PATH}/_symbols.ts`, + functions, + callbacks, + enums, + allStructs, + opaqueStructs + ); // await writeCallbacks(`${SDL_IMAGE_SRC_PATH}/callbacks.ts`, callbacks, enums, structs, opaqueStructs, []); await writeFunctions( `${SDL_IMAGE_SRC_PATH}/functions.ts`, @@ -42,8 +55,6 @@ export async function codegenSDL_image(): Promise { enums, allStructs, opaqueStructs, - [ - `import { Renderer, Surface, Texture, version } from "../SDL/structs.ts";`, - ], + [`import { Renderer, Surface, Texture, version } from "../SDL/structs.ts";`] ); } diff --git a/tools/codegen/SDL_ttf.ts b/tools/codegen/SDL_ttf.ts index c473775..f43bab1 100644 --- a/tools/codegen/SDL_ttf.ts +++ b/tools/codegen/SDL_ttf.ts @@ -1,13 +1,19 @@ -import { path } from "../../deps.ts"; +import { join } from "@std/path"; import { SRC_PATH } from "../../shared/constants.ts"; -import { writeCallbacks, writeEnums, writeFunctions, writeStructs, writeSymbols } from "./generators.ts"; +import { + writeCallbacks, + writeEnums, + writeFunctions, + writeStructs, + writeSymbols, +} from "./generators.ts"; import { callbacks } from "./SDL_ttf/callbacks.ts"; import { enums } from "./SDL_ttf/enums.ts"; import { functions } from "./SDL_ttf/functions.ts"; import { opaqueStructs, structs } from "./SDL_ttf/structs.ts"; import { structs as SDL_structs } from "./SDL/structs.ts"; -const SDL_TTF_SRC_PATH = path.join(SRC_PATH, "SDL_ttf"); +const SDL_TTF_SRC_PATH = join(SRC_PATH, "SDL_ttf"); export async function codegenSDL_ttf(): Promise { const allStructs = { @@ -27,7 +33,13 @@ export async function codegenSDL_ttf(): Promise { }; // await writeEnums(`${SDL_TTF_SRC_PATH}/enums.ts`, enums, []); - await writeStructs(`${SDL_TTF_SRC_PATH}/structs.ts`, callbacks, enums, structs, opaqueStructs); + await writeStructs( + `${SDL_TTF_SRC_PATH}/structs.ts`, + callbacks, + enums, + structs, + opaqueStructs + ); // await writeSymbols(`${SDL_TTF_SRC_PATH}/_symbols.ts`, functions, enums, allStructs, opaqueStructs); // await writeCallbacks(`${SDL_TTF_SRC_PATH}/callbacks.ts`, callbacks, enums, structs, opaqueStructs, []); await writeFunctions( @@ -38,8 +50,6 @@ export async function codegenSDL_ttf(): Promise { enums, allStructs, opaqueStructs, - [ - `import { Color, Surface, version } from "../SDL/structs.ts";`, - ], + [`import { Color, Surface, version } from "../SDL/structs.ts";`] ); } diff --git a/tools/init.ts b/tools/init.ts deleted file mode 100644 index 90423d0..0000000 --- a/tools/init.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { REPO_URL } from "../shared/constants.ts"; -import { downloadFile } from "../shared/http.ts"; -import { fs, path } from "../deps.ts"; - -type ProjectFileData = { - readonly destination: readonly string[]; - readonly overwrite: boolean; -}; - -const PROJECT_FILES: Record = { - "/ext/SDL/windows/x64/SDL2.dll": { - destination: ["windows", "x64", "SDL2.dll"], - overwrite: true, - }, - - "/ext/SDL/README-SDL_image.txt": { - destination: ["README-SDL_image.txt"], - overwrite: true, - }, - - "/ext/SDL/README-SDL.txt": { - destination: ["README-SDL.txt"], - overwrite: true, - }, - - "/tools/init/deno.json": { - destination: ["deno.json"], - overwrite: false, - }, - - "/tools/init/imports.deno.json": { - destination: ["imports.deno.json"], - overwrite: false, - }, - - "/tools/init/main.ts": { - destination: ["main.ts"], - overwrite: false, - }, -} as const; - -export async function main(args: string[]): Promise { - const destination = args[0] ?? Deno.cwd(); - - for (const [fileURL, fileData] of Object.entries(PROJECT_FILES)) { - if (fileData.destination.length > 1) { - await fs.ensureDir( - path.join(destination, ...fileData.destination.slice(0, fileData.destination.length - 1)), - ); - } - - const fileDestination = path.join(destination, ...fileData.destination); - await downloadFile(REPO_URL + fileURL, fileDestination, fileData.overwrite); - } - - return 0; -} diff --git a/tools/init/deno.json b/tools/init/deno.json deleted file mode 100644 index 3dd2950..0000000 --- a/tools/init/deno.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "lib": ["deno.window", "deno.unstable"] - }, - "fmt": { - "useTabs": false, - "lineWidth": 120, - "indentWidth": 2 - }, - "lint": { - "rules": { - "tags": ["recommended"], - "include": ["explicit-function-return-type"] - } - }, - "importMap": "imports.deno.json", - "tasks": { - "start": "deno run --unstable-ffi --allow-env --allow-ffi ./main.ts" - } -} diff --git a/tools/init/imports.deno.json b/tools/init/imports.deno.json deleted file mode 100644 index ff06779..0000000 --- a/tools/init/imports.deno.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "imports": { - "SDL_ts": "https://deno.land/x/sdl_ts@0.0.4/mod.ts" - } -}