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::cell::{Cell, RefCell, UnsafeCell};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash}; use std::hash::{BuildHasher, Hash};
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut, Range};
use std::path::PathBuf; use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicUsize}; 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!(Option<ComputePass>);
unsafe_no_jsmanaged_fields!(GPUBufferState); unsafe_no_jsmanaged_fields!(GPUBufferState);
unsafe_no_jsmanaged_fields!(GPUCommandEncoderState); unsafe_no_jsmanaged_fields!(GPUCommandEncoderState);
unsafe_no_jsmanaged_fields!(Range<u64>);
unsafe_no_jsmanaged_fields!(WebXRSwapChainId); unsafe_no_jsmanaged_fields!(WebXRSwapChainId);
unsafe_no_jsmanaged_fields!(MediaList); unsafe_no_jsmanaged_fields!(MediaList);
unsafe_no_jsmanaged_fields!( unsafe_no_jsmanaged_fields!(

View file

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

View file

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