116 lines
2.3 KiB
TypeScript
116 lines
2.3 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
import { create_texture, device, push_quad, push_quad_vertices, use_texture } from "./core.ts";
|
|
import { Texture } from "./types.ts";
|
|
import type { Pixels } from "../png.ts";
|
|
|
|
export function load_texture(image: Pixels): Texture {
|
|
const texture = create_texture(image.width, image.height);
|
|
device.queue.writeTexture({ texture }, image.data, { bytesPerRow: image.width * 4 }, [image.width, image.height]);
|
|
|
|
return {
|
|
tex: texture,
|
|
width: image.width,
|
|
height: image.height,
|
|
};
|
|
}
|
|
|
|
export function draw_texture(
|
|
texture: Texture,
|
|
x: number,
|
|
y: number,
|
|
w: number,
|
|
h: number,
|
|
flip_x = false,
|
|
flip_y = false,
|
|
) {
|
|
draw_texture_region(texture, 0, 0, texture.width, texture.height, x, y, w, h, flip_x, flip_y);
|
|
}
|
|
|
|
export function draw_texture_region(
|
|
texture: Texture,
|
|
sx: number,
|
|
sy: number,
|
|
sw: number,
|
|
sh: number,
|
|
dx: number,
|
|
dy: number,
|
|
dw: number,
|
|
dh: number,
|
|
flip_x = false,
|
|
flip_y = false,
|
|
r = 1,
|
|
g = 1,
|
|
b = 1,
|
|
a = 1,
|
|
) {
|
|
use_texture(texture.tex);
|
|
const [u0, v0, u1, v1] = region_uvs(texture, sx, sy, sw, sh, flip_x, flip_y);
|
|
push_quad(dx, dy, dw, dh, u0, v0, u1, v1, r, g, b, a);
|
|
}
|
|
|
|
export function draw_texture_region_skewed(
|
|
texture: Texture,
|
|
sx: number,
|
|
sy: number,
|
|
sw: number,
|
|
sh: number,
|
|
points: [
|
|
{ x: number; y: number }, // top-left
|
|
{ x: number; y: number }, // top-right
|
|
{ x: number; y: number }, // bottom-right
|
|
{ x: number; y: number }, // bottom-left
|
|
],
|
|
r = 1,
|
|
g = 1,
|
|
b = 1,
|
|
a = 1,
|
|
flip_x = false,
|
|
flip_y = false,
|
|
) {
|
|
use_texture(texture.tex);
|
|
const [u0, v0, u1, v1] = region_uvs(texture, sx, sy, sw, sh, flip_x, flip_y);
|
|
|
|
const p0 = points[0];
|
|
const p1 = points[1];
|
|
const p2 = points[2];
|
|
const p3 = points[3];
|
|
|
|
push_quad_vertices(
|
|
p0.x,
|
|
p0.y,
|
|
p1.x,
|
|
p1.y,
|
|
p2.x,
|
|
p2.y,
|
|
p3.x,
|
|
p3.y,
|
|
u0,
|
|
v0,
|
|
u1,
|
|
v1,
|
|
r,
|
|
g,
|
|
b,
|
|
a,
|
|
);
|
|
}
|
|
|
|
// the uvs of a region of texture given in pixels, swapped to flip it
|
|
function region_uvs(
|
|
texture: Texture,
|
|
sx: number,
|
|
sy: number,
|
|
sw: number,
|
|
sh: number,
|
|
flip_x: boolean,
|
|
flip_y: boolean,
|
|
) {
|
|
const u = [sx / texture.width, (sx + sw) / texture.width];
|
|
const v = [sy / texture.height, (sy + sh) / texture.height];
|
|
if (flip_x) u.reverse();
|
|
if (flip_y) v.reverse();
|
|
return [u[0], v[0], u[1], v[1]];
|
|
}
|