mirror of
https://github.com/storytold/wgpu.git
synced 2026-11-26 17:31:05 +01:00
Merge #1510
1510: OpenGL ES3 backend r=cwfitzgerald,Gordon-F,kvark a=kvark **Connections** Follow-up to #1471 **Description** The new wgpu-hal backend for GLES3 ~~and WebGL2~~ Edit: WebGL2 is not included here **Testing** Examples! Current status: - all examples work, minus the next issue - "mipmap" is buggy because we don't have a good way to do mipmap/layer selection - automated testing? Co-authored-by: Dzmitry Malyshau <kvarkus@gmail.com> Co-authored-by: Dzmitry Malyshau <dmalyshau@mozilla.com> Co-authored-by: Dzmitry Malyshau <kvark@fastmail.com>
This commit is contained in:
41 files changed
+5524
-208
No files matched your search
Generated
+33
-1
@@ -687,6 +687,17 @@ dependencies = [
|
||||
"weezl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glow"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/grovesNL/glow?rev=0864897a28bbdd43f89f4fd8fdd4ed781b719f8a#0864897a28bbdd43f89f4fd8fdd4ed781b719f8a"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"slotmap",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpu-alloc"
|
||||
version = "0.4.7"
|
||||
@@ -846,6 +857,16 @@ dependencies = [
|
||||
"winapi-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "khronos-egl"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c2352bd1d0bceb871cb9d40f24360c8133c11d7486b68b5381c1dd1a32015e3"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"libloading 0.7.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.4.0"
|
||||
@@ -1019,7 +1040,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/gfx-rs/naga?rev=57b325602015ce6445749a4d8ee5d491edc818d7#57b325602015ce6445749a4d8ee5d491edc818d7"
|
||||
source = "git+https://github.com/gfx-rs/naga?rev=68a2efd3c5db62c2c011ccbad84f58be5e539fe3#68a2efd3c5db62c2c011ccbad84f58be5e539fe3"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bitflags",
|
||||
@@ -1586,6 +1607,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f173ac3d1a7e3b28003f40de0b5ce7fe2710f9b9dc3fc38664cebee46b3b6527"
|
||||
|
||||
[[package]]
|
||||
name = "slotmap"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "585cd5dffe4e9e06f6dfdf66708b70aca3f781bed561f4f667b2d9c0d4559e36"
|
||||
dependencies = [
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.6.1"
|
||||
@@ -1957,9 +1987,11 @@ dependencies = [
|
||||
"env_logger",
|
||||
"foreign-types",
|
||||
"fxhash",
|
||||
"glow",
|
||||
"gpu-alloc",
|
||||
"gpu-descriptor",
|
||||
"inplace_it",
|
||||
"khronos-egl",
|
||||
"libloading 0.7.0",
|
||||
"log",
|
||||
"metal",
|
||||
|
||||
@@ -20,6 +20,9 @@ default-members = ["wgpu", "player", "wgpu-hal", "wgpu-info"]
|
||||
[patch."https://github.com/zakarumych/gpu-alloc"]
|
||||
#gpu-alloc = { path = "../gpu-alloc/gpu-alloc" }
|
||||
|
||||
[patch."https://github.com/grovesNL/glow"]
|
||||
#glow = { path = "../glow" }
|
||||
|
||||
[patch.crates-io]
|
||||
#web-sys = { path = "../wasm-bindgen/crates/web-sys" }
|
||||
#js-sys = { path = "../wasm-bindgen/crates/js-sys" }
|
||||
|
||||
@@ -36,7 +36,7 @@ thiserror = "1"
|
||||
|
||||
[dependencies.naga]
|
||||
git = "https://github.com/gfx-rs/naga"
|
||||
rev = "57b325602015ce6445749a4d8ee5d491edc818d7"
|
||||
rev = "68a2efd3c5db62c2c011ccbad84f58be5e539fe3"
|
||||
features = ["wgsl-in"]
|
||||
|
||||
[dependencies.wgt]
|
||||
@@ -54,7 +54,7 @@ hal = { path = "../wgpu-hal", package = "wgpu-hal", features = ["metal"] }
|
||||
#Note: could also enable "vulkan" for Vulkan Portability
|
||||
|
||||
[target.'cfg(all(not(target_arch = "wasm32"), unix, not(target_os = "ios"), not(target_os = "macos")))'.dependencies]
|
||||
hal = { path = "../wgpu-hal", package = "wgpu-hal", features = ["vulkan"] }
|
||||
hal = { path = "../wgpu-hal", package = "wgpu-hal", features = ["vulkan", "gles"] }
|
||||
|
||||
[target.'cfg(all(not(target_arch = "wasm32"), windows))'.dependencies]
|
||||
hal = { path = "../wgpu-hal", package = "wgpu-hal", features = ["vulkan"] }
|
||||
|
||||
+1
-1
@@ -11,6 +11,6 @@ fn main() {
|
||||
metal: { all(not(wasm), apple) },
|
||||
dx12: { all(false, not(wasm), windows) },
|
||||
dx11: { all(false, not(wasm), windows) },
|
||||
gl: { all(false, any(wasm, unix_wo_apple)) },
|
||||
gl: { all(not(wasm), unix_wo_apple) },
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
device::{DeviceError, MissingFeatures, SHADER_STAGE_COUNT},
|
||||
device::{DeviceError, MissingDownlevelFlags, MissingFeatures, SHADER_STAGE_COUNT},
|
||||
hub::Resource,
|
||||
id::{BindGroupLayoutId, BufferId, DeviceId, SamplerId, TextureViewId, Valid},
|
||||
memory_init_tracker::MemoryInitTrackerAction,
|
||||
@@ -28,6 +28,8 @@ pub enum BindGroupLayoutEntryError {
|
||||
ArrayUnsupported,
|
||||
#[error(transparent)]
|
||||
MissingFeatures(#[from] MissingFeatures),
|
||||
#[error(transparent)]
|
||||
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Error)]
|
||||
|
||||
@@ -39,7 +39,10 @@ use crate::{
|
||||
StateChange,
|
||||
},
|
||||
conv,
|
||||
device::{AttachmentData, Device, DeviceError, RenderPassContext, SHADER_STAGE_COUNT},
|
||||
device::{
|
||||
AttachmentData, Device, DeviceError, MissingDownlevelFlags, RenderPassContext,
|
||||
SHADER_STAGE_COUNT,
|
||||
},
|
||||
hub::{GlobalIdentityHandlerFactory, HalApi, Hub, Resource, Storage, Token},
|
||||
id,
|
||||
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
|
||||
@@ -403,6 +406,10 @@ impl RenderBundleEncoder {
|
||||
indirect: true,
|
||||
pipeline: state.pipeline.last_state,
|
||||
};
|
||||
device
|
||||
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)
|
||||
.map_pass_err(scope)?;
|
||||
|
||||
let buffer = state
|
||||
.trackers
|
||||
.buffers
|
||||
@@ -439,6 +446,10 @@ impl RenderBundleEncoder {
|
||||
indirect: true,
|
||||
pipeline: state.pipeline.last_state,
|
||||
};
|
||||
device
|
||||
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)
|
||||
.map_pass_err(scope)?;
|
||||
|
||||
let buffer = state
|
||||
.trackers
|
||||
.buffers
|
||||
@@ -1104,6 +1115,8 @@ pub(super) enum RenderBundleErrorInner {
|
||||
ResourceUsageConflict(#[from] UsageConflict),
|
||||
#[error(transparent)]
|
||||
Draw(#[from] DrawError),
|
||||
#[error(transparent)]
|
||||
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
|
||||
}
|
||||
|
||||
impl<T> From<T> for RenderBundleErrorInner
|
||||
|
||||
@@ -5,13 +5,14 @@ use crate::{
|
||||
CommandEncoderError, CommandEncoderStatus, MapPassErr, PassErrorScope, QueryUseError,
|
||||
StateChange,
|
||||
},
|
||||
device::MissingDownlevelFlags,
|
||||
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
|
||||
id,
|
||||
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
|
||||
resource::{Buffer, Texture},
|
||||
track::{StatefulTrackerSubset, TrackerSet, UsageConflict, UseExtendError},
|
||||
validation::{check_buffer_usage, MissingBufferUsageError},
|
||||
Label, DOWNLEVEL_ERROR_WARNING_MESSAGE,
|
||||
Label,
|
||||
};
|
||||
|
||||
use hal::CommandEncoder as _;
|
||||
@@ -149,11 +150,6 @@ pub enum ComputePassErrorInner {
|
||||
MissingBufferUsage(#[from] MissingBufferUsageError),
|
||||
#[error("cannot pop debug group, because number of pushed debug groups is zero")]
|
||||
InvalidPopDebugGroup,
|
||||
#[error(
|
||||
"Compute shaders are not supported by the underlying platform. {}",
|
||||
DOWNLEVEL_ERROR_WARNING_MESSAGE
|
||||
)]
|
||||
ComputeShadersUnsupported,
|
||||
#[error(transparent)]
|
||||
Dispatch(#[from] DispatchError),
|
||||
#[error(transparent)]
|
||||
@@ -162,6 +158,8 @@ pub enum ComputePassErrorInner {
|
||||
PushConstants(#[from] PushConstantUploadError),
|
||||
#[error(transparent)]
|
||||
QueryUse(#[from] QueryUseError),
|
||||
#[error(transparent)]
|
||||
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
|
||||
}
|
||||
|
||||
/// Error encountered when performing a compute pass.
|
||||
@@ -262,6 +260,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
let hub = A::hub(self);
|
||||
let mut token = Token::root();
|
||||
|
||||
let (device_guard, mut token) = hub.devices.read(&mut token);
|
||||
|
||||
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
|
||||
let cmd_buf =
|
||||
CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, encoder_id).map_pass_err(scope)?;
|
||||
@@ -269,6 +269,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
cmd_buf.status = CommandEncoderStatus::Error;
|
||||
let raw = cmd_buf.encoder.open();
|
||||
|
||||
let device = &device_guard[cmd_buf.device_id.value];
|
||||
|
||||
#[cfg(feature = "trace")]
|
||||
if let Some(ref mut list) = cmd_buf.commands {
|
||||
list.push(crate::device::trace::Command::RunComputePass {
|
||||
@@ -276,17 +278,6 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
});
|
||||
}
|
||||
|
||||
if !cmd_buf
|
||||
.downlevel
|
||||
.flags
|
||||
.contains(wgt::DownlevelFlags::COMPUTE_SHADERS)
|
||||
{
|
||||
return Err(ComputePassError {
|
||||
scope: PassErrorScope::Pass(encoder_id),
|
||||
inner: ComputePassErrorInner::ComputeShadersUnsupported,
|
||||
});
|
||||
}
|
||||
|
||||
let (_, mut token) = hub.render_bundles.read(&mut token);
|
||||
let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token);
|
||||
let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token);
|
||||
@@ -516,6 +507,10 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
|
||||
state.is_ready().map_pass_err(scope)?;
|
||||
|
||||
device
|
||||
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)
|
||||
.map_pass_err(scope)?;
|
||||
|
||||
let indirect_buffer = state
|
||||
.trackers
|
||||
.buffers
|
||||
|
||||
@@ -77,7 +77,6 @@ pub struct CommandBuffer<A: hal::Api> {
|
||||
pub(crate) used_swap_chains: SmallVec<[Stored<id::SwapChainId>; 1]>,
|
||||
pub(crate) buffer_memory_init_actions: Vec<MemoryInitTrackerAction<id::BufferId>>,
|
||||
limits: wgt::Limits,
|
||||
downlevel: wgt::DownlevelCapabilities,
|
||||
support_fill_buffer_texture: bool,
|
||||
#[cfg(feature = "trace")]
|
||||
pub(crate) commands: Option<Vec<crate::device::trace::Command>>,
|
||||
@@ -88,7 +87,7 @@ impl<A: HalApi> CommandBuffer<A> {
|
||||
encoder: A::CommandEncoder,
|
||||
device_id: Stored<id::DeviceId>,
|
||||
limits: wgt::Limits,
|
||||
downlevel: wgt::DownlevelCapabilities,
|
||||
_downlevel: wgt::DownlevelCapabilities,
|
||||
features: wgt::Features,
|
||||
#[cfg(feature = "trace")] enable_tracing: bool,
|
||||
label: &Label,
|
||||
@@ -106,7 +105,6 @@ impl<A: HalApi> CommandBuffer<A> {
|
||||
used_swap_chains: Default::default(),
|
||||
buffer_memory_init_actions: Default::default(),
|
||||
limits,
|
||||
downlevel,
|
||||
support_fill_buffer_texture: features.contains(wgt::Features::CLEAR_COMMANDS),
|
||||
#[cfg(feature = "trace")]
|
||||
commands: if enable_tracing {
|
||||
|
||||
@@ -6,7 +6,10 @@ use crate::{
|
||||
PassErrorScope, QueryResetMap, QueryUseError, RenderCommand, RenderCommandError,
|
||||
StateChange,
|
||||
},
|
||||
device::{AttachmentData, RenderPassCompatibilityError, RenderPassContext},
|
||||
device::{
|
||||
AttachmentData, MissingDownlevelFlags, MissingFeatures, RenderPassCompatibilityError,
|
||||
RenderPassContext,
|
||||
},
|
||||
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
|
||||
id,
|
||||
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
|
||||
@@ -419,8 +422,10 @@ pub enum RenderPassErrorInner {
|
||||
SampleCountMismatch { actual: u32, expected: u32 },
|
||||
#[error("setting `values_offset` to be `None` is only for internal use in render bundles")]
|
||||
InvalidValuesOffset,
|
||||
#[error("required device features not enabled: {0:?}")]
|
||||
MissingDeviceFeatures(wgt::Features),
|
||||
#[error(transparent)]
|
||||
MissingFeatures(#[from] MissingFeatures),
|
||||
#[error(transparent)]
|
||||
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
|
||||
#[error("indirect draw uses bytes {offset}..{end_offset} {} which overruns indirect buffer of size {buffer_size}", count.map_or_else(String::new, |v| format!("(using count {})", v)))]
|
||||
IndirectBufferOverrun {
|
||||
count: Option<NonZeroU32>,
|
||||
@@ -483,17 +488,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn check_device_features(
|
||||
actual: wgt::Features,
|
||||
expected: wgt::Features,
|
||||
) -> Result<(), RenderPassErrorInner> {
|
||||
if !actual.contains(expected) {
|
||||
Err(RenderPassErrorInner::MissingDeviceFeatures(expected))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct RenderAttachment<'a> {
|
||||
texture_id: &'a Stored<id::TextureId>,
|
||||
selector: &'a TextureSelector,
|
||||
@@ -745,6 +739,8 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
|
||||
|
||||
let hal_desc = hal::RenderPassDescriptor {
|
||||
label,
|
||||
extent,
|
||||
sample_count,
|
||||
color_attachments: &colors,
|
||||
depth_stencil_attachment: depth_stencil,
|
||||
};
|
||||
@@ -1175,6 +1171,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
.inputs
|
||||
.extend(iter::repeat(VertexBufferState::EMPTY).take(empty_slots));
|
||||
let vertex_state = &mut state.vertex.inputs[slot as usize];
|
||||
//TODO: where are we checking that the offset is in bound?
|
||||
vertex_state.total_size = match size {
|
||||
Some(s) => s.get(),
|
||||
None => buffer.size - offset,
|
||||
@@ -1400,12 +1397,13 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
};
|
||||
|
||||
if count.is_some() {
|
||||
check_device_features(
|
||||
device.features,
|
||||
wgt::Features::MULTI_DRAW_INDIRECT,
|
||||
)
|
||||
.map_pass_err(scope)?;
|
||||
device
|
||||
.require_features(wgt::Features::MULTI_DRAW_INDIRECT)
|
||||
.map_pass_err(scope)?;
|
||||
}
|
||||
device
|
||||
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)
|
||||
.map_pass_err(scope)?;
|
||||
|
||||
let indirect_buffer = info
|
||||
.trackers
|
||||
@@ -1474,11 +1472,12 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
true => mem::size_of::<wgt::DrawIndexedIndirectArgs>(),
|
||||
} as u64;
|
||||
|
||||
check_device_features(
|
||||
device.features,
|
||||
wgt::Features::MULTI_DRAW_INDIRECT_COUNT,
|
||||
)
|
||||
.map_pass_err(scope)?;
|
||||
device
|
||||
.require_features(wgt::Features::MULTI_DRAW_INDIRECT_COUNT)
|
||||
.map_pass_err(scope)?;
|
||||
device
|
||||
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)
|
||||
.map_pass_err(scope)?;
|
||||
|
||||
let indirect_buffer = info
|
||||
.trackers
|
||||
|
||||
+52
-18
@@ -8,6 +8,7 @@ use crate::{
|
||||
track::{BufferState, TextureSelector, TextureState, TrackerSet, UsageConflict},
|
||||
validation::{self, check_buffer_usage, check_texture_usage},
|
||||
FastHashMap, Label, LabelHelpers as _, LifeGuard, MultiRefCount, Stored, SubmissionIndex,
|
||||
DOWNLEVEL_ERROR_WARNING_MESSAGE,
|
||||
};
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
@@ -253,6 +254,27 @@ pub enum CreateDeviceError {
|
||||
OutOfMemory,
|
||||
}
|
||||
|
||||
impl<A: hal::Api> Device<A> {
|
||||
pub(crate) fn require_features(&self, feature: wgt::Features) -> Result<(), MissingFeatures> {
|
||||
if self.features.contains(feature) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MissingFeatures(feature))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn require_downlevel_flags(
|
||||
&self,
|
||||
flags: wgt::DownlevelFlags,
|
||||
) -> Result<(), MissingDownlevelFlags> {
|
||||
if self.downlevel.flags.contains(flags) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MissingDownlevelFlags(flags))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: HalApi> Device<A> {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
@@ -311,14 +333,6 @@ impl<A: HalApi> Device<A> {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn require_features(&self, feature: wgt::Features) -> Result<(), MissingFeatures> {
|
||||
if self.features.contains(feature) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MissingFeatures(feature))
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_life_internal<'this, 'token: 'this>(
|
||||
tracker: &'this Mutex<life::LifetimeTracker<A>>,
|
||||
_token: &mut Token<'token, Self>,
|
||||
@@ -1026,6 +1040,14 @@ impl<A: HalApi> Device<A> {
|
||||
if is_writable_storage && entry.visibility.contains(wgt::ShaderStage::VERTEX) {
|
||||
required_features |= wgt::Features::VERTEX_WRITABLE_STORAGE;
|
||||
}
|
||||
if is_writable_storage && entry.visibility.contains(wgt::ShaderStage::FRAGMENT) {
|
||||
self.require_downlevel_flags(wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE)
|
||||
.map_err(binding_model::BindGroupLayoutEntryError::MissingDownlevelFlags)
|
||||
.map_err(|error| binding_model::CreateBindGroupLayoutError::Entry {
|
||||
binding: entry.binding,
|
||||
error,
|
||||
})?;
|
||||
}
|
||||
|
||||
self.require_features(required_features)
|
||||
.map_err(binding_model::BindGroupLayoutEntryError::MissingFeatures)
|
||||
@@ -1035,7 +1057,8 @@ impl<A: HalApi> Device<A> {
|
||||
})?;
|
||||
}
|
||||
|
||||
let hal_bindings = entry_map.values().cloned().collect::<Vec<_>>();
|
||||
let mut hal_bindings = entry_map.values().cloned().collect::<Vec<_>>();
|
||||
hal_bindings.sort_by_key(|b| b.binding);
|
||||
let hal_desc = hal::BindGroupLayoutDescriptor {
|
||||
label,
|
||||
entries: &hal_bindings,
|
||||
@@ -1728,13 +1751,7 @@ impl<A: HalApi> Device<A> {
|
||||
}
|
||||
}
|
||||
|
||||
if !self
|
||||
.downlevel
|
||||
.flags
|
||||
.contains(wgt::DownlevelFlags::COMPUTE_SHADERS)
|
||||
{
|
||||
return Err(pipeline::CreateComputePipelineError::ComputeShadersUnsupported);
|
||||
}
|
||||
self.require_downlevel_flags(wgt::DownlevelFlags::COMPUTE_SHADERS)?;
|
||||
|
||||
let mut derived_group_layouts =
|
||||
ArrayVec::<[binding_model::BindEntryMap; hal::MAX_BIND_GROUPS]>::new();
|
||||
@@ -1857,6 +1874,16 @@ impl<A: HalApi> Device<A> {
|
||||
.map_or(&[][..], |fragment| &fragment.targets);
|
||||
let depth_stencil_state = desc.depth_stencil.as_ref();
|
||||
|
||||
if !color_targets.is_empty() && {
|
||||
let first = &color_targets[0];
|
||||
color_targets[1..]
|
||||
.iter()
|
||||
.any(|ct| ct.write_mask != first.write_mask || ct.blend != first.blend)
|
||||
} {
|
||||
log::error!("Color targets: {:?}", color_targets);
|
||||
self.require_downlevel_flags(wgt::DownlevelFlags::INDEPENDENT_BLENDING)?;
|
||||
}
|
||||
|
||||
let mut io = validation::StageIo::default();
|
||||
let mut validated_stages = wgt::ShaderStage::empty();
|
||||
|
||||
@@ -2404,6 +2431,13 @@ impl From<hal::DeviceError> for DeviceError {
|
||||
#[error("Features {0:?} are required but not enabled on the device")]
|
||||
pub struct MissingFeatures(pub wgt::Features);
|
||||
|
||||
#[derive(Clone, Debug, Error)]
|
||||
#[error(
|
||||
"Downlevel flags {0:?} are required but not supported on the device.\n{}",
|
||||
DOWNLEVEL_ERROR_WARNING_MESSAGE
|
||||
)]
|
||||
pub struct MissingDownlevelFlags(pub wgt::DownlevelFlags);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(feature = "trace", derive(serde::Serialize))]
|
||||
#[cfg_attr(feature = "replay", derive(serde::Deserialize))]
|
||||
@@ -2484,7 +2518,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
let (device_guard, _) = hub.devices.read(&mut token);
|
||||
let device = device_guard.get(device_id).map_err(|_| InvalidDevice)?;
|
||||
|
||||
Ok(device.downlevel)
|
||||
Ok(device.downlevel.clone())
|
||||
}
|
||||
|
||||
pub fn device_create_buffer<A: HalApi>(
|
||||
@@ -3606,7 +3640,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
encoder,
|
||||
dev_stored,
|
||||
device.limits.clone(),
|
||||
device.downlevel,
|
||||
device.downlevel.clone(),
|
||||
device.features,
|
||||
#[cfg(feature = "trace")]
|
||||
device.trace.is_some(),
|
||||
|
||||
@@ -854,6 +854,7 @@ impl HalApi for hal::api::Dx11 {
|
||||
surface.dx11.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
#[cfg(gl)]
|
||||
impl HalApi for hal::api::Gles {
|
||||
@@ -864,7 +865,7 @@ impl HalApi for hal::api::Gles {
|
||||
fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface {
|
||||
surface.gl.as_mut().unwrap()
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn _test_send_sync(global: &Global<IdentityManagerFactory>) {
|
||||
|
||||
+28
-22
@@ -31,35 +31,35 @@ pub struct Instance {
|
||||
|
||||
impl Instance {
|
||||
pub fn new(name: &str, backends: BackendBit) -> Self {
|
||||
let mut flags = hal::InstanceFlag::empty();
|
||||
if cfg!(debug_assertions) {
|
||||
flags |= hal::InstanceFlag::VALIDATION;
|
||||
flags |= hal::InstanceFlag::DEBUG;
|
||||
}
|
||||
let hal_desc = hal::InstanceDescriptor {
|
||||
name: "wgpu",
|
||||
flags,
|
||||
};
|
||||
|
||||
let map = |backend: Backend| unsafe {
|
||||
if backends.contains(backend.into()) {
|
||||
hal::Instance::init(&hal_desc).ok()
|
||||
fn init<A: HalApi>(mask: BackendBit) -> Option<A::Instance> {
|
||||
if mask.contains(A::VARIANT.into()) {
|
||||
let mut flags = hal::InstanceFlag::empty();
|
||||
if cfg!(debug_assertions) {
|
||||
flags |= hal::InstanceFlag::VALIDATION;
|
||||
flags |= hal::InstanceFlag::DEBUG;
|
||||
}
|
||||
let hal_desc = hal::InstanceDescriptor {
|
||||
name: "wgpu",
|
||||
flags,
|
||||
};
|
||||
unsafe { hal::Instance::init(&hal_desc).ok() }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
#[cfg(vulkan)]
|
||||
vulkan: map(Backend::Vulkan),
|
||||
vulkan: init::<hal::api::Vulkan>(backends),
|
||||
#[cfg(metal)]
|
||||
metal: map(Backend::Metal),
|
||||
metal: init::<hal::api::Metal>(backends),
|
||||
#[cfg(dx12)]
|
||||
dx12: map(Backend::Dx12),
|
||||
dx12: init(Backend::Dx12, backends),
|
||||
#[cfg(dx11)]
|
||||
dx11: map(Backend::Dx11),
|
||||
dx11: init(Backend::Dx11, backends),
|
||||
#[cfg(gl)]
|
||||
gl: map(Backend::Gl),
|
||||
gl: init::<hal::api::Gles>(backends),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +210,13 @@ impl<A: HalApi> Adapter<A> {
|
||||
|
||||
let caps = &self.raw.capabilities;
|
||||
if !caps.downlevel.is_webgpu_compliant() {
|
||||
log::warn!("{}", DOWNLEVEL_WARNING_MESSAGE);
|
||||
let missing_flags = wgt::DownlevelFlags::COMPLIANT - caps.downlevel.flags;
|
||||
log::warn!(
|
||||
"Missing downlevel flags: {:?}\n{}",
|
||||
missing_flags,
|
||||
DOWNLEVEL_WARNING_MESSAGE
|
||||
);
|
||||
log::info!("{:#?}", caps.downlevel);
|
||||
}
|
||||
|
||||
// Verify feature preconditions
|
||||
@@ -252,7 +258,7 @@ impl<A: HalApi> Adapter<A> {
|
||||
ref_count: self.life_guard.add_ref(),
|
||||
},
|
||||
caps.alignments.clone(),
|
||||
caps.downlevel,
|
||||
caps.downlevel.clone(),
|
||||
desc,
|
||||
trace_path,
|
||||
)
|
||||
@@ -653,7 +659,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
|
||||
let (adapter_guard, _) = hub.adapters.read(&mut token);
|
||||
adapter_guard
|
||||
.get(adapter_id)
|
||||
.map(|adapter| adapter.raw.capabilities.downlevel)
|
||||
.map(|adapter| adapter.raw.capabilities.downlevel.clone())
|
||||
.map_err(|_| InvalidAdapter)
|
||||
}
|
||||
|
||||
|
||||
@@ -207,14 +207,12 @@ macro_rules! gfx_select {
|
||||
wgt::Backend::Vulkan => $global.$method::<$crate::api::Vulkan>( $($param),* ),
|
||||
#[cfg(all(not(target_arch = "wasm32"), any(target_os = "ios", target_os = "macos")))]
|
||||
wgt::Backend::Metal => $global.$method::<$crate::api::Metal>( $($param),* ),
|
||||
/*
|
||||
#[cfg(all(not(target_arch = "wasm32"), windows))]
|
||||
wgt::Backend::Dx12 => $global.$method::<$crate::backend::Dx12>( $($param),* ),
|
||||
#[cfg(all(not(target_arch = "wasm32"), windows))]
|
||||
wgt::Backend::Dx11 => $global.$method::<$crate::backend::Dx11>( $($param),* ),
|
||||
#[cfg(any(target_arch = "wasm32", all(unix, not(any(target_os = "ios", target_os = "macos")))))]
|
||||
wgt::Backend::Gl => $global.$method::<$crate::backend::Gl>( $($param),+ ),
|
||||
*/
|
||||
//#[cfg(all(not(target_arch = "wasm32"), windows))]
|
||||
//wgt::Backend::Dx12 => $global.$method::<$crate::api::Dx12>( $($param),* ),
|
||||
//#[cfg(all(not(target_arch = "wasm32"), windows))]
|
||||
//wgt::Backend::Dx11 => $global.$method::<$crate::api::Dx11>( $($param),* ),
|
||||
#[cfg(all(not(target_arch = "wasm32"), unix, not(any(target_os = "ios", target_os = "macos"))))]
|
||||
wgt::Backend::Gl => $global.$method::<$crate::api::Gles>( $($param),+ ),
|
||||
other => panic!("Unexpected backend {:?}", other),
|
||||
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::{
|
||||
binding_model::{CreateBindGroupLayoutError, CreatePipelineLayoutError},
|
||||
device::{DeviceError, MissingFeatures, RenderPassContext},
|
||||
device::{DeviceError, MissingDownlevelFlags, MissingFeatures, RenderPassContext},
|
||||
hub::Resource,
|
||||
id::{DeviceId, PipelineLayoutId, ShaderModuleId},
|
||||
validation, Label, LifeGuard, Stored, DOWNLEVEL_ERROR_WARNING_MESSAGE,
|
||||
validation, Label, LifeGuard, Stored,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
use thiserror::Error;
|
||||
@@ -109,11 +109,8 @@ pub enum CreateComputePipelineError {
|
||||
Stage(#[from] validation::StageError),
|
||||
#[error("Internal error: {0}")]
|
||||
Internal(String),
|
||||
#[error(
|
||||
"Compute shaders are not supported by the underlying platform. {}",
|
||||
DOWNLEVEL_ERROR_WARNING_MESSAGE
|
||||
)]
|
||||
ComputeShadersUnsupported,
|
||||
#[error(transparent)]
|
||||
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -258,6 +255,8 @@ pub enum CreateRenderPipelineError {
|
||||
ConservativeRasterizationNonFillPolygonMode,
|
||||
#[error(transparent)]
|
||||
MissingFeatures(#[from] MissingFeatures),
|
||||
#[error(transparent)]
|
||||
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
|
||||
#[error("error matching {stage:?} shader requirements against the pipeline")]
|
||||
Stage {
|
||||
stage: wgt::ShaderStage,
|
||||
|
||||
@@ -658,7 +658,7 @@ impl NumericType {
|
||||
Tf::Bc4RUnorm | Tf::Bc4RSnorm | Tf::EacRUnorm | Tf::EacRSnorm => {
|
||||
(NumericDimension::Scalar, Sk::Float)
|
||||
}
|
||||
Tf::Bc5RgUnorm | Tf::Bc5RgSnorm | Tf::EtcRgUnorm | Tf::EtcRgSnorm => {
|
||||
Tf::Bc5RgUnorm | Tf::Bc5RgSnorm | Tf::EacRgUnorm | Tf::EacRgSnorm => {
|
||||
(NumericDimension::Vector(Vs::Bi), Sk::Float)
|
||||
}
|
||||
Tf::Bc6hRgbUfloat | Tf::Bc6hRgbSfloat | Tf::Etc2RgbUnorm | Tf::Etc2RgbUnormSrgb => {
|
||||
|
||||
+9
-3
@@ -15,6 +15,7 @@ license = "MIT OR Apache-2.0"
|
||||
default = []
|
||||
metal = ["naga/msl-out", "block", "foreign-types"]
|
||||
vulkan = ["naga/spv-out", "ash", "gpu-alloc", "gpu-descriptor", "libloading", "inplace_it", "renderdoc-sys"]
|
||||
gles = ["naga/glsl-out", "glow", "egl", "libloading"]
|
||||
|
||||
[dependencies]
|
||||
bitflags = "1.0"
|
||||
@@ -26,7 +27,6 @@ wgt = { package = "wgpu-types", path = "../wgpu-types" }
|
||||
# backends common
|
||||
arrayvec = "0.5"
|
||||
fxhash = "0.2.1"
|
||||
libloading = { version = "0.7", optional = true }
|
||||
log = "0.4"
|
||||
# backend: Metal
|
||||
block = { version = "0.1", optional = true }
|
||||
@@ -37,6 +37,12 @@ gpu-alloc = { version = "0.4", optional = true }
|
||||
gpu-descriptor = { version = "0.1", optional = true }
|
||||
inplace_it = { version ="0.3.3", optional = true }
|
||||
renderdoc-sys = { version = "0.7.1", optional = true }
|
||||
# backend: Gles
|
||||
glow = { git = "https://github.com/grovesNL/glow", rev = "0864897a28bbdd43f89f4fd8fdd4ed781b719f8a", optional = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
egl = { package = "khronos-egl", version = "4.1", features = ["dynamic"], optional = true }
|
||||
libloading = { version = "0.7", optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winapi = { version = "0.3", features = ["libloaderapi", "windef", "winuser"] }
|
||||
@@ -48,11 +54,11 @@ core-graphics-types = "0.1"
|
||||
|
||||
[dependencies.naga]
|
||||
git = "https://github.com/gfx-rs/naga"
|
||||
rev = "57b325602015ce6445749a4d8ee5d491edc818d7"
|
||||
rev = "68a2efd3c5db62c2c011ccbad84f58be5e539fe3"
|
||||
|
||||
[dev-dependencies.naga]
|
||||
git = "https://github.com/gfx-rs/naga"
|
||||
rev = "57b325602015ce6445749a4d8ee5d491edc818d7"
|
||||
rev = "68a2efd3c5db62c2c011ccbad84f58be5e539fe3"
|
||||
features = ["wgsl-in"]
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -239,7 +239,7 @@ impl<A: hal::Api> Example<A> {
|
||||
label: Some("stage"),
|
||||
size: texture_data.len() as wgt::BufferAddress,
|
||||
usage: hal::BufferUse::MAP_WRITE | hal::BufferUse::COPY_SRC,
|
||||
memory_flags: hal::MemoryFlag::TRANSIENT,
|
||||
memory_flags: hal::MemoryFlag::TRANSIENT | hal::MemoryFlag::PREFER_COHERENT,
|
||||
};
|
||||
let staging_buffer = unsafe { device.create_buffer(&staging_buffer_desc).unwrap() };
|
||||
unsafe {
|
||||
@@ -342,7 +342,7 @@ impl<A: hal::Api> Example<A> {
|
||||
label: Some("global"),
|
||||
size: mem::size_of::<Globals>() as wgt::BufferAddress,
|
||||
usage: hal::BufferUse::MAP_WRITE | hal::BufferUse::UNIFORM,
|
||||
memory_flags: hal::MemoryFlag::empty(),
|
||||
memory_flags: hal::MemoryFlag::PREFER_COHERENT,
|
||||
};
|
||||
let global_buffer = unsafe {
|
||||
let buffer = device.create_buffer(&global_buffer_desc).unwrap();
|
||||
@@ -363,7 +363,7 @@ impl<A: hal::Api> Example<A> {
|
||||
label: Some("local"),
|
||||
size: (MAX_BUNNIES as wgt::BufferAddress) * wgt::BIND_BUFFER_ALIGNMENT,
|
||||
usage: hal::BufferUse::MAP_WRITE | hal::BufferUse::UNIFORM,
|
||||
memory_flags: hal::MemoryFlag::empty(),
|
||||
memory_flags: hal::MemoryFlag::PREFER_COHERENT,
|
||||
};
|
||||
let local_buffer = unsafe { device.create_buffer(&local_buffer_desc).unwrap() };
|
||||
|
||||
@@ -474,6 +474,10 @@ impl<A: hal::Api> Example<A> {
|
||||
})
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.bunnies.is_empty()
|
||||
}
|
||||
|
||||
fn exit(mut self) {
|
||||
unsafe {
|
||||
{
|
||||
@@ -597,6 +601,12 @@ impl<A: hal::Api> Example<A> {
|
||||
};
|
||||
let pass_desc = hal::RenderPassDescriptor {
|
||||
label: None,
|
||||
extent: wgt::Extent3d {
|
||||
width: self.extent[0],
|
||||
height: self.extent[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
sample_count: 1,
|
||||
color_attachments: &[hal::ColorAttachment {
|
||||
target: hal::Attachment {
|
||||
view: &surface_tex_view,
|
||||
@@ -681,7 +691,9 @@ impl<A: hal::Api> Example<A> {
|
||||
type Api = hal::api::Metal;
|
||||
#[cfg(all(feature = "vulkan", not(feature = "metal")))]
|
||||
type Api = hal::api::Vulkan;
|
||||
#[cfg(all(not(feature = "vulkan"), not(feature = "metal")))]
|
||||
#[cfg(all(feature = "gles", not(feature = "metal"), not(feature = "vulkan")))]
|
||||
type Api = hal::api::Gles;
|
||||
#[cfg(not(any(feature = "metal", feature = "vulkan", feature = "gles")))]
|
||||
type Api = hal::api::Empty;
|
||||
|
||||
fn main() {
|
||||
@@ -724,11 +736,12 @@ fn main() {
|
||||
}
|
||||
},
|
||||
winit::event::Event::RedrawRequested(_) => {
|
||||
let ex = example.as_mut().unwrap();
|
||||
{
|
||||
accum_time += last_frame_inst.elapsed().as_secs_f32();
|
||||
last_frame_inst = Instant::now();
|
||||
frame_count += 1;
|
||||
if frame_count == 100 {
|
||||
if frame_count == 100 && !ex.is_empty() {
|
||||
println!(
|
||||
"Avg frame time {}ms",
|
||||
accum_time * 1000.0 / frame_count as f32
|
||||
@@ -737,7 +750,7 @@ fn main() {
|
||||
frame_count = 0;
|
||||
}
|
||||
}
|
||||
example.as_mut().unwrap().render();
|
||||
ex.render();
|
||||
}
|
||||
winit::event::Event::LoopDestroyed => {
|
||||
example.take().unwrap().exit();
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
use glow::HasContext;
|
||||
use std::sync::Arc;
|
||||
|
||||
// https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html
|
||||
|
||||
impl super::Adapter {
|
||||
/// According to the OpenGL specification, the version information is
|
||||
/// expected to follow the following syntax:
|
||||
///
|
||||
/// ~~~bnf
|
||||
/// <major> ::= <number>
|
||||
/// <minor> ::= <number>
|
||||
/// <revision> ::= <number>
|
||||
/// <vendor-info> ::= <string>
|
||||
/// <release> ::= <major> "." <minor> ["." <release>]
|
||||
/// <version> ::= <release> [" " <vendor-info>]
|
||||
/// ~~~
|
||||
///
|
||||
/// Note that this function is intentionally lenient in regards to parsing,
|
||||
/// and will try to recover at least the first two version numbers without
|
||||
/// resulting in an `Err`.
|
||||
/// # Notes
|
||||
/// `WebGL 2` version returned as `OpenGL ES 3.0`
|
||||
fn parse_version(mut src: &str) -> Result<(u8, u8), crate::InstanceError> {
|
||||
let webgl_sig = "WebGL ";
|
||||
// According to the WebGL specification
|
||||
// VERSION WebGL<space>1.0<space><vendor-specific information>
|
||||
// SHADING_LANGUAGE_VERSION WebGL<space>GLSL<space>ES<space>1.0<space><vendor-specific information>
|
||||
let is_webgl = src.starts_with(webgl_sig);
|
||||
if is_webgl {
|
||||
let pos = src.rfind(webgl_sig).unwrap_or(0);
|
||||
src = &src[pos + webgl_sig.len()..];
|
||||
} else {
|
||||
let es_sig = " ES ";
|
||||
match src.rfind(es_sig) {
|
||||
Some(pos) => {
|
||||
src = &src[pos + es_sig.len()..];
|
||||
}
|
||||
None => {
|
||||
log::warn!("ES not found in '{}'", src);
|
||||
return Err(crate::InstanceError);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let glsl_es_sig = "GLSL ES ";
|
||||
let is_glsl = match src.find(glsl_es_sig) {
|
||||
Some(pos) => {
|
||||
src = &src[pos + glsl_es_sig.len()..];
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
|
||||
let (version, _vendor_info) = match src.find(' ') {
|
||||
Some(i) => (&src[..i], src[i + 1..].to_string()),
|
||||
None => (src, String::new()),
|
||||
};
|
||||
|
||||
// TODO: make this even more lenient so that we can also accept
|
||||
// `<major> "." <minor> [<???>]`
|
||||
let mut it = version.split('.');
|
||||
let major = it.next().and_then(|s| s.parse().ok());
|
||||
let minor = it.next().and_then(|s| {
|
||||
let trimmed = if s.starts_with('0') {
|
||||
"0"
|
||||
} else {
|
||||
s.trim_end_matches('0')
|
||||
};
|
||||
trimmed.parse().ok()
|
||||
});
|
||||
|
||||
match (major, minor) {
|
||||
(Some(major), Some(minor)) => Ok((
|
||||
// Return WebGL 2.0 version as OpenGL ES 3.0
|
||||
if is_webgl && !is_glsl {
|
||||
major + 1
|
||||
} else {
|
||||
major
|
||||
},
|
||||
minor,
|
||||
)),
|
||||
_ => {
|
||||
log::warn!("Unable to extract the version from '{}'", version);
|
||||
Err(crate::InstanceError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn make_info(vendor_orig: String, renderer_orig: String) -> wgt::AdapterInfo {
|
||||
let vendor = vendor_orig.to_lowercase();
|
||||
let renderer = renderer_orig.to_lowercase();
|
||||
|
||||
// opengl has no way to discern device_type, so we can try to infer it from the renderer string
|
||||
let strings_that_imply_integrated = [
|
||||
" xpress", // space here is on purpose so we don't match express
|
||||
"radeon hd 4200",
|
||||
"radeon hd 4250",
|
||||
"radeon hd 4290",
|
||||
"radeon hd 4270",
|
||||
"radeon hd 4225",
|
||||
"radeon hd 3100",
|
||||
"radeon hd 3200",
|
||||
"radeon hd 3000",
|
||||
"radeon hd 3300",
|
||||
"radeon(tm) r4 graphics",
|
||||
"radeon(tm) r5 graphics",
|
||||
"radeon(tm) r6 graphics",
|
||||
"radeon(tm) r7 graphics",
|
||||
"radeon r7 graphics",
|
||||
"nforce", // all nvidia nforce are integrated
|
||||
"tegra", // all nvidia tegra are integrated
|
||||
"shield", // all nvidia shield are integrated
|
||||
"igp",
|
||||
"mali",
|
||||
"intel",
|
||||
];
|
||||
let strings_that_imply_cpu = ["mesa offscreen", "swiftshader", "lavapipe"];
|
||||
|
||||
//TODO: handle Intel Iris XE as discreet
|
||||
let inferred_device_type = if vendor.contains("qualcomm")
|
||||
|| vendor.contains("intel")
|
||||
|| strings_that_imply_integrated
|
||||
.iter()
|
||||
.any(|&s| renderer.contains(s))
|
||||
{
|
||||
wgt::DeviceType::IntegratedGpu
|
||||
} else if strings_that_imply_cpu.iter().any(|&s| renderer.contains(s)) {
|
||||
wgt::DeviceType::Cpu
|
||||
} else {
|
||||
wgt::DeviceType::DiscreteGpu
|
||||
};
|
||||
|
||||
// source: Sascha Willems at Vulkan
|
||||
let vendor_id = if vendor.contains("amd") {
|
||||
0x1002
|
||||
} else if vendor.contains("imgtec") {
|
||||
0x1010
|
||||
} else if vendor.contains("nvidia") {
|
||||
0x10DE
|
||||
} else if vendor.contains("arm") {
|
||||
0x13B5
|
||||
} else if vendor.contains("qualcomm") {
|
||||
0x5143
|
||||
} else if vendor.contains("intel") {
|
||||
0x8086
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
wgt::AdapterInfo {
|
||||
name: renderer_orig,
|
||||
vendor: vendor_id,
|
||||
device: 0,
|
||||
device_type: inferred_device_type,
|
||||
backend: wgt::Backend::Gl,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) unsafe fn expose(gl: glow::Context) -> Option<crate::ExposedAdapter<super::Api>> {
|
||||
let vendor = gl.get_parameter_string(glow::VENDOR);
|
||||
let renderer = gl.get_parameter_string(glow::RENDERER);
|
||||
let version = gl.get_parameter_string(glow::VERSION);
|
||||
log::info!("Vendor: {}", vendor);
|
||||
log::info!("Renderer: {}", renderer);
|
||||
log::info!("Version: {}", version);
|
||||
|
||||
let ver = Self::parse_version(&version).ok()?;
|
||||
let extensions = gl.supported_extensions();
|
||||
log::debug!("Extensions: {:#?}", extensions);
|
||||
|
||||
let shading_language_version = {
|
||||
let sl_version = gl.get_parameter_string(glow::SHADING_LANGUAGE_VERSION);
|
||||
log::info!("SL version: {}", sl_version);
|
||||
let (sl_major, sl_minor) = Self::parse_version(&sl_version).ok()?;
|
||||
let value = sl_major as u16 * 100 + sl_minor as u16 * 10;
|
||||
naga::back::glsl::Version::Embedded(value)
|
||||
};
|
||||
|
||||
let mut features = wgt::Features::empty() | wgt::Features::TEXTURE_COMPRESSION_ETC2;
|
||||
features.set(
|
||||
wgt::Features::DEPTH_CLAMPING,
|
||||
extensions.contains("GL_EXT_depth_clamp"),
|
||||
);
|
||||
features.set(wgt::Features::VERTEX_WRITABLE_STORAGE, ver >= (3, 1));
|
||||
|
||||
let mut downlevel_flags = wgt::DownlevelFlags::empty()
|
||||
| wgt::DownlevelFlags::DEVICE_LOCAL_IMAGE_COPIES
|
||||
| wgt::DownlevelFlags::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES
|
||||
| wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES
|
||||
| wgt::DownlevelFlags::COMPARISON_SAMPLERS;
|
||||
downlevel_flags.set(wgt::DownlevelFlags::COMPUTE_SHADERS, ver >= (3, 1));
|
||||
downlevel_flags.set(
|
||||
wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE,
|
||||
ver >= (3, 1),
|
||||
);
|
||||
downlevel_flags.set(wgt::DownlevelFlags::INDIRECT_EXECUTION, ver >= (3, 1));
|
||||
//TODO: we can actually support positive `base_vertex` in the same way
|
||||
// as we emulate the `start_instance`. But we can't deal with negatives...
|
||||
downlevel_flags.set(wgt::DownlevelFlags::BASE_VERTEX, ver >= (3, 2));
|
||||
downlevel_flags.set(
|
||||
wgt::DownlevelFlags::INDEPENDENT_BLENDING,
|
||||
ver >= (3, 2) || extensions.contains("GL_EXT_draw_buffers_indexed"),
|
||||
);
|
||||
|
||||
let max_texture_size = gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE) as u32;
|
||||
let max_texture_3d_size = gl.get_parameter_i32(glow::MAX_3D_TEXTURE_SIZE) as u32;
|
||||
|
||||
let min_uniform_buffer_offset_alignment =
|
||||
gl.get_parameter_i32(glow::UNIFORM_BUFFER_OFFSET_ALIGNMENT);
|
||||
let min_storage_buffer_offset_alignment = if cfg!(target_arch = "wasm32") {
|
||||
256
|
||||
} else {
|
||||
gl.get_parameter_i32(glow::SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT)
|
||||
};
|
||||
let max_uniform_buffers_per_shader_stage =
|
||||
gl.get_parameter_i32(glow::MAX_VERTEX_UNIFORM_BLOCKS)
|
||||
.min(gl.get_parameter_i32(glow::MAX_FRAGMENT_UNIFORM_BLOCKS)) as u32;
|
||||
let max_storage_buffers_per_shader_stage = gl
|
||||
.get_parameter_i32(glow::MAX_VERTEX_SHADER_STORAGE_BLOCKS)
|
||||
.min(gl.get_parameter_i32(glow::MAX_FRAGMENT_SHADER_STORAGE_BLOCKS))
|
||||
as u32;
|
||||
let max_storage_textures_per_shader_stage =
|
||||
gl.get_parameter_i32(glow::MAX_FRAGMENT_IMAGE_UNIFORMS) as u32;
|
||||
|
||||
let limits = wgt::Limits {
|
||||
max_texture_dimension_1d: max_texture_size,
|
||||
max_texture_dimension_2d: max_texture_size,
|
||||
max_texture_dimension_3d: max_texture_3d_size,
|
||||
max_texture_array_layers: gl.get_parameter_i32(glow::MAX_ARRAY_TEXTURE_LAYERS) as u32,
|
||||
max_bind_groups: crate::MAX_BIND_GROUPS as u32,
|
||||
max_dynamic_uniform_buffers_per_pipeline_layout: max_uniform_buffers_per_shader_stage,
|
||||
max_dynamic_storage_buffers_per_pipeline_layout: max_storage_buffers_per_shader_stage,
|
||||
max_sampled_textures_per_shader_stage: super::MAX_TEXTURE_SLOTS as u32,
|
||||
max_samplers_per_shader_stage: super::MAX_SAMPLERS as u32,
|
||||
max_storage_buffers_per_shader_stage,
|
||||
max_storage_textures_per_shader_stage,
|
||||
max_uniform_buffers_per_shader_stage,
|
||||
max_uniform_buffer_binding_size: gl.get_parameter_i32(glow::MAX_UNIFORM_BLOCK_SIZE)
|
||||
as u32,
|
||||
max_storage_buffer_binding_size: if ver >= (3, 1) {
|
||||
gl.get_parameter_i32(glow::MAX_SHADER_STORAGE_BLOCK_SIZE) as u32
|
||||
} else {
|
||||
0
|
||||
},
|
||||
max_vertex_buffers: gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_BINDINGS) as u32,
|
||||
max_vertex_attributes: (gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIBS) as u32)
|
||||
.min(super::MAX_VERTEX_ATTRIBUTES as u32),
|
||||
max_vertex_buffer_array_stride: gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_STRIDE)
|
||||
as u32,
|
||||
max_push_constant_size: 0,
|
||||
};
|
||||
|
||||
let mut private_caps = super::PrivateCapability::empty();
|
||||
private_caps.set(
|
||||
super::PrivateCapability::SHADER_BINDING_LAYOUT,
|
||||
ver >= (3, 1),
|
||||
);
|
||||
private_caps.set(
|
||||
super::PrivateCapability::SHADER_TEXTURE_SHADOW_LOD,
|
||||
extensions.contains("GL_EXT_texture_shadow_lod"),
|
||||
);
|
||||
private_caps.set(super::PrivateCapability::MEMORY_BARRIERS, ver >= (3, 1));
|
||||
private_caps.set(
|
||||
super::PrivateCapability::VERTEX_BUFFER_LAYOUT,
|
||||
ver >= (3, 1),
|
||||
);
|
||||
|
||||
let downlevel_limits = wgt::DownlevelLimits {};
|
||||
|
||||
Some(crate::ExposedAdapter {
|
||||
adapter: super::Adapter {
|
||||
shared: Arc::new(super::AdapterShared {
|
||||
context: gl,
|
||||
private_caps,
|
||||
shading_language_version,
|
||||
}),
|
||||
},
|
||||
info: Self::make_info(vendor, renderer),
|
||||
features,
|
||||
capabilities: crate::Capabilities {
|
||||
limits,
|
||||
downlevel: wgt::DownlevelCapabilities {
|
||||
flags: downlevel_flags,
|
||||
limits: downlevel_limits,
|
||||
shader_model: wgt::ShaderModel::Sm5,
|
||||
},
|
||||
alignments: crate::Alignments {
|
||||
buffer_copy_offset: wgt::BufferSize::new(4).unwrap(),
|
||||
buffer_copy_pitch: wgt::BufferSize::new(4).unwrap(),
|
||||
uniform_buffer_offset: wgt::BufferSize::new(
|
||||
min_storage_buffer_offset_alignment as u64,
|
||||
)
|
||||
.unwrap(),
|
||||
storage_buffer_offset: wgt::BufferSize::new(
|
||||
min_uniform_buffer_offset_alignment as u64,
|
||||
)
|
||||
.unwrap(),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Adapter<super::Api> for super::Adapter {
|
||||
unsafe fn open(
|
||||
&self,
|
||||
features: wgt::Features,
|
||||
) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
|
||||
let gl = &self.shared.context;
|
||||
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
|
||||
gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
|
||||
let main_vao = gl
|
||||
.create_vertex_array()
|
||||
.map_err(|_| crate::DeviceError::OutOfMemory)?;
|
||||
gl.bind_vertex_array(Some(main_vao));
|
||||
|
||||
let zero_buffer = gl
|
||||
.create_buffer()
|
||||
.map_err(|_| crate::DeviceError::OutOfMemory)?;
|
||||
gl.bind_buffer(glow::COPY_READ_BUFFER, Some(zero_buffer));
|
||||
let zeroes = vec![0u8; super::ZERO_BUFFER_SIZE];
|
||||
gl.buffer_data_u8_slice(glow::COPY_READ_BUFFER, &zeroes, glow::STATIC_DRAW);
|
||||
|
||||
Ok(crate::OpenDevice {
|
||||
device: super::Device {
|
||||
shared: Arc::clone(&self.shared),
|
||||
main_vao,
|
||||
},
|
||||
queue: super::Queue {
|
||||
shared: Arc::clone(&self.shared),
|
||||
features,
|
||||
draw_fbo: gl
|
||||
.create_framebuffer()
|
||||
.map_err(|_| crate::DeviceError::OutOfMemory)?,
|
||||
copy_fbo: gl
|
||||
.create_framebuffer()
|
||||
.map_err(|_| crate::DeviceError::OutOfMemory)?,
|
||||
zero_buffer,
|
||||
temp_query_results: Vec::new(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn texture_format_capabilities(
|
||||
&self,
|
||||
format: wgt::TextureFormat,
|
||||
) -> crate::TextureFormatCapability {
|
||||
use crate::TextureFormatCapability as Tfc;
|
||||
use wgt::TextureFormat as Tf;
|
||||
// The storage types are sprinkled based on section
|
||||
// "TEXTURE IMAGE LOADS AND STORES" of GLES-3.2 spec.
|
||||
let unfiltered_color = Tfc::SAMPLED | Tfc::COLOR_ATTACHMENT;
|
||||
let filtered_color = unfiltered_color | Tfc::SAMPLED_LINEAR | Tfc::COLOR_ATTACHMENT_BLEND;
|
||||
match format {
|
||||
Tf::R8Unorm | Tf::R8Snorm => filtered_color,
|
||||
Tf::R8Uint | Tf::R8Sint | Tf::R16Uint | Tf::R16Sint => unfiltered_color,
|
||||
Tf::R16Float | Tf::Rg8Unorm | Tf::Rg8Snorm => filtered_color,
|
||||
Tf::Rg8Uint | Tf::Rg8Sint | Tf::R32Uint | Tf::R32Sint => {
|
||||
unfiltered_color | Tfc::STORAGE
|
||||
}
|
||||
Tf::R32Float => unfiltered_color,
|
||||
Tf::Rg16Uint | Tf::Rg16Sint => unfiltered_color,
|
||||
Tf::Rg16Float | Tf::Rgba8Unorm | Tf::Rgba8UnormSrgb => filtered_color | Tfc::STORAGE,
|
||||
Tf::Bgra8UnormSrgb | Tf::Rgba8Snorm | Tf::Bgra8Unorm => filtered_color,
|
||||
Tf::Rgba8Uint | Tf::Rgba8Sint => unfiltered_color | Tfc::STORAGE,
|
||||
Tf::Rgb10a2Unorm | Tf::Rg11b10Float => filtered_color,
|
||||
Tf::Rg32Uint | Tf::Rg32Sint => unfiltered_color,
|
||||
Tf::Rg32Float => unfiltered_color | Tfc::STORAGE,
|
||||
Tf::Rgba16Uint | Tf::Rgba16Sint => unfiltered_color | Tfc::STORAGE,
|
||||
Tf::Rgba16Float => filtered_color | Tfc::STORAGE,
|
||||
Tf::Rgba32Uint | Tf::Rgba32Sint => unfiltered_color | Tfc::STORAGE,
|
||||
Tf::Rgba32Float => unfiltered_color | Tfc::STORAGE,
|
||||
Tf::Depth32Float => Tfc::SAMPLED | Tfc::DEPTH_STENCIL_ATTACHMENT,
|
||||
Tf::Depth24Plus => Tfc::SAMPLED | Tfc::DEPTH_STENCIL_ATTACHMENT,
|
||||
Tf::Depth24PlusStencil8 => Tfc::SAMPLED | Tfc::DEPTH_STENCIL_ATTACHMENT,
|
||||
Tf::Bc1RgbaUnorm
|
||||
| Tf::Bc1RgbaUnormSrgb
|
||||
| Tf::Bc2RgbaUnorm
|
||||
| Tf::Bc2RgbaUnormSrgb
|
||||
| Tf::Bc3RgbaUnorm
|
||||
| Tf::Bc3RgbaUnormSrgb
|
||||
| Tf::Bc4RUnorm
|
||||
| Tf::Bc4RSnorm
|
||||
| Tf::Bc5RgUnorm
|
||||
| Tf::Bc5RgSnorm
|
||||
| Tf::Bc6hRgbSfloat
|
||||
| Tf::Bc6hRgbUfloat
|
||||
| Tf::Bc7RgbaUnorm
|
||||
| Tf::Bc7RgbaUnormSrgb
|
||||
| Tf::Etc2RgbUnorm
|
||||
| Tf::Etc2RgbUnormSrgb
|
||||
| Tf::Etc2RgbA1Unorm
|
||||
| Tf::Etc2RgbA1UnormSrgb
|
||||
| Tf::EacRUnorm
|
||||
| Tf::EacRSnorm
|
||||
| Tf::EacRgUnorm
|
||||
| Tf::EacRgSnorm
|
||||
| Tf::Astc4x4RgbaUnorm
|
||||
| Tf::Astc4x4RgbaUnormSrgb
|
||||
| Tf::Astc5x4RgbaUnorm
|
||||
| Tf::Astc5x4RgbaUnormSrgb
|
||||
| Tf::Astc5x5RgbaUnorm
|
||||
| Tf::Astc5x5RgbaUnormSrgb
|
||||
| Tf::Astc6x5RgbaUnorm
|
||||
| Tf::Astc6x5RgbaUnormSrgb
|
||||
| Tf::Astc6x6RgbaUnorm
|
||||
| Tf::Astc6x6RgbaUnormSrgb
|
||||
| Tf::Astc8x5RgbaUnorm
|
||||
| Tf::Astc8x5RgbaUnormSrgb
|
||||
| Tf::Astc8x6RgbaUnorm
|
||||
| Tf::Astc8x6RgbaUnormSrgb
|
||||
| Tf::Astc10x5RgbaUnorm
|
||||
| Tf::Astc10x5RgbaUnormSrgb
|
||||
| Tf::Astc10x6RgbaUnorm
|
||||
| Tf::Astc10x6RgbaUnormSrgb
|
||||
| Tf::Astc8x8RgbaUnorm
|
||||
| Tf::Astc8x8RgbaUnormSrgb
|
||||
| Tf::Astc10x8RgbaUnorm
|
||||
| Tf::Astc10x8RgbaUnormSrgb
|
||||
| Tf::Astc10x10RgbaUnorm
|
||||
| Tf::Astc10x10RgbaUnormSrgb
|
||||
| Tf::Astc12x10RgbaUnorm
|
||||
| Tf::Astc12x10RgbaUnormSrgb
|
||||
| Tf::Astc12x12RgbaUnorm
|
||||
| Tf::Astc12x12RgbaUnormSrgb => Tfc::SAMPLED | Tfc::SAMPLED_LINEAR,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn surface_capabilities(
|
||||
&self,
|
||||
surface: &super::Surface,
|
||||
) -> Option<crate::SurfaceCapabilities> {
|
||||
if surface.presentable {
|
||||
Some(crate::SurfaceCapabilities {
|
||||
formats: vec![
|
||||
wgt::TextureFormat::Rgba8UnormSrgb,
|
||||
wgt::TextureFormat::Bgra8UnormSrgb,
|
||||
],
|
||||
present_modes: vec![wgt::PresentMode::Fifo], //TODO
|
||||
composite_alpha_modes: vec![crate::CompositeAlphaMode::Opaque], //TODO
|
||||
swap_chain_sizes: 2..=2,
|
||||
current_extent: None,
|
||||
extents: wgt::Extent3d {
|
||||
width: 4,
|
||||
height: 4,
|
||||
depth_or_array_layers: 1,
|
||||
}..=wgt::Extent3d {
|
||||
width: 4096,
|
||||
height: 4096,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
usage: crate::TextureUse::COLOR_TARGET,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::Adapter;
|
||||
|
||||
#[test]
|
||||
fn test_version_parse() {
|
||||
let error = Err(crate::InstanceError);
|
||||
assert_eq!(Adapter::parse_version("1"), error);
|
||||
assert_eq!(Adapter::parse_version("1."), error);
|
||||
assert_eq!(Adapter::parse_version("1 h3l1o. W0rld"), error);
|
||||
assert_eq!(Adapter::parse_version("1. h3l1o. W0rld"), error);
|
||||
assert_eq!(Adapter::parse_version("1.2.3"), error);
|
||||
assert_eq!(Adapter::parse_version("OpenGL ES 3.1"), Ok((3, 1)));
|
||||
assert_eq!(
|
||||
Adapter::parse_version("OpenGL ES 2.0 Google Nexus"),
|
||||
Ok((2, 0))
|
||||
);
|
||||
assert_eq!(Adapter::parse_version("GLSL ES 1.1"), Ok((1, 1)));
|
||||
assert_eq!(Adapter::parse_version("OpenGL ES GLSL ES 3.20"), Ok((3, 2)));
|
||||
assert_eq!(
|
||||
// WebGL 2.0 should parse as OpenGL ES 3.0
|
||||
Adapter::parse_version("WebGL 2.0 (OpenGL ES 3.0 Chromium)"),
|
||||
Ok((3, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
Adapter::parse_version("WebGL GLSL ES 3.00 (OpenGL ES GLSL ES 3.0 Chromium)"),
|
||||
Ok((3, 0))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,907 @@
|
||||
use super::{conv, Command as C};
|
||||
use arrayvec::ArrayVec;
|
||||
use std::{mem, ops::Range};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct TextureSlotDesc {
|
||||
tex_target: super::BindTarget,
|
||||
sampler_index: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
topology: u32,
|
||||
primitive: super::PrimitiveState,
|
||||
index_format: wgt::IndexFormat,
|
||||
index_offset: wgt::BufferAddress,
|
||||
vertex_buffers: [(super::VertexBufferDesc, super::BufferBinding); crate::MAX_VERTEX_BUFFERS],
|
||||
vertex_attributes: ArrayVec<[super::AttributeDesc; super::MAX_VERTEX_ATTRIBUTES]>,
|
||||
color_targets: ArrayVec<[super::ColorTargetDesc; crate::MAX_COLOR_TARGETS]>,
|
||||
stencil: super::StencilState,
|
||||
depth_bias: wgt::DepthBiasState,
|
||||
samplers: [Option<glow::Sampler>; super::MAX_SAMPLERS],
|
||||
texture_slots: [TextureSlotDesc; super::MAX_TEXTURE_SLOTS],
|
||||
render_size: wgt::Extent3d,
|
||||
resolve_attachments: ArrayVec<[(u32, super::TextureView); crate::MAX_COLOR_TARGETS]>,
|
||||
invalidate_attachments: ArrayVec<[u32; crate::MAX_COLOR_TARGETS + 2]>,
|
||||
has_pass_label: bool,
|
||||
instance_vbuf_mask: usize,
|
||||
dirty_vbuf_mask: usize,
|
||||
}
|
||||
|
||||
impl super::CommandBuffer {
|
||||
fn clear(&mut self) {
|
||||
self.label = None;
|
||||
self.commands.clear();
|
||||
self.data_bytes.clear();
|
||||
self.data_words.clear();
|
||||
}
|
||||
|
||||
fn add_marker(&mut self, marker: &str) -> Range<u32> {
|
||||
let start = self.data_bytes.len() as u32;
|
||||
self.data_bytes.extend(marker.as_bytes());
|
||||
start..self.data_bytes.len() as u32
|
||||
}
|
||||
}
|
||||
|
||||
impl super::CommandEncoder {
|
||||
fn rebind_stencil_func(&mut self) {
|
||||
fn make(s: &super::StencilSide, face: u32) -> C {
|
||||
C::SetStencilFunc {
|
||||
face,
|
||||
function: s.function,
|
||||
reference: s.reference,
|
||||
read_mask: s.mask_read,
|
||||
}
|
||||
}
|
||||
|
||||
let s = &self.state.stencil;
|
||||
if s.front.function == s.back.function
|
||||
&& s.front.mask_read == s.back.mask_read
|
||||
&& s.front.reference == s.back.reference
|
||||
{
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(make(&s.front, glow::FRONT_AND_BACK));
|
||||
} else {
|
||||
self.cmd_buffer.commands.push(make(&s.front, glow::FRONT));
|
||||
self.cmd_buffer.commands.push(make(&s.back, glow::BACK));
|
||||
}
|
||||
}
|
||||
|
||||
fn rebind_vertex_data(&mut self, first_instance: u32) {
|
||||
if self
|
||||
.private_caps
|
||||
.contains(super::PrivateCapability::VERTEX_BUFFER_LAYOUT)
|
||||
{
|
||||
for (index, &(ref vb_desc, ref vb)) in self.state.vertex_buffers.iter().enumerate() {
|
||||
if self.state.dirty_vbuf_mask & (1 << index) == 0 {
|
||||
continue;
|
||||
}
|
||||
let instance_offset = match vb_desc.step {
|
||||
wgt::InputStepMode::Vertex => 0,
|
||||
wgt::InputStepMode::Instance => first_instance * vb_desc.stride,
|
||||
};
|
||||
self.cmd_buffer.commands.push(C::SetVertexBuffer {
|
||||
index: index as u32,
|
||||
buffer: super::BufferBinding {
|
||||
raw: vb.raw,
|
||||
offset: vb.offset + instance_offset as wgt::BufferAddress,
|
||||
},
|
||||
buffer_desc: vb_desc.clone(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
for attribute in self.state.vertex_attributes.iter() {
|
||||
if self.state.dirty_vbuf_mask & (1 << attribute.buffer_index) == 0 {
|
||||
continue;
|
||||
}
|
||||
let (buffer_desc, buffer) =
|
||||
self.state.vertex_buffers[attribute.buffer_index as usize].clone();
|
||||
|
||||
let mut attribute_desc = attribute.clone();
|
||||
attribute_desc.offset += buffer.offset as u32;
|
||||
if buffer_desc.step == wgt::InputStepMode::Instance {
|
||||
attribute_desc.offset += buffer_desc.stride * first_instance;
|
||||
}
|
||||
|
||||
self.cmd_buffer.commands.push(C::SetVertexAttribute {
|
||||
buffer: Some(buffer.raw),
|
||||
buffer_desc,
|
||||
attribute_desc,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rebind_sampler_states(&mut self, dirty_textures: u32, dirty_samplers: u32) {
|
||||
for (texture_index, slot) in self.state.texture_slots.iter().enumerate() {
|
||||
if let Some(sampler_index) = slot.sampler_index {
|
||||
if dirty_textures & (1 << texture_index) != 0
|
||||
|| dirty_samplers & (1 << sampler_index) != 0
|
||||
{
|
||||
if let Some(sampler) = self.state.samplers[sampler_index as usize] {
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::BindSampler(texture_index as u32, sampler));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_draw(&mut self, first_instance: u32) {
|
||||
if first_instance != 0 {
|
||||
self.state.dirty_vbuf_mask = self.state.instance_vbuf_mask;
|
||||
}
|
||||
if self.state.dirty_vbuf_mask != 0 {
|
||||
self.rebind_vertex_data(first_instance);
|
||||
if first_instance == 0 {
|
||||
self.state.dirty_vbuf_mask = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_pipeline_inner(&mut self, inner: &super::PipelineInner) {
|
||||
self.cmd_buffer.commands.push(C::SetProgram(inner.program));
|
||||
|
||||
//TODO: push constants
|
||||
let _ = &inner.uniforms;
|
||||
|
||||
// rebind textures, if needed
|
||||
let mut dirty_textures = 0u32;
|
||||
for (texture_index, (slot, &sampler_index)) in self
|
||||
.state
|
||||
.texture_slots
|
||||
.iter_mut()
|
||||
.zip(inner.sampler_map.iter())
|
||||
.enumerate()
|
||||
{
|
||||
if slot.sampler_index != sampler_index {
|
||||
slot.sampler_index = sampler_index;
|
||||
dirty_textures |= 1 << texture_index;
|
||||
}
|
||||
}
|
||||
if dirty_textures != 0 {
|
||||
self.rebind_sampler_states(dirty_textures, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::CommandEncoder<super::Api> for super::CommandEncoder {
|
||||
unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> {
|
||||
self.state = State::default();
|
||||
self.cmd_buffer.label = label.map(str::to_string);
|
||||
Ok(())
|
||||
}
|
||||
unsafe fn discard_encoding(&mut self) {
|
||||
self.cmd_buffer.clear();
|
||||
}
|
||||
unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> {
|
||||
Ok(mem::take(&mut self.cmd_buffer))
|
||||
}
|
||||
unsafe fn reset_all<I>(&mut self, _command_buffers: I) {
|
||||
//TODO: could re-use the allocations in all these command buffers
|
||||
}
|
||||
|
||||
unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
|
||||
where
|
||||
T: Iterator<Item = crate::BufferBarrier<'a, super::Api>>,
|
||||
{
|
||||
if !self
|
||||
.private_caps
|
||||
.contains(super::PrivateCapability::MEMORY_BARRIERS)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for bar in barriers {
|
||||
// GLES only synchronizes storage -> anything explicitly
|
||||
if !bar.usage.start.contains(crate::BufferUse::STORAGE_STORE) {
|
||||
continue;
|
||||
}
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::BufferBarrier(bar.buffer.raw, bar.usage.end));
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn transition_textures<'a, T>(&mut self, barriers: T)
|
||||
where
|
||||
T: Iterator<Item = crate::TextureBarrier<'a, super::Api>>,
|
||||
{
|
||||
if !self
|
||||
.private_caps
|
||||
.contains(super::PrivateCapability::MEMORY_BARRIERS)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let mut combined_usage = crate::TextureUse::empty();
|
||||
for bar in barriers {
|
||||
// GLES only synchronizes storage -> anything explicitly
|
||||
if !bar.usage.start.contains(crate::TextureUse::STORAGE_STORE) {
|
||||
continue;
|
||||
}
|
||||
// unlike buffers, there is no need for a concrete texture
|
||||
// object to be bound anywhere for a barrier
|
||||
combined_usage |= bar.usage.end;
|
||||
}
|
||||
|
||||
if !combined_usage.is_empty() {
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::TextureBarrier(combined_usage));
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn fill_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange, value: u8) {
|
||||
self.cmd_buffer.commands.push(C::FillBuffer {
|
||||
dst: buffer.raw,
|
||||
dst_target: buffer.target,
|
||||
range,
|
||||
value,
|
||||
});
|
||||
}
|
||||
|
||||
unsafe fn copy_buffer_to_buffer<T>(
|
||||
&mut self,
|
||||
src: &super::Buffer,
|
||||
dst: &super::Buffer,
|
||||
regions: T,
|
||||
) where
|
||||
T: Iterator<Item = crate::BufferCopy>,
|
||||
{
|
||||
//TODO: preserve `src.target` and `dst.target`
|
||||
// at least for the buffers that require it.
|
||||
for copy in regions {
|
||||
self.cmd_buffer.commands.push(C::CopyBufferToBuffer {
|
||||
src: src.raw,
|
||||
src_target: glow::COPY_READ_BUFFER,
|
||||
dst: dst.raw,
|
||||
dst_target: glow::COPY_WRITE_BUFFER,
|
||||
copy,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_texture_to_texture<T>(
|
||||
&mut self,
|
||||
src: &super::Texture,
|
||||
_src_usage: crate::TextureUse,
|
||||
dst: &super::Texture,
|
||||
regions: T,
|
||||
) where
|
||||
T: Iterator<Item = crate::TextureCopy>,
|
||||
{
|
||||
let (src_raw, src_target) = src.inner.as_native();
|
||||
let (dst_raw, dst_target) = dst.inner.as_native();
|
||||
for copy in regions {
|
||||
self.cmd_buffer.commands.push(C::CopyTextureToTexture {
|
||||
src: src_raw,
|
||||
src_target,
|
||||
dst: dst_raw,
|
||||
dst_target,
|
||||
copy,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_buffer_to_texture<T>(
|
||||
&mut self,
|
||||
src: &super::Buffer,
|
||||
dst: &super::Texture,
|
||||
regions: T,
|
||||
) where
|
||||
T: Iterator<Item = crate::BufferTextureCopy>,
|
||||
{
|
||||
let (dst_raw, dst_target) = dst.inner.as_native();
|
||||
for copy in regions {
|
||||
self.cmd_buffer.commands.push(C::CopyBufferToTexture {
|
||||
src: src.raw,
|
||||
src_target: src.target,
|
||||
dst: dst_raw,
|
||||
dst_target,
|
||||
dst_format: dst.format,
|
||||
copy,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_texture_to_buffer<T>(
|
||||
&mut self,
|
||||
src: &super::Texture,
|
||||
_src_usage: crate::TextureUse,
|
||||
dst: &super::Buffer,
|
||||
regions: T,
|
||||
) where
|
||||
T: Iterator<Item = crate::BufferTextureCopy>,
|
||||
{
|
||||
let (src_raw, src_target) = src.inner.as_native();
|
||||
for copy in regions {
|
||||
self.cmd_buffer.commands.push(C::CopyTextureToBuffer {
|
||||
src: src_raw,
|
||||
src_target,
|
||||
src_format: src.format,
|
||||
dst: dst.raw,
|
||||
dst_target: dst.target,
|
||||
copy,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) {
|
||||
let query = set.queries[index as usize];
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::BeginQuery(query, set.target));
|
||||
}
|
||||
unsafe fn end_query(&mut self, set: &super::QuerySet, _index: u32) {
|
||||
self.cmd_buffer.commands.push(C::EndQuery(set.target));
|
||||
}
|
||||
unsafe fn write_timestamp(&mut self, _set: &super::QuerySet, _index: u32) {
|
||||
unimplemented!()
|
||||
}
|
||||
unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range<u32>) {
|
||||
//TODO: what do we do here?
|
||||
}
|
||||
unsafe fn copy_query_results(
|
||||
&mut self,
|
||||
set: &super::QuerySet,
|
||||
range: Range<u32>,
|
||||
buffer: &super::Buffer,
|
||||
offset: wgt::BufferAddress,
|
||||
_stride: wgt::BufferSize,
|
||||
) {
|
||||
let start = self.cmd_buffer.data_words.len();
|
||||
self.cmd_buffer
|
||||
.data_words
|
||||
.extend_from_slice(&set.queries[range.start as usize..range.end as usize]);
|
||||
let query_range = start as u32..self.cmd_buffer.data_words.len() as u32;
|
||||
self.cmd_buffer.commands.push(C::CopyQueryResults {
|
||||
query_range,
|
||||
dst: buffer.raw,
|
||||
dst_target: buffer.target,
|
||||
dst_offset: offset,
|
||||
});
|
||||
}
|
||||
|
||||
// render
|
||||
|
||||
unsafe fn begin_render_pass(&mut self, desc: &crate::RenderPassDescriptor<super::Api>) {
|
||||
self.state.render_size = desc.extent;
|
||||
self.state.resolve_attachments.clear();
|
||||
self.state.invalidate_attachments.clear();
|
||||
if let Some(label) = desc.label {
|
||||
let range = self.cmd_buffer.add_marker(label);
|
||||
self.cmd_buffer.commands.push(C::PushDebugGroup(range));
|
||||
self.state.has_pass_label = true;
|
||||
}
|
||||
|
||||
// set the framebuffer
|
||||
self.cmd_buffer.commands.push(C::ResetFramebuffer);
|
||||
for (i, cat) in desc.color_attachments.iter().enumerate() {
|
||||
let attachment = glow::COLOR_ATTACHMENT0 + i as u32;
|
||||
self.cmd_buffer.commands.push(C::BindAttachment {
|
||||
attachment,
|
||||
view: cat.target.view.clone(),
|
||||
});
|
||||
if let Some(ref rat) = cat.resolve_target {
|
||||
self.state
|
||||
.resolve_attachments
|
||||
.push((attachment, rat.view.clone()));
|
||||
}
|
||||
if !cat.ops.contains(crate::AttachmentOp::STORE) {
|
||||
self.state.invalidate_attachments.push(attachment);
|
||||
}
|
||||
}
|
||||
if let Some(ref dsat) = desc.depth_stencil_attachment {
|
||||
let aspects = dsat.target.view.aspects;
|
||||
let attachment = match aspects {
|
||||
crate::FormatAspect::DEPTH => glow::DEPTH_ATTACHMENT,
|
||||
crate::FormatAspect::STENCIL => glow::STENCIL_ATTACHMENT,
|
||||
_ => glow::DEPTH_STENCIL_ATTACHMENT,
|
||||
};
|
||||
self.cmd_buffer.commands.push(C::BindAttachment {
|
||||
attachment,
|
||||
view: dsat.target.view.clone(),
|
||||
});
|
||||
if aspects.contains(crate::FormatAspect::DEPTH)
|
||||
&& !dsat.depth_ops.contains(crate::AttachmentOp::STORE)
|
||||
{
|
||||
self.state
|
||||
.invalidate_attachments
|
||||
.push(glow::DEPTH_ATTACHMENT);
|
||||
}
|
||||
if aspects.contains(crate::FormatAspect::STENCIL)
|
||||
&& !dsat.stencil_ops.contains(crate::AttachmentOp::STORE)
|
||||
{
|
||||
self.state
|
||||
.invalidate_attachments
|
||||
.push(glow::STENCIL_ATTACHMENT);
|
||||
}
|
||||
}
|
||||
|
||||
// set the draw buffers and states
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::SetDrawColorBuffers(desc.color_attachments.len() as u8));
|
||||
let rect = crate::Rect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
w: desc.extent.width as i32,
|
||||
h: desc.extent.height as i32,
|
||||
};
|
||||
self.cmd_buffer.commands.push(C::SetScissor(rect.clone()));
|
||||
self.cmd_buffer.commands.push(C::SetViewport {
|
||||
rect,
|
||||
depth: 0.0..1.0,
|
||||
});
|
||||
|
||||
// issue the clears
|
||||
for (i, cat) in desc.color_attachments.iter().enumerate() {
|
||||
if !cat.ops.contains(crate::AttachmentOp::LOAD) {
|
||||
let c = &cat.clear_value;
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(match cat.target.view.sample_type {
|
||||
wgt::TextureSampleType::Float { .. } => C::ClearColorF(
|
||||
i as u32,
|
||||
[c.r as f32, c.g as f32, c.b as f32, c.a as f32],
|
||||
),
|
||||
wgt::TextureSampleType::Depth => unimplemented!(),
|
||||
wgt::TextureSampleType::Uint => C::ClearColorU(
|
||||
i as u32,
|
||||
[c.r as u32, c.g as u32, c.b as u32, c.a as u32],
|
||||
),
|
||||
wgt::TextureSampleType::Sint => C::ClearColorI(
|
||||
i as u32,
|
||||
[c.r as i32, c.g as i32, c.b as i32, c.a as i32],
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(ref dsat) = desc.depth_stencil_attachment {
|
||||
if !dsat.depth_ops.contains(crate::AttachmentOp::LOAD) {
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::ClearDepth(dsat.clear_value.0));
|
||||
}
|
||||
if !dsat.stencil_ops.contains(crate::AttachmentOp::LOAD) {
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::ClearStencil(dsat.clear_value.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe fn end_render_pass(&mut self) {
|
||||
for (attachment, dst) in self.state.resolve_attachments.drain(..) {
|
||||
self.cmd_buffer.commands.push(C::ResolveAttachment {
|
||||
attachment,
|
||||
dst,
|
||||
size: self.state.render_size,
|
||||
});
|
||||
}
|
||||
if !self.state.invalidate_attachments.is_empty() {
|
||||
self.cmd_buffer.commands.push(C::InvalidateAttachments(
|
||||
self.state.invalidate_attachments.clone(),
|
||||
));
|
||||
self.state.invalidate_attachments.clear();
|
||||
}
|
||||
if self.state.has_pass_label {
|
||||
self.cmd_buffer.commands.push(C::PopDebugGroup);
|
||||
self.state.has_pass_label = false;
|
||||
}
|
||||
self.state.instance_vbuf_mask = 0;
|
||||
self.state.dirty_vbuf_mask = 0;
|
||||
self.state.color_targets.clear();
|
||||
self.state.vertex_attributes.clear();
|
||||
self.state.primitive = super::PrimitiveState::default();
|
||||
}
|
||||
|
||||
unsafe fn set_bind_group(
|
||||
&mut self,
|
||||
layout: &super::PipelineLayout,
|
||||
index: u32,
|
||||
group: &super::BindGroup,
|
||||
dynamic_offsets: &[wgt::DynamicOffset],
|
||||
) {
|
||||
let mut do_index = 0;
|
||||
let mut dirty_textures = 0u32;
|
||||
let mut dirty_samplers = 0u32;
|
||||
let group_info = &layout.group_infos[index as usize];
|
||||
|
||||
for (binding_layout, raw_binding) in group_info.entries.iter().zip(group.contents.iter()) {
|
||||
let slot = group_info.binding_to_slot[binding_layout.binding as usize] as u32;
|
||||
match *raw_binding {
|
||||
super::RawBinding::Buffer {
|
||||
raw,
|
||||
offset: base_offset,
|
||||
size,
|
||||
} => {
|
||||
let mut offset = base_offset;
|
||||
let target = match binding_layout.ty {
|
||||
wgt::BindingType::Buffer {
|
||||
ty,
|
||||
has_dynamic_offset,
|
||||
min_binding_size: _,
|
||||
} => {
|
||||
if has_dynamic_offset {
|
||||
offset += dynamic_offsets[do_index] as i32;
|
||||
do_index += 1;
|
||||
}
|
||||
match ty {
|
||||
wgt::BufferBindingType::Uniform => glow::UNIFORM_BUFFER,
|
||||
wgt::BufferBindingType::Storage { .. } => {
|
||||
glow::SHADER_STORAGE_BUFFER
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
self.cmd_buffer.commands.push(C::BindBuffer {
|
||||
target,
|
||||
slot,
|
||||
buffer: raw,
|
||||
offset,
|
||||
size,
|
||||
});
|
||||
}
|
||||
super::RawBinding::Sampler(sampler) => {
|
||||
dirty_samplers |= 1 << slot;
|
||||
self.state.samplers[slot as usize] = Some(sampler);
|
||||
}
|
||||
super::RawBinding::Texture { raw, target } => {
|
||||
dirty_textures |= 1 << slot;
|
||||
self.state.texture_slots[slot as usize].tex_target = target;
|
||||
self.cmd_buffer.commands.push(C::BindTexture {
|
||||
slot,
|
||||
texture: raw,
|
||||
target,
|
||||
});
|
||||
}
|
||||
super::RawBinding::Image(ref binding) => {
|
||||
self.cmd_buffer.commands.push(C::BindImage {
|
||||
slot,
|
||||
binding: binding.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.rebind_sampler_states(dirty_textures, dirty_samplers);
|
||||
}
|
||||
|
||||
unsafe fn set_push_constants(
|
||||
&mut self,
|
||||
_layout: &super::PipelineLayout,
|
||||
_stages: wgt::ShaderStage,
|
||||
_offset: u32,
|
||||
_data: &[u32],
|
||||
) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
unsafe fn insert_debug_marker(&mut self, label: &str) {
|
||||
let range = self.cmd_buffer.add_marker(label);
|
||||
self.cmd_buffer.commands.push(C::InsertDebugMarker(range));
|
||||
}
|
||||
unsafe fn begin_debug_marker(&mut self, group_label: &str) {
|
||||
let range = self.cmd_buffer.add_marker(group_label);
|
||||
self.cmd_buffer.commands.push(C::PushDebugGroup(range));
|
||||
}
|
||||
unsafe fn end_debug_marker(&mut self) {
|
||||
self.cmd_buffer.commands.push(C::PopDebugGroup);
|
||||
}
|
||||
|
||||
unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) {
|
||||
self.state.topology = conv::map_primitive_topology(pipeline.primitive.topology);
|
||||
|
||||
for index in self.state.vertex_attributes.len()..pipeline.vertex_attributes.len() {
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::UnsetVertexAttribute(index as u32));
|
||||
}
|
||||
|
||||
if self
|
||||
.private_caps
|
||||
.contains(super::PrivateCapability::VERTEX_BUFFER_LAYOUT)
|
||||
{
|
||||
for vat in pipeline.vertex_attributes.iter() {
|
||||
let vb = &pipeline.vertex_buffers[vat.buffer_index as usize];
|
||||
// set the layout
|
||||
self.cmd_buffer.commands.push(C::SetVertexAttribute {
|
||||
buffer: None,
|
||||
buffer_desc: vb.clone(),
|
||||
attribute_desc: vat.clone(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
self.state.dirty_vbuf_mask = 0;
|
||||
// copy vertex attributes
|
||||
for vat in pipeline.vertex_attributes.iter() {
|
||||
//Note: we can invalidate more carefully here.
|
||||
self.state.dirty_vbuf_mask |= 1 << vat.buffer_index;
|
||||
self.state.vertex_attributes.push(vat.clone());
|
||||
}
|
||||
}
|
||||
|
||||
self.state.instance_vbuf_mask = 0;
|
||||
// copy vertex state
|
||||
for (index, (&mut (ref mut state_desc, _), pipe_desc)) in self
|
||||
.state
|
||||
.vertex_buffers
|
||||
.iter_mut()
|
||||
.zip(pipeline.vertex_buffers.iter())
|
||||
.enumerate()
|
||||
{
|
||||
if pipe_desc.step == wgt::InputStepMode::Instance {
|
||||
self.state.instance_vbuf_mask |= 1 << index;
|
||||
}
|
||||
if state_desc != pipe_desc {
|
||||
self.state.dirty_vbuf_mask |= 1 << index;
|
||||
*state_desc = pipe_desc.clone();
|
||||
}
|
||||
}
|
||||
|
||||
self.set_pipeline_inner(&pipeline.inner);
|
||||
|
||||
// set primitive state
|
||||
let prim_state = conv::map_primitive_state(&pipeline.primitive);
|
||||
if prim_state != self.state.primitive {
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::SetPrimitive(prim_state.clone()));
|
||||
self.state.primitive = prim_state;
|
||||
}
|
||||
|
||||
// set depth/stencil states
|
||||
let mut aspects = crate::FormatAspect::empty();
|
||||
if pipeline.depth_bias != self.state.depth_bias {
|
||||
self.state.depth_bias = pipeline.depth_bias;
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::SetDepthBias(pipeline.depth_bias));
|
||||
}
|
||||
if let Some(ref depth) = pipeline.depth {
|
||||
aspects |= crate::FormatAspect::DEPTH;
|
||||
self.cmd_buffer.commands.push(C::SetDepth(depth.clone()));
|
||||
}
|
||||
if let Some(ref stencil) = pipeline.stencil {
|
||||
aspects |= crate::FormatAspect::STENCIL;
|
||||
self.state.stencil = stencil.clone();
|
||||
self.rebind_stencil_func();
|
||||
if stencil.front.ops == stencil.back.ops
|
||||
&& stencil.front.mask_write == stencil.back.mask_write
|
||||
{
|
||||
self.cmd_buffer.commands.push(C::SetStencilOps {
|
||||
face: glow::FRONT_AND_BACK,
|
||||
write_mask: stencil.front.mask_write,
|
||||
ops: stencil.front.ops.clone(),
|
||||
});
|
||||
} else {
|
||||
self.cmd_buffer.commands.push(C::SetStencilOps {
|
||||
face: glow::FRONT,
|
||||
write_mask: stencil.front.mask_write,
|
||||
ops: stencil.front.ops.clone(),
|
||||
});
|
||||
self.cmd_buffer.commands.push(C::SetStencilOps {
|
||||
face: glow::BACK,
|
||||
write_mask: stencil.back.mask_write,
|
||||
ops: stencil.back.ops.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::ConfigureDepthStencil(aspects));
|
||||
|
||||
// set blend states
|
||||
if self.state.color_targets[..] != pipeline.color_targets[..] {
|
||||
if pipeline
|
||||
.color_targets
|
||||
.iter()
|
||||
.skip(1)
|
||||
.any(|ct| *ct != pipeline.color_targets[0])
|
||||
{
|
||||
for (index, ct) in pipeline.color_targets.iter().enumerate() {
|
||||
self.cmd_buffer.commands.push(C::SetColorTarget {
|
||||
draw_buffer_index: Some(index as u32),
|
||||
desc: ct.clone(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
self.cmd_buffer.commands.push(C::SetColorTarget {
|
||||
draw_buffer_index: None,
|
||||
desc: pipeline.color_targets.first().cloned().unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
}
|
||||
self.state.color_targets.clear();
|
||||
for ct in pipeline.color_targets.iter() {
|
||||
self.state.color_targets.push(ct.clone());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_index_buffer<'a>(
|
||||
&mut self,
|
||||
binding: crate::BufferBinding<'a, super::Api>,
|
||||
format: wgt::IndexFormat,
|
||||
) {
|
||||
self.state.index_offset = binding.offset;
|
||||
self.state.index_format = format;
|
||||
self.cmd_buffer
|
||||
.commands
|
||||
.push(C::SetIndexBuffer(binding.buffer.raw));
|
||||
}
|
||||
unsafe fn set_vertex_buffer<'a>(
|
||||
&mut self,
|
||||
index: u32,
|
||||
binding: crate::BufferBinding<'a, super::Api>,
|
||||
) {
|
||||
self.state.dirty_vbuf_mask |= 1 << index;
|
||||
let (_, ref mut vb) = self.state.vertex_buffers[index as usize];
|
||||
vb.raw = binding.buffer.raw;
|
||||
vb.offset = binding.offset;
|
||||
}
|
||||
unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth: Range<f32>) {
|
||||
self.cmd_buffer.commands.push(C::SetViewport {
|
||||
rect: crate::Rect {
|
||||
x: rect.x as i32,
|
||||
y: rect.y as i32,
|
||||
w: rect.w as i32,
|
||||
h: rect.h as i32,
|
||||
},
|
||||
depth,
|
||||
});
|
||||
}
|
||||
unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) {
|
||||
self.cmd_buffer.commands.push(C::SetScissor(crate::Rect {
|
||||
x: rect.x as i32,
|
||||
y: rect.y as i32,
|
||||
w: rect.w as i32,
|
||||
h: rect.h as i32,
|
||||
}));
|
||||
}
|
||||
unsafe fn set_stencil_reference(&mut self, value: u32) {
|
||||
self.state.stencil.front.reference = value;
|
||||
self.state.stencil.back.reference = value;
|
||||
self.rebind_stencil_func();
|
||||
}
|
||||
unsafe fn set_blend_constants(&mut self, color: &wgt::Color) {
|
||||
let color = [
|
||||
color.r as f32,
|
||||
color.g as f32,
|
||||
color.b as f32,
|
||||
color.a as f32,
|
||||
];
|
||||
self.cmd_buffer.commands.push(C::SetBlendConstant(color));
|
||||
}
|
||||
|
||||
unsafe fn draw(
|
||||
&mut self,
|
||||
start_vertex: u32,
|
||||
vertex_count: u32,
|
||||
start_instance: u32,
|
||||
instance_count: u32,
|
||||
) {
|
||||
self.prepare_draw(start_instance);
|
||||
self.cmd_buffer.commands.push(C::Draw {
|
||||
topology: self.state.topology,
|
||||
start_vertex,
|
||||
vertex_count,
|
||||
instance_count,
|
||||
});
|
||||
}
|
||||
unsafe fn draw_indexed(
|
||||
&mut self,
|
||||
start_index: u32,
|
||||
index_count: u32,
|
||||
base_vertex: i32,
|
||||
start_instance: u32,
|
||||
instance_count: u32,
|
||||
) {
|
||||
self.prepare_draw(start_instance);
|
||||
let (index_size, index_type) = match self.state.index_format {
|
||||
wgt::IndexFormat::Uint16 => (2, glow::UNSIGNED_SHORT),
|
||||
wgt::IndexFormat::Uint32 => (4, glow::UNSIGNED_INT),
|
||||
};
|
||||
let index_offset = self.state.index_offset + index_size * start_index as wgt::BufferAddress;
|
||||
self.cmd_buffer.commands.push(C::DrawIndexed {
|
||||
topology: self.state.topology,
|
||||
index_type,
|
||||
index_offset,
|
||||
index_count,
|
||||
base_vertex,
|
||||
instance_count,
|
||||
});
|
||||
}
|
||||
unsafe fn draw_indirect(
|
||||
&mut self,
|
||||
buffer: &super::Buffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
self.prepare_draw(0);
|
||||
for draw in 0..draw_count as wgt::BufferAddress {
|
||||
let indirect_offset =
|
||||
offset + draw * mem::size_of::<wgt::DrawIndirectArgs>() as wgt::BufferAddress;
|
||||
self.cmd_buffer.commands.push(C::DrawIndirect {
|
||||
topology: self.state.topology,
|
||||
indirect_buf: buffer.raw,
|
||||
indirect_offset,
|
||||
});
|
||||
}
|
||||
}
|
||||
unsafe fn draw_indexed_indirect(
|
||||
&mut self,
|
||||
buffer: &super::Buffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
self.prepare_draw(0);
|
||||
let index_type = match self.state.index_format {
|
||||
wgt::IndexFormat::Uint16 => glow::UNSIGNED_SHORT,
|
||||
wgt::IndexFormat::Uint32 => glow::UNSIGNED_INT,
|
||||
};
|
||||
for draw in 0..draw_count as wgt::BufferAddress {
|
||||
let indirect_offset = offset
|
||||
+ draw * mem::size_of::<wgt::DrawIndexedIndirectArgs>() as wgt::BufferAddress;
|
||||
self.cmd_buffer.commands.push(C::DrawIndexedIndirect {
|
||||
topology: self.state.topology,
|
||||
index_type,
|
||||
indirect_buf: buffer.raw,
|
||||
indirect_offset,
|
||||
});
|
||||
}
|
||||
}
|
||||
unsafe fn draw_indirect_count(
|
||||
&mut self,
|
||||
_buffer: &super::Buffer,
|
||||
_offset: wgt::BufferAddress,
|
||||
_count_buffer: &super::Buffer,
|
||||
_count_offset: wgt::BufferAddress,
|
||||
_max_count: u32,
|
||||
) {
|
||||
unreachable!()
|
||||
}
|
||||
unsafe fn draw_indexed_indirect_count(
|
||||
&mut self,
|
||||
_buffer: &super::Buffer,
|
||||
_offset: wgt::BufferAddress,
|
||||
_count_buffer: &super::Buffer,
|
||||
_count_offset: wgt::BufferAddress,
|
||||
_max_count: u32,
|
||||
) {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
// compute
|
||||
|
||||
unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor) {
|
||||
if let Some(label) = desc.label {
|
||||
let range = self.cmd_buffer.add_marker(label);
|
||||
self.cmd_buffer.commands.push(C::PushDebugGroup(range));
|
||||
self.state.has_pass_label = true;
|
||||
}
|
||||
}
|
||||
unsafe fn end_compute_pass(&mut self) {
|
||||
if self.state.has_pass_label {
|
||||
self.cmd_buffer.commands.push(C::PopDebugGroup);
|
||||
self.state.has_pass_label = false;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) {
|
||||
self.set_pipeline_inner(&pipeline.inner);
|
||||
}
|
||||
|
||||
unsafe fn dispatch(&mut self, count: [u32; 3]) {
|
||||
self.cmd_buffer.commands.push(C::Dispatch(count));
|
||||
}
|
||||
unsafe fn dispatch_indirect(&mut self, buffer: &super::Buffer, offset: wgt::BufferAddress) {
|
||||
self.cmd_buffer.commands.push(C::DispatchIndirect {
|
||||
indirect_buf: buffer.raw,
|
||||
indirect_offset: offset,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
impl super::AdapterShared {
|
||||
pub(super) fn describe_texture_format(
|
||||
&self,
|
||||
texture_format: wgt::TextureFormat,
|
||||
) -> super::TextureFormatDesc {
|
||||
use wgt::TextureFormat as Tf;
|
||||
|
||||
let (internal, external, data_type) = match texture_format {
|
||||
Tf::R8Unorm => (glow::R8, glow::RED, glow::UNSIGNED_BYTE),
|
||||
Tf::R8Snorm => (glow::R8, 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::R16Float => (glow::R16F, glow::RED, glow::HALF_FLOAT),
|
||||
Tf::Rg8Unorm => (glow::RG8, glow::RG, glow::UNSIGNED_BYTE),
|
||||
Tf::Rg8Snorm => (glow::RG8, 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::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::RGBA, glow::UNSIGNED_BYTE), //TODO?
|
||||
Tf::Rgba8Snorm => (glow::RGBA8, glow::RGBA, glow::BYTE),
|
||||
Tf::Bgra8Unorm => (glow::RGBA8, glow::BGRA, glow::UNSIGNED_BYTE),
|
||||
Tf::Rgba8Uint => (glow::RGBA8UI, glow::RGBA_INTEGER, glow::UNSIGNED_BYTE),
|
||||
Tf::Rgba8Sint => (glow::RGBA8I, glow::RGBA_INTEGER, glow::BYTE),
|
||||
Tf::Rgb10a2Unorm => (
|
||||
glow::RGB10_A2,
|
||||
glow::RGBA,
|
||||
glow::UNSIGNED_INT_2_10_10_10_REV,
|
||||
),
|
||||
Tf::Rg11b10Float => (
|
||||
glow::R11F_G11F_B10F,
|
||||
glow::RGB,
|
||||
glow::UNSIGNED_INT_10F_11F_11F_REV,
|
||||
),
|
||||
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::Rgba16Float => (glow::RGBA16F, glow::RG, 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::Depth32Float => (glow::DEPTH_COMPONENT32F, glow::DEPTH_COMPONENT, glow::FLOAT),
|
||||
Tf::Depth24Plus => (
|
||||
glow::DEPTH_COMPONENT24,
|
||||
glow::DEPTH_COMPONENT,
|
||||
glow::UNSIGNED_NORMALIZED,
|
||||
),
|
||||
Tf::Depth24PlusStencil8 => (
|
||||
glow::DEPTH24_STENCIL8,
|
||||
glow::DEPTH_COMPONENT,
|
||||
glow::UNSIGNED_INT,
|
||||
),
|
||||
Tf::Bc1RgbaUnorm
|
||||
| Tf::Bc1RgbaUnormSrgb
|
||||
| Tf::Bc2RgbaUnorm
|
||||
| Tf::Bc2RgbaUnormSrgb
|
||||
| Tf::Bc3RgbaUnorm
|
||||
| Tf::Bc3RgbaUnormSrgb
|
||||
| Tf::Bc4RUnorm
|
||||
| Tf::Bc4RSnorm
|
||||
| Tf::Bc5RgUnorm
|
||||
| Tf::Bc5RgSnorm
|
||||
| Tf::Bc6hRgbSfloat
|
||||
| Tf::Bc6hRgbUfloat
|
||||
| Tf::Bc7RgbaUnorm
|
||||
| Tf::Bc7RgbaUnormSrgb => unimplemented!(),
|
||||
Tf::Etc2RgbUnorm => (glow::COMPRESSED_RGB8_ETC2, glow::RGB, 0),
|
||||
Tf::Etc2RgbUnormSrgb => (glow::COMPRESSED_SRGB8_ETC2, glow::RGB, 0),
|
||||
Tf::Etc2RgbA1Unorm => (
|
||||
glow::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
|
||||
glow::RGBA,
|
||||
0,
|
||||
),
|
||||
Tf::Etc2RgbA1UnormSrgb => (
|
||||
glow::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,
|
||||
glow::RGBA,
|
||||
0,
|
||||
),
|
||||
Tf::EacRUnorm => (glow::COMPRESSED_R11_EAC, glow::RED, 0),
|
||||
Tf::EacRSnorm => (glow::COMPRESSED_SIGNED_R11_EAC, glow::RED, 0),
|
||||
Tf::EacRgUnorm => (glow::COMPRESSED_RG11_EAC, glow::RG, 0),
|
||||
Tf::EacRgSnorm => (glow::COMPRESSED_SIGNED_RG11_EAC, glow::RG, 0),
|
||||
Tf::Astc4x4RgbaUnorm
|
||||
| Tf::Astc4x4RgbaUnormSrgb
|
||||
| Tf::Astc5x4RgbaUnorm
|
||||
| Tf::Astc5x4RgbaUnormSrgb
|
||||
| Tf::Astc5x5RgbaUnorm
|
||||
| Tf::Astc5x5RgbaUnormSrgb
|
||||
| Tf::Astc6x5RgbaUnorm
|
||||
| Tf::Astc6x5RgbaUnormSrgb
|
||||
| Tf::Astc6x6RgbaUnorm
|
||||
| Tf::Astc6x6RgbaUnormSrgb
|
||||
| Tf::Astc8x5RgbaUnorm
|
||||
| Tf::Astc8x5RgbaUnormSrgb
|
||||
| Tf::Astc8x6RgbaUnorm
|
||||
| Tf::Astc8x6RgbaUnormSrgb
|
||||
| Tf::Astc10x5RgbaUnorm
|
||||
| Tf::Astc10x5RgbaUnormSrgb
|
||||
| Tf::Astc10x6RgbaUnorm
|
||||
| Tf::Astc10x6RgbaUnormSrgb
|
||||
| Tf::Astc8x8RgbaUnorm
|
||||
| Tf::Astc8x8RgbaUnormSrgb
|
||||
| Tf::Astc10x8RgbaUnorm
|
||||
| Tf::Astc10x8RgbaUnormSrgb
|
||||
| Tf::Astc10x10RgbaUnorm
|
||||
| Tf::Astc10x10RgbaUnormSrgb
|
||||
| Tf::Astc12x10RgbaUnorm
|
||||
| Tf::Astc12x10RgbaUnormSrgb
|
||||
| Tf::Astc12x12RgbaUnorm
|
||||
| Tf::Astc12x12RgbaUnormSrgb => unimplemented!(),
|
||||
};
|
||||
|
||||
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::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::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::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::FilterMode,
|
||||
) -> (u32, u32) {
|
||||
use wgt::FilterMode as Fm;
|
||||
|
||||
let mag_filter = match mag {
|
||||
Fm::Nearest => glow::NEAREST,
|
||||
Fm::Linear => glow::LINEAR,
|
||||
};
|
||||
|
||||
let min_filter = match (min, mip) {
|
||||
(Fm::Nearest, Fm::Nearest) => glow::NEAREST_MIPMAP_NEAREST,
|
||||
(Fm::Nearest, Fm::Linear) => glow::NEAREST_MIPMAP_LINEAR,
|
||||
(Fm::Linear, Fm::Nearest) => glow::LINEAR_MIPMAP_NEAREST,
|
||||
(Fm::Linear, Fm::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 {
|
||||
//Note: state.polygon_mode is not supported, see `Features::NON_FILL_POLYGON_MODE`
|
||||
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,
|
||||
},
|
||||
clamp_depth: state.clamp_depth,
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,788 @@
|
||||
use glow::HasContext;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use std::{ffi::CStr, os::raw, ptr, sync::Arc};
|
||||
|
||||
const EGL_PLATFORM_WAYLAND_KHR: u32 = 0x31D8;
|
||||
const EGL_PLATFORM_X11_KHR: u32 = 0x31D5;
|
||||
|
||||
type XOpenDisplayFun =
|
||||
unsafe extern "system" fn(display_name: *const raw::c_char) -> *mut raw::c_void;
|
||||
|
||||
type WlDisplayConnectFun =
|
||||
unsafe extern "system" fn(display_name: *const raw::c_char) -> *mut raw::c_void;
|
||||
|
||||
type WlDisplayDisconnectFun = unsafe extern "system" fn(display: *const raw::c_void);
|
||||
|
||||
#[cfg(not(any(target_os = "android", target_os = "macos")))]
|
||||
type WlEglWindowCreateFun = unsafe extern "system" fn(
|
||||
surface: *const raw::c_void,
|
||||
width: raw::c_int,
|
||||
height: raw::c_int,
|
||||
) -> *mut raw::c_void;
|
||||
|
||||
type WlEglWindowResizeFun = unsafe extern "system" fn(
|
||||
window: *const raw::c_void,
|
||||
width: raw::c_int,
|
||||
height: raw::c_int,
|
||||
dx: raw::c_int,
|
||||
dy: raw::c_int,
|
||||
);
|
||||
|
||||
type WlEglWindowDestroyFun = unsafe extern "system" fn(window: *const raw::c_void);
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
extern "C" {
|
||||
pub fn ANativeWindow_setBuffersGeometry(
|
||||
window: *mut raw::c_void,
|
||||
width: i32,
|
||||
height: i32,
|
||||
format: i32,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
type EglLabel = *const raw::c_void;
|
||||
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
type EGLDEBUGPROCKHR = Option<
|
||||
unsafe extern "system" fn(
|
||||
error: egl::Enum,
|
||||
command: *const raw::c_char,
|
||||
message_type: u32,
|
||||
thread_label: EglLabel,
|
||||
object_label: EglLabel,
|
||||
message: *const raw::c_char,
|
||||
),
|
||||
>;
|
||||
|
||||
const EGL_DEBUG_MSG_CRITICAL_KHR: u32 = 0x33B9;
|
||||
const EGL_DEBUG_MSG_ERROR_KHR: u32 = 0x33BA;
|
||||
const EGL_DEBUG_MSG_WARN_KHR: u32 = 0x33BB;
|
||||
const EGL_DEBUG_MSG_INFO_KHR: u32 = 0x33BC;
|
||||
|
||||
type EglDebugMessageControlFun =
|
||||
unsafe extern "system" fn(proc: EGLDEBUGPROCKHR, attrib_list: *const egl::Attrib) -> raw::c_int;
|
||||
|
||||
unsafe extern "system" fn egl_debug_proc(
|
||||
error: egl::Enum,
|
||||
command_raw: *const raw::c_char,
|
||||
message_type: u32,
|
||||
_thread_label: EglLabel,
|
||||
_object_label: EglLabel,
|
||||
message_raw: *const raw::c_char,
|
||||
) {
|
||||
let log_severity = match message_type {
|
||||
EGL_DEBUG_MSG_CRITICAL_KHR | EGL_DEBUG_MSG_ERROR_KHR => log::Level::Error,
|
||||
EGL_DEBUG_MSG_WARN_KHR => log::Level::Warn,
|
||||
EGL_DEBUG_MSG_INFO_KHR => log::Level::Info,
|
||||
_ => log::Level::Debug,
|
||||
};
|
||||
let command = CStr::from_ptr(command_raw).to_string_lossy();
|
||||
let message = if message_raw.is_null() {
|
||||
"".into()
|
||||
} else {
|
||||
CStr::from_ptr(message_raw).to_string_lossy()
|
||||
};
|
||||
|
||||
log::log!(
|
||||
log_severity,
|
||||
"EGL '{}' code 0x{:x}: {}",
|
||||
command,
|
||||
error,
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
fn open_x_display() -> Option<(ptr::NonNull<raw::c_void>, libloading::Library)> {
|
||||
log::info!("Loading X11 library to get the current display");
|
||||
unsafe {
|
||||
let library = libloading::Library::new("libX11.so").ok()?;
|
||||
let func: libloading::Symbol<XOpenDisplayFun> = library.get(b"XOpenDisplay").unwrap();
|
||||
let result = func(ptr::null());
|
||||
ptr::NonNull::new(result).map(|ptr| (ptr, library))
|
||||
}
|
||||
}
|
||||
|
||||
fn test_wayland_display() -> Option<libloading::Library> {
|
||||
/* We try to connect and disconnect here to simply ensure there
|
||||
* is an active wayland display available.
|
||||
*/
|
||||
log::info!("Loading Wayland library to get the current display");
|
||||
let library = unsafe {
|
||||
let client_library = libloading::Library::new("libwayland-client.so").ok()?;
|
||||
let wl_display_connect: libloading::Symbol<WlDisplayConnectFun> =
|
||||
client_library.get(b"wl_display_connect").unwrap();
|
||||
let wl_display_disconnect: libloading::Symbol<WlDisplayDisconnectFun> =
|
||||
client_library.get(b"wl_display_disconnect").unwrap();
|
||||
let display = ptr::NonNull::new(wl_display_connect(ptr::null()))?;
|
||||
wl_display_disconnect(display.as_ptr());
|
||||
libloading::Library::new("libwayland-egl.so").ok()?
|
||||
};
|
||||
Some(library)
|
||||
}
|
||||
|
||||
/// Choose GLES framebuffer configuration.
|
||||
fn choose_config(
|
||||
egl: &egl::DynamicInstance<egl::EGL1_4>,
|
||||
display: egl::Display,
|
||||
) -> Result<(egl::Config, bool), crate::InstanceError> {
|
||||
//TODO: EGL_SLOW_CONFIG
|
||||
let tiers = [
|
||||
(
|
||||
"off-screen",
|
||||
&[egl::RENDERABLE_TYPE, egl::OPENGL_ES2_BIT][..],
|
||||
),
|
||||
("presentation", &[egl::SURFACE_TYPE, egl::WINDOW_BIT]),
|
||||
#[cfg(not(target_os = "android"))]
|
||||
("native-render", &[egl::NATIVE_RENDERABLE, egl::TRUE as _]),
|
||||
];
|
||||
|
||||
let mut attributes = Vec::with_capacity(7);
|
||||
for tier_max in (0..tiers.len()).rev() {
|
||||
let name = tiers[tier_max].0;
|
||||
log::info!("\tTrying {}", name);
|
||||
|
||||
attributes.clear();
|
||||
for &(_, tier_attr) in tiers[..=tier_max].iter() {
|
||||
attributes.extend_from_slice(tier_attr);
|
||||
}
|
||||
attributes.push(egl::NONE);
|
||||
|
||||
match egl.choose_first_config(display, &attributes) {
|
||||
Ok(Some(config)) => {
|
||||
return Ok((config, tier_max >= 1));
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!("No config found!");
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("error in choose_first_config: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(crate::InstanceError)
|
||||
}
|
||||
|
||||
fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
|
||||
let source_str = match source {
|
||||
glow::DEBUG_SOURCE_API => "API",
|
||||
glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
|
||||
glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
|
||||
glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
|
||||
glow::DEBUG_SOURCE_APPLICATION => "Application",
|
||||
glow::DEBUG_SOURCE_OTHER => "Other",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let log_severity = match severity {
|
||||
glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
|
||||
glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
|
||||
glow::DEBUG_SEVERITY_LOW => log::Level::Info,
|
||||
glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let type_str = match gltype {
|
||||
glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
|
||||
glow::DEBUG_TYPE_ERROR => "Error",
|
||||
glow::DEBUG_TYPE_MARKER => "Marker",
|
||||
glow::DEBUG_TYPE_OTHER => "Other",
|
||||
glow::DEBUG_TYPE_PERFORMANCE => "Performance",
|
||||
glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
|
||||
glow::DEBUG_TYPE_PORTABILITY => "Portability",
|
||||
glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
|
||||
glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
log::log!(
|
||||
log_severity,
|
||||
"GLES: [{}/{}] ID {} : {}",
|
||||
source_str,
|
||||
type_str,
|
||||
id,
|
||||
message
|
||||
);
|
||||
|
||||
if cfg!(debug_assertions) && log_severity == log::Level::Error {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
egl: Arc<egl::DynamicInstance<egl::EGL1_4>>,
|
||||
version: (i32, i32),
|
||||
supports_native_window: bool,
|
||||
display: egl::Display,
|
||||
config: egl::Config,
|
||||
context: egl::Context,
|
||||
/// Dummy pbuffer (1x1).
|
||||
/// Required for `eglMakeCurrent` on platforms that doesn't supports `EGL_KHR_surfaceless_context`.
|
||||
pbuffer: Option<egl::Surface>,
|
||||
wl_display: Option<*mut raw::c_void>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn create(
|
||||
flags: crate::InstanceFlag,
|
||||
egl: Arc<egl::DynamicInstance<egl::EGL1_4>>,
|
||||
display: egl::Display,
|
||||
) -> Result<Self, crate::InstanceError> {
|
||||
let version = egl.initialize(display).map_err(|_| crate::InstanceError)?;
|
||||
let vendor = egl.query_string(Some(display), egl::VENDOR).unwrap();
|
||||
let display_extensions = egl
|
||||
.query_string(Some(display), egl::EXTENSIONS)
|
||||
.unwrap()
|
||||
.to_string_lossy();
|
||||
log::info!("Display vendor {:?}, version {:?}", vendor, version,);
|
||||
log::debug!(
|
||||
"Display extensions: {:#?}",
|
||||
display_extensions.split_whitespace().collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
if log::max_level() >= log::LevelFilter::Trace {
|
||||
log::trace!("Configurations:");
|
||||
let config_count = egl.get_config_count(display).unwrap();
|
||||
let mut configurations = Vec::with_capacity(config_count);
|
||||
egl.get_configs(display, &mut configurations).unwrap();
|
||||
for &config in configurations.iter() {
|
||||
log::trace!("\tCONFORMANT=0x{:X}, RENDERABLE=0x{:X}, NATIVE_RENDERABLE=0x{:X}, SURFACE_TYPE=0x{:X}",
|
||||
egl.get_config_attrib(display, config, egl::CONFORMANT).unwrap(),
|
||||
egl.get_config_attrib(display, config, egl::RENDERABLE_TYPE).unwrap(),
|
||||
egl.get_config_attrib(display, config, egl::NATIVE_RENDERABLE).unwrap(),
|
||||
egl.get_config_attrib(display, config, egl::SURFACE_TYPE).unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let (config, supports_native_window) = choose_config(&egl, display)?;
|
||||
egl.bind_api(egl::OPENGL_ES_API).unwrap();
|
||||
|
||||
//TODO: make it so `Device` == EGL Context
|
||||
let mut context_attributes = vec![
|
||||
egl::CONTEXT_CLIENT_VERSION,
|
||||
3, // Request GLES 3.0 or higher
|
||||
];
|
||||
if flags.contains(crate::InstanceFlag::DEBUG) && !cfg!(target_os = "android") {
|
||||
log::info!("\tEGL context: +debug");
|
||||
//TODO: figure out why this is needed
|
||||
context_attributes.push(egl::CONTEXT_OPENGL_DEBUG);
|
||||
context_attributes.push(egl::TRUE as _);
|
||||
}
|
||||
if display_extensions.contains("EGL_EXT_create_context_robustness") {
|
||||
log::info!("\tEGL context: +robust access");
|
||||
context_attributes.push(egl::CONTEXT_OPENGL_ROBUST_ACCESS);
|
||||
context_attributes.push(egl::TRUE as _);
|
||||
//TODO do we need `egl::CONTEXT_OPENGL_NOTIFICATION_STRATEGY_EXT`?
|
||||
}
|
||||
context_attributes.push(egl::NONE);
|
||||
let context = match egl.create_context(display, config, None, &context_attributes) {
|
||||
Ok(context) => context,
|
||||
Err(e) => {
|
||||
log::warn!("unable to create GLES 3.x context: {:?}", e);
|
||||
return Err(crate::InstanceError);
|
||||
}
|
||||
};
|
||||
|
||||
// Testing if context can be binded without surface
|
||||
// and creating dummy pbuffer surface if not.
|
||||
let pbuffer =
|
||||
if version < (1, 5) || !display_extensions.contains("EGL_KHR_surfaceless_context") {
|
||||
let attributes = [egl::WIDTH, 1, egl::HEIGHT, 1, egl::NONE];
|
||||
egl.create_pbuffer_surface(display, config, &attributes)
|
||||
.map(Some)
|
||||
.map_err(|e| {
|
||||
log::warn!("Error in create_pbuffer_surface: {:?}", e);
|
||||
crate::InstanceError
|
||||
})?
|
||||
} else {
|
||||
log::info!("\tEGL context: +surfaceless");
|
||||
None
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
egl,
|
||||
display,
|
||||
version,
|
||||
supports_native_window,
|
||||
config,
|
||||
context,
|
||||
pbuffer,
|
||||
wl_display: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inner {
|
||||
fn drop(&mut self) {
|
||||
if let Err(e) = self.egl.destroy_context(self.display, self.context) {
|
||||
log::warn!("Error in destroy_context: {:?}", e);
|
||||
}
|
||||
if let Err(e) = self.egl.terminate(self.display) {
|
||||
log::warn!("Error in terminate: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Instance {
|
||||
wsi_library: Option<libloading::Library>,
|
||||
flags: crate::InstanceFlag,
|
||||
inner: Mutex<Inner>,
|
||||
}
|
||||
|
||||
unsafe impl Send for Instance {}
|
||||
unsafe impl Sync for Instance {}
|
||||
|
||||
impl crate::Instance<super::Api> for Instance {
|
||||
unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
|
||||
let egl = match egl::DynamicInstance::<egl::EGL1_4>::load_required() {
|
||||
Ok(egl) => Arc::new(egl),
|
||||
Err(e) => {
|
||||
log::warn!("Unable to open libEGL.so: {:?}", e);
|
||||
return Err(crate::InstanceError);
|
||||
}
|
||||
};
|
||||
|
||||
let client_extensions = egl.query_string(None, egl::EXTENSIONS);
|
||||
|
||||
let client_ext_str = match client_extensions {
|
||||
Ok(ext) => ext.to_string_lossy().into_owned(),
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
log::debug!(
|
||||
"Client extensions: {:#?}",
|
||||
client_ext_str.split_whitespace().collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
let mut wsi_library = None;
|
||||
|
||||
let wayland_library = if client_ext_str.contains(&"EGL_EXT_platform_wayland") {
|
||||
test_wayland_display()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let x11_display_library = if client_ext_str.contains(&"EGL_EXT_platform_x11") {
|
||||
open_x_display()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let display = if let (Some(library), Some(egl)) =
|
||||
(wayland_library, egl.upcast::<egl::EGL1_5>())
|
||||
{
|
||||
log::info!("Using Wayland platform");
|
||||
let display_attributes = [egl::ATTRIB_NONE];
|
||||
wsi_library = Some(library);
|
||||
egl.get_platform_display(
|
||||
EGL_PLATFORM_WAYLAND_KHR,
|
||||
egl::DEFAULT_DISPLAY,
|
||||
&display_attributes,
|
||||
)
|
||||
.unwrap()
|
||||
} else if let (Some((display, library)), Some(egl)) =
|
||||
(x11_display_library, egl.upcast::<egl::EGL1_5>())
|
||||
{
|
||||
log::info!("Using X11 platform");
|
||||
let display_attributes = [egl::ATTRIB_NONE];
|
||||
wsi_library = Some(library);
|
||||
egl.get_platform_display(EGL_PLATFORM_X11_KHR, display.as_ptr(), &display_attributes)
|
||||
.unwrap()
|
||||
} else {
|
||||
log::info!("Using default platform");
|
||||
egl.get_display(egl::DEFAULT_DISPLAY).unwrap()
|
||||
};
|
||||
|
||||
if desc.flags.contains(crate::InstanceFlag::VALIDATION)
|
||||
&& client_ext_str.contains(&"EGL_KHR_debug")
|
||||
{
|
||||
log::info!("Enabling EGL debug output");
|
||||
let function: EglDebugMessageControlFun =
|
||||
std::mem::transmute(egl.get_proc_address("eglDebugMessageControlKHR").unwrap());
|
||||
let attributes = [
|
||||
EGL_DEBUG_MSG_CRITICAL_KHR as egl::Attrib,
|
||||
1,
|
||||
EGL_DEBUG_MSG_ERROR_KHR as egl::Attrib,
|
||||
1,
|
||||
EGL_DEBUG_MSG_WARN_KHR as egl::Attrib,
|
||||
1,
|
||||
EGL_DEBUG_MSG_INFO_KHR as egl::Attrib,
|
||||
1,
|
||||
egl::ATTRIB_NONE,
|
||||
];
|
||||
(function)(Some(egl_debug_proc), attributes.as_ptr());
|
||||
}
|
||||
|
||||
let inner = Inner::create(desc.flags, egl, display)?;
|
||||
|
||||
Ok(Instance {
|
||||
wsi_library,
|
||||
flags: desc.flags,
|
||||
inner: Mutex::new(inner),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg_attr(target_os = "macos", allow(unused, unused_mut, unreachable_code))]
|
||||
unsafe fn create_surface(
|
||||
&self,
|
||||
has_handle: &impl raw_window_handle::HasRawWindowHandle,
|
||||
) -> Result<Surface, crate::InstanceError> {
|
||||
use raw_window_handle::RawWindowHandle as Rwh;
|
||||
|
||||
let mut inner = self.inner.lock();
|
||||
let mut wl_window = None;
|
||||
#[cfg(not(any(target_os = "android", target_os = "macos")))]
|
||||
let (mut temp_xlib_handle, mut temp_xcb_handle);
|
||||
|
||||
#[allow(trivial_casts)]
|
||||
let native_window_ptr = match has_handle.raw_window_handle() {
|
||||
#[cfg(not(any(target_os = "android", target_os = "macos")))]
|
||||
Rwh::Xlib(handle) => {
|
||||
temp_xlib_handle = handle.window;
|
||||
&mut temp_xlib_handle as *mut _ as *mut std::ffi::c_void
|
||||
}
|
||||
#[cfg(not(any(target_os = "android", target_os = "macos")))]
|
||||
Rwh::Xcb(handle) => {
|
||||
temp_xcb_handle = handle.window;
|
||||
&mut temp_xcb_handle as *mut _ as *mut std::ffi::c_void
|
||||
}
|
||||
#[cfg(target_os = "android")]
|
||||
Rwh::Android(handle) => handle.a_native_window as *mut _ as *mut std::ffi::c_void,
|
||||
#[cfg(not(any(target_os = "android", target_os = "macos")))]
|
||||
Rwh::Wayland(handle) => {
|
||||
/* Wayland displays are not sharable between surfaces so if the
|
||||
* surface we receive from this handle is from a different
|
||||
* display, we must re-initialize the context.
|
||||
*
|
||||
* See gfx-rs/gfx#3545
|
||||
*/
|
||||
log::warn!("Re-initializing Gles context due to Wayland window");
|
||||
if inner
|
||||
.wl_display
|
||||
.map(|ptr| ptr != handle.display)
|
||||
.unwrap_or(true)
|
||||
{
|
||||
use std::ops::DerefMut;
|
||||
let display_attributes = [egl::ATTRIB_NONE];
|
||||
let display = inner
|
||||
.egl
|
||||
.upcast::<egl::EGL1_5>()
|
||||
.unwrap()
|
||||
.get_platform_display(
|
||||
EGL_PLATFORM_WAYLAND_KHR,
|
||||
handle.display,
|
||||
&display_attributes,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let new_inner = Inner::create(self.flags, inner.egl.clone(), display)
|
||||
.map_err(|_| crate::InstanceError)?;
|
||||
|
||||
let old_inner = std::mem::replace(inner.deref_mut(), new_inner);
|
||||
inner.wl_display = Some(handle.display);
|
||||
drop(old_inner);
|
||||
}
|
||||
|
||||
let wl_egl_window_create: libloading::Symbol<WlEglWindowCreateFun> = self
|
||||
.wsi_library
|
||||
.as_ref()
|
||||
.expect("unsupported window")
|
||||
.get(b"wl_egl_window_create")
|
||||
.unwrap();
|
||||
let result = wl_egl_window_create(handle.surface, 640, 480) as *mut _
|
||||
as *mut std::ffi::c_void;
|
||||
wl_window = Some(result);
|
||||
result
|
||||
}
|
||||
other => {
|
||||
log::error!("Unsupported window: {:?}", other);
|
||||
return Err(crate::InstanceError);
|
||||
}
|
||||
};
|
||||
|
||||
let mut attributes = vec![
|
||||
egl::RENDER_BUFFER as usize,
|
||||
if cfg!(target_os = "android") {
|
||||
egl::BACK_BUFFER as usize
|
||||
} else {
|
||||
egl::SINGLE_BUFFER as usize
|
||||
},
|
||||
];
|
||||
if inner.version >= (1, 5) {
|
||||
// Always enable sRGB in EGL 1.5
|
||||
attributes.push(egl::GL_COLORSPACE as usize);
|
||||
attributes.push(egl::GL_COLORSPACE_SRGB as usize);
|
||||
}
|
||||
attributes.push(egl::ATTRIB_NONE);
|
||||
|
||||
let raw = if let Some(egl) = inner.egl.upcast::<egl::EGL1_5>() {
|
||||
egl.create_platform_window_surface(
|
||||
inner.display,
|
||||
inner.config,
|
||||
native_window_ptr,
|
||||
&attributes,
|
||||
)
|
||||
.map_err(|e| {
|
||||
log::warn!("Error in create_platform_window_surface: {:?}", e);
|
||||
crate::InstanceError
|
||||
})
|
||||
} else {
|
||||
let attributes_i32: Vec<i32> = attributes.iter().map(|a| *a as i32).collect();
|
||||
inner
|
||||
.egl
|
||||
.create_window_surface(
|
||||
inner.display,
|
||||
inner.config,
|
||||
native_window_ptr,
|
||||
Some(&attributes_i32),
|
||||
)
|
||||
.map_err(|e| {
|
||||
log::warn!("Error in create_platform_window_surface: {:?}", e);
|
||||
crate::InstanceError
|
||||
})
|
||||
}?;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
let format = inner
|
||||
.egl
|
||||
.get_config_attrib(inner.display, inner.config, egl::NATIVE_VISUAL_ID)
|
||||
.unwrap();
|
||||
|
||||
let ret = ANativeWindow_setBuffersGeometry(native_window_ptr, 0, 0, format);
|
||||
|
||||
if ret != 0 {
|
||||
log::error!("Error returned from ANativeWindow_setBuffersGeometry");
|
||||
return Err(crate::InstanceError);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Surface {
|
||||
egl: Arc::clone(&inner.egl),
|
||||
raw,
|
||||
display: inner.display,
|
||||
context: inner.context,
|
||||
presentable: inner.supports_native_window,
|
||||
pbuffer: inner.pbuffer,
|
||||
wl_window,
|
||||
swapchain: None,
|
||||
})
|
||||
}
|
||||
unsafe fn destroy_surface(&self, surface: Surface) {
|
||||
let inner = self.inner.lock();
|
||||
inner
|
||||
.egl
|
||||
.destroy_surface(inner.display, surface.raw)
|
||||
.unwrap();
|
||||
if let Some(wl_window) = surface.wl_window {
|
||||
let wl_egl_window_destroy: libloading::Symbol<WlEglWindowDestroyFun> = self
|
||||
.wsi_library
|
||||
.as_ref()
|
||||
.expect("unsupported window")
|
||||
.get(b"wl_egl_window_destroy")
|
||||
.unwrap();
|
||||
wl_egl_window_destroy(wl_window)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn enumerate_adapters(&self) -> Vec<crate::ExposedAdapter<super::Api>> {
|
||||
let inner = self.inner.lock();
|
||||
inner
|
||||
.egl
|
||||
.make_current(
|
||||
inner.display,
|
||||
inner.pbuffer,
|
||||
inner.pbuffer,
|
||||
Some(inner.context),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let gl = glow::Context::from_loader_function(|name| {
|
||||
inner
|
||||
.egl
|
||||
.get_proc_address(name)
|
||||
.map_or(ptr::null(), |p| p as *const _)
|
||||
});
|
||||
|
||||
if self.flags.contains(crate::InstanceFlag::DEBUG) && gl.supports_debug() {
|
||||
log::info!(
|
||||
"Max label length: {}",
|
||||
gl.get_parameter_i32(glow::MAX_LABEL_LENGTH)
|
||||
);
|
||||
}
|
||||
|
||||
if self.flags.contains(crate::InstanceFlag::VALIDATION) && gl.supports_debug() {
|
||||
log::info!("Enabling GLES debug output");
|
||||
gl.enable(glow::DEBUG_OUTPUT);
|
||||
gl.debug_message_callback(gl_debug_message_callback);
|
||||
}
|
||||
|
||||
super::Adapter::expose(gl).into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Swapchain {
|
||||
framebuffer: glow::Framebuffer,
|
||||
renderbuffer: glow::Renderbuffer,
|
||||
/// Extent because the window lies
|
||||
extent: wgt::Extent3d,
|
||||
format: wgt::TextureFormat,
|
||||
format_desc: super::TextureFormatDesc,
|
||||
sample_type: wgt::TextureSampleType,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Surface {
|
||||
egl: Arc<egl::DynamicInstance<egl::EGL1_4>>,
|
||||
raw: egl::Surface,
|
||||
display: egl::Display,
|
||||
context: egl::Context,
|
||||
pbuffer: Option<egl::Surface>,
|
||||
pub(super) presentable: bool,
|
||||
wl_window: Option<*mut raw::c_void>,
|
||||
swapchain: Option<Swapchain>,
|
||||
}
|
||||
|
||||
unsafe impl Send for Surface {}
|
||||
unsafe impl Sync for Surface {}
|
||||
|
||||
impl Surface {
|
||||
pub(super) unsafe fn present(
|
||||
&mut self,
|
||||
_suf_texture: super::Texture,
|
||||
gl: &glow::Context,
|
||||
) -> Result<(), crate::SurfaceError> {
|
||||
let sc = self.swapchain.as_ref().unwrap();
|
||||
|
||||
self.egl
|
||||
.make_current(
|
||||
self.display,
|
||||
Some(self.raw),
|
||||
Some(self.raw),
|
||||
Some(self.context),
|
||||
)
|
||||
.map_err(|e| {
|
||||
log::error!("make_current(surface) failed: {}", e);
|
||||
crate::SurfaceError::Lost
|
||||
})?;
|
||||
|
||||
gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None);
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer));
|
||||
// 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.
|
||||
gl.blit_framebuffer(
|
||||
0,
|
||||
sc.extent.height as i32,
|
||||
sc.extent.width as i32,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
sc.extent.width as i32,
|
||||
sc.extent.height as i32,
|
||||
glow::COLOR_BUFFER_BIT,
|
||||
glow::NEAREST,
|
||||
);
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None);
|
||||
|
||||
self.egl.swap_buffers(self.display, self.raw).map_err(|e| {
|
||||
log::error!("swap_buffers failed: {}", e);
|
||||
crate::SurfaceError::Lost
|
||||
})?;
|
||||
self.egl
|
||||
.make_current(self.display, self.pbuffer, self.pbuffer, Some(self.context))
|
||||
.map_err(|e| {
|
||||
log::error!("make_current(null) failed: {}", e);
|
||||
crate::SurfaceError::Lost
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Surface<super::Api> for Surface {
|
||||
unsafe fn configure(
|
||||
&mut self,
|
||||
device: &super::Device,
|
||||
config: &crate::SurfaceConfiguration,
|
||||
) -> Result<(), crate::SurfaceError> {
|
||||
self.unconfigure(device);
|
||||
|
||||
if let Some(window) = self.wl_window {
|
||||
let library = libloading::Library::new("libwayland-egl.so").unwrap();
|
||||
let wl_egl_window_resize: libloading::Symbol<WlEglWindowResizeFun> =
|
||||
library.get(b"wl_egl_window_resize").unwrap();
|
||||
wl_egl_window_resize(
|
||||
window,
|
||||
config.extent.width as i32,
|
||||
config.extent.height as i32,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
let format_desc = device.shared.describe_texture_format(config.format);
|
||||
let gl = &device.shared.context;
|
||||
let renderbuffer = gl.create_renderbuffer().unwrap();
|
||||
gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer));
|
||||
gl.renderbuffer_storage(
|
||||
glow::RENDERBUFFER,
|
||||
format_desc.internal,
|
||||
config.extent.width as _,
|
||||
config.extent.height as _,
|
||||
);
|
||||
let framebuffer = gl.create_framebuffer().unwrap();
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer));
|
||||
gl.framebuffer_renderbuffer(
|
||||
glow::READ_FRAMEBUFFER,
|
||||
glow::COLOR_ATTACHMENT0,
|
||||
glow::RENDERBUFFER,
|
||||
Some(renderbuffer),
|
||||
);
|
||||
gl.bind_renderbuffer(glow::RENDERBUFFER, None);
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None);
|
||||
|
||||
self.swapchain = Some(Swapchain {
|
||||
renderbuffer,
|
||||
framebuffer,
|
||||
extent: config.extent,
|
||||
format: config.format,
|
||||
format_desc,
|
||||
sample_type: wgt::TextureSampleType::Float { filterable: false },
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
unsafe fn unconfigure(&mut self, device: &super::Device) {
|
||||
let gl = &device.shared.context;
|
||||
if let Some(sc) = self.swapchain.take() {
|
||||
gl.delete_renderbuffer(sc.renderbuffer);
|
||||
gl.delete_framebuffer(sc.framebuffer);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn acquire_texture(
|
||||
&mut self,
|
||||
_timeout_ms: u32, //TODO
|
||||
) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
|
||||
let sc = self.swapchain.as_ref().unwrap();
|
||||
let texture = super::Texture {
|
||||
inner: super::TextureInner::Renderbuffer {
|
||||
raw: sc.renderbuffer,
|
||||
},
|
||||
array_layer_count: 1,
|
||||
mip_level_count: 1,
|
||||
format: sc.format,
|
||||
format_desc: sc.format_desc.clone(),
|
||||
};
|
||||
Ok(Some(crate::AcquiredSurfaceTexture {
|
||||
texture,
|
||||
suboptimal: false,
|
||||
}))
|
||||
}
|
||||
unsafe fn discard_texture(&mut self, _texture: super::Texture) {}
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
/*!
|
||||
# OpenGL ES3 API (aka GLES3).
|
||||
|
||||
Designed to work on Linux and Android, with context provided by EGL.
|
||||
|
||||
## Texture views
|
||||
|
||||
GLES3 doesn't really have separate texture view objects. We have to remember the
|
||||
original texture and the sub-range into it. Problem is, however, that there is
|
||||
no way to expose a subset of array layers or mip levels of a sampled texture.
|
||||
|
||||
## Binding model
|
||||
|
||||
Binding model is very different from WebGPU, especially with regards to samplers.
|
||||
GLES3 has sampler objects, but they aren't separately bindable to the shaders.
|
||||
Each sampled texture is exposed to the shader as a combined texture-sampler binding.
|
||||
|
||||
When building the pipeline layout, we linearize binding entries based on the groups
|
||||
(uniform/storage buffers, uniform/storage textures), and record the mapping into
|
||||
`BindGroupLayoutInfo`.
|
||||
When a pipeline gets created, and we track all the texture-sampler associations
|
||||
from the static use in the shader.
|
||||
We only support at most one sampler used with each texture so far. The linear index
|
||||
of this sampler is stored per texture slot in `SamplerBindMap` array.
|
||||
|
||||
The texture-sampler pairs get potentially invalidated in 2 places:
|
||||
- when a new pipeline is set, we update the linear indices of associated samplers
|
||||
- when a new bind group is set, we update both the textures and the samplers
|
||||
|
||||
We expect that the changes to sampler states between any 2 pipelines of the same layout
|
||||
will be minimal, if any.
|
||||
|
||||
## Vertex data
|
||||
|
||||
Generally, vertex buffers are marked as dirty and lazily bound on draw.
|
||||
|
||||
GLES3 doesn't support "base instance" semantics. However, it's easy to support,
|
||||
since we are forced to do late binding anyway. We just adjust the offsets
|
||||
into the vertex data.
|
||||
|
||||
### Old path
|
||||
|
||||
In GLES-3.0 and WebGL2, vertex buffer layout is provided
|
||||
together with the actual buffer binding.
|
||||
We invalidate the attributes on the vertex buffer change, and re-bind them.
|
||||
|
||||
### New path
|
||||
|
||||
In GLES-3.1 and higher, the vertex buffer layout can be declared separately
|
||||
from the vertex data itself. This mostly matches WebGPU, however there is a catch:
|
||||
`stride` needs to be specified with the data, not as a part of the layout.
|
||||
|
||||
To address this, we invalidate the vertex buffers based on:
|
||||
- whether or not `start_instance` is used
|
||||
- stride has changed
|
||||
|
||||
*/
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod egl;
|
||||
|
||||
mod adapter;
|
||||
mod command;
|
||||
mod conv;
|
||||
mod device;
|
||||
mod queue;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use self::egl::{Instance, Surface};
|
||||
|
||||
use glow::HasContext;
|
||||
|
||||
use std::{ops::Range, sync::Arc};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Api;
|
||||
|
||||
//Note: we can support more samplers if not every one of them is used at a time,
|
||||
// but it probably doesn't worth it.
|
||||
const MAX_TEXTURE_SLOTS: usize = 16;
|
||||
const MAX_SAMPLERS: usize = 16;
|
||||
const MAX_VERTEX_ATTRIBUTES: usize = 16;
|
||||
const ZERO_BUFFER_SIZE: usize = 256 << 10;
|
||||
|
||||
impl crate::Api for Api {
|
||||
type Instance = Instance;
|
||||
type Surface = Surface;
|
||||
type Adapter = Adapter;
|
||||
type Device = Device;
|
||||
|
||||
type Queue = Queue;
|
||||
type CommandEncoder = CommandEncoder;
|
||||
type CommandBuffer = CommandBuffer;
|
||||
|
||||
type Buffer = Buffer;
|
||||
type Texture = Texture;
|
||||
type SurfaceTexture = Texture;
|
||||
type TextureView = TextureView;
|
||||
type Sampler = Sampler;
|
||||
type QuerySet = QuerySet;
|
||||
type Fence = Fence;
|
||||
|
||||
type BindGroupLayout = BindGroupLayout;
|
||||
type BindGroup = BindGroup;
|
||||
type PipelineLayout = PipelineLayout;
|
||||
type ShaderModule = ShaderModule;
|
||||
type RenderPipeline = RenderPipeline;
|
||||
type ComputePipeline = ComputePipeline;
|
||||
}
|
||||
|
||||
bitflags::bitflags! {
|
||||
/// Flags that affect internal code paths but do not
|
||||
/// change the exposed feature set.
|
||||
struct PrivateCapability: u32 {
|
||||
/// Support explicit layouts in shader.
|
||||
const SHADER_BINDING_LAYOUT = 0x0001;
|
||||
/// Support extended shadow sampling instructions.
|
||||
const SHADER_TEXTURE_SHADOW_LOD = 0x0002;
|
||||
/// Support memory barriers.
|
||||
const MEMORY_BARRIERS = 0x0004;
|
||||
/// Vertex buffer layouts separate from the data.
|
||||
const VERTEX_BUFFER_LAYOUT = 0x0008;
|
||||
}
|
||||
}
|
||||
|
||||
type BindTarget = u32;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum VertexAttribKind {
|
||||
Float, // glVertexAttribPointer
|
||||
Integer, // glVertexAttribIPointer
|
||||
//Double, // glVertexAttribLPointer
|
||||
}
|
||||
|
||||
impl Default for VertexAttribKind {
|
||||
fn default() -> Self {
|
||||
Self::Float
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct TextureFormatDesc {
|
||||
internal: u32,
|
||||
external: u32,
|
||||
data_type: u32,
|
||||
}
|
||||
|
||||
struct AdapterShared {
|
||||
context: glow::Context,
|
||||
private_caps: PrivateCapability,
|
||||
shading_language_version: naga::back::glsl::Version,
|
||||
}
|
||||
|
||||
pub struct Adapter {
|
||||
shared: Arc<AdapterShared>,
|
||||
}
|
||||
|
||||
pub struct Device {
|
||||
shared: Arc<AdapterShared>,
|
||||
main_vao: glow::VertexArray,
|
||||
}
|
||||
|
||||
pub struct Queue {
|
||||
shared: Arc<AdapterShared>,
|
||||
features: wgt::Features,
|
||||
draw_fbo: glow::Framebuffer,
|
||||
copy_fbo: glow::Framebuffer,
|
||||
/// Keep a reasonably large buffer filled with zeroes,
|
||||
/// so that we can implement `FillBuffer` of zeroes
|
||||
/// by copying from it.
|
||||
zero_buffer: glow::Buffer,
|
||||
temp_query_results: Vec<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Buffer {
|
||||
raw: glow::Buffer,
|
||||
target: BindTarget,
|
||||
size: wgt::BufferAddress,
|
||||
map_flags: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum TextureInner {
|
||||
Renderbuffer {
|
||||
raw: glow::Renderbuffer,
|
||||
},
|
||||
Texture {
|
||||
raw: glow::Texture,
|
||||
target: BindTarget,
|
||||
},
|
||||
}
|
||||
|
||||
impl TextureInner {
|
||||
fn as_native(&self) -> (glow::Texture, BindTarget) {
|
||||
match *self {
|
||||
Self::Renderbuffer { raw, .. } => panic!("Unexpected renderbuffer {}", raw),
|
||||
Self::Texture { raw, target } => (raw, target),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Texture {
|
||||
inner: TextureInner,
|
||||
mip_level_count: u32,
|
||||
array_layer_count: u32,
|
||||
format: wgt::TextureFormat,
|
||||
format_desc: TextureFormatDesc,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TextureView {
|
||||
inner: TextureInner,
|
||||
sample_type: wgt::TextureSampleType,
|
||||
aspects: crate::FormatAspect,
|
||||
mip_levels: Range<u32>,
|
||||
array_layers: Range<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Sampler {
|
||||
raw: glow::Sampler,
|
||||
}
|
||||
|
||||
pub struct BindGroupLayout {
|
||||
entries: Arc<[wgt::BindGroupLayoutEntry]>,
|
||||
}
|
||||
|
||||
struct BindGroupLayoutInfo {
|
||||
entries: Arc<[wgt::BindGroupLayoutEntry]>,
|
||||
/// Mapping of resources, indexed by `binding`, into the whole layout space.
|
||||
/// For texture resources, the value is the texture slot index.
|
||||
/// For sampler resources, the value is the index of the sampler in the whole layout.
|
||||
/// For buffers, the value is the uniform or storage slot index.
|
||||
/// For unused bindings, the value is `!0`
|
||||
binding_to_slot: Box<[u8]>,
|
||||
}
|
||||
|
||||
pub struct PipelineLayout {
|
||||
group_infos: Box<[BindGroupLayoutInfo]>,
|
||||
naga_options: naga::back::glsl::Options,
|
||||
}
|
||||
|
||||
impl PipelineLayout {
|
||||
fn get_slot(&self, br: &naga::ResourceBinding) -> u8 {
|
||||
let group_info = &self.group_infos[br.group as usize];
|
||||
group_info.binding_to_slot[br.binding as usize]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum BindingRegister {
|
||||
UniformBuffers,
|
||||
StorageBuffers,
|
||||
Textures,
|
||||
Images,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum RawBinding {
|
||||
Buffer {
|
||||
raw: glow::Buffer,
|
||||
offset: i32,
|
||||
size: i32,
|
||||
},
|
||||
Texture {
|
||||
raw: glow::Texture,
|
||||
target: BindTarget,
|
||||
//TODO: mip levels, array layers
|
||||
},
|
||||
Image(ImageBinding),
|
||||
Sampler(glow::Sampler),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BindGroup {
|
||||
contents: Box<[RawBinding]>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ShaderModule {
|
||||
naga: crate::NagaShader,
|
||||
label: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct VertexFormatDesc {
|
||||
element_count: i32,
|
||||
element_format: u32,
|
||||
attrib_kind: VertexAttribKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct AttributeDesc {
|
||||
location: u32,
|
||||
offset: u32,
|
||||
buffer_index: u32,
|
||||
format_desc: VertexFormatDesc,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct BufferBinding {
|
||||
raw: glow::Buffer,
|
||||
offset: wgt::BufferAddress,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct ImageBinding {
|
||||
raw: glow::Texture,
|
||||
mip_level: u32,
|
||||
array_layer: Option<u32>,
|
||||
access: u32,
|
||||
format: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct VertexBufferDesc {
|
||||
step: wgt::InputStepMode,
|
||||
stride: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct UniformDesc {
|
||||
location: glow::UniformLocation,
|
||||
offset: u32,
|
||||
utype: u32,
|
||||
}
|
||||
|
||||
/// For each texture in the pipeline layout, store the index of the only
|
||||
/// sampler (in this layout) that the texture is used with.
|
||||
type SamplerBindMap = [Option<u8>; MAX_TEXTURE_SLOTS];
|
||||
|
||||
struct PipelineInner {
|
||||
program: glow::Program,
|
||||
sampler_map: SamplerBindMap,
|
||||
uniforms: Box<[UniformDesc]>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct DepthState {
|
||||
function: u32,
|
||||
mask: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct BlendComponent {
|
||||
src: u32,
|
||||
dst: u32,
|
||||
equation: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct BlendDesc {
|
||||
alpha: BlendComponent,
|
||||
color: BlendComponent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct ColorTargetDesc {
|
||||
mask: wgt::ColorWrite,
|
||||
blend: Option<BlendDesc>,
|
||||
}
|
||||
|
||||
pub struct RenderPipeline {
|
||||
inner: PipelineInner,
|
||||
primitive: wgt::PrimitiveState,
|
||||
vertex_buffers: Box<[VertexBufferDesc]>,
|
||||
vertex_attributes: Box<[AttributeDesc]>,
|
||||
color_targets: Box<[ColorTargetDesc]>,
|
||||
depth: Option<DepthState>,
|
||||
depth_bias: wgt::DepthBiasState,
|
||||
stencil: Option<StencilState>,
|
||||
}
|
||||
|
||||
pub struct ComputePipeline {
|
||||
inner: PipelineInner,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct QuerySet {
|
||||
queries: Box<[glow::Query]>,
|
||||
target: BindTarget,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Fence {
|
||||
last_completed: crate::FenceValue,
|
||||
pending: Vec<(crate::FenceValue, glow::Fence)>,
|
||||
}
|
||||
|
||||
unsafe impl Send for Fence {}
|
||||
unsafe impl Sync for Fence {}
|
||||
|
||||
impl Fence {
|
||||
fn get_latest(&self, gl: &glow::Context) -> crate::FenceValue {
|
||||
let mut max_value = self.last_completed;
|
||||
for &(value, sync) in self.pending.iter() {
|
||||
let status = unsafe { gl.get_sync_status(sync) };
|
||||
if status == glow::SIGNALED {
|
||||
max_value = value;
|
||||
}
|
||||
}
|
||||
max_value
|
||||
}
|
||||
|
||||
fn maintain(&mut self, gl: &glow::Context) {
|
||||
let latest = self.get_latest(gl);
|
||||
for &(value, sync) in self.pending.iter() {
|
||||
if value <= latest {
|
||||
unsafe {
|
||||
gl.delete_sync(sync);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.pending.retain(|&(value, _)| value > latest);
|
||||
self.last_completed = latest;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct StencilOps {
|
||||
pass: u32,
|
||||
fail: u32,
|
||||
depth_fail: u32,
|
||||
}
|
||||
|
||||
impl Default for StencilOps {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pass: glow::KEEP,
|
||||
fail: glow::KEEP,
|
||||
depth_fail: glow::KEEP,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct StencilSide {
|
||||
function: u32,
|
||||
mask_read: u32,
|
||||
mask_write: u32,
|
||||
reference: u32,
|
||||
ops: StencilOps,
|
||||
}
|
||||
|
||||
impl Default for StencilSide {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
function: glow::ALWAYS,
|
||||
mask_read: 0xFF,
|
||||
mask_write: 0xFF,
|
||||
reference: 0,
|
||||
ops: StencilOps::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct StencilState {
|
||||
front: StencilSide,
|
||||
back: StencilSide,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct PrimitiveState {
|
||||
front_face: u32,
|
||||
cull_face: u32,
|
||||
clamp_depth: bool,
|
||||
}
|
||||
|
||||
type InvalidatedAttachments = arrayvec::ArrayVec<[u32; crate::MAX_COLOR_TARGETS + 2]>;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Command {
|
||||
Draw {
|
||||
topology: u32,
|
||||
start_vertex: u32,
|
||||
vertex_count: u32,
|
||||
instance_count: u32,
|
||||
},
|
||||
DrawIndexed {
|
||||
topology: u32,
|
||||
index_type: u32,
|
||||
index_count: u32,
|
||||
index_offset: wgt::BufferAddress,
|
||||
base_vertex: i32,
|
||||
instance_count: u32,
|
||||
},
|
||||
DrawIndirect {
|
||||
topology: u32,
|
||||
indirect_buf: glow::Buffer,
|
||||
indirect_offset: wgt::BufferAddress,
|
||||
},
|
||||
DrawIndexedIndirect {
|
||||
topology: u32,
|
||||
index_type: u32,
|
||||
indirect_buf: glow::Buffer,
|
||||
indirect_offset: wgt::BufferAddress,
|
||||
},
|
||||
Dispatch([u32; 3]),
|
||||
DispatchIndirect {
|
||||
indirect_buf: glow::Buffer,
|
||||
indirect_offset: wgt::BufferAddress,
|
||||
},
|
||||
FillBuffer {
|
||||
dst: glow::Buffer,
|
||||
dst_target: BindTarget,
|
||||
range: crate::MemoryRange,
|
||||
value: u8,
|
||||
},
|
||||
CopyBufferToBuffer {
|
||||
src: glow::Buffer,
|
||||
src_target: BindTarget,
|
||||
dst: glow::Buffer,
|
||||
dst_target: BindTarget,
|
||||
copy: crate::BufferCopy,
|
||||
},
|
||||
CopyTextureToTexture {
|
||||
src: glow::Texture,
|
||||
src_target: BindTarget,
|
||||
dst: glow::Texture,
|
||||
dst_target: BindTarget,
|
||||
copy: crate::TextureCopy,
|
||||
},
|
||||
CopyBufferToTexture {
|
||||
src: glow::Buffer,
|
||||
src_target: BindTarget,
|
||||
dst: glow::Texture,
|
||||
dst_target: BindTarget,
|
||||
dst_format: wgt::TextureFormat,
|
||||
copy: crate::BufferTextureCopy,
|
||||
},
|
||||
CopyTextureToBuffer {
|
||||
src: glow::Texture,
|
||||
src_target: BindTarget,
|
||||
src_format: wgt::TextureFormat,
|
||||
dst: glow::Buffer,
|
||||
dst_target: BindTarget,
|
||||
copy: crate::BufferTextureCopy,
|
||||
},
|
||||
SetIndexBuffer(glow::Buffer),
|
||||
BeginQuery(glow::Query, BindTarget),
|
||||
EndQuery(BindTarget),
|
||||
CopyQueryResults {
|
||||
query_range: Range<u32>,
|
||||
dst: glow::Buffer,
|
||||
dst_target: BindTarget,
|
||||
dst_offset: wgt::BufferAddress,
|
||||
},
|
||||
ResetFramebuffer,
|
||||
BindAttachment {
|
||||
attachment: u32,
|
||||
view: TextureView,
|
||||
},
|
||||
ResolveAttachment {
|
||||
attachment: u32,
|
||||
dst: TextureView,
|
||||
size: wgt::Extent3d,
|
||||
},
|
||||
InvalidateAttachments(InvalidatedAttachments),
|
||||
SetDrawColorBuffers(u8),
|
||||
ClearColorF(u32, [f32; 4]),
|
||||
ClearColorU(u32, [u32; 4]),
|
||||
ClearColorI(u32, [i32; 4]),
|
||||
ClearDepth(f32),
|
||||
ClearStencil(u32),
|
||||
BufferBarrier(glow::Buffer, crate::BufferUse),
|
||||
TextureBarrier(crate::TextureUse),
|
||||
SetViewport {
|
||||
rect: crate::Rect<i32>,
|
||||
depth: Range<f32>,
|
||||
},
|
||||
SetScissor(crate::Rect<i32>),
|
||||
SetStencilFunc {
|
||||
face: u32,
|
||||
function: u32,
|
||||
reference: u32,
|
||||
read_mask: u32,
|
||||
},
|
||||
SetStencilOps {
|
||||
face: u32,
|
||||
write_mask: u32,
|
||||
ops: StencilOps,
|
||||
},
|
||||
SetDepth(DepthState),
|
||||
SetDepthBias(wgt::DepthBiasState),
|
||||
ConfigureDepthStencil(crate::FormatAspect),
|
||||
SetVertexAttribute {
|
||||
buffer: Option<glow::Buffer>,
|
||||
buffer_desc: VertexBufferDesc,
|
||||
attribute_desc: AttributeDesc,
|
||||
},
|
||||
UnsetVertexAttribute(u32),
|
||||
SetVertexBuffer {
|
||||
index: u32,
|
||||
buffer: BufferBinding,
|
||||
buffer_desc: VertexBufferDesc,
|
||||
},
|
||||
SetProgram(glow::Program),
|
||||
SetPrimitive(PrimitiveState),
|
||||
SetBlendConstant([f32; 4]),
|
||||
SetColorTarget {
|
||||
draw_buffer_index: Option<u32>,
|
||||
desc: ColorTargetDesc,
|
||||
},
|
||||
BindBuffer {
|
||||
target: BindTarget,
|
||||
slot: u32,
|
||||
buffer: glow::Buffer,
|
||||
offset: i32,
|
||||
size: i32,
|
||||
},
|
||||
BindSampler(u32, glow::Sampler),
|
||||
BindTexture {
|
||||
slot: u32,
|
||||
texture: glow::Texture,
|
||||
target: BindTarget,
|
||||
},
|
||||
BindImage {
|
||||
slot: u32,
|
||||
binding: ImageBinding,
|
||||
},
|
||||
InsertDebugMarker(Range<u32>),
|
||||
PushDebugGroup(Range<u32>),
|
||||
PopDebugGroup,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct CommandBuffer {
|
||||
label: Option<String>,
|
||||
commands: Vec<Command>,
|
||||
data_bytes: Vec<u8>,
|
||||
data_words: Vec<u32>,
|
||||
}
|
||||
|
||||
//TODO: we would have something like `Arc<typed_arena::Arena>`
|
||||
// here and in the command buffers. So that everything grows
|
||||
// inside the encoder and stays there until `reset_all`.
|
||||
|
||||
pub struct CommandEncoder {
|
||||
cmd_buffer: CommandBuffer,
|
||||
state: command::State,
|
||||
private_caps: PrivateCapability,
|
||||
}
|
||||
@@ -0,0 +1,942 @@
|
||||
use super::Command as C;
|
||||
use arrayvec::ArrayVec;
|
||||
use glow::HasContext;
|
||||
use std::{mem, ops::Range, slice};
|
||||
|
||||
const DEBUG_ID: u32 = 0;
|
||||
|
||||
const CUBEMAP_FACES: [u32; 6] = [
|
||||
glow::TEXTURE_CUBE_MAP_POSITIVE_X,
|
||||
glow::TEXTURE_CUBE_MAP_NEGATIVE_X,
|
||||
glow::TEXTURE_CUBE_MAP_POSITIVE_Y,
|
||||
glow::TEXTURE_CUBE_MAP_NEGATIVE_Y,
|
||||
glow::TEXTURE_CUBE_MAP_POSITIVE_Z,
|
||||
glow::TEXTURE_CUBE_MAP_NEGATIVE_Z,
|
||||
];
|
||||
|
||||
fn extract_marker<'a>(data: &'a [u8], range: &Range<u32>) -> &'a str {
|
||||
std::str::from_utf8(&data[range.start as usize..range.end as usize]).unwrap()
|
||||
}
|
||||
|
||||
fn is_3d_target(target: super::BindTarget) -> bool {
|
||||
match target {
|
||||
glow::TEXTURE_2D_ARRAY | glow::TEXTURE_3D => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Queue {
|
||||
unsafe fn reset_state(&self) {
|
||||
let gl = &self.shared.context;
|
||||
gl.use_program(None);
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
|
||||
gl.disable(glow::DEPTH_TEST);
|
||||
gl.disable(glow::STENCIL_TEST);
|
||||
gl.disable(glow::SCISSOR_TEST);
|
||||
gl.disable(glow::BLEND);
|
||||
gl.disable(glow::CULL_FACE);
|
||||
gl.disable(glow::POLYGON_OFFSET_FILL);
|
||||
if self.features.contains(wgt::Features::DEPTH_CLAMPING) {
|
||||
gl.disable(glow::DEPTH_CLAMP);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_attachment(&self, fbo_target: u32, attachment: u32, view: &super::TextureView) {
|
||||
let gl = &self.shared.context;
|
||||
match view.inner {
|
||||
super::TextureInner::Renderbuffer { raw } => {
|
||||
gl.framebuffer_renderbuffer(fbo_target, attachment, glow::RENDERBUFFER, Some(raw));
|
||||
}
|
||||
super::TextureInner::Texture { raw, target } => {
|
||||
if is_3d_target(target) {
|
||||
gl.framebuffer_texture_layer(
|
||||
fbo_target,
|
||||
attachment,
|
||||
Some(raw),
|
||||
view.mip_levels.start as i32,
|
||||
view.array_layers.start as i32,
|
||||
);
|
||||
} else {
|
||||
gl.framebuffer_texture_2d(
|
||||
fbo_target,
|
||||
attachment,
|
||||
target,
|
||||
Some(raw),
|
||||
view.mip_levels.start as i32,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn process(&mut self, command: &C, data_bytes: &[u8], data_words: &[u32]) {
|
||||
let gl = &self.shared.context;
|
||||
match *command {
|
||||
C::Draw {
|
||||
topology,
|
||||
start_vertex,
|
||||
vertex_count,
|
||||
instance_count,
|
||||
} => {
|
||||
if instance_count == 1 {
|
||||
gl.draw_arrays(topology, start_vertex as i32, vertex_count as i32);
|
||||
} else {
|
||||
gl.draw_arrays_instanced(
|
||||
topology,
|
||||
start_vertex as i32,
|
||||
vertex_count as i32,
|
||||
instance_count as i32,
|
||||
);
|
||||
}
|
||||
}
|
||||
C::DrawIndexed {
|
||||
topology,
|
||||
index_type,
|
||||
index_count,
|
||||
index_offset,
|
||||
base_vertex,
|
||||
instance_count,
|
||||
} => match (base_vertex, instance_count) {
|
||||
(0, 1) => gl.draw_elements(
|
||||
topology,
|
||||
index_count as i32,
|
||||
index_type,
|
||||
index_offset as i32,
|
||||
),
|
||||
(0, _) => gl.draw_elements_instanced(
|
||||
topology,
|
||||
index_count as i32,
|
||||
index_type,
|
||||
index_offset as i32,
|
||||
instance_count as i32,
|
||||
),
|
||||
(_, 1) => gl.draw_elements_base_vertex(
|
||||
topology,
|
||||
index_count as i32,
|
||||
index_type,
|
||||
index_offset as i32,
|
||||
base_vertex,
|
||||
),
|
||||
(_, _) => gl.draw_elements_instanced_base_vertex(
|
||||
topology,
|
||||
index_count as _,
|
||||
index_type,
|
||||
index_offset as i32,
|
||||
instance_count as i32,
|
||||
base_vertex,
|
||||
),
|
||||
},
|
||||
C::DrawIndirect {
|
||||
topology,
|
||||
indirect_buf,
|
||||
indirect_offset,
|
||||
} => {
|
||||
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(indirect_buf));
|
||||
gl.draw_arrays_indirect_offset(topology, indirect_offset as i32);
|
||||
}
|
||||
C::DrawIndexedIndirect {
|
||||
topology,
|
||||
index_type,
|
||||
indirect_buf,
|
||||
indirect_offset,
|
||||
} => {
|
||||
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(indirect_buf));
|
||||
gl.draw_elements_indirect_offset(topology, index_type, indirect_offset as i32);
|
||||
}
|
||||
C::Dispatch(group_counts) => {
|
||||
gl.dispatch_compute(group_counts[0], group_counts[1], group_counts[2]);
|
||||
}
|
||||
C::DispatchIndirect {
|
||||
indirect_buf,
|
||||
indirect_offset,
|
||||
} => {
|
||||
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(indirect_buf));
|
||||
gl.dispatch_compute_indirect(indirect_offset as i32);
|
||||
}
|
||||
C::FillBuffer {
|
||||
dst,
|
||||
dst_target,
|
||||
ref range,
|
||||
value,
|
||||
} => {
|
||||
assert_eq!(value, 0); // other values require `wgt::Features::CLEAR_COMMANDS`.
|
||||
gl.bind_buffer(glow::COPY_READ_BUFFER, Some(self.zero_buffer));
|
||||
gl.bind_buffer(dst_target, Some(dst));
|
||||
let mut dst_offset = range.start;
|
||||
while dst_offset < range.end {
|
||||
let size = (range.end - dst_offset).min(super::ZERO_BUFFER_SIZE as u64);
|
||||
gl.copy_buffer_sub_data(
|
||||
glow::COPY_READ_BUFFER,
|
||||
dst_target,
|
||||
0,
|
||||
dst_offset as i32,
|
||||
size as i32,
|
||||
);
|
||||
dst_offset += size;
|
||||
}
|
||||
}
|
||||
C::CopyBufferToBuffer {
|
||||
src,
|
||||
src_target,
|
||||
dst,
|
||||
dst_target,
|
||||
copy,
|
||||
} => {
|
||||
gl.bind_buffer(src_target, Some(src));
|
||||
gl.bind_buffer(dst_target, Some(dst));
|
||||
|
||||
gl.copy_buffer_sub_data(
|
||||
src_target,
|
||||
dst_target,
|
||||
copy.src_offset as i32,
|
||||
copy.dst_offset as i32,
|
||||
copy.size.get() as i32,
|
||||
);
|
||||
}
|
||||
C::CopyTextureToTexture {
|
||||
src,
|
||||
src_target,
|
||||
dst,
|
||||
dst_target,
|
||||
ref copy,
|
||||
} => {
|
||||
//TODO: cubemaps
|
||||
//TODO: how is depth handled?
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.copy_fbo));
|
||||
for layer in 0..copy.size.depth_or_array_layers as i32 {
|
||||
if is_3d_target(src_target) {
|
||||
//TODO: handle GLES without framebuffer_texture_3d
|
||||
gl.framebuffer_texture_layer(
|
||||
glow::READ_FRAMEBUFFER,
|
||||
glow::COLOR_ATTACHMENT0,
|
||||
Some(src),
|
||||
copy.src_base.mip_level as i32,
|
||||
copy.src_base.origin.z as i32 + layer,
|
||||
);
|
||||
} else {
|
||||
gl.framebuffer_texture_2d(
|
||||
glow::READ_FRAMEBUFFER,
|
||||
glow::COLOR_ATTACHMENT0,
|
||||
src_target,
|
||||
Some(src),
|
||||
copy.src_base.mip_level as i32,
|
||||
);
|
||||
}
|
||||
gl.bind_texture(dst_target, Some(dst));
|
||||
if is_3d_target(dst_target) {
|
||||
gl.copy_tex_sub_image_3d(
|
||||
dst_target,
|
||||
copy.dst_base.mip_level as i32,
|
||||
copy.dst_base.origin.x as i32,
|
||||
copy.dst_base.origin.y as i32,
|
||||
copy.dst_base.origin.z as i32 + layer,
|
||||
copy.src_base.origin.x as i32,
|
||||
copy.src_base.origin.y as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
);
|
||||
} else {
|
||||
gl.copy_tex_sub_image_2d(
|
||||
dst_target,
|
||||
copy.dst_base.mip_level as i32,
|
||||
copy.dst_base.origin.x as i32,
|
||||
copy.dst_base.origin.y as i32,
|
||||
copy.src_base.origin.x as i32,
|
||||
copy.src_base.origin.y as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
C::CopyBufferToTexture {
|
||||
src,
|
||||
src_target: _,
|
||||
dst,
|
||||
dst_target,
|
||||
dst_format,
|
||||
ref copy,
|
||||
} => {
|
||||
let format_info = dst_format.describe();
|
||||
let format_desc = self.shared.describe_texture_format(dst_format);
|
||||
|
||||
let row_texels = copy.buffer_layout.bytes_per_row.map_or(0, |bpr| {
|
||||
format_info.block_dimensions.0 as u32 * bpr.get()
|
||||
/ format_info.block_size as u32
|
||||
});
|
||||
let column_texels = copy
|
||||
.buffer_layout
|
||||
.rows_per_image
|
||||
.map_or(0, |rpi| format_info.block_dimensions.1 as u32 * rpi.get());
|
||||
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, row_texels as i32);
|
||||
gl.pixel_store_i32(glow::UNPACK_IMAGE_HEIGHT, column_texels as i32);
|
||||
gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(src));
|
||||
gl.bind_texture(dst_target, Some(dst));
|
||||
|
||||
if format_info.block_dimensions == (1, 1) {
|
||||
let unpack_data =
|
||||
glow::PixelUnpackData::BufferOffset(copy.buffer_layout.offset as u32);
|
||||
match dst_target {
|
||||
glow::TEXTURE_3D | glow::TEXTURE_2D_ARRAY => {
|
||||
gl.tex_sub_image_3d(
|
||||
dst_target,
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.texture_base.origin.z as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
copy.size.depth_or_array_layers as i32,
|
||||
format_desc.external,
|
||||
format_desc.data_type,
|
||||
unpack_data,
|
||||
);
|
||||
}
|
||||
glow::TEXTURE_2D => {
|
||||
gl.tex_sub_image_2d(
|
||||
dst_target,
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
format_desc.external,
|
||||
format_desc.data_type,
|
||||
unpack_data,
|
||||
);
|
||||
}
|
||||
glow::TEXTURE_CUBE_MAP => {
|
||||
let mut offset = copy.buffer_layout.offset as u32;
|
||||
for face_index in 0..copy.size.depth_or_array_layers {
|
||||
gl.tex_sub_image_2d(
|
||||
CUBEMAP_FACES
|
||||
[(copy.texture_base.origin.z + face_index) as usize],
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
format_desc.external,
|
||||
format_desc.data_type,
|
||||
glow::PixelUnpackData::BufferOffset(offset),
|
||||
);
|
||||
offset += copy
|
||||
.buffer_layout
|
||||
.rows_per_image
|
||||
.map_or(0, |rpi| rpi.get())
|
||||
* copy.buffer_layout.bytes_per_row.map_or(0, |bpr| bpr.get());
|
||||
}
|
||||
}
|
||||
glow::TEXTURE_CUBE_MAP_ARRAY => {
|
||||
//Note: not sure if this is correct!
|
||||
gl.tex_sub_image_3d(
|
||||
dst_target,
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.texture_base.origin.z as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
copy.size.depth_or_array_layers as i32,
|
||||
format_desc.external,
|
||||
format_desc.data_type,
|
||||
unpack_data,
|
||||
);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
let bytes_per_image =
|
||||
copy.buffer_layout.rows_per_image.map_or(1, |rpi| rpi.get())
|
||||
* copy.buffer_layout.bytes_per_row.map_or(1, |bpr| bpr.get());
|
||||
let offset_end = copy.buffer_layout.offset as u32
|
||||
+ bytes_per_image * copy.size.depth_or_array_layers;
|
||||
let unpack_data = glow::CompressedPixelUnpackData::BufferRange(
|
||||
copy.buffer_layout.offset as u32..offset_end,
|
||||
);
|
||||
match dst_target {
|
||||
glow::TEXTURE_3D | glow::TEXTURE_2D_ARRAY => {
|
||||
gl.compressed_tex_sub_image_3d(
|
||||
dst_target,
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.texture_base.origin.z as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
copy.size.depth_or_array_layers as i32,
|
||||
format_desc.internal,
|
||||
unpack_data,
|
||||
);
|
||||
}
|
||||
glow::TEXTURE_2D => {
|
||||
gl.compressed_tex_sub_image_2d(
|
||||
dst_target,
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
format_desc.internal,
|
||||
unpack_data,
|
||||
);
|
||||
}
|
||||
glow::TEXTURE_CUBE_MAP => {
|
||||
let mut offset = copy.buffer_layout.offset as u32;
|
||||
for face_index in 0..copy.size.depth_or_array_layers {
|
||||
gl.compressed_tex_sub_image_2d(
|
||||
CUBEMAP_FACES
|
||||
[(copy.texture_base.origin.z + face_index) as usize],
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
format_desc.internal,
|
||||
glow::CompressedPixelUnpackData::BufferRange(
|
||||
offset..offset + bytes_per_image,
|
||||
),
|
||||
);
|
||||
offset += bytes_per_image;
|
||||
}
|
||||
}
|
||||
glow::TEXTURE_CUBE_MAP_ARRAY => {
|
||||
//Note: not sure if this is correct!
|
||||
gl.compressed_tex_sub_image_3d(
|
||||
dst_target,
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.texture_base.origin.z as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
copy.size.depth_or_array_layers as i32,
|
||||
format_desc.internal,
|
||||
unpack_data,
|
||||
);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
C::CopyTextureToBuffer {
|
||||
src,
|
||||
src_target,
|
||||
src_format,
|
||||
dst,
|
||||
dst_target: _,
|
||||
ref copy,
|
||||
} => {
|
||||
let format_info = src_format.describe();
|
||||
if format_info.block_dimensions != (1, 1) {
|
||||
log::error!("Not implemented yet: compressed texture copy to buffer");
|
||||
return;
|
||||
}
|
||||
if src_target == glow::TEXTURE_CUBE_MAP
|
||||
|| src_target == glow::TEXTURE_CUBE_MAP_ARRAY
|
||||
{
|
||||
log::error!("Not implemented yet: cubemap texture copy to buffer");
|
||||
return;
|
||||
}
|
||||
let format_desc = self.shared.describe_texture_format(src_format);
|
||||
let row_texels = copy
|
||||
.buffer_layout
|
||||
.bytes_per_row
|
||||
.map_or(copy.size.width, |bpr| {
|
||||
bpr.get() / format_info.block_size as u32
|
||||
});
|
||||
let column_texels = copy
|
||||
.buffer_layout
|
||||
.rows_per_image
|
||||
.map_or(copy.size.height, |rpi| rpi.get());
|
||||
gl.pixel_store_i32(glow::PACK_ROW_LENGTH, row_texels as i32);
|
||||
gl.bind_buffer(glow::PIXEL_PACK_BUFFER, Some(dst));
|
||||
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.copy_fbo));
|
||||
for layer in 0..copy.size.depth_or_array_layers {
|
||||
let offset = copy.buffer_layout.offset as u32
|
||||
+ layer * column_texels * row_texels * format_info.block_size as u32;
|
||||
if is_3d_target(src_target) {
|
||||
//TODO: handle GLES without framebuffer_texture_3d
|
||||
gl.framebuffer_texture_layer(
|
||||
glow::READ_FRAMEBUFFER,
|
||||
glow::COLOR_ATTACHMENT0,
|
||||
Some(src),
|
||||
copy.texture_base.mip_level as i32,
|
||||
copy.texture_base.origin.z as i32 + layer as i32,
|
||||
);
|
||||
} else {
|
||||
gl.framebuffer_texture_2d(
|
||||
glow::READ_FRAMEBUFFER,
|
||||
glow::COLOR_ATTACHMENT0,
|
||||
src_target,
|
||||
Some(src),
|
||||
copy.texture_base.mip_level as i32,
|
||||
);
|
||||
}
|
||||
gl.read_pixels(
|
||||
copy.texture_base.origin.x as i32,
|
||||
copy.texture_base.origin.y as i32,
|
||||
copy.size.width as i32,
|
||||
copy.size.height as i32,
|
||||
format_desc.external,
|
||||
format_desc.data_type,
|
||||
glow::PixelPackData::BufferOffset(offset),
|
||||
);
|
||||
}
|
||||
}
|
||||
C::SetIndexBuffer(buffer) => {
|
||||
gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(buffer));
|
||||
}
|
||||
C::BeginQuery(query, target) => {
|
||||
gl.begin_query(target, query);
|
||||
}
|
||||
C::EndQuery(target) => {
|
||||
gl.end_query(target);
|
||||
}
|
||||
C::CopyQueryResults {
|
||||
ref query_range,
|
||||
dst,
|
||||
dst_target,
|
||||
dst_offset,
|
||||
} => {
|
||||
self.temp_query_results.clear();
|
||||
for &query in
|
||||
data_words[query_range.start as usize..query_range.end as usize].iter()
|
||||
{
|
||||
let result = gl.get_query_parameter_u32(query, glow::QUERY_RESULT);
|
||||
self.temp_query_results.push(result as u64);
|
||||
}
|
||||
let query_data = slice::from_raw_parts(
|
||||
self.temp_query_results.as_ptr() as *const u8,
|
||||
self.temp_query_results.len() * mem::size_of::<u64>(),
|
||||
);
|
||||
gl.bind_buffer(dst_target, Some(dst));
|
||||
gl.buffer_sub_data_u8_slice(dst_target, dst_offset as i32, query_data);
|
||||
}
|
||||
C::ResetFramebuffer => {
|
||||
gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.draw_fbo));
|
||||
gl.framebuffer_texture_2d(
|
||||
glow::DRAW_FRAMEBUFFER,
|
||||
glow::DEPTH_STENCIL_ATTACHMENT,
|
||||
glow::TEXTURE_2D,
|
||||
None,
|
||||
0,
|
||||
);
|
||||
for i in 0..crate::MAX_COLOR_TARGETS {
|
||||
let target = glow::COLOR_ATTACHMENT0 + i as u32;
|
||||
gl.framebuffer_texture_2d(
|
||||
glow::DRAW_FRAMEBUFFER,
|
||||
target,
|
||||
glow::TEXTURE_2D,
|
||||
None,
|
||||
0,
|
||||
);
|
||||
}
|
||||
gl.color_mask(true, true, true, true);
|
||||
gl.depth_mask(true);
|
||||
gl.stencil_mask(!0);
|
||||
gl.disable(glow::DEPTH_TEST);
|
||||
gl.disable(glow::STENCIL_TEST);
|
||||
gl.disable(glow::SCISSOR_TEST);
|
||||
}
|
||||
C::BindAttachment {
|
||||
attachment,
|
||||
ref view,
|
||||
} => {
|
||||
self.set_attachment(glow::DRAW_FRAMEBUFFER, attachment, view);
|
||||
}
|
||||
C::ResolveAttachment {
|
||||
attachment,
|
||||
ref dst,
|
||||
ref size,
|
||||
} => {
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.draw_fbo));
|
||||
gl.read_buffer(attachment);
|
||||
gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.copy_fbo));
|
||||
self.set_attachment(glow::DRAW_FRAMEBUFFER, glow::COLOR_ATTACHMENT0, dst);
|
||||
gl.blit_framebuffer(
|
||||
0,
|
||||
0,
|
||||
size.width as i32,
|
||||
size.height as i32,
|
||||
0,
|
||||
0,
|
||||
size.width as i32,
|
||||
size.height as i32,
|
||||
glow::COLOR_BUFFER_BIT,
|
||||
glow::NEAREST,
|
||||
);
|
||||
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None);
|
||||
gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.draw_fbo));
|
||||
}
|
||||
C::InvalidateAttachments(ref list) => {
|
||||
gl.invalidate_framebuffer(glow::DRAW_FRAMEBUFFER, list);
|
||||
}
|
||||
C::SetDrawColorBuffers(count) => {
|
||||
let indices = (0..count as u32)
|
||||
.map(|i| glow::COLOR_ATTACHMENT0 + i)
|
||||
.collect::<ArrayVec<[_; crate::MAX_COLOR_TARGETS]>>();
|
||||
gl.draw_buffers(&indices);
|
||||
for draw_buffer in 0..count as u32 {
|
||||
gl.disable_draw_buffer(glow::BLEND, draw_buffer);
|
||||
}
|
||||
}
|
||||
C::ClearColorF(draw_buffer, ref color) => {
|
||||
gl.clear_buffer_f32_slice(glow::COLOR, draw_buffer, color);
|
||||
}
|
||||
C::ClearColorU(draw_buffer, ref color) => {
|
||||
gl.clear_buffer_u32_slice(glow::COLOR, draw_buffer, color);
|
||||
}
|
||||
C::ClearColorI(draw_buffer, ref color) => {
|
||||
gl.clear_buffer_i32_slice(glow::COLOR, draw_buffer, color);
|
||||
}
|
||||
C::ClearDepth(depth) => {
|
||||
gl.clear_buffer_f32_slice(glow::DEPTH, 0, &[depth]);
|
||||
}
|
||||
C::ClearStencil(value) => {
|
||||
gl.clear_buffer_i32_slice(glow::STENCIL, 0, &[value as i32]);
|
||||
}
|
||||
C::BufferBarrier(raw, usage) => {
|
||||
let mut flags = 0;
|
||||
if usage.contains(crate::BufferUse::VERTEX) {
|
||||
flags |= glow::VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
|
||||
gl.bind_buffer(glow::ARRAY_BUFFER, Some(raw));
|
||||
gl.vertex_attrib_pointer_f32(0, 1, glow::BYTE, true, 0, 0);
|
||||
}
|
||||
if usage.contains(crate::BufferUse::INDEX) {
|
||||
flags |= glow::ELEMENT_ARRAY_BARRIER_BIT;
|
||||
gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(raw));
|
||||
}
|
||||
if usage.contains(crate::BufferUse::UNIFORM) {
|
||||
flags |= glow::UNIFORM_BARRIER_BIT;
|
||||
}
|
||||
if usage.contains(crate::BufferUse::INDIRECT) {
|
||||
flags |= glow::COMMAND_BARRIER_BIT;
|
||||
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(raw));
|
||||
}
|
||||
if usage.contains(crate::BufferUse::COPY_SRC) {
|
||||
flags |= glow::PIXEL_BUFFER_BARRIER_BIT;
|
||||
gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(raw));
|
||||
}
|
||||
if usage.contains(crate::BufferUse::COPY_DST) {
|
||||
flags |= glow::PIXEL_BUFFER_BARRIER_BIT;
|
||||
gl.bind_buffer(glow::PIXEL_PACK_BUFFER, Some(raw));
|
||||
}
|
||||
if usage.intersects(crate::BufferUse::MAP_READ | crate::BufferUse::MAP_WRITE) {
|
||||
flags |= glow::BUFFER_UPDATE_BARRIER_BIT;
|
||||
}
|
||||
if usage
|
||||
.intersects(crate::BufferUse::STORAGE_LOAD | crate::BufferUse::STORAGE_STORE)
|
||||
{
|
||||
flags |= glow::SHADER_STORAGE_BARRIER_BIT;
|
||||
}
|
||||
gl.memory_barrier(flags);
|
||||
}
|
||||
C::TextureBarrier(usage) => {
|
||||
let mut flags = 0;
|
||||
if usage.contains(crate::TextureUse::SAMPLED) {
|
||||
flags |= glow::TEXTURE_FETCH_BARRIER_BIT;
|
||||
}
|
||||
if usage
|
||||
.intersects(crate::TextureUse::STORAGE_LOAD | crate::TextureUse::STORAGE_STORE)
|
||||
{
|
||||
flags |= glow::SHADER_IMAGE_ACCESS_BARRIER_BIT;
|
||||
}
|
||||
if usage.contains(crate::TextureUse::COPY_DST) {
|
||||
flags |= glow::TEXTURE_UPDATE_BARRIER_BIT;
|
||||
}
|
||||
if usage.intersects(
|
||||
crate::TextureUse::COLOR_TARGET
|
||||
| crate::TextureUse::DEPTH_STENCIL_READ
|
||||
| crate::TextureUse::DEPTH_STENCIL_WRITE,
|
||||
) {
|
||||
flags |= glow::FRAMEBUFFER_BARRIER_BIT;
|
||||
}
|
||||
gl.memory_barrier(flags);
|
||||
}
|
||||
C::SetViewport {
|
||||
ref rect,
|
||||
ref depth,
|
||||
} => {
|
||||
gl.viewport(rect.x, rect.y, rect.w, rect.h);
|
||||
gl.depth_range_f32(depth.start, depth.end);
|
||||
}
|
||||
C::SetScissor(ref rect) => {
|
||||
gl.scissor(rect.x, rect.y, rect.w, rect.h);
|
||||
gl.enable(glow::SCISSOR_TEST);
|
||||
}
|
||||
C::SetStencilFunc {
|
||||
face,
|
||||
function,
|
||||
reference,
|
||||
read_mask,
|
||||
} => {
|
||||
gl.stencil_func_separate(face, function, reference as i32, read_mask);
|
||||
}
|
||||
C::SetStencilOps {
|
||||
face,
|
||||
write_mask,
|
||||
ref ops,
|
||||
} => {
|
||||
gl.stencil_mask_separate(face, write_mask);
|
||||
gl.stencil_op_separate(face, ops.fail, ops.depth_fail, ops.pass);
|
||||
}
|
||||
C::SetVertexAttribute {
|
||||
buffer,
|
||||
ref buffer_desc,
|
||||
attribute_desc: ref vat,
|
||||
} => {
|
||||
gl.bind_buffer(glow::ARRAY_BUFFER, buffer);
|
||||
gl.enable_vertex_attrib_array(vat.location);
|
||||
|
||||
if buffer.is_none() {
|
||||
match vat.format_desc.attrib_kind {
|
||||
super::VertexAttribKind::Float => gl.vertex_attrib_format_f32(
|
||||
vat.location,
|
||||
vat.format_desc.element_count,
|
||||
vat.format_desc.element_format,
|
||||
true, // always normalized
|
||||
vat.offset,
|
||||
),
|
||||
super::VertexAttribKind::Integer => gl.vertex_attrib_format_i32(
|
||||
vat.location,
|
||||
vat.format_desc.element_count,
|
||||
vat.format_desc.element_format,
|
||||
vat.offset,
|
||||
),
|
||||
}
|
||||
|
||||
//Note: there is apparently a bug on AMD 3500U:
|
||||
// this call is ignored if the current array is disabled.
|
||||
gl.vertex_attrib_binding(vat.location, vat.buffer_index);
|
||||
} else {
|
||||
match vat.format_desc.attrib_kind {
|
||||
super::VertexAttribKind::Float => gl.vertex_attrib_pointer_f32(
|
||||
vat.location,
|
||||
vat.format_desc.element_count,
|
||||
vat.format_desc.element_format,
|
||||
true, // always normalized
|
||||
buffer_desc.stride as i32,
|
||||
vat.offset as i32,
|
||||
),
|
||||
super::VertexAttribKind::Integer => gl.vertex_attrib_pointer_i32(
|
||||
vat.location,
|
||||
vat.format_desc.element_count,
|
||||
vat.format_desc.element_format,
|
||||
buffer_desc.stride as i32,
|
||||
vat.offset as i32,
|
||||
),
|
||||
}
|
||||
gl.vertex_attrib_divisor(vat.location, buffer_desc.step as u32);
|
||||
}
|
||||
}
|
||||
C::UnsetVertexAttribute(location) => {
|
||||
gl.disable_vertex_attrib_array(location);
|
||||
}
|
||||
C::SetVertexBuffer {
|
||||
index,
|
||||
ref buffer,
|
||||
ref buffer_desc,
|
||||
} => {
|
||||
gl.vertex_binding_divisor(index, buffer_desc.step as u32);
|
||||
gl.bind_vertex_buffer(
|
||||
index,
|
||||
Some(buffer.raw),
|
||||
buffer.offset as i32,
|
||||
buffer_desc.stride as i32,
|
||||
);
|
||||
}
|
||||
C::SetDepth(ref depth) => {
|
||||
gl.depth_func(depth.function);
|
||||
gl.depth_mask(depth.mask);
|
||||
}
|
||||
C::SetDepthBias(bias) => {
|
||||
if bias.is_enabled() {
|
||||
gl.enable(glow::POLYGON_OFFSET_FILL);
|
||||
gl.polygon_offset(bias.constant as f32, bias.slope_scale);
|
||||
} else {
|
||||
gl.disable(glow::POLYGON_OFFSET_FILL);
|
||||
}
|
||||
}
|
||||
C::ConfigureDepthStencil(aspects) => {
|
||||
if aspects.contains(crate::FormatAspect::DEPTH) {
|
||||
gl.enable(glow::DEPTH_TEST);
|
||||
} else {
|
||||
gl.disable(glow::DEPTH_TEST);
|
||||
}
|
||||
if aspects.contains(crate::FormatAspect::STENCIL) {
|
||||
gl.enable(glow::STENCIL_TEST);
|
||||
} else {
|
||||
gl.disable(glow::STENCIL_TEST);
|
||||
}
|
||||
}
|
||||
C::SetProgram(program) => {
|
||||
gl.use_program(Some(program));
|
||||
}
|
||||
C::SetPrimitive(ref state) => {
|
||||
gl.front_face(state.front_face);
|
||||
if state.cull_face != 0 {
|
||||
gl.enable(glow::CULL_FACE);
|
||||
gl.cull_face(state.cull_face);
|
||||
} else {
|
||||
gl.disable(glow::CULL_FACE);
|
||||
}
|
||||
if self.features.contains(wgt::Features::DEPTH_CLAMPING) {
|
||||
if state.clamp_depth {
|
||||
gl.enable(glow::DEPTH_CLAMP);
|
||||
} else {
|
||||
gl.disable(glow::DEPTH_CLAMP);
|
||||
}
|
||||
}
|
||||
}
|
||||
C::SetBlendConstant(c) => {
|
||||
gl.blend_color(c[0], c[1], c[2], c[3]);
|
||||
}
|
||||
C::SetColorTarget {
|
||||
draw_buffer_index,
|
||||
desc: super::ColorTargetDesc { mask, ref blend },
|
||||
} => {
|
||||
use wgt::ColorWrite as Cw;
|
||||
if let Some(index) = draw_buffer_index {
|
||||
gl.color_mask_draw_buffer(
|
||||
index,
|
||||
mask.contains(Cw::RED),
|
||||
mask.contains(Cw::GREEN),
|
||||
mask.contains(Cw::BLUE),
|
||||
mask.contains(Cw::ALPHA),
|
||||
);
|
||||
if let Some(ref blend) = *blend {
|
||||
gl.enable_draw_buffer(index, glow::BLEND);
|
||||
if blend.color != blend.alpha {
|
||||
gl.blend_equation_separate_draw_buffer(
|
||||
index,
|
||||
blend.color.equation,
|
||||
blend.alpha.equation,
|
||||
);
|
||||
gl.blend_func_separate_draw_buffer(
|
||||
index,
|
||||
blend.color.src,
|
||||
blend.color.dst,
|
||||
blend.alpha.src,
|
||||
blend.alpha.dst,
|
||||
);
|
||||
} else {
|
||||
gl.blend_equation_draw_buffer(index, blend.color.equation);
|
||||
gl.blend_func_draw_buffer(index, blend.color.src, blend.color.dst);
|
||||
}
|
||||
} else {
|
||||
gl.disable_draw_buffer(index, glow::BLEND);
|
||||
}
|
||||
} else {
|
||||
gl.color_mask(
|
||||
mask.contains(Cw::RED),
|
||||
mask.contains(Cw::GREEN),
|
||||
mask.contains(Cw::BLUE),
|
||||
mask.contains(Cw::ALPHA),
|
||||
);
|
||||
if let Some(ref blend) = *blend {
|
||||
gl.enable(glow::BLEND);
|
||||
if blend.color != blend.alpha {
|
||||
gl.blend_equation_separate(blend.color.equation, blend.alpha.equation);
|
||||
gl.blend_func_separate(
|
||||
blend.color.src,
|
||||
blend.color.dst,
|
||||
blend.alpha.src,
|
||||
blend.alpha.dst,
|
||||
);
|
||||
} else {
|
||||
gl.blend_equation(blend.color.equation);
|
||||
gl.blend_func(blend.color.src, blend.color.dst);
|
||||
}
|
||||
} else {
|
||||
gl.disable(glow::BLEND);
|
||||
}
|
||||
}
|
||||
}
|
||||
C::BindBuffer {
|
||||
target,
|
||||
slot,
|
||||
buffer,
|
||||
offset,
|
||||
size,
|
||||
} => {
|
||||
gl.bind_buffer_range(target, slot, Some(buffer), offset, size);
|
||||
}
|
||||
C::BindSampler(texture_index, sampler) => {
|
||||
gl.bind_sampler(texture_index, Some(sampler));
|
||||
}
|
||||
C::BindTexture {
|
||||
slot,
|
||||
texture,
|
||||
target,
|
||||
} => {
|
||||
gl.active_texture(glow::TEXTURE0 + slot);
|
||||
gl.bind_texture(target, Some(texture));
|
||||
}
|
||||
C::BindImage { slot, ref binding } => {
|
||||
gl.bind_image_texture(
|
||||
slot,
|
||||
binding.raw,
|
||||
binding.mip_level as i32,
|
||||
binding.array_layer.is_none(),
|
||||
binding.array_layer.unwrap_or_default() as i32,
|
||||
binding.access,
|
||||
binding.format,
|
||||
);
|
||||
}
|
||||
C::InsertDebugMarker(ref range) => {
|
||||
let marker = extract_marker(data_bytes, range);
|
||||
gl.debug_message_insert(
|
||||
glow::DEBUG_SOURCE_APPLICATION,
|
||||
glow::DEBUG_TYPE_MARKER,
|
||||
DEBUG_ID,
|
||||
glow::DEBUG_SEVERITY_NOTIFICATION,
|
||||
marker,
|
||||
);
|
||||
}
|
||||
C::PushDebugGroup(ref range) => {
|
||||
let marker = extract_marker(data_bytes, range);
|
||||
gl.push_debug_group(glow::DEBUG_SOURCE_APPLICATION, DEBUG_ID, marker);
|
||||
}
|
||||
C::PopDebugGroup => {
|
||||
gl.pop_debug_group();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Queue<super::Api> for super::Queue {
|
||||
unsafe fn submit(
|
||||
&mut self,
|
||||
command_buffers: &[&super::CommandBuffer],
|
||||
signal_fence: Option<(&mut super::Fence, crate::FenceValue)>,
|
||||
) -> Result<(), crate::DeviceError> {
|
||||
self.reset_state();
|
||||
for cmd_buf in command_buffers.iter() {
|
||||
for command in cmd_buf.commands.iter() {
|
||||
self.process(command, &cmd_buf.data_bytes, &cmd_buf.data_words);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((fence, value)) = signal_fence {
|
||||
let gl = &self.shared.context;
|
||||
fence.maintain(gl);
|
||||
let sync = gl
|
||||
.fence_sync(glow::SYNC_GPU_COMMANDS_COMPLETE, 0)
|
||||
.map_err(|_| crate::DeviceError::OutOfMemory)?;
|
||||
fence.pending.push((value, sync));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
unsafe fn present(
|
||||
&mut self,
|
||||
surface: &mut super::Surface,
|
||||
texture: super::Texture,
|
||||
) -> Result<(), crate::SurfaceError> {
|
||||
let gl = &self.shared.context;
|
||||
surface.present(texture, gl)
|
||||
}
|
||||
}
|
||||
+25
-2
@@ -45,6 +45,8 @@
|
||||
compile_error!("Metal backend enabled on non-Apple OS. If your project is not using resolver=\"2\" in Cargo.toml, it should.");
|
||||
|
||||
mod empty;
|
||||
#[cfg(feature = "gles")]
|
||||
mod gles;
|
||||
#[cfg(all(feature = "metal", any(target_os = "macos", target_os = "ios")))]
|
||||
mod metal;
|
||||
#[cfg(feature = "vulkan")]
|
||||
@@ -53,6 +55,8 @@ mod vulkan;
|
||||
pub mod util;
|
||||
pub mod api {
|
||||
pub use super::empty::Api as Empty;
|
||||
#[cfg(feature = "gles")]
|
||||
pub use super::gles::Api as Gles;
|
||||
#[cfg(feature = "metal")]
|
||||
pub use super::metal::Api as Metal;
|
||||
#[cfg(feature = "vulkan")]
|
||||
@@ -234,6 +238,7 @@ pub trait Device<A: Api>: Send + Sync {
|
||||
) -> Result<A::CommandEncoder, DeviceError>;
|
||||
unsafe fn destroy_command_encoder(&self, pool: A::CommandEncoder);
|
||||
|
||||
/// Creates a bind group layout.
|
||||
unsafe fn create_bind_group_layout(
|
||||
&self,
|
||||
desc: &BindGroupLayoutDescriptor,
|
||||
@@ -332,6 +337,8 @@ pub trait CommandEncoder<A: Api>: Send + Sync {
|
||||
|
||||
// copy operations
|
||||
|
||||
/// This is valid to call with `value == 0`.
|
||||
/// Otherwise `wgt::Features::CLEAR_COMMANDS` is required.
|
||||
unsafe fn fill_buffer(&mut self, buffer: &A::Buffer, range: MemoryRange, value: u8);
|
||||
|
||||
unsafe fn copy_buffer_to_buffer<T>(&mut self, src: &A::Buffer, dst: &A::Buffer, regions: T)
|
||||
@@ -549,9 +556,12 @@ impl From<wgt::TextureFormat> for FormatAspect {
|
||||
bitflags!(
|
||||
pub struct MemoryFlag: u32 {
|
||||
const TRANSIENT = 1;
|
||||
const PREFER_COHERENT = 2;
|
||||
}
|
||||
);
|
||||
|
||||
//TODO: it's not intuitive for the backends to consider `LOAD` being optional.
|
||||
|
||||
bitflags!(
|
||||
pub struct AttachmentOp: u8 {
|
||||
const LOAD = 1;
|
||||
@@ -621,8 +631,8 @@ pub struct Alignments {
|
||||
/// The alignment of the row pitch of the texture data stored in a buffer that is
|
||||
/// used in a GPU copy operation.
|
||||
pub buffer_copy_pitch: wgt::BufferSize,
|
||||
pub storage_buffer_offset: wgt::BufferSize,
|
||||
pub uniform_buffer_offset: wgt::BufferSize,
|
||||
pub storage_buffer_offset: wgt::BufferSize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -749,6 +759,10 @@ pub struct SamplerDescriptor<'a> {
|
||||
pub border_color: Option<wgt::SamplerBorderColor>,
|
||||
}
|
||||
|
||||
/// BindGroupLayout descriptor.
|
||||
///
|
||||
/// Valid usage:
|
||||
/// - `entries` are sorted by ascending `wgt::BindGroupLayoutEntry::binding`
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BindGroupLayoutDescriptor<'a> {
|
||||
pub label: Label<'a>,
|
||||
@@ -828,7 +842,6 @@ pub struct CommandEncoderDescriptor<'a, A: Api> {
|
||||
}
|
||||
|
||||
/// Naga shader module.
|
||||
#[derive(Debug)]
|
||||
pub struct NagaShader {
|
||||
/// Shader module IR.
|
||||
pub module: naga::Module,
|
||||
@@ -836,6 +849,14 @@ pub struct NagaShader {
|
||||
pub info: naga::valid::ModuleInfo,
|
||||
}
|
||||
|
||||
// Custom implementation avoids the need to generate Debug impl code
|
||||
// for the whole Naga module and info.
|
||||
impl fmt::Debug for NagaShader {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "Naga shader")
|
||||
}
|
||||
}
|
||||
|
||||
/// Shader input.
|
||||
pub enum ShaderInput<'a> {
|
||||
Naga(NagaShader),
|
||||
@@ -1051,6 +1072,8 @@ pub struct DepthStencilAttachment<'a, A: Api> {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RenderPassDescriptor<'a, A: Api> {
|
||||
pub label: Label<'a>,
|
||||
pub extent: wgt::Extent3d,
|
||||
pub sample_count: u32,
|
||||
pub color_attachments: &'a [ColorAttachment<'a, A>],
|
||||
pub depth_stencil_attachment: Option<DepthStencilAttachment<'a, A>>,
|
||||
}
|
||||
|
||||
@@ -215,8 +215,8 @@ impl crate::Adapter<super::Api> for super::Adapter {
|
||||
| Tf::Etc2RgbA1UnormSrgb
|
||||
| Tf::EacRUnorm
|
||||
| Tf::EacRSnorm
|
||||
| Tf::EtcRgUnorm
|
||||
| Tf::EtcRgSnorm => {
|
||||
| Tf::EacRgUnorm
|
||||
| Tf::EacRgSnorm => {
|
||||
if pc.format_eac_etc {
|
||||
Tfc::SAMPLED_LINEAR
|
||||
} else {
|
||||
@@ -880,6 +880,9 @@ impl super::PrivateCapabilities {
|
||||
wgt::DownlevelFlags::COMPARISON_SAMPLERS,
|
||||
self.mutable_comparison_samplers,
|
||||
);
|
||||
downlevel
|
||||
.flags
|
||||
.set(wgt::DownlevelFlags::ANISOTROPIC_FILTERING, true);
|
||||
|
||||
crate::Capabilities {
|
||||
limits: wgt::Limits {
|
||||
@@ -905,8 +908,8 @@ impl super::PrivateCapabilities {
|
||||
alignments: crate::Alignments {
|
||||
buffer_copy_offset: buffer_alignment,
|
||||
buffer_copy_pitch: wgt::BufferSize::new(4).unwrap(),
|
||||
storage_buffer_offset: buffer_alignment,
|
||||
uniform_buffer_offset: buffer_alignment,
|
||||
storage_buffer_offset: buffer_alignment,
|
||||
},
|
||||
downlevel,
|
||||
}
|
||||
@@ -987,8 +990,8 @@ impl super::PrivateCapabilities {
|
||||
Tf::Etc2RgbA1UnormSrgb => ETC2_RGB8A1_sRGB,
|
||||
Tf::EacRUnorm => EAC_R11Unorm,
|
||||
Tf::EacRSnorm => EAC_R11Snorm,
|
||||
Tf::EtcRgUnorm => EAC_RG11Unorm,
|
||||
Tf::EtcRgSnorm => EAC_RG11Snorm,
|
||||
Tf::EacRgUnorm => EAC_RG11Unorm,
|
||||
Tf::EacRgSnorm => EAC_RG11Snorm,
|
||||
Tf::Astc4x4RgbaUnorm => ASTC_4x4_LDR,
|
||||
Tf::Astc4x4RgbaUnormSrgb => ASTC_4x4_sRGB,
|
||||
Tf::Astc5x4RgbaUnorm => ASTC_5x4_LDR,
|
||||
|
||||
@@ -61,10 +61,10 @@ impl super::Device {
|
||||
},
|
||||
};
|
||||
|
||||
let module = &stage.module.raw.module;
|
||||
let module = &stage.module.naga.module;
|
||||
let (source, info) = naga::back::msl::write_string(
|
||||
module,
|
||||
&stage.module.raw.info,
|
||||
&stage.module.naga.info,
|
||||
&layout.naga_options,
|
||||
&pipeline_options,
|
||||
)
|
||||
@@ -140,6 +140,7 @@ impl crate::Device<super::Api> for super::Device {
|
||||
|
||||
let mut options = mtl::MTLResourceOptions::empty();
|
||||
options |= if map_read || map_write {
|
||||
// `crate::MemoryFlag::PREFER_COHERENT` is ignored here
|
||||
mtl::MTLResourceOptions::StorageModeShared
|
||||
} else {
|
||||
mtl::MTLResourceOptions::StorageModePrivate
|
||||
@@ -363,11 +364,8 @@ impl crate::Device<super::Api> for super::Device {
|
||||
&self,
|
||||
desc: &crate::BindGroupLayoutDescriptor,
|
||||
) -> DeviceResult<super::BindGroupLayout> {
|
||||
let mut map = desc.entries.to_vec();
|
||||
map.sort_by_key(|e| e.binding);
|
||||
|
||||
Ok(super::BindGroupLayout {
|
||||
entries: Arc::new(map),
|
||||
entries: Arc::from(desc.entries),
|
||||
})
|
||||
}
|
||||
unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) {}
|
||||
@@ -647,7 +645,7 @@ impl crate::Device<super::Api> for super::Device {
|
||||
shader: crate::ShaderInput,
|
||||
) -> Result<super::ShaderModule, crate::ShaderError> {
|
||||
match shader {
|
||||
crate::ShaderInput::Naga(raw) => Ok(super::ShaderModule { raw }),
|
||||
crate::ShaderInput::Naga(naga) => Ok(super::ShaderModule { naga }),
|
||||
crate::ShaderInput::SpirV(_) => {
|
||||
unreachable!("SPIRV_SHADER_PASSTHROUGH is not enabled for this backend")
|
||||
}
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
/*!
|
||||
# Metal API internals.
|
||||
|
||||
## Pipeline Layout
|
||||
|
||||
In Metal, push constants, vertex buffers, and resources in the bind groups
|
||||
are all placed together in the native resource bindings, which work similarly to D3D11:
|
||||
there are tables of textures, buffers, and samplers.
|
||||
|
||||
We put push constants first (if any) in the table, followed by bind group 0
|
||||
resources, followed by other bind groups. The vertex buffers are bound at the very
|
||||
end of the VS buffer table.
|
||||
|
||||
!*/
|
||||
|
||||
mod adapter;
|
||||
mod command;
|
||||
mod conv;
|
||||
@@ -412,7 +427,7 @@ impl Sampler {
|
||||
#[derive(Debug)]
|
||||
pub struct BindGroupLayout {
|
||||
/// Sorted list of BGL entries.
|
||||
entries: Arc<Vec<wgt::BindGroupLayoutEntry>>,
|
||||
entries: Arc<[wgt::BindGroupLayoutEntry]>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -555,7 +570,7 @@ unsafe impl Sync for BindGroup {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ShaderModule {
|
||||
raw: crate::NagaShader,
|
||||
naga: crate::NagaShader,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
|
||||
@@ -99,7 +99,7 @@ impl PhysicalDeviceFeatures {
|
||||
requested_features.contains(wgt::Features::VERTEX_WRITABLE_STORAGE),
|
||||
)
|
||||
.fragment_stores_and_atomics(
|
||||
downlevel_flags.contains(wgt::DownlevelFlags::STORAGE_IMAGES),
|
||||
downlevel_flags.contains(wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE),
|
||||
)
|
||||
//.shader_image_gather_extended(
|
||||
//.shader_storage_image_extended_formats(
|
||||
@@ -239,7 +239,7 @@ impl PhysicalDeviceFeatures {
|
||||
dl_flags.set(Df::CUBE_ARRAY_TEXTURES, self.core.image_cube_array != 0);
|
||||
dl_flags.set(Df::ANISOTROPIC_FILTERING, self.core.sampler_anisotropy != 0);
|
||||
dl_flags.set(
|
||||
Df::STORAGE_IMAGES,
|
||||
Df::FRAGMENT_WRITABLE_STORAGE,
|
||||
self.core.fragment_stores_and_atomics != 0,
|
||||
);
|
||||
|
||||
@@ -665,6 +665,7 @@ impl super::Instance {
|
||||
alignments: phd_capabilities.to_hal_alignments(),
|
||||
downlevel: wgt::DownlevelCapabilities {
|
||||
flags: downlevel_flags,
|
||||
limits: wgt::DownlevelLimits {},
|
||||
shader_model: wgt::ShaderModel::Sm5, //TODO?
|
||||
},
|
||||
};
|
||||
|
||||
@@ -351,7 +351,11 @@ impl crate::CommandEncoder<super::Api> for super::CommandEncoder {
|
||||
let mut vk_clear_values = ArrayVec::<[vk::ClearValue; super::MAX_TOTAL_ATTACHMENTS]>::new();
|
||||
let mut vk_image_views = ArrayVec::<[vk::ImageView; super::MAX_TOTAL_ATTACHMENTS]>::new();
|
||||
let mut rp_key = super::RenderPassKey::default();
|
||||
let mut fb_key = super::FramebufferKey::default();
|
||||
let mut fb_key = super::FramebufferKey {
|
||||
attachments: ArrayVec::default(),
|
||||
extent: desc.extent,
|
||||
sample_count: desc.sample_count,
|
||||
};
|
||||
let caps = &self.device.private_caps;
|
||||
|
||||
for cat in desc.color_attachments {
|
||||
@@ -366,11 +370,11 @@ impl crate::CommandEncoder<super::Api> for super::CommandEncoder {
|
||||
.as_ref()
|
||||
.map(|target| target.make_attachment_key(crate::AttachmentOp::STORE, caps)),
|
||||
});
|
||||
fb_key.add(cat.target.view);
|
||||
fb_key.attachments.push(cat.target.view.attachment.clone());
|
||||
if let Some(ref at) = cat.resolve_target {
|
||||
vk_clear_values.push(mem::zeroed());
|
||||
vk_image_views.push(at.view.raw);
|
||||
fb_key.add(at.view);
|
||||
fb_key.attachments.push(at.view.attachment.clone());
|
||||
}
|
||||
}
|
||||
if let Some(ref ds) = desc.depth_stencil_attachment {
|
||||
@@ -385,26 +389,26 @@ impl crate::CommandEncoder<super::Api> for super::CommandEncoder {
|
||||
base: ds.target.make_attachment_key(ds.depth_ops, caps),
|
||||
stencil_ops: ds.stencil_ops,
|
||||
});
|
||||
fb_key.add(ds.target.view);
|
||||
fb_key.attachments.push(ds.target.view.attachment.clone());
|
||||
}
|
||||
rp_key.sample_count = fb_key.sample_count;
|
||||
|
||||
let render_area = vk::Rect2D {
|
||||
offset: vk::Offset2D { x: 0, y: 0 },
|
||||
extent: vk::Extent2D {
|
||||
width: fb_key.extent.width,
|
||||
height: fb_key.extent.height,
|
||||
width: desc.extent.width,
|
||||
height: desc.extent.height,
|
||||
},
|
||||
};
|
||||
let vk_viewports = [vk::Viewport {
|
||||
x: 0.0,
|
||||
y: if self.device.private_caps.flip_y_requires_shift {
|
||||
fb_key.extent.height as f32
|
||||
desc.extent.height as f32
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
width: fb_key.extent.width as f32,
|
||||
height: -(fb_key.extent.height as f32),
|
||||
width: desc.extent.width as f32,
|
||||
height: -(desc.extent.height as f32),
|
||||
min_depth: 0.0,
|
||||
max_depth: 1.0,
|
||||
}];
|
||||
|
||||
@@ -76,8 +76,8 @@ impl super::PrivateCapabilities {
|
||||
Tf::Etc2RgbA1UnormSrgb => F::ETC2_R8G8B8A1_SRGB_BLOCK,
|
||||
Tf::EacRUnorm => F::EAC_R11_UNORM_BLOCK,
|
||||
Tf::EacRSnorm => F::EAC_R11_SNORM_BLOCK,
|
||||
Tf::EtcRgUnorm => F::EAC_R11G11_UNORM_BLOCK,
|
||||
Tf::EtcRgSnorm => F::EAC_R11G11_SNORM_BLOCK,
|
||||
Tf::EacRgUnorm => F::EAC_R11G11_UNORM_BLOCK,
|
||||
Tf::EacRgSnorm => F::EAC_R11G11_SNORM_BLOCK,
|
||||
Tf::Astc4x4RgbaUnorm => F::ASTC_4X4_UNORM_BLOCK,
|
||||
Tf::Astc4x4RgbaUnormSrgb => F::ASTC_4X4_SRGB_BLOCK,
|
||||
Tf::Astc5x4RgbaUnorm => F::ASTC_5X4_UNORM_BLOCK,
|
||||
|
||||
@@ -5,7 +5,7 @@ use ash::{extensions::khr, version::DeviceV1_0, vk};
|
||||
use inplace_it::inplace_or_alloc_from_iter;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use std::{borrow::Cow, cmp, collections::hash_map::Entry, ffi::CString, ptr, sync::Arc};
|
||||
use std::{borrow::Cow, collections::hash_map::Entry, ffi::CString, ptr, sync::Arc};
|
||||
|
||||
impl super::DeviceShared {
|
||||
pub(super) unsafe fn set_object_name(
|
||||
@@ -557,6 +557,7 @@ impl crate::Device<super::Api> for super::Device {
|
||||
.intersects(crate::BufferUse::MAP_READ | crate::BufferUse::MAP_WRITE)
|
||||
{
|
||||
let mut flags = gpu_alloc::UsageFlags::HOST_ACCESS;
|
||||
//TODO: find a way to use `crate::MemoryFlag::PREFER_COHERENT`
|
||||
flags.set(
|
||||
gpu_alloc::UsageFlags::DOWNLOAD,
|
||||
desc.usage.contains(crate::BufferUse::MAP_READ),
|
||||
@@ -697,8 +698,6 @@ impl crate::Device<super::Api> for super::Device {
|
||||
dim: desc.dimension,
|
||||
aspects: crate::FormatAspect::from(desc.format),
|
||||
format_info: desc.format.describe(),
|
||||
sample_count: desc.sample_count,
|
||||
size: desc.size,
|
||||
raw_flags,
|
||||
})
|
||||
}
|
||||
@@ -746,19 +745,8 @@ impl crate::Device<super::Api> for super::Device {
|
||||
raw_image_flags: texture.raw_flags,
|
||||
view_format: desc.format,
|
||||
};
|
||||
let sample_count = texture.sample_count;
|
||||
let render_size = wgt::Extent3d {
|
||||
width: cmp::max(1, texture.size.width >> desc.range.base_mip_level),
|
||||
height: cmp::max(1, texture.size.height >> desc.range.base_mip_level),
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
|
||||
Ok(super::TextureView {
|
||||
raw,
|
||||
attachment,
|
||||
sample_count,
|
||||
render_size,
|
||||
})
|
||||
Ok(super::TextureView { raw, attachment })
|
||||
}
|
||||
unsafe fn destroy_texture_view(&self, view: super::TextureView) {
|
||||
if !self.shared.private_caps.imageless_framebuffers {
|
||||
@@ -937,7 +925,7 @@ impl crate::Device<super::Api> for super::Device {
|
||||
Ok(super::BindGroupLayout {
|
||||
raw,
|
||||
desc_count,
|
||||
types,
|
||||
types: types.into_boxed_slice(),
|
||||
})
|
||||
}
|
||||
unsafe fn destroy_bind_group_layout(&self, bg_layout: super::BindGroupLayout) {
|
||||
|
||||
@@ -287,6 +287,18 @@ impl super::Instance {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for super::InstanceShared {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if let Some(du) = self.debug_utils.take() {
|
||||
du.extension
|
||||
.destroy_debug_utils_messenger(du.messenger, None);
|
||||
}
|
||||
self.raw.destroy_instance(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Instance<super::Api> for super::Instance {
|
||||
unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
|
||||
let entry = match ash::Entry::new() {
|
||||
@@ -638,8 +650,6 @@ impl crate::Surface<super::Api> for super::Surface {
|
||||
dim: wgt::TextureDimension::D2,
|
||||
aspects: crate::FormatAspect::COLOR,
|
||||
format_info: sc.config.format.describe(),
|
||||
sample_count: 1,
|
||||
size: sc.config.extent,
|
||||
raw_flags: vk::ImageCreateFlags::empty(),
|
||||
},
|
||||
};
|
||||
|
||||
+24
-20
@@ -1,3 +1,25 @@
|
||||
/*!
|
||||
# Vulkan API internals.
|
||||
|
||||
## Stack memory
|
||||
|
||||
Ash expects slices, which we don't generally have available.
|
||||
We cope with this requirement by the combination of the following ways:
|
||||
- temporarily allocating `Vec` on heap, where overhead is permitted
|
||||
- growing temporary local storage
|
||||
- using `implace_it` on iterators
|
||||
|
||||
## Framebuffers and Render passes
|
||||
|
||||
Render passes are cached on the device and kept forever.
|
||||
|
||||
Framebuffers are also cached on the device, but they are removed when
|
||||
any of the image views (they have) gets removed.
|
||||
If Vulkan supports image-less framebuffers,
|
||||
then the actual views are excluded from the framebuffer key.
|
||||
|
||||
!*/
|
||||
|
||||
mod adapter;
|
||||
mod command;
|
||||
mod conv;
|
||||
@@ -48,7 +70,6 @@ impl crate::Api for Api {
|
||||
|
||||
struct DebugUtils {
|
||||
extension: ext::DebugUtils,
|
||||
#[allow(dead_code)]
|
||||
messenger: vk::DebugUtilsMessengerEXT,
|
||||
}
|
||||
|
||||
@@ -181,26 +202,13 @@ struct FramebufferAttachment {
|
||||
view_format: wgt::TextureFormat,
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, Default, Hash, PartialEq)]
|
||||
#[derive(Clone, Eq, Hash, PartialEq)]
|
||||
struct FramebufferKey {
|
||||
attachments: ArrayVec<[FramebufferAttachment; MAX_TOTAL_ATTACHMENTS]>,
|
||||
extent: wgt::Extent3d,
|
||||
sample_count: u32,
|
||||
}
|
||||
|
||||
impl FramebufferKey {
|
||||
fn add(&mut self, view: &TextureView) {
|
||||
self.extent.width = self.extent.width.max(view.render_size.width);
|
||||
self.extent.height = self.extent.height.max(view.render_size.height);
|
||||
self.extent.depth_or_array_layers = self
|
||||
.extent
|
||||
.depth_or_array_layers
|
||||
.max(view.render_size.depth_or_array_layers);
|
||||
self.sample_count = self.sample_count.max(view.sample_count);
|
||||
self.attachments.push(view.attachment.clone());
|
||||
}
|
||||
}
|
||||
|
||||
struct DeviceShared {
|
||||
raw: ash::Device,
|
||||
instance: Arc<InstanceShared>,
|
||||
@@ -243,8 +251,6 @@ pub struct Texture {
|
||||
dim: wgt::TextureDimension,
|
||||
aspects: crate::FormatAspect,
|
||||
format_info: wgt::TextureFormatInfo,
|
||||
sample_count: u32,
|
||||
size: wgt::Extent3d,
|
||||
raw_flags: vk::ImageCreateFlags,
|
||||
}
|
||||
|
||||
@@ -252,8 +258,6 @@ pub struct Texture {
|
||||
pub struct TextureView {
|
||||
raw: vk::ImageView,
|
||||
attachment: FramebufferAttachment,
|
||||
sample_count: u32,
|
||||
render_size: wgt::Extent3d,
|
||||
}
|
||||
|
||||
impl TextureView {
|
||||
@@ -271,7 +275,7 @@ pub struct Sampler {
|
||||
pub struct BindGroupLayout {
|
||||
raw: vk::DescriptorSetLayout,
|
||||
desc_count: gpu_descriptor::DescriptorTotalCount,
|
||||
types: Vec<(vk::DescriptorType, u32)>,
|
||||
types: Box<[(vk::DescriptorType, u32)]>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -70,7 +70,8 @@ fn print_info_from_adapter(adapter: &wgpu::Adapter, idx: usize) {
|
||||
println!("\tDownlevel Properties:");
|
||||
let wgpu::DownlevelCapabilities {
|
||||
shader_model,
|
||||
flags
|
||||
limits: _,
|
||||
flags,
|
||||
} = downlevel;
|
||||
println!("\t\tShader Model: {:?}", shader_model);
|
||||
for i in 0..(size_of::<wgpu::DownlevelFlags>() * 8) {
|
||||
|
||||
+37
-15
@@ -586,11 +586,24 @@ impl Default for Limits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the sets of additional limits on an adapter,
|
||||
/// which take place when running on downlevel backends.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DownlevelLimits {}
|
||||
|
||||
impl Default for DownlevelLimits {
|
||||
fn default() -> Self {
|
||||
DownlevelLimits {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists various ways the underlying platform does not conform to the WebGPU standard.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DownlevelCapabilities {
|
||||
/// Combined boolean flags.
|
||||
pub flags: DownlevelFlags,
|
||||
/// Additional limits
|
||||
pub limits: DownlevelLimits,
|
||||
/// Which collections of features shaders support. Defined in terms of D3D's shader models.
|
||||
pub shader_model: ShaderModel,
|
||||
}
|
||||
@@ -599,6 +612,7 @@ impl Default for DownlevelCapabilities {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
flags: DownlevelFlags::COMPLIANT,
|
||||
limits: DownlevelLimits::default(),
|
||||
shader_model: ShaderModel::Sm5,
|
||||
}
|
||||
}
|
||||
@@ -609,8 +623,10 @@ impl DownlevelCapabilities {
|
||||
///
|
||||
/// If this returns false, some parts of the API will result in validation errors where they would not normally.
|
||||
/// These parts can be determined by the values in this structure.
|
||||
pub fn is_webgpu_compliant(self) -> bool {
|
||||
self.flags.contains(DownlevelFlags::COMPLIANT) && self.shader_model >= ShaderModel::Sm5
|
||||
pub fn is_webgpu_compliant(&self) -> bool {
|
||||
self.flags.contains(DownlevelFlags::COMPLIANT)
|
||||
&& self.limits == DownlevelLimits::default()
|
||||
&& self.shader_model >= ShaderModel::Sm5
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,24 +635,30 @@ bitflags::bitflags! {
|
||||
pub struct DownlevelFlags: u32 {
|
||||
/// The device supports compiling and using compute shaders.
|
||||
const COMPUTE_SHADERS = 0x0000_0001;
|
||||
/// Supports creating storage images.
|
||||
const STORAGE_IMAGES = 0x0000_0002;
|
||||
/// Supports binding storage buffers and textures to fragment shaders.
|
||||
const FRAGMENT_WRITABLE_STORAGE = 0x0000_0002;
|
||||
/// Supports indirect drawing and dispatching.
|
||||
const INDIRECT_EXECUTION = 0x0000_0004;
|
||||
/// Supports non-zero `base_vertex` parameter to indexed draw calls.
|
||||
const BASE_VERTEX = 0x0000_0008;
|
||||
/// Supports reading from a depth/stencil buffer while using as a read-only depth/stencil attachment.
|
||||
const READ_ONLY_DEPTH_STENCIL = 0x0000_0004;
|
||||
const READ_ONLY_DEPTH_STENCIL = 0x0000_0010;
|
||||
/// Supports:
|
||||
/// - copy_image_to_image
|
||||
/// - copy_buffer_to_image and copy_image_to_buffer with a buffer without a MAP_* usage
|
||||
const DEVICE_LOCAL_IMAGE_COPIES = 0x0000_0008;
|
||||
const DEVICE_LOCAL_IMAGE_COPIES = 0x0000_0020;
|
||||
/// Supports textures with mipmaps which have a non power of two size.
|
||||
const NON_POWER_OF_TWO_MIPMAPPED_TEXTURES = 0x0000_0010;
|
||||
const NON_POWER_OF_TWO_MIPMAPPED_TEXTURES = 0x0000_0040;
|
||||
/// Supports textures that are cube arrays.
|
||||
const CUBE_ARRAY_TEXTURES = 0x0000_0020;
|
||||
const CUBE_ARRAY_TEXTURES = 0x0000_0080;
|
||||
/// Supports comparison samplers.
|
||||
const COMPARISON_SAMPLERS = 0x0000_0040;
|
||||
const COMPARISON_SAMPLERS = 0x0000_0100;
|
||||
/// Supports different blending modes per color target.
|
||||
const INDEPENDENT_BLENDING = 0x0000_0200;
|
||||
/// Supports samplers with anisotropic filtering
|
||||
const ANISOTROPIC_FILTERING = 0x0001_0000;
|
||||
/// All flags are in their compliant state.
|
||||
const COMPLIANT = 0x0000_007F;
|
||||
const COMPLIANT = 0x0000_13FF;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1394,12 +1416,12 @@ pub enum TextureFormat {
|
||||
/// [0, 255] converted to/from float [0, 1] in shader.
|
||||
///
|
||||
/// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
|
||||
EtcRgUnorm = 60,
|
||||
EacRgUnorm = 60,
|
||||
/// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Complex pallet. 8 bit integer R + 8 bit integer G.
|
||||
/// [-127, 127] converted to/from float [-1, 1] in shader.
|
||||
///
|
||||
/// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
|
||||
EtcRgSnorm = 61,
|
||||
EacRgSnorm = 61,
|
||||
/// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Complex pallet. 8 bit integer RGBA.
|
||||
/// [0, 255] converted to/from float [0, 1] in shader.
|
||||
///
|
||||
@@ -1648,8 +1670,8 @@ impl TextureFormat {
|
||||
//Self::Etc2RgbA8UnormSrgb => (etc2, float, srgb, (4, 4), 16, basic),
|
||||
Self::EacRUnorm => (etc2, float, linear, (4, 4), 8, basic),
|
||||
Self::EacRSnorm => (etc2, float, linear, (4, 4), 8, basic),
|
||||
Self::EtcRgUnorm => (etc2, float, linear, (4, 4), 16, basic),
|
||||
Self::EtcRgSnorm => (etc2, float, linear, (4, 4), 16, basic),
|
||||
Self::EacRgUnorm => (etc2, float, linear, (4, 4), 16, basic),
|
||||
Self::EacRgSnorm => (etc2, float, linear, (4, 4), 16, basic),
|
||||
|
||||
// ASTC compressed textures
|
||||
Self::Astc4x4RgbaUnorm => (astc_ldr, float, linear, (4, 4), 16, basic),
|
||||
|
||||
+3
-3
@@ -73,19 +73,19 @@ env_logger = "0.8"
|
||||
|
||||
[dependencies.naga]
|
||||
git = "https://github.com/gfx-rs/naga"
|
||||
rev = "57b325602015ce6445749a4d8ee5d491edc818d7"
|
||||
rev = "68a2efd3c5db62c2c011ccbad84f58be5e539fe3"
|
||||
optional = true
|
||||
|
||||
# used to test all the example shaders
|
||||
[dev-dependencies.naga]
|
||||
git = "https://github.com/gfx-rs/naga"
|
||||
rev = "57b325602015ce6445749a4d8ee5d491edc818d7"
|
||||
rev = "68a2efd3c5db62c2c011ccbad84f58be5e539fe3"
|
||||
features = ["wgsl-in"]
|
||||
|
||||
# used to generate SPIR-V for the Web target
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.naga]
|
||||
git = "https://github.com/gfx-rs/naga"
|
||||
rev = "57b325602015ce6445749a4d8ee5d491edc818d7"
|
||||
rev = "68a2efd3c5db62c2c011ccbad84f58be5e539fe3"
|
||||
features = ["wgsl-in", "spv-out"]
|
||||
|
||||
[[example]]
|
||||
|
||||
@@ -41,8 +41,6 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3<u32>) {
|
||||
var cMassCount : i32 = 0;
|
||||
var cVelCount : i32 = 0;
|
||||
|
||||
var pos : vec2<f32>;
|
||||
var vel : vec2<f32>;
|
||||
var i : u32 = 0u;
|
||||
loop {
|
||||
if (i >= total) {
|
||||
@@ -52,8 +50,8 @@ fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3<u32>) {
|
||||
continue;
|
||||
}
|
||||
|
||||
pos = particlesSrc.particles[i].pos;
|
||||
vel = particlesSrc.particles[i].vel;
|
||||
let pos = particlesSrc.particles[i].pos;
|
||||
let vel = particlesSrc.particles[i].vel;
|
||||
|
||||
if (distance(pos, vPos) < params.rule1Distance) {
|
||||
cMass = cMass + pos;
|
||||
|
||||
@@ -273,12 +273,16 @@ impl framework::Example for Skybox {
|
||||
|
||||
let skybox_format =
|
||||
if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC_LDR) {
|
||||
log::info!("Using ASTC_LDR");
|
||||
wgpu::TextureFormat::Astc4x4RgbaUnormSrgb
|
||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
||||
log::info!("Using ETC2");
|
||||
wgpu::TextureFormat::Etc2RgbUnormSrgb
|
||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
||||
log::info!("Using BC");
|
||||
wgpu::TextureFormat::Bc1RgbaUnormSrgb
|
||||
} else {
|
||||
log::info!("Using plain");
|
||||
wgpu::TextureFormat::Bgra8UnormSrgb
|
||||
};
|
||||
|
||||
|
||||
@@ -42,13 +42,13 @@ pub fn initialize_adapter_from_env(
|
||||
instance: &Instance,
|
||||
backend_bits: BackendBit,
|
||||
) -> Option<Adapter> {
|
||||
let adapters = instance.enumerate_adapters(backend_bits);
|
||||
|
||||
let desired_adapter_name = std::env::var("WGPU_ADAPTER_NAME")
|
||||
.as_deref()
|
||||
.map(str::to_lowercase)
|
||||
.ok()?;
|
||||
|
||||
let adapters = instance.enumerate_adapters(backend_bits);
|
||||
|
||||
let mut chosen_adapter = None;
|
||||
for adapter in adapters {
|
||||
let info = adapter.get_info();
|
||||
|
||||
@@ -66,6 +66,7 @@ pub fn lowest_reasonable_limits() -> Limits {
|
||||
fn lowest_downlevel_properties() -> DownlevelCapabilities {
|
||||
DownlevelCapabilities {
|
||||
flags: wgt::DownlevelFlags::empty(),
|
||||
limits: wgt::DownlevelLimits {},
|
||||
shader_model: wgt::ShaderModel::Sm2,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user