address review comments

This commit is contained in:
Kunal Mohan 2020-06-26 13:20:29 +05:30
parent e6f0d12f97
commit ef3b141406
4 changed files with 632 additions and 600 deletions

View file

@ -135,7 +135,7 @@ use std::borrow::Cow;
use std::cell::{Cell, RefCell, UnsafeCell};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash};
use std::ops::{Deref, DerefMut};
use std::ops::{Deref, DerefMut, Range};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
@ -586,6 +586,7 @@ unsafe_no_jsmanaged_fields!(Option<RenderPass>);
unsafe_no_jsmanaged_fields!(Option<ComputePass>);
unsafe_no_jsmanaged_fields!(GPUBufferState);
unsafe_no_jsmanaged_fields!(GPUCommandEncoderState);
unsafe_no_jsmanaged_fields!(Range<u64>);
unsafe_no_jsmanaged_fields!(WebXRSwapChainId);
unsafe_no_jsmanaged_fields!(MediaList);
unsafe_no_jsmanaged_fields!(

View file

@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::GPUBufferBinding::GPUBufferMethods;
use crate::dom::bindings::codegen::Bindings::GPUBufferBinding::{GPUBufferMethods, GPUSize64};
use crate::dom::bindings::codegen::Bindings::GPUMapModeBinding::GPUMapModeConstants;
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::DomObject;
@ -22,6 +22,7 @@ use js::rust::jsapi_wrapped::{DetachArrayBuffer, IsPromiseObject, RejectPromise}
use js::rust::MutableHandle;
use js::typedarray::{ArrayBuffer, CreateWith};
use std::cell::Cell;
use std::ops::Range;
use std::ptr;
use std::rc::Rc;
use webgpu::{
@ -50,8 +51,8 @@ pub struct GPUBuffer {
valid: Cell<bool>,
#[ignore_malloc_size_of = "defined in mozjs"]
mapping: RootedTraceableBox<Heap<*mut JSObject>>,
mapping_range: (u64, u64),
size: u64,
mapping_range: DomRefCell<Range<u64>>,
size: GPUSize64,
map_mode: Cell<Option<u32>>,
}
@ -61,10 +62,10 @@ impl GPUBuffer {
buffer: WebGPUBuffer,
device: WebGPUDevice,
state: GPUBufferState,
size: u64,
size: GPUSize64,
valid: bool,
mapping: RootedTraceableBox<Heap<*mut JSObject>>,
mapping_range: (u64, u64),
mapping_range: Range<u64>,
) -> Self {
Self {
reflector_: Reflector::new(),
@ -76,7 +77,7 @@ impl GPUBuffer {
buffer,
mapping,
size,
mapping_range,
mapping_range: DomRefCell::new(mapping_range),
map_mode: Cell::new(None),
}
}
@ -88,10 +89,10 @@ impl GPUBuffer {
buffer: WebGPUBuffer,
device: WebGPUDevice,
state: GPUBufferState,
size: u64,
size: GPUSize64,
valid: bool,
mapping: RootedTraceableBox<Heap<*mut JSObject>>,
mapping_range: (u64, u64),
mapping_range: Range<u64>,
) -> DomRoot<Self> {
reflect_dom_object(
Box::new(GPUBuffer::new_inherited(
@ -186,6 +187,7 @@ impl GPUBufferMethods for GPUBuffer {
// Step 4
self.state.set(GPUBufferState::Unmapped);
self.map_mode.set(None);
*self.mapping_range.borrow_mut() = 0..0;
}
/// https://gpuweb.github.io/gpuweb/#dom-gpubuffer-destroy
@ -217,17 +219,16 @@ impl GPUBufferMethods for GPUBuffer {
let map_range = if size == 0 {
offset..self.size
} else {
offset..size
if offset + size > self.size {
warn!("Requested mapping size is greated than buffer size");
promise.reject_error(Error::Abort);
return promise;
}
offset..offset + size
};
let host_map = match mode {
GPUMapModeConstants::READ => {
self.map_mode.set(Some(mode));
HostMap::Read
},
GPUMapModeConstants::WRITE => {
self.map_mode.set(Some(mode));
HostMap::Write
},
GPUMapModeConstants::READ => HostMap::Read,
GPUMapModeConstants::WRITE => HostMap::Write,
_ => {
promise.reject_error(Error::Abort);
return promise;
@ -238,15 +239,13 @@ impl GPUBufferMethods for GPUBuffer {
return promise;
}
self.mapping.set(*promise.promise_obj());
self.state.set(GPUBufferState::MappingPending);
let sender = response_async(&promise, self);
if let Err(e) = self.channel.0.send(WebGPURequest::BufferMapAsync {
sender,
buffer_id: self.buffer.0,
host_map,
map_range,
map_range: map_range.clone(),
}) {
warn!(
"Failed to send BufferMapAsync ({:?}) ({})",
@ -256,6 +255,9 @@ impl GPUBufferMethods for GPUBuffer {
return promise;
}
self.state.set(GPUBufferState::MappingPending);
self.map_mode.set(Some(mode));
*self.mapping_range.borrow_mut() = map_range;
promise
}
@ -275,19 +277,23 @@ impl AsyncWGPUListener for GPUBuffer {
fn handle_response(&self, response: WebGPUResponse, promise: &Rc<Promise>) {
match response {
WebGPUResponse::BufferMapAsync(bytes) => {
if unsafe {
match unsafe {
ArrayBuffer::create(
*self.global().get_cx(),
CreateWith::Slice(&bytes),
MutableHandle::from_raw(self.mapping.handle_mut()),
)
}
.is_err()
{
} {
Ok(_) => promise.resolve_native(&()),
Err(()) => {
warn!(
"Failed to create ArrayBuffer for buffer({:?})",
self.buffer.0
);
promise.reject_error(Error::Operation);
},
}
self.state.set(GPUBufferState::Mapped);
promise.resolve_native(&());
},
_ => {
warn!("Wrong WebGPUResponse received");

View file

@ -191,10 +191,10 @@ impl GPUDeviceMethods for GPUDevice {
.is_ok());
}
state = GPUBufferState::MappedAtCreation;
mapping_range = (0, descriptor.size);
mapping_range = 0..descriptor.size;
} else {
state = GPUBufferState::Unmapped;
mapping_range = (0, 0);
mapping_range = 0..0;
}
GPUBuffer::new(
@ -364,7 +364,7 @@ impl GPUDeviceMethods for GPUDevice {
WebGPUBindings::Buffer(BufferBinding {
buffer_id: b.buffer.id().0,
offset: b.offset,
size: wgt::BufferSize::new(b.size.unwrap_or(0)),
size: b.size.and_then(wgt::BufferSize::new),
})
},
},

View file

@ -20,9 +20,10 @@ use servo_config::pref;
use smallvec::SmallVec;
use std::collections::HashMap;
use std::ffi::CString;
use std::ptr;
use std::ptr::{self, NonNull};
use std::slice;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use webrender_traits::{
WebrenderExternalImageApi, WebrenderExternalImageRegistry, WebrenderImageHandlerType,
WebrenderImageSource,
@ -36,6 +37,8 @@ use wgpu::{
resource::{BufferMapAsyncStatus, BufferMapOperation},
};
const DEVICE_POLL_INTERVAL: u64 = 100;
#[derive(Debug, Deserialize, Serialize)]
pub enum WebGPUResponse {
RequestAdapter {
@ -295,6 +298,7 @@ struct WGPU<'a> {
webrender_document: webrender_api::DocumentId,
external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
wgpu_image_map: Arc<Mutex<HashMap<u64, PresentationData>>>,
last_poll: Instant,
}
impl<'a> WGPU<'a> {
@ -323,16 +327,17 @@ impl<'a> WGPU<'a> {
webrender_document,
external_images,
wgpu_image_map,
last_poll: Instant::now(),
}
}
fn run(&'a mut self) {
while let Ok(msg) = self.receiver.recv() {
self.devices.iter().for_each(|device| {
let global = &self.global;
let device_id = device.0;
gfx_select!(device_id => global.device_poll(device_id, false));
});
loop {
if self.last_poll.elapsed() >= Duration::from_millis(DEVICE_POLL_INTERVAL) {
self.global.poll_all_devices(false);
self.last_poll = Instant::now();
}
if let Ok(msg) = self.receiver.try_recv() {
match msg {
WebGPURequest::BufferMapAsync {
sender,
@ -348,11 +353,16 @@ impl<'a> WGPU<'a> {
};
self.buffer_maps.insert(buffer_id, map_info);
unsafe extern "C" fn callback(status: BufferMapAsyncStatus, userdata: *mut u8) {
let info = (userdata as *mut BufferMapInfo).as_ref().unwrap();
unsafe extern "C" fn callback(
status: BufferMapAsyncStatus,
userdata: *mut u8,
) {
let nonnull_info =
NonNull::new(userdata as *mut BufferMapInfo).unwrap();
let info = nonnull_info.as_ref();
match status {
BufferMapAsyncStatus::Success => {
let global = info.global;
let global = &info.global;
let data_pt = gfx_select!(info.buffer_id =>
global.buffer_get_mapped_range(info.buffer_id, 0, None));
let data = slice::from_raw_parts(data_pt, info.size).to_vec();
@ -362,14 +372,16 @@ impl<'a> WGPU<'a> {
warn!("Could not send BufferMapAsync Response ({})", e);
}
},
_ => warn!("Could not map buffer({:?})", info.buffer_id),
_ => error!("Could not map buffer({:?})", info.buffer_id),
}
}
let operation = BufferMapOperation {
host: host_map,
callback,
user_data: convert_to_pointer(self.buffer_maps.get(&buffer_id).unwrap()),
user_data: convert_to_pointer(
self.buffer_maps.get(&buffer_id).unwrap(),
),
};
let global = &self.global;
gfx_select!(buffer_id => global.buffer_map_async(buffer_id, map_range, operation));
@ -414,7 +426,9 @@ impl<'a> WGPU<'a> {
.map(|(bind, res)| {
let resource = match res {
WebGPUBindings::Sampler(s) => BindingResource::Sampler(s),
WebGPUBindings::TextureView(t) => BindingResource::TextureView(t),
WebGPUBindings::TextureView(t) => {
BindingResource::TextureView(t)
},
WebGPUBindings::Buffer(b) => BindingResource::Buffer(b),
};
BindGroupEntry {
@ -530,7 +544,8 @@ impl<'a> WGPU<'a> {
Some(frag) => {
frag_ep =
std::ffi::CString::new(fragment_entry_point.unwrap()).unwrap();
let frag_module = wgpu_core::pipeline::ProgrammableStageDescriptor {
let frag_module =
wgpu_core::pipeline::ProgrammableStageDescriptor {
module: frag,
entry_point: frag_ep.as_ptr(),
};
@ -560,11 +575,13 @@ impl<'a> WGPU<'a> {
vertex_buffers: vertex_state
.1
.iter()
.map(|buffer| wgpu_core::pipeline::VertexBufferLayoutDescriptor {
.map(|buffer| {
wgpu_core::pipeline::VertexBufferLayoutDescriptor {
array_stride: buffer.0,
step_mode: buffer.1,
attributes_length: buffer.2.len(),
attributes: buffer.2.as_ptr(),
}
})
.collect::<Vec<_>>()
.as_ptr(),
@ -584,8 +601,11 @@ impl<'a> WGPU<'a> {
} => {
let global = &self.global;
let st = CString::new(descriptor.label.as_bytes()).unwrap();
let _ = gfx_select!(sampler_id =>
global.device_create_sampler(device_id, &descriptor.map_label(|_| st.as_ptr()), sampler_id));
let _ = gfx_select!(sampler_id => global.device_create_sampler(
device_id,
&descriptor.map_label(|_| st.as_ptr()),
sampler_id
));
},
WebGPURequest::CreateShaderModule {
device_id,
@ -653,8 +673,11 @@ impl<'a> WGPU<'a> {
} => {
let global = &self.global;
let st = CString::new(descriptor.label.as_bytes()).unwrap();
let _ = gfx_select!(texture_id =>
global.device_create_texture(device_id, &descriptor.map_label(|_| st.as_ptr()), texture_id));
let _ = gfx_select!(texture_id => global.device_create_texture(
device_id,
&descriptor.map_label(|_| st.as_ptr()),
texture_id
));
},
WebGPURequest::CreateTextureView {
texture_id,
@ -828,7 +851,8 @@ impl<'a> WGPU<'a> {
}
}
let buffer_size = (size.height as u32 * buffer_stride) as wgt::BufferAddress;
let buffer_size =
(size.height as u32 * buffer_stride) as wgt::BufferAddress;
let comm_desc = wgt::CommandEncoderDescriptor { label: ptr::null() };
let _ = gfx_select!(encoder_id => global.device_create_command_encoder(
device_id,
@ -932,6 +956,7 @@ impl<'a> WGPU<'a> {
}
}
}
}
}
fn convert_to_pointer<T: Sized>(obj: &T) -> *mut u8 {