<commit_before>#[link(name="rm", vers="1.0.0", author="Arcterus")];

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Arcterus <arcterus@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

extern mod extra;

use std::os;
use std::io::{stdin,stderr,stdio,fs,buffered,io_error};
use extra::getopts::groups;

enum InteractiveMode {
    InteractiveNone,
    InteractiveOnce,
    InteractiveAlways
}

impl Eq for InteractiveMode {
    fn eq(&self, other: &InteractiveMode) -> bool {
        match (*self, *other) {
            (InteractiveNone, InteractiveNone) |
            (InteractiveOnce, InteractiveOnce) |
            (InteractiveAlways, InteractiveAlways) => true,
            _ => false
        }
    }

    fn ne(&self, other: &InteractiveMode) -> bool {
        !self.eq(other)
    }
}

fn main() {
    let args = os::args();
    let program = args[0].clone();

    // TODO: make getopts support -R in addition to -r
    let opts = ~[
        groups::optflag("f", "force", "ignore nonexistent files and arguments, never prompt"),
        groups::optflag("i", "", "prompt before every removal"),
        groups::optflag("I", "", "prompt once before removing more than three files, or when removing recursively.  Less intrusive than -i, while still giving some protection against most mistakes"),
        groups::optflagopt("", "interactive", "prompt according to WHEN: never, once (-I), or always (-i).  Without WHEN, prompts always", "WHEN"),
        groups::optflag("", "one-file-system", "when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument (NOT IMPLEMENTED)"),
        groups::optflag("", "no-preserve-root", "do not treat '/' specially"),
        groups::optflag("", "preserve-root", "do not remove '/' (default)"),
        groups::optflag("r", "recursive", "remove directories and their contents recursively"),
        groups::optflag("d", "dir", "remove empty directories"),
        groups::optflag("v", "verbose", "explain what is being done"),
        groups::optflag("", "help", "display this help and exit"),
        groups::optflag("", "version", "output version information and exit")
    ];
    let matches = match groups::getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(f) => {
            writeln!(&mut stderr() as &mut Writer,
                     "{}", f.to_err_msg());
            os::set_exit_status(1);
            return
        }
    };
    if matches.opt_present("help") {
        println("rm 1.0.0");
        println("");
        println("Usage:");
        println!("  {0:s} [OPTION]... [FILE]...", program);
        println("");
        print(groups::usage("Remove (unlink) the FILE(s).", opts));
        println("");
        println("By default, rm does not remove directories.  Use the --recursive (-r)");
        println("option to remove each listed directory, too, along with all of its contents");
        println("");
        println("To remove a file whose name starts with a '-', for example '-foo',");
        println("use one of these commands:");
        println("rm -- -foo");
        println("");
        println("rm ./-foo");
        println("");
        println("Note that if you use rm to remove a file, it might be possible to recover");
        println("some of its contents, given sufficient expertise and/or time.  For greater");
        println("assurance that the contents are truly unrecoverable, consider using shred.");
    } else if matches.opt_present("version") {
        println("rm 1.0.0");
    } else if matches.free.is_empty() {
        writeln!(&mut stderr() as &mut Writer, "Missing an argument");
        writeln!(&mut stderr() as &mut Writer,
                 "For help, try '{0:s} --help'", program);
        os::set_exit_status(1);
    } else {
        let force = matches.opt_present("force");
        let interactive =
            if matches.opt_present("i") {
                InteractiveAlways
            } else if matches.opt_present("I") {
                InteractiveOnce
            } else if matches.opt_present("interactive") {
                match matches.opt_str("interactive").unwrap() {
                    ~"none" => InteractiveNone,
                    ~"once" => InteractiveOnce,
                    ~"always" => InteractiveAlways,
                    val => {
                        writeln!(&mut stderr() as &mut Writer,
                                 "Invalid argument to interactive ({})", val);
                        os::set_exit_status(1);
                        return
                    }
                }
            } else {
                InteractiveNone
            };
        let one_fs = matches.opt_present("one-file-system");
        let preserve_root = !matches.opt_present("no-preserve-root");
        let recursive = matches.opt_present("recursive");
        let dir = matches.opt_present("dir");
        let verbose = matches.opt_present("verbose");
        if interactive == InteractiveOnce && (recursive || matches.free.len() > 3) {
            let msg =
                if recursive {
                    "Remove all arguments recursively? "
                } else {
                    "Remove all arguments? "
                };
            if !prompt(msg) {
                return;
            }
        }
        remove(matches.free, force, interactive, one_fs, preserve_root,
               recursive, dir, verbose);
    }
}

// TODO: implement one-file-system
fn remove(files: &[~str], force: bool, interactive: InteractiveMode, one_fs: bool, preserve_root: bool, recursive: bool, dir: bool, verbose: bool) {
    for filename in files.iter() {
        let file = Path::new(filename.to_owned());
        if file.exists() {
            if file.is_dir() {
                if recursive && (*filename != ~"/" || !preserve_root) {
                    remove(fs::walk_dir(&file).map(|x| x.as_str().unwrap().to_owned()).to_owned_vec(), force, interactive, one_fs, preserve_root, recursive, dir, verbose);
                    remove_dir(&file, *filename, interactive, verbose);
                } else if dir && (*filename != ~"/" || !preserve_root) {
                    remove_dir(&file, *filename, interactive, verbose);
                } else {
                    if recursive {
                        writeln!(&mut stderr() as &mut Writer,
                                 "Could not remove directory '{}'",
                                 *filename);
                    } else {
                        writeln!(&mut stderr() as &mut Writer,
                                 "Could not remove directory '{}' (did you mean to pass '-r'?)",
                                 *filename);
                    }
                    os::set_exit_status(1);
                }
            } else {
                remove_file(&file, *filename, interactive, verbose);
            }
        } else if !force {
            writeln!(&mut stderr() as &mut Writer,
                     "No such file or directory '{}'", *filename);
            os::set_exit_status(1);
        }
    }
}

fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) {
    let response =
        if interactive == InteractiveAlways {
            prompt_file(path, name)
        } else {
            true
        };
    if response {
        io_error::cond.trap(|_| {
            writeln!(&mut stderr() as &mut Writer,
                     "Could not remove directory '{}'", name);
            os::set_exit_status(1);
        }).inside(|| {
            fs::rmdir(path);
            if verbose {
                println!("Removed '{}'", name);
            }
        });
    }
}

fn remove_file(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) {
    let response =
        if interactive == InteractiveAlways {
            prompt_file(path, name)
        } else {
            true
        };
    if response {
        io_error::cond.trap(|_| {
            writeln!(&mut stderr() as &mut Writer,
                     "Could not remove file '{}'", name);
            os::set_exit_status(1);
        }).inside(|| {
            fs::unlink(path);
            if verbose {
                println!("Removed '{}'", name);
            }
        });
    }
}

fn prompt_file(path: &Path, name: &str) -> bool {
    if path.is_dir() {
        prompt(format!("Remove directory '{}'? ", name))
    } else {
        prompt(format!("Remove file '{}'? ", name))
    }
}

fn prompt(msg: &str) -> bool {
    print(msg);
    read_prompt()
}

fn read_prompt() -> bool {
    stdio::flush();
    match buffered::BufferedReader::new(stdin()).read_line() {
        Some(line) => {
            match line.char_at(0) {
                'y' | 'Y' => true,
                'n' | 'N' => false,
                _ => {
                    print("Please enter either Y or N: ");
                    read_prompt()
                }
            }
        }
        None => true
    }
}

<commit_msg>Added the aliases -h and -V for --help and --version to rm<commit_after>#[link(name="rm", vers="1.0.0", author="Arcterus")];

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Arcterus <arcterus@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

extern mod extra;

use std::os;
use std::io::{stdin,stderr,stdio,fs,buffered,io_error};
use extra::getopts::groups;

enum InteractiveMode {
    InteractiveNone,
    InteractiveOnce,
    InteractiveAlways
}

impl Eq for InteractiveMode {
    fn eq(&self, other: &InteractiveMode) -> bool {
        match (*self, *other) {
            (InteractiveNone, InteractiveNone) |
            (InteractiveOnce, InteractiveOnce) |
            (InteractiveAlways, InteractiveAlways) => true,
            _ => false
        }
    }

    fn ne(&self, other: &InteractiveMode) -> bool {
        !self.eq(other)
    }
}

fn main() {
    let args = os::args();
    let program = args[0].clone();

    // TODO: make getopts support -R in addition to -r
    let opts = ~[
        groups::optflag("f", "force", "ignore nonexistent files and arguments, never prompt"),
        groups::optflag("i", "", "prompt before every removal"),
        groups::optflag("I", "", "prompt once before removing more than three files, or when removing recursively.  Less intrusive than -i, while still giving some protection against most mistakes"),
        groups::optflagopt("", "interactive", "prompt according to WHEN: never, once (-I), or always (-i).  Without WHEN, prompts always", "WHEN"),
        groups::optflag("", "one-file-system", "when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument (NOT IMPLEMENTED)"),
        groups::optflag("", "no-preserve-root", "do not treat '/' specially"),
        groups::optflag("", "preserve-root", "do not remove '/' (default)"),
        groups::optflag("r", "recursive", "remove directories and their contents recursively"),
        groups::optflag("d", "dir", "remove empty directories"),
        groups::optflag("v", "verbose", "explain what is being done"),
        groups::optflag("h", "help", "display this help and exit"),
        groups::optflag("V", "version", "output version information and exit")
    ];
    let matches = match groups::getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(f) => {
            writeln!(&mut stderr() as &mut Writer,
                     "{}", f.to_err_msg());
            os::set_exit_status(1);
            return
        }
    };
    if matches.opt_present("help") {
        println("rm 1.0.0");
        println("");
        println("Usage:");
        println!("  {0:s} [OPTION]... [FILE]...", program);
        println("");
        print(groups::usage("Remove (unlink) the FILE(s).", opts));
        println("");
        println("By default, rm does not remove directories.  Use the --recursive (-r)");
        println("option to remove each listed directory, too, along with all of its contents");
        println("");
        println("To remove a file whose name starts with a '-', for example '-foo',");
        println("use one of these commands:");
        println("rm -- -foo");
        println("");
        println("rm ./-foo");
        println("");
        println("Note that if you use rm to remove a file, it might be possible to recover");
        println("some of its contents, given sufficient expertise and/or time.  For greater");
        println("assurance that the contents are truly unrecoverable, consider using shred.");
    } else if matches.opt_present("version") {
        println("rm 1.0.0");
    } else if matches.free.is_empty() {
        writeln!(&mut stderr() as &mut Writer, "Missing an argument");
        writeln!(&mut stderr() as &mut Writer,
                 "For help, try '{0:s} --help'", program);
        os::set_exit_status(1);
    } else {
        let force = matches.opt_present("force");
        let interactive =
            if matches.opt_present("i") {
                InteractiveAlways
            } else if matches.opt_present("I") {
                InteractiveOnce
            } else if matches.opt_present("interactive") {
                match matches.opt_str("interactive").unwrap() {
                    ~"none" => InteractiveNone,
                    ~"once" => InteractiveOnce,
                    ~"always" => InteractiveAlways,
                    val => {
                        writeln!(&mut stderr() as &mut Writer,
                                 "Invalid argument to interactive ({})", val);
                        os::set_exit_status(1);
                        return
                    }
                }
            } else {
                InteractiveNone
            };
        let one_fs = matches.opt_present("one-file-system");
        let preserve_root = !matches.opt_present("no-preserve-root");
        let recursive = matches.opt_present("recursive");
        let dir = matches.opt_present("dir");
        let verbose = matches.opt_present("verbose");
        if interactive == InteractiveOnce && (recursive || matches.free.len() > 3) {
            let msg =
                if recursive {
                    "Remove all arguments recursively? "
                } else {
                    "Remove all arguments? "
                };
            if !prompt(msg) {
                return;
            }
        }
        remove(matches.free, force, interactive, one_fs, preserve_root,
               recursive, dir, verbose);
    }
}

// TODO: implement one-file-system
fn remove(files: &[~str], force: bool, interactive: InteractiveMode, one_fs: bool, preserve_root: bool, recursive: bool, dir: bool, verbose: bool) {
    for filename in files.iter() {
        let file = Path::new(filename.to_owned());
        if file.exists() {
            if file.is_dir() {
                if recursive && (*filename != ~"/" || !preserve_root) {
                    remove(fs::walk_dir(&file).map(|x| x.as_str().unwrap().to_owned()).to_owned_vec(), force, interactive, one_fs, preserve_root, recursive, dir, verbose);
                    remove_dir(&file, *filename, interactive, verbose);
                } else if dir && (*filename != ~"/" || !preserve_root) {
                    remove_dir(&file, *filename, interactive, verbose);
                } else {
                    if recursive {
                        writeln!(&mut stderr() as &mut Writer,
                                 "Could not remove directory '{}'",
                                 *filename);
                    } else {
                        writeln!(&mut stderr() as &mut Writer,
                                 "Could not remove directory '{}' (did you mean to pass '-r'?)",
                                 *filename);
                    }
                    os::set_exit_status(1);
                }
            } else {
                remove_file(&file, *filename, interactive, verbose);
            }
        } else if !force {
            writeln!(&mut stderr() as &mut Writer,
                     "No such file or directory '{}'", *filename);
            os::set_exit_status(1);
        }
    }
}

fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) {
    let response =
        if interactive == InteractiveAlways {
            prompt_file(path, name)
        } else {
            true
        };
    if response {
        io_error::cond.trap(|_| {
            writeln!(&mut stderr() as &mut Writer,
                     "Could not remove directory '{}'", name);
            os::set_exit_status(1);
        }).inside(|| {
            fs::rmdir(path);
            if verbose {
                println!("Removed '{}'", name);
            }
        });
    }
}

fn remove_file(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) {
    let response =
        if interactive == InteractiveAlways {
            prompt_file(path, name)
        } else {
            true
        };
    if response {
        io_error::cond.trap(|_| {
            writeln!(&mut stderr() as &mut Writer,
                     "Could not remove file '{}'", name);
            os::set_exit_status(1);
        }).inside(|| {
            fs::unlink(path);
            if verbose {
                println!("Removed '{}'", name);
            }
        });
    }
}

fn prompt_file(path: &Path, name: &str) -> bool {
    if path.is_dir() {
        prompt(format!("Remove directory '{}'? ", name))
    } else {
        prompt(format!("Remove file '{}'? ", name))
    }
}

fn prompt(msg: &str) -> bool {
    print(msg);
    read_prompt()
}

fn read_prompt() -> bool {
    stdio::flush();
    match buffered::BufferedReader::new(stdin()).read_line() {
        Some(line) => {
            match line.char_at(0) {
                'y' | 'Y' => true,
                'n' | 'N' => false,
                _ => {
                    print("Please enter either Y or N: ");
                    read_prompt()
                }
            }
        }
        None => true
    }
}

<|endoftext|>


<commit_before>// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use euclid::rect::{Rect, TypedRect};
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use euclid::point::Point2D;
use geometry::{DevicePixel, LayerPixel};
use layers::{BufferRequest, Layer, LayerBuffer};
use std::rc::Rc;

pub struct Scene<T> {
    pub root: Option<Rc<Layer<T>>>,
    pub viewport: TypedRect<DevicePixel, f32>,

    /// The scene scale, to allow for zooming and high-resolution painting.
    pub scale: ScaleFactor<LayerPixel, DevicePixel, f32>,
}

impl<T> Scene<T> {
    pub fn new(viewport: TypedRect<DevicePixel, f32>) -> Scene<T> {
        Scene {
            root: None,
            viewport: viewport,
            scale: ScaleFactor::new(1.0),
        }
    }

    pub fn get_buffer_requests_for_layer(&mut self,
                                         layer: Rc<Layer<T>>,
                                         dirty_rect: TypedRect<LayerPixel, f32>,
                                         viewport_rect: TypedRect<LayerPixel, f32>,
                                         layers_and_requests: &mut Vec<(Rc<Layer<T>>,
                                                                        Vec<BufferRequest>)>,
                                         unused_buffers: &mut Vec<Box<LayerBuffer>>) {
        // Get buffers for this layer, in global (screen) coordinates.
        let requests = layer.get_buffer_requests(dirty_rect,
                                                 viewport_rect,
                                                 self.scale);
        if !requests.is_empty() {
            layers_and_requests.push((layer.clone(), requests));
        }
        unused_buffers.extend(layer.collect_unused_buffers().into_iter());

        // If this layer masks its children, we don't need to ask for tiles outside the
        // boundaries of this layer.
        let mut child_dirty_rect = dirty_rect;
        if *layer.masks_to_bounds.borrow() {
            // FIXME: Likely because of rust bug rust-lang/rust#16822, caching the intersected
            // rect and reusing it causes a crash in rustc. When that bug is resolved this code
            // should simply reuse a cached version of the intersection.
            match layer.transform_state.borrow().screen_rect {
                Some(ref screen_rect) => {
                    child_dirty_rect =
                        match dirty_rect.to_untyped().intersection(&screen_rect.rect) {
                            Some(child_dirty_rect) => {
                                Rect::from_untyped(&child_dirty_rect)
                            }
                            None => {
                                // The layer is entirely clipped by the dirty
                                // rect, so early exit.
                                return;
                            }
                        }
                }
                None => {
                    // The layer is entirely clipped, and it masks children,
                    // so early exit.
                    return;
                }
            }
        }

        for kid in layer.children().iter() {
            self.get_buffer_requests_for_layer(kid.clone(),
                                               child_dirty_rect,
                                               viewport_rect,
                                               layers_and_requests,
                                               unused_buffers);
        }
    }

    pub fn get_buffer_requests(&mut self,
                               requests: &mut Vec<(Rc<Layer<T>>, Vec<BufferRequest>)>,
                               unused_buffers: &mut Vec<Box<LayerBuffer>>) {
        let root_layer = match self.root {
            Some(ref root_layer) => root_layer.clone(),
            None => return,
        };

        self.get_buffer_requests_for_layer(root_layer.clone(),
                                           *root_layer.bounds.borrow(),
                                           *root_layer.bounds.borrow(),
                                           requests,
                                           unused_buffers);
    }

    pub fn mark_layer_contents_as_changed_recursively_for_layer(&self, layer: Rc<Layer<T>>) {
        layer.contents_changed();
        for kid in layer.children().iter() {
            self.mark_layer_contents_as_changed_recursively_for_layer(kid.clone());
        }
    }

    pub fn mark_layer_contents_as_changed_recursively(&self) {
        let root_layer = match self.root {
            Some(ref root_layer) => root_layer.clone(),
            None => return,
        };
        self.mark_layer_contents_as_changed_recursively_for_layer(root_layer);
    }

    pub fn set_root_layer_size(&self, new_size: TypedSize2D<DevicePixel, f32>) {
        match self.root {
            Some(ref root_layer) => {
                *root_layer.bounds.borrow_mut() = Rect::new(Point2D::zero(), new_size / self.scale);
            },
            None => {},
        }
    }

    /// Calculate the amount of memory used by all the layers in the
    /// scene graph. The memory may be allocated on the heap or in GPU memory.
    pub fn get_memory_usage(&self) -> usize {
        match self.root {
            Some(ref root_layer) => root_layer.get_memory_usage(),
            None => 0,
        }
    }
}

<commit_msg>Simplify some code and remove an inaccurate comment<commit_after>// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use euclid::rect::{Rect, TypedRect};
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use euclid::point::Point2D;
use geometry::{DevicePixel, LayerPixel};
use layers::{BufferRequest, Layer, LayerBuffer};
use std::rc::Rc;

pub struct Scene<T> {
    pub root: Option<Rc<Layer<T>>>,
    pub viewport: TypedRect<DevicePixel, f32>,

    /// The scene scale, to allow for zooming and high-resolution painting.
    pub scale: ScaleFactor<LayerPixel, DevicePixel, f32>,
}

impl<T> Scene<T> {
    pub fn new(viewport: TypedRect<DevicePixel, f32>) -> Scene<T> {
        Scene {
            root: None,
            viewport: viewport,
            scale: ScaleFactor::new(1.0),
        }
    }

    pub fn get_buffer_requests_for_layer(&mut self,
                                         layer: Rc<Layer<T>>,
                                         dirty_rect: TypedRect<LayerPixel, f32>,
                                         viewport_rect: TypedRect<LayerPixel, f32>,
                                         layers_and_requests: &mut Vec<(Rc<Layer<T>>,
                                                                        Vec<BufferRequest>)>,
                                         unused_buffers: &mut Vec<Box<LayerBuffer>>) {
        // Get buffers for this layer, in global (screen) coordinates.
        let requests = layer.get_buffer_requests(dirty_rect, viewport_rect, self.scale);
        if !requests.is_empty() {
            layers_and_requests.push((layer.clone(), requests));
        }
        unused_buffers.extend(layer.collect_unused_buffers().into_iter());

        // If this layer masks its children, we don't need to ask for tiles outside the
        // boundaries of this layer.
        let child_dirty_rect = if !*layer.masks_to_bounds.borrow() {
            dirty_rect
        } else {
            match layer.transform_state.borrow().screen_rect {
                Some(ref screen_rect) => {
                    match dirty_rect.to_untyped().intersection(&screen_rect.rect) {
                        Some(ref child_dirty_rect) => Rect::from_untyped(child_dirty_rect),
                        None => return, // The layer is entirely outside the dirty rect.
                    }
                },
                None => return, // The layer is entirely clipped.
            }
        };

        for kid in layer.children().iter() {
            self.get_buffer_requests_for_layer(kid.clone(),
                                               child_dirty_rect,
                                               viewport_rect,
                                               layers_and_requests,
                                               unused_buffers);
        }
    }

    pub fn get_buffer_requests(&mut self,
                               requests: &mut Vec<(Rc<Layer<T>>, Vec<BufferRequest>)>,
                               unused_buffers: &mut Vec<Box<LayerBuffer>>) {
        let root_layer = match self.root {
            Some(ref root_layer) => root_layer.clone(),
            None => return,
        };

        self.get_buffer_requests_for_layer(root_layer.clone(),
                                           *root_layer.bounds.borrow(),
                                           *root_layer.bounds.borrow(),
                                           requests,
                                           unused_buffers);
    }

    pub fn mark_layer_contents_as_changed_recursively_for_layer(&self, layer: Rc<Layer<T>>) {
        layer.contents_changed();
        for kid in layer.children().iter() {
            self.mark_layer_contents_as_changed_recursively_for_layer(kid.clone());
        }
    }

    pub fn mark_layer_contents_as_changed_recursively(&self) {
        let root_layer = match self.root {
            Some(ref root_layer) => root_layer.clone(),
            None => return,
        };
        self.mark_layer_contents_as_changed_recursively_for_layer(root_layer);
    }

    pub fn set_root_layer_size(&self, new_size: TypedSize2D<DevicePixel, f32>) {
        match self.root {
            Some(ref root_layer) => {
                *root_layer.bounds.borrow_mut() = Rect::new(Point2D::zero(), new_size / self.scale);
            },
            None => {},
        }
    }

    /// Calculate the amount of memory used by all the layers in the
    /// scene graph. The memory may be allocated on the heap or in GPU memory.
    pub fn get_memory_usage(&self) -> usize {
        match self.root {
            Some(ref root_layer) => root_layer.get_memory_usage(),
            None => 0,
        }
    }
}

<|endoftext|>


<commit_before>pub type BoxedScene<EventT, RendererT, EngineDataT> = Box<Scene<EventT, RendererT, EngineDataT> + 'static>;
pub type SceneChangeCallback<EventT, RendererT, EngineDataT> = Box<Fn(&mut RendererT, &mut EngineDataT) -> BoxedScene<EventT, RendererT, EngineDataT>>;

pub trait Scene<EventT, RendererT, EngineDataT> {
    fn render(&self, renderer: &mut RendererT, engine_data: &EngineDataT, tick: u64);
    fn handle_event(&mut self, event: &EventT, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64) -> Option<SceneChangeEvent<EventT, RendererT, EngineDataT>>;
    fn think(&mut self, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64) -> Option<SceneChangeEvent<EventT, RendererT, EngineDataT>>;
}

pub enum SceneChangeEvent<EventT, RendererT, EngineDataT> {
    PushScene(SceneChangeCallback<EventT, RendererT, EngineDataT>),
    SwapScene(SceneChangeCallback<EventT, RendererT, EngineDataT>),
    PopScene,
}

pub struct SceneStack<EventT, RendererT, EngineDataT> {
    scenes: Vec<BoxedScene<EventT, RendererT, EngineDataT>>
}

impl<EventT, RendererT, EngineDataT> SceneStack<EventT, RendererT, EngineDataT> {

    pub fn new() -> SceneStack<EngineDataT, EventT, RendererT> {
        SceneStack {
            scenes: vec![]
        }
    }

    pub fn is_empty(&self) -> bool {
        self.scenes.len() == 0
    }

    pub fn push(&mut self, scene: BoxedScene<EventT, RendererT, EngineDataT>) {
        self.scenes.push(scene)
    }

    pub fn swap(&mut self, scene: BoxedScene<EventT, RendererT, EngineDataT>) -> Option<BoxedScene<EventT, RendererT, EngineDataT>> {
        let old_scene = self.scenes.pop();
        self.scenes.push(scene);
        old_scene
    }

    pub fn pop(&mut self) -> Option<BoxedScene<EventT, RendererT, EngineDataT>> {
        self.scenes.pop()
    }

    pub fn render(&mut self, renderer: &mut RendererT, engine_data: &EngineDataT, tick: u64) {
        let maybe_last_scene = self.scenes.pop();
        match maybe_last_scene {
            Some(scene) => {
                scene.render(renderer, engine_data, tick);
                self.scenes.push(scene);
            },
            None => ()
        }
    }

    pub fn handle_event(&mut self, event: &EventT, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64) {
        let maybe_last_scene = self.scenes.pop();
        match maybe_last_scene {
            Some(mut scene) => scene.handle_event(event, renderer, engine_data, tick),
            None => None
        };
    }

    pub fn think(&mut self, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64) {
        let maybe_last_scene = self.scenes.pop();
        let event = match maybe_last_scene {
            Some(mut scene) => {
                let event = scene.think(renderer, engine_data, tick);
                self.scenes.push(scene);
                event
            },
            None => None
        };

        match event {
            Some(SceneChangeEvent::PushScene(callback)) => {
                self.push(callback(renderer, engine_data));
            },
            Some(SceneChangeEvent::SwapScene(callback)) => {
                self.swap(callback(renderer, engine_data));
            },
            Some(SceneChangeEvent::PopScene) => {
                self.pop();
            },
            None => ()
        };
    }
}
<commit_msg>Slight correction<commit_after>pub type BoxedScene<EventT, RendererT, EngineDataT> = Box<Scene<EventT, RendererT, EngineDataT> + 'static>;
pub type SceneChangeCallback<EventT, RendererT, EngineDataT> = Box<Fn(&mut RendererT, &mut EngineDataT) -> BoxedScene<EventT, RendererT, EngineDataT>>;

pub trait Scene<EventT, RendererT, EngineDataT> {
    fn render(&self, renderer: &mut RendererT, engine_data: &EngineDataT, tick: u64);
    fn handle_event(&mut self, event: &EventT, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64);
    fn think(&mut self, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64) -> Option<SceneChangeEvent<EventT, RendererT, EngineDataT>>;
}

pub enum SceneChangeEvent<EventT, RendererT, EngineDataT> {
    PushScene(SceneChangeCallback<EventT, RendererT, EngineDataT>),
    SwapScene(SceneChangeCallback<EventT, RendererT, EngineDataT>),
    PopScene,
}

pub struct SceneStack<EventT, RendererT, EngineDataT> {
    scenes: Vec<BoxedScene<EventT, RendererT, EngineDataT>>
}

impl<EventT, RendererT, EngineDataT> SceneStack<EventT, RendererT, EngineDataT> {

    pub fn new() -> SceneStack<EngineDataT, EventT, RendererT> {
        SceneStack {
            scenes: vec![]
        }
    }

    pub fn is_empty(&self) -> bool {
        self.scenes.len() == 0
    }

    pub fn push(&mut self, scene: BoxedScene<EventT, RendererT, EngineDataT>) {
        self.scenes.push(scene)
    }

    pub fn swap(&mut self, scene: BoxedScene<EventT, RendererT, EngineDataT>) -> Option<BoxedScene<EventT, RendererT, EngineDataT>> {
        let old_scene = self.scenes.pop();
        self.scenes.push(scene);
        old_scene
    }

    pub fn pop(&mut self) -> Option<BoxedScene<EventT, RendererT, EngineDataT>> {
        self.scenes.pop()
    }

    pub fn render(&mut self, renderer: &mut RendererT, engine_data: &EngineDataT, tick: u64) {
        let maybe_last_scene = self.scenes.pop();
        match maybe_last_scene {
            Some(scene) => {
                scene.render(renderer, engine_data, tick);
                self.scenes.push(scene);
            },
            None => ()
        }
    }

    pub fn handle_event(&mut self, event: &EventT, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64) {
        let maybe_last_scene = self.scenes.pop();
        match maybe_last_scene {
            Some(mut scene) => scene.handle_event(event, renderer, engine_data, tick),
            None => ()
        };
    }

    pub fn think(&mut self, renderer: &mut RendererT, engine_data: &mut EngineDataT, tick: u64) {
        let maybe_last_scene = self.scenes.pop();
        let event = match maybe_last_scene {
            Some(mut scene) => {
                let event = scene.think(renderer, engine_data, tick);
                self.scenes.push(scene);
                event
            },
            None => None
        };

        match event {
            Some(SceneChangeEvent::PushScene(callback)) => {
                self.push(callback(renderer, engine_data));
            },
            Some(SceneChangeEvent::SwapScene(callback)) => {
                self.swap(callback(renderer, engine_data));
            },
            Some(SceneChangeEvent::PopScene) => {
                self.pop();
            },
            None => ()
        };
    }
}
<|endoftext|>


<commit_before>use std::ops;

use cgmath::Ortho;
use froggy::Pointer;
use mint;

use {Object, Operation, Node, SubNode,
     Scene, ShadowProjection, Transform};
use factory::{Geometry, ShadowMap, Texture};

/// Color represented by 4-bytes hex number.
pub type Color = u32;

/// Background type.
#[derive(Clone, Debug, PartialEq)]
pub enum Background {
    /// Basic solid color background.
    Color(Color),
    //TODO: texture, cubemap
}

/// Material is the enhancement of Texture that is used to setup appearence of [`Mesh`](struct.Mesh.html).
#[derive(Clone, Debug)]
pub enum Material {
    /// Basic wireframe with specific `Color`.
    #[allow(missing_docs)]
    LineBasic { color: Color },
    /// Basic material with color, optional `Texture` and optional wireframe mode.
    #[allow(missing_docs)]
    MeshBasic { color: Color, map: Option<Texture<[f32; 4]>>, wireframe: bool },
    /// Lambertian diffuse reflection. This technique causes all closed polygons
    /// (such as a triangle within a 3D mesh) to reflect light equally in all
    /// directions when rendered.
    #[allow(missing_docs)]
    MeshLambert { color: Color, flat: bool },
    /// Material that uses Phong reflection model.
    #[allow(missing_docs)]
    MeshPhong { color: Color, glossiness: f32 },
    /// 2D Sprite.
    #[allow(missing_docs)]
    Sprite { map: Texture<[f32; 4]> },
}

/// Position, rotation and scale of the scene [`Node`](struct.Node.html).
#[derive(Clone, Debug)]
pub struct NodeTransform {
    /// Position.
    pub position: mint::Point3<f32>,
    /// Orientation.
    pub orientation: mint::Quaternion<f32>,
    /// Scale.
    pub scale: f32,
}

impl From<Transform> for NodeTransform {
    fn from(tf: Transform) -> Self {
        let p: [f32; 3] = tf.disp.into();
        let v: [f32; 3] = tf.rot.v.into();
        NodeTransform {
            position: p.into(),
            orientation: mint::Quaternion {
                v: v.into(),
                s: tf.rot.s,
            },
            scale: tf.scale,
        }
    }
}

/// General information about scene [`Node`](struct.Node.html).
#[derive(Clone, Debug)]
pub struct NodeInfo {
    /// Relative to parent transform.
    pub transform: NodeTransform,
    /// World transform (relative to the world's origin).
    pub world_transform: NodeTransform,
    /// Is `Node` visible by cameras or not?
    pub visible: bool,
    /// The same as `visible`, used internally.
    pub world_visible: bool,
    /// Material in case this `Node` has it.
    pub material: Option<Material>,
}

impl Object {
    /// Invisible objects are not rendered by cameras.
    pub fn set_visible(&mut self, visible: bool) {
        let msg = Operation::SetVisible(visible);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Rotates object in the specific direction of `target`.
    pub fn look_at<P>(&mut self, eye: P, target: P, up: Option<mint::Vector3<f32>>)
    where P: Into<[f32; 3]>
    {
        use cgmath::{InnerSpace, Point3, Quaternion, Rotation, Vector3};
        //TEMP
        let p: [[f32; 3]; 2] = [eye.into(), target.into()];
        let dir = (Point3::from(p[0]) - Point3::from(p[1])).normalize();
        let z = Vector3::unit_z();
        let up = match up {
            Some(v) => {
                let vf: [f32; 3] = v.into();
                Vector3::from(vf).normalize()
            },
            None if dir.dot(z).abs() < 0.99 => z,
            None => Vector3::unit_y(),
        };
        let q = Quaternion::look_at(dir, up).invert();
        let qv: [f32; 3] = q.v.into();
        let rot = mint::Quaternion {
            s: q.s,
            v: qv.into(),
        };
        self.set_transform(p[0], rot, 1.0);
    }

    /// Set both position, orientation and scale.
    pub fn set_transform<P, Q>(&mut self, pos: P, rot: Q, scale: f32) where
        P: Into<mint::Point3<f32>>,
        Q: Into<mint::Quaternion<f32>>,
    {
        let msg = Operation::SetTransform(Some(pos.into()), Some(rot.into()), Some(scale));
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Set position.
    pub fn set_position<P>(&mut self, pos: P) where P: Into<mint::Point3<f32>> {
        let msg = Operation::SetTransform(Some(pos.into()), None, None);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Set orientation.
    pub fn set_orientation<Q>(&mut self, rot: Q) where Q: Into<mint::Quaternion<f32>> {
        let msg = Operation::SetTransform(None, Some(rot.into()), None);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Set scale.
    pub fn set_scale(&mut self, scale: f32) {
        let msg = Operation::SetTransform(None, None, Some(scale));
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Get actual information about itself from the `scene`.
    /// # Panics
    /// Panics if `scene` doesn't have this `Object`.
    pub fn sync(&mut self, scene: &Scene) -> NodeInfo {
        let mut hub = scene.hub.lock().unwrap();
        hub.process_messages();
        let node = &hub.nodes[&self.node];
        assert_eq!(node.scene_id, Some(scene.unique_id));
        NodeInfo {
            transform: node.transform.into(),
            world_transform: node.world_transform.into(),
            visible: node.visible,
            world_visible: node.world_visible,
            material: match node.sub_node {
                SubNode::Visual(ref mat, _) => Some(mat.clone()),
                _ => None,
            },
        }
    }
}

/// Groups are used to combine several other objects or groups to work with them
/// as with a single entity.
pub struct Group {
    object: Object,
}

impl Group {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        Group {
            object,
        }
    }

    /// Add new [`Object`](struct.Object.html) to the group.
    pub fn add<P: AsRef<Pointer<Node>>>(&mut self, child: &P) {
        let msg = Operation::SetParent(self.object.node.clone());
        let _ = self.object.tx.send((child.as_ref().downgrade(), msg));
    }
}

/// [`Geometry`](struct.Geometry.html) with some [`Material`](struct.Material.html).
pub struct Mesh {
    object: Object,
    _geometry: Option<Geometry>,
}

impl Mesh {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        Mesh {
            object,
            _geometry: None,
        }
    }

    /// Set mesh material.
    pub fn set_material(&mut self, material: Material) {
        let msg = Operation::SetMaterial(material);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }
}

/// Two-dimensional bitmap that is integrated into a larger scene.
pub struct Sprite {
    object: Object,
}

impl Sprite {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        Sprite {
            object,
        }
    }

    /// Set area of the texture to render. It can be used in sequential animations.
    pub fn set_texel_range<P, S>(&mut self, base: P, size: S) where
        P: Into<mint::Point2<i16>>,
        S: Into<mint::Vector2<u16>>,
    {
        let msg = Operation::SetTexelRange(base.into(), size.into());
        let _ = self.object.tx.send((self.node.downgrade(), msg));
    }
}

/// Omni-directional, fixed-intensity and fixed-color light source that affects
/// all objects in the scene equally.
pub struct AmbientLight {
    object: Object,
}

impl AmbientLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        AmbientLight {
            object,
        }
    }
}

/// The light source that illuminates all objects equally from a given direction,
/// like an area light of infinite size and infinite distance from the scene;
/// there is shading, but cannot be any distance falloff.
pub struct DirectionalLight {
    object: Object,
    shadow: Option<ShadowMap>,
}

impl DirectionalLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        DirectionalLight {
            object,
            shadow: None,
        }
    }

    /// Returns `true` if it has [`ShadowMap`](struct.ShadowMap.html), `false` otherwise.
    pub fn has_shadow(&self) -> bool {
        self.shadow.is_some()
    }

    /// Adds shadow map for this light source.
    pub fn set_shadow(&mut self, map: ShadowMap,
                      width: f32, height: f32, near: f32, far: f32) {
        let sp = ShadowProjection::Ortho(Ortho {
            left: -0.5 * width,
            right: 0.5 * width,
            bottom: -0.5 * height,
            top: 0.5 * height,
            near,
            far,
        });
        self.shadow = Some(map.clone());
        let msg = Operation::SetShadow(map, sp);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }
}

/// `HemisphereLight` uses two different colors in opposite to
/// [`AmbientLight`](struct.AmbientLight.html).
///
/// The color of each fragment is determined by direction of normal. If the
/// normal points in the direction of the upper hemisphere, the fragment has
/// color of the "sky". If the direction of the normal is opposite, then fragment
/// takes color of the "ground". In other cases, color is determined as
/// interpolation between colors of upper and lower hemispheres, depending on
/// how much the normal is oriented to the upper and the lower hemisphere.
pub struct HemisphereLight {
    object: Object,
}

impl HemisphereLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        HemisphereLight {
            object,
        }
    }
}

/// Light originates from a single point, and spreads outward in all directions.
pub struct PointLight {
    object: Object,
}

impl PointLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        PointLight {
            object,
        }
    }
}

impl Scene {
    /// Add new [`Object`](struct.Object.html) to the scene.
    pub fn add<P: AsRef<Pointer<Node>>>(&mut self, child: &P) {
        let msg = Operation::SetParent(self.node.clone());
        let _ = self.tx.send((child.as_ref().downgrade(), msg));
    }
}

macro_rules! as_node {
    ($($name:ident),*) => {
        $(
            impl AsRef<Pointer<Node>> for $name {
                fn as_ref(&self) -> &Pointer<Node> {
                    &self.node
                }
            }
        )*
    }
}

as_node!(Object, Group, Mesh, Sprite,
         AmbientLight, DirectionalLight, HemisphereLight, PointLight);

macro_rules! deref_objects {
    ($( $name:ident ),*) => {
        $(
            impl ops::Deref for $name {
                type Target = Object;
                fn deref(&self) -> &Object {
                    &self.object
                }
            }

            impl ops::DerefMut for $name {
                fn deref_mut(&mut self) -> &mut Object {
                    &mut self.object
                }
            }
        )*
    }
}

deref_objects!(Group, Mesh, Sprite,
    AmbientLight, HemisphereLight, DirectionalLight, PointLight);
<commit_msg>Update graph in sync<commit_after>use std::ops;

use cgmath::Ortho;
use froggy::Pointer;
use mint;

use {Object, Operation, Node, SubNode,
     Scene, ShadowProjection, Transform};
use factory::{Geometry, ShadowMap, Texture};

/// Color represented by 4-bytes hex number.
pub type Color = u32;

/// Background type.
#[derive(Clone, Debug, PartialEq)]
pub enum Background {
    /// Basic solid color background.
    Color(Color),
    //TODO: texture, cubemap
}

/// Material is the enhancement of Texture that is used to setup appearence of [`Mesh`](struct.Mesh.html).
#[derive(Clone, Debug)]
pub enum Material {
    /// Basic wireframe with specific `Color`.
    #[allow(missing_docs)]
    LineBasic { color: Color },
    /// Basic material with color, optional `Texture` and optional wireframe mode.
    #[allow(missing_docs)]
    MeshBasic { color: Color, map: Option<Texture<[f32; 4]>>, wireframe: bool },
    /// Lambertian diffuse reflection. This technique causes all closed polygons
    /// (such as a triangle within a 3D mesh) to reflect light equally in all
    /// directions when rendered.
    #[allow(missing_docs)]
    MeshLambert { color: Color, flat: bool },
    /// Material that uses Phong reflection model.
    #[allow(missing_docs)]
    MeshPhong { color: Color, glossiness: f32 },
    /// 2D Sprite.
    #[allow(missing_docs)]
    Sprite { map: Texture<[f32; 4]> },
}

/// Position, rotation and scale of the scene [`Node`](struct.Node.html).
#[derive(Clone, Debug)]
pub struct NodeTransform {
    /// Position.
    pub position: mint::Point3<f32>,
    /// Orientation.
    pub orientation: mint::Quaternion<f32>,
    /// Scale.
    pub scale: f32,
}

impl From<Transform> for NodeTransform {
    fn from(tf: Transform) -> Self {
        let p: [f32; 3] = tf.disp.into();
        let v: [f32; 3] = tf.rot.v.into();
        NodeTransform {
            position: p.into(),
            orientation: mint::Quaternion {
                v: v.into(),
                s: tf.rot.s,
            },
            scale: tf.scale,
        }
    }
}

/// General information about scene [`Node`](struct.Node.html).
#[derive(Clone, Debug)]
pub struct NodeInfo {
    /// Relative to parent transform.
    pub transform: NodeTransform,
    /// World transform (relative to the world's origin).
    pub world_transform: NodeTransform,
    /// Is `Node` visible by cameras or not?
    pub visible: bool,
    /// The same as `visible`, used internally.
    pub world_visible: bool,
    /// Material in case this `Node` has it.
    pub material: Option<Material>,
}

impl Object {
    /// Invisible objects are not rendered by cameras.
    pub fn set_visible(&mut self, visible: bool) {
        let msg = Operation::SetVisible(visible);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Rotates object in the specific direction of `target`.
    pub fn look_at<P>(&mut self, eye: P, target: P, up: Option<mint::Vector3<f32>>)
    where P: Into<[f32; 3]>
    {
        use cgmath::{InnerSpace, Point3, Quaternion, Rotation, Vector3};
        //TEMP
        let p: [[f32; 3]; 2] = [eye.into(), target.into()];
        let dir = (Point3::from(p[0]) - Point3::from(p[1])).normalize();
        let z = Vector3::unit_z();
        let up = match up {
            Some(v) => {
                let vf: [f32; 3] = v.into();
                Vector3::from(vf).normalize()
            },
            None if dir.dot(z).abs() < 0.99 => z,
            None => Vector3::unit_y(),
        };
        let q = Quaternion::look_at(dir, up).invert();
        let qv: [f32; 3] = q.v.into();
        let rot = mint::Quaternion {
            s: q.s,
            v: qv.into(),
        };
        self.set_transform(p[0], rot, 1.0);
    }

    /// Set both position, orientation and scale.
    pub fn set_transform<P, Q>(&mut self, pos: P, rot: Q, scale: f32) where
        P: Into<mint::Point3<f32>>,
        Q: Into<mint::Quaternion<f32>>,
    {
        let msg = Operation::SetTransform(Some(pos.into()), Some(rot.into()), Some(scale));
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Set position.
    pub fn set_position<P>(&mut self, pos: P) where P: Into<mint::Point3<f32>> {
        let msg = Operation::SetTransform(Some(pos.into()), None, None);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Set orientation.
    pub fn set_orientation<Q>(&mut self, rot: Q) where Q: Into<mint::Quaternion<f32>> {
        let msg = Operation::SetTransform(None, Some(rot.into()), None);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Set scale.
    pub fn set_scale(&mut self, scale: f32) {
        let msg = Operation::SetTransform(None, None, Some(scale));
        let _ = self.tx.send((self.node.downgrade(), msg));
    }

    /// Get actual information about itself from the `scene`.
    /// # Panics
    /// Panics if `scene` doesn't have this `Object`.
    pub fn sync(&mut self, scene: &Scene) -> NodeInfo {
        let mut hub = scene.hub.lock().unwrap();
        hub.process_messages();
        hub.update_graph();
        let node = &hub.nodes[&self.node];
        assert_eq!(node.scene_id, Some(scene.unique_id));
        NodeInfo {
            transform: node.transform.into(),
            world_transform: node.world_transform.into(),
            visible: node.visible,
            world_visible: node.world_visible,
            material: match node.sub_node {
                SubNode::Visual(ref mat, _) => Some(mat.clone()),
                _ => None,
            },
        }
    }
}

/// Groups are used to combine several other objects or groups to work with them
/// as with a single entity.
pub struct Group {
    object: Object,
}

impl Group {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        Group {
            object,
        }
    }

    /// Add new [`Object`](struct.Object.html) to the group.
    pub fn add<P: AsRef<Pointer<Node>>>(&mut self, child: &P) {
        let msg = Operation::SetParent(self.object.node.clone());
        let _ = self.object.tx.send((child.as_ref().downgrade(), msg));
    }
}

/// [`Geometry`](struct.Geometry.html) with some [`Material`](struct.Material.html).
pub struct Mesh {
    object: Object,
    _geometry: Option<Geometry>,
}

impl Mesh {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        Mesh {
            object,
            _geometry: None,
        }
    }

    /// Set mesh material.
    pub fn set_material(&mut self, material: Material) {
        let msg = Operation::SetMaterial(material);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }
}

/// Two-dimensional bitmap that is integrated into a larger scene.
pub struct Sprite {
    object: Object,
}

impl Sprite {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        Sprite {
            object,
        }
    }

    /// Set area of the texture to render. It can be used in sequential animations.
    pub fn set_texel_range<P, S>(&mut self, base: P, size: S) where
        P: Into<mint::Point2<i16>>,
        S: Into<mint::Vector2<u16>>,
    {
        let msg = Operation::SetTexelRange(base.into(), size.into());
        let _ = self.object.tx.send((self.node.downgrade(), msg));
    }
}

/// Omni-directional, fixed-intensity and fixed-color light source that affects
/// all objects in the scene equally.
pub struct AmbientLight {
    object: Object,
}

impl AmbientLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        AmbientLight {
            object,
        }
    }
}

/// The light source that illuminates all objects equally from a given direction,
/// like an area light of infinite size and infinite distance from the scene;
/// there is shading, but cannot be any distance falloff.
pub struct DirectionalLight {
    object: Object,
    shadow: Option<ShadowMap>,
}

impl DirectionalLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        DirectionalLight {
            object,
            shadow: None,
        }
    }

    /// Returns `true` if it has [`ShadowMap`](struct.ShadowMap.html), `false` otherwise.
    pub fn has_shadow(&self) -> bool {
        self.shadow.is_some()
    }

    /// Adds shadow map for this light source.
    pub fn set_shadow(&mut self, map: ShadowMap,
                      width: f32, height: f32, near: f32, far: f32) {
        let sp = ShadowProjection::Ortho(Ortho {
            left: -0.5 * width,
            right: 0.5 * width,
            bottom: -0.5 * height,
            top: 0.5 * height,
            near,
            far,
        });
        self.shadow = Some(map.clone());
        let msg = Operation::SetShadow(map, sp);
        let _ = self.tx.send((self.node.downgrade(), msg));
    }
}

/// `HemisphereLight` uses two different colors in opposite to
/// [`AmbientLight`](struct.AmbientLight.html).
///
/// The color of each fragment is determined by direction of normal. If the
/// normal points in the direction of the upper hemisphere, the fragment has
/// color of the "sky". If the direction of the normal is opposite, then fragment
/// takes color of the "ground". In other cases, color is determined as
/// interpolation between colors of upper and lower hemispheres, depending on
/// how much the normal is oriented to the upper and the lower hemisphere.
pub struct HemisphereLight {
    object: Object,
}

impl HemisphereLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        HemisphereLight {
            object,
        }
    }
}

/// Light originates from a single point, and spreads outward in all directions.
pub struct PointLight {
    object: Object,
}

impl PointLight {
    #[doc(hidden)]
    pub fn new(object: Object) -> Self {
        PointLight {
            object,
        }
    }
}

impl Scene {
    /// Add new [`Object`](struct.Object.html) to the scene.
    pub fn add<P: AsRef<Pointer<Node>>>(&mut self, child: &P) {
        let msg = Operation::SetParent(self.node.clone());
        let _ = self.tx.send((child.as_ref().downgrade(), msg));
    }
}

macro_rules! as_node {
    ($($name:ident),*) => {
        $(
            impl AsRef<Pointer<Node>> for $name {
                fn as_ref(&self) -> &Pointer<Node> {
                    &self.node
                }
            }
        )*
    }
}

as_node!(Object, Group, Mesh, Sprite,
         AmbientLight, DirectionalLight, HemisphereLight, PointLight);

macro_rules! deref_objects {
    ($( $name:ident ),*) => {
        $(
            impl ops::Deref for $name {
                type Target = Object;
                fn deref(&self) -> &Object {
                    &self.object
                }
            }

            impl ops::DerefMut for $name {
                fn deref_mut(&mut self) -> &mut Object {
                    &mut self.object
                }
            }
        )*
    }
}

deref_objects!(Group, Mesh, Sprite,
    AmbientLight, HemisphereLight, DirectionalLight, PointLight);
<|endoftext|>


<commit_before>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

//! Internal `serde` helpers.

#![allow(clippy::from_str_radix_10)]

use core::fmt;
use core::fmt::Binary;
use core::fmt::LowerHex;
use core::marker::PhantomData;

#[cfg(feature = "std")]
use std::ffi::CString;

use serde::de;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serializer;

struct ExpectedByDisplay<T>(T);
impl<T: fmt::Display> de::Expected for ExpectedByDisplay<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// For defaulting a field to `true`.
pub fn default_to_true() -> bool {
    true
}

/// For skipping field serialization if it's set to `true`.
///
/// (Use with `default_to_true()`.
pub fn skip_if_true(b: &bool) -> bool {
    *b
}

/// For deserializing a `Vec<u8>` from either a string or a sequence of bytes.
#[cfg(feature = "std")]
pub fn de_bytestring<'de, D>(d: D) -> Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    // CString "does the right thing" per serde's implementation.
    Ok(CString::deserialize(d)?.into_bytes())
}

/// For serializing a `Vec<u8>` as a bytestring.
#[cfg(feature = "std")]
pub fn se_bytestring<S>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_bytes(bytes)
}

/// For deserializing an `&[u8; N]`.
pub fn de_u8_array_ref<'de: 'a, 'a, D: Deserializer<'de>, const N: usize>(
    d: D,
) -> Result<&'a [u8; N], D::Error> {
    use core::convert::TryInto as _;

    let slice: &'a [u8] = Deserialize::deserialize(d)?;
    slice.try_into().map_err(|_| {
        <D::Error as serde::de::Error>::invalid_length(
            slice.len(),
            &ExpectedByDisplay(N),
        )
    })
}

/// For deserializing an `&[[u8; N]]`.
pub fn de_slice_of_u8_arrays<
    'de: 'a,
    'a,
    D: Deserializer<'de>,
    const N: usize,
>(
    d: D,
) -> Result<&'a [[u8; N]], D::Error> {
    let slice: &'a [u8] = Deserialize::deserialize(d)?;
    let lv = zerocopy::LayoutVerified::new_slice(slice).ok_or_else(|| {
        <D::Error as serde::de::Error>::invalid_length(
            slice.len(),
            &ExpectedByDisplay(format_args!("multiple of {}", N)),
        )
    })?;
    Ok(lv.into_slice())
}

/// Helper for `de_radix`.
pub struct Radix<T>(PhantomData<T>);

macro_rules! impl_radix {
    ($($ty:ident)*) => {$(
        impl<'de> de::Visitor<'de> for Radix<$ty> {
            type Value = $ty;

            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(f, "integer between 0 and {}", core::$ty::MAX)
            }
            fn visit_borrowed_str<E>(self, s: &'de str) -> Result<$ty, E>
                where E: de::Error,
            {
                let int = if s.starts_with("0b") || s.starts_with("0B") {
                    $ty::from_str_radix(&s[2..], 2)
                }
                else if s.starts_with("0o") || s.starts_with("0O") {
                    $ty::from_str_radix(&s[2..], 8)
                }
                else if s.starts_with("0x") || s.starts_with("0X") {
                    $ty::from_str_radix(&s[2..], 16)
                } else {
                    $ty::from_str_radix(s, 10)
                };

                int.map_err(E::custom)
            }

            fn visit_u64<E>(self, n: u64) -> Result<$ty, E>
                where E: de::Error,
            {
                if n <= core::$ty::MAX as u64 {
                    Ok(n as $ty)
                } else {
                    let msg = concat!("integer between 0 and ", stringify!($ty), "::MAX");
                    Err(E::invalid_value(de::Unexpected::Unsigned(n), &msg))
                }
            }
        }
    )*}
}
impl_radix! {
    u8 u16 u32 u64 usize
}

/// Deserializes an integer from either a string (which supports hex encoding)
/// or a normal integer.
///
/// Unfortunately, the way this is implemented breaks non-self-describing
/// formats, but Serde support isn't really intended for that anways.
pub fn de_radix<'de, D, T>(d: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    Radix<T>: de::Visitor<'de, Value = T>,
{
    d.deserialize_any(Radix::<T>(PhantomData))
}

/// Serializes an integer as hex.
///
/// This function requires `std` due to what are (apparently?) serde limitations.
#[cfg(feature = "std")]
pub fn se_hex<S, X>(x: X, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    X: LowerHex,
{
    s.serialize_str(&format!("0x{:x}", x))
}

/// Serializes an integer as binary.
///
/// This function requires `std` due to what are (apparently?) serde limitations.
#[cfg(feature = "std")]
pub fn se_bin<S, X>(x: X, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    X: Binary,
{
    s.serialize_str(&format!("0b{:b}", x))
}
<commit_msg>[serde] Clean up serde.rs<commit_after>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

//! Internal `serde` helpers.

#![allow(clippy::from_str_radix_10)]
// Some configurations may not use ever helper defined here.
#![allow(unused)]

use core::fmt;
use core::fmt::Binary;
use core::fmt::LowerHex;
use core::fmt::Write as _;
use core::marker::PhantomData;

use serde::de;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serializer;

/// No-std helper for using as a `write!()` target.
struct ArrayBuf<const N: usize>([u8; N], usize);

impl<const N: usize> AsRef<str> for ArrayBuf<N> {
    fn as_ref(&self) -> &str {
        core::str::from_utf8(&self.0[..self.1]).unwrap()
    }
}

impl<const N: usize> Default for ArrayBuf<N> {
    fn default() -> Self {
        Self([0; N], 0)
    }
}

impl<const N: usize> fmt::Write for ArrayBuf<N> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let bytes = s.as_bytes();
        let space_left = N - self.1;
        if space_left < bytes.len() {
            return Err(fmt::Error);
        }

        self.0[self.1..self.1 + bytes.len()].copy_from_slice(bytes);
        self.1 += bytes.len();
        Ok(())
    }
}

struct ExpectedByDisplay<T>(T);
impl<T: fmt::Display> de::Expected for ExpectedByDisplay<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// For defaulting a field to `true`.
pub fn default_to_true() -> bool {
    true
}

/// For skipping field serialization if it's set to `true`.
///
/// (Use with `default_to_true()`.
pub fn skip_if_true(b: &bool) -> bool {
    *b
}

/// For deserializing a `Vec<u8>` from either a string or a sequence of bytes.
#[cfg(all(feature = "std"))]
pub fn de_bytestring<'de, D>(d: D) -> Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    // CString "does the right thing" per serde's implementation.
    Ok(std::ffi::CString::deserialize(d)?.into_bytes())
}

/// For serializing a `Vec<u8>` as a bytestring.
pub fn se_bytestring<S>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_bytes(bytes)
}

/// For deserializing an `&[u8; N]`.
pub fn de_u8_array_ref<'de, 'a, D, const N: usize>(
    d: D,
) -> Result<&'a [u8; N], D::Error>
where
    'de: 'a,
    D: Deserializer<'de>,
{
    use core::convert::TryInto as _;

    let slice = <&[u8]>::deserialize(d)?;
    slice.try_into().map_err(|_| {
        <D::Error as de::Error>::invalid_length(
            slice.len(),
            &ExpectedByDisplay(N),
        )
    })
}

/// For deserializing an `&[[u8; N]]`.
pub fn de_slice_of_u8_arrays<'de, 'a, D, const N: usize>(
    d: D,
) -> Result<&'a [[u8; N]], D::Error>
where
    'de: 'a,
    D: Deserializer<'de>,
{
    let slice = <&[u8]>::deserialize(d)?;
    let lv = zerocopy::LayoutVerified::new_slice(slice).ok_or_else(|| {
        <D::Error as de::Error>::invalid_length(
            slice.len(),
            &ExpectedByDisplay(format_args!("multiple of {}", N)),
        )
    })?;
    Ok(lv.into_slice())
}

/// Helper for `de_radix`.
pub struct Radix<T>(PhantomData<T>);

macro_rules! impl_radix {
    ($($ty:ident)*) => {$(
        impl<'de> de::Visitor<'de> for Radix<$ty> {
            type Value = $ty;

            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(f, "integer between 0 and {}", $ty::MAX)
            }

            fn visit_borrowed_str<E>(self, s: &'de str) -> Result<$ty, E>
                where E: de::Error,
            {
                let int = if s.starts_with("0b") || s.starts_with("0B") {
                    $ty::from_str_radix(&s[2..], 2)
                }
                else if s.starts_with("0o") || s.starts_with("0O") {
                    $ty::from_str_radix(&s[2..], 8)
                }
                else if s.starts_with("0x") || s.starts_with("0X") {
                    $ty::from_str_radix(&s[2..], 16)
                } else {
                    $ty::from_str_radix(s, 10)
                };

                int.map_err(E::custom)
            }

            fn visit_u64<E>(self, n: u64) -> Result<$ty, E>
                where E: de::Error,
            {
                if n <= core::$ty::MAX as u64 {
                    Ok(n as $ty)
                } else {
                    let msg = concat!("integer between 0 and ", stringify!($ty), "::MAX");
                    Err(E::invalid_value(de::Unexpected::Unsigned(n), &msg))
                }
            }
        }
    )*}
}
impl_radix! {
    u8 u16 u32 u64 usize
}

/// Deserializes an integer from either a string (which supports hex encoding)
/// or a normal integer.
///
/// Unfortunately, the way this is implemented breaks non-self-describing
/// formats, but Serde support isn't really intended for that anways.
pub fn de_radix<'de, D, T>(d: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    Radix<T>: de::Visitor<'de, Value = T>,
{
    d.deserialize_any(Radix::<T>(PhantomData))
}

/// Serializes an integer as hex.
///
/// This function requires `std` due to what are (apparently?) serde limitations.
pub fn se_hex<S, X>(x: X, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    X: LowerHex,
{
    let mut buf = ArrayBuf::<18>::default();
    let _ = write!(buf, "0x{:x}", x);
    s.serialize_str(buf.as_ref())
}

/// Serializes an integer as binary.
///
/// This function requires `std` due to what are (apparently?) serde limitations.
pub fn se_bin<S, X>(x: X, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    X: Binary,
{
    let mut buf = ArrayBuf::<66>::default();
    let _ = write!(buf, "0b{:b}", x);
    s.serialize_str(buf.as_ref())
}
<|endoftext|>


<commit_before>use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

use build_helper::{output, tracked_env_var_os};

fn detect_llvm_link() -> (&'static str, &'static str) {
    // Force the link mode we want, preferring static by default, but
    // possibly overridden by `configure --enable-llvm-link-shared`.
    if tracked_env_var_os("LLVM_LINK_SHARED").is_some() {
        ("dylib", "--link-shared")
    } else {
        ("static", "--link-static")
    }
}

fn main() {
    if tracked_env_var_os("RUST_CHECK").is_some() {
        // If we're just running `check`, there's no need for LLVM to be built.
        return;
    }

    build_helper::restore_library_path();

    let target = env::var("TARGET").expect("TARGET was not set");
    let llvm_config =
        tracked_env_var_os("LLVM_CONFIG").map(|x| Some(PathBuf::from(x))).unwrap_or_else(|| {
            if let Some(dir) = tracked_env_var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
                let to_test = dir
                    .parent()
                    .unwrap()
                    .parent()
                    .unwrap()
                    .join(&target)
                    .join("llvm/bin/llvm-config");
                if Command::new(&to_test).output().is_ok() {
                    return Some(to_test);
                }
            }
            None
        });

    if let Some(llvm_config) = &llvm_config {
        println!("cargo:rerun-if-changed={}", llvm_config.display());
    }
    let llvm_config = llvm_config.unwrap_or_else(|| PathBuf::from("llvm-config"));

    // Test whether we're cross-compiling LLVM. This is a pretty rare case
    // currently where we're producing an LLVM for a different platform than
    // what this build script is currently running on.
    //
    // In that case, there's no guarantee that we can actually run the target,
    // so the build system works around this by giving us the LLVM_CONFIG for
    // the host platform. This only really works if the host LLVM and target
    // LLVM are compiled the same way, but for us that's typically the case.
    //
    // We *want* detect this cross compiling situation by asking llvm-config
    // what its host-target is. If that's not the TARGET, then we're cross
    // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
    // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
    // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
    // tricks us into thinking we're doing a cross build when we aren't, so
    // havoc ensues.
    //
    // In any case, if we're cross compiling, this generally just means that we
    // can't trust all the output of llvm-config because it might be targeted
    // for the host rather than the target. As a result a bunch of blocks below
    // are gated on `if !is_crossed`
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    let is_crossed = target != host;

    let mut optional_components = vec![
        "x86",
        "arm",
        "aarch64",
        "amdgpu",
        "avr",
        "mips",
        "powerpc",
        "systemz",
        "jsbackend",
        "webassembly",
        "msp430",
        "sparc",
        "nvptx",
        "hexagon",
    ];

    let mut version_cmd = Command::new(&llvm_config);
    version_cmd.arg("--version");
    let version_output = output(&mut version_cmd);
    let mut parts = version_output.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
    let (major, _minor) = if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
        (major, minor)
    } else {
        (6, 0)
    };

    if major > 6 {
        optional_components.push("riscv");
    }

    let required_components = &[
        "ipo",
        "bitreader",
        "bitwriter",
        "linker",
        "asmparser",
        "lto",
        "coverage",
        "instrumentation",
    ];

    let components = output(Command::new(&llvm_config).arg("--components"));
    let mut components = components.split_whitespace().collect::<Vec<_>>();
    components.retain(|c| optional_components.contains(c) || required_components.contains(c));

    for component in required_components {
        if !components.contains(component) {
            panic!("require llvm component {} but wasn't found", component);
        }
    }

    for component in components.iter() {
        println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
    }

    if major >= 9 {
        println!("cargo:rustc-cfg=llvm_has_msp430_asm_parser");
    }

    // Link in our own LLVM shims, compiled with the same flags as LLVM
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--cxxflags");
    let cxxflags = output(&mut cmd);
    let mut cfg = cc::Build::new();
    cfg.warnings(false);
    for flag in cxxflags.split_whitespace() {
        // Ignore flags like `-m64` when we're doing a cross build
        if is_crossed && flag.starts_with("-m") {
            continue;
        }

        if flag.starts_with("-flto") {
            continue;
        }

        // -Wdate-time is not supported by the netbsd cross compiler
        if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
            continue;
        }

        // Include path contains host directory, replace it with target
        if is_crossed && flag.starts_with("-I") {
            cfg.flag(&flag.replace(&host, &target));
            continue;
        }

        cfg.flag(flag);
    }

    for component in &components {
        let mut flag = String::from("LLVM_COMPONENT_");
        flag.push_str(&component.to_uppercase());
        cfg.define(&flag, None);
    }

    if tracked_env_var_os("LLVM_RUSTLLVM").is_some() {
        cfg.define("LLVM_RUSTLLVM", None);
    }

    if tracked_env_var_os("LLVM_NDEBUG").is_some() {
        cfg.define("NDEBUG", None);
        cfg.debug(false);
    }

    build_helper::rerun_if_changed_anything_in_dir(Path::new("llvm-wrapper"));
    cfg.file("llvm-wrapper/PassWrapper.cpp")
        .file("llvm-wrapper/RustWrapper.cpp")
        .file("llvm-wrapper/ArchiveWrapper.cpp")
        .file("llvm-wrapper/CoverageMappingWrapper.cpp")
        .file("llvm-wrapper/Linker.cpp")
        .cpp(true)
        .cpp_link_stdlib(None) // we handle this below
        .compile("llvm-wrapper");

    let (llvm_kind, llvm_link_arg) = detect_llvm_link();

    // Link in all LLVM libraries, if we're using the "wrong" llvm-config then
    // we don't pick up system libs because unfortunately they're for the host
    // of llvm-config, not the target that we're attempting to link.
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--libs");

    if !is_crossed {
        cmd.arg("--system-libs");
    } else if target.contains("windows-gnu") {
        println!("cargo:rustc-link-lib=shell32");
        println!("cargo:rustc-link-lib=uuid");
    } else if target.contains("netbsd") || target.contains("haiku") {
        println!("cargo:rustc-link-lib=z");
    }
    cmd.args(&components);

    for lib in output(&mut cmd).split_whitespace() {
        let name = if lib.starts_with("-l") {
            &lib[2..]
        } else if lib.starts_with('-') {
            &lib[1..]
        } else if Path::new(lib).exists() {
            // On MSVC llvm-config will print the full name to libraries, but
            // we're only interested in the name part
            let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
            name.trim_end_matches(".lib")
        } else if lib.ends_with(".lib") {
            // Some MSVC libraries just come up with `.lib` tacked on, so chop
            // that off
            lib.trim_end_matches(".lib")
        } else {
            continue;
        };

        // Don't need or want this library, but LLVM's CMake build system
        // doesn't provide a way to disable it, so filter it here even though we
        // may or may not have built it. We don't reference anything from this
        // library and it otherwise may just pull in extra dependencies on
        // libedit which we don't want
        if name == "LLVMLineEditor" {
            continue;
        }

        let kind = if name.starts_with("LLVM") { llvm_kind } else { "dylib" };
        println!("cargo:rustc-link-lib={}={}", kind, name);
    }

    // LLVM ldflags
    //
    // If we're a cross-compile of LLVM then unfortunately we can't trust these
    // ldflags (largely where all the LLVM libs are located). Currently just
    // hack around this by replacing the host triple with the target and pray
    // that those -L directories are the same!
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--ldflags");
    for lib in output(&mut cmd).split_whitespace() {
        if is_crossed {
            if lib.starts_with("-LIBPATH:") {
                println!("cargo:rustc-link-search=native={}", lib[9..].replace(&host, &target));
            } else if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}", lib[2..].replace(&host, &target));
            }
        } else if lib.starts_with("-LIBPATH:") {
            println!("cargo:rustc-link-search=native={}", &lib[9..]);
        } else if lib.starts_with("-l") {
            println!("cargo:rustc-link-lib={}", &lib[2..]);
        } else if lib.starts_with("-L") {
            println!("cargo:rustc-link-search=native={}", &lib[2..]);
        }
    }

    // Some LLVM linker flags (-L and -l) may be needed even when linking
    // rustc_llvm, for example when using static libc++, we may need to
    // manually specify the library search path and -ldl -lpthread as link
    // dependencies.
    let llvm_linker_flags = tracked_env_var_os("LLVM_LINKER_FLAGS");
    if let Some(s) = llvm_linker_flags {
        for lib in s.into_string().unwrap().split_whitespace() {
            if lib.starts_with("-l") {
                println!("cargo:rustc-link-lib={}", &lib[2..]);
            } else if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}", &lib[2..]);
            }
        }
    }

    let llvm_static_stdcpp = tracked_env_var_os("LLVM_STATIC_STDCPP");
    let llvm_use_libcxx = tracked_env_var_os("LLVM_USE_LIBCXX");

    let stdcppname = if target.contains("openbsd") {
        if target.contains("sparc64") { "estdc++" } else { "c++" }
    } else if target.contains("freebsd") {
        "c++"
    } else if target.contains("darwin") {
        "c++"
    } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
        // NetBSD uses a separate library when relocation is required
        "stdc++_pic"
    } else if llvm_use_libcxx.is_some() {
        "c++"
    } else {
        "stdc++"
    };

    // RISC-V requires libatomic for sub-word atomic operations
    if target.starts_with("riscv") {
        println!("cargo:rustc-link-lib=atomic");
    }

    // C++ runtime library
    if !target.contains("msvc") {
        if let Some(s) = llvm_static_stdcpp {
            assert!(!cxxflags.contains("stdlib=libc++"));
            let path = PathBuf::from(s);
            println!("cargo:rustc-link-search=native={}", path.parent().unwrap().display());
            if target.contains("windows") {
                println!("cargo:rustc-link-lib=static-nobundle={}", stdcppname);
            } else {
                println!("cargo:rustc-link-lib=static={}", stdcppname);
            }
        } else if cxxflags.contains("stdlib=libc++") {
            println!("cargo:rustc-link-lib=c++");
        } else {
            println!("cargo:rustc-link-lib={}", stdcppname);
        }
    }

    // Libstdc++ depends on pthread which Rust doesn't link on MinGW
    // since nothing else requires it.
    if target.contains("windows-gnu") {
        println!("cargo:rustc-link-lib=static-nobundle=pthread");
    }
}
<commit_msg>Auto merge of #77690 - est31:llvm_8_required, r=matthewjasper<commit_after>use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

use build_helper::{output, tracked_env_var_os};

fn detect_llvm_link() -> (&'static str, &'static str) {
    // Force the link mode we want, preferring static by default, but
    // possibly overridden by `configure --enable-llvm-link-shared`.
    if tracked_env_var_os("LLVM_LINK_SHARED").is_some() {
        ("dylib", "--link-shared")
    } else {
        ("static", "--link-static")
    }
}

fn main() {
    if tracked_env_var_os("RUST_CHECK").is_some() {
        // If we're just running `check`, there's no need for LLVM to be built.
        return;
    }

    build_helper::restore_library_path();

    let target = env::var("TARGET").expect("TARGET was not set");
    let llvm_config =
        tracked_env_var_os("LLVM_CONFIG").map(|x| Some(PathBuf::from(x))).unwrap_or_else(|| {
            if let Some(dir) = tracked_env_var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
                let to_test = dir
                    .parent()
                    .unwrap()
                    .parent()
                    .unwrap()
                    .join(&target)
                    .join("llvm/bin/llvm-config");
                if Command::new(&to_test).output().is_ok() {
                    return Some(to_test);
                }
            }
            None
        });

    if let Some(llvm_config) = &llvm_config {
        println!("cargo:rerun-if-changed={}", llvm_config.display());
    }
    let llvm_config = llvm_config.unwrap_or_else(|| PathBuf::from("llvm-config"));

    // Test whether we're cross-compiling LLVM. This is a pretty rare case
    // currently where we're producing an LLVM for a different platform than
    // what this build script is currently running on.
    //
    // In that case, there's no guarantee that we can actually run the target,
    // so the build system works around this by giving us the LLVM_CONFIG for
    // the host platform. This only really works if the host LLVM and target
    // LLVM are compiled the same way, but for us that's typically the case.
    //
    // We *want* detect this cross compiling situation by asking llvm-config
    // what its host-target is. If that's not the TARGET, then we're cross
    // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
    // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
    // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
    // tricks us into thinking we're doing a cross build when we aren't, so
    // havoc ensues.
    //
    // In any case, if we're cross compiling, this generally just means that we
    // can't trust all the output of llvm-config because it might be targeted
    // for the host rather than the target. As a result a bunch of blocks below
    // are gated on `if !is_crossed`
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    let is_crossed = target != host;

    let optional_components = &[
        "x86",
        "arm",
        "aarch64",
        "amdgpu",
        "avr",
        "mips",
        "powerpc",
        "systemz",
        "jsbackend",
        "webassembly",
        "msp430",
        "sparc",
        "nvptx",
        "hexagon",
        "riscv",
    ];

    let mut version_cmd = Command::new(&llvm_config);
    version_cmd.arg("--version");
    let version_output = output(&mut version_cmd);
    let mut parts = version_output.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
    let (major, _minor) = if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
        (major, minor)
    } else {
        (8, 0)
    };

    let required_components = &[
        "ipo",
        "bitreader",
        "bitwriter",
        "linker",
        "asmparser",
        "lto",
        "coverage",
        "instrumentation",
    ];

    let components = output(Command::new(&llvm_config).arg("--components"));
    let mut components = components.split_whitespace().collect::<Vec<_>>();
    components.retain(|c| optional_components.contains(c) || required_components.contains(c));

    for component in required_components {
        if !components.contains(component) {
            panic!("require llvm component {} but wasn't found", component);
        }
    }

    for component in components.iter() {
        println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
    }

    if major >= 9 {
        println!("cargo:rustc-cfg=llvm_has_msp430_asm_parser");
    }

    // Link in our own LLVM shims, compiled with the same flags as LLVM
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--cxxflags");
    let cxxflags = output(&mut cmd);
    let mut cfg = cc::Build::new();
    cfg.warnings(false);
    for flag in cxxflags.split_whitespace() {
        // Ignore flags like `-m64` when we're doing a cross build
        if is_crossed && flag.starts_with("-m") {
            continue;
        }

        if flag.starts_with("-flto") {
            continue;
        }

        // -Wdate-time is not supported by the netbsd cross compiler
        if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
            continue;
        }

        // Include path contains host directory, replace it with target
        if is_crossed && flag.starts_with("-I") {
            cfg.flag(&flag.replace(&host, &target));
            continue;
        }

        cfg.flag(flag);
    }

    for component in &components {
        let mut flag = String::from("LLVM_COMPONENT_");
        flag.push_str(&component.to_uppercase());
        cfg.define(&flag, None);
    }

    if tracked_env_var_os("LLVM_RUSTLLVM").is_some() {
        cfg.define("LLVM_RUSTLLVM", None);
    }

    if tracked_env_var_os("LLVM_NDEBUG").is_some() {
        cfg.define("NDEBUG", None);
        cfg.debug(false);
    }

    build_helper::rerun_if_changed_anything_in_dir(Path::new("llvm-wrapper"));
    cfg.file("llvm-wrapper/PassWrapper.cpp")
        .file("llvm-wrapper/RustWrapper.cpp")
        .file("llvm-wrapper/ArchiveWrapper.cpp")
        .file("llvm-wrapper/CoverageMappingWrapper.cpp")
        .file("llvm-wrapper/Linker.cpp")
        .cpp(true)
        .cpp_link_stdlib(None) // we handle this below
        .compile("llvm-wrapper");

    let (llvm_kind, llvm_link_arg) = detect_llvm_link();

    // Link in all LLVM libraries, if we're using the "wrong" llvm-config then
    // we don't pick up system libs because unfortunately they're for the host
    // of llvm-config, not the target that we're attempting to link.
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--libs");

    if !is_crossed {
        cmd.arg("--system-libs");
    } else if target.contains("windows-gnu") {
        println!("cargo:rustc-link-lib=shell32");
        println!("cargo:rustc-link-lib=uuid");
    } else if target.contains("netbsd") || target.contains("haiku") {
        println!("cargo:rustc-link-lib=z");
    }
    cmd.args(&components);

    for lib in output(&mut cmd).split_whitespace() {
        let name = if lib.starts_with("-l") {
            &lib[2..]
        } else if lib.starts_with('-') {
            &lib[1..]
        } else if Path::new(lib).exists() {
            // On MSVC llvm-config will print the full name to libraries, but
            // we're only interested in the name part
            let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
            name.trim_end_matches(".lib")
        } else if lib.ends_with(".lib") {
            // Some MSVC libraries just come up with `.lib` tacked on, so chop
            // that off
            lib.trim_end_matches(".lib")
        } else {
            continue;
        };

        // Don't need or want this library, but LLVM's CMake build system
        // doesn't provide a way to disable it, so filter it here even though we
        // may or may not have built it. We don't reference anything from this
        // library and it otherwise may just pull in extra dependencies on
        // libedit which we don't want
        if name == "LLVMLineEditor" {
            continue;
        }

        let kind = if name.starts_with("LLVM") { llvm_kind } else { "dylib" };
        println!("cargo:rustc-link-lib={}={}", kind, name);
    }

    // LLVM ldflags
    //
    // If we're a cross-compile of LLVM then unfortunately we can't trust these
    // ldflags (largely where all the LLVM libs are located). Currently just
    // hack around this by replacing the host triple with the target and pray
    // that those -L directories are the same!
    let mut cmd = Command::new(&llvm_config);
    cmd.arg(llvm_link_arg).arg("--ldflags");
    for lib in output(&mut cmd).split_whitespace() {
        if is_crossed {
            if lib.starts_with("-LIBPATH:") {
                println!("cargo:rustc-link-search=native={}", lib[9..].replace(&host, &target));
            } else if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}", lib[2..].replace(&host, &target));
            }
        } else if lib.starts_with("-LIBPATH:") {
            println!("cargo:rustc-link-search=native={}", &lib[9..]);
        } else if lib.starts_with("-l") {
            println!("cargo:rustc-link-lib={}", &lib[2..]);
        } else if lib.starts_with("-L") {
            println!("cargo:rustc-link-search=native={}", &lib[2..]);
        }
    }

    // Some LLVM linker flags (-L and -l) may be needed even when linking
    // rustc_llvm, for example when using static libc++, we may need to
    // manually specify the library search path and -ldl -lpthread as link
    // dependencies.
    let llvm_linker_flags = tracked_env_var_os("LLVM_LINKER_FLAGS");
    if let Some(s) = llvm_linker_flags {
        for lib in s.into_string().unwrap().split_whitespace() {
            if lib.starts_with("-l") {
                println!("cargo:rustc-link-lib={}", &lib[2..]);
            } else if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}", &lib[2..]);
            }
        }
    }

    let llvm_static_stdcpp = tracked_env_var_os("LLVM_STATIC_STDCPP");
    let llvm_use_libcxx = tracked_env_var_os("LLVM_USE_LIBCXX");

    let stdcppname = if target.contains("openbsd") {
        if target.contains("sparc64") { "estdc++" } else { "c++" }
    } else if target.contains("freebsd") {
        "c++"
    } else if target.contains("darwin") {
        "c++"
    } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
        // NetBSD uses a separate library when relocation is required
        "stdc++_pic"
    } else if llvm_use_libcxx.is_some() {
        "c++"
    } else {
        "stdc++"
    };

    // RISC-V requires libatomic for sub-word atomic operations
    if target.starts_with("riscv") {
        println!("cargo:rustc-link-lib=atomic");
    }

    // C++ runtime library
    if !target.contains("msvc") {
        if let Some(s) = llvm_static_stdcpp {
            assert!(!cxxflags.contains("stdlib=libc++"));
            let path = PathBuf::from(s);
            println!("cargo:rustc-link-search=native={}", path.parent().unwrap().display());
            if target.contains("windows") {
                println!("cargo:rustc-link-lib=static-nobundle={}", stdcppname);
            } else {
                println!("cargo:rustc-link-lib=static={}", stdcppname);
            }
        } else if cxxflags.contains("stdlib=libc++") {
            println!("cargo:rustc-link-lib=c++");
        } else {
            println!("cargo:rustc-link-lib={}", stdcppname);
        }
    }

    // Libstdc++ depends on pthread which Rust doesn't link on MinGW
    // since nothing else requires it.
    if target.contains("windows-gnu") {
        println!("cargo:rustc-link-lib=static-nobundle=pthread");
    }
}
<|endoftext|>


<commit_before>use crate::zero_copy::RawObject;

use std::io::{self, Write};

/// A "zero-copy" writer used on platforms for which we have no actual zero-copy implementation (or
/// which use standard read/write operations for zero-copy I/O).  This writer just delegates to the
/// inner writer used to create it.  Using this struct avoids going through the machinery used to
/// handle the case where a given writer does not support zero-copy on a platform.
pub struct PlatformZeroCopyWriter;

impl PlatformZeroCopyWriter {
   pub unsafe fn new(_obj: RawObject) -> Result<Self, ()> {
      Err(())
   }
}

impl Write for PlatformZeroCopyWriter {
   fn write(&mut self, _bytes: &[u8]) -> io::Result<usize> {
      panic!("should never occur")
   }

   fn flush(&mut self) -> io::Result<()> {
      panic!("should never occur")
   }
}
<commit_msg>uucore: remove an inaccurate comment<commit_after>use crate::zero_copy::RawObject;

use std::io::{self, Write};

pub struct PlatformZeroCopyWriter;

impl PlatformZeroCopyWriter {
   pub unsafe fn new(_obj: RawObject) -> Result<Self, ()> {
      Err(())
   }
}

impl Write for PlatformZeroCopyWriter {
   fn write(&mut self, _bytes: &[u8]) -> io::Result<usize> {
      panic!("should never occur")
   }

   fn flush(&mut self) -> io::Result<()> {
      panic!("should never occur")
   }
}
<|endoftext|>


<commit_before>use vec3::Vec3;
use material::Material;
use std::f64::consts::PI;

pub struct CookTorranceMaterial {
    pub k_a: f64,            // Ambient coefficient
    pub k_d: f64,            // Diffuse coefficient
    pub k_s: f64,            // Local specular coefficient
    pub k_sg: f64,           // Global specular coefficient (mirror reflection)
    pub k_tg: f64,           // Global transmissive coefficient (refraction)
    pub ambient: Vec3,       // Ambient color
    pub diffuse: Vec3,       // Diffuse color
    pub transmission: Vec3,  // Transmissive color
    pub specular: Vec3,      // Specular color
    pub roughness: f64,      //
    pub gauss_constant: f64, //
    pub ior: f64             // Index of refraction
}

impl Material for CookTorranceMaterial {
    fn sample(&self, n: Vec3, i: Vec3, l: Vec3) -> Vec3 {
        let h = (l + i).unit();

        // Blinn-Phong approximation
        let ambient  = self.ambient.scale(self.k_a);
        let diffuse  = self.diffuse.scale(self.k_d).scale(n.dot(&l));

        // Specular calculations
        let n_dot_h = n.dot(&h);
        let n_dot_l = n.dot(&l);
        let v_dot_h = i.dot(&h);
        let n_dot_v = n.dot(&i);

        // Approximate Fresnel term, Schlick's approximation
        let n1 = 1.0;
        let n2 = self.ior;
        let f0 = ((n1 - n2) / (n1 + n2)).powf(2.0);
        let f = (1.0 - v_dot_h).powf(5.0) * (1.0 - f0) + f0;

        // Microfacet distribution
        let alpha = n_dot_h.acos();
        let d = self.gauss_constant * (-alpha / self.roughness.sqrt()).exp();

        // Geometric attenuation factor
        let g1 = (2.0 * n_dot_h * n_dot_v) / v_dot_h;
        let g2 = (2.0 * n_dot_h * n_dot_l) / v_dot_h;
        let g = g1.min(g2);

        let brdf = f * d * g / (n_dot_v * n_dot_l);

        // println!("f{} d{} g{} ndotv{} ndotl{} brdf{}", f, d, g, n_dot_v, n_dot_l, brdf);
        println!("{}", brdf)
        self.specular.scale(self.k_s * brdf) + diffuse + ambient
    }

    fn is_reflective(&self) -> bool {
        self.k_sg > 0.0
    }

    fn is_refractive(&self) -> bool {
        self.k_tg > 0.0
    }

    fn global_specular(&self, color: &Vec3) -> Vec3 {
        color.scale(self.k_sg)
    }

    fn global_transmissive(&self, color: &Vec3) -> Vec3 {
        color.scale(self.k_tg)
    }

    fn transmission(&self) -> Vec3 {
        self.transmission
    }

    fn ior(&self) -> f64 {
        self.ior
    }
}
<commit_msg>Remove debug println from Cook-Torrance material.<commit_after>use vec3::Vec3;
use material::Material;
use std::f64::consts::PI;

pub struct CookTorranceMaterial {
    pub k_a: f64,            // Ambient coefficient
    pub k_d: f64,            // Diffuse coefficient
    pub k_s: f64,            // Local specular coefficient
    pub k_sg: f64,           // Global specular coefficient (mirror reflection)
    pub k_tg: f64,           // Global transmissive coefficient (refraction)
    pub ambient: Vec3,       // Ambient color
    pub diffuse: Vec3,       // Diffuse color
    pub transmission: Vec3,  // Transmissive color
    pub specular: Vec3,      // Specular color
    pub roughness: f64,      //
    pub gauss_constant: f64, //
    pub ior: f64             // Index of refraction
}

impl Material for CookTorranceMaterial {
    fn sample(&self, n: Vec3, i: Vec3, l: Vec3) -> Vec3 {
        let h = (l + i).unit();

        // Blinn-Phong approximation
        let ambient  = self.ambient.scale(self.k_a);
        let diffuse  = self.diffuse.scale(self.k_d).scale(n.dot(&l));

        // Specular calculations
        let n_dot_h = n.dot(&h);
        let n_dot_l = n.dot(&l);
        let v_dot_h = i.dot(&h);
        let n_dot_v = n.dot(&i);

        // Approximate Fresnel term, Schlick's approximation
        let n1 = 1.0;
        let n2 = self.ior;
        let f0 = ((n1 - n2) / (n1 + n2)).powf(2.0);
        let f = (1.0 - v_dot_h).powf(5.0) * (1.0 - f0) + f0;

        // Microfacet distribution
        let alpha = n_dot_h.acos();
        let d = self.gauss_constant * (-alpha / self.roughness.sqrt()).exp();

        // Geometric attenuation factor
        let g1 = (2.0 * n_dot_h * n_dot_v) / v_dot_h;
        let g2 = (2.0 * n_dot_h * n_dot_l) / v_dot_h;
        let g = g1.min(g2);

        let brdf = f * d * g / (n_dot_v * n_dot_l);

        self.specular.scale(self.k_s * brdf) + diffuse + ambient
    }

    fn is_reflective(&self) -> bool {
        self.k_sg > 0.0
    }

    fn is_refractive(&self) -> bool {
        self.k_tg > 0.0
    }

    fn global_specular(&self, color: &Vec3) -> Vec3 {
        color.scale(self.k_sg)
    }

    fn global_transmissive(&self, color: &Vec3) -> Vec3 {
        color.scale(self.k_tg)
    }

    fn transmission(&self) -> Vec3 {
        self.transmission
    }

    fn ior(&self) -> f64 {
        self.ior
    }
}
<|endoftext|>


<commit_before><commit_msg>Support accepting default name by providing -n ""<commit_after><|endoftext|>