Added image loading routines and a triangular lattice sampler

This commit is contained in:
2025-07-21 23:41:53 +02:00
parent d52d77cf11
commit 4eb0f06e3f
4 changed files with 175 additions and 2 deletions

View File

@@ -16,6 +16,77 @@ export function load_image_from_src(src) {
});
}
export class Bitfield_Image_Sampler {
constructor(width, height, data) {
Object.assign(this, { width, height, data });
}
static from_string(encoded) {
const [width_str, height_str, b64] = encoded.split(',');
const width = parseInt(width_str, 10);
const height = parseInt(height_str, 10);
const decoded = atob(b64);
const data = new Uint8Array(decoded.length);
for (let i = 0; i < decoded.length; i++) {
data[i] = decoded.charCodeAt(i);
}
return new this(width, height, data);
}
*iter_row(row) {
const { width, data } = this;
const row_offset = row * Math.ceil(width / 8);
let byte_index = row_offset;
let bit_mask = 1;
let byte = data[byte_index++] ?? 0;
for (let x = 0; x < width; x++) {
yield (byte & bit_mask) !== 0;
bit_mask <<= 1;
if (bit_mask === 256) {
bit_mask = 1;
byte = data[byte_index++] ?? 0;
}
}
}
*[Symbol.iterator]() {
for (let y = 0; y < this.height; y++) {
yield new Image_Row_Reference(this, y);
}
}
sample(rawx, rawy) {
const { width, height, data } = this;
const x = Math.floor(rawx);
const y = Math.floor(rawy);
if (x < 0 || y < 0 || x >= width || y >= height ) {
return undefined;
}
const row_offset = y * Math.ceil(width / 8);
let byte_index = row_offset + Math.floor(x / 8);
return data[byte_index] & (1 << x % 8)
}
pixel_map(cb) {
let y = 0;
for (const row of this) {
let x = 0;
for (const pixel of row) {
cb(x, y, pixel);
x++;
}
y++;
}
}
}
export class Image_Row_Reference {
constructor(sampler, row) {
Object.assign(this, { sampler, row });