Skip to content
Snippets Groups Projects
Commit 9845261c authored by TOMsworkspace's avatar TOMsworkspace
Browse files

update demo

parent c8e1336d
No related branches found
No related tags found
No related merge requests found
Showing
with 3 additions and 3118 deletions
......@@ -41,3 +41,6 @@ build/
install
install/
example
example/
cmake_minimum_required(VERSION 3.0)
project(NewtonPendulum)
set(CMAKE_CXX_STANDARD 11)
aux_source_directory(. dir_source)
file(GLOB dir_headers *.h)
include_directories({dir_headers})
set(GLFW_INCLUDE_DIR D:\\glfw-3.3.4\\include)
set(GLFW_LIBRARIES_DIR D:\\glfw-3.3.4\\lib-vc2019)
set(GLAD_INCLUDE_DIR D:\\glad\\include)
set(GLM_INCLUDE_DIR D:\\glm-0.9.9.8\\glm)
include_directories(${GLFW_INCLUDE_DIR})
include_directories(${GLAD_INCLUDE_DIR})
include_directories(${GLM_INCLUDE_DIR})
link_directories(${GLFW_LIBRARIES_DIR})
#link
#single lib
#glfw static library include glfw3.lib
#glfw dynamic library include glfw3dll.lib glfw3.dll
#multi-thread lib
#glfw static library include glfw3_mt.lib
#glfw dynamic library include glfw3dll.lib glfw3.dll
add_executable(NewtonPendulum ${dir_source})
target_link_libraries(NewtonPendulum ${GLFW_LIBRARIES} opengl32.lib glfw3dll.lib glfw3.dll)
/******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include "ball_object.h"
#include <iostream>
BallObject::BallObject()
: GameObject(), Radius(12.5f), Stuck(true), Sticky(false), PassThrough(false) {
//GLuint VBO,VAO;
glGenVertexArrays(1, &this->lineVAO);
glGenBuffers(1,&this->lineVBO);
glBindVertexArray(this->lineVAO);
glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1,3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
}
BallObject::BallObject(glm::vec2 pos, float radius, Texture2D sprite, glm::vec2 velocity, float mass, float stiff)
: GameObject(pos, glm::vec2(radius * 2.0f, radius * 2.0f), sprite, glm::vec3(1.0f), velocity)
, Radius(radius), Stuck(true), Sticky(false), PassThrough(false), FixedPoint(glm::vec2(400, 0))
,Mass(mass), Stiff(stiff), Acce(glm::vec2(0,9.8f)),Force(mass * Acce), Impuse(glm::vec2(0.0f)) {
angle = 1.0472; //asin((this->Position.x - this->FixedPoint.x )/LINE_LEN/2);
angle_speed = 0;
glGenVertexArrays(1, &this->lineVAO);
glGenBuffers(1,&this->lineVBO);
glBindVertexArray(this->lineVAO);
float vertexs[]={
//this->Position.x, this->Position.y, 0,
//this->FixedPoint.x, this->FixedPoint.y,0
1.0f,0.0f,0.0f,1.0f, 1.0f, 1.0f,
0.0f,1.0f,0.0f,1.0f, 1.0f, 1.0f,
//this->Position.x, this->Position.y, 0, 1.0f, 1.0f, 1.0f, // 右下
//this->FixedPoint.x, this->FixedPoint.y,0, 1.0f, 1.0f, 1.0f,
};
glBindBuffer(GL_ARRAY_BUFFER,lineVBO);
//glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(vertexs),vertexs);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertexs),vertexs,GL_DYNAMIC_DRAW);
glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1,3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
left = true;
}
glm::vec2 BallObject::Move(float dt, unsigned int window_width, unsigned int window_height)
{
// if not stuck to player board
//if (!this->Stuck)
//{
// move the ball
//std::cout << dt << std::endl;
//for(int i = 0; i < 100; ++i){
/*
float delta = dt;
float k1 = angle_speed;
float l1 = -(g/LINE_LEN)*sin(angle);
float k2 = angle_speed + delta * l1 / 2.0;
float l2 = -(g/LINE_LEN)*sin(angle + delta * k1 / 2.0);
float k3 = angle_speed + delta * l2 / 2.0;
float l3 = -(g/LINE_LEN) * sin(angle + delta * k2 / 2.0);
float k4 = angle_speed + delta * l3;
float l4 = -(g /LINE_LEN) * sin(angle + delta * k3);
angle = angle + delta *(k1 + 2 * k2 + 2 * k3 + k4) / 6.0;
angle_speed = angle_speed + delta * (l1 + 2 * l2 + 2 * l3 + l4) / 6.0;
std::cout << angle << " " << angle_speed << std::endl;
//}
this->Position = glm::vec2(LINE_LEN * sin(angle) + this->FixedPoint.x , LINE_LEN * cos(angle));
*/
glm::vec2 vec = this->Position + glm::vec2(Radius, Radius) - this->FixedPoint;
this->Force = glm::vec2(0,9.8 * this->Mass) - glm::normalize(vec) * (glm::length(glm::vec2(0,9.8 * this->Mass))*((this->Position.y - this->FixedPoint.y) / LINE_LEN));
this->Acce = this->Force / this->Mass;
// this->Velocity = this->Velocity * (1.0f - this->Stiff);
this->Velocity += this->Acce * dt;
//std::cout << this->Velocity.x << " " << this->Velocity.y << std::endl;
this->Impuse = this->Mass * this->Velocity;
this->Position += this->Velocity * dt;
// then check if outside window bounds and if so, reverse velocity and restore at correct position
//glm::vec4 pos = glm::vec4(this->Position + glm::vec2(Radius,Radius), 0,0);
//glm::mat4 model = glm::mat4(1.0f);
//model = glm::translate(model, glm::vec3(this->Position, 0.0f));
//pos = model * pos;
vec = this->Position + glm::vec2(Radius, Radius) - this->FixedPoint;;
int len = glm::length(vec);
if(len > LINE_LEN)
{
this->Position = vec * (float)LINE_LEN / (float)len + this->FixedPoint - glm::vec2(Radius, Radius);
// this->Velocity.y = 0;
if(glm::length(this->Velocity) < 0.2){
//this->Velocity = glm::vec2(0.0f,0.0f);
//this->Force = glm::vec2(0.0f,0.0f);
//this->Acce = glm::vec2(0.0f,0.0f);
}
}
//}
if(left)
angle -= dt * 0.05 * this->Position.y / 5;
else
angle += dt * 0.05 * this->Position.y / 5;
this->Position = glm::vec2(LINE_LEN * sin(angle) + this->FixedPoint.x , LINE_LEN * cos(angle)) - glm::vec2(Radius, Radius);
if (this->Position.x <= 0.0f)
{
this->Velocity.x = -this->Velocity.x;
this->Position.x = 0.0f;
}
else if (this->Position.x + this->Size.x >= window_width)
{
this->Velocity.x = -this->Velocity.x;
this->Position.x = window_width - this->Size.x;
}
else if(this->Position.y + this->Size.y >= window_height ){
this->Velocity.y = -this->Velocity.y * 0.9;
this->Position.y = window_height - this->Size.y;
}
if (this->Position.y <= 0.0f)
{
this->Velocity.y = -this->Velocity.y ;
this->Position.y = 0.0f;
}
if(this->Position.y <= Radius)
left ^= true;
//}
return this->Position;
}
// resets the ball to initial Stuck Position (if ball is outside window bounds)
void BallObject::Reset(glm::vec2 position, glm::vec2 velocity)
{
this->Position = position;
this->Velocity = velocity;
this->Stuck = true;
this->Sticky = false;
this->PassThrough = false;
}
void BallObject::Draw(SpriteRenderer &renderer){
// line
//glClearColor (0.0, 0.0, 0.0, 0.0);
//glClear (GL_COLOR_BUFFER_BIT);
glLineWidth(2.0f);//设置线段宽度
Shader lineshader = ResourceManager::GetShader("line");
glm::vec4 pos = glm::vec4(this->Position + glm::vec2(Radius,Radius), 0,0);
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(this->Position, 0.0f));
pos = model * pos;
float vertexs[]={
//this->Position.x, this->Position.y, 0,
//this->FixedPoint.x, this->FixedPoint.y,0
//1.0f,0.0f,0.0f,1.0f, 0.0f, 0.0f,
//0.0f,0.0f,0.0f,1.0f, 1.0f, 1.0f,
pos.x, pos.y , 0, 1.0f, 0.0f, 1.0f, // 右下
this->FixedPoint.x, this->FixedPoint.y,0, 1.0f, 0.0f, 1.0f,
};
//GLuint VBO,VAO;
//glGenVertexArrays(1, &VAO);
//glGenBuffers(1,&VBO);
//glBindVertexArray(VAO);
//glBufferData(GL_ARRAY_BUFFER,sizeof(vertexs),vertexs,GL_DYNAMIC_DRAW);
//lineshader.SetMatrix4("model1", model);
glBindBuffer(GL_ARRAY_BUFFER,lineVBO);
glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(vertexs),vertexs);
//glBindBuffer(GL_ARRAY_BUFFER,VBO);
//glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
//glEnableVertexAttribArray(0);
//glVertexAttribPointer(1,3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
//glEnableVertexAttribArray(1);
//glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
//glClear(GL_COLOR_BUFFER_BIT);
lineshader.Use();
glBindVertexArray(lineVAO);
glDrawArrays(GL_LINES,0,2);
//glDisableVertexAttribArray(0);
//glDeleteVertexArrays(2, &VAO);
renderer.DrawSprite(this->Sprite, this->Position, this->Size, this->Rotation, this->Color);
}
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#ifndef BALLOBJECT_H
#define BALLOBJECT_H
#include "glad/glad.h"
#include "glm/glm.hpp"
#include <GLFW/glfw3.h>
#include "game_object.h"
#include "texture.h"
const unsigned int LINE_LEN = 300;
const unsigned int g = 9.8f;
// BallObject holds the state of the Ball object inheriting
// relevant state data from GameObject. Contains some extra
// functionality specific to Breakout's ball object that
// were too specific for within GameObject alone.
class BallObject : public GameObject
{
public:
// ball state
float Radius;
bool Stuck;
bool Sticky, PassThrough;
float Mass = 1.0f;
glm::vec2 Acce;
glm::vec2 Force;
glm::vec2 Impuse;
float Stiff;
float angle;
float angle_speed;
glm::vec2 FixedPoint;
GLuint lineVAO,lineVBO;
bool left;
// constructor(s)
BallObject();
BallObject(glm::vec2 pos, float radius, Texture2D sprite, glm::vec2 velocity, float mass = 1.0, float stiff = 0.05);
// moves the ball, keeping it constrained within the window bounds (except bottom edge); returns new position
glm::vec2 Move(float dt, unsigned int window_width, unsigned int window_height);
// resets the ball to original state with given position and velocity
void Reset(glm::vec2 position, glm::vec2 velocity);
void Draw(SpriteRenderer &renderer);
};
#endif
\ No newline at end of file
This diff is collapsed.
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#ifndef GAME_H
#define GAME_H
#include <vector>
#include <tuple>
#include <glm/glm.hpp>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "game_level.h"
//#include "power_up.h"
// Represents the current state of the game
enum GameState {
GAME_ACTIVE,
GAME_MENU,
GAME_WIN
};
// Represents the four possible (collision) directions
enum Direction {
UP,
RIGHT,
DOWN,
LEFT
};
// Defines a Collision typedef that represents collision data
typedef std::tuple<bool, Direction, glm::vec2> Collision; // <collision?, what direction?, difference vector center - closest point>
// Initial size of the player paddle
const glm::vec2 PLAYER_SIZE(100.0f, 20.0f);
// Initial velocity of the player paddle
const float PLAYER_VELOCITY(500.0f);
// Initial velocity of the Ball
const glm::vec2 INITIAL_BALL_VELOCITY(0.0f, 0.0f);
// Radius of the ball object
const float BALL_RADIUS = 30.0f;
// Game holds all game-related state and functionality.
// Combines all game-related data into a single class for
// easy access to each of the components and manageability.
class Game
{
public:
// game state
GameState State;
bool Keys[1024];
bool KeysProcessed[1024];
unsigned int Width, Height;
std::vector<GameLevel> Levels;
//std::vector<PowerUp> PowerUps;
unsigned int Level;
unsigned int Lives;
// constructor/destructor
Game(unsigned int width, unsigned int height);
~Game();
// initialize game state (load all shaders/textures/levels)
void Init();
// game loop
void ProcessInput(float dt);
void Update(float dt);
void Render();
void DoCollisions();
// reset
void ResetLevel();
//void ResetPlayer();
// powerups
//void SpawnPowerUps(GameObject &block);
//void UpdatePowerUps(float dt);
};
#endif
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include "game_level.h"
#include <fstream>
#include <sstream>
void GameLevel::Load(const char *file, unsigned int levelWidth, unsigned int levelHeight)
{
// clear old data
this->Bricks.clear();
// load from file
unsigned int tileCode;
GameLevel level;
std::string line;
std::ifstream fstream(file);
std::vector<std::vector<unsigned int>> tileData;
if (fstream)
{
while (std::getline(fstream, line)) // read each line from level file
{
std::istringstream sstream(line);
std::vector<unsigned int> row;
while (sstream >> tileCode) // read each word separated by spaces
row.push_back(tileCode);
tileData.push_back(row);
}
if (tileData.size() > 0)
this->init(tileData, levelWidth, levelHeight);
}
}
void GameLevel::Draw(SpriteRenderer &renderer)
{
for (GameObject &tile : this->Bricks)
if (!tile.Destroyed)
tile.Draw(renderer);
}
bool GameLevel::IsCompleted()
{
for (GameObject &tile : this->Bricks)
if (!tile.IsSolid && !tile.Destroyed)
return false;
return true;
}
void GameLevel::init(std::vector<std::vector<unsigned int>> tileData, unsigned int levelWidth, unsigned int levelHeight)
{
// calculate dimensions
unsigned int height = tileData.size();
unsigned int width = tileData[0].size(); // note we can index vector at [0] since this function is only called if height > 0
float unit_width = levelWidth / static_cast<float>(width), unit_height = levelHeight / height;
// initialize level tiles based on tileData
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width; ++x)
{
// check block type from level data (2D level array)
if (tileData[y][x] == 1) // solid
{
glm::vec2 pos(unit_width * x, unit_height * y);
glm::vec2 size(unit_width, unit_height);
GameObject obj(pos, size, ResourceManager::GetTexture("block_solid"), glm::vec3(0.8f, 0.8f, 0.7f));
obj.IsSolid = true;
this->Bricks.push_back(obj);
}
else if (tileData[y][x] > 1) // non-solid; now determine its color based on level data
{
glm::vec3 color = glm::vec3(1.0f); // original: white
if (tileData[y][x] == 2)
color = glm::vec3(0.2f, 0.6f, 1.0f);
else if (tileData[y][x] == 3)
color = glm::vec3(0.0f, 0.7f, 0.0f);
else if (tileData[y][x] == 4)
color = glm::vec3(0.8f, 0.8f, 0.4f);
else if (tileData[y][x] == 5)
color = glm::vec3(1.0f, 0.5f, 0.0f);
glm::vec2 pos(unit_width * x, unit_height * y);
glm::vec2 size(unit_width, unit_height);
this->Bricks.push_back(GameObject(pos, size, ResourceManager::GetTexture("block"), color));
}
}
}
}
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#ifndef GAMELEVEL_H
#define GAMELEVEL_H
#include <vector>
#include <glad/glad.h>
#include <glm/glm.hpp>
#include "game_object.h"
#include "sprite_renderer.h"
#include "resource_manager.h"
/// GameLevel holds all Tiles as part of a Breakout level and
/// hosts functionality to Load/render levels from the harddisk.
class GameLevel
{
public:
// level state
std::vector<GameObject> Bricks;
// constructor
GameLevel() { }
// loads level from file
void Load(const char *file, unsigned int levelWidth, unsigned int levelHeight);
// render level
void Draw(SpriteRenderer &renderer);
// check if the level is completed (all non-solid tiles are destroyed)
bool IsCompleted();
private:
// initialize level from tile data
void init(std::vector<std::vector<unsigned int>> tileData, unsigned int levelWidth, unsigned int levelHeight);
};
#endif
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include "game_object.h"
GameObject::GameObject()
: Position(0.0f, 0.0f), Size(1.0f, 1.0f), Velocity(0.0f), Color(1.0f), Rotation(0.0f), Sprite(), IsSolid(false), Destroyed(false) { }
GameObject::GameObject(glm::vec2 pos, glm::vec2 size, Texture2D sprite, glm::vec3 color, glm::vec2 velocity)
: Position(pos), Size(size), Velocity(velocity), Color(color), Rotation(0.0f), Sprite(sprite), IsSolid(false), Destroyed(false) { }
void GameObject::Draw(SpriteRenderer &renderer)
{
renderer.DrawSprite(this->Sprite, this->Position, this->Size, this->Rotation, this->Color);
}
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "texture.h"
#include "sprite_renderer.h"
#include "resource_manager.h"
// Container object for holding all state relevant for a single
// game object entity. Each object in the game likely needs the
// minimal of state as described within GameObject.
class GameObject
{
public:
// object state
glm::vec2 Position, Size, Velocity;
glm::vec3 Color;
float Rotation;
bool IsSolid;
bool Destroyed;
// render state
Texture2D Sprite;
// constructor(s)
GameObject();
GameObject(glm::vec2 pos, glm::vec2 size, Texture2D sprite, glm::vec3 color = glm::vec3(1.0f), glm::vec2 velocity = glm::vec2(0.0f, 0.0f));
// draw sprite
virtual void Draw(SpriteRenderer &renderer);
};
#endif
\ No newline at end of file
This diff is collapsed.
#version 330 core
out vec4 FragColor;
in vec3 ourColor;
void main()
{
FragColor = vec4(ourColor, 1.0f);
}
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "game.h"
#include "resource_manager.h"
#include <iostream>
// GLFW function declarations
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
// The Width of the screen
const unsigned int SCREEN_WIDTH = 800;
// The height of the screen
const unsigned int SCREEN_HEIGHT = 600;
Game Breakout(SCREEN_WIDTH, SCREEN_HEIGHT);
int main(int argc, char *argv[])
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
glfwWindowHint(GLFW_RESIZABLE, false);
GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Breakout", nullptr, nullptr);
glfwMakeContextCurrent(window);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glfwSetKeyCallback(window, key_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// OpenGL configuration
// --------------------
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// initialize game
// ---------------
Breakout.Init();
// deltaTime variables
// -------------------
float deltaTime = 0.0f;
float lastFrame = 0.0f;
while (!glfwWindowShouldClose(window))
{
// calculate delta time
// --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
glfwPollEvents();
// manage user input
// -----------------
Breakout.ProcessInput(deltaTime);
// update game state
// -----------------
Breakout.Update(deltaTime);
// render
// ------
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
Breakout.Render();
glfwSwapBuffers(window);
}
// delete all resources as loaded using the resource manager
// ---------------------------------------------------------
ResourceManager::Clear();
glfwTerminate();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
// when a user presses the escape key, we set the WindowShouldClose property to true, closing the application
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (key >= 0 && key < 1024)
{
if (action == GLFW_PRESS)
Breakout.Keys[key] = true;
else if (action == GLFW_RELEASE)
{
Breakout.Keys[key] = false;
Breakout.KeysProcessed[key] = false;
}
}
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include "resource_manager.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include "stb_image.h"
// Instantiate static variables
std::map<std::string, Texture2D> ResourceManager::Textures;
std::map<std::string, Shader> ResourceManager::Shaders;
Shader ResourceManager::LoadShader(const char *vShaderFile, const char *fShaderFile, const char *gShaderFile, std::string name)
{
Shaders[name] = loadShaderFromFile(vShaderFile, fShaderFile, gShaderFile);
return Shaders[name];
}
Shader ResourceManager::GetShader(std::string name)
{
return Shaders[name];
}
Texture2D ResourceManager::LoadTexture(const char *file, bool alpha, std::string name)
{
Textures[name] = loadTextureFromFile(file, alpha);
return Textures[name];
}
Texture2D ResourceManager::GetTexture(std::string name)
{
return Textures[name];
}
void ResourceManager::Clear()
{
// (properly) delete all shaders
for (auto iter : Shaders)
glDeleteProgram(iter.second.ID);
// (properly) delete all textures
for (auto iter : Textures)
glDeleteTextures(1, &iter.second.ID);
}
Shader ResourceManager::loadShaderFromFile(const char *vShaderFile, const char *fShaderFile, const char *gShaderFile)
{
// 1. retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::string geometryCode;
try
{
// open files
std::ifstream vertexShaderFile(vShaderFile);
std::ifstream fragmentShaderFile(fShaderFile);
std::stringstream vShaderStream, fShaderStream;
// read file's buffer contents into streams
vShaderStream << vertexShaderFile.rdbuf();
fShaderStream << fragmentShaderFile.rdbuf();
// close file handlers
vertexShaderFile.close();
fragmentShaderFile.close();
// convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
// if geometry shader path is present, also load a geometry shader
if (gShaderFile != nullptr)
{
std::ifstream geometryShaderFile(gShaderFile);
std::stringstream gShaderStream;
gShaderStream << geometryShaderFile.rdbuf();
geometryShaderFile.close();
geometryCode = gShaderStream.str();
}
}
catch (std::exception e)
{
std::cout << "ERROR::SHADER: Failed to read shader files" << std::endl;
}
const char *vShaderCode = vertexCode.c_str();
const char *fShaderCode = fragmentCode.c_str();
const char *gShaderCode = geometryCode.c_str();
// 2. now create shader object from source code
Shader shader;
shader.Compile(vShaderCode, fShaderCode, gShaderFile != nullptr ? gShaderCode : nullptr);
return shader;
}
Texture2D ResourceManager::loadTextureFromFile(const char *file, bool alpha)
{
// create texture object
Texture2D texture;
if (alpha)
{
texture.Internal_Format = GL_RGBA;
texture.Image_Format = GL_RGBA;
}
// load image
int width, height, nrChannels;
unsigned char* data = stbi_load(file, &width, &height, &nrChannels, 0);
// now generate texture
texture.Generate(width, height, data);
// and finally free image data
stbi_image_free(data);
return texture;
}
\ No newline at end of file
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#ifndef RESOURCE_MANAGER_H
#define RESOURCE_MANAGER_H
#include <map>
#include <string>
#include <glad/glad.h>
#include "texture.h"
#include "shader.h"
// A static singleton ResourceManager class that hosts several
// functions to load Textures and Shaders. Each loaded texture
// and/or shader is also stored for future reference by string
// handles. All functions and resources are static and no
// public constructor is defined.
class ResourceManager
{
public:
// resource storage
static std::map<std::string, Shader> Shaders;
static std::map<std::string, Texture2D> Textures;
// loads (and generates) a shader program from file loading vertex, fragment (and geometry) shader's source code. If gShaderFile is not nullptr, it also loads a geometry shader
static Shader LoadShader(const char *vShaderFile, const char *fShaderFile, const char *gShaderFile, std::string name);
// retrieves a stored sader
static Shader GetShader(std::string name);
// loads (and generates) a texture from file
static Texture2D LoadTexture(const char *file, bool alpha, std::string name);
// retrieves a stored texture
static Texture2D GetTexture(std::string name);
// properly de-allocates all loaded resources
static void Clear();
private:
// private constructor, that is we do not want any actual resource manager objects. Its members and functions should be publicly available (static).
ResourceManager() { }
// loads and generates a shader from file
static Shader loadShaderFromFile(const char *vShaderFile, const char *fShaderFile, const char *gShaderFile = nullptr);
// loads a single texture from file
static Texture2D loadTextureFromFile(const char *file, bool alpha);
};
#endif
\ No newline at end of file
File deleted
File deleted
File deleted
File deleted
File deleted
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment