qbsp 0.14.1

Rust crate for parsing and operating with Quake 1, 2, and GoldSrc BSP files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! [BSPX](https://developer.valvesoftware.com/wiki/BSPX) data definitions.

use std::{collections::HashMap, str::FromStr};

#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use glam::{U16Vec2, UVec3, Vec3};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;

use qbsp_macros::BspValue;

use crate::{
	BspData, BspParseError, BspParseResultDoingJobExt, BspResult, LumpEntry,
	data::{
		BspFace, LightmapOffset,
		lighting::{LightmapStyle, RgbLighting, read_lit},
		nodes::{FloatBoundingBox, ShortBsp29LeafContents},
		texture::PlanarTextureProjection,
		util::{BspVariableArray, FixedStr},
	},
	reader::{BspByteReader, BspParseContext, BspValue},
};

pub const BSPX_ENTRY_NAME_LEN: usize = 24;

#[derive(BspValue, Debug, Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BspxLumpEntry {
	pub name: FixedStr<BSPX_ENTRY_NAME_LEN>,
	pub lump: LumpEntry,
}

#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BspxDirectory {
	pub entries: Vec<BspxLumpEntry>,
}
impl BspValue for BspxDirectory {
	fn bsp_parse(reader: &mut BspByteReader) -> BspResult<Self> {
		match reader.read().and_then(|magic| {
			if &magic != b"BSPX" {
				Err(BspParseError::WrongMagicNumber {
					found: magic,
					expected: "BSPX",
				})
			} else {
				Ok(())
			}
		}) {
			Ok(()) => {}
			Err(BspParseError::BufferOutOfBounds { .. }) => return Err(BspParseError::NoBspxDirectory),
			Err(err) => return Err(err),
		}

		let num_lumps: u32 = reader.read().job("lump count")?;

		let mut entries = Vec::with_capacity(num_lumps as usize);

		for i in 0..num_lumps {
			let entry: BspxLumpEntry = reader.read().job(|| format!("lump entry {i}/{num_lumps}"))?;
			entries.push(entry);
		}

		Ok(Self { entries })
	}
	fn bsp_struct_size(_ctx: &BspParseContext) -> usize {
		unimplemented!("BspxDirectory is of variable size")
	}
}

/// BSPX is a community addition to the BSP format.
/// This struct contains built-in reading and support for commonly used ones.
/// Any lumps it doesn't know how to parse is stored in [`BspxData::unparsed`].
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BspxData {
	pub rgb_lighting: Option<RgbLighting>,
	pub light_grid_octree: Option<LightGridOctree>,
	pub brush_list: Option<BrushList>,
	pub decoupled_lm: Option<DecoupledLightmaps>,
	pub face_normals: Option<FaceNormals>,

	pub unparsed: HashMap<FixedStr<BSPX_ENTRY_NAME_LEN>, Vec<u8>>,
}
impl BspxData {
	pub fn parse(bsp: &[u8], dir: &BspxDirectory, bsp_data: &BspData) -> BspResult<Self> {
		let mut data = Self::default();

		for entry in &dir.entries {
			macro_rules! check_duplicate {
				($lump:ident) => {
					if data.$lump.is_some() {
						return Err(BspParseError::DuplicateBspxLump(entry.name.to_string()));
					}
				};
			}

			let lump = entry.lump.get(bsp)?;

			match entry.name.as_str() {
				// Builtin lumps.
				"RGBLIGHTING" => {
					check_duplicate!(rgb_lighting);
					data.rgb_lighting = Some(read_lit(lump, &bsp_data.parse_ctx, true).job("Parsing RGBLIGHTING BSPX lump")?);
				}
				"LIGHTGRID_OCTREE" => {
					check_duplicate!(light_grid_octree);
					data.light_grid_octree = Some(BspByteReader::new(lump, &bsp_data.parse_ctx).read()?);
				}
				"BRUSHLIST" => {
					check_duplicate!(brush_list);
					data.brush_list = Some(parse_brush_list(BspByteReader::new(lump, &bsp_data.parse_ctx))?);
				}
				"DECOUPLED_LM" => {
					check_duplicate!(decoupled_lm);
					data.decoupled_lm = Some(parse_decoupled_lm(BspByteReader::new(lump, &bsp_data.parse_ctx))?);
				}
				"FACENORMALS" => {
					check_duplicate!(face_normals);
					data.face_normals = Some(FaceNormals::parse(BspByteReader::new(lump, &bsp_data.parse_ctx), &bsp_data.faces)?);
				}

				// Lumps we don't know how to parse.
				_ => {
					data.unparsed.insert(entry.name, lump.to_vec());
				}
			}
		}

		Ok(data)
	}

	/// Retrieves an unparsed lump entry from the unparsed data, returns `None` if the entry does not exist.
	#[inline]
	pub fn get_unparsed(&self, s: &str) -> Option<&[u8]> {
		self.unparsed.get(&FixedStr::from_str(s).ok()?).map(|v| &**v)
	}

	/// Returns whether no BSPX data is stored.
	pub fn is_empty(&self) -> bool {
		self.rgb_lighting.is_none()
			&& self.light_grid_octree.is_none()
			&& self.brush_list.is_none()
			&& self.decoupled_lm.is_none()
			&& self.face_normals.is_none()
			&& self.unparsed.is_empty()
	}

	/// BSPX data must be aligned to 4 bytes, this little helper function handles that.
	#[inline]
	pub fn align_offset(offset: usize) -> usize {
		(offset + 3) & !3
	}
}

/// 3d lighting data stored in an octree. Referenced from the [FTE BSPX specification](https://github.com/fte-team/fteqw/blob/master/specs/bspx.txt) and ericw-tools source code.
#[derive(BspValue, Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LightGridOctree {
	pub step: Vec3,
	pub size: UVec3,
	pub mins: Vec3,
	pub num_styles: u8,
	pub root_idx: u32,
	pub nodes: BspVariableArray<LightGridNode, u32>,
	pub leafs: BspVariableArray<LightGridLeaf, u32>,
}

#[derive(BspValue, Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LightGridNode {
	pub division_point: UVec3,
	pub children: [u32; 8],
}
impl LightGridNode {
	pub const LEAF: u32 = 1 << 31;
	pub const MISSING: u32 = 1 << 30;

	#[rustfmt::skip]
	#[allow(clippy::identity_op)]
	pub fn get_child_index_towards(&self, point: Vec3) -> u32 {
		self.children[
			(((point.z >= self.division_point.z as f32) as usize) << 0) |
			(((point.y >= self.division_point.y as f32) as usize) << 1) |
			(((point.x >= self.division_point.x as f32) as usize) << 2)
		]
	}
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LightGridLeaf {
	pub mins: UVec3,
	size: UVec3,

	data: Vec<LightGridCell>,
}
impl BspValue for LightGridLeaf {
	fn bsp_parse(reader: &mut BspByteReader) -> BspResult<Self> {
		let mins: UVec3 = reader.read().job("position")?;
		let size: UVec3 = reader.read().job("size")?;

		let mut data = Vec::with_capacity(size.element_product() as usize);

		for _ in 0..size.element_product() {
			data.push(reader.read().job("Reading cell")?);
		}

		Ok(Self { mins, size, data })
	}

	fn bsp_struct_size(_ctx: &BspParseContext) -> usize {
		unimplemented!("LightGridLeaf is of variable size")
	}
}
impl LightGridLeaf {
	#[inline]
	pub fn cells(&self) -> &[LightGridCell] {
		&self.data
	}

	/// Returns the index into `data` of the cell at the position specified.
	#[inline]
	pub const fn cell_idx(&self, x: u32, y: u32, z: u32) -> usize {
		((z * self.size.x * self.size.y) + (y * self.size.x) + x) as usize
	}

	/// Returns the cell at the specified position, panics if the position is out of bounds.
	pub fn get_cell(&self, x: u32, y: u32, z: u32) -> &LightGridCell {
		&self.data[self.cell_idx(x, y, z)]
	}
	/// Returns the cell at the specified position, panics if the position is out of bounds.
	pub fn get_cell_mut(&mut self, x: u32, y: u32, z: u32) -> &mut LightGridCell {
		let idx = self.cell_idx(x, y, z);
		&mut self.data[idx]
	}

	#[inline]
	pub const fn size(&self) -> UVec3 {
		self.size
	}
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum LightGridCell {
	/// Cell is filled by geometry.
	Occluded,
	/// Cell is filled,
	Filled(SmallVec<[LightmapCellSample; 4]>),
}
impl BspValue for LightGridCell {
	fn bsp_parse(reader: &mut BspByteReader) -> BspResult<Self> {
		let style_count: u8 = reader.read().job("style count")?;
		if style_count == 255 {
			return Ok(Self::Occluded);
		}

		let mut samples = SmallVec::with_capacity(style_count as usize);
		for _ in 0..style_count {
			samples.push(reader.read().job("cell sample")?);
		}

		Ok(Self::Filled(samples))
	}

	fn bsp_struct_size(_ctx: &BspParseContext) -> usize {
		unimplemented!("LightGridCell is of variable size")
	}
}

#[derive(BspValue, Debug, Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LightmapCellSample {
	pub style: LightmapStyle,
	pub color: [u8; 3],
}

#[derive(BspValue, Debug, Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ModelBrushesIdx {
	pub brush_count: u32,
	/// Total plane count, for validation.
	pub plane_count: u32,
}
impl TryFrom<ModelBrushesIdx> for usize {
	type Error = ();

	fn try_from(value: ModelBrushesIdx) -> Result<Self, Self::Error> {
		Ok(value.brush_count as usize)
	}
}

/// Stores the brushes used to create the map, which non-Quake-2 BSPs don't. This can be useful mainly for collision.
pub type BrushList = Vec<ModelBrushes>;

/// Parses the `BRUSHLIST` lump. See [`BrushList`] documentation for more info on it.
///
/// This is a loose function because [`BrushList`] is a type alias.
pub fn parse_brush_list(mut reader: BspByteReader) -> BspResult<BrushList> {
	let mut brush_list = BrushList::new();

	let mut i: usize = 0;
	while reader.in_bounds() {
		let brushes = reader.read().job(|| format!("Parsing BRUSHLIST BSPX lump element {i}"))?;

		brush_list.push(brushes);
		i += 1;
	}

	Ok(brush_list)
}

/// Per-model brush information stored in the `BRUSHLIST` BSPX lump.
#[derive(BspValue, Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ModelBrushes {
	/// Should be `1`.
	pub version: u32,
	pub model_idx: u32,
	pub brushes: BspVariableArray<ModelBrush, ModelBrushesIdx>,
}

#[derive(BspValue, Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ModelBrush {
	pub bound: FloatBoundingBox,
	pub contents: ShortBsp29LeafContents,
	/// Non-axial faces only. It's on you to add axial planes via the bounding box.
	pub planes: BspVariableArray<ModelBrushPlane, u16>,
}

#[derive(BspValue, Debug, Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ModelBrushPlane {
	pub normal: Vec3,
	pub dist: f32,
}

/// For the `DECOUPLED_LM` BSPX lump. Stores lightmap sizes and axes separately to textures. This vector is per-surface.
pub type DecoupledLightmaps = Vec<DecoupledLightmap>;

/// Parses the `DECOUPLED_LM` lump. See [`DecoupledLightmaps`] documentation for more info on it.
///
/// This is a loose function because [`DecoupledLightmaps`] is a type alias.
pub fn parse_decoupled_lm(mut reader: BspByteReader) -> BspResult<DecoupledLightmaps> {
	let entries_count = reader.len() / DecoupledLightmap::bsp_struct_size(reader.ctx);
	let mut lm_infos = DecoupledLightmaps::with_capacity(entries_count);

	for i in 0..entries_count {
		let mut lm_info: DecoupledLightmap = reader.read().job(|| format!("Parsing DECOUPLED_LM BSPX lump element {i}"))?;

		// This is done in FTE quake's source code, each with a comment saying "sigh" after, not sure why.
		lm_info.projection.u_offset += 0.5;
		lm_info.projection.v_offset += 0.5;

		lm_infos.push(lm_info);
	}

	Ok(lm_infos)
}

#[derive(BspValue, Debug, Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DecoupledLightmap {
	pub size: U16Vec2,
	/// Offset into the lighting lump, or -1
	pub offset: LightmapOffset,

	pub projection: PlanarTextureProjection,
}

/// Stores per-face-corner normals, tangents, and bi-tangents.
///
/// Per-ericw-tools documentation:
/// "For maps using `_phong`, this allows in-engine dynamic lights to render with the same smooth/sharp edges that the baked lighting uses."
#[derive(Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FaceNormals {
	/// Many, if not most brush faces are cardinally aligned. Because of this, the `FACENORMALS` lump only stores unique vectors.
	/// Face vertices store indexes into this, cutting the size of each from 36 bytes to 12.
	pub unique_vecs: Vec<Vec3>,
	/// The normal indexes of every face corner stored in a continuous buffer that `faces` indexes into.
	pub face_vertices: Vec<FaceNormalVertex>,
	/// Corresponds to the [`BspData::faces`](qbsp::BspData::faces) vector, each one indexing into `face_vertices`.
	pub faces: Vec<FaceNormalFace>,
}
impl FaceNormals {
	/// Parses [`FaceNormals`] from a BSP file. The `faces` parameter should be provided with [`BspData::faces`](qbsp::BspData::faces).
	pub fn parse(mut reader: BspByteReader, faces: &[BspFace]) -> BspResult<Self> {
		let unique_vecs = reader.read::<BspVariableArray<Vec3, u32>>()?.inner;

		let mut face_vertices: Vec<FaceNormalVertex> = Vec::with_capacity(faces.iter().map(|face| face.num_edges.0 as usize).sum::<usize>());
		let mut face_mappings: Vec<FaceNormalFace> = Vec::with_capacity(faces.len());

		for face in faces {
			face_mappings.push(FaceNormalFace {
				vertex_start: face_vertices.len() as u32,
				vertex_count: face.num_edges.0,
			});

			for _ in 0..face.num_edges.0 {
				face_vertices.push(reader.read()?);
			}
		}

		Ok(Self {
			unique_vecs,
			face_vertices,
			faces: face_mappings,
		})
	}
}

/// Contains a range to index into [`FaceNormals::face_vertices`].
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FaceNormalFace {
	pub vertex_start: u32,
	pub vertex_count: u32,
}

/// Indexes into [`FaceNormals::unique_vecs`].
#[derive(BspValue, Debug, Clone, Copy)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FaceNormalVertex {
	pub normal_idx: u32,
	pub tangent_idx: u32,
	pub bi_tangent_idx: u32,
}