Skip to content

Commit

Permalink
add more doc comments and clean up some public exports
Browse files Browse the repository at this point in the history
  • Loading branch information
cart committed Aug 9, 2020
1 parent f963cd4 commit 3d09459
Show file tree
Hide file tree
Showing 74 changed files with 360 additions and 163 deletions.
20 changes: 20 additions & 0 deletions crates/bevy_app/src/app.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
use crate::app_builder::AppBuilder;
use bevy_ecs::{ParallelExecutor, Resources, Schedule, World};

/// Containers of app logic and data
///
/// App store the ECS World, Resources, Schedule, and Executor. They also store the "run" function of the App, which
/// by default executes the App schedule once. Apps are constructed using the builder pattern.
///
/// ## Example
/// Here is a simple "Hello World" Bevy app:
/// ```
///use bevy::prelude::*;
///
///fn main() {
/// App::build()
/// .add_system(hello_world_system.system())
/// .run();
///}
///
///fn hello_world_system() {
/// println!("hello world");
///}
/// ```
pub struct App {
pub world: World,
pub resources: Resources,
Expand Down
5 changes: 3 additions & 2 deletions crates/bevy_app/src/app_builder.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::{
app::{App, AppExit},
event::Events,
plugin::{load_plugin, Plugin},
plugin::{dynamically_load_plugin, Plugin},
stage, startup_stage,
};
use bevy_ecs::{FromResources, IntoQuerySystem, Resources, System, World};

/// Configure [App]s using the builder pattern
pub struct AppBuilder {
pub app: App,
}
Expand Down Expand Up @@ -220,7 +221,7 @@ impl AppBuilder {
}

pub fn load_plugin(&mut self, path: &str) -> &mut Self {
let (_lib, plugin) = load_plugin(path);
let (_lib, plugin) = dynamically_load_plugin(path);
log::debug!("loaded plugin: {}", plugin.name());
plugin.build(self);
self
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_app/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ fn map_instance_event<T>(event_instance: &EventInstance<T>) -> &T {
&event_instance.event
}

/// Reads events of type `T` in order and tracks which events have already been read.
pub struct EventReader<T> {
last_event_count: usize,
_marker: PhantomData<T>,
Expand Down
5 changes: 3 additions & 2 deletions crates/bevy_app/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
/// The names of the default App stages
pub mod stage;
/// The names of the default App startup stages
pub mod startup_stage;

mod app;
mod app_builder;
mod event;
mod plugin;
mod schedule_runner;
mod startup_stage;

pub use app::*;
pub use app_builder::*;
pub use bevy_derive::DynamicPlugin;
pub use event::*;
pub use plugin::*;
pub use schedule_runner::*;
pub use startup_stage::*;

pub mod prelude {
pub use crate::{
Expand Down
6 changes: 5 additions & 1 deletion crates/bevy_app/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use crate::AppBuilder;
use libloading::{Library, Symbol};
use std::any::Any;

/// A collection of Bevy App logic and configuration
///
/// Plugins use [AppBuilder] to configure an [App](crate::App). When an [App](crate::App) registers a plugin, the plugin's [Plugin::build] function is run.
pub trait Plugin: Any + Send + Sync {
fn build(&self, app: &mut AppBuilder);
fn name(&self) -> &str {
Expand All @@ -11,7 +14,8 @@ pub trait Plugin: Any + Send + Sync {

pub type CreatePlugin = unsafe fn() -> *mut dyn Plugin;

pub fn load_plugin(path: &str) -> (Library, Box<dyn Plugin>) {
/// Dynamically links a plugin a the given path. The plugin must export the [CreatePlugin] function.
pub fn dynamically_load_plugin(path: &str) -> (Library, Box<dyn Plugin>) {
let lib = Library::new(path).unwrap();

unsafe {
Expand Down
2 changes: 2 additions & 0 deletions crates/bevy_app/src/schedule_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{
};
use std::{thread, time::Duration};

/// Determines the method used to run an [App]'s `Schedule`
#[derive(Copy, Clone, Debug)]
pub enum RunMode {
Loop { wait: Option<Duration> },
Expand All @@ -18,6 +19,7 @@ impl Default for RunMode {
}
}

/// Configures an App to run its [Schedule](bevy_ecs::Schedule) according to a given [RunMode]
#[derive(Default)]
pub struct ScheduleRunnerPlugin {
pub run_mode: RunMode,
Expand Down
12 changes: 9 additions & 3 deletions crates/bevy_asset/src/asset_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use std::{
};
use thiserror::Error;

/// The type used for asset versioning
pub type AssetVersion = usize;

/// Errors that occur while loading assets with an AssetServer
#[derive(Error, Debug)]
pub enum AssetServerError {
#[error("Asset folder path is not a directory.")]
Expand All @@ -39,13 +42,15 @@ struct LoaderThread {
requests: Arc<RwLock<Vec<LoadRequest>>>,
}

/// Info about a specific asset, such as its path and its current load state
#[derive(Clone, Debug)]
pub struct AssetInfo {
handle_id: HandleId,
path: PathBuf,
load_state: LoadState,
pub handle_id: HandleId,
pub path: PathBuf,
pub load_state: LoadState,
}

/// The load state of an asset
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LoadState {
Loading(AssetVersion),
Expand All @@ -63,6 +68,7 @@ impl LoadState {
}
}

/// Loads assets from the filesystem on background threads
pub struct AssetServer {
asset_folders: RwLock<Vec<PathBuf>>,
loader_threads: RwLock<Vec<LoaderThread>>,
Expand Down
3 changes: 3 additions & 0 deletions crates/bevy_asset/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ use bevy_ecs::{FromResources, IntoQuerySystem, ResMut, Resource};
use bevy_type_registry::RegisterType;
use std::collections::HashMap;

/// Events that happen on assets of type `T`
pub enum AssetEvent<T: Resource> {
Created { handle: Handle<T> },
Modified { handle: Handle<T> },
Removed { handle: Handle<T> },
}

/// Stores Assets of a given type and tracks changes to them.
pub struct Assets<T: Resource> {
assets: HashMap<Handle<T>, T>,
events: Events<AssetEvent<T>>,
Expand Down Expand Up @@ -108,6 +110,7 @@ impl<T: Resource> Assets<T> {
}
}

/// [AppBuilder] extension methods for adding new asset types
pub trait AddAsset {
fn add_asset<T>(&mut self) -> &mut Self
where
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_asset/src/filesystem_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crossbeam_channel::Receiver;
use notify::{Event, RecommendedWatcher, RecursiveMode, Result, Watcher};
use std::path::Path;

/// Watches for changes to assets on the filesystem and informs the `AssetServer` to reload them
/// Watches for changes to assets on the filesystem. This is used by the `AssetServer` to reload them
pub struct FilesystemWatcher {
pub watcher: RecommendedWatcher,
pub receiver: Receiver<Result<Event>>,
Expand Down
13 changes: 11 additions & 2 deletions crates/bevy_asset/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,23 @@ use serde::{Deserialize, Serialize};
use std::{any::TypeId, marker::PhantomData};
use uuid::Uuid;

/// The ID of the "default" asset
pub(crate) const DEFAULT_HANDLE_ID: HandleId =
HandleId(Uuid::from_u128(240940089166493627844978703213080810552));

/// A unique id that corresponds to a specific asset in the [Assets](crate::Assets) collection.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, Property)]
pub struct HandleId(pub Uuid);
pub const DEFAULT_HANDLE_ID: HandleId =
HandleId(Uuid::from_u128(240940089166493627844978703213080810552));

impl HandleId {
pub fn new() -> HandleId {
HandleId(Uuid::new_v4())
}
}

/// A handle into a specific Asset of type `T`
///
/// Handles contain a unique id that corresponds to a specific asset in the [Assets](crate::Assets) collection.
#[derive(Properties)]
pub struct Handle<T>
where
Expand Down Expand Up @@ -156,6 +162,9 @@ impl<T> Copy for Handle<T> {}
unsafe impl<T> Send for Handle<T> {}
unsafe impl<T> Sync for Handle<T> {}

/// A non-generic version of [Handle]
///
/// This allows handles to be mingled in a cross asset context. For example, storing `Handle<A>` and `Handle<B>` in the same `HashSet<HandleUntyped>`.
#[derive(Hash, Copy, Clone, Eq, PartialEq, Debug)]
pub struct HandleUntyped {
pub id: HandleId,
Expand Down
7 changes: 5 additions & 2 deletions crates/bevy_asset/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[cfg(feature = "filesystem_watcher")]
mod filesystem_watcher;
mod asset_server;
mod assets;
#[cfg(feature = "filesystem_watcher")]
pub mod filesystem_watcher;
mod handle;
mod load_request;
mod loader;
Expand All @@ -12,6 +12,7 @@ pub use handle::*;
pub use load_request::*;
pub use loader::*;

/// The names of asset stages in an App Schedule
pub mod stage {
pub const LOAD_ASSETS: &str = "load_assets";
pub const ASSET_EVENTS: &str = "asset_events";
Expand All @@ -25,6 +26,8 @@ use bevy_app::{prelude::Plugin, AppBuilder};
use bevy_ecs::IntoQuerySystem;
use bevy_type_registry::RegisterType;

/// Adds support for Assets to an App. Assets are typed collections with change tracking, which are added as App Resources.
/// Examples of assets: textures, sounds, 3d models, maps, scenes
#[derive(Default)]
pub struct AssetPlugin;

Expand Down
4 changes: 3 additions & 1 deletion crates/bevy_asset/src/load_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use fs::File;
use io::Read;
use std::{fs, io, path::PathBuf};

/// A request from an [AssetServer](crate::AssetServer) to load an asset.
#[derive(Debug)]
pub struct LoadRequest {
pub path: PathBuf,
Expand All @@ -13,12 +14,13 @@ pub struct LoadRequest {
pub version: AssetVersion,
}

/// Handles load requests from an AssetServer
pub trait AssetLoadRequestHandler: Send + Sync + 'static {
fn handle_request(&self, load_request: &LoadRequest);
fn extensions(&self) -> &[&str];
}

pub struct ChannelAssetHandler<TLoader, TAsset>
pub(crate) struct ChannelAssetHandler<TLoader, TAsset>
where
TLoader: AssetLoader<TAsset>,
TAsset: 'static,
Expand Down
5 changes: 5 additions & 0 deletions crates/bevy_asset/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{
};
use thiserror::Error;

/// Errors that occur while loading assets
#[derive(Error, Debug)]
pub enum AssetLoadError {
#[error("Encountered an io error while loading asset.")]
Expand All @@ -18,6 +19,7 @@ pub enum AssetLoadError {
LoaderError(#[from] anyhow::Error),
}

/// A loader for a given asset of type `T`
pub trait AssetLoader<T>: Send + Sync + 'static {
fn from_bytes(&self, asset_path: &Path, bytes: Vec<u8>) -> Result<T, anyhow::Error>;
fn extensions(&self) -> &[&str];
Expand All @@ -30,13 +32,15 @@ pub trait AssetLoader<T>: Send + Sync + 'static {
}
}

/// The result of loading an asset of type `T`
pub struct AssetResult<T: 'static> {
pub result: Result<T, AssetLoadError>,
pub handle: Handle<T>,
pub path: PathBuf,
pub version: AssetVersion,
}

/// A channel to send and receive [AssetResult]s
pub struct AssetChannel<T: 'static> {
pub sender: Sender<AssetResult<T>>,
pub receiver: Receiver<AssetResult<T>>,
Expand All @@ -49,6 +53,7 @@ impl<T> AssetChannel<T> {
}
}

/// Reads [AssetResult]s from an [AssetChannel] and updates the [Assets] collection and [LoadState] accordingly
pub fn update_asset_storage_system<T: Resource>(
asset_channel: Res<AssetChannel<T>>,
asset_server: Res<AssetServer>,
Expand Down
4 changes: 3 additions & 1 deletion crates/bevy_audio/src/audio_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use bevy_ecs::Res;
use rodio::{Decoder, Device, Sink};
use std::{collections::VecDeque, io::Cursor, sync::RwLock};

/// Used to play audio on the current "audio device"
pub struct AudioOutput {
device: Device,
queue: RwLock<VecDeque<Handle<AudioSource>>>,
Expand Down Expand Up @@ -46,7 +47,8 @@ impl AudioOutput {
}
}

pub fn play_queued_audio_system(
/// Plays audio currently queued in the [AudioOutput] resource
pub(crate) fn play_queued_audio_system(
audio_sources: Res<Assets<AudioSource>>,
audio_output: Res<AudioOutput>,
) {
Expand Down
2 changes: 2 additions & 0 deletions crates/bevy_audio/src/audio_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use anyhow::Result;
use bevy_asset::AssetLoader;
use std::{path::Path, sync::Arc};

/// A source of audio data
#[derive(Clone)]
pub struct AudioSource {
pub bytes: Arc<Vec<u8>>,
Expand All @@ -13,6 +14,7 @@ impl AsRef<[u8]> for AudioSource {
}
}

/// Loads mp3 files as [AudioSource] [Assets](bevy_asset::Assets)
#[derive(Default)]
pub struct Mp3Loader;

Expand Down
1 change: 1 addition & 0 deletions crates/bevy_audio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use bevy_app::prelude::*;
use bevy_asset::AddAsset;
use bevy_ecs::IntoQuerySystem;

/// Adds support for audio playback to an App
#[derive(Default)]
pub struct AudioPlugin;

Expand Down
9 changes: 9 additions & 0 deletions crates/bevy_core/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ use bevy_math::{Mat4, Vec2, Vec3, Vec4};

pub use bevy_derive::Bytes;

/// Converts the implementing type to bytes by writing them to a given buffer
pub trait Bytes {
/// Converts the implementing type to bytes by writing them to a given buffer
fn write_bytes(&self, buffer: &mut [u8]);

/// The number of bytes that will be written when calling `write_bytes`
fn byte_len(&self) -> usize;
}

/// A trait that indicates that it is safe to cast the type to a byte array reference.
pub unsafe trait Byteable
where
Self: Sized,
Expand All @@ -27,11 +32,15 @@ where
}
}

/// Reads the implementing type as a byte array reference
pub trait AsBytes {
/// Reads the implementing type as a byte array reference
fn as_bytes(&self) -> &[u8];
}

/// Converts a byte array to `Self`
pub trait FromBytes {
/// Converts a byte array to `Self`
fn from_bytes(bytes: &[u8]) -> Self;
}

Expand Down
4 changes: 3 additions & 1 deletion crates/bevy_core/src/float_ord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use std::{
ops::Neg,
};

// working around the famous "rust float ordering" problem
/// A wrapper type that enables ordering floats. This is a work around for the famous "rust float ordering" problem.
/// By using it, you acknowledge that sorting NaN is undefined according to spec. This implementation treats NaN as the
/// "smallest" float.
#[derive(Debug, Copy, Clone, PartialOrd)]
pub struct FloatOrd(pub f32);

Expand Down
Loading

0 comments on commit 3d09459

Please sign in to comment.