Beispiel #1
0
DeferredRenderEngine::DeferredRenderEngine(Scene &scene, RenderTarget &finalTarget, RenderView &finalView)
    : scene(scene)
    , target(finalTarget)
    , view(finalView)
    , color(finalTarget.width, finalTarget.height, GL_RGBA32F)
    , depth(finalTarget.width, finalTarget.height, GL_RGBA32F)
    , normal(finalTarget.width, finalTarget.height, GL_RGBA32F)
    , other(finalTarget.width, finalTarget.height, GL_RGBA32F)
    , perlin(TextureDeserializer("perlin").deserialize())
    , random(TextureDeserializer("random").deserialize())
    , initialR(finalTarget.width, finalTarget.height, true)
    , initial(ShaderProgram(initialVS, initialGS, initialFS, invecs), scene, initialR, view)
    , ambient(ShaderProgram(ambientVS, 0, ambientFS, invecs), Model::Square(), target, nullView)
{
    initialR.AddTarget(color);
    initialR.AddTarget(depth);
    initialR.AddTarget(normal);
    initialR.AddTarget(other);
    initial.AddTexture("perlin", *perlin);
    initial.AddTexture("random", *random);

    ambient.AddTexture("color", color);
    ambient.AddTexture("depth", depth);
    ambient.AddTexture("normal", normal);
    ambient.AddTexture("other", other);
    ambient.AddTexture("random", *random);
}
Beispiel #2
0
water::water()
  : material_(float4(0.4f, 0.4f, 0.4f, 1.0f),
							float4(0.1f, 0.1f, 0.1f, 1.0f),
							float4(0.6f, 0.6f, 0.6f, 1.0f),
							0.9f) {
  render_prog_ = ShaderProgram("Water.vert", "Water.frag");
  sim_prog_ = ShaderProgram("Quad.vert", "WaterSimStep.frag");
  normal_prog_ = ShaderProgram("Quad.vert", "WaterNormal.frag");

  water_mesh_ = new SimpleMesh(render_prog_.program, 256, SimpleMesh::PLANE, 0.999999f);
  
  full_screen_quad_ = new FullScreenQuad();

  grid_size_x_ = 256;
  grid_size_z_ = 256;

  for(int i = 0; i < 3; i++)
    pos_tex_[i] = new RenderableTexture2D(GL_R32F, grid_size_x_, grid_size_z_);

	norm_tex_ = new RenderableTexture2D(GL_RGB16F, grid_size_x_, grid_size_z_);
  a_ = 0; 
  b_ = 1; 
  c_ = 2;

  GLint old_viewport[4];
  glGetIntegerv(GL_VIEWPORT, old_viewport);
  glViewport(0, 0, grid_size_x_, grid_size_z_);
  
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  for(int i = 0; i < 3; i++) {
    pos_tex_[i]->BeginRenderingToThisTexture();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    pos_tex_[i]->EndRenderingToThisTexture();
  }
	norm_tex_->BeginRenderingToThisTexture();
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  norm_tex_->EndRenderingToThisTexture();


  glViewport(old_viewport[0], old_viewport[1], old_viewport[2], old_viewport[3]);

	float4x4 rotation_matrix, scale_matrix, translate_matrix;
  float4x4 transform_matrix1;

  glusScalef(scale_matrix.L(), 10, 10, 10);
  glusTranslatef(translate_matrix.L(), 0,0,0);
  glusMultMatrixf(object_matrix_.L(), translate_matrix.L(), scale_matrix.L());
	//glusMultMatrixf(object_matrix_.L(), scale_matrix.L(), translate_matrix.L());

	glusInverseMatrixf(inversed_object_matrix_.L(), object_matrix_.L());
}
Beispiel #3
0
void createLoadingScreen(const std::string &file_name, GLFWwindow *window) {

    auto program_id = ShaderProgram("src/shaders/vert_texture.glsl", "src/shaders/frag_texture.glsl");
    glUseProgram(program_id);
    InitializeGeometry(program_id);

    FileLoader::TGAFILE_t tgafile;
    FileLoader::LoadTGAFile(file_name.c_str(), &tgafile);

    std::vector<char> buffer(tgafile.imageData, tgafile.imageData + tgafile.imageWidth * tgafile.imageHeight * (tgafile.bitCount / 8));

    GLuint texture_id;
    glGenTextures(1, &texture_id);
    glBindTexture(GL_TEXTURE_2D, texture_id);

    // Set mipmaps
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1500, 843, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer.data());

    auto texture_attrib = glGetUniformLocation(program_id, "Texture");
    glUniform1i(texture_attrib, 0);
    glActiveTexture(GL_TEXTURE0 + 0);
    glBindTexture(GL_TEXTURE_2D, texture_id);
    glClearColor(.5f,.5f,.5f,0);
    // Clear depth and color buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Draw triangles using the program
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glfwSwapBuffers(window);
    //glfwPollEvents();
}
Beispiel #4
0
AnimatedBillboard::AnimatedBillboard(std::string animationFilePath)
	: m_billboard("nanaka/models/billboard.nmdl")
	, m_asset(g_resourceManager->Acquire<BillboardAnimationResource>(
		animationFilePath))
{
	if (!m_asset.IsValid())
	{
		return;
	}

	Material material;
	material.SetShaderProgram(ShaderProgram("nanaka/shaders/scaleoffset.nsp"));
	material.SetTexture(Texture(m_asset.GetResource()->m_textureAsset));
	material.SetTransparent(true);
	material.SetColor(Vec4f(1.0f));

	for (size_t i = 0; i < m_asset.GetResource()->m_times.size(); ++i)
	{
		material.SetTexcoordsScale(
			m_asset.GetResource()->m_texcoordsScales.at(i));
		material.SetTexcoordsOffset(
			m_asset.GetResource()->m_texcoordsOffsets.at(i));
		auto ms = m_asset.GetResource()->m_times.at(i);
		m_materialAnimation.AddKeyframe(
			ms, material, Interpolation<Material>::Flat());
	}

	m_materialAnimation.ResetAnimation();
}
void GameOfLifeWorldRenderer::initializeShaders()
{
	VertexShader vertexShader(
		"#version 330 core\n"
		"layout (location = 0) in vec2 position;\n"
		"layout (location = 1) in vec2 offset;\n"
		"layout (location = 2) in vec3 color;\n"
		"out vec3 fColor;\n"
		"void main()\n"
		"{\n"
		"	gl_Position = vec4(position + offset, 0.0f, 1.0f);\n"
		"	fColor = color;\n"
		"}\n"
	);
	FragmentShader fragmentShader(
		"#version 330 core\n"
		"in vec3 fColor;\n"
		"out vec4 color;\n"
		"void main()\n"
		"{\n"
		"	color = vec4(fColor, 1.0f);\n"
		"}\n"
	);

	program = ShaderProgram(vertexShader, fragmentShader);
}
Beispiel #6
0
MaterialData *NmtReader::loadV1(const char *data, void *) {
	Version1Header header;
	memcpy(&header, data, sizeof(Version1Header));
	if(header.version != 1) {
		logMsg("Invalid material version", ErrorLog);
	}

	MaterialData *mat = new MaterialData();

	if(header.renderDataOffset != 0) {
		memcpy(&mat->render, data + header.renderDataOffset, sizeof(uint32));
	}

	if(header.shaderLen) {
		core::String shader(data + header.shaderCodeOffset, header.shaderLen);
		mat->prog = ShaderProgram(new Shader<FragmentShader>(shader));
	}

	for(uint i = 0; i != 4; i++) {
		uint offset = header.texHeaderOffset[i];
		if(offset) {
			Version1TexHeader h;
			memcpy(&h, data + offset, sizeof(Version1TexHeader));

			core::String texName(data + offset, h.nameLen);
			mat->surface.textures[i] = Texture(ImageLoader::load<core::String>(texName), true);
		}
	}


	return mat;
}
Beispiel #7
0
NmtReader::NmtReader() {

	addReader(FragShader, [](const char *data, uint offset, MaterialData *mat, void *) {
		logMsg("shader");
		uint length = 0;
		memcpy(&length, data + offset, sizeof(uint));
		if(length) {
			core::String shader(data + offset + sizeof(uint), length);
			mat->prog = ShaderProgram(new Shader<FragmentShader>(shader));
		}
	});

	addReader(RenderData, [](const char *data, uint offset, MaterialData *mat, void *) {
		logMsg("data");
		memcpy(&mat->render, data + offset, sizeof(mat->render));
	});

	addReader(TextureName, [](const char *data, uint offset, MaterialData *mat, void *) {
		logMsg("texture");
		uint length = 0;
		memcpy(&length, data + offset, sizeof(uint));
		if(length) {
			uint id = 0;
			memcpy(&id, data + offset + sizeof(uint), sizeof(uint));
			core::String texName(data + offset + 2 * sizeof(uint), length);
			mat->surface.textures[id] = Texture(ImageLoader::load<core::String>(texName), true);
		}
	});
}
Beispiel #8
0
GLContext *GLContext::getContext() {
	static GLContext *ct = 0;
	if(!ct) {
		ct = new GLContext();
		ShaderProgram().bind();
		MaterialRenderData().bind();
	}
	return ct;
}
FireParticleSystem::FireParticleSystem(int a_particlesNum)
{
  for(int i=0;i<2;i++)
  {
    m_posAndSizeBuffers[i] = -1;
    m_velAndHPBuffers[i]   = -1;
    m_drawVAOs[i]          = -1;
  }
  m_vertexPosTBO = -1;

  m_particlesNum = 0;
  m_currPinPongId = 0;

  m_pFogTexture = NULL;

  glGenBuffers(2, m_posAndSizeBuffers); CHECK_GL_ERRORS;
  glGenBuffers(2, m_velAndHPBuffers);   CHECK_GL_ERRORS;
  glGenBuffers(2, m_randBuffers);       CHECK_GL_ERRORS;

  glGenTextures(1, &m_vertexPosTBO);

  SetParticlesNum(a_particlesNum);
  Init(); // dispatching call

  m_renderProgram  = ShaderProgram("../ParticleSystem/Particle.vert", "../ParticleSystem/FireParticle.geom", "../ParticleSystem/FireParticle.frag");
  m_animateProgram = ShaderProgram("../ParticleSystem/FireParticlePhysics.vert");

  const GLchar* names[3] = {"newPosAndSize", "newVelAndHp", "outRndSeed"};
  glTransformFeedbackVaryings (m_animateProgram.program, 3, names, GL_SEPARATE_ATTRIBS); CHECK_GL_ERRORS;
  if(!m_animateProgram.Link())
    throw std::runtime_error("can not relink program after glTransformFeedbackVaryings");

  CreateBuffers(m_renderProgram.program, m_animateProgram.program);

  //m_pFogTexture = new Texture2D("../data/fog.bmp");
  //m_pFogTexture = new Texture2D("../data/particle.tga");
  m_pFogTexture = new Texture2D("../data/fire_texturemap_small_grey.bmp");

  m_pFullScreenQuad = new FullScreenQuad();
  m_lastDeltaTime = 0.0f;
  m_windChangeTime = 0.0f;
}
Beispiel #10
0
PointLightRenderPass::PointLightRenderPass(Texture &depth, Texture &normals, Texture &color, PointLight &light, RenderView &view, RenderTarget &output)
: depth(depth)
, normals(normals)
, color(color)
, light(light)
, render(ShaderProgram(noneVS, 0, pointLightFS, invecs), Model::Square(), output, view)
{
	render.AddTexture("depth", depth);
	render.AddTexture("normal", normals);
	render.AddTexture("color", color);
}
Beispiel #11
0
MaterialData CompiledMaterial::getMaterial() const {
	MaterialData data;

	String frag = core::String(getShader().toStdString());
	data.prog = ShaderProgram(new Shader<FragmentShader>(frag));

	for(int i = 0; i != samplers.size(); i++) {
		data.surface.textures[i] = samplers[i].texture;
	}

	return data;
}
Beispiel #12
0
ShaderProgram setup()
{
    SDL_Init(SDL_INIT_VIDEO);
    displayWindow = SDL_CreateWindow("Assignment 2 - Sergey Smirnov", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
    SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
    glewInit();
#endif
    glViewport(0, 0, 1280, 720);
    return ShaderProgram(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
}
	static Program make(void)
	{
		const GLchar* shader_source =
		"#version 150\n"
		"uniform mat4 CameraMatrix, ModelMatrix;"
		"uniform mat4 LightProjMatrix;"
		"uniform mat2 TextureMatrix;"
		"uniform vec3 CameraPosition, LightPosition;"
		"uniform vec4 ClipPlane;"
		"uniform float ClipDirection;"
		"in vec4 Position;"
		"in vec3 Normal;"
		"in vec3 Tangent;"
		"in vec2 TexCoord;"
		"out gl_PerVertex {"
		"	vec4 gl_Position;"
		"	float gl_ClipDistance[];"
		"};"
		"out vec3 vertNormal;"
		"out vec3 vertTangent;"
		"out vec3 vertBitangent;"
		"out vec3 vertLightDir;"
		"out vec3 vertViewDir;"
		"out vec2 vertTexCoord;"
		"out vec4 vertLightTexCoord;"
		"void main(void)"
		"{"
		"	gl_Position = "
		"		ModelMatrix *"
		"		Position;"
		"	gl_ClipDistance[0] = "
		"		ClipDirection* "
		"		dot(ClipPlane, gl_Position);"
		"	vertLightDir = LightPosition - gl_Position.xyz;"
		"	vertViewDir = CameraPosition - gl_Position.xyz;"
		"	vertNormal =  (ModelMatrix * vec4(Normal,  0.0)).xyz;"
		"	vertTangent = (ModelMatrix * vec4(Tangent, 0.0)).xyz;"
		"	vertBitangent = cross(vertNormal, vertTangent);"
		"	vertTexCoord = TextureMatrix * TexCoord;"
		"	vertLightTexCoord = LightProjMatrix* gl_Position;"
		"	gl_Position = CameraMatrix * gl_Position;"
		"}";

		return ShaderProgram(
			ShaderType::Vertex,
			shader_source,
			ObjectDesc("Transform")
		);
	}
Beispiel #14
0
void Demo::initGraphics() {
  this->window.makeCurrent();
  FragmentShader f("res/screen.frag");
  VertexShader v("res/screen.vert");

  this->p = ShaderProgram(f, v);

  this->p["P"] = glm::perspective(45.0f, (float)this->window.width / (float)this->window.height, 0.1f, 1000.0f);
  //this->p["V"] = c.viewMatrix();
  //this->p["M"] = glm::translate(glm::mat4(1.0f), boxPosition);

  /*this->t = Texture("res/cubemap.png");
  this->p["tex"] = t;

  this->m = Model("res/cube.obj", this->p, "vertexPosition", "vertexNormal", "vertexUV");*/
}
Beispiel #15
0
ShaderProgram setup()
{
	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("Purple Pong!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
	glewInit();
#endif
	glViewport(0, 0, 1280, 720);



	return ShaderProgram(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
}
Beispiel #16
0
	static Program make(void)
	{
		const GLchar* shader_source =
		"#version 150\n"
		"uniform mat4 CameraMatrix, ModelMatrix;"
		"uniform mat4 LightProjMatrix;"
		"uniform mat2 TextureMatrix;"
		"uniform vec3 CameraPosition, LightPosition;"
		"in vec4 Position;"
		"in vec3 Normal;"
		"in vec2 TexCoord;"

		"out gl_PerVertex {"
		"	vec4 gl_Position;"
		"};"
		"out float vertNoise;"
		"out vec3 vertNormal;"
		"out vec3 vertLightDir, vertViewDir;"
		"out vec2 vertTexCoord;"
		"out vec4 vertLightTexCoord;"
		"void main(void)"
		"{"
		"	gl_Position = "
		"		ModelMatrix *"
		"		Position;"
		"	vertNoise = noise1(Position.x+Position.y+Position.z);"
		"	vertLightDir = LightPosition - gl_Position.xyz;"
		"	vertViewDir = CameraPosition - gl_Position.xyz;"
		"	vertNormal =  (ModelMatrix * vec4(Normal,  0.0)).xyz;"
		"	vertTexCoord = TextureMatrix * TexCoord;"
		"	vertLightTexCoord = LightProjMatrix* gl_Position;"
		"	gl_Position = CameraMatrix * gl_Position;"
		"}";

		return ShaderProgram(
			ShaderType::Vertex,
			shader_source,
			ObjectDesc("Transform")
		);
	}
Beispiel #17
0
pool::pool(GLfloat floor_height, GLfloat left_wall_coord, GLfloat right_wall_coord, GLfloat front_wall_coord, GLfloat back_wall_coord)
    : material_(float4(0.45f, 0.45f, 0.45f, 1.0f),
                float4(0.1f, 0.1f, 0.1f, 1.0f),
                float4(0.01f, 0.01f, 0.01f, 1.0f),
                0.01f) {
    render_prog_ = ShaderProgram("Room.vert", "Room.frag");
    pool_mesh_ = new SimpleMesh(render_prog_ .program, 256, SimpleMesh::PLANE, 1.0f);

    floor_tex_ = new Texture2D("pool_texture.bmp");

    wall_coord_[FLOOR]      = float3(0, floor_height, 0);
    wall_coord_[LEFT_WALL]  = float3(left_wall_coord, 0, 0);
    wall_coord_[RIGHT_WALL] = float3(right_wall_coord, 0, 0);
    wall_coord_[FRONT_WALL] = float3(0, 0, front_wall_coord);
    wall_coord_[BACK_WALL]  = float3(0, 0, back_wall_coord);

    init_object_matrix(FLOOR,                                  10, 10,                    10,                  0,       floor_height,                0,   0,   0);
    init_object_matrix(LEFT_WALL,  GLfloat(abs(floor_height / 2)), 10,                    10,    left_wall_coord, GLfloat(floor_height / 2.0),                0,   0,  90);
    init_object_matrix(RIGHT_WALL, GLfloat(abs(floor_height / 2)), 10,                    10,   right_wall_coord, GLfloat(floor_height / 2.0),                0,   0, -90);
    init_object_matrix(FRONT_WALL,                             10, 10, abs(floor_height / 2),                  0, GLfloat(floor_height / 2.0), front_wall_coord,  90,   0);
    init_object_matrix(BACK_WALL,                              10, 10, abs(floor_height / 2),                  0, GLfloat(floor_height / 2.0),  back_wall_coord, -90,   0);
}
Beispiel #18
0
TileBatch::TileBatch (uint16 capacity, const math::vec2& tile_size)
    : m_capacity(capacity)
    , m_tileSize(tile_size)
{
    this->blend.enabled = true;

    std::ostringstream vert;
    vert << "#version 330 core\n"
         //
         << "layout (location = " << VA_POS_INDEX   << ") in vec4 v_pos;\n"
         << "layout (location = " << VA_UV_INDEX    << ") in vec2 v_uv;\n"
         << "layout (location = " << VA_COLOR_INDEX << ") in vec4 v_color;\n"
         //
         << "uniform mat4 " << U_PROJ_XF << ";\n"
         //
         << "out vertex_attributes\n"
         << "{\n"
         << "  vec2 uv;\n"
         << "  vec4 color;\n"
         << "} vertex;\n"
         //
         << "void main()\n"
         << "{\n"
         << "  vertex.uv    = v_uv;\n"
         << "  vertex.color = v_color;\n"
         << "  gl_Position  = " << U_PROJ_XF << " * v_pos;\n"
         << "}\n";

    std::ostringstream frag;
    frag << "#version 330 core\n"
         //
         << "layout (location = 0) out vec4 color;\n"
         //
         << "uniform sampler2D " << U_SAMPLER << ";\n"
         //
         << "in vertex_attributes\n"
         << "{\n"
         << "  vec2 uv;\n"
         << "  vec4 color;\n"
         << "} vertex;\n"
         //
         << "void main()\n"
         << "{\n"
         << "  color = vertex.color * texture(" << U_SAMPLER << ", vertex.uv);\n"
         << "}\n";

    m_shader = ShaderProgram(vert.str(), frag.str());

    // TileBatch implements it's buffer object streaming using the orphaning
    // technique, which means for every frame we ask OpenGL to give us a new buffer.
    // Since we request the same size, it's likely (though not guaranteed) that
    // no allocation will take place.  The major drawback of this approach is
    // is it's dependent on the implementation, so performance may differ.
    // https://www.opengl.org/wiki/Buffer_Object_Streaming#Buffer_re-specification
    m_vao = opengl::CreateVertexArray();
    opengl::BindVertexArray(m_vao);

    // VBO
    m_vbo = opengl::CreateBuffer();
    opengl::BindBuffer(GL_ARRAY_BUFFER, m_vbo);

    std::ptrdiff_t vbo_size = m_capacity * TILE_SIZE;
    opengl::SetBufferData(GL_ARRAY_BUFFER, vbo_size, nullptr, GL_DYNAMIC_DRAW);

    opengl::EnableVertexAttribute(VA_POS_INDEX);
    opengl::VertexAttribPointer(VA_POS_INDEX,
                                3,
                                GL_FLOAT,
                                false,
                                VERTEX_SIZE,
                                reinterpret_cast<void*>(offsetof(tile_vertex, pos)));

    opengl::EnableVertexAttribute(VA_UV_INDEX);
    opengl::VertexAttribPointer(VA_UV_INDEX,
                                2,
                                GL_FLOAT,
                                false,
                                VERTEX_SIZE,
                                reinterpret_cast<void*>(offsetof(tile_vertex, uv)));

    opengl::EnableVertexAttribute(VA_COLOR_INDEX);
    opengl::VertexAttribPointer(VA_COLOR_INDEX,
                                4,
                                GL_UNSIGNED_BYTE,
                                true,
                                VERTEX_SIZE,
                                reinterpret_cast<void*>(offsetof(tile_vertex, color)));

    opengl::UnbindBuffers(GL_ARRAY_BUFFER);

    // IBO
    m_ibo = opengl::CreateBuffer();
    opengl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);

    size_t ibo_count = m_capacity * 6;
    size_t ibo_size = ibo_count * sizeof(uint32);

    uint32* ibo_data = (uint32*)RDGE_MALLOC(ibo_size, memory_bucket_graphics);
    if (RDGE_UNLIKELY(!ibo_data))
    {
        RDGE_THROW("Memory allocation failed");
    }

    for (uint32 i = 0, idx = 0, offset = 0;
         i < m_capacity;
         i++, idx = i * 6, offset = i * 4)
    {
        ibo_data[idx]     = offset;
        ibo_data[idx + 1] = offset + 1;
        ibo_data[idx + 2] = offset + 2;

        ibo_data[idx + 3] = offset + 2;
        ibo_data[idx + 4] = offset + 3;
        ibo_data[idx + 5] = offset;
    }

    opengl::SetBufferData(GL_ELEMENT_ARRAY_BUFFER, ibo_size, ibo_data, GL_STATIC_DRAW);
    opengl::UnbindBuffers(GL_ELEMENT_ARRAY_BUFFER);
    RDGE_FREE(ibo_data, memory_bucket_graphics);

    opengl::UnbindVertexArrays();

    DLOG() << "TileBatch[" << this << "]"
           << " capacity=" << m_capacity
           << " tile_size=" << m_tileSize
           << " vao[" << m_vao << "]"
           << " vbo[" << m_vbo << "].size=" << vbo_size
           << " ibo[" << m_ibo << "].size=" << ibo_size;
}
int main(int argc, char *argv[])
{
	//start context
	if (!glfwInit())
	{
		fprintf(stderr, "Error, could not start GLFW3\n");
		return 1;
	}
	else
	{
		fprintf(stderr, "GLFW initialized properly.");
	}

	//Forward compatibility from version 3.2.
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_SAMPLES, 4); //Anti aliasing (4 passes)
	
	//start logs
	Logger::restartLog(GL_LOG_FILE);
	glfwSetErrorCallback(glfwErrorCallback);

	GLFWmonitor* monitor = glfwGetPrimaryMonitor();
	const GLFWvidmode* mode = glfwGetVideoMode(monitor);

	//init window with primary monitor resolution
	//Set these modes for a fullscreen window and don't for classic fullscreen:
	/*glfwWindowHint(GLFW_RED_BITS, mode->redBits);
	glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
	glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
	glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);*/
	//------------------------------------------------

	//GLFWwindow * window = glfwCreateWindow(mode->width, mode->height, "Tutorial 1: Draw a triangle", monitor, NULL); //Fullscreen
	GLFWwindow * window = glfwCreateWindow(800, 600, "Tutorial 1: Draw a triangle", NULL, NULL); //Not Fullscreen

	//if window initialisation failed
	if (!window)
	{
		fprintf(stderr, "Could not open window with GLFW3\n");
		glfwTerminate();
		return 1;
	}

	glfwMakeContextCurrent(window);
	glfwSetWindowSizeCallback(window, glfwWindowSizeCallback);

	//start glew extension handler;
	glewExperimental = GL_TRUE;
	glewInit();

	//get version info
	const GLubyte * renderer = glGetString(GL_RENDERER);
	const GLubyte * version = glGetString(GL_VERSION);

	//Log informations
	Logger::printToLog(GL_LOG_FILE, "Starting GLFW: %s \n", glfwGetVersionString());
	logGlParams();

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);

	//draw triangle
	initTriangles();

	Shader vertex = Shader("vertex.vert", GL_VERTEX_SHADER);
	Shader frag_1 = Shader("frag1.frag", GL_FRAGMENT_SHADER);
	Shader frag_2 = Shader("frag2.frag", GL_FRAGMENT_SHADER);

	Shader shaders_1[2] = { vertex, frag_1 };
	Shader shaders_2[2] = { vertex, frag_2 };

	ShaderProgram shader_programme_1 = ShaderProgram(shaders_1, VERT_FRAG);
	ShaderProgram shader_programme_2 = ShaderProgram(shaders_2, VERT_FRAG);

	while (!glfwWindowShouldClose(window)) {
		updateFpsCounter(window);

		// wipe the drawing surface clear 
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport(0, 0, g_gl_width, g_gl_height);

		glClearColor(0.1f, 0.1f, 0.1f, 0.0f);

		glUseProgram(shader_programme_1.get_program());
		glBindVertexArray(vao_1);

		// draw points 0-5 from the currently bound VAO with current in-use shader 
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glUseProgram(shader_programme_2.get_program());
		glBindVertexArray(vao_2);

		// draw points 0-5 from the currently bound VAO with current in-use shader 
		glDrawArrays(GL_TRIANGLES, 0, 3);

		// update other events like input handling 
		glfwPollEvents();
		// put the stuff we've been drawing onto the display 
		glfwSwapBuffers(window);

		if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) 
		{
			glfwSetWindowShouldClose(window, 1);
		}
	}

	//close gl context and other glfw resources
	glfwTerminate();

	return 0;
}
Beispiel #20
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	#ifdef _WINDOWS
		glewInit();
	#endif
	///setup
		//ShaderProgram program = ShaderProgram(RESOURCE_FOLDER"vertex.glsl", RESOURCE_FOLDER"fragment.glsl");
		ShaderProgram program = ShaderProgram(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
		Matrix projectionMatrix;
		Matrix modelMatrix;
		Matrix viewMatrix;

		projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0, 2.0, -1.0, 1.0);
	
		GLuint Charmander = LoadTexture("Charmander.png");
		GLuint Bulbasaur = LoadTexture("Bulbasaur.png");
		GLuint Squirtle = LoadTexture("Squirtle.png");

		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		float lastFrameTicks = 0.0f;
		float angle = 0.0f;

	SDL_Event event;
	bool done = false;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glClearColor(0.8f, 0.8f, 0.8f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		glUseProgram(program.programID);

		float vertices[] = { -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoords[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
		glEnableVertexAttribArray(program.texCoordAttribute);

		glBindTexture(GL_TEXTURE_2D, Charmander);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		float vertices2[] = { -1.5f, -0.5f, -0.5f, 0.5f, -1.5f, 0.5f, -0.5f, 0.5f, -1.5f, -0.5f, -0.5f, -0.5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoords2[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2);
		glEnableVertexAttribArray(program.texCoordAttribute);

		glBindTexture(GL_TEXTURE_2D, Squirtle);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		float vertices3[] = { 1.5f, -0.5f, 0.5f, 0.5f, 1.5f, 0.5f, 0.5f, 0.5f, 1.5f, -0.5f, 0.5f, -0.5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoords3[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords3);
		glEnableVertexAttribArray(program.texCoordAttribute);

		glBindTexture(GL_TEXTURE_2D, Bulbasaur);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;

		angle += elapsed;
		glMatrixMode(Bulbasaur);
		modelMatrix.identity();
		modelMatrix.Rotate(angle);
		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
Beispiel #21
0
void Game::init() {
    this->window.clearColor(glm::vec3(0.2f, 0.2f, 0.2f));

    FragmentShader f("res/texture.frag");
    VertexShader v("res/texture.vert");
    FragmentShader ffrag("res/text.frag");
    VertexShader fvert("res/text.vert");

    this->p = ShaderProgram(f, v);
    this->text = ShaderProgram(ffrag, fvert);

    this->t = Texture("res/tile.png");
    this->p["tex"] = this->t;
    this->p["P"] = glm::ortho(0.0f, (float)this->window.width, (float)this->window.height, 0.0f, -0.1f, 100.0f);
    this->p["V"] = glm::mat4(1.0f);
    this->p["M"] = glm::scale(glm::translate(glm::mat4(1.0f), glm::vec3(this->window.width / 2 - (gridWidth * 25) / 2, this->window.height / 2 - (gridHeight * 25) / 2, 0.0f)), glm::vec3(25.0f, 25.0f, 0.0f));


    this->font = Texture("res/font.png", GL_NEAREST);
    this->text["tex"] = this->font;
    this->text["P"] = glm::ortho(0.0f, (float)this->window.width, (float)this->window.height, 0.0f, -0.1f, 100.0f);
    this->text["V"] = glm::mat4(1.0f);
    this->text["M"] = glm::mat4(1.0f);

    std::vector<glm::vec3> verts;
    verts.push_back(glm::vec3(0.0f, 0.0f, 0.0f));
    verts.push_back(glm::vec3(0.0f, 1.0f, 0.0f));
    verts.push_back(glm::vec3(1.0f, 1.0f, 0.0f));
    verts.push_back(glm::vec3(1.0f, 0.0f, 0.0f));
    vertices = Buffer(verts);
    vao.setAttrib(this->p, "vertexPosition", vertices, 3, GL_FLOAT, false);

    std::vector<glm::vec2> temp_uvs;
    temp_uvs.push_back(glm::vec2(0, 1));
    temp_uvs.push_back(glm::vec2(0, 0));
    temp_uvs.push_back(glm::vec2(1, 0));
    temp_uvs.push_back(glm::vec2(1, 1));
    uvs = Buffer(temp_uvs);
    vao.setAttrib(this->p, "vertexUV", uvs, 2, GL_FLOAT, false);

    std::vector<unsigned> indices;
    indices.push_back(0);
    indices.push_back(1);
    indices.push_back(2);
    indices.push_back(2);
    indices.push_back(3);
    indices.push_back(0);

    inds = Buffer(indices, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW);

    std::vector<glm::vec2> poss;
    for(int y = 0; y < gridHeight; ++y)
        for(int x = 0; x < gridWidth; ++x)
            poss.push_back(glm::vec2((float)x, (float)y));

    for(int y = 0; y < 4; ++y)
        for(int x = 0; x < 4; ++x)
            poss.push_back(glm::vec2(-6.0f + (float)x, (float)y));

    for(int y = 0; y < 4; ++y)
        for(int x = 0; x < 4; ++x)
            poss.push_back(glm::vec2(gridWidth + 1 + (float)x, (float)y));

    positions = Buffer(poss);
    vao.setAttrib(this->p, "tilePosition", positions, 2, GL_FLOAT, false, 1);
    this->vao.unbind();

    newGame();
}
Beispiel #22
0
ShaderProgram GLContext::getShaderProgram() const {
	return ShaderProgram(program);
}
Beispiel #23
0
int main() {
  // Initialize GLFW
  if (!glfwInit()) {
    std::cerr << "Failed to initialize GLFW!" << std::endl;
    return EXIT_FAILURE;
  }

  // Setup OpenGL context
  glfwWindowHint(GLFW_SAMPLES, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  // Try to create a window
  auto window = glfwCreateWindow( SIZE, SIZE, "OpenGL", NULL, NULL);
  if (window == NULL) {
    std::cerr << "Failed to open GLFW window, your graphics card is probably only capable of OpenGL 2.1" << std::endl;
    glfwTerminate();
    return EXIT_FAILURE;
  }

  // Finalize window setup
  glfwMakeContextCurrent(window);

  // Initialize GLEW
  glewExperimental = GL_TRUE;
  glewInit();
  if (!glewIsSupported("GL_VERSION_3_3")) {
    std::cerr << "Failed to initialize GLEW with OpenGL 3.3!" << std::endl;
    glfwTerminate();
    return EXIT_FAILURE;
  }

  // Load shaders
  auto program_id = ShaderProgram("gl_texture.vert", "gl_texture.frag");
  glUseProgram(program_id);

  InitializeGeometry(program_id);

  // Create texture
  GLuint texture_id;
  glGenTextures(1, &texture_id);
  glBindTexture(GL_TEXTURE_2D, texture_id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

  // Bind texture
  auto texture_attrib = glGetUniformLocation(program_id, "Texture");
  glUniform1i(texture_attrib, 0);
  glActiveTexture(GL_TEXTURE0 + 0);
  glBindTexture(GL_TEXTURE_2D, texture_id);

  // Time counter
  float time = 0;

  // Main execution loop
  while (!glfwWindowShouldClose(window)) {
    // Update Framebuffer
    UpdateFramebuffer(time++);

    // Update texture data with framebuffer
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SIZE, SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, framebuffer);

    // Set gray background
    glClearColor(.5f,.5f,.5f,0);
    // Clear depth and color buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Draw triangles using the program
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    // Display result
    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  // Clean up
  glfwTerminate();

  return EXIT_SUCCESS;
}
Beispiel #24
0
ShaderProgram ShaderProgram::Current() {
	GLint current_shader;
	glGetIntegerv(GL_CURRENT_PROGRAM, &current_shader);
	return ShaderProgram(current_shader);
}
Beispiel #25
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	#ifdef _WINDOWS
		glewInit();
	#endif

	glViewport(0, 0, 640, 360);


	//For No Textures used
	//ShaderProgram program = ShaderProgram("vertex.glsl", "fragment.glsl");

	//For Textures used
	ShaderProgram program = ShaderProgram("vertex_textured.glsl", "fragment_textured.glsl");

	//Sets clear color of screen. (0.0f, 0.0f, 0.0f, 1.0f) is black
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //Black Color

	Matrix projectionMatrix;
	Matrix modelMatrix;
	Matrix viewMatrix;

	//HW2
	Matrix modelMatrixleftpaddle;
	Matrix modelMatrixrightpaddle;
	Matrix modelMatrixBall;
	Matrix modelMatrixBorder;

	projectionMatrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f);

	//Declare variables outisde of event loop
	float lastFrameTicks = 0.0f;

	float angle = 0.0f;

	GLuint redTextureID = LoadTexture(RESOURCE_FOLDER"red.png");
	GLuint blueTextureID = LoadTexture(RESOURCE_FOLDER"blue.png");
	GLuint yellowTextureID = LoadTexture(RESOURCE_FOLDER"yellow.png");
	GLuint purpleTextureID = LoadTexture(RESOURCE_FOLDER"purple.png");
	GLuint greenTextureID = LoadTexture(RESOURCE_FOLDER"green.png");
	GLuint orangeTextureID = LoadTexture(RESOURCE_FOLDER"orange.png");

	//HW2
	float paddleLength = 0.4f;
	float paddleWidth = 0.1f;
	float leftpaddleY = 0.0f;
	float leftpaddleX = 0.0f;
	float rightpaddleY = 0.0f;
	float rightpaddlex = 0.0f;

	float ballPosiX = 0.0f;
	float ballPosiY = 0.0f;
	float ballDirectX = 0.0f;
	float ballDirectY = 0.0f;
	float ballSpeed = 1.0f;
	float ballSize = 0.1f;


	SDL_Event event;
	bool done = false;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}

			else if (event.type == SDL_KEYDOWN){
				if (event.key.keysym.scancode == SDL_SCANCODE_SPACE) {
					//make character jump
					//character should be affected by gravity
				}

			}

			else if (event.type == SDL_MOUSEMOTION){
				//event.motion.x is our new x
				//float unitX = (((float)event.motion.x / 640.0f) * 3.554f) - 1.777f;

				//event.motion.y is our new y
				//float unitY = (((float)(360-event.motion.y) / 360.0f) * 2.0f) - 1.0f;
			}

			else if (event.type == SDL_MOUSEBUTTONDOWN){
				//event.button.x = click x position
				//event.button.y = click y position
				//event.button.button is the mouse button clicked (1,2,3,etc.)
			}
		}

		const Uint8 *keys = SDL_GetKeyboardState(NULL); //returns an array of keyboard keys, 1 if key is pressed
		
		//entities[0].acceleration_x = 0.0f //sets player motion to 0 on x axis


		//Polling Input
		if (keys[SDL_SCANCODE_LEFT]) {
			//MOVE CHARACTER LEFT/ROTATE LEFT
		}
		else if (keys[SDL_SCANCODE_RIGHT]) {
			//MOVE CHARACTER RIGHT/ROTATE RIGHT
		}

		else if (keys[SDL_SCANCODE_UP]){
			//MOVE CHARACTER UP
		}

		else if (keys[SDL_SCANCODE_DOWN]){
			//MOVE CHARACTER DOWN
		}

		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;

		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);


		glClear(GL_COLOR_BUFFER_BIT);
		glUseProgram(program.programID);



		//HW2 Pong

		//Left Paddle
		program.setModelMatrix(modelMatrixleftpaddle);

		if (keys[SDL_SCANCODE_W] && leftpaddleY < 0.8f) { leftpaddleY += elapsed; } // Up
		else if (keys[SDL_SCANCODE_S] && leftpaddleY > -0.8f){ leftpaddleY -= elapsed; } // Down

		float leftvertices[] = { 
		    -paddleWidth / 2, -paddleLength / 2,
			-paddleWidth / 2, paddleLength / 2,
			paddleWidth / 2, paddleLength / 2,
			-paddleWidth / 2, -paddleLength / 2,
			paddleWidth / 2, -paddleLength / 2,
			paddleWidth / 2, paddleLength / 2 
			};

		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, leftvertices);
		glEnableVertexAttribArray(program.positionAttribute);


		modelMatrixleftpaddle.identity();
		modelMatrixleftpaddle.Translate(-1.652f, leftpaddleY, 0.0f);

		glDrawArrays(GL_TRIANGLES, 0, 6);

		glDisableVertexAttribArray(program.positionAttribute);

		//Right Paddle
		program.setModelMatrix(modelMatrixrightpaddle);

		if (keys[SDL_SCANCODE_UP] && rightpaddleY < 0.8f) { rightpaddleY += elapsed; } // Up
		else if (keys[SDL_SCANCODE_DOWN] && rightpaddleY > -0.8f){ rightpaddleY -= elapsed; } // Down

		float rightvertices[] = { 
		    -paddleWidth / 2, -paddleLength / 2, 
			-paddleWidth / 2, paddleLength / 2,
			paddleWidth / 2, paddleLength / 2,
			-paddleWidth / 2, -paddleLength / 2,
			paddleWidth / 2, -paddleLength / 2, 
			paddleWidth / 2, paddleLength / 2 
			};

		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, rightvertices);
		glEnableVertexAttribArray(program.positionAttribute);

		modelMatrixrightpaddle.identity();
		modelMatrixrightpaddle.Translate(1.652f, rightpaddleY, 0.0f);

		glDrawArrays(GL_TRIANGLES, 0, 6);

		glDisableVertexAttribArray(program.positionAttribute);

		//Ball
		program.setModelMatrix(modelMatrixBall);

		if (keys[SDL_SCANCODE_SPACE] && ballDirectX == 0 && ballDirectY == 0)
		{
			ballDirectX = ballStart();
			ballDirectY = ballStart();
		}

		ballPosiX += elapsed * ballSpeed * ballDirectX;
		ballPosiY += elapsed * ballSpeed * ballDirectY;
		
		if (ballPosiY <= -0.975f) { ballDirectY = 1.0f; } // Ball impacting bottom
		else if (ballPosiY >= 0.975f) { ballDirectY = -1.0f; } // Ball impacting top

		// Ball impacting left paddle
		if (-1.652f + paddleWidth / 2 >= ballPosiX - ballSize / 2 &&
			leftpaddleY - paddleLength / 2 <= ballPosiY - ballSize / 2 &&
			leftpaddleY + paddleLength / 2 >= ballPosiY + ballSize / 2) {
			ballDirectX = 1.0f;
		} 

		// Ball impact right paddle
		if (1.652f - paddleWidth / 2 <= ballPosiX + ballSize / 2 &&
			rightpaddleY - paddleLength / 2 <= ballPosiY - ballSize / 2 &&
			rightpaddleY + paddleLength / 2 >= ballPosiY + ballSize / 2) {
			ballDirectX = -1.0f;
		}

		// Ball impacting goal
		if (ballPosiX >= 1.752f || ballPosiX <= -1.752) {
			ballPosiX = 0.0f; ballPosiY = 0.0f; ballDirectX = 0.0f; ballDirectY = 0.0f;
			leftpaddleY = 0.0f;  rightpaddleY = 0.0f; //Resets the paddles
		} 

		float ballvertices[] = { -ballSize / 2, -ballSize / 2, ballSize / 2, ballSize / 2, -ballSize / 2, ballSize / 2,
			-ballSize / 2, -ballSize / 2, ballSize / 2, -ballSize / 2, ballSize / 2, ballSize / 2 };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, ballvertices);
		glEnableVertexAttribArray(program.positionAttribute);

		modelMatrixBall.identity();
		modelMatrixBall.Translate(ballPosiX, ballPosiY, 0.0f);

		glDrawArrays(GL_TRIANGLES, 0, 6);

		glDisableVertexAttribArray(program.positionAttribute);

		//Border?
		program.setModelMatrix(modelMatrixBorder);
		float bottomvertices[] = {
			1.77f, -1.0f, //top right 
			-1.77f, -1.0f, //top left
			-1.77f, -1.0f, //bottom left
			1.77f, -1.0f }; //bottom right
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, bottomvertices);
		glEnableVertexAttribArray(program.positionAttribute);

		float bottomtexcoords[] = { 1.5f, 1.5f, -1.5f, 1.5f, -1.5f, -1.5f, 1.5f, -1.5f };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, bottomtexcoords);
		glEnableVertexAttribArray(program.texCoordAttribute);




		glBindTexture(GL_TEXTURE_2D, blueTextureID);
		glDrawArrays(GL_QUADS, 0, 4);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);
		

		//HW1 Textures
		/*
		//Blue Box
		modelMatrix.identity();


		program.setModelMatrix(modelMatrix);

		float iconvertices2[] = {
			3.56f, 2.0f, //top right 
			-3.56f, 2.0f, //top left
			-3.56f, -2.0f, //bottom left
			3.56f, -2.0f }; //bottom right
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, iconvertices2);
		glEnableVertexAttribArray(program.positionAttribute);

		float iconTexCoords2[] = { 1.5f, 1.5f, -1.5f, 1.5f, -1.5f, -1.5f, 1.5f, -1.5f };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, iconTexCoords2);
		glEnableVertexAttribArray(program.texCoordAttribute);




		glBindTexture(GL_TEXTURE_2D, blueTextureID);
		glDrawArrays(GL_QUADS, 0, 4);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		//yellow Box
		modelMatrix.identity();
		modelMatrix.Rotate(-ticks * ticks);

		program.setModelMatrix(modelMatrix);

		float iconvertices1[] = {
			0.0f, 0.0f, //top right 
			-1.0f, 0.0f, //top left
			-1.0f, -1.0f, //bottom left
			0.0f, -1.0f }; //bottom right
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, iconvertices1);
		glEnableVertexAttribArray(program.positionAttribute);

		float iconTexCoords1[] = { 1.5f, 1.5f, -1.5f, 1.5f, -1.5f, -1.5f, 1.5f, -1.5f };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, iconTexCoords1);
		glEnableVertexAttribArray(program.texCoordAttribute);




		glBindTexture(GL_TEXTURE_2D, yellowTextureID);
		glDrawArrays(GL_QUADS, 0, 4);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);



		//Red Box
		modelMatrix.identity();
		modelMatrix.Rotate(ticks);

		program.setModelMatrix(modelMatrix);

		float iconvertices3[] = { 
			0.5f, 0.5f, //top right 
			-0.5f, 0.5f, //top left
			-0.5f, -0.5f, //bottom left
			0.5f, -0.5f }; //bottom right
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, iconvertices3);
		glEnableVertexAttribArray(program.positionAttribute);

		float iconTexCoords3[] = { 1.5f, 1.5f, -1.5f, 1.5f, -1.5f, -1.5f, 1.5f, -1.5f};
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, iconTexCoords3);
		glEnableVertexAttribArray(program.texCoordAttribute);




		glBindTexture(GL_TEXTURE_2D, redTextureID);
		glDrawArrays(GL_QUADS, 0, 4);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);
		*/
		
		//HW1 No Textures
		/* //HW1 no textures
		modelMatrix.identity();
		modelMatrix.Rotate(ticks);
		program.setModelMatrix(modelMatrix);

		//Triangle Declaration
		float vertices[] = {
			-0.5f, -0.5f, //Bottom Left
			0.5f, -0.5f, // bottom right
			0.5f, 0.5f, //Top right
			-0.5f, 0.5f //top left
		};
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
		glEnableVertexAttribArray(program.positionAttribute);

		//Triangle Drawing
		glDrawArrays(GL_QUADS, 0, 4);

		glDisableVertexAttribArray(program.positionAttribute);

		modelMatrix.identity();
		modelMatrix.Rotate(-ticks);
		program.setModelMatrix(modelMatrix);

		//Triangle Declaration
		float vertices2[] = {
			-0.5f, -0.5f, //Bottom Left
			-1.5f, -1.5f, // bottom right
			-1.5f, 0.5f, //Top right
			-0.5f, 0.5f //top left
		};
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2);
		glEnableVertexAttribArray(program.positionAttribute);

		//Triangle Drawing
		glDrawArrays(GL_QUADS, 0, 4);

		glDisableVertexAttribArray(program.positionAttribute);

		modelMatrix.identity();
		modelMatrix.Rotate((ticks * ticks));
		program.setModelMatrix(modelMatrix);

		//Triangle Declaration
		float vertices3[] = {
			0.5f, 0.0f, //Bottom Left
			1.5f, 0.0f, // bottom right
			1.5f, 1.5f, //Top right
			1.0f, 1.5f //top left
		};
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3);
		glEnableVertexAttribArray(program.positionAttribute);

		//Triangle Drawing
		glDrawArrays(GL_QUADS, 0, 4);

		glDisableVertexAttribArray(program.positionAttribute);

		*/

		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
void VisibilityExtractionDemo::init()
{
    window = generateWindow();

    // load a file
    std::vector<std::string> paths;
    //paths.push_back("/home/nlichtenberg/1crn.pdb");
    paths.push_back("/home/nlichtenberg/1vis.pdb");
    //paths.push_back("/home/nlichtenberg/Develop/Mol_Sandbox/resources/TrajectoryFiles/1aon.pdb");
    MdTrajWrapper mdwrap;
    std::auto_ptr<Protein> prot = mdwrap.load(paths);

    impSph = new ImpostorSpheres(!useAtomicCounters, false);
    impSph->setProteinData(prot.get());
    impSph->init();
    num_balls = impSph->num_balls;

    if(perspectiveProj)
        projection = perspective(45.0f, getRatio(window), 0.1f, 100.0f);
    else
        projection = ortho(-30.0f, 30.0f, -30.0f, 30.0f, 0.0f, 100.0f);

    if (useAtomicCounters)
    {
        spRenderImpostor = ShaderProgram("/VisibleAtomsDetection/Impostor/impostorSpheres_InstancedUA.vert",
                                         "/VisibleAtomsDetection/Detection/solidColorInstanceCount.frag");
        spRenderDiscs = ShaderProgram("/VisibleAtomsDetection//Impostor/impostorSpheres_InstancedUA.vert",
                                      "/VisibleAtomsDetection//Impostor/impostorSpheres_discardFragments_Instanced.frag");
        if(perspectiveProj)
            spRenderBalls = ShaderProgram("/VisibleAtomsDetection/Base/modelViewProjectionInstancedUA.vert",
                                          "/VisibleAtomsDetection/Impostor/Impostor3DSphere.frag");
        else
            spRenderBalls = ShaderProgram("/VisibleAtomsDetection/Base/modelViewProjectionInstancedUA.vert",
                                          "/VisibleAtomsDetection/Impostor/Impostor3DSphere_Ortho.frag");
    }
    else
    {
        spRenderImpostor = ShaderProgram("/VisibleAtomsDetection/Impostor/impostorSpheres_Instanced.vert",
                                         "/VisibleAtomsDetection/Detection/solidColorInstanceCount.frag");
        spRenderDiscs = ShaderProgram("/VisibleAtomsDetection/Impostor/impostorSpheres_Instanced.vert",
                                      "/VisibleAtomsDetection/Impostor/impostorSpheres_discardFragments_Instanced.frag");
        spRenderBalls = ShaderProgram("/VisibleAtomsDetection/Impostor/impostorSpheres_Instanced.vert",
                                      "/VisibleAtomsDetection/Impostor/Impostor3DSphere.frag");
    }

    /// Renderpass to render impostors/fake geometry
    renderBalls = new RenderPass(
                impSph,
                &spRenderBalls,
                getWidth(window),
                getHeight(window));

    renderBalls->update("projection", projection);

    // define projection matrix for other shader programs
    renderBalls->setShaderProgram(&spRenderDiscs);
    renderBalls->update("projection", projection);
    renderBalls->setShaderProgram(&spRenderImpostor);
    renderBalls->update("projection", projection);

    /// Renderpass to detect the visible instances
    collectSurfaceIDs = new RenderPass(
                new Quad(),
                new ShaderProgram("/VisibleAtomsDetection/Base/fullscreen.vert",
                                  "/VisibleAtomsDetection/Detection/DetectVisibleInstanceIDs.frag"),
                getWidth(window),
                getHeight(window));

    // prepare 1D buffer for entries
    tex_collectedIDsBuffer = new Texture(GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
    tex_collectedIDsBuffer->genUimageBuffer(num_balls);
    collectSurfaceIDs->texture("collectedIDsBuffer", tex_collectedIDsBuffer);
    collectSurfaceIDs->texture("tex", renderBalls->get("InstanceID"));

    /// renderpass to display result frame
    result = new RenderPass(
                new Quad(),
                new ShaderProgram("/VisibleAtomsDetection/Base/fullscreen.vert",
                                  "/VisibleAtomsDetection/Detection/toneMapperLinearInstanceCount.frag"));
    result->texture("tex", renderBalls->get("fragColor"));

    /// compute shader to process a list of visible IDs (with the actual instanceID of the first general draw)
    computeSortedIDs = new ComputeProgram(new ShaderProgram("/VisibleAtomsDetection/Detection/CreateVisibleIDList.comp"));

    // 1D buffer for visible IDs
    tex_sortedVisibleIDsBuffer = new Texture(GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
    tex_sortedVisibleIDsBuffer->genUimageBuffer(num_balls);

    computeSortedIDs->texture("collectedIDsBuffer", tex_collectedIDsBuffer);
    computeSortedIDs->texture("sortedVisibleIDsBuffer", tex_sortedVisibleIDsBuffer);

    // atomic counter buffer for consecutive index access in compute shader
    glGenBuffers(1, &atomBuff);
    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, atomBuff);
    glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 3, atomBuff);
    glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), NULL, GL_DYNAMIC_DRAW);
    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0);

    positions_size = sizeof(glm::vec4) * impSph->instance_positions_s.instance_positions.size();
    colors_size = sizeof(glm::vec4) * impSph->instance_colors_s.instance_colors.size();

    // SSBO setup
    glGenBuffers(2, SSBO);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[0]);
    glBufferData(GL_SHADER_STORAGE_BUFFER, positions_size, &impSph->instance_positions_s.instance_positions[0], GL_DYNAMIC_COPY);
    glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, SSBO[0], 0, positions_size);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[1]);
    glBufferData(GL_SHADER_STORAGE_BUFFER, colors_size, &impSph->instance_colors_s.instance_colors[0], GL_DYNAMIC_COPY);
    glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 1, SSBO[1], 0, colors_size);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);

    // SSBO copy data
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[0]);
    GLvoid* p_ = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY);
    memcpy(p_, &impSph->instance_positions_s.instance_positions[0], positions_size);
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[1]);
    p_ = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY);
    memcpy(p_, &impSph->instance_colors_s.instance_colors[0], colors_size);
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

    // SSBO bind to shaders
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[0]);
    GLuint block_index = 0;
    block_index = glGetProgramResourceIndex(spRenderBalls.getProgramHandle(), GL_SHADER_STORAGE_BLOCK, "instance_positions_t");
    glShaderStorageBlockBinding(spRenderBalls.getProgramHandle(), block_index, 0);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[1]);
    block_index = glGetProgramResourceIndex(spRenderBalls.getProgramHandle(), GL_SHADER_STORAGE_BLOCK, "instance_colors_t");
    glShaderStorageBlockBinding(spRenderBalls.getProgramHandle(), block_index, 1);

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[0]);
    block_index = glGetProgramResourceIndex(spRenderDiscs.getProgramHandle(), GL_SHADER_STORAGE_BLOCK, "instance_positions_t");
    glShaderStorageBlockBinding(spRenderBalls.getProgramHandle(), block_index, 0);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[1]);
    block_index = glGetProgramResourceIndex(spRenderDiscs.getProgramHandle(), GL_SHADER_STORAGE_BLOCK, "instance_colors_t");
    glShaderStorageBlockBinding(spRenderBalls.getProgramHandle(), block_index, 1);

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[0]);
    block_index = glGetProgramResourceIndex(spRenderImpostor.getProgramHandle(), GL_SHADER_STORAGE_BLOCK, "instance_positions_t");
    glShaderStorageBlockBinding(spRenderBalls.getProgramHandle(), block_index, 0);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO[1]);
    block_index = glGetProgramResourceIndex(spRenderImpostor.getProgramHandle(), GL_SHADER_STORAGE_BLOCK, "instance_colors_t");
    glShaderStorageBlockBinding(spRenderBalls.getProgramHandle(), block_index, 1);


    // prepare data to reset the buffer that holds the visible instance IDs
    int byteCount = sizeof(unsigned int)* num_balls;
    zeros = new unsigned char[byteCount];
    unsigned int f = 0;
    unsigned char const * p = reinterpret_cast<unsigned char const *>(&f);

    for (int i = 0; i < byteCount; i+=4)
    {
        zeros[i] = p[0];
        zeros[i+1] = p[1];
        zeros[i+2] = p[2];
        zeros[i+3] = p[3];
    }

    // prepare buffer with index = value
    // used to draw all istances

    identityInstancesMap.clear();
    for (GLuint i = 0; i < num_balls; i++)
        identityInstancesMap.push_back(i);

    glBindTexture(GL_TEXTURE_1D, tex_sortedVisibleIDsBuffer->getHandle());
    glTexImage1D(GL_TEXTURE_1D, 0, GL_R32UI, num_balls, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, &identityInstancesMap[0]);

    // map to set all instances visible
    mapAllVisible.resize(num_balls);
    std::fill(mapAllVisible.begin(), mapAllVisible.end(), 1);

    // time query
    GLuint timeQuery;
    glGenQueries(1, &timeQuery);

    glEnable(GL_DEPTH_TEST);
}