mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! In-process shader program validation and `ProgramHandle` implementation for
//! `mln_plugin::ProgramDesc`.

use std::any::Any;
use std::sync::Arc;

use mln_gfx::gfx_types::AttributeDataType;
use mln_gfx::shaders::bindings::{
    FIRST_UNIFORM_ID, FIRST_VERTICES_ID, MAX_ATTRIBUTES, MAX_TEXTURES, UNIFORM_SLOTS, VERTICES_SLOTS,
};
use mln_gfx::shaders::block::{Block, Member, MemberType};
use mln_gfx::shaders::program::{
    Attribute, BufferKind, Program, ProgramBuffer, ProgramTexture, Projection, Property, Stages, TextureRead, Variants,
    VertexWord,
};
use mln_gfx::shaders::source::{
    GlslEsDeclarations, GlslEsSource, GlslSource, MslSource, Precision, Sources, WgslSource,
};
use mln_plugin::backend::ProgramHandle;
use mln_plugin::{
    AttributeDesc, AttributeFormat, BlockDesc, BlockMemberType, BufferKind as PluginBufferKind, Error, GlslPrecision,
    Program as PluginProgram, ProgramDesc, ProjectionMode, Result, ShaderStages, TextureRead as PluginTextureRead,
    Variants as PluginVariants,
};
use mln_style::hash::{HashMap, HashSet};

#[derive(Debug)]
pub(crate) struct EngineProgram {
    program: &'static Program,
}

impl EngineProgram {
    pub(crate) const fn inner(&self) -> &'static Program {
        self.program
    }
}

impl ProgramHandle for EngineProgram {
    fn buffer_id(&self, name: &str) -> Result<u32> {
        for buf in self.program.buffers {
            if buf.name == name {
                return u32::try_from(buf.id).map_err(|_| Error::invalid_argument("buffer id overflow"));
            }
        }
        Err(Error::not_found(format!("program '{}' has no buffer named '{name}'", self.program.name)))
    }

    fn texture_slot(&self, name: &str) -> Result<u32> {
        for (slot, tex) in self.program.textures.iter().enumerate() {
            if tex.name == name {
                return u32::try_from(slot).map_err(|_| Error::invalid_argument("texture slot overflow"));
            }
        }
        Err(Error::not_found(format!("program '{}' has no texture named '{name}'", self.program.name)))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

pub(crate) fn resolve_attribute_name(program: &'static Program, name: &str) -> Result<&'static str> {
    for attr in program.attributes.iter().chain(program.instance_attributes.iter()) {
        if attr.name == name {
            return Ok(attr.name);
        }
    }
    Err(Error::invalid_argument(format!("program '{}' has no attribute named '{name}'", program.name)))
}

pub(crate) fn resolve_uniform_block(program: &'static Program, buffer_name: &str) -> Result<&'static Block> {
    for buffer in program.buffers {
        if buffer.name == buffer_name {
            return match buffer.kind {
                BufferKind::Uniform(block) => Ok(block),
                _ => Err(Error::invalid_argument(format!(
                    "buffer '{buffer_name}' on program '{}' is not a shared layer uniform block",
                    program.name
                ))),
            };
        }
    }
    Err(Error::invalid_argument(format!("program '{}' has no uniform buffer named '{buffer_name}'", program.name)))
}

pub(crate) fn to_attribute_format(format: AttributeFormat) -> AttributeDataType {
    match format {
        AttributeFormat::Byte => AttributeDataType::Byte,
        AttributeFormat::Byte2 => AttributeDataType::Byte2,
        AttributeFormat::Byte3 => AttributeDataType::Byte3,
        AttributeFormat::Byte4 => AttributeDataType::Byte4,
        AttributeFormat::UByte => AttributeDataType::UByte,
        AttributeFormat::UByte2 => AttributeDataType::UByte2,
        AttributeFormat::UByte3 => AttributeDataType::UByte3,
        AttributeFormat::UByte4 => AttributeDataType::UByte4,
        AttributeFormat::Short => AttributeDataType::Short,
        AttributeFormat::Short2 => AttributeDataType::Short2,
        AttributeFormat::Short3 => AttributeDataType::Short3,
        AttributeFormat::Short4 => AttributeDataType::Short4,
        AttributeFormat::UShort => AttributeDataType::UShort,
        AttributeFormat::UShort2 => AttributeDataType::UShort2,
        AttributeFormat::UShort3 => AttributeDataType::UShort3,
        AttributeFormat::UShort4 => AttributeDataType::UShort4,
        AttributeFormat::Int => AttributeDataType::Int,
        AttributeFormat::Int2 => AttributeDataType::Int2,
        AttributeFormat::Int3 => AttributeDataType::Int3,
        AttributeFormat::Int4 => AttributeDataType::Int4,
        AttributeFormat::UInt => AttributeDataType::UInt,
        AttributeFormat::UInt2 => AttributeDataType::UInt2,
        AttributeFormat::UInt3 => AttributeDataType::UInt3,
        AttributeFormat::UInt4 => AttributeDataType::UInt4,
        AttributeFormat::Float => AttributeDataType::Float,
        AttributeFormat::Float2 => AttributeDataType::Float2,
        AttributeFormat::Float3 => AttributeDataType::Float3,
        AttributeFormat::Float4 => AttributeDataType::Float4,
        AttributeFormat::UByte4Normalized => AttributeDataType::UByte4Normalized,
    }
}

fn to_stages(stages: ShaderStages) -> Stages {
    match stages {
        ShaderStages::Vertex => Stages::Vertex,
        ShaderStages::Fragment => Stages::Fragment,
        ShaderStages::Both => Stages::Both,
    }
}

fn to_projection(mode: ProjectionMode) -> Projection {
    match mode {
        ProjectionMode::None => Projection::None,
        ProjectionMode::PerDraw => Projection::PerDraw,
        ProjectionMode::Own => Projection::Own,
    }
}

fn to_texture_read(read: PluginTextureRead) -> TextureRead {
    match read {
        PluginTextureRead::Filtered => TextureRead::Filtered,
        PluginTextureRead::Unfiltered => TextureRead::Unfiltered,
        PluginTextureRead::Texels => TextureRead::Texels,
    }
}

fn to_precision(p: GlslPrecision) -> Precision {
    match p {
        GlslPrecision::Low => Precision::Low,
        GlslPrecision::Medium => Precision::Medium,
        GlslPrecision::High => Precision::High,
    }
}

fn member_layout(ty: BlockMemberType) -> Result<(MemberType, usize, usize)> {
    match ty {
        BlockMemberType::Float => Ok((MemberType::Float, 4, 4)),
        BlockMemberType::Int => Ok((MemberType::Int, 4, 4)),
        BlockMemberType::Uint => Ok((MemberType::Uint, 4, 4)),
        BlockMemberType::Vec2 => Ok((MemberType::Vec2, 8, 8)),
        BlockMemberType::Vec3 => Ok((MemberType::Vec3, 16, 12)),
        BlockMemberType::Vec4 => Ok((MemberType::Vec4, 16, 16)),
        BlockMemberType::Mat4 => Ok((MemberType::Mat4, 16, 64)),
        BlockMemberType::Vec4Array(array_length) => {
            if array_length == 0 {
                return Err(Error::invalid_argument("Vec4Array member must have length > 0"));
            }
            let len =
                usize::try_from(array_length).map_err(|_| Error::invalid_argument("Vec4Array length out of range"))?;
            let size =
                len.checked_mul(16).ok_or_else(|| Error::invalid_argument("Vec4Array member byte size overflow"))?;
            Ok((MemberType::Vec4Array(len), 16, size))
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ValidatedMember {
    name: String,
    ty: MemberType,
    offset: usize,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ValidatedBlock {
    name: String,
    size: usize,
    members: Vec<ValidatedMember>,
}

enum ValidatedVariants {
    All,
    Standing,
    PerVertex,
    Defined(String),
}

enum ValidatedBufferKind {
    Uniform(ValidatedBlock),
    DrawUniform(ValidatedBlock),
    Storage { block: ValidatedBlock, stride: usize },
    Vertices(VertexWord),
}

struct ValidatedBuffer {
    id: usize,
    name: String,
    kind: ValidatedBufferKind,
    stages: Stages,
    variants: ValidatedVariants,
}

struct ValidatedAttribute {
    name: String,
    format: AttributeDataType,
    variants: ValidatedVariants,
}

struct ValidatedTexture {
    name: String,
    read: TextureRead,
    stages: Stages,
    variants: ValidatedVariants,
}

fn validate_variants(v: PluginVariants<'_>, label: &str) -> Result<ValidatedVariants> {
    match v {
        PluginVariants::All => Ok(ValidatedVariants::All),
        PluginVariants::Standing => Ok(ValidatedVariants::Standing),
        PluginVariants::PerVertex => Ok(ValidatedVariants::PerVertex),
        PluginVariants::Defined(text) => {
            if text.is_empty() {
                return Err(Error::invalid_argument(format!("{label} must not be empty for Variants::Defined")));
            }
            Ok(ValidatedVariants::Defined(text.to_owned()))
        }
    }
}

fn validate_block(desc: BlockDesc<'_>, context: &str) -> Result<ValidatedBlock> {
    if desc.name.is_empty() {
        return Err(Error::invalid_argument(format!("{context}: block name must not be empty")));
    }
    let byte_size = desc.byte_size as usize;
    if byte_size == 0 || !byte_size.is_multiple_of(16) {
        return Err(Error::invalid_argument(format!(
            "block '{}' byte_size ({byte_size}) must be non-zero and a multiple of 16",
            desc.name
        )));
    }
    let mut members = Vec::with_capacity(desc.members.len());
    let mut seen_members: HashSet<String> = HashSet::default();
    let mut running_offset = 0usize;

    for m in desc.members {
        if m.name.is_empty() {
            return Err(Error::invalid_argument(format!("block '{}' has a member with an empty name", desc.name)));
        }
        if !seen_members.insert(m.name.to_owned()) {
            return Err(Error::invalid_argument(format!("block '{}' has duplicate member '{}'", desc.name, m.name)));
        }
        let (ty, align, elem_size) = member_layout(m.ty)?;
        let offset = m.offset as usize;
        if offset != running_offset {
            return Err(Error::invalid_argument(format!(
                "block '{}' member '{}' offset {offset} does not match expected contiguous offset {running_offset}",
                desc.name, m.name
            )));
        }
        if !offset.is_multiple_of(align) {
            return Err(Error::invalid_argument(format!(
                "block '{}' member '{}' offset {offset} is not aligned to {align} bytes",
                desc.name, m.name
            )));
        }
        running_offset = running_offset
            .checked_add(elem_size)
            .ok_or_else(|| Error::invalid_argument(format!("block '{}' member offset overflow", desc.name)))?;
        members.push(ValidatedMember { name: m.name.to_owned(), ty, offset });
    }

    if running_offset != byte_size {
        return Err(Error::invalid_argument(format!(
            "block '{}' members end at {running_offset} bytes, expected byte_size {byte_size}",
            desc.name
        )));
    }

    Ok(ValidatedBlock { name: desc.name.to_owned(), size: byte_size, members })
}

fn validate_attributes(
    attrs: &[AttributeDesc<'_>],
    program_name: &str,
    seen: &mut HashSet<String>,
) -> Result<Vec<ValidatedAttribute>> {
    let mut out = Vec::with_capacity(attrs.len());
    for a in attrs {
        if a.name.is_empty() {
            return Err(Error::invalid_argument(format!(
                "program '{program_name}' has an attribute with an empty name"
            )));
        }
        if !seen.insert(a.name.to_owned()) {
            return Err(Error::invalid_argument(format!(
                "program '{program_name}' has duplicate attribute '{}'",
                a.name
            )));
        }
        out.push(ValidatedAttribute {
            name: a.name.to_owned(),
            format: to_attribute_format(a.format),
            variants: validate_variants(a.variants, "attribute.variants")?,
        });
    }
    Ok(out)
}

fn leak_str(s: String) -> &'static str {
    Box::leak(s.into_boxed_str())
}

fn leak_slice<T>(v: Vec<T>) -> &'static [T] {
    Box::leak(v.into_boxed_slice())
}

fn leak_variants(v: ValidatedVariants) -> Variants {
    match v {
        ValidatedVariants::All => Variants::All,
        ValidatedVariants::Standing => Variants::Standing,
        ValidatedVariants::PerVertex => Variants::PerVertex,
        ValidatedVariants::Defined(s) => Variants::Defined(leak_str(s)),
    }
}

fn leak_block(b: ValidatedBlock) -> &'static Block {
    let members: Vec<Member> =
        b.members.into_iter().map(|m| Member { name: leak_str(m.name), ty: m.ty, offset: m.offset }).collect();
    Box::leak(Box::new(Block { name: leak_str(b.name), size: b.size, members: leak_slice(members) }))
}

pub(crate) fn create_program(desc: &ProgramDesc<'_>) -> Result<PluginProgram> {
    if desc.name.is_empty() {
        return Err(Error::invalid_argument("program.name must not be empty"));
    }

    let paint_params = desc.paint_params.map(to_stages);
    let projection = to_projection(desc.projection);

    let mut buffers = Vec::with_capacity(desc.buffers.len());
    let mut seen_buffer_ids = HashSet::default();
    let mut seen_buffer_names = HashSet::default();
    let mut blocks_by_name: HashMap<String, ValidatedBlock> = HashMap::default();

    for (idx, b) in desc.buffers.iter().enumerate() {
        if b.name.is_empty() {
            return Err(Error::invalid_argument(format!(
                "program '{}' buffer[{idx}] name must not be empty",
                desc.name
            )));
        }
        if !seen_buffer_names.insert(b.name.to_owned()) {
            return Err(Error::invalid_argument(format!(
                "program '{}' has duplicate buffer name '{}'",
                desc.name, b.name
            )));
        }
        let stages = to_stages(b.stages);
        let variants = validate_variants(b.variants, "buffer.variants")?;
        let (id, kind) = match b.kind {
            PluginBufferKind::Uniform => {
                let slot = b.slot as usize;
                if slot >= UNIFORM_SLOTS {
                    return Err(Error::invalid_argument(format!(
                        "uniform buffer '{}' slot {slot} exceeds maximum ({UNIFORM_SLOTS})",
                        b.name
                    )));
                }
                let block = validate_block(
                    b.block.ok_or_else(|| {
                        Error::invalid_argument(format!("uniform buffer '{}' requires a block", b.name))
                    })?,
                    b.name,
                )?;
                (FIRST_UNIFORM_ID + slot, ValidatedBufferKind::Uniform(block))
            }
            PluginBufferKind::DrawUniform => {
                let block = validate_block(
                    b.block.ok_or_else(|| {
                        Error::invalid_argument(format!("draw uniform buffer '{}' requires a block", b.name))
                    })?,
                    b.name,
                )?;
                (stages.id(), ValidatedBufferKind::DrawUniform(block))
            }
            PluginBufferKind::Storage => {
                let block = validate_block(
                    b.block.ok_or_else(|| {
                        Error::invalid_argument(format!("storage buffer '{}' requires a block", b.name))
                    })?,
                    b.name,
                )?;
                let stride = if b.storage_stride == 0 { block.size } else { b.storage_stride as usize };
                if stride < block.size || !stride.is_multiple_of(16) {
                    return Err(Error::invalid_argument(format!(
                        "storage buffer '{}' stride ({stride}) must be >= block byte_size ({}) and a multiple of 16",
                        b.name, block.size
                    )));
                }
                (stages.id(), ValidatedBufferKind::Storage { block, stride })
            }
            PluginBufferKind::VerticesUint | PluginBufferKind::VerticesFloat => {
                let slot = b.slot as usize;
                if slot >= VERTICES_SLOTS {
                    return Err(Error::invalid_argument(format!(
                        "vertex storage buffer '{}' slot {slot} exceeds maximum ({VERTICES_SLOTS})",
                        b.name
                    )));
                }
                if stages != Stages::Vertex {
                    return Err(Error::invalid_argument(format!(
                        "vertex storage buffer '{}' must use ShaderStages::Vertex",
                        b.name
                    )));
                }
                if b.block.is_some() {
                    return Err(Error::invalid_argument(format!(
                        "vertex storage buffer '{}' must not specify a block",
                        b.name
                    )));
                }
                let word = if b.kind == PluginBufferKind::VerticesUint { VertexWord::Uint } else { VertexWord::Float };
                (FIRST_VERTICES_ID + slot, ValidatedBufferKind::Vertices(word))
            }
        };

        if !seen_buffer_ids.insert(id) {
            return Err(Error::invalid_argument(format!(
                "program '{}' buffer '{}' collides on binding id {id}",
                desc.name, b.name
            )));
        }

        if let ValidatedBufferKind::Uniform(ref block)
        | ValidatedBufferKind::DrawUniform(ref block)
        | ValidatedBufferKind::Storage { ref block, .. } = kind
        {
            if let Some(existing) = blocks_by_name.get(&block.name) {
                if existing != block {
                    return Err(Error::invalid_argument(format!(
                        "program '{}' declares block '{}' with conflicting layouts",
                        desc.name, block.name
                    )));
                }
            } else {
                blocks_by_name.insert(block.name.clone(), block.clone());
            }
        }

        buffers.push(ValidatedBuffer { id, name: b.name.to_owned(), kind, stages, variants });
    }

    if desc.attributes.len().saturating_add(desc.instance_attributes.len()) > MAX_ATTRIBUTES {
        return Err(Error::invalid_argument(format!(
            "program '{}' declares {} attributes, exceeding maximum ({MAX_ATTRIBUTES})",
            desc.name,
            desc.attributes.len().saturating_add(desc.instance_attributes.len())
        )));
    }
    let mut seen_attrs = HashSet::default();
    let attributes = validate_attributes(desc.attributes, desc.name, &mut seen_attrs)?;
    let instance_attributes = validate_attributes(desc.instance_attributes, desc.name, &mut seen_attrs)?;

    if desc.textures.len() > MAX_TEXTURES {
        return Err(Error::invalid_argument(format!(
            "program '{}' declares {} textures, exceeding maximum ({MAX_TEXTURES})",
            desc.name,
            desc.textures.len()
        )));
    }
    let mut textures = Vec::with_capacity(desc.textures.len());
    let mut seen_textures = HashSet::default();
    for t in desc.textures {
        if !t.name.is_empty() && !seen_textures.insert(t.name.to_owned()) {
            return Err(Error::invalid_argument(format!(
                "program '{}' has duplicate texture name '{}'",
                desc.name, t.name
            )));
        }
        textures.push(ValidatedTexture {
            name: t.name.to_owned(),
            read: to_texture_read(t.read),
            stages: to_stages(t.stages),
            variants: validate_variants(t.variants, "texture.variants")?,
        });
    }

    let mut properties = Vec::with_capacity(desc.properties.len());
    let mut seen_props = HashSet::default();
    for &p in desc.properties {
        if p.is_empty() {
            return Err(Error::invalid_argument(format!("program '{}' has an empty property name", desc.name)));
        }
        if !seen_props.insert(p.to_owned()) {
            return Err(Error::invalid_argument(format!("program '{}' has duplicate property '{p}'", desc.name)));
        }
        properties.push(p.to_owned());
    }

    if desc.wgsl.is_none() && desc.msl.is_none() && desc.glsl.is_none() && desc.glsl_es.is_none() {
        return Err(Error::invalid_argument(format!(
            "program '{}' must provide at least one shader source",
            desc.name
        )));
    }

    // Leak the validated static `Program`.
    let mut block_cache: HashMap<String, &'static Block> = HashMap::default();
    let mut leak_cached_block = |block: ValidatedBlock| -> &'static Block {
        if let Some(&existing) = block_cache.get(&block.name) {
            return existing;
        }
        let key = block.name.clone();
        let leaked = leak_block(block);
        block_cache.insert(key, leaked);
        leaked
    };

    let leaked_buffers: Vec<ProgramBuffer> = buffers
        .into_iter()
        .map(|b| {
            let kind = match b.kind {
                ValidatedBufferKind::Uniform(block) => BufferKind::Uniform(leak_cached_block(block)),
                ValidatedBufferKind::DrawUniform(block) => BufferKind::DrawUniform(leak_cached_block(block)),
                ValidatedBufferKind::Storage { block, stride } => {
                    BufferKind::Storage { block: leak_cached_block(block), stride }
                }
                ValidatedBufferKind::Vertices(word) => BufferKind::Vertices(word),
            };
            ProgramBuffer {
                id: b.id,
                name: leak_str(b.name),
                kind,
                stages: b.stages,
                variants: leak_variants(b.variants),
            }
        })
        .collect();

    let leaked_attrs: Vec<Attribute> = attributes
        .into_iter()
        .map(|a| Attribute { name: leak_str(a.name), format: a.format, variants: leak_variants(a.variants) })
        .collect();

    let leaked_inst_attrs: Vec<Attribute> = instance_attributes
        .into_iter()
        .map(|a| Attribute { name: leak_str(a.name), format: a.format, variants: leak_variants(a.variants) })
        .collect();

    let leaked_textures: Vec<ProgramTexture> = textures
        .into_iter()
        .map(|t| {
            if t.name.is_empty() {
                ProgramTexture::UNUSED
            } else {
                ProgramTexture {
                    name: leak_str(t.name),
                    read: t.read,
                    stages: t.stages,
                    variants: leak_variants(t.variants),
                }
            }
        })
        .collect();

    let leaked_props: Vec<Property> = properties.into_iter().map(|p| Property { name: leak_str(p) }).collect();

    let mut sources = Sources::NONE;
    if let Some(w) = desc.wgsl {
        let leaked = Box::leak(Box::new(WgslSource {
            vertex: (!w.vertex.is_empty()).then(|| leak_str(w.vertex.to_owned())),
            fragment: (!w.fragment.is_empty()).then(|| leak_str(w.fragment.to_owned())),
            prelude: (!w.prelude.is_empty()).then(|| leak_str(w.prelude.to_owned())),
        }));
        sources = sources.wgsl(leaked);
    }
    if let Some(m) = desc.msl {
        let leaked = Box::leak(Box::new(MslSource {
            vertex_main_function: leak_str(m.vertex_main_function.to_owned()),
            fragment_main_function: leak_str(m.fragment_main_function.to_owned()),
            source: leak_str(m.source.to_owned()),
            fast_math: m.fast_math,
        }));
        sources = sources.msl(leaked);
    }
    if let Some(g) = desc.glsl {
        let leaked = Box::leak(Box::new(GlslSource {
            vertex: leak_str(g.vertex.to_owned()),
            fragment: leak_str(g.fragment.to_owned()),
        }));
        sources = sources.glsl(leaked);
    }
    if let Some(es) = desc.glsl_es {
        let members: Vec<(&'static Block, Precision, &'static [&'static str])> = es
            .member_precisions
            .iter()
            .filter_map(|mp| {
                let block = *block_cache.get(mp.block_name)?;
                let names: Vec<&'static str> = mp.member_names.iter().map(|s| leak_str((*s).to_owned())).collect();
                Some((block, to_precision(mp.precision), leak_slice(names)))
            })
            .collect();
        let attributes: Vec<(Precision, &'static [&'static str])> = es
            .attribute_precisions
            .iter()
            .map(|ap| {
                let names: Vec<&'static str> = ap.attribute_names.iter().map(|s| leak_str((*s).to_owned())).collect();
                (to_precision(ap.precision), leak_slice(names))
            })
            .collect();
        let highp_samplers: Vec<&'static str> = es.highp_samplers.iter().map(|s| leak_str((*s).to_owned())).collect();
        let declarations: &'static GlslEsDeclarations = Box::leak(Box::new(GlslEsDeclarations {
            members: leak_slice(members),
            attributes: leak_slice(attributes),
            highp_samplers: leak_slice(highp_samplers),
        }));
        let leaked = Box::leak(Box::new(GlslEsSource {
            vertex: leak_str(es.vertex.to_owned()),
            fragment: leak_str(es.fragment.to_owned()),
            declarations,
        }));
        sources = sources.glsl_es(leaked);
    }

    let leaked_program: &'static Program = Box::leak(Box::new(Program {
        name: leak_str(desc.name.to_owned()),
        buffers: leak_slice(leaked_buffers),
        paint_params,
        projection,
        attributes: leak_slice(leaked_attrs),
        instance_attributes: leak_slice(leaked_inst_attrs),
        textures: leak_slice(leaked_textures),
        properties: leak_slice(leaked_props),
        sources,
    }));

    Ok(PluginProgram::from_handle(Arc::new(EngineProgram { program: leaked_program })))
}