Newer
Older
Import / research / 3d-experiments / WireFrame / WireFrame.cpp
//
//  WireFrame.cpp
//  WireFrame
//
//  Created by John Ryland on 2/10/17.
//  Copyright © 2017 John Ryland. All rights reserved.
//

#include "../Framework/Framework.h"


DECLARE_PROGRAM_UNIFORMS(VertexColorProgram)
  DECLARE_UNIFORM(mat4, modelViewProjectionMatrix)
DECLARE_PROGRAM_UNIFORMS_END


DECLARE_VERTEX(VertexColorVertex)
  DECLARE_ATTRIB(vec3,  pos, GL_FALSE)
  DECLARE_ATTRIB(col4i, col, GL_TRUE)
DECLARE_VERTEX_END


const char* s_vertexColorsVertexShader =
R"(
  varying lowp vec4 colorVarying;
  void main()
  {
    colorVarying = col;
    gl_Position = modelViewProjectionMatrix * vec4(pos, 1.0);
  }
)";


const char* s_vertexColorsFragmentShader =
R"(
  varying lowp vec4 colorVarying;
  void main()
  {
    gl_FragColor = colorVarying;
  }
)";


class WireFrame : public DemoContext
{
public:
  ~WireFrame() override;
  void prepare() override;
  void update(float a_seconds) override;
  void draw() override;
  void onResize(const vec2f& a_shape) override;

private:
  ProgramContext2<VertexColorProgram, VertexColorVertex>  m_demoModelContext;
  float m_projectionMatrix[16];
};


WireFrame::~WireFrame()
{
  m_demoModelContext.shutdown();
}


void WireFrame::prepare()
{
  OptionsType options;
  m_demoModelContext.setup(s_vertexColorsVertexShader, s_vertexColorsFragmentShader, Medium, options, 0, Lines);
  m_demoModelContext.m_vertexArray.m_vertexData.clear();

  const int lineSegments[12][2] = {{0,1},{1,3},{3,2},{2,0}, {4,5},{5,7},{7,6},{6,4}, {0,4},{1,5},{3,7},{2,6}};
  float cuboid[8][4];
  for (int i = 0; i < 8; i++)
  {
    cuboid[i][0] = ((i&1) ? 0.5f : -0.5f);
    cuboid[i][1] = ((i&2) ? 0.5f : -0.5f);
    cuboid[i][2] = ((i&4) ? 0.5f : -0.5f);
  }
  for (int i = 0; i < 12; i++)
  {
    for (int p = 0; p < 2; p++)
    {
      m_demoModelContext.m_vertexArray.m_vertexData.emplace_back(VertexColorVertex{
         cuboid[lineSegments[i][p]][0], cuboid[lineSegments[i][p]][1], cuboid[lineSegments[i][p]][2], 255, 128, 128 } );
    }
  }
  
  m_demoModelContext.update();
}


void WireFrame::onResize(const vec2f& a_shape)
{
  float fov = 45.0f;
  float aspect = a_shape.x / a_shape.y;
  Math::makePerspectiveMatrix4x4(m_projectionMatrix, Math::degreesToRadians(fov), aspect, 0.1f, 100.0f);
}


void WireFrame::update(float a_seconds)
{
  float trans[3] = { 0.0f, 0.0f, -20.0f };
  float rotate[3] = { fmod(a_seconds*23.f, 360.0f), fmod(a_seconds*37.f, 360.0f), fmod(a_seconds*46.0f, 360.0f)};
  float baseModelViewMatrix[16];
  Math::translationRotationScaleToMatrix4x4(baseModelViewMatrix, trans, rotate, 5.0f);

  Math::multiplyMatrix4x4(m_demoModelContext.m_uniforms.m_modelViewProjectionMatrix.m[0], m_projectionMatrix, baseModelViewMatrix);
}


void WireFrame::draw()
{
  m_demoModelContext.draw();
}


REGISTER_DEMO_CONTEXT("WireFrame", WireFrame)