Skip to main content

mln_engine/draw/
context.rs

1//! What the renderer keeps over its backend's `Gpu`: its caps, the caches
2//! its draws share, among them the keys of the programs' variants, the
3//! stores of the textures, indexes and vertices they share, the buffers
4//! every draw binds, and the device that makes its
5//! buffers and textures, with the rendering stats and the queue of what it
6//! dropped. The renderer owns it, and lends it
7//! to a frame's encode, which changes it through `&mut`. The context holds
8//! no `Gpu`: each call that makes, writes or destroys a resource takes the
9//! one the renderer was made for.
10
11use std::rc::Rc;
12
13use mln_gfx::Size;
14use mln_gfx::gfx_types::AttributeDataType;
15use mln_gfx::gpu::{
16    BufferId, BufferUsage, Caps, Gpu, GpuError, PipelineId, PipelineKey, ResourceId, SamplerId, ShaderId, ShaderKey,
17    TextureFormat, TextureId,
18};
19use mln_gfx::projection_variant::ProjectionVariant;
20use mln_gfx::rendering_stats::RenderingStats;
21use mln_gfx::shaders::program::Program;
22use mln_gfx::shaders::program_parameters::ProgramParameters;
23use mln_gfx::texture2d::SamplerState;
24use mln_gfx::types::TextureChannelDataType;
25use mln_style::hash::HashMap;
26
27use crate::draw::after_gpu::AfterGpuQueue;
28use crate::draw::buffer::{self, Buffer};
29use crate::draw::indexes::{Indexes, SharedIndexes};
30use crate::draw::objects::{DrawObjects, Mesh};
31use crate::draw::owned::{Held, Owned};
32use crate::draw::release::{Release, destroy_order};
33use crate::draw::resources::{Device, SharedGpuTexture};
34use crate::draw::store::{
35    IndexesKey, MeshKey, Shared, SharedTexture, Store, StoreKey, TargetKey, TextureKey, WeakShared,
36};
37use crate::draw::target::{Target, TargetObjects};
38use crate::draw::texture2d::{Texture2D, TextureMut};
39use crate::draw::uniform_buffer::UniformBufferArray;
40use crate::draw::vertex_attribute::Uniforms;
41use crate::draw::vertices::{SharedVertices, TypedVertices, VertexStore, Vertices};
42use crate::log_target;
43
44/// What the renderer draws with: its device, and the stores of the
45/// textures, vertices, indexes, meshes and targets that draws share, which
46/// the GPU objects of each are made from and released with.
47pub struct Context {
48    device: Device,
49    caps: Caps,
50    global_uniform_buffers: UniformBufferArray,
51    /// The sampler of each state a texture is sampled with.
52    samplers: HashMap<SamplerState, SamplerId>,
53    /// What the programs are compiled with: the pixel ratio's defines.
54    program_parameters: ProgramParameters,
55    /// The key of each variant a draw used, by program, the properties of
56    /// the program it reads from uniforms, a bit by index, and projection.
57    shader_keys: HashMap<(&'static Program, u16, ProjectionVariant), ShaderKey>,
58    /// The shader of each key a draw used.
59    shaders: HashMap<ShaderKey, ShaderId>,
60    /// The pipeline of each key a draw used.
61    pipelines: HashMap<PipelineKey, PipelineId>,
62    /// The buffers of default attribute values, one per format, with the
63    /// vertex count each covers.
64    default_vertex_buffers: HashMap<AttributeDataType, (usize, Rc<Buffer>)>,
65    /// The renderer's textures, which their owners and the draws that bind
66    /// them hold as [`SharedTexture`]s.
67    textures: Store<TextureKey, Texture2D>,
68    /// The indexes that draws share, which they hold as [`SharedIndexes`].
69    indexes: Store<IndexesKey, Indexes>,
70    /// [`quad_indexes`](Self::quad_indexes), while a draw holds them.
71    quad_indexes: WeakShared<IndexesKey>,
72    /// The meshes, which their layers and the draws of them hold as
73    /// [`Mesh`]es; `None` while one draws or uploads.
74    meshes: Store<MeshKey, Option<Box<DrawObjects>>>,
75    /// The layers' render targets, which they hold as [`Target`]s.
76    targets: Store<TargetKey, TargetObjects>,
77    /// The targets whose draws the frame wrote, until it ends
78    /// ([`end_targets`](Self::end_targets)).
79    frame_targets: Vec<Target>,
80    /// The vertices that draws share, which they hold as [`SharedVertices`].
81    vertices: VertexStore,
82    /// What a [`destroy_released`](Self::destroy_released) takes from the
83    /// queue, and what it destroys, kept for their storage.
84    releases: Vec<Release>,
85    doomed: Vec<ResourceId>,
86    /// Whether [`tear_down`](Self::tear_down) destroyed what the context
87    /// made.
88    torn_down: bool,
89    /// The work that waits for the GPU, which [`Lent`](crate::draw::Lent)
90    /// gives layers a handle to.
91    after_gpu: AfterGpuQueue,
92}
93
94impl Context {
95    /// The renderer's state over a `Gpu` of `caps`, for draws at
96    /// `pixel_ratio` device pixels per logical pixel.
97    #[must_use]
98    pub fn new(caps: Caps, pixel_ratio: f32) -> Context {
99        Context {
100            device: Device::default(),
101            caps,
102            global_uniform_buffers: UniformBufferArray::default(),
103            samplers: HashMap::default(),
104            program_parameters: ProgramParameters::new(pixel_ratio),
105            shader_keys: HashMap::default(),
106            shaders: HashMap::default(),
107            pipelines: HashMap::default(),
108            default_vertex_buffers: HashMap::default(),
109            textures: Store::default(),
110            indexes: Store::default(),
111            quad_indexes: WeakShared::default(),
112            meshes: Store::default(),
113            targets: Store::default(),
114            frame_targets: Vec::new(),
115            vertices: VertexStore::default(),
116            releases: Vec::new(),
117            doomed: Vec::new(),
118            torn_down: false,
119            after_gpu: AfterGpuQueue::new(),
120        }
121    }
122
123    /// The work that waits for the GPU.
124    pub(crate) fn after_gpu(&self) -> &AfterGpuQueue {
125        &self.after_gpu
126    }
127
128    /// What the renderer makes its buffers and textures with.
129    pub(crate) fn device(&mut self) -> &mut Device {
130        &mut self.device
131    }
132
133    /// What the backend's device allows, and how the renderer draws on it.
134    #[must_use]
135    pub fn caps(&self) -> &Caps {
136        &self.caps
137    }
138
139    /// The channel type of a render target's color texture, which draws
140    /// draw into and then sample, for one asked for of `type_`: unsigned
141    /// bytes for half floats where the `Gpu` can't draw into them.
142    pub(crate) fn render_target_type(&self, type_: TextureChannelDataType) -> TextureChannelDataType {
143        if type_ == TextureChannelDataType::HalfFloat && !self.caps.half_float_render_targets {
144            TextureChannelDataType::UnsignedByte
145        } else {
146            type_
147        }
148    }
149
150    /// The format of a render target's depth texture, `None` for render
151    /// targets without one, where every depth test passes.
152    pub(crate) fn render_target_depth(&self) -> Option<TextureFormat> {
153        self.caps.render_target_depth
154    }
155
156    /// Bindings or geometry `id` of the context's `Gpu`, made of `held`,
157    /// which the context destroys once the returned value drops, before
158    /// what they were made of.
159    pub(crate) fn own<T: Copy + Into<ResourceId>>(&self, id: T, held: Vec<Held>) -> Owned<T> {
160        Owned::new(id, held, &self.device.queue)
161    }
162
163    /// The rendering stats, to count what the renderer makes and does.
164    pub fn rendering_stats(&mut self) -> &mut RenderingStats {
165        &mut self.device.stats
166    }
167
168    /// Logs `message`, why something of the frame being encoded failed on
169    /// the GPU, and keeps it as the frame's failure unless one came first
170    /// (`Device::fail`).
171    pub fn fail(&mut self, message: String) {
172        self.device.fail(message);
173    }
174
175    /// The rendering stats now. What the renderer released counts until the
176    /// next [`destroy_released`](Self::destroy_released) destroys it.
177    pub(crate) fn stats(&self) -> RenderingStats {
178        self.device.stats.clone()
179    }
180
181    /// Destroys the resources the renderer dropped, first taking the store
182    /// entries whose last handles dropped out of their stores, and the
183    /// buffers and textures out of the rendering stats. Bindings and
184    /// geometry go before the buffers and textures they were made of. What
185    /// dropped keeps its GPU memory until then. Not while a pass is open on
186    /// `gpu`.
187    pub(crate) fn destroy_released(&mut self, gpu: &mut dyn Gpu) {
188        let Context { device, textures, indexes, vertices, meshes, targets, releases, doomed, .. } = self;
189        loop {
190            device.queue.take_into(releases);
191            if releases.is_empty() {
192                break;
193            }
194            for release in releases.drain(..) {
195                match release {
196                    Release::Resource(resource) => doomed.push(resource),
197                    Release::Entry(StoreKey::Texture(key)) => drop(textures.remove(key)),
198                    Release::Entry(StoreKey::Indexes(key)) => drop(indexes.remove(key)),
199                    Release::Entry(StoreKey::Vertices(key)) => drop(vertices.remove(key)),
200                    Release::Entry(StoreKey::Mesh(key)) => drop(meshes.remove(key)),
201                    Release::Entry(StoreKey::Target(key)) => drop(targets.remove(key)),
202                    Release::Buffer(id, usage, allocated) => {
203                        buffer::count(&mut device.stats, usage, allocated, -1);
204                        doomed.push(id.into());
205                    }
206                    Release::Texture(id, bytes) => {
207                        device.stats.num_active_textures -= 1;
208                        device.stats.mem_textures -= bytes as i32;
209                        doomed.push(id.into());
210                    }
211                }
212            }
213        }
214        if doomed.is_empty() {
215            return;
216        }
217        doomed.sort_unstable_by_key(destroy_order);
218        for resource in doomed.drain(..) {
219            if let Err(error) = gpu.destroy(resource) {
220                log::error!(target: log_target::RENDER, "Destroying {resource:?} failed: {error}");
221                debug_assert!(false, "destroying {resource:?} failed: {error}");
222            }
223        }
224    }
225
226    /// Keeps `indexes` for the draws that share them, while a clone of the
227    /// returned handle lasts.
228    pub fn add_indexes(&mut self, indexes: Indexes) -> SharedIndexes {
229        self.indexes.add(indexes, &self.device.queue)
230    }
231
232    /// Keeps the objects that `make` makes, given the handle of their
233    /// entry, while a clone of the returned handle lasts.
234    pub(crate) fn add_mesh_with(&mut self, make: impl FnOnce(&Shared<MeshKey>) -> DrawObjects) -> Shared<MeshKey> {
235        let key = self.meshes.add(None, &self.device.queue);
236        let objects = make(&key);
237        if let Some(slot) = self.meshes.get_mut(&key) {
238            *slot = Some(Box::new(objects));
239        }
240        key
241    }
242
243    /// The objects of `mesh`.
244    #[must_use]
245    pub(crate) fn mesh(&self, mesh: &Mesh) -> Option<&DrawObjects> {
246        self.meshes.get(mesh.key())?.as_deref()
247    }
248
249    /// The objects of `mesh`, to change.
250    pub(crate) fn mesh_mut(&mut self, mesh: &Mesh) -> Option<&mut DrawObjects> {
251        self.meshes.get_mut(mesh.key())?.as_deref_mut()
252    }
253
254    /// Takes out the objects of `mesh`, to draw or upload them with the
255    /// context, until [`put_mesh`](Self::put_mesh) puts them back.
256    pub(crate) fn take_mesh(&mut self, mesh: &Mesh) -> Option<Box<DrawObjects>> {
257        self.meshes.get_mut(mesh.key())?.take()
258    }
259
260    /// Puts back the objects of `mesh` that [`take_mesh`](Self::take_mesh)
261    /// took out.
262    pub(crate) fn put_mesh(&mut self, mesh: &Mesh, objects: Box<DrawObjects>) {
263        if let Some(slot) = self.meshes.get_mut(mesh.key()) {
264            *slot = Some(objects);
265        }
266    }
267
268    /// Keeps `objects` of a render target, while a clone of the returned
269    /// handle lasts.
270    pub(crate) fn add_target(&mut self, objects: TargetObjects) -> Shared<TargetKey> {
271        self.targets.add(objects, &self.device.queue)
272    }
273
274    /// What the context keeps of `target`.
275    pub(crate) fn target(&self, target: &Target) -> Option<&TargetObjects> {
276        self.targets.get(target.key())
277    }
278
279    /// What the context keeps of `target`, to change.
280    pub(crate) fn target_mut(&mut self, target: &Target) -> Option<&mut TargetObjects> {
281        self.targets.get_mut(target.key())
282    }
283
284    /// Records that the frame wrote the draws into `target`, which holds
285    /// what they draw from now on, unless the frame doesn't draw them
286    /// ([`end_targets`](Self::end_targets)).
287    pub(crate) fn declare_target(&mut self, target: &Target) {
288        if let Some(objects) = self.targets.get_mut(target.key()) {
289            objects.declare();
290            self.frame_targets.push(target.clone());
291        }
292    }
293
294    /// Ends the frame's draws into the targets it wrote them for: a target
295    /// that the frame drew holds what it drew if `submitted`, the frame's
296    /// work reached the GPU, and one that it didn't draw holds nothing.
297    pub(crate) fn end_targets(&mut self, submitted: bool) {
298        for target in self.frame_targets.drain(..) {
299            if let Some(objects) = self.targets.get_mut(target.key()) {
300                objects.end(submitted);
301            }
302        }
303    }
304
305    /// The indexes of quads four vertices apart, two triangles each, which
306    /// the draws that draw such quads share: they stay in the store while a
307    /// draw holds them.
308    pub fn quad_indexes(&mut self) -> SharedIndexes {
309        let held = self.quad_indexes.upgrade();
310        let indexes = held.unwrap_or_else(|| {
311            self.add_indexes(Indexes::new(crate::render::static_data::RenderStaticData::quads_indices()))
312        });
313        self.quad_indexes = indexes.downgrade();
314        indexes
315    }
316
317    /// The indexes of `handle`.
318    pub(crate) fn indexes(&self, handle: &SharedIndexes) -> Option<&Indexes> {
319        self.indexes.get(handle)
320    }
321
322    /// Writes the indexes of `handle` to a buffer, unless they have one.
323    pub(crate) fn upload_indexes(&mut self, gpu: &mut dyn Gpu, handle: &SharedIndexes) -> Result<(), GpuError> {
324        let Context { device, indexes, .. } = self;
325        indexes.get_mut(handle).ok_or(GpuError::UnknownId("indexes"))?.upload(gpu, device)
326    }
327
328    /// Keeps `vertices` for the draws that share them, while a clone of the
329    /// returned handle lasts.
330    pub fn add_vertices<V: bytemuck::Pod>(&mut self, vertices: Vec<V>) -> SharedVertices {
331        self.vertices.add(vertices, &self.device.queue)
332    }
333
334    /// Keeps a copy of `vertices`, as [`add_vertices`](Self::add_vertices)
335    /// does, as dynamic vertices, which the holder of the returned handle
336    /// updates ([`update_vertices`](Self::update_vertices)), and whose
337    /// storage stays across uploads for the next update to fill.
338    pub fn add_dynamic_vertices<V: bytemuck::Pod>(&mut self, vertices: &[V]) -> TypedVertices<V> {
339        self.vertices.add_dynamic(vertices, &self.device.queue)
340    }
341
342    /// Keeps the vertices of the type `V` in the JS array `bytes`, as
343    /// [`add_vertices`](Self::add_vertices) does.
344    #[cfg(target_family = "wasm")]
345    pub(crate) fn add_host_vertices<V: bytemuck::Pod>(
346        &mut self,
347        bytes: mln_wire::host_bytes::HostBytes,
348    ) -> SharedVertices {
349        self.vertices.add_host::<V>(bytes, &self.device.queue)
350    }
351
352    /// The vertices of `shared`.
353    #[must_use]
354    pub fn vertices(&self, shared: &SharedVertices) -> Option<&Vertices> {
355        self.vertices.get(shared)
356    }
357
358    /// Whether the store has the vertices `key`.
359    #[cfg(test)]
360    pub(crate) fn has_vertices(&self, key: crate::draw::store::VerticesKey) -> bool {
361        self.vertices.contains(key)
362    }
363
364    /// Replaces the vertices of `typed` with a copy of `data`, as many, which
365    /// the next upload writes over their buffer's. Returns false, leaving
366    /// them be, for another number of vertices.
367    pub fn update_vertices<V: bytemuck::Pod>(&mut self, typed: &TypedVertices<V>, data: &[V]) -> bool {
368        self.vertices.update(typed, data)
369    }
370
371    /// The buffer of the vertices of `shared`, made of them by their first
372    /// upload and written over after an update, as `Vertices::upload`
373    /// says.
374    pub fn upload_vertices(
375        &mut self,
376        gpu: &mut dyn Gpu,
377        shared: &SharedVertices,
378    ) -> Result<Option<BufferId>, GpuError> {
379        self.vertices.upload(gpu, &mut self.device, shared)
380    }
381
382    /// A texture without a size, made by its first upload or
383    /// `create_texture`, which the context keeps
384    /// while a clone of the returned handle lasts.
385    pub fn add_texture(&mut self) -> SharedTexture {
386        self.add_texture_with(|_| {})
387    }
388
389    /// A texture that `setup` sets up, as [`add_texture`](Self::add_texture)
390    /// makes it.
391    pub fn add_texture_with(&mut self, setup: impl FnOnce(&mut TextureMut<'_>)) -> SharedTexture {
392        let mut texture = Texture2D::new();
393        setup(&mut TextureMut::new(&mut texture));
394        self.textures.add(texture, &self.device.queue)
395    }
396
397    /// The texture of `handle`.
398    #[must_use]
399    pub fn texture(&self, handle: &SharedTexture) -> Option<&Texture2D> {
400        self.textures.get(handle)
401    }
402
403    /// The texture of `handle`, to set up.
404    pub fn texture_mut(&mut self, handle: &SharedTexture) -> Option<TextureMut<'_>> {
405        Some(TextureMut::new(self.textures.get_mut(handle)?))
406    }
407
408    /// The texture of `handle` and what changes it, or the error of a handle
409    /// without one.
410    fn texture_entry(&mut self, handle: &SharedTexture) -> Result<(&mut Texture2D, &mut Device), GpuError> {
411        let Context { device, textures, .. } = self;
412        Ok((textures.get_mut(handle).ok_or(GpuError::UnknownId("texture"))?, device))
413    }
414
415    /// Makes the backend's texture of `handle`'s size and format, unless it
416    /// is made. Fails for an empty size.
417    pub(crate) fn create_texture(&mut self, gpu: &mut dyn Gpu, handle: &SharedTexture) -> Result<TextureId, GpuError> {
418        let (texture, device) = self.texture_entry(handle)?;
419        texture.create(gpu, device)
420    }
421
422    /// Writes `data`, the texels of a texture of `size` in rows from the top,
423    /// to the whole texture of `handle`, first making it of that size. Empty
424    /// `data` leaves the texels unspecified, and an empty size makes no
425    /// texture.
426    pub fn upload_texture_data(
427        &mut self,
428        gpu: &mut dyn Gpu,
429        handle: &SharedTexture,
430        data: &[u8],
431        size: Size,
432    ) -> Result<(), GpuError> {
433        let (texture, device) = self.texture_entry(handle)?;
434        texture.upload_data(gpu, device, data, size)
435    }
436
437    /// Writes `data`, the texels of a region of `size` in rows from the top,
438    /// at `x`, `y` of the texture of `handle`, first making it.
439    pub(crate) fn upload_texture_region(
440        &mut self,
441        gpu: &mut dyn Gpu,
442        handle: &SharedTexture,
443        data: &[u8],
444        size: Size,
445        x: u16,
446        y: u16,
447    ) -> Result<(), GpuError> {
448        let (texture, device) = self.texture_entry(handle)?;
449        texture.upload_sub_region(gpu, device, data, size, x, y)
450    }
451
452    /// Fills the mip levels below the first of the texture of `handle`,
453    /// which is made mipmapped, from what the work recorded so far leaves in
454    /// the first. Fails while a pass is open and for a texture not made.
455    pub(crate) fn generate_mipmaps(&mut self, gpu: &mut dyn Gpu, handle: &SharedTexture) -> Result<(), GpuError> {
456        let texture = self.gpu_texture(handle).ok_or(GpuError::UnknownId("texture"))?;
457        gpu.generate_mipmaps(texture.id())
458    }
459
460    /// Writes the image the texture of `handle` was given, if any.
461    pub(crate) fn upload_texture(&mut self, gpu: &mut dyn Gpu, handle: &SharedTexture) -> Result<(), GpuError> {
462        let (texture, device) = self.texture_entry(handle)?;
463        if !texture.has_image() {
464            return Ok(());
465        }
466        texture.upload(gpu, device)
467    }
468
469    /// What a draw binds of the texture of `handle`, through `gpu`: the
470    /// texture, made and holding its image, and the sampler of its state.
471    pub(crate) fn texture_binding(
472        &mut self,
473        gpu: &mut dyn Gpu,
474        handle: &SharedTexture,
475    ) -> Result<(TextureId, SamplerId), GpuError> {
476        let Context { device, textures, samplers, .. } = self;
477        bind(textures, samplers, device, gpu, handle)
478    }
479
480    /// The backend's texture of the texture of `handle`, once made, which
481    /// bindings made of it hold.
482    pub(crate) fn gpu_texture(&self, handle: &SharedTexture) -> Option<&SharedGpuTexture> {
483        self.textures.get(handle)?.gpu_texture()
484    }
485
486    /// The key of the variant of `program` that reads its properties of
487    /// `uniforms` from their uniforms, for `projection`, at the context's
488    /// pixel ratio.
489    pub fn shader_key(
490        &mut self,
491        program: &'static Program,
492        uniforms: Uniforms,
493        projection: ProjectionVariant,
494    ) -> ShaderKey {
495        // Only the program's own properties tell its variants apart.
496        let mut read = 0u16;
497        for (index, property) in program.properties.iter().enumerate() {
498            if uniforms.contains(property.name) {
499                read |= 1 << index;
500            }
501        }
502        let parameters = &self.program_parameters;
503        self.shader_keys
504            .entry((program, read, projection))
505            .or_insert_with(|| {
506                let properties = program.properties.iter().enumerate();
507                let uniforms = properties.filter(|&(index, _)| read & (1 << index) != 0).map(|(_, property)| property);
508                program.variant_key(parameters, uniforms, projection)
509            })
510            .clone()
511    }
512
513    /// Makes the keys of later variants at `pixel_ratio`. The shaders of
514    /// the earlier keys stay until [`release_shaders`](Self::release_shaders).
515    pub(crate) fn set_program_parameters(&mut self, pixel_ratio: f32) {
516        self.program_parameters = ProgramParameters::new(pixel_ratio);
517        self.shader_keys.clear();
518    }
519
520    /// The shader of `key`, made through `gpu` on first use.
521    pub(crate) fn shader(&mut self, gpu: &mut dyn Gpu, key: &ShaderKey) -> Result<ShaderId, GpuError> {
522        if let Some(&shader) = self.shaders.get(key) {
523            return Ok(shader);
524        }
525        let shader = gpu.create_shader(key)?;
526        self.shaders.insert(key.clone(), shader);
527        Ok(shader)
528    }
529
530    /// The buffers every draw binds, at the ids they bind at, which the
531    /// context replaces only at its tear-down: the draws' bindings bind
532    /// them.
533    pub(crate) fn global_uniform_buffers(&self) -> &UniformBufferArray {
534        &self.global_uniform_buffers
535    }
536
537    /// Writes `value` to the global uniform buffer `id`.
538    pub(crate) fn write_global_uniform_buffer<T: bytemuck::Pod>(&mut self, gpu: &mut dyn Gpu, id: usize, value: &T) {
539        let replaced = self.global_uniform_buffers.write_pod(gpu, id, value, &mut self.device);
540        debug_assert!(!replaced, "the global uniform buffer {id} written with another type");
541    }
542
543    /// The sampler of `state`, made through `gpu` on first use.
544    pub(crate) fn sampler(&mut self, gpu: &mut dyn Gpu, state: SamplerState) -> Result<SamplerId, GpuError> {
545        sampler(&mut self.samplers, gpu, state)
546    }
547
548    /// The pipeline of `key`, made through `gpu` on first use.
549    pub(crate) fn pipeline(&mut self, gpu: &mut dyn Gpu, key: &PipelineKey) -> Result<PipelineId, GpuError> {
550        if let Some(&pipeline) = self.pipelines.get(key) {
551            return Ok(pipeline);
552        }
553        let pipeline = gpu.create_pipeline(&key.desc())?;
554        self.pipelines.insert(key.clone(), pipeline);
555        Ok(pipeline)
556    }
557
558    /// A vertex buffer of at least `vertex_count` default values of
559    /// `format`, for an attribute a draw has no data for: zeros, or ones
560    /// for `Float2` and `Float4`. The context keeps one per format, grown
561    /// geometrically; geometry made of a replaced smaller one keeps it.
562    pub(crate) fn default_vertex_buffer(
563        &mut self,
564        gpu: &mut dyn Gpu,
565        format: AttributeDataType,
566        vertex_count: usize,
567    ) -> Result<Rc<Buffer>, GpuError> {
568        let cached_count = match self.default_vertex_buffers.get(&format) {
569            Some((count, buffer)) if *count >= vertex_count => return Ok(Rc::clone(buffer)),
570            Some((count, _)) => *count,
571            None => 0,
572        };
573        let count = vertex_count.max(2 * cached_count).max(1);
574        let mut data = vec![0u8; format.stride() * count];
575        if matches!(format, AttributeDataType::Float4 | AttributeDataType::Float2) {
576            for value in data.as_chunks_mut::<4>().0 {
577                value.copy_from_slice(&1.0f32.to_ne_bytes());
578            }
579        }
580        let buffer = Rc::new(self.device.buffer(gpu, BufferUsage::Vertex, &data)?);
581        self.default_vertex_buffers.insert(format, (count, Rc::clone(&buffer)));
582        Ok(buffer)
583    }
584}
585
586/// What a draw binds of the texture of `handle` in `textures`, through
587/// `gpu`: the texture, made through `device` and holding its image, and
588/// the sampler of its state in `samplers`.
589fn bind(
590    textures: &mut Store<TextureKey, Texture2D>,
591    samplers: &mut HashMap<SamplerState, SamplerId>,
592    device: &mut Device,
593    gpu: &mut dyn Gpu,
594    handle: &SharedTexture,
595) -> Result<(TextureId, SamplerId), GpuError> {
596    let texture = textures.get_mut(handle).ok_or(GpuError::UnknownId("texture"))?;
597    let id = texture.bind(gpu, device)?;
598    let sampler = if let Some(sampler) = texture.sampler_id() {
599        sampler
600    } else {
601        let sampler = sampler(samplers, gpu, texture.sampler())?;
602        texture.set_sampler_id(sampler);
603        sampler
604    };
605    Ok((id, sampler))
606}
607
608/// The sampler of `state` in `samplers`, made through `gpu` on first use.
609fn sampler(
610    samplers: &mut HashMap<SamplerState, SamplerId>,
611    gpu: &mut dyn Gpu,
612    state: SamplerState,
613) -> Result<SamplerId, GpuError> {
614    if let Some(&sampler) = samplers.get(&state) {
615        return Ok(sampler);
616    }
617    let sampler = gpu.create_sampler(&state)?;
618    samplers.insert(state, sampler);
619    Ok(sampler)
620}
621
622impl Context {
623    /// Lets go of the shaders and pipelines the draws made, which the next
624    /// [`destroy_released`](Self::destroy_released) destroys after the
625    /// bindings and geometry released before it: for a new pixel ratio,
626    /// once the draws made with them went. Draws made later make new ones.
627    pub(crate) fn release_shaders(&mut self) {
628        let queue = &self.device.queue;
629        for (_, pipeline) in self.pipelines.drain() {
630            queue.push(Release::Resource(pipeline.into()));
631        }
632        for (_, shader) in self.shaders.drain() {
633            queue.push(Release::Resource(shader.into()));
634        }
635    }
636
637    /// Destroys what the context made and what the renderer released. What
638    /// drops later still goes to the queue, and goes with the `Gpu`.
639    pub fn tear_down(&mut self, gpu: &mut dyn Gpu) {
640        self.global_uniform_buffers = UniformBufferArray::new();
641        self.default_vertex_buffers.clear();
642        // The meshes first, which hold what the other stores keep.
643        self.meshes.clear();
644        self.frame_targets.clear();
645        self.targets.clear();
646        self.textures.clear();
647        self.indexes.clear();
648        self.vertices.clear();
649        self.release_shaders();
650        let queue = &self.device.queue;
651        for (_, sampler) in self.samplers.drain() {
652            queue.push(Release::Resource(sampler.into()));
653        }
654        self.destroy_released(gpu);
655        self.torn_down = true;
656    }
657}
658
659impl Drop for Context {
660    /// A context dropped without [`tear_down`](Context::tear_down) leaves
661    /// what it made to the `Gpu`, which frees it when it drops, and logs
662    /// that it did.
663    fn drop(&mut self) {
664        if !self.torn_down && !std::thread::panicking() {
665            log::warn!(
666                target: log_target::RENDER,
667                "A renderer was dropped without its tear-down; its GPU objects stay until the backend goes"
668            );
669        }
670    }
671}