use std::sync::Arc;
use unityrs_core::env::{DerefError, PPtr};
use unityrs_core::files::{BundleFile, ParentKind, SerializedFile};
use unityrs_core::limits::{Limits, Meter, MeteredVec};
use unityrs_core::typetree::{NodeList, NodeRow, Tree};
use unityrs_core::{Bytes, Map, ObjectRef, Parsed, PrimArray, RawStr, Value};
use unityrs_texture::{Format, Formats, SWITCH, Selection, Skip, TextureFields, select_in};
use super::classify::{self, Class, Reason};
use super::seam::Seam;
use super::table;
const WIDE_PATH_ID: u32 = 14;
#[must_use]
pub fn shape() -> Class {
Class::Skip(Reason::decode_error("read"))
}
#[must_use]
pub fn parent_bundle(kind: Option<&ParentKind>) -> Option<Arc<BundleFile>> {
match kind? {
ParentKind::Bundle { bundle, .. } => bundle.upgrade(),
ParentKind::Web { .. } => None,
}
}
#[must_use]
pub fn top_bundle(file: &SerializedFile) -> Option<Arc<BundleFile>> {
let mut top = parent_bundle(file.parent().map(|p| &p.kind))?;
while let Some(up) = parent_bundle(top.parent().map(|p| &p.kind)) {
top = up;
}
Some(top)
}
#[must_use]
pub fn field<'a>(parsed: &'a Parsed, value: &'a Value, name: &[u8]) -> Option<&'a Value> {
parsed.field(value.as_dict()?, name)
}
#[must_use]
pub fn attr<'a>(parsed: &'a Parsed, value: &'a Value, name: &[u8]) -> Option<&'a Value> {
parsed.attr(value.as_dict()?, name)
}
#[must_use]
pub fn pptr(parsed: &Parsed, value: &Value) -> Option<PPtr> {
let file_id = field(parsed, value, b"m_FileID")?.as_i64()?;
let path_id = field(parsed, value, b"m_PathID")?.as_i64()?;
Some(PPtr {
file_id: i32::try_from(file_id).ok()?,
path_id,
})
}
fn string(value: &Value) -> Option<&RawStr> {
match value {
Value::Str(s) => Some(s),
_ => None,
}
}
#[derive(Clone, Debug)]
pub struct Head {
pub script: PPtr,
pub name: RawStr,
}
const ALIGN: i64 = 0x4000;
fn head_rows(wide: bool) -> Vec<NodeRow> {
let id_ty = if wide { "SInt64" } else { "int" };
let row = |level, ty: &str, name: &str| NodeRow::new(level, ty, name).with_meta_flag(0);
let aligned = |level, ty: &str, name: &str| NodeRow::new(level, ty, name).with_meta_flag(ALIGN);
vec![
row(0, "MonoBehaviour", "Base"),
row(1, "PPtr<GameObject>", "m_GameObject"),
row(2, "int", "m_FileID"),
row(2, id_ty, "m_PathID"),
aligned(1, "UInt8", "m_Enabled"),
row(1, "PPtr<MonoScript>", "m_Script"),
row(2, "int", "m_FileID"),
row(2, id_ty, "m_PathID"),
row(1, "string", "m_Name"),
aligned(2, "Array", "Array"),
row(3, "int", "size"),
row(3, "char", "data"),
]
}
type Peek = (Arc<Tree>, Option<Arc<Tree>>);
#[derive(Debug)]
pub struct Reader {
wide: Arc<Tree>,
narrow: Arc<Tree>,
peeks: table::Map<usize, Peek>,
}
impl Reader {
pub fn new(meter: &Arc<Meter>) -> Result<Self, Class> {
fn internal<E>(_: E) -> Class {
Class::Run(Reason::plain("internal"))
}
let tree = |wide| {
let list = NodeList::trusted(head_rows(wide)).map_err(internal)?;
Tree::compile(list.into_shared().map_err(internal)?, &Limits::default())
.map_err(internal)
};
Ok(Self {
wide: tree(true)?,
narrow: tree(false)?,
peeks: table::Map::new(meter),
})
}
pub fn head(&self, obj: &ObjectRef) -> Result<Head, Class> {
let tree = if obj.file().header().version >= WIDE_PATH_ID {
&self.wide
} else {
&self.narrow
};
let parsed = obj
.read_typetree(Some(tree), false)
.map_err(|e| classify::parse(&e))?;
let root = parsed.value();
let script = field(&parsed, root, b"m_Script")
.and_then(|v| pptr(&parsed, v))
.ok_or_else(shape)?;
let name = field(&parsed, root, b"m_Name")
.and_then(string)
.ok_or_else(shape)?
.clone();
Ok(Head { script, name })
}
pub(super) fn peek_name(&mut self, seam: &Seam<'_>, obj: &ObjectRef) -> Result<RawStr, Class> {
self.peek(seam, obj)?.ok_or_else(shape)
}
#[inline(never)]
pub(super) fn atlas_name(
&mut self,
seam: &Seam<'_>,
obj: &ObjectRef,
) -> Result<Option<RawStr>, Class> {
self.peek(seam, obj)
}
pub(super) fn peek(
&mut self,
seam: &Seam<'_>,
obj: &ObjectRef,
) -> Result<Option<RawStr>, Class> {
let _sample = Sample(obj.file().meter(), seam.hooks);
let found = seam.probe(|| obj.tree(None).map_err(|e| classify::parse(&e)))?;
let Some(tree) = found else {
return Err(Class::Skip(Reason::decode_error("asset_bundle")));
};
let own = top_bundle(obj.file()).is_some_and(|b| Arc::ptr_eq(&b, &seam.registered.own));
let peek = if own {
self.kept(seam, &tree.tree, obj.file())?
} else {
peek_tree(seam, &tree.tree, obj.file())?
};
drop(tree);
let Some(peek) = peek else {
return Ok(None);
};
let parsed = seam.probe(|| {
obj.read_typetree(Some(&peek), false)
.map_err(|e| classify::parse(&e))
})?;
let list = peek.list();
let key = list
.children(list.root())
.last()
.map(|c| list.name(*c))
.ok_or_else(shape)?;
Ok(field(&parsed, parsed.value(), key)
.and_then(string)
.cloned())
}
fn kept(
&mut self,
seam: &Seam<'_>,
tree: &Arc<Tree>,
file: &SerializedFile,
) -> Result<Option<Arc<Tree>>, Class> {
let at = Arc::as_ptr(tree) as usize;
if let Some((_, peek)) = self.peeks.get(&at) {
return Ok(peek.clone());
}
let peek = peek_tree(seam, tree, file)?;
let peeks = &mut self.peeks;
seam.probe(|| peeks.insert(at, (tree.clone(), peek.clone())))?;
Ok(peek)
}
}
fn peek_tree(
seam: &Seam<'_>,
tree: &Arc<Tree>,
file: &SerializedFile,
) -> Result<Option<Arc<Tree>>, Class> {
let list = tree.list();
let root = list.root();
let children = list.children(root);
let Some(pos) = children
.iter()
.position(|c| matches!(list.name(*c), b"m_Name" | b"name"))
else {
return Ok(None);
};
let end = children
.get(pos + 1)
.map_or(list.rows().len(), |next| next.index());
let rows = list.rows().get(..end).unwrap_or_default();
let mut kept = seam.probe(|| {
MeteredVec::with_capacity(file.meter(), rows.len()).map_err(|e| classify::charge(&e))
})?;
seam.probe(|| {
kept.extend_from_slice(rows)
.map_err(|e| classify::charge(&e))
})?;
let peek = seam.probe(|| NodeList::from_rows(kept).map_err(|e| classify::tree(&e)))?;
let limits = &file.context().limits;
let compiled = seam.probe(|| {
Tree::compile(peek.into_shared().map_err(|e| classify::tree(&e))?, limits)
.map_err(|e| classify::tree(&e))
})?;
Ok(Some(compiled))
}
pub use unityrs_texture::fetch::{Span, Stream, python_slice};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Blob {
pub len: usize,
pub gobs: Option<[u8; 4]>,
}
pub const BLOB_ELEMENT: &str = "read";
fn prim_byte(p: &PrimArray, i: usize) -> Option<u8> {
let int = |v: Option<i128>| v.and_then(|v| u8::try_from(v).ok());
match p {
PrimArray::Bool(v) => v.get(i).map(|b| u8::from(*b)),
PrimArray::U8(v) => v.get(i).copied(),
PrimArray::I8(v) => int(v.get(i).map(|x| i128::from(*x))),
PrimArray::U16(v) => int(v.get(i).map(|x| i128::from(*x))),
PrimArray::I16(v) => int(v.get(i).map(|x| i128::from(*x))),
PrimArray::U32(v) => int(v.get(i).map(|x| i128::from(*x))),
PrimArray::I32(v) => int(v.get(i).map(|x| i128::from(*x))),
PrimArray::U64(v) => int(v.get(i).map(|x| i128::from(*x))),
PrimArray::I64(v) => int(v.get(i).map(|x| i128::from(*x))),
PrimArray::F32(_) | PrimArray::F64(_) => None,
}
}
impl Blob {
fn of(value: &Value) -> Option<Self> {
let byte = |v: &Value| match v {
Value::Bool(b) => Some(u8::from(*b)),
other => u8::try_from(other.as_i64()?).ok(),
};
let (len, gobs) = match value {
Value::Prims(p) => {
let gobs = (8..12)
.map(|i| prim_byte(p, i))
.collect::<Option<Vec<u8>>>();
(p.len(), gobs)
}
Value::List(items) => {
let gobs = items
.get(8..12)
.map(|four| four.iter().map(byte).collect::<Option<Vec<u8>>>())
.unwrap_or_default();
(items.len(), gobs)
}
_ => return None,
};
let gobs = gobs.and_then(|g| <[u8; 4]>::try_from(g).ok());
Some(Self { len, gobs })
}
}
#[derive(Clone, Debug)]
pub struct Texture {
pub width: i128,
pub height: i128,
pub format: i128,
pub image_data: Bytes,
pub stream: Option<Stream>,
pub platform_blob: Option<Blob>,
}
impl Texture {
pub(crate) fn fields<'a>(
&self,
format: i32,
platform: i32,
blob: &'a mut [u8; 12],
) -> TextureFields<'a> {
let platform_blob = self
.platform_blob
.filter(|b| b.len >= 12)
.and_then(|b| b.gobs)
.map(|g| {
blob.fill(0);
blob[8..].copy_from_slice(&g);
blob.as_slice()
});
let (width, height) = self.sides();
TextureFields {
texture_format: format,
width,
height,
platform,
platform_blob,
}
}
#[must_use]
pub fn sides(&self) -> (i32, i32) {
let narrow = |v: i128| {
i32::try_from(v.clamp(i128::from(i32::MIN), i128::from(i32::MAX))).unwrap_or(i32::MAX)
};
(narrow(self.width), narrow(self.height))
}
}
pub fn answer(
t: &Texture,
platform: i32,
allowed: Formats,
unity_version: (u16, u16),
) -> Result<Format, Class> {
if t.width == 0 || t.height == 0 {
return Err(Class::Skip(Reason::plain(Skip::EmptyImage.to_string())));
}
formats(t, platform, allowed, unity_version)
}
pub(crate) fn object_answer(
t: &Texture,
obj: Option<&ObjectRef>,
allowed: Formats,
) -> Result<Format, Class> {
let platform = obj
.and_then(|o| o.file().target_platform())
.unwrap_or(super::attempt::UNKNOWN_PLATFORM);
answer(t, platform, allowed, (u16::MAX, u16::MAX))
}
mod crunch;
pub(super) use crunch::data_format;
pub(crate) fn formats(
t: &Texture,
platform: i32,
allowed: Formats,
unity_version: (u16, u16),
) -> Result<Format, Class> {
let Ok(format) = i32::try_from(t.format) else {
return Err(Class::Skip(Reason::plain(format!(
"unsupported_format({})",
t.format
))));
};
let mut blob = [0u8; 12];
match select_in(
&t.fields(format, platform, &mut blob),
allowed,
unity_version,
) {
Selection::Export(_)
if platform == SWITCH
&& t.platform_blob
.is_some_and(|b| b.len >= 12 && b.gobs.is_none()) =>
{
Err(Class::Skip(Reason::decode_error(BLOB_ELEMENT)))
}
Selection::Export(f) => Ok(f),
Selection::Skip(s) => Err(Class::Skip(Reason::plain(s.to_string()))),
}
}
const TEXTURE_FIELDS: [&[u8]; 11] = [
b"image_data",
b"m_CompleteImageSize",
b"m_Height",
b"m_ImageCount",
b"m_IsReadable",
b"m_LightmapFormat",
b"m_Name",
b"m_TextureDimension",
b"m_TextureFormat",
b"m_TextureSettings",
b"m_Width",
];
#[must_use]
pub fn integer(value: &Value) -> Option<i128> {
match value {
Value::Int(i) => Some(i128::from(*i)),
Value::UInt(u) => Some(i128::from(*u)),
_ => None,
}
}
pub(crate) const SETTERLESS: [&[u8]; 5] = [
b"image",
b"assets_file",
b"__class__",
b"__dict__",
b"__weakref__",
];
#[must_use]
pub(crate) fn setterless(parsed: &Parsed, map: &Map) -> bool {
SETTERLESS.iter().any(|n| parsed.attr(map, n).is_some())
}
#[must_use]
pub(crate) fn shadowed(parsed: &Parsed, map: &Map) -> bool {
parsed.attr(map, b"set_object_reader").is_some()
}
pub fn texture(obj: &ObjectRef) -> Result<Texture, Class> {
let parsed = obj
.read_typetree(None, true)
.map_err(|e| classify::parse(&e))?;
let root = parsed.value();
let map: &Map = root.as_dict().ok_or_else(shape)?;
if TEXTURE_FIELDS.iter().any(|f| parsed.attr(map, f).is_none())
|| setterless(&parsed, map)
|| shadowed(&parsed, map)
{
return Err(shape());
}
let get = |name: &[u8]| parsed.attr(map, name);
let width = get(b"m_Width").and_then(integer).ok_or_else(shape)?;
let height = get(b"m_Height").and_then(integer).ok_or_else(shape)?;
let format = get(b"m_TextureFormat")
.and_then(integer)
.ok_or_else(shape)?;
let stream = match get(b"m_StreamData") {
None => None,
Some(s) => {
let path = attr(&parsed, s, b"path")
.and_then(string)
.ok_or_else(shape)?;
let int = |name: &[u8]| attr(&parsed, s, name).and_then(integer);
Some(Stream {
path: path.clone(),
offset: int(b"offset").ok_or_else(shape)?,
size: int(b"size").ok_or_else(shape)?,
})
}
};
let image_data = match get(b"image_data") {
Some(Value::Bytes(b)) => b.clone(),
_ => return Err(shape()),
};
let platform_blob = match get(b"m_PlatformBlob") {
None => None,
Some(v) => Some(Blob::of(v).ok_or_else(shape)?),
};
Ok(Texture {
width,
height,
format,
image_data,
stream,
platform_blob,
})
}
pub(super) fn deref(
seam: &Seam<'_>,
from: &Arc<SerializedFile>,
pptr: PPtr,
) -> Result<ObjectRef, Class> {
seam.env_call(|| {
seam.env()
.deref(from, pptr)
.map_err(|e: DerefError| classify::deref(&e))
})
}
pub(super) fn material_name(
seam: &Seam<'_>,
reader: &mut Reader,
atlas: &ObjectRef,
parsed: &Parsed,
) -> Result<Option<RawStr>, Class> {
let Some(material) = field(parsed, parsed.value(), b"material") else {
return Ok(None);
};
let at = pptr(parsed, material).ok_or_else(shape)?;
let target = deref(seam, atlas.file(), at)?;
let _top = top_bundle(target.file());
let _sample = Sample(target.file().meter(), seam.hooks);
let mat = seam.probe(|| {
target
.read_typetree(None, true)
.map_err(|e| classify::parse(&e))
})?;
let envs = field(&mat, mat.value(), b"m_SavedProperties")
.and_then(|p| field(&mat, p, b"m_TexEnvs"))
.ok_or_else(shape)?;
let Value::List(pairs) = envs else {
return match envs {
Value::Prims(p) if p.is_empty() => Ok(None),
_ => Err(shape()),
};
};
for pair in pairs {
let two: &[Value] = match pair {
Value::Tuple(t) => t,
Value::List(l) => l,
_ => return Err(shape()),
};
let [first, second] = two else {
return Err(shape());
};
let key = match first {
Value::Str(s) => Some(s),
Value::Dict(_) => field(&mat, first, b"name").and_then(string),
_ => None,
};
if key.map(RawStr::as_bytes) != Some(b"_MainTex".as_slice()) {
continue;
}
let tex = field(&mat, second, b"m_Texture")
.and_then(|t| pptr(&mat, t))
.ok_or_else(shape)?;
let texture = deref(seam, target.file(), tex)?;
let _held = top_bundle(texture.file());
return reader.peek_name(seam, &texture).map(Some);
}
Ok(None)
}
pub(super) struct Sample<'a>(pub &'a Meter, pub &'a dyn super::Hooks);
impl Drop for Sample<'_> {
fn drop(&mut self) {
self.1.meter(self.0);
}
}
#[cfg(test)]
mod tests;