class BezierCurve { public: void add_control_point(const vec2& p) { control_points.push_back(p); } void deCastelijau(int resolution) { //todo... } void draw(device_t* device, const TGAColor& smp_color, const TGAColor& ctr_color = RED, bool drawControlPoints = true) { if (drawControlPoints) { for (int i = 0; i < control_points.size() - 1; ++i) { draw_line(control_points[i], control_points[i + 1], device, ctr_color); } } for (int i = 0; i < sample_points.size() - 1; ++i) { draw_line(sample_points[i], sample_points[i + 1], device, smp_color); } } private: vector<vec2> control_points; //控制点 vector<vec2> sample_points; //贝塞尔曲线上的点 };完善代码
时间: 2023-06-18 21:07:01 浏览: 85
以下是完整的BezierCurve类的代码,其中deCastelijau函数实现了贝塞尔曲线的生成算法:
```
#include <vector>
#include "geometry.h"
#include "tgaimage.h"
class BezierCurve {
public:
void add_control_point(const vec2& p) {
control_points.push_back(p);
}
void deCastelijau(int resolution) {
sample_points.clear();
if (control_points.size() < 2) {
return;
}
for (int i = 0; i <= resolution; ++i) {
float t = static_cast<float>(i) / static_cast<float>(resolution);
vec2 p = deCastelijau(control_points, t);
sample_points.push_back(p);
}
}
void draw(device_t* device, const TGAColor& smp_color, const TGAColor& ctr_color = RED, bool drawControlPoints = true) {
if (drawControlPoints) {
for (int i = 0; i < control_points.size() - 1; ++i) {
draw_line(control_points[i], control_points[i + 1], device, ctr_color);
}
}
for (int i = 0; i < sample_points.size() - 1; ++i) {
draw_line(sample_points[i], sample_points[i + 1], device, smp_color);
}
}
private:
vector<vec2> control_points; // 控制点
vector<vec2> sample_points; // 贝塞尔曲线上的点
vec2 deCastelijau(const vector<vec2>& points, float t) {
if (points.size() == 1) {
return points[0];
}
vector<vec2> new_points(points.size() - 1);
for (int i = 0; i < points.size() - 1; ++i) {
new_points[i] = (1 - t) * points[i] + t * points[i + 1];
}
return deCastelijau(new_points, t);
}
};
```
其中的deCastelijau函数是递归实现的,通过向下逐层迭代,生成贝塞尔曲线上的点。在draw函数中,如果drawControlPoints参数为true,则绘制出所有控制点之间的连线,否则仅绘制贝塞尔曲线上的点之间的连线。
阅读全文