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
//! Lights: each point, spot and rectangle light's description and its
//! record in the scene's light buffer, which group 0 binds, with the `Scene`
//! operations that add, read, change and remove them. A removed light's
//! record stays until its index is reused, or until the render origin moves
//! while a light of a higher index lives, which zeroes it; no view lists it.
//!
//! A spot's cookie is an image in the decal atlas (`decals`): a cookied
//! light uses its image as a decal does, so the atlas packs it, and its
//! record names the image's place in the layout the next upload binds, as
//! a decal's does; an upload that packs the atlas anew rewrites every
//! cookied light's record with the decals' (`Scene::upload_decals`).
use super::decal_atlas::Sampling;
use super::slots::Slots;
use super::{Scene, SceneError};
use crate::content::identity::{Identity, LightId};
use crate::content::light::{Light, LightShape};
use crate::shading::lights::LightRecord;
const RECORD: u64 = std::mem::size_of::<LightRecord>() as u64;
pub(crate) struct Lights {
pub slots: Slots<LightId, Light>,
buffer: wgpu::Buffer,
/// How many of `slots` are rectangles.
rects: usize,
/// How many of `slots` project a cookie.
cookies: usize,
}
impl Lights {
/// Room for one record.
pub fn new(device: &wgpu::Device) -> Self {
Self {
slots: Slots::default(),
buffer: light_buffer(device, 1),
rects: 0,
cookies: 0,
}
}
/// The records, as group 0 binds them.
pub fn buffer(&self) -> &wgpu::Buffer {
&self.buffer
}
/// The records the buffer holds: more than any light's index.
pub fn capacity(&self) -> usize {
(self.buffer.size() / RECORD) as usize
}
/// Whether the scene holds a rectangle light: the lit pipelines shade
/// rectangles only while it does.
pub fn holds_rect(&self) -> bool {
self.rects > 0
}
/// Whether the scene holds a cookied light: the lit pipelines sample
/// cookies only while it does.
pub fn holds_cookie(&self) -> bool {
self.cookies > 0
}
/// The decal atlas's images the lights project, other than `except`'s,
/// as the atlas packs them (`Scene::place_atlas`).
pub fn cookie_keys(
&self,
except: Option<LightId>,
) -> impl Iterator<Item = super::decal_atlas::AtlasKey> + '_ {
self.slots
.iter()
.filter(move |(id, _)| Some(*id) != except)
.filter_map(|(_, light)| cookie_key(light))
}
pub fn get(&self, id: LightId) -> Result<&Light, SceneError> {
self.slots.get(id).ok_or(SceneError::UnknownLight)
}
/// The lights that are on, with some intensity and colour, in index
/// order: the ones every view lists and that may cast a shadow.
pub fn on(&self) -> impl Iterator<Item = (LightId, &Light)> {
self.slots
.iter()
.filter(|(_, light)| light.intensity > 0. && light.color.iter().any(|&c| c > 0.))
}
/// Writes `light`'s record at `index`, its cookie at the place
/// `cookie_rect` gives (`Decals::cookie_rect`).
fn write(
&self,
queue: &wgpu::Queue,
index: usize,
light: &Light,
cookie_rect: &impl Fn(&Light) -> [f32; 4],
) {
crate::counters::write_buffer(
queue,
&self.buffer,
index as u64 * RECORD,
bytemuck::bytes_of(&LightRecord::new(light, cookie_rect(light))),
);
}
/// Rewrites every cookied light's record, its cookie at the place
/// `cookie_rect` gives: after the atlas is packed anew.
pub fn write_cookied(&self, queue: &wgpu::Queue, cookie_rect: &impl Fn(&Light) -> [f32; 4]) {
for (id, light) in self.slots.iter() {
if light.cookie.is_some() {
self.write(queue, id.index(), light, cookie_rect);
}
}
}
/// Room for `count` records, rewriting every record when the buffer is
/// replaced; returns whether it was.
fn reserve(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
count: usize,
cookie_rect: &impl Fn(&Light) -> [f32; 4],
) -> Result<bool, SceneError> {
let capacity = self.buffer.size() / RECORD;
if count as u64 <= capacity {
return Ok(false);
}
let limits = device.limits();
let limit = limits
.max_storage_buffer_binding_size
.min(limits.max_buffer_size)
/ RECORD;
if count as u64 > limit {
return Err(SceneError::DeviceLimit);
}
self.buffer = light_buffer(device, (count as u64).max(capacity * 2).min(limit));
for (id, light) in self.slots.iter() {
self.write(queue, id.index(), light, cookie_rect);
}
Ok(true)
}
}
impl Lights {
/// Moves the render origin by `by` (`Scene::move_origin`): each light's
/// position, and every record in one write, as `Objects::write_all`
/// writes the instances', rather than one write a light. The write
/// zeroes the records of removed indices below the highest live one,
/// which no view lists.
pub fn move_origin(
&mut self,
queue: &wgpu::Queue,
by: glam::Vec3,
cookie_rect: &impl Fn(&Light) -> [f32; 4],
) {
let mut records = Vec::new();
for (id, light) in self.slots.iter_mut() {
light.position -= by;
if records.len() <= id.index() {
records.resize(id.index() + 1, bytemuck::Zeroable::zeroed());
}
records[id.index()] = LightRecord::new(light, cookie_rect(light));
}
if !records.is_empty() {
crate::counters::write_buffer(queue, &self.buffer, 0, bytemuck::cast_slice(&records));
}
}
}
fn light_buffer(device: &wgpu::Device, records: u64) -> wgpu::Buffer {
crate::counters::buffer(
device,
&wgpu::BufferDescriptor {
label: Some("scene lights"),
size: records * RECORD,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
},
)
}
fn is_rect(light: &Light) -> bool {
matches!(light.shape, LightShape::Rect { .. })
}
/// The decal atlas's image `light` projects, sampled as colour.
pub(crate) fn cookie_key(light: &Light) -> Option<super::decal_atlas::AtlasKey> {
light.cookie.map(|cookie| (cookie.image, Sampling::Color))
}
/// A cookie a record can hold: one with a frame (`cookie_frame`), on a
/// spot of a positive outer angle with an `up` that has a finite part
/// across the spot's direction.
fn valid_cookie(light: &Light) -> bool {
light
.cookie
.is_none_or(|cookie| crate::shading::lights::cookie_frame(&cookie, &light.shape).is_some())
}
/// Each light's cookie's place in the layout `decals`' records name
/// (`Decals::cookie_rect`), for the record writers.
pub(crate) fn cookie_rects(decals: &super::decals::Decals) -> impl Fn(&Light) -> [f32; 4] + '_ {
move |light| decals.cookie_rect(cookie_key(light))
}
/// A light a record can hold: finite, nonnegative colour, intensity,
/// specular scale and fog energy, a shadow opacity in 0..=1, a positive
/// range, a spot's nonzero direction and ordered angles below a right angle
/// (Bevy's limit), a rectangle's nonzero direction, a width axis not
/// parallel to it, and a positive size, and a cookie only on a spot
/// (`valid_cookie`).
fn validate(light: &Light) -> Result<(), SceneError> {
let nonnegative = |value: f32| value.is_finite() && value >= 0.;
let valid = light.position.is_finite()
&& light.color.iter().all(|&channel| nonnegative(channel))
&& nonnegative(light.intensity)
&& nonnegative(light.specular)
&& nonnegative(light.fog_energy)
&& (0.0..=1.).contains(&light.shadow_opacity)
&& light.range.is_finite()
&& light.range > 0.
&& match light.shape {
LightShape::Point { radius } => radius.is_finite() && radius >= 0.,
LightShape::Spot {
direction,
inner_angle,
outer_angle,
radius,
} => {
radius.is_finite()
&& radius >= 0.
&& direction.is_finite()
&& direction.length_squared() > 0.
&& direction.normalize().is_finite()
&& inner_angle >= 0.
&& inner_angle <= outer_angle
&& outer_angle < std::f32::consts::FRAC_PI_2
}
LightShape::Rect {
direction,
width_axis,
width,
height,
} => {
let normal = direction.normalize();
normal.is_finite()
&& width_axis.is_finite()
&& width_axis
.reject_from_normalized(normal)
.normalize()
.is_finite()
&& width.is_finite()
&& width > 0.
&& height.is_finite()
&& height > 0.
&& (light.intensity / (width * height)).is_finite()
}
}
&& valid_cookie(light);
if valid {
Ok(())
} else {
Err(SceneError::InvalidLight)
}
}
impl Scene {
/// `light` is valid and its cookie's image is in the scene, and the
/// decal atlas's layout that it needs, if the atlas lacks its cookie,
/// beside the images the decals and the lights other than `replacing`
/// use.
fn light_layout(
&self,
light: &Light,
replacing: Option<LightId>,
) -> Result<Option<super::decal_atlas::AtlasLayout>, SceneError> {
validate(light)?;
let adding: Vec<_> = cookie_key(light).into_iter().collect();
self.decals.validate_images(&adding)?;
self.place_atlas(&adding, None, replacing)
}
/// Counts `light` among the lights, once more or once less.
fn count_light(&mut self, light: &Light, more: bool) {
let count = |counter: &mut usize, counted: bool| {
if counted && more {
*counter += 1;
} else if counted {
*counter -= 1;
}
};
count(&mut self.lights.rects, is_rect(light));
count(&mut self.lights.cookies, light.cookie.is_some());
if let Some(cookie) = light.cookie {
self.decals.count_image(cookie.image, more);
}
}
/// Adds a point, spot or rectangle light. One whose cookie the decal
/// atlas lacks packs the atlas anew before the next frame.
pub fn add_light(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
light: Light,
) -> Result<LightId, SceneError> {
self.edited();
let layout = self.light_layout(&light, None)?;
let count = self.lights.slots.next_index() + 1;
let decals = &self.decals;
if self
.lights
.reserve(device, queue, count, &cookie_rects(decals))?
{
self.resources = super::next_generation();
}
self.decals.repack(layout);
let id = self.lights.slots.insert(light);
self.count_light(&light, true);
let decals = &self.decals;
self.lights
.write(queue, id.index(), &light, &cookie_rects(decals));
Ok(id)
}
/// A light's current description.
pub fn light(&self, id: LightId) -> Result<&Light, SceneError> {
self.lights.get(id)
}
/// Replaces a light's description. One whose cookie the decal atlas
/// lacks packs the atlas anew before the next frame.
pub fn set_light(
&mut self,
queue: &wgpu::Queue,
id: LightId,
light: Light,
) -> Result<(), SceneError> {
let old = *self.lights.get(id)?;
if old != light {
self.edited();
}
let layout = self.light_layout(&light, Some(id))?;
self.decals.repack(layout);
self.count_light(&old, false);
self.count_light(&light, true);
*self.lights.slots.get_mut(id).unwrap() = light;
let decals = &self.decals;
self.lights
.write(queue, id.index(), &light, &cookie_rects(decals));
Ok(())
}
/// Removes a light. Its index is reused under a new identity.
pub fn remove_light(&mut self, id: LightId) -> Result<(), SceneError> {
self.edited();
let light = self
.lights
.slots
.remove(id)
.ok_or(SceneError::UnknownLight)?;
self.count_light(&light, false);
Ok(())
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;