Skip to content

Commit

Permalink
feat: use texture2ddecoder
Browse files Browse the repository at this point in the history
  • Loading branch information
Tsuk1ko committed Aug 7, 2023
1 parent fdc33e7 commit 951cc8c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 23 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "unity-js-tools"
version = "1.0.0"
version = "1.0.1"
edition = "2021"
authors = ["神代綺凛 <[email protected]>"]
license = "MIT"
Expand All @@ -16,6 +16,6 @@ codegen-units = 1
crate-type = ["cdylib"]

[dependencies]
astc-decode = "0.3.1"
lz4_flex = "0.11.1"
texture2ddecoder = "0.0.5"
wasm-bindgen = "0.2.87"
51 changes: 30 additions & 21 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,48 @@
use std::error::Error;

use astc_decode::{astc_decode, Footprint};
use lz4_flex::decompress;
use texture2ddecoder::decode_astc;
use wasm_bindgen::prelude::*;

fn to_js_err(e: impl Error) -> JsError {
fn to_js_err(e: impl ToString) -> JsError {
JsError::new(&e.to_string())
}

fn image_to_rgba(image: Vec<u32>, width: usize, height: usize) -> Vec<u8> {
let mut lines: Vec<&[u32]> = Vec::with_capacity(height);
for i in 0..height {
let start = i * width;
lines.push(&image[start..start + width]);
}
lines
.iter()
.copied()
.rev()
.flatten()
.flat_map(|x| {
let v = x.to_le_bytes();
[v[2], v[1], v[0], v[3]]
})
.collect::<Vec<u8>>()
}

#[wasm_bindgen(js_name = decodeAstc)]
pub fn decode_astc(
pub fn export_decode_astc(
data: &[u8],
width: u32,
height: u32,
block_width: u32,
block_height: u32,
width: usize,
height: usize,
block_width: usize,
block_height: usize,
) -> Result<Vec<u8>, JsError> {
let footprint = Footprint::new(block_width, block_height);
let mut result: Vec<u8> = vec![0; (width * height * 4) as usize];
let mut image: Vec<u32> = vec![0; (width * height) as usize];

let astc_result = astc_decode(data, width, height, footprint, |x, y, v4| {
let y = height - y - 1;
let ri = ((y * width + x) * 4) as usize;
for (i, v) in v4.iter().enumerate() {
result[ri + i] = *v;
}
});
let result = decode_astc(data, width, height, block_width, block_height, &mut image);

match astc_result {
Ok(()) => Ok(result),
match result {
Ok(()) => Ok(image_to_rgba(image, width, height)),
Err(e) => Err(to_js_err(e)),
}
}

#[wasm_bindgen(js_name = decompressLz4)]
pub fn decompress_lz4(data: &[u8], size: usize) -> Result<Vec<u8>, JsError> {
pub fn export_decompress_lz4(data: &[u8], size: usize) -> Result<Vec<u8>, JsError> {
decompress(data, size).map_err(to_js_err)
}

0 comments on commit 951cc8c

Please sign in to comment.