In [2]:
//returns wether or not a point (px, py) is above a line, defined by its origin and direction:

fn is_above(px: i64, py: i64, origin_x: i64, origin_y: i64, direction_x: i64, direction_y: i64)->bool{
    let px = px - origin_x;
    let py = py - origin_y;
    let result = px * direction_y - py * direction_x; 
    return result < 0;
}
In [5]:
println!("is_above: {}", is_above(0, 1, 0, 0, 1, 1));
println!("is_above: {}", is_above(0, 1, 1, 1, -1, -1));
println!("is_above: {}", is_above(0, -1, 0, 0, 1, 1));
is_above: true
is_above: false
is_above: false
In [15]:
//returns wether or not a point (px, py) is inside a triangle defined by its three points
fn point_in_triangle(px: i64, py: i64, triangle: [[i64;2];3])->bool{
    let direction_x = triangle[1][0] - triangle[0][0];
    let direction_y = triangle[1][1] - triangle[0][1];
    let result1 = is_above(px, py, triangle[0][0], triangle[0][1], direction_x, direction_y);
    
    let direction_x = triangle[2][0] - triangle[1][0];
    let direction_y = triangle[2][1] - triangle[1][1];
    let result2 = is_above(px, py, triangle[1][0], triangle[1][1], direction_x, direction_y);
    
    let direction_x = triangle[0][0] - triangle[2][0];
    let direction_y = triangle[0][1] - triangle[2][1];
    let result3 = is_above(px, py, triangle[2][0], triangle[2][1], direction_x, direction_y);
    
    let result1 = result1 as i8 * 2 - 1;
    let result2 = result2 as i8 * 2 - 1;
    let result3 = result3 as i8 * 2 - 1;
    
    return (result1 + result2 + result3).abs() == 1;
}
In [16]:
:dep image = "0.23"
:dep evcxr_image = "1.1"
use evcxr_image::ImageDisplay;

image::ImageBuffer::from_fn(32, 32, |x, y| {
    if point_in_triangle(x as i64, y as i64, [[1, 1], [16, 5], [1,32]]) {
        image::Rgb([255;3])
    } else {
        image::Rgb([0;3])
    }
})
Out[16]:
In [12]:
:dep image = "0.23"
:dep evcxr_image = "1.1"
use evcxr_image::ImageDisplay;
//the arrangement of the 3 triangle points does not matter
image::ImageBuffer::from_fn(32, 32, |x, y| {
    if point_in_triangle(x as i64, y as i64, [[1, 32], [16, 5], [1,1]]) {
        image::Rgb([255;3])
    } else {
        image::Rgb([0;3])
    }
})
Out[12]:
In [18]:
:dep image = "0.23"
:dep evcxr_image = "1.1"
use evcxr_image::ImageDisplay;
//the arrangement of the 3 triangle points does not matter
image::ImageBuffer::from_fn(32, 32, |x, y| {
    if point_in_triangle(x as i64, y as i64, [[1, 32], [1, 1], [16,5]]) {
        image::Rgb([255;3])
    } else {
        image::Rgb([0;3])
    }
})
Out[18]:
In [20]:
:dep image = "0.23"
:dep evcxr_image = "1.1"
use evcxr_image::ImageDisplay;
//the arrangement of the 3 triangle points does not matter
image::ImageBuffer::from_fn(32, 32, |x, y| {
    if point_in_triangle(x as i64, y as i64, [[1, 1], [1, 31], [31,1]]) {
        image::Rgb([255;3])
    } else {
        image::Rgb([0;3])
    }
})
Out[20]:
In [ ]: