vtf-js
Version:
A javascript IO library for the Valve Texture Format.
90 lines (89 loc) • 2.96 kB
JavaScript
import { VCompressionMethods, VFormats } from './core/enums.js';
import { getThumbMip } from './core/utils.js';
/**
* A decoded Vtf.
* ```ts
* const vtf = await Vtf.decode(myBuffer);
* const image = vtf.data.getImage(0, 0, 0, 0);
* ```
*/
export class Vtf {
data;
version;
format;
flags;
meta;
reflectivity;
first_frame;
bump_scale;
compression_level;
compression_method;
constructor(data, options) {
this.data = data;
this.version = options?.version ?? 4;
this.format = options?.format ?? VFormats.RGBA8888;
this.flags = options?.flags ?? 0x0;
this.meta = options?.meta ?? [];
if (options?.reflectivity) {
this.reflectivity = options.reflectivity;
}
else {
const smallest_mip_index = getThumbMip(...this.data.getSize(0, 0, 0, 0), 1);
if (smallest_mip_index < this.data.mipmapCount()) {
const smallest_mip = this.data.getImage(smallest_mip_index, 0, 0, 0).convert(Float32Array);
this.reflectivity = smallest_mip.data.slice(0, 3);
}
else {
this.reflectivity = new Float32Array(3).fill(0);
}
}
this.first_frame = options?.first_frame ?? 0;
this.bump_scale = options?.bump_scale ?? 1.0;
this.compression_level = options?.compression_level ?? 0;
this.compression_method = options?.compression_method ?? VCompressionMethods.Deflate;
}
/** Encodes this Vtf object into an ArrayBuffer. */
encode() {
throw Error('Vtf.encode: Implementation override not present!');
}
static decode(data, header_only = false, lazy_decode = true) {
throw Error('Vtf.decode: Implementation override not present!');
}
}
/** A decoded Vtf header. Returned by `Vtf.decode(...)` when `header_only` is `true`. */
export class VFileHeader {
version;
width;
height;
flags;
frames;
first_frame;
reflectivity;
bump_scale;
format;
mipmaps;
thumb_format;
thumb_width;
thumb_height;
slices;
compression_method;
compression_level;
compressed_lengths;
/** Creates a new VFileHeader from the provided Vtf object. Used internally when encoding. */
static fromVtf(vtf) {
const header = new VFileHeader();
header.version = vtf.version;
[header.width, header.height] = vtf.data.getSize();
header.flags = vtf.flags;
header.frames = vtf.data.frameCount();
header.first_frame = vtf.first_frame;
header.reflectivity = vtf.reflectivity;
header.bump_scale = vtf.bump_scale;
header.format = vtf.format;
header.mipmaps = vtf.data.mipmapCount();
header.slices = vtf.data.sliceCount();
header.compression_method = vtf.compression_method;
header.compression_level = vtf.compression_level;
return header;
}
}