C++と色々

主にC++やプログラムに関する記事を投稿します。

2次ベジェ曲線

2次ベジェ曲線買いてみようと思った。折角なので自作のDirectXラッパライブラリで書いてみた。

#include <Frame.h>
#include <Utility.h>
#include <memory>
#include <list>
using namespace NekLib;
using NekLib::Utility::DrawPoint;
using NekLib::Utility::GetColor;

#ifdef _DEBUG
#pragma comment(lib, "NekLib_d.lib")
#else
#pragma comment(lib, "NekLib.lib")
#endif

const float X1 = 0.0f;
const float Y1 = 200.0f;
const float X2 = 100.0f;
const float Y2 = 0.0f;
const float X3 = 200.0f;
const float Y3 = 200.0f;

class Game
{
	float t;
	const DWORD Red;
	float x;
	float y;
	float xline[2];
	float yline[2];
	std::list<float> xlog;
	std::list<float> ylog;

public:
	Game();
	void Update();
	void Draw();
};

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow)
{
	Frame* pFrame = Frame::Get();

	pFrame->Init("Bezier", 200, 200, false, true);

	pFrame->Create();

	pFrame->Run(std::shared_ptr<Game>(new Game()).get());

	return 0;
}

Game::Game() : t(0.0f), Red(GetColor(255, 0, 0)), x(0.0f), y(0.0f)
{
}

void Game::Update()
{
	if(t <= 1.0f)
	{
		xline[0] = X1 * (1.0f - t) + X2 * t;
		xline[1] = X2 * (1.0f - t) + X3 * t;
		yline[0] = Y1 * (1.0f - t) + Y2 * t;
		yline[1] = Y2 * (1.0f - t) + Y3 * t;
		x = xline[0] * (1.0f - t) + xline[1] * t;
		y = yline[0] * (1.0f - t) + yline[1] * t;

		xlog.push_back(x);
		ylog.push_back(y);

		t += 0.004f;
	}
}

void Game::Draw()
{
	auto xit = xlog.begin();
	auto yit = ylog.begin();

	for(; xit != xlog.end() || yit != ylog.end(); xit++, yit++)
	{
		DrawPoint(static_cast<int>(*xit), static_cast<int>(*yit), Red);
	}

	int FX1 = static_cast<int>(X1);
	int FX2 = static_cast<int>(X2);
	int FX3 = static_cast<int>(X3);
	int FY1 = static_cast<int>(Y1);
	int FY2 = static_cast<int>(Y2);
	int FY3 = static_cast<int>(Y3);

	Utility::DrawLine(FX1, FY1, FX2, FY2, GetColor(0, 0, 0));
	Utility::DrawLine(FX2, FY2, FX3, FY3, GetColor(0, 0, 0));

	Utility::DrawLine(
		static_cast<int>(xline[0]), static_cast<int>(yline[0]),
		static_cast<int>(xline[1]), static_cast<int>(yline[1]),
		GetColor(255, 255, 0)
		);
}

実行結果

大分クソースだけど、まぁいいや… メッチャ重い。なんとか軽くしたい。