| 1 | //! Safe reader/index for completed production export runs. |
| 2 | //! |
| 3 | //! A run directory is accepted only when both `render.json` (schema 3) and |
| 4 | //! `complete.json` are present, their identity contracts match, every listed |
| 5 | //! PNG checksum verifies, and each map decodes under the published pixel |
| 6 | //! contract. Filenames alone never prove compatibility. |
| 7 | use crate::{ |
| 8 | digest::{self, is_sha256_hex}, |
| 9 | production::{MAX_HIGHRES, PASSES, SCALE}, |
| 10 | project::{self, CameraFraming}, |
| 11 | }; |
| 12 | use serde::Deserialize; |
| 13 | use std::{ |
| 14 | collections::BTreeMap, |
| 15 | fs, |
| 16 | io::Read, |
| 17 | path::{Path, PathBuf}, |
| 18 | }; |
| 19 | |
| 20 | /// Output metadata schema written by production and required by this reader. |
| 21 | /// 5: per-sex narrow depth range (depth_near/depth_far/depth_encoding, t964u); |
| 22 | /// schema-4 runs used the global 0.05–40 m range and are not mixed in. |
| 23 | /// 6: depth_bits + depth_encoding token (gray/rgb_bands/rgb_packed, t987u); |
| 24 | /// schema-5 runs are still read (16-bit gray). |
| 25 | pub const OUTPUT_META_VERSION: u32 = 6; |
| 26 | /// Oldest output schema still read. |
| 27 | pub const MIN_OUTPUT_META_VERSION: u32 = 5; |
| 28 | pub const MAX_TARGET: u32 = MAX_HIGHRES / SCALE; |
| 29 | /// Hard ceiling for a single published PNG on disk (encoded). |
| 30 | pub const MAX_PNG_BYTES: u64 = 8 * 1024 * 1024; |
| 31 | /// Same batch file ceiling as production planning. |
| 32 | pub const MAX_PNG_FILES: u32 = 500_000; |
| 33 | const MAX_MANIFEST_BYTES: u64 = 32 * 1024 * 1024; |
| 34 | const MAX_CLIP_NAME: usize = 256; |
| 35 | const MAX_CLIPS: usize = 4096; |
| 36 | |
| 37 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 38 | pub enum ExportError { |
| 39 | Incomplete(String), |
| 40 | Identity(String), |
| 41 | Io(String), |
| 42 | Corrupt(String), |
| 43 | Resource(String), |
| 44 | Traversal(String), |
| 45 | } |
| 46 | |
| 47 | impl std::fmt::Display for ExportError { |
| 48 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 49 | match self { |
| 50 | Self::Incomplete(m) |
| 51 | | Self::Identity(m) |
| 52 | | Self::Io(m) |
| 53 | | Self::Corrupt(m) |
| 54 | | Self::Resource(m) |
| 55 | | Self::Traversal(m) => write!(f, "{m}"), |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl std::error::Error for ExportError {} |
| 61 | |
| 62 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 63 | pub enum MapKind { |
| 64 | Diffuse, |
| 65 | Normal, |
| 66 | Specular, |
| 67 | Depth, |
| 68 | } |
| 69 | |
| 70 | impl MapKind { |
| 71 | pub fn token(self) -> &'static str { |
| 72 | match self { |
| 73 | Self::Diffuse => "diffuse", |
| 74 | Self::Normal => "normal", |
| 75 | Self::Specular => "specular", |
| 76 | Self::Depth => "depth", |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | pub fn parse(token: &str) -> Option<Self> { |
| 81 | match token { |
| 82 | "diffuse" => Some(Self::Diffuse), |
| 83 | "normal" => Some(Self::Normal), |
| 84 | "specular" => Some(Self::Specular), |
| 85 | "depth" => Some(Self::Depth), |
| 86 | _ => None, |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 92 | pub enum MapImage { |
| 93 | Rgba8 { |
| 94 | width: u32, |
| 95 | height: u32, |
| 96 | rgba: Vec<u8>, |
| 97 | }, |
| 98 | Depth16 { |
| 99 | width: u32, |
| 100 | height: u32, |
| 101 | /// Interleaved gray, alpha samples (length = width*height*2). |
| 102 | samples: Vec<u16>, |
| 103 | }, |
| 104 | } |
| 105 | |
| 106 | impl MapImage { |
| 107 | pub fn width(&self) -> u32 { |
| 108 | match self { |
| 109 | Self::Rgba8 { width, .. } | Self::Depth16 { width, .. } => *width, |
| 110 | } |
| 111 | } |
| 112 | pub fn height(&self) -> u32 { |
| 113 | match self { |
| 114 | Self::Rgba8 { height, .. } | Self::Depth16 { height, .. } => *height, |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | #[derive(Debug, Clone, Deserialize)] |
| 120 | pub struct SourceRef { |
| 121 | pub path: String, |
| 122 | pub sha256: String, |
| 123 | } |
| 124 | |
| 125 | #[derive(Debug, Clone, Deserialize)] |
| 126 | pub struct PresetRef { |
| 127 | pub name: String, |
| 128 | pub sha256: String, |
| 129 | } |
| 130 | |
| 131 | #[derive(Debug, Clone, Deserialize)] |
| 132 | pub struct ClipRecord { |
| 133 | pub name: String, |
| 134 | pub token: String, |
| 135 | pub frames: u32, |
| 136 | pub duration: f32, |
| 137 | } |
| 138 | |
| 139 | #[derive(Debug, Clone, Deserialize)] |
| 140 | pub struct PivotSourceJson { |
| 141 | pub kind: String, |
| 142 | #[serde(default)] |
| 143 | pub joint_index: Option<usize>, |
| 144 | #[serde(default)] |
| 145 | pub joint_name: Option<String>, |
| 146 | #[serde(default)] |
| 147 | pub reason: Option<String>, |
| 148 | } |
| 149 | |
| 150 | #[derive(Debug, Clone, Deserialize)] |
| 151 | pub struct RenderManifest { |
| 152 | pub format_version: u32, |
| 153 | pub status: String, |
| 154 | pub project: ProjectRef, |
| 155 | pub sex: String, |
| 156 | pub set: String, |
| 157 | pub body_model: SourceRef, |
| 158 | #[serde(default)] |
| 159 | pub equipment_preset: Option<PresetRef>, |
| 160 | pub target: [u32; 2], |
| 161 | pub fps: u32, |
| 162 | pub highres_scale: u32, |
| 163 | pub framing: CameraFraming, |
| 164 | pub pivot_source: PivotSourceJson, |
| 165 | pub near: f32, |
| 166 | pub far: f32, |
| 167 | pub depth_near: f32, |
| 168 | pub depth_far: f32, |
| 169 | pub depth_encoding: String, |
| 170 | #[serde(default)] |
| 171 | pub depth_bits: Option<u64>, |
| 172 | pub camera_distance: f32, |
| 173 | pub pitches: Vec<i32>, |
| 174 | pub yaws: Vec<u32>, |
| 175 | pub pass_order: Vec<String>, |
| 176 | pub saved_maps: Vec<String>, |
| 177 | pub clips: Vec<ClipRecord>, |
| 178 | pub images: u32, |
| 179 | pub passes: u32, |
| 180 | pub png_files: u32, |
| 181 | } |
| 182 | |
| 183 | #[derive(Debug, Clone, Deserialize)] |
| 184 | pub struct ProjectRef { |
| 185 | pub id: String, |
| 186 | pub name: String, |
| 187 | } |
| 188 | |
| 189 | #[derive(Debug, Clone, Deserialize)] |
| 190 | pub struct CompleteIdentity { |
| 191 | pub project_id: String, |
| 192 | pub project_name: String, |
| 193 | pub sex: String, |
| 194 | pub set: String, |
| 195 | pub body_model_sha256: String, |
| 196 | #[serde(default)] |
| 197 | pub equipment_preset_sha256: Option<String>, |
| 198 | pub target: [u32; 2], |
| 199 | pub fps: u32, |
| 200 | pub framing: CameraFraming, |
| 201 | pub pivot_source: PivotSourceJson, |
| 202 | pub near: f32, |
| 203 | pub far: f32, |
| 204 | pub clips: Vec<ClipRecord>, |
| 205 | pub saved_maps: Vec<String>, |
| 206 | } |
| 207 | |
| 208 | #[derive(Debug, Clone, Deserialize)] |
| 209 | pub struct CompleteManifest { |
| 210 | pub format_version: u32, |
| 211 | pub status: String, |
| 212 | pub identity: CompleteIdentity, |
| 213 | pub passes: u32, |
| 214 | pub png_files: u32, |
| 215 | pub png_sha256: BTreeMap<String, String>, |
| 216 | /// Per-map atlases + `.ppda` written before this marker (t955u). |
| 217 | pub atlas: AtlasRef, |
| 218 | } |
| 219 | |
| 220 | #[derive(Debug, Clone, Deserialize)] |
| 221 | #[serde(deny_unknown_fields)] |
| 222 | pub struct AtlasRef { |
| 223 | pub ppda: String, |
| 224 | pub ppda_sha256: String, |
| 225 | pub maps: BTreeMap<String, AtlasMapRef>, |
| 226 | } |
| 227 | |
| 228 | #[derive(Debug, Clone, Deserialize)] |
| 229 | #[serde(deny_unknown_fields)] |
| 230 | pub struct AtlasMapRef { |
| 231 | pub file: String, |
| 232 | pub sha256: String, |
| 233 | } |
| 234 | |
| 235 | #[derive(Debug, Clone)] |
| 236 | pub struct ExportRun { |
| 237 | root: PathBuf, |
| 238 | pub render: RenderManifest, |
| 239 | pub complete: CompleteManifest, |
| 240 | /// Present when the finished folder has no loose/checkpoint PNGs: maps are |
| 241 | /// served from atlases (Tim t1065u). |
| 242 | atlas: Option<crate::atlas::LoadedAtlas>, |
| 243 | } |
| 244 | |
| 245 | impl ExportRun { |
| 246 | pub fn root(&self) -> &Path { |
| 247 | &self.root |
| 248 | } |
| 249 | |
| 250 | pub fn open(run_dir: &Path) -> Result<Self, ExportError> { |
| 251 | let root = canonicalize_dir(run_dir)?; |
| 252 | if root.join("cancelled.json").exists() || root.join("failed.json").exists() { |
| 253 | return Err(ExportError::Incomplete( |
| 254 | "run is geannuleerd of mislukt; complete.json ontbreekt of is ongeldig".into(), |
| 255 | )); |
| 256 | } |
| 257 | // Finished folders (t993u/t994u) have no JSON besides the `.ppda`, |
| 258 | // which embeds the export contract and per-PNG checksums. |
| 259 | let ppda_export = crate::atlas::AtlasSet::open_run(&root) |
| 260 | .ok() |
| 261 | .is_some_and(|set| set.ppda.export.is_some()); |
| 262 | let (render_bytes, complete_bytes) = if !ppda_export { |
| 263 | let render_bytes = read_manifest_file(&root, "render.json")?; |
| 264 | let complete_bytes = read_manifest_file(&root, "complete.json").map_err(|err| { |
| 265 | if matches!(err, ExportError::Incomplete(_)) { |
| 266 | ExportError::Incomplete( |
| 267 | "complete.json ontbreekt; de exportset is niet volledig".into(), |
| 268 | ) |
| 269 | } else { |
| 270 | err |
| 271 | } |
| 272 | })?; |
| 273 | (render_bytes, complete_bytes) |
| 274 | } else { |
| 275 | manifests_from_ppda(&root)? |
| 276 | }; |
| 277 | let render: RenderManifest = serde_json::from_slice(&render_bytes) |
| 278 | .map_err(|e| ExportError::Corrupt(format!("render.json: {e}")))?; |
| 279 | let complete: CompleteManifest = serde_json::from_slice(&complete_bytes) |
| 280 | .map_err(|e| ExportError::Corrupt(format!("complete.json: {e}")))?; |
| 281 | validate_render(&render)?; |
| 282 | validate_complete(&complete)?; |
| 283 | identities_match(&render, &complete)?; |
| 284 | if complete.png_sha256.len() as u32 != complete.png_files { |
| 285 | return Err(ExportError::Corrupt( |
| 286 | "complete.json png_sha256 telt niet gelijk aan png_files".into(), |
| 287 | )); |
| 288 | } |
| 289 | if complete.png_files != render.png_files { |
| 290 | return Err(ExportError::Identity( |
| 291 | "png_files in complete.json wijkt af van render.json".into(), |
| 292 | )); |
| 293 | } |
| 294 | // Prefer loose/checkpoint PNG verification when present (in-progress or |
| 295 | // legacy result folders). Finished atlas-only folders serve maps from |
| 296 | // the atlases; AtlasSet::open_run already checked atlas digests. |
| 297 | let mut any_cell_file = false; |
| 298 | for relative in complete.png_sha256.keys() { |
| 299 | if cell_file_path(&root, relative).is_some() { |
| 300 | any_cell_file = true; |
| 301 | break; |
| 302 | } |
| 303 | } |
| 304 | let atlas = if any_cell_file { |
| 305 | for (relative, digest) in &complete.png_sha256 { |
| 306 | let path = cell_file_path(&root, relative).ok_or_else(|| { |
| 307 | ExportError::Incomplete(format!("PNG '{relative}' ontbreekt")) |
| 308 | })?; |
| 309 | verify_regular_file(&path, &root)?; |
| 310 | let meta = fs::metadata(&path).map_err(|e| ExportError::Io(e.to_string()))?; |
| 311 | if meta.len() > MAX_PNG_BYTES { |
| 312 | return Err(ExportError::Resource(format!( |
| 313 | "PNG '{relative}' groter dan {MAX_PNG_BYTES} bytes" |
| 314 | ))); |
| 315 | } |
| 316 | let bytes = fs::read(&path).map_err(|e| ExportError::Io(e.to_string()))?; |
| 317 | let actual = digest::sha256_hex(&bytes); |
| 318 | if actual != *digest { |
| 319 | return Err(ExportError::Corrupt(format!( |
| 320 | "checksum mismatch voor '{relative}'" |
| 321 | ))); |
| 322 | } |
| 323 | } |
| 324 | None |
| 325 | } else { |
| 326 | let set = crate::atlas::AtlasSet::open_run(&root)?; |
| 327 | Some(set.load()?) |
| 328 | }; |
| 329 | Ok(Self { |
| 330 | root, |
| 331 | render, |
| 332 | complete, |
| 333 | atlas, |
| 334 | }) |
| 335 | } |
| 336 | |
| 337 | pub fn map_path( |
| 338 | &self, |
| 339 | clip_token: &str, |
| 340 | frame: u32, |
| 341 | pitch: i32, |
| 342 | yaw: u32, |
| 343 | kind: MapKind, |
| 344 | ) -> Result<String, ExportError> { |
| 345 | let relative = crate::production::output_path( |
| 346 | &self.render.sex, |
| 347 | &self.render.set, |
| 348 | clip_token, |
| 349 | frame, |
| 350 | pitch, |
| 351 | yaw, |
| 352 | kind.token(), |
| 353 | ) |
| 354 | .map_err(ExportError::Identity)?; |
| 355 | let mut key = relative |
| 356 | .to_str() |
| 357 | .ok_or_else(|| ExportError::Identity("ongeldig map-pad".into()))? |
| 358 | .replace('\\', "/"); |
| 359 | if !self.complete.png_sha256.contains_key(&key) { |
| 360 | // Older exports stored the loose maps at the run root. |
| 361 | let prefix = format!("{}/", crate::resume::RAW_DIR); |
| 362 | if let Some(legacy) = key.strip_prefix(&prefix) { |
| 363 | if self.complete.png_sha256.contains_key(legacy) { |
| 364 | key = legacy.to_string(); |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | if !self.complete.png_sha256.contains_key(&key) { |
| 369 | return Err(ExportError::Incomplete(format!( |
| 370 | "map '{key}' staat niet in complete.json" |
| 371 | ))); |
| 372 | } |
| 373 | Ok(key) |
| 374 | } |
| 375 | |
| 376 | pub fn load_map( |
| 377 | &self, |
| 378 | clip_token: &str, |
| 379 | frame: u32, |
| 380 | pitch: i32, |
| 381 | yaw: u32, |
| 382 | kind: MapKind, |
| 383 | ) -> Result<MapImage, ExportError> { |
| 384 | let key = self.map_path(clip_token, frame, pitch, yaw, kind)?; |
| 385 | match self.load_relative(&key, kind) { |
| 386 | Ok(img) => Ok(img), |
| 387 | Err(ExportError::Incomplete(_)) | Err(ExportError::Io(_)) if self.atlas.is_some() => { |
| 388 | self.atlas |
| 389 | .as_ref() |
| 390 | .unwrap() |
| 391 | .cell(clip_token, frame, pitch, yaw, kind) |
| 392 | } |
| 393 | Err(e) => Err(e), |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | pub fn load_relative( |
| 398 | &self, |
| 399 | relative: &str, |
| 400 | expected: MapKind, |
| 401 | ) -> Result<MapImage, ExportError> { |
| 402 | let expected_digest = self |
| 403 | .complete |
| 404 | .png_sha256 |
| 405 | .get(relative) |
| 406 | .ok_or_else(|| ExportError::Incomplete(format!("onbekende map '{relative}'")))?; |
| 407 | let path = cell_file_path(&self.root, relative) |
| 408 | .ok_or_else(|| ExportError::Incomplete(format!("PNG '{relative}' ontbreekt")))?; |
| 409 | verify_regular_file(&path, &self.root)?; |
| 410 | let bytes = read_bounded_file(&path, MAX_PNG_BYTES)?; |
| 411 | let actual = digest::sha256_hex(&bytes); |
| 412 | if actual != *expected_digest { |
| 413 | return Err(ExportError::Corrupt(format!( |
| 414 | "checksum mismatch voor '{relative}'" |
| 415 | ))); |
| 416 | } |
| 417 | let token = relative |
| 418 | .rsplit('_') |
| 419 | .next() |
| 420 | .and_then(|s| s.strip_suffix(".png")) |
| 421 | .ok_or_else(|| ExportError::Corrupt(format!("geen map-token in '{relative}'")))?; |
| 422 | let kind = MapKind::parse(token).ok_or_else(|| { |
| 423 | ExportError::Corrupt(format!("onbekend map-token '{token}' in '{relative}'")) |
| 424 | })?; |
| 425 | if kind != expected { |
| 426 | return Err(ExportError::Identity(format!( |
| 427 | "verwachtte {} maar pad is {}", |
| 428 | expected.token(), |
| 429 | kind.token() |
| 430 | ))); |
| 431 | } |
| 432 | let [width, height] = self.render.target; |
| 433 | decode_map(&bytes, kind, width, height, self.render.depth_format()?) |
| 434 | } |
| 435 | |
| 436 | pub fn listed_maps(&self) -> impl Iterator<Item = (&str, &str)> { |
| 437 | self.complete |
| 438 | .png_sha256 |
| 439 | .iter() |
| 440 | .map(|(k, v)| (k.as_str(), v.as_str())) |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | impl RenderManifest { |
| 445 | pub fn depth_format(&self) -> Result<crate::camera::DepthFormat, ExportError> { |
| 446 | let fmt = crate::camera::DepthFormat::from_manifest(self.depth_bits, &self.depth_encoding) |
| 447 | .map_err(ExportError::Identity)?; |
| 448 | if (self.format_version >= 6) != self.depth_bits.is_some() { |
| 449 | return Err(ExportError::Identity( |
| 450 | "depth_bits past niet bij render.json-schema".into(), |
| 451 | )); |
| 452 | } |
| 453 | Ok(fmt) |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | fn validate_render(m: &RenderManifest) -> Result<(), ExportError> { |
| 458 | if !(MIN_OUTPUT_META_VERSION..=OUTPUT_META_VERSION).contains(&m.format_version) { |
| 459 | return Err(ExportError::Identity(if m.format_version == 4 { |
| 460 | "render.json schema 4: oude export met globaal dieptebereik 0,05–40 m; opnieuw renderen" |
| 461 | .into() |
| 462 | } else { |
| 463 | format!( |
| 464 | "render.json format_version {} wordt niet ondersteund (verwacht {OUTPUT_META_VERSION})", |
| 465 | m.format_version |
| 466 | ) |
| 467 | })); |
| 468 | } |
| 469 | if m.status != "incomplete" && m.status != "complete" { |
| 470 | // production leaves status=incomplete in render.json even after success |
| 471 | return Err(ExportError::Corrupt(format!( |
| 472 | "onbekende render.json status '{}'", |
| 473 | m.status |
| 474 | ))); |
| 475 | } |
| 476 | if !["male", "female"].contains(&m.sex.as_str()) { |
| 477 | return Err(ExportError::Identity("ongeldig geslacht".into())); |
| 478 | } |
| 479 | if m.set != "body" && !crate::equipment::valid_name(&m.set) { |
| 480 | return Err(ExportError::Identity("ongeldige setnaam".into())); |
| 481 | } |
| 482 | if m.target[0] == 0 || m.target[1] == 0 || m.target[0] > MAX_TARGET || m.target[1] > MAX_TARGET |
| 483 | { |
| 484 | return Err(ExportError::Resource("target buiten 1–256".into())); |
| 485 | } |
| 486 | if m.fps == 0 || m.fps > 240 { |
| 487 | return Err(ExportError::Identity("ongeldige fps".into())); |
| 488 | } |
| 489 | if m.highres_scale != SCALE { |
| 490 | return Err(ExportError::Identity("highres_scale wijkt af van 8".into())); |
| 491 | } |
| 492 | m.framing.validate().map_err(ExportError::Identity)?; |
| 493 | let (near, far) = crate::camera::depth_range(m.framing); |
| 494 | if m.near != near || m.far != far || m.depth_near != near || m.depth_far != far { |
| 495 | return Err(ExportError::Identity( |
| 496 | "near/far wijkt af van het vaste dieptebereik van deze framing".into(), |
| 497 | )); |
| 498 | } |
| 499 | m.depth_format()?; |
| 500 | if m.camera_distance != crate::camera::CAMERA_DISTANCE { |
| 501 | return Err(ExportError::Identity( |
| 502 | "camera_distance wijkt af van contract".into(), |
| 503 | )); |
| 504 | } |
| 505 | if m.pitches != crate::preview::PRODUCTION_PITCHES { |
| 506 | return Err(ExportError::Identity( |
| 507 | "pitches wijken af van −60,−30,0,+30,+60".into(), |
| 508 | )); |
| 509 | } |
| 510 | if m.yaws != crate::production::production_yaws() { |
| 511 | return Err(ExportError::Identity( |
| 512 | "yaws wijken af van 0…330 stap 30".into(), |
| 513 | )); |
| 514 | } |
| 515 | if m.pass_order != PASSES { |
| 516 | return Err(ExportError::Identity( |
| 517 | "pass_order wijkt af van contract".into(), |
| 518 | )); |
| 519 | } |
| 520 | if m.saved_maps != ["diffuse", "depth", "normal", "specular"] { |
| 521 | return Err(ExportError::Identity( |
| 522 | "saved_maps wijkt af van diffuse/depth/normal/specular".into(), |
| 523 | )); |
| 524 | } |
| 525 | if m.clips.is_empty() || m.clips.len() > MAX_CLIPS { |
| 526 | return Err(ExportError::Resource("clip-inventaris ongeldig".into())); |
| 527 | } |
| 528 | for clip in &m.clips { |
| 529 | if clip.token.is_empty() |
| 530 | || clip.token.len() > 64 |
| 531 | || !crate::equipment::valid_name(&clip.token) |
| 532 | { |
| 533 | return Err(ExportError::Identity(format!( |
| 534 | "ongeldige clip-token '{}'", |
| 535 | clip.token |
| 536 | ))); |
| 537 | } |
| 538 | if clip.name.len() > MAX_CLIP_NAME { |
| 539 | return Err(ExportError::Resource("clipnaam te lang".into())); |
| 540 | } |
| 541 | if clip.frames == 0 { |
| 542 | return Err(ExportError::Identity("clip zonder frames".into())); |
| 543 | } |
| 544 | if !clip.duration.is_finite() || clip.duration < 0. { |
| 545 | return Err(ExportError::Identity("ongeldige clipduur".into())); |
| 546 | } |
| 547 | } |
| 548 | if m.png_files == 0 || m.png_files > MAX_PNG_FILES { |
| 549 | return Err(ExportError::Resource("png_files buiten limiet".into())); |
| 550 | } |
| 551 | if !is_sha256_hex(&m.body_model.sha256) { |
| 552 | return Err(ExportError::Corrupt( |
| 553 | "body_model.sha256 is geen SHA-256 hex".into(), |
| 554 | )); |
| 555 | } |
| 556 | project::portable_relative(&m.body_model.path).map_err(ExportError::Traversal)?; |
| 557 | if m.project.id.is_empty() || m.project.id.len() > 128 { |
| 558 | return Err(ExportError::Identity("project.id ongeldig".into())); |
| 559 | } |
| 560 | if m.project.name.len() > 256 { |
| 561 | return Err(ExportError::Identity("project.name te lang".into())); |
| 562 | } |
| 563 | match &m.equipment_preset { |
| 564 | None if m.set == "body" => {} |
| 565 | Some(p) |
| 566 | if m.set == p.name |
| 567 | && is_sha256_hex(&p.sha256) |
| 568 | && crate::equipment::valid_name(&p.name) => {} |
| 569 | _ => { |
| 570 | return Err(ExportError::Identity( |
| 571 | "equipment_preset past niet bij set of mist geldige sha256".into(), |
| 572 | )) |
| 573 | } |
| 574 | } |
| 575 | match m.pivot_source.kind.as_str() { |
| 576 | "manual" | "bounds_center" | "neck" | "fallback" => {} |
| 577 | other => { |
| 578 | return Err(ExportError::Identity(format!( |
| 579 | "onbekende pivot_source.kind '{other}'" |
| 580 | ))) |
| 581 | } |
| 582 | } |
| 583 | Ok(()) |
| 584 | } |
| 585 | |
| 586 | fn validate_complete(m: &CompleteManifest) -> Result<(), ExportError> { |
| 587 | if !(MIN_OUTPUT_META_VERSION..=OUTPUT_META_VERSION).contains(&m.format_version) { |
| 588 | return Err(ExportError::Identity(format!( |
| 589 | "complete.json format_version {} wordt niet ondersteund", |
| 590 | m.format_version |
| 591 | ))); |
| 592 | } |
| 593 | if m.status != "complete" { |
| 594 | return Err(ExportError::Incomplete( |
| 595 | "complete.json status is niet 'complete'".into(), |
| 596 | )); |
| 597 | } |
| 598 | if m.png_files == 0 || m.png_files > MAX_PNG_FILES { |
| 599 | return Err(ExportError::Resource("png_files buiten limiet".into())); |
| 600 | } |
| 601 | if m.png_sha256.len() > MAX_PNG_FILES as usize { |
| 602 | return Err(ExportError::Resource("te veel png_sha256-items".into())); |
| 603 | } |
| 604 | if !is_sha256_hex(&m.identity.body_model_sha256) { |
| 605 | return Err(ExportError::Corrupt( |
| 606 | "identity.body_model_sha256 ongeldig".into(), |
| 607 | )); |
| 608 | } |
| 609 | if let Some(hash) = &m.identity.equipment_preset_sha256 { |
| 610 | if !is_sha256_hex(hash) { |
| 611 | return Err(ExportError::Corrupt( |
| 612 | "identity.equipment_preset_sha256 ongeldig".into(), |
| 613 | )); |
| 614 | } |
| 615 | } |
| 616 | for (path, hash) in &m.png_sha256 { |
| 617 | project::portable_relative(path).map_err(ExportError::Traversal)?; |
| 618 | if !path.ends_with(".png") { |
| 619 | return Err(ExportError::Corrupt(format!( |
| 620 | "png_sha256-sleutel '{path}' is geen .png" |
| 621 | ))); |
| 622 | } |
| 623 | if !is_sha256_hex(hash) { |
| 624 | return Err(ExportError::Corrupt(format!( |
| 625 | "png_sha256 voor '{path}' is geen SHA-256 hex" |
| 626 | ))); |
| 627 | } |
| 628 | } |
| 629 | Ok(()) |
| 630 | } |
| 631 | |
| 632 | fn identities_match( |
| 633 | render: &RenderManifest, |
| 634 | complete: &CompleteManifest, |
| 635 | ) -> Result<(), ExportError> { |
| 636 | let id = &complete.identity; |
| 637 | let check = |ok: bool, msg: &str| { |
| 638 | if ok { |
| 639 | Ok(()) |
| 640 | } else { |
| 641 | Err(ExportError::Identity(msg.into())) |
| 642 | } |
| 643 | }; |
| 644 | check(id.project_id == render.project.id, "project.id mismatch")?; |
| 645 | check( |
| 646 | id.project_name == render.project.name, |
| 647 | "project.name mismatch", |
| 648 | )?; |
| 649 | check(id.sex == render.sex, "sex mismatch")?; |
| 650 | check(id.set == render.set, "set mismatch")?; |
| 651 | check( |
| 652 | id.body_model_sha256 == render.body_model.sha256, |
| 653 | "body_model sha256 mismatch", |
| 654 | )?; |
| 655 | check(id.target == render.target, "target mismatch")?; |
| 656 | check(id.fps == render.fps, "fps mismatch")?; |
| 657 | check(id.framing == render.framing, "framing mismatch")?; |
| 658 | check( |
| 659 | id.near == render.near && id.far == render.far, |
| 660 | "near/far mismatch", |
| 661 | )?; |
| 662 | check(id.saved_maps == render.saved_maps, "saved_maps mismatch")?; |
| 663 | let atlas = &complete.atlas; |
| 664 | check( |
| 665 | atlas.ppda == crate::atlas::ppda_name(&render.sex, &render.set) |
| 666 | && is_sha256_hex(&atlas.ppda_sha256), |
| 667 | "atlas.ppda naam/sha256 ongeldig", |
| 668 | )?; |
| 669 | check(atlas.maps.len() == 4, "atlas.maps moet vier maps bevatten")?; |
| 670 | for kind in crate::atlas::ATLAS_MAPS { |
| 671 | let entry = atlas |
| 672 | .maps |
| 673 | .get(kind.token()) |
| 674 | .ok_or_else(|| ExportError::Identity(format!("atlas mist {}", kind.token())))?; |
| 675 | check( |
| 676 | entry.file == crate::atlas::atlas_png_name(&render.sex, &render.set, kind) |
| 677 | && is_sha256_hex(&entry.sha256), |
| 678 | "atlas-bestandsnaam/sha256 ongeldig", |
| 679 | )?; |
| 680 | } |
| 681 | check( |
| 682 | id.clips.len() == render.clips.len(), |
| 683 | "clips length mismatch", |
| 684 | )?; |
| 685 | for (a, b) in id.clips.iter().zip(render.clips.iter()) { |
| 686 | if a.token != b.token || a.frames != b.frames || a.name != b.name { |
| 687 | return Err(ExportError::Identity("clip inventory mismatch".into())); |
| 688 | } |
| 689 | } |
| 690 | check( |
| 691 | id.pivot_source.kind == render.pivot_source.kind, |
| 692 | "pivot_source mismatch", |
| 693 | )?; |
| 694 | let preset_hash = render.equipment_preset.as_ref().map(|p| p.sha256.clone()); |
| 695 | check( |
| 696 | id.equipment_preset_sha256 == preset_hash, |
| 697 | "equipment preset sha256 mismatch", |
| 698 | )?; |
| 699 | Ok(()) |
| 700 | } |
| 701 | |
| 702 | pub(crate) fn decode_map( |
| 703 | bytes: &[u8], |
| 704 | kind: MapKind, |
| 705 | expect_w: u32, |
| 706 | expect_h: u32, |
| 707 | depth: crate::camera::DepthFormat, |
| 708 | ) -> Result<MapImage, ExportError> { |
| 709 | decode_map_sized(bytes, kind, expect_w, expect_h, MAX_TARGET, depth) |
| 710 | } |
| 711 | |
| 712 | /// Decode a map PNG of exactly `expect_w`×`expect_h` (each ≤ `max_dim`) under |
| 713 | /// the published pixel contract. Atlases use the same rules with a larger cap. |
| 714 | pub(crate) fn decode_map_sized( |
| 715 | bytes: &[u8], |
| 716 | kind: MapKind, |
| 717 | expect_w: u32, |
| 718 | expect_h: u32, |
| 719 | max_dim: u32, |
| 720 | depth: crate::camera::DepthFormat, |
| 721 | ) -> Result<MapImage, ExportError> { |
| 722 | if expect_w == 0 || expect_h == 0 || expect_w > max_dim || expect_h > max_dim { |
| 723 | return Err(ExportError::Resource("PNG-afmetingen buiten limiet".into())); |
| 724 | } |
| 725 | let decoded = expect_w as usize * expect_h as usize * 4; |
| 726 | let mut decoder = png::Decoder::new_with_limits( |
| 727 | std::io::Cursor::new(bytes), |
| 728 | png::Limits { |
| 729 | bytes: decoded.saturating_mul(2).max(64 * 1024 * 1024), |
| 730 | }, |
| 731 | ); |
| 732 | decoder.set_transformations(png::Transformations::IDENTITY); |
| 733 | let mut reader = decoder |
| 734 | .read_info() |
| 735 | .map_err(|e| ExportError::Corrupt(format!("PNG header: {e}")))?; |
| 736 | let info = reader.info(); |
| 737 | if info.width != expect_w || info.height != expect_h { |
| 738 | return Err(ExportError::Corrupt(format!( |
| 739 | "PNG-afmetingen {}x{} wijken af van target {expect_w}x{expect_h}", |
| 740 | info.width, info.height |
| 741 | ))); |
| 742 | } |
| 743 | if info.width > max_dim || info.height > max_dim { |
| 744 | return Err(ExportError::Resource("PNG groter dan limiet".into())); |
| 745 | } |
| 746 | match kind { |
| 747 | MapKind::Diffuse | MapKind::Normal | MapKind::Specular => { |
| 748 | if info.color_type != png::ColorType::Rgba || info.bit_depth != png::BitDepth::Eight { |
| 749 | return Err(ExportError::Corrupt( |
| 750 | "RGBA8-map heeft onverwacht kleurtype/bitdiepte".into(), |
| 751 | )); |
| 752 | } |
| 753 | let size = reader.output_buffer_size().ok_or_else(|| { |
| 754 | ExportError::Corrupt("PNG buffergrootte onbekend of te groot".into()) |
| 755 | })?; |
| 756 | let mut buf = vec![0u8; size]; |
| 757 | let frame = reader |
| 758 | .next_frame(&mut buf) |
| 759 | .map_err(|e| ExportError::Corrupt(format!("PNG data: {e}")))?; |
| 760 | if frame.buffer_size() != expect_w as usize * expect_h as usize * 4 { |
| 761 | return Err(ExportError::Corrupt("PNG buffergrootte klopt niet".into())); |
| 762 | } |
| 763 | buf.truncate(frame.buffer_size()); |
| 764 | if kind == MapKind::Normal { |
| 765 | validate_normals(&buf, expect_w, expect_h)?; |
| 766 | } |
| 767 | if kind == MapKind::Specular { |
| 768 | validate_specular_channels(&buf)?; |
| 769 | } |
| 770 | Ok(MapImage::Rgba8 { |
| 771 | width: expect_w, |
| 772 | height: expect_h, |
| 773 | rgba: buf, |
| 774 | }) |
| 775 | } |
| 776 | MapKind::Depth => { |
| 777 | drop(reader); |
| 778 | let native = decode_depth_native(bytes, expect_w, expect_h, max_dim, depth)?; |
| 779 | let samples = canonical_depth(&native, depth)?; |
| 780 | Ok(MapImage::Depth16 { |
| 781 | width: expect_w, |
| 782 | height: expect_h, |
| 783 | samples, |
| 784 | }) |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | /// Decode a depth PNG in `fmt` and return its raw big-endian samples |
| 790 | /// (validated: format, size, alpha rule, band order). |
| 791 | pub(crate) fn decode_depth_native( |
| 792 | bytes: &[u8], |
| 793 | expect_w: u32, |
| 794 | expect_h: u32, |
| 795 | max_dim: u32, |
| 796 | fmt: crate::camera::DepthFormat, |
| 797 | ) -> Result<Vec<u8>, ExportError> { |
| 798 | if expect_w == 0 || expect_h == 0 || expect_w > max_dim || expect_h > max_dim { |
| 799 | return Err(ExportError::Resource("PNG-afmetingen buiten limiet".into())); |
| 800 | } |
| 801 | let expected = expect_w as usize * expect_h as usize * fmt.bytes_per_pixel(); |
| 802 | let mut decoder = png::Decoder::new_with_limits( |
| 803 | std::io::Cursor::new(bytes), |
| 804 | png::Limits { |
| 805 | bytes: expected.saturating_mul(2).max(64 * 1024 * 1024), |
| 806 | }, |
| 807 | ); |
| 808 | decoder.set_transformations(png::Transformations::IDENTITY); |
| 809 | let mut reader = decoder |
| 810 | .read_info() |
| 811 | .map_err(|e| ExportError::Corrupt(format!("PNG header: {e}")))?; |
| 812 | let info = reader.info(); |
| 813 | if info.width != expect_w || info.height != expect_h { |
| 814 | return Err(ExportError::Corrupt(format!( |
| 815 | "PNG-afmetingen {}x{} wijken af van target {expect_w}x{expect_h}", |
| 816 | info.width, info.height |
| 817 | ))); |
| 818 | } |
| 819 | if info.color_type != fmt.color_type() || info.bit_depth != fmt.bit_depth() { |
| 820 | return Err(ExportError::Corrupt(format!( |
| 821 | "depth-map moet {} {}-bit zijn", |
| 822 | fmt.encoding.token(), |
| 823 | fmt.bits |
| 824 | ))); |
| 825 | } |
| 826 | let size = reader |
| 827 | .output_buffer_size() |
| 828 | .ok_or_else(|| ExportError::Corrupt("PNG buffergrootte onbekend of te groot".into()))?; |
| 829 | let mut buf = vec![0u8; size]; |
| 830 | let frame = reader |
| 831 | .next_frame(&mut buf) |
| 832 | .map_err(|e| ExportError::Corrupt(format!("PNG data: {e}")))?; |
| 833 | if frame.buffer_size() != expected { |
| 834 | return Err(ExportError::Corrupt( |
| 835 | "depth buffergrootte klopt niet".into(), |
| 836 | )); |
| 837 | } |
| 838 | buf.truncate(expected); |
| 839 | canonical_depth(&buf, fmt)?; |
| 840 | Ok(buf) |
| 841 | } |
| 842 | |
| 843 | /// Stored depth pixels in `fmt` → RGBA8 for display, as stored (Tim t992u): no |
| 844 | /// decoding of rgb_bands / rgb_packed. Gray shows as gray, RGB channels show as |
| 845 | /// their own RGB, alpha stays alpha; 16-bit samples are reduced to 8-bit display |
| 846 | /// precision by rounding (`v·255/65535`). |
| 847 | pub(crate) fn depth_display_rgba(native: &[u8], fmt: crate::camera::DepthFormat) -> Vec<u8> { |
| 848 | let wide = fmt.bits == 16; |
| 849 | let sample = |px: &[u8], c: usize| -> u8 { |
| 850 | if wide { |
| 851 | let v = u32::from(u16::from_be_bytes([px[c * 2], px[c * 2 + 1]])); |
| 852 | ((v * 255 + 32767) / 65535) as u8 |
| 853 | } else { |
| 854 | px[c] |
| 855 | } |
| 856 | }; |
| 857 | let bpp = fmt.bytes_per_pixel(); |
| 858 | let mut out = Vec::with_capacity(native.len() / bpp * 4); |
| 859 | for px in native.chunks_exact(bpp) { |
| 860 | if fmt.channels() == 2 { |
| 861 | let g = sample(px, 0); |
| 862 | out.extend_from_slice(&[g, g, g, sample(px, 1)]); |
| 863 | } else { |
| 864 | out.extend_from_slice(&[sample(px, 0), sample(px, 1), sample(px, 2), sample(px, 3)]); |
| 865 | } |
| 866 | } |
| 867 | out |
| 868 | } |
| 869 | |
| 870 | /// Raw depth samples in `fmt` → canonical interleaved 16-bit (depth, alpha). |
| 871 | pub(crate) fn canonical_depth( |
| 872 | native: &[u8], |
| 873 | fmt: crate::camera::DepthFormat, |
| 874 | ) -> Result<Vec<u16>, ExportError> { |
| 875 | let bpp = fmt.bytes_per_pixel(); |
| 876 | let mut samples = Vec::with_capacity(native.len() / bpp * 2); |
| 877 | for px in native.chunks_exact(bpp) { |
| 878 | let (d, a) = fmt.decode_pixel(px).map_err(ExportError::Corrupt)?; |
| 879 | if a == 0 && px[..bpp - bpp / fmt.channels()].iter().any(|b| *b != 0) { |
| 880 | return Err(ExportError::Corrupt( |
| 881 | "transparante depth heeft niet-nul gray".into(), |
| 882 | )); |
| 883 | } |
| 884 | samples.push(d); |
| 885 | samples.push(a); |
| 886 | } |
| 887 | validate_depth_alpha(&samples)?; |
| 888 | Ok(samples) |
| 889 | } |
| 890 | |
| 891 | fn validate_normals(rgba: &[u8], _w: u32, _h: u32) -> Result<(), ExportError> { |
| 892 | for px in rgba.chunks_exact(4) { |
| 893 | let a = px[3]; |
| 894 | if a == 0 { |
| 895 | if px[0] != 0 || px[1] != 0 || px[2] != 0 { |
| 896 | return Err(ExportError::Corrupt( |
| 897 | "transparante normal heeft niet-nul RGB".into(), |
| 898 | )); |
| 899 | } |
| 900 | continue; |
| 901 | } |
| 902 | let nx = px[0] as f32 / 255. * 2. - 1.; |
| 903 | let ny = px[1] as f32 / 255. * 2. - 1.; |
| 904 | let nz = px[2] as f32 / 255. * 2. - 1.; |
| 905 | let len = (nx * nx + ny * ny + nz * nz).sqrt(); |
| 906 | if !(0.85..=1.15).contains(&len) { |
| 907 | return Err(ExportError::Corrupt(format!( |
| 908 | "normal lengte {len} buiten tolerantie" |
| 909 | ))); |
| 910 | } |
| 911 | } |
| 912 | Ok(()) |
| 913 | } |
| 914 | |
| 915 | fn validate_specular_channels(rgba: &[u8]) -> Result<(), ExportError> { |
| 916 | for px in rgba.chunks_exact(4) { |
| 917 | if px[0] != px[1] || px[1] != px[2] { |
| 918 | return Err(ExportError::Corrupt( |
| 919 | "specular RGB-kanalen zijn niet gelijk".into(), |
| 920 | )); |
| 921 | } |
| 922 | } |
| 923 | Ok(()) |
| 924 | } |
| 925 | |
| 926 | fn validate_depth_alpha(samples: &[u16]) -> Result<(), ExportError> { |
| 927 | for pair in samples.chunks_exact(2) { |
| 928 | let gray = pair[0]; |
| 929 | let alpha = pair[1]; |
| 930 | if alpha == 0 && gray != 0 { |
| 931 | return Err(ExportError::Corrupt( |
| 932 | "transparante depth heeft niet-nul gray".into(), |
| 933 | )); |
| 934 | } |
| 935 | } |
| 936 | Ok(()) |
| 937 | } |
| 938 | |
| 939 | fn canonicalize_dir(path: &Path) -> Result<PathBuf, ExportError> { |
| 940 | let meta = fs::metadata(path).map_err(|e| ExportError::Io(e.to_string()))?; |
| 941 | if !meta.is_dir() { |
| 942 | return Err(ExportError::Io("runpad is geen map".into())); |
| 943 | } |
| 944 | path.canonicalize() |
| 945 | .map_err(|e| ExportError::Io(e.to_string())) |
| 946 | } |
| 947 | |
| 948 | /// Rebuild the `render.json` / `complete.json` documents from the `.ppda`'s |
| 949 | /// embedded `export` section (finished result folders, Tim t994u). |
| 950 | fn manifests_from_ppda(root: &Path) -> Result<(Vec<u8>, Vec<u8>), ExportError> { |
| 951 | let set = crate::atlas::AtlasSet::open_run(root).map_err(|e| match e { |
| 952 | ExportError::Incomplete(_) => ExportError::Incomplete( |
| 953 | "complete.json ontbreekt en er is geen .ppda; de exportset is niet volledig".into(), |
| 954 | ), |
| 955 | other => other, |
| 956 | })?; |
| 957 | let export = set.ppda.export.as_ref().ok_or_else(|| { |
| 958 | ExportError::Incomplete(".ppda bevat geen exportgegevens en complete.json ontbreekt".into()) |
| 959 | })?; |
| 960 | let ppda_name = crate::atlas::ppda_name(&set.ppda.sex, &set.ppda.settype); |
| 961 | let ppda_bytes = read_bounded_file(&root.join(&ppda_name), crate::atlas::MAX_PPDA_BYTES)?; |
| 962 | let identity = complete_identity_json(&export.render).map_err(ExportError::Identity)?; |
| 963 | let maps: serde_json::Map<String, serde_json::Value> = set |
| 964 | .ppda |
| 965 | .maps |
| 966 | .iter() |
| 967 | .map(|(k, m)| { |
| 968 | ( |
| 969 | k.clone(), |
| 970 | serde_json::json!({"file": m.file, "sha256": m.sha256}), |
| 971 | ) |
| 972 | }) |
| 973 | .collect(); |
| 974 | let complete = serde_json::json!({ |
| 975 | "format_version": export.render.get("format_version").cloned().unwrap_or_default(), |
| 976 | "status": "complete", |
| 977 | "identity": identity, |
| 978 | "passes": export.passes, |
| 979 | "png_files": export.png_sha256.len(), |
| 980 | "png_sha256": export.png_sha256, |
| 981 | "atlas": { |
| 982 | "ppda": ppda_name, |
| 983 | "ppda_sha256": digest::sha256_hex(&ppda_bytes), |
| 984 | "maps": maps, |
| 985 | }, |
| 986 | }); |
| 987 | let to = |v: &serde_json::Value| { |
| 988 | serde_json::to_vec(v).map_err(|e| ExportError::Corrupt(e.to_string())) |
| 989 | }; |
| 990 | Ok((to(&export.render)?, to(&complete)?)) |
| 991 | } |
| 992 | |
| 993 | fn read_manifest_file(root: &Path, name: &str) -> Result<Vec<u8>, ExportError> { |
| 994 | let path = root.join(name); |
| 995 | if !path.exists() { |
| 996 | return Err(ExportError::Incomplete(format!("{name} ontbreekt"))); |
| 997 | } |
| 998 | verify_regular_file(&path, root)?; |
| 999 | read_bounded_file(&path, MAX_MANIFEST_BYTES) |
| 1000 | } |
| 1001 | |
| 1002 | pub(crate) fn read_bounded_file(path: &Path, max: u64) -> Result<Vec<u8>, ExportError> { |
| 1003 | let meta = fs::metadata(path).map_err(|e| ExportError::Io(e.to_string()))?; |
| 1004 | if meta.len() > max { |
| 1005 | return Err(ExportError::Resource(format!( |
| 1006 | "{} groter dan {max} bytes", |
| 1007 | path.display() |
| 1008 | ))); |
| 1009 | } |
| 1010 | let file = fs::File::open(path).map_err(|e| ExportError::Io(e.to_string()))?; |
| 1011 | let mut bytes = Vec::new(); |
| 1012 | file.take(max + 1) |
| 1013 | .read_to_end(&mut bytes) |
| 1014 | .map_err(|e| ExportError::Io(e.to_string()))?; |
| 1015 | if bytes.len() as u64 > max { |
| 1016 | return Err(ExportError::Resource(format!( |
| 1017 | "{} groter dan {max} bytes", |
| 1018 | path.display() |
| 1019 | ))); |
| 1020 | } |
| 1021 | Ok(bytes) |
| 1022 | } |
| 1023 | |
| 1024 | |
| 1025 | /// Locate a cell PNG: logical path, then `checkpoint/<logical>` (Tim t1065u). |
| 1026 | fn cell_file_path(root: &Path, relative: &str) -> Option<PathBuf> { |
| 1027 | crate::resume::find_cell_file(root, relative) |
| 1028 | } |
| 1029 | |
| 1030 | pub(crate) fn verify_regular_file(path: &Path, root: &Path) -> Result<(), ExportError> { |
| 1031 | let meta = fs::symlink_metadata(path).map_err(|e| ExportError::Io(e.to_string()))?; |
| 1032 | if meta.file_type().is_symlink() { |
| 1033 | return Err(ExportError::Traversal(format!( |
| 1034 | "symlink geweigerd: {}", |
| 1035 | path.display() |
| 1036 | ))); |
| 1037 | } |
| 1038 | if !meta.is_file() { |
| 1039 | return Err(ExportError::Io(format!( |
| 1040 | "geen regulier bestand: {}", |
| 1041 | path.display() |
| 1042 | ))); |
| 1043 | } |
| 1044 | let root_real = root |
| 1045 | .canonicalize() |
| 1046 | .map_err(|e| ExportError::Io(e.to_string()))?; |
| 1047 | let path_real = path |
| 1048 | .canonicalize() |
| 1049 | .map_err(|e| ExportError::Io(e.to_string()))?; |
| 1050 | if !path_real.starts_with(&root_real) { |
| 1051 | return Err(ExportError::Traversal(format!( |
| 1052 | "pad verlaat runmap: {}", |
| 1053 | path.display() |
| 1054 | ))); |
| 1055 | } |
| 1056 | Ok(()) |
| 1057 | } |
| 1058 | |
| 1059 | /// Build the identity object embedded in complete.json (shared with production). |
| 1060 | pub fn complete_identity_json(render: &serde_json::Value) -> Result<serde_json::Value, String> { |
| 1061 | let project = render.get("project").ok_or("render.json mist project")?; |
| 1062 | Ok(serde_json::json!({ |
| 1063 | "project_id": project.get("id").ok_or("project.id")?, |
| 1064 | "project_name": project.get("name").ok_or("project.name")?, |
| 1065 | "sex": render.get("sex").ok_or("sex")?, |
| 1066 | "set": render.get("set").ok_or("set")?, |
| 1067 | "body_model_sha256": render.pointer("/body_model/sha256").ok_or("body sha")?, |
| 1068 | "equipment_preset_sha256": render.pointer("/equipment_preset/sha256").cloned().unwrap_or(serde_json::Value::Null), |
| 1069 | "target": render.get("target").ok_or("target")?, |
| 1070 | "fps": render.get("fps").ok_or("fps")?, |
| 1071 | "framing": render.get("framing").ok_or("framing")?, |
| 1072 | "pivot_source": render.get("pivot_source").ok_or("pivot")?, |
| 1073 | "near": render.get("near").ok_or("near")?, |
| 1074 | "far": render.get("far").ok_or("far")?, |
| 1075 | "clips": render.get("clips").ok_or("clips")?, |
| 1076 | "saved_maps": render.get("saved_maps").ok_or("maps")?, |
| 1077 | })) |
| 1078 | } |
| 1079 | |
| 1080 | #[cfg(test)] |
| 1081 | mod tests { |
| 1082 | use super::*; |
| 1083 | use crate::production::{write_depth, write_rgba}; |
| 1084 | use crate::render_job::ImageBuf; |
| 1085 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 1086 | |
| 1087 | struct Temp(PathBuf); |
| 1088 | impl Temp { |
| 1089 | fn new() -> Self { |
| 1090 | static N: AtomicU64 = AtomicU64::new(0); |
| 1091 | let id = N.fetch_add(1, Ordering::Relaxed); |
| 1092 | let path = std::env::temp_dir().join(format!( |
| 1093 | "paperdoll-export-set-{}-{}", |
| 1094 | std::process::id(), |
| 1095 | id |
| 1096 | )); |
| 1097 | let _ = fs::remove_dir_all(&path); |
| 1098 | fs::create_dir_all(&path).unwrap(); |
| 1099 | Self(path) |
| 1100 | } |
| 1101 | } |
| 1102 | impl Drop for Temp { |
| 1103 | fn drop(&mut self) { |
| 1104 | let _ = fs::remove_dir_all(&self.0); |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | fn framing() -> CameraFraming { |
| 1109 | CameraFraming { |
| 1110 | height_milli: 2600, |
| 1111 | center_y_milli: 1000, |
| 1112 | pivot_y_milli: Some(1460), |
| 1113 | depth_range_milli: None, |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | fn write_atomic_json(root: &Path, name: &str, value: &serde_json::Value) { |
| 1118 | let data = serde_json::to_vec_pretty(value).unwrap(); |
| 1119 | let path = root.join(name); |
| 1120 | let temp = path.with_extension(format!("part-{}", std::process::id())); |
| 1121 | fs::write(&temp, &data).unwrap(); |
| 1122 | fs::hard_link(&temp, &path).unwrap(); |
| 1123 | let _ = fs::remove_file(temp); |
| 1124 | } |
| 1125 | |
| 1126 | fn atlas_ref() -> serde_json::Value { |
| 1127 | let sha = digest::sha256_hex(b"atlas"); |
| 1128 | let map = |m: &str| serde_json::json!({"file": format!("male-body-{m}-atlas.png"), "sha256": sha}); |
| 1129 | serde_json::json!({ |
| 1130 | "ppda": "male-body-atlas.ppda", |
| 1131 | "ppda_sha256": sha, |
| 1132 | "maps": {"diffuse": map("diffuse"), "normal": map("normal"), "depth": map("depth"), "specular": map("specular")} |
| 1133 | }) |
| 1134 | } |
| 1135 | |
| 1136 | fn base_render(png_files: u32) -> serde_json::Value { |
| 1137 | serde_json::json!({ |
| 1138 | "format_version": OUTPUT_META_VERSION, |
| 1139 | "status": "incomplete", |
| 1140 | "project": {"id": "demo", "name": "Demo"}, |
| 1141 | "sex": "male", |
| 1142 | "set": "body", |
| 1143 | "body_model": {"path": "assets/body/x.glb", "sha256": digest::sha256_hex(b"body")}, |
| 1144 | "equipment_preset": null, |
| 1145 | "target": [1, 1], |
| 1146 | "fps": 12, |
| 1147 | "highres_scale": 8, |
| 1148 | "framing": framing(), |
| 1149 | "pivot_source": {"kind": "manual"}, |
| 1150 | "near": crate::camera::depth_range(framing()).0, |
| 1151 | "far": crate::camera::depth_range(framing()).1, |
| 1152 | "depth_near": crate::camera::depth_range(framing()).0, |
| 1153 | "depth_far": crate::camera::depth_range(framing()).1, |
| 1154 | "depth_encoding": "gray", |
| 1155 | "depth_bits": 16, |
| 1156 | "camera_distance": 10.0, |
| 1157 | "yaw_zero": "camera on +Z", |
| 1158 | "normal_space": "view (+Y up), PNG rows top-down", |
| 1159 | "pitches": crate::preview::PRODUCTION_PITCHES, |
| 1160 | "yaws": crate::production::production_yaws(), |
| 1161 | "yaw_step": 30, |
| 1162 | "sampling": "test", |
| 1163 | "alpha": "straight", |
| 1164 | "diffuse": "unlit", |
| 1165 | "depth": "16-bit", |
| 1166 | "specular": "scalar", |
| 1167 | "pass_order": PASSES, |
| 1168 | "saved_maps": ["diffuse", "depth", "normal", "specular"], |
| 1169 | "clips": [{"name": "", "token": "clip000-bind", "frames": 1, "duration": 0.0}], |
| 1170 | "images": 1, |
| 1171 | "passes": 6, |
| 1172 | "png_files": png_files |
| 1173 | }) |
| 1174 | } |
| 1175 | |
| 1176 | fn publish_four(root: &Path) -> BTreeMap<String, String> { |
| 1177 | let mut map = BTreeMap::new(); |
| 1178 | let rels = [ |
| 1179 | ( |
| 1180 | "male/body/clip000-bind/f000000/p-60_y000_diffuse.png", |
| 1181 | "diffuse", |
| 1182 | ), |
| 1183 | ( |
| 1184 | "male/body/clip000-bind/f000000/p-60_y000_depth.png", |
| 1185 | "depth", |
| 1186 | ), |
| 1187 | ( |
| 1188 | "male/body/clip000-bind/f000000/p-60_y000_normal.png", |
| 1189 | "normal", |
| 1190 | ), |
| 1191 | ( |
| 1192 | "male/body/clip000-bind/f000000/p-60_y000_specular.png", |
| 1193 | "specular", |
| 1194 | ), |
| 1195 | ]; |
| 1196 | for (rel, kind) in rels { |
| 1197 | let path = Path::new(rel); |
| 1198 | match kind { |
| 1199 | "depth" => write_depth(root, path, 1, 1, &[20000, 65535]).unwrap(), |
| 1200 | "normal" => write_rgba( |
| 1201 | root, |
| 1202 | path, |
| 1203 | &ImageBuf { |
| 1204 | width: 1, |
| 1205 | height: 1, |
| 1206 | rgba: vec![128, 128, 255, 255], |
| 1207 | }, |
| 1208 | ) |
| 1209 | .unwrap(), |
| 1210 | "specular" => write_rgba( |
| 1211 | root, |
| 1212 | path, |
| 1213 | &ImageBuf { |
| 1214 | width: 1, |
| 1215 | height: 1, |
| 1216 | rgba: vec![0, 0, 0, 255], |
| 1217 | }, |
| 1218 | ) |
| 1219 | .unwrap(), |
| 1220 | _ => write_rgba( |
| 1221 | root, |
| 1222 | path, |
| 1223 | &ImageBuf { |
| 1224 | width: 1, |
| 1225 | height: 1, |
| 1226 | rgba: vec![10, 20, 30, 255], |
| 1227 | }, |
| 1228 | ) |
| 1229 | .unwrap(), |
| 1230 | }; |
| 1231 | let bytes = fs::read(root.join(rel)).unwrap(); |
| 1232 | map.insert(rel.to_string(), digest::sha256_hex(&bytes)); |
| 1233 | } |
| 1234 | map |
| 1235 | } |
| 1236 | |
| 1237 | #[test] |
| 1238 | fn opens_completed_run_and_reads_maps() { |
| 1239 | let tmp = Temp::new(); |
| 1240 | let checksums = publish_four(&tmp.0); |
| 1241 | let render = base_render(4); |
| 1242 | write_atomic_json(&tmp.0, "render.json", &render); |
| 1243 | let identity = complete_identity_json(&render).unwrap(); |
| 1244 | write_atomic_json( |
| 1245 | &tmp.0, |
| 1246 | "complete.json", |
| 1247 | &serde_json::json!({ |
| 1248 | "format_version": OUTPUT_META_VERSION, |
| 1249 | "status": "complete", |
| 1250 | "identity": identity, |
| 1251 | "passes": 6, |
| 1252 | "png_files": 4, |
| 1253 | "png_sha256": checksums, |
| 1254 | "atlas": atlas_ref() |
| 1255 | }), |
| 1256 | ); |
| 1257 | let run = ExportRun::open(&tmp.0).unwrap(); |
| 1258 | let diffuse = run |
| 1259 | .load_map("clip000-bind", 0, -60, 0, MapKind::Diffuse) |
| 1260 | .unwrap(); |
| 1261 | match diffuse { |
| 1262 | MapImage::Rgba8 { |
| 1263 | width, |
| 1264 | height, |
| 1265 | rgba, |
| 1266 | } => { |
| 1267 | assert_eq!((width, height), (1, 1)); |
| 1268 | assert_eq!(rgba, [10, 20, 30, 255]); |
| 1269 | } |
| 1270 | _ => panic!("expected rgba"), |
| 1271 | } |
| 1272 | let depth = run |
| 1273 | .load_map("clip000-bind", 0, -60, 0, MapKind::Depth) |
| 1274 | .unwrap(); |
| 1275 | match depth { |
| 1276 | MapImage::Depth16 { samples, .. } => assert_eq!(samples, [20000, 65535]), |
| 1277 | _ => panic!("expected depth"), |
| 1278 | } |
| 1279 | } |
| 1280 | |
| 1281 | #[test] |
| 1282 | fn rejects_missing_complete_and_checksum_mismatch() { |
| 1283 | let tmp = Temp::new(); |
| 1284 | let render = base_render(4); |
| 1285 | write_atomic_json(&tmp.0, "render.json", &render); |
| 1286 | assert!(matches!( |
| 1287 | ExportRun::open(&tmp.0), |
| 1288 | Err(ExportError::Incomplete(_)) |
| 1289 | )); |
| 1290 | let mut checksums = publish_four(&tmp.0); |
| 1291 | *checksums.values_mut().next().unwrap() = digest::sha256_hex(b"tampered"); |
| 1292 | let identity = complete_identity_json(&render).unwrap(); |
| 1293 | write_atomic_json( |
| 1294 | &tmp.0, |
| 1295 | "complete.json", |
| 1296 | &serde_json::json!({ |
| 1297 | "format_version": OUTPUT_META_VERSION, |
| 1298 | "status": "complete", |
| 1299 | "identity": identity, |
| 1300 | "passes": 6, |
| 1301 | "png_files": 4, |
| 1302 | "png_sha256": checksums, |
| 1303 | "atlas": atlas_ref() |
| 1304 | }), |
| 1305 | ); |
| 1306 | assert!(matches!( |
| 1307 | ExportRun::open(&tmp.0), |
| 1308 | Err(ExportError::Corrupt(_)) |
| 1309 | )); |
| 1310 | } |
| 1311 | |
| 1312 | #[test] |
| 1313 | fn rejects_path_traversal_and_symlink_escape() { |
| 1314 | let tmp = Temp::new(); |
| 1315 | let mut checksums = publish_four(&tmp.0); |
| 1316 | checksums.insert("../escape.png".into(), digest::sha256_hex(b"x")); |
| 1317 | let render = base_render(5); |
| 1318 | write_atomic_json(&tmp.0, "render.json", &render); |
| 1319 | let identity = complete_identity_json(&render).unwrap(); |
| 1320 | write_atomic_json( |
| 1321 | &tmp.0, |
| 1322 | "complete.json", |
| 1323 | &serde_json::json!({ |
| 1324 | "format_version": OUTPUT_META_VERSION, |
| 1325 | "status": "complete", |
| 1326 | "identity": identity, |
| 1327 | "passes": 6, |
| 1328 | "png_files": 5, |
| 1329 | "png_sha256": checksums, |
| 1330 | "atlas": atlas_ref() |
| 1331 | }), |
| 1332 | ); |
| 1333 | assert!(matches!( |
| 1334 | ExportRun::open(&tmp.0), |
| 1335 | Err(ExportError::Traversal(_)) |
| 1336 | )); |
| 1337 | |
| 1338 | #[cfg(unix)] |
| 1339 | { |
| 1340 | let tmp = Temp::new(); |
| 1341 | let outside = Temp::new(); |
| 1342 | let checksums = publish_four(&tmp.0); |
| 1343 | let evil = "male/body/clip000-bind/f000000/p-60_y000_diffuse.png"; |
| 1344 | let _ = fs::remove_file(tmp.0.join(evil)); |
| 1345 | std::os::unix::fs::symlink(outside.0.join("secret.png"), tmp.0.join(evil)).unwrap(); |
| 1346 | fs::write(outside.0.join("secret.png"), b"not-a-png").unwrap(); |
| 1347 | let render = base_render(4); |
| 1348 | write_atomic_json(&tmp.0, "render.json", &render); |
| 1349 | let identity = complete_identity_json(&render).unwrap(); |
| 1350 | let mut checksums = checksums; |
| 1351 | checksums.insert(evil.into(), digest::sha256_hex(b"not-a-png")); |
| 1352 | write_atomic_json( |
| 1353 | &tmp.0, |
| 1354 | "complete.json", |
| 1355 | &serde_json::json!({ |
| 1356 | "format_version": OUTPUT_META_VERSION, |
| 1357 | "status": "complete", |
| 1358 | "identity": identity, |
| 1359 | "passes": 6, |
| 1360 | "png_files": 4, |
| 1361 | "png_sha256": checksums, |
| 1362 | "atlas": atlas_ref() |
| 1363 | }), |
| 1364 | ); |
| 1365 | assert!(matches!( |
| 1366 | ExportRun::open(&tmp.0), |
| 1367 | Err(ExportError::Traversal(_)) |
| 1368 | )); |
| 1369 | } |
| 1370 | } |
| 1371 | |
| 1372 | #[test] |
| 1373 | fn depth_range_contract_and_old_global_range_schema() { |
| 1374 | let parse = |v: serde_json::Value| -> RenderManifest { serde_json::from_value(v).unwrap() }; |
| 1375 | validate_render(&parse(base_render(4))).unwrap(); |
| 1376 | let mut old = base_render(4); |
| 1377 | old["format_version"] = 4.into(); |
| 1378 | let err = validate_render(&parse(old)).unwrap_err(); |
| 1379 | assert!(matches!(&err, ExportError::Identity(m) if m.contains("globaal dieptebereik"))); |
| 1380 | for (key, value) in [ |
| 1381 | ("near", serde_json::json!(0.05)), |
| 1382 | ("far", serde_json::json!(40.0)), |
| 1383 | ("depth_far", serde_json::json!(12.0)), |
| 1384 | ("depth_encoding", serde_json::json!("other")), |
| 1385 | ("depth_bits", serde_json::json!(12)), |
| 1386 | ("depth_bits", serde_json::Value::Null), |
| 1387 | ] { |
| 1388 | let mut doc = base_render(4); |
| 1389 | doc[key] = value; |
| 1390 | assert!(matches!( |
| 1391 | validate_render(&parse(doc)), |
| 1392 | Err(ExportError::Identity(_)) |
| 1393 | )); |
| 1394 | } |
| 1395 | // Schema 5 (before depth_bits) is still read as 16-bit gray. |
| 1396 | let mut legacy = base_render(4); |
| 1397 | legacy["format_version"] = 5.into(); |
| 1398 | legacy.as_object_mut().unwrap().remove("depth_bits"); |
| 1399 | legacy["depth_encoding"] = crate::camera::DEPTH_ENCODING.into(); |
| 1400 | let m = parse(legacy.clone()); |
| 1401 | validate_render(&m).unwrap(); |
| 1402 | assert_eq!( |
| 1403 | m.depth_format().unwrap(), |
| 1404 | crate::camera::DepthFormat::GRAY16 |
| 1405 | ); |
| 1406 | // ...but schema 5 cannot claim a new encoding. |
| 1407 | legacy["depth_bits"] = 8.into(); |
| 1408 | legacy["depth_encoding"] = "rgb_packed".into(); |
| 1409 | assert!(validate_render(&parse(legacy)).is_err()); |
| 1410 | // Every new encoding/bit combination is accepted in schema 6. |
| 1411 | for bits in [8, 16] { |
| 1412 | for e in ["gray", "rgb_bands", "rgb_packed"] { |
| 1413 | let mut doc = base_render(4); |
| 1414 | doc["depth_bits"] = bits.into(); |
| 1415 | doc["depth_encoding"] = e.into(); |
| 1416 | validate_render(&parse(doc)).unwrap(); |
| 1417 | } |
| 1418 | } |
| 1419 | } |
| 1420 | |
| 1421 | #[test] |
| 1422 | fn rejects_stale_schema_and_identity_drift() { |
| 1423 | let tmp = Temp::new(); |
| 1424 | let checksums = publish_four(&tmp.0); |
| 1425 | let mut render = base_render(4); |
| 1426 | render["format_version"] = serde_json::json!(2); |
| 1427 | write_atomic_json(&tmp.0, "render.json", &render); |
| 1428 | write_atomic_json( |
| 1429 | &tmp.0, |
| 1430 | "complete.json", |
| 1431 | &serde_json::json!({ |
| 1432 | "format_version": OUTPUT_META_VERSION, |
| 1433 | "status": "complete", |
| 1434 | "identity": { |
| 1435 | "project_id": "demo", |
| 1436 | "project_name": "Demo", |
| 1437 | "sex": "male", |
| 1438 | "set": "body", |
| 1439 | "body_model_sha256": digest::sha256_hex(b"body"), |
| 1440 | "equipment_preset_sha256": null, |
| 1441 | "target": [1,1], |
| 1442 | "fps": 12, |
| 1443 | "framing": framing(), |
| 1444 | "pivot_source": {"kind": "manual"}, |
| 1445 | "near": crate::camera::depth_range(framing()).0, |
| 1446 | "far": crate::camera::depth_range(framing()).1, |
| 1447 | "clips": [{"name":"","token":"clip000-bind","frames":1,"duration":0.0}], |
| 1448 | "saved_maps": ["diffuse","depth","normal","specular"] |
| 1449 | }, |
| 1450 | "passes": 6, |
| 1451 | "png_files": 4, |
| 1452 | "png_sha256": checksums, |
| 1453 | "atlas": atlas_ref() |
| 1454 | }), |
| 1455 | ); |
| 1456 | assert!(matches!( |
| 1457 | ExportRun::open(&tmp.0), |
| 1458 | Err(ExportError::Identity(_)) |
| 1459 | )); |
| 1460 | } |
| 1461 | |
| 1462 | #[test] |
| 1463 | fn rejects_bad_normal_and_wrong_depth_type() { |
| 1464 | let tmp = Temp::new(); |
| 1465 | // Broken normal: transparent with non-zero RGB |
| 1466 | write_rgba( |
| 1467 | &tmp.0, |
| 1468 | Path::new("bad_normal.png"), |
| 1469 | &ImageBuf { |
| 1470 | width: 1, |
| 1471 | height: 1, |
| 1472 | rgba: vec![10, 0, 0, 0], |
| 1473 | }, |
| 1474 | ) |
| 1475 | .unwrap(); |
| 1476 | let bytes = fs::read(tmp.0.join("bad_normal.png")).unwrap(); |
| 1477 | assert!(matches!( |
| 1478 | decode_map( |
| 1479 | &bytes, |
| 1480 | MapKind::Normal, |
| 1481 | 1, |
| 1482 | 1, |
| 1483 | crate::camera::DepthFormat::GRAY16 |
| 1484 | ), |
| 1485 | Err(ExportError::Corrupt(_)) |
| 1486 | )); |
| 1487 | // RGBA written as depth should fail color type check |
| 1488 | write_rgba( |
| 1489 | &tmp.0, |
| 1490 | Path::new("fake_depth.png"), |
| 1491 | &ImageBuf { |
| 1492 | width: 1, |
| 1493 | height: 1, |
| 1494 | rgba: vec![0, 0, 0, 255], |
| 1495 | }, |
| 1496 | ) |
| 1497 | .unwrap(); |
| 1498 | let bytes = fs::read(tmp.0.join("fake_depth.png")).unwrap(); |
| 1499 | assert!(matches!( |
| 1500 | decode_map( |
| 1501 | &bytes, |
| 1502 | MapKind::Depth, |
| 1503 | 1, |
| 1504 | 1, |
| 1505 | crate::camera::DepthFormat::GRAY16 |
| 1506 | ), |
| 1507 | Err(ExportError::Corrupt(_)) |
| 1508 | )); |
| 1509 | } |
| 1510 | } |