为方便点Point的几何变换,点的几何属性x、y保存在转换矩阵的m01、m02变量中,转换矩阵如下:
1 m01 m02
0 0 0
0 0 0
Point类是转换矩阵的一个特例。详细代码如下,相关代码见附件:
/*
* 点的类Point
** 编制人: $ource
* 修改版次及创建时间:0版完成版(2024年8月25日)
* 修改内容及时间:无
* 待完善问题:无
* 内容说明:点的几何属性保存在转换矩阵的m01、m02变量中。
*/
use super::*;
use super::super::angle::Angle;
use std::ops::{Add,Sub};
//表示点的矩阵Point
pub type Point=Matrix<f64,f64,Zero,Zero,Zero,Zero>;
impl Point{
pub fn new(dx:f64,dy:f64)->Point{
Point{
m01:dx, m02:dy,
m11:Zero{}, m12:Zero{},
m21:Zero{}, m22:Zero{}
}
}
pub fn get_x(&self)->f64{
self.m01
}
pub fn get_y(&self)->f64{
self.m02
}
pub fn set_x(&mut self,dx:f64){
self.m01=dx;
}
pub fn set_y(&mut self,dy:f64){
self.m02=dy;
}
pub fn polar(distance:f64, angle:Angle)->Point{
Point::new(distance * angle.unit_x() ,distance * angle.unit_y())
}
// 极坐标属性
pub fn get_distance(&self)->f64{
(self.m01 * self.m01 + self.m02 * self.m02).sqrt()
}
pub fn set_distance(&mut self,d:f64){
if self.m02== 0f64 {
self.m02=d;//保证原Distance!=0
}else{
let dd=d / self.get_distance();
*self=Point::new(self.m01*dd,self.m02*dd);
}
}
pub fn get_angle(&self)->Angle{
Angle::from(self.m01,self.m02)
}
pub fn set_angle(&mut self,angle:Angle){
let d=self.get_distance();
*self=Point::new(angle.unit_x()*d,angle.unit_y()*d);
}
}
impl Mul<M2D> for Point{
type Output = Point;
fn mul(self, tm:M2D) ->Point{
Point::new(
self.m01 * tm.m11 + self.m02 * tm.m21 + tm.m01,
self.m01 * tm.m12 + self.m02 * tm.m22 + tm.m02
)
}
}
impl Mul<Move> for Point{
type Output = Point;
fn mul(self, tm:Move) ->Point{
Point::new(
self.m01 + tm.m01,
self.m02+ tm.m02
)
}
}
impl Div<Move> for Point{
type Output = Point;
fn div(self, tm:Move) ->Point{
Point::new(
self.m01 - tm.m01,
self.m02 - tm.m02
)
}
}
impl Add<Point> for Point{
type Output = Point;
fn add(self, other: Point) ->Point{
Point::new(self.m01+other.m01,self.m02+other.m02)
}
}
impl Sub<Point> for Point{
type Output = Point;
fn sub(self, other: Point) ->Point{
Point::new(self.m01-other.m01,self.m02-other.m02)
}
}
#[cfg(test)] //cfg 属性负责控制条件编译,并仅会在谓词为 true 时编译其所附带的内容。cargo test 时满足运行条件
mod tests {
use super::*;
#[test]
fn point_test() {
assert_eq!((Point::new(1f64,1f64)+Point::new(5f64,5f64)-Point::new(5f64,5f64)).get_x(),1f64);
}
}