#include "layout_transform.h"

transform2d::transform2d(const Eigen::Vector2f& in_translation, float in_rotation, const Eigen::Vector2f& in_scale): translation_(in_translation), scale_(in_scale), rotation_(in_rotation) {
	update_matrix();
}

void transform2d::set_transform(const Eigen::Vector2f& in_translation, float in_rotation,
	const Eigen::Vector2f& in_scale) {
	translation_ = in_translation;
	rotation_    = in_rotation;
	scale_      = in_scale;

	update_matrix();
}

void transform2d::translate(const Eigen::Vector2f& in_delta) {
	translation_ += in_delta;
	update_matrix();
}

void transform2d::rotate(float in_angle) {
	rotation_ += in_angle;
	update_matrix();
}

void transform2d::scale(const Eigen::Vector2f& in_scale) {
	scale_.array() *= in_scale.array();
	update_matrix();
}

void transform2d::update_matrix() {
	// 构建变换矩阵: 平移 * 旋转 * 缩放
	const float con_theta = std::cos(rotation_);
	const float sin_theta = std::sin(rotation_);

	// 缩放矩阵
	Eigen::Matrix3f s = Eigen::Matrix3f::Identity();
	s(0, 0)           = scale_.x();
	s(1, 1)           = scale_.y();

	// 旋转矩阵
	Eigen::Matrix3f r = Eigen::Matrix3f::Identity();
	r(0, 0)           = con_theta;
	r(0, 1)           = -sin_theta;
	r(1, 0)           = sin_theta;
	r(1, 1)           = con_theta;

	// 平移矩阵
	Eigen::Matrix3f t = Eigen::Matrix3f::Identity();
	t(0, 2)           = translation_.x();
	t(1, 2)           = translation_.y();

	// 更新变换矩阵
	matrix_ = t * r * s;
}
