Skip to content

Instantly share code, notes, and snippets.

@tek-nishi
Created June 24, 2018 09:29
Show Gist options
  • Save tek-nishi/e529c99a42913060a986782fece3de61 to your computer and use it in GitHub Desktop.
Save tek-nishi/e529c99a42913060a986782fece3de61 to your computer and use it in GitHub Desktop.
OpenSiv3D 実装会(6/24)で作ったサンプル1
//
// Siv3Dで3D
//
# include <Siv3D.hpp>
// ベクトル&行列ライブラリ
// SOURCE https://glm.g-truc.net/0.9.8/index.html
# include "glm/glm.hpp"
# include "glm/gtc/matrix_transform.hpp"
# include "glm/gtx/transform.hpp"
# include "glm/gtx/string_cast.hpp"
void Main()
{
const int window_width = 960;
const int window_height = 640;
Window::Resize(window_width, window_height);
glm::vec4 vertex[] {
// TOP
{ -1, -1, -1, 1 },
{ 1, -1, -1, 1 },
{ 1, -1, 1, 1 },
{ -1, -1, 1, 1 },
// BOTTOM
{ -1, 1, -1, 1 },
{ -1, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 1, 1, -1, 1 },
// LEFT
{ -1, -1, -1, 1 },
{ -1, -1, 1, 1 },
{ -1, 1, 1, 1 },
{ -1, 1, -1, 1 },
// RIGHT
{ 1, -1, -1, 1 },
{ 1, 1, -1, 1 },
{ 1, 1, 1, 1 },
{ 1, -1, 1, 1 },
// FRONT
{ -1, -1, 1, 1 },
{ 1, -1, 1, 1 },
{ 1, 1, 1, 1 },
{ -1, 1, 1, 1 },
// BACK
{ -1, -1, -1, 1 },
{ -1, 1, -1, 1 },
{ 1, 1, -1, 1 },
{ 1, -1, -1, 1 },
};
auto proj_matrix = glm::perspective(float(M_PI) * 60.0f / 180.0f, float(window_width) / float(window_height), 0.1f, 100.0f);
auto view_matrix = glm::translate(glm::vec3(0, 0, -5.0));
ColorF color[] = {
{ 0, 0, 1 },
{ 0, 1, 0 },
{ 0, 1, 1 },
{ 1, 0, 0 },
{ 1, 0, 1 },
{ 1, 1, 0 },
};
float yaw = 0.0f;
float pitch = 0.0f;
while (System::Update())
{
auto model_matrix = glm::rotate(yaw, glm::vec3(0, 1, 0)) * glm::rotate(pitch, glm::vec3(1, 0, 0));
yaw += 0.01f;
pitch += 0.006f;
for (int i = 0; i < 6; ++i)
{
glm::vec2 p[4];
glm::vec3 p3[4];
for (int j = 0; j < 4; ++j)
{
// 簡易透視変換
auto pos = view_matrix * model_matrix * vertex[i * 4 + j];
p3[j] = pos;
pos = proj_matrix * pos;
pos = pos / pos.w;
// 単位座標→表示画面座標
glm::vec2 p2(pos.x * (window_width / 2), pos.y * (window_height / 2));
p2 = p2 + glm::vec2(window_width / 2, window_height / 2);
p[j] = p2;
}
// 表裏判定
auto a = p[1] - p[0];
auto b = p[2] - p[0];
auto cross = a.x * b.y - b.x * a.y;
if (cross > 0.0f)
{
auto v1 = p3[1] - p3[0];
auto v2 = p3[2] - p3[0];
auto cv = glm::normalize(glm::cross(v1, v2));
auto dot = glm::dot(cv, glm::vec3(0, 0, 1));
Quad(Vec2(p[0].x, p[0].y),
Vec2(p[1].x, p[1].y),
Vec2(p[2].x, p[2].y),
Vec2(p[3].x, p[3].y)).draw(color[i] * dot);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment