mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-03 22:41:19 +00:00
Compare commits
123
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e43e8df31 | ||
|
|
36e8c31f0d | ||
|
|
17fb7a3c43 | ||
|
|
5ab5e6f343 | ||
|
|
5a7182240e | ||
|
|
8698649da1 | ||
|
|
4610454c58 | ||
|
|
a6add77c5a | ||
|
|
e90f00dcf3 | ||
|
|
e7d05e1b42 | ||
|
|
d55ac7ba7a | ||
|
|
7afe6b3b78 | ||
|
|
0623c42d10 | ||
|
|
738230f7ea | ||
|
|
17e0c81967 | ||
|
|
adca169651 | ||
|
|
d049a1cf7f | ||
|
|
4ecd4aed42 | ||
|
|
636dd26f07 | ||
|
|
0d70d25f07 | ||
|
|
15c8926c97 | ||
|
|
300a64f711 | ||
|
|
27a9b91f3c | ||
|
|
e48f8805a5 | ||
|
|
9bbe7b69a3 | ||
|
|
8cde239e64 | ||
|
|
15c3c9564a | ||
|
|
f288082ff3 | ||
|
|
0fd046c4c1 | ||
|
|
7bd33b7ff1 | ||
|
|
9ce7cde286 | ||
|
|
0cf540495f | ||
|
|
6050f3c396 | ||
|
|
3371028cdf | ||
|
|
206d40bc0d | ||
|
|
f796d5c8fc | ||
|
|
03bf451124 | ||
|
|
2659b44569 | ||
|
|
e5f62c9546 | ||
|
|
f5a70b0e98 | ||
|
|
13aa3a5cc6 | ||
|
|
3fe6d7e954 | ||
|
|
5950cbce24 | ||
|
|
88a3069ea2 | ||
|
|
20e2efebf7 | ||
|
|
a193f64e04 | ||
|
|
494dbd965b | ||
|
|
bea1843497 | ||
|
|
f9284510ea | ||
|
|
723997489a | ||
|
|
0bc5f721fb | ||
|
|
7aaee29277 | ||
|
|
334bcc3dc0 | ||
|
|
3944964adf | ||
|
|
e9ac879b83 | ||
|
|
ffde4b3bbe | ||
|
|
0db2d73e02 | ||
|
|
fcb2188143 | ||
|
|
ab183249f9 | ||
|
|
cd4912b003 | ||
|
|
61d1f267cf | ||
|
|
b9c9162b14 | ||
|
|
bbf613e944 | ||
|
|
91acccc36a | ||
|
|
dec54a9ded | ||
|
|
38a239b1e9 | ||
|
|
60ac79d4b5 | ||
|
|
a65a9b36b5 | ||
|
|
808ae34499 | ||
|
|
f8769d9650 | ||
|
|
0b2cfae274 | ||
|
|
c647cb4eb9 | ||
|
|
0314c8bf2a | ||
|
|
71f4879f9c | ||
|
|
472d3661ce | ||
|
|
ca90388ff3 | ||
|
|
ded4122de0 | ||
|
|
fe3b20a37a | ||
|
|
9746b6999a | ||
|
|
0ca0af9026 | ||
|
|
6971715295 | ||
|
|
5bfba91aa8 | ||
|
|
080c96aa06 | ||
|
|
a2f732118f | ||
|
|
c2af11dfa7 | ||
|
|
b1dcb46e08 | ||
|
|
c00bc59949 | ||
|
|
1b577e9eed | ||
|
|
29bf02b6ce | ||
|
|
1998da2643 | ||
|
|
28ed9c58a7 | ||
|
|
a3560a1442 | ||
|
|
c40ff9603e | ||
|
|
595ccf2b06 | ||
|
|
8acdceeb61 | ||
|
|
4ce72c668a | ||
|
|
ebeee968b5 | ||
|
|
2eaf90df4b | ||
|
|
d8cf5fbb62 | ||
|
|
bf3e607bd6 | ||
|
|
6042310fc7 | ||
|
|
1ec5d20c84 | ||
|
|
723810f768 | ||
|
|
60e22f38c4 | ||
|
|
ba63055fd3 | ||
|
|
cec2e0c04a | ||
|
|
8fb5e95f15 | ||
|
|
5f4a17cb7c | ||
|
|
1c02f239c3 | ||
|
|
ea0d0e9595 | ||
|
|
5c24bc3dcf | ||
|
|
5689203791 | ||
|
|
b99ea8905e | ||
|
|
c1c97ed00e | ||
|
|
a551f206e8 | ||
|
|
b70c8609c9 | ||
|
|
55ec024e31 | ||
|
|
64cb95d8ec | ||
|
|
4a0063f5f6 | ||
|
|
f4f0702d08 | ||
|
|
98401d6de2 | ||
|
|
97fbaf7da4 | ||
|
|
90a239b410 |
@@ -25,10 +25,10 @@ jobs:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
# A failed pass warns; the next run's prune deletes what it missed.
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@b2726eb1defb6eccdfad920cc6988e1e3ec1c3c9 # main
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@94c8262155ee5424556db4e4983fe80ef9e779ba # main
|
||||
continue-on-error: true
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
@@ -30,6 +30,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
|
||||
| `vendor/wgpu-hal/` | wgpu developers; Metal language probe by CADCraft contributors | [wgpu-hal 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) ([gfx-rs/wgpu 40f4a34e](https://github.com/gfx-rs/wgpu/tree/40f4a34ebaf56f9a046231f54125ad046239d3f3/wgpu-hal)), same patch as [storytold/craft-anything vendor/wgpu-hal](https://github.com/storytold/craft-anything/tree/6c7d1f07f9f33643714bd203e1e004f04481f28e/vendor/wgpu-hal) | MIT OR Apache-2.0 | Graphics dependency, patched in `src/metal/adapter.rs` only (#1631); see `vendor/wgpu-hal/CADCRAFT.md`. |
|
||||
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
|
||||
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
|
||||
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
|
||||
|
||||
Generated
-2
@@ -7275,8 +7275,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "wgpu-hal"
|
||||
version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"arrayvec",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
# Patched third-party crates under [patch.crates-io], not ours to lint or test.
|
||||
exclude = ["vendor/wgpu-hal"]
|
||||
# default-members
|
||||
|
||||
[workspace.package]
|
||||
@@ -130,6 +132,10 @@ hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
# wgpu-hal that picks a Metal language version the system compiler accepts, not the OS's alone
|
||||
# (#1631; upstream gfx-rs/wgpu#10687). See vendor/wgpu-hal/CADCRAFT.md for when to remove it.
|
||||
wgpu-hal = { path = "vendor/wgpu-hal" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
|
||||
@@ -45,6 +45,31 @@ pub struct ForeignExtra {
|
||||
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
|
||||
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
|
||||
pub tail: Vec<RawTag>,
|
||||
/// A lightweight polyline's vertex identifiers (group 91, DXF 2010 and later) as read: one per
|
||||
/// vertex in the polyline's order; empty when the file gave none. Geometric constraints name the
|
||||
/// polyline's segments by them, so they are written back while the polyline's vertices are
|
||||
/// where they were read ([`vertex_ids_for`]).
|
||||
pub vertex_ids: Vec<VertexId>,
|
||||
}
|
||||
|
||||
/// A vertex of a lightweight polyline as it was read: its identifier and its point as the
|
||||
/// polyline has it once read (a polyline whose normal points down is read mirrored in x).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct VertexId {
|
||||
/// The identifier (group 91); 0 for a vertex without one.
|
||||
pub id: i32,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
}
|
||||
|
||||
/// The identifiers `kept` gives the vertices at `points`, in their order, while every vertex is
|
||||
/// where it was read. `None` once a vertex was added, removed, moved or the order changed: the
|
||||
/// identifiers no longer say which vertex is which.
|
||||
pub fn vertex_ids_for(kept: &[VertexId], points: impl ExactSizeIterator<Item = (f64, f64)> + Clone) -> Option<Vec<i32>> {
|
||||
if kept.is_empty() || kept.len() != points.len() {
|
||||
return None;
|
||||
}
|
||||
kept.iter().zip(points).all(|(k, (x, y))| k.x == x && k.y == y).then(|| kept.iter().map(|k| k.id).collect())
|
||||
}
|
||||
|
||||
impl ForeignExtra {
|
||||
@@ -55,6 +80,7 @@ impl ForeignExtra {
|
||||
&& self.color_book.is_none()
|
||||
&& self.props.is_empty()
|
||||
&& self.tail.is_empty()
|
||||
&& self.vertex_ids.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -154,6 +154,8 @@ impl Header {
|
||||
// Annotation scale of model space; annotative objects of other scales show (1) or not.
|
||||
h.set_str("CANNOSCALE", "1:1");
|
||||
h.set_i64("ANNOALLVISIBLE", 1);
|
||||
// Written to DXF as $REGENMODE; a header variable the drawing lacks is not written.
|
||||
h.set_i64("REGENMODE", 1);
|
||||
h
|
||||
}
|
||||
|
||||
|
||||
@@ -343,6 +343,11 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
|
||||
|
||||
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
|
||||
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
ttt_where(objs, |_| true)
|
||||
}
|
||||
|
||||
/// [`ttt`] among the circles `ok` accepts.
|
||||
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
|
||||
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
|
||||
let mut starts: Vec<[f64; 3]> = Vec::new();
|
||||
let cen = (p1 + p2 + p3) / 3.0;
|
||||
@@ -350,6 +355,20 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
starts.push([cen.x, cen.y, rad.max(1e-3)]);
|
||||
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
|
||||
starts.push([c.center.x, c.center.y, c.radius]);
|
||||
} else {
|
||||
// The picks lie in one line. When the circles picked are centred on it too, every Newton
|
||||
// step from a start on that line stays on it: start off it as well, on both sides, from
|
||||
// the circle through the two picks farthest apart and a point beside them.
|
||||
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
|
||||
let span = a.dist(b);
|
||||
let n = (b - a).normalized().perp();
|
||||
if span.is_finite() && span > 0.0 && n.is_finite() {
|
||||
for side in [1.0, -1.0] {
|
||||
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
|
||||
starts.push([c.center.x, c.center.y, c.radius]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut best: Option<(f64, Circle)> = None;
|
||||
let scale = rad.max(p1.dist(p2)).max(1e-6);
|
||||
@@ -379,6 +398,9 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
continue;
|
||||
}
|
||||
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
|
||||
if !ok(&c) {
|
||||
continue;
|
||||
}
|
||||
let sc = score(&c, &objs);
|
||||
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
|
||||
best = Some((sc, c));
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::{
|
||||
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
|
||||
point_param, size_param,
|
||||
};
|
||||
use crate::snap;
|
||||
|
||||
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = if let Some(center) = point_param(p, "center") {
|
||||
@@ -51,6 +52,8 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) struct CircleM {
|
||||
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
|
||||
pts: Vec<Vec2>,
|
||||
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
|
||||
tans: Vec<Option<snap::SnapCurve>>,
|
||||
diameter: bool,
|
||||
/// The `Ttr` option hands over to the tangent-circle machine.
|
||||
delegate: Option<Box<dyn Interactive>>,
|
||||
@@ -69,18 +72,22 @@ impl Interactive for CircleM {
|
||||
match (self.mode, n) {
|
||||
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
|
||||
(0, _) if self.diameter => {
|
||||
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
|
||||
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
|
||||
}
|
||||
(0, _) => {
|
||||
let p =
|
||||
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
|
||||
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
|
||||
.kw(&["Diameter"])
|
||||
.base_opt(self.pts.first().copied())
|
||||
.distance()
|
||||
.deferred();
|
||||
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
|
||||
}
|
||||
(1, k) => Prompt::new(
|
||||
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
|
||||
Accept::POINT,
|
||||
)
|
||||
.base_opt(self.pts.last().copied()),
|
||||
.base_opt(self.pts.last().copied())
|
||||
.deferred(),
|
||||
(2, k) => Prompt::new(
|
||||
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
|
||||
Accept::POINT,
|
||||
@@ -120,7 +127,14 @@ impl Interactive for CircleM {
|
||||
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
|
||||
Some(Circle::new(*c, r))
|
||||
}
|
||||
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
|
||||
1 if self.pts.len() == 3 => match self.three_points() {
|
||||
Some(c) => Some(c),
|
||||
None => {
|
||||
self.pts.pop();
|
||||
self.tans.truncate(self.pts.len());
|
||||
return Err(crate::EngineError::Other("Circle does not exist.".into()));
|
||||
}
|
||||
},
|
||||
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
|
||||
_ => None,
|
||||
};
|
||||
@@ -130,6 +144,29 @@ impl Interactive for CircleM {
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
|
||||
Input::Deferred(d) if self.mode == 1 => {
|
||||
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
|
||||
self.tans.resize(self.pts.len(), None);
|
||||
self.tans.push(tan);
|
||||
self.input(s, Input::Point(d.at))
|
||||
}
|
||||
// A tangent picked for the radius: the circle around the center that touches the
|
||||
// curve, on the side it was picked (#1512).
|
||||
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
|
||||
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
|
||||
// Around the picked curve's own center the circle would lie on it, not touch it.
|
||||
let concentric =
|
||||
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
|
||||
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
|
||||
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
|
||||
Some(r) => {
|
||||
finish_circle(s, Circle::new(c, r))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
|
||||
}
|
||||
}
|
||||
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
|
||||
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
|
||||
let r = if self.diameter { v / 2.0 } else { v };
|
||||
@@ -174,6 +211,38 @@ impl Interactive for CircleM {
|
||||
}
|
||||
}
|
||||
|
||||
impl CircleM {
|
||||
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
|
||||
fn three_points(&self) -> Option<Circle> {
|
||||
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
|
||||
if self.tans.iter().all(Option::is_none) {
|
||||
return Circle::from_3_points(a, b, c);
|
||||
}
|
||||
let tan = |i: usize| self.tans.get(i).copied().flatten();
|
||||
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
|
||||
let target = |i: usize, p: Vec2| {
|
||||
let circle = match tan(i) {
|
||||
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
|
||||
_ => Circle::new(p, 0.0),
|
||||
};
|
||||
crate::cmd::curves::TanObj::Circle(circle)
|
||||
};
|
||||
let pts = [a, b, c];
|
||||
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
|
||||
// not be the picked circle itself (which lies on it rather than touching it).
|
||||
let touches = |found: &Circle| {
|
||||
pts.iter().enumerate().all(|(i, p)| {
|
||||
tan(i).is_none_or(|t| {
|
||||
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
|
||||
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
|
||||
!same && t.contains(target(i, *p).touch(found))
|
||||
})
|
||||
})
|
||||
};
|
||||
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
|
||||
s.add_entity(circle(c.center, c.radius))?;
|
||||
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
|
||||
|
||||
@@ -603,6 +603,64 @@ fn plot_path_extension_picks_the_format_like_export() {
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
|
||||
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
|
||||
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
|
||||
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
|
||||
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
|
||||
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
|
||||
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
|
||||
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
|
||||
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
|
||||
|
||||
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
|
||||
let d = ap * 0.5;
|
||||
let model_before = s.doc().unwrap().model.len();
|
||||
for (ovr, pt, name) in [
|
||||
("end", format!("{},-25", 60.0 + d), "Endpoint"),
|
||||
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
|
||||
("nea", format!("63,{}", -25.0 + d), "Nearest"),
|
||||
] {
|
||||
s.cmdline("line").unwrap();
|
||||
s.cmdline(ovr).unwrap();
|
||||
s.cmdline(&pt).unwrap();
|
||||
assert_eq!(
|
||||
s.log.last().map(String::as_str),
|
||||
Some(format!("No {name} found for specified point.").as_str()),
|
||||
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
|
||||
s.log
|
||||
);
|
||||
s.cmdline("").unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
|
||||
|
||||
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
|
||||
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
|
||||
let cs = s.snap_cursor(
|
||||
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
|
||||
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
|
||||
);
|
||||
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
|
||||
|
||||
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
|
||||
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
|
||||
let model_with_block = s.doc().unwrap().model.len();
|
||||
s.cmdline("line").unwrap();
|
||||
s.cmdline("end").unwrap();
|
||||
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
|
||||
assert_eq!(
|
||||
s.log.last().map(String::as_str),
|
||||
Some("No Endpoint found for specified point."),
|
||||
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
|
||||
s.log
|
||||
);
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_set_frames_extents_away_from_origin() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -237,7 +237,7 @@ impl Interactive for SetvarM {
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &Value::String(t)) {
|
||||
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &crate::sysvars::typed_value(&n, t)) {
|
||||
Ok(()) => {
|
||||
s.touch();
|
||||
Ok(Step::Done)
|
||||
|
||||
@@ -126,14 +126,36 @@ pub fn snap_name(m: u32) -> &'static str {
|
||||
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
||||
}
|
||||
|
||||
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
|
||||
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
|
||||
/// first, then deferred snaps, then Nearest), without repeats.
|
||||
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
|
||||
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
|
||||
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
|
||||
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
|
||||
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn snap_candidates_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Vec<SnapHit> {
|
||||
// A base that is not a number would give meaningless perpendiculars and tangents.
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
|
||||
return Vec::new();
|
||||
}
|
||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
||||
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
|
||||
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
|
||||
if !out.iter().any(|o| o.same(&h, aperture)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||
@@ -356,12 +378,15 @@ impl Session {
|
||||
Frame::Snap { mode } => {
|
||||
// Snap the point with this mode alone, within the aperture.
|
||||
let prompt = self.current_prompt();
|
||||
let space = self.space();
|
||||
let (doc, space, frozen) = {
|
||||
let st = self.state()?;
|
||||
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
|
||||
};
|
||||
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
|
||||
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
|
||||
let base = prompt.as_ref().and_then(|q| q.base);
|
||||
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
|
||||
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
|
||||
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
|
||||
match hit {
|
||||
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
|
||||
Some(h) => {
|
||||
|
||||
@@ -76,8 +76,9 @@ pub struct Prompt {
|
||||
/// Rubber-band origin (for direct distance entry, ortho and polar).
|
||||
pub base: Option<Vec2>,
|
||||
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
|
||||
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
|
||||
/// pick arrives as the plain point it was picked at.
|
||||
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
|
||||
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
|
||||
/// was picked at.
|
||||
pub deferred: bool,
|
||||
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
|
||||
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
|
||||
@@ -149,6 +149,9 @@ pub struct Settings {
|
||||
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
|
||||
/// dialog; on by default, as in AutoCAD (Initial value 1).
|
||||
pub attdia: bool,
|
||||
/// TEXTEVAL: 1 lets a routine's input be read as LISP where it would be text (default: 0).
|
||||
/// Kept for routines that switch it around their prompts; no prompt reads it yet.
|
||||
pub texteval: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -220,6 +223,7 @@ impl Default for Settings {
|
||||
auditctl: false,
|
||||
attreq: true,
|
||||
attdia: true,
|
||||
texteval: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+581
-217
@@ -90,6 +90,24 @@ pub struct BlockLeaf {
|
||||
}
|
||||
|
||||
impl SnapHit {
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None, source: None }
|
||||
}
|
||||
|
||||
/// The same snap as `o`, for a Tab list without repeats: the same mode at the same point
|
||||
/// (within a millionth of `aperture`), deferred or not alike (and if deferred, on the same
|
||||
/// curve), and from the same source (this space, or one viewport). Overlapping viewports can
|
||||
/// show different model points at one paper point; each stays a candidate, since DIST
|
||||
/// measures in the model units of the viewport picked.
|
||||
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
|
||||
self.mode == o.mode
|
||||
// Deferred snaps on different curves at one provisional point stay apart: the line
|
||||
// drawn from each depends on its curve.
|
||||
&& self.deferred.map(|d| d.curve) == o.deferred.map(|d| d.curve)
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, aperture * 1e-6)
|
||||
}
|
||||
|
||||
/// The command input a pick at this snap gives: a deferred snap or a plain point.
|
||||
pub fn input(&self) -> crate::Input {
|
||||
match self.deferred {
|
||||
@@ -97,33 +115,6 @@ impl SnapHit {
|
||||
None => crate::Input::Point(self.point),
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None, source: None }
|
||||
}
|
||||
|
||||
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
|
||||
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
|
||||
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
|
||||
let class = if self.deferred.is_some() {
|
||||
1
|
||||
} else if self.mode == mode::NEA {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(class, snap_score(self.mode, self.point, cursor, aperture))
|
||||
}
|
||||
|
||||
/// The same snap as `o`: mode and point, from the same source (paper space, or one
|
||||
/// viewport). Overlapping viewports can show different model points at one paper point;
|
||||
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
|
||||
fn same(&self, o: &SnapHit) -> bool {
|
||||
self.mode == o.mode
|
||||
&& self.deferred.is_some() == o.deferred.is_some()
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The curve a deferred snap refers to.
|
||||
@@ -162,12 +153,16 @@ impl SnapCurve {
|
||||
}
|
||||
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
|
||||
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
|
||||
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
||||
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
||||
match self {
|
||||
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
|
||||
let u = (p - *center).normalized();
|
||||
if u == Vec2::ZERO {
|
||||
vec![Circle::new(*center, *radius).closest(picked)]
|
||||
// On an arc, the point within its sweep.
|
||||
vec![match *self {
|
||||
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(picked),
|
||||
_ => Circle::new(*center, *radius).closest(picked),
|
||||
}]
|
||||
} else {
|
||||
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
|
||||
}
|
||||
@@ -254,23 +249,34 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
|
||||
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
|
||||
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
|
||||
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
|
||||
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest).
|
||||
/// known. With a base and `deferred` set, tangents to circles and circular arcs are deferred too
|
||||
/// (CIRCLE's radius: the circle around the base that touches the curve, #1512); an elliptical arc
|
||||
/// or a spline keeps its ordinary tangent from the base. Deferred hits only win
|
||||
/// where no other snap does (they are as unspecific as Nearest).
|
||||
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
|
||||
osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`osnap`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn osnap_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Option<SnapHit> {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 {
|
||||
return None;
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
|
||||
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
|
||||
/// Snaps seen through layout viewports are included.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
|
||||
osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn osnap_with(
|
||||
d: &Drawing,
|
||||
@@ -282,7 +288,7 @@ pub(crate) fn osnap_with(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> Option<SnapHit> {
|
||||
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred).0
|
||||
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred, &[]).0
|
||||
}
|
||||
|
||||
/// Find the best object snap and retain the local-space primitives gathered for that query.
|
||||
@@ -296,40 +302,21 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
|
||||
(all.into_iter().next(), prims)
|
||||
}
|
||||
|
||||
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_all_with_neighborhood(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||
return (Vec::new(), None);
|
||||
return (None, None);
|
||||
}
|
||||
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hits, prims)) => (hits, Some(prims)),
|
||||
None => (Vec::new(), None),
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
|
||||
Some((hit, prims)) => (hit, Some(prims)),
|
||||
None => (None, None),
|
||||
};
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (all, near_prims);
|
||||
return (best.map(|(h, _)| h), near_prims);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
|
||||
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
|
||||
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
|
||||
let mut pick = all.first().copied();
|
||||
for view in views {
|
||||
let model_cursor = view.to_model(cursor);
|
||||
let model_aperture = aperture / view.scale;
|
||||
@@ -337,66 +324,50 @@ fn osnap_all_with_neighborhood(
|
||||
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let hits = osnap_in(
|
||||
d,
|
||||
&model,
|
||||
&model_ix,
|
||||
model_cursor,
|
||||
model_aperture,
|
||||
osmode,
|
||||
model_base,
|
||||
deferred,
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
);
|
||||
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
|
||||
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
let Some((cands, prims, src)) = collect_in(d, &model, &model_ix, model_cursor, model_aperture, osmode, &view.viewport.frozen_layers) else {
|
||||
continue;
|
||||
};
|
||||
let clip = Some(view.model_clip);
|
||||
// The rank was found in model units: paper units are model units times the scale.
|
||||
let project = |(h, r): (SnapHit, Rank)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }));
|
||||
let first = finish(cands.clone(), &prims, &src, model_cursor, model_aperture, osmode, model_base, deferred, clip);
|
||||
// The model clip is the box round the viewport as the model sees it, larger than the
|
||||
// viewport when it is twisted: a snap inside it can still fall off the viewport. Then the
|
||||
// best of the others that is on it, as Tab ranks them.
|
||||
let hit = first.and_then(|f| {
|
||||
project(f).or_else(|| {
|
||||
finish_all(cands, &prims, &src, model_cursor, model_aperture, osmode, model_base, deferred, clip).into_iter().find_map(project)
|
||||
})
|
||||
});
|
||||
if let Some((hit, rank)) = hit
|
||||
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
|
||||
{
|
||||
pick = Some(hit);
|
||||
}
|
||||
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
|
||||
}
|
||||
let mut out = ranked(all, cursor, aperture);
|
||||
if let Some(pick) = pick {
|
||||
out.retain(|h| !h.same(&pick));
|
||||
out.insert(0, pick);
|
||||
}
|
||||
(out, near_prims)
|
||||
}
|
||||
|
||||
/// `hits` best first ([`SnapHit::rank`]), without repeats.
|
||||
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
|
||||
hits.sort_by(|a, b| {
|
||||
let (ca, sa) = a.rank(cursor, aperture);
|
||||
let (cb, sb) = b.rank(cursor, aperture);
|
||||
ca.cmp(&cb).then(sa.total_cmp(&sb))
|
||||
});
|
||||
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
|
||||
for h in hits {
|
||||
if !out.iter().any(|o| o.same(&h)) {
|
||||
out.push(h);
|
||||
best = Some((hit, rank));
|
||||
}
|
||||
}
|
||||
out
|
||||
(best.map(|(h, _)| h), near_prims)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
||||
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
|
||||
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
|
||||
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
|
||||
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Rank {
|
||||
tier: u8,
|
||||
score: f64,
|
||||
}
|
||||
|
||||
impl Rank {
|
||||
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
|
||||
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
|
||||
}
|
||||
|
||||
fn beats(&self, other: &Rank) -> bool {
|
||||
self.cmp(other).is_lt()
|
||||
}
|
||||
}
|
||||
|
||||
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in_with_prims(
|
||||
d: &Drawing,
|
||||
@@ -409,7 +380,92 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
||||
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
|
||||
let (cands, near_prims, src) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
let hit = finish(cands, &near_prims, &src, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
}
|
||||
|
||||
/// Every snap of `osmode` under the aperture round `cursor`, best first: Tab cycles through
|
||||
/// these. Each mode's points of every object nearby, the intersections, perpendicular and
|
||||
/// tangent points from `base`, the centers found from their curves, the deferred snaps and the
|
||||
/// nearest point of each object, ranked as [`osnap`] ranks them, without repeats and at most
|
||||
/// [`MAX_CYCLE`]; in viewports too, as [`osnap`] snaps.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`osnap_all`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn osnap_all_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Vec<SnapHit> {
|
||||
if osmode == 0
|
||||
|| osmode & mode::OFF != 0
|
||||
|| !cursor.is_finite()
|
||||
|| !(aperture.is_finite() && aperture > 0.0)
|
||||
|| base.is_some_and(|b| !b.is_finite())
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let mut out: Vec<(SnapHit, Rank)> = Vec::new();
|
||||
if let Some((cands, prims, src)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
|
||||
out = finish_all(cands, &prims, &src, cursor, aperture, osmode, base, deferred, None);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if !views.is_empty() {
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
for view in views {
|
||||
let (mc, ma, mb) = (view.to_model(cursor), aperture / view.scale, base.map(|p| view.to_model(p)));
|
||||
if !mc.is_finite() || !(ma.is_finite() && ma > 0.0) || mb.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let Some((cands, prims, src)) = collect_in(d, &model, &model_ix, mc, ma, osmode, &view.viewport.frozen_layers) else { continue };
|
||||
// The rank was found in model units: paper units are model units times the scale.
|
||||
out.extend(
|
||||
finish_all(cands, &prims, &src, mc, ma, osmode, mb, deferred, Some(view.model_clip))
|
||||
.into_iter()
|
||||
.filter_map(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }))),
|
||||
);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
let mut unique: Vec<SnapHit> = Vec::with_capacity(out.len().min(MAX_CYCLE));
|
||||
for (h, _) in out {
|
||||
if unique.len() >= MAX_CYCLE {
|
||||
break;
|
||||
}
|
||||
if !unique.iter().any(|u| u.same(&h, aperture)) {
|
||||
unique.push(h);
|
||||
}
|
||||
}
|
||||
unique
|
||||
}
|
||||
|
||||
/// Most snaps [`osnap_all`] offers.
|
||||
const MAX_CYCLE: usize = 256;
|
||||
|
||||
/// The candidate snap points near `cursor` (each with its mode) and the primitives near it:
|
||||
/// [`gather_in`]'s, plus the intersections between those primitives, and what each lies on.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn collect_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
frozen: &[String],
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>, Sources)> {
|
||||
let (mut cands, near_prims, mut src) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
|
||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||
@@ -449,8 +505,7 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hits = finish(cands, &near_prims, src, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hits, near_prims))
|
||||
Some((cands, near_prims, src))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -492,26 +547,26 @@ pub(crate) fn extendable(p: &Prim) -> bool {
|
||||
matches!(p, Prim::Seg(_) | Prim::Circle(_) | Prim::Infinite { .. })
|
||||
}
|
||||
|
||||
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
|
||||
/// when the drawing can't be searched.
|
||||
pub(crate) fn gather(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[], None).map(|(cands, prims, _)| (cands, prims))
|
||||
}
|
||||
|
||||
/// The entity each gathered candidate and nearby primitive comes from (parallel to them).
|
||||
#[derive(Default)]
|
||||
struct Sources {
|
||||
pub(crate) struct Sources {
|
||||
cands: Vec<Option<SnapSource>>,
|
||||
prims: Vec<Option<SnapSource>>,
|
||||
}
|
||||
|
||||
/// What the nearby primitive `i` lies on.
|
||||
fn prim_source(src: &Sources, i: usize) -> Option<SnapSource> {
|
||||
src.prims.get(i).copied().flatten()
|
||||
}
|
||||
|
||||
/// What each candidate lies on: the `n` gathered candidates' sources, then the object of each
|
||||
/// point found from the base point.
|
||||
fn candidate_sources(n: usize, src: &Sources, from_base: &[FromBase]) -> Vec<Option<SnapSource>> {
|
||||
let mut out: Vec<Option<SnapSource>> = (0..n).map(|i| src.cands.get(i).copied().flatten()).collect();
|
||||
out.extend(from_base.iter().map(|f| prim_source(src, f.prim)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
|
||||
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
|
||||
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
|
||||
@@ -562,8 +617,10 @@ pub(crate) fn nearest_with_direction(
|
||||
best.map(|(_, at, dir)| (at, dir))
|
||||
}
|
||||
|
||||
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
|
||||
/// when the drawing can't be searched.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gather_in(
|
||||
pub(crate) fn gather_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
@@ -673,89 +730,225 @@ fn leaf_with_source(be: &Entity, m: &Mat3, z: Option<(f64, f64)>, handle: Handle
|
||||
src.prims.resize(sink.near.len(), from);
|
||||
}
|
||||
|
||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
||||
/// snaps, the deferred snaps and Nearest.
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
|
||||
/// its [`Rank`].
|
||||
///
|
||||
/// In order of preference (the rank's tier):
|
||||
/// 0. the snap point within `aperture` of the cursor that scores best (see [`snap_score`]),
|
||||
/// perpendicular and tangent points from the base point included;
|
||||
/// 1. with a base point, a perpendicular or tangent on an object that passes within `aperture`,
|
||||
/// wherever its point lies (see [`from_base_on_objects`]), or the center of a circle, arc or
|
||||
/// ellipse under the cursor (see [`curve_centers`]): the object nearest the cursor;
|
||||
/// 2. a deferred perpendicular or tangent (no base point yet);
|
||||
/// 3. Nearest.
|
||||
///
|
||||
/// [`finish_all`] keeps every candidate in this order, for Tab.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
near_prims: &[Prim],
|
||||
mut src: Sources,
|
||||
src: &Sources,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for (p, from) in near_prims.iter().zip(&src.prims) {
|
||||
if osmode & mode::PER != 0 {
|
||||
match p {
|
||||
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
|
||||
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
||||
// not offered, and the far side is still found.
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => {
|
||||
let curve = SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end };
|
||||
cands.extend(curve.perpendiculars(bp, bp).into_iter().map(|q| (mode::PER, q)));
|
||||
}
|
||||
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
|
||||
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
|
||||
Prim::Ellipse(e) => cands.extend(curves::ellipse_perpendiculars(e, bp).into_iter().map(|q| (mode::PER, q))),
|
||||
Prim::Spline(s) => cands.extend(curves::spline_perpendiculars(s, bp).into_iter().map(|q| (mode::PER, q))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if osmode & mode::TAN != 0 {
|
||||
let pts = match p {
|
||||
// Only the tangent points that lie on the arc itself (not its circle).
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
||||
.tangent_points(bp)
|
||||
.into_iter()
|
||||
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
||||
.collect(),
|
||||
Prim::Circle(c) => c.tangent_points(bp),
|
||||
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
||||
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
|
||||
}
|
||||
src.cands.resize(cands.len(), *from);
|
||||
}
|
||||
}
|
||||
) -> Option<(SnapHit, Rank)> {
|
||||
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||
let sources = candidate_sources(cands.len(), src, &from_base);
|
||||
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let mut hits: Vec<SnapHit> = cands
|
||||
.into_iter()
|
||||
.zip(src.cands.iter().copied().chain(std::iter::repeat(None)))
|
||||
// Prefer more specific modes when nearly equidistant.
|
||||
let best = cands
|
||||
.iter()
|
||||
.zip(&sources)
|
||||
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
|
||||
.map(|((m, p), from)| SnapHit { source: from, ..SnapHit::plain(m, p) })
|
||||
.collect();
|
||||
if base.is_none() && deferred {
|
||||
hits.extend(deferred_hits(near_prims, &src.prims, cursor, aperture, osmode, clip));
|
||||
.map(|((m, p), from)| (snap_score(*m, *p, cursor, aperture), *m, *p, *from))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if let Some((score, m, p, from)) = best {
|
||||
return Some((SnapHit { source: from, ..SnapHit::plain(m, p) }, Rank { tier: 0, score }));
|
||||
}
|
||||
// A perpendicular or tangent on the object under the cursor, or the center found from its
|
||||
// curve, only when no snap point is in the aperture: the Midpoint or Quadrant under the cursor
|
||||
// wins over the center of the same curve, as in AutoCAD. Of the two, the object nearer the
|
||||
// cursor; on a tie (the same curve), the perpendicular or tangent.
|
||||
let on_object = from_base_on_objects(&from_base, near_prims, &src.prims, cursor, aperture, visible)
|
||||
.into_iter()
|
||||
.min_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)))
|
||||
.map(|(h, r, _)| (h, r));
|
||||
let center = curve_centers(near_prims, cursor, aperture, osmode)
|
||||
.into_iter()
|
||||
.filter(|(_, c, _)| visible(*c))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(score, c, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::CEN, c) }, Rank { tier: 1, score }));
|
||||
match (on_object, center) {
|
||||
(Some(o), Some(c)) => return Some(if c.1.beats(&o.1) { c } else { o }),
|
||||
(Some(h), None) | (None, Some(h)) => return Some(h),
|
||||
(None, None) => {}
|
||||
}
|
||||
// With a base, perpendiculars are resolved from it above; only tangents are left to defer.
|
||||
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||
if deferred && let Some(h) = deferred_hit(near_prims, &src.prims, cursor, aperture, deferrable, clip) {
|
||||
let score = h.point.dist(cursor);
|
||||
return Some((h, Rank { tier: 2, score }));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
let mut nb: Option<(f64, Vec2, Option<SnapSource>)> = None;
|
||||
let mut consider = |c: Vec2, from: Option<SnapSource>| {
|
||||
let dd = c.dist(cursor);
|
||||
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, ..)| dd < bd) {
|
||||
nb = Some((dd, c, from));
|
||||
}
|
||||
};
|
||||
for (p, from) in near_prims.iter().zip(&src.prims) {
|
||||
for s in prim_segments(p) {
|
||||
consider(fix_circle(&s).closest(cursor), *from);
|
||||
}
|
||||
if let Prim::Circle(c) = p {
|
||||
consider(c.closest(cursor), *from);
|
||||
}
|
||||
}
|
||||
if let Some((_, p, source)) = nb {
|
||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None, source });
|
||||
let nb = near_prims
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, p)| nearest_point(p, cursor, aperture, &visible).map(|(score, q)| (score, q, i)))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if let Some((score, p, i)) = nb {
|
||||
return Some((SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::NEA, p) }, Rank { tier: 3, score }));
|
||||
}
|
||||
}
|
||||
ranked(hits, cursor, aperture)
|
||||
None
|
||||
}
|
||||
|
||||
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
|
||||
/// the snap points best first, then the perpendiculars and tangents on the objects under the
|
||||
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
|
||||
/// of each object nearby.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish_all(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
near_prims: &[Prim],
|
||||
src: &Sources,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<(SnapHit, Rank)> {
|
||||
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||
let sources = candidate_sources(cands.len(), src, &from_base);
|
||||
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let mut out: Vec<(SnapHit, Rank)> = cands
|
||||
.iter()
|
||||
.zip(&sources)
|
||||
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
|
||||
.map(|((m, p), from)| (SnapHit { source: *from, ..SnapHit::plain(*m, *p) }, Rank { tier: 0, score: snap_score(*m, *p, cursor, aperture) }))
|
||||
.collect();
|
||||
// Of several points on one object (a circle's two tangents), the one nearer the cursor first,
|
||||
// as `finish` picks it; the sort below is stable.
|
||||
let mut on_object = from_base_on_objects(&from_base, near_prims, &src.prims, cursor, aperture, visible);
|
||||
on_object.sort_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)));
|
||||
out.extend(on_object.into_iter().map(|(h, r, _)| (h, r)));
|
||||
out.extend(
|
||||
curve_centers(near_prims, cursor, aperture, osmode)
|
||||
.into_iter()
|
||||
.filter(|(_, c, _)| visible(*c))
|
||||
.map(|(score, c, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::CEN, c) }, Rank { tier: 1, score })),
|
||||
);
|
||||
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||
if deferred {
|
||||
let hits = deferred_hits(near_prims, &src.prims, cursor, aperture, deferrable, clip);
|
||||
out.extend(hits.into_iter().map(|h| (h, Rank { tier: 2, score: h.point.dist(cursor) })));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
let near = near_prims.iter().enumerate().filter_map(|(i, p)| nearest_point(p, cursor, aperture, &visible).map(|(score, q)| (score, q, i)));
|
||||
out.extend(near.map(|(score, p, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::NEA, p) }, Rank { tier: 3, score })));
|
||||
}
|
||||
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
out
|
||||
}
|
||||
|
||||
/// The point of `p` closest to `cursor` among its visible points within `aperture`, with its
|
||||
/// distance: each segment's closest point is checked before the closest is chosen, so a curve
|
||||
/// whose closest point is clipped away (outside a viewport) still offers the visible one.
|
||||
fn nearest_point(p: &Prim, cursor: Vec2, aperture: f64, visible: &impl Fn(Vec2) -> bool) -> Option<(f64, Vec2)> {
|
||||
let mut nb: Option<(f64, Vec2)> = None;
|
||||
let mut consider = |c: Vec2| {
|
||||
let dd = c.dist(cursor);
|
||||
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
|
||||
nb = Some((dd, c));
|
||||
}
|
||||
};
|
||||
for s in prim_segments(p) {
|
||||
consider(fix_circle(&s).closest(cursor));
|
||||
}
|
||||
if let Prim::Circle(c) = p {
|
||||
consider(c.closest(cursor));
|
||||
}
|
||||
nb
|
||||
}
|
||||
|
||||
/// The perpendicular and tangent points from the base point `base` (none without one), each
|
||||
/// with the index in `near_prims` of the object it lies on. At a `deferred` prompt the tangents to
|
||||
/// circles and arcs are left out: the prompt resolves them itself (CIRCLE's radius, #1512).
|
||||
fn base_snaps(near_prims: &[Prim], osmode: u32, base: Option<Vec2>, cursor: Vec2, deferred: bool) -> Vec<FromBase> {
|
||||
let mut from_base: Vec<FromBase> = Vec::new();
|
||||
let Some(bp) = base else { return from_base };
|
||||
for (prim, p) in near_prims.iter().enumerate() {
|
||||
let mut found = |mode: u32, points: Vec<Vec2>| from_base.extend(points.into_iter().map(|point| FromBase { mode, point, prim }));
|
||||
if osmode & mode::PER != 0 {
|
||||
let pts = match p {
|
||||
Prim::Seg(Segment::Line(l)) => vec![l.project(bp)],
|
||||
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
||||
// not offered, and the far side is still found. From the centre, the point of
|
||||
// the arc under the cursor.
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => {
|
||||
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, cursor)
|
||||
}
|
||||
// Both antipodes too, so a pick on the far side of the circle snaps there
|
||||
// rather than across it. From the centre every point is perpendicular: the
|
||||
// one under the cursor.
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
|
||||
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
|
||||
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
|
||||
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
found(mode::PER, pts);
|
||||
}
|
||||
if osmode & mode::TAN != 0 {
|
||||
let pts = match p {
|
||||
// A deferred prompt resolves tangents to circles and arcs itself.
|
||||
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
|
||||
// Only the tangent points that lie on the arc itself (not its circle).
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
||||
.tangent_points(bp)
|
||||
.into_iter()
|
||||
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
||||
.collect(),
|
||||
Prim::Circle(c) => c.tangent_points(bp),
|
||||
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
||||
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
found(mode::TAN, pts);
|
||||
}
|
||||
}
|
||||
from_base
|
||||
}
|
||||
|
||||
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
|
||||
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
|
||||
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
|
||||
/// point is in the aperture. Empty unless Center is among `osmode`.
|
||||
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2, usize)> {
|
||||
let mut out = Vec::new();
|
||||
if osmode & mode::CEN == 0 {
|
||||
return out;
|
||||
}
|
||||
// The work limit counts the curves only, so straight segments before them can't hide them.
|
||||
let curves = prims.iter().enumerate().filter_map(|(i, p)| match p {
|
||||
Prim::Circle(c) => Some((c.center, c.closest(cursor), i)),
|
||||
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor), i)),
|
||||
Prim::Ellipse(e) => Some((e.center, e.closest(cursor), i)),
|
||||
_ => None,
|
||||
});
|
||||
for (center, on, i) in curves.take(2000) {
|
||||
let d = on.dist(cursor);
|
||||
if center.is_finite() && d.is_finite() && d <= aperture {
|
||||
out.push((d, center, i));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Prefer more specific modes when nearly equidistant.
|
||||
@@ -763,6 +956,63 @@ fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
|
||||
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A perpendicular ([`mode::PER`]) or tangent ([`mode::TAN`]) point found from the base point,
|
||||
/// with the index in `near_prims` of the object it lies on.
|
||||
struct FromBase {
|
||||
mode: u32,
|
||||
point: Vec2,
|
||||
prim: usize,
|
||||
}
|
||||
|
||||
/// The perpendiculars and tangents from the base point on the objects that pass within
|
||||
/// `aperture` of the cursor, wherever the foot or tangent point lies (#2800), each with its
|
||||
/// [`Rank`] (tier 1, scored by the cursor's distance to the object) and its distance to the cursor.
|
||||
///
|
||||
/// These snaps name an object, not a spot on it: you can't know in advance where the foot of a
|
||||
/// perpendicular will be, so, as in AutoCAD, hovering anywhere over the object finds it and the
|
||||
/// point jumps there. [`finish`] asks for this only when no snap point lies within the aperture,
|
||||
/// so an endpoint, midpoint or intersection under the cursor still wins.
|
||||
///
|
||||
/// [`finish`] takes the object nearest the cursor; of several points on it (an arc's two
|
||||
/// antipodes, a circle's two tangents), the one nearest the cursor.
|
||||
fn from_base_on_objects(
|
||||
found: &[FromBase],
|
||||
near_prims: &[Prim],
|
||||
sources: &[Option<SnapSource>],
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
visible: impl Fn(Vec2) -> bool,
|
||||
) -> Vec<(SnapHit, Rank, f64)> {
|
||||
let mut out = Vec::new();
|
||||
if found.is_empty() {
|
||||
return out;
|
||||
}
|
||||
// `near_prims` holds every object whose box comes near the cursor, so the true distance is
|
||||
// checked here. It is measured once per object, and only for objects with a point to offer:
|
||||
// an ellipse or a spline is measured on its tessellation.
|
||||
let mut reach: Vec<Option<f64>> = vec![None; near_prims.len()];
|
||||
for f in found.iter().filter(|f| visible(f.point)) {
|
||||
let Some(slot) = reach.get_mut(f.prim) else { continue };
|
||||
let to_object = *slot.get_or_insert_with(|| near_prims.get(f.prim).map_or(f64::INFINITY, |p| distance_to_prim(p, cursor)));
|
||||
// A NaN distance (from a degenerate object) never qualifies.
|
||||
if to_object.is_nan() || to_object > aperture {
|
||||
continue;
|
||||
}
|
||||
let source = sources.get(f.prim).copied().flatten();
|
||||
out.push((SnapHit { source, ..SnapHit::plain(f.mode, f.point) }, Rank { tier: 1, score: to_object }, f.point.dist(cursor)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The distance from `cursor` to the nearest point of `p`, measured as Nearest measures it.
|
||||
fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
|
||||
// A ray runs one way from its start (an xline both ways, as its segment does).
|
||||
if let Prim::Infinite { base, dir, ray: true } = p {
|
||||
return (*base + *dir * (cursor - *base).dot(*dir).max(0.0)).dist(cursor);
|
||||
}
|
||||
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
|
||||
const MAX_BLOCK_LEAVES: usize = 20_000;
|
||||
|
||||
@@ -1140,11 +1390,15 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
|
||||
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
|
||||
/// perpendicular on the same circle. `sources` is parallel to `prims`.
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
|
||||
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
|
||||
/// perpendicular on the same circle, and to the deferred snap of each curve nearby. A click takes
|
||||
/// the nearest one ([`deferred_hit`]).
|
||||
fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||
let mut hits = Vec::new();
|
||||
if osmode & (mode::TAN | mode::PER) == 0 {
|
||||
return hits;
|
||||
}
|
||||
for (i, p) in prims.iter().enumerate() {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
@@ -1178,6 +1432,46 @@ fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, a
|
||||
hits
|
||||
}
|
||||
|
||||
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
|
||||
fn deferred_hit(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
|
||||
let mut best: Option<(f64, SnapHit)> = None;
|
||||
for (i, p) in prims.iter().enumerate() {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
|
||||
Prim::Seg(Segment::Line(l)) => SnapCurve::Line { a: l.a, b: l.b },
|
||||
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||
_ => continue,
|
||||
};
|
||||
let (m, name, at) = match curve {
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||
let source = sources.get(i).copied().flatten();
|
||||
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }), source }));
|
||||
}
|
||||
}
|
||||
best.map(|(_, h)| h)
|
||||
}
|
||||
|
||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||
/// endpoints (in the order given), or `None` when there is no such line (a point inside the
|
||||
/// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to
|
||||
@@ -1449,7 +1743,7 @@ mod tests {
|
||||
let frozen = ["vp".to_string()];
|
||||
let end = |x: f64, y: f64| {
|
||||
let at = Vec2::new(x, y);
|
||||
osnap_in(&d, &Space::Model, &None, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen, None)
|
||||
osnap_all_with_frozen(&d, &Space::Model, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen)
|
||||
.into_iter()
|
||||
.any(|h| h.point.dist(at) < 1e-9)
|
||||
};
|
||||
@@ -1632,21 +1926,22 @@ mod tests {
|
||||
assert_eq!(h.name, "Intersection");
|
||||
}
|
||||
|
||||
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
|
||||
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
|
||||
/// picks.
|
||||
/// Tab cycling sees every snap within the aperture: snap points nearest first (Intersection
|
||||
/// favoured), then Nearest on each object, and no snap twice; the first is what `osnap` picks.
|
||||
/// On a circle with no base point, its quadrant, then the deferred tangent and the deferred
|
||||
/// perpendicular at the same spot.
|
||||
#[test]
|
||||
fn osnap_all_ranks_every_candidate() {
|
||||
let d = drawing();
|
||||
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
|
||||
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
|
||||
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
|
||||
let (cursor, modes) = (Vec2::new(5.2, 0.2), mode::END | mode::MID | mode::INT | mode::NEA);
|
||||
let all = osnap_all(&d, &Space::Model, cursor, 0.5, modes, None, false);
|
||||
// Both lines' midpoints are the intersection point: one Midpoint. Each line has its Nearest.
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA, mode::NEA], "{all:?}");
|
||||
assert_eq!(all.first().map(|h| h.point), osnap(&d, &Space::Model, cursor, 0.5, modes, None, false).map(|h| h.point));
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
||||
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
||||
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1665,6 +1960,70 @@ mod tests {
|
||||
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
/// #2800: hovering anywhere over the line finds the perpendicular, though its foot (2,0) is
|
||||
/// six units from the cursor; it used to snap only within the aperture of the foot.
|
||||
#[test]
|
||||
fn perpendicular_from_base_anywhere_on_the_line() {
|
||||
let d = drawing();
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(8.0, 0.1), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(2.0, 0.0), 1e-9), "{h:?}");
|
||||
assert_eq!(h.mode, mode::PER);
|
||||
}
|
||||
|
||||
/// #2800: the tangent point is found from anywhere on the circle; of its two tangent points
|
||||
/// from the base, the one nearer the cursor.
|
||||
#[test]
|
||||
fn tangent_from_base_anywhere_on_the_circle() {
|
||||
let d = drawing();
|
||||
// From (30,0), 10 from the centre (20,0) of the radius-2 circle: the tangent points are
|
||||
// at cos = 2/10 from the line to the base, (20.4, ±1.9596).
|
||||
let upper = Vec2::new(20.4, 2.0 * (1.0f64 - 0.04).sqrt());
|
||||
let on_circle = Vec2::new(20.0 - 2.0 * std::f64::consts::FRAC_1_SQRT_2, 2.0 * std::f64::consts::FRAC_1_SQRT_2);
|
||||
let h = osnap(&d, &Space::Model, on_circle, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||
assert!(h.point.near(upper, 1e-9), "{h:?}");
|
||||
let mirrored = Vec2::new(on_circle.x, -on_circle.y);
|
||||
let h = osnap(&d, &Space::Model, mirrored, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(upper.x, -upper.y), 1e-9), "{h:?}");
|
||||
}
|
||||
|
||||
/// A circle offers both perpendicular points from the base, so a pick on its far side snaps
|
||||
/// there, not to the near side across the circle (CodeRabbit on #2825).
|
||||
#[test]
|
||||
fn perpendicular_from_base_on_a_circle_takes_the_side_under_the_cursor() {
|
||||
let d = drawing();
|
||||
// The circle at (20,0), radius 2, seen from (30,0): perpendicular at (22,0) and (18,0).
|
||||
let base = Some(Vec2::new(30.0, 0.0));
|
||||
let far = osnap(&d, &Space::Model, Vec2::new(18.1, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(far.point.near(Vec2::new(18.0, 0.0), 1e-9), "{far:?}");
|
||||
// Away from both points, at (19, √3) on the circle: 2 from (18,0) and √12 from (22,0).
|
||||
let top = osnap(&d, &Space::Model, Vec2::new(19.0, 3.0f64.sqrt()), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(top.point.near(Vec2::new(18.0, 0.0), 1e-9), "{top:?}");
|
||||
let near = osnap(&d, &Space::Model, Vec2::new(21.9, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(near.point.near(Vec2::new(22.0, 0.0), 1e-9), "{near:?}");
|
||||
}
|
||||
|
||||
/// With several objects under the aperture, the one nearest the cursor gives the
|
||||
/// perpendicular, even when another object's foot is nearer.
|
||||
#[test]
|
||||
fn perpendicular_from_base_takes_the_object_nearest_the_cursor() {
|
||||
let d = drawing();
|
||||
// 0.4 above the horizontal line and 0.2 right of the vertical one: the vertical line wins,
|
||||
// with its foot (5,4) farther from the cursor than the horizontal line's (2,0).
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.4), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(5.0, 4.0), 1e-9), "{h:?}");
|
||||
}
|
||||
|
||||
/// A snap point under the cursor still beats a perpendicular whose foot is away from it, and
|
||||
/// an object outside the aperture gives none, though its box is near.
|
||||
#[test]
|
||||
fn perpendicular_from_base_yields_to_points_under_the_cursor() {
|
||||
let d = drawing();
|
||||
let base = Some(Vec2::new(2.0, 4.0));
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(9.9, 0.05), 0.5, mode::END | mode::PER, base, false).unwrap();
|
||||
assert_eq!((h.point, h.mode), (Vec2::new(10.0, 0.0), mode::END));
|
||||
assert!(osnap(&d, &Space::Model, Vec2::new(8.0, 0.7), 0.5, mode::PER, base, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ortho_and_polar() {
|
||||
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
|
||||
@@ -1707,9 +2066,14 @@ mod tests {
|
||||
let df = h.deferred.unwrap();
|
||||
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
|
||||
assert_eq!(h.input(), crate::Input::Deferred(df));
|
||||
// With a base it is an ordinary tangent.
|
||||
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
||||
// With a base it is an ordinary tangent, unless the prompt resolves it (CIRCLE's radius).
|
||||
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), false).unwrap();
|
||||
assert!(t.deferred.is_none() && t.name == "Tangent");
|
||||
let t = osnap(&d, &Space::Model, at, 0.5, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
||||
assert_eq!(t.name, "Deferred Tangent");
|
||||
// A perpendicular from the base is still resolved from it.
|
||||
let p = osnap(&d, &Space::Model, Vec2::new(2.0, 0.2), 0.5, mode::PER, Some(Vec2::new(2.0, 5.0)), true).unwrap();
|
||||
assert!(p.deferred.is_none() && p.point.near(Vec2::new(2.0, 0.0), 1e-9));
|
||||
// A specific snap still wins over a deferred one.
|
||||
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
|
||||
assert_eq!(q.mode, mode::QUA);
|
||||
|
||||
@@ -482,13 +482,38 @@ impl Tracker {
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
) -> Option<Track> {
|
||||
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
|
||||
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn track_with_frozen(
|
||||
&mut self,
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
tol: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Track> {
|
||||
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
|
||||
self.last = t.clone();
|
||||
t
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
|
||||
fn find(
|
||||
&self,
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
tol: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Track> {
|
||||
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -538,7 +563,7 @@ impl Tracker {
|
||||
// 2. A path crossing an object.
|
||||
if cfg.running(mode::INT | mode::APP) {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
||||
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
|
||||
for prim in prims.iter().take(200) {
|
||||
let extend = cfg.running(mode::APP) && super::extendable(prim);
|
||||
for seg in super::prim_segments(prim) {
|
||||
@@ -588,12 +613,26 @@ pub fn candidate(
|
||||
aperture: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
) -> Option<Acquired> {
|
||||
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn candidate_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
hit: Option<&SnapHit>,
|
||||
aperture: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Acquired> {
|
||||
if !can_acquire(cursor, aperture, cfg) {
|
||||
return None;
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
||||
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
|
||||
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
|
||||
}
|
||||
|
||||
@@ -789,7 +828,7 @@ impl crate::Session {
|
||||
s.orthomode ^= q.shift;
|
||||
let angbase = self.angle_settings().angbase;
|
||||
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
|
||||
let (doc, space) = (st.doc.clone(), st.edit_space());
|
||||
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
|
||||
if !raw.is_finite() {
|
||||
return CursorSnap { point: raw, ..Default::default() };
|
||||
}
|
||||
@@ -798,10 +837,10 @@ impl crate::Session {
|
||||
let cfg = TrackConfig::relative_to(&s, angbase, last);
|
||||
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
|
||||
let ix = crate::spatial::index(&doc, &space);
|
||||
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
|
||||
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
|
||||
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
|
||||
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
|
||||
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
|
||||
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
|
||||
};
|
||||
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
|
||||
if let Some(h) = hit {
|
||||
@@ -816,7 +855,7 @@ impl crate::Session {
|
||||
let (origin, angle) = super::grid_frame_in(&doc, &space);
|
||||
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
|
||||
}
|
||||
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
|
||||
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
|
||||
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
|
||||
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
|
||||
if s.snapmode
|
||||
|
||||
@@ -7,7 +7,14 @@ use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_
|
||||
|
||||
mod table;
|
||||
|
||||
/// ACADVER: the program's release, as a text AutoCAD documents it and `atof` reads back as a
|
||||
/// number. A drawing's `$ACADVER` header is its file version, which is what a save writes, so the
|
||||
/// two are separate values: `get` gives this text, `list` too, and the header stays as read.
|
||||
pub const ACADVER_TEXT: &str = "24.3s (CADCraft)";
|
||||
|
||||
const SESSION_VARS: &[&str] = &[
|
||||
// The release text, with or without a drawing (the header's `$ACADVER` is the file version).
|
||||
"ACADVER",
|
||||
"AUDITCTL",
|
||||
"ATTREQ",
|
||||
"OSMODE",
|
||||
@@ -81,10 +88,54 @@ const SESSION_VARS: &[&str] = &[
|
||||
"SAVETIME",
|
||||
"SAVEFILEPATH",
|
||||
"ISAVEBAK",
|
||||
"DIMASO",
|
||||
"TEXTEVAL",
|
||||
"POPUPS",
|
||||
];
|
||||
|
||||
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
/// The DIMASSOC mode DIMASO turned off, kept in the drawing's header so undo restores it.
|
||||
/// `CADCRAFT_` names are not listed by SYSVARS and no file writes this one.
|
||||
const DIMASO_MODE: &str = "CADCRAFT_DIMASO_MODE";
|
||||
|
||||
/// The header key above, under any number of `$`: no variable of that name exists.
|
||||
fn is_internal(n: &str) -> bool {
|
||||
n.trim_start_matches('$') == DIMASO_MODE
|
||||
}
|
||||
|
||||
/// The names this session also answers with DXF's `$` in front: the header writes them that way
|
||||
/// (`$DIMASO`, `$TEXTEVAL`, `$REGENMODE`, `$POPUPS`), so a routine may type either form.
|
||||
const DOLLAR_VARS: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"];
|
||||
|
||||
/// [`set`] takes only a number for these: a program's or a routine's text is refused. A value
|
||||
/// typed at the command line arrives as text and goes through [`typed_value`] first.
|
||||
const NUMBER_ONLY: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE"];
|
||||
|
||||
/// The value of `text` typed at a SETVAR prompt for `name`: typed digits are a number for the
|
||||
/// [`NUMBER_ONLY`] variables. Anything else stays text.
|
||||
pub(crate) fn typed_value(name: &str, text: String) -> Value {
|
||||
if NUMBER_ONLY.contains(&bare_name(name).as_str())
|
||||
&& let Ok(number) = text.trim().parse::<i64>()
|
||||
{
|
||||
return json!(number);
|
||||
}
|
||||
Value::String(text)
|
||||
}
|
||||
|
||||
/// `name` trimmed and upper case, without the `$` those names take. Every other name keeps the
|
||||
/// `$` it was typed with: `$ANGBASE` stays a name of its own (LISP converts radians only for the
|
||||
/// plain name) and `$OSMODE` is not the session's OSMODE.
|
||||
fn bare_name(name: &str) -> String {
|
||||
let n = name.trim().to_ascii_uppercase();
|
||||
// Every leading `$`, as the header drops them all when it stores a value.
|
||||
let rest = n.trim_start_matches('$');
|
||||
if rest.len() < n.len() && DOLLAR_VARS.contains(&rest) { rest.to_string() } else { n }
|
||||
}
|
||||
|
||||
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
let n = bare_name(name);
|
||||
if is_internal(&n) {
|
||||
return None;
|
||||
}
|
||||
let st = &s.settings;
|
||||
let v = match n.as_str() {
|
||||
"OSMODE" => json!(st.osmode),
|
||||
@@ -177,6 +228,12 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"SAVETIME" => json!(crate::autosave::savetime()),
|
||||
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
|
||||
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
|
||||
// DIMASO is obsolete in AutoCAD and has no value of its own: it reports DIMASSOC.
|
||||
"DIMASO" => json!(i32::from(matches!(dimassoc(s)?, 1 | 2))),
|
||||
// Whether a prompt reads typed text as LISP (routines switch it around their prompts).
|
||||
"TEXTEVAL" => json!(i32::from(st.texteval)),
|
||||
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
|
||||
"POPUPS" => json!(1),
|
||||
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
|
||||
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
|
||||
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
|
||||
@@ -189,6 +246,9 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
|
||||
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
|
||||
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
|
||||
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
|
||||
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
|
||||
"ACADVER" => json!(ACADVER_TEXT),
|
||||
"PLATFORM" => json!(std::env::consts::OS),
|
||||
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
|
||||
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
|
||||
@@ -257,6 +317,11 @@ fn dwg_prefix(path: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// DIMASSOC's value (0 off, 1 or 2 associative), read where DIMASO reports it from.
|
||||
fn dimassoc(s: &Session) -> Option<i64> {
|
||||
table::get(s, "DIMASSOC")?.as_i64()
|
||||
}
|
||||
|
||||
fn as_bool(v: &Value) -> Option<bool> {
|
||||
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
|
||||
}
|
||||
@@ -277,6 +342,7 @@ fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
|
||||
|
||||
/// Variables `get` reports from session or drawing state that `set` can't change.
|
||||
const READ_ONLY: &[&str] = &[
|
||||
"ACADVER",
|
||||
"CMDNAMES",
|
||||
"DWGNAME",
|
||||
"DWGPREFIX",
|
||||
@@ -304,10 +370,15 @@ const READ_ONLY: &[&str] = &[
|
||||
"UCSXDIR",
|
||||
"UCSYDIR",
|
||||
"WORLDUCS",
|
||||
// Dialogs: a session always has them, so the variable is fixed (not saved).
|
||||
"POPUPS",
|
||||
];
|
||||
|
||||
pub fn is_read_only(name: &str) -> bool {
|
||||
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase())
|
||||
// A header name's `$` is ignored: the header drops it when it stores a value, so `$ACADVER`
|
||||
// would otherwise change ACADVER, and with it the version a save writes.
|
||||
let n = name.trim().trim_start_matches('$').trim();
|
||||
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(n)) || table::is_read_only(&n.to_ascii_uppercase())
|
||||
}
|
||||
|
||||
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
|
||||
@@ -325,11 +396,17 @@ pub fn format_angle_list(angles: &[f64]) -> String {
|
||||
|
||||
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
|
||||
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
let n = name.trim().to_ascii_uppercase();
|
||||
let n = bare_name(name);
|
||||
if is_internal(&n) {
|
||||
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("unknown variable `{n}`") });
|
||||
}
|
||||
if is_read_only(&n) {
|
||||
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
|
||||
}
|
||||
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
|
||||
if NUMBER_ONLY.contains(&n.as_str()) && !v.is_number() {
|
||||
return Err(bad());
|
||||
}
|
||||
let st = &mut s.settings;
|
||||
match n.as_str() {
|
||||
"OSMODE" => {
|
||||
@@ -436,6 +513,35 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
}
|
||||
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
|
||||
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
|
||||
// DIMASO has no value of its own: 0 turns DIMASSOC off (remembering the mode it had),
|
||||
// 1 restores that mode (2 when none was seen), and 1 while it is on changes nothing. The
|
||||
// mode it remembers is in the drawing's header ([`DIMASO_MODE`]), so each open drawing
|
||||
// keeps its own and undo restores it with DIMASSOC; no file writes it.
|
||||
"DIMASO" => {
|
||||
let on = as_i(v).filter(|i| matches!(i, 0 | 1)).ok_or_else(bad)? == 1;
|
||||
let mode = dimassoc(s).ok_or_else(bad)?;
|
||||
// The drawing is touched only when DIMASSOC changes, so it is not marked modified
|
||||
// and no undo step is left for a value it already has.
|
||||
match (on, mode) {
|
||||
(true, 1 | 2) | (false, 0) => {}
|
||||
// Turned back on, from off or from a file's unknown mode: the mode it had.
|
||||
(true, _) => {
|
||||
let h = &mut s.doc_mut()?.header;
|
||||
// Only a mode DIMASSOC takes: a file's value of anything else restores 2.
|
||||
let restore = h.i64(DIMASO_MODE, 2);
|
||||
h.set_i64("DIMASSOC", if matches!(restore, 1 | 2) { restore } else { 2 });
|
||||
}
|
||||
(false, _) => {
|
||||
let h = &mut s.doc_mut()?.header;
|
||||
if matches!(mode, 1 | 2) {
|
||||
h.set_i64(DIMASO_MODE, mode);
|
||||
}
|
||||
h.set_i64("DIMASSOC", 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stored for routines that switch it around their prompts; no prompt reads it yet.
|
||||
"TEXTEVAL" => st.texteval = small(v, 1).ok_or_else(bad)? == 1,
|
||||
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
|
||||
"ANGBASE" => {
|
||||
let a = match v {
|
||||
|
||||
@@ -73,6 +73,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
|
||||
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
|
||||
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||
// 1 regenerates the drawing after a command that changes it (stored, nothing reads it yet).
|
||||
("REGENMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
|
||||
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
|
||||
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
|
||||
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
|
||||
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
|
||||
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::lisp::value::Value;
|
||||
use serde_json::json;
|
||||
|
||||
/// The release text `getvar` and `(getvar "ACADVER")` report.
|
||||
const RELEASE: &str = "24.3s (CADCraft)";
|
||||
|
||||
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n\
|
||||
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
/// A LISP expression's value, or its error message.
|
||||
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
|
||||
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||
Ok(Some(Ok(v))) => Ok(v),
|
||||
Ok(Some(Err(e))) => Err(e),
|
||||
Ok(None) => Err("did not finish".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// GETVAR's value.
|
||||
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
|
||||
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||
}
|
||||
|
||||
/// The `$ACADVER` a DXF text declares.
|
||||
fn file_version(text: &str) -> Option<String> {
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
|
||||
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
|
||||
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
|
||||
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setvar_refuses_acadver_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let before = s.state().unwrap().doc.header.str("ACADVER", "");
|
||||
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
|
||||
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
|
||||
s.cmdline("setvar acadver").unwrap();
|
||||
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
|
||||
// Neither the release text nor the drawing's file version moved.
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
|
||||
assert_eq!(before, "AC1032");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2000_drawing_saves_as_2000() {
|
||||
crate::refedit_xref::hooks();
|
||||
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("r2000.dxf");
|
||||
let name = path.to_string_lossy().into_owned();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
|
||||
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
|
||||
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
let saved = std::fs::read_to_string(&path).unwrap();
|
||||
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dollar_name_cannot_change_the_file_version() {
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
|
||||
// Other `$` names still reach the header as before, in LISP's units.
|
||||
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
|
||||
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
|
||||
assert_eq!(r["value"], json!(9), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listings_show_the_release_text_without_a_drawing() {
|
||||
let mut s = Session::empty();
|
||||
let all = s.execute("sysvars", &json!({})).unwrap();
|
||||
let text = all.to_string();
|
||||
assert!(text.contains(RELEASE), "{text}");
|
||||
let mut s = Session::new();
|
||||
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
|
||||
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
|
||||
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
|
||||
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
|
||||
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
|
||||
//! associativity changed.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn getvar(s: &mut Session, name: &str) -> Value {
|
||||
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||
}
|
||||
|
||||
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
|
||||
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
|
||||
}
|
||||
|
||||
/// The value of a LISP expression, or the error it left.
|
||||
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
|
||||
match s.lisp_eval(src, false, true, Vec::new()) {
|
||||
Ok(Some(v)) => v,
|
||||
Ok(None) => Err("no value".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `(getvar name)` as the integer a routine receives.
|
||||
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
|
||||
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
|
||||
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
|
||||
n as i64
|
||||
}
|
||||
|
||||
/// `(setvar name value)` from LISP: whether it was accepted.
|
||||
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
|
||||
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
|
||||
}
|
||||
|
||||
/// The DXF pairs `(group code, value)` of a file, both trimmed.
|
||||
fn pairs(text: &str) -> Vec<(i32, String)> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out = Vec::new();
|
||||
for chunk in lines.chunks(2) {
|
||||
let [code, value] = chunk else { break };
|
||||
let Ok(c) = code.parse::<i32>() else { continue };
|
||||
out.push((c, (*value).to_string()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The HEADER variable names a DXF text writes (the value after each group code 9).
|
||||
fn header_names(text: &str) -> Vec<String> {
|
||||
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
|
||||
}
|
||||
|
||||
/// The integer a header variable is written with, as `(group code, value)` after its name.
|
||||
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
|
||||
let ps = pairs(text);
|
||||
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
|
||||
ps.get(i + 1).cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_values_are_integers_a_routine_reads() {
|
||||
let mut s = Session::new();
|
||||
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
|
||||
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
|
||||
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
|
||||
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
|
||||
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
|
||||
}
|
||||
// The list a routine sees (`SETVAR ?`) carries them too.
|
||||
let all = cadcraft_engine::sysvars::list(&s);
|
||||
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
|
||||
let mut s = Session::new();
|
||||
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||
let before = lisp_getvar(&mut s, name);
|
||||
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
|
||||
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
|
||||
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
|
||||
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
|
||||
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
|
||||
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
|
||||
}
|
||||
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
|
||||
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
|
||||
// The routine's save/restore through DIMASO, for each associative mode.
|
||||
for mode in [1, 2] {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
|
||||
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
|
||||
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
|
||||
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
|
||||
}
|
||||
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
|
||||
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
|
||||
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_setvar_still_takes_digits() {
|
||||
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||
let want = json!(digits.parse::<i64>().unwrap());
|
||||
let dollar = format!("${name}");
|
||||
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
|
||||
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
|
||||
let mut s = Session::new();
|
||||
for line in &lines {
|
||||
s.cmdline(line).unwrap();
|
||||
}
|
||||
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
|
||||
}
|
||||
// A routine that types the command passes its answers the same way.
|
||||
let mut s = Session::new();
|
||||
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
|
||||
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
|
||||
// Typed words are still refused.
|
||||
let mut s = Session::new();
|
||||
let before = getvar(&mut s, name);
|
||||
for line in ["setvar", name, "two"] {
|
||||
s.cmdline(line).unwrap();
|
||||
}
|
||||
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_drawing_writes_regenmode() {
|
||||
let mut s = Session::new();
|
||||
// The first drawing, then a new metric and a new imperial one.
|
||||
for metric in [None, Some(true), Some(false)] {
|
||||
if let Some(metric) = metric {
|
||||
s.new_drawing(metric);
|
||||
}
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_are_refused_and_change_nothing() {
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [
|
||||
("REGENMODE", json!(2)),
|
||||
("REGENMODE", json!(-1)),
|
||||
("REGENMODE", json!(1.5)),
|
||||
("REGENMODE", json!("two")),
|
||||
("REGENMODE", Value::Null),
|
||||
("TEXTEVAL", json!(-1)),
|
||||
("TEXTEVAL", json!(2)),
|
||||
("TEXTEVAL", json!("two")),
|
||||
("TEXTEVAL", Value::Null),
|
||||
("DIMASO", json!(3)),
|
||||
("DIMASO", json!(-1)),
|
||||
("DIMASO", json!(0.5)),
|
||||
("DIMASO", json!("two")),
|
||||
("DIMASO", Value::Null),
|
||||
// Text a program or a routine passes is refused even when it spells a number.
|
||||
("REGENMODE", json!("0")),
|
||||
("TEXTEVAL", json!("1")),
|
||||
("DIMASO", json!("0")),
|
||||
("TEXTEVAL", json!(true)),
|
||||
] {
|
||||
let before = getvar(&mut s, name);
|
||||
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
|
||||
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
|
||||
}
|
||||
// The drawing's associativity is untouched by a refused DIMASO.
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(!setvar(&mut s, "DIMASO", json!(3)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
|
||||
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
|
||||
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
|
||||
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
|
||||
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
|
||||
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
|
||||
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
|
||||
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popups_is_read_only() {
|
||||
let mut s = Session::new();
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
|
||||
for v in [json!(1), json!(0), json!("1")] {
|
||||
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{v}: {e}");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
|
||||
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "REGENMODE", json!(0)));
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
|
||||
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
|
||||
// A reopened drawing has the value it was saved with, and saves it back.
|
||||
let mut back = Session::new();
|
||||
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
|
||||
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
|
||||
let again = cadcraft_io::write_dxf(back.doc().unwrap());
|
||||
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texteval_dimaso_and_popups_are_not_saved() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let names = header_names(&text);
|
||||
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
|
||||
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
|
||||
}
|
||||
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
|
||||
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_remembers_the_mode_of_each_open_drawing() {
|
||||
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
|
||||
// between each put back the DIMASSOC mode they had.
|
||||
let mut s = Session::new();
|
||||
let first = s.active;
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
let second = s.new_drawing(true);
|
||||
assert_eq!(second, first + 1);
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
s.execute("document.switch", &json!({ "index": first })).unwrap();
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
|
||||
s.execute("document.switch", &json!({ "index": second })).unwrap();
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dollar_forms_are_the_same_variables() {
|
||||
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
|
||||
// the command line takes them that way too, in any case and with spaces around them.
|
||||
let mut s = Session::new();
|
||||
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||
let plain = getvar(&mut s, name);
|
||||
let dollar = format!("${name}");
|
||||
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
|
||||
let typed = format!(" ${} ", name.to_ascii_lowercase());
|
||||
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
|
||||
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
|
||||
}
|
||||
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "$DIMASO", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
|
||||
assert!(setvar(&mut s, " $dimaso ", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
|
||||
// TEXTEVAL: set under one name, read under the other.
|
||||
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
|
||||
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
|
||||
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
|
||||
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
|
||||
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
|
||||
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
|
||||
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
|
||||
// POPUPS is read-only under its DXF name too.
|
||||
for v in [json!(0), json!("1")] {
|
||||
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
|
||||
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_dollar_names_keep_their_own_handling() {
|
||||
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
|
||||
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
|
||||
let mut s = Session::new();
|
||||
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
|
||||
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
|
||||
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
|
||||
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
|
||||
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
|
||||
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_puts_back_the_mode_dimaso_remembers() {
|
||||
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
|
||||
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
|
||||
}
|
||||
s.cmdline("u").unwrap();
|
||||
s.cmdline("u").unwrap();
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_dollars_are_the_same_variables() {
|
||||
let mut s = Session::new();
|
||||
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
|
||||
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
|
||||
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
|
||||
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
|
||||
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
|
||||
}
|
||||
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
|
||||
// Saved and read back, the drawing has lost nothing a save keeps.
|
||||
let before = s.doc().unwrap().clone();
|
||||
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
|
||||
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
|
||||
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
mod acadver;
|
||||
mod angle_prompts;
|
||||
mod angle_settings;
|
||||
mod annotate_options;
|
||||
@@ -104,6 +105,7 @@ mod layout_prompts;
|
||||
mod leader_command;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod leader_text_scale;
|
||||
mod legacy_sysvars;
|
||||
mod lisp_answer_by_frames;
|
||||
mod lisp_corpus;
|
||||
mod lisp_findfile;
|
||||
@@ -135,6 +137,7 @@ mod offset_ellipse_side;
|
||||
mod offset_move;
|
||||
mod oops_command;
|
||||
mod options_profile;
|
||||
mod osnap_opened_drawings;
|
||||
mod overkill;
|
||||
mod parallel_display_list;
|
||||
mod pedit_heights;
|
||||
@@ -185,10 +188,12 @@ mod setvar_coverage;
|
||||
mod shapes;
|
||||
mod snap_annotations;
|
||||
mod snap_blocks;
|
||||
mod snap_center_on_curve;
|
||||
mod snap_curves;
|
||||
mod snap_intersections_aperture;
|
||||
mod snap_nearest;
|
||||
mod snap_overrides;
|
||||
mod snap_tab_cycling;
|
||||
mod snap_tracking;
|
||||
mod snap_z;
|
||||
mod snaps_more;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
|
||||
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
@@ -307,22 +308,22 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
||||
}
|
||||
|
||||
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
|
||||
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
|
||||
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
|
||||
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
|
||||
/// still reaches the paper-space Nearest.
|
||||
#[test]
|
||||
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
|
||||
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
|
||||
let (mut d, paper) = drawing();
|
||||
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
||||
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
||||
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
||||
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
|
||||
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
|
||||
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
|
||||
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
||||
assert!(
|
||||
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
|
||||
"Tab reaches the viewport's endpoint: {all:?}"
|
||||
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
|
||||
"Tab reaches the paper-space Nearest: {all:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -458,3 +459,50 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
|
||||
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
|
||||
#[test]
|
||||
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
|
||||
let (mut d, paper) = drawing();
|
||||
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
|
||||
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
|
||||
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
|
||||
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
|
||||
let vp = viewport(&d, &paper);
|
||||
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
|
||||
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
|
||||
let cursor = Vec2::new(102.5, 59.995);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
|
||||
let model = hit.viewport.expect("seen through the viewport").point;
|
||||
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_twisted_viewport_offers_the_visible_perpendicular_when_a_nearer_one_is_off_the_sheet() {
|
||||
// A viewport twisted 45°, 20 square at 0,0 on the sheet, scale 1. Through it, a line along
|
||||
// y = 0 under the cursor and one along x = 9.3 (sheet coordinates). From the base 12,3 the
|
||||
// foot on the first, 12,0, is inside the turned model box but off the viewport; the foot on
|
||||
// the second, 9.3,3, is on it.
|
||||
let mut d = Drawing::new_imperial();
|
||||
let paper = Space::Paper("Layout1".into());
|
||||
let vp = Viewport {
|
||||
center: Vec3::ZERO,
|
||||
width: 20.0,
|
||||
height: 20.0,
|
||||
view_center: Vec2::ZERO,
|
||||
view_height: 20.0,
|
||||
id: 2,
|
||||
twist: std::f64::consts::FRAC_PI_4,
|
||||
..Viewport::default()
|
||||
};
|
||||
for (a, b) in [(Vec2::new(-9.0, 0.0), Vec2::new(30.0, 0.0)), (Vec2::new(9.3, -9.0), Vec2::new(9.3, 9.0))] {
|
||||
let (a, b) = (vp.paper_to_model(a), vp.paper_to_model(b));
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })).unwrap();
|
||||
}
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
let hit = osnap(&d, &paper, Vec2::new(9.0, 0.0), 0.5, mode::PER, Some(Vec2::new(12.0, 3.0)), false).expect("the visible foot");
|
||||
assert_eq!(hit.mode, mode::PER);
|
||||
assert!(hit.point.near(Vec2::new(9.3, 3.0), 1e-9), "{hit:?}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
|
||||
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
|
||||
//!
|
||||
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
|
||||
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
|
||||
//! variable, 0 included, never changes the running snaps.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Drawing;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
|
||||
use serde_json::json;
|
||||
|
||||
/// AutoCAD's default running snaps.
|
||||
const DEFAULT: u32 = 4133;
|
||||
|
||||
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||
let a = deg.to_radians();
|
||||
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||
}
|
||||
|
||||
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
|
||||
fn draw(s: &mut Session) {
|
||||
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
|
||||
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
|
||||
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
|
||||
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
|
||||
}
|
||||
|
||||
fn drawing() -> Drawing {
|
||||
let mut s = Session::new();
|
||||
draw(&mut s);
|
||||
s.doc().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
|
||||
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
|
||||
if s.running.is_none() {
|
||||
s.start("line").unwrap();
|
||||
}
|
||||
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||
let r = s.snap_cursor(cursor, &q);
|
||||
r.snap.map(|h| (r.point, h.mode))
|
||||
}
|
||||
|
||||
fn assert_snaps(s: &mut Session, what: &str) {
|
||||
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
|
||||
let cases = [
|
||||
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
|
||||
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
|
||||
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
|
||||
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
|
||||
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
|
||||
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
|
||||
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
|
||||
];
|
||||
for (name, cursor, want, modes) in cases {
|
||||
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
|
||||
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
|
||||
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
|
||||
}
|
||||
// Away from everything: nothing.
|
||||
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
|
||||
// F3 off: nothing; on again: back.
|
||||
s.execute("osnap", &json!({})).unwrap();
|
||||
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
|
||||
s.execute("osnap", &json!({})).unwrap();
|
||||
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_snaps_work_in_a_fresh_drawing() {
|
||||
let mut s = Session::new();
|
||||
draw(&mut s);
|
||||
assert_snaps(&mut s, "fresh drawing");
|
||||
}
|
||||
|
||||
/// `text` with `$OSMODE` set to `value` at the top of its header.
|
||||
fn with_osmode(text: &str, value: u32) -> String {
|
||||
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
|
||||
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
||||
let (head, tail) = text.split_at(at);
|
||||
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
|
||||
let clean = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
|
||||
let text = with_osmode(&clean, 0);
|
||||
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
|
||||
let mut s = Session::new();
|
||||
// OSMODE is the profile's: the user's own choice survives opening the file.
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
|
||||
s.open_drawing(d, "snaps.dxf", None);
|
||||
assert_snaps(&mut s, "DXF with $OSMODE 0");
|
||||
// Nor does a file change a profile without Center.
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
|
||||
let text = with_osmode(&clean, DEFAULT);
|
||||
assert_eq!(text.matches("$OSMODE").count(), 1, "one $OSMODE in the file");
|
||||
s.open_drawing(cadcraft_io::read(text.as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
|
||||
assert_eq!(s.settings.osmode, mode::END);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
|
||||
// The drawing is the test's own, so it is converted in this process.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
|
||||
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
|
||||
let mut s = Session::new();
|
||||
s.open_drawing(d, "snaps.dwg", None);
|
||||
assert_snaps(&mut s, "DWG");
|
||||
}
|
||||
@@ -11,7 +11,9 @@ use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, I
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hooks() {
|
||||
/// The real file formats, for every test in this binary that opens or saves files (the hooks are
|
||||
/// process-wide and the first ones set stay).
|
||||
pub(crate) fn hooks() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
|
||||
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
|
||||
//! center, however far away it is. Before, the center was only found with the cursor on the
|
||||
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
|
||||
//! showed nothing.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::{self, mode};
|
||||
use serde_json::json;
|
||||
|
||||
/// AutoCAD's default running snaps (OSMODE 4133).
|
||||
const DEFAULT: u32 = 4133;
|
||||
|
||||
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
|
||||
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
|
||||
}
|
||||
|
||||
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||
let a = deg.to_radians();
|
||||
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_on_a_circle_snaps_to_its_center() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
|
||||
let c = Vec2::new(100.0, 50.0);
|
||||
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
|
||||
// A hair off the circle, well inside the aperture; the center is 20 units away.
|
||||
let cursor = polar(c, 20.3, deg);
|
||||
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
|
||||
assert_eq!(m, mode::CEN, "at {deg}°");
|
||||
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
|
||||
}
|
||||
// Away from the circle (outside the aperture) there is nothing.
|
||||
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
|
||||
// Center off: no center.
|
||||
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
|
||||
// On the center itself, as before.
|
||||
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
|
||||
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
|
||||
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
|
||||
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
|
||||
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(arc.1, mode::CEN);
|
||||
assert!(arc.0.near(Vec2::ZERO, 1e-9));
|
||||
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
|
||||
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
|
||||
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(el.1, mode::CEN);
|
||||
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
|
||||
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
|
||||
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nearer_endpoint_or_intersection_still_wins() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
|
||||
// At the line's end on the circle: Endpoint/Intersection, not the far center.
|
||||
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
|
||||
assert!(m == mode::END || m == mode::INT, "{m}");
|
||||
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_inside_block_references_snap_to_their_centers() {
|
||||
let mut s = Session::new();
|
||||
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
|
||||
let kind = EntityKind::Insert(Insert {
|
||||
block: "H".into(),
|
||||
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||
scale: Vec3::new(3.0, 3.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
});
|
||||
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
|
||||
// The circle lands at (115,100) with radius 6.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_cycling_offers_the_center_from_the_curve() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
|
||||
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
|
||||
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
|
||||
s.start("line").unwrap();
|
||||
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
|
||||
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
|
||||
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
|
||||
}
|
||||
|
||||
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
|
||||
fn review_arc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
|
||||
let s = review_arc();
|
||||
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
|
||||
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||
}
|
||||
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
|
||||
let cursor = Vec2::new(20.1, 2.0);
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||
// Away from the quadrants the center from the curve.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_straight_segments_do_not_hide_a_circle_from_center() {
|
||||
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
|
||||
// work limit counts circles and arcs only, so the circle's center is still found.
|
||||
let mut s = Session::new();
|
||||
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
|
||||
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
|
||||
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
|
||||
let mut d = Drawing::new_imperial();
|
||||
let paper = Space::Paper("Layout1".into());
|
||||
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
|
||||
let vp = Viewport {
|
||||
center: Vec3::new(100.0, 50.0, 0.0),
|
||||
width: 20.0,
|
||||
height: 20.0,
|
||||
view_center: Vec2::new(10.0, 0.0),
|
||||
view_height: 40.0,
|
||||
id: 2,
|
||||
locked: false,
|
||||
frozen_layers: Vec::new(),
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
twist: 0.0,
|
||||
..Default::default()
|
||||
};
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
|
||||
// nearer the cursor (3.3) than the model circle's (8).
|
||||
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
|
||||
// The cursor is on the model circle (0.1 off in paper units): its center wins.
|
||||
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
|
||||
assert_eq!(h.mode, mode::CEN);
|
||||
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
|
||||
assert!(h.viewport.is_some());
|
||||
// On the paper circle, away from the model one: its center.
|
||||
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
|
||||
assert!(h.viewport.is_none());
|
||||
}
|
||||
@@ -70,6 +70,9 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
|
||||
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
|
||||
assert_eq!(m, mode::TAN);
|
||||
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
|
||||
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
|
||||
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
|
||||
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
|
||||
// Perpendicular from (10,10): the line from the base runs along the normal.
|
||||
let base = Vec2::new(10.0, 10.0);
|
||||
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
|
||||
@@ -119,3 +122,28 @@ fn spline_midpoint_perpendicular_and_tangent() {
|
||||
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
|
||||
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perpendicular_from_an_arcs_center_stays_on_the_arc() {
|
||||
// From the center of an arc every point is perpendicular: the one under the cursor, never a
|
||||
// point of its circle outside the sweep.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [0, 0], "radius": 10, "start": 90, "end": 180})).unwrap();
|
||||
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, Vec2::new(-6.0, 8.0), 0.3, mode::PER, Some(Vec2::ZERO), false);
|
||||
let (p, m) = hit.map(|h| (h.point, h.mode)).expect("a perpendicular on the arc");
|
||||
assert_eq!(m, mode::PER);
|
||||
assert!(p.near(Vec2::new(-6.0, 8.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perpendicular_to_a_ray_needs_the_cursor_on_the_ray() {
|
||||
// A ray along +X from the origin: behind its start the cursor is over nothing.
|
||||
let mut s = Session::new();
|
||||
s.execute("ray", &serde_json::json!({"base": [0, 0], "through": [10, 0]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let base = Some(Vec2::new(5.0, 3.0));
|
||||
assert_eq!(snap::osnap(d, &Space::Model, Vec2::new(-2.0, 0.0), 0.5, mode::PER, base, false), None);
|
||||
// Over the ray, the foot is found.
|
||||
let hit = snap::osnap(d, &Space::Model, Vec2::new(2.0, 0.0), 0.5, mode::PER, base, false).expect("the foot on the ray");
|
||||
assert!(hit.point.near(Vec2::new(5.0, 0.0), 1e-9), "{hit:?}");
|
||||
}
|
||||
|
||||
@@ -21,6 +21,17 @@ fn last_line(s: &Session) -> (Vec2, Vec2) {
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
|
||||
}
|
||||
|
||||
/// The last circle drawn as (center, radius).
|
||||
fn last_circle(s: &Session) -> (Vec2, f64) {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
|
||||
.last()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn near(p: Vec2, x: f64, y: f64) -> bool {
|
||||
p.near(Vec2::new(x, y), 1e-9)
|
||||
}
|
||||
@@ -80,6 +91,23 @@ fn nothing_to_snap_to_rejects_the_point() {
|
||||
assert!(near(s.last_point, 10.0, 10.0));
|
||||
}
|
||||
|
||||
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
|
||||
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
|
||||
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
|
||||
#[test]
|
||||
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
|
||||
let mut s = drawing();
|
||||
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
|
||||
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
|
||||
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
|
||||
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
|
||||
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_nests_with_a_snap_override() {
|
||||
let mut s = drawing();
|
||||
@@ -116,3 +144,97 @@ fn a_command_keyword_wins_over_a_snap_word() {
|
||||
s.cmdline("arc _cen").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_circle_radius_touches_the_picked_circle() {
|
||||
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
|
||||
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
|
||||
for (script, center, r) in [
|
||||
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
|
||||
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
|
||||
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
|
||||
] {
|
||||
let mut s = drawing();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
let (c, got) = last_circle(&s);
|
||||
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_touches_the_picked_circles() {
|
||||
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
|
||||
// first or last.
|
||||
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
|
||||
let mut s = drawing();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
|
||||
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
|
||||
}
|
||||
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
|
||||
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
|
||||
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
|
||||
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
|
||||
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
|
||||
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
|
||||
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
|
||||
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
|
||||
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
|
||||
let mut s = drawing();
|
||||
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
|
||||
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
|
||||
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
|
||||
let mut s = drawing();
|
||||
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
|
||||
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_through_points_in_line_with_the_picked_circles_center() {
|
||||
// Through 3,0 and 5,0 and tangent to the unit circle at the origin: the two points and that
|
||||
// circle's center lie on one line, the circle that touches it does not (center 4,±√48, radius 7).
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 0,0 1\nCIRCLE 3P 3,0 5,0 TAN 1,0\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!(near(Vec2::new(c.x, c.y.abs()), 4.0, 48f64.sqrt()) && (r - 7.0).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
|
||||
//! apertures give no candidates, and the list never repeats a snap.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Space;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::mode;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
|
||||
let mut s = Session::new();
|
||||
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
|
||||
for i in 0..600 {
|
||||
let a = f64::from(i) * 0.01;
|
||||
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
|
||||
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
|
||||
assert!(!cands.is_empty());
|
||||
assert!(cands.len() <= 257, "{} candidates", cands.len());
|
||||
for (i, a) in cands.iter().enumerate() {
|
||||
assert!(a.point.is_finite());
|
||||
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_cursor_and_aperture_give_no_candidates() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let space = Space::Model;
|
||||
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
|
||||
for (c, ap) in [
|
||||
(Vec2::new(f64::NAN, 0.0), 0.5),
|
||||
(Vec2::new(0.0, f64::INFINITY), 0.5),
|
||||
(Vec2::ZERO, f64::NAN),
|
||||
(Vec2::ZERO, 0.0),
|
||||
(Vec2::ZERO, -1.0),
|
||||
(Vec2::ZERO, f64::INFINITY),
|
||||
] {
|
||||
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
|
||||
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
|
||||
}
|
||||
// A huge but finite aperture still answers, from the objects there are.
|
||||
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
|
||||
assert!(far.iter().all(|h| h.point.is_finite()));
|
||||
// Object snaps off (or only the OFF bit) offer nothing.
|
||||
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
|
||||
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
|
||||
let mut s = Session::new();
|
||||
// Three line ends close together, all within the aperture of the cursor between them.
|
||||
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
|
||||
s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
|
||||
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
|
||||
assert_eq!(ends.len(), 3, "{cands:?}");
|
||||
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
|
||||
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
|
||||
}
|
||||
// The first is the snap a click would take.
|
||||
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
|
||||
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
|
||||
}
|
||||
|
||||
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
|
||||
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
|
||||
#[test]
|
||||
fn a_non_finite_base_gives_no_candidates() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
|
||||
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
|
||||
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
|
||||
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
|
||||
}
|
||||
// A finite base still offers them.
|
||||
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_snaps_of_two_curves_at_one_point_are_both_offered() {
|
||||
// Two circles touching at the origin: each offers its own deferred tangent there, and the
|
||||
// line drawn from it depends on which circle it is.
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 0,1 1\nCIRCLE 0,-2 2\n").unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let all = cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(0.0, 0.1), 0.5, mode::TAN, None, true);
|
||||
let curves: Vec<_> = all.iter().filter_map(|h| h.deferred.map(|f| f.curve)).collect();
|
||||
assert_eq!(curves.len(), 2, "{all:?}");
|
||||
assert_ne!(curves.first(), curves.get(1), "{all:?}");
|
||||
}
|
||||
@@ -16,7 +16,9 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
||||
use cadcraft_doc::foreign::{
|
||||
Foreign, ForeignExtra, ForeignKey, ForeignObject, VertexId, class_group, class_index, class_number, proxy_has_string_stream,
|
||||
};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{SectionRef, Tag, Version};
|
||||
|
||||
@@ -83,6 +85,8 @@ fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
|
||||
|
||||
/// Most objects kept from one file.
|
||||
const MAX_OBJECTS: usize = 1_000_000;
|
||||
/// Most vertices of one polyline whose identifiers are kept.
|
||||
const MAX_VERTEX_IDS: usize = 1_000_000;
|
||||
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
|
||||
const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS;
|
||||
/// Longest ownership chain followed.
|
||||
@@ -345,9 +349,57 @@ fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet<S
|
||||
}
|
||||
x.props = props.iter().filter(|t| matches!(t.code, 347 | 284)).map(raw).collect();
|
||||
}
|
||||
if entity && !unknown && kind == "LWPOLYLINE" {
|
||||
x.vertex_ids = vertex_ids(tags);
|
||||
}
|
||||
x
|
||||
}
|
||||
|
||||
/// A LWPOLYLINE record's vertices with their identifiers (group 91 after a vertex's point): one
|
||||
/// per vertex, identifier 0 for a vertex without one; empty when no vertex has one
|
||||
/// ([`ForeignExtra::vertex_ids`]). The points are as the reader gives them: mirrored in x when
|
||||
/// the normal points down. Groups inside an application's `102 {` … `102 }` are not the
|
||||
/// polyline's.
|
||||
fn vertex_ids(tags: &[Tag]) -> Vec<VertexId> {
|
||||
let mut in_app = false;
|
||||
let own_tags: Vec<&Tag> = tags
|
||||
.iter()
|
||||
.take_while(|t| t.code < 1000)
|
||||
.filter(|t| {
|
||||
if t.code == 102 {
|
||||
in_app = t.str().trim_start().starts_with('{');
|
||||
return false;
|
||||
}
|
||||
!in_app
|
||||
})
|
||||
.collect();
|
||||
let own = || own_tags.iter().copied();
|
||||
let down = own().any(|t| t.code == 230 && t.f64() < 0.0);
|
||||
if !own().any(|t| t.code == 91 && t.i64() != 0) {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ids: Vec<VertexId> = Vec::new();
|
||||
for t in own() {
|
||||
match t.code {
|
||||
// A polyline past the cap keeps none: identifiers for some of its vertices would be wrong.
|
||||
10 if ids.len() >= MAX_VERTEX_IDS => return Vec::new(),
|
||||
10 => ids.push(VertexId { id: 0, x: if down { -t.f64() } else { t.f64() }, y: 0.0 }),
|
||||
20 => {
|
||||
if let Some(last) = ids.last_mut() {
|
||||
last.y = t.f64();
|
||||
}
|
||||
}
|
||||
91 => {
|
||||
if let Some(last) = ids.last_mut() {
|
||||
last.id = i32::try_from(t.i64()).unwrap_or(0);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// Every entity of the drawing (model space, layouts, blocks).
|
||||
fn all_entities(d: &Drawing) -> impl Iterator<Item = &Entity> {
|
||||
std::iter::once(&d.model)
|
||||
|
||||
@@ -169,7 +169,11 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
w.f(38, elevation);
|
||||
}
|
||||
thickness(w, e);
|
||||
for v in &p.vertices {
|
||||
// The vertex identifiers the file gave the polyline (DXF 2010 and later), while its
|
||||
// vertices are where they were read: geometric constraints name its segments by them.
|
||||
let kept = d.foreign.entities.get(&e.handle).map(|x| x.vertex_ids.as_slice()).filter(|_| cx.target >= Version::R2010);
|
||||
let ids = kept.and_then(|kept| cadcraft_doc::foreign::vertex_ids_for(kept, p.vertices.iter().map(|v| (v.p.x, v.p.y))));
|
||||
for (i, v) in p.vertices.iter().enumerate() {
|
||||
w.p2(10, v.p);
|
||||
if v.start_width != 0.0 || v.end_width != 0.0 {
|
||||
w.f(40, v.start_width);
|
||||
@@ -178,6 +182,9 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
if v.bulge != 0.0 {
|
||||
w.f(42, v.bulge);
|
||||
}
|
||||
if let Some(id) = ids.as_ref().and_then(|ids| ids.get(i)).filter(|id| **id != 0) {
|
||||
w.i(91, i64::from(*id));
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::MLine(m) => {
|
||||
|
||||
@@ -51,6 +51,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
|
||||
("PSTYLEMODE", 290),
|
||||
("INSUNITS", 70),
|
||||
("MEASUREMENT", 70),
|
||||
("REGENMODE", 70),
|
||||
("PSLTSCALE", 70),
|
||||
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
|
||||
// record below repeats it). Written so a drawing opened on its saved view saves it back.
|
||||
|
||||
@@ -287,8 +287,19 @@ impl<'o> Out<'o> {
|
||||
|
||||
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
|
||||
/// compared.
|
||||
pub const VOLATILE_HEADER: &[&str] =
|
||||
&["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"];
|
||||
/// `CADCRAFT_DIMASO_MODE` is the engine's memory of the mode DIMASO turned off; no file keeps it.
|
||||
pub const VOLATILE_HEADER: &[&str] = &[
|
||||
"HANDSEED",
|
||||
"TDCREATE",
|
||||
"TDUCREATE",
|
||||
"TDUPDATE",
|
||||
"TDUUPDATE",
|
||||
"TDINDWG",
|
||||
"TDUSRTIMER",
|
||||
"VERSIONGUID",
|
||||
"FINGERPRINTGUID",
|
||||
"CADCRAFT_DIMASO_MODE",
|
||||
];
|
||||
|
||||
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
|
||||
/// reopened). Differences are reported as what `after` lost, gained or changed.
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! A lightweight polyline keeps its vertex identifiers (LWPOLYLINE group 91 after a vertex, DXF
|
||||
//! 2010 and later) through a save while its vertices are where they were read.
|
||||
//! Geometric constraints name a polyline's segments by these identifiers. CADCraft's polyline has
|
||||
//! none, so every save wrote the polyline without them, and what the constraints name was gone.
|
||||
//!
|
||||
//! The DWG is written here with acadrust, the identifiers out of order and the first vertex not
|
||||
//! the smallest, as on a polyline that was edited in another program. The harness builds this
|
||||
//! module only where acadrust builds (see `main.rs`).
|
||||
use std::io::Cursor;
|
||||
|
||||
use acadrust::entities::{EntityType, LwPolyline, LwVertex};
|
||||
use acadrust::{CadDocument, DxfVersion, Vector2};
|
||||
use cadcraft_io::{SaveOptions, Version, read, write_with};
|
||||
|
||||
const VERTEX_IDS: [i32; 4] = [2, 5, 7, 1];
|
||||
|
||||
fn polyline_dwg() -> Vec<u8> {
|
||||
polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], 1.0)
|
||||
}
|
||||
|
||||
/// A DWG with one closed polyline at `points`, its normal along `normal_z` Z.
|
||||
fn polyline_dwg_with(points: [(f64, f64); 4], normal_z: f64) -> Vec<u8> {
|
||||
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
|
||||
let mut polyline = LwPolyline::new();
|
||||
polyline.is_closed = true;
|
||||
polyline.normal = acadrust::Vector3::new(0.0, 0.0, normal_z);
|
||||
for (id, (x, y)) in VERTEX_IDS.iter().zip(points) {
|
||||
polyline.vertices.push(LwVertex { vertex_id: *id, ..LwVertex::new(Vector2::new(x, y)) });
|
||||
}
|
||||
doc.add_entity(EntityType::LwPolyline(polyline)).expect("add the polyline");
|
||||
acadrust::DwgWriter::write_to_vec(&doc).expect("write the DWG")
|
||||
}
|
||||
|
||||
/// The vertex identifiers of the one lightweight polyline in DWG bytes.
|
||||
fn vertex_ids_of(dwg: &[u8]) -> Vec<i32> {
|
||||
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap();
|
||||
doc.entities()
|
||||
.find_map(|e| match e {
|
||||
EntityType::LwPolyline(p) => Some(p.vertices.iter().map(|v| v.vertex_id).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the polyline is in the DWG")
|
||||
}
|
||||
|
||||
/// The vertex identifiers (groups 91) of the one LWPOLYLINE record in a DXF text.
|
||||
fn dxf_vertex_ids(dxf: &[u8]) -> Vec<String> {
|
||||
let text = String::from_utf8_lossy(dxf);
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut pairs = lines.chunks(2).filter_map(|pair| Some((*pair.first()?, *pair.get(1)?)));
|
||||
let record = pairs.by_ref().skip_while(|pair| *pair != ("0", "LWPOLYLINE")).skip(1);
|
||||
record.take_while(|(code, _)| *code != "0").filter(|(code, _)| *code == "91").map(|(_, value)| value.to_string()).collect()
|
||||
}
|
||||
|
||||
fn save(d: &cadcraft_doc::Drawing, name: &str, version: Version) -> Vec<u8> {
|
||||
write_with(d, name, &SaveOptions { version: Some(version), binary: false }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_keeps_its_vertex_identifiers_through_a_save() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dwg = polyline_dwg();
|
||||
assert_eq!(vertex_ids_of(&dwg), VERTEX_IDS, "the fixture as acadrust reads it");
|
||||
let d = read(&dwg, "polyline.dwg").unwrap();
|
||||
for version in [Version::R2010, Version::R2018] {
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", version)), VERTEX_IDS, "DWG {version:?}");
|
||||
}
|
||||
assert_eq!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||
// A DXF before 2010 has no such group.
|
||||
assert!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2000)).is_empty());
|
||||
let back = read(&save(&d, "saved.dxf", Version::R2018), "saved.dxf").unwrap();
|
||||
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"], "read back from a DXF");
|
||||
}
|
||||
|
||||
/// Once a vertex is elsewhere, the order is another or a vertex is gone, the identifiers no longer
|
||||
/// say which vertex is which: none are written.
|
||||
#[test]
|
||||
fn an_edited_polyline_drops_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||
let mut after = |edit: fn(&mut cadcraft_doc::LwPolyline)| {
|
||||
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||
edit(p);
|
||||
}
|
||||
}));
|
||||
vertex_ids_of(&save(&d, "edited.dwg", Version::R2018))
|
||||
};
|
||||
assert_eq!(after(|p| p.vertices.reverse()), [0; 4], "reversed");
|
||||
assert_eq!(after(|p| p.vertices.reverse()), VERTEX_IDS, "reversed back: every vertex is where it was read");
|
||||
assert_eq!(after(|p| p.vertices[1].p.x += 1.0), [0; 4], "a vertex moved");
|
||||
}
|
||||
|
||||
/// A polyline whose normal points down is read mirrored in x; untouched, it keeps its identifiers.
|
||||
#[test]
|
||||
fn a_polyline_facing_down_keeps_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read(&polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], -1.0), "down.dwg").unwrap();
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), VERTEX_IDS);
|
||||
}
|
||||
|
||||
/// Reversed, a polyline symmetric about x = 0 has its mirror image's points: the identifiers still
|
||||
/// no longer say which vertex is which.
|
||||
#[test]
|
||||
fn a_reversed_symmetric_polyline_drops_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read(&polyline_dwg_with([(-20.0, 0.0), (-20.0, 25.0), (20.0, 25.0), (20.0, 0.0)], 1.0), "sym.dwg").unwrap();
|
||||
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||
p.vertices.reverse();
|
||||
}
|
||||
}));
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), [0; 4]);
|
||||
}
|
||||
|
||||
/// A group 91 inside an application's `102 {` group of the record is not a vertex identifier.
|
||||
#[test]
|
||||
fn a_91_inside_an_application_group_is_not_an_identifier() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||
let dxf = String::from_utf8(save(&d, "saved.dxf", Version::R2018)).unwrap();
|
||||
let mut lines: Vec<&str> = dxf.lines().collect();
|
||||
let start = lines.windows(2).position(|pair| pair[0].trim() == "0" && pair[1].trim() == "LWPOLYLINE").unwrap();
|
||||
// After the first vertex's identifier.
|
||||
let at = (start..lines.len()).step_by(2).find(|i| lines[*i].trim() == "91").unwrap() + 2;
|
||||
lines.splice(at..at, ["102", "{SOMEAPP", " 91", "9", "102", "}"]);
|
||||
let back = read(lines.join("\n").as_bytes(), "app.dxf").unwrap();
|
||||
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||
}
|
||||
@@ -62,6 +62,8 @@ mod low_handseed;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod ltype_dwg_dash_count;
|
||||
mod ltype_element_cap;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod lwpolyline_vertex_ids;
|
||||
mod minsert_marker;
|
||||
mod mleader_content;
|
||||
mod mleader_roundtrip;
|
||||
|
||||
@@ -44,8 +44,8 @@ craft-update = { workspace = true, features = ["screen-testing"] }
|
||||
# The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in
|
||||
# production too; the tests exercise the same installed chain as the app.
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses).
|
||||
naga = { version = "30", features = ["wgsl-in", "glsl-out"] }
|
||||
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) and Metal translations in tests (same naga wgpu uses).
|
||||
naga = { version = "30", features = ["wgsl-in", "glsl-out", "msl-out"] }
|
||||
|
||||
[build-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -200,12 +200,14 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
|
||||
let s = &app.session.settings;
|
||||
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
|
||||
let Ok(st) = app.session.state() else { return };
|
||||
let space = st.edit_space();
|
||||
let frozen = st.viewport_frozen();
|
||||
let hit = match cycle {
|
||||
Some(i) => {
|
||||
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
|
||||
let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
|
||||
cands.get(i % cands.len().max(1)).copied()
|
||||
}
|
||||
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
|
||||
None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
|
||||
};
|
||||
let p = match (hit, app.canvas.snap) {
|
||||
(Some(h), _) => {
|
||||
|
||||
@@ -1100,6 +1100,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The patched wgpu-hal (vendor/wgpu-hal, #1631) compiles with the newest Metal language the
|
||||
/// Mac's compiler accepts, which can be as old as macOS 11's (2.3, LSMinimumSystemVersion in
|
||||
/// packaging/macos/Info.plist.in), so the canvas shader must still translate at that version.
|
||||
#[test]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
fn shader_translates_for_the_oldest_metal_the_app_supports() {
|
||||
let module = naga::front::wgsl::parse_str(SHADER).unwrap();
|
||||
let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap();
|
||||
for (stage, entry) in
|
||||
[(naga::ShaderStage::Vertex, "vs_line"), (naga::ShaderStage::Vertex, "vs_quad"), (naga::ShaderStage::Fragment, "fs_main")]
|
||||
{
|
||||
let options = naga::back::msl::Options { lang_version: (2, 3), ..Default::default() };
|
||||
let pipeline = naga::back::msl::PipelineOptions { entry_point: Some((stage, entry.into())), ..Default::default() };
|
||||
let (out, _) = naga::back::msl::write_string(&module, &info, &options, &pipeline).unwrap();
|
||||
assert!(out.contains(entry), "{entry}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A wgpu bump leaves the `[patch.crates-io]` copy of wgpu-hal unused (Cargo only warns) and
|
||||
/// brings #1631 back: older Macs would ask the Metal compiler for a version it rejects again.
|
||||
/// See vendor/wgpu-hal/CADCRAFT.md.
|
||||
#[test]
|
||||
fn wgpu_hal_is_the_patched_copy() {
|
||||
let lock = include_str!("../../../Cargo.lock").replace("\r\n", "\n");
|
||||
let hal: Vec<&str> = lock.split("[[package]]").filter(|p| p.contains("\nname = \"wgpu-hal\"\n")).collect();
|
||||
assert!(!hal.is_empty() && hal.iter().all(|p| !p.contains("\nsource = ")), "wgpu-hal comes from a registry, not vendor/wgpu-hal");
|
||||
}
|
||||
|
||||
/// `prims` polylines of `points` points each (all over the same vertices).
|
||||
fn polylines(prims: usize, points: usize) -> DisplayList {
|
||||
let mut l = list();
|
||||
|
||||
@@ -52,6 +52,7 @@ mod shared_controls;
|
||||
mod shortcut_menus;
|
||||
mod shortcuts_checked;
|
||||
mod slow_clicks;
|
||||
mod snap_tab_cycling;
|
||||
mod space_at_options;
|
||||
mod status_bar_toggles;
|
||||
mod style_dialogs;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Tab at a point prompt steps through every object snap under the aperture (each endpoint of
|
||||
//! each object nearby), not just the closest snap of each running mode, and comes back round.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
|
||||
use cadcraft_engine::snap::mode;
|
||||
use cadcraft_geom::Vec2;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn tab_cycles_through_every_endpoint_under_the_aperture() {
|
||||
let mut s = Session::new();
|
||||
// Three line ends close together (within the aperture of the cursor between them).
|
||||
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
|
||||
s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
}
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": 1 })).unwrap();
|
||||
s.execute("view.set", &json!({ "center": [0, 0], "height": 20 })).unwrap();
|
||||
let mut app = CadApp::new(s, Services::default());
|
||||
app.canvas.zoom_pending = false;
|
||||
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.state_mut().session.start("line").unwrap();
|
||||
h.run_steps(2);
|
||||
let xf = h.state().canvas.xf.unwrap();
|
||||
let at = xf.to_screen(Vec2::new(0.03, 0.0));
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.run_steps(2);
|
||||
let mut seen: Vec<Vec2> = Vec::new();
|
||||
for i in 0..4 {
|
||||
let p = h.state().canvas.snap.map(|s| s.point).unwrap();
|
||||
if i < 3 {
|
||||
assert!(!seen.iter().any(|q| q.near(p, 1e-9)), "Tab {i} repeats {p:?} ({seen:?})");
|
||||
} else {
|
||||
assert!(seen.first().is_some_and(|q| q.near(p, 1e-9)), "the fourth Tab comes back round");
|
||||
}
|
||||
seen.push(p);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(2);
|
||||
}
|
||||
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
|
||||
assert!(seen.iter().any(|q| q.near(want, 1e-9)), "{want:?} in {seen:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Three endpoints near 10,0: 10,0 (the nearest to the cursor), 10.03,0 and 9.95,0. Endpoint is
|
||||
/// the only running snap, so every candidate is an endpoint.
|
||||
fn three_ends() -> Harness<'static, CadApp> {
|
||||
let mut d = Drawing::new_imperial();
|
||||
for (a, b) in [((0.0, 0.0), (10.0, 0.0)), ((10.03, 0.0), (20.0, 0.0)), ((9.95, 0.0), (9.95, -5.0))] {
|
||||
let line = Line { a: Vec2::new(a.0, a.1).to3(0.0), b: Vec2::new(b.0, b.1).to3(0.0) };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
|
||||
}
|
||||
let mut session = Session::empty();
|
||||
session.open_drawing(d, "Tab snap cycling", None);
|
||||
session.execute("view.set", &json!({"center":[10,0],"height":8})).unwrap();
|
||||
session.settings.osmode = mode::END;
|
||||
session.settings.snapmode = false;
|
||||
session.settings.orthomode = false;
|
||||
let mut app = CadApp::new(session, Services::default());
|
||||
app.canvas.zoom_pending = false;
|
||||
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.state_mut().start("line");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.running.as_ref().unwrap().id, "line");
|
||||
let ap = h.state().session.settings.aperture / h.state().canvas.xf.unwrap().scale;
|
||||
assert!(ap > 0.07, "all three endpoints lie in the aperture ({ap})");
|
||||
h
|
||||
}
|
||||
|
||||
const CURSOR: Vec2 = Vec2::new(10.01, 0.0);
|
||||
|
||||
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) -> Pos2 {
|
||||
let pos = h.state().canvas.xf.unwrap().to_screen(p);
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(3);
|
||||
pos
|
||||
}
|
||||
|
||||
/// Tab, as the command line receives it (`cmdline::capture_tab`).
|
||||
fn tab(h: &mut Harness<'_, CadApp>) {
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
fn snapped(h: &Harness<'_, CadApp>) -> Vec2 {
|
||||
let hit = h.state().canvas.snap.expect("a snap marker");
|
||||
assert_eq!(hit.mode, mode::END);
|
||||
hit.point
|
||||
}
|
||||
|
||||
fn assert_at(got: Vec2, x: f64) {
|
||||
assert!(got.near(Vec2::new(x, 0.0), 1e-9), "{got:?}, expected {x},0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_cursor_away_starts_the_cycle_over() {
|
||||
let mut h = three_ends();
|
||||
hover(&mut h, CURSOR);
|
||||
tab(&mut h);
|
||||
assert_at(snapped(&h), 10.03);
|
||||
hover(&mut h, Vec2::new(10.0, 2.0));
|
||||
assert!(h.state().canvas.snap.is_none());
|
||||
hover(&mut h, CURSOR);
|
||||
assert_at(snapped(&h), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_places_the_candidate_tab_chose() {
|
||||
let mut h = three_ends();
|
||||
let pos = hover(&mut h, CURSOR);
|
||||
tab(&mut h);
|
||||
assert_at(snapped(&h), 10.03);
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
let base = h.state().session.current_prompt().and_then(|p| p.base).expect("LINE asks for the next point");
|
||||
assert_at(base, 10.03);
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
sonar.projectKey=storytold_cadcraft
|
||||
sonar.organization=storytold
|
||||
sonar.coverage.exclusions=packaging/**
|
||||
# Third-party crates copied in unchanged (apart from their noted patch), not ours to analyse.
|
||||
sonar.exclusions=vendor/**
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "40f4a34ebaf56f9a046231f54125ad046239d3f3"
|
||||
},
|
||||
"path_in_vcs": "wgpu-hal"
|
||||
}
|
||||
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
# wgpu-hal 30.0.1, patched for CADCraft
|
||||
|
||||
A copy of [`wgpu-hal` 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) (MIT OR Apache-2.0, see
|
||||
`LICENSE.*`), used through `[patch.crates-io]` in the workspace `Cargo.toml`. Every file is the
|
||||
published crate unchanged except `src/metal/adapter.rs` and this note.
|
||||
|
||||
## The change
|
||||
|
||||
`src/metal/adapter.rs`, `accepted_msl_version`: the Metal shading language version is no longer
|
||||
taken from the macOS version alone. A tiny kernel is compiled with each version up to the OS's,
|
||||
newest first, and the first one the system's Metal compiler accepts is used. If none is accepted,
|
||||
the OS's version is kept, as upstream does. The same patch is in storytold/craft-anything
|
||||
`vendor/wgpu-hal`.
|
||||
|
||||
## Why
|
||||
|
||||
On Macs with older GPUs running a newer macOS than Apple ships for them (OpenCore Legacy Patcher),
|
||||
macOS 15 makes wgpu ask for `-std=metal3.2` while the Metal compiler stops at 3.1 or earlier. Every
|
||||
shader fails, the device is lost and CADCraft exits before its window opens (storytold/cadcraft#1631;
|
||||
upstream gfx-rs/wgpu#10687, closed with no fix on trunk; open fix proposal gfx-rs/wgpu#10725).
|
||||
|
||||
## Removing it
|
||||
|
||||
Delete this directory and its `[patch.crates-io]` entry once a released wgpu picks a Metal version the
|
||||
compiler accepts. `wgpu_hal_is_the_patched_copy` (`crates/ui-egui/src/gpu.rs`) fails when a wgpu bump
|
||||
leaves this copy unused, so the patch can't be dropped by accident: either port the change to the new
|
||||
version or confirm upstream fixed it and remove the copy and the test together.
|
||||
Vendored
+542
@@ -0,0 +1,542 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.87"
|
||||
name = "wgpu-hal"
|
||||
version = "30.0.1"
|
||||
authors = ["gfx-rs developers"]
|
||||
build = "build.rs"
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API"
|
||||
homepage = "https://wgpu.rs/"
|
||||
readme = "README.md"
|
||||
keywords = ["graphics"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/gfx-rs/wgpu"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = [
|
||||
"metal",
|
||||
"vulkan",
|
||||
"gles",
|
||||
"renderdoc",
|
||||
]
|
||||
rustdoc-args = [
|
||||
"--cfg",
|
||||
"docsrs",
|
||||
]
|
||||
targets = [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = ["cfg_aliases"]
|
||||
|
||||
[features]
|
||||
device_lost_panic = []
|
||||
dx12 = [
|
||||
"dep:arrayvec",
|
||||
"dep:bit-set",
|
||||
"dep:bytemuck",
|
||||
"dep:gpu-allocator",
|
||||
"dep:libloading",
|
||||
"dep:once_cell",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:range-alloc",
|
||||
"dep:windows-core",
|
||||
"gpu-allocator/d3d12",
|
||||
"naga/hlsl-out",
|
||||
"once_cell/std",
|
||||
"windows/Win32_Devices_DeviceAndDriverInstallation",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Graphics_Direct3D_Dxc",
|
||||
"windows/Win32_Graphics_Direct3D_Fxc",
|
||||
"windows/Win32_Graphics_Direct3D",
|
||||
"windows/Win32_Graphics_Direct3D12",
|
||||
"windows/Win32_Graphics_DirectComposition",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Security",
|
||||
"windows/Win32_System_Diagnostics_Debug",
|
||||
"windows/Win32_System_Kernel",
|
||||
"windows/Win32_System_Performance",
|
||||
"windows/Win32_System_Threading",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
fragile-send-sync-non-atomic-wasm = ["wgpu-types/fragile-send-sync-non-atomic-wasm"]
|
||||
gles = [
|
||||
"dep:arrayvec",
|
||||
"dep:bytemuck",
|
||||
"dep:glow",
|
||||
"dep:glutin_wgl_sys",
|
||||
"dep:js-sys",
|
||||
"dep:khronos-egl",
|
||||
"dep:libloading",
|
||||
"dep:ndk-sys",
|
||||
"dep:objc2",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:wasm-bindgen",
|
||||
"dep:wayland-sys",
|
||||
"dep:web-sys",
|
||||
"dep:windows-result",
|
||||
"naga/glsl-out",
|
||||
"wgpu-types/web",
|
||||
"windows-result/std",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Graphics_OpenGL",
|
||||
"windows/Win32_System_LibraryLoader",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
internal_error_panic = []
|
||||
metal = [
|
||||
"naga/msl-out",
|
||||
"dep:arrayvec",
|
||||
"dep:block2",
|
||||
"dep:bytemuck",
|
||||
"dep:libloading",
|
||||
"dep:objc2",
|
||||
"dep:objc2-core-foundation",
|
||||
"dep:objc2-core-graphics",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-metal",
|
||||
"dep:objc2-quartz-core",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:smallvec",
|
||||
"dep:raw-window-metal",
|
||||
]
|
||||
portable-atomic = [
|
||||
"dep:portable-atomic",
|
||||
"dep:portable-atomic-util",
|
||||
]
|
||||
renderdoc = [
|
||||
"dep:libloading",
|
||||
"dep:renderdoc-sys",
|
||||
]
|
||||
static-dxc = ["dep:mach-dxcompiler-rs"]
|
||||
validation_canary = ["dep:parking_lot"]
|
||||
vulkan = [
|
||||
"naga/spv-out",
|
||||
"dep:android_system_properties",
|
||||
"dep:arrayvec",
|
||||
"dep:ash",
|
||||
"dep:bytemuck",
|
||||
"dep:libc",
|
||||
"dep:libloading",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:raw-window-metal",
|
||||
"dep:smallvec",
|
||||
"dep:windows",
|
||||
"gpu-allocator/vulkan",
|
||||
"windows/Win32",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Foundation",
|
||||
"windows/Win32_Graphics_Dxgi",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "wgpu_hal"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[example]]
|
||||
name = "halmark"
|
||||
path = "examples/halmark/main.rs"
|
||||
|
||||
[[example]]
|
||||
name = "raw-gles"
|
||||
path = "examples/raw-gles.rs"
|
||||
required-features = ["gles"]
|
||||
|
||||
[[example]]
|
||||
name = "ray-traced-triangle"
|
||||
path = "examples/ray-traced-triangle/main.rs"
|
||||
|
||||
[dependencies.arrayvec]
|
||||
version = "0.7.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.bitflags]
|
||||
version = "2.9"
|
||||
|
||||
[dependencies.bytemuck]
|
||||
version = "1.22"
|
||||
features = [
|
||||
"extern_crate_alloc",
|
||||
"min_const_generics",
|
||||
"derive",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[dependencies.cfg-if]
|
||||
version = "1"
|
||||
|
||||
[dependencies.glow]
|
||||
version = "0.17"
|
||||
optional = true
|
||||
|
||||
[dependencies.hashbrown]
|
||||
version = "0.17"
|
||||
features = [
|
||||
"default-hasher",
|
||||
"inline-more",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[dependencies.log]
|
||||
version = "0.4.29"
|
||||
|
||||
[dependencies.naga]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.naga-types]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.ordered-float]
|
||||
version = ">=3, <6.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.parking_lot]
|
||||
version = "0.12.3"
|
||||
optional = true
|
||||
|
||||
[dependencies.profiling]
|
||||
version = "1.0.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.raw-window-handle]
|
||||
version = "0.6.2"
|
||||
default-features = false
|
||||
|
||||
[dependencies.static_assertions]
|
||||
version = "1.1"
|
||||
|
||||
[dependencies.thiserror]
|
||||
version = "2.0.12"
|
||||
default-features = false
|
||||
|
||||
[dependencies.wgpu-naga-bridge]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.wgpu-types]
|
||||
version = "30.0.0"
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.env_logger]
|
||||
version = "0.11"
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.glam]
|
||||
version = "0.33.0"
|
||||
|
||||
[dev-dependencies.naga]
|
||||
version = "30.0.0"
|
||||
features = [
|
||||
"wgsl-in",
|
||||
"termcolor",
|
||||
]
|
||||
|
||||
[dev-dependencies.winit]
|
||||
version = "0.30.8"
|
||||
features = ["android-native-activity"]
|
||||
|
||||
[build-dependencies.cfg_aliases]
|
||||
version = "0.2.2"
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.js-sys]
|
||||
version = "0.3.104"
|
||||
optional = true
|
||||
default-features = true
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.wasm-bindgen]
|
||||
version = "0.2.127"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.web-sys]
|
||||
version = "0.3.104"
|
||||
features = [
|
||||
"default",
|
||||
"Window",
|
||||
"HtmlCanvasElement",
|
||||
"WebGl2RenderingContext",
|
||||
"OffscreenCanvas",
|
||||
"VideoFrame",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies.drm]
|
||||
version = "0.15"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies.mach-dxcompiler-rs]
|
||||
version = "0.1.4"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies.portable-atomic]
|
||||
version = "1.10"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin]
|
||||
version = "0.32"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
"wayland",
|
||||
"x11",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin-winit]
|
||||
version = "0.5"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
"wayland",
|
||||
"x11",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.ash]
|
||||
version = "0.38"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.gpu-allocator]
|
||||
version = "0.28"
|
||||
features = ["hashbrown"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.khronos-egl]
|
||||
version = "6"
|
||||
features = ["dynamic"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.libloading]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.renderdoc-sys]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.smallvec]
|
||||
version = "1.14"
|
||||
features = ["union"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies.portable-atomic-util]
|
||||
version = "0.2.4"
|
||||
features = ["alloc"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies.android_system_properties]
|
||||
version = "0.1.1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies.ndk-sys]
|
||||
version = "0.6"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies.khronos-egl]
|
||||
version = "6"
|
||||
features = [
|
||||
"static",
|
||||
"no-pkg-config",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies.libloading]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.block2]
|
||||
version = "0.6.2"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.bytemuck]
|
||||
version = "1.22"
|
||||
features = [
|
||||
"extern_crate_alloc",
|
||||
"min_const_generics",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2]
|
||||
version = "0.6.3"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"CFCGTypes",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-graphics]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"CGColorSpace",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"NSError",
|
||||
"NSProcessInfo",
|
||||
"NSRange",
|
||||
"NSString",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-metal]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"block2",
|
||||
"MTLAllocation",
|
||||
"MTLBlitCommandEncoder",
|
||||
"MTLBlitPass",
|
||||
"MTLBuffer",
|
||||
"MTLCaptureManager",
|
||||
"MTLCaptureScope",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
"MTLCommandQueue",
|
||||
"MTLComputeCommandEncoder",
|
||||
"MTLComputePass",
|
||||
"MTLComputePipeline",
|
||||
"MTLCounters",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLDrawable",
|
||||
"MTLEvent",
|
||||
"MTLLibrary",
|
||||
"MTLPipeline",
|
||||
"MTLPixelFormat",
|
||||
"MTLRenderCommandEncoder",
|
||||
"MTLRenderPass",
|
||||
"MTLRenderPipeline",
|
||||
"MTLResource",
|
||||
"MTLSampler",
|
||||
"MTLStageInputOutputDescriptor",
|
||||
"MTLTexture",
|
||||
"MTLTypes",
|
||||
"MTLVertexDescriptor",
|
||||
"MTLAccelerationStructure",
|
||||
"MTLAccelerationStructureTypes",
|
||||
"MTLAccelerationStructureCommandEncoder",
|
||||
"MTLResidencySet",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-quartz-core]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"CALayer",
|
||||
"CAMetalLayer",
|
||||
"objc2-metal",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.raw-window-metal]
|
||||
version = "1.0"
|
||||
optional = true
|
||||
|
||||
[target."cfg(unix)".dependencies.libc]
|
||||
version = "0.2.183"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(unix)".dependencies.wayland-sys]
|
||||
version = "0.31.3"
|
||||
features = [
|
||||
"client",
|
||||
"dlopen",
|
||||
"egl",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.bit-set]
|
||||
version = "0.10"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.glutin_wgl_sys]
|
||||
version = "0.6"
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.once_cell]
|
||||
version = "1.21"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.range-alloc]
|
||||
version = "0.1"
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.windows]
|
||||
version = "0.62"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.windows-core]
|
||||
version = "0.62"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.windows-result]
|
||||
version = "0.4"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[lints.rust]
|
||||
missing_debug_implementations = "warn"
|
||||
|
||||
[lints.rust.unexpected_cfgs]
|
||||
level = "warn"
|
||||
priority = 0
|
||||
check-cfg = [
|
||||
'cfg(feature, values("cargo-clippy"))',
|
||||
"cfg(web_sys_unstable_apis)",
|
||||
]
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
[package]
|
||||
name = "wgpu-hal"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
keywords.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
# Override the workspace's `rust-version` key. `wgpu-core` and its dependencies
|
||||
# have a less strict MSRV, to allow firefox more leeway in updating their Rust toolchain.
|
||||
#
|
||||
# See the repo README for more information on MSRV policy.
|
||||
rust-version = "1.87"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# Ideally we would enable all the features.
|
||||
#
|
||||
# However, the dx12 features fail to be documented because the docs.rs runner cross-compiling under
|
||||
# x86_64-unknown-linux-gnu cannot compile in that environment at the moment.
|
||||
features = ["metal", "vulkan", "gles", "renderdoc"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
targets = [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
# Cargo machete can't check build.rs dependencies. See https://github.com/bnjbvr/cargo-machete/issues/100
|
||||
ignored = ["cfg_aliases"]
|
||||
|
||||
[lints.rust]
|
||||
missing_debug_implementations = "warn"
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(feature, values("cargo-clippy"))', # objc's `msg_send` macro injects this in our code https://github.com/SSheldon/rust-objc/issues/125
|
||||
'cfg(web_sys_unstable_apis)', # web-sys uses this
|
||||
] }
|
||||
|
||||
[lib]
|
||||
|
||||
[features]
|
||||
########################
|
||||
### Backend Features ###
|
||||
########################
|
||||
|
||||
# The interaction of features between wgpu-core and wgpu-hal is a bit nuanced to get
|
||||
# the desired behavior on all platforms.
|
||||
#
|
||||
# At the wgpu-hal level the features are defined to enable the backends on all platforms
|
||||
# that can compile the backend. Vulkan for example will have an effect on Windows, Mac, Linux, and Android.
|
||||
# This is done with target conditional dependencies in wgpu-hal. This allows `--all-features`
|
||||
# to compile on all platforms.
|
||||
#
|
||||
# wgpu-core's features are defined to enable the backends on their "default" platforms. For example we
|
||||
# exclude the Vulkan backend on MacOS unless a separate feature `vulkan-portability` is enabled. In response
|
||||
# to these features, it enables features of platform specific crates. For example, the `vulkan` feature in wgpu-core
|
||||
# enables the `vulkan` feature in `wgpu-core-deps-windows-linux-android` which in turn enables the
|
||||
# `vulkan` feature in `wgpu-hal` _only_ on those platforms. If you enable the `vulkan-portability` feature, it
|
||||
# will enable the `vulkan` feature in `wgpu-core-deps-apple`. The only way to do this is unfortunately to have
|
||||
# a separate crate for each platform category that participates in the feature unification.
|
||||
#
|
||||
# This trick doesn't work at the `wgpu` level, because the `wgpu` -> `wgpu-core` dependency is conditional,
|
||||
# making the Cargo.toml signifigantly more complicated in all areas.
|
||||
#
|
||||
# See https://github.com/gfx-rs/wgpu/issues/3514, https://github.com/gfx-rs/wgpu/pull/7076,
|
||||
# and https://github.com/rust-lang/cargo/issues/1197 for more information.
|
||||
|
||||
## Enables the Metal backend when targeting Apple platforms.
|
||||
metal = [
|
||||
# Metal is only available on Apple platforms, therefore request MSL output also only if we target an Apple platform.
|
||||
"naga/msl-out",
|
||||
"dep:arrayvec",
|
||||
"dep:block2",
|
||||
"dep:bytemuck",
|
||||
"dep:libloading",
|
||||
"dep:objc2",
|
||||
"dep:objc2-core-foundation",
|
||||
"dep:objc2-core-graphics",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-metal",
|
||||
"dep:objc2-quartz-core",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:smallvec",
|
||||
"dep:raw-window-metal",
|
||||
]
|
||||
vulkan = [
|
||||
"naga/spv-out",
|
||||
"dep:android_system_properties",
|
||||
"dep:arrayvec",
|
||||
"dep:ash",
|
||||
"dep:bytemuck",
|
||||
"dep:libc",
|
||||
"dep:libloading",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:raw-window-metal",
|
||||
"dep:smallvec",
|
||||
"dep:windows",
|
||||
"gpu-allocator/vulkan",
|
||||
"windows/Win32",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Foundation",
|
||||
"windows/Win32_Graphics_Dxgi",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
]
|
||||
gles = [
|
||||
"dep:arrayvec",
|
||||
"dep:bytemuck",
|
||||
"dep:glow",
|
||||
"dep:glutin_wgl_sys",
|
||||
"dep:js-sys",
|
||||
"dep:khronos-egl",
|
||||
"dep:libloading",
|
||||
"dep:ndk-sys",
|
||||
"dep:objc2",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:wasm-bindgen",
|
||||
"dep:wayland-sys",
|
||||
"dep:web-sys",
|
||||
"dep:windows-result",
|
||||
"naga/glsl-out",
|
||||
"wgpu-types/web",
|
||||
"windows-result/std", # Need to enable this for the `Error` impl on `windows_result::Error` to work.
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Graphics_OpenGL",
|
||||
"windows/Win32_System_LibraryLoader",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
## Enables the DX12 backend when targeting Windows.
|
||||
dx12 = [
|
||||
"dep:arrayvec",
|
||||
"dep:bit-set",
|
||||
"dep:bytemuck",
|
||||
"dep:gpu-allocator",
|
||||
"dep:libloading",
|
||||
"dep:once_cell",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:range-alloc",
|
||||
"dep:windows-core",
|
||||
"gpu-allocator/d3d12",
|
||||
"naga/hlsl-out",
|
||||
"once_cell/std",
|
||||
"windows/Win32_Devices_DeviceAndDriverInstallation",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Graphics_Direct3D_Dxc",
|
||||
"windows/Win32_Graphics_Direct3D_Fxc",
|
||||
"windows/Win32_Graphics_Direct3D",
|
||||
"windows/Win32_Graphics_Direct3D12",
|
||||
"windows/Win32_Graphics_DirectComposition",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Security",
|
||||
"windows/Win32_System_Diagnostics_Debug",
|
||||
"windows/Win32_System_Kernel",
|
||||
"windows/Win32_System_Performance",
|
||||
"windows/Win32_System_Threading",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
|
||||
###########################
|
||||
### Misc Other Features ###
|
||||
###########################
|
||||
|
||||
static-dxc = ["dep:mach-dxcompiler-rs"]
|
||||
renderdoc = ["dep:libloading", "dep:renderdoc-sys"]
|
||||
fragile-send-sync-non-atomic-wasm = [
|
||||
"wgpu-types/fragile-send-sync-non-atomic-wasm",
|
||||
]
|
||||
portable-atomic = ["dep:portable-atomic", "dep:portable-atomic-util"]
|
||||
|
||||
###################################
|
||||
### Internal Debugging Features ###
|
||||
###################################
|
||||
|
||||
# Panic when running into a device lost error (for debugging purposes).
|
||||
# Only affects the d3d12 and vulkan backends.
|
||||
device_lost_panic = []
|
||||
# Panic when running into an internal error other than out-of-memory and device lost
|
||||
# (for debugging purposes).
|
||||
#
|
||||
# Only affects the d3d12 and vulkan backends.
|
||||
internal_error_panic = []
|
||||
# Tracks validation errors in a `VALIDATION_CANARY` static.
|
||||
validation_canary = ["dep:parking_lot"]
|
||||
|
||||
[[example]]
|
||||
name = "halmark"
|
||||
|
||||
[[example]]
|
||||
name = "raw-gles"
|
||||
required-features = ["gles"]
|
||||
|
||||
#####################
|
||||
### Platform: All ###
|
||||
#####################
|
||||
|
||||
[dependencies]
|
||||
naga.workspace = true
|
||||
wgpu-naga-bridge.workspace = true
|
||||
naga-types = { workspace = true }
|
||||
wgpu-types = { workspace = true, default-features = false }
|
||||
|
||||
# Dependencies in the lib and empty backend
|
||||
bitflags.workspace = true
|
||||
cfg-if.workspace = true
|
||||
log = { workspace = true }
|
||||
parking_lot = { workspace = true, optional = true }
|
||||
raw-window-handle.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
# Target agnostic dependencies used only in backends.
|
||||
arrayvec = { workspace = true, optional = true }
|
||||
bytemuck = { workspace = true, optional = true, features = ["derive"] }
|
||||
hashbrown = { workspace = true }
|
||||
ordered-float = { workspace = true, optional = true }
|
||||
profiling = { workspace = true, optional = true, default-features = false }
|
||||
static_assertions = { workspace = true }
|
||||
|
||||
# Backend: GLES
|
||||
glow = { workspace = true, optional = true }
|
||||
|
||||
########################
|
||||
### Platform: Native ###
|
||||
########################
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Backend: Vulkan and Dx12
|
||||
gpu-allocator = { workspace = true, optional = true }
|
||||
# Backend: Vulkan
|
||||
ash = { workspace = true, optional = true }
|
||||
smallvec = { workspace = true, optional = true, features = ["union"] }
|
||||
# Backend: GLES
|
||||
khronos-egl = { workspace = true, features = ["dynamic"], optional = true }
|
||||
libloading = { workspace = true, optional = true }
|
||||
renderdoc-sys = { workspace = true, optional = true }
|
||||
|
||||
##########################
|
||||
### Platform: All Unix ###
|
||||
##########################
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
# Backend: Vulkan
|
||||
libc = { workspace = true, optional = true }
|
||||
# backend: GLES
|
||||
wayland-sys = { version = "0.31.3", features = [
|
||||
"client",
|
||||
"dlopen",
|
||||
"egl",
|
||||
], optional = true }
|
||||
|
||||
## Support creating textures from DRM display/window handles.
|
||||
[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies]
|
||||
drm = { version = "0.15", optional = true }
|
||||
|
||||
#########################
|
||||
### Platform: Windows ###
|
||||
#########################
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# Backend: Dx12 and GLES
|
||||
windows = { workspace = true, optional = true }
|
||||
windows-core = { workspace = true, optional = true }
|
||||
windows-result = { workspace = true, optional = true }
|
||||
# Backend: Dx12
|
||||
bit-set = { workspace = true, optional = true }
|
||||
range-alloc = { workspace = true, optional = true }
|
||||
once_cell = { workspace = true, optional = true }
|
||||
# backend: GLES
|
||||
glutin_wgl_sys = { workspace = true, optional = true }
|
||||
|
||||
### Platform: x86/x86_64 Windows ###
|
||||
# This doesn't support aarch64. See https://github.com/gfx-rs/wgpu/issues/6860.
|
||||
# This doesn't support x86_64-pc-windows-gnu. See https://github.com/gfx-rs/wgpu/issues/8303
|
||||
#
|
||||
# ⚠️ Keep in sync with static_dxc cfg in build.rs and cfg_alias in `wgpu` crate ⚠️
|
||||
[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies]
|
||||
mach-dxcompiler-rs = { workspace = true, optional = true }
|
||||
|
||||
#######################
|
||||
### Platform: Apple ###
|
||||
#######################
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
# Backend: Metal
|
||||
block2 = { workspace = true, optional = true }
|
||||
bytemuck = { workspace = true, optional = true }
|
||||
objc2 = { workspace = true, optional = true }
|
||||
objc2-core-foundation = { workspace = true, optional = true }
|
||||
objc2-core-graphics = { workspace = true, optional = true }
|
||||
objc2-foundation = { workspace = true, optional = true }
|
||||
objc2-metal = { workspace = true, optional = true }
|
||||
objc2-quartz-core = { workspace = true, optional = true }
|
||||
|
||||
# backend: Metal + Vulkan
|
||||
raw-window-metal = { workspace = true, optional = true }
|
||||
|
||||
#########################
|
||||
### Platform: Android ###
|
||||
#########################
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
android_system_properties = { workspace = true, optional = true }
|
||||
ndk-sys = { workspace = true, optional = true }
|
||||
|
||||
#############################
|
||||
### Platform: Webassembly ###
|
||||
#############################
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies]
|
||||
# Backend: GLES
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
web-sys = { workspace = true, optional = true, features = [
|
||||
"default",
|
||||
"Window",
|
||||
"HtmlCanvasElement",
|
||||
"WebGl2RenderingContext",
|
||||
"OffscreenCanvas",
|
||||
"VideoFrame",
|
||||
] }
|
||||
js-sys = { workspace = true, optional = true, default-features = true }
|
||||
|
||||
############################
|
||||
### Platform: Emscripten ###
|
||||
############################
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies]
|
||||
# Backend: GLES
|
||||
khronos-egl = { workspace = true, optional = true, features = [
|
||||
"static",
|
||||
"no-pkg-config",
|
||||
] }
|
||||
# Note: it's unused by emscripten, but we keep it to have single code base in egl.rs
|
||||
libloading = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies]
|
||||
portable-atomic = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies]
|
||||
portable-atomic-util = { workspace = true, features = [
|
||||
"alloc",
|
||||
], optional = true }
|
||||
|
||||
[build-dependencies]
|
||||
cfg_aliases.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger.workspace = true
|
||||
glam.workspace = true # for ray-traced-triangle example
|
||||
naga = { workspace = true, features = ["wgsl-in", "termcolor"] }
|
||||
winit.workspace = true # for "halmark" example
|
||||
|
||||
### Platform: Windows + MacOS + Linux for "raw-gles" example ###
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies]
|
||||
glutin-winit = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
|
||||
glutin = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
|
||||
Vendored
+176
@@ -0,0 +1,176 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 The gfx-rs developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+119
@@ -0,0 +1,119 @@
|
||||
# `wgpu_hal`: a cross-platform unsafe graphics abstraction
|
||||
|
||||
This crate defines a set of traits abstracting over modern graphics APIs,
|
||||
with implementations ("backends") for Vulkan, Metal, Direct3D, and GL.
|
||||
|
||||
`wgpu_hal` is a spiritual successor to
|
||||
[gfx-hal](https://github.com/gfx-rs/gfx), but with reduced scope, and
|
||||
oriented towards WebGPU implementation goals. It has no overhead for
|
||||
validation or tracking, and the API translation overhead is kept to the bare
|
||||
minimum by the design of WebGPU. This API can be used for resource-demanding
|
||||
applications and engines.
|
||||
|
||||
The `wgpu_hal` crate's main design choices:
|
||||
|
||||
- Our traits are meant to be _portable_: proper use
|
||||
should get equivalent results regardless of the backend.
|
||||
|
||||
- Our traits' contracts are _unsafe_: implementations perform minimal
|
||||
validation, if any, and incorrect use will often cause undefined behavior.
|
||||
This allows us to minimize the overhead we impose over the underlying
|
||||
graphics system. If you need safety, the [`wgpu-core`] crate provides a
|
||||
safe API for driving `wgpu_hal`, implementing all necessary validation,
|
||||
resource state tracking, and so on. (Note that `wgpu-core` is designed for
|
||||
use via FFI; the [`wgpu`] crate provides more idiomatic Rust bindings for
|
||||
`wgpu-core`.) Or, you can do your own validation.
|
||||
|
||||
- In the same vein, returned errors _only cover cases the user can't
|
||||
anticipate_, like running out of memory or losing the device. Any errors
|
||||
that the user could reasonably anticipate are their responsibility to
|
||||
avoid. For example, `wgpu_hal` returns no error for mapping a buffer that's
|
||||
not mappable: as the buffer creator, the user should already know if they
|
||||
can map it.
|
||||
|
||||
- We use _static dispatch_. The traits are not
|
||||
generally object-safe. You must select a specific backend type
|
||||
like [`vulkan::Api`] or [`metal::Api`], and then use that
|
||||
according to the main traits, or call backend-specific methods.
|
||||
|
||||
- We use _idiomatic Rust parameter passing_,
|
||||
taking objects by reference, returning them by value, and so on,
|
||||
unlike `wgpu-core`, which refers to objects by ID.
|
||||
|
||||
- We map buffer contents _persistently_. This means that the buffer
|
||||
can remain mapped on the CPU while the GPU reads or writes to it.
|
||||
You must explicitly indicate when data might need to be
|
||||
transferred between CPU and GPU, if `wgpu_hal` indicates that the
|
||||
mapping is not coherent (that is, automatically synchronized
|
||||
between the two devices).
|
||||
|
||||
- You must record _explicit barriers_ between different usages of a
|
||||
resource. For example, if a buffer is written to by a compute
|
||||
shader, and then used as and index buffer to a draw call, you
|
||||
must use [`CommandEncoder::transition_buffers`] between those two
|
||||
operations.
|
||||
|
||||
- Pipeline layouts are _explicitly specified_ when setting bind
|
||||
group. Incompatible layouts disturb groups bound at higher indices.
|
||||
|
||||
- The API _accepts collections as iterators_, to avoid forcing the user to
|
||||
store data in particular containers. The implementation doesn't guarantee
|
||||
that any of the iterators are drained, unless stated otherwise by the
|
||||
function documentation. For this reason, we recommend that iterators don't
|
||||
do any mutating work.
|
||||
|
||||
Unfortunately, `wgpu_hal`'s safety requirements are not fully documented.
|
||||
Ideally, all trait methods would have doc comments setting out the
|
||||
requirements users must meet to ensure correct and portable behavior. If you
|
||||
are aware of a specific requirement that a backend imposes that is not
|
||||
ensured by the traits' documented rules, please file an issue. Or, if you are
|
||||
a capable technical writer, please file a pull request!
|
||||
|
||||
[`wgpu-core`]: https://crates.io/crates/wgpu-core
|
||||
[`wgpu`]: https://crates.io/crates/wgpu
|
||||
[`vulkan::Api`]: vulkan/struct.Api.html
|
||||
[`metal::Api`]: metal/struct.Api.html
|
||||
|
||||
## Primary backends
|
||||
|
||||
The `wgpu_hal` crate has full-featured backends implemented on the following
|
||||
platform graphics APIs:
|
||||
|
||||
- Vulkan, available on Linux, Android, and Windows, using the [`ash`] crate's
|
||||
Vulkan bindings. It's also available on macOS, if you install [MoltenVK].
|
||||
|
||||
- Metal on macOS, using the [`metal`] crate's bindings.
|
||||
|
||||
- Direct3D 12 on Windows, using the [`windows`] crate's bindings.
|
||||
|
||||
[`ash`]: https://crates.io/crates/ash
|
||||
[MoltenVK]: https://github.com/KhronosGroup/MoltenVK
|
||||
[`metal`]: https://crates.io/crates/metal
|
||||
[`windows`]: https://crates.io/crates/windows
|
||||
|
||||
## Secondary backends
|
||||
|
||||
The `wgpu_hal` crate has a partial implementation based on the following
|
||||
platform graphics API:
|
||||
|
||||
- The GL backend is available anywhere OpenGL, OpenGL ES, or WebGL are
|
||||
available. See the [`gles`] module documentation for details.
|
||||
|
||||
[`gles`]: gles/index.html
|
||||
|
||||
You can see what capabilities an adapter is missing by checking the
|
||||
[`DownlevelCapabilities`][tdc] in [`ExposedAdapter::capabilities`], available
|
||||
from [`Instance::enumerate_adapters`].
|
||||
|
||||
The API is generally designed to fit the primary backends better than the
|
||||
secondary backends, so the latter may impose more overhead.
|
||||
|
||||
[tdc]: wgt::DownlevelCapabilities
|
||||
|
||||
## Debugging
|
||||
|
||||
Most of the information on the wiki [Debugging wgpu Applications][wiki-debug]
|
||||
page still applies to this API, with the exception of API tracing/replay
|
||||
functionality, which is only available in `wgpu-core`.
|
||||
|
||||
[wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
fn main() {
|
||||
cfg_aliases::cfg_aliases! {
|
||||
native: { not(target_arch = "wasm32") },
|
||||
send_sync: { any(
|
||||
not(target_arch = "wasm32"),
|
||||
all(feature = "fragile-send-sync-non-atomic-wasm", not(target_feature = "atomics"))
|
||||
) },
|
||||
webgl: { all(target_arch = "wasm32", not(target_os = "emscripten"), gles) },
|
||||
Emscripten: { all(target_os = "emscripten", gles) },
|
||||
dx12: { all(target_os = "windows", feature = "dx12") },
|
||||
gles: { all(feature = "gles") },
|
||||
// Within the GL ES backend, use `std` and be Send + Sync only if we are using a target
|
||||
// that, among the ones where the GL ES backend is supported, has `std`.
|
||||
gles_with_std: { all(
|
||||
feature = "gles",
|
||||
any(
|
||||
not(target_arch = "wasm32"),
|
||||
// Accept wasm32-unknown-unknown, which uniquely has a stub `std`
|
||||
all(target_vendor = "unknown", target_os = "unknown"),
|
||||
// Accept wasm32-unknown-emscripten and similar, which has a real `std`
|
||||
target_os = "emscripten"
|
||||
)
|
||||
) },
|
||||
metal: { all(target_vendor = "apple", feature = "metal") },
|
||||
vulkan: { all(not(target_arch = "wasm32"), feature = "vulkan") },
|
||||
drm: { all(
|
||||
feature = "drm",
|
||||
any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")
|
||||
) },
|
||||
any_backend: { any(dx12, metal, vulkan, gles) },
|
||||
// ⚠️ Keep in sync with target.cfg() definition in Cargo.toml and cfg_alias in `wgpu` crate ⚠️
|
||||
static_dxc: { all(target_os = "windows", feature = "static-dxc", not(target_arch = "aarch64"), target_env = "msvc") },
|
||||
supports_64bit_atomics: { target_has_atomic = "64" },
|
||||
supports_ptr_atomics: { target_has_atomic = "ptr" }
|
||||
}
|
||||
}
|
||||
+919
@@ -0,0 +1,919 @@
|
||||
//! This example shows basic usage of wgpu-hal by rendering
|
||||
//! a ton of moving sprites, each with a separate texture and draw call.
|
||||
extern crate wgpu_hal as hal;
|
||||
|
||||
use hal::{
|
||||
Adapter as _, CommandEncoder as _, Device as _, Instance as _, Queue as _, Surface as _,
|
||||
};
|
||||
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{ElementState, KeyEvent, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow},
|
||||
keyboard::{Key, NamedKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
use std::{
|
||||
borrow::{Borrow, Cow},
|
||||
iter,
|
||||
num::NonZeroU64,
|
||||
ptr,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
const MAX_BUNNIES: usize = 1 << 20;
|
||||
const BUNNY_SIZE: f32 = 0.15 * 256.0;
|
||||
const GRAVITY: f32 = -9.8 * 100.0;
|
||||
const MAX_VELOCITY: f32 = 750.0;
|
||||
const DESIRED_MAX_LATENCY: u32 = 2;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Globals {
|
||||
mvp: [[f32; 4]; 4],
|
||||
size: [f32; 2],
|
||||
pad: [f32; 2],
|
||||
}
|
||||
|
||||
#[repr(C, align(256))]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Locals {
|
||||
position: [f32; 2],
|
||||
velocity: [f32; 2],
|
||||
color: u32,
|
||||
_pad: u32,
|
||||
}
|
||||
|
||||
struct ExecutionContext<A: hal::Api> {
|
||||
encoder: A::CommandEncoder,
|
||||
fence: A::Fence,
|
||||
fence_value: hal::FenceValue,
|
||||
used_views: Vec<A::TextureView>,
|
||||
used_cmd_bufs: Vec<A::CommandBuffer>,
|
||||
frames_recorded: usize,
|
||||
}
|
||||
|
||||
impl<A: hal::Api> ExecutionContext<A> {
|
||||
unsafe fn wait_and_clear(&mut self, device: &A::Device) {
|
||||
device.wait(&self.fence, self.fence_value, None).unwrap();
|
||||
self.encoder.reset_all(self.used_cmd_bufs.drain(..));
|
||||
for view in self.used_views.drain(..) {
|
||||
device.destroy_texture_view(view);
|
||||
}
|
||||
self.frames_recorded = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
struct Example<A: hal::Api> {
|
||||
instance: A::Instance,
|
||||
adapter: A::Adapter,
|
||||
surface: A::Surface,
|
||||
surface_format: wgpu_types::TextureFormat,
|
||||
device: A::Device,
|
||||
queue: A::Queue,
|
||||
global_group: A::BindGroup,
|
||||
local_group: A::BindGroup,
|
||||
global_group_layout: A::BindGroupLayout,
|
||||
local_group_layout: A::BindGroupLayout,
|
||||
pipeline_layout: A::PipelineLayout,
|
||||
shader: A::ShaderModule,
|
||||
pipeline: A::RenderPipeline,
|
||||
bunnies: Vec<Locals>,
|
||||
local_buffer: A::Buffer,
|
||||
local_alignment: u32,
|
||||
global_buffer: A::Buffer,
|
||||
sampler: A::Sampler,
|
||||
texture: A::Texture,
|
||||
texture_view: A::TextureView,
|
||||
contexts: Vec<ExecutionContext<A>>,
|
||||
context_index: usize,
|
||||
extent: [u32; 2],
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
impl<A: hal::Api> Example<A> {
|
||||
fn init(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
// The Instance can be initialized with the DisplayHandle from the EventLoop as well
|
||||
let raw_display_handle = window.display_handle()?;
|
||||
|
||||
let instance_desc = hal::InstanceDescriptor {
|
||||
name: "example",
|
||||
flags: wgpu_types::InstanceFlags::from_build_config().with_env(),
|
||||
memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds::default(),
|
||||
// Can't rely on having DXC available, so use FXC instead
|
||||
backend_options: wgpu_types::BackendOptions::default(),
|
||||
telemetry: None,
|
||||
display: Some(raw_display_handle),
|
||||
};
|
||||
let instance = unsafe { A::Instance::init(&instance_desc)? };
|
||||
let surface = {
|
||||
let raw_window_handle = window.window_handle()?.as_raw();
|
||||
|
||||
unsafe {
|
||||
instance
|
||||
.create_surface(raw_display_handle.as_raw(), raw_window_handle)
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
|
||||
let (adapter, capabilities) = unsafe {
|
||||
let mut adapters = instance.enumerate_adapters(Some(&surface));
|
||||
if adapters.is_empty() {
|
||||
return Err("no adapters found".into());
|
||||
}
|
||||
let exposed = adapters.swap_remove(0);
|
||||
(exposed.adapter, exposed.capabilities)
|
||||
};
|
||||
|
||||
let surface_caps = unsafe { adapter.surface_capabilities(&surface) }
|
||||
.ok_or("failed to get surface capabilities")?;
|
||||
log::info!("Surface caps: {surface_caps:#?}");
|
||||
|
||||
let hal::OpenDevice { device, queue } = unsafe {
|
||||
adapter
|
||||
.open(
|
||||
wgpu_types::Features::empty(),
|
||||
&wgpu_types::Limits::default(),
|
||||
&wgpu_types::MemoryHints::default(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let window_size: (u32, u32) = window.inner_size().into();
|
||||
let surface_config = hal::SurfaceConfiguration {
|
||||
maximum_frame_latency: DESIRED_MAX_LATENCY.clamp(
|
||||
*surface_caps.maximum_frame_latency.start(),
|
||||
*surface_caps.maximum_frame_latency.end(),
|
||||
),
|
||||
present_mode: wgpu_types::PresentMode::Fifo,
|
||||
composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque,
|
||||
format: wgpu_types::TextureFormat::Bgra8UnormSrgb,
|
||||
color_space: wgpu_types::SurfaceColorSpace::Srgb,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width: window_size.0,
|
||||
height: window_size.1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
view_formats: vec![],
|
||||
};
|
||||
unsafe {
|
||||
surface.configure(&device, &surface_config).unwrap();
|
||||
};
|
||||
|
||||
let naga_shader = {
|
||||
let shader_file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("examples")
|
||||
.join("halmark")
|
||||
.join("shader.wgsl");
|
||||
let source = std::fs::read_to_string(shader_file).unwrap();
|
||||
let module = naga::front::wgsl::Frontend::new().parse(&source).unwrap();
|
||||
let info = naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::empty(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
hal::NagaShader {
|
||||
module: Cow::Owned(module),
|
||||
info,
|
||||
debug_source: None,
|
||||
}
|
||||
};
|
||||
let shader_desc = hal::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(),
|
||||
};
|
||||
let shader = unsafe {
|
||||
device
|
||||
.create_shader_module(&shader_desc, hal::ShaderInput::Naga(naga_shader))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let global_bgl_desc = hal::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::BindGroupLayoutFlags::empty(),
|
||||
entries: &[
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu_types::ShaderStages::VERTEX,
|
||||
ty: wgpu_types::BindingType::Buffer {
|
||||
ty: wgpu_types::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu_types::BufferSize::new(size_of::<Globals>() as _),
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu_types::ShaderStages::FRAGMENT,
|
||||
ty: wgpu_types::BindingType::Texture {
|
||||
sample_type: wgpu_types::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu_types::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu_types::ShaderStages::FRAGMENT,
|
||||
ty: wgpu_types::BindingType::Sampler(wgpu_types::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let global_group_layout =
|
||||
unsafe { device.create_bind_group_layout(&global_bgl_desc).unwrap() };
|
||||
|
||||
let local_bgl_desc = hal::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::BindGroupLayoutFlags::empty(),
|
||||
entries: &[wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu_types::ShaderStages::VERTEX,
|
||||
ty: wgpu_types::BindingType::Buffer {
|
||||
ty: wgpu_types::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: true,
|
||||
min_binding_size: wgpu_types::BufferSize::new(size_of::<Locals>() as _),
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
};
|
||||
let local_group_layout =
|
||||
unsafe { device.create_bind_group_layout(&local_bgl_desc).unwrap() };
|
||||
|
||||
let pipeline_layout_desc = hal::PipelineLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::PipelineLayoutFlags::empty(),
|
||||
bind_group_layouts: &[Some(&global_group_layout), Some(&local_group_layout)],
|
||||
immediate_size: 0,
|
||||
};
|
||||
let pipeline_layout = unsafe {
|
||||
device
|
||||
.create_pipeline_layout(&pipeline_layout_desc)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let constants = naga::back::PipelineConstants::default();
|
||||
let pipeline_desc = hal::RenderPipelineDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline_layout,
|
||||
vertex_processor: hal::VertexProcessor::Standard {
|
||||
vertex_stage: hal::ProgrammableStage {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
constants: &constants,
|
||||
zero_initialize_workgroup_memory: true,
|
||||
},
|
||||
vertex_buffers: &[],
|
||||
},
|
||||
fragment_stage: Some(hal::ProgrammableStage {
|
||||
module: &shader,
|
||||
entry_point: "fs_main",
|
||||
constants: &constants,
|
||||
zero_initialize_workgroup_memory: true,
|
||||
}),
|
||||
primitive: wgpu_types::PrimitiveState {
|
||||
topology: wgpu_types::PrimitiveTopology::TriangleStrip,
|
||||
..wgpu_types::PrimitiveState::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu_types::MultisampleState::default(),
|
||||
color_targets: &[Some(wgpu_types::ColorTargetState {
|
||||
format: surface_config.format,
|
||||
blend: Some(wgpu_types::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu_types::ColorWrites::default(),
|
||||
})],
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
};
|
||||
let pipeline = unsafe { device.create_render_pipeline(&pipeline_desc).unwrap() };
|
||||
|
||||
let texture_data = [0xFFu8; 4];
|
||||
|
||||
let staging_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("stage"),
|
||||
size: texture_data.len() as wgpu_types::BufferAddress,
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::COPY_SRC,
|
||||
memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let staging_buffer = unsafe { device.create_buffer(&staging_buffer_desc).unwrap() };
|
||||
unsafe {
|
||||
let mapping = device
|
||||
.map_buffer(&staging_buffer, 0..staging_buffer_desc.size)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
texture_data.as_ptr(),
|
||||
mapping.ptr.as_ptr(),
|
||||
texture_data.len(),
|
||||
);
|
||||
device.unmap_buffer(&staging_buffer);
|
||||
assert!(mapping.is_coherent);
|
||||
}
|
||||
|
||||
let texture_desc = hal::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu_types::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu_types::TextureDimension::D2,
|
||||
format: wgpu_types::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu_types::TextureUses::COPY_DST | wgpu_types::TextureUses::RESOURCE,
|
||||
memory_flags: hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
};
|
||||
let texture = unsafe { device.create_texture(&texture_desc).unwrap() };
|
||||
|
||||
let cmd_encoder_desc = hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &queue,
|
||||
};
|
||||
let mut cmd_encoder = unsafe { device.create_command_encoder(&cmd_encoder_desc).unwrap() };
|
||||
unsafe { cmd_encoder.begin_encoding(Some("init")).unwrap() };
|
||||
{
|
||||
let buffer_barrier = hal::BufferBarrier {
|
||||
buffer: &staging_buffer,
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::BufferUses::empty(),
|
||||
to: wgpu_types::BufferUses::COPY_SRC,
|
||||
},
|
||||
};
|
||||
let texture_barrier1 = hal::TextureBarrier {
|
||||
texture: &texture,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::UNINITIALIZED,
|
||||
to: wgpu_types::TextureUses::COPY_DST,
|
||||
},
|
||||
};
|
||||
let texture_barrier2 = hal::TextureBarrier {
|
||||
texture: &texture,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::COPY_DST,
|
||||
to: wgpu_types::TextureUses::RESOURCE,
|
||||
},
|
||||
};
|
||||
let copy = hal::BufferTextureCopy {
|
||||
buffer_layout: wgpu_types::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(4),
|
||||
rows_per_image: None,
|
||||
},
|
||||
texture_base: hal::TextureCopyBase {
|
||||
origin: wgpu_types::Origin3d::ZERO,
|
||||
mip_level: 0,
|
||||
array_layer: 0,
|
||||
aspect: hal::FormatAspects::COLOR,
|
||||
},
|
||||
size: hal::CopyExtent {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth: 1,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
cmd_encoder.transition_buffers(iter::once(buffer_barrier));
|
||||
cmd_encoder.transition_textures(iter::once(texture_barrier1));
|
||||
cmd_encoder.copy_buffer_to_texture(&staging_buffer, &texture, iter::once(copy));
|
||||
cmd_encoder.transition_textures(iter::once(texture_barrier2));
|
||||
}
|
||||
}
|
||||
|
||||
let sampler_desc = hal::SamplerDescriptor {
|
||||
label: None,
|
||||
address_modes: [wgpu_types::AddressMode::ClampToEdge; 3],
|
||||
mag_filter: wgpu_types::FilterMode::Linear,
|
||||
min_filter: wgpu_types::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu_types::MipmapFilterMode::Nearest,
|
||||
lod_clamp: 0.0..32.0,
|
||||
compare: None,
|
||||
anisotropy_clamp: 1,
|
||||
border_color: None,
|
||||
};
|
||||
let sampler = unsafe { device.create_sampler(&sampler_desc).unwrap() };
|
||||
|
||||
let globals = Globals {
|
||||
// cgmath::ortho() projection
|
||||
mvp: [
|
||||
[2.0 / window_size.0 as f32, 0.0, 0.0, 0.0],
|
||||
[0.0, 2.0 / window_size.1 as f32, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[-1.0, -1.0, 0.0, 1.0],
|
||||
],
|
||||
size: [BUNNY_SIZE; 2],
|
||||
pad: [0.0; 2],
|
||||
};
|
||||
|
||||
let global_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("global"),
|
||||
size: size_of::<Globals>() as wgpu_types::BufferAddress,
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM,
|
||||
memory_flags: hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let global_buffer = unsafe {
|
||||
let buffer = device.create_buffer(&global_buffer_desc).unwrap();
|
||||
let mapping = device
|
||||
.map_buffer(&buffer, 0..global_buffer_desc.size)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
&globals as *const Globals as *const u8,
|
||||
mapping.ptr.as_ptr(),
|
||||
size_of::<Globals>(),
|
||||
);
|
||||
device.unmap_buffer(&buffer);
|
||||
assert!(mapping.is_coherent);
|
||||
buffer
|
||||
};
|
||||
|
||||
let local_alignment = wgpu_types::math::align_to(
|
||||
size_of::<Locals>() as u32,
|
||||
capabilities.limits.min_uniform_buffer_offset_alignment,
|
||||
);
|
||||
let local_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("local"),
|
||||
size: (MAX_BUNNIES as wgpu_types::BufferAddress)
|
||||
* (local_alignment as wgpu_types::BufferAddress),
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM,
|
||||
memory_flags: hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let local_buffer = unsafe { device.create_buffer(&local_buffer_desc).unwrap() };
|
||||
|
||||
let view_desc = hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format: texture_desc.format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::RESOURCE,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
};
|
||||
let texture_view = unsafe { device.create_texture_view(&texture, &view_desc).unwrap() };
|
||||
|
||||
let global_group = {
|
||||
// SAFETY: This is the same size that was specified for buffer creation.
|
||||
let global_buffer_binding = hal::BufferBinding::new_unchecked(
|
||||
&global_buffer,
|
||||
0,
|
||||
NonZeroU64::new(global_buffer_desc.size),
|
||||
);
|
||||
let texture_binding = hal::TextureBinding {
|
||||
view: &texture_view,
|
||||
usage: wgpu_types::TextureUses::RESOURCE,
|
||||
};
|
||||
let global_group_desc = hal::BindGroupDescriptor {
|
||||
label: Some("global"),
|
||||
layout: &global_group_layout,
|
||||
buffers: &[global_buffer_binding],
|
||||
samplers: &[&sampler],
|
||||
textures: &[texture_binding],
|
||||
acceleration_structures: &[],
|
||||
external_textures: &[],
|
||||
entries: &[
|
||||
hal::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
hal::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
hal::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
unsafe { device.create_bind_group(&global_group_desc).unwrap() }
|
||||
};
|
||||
|
||||
let local_group = {
|
||||
// SAFETY: The size must fit within the buffer.
|
||||
let local_buffer_binding = hal::BufferBinding::new_unchecked(
|
||||
&local_buffer,
|
||||
0,
|
||||
wgpu_types::BufferSize::new(size_of::<Locals>() as _),
|
||||
);
|
||||
let local_group_desc = hal::BindGroupDescriptor {
|
||||
label: Some("local"),
|
||||
layout: &local_group_layout,
|
||||
buffers: &[local_buffer_binding],
|
||||
samplers: &[],
|
||||
textures: &[],
|
||||
acceleration_structures: &[],
|
||||
external_textures: &[],
|
||||
entries: &[hal::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
}],
|
||||
};
|
||||
unsafe { device.create_bind_group(&local_group_desc).unwrap() }
|
||||
};
|
||||
|
||||
let init_fence_value = 1;
|
||||
let fence = unsafe {
|
||||
let mut fence = device.create_fence().unwrap();
|
||||
let init_cmd = cmd_encoder.end_encoding().unwrap();
|
||||
queue
|
||||
.submit(&[&init_cmd], &[], (&mut fence, init_fence_value))
|
||||
.unwrap();
|
||||
device.wait(&fence, init_fence_value, None).unwrap();
|
||||
device.destroy_buffer(staging_buffer);
|
||||
cmd_encoder.reset_all(iter::once(init_cmd));
|
||||
fence
|
||||
};
|
||||
|
||||
Ok(Example {
|
||||
instance,
|
||||
surface,
|
||||
surface_format: surface_config.format,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
pipeline_layout,
|
||||
shader,
|
||||
pipeline,
|
||||
global_group,
|
||||
local_group,
|
||||
global_group_layout,
|
||||
local_group_layout,
|
||||
bunnies: Vec::new(),
|
||||
local_buffer,
|
||||
local_alignment,
|
||||
global_buffer,
|
||||
sampler,
|
||||
texture,
|
||||
texture_view,
|
||||
contexts: vec![ExecutionContext {
|
||||
encoder: cmd_encoder,
|
||||
fence,
|
||||
fence_value: init_fence_value + 1,
|
||||
used_views: Vec::new(),
|
||||
used_cmd_bufs: Vec::new(),
|
||||
frames_recorded: 0,
|
||||
}],
|
||||
context_index: 0,
|
||||
extent: [window_size.0, window_size.1],
|
||||
start: Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.bunnies.is_empty()
|
||||
}
|
||||
|
||||
fn exit(mut self) {
|
||||
unsafe {
|
||||
{
|
||||
let ctx = &mut self.contexts[self.context_index];
|
||||
self.queue
|
||||
.submit(&[], &[], (&mut ctx.fence, ctx.fence_value))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
for mut ctx in self.contexts {
|
||||
ctx.wait_and_clear(&self.device);
|
||||
drop(ctx.encoder);
|
||||
self.device.destroy_fence(ctx.fence);
|
||||
}
|
||||
|
||||
self.device.destroy_bind_group(self.local_group);
|
||||
self.device.destroy_bind_group(self.global_group);
|
||||
self.device.destroy_buffer(self.local_buffer);
|
||||
self.device.destroy_buffer(self.global_buffer);
|
||||
self.device.destroy_texture_view(self.texture_view);
|
||||
self.device.destroy_texture(self.texture);
|
||||
self.device.destroy_sampler(self.sampler);
|
||||
self.device.destroy_shader_module(self.shader);
|
||||
self.device.destroy_render_pipeline(self.pipeline);
|
||||
self.device
|
||||
.destroy_bind_group_layout(self.local_group_layout);
|
||||
self.device
|
||||
.destroy_bind_group_layout(self.global_group_layout);
|
||||
self.device.destroy_pipeline_layout(self.pipeline_layout);
|
||||
|
||||
self.surface.unconfigure(&self.device);
|
||||
drop(self.queue);
|
||||
drop(self.device);
|
||||
drop(self.surface);
|
||||
drop(self.adapter);
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, event: winit::event::WindowEvent) {
|
||||
if let winit::event::WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Space),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} = event
|
||||
{
|
||||
let spawn_count = 64 + self.bunnies.len() / 2;
|
||||
let elapsed = self.start.elapsed();
|
||||
let color = elapsed.as_nanos() as u32;
|
||||
println!(
|
||||
"Spawning {} bunnies, total at {}",
|
||||
spawn_count,
|
||||
self.bunnies.len() + spawn_count
|
||||
);
|
||||
for i in 0..spawn_count {
|
||||
let random = ((elapsed.as_nanos() * (i + 1) as u128) & 0xFF) as f32 / 255.0;
|
||||
let speed = random * MAX_VELOCITY - (MAX_VELOCITY * 0.5);
|
||||
self.bunnies.push(Locals {
|
||||
position: [0.0, 0.5 * (self.extent[1] as f32)],
|
||||
velocity: [speed, 0.0],
|
||||
color,
|
||||
_pad: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render(&mut self) {
|
||||
let delta = 0.01;
|
||||
for bunny in self.bunnies.iter_mut() {
|
||||
bunny.position[0] += bunny.velocity[0] * delta;
|
||||
bunny.position[1] += bunny.velocity[1] * delta;
|
||||
bunny.velocity[1] += GRAVITY * delta;
|
||||
if (bunny.velocity[0] > 0.0
|
||||
&& bunny.position[0] + 0.5 * BUNNY_SIZE > self.extent[0] as f32)
|
||||
|| (bunny.velocity[0] < 0.0 && bunny.position[0] - 0.5 * BUNNY_SIZE < 0.0)
|
||||
{
|
||||
bunny.velocity[0] *= -1.0;
|
||||
}
|
||||
if bunny.velocity[1] < 0.0 && bunny.position[1] < 0.5 * BUNNY_SIZE {
|
||||
bunny.velocity[1] *= -1.0;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.bunnies.is_empty() {
|
||||
let size = self.bunnies.len() * self.local_alignment as usize;
|
||||
unsafe {
|
||||
let mapping = self
|
||||
.device
|
||||
.map_buffer(&self.local_buffer, 0..size as wgpu_types::BufferAddress)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
self.bunnies.as_ptr() as *const u8,
|
||||
mapping.ptr.as_ptr(),
|
||||
size,
|
||||
);
|
||||
assert!(mapping.is_coherent);
|
||||
self.device.unmap_buffer(&self.local_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
let ctx = &mut self.contexts[self.context_index];
|
||||
|
||||
let surface_tex = unsafe {
|
||||
self.surface
|
||||
.acquire_texture(None, &ctx.fence)
|
||||
.unwrap()
|
||||
.texture
|
||||
};
|
||||
|
||||
let target_barrier0 = hal::TextureBarrier {
|
||||
texture: surface_tex.borrow(),
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::UNINITIALIZED,
|
||||
to: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.begin_encoding(Some("frame")).unwrap();
|
||||
ctx.encoder.transition_textures(iter::once(target_barrier0));
|
||||
}
|
||||
|
||||
let surface_view_desc = hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format: self.surface_format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
};
|
||||
let surface_tex_view = unsafe {
|
||||
self.device
|
||||
.create_texture_view(surface_tex.borrow(), &surface_view_desc)
|
||||
.unwrap()
|
||||
};
|
||||
let pass_desc = hal::RenderPassDescriptor {
|
||||
label: None,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width: self.extent[0],
|
||||
height: self.extent[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
sample_count: 1,
|
||||
color_attachments: &[Some(hal::ColorAttachment {
|
||||
target: hal::Attachment {
|
||||
view: &surface_tex_view,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
|
||||
clear_value: wgpu_types::Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
multiview_mask: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.begin_render_pass(&pass_desc).unwrap();
|
||||
ctx.encoder.set_render_pipeline(&self.pipeline);
|
||||
ctx.encoder
|
||||
.set_bind_group(&self.pipeline_layout, 0, &self.global_group, &[]);
|
||||
}
|
||||
|
||||
for i in 0..self.bunnies.len() {
|
||||
let offset = (i as wgpu_types::DynamicOffset)
|
||||
* (self.local_alignment as wgpu_types::DynamicOffset);
|
||||
unsafe {
|
||||
ctx.encoder
|
||||
.set_bind_group(&self.pipeline_layout, 1, &self.local_group, &[offset]);
|
||||
ctx.encoder.draw(0, 4, 0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.frames_recorded += 1;
|
||||
|
||||
let target_barrier1 = hal::TextureBarrier {
|
||||
texture: surface_tex.borrow(),
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
to: wgpu_types::TextureUses::PRESENT,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.end_render_pass();
|
||||
ctx.encoder.transition_textures(iter::once(target_barrier1));
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let cmd_buf = ctx.encoder.end_encoding().unwrap();
|
||||
self.queue
|
||||
.submit(
|
||||
&[&cmd_buf],
|
||||
&[&surface_tex],
|
||||
(&mut ctx.fence, ctx.fence_value),
|
||||
)
|
||||
.unwrap();
|
||||
self.queue.present(&self.surface, surface_tex).unwrap();
|
||||
ctx.used_cmd_bufs.push(cmd_buf);
|
||||
ctx.used_views.push(surface_tex_view);
|
||||
};
|
||||
|
||||
log::debug!("Context switch from {}", self.context_index);
|
||||
let old_fence_value = ctx.fence_value;
|
||||
if self.contexts.len() == 1 {
|
||||
let hal_desc = hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &self.queue,
|
||||
};
|
||||
self.contexts.push(unsafe {
|
||||
ExecutionContext {
|
||||
encoder: self.device.create_command_encoder(&hal_desc).unwrap(),
|
||||
fence: self.device.create_fence().unwrap(),
|
||||
fence_value: 0,
|
||||
used_views: Vec::new(),
|
||||
used_cmd_bufs: Vec::new(),
|
||||
frames_recorded: 0,
|
||||
}
|
||||
});
|
||||
}
|
||||
self.context_index = (self.context_index + 1) % self.contexts.len();
|
||||
let next = &mut self.contexts[self.context_index];
|
||||
unsafe {
|
||||
next.wait_and_clear(&self.device);
|
||||
}
|
||||
next.fence_value = old_fence_value + 1;
|
||||
}
|
||||
}
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
// Apple + Metal
|
||||
if #[cfg(all(target_vendor = "apple", feature = "metal"))] {
|
||||
type Api = hal::api::Metal;
|
||||
}
|
||||
// Wasm + Vulkan
|
||||
else if #[cfg(all(not(target_arch = "wasm32"), feature = "vulkan"))] {
|
||||
type Api = hal::api::Vulkan;
|
||||
}
|
||||
// Windows + DX12
|
||||
else if #[cfg(all(windows, feature = "dx12"))] {
|
||||
type Api = hal::api::Dx12;
|
||||
}
|
||||
// Anything + GLES
|
||||
else if #[cfg(feature = "gles")] {
|
||||
type Api = hal::api::Gles;
|
||||
}
|
||||
// Fallback
|
||||
else {
|
||||
type Api = hal::api::Noop;
|
||||
}
|
||||
}
|
||||
|
||||
struct App {
|
||||
example: Option<Example<Api>>,
|
||||
window: Option<Window>,
|
||||
last_frame_inst: Instant,
|
||||
frame_count: u32,
|
||||
accum_time: f32,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
}
|
||||
let window = event_loop
|
||||
.create_window(Window::default_attributes().with_title("hal-bunnymark"))
|
||||
.unwrap();
|
||||
let example = Example::<Api>::init(&window).expect("Selected backend is not supported");
|
||||
self.window = Some(window);
|
||||
self.example = Some(example);
|
||||
println!("Press space to spawn bunnies.");
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
|
||||
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
self.example.take().unwrap().exit();
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
|
||||
match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Escape),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
}
|
||||
| WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
let ex = self.example.as_mut().unwrap();
|
||||
{
|
||||
self.accum_time += self.last_frame_inst.elapsed().as_secs_f32();
|
||||
self.last_frame_inst = Instant::now();
|
||||
self.frame_count += 1;
|
||||
if self.frame_count == 100 && !ex.is_empty() {
|
||||
println!(
|
||||
"Avg frame time {}ms",
|
||||
self.accum_time * 1000.0 / self.frame_count as f32
|
||||
);
|
||||
self.accum_time = 0.0;
|
||||
self.frame_count = 0;
|
||||
}
|
||||
}
|
||||
ex.render();
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
_ => {
|
||||
self.example.as_mut().unwrap().update(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
||||
let mut app = App {
|
||||
example: None,
|
||||
window: None,
|
||||
last_frame_inst: Instant::now(),
|
||||
frame_count: 0,
|
||||
accum_time: 0.0,
|
||||
};
|
||||
event_loop.run_app(&mut app).unwrap();
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
struct Globals {
|
||||
mvp: mat4x4<f32>,
|
||||
size: vec2<f32>,
|
||||
_pad0: u32,
|
||||
_pad1: u32,
|
||||
};
|
||||
|
||||
struct Locals {
|
||||
position: vec2<f32>,
|
||||
velocity: vec2<f32>,
|
||||
color: u32,
|
||||
_pad0: u32,
|
||||
_pad1: u32,
|
||||
_pad2: u32,
|
||||
};
|
||||
|
||||
@group(0)
|
||||
@binding(0)
|
||||
var<uniform> globals: Globals;
|
||||
|
||||
@group(1)
|
||||
@binding(0)
|
||||
var<uniform> locals: Locals;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) tex_coords: vec2<f32>,
|
||||
@location(1) color: vec4<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
|
||||
let tc = vec2<f32>(f32(vi & 1u), 0.5 * f32(vi & 2u));
|
||||
let offset = vec2<f32>(tc.x * globals.size.x, tc.y * globals.size.y);
|
||||
let pos = globals.mvp * vec4<f32>(locals.position + offset, 0.0, 1.0);
|
||||
let color = vec4<f32>((vec4<u32>(locals.color) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(255u)) / 255.0;
|
||||
return VertexOutput(pos, tc, color);
|
||||
}
|
||||
|
||||
@group(0)
|
||||
@binding(1)
|
||||
var tex: texture_2d<f32>;
|
||||
@group(0)
|
||||
@binding(2)
|
||||
var sam: sampler;
|
||||
|
||||
@fragment
|
||||
fn fs_main(vertex: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return vertex.color * textureSampleLevel(tex, sam, vertex.tex_coords, 0.0);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="canvas" width="640" height="400"></canvas>
|
||||
<script>
|
||||
var Module = {
|
||||
canvas: document.getElementById("canvas"),
|
||||
preRun: [
|
||||
function () {
|
||||
ENV.RUST_LOG = "debug";
|
||||
},
|
||||
],
|
||||
};
|
||||
</script>
|
||||
<script src="raw-gles.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
+396
@@ -0,0 +1,396 @@
|
||||
//! This example shows interop with raw GLES contexts -
|
||||
//! the ability to hook up wgpu-hal to an existing context and draw into it.
|
||||
//!
|
||||
//! Emscripten build:
|
||||
//! 1. install emsdk
|
||||
//! 2. build this example with cargo:
|
||||
//! EMCC_CFLAGS="-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 --no-entry -s FULL_ES3=1" cargo build --example raw-gles --target wasm32-unknown-emscripten
|
||||
//! 3. copy raw-gles.em.html into target directory and open it in browser:
|
||||
//! cp wgpu-hal/examples/raw-gles.em.html target/wasm32-unknown-emscripten/debug/examples
|
||||
|
||||
extern crate wgpu_hal as hal;
|
||||
|
||||
#[cfg(not(any(
|
||||
target_arch = "wasm32",
|
||||
target_os = "ios",
|
||||
target_os = "visionos",
|
||||
target_env = "ohos"
|
||||
)))]
|
||||
fn main() {
|
||||
use std::ffi::CString;
|
||||
|
||||
use glutin::{
|
||||
config::GlConfig as _,
|
||||
context::{NotCurrentGlContext as _, PossiblyCurrentGlContext as _, Version},
|
||||
display::{GetGlDisplay as _, GlDisplay as _},
|
||||
surface::GlSurface as _,
|
||||
};
|
||||
use glutin_winit::GlWindow as _;
|
||||
use raw_window_handle::HasWindowHandle as _;
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{KeyEvent, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
|
||||
keyboard::{Key, NamedKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
env_logger::init();
|
||||
println!("Initializing external GL context");
|
||||
|
||||
/// Find the config with the maximum number of samples, so our triangle will be
|
||||
/// smooth.
|
||||
fn gl_config_picker(
|
||||
configs: Box<dyn Iterator<Item = glutin::config::Config> + '_>,
|
||||
) -> glutin::config::Config {
|
||||
configs
|
||||
.reduce(|accum, config| {
|
||||
if config.num_samples() > accum.num_samples() {
|
||||
config
|
||||
} else {
|
||||
accum
|
||||
}
|
||||
})
|
||||
.expect("Failed to find a matching config")
|
||||
}
|
||||
|
||||
struct App {
|
||||
gl_config: Option<glutin::config::Config>,
|
||||
not_current_gl_context: Option<glutin::context::NotCurrentContext>,
|
||||
state: Option<(
|
||||
glutin::context::PossiblyCurrentContext,
|
||||
glutin::surface::Surface<glutin::surface::WindowSurface>,
|
||||
Window,
|
||||
)>,
|
||||
exposed: Option<hal::ExposedAdapter<hal::api::Gles>>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
gl_config: None,
|
||||
not_current_gl_context: None,
|
||||
state: None,
|
||||
exposed: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
// First call: create display, pick config, create GL context.
|
||||
if self.gl_config.is_none() {
|
||||
// Only Windows requires the window to be present before creating the display.
|
||||
// Other platforms don't really need one.
|
||||
let window_attributes = cfg!(windows).then(|| {
|
||||
Window::default_attributes()
|
||||
.with_title("wgpu raw GLES example (press Escape to exit)")
|
||||
});
|
||||
|
||||
let template = glutin::config::ConfigTemplateBuilder::new();
|
||||
|
||||
let display_builder =
|
||||
glutin_winit::DisplayBuilder::new().with_window_attributes(window_attributes);
|
||||
|
||||
let (window, gl_config) = display_builder
|
||||
.build(event_loop, template, gl_config_picker)
|
||||
.expect("Failed to build window and config from display");
|
||||
|
||||
println!("Picked a config with {} samples", gl_config.num_samples());
|
||||
|
||||
let raw_window_handle = window
|
||||
.as_ref()
|
||||
.and_then(|window| window.window_handle().ok())
|
||||
.map(|handle| handle.as_raw());
|
||||
|
||||
let gl_display = gl_config.display();
|
||||
|
||||
// Glutin tries to create an OpenGL context by default.
|
||||
// Force it to use any version of GLES.
|
||||
let context_attributes = glutin::context::ContextAttributesBuilder::new()
|
||||
// wgpu expects GLES 3.0+.
|
||||
.with_context_api(glutin::context::ContextApi::Gles(Some(Version::new(3, 0))))
|
||||
.build(raw_window_handle);
|
||||
|
||||
let gl_context = unsafe {
|
||||
gl_display
|
||||
.create_context(&gl_config, &context_attributes)
|
||||
.expect("failed to create context")
|
||||
};
|
||||
|
||||
self.not_current_gl_context = Some(gl_context);
|
||||
self.gl_config = Some(gl_config);
|
||||
|
||||
// On Windows, the window was already created by DisplayBuilder.
|
||||
if let Some(window) = window {
|
||||
self.create_surface(event_loop, window);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Create window + surface (non-Windows first call, or Android re-resume).
|
||||
if self.state.is_none() {
|
||||
let gl_config = self.gl_config.as_ref().unwrap();
|
||||
let window = glutin_winit::finalize_window(
|
||||
event_loop,
|
||||
Window::default_attributes()
|
||||
.with_title("wgpu raw GLES example (press Escape to exit)"),
|
||||
gl_config,
|
||||
)
|
||||
.unwrap();
|
||||
self.create_surface(event_loop, window);
|
||||
}
|
||||
}
|
||||
|
||||
fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
// This event is only raised on Android, where the backing NativeWindow for a GL
|
||||
// Surface can appear and disappear at any moment.
|
||||
println!("Android window removed");
|
||||
|
||||
// Destroy the GL Surface and un-current the GL Context before ndk-glue releases
|
||||
// the window back to the system.
|
||||
if let Some((gl_context, ..)) = self.state.take() {
|
||||
assert!(self
|
||||
.not_current_gl_context
|
||||
.replace(gl_context.make_not_current().unwrap())
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
event_loop.set_control_flow(ControlFlow::Wait);
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested
|
||||
| WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Escape),
|
||||
..
|
||||
},
|
||||
..
|
||||
} => event_loop.exit(),
|
||||
WindowEvent::Resized(size) => {
|
||||
if size.width != 0 && size.height != 0 {
|
||||
// Some platforms like EGL require resizing GL surface to update the size.
|
||||
// Notable platforms here are Wayland and macOS, other don't require it
|
||||
// and the function is no-op, but it's wise to resize it for portability
|
||||
// reasons.
|
||||
if let Some((gl_context, gl_surface, window)) = &self.state {
|
||||
window.resize_surface(gl_surface, gl_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let (Some(exposed), Some((gl_context, gl_surface, window))) =
|
||||
(&self.exposed, &self.state)
|
||||
{
|
||||
let inner_size = window.inner_size();
|
||||
|
||||
fill_screen(exposed, inner_size.width, inner_size.height);
|
||||
|
||||
println!("Showing the window");
|
||||
gl_surface
|
||||
.swap_buffers(gl_context)
|
||||
.expect("Failed to swap buffers");
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn create_surface(&mut self, _event_loop: &ActiveEventLoop, window: Window) {
|
||||
let gl_config = self.gl_config.as_ref().unwrap();
|
||||
|
||||
let attrs = window
|
||||
.build_surface_attributes(Default::default())
|
||||
.expect("Failed to build surface attributes");
|
||||
let gl_surface = unsafe {
|
||||
gl_config
|
||||
.display()
|
||||
.create_window_surface(gl_config, &attrs)
|
||||
.expect("Cannot create GL WindowSurface")
|
||||
};
|
||||
|
||||
// Make it current.
|
||||
let gl_context = self
|
||||
.not_current_gl_context
|
||||
.take()
|
||||
.unwrap()
|
||||
.make_current(&gl_surface)
|
||||
.expect("GL context cannot be made current with WindowSurface");
|
||||
|
||||
// The context needs to be current for the Renderer to set up shaders and
|
||||
// buffers. It also performs function loading, which needs a current context on
|
||||
// WGL.
|
||||
println!("Hooking up to wgpu-hal");
|
||||
self.exposed.get_or_insert_with(|| {
|
||||
unsafe {
|
||||
<hal::api::Gles as hal::Api>::Adapter::new_external(
|
||||
|name| {
|
||||
// XXX: On WGL this should only be called after the context was
|
||||
// made current
|
||||
gl_config
|
||||
.display()
|
||||
.get_proc_address(&CString::new(name).expect(name))
|
||||
},
|
||||
wgpu_types::GlBackendOptions::default(),
|
||||
)
|
||||
}
|
||||
.expect("GL adapter can't be initialized")
|
||||
});
|
||||
|
||||
window.request_redraw();
|
||||
self.state = Some((gl_context, gl_surface, window));
|
||||
}
|
||||
}
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let mut app = App::new();
|
||||
event_loop
|
||||
.run_app(&mut app)
|
||||
.expect("Couldn't run event loop");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
println!("Initializing external GL context");
|
||||
let egl = khronos_egl::Instance::new(khronos_egl::Static);
|
||||
let display = unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.unwrap();
|
||||
egl.initialize(display)
|
||||
.expect("unable to initialize display");
|
||||
|
||||
let attributes = [
|
||||
khronos_egl::RED_SIZE,
|
||||
8,
|
||||
khronos_egl::GREEN_SIZE,
|
||||
8,
|
||||
khronos_egl::BLUE_SIZE,
|
||||
8,
|
||||
khronos_egl::NONE,
|
||||
];
|
||||
|
||||
let config = egl
|
||||
.choose_first_config(display, &attributes)
|
||||
.unwrap()
|
||||
.expect("unable to choose config");
|
||||
let surface = unsafe {
|
||||
let window = std::ptr::null_mut::<std::ffi::c_void>();
|
||||
egl.create_window_surface(display, config, window, None)
|
||||
}
|
||||
.expect("unable to create surface");
|
||||
|
||||
let context_attributes = [khronos_egl::CONTEXT_CLIENT_VERSION, 3, khronos_egl::NONE];
|
||||
|
||||
let gl_context = egl
|
||||
.create_context(display, config, None, &context_attributes)
|
||||
.expect("unable to create context");
|
||||
egl.make_current(display, Some(surface), Some(surface), Some(gl_context))
|
||||
.expect("can't make context current");
|
||||
|
||||
println!("Hooking up to wgpu-hal");
|
||||
let exposed = unsafe {
|
||||
<hal::api::Gles as hal::Api>::Adapter::new_external(|name| {
|
||||
egl.get_proc_address(name)
|
||||
.map_or(std::ptr::null(), |p| p as *const _)
|
||||
})
|
||||
}
|
||||
.expect("GL adapter can't be initialized");
|
||||
|
||||
fill_screen(&exposed, 640, 400);
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(target_arch = "wasm32", not(target_os = "emscripten")),
|
||||
target_os = "ios",
|
||||
target_os = "visionos",
|
||||
target_env = "ohos"
|
||||
))]
|
||||
fn main() {
|
||||
eprintln!("This example is not supported on this platform")
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
all(target_arch = "wasm32", not(target_os = "emscripten")),
|
||||
target_os = "ios",
|
||||
target_os = "visionos"
|
||||
)))]
|
||||
fn fill_screen(exposed: &hal::ExposedAdapter<hal::api::Gles>, width: u32, height: u32) {
|
||||
use hal::{Adapter as _, CommandEncoder as _, Device as _, Queue as _};
|
||||
|
||||
let od = unsafe {
|
||||
exposed.adapter.open(
|
||||
wgpu_types::Features::empty(),
|
||||
&wgpu_types::Limits::downlevel_defaults(),
|
||||
&wgpu_types::MemoryHints::default(),
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
|
||||
let format = wgpu_types::TextureFormat::Rgba8UnormSrgb;
|
||||
let texture = <hal::api::Gles as hal::Api>::Texture::default_framebuffer(format);
|
||||
let view = unsafe {
|
||||
od.device
|
||||
.create_texture_view(
|
||||
&texture,
|
||||
&hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
println!("Filling the screen");
|
||||
let mut encoder = unsafe {
|
||||
od.device
|
||||
.create_command_encoder(&hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &od.queue,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let mut fence = unsafe { od.device.create_fence().unwrap() };
|
||||
let rp_desc = hal::RenderPassDescriptor {
|
||||
label: None,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
sample_count: 1,
|
||||
color_attachments: &[Some(hal::ColorAttachment {
|
||||
target: hal::Attachment {
|
||||
view: &view,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
|
||||
clear_value: wgpu_types::Color::BLUE,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
multiview_mask: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
};
|
||||
unsafe {
|
||||
encoder.begin_encoding(None).unwrap();
|
||||
encoder.begin_render_pass(&rp_desc).unwrap();
|
||||
encoder.end_render_pass();
|
||||
let cmd_buf = encoder.end_encoding().unwrap();
|
||||
od.queue.submit(&[&cmd_buf], &[], (&mut fence, 0)).unwrap();
|
||||
}
|
||||
}
|
||||
+1225
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,39 @@
|
||||
enable wgpu_ray_query;
|
||||
|
||||
struct Uniforms {
|
||||
view_inv: mat4x4<f32>,
|
||||
proj_inv: mat4x4<f32>,
|
||||
};
|
||||
@group(0) @binding(0)
|
||||
var<uniform> uniforms: Uniforms;
|
||||
|
||||
@group(0) @binding(1)
|
||||
var output: texture_storage_2d<rgba8unorm, write>;
|
||||
|
||||
@group(0) @binding(2)
|
||||
var acc_struct: acceleration_structure;
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
let target_size = textureDimensions(output);
|
||||
|
||||
let pixel_center = vec2<f32>(global_id.xy) + vec2<f32>(0.5);
|
||||
let in_uv = pixel_center / vec2<f32>(target_size.xy);
|
||||
let d = in_uv * 2.0 - 1.0;
|
||||
|
||||
let origin = (uniforms.view_inv * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz;
|
||||
let temp = uniforms.proj_inv * vec4<f32>(d.x, d.y, 1.0, 1.0);
|
||||
let direction = (uniforms.view_inv * vec4<f32>(normalize(temp.xyz), 0.0)).xyz;
|
||||
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, acc_struct, RayDesc(0u, 0xFFu, 0.1, 200.0, origin, direction));
|
||||
rayQueryProceed(&rq);
|
||||
|
||||
var color = vec4<f32>(0.0, 0.0, 0.0, 1.0);
|
||||
let intersection = rayQueryGetCommittedIntersection(&rq);
|
||||
if intersection.kind != RAY_QUERY_INTERSECTION_NONE {
|
||||
color = vec4<f32>(intersection.barycentrics, 1.0 - intersection.barycentrics.x - intersection.barycentrics.y, 1.0);
|
||||
}
|
||||
|
||||
textureStore(output, global_id.xy, color);
|
||||
}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
use alloc::string::String;
|
||||
use std::{ffi::OsString, os::windows::ffi::OsStringExt};
|
||||
|
||||
use windows::Win32::Graphics::Dxgi;
|
||||
|
||||
// Helper to convert DXGI adapter name to a normal string
|
||||
pub fn map_adapter_name(name: [u16; 128]) -> String {
|
||||
let len = name.iter().take_while(|&&c| c != 0).count();
|
||||
let name = OsString::from_wide(&name[..len]);
|
||||
name.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
pub fn map_texture_format_failable(
|
||||
format: wgt::TextureFormat,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
use wgt::TextureFormat as Tf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
Some(match format {
|
||||
Tf::R8Unorm => DXGI_FORMAT_R8_UNORM,
|
||||
Tf::R8Snorm => DXGI_FORMAT_R8_SNORM,
|
||||
Tf::R8Uint => DXGI_FORMAT_R8_UINT,
|
||||
Tf::R8Sint => DXGI_FORMAT_R8_SINT,
|
||||
Tf::R16Uint => DXGI_FORMAT_R16_UINT,
|
||||
Tf::R16Sint => DXGI_FORMAT_R16_SINT,
|
||||
Tf::R16Unorm => DXGI_FORMAT_R16_UNORM,
|
||||
Tf::R16Snorm => DXGI_FORMAT_R16_SNORM,
|
||||
Tf::R16Float => DXGI_FORMAT_R16_FLOAT,
|
||||
Tf::Rg8Unorm => DXGI_FORMAT_R8G8_UNORM,
|
||||
Tf::Rg8Snorm => DXGI_FORMAT_R8G8_SNORM,
|
||||
Tf::Rg8Uint => DXGI_FORMAT_R8G8_UINT,
|
||||
Tf::Rg8Sint => DXGI_FORMAT_R8G8_SINT,
|
||||
Tf::Rg16Unorm => DXGI_FORMAT_R16G16_UNORM,
|
||||
Tf::Rg16Snorm => DXGI_FORMAT_R16G16_SNORM,
|
||||
Tf::R32Uint => DXGI_FORMAT_R32_UINT,
|
||||
Tf::R32Sint => DXGI_FORMAT_R32_SINT,
|
||||
Tf::R32Float => DXGI_FORMAT_R32_FLOAT,
|
||||
Tf::Rg16Uint => DXGI_FORMAT_R16G16_UINT,
|
||||
Tf::Rg16Sint => DXGI_FORMAT_R16G16_SINT,
|
||||
Tf::Rg16Float => DXGI_FORMAT_R16G16_FLOAT,
|
||||
Tf::Rgba8Unorm => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
|
||||
Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
|
||||
Tf::Rgba8Snorm => DXGI_FORMAT_R8G8B8A8_SNORM,
|
||||
Tf::Bgra8Unorm => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
Tf::Rgba8Uint => DXGI_FORMAT_R8G8B8A8_UINT,
|
||||
Tf::Rgba8Sint => DXGI_FORMAT_R8G8B8A8_SINT,
|
||||
Tf::Rgb9e5Ufloat => DXGI_FORMAT_R9G9B9E5_SHAREDEXP,
|
||||
Tf::Rgb10a2Uint => DXGI_FORMAT_R10G10B10A2_UINT,
|
||||
Tf::Rgb10a2Unorm => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
Tf::Rg11b10Ufloat => DXGI_FORMAT_R11G11B10_FLOAT,
|
||||
Tf::R64Uint => DXGI_FORMAT_R32G32_UINT, // R64 emulated by R32G32
|
||||
Tf::Rg32Uint => DXGI_FORMAT_R32G32_UINT,
|
||||
Tf::Rg32Sint => DXGI_FORMAT_R32G32_SINT,
|
||||
Tf::Rg32Float => DXGI_FORMAT_R32G32_FLOAT,
|
||||
Tf::Rgba16Uint => DXGI_FORMAT_R16G16B16A16_UINT,
|
||||
Tf::Rgba16Sint => DXGI_FORMAT_R16G16B16A16_SINT,
|
||||
Tf::Rgba16Unorm => DXGI_FORMAT_R16G16B16A16_UNORM,
|
||||
Tf::Rgba16Snorm => DXGI_FORMAT_R16G16B16A16_SNORM,
|
||||
Tf::Rgba16Float => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
Tf::Rgba32Uint => DXGI_FORMAT_R32G32B32A32_UINT,
|
||||
Tf::Rgba32Sint => DXGI_FORMAT_R32G32B32A32_SINT,
|
||||
Tf::Rgba32Float => DXGI_FORMAT_R32G32B32A32_FLOAT,
|
||||
Tf::Stencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth16Unorm => DXGI_FORMAT_D16_UNORM,
|
||||
Tf::Depth24Plus => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth24PlusStencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth32Float => DXGI_FORMAT_D32_FLOAT,
|
||||
Tf::Depth32FloatStencil8 => DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
|
||||
Tf::NV12 => DXGI_FORMAT_NV12,
|
||||
Tf::P010 => DXGI_FORMAT_P010,
|
||||
Tf::Bc1RgbaUnorm => DXGI_FORMAT_BC1_UNORM,
|
||||
Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_UNORM_SRGB,
|
||||
Tf::Bc2RgbaUnorm => DXGI_FORMAT_BC2_UNORM,
|
||||
Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_UNORM_SRGB,
|
||||
Tf::Bc3RgbaUnorm => DXGI_FORMAT_BC3_UNORM,
|
||||
Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_UNORM_SRGB,
|
||||
Tf::Bc4RUnorm => DXGI_FORMAT_BC4_UNORM,
|
||||
Tf::Bc4RSnorm => DXGI_FORMAT_BC4_SNORM,
|
||||
Tf::Bc5RgUnorm => DXGI_FORMAT_BC5_UNORM,
|
||||
Tf::Bc5RgSnorm => DXGI_FORMAT_BC5_SNORM,
|
||||
Tf::Bc6hRgbUfloat => DXGI_FORMAT_BC6H_UF16,
|
||||
Tf::Bc6hRgbFloat => DXGI_FORMAT_BC6H_SF16,
|
||||
Tf::Bc7RgbaUnorm => DXGI_FORMAT_BC7_UNORM,
|
||||
Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_UNORM_SRGB,
|
||||
Tf::Etc2Rgb8Unorm
|
||||
| Tf::Etc2Rgb8UnormSrgb
|
||||
| Tf::Etc2Rgb8A1Unorm
|
||||
| Tf::Etc2Rgb8A1UnormSrgb
|
||||
| Tf::Etc2Rgba8Unorm
|
||||
| Tf::Etc2Rgba8UnormSrgb
|
||||
| Tf::EacR11Unorm
|
||||
| Tf::EacR11Snorm
|
||||
| Tf::EacRg11Unorm
|
||||
| Tf::EacRg11Snorm
|
||||
| Tf::Astc {
|
||||
block: _,
|
||||
channel: _,
|
||||
} => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn map_texture_format(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match map_texture_format_failable(format) {
|
||||
Some(f) => f,
|
||||
None => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Note: DXGI doesn't allow sRGB format on the swapchain,
|
||||
// but creating RTV of swapchain buffers with sRGB works.
|
||||
pub fn map_texture_format_nosrgb(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match format {
|
||||
wgt::TextureFormat::Bgra8UnormSrgb => Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
wgt::TextureFormat::Rgba8UnormSrgb => Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
_ => map_texture_format(format),
|
||||
}
|
||||
}
|
||||
|
||||
// SRV and UAV can't use the depth or typeless formats
|
||||
// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#view-creation
|
||||
pub fn map_texture_format_for_srv_uav(
|
||||
format: wgt::TextureFormat,
|
||||
aspect: crate::FormatAspects,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
Some(match (format, aspect) {
|
||||
(wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R16_UNORM
|
||||
}
|
||||
(wgt::TextureFormat::Depth32Float, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R32_FLOAT
|
||||
}
|
||||
(wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Depth24Plus | wgt::TextureFormat::Depth24PlusStencil8,
|
||||
crate::FormatAspects::DEPTH,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
|
||||
|
||||
(wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::STENCIL) => {
|
||||
Dxgi::Common::DXGI_FORMAT_X32_TYPELESS_G8X24_UINT
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Stencil8 | wgt::TextureFormat::Depth24PlusStencil8,
|
||||
crate::FormatAspects::STENCIL,
|
||||
) => Dxgi::Common::DXGI_FORMAT_X24_TYPELESS_G8_UINT,
|
||||
|
||||
(_, crate::FormatAspects::DEPTH)
|
||||
| (_, crate::FormatAspects::STENCIL)
|
||||
| (_, crate::FormatAspects::DEPTH_STENCIL) => return None,
|
||||
|
||||
_ => map_texture_format(format),
|
||||
})
|
||||
}
|
||||
|
||||
// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#planar-layout-for-staging-from-buffer
|
||||
pub fn map_texture_format_for_copy(
|
||||
format: wgt::TextureFormat,
|
||||
aspect: crate::FormatAspects,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
Some(match (format, aspect) {
|
||||
(wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R16_UNORM
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Depth32Float | wgt::TextureFormat::Depth32FloatStencil8,
|
||||
crate::FormatAspects::DEPTH,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R32_FLOAT,
|
||||
|
||||
(
|
||||
wgt::TextureFormat::Stencil8
|
||||
| wgt::TextureFormat::Depth24PlusStencil8
|
||||
| wgt::TextureFormat::Depth32FloatStencil8,
|
||||
crate::FormatAspects::STENCIL,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R8_UINT,
|
||||
|
||||
// `CopyTextureRegion` on a plane subresource wants the
|
||||
// single-plane DXGI format, not the planar one.
|
||||
(format, aspects) if format.is_multi_planar_format() && aspects.is_one() => {
|
||||
map_texture_format(format.aspect_specific_format(aspects.map())?)
|
||||
}
|
||||
|
||||
(format, crate::FormatAspects::COLOR) => map_texture_format(format),
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn map_texture_format_for_resource(
|
||||
format: wgt::TextureFormat,
|
||||
usage: wgt::TextureUses,
|
||||
has_view_formats: bool,
|
||||
casting_fully_typed_format_supported: bool,
|
||||
) -> Dxgi::Common::DXGI_FORMAT {
|
||||
use wgt::TextureFormat as Tf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
if casting_fully_typed_format_supported {
|
||||
map_texture_format(format)
|
||||
|
||||
// We might view this resource as srgb or non-srgb
|
||||
} else if has_view_formats {
|
||||
match format {
|
||||
Tf::Rgba8Unorm | Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_TYPELESS,
|
||||
Tf::Bgra8Unorm | Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_TYPELESS,
|
||||
Tf::Bc1RgbaUnorm | Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_TYPELESS,
|
||||
Tf::Bc2RgbaUnorm | Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_TYPELESS,
|
||||
Tf::Bc3RgbaUnorm | Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_TYPELESS,
|
||||
Tf::Bc7RgbaUnorm | Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_TYPELESS,
|
||||
format => map_texture_format(format),
|
||||
}
|
||||
|
||||
// We might view this resource as SRV/UAV but also as DSV
|
||||
} else if format.is_depth_stencil_format()
|
||||
&& usage.intersects(
|
||||
wgt::TextureUses::RESOURCE
|
||||
| wgt::TextureUses::STORAGE_READ_ONLY
|
||||
| wgt::TextureUses::STORAGE_WRITE_ONLY
|
||||
| wgt::TextureUses::STORAGE_READ_WRITE,
|
||||
)
|
||||
{
|
||||
match format {
|
||||
Tf::Depth16Unorm => DXGI_FORMAT_R16_TYPELESS,
|
||||
Tf::Depth32Float => DXGI_FORMAT_R32_TYPELESS,
|
||||
Tf::Depth32FloatStencil8 => DXGI_FORMAT_R32G8X24_TYPELESS,
|
||||
Tf::Stencil8 | Tf::Depth24Plus | Tf::Depth24PlusStencil8 => DXGI_FORMAT_R24G8_TYPELESS,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
map_texture_format(format)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_index_format(format: wgt::IndexFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match format {
|
||||
wgt::IndexFormat::Uint16 => Dxgi::Common::DXGI_FORMAT_R16_UINT,
|
||||
wgt::IndexFormat::Uint32 => Dxgi::Common::DXGI_FORMAT_R32_UINT,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_vertex_format(format: wgt::VertexFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
use wgt::VertexFormat as Vf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
match format {
|
||||
Vf::Unorm8 => DXGI_FORMAT_R8_UNORM,
|
||||
Vf::Snorm8 => DXGI_FORMAT_R8_SNORM,
|
||||
Vf::Uint8 => DXGI_FORMAT_R8_UINT,
|
||||
Vf::Sint8 => DXGI_FORMAT_R8_SINT,
|
||||
Vf::Unorm8x2 => DXGI_FORMAT_R8G8_UNORM,
|
||||
Vf::Snorm8x2 => DXGI_FORMAT_R8G8_SNORM,
|
||||
Vf::Uint8x2 => DXGI_FORMAT_R8G8_UINT,
|
||||
Vf::Sint8x2 => DXGI_FORMAT_R8G8_SINT,
|
||||
Vf::Unorm8x4 => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
Vf::Snorm8x4 => DXGI_FORMAT_R8G8B8A8_SNORM,
|
||||
Vf::Uint8x4 => DXGI_FORMAT_R8G8B8A8_UINT,
|
||||
Vf::Sint8x4 => DXGI_FORMAT_R8G8B8A8_SINT,
|
||||
Vf::Unorm16 => DXGI_FORMAT_R16_UNORM,
|
||||
Vf::Snorm16 => DXGI_FORMAT_R16_SNORM,
|
||||
Vf::Uint16 => DXGI_FORMAT_R16_UINT,
|
||||
Vf::Sint16 => DXGI_FORMAT_R16_SINT,
|
||||
Vf::Float16 => DXGI_FORMAT_R16_FLOAT,
|
||||
Vf::Unorm16x2 => DXGI_FORMAT_R16G16_UNORM,
|
||||
Vf::Snorm16x2 => DXGI_FORMAT_R16G16_SNORM,
|
||||
Vf::Uint16x2 => DXGI_FORMAT_R16G16_UINT,
|
||||
Vf::Sint16x2 => DXGI_FORMAT_R16G16_SINT,
|
||||
Vf::Float16x2 => DXGI_FORMAT_R16G16_FLOAT,
|
||||
Vf::Unorm16x4 => DXGI_FORMAT_R16G16B16A16_UNORM,
|
||||
Vf::Snorm16x4 => DXGI_FORMAT_R16G16B16A16_SNORM,
|
||||
Vf::Uint16x4 => DXGI_FORMAT_R16G16B16A16_UINT,
|
||||
Vf::Sint16x4 => DXGI_FORMAT_R16G16B16A16_SINT,
|
||||
Vf::Float16x4 => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
Vf::Uint32 => DXGI_FORMAT_R32_UINT,
|
||||
Vf::Sint32 => DXGI_FORMAT_R32_SINT,
|
||||
Vf::Float32 => DXGI_FORMAT_R32_FLOAT,
|
||||
Vf::Uint32x2 => DXGI_FORMAT_R32G32_UINT,
|
||||
Vf::Sint32x2 => DXGI_FORMAT_R32G32_SINT,
|
||||
Vf::Float32x2 => DXGI_FORMAT_R32G32_FLOAT,
|
||||
Vf::Uint32x3 => DXGI_FORMAT_R32G32B32_UINT,
|
||||
Vf::Sint32x3 => DXGI_FORMAT_R32G32B32_SINT,
|
||||
Vf::Float32x3 => DXGI_FORMAT_R32G32B32_FLOAT,
|
||||
Vf::Uint32x4 => DXGI_FORMAT_R32G32B32A32_UINT,
|
||||
Vf::Sint32x4 => DXGI_FORMAT_R32G32B32A32_SINT,
|
||||
Vf::Float32x4 => DXGI_FORMAT_R32G32B32A32_FLOAT,
|
||||
Vf::Unorm10_10_10_2 => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
Vf::Unorm8x4Bgra => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_acomposite_alpha_mode(mode: wgt::CompositeAlphaMode) -> Dxgi::Common::DXGI_ALPHA_MODE {
|
||||
match mode {
|
||||
wgt::CompositeAlphaMode::PreMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_PREMULTIPLIED,
|
||||
wgt::CompositeAlphaMode::PostMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_STRAIGHT,
|
||||
wgt::CompositeAlphaMode::Opaque => Dxgi::Common::DXGI_ALPHA_MODE_IGNORE,
|
||||
wgt::CompositeAlphaMode::Auto | wgt::CompositeAlphaMode::Inherit => {
|
||||
Dxgi::Common::DXGI_ALPHA_MODE_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
use alloc::{borrow::Cow, string::String};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use windows::Win32::{Foundation, System::Diagnostics::Debug};
|
||||
|
||||
// This is a mutex as opposed to an atomic as we need to completely
|
||||
// lock everyone out until we have registered or unregistered the
|
||||
// exception handler, otherwise really nasty races could happen.
|
||||
//
|
||||
// By routing all the registration through these functions we can guarantee
|
||||
// there is either 1 or 0 exception handlers registered, not multiple.
|
||||
static EXCEPTION_HANDLER_COUNT: Mutex<usize> = Mutex::new(0);
|
||||
|
||||
pub fn register_exception_handler() {
|
||||
let mut count_guard = EXCEPTION_HANDLER_COUNT.lock();
|
||||
if *count_guard == 0 {
|
||||
unsafe { Debug::AddVectoredExceptionHandler(0, Some(output_debug_string_handler)) };
|
||||
}
|
||||
*count_guard += 1;
|
||||
}
|
||||
|
||||
pub fn unregister_exception_handler() {
|
||||
let mut count_guard = EXCEPTION_HANDLER_COUNT.lock();
|
||||
if *count_guard == 1 {
|
||||
unsafe { Debug::RemoveVectoredExceptionHandler(output_debug_string_handler as *mut _) };
|
||||
}
|
||||
*count_guard -= 1;
|
||||
}
|
||||
|
||||
const MESSAGE_PREFIXES: &[(&str, log::Level)] = &[
|
||||
("CORRUPTION", log::Level::Error),
|
||||
("ERROR", log::Level::Error),
|
||||
("WARNING", log::Level::Warn),
|
||||
// We intentionally suppress "INFO" messages down to debug
|
||||
// so that users are not innundated with info messages from the runtime.
|
||||
("INFO", log::Level::Debug),
|
||||
("MESSAGE", log::Level::Trace),
|
||||
];
|
||||
|
||||
unsafe extern "system" fn output_debug_string_handler(
|
||||
exception_info: *mut Debug::EXCEPTION_POINTERS,
|
||||
) -> i32 {
|
||||
// See https://stackoverflow.com/a/41480827
|
||||
let record = unsafe { &*(*exception_info).ExceptionRecord };
|
||||
if record.NumberParameters != 2 {
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
let message = match record.ExceptionCode {
|
||||
Foundation::DBG_PRINTEXCEPTION_C => {
|
||||
String::from_utf8_lossy(bytemuck::cast_slice(&record.ExceptionInformation))
|
||||
}
|
||||
Foundation::DBG_PRINTEXCEPTION_WIDE_C => Cow::Owned(String::from_utf16_lossy(
|
||||
bytemuck::cast_slice(&record.ExceptionInformation),
|
||||
)),
|
||||
_ => return Debug::EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
|
||||
let message = match message.strip_prefix("D3D12 ") {
|
||||
Some(msg) => msg
|
||||
.trim_end_matches("\n\0")
|
||||
.trim_end_matches("[ STATE_CREATION WARNING #0: UNKNOWN]"),
|
||||
None => return Debug::EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
|
||||
let (message, level) = match MESSAGE_PREFIXES
|
||||
.iter()
|
||||
.find(|&&(prefix, _)| message.starts_with(prefix))
|
||||
{
|
||||
Some(&(prefix, level)) => (&message[prefix.len() + 2..], level),
|
||||
None => (message, log::Level::Debug),
|
||||
};
|
||||
|
||||
if level == log::Level::Warn && message.contains("#82") {
|
||||
// This is are useless spammy warnings (#820, #821):
|
||||
// "The application did not pass any clear value to resource creation"
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
if level == log::Level::Warn && message.contains("DRAW_EMPTY_SCISSOR_RECTANGLE") {
|
||||
// This is normal, WebGPU allows passing empty scissor rectangles.
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
let _ = std::panic::catch_unwind(|| {
|
||||
log::log!(level, "{message}");
|
||||
});
|
||||
|
||||
#[cfg(feature = "validation_canary")]
|
||||
if cfg!(debug_assertions) && level == log::Level::Error {
|
||||
use alloc::string::ToString as _;
|
||||
|
||||
// Set canary and continue
|
||||
crate::VALIDATION_CANARY.add(message.to_string());
|
||||
}
|
||||
|
||||
Debug::EXCEPTION_CONTINUE_EXECUTION
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use core::ops::Deref;
|
||||
|
||||
use windows::{core::Interface as _, Win32::Graphics::Dxgi};
|
||||
|
||||
use crate::dx12::DxgiLib;
|
||||
|
||||
use super::result::HResult as _;
|
||||
|
||||
// We can rely on the presence of DXGI 1.4 since D3D12 requires WDDM 2.0, Windows 10 (1507), and so does DXGI 1.4.
|
||||
|
||||
fn should_keep_adapter(adapter: &Dxgi::IDXGIAdapter1) -> bool {
|
||||
let desc = unsafe { adapter.GetDesc1() }.unwrap();
|
||||
|
||||
// The Intel Haswell family of iGPUs had support for the D3D12 API but it was later
|
||||
// removed due to a security vulnerability.
|
||||
//
|
||||
// We are explicitly filtering out all the devices in the family because we are now
|
||||
// getting reports of device loss at a later time than at device creation time (`D3D12CreateDevice`).
|
||||
//
|
||||
// See https://www.intel.com/content/www/us/en/support/articles/000057520/graphics.html
|
||||
// This list of device IDs is from https://dgpu-docs.intel.com/devices/hardware-table.html
|
||||
let haswell_device_ids = [
|
||||
0x0422, 0x0426, 0x042A, 0x042B, 0x042E, 0x0C22, 0x0C26, 0x0C2A, 0x0C2B, 0x0C2E, 0x0A22,
|
||||
0x0A2A, 0x0A2B, 0x0D2A, 0x0D2B, 0x0D2E, 0x0A26, 0x0A2E, 0x0D22, 0x0D26, 0x0412, 0x0416,
|
||||
0x0D12, 0x041A, 0x041B, 0x0C12, 0x0C16, 0x0C1A, 0x0C1B, 0x0C1E, 0x0A12, 0x0A1A, 0x0A1B,
|
||||
0x0D16, 0x0D1A, 0x0D1B, 0x0D1E, 0x041E, 0x0A16, 0x0A1E, 0x0402, 0x0406, 0x040A, 0x040B,
|
||||
0x040E, 0x0C02, 0x0C06, 0x0C0A, 0x0C0B, 0x0C0E, 0x0A02, 0x0A06, 0x0A0A, 0x0A0B, 0x0A0E,
|
||||
0x0D02, 0x0D06, 0x0D0A, 0x0D0B, 0x0D0E,
|
||||
];
|
||||
if desc.VendorId == 0x8086 && haswell_device_ids.contains(&desc.DeviceId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If run completely headless, windows will show two different WARP adapters, one
|
||||
// which is lying about being an integrated card. This is so that programs
|
||||
// that ignore software adapters will actually run on headless/gpu-less machines.
|
||||
//
|
||||
// We don't want that and discourage that kind of filtering anyway, so we skip the integrated WARP.
|
||||
if desc.VendorId == 5140
|
||||
&& !Dxgi::DXGI_ADAPTER_FLAG(desc.Flags as i32).contains(Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE)
|
||||
{
|
||||
let adapter_name = super::conv::map_adapter_name(desc.Description);
|
||||
if adapter_name.contains("Microsoft Basic Render Driver") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DxgiAdapter {
|
||||
/// Provided by DXGI 1.4
|
||||
Adapter3(Dxgi::IDXGIAdapter3),
|
||||
/// Provided by DXGI 1.6
|
||||
Adapter4(Dxgi::IDXGIAdapter4),
|
||||
}
|
||||
|
||||
impl DxgiAdapter {
|
||||
pub fn query_video_memory_info(
|
||||
&self,
|
||||
group: Dxgi::DXGI_MEMORY_SEGMENT_GROUP,
|
||||
) -> Result<Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO, crate::DeviceError> {
|
||||
let mut info = Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO::default();
|
||||
unsafe { self.QueryVideoMemoryInfo(0, group, &mut info) }
|
||||
.into_device_result("QueryVideoMemoryInfo")?;
|
||||
Ok(info)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for DxgiAdapter {
|
||||
type Target = Dxgi::IDXGIAdapter3;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
DxgiAdapter::Adapter3(a) => a,
|
||||
DxgiAdapter::Adapter4(a) => a,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enumerate_adapters(factory: DxgiFactory) -> Vec<DxgiAdapter> {
|
||||
let mut adapters = Vec::with_capacity(8);
|
||||
|
||||
for cur_index in 0.. {
|
||||
profiling::scope!("IDXGIFactory1::EnumAdapters1");
|
||||
let adapter1: Dxgi::IDXGIAdapter1 = match unsafe { factory.EnumAdapters1(cur_index) } {
|
||||
Ok(a) => a,
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::error!("Failed enumerating adapters: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if !should_keep_adapter(&adapter1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(adapter4) = adapter1.cast::<Dxgi::IDXGIAdapter4>() {
|
||||
adapters.push(DxgiAdapter::Adapter4(adapter4));
|
||||
} else {
|
||||
let adapter3 = adapter1.cast::<Dxgi::IDXGIAdapter3>().unwrap();
|
||||
adapters.push(DxgiAdapter::Adapter3(adapter3));
|
||||
}
|
||||
}
|
||||
|
||||
adapters
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DxgiFactory {
|
||||
/// Provided by DXGI 1.4
|
||||
Factory4(Dxgi::IDXGIFactory4),
|
||||
/// Provided by DXGI 1.5
|
||||
Factory5(Dxgi::IDXGIFactory5),
|
||||
/// Provided by DXGI 1.6
|
||||
Factory6(Dxgi::IDXGIFactory6),
|
||||
}
|
||||
|
||||
impl Deref for DxgiFactory {
|
||||
type Target = Dxgi::IDXGIFactory4;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
DxgiFactory::Factory4(f) => f,
|
||||
DxgiFactory::Factory5(f) => f,
|
||||
DxgiFactory::Factory6(f) => f,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DxgiFactory {
|
||||
pub fn as_factory5(&self) -> Option<&Dxgi::IDXGIFactory5> {
|
||||
match self {
|
||||
Self::Factory4(_) => None,
|
||||
Self::Factory5(f) => Some(f),
|
||||
Self::Factory6(f) => Some(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_factory(
|
||||
instance_flags: wgt::InstanceFlags,
|
||||
) -> Result<(DxgiLib, DxgiFactory), crate::InstanceError> {
|
||||
let lib_dxgi = DxgiLib::new().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("failed to load dxgi.dll"), e)
|
||||
})?;
|
||||
|
||||
let mut factory_flags = Dxgi::DXGI_CREATE_FACTORY_FLAGS::default();
|
||||
|
||||
if instance_flags.contains(wgt::InstanceFlags::VALIDATION) {
|
||||
// The `DXGI_CREATE_FACTORY_DEBUG` flag is only allowed to be passed to
|
||||
// `CreateDXGIFactory2` if the debug interface is actually available. So
|
||||
// we check for whether it exists first.
|
||||
if let Ok(Some(_)) = lib_dxgi.debug_interface1() {
|
||||
factory_flags |= Dxgi::DXGI_CREATE_FACTORY_DEBUG;
|
||||
}
|
||||
}
|
||||
|
||||
let factory4 = match lib_dxgi.create_factory4(factory_flags) {
|
||||
Ok(factory) => factory,
|
||||
Err(err) => {
|
||||
return Err(crate::InstanceError::with_source(
|
||||
String::from("IDXGIFactory4 creation failed"),
|
||||
err,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Ok(factory6) = factory4.cast::<Dxgi::IDXGIFactory6>() {
|
||||
return Ok((lib_dxgi, DxgiFactory::Factory6(factory6)));
|
||||
}
|
||||
|
||||
if let Ok(factory5) = factory4.cast::<Dxgi::IDXGIFactory5>() {
|
||||
return Ok((lib_dxgi, DxgiFactory::Factory5(factory5)));
|
||||
}
|
||||
|
||||
Ok((lib_dxgi, DxgiFactory::Factory4(factory4)))
|
||||
}
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
//! Reading a window's [`wgt::DisplayHdrInfo`] through DXGI.
|
||||
//!
|
||||
//! Lives in `auxil/dxgi` so the DX12 and Vulkan-on-Windows backends share it:
|
||||
//! both query through a [`DxgiHdrSource`], so the same monitor reports identical
|
||||
//! numbers under either backend.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use windows::{
|
||||
core::Interface as _,
|
||||
Win32::{
|
||||
Foundation::HWND,
|
||||
Graphics::{Dxgi, Gdi},
|
||||
},
|
||||
};
|
||||
|
||||
/// The primary colors of a color space, in CIE 1931 xy:
|
||||
/// `[[red_x, red_y], [green_x, green_y], [blue_x, blue_y]]`.
|
||||
type Primaries = [[f32; 2]; 3];
|
||||
|
||||
/// Reference primaries (CIE 1931 xy: red, green, blue) for the three coarse
|
||||
/// gamut buckets, used to classify a display's reported primaries.
|
||||
const REC709: Primaries = [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]];
|
||||
const DISPLAY_P3: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]];
|
||||
const REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]];
|
||||
|
||||
/// Classifies reported primaries into the closest coarse [`wgt::DisplayGamut`]
|
||||
/// bucket (least-squares over the R/G/B chromaticities). Advisory only.
|
||||
///
|
||||
/// Returns `None` if every primary is zeroed (the EDID reported nothing usable),
|
||||
/// so a bogus all-zero descriptor is not misclassified as sRGB.
|
||||
fn classify_gamut(red: [f32; 2], green: [f32; 2], blue: [f32; 2]) -> Option<wgt::DisplayGamut> {
|
||||
let measured = [red, green, blue];
|
||||
if measured.iter().all(|p| p[0] == 0.0 && p[1] == 0.0) {
|
||||
return None;
|
||||
}
|
||||
let dist = |reference: &Primaries| -> f32 {
|
||||
measured
|
||||
.iter()
|
||||
.zip(reference)
|
||||
.map(|(m, r)| {
|
||||
let dx = m[0] - r[0];
|
||||
let dy = m[1] - r[1];
|
||||
dx * dx + dy * dy
|
||||
})
|
||||
.sum()
|
||||
};
|
||||
[
|
||||
(wgt::DisplayGamut::Srgb, dist(&REC709)),
|
||||
(wgt::DisplayGamut::DisplayP3, dist(&DISPLAY_P3)),
|
||||
(wgt::DisplayGamut::Rec2020, dist(&REC2020)),
|
||||
]
|
||||
.into_iter()
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(gamut, _)| gamut)
|
||||
}
|
||||
|
||||
/// Maps an [`IDXGIOutput6::GetDesc1`] result and the SDR white level (from
|
||||
/// [`sdr_white_nits_for_monitor`]) into the backend-agnostic
|
||||
/// [`wgt::DisplayHdrInfo`].
|
||||
///
|
||||
/// Pure: it interprets `desc1` without any system call. Numeric values are
|
||||
/// advisory (EDID-sourced); see [`wgt::DisplayLuminance`].
|
||||
///
|
||||
/// [`IDXGIOutput6::GetDesc1`]: windows::Win32::Graphics::Dxgi::IDXGIOutput6::GetDesc1
|
||||
fn display_hdr_info_from_desc1(
|
||||
desc1: &Dxgi::DXGI_OUTPUT_DESC1,
|
||||
sdr_white_nits: Option<f32>,
|
||||
) -> wgt::DisplayHdrInfo {
|
||||
// The output is in an HDR color space if its `ColorSpace` is one of the two
|
||||
// Windows uses for HDR swap-chains: HDR10 / PQ (`G2084_NONE_P2020`) or
|
||||
// scRGB / linear-extended-sRGB (`G10_NONE_P709`). Checking both ensures scRGB
|
||||
// HDR is not misreported as SDR.
|
||||
let high_dynamic_range = desc1.ColorSpace
|
||||
== Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020
|
||||
|| desc1.ColorSpace == Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
|
||||
|
||||
let luminance = wgt::DisplayLuminance {
|
||||
max_nits: Some(desc1.MaxLuminance),
|
||||
max_full_frame_nits: Some(desc1.MaxFullFrameLuminance),
|
||||
min_nits: Some(desc1.MinLuminance),
|
||||
sdr_white_nits,
|
||||
};
|
||||
|
||||
let chromaticity = wgt::DisplayChromaticity {
|
||||
red: Some(desc1.RedPrimary),
|
||||
green: Some(desc1.GreenPrimary),
|
||||
blue: Some(desc1.BluePrimary),
|
||||
white: Some(desc1.WhitePoint),
|
||||
};
|
||||
|
||||
let coarse = wgt::DisplayCoarseRange {
|
||||
high_dynamic_range: Some(high_dynamic_range),
|
||||
gamut: classify_gamut(desc1.RedPrimary, desc1.GreenPrimary, desc1.BluePrimary),
|
||||
};
|
||||
|
||||
// `headroom` is `None`: DXGI exposes absolute luminance (captured in
|
||||
// `luminance`) rather than a relative headroom ratio. `bits_per_color` drops
|
||||
// values that don't fit `u8`.
|
||||
wgt::DisplayHdrInfo {
|
||||
luminance: Some(luminance),
|
||||
headroom: None,
|
||||
chromaticity: Some(chromaticity),
|
||||
coarse: Some(coarse),
|
||||
bits_per_color: u8::try_from(desc1.BitsPerColor).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A window's display HDR info, read through DXGI.
|
||||
///
|
||||
/// Bundles the window's `HWND` with the DXGI factory used to query it. The factory
|
||||
/// is built once and reused, rebuilt only when DXGI reports it stale; the monitor
|
||||
/// lookup and adapter/output walk still run every call, since the window can move
|
||||
/// between displays and the SDR white level changes at runtime.
|
||||
pub struct DxgiHdrSource {
|
||||
hwnd: HWND,
|
||||
factory: Mutex<Option<Dxgi::IDXGIFactory1>>,
|
||||
}
|
||||
|
||||
// SAFETY: `HWND` and `IDXGIFactory1` are `!Send`/`!Sync` in windows-rs. The `HWND`
|
||||
// is only ever read to run a DXGI query (fine from any thread), and the factory is
|
||||
// free-threaded for the enumeration done here with the `Mutex` serializing access.
|
||||
// This mirrors the manual `Send`/`Sync` on `dx12::Surface`.
|
||||
unsafe impl Send for DxgiHdrSource {}
|
||||
unsafe impl Sync for DxgiHdrSource {}
|
||||
|
||||
impl DxgiHdrSource {
|
||||
/// Creates a source for the window identified by `hwnd`. The `HWND` is
|
||||
/// borrowed; using the source after that window is destroyed is undefined
|
||||
/// behavior.
|
||||
pub fn new(hwnd: HWND) -> Self {
|
||||
Self {
|
||||
hwnd,
|
||||
factory: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the window's [`wgt::DisplayHdrInfo`], or `None` if its monitor can't
|
||||
/// be identified or queried (a headless or composition window, a
|
||||
/// pre-Win10-1703 system without `IDXGIOutput6`, or a COM failure). Never
|
||||
/// panics.
|
||||
pub fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> {
|
||||
let desc1 = self.output_desc1()?;
|
||||
let sdr_white_nits = sdr_white_nits_for_monitor(desc1.Monitor);
|
||||
Some(display_hdr_info_from_desc1(&desc1, sdr_white_nits))
|
||||
}
|
||||
|
||||
/// The [`DXGI_OUTPUT_DESC1`] for the window's monitor, reusing the cached
|
||||
/// factory unless DXGI reports it stale.
|
||||
///
|
||||
/// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1
|
||||
fn output_desc1(&self) -> Option<Dxgi::DXGI_OUTPUT_DESC1> {
|
||||
let mut factory = self.factory.lock();
|
||||
|
||||
// A factory only enumerates the adapter/output topology it saw at
|
||||
// creation, so rebuild it once it reports `IsCurrent() == false` (a
|
||||
// monitor or GPU was plugged or unplugged).
|
||||
// SAFETY: a cached factory is live; `IsCurrent` takes no caller pointers.
|
||||
let need_new = factory
|
||||
.as_ref()
|
||||
.is_none_or(|f| !unsafe { f.IsCurrent() }.as_bool());
|
||||
if need_new {
|
||||
// SAFETY: `CreateDXGIFactory1` takes no caller pointers; the `windows`
|
||||
// binding fills the interface out-pointer itself.
|
||||
match unsafe { Dxgi::CreateDXGIFactory1() } {
|
||||
Ok(new) => *factory = Some(new),
|
||||
Err(e) => {
|
||||
log::warn!("CreateDXGIFactory1 failed: {e}");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
output_desc1_from_factory(factory.as_ref()?, self.hwnd)
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`DXGI_OUTPUT_DESC1`] for the monitor backing `wnd_handle`, found by
|
||||
/// walking every adapter's outputs on `factory` — not just the rendering
|
||||
/// adapter's, so the monitor is found on hybrid-GPU systems where the window sits
|
||||
/// on a display wired to a different adapter. `None` if none match.
|
||||
///
|
||||
/// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1
|
||||
fn output_desc1_from_factory(
|
||||
factory: &Dxgi::IDXGIFactory1,
|
||||
wnd_handle: HWND,
|
||||
) -> Option<Dxgi::DXGI_OUTPUT_DESC1> {
|
||||
// SAFETY: `MonitorFromWindow` is sound for any `HWND`; an invalid one yields
|
||||
// a null `HMONITOR`, checked below.
|
||||
let hmonitor = unsafe { Gdi::MonitorFromWindow(wnd_handle, Gdi::MONITOR_DEFAULTTONEAREST) };
|
||||
if hmonitor.is_invalid() {
|
||||
log::warn!("MonitorFromWindow failed; cannot identify the window's output");
|
||||
return None;
|
||||
}
|
||||
for adapter_index in 0.. {
|
||||
// SAFETY: `factory` is live; `EnumAdapters1` takes only an index.
|
||||
let adapter = match unsafe { factory.EnumAdapters1(adapter_index) } {
|
||||
Ok(adapter) => adapter,
|
||||
// End of the adapter list: the monitor matched none of them.
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIFactory1::EnumAdapters1 failed: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
for output_index in 0.. {
|
||||
// SAFETY: `adapter` is live (from above); `EnumOutputs` takes only
|
||||
// an index.
|
||||
let output = match unsafe { adapter.EnumOutputs(output_index) } {
|
||||
Ok(output) => output,
|
||||
// End of this adapter's outputs: move on to the next adapter.
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIAdapter1::EnumOutputs failed: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
// SAFETY: `output` is live (from above); `GetDesc` returns a
|
||||
// binding-owned `DXGI_OUTPUT_DESC` by value.
|
||||
let desc = match unsafe { output.GetDesc() } {
|
||||
Ok(desc) => desc,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIOutput::GetDesc failed: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if desc.Monitor != hmonitor {
|
||||
continue;
|
||||
}
|
||||
// The window's monitor matched, so a failure past this point is a
|
||||
// real anomaly. `IDXGIOutput6` (DXGI 1.6 / Win10 1703+) is required
|
||||
// for `GetDesc1`.
|
||||
let output6 = match output.cast::<Dxgi::IDXGIOutput6>() {
|
||||
Ok(output6) => output6,
|
||||
Err(e) => {
|
||||
log::warn!("Casting to IDXGIOutput6 failed: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// SAFETY: `output6` is live (from the cast above); `GetDesc1`
|
||||
// returns a binding-owned `DXGI_OUTPUT_DESC1` by value.
|
||||
return match unsafe { output6.GetDesc1() } {
|
||||
Ok(desc1) => Some(desc1),
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIOutput6::GetDesc1 failed: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
log::warn!("No DXGI output matches the window's monitor");
|
||||
None
|
||||
}
|
||||
|
||||
/// Best-effort SDR white level in nits for `hmonitor`, via the Windows
|
||||
/// DisplayConfig API. Tracks the brightness slider, so it changes at runtime.
|
||||
///
|
||||
/// This is the only [`wgt::DisplayLuminance`] field `GetDesc1` doesn't carry; it
|
||||
/// bridges absolute nits and relative headroom. It lives in
|
||||
/// `DISPLAYCONFIG_SDR_WHITE_LEVEL`, outside DXGI, so it needs its own query.
|
||||
///
|
||||
/// Returns `None` on any failure (no match, query error, or a `0` reading). Never
|
||||
/// panics. Pass [`Dxgi::DXGI_OUTPUT_DESC1::Monitor`] so the value matches the rest
|
||||
/// of the `DisplayHdrInfo`.
|
||||
fn sdr_white_nits_for_monitor(hmonitor: Gdi::HMONITOR) -> Option<f32> {
|
||||
use windows::Win32::{
|
||||
Devices::Display::{
|
||||
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QueryDisplayConfig,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_MODE_INFO,
|
||||
DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SDR_WHITE_LEVEL,
|
||||
DISPLAYCONFIG_SOURCE_DEVICE_NAME, QDC_ONLY_ACTIVE_PATHS,
|
||||
},
|
||||
Foundation::ERROR_SUCCESS,
|
||||
Graphics::Gdi::{GetMonitorInfoW, MONITORINFO, MONITORINFOEXW},
|
||||
};
|
||||
|
||||
// 1. HMONITOR -> GDI device name (e.g. `\\.\DISPLAY1`).
|
||||
let mut monitor_info = MONITORINFOEXW::default();
|
||||
monitor_info.monitorInfo.cbSize = size_of::<MONITORINFOEXW>() as u32;
|
||||
// `GetMonitorInfoW` takes a `*mut MONITORINFO`; the `EXW` variant is
|
||||
// layout-compatible (it starts with `MONITORINFO`) and reports `cbSize`.
|
||||
let lpmi = core::ptr::from_mut(&mut monitor_info).cast::<MONITORINFO>();
|
||||
// SAFETY: `lpmi` points at a live `MONITORINFOEXW` with `cbSize` set, which
|
||||
// bounds the write; an invalid `hmonitor` just fails (handled below).
|
||||
let got_info = unsafe { GetMonitorInfoW(hmonitor, lpmi) };
|
||||
if !got_info.as_bool() {
|
||||
return None;
|
||||
}
|
||||
let gdi_device_name = monitor_info.szDevice;
|
||||
|
||||
// 2. Enumerate the active DisplayConfig paths.
|
||||
let mut path_count = 0u32;
|
||||
let mut mode_count = 0u32;
|
||||
// SAFETY: both out-params are live `u32`s; the call only writes the required
|
||||
// buffer sizes into them.
|
||||
if unsafe {
|
||||
GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut path_count, &mut mode_count)
|
||||
} != ERROR_SUCCESS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut paths = alloc::vec![DISPLAYCONFIG_PATH_INFO::default(); path_count as usize];
|
||||
let mut modes = alloc::vec![DISPLAYCONFIG_MODE_INFO::default(); mode_count as usize];
|
||||
// SAFETY: `paths`/`modes` are sized to the counts reported above and passed
|
||||
// with those counts, bounding the writes.
|
||||
if unsafe {
|
||||
QueryDisplayConfig(
|
||||
QDC_ONLY_ACTIVE_PATHS,
|
||||
&mut path_count,
|
||||
paths.as_mut_ptr(),
|
||||
&mut mode_count,
|
||||
modes.as_mut_ptr(),
|
||||
None,
|
||||
)
|
||||
} != ERROR_SUCCESS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
// 3. Match the path whose source is this monitor, then read its target's
|
||||
// SDR white level. `DisplayConfigGetDeviceInfo` returns a WIN32 code as
|
||||
// `i32` (`0` == `ERROR_SUCCESS`).
|
||||
for path in paths.iter().take(path_count as usize) {
|
||||
let mut source = DISPLAYCONFIG_SOURCE_DEVICE_NAME::default();
|
||||
source.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
|
||||
source.header.size = size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32;
|
||||
source.header.adapterId = path.sourceInfo.adapterId;
|
||||
source.header.id = path.sourceInfo.id;
|
||||
// SAFETY: `source` is live with `header.type`/`header.size` set, which
|
||||
// bounds the call's access to that struct.
|
||||
if unsafe { DisplayConfigGetDeviceInfo(&mut source.header) } != ERROR_SUCCESS.0 as i32 {
|
||||
continue;
|
||||
}
|
||||
if source.viewGdiDeviceName != gdi_device_name {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut white = DISPLAYCONFIG_SDR_WHITE_LEVEL::default();
|
||||
white.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
|
||||
white.header.size = size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as u32;
|
||||
white.header.adapterId = path.targetInfo.adapterId;
|
||||
white.header.id = path.targetInfo.id;
|
||||
// SAFETY: `white` is live with `header.type`/`header.size` set, which
|
||||
// bounds the call's access to that struct.
|
||||
if unsafe { DisplayConfigGetDeviceInfo(&mut white.header) } != ERROR_SUCCESS.0 as i32 {
|
||||
return None;
|
||||
}
|
||||
// `SDRWhiteLevel` encodes nits as `(nits / 80) * 1000`; `0` means the OS
|
||||
// reported nothing usable.
|
||||
return (white.SDRWhiteLevel > 0).then(|| white.SDRWhiteLevel as f32 * 80.0 / 1000.0);
|
||||
}
|
||||
None
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// Every module here is gated behind `dx12` except `hdr` (the
|
||||
// `DXGI_OUTPUT_DESC1` -> `DisplayHdrInfo` mapping), which the
|
||||
// Vulkan-on-Windows backend also uses.
|
||||
#[cfg(dx12)]
|
||||
pub mod conv;
|
||||
#[cfg(dx12)]
|
||||
pub mod exception;
|
||||
#[cfg(dx12)]
|
||||
pub mod factory;
|
||||
pub mod hdr;
|
||||
#[cfg(dx12)]
|
||||
pub mod name;
|
||||
#[cfg(dx12)]
|
||||
pub mod result;
|
||||
#[cfg(dx12)]
|
||||
pub mod time;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
use windows::Win32::Graphics::Direct3D12::ID3D12Object;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult;
|
||||
|
||||
/// Helper trait for setting the name of a D3D12 object.
|
||||
///
|
||||
/// This is implemented on all types that can be converted to an [`ID3D12Object`].
|
||||
pub trait ObjectExt {
|
||||
fn set_name(&self, name: &str) -> Result<(), crate::DeviceError>;
|
||||
}
|
||||
|
||||
impl<T> ObjectExt for T
|
||||
where
|
||||
// Windows impls `From` for all parent interfaces, so we can use that to convert to ID3D12Object.
|
||||
//
|
||||
// This includes implementations for references.
|
||||
for<'a> &'a ID3D12Object: From<&'a T>,
|
||||
{
|
||||
fn set_name(&self, name: &str) -> Result<(), crate::DeviceError> {
|
||||
let name = windows::core::HSTRING::from(name);
|
||||
let object: &ID3D12Object = self.into();
|
||||
unsafe { object.SetName(&name).into_device_result("SetName") }
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
use windows::Win32::{Foundation, Graphics::Dxgi};
|
||||
|
||||
pub(crate) trait HResult<O> {
|
||||
fn into_device_result(self, description: &str) -> Result<O, crate::DeviceError>;
|
||||
}
|
||||
impl<T> HResult<T> for windows::core::Result<T> {
|
||||
fn into_device_result(self, description: &str) -> Result<T, crate::DeviceError> {
|
||||
#![allow(unreachable_code)]
|
||||
|
||||
self.map_err(|err| {
|
||||
log::error!("{description} failed: {err}");
|
||||
|
||||
match err.code() {
|
||||
Foundation::E_OUTOFMEMORY => crate::DeviceError::OutOfMemory,
|
||||
Dxgi::DXGI_ERROR_DEVICE_RESET | Dxgi::DXGI_ERROR_DEVICE_REMOVED => {
|
||||
#[cfg(feature = "device_lost_panic")]
|
||||
panic!("{description} failed: Device lost ({err})");
|
||||
crate::DeviceError::Lost
|
||||
}
|
||||
_ => {
|
||||
#[cfg(feature = "internal_error_panic")]
|
||||
panic!("{description} failed: {err}");
|
||||
crate::DeviceError::Unexpected
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#![allow(dead_code, reason = "IPresentationManager is unused currently")]
|
||||
|
||||
use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency};
|
||||
|
||||
pub enum PresentationTimer {
|
||||
/// DXGI uses [`QueryPerformanceCounter()`]
|
||||
Dxgi {
|
||||
/// How many ticks of QPC per second
|
||||
frequency: u64,
|
||||
},
|
||||
/// [`IPresentationManager`] uses [`QueryInterruptTimePrecise()`]
|
||||
///
|
||||
/// [`IPresentationManager`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Graphics/CompositionSwapchain/struct.IPresentationManager.html
|
||||
/// [`QueryInterruptTimePrecise()`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/WindowsProgramming/fn.QueryInterruptTimePrecise.html
|
||||
#[allow(non_snake_case)]
|
||||
IPresentationManager {
|
||||
fnQueryInterruptTimePrecise: unsafe extern "system" fn(*mut u64),
|
||||
},
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for PresentationTimer {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match *self {
|
||||
Self::Dxgi { frequency } => f
|
||||
.debug_struct("DXGI")
|
||||
.field("frequency", &frequency)
|
||||
.finish(),
|
||||
Self::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise,
|
||||
} => f
|
||||
.debug_struct("IPresentationManager")
|
||||
.field(
|
||||
"QueryInterruptTimePrecise",
|
||||
&(fnQueryInterruptTimePrecise as usize),
|
||||
)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PresentationTimer {
|
||||
/// Create a presentation timer using QueryPerformanceFrequency (what DXGI uses for presentation times)
|
||||
pub fn new_dxgi() -> Self {
|
||||
let mut frequency = 0;
|
||||
unsafe { QueryPerformanceFrequency(&mut frequency) }.unwrap();
|
||||
|
||||
Self::Dxgi {
|
||||
frequency: frequency
|
||||
.try_into()
|
||||
.expect("Frequency should not be negative"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a presentation timer using QueryInterruptTimePrecise (what IPresentationManager uses for presentation times)
|
||||
///
|
||||
/// Panics if QueryInterruptTimePrecise isn't found (below Win10)
|
||||
pub fn new_ipresentation_manager() -> Self {
|
||||
// We need to load this explicitly, as QueryInterruptTimePrecise is only available on Windows 10+
|
||||
//
|
||||
// Docs say it's in kernel32.dll, but it's actually in kernelbase.dll.
|
||||
// api-ms-win-core-realtime-l1-1-1.dll
|
||||
let kernelbase =
|
||||
libloading::os::windows::Library::open_already_loaded("kernelbase.dll").unwrap();
|
||||
// No concerns about lifetimes here as kernelbase is always there.
|
||||
let ptr = unsafe {
|
||||
kernelbase
|
||||
.get(c"QueryInterruptTimePrecise".to_bytes())
|
||||
.unwrap()
|
||||
};
|
||||
Self::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise: *ptr,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the current time in nanoseconds.
|
||||
pub fn get_timestamp_ns(&self) -> u128 {
|
||||
// Always do u128 math _after_ hitting the timing function.
|
||||
match *self {
|
||||
PresentationTimer::Dxgi { frequency } => {
|
||||
let mut counter = 0;
|
||||
unsafe { QueryPerformanceCounter(&mut counter) }.unwrap();
|
||||
|
||||
// counter * (1_000_000_000 / freq) but re-ordered to make more precise
|
||||
(counter as u128 * 1_000_000_000) / frequency as u128
|
||||
}
|
||||
PresentationTimer::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise,
|
||||
} => {
|
||||
let mut counter = 0;
|
||||
unsafe { fnQueryInterruptTimePrecise(&mut counter) };
|
||||
|
||||
// QueryInterruptTimePrecise uses units of 100ns for its tick.
|
||||
counter as u128 * 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+241
@@ -0,0 +1,241 @@
|
||||
// Mostly DX12-only, but also compiled for Vulkan-on-Windows, which reuses
|
||||
// `dxgi::hdr` to query display HDR info. The DX12-only submodules stay gated
|
||||
// behind `dx12` in `dxgi/mod.rs`.
|
||||
#[cfg(any(dx12, all(vulkan, windows)))]
|
||||
pub(super) mod dxgi;
|
||||
|
||||
#[cfg(all(native, feature = "renderdoc"))]
|
||||
pub(super) mod renderdoc;
|
||||
|
||||
pub mod db {
|
||||
pub mod amd {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x1002;
|
||||
}
|
||||
pub mod apple {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x106B;
|
||||
}
|
||||
pub mod arm {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x13B5;
|
||||
}
|
||||
pub mod broadcom {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x14E4;
|
||||
}
|
||||
pub mod imgtec {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x1010;
|
||||
}
|
||||
pub mod intel {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x8086;
|
||||
pub const DEVICE_KABY_LAKE_MASK: u32 = 0x5900;
|
||||
pub const DEVICE_SKY_LAKE_MASK: u32 = 0x1900;
|
||||
}
|
||||
pub mod mesa {
|
||||
// Mesa does not actually have a PCI vendor id.
|
||||
//
|
||||
// To match Vulkan, we use the VkVendorId for Mesa in the gles backend so that lavapipe (Vulkan) and
|
||||
// llvmpipe (OpenGL) have the same vendor id.
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x10005;
|
||||
}
|
||||
pub mod nvidia {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x10DE;
|
||||
}
|
||||
pub mod qualcomm {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x5143;
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum binding size for the shaders that only support `i32` indexing.
|
||||
/// Interestingly, the index itself can't reach that high, because the minimum
|
||||
/// element size is 4 bytes, but the compiler toolchain still computes the
|
||||
/// offset at some intermediate point, internally, as i32.
|
||||
pub const MAX_I32_BINDING_SIZE: u32 = (1 << 31) - 1;
|
||||
|
||||
pub use wgpu_naga_bridge::map_naga_stage;
|
||||
|
||||
impl crate::CopyExtent {
|
||||
pub fn map_extent_to_copy_size(extent: &wgt::Extent3d, dim: wgt::TextureDimension) -> Self {
|
||||
Self {
|
||||
width: extent.width,
|
||||
height: extent.height,
|
||||
depth: match dim {
|
||||
wgt::TextureDimension::D1 | wgt::TextureDimension::D2 => 1,
|
||||
wgt::TextureDimension::D3 => extent.depth_or_array_layers,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn min(&self, other: &Self) -> Self {
|
||||
Self {
|
||||
width: self.width.min(other.width),
|
||||
height: self.height.min(other.height),
|
||||
depth: self.depth.min(other.depth),
|
||||
}
|
||||
}
|
||||
|
||||
// Get the copy size at a specific mipmap level. This doesn't make most sense,
|
||||
// since the copy extents are provided *for* a mipmap level to start with.
|
||||
// But backends use `CopyExtent` more sparingly, and this piece is shared.
|
||||
pub fn at_mip_level(&self, level: u32) -> Self {
|
||||
Self {
|
||||
width: (self.width >> level).max(1),
|
||||
height: (self.height >> level).max(1),
|
||||
depth: (self.depth >> level).max(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::TextureCopyBase {
|
||||
pub fn max_copy_size(&self, full_size: &crate::CopyExtent) -> crate::CopyExtent {
|
||||
let mip = full_size.at_mip_level(self.mip_level);
|
||||
crate::CopyExtent {
|
||||
width: mip.width - self.origin.x,
|
||||
height: mip.height - self.origin.y,
|
||||
depth: mip.depth - self.origin.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::BufferTextureCopy {
|
||||
pub fn clamp_size_to_virtual(&mut self, full_size: &crate::CopyExtent) {
|
||||
let max_size = self.texture_base.max_copy_size(full_size);
|
||||
self.size = self.size.min(&max_size);
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::TextureCopy {
|
||||
pub fn clamp_size_to_virtual(
|
||||
&mut self,
|
||||
full_src_size: &crate::CopyExtent,
|
||||
full_dst_size: &crate::CopyExtent,
|
||||
) {
|
||||
let max_src_size = self.src_base.max_copy_size(full_src_size);
|
||||
let max_dst_size = self.dst_base.max_copy_size(full_dst_size);
|
||||
self.size = self.size.min(&max_src_size).min(&max_dst_size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adjust `limits` to honor HAL-imposed maximums and comply with WebGPU's
|
||||
/// adapter capability guarantees.
|
||||
#[cfg_attr(not(any_backend), allow(dead_code))]
|
||||
pub(crate) fn adjust_raw_limits(mut limits: wgt::Limits) -> wgt::Limits {
|
||||
// Apply hal limits.
|
||||
limits.max_bind_groups = limits.max_bind_groups.min(crate::MAX_BIND_GROUPS as u32);
|
||||
limits.max_vertex_buffers = limits
|
||||
.max_vertex_buffers
|
||||
.min(crate::MAX_VERTEX_BUFFERS as u32);
|
||||
// Once we allow the 2 limits above to be higher than 24 we should use
|
||||
// `cap_limits_to_be_under_the_sum_limit` to cap them under
|
||||
// `max_bind_groups_plus_vertex_buffers`.
|
||||
const { assert!(crate::MAX_BIND_GROUPS + crate::MAX_VERTEX_BUFFERS == 24) };
|
||||
limits.max_bind_groups_plus_vertex_buffers = limits.max_bind_groups_plus_vertex_buffers.min(24);
|
||||
limits.max_color_attachments = limits
|
||||
.max_color_attachments
|
||||
.min(crate::MAX_COLOR_ATTACHMENTS as u32);
|
||||
|
||||
// Adjust limits according to WebGPU adapter capability guarantees.
|
||||
// See <https://gpuweb.github.io/gpuweb/#adapter-capability-guarantees>.
|
||||
|
||||
// WebGPU requires maxBindingsPerBindGroup to be at least the sum of all
|
||||
// per-stage limits multiplied with the maximum shader stages per pipeline.
|
||||
//
|
||||
// Since backends already report their maximum maxBindingsPerBindGroup,
|
||||
// we need to lower all per-stage limits to satisfy this guarantee.
|
||||
const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2;
|
||||
let max_per_stage_resources =
|
||||
limits.max_bindings_per_bind_group / MAX_SHADER_STAGES_PER_PIPELINE;
|
||||
|
||||
cap_limits_to_be_under_the_sum_limit(
|
||||
[
|
||||
&mut limits.max_sampled_textures_per_shader_stage,
|
||||
&mut limits.max_uniform_buffers_per_shader_stage,
|
||||
&mut limits.max_storage_textures_per_shader_stage,
|
||||
&mut limits.max_storage_buffers_per_shader_stage,
|
||||
&mut limits.max_samplers_per_shader_stage,
|
||||
&mut limits.max_acceleration_structures_per_shader_stage,
|
||||
],
|
||||
max_per_stage_resources,
|
||||
);
|
||||
|
||||
// Not required by the spec but dynamic buffers count
|
||||
// towards non-dynamic buffer limits as well.
|
||||
limits.max_dynamic_uniform_buffers_per_pipeline_layout = limits
|
||||
.max_dynamic_uniform_buffers_per_pipeline_layout
|
||||
.min(limits.max_uniform_buffers_per_shader_stage);
|
||||
limits.max_dynamic_storage_buffers_per_pipeline_layout = limits
|
||||
.max_dynamic_storage_buffers_per_pipeline_layout
|
||||
.min(limits.max_storage_buffers_per_shader_stage);
|
||||
|
||||
limits.min_uniform_buffer_offset_alignment = limits.min_uniform_buffer_offset_alignment.max(32);
|
||||
limits.min_storage_buffer_offset_alignment = limits.min_storage_buffer_offset_alignment.max(32);
|
||||
|
||||
limits.max_uniform_buffer_binding_size = limits
|
||||
.max_uniform_buffer_binding_size
|
||||
.min(limits.max_buffer_size);
|
||||
limits.max_storage_buffer_binding_size = limits
|
||||
.max_storage_buffer_binding_size
|
||||
.min(limits.max_buffer_size);
|
||||
|
||||
limits.max_storage_buffer_binding_size &= !(u64::from(wgt::STORAGE_BINDING_SIZE_ALIGNMENT) - 1);
|
||||
limits.max_vertex_buffer_array_stride &= !(wgt::VERTEX_ALIGNMENT as u32 - 1);
|
||||
|
||||
let x = limits.max_compute_workgroup_size_x;
|
||||
let y = limits.max_compute_workgroup_size_y;
|
||||
let z = limits.max_compute_workgroup_size_z;
|
||||
let m = limits.max_compute_invocations_per_workgroup;
|
||||
limits.max_compute_workgroup_size_x = x.min(m);
|
||||
limits.max_compute_workgroup_size_y = y.min(m);
|
||||
limits.max_compute_workgroup_size_z = z.min(m);
|
||||
limits.max_compute_invocations_per_workgroup = m.min(x.saturating_mul(y).saturating_mul(z));
|
||||
|
||||
limits.max_immediate_size = limits.max_immediate_size.min(256);
|
||||
|
||||
limits
|
||||
}
|
||||
|
||||
/// Evenly allocates space to each limit,
|
||||
/// capping them only if strictly necessary.
|
||||
pub fn cap_limits_to_be_under_the_sum_limit<const N: usize>(
|
||||
mut limits: [&mut u32; N],
|
||||
sum_limit: u32,
|
||||
) {
|
||||
limits.sort();
|
||||
|
||||
let mut rem_limit = sum_limit;
|
||||
let mut divisor = limits.len() as u32;
|
||||
for limit_to_adjust in limits {
|
||||
let limit = rem_limit / divisor;
|
||||
*limit_to_adjust = (*limit_to_adjust).min(limit);
|
||||
rem_limit -= *limit_to_adjust;
|
||||
divisor -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_cap_limits_to_be_under_the_sum_limit() {
|
||||
test([3, 3, 3], 3, [1, 1, 1]);
|
||||
test([3, 2, 1], 3, [1, 1, 1]);
|
||||
test([1, 2, 3], 6, [1, 2, 3]);
|
||||
test([1, 2, 3], 3, [1, 1, 1]);
|
||||
test([1, 8, 100], 6, [1, 2, 3]);
|
||||
test([2, 80, 80], 6, [2, 2, 2]);
|
||||
test([2, 80, 80], 12, [2, 5, 5]);
|
||||
|
||||
#[track_caller]
|
||||
fn test<const N: usize>(mut input: [u32; N], limit: u32, output: [u32; N]) {
|
||||
cap_limits_to_be_under_the_sum_limit(input.each_mut(), limit);
|
||||
assert_eq!(input, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
//! RenderDoc integration - <https://renderdoc.org/>
|
||||
#![cfg_attr(not(any(feature = "gles", feature = "vulkan")), allow(dead_code))]
|
||||
|
||||
use alloc::format;
|
||||
use alloc::string::String;
|
||||
use core::{ffi, ptr};
|
||||
|
||||
/// The dynamically loaded RenderDoc API function table
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct RenderDocApi {
|
||||
api: renderdoc_sys::RENDERDOC_API_1_4_1,
|
||||
lib: libloading::Library,
|
||||
}
|
||||
|
||||
unsafe impl Send for RenderDocApi {}
|
||||
unsafe impl Sync for RenderDocApi {}
|
||||
|
||||
/// RenderDoc API type
|
||||
#[derive(Debug)]
|
||||
pub enum RenderDoc {
|
||||
/// RenderDoc functionality is available
|
||||
Available {
|
||||
/// RenderDoc API with function pointers
|
||||
api: RenderDocApi,
|
||||
},
|
||||
/// RenderDoc functionality is _not_ available
|
||||
NotAvailable {
|
||||
/// A description why renderdoc functionality is not available
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
// TODO: replace with libloading API once supported
|
||||
#[cfg(unix)]
|
||||
const RTLD_NOLOAD: i32 = 0x4;
|
||||
|
||||
impl RenderDoc {
|
||||
pub unsafe fn new() -> Self {
|
||||
type GetApiFn = unsafe extern "C" fn(version: u32, out: *mut *mut ffi::c_void) -> i32;
|
||||
|
||||
#[cfg(windows)]
|
||||
let renderdoc_filename = "renderdoc.dll";
|
||||
#[cfg(all(unix, not(target_os = "android")))]
|
||||
let renderdoc_filename = "librenderdoc.so";
|
||||
#[cfg(target_os = "android")]
|
||||
let renderdoc_filename = "libVkLayer_GLES_RenderDoc.so";
|
||||
|
||||
#[cfg(unix)]
|
||||
let renderdoc_result: Result<libloading::Library, libloading::Error> = unsafe {
|
||||
libloading::os::unix::Library::open(
|
||||
Some(renderdoc_filename),
|
||||
libloading::os::unix::RTLD_NOW | RTLD_NOLOAD,
|
||||
)
|
||||
}
|
||||
.map(|lib| lib.into());
|
||||
|
||||
#[cfg(windows)]
|
||||
let renderdoc_result: Result<libloading::Library, libloading::Error> =
|
||||
libloading::os::windows::Library::open_already_loaded(renderdoc_filename)
|
||||
.map(|lib| lib.into());
|
||||
|
||||
let renderdoc_lib = match renderdoc_result {
|
||||
Ok(lib) => lib,
|
||||
Err(e) => {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to load renderdoc library '{renderdoc_filename}': {e:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let get_api: libloading::Symbol<GetApiFn> =
|
||||
match unsafe { renderdoc_lib.get(c"RENDERDOC_GetAPI".to_bytes()) } {
|
||||
Ok(api) => api,
|
||||
Err(e) => {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to get RENDERDOC_GetAPI from renderdoc library '{renderdoc_filename}': {e:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut obj = ptr::null_mut();
|
||||
match unsafe { get_api(10401, &mut obj) } {
|
||||
1 => RenderDoc::Available {
|
||||
api: RenderDocApi {
|
||||
api: unsafe { *obj.cast::<renderdoc_sys::RENDERDOC_API_1_4_1>() },
|
||||
lib: renderdoc_lib,
|
||||
},
|
||||
},
|
||||
return_value => RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to get API from renderdoc library '{renderdoc_filename}': {return_value}"
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RenderDoc {
|
||||
fn default() -> Self {
|
||||
if !cfg!(debug_assertions) {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: "RenderDoc support is only enabled with 'debug_assertions'".into(),
|
||||
};
|
||||
}
|
||||
unsafe { Self::new() }
|
||||
}
|
||||
}
|
||||
/// An implementation specific handle
|
||||
pub type Handle = *mut ffi::c_void;
|
||||
|
||||
impl RenderDoc {
|
||||
/// Start a RenderDoc frame capture
|
||||
pub unsafe fn start_frame_capture(&self, device_handle: Handle, window_handle: Handle) -> bool {
|
||||
match *self {
|
||||
Self::Available { api: ref entry } => {
|
||||
unsafe { entry.api.StartFrameCapture.unwrap()(device_handle, window_handle) };
|
||||
true
|
||||
}
|
||||
Self::NotAvailable { ref reason } => {
|
||||
log::warn!("Could not start RenderDoc frame capture: {reason}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// End a RenderDoc frame capture
|
||||
pub unsafe fn end_frame_capture(&self, device_handle: Handle, window_handle: Handle) {
|
||||
match *self {
|
||||
Self::Available { api: ref entry } => {
|
||||
unsafe { entry.api.EndFrameCapture.unwrap()(device_handle, window_handle) };
|
||||
}
|
||||
Self::NotAvailable { ref reason } => {
|
||||
log::warn!("Could not end RenderDoc frame capture: {reason}")
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Vendored
+1546
File diff suppressed because it is too large
Load Diff
Vendored
+1868
File diff suppressed because it is too large
Load Diff
Vendored
+467
@@ -0,0 +1,467 @@
|
||||
use windows::Win32::Graphics::{Direct3D, Direct3D12, Dxgi};
|
||||
|
||||
pub fn map_buffer_usage_to_resource_flags(
|
||||
usage: wgt::BufferUses,
|
||||
) -> Direct3D12::D3D12_RESOURCE_FLAGS {
|
||||
let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE;
|
||||
if usage.contains(wgt::BufferUses::STORAGE_READ_WRITE)
|
||||
|| usage.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY)
|
||||
{
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
}
|
||||
flags
|
||||
}
|
||||
|
||||
pub fn map_buffer_descriptor(
|
||||
desc: &crate::BufferDescriptor<'_>,
|
||||
) -> Direct3D12::D3D12_RESOURCE_DESC {
|
||||
Direct3D12::D3D12_RESOURCE_DESC {
|
||||
Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Alignment: 0,
|
||||
Width: desc.size,
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN,
|
||||
SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
Flags: map_buffer_usage_to_resource_flags(desc.usage),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_texture_dimension(dim: wgt::TextureDimension) -> Direct3D12::D3D12_RESOURCE_DIMENSION {
|
||||
match dim {
|
||||
wgt::TextureDimension::D1 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE1D,
|
||||
wgt::TextureDimension::D2 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE2D,
|
||||
wgt::TextureDimension::D3 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE3D,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_texture_usage_to_resource_flags(
|
||||
usage: wgt::TextureUses,
|
||||
) -> Direct3D12::D3D12_RESOURCE_FLAGS {
|
||||
let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE;
|
||||
|
||||
if usage.contains(wgt::TextureUses::COLOR_TARGET) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
}
|
||||
if usage
|
||||
.intersects(wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::DEPTH_STENCIL_WRITE)
|
||||
{
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
|
||||
if !usage.contains(wgt::TextureUses::RESOURCE) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
|
||||
}
|
||||
}
|
||||
if usage.intersects(
|
||||
wgt::TextureUses::STORAGE_READ_ONLY
|
||||
| wgt::TextureUses::STORAGE_WRITE_ONLY
|
||||
| wgt::TextureUses::STORAGE_READ_WRITE,
|
||||
) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
}
|
||||
|
||||
flags
|
||||
}
|
||||
|
||||
pub fn map_address_mode(mode: wgt::AddressMode) -> Direct3D12::D3D12_TEXTURE_ADDRESS_MODE {
|
||||
use wgt::AddressMode as Am;
|
||||
match mode {
|
||||
Am::Repeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_WRAP,
|
||||
Am::MirrorRepeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR,
|
||||
Am::ClampToEdge => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
Am::ClampToBorder => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_BORDER,
|
||||
//Am::MirrorClamp => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_filter_mode(mode: wgt::FilterMode) -> Direct3D12::D3D12_FILTER_TYPE {
|
||||
match mode {
|
||||
wgt::FilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT,
|
||||
wgt::FilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_mipmap_filter_mode(mode: wgt::MipmapFilterMode) -> Direct3D12::D3D12_FILTER_TYPE {
|
||||
match mode {
|
||||
wgt::MipmapFilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT,
|
||||
wgt::MipmapFilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_comparison(func: wgt::CompareFunction) -> Direct3D12::D3D12_COMPARISON_FUNC {
|
||||
use wgt::CompareFunction as Cf;
|
||||
match func {
|
||||
Cf::Never => Direct3D12::D3D12_COMPARISON_FUNC_NEVER,
|
||||
Cf::Less => Direct3D12::D3D12_COMPARISON_FUNC_LESS,
|
||||
Cf::LessEqual => Direct3D12::D3D12_COMPARISON_FUNC_LESS_EQUAL,
|
||||
Cf::Equal => Direct3D12::D3D12_COMPARISON_FUNC_EQUAL,
|
||||
Cf::GreaterEqual => Direct3D12::D3D12_COMPARISON_FUNC_GREATER_EQUAL,
|
||||
Cf::Greater => Direct3D12::D3D12_COMPARISON_FUNC_GREATER,
|
||||
Cf::NotEqual => Direct3D12::D3D12_COMPARISON_FUNC_NOT_EQUAL,
|
||||
Cf::Always => Direct3D12::D3D12_COMPARISON_FUNC_ALWAYS,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_border_color(border_color: Option<wgt::SamplerBorderColor>) -> [f32; 4] {
|
||||
use wgt::SamplerBorderColor as Sbc;
|
||||
match border_color {
|
||||
Some(Sbc::TransparentBlack) | Some(Sbc::Zero) | None => [0.0; 4],
|
||||
Some(Sbc::OpaqueBlack) => [0.0, 0.0, 0.0, 1.0],
|
||||
Some(Sbc::OpaqueWhite) => [1.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_visibility(visibility: wgt::ShaderStages) -> Direct3D12::D3D12_SHADER_VISIBILITY {
|
||||
match visibility {
|
||||
wgt::ShaderStages::VERTEX => Direct3D12::D3D12_SHADER_VISIBILITY_VERTEX,
|
||||
wgt::ShaderStages::FRAGMENT => Direct3D12::D3D12_SHADER_VISIBILITY_PIXEL,
|
||||
_ => Direct3D12::D3D12_SHADER_VISIBILITY_ALL,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_binding_type(ty: &wgt::BindingType) -> Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE {
|
||||
use wgt::BindingType as Bt;
|
||||
match *ty {
|
||||
Bt::Sampler { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Uniform,
|
||||
..
|
||||
} => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { read_only: true },
|
||||
..
|
||||
}
|
||||
| Bt::Texture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { read_only: false },
|
||||
..
|
||||
}
|
||||
| Bt::StorageTexture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
|
||||
Bt::AccelerationStructure { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
|
||||
// External textures require multiple bindings and therefore cannot
|
||||
// be mapped to a single descriptor range type. They must be handled
|
||||
// separately by the caller.
|
||||
Bt::ExternalTexture => unreachable!("External textures must be handled separately"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_buffer_usage_to_state(usage: wgt::BufferUses) -> Direct3D12::D3D12_RESOURCE_STATES {
|
||||
use wgt::BufferUses as Bu;
|
||||
let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON;
|
||||
|
||||
if usage.intersects(Bu::COPY_SRC) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
}
|
||||
if usage.intersects(Bu::COPY_DST) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
}
|
||||
if usage.intersects(Bu::INDEX) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_INDEX_BUFFER;
|
||||
}
|
||||
if usage.intersects(Bu::VERTEX | Bu::UNIFORM) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
|
||||
}
|
||||
if usage.intersects(Bu::STORAGE_READ_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
} else if usage.intersects(Bu::STORAGE_READ_ONLY) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
|
||||
| Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
|
||||
}
|
||||
if usage.intersects(Bu::INDIRECT) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
|
||||
}
|
||||
if usage.intersects(Bu::ACCELERATION_STRUCTURE_QUERY) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub fn map_texture_usage_to_state(usage: wgt::TextureUses) -> Direct3D12::D3D12_RESOURCE_STATES {
|
||||
use wgt::TextureUses as Tu;
|
||||
let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON;
|
||||
//Note: `RESOLVE_SOURCE` and `RESOLVE_DEST` are not used here
|
||||
//Note: `PRESENT` is the same as `COMMON`
|
||||
if usage == wgt::TextureUses::UNINITIALIZED {
|
||||
return state;
|
||||
}
|
||||
|
||||
if usage.intersects(Tu::COPY_SRC) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
}
|
||||
if usage.intersects(Tu::COPY_DST) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
}
|
||||
if usage.intersects(Tu::RESOURCE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
|
||||
| Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
|
||||
}
|
||||
if usage.intersects(Tu::COLOR_TARGET) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
}
|
||||
if usage.intersects(Tu::DEPTH_STENCIL_READ) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_READ;
|
||||
}
|
||||
if usage.intersects(Tu::DEPTH_STENCIL_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_WRITE;
|
||||
}
|
||||
if usage.intersects(Tu::STORAGE_READ_ONLY | Tu::STORAGE_WRITE_ONLY | Tu::STORAGE_READ_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub fn map_topology(
|
||||
topology: wgt::PrimitiveTopology,
|
||||
) -> (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY,
|
||||
) {
|
||||
match topology {
|
||||
wgt::PrimitiveTopology::PointList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::LineList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINELIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::LineStrip => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINESTRIP,
|
||||
),
|
||||
wgt::PrimitiveTopology::TriangleList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::TriangleStrip => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_polygon_mode(mode: wgt::PolygonMode) -> Direct3D12::D3D12_FILL_MODE {
|
||||
match mode {
|
||||
wgt::PolygonMode::Fill => Direct3D12::D3D12_FILL_MODE_SOLID,
|
||||
wgt::PolygonMode::Line => Direct3D12::D3D12_FILL_MODE_WIREFRAME,
|
||||
wgt::PolygonMode::Point => panic!(
|
||||
"{:?} is not enabled for this backend",
|
||||
wgt::Features::POLYGON_MODE_POINT
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// D3D12 doesn't support passing factors ending in `_COLOR` for alpha blending
|
||||
/// (see <https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_render_target_blend_desc>).
|
||||
/// Therefore this function takes an additional `is_alpha` argument
|
||||
/// which if set will return an equivalent `_ALPHA` factor.
|
||||
fn map_blend_factor(factor: wgt::BlendFactor, is_alpha: bool) -> Direct3D12::D3D12_BLEND {
|
||||
use wgt::BlendFactor as Bf;
|
||||
match factor {
|
||||
Bf::Zero => Direct3D12::D3D12_BLEND_ZERO,
|
||||
Bf::One => Direct3D12::D3D12_BLEND_ONE,
|
||||
Bf::Src if is_alpha => Direct3D12::D3D12_BLEND_SRC_ALPHA,
|
||||
Bf::Src => Direct3D12::D3D12_BLEND_SRC_COLOR,
|
||||
Bf::OneMinusSrc if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA,
|
||||
Bf::OneMinusSrc => Direct3D12::D3D12_BLEND_INV_SRC_COLOR,
|
||||
Bf::Dst if is_alpha => Direct3D12::D3D12_BLEND_DEST_ALPHA,
|
||||
Bf::Dst => Direct3D12::D3D12_BLEND_DEST_COLOR,
|
||||
Bf::OneMinusDst if is_alpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA,
|
||||
Bf::OneMinusDst => Direct3D12::D3D12_BLEND_INV_DEST_COLOR,
|
||||
Bf::SrcAlpha => Direct3D12::D3D12_BLEND_SRC_ALPHA,
|
||||
Bf::OneMinusSrcAlpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA,
|
||||
Bf::DstAlpha => Direct3D12::D3D12_BLEND_DEST_ALPHA,
|
||||
Bf::OneMinusDstAlpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA,
|
||||
Bf::Constant => Direct3D12::D3D12_BLEND_BLEND_FACTOR,
|
||||
Bf::OneMinusConstant => Direct3D12::D3D12_BLEND_INV_BLEND_FACTOR,
|
||||
Bf::SrcAlphaSaturated => Direct3D12::D3D12_BLEND_SRC_ALPHA_SAT,
|
||||
Bf::Src1 if is_alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA,
|
||||
Bf::Src1 => Direct3D12::D3D12_BLEND_SRC1_COLOR,
|
||||
Bf::OneMinusSrc1 if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA,
|
||||
Bf::OneMinusSrc1 => Direct3D12::D3D12_BLEND_INV_SRC1_COLOR,
|
||||
Bf::Src1Alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA,
|
||||
Bf::OneMinusSrc1Alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_blend_component(
|
||||
component: &wgt::BlendComponent,
|
||||
is_alpha: bool,
|
||||
) -> (
|
||||
Direct3D12::D3D12_BLEND_OP,
|
||||
Direct3D12::D3D12_BLEND,
|
||||
Direct3D12::D3D12_BLEND,
|
||||
) {
|
||||
let raw_op = match component.operation {
|
||||
wgt::BlendOperation::Add => Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
wgt::BlendOperation::Subtract => Direct3D12::D3D12_BLEND_OP_SUBTRACT,
|
||||
wgt::BlendOperation::ReverseSubtract => Direct3D12::D3D12_BLEND_OP_REV_SUBTRACT,
|
||||
wgt::BlendOperation::Min => Direct3D12::D3D12_BLEND_OP_MIN,
|
||||
wgt::BlendOperation::Max => Direct3D12::D3D12_BLEND_OP_MAX,
|
||||
};
|
||||
let raw_src = map_blend_factor(component.src_factor, is_alpha);
|
||||
let raw_dst = map_blend_factor(component.dst_factor, is_alpha);
|
||||
(raw_op, raw_src, raw_dst)
|
||||
}
|
||||
|
||||
pub fn map_render_targets(
|
||||
color_targets: &[Option<wgt::ColorTargetState>],
|
||||
) -> [Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC;
|
||||
Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize] {
|
||||
let dummy_target = Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC {
|
||||
BlendEnable: false.into(),
|
||||
LogicOpEnable: false.into(),
|
||||
SrcBlend: Direct3D12::D3D12_BLEND_ZERO,
|
||||
DestBlend: Direct3D12::D3D12_BLEND_ZERO,
|
||||
BlendOp: Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
SrcBlendAlpha: Direct3D12::D3D12_BLEND_ZERO,
|
||||
DestBlendAlpha: Direct3D12::D3D12_BLEND_ZERO,
|
||||
BlendOpAlpha: Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
LogicOp: Direct3D12::D3D12_LOGIC_OP_CLEAR,
|
||||
RenderTargetWriteMask: 0,
|
||||
};
|
||||
let mut raw_targets =
|
||||
[dummy_target; Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize];
|
||||
|
||||
for (raw, ct) in raw_targets.iter_mut().zip(color_targets.iter()) {
|
||||
if let Some(ct) = ct.as_ref() {
|
||||
raw.RenderTargetWriteMask = ct.write_mask.bits() as u8;
|
||||
if let Some(ref blend) = ct.blend {
|
||||
let (color_op, color_src, color_dst) = map_blend_component(&blend.color, false);
|
||||
let (alpha_op, alpha_src, alpha_dst) = map_blend_component(&blend.alpha, true);
|
||||
raw.BlendEnable = true.into();
|
||||
raw.BlendOp = color_op;
|
||||
raw.SrcBlend = color_src;
|
||||
raw.DestBlend = color_dst;
|
||||
raw.BlendOpAlpha = alpha_op;
|
||||
raw.SrcBlendAlpha = alpha_src;
|
||||
raw.DestBlendAlpha = alpha_dst;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
raw_targets
|
||||
}
|
||||
|
||||
fn map_stencil_op(op: wgt::StencilOperation) -> Direct3D12::D3D12_STENCIL_OP {
|
||||
use wgt::StencilOperation as So;
|
||||
match op {
|
||||
So::Keep => Direct3D12::D3D12_STENCIL_OP_KEEP,
|
||||
So::Zero => Direct3D12::D3D12_STENCIL_OP_ZERO,
|
||||
So::Replace => Direct3D12::D3D12_STENCIL_OP_REPLACE,
|
||||
So::IncrementClamp => Direct3D12::D3D12_STENCIL_OP_INCR_SAT,
|
||||
So::IncrementWrap => Direct3D12::D3D12_STENCIL_OP_INCR,
|
||||
So::DecrementClamp => Direct3D12::D3D12_STENCIL_OP_DECR_SAT,
|
||||
So::DecrementWrap => Direct3D12::D3D12_STENCIL_OP_DECR,
|
||||
So::Invert => Direct3D12::D3D12_STENCIL_OP_INVERT,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_stencil_face(face: &wgt::StencilFaceState) -> Direct3D12::D3D12_DEPTH_STENCILOP_DESC {
|
||||
Direct3D12::D3D12_DEPTH_STENCILOP_DESC {
|
||||
StencilFailOp: map_stencil_op(face.fail_op),
|
||||
StencilDepthFailOp: map_stencil_op(face.depth_fail_op),
|
||||
StencilPassOp: map_stencil_op(face.pass_op),
|
||||
StencilFunc: map_comparison(face.compare),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_depth_stencil(ds: &wgt::DepthStencilState) -> Direct3D12::D3D12_DEPTH_STENCIL_DESC {
|
||||
Direct3D12::D3D12_DEPTH_STENCIL_DESC {
|
||||
DepthEnable: ds.is_depth_enabled().into(),
|
||||
DepthWriteMask: if ds.depth_write_enabled.unwrap_or_default() {
|
||||
Direct3D12::D3D12_DEPTH_WRITE_MASK_ALL
|
||||
} else {
|
||||
Direct3D12::D3D12_DEPTH_WRITE_MASK_ZERO
|
||||
},
|
||||
DepthFunc: map_comparison(ds.depth_compare.unwrap_or_default()),
|
||||
StencilEnable: ds.stencil.is_enabled().into(),
|
||||
StencilReadMask: ds.stencil.read_mask as u8,
|
||||
StencilWriteMask: ds.stencil.write_mask as u8,
|
||||
FrontFace: map_stencil_face(&ds.stencil.front),
|
||||
BackFace: map_stencil_face(&ds.stencil.back),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_build_flags(
|
||||
flags: wgt::AccelerationStructureFlags,
|
||||
mode: Option<crate::AccelerationStructureBuildMode>,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS {
|
||||
let mut d3d_flags = Default::default();
|
||||
if flags.contains(wgt::AccelerationStructureFlags::ALLOW_COMPACTION) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::ALLOW_UPDATE) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::LOW_MEMORY) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_BUILD) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_TRACE) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE;
|
||||
}
|
||||
|
||||
if let Some(crate::AccelerationStructureBuildMode::Update) = mode {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE
|
||||
}
|
||||
|
||||
d3d_flags
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_geometry_flags(
|
||||
flags: wgt::AccelerationStructureGeometryFlags,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAGS {
|
||||
let mut d3d_flags = Default::default();
|
||||
if flags.contains(wgt::AccelerationStructureGeometryFlags::OPAQUE) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE;
|
||||
}
|
||||
if flags.contains(wgt::AccelerationStructureGeometryFlags::NO_DUPLICATE_ANY_HIT_INVOCATION) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_NO_DUPLICATE_ANYHIT_INVOCATION;
|
||||
}
|
||||
d3d_flags
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_copy_mode(
|
||||
mode: wgt::AccelerationStructureCopy,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE {
|
||||
match mode {
|
||||
wgt::AccelerationStructureCopy::Clone => {
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE
|
||||
}
|
||||
wgt::AccelerationStructureCopy::Compact => {
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn make_shader_component_mapping(
|
||||
src0: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src1: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src2: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src3: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
) -> Direct3D12::D3D12_SHADER_COMPONENT_MAPPING {
|
||||
const M: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_MASK as i32;
|
||||
const S: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_SHIFT as i32;
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING(
|
||||
(src0.0 & M)
|
||||
| (src1.0 & M) << S
|
||||
| (src2.0 & M) << (S * 2)
|
||||
| (src3.0 & M) << (S * 3)
|
||||
| Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES
|
||||
as i32,
|
||||
)
|
||||
}
|
||||
Vendored
+120
@@ -0,0 +1,120 @@
|
||||
use alloc::sync::Arc;
|
||||
use core::{ffi, ptr};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use windows::{
|
||||
core::Interface as _,
|
||||
Win32::{Foundation::HWND, Graphics::DirectComposition},
|
||||
};
|
||||
|
||||
use super::DynLib;
|
||||
|
||||
// Lazy-loaded DirectComposition library
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DCompLib {
|
||||
lib: Lazy<Result<DynLib, crate::SurfaceError>>,
|
||||
}
|
||||
|
||||
impl DCompLib {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
lib: Lazy::new(|| unsafe {
|
||||
DynLib::new("dcomp.dll").map_err(|err| {
|
||||
log::error!("Error loading dcomp.dll: {err}");
|
||||
crate::SurfaceError::Other("Error loading dcomp.dll")
|
||||
})
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_lib(&self) -> Result<&DynLib, crate::SurfaceError> {
|
||||
match self.lib.as_ref() {
|
||||
Ok(lib) => Ok(lib),
|
||||
Err(err) => Err(err.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_device(
|
||||
&self,
|
||||
) -> Result<DirectComposition::IDCompositionDevice, crate::SurfaceError> {
|
||||
let lib = self.get_lib()?;
|
||||
|
||||
// Calls windows::Win32::Graphics::DirectComposition::DCompositionCreateDevice2 on dcomp.dll
|
||||
type Fun = extern "system" fn(
|
||||
pdxdevice: *mut ffi::c_void,
|
||||
riid: *const windows_core::GUID,
|
||||
ppdcompdevice: *mut *mut ffi::c_void,
|
||||
) -> windows_core::HRESULT;
|
||||
let func: libloading::Symbol<Fun> =
|
||||
unsafe { lib.get(c"DCompositionCreateDevice2".to_bytes()) }?;
|
||||
|
||||
let mut res: Option<DirectComposition::IDCompositionDevice> = None;
|
||||
|
||||
(func)(
|
||||
ptr::null_mut(),
|
||||
&DirectComposition::IDCompositionDevice::IID,
|
||||
<*mut _>::cast(&mut res),
|
||||
)
|
||||
.map(|| res.unwrap())
|
||||
.map_err(|err| {
|
||||
log::error!("DirectComposition::DCompositionCreateDevice2 failed: {err}");
|
||||
crate::SurfaceError::Other("DirectComposition::DCompositionCreateDevice2")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DCompState {
|
||||
inner: Option<InnerState>,
|
||||
}
|
||||
|
||||
impl DCompState {
|
||||
/// This will create a DirectComposition device and a target for the window handle if not already initialized.
|
||||
/// If the device is already initialized, it will return the existing state.
|
||||
pub unsafe fn get_or_init(
|
||||
&mut self,
|
||||
lib: &Arc<DCompLib>,
|
||||
hwnd: &HWND,
|
||||
) -> Result<&mut InnerState, crate::SurfaceError> {
|
||||
if self.inner.is_none() {
|
||||
self.inner = Some(unsafe { InnerState::init(lib, hwnd) }?);
|
||||
}
|
||||
Ok(self.inner.as_mut().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InnerState {
|
||||
pub visual: DirectComposition::IDCompositionVisual,
|
||||
pub device: DirectComposition::IDCompositionDevice,
|
||||
// Must be kept alive but is otherwise unused after initialization.
|
||||
pub _target: DirectComposition::IDCompositionTarget,
|
||||
}
|
||||
|
||||
impl InnerState {
|
||||
/// Creates a DirectComposition device and a target for the given window handle.
|
||||
pub unsafe fn init(lib: &Arc<DCompLib>, hwnd: &HWND) -> Result<Self, crate::SurfaceError> {
|
||||
profiling::scope!("DCompState::init");
|
||||
let dcomp_device = lib.create_device()?;
|
||||
|
||||
let target = unsafe { dcomp_device.CreateTargetForHwnd(*hwnd, false) }.map_err(|err| {
|
||||
log::error!("IDCompositionDevice::CreateTargetForHwnd failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionDevice::CreateTargetForHwnd")
|
||||
})?;
|
||||
|
||||
let visual = unsafe { dcomp_device.CreateVisual() }.map_err(|err| {
|
||||
log::error!("IDCompositionDevice::CreateVisual failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionDevice::CreateVisual")
|
||||
})?;
|
||||
|
||||
unsafe { target.SetRoot(&visual) }.map_err(|err| {
|
||||
log::error!("IDCompositionTarget::SetRoot failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionTarget::SetRoot")
|
||||
})?;
|
||||
|
||||
Ok(InnerState {
|
||||
visual,
|
||||
device: dcomp_device,
|
||||
_target: target,
|
||||
})
|
||||
}
|
||||
}
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
use alloc::vec::Vec;
|
||||
use core::fmt;
|
||||
|
||||
use bit_set::BitSet;
|
||||
use parking_lot::Mutex;
|
||||
use range_alloc::RangeAllocator;
|
||||
use windows::Win32::Graphics::Direct3D12;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult as _;
|
||||
|
||||
const HEAP_SIZE_FIXED: usize = 64;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub(super) struct DualHandle {
|
||||
cpu: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
pub gpu: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE,
|
||||
/// How large the block allocated to this handle is.
|
||||
count: u64,
|
||||
}
|
||||
|
||||
impl fmt::Debug for DualHandle {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("DualHandle")
|
||||
.field("cpu", &self.cpu.ptr)
|
||||
.field("gpu", &self.gpu.ptr)
|
||||
.field("count", &self.count)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
type DescriptorIndex = u64;
|
||||
|
||||
pub(super) struct GeneralHeap {
|
||||
pub raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
handle_size: u64,
|
||||
total_handles: u64,
|
||||
start: DualHandle,
|
||||
ranges: Mutex<RangeAllocator<DescriptorIndex>>,
|
||||
}
|
||||
|
||||
impl GeneralHeap {
|
||||
pub(super) fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
total_handles: u64,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let raw = {
|
||||
profiling::scope!("ID3D12Device::CreateDescriptorHeap");
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: total_handles as u32,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Descriptor heap creation")?
|
||||
};
|
||||
|
||||
let start = DualHandle {
|
||||
cpu: unsafe { raw.GetCPUDescriptorHandleForHeapStart() },
|
||||
gpu: unsafe { raw.GetGPUDescriptorHandleForHeapStart() },
|
||||
count: 0,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
raw,
|
||||
ty,
|
||||
handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as u64,
|
||||
total_handles,
|
||||
start,
|
||||
ranges: Mutex::new(RangeAllocator::new(0..total_handles)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn at(&self, index: DescriptorIndex, count: u64) -> DualHandle {
|
||||
assert!(index < self.total_handles);
|
||||
DualHandle {
|
||||
cpu: self.cpu_descriptor_at(index),
|
||||
gpu: self.gpu_descriptor_at(index),
|
||||
count,
|
||||
}
|
||||
}
|
||||
|
||||
fn cpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.cpu.ptr + (self.handle_size * index) as usize,
|
||||
}
|
||||
}
|
||||
|
||||
fn gpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.gpu.ptr + self.handle_size * index,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn allocate_slice(&self, count: u64) -> Result<DescriptorIndex, crate::DeviceError> {
|
||||
let range = self.ranges.lock().allocate_range(count).map_err(|err| {
|
||||
log::error!("Unable to allocate descriptors: {err:?}");
|
||||
crate::DeviceError::OutOfMemory
|
||||
})?;
|
||||
Ok(range.start)
|
||||
}
|
||||
|
||||
/// Free handles previously given out by this `DescriptorHeapSlice`.
|
||||
/// Do not use this with handles not given out by this `DescriptorHeapSlice`.
|
||||
pub(crate) fn free_slice(&self, handle: DualHandle) {
|
||||
let start = (handle.gpu.ptr - self.start.gpu.ptr) / self.handle_size;
|
||||
self.ranges.lock().free_range(start..start + handle.count);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed-size free-list allocator for CPU descriptors.
|
||||
struct FixedSizeHeap {
|
||||
_raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
/// Bit flag representation of available handles in the heap.
|
||||
///
|
||||
/// 0 - Occupied
|
||||
/// 1 - free
|
||||
availability: u64,
|
||||
handle_size: usize,
|
||||
start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
}
|
||||
|
||||
impl FixedSizeHeap {
|
||||
fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: HEAP_SIZE_FIXED as u32,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let heap =
|
||||
unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Descriptor heap creation")?;
|
||||
|
||||
Ok(Self {
|
||||
handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as usize,
|
||||
availability: !0, // all free!
|
||||
start: unsafe { heap.GetCPUDescriptorHandleForHeapStart() },
|
||||
_raw: heap,
|
||||
})
|
||||
}
|
||||
|
||||
fn alloc_handle(
|
||||
&mut self,
|
||||
) -> Result<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, crate::DeviceError> {
|
||||
// Find first free slot.
|
||||
let slot = self.availability.trailing_zeros() as usize;
|
||||
if slot >= HEAP_SIZE_FIXED {
|
||||
log::error!("Failed to allocate a handle form a fixed size heap");
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
// Set the slot as occupied.
|
||||
self.availability ^= 1 << slot;
|
||||
|
||||
Ok(Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.ptr + self.handle_size * slot,
|
||||
})
|
||||
}
|
||||
|
||||
fn free_handle(&mut self, handle: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let slot = (handle.ptr - self.start.ptr) / self.handle_size;
|
||||
assert!(slot < HEAP_SIZE_FIXED);
|
||||
assert_eq!(self.availability & (1 << slot), 0);
|
||||
self.availability ^= 1 << slot;
|
||||
}
|
||||
|
||||
fn is_full(&self) -> bool {
|
||||
self.availability == 0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Handle {
|
||||
pub raw: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
heap_index: usize,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Handle {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.debug_struct("Handle")
|
||||
.field("ptr", &self.raw.ptr)
|
||||
.field("heap_index", &self.heap_index)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct CpuPool {
|
||||
device: Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
heaps: Vec<FixedSizeHeap>,
|
||||
available_heap_indices: BitSet,
|
||||
}
|
||||
|
||||
impl CpuPool {
|
||||
pub(super) fn new(
|
||||
device: Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
) -> Self {
|
||||
Self {
|
||||
device,
|
||||
ty,
|
||||
heaps: Vec::new(),
|
||||
available_heap_indices: BitSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn alloc_handle(&mut self) -> Result<Handle, crate::DeviceError> {
|
||||
let heap_index = self
|
||||
.available_heap_indices
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap_or(self.heaps.len());
|
||||
|
||||
// Allocate a new heap
|
||||
if heap_index == self.heaps.len() {
|
||||
self.heaps.push(FixedSizeHeap::new(&self.device, self.ty)?);
|
||||
self.available_heap_indices.insert(heap_index);
|
||||
}
|
||||
|
||||
let heap = &mut self.heaps[heap_index];
|
||||
let handle = Handle {
|
||||
raw: heap.alloc_handle()?,
|
||||
heap_index,
|
||||
};
|
||||
if heap.is_full() {
|
||||
self.available_heap_indices.remove(heap_index);
|
||||
}
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub(super) fn free_handle(&mut self, handle: Handle) {
|
||||
self.heaps[handle.heap_index].free_handle(handle.raw);
|
||||
self.available_heap_indices.insert(handle.heap_index);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct CpuHeapInner {
|
||||
pub _raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
pub stage: Vec<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE>,
|
||||
}
|
||||
|
||||
pub(super) struct CpuHeap {
|
||||
pub inner: Mutex<CpuHeapInner>,
|
||||
start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
handle_size: u32,
|
||||
total: u32,
|
||||
}
|
||||
|
||||
unsafe impl Send for CpuHeap {}
|
||||
unsafe impl Sync for CpuHeap {}
|
||||
|
||||
impl CpuHeap {
|
||||
pub(super) fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
total: u32,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let handle_size = unsafe { device.GetDescriptorHandleIncrementSize(ty) };
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: total,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let raw = unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("CPU descriptor heap creation")?;
|
||||
|
||||
let start = unsafe { raw.GetCPUDescriptorHandleForHeapStart() };
|
||||
|
||||
Ok(Self {
|
||||
inner: Mutex::new(CpuHeapInner {
|
||||
_raw: raw,
|
||||
stage: Vec::new(),
|
||||
}),
|
||||
start,
|
||||
handle_size,
|
||||
total,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn at(&self, index: u32) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
debug_assert!(
|
||||
index < self.total,
|
||||
"Index ({index}) out of bounds {total}",
|
||||
total = self.total
|
||||
);
|
||||
Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.ptr + (self.handle_size * index) as usize,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CpuHeap {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("CpuHeap")
|
||||
.field("start", &self.start.ptr)
|
||||
.field("handle_size", &self.handle_size)
|
||||
.field("total", &self.total)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) unsafe fn upload(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
src: &CpuHeapInner,
|
||||
dst: &GeneralHeap,
|
||||
dummy_copy_counts: &[u32],
|
||||
) -> Result<DualHandle, crate::DeviceError> {
|
||||
let count = src.stage.len() as u32;
|
||||
let index = dst.allocate_slice(count as u64)?;
|
||||
unsafe {
|
||||
device.CopyDescriptors(
|
||||
1,
|
||||
&dst.cpu_descriptor_at(index),
|
||||
Some(&count),
|
||||
count,
|
||||
src.stage.as_ptr(),
|
||||
Some(dummy_copy_counts.as_ptr()),
|
||||
dst.ty,
|
||||
)
|
||||
};
|
||||
Ok(dst.at(index, count as u64))
|
||||
}
|
||||
Vendored
+2691
File diff suppressed because it is too large
Load Diff
+176
@@ -0,0 +1,176 @@
|
||||
use alloc::sync::Arc;
|
||||
use core::ops::Deref;
|
||||
|
||||
use windows::core::Interface as _;
|
||||
use windows::Win32::Graphics::{Direct3D, Direct3D12};
|
||||
|
||||
use super::D3D12Lib;
|
||||
use crate::auxil::dxgi::factory::DxgiAdapter;
|
||||
|
||||
/// Abstraction over D3D12 device creation.
|
||||
///
|
||||
/// Supports two paths:
|
||||
/// - **Independent**: Uses `ID3D12DeviceFactory` from the Agility SDK's Independent Devices API.
|
||||
/// - **Legacy**: Uses the traditional `D3D12CreateDevice` export.
|
||||
pub(super) enum DeviceFactory {
|
||||
/// Uses `ID3D12DeviceFactory` from the Independent Devices API.
|
||||
Independent(Direct3D12::ID3D12DeviceFactory),
|
||||
/// Uses the traditional `D3D12CreateDevice` export.
|
||||
Legacy,
|
||||
}
|
||||
|
||||
impl DeviceFactory {
|
||||
/// Create a new `DeviceFactory`.
|
||||
///
|
||||
/// If `agility_sdk` is `Some`, attempts to set up the Independent Devices API path.
|
||||
/// On failure, the behavior depends on
|
||||
/// [`on_load_failure`](wgt::Dx12AgilitySDKLoadFailure):
|
||||
/// - [`Fallback`](wgt::Dx12AgilitySDKLoadFailure::Fallback): logs a warning and
|
||||
/// returns `Ok(Legacy)`.
|
||||
/// - [`Error`](wgt::Dx12AgilitySDKLoadFailure::Error): returns an `Err`.
|
||||
pub(super) fn new(
|
||||
lib: &D3D12Lib,
|
||||
agility_sdk: Option<&wgt::Dx12AgilitySDK>,
|
||||
) -> Result<Self, crate::InstanceError> {
|
||||
let Some(agility_sdk) = agility_sdk else {
|
||||
log::debug!("No D3D12 Agility SDK configuration provided; using system D3D12 runtime");
|
||||
return Ok(Self::Legacy);
|
||||
};
|
||||
|
||||
match Self::try_create_independent(lib, agility_sdk) {
|
||||
Ok(factory) => {
|
||||
log::debug!(
|
||||
"Using D3D12 Agility SDK v{} from '{}'",
|
||||
agility_sdk.sdk_version,
|
||||
agility_sdk.sdk_path
|
||||
);
|
||||
Ok(Self::Independent(factory))
|
||||
}
|
||||
Err(err) => {
|
||||
let message = format!(
|
||||
"Failed to initialize D3D12 Agility SDK (v{} at '{}'): {err}",
|
||||
agility_sdk.sdk_version, agility_sdk.sdk_path
|
||||
);
|
||||
|
||||
match agility_sdk.on_load_failure {
|
||||
wgt::Dx12AgilitySDKLoadFailure::Fallback => {
|
||||
log::warn!("{message}; falling back to system D3D12 runtime");
|
||||
Ok(Self::Legacy)
|
||||
}
|
||||
wgt::Dx12AgilitySDKLoadFailure::Error => {
|
||||
Err(crate::InstanceError::new(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_create_independent(
|
||||
lib: &D3D12Lib,
|
||||
agility_sdk: &wgt::Dx12AgilitySDK,
|
||||
) -> Result<Direct3D12::ID3D12DeviceFactory, DeviceFactoryError> {
|
||||
// Step 1: Get ID3D12SDKConfiguration1 via D3D12GetInterface
|
||||
let sdk_config: Direct3D12::ID3D12SDKConfiguration1 = lib
|
||||
.get_interface(&Direct3D12::CLSID_D3D12SDKConfiguration)
|
||||
.map_err(DeviceFactoryError::GetInterface)?;
|
||||
|
||||
// Step 2: Create device factory with the specified SDK version and path
|
||||
let sdk_path = std::ffi::CString::new(agility_sdk.sdk_path.as_bytes())
|
||||
.map_err(|_| DeviceFactoryError::InvalidPath)?;
|
||||
let factory: Direct3D12::ID3D12DeviceFactory = unsafe {
|
||||
sdk_config.CreateDeviceFactory(
|
||||
agility_sdk.sdk_version,
|
||||
windows::core::PCSTR(sdk_path.as_ptr().cast::<u8>()),
|
||||
)
|
||||
}
|
||||
.map_err(DeviceFactoryError::CreateDeviceFactory)?;
|
||||
|
||||
Ok(factory)
|
||||
}
|
||||
|
||||
/// Enable the D3D12 debug layer and optionally GPU-based validation.
|
||||
///
|
||||
/// - **Legacy**: configures debug globally via `D3D12GetDebugInterface`.
|
||||
/// - **Independent**: uses `GetConfigurationInterface` to get an
|
||||
/// `ID3D12Debug` scoped to the factory.
|
||||
pub(super) fn enable_debug_layer(&self, lib: &D3D12Lib, flags: wgt::InstanceFlags) {
|
||||
if !flags
|
||||
.intersects(wgt::InstanceFlags::VALIDATION | wgt::InstanceFlags::GPU_BASED_VALIDATION)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let debug_controller = match self {
|
||||
Self::Independent(factory) => {
|
||||
match unsafe {
|
||||
factory.GetConfigurationInterface::<Direct3D12::ID3D12Debug>(
|
||||
&Direct3D12::CLSID_D3D12Debug,
|
||||
)
|
||||
} {
|
||||
Ok(debug) => debug,
|
||||
Err(err) => {
|
||||
log::warn!("Failed to get debug interface from device factory: {err}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::Legacy => match lib.debug_interface() {
|
||||
Ok(Some(debug)) => debug,
|
||||
Ok(None) => return,
|
||||
Err(err) => {
|
||||
log::warn!("Failed to get debug interface: {err}");
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if flags.intersects(wgt::InstanceFlags::VALIDATION) {
|
||||
unsafe { debug_controller.EnableDebugLayer() }
|
||||
}
|
||||
if flags.intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION) {
|
||||
if let Ok(debug1) = debug_controller.cast::<Direct3D12::ID3D12Debug1>() {
|
||||
unsafe { debug1.SetEnableGPUBasedValidation(true) }
|
||||
} else {
|
||||
log::warn!("Failed to enable GPU-based validation");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a D3D12 device using the appropriate method.
|
||||
pub(super) fn create_device(
|
||||
&self,
|
||||
lib: &Arc<D3D12Lib>,
|
||||
adapter: &DxgiAdapter,
|
||||
feature_level: Direct3D::D3D_FEATURE_LEVEL,
|
||||
) -> Result<Direct3D12::ID3D12Device, super::CreateDeviceError> {
|
||||
match self {
|
||||
Self::Independent(factory) => {
|
||||
let mut result__: Option<Direct3D12::ID3D12Device> = None;
|
||||
unsafe { factory.CreateDevice(adapter.deref(), feature_level, &mut result__) }
|
||||
.map_err(|e| super::CreateDeviceError::D3D12CreateDevice(e.into()))?;
|
||||
|
||||
result__.ok_or(super::CreateDeviceError::RetDeviceIsNull)
|
||||
}
|
||||
Self::Legacy => lib.create_device(adapter, feature_level),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for DeviceFactory {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::Independent(_) => write!(f, "DeviceFactory::Independent"),
|
||||
Self::Legacy => write!(f, "DeviceFactory::Legacy"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum DeviceFactoryError {
|
||||
#[error("failed to get ID3D12SDKConfiguration1: {0}")]
|
||||
GetInterface(super::GetInterfaceError),
|
||||
#[error("SDK path contains null bytes")]
|
||||
InvalidPath,
|
||||
#[error("CreateDeviceFactory failed: {0}")]
|
||||
CreateDeviceFactory(windows::core::Error),
|
||||
}
|
||||
Vendored
+189
@@ -0,0 +1,189 @@
|
||||
use alloc::{string::String, sync::Arc, vec::Vec};
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use windows::Win32::{Foundation, Graphics::Dxgi};
|
||||
|
||||
use super::SurfaceTarget;
|
||||
use crate::{
|
||||
auxil,
|
||||
dx12::{
|
||||
device_creation::DeviceFactory, shader_compilation::CompilerContainer, D3D12Lib, DCompLib,
|
||||
},
|
||||
};
|
||||
|
||||
impl crate::Instance for super::Instance {
|
||||
type A = super::Api;
|
||||
|
||||
unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
|
||||
profiling::scope!("Init DX12 Backend");
|
||||
let lib_main = D3D12Lib::new().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("failed to load d3d12.dll"), e)
|
||||
})?;
|
||||
|
||||
// Create DeviceFactory first so we know which debug path to use
|
||||
let device_factory =
|
||||
DeviceFactory::new(&lib_main, desc.backend_options.dx12.agility_sdk.as_ref())?;
|
||||
|
||||
device_factory.enable_debug_layer(&lib_main, desc.flags);
|
||||
|
||||
let (lib_dxgi, factory) = auxil::dxgi::factory::create_factory(desc.flags)?;
|
||||
|
||||
// Create IDXGIFactoryMedia
|
||||
let factory_media = lib_dxgi.create_factory_media().ok();
|
||||
|
||||
let mut supports_allow_tearing = false;
|
||||
if let Some(factory5) = factory.as_factory5() {
|
||||
let mut allow_tearing = Foundation::FALSE;
|
||||
let hr = unsafe {
|
||||
factory5.CheckFeatureSupport(
|
||||
Dxgi::DXGI_FEATURE_PRESENT_ALLOW_TEARING,
|
||||
<*mut _>::cast(&mut allow_tearing),
|
||||
size_of_val(&allow_tearing) as u32,
|
||||
)
|
||||
};
|
||||
|
||||
match hr {
|
||||
Err(err) => log::warn!("Unable to check for tearing support: {err}"),
|
||||
Ok(()) => supports_allow_tearing = true,
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the shader compiler
|
||||
let compiler_container = match desc.backend_options.dx12.shader_compiler.clone() {
|
||||
wgt::Dx12Compiler::DynamicDxc { dxc_path } => {
|
||||
CompilerContainer::new_dynamic_dxc(dxc_path.into()).map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load dynamic DXC"), e)
|
||||
})?
|
||||
}
|
||||
wgt::Dx12Compiler::StaticDxc => CompilerContainer::new_static_dxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load static DXC"), e)
|
||||
})?,
|
||||
wgt::Dx12Compiler::Fxc => CompilerContainer::new_fxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load FXC"), e)
|
||||
})?,
|
||||
wgt::Dx12Compiler::Auto => {
|
||||
if cfg!(static_dxc) {
|
||||
// Prefer static DXC if its compiled in
|
||||
CompilerContainer::new_static_dxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(
|
||||
String::from("Failed to load static DXC"),
|
||||
e,
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
// Try to load dynamic DXC
|
||||
let dynamic = CompilerContainer::new_dynamic_dxc("dxcompiler.dll".into());
|
||||
match dynamic {
|
||||
Ok(v) => v,
|
||||
Err(super::shader_compilation::GetContainerError::FailedToLoad(..)) => {
|
||||
// If it can't be found load FXC
|
||||
CompilerContainer::new_fxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(
|
||||
String::from("Failed to load FXC"),
|
||||
e,
|
||||
)
|
||||
})?
|
||||
}
|
||||
Err(e) => {
|
||||
// If another error occurs when loading static DXC return that error
|
||||
return Err(crate::InstanceError::with_source(
|
||||
String::from("Failed to load dynamic DXC"),
|
||||
e,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match compiler_container {
|
||||
CompilerContainer::DynamicDxc(..) => {
|
||||
log::debug!("Using dynamic DXC for shader compilation")
|
||||
}
|
||||
CompilerContainer::StaticDxc(..) => {
|
||||
log::debug!("Using static DXC for shader compilation")
|
||||
}
|
||||
CompilerContainer::Fxc(..) => {
|
||||
log::debug!("Using FXC for shader compilation")
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
// The call to create_factory will only succeed if we get a factory4, so this is safe.
|
||||
factory,
|
||||
factory_media,
|
||||
library: Arc::new(lib_main),
|
||||
device_factory: Arc::new(device_factory),
|
||||
dcomp_lib: Arc::new(DCompLib::new()),
|
||||
presentation_system: desc.backend_options.dx12.presentation_system,
|
||||
_lib_dxgi: lib_dxgi,
|
||||
supports_allow_tearing,
|
||||
flags: desc.flags,
|
||||
memory_budget_thresholds: desc.memory_budget_thresholds,
|
||||
compiler_container: Arc::new(compiler_container),
|
||||
options: desc.backend_options.dx12.clone(),
|
||||
telemetry: desc.telemetry,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn create_surface(
|
||||
&self,
|
||||
display_handle: raw_window_handle::RawDisplayHandle,
|
||||
window_handle: raw_window_handle::RawWindowHandle,
|
||||
) -> Result<super::Surface, crate::InstanceError> {
|
||||
assert!(matches!(
|
||||
display_handle,
|
||||
raw_window_handle::RawDisplayHandle::Windows(_)
|
||||
));
|
||||
match window_handle {
|
||||
raw_window_handle::RawWindowHandle::Win32(handle) => {
|
||||
// https://github.com/rust-windowing/raw-window-handle/issues/171
|
||||
let handle = Foundation::HWND(handle.hwnd.get() as *mut _);
|
||||
let target = match self.presentation_system {
|
||||
wgt::Dx12SwapchainKind::DxgiFromHwnd => SurfaceTarget::WndHandle(handle),
|
||||
wgt::Dx12SwapchainKind::DxgiFromVisual => SurfaceTarget::VisualFromWndHandle {
|
||||
handle,
|
||||
dcomp_state: Default::default(),
|
||||
},
|
||||
};
|
||||
|
||||
Ok(super::Surface {
|
||||
factory: self.factory.clone(),
|
||||
factory_media: self.factory_media.clone(),
|
||||
target,
|
||||
supports_allow_tearing: self.supports_allow_tearing,
|
||||
swap_chain: RwLock::new(None),
|
||||
options: self.options.clone(),
|
||||
hdr_source: Some(auxil::dxgi::hdr::DxgiHdrSource::new(handle)),
|
||||
})
|
||||
}
|
||||
_ => Err(crate::InstanceError::new(format!(
|
||||
"window handle {window_handle:?} is not a Win32 handle"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn enumerate_adapters(
|
||||
&self,
|
||||
_surface_hint: Option<&super::Surface>,
|
||||
) -> Vec<crate::ExposedAdapter<super::Api>> {
|
||||
let adapters = auxil::dxgi::factory::enumerate_adapters(self.factory.clone());
|
||||
|
||||
adapters
|
||||
.into_iter()
|
||||
.filter_map(|raw| {
|
||||
super::Adapter::expose(
|
||||
raw,
|
||||
&self.library,
|
||||
&self.device_factory,
|
||||
&self.dcomp_lib,
|
||||
self.flags,
|
||||
self.memory_budget_thresholds,
|
||||
self.compiler_container.clone(),
|
||||
self.options.clone(),
|
||||
self.telemetry,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
Vendored
+1908
File diff suppressed because it is too large
Load Diff
+344
@@ -0,0 +1,344 @@
|
||||
//! We try to use pipeline stream descriptors where possible, but this isn't allowed
|
||||
//! on some older windows 10 versions. Therefore, we also must have some logic to
|
||||
//! convert such descriptors to the "traditional" equivalent,
|
||||
//! `D3D12_GRAPHICS_PIPELINE_STATE_DESC`.
|
||||
//!
|
||||
//! Stream descriptors allow extending the pipeline, enabling more advanced features,
|
||||
//! including mesh shaders and multiview/view instancing. Using a stream descriptor
|
||||
//! is like using a vulkan descriptor with a `pNext` chain. It doesn't have direct
|
||||
//! benefits to all use cases, but allows new use cases.
|
||||
//!
|
||||
//! The code for pipeline stream descriptors is very complicated, and can have bad
|
||||
//! consequences if it is written incorrectly. It has been isolated to this file for
|
||||
//! that reason.
|
||||
|
||||
use core::{ffi::c_void, mem::ManuallyDrop, ptr::NonNull};
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows_core::Interface;
|
||||
|
||||
use crate::dx12::borrow_interface_temporarily;
|
||||
|
||||
// Wrapper newtypes for various pipeline subobjects which
|
||||
// use complicated or non-unique representations.
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
// Option<NonNull<c_void>> is guaranteed to have the same representation as a raw pointer.
|
||||
struct RootSignature(Option<NonNull<c_void>>);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct VertexShader(D3D12_SHADER_BYTECODE);
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct PixelShader(D3D12_SHADER_BYTECODE);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct MeshShader(D3D12_SHADER_BYTECODE);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct TaskShader(D3D12_SHADER_BYTECODE);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct SampleMask(u32);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct NodeMask(u32);
|
||||
|
||||
/// Trait for types that can be used as subobjects in a pipeline state stream.
|
||||
///
|
||||
/// Safety:
|
||||
/// - The type must be the correct alignment and size for the subobject it represents.
|
||||
/// - The type must map to exactly one `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE` variant.
|
||||
/// - The variant must correctly represent the type's role in the pipeline state stream.
|
||||
/// - The type must be `Copy` to ensure safe duplication in the stream.
|
||||
/// - The type must be valid to memcpy into the pipeline state stream.
|
||||
unsafe trait RenderPipelineStreamObject: Copy {
|
||||
const SUBOBJECT_TYPE: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE;
|
||||
}
|
||||
|
||||
macro_rules! implement_stream_object {
|
||||
(unsafe $ty:ty => $variant:expr) => {
|
||||
unsafe impl RenderPipelineStreamObject for $ty {
|
||||
const SUBOBJECT_TYPE: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE = $variant;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
implement_stream_object! { unsafe RootSignature => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE }
|
||||
implement_stream_object! { unsafe VertexShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS }
|
||||
implement_stream_object! { unsafe PixelShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS }
|
||||
implement_stream_object! { unsafe MeshShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS }
|
||||
implement_stream_object! { unsafe TaskShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS }
|
||||
implement_stream_object! { unsafe D3D12_BLEND_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND }
|
||||
implement_stream_object! { unsafe SampleMask => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK }
|
||||
implement_stream_object! { unsafe D3D12_RASTERIZER_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER }
|
||||
implement_stream_object! { unsafe D3D12_DEPTH_STENCIL_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL }
|
||||
implement_stream_object! { unsafe D3D12_PRIMITIVE_TOPOLOGY_TYPE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY }
|
||||
implement_stream_object! { unsafe D3D12_RT_FORMAT_ARRAY => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS }
|
||||
implement_stream_object! { unsafe DXGI_FORMAT => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT }
|
||||
implement_stream_object! { unsafe DXGI_SAMPLE_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC }
|
||||
implement_stream_object! { unsafe NodeMask => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK }
|
||||
implement_stream_object! { unsafe D3D12_CACHED_PIPELINE_STATE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO }
|
||||
implement_stream_object! { unsafe D3D12_PIPELINE_STATE_FLAGS => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS }
|
||||
implement_stream_object! { unsafe D3D12_INPUT_LAYOUT_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT }
|
||||
implement_stream_object! { unsafe D3D12_INDEX_BUFFER_STRIP_CUT_VALUE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE }
|
||||
implement_stream_object! { unsafe D3D12_STREAM_OUTPUT_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT }
|
||||
implement_stream_object! { unsafe D3D12_VIEW_INSTANCING_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING }
|
||||
|
||||
/// Implementaation of a pipeline state stream, which is a sequence of subobjects put into
|
||||
/// a byte array according to some basic alignment rules.
|
||||
///
|
||||
/// Each subobject must start on an 8 byte boundary. Each subobject contains a 32 bit
|
||||
/// type identifier, followed by the actual subobject data, aligned as required by the
|
||||
/// subobject's structure.
|
||||
///
|
||||
/// See <https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_pipeline_state_stream_desc>
|
||||
/// for more information.
|
||||
pub(super) struct RenderPipelineStateStream<'a> {
|
||||
bytes: Vec<u8>,
|
||||
_marker: core::marker::PhantomData<&'a ()>,
|
||||
}
|
||||
|
||||
impl<'a> RenderPipelineStateStream<'a> {
|
||||
fn new() -> Self {
|
||||
// Dynamic allocation is used here because the resulting stream can become very large.
|
||||
// We pre-allocate the size based on an estimate of the size of the struct plus some extra space
|
||||
// per member for tags and alignment padding. In practice this will always be too big, as not
|
||||
// all members will be used.
|
||||
let size_of_stream_desc = size_of::<RenderPipelineStateStreamDesc>();
|
||||
let members = 20; // Approximate number of members we might push
|
||||
let capacity = size_of_stream_desc + members * 8; // Extra space for tags and alignment
|
||||
Self {
|
||||
bytes: Vec::with_capacity(capacity),
|
||||
_marker: core::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Align the internal byte buffer to the given alignment,
|
||||
/// padding with zeros as necessary.
|
||||
fn align_to(&mut self, alignment: usize) {
|
||||
let aligned_length = self.bytes.len().next_multiple_of(alignment);
|
||||
self.bytes.resize(aligned_length, 0);
|
||||
}
|
||||
|
||||
/// Adds a subobject to the pipeline state stream.
|
||||
fn add_object<T: RenderPipelineStreamObject>(&mut self, object: T) {
|
||||
// Ensure 8-byte alignment for the subobject start.
|
||||
self.align_to(8);
|
||||
|
||||
// Append the type tag (u32)
|
||||
let tag: u32 = T::SUBOBJECT_TYPE.0 as u32;
|
||||
self.bytes.extend_from_slice(&tag.to_ne_bytes());
|
||||
|
||||
// Align the data to its natural alignment.
|
||||
self.align_to(align_of_val::<T>(&object));
|
||||
|
||||
// Append the data itself, as raw bytes
|
||||
let data_ptr: *const T = &object;
|
||||
let data_u8_ptr: *const u8 = data_ptr.cast::<u8>();
|
||||
let data_size = size_of_val::<T>(&object);
|
||||
let slice = unsafe { core::slice::from_raw_parts::<u8>(data_u8_ptr, data_size) };
|
||||
self.bytes.extend_from_slice(slice);
|
||||
}
|
||||
|
||||
/// Creates a pipeline state object from the stream.
|
||||
///
|
||||
/// Safety:
|
||||
/// - All unsafety invariants required by [`ID3D12Device2::CreatePipelineState`] must be upheld by the caller.
|
||||
pub unsafe fn create_pipeline_state(
|
||||
&mut self,
|
||||
device: &ID3D12Device2,
|
||||
) -> windows::core::Result<ID3D12PipelineState> {
|
||||
let stream_desc = D3D12_PIPELINE_STATE_STREAM_DESC {
|
||||
SizeInBytes: self.bytes.len(),
|
||||
pPipelineStateSubobjectStream: self.bytes.as_mut_ptr().cast(),
|
||||
};
|
||||
|
||||
// Safety: lifetime on Self preserved the contents
|
||||
// of the stream. Other unsafety invariants are upheld by the caller.
|
||||
unsafe { device.CreatePipelineState(&stream_desc) }
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct RenderPipelineStateStreamDesc<'a> {
|
||||
pub root_signature: Option<&'a ID3D12RootSignature>,
|
||||
pub pixel_shader: D3D12_SHADER_BYTECODE,
|
||||
pub blend_state: D3D12_BLEND_DESC,
|
||||
pub sample_mask: u32,
|
||||
pub rasterizer_state: D3D12_RASTERIZER_DESC,
|
||||
pub depth_stencil_state: D3D12_DEPTH_STENCIL_DESC,
|
||||
pub primitive_topology_type: D3D12_PRIMITIVE_TOPOLOGY_TYPE,
|
||||
pub rtv_formats: D3D12_RT_FORMAT_ARRAY,
|
||||
pub dsv_format: DXGI_FORMAT,
|
||||
pub sample_desc: DXGI_SAMPLE_DESC,
|
||||
pub node_mask: u32,
|
||||
pub cached_pso: D3D12_CACHED_PIPELINE_STATE,
|
||||
pub flags: D3D12_PIPELINE_STATE_FLAGS,
|
||||
pub view_instancing: Option<D3D12_VIEW_INSTANCING_DESC>,
|
||||
|
||||
// Vertex pipeline specific
|
||||
pub vertex_shader: D3D12_SHADER_BYTECODE,
|
||||
pub input_layout: D3D12_INPUT_LAYOUT_DESC,
|
||||
pub index_buffer_strip_cut_value: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
|
||||
pub stream_output: D3D12_STREAM_OUTPUT_DESC,
|
||||
|
||||
// Mesh pipeline specific
|
||||
pub task_shader: D3D12_SHADER_BYTECODE,
|
||||
pub mesh_shader: D3D12_SHADER_BYTECODE,
|
||||
}
|
||||
|
||||
impl RenderPipelineStateStreamDesc<'_> {
|
||||
pub fn to_stream(&self) -> RenderPipelineStateStream<'_> {
|
||||
let mut stream = RenderPipelineStateStream::new();
|
||||
|
||||
// Importantly here, the ID3D12RootSignature _itself_ is the pointer we're
|
||||
// trying to serialize into the stream, not a pointer to the pointer.
|
||||
//
|
||||
// This is correct because as_raw() returns turns that smart object into the raw
|
||||
// pointer that _is_ the com object handle.
|
||||
let root_sig_pointer = self
|
||||
.root_signature
|
||||
.map(|a| NonNull::new(a.as_raw()).unwrap());
|
||||
// Because the stream object borrows from self for its entire lifetime,
|
||||
// it is safe to store the pointer into it.
|
||||
stream.add_object(RootSignature(root_sig_pointer));
|
||||
|
||||
stream.add_object(self.blend_state);
|
||||
stream.add_object(SampleMask(self.sample_mask));
|
||||
stream.add_object(self.rasterizer_state);
|
||||
stream.add_object(self.depth_stencil_state);
|
||||
stream.add_object(self.primitive_topology_type);
|
||||
if self.rtv_formats.NumRenderTargets != 0 {
|
||||
stream.add_object(self.rtv_formats);
|
||||
}
|
||||
if self.dsv_format != DXGI_FORMAT_UNKNOWN {
|
||||
stream.add_object(self.dsv_format);
|
||||
}
|
||||
stream.add_object(self.sample_desc);
|
||||
if self.node_mask != 0 {
|
||||
stream.add_object(NodeMask(self.node_mask));
|
||||
}
|
||||
if !self.cached_pso.pCachedBlob.is_null() {
|
||||
stream.add_object(self.cached_pso);
|
||||
}
|
||||
stream.add_object(self.flags);
|
||||
if let Some(view_instancing) = self.view_instancing {
|
||||
stream.add_object(view_instancing);
|
||||
}
|
||||
if !self.pixel_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(PixelShader(self.pixel_shader));
|
||||
}
|
||||
if !self.vertex_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(VertexShader(self.vertex_shader));
|
||||
stream.add_object(self.input_layout);
|
||||
stream.add_object(self.index_buffer_strip_cut_value);
|
||||
stream.add_object(self.stream_output);
|
||||
}
|
||||
if !self.task_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(TaskShader(self.task_shader));
|
||||
}
|
||||
if !self.mesh_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(MeshShader(self.mesh_shader));
|
||||
}
|
||||
|
||||
stream
|
||||
}
|
||||
|
||||
/// Returns a traditional D3D12_GRAPHICS_PIPELINE_STATE_DESC.
|
||||
///
|
||||
/// Safety:
|
||||
/// - This returned struct must not outlive self.
|
||||
pub unsafe fn to_graphics_pipeline_descriptor(&self) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
pRootSignature: if let Some(rsig) = self.root_signature {
|
||||
unsafe { borrow_interface_temporarily(rsig) }
|
||||
} else {
|
||||
ManuallyDrop::new(None)
|
||||
},
|
||||
VS: self.vertex_shader,
|
||||
PS: self.pixel_shader,
|
||||
DS: D3D12_SHADER_BYTECODE::default(),
|
||||
HS: D3D12_SHADER_BYTECODE::default(),
|
||||
GS: D3D12_SHADER_BYTECODE::default(),
|
||||
StreamOutput: self.stream_output,
|
||||
BlendState: self.blend_state,
|
||||
SampleMask: self.sample_mask,
|
||||
RasterizerState: self.rasterizer_state,
|
||||
DepthStencilState: self.depth_stencil_state,
|
||||
InputLayout: self.input_layout,
|
||||
IBStripCutValue: self.index_buffer_strip_cut_value,
|
||||
PrimitiveTopologyType: self.primitive_topology_type,
|
||||
NumRenderTargets: self.rtv_formats.NumRenderTargets,
|
||||
RTVFormats: self.rtv_formats.RTFormats,
|
||||
DSVFormat: self.dsv_format,
|
||||
SampleDesc: self.sample_desc,
|
||||
NodeMask: self.node_mask,
|
||||
CachedPSO: self.cached_pso,
|
||||
Flags: self.flags,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wrappers() {
|
||||
assert_eq!(size_of::<RootSignature>(), size_of::<ID3D12RootSignature>());
|
||||
assert_eq!(
|
||||
align_of::<RootSignature>(),
|
||||
align_of::<ID3D12RootSignature>()
|
||||
)
|
||||
}
|
||||
|
||||
implement_stream_object!(unsafe u16 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(1));
|
||||
implement_stream_object!(unsafe u32 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(2));
|
||||
implement_stream_object!(unsafe u64 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(3));
|
||||
|
||||
#[test]
|
||||
fn stream() {
|
||||
let mut stream = RenderPipelineStateStream::new();
|
||||
|
||||
stream.add_object(42u16);
|
||||
stream.add_object(84u32);
|
||||
stream.add_object(168u64);
|
||||
|
||||
assert_eq!(stream.bytes.len(), 32);
|
||||
|
||||
// Object 1: u16
|
||||
|
||||
// Tag at the beginning
|
||||
assert_eq!(&stream.bytes[0..4], &1u32.to_ne_bytes());
|
||||
// Data tucked in, aligned to the natural alignment of u16
|
||||
assert_eq!(&stream.bytes[4..6], &42u16.to_ne_bytes());
|
||||
// Padding to align the next subobject to an 8 byte boundary.
|
||||
assert_eq!(&stream.bytes[6..8], &[0, 0]);
|
||||
|
||||
// Object 2: u32
|
||||
|
||||
// Tag at the beginning
|
||||
assert_eq!(&stream.bytes[8..12], &2u32.to_ne_bytes());
|
||||
// Data tucked in, aligned to the natural alignment of u32
|
||||
assert_eq!(&stream.bytes[12..16], &84u32.to_ne_bytes());
|
||||
|
||||
// Object 3: u64
|
||||
|
||||
// Tag at the beginning
|
||||
assert_eq!(&stream.bytes[16..20], &3u32.to_ne_bytes());
|
||||
// Padding to align the u64 to an 8 byte boundary.
|
||||
assert_eq!(&stream.bytes[20..24], &[0, 0, 0, 0]);
|
||||
// Data tucked in, aligned to the natural alignment of u64
|
||||
assert_eq!(&stream.bytes[24..32], &168u64.to_ne_bytes());
|
||||
}
|
||||
}
|
||||
Vendored
+252
@@ -0,0 +1,252 @@
|
||||
//! Sampler management for DX12.
|
||||
//!
|
||||
//! Nearly identical to the Vulkan sampler cache, with added descriptor heap management.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use hashbrown::{hash_map::Entry, HashMap};
|
||||
|
||||
use ordered_float::OrderedFloat;
|
||||
use parking_lot::Mutex;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use crate::dx12::HResult;
|
||||
|
||||
/// The index of a sampler in the global sampler heap.
|
||||
///
|
||||
/// This is a type-safe, transparent wrapper around a u32.
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct SamplerIndex(u32);
|
||||
|
||||
/// [`D3D12_SAMPLER_DESC`] is not hashable, so we wrap it in a newtype that is.
|
||||
///
|
||||
/// We use [`OrderedFloat`] to allow for floating point values to be compared and
|
||||
/// hashed in a defined way.
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
struct HashableSamplerDesc(D3D12_SAMPLER_DESC);
|
||||
|
||||
impl PartialEq for HashableSamplerDesc {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.Filter == other.0.Filter
|
||||
&& self.0.AddressU == other.0.AddressU
|
||||
&& self.0.AddressV == other.0.AddressV
|
||||
&& self.0.AddressW == other.0.AddressW
|
||||
&& OrderedFloat(self.0.MipLODBias) == OrderedFloat(other.0.MipLODBias)
|
||||
&& self.0.MaxAnisotropy == other.0.MaxAnisotropy
|
||||
&& self.0.ComparisonFunc == other.0.ComparisonFunc
|
||||
&& self.0.BorderColor.map(OrderedFloat) == other.0.BorderColor.map(OrderedFloat)
|
||||
&& OrderedFloat(self.0.MinLOD) == OrderedFloat(other.0.MinLOD)
|
||||
&& OrderedFloat(self.0.MaxLOD) == OrderedFloat(other.0.MaxLOD)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for HashableSamplerDesc {}
|
||||
|
||||
impl core::hash::Hash for HashableSamplerDesc {
|
||||
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.Filter.0.hash(state);
|
||||
self.0.AddressU.0.hash(state);
|
||||
self.0.AddressV.0.hash(state);
|
||||
self.0.AddressW.0.hash(state);
|
||||
OrderedFloat(self.0.MipLODBias).hash(state);
|
||||
self.0.MaxAnisotropy.hash(state);
|
||||
self.0.ComparisonFunc.0.hash(state);
|
||||
self.0.BorderColor.map(OrderedFloat).hash(state);
|
||||
OrderedFloat(self.0.MinLOD).hash(state);
|
||||
OrderedFloat(self.0.MaxLOD).hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry in the sampler cache.
|
||||
struct CacheEntry {
|
||||
index: SamplerIndex,
|
||||
ref_count: u32,
|
||||
}
|
||||
|
||||
/// Container for the mutable management state of the sampler heap.
|
||||
///
|
||||
/// We have this separated, using interior mutability, to allow for the outside world
|
||||
/// to access the heap directly without needing to take the lock.
|
||||
pub(crate) struct SamplerHeapState {
|
||||
/// Mapping from the sampler description to the index within the heap and the refcount.
|
||||
mapping: HashMap<HashableSamplerDesc, CacheEntry>,
|
||||
/// List of free sampler indices.
|
||||
freelist: Vec<SamplerIndex>,
|
||||
}
|
||||
|
||||
/// Global sampler heap for the device.
|
||||
///
|
||||
/// As D3D12 only allows 2048 samplers to be in a single heap, we need to cache
|
||||
/// samplers aggressively and refer to them in shaders by index.
|
||||
pub(crate) struct SamplerHeap {
|
||||
/// Mutable management state of the sampler heap.
|
||||
state: Mutex<SamplerHeapState>,
|
||||
|
||||
/// The heap itself.
|
||||
heap: ID3D12DescriptorHeap,
|
||||
/// The CPU-side handle to the first descriptor in the heap.
|
||||
///
|
||||
/// Both the CPU and GPU handles point to the same descriptor, just in
|
||||
/// different contexts.
|
||||
heap_cpu_start_handle: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
/// The GPU-side handle to the first descriptor in the heap.
|
||||
///
|
||||
/// Both the CPU and GPU handles point to the same descriptor, just in
|
||||
/// different contexts.
|
||||
heap_gpu_start_handle: D3D12_GPU_DESCRIPTOR_HANDLE,
|
||||
|
||||
/// This is the device-specific size of sampler descriptors.
|
||||
descriptor_stride: u32,
|
||||
}
|
||||
|
||||
impl SamplerHeap {
|
||||
pub fn new(
|
||||
device: &ID3D12Device,
|
||||
private_caps: &super::PrivateCapabilities,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
profiling::scope!("SamplerHeap::new");
|
||||
|
||||
// WARP can report this as 2M or more. We clamp it to 64k to be safe.
|
||||
const SAMPLER_HEAP_SIZE_CLAMP: u32 = 64 * 1024;
|
||||
|
||||
let max_unique_samplers = private_caps
|
||||
.max_sampler_descriptor_heap_size
|
||||
.min(SAMPLER_HEAP_SIZE_CLAMP);
|
||||
|
||||
let desc = D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
|
||||
NumDescriptors: max_unique_samplers,
|
||||
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let heap = unsafe { device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Failed to create global GPU-Visible Sampler Descriptor Heap")?;
|
||||
|
||||
let heap_cpu_start_handle = unsafe { heap.GetCPUDescriptorHandleForHeapStart() };
|
||||
let heap_gpu_start_handle = unsafe { heap.GetGPUDescriptorHandleForHeapStart() };
|
||||
|
||||
let descriptor_stride =
|
||||
unsafe { device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) };
|
||||
|
||||
Ok(Self {
|
||||
state: Mutex::new(SamplerHeapState {
|
||||
mapping: HashMap::new(),
|
||||
// Reverse so that samplers get allocated starting from zero.
|
||||
freelist: (0..max_unique_samplers).map(SamplerIndex).rev().collect(),
|
||||
}),
|
||||
heap,
|
||||
heap_cpu_start_handle,
|
||||
heap_gpu_start_handle,
|
||||
descriptor_stride,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a reference to the raw descriptor heap.
|
||||
pub fn heap(&self) -> &ID3D12DescriptorHeap {
|
||||
&self.heap
|
||||
}
|
||||
|
||||
/// Returns a reference the handle to be bound to the descriptor table.
|
||||
pub fn gpu_descriptor_table(&self) -> D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
self.heap_gpu_start_handle
|
||||
}
|
||||
|
||||
/// Add a sampler with the given description to the heap.
|
||||
///
|
||||
/// If the sampler already exists, the refcount is incremented and the existing index is returned.
|
||||
///
|
||||
/// If the sampler does not exist, a new sampler is created and the index is returned.
|
||||
///
|
||||
/// If the heap is full, an error is returned.
|
||||
pub fn create_sampler(
|
||||
&self,
|
||||
device: &ID3D12Device,
|
||||
desc: D3D12_SAMPLER_DESC,
|
||||
) -> Result<SamplerIndex, crate::DeviceError> {
|
||||
profiling::scope!("SamplerHeap::create_sampler");
|
||||
|
||||
let hashable_desc = HashableSamplerDesc(desc);
|
||||
|
||||
// Eagarly dereference the lock to allow split borrows.
|
||||
let state = &mut *self.state.lock();
|
||||
|
||||
// Lookup the sampler in the mapping.
|
||||
match state.mapping.entry(hashable_desc) {
|
||||
Entry::Occupied(occupied_entry) => {
|
||||
// We have found a match, so increment the refcount and return the index.
|
||||
let entry = occupied_entry.into_mut();
|
||||
entry.ref_count += 1;
|
||||
Ok(entry.index)
|
||||
}
|
||||
Entry::Vacant(vacant_entry) => {
|
||||
// We need to create a new sampler.
|
||||
|
||||
// Try to get a new index from the freelist.
|
||||
let Some(index) = state.freelist.pop() else {
|
||||
// If the freelist is empty, we have hit the maximum number of samplers.
|
||||
log::error!("There is no more room in the global sampler heap for more unique samplers. Your device supports a maximum of {} unique samplers.", state.mapping.len());
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
};
|
||||
|
||||
// Compute the CPU side handle for the new sampler.
|
||||
let handle = D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.heap_cpu_start_handle.ptr
|
||||
+ self.descriptor_stride as usize * index.0 as usize,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
device.CreateSampler(&desc, handle);
|
||||
}
|
||||
|
||||
// Insert the new sampler into the mapping.
|
||||
vacant_entry.insert(CacheEntry {
|
||||
index,
|
||||
ref_count: 1,
|
||||
});
|
||||
|
||||
Ok(index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decrement the refcount of the sampler with the given description.
|
||||
///
|
||||
/// If the refcount reaches zero, the sampler is destroyed and the index is returned to the freelist.
|
||||
///
|
||||
/// The provided index is checked against the index of the sampler with the given description, ensuring
|
||||
/// that there isn't a clerical error from the caller.
|
||||
pub fn destroy_sampler(&self, desc: D3D12_SAMPLER_DESC, provided_index: SamplerIndex) {
|
||||
profiling::scope!("SamplerHeap::destroy_sampler");
|
||||
|
||||
// Eagarly dereference the lock to allow split borrows.
|
||||
let state = &mut *self.state.lock();
|
||||
|
||||
// Get the index of the sampler to destroy.
|
||||
let Entry::Occupied(mut hash_map_entry) = state.mapping.entry(HashableSamplerDesc(desc))
|
||||
else {
|
||||
log::error!(
|
||||
"Tried to destroy a sampler that doesn't exist. Sampler description: {desc:#?}"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let cache_entry = hash_map_entry.get_mut();
|
||||
|
||||
// Ensure that the provided index matches the index of the sampler to destroy.
|
||||
assert_eq!(
|
||||
cache_entry.index, provided_index,
|
||||
"Mismatched sampler index, this is an implementation bug"
|
||||
);
|
||||
|
||||
// Decrement the refcount of the sampler.
|
||||
cache_entry.ref_count -= 1;
|
||||
|
||||
// If we are the last reference, remove the sampler from the mapping and return the index to the freelist.
|
||||
//
|
||||
// As samplers only exist as descriptors in the heap, there is nothing needed to be done to destroy the sampler.
|
||||
if cache_entry.ref_count == 0 {
|
||||
state.freelist.push(cache_entry.index);
|
||||
hash_map_entry.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
+450
@@ -0,0 +1,450 @@
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use core::ffi::CStr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult;
|
||||
use thiserror::Error;
|
||||
use windows::{
|
||||
core::{Interface, PCSTR, PCWSTR},
|
||||
Win32::Graphics::Direct3D::{Dxc, Fxc, ID3DBlob, D3D_SHADER_MACRO},
|
||||
};
|
||||
|
||||
pub(super) enum CompilerContainer {
|
||||
Fxc(CompilerFxc),
|
||||
DynamicDxc(CompilerDynamicDxc),
|
||||
#[cfg_attr(not(static_dxc), allow(unused))]
|
||||
StaticDxc(CompilerStaticDxc),
|
||||
}
|
||||
|
||||
pub(super) struct CompilerFxc {
|
||||
fxc: FxcLib,
|
||||
}
|
||||
|
||||
pub(super) struct CompilerDynamicDxc {
|
||||
max_shader_model: wgt::DxcShaderModel,
|
||||
compiler: Dxc::IDxcCompiler3,
|
||||
// Has to be held onto for the lifetime of the device otherwise shaders will fail to compile.
|
||||
// Only needed when using dynamic linking.
|
||||
_dxc: DxcLib,
|
||||
}
|
||||
|
||||
pub(super) struct CompilerStaticDxc {
|
||||
max_shader_model: wgt::DxcShaderModel,
|
||||
compiler: Dxc::IDxcCompiler3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub(super) enum GetContainerError {
|
||||
#[error(transparent)]
|
||||
Device(#[from] crate::DeviceError),
|
||||
#[error("Failed to load {0}: {1}")]
|
||||
FailedToLoad(&'static str, libloading::Error),
|
||||
}
|
||||
|
||||
impl CompilerContainer {
|
||||
pub(super) fn new_fxc() -> Result<Self, GetContainerError> {
|
||||
FxcLib::new_dynamic().map(|fxc| Self::Fxc(CompilerFxc { fxc }))
|
||||
}
|
||||
|
||||
pub(super) fn new_dynamic_dxc(dxc_path: PathBuf) -> Result<Self, GetContainerError> {
|
||||
let dxc = DxcLib::new_dynamic(dxc_path)
|
||||
.map_err(|e| GetContainerError::FailedToLoad("dxcompiler.dll", e))?;
|
||||
|
||||
let compiler = dxc.create_instance::<Dxc::IDxcCompiler3>()?;
|
||||
|
||||
let (mut major, mut minor) = (1, 0);
|
||||
// DXC 1.0 didn't support this. If the cast fails assume it is DXC 1.0.
|
||||
if let Ok(version_info) = compiler.cast::<Dxc::IDxcVersionInfo>() {
|
||||
unsafe {
|
||||
version_info.GetVersion(&mut major, &mut minor).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self::DynamicDxc(CompilerDynamicDxc {
|
||||
max_shader_model: wgt::DxcShaderModel::from_dxc_version(major, minor),
|
||||
compiler,
|
||||
_dxc: dxc,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Creates a [`CompilerContainer`] that delegates to the statically-linked version of DXC.
|
||||
pub(super) fn new_static_dxc() -> Result<CompilerContainer, crate::DeviceError> {
|
||||
#[cfg(static_dxc)]
|
||||
{
|
||||
unsafe {
|
||||
let compiler = dxc_create_instance::<Dxc::IDxcCompiler3>(|clsid, iid, ppv| {
|
||||
windows_core::HRESULT(mach_dxcompiler_rs::DxcCreateInstance(
|
||||
clsid.cast(),
|
||||
iid.cast(),
|
||||
ppv,
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(CompilerContainer::StaticDxc(CompilerStaticDxc {
|
||||
max_shader_model: wgt::DxcShaderModel::V6_7,
|
||||
compiler,
|
||||
}))
|
||||
}
|
||||
}
|
||||
#[cfg(not(static_dxc))]
|
||||
{
|
||||
panic!("Attempted to create a static DXC shader compiler, but the static-dxc feature was not enabled")
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn max_shader_model(&self) -> Option<wgt::DxcShaderModel> {
|
||||
match self {
|
||||
CompilerContainer::Fxc(..) => None,
|
||||
CompilerContainer::DynamicDxc(CompilerDynamicDxc {
|
||||
max_shader_model, ..
|
||||
})
|
||||
| CompilerContainer::StaticDxc(CompilerStaticDxc {
|
||||
max_shader_model, ..
|
||||
}) => Some(max_shader_model.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn compile(
|
||||
&self,
|
||||
device: &super::Device,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
stage_bit: wgt::ShaderStages,
|
||||
full_stage: &str,
|
||||
) -> Result<super::CompiledShader, crate::PipelineError> {
|
||||
match self {
|
||||
CompilerContainer::Fxc(CompilerFxc { fxc }) => compile_fxc(
|
||||
device,
|
||||
source,
|
||||
source_name,
|
||||
raw_ep,
|
||||
stage_bit,
|
||||
full_stage,
|
||||
fxc,
|
||||
),
|
||||
CompilerContainer::DynamicDxc(CompilerDynamicDxc { compiler, .. })
|
||||
| CompilerContainer::StaticDxc(CompilerStaticDxc { compiler, .. }) => compile_dxc(
|
||||
device,
|
||||
source,
|
||||
source_name,
|
||||
raw_ep,
|
||||
stage_bit,
|
||||
full_stage,
|
||||
compiler,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type D3DCompileFn = unsafe extern "system" fn(
|
||||
psrcdata: *const core::ffi::c_void,
|
||||
srcdatasize: usize,
|
||||
psourcename: PCSTR,
|
||||
pdefines: *const D3D_SHADER_MACRO,
|
||||
pinclude: *mut core::ffi::c_void,
|
||||
pentrypoint: PCSTR,
|
||||
ptarget: PCSTR,
|
||||
flags1: u32,
|
||||
flags2: u32,
|
||||
ppcode: *mut *mut core::ffi::c_void,
|
||||
pperrormsgs: *mut *mut core::ffi::c_void,
|
||||
) -> windows_core::HRESULT;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FxcLib {
|
||||
// `d3dcompile_fn` points into `_lib`, so `_lib` must be held for as long
|
||||
// as we want to keep compiling shaders with FXC.
|
||||
_lib: crate::dx12::DynLib,
|
||||
d3dcompile_fn: D3DCompileFn,
|
||||
}
|
||||
|
||||
impl FxcLib {
|
||||
const PATH: &str = "d3dcompiler_47.dll";
|
||||
|
||||
fn new_dynamic() -> Result<Self, GetContainerError> {
|
||||
unsafe {
|
||||
let lib = crate::dx12::DynLib::new(Self::PATH)
|
||||
.map_err(|e| GetContainerError::FailedToLoad(FxcLib::PATH, e))?;
|
||||
let d3dcompile_fn: D3DCompileFn = *lib.get::<D3DCompileFn>(c"D3DCompile".to_bytes())?;
|
||||
|
||||
Ok(Self {
|
||||
_lib: lib,
|
||||
d3dcompile_fn,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn compile(
|
||||
&self,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
full_stage: &str,
|
||||
compile_flags: u32,
|
||||
shader_data: &mut Option<ID3DBlob>,
|
||||
error: &mut Option<ID3DBlob>,
|
||||
) -> Result<windows_core::Result<()>, crate::DeviceError> {
|
||||
unsafe {
|
||||
let raw_ep = alloc::ffi::CString::new(raw_ep).unwrap();
|
||||
let full_stage = alloc::ffi::CString::new(full_stage).unwrap();
|
||||
|
||||
// If no name has been set, D3DCompile wants the null pointer.
|
||||
let source_name = source_name
|
||||
.map(|cstr| cstr.as_ptr().cast())
|
||||
.unwrap_or(core::ptr::null());
|
||||
|
||||
let shader_data: *mut Option<ID3DBlob> = shader_data;
|
||||
let error: *mut Option<ID3DBlob> = error;
|
||||
|
||||
{
|
||||
profiling::scope!("Fxc::D3DCompile");
|
||||
Ok((self.d3dcompile_fn)(
|
||||
source.as_ptr().cast(),
|
||||
source.len(),
|
||||
PCSTR(source_name),
|
||||
core::ptr::null(),
|
||||
core::ptr::null_mut(),
|
||||
PCSTR(raw_ep.as_ptr().cast()),
|
||||
PCSTR(full_stage.as_ptr().cast()),
|
||||
compile_flags,
|
||||
0,
|
||||
shader_data.cast(),
|
||||
error.cast(),
|
||||
)
|
||||
.ok())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_fxc(
|
||||
device: &super::Device,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
stage_bit: wgt::ShaderStages,
|
||||
full_stage: &str,
|
||||
fxc: &FxcLib,
|
||||
) -> Result<super::CompiledShader, crate::PipelineError> {
|
||||
profiling::scope!("compile_fxc");
|
||||
let mut compile_flags = Fxc::D3DCOMPILE_ENABLE_STRICTNESS;
|
||||
if device
|
||||
.shared
|
||||
.private_caps
|
||||
.instance_flags
|
||||
.contains(wgt::InstanceFlags::DEBUG)
|
||||
{
|
||||
compile_flags |= Fxc::D3DCOMPILE_DEBUG | Fxc::D3DCOMPILE_SKIP_OPTIMIZATION;
|
||||
}
|
||||
|
||||
let mut shader_data = None;
|
||||
let mut error = None;
|
||||
let hr = fxc.compile(
|
||||
source,
|
||||
source_name,
|
||||
raw_ep,
|
||||
full_stage,
|
||||
compile_flags,
|
||||
&mut shader_data,
|
||||
&mut error,
|
||||
)?;
|
||||
|
||||
match hr {
|
||||
Ok(()) => {
|
||||
let shader_data = shader_data.unwrap();
|
||||
Ok(super::CompiledShader::Fxc(shader_data))
|
||||
}
|
||||
Err(e) => {
|
||||
let mut full_msg = format!("FXC D3DCompile error ({e})");
|
||||
if let Some(error) = error {
|
||||
use core::fmt::Write as _;
|
||||
let message = unsafe {
|
||||
core::slice::from_raw_parts(
|
||||
error.GetBufferPointer().cast(),
|
||||
error.GetBufferSize(),
|
||||
)
|
||||
};
|
||||
let _ = write!(full_msg, ": {}", String::from_utf8_lossy(message));
|
||||
}
|
||||
Err(crate::PipelineError::Linkage(stage_bit, full_msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait DxcObj: Interface {
|
||||
const CLSID: windows::core::GUID;
|
||||
}
|
||||
impl DxcObj for Dxc::IDxcCompiler3 {
|
||||
const CLSID: windows::core::GUID = Dxc::CLSID_DxcCompiler;
|
||||
}
|
||||
impl DxcObj for Dxc::IDxcUtils {
|
||||
const CLSID: windows::core::GUID = Dxc::CLSID_DxcUtils;
|
||||
}
|
||||
impl DxcObj for Dxc::IDxcValidator {
|
||||
const CLSID: windows::core::GUID = Dxc::CLSID_DxcValidator;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DxcLib {
|
||||
lib: crate::dx12::DynLib,
|
||||
}
|
||||
|
||||
impl DxcLib {
|
||||
fn new_dynamic(lib_path: PathBuf) -> Result<Self, libloading::Error> {
|
||||
unsafe { crate::dx12::DynLib::new(lib_path).map(|lib| Self { lib }) }
|
||||
}
|
||||
|
||||
pub fn create_instance<T: DxcObj>(&self) -> Result<T, crate::DeviceError> {
|
||||
unsafe {
|
||||
type DxcCreateInstanceFn = unsafe extern "system" fn(
|
||||
rclsid: *const windows_core::GUID,
|
||||
riid: *const windows_core::GUID,
|
||||
ppv: *mut *mut core::ffi::c_void,
|
||||
)
|
||||
-> windows_core::HRESULT;
|
||||
|
||||
let func: libloading::Symbol<DxcCreateInstanceFn> =
|
||||
self.lib.get(c"DxcCreateInstance".to_bytes())?;
|
||||
dxc_create_instance::<T>(|clsid, iid, ppv| func(clsid, iid, ppv))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Invokes the provided library function to create a DXC object.
|
||||
unsafe fn dxc_create_instance<T: DxcObj>(
|
||||
f: impl Fn(
|
||||
*const windows_core::GUID,
|
||||
*const windows_core::GUID,
|
||||
*mut *mut core::ffi::c_void,
|
||||
) -> windows_core::HRESULT,
|
||||
) -> Result<T, crate::DeviceError> {
|
||||
let mut result__ = None;
|
||||
f(&T::CLSID, &T::IID, <*mut _>::cast(&mut result__))
|
||||
.ok()
|
||||
.into_device_result("DxcCreateInstance")?;
|
||||
result__.ok_or(crate::DeviceError::Unexpected)
|
||||
}
|
||||
|
||||
/// Owned PCWSTR
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
struct OPCWSTR {
|
||||
inner: Vec<u16>,
|
||||
}
|
||||
|
||||
impl OPCWSTR {
|
||||
fn new(s: &str) -> Self {
|
||||
let mut inner: Vec<_> = s.encode_utf16().collect();
|
||||
inner.push(0);
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
fn ptr(&self) -> PCWSTR {
|
||||
PCWSTR(self.inner.as_ptr())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_output<T: Interface>(
|
||||
res: &Dxc::IDxcResult,
|
||||
kind: Dxc::DXC_OUT_KIND,
|
||||
) -> Result<T, crate::DeviceError> {
|
||||
let mut result__: Option<T> = None;
|
||||
unsafe { res.GetOutput::<T>(kind, &mut None, <*mut _>::cast(&mut result__)) }
|
||||
.into_device_result("GetOutput")?;
|
||||
result__.ok_or(crate::DeviceError::Unexpected)
|
||||
}
|
||||
|
||||
fn as_err_str(blob: &Dxc::IDxcBlobUtf8) -> Result<&str, crate::DeviceError> {
|
||||
let ptr = unsafe { blob.GetStringPointer() };
|
||||
let len = unsafe { blob.GetStringLength() };
|
||||
core::str::from_utf8(unsafe { core::slice::from_raw_parts(ptr.0, len) })
|
||||
.map_err(|_| crate::DeviceError::Unexpected)
|
||||
}
|
||||
|
||||
fn compile_dxc(
|
||||
device: &crate::dx12::Device,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
stage_bit: wgt::ShaderStages,
|
||||
full_stage: &str,
|
||||
compiler: &Dxc::IDxcCompiler3,
|
||||
) -> Result<crate::dx12::CompiledShader, crate::PipelineError> {
|
||||
profiling::scope!("compile_dxc");
|
||||
|
||||
let source_name = source_name.and_then(|cstr| cstr.to_str().ok());
|
||||
|
||||
let source_name = source_name.map(OPCWSTR::new);
|
||||
let raw_ep = OPCWSTR::new(raw_ep);
|
||||
let full_stage = OPCWSTR::new(full_stage);
|
||||
|
||||
let mut compile_args = arrayvec::ArrayVec::<PCWSTR, 13>::new_const();
|
||||
|
||||
if let Some(source_name) = source_name.as_ref() {
|
||||
compile_args.push(source_name.ptr())
|
||||
}
|
||||
|
||||
compile_args.extend([
|
||||
windows::core::w!("-E"),
|
||||
raw_ep.ptr(),
|
||||
windows::core::w!("-T"),
|
||||
full_stage.ptr(),
|
||||
windows::core::w!("-HV"),
|
||||
windows::core::w!("2018"), // Use HLSL 2018, Naga doesn't supported 2021 yet.
|
||||
windows::core::w!("-no-warnings"),
|
||||
Dxc::DXC_ARG_ENABLE_STRICTNESS,
|
||||
]);
|
||||
|
||||
if device
|
||||
.shared
|
||||
.private_caps
|
||||
.instance_flags
|
||||
.contains(wgt::InstanceFlags::DEBUG)
|
||||
&& !device
|
||||
.shared
|
||||
.private_caps
|
||||
.workarounds
|
||||
.avoid_shader_debug_info
|
||||
{
|
||||
compile_args.push(Dxc::DXC_ARG_DEBUG);
|
||||
compile_args.push(Dxc::DXC_ARG_SKIP_OPTIMIZATIONS);
|
||||
}
|
||||
|
||||
if device
|
||||
.features
|
||||
.intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16)
|
||||
{
|
||||
compile_args.push(windows::core::w!("-enable-16bit-types"));
|
||||
}
|
||||
|
||||
let buffer = Dxc::DxcBuffer {
|
||||
Ptr: source.as_ptr().cast(),
|
||||
Size: source.len(),
|
||||
Encoding: Dxc::DXC_CP_UTF8.0,
|
||||
};
|
||||
|
||||
let compile_res: Dxc::IDxcResult =
|
||||
unsafe { compiler.Compile(&buffer, Some(&compile_args), None) }
|
||||
.into_device_result("Compile")?;
|
||||
|
||||
drop(compile_args);
|
||||
drop(source_name);
|
||||
drop(raw_ep);
|
||||
drop(full_stage);
|
||||
|
||||
let err_blob = get_output::<Dxc::IDxcBlobUtf8>(&compile_res, Dxc::DXC_OUT_ERRORS)?;
|
||||
|
||||
let len = unsafe { err_blob.GetStringLength() };
|
||||
if len != 0 {
|
||||
let err = as_err_str(&err_blob)?;
|
||||
return Err(crate::PipelineError::Linkage(
|
||||
stage_bit,
|
||||
format!("DXC compile error: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
let blob = get_output::<Dxc::IDxcBlob>(&compile_res, Dxc::DXC_OUT_OBJECT)?;
|
||||
|
||||
Ok(crate::dx12::CompiledShader::Dxc(blob))
|
||||
}
|
||||
+603
@@ -0,0 +1,603 @@
|
||||
use alloc::sync::Arc;
|
||||
|
||||
use gpu_allocator::{d3d12::AllocationCreateDesc, MemoryLocation};
|
||||
use parking_lot::Mutex;
|
||||
use windows::Win32::Graphics::{Direct3D12, Dxgi};
|
||||
|
||||
use crate::{
|
||||
auxil::dxgi::{name::ObjectExt as _, result::HResult as _},
|
||||
dx12::conv,
|
||||
AllocationSizes,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AllocationType {
|
||||
Buffer,
|
||||
Texture,
|
||||
AccelerationStructure,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum AllocationInner {
|
||||
/// This resource is suballocated from a heap.
|
||||
Placed {
|
||||
inner: gpu_allocator::d3d12::Allocation,
|
||||
},
|
||||
/// This resource is a committed resource and does not belong to a
|
||||
/// suballocated heap. We store an approximate size, so we can manage our counters
|
||||
/// correctly.
|
||||
///
|
||||
/// This is only used for Intel Xe drivers, which have a bug that
|
||||
/// prevents suballocation from working correctly.
|
||||
Committed { size: u64 },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Allocation {
|
||||
inner: AllocationInner,
|
||||
ty: AllocationType,
|
||||
}
|
||||
|
||||
impl Allocation {
|
||||
pub fn placed(inner: gpu_allocator::d3d12::Allocation, ty: AllocationType) -> Self {
|
||||
Self {
|
||||
inner: AllocationInner::Placed { inner },
|
||||
ty,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn none(ty: AllocationType, size: u64) -> Self {
|
||||
Self {
|
||||
inner: AllocationInner::Committed { size },
|
||||
ty,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(&self) -> u64 {
|
||||
match self.inner {
|
||||
AllocationInner::Placed { ref inner } => inner.size(),
|
||||
AllocationInner::Committed { size } => size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Allocator {
|
||||
inner: Arc<Mutex<gpu_allocator::d3d12::Allocator>>,
|
||||
device_memblock_size: u64,
|
||||
host_memblock_size: u64,
|
||||
pub memory_budget_thresholds: wgt::MemoryBudgetThresholds,
|
||||
}
|
||||
|
||||
impl Allocator {
|
||||
pub(crate) fn new(
|
||||
raw: &Direct3D12::ID3D12Device,
|
||||
memory_hints: &wgt::MemoryHints,
|
||||
memory_budget_thresholds: wgt::MemoryBudgetThresholds,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let allocation_sizes = AllocationSizes::from_memory_hints(memory_hints);
|
||||
let device_memblock_size = allocation_sizes.min_device_memblock_size;
|
||||
let host_memblock_size = allocation_sizes.min_host_memblock_size;
|
||||
|
||||
let allocator_desc = gpu_allocator::d3d12::AllocatorCreateDesc {
|
||||
device: gpu_allocator::d3d12::ID3D12DeviceVersion::Device(raw.clone()),
|
||||
debug_settings: Default::default(),
|
||||
allocation_sizes: allocation_sizes.into(),
|
||||
};
|
||||
|
||||
let allocator = gpu_allocator::d3d12::Allocator::new(&allocator_desc).inspect_err(|e| {
|
||||
log::error!("Failed to create d3d12 allocator, error: {e}");
|
||||
})?;
|
||||
|
||||
Ok(Self {
|
||||
inner: Arc::new(Mutex::new(allocator)),
|
||||
device_memblock_size,
|
||||
host_memblock_size,
|
||||
memory_budget_thresholds,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn generate_report(&self) -> wgt::AllocatorReport {
|
||||
let mut upstream = self.inner.lock().generate_report();
|
||||
|
||||
let allocations = upstream
|
||||
.allocations
|
||||
.iter_mut()
|
||||
.map(|alloc| wgt::AllocationReport {
|
||||
name: core::mem::take(&mut alloc.name),
|
||||
offset: alloc.offset,
|
||||
size: alloc.size,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let blocks = upstream
|
||||
.blocks
|
||||
.iter()
|
||||
.map(|block| wgt::MemoryBlockReport {
|
||||
size: block.size,
|
||||
allocations: block.allocations.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
wgt::AllocatorReport {
|
||||
allocations,
|
||||
blocks,
|
||||
total_allocated_bytes: upstream.total_allocated_bytes,
|
||||
total_reserved_bytes: upstream.total_capacity_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// To allow us to construct buffers from both a `Device` and `CommandEncoder`
|
||||
/// without needing each function to take a million arguments, we create a
|
||||
/// borrowed context struct that contains the relevant members.
|
||||
pub(crate) struct DeviceAllocationContext<'a> {
|
||||
pub(crate) raw: &'a Direct3D12::ID3D12Device,
|
||||
pub(crate) shared: &'a super::DeviceShared,
|
||||
pub(crate) mem_allocator: &'a Allocator,
|
||||
pub(crate) counters: &'a wgt::HalCounters,
|
||||
}
|
||||
|
||||
impl<'a> From<&'a super::Device> for DeviceAllocationContext<'a> {
|
||||
fn from(device: &'a super::Device) -> Self {
|
||||
Self {
|
||||
raw: &device.raw,
|
||||
shared: &device.shared,
|
||||
mem_allocator: &device.mem_allocator,
|
||||
counters: &device.counters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a super::CommandEncoder> for DeviceAllocationContext<'a> {
|
||||
fn from(encoder: &'a super::CommandEncoder) -> Self {
|
||||
Self {
|
||||
raw: &encoder.device,
|
||||
shared: &encoder.shared,
|
||||
mem_allocator: &encoder.mem_allocator,
|
||||
counters: &encoder.counters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> DeviceAllocationContext<'a> {
|
||||
///////////////////////
|
||||
// Resource Creation //
|
||||
///////////////////////
|
||||
|
||||
pub(crate) fn create_buffer(
|
||||
&self,
|
||||
desc: &crate::BufferDescriptor,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ);
|
||||
let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE);
|
||||
|
||||
let location = match (is_cpu_read, is_cpu_write) {
|
||||
(true, true) => MemoryLocation::CpuToGpu,
|
||||
(true, false) => MemoryLocation::GpuToCpu,
|
||||
(false, true) => MemoryLocation::CpuToGpu,
|
||||
(false, false) => MemoryLocation::GpuOnly,
|
||||
};
|
||||
|
||||
let raw_desc = conv::map_buffer_descriptor(desc);
|
||||
let allocation_info =
|
||||
self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?;
|
||||
|
||||
let (resource, allocation) = if self.shared.private_caps.suballocation_supported {
|
||||
self.create_placed_buffer(desc, raw_desc, allocation_info, location)?
|
||||
} else {
|
||||
self.create_committed_buffer(raw_desc, location)?
|
||||
};
|
||||
|
||||
if let Some(label) = desc.label {
|
||||
resource.set_name(label)?;
|
||||
}
|
||||
|
||||
self.counters.buffer_memory.add(allocation.size() as isize);
|
||||
|
||||
Ok((resource, allocation))
|
||||
}
|
||||
|
||||
pub(crate) fn create_texture(
|
||||
&self,
|
||||
desc: &crate::TextureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let location = MemoryLocation::GpuOnly;
|
||||
let allocation_info =
|
||||
self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?;
|
||||
|
||||
let (resource, allocation) = if self.shared.private_caps.suballocation_supported {
|
||||
self.create_placed_texture(desc, raw_desc, allocation_info, location)?
|
||||
} else {
|
||||
self.create_committed_texture(desc, raw_desc)?
|
||||
};
|
||||
|
||||
if let Some(label) = desc.label {
|
||||
resource.set_name(label)?;
|
||||
}
|
||||
|
||||
self.counters.texture_memory.add(allocation.size() as isize);
|
||||
|
||||
Ok((resource, allocation))
|
||||
}
|
||||
|
||||
pub(crate) fn create_acceleration_structure(
|
||||
&self,
|
||||
desc: &crate::AccelerationStructureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let location = MemoryLocation::GpuOnly;
|
||||
let allocation_info =
|
||||
self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?;
|
||||
|
||||
let (resource, allocation) = if self.shared.private_caps.suballocation_supported {
|
||||
self.create_placed_acceleration_structure(desc, raw_desc, allocation_info, location)?
|
||||
} else {
|
||||
self.create_committed_acceleration_structure(desc, raw_desc)?
|
||||
};
|
||||
|
||||
if let Some(label) = desc.label {
|
||||
resource.set_name(label)?;
|
||||
}
|
||||
|
||||
self.counters
|
||||
.acceleration_structure_memory
|
||||
.add(allocation.size() as isize);
|
||||
|
||||
Ok((resource, allocation))
|
||||
}
|
||||
|
||||
//////////////////////////
|
||||
// Resource Destruction //
|
||||
//////////////////////////
|
||||
|
||||
pub(crate) fn free_resource(
|
||||
&self,
|
||||
resource: Direct3D12::ID3D12Resource,
|
||||
allocation: Allocation,
|
||||
) {
|
||||
// Make sure the resource is released before we free the allocation.
|
||||
drop(resource);
|
||||
|
||||
let counter = match allocation.ty {
|
||||
AllocationType::Buffer => &self.counters.buffer_memory,
|
||||
AllocationType::Texture => &self.counters.texture_memory,
|
||||
AllocationType::AccelerationStructure => &self.counters.acceleration_structure_memory,
|
||||
};
|
||||
counter.sub(allocation.size() as isize);
|
||||
|
||||
if let AllocationInner::Placed { inner } = allocation.inner {
|
||||
match self.mem_allocator.inner.lock().free(inner) {
|
||||
Ok(_) => (),
|
||||
// TODO: Don't panic here
|
||||
Err(e) => panic!("Failed to destroy dx12 {:?}, {e}", allocation.ty),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////
|
||||
// Placed Resource Creation ///
|
||||
///////////////////////////////
|
||||
|
||||
fn create_placed_buffer(
|
||||
&self,
|
||||
desc: &crate::BufferDescriptor<'_>,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let name = desc.label.unwrap_or("Unlabeled buffer");
|
||||
|
||||
let mut allocator = self.mem_allocator.inner.lock();
|
||||
|
||||
let allocation_desc = AllocationCreateDesc {
|
||||
name,
|
||||
location,
|
||||
size: allocation_info.SizeInBytes,
|
||||
alignment: allocation_info.Alignment,
|
||||
resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc),
|
||||
};
|
||||
|
||||
let allocation = allocator.allocate(&allocation_desc)?;
|
||||
let mut resource = None;
|
||||
unsafe {
|
||||
self.raw.CreatePlacedResource(
|
||||
allocation.heap(),
|
||||
allocation.offset(),
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Placed buffer creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::placed(allocation, AllocationType::Buffer);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_placed_texture(
|
||||
&self,
|
||||
desc: &crate::TextureDescriptor<'_>,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let name = desc.label.unwrap_or("Unlabeled texture");
|
||||
|
||||
let mut allocator = self.mem_allocator.inner.lock();
|
||||
|
||||
let allocation_desc = AllocationCreateDesc {
|
||||
name,
|
||||
location,
|
||||
size: allocation_info.SizeInBytes,
|
||||
alignment: allocation_info.Alignment,
|
||||
resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc),
|
||||
};
|
||||
|
||||
let allocation = allocator.allocate(&allocation_desc)?;
|
||||
let mut resource = None;
|
||||
unsafe {
|
||||
self.raw.CreatePlacedResource(
|
||||
allocation.heap(),
|
||||
allocation.offset(),
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None, // clear value
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Placed texture creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::placed(allocation, AllocationType::Texture);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_placed_acceleration_structure(
|
||||
&self,
|
||||
desc: &crate::AccelerationStructureDescriptor<'_>,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let name = desc.label.unwrap_or("Unlabeled acceleration structure");
|
||||
|
||||
let mut allocator = self.mem_allocator.inner.lock();
|
||||
|
||||
let allocation_desc = AllocationCreateDesc {
|
||||
name,
|
||||
location,
|
||||
size: allocation_info.SizeInBytes,
|
||||
alignment: allocation_info.Alignment,
|
||||
resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc),
|
||||
};
|
||||
|
||||
let allocation = allocator.allocate(&allocation_desc)?;
|
||||
let mut resource = None;
|
||||
unsafe {
|
||||
self.raw.CreatePlacedResource(
|
||||
allocation.heap(),
|
||||
allocation.offset(),
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Placed acceleration structure creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation =
|
||||
Allocation::placed(allocation, AllocationType::AccelerationStructure);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
/////////////////////////////////
|
||||
// Committed Resource Creation //
|
||||
/////////////////////////////////
|
||||
|
||||
fn create_committed_buffer(
|
||||
&self,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let is_uma = matches!(
|
||||
self.shared.private_caps.memory_architecture,
|
||||
crate::dx12::MemoryArchitecture::Unified { .. }
|
||||
);
|
||||
|
||||
let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES {
|
||||
Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM,
|
||||
CPUPageProperty: match location {
|
||||
MemoryLocation::GpuOnly => Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
|
||||
MemoryLocation::CpuToGpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
|
||||
MemoryLocation::GpuToCpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
|
||||
_ => unreachable!(),
|
||||
},
|
||||
MemoryPoolPreference: match (is_uma, location) {
|
||||
// On dedicated GPUs, we only use L1 for GPU-only allocations.
|
||||
(false, MemoryLocation::GpuOnly) => Direct3D12::D3D12_MEMORY_POOL_L1,
|
||||
(_, _) => Direct3D12::D3D12_MEMORY_POOL_L0,
|
||||
},
|
||||
CreationNodeMask: 0,
|
||||
VisibleNodeMask: 0,
|
||||
};
|
||||
|
||||
let mut resource = None;
|
||||
|
||||
unsafe {
|
||||
self.raw.CreateCommittedResource(
|
||||
&heap_properties,
|
||||
if self.shared.private_caps.heap_create_not_zeroed {
|
||||
Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED
|
||||
} else {
|
||||
Direct3D12::D3D12_HEAP_FLAG_NONE
|
||||
},
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Committed buffer creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::none(AllocationType::Buffer, raw_desc.Width);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_committed_texture(
|
||||
&self,
|
||||
desc: &crate::TextureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES {
|
||||
Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM,
|
||||
CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
|
||||
MemoryPoolPreference: match self.shared.private_caps.memory_architecture {
|
||||
crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1,
|
||||
crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0,
|
||||
},
|
||||
CreationNodeMask: 0,
|
||||
VisibleNodeMask: 0,
|
||||
};
|
||||
|
||||
let mut resource = None;
|
||||
|
||||
unsafe {
|
||||
self.raw.CreateCommittedResource(
|
||||
&heap_properties,
|
||||
if self.shared.private_caps.heap_create_not_zeroed {
|
||||
Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED
|
||||
} else {
|
||||
Direct3D12::D3D12_HEAP_FLAG_NONE
|
||||
},
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None, // clear value
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Committed texture creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::none(
|
||||
AllocationType::Texture,
|
||||
desc.format.theoretical_memory_footprint(desc.size),
|
||||
);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_committed_acceleration_structure(
|
||||
&self,
|
||||
desc: &crate::AccelerationStructureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES {
|
||||
Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM,
|
||||
CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
|
||||
MemoryPoolPreference: match self.shared.private_caps.memory_architecture {
|
||||
crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1,
|
||||
crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0,
|
||||
},
|
||||
CreationNodeMask: 0,
|
||||
VisibleNodeMask: 0,
|
||||
};
|
||||
|
||||
let mut resource = None;
|
||||
|
||||
unsafe {
|
||||
self.raw.CreateCommittedResource(
|
||||
&heap_properties,
|
||||
if self.shared.private_caps.heap_create_not_zeroed {
|
||||
Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED
|
||||
} else {
|
||||
Direct3D12::D3D12_HEAP_FLAG_NONE
|
||||
},
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Committed acceleration structure creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::none(AllocationType::AccelerationStructure, desc.size);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn error_if_would_oom_on_resource_allocation(
|
||||
&self,
|
||||
desc: &Direct3D12::D3D12_RESOURCE_DESC,
|
||||
location: MemoryLocation,
|
||||
) -> Result<Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, crate::DeviceError> {
|
||||
let allocation_info = unsafe {
|
||||
self.raw
|
||||
.GetResourceAllocationInfo(0, core::slice::from_ref(desc))
|
||||
};
|
||||
|
||||
// Some versions of WARP return SizeInBytes == 0 for very large
|
||||
// allocations. Proceeding to attempt to allocate a zero-sized resource
|
||||
// will result in a device lost error, so it seems preferable to return
|
||||
// an out of memory error now.
|
||||
if allocation_info.SizeInBytes == 0 {
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
|
||||
let Some(threshold) = self
|
||||
.mem_allocator
|
||||
.memory_budget_thresholds
|
||||
.for_resource_creation
|
||||
else {
|
||||
return Ok(allocation_info);
|
||||
};
|
||||
|
||||
let memory_segment_group = match location {
|
||||
MemoryLocation::Unknown => unreachable!(),
|
||||
MemoryLocation::GpuOnly => Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL,
|
||||
MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => {
|
||||
match self.shared.private_caps.memory_architecture {
|
||||
super::MemoryArchitecture::Unified { .. } => {
|
||||
Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL
|
||||
}
|
||||
super::MemoryArchitecture::NonUnified => {
|
||||
Dxgi::DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let info = self
|
||||
.shared
|
||||
.adapter
|
||||
.query_video_memory_info(memory_segment_group)?;
|
||||
|
||||
let memblock_size = match location {
|
||||
MemoryLocation::Unknown => unreachable!(),
|
||||
MemoryLocation::GpuOnly => self.mem_allocator.device_memblock_size,
|
||||
MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => {
|
||||
self.mem_allocator.host_memblock_size
|
||||
}
|
||||
};
|
||||
|
||||
if info
|
||||
.CurrentUsage
|
||||
.checked_add(allocation_info.SizeInBytes.max(memblock_size))
|
||||
.is_none_or(|usage| usage >= info.Budget / 100 * threshold as u64)
|
||||
{
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
|
||||
Ok(allocation_info)
|
||||
}
|
||||
}
|
||||
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use windows::Win32::Graphics::Dxgi;
|
||||
|
||||
windows_core::imp::define_interface!(
|
||||
ISwapChainPanelNative,
|
||||
ISwapChainPanelNative_Vtbl,
|
||||
0x63aad0b8_7c24_40ff_85a8_640d944cc325
|
||||
);
|
||||
impl core::ops::Deref for ISwapChainPanelNative {
|
||||
type Target = windows_core::IUnknown;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { core::mem::transmute(self) }
|
||||
}
|
||||
}
|
||||
windows_core::imp::interface_hierarchy!(ISwapChainPanelNative, windows_core::IUnknown);
|
||||
impl ISwapChainPanelNative {
|
||||
pub unsafe fn SetSwapChain<P0>(&self, swap_chain: P0) -> windows_core::Result<()>
|
||||
where
|
||||
P0: windows_core::Param<Dxgi::IDXGISwapChain1>,
|
||||
{
|
||||
unsafe {
|
||||
(windows_core::Interface::vtable(self).SetSwapChain)(
|
||||
windows_core::Interface::as_raw(self),
|
||||
swap_chain.param().abi(),
|
||||
)
|
||||
}
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
#[repr(C)]
|
||||
pub struct ISwapChainPanelNative_Vtbl {
|
||||
pub base__: windows_core::IUnknown_Vtbl,
|
||||
pub SetSwapChain: unsafe extern "system" fn(
|
||||
swap_chain_panel_native: *mut core::ffi::c_void,
|
||||
swap_chain: *mut core::ffi::c_void,
|
||||
) -> windows_core::HRESULT,
|
||||
}
|
||||
Vendored
+370
@@ -0,0 +1,370 @@
|
||||
use windows::Win32::Graphics::{Direct3D12, Dxgi};
|
||||
|
||||
use crate::auxil;
|
||||
|
||||
pub(super) struct ViewDescriptor {
|
||||
dimension: wgt::TextureViewDimension,
|
||||
pub aspects: crate::FormatAspects,
|
||||
pub rtv_dsv_format: Dxgi::Common::DXGI_FORMAT,
|
||||
srv_uav_format: Option<Dxgi::Common::DXGI_FORMAT>,
|
||||
multisampled: bool,
|
||||
array_layer_base: u32,
|
||||
array_layer_count: u32,
|
||||
mip_level_base: u32,
|
||||
mip_level_count: u32,
|
||||
plane_slice_override: Option<u32>,
|
||||
}
|
||||
|
||||
impl crate::TextureViewDescriptor<'_> {
|
||||
pub(super) fn to_internal(&self, texture: &super::Texture) -> ViewDescriptor {
|
||||
let aspects = crate::FormatAspects::new(texture.format, self.range.aspect);
|
||||
|
||||
ViewDescriptor {
|
||||
dimension: self.dimension,
|
||||
aspects,
|
||||
rtv_dsv_format: auxil::dxgi::conv::map_texture_format(self.format),
|
||||
srv_uav_format: auxil::dxgi::conv::map_texture_format_for_srv_uav(self.format, aspects),
|
||||
multisampled: texture.sample_count > 1,
|
||||
mip_level_base: self.range.base_mip_level,
|
||||
mip_level_count: self.range.mip_level_count.unwrap_or(!0),
|
||||
array_layer_base: self.range.base_array_layer,
|
||||
array_layer_count: self.range.array_layer_count.unwrap_or(!0),
|
||||
plane_slice_override: texture.plane_slice_override(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn aspects_to_plane(aspects: crate::FormatAspects) -> u32 {
|
||||
match aspects {
|
||||
crate::FormatAspects::STENCIL => 1,
|
||||
crate::FormatAspects::PLANE_1 => 1,
|
||||
crate::FormatAspects::PLANE_2 => 2,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
impl ViewDescriptor {
|
||||
pub(super) fn plane_slice(&self) -> u32 {
|
||||
self.plane_slice_override
|
||||
.unwrap_or_else(|| aspects_to_plane(self.aspects))
|
||||
}
|
||||
}
|
||||
|
||||
/// Shader component mapping for stencil views
|
||||
///
|
||||
/// Stencil views use `DXGI_FORMAT_X24_TYPELESS_G8_UINT` or
|
||||
/// `DXGI_FORMAT_X32_TYPELESS_G8X24_UINT`, which have the stencil value in
|
||||
/// the green component. WebGPU specifies that the stencil value be in the
|
||||
/// red component. It also specifies that the remaining components _should_
|
||||
/// be (0, 0, 1), but may have an unspecified value.
|
||||
const STENCIL_COMPONENT_MAPPING: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING =
|
||||
super::conv::make_shader_component_mapping(
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_1,
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0,
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0,
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1,
|
||||
);
|
||||
|
||||
impl ViewDescriptor {
|
||||
pub(crate) unsafe fn to_srv(&self) -> Option<Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC> {
|
||||
let swizzle = if self.aspects == crate::FormatAspects::STENCIL {
|
||||
STENCIL_COMPONENT_MAPPING.0 as u32
|
||||
} else {
|
||||
Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING
|
||||
};
|
||||
|
||||
let mut desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: self.srv_uav_format?,
|
||||
ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_UNKNOWN,
|
||||
Shader4ComponentMapping: swizzle,
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
*/
|
||||
wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DMS;
|
||||
desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_SRV {
|
||||
UnusedField_NothingToDefine: 0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2D;
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array
|
||||
if self.multisampled =>
|
||||
{
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
|
||||
desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_SRV {
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE3D;
|
||||
desc.Anonymous.Texture3D = Direct3D12::D3D12_TEX3D_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::Cube if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURECUBE;
|
||||
desc.Anonymous.TextureCube = Direct3D12::D3D12_TEXCUBE_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
|
||||
desc.Anonymous.TextureCubeArray = Direct3D12::D3D12_TEXCUBE_ARRAY_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
First2DArrayFace: self.array_layer_base,
|
||||
NumCubes: if self.array_layer_count == !0 {
|
||||
!0
|
||||
} else {
|
||||
self.array_layer_count / 6
|
||||
},
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(desc)
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn to_uav(&self) -> Option<Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC> {
|
||||
let mut desc = Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: self.srv_uav_format?,
|
||||
ViewDimension: Direct3D12::D3D12_UAV_DIMENSION_UNKNOWN,
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize,
|
||||
}
|
||||
}*/
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE2D;
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE3D;
|
||||
desc.Anonymous.Texture3D = Direct3D12::D3D12_TEX3D_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstWSlice: 0,
|
||||
WSize: u32::MAX,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => {
|
||||
panic!("Unable to view texture as cube UAV")
|
||||
}
|
||||
}
|
||||
|
||||
Some(desc)
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn to_rtv(&self) -> Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC {
|
||||
let mut desc = Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC {
|
||||
Format: self.rtv_dsv_format,
|
||||
ViewDimension: Direct3D12::D3D12_RTV_DIMENSION_UNKNOWN,
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize,
|
||||
}
|
||||
}*/
|
||||
wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DMS;
|
||||
desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_RTV {
|
||||
UnusedField_NothingToDefine: 0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2D;
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array
|
||||
if self.multisampled =>
|
||||
{
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
|
||||
desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_RTV {
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3
|
||||
| wgt::TextureViewDimension::Cube
|
||||
| wgt::TextureViewDimension::CubeArray => {
|
||||
panic!("Unable to view texture as cube or 3D RTV")
|
||||
}
|
||||
}
|
||||
|
||||
desc
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn to_dsv(
|
||||
&self,
|
||||
read_only: bool,
|
||||
) -> Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC {
|
||||
let mut desc = Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC {
|
||||
Format: self.rtv_dsv_format,
|
||||
ViewDimension: Direct3D12::D3D12_DSV_DIMENSION_UNKNOWN,
|
||||
Flags: {
|
||||
let mut flags = Direct3D12::D3D12_DSV_FLAG_NONE;
|
||||
if read_only {
|
||||
if self.aspects.contains(crate::FormatAspects::DEPTH) {
|
||||
flags |= Direct3D12::D3D12_DSV_FLAG_READ_ONLY_DEPTH;
|
||||
}
|
||||
if self.aspects.contains(crate::FormatAspects::STENCIL) {
|
||||
flags |= Direct3D12::D3D12_DSV_FLAG_READ_ONLY_STENCIL;
|
||||
}
|
||||
}
|
||||
flags
|
||||
},
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize,
|
||||
}
|
||||
}*/
|
||||
wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DMS;
|
||||
desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_DSV {
|
||||
UnusedField_NothingToDefine: 0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2D;
|
||||
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array
|
||||
if self.multisampled =>
|
||||
{
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
|
||||
desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_DSV {
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3
|
||||
| wgt::TextureViewDimension::Cube
|
||||
| wgt::TextureViewDimension::CubeArray => {
|
||||
panic!("Unable to view texture as cube or 3D DSV")
|
||||
}
|
||||
}
|
||||
|
||||
desc
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
use alloc::boxed::Box;
|
||||
|
||||
use crate::{
|
||||
Adapter, Api, DeviceError, OpenDevice, SurfaceCapabilities, TextureFormatCapabilities,
|
||||
};
|
||||
|
||||
use super::{DynDevice, DynQueue, DynResource, DynResourceExt, DynSurface};
|
||||
|
||||
#[expect(missing_debug_implementations, reason = "dyn")]
|
||||
pub struct DynOpenDevice {
|
||||
pub device: Box<dyn DynDevice>,
|
||||
pub queue: Box<dyn DynQueue>,
|
||||
}
|
||||
|
||||
impl<A: Api> From<OpenDevice<A>> for DynOpenDevice {
|
||||
fn from(open_device: OpenDevice<A>) -> Self {
|
||||
Self {
|
||||
device: Box::new(open_device.device),
|
||||
queue: Box::new(open_device.queue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DynAdapter: DynResource {
|
||||
unsafe fn open(
|
||||
&self,
|
||||
features: wgt::Features,
|
||||
limits: &wgt::Limits,
|
||||
memory_hints: &wgt::MemoryHints,
|
||||
) -> Result<DynOpenDevice, DeviceError>;
|
||||
|
||||
unsafe fn texture_format_capabilities(
|
||||
&self,
|
||||
format: wgt::TextureFormat,
|
||||
) -> TextureFormatCapabilities;
|
||||
|
||||
unsafe fn surface_capabilities(&self, surface: &dyn DynSurface) -> Option<SurfaceCapabilities>;
|
||||
|
||||
unsafe fn surface_display_hdr_info(
|
||||
&self,
|
||||
surface: &dyn DynSurface,
|
||||
) -> Option<wgt::DisplayHdrInfo>;
|
||||
|
||||
unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp;
|
||||
|
||||
fn get_ordered_buffer_usages(&self) -> wgt::BufferUses;
|
||||
|
||||
fn get_ordered_texture_usages(&self) -> wgt::TextureUses;
|
||||
}
|
||||
|
||||
impl<A: Adapter + DynResource> DynAdapter for A {
|
||||
unsafe fn open(
|
||||
&self,
|
||||
features: wgt::Features,
|
||||
limits: &wgt::Limits,
|
||||
memory_hints: &wgt::MemoryHints,
|
||||
) -> Result<DynOpenDevice, DeviceError> {
|
||||
unsafe { A::open(self, features, limits, memory_hints) }.map(|open_device| DynOpenDevice {
|
||||
device: Box::new(open_device.device),
|
||||
queue: Box::new(open_device.queue),
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn texture_format_capabilities(
|
||||
&self,
|
||||
format: wgt::TextureFormat,
|
||||
) -> TextureFormatCapabilities {
|
||||
unsafe { A::texture_format_capabilities(self, format) }
|
||||
}
|
||||
|
||||
unsafe fn surface_capabilities(&self, surface: &dyn DynSurface) -> Option<SurfaceCapabilities> {
|
||||
let surface = surface.expect_downcast_ref();
|
||||
unsafe { A::surface_capabilities(self, surface) }
|
||||
}
|
||||
|
||||
unsafe fn surface_display_hdr_info(
|
||||
&self,
|
||||
surface: &dyn DynSurface,
|
||||
) -> Option<wgt::DisplayHdrInfo> {
|
||||
let surface = surface.expect_downcast_ref();
|
||||
unsafe { A::surface_display_hdr_info(self, surface) }
|
||||
}
|
||||
|
||||
unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
|
||||
unsafe { A::get_presentation_timestamp(self) }
|
||||
}
|
||||
|
||||
fn get_ordered_buffer_usages(&self) -> wgt::BufferUses {
|
||||
A::get_ordered_buffer_usages(self)
|
||||
}
|
||||
|
||||
fn get_ordered_texture_usages(&self) -> wgt::TextureUses {
|
||||
A::get_ordered_texture_usages(self)
|
||||
}
|
||||
}
|
||||
+823
@@ -0,0 +1,823 @@
|
||||
use alloc::{boxed::Box, vec::Vec};
|
||||
use core::ops::Range;
|
||||
|
||||
use crate::{
|
||||
AccelerationStructureBarrier, Api, Attachment, BufferBarrier, BufferBinding, BufferCopy,
|
||||
BufferTextureCopy, BuildAccelerationStructureDescriptor, ColorAttachment, CommandEncoder,
|
||||
ComputePassDescriptor, DepthStencilAttachment, DeviceError, DynRayTracingPipeline, Label,
|
||||
MemoryRange, PassTimestampWrites, RayTracingPassDescriptor, Rect, RenderPassDescriptor,
|
||||
TextureBarrier, TextureCopy,
|
||||
};
|
||||
|
||||
use super::{
|
||||
DynAccelerationStructure, DynBindGroup, DynBuffer, DynCommandBuffer, DynComputePipeline,
|
||||
DynPipelineLayout, DynQuerySet, DynRenderPipeline, DynResource, DynResourceExt as _,
|
||||
DynTexture, DynTextureView,
|
||||
};
|
||||
|
||||
pub trait DynCommandEncoder: DynResource + core::fmt::Debug {
|
||||
unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError>;
|
||||
|
||||
unsafe fn discard_encoding(&mut self);
|
||||
|
||||
unsafe fn end_encoding(&mut self) -> Result<Box<dyn DynCommandBuffer>, DeviceError>;
|
||||
|
||||
unsafe fn reset_all(&mut self, command_buffers: Vec<Box<dyn DynCommandBuffer>>);
|
||||
|
||||
unsafe fn transition_buffers(&mut self, barriers: &[BufferBarrier<'_, dyn DynBuffer>]);
|
||||
unsafe fn transition_textures(&mut self, barriers: &[TextureBarrier<'_, dyn DynTexture>]);
|
||||
|
||||
unsafe fn clear_buffer(&mut self, buffer: &dyn DynBuffer, range: MemoryRange);
|
||||
|
||||
unsafe fn copy_buffer_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferCopy],
|
||||
);
|
||||
|
||||
unsafe fn copy_texture_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[TextureCopy],
|
||||
);
|
||||
|
||||
unsafe fn copy_buffer_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[BufferTextureCopy],
|
||||
);
|
||||
|
||||
unsafe fn copy_texture_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferTextureCopy],
|
||||
);
|
||||
|
||||
unsafe fn set_bind_group(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
index: u32,
|
||||
group: &dyn DynBindGroup,
|
||||
dynamic_offsets: &[wgt::DynamicOffset],
|
||||
);
|
||||
|
||||
unsafe fn set_immediates(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
offset_bytes: u32,
|
||||
data: &[u32],
|
||||
);
|
||||
|
||||
unsafe fn insert_debug_marker(&mut self, label: &str);
|
||||
unsafe fn begin_debug_marker(&mut self, group_label: &str);
|
||||
unsafe fn end_debug_marker(&mut self);
|
||||
|
||||
unsafe fn begin_query(&mut self, set: &dyn DynQuerySet, index: u32);
|
||||
unsafe fn end_query(&mut self, set: &dyn DynQuerySet, index: u32);
|
||||
unsafe fn write_timestamp(&mut self, set: &dyn DynQuerySet, index: u32);
|
||||
unsafe fn reset_queries(&mut self, set: &dyn DynQuerySet, range: Range<u32>);
|
||||
unsafe fn copy_query_results(
|
||||
&mut self,
|
||||
set: &dyn DynQuerySet,
|
||||
range: Range<u32>,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
stride: wgt::BufferSize,
|
||||
);
|
||||
|
||||
unsafe fn begin_render_pass(
|
||||
&mut self,
|
||||
desc: &RenderPassDescriptor<dyn DynQuerySet, dyn DynTextureView>,
|
||||
) -> Result<(), DeviceError>;
|
||||
unsafe fn end_render_pass(&mut self);
|
||||
|
||||
unsafe fn set_render_pipeline(&mut self, pipeline: &dyn DynRenderPipeline);
|
||||
|
||||
unsafe fn set_index_buffer<'a>(
|
||||
&mut self,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
format: wgt::IndexFormat,
|
||||
);
|
||||
|
||||
unsafe fn set_vertex_buffer<'a>(
|
||||
&mut self,
|
||||
index: u32,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
);
|
||||
unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>);
|
||||
unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>);
|
||||
unsafe fn set_stencil_reference(&mut self, value: u32);
|
||||
unsafe fn set_blend_constants(&mut self, color: &[f32; 4]);
|
||||
|
||||
unsafe fn draw(
|
||||
&mut self,
|
||||
first_vertex: u32,
|
||||
vertex_count: u32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
);
|
||||
unsafe fn draw_indexed(
|
||||
&mut self,
|
||||
first_index: u32,
|
||||
index_count: u32,
|
||||
base_vertex: i32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
);
|
||||
unsafe fn draw_mesh_tasks(
|
||||
&mut self,
|
||||
group_count_x: u32,
|
||||
group_count_y: u32,
|
||||
group_count_z: u32,
|
||||
);
|
||||
unsafe fn draw_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
);
|
||||
unsafe fn draw_indexed_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
);
|
||||
unsafe fn draw_mesh_tasks_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
);
|
||||
unsafe fn draw_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
);
|
||||
unsafe fn draw_indexed_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
);
|
||||
unsafe fn draw_mesh_tasks_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
);
|
||||
|
||||
unsafe fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor<dyn DynQuerySet>);
|
||||
unsafe fn end_compute_pass(&mut self);
|
||||
|
||||
unsafe fn set_compute_pipeline(&mut self, pipeline: &dyn DynComputePipeline);
|
||||
|
||||
unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]);
|
||||
unsafe fn dispatch_workgroups_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
);
|
||||
|
||||
unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor);
|
||||
unsafe fn end_ray_tracing_pass(&mut self);
|
||||
|
||||
unsafe fn trace_rays(
|
||||
&mut self,
|
||||
count: [u32; 3],
|
||||
ray_generation_group_data: crate::PipelineGroupData<dyn DynBuffer>,
|
||||
miss_group_data: crate::PipelineGroupData<dyn DynBuffer>,
|
||||
intersection_group_data: crate::PipelineGroupData<dyn DynBuffer>,
|
||||
);
|
||||
|
||||
unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &dyn DynRayTracingPipeline);
|
||||
|
||||
unsafe fn build_acceleration_structures<'a>(
|
||||
&mut self,
|
||||
descriptors: &'a [BuildAccelerationStructureDescriptor<
|
||||
'a,
|
||||
dyn DynBuffer,
|
||||
dyn DynAccelerationStructure,
|
||||
>],
|
||||
);
|
||||
unsafe fn place_acceleration_structure_barrier(
|
||||
&mut self,
|
||||
barrier: AccelerationStructureBarrier,
|
||||
);
|
||||
unsafe fn copy_acceleration_structure_to_acceleration_structure(
|
||||
&mut self,
|
||||
src: &dyn DynAccelerationStructure,
|
||||
dst: &dyn DynAccelerationStructure,
|
||||
copy: wgt::AccelerationStructureCopy,
|
||||
);
|
||||
unsafe fn read_acceleration_structure_compact_size(
|
||||
&mut self,
|
||||
acceleration_structure: &dyn DynAccelerationStructure,
|
||||
buf: &dyn DynBuffer,
|
||||
);
|
||||
unsafe fn set_acceleration_structure_dependencies(
|
||||
&self,
|
||||
command_buffers: &[Box<dyn DynCommandBuffer>],
|
||||
dependencies: &[&dyn DynAccelerationStructure],
|
||||
);
|
||||
}
|
||||
|
||||
impl<C: CommandEncoder + DynResource> DynCommandEncoder for C {
|
||||
unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError> {
|
||||
unsafe { C::begin_encoding(self, label) }
|
||||
}
|
||||
|
||||
unsafe fn discard_encoding(&mut self) {
|
||||
unsafe { C::discard_encoding(self) }
|
||||
}
|
||||
|
||||
unsafe fn end_encoding(&mut self) -> Result<Box<dyn DynCommandBuffer>, DeviceError> {
|
||||
unsafe { C::end_encoding(self) }.map(|cb| {
|
||||
let boxed_command_buffer: Box<<C::A as Api>::CommandBuffer> = Box::new(cb);
|
||||
let boxed_command_buffer: Box<dyn DynCommandBuffer> = boxed_command_buffer;
|
||||
boxed_command_buffer
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn reset_all(&mut self, command_buffers: Vec<Box<dyn DynCommandBuffer>>) {
|
||||
unsafe { C::reset_all(self, command_buffers.into_iter().map(|cb| cb.unbox())) }
|
||||
}
|
||||
|
||||
unsafe fn transition_buffers(&mut self, barriers: &[BufferBarrier<'_, dyn DynBuffer>]) {
|
||||
let barriers = barriers.iter().map(|barrier| BufferBarrier {
|
||||
buffer: barrier.buffer.expect_downcast_ref(),
|
||||
usage: barrier.usage.clone(),
|
||||
});
|
||||
unsafe { self.transition_buffers(barriers) };
|
||||
}
|
||||
|
||||
unsafe fn transition_textures(&mut self, barriers: &[TextureBarrier<'_, dyn DynTexture>]) {
|
||||
let barriers = barriers.iter().map(|barrier| TextureBarrier {
|
||||
texture: barrier.texture.expect_downcast_ref(),
|
||||
usage: barrier.usage.clone(),
|
||||
range: barrier.range,
|
||||
});
|
||||
unsafe { self.transition_textures(barriers) };
|
||||
}
|
||||
|
||||
unsafe fn clear_buffer(&mut self, buffer: &dyn DynBuffer, range: MemoryRange) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::clear_buffer(self, buffer, range) };
|
||||
}
|
||||
|
||||
unsafe fn copy_buffer_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_buffer_to_buffer(self, src, dst, regions.iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_texture_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[TextureCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_texture_to_texture(self, src, src_usage, dst, regions.iter().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_buffer_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[BufferTextureCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_buffer_to_texture(self, src, dst, regions.iter().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_texture_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferTextureCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_texture_to_buffer(self, src, src_usage, dst, regions.iter().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_bind_group(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
index: u32,
|
||||
group: &dyn DynBindGroup,
|
||||
dynamic_offsets: &[wgt::DynamicOffset],
|
||||
) {
|
||||
let layout = layout.expect_downcast_ref();
|
||||
let group = group.expect_downcast_ref();
|
||||
unsafe { C::set_bind_group(self, layout, index, group, dynamic_offsets) };
|
||||
}
|
||||
|
||||
unsafe fn set_immediates(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
offset_bytes: u32,
|
||||
data: &[u32],
|
||||
) {
|
||||
let layout = layout.expect_downcast_ref();
|
||||
unsafe { C::set_immediates(self, layout, offset_bytes, data) };
|
||||
}
|
||||
|
||||
unsafe fn insert_debug_marker(&mut self, label: &str) {
|
||||
unsafe {
|
||||
C::insert_debug_marker(self, label);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn begin_debug_marker(&mut self, group_label: &str) {
|
||||
unsafe {
|
||||
C::begin_debug_marker(self, group_label);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn end_debug_marker(&mut self) {
|
||||
unsafe {
|
||||
C::end_debug_marker(self);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn begin_query(&mut self, set: &dyn DynQuerySet, index: u32) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::begin_query(self, set, index) };
|
||||
}
|
||||
|
||||
unsafe fn end_query(&mut self, set: &dyn DynQuerySet, index: u32) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::end_query(self, set, index) };
|
||||
}
|
||||
|
||||
unsafe fn write_timestamp(&mut self, set: &dyn DynQuerySet, index: u32) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::write_timestamp(self, set, index) };
|
||||
}
|
||||
|
||||
unsafe fn reset_queries(&mut self, set: &dyn DynQuerySet, range: Range<u32>) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::reset_queries(self, set, range) };
|
||||
}
|
||||
|
||||
unsafe fn copy_query_results(
|
||||
&mut self,
|
||||
set: &dyn DynQuerySet,
|
||||
range: Range<u32>,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
stride: wgt::BufferSize,
|
||||
) {
|
||||
let set = set.expect_downcast_ref();
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::copy_query_results(self, set, range, buffer, offset, stride) };
|
||||
}
|
||||
|
||||
unsafe fn begin_render_pass(
|
||||
&mut self,
|
||||
desc: &RenderPassDescriptor<dyn DynQuerySet, dyn DynTextureView>,
|
||||
) -> Result<(), DeviceError> {
|
||||
let color_attachments = desc
|
||||
.color_attachments
|
||||
.iter()
|
||||
.map(|attachment| {
|
||||
attachment
|
||||
.as_ref()
|
||||
.map(|attachment| attachment.expect_downcast())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let desc: RenderPassDescriptor<<C::A as Api>::QuerySet, <C::A as Api>::TextureView> =
|
||||
RenderPassDescriptor {
|
||||
label: desc.label,
|
||||
extent: desc.extent,
|
||||
sample_count: desc.sample_count,
|
||||
color_attachments: &color_attachments,
|
||||
depth_stencil_attachment: desc
|
||||
.depth_stencil_attachment
|
||||
.as_ref()
|
||||
.map(|ds| ds.expect_downcast()),
|
||||
multiview_mask: desc.multiview_mask,
|
||||
timestamp_writes: desc
|
||||
.timestamp_writes
|
||||
.as_ref()
|
||||
.map(|writes| writes.expect_downcast()),
|
||||
occlusion_query_set: desc
|
||||
.occlusion_query_set
|
||||
.map(|set| set.expect_downcast_ref()),
|
||||
};
|
||||
unsafe { C::begin_render_pass(self, &desc) }
|
||||
}
|
||||
|
||||
unsafe fn end_render_pass(&mut self) {
|
||||
unsafe {
|
||||
C::end_render_pass(self);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>) {
|
||||
unsafe {
|
||||
C::set_viewport(self, rect, depth_range);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>) {
|
||||
unsafe {
|
||||
C::set_scissor_rect(self, rect);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_stencil_reference(&mut self, value: u32) {
|
||||
unsafe {
|
||||
C::set_stencil_reference(self, value);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) {
|
||||
unsafe { C::set_blend_constants(self, color) };
|
||||
}
|
||||
|
||||
unsafe fn draw(
|
||||
&mut self,
|
||||
first_vertex: u32,
|
||||
vertex_count: u32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
) {
|
||||
unsafe {
|
||||
C::draw(
|
||||
self,
|
||||
first_vertex,
|
||||
vertex_count,
|
||||
first_instance,
|
||||
instance_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_indexed(
|
||||
&mut self,
|
||||
first_index: u32,
|
||||
index_count: u32,
|
||||
base_vertex: i32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
) {
|
||||
unsafe {
|
||||
C::draw_indexed(
|
||||
self,
|
||||
first_index,
|
||||
index_count,
|
||||
base_vertex,
|
||||
first_instance,
|
||||
instance_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_mesh_tasks(
|
||||
&mut self,
|
||||
group_count_x: u32,
|
||||
group_count_y: u32,
|
||||
group_count_z: u32,
|
||||
) {
|
||||
unsafe { C::draw_mesh_tasks(self, group_count_x, group_count_y, group_count_z) };
|
||||
}
|
||||
|
||||
unsafe fn draw_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::draw_indirect(self, buffer, offset, draw_count) };
|
||||
}
|
||||
|
||||
unsafe fn draw_indexed_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::draw_indexed_indirect(self, buffer, offset, draw_count) };
|
||||
}
|
||||
|
||||
unsafe fn draw_mesh_tasks_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::draw_mesh_tasks_indirect(self, buffer, offset, draw_count) };
|
||||
}
|
||||
|
||||
unsafe fn draw_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
let count_buffer = count_buffer.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::draw_indirect_count(self, buffer, offset, count_buffer, count_offset, max_count)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_indexed_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
let count_buffer = count_buffer.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::draw_indexed_indirect_count(
|
||||
self,
|
||||
buffer,
|
||||
offset,
|
||||
count_buffer,
|
||||
count_offset,
|
||||
max_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_mesh_tasks_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
let count_buffer = count_buffer.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::draw_mesh_tasks_indirect_count(
|
||||
self,
|
||||
buffer,
|
||||
offset,
|
||||
count_buffer,
|
||||
count_offset,
|
||||
max_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor<dyn DynQuerySet>) {
|
||||
let desc = ComputePassDescriptor {
|
||||
label: desc.label,
|
||||
timestamp_writes: desc
|
||||
.timestamp_writes
|
||||
.as_ref()
|
||||
.map(|writes| writes.expect_downcast()),
|
||||
};
|
||||
unsafe { C::begin_compute_pass(self, &desc) };
|
||||
}
|
||||
|
||||
unsafe fn end_compute_pass(&mut self) {
|
||||
unsafe { C::end_compute_pass(self) };
|
||||
}
|
||||
|
||||
unsafe fn set_compute_pipeline(&mut self, pipeline: &dyn DynComputePipeline) {
|
||||
let pipeline = pipeline.expect_downcast_ref();
|
||||
unsafe { C::set_compute_pipeline(self, pipeline) };
|
||||
}
|
||||
|
||||
unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) {
|
||||
unsafe { C::dispatch_workgroups(self, count) };
|
||||
}
|
||||
|
||||
unsafe fn dispatch_workgroups_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::dispatch_workgroups_indirect(self, buffer, offset) };
|
||||
}
|
||||
|
||||
unsafe fn set_render_pipeline(&mut self, pipeline: &dyn DynRenderPipeline) {
|
||||
let pipeline = pipeline.expect_downcast_ref();
|
||||
unsafe { C::set_render_pipeline(self, pipeline) };
|
||||
}
|
||||
|
||||
unsafe fn set_index_buffer<'a>(
|
||||
&mut self,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
format: wgt::IndexFormat,
|
||||
) {
|
||||
let binding = binding.expect_downcast();
|
||||
unsafe { self.set_index_buffer(binding, format) };
|
||||
}
|
||||
|
||||
unsafe fn set_vertex_buffer<'a>(
|
||||
&mut self,
|
||||
index: u32,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
) {
|
||||
let binding = binding.expect_downcast();
|
||||
unsafe { self.set_vertex_buffer(index, binding) };
|
||||
}
|
||||
|
||||
unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor) {
|
||||
let desc = RayTracingPassDescriptor { label: desc.label };
|
||||
unsafe { C::begin_ray_tracing_pass(self, &desc) };
|
||||
}
|
||||
|
||||
unsafe fn end_ray_tracing_pass(&mut self) {
|
||||
unsafe { C::end_ray_tracing_pass(self) };
|
||||
}
|
||||
|
||||
unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &dyn DynRayTracingPipeline) {
|
||||
let pipeline = pipeline.expect_downcast_ref();
|
||||
unsafe { C::set_ray_tracing_pipeline(self, pipeline) };
|
||||
}
|
||||
|
||||
unsafe fn trace_rays<'a>(
|
||||
&mut self,
|
||||
count: [u32; 3],
|
||||
ray_generation_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>,
|
||||
miss_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>,
|
||||
intersection_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>,
|
||||
) {
|
||||
let downcast_group_data =
|
||||
|data: crate::PipelineGroupData<'a, dyn DynBuffer>| crate::PipelineGroupData {
|
||||
buffer: data.buffer.expect_downcast_ref(),
|
||||
offset: data.offset,
|
||||
stride: data.stride,
|
||||
count: data.count,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
C::trace_rays(
|
||||
self,
|
||||
count,
|
||||
downcast_group_data(ray_generation_group_data),
|
||||
downcast_group_data(miss_group_data),
|
||||
downcast_group_data(intersection_group_data),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn build_acceleration_structures<'a>(
|
||||
&mut self,
|
||||
descriptors: &'a [BuildAccelerationStructureDescriptor<
|
||||
'a,
|
||||
dyn DynBuffer,
|
||||
dyn DynAccelerationStructure,
|
||||
>],
|
||||
) {
|
||||
// Need to collect entries here so we can reference them in the descriptor.
|
||||
// TODO: API should be redesigned to avoid this and other descriptor copies that happen due to the dyn api.
|
||||
let descriptor_entries = descriptors
|
||||
.iter()
|
||||
.map(|d| d.entries.expect_downcast())
|
||||
.collect::<Vec<_>>();
|
||||
let descriptors = descriptors
|
||||
.iter()
|
||||
.zip(descriptor_entries.iter())
|
||||
.map(|(d, entries)| BuildAccelerationStructureDescriptor::<
|
||||
<C::A as Api>::Buffer,
|
||||
<C::A as Api>::AccelerationStructure,
|
||||
> {
|
||||
entries,
|
||||
mode: d.mode,
|
||||
flags: d.flags,
|
||||
source_acceleration_structure: d
|
||||
.source_acceleration_structure
|
||||
.map(|a| a.expect_downcast_ref()),
|
||||
destination_acceleration_structure: d
|
||||
.destination_acceleration_structure
|
||||
.expect_downcast_ref(),
|
||||
scratch_buffer: d.scratch_buffer.expect_downcast_ref(),
|
||||
scratch_buffer_offset: d.scratch_buffer_offset,
|
||||
});
|
||||
unsafe { C::build_acceleration_structures(self, descriptors.len() as _, descriptors) };
|
||||
}
|
||||
|
||||
unsafe fn place_acceleration_structure_barrier(
|
||||
&mut self,
|
||||
barrier: AccelerationStructureBarrier,
|
||||
) {
|
||||
unsafe { C::place_acceleration_structure_barrier(self, barrier) };
|
||||
}
|
||||
|
||||
unsafe fn copy_acceleration_structure_to_acceleration_structure(
|
||||
&mut self,
|
||||
src: &dyn DynAccelerationStructure,
|
||||
dst: &dyn DynAccelerationStructure,
|
||||
copy: wgt::AccelerationStructureCopy,
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe { C::copy_acceleration_structure_to_acceleration_structure(self, src, dst, copy) };
|
||||
}
|
||||
unsafe fn read_acceleration_structure_compact_size(
|
||||
&mut self,
|
||||
acceleration_structure: &dyn DynAccelerationStructure,
|
||||
buf: &dyn DynBuffer,
|
||||
) {
|
||||
let acceleration_structure = acceleration_structure.expect_downcast_ref();
|
||||
let buf = buf.expect_downcast_ref();
|
||||
unsafe { C::read_acceleration_structure_compact_size(self, acceleration_structure, buf) }
|
||||
}
|
||||
|
||||
unsafe fn set_acceleration_structure_dependencies(
|
||||
&self,
|
||||
command_buffers: &[Box<dyn DynCommandBuffer>],
|
||||
dependencies: &[&dyn DynAccelerationStructure],
|
||||
) {
|
||||
let command_buffers: Vec<&<C::A as Api>::CommandBuffer> = command_buffers
|
||||
.iter()
|
||||
.map(|command_buffer| command_buffer.expect_downcast_ref())
|
||||
.collect();
|
||||
let dependencies: Vec<&<C::A as Api>::AccelerationStructure> = dependencies
|
||||
.iter()
|
||||
.map(|dependency| dependency.expect_downcast_ref())
|
||||
.collect();
|
||||
unsafe { C::set_acceleration_structure_dependencies(&command_buffers, &dependencies) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> PassTimestampWrites<'a, dyn DynQuerySet> {
|
||||
pub fn expect_downcast<B: DynQuerySet>(&self) -> PassTimestampWrites<'a, B> {
|
||||
PassTimestampWrites {
|
||||
query_set: self.query_set.expect_downcast_ref(),
|
||||
beginning_of_pass_write_index: self.beginning_of_pass_write_index,
|
||||
end_of_pass_write_index: self.end_of_pass_write_index,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Attachment<'a, dyn DynTextureView> {
|
||||
pub fn expect_downcast<B: DynTextureView>(&self) -> Attachment<'a, B> {
|
||||
Attachment {
|
||||
view: self.view.expect_downcast_ref(),
|
||||
usage: self.usage,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ColorAttachment<'a, dyn DynTextureView> {
|
||||
pub fn expect_downcast<B: DynTextureView>(&self) -> ColorAttachment<'a, B> {
|
||||
ColorAttachment {
|
||||
target: self.target.expect_downcast(),
|
||||
depth_slice: self.depth_slice,
|
||||
resolve_target: self.resolve_target.as_ref().map(|rt| rt.expect_downcast()),
|
||||
ops: self.ops,
|
||||
clear_value: self.clear_value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> DepthStencilAttachment<'a, dyn DynTextureView> {
|
||||
pub fn expect_downcast<B: DynTextureView>(&self) -> DepthStencilAttachment<'a, B> {
|
||||
DepthStencilAttachment {
|
||||
target: self.target.expect_downcast(),
|
||||
depth_ops: self.depth_ops,
|
||||
stencil_ops: self.stencil_ops,
|
||||
clear_value: self.clear_value,
|
||||
}
|
||||
}
|
||||
}
|
||||
+622
@@ -0,0 +1,622 @@
|
||||
use alloc::{borrow::ToOwned as _, boxed::Box, vec::Vec};
|
||||
|
||||
use crate::{
|
||||
AccelerationStructureBuildSizes, AccelerationStructureDescriptor, Api, BindGroupDescriptor,
|
||||
BindGroupLayoutDescriptor, BufferDescriptor, BufferMapping, CommandEncoderDescriptor,
|
||||
ComputePipelineDescriptor, Device, DeviceError, FenceValue,
|
||||
GetAccelerationStructureBuildSizesDescriptor, Label, MemoryRange, PipelineCacheDescriptor,
|
||||
PipelineCacheError, PipelineError, PipelineLayoutDescriptor, RayObjectIntersectionState,
|
||||
RayTracingPipelineDescriptor, RenderPipelineDescriptor, SamplerDescriptor, ShaderError,
|
||||
ShaderInput, ShaderModuleDescriptor, TextureDescriptor, TextureViewDescriptor, TlasInstance,
|
||||
};
|
||||
|
||||
use super::{
|
||||
DynAccelerationStructure, DynBindGroup, DynBindGroupLayout, DynBuffer, DynCommandEncoder,
|
||||
DynComputePipeline, DynFence, DynPipelineCache, DynPipelineLayout, DynQuerySet, DynQueue,
|
||||
DynRayTracingPipeline, DynRenderPipeline, DynResource, DynResourceExt as _, DynSampler,
|
||||
DynShaderModule, DynTexture, DynTextureView,
|
||||
};
|
||||
|
||||
pub trait DynDevice: DynResource {
|
||||
unsafe fn create_buffer(
|
||||
&self,
|
||||
desc: &BufferDescriptor,
|
||||
) -> Result<Box<dyn DynBuffer>, DeviceError>;
|
||||
|
||||
unsafe fn destroy_buffer(&self, buffer: Box<dyn DynBuffer>);
|
||||
unsafe fn add_raw_buffer(&self, buffer: &dyn DynBuffer);
|
||||
|
||||
unsafe fn map_buffer(
|
||||
&self,
|
||||
buffer: &dyn DynBuffer,
|
||||
range: MemoryRange,
|
||||
) -> Result<BufferMapping, DeviceError>;
|
||||
|
||||
unsafe fn unmap_buffer(&self, buffer: &dyn DynBuffer);
|
||||
|
||||
unsafe fn flush_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]);
|
||||
unsafe fn invalidate_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]);
|
||||
|
||||
unsafe fn create_texture(
|
||||
&self,
|
||||
desc: &TextureDescriptor,
|
||||
) -> Result<Box<dyn DynTexture>, DeviceError>;
|
||||
unsafe fn destroy_texture(&self, texture: Box<dyn DynTexture>);
|
||||
unsafe fn add_raw_texture(&self, texture: &dyn DynTexture);
|
||||
|
||||
unsafe fn create_texture_view(
|
||||
&self,
|
||||
texture: &dyn DynTexture,
|
||||
desc: &TextureViewDescriptor,
|
||||
) -> Result<Box<dyn DynTextureView>, DeviceError>;
|
||||
unsafe fn destroy_texture_view(&self, view: Box<dyn DynTextureView>);
|
||||
unsafe fn create_sampler(
|
||||
&self,
|
||||
desc: &SamplerDescriptor,
|
||||
) -> Result<Box<dyn DynSampler>, DeviceError>;
|
||||
unsafe fn destroy_sampler(&self, sampler: Box<dyn DynSampler>);
|
||||
|
||||
unsafe fn create_command_encoder(
|
||||
&self,
|
||||
desc: &CommandEncoderDescriptor<dyn DynQueue>,
|
||||
) -> Result<Box<dyn DynCommandEncoder>, DeviceError>;
|
||||
|
||||
unsafe fn create_bind_group_layout(
|
||||
&self,
|
||||
desc: &BindGroupLayoutDescriptor,
|
||||
) -> Result<Box<dyn DynBindGroupLayout>, DeviceError>;
|
||||
unsafe fn destroy_bind_group_layout(&self, bg_layout: Box<dyn DynBindGroupLayout>);
|
||||
|
||||
unsafe fn create_pipeline_layout(
|
||||
&self,
|
||||
desc: &PipelineLayoutDescriptor<dyn DynBindGroupLayout>,
|
||||
) -> Result<Box<dyn DynPipelineLayout>, DeviceError>;
|
||||
unsafe fn destroy_pipeline_layout(&self, pipeline_layout: Box<dyn DynPipelineLayout>);
|
||||
|
||||
unsafe fn create_bind_group(
|
||||
&self,
|
||||
desc: &BindGroupDescriptor<
|
||||
dyn DynBindGroupLayout,
|
||||
dyn DynBuffer,
|
||||
dyn DynSampler,
|
||||
dyn DynTextureView,
|
||||
dyn DynAccelerationStructure,
|
||||
>,
|
||||
) -> Result<Box<dyn DynBindGroup>, DeviceError>;
|
||||
unsafe fn destroy_bind_group(&self, group: Box<dyn DynBindGroup>);
|
||||
|
||||
unsafe fn create_shader_module(
|
||||
&self,
|
||||
desc: &ShaderModuleDescriptor,
|
||||
shader: ShaderInput,
|
||||
) -> Result<Box<dyn DynShaderModule>, ShaderError>;
|
||||
unsafe fn destroy_shader_module(&self, module: Box<dyn DynShaderModule>);
|
||||
|
||||
unsafe fn create_render_pipeline(
|
||||
&self,
|
||||
desc: &RenderPipelineDescriptor<
|
||||
dyn DynPipelineLayout,
|
||||
dyn DynShaderModule,
|
||||
dyn DynPipelineCache,
|
||||
>,
|
||||
) -> Result<Box<dyn DynRenderPipeline>, PipelineError>;
|
||||
unsafe fn destroy_render_pipeline(&self, pipeline: Box<dyn DynRenderPipeline>);
|
||||
|
||||
unsafe fn create_compute_pipeline(
|
||||
&self,
|
||||
desc: &ComputePipelineDescriptor<
|
||||
dyn DynPipelineLayout,
|
||||
dyn DynShaderModule,
|
||||
dyn DynPipelineCache,
|
||||
>,
|
||||
) -> Result<Box<dyn DynComputePipeline>, PipelineError>;
|
||||
unsafe fn destroy_compute_pipeline(&self, pipeline: Box<dyn DynComputePipeline>);
|
||||
|
||||
unsafe fn create_ray_tracing_pipeline(
|
||||
&self,
|
||||
desc: &RayTracingPipelineDescriptor<
|
||||
dyn DynPipelineLayout,
|
||||
dyn DynShaderModule,
|
||||
dyn DynPipelineCache,
|
||||
>,
|
||||
) -> Result<Box<dyn DynRayTracingPipeline>, PipelineError>;
|
||||
unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: Box<dyn DynRayTracingPipeline>);
|
||||
unsafe fn get_raytracing_pipeline_group_data(
|
||||
&self,
|
||||
pipeline: &dyn DynRayTracingPipeline,
|
||||
groups: core::ops::Range<u32>,
|
||||
) -> Result<Vec<u8>, DeviceError>;
|
||||
|
||||
unsafe fn create_pipeline_cache(
|
||||
&self,
|
||||
desc: &PipelineCacheDescriptor<'_>,
|
||||
) -> Result<Box<dyn DynPipelineCache>, PipelineCacheError>;
|
||||
fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> {
|
||||
None
|
||||
}
|
||||
unsafe fn destroy_pipeline_cache(&self, cache: Box<dyn DynPipelineCache>);
|
||||
|
||||
unsafe fn create_query_set(
|
||||
&self,
|
||||
desc: &wgt::QuerySetDescriptor<Label>,
|
||||
) -> Result<Box<dyn DynQuerySet>, DeviceError>;
|
||||
unsafe fn destroy_query_set(&self, set: Box<dyn DynQuerySet>);
|
||||
|
||||
unsafe fn create_fence(&self) -> Result<Box<dyn DynFence>, DeviceError>;
|
||||
unsafe fn destroy_fence(&self, fence: Box<dyn DynFence>);
|
||||
unsafe fn get_fence_value(&self, fence: &dyn DynFence) -> Result<FenceValue, DeviceError>;
|
||||
|
||||
unsafe fn wait(
|
||||
&self,
|
||||
fence: &dyn DynFence,
|
||||
value: FenceValue,
|
||||
timeout: Option<core::time::Duration>,
|
||||
) -> Result<bool, DeviceError>;
|
||||
|
||||
unsafe fn start_graphics_debugger_capture(&self) -> bool;
|
||||
unsafe fn stop_graphics_debugger_capture(&self);
|
||||
|
||||
unsafe fn pipeline_cache_get_data(&self, cache: &dyn DynPipelineCache) -> Option<Vec<u8>>;
|
||||
|
||||
unsafe fn create_acceleration_structure(
|
||||
&self,
|
||||
desc: &AccelerationStructureDescriptor,
|
||||
) -> Result<Box<dyn DynAccelerationStructure>, DeviceError>;
|
||||
unsafe fn get_acceleration_structure_build_sizes(
|
||||
&self,
|
||||
desc: &GetAccelerationStructureBuildSizesDescriptor<dyn DynBuffer>,
|
||||
) -> AccelerationStructureBuildSizes;
|
||||
unsafe fn get_acceleration_structure_device_address(
|
||||
&self,
|
||||
acceleration_structure: &dyn DynAccelerationStructure,
|
||||
) -> wgt::BufferAddress;
|
||||
unsafe fn destroy_acceleration_structure(
|
||||
&self,
|
||||
acceleration_structure: Box<dyn DynAccelerationStructure>,
|
||||
);
|
||||
fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8>;
|
||||
|
||||
fn get_internal_counters(&self) -> wgt::HalCounters;
|
||||
fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport>;
|
||||
|
||||
fn check_if_oom(&self) -> Result<(), DeviceError>;
|
||||
}
|
||||
|
||||
impl<D: Device + DynResource> DynDevice for D {
|
||||
unsafe fn create_buffer(
|
||||
&self,
|
||||
desc: &BufferDescriptor,
|
||||
) -> Result<Box<dyn DynBuffer>, DeviceError> {
|
||||
unsafe { D::create_buffer(self, desc) }.map(|b| -> Box<dyn DynBuffer> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_buffer(&self, buffer: Box<dyn DynBuffer>) {
|
||||
unsafe { D::destroy_buffer(self, buffer.unbox()) };
|
||||
}
|
||||
unsafe fn add_raw_buffer(&self, buffer: &dyn DynBuffer) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { D::add_raw_buffer(self, buffer) };
|
||||
}
|
||||
|
||||
unsafe fn map_buffer(
|
||||
&self,
|
||||
buffer: &dyn DynBuffer,
|
||||
range: MemoryRange,
|
||||
) -> Result<BufferMapping, DeviceError> {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { D::map_buffer(self, buffer, range) }
|
||||
}
|
||||
|
||||
unsafe fn unmap_buffer(&self, buffer: &dyn DynBuffer) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { D::unmap_buffer(self, buffer) }
|
||||
}
|
||||
|
||||
unsafe fn flush_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { D::flush_mapped_ranges(self, buffer, ranges.iter().cloned()) }
|
||||
}
|
||||
|
||||
unsafe fn invalidate_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { D::invalidate_mapped_ranges(self, buffer, ranges.iter().cloned()) }
|
||||
}
|
||||
|
||||
unsafe fn create_texture(
|
||||
&self,
|
||||
desc: &TextureDescriptor,
|
||||
) -> Result<Box<dyn DynTexture>, DeviceError> {
|
||||
unsafe { D::create_texture(self, desc) }.map(|b| {
|
||||
let boxed_texture: Box<<D::A as Api>::Texture> = Box::new(b);
|
||||
let boxed_texture: Box<dyn DynTexture> = boxed_texture;
|
||||
boxed_texture
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn destroy_texture(&self, texture: Box<dyn DynTexture>) {
|
||||
unsafe { D::destroy_texture(self, texture.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn add_raw_texture(&self, texture: &dyn DynTexture) {
|
||||
let texture = texture.expect_downcast_ref();
|
||||
unsafe { D::add_raw_texture(self, texture) };
|
||||
}
|
||||
|
||||
unsafe fn create_texture_view(
|
||||
&self,
|
||||
texture: &dyn DynTexture,
|
||||
desc: &TextureViewDescriptor,
|
||||
) -> Result<Box<dyn DynTextureView>, DeviceError> {
|
||||
let texture = texture.expect_downcast_ref();
|
||||
unsafe { D::create_texture_view(self, texture, desc) }.map(|b| {
|
||||
let boxed_texture_view: Box<<D::A as Api>::TextureView> = Box::new(b);
|
||||
let boxed_texture_view: Box<dyn DynTextureView> = boxed_texture_view;
|
||||
boxed_texture_view
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn destroy_texture_view(&self, view: Box<dyn DynTextureView>) {
|
||||
unsafe { D::destroy_texture_view(self, view.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_sampler(
|
||||
&self,
|
||||
desc: &SamplerDescriptor,
|
||||
) -> Result<Box<dyn DynSampler>, DeviceError> {
|
||||
unsafe { D::create_sampler(self, desc) }.map(|b| {
|
||||
let boxed_sampler: Box<<D::A as Api>::Sampler> = Box::new(b);
|
||||
let boxed_sampler: Box<dyn DynSampler> = boxed_sampler;
|
||||
boxed_sampler
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn destroy_sampler(&self, sampler: Box<dyn DynSampler>) {
|
||||
unsafe { D::destroy_sampler(self, sampler.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_command_encoder(
|
||||
&self,
|
||||
desc: &CommandEncoderDescriptor<'_, dyn DynQueue>,
|
||||
) -> Result<Box<dyn DynCommandEncoder>, DeviceError> {
|
||||
let desc = CommandEncoderDescriptor {
|
||||
label: desc.label,
|
||||
queue: desc.queue.expect_downcast_ref(),
|
||||
};
|
||||
unsafe { D::create_command_encoder(self, &desc) }
|
||||
.map(|b| -> Box<dyn DynCommandEncoder> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn create_bind_group_layout(
|
||||
&self,
|
||||
desc: &BindGroupLayoutDescriptor,
|
||||
) -> Result<Box<dyn DynBindGroupLayout>, DeviceError> {
|
||||
unsafe { D::create_bind_group_layout(self, desc) }
|
||||
.map(|b| -> Box<dyn DynBindGroupLayout> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_bind_group_layout(&self, bg_layout: Box<dyn DynBindGroupLayout>) {
|
||||
unsafe { D::destroy_bind_group_layout(self, bg_layout.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_pipeline_layout(
|
||||
&self,
|
||||
desc: &PipelineLayoutDescriptor<dyn DynBindGroupLayout>,
|
||||
) -> Result<Box<dyn DynPipelineLayout>, DeviceError> {
|
||||
let bind_group_layouts: Vec<_> = desc
|
||||
.bind_group_layouts
|
||||
.iter()
|
||||
.map(|bgl| bgl.map(|bgl| bgl.expect_downcast_ref()))
|
||||
.collect();
|
||||
let desc = PipelineLayoutDescriptor {
|
||||
label: desc.label,
|
||||
bind_group_layouts: &bind_group_layouts,
|
||||
immediate_size: desc.immediate_size,
|
||||
flags: desc.flags,
|
||||
};
|
||||
|
||||
unsafe { D::create_pipeline_layout(self, &desc) }
|
||||
.map(|b| -> Box<dyn DynPipelineLayout> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_pipeline_layout(&self, pipeline_layout: Box<dyn DynPipelineLayout>) {
|
||||
unsafe { D::destroy_pipeline_layout(self, pipeline_layout.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_bind_group(
|
||||
&self,
|
||||
desc: &BindGroupDescriptor<
|
||||
dyn DynBindGroupLayout,
|
||||
dyn DynBuffer,
|
||||
dyn DynSampler,
|
||||
dyn DynTextureView,
|
||||
dyn DynAccelerationStructure,
|
||||
>,
|
||||
) -> Result<Box<dyn DynBindGroup>, DeviceError> {
|
||||
let buffers: Vec<_> = desc
|
||||
.buffers
|
||||
.iter()
|
||||
.map(|b| b.clone().expect_downcast())
|
||||
.collect();
|
||||
let samplers: Vec<_> = desc
|
||||
.samplers
|
||||
.iter()
|
||||
.map(|s| s.expect_downcast_ref())
|
||||
.collect();
|
||||
let textures: Vec<_> = desc
|
||||
.textures
|
||||
.iter()
|
||||
.map(|t| t.clone().expect_downcast())
|
||||
.collect();
|
||||
let acceleration_structures: Vec<_> = desc
|
||||
.acceleration_structures
|
||||
.iter()
|
||||
.map(|a| a.expect_downcast_ref())
|
||||
.collect();
|
||||
let external_textures: Vec<_> = desc
|
||||
.external_textures
|
||||
.iter()
|
||||
.map(|et| et.clone().expect_downcast())
|
||||
.collect();
|
||||
|
||||
let desc = BindGroupDescriptor {
|
||||
label: desc.label.to_owned(),
|
||||
layout: desc.layout.expect_downcast_ref(),
|
||||
buffers: &buffers,
|
||||
samplers: &samplers,
|
||||
textures: &textures,
|
||||
entries: desc.entries,
|
||||
acceleration_structures: &acceleration_structures,
|
||||
external_textures: &external_textures,
|
||||
};
|
||||
|
||||
unsafe { D::create_bind_group(self, &desc) }
|
||||
.map(|b| -> Box<dyn DynBindGroup> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_bind_group(&self, group: Box<dyn DynBindGroup>) {
|
||||
unsafe { D::destroy_bind_group(self, group.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_shader_module(
|
||||
&self,
|
||||
desc: &ShaderModuleDescriptor,
|
||||
shader: ShaderInput,
|
||||
) -> Result<Box<dyn DynShaderModule>, ShaderError> {
|
||||
unsafe { D::create_shader_module(self, desc, shader) }
|
||||
.map(|b| -> Box<dyn DynShaderModule> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_shader_module(&self, module: Box<dyn DynShaderModule>) {
|
||||
unsafe { D::destroy_shader_module(self, module.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_render_pipeline(
|
||||
&self,
|
||||
desc: &RenderPipelineDescriptor<
|
||||
dyn DynPipelineLayout,
|
||||
dyn DynShaderModule,
|
||||
dyn DynPipelineCache,
|
||||
>,
|
||||
) -> Result<Box<dyn DynRenderPipeline>, PipelineError> {
|
||||
let desc = RenderPipelineDescriptor {
|
||||
label: desc.label,
|
||||
layout: desc.layout.expect_downcast_ref(),
|
||||
vertex_processor: match &desc.vertex_processor {
|
||||
crate::VertexProcessor::Standard {
|
||||
vertex_buffers,
|
||||
vertex_stage,
|
||||
} => crate::VertexProcessor::Standard {
|
||||
vertex_buffers,
|
||||
vertex_stage: vertex_stage.clone().expect_downcast(),
|
||||
},
|
||||
crate::VertexProcessor::Mesh {
|
||||
task_stage: task,
|
||||
mesh_stage: mesh,
|
||||
} => crate::VertexProcessor::Mesh {
|
||||
task_stage: task.as_ref().map(|a| a.clone().expect_downcast()),
|
||||
mesh_stage: mesh.clone().expect_downcast(),
|
||||
},
|
||||
},
|
||||
primitive: desc.primitive,
|
||||
depth_stencil: desc.depth_stencil.clone(),
|
||||
multisample: desc.multisample,
|
||||
fragment_stage: desc.fragment_stage.clone().map(|f| f.expect_downcast()),
|
||||
color_targets: desc.color_targets,
|
||||
multiview_mask: desc.multiview_mask,
|
||||
cache: desc.cache.map(|c| c.expect_downcast_ref()),
|
||||
};
|
||||
|
||||
unsafe { D::create_render_pipeline(self, &desc) }
|
||||
.map(|b| -> Box<dyn DynRenderPipeline> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_render_pipeline(&self, pipeline: Box<dyn DynRenderPipeline>) {
|
||||
unsafe { D::destroy_render_pipeline(self, pipeline.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_compute_pipeline(
|
||||
&self,
|
||||
desc: &ComputePipelineDescriptor<
|
||||
dyn DynPipelineLayout,
|
||||
dyn DynShaderModule,
|
||||
dyn DynPipelineCache,
|
||||
>,
|
||||
) -> Result<Box<dyn DynComputePipeline>, PipelineError> {
|
||||
let desc = ComputePipelineDescriptor {
|
||||
label: desc.label,
|
||||
layout: desc.layout.expect_downcast_ref(),
|
||||
stage: desc.stage.clone().expect_downcast(),
|
||||
cache: desc.cache.as_ref().map(|c| c.expect_downcast_ref()),
|
||||
};
|
||||
|
||||
unsafe { D::create_compute_pipeline(self, &desc) }
|
||||
.map(|b| -> Box<dyn DynComputePipeline> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_compute_pipeline(&self, pipeline: Box<dyn DynComputePipeline>) {
|
||||
unsafe { D::destroy_compute_pipeline(self, pipeline.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_ray_tracing_pipeline(
|
||||
&self,
|
||||
desc: &RayTracingPipelineDescriptor<
|
||||
dyn DynPipelineLayout,
|
||||
dyn DynShaderModule,
|
||||
dyn DynPipelineCache,
|
||||
>,
|
||||
) -> Result<Box<dyn DynRayTracingPipeline>, PipelineError> {
|
||||
let ray_intersection: Vec<_> = desc
|
||||
.intersection
|
||||
.iter()
|
||||
.map(|stage| RayObjectIntersectionState {
|
||||
closest_hit: stage.closest_hit.clone().expect_downcast(),
|
||||
any_hit: stage
|
||||
.any_hit
|
||||
.as_ref()
|
||||
.map(|stage| stage.clone().expect_downcast()),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let desc = RayTracingPipelineDescriptor {
|
||||
label: desc.label,
|
||||
layout: desc.layout.expect_downcast_ref(),
|
||||
ray_generation: desc.ray_generation.clone().expect_downcast(),
|
||||
miss: desc.miss.clone().expect_downcast(),
|
||||
intersection: &ray_intersection,
|
||||
max_recursion_depth: desc.max_recursion_depth,
|
||||
cache: desc.cache.as_ref().map(|c| c.expect_downcast_ref()),
|
||||
};
|
||||
|
||||
unsafe { D::create_ray_tracing_pipeline(self, &desc) }
|
||||
.map(|b| -> Box<dyn DynRayTracingPipeline> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: Box<dyn DynRayTracingPipeline>) {
|
||||
unsafe {
|
||||
D::destroy_ray_tracing_pipeline(self, pipeline.unbox());
|
||||
};
|
||||
}
|
||||
unsafe fn get_raytracing_pipeline_group_data(
|
||||
&self,
|
||||
pipeline: &dyn DynRayTracingPipeline,
|
||||
groups: core::ops::Range<u32>,
|
||||
) -> Result<Vec<u8>, DeviceError> {
|
||||
unsafe {
|
||||
D::get_raytracing_pipeline_group_data(self, pipeline.expect_downcast_ref(), groups)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn create_pipeline_cache(
|
||||
&self,
|
||||
desc: &PipelineCacheDescriptor<'_>,
|
||||
) -> Result<Box<dyn DynPipelineCache>, PipelineCacheError> {
|
||||
unsafe { D::create_pipeline_cache(self, desc) }
|
||||
.map(|b| -> Box<dyn DynPipelineCache> { Box::new(b) })
|
||||
}
|
||||
|
||||
fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> {
|
||||
D::pipeline_cache_validation_key(self)
|
||||
}
|
||||
|
||||
unsafe fn destroy_pipeline_cache(&self, pipeline_cache: Box<dyn DynPipelineCache>) {
|
||||
unsafe { D::destroy_pipeline_cache(self, pipeline_cache.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_query_set(
|
||||
&self,
|
||||
desc: &wgt::QuerySetDescriptor<Label>,
|
||||
) -> Result<Box<dyn DynQuerySet>, DeviceError> {
|
||||
unsafe { D::create_query_set(self, desc) }.map(|b| -> Box<dyn DynQuerySet> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_query_set(&self, query_set: Box<dyn DynQuerySet>) {
|
||||
unsafe { D::destroy_query_set(self, query_set.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn create_fence(&self) -> Result<Box<dyn DynFence>, DeviceError> {
|
||||
unsafe { D::create_fence(self) }.map(|b| -> Box<dyn DynFence> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn destroy_fence(&self, fence: Box<dyn DynFence>) {
|
||||
unsafe { D::destroy_fence(self, fence.unbox()) };
|
||||
}
|
||||
|
||||
unsafe fn get_fence_value(&self, fence: &dyn DynFence) -> Result<FenceValue, DeviceError> {
|
||||
let fence = fence.expect_downcast_ref();
|
||||
unsafe { D::get_fence_value(self, fence) }
|
||||
}
|
||||
|
||||
unsafe fn wait(
|
||||
&self,
|
||||
fence: &dyn DynFence,
|
||||
value: FenceValue,
|
||||
timeout: Option<core::time::Duration>,
|
||||
) -> Result<bool, DeviceError> {
|
||||
let fence = fence.expect_downcast_ref();
|
||||
unsafe { D::wait(self, fence, value, timeout) }
|
||||
}
|
||||
|
||||
unsafe fn start_graphics_debugger_capture(&self) -> bool {
|
||||
unsafe { D::start_graphics_debugger_capture(self) }
|
||||
}
|
||||
|
||||
unsafe fn stop_graphics_debugger_capture(&self) {
|
||||
unsafe { D::stop_graphics_debugger_capture(self) }
|
||||
}
|
||||
|
||||
unsafe fn pipeline_cache_get_data(&self, cache: &dyn DynPipelineCache) -> Option<Vec<u8>> {
|
||||
let cache = cache.expect_downcast_ref();
|
||||
unsafe { D::pipeline_cache_get_data(self, cache) }
|
||||
}
|
||||
|
||||
unsafe fn create_acceleration_structure(
|
||||
&self,
|
||||
desc: &AccelerationStructureDescriptor,
|
||||
) -> Result<Box<dyn DynAccelerationStructure>, DeviceError> {
|
||||
unsafe { D::create_acceleration_structure(self, desc) }
|
||||
.map(|b| -> Box<dyn DynAccelerationStructure> { Box::new(b) })
|
||||
}
|
||||
|
||||
unsafe fn get_acceleration_structure_build_sizes(
|
||||
&self,
|
||||
desc: &GetAccelerationStructureBuildSizesDescriptor<dyn DynBuffer>,
|
||||
) -> AccelerationStructureBuildSizes {
|
||||
let entries = desc.entries.expect_downcast();
|
||||
let desc = GetAccelerationStructureBuildSizesDescriptor {
|
||||
entries: &entries,
|
||||
flags: desc.flags,
|
||||
};
|
||||
unsafe { D::get_acceleration_structure_build_sizes(self, &desc) }
|
||||
}
|
||||
|
||||
unsafe fn get_acceleration_structure_device_address(
|
||||
&self,
|
||||
acceleration_structure: &dyn DynAccelerationStructure,
|
||||
) -> wgt::BufferAddress {
|
||||
let acceleration_structure = acceleration_structure.expect_downcast_ref();
|
||||
unsafe { D::get_acceleration_structure_device_address(self, acceleration_structure) }
|
||||
}
|
||||
|
||||
unsafe fn destroy_acceleration_structure(
|
||||
&self,
|
||||
acceleration_structure: Box<dyn DynAccelerationStructure>,
|
||||
) {
|
||||
unsafe { D::destroy_acceleration_structure(self, acceleration_structure.unbox()) }
|
||||
}
|
||||
|
||||
fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> {
|
||||
D::tlas_instance_to_bytes(self, instance)
|
||||
}
|
||||
|
||||
fn get_internal_counters(&self) -> wgt::HalCounters {
|
||||
D::get_internal_counters(self)
|
||||
}
|
||||
|
||||
fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
|
||||
D::generate_allocator_report(self)
|
||||
}
|
||||
|
||||
fn check_if_oom(&self) -> Result<(), DeviceError> {
|
||||
D::check_if_oom(self)
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
use alloc::{boxed::Box, vec::Vec};
|
||||
|
||||
use crate::{Api, Capabilities, ExposedAdapter, Instance, InstanceError};
|
||||
|
||||
use super::{DynAdapter, DynResource, DynResourceExt as _, DynSurface};
|
||||
|
||||
#[expect(missing_debug_implementations, reason = "dyn")]
|
||||
pub struct DynExposedAdapter {
|
||||
pub adapter: Box<dyn DynAdapter>,
|
||||
pub info: wgt::AdapterInfo,
|
||||
pub features: wgt::Features,
|
||||
pub capabilities: Capabilities,
|
||||
}
|
||||
|
||||
impl DynExposedAdapter {
|
||||
/// Returns the backend this adapter is using.
|
||||
pub fn backend(&self) -> wgt::Backend {
|
||||
self.info.backend
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Api> From<ExposedAdapter<A>> for DynExposedAdapter {
|
||||
fn from(exposed_adapter: ExposedAdapter<A>) -> Self {
|
||||
Self {
|
||||
adapter: Box::new(exposed_adapter.adapter),
|
||||
info: exposed_adapter.info,
|
||||
features: exposed_adapter.features,
|
||||
capabilities: exposed_adapter.capabilities,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DynInstance: DynResource {
|
||||
unsafe fn create_surface(
|
||||
&self,
|
||||
display_handle: raw_window_handle::RawDisplayHandle,
|
||||
window_handle: raw_window_handle::RawWindowHandle,
|
||||
) -> Result<Box<dyn DynSurface>, InstanceError>;
|
||||
|
||||
unsafe fn enumerate_adapters(
|
||||
&self,
|
||||
surface_hint: Option<&dyn DynSurface>,
|
||||
) -> Vec<DynExposedAdapter>;
|
||||
}
|
||||
|
||||
impl<I: Instance + DynResource> DynInstance for I {
|
||||
unsafe fn create_surface(
|
||||
&self,
|
||||
display_handle: raw_window_handle::RawDisplayHandle,
|
||||
window_handle: raw_window_handle::RawWindowHandle,
|
||||
) -> Result<Box<dyn DynSurface>, InstanceError> {
|
||||
unsafe { I::create_surface(self, display_handle, window_handle) }
|
||||
.map(|surface| -> Box<dyn DynSurface> { Box::new(surface) })
|
||||
}
|
||||
|
||||
unsafe fn enumerate_adapters(
|
||||
&self,
|
||||
surface_hint: Option<&dyn DynSurface>,
|
||||
) -> Vec<DynExposedAdapter> {
|
||||
let surface_hint = surface_hint.map(|s| s.expect_downcast_ref());
|
||||
unsafe { I::enumerate_adapters(self, surface_hint) }
|
||||
.into_iter()
|
||||
.map(|exposed| DynExposedAdapter {
|
||||
adapter: Box::new(exposed.adapter),
|
||||
info: exposed.info,
|
||||
features: exposed.features,
|
||||
capabilities: exposed.capabilities,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
Vendored
+212
@@ -0,0 +1,212 @@
|
||||
mod adapter;
|
||||
mod command;
|
||||
mod device;
|
||||
mod instance;
|
||||
mod queue;
|
||||
mod surface;
|
||||
|
||||
pub use adapter::{DynAdapter, DynOpenDevice};
|
||||
pub use command::DynCommandEncoder;
|
||||
pub use device::DynDevice;
|
||||
pub use instance::{DynExposedAdapter, DynInstance};
|
||||
pub use queue::DynQueue;
|
||||
pub use surface::{DynAcquiredSurfaceTexture, DynSurface};
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use core::{
|
||||
any::{Any, TypeId},
|
||||
fmt,
|
||||
};
|
||||
|
||||
use wgt::WasmNotSendSync;
|
||||
|
||||
use crate::{
|
||||
AccelerationStructureAABBs, AccelerationStructureEntries, AccelerationStructureInstances,
|
||||
AccelerationStructureTriangleIndices, AccelerationStructureTriangleTransform,
|
||||
AccelerationStructureTriangles, BufferBinding, ExternalTextureBinding, ProgrammableStage,
|
||||
TextureBinding,
|
||||
};
|
||||
|
||||
/// Base trait for all resources, allows downcasting via [`Any`].
|
||||
pub trait DynResource: Any + WasmNotSendSync + 'static {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any;
|
||||
}
|
||||
|
||||
/// Utility macro for implementing `DynResource` for a list of types.
|
||||
macro_rules! impl_dyn_resource {
|
||||
($($type:ty),*) => {
|
||||
$(
|
||||
impl crate::DynResource for $type {
|
||||
fn as_any(&self) -> &dyn ::core::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
pub(crate) use impl_dyn_resource;
|
||||
|
||||
/// Extension trait for `DynResource` used by implementations of various dynamic resource traits.
|
||||
trait DynResourceExt {
|
||||
/// # Panics
|
||||
///
|
||||
/// - Panics if `self` is not downcastable to `T`.
|
||||
fn expect_downcast_ref<T: DynResource>(&self) -> &T;
|
||||
|
||||
/// Unboxes a `Box<dyn DynResource>` to a concrete type.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// - `self` must be the correct concrete type.
|
||||
unsafe fn unbox<T: DynResource + 'static>(self: Box<Self>) -> T;
|
||||
}
|
||||
|
||||
impl<R: DynResource + ?Sized> DynResourceExt for R {
|
||||
fn expect_downcast_ref<'a, T: DynResource>(&'a self) -> &'a T {
|
||||
self.as_any()
|
||||
.downcast_ref()
|
||||
.expect("Resource doesn't have the expected backend type.")
|
||||
}
|
||||
|
||||
unsafe fn unbox<T: DynResource + 'static>(self: Box<Self>) -> T {
|
||||
debug_assert!(
|
||||
<Self as Any>::type_id(self.as_ref()) == TypeId::of::<T>(),
|
||||
"Resource doesn't have the expected type, expected {:?}, got {:?}",
|
||||
TypeId::of::<T>(),
|
||||
<Self as Any>::type_id(self.as_ref())
|
||||
);
|
||||
|
||||
let casted_ptr = Box::into_raw(self).cast::<T>();
|
||||
// SAFETY: This is adheres to the safety contract of `Box::from_raw` because:
|
||||
//
|
||||
// - We are casting the value of a previously `Box`ed value, which guarantees:
|
||||
// - `casted_ptr` is not null.
|
||||
// - `casted_ptr` is valid for reads and writes, though by itself this does not mean
|
||||
// valid reads and writes for `T` (read on for that).
|
||||
// - We don't change the allocator.
|
||||
// - The contract of `Box::from_raw` requires that an initialized and aligned `T` is stored
|
||||
// within `casted_ptr`.
|
||||
*unsafe { Box::from_raw(casted_ptr) }
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DynAccelerationStructure: DynResource + fmt::Debug {}
|
||||
pub trait DynBindGroup: DynResource + fmt::Debug {}
|
||||
pub trait DynBindGroupLayout: DynResource + fmt::Debug {}
|
||||
pub trait DynBuffer: DynResource + fmt::Debug {}
|
||||
pub trait DynCommandBuffer: DynResource + fmt::Debug {}
|
||||
pub trait DynComputePipeline: DynResource + fmt::Debug {}
|
||||
pub trait DynFence: DynResource + fmt::Debug {}
|
||||
pub trait DynPipelineCache: DynResource + fmt::Debug {}
|
||||
pub trait DynPipelineLayout: DynResource + fmt::Debug {}
|
||||
pub trait DynQuerySet: DynResource + fmt::Debug {}
|
||||
pub trait DynRenderPipeline: DynResource + fmt::Debug {}
|
||||
pub trait DynRayTracingPipeline: DynResource + fmt::Debug {}
|
||||
pub trait DynSampler: DynResource + fmt::Debug {}
|
||||
pub trait DynShaderModule: DynResource + fmt::Debug {}
|
||||
pub trait DynSurfaceTexture:
|
||||
DynResource + core::borrow::Borrow<dyn DynTexture> + fmt::Debug
|
||||
{
|
||||
}
|
||||
pub trait DynTexture: DynResource + fmt::Debug {}
|
||||
pub trait DynTextureView: DynResource + fmt::Debug {}
|
||||
|
||||
impl<'a> BufferBinding<'a, dyn DynBuffer> {
|
||||
pub fn expect_downcast<B: DynBuffer>(self) -> BufferBinding<'a, B> {
|
||||
BufferBinding {
|
||||
buffer: self.buffer.expect_downcast_ref(),
|
||||
offset: self.offset,
|
||||
size: self.size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TextureBinding<'a, dyn DynTextureView> {
|
||||
pub fn expect_downcast<T: DynTextureView>(self) -> TextureBinding<'a, T> {
|
||||
TextureBinding {
|
||||
view: self.view.expect_downcast_ref(),
|
||||
usage: self.usage,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ExternalTextureBinding<'a, dyn DynBuffer, dyn DynTextureView> {
|
||||
pub fn expect_downcast<B: DynBuffer, T: DynTextureView>(
|
||||
self,
|
||||
) -> ExternalTextureBinding<'a, B, T> {
|
||||
let planes = self.planes.map(|plane| plane.expect_downcast());
|
||||
let params = self.params.expect_downcast();
|
||||
ExternalTextureBinding { planes, params }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ProgrammableStage<'a, dyn DynShaderModule> {
|
||||
fn expect_downcast<T: DynShaderModule>(self) -> ProgrammableStage<'a, T> {
|
||||
ProgrammableStage {
|
||||
module: self.module.expect_downcast_ref(),
|
||||
entry_point: self.entry_point,
|
||||
constants: self.constants,
|
||||
zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AccelerationStructureEntries<'a, dyn DynBuffer> {
|
||||
fn expect_downcast<B: DynBuffer>(&self) -> AccelerationStructureEntries<'a, B> {
|
||||
match self {
|
||||
AccelerationStructureEntries::Instances(instances) => {
|
||||
AccelerationStructureEntries::Instances(AccelerationStructureInstances {
|
||||
buffer: instances.buffer.map(|b| b.expect_downcast_ref()),
|
||||
offset: instances.offset,
|
||||
count: instances.count,
|
||||
})
|
||||
}
|
||||
AccelerationStructureEntries::Triangles(triangles) => {
|
||||
AccelerationStructureEntries::Triangles(
|
||||
triangles
|
||||
.iter()
|
||||
.map(|t| AccelerationStructureTriangles {
|
||||
vertex_buffer: t.vertex_buffer.map(|b| b.expect_downcast_ref()),
|
||||
vertex_format: t.vertex_format,
|
||||
first_vertex: t.first_vertex,
|
||||
vertex_count: t.vertex_count,
|
||||
vertex_stride: t.vertex_stride,
|
||||
indices: t.indices.as_ref().map(|i| {
|
||||
AccelerationStructureTriangleIndices {
|
||||
buffer: i.buffer.map(|b| b.expect_downcast_ref()),
|
||||
format: i.format,
|
||||
offset: i.offset,
|
||||
count: i.count,
|
||||
}
|
||||
}),
|
||||
transform: t.transform.as_ref().map(|t| {
|
||||
AccelerationStructureTriangleTransform {
|
||||
buffer: t.buffer.expect_downcast_ref(),
|
||||
offset: t.offset,
|
||||
}
|
||||
}),
|
||||
flags: t.flags,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
AccelerationStructureEntries::AABBs(entries) => AccelerationStructureEntries::AABBs(
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| AccelerationStructureAABBs {
|
||||
buffer: e.buffer.map(|b| b.expect_downcast_ref()),
|
||||
offset: e.offset,
|
||||
count: e.count,
|
||||
stride: e.stride,
|
||||
flags: e.flags,
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+61
@@ -0,0 +1,61 @@
|
||||
use alloc::{boxed::Box, vec::Vec};
|
||||
|
||||
use crate::{
|
||||
DeviceError, DynCommandBuffer, DynFence, DynResource, DynSurface, DynSurfaceTexture,
|
||||
FenceValue, Queue, SurfaceError,
|
||||
};
|
||||
|
||||
use super::DynResourceExt as _;
|
||||
|
||||
pub trait DynQueue: DynResource {
|
||||
unsafe fn submit(
|
||||
&self,
|
||||
command_buffers: &[&dyn DynCommandBuffer],
|
||||
surface_textures: &[&dyn DynSurfaceTexture],
|
||||
signal_fence: (&dyn DynFence, FenceValue),
|
||||
) -> Result<(), DeviceError>;
|
||||
unsafe fn present(
|
||||
&self,
|
||||
surface: &dyn DynSurface,
|
||||
texture: Box<dyn DynSurfaceTexture>,
|
||||
) -> Result<(), SurfaceError>;
|
||||
unsafe fn get_timestamp_period(&self) -> f32;
|
||||
unsafe fn wait_for_idle(&self) -> Result<(), DeviceError>;
|
||||
}
|
||||
|
||||
impl<Q: Queue + DynResource> DynQueue for Q {
|
||||
unsafe fn submit(
|
||||
&self,
|
||||
command_buffers: &[&dyn DynCommandBuffer],
|
||||
surface_textures: &[&dyn DynSurfaceTexture],
|
||||
signal_fence: (&dyn DynFence, FenceValue),
|
||||
) -> Result<(), DeviceError> {
|
||||
let command_buffers = command_buffers
|
||||
.iter()
|
||||
.map(|cb| (*cb).expect_downcast_ref())
|
||||
.collect::<Vec<_>>();
|
||||
let surface_textures = surface_textures
|
||||
.iter()
|
||||
.map(|surface| (*surface).expect_downcast_ref())
|
||||
.collect::<Vec<_>>();
|
||||
let signal_fence = (signal_fence.0.expect_downcast_ref(), signal_fence.1);
|
||||
unsafe { Q::submit(self, &command_buffers, &surface_textures, signal_fence) }
|
||||
}
|
||||
|
||||
unsafe fn present(
|
||||
&self,
|
||||
surface: &dyn DynSurface,
|
||||
texture: Box<dyn DynSurfaceTexture>,
|
||||
) -> Result<(), SurfaceError> {
|
||||
let surface = surface.expect_downcast_ref();
|
||||
unsafe { Q::present(self, surface, texture.unbox()) }
|
||||
}
|
||||
|
||||
unsafe fn get_timestamp_period(&self) -> f32 {
|
||||
unsafe { Q::get_timestamp_period(self) }
|
||||
}
|
||||
|
||||
unsafe fn wait_for_idle(&self) -> Result<(), DeviceError> {
|
||||
unsafe { Q::wait_for_idle(self) }
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
use alloc::boxed::Box;
|
||||
use core::time::Duration;
|
||||
|
||||
use crate::{
|
||||
DynDevice, DynFence, DynResource, DynSurfaceTexture, Surface, SurfaceConfiguration,
|
||||
SurfaceError,
|
||||
};
|
||||
|
||||
use super::DynResourceExt as _;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DynAcquiredSurfaceTexture {
|
||||
pub texture: Box<dyn DynSurfaceTexture>,
|
||||
/// The presentation configuration no longer matches
|
||||
/// the surface properties exactly, but can still be used to present
|
||||
/// to the surface successfully.
|
||||
pub suboptimal: bool,
|
||||
}
|
||||
|
||||
pub trait DynSurface: DynResource {
|
||||
unsafe fn configure(
|
||||
&self,
|
||||
device: &dyn DynDevice,
|
||||
config: &SurfaceConfiguration,
|
||||
) -> Result<(), SurfaceError>;
|
||||
|
||||
unsafe fn unconfigure(&self, device: &dyn DynDevice);
|
||||
|
||||
unsafe fn acquire_texture(
|
||||
&self,
|
||||
timeout: Option<Duration>,
|
||||
fence: &dyn DynFence,
|
||||
) -> Result<DynAcquiredSurfaceTexture, SurfaceError>;
|
||||
|
||||
unsafe fn discard_texture(&self, texture: Box<dyn DynSurfaceTexture>);
|
||||
}
|
||||
|
||||
impl<S: Surface + DynResource> DynSurface for S {
|
||||
unsafe fn configure(
|
||||
&self,
|
||||
device: &dyn DynDevice,
|
||||
config: &SurfaceConfiguration,
|
||||
) -> Result<(), SurfaceError> {
|
||||
let device = device.expect_downcast_ref();
|
||||
unsafe { S::configure(self, device, config) }
|
||||
}
|
||||
|
||||
unsafe fn unconfigure(&self, device: &dyn DynDevice) {
|
||||
let device = device.expect_downcast_ref();
|
||||
unsafe { S::unconfigure(self, device) }
|
||||
}
|
||||
|
||||
unsafe fn acquire_texture(
|
||||
&self,
|
||||
timeout: Option<Duration>,
|
||||
fence: &dyn DynFence,
|
||||
) -> Result<DynAcquiredSurfaceTexture, SurfaceError> {
|
||||
let fence = fence.expect_downcast_ref();
|
||||
unsafe { S::acquire_texture(self, timeout, fence) }.map(|ast| {
|
||||
let texture = Box::new(ast.texture);
|
||||
let suboptimal = ast.suboptimal;
|
||||
DynAcquiredSurfaceTexture {
|
||||
texture,
|
||||
suboptimal,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn discard_texture(&self, texture: Box<dyn DynSurfaceTexture>) {
|
||||
unsafe { S::discard_texture(self, texture.unbox()) }
|
||||
}
|
||||
}
|
||||
Vendored
+1470
File diff suppressed because it is too large
Load Diff
Vendored
+1345
File diff suppressed because it is too large
Load Diff
Vendored
+430
@@ -0,0 +1,430 @@
|
||||
impl super::AdapterShared {
|
||||
pub(super) fn describe_texture_format(
|
||||
&self,
|
||||
texture_format: wgt::TextureFormat,
|
||||
) -> super::TextureFormatDesc {
|
||||
use wgt::TextureFormat as Tf;
|
||||
use wgt::{AstcBlock, AstcChannel};
|
||||
|
||||
let (internal, external, data_type) = match texture_format {
|
||||
Tf::R8Unorm => (glow::R8, glow::RED, glow::UNSIGNED_BYTE),
|
||||
Tf::R8Snorm => (glow::R8_SNORM, glow::RED, glow::BYTE),
|
||||
Tf::R8Uint => (glow::R8UI, glow::RED_INTEGER, glow::UNSIGNED_BYTE),
|
||||
Tf::R8Sint => (glow::R8I, glow::RED_INTEGER, glow::BYTE),
|
||||
Tf::R16Uint => (glow::R16UI, glow::RED_INTEGER, glow::UNSIGNED_SHORT),
|
||||
Tf::R16Sint => (glow::R16I, glow::RED_INTEGER, glow::SHORT),
|
||||
Tf::R16Unorm => (glow::R16, glow::RED, glow::UNSIGNED_SHORT),
|
||||
Tf::R16Snorm => (glow::R16_SNORM, glow::RED, glow::SHORT),
|
||||
Tf::R16Float => (glow::R16F, glow::RED, glow::HALF_FLOAT),
|
||||
Tf::Rg8Unorm => (glow::RG8, glow::RG, glow::UNSIGNED_BYTE),
|
||||
Tf::Rg8Snorm => (glow::RG8_SNORM, glow::RG, glow::BYTE),
|
||||
Tf::Rg8Uint => (glow::RG8UI, glow::RG_INTEGER, glow::UNSIGNED_BYTE),
|
||||
Tf::Rg8Sint => (glow::RG8I, glow::RG_INTEGER, glow::BYTE),
|
||||
Tf::R32Uint => (glow::R32UI, glow::RED_INTEGER, glow::UNSIGNED_INT),
|
||||
Tf::R32Sint => (glow::R32I, glow::RED_INTEGER, glow::INT),
|
||||
Tf::R32Float => (glow::R32F, glow::RED, glow::FLOAT),
|
||||
Tf::Rg16Uint => (glow::RG16UI, glow::RG_INTEGER, glow::UNSIGNED_SHORT),
|
||||
Tf::Rg16Sint => (glow::RG16I, glow::RG_INTEGER, glow::SHORT),
|
||||
Tf::Rg16Unorm => (glow::RG16, glow::RG, glow::UNSIGNED_SHORT),
|
||||
Tf::Rg16Snorm => (glow::RG16_SNORM, glow::RG, glow::SHORT),
|
||||
Tf::Rg16Float => (glow::RG16F, glow::RG, glow::HALF_FLOAT),
|
||||
Tf::Rgba8Unorm => (glow::RGBA8, glow::RGBA, glow::UNSIGNED_BYTE),
|
||||
Tf::Rgba8UnormSrgb => (glow::SRGB8_ALPHA8, glow::RGBA, glow::UNSIGNED_BYTE),
|
||||
Tf::Bgra8UnormSrgb => (glow::SRGB8_ALPHA8, glow::BGRA, glow::UNSIGNED_BYTE), //TODO?
|
||||
Tf::Rgba8Snorm => (glow::RGBA8_SNORM, glow::RGBA, glow::BYTE),
|
||||
Tf::Bgra8Unorm => (glow::RGBA8, glow::BGRA, glow::UNSIGNED_BYTE), //TODO?
|
||||
Tf::Rgba8Uint => (glow::RGBA8UI, glow::RGBA_INTEGER, glow::UNSIGNED_BYTE),
|
||||
Tf::Rgba8Sint => (glow::RGBA8I, glow::RGBA_INTEGER, glow::BYTE),
|
||||
Tf::Rgb10a2Uint => (
|
||||
glow::RGB10_A2UI,
|
||||
glow::RGBA_INTEGER,
|
||||
glow::UNSIGNED_INT_2_10_10_10_REV,
|
||||
),
|
||||
Tf::Rgb10a2Unorm => (
|
||||
glow::RGB10_A2,
|
||||
glow::RGBA,
|
||||
glow::UNSIGNED_INT_2_10_10_10_REV,
|
||||
),
|
||||
Tf::Rg11b10Ufloat => (
|
||||
glow::R11F_G11F_B10F,
|
||||
glow::RGB,
|
||||
glow::UNSIGNED_INT_10F_11F_11F_REV,
|
||||
),
|
||||
Tf::R64Uint => (glow::RG32UI, glow::RED_INTEGER, glow::UNSIGNED_INT),
|
||||
Tf::Rg32Uint => (glow::RG32UI, glow::RG_INTEGER, glow::UNSIGNED_INT),
|
||||
Tf::Rg32Sint => (glow::RG32I, glow::RG_INTEGER, glow::INT),
|
||||
Tf::Rg32Float => (glow::RG32F, glow::RG, glow::FLOAT),
|
||||
Tf::Rgba16Uint => (glow::RGBA16UI, glow::RGBA_INTEGER, glow::UNSIGNED_SHORT),
|
||||
Tf::Rgba16Sint => (glow::RGBA16I, glow::RGBA_INTEGER, glow::SHORT),
|
||||
Tf::Rgba16Unorm => (glow::RGBA16, glow::RGBA, glow::UNSIGNED_SHORT),
|
||||
Tf::Rgba16Snorm => (glow::RGBA16_SNORM, glow::RGBA, glow::SHORT),
|
||||
Tf::Rgba16Float => (glow::RGBA16F, glow::RGBA, glow::HALF_FLOAT),
|
||||
Tf::Rgba32Uint => (glow::RGBA32UI, glow::RGBA_INTEGER, glow::UNSIGNED_INT),
|
||||
Tf::Rgba32Sint => (glow::RGBA32I, glow::RGBA_INTEGER, glow::INT),
|
||||
Tf::Rgba32Float => (glow::RGBA32F, glow::RGBA, glow::FLOAT),
|
||||
Tf::Stencil8 => (
|
||||
glow::STENCIL_INDEX8,
|
||||
glow::STENCIL_INDEX,
|
||||
glow::UNSIGNED_BYTE,
|
||||
),
|
||||
Tf::Depth16Unorm => (
|
||||
glow::DEPTH_COMPONENT16,
|
||||
glow::DEPTH_COMPONENT,
|
||||
glow::UNSIGNED_SHORT,
|
||||
),
|
||||
Tf::Depth32Float => (glow::DEPTH_COMPONENT32F, glow::DEPTH_COMPONENT, glow::FLOAT),
|
||||
Tf::Depth32FloatStencil8 => (
|
||||
glow::DEPTH32F_STENCIL8,
|
||||
glow::DEPTH_STENCIL,
|
||||
glow::FLOAT_32_UNSIGNED_INT_24_8_REV,
|
||||
),
|
||||
Tf::Depth24Plus => (
|
||||
glow::DEPTH_COMPONENT24,
|
||||
glow::DEPTH_COMPONENT,
|
||||
glow::UNSIGNED_INT,
|
||||
),
|
||||
Tf::Depth24PlusStencil8 => (
|
||||
glow::DEPTH24_STENCIL8,
|
||||
glow::DEPTH_STENCIL,
|
||||
glow::UNSIGNED_INT_24_8,
|
||||
),
|
||||
Tf::NV12 => unreachable!(),
|
||||
Tf::P010 => unreachable!(),
|
||||
Tf::Rgb9e5Ufloat => (glow::RGB9_E5, glow::RGB, glow::UNSIGNED_INT_5_9_9_9_REV),
|
||||
Tf::Bc1RgbaUnorm => (glow::COMPRESSED_RGBA_S3TC_DXT1_EXT, glow::RGBA, 0),
|
||||
Tf::Bc1RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, glow::RGBA, 0),
|
||||
Tf::Bc2RgbaUnorm => (glow::COMPRESSED_RGBA_S3TC_DXT3_EXT, glow::RGBA, 0),
|
||||
Tf::Bc2RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, glow::RGBA, 0),
|
||||
Tf::Bc3RgbaUnorm => (glow::COMPRESSED_RGBA_S3TC_DXT5_EXT, glow::RGBA, 0),
|
||||
Tf::Bc3RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, glow::RGBA, 0),
|
||||
Tf::Bc4RUnorm => (glow::COMPRESSED_RED_RGTC1, glow::RED, 0),
|
||||
Tf::Bc4RSnorm => (glow::COMPRESSED_SIGNED_RED_RGTC1, glow::RED, 0),
|
||||
Tf::Bc5RgUnorm => (glow::COMPRESSED_RG_RGTC2, glow::RG, 0),
|
||||
Tf::Bc5RgSnorm => (glow::COMPRESSED_SIGNED_RG_RGTC2, glow::RG, 0),
|
||||
Tf::Bc6hRgbUfloat => (glow::COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, glow::RGB, 0),
|
||||
Tf::Bc6hRgbFloat => (glow::COMPRESSED_RGB_BPTC_SIGNED_FLOAT, glow::RGB, 0),
|
||||
Tf::Bc7RgbaUnorm => (glow::COMPRESSED_RGBA_BPTC_UNORM, glow::RGBA, 0),
|
||||
Tf::Bc7RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_BPTC_UNORM, glow::RGBA, 0),
|
||||
Tf::Etc2Rgb8Unorm => (glow::COMPRESSED_RGB8_ETC2, glow::RGB, 0),
|
||||
Tf::Etc2Rgb8UnormSrgb => (glow::COMPRESSED_SRGB8_ETC2, glow::RGB, 0),
|
||||
Tf::Etc2Rgb8A1Unorm => (
|
||||
glow::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
|
||||
glow::RGBA,
|
||||
0,
|
||||
),
|
||||
Tf::Etc2Rgb8A1UnormSrgb => (
|
||||
glow::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,
|
||||
glow::RGBA,
|
||||
0,
|
||||
),
|
||||
Tf::Etc2Rgba8Unorm => (glow::COMPRESSED_RGBA8_ETC2_EAC, glow::RGBA, 0),
|
||||
Tf::Etc2Rgba8UnormSrgb => (glow::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, glow::RGBA, 0),
|
||||
Tf::EacR11Unorm => (glow::COMPRESSED_R11_EAC, glow::RED, 0),
|
||||
Tf::EacR11Snorm => (glow::COMPRESSED_SIGNED_R11_EAC, glow::RED, 0),
|
||||
Tf::EacRg11Unorm => (glow::COMPRESSED_RG11_EAC, glow::RG, 0),
|
||||
Tf::EacRg11Snorm => (glow::COMPRESSED_SIGNED_RG11_EAC, glow::RG, 0),
|
||||
Tf::Astc { block, channel } => match channel {
|
||||
AstcChannel::Unorm | AstcChannel::Hdr => match block {
|
||||
AstcBlock::B4x4 => (glow::COMPRESSED_RGBA_ASTC_4x4_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B5x4 => (glow::COMPRESSED_RGBA_ASTC_5x4_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B5x5 => (glow::COMPRESSED_RGBA_ASTC_5x5_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B6x5 => (glow::COMPRESSED_RGBA_ASTC_6x5_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B6x6 => (glow::COMPRESSED_RGBA_ASTC_6x6_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B8x5 => (glow::COMPRESSED_RGBA_ASTC_8x5_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B8x6 => (glow::COMPRESSED_RGBA_ASTC_8x6_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B8x8 => (glow::COMPRESSED_RGBA_ASTC_8x8_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B10x5 => (glow::COMPRESSED_RGBA_ASTC_10x5_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B10x6 => (glow::COMPRESSED_RGBA_ASTC_10x6_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B10x8 => (glow::COMPRESSED_RGBA_ASTC_10x8_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B10x10 => (glow::COMPRESSED_RGBA_ASTC_10x10_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B12x10 => (glow::COMPRESSED_RGBA_ASTC_12x10_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B12x12 => (glow::COMPRESSED_RGBA_ASTC_12x12_KHR, glow::RGBA, 0),
|
||||
},
|
||||
AstcChannel::UnormSrgb => match block {
|
||||
AstcBlock::B4x4 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B5x4 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B5x5 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B6x5 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B6x6 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B8x5 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B8x6 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B8x8 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, glow::RGBA, 0),
|
||||
AstcBlock::B10x5 => {
|
||||
(glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR, glow::RGBA, 0)
|
||||
}
|
||||
AstcBlock::B10x6 => {
|
||||
(glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, glow::RGBA, 0)
|
||||
}
|
||||
AstcBlock::B10x8 => {
|
||||
(glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, glow::RGBA, 0)
|
||||
}
|
||||
AstcBlock::B10x10 => {
|
||||
(glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, glow::RGBA, 0)
|
||||
}
|
||||
AstcBlock::B12x10 => {
|
||||
(glow::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, glow::RGBA, 0)
|
||||
}
|
||||
AstcBlock::B12x12 => {
|
||||
(glow::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, glow::RGBA, 0)
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
super::TextureFormatDesc {
|
||||
internal,
|
||||
external,
|
||||
data_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn describe_vertex_format(vertex_format: wgt::VertexFormat) -> super::VertexFormatDesc {
|
||||
use super::VertexAttribKind as Vak;
|
||||
use wgt::VertexFormat as Vf;
|
||||
|
||||
let (element_count, element_format, attrib_kind) = match vertex_format {
|
||||
Vf::Unorm8 => (1, glow::UNSIGNED_BYTE, Vak::Float),
|
||||
Vf::Snorm8 => (1, glow::BYTE, Vak::Float),
|
||||
Vf::Uint8 => (1, glow::UNSIGNED_BYTE, Vak::Integer),
|
||||
Vf::Sint8 => (1, glow::BYTE, Vak::Integer),
|
||||
Vf::Unorm8x2 => (2, glow::UNSIGNED_BYTE, Vak::Float),
|
||||
Vf::Snorm8x2 => (2, glow::BYTE, Vak::Float),
|
||||
Vf::Uint8x2 => (2, glow::UNSIGNED_BYTE, Vak::Integer),
|
||||
Vf::Sint8x2 => (2, glow::BYTE, Vak::Integer),
|
||||
Vf::Unorm8x4 => (4, glow::UNSIGNED_BYTE, Vak::Float),
|
||||
Vf::Snorm8x4 => (4, glow::BYTE, Vak::Float),
|
||||
Vf::Uint8x4 => (4, glow::UNSIGNED_BYTE, Vak::Integer),
|
||||
Vf::Sint8x4 => (4, glow::BYTE, Vak::Integer),
|
||||
Vf::Unorm16 => (1, glow::UNSIGNED_SHORT, Vak::Float),
|
||||
Vf::Snorm16 => (1, glow::SHORT, Vak::Float),
|
||||
Vf::Uint16 => (1, glow::UNSIGNED_SHORT, Vak::Integer),
|
||||
Vf::Sint16 => (1, glow::SHORT, Vak::Integer),
|
||||
Vf::Float16 => (1, glow::HALF_FLOAT, Vak::Float),
|
||||
Vf::Unorm16x2 => (2, glow::UNSIGNED_SHORT, Vak::Float),
|
||||
Vf::Snorm16x2 => (2, glow::SHORT, Vak::Float),
|
||||
Vf::Uint16x2 => (2, glow::UNSIGNED_SHORT, Vak::Integer),
|
||||
Vf::Sint16x2 => (2, glow::SHORT, Vak::Integer),
|
||||
Vf::Float16x2 => (2, glow::HALF_FLOAT, Vak::Float),
|
||||
Vf::Unorm16x4 => (4, glow::UNSIGNED_SHORT, Vak::Float),
|
||||
Vf::Snorm16x4 => (4, glow::SHORT, Vak::Float),
|
||||
Vf::Uint16x4 => (4, glow::UNSIGNED_SHORT, Vak::Integer),
|
||||
Vf::Sint16x4 => (4, glow::SHORT, Vak::Integer),
|
||||
Vf::Float16x4 => (4, glow::HALF_FLOAT, Vak::Float),
|
||||
Vf::Uint32 => (1, glow::UNSIGNED_INT, Vak::Integer),
|
||||
Vf::Sint32 => (1, glow::INT, Vak::Integer),
|
||||
Vf::Float32 => (1, glow::FLOAT, Vak::Float),
|
||||
Vf::Uint32x2 => (2, glow::UNSIGNED_INT, Vak::Integer),
|
||||
Vf::Sint32x2 => (2, glow::INT, Vak::Integer),
|
||||
Vf::Float32x2 => (2, glow::FLOAT, Vak::Float),
|
||||
Vf::Uint32x3 => (3, glow::UNSIGNED_INT, Vak::Integer),
|
||||
Vf::Sint32x3 => (3, glow::INT, Vak::Integer),
|
||||
Vf::Float32x3 => (3, glow::FLOAT, Vak::Float),
|
||||
Vf::Uint32x4 => (4, glow::UNSIGNED_INT, Vak::Integer),
|
||||
Vf::Sint32x4 => (4, glow::INT, Vak::Integer),
|
||||
Vf::Float32x4 => (4, glow::FLOAT, Vak::Float),
|
||||
Vf::Unorm10_10_10_2 => (4, glow::UNSIGNED_INT_2_10_10_10_REV, Vak::Float),
|
||||
Vf::Unorm8x4Bgra => (glow::BGRA as i32, glow::UNSIGNED_BYTE, Vak::Float),
|
||||
Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(),
|
||||
};
|
||||
|
||||
super::VertexFormatDesc {
|
||||
element_count,
|
||||
element_format,
|
||||
attrib_kind,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_filter_modes(
|
||||
min: wgt::FilterMode,
|
||||
mag: wgt::FilterMode,
|
||||
mip: wgt::MipmapFilterMode,
|
||||
) -> (u32, u32) {
|
||||
use wgt::FilterMode as Fm;
|
||||
use wgt::MipmapFilterMode as Mfm;
|
||||
|
||||
let mag_filter = match mag {
|
||||
Fm::Nearest => glow::NEAREST,
|
||||
Fm::Linear => glow::LINEAR,
|
||||
};
|
||||
|
||||
let min_filter = match (min, mip) {
|
||||
(Fm::Nearest, Mfm::Nearest) => glow::NEAREST_MIPMAP_NEAREST,
|
||||
(Fm::Nearest, Mfm::Linear) => glow::NEAREST_MIPMAP_LINEAR,
|
||||
(Fm::Linear, Mfm::Nearest) => glow::LINEAR_MIPMAP_NEAREST,
|
||||
(Fm::Linear, Mfm::Linear) => glow::LINEAR_MIPMAP_LINEAR,
|
||||
};
|
||||
|
||||
(min_filter, mag_filter)
|
||||
}
|
||||
|
||||
pub fn map_address_mode(mode: wgt::AddressMode) -> u32 {
|
||||
match mode {
|
||||
wgt::AddressMode::Repeat => glow::REPEAT,
|
||||
wgt::AddressMode::MirrorRepeat => glow::MIRRORED_REPEAT,
|
||||
wgt::AddressMode::ClampToEdge => glow::CLAMP_TO_EDGE,
|
||||
wgt::AddressMode::ClampToBorder => glow::CLAMP_TO_BORDER,
|
||||
//wgt::AddressMode::MirrorClamp => glow::MIRROR_CLAMP_TO_EDGE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_compare_func(fun: wgt::CompareFunction) -> u32 {
|
||||
use wgt::CompareFunction as Cf;
|
||||
match fun {
|
||||
Cf::Never => glow::NEVER,
|
||||
Cf::Less => glow::LESS,
|
||||
Cf::LessEqual => glow::LEQUAL,
|
||||
Cf::Equal => glow::EQUAL,
|
||||
Cf::GreaterEqual => glow::GEQUAL,
|
||||
Cf::Greater => glow::GREATER,
|
||||
Cf::NotEqual => glow::NOTEQUAL,
|
||||
Cf::Always => glow::ALWAYS,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_primitive_topology(topology: wgt::PrimitiveTopology) -> u32 {
|
||||
use wgt::PrimitiveTopology as Pt;
|
||||
match topology {
|
||||
Pt::PointList => glow::POINTS,
|
||||
Pt::LineList => glow::LINES,
|
||||
Pt::LineStrip => glow::LINE_STRIP,
|
||||
Pt::TriangleList => glow::TRIANGLES,
|
||||
Pt::TriangleStrip => glow::TRIANGLE_STRIP,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn map_primitive_state(state: &wgt::PrimitiveState) -> super::PrimitiveState {
|
||||
super::PrimitiveState {
|
||||
//Note: we are flipping the front face, so that
|
||||
// the Y-flip in the generated GLSL keeps the same visibility.
|
||||
// See `naga::back::glsl::WriterFlags::ADJUST_COORDINATE_SPACE`.
|
||||
front_face: match state.front_face {
|
||||
wgt::FrontFace::Cw => glow::CCW,
|
||||
wgt::FrontFace::Ccw => glow::CW,
|
||||
},
|
||||
cull_face: match state.cull_mode {
|
||||
Some(wgt::Face::Front) => glow::FRONT,
|
||||
Some(wgt::Face::Back) => glow::BACK,
|
||||
None => 0,
|
||||
},
|
||||
unclipped_depth: state.unclipped_depth,
|
||||
polygon_mode: match state.polygon_mode {
|
||||
wgt::PolygonMode::Fill => glow::FILL,
|
||||
wgt::PolygonMode::Line => glow::LINE,
|
||||
wgt::PolygonMode::Point => glow::POINT,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn _map_view_dimension(dim: wgt::TextureViewDimension) -> u32 {
|
||||
use wgt::TextureViewDimension as Tvd;
|
||||
match dim {
|
||||
Tvd::D1 | Tvd::D2 => glow::TEXTURE_2D,
|
||||
Tvd::D2Array => glow::TEXTURE_2D_ARRAY,
|
||||
Tvd::Cube => glow::TEXTURE_CUBE_MAP,
|
||||
Tvd::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY,
|
||||
Tvd::D3 => glow::TEXTURE_3D,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_stencil_op(operation: wgt::StencilOperation) -> u32 {
|
||||
use wgt::StencilOperation as So;
|
||||
match operation {
|
||||
So::Keep => glow::KEEP,
|
||||
So::Zero => glow::ZERO,
|
||||
So::Replace => glow::REPLACE,
|
||||
So::Invert => glow::INVERT,
|
||||
So::IncrementClamp => glow::INCR,
|
||||
So::DecrementClamp => glow::DECR,
|
||||
So::IncrementWrap => glow::INCR_WRAP,
|
||||
So::DecrementWrap => glow::DECR_WRAP,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_stencil_ops(face: &wgt::StencilFaceState) -> super::StencilOps {
|
||||
super::StencilOps {
|
||||
pass: map_stencil_op(face.pass_op),
|
||||
fail: map_stencil_op(face.fail_op),
|
||||
depth_fail: map_stencil_op(face.depth_fail_op),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn map_stencil(state: &wgt::StencilState) -> super::StencilState {
|
||||
super::StencilState {
|
||||
front: super::StencilSide {
|
||||
function: map_compare_func(state.front.compare),
|
||||
mask_read: state.read_mask,
|
||||
mask_write: state.write_mask,
|
||||
reference: 0,
|
||||
ops: map_stencil_ops(&state.front),
|
||||
},
|
||||
back: super::StencilSide {
|
||||
function: map_compare_func(state.back.compare),
|
||||
mask_read: state.read_mask,
|
||||
mask_write: state.write_mask,
|
||||
reference: 0,
|
||||
ops: map_stencil_ops(&state.back),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn map_blend_factor(factor: wgt::BlendFactor) -> u32 {
|
||||
use wgt::BlendFactor as Bf;
|
||||
match factor {
|
||||
Bf::Zero => glow::ZERO,
|
||||
Bf::One => glow::ONE,
|
||||
Bf::Src => glow::SRC_COLOR,
|
||||
Bf::OneMinusSrc => glow::ONE_MINUS_SRC_COLOR,
|
||||
Bf::Dst => glow::DST_COLOR,
|
||||
Bf::OneMinusDst => glow::ONE_MINUS_DST_COLOR,
|
||||
Bf::SrcAlpha => glow::SRC_ALPHA,
|
||||
Bf::OneMinusSrcAlpha => glow::ONE_MINUS_SRC_ALPHA,
|
||||
Bf::DstAlpha => glow::DST_ALPHA,
|
||||
Bf::OneMinusDstAlpha => glow::ONE_MINUS_DST_ALPHA,
|
||||
Bf::Constant => glow::CONSTANT_COLOR,
|
||||
Bf::OneMinusConstant => glow::ONE_MINUS_CONSTANT_COLOR,
|
||||
Bf::SrcAlphaSaturated => glow::SRC_ALPHA_SATURATE,
|
||||
Bf::Src1 => glow::SRC1_COLOR,
|
||||
Bf::OneMinusSrc1 => glow::ONE_MINUS_SRC1_COLOR,
|
||||
Bf::Src1Alpha => glow::SRC1_ALPHA,
|
||||
Bf::OneMinusSrc1Alpha => glow::ONE_MINUS_SRC1_ALPHA,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_blend_component(component: &wgt::BlendComponent) -> super::BlendComponent {
|
||||
super::BlendComponent {
|
||||
src: map_blend_factor(component.src_factor),
|
||||
dst: map_blend_factor(component.dst_factor),
|
||||
equation: match component.operation {
|
||||
wgt::BlendOperation::Add => glow::FUNC_ADD,
|
||||
wgt::BlendOperation::Subtract => glow::FUNC_SUBTRACT,
|
||||
wgt::BlendOperation::ReverseSubtract => glow::FUNC_REVERSE_SUBTRACT,
|
||||
wgt::BlendOperation::Min => glow::MIN,
|
||||
wgt::BlendOperation::Max => glow::MAX,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn map_blend(blend: &wgt::BlendState) -> super::BlendDesc {
|
||||
super::BlendDesc {
|
||||
color: map_blend_component(&blend.color),
|
||||
alpha: map_blend_component(&blend.alpha),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn map_storage_access(access: wgt::StorageTextureAccess) -> u32 {
|
||||
match access {
|
||||
wgt::StorageTextureAccess::ReadOnly => glow::READ_ONLY,
|
||||
wgt::StorageTextureAccess::WriteOnly => glow::WRITE_ONLY,
|
||||
wgt::StorageTextureAccess::ReadWrite => glow::READ_WRITE,
|
||||
wgt::StorageTextureAccess::Atomic => glow::READ_WRITE,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_layered_target(target: u32) -> bool {
|
||||
match target {
|
||||
glow::TEXTURE_2D | glow::TEXTURE_CUBE_MAP => false,
|
||||
glow::TEXTURE_2D_ARRAY | glow::TEXTURE_CUBE_MAP_ARRAY | glow::TEXTURE_3D => true,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
Vendored
+1823
File diff suppressed because it is too large
Load Diff
Vendored
+1470
File diff suppressed because it is too large
Load Diff
+26
@@ -0,0 +1,26 @@
|
||||
extern "C" {
|
||||
/// returns 1 if success. 0 if failure. extension name must be null terminated
|
||||
fn emscripten_webgl_enable_extension(
|
||||
context: core::ffi::c_int,
|
||||
extension: *const core::ffi::c_char,
|
||||
) -> core::ffi::c_int;
|
||||
fn emscripten_webgl_get_current_context() -> core::ffi::c_int;
|
||||
}
|
||||
/// Webgl requires extensions to be enabled before using them.
|
||||
/// This function can be used to enable webgl extension on emscripten target.
|
||||
///
|
||||
/// returns true on success
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// - opengl context MUST BE current
|
||||
/// - extension_name_null_terminated argument must be a valid string with null terminator.
|
||||
/// - extension must be present. check `glow_context.supported_extensions()`
|
||||
pub unsafe fn enable_extension(extension_name_null_terminated: &str) -> bool {
|
||||
unsafe {
|
||||
emscripten_webgl_enable_extension(
|
||||
emscripten_webgl_get_current_context(),
|
||||
extension_name_null_terminated.as_ptr().cast(),
|
||||
) == 1
|
||||
}
|
||||
}
|
||||
Vendored
+198
@@ -0,0 +1,198 @@
|
||||
use alloc::{sync::Arc, vec::Vec};
|
||||
use core::sync::atomic::Ordering;
|
||||
use parking_lot::RwLock;
|
||||
|
||||
use glow::HasContext;
|
||||
|
||||
use crate::AtomicFenceValue;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GLFence {
|
||||
// Since a fence can be `Copy`ed, there can exist some
|
||||
// cases where a fence could be destroyed while something
|
||||
// else is still using it. Therefore, while a function is
|
||||
// using this fence (and doesn't keep pending read locked),
|
||||
// it should clone the `Arc` to show it needs this to
|
||||
// stay alive.
|
||||
//
|
||||
// The arc should not be kept after a function has finished
|
||||
sync: Arc<glow::Fence>,
|
||||
value: crate::FenceValue,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Fence {
|
||||
last_completed: AtomicFenceValue,
|
||||
pending: RwLock<Vec<GLFence>>,
|
||||
fence_behavior: wgt::GlFenceBehavior,
|
||||
}
|
||||
|
||||
impl crate::DynFence for Fence {}
|
||||
|
||||
#[cfg(send_sync)]
|
||||
unsafe impl Send for Fence {}
|
||||
#[cfg(send_sync)]
|
||||
unsafe impl Sync for Fence {}
|
||||
|
||||
impl Fence {
|
||||
pub fn new(options: &wgt::GlBackendOptions) -> Self {
|
||||
Self {
|
||||
last_completed: AtomicFenceValue::new(0),
|
||||
pending: RwLock::new(Vec::new()),
|
||||
fence_behavior: options.fence_behavior,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn signal(
|
||||
&self,
|
||||
gl: &glow::Context,
|
||||
value: crate::FenceValue,
|
||||
) -> Result<(), crate::DeviceError> {
|
||||
if self.fence_behavior.is_auto_finish() {
|
||||
self.last_completed.store(value, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let sync = unsafe { gl.fence_sync(glow::SYNC_GPU_COMMANDS_COMPLETE, 0) }
|
||||
.map_err(|_| crate::DeviceError::OutOfMemory)?;
|
||||
self.pending.write().push(GLFence {
|
||||
sync: Arc::new(sync),
|
||||
value,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn satisfied(&self, value: crate::FenceValue) -> bool {
|
||||
self.last_completed.load(Ordering::Acquire) >= value
|
||||
}
|
||||
|
||||
pub fn get_latest(&self, gl: &glow::Context) -> crate::FenceValue {
|
||||
let mut max_value = self.last_completed.load(Ordering::Acquire);
|
||||
|
||||
if self.fence_behavior.is_auto_finish() {
|
||||
return max_value;
|
||||
}
|
||||
|
||||
let pending = self.pending.read();
|
||||
|
||||
for gl_fence in pending.iter() {
|
||||
if gl_fence.value <= max_value {
|
||||
// We already know this was good, no need to check again
|
||||
continue;
|
||||
}
|
||||
// We have pending `read` locked, so we shouldn't have to clone it.
|
||||
let status = unsafe { gl.get_sync_status(*gl_fence.sync) };
|
||||
if status == glow::SIGNALED {
|
||||
max_value = gl_fence.value;
|
||||
} else {
|
||||
// Anything after the first unsignalled is guaranteed to also be unsignalled
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Track the latest value, to save ourselves some querying later
|
||||
self.last_completed.fetch_max(max_value, Ordering::AcqRel);
|
||||
|
||||
max_value
|
||||
}
|
||||
|
||||
pub fn maintain(&self, gl: &glow::Context) {
|
||||
if self.fence_behavior.is_auto_finish() {
|
||||
return;
|
||||
}
|
||||
|
||||
let latest = self.get_latest(gl);
|
||||
let mut pending = self.pending.write();
|
||||
pending.retain_mut(|gl_fence| {
|
||||
if gl_fence.value > latest {
|
||||
true
|
||||
} else if let Some(fence) = Arc::get_mut(&mut gl_fence.sync) {
|
||||
unsafe {
|
||||
gl.delete_sync(*fence);
|
||||
}
|
||||
false
|
||||
} else {
|
||||
// Another function is currently using this value. In general, these should finish
|
||||
// very quickly (for wait because the fence should already be signaled, an all
|
||||
// others are just fast), but submit should be very fast, so we shouldn't block on
|
||||
// this.
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn wait(
|
||||
&self,
|
||||
gl: &glow::Context,
|
||||
wait_value: crate::FenceValue,
|
||||
timeout_ns: u32,
|
||||
) -> Result<bool, crate::DeviceError> {
|
||||
let last_completed = self.last_completed.load(Ordering::Acquire);
|
||||
|
||||
if self.fence_behavior.is_auto_finish() {
|
||||
return Ok(last_completed >= wait_value);
|
||||
}
|
||||
|
||||
// We already know this fence has been signalled to that value. Return signalled.
|
||||
if last_completed >= wait_value {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
let pending = self.pending.read();
|
||||
|
||||
// Find a matching fence
|
||||
let gl_fence = pending.iter().find(|gl_fence| gl_fence.value >= wait_value);
|
||||
|
||||
let Some(gl_fence) = gl_fence else {
|
||||
log::warn!("Tried to wait for {wait_value} but that value has not been signalled yet");
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
// clone to show we're using the fence
|
||||
let sync = gl_fence.sync.clone();
|
||||
let fence_value = gl_fence.value;
|
||||
|
||||
drop(pending);
|
||||
|
||||
let status = unsafe {
|
||||
gl.client_wait_sync(
|
||||
*sync,
|
||||
glow::SYNC_FLUSH_COMMANDS_BIT,
|
||||
timeout_ns.min(i32::MAX as u32) as i32,
|
||||
)
|
||||
};
|
||||
|
||||
drop(sync);
|
||||
|
||||
let signalled = match status {
|
||||
glow::ALREADY_SIGNALED | glow::CONDITION_SATISFIED => true,
|
||||
glow::TIMEOUT_EXPIRED | glow::WAIT_FAILED => false,
|
||||
_ => {
|
||||
log::warn!("Unexpected result from client_wait_sync: {status}");
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
if signalled {
|
||||
self.last_completed.fetch_max(fence_value, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
Ok(signalled)
|
||||
}
|
||||
|
||||
pub fn destroy(self, gl: &glow::Context) {
|
||||
if self.fence_behavior.is_auto_finish() {
|
||||
return;
|
||||
}
|
||||
|
||||
for gl_fence in self.pending.into_inner() {
|
||||
unsafe {
|
||||
gl.delete_sync(
|
||||
Arc::into_inner(gl_fence.sync)
|
||||
.expect("A function has failed to drop all its references to this"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+1215
File diff suppressed because it is too large
Load Diff
Vendored
+1980
File diff suppressed because it is too large
Load Diff
+7
@@ -0,0 +1,7 @@
|
||||
uniform vec4 color;
|
||||
//Hack: Some WebGL implementations don't find "color" otherwise.
|
||||
uniform vec4 color_workaround;
|
||||
out vec4 frag;
|
||||
void main() {
|
||||
frag = color + color_workaround;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// A triangle that fills the whole screen
|
||||
vec2[3] TRIANGLE_POS = vec2[](
|
||||
vec2( 0.0, -3.0),
|
||||
vec2(-3.0, 1.0),
|
||||
vec2( 3.0, 1.0)
|
||||
);
|
||||
void main() {
|
||||
gl_Position = vec4(TRIANGLE_POS[gl_VertexID], 0.0, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#version 300 es
|
||||
precision mediump float;
|
||||
in vec2 uv;
|
||||
uniform sampler2D present_texture;
|
||||
out vec4 frag;
|
||||
vec4 linear_to_srgb(vec4 linear) {
|
||||
vec3 color_linear = linear.rgb;
|
||||
vec3 selector = ceil(color_linear - 0.0031308); // 0 if under value, 1 if over
|
||||
vec3 under = 12.92 * color_linear;
|
||||
vec3 over = 1.055 * pow(color_linear, vec3(0.41666)) - 0.055;
|
||||
vec3 result = mix(under, over, selector);
|
||||
return vec4(result, linear.a);
|
||||
}
|
||||
void main() {
|
||||
frag = linear_to_srgb(texture(present_texture, uv));
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#version 300 es
|
||||
precision mediump float;
|
||||
// A triangle that fills the whole screen
|
||||
const vec2[3] TRIANGLE_POS = vec2[](
|
||||
vec2( 0.0, -3.0),
|
||||
vec2(-3.0, 1.0),
|
||||
vec2( 3.0, 1.0)
|
||||
);
|
||||
const vec2[3] TRIANGLE_UV = vec2[](
|
||||
vec2( 0.5, 1.),
|
||||
vec2( -1.0, -1.0),
|
||||
vec2( 2.0, -1.0)
|
||||
);
|
||||
out vec2 uv;
|
||||
void main() {
|
||||
uv = TRIANGLE_UV[gl_VertexID];
|
||||
gl_Position = vec4(TRIANGLE_POS[gl_VertexID], 0.0, 1.0);
|
||||
}
|
||||
Vendored
+490
@@ -0,0 +1,490 @@
|
||||
use alloc::{format, string::String, vec::Vec};
|
||||
|
||||
use glow::HasContext;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
|
||||
use super::TextureFormatDesc;
|
||||
|
||||
/// A wrapper around a [`glow::Context`] to provide a fake `lock()` api that makes it compatible
|
||||
/// with the `AdapterContext` API from the EGL implementation.
|
||||
#[derive(Debug)]
|
||||
pub struct AdapterContext {
|
||||
pub glow_context: glow::Context,
|
||||
pub webgl2_context: web_sys::WebGl2RenderingContext,
|
||||
}
|
||||
|
||||
impl AdapterContext {
|
||||
pub fn is_owned(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Obtain a lock to the EGL context and get handle to the [`glow::Context`] that can be used to
|
||||
/// do rendering.
|
||||
#[track_caller]
|
||||
pub fn lock(&self) -> &glow::Context {
|
||||
&self.glow_context
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Instance {
|
||||
options: wgt::GlBackendOptions,
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
pub fn create_surface_from_canvas(
|
||||
&self,
|
||||
canvas: web_sys::HtmlCanvasElement,
|
||||
) -> Result<Surface, crate::InstanceError> {
|
||||
let result =
|
||||
canvas.get_context_with_context_options("webgl2", &Self::create_context_options());
|
||||
self.create_surface_from_context(Canvas::Canvas(canvas), result)
|
||||
}
|
||||
|
||||
pub fn create_surface_from_offscreen_canvas(
|
||||
&self,
|
||||
canvas: web_sys::OffscreenCanvas,
|
||||
) -> Result<Surface, crate::InstanceError> {
|
||||
let result =
|
||||
canvas.get_context_with_context_options("webgl2", &Self::create_context_options());
|
||||
self.create_surface_from_context(Canvas::Offscreen(canvas), result)
|
||||
}
|
||||
|
||||
/// Common portion of public `create_surface_from_*` functions.
|
||||
///
|
||||
/// Note: Analogous code also exists in the WebGPU backend at
|
||||
/// `wgpu::backend::web::Context`.
|
||||
fn create_surface_from_context(
|
||||
&self,
|
||||
canvas: Canvas,
|
||||
context_result: Result<Option<js_sys::Object>, JsValue>,
|
||||
) -> Result<Surface, crate::InstanceError> {
|
||||
let context_object: js_sys::Object = match context_result {
|
||||
Ok(Some(context)) => context,
|
||||
Ok(None) => {
|
||||
// <https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext-dev>
|
||||
// A getContext() call “returns null if contextId is not supported, or if the
|
||||
// canvas has already been initialized with another context type”. Additionally,
|
||||
// “not supported” could include “insufficient GPU resources” or “the GPU process
|
||||
// previously crashed”. So, we must return it as an `Err` since it could occur
|
||||
// for circumstances outside the application author's control.
|
||||
return Err(crate::InstanceError::new(String::from(concat!(
|
||||
"canvas.getContext() returned null; ",
|
||||
"webgl2 not available or canvas already in use"
|
||||
))));
|
||||
}
|
||||
Err(js_error) => {
|
||||
// <https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext>
|
||||
// A thrown exception indicates misuse of the canvas state.
|
||||
return Err(crate::InstanceError::new(format!(
|
||||
"canvas.getContext() threw exception {js_error:?}",
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
// Not returning this error because it is a type error that shouldn't happen unless
|
||||
// the browser, JS builtin objects, or wasm bindings are misbehaving somehow.
|
||||
let webgl2_context: web_sys::WebGl2RenderingContext = context_object
|
||||
.dyn_into()
|
||||
.expect("canvas context is not a WebGl2RenderingContext");
|
||||
|
||||
Ok(Surface {
|
||||
canvas,
|
||||
webgl2_context,
|
||||
srgb_present_program: Mutex::new(None),
|
||||
swapchain: RwLock::new(None),
|
||||
texture: Mutex::new(None),
|
||||
presentable: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn create_context_options() -> js_sys::Object {
|
||||
let context_options = js_sys::Object::new();
|
||||
js_sys::Reflect::set(&context_options, &"antialias".into(), &JsValue::FALSE)
|
||||
.expect("Cannot create context options");
|
||||
context_options
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(send_sync)]
|
||||
static_assertions::assert_impl_all!(Instance: Send, Sync);
|
||||
|
||||
impl crate::Instance for Instance {
|
||||
type A = super::Api;
|
||||
|
||||
unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
|
||||
profiling::scope!("Init OpenGL (WebGL) Backend");
|
||||
Ok(Instance {
|
||||
options: desc.backend_options.gl.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn enumerate_adapters(
|
||||
&self,
|
||||
surface_hint: Option<&Surface>,
|
||||
) -> Vec<crate::ExposedAdapter<super::Api>> {
|
||||
if let Some(surface_hint) = surface_hint {
|
||||
let gl = glow::Context::from_webgl2_context(surface_hint.webgl2_context.clone());
|
||||
|
||||
unsafe {
|
||||
super::Adapter::expose(
|
||||
AdapterContext {
|
||||
glow_context: gl,
|
||||
webgl2_context: surface_hint.webgl2_context.clone(),
|
||||
},
|
||||
self.options.clone(),
|
||||
)
|
||||
}
|
||||
.into_iter()
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn create_surface(
|
||||
&self,
|
||||
_display_handle: raw_window_handle::RawDisplayHandle,
|
||||
window_handle: raw_window_handle::RawWindowHandle,
|
||||
) -> Result<Surface, crate::InstanceError> {
|
||||
let canvas: web_sys::HtmlCanvasElement = match window_handle {
|
||||
raw_window_handle::RawWindowHandle::Web(handle) => web_sys::window()
|
||||
.and_then(|win| win.document())
|
||||
.expect("Cannot get document")
|
||||
.query_selector(&format!("canvas[data-raw-handle=\"{}\"]", handle.id))
|
||||
.expect("Cannot query for canvas")
|
||||
.expect("Canvas is not found")
|
||||
.dyn_into()
|
||||
.expect("Failed to downcast to canvas type"),
|
||||
raw_window_handle::RawWindowHandle::WebCanvas(handle) => {
|
||||
let value: &JsValue = unsafe { handle.obj.cast().as_ref() };
|
||||
value.clone().unchecked_into()
|
||||
}
|
||||
raw_window_handle::RawWindowHandle::WebOffscreenCanvas(handle) => {
|
||||
let value: &JsValue = unsafe { handle.obj.cast().as_ref() };
|
||||
let canvas: web_sys::OffscreenCanvas = value.clone().unchecked_into();
|
||||
|
||||
return self.create_surface_from_offscreen_canvas(canvas);
|
||||
}
|
||||
_ => {
|
||||
return Err(crate::InstanceError::new(format!(
|
||||
"window handle {window_handle:?} is not a web handle"
|
||||
)))
|
||||
}
|
||||
};
|
||||
|
||||
self.create_surface_from_canvas(canvas)
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Adapter {
|
||||
/// Creates a new external adapter from an existing WebGL2 rendering context.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// - The underlying WebGL2 context must be valid (not lost).
|
||||
/// - The underlying WebGL2 context must be valid when interfacing with any objects returned by
|
||||
/// wgpu-hal from this adapter.
|
||||
/// - The underlying WebGL2 context must be valid when dropping this adapter and when
|
||||
/// dropping any objects returned from this adapter.
|
||||
pub unsafe fn new_external(
|
||||
webgl2_context: web_sys::WebGl2RenderingContext,
|
||||
options: wgt::GlBackendOptions,
|
||||
) -> Option<crate::ExposedAdapter<super::Api>> {
|
||||
let glow_context = glow::Context::from_webgl2_context(webgl2_context.clone());
|
||||
unsafe {
|
||||
Self::expose(
|
||||
AdapterContext {
|
||||
glow_context,
|
||||
webgl2_context,
|
||||
},
|
||||
options,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn adapter_context(&self) -> &AdapterContext {
|
||||
&self.shared.context
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Device {
|
||||
/// Returns the underlying WebGL2 `AdapterContext`.
|
||||
pub fn context(&self) -> &AdapterContext {
|
||||
&self.shared.context
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Surface {
|
||||
canvas: Canvas,
|
||||
pub(super) webgl2_context: web_sys::WebGl2RenderingContext,
|
||||
pub(super) swapchain: RwLock<Option<Swapchain>>,
|
||||
texture: Mutex<Option<glow::Texture>>,
|
||||
pub(super) presentable: bool,
|
||||
srgb_present_program: Mutex<Option<glow::Program>>,
|
||||
}
|
||||
|
||||
impl Clone for Surface {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
canvas: self.canvas.clone(),
|
||||
webgl2_context: self.webgl2_context.clone(),
|
||||
swapchain: RwLock::new(self.swapchain.read().clone()),
|
||||
texture: Mutex::new(*self.texture.lock()),
|
||||
presentable: self.presentable,
|
||||
srgb_present_program: Mutex::new(*self.srgb_present_program.lock()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(send_sync)]
|
||||
unsafe impl Sync for Surface {}
|
||||
#[cfg(send_sync)]
|
||||
unsafe impl Send for Surface {}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Canvas {
|
||||
Canvas(web_sys::HtmlCanvasElement),
|
||||
Offscreen(web_sys::OffscreenCanvas),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Swapchain {
|
||||
pub(crate) extent: wgt::Extent3d,
|
||||
// pub(crate) channel: f::ChannelType,
|
||||
pub(super) format: wgt::TextureFormat,
|
||||
pub(super) framebuffer: glow::Framebuffer,
|
||||
pub(super) format_desc: TextureFormatDesc,
|
||||
}
|
||||
|
||||
impl Surface {
|
||||
pub(super) unsafe fn present(
|
||||
&self,
|
||||
_suf_texture: super::Texture,
|
||||
context: &AdapterContext,
|
||||
) -> Result<(), crate::SurfaceError> {
|
||||
let gl = &context.glow_context;
|
||||
let swapchain = self.swapchain.read();
|
||||
let swapchain = swapchain.as_ref().ok_or(crate::SurfaceError::Other(
|
||||
"need to configure surface before presenting",
|
||||
))?;
|
||||
|
||||
if swapchain.format.is_srgb() {
|
||||
// Important to set the viewport since we don't know in what state the user left it.
|
||||
unsafe {
|
||||
gl.viewport(
|
||||
0,
|
||||
0,
|
||||
swapchain.extent.width as _,
|
||||
swapchain.extent.height as _,
|
||||
)
|
||||
};
|
||||
unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
|
||||
unsafe { gl.bind_sampler(0, None) };
|
||||
unsafe { gl.active_texture(glow::TEXTURE0) };
|
||||
unsafe { gl.bind_texture(glow::TEXTURE_2D, *self.texture.lock()) };
|
||||
unsafe { gl.use_program(*self.srgb_present_program.lock()) };
|
||||
unsafe { gl.disable(glow::DEPTH_TEST) };
|
||||
unsafe { gl.disable(glow::STENCIL_TEST) };
|
||||
unsafe { gl.disable(glow::SCISSOR_TEST) };
|
||||
unsafe { gl.disable(glow::BLEND) };
|
||||
unsafe { gl.disable(glow::CULL_FACE) };
|
||||
unsafe { gl.draw_buffers(&[glow::BACK]) };
|
||||
unsafe { gl.draw_arrays(glow::TRIANGLES, 0, 3) };
|
||||
} else {
|
||||
unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(swapchain.framebuffer)) };
|
||||
unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
|
||||
// Note the Y-flipping here. GL's presentation is not flipped,
|
||||
// but main rendering is. Therefore, we Y-flip the output positions
|
||||
// in the shader, and also this blit.
|
||||
unsafe {
|
||||
gl.blit_framebuffer(
|
||||
0,
|
||||
swapchain.extent.height as i32,
|
||||
swapchain.extent.width as i32,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
swapchain.extent.width as i32,
|
||||
swapchain.extent.height as i32,
|
||||
glow::COLOR_BUFFER_BIT,
|
||||
glow::NEAREST,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
unsafe fn create_srgb_present_program(gl: &glow::Context) -> glow::Program {
|
||||
let program = unsafe { gl.create_program() }.expect("Could not create shader program");
|
||||
let vertex =
|
||||
unsafe { gl.create_shader(glow::VERTEX_SHADER) }.expect("Could not create shader");
|
||||
unsafe { gl.shader_source(vertex, include_str!("./shaders/srgb_present.vert")) };
|
||||
unsafe { gl.compile_shader(vertex) };
|
||||
let fragment =
|
||||
unsafe { gl.create_shader(glow::FRAGMENT_SHADER) }.expect("Could not create shader");
|
||||
unsafe { gl.shader_source(fragment, include_str!("./shaders/srgb_present.frag")) };
|
||||
unsafe { gl.compile_shader(fragment) };
|
||||
unsafe { gl.attach_shader(program, vertex) };
|
||||
unsafe { gl.attach_shader(program, fragment) };
|
||||
unsafe { gl.link_program(program) };
|
||||
unsafe { gl.delete_shader(vertex) };
|
||||
unsafe { gl.delete_shader(fragment) };
|
||||
unsafe { gl.bind_texture(glow::TEXTURE_2D, None) };
|
||||
|
||||
program
|
||||
}
|
||||
|
||||
pub fn supports_srgb(&self) -> bool {
|
||||
// present.frag takes care of handling srgb conversion
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Surface for Surface {
|
||||
type A = super::Api;
|
||||
|
||||
unsafe fn configure(
|
||||
&self,
|
||||
device: &super::Device,
|
||||
config: &crate::SurfaceConfiguration,
|
||||
) -> Result<(), crate::SurfaceError> {
|
||||
match self.canvas {
|
||||
Canvas::Canvas(ref canvas) => {
|
||||
canvas.set_width(config.extent.width);
|
||||
canvas.set_height(config.extent.height);
|
||||
}
|
||||
Canvas::Offscreen(ref canvas) => {
|
||||
canvas.set_width(config.extent.width);
|
||||
canvas.set_height(config.extent.height);
|
||||
}
|
||||
}
|
||||
|
||||
let gl = &device.shared.context.lock();
|
||||
|
||||
{
|
||||
let mut swapchain = self.swapchain.write();
|
||||
if let Some(swapchain) = swapchain.take() {
|
||||
// delete all frame buffers already allocated
|
||||
unsafe { gl.delete_framebuffer(swapchain.framebuffer) };
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut srgb_present_program = self.srgb_present_program.lock();
|
||||
if srgb_present_program.is_none() && config.format.is_srgb() {
|
||||
*srgb_present_program = Some(unsafe { Self::create_srgb_present_program(gl) });
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut texture = self.texture.lock();
|
||||
if let Some(texture) = texture.take() {
|
||||
unsafe { gl.delete_texture(texture) };
|
||||
}
|
||||
|
||||
*texture = Some(unsafe { gl.create_texture() }.map_err(|error| {
|
||||
log::error!("Internal swapchain texture creation failed: {error}");
|
||||
crate::DeviceError::OutOfMemory
|
||||
})?);
|
||||
|
||||
let desc = device.shared.describe_texture_format(config.format);
|
||||
unsafe { gl.bind_texture(glow::TEXTURE_2D, *texture) };
|
||||
unsafe {
|
||||
gl.tex_parameter_i32(
|
||||
glow::TEXTURE_2D,
|
||||
glow::TEXTURE_MIN_FILTER,
|
||||
glow::NEAREST as _,
|
||||
)
|
||||
};
|
||||
unsafe {
|
||||
gl.tex_parameter_i32(
|
||||
glow::TEXTURE_2D,
|
||||
glow::TEXTURE_MAG_FILTER,
|
||||
glow::NEAREST as _,
|
||||
)
|
||||
};
|
||||
unsafe {
|
||||
gl.tex_storage_2d(
|
||||
glow::TEXTURE_2D,
|
||||
1,
|
||||
desc.internal,
|
||||
config.extent.width as i32,
|
||||
config.extent.height as i32,
|
||||
)
|
||||
};
|
||||
|
||||
let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| {
|
||||
log::error!("Internal swapchain framebuffer creation failed: {error}");
|
||||
crate::DeviceError::OutOfMemory
|
||||
})?;
|
||||
unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) };
|
||||
unsafe {
|
||||
gl.framebuffer_texture_2d(
|
||||
glow::READ_FRAMEBUFFER,
|
||||
glow::COLOR_ATTACHMENT0,
|
||||
glow::TEXTURE_2D,
|
||||
*texture,
|
||||
0,
|
||||
)
|
||||
};
|
||||
unsafe { gl.bind_texture(glow::TEXTURE_2D, None) };
|
||||
|
||||
let mut swapchain = self.swapchain.write();
|
||||
*swapchain = Some(Swapchain {
|
||||
extent: config.extent,
|
||||
// channel: config.format.base_format().1,
|
||||
format: config.format,
|
||||
format_desc: desc,
|
||||
framebuffer,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
unsafe fn unconfigure(&self, device: &super::Device) {
|
||||
let gl = device.shared.context.lock();
|
||||
{
|
||||
let mut swapchain = self.swapchain.write();
|
||||
if let Some(swapchain) = swapchain.take() {
|
||||
unsafe { gl.delete_framebuffer(swapchain.framebuffer) };
|
||||
}
|
||||
}
|
||||
if let Some(renderbuffer) = self.texture.lock().take() {
|
||||
unsafe { gl.delete_texture(renderbuffer) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn acquire_texture(
|
||||
&self,
|
||||
_timeout_ms: Option<core::time::Duration>, //TODO
|
||||
_fence: &super::Fence,
|
||||
) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> {
|
||||
let swapchain = self.swapchain.read();
|
||||
let sc = swapchain.as_ref().unwrap();
|
||||
let texture = super::Texture {
|
||||
inner: super::TextureInner::Texture {
|
||||
raw: self.texture.lock().unwrap(),
|
||||
target: glow::TEXTURE_2D,
|
||||
},
|
||||
drop_guard: None,
|
||||
array_layer_count: 1,
|
||||
mip_level_count: 1,
|
||||
format: sc.format,
|
||||
format_desc: sc.format_desc.clone(),
|
||||
copy_size: crate::CopyExtent {
|
||||
width: sc.extent.width,
|
||||
height: sc.extent.height,
|
||||
depth: 1,
|
||||
},
|
||||
};
|
||||
Ok(crate::AcquiredSurfaceTexture {
|
||||
texture,
|
||||
suboptimal: false,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn discard_texture(&self, _texture: super::Texture) {}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user