├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── draw_rgb_triangles.rs ├── draw_triangle.rs ├── rainbow.rs └── turtle.rs └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | doc/ 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "drawille" 3 | version = "0.3.0" 4 | authors = ["ftxqxd"] 5 | description = "Draw to the terminal using braille characters" 6 | license = "MIT OR Apache-2.0" 7 | repository = "https://github.com/ftxqxd/drawille-rs" 8 | homepage = "https://github.com/ftxqxd/drawille-rs" 9 | 10 | [lib] 11 | name = "drawille" 12 | 13 | [dependencies] 14 | fnv = "1.0.6" 15 | colored = "2.0.0" 16 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The drawille-rs Developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | drawille-rs 2 | =========== 3 | 4 | A terminal graphics library for Rust that enables the use of braille characters 5 | to draw shapes. 6 | 7 | This is a port of [asciimoo/drawille](https://github.com/asciimoo/drawille) to Rust. 8 | 9 | Usage 10 | ----- 11 | 12 | Just add ftxqxd/drawille-rs to your Cargo.toml: 13 | 14 | ```toml 15 | [dependencies] 16 | drawille = "0.3.0" 17 | ``` 18 | 19 | ## License 20 | 21 | Licensed under either of 22 | 23 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 24 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 25 | 26 | at your option. 27 | 28 | ### Contribution 29 | 30 | Unless you explicitly state otherwise, any contribution intentionally 31 | submitted for inclusion in the work by you, as defined in the Apache-2.0 32 | license, shall be dual licensed as above, without any additional terms or 33 | conditions. 34 | -------------------------------------------------------------------------------- /examples/draw_rgb_triangles.rs: -------------------------------------------------------------------------------- 1 | extern crate drawille; 2 | 3 | use drawille::Canvas; 4 | use drawille::PixelColor; 5 | 6 | fn main() { 7 | let mut canvas = Canvas::new(100, 100); 8 | canvas.line_colored(2, 2, 80, 80, PixelColor::Red); 9 | canvas.line_colored(2, 80, 80, 80, PixelColor::Green); 10 | canvas.line_colored(2, 2, 2, 80, PixelColor::Blue); 11 | 12 | canvas.line_colored( 13 | 2 + 5, 14 | 2 + 15, 15 | 80 + 5, 16 | 80 + 15, 17 | PixelColor::TrueColor { r: 255, g: 0, b: 0 }, 18 | ); 19 | canvas.line_colored( 20 | 2 + 5, 21 | 80 + 15, 22 | 80 + 5, 23 | 80 + 15, 24 | PixelColor::TrueColor { r: 0, g: 255, b: 0 }, 25 | ); 26 | canvas.line_colored( 27 | 2 + 5, 28 | 2 + 15, 29 | 2 + 5, 30 | 80 + 15, 31 | PixelColor::TrueColor { r: 0, g: 0, b: 255 }, 32 | ); 33 | println!("{}", canvas.frame()); 34 | } 35 | -------------------------------------------------------------------------------- /examples/draw_triangle.rs: -------------------------------------------------------------------------------- 1 | extern crate drawille; 2 | 3 | use drawille::Canvas; 4 | 5 | fn main() { 6 | let mut canvas = Canvas::new(100, 100); 7 | canvas.line(2, 2, 80, 80); 8 | canvas.line(2, 80, 80, 80); 9 | canvas.line(2, 2, 2, 80); 10 | println!("{}", canvas.frame()); 11 | } 12 | -------------------------------------------------------------------------------- /examples/rainbow.rs: -------------------------------------------------------------------------------- 1 | extern crate drawille; 2 | 3 | use drawille::{PixelColor, PixelColor::TrueColor, Turtle}; 4 | 5 | fn main() { 6 | // Rainbow using true colors 7 | let mut turtle_true = Turtle::new(0., 0.); 8 | let colors1 = vec![ 9 | TrueColor{r: 255, g: 0, b: 0}, 10 | TrueColor{r: 255, g: 127, b:0}, 11 | TrueColor{r: 255, g: 255, b: 0}, 12 | TrueColor{r: 0, g: 255, b:0}, 13 | TrueColor{r: 0, g: 0, b:255}, 14 | TrueColor{r: 46, g: 43, b:95}, 15 | TrueColor{r: 139, g: 0, b:255}, 16 | ]; 17 | 18 | for (cn, &color) in colors1.iter().enumerate() { 19 | turtle_true.up(); 20 | turtle_true.teleport(0.+(cn as f32)*3., 50.); 21 | turtle_true.rotation = -90.; 22 | turtle_true.down(); 23 | turtle_true.color(color); 24 | for _ in 0..150 { 25 | turtle_true.forward(1.-(cn as f32)/16.); 26 | turtle_true.right(180./150.); 27 | } 28 | } 29 | println!("{}", turtle_true.frame()); 30 | 31 | // Rainbow using adaptive colors 32 | let mut turtle_buildin= Turtle::new(0., 0.); 33 | let colors2 = vec![ 34 | PixelColor::Red, 35 | PixelColor::Yellow, 36 | PixelColor::Green, 37 | PixelColor::Blue, 38 | PixelColor::Magenta, 39 | ]; 40 | 41 | for (cn, &color) in colors2.iter().enumerate() { 42 | turtle_buildin.up(); 43 | turtle_buildin.teleport(0.+(cn as f32)*3., 50.); 44 | turtle_buildin.rotation = -90.; 45 | turtle_buildin.down(); 46 | turtle_buildin.color(color); 47 | for _ in 0..150 { 48 | turtle_buildin.forward(1.-(cn as f32)/16.); 49 | turtle_buildin.right(180./150.); 50 | } 51 | } 52 | println!("{}", turtle_buildin.frame()); 53 | } 54 | -------------------------------------------------------------------------------- /examples/turtle.rs: -------------------------------------------------------------------------------- 1 | extern crate drawille; 2 | 3 | use drawille::Turtle; 4 | 5 | fn main() { 6 | let mut turtle = Turtle::new(50., 0.); 7 | //turtle.up(); 8 | turtle.down(); 9 | for n in 0..100 { 10 | turtle.forward(10. - (n as f32)/10.); 11 | turtle.right(10.); 12 | } 13 | println!("{}", turtle.frame()); 14 | } 15 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! `drawille` – a terminal graphics library for Rust, based on the Python library 2 | //! [drawille](https://github.com/asciimoo/drawille). 3 | //! 4 | //! This crate provides an interface for utilising Braille characters to draw a picture to a 5 | //! terminal, allowing for much smaller pixels but losing proper colour support. 6 | //! 7 | //! # Example 8 | //! 9 | //! ``` 10 | //! extern crate drawille; 11 | //! 12 | //! use drawille::Canvas; 13 | //! 14 | //! fn main() { 15 | //! let mut canvas = Canvas::new(10, 10); 16 | //! canvas.set(5, 4); 17 | //! canvas.line(2, 2, 8, 8); 18 | //! assert_eq!(canvas.frame(), [ 19 | //! " ⢄ ", 20 | //! " ⠙⢄ ", 21 | //! " ⠁ "].join("\n")); 22 | //! } 23 | //! ``` 24 | use std::char; 25 | use std::cmp; 26 | use std::f32; 27 | 28 | extern crate fnv; 29 | use fnv::FnvHashMap; 30 | 31 | extern crate colored; 32 | pub use colored::Color as PixelColor; 33 | use colored::Colorize; 34 | 35 | static PIXEL_MAP: [[u8; 2]; 4] = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]]; 36 | 37 | /// A canvas object that can be used to draw to the terminal using Braille characters. 38 | #[derive(Clone, Debug, PartialEq, Eq)] 39 | pub struct Canvas { 40 | chars: FnvHashMap<(u16, u16), (u8, char, bool, PixelColor)>, 41 | width: u16, 42 | height: u16, 43 | } 44 | 45 | impl Canvas { 46 | /// Creates a new `Canvas` with the given width and height. 47 | /// 48 | /// Note that the `Canvas` can still draw outside the given dimensions (expanding the canvas) 49 | /// if a pixel is set outside the dimensions. 50 | pub fn new(width: u32, height: u32) -> Canvas { 51 | Canvas { 52 | chars: FnvHashMap::default(), 53 | width: (width / 2) as u16, 54 | height: (height / 4) as u16, 55 | } 56 | } 57 | 58 | /// Clears the canvas. 59 | pub fn clear(&mut self) { 60 | self.chars.clear(); 61 | } 62 | 63 | /// Sets a pixel at the specified coordinates. 64 | pub fn set(&mut self, x: u32, y: u32) { 65 | let (row, col) = ((x / 2) as u16, (y / 4) as u16); 66 | let a = self 67 | .chars 68 | .entry((row, col)) 69 | .or_insert((0, ' ', false, PixelColor::White)); 70 | a.0 |= PIXEL_MAP[y as usize % 4][x as usize % 2]; 71 | a.1 = ' '; 72 | a.2 = false; 73 | a.3 = PixelColor::White; 74 | } 75 | 76 | /// Sets a pixel at the specified coordinates. 77 | /// specifying the color of the braille char 78 | pub fn set_colored(&mut self, x: u32, y: u32, color: PixelColor) { 79 | let (row, col) = ((x / 2) as u16, (y / 4) as u16); 80 | let a = self 81 | .chars 82 | .entry((row, col)) 83 | .or_insert((0, ' ', false, PixelColor::White)); 84 | a.0 |= PIXEL_MAP[y as usize % 4][x as usize % 2]; 85 | a.1 = ' '; 86 | a.2 = true; 87 | a.3 = color; 88 | } 89 | 90 | /// Sets a letter at the specified coordinates. 91 | pub fn set_char(&mut self, x: u32, y: u32, c: char) { 92 | let (row, col) = ((x / 2) as u16, (y / 4) as u16); 93 | let a = self 94 | .chars 95 | .entry((row, col)) 96 | .or_insert((0, ' ', false, PixelColor::White)); 97 | a.0 = 0; 98 | a.1 = c; 99 | a.2 = false; 100 | a.3 = PixelColor::White; 101 | } 102 | 103 | /// Draws text at the specified coordinates (top-left of the text) up to max_width length 104 | pub fn text(&mut self, x: u32, y: u32, max_width: u32, text: &str) { 105 | for (i, c) in text.chars().enumerate() { 106 | let w = i as u32 * 2; 107 | if w > max_width { 108 | return; 109 | } 110 | self.set_char(x + w, y, c); 111 | } 112 | } 113 | 114 | /// Deletes a pixel at the specified coordinates. 115 | pub fn unset(&mut self, x: u32, y: u32) { 116 | let (row, col) = ((x / 2) as u16, (y / 4) as u16); 117 | let a = self 118 | .chars 119 | .entry((row, col)) 120 | .or_insert((0, ' ', false, PixelColor::White)); 121 | a.0 &= !PIXEL_MAP[y as usize % 4][x as usize % 2]; 122 | } 123 | 124 | /// Toggles a pixel at the specified coordinates. 125 | pub fn toggle(&mut self, x: u32, y: u32) { 126 | let (row, col) = ((x / 2) as u16, (y / 4) as u16); 127 | let a = self 128 | .chars 129 | .entry((row, col)) 130 | .or_insert((0, ' ', false, PixelColor::White)); 131 | a.0 ^= PIXEL_MAP[y as usize % 4][x as usize % 2]; 132 | } 133 | 134 | /// Detects whether the pixel at the given coordinates is set. 135 | pub fn get(&self, x: u32, y: u32) -> bool { 136 | let (row, col) = ((x / 2) as u16, (y / 4) as u16); 137 | self.chars.get(&(row, col)).map_or(false, |a| { 138 | let dot_index = PIXEL_MAP[y as usize % 4][x as usize % 2]; 139 | a.0 & dot_index != 0 140 | }) 141 | } 142 | 143 | /// Returns a `Vec` of each row of the `Canvas`. 144 | /// 145 | /// Note that each row is actually four pixels high due to the fact that a single Braille 146 | /// character spans two by four pixels. 147 | pub fn rows(&self) -> Vec { 148 | let mut maxrow = self.width; 149 | let mut maxcol = self.height; 150 | for &(x, y) in self.chars.keys() { 151 | if x > maxrow { 152 | maxrow = x; 153 | } 154 | if y > maxcol { 155 | maxcol = y; 156 | } 157 | } 158 | 159 | let mut result = Vec::with_capacity(maxcol as usize + 1); 160 | for y in 0..=maxcol { 161 | let mut row = String::with_capacity(maxrow as usize + 1); 162 | for x in 0..=maxrow { 163 | let cell = 164 | self.chars 165 | .get(&(x, y)) 166 | .cloned() 167 | .unwrap_or((0, ' ', false, PixelColor::White)); 168 | match cell { 169 | (0, _, _, _) => row.push(cell.1), 170 | (_, _, false, _) => row.push(char::from_u32(0x2800 + cell.0 as u32).unwrap()), 171 | (_, _, true, _) => { 172 | row = format!( 173 | "{0}{1}", 174 | row, 175 | String::from(char::from_u32(0x2800 + cell.0 as u32).unwrap()) 176 | .color(cell.3) 177 | ) 178 | } 179 | }; 180 | } 181 | result.push(row); 182 | } 183 | result 184 | } 185 | 186 | /// Draws the canvas to a `String` and returns it. 187 | pub fn frame(&self) -> String { 188 | self.rows().join("\n") 189 | } 190 | 191 | /// Draws a line from `(x1, y1)` to `(x2, y2)` onto the `Canvas`. 192 | pub fn line(&mut self, x1: u32, y1: u32, x2: u32, y2: u32) { 193 | let xdiff = cmp::max(x1, x2) - cmp::min(x1, x2); 194 | let ydiff = cmp::max(y1, y2) - cmp::min(y1, y2); 195 | let xdir = if x1 <= x2 { 1 } else { -1 }; 196 | let ydir = if y1 <= y2 { 1 } else { -1 }; 197 | 198 | let r = cmp::max(xdiff, ydiff); 199 | 200 | for i in 0..=r { 201 | let mut x = x1 as i32; 202 | let mut y = y1 as i32; 203 | 204 | if ydiff != 0 { 205 | y += ((i * ydiff) / r) as i32 * ydir; 206 | } 207 | if xdiff != 0 { 208 | x += ((i * xdiff) / r) as i32 * xdir; 209 | } 210 | 211 | self.set(x as u32, y as u32); 212 | } 213 | } 214 | 215 | /// Draws a line from `(x1, y1)` to `(x2, y2)` onto the `Canvas` 216 | /// specifying the color of the line 217 | pub fn line_colored(&mut self, x1: u32, y1: u32, x2: u32, y2: u32, color: PixelColor) { 218 | let xdiff = cmp::max(x1, x2) - cmp::min(x1, x2); 219 | let ydiff = cmp::max(y1, y2) - cmp::min(y1, y2); 220 | let xdir = if x1 <= x2 { 1 } else { -1 }; 221 | let ydir = if y1 <= y2 { 1 } else { -1 }; 222 | 223 | let r = cmp::max(xdiff, ydiff); 224 | 225 | for i in 0..=r { 226 | let mut x = x1 as i32; 227 | let mut y = y1 as i32; 228 | 229 | if ydiff != 0 { 230 | y += ((i * ydiff) / r) as i32 * ydir; 231 | } 232 | if xdiff != 0 { 233 | x += ((i * xdiff) / r) as i32 * xdir; 234 | } 235 | 236 | self.set_colored(x as u32, y as u32, color); 237 | } 238 | } 239 | } 240 | 241 | /// A ‘turtle’ that can walk around a canvas drawing lines. 242 | pub struct Turtle { 243 | pub x: f32, 244 | pub y: f32, 245 | pub brush: bool, 246 | pub use_color: bool, 247 | pub brush_color: PixelColor, 248 | pub rotation: f32, 249 | pub cvs: Canvas, 250 | } 251 | 252 | impl Turtle { 253 | /// Create a new `Turtle`, starting at the given coordinates. 254 | /// 255 | /// The turtle starts with its brush down, facing right. 256 | pub fn new(x: f32, y: f32) -> Turtle { 257 | Turtle { 258 | cvs: Canvas::new(0, 0), 259 | x: x, 260 | y: y, 261 | brush: true, 262 | use_color: false, 263 | brush_color: PixelColor::White, 264 | rotation: 0.0, 265 | } 266 | } 267 | 268 | /// Creates a new `Turtle` with the provided `Canvas`, starting at the given coordinates. 269 | /// 270 | /// The turtle starts with its brush down, facing right. 271 | pub fn from_canvas(x: f32, y: f32, cvs: Canvas) -> Turtle { 272 | Turtle { 273 | cvs: cvs, 274 | x: x, 275 | y: y, 276 | brush: true, 277 | use_color: false, 278 | brush_color: PixelColor::White, 279 | rotation: 0.0, 280 | } 281 | } 282 | 283 | /// Sets the width of a `Turtle`’s `Canvas`, and return it for use again. 284 | pub fn width(mut self, width: u32) -> Turtle { 285 | self.cvs.width = width as u16; 286 | self 287 | } 288 | 289 | /// Sets the height of a `Turtle`’s `Canvas`, and return it for use again. 290 | pub fn height(mut self, height: u32) -> Turtle { 291 | self.cvs.height = height as u16; 292 | self 293 | } 294 | 295 | /// Lifts the `Turtle`’s brush. 296 | pub fn up(&mut self) { 297 | self.brush = false; 298 | } 299 | 300 | /// Puts down the `Turtle`’s brush. 301 | pub fn down(&mut self) { 302 | self.brush = true; 303 | } 304 | 305 | /// Toggles the `Turtle`’s brush. 306 | pub fn toggle(&mut self) { 307 | self.brush = !self.brush; 308 | } 309 | 310 | /// Use specific color the the brush. 311 | pub fn color(&mut self, brush_color: PixelColor) { 312 | self.use_color = true; 313 | self.brush_color = brush_color; 314 | } 315 | 316 | /// Remove color from brush. 317 | pub fn clean_brush(&mut self) { 318 | self.use_color = false; 319 | } 320 | 321 | /// Moves the `Turtle` forward by `dist` steps. 322 | pub fn forward(&mut self, dist: f32) { 323 | let x = self.x + degrees_to_radians(self.rotation).cos() * dist; 324 | let y = self.y + degrees_to_radians(self.rotation).sin() * dist; 325 | self.teleport(x, y); 326 | } 327 | 328 | /// Moves the `Turtle` backward by `dist` steps. 329 | pub fn back(&mut self, dist: f32) { 330 | self.forward(-dist); 331 | } 332 | 333 | /// Teleports the `Turtle` to the given coordinates. 334 | /// 335 | /// Note that this draws a line between the old position and the new one if the `Turtle`’s 336 | /// brush is down. 337 | pub fn teleport(&mut self, x: f32, y: f32) { 338 | if self.brush { 339 | if self.use_color { 340 | self.cvs.line_colored( 341 | cmp::max(0, self.x.round() as i32) as u32, 342 | cmp::max(0, self.y.round() as i32) as u32, 343 | cmp::max(0, x.round() as i32) as u32, 344 | cmp::max(0, y.round() as i32) as u32, 345 | self.brush_color, 346 | ); 347 | } else { 348 | self.cvs.line( 349 | cmp::max(0, self.x.round() as i32) as u32, 350 | cmp::max(0, self.y.round() as i32) as u32, 351 | cmp::max(0, x.round() as i32) as u32, 352 | cmp::max(0, y.round() as i32) as u32, 353 | ); 354 | } 355 | } 356 | 357 | self.x = x; 358 | self.y = y; 359 | } 360 | 361 | /// Turns the `Turtle` right (clockwise) by `angle` degrees. 362 | pub fn right(&mut self, angle: f32) { 363 | self.rotation += angle; 364 | } 365 | 366 | /// Turns the `Turtle` left (clockwise) by `angle` degrees. 367 | pub fn left(&mut self, angle: f32) { 368 | self.rotation -= angle; 369 | } 370 | 371 | /// Writes the `Turtle`’s `Canvas` to a `String` and returns it. 372 | pub fn frame(&self) -> String { 373 | self.cvs.frame() 374 | } 375 | } 376 | 377 | fn degrees_to_radians(deg: f32) -> f32 { 378 | deg * (f32::consts::PI / 180.0f32) 379 | } 380 | --------------------------------------------------------------------------------