175: API update with naming, formats, and extra fields  r=grovesNL a=kvark



Co-authored-by: Dzmitry Malyshau <kvarkus@gmail.com>
This commit is contained in:
bors[bot]
2019-05-15 07:31:42 +00:00
22 changed files with 654 additions and 527 deletions

View File

@@ -53,10 +53,10 @@ lib-native: Cargo.lock wgpu-native/Cargo.toml $(wildcard wgpu-native/**/*.rs)
lib-remote: Cargo.lock wgpu-remote/Cargo.toml $(wildcard wgpu-native/**/*.rs wgpu-remote/**/*.rs)
cargo build --manifest-path wgpu-remote/Cargo.toml --features $(FEATURE_RUST)
ffi/wgpu.h: wgpu-native/cbindgen.toml $(wildcard wgpu-native/**/*.rs)
ffi/wgpu.h: wgpu-native/cbindgen.toml $(wildcard wgpu-native/src/**/*.rs)
rustup run nightly cbindgen wgpu-native >ffi/wgpu.h
ffi/wgpu-remote.h: wgpu-remote/cbindgen.toml $(wildcard wgpu-native/**/*.rs wgpu-remote/**/*.rs)
ffi/wgpu-remote.h: wgpu-remote/cbindgen.toml $(wildcard wgpu-native/src/**/*.rs wgpu-remote/src/**/*.rs)
rustup run nightly cbindgen wgpu-remote >ffi/wgpu-remote.h
examples-native: lib-native ffi/wgpu.h examples/hello_triangle_c/main.c

View File

@@ -49,7 +49,7 @@ int main() {
.power_preference = WGPUPowerPreference_LowPower,
});
WGPUDeviceId device = wgpu_adapter_create_device(adapter,
WGPUDeviceId device = wgpu_adapter_request_device(adapter,
&(WGPUDeviceDescriptor){
.extensions =
{
@@ -102,7 +102,7 @@ int main() {
.entry_point = "main",
},
.fragment_stage =
(WGPUPipelineStageDescriptor){
&(WGPUPipelineStageDescriptor){
.module = fragment_shader,
.entry_point = "main",
},
@@ -118,24 +118,24 @@ int main() {
.color_states =
&(WGPUColorStateDescriptor){
.format = WGPUTextureFormat_Bgra8Unorm,
.alpha =
.alpha_blend =
(WGPUBlendDescriptor){
.src_factor = WGPUBlendFactor_One,
.dst_factor = WGPUBlendFactor_Zero,
.operation = WGPUBlendOperation_Add,
},
.color =
.color_blend =
(WGPUBlendDescriptor){
.src_factor = WGPUBlendFactor_One,
.dst_factor = WGPUBlendFactor_Zero,
.operation = WGPUBlendOperation_Add,
},
.write_mask = WGPUColorWriteFlags_ALL,
.write_mask = WGPUColorWrite_ALL,
},
.color_states_length = 1,
.depth_stencil_state = NULL,
.vertex_buffer_state =
(WGPUVertexBufferStateDescriptor){
.vertex_input =
(WGPUVertexInputDescriptor){
.index_format = WGPUIndexFormat_Uint16,
.vertex_buffers = NULL,
.vertex_buffers_count = 0,
@@ -194,7 +194,7 @@ int main() {
WGPUSwapChainId swap_chain = wgpu_device_create_swap_chain(device, surface,
&(WGPUSwapChainDescriptor){
.usage = WGPUTextureUsageFlags_OUTPUT_ATTACHMENT,
.usage = WGPUTextureUsage_OUTPUT_ATTACHMENT,
.format = WGPUTextureFormat_Bgra8Unorm,
.width = prev_width,
.height = prev_height,
@@ -210,7 +210,7 @@ int main() {
swap_chain = wgpu_device_create_swap_chain(device, surface,
&(WGPUSwapChainDescriptor){
.usage = WGPUTextureUsageFlags_OUTPUT_ATTACHMENT,
.usage = WGPUTextureUsage_OUTPUT_ATTACHMENT,
.format = WGPUTextureFormat_Bgra8Unorm,
.width = width,
.height = height,

View File

@@ -38,8 +38,13 @@ typedef struct {
bool anisotropic_filtering;
} WGPUExtensions;
typedef struct {
uint32_t max_bind_groups;
} WGPULimits;
typedef struct {
WGPUExtensions extensions;
WGPULimits limits;
} WGPUDeviceDescriptor;
typedef struct {

View File

@@ -15,7 +15,6 @@ typedef enum {
WGPUAddressMode_ClampToEdge = 0,
WGPUAddressMode_Repeat = 1,
WGPUAddressMode_MirrorRepeat = 2,
WGPUAddressMode_ClampToBorderColor = 3,
} WGPUAddressMode;
typedef enum {
@@ -25,6 +24,7 @@ typedef enum {
WGPUBindingType_StorageBuffer = 3,
WGPUBindingType_UniformBufferDynamic = 4,
WGPUBindingType_StorageBufferDynamic = 5,
WGPUBindingType_StorageTexture = 10,
} WGPUBindingType;
typedef enum {
@@ -51,12 +51,6 @@ typedef enum {
WGPUBlendOperation_Max = 4,
} WGPUBlendOperation;
typedef enum {
WGPUBorderColor_TransparentBlack = 0,
WGPUBorderColor_OpaqueBlack = 1,
WGPUBorderColor_OpaqueWhite = 2,
} WGPUBorderColor;
typedef enum {
WGPUBufferMapAsyncStatus_Success,
WGPUBufferMapAsyncStatus_Error,
@@ -202,42 +196,23 @@ typedef enum {
} WGPUTextureViewDimension;
typedef enum {
WGPUVertexFormat_Uchar = 0,
WGPUVertexFormat_Uchar2 = 1,
WGPUVertexFormat_Uchar3 = 2,
WGPUVertexFormat_Uchar4 = 3,
WGPUVertexFormat_Char = 4,
WGPUVertexFormat_Char2 = 5,
WGPUVertexFormat_Char3 = 6,
WGPUVertexFormat_Char4 = 7,
WGPUVertexFormat_UcharNorm = 8,
WGPUVertexFormat_Uchar2Norm = 9,
WGPUVertexFormat_Uchar3Norm = 10,
WGPUVertexFormat_Uchar4Norm = 11,
WGPUVertexFormat_Uchar4NormBgra = 12,
WGPUVertexFormat_CharNorm = 13,
WGPUVertexFormat_Char2Norm = 14,
WGPUVertexFormat_Char3Norm = 15,
WGPUVertexFormat_Char4Norm = 16,
WGPUVertexFormat_Ushort = 17,
WGPUVertexFormat_Ushort2 = 18,
WGPUVertexFormat_Ushort3 = 19,
WGPUVertexFormat_Ushort4 = 20,
WGPUVertexFormat_Short = 21,
WGPUVertexFormat_Short2 = 22,
WGPUVertexFormat_Short3 = 23,
WGPUVertexFormat_Short4 = 24,
WGPUVertexFormat_UshortNorm = 25,
WGPUVertexFormat_Ushort2Norm = 26,
WGPUVertexFormat_Ushort3Norm = 27,
WGPUVertexFormat_Ushort4Norm = 28,
WGPUVertexFormat_ShortNorm = 29,
WGPUVertexFormat_Short2Norm = 30,
WGPUVertexFormat_Short3Norm = 31,
WGPUVertexFormat_Short4Norm = 32,
WGPUVertexFormat_Half = 33,
WGPUVertexFormat_Half2 = 34,
WGPUVertexFormat_Half3 = 35,
WGPUVertexFormat_Half4 = 36,
WGPUVertexFormat_Float = 37,
WGPUVertexFormat_Float2 = 38,
@@ -272,14 +247,21 @@ typedef struct {
bool anisotropic_filtering;
} WGPUExtensions;
typedef struct {
uint32_t max_bind_groups;
} WGPULimits;
typedef struct {
WGPUExtensions extensions;
WGPULimits limits;
} WGPUDeviceDescriptor;
typedef WGPUId WGPUBindGroupId;
typedef WGPUId WGPUBufferId;
typedef uint64_t WGPUBufferAddress;
typedef void (*WGPUBufferMapReadCallback)(WGPUBufferMapAsyncStatus status, const uint8_t *data, uint8_t *userdata);
typedef void (*WGPUBufferMapWriteCallback)(WGPUBufferMapAsyncStatus status, uint8_t *data, uint8_t *userdata);
@@ -288,7 +270,7 @@ typedef WGPUId WGPUCommandBufferId;
typedef struct {
WGPUBufferId buffer;
uint32_t offset;
WGPUBufferAddress offset;
uint32_t row_pitch;
uint32_t image_height;
} WGPUBufferCopyView;
@@ -300,11 +282,12 @@ typedef struct {
float y;
float z;
} WGPUOrigin3d;
#define WGPUOrigin3d_ZERO (WGPUOrigin3d){ .x = 0, .y = 0, .z = 0 }
typedef struct {
WGPUTextureId texture;
uint32_t level;
uint32_t slice;
uint32_t mip_level;
uint32_t array_layer;
WGPUOrigin3d origin;
} WGPUTextureCopyView;
@@ -337,6 +320,7 @@ typedef struct {
typedef struct {
WGPUTextureViewId attachment;
const WGPUTextureViewId *resolve_target;
WGPULoadOp load_op;
WGPUStoreOp store_op;
WGPUColor clear_color;
@@ -358,6 +342,8 @@ typedef struct {
const WGPURenderPassDepthStencilAttachmentDescriptor_TextureViewId *depth_stencil_attachment;
} WGPURenderPassDescriptor;
typedef const char *WGPURawString;
typedef WGPUId WGPUComputePipelineId;
typedef WGPUId WGPUInstanceId;
@@ -366,8 +352,8 @@ typedef WGPUId WGPUBindGroupLayoutId;
typedef struct {
WGPUBufferId buffer;
uint32_t offset;
uint32_t size;
WGPUBufferAddress offset;
WGPUBufferAddress size;
} WGPUBufferBinding;
typedef WGPUId WGPUSamplerId;
@@ -402,22 +388,23 @@ typedef struct {
typedef struct {
uint32_t binding;
WGPUBindingResource resource;
} WGPUBinding;
} WGPUBindGroupBinding;
typedef struct {
WGPUBindGroupLayoutId layout;
const WGPUBinding *bindings;
const WGPUBindGroupBinding *bindings;
uintptr_t bindings_length;
} WGPUBindGroupDescriptor;
typedef uint32_t WGPUShaderStageFlags;
#define WGPUShaderStageFlags_VERTEX 1
#define WGPUShaderStageFlags_FRAGMENT 2
#define WGPUShaderStageFlags_COMPUTE 4
typedef uint32_t WGPUShaderStage;
#define WGPUShaderStage_NONE 0
#define WGPUShaderStage_VERTEX 1
#define WGPUShaderStage_FRAGMENT 2
#define WGPUShaderStage_COMPUTE 4
typedef struct {
uint32_t binding;
WGPUShaderStageFlags visibility;
WGPUShaderStage visibility;
WGPUBindingType ty;
} WGPUBindGroupLayoutBinding;
@@ -426,21 +413,21 @@ typedef struct {
uintptr_t bindings_length;
} WGPUBindGroupLayoutDescriptor;
typedef uint32_t WGPUBufferUsageFlags;
#define WGPUBufferUsageFlags_MAP_READ 1
#define WGPUBufferUsageFlags_MAP_WRITE 2
#define WGPUBufferUsageFlags_TRANSFER_SRC 4
#define WGPUBufferUsageFlags_TRANSFER_DST 8
#define WGPUBufferUsageFlags_INDEX 16
#define WGPUBufferUsageFlags_VERTEX 32
#define WGPUBufferUsageFlags_UNIFORM 64
#define WGPUBufferUsageFlags_STORAGE 128
#define WGPUBufferUsageFlags_NONE 0
#define WGPUBufferUsageFlags_WRITE_ALL 2 + 8 + 128
typedef uint32_t WGPUBufferUsage;
#define WGPUBufferUsage_MAP_READ 1
#define WGPUBufferUsage_MAP_WRITE 2
#define WGPUBufferUsage_TRANSFER_SRC 4
#define WGPUBufferUsage_TRANSFER_DST 8
#define WGPUBufferUsage_INDEX 16
#define WGPUBufferUsage_VERTEX 32
#define WGPUBufferUsage_UNIFORM 64
#define WGPUBufferUsage_STORAGE 128
#define WGPUBufferUsage_NONE 0
#define WGPUBufferUsage_WRITE_ALL 2 + 8 + 128
typedef struct {
uint32_t size;
WGPUBufferUsageFlags usage;
WGPUBufferAddress size;
WGPUBufferUsage usage;
} WGPUBufferDescriptor;
typedef struct {
@@ -453,7 +440,7 @@ typedef WGPUId WGPUShaderModuleId;
typedef struct {
WGPUShaderModuleId module;
const char *entry_point;
WGPURawString entry_point;
} WGPUPipelineStageDescriptor;
typedef struct {
@@ -482,19 +469,19 @@ typedef struct {
WGPUBlendOperation operation;
} WGPUBlendDescriptor;
typedef uint32_t WGPUColorWriteFlags;
#define WGPUColorWriteFlags_RED 1
#define WGPUColorWriteFlags_GREEN 2
#define WGPUColorWriteFlags_BLUE 4
#define WGPUColorWriteFlags_ALPHA 8
#define WGPUColorWriteFlags_COLOR 7
#define WGPUColorWriteFlags_ALL 15
typedef uint32_t WGPUColorWrite;
#define WGPUColorWrite_RED 1
#define WGPUColorWrite_GREEN 2
#define WGPUColorWrite_BLUE 4
#define WGPUColorWrite_ALPHA 8
#define WGPUColorWrite_COLOR 7
#define WGPUColorWrite_ALL 15
typedef struct {
WGPUTextureFormat format;
WGPUBlendDescriptor alpha;
WGPUBlendDescriptor color;
WGPUColorWriteFlags write_mask;
WGPUBlendDescriptor alpha_blend;
WGPUBlendDescriptor color_blend;
WGPUColorWrite write_mask;
} WGPUColorStateDescriptor;
typedef struct {
@@ -514,16 +501,16 @@ typedef struct {
uint32_t stencil_write_mask;
} WGPUDepthStencilStateDescriptor;
typedef uint32_t WGPUShaderAttributeIndex;
typedef uint32_t WGPUShaderLocation;
typedef struct {
uint32_t offset;
WGPUBufferAddress offset;
WGPUVertexFormat format;
WGPUShaderAttributeIndex attribute_index;
WGPUShaderLocation shader_location;
} WGPUVertexAttributeDescriptor;
typedef struct {
uint32_t stride;
WGPUBufferAddress stride;
WGPUInputStepMode step_mode;
const WGPUVertexAttributeDescriptor *attributes;
uintptr_t attributes_count;
@@ -533,33 +520,31 @@ typedef struct {
WGPUIndexFormat index_format;
const WGPUVertexBufferDescriptor *vertex_buffers;
uintptr_t vertex_buffers_count;
} WGPUVertexBufferStateDescriptor;
} WGPUVertexInputDescriptor;
typedef struct {
WGPUPipelineLayoutId layout;
WGPUPipelineStageDescriptor vertex_stage;
WGPUPipelineStageDescriptor fragment_stage;
const WGPUPipelineStageDescriptor *fragment_stage;
WGPUPrimitiveTopology primitive_topology;
WGPURasterizationStateDescriptor rasterization_state;
const WGPUColorStateDescriptor *color_states;
uintptr_t color_states_length;
const WGPUDepthStencilStateDescriptor *depth_stencil_state;
WGPUVertexBufferStateDescriptor vertex_buffer_state;
WGPUVertexInputDescriptor vertex_input;
uint32_t sample_count;
} WGPURenderPipelineDescriptor;
typedef struct {
WGPUAddressMode r_address_mode;
WGPUAddressMode s_address_mode;
WGPUAddressMode t_address_mode;
WGPUAddressMode address_mode_u;
WGPUAddressMode address_mode_v;
WGPUAddressMode address_mode_w;
WGPUFilterMode mag_filter;
WGPUFilterMode min_filter;
WGPUFilterMode mipmap_filter;
float lod_min_clamp;
float lod_max_clamp;
uint32_t max_anisotropy;
WGPUCompareFunction compare_function;
WGPUBorderColor border_color;
} WGPUSamplerDescriptor;
typedef struct {
@@ -575,18 +560,18 @@ typedef WGPUId WGPUSurfaceId;
typedef WGPUSurfaceId WGPUSwapChainId;
typedef uint32_t WGPUTextureUsageFlags;
#define WGPUTextureUsageFlags_TRANSFER_SRC 1
#define WGPUTextureUsageFlags_TRANSFER_DST 2
#define WGPUTextureUsageFlags_SAMPLED 4
#define WGPUTextureUsageFlags_STORAGE 8
#define WGPUTextureUsageFlags_OUTPUT_ATTACHMENT 16
#define WGPUTextureUsageFlags_NONE 0
#define WGPUTextureUsageFlags_WRITE_ALL 2 + 8 + 16
#define WGPUTextureUsageFlags_UNINITIALIZED 65535
typedef uint32_t WGPUTextureUsage;
#define WGPUTextureUsage_TRANSFER_SRC 1
#define WGPUTextureUsage_TRANSFER_DST 2
#define WGPUTextureUsage_SAMPLED 4
#define WGPUTextureUsage_STORAGE 8
#define WGPUTextureUsage_OUTPUT_ATTACHMENT 16
#define WGPUTextureUsage_NONE 0
#define WGPUTextureUsage_WRITE_ALL 2 + 8 + 16
#define WGPUTextureUsage_UNINITIALIZED 65535
typedef struct {
WGPUTextureUsageFlags usage;
WGPUTextureUsage usage;
WGPUTextureFormat format;
uint32_t width;
uint32_t height;
@@ -594,10 +579,12 @@ typedef struct {
typedef struct {
WGPUExtent3d size;
uint32_t array_size;
uint32_t array_layer_count;
uint32_t mip_level_count;
uint32_t sample_count;
WGPUTextureDimension dimension;
WGPUTextureFormat format;
WGPUTextureUsageFlags usage;
WGPUTextureUsage usage;
} WGPUTextureDescriptor;
typedef WGPUDeviceId WGPUQueueId;
@@ -631,7 +618,8 @@ typedef struct {
#if defined(WGPU_LOCAL)
WGPUDeviceId wgpu_adapter_create_device(WGPUAdapterId adapter_id, const WGPUDeviceDescriptor *desc);
WGPUDeviceId wgpu_adapter_request_device(WGPUAdapterId adapter_id,
const WGPUDeviceDescriptor *desc);
#endif
void wgpu_bind_group_destroy(WGPUBindGroupId bind_group_id);
@@ -639,14 +627,14 @@ void wgpu_bind_group_destroy(WGPUBindGroupId bind_group_id);
void wgpu_buffer_destroy(WGPUBufferId buffer_id);
void wgpu_buffer_map_read_async(WGPUBufferId buffer_id,
uint32_t start,
uint32_t size,
WGPUBufferAddress start,
WGPUBufferAddress size,
WGPUBufferMapReadCallback callback,
uint8_t *userdata);
void wgpu_buffer_map_write_async(WGPUBufferId buffer_id,
uint32_t start,
uint32_t size,
WGPUBufferAddress start,
WGPUBufferAddress size,
WGPUBufferMapWriteCallback callback,
uint8_t *userdata);
@@ -654,10 +642,10 @@ void wgpu_buffer_unmap(WGPUBufferId buffer_id);
void wgpu_command_buffer_copy_buffer_to_buffer(WGPUCommandBufferId command_buffer_id,
WGPUBufferId src,
uint32_t src_offset,
WGPUBufferAddress src_offset,
WGPUBufferId dst,
uint32_t dst_offset,
uint32_t size);
WGPUBufferAddress dst_offset,
WGPUBufferAddress size);
void wgpu_command_buffer_copy_buffer_to_texture(WGPUCommandBufferId command_buffer_id,
const WGPUBufferCopyView *source,
@@ -689,6 +677,12 @@ void wgpu_compute_pass_dispatch(WGPUComputePassId pass_id, uint32_t x, uint32_t
WGPUCommandBufferId wgpu_compute_pass_end_pass(WGPUComputePassId pass_id);
void wgpu_compute_pass_insert_debug_marker(WGPUComputePassId _pass_id, WGPURawString _label);
void wgpu_compute_pass_pop_debug_group(WGPUComputePassId _pass_id);
void wgpu_compute_pass_push_debug_group(WGPUComputePassId _pass_id, WGPURawString _label);
void wgpu_compute_pass_set_bind_group(WGPUComputePassId pass_id,
uint32_t index,
WGPUBindGroupId bind_group_id,
@@ -807,6 +801,12 @@ void wgpu_render_pass_draw_indexed(WGPURenderPassId pass_id,
WGPUCommandBufferId wgpu_render_pass_end_pass(WGPURenderPassId pass_id);
void wgpu_render_pass_insert_debug_marker(WGPURenderPassId _pass_id, WGPURawString _label);
void wgpu_render_pass_pop_debug_group(WGPURenderPassId _pass_id);
void wgpu_render_pass_push_debug_group(WGPURenderPassId _pass_id, WGPURawString _label);
void wgpu_render_pass_set_bind_group(WGPURenderPassId pass_id,
uint32_t index,
WGPUBindGroupId bind_group_id,
@@ -817,7 +817,7 @@ void wgpu_render_pass_set_blend_color(WGPURenderPassId pass_id, const WGPUColor
void wgpu_render_pass_set_index_buffer(WGPURenderPassId pass_id,
WGPUBufferId buffer_id,
uint32_t offset);
WGPUBufferAddress offset);
void wgpu_render_pass_set_pipeline(WGPURenderPassId pass_id, WGPURenderPipelineId pipeline_id);
@@ -827,11 +827,21 @@ void wgpu_render_pass_set_scissor_rect(WGPURenderPassId pass_id,
uint32_t w,
uint32_t h);
void wgpu_render_pass_set_stencil_reference(WGPURenderPassId pass_id, uint32_t value);
void wgpu_render_pass_set_vertex_buffers(WGPURenderPassId pass_id,
const WGPUBufferId *buffer_ptr,
const uint32_t *offset_ptr,
uintptr_t count);
void wgpu_render_pass_set_viewport(WGPURenderPassId pass_id,
float x,
float y,
float w,
float h,
float min_depth,
float max_depth);
WGPUSwapChainOutput wgpu_swap_chain_get_next_texture(WGPUSwapChainId swap_chain_id);
void wgpu_swap_chain_present(WGPUSwapChainId swap_chain_id);

View File

@@ -1,4 +1,12 @@
use crate::{track::TrackerSet, BindGroupLayoutId, BufferId, LifeGuard, SamplerId, TextureViewId};
use crate::{
track::TrackerSet,
BindGroupLayoutId,
BufferAddress,
BufferId,
LifeGuard,
SamplerId,
TextureViewId,
};
use arrayvec::ArrayVec;
use bitflags::bitflags;
@@ -7,7 +15,8 @@ pub const MAX_BIND_GROUPS: usize = 4;
bitflags! {
#[repr(transparent)]
pub struct ShaderStageFlags: u32 {
pub struct ShaderStage: u32 {
const NONE = 0;
const VERTEX = 1;
const FRAGMENT = 2;
const COMPUTE = 4;
@@ -23,13 +32,14 @@ pub enum BindingType {
StorageBuffer = 3,
UniformBufferDynamic = 4,
StorageBufferDynamic = 5,
StorageTexture = 10,
}
#[repr(C)]
#[derive(Clone, Debug, Hash)]
pub struct BindGroupLayoutBinding {
pub binding: u32,
pub visibility: ShaderStageFlags,
pub visibility: ShaderStage,
pub ty: BindingType,
}
@@ -59,8 +69,8 @@ pub struct PipelineLayout<B: hal::Backend> {
#[repr(C)]
pub struct BufferBinding {
pub buffer: BufferId,
pub offset: u32,
pub size: u32,
pub offset: BufferAddress,
pub size: BufferAddress,
}
#[repr(C)]
@@ -71,7 +81,7 @@ pub enum BindingResource {
}
#[repr(C)]
pub struct Binding {
pub struct BindGroupBinding {
pub binding: u32,
pub resource: BindingResource,
}
@@ -79,7 +89,7 @@ pub struct Binding {
#[repr(C)]
pub struct BindGroupDescriptor {
pub layout: BindGroupLayoutId,
pub bindings: *const Binding,
pub bindings: *const BindGroupBinding,
pub bindings_length: usize,
}

View File

@@ -109,7 +109,7 @@ impl<B: hal::Backend> CommandAllocator<B> {
pub fn maintain(&self, last_done: SubmissionIndex) {
let mut inner = self.inner.lock();
for i in (0..inner.pending.len()).rev() {
for i in (0 .. inner.pending.len()).rev() {
let index = inner.pending[i]
.life_guard
.submission_index

View File

@@ -46,7 +46,12 @@ pub struct BindGroupEntry {
}
impl BindGroupEntry {
fn provide(&mut self, bind_group_id: BindGroupId, bind_group: &BindGroupHandle, offsets: &[u32]) -> Provision {
fn provide(
&mut self,
bind_group_id: BindGroupId,
bind_group: &BindGroupHandle,
offsets: &[u32],
) -> Provision {
let was_compatible = match self.provided {
Some(BindGroupPair {
layout_id,
@@ -120,7 +125,7 @@ pub struct Binder {
impl Binder {
pub(crate) fn reset_expectations(&mut self, length: usize) {
for entry in self.entries[length..].iter_mut() {
for entry in self.entries[length ..].iter_mut() {
entry.expected_layout_id = None;
}
}
@@ -148,7 +153,7 @@ impl Binder {
None
}
Provision::Changed { was_compatible, .. } => {
if self.entries[..index].iter().all(|entry| entry.is_valid()) {
if self.entries[.. index].iter().all(|entry| entry.is_valid()) {
self.pipeline_layout_id.map(move |pipeline_layout_id| {
let end = if was_compatible {
trace!("\t\tgenerating follow-up sequence");
@@ -159,7 +164,7 @@ impl Binder {
(
pipeline_layout_id,
TakeSome {
iter: self.entries[index + 1..end]
iter: self.entries[index + 1 .. end]
.iter()
.map(|entry| entry.actual_value()),
},

View File

@@ -7,6 +7,7 @@ use crate::{
CommandBufferId,
ComputePassId,
ComputePipelineId,
RawString,
Stored,
};
@@ -14,7 +15,6 @@ use hal::{self, command::RawCommandBuffer};
use std::{iter, slice};
pub struct ComputePass<B: hal::Backend> {
raw: B::CommandBuffer,
cmb_id: Stored<CommandBufferId>,
@@ -33,6 +33,8 @@ impl<B: hal::Backend> ComputePass<B> {
}
}
// Common routines between render/compute
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) -> CommandBufferId {
let mut command_buffer_guard = HUB.command_buffers.write();
@@ -46,13 +48,6 @@ pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) -> CommandB
pass.cmb_id.value
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) {
unsafe {
HUB.compute_passes.write()[pass_id].raw.dispatch([x, y, z]);
}
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_set_bind_group(
pass_id: ComputePassId,
@@ -68,9 +63,7 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group(
assert_eq!(bind_group.dynamic_count, offsets_count);
let offsets = if offsets_count != 0 {
unsafe {
slice::from_raw_parts(offsets_ptr, offsets_count)
}
unsafe { slice::from_raw_parts(offsets_ptr, offsets_count) }
} else {
&[]
};
@@ -105,6 +98,33 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group(
};
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_push_debug_group(_pass_id: ComputePassId, _label: RawString) {
//TODO
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_pop_debug_group(_pass_id: ComputePassId) {
//TODO
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_insert_debug_marker(
_pass_id: ComputePassId,
_label: RawString,
) {
//TODO
}
// Compute-specific routines
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) {
unsafe {
HUB.compute_passes.write()[pass_id].raw.dispatch([x, y, z]);
}
}
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_set_pipeline(
pass_id: ComputePassId,

View File

@@ -23,8 +23,8 @@ use crate::{
resource::TexturePlacement,
swap_chain::{SwapChainLink, SwapImageEpoch},
track::{DummyUsage, Stitch, TrackerSet},
BufferId,
BufferHandle,
BufferId,
Color,
CommandBufferHandle,
CommandBufferId,
@@ -34,7 +34,7 @@ use crate::{
Stored,
TextureHandle,
TextureId,
TextureUsageFlags,
TextureUsage,
TextureViewId,
};
#[cfg(feature = "local")]
@@ -62,6 +62,7 @@ pub enum StoreOp {
#[repr(C)]
pub struct RenderPassColorAttachmentDescriptor<T> {
pub attachment: T,
pub resolve_target: *const TextureViewId,
pub load_op: LoadOp,
pub store_op: StoreOp,
pub clear_color: Color,
@@ -112,9 +113,9 @@ impl CommandBufferHandle {
trace!("transit buffer {:?} {:?}", id, transit);
hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(transit.start)
..conv::map_buffer_state(transit.end),
.. conv::map_buffer_state(transit.end),
target: &b.raw,
range: None..None,
range: None .. None,
families: None,
}
});
@@ -127,7 +128,7 @@ impl CommandBufferHandle {
let aspects = t.full_range.aspects;
hal::memory::Barrier::Image {
states: conv::map_texture_state(transit.start, aspects)
..conv::map_texture_state(transit.end, aspects),
.. conv::map_texture_state(transit.end, aspects),
target: &t.raw,
range: t.full_range.clone(), //TODO?
families: None,
@@ -138,7 +139,7 @@ impl CommandBufferHandle {
let stages = all_buffer_stages() | all_image_stages();
unsafe {
raw.pipeline_barrier(
stages..stages,
stages .. stages,
hal::memory::Dependencies::empty(),
buffer_barriers.chain(texture_barriers),
);
@@ -202,7 +203,7 @@ pub fn command_encoder_begin_render_pass(
let query = trackers.textures.query(
view.texture_id.value,
&view.texture_id.ref_count,
TextureUsageFlags::empty(),
TextureUsage::empty(),
);
let (_, layout) = conv::map_texture_state(
query.usage,
@@ -213,7 +214,7 @@ pub fn command_encoder_begin_render_pass(
samples: view.samples,
ops: conv::map_load_store_ops(at.depth_load_op, at.depth_store_op),
stencil_ops: conv::map_load_store_ops(at.stencil_load_op, at.stencil_store_op),
layouts: layout..layout,
layouts: layout .. layout,
}
});
@@ -243,7 +244,7 @@ pub fn command_encoder_begin_render_pass(
let query = trackers.textures.query(
view.texture_id.value,
&view.texture_id.ref_count,
TextureUsageFlags::empty(),
TextureUsage::empty(),
);
let (_, layout) = conv::map_texture_state(query.usage, hal::format::Aspects::COLOR);
hal::pass::Attachment {
@@ -251,7 +252,7 @@ pub fn command_encoder_begin_render_pass(
samples: view.samples,
ops: conv::map_load_store_ops(at.load_op, at.store_op),
stencil_ops: hal::pass::AttachmentOps::DONT_CARE,
layouts: layout..layout,
layouts: layout .. layout,
}
});
@@ -277,7 +278,7 @@ pub fn command_encoder_begin_render_pass(
);
let subpass = hal::pass::SubpassDesc {
colors: &color_ids[..color_attachments.len()],
colors: &color_ids[.. color_attachments.len()],
depth_stencil: depth_stencil_attachment.map(|_| &depth_id),
inputs: &[],
resolves: &[],
@@ -351,7 +352,7 @@ pub fn command_encoder_begin_render_pass(
0,
iter::once(hal::pso::Viewport {
rect,
depth: 0.0..1.0,
depth: 0.0 .. 1.0,
}),
);
}

View File

@@ -4,13 +4,15 @@ use crate::{
device::RenderPassContext,
hub::HUB,
pipeline::{IndexFormat, PipelineFlags},
resource::BufferUsageFlags,
resource::BufferUsage,
track::{Stitch, TrackerSet},
BindGroupId,
BufferAddress,
BufferId,
Color,
CommandBuffer,
CommandBufferId,
RawString,
RenderPassId,
RenderPipelineId,
Stored,
@@ -21,15 +23,24 @@ use hal::command::RawCommandBuffer;
use std::{iter, slice};
#[derive(Debug, PartialEq)]
enum BlendColorStatus {
enum OptionalState {
Unused,
Required,
Set,
}
impl OptionalState {
fn require(&mut self, require: bool) {
if require && *self == OptionalState::Unused {
*self = OptionalState::Required;
}
}
}
#[derive(Debug, PartialEq)]
enum DrawError {
MissingBlendColor,
MissingStencilReference,
IncompatibleBindGroup {
index: u32,
//expected: BindGroupLayoutId,
@@ -39,7 +50,7 @@ enum DrawError {
#[derive(Debug)]
pub struct IndexState {
pub(crate) bound_buffer_view: Option<(BufferId, u32)>,
pub(crate) bound_buffer_view: Option<(BufferId, BufferAddress)>,
pub(crate) format: IndexFormat,
}
@@ -49,7 +60,8 @@ pub struct RenderPass<B: hal::Backend> {
context: RenderPassContext,
binder: Binder,
trackers: TrackerSet,
blend_color_status: BlendColorStatus,
blend_color_status: OptionalState,
stencil_reference_status: OptionalState,
index_state: IndexState,
}
@@ -66,7 +78,8 @@ impl<B: hal::Backend> RenderPass<B> {
context,
binder: Binder::default(),
trackers: TrackerSet::new(),
blend_color_status: BlendColorStatus::Unused,
blend_color_status: OptionalState::Unused,
stencil_reference_status: OptionalState::Unused,
index_state,
}
}
@@ -80,13 +93,18 @@ impl<B: hal::Backend> RenderPass<B> {
index: bind_mask.trailing_zeros() as u32,
});
}
if self.blend_color_status == BlendColorStatus::Required {
if self.blend_color_status == OptionalState::Required {
return Err(DrawError::MissingBlendColor);
}
if self.stencil_reference_status == OptionalState::Required {
return Err(DrawError::MissingStencilReference);
}
Ok(())
}
}
// Common routines between render/compute
#[no_mangle]
pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) -> CommandBufferId {
let mut cmb_guard = HUB.command_buffers.write();
@@ -117,11 +135,68 @@ pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) -> CommandBuf
pass.cmb_id.value
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_bind_group(
pass_id: RenderPassId,
index: u32,
bind_group_id: BindGroupId,
offsets_ptr: *const u32,
offsets_count: usize,
) {
let mut pass_guard = HUB.render_passes.write();
let pass = &mut pass_guard[pass_id];
let bind_group_guard = HUB.bind_groups.read();
let bind_group = &bind_group_guard[bind_group_id];
assert_eq!(bind_group.dynamic_count, offsets_count);
let offsets = if offsets_count != 0 {
unsafe { slice::from_raw_parts(offsets_ptr, offsets_count) }
} else {
&[]
};
pass.trackers.consume_by_extend(&bind_group.used);
if let Some((pipeline_layout_id, follow_up)) =
pass.binder
.provide_entry(index as usize, bind_group_id, bind_group, offsets)
{
let pipeline_layout_guard = HUB.pipeline_layouts.read();
let bind_groups =
iter::once(&bind_group.raw).chain(follow_up.map(|bg_id| &bind_group_guard[bg_id].raw));
unsafe {
pass.raw.bind_graphics_descriptor_sets(
&&pipeline_layout_guard[pipeline_layout_id].raw,
index as usize,
bind_groups,
offsets,
);
}
};
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_push_debug_group(_pass_id: RenderPassId, _label: RawString) {
//TODO
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_pop_debug_group(_pass_id: RenderPassId) {
//TODO
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_insert_debug_marker(_pass_id: RenderPassId, _label: RawString) {
//TODO
}
// Render-specific routines
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_index_buffer(
pass_id: RenderPassId,
buffer_id: BufferId,
offset: u32,
offset: BufferAddress,
) {
let mut pass_guard = HUB.render_passes.write();
let buffer_guard = HUB.buffers.read();
@@ -130,12 +205,12 @@ pub extern "C" fn wgpu_render_pass_set_index_buffer(
let buffer = pass
.trackers
.buffers
.get_with_extended_usage(&*buffer_guard, buffer_id, BufferUsageFlags::INDEX)
.get_with_extended_usage(&*buffer_guard, buffer_id, BufferUsage::INDEX)
.unwrap();
let view = hal::buffer::IndexBufferView {
buffer: &buffer.raw,
offset: offset as u64,
offset,
index_type: conv::map_index_format(pass.index_state.format),
};
@@ -162,7 +237,7 @@ pub extern "C" fn wgpu_render_pass_set_vertex_buffers(
for &id in buffers {
pass.trackers
.buffers
.get_with_extended_usage(&*buffer_guard, id, BufferUsageFlags::VERTEX)
.get_with_extended_usage(&*buffer_guard, id, BufferUsage::VERTEX)
.unwrap();
}
@@ -190,8 +265,8 @@ pub extern "C" fn wgpu_render_pass_draw(
unsafe {
pass.raw.draw(
first_vertex..first_vertex + vertex_count,
first_instance..first_instance + instance_count,
first_vertex .. first_vertex + vertex_count,
first_instance .. first_instance + instance_count,
);
}
}
@@ -211,55 +286,13 @@ pub extern "C" fn wgpu_render_pass_draw_indexed(
unsafe {
pass.raw.draw_indexed(
first_index..first_index + index_count,
first_index .. first_index + index_count,
base_vertex,
first_instance..first_instance + instance_count,
first_instance .. first_instance + instance_count,
);
}
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_bind_group(
pass_id: RenderPassId,
index: u32,
bind_group_id: BindGroupId,
offsets_ptr: *const u32,
offsets_count: usize,
) {
let mut pass_guard = HUB.render_passes.write();
let pass = &mut pass_guard[pass_id];
let bind_group_guard = HUB.bind_groups.read();
let bind_group = &bind_group_guard[bind_group_id];
assert_eq!(bind_group.dynamic_count, offsets_count);
let offsets = if offsets_count != 0 {
unsafe {
slice::from_raw_parts(offsets_ptr, offsets_count)
}
} else {
&[]
};
pass.trackers.consume_by_extend(&bind_group.used);
if let Some((pipeline_layout_id, follow_up)) =
pass.binder
.provide_entry(index as usize, bind_group_id, bind_group, offsets)
{
let pipeline_layout_guard = HUB.pipeline_layouts.read();
let bind_groups =
iter::once(&bind_group.raw).chain(follow_up.map(|bg_id| &bind_group_guard[bg_id].raw));
unsafe {
pass.raw.bind_graphics_descriptor_sets(
&&pipeline_layout_guard[pipeline_layout_id].raw,
index as usize,
bind_groups,
offsets,
);
}
};
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_pipeline(
pass_id: RenderPassId,
@@ -275,11 +308,10 @@ pub extern "C" fn wgpu_render_pass_set_pipeline(
"The render pipeline is not compatible with the pass!"
);
if pipeline.flags.contains(PipelineFlags::BLEND_COLOR)
&& pass.blend_color_status == BlendColorStatus::Unused
{
pass.blend_color_status = BlendColorStatus::Required;
}
pass.blend_color_status
.require(pipeline.flags.contains(PipelineFlags::BLEND_COLOR));
pass.stencil_reference_status
.require(pipeline.flags.contains(PipelineFlags::STENCIL_REFERENCE));
unsafe {
pass.raw.bind_graphics_pipeline(&pipeline.raw);
@@ -326,12 +358,12 @@ pub extern "C" fn wgpu_render_pass_set_pipeline(
let buffer = pass
.trackers
.buffers
.get_with_extended_usage(&*buffer_guard, buffer_id, BufferUsageFlags::INDEX)
.get_with_extended_usage(&*buffer_guard, buffer_id, BufferUsage::INDEX)
.unwrap();
let view = hal::buffer::IndexBufferView {
buffer: &buffer.raw,
offset: offset as u64,
offset,
index_type: conv::map_index_format(pass.index_state.format),
};
@@ -347,13 +379,57 @@ pub extern "C" fn wgpu_render_pass_set_blend_color(pass_id: RenderPassId, color:
let mut pass_guard = HUB.render_passes.write();
let pass = &mut pass_guard[pass_id];
pass.blend_color_status = BlendColorStatus::Set;
pass.blend_color_status = OptionalState::Set;
unsafe {
pass.raw.set_blend_constants(conv::map_color(color));
}
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_stencil_reference(pass_id: RenderPassId, value: u32) {
let mut pass_guard = HUB.render_passes.write();
let pass = &mut pass_guard[pass_id];
pass.stencil_reference_status = OptionalState::Set;
unsafe {
pass.raw.set_stencil_reference(hal::pso::Face::all(), value);
}
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_viewport(
pass_id: RenderPassId,
x: f32,
y: f32,
w: f32,
h: f32,
min_depth: f32,
max_depth: f32,
) {
let mut pass_guard = HUB.render_passes.write();
let pass = &mut pass_guard[pass_id];
unsafe {
use std::convert::TryFrom;
use std::i16;
pass.raw.set_viewports(
0,
&[hal::pso::Viewport {
rect: hal::pso::Rect {
x: i16::try_from(x.round() as i64).unwrap_or(0),
y: i16::try_from(y.round() as i64).unwrap_or(0),
w: i16::try_from(w.round() as i64).unwrap_or(i16::MAX),
h: i16::try_from(h.round() as i64).unwrap_or(i16::MAX),
},
depth: min_depth .. max_depth,
}],
);
}
}
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_scissor_rect(
pass_id: RenderPassId,

View File

@@ -4,13 +4,14 @@ use crate::{
hub::HUB,
resource::TexturePlacement,
swap_chain::SwapChainLink,
BufferAddress,
BufferId,
BufferUsageFlags,
BufferUsage,
CommandBufferId,
Extent3d,
Origin3d,
TextureId,
TextureUsageFlags,
TextureUsage,
};
use copyless::VecHelper as _;
@@ -23,7 +24,7 @@ const BITS_PER_BYTE: u32 = 8;
#[repr(C)]
pub struct BufferCopyView {
pub buffer: BufferId,
pub offset: u32,
pub offset: BufferAddress,
pub row_pitch: u32,
pub image_height: u32,
}
@@ -31,20 +32,19 @@ pub struct BufferCopyView {
#[repr(C)]
pub struct TextureCopyView {
pub texture: TextureId,
pub level: u32,
pub slice: u32,
pub mip_level: u32,
pub array_layer: u32,
pub origin: Origin3d,
//TODO: pub aspect: TextureAspect,
}
#[no_mangle]
pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer(
command_buffer_id: CommandBufferId,
src: BufferId,
src_offset: u32,
src_offset: BufferAddress,
dst: BufferId,
dst_offset: u32,
size: u32,
dst_offset: BufferAddress,
size: BufferAddress,
) {
let mut cmb_guard = HUB.command_buffers.write();
let cmb = &mut cmb_guard[command_buffer_id];
@@ -53,36 +53,36 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer(
let (src_buffer, src_usage) = cmb
.trackers
.buffers
.get_with_replaced_usage(&*buffer_guard, src, BufferUsageFlags::TRANSFER_SRC)
.get_with_replaced_usage(&*buffer_guard, src, BufferUsage::TRANSFER_SRC)
.unwrap();
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_READ,
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_READ,
target: &src_buffer.raw,
families: None,
range: None..None,
range: None .. None,
});
let (dst_buffer, dst_usage) = cmb
.trackers
.buffers
.get_with_replaced_usage(&*buffer_guard, dst, BufferUsageFlags::TRANSFER_DST)
.get_with_replaced_usage(&*buffer_guard, dst, BufferUsage::TRANSFER_DST)
.unwrap();
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_WRITE,
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_WRITE,
target: &dst_buffer.raw,
families: None,
range: None..None,
range: None .. None,
});
let region = hal::command::BufferCopy {
src: src_offset as hal::buffer::Offset,
dst: dst_offset as hal::buffer::Offset,
size: size as hal::buffer::Offset,
src: src_offset,
dst: dst_offset,
size,
};
let cmb_raw = cmb.raw.last_mut().unwrap();
unsafe {
cmb_raw.pipeline_barrier(
all_buffer_stages()..all_buffer_stages(),
all_buffer_stages() .. all_buffer_stages(),
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);
@@ -105,17 +105,13 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
let (src_buffer, src_usage) = cmb
.trackers
.buffers
.get_with_replaced_usage(
&*buffer_guard,
source.buffer,
BufferUsageFlags::TRANSFER_SRC,
)
.get_with_replaced_usage(&*buffer_guard, source.buffer, BufferUsage::TRANSFER_SRC)
.unwrap();
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_READ,
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_READ,
target: &src_buffer.raw,
families: None,
range: None..None,
range: None .. None,
});
let (dst_texture, dst_usage) = cmb
@@ -124,13 +120,13 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
.get_with_replaced_usage(
&*texture_guard,
destination.texture,
TextureUsageFlags::TRANSFER_DST,
TextureUsage::TRANSFER_DST,
)
.unwrap();
let aspects = dst_texture.full_range.aspects;
let dst_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_DST, aspects);
let dst_texture_state = conv::map_texture_state(TextureUsage::TRANSFER_DST, aspects);
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects)..dst_texture_state,
states: conv::map_texture_state(old, aspects) .. dst_texture_state,
target: &dst_texture.raw,
families: None,
range: dst_texture.full_range.clone(),
@@ -151,13 +147,13 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
let buffer_width = source.row_pitch / bytes_per_texel;
assert_eq!(source.row_pitch % bytes_per_texel, 0);
let region = hal::command::BufferImageCopy {
buffer_offset: source.offset as hal::buffer::Offset,
buffer_offset: source.offset,
buffer_width,
buffer_height: source.image_height,
image_layers: hal::image::SubresourceLayers {
aspects, //TODO
level: destination.level as hal::image::Level,
layers: destination.slice as u16..destination.slice as u16 + 1,
level: destination.mip_level as hal::image::Level,
layers: destination.array_layer as u16 .. destination.array_layer as u16 + 1,
},
image_offset: conv::map_origin(destination.origin),
image_extent: conv::map_extent(copy_size),
@@ -166,7 +162,7 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
let stages = all_buffer_stages() | all_image_stages();
unsafe {
cmb_raw.pipeline_barrier(
stages..stages,
stages .. stages,
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);
@@ -194,16 +190,12 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
let (src_texture, src_usage) = cmb
.trackers
.textures
.get_with_replaced_usage(
&*texture_guard,
source.texture,
TextureUsageFlags::TRANSFER_SRC,
)
.get_with_replaced_usage(&*texture_guard, source.texture, TextureUsage::TRANSFER_SRC)
.unwrap();
let aspects = src_texture.full_range.aspects;
let src_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_SRC, aspects);
let src_texture_state = conv::map_texture_state(TextureUsage::TRANSFER_SRC, aspects);
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects)..src_texture_state,
states: conv::map_texture_state(old, aspects) .. src_texture_state,
target: &src_texture.raw,
families: None,
range: src_texture.full_range.clone(),
@@ -220,14 +212,14 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
.get_with_replaced_usage(
&*buffer_guard,
destination.buffer,
BufferUsageFlags::TRANSFER_DST,
BufferUsage::TRANSFER_DST,
)
.unwrap();
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_WRITE,
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_WRITE,
target: &dst_buffer.raw,
families: None,
range: None..None,
range: None .. None,
});
let bytes_per_texel = conv::map_texture_format(src_texture.format)
@@ -237,13 +229,13 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
let buffer_width = destination.row_pitch / bytes_per_texel;
assert_eq!(destination.row_pitch % bytes_per_texel, 0);
let region = hal::command::BufferImageCopy {
buffer_offset: destination.offset as hal::buffer::Offset,
buffer_offset: destination.offset,
buffer_width,
buffer_height: destination.image_height,
image_layers: hal::image::SubresourceLayers {
aspects, //TODO
level: source.level as hal::image::Level,
layers: source.slice as u16..source.slice as u16 + 1,
level: source.mip_level as hal::image::Level,
layers: source.array_layer as u16 .. source.array_layer as u16 + 1,
},
image_offset: conv::map_origin(source.origin),
image_extent: conv::map_extent(copy_size),
@@ -252,7 +244,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
let stages = all_buffer_stages() | all_image_stages();
unsafe {
cmb_raw.pipeline_barrier(
stages..stages,
stages .. stages,
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);
@@ -279,11 +271,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
let (src_texture, src_usage) = cmb
.trackers
.textures
.get_with_replaced_usage(
&*texture_guard,
source.texture,
TextureUsageFlags::TRANSFER_SRC,
)
.get_with_replaced_usage(&*texture_guard, source.texture, TextureUsage::TRANSFER_SRC)
.unwrap();
let (dst_texture, dst_usage) = cmb
.trackers
@@ -291,22 +279,22 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
.get_with_replaced_usage(
&*texture_guard,
destination.texture,
TextureUsageFlags::TRANSFER_DST,
TextureUsage::TRANSFER_DST,
)
.unwrap();
let aspects = src_texture.full_range.aspects & dst_texture.full_range.aspects;
let src_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_SRC, aspects);
let dst_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_DST, aspects);
let src_texture_state = conv::map_texture_state(TextureUsage::TRANSFER_SRC, aspects);
let dst_texture_state = conv::map_texture_state(TextureUsage::TRANSFER_DST, aspects);
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects)..src_texture_state,
states: conv::map_texture_state(old, aspects) .. src_texture_state,
target: &src_texture.raw,
families: None,
range: src_texture.full_range.clone(),
});
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects)..dst_texture_state,
states: conv::map_texture_state(old, aspects) .. dst_texture_state,
target: &dst_texture.raw,
families: None,
range: dst_texture.full_range.clone(),
@@ -323,14 +311,14 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
let region = hal::command::ImageCopy {
src_subresource: hal::image::SubresourceLayers {
aspects,
level: source.level as hal::image::Level,
layers: source.slice as u16..source.slice as u16 + 1,
level: source.mip_level as hal::image::Level,
layers: source.array_layer as u16 .. source.array_layer as u16 + 1,
},
src_offset: conv::map_origin(source.origin),
dst_subresource: hal::image::SubresourceLayers {
aspects,
level: destination.level as hal::image::Level,
layers: destination.slice as u16..destination.slice as u16 + 1,
level: destination.mip_level as hal::image::Level,
layers: destination.array_layer as u16 .. destination.array_layer as u16 + 1,
},
dst_offset: conv::map_origin(destination.origin),
extent: conv::map_extent(copy_size),
@@ -338,7 +326,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
let cmb_raw = cmb.raw.last_mut().unwrap();
unsafe {
cmb_raw.pipeline_barrier(
all_image_stages()..all_image_stages(),
all_image_stages() .. all_image_stages(),
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);

View File

@@ -1,9 +1,9 @@
use crate::{binding_model, command, pipeline, resource, Color, Extent3d, Origin3d};
pub fn map_buffer_usage(
usage: resource::BufferUsageFlags,
usage: resource::BufferUsage,
) -> (hal::buffer::Usage, hal::memory::Properties) {
use crate::resource::BufferUsageFlags as W;
use crate::resource::BufferUsage as W;
use hal::buffer::Usage as U;
use hal::memory::Properties as P;
@@ -39,10 +39,10 @@ pub fn map_buffer_usage(
}
pub fn map_texture_usage(
usage: resource::TextureUsageFlags,
usage: resource::TextureUsage,
aspects: hal::format::Aspects,
) -> hal::image::Usage {
use crate::resource::TextureUsageFlags as W;
use crate::resource::TextureUsage as W;
use hal::image::Usage as U;
let mut value = U::empty();
@@ -65,7 +65,7 @@ pub fn map_texture_usage(
value |= U::COLOR_ATTACHMENT;
}
}
// Note: TextureUsageFlags::Present does not need to be handled explicitly
// Note: TextureUsage::Present does not need to be handled explicitly
// TODO: HAL Transient Attachment, HAL Input Attachment
value
}
@@ -77,6 +77,7 @@ pub fn map_binding_type(binding_ty: binding_model::BindingType) -> hal::pso::Des
UniformBuffer => H::UniformBuffer,
Sampler => H::Sampler,
SampledTexture => H::SampledImage,
StorageTexture => H::StorageImage,
StorageBuffer => H::StorageBuffer,
UniformBufferDynamic => H::UniformBufferDynamic,
StorageBufferDynamic => H::StorageBufferDynamic,
@@ -84,19 +85,19 @@ pub fn map_binding_type(binding_ty: binding_model::BindingType) -> hal::pso::Des
}
pub fn map_shader_stage_flags(
shader_stage_flags: binding_model::ShaderStageFlags,
shader_stage_flags: binding_model::ShaderStage,
) -> hal::pso::ShaderStageFlags {
use crate::binding_model::ShaderStageFlags as F;
use crate::binding_model::ShaderStage as Ss;
use hal::pso::ShaderStageFlags as H;
let mut value = H::empty();
if shader_stage_flags.contains(F::VERTEX) {
if shader_stage_flags.contains(Ss::VERTEX) {
value |= H::VERTEX;
}
if shader_stage_flags.contains(F::FRAGMENT) {
if shader_stage_flags.contains(Ss::FRAGMENT) {
value |= H::FRAGMENT;
}
if shader_stage_flags.contains(F::COMPUTE) {
if shader_stage_flags.contains(Ss::COMPUTE) {
value |= H::COMPUTE;
}
value
@@ -134,12 +135,12 @@ pub fn map_color_state_descriptor(
desc: &pipeline::ColorStateDescriptor,
) -> hal::pso::ColorBlendDesc {
let color_mask = desc.write_mask;
let blend_state = if desc.color != pipeline::BlendDescriptor::REPLACE
|| desc.alpha != pipeline::BlendDescriptor::REPLACE
let blend_state = if desc.color_blend != pipeline::BlendDescriptor::REPLACE
|| desc.alpha_blend != pipeline::BlendDescriptor::REPLACE
{
hal::pso::BlendState::On {
color: map_blend_descriptor(&desc.color),
alpha: map_blend_descriptor(&desc.alpha),
color: map_blend_descriptor(&desc.color_blend),
alpha: map_blend_descriptor(&desc.alpha_blend),
}
} else {
hal::pso::BlendState::Off
@@ -147,21 +148,21 @@ pub fn map_color_state_descriptor(
hal::pso::ColorBlendDesc(map_color_write_flags(color_mask), blend_state)
}
fn map_color_write_flags(flags: pipeline::ColorWriteFlags) -> hal::pso::ColorMask {
use crate::pipeline::ColorWriteFlags as F;
fn map_color_write_flags(flags: pipeline::ColorWrite) -> hal::pso::ColorMask {
use crate::pipeline::ColorWrite as Cw;
use hal::pso::ColorMask as H;
let mut value = H::empty();
if flags.contains(F::RED) {
if flags.contains(Cw::RED) {
value |= H::RED;
}
if flags.contains(F::GREEN) {
if flags.contains(Cw::GREEN) {
value |= H::GREEN;
}
if flags.contains(F::BLUE) {
if flags.contains(Cw::BLUE) {
value |= H::BLUE;
}
if flags.contains(F::ALPHA) {
if flags.contains(Cw::ALPHA) {
value |= H::ALPHA;
}
value
@@ -367,42 +368,23 @@ pub fn map_vertex_format(vertex_format: pipeline::VertexFormat) -> hal::format::
use crate::pipeline::VertexFormat::*;
use hal::format::Format as H;
match vertex_format {
Uchar => H::R8Uint,
Uchar2 => H::Rg8Uint,
Uchar3 => H::Rgb8Uint,
Uchar4 => H::Rgba8Uint,
Char => H::R8Sint,
Char2 => H::Rg8Sint,
Char3 => H::Rgb8Sint,
Char4 => H::Rgba8Sint,
UcharNorm => H::R8Unorm,
Uchar2Norm => H::Rg8Unorm,
Uchar3Norm => H::Rgb8Unorm,
Uchar4Norm => H::Rgba8Unorm,
Uchar4NormBgra => H::Bgra8Unorm,
CharNorm => H::R8Snorm,
Char2Norm => H::Rg8Snorm,
Char3Norm => H::Rgb8Snorm,
Char4Norm => H::Rgba8Snorm,
Ushort => H::R16Uint,
Ushort2 => H::Rg16Uint,
Ushort3 => H::Rgb16Uint,
Ushort4 => H::Rgba16Uint,
Short => H::R16Sint,
Short2 => H::Rg16Sint,
Short3 => H::Rgb16Sint,
Short4 => H::Rgba16Sint,
UshortNorm => H::R16Unorm,
Ushort2Norm => H::Rg16Unorm,
Ushort3Norm => H::Rgb16Unorm,
Ushort4Norm => H::Rgba16Unorm,
ShortNorm => H::R16Snorm,
Short2Norm => H::Rg16Snorm,
Short3Norm => H::Rgb16Snorm,
Short4Norm => H::Rgba16Snorm,
Half => H::R16Sfloat,
Half2 => H::Rg16Sfloat,
Half3 => H::Rgb16Sfloat,
Half4 => H::Rgba16Sfloat,
Float => H::R32Sfloat,
Float2 => H::Rg32Sfloat,
@@ -486,8 +468,8 @@ pub fn map_texture_aspect_flags(aspect: resource::TextureAspectFlags) -> hal::fo
flags
}
pub fn map_buffer_state(usage: resource::BufferUsageFlags) -> hal::buffer::State {
use crate::resource::BufferUsageFlags as W;
pub fn map_buffer_state(usage: resource::BufferUsage) -> hal::buffer::State {
use crate::resource::BufferUsage as W;
use hal::buffer::Access as A;
let mut access = A::empty();
@@ -514,10 +496,10 @@ pub fn map_buffer_state(usage: resource::BufferUsageFlags) -> hal::buffer::State
}
pub fn map_texture_state(
usage: resource::TextureUsageFlags,
usage: resource::TextureUsage,
aspects: hal::format::Aspects,
) -> hal::image::State {
use crate::resource::TextureUsageFlags as W;
use crate::resource::TextureUsage as W;
use hal::image::{Access as A, Layout as L};
let is_color = aspects.contains(hal::format::Aspects::COLOR);
@@ -589,7 +571,6 @@ pub fn map_wrap(address: resource::AddressMode) -> hal::image::WrapMode {
Am::ClampToEdge => W::Clamp,
Am::Repeat => W::Tile,
Am::MirrorRepeat => W::Mirror,
Am::ClampToBorderColor => W::Border,
}
}

View File

@@ -9,6 +9,7 @@ use crate::{
track::{DummyUsage, Stitch, TrackPermit, TrackerSet, Tracktion},
AdapterId,
BindGroupId,
BufferAddress,
BufferId,
BufferMapAsyncStatus,
BufferMapOperation,
@@ -51,17 +52,9 @@ use log::{info, trace};
//use rendy_memory::{allocator, Config, Heaps};
use parking_lot::Mutex;
use std::{
collections::hash_map::Entry,
ffi,
iter,
ptr,
slice,
sync::atomic::Ordering,
};
#[cfg(feature = "local")]
use std::sync::atomic::AtomicBool;
use std::{collections::hash_map::Entry, ffi, iter, ptr, slice, sync::atomic::Ordering};
const CLEANUP_WAIT_MS: u64 = 5000;
pub const MAX_COLOR_TARGETS: usize = 4;
@@ -188,11 +181,10 @@ impl<B: hal::Backend> PendingResources<B> {
//TODO: enable when `is_sorted_by_key` is stable
//debug_assert!(self.active.is_sorted_by_key(|a| a.index));
let done_count = self.active
let done_count = self
.active
.iter()
.position(|a| unsafe {
!device.get_fence_status(&a.fence).unwrap()
})
.position(|a| unsafe { !device.get_fence_status(&a.fence).unwrap() })
.unwrap_or(self.active.len());
let last_done = if done_count != 0 {
self.active[done_count - 1].index
@@ -200,7 +192,7 @@ impl<B: hal::Backend> PendingResources<B> {
0
};
for a in self.active.drain(..done_count) {
for a in self.active.drain(.. done_count) {
trace!("Active submission {} is done", a.index);
self.free.extend(a.resources.into_iter().map(|(_, r)| r));
self.ready_to_map.extend(a.mapped);
@@ -234,7 +226,7 @@ impl<B: hal::Backend> PendingResources<B> {
impl PendingResources<back::Backend> {
fn triage_referenced(&mut self, trackers: &mut TrackerSet) {
for i in (0..self.referenced.len()).rev() {
for i in (0 .. self.referenced.len()).rev() {
let num_refs = self.referenced[i].1.load();
// Before destruction, a resource is expected to have the following strong refs:
// 1. in resource itself
@@ -375,7 +367,7 @@ fn map_buffer(
raw: &<back::Backend as hal::Backend>::Device,
limits: &hal::Limits,
buffer: &mut resource::Buffer<back::Backend>,
original_range: &std::ops::Range<u64>,
original_range: &std::ops::Range<BufferAddress>,
kind: HostMap,
) -> BufferMapResult {
// gfx-rs requires mapping and flushing/invalidation ranges to be done at `non_coherent_atom_size`
@@ -390,7 +382,7 @@ fn map_buffer(
limits.non_coherent_atom_size as u64 - 1
};
let atom_offset = original_range.start & atom_mask;
let range = (original_range.start & !atom_mask)..((original_range.end - 1) | atom_mask) + 1;
let range = (original_range.start & !atom_mask) .. ((original_range.end - 1) | atom_mask) + 1;
let pointer = unsafe { raw.map_memory(&buffer.memory, range.clone()) }?;
if !is_coherent {
@@ -523,9 +515,7 @@ impl<B: hal::Backend> Device<B> {
}
impl Device<back::Backend> {
fn maintain(
&self, force_wait: bool
) -> Vec<BufferMapPendingCallback> {
fn maintain(&self, force_wait: bool) -> Vec<BufferMapPendingCallback> {
let mut pending = self.pending.lock();
let mut trackers = self.trackers.lock();
@@ -572,7 +562,7 @@ pub fn device_create_buffer(
let device = &device_guard[device_id];
let (usage, memory_properties) = conv::map_buffer_usage(desc.usage);
let mut buffer = unsafe { device.raw.create_buffer(desc.size as u64, usage).unwrap() };
let mut buffer = unsafe { device.raw.create_buffer(desc.size, usage).unwrap() };
let requirements = unsafe { device.raw.get_buffer_requirements(&buffer) };
let device_type = device
.mem_props
@@ -622,7 +612,7 @@ pub fn device_track_buffer(
device_id: DeviceId,
buffer_id: BufferId,
ref_count: RefCount,
flags: resource::BufferUsageFlags,
flags: resource::BufferUsage,
) {
let query = HUB.devices.read()[device_id]
.trackers
@@ -641,12 +631,7 @@ pub extern "C" fn wgpu_device_create_buffer(
let buffer = device_create_buffer(device_id, desc);
let ref_count = buffer.life_guard.ref_count.clone();
let id = HUB.buffers.register_local(buffer);
device_track_buffer(
device_id,
id,
ref_count,
resource::BufferUsageFlags::empty(),
);
device_track_buffer(device_id, id, ref_count, resource::BufferUsage::empty());
id
}
@@ -658,13 +643,13 @@ pub extern "C" fn wgpu_device_create_buffer_mapped(
mapped_ptr_out: *mut *mut u8,
) -> BufferId {
let mut desc = desc.clone();
desc.usage |= resource::BufferUsageFlags::MAP_WRITE;
desc.usage |= resource::BufferUsage::MAP_WRITE;
let mut buffer = device_create_buffer(device_id, &desc);
{
let device_guard = HUB.devices.read();
let device = &device_guard[device_id];
let range = 0..desc.size as u64;
let range = 0 .. desc.size;
match map_buffer(
&device.raw,
@@ -687,12 +672,7 @@ pub extern "C" fn wgpu_device_create_buffer_mapped(
let ref_count = buffer.life_guard.ref_count.clone();
let id = HUB.buffers.register_local(buffer);
device_track_buffer(
device_id,
id,
ref_count,
resource::BufferUsageFlags::MAP_WRITE,
);
device_track_buffer(device_id, id, ref_count, resource::BufferUsage::MAP_WRITE);
id
}
@@ -701,20 +681,17 @@ pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) {
let device_guard = HUB.devices.read();
let buffer_guard = HUB.buffers.read();
let buffer = &buffer_guard[buffer_id];
device_guard[buffer.device_id.value]
.pending
.lock()
.destroy(
ResourceId::Buffer(buffer_id),
buffer.life_guard.ref_count.clone(),
);
device_guard[buffer.device_id.value].pending.lock().destroy(
ResourceId::Buffer(buffer_id),
buffer.life_guard.ref_count.clone(),
);
}
pub fn device_create_texture(
device_id: DeviceId,
desc: &resource::TextureDescriptor,
) -> resource::Texture<back::Backend> {
let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.array_size);
let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.array_layer_count);
let format = conv::map_texture_format(desc.format);
let aspects = format.surface_desc().aspects;
let usage = conv::map_texture_usage(desc.usage, aspects);
@@ -724,9 +701,9 @@ pub fn device_create_texture(
let mut image = unsafe {
device.raw.create_image(
kind,
1, // TODO: mips
desc.mip_level_count as hal::image::Level,
format,
hal::image::Tiling::Optimal, // TODO: linear
hal::image::Tiling::Optimal,
usage,
hal::image::ViewCapabilities::empty(), // TODO: format, 2d array, cube
)
@@ -771,8 +748,8 @@ pub fn device_create_texture(
format: desc.format,
full_range: hal::image::SubresourceRange {
aspects,
levels: 0..1, //TODO: mips
layers: 0..desc.array_size as u16,
levels: 0 .. desc.mip_level_count as hal::image::Level,
layers: 0 .. desc.array_layer_count as hal::image::Layer,
},
placement: resource::TexturePlacement::Memory(memory),
life_guard: LifeGuard::new(),
@@ -787,7 +764,7 @@ pub fn device_track_texture(device_id: DeviceId, texture_id: TextureId, ref_coun
.query(
texture_id,
&ref_count,
resource::TextureUsageFlags::UNINITIALIZED,
resource::TextureUsage::UNINITIALIZED,
);
assert!(query.initialized);
}
@@ -864,8 +841,9 @@ pub extern "C" fn wgpu_texture_create_view(
conv::map_texture_view_dimension(desc.dimension),
hal::image::SubresourceRange {
aspects: conv::map_texture_aspect_flags(desc.aspect),
levels: desc.base_mip_level as u8..(desc.base_mip_level + desc.level_count) as u8,
layers: desc.base_array_layer as u16..(desc.base_array_layer + desc.array_count) as u16,
levels: desc.base_mip_level as u8 .. (desc.base_mip_level + desc.level_count) as u8,
layers: desc.base_array_layer as u16
.. (desc.base_array_layer + desc.array_count) as u16,
},
);
let ref_count = view.life_guard.ref_count.clone();
@@ -935,22 +913,18 @@ pub fn device_create_sampler(
mag_filter: conv::map_filter(desc.mag_filter),
mip_filter: conv::map_filter(desc.mipmap_filter),
wrap_mode: (
conv::map_wrap(desc.r_address_mode),
conv::map_wrap(desc.s_address_mode),
conv::map_wrap(desc.t_address_mode),
conv::map_wrap(desc.address_mode_u),
conv::map_wrap(desc.address_mode_v),
conv::map_wrap(desc.address_mode_w),
),
lod_bias: 0.0.into(),
lod_range: desc.lod_min_clamp.into()..desc.lod_max_clamp.into(),
lod_range: desc.lod_min_clamp.into() .. desc.lod_max_clamp.into(),
comparison: if desc.compare_function == resource::CompareFunction::Always {
None
} else {
Some(conv::map_compare_function(desc.compare_function))
},
border: hal::image::PackedColor(match desc.border_color {
resource::BorderColor::TransparentBlack => 0x00000000,
resource::BorderColor::OpaqueBlack => 0x000000FF,
resource::BorderColor::OpaqueWhite => 0xFFFFFFFF,
}),
border: hal::image::PackedColor(0),
anisotropic: hal::image::Anisotropic::Off, //TODO
};
let raw = unsafe { device.raw.create_sampler(info).unwrap() };
@@ -1081,7 +1055,7 @@ pub fn device_create_bind_group(
.get_with_extended_usage(
&*buffer_guard,
bb.buffer,
resource::BufferUsageFlags::UNIFORM,
resource::BufferUsage::UNIFORM,
)
.unwrap();
let alignment = match decl.ty {
@@ -1094,7 +1068,8 @@ pub fn device_create_bind_group(
device.limits.min_storage_buffer_offset_alignment
}
binding_model::BindingType::Sampler
| binding_model::BindingType::SampledTexture => {
| binding_model::BindingType::SampledTexture
| binding_model::BindingType::StorageTexture => {
panic!("Mismatched buffer binding for {:?}", decl)
}
};
@@ -1104,7 +1079,7 @@ pub fn device_create_bind_group(
"Misaligned buffer offset {}",
bb.offset
);
let range = Some(bb.offset as u64)..Some((bb.offset + bb.size) as u64);
let range = Some(bb.offset) .. Some(bb.offset + bb.size);
hal::pso::Descriptor::Buffer(&buffer.raw, range)
}
binding_model::BindingResource::Sampler(id) => {
@@ -1120,7 +1095,7 @@ pub fn device_create_bind_group(
.transit(
view.texture_id.value,
&view.texture_id.ref_count,
resource::TextureUsageFlags::SAMPLED,
resource::TextureUsage::SAMPLED,
TrackPermit::EXTEND,
)
.unwrap();
@@ -1396,7 +1371,7 @@ pub fn device_create_render_pipeline(
samples: desc.sample_count as u8,
ops: hal::pass::AttachmentOps::PRESERVE,
stencil_ops: hal::pass::AttachmentOps::DONT_CARE,
layouts: hal::image::Layout::General..hal::image::Layout::General,
layouts: hal::image::Layout::General .. hal::image::Layout::General,
})
.collect(),
depth_stencil: depth_stencil_state.map(|at| hal::pass::Attachment {
@@ -1404,7 +1379,7 @@ pub fn device_create_render_pipeline(
samples: desc.sample_count as u8,
ops: hal::pass::AttachmentOps::PRESERVE,
stencil_ops: hal::pass::AttachmentOps::PRESERVE,
layouts: hal::image::Layout::General..hal::image::Layout::General,
layouts: hal::image::Layout::General .. hal::image::Layout::General,
}),
};
@@ -1424,7 +1399,7 @@ pub fn device_create_render_pipeline(
);
let subpass = hal::pass::SubpassDesc {
colors: &color_ids[..desc.color_states_length],
colors: &color_ids[.. desc.color_states_length],
depth_stencil: depth_stencil_state.map(|_| &depth_id),
inputs: &[],
resolves: &[],
@@ -1449,28 +1424,30 @@ pub fn device_create_render_pipeline(
module: &shader_module_guard[desc.vertex_stage.module].raw,
specialization: hal::pso::Specialization::EMPTY,
};
let fragment = hal::pso::EntryPoint::<back::Backend> {
entry: unsafe { ffi::CStr::from_ptr(desc.fragment_stage.entry_point) }
let fragment = unsafe { desc.fragment_stage.as_ref() }.map(|stage| hal::pso::EntryPoint::<
back::Backend,
> {
entry: unsafe { ffi::CStr::from_ptr(stage.entry_point) }
.to_str()
.to_owned()
.unwrap(), // TODO
module: &shader_module_guard[desc.fragment_stage.module].raw,
module: &shader_module_guard[stage.module].raw,
specialization: hal::pso::Specialization::EMPTY,
};
});
let shaders = hal::pso::GraphicsShaderSet {
vertex,
hull: None,
domain: None,
geometry: None,
fragment: Some(fragment),
fragment,
};
let rasterizer = conv::map_rasterization_state_descriptor(&desc.rasterization_state);
let desc_vbs = unsafe {
slice::from_raw_parts(
desc.vertex_buffer_state.vertex_buffers,
desc.vertex_buffer_state.vertex_buffers_count,
desc.vertex_input.vertex_buffers,
desc.vertex_input.vertex_buffers_count,
)
};
let mut vertex_buffers = Vec::with_capacity(desc_vbs.len());
@@ -1481,7 +1458,7 @@ pub fn device_create_render_pipeline(
}
vertex_buffers.alloc().init(hal::pso::VertexBufferDesc {
binding: i as u32,
stride: vb_state.stride,
stride: vb_state.stride as u32,
rate: match vb_state.step_mode {
pipeline::InputStepMode::Vertex => hal::pso::VertexInputRate::Vertex,
pipeline::InputStepMode::Instance => hal::pso::VertexInputRate::Instance(1),
@@ -1490,12 +1467,13 @@ pub fn device_create_render_pipeline(
let desc_atts =
unsafe { slice::from_raw_parts(vb_state.attributes, vb_state.attributes_count) };
for attribute in desc_atts {
assert_eq!(0, attribute.offset >> 32);
attributes.alloc().init(hal::pso::AttributeDesc {
location: attribute.attribute_index,
location: attribute.shader_location,
binding: i as u32,
element: hal::pso::Element {
format: conv::map_vertex_format(attribute.format),
offset: attribute.offset,
offset: attribute.offset as u32,
},
});
}
@@ -1568,11 +1546,15 @@ pub fn device_create_render_pipeline(
};
let mut flags = pipeline::PipelineFlags::empty();
if color_states
.iter()
.any(|state| state.color.uses_color() | state.alpha.uses_color())
{
flags |= pipeline::PipelineFlags::BLEND_COLOR;
for state in color_states {
if state.color_blend.uses_color() | state.alpha_blend.uses_color() {
flags |= pipeline::PipelineFlags::BLEND_COLOR;
}
}
if let Some(ds) = depth_stencil_state {
if ds.needs_stencil_reference() {
flags |= pipeline::PipelineFlags::STENCIL_REFERENCE;
}
}
pipeline::RenderPipeline {
@@ -1580,7 +1562,7 @@ pub fn device_create_render_pipeline(
layout_id: desc.layout,
pass_context,
flags,
index_format: desc.vertex_buffer_state.index_format,
index_format: desc.vertex_input.index_format,
}
}
@@ -1758,8 +1740,8 @@ pub fn device_create_swap_chain(
format: desc.format,
full_range: hal::image::SubresourceRange {
aspects: hal::format::Aspects::COLOR,
levels: 0..1,
layers: 0..1,
levels: 0 .. 1,
layers: 0 .. 1,
},
placement: resource::TexturePlacement::Void,
life_guard: LifeGuard::new(),
@@ -1806,7 +1788,7 @@ pub fn swap_chain_populate_textures(
trackers.textures.query(
texture_id.value,
&texture_id.ref_count,
resource::TextureUsageFlags::UNINITIALIZED,
resource::TextureUsage::UNINITIALIZED,
);
let view = resource::TextureView {
@@ -1872,8 +1854,8 @@ pub type BufferMapWriteCallback =
#[no_mangle]
pub extern "C" fn wgpu_buffer_map_read_async(
buffer_id: BufferId,
start: u32,
size: u32,
start: BufferAddress,
size: BufferAddress,
callback: BufferMapReadCallback,
userdata: *mut u8,
) {
@@ -1887,7 +1869,7 @@ pub extern "C" fn wgpu_buffer_map_read_async(
return;
}
let range = start as u64..(start + size) as u64;
let range = start .. start + size;
buffer.pending_map_operation = Some(BufferMapOperation::Read(range, callback, userdata));
(buffer.device_id.value, buffer.life_guard.ref_count.clone())
};
@@ -1895,7 +1877,7 @@ pub extern "C" fn wgpu_buffer_map_read_async(
let device_guard = HUB.devices.read();
let device = &device_guard[device_id];
let usage = resource::BufferUsageFlags::MAP_READ;
let usage = resource::BufferUsage::MAP_READ;
match device
.trackers
.lock()
@@ -1915,8 +1897,8 @@ pub extern "C" fn wgpu_buffer_map_read_async(
#[no_mangle]
pub extern "C" fn wgpu_buffer_map_write_async(
buffer_id: BufferId,
start: u32,
size: u32,
start: BufferAddress,
size: BufferAddress,
callback: BufferMapWriteCallback,
userdata: *mut u8,
) {
@@ -1930,7 +1912,7 @@ pub extern "C" fn wgpu_buffer_map_write_async(
return;
}
let range = start as u64..(start + size) as u64;
let range = start .. start + size;
buffer.pending_map_operation = Some(BufferMapOperation::Write(range, callback, userdata));
(buffer.device_id.value, buffer.life_guard.ref_count.clone())
};
@@ -1938,7 +1920,7 @@ pub extern "C" fn wgpu_buffer_map_write_async(
let device_guard = HUB.devices.read();
let device = &device_guard[device_id];
let usage = resource::BufferUsageFlags::MAP_WRITE;
let usage = resource::BufferUsage::MAP_WRITE;
match device
.trackers
.lock()

View File

@@ -35,7 +35,7 @@ use crate::{
TextureId,
TextureViewHandle,
TextureViewId,
TypedId
TypedId,
};
use lazy_static::lazy_static;
#[cfg(feature = "local")]
@@ -46,7 +46,7 @@ use vec_map::VecMap;
use std::{ops, sync::Arc};
/// A simple structure to manage identities of objects.
pub struct IdentityManager<I:TypedId> {
pub struct IdentityManager<I: TypedId> {
free: Vec<Index>,
epochs: Vec<Epoch>,
phantom: std::marker::PhantomData<I>,
@@ -87,13 +87,13 @@ impl<I: TypedId> IdentityManager<I> {
}
}
pub struct Storage<T, I:TypedId> {
pub struct Storage<T, I: TypedId> {
//TODO: consider concurrent hashmap?
map: VecMap<(T, Epoch)>,
_phantom: std::marker::PhantomData<I>,
}
impl<T, I:TypedId> ops::Index<I> for Storage<T, I> {
impl<T, I: TypedId> ops::Index<I> for Storage<T, I> {
type Output = T;
fn index(&self, id: I) -> &T {
let (ref value, epoch) = self.map[id.index() as usize];
@@ -102,7 +102,7 @@ impl<T, I:TypedId> ops::Index<I> for Storage<T, I> {
}
}
impl<T, I:TypedId> ops::IndexMut<I> for Storage<T, I> {
impl<T, I: TypedId> ops::IndexMut<I> for Storage<T, I> {
fn index_mut(&mut self, id: I) -> &mut T {
let (ref mut value, epoch) = self.map[id.index() as usize];
assert_eq!(epoch, id.epoch());
@@ -110,7 +110,7 @@ impl<T, I:TypedId> ops::IndexMut<I> for Storage<T, I> {
}
}
impl<T, I:TypedId> Storage<T, I> {
impl<T, I: TypedId> Storage<T, I> {
pub fn contains(&self, id: I) -> bool {
match self.map.get(id.index() as usize) {
Some(&(_, epoch)) if epoch == id.epoch() => true,
@@ -119,7 +119,7 @@ impl<T, I:TypedId> Storage<T, I> {
}
}
pub struct Registry<T, I:TypedId> {
pub struct Registry<T, I: TypedId> {
#[cfg(feature = "local")]
identity: Mutex<IdentityManager<I>>,
data: RwLock<Storage<T, I>>,
@@ -130,7 +130,10 @@ impl<T, I: TypedId> Default for Registry<T, I> {
Registry {
#[cfg(feature = "local")]
identity: Mutex::new(IdentityManager::default()),
data: RwLock::new(Storage { map: VecMap::new(), _phantom: std::marker::PhantomData }),
data: RwLock::new(Storage {
map: VecMap::new(),
_phantom: std::marker::PhantomData,
}),
}
}
}
@@ -150,7 +153,11 @@ impl<T, I: TypedId> ops::DerefMut for Registry<T, I> {
impl<T, I: TypedId + Copy> Registry<T, I> {
pub fn register(&self, id: I, value: T) {
let old = self.data.write().map.insert(id.index() as usize, (value, id.epoch()));
let old = self
.data
.write()
.map
.insert(id.index() as usize, (value, id.epoch()));
assert!(old.is_none());
}

View File

@@ -1,4 +1,12 @@
use crate::{hub::HUB, AdapterHandle, AdapterId, DeviceHandle, InstanceId, SurfaceHandle};
use crate::{
binding_model::MAX_BIND_GROUPS,
hub::HUB,
AdapterHandle,
AdapterId,
DeviceHandle,
InstanceId,
SurfaceHandle,
};
#[cfg(feature = "local")]
use crate::{DeviceId, SurfaceId};
@@ -26,17 +34,33 @@ pub struct AdapterDescriptor {
}
#[repr(C)]
#[derive(Debug)]
#[derive(Debug, Default)]
#[cfg_attr(feature = "remote", derive(Clone, Serialize, Deserialize))]
pub struct Extensions {
pub anisotropic_filtering: bool,
}
#[repr(C)]
#[derive(Debug)]
#[cfg_attr(feature = "remote", derive(Clone, Serialize, Deserialize))]
pub struct Limits {
pub max_bind_groups: u32,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_bind_groups: MAX_BIND_GROUPS as u32,
}
}
}
#[repr(C)]
#[derive(Debug)]
#[cfg_attr(feature = "remote", derive(Clone, Serialize, Deserialize))]
pub struct DeviceDescriptor {
pub extensions: Extensions,
pub limits: Limits,
}
pub fn create_instance() -> ::back::Instance {
@@ -50,7 +74,6 @@ pub extern "C" fn wgpu_create_instance() -> InstanceId {
HUB.instances.register_local(inst)
}
#[cfg(feature = "window-winit")]
#[no_mangle]
pub extern "C" fn wgpu_instance_create_surface_from_winit(
@@ -95,8 +118,10 @@ pub fn instance_create_surface_from_macos_layer(
unimplemented!();
#[cfg(feature = "gfx-backend-metal")]
SurfaceHandle::new(HUB.instances.read()[instance_id]
.create_surface_from_layer(layer as *mut _, cfg!(debug_assertions)))
SurfaceHandle::new(
HUB.instances.read()[instance_id]
.create_surface_from_layer(layer as *mut _, cfg!(debug_assertions)),
)
}
#[cfg(feature = "local")]
@@ -186,7 +211,7 @@ pub fn adapter_create_device(adapter_id: AdapterId, _desc: &DeviceDescriptor) ->
#[cfg(feature = "local")]
#[no_mangle]
pub extern "C" fn wgpu_adapter_create_device(
pub extern "C" fn wgpu_adapter_request_device(
adapter_id: AdapterId,
desc: &DeviceDescriptor,
) -> DeviceId {

View File

@@ -40,14 +40,19 @@ pub use self::swap_chain::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{
os::raw::c_char,
ptr,
sync::atomic::{AtomicUsize, Ordering},
};
type SubmissionIndex = usize;
pub(crate) type Index = u32;
pub(crate) type Epoch = u32;
pub type BufferAddress = u64;
pub type RawString = *const c_char;
//TODO: make it private. Currently used for swapchain creation impl.
#[derive(Debug)]
pub struct RefCount(ptr::NonNull<AtomicUsize>);
@@ -156,6 +161,14 @@ pub struct Origin3d {
pub z: f32,
}
impl Origin3d {
pub const ZERO: Self = Origin3d {
x: 0.0,
y: 0.0,
z: 0.0,
};
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Extent3d {
@@ -185,20 +198,20 @@ macro_rules! define_id {
($i:ident) => {
transparent!($i);
typed_id!($i);
}
};
}
macro_rules! transparent {
($i:ident) => (
($i:ident) => {
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct $i(Id);
)
};
}
macro_rules! typed_id {
($i:ident) => (
($i:ident) => {
impl $i {
fn raw(&self) -> Id {
self.0
@@ -215,10 +228,10 @@ macro_rules! typed_id {
}
fn epoch(&self) -> Epoch {
(self.raw()).1
(self.raw()).1
}
}
)
};
}
define_id!(InstanceId);

View File

@@ -1,8 +1,16 @@
use crate::{device::RenderPassContext, resource, ByteArray, PipelineLayoutId, ShaderModuleId};
use crate::{
device::RenderPassContext,
resource,
BufferAddress,
ByteArray,
PipelineLayoutId,
RawString,
ShaderModuleId,
};
use bitflags::bitflags;
pub type ShaderAttributeIndex = u32;
pub type ShaderLocation = u32;
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
@@ -34,7 +42,7 @@ pub enum BlendOperation {
bitflags! {
#[repr(transparent)]
pub struct ColorWriteFlags: u32 {
pub struct ColorWrite: u32 {
const RED = 1;
const GREEN = 2;
const BLUE = 4;
@@ -74,9 +82,9 @@ impl BlendDescriptor {
#[derive(Clone, Debug)]
pub struct ColorStateDescriptor {
pub format: resource::TextureFormat,
pub alpha: BlendDescriptor,
pub color: BlendDescriptor,
pub write_mask: ColorWriteFlags,
pub alpha_blend: BlendDescriptor,
pub color_blend: BlendDescriptor,
pub write_mask: ColorWrite,
}
#[repr(C)]
@@ -122,6 +130,12 @@ pub struct DepthStencilStateDescriptor {
pub stencil_write_mask: u32,
}
impl DepthStencilStateDescriptor {
pub fn needs_stencil_reference(&self) -> bool {
!self.stencil_front.compare.is_trivial() || !self.stencil_back.compare.is_trivial()
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum IndexFormat {
@@ -132,42 +146,23 @@ pub enum IndexFormat {
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum VertexFormat {
Uchar = 0,
Uchar2 = 1,
Uchar3 = 2,
Uchar4 = 3,
Char = 4,
Char2 = 5,
Char3 = 6,
Char4 = 7,
UcharNorm = 8,
Uchar2Norm = 9,
Uchar3Norm = 10,
Uchar4Norm = 11,
Uchar4NormBgra = 12,
CharNorm = 13,
Char2Norm = 14,
Char3Norm = 15,
Char4Norm = 16,
Ushort = 17,
Ushort2 = 18,
Ushort3 = 19,
Ushort4 = 20,
Short = 21,
Short2 = 22,
Short3 = 23,
Short4 = 24,
UshortNorm = 25,
Ushort2Norm = 26,
Ushort3Norm = 27,
Ushort4Norm = 28,
ShortNorm = 29,
Short2Norm = 30,
Short3Norm = 31,
Short4Norm = 32,
Half = 33,
Half2 = 34,
Half3 = 35,
Half4 = 36,
Float = 37,
Float2 = 38,
@@ -193,21 +188,21 @@ pub enum InputStepMode {
#[repr(C)]
#[derive(Clone, Debug)]
pub struct VertexAttributeDescriptor {
pub offset: u32,
pub offset: BufferAddress,
pub format: VertexFormat,
pub attribute_index: ShaderAttributeIndex,
pub shader_location: ShaderLocation,
}
#[repr(C)]
pub struct VertexBufferDescriptor {
pub stride: u32,
pub stride: BufferAddress,
pub step_mode: InputStepMode,
pub attributes: *const VertexAttributeDescriptor,
pub attributes_count: usize,
}
#[repr(C)]
pub struct VertexBufferStateDescriptor {
pub struct VertexInputDescriptor {
pub index_format: IndexFormat,
pub vertex_buffers: *const VertexBufferDescriptor,
pub vertex_buffers_count: usize,
@@ -221,7 +216,7 @@ pub struct ShaderModuleDescriptor {
#[repr(C)]
pub struct PipelineStageDescriptor {
pub module: ShaderModuleId,
pub entry_point: *const ::std::os::raw::c_char,
pub entry_point: RawString,
}
#[repr(C)]
@@ -274,13 +269,13 @@ pub struct RasterizationStateDescriptor {
pub struct RenderPipelineDescriptor {
pub layout: PipelineLayoutId,
pub vertex_stage: PipelineStageDescriptor,
pub fragment_stage: PipelineStageDescriptor,
pub fragment_stage: *const PipelineStageDescriptor,
pub primitive_topology: PrimitiveTopology,
pub rasterization_state: RasterizationStateDescriptor,
pub color_states: *const ColorStateDescriptor,
pub color_states_length: usize,
pub depth_stencil_state: *const DepthStencilStateDescriptor,
pub vertex_buffer_state: VertexBufferStateDescriptor,
pub vertex_input: VertexInputDescriptor,
pub sample_count: u32,
}
@@ -288,6 +283,7 @@ bitflags! {
#[repr(transparent)]
pub struct PipelineFlags: u32 {
const BLEND_COLOR = 1;
const STENCIL_REFERENCE = 2;
}
}

View File

@@ -1,5 +1,6 @@
use crate::{
swap_chain::{SwapChainLink, SwapImageEpoch},
BufferAddress,
BufferMapReadCallback,
BufferMapWriteCallback,
DeviceId,
@@ -18,7 +19,7 @@ use std::borrow::Borrow;
bitflags! {
#[repr(transparent)]
pub struct BufferUsageFlags: u32 {
pub struct BufferUsage: u32 {
const MAP_READ = 1;
const MAP_WRITE = 2;
const TRANSFER_SRC = 4;
@@ -35,8 +36,8 @@ bitflags! {
#[repr(C)]
#[derive(Clone)]
pub struct BufferDescriptor {
pub size: u32,
pub usage: BufferUsageFlags,
pub size: BufferAddress,
pub usage: BufferUsage,
}
#[repr(C)]
@@ -151,7 +152,7 @@ pub enum TextureFormat {
bitflags! {
#[repr(transparent)]
pub struct TextureUsageFlags: u32 {
pub struct TextureUsage: u32 {
const TRANSFER_SRC = 1;
const TRANSFER_DST = 2;
const SAMPLED = 4;
@@ -166,10 +167,12 @@ bitflags! {
#[repr(C)]
pub struct TextureDescriptor {
pub size: Extent3d,
pub array_size: u32,
pub array_layer_count: u32,
pub mip_level_count: u32,
pub sample_count: u32,
pub dimension: TextureDimension,
pub format: TextureFormat,
pub usage: TextureUsageFlags,
pub usage: TextureUsage,
}
pub(crate) enum TexturePlacement<B: hal::Backend> {
@@ -255,7 +258,6 @@ pub enum AddressMode {
ClampToEdge = 0,
Repeat = 1,
MirrorRepeat = 2,
ClampToBorderColor = 3,
}
#[repr(C)]
@@ -278,27 +280,26 @@ pub enum CompareFunction {
Always = 7,
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum BorderColor {
TransparentBlack = 0,
OpaqueBlack = 1,
OpaqueWhite = 2,
impl CompareFunction {
pub fn is_trivial(&self) -> bool {
match *self {
CompareFunction::Never | CompareFunction::Always => true,
_ => false,
}
}
}
#[repr(C)]
pub struct SamplerDescriptor {
pub r_address_mode: AddressMode,
pub s_address_mode: AddressMode,
pub t_address_mode: AddressMode,
pub address_mode_u: AddressMode,
pub address_mode_v: AddressMode,
pub address_mode_w: AddressMode,
pub mag_filter: FilterMode,
pub min_filter: FilterMode,
pub mipmap_filter: FilterMode,
pub lod_min_clamp: f32,
pub lod_max_clamp: f32,
pub max_anisotropy: u32,
pub compare_function: CompareFunction,
pub border_color: BorderColor,
}
pub struct Sampler<B: hal::Backend> {

View File

@@ -17,7 +17,9 @@ use log::{trace, warn};
use parking_lot::Mutex;
use std::{
iter, mem, sync::atomic::{AtomicBool, Ordering},
iter,
mem,
sync::atomic::{AtomicBool, Ordering},
};
pub type SwapImageEpoch = u16;
@@ -78,7 +80,7 @@ pub struct SwapChain<B: hal::Backend> {
#[repr(C)]
#[derive(Clone, Debug)]
pub struct SwapChainDescriptor {
pub usage: resource::TextureUsageFlags,
pub usage: resource::TextureUsage,
pub format: resource::TextureFormat,
pub width: u32,
pub height: u32,
@@ -92,7 +94,9 @@ impl SwapChainDescriptor {
height: self.height,
depth: 1,
},
array_size: 1,
mip_level_count: 1,
array_layer_count: 1,
sample_count: 1,
dimension: resource::TextureDimension::D2,
format: self.format,
usage: self.usage,
@@ -112,11 +116,9 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -
let mut surface_guard = HUB.surfaces.write();
let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap();
let result = unsafe {
swap_chain.raw.acquire_image(
!0,
Some(&swap_chain.sem_available),
None,
)
swap_chain
.raw
.acquire_image(!0, Some(&swap_chain.sem_available), None)
};
(
result.ok(),
@@ -148,12 +150,9 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -
index
}
None => unsafe {
swap_chain.raw
.acquire_image(
!0,
Some(&swap_chain.sem_available),
None,
)
swap_chain
.raw
.acquire_image(!0, Some(&swap_chain.sem_available), None)
.unwrap()
.0
},
@@ -171,9 +170,16 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -
let frame = &mut swap_chain.frames[image_index as usize];
let status = unsafe {
device.raw.wait_for_fence(&frame.fence, FRAME_TIMEOUT_MS * 1_000_000)
device
.raw
.wait_for_fence(&frame.fence, FRAME_TIMEOUT_MS * 1_000_000)
};
assert_eq!(status, Ok(true), "GPU got stuck on a frame (image {}) :(", image_index);
assert_eq!(
status,
Ok(true),
"GPU got stuck on a frame (image {}) :(",
image_index
);
mem::swap(&mut frame.sem_available, &mut swap_chain.sem_available);
frame.need_waiting.store(true, Ordering::Release);
@@ -182,8 +188,11 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -
.as_swap_chain()
.bump_epoch();
assert_eq!(frame.acquired_epoch, None, "Last swapchain output hasn't been presented");
frame.acquired_epoch =Some(frame_epoch);
assert_eq!(
frame.acquired_epoch, None,
"Last swapchain output hasn't been presented"
);
frame.acquired_epoch = Some(frame_epoch);
SwapChainOutput {
texture_id: frame.texture_id.value,
@@ -199,9 +208,16 @@ pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) {
let image_index = swap_chain.acquired.remove(0);
let frame = &mut swap_chain.frames[image_index as usize];
let epoch = frame.acquired_epoch.take();
assert!(epoch.is_some(), "Presented frame (image {}) was not acquired", image_index);
assert!(!frame.need_waiting.load(Ordering::Acquire),
"No rendering work has been submitted for the presented frame (image {})", image_index);
assert!(
epoch.is_some(),
"Presented frame (image {}) was not acquired",
image_index
);
assert!(
!frame.need_waiting.load(Ordering::Acquire),
"No rendering work has been submitted for the presented frame (image {})",
image_index
);
let mut device_guard = HUB.devices.write();
let device = &mut device_guard[swap_chain.device_id.value];
@@ -220,14 +236,14 @@ pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) {
.transit(
frame.texture_id.value,
&texture.life_guard.ref_count,
resource::TextureUsageFlags::UNINITIALIZED,
resource::TextureUsage::UNINITIALIZED,
TrackPermit::REPLACE,
)
.unwrap()
.into_source()
.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, hal::format::Aspects::COLOR)
..(
.. (
hal::image::Access::COLOR_ATTACHMENT_WRITE,
hal::image::Layout::Present,
),
@@ -239,7 +255,7 @@ pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) {
let err = unsafe {
frame.comb.begin(false);
frame.comb.pipeline_barrier(
all_image_stages()..hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT,
all_image_stages() .. hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT,
hal::memory::Dependencies::empty(),
barrier,
);

View File

@@ -1,13 +1,13 @@
use crate::{
hub::{Storage},
resource::{BufferUsageFlags, TextureUsageFlags},
hub::Storage,
resource::{BufferUsage, TextureUsage},
BufferId,
Epoch,
Index,
RefCount,
TextureId,
TextureViewId,
TypedId
TypedId,
};
use bitflags::bitflags;
@@ -69,14 +69,14 @@ impl BitOr for DummyUsage {
}
}
impl GenericUsage for BufferUsageFlags {
impl GenericUsage for BufferUsage {
fn is_exclusive(&self) -> bool {
BufferUsageFlags::WRITE_ALL.intersects(*self)
BufferUsage::WRITE_ALL.intersects(*self)
}
}
impl GenericUsage for TextureUsageFlags {
impl GenericUsage for TextureUsage {
fn is_exclusive(&self) -> bool {
TextureUsageFlags::WRITE_ALL.intersects(*self)
TextureUsage::WRITE_ALL.intersects(*self)
}
}
impl GenericUsage for DummyUsage {
@@ -98,8 +98,8 @@ pub struct Tracker<I, U> {
map: FastHashMap<Index, Track<U>>,
_phantom: PhantomData<I>,
}
pub type BufferTracker = Tracker<BufferId, BufferUsageFlags>;
pub type TextureTracker = Tracker<TextureId, TextureUsageFlags>;
pub type BufferTracker = Tracker<BufferId, BufferUsage>;
pub type TextureTracker = Tracker<TextureId, TextureUsage>;
pub type TextureViewTracker = Tracker<TextureViewId, DummyUsage>;
//TODO: make this a generic parameter.
@@ -240,7 +240,7 @@ impl<I: TypedId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker
Stitch::Init => new.init,
Stitch::Last => new.last,
};
Some((I::new(index, new.epoch), old..state))
Some((I::new(index, new.epoch), old .. state))
}
}
})
@@ -261,7 +261,7 @@ impl<I: TypedId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker
let extended = old | new.last;
if extended.is_exclusive() {
let id = I::new(index, new.epoch);
return Err((id, old..new.last));
return Err((id, old .. new.last));
}
e.get_mut().last = extended;
}

View File

@@ -13,7 +13,6 @@ use std::ptr;
mod server;
#[derive(Serialize, Deserialize)]
enum InstanceMessage {
Create(wgn::InstanceId),
@@ -85,9 +84,7 @@ pub extern "C" fn wgpu_initialize() -> Infrastructure {
#[no_mangle]
pub extern "C" fn wgpu_terminate(factory: *mut ClientFactory) {
let factory = unsafe {
Box::from_raw(factory)
};
let factory = unsafe { Box::from_raw(factory) };
let _ = factory.channel.send(GlobalMessage::Terminate);
}
@@ -106,9 +103,7 @@ pub extern "C" fn wgpu_client_create(factory: &ClientFactory) -> *mut Client {
#[no_mangle]
pub extern "C" fn wgpu_client_destroy(factory: &ClientFactory, client: *mut Client) {
let client = unsafe {
Box::from_raw(client)
};
let client = unsafe { Box::from_raw(client) };
factory.instance_identities.lock().free(client.instance_id);
let msg = GlobalMessage::Instance(InstanceMessage::Destroy(client.instance_id));
client.channel.send(msg).unwrap();

View File

@@ -3,16 +3,13 @@ use crate::{GlobalMessage, InstanceMessage};
use ipc_channel::ipc::IpcReceiver;
use wgn;
pub struct Server {
channel: IpcReceiver<GlobalMessage>,
}
impl Server {
pub(crate) fn new(channel: IpcReceiver<GlobalMessage>) -> Self {
Server {
channel,
}
Server { channel }
}
}
@@ -46,12 +43,11 @@ fn process(message: GlobalMessage) -> ControlFlow {
ControlFlow::Continue
}
#[no_mangle]
pub extern "C" fn wgpu_server_process(server: &Server) {
while let Ok(message) = server.channel.try_recv() {
match process(message) {
ControlFlow::Continue => {},
ControlFlow::Continue => {}
ControlFlow::Terminate => break,
}
}