Пример #1
0
/**
 * initGL() - create and configure OpenGL resources
 *
 * @return bool true if initialization is a success
 */
bool GLManager::initGL()
{
    // success flag
    bool success = true;

    // generate program
    programID = glCreateProgram();

    // enable z-buffer face culling
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    // transparency
    //glEnable(GL_BLEND);
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // enable vsync rate
    if (SDL_GL_SetSwapInterval(1) < 0)
        std::cout << "Swap Interval could not be set!" << std::endl;

    // vertex & fragment shaders
    vertexShader   = 0;
    fragmentShader = 0;
    ShaderLoader loader;

    // load vertex shader
    int failCount = 0;
    while (vertexShader == 0) {
        vertexShader = loader.loadShader( OsType::osConvert("shaders/phongAttenuation.vert"), programID );
        ++failCount;
        if (failCount >= 1000) {
            std::cout << "Loading vertexShader failed!" << std::endl;
            failCount = 0;
            break;
        }
    }

    // load fragment shader
    while (fragmentShader == 0) {
        fragmentShader = loader.loadShader( OsType::osConvert("shaders/phongAttenuation.frag"), programID );
        ++failCount;
        if (failCount >= 1000) {
            std::cout << "Loading fragmentShader failed!" << std::endl;
            failCount = 0;
            break;
        }
    }

    // create VAO
    glGenVertexArrays(1, &VAO);

    // link OpenGL program
    glLinkProgram(programID);

    //Initialize clear color
    glClearColor(0.0, 0.0, 0.0, 1.0f);

    return success;
}
Пример #2
0
const Shader::Setup *CurvesPrimitive::shaderSetup( const Shader *shader, State *state ) const
{
	bool linear, ribbons;
	renderMode( state, linear, ribbons );

	if( linear && !ribbons  )
	{
		// we just render in the standard way.
		return Primitive::shaderSetup( shader, state );
	}
		
	// we're rendering with ribbons and/or cubic interpolation. we need
	// to substitute in a geometry shader to do the work.
	
	for( MemberData::GeometrySetupVector::const_iterator it = m_memberData->geometrySetups.begin(), eIt = m_memberData->geometrySetups.end(); it != eIt; it++ )
	{
		if( it->originalShader == shader && it->linear == linear && it->ribbons == ribbons )
		{
			return it->shaderSetup.get();
		}
	}

	ConstShaderPtr geometryShader = shader;
	ShaderStateComponent *shaderStateComponent = state->get<ShaderStateComponent>();
	if( geometryShader->geometrySource() == "" )
	{
		// if the current shader has a specific geometry shader component,
		// then we assume the user has provided one capable of doing the tesselation,
		// but if not then we substitute in our own geometry shader.
		ShaderLoader *shaderLoader = shaderStateComponent->shaderLoader();
		if( ribbons )
		{
			if( linear )
			{
				geometryShader = shaderLoader->create( geometryShader->vertexSource(), linearRibbonsGeometrySource(), geometryShader->fragmentSource() );		
			}
			else
			{
				geometryShader = shaderLoader->create( geometryShader->vertexSource(), cubicRibbonsGeometrySource(), geometryShader->fragmentSource() );		
			}
		}
		else
		{
			geometryShader = shaderLoader->create( geometryShader->vertexSource(), cubicLinesGeometrySource(), geometryShader->fragmentSource() );
		}
	}

	Shader::SetupPtr geometryShaderSetup = new Shader::Setup( geometryShader );
	shaderStateComponent->addParametersToShaderSetup( geometryShaderSetup.get() );
	addPrimitiveVariablesToShaderSetup( geometryShaderSetup.get() );
	geometryShaderSetup->addUniformParameter( "basis", new IECore::M44fData( m_memberData->basis.matrix ) );
	geometryShaderSetup->addUniformParameter( "width", new IECore::M44fData( m_memberData->width ) );

	m_memberData->geometrySetups.push_back( MemberData::GeometrySetup( shader, geometryShaderSetup, linear, ribbons ) );
	
	return geometryShaderSetup.get();
}
Пример #3
0
void Init() {
	glEnable(GL_DEPTH_TEST);
	
	//load and compile shaders
	ShaderLoader shaderLoader;
	program = shaderLoader.CreateProgramm("Vertex_Shader.glsl", "Fragment_Shader.glsl");

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
Пример #4
0
// called on keyboard input
void keyboard(unsigned char key, int x_pos, int y_pos )
{
        ShaderLoader programLoad;
  // Handle keyboard input - end program
    if((key == 27)||(key == 'q')||(key == 'Q'))
    {
      glutLeaveMainLoop();
    }
    else if((key == 'w')||(key == 'W'))
    {
      forward = true;
    }
    else if((key == 'a')||(key == 'A'))
    {
      goLeft = true;
    }
    else if((key == 's')||(key == 'S'))
    {
      backward = true;
    }
    else if((key == 'd')||(key == 'D'))
    {
      goRight = true;
    }
    else if(key == '1')
    {
      programLoad.loadShader( vsFileName, fsFileName1, program );
      viewType = 1;
    }         
    else if(key == '2')
    {
      programLoad.loadShader( vsFileName, fsFileName2, program );
      viewType = 2;
    }  
    else if(key == '3')
    {
      programLoad.loadShader( vsFileName, fsFileName3, program );
      viewType = 3;
    }  
    else if(key == '4')
    {
      programLoad.loadShader( vsFileName, fsFileName4, program );
      viewType = 4;
    }      
}
Пример #5
0
SkyboxShader::SkyboxShader()
{
	glProgram = glCreateProgram();

	ShaderLoader shaderLoader;

	GLuint vertShaderID = shaderLoader.LoadShader("skybox.vert", ShaderLoader::VERTEX);
	GLuint fragShaderID = shaderLoader.LoadShader("skybox.frag", ShaderLoader::FRAGMENTATION);

	shaderLoader.CompileShader(vertShaderID);
	shaderLoader.CompileShader(fragShaderID);

	glBindAttribLocation(glProgram, 0, "position");

	glAttachShader(glProgram, vertShaderID);
	glAttachShader(glProgram, fragShaderID);

	glLinkProgram(glProgram);
}
Пример #6
0
//设置并使用着色器
void initShader(void)
{
    shaderLoader.load("/Users/wistoneqqx/Documents/opengl/github/texture-maps-gl7/texture-maps/simpleShader.vert",
                      "/Users/wistoneqqx/Documents/opengl/github/texture-maps-gl7/texture-maps/simpleShader.frag");
    shaderLoader.bind();
    
    //定义两张纹理的采样器
    glGenSamplers(1,&g_Sampler1);
    glGenSamplers(1,&g_Sampler2);
    
    glSamplerParameteri(g_Sampler1, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glSamplerParameteri(g_Sampler1, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    
    glSamplerParameteri(g_Sampler2, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glSamplerParameteri(g_Sampler2, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    
    textureLocation1 = glGetUniformLocation(shaderLoader.getProgramID(), "u_texture1");
    textureLocation2 = glGetUniformLocation(shaderLoader.getProgramID(), "u_texture2");
    
    if(textureLocation1==-1 && textureLocation2==-1)
        printf("Get textureLocation error!\n");
}
Пример #7
0
//画三角形
void drawTriangle(void)
{
    GLuint ModelID = glGetUniformLocation(shaderLoader.getProgramID(), "Model");
    if(ModelID != -1)
    {
        glUniformMatrix4fv(ModelID, 1, GL_FALSE, &Model[0][0]);
    }
    
    GLuint ProjectionID = glGetUniformLocation(shaderLoader.getProgramID(), "Projection");
    if(ProjectionID != -1)
    {
        glUniformMatrix4fv(ProjectionID, 1, GL_FALSE, &Projection[0][0]);
    }
    
    GLuint ViewID = glGetUniformLocation(shaderLoader.getProgramID(), "View");
    if(ViewID != -1)
    {
        glUniformMatrix4fv(ViewID, 1, GL_FALSE, &View[0][0]);
    }
    
    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLES, 0, 12*3); // 12*3 indices starting at 0 -> 12 triangles
    glBindVertexArray(0);
}
Пример #8
0
bool TestApplication::startup() {

	// create a basic window
	createWindow("AIE OpenGL Application", 1280, 720);

	// start the gizmo system that can draw basic shapes
	Gizmos::create();

	terrain = new Terrain(64, 50);

	// create a camera
	m_camera = new Camera(glm::pi<float>() * 0.25f, 16 / 9.f, 0.1f, 1000.f);
	m_camera->setLookAtFrom(vec3(-10, 100, -10), vec3(100, 0, 100));

	//////////////////////////////////////////////////////////////////////////
	// YOUR STARTUP CODE HERE
	//////////////////////////////////////////////////////////////////////////
	m_pickPosition = glm::vec3(0);
	
	shaders.Loader(m_program, "./src/Shader.vert", "./src/Shader.frag");

	glfwSetMouseButtonCallback(m_window, OnMouseButton);
	glfwSetCursorPosCallback(m_window, OnMousePosition);
	glfwSetScrollCallback(m_window, OnMouseScroll);
	glfwSetKeyCallback(m_window, OnKey);
	glfwSetCharCallback(m_window, OnChar);
	glfwSetWindowSizeCallback(m_window, OnWindowResize);



	TwInit(TW_OPENGL_CORE, nullptr);
	TwWindowSize(1280, 720);

	m_bar = TwNewBar("my bar");

	TwAddVarRW(m_bar, "clear colour", TW_TYPE_COLOR4F, &m_clearColour, "");
	TwAddVarRW(m_bar, "snow height", TW_TYPE_FLOAT, &textureBlend, "group=terrain");
	TwAddVarRW(m_bar, "light direction", TW_TYPE_DIR3F, &light, "group=light");
	TwAddVarRW(m_bar, "light colour", TW_TYPE_DIR3F, &lightColour, "group=light");

	return true;
}
Пример #9
0
bool TestApplication::update(float deltaTime) {

	// close the application if the window closes
	if (glfwWindowShouldClose(m_window) ||
		glfwGetKey(m_window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
		return false;

	// update the camera's movement
	m_camera->update(deltaTime);

	// clear the gizmos out for this frame
	Gizmos::clear();

	//////////////////////////////////////////////////////////////////////////
	// YOUR UPDATE CODE HERE
	//////////////////////////////////////////////////////////////////////////

	// an example of mouse picking
	if (glfwGetMouseButton(m_window, 0) == GLFW_PRESS) {
		double x = 0, y = 0;
		glfwGetCursorPos(m_window, &x, &y);

		// plane represents the ground, with a normal of (0,1,0) and a distance of 0 from (0,0,0)
		glm::vec4 plane(0, 1, 0, 0);
		m_pickPosition = m_camera->pickAgainstPlane((float)x, (float)y, plane);
	}

	if (glfwGetKey(m_window, GLFW_KEY_L) == GLFW_PRESS)
	{
		shaders.Loader(m_program, "./src/Shader.vert", "./src/Shader.frag");
	}
	Gizmos::addTransform(glm::translate(m_pickPosition));

	terrain->light =  light;
	terrain->lightColour = lightColour;
	
	terrain->textureBlend = textureBlend;

	// return true, else the application closes
	return true;
}
Пример #10
0
const Shader::Setup *PointsPrimitive::shaderSetup( const Shader *shader, State *state ) const
{
	Type type = effectiveType( state );
	if( type == Point )
	{
		// rendering as gl points goes through the normal process
		return Primitive::shaderSetup( shader, state );
	}
	else
	{
		// for rendering as disks, quads or spheres, we build a custom setup which we use
		// for instancing primitives onto our points.
		for( MemberData::InstancingSetupVector::const_iterator it = m_memberData->instancingSetups.begin(), eIt = m_memberData->instancingSetups.end(); it != eIt; it++ )
		{
			if( it->originalShader == shader && it->type == type )
			{
				return it->shaderSetup.get();
			}
		}

		ConstShaderPtr instancingShader = shader;
		ShaderStateComponent *shaderStateComponent = state->get<ShaderStateComponent>();
		if( instancingShader->vertexSource() == "" )
		{
			// if the current shader has specific vertex source, then we assume the user has provided
			// a shader capable of performing the instancing, but if not then we substitute in our own
			// instancing vertex shader.
			ShaderLoader *shaderLoader = shaderStateComponent->shaderLoader();
			instancingShader = shaderLoader->create( instancingVertexSource(), "", shader->fragmentSource() );
		}

		Shader::SetupPtr instancingShaderSetup = new Shader::Setup( instancingShader );
		shaderStateComponent->addParametersToShaderSetup( instancingShaderSetup.get() );
		addPrimitiveVariablesToShaderSetup( instancingShaderSetup.get(), "vertex", 1 );

		instancingShaderSetup->addUniformParameter( "useWidth", new BoolData( static_cast<bool>( m_memberData->widths ) ) );
		if( !m_memberData->constantWidth )
		{
			instancingShaderSetup->addUniformParameter( "constantwidth", new FloatData( 1.0f ) );
		}
		instancingShaderSetup->addUniformParameter( "useAspectRatio", new BoolData( static_cast<bool>( m_memberData->patchAspectRatio ) ) );
		instancingShaderSetup->addUniformParameter( "useRotation", new BoolData( static_cast<bool>( m_memberData->rotations ) ) );

		switch( type )
		{
			case Disk :
				if( !m_memberData->diskPrimitive )
				{
					m_memberData->diskPrimitive = new DiskPrimitive( 0.5f );
				}
				m_memberData->diskPrimitive->addPrimitiveVariablesToShaderSetup( instancingShaderSetup.get(), "instance" );
				break;
			case Sphere :
				if( !m_memberData->spherePrimitive )
				{
					m_memberData->spherePrimitive = new SpherePrimitive( 0.5f );
				}
				m_memberData->spherePrimitive->addPrimitiveVariablesToShaderSetup( instancingShaderSetup.get(), "instance" );
				break;
			case Quad :
				if( !m_memberData->quadPrimitive )
				{
					m_memberData->quadPrimitive = new QuadPrimitive();
				}
				m_memberData->quadPrimitive->addPrimitiveVariablesToShaderSetup( instancingShaderSetup.get(), "instance" );
				break;
			default :
				break;
		}

		m_memberData->instancingSetups.push_back( MemberData::InstancingSetup( shader, type, instancingShaderSetup ) );

		return instancingShaderSetup.get();
	}
}
Пример #11
0
static python::tuple loadSource( ShaderLoader &s, const std::string &name )
{
	std::string vertexSource, geometrySource, fragmentSource;
	s.loadSource( name, vertexSource, geometrySource, fragmentSource );
	return python::make_tuple( vertexSource, geometrySource, fragmentSource );
}
Пример #12
0
//设置并使用着色器
void initShader(void)
{
    shaderLoader.load("/Users/wistoneqqx/Documents/github/sbxfc/OpenGLProjectionMatrices/draw-triangle/draw-triangle/simpleShader.vert",
                      "/Users/wistoneqqx/Documents/github/sbxfc/OpenGLProjectionMatrices/draw-triangle/draw-triangle/simpleShader.frag");
    shaderLoader.bind();
}
Пример #13
0
bool initialize()
{
    // Initialize basic geometry and shaders for this example

    //this defines a cube, this is why a model loader is nice
    //you can also do this with a draw elements and indices, try to get that working
    Vertex geometry[] = { {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},

                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
                          
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          
                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},

                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},

                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
                          
                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},

                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}}
                        };
    // create a Vertex Buffer object to store this vertex info on the GPU
    glGenBuffers(1, &vbo_geometry);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
    glBufferData(GL_ARRAY_BUFFER, sizeof(geometry), geometry, GL_STATIC_DRAW);

    // loads shaders to program
    programLoad.loadShader( vsFileName, fsFileName,  program );

    // now we set the locations of the attributes and uniforms
    // this allows us to access them easily while rendering
    loc_position = glGetAttribLocation(program,
                    const_cast<const char*>("v_position"));
    if(loc_position == -1)
    {
        std::cerr << "[F] POSITION NOT FOUND" << std::endl;
        return false;
    }

    loc_color = glGetAttribLocation(program,
                    const_cast<const char*>("v_color"));
    if(loc_color == -1)
    {
        std::cerr << "[F] V_COLOR NOT FOUND" << std::endl;
        return false;
    }

    loc_mvpmat = glGetUniformLocation(program,
                    const_cast<const char*>("mvpMatrix"));
    if(loc_mvpmat == -1)
    {
        std::cerr << "[F] MVPMATRIX NOT FOUND" << std::endl;
        return false;
    }
    
    //--Init the view and projection matrices
    //  if you will be having a moving camera the view matrix will need to more dynamic
    //  ...Like you should update it before you render more dynamic 
    //  for this project having them static will be fine
    view = glm::lookAt( glm::vec3(0.0, 8.0, -16.0), //Eye Position
                        glm::vec3(0.0, 0.0, 0.0), //Focus point
                        glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up

    projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to
                                   float(w)/float(h), //Aspect Ratio, so Circles stay Circular
                                   0.01f, //Distance to the near plane, normally a small value like this
                                   100.0f); //Distance to the far plane, 

    //enable depth testing
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //and its done
    return true;
}
Пример #14
0
		int init() {
			// --- ezeket kell osszeszedni egy initwindowban
			const int screenWidth = m_window.getRealWidth(), screenHeight = m_window.getRealHeight();
			const int VSYNC_ENABLED = 1, FULL_SCREEN = 0;

			this->render.Initialize(screenWidth, screenHeight, VSYNC_ENABLED, this->m_window.getHWnd(), FULL_SCREEN);

			// init file loader
			this->m_file_loader = new FileAssetFactory("./../../assets/rotating_cube/");

			// --------------------------------------------------

			// -- camera
			m_camera = new Camera;
			m_camera->SetPosition(0.0f, 0.0f, -10.0f);

			// -- texture
			
			TextureFromBitmap *textureLoader = new TextureFromBitmap("normap.jpg");
			TextureResRef textureRes = (TextureRes*)textureLoader->NewResource();
			textureLoader->Load(this, textureRes);

			this->m_texture = textureRes->Get();

			delete textureLoader;

			// -- texture sampler
			m_textureSampler = new TextureSampler();
			m_textureSampler->Initialize(render);

			// -- load shader
			
			ShaderLoader *vShaderLoader = new ShaderLoader("vshader", "texture.hlsl", "TextureVertexShader", ST_Vertex);
			ShaderResRef vShaderRef = (ShaderRes*)(vShaderLoader->NewResource());
			vShaderLoader->Load(this, vShaderRef);
			
			m_vertexShader = vShaderRef->Get();

			delete vShaderLoader;

			ShaderLoader *pShaderLoader = new ShaderLoader("pshader", "texture.hlsl", "TexturePixelShader", ST_Pixel);
			ShaderResRef pShaderRef = (ShaderRes*)(pShaderLoader->NewResource());
			pShaderLoader->Load(this, pShaderRef);

			m_fragmentShader = pShaderRef->Get();

			delete pShaderLoader;

			// -- model 
			this->m_model = new Model;

			// -- generator
			SimpleMeshGenerator generator(render, m_vertexShader);
			generator["POSITION"] = (void*)GrafkitData::cubeVertices;
			generator["TEXCOORD"] = (void*)GrafkitData::cubeTextureUVs;
			
			generator(GrafkitData::cubeVertexLength, GrafkitData::cubeIndicesLength, GrafkitData::cubeIndices, this->m_model);

			// --- 

			this->t = 0;

			return 0;
		};
Пример #15
0
int main()
{
	InitGlfw initGlfw;
	ShaderLoader shaderLoader;
	TextureLoader textureLoader;
	TextRenderer textRenderer;

	// Init
	initGlfw.Init();
	textRenderer.Init();
	glfwSetKeyCallback(initGlfw.window, KeyCallback);
	glfwSetMouseButtonCallback(initGlfw.window, MouseButtonCallback);
	glfwSetCursorPosCallback(initGlfw.window, MouseMoveCallback);

	// Shader loading
	GLuint defaultShaderProgram;
	GLuint textShaderProgram;
	GLuint simpleShaderProgram;
	defaultShaderProgram = shaderLoader.CreateProgram("Shaders\\vertex_shader.glsl", "Shaders\\fragment_shader.glsl");
	textShaderProgram = shaderLoader.CreateProgram("Shaders\\text_vs.glsl", "Shaders\\text_fs.glsl");
	simpleShaderProgram = shaderLoader.CreateProgram("Shaders\\simple_vertex_shader.glsl", "Shaders\\simple_fragment_shader.glsl");
	

	// Load texture
	GLuint texture = textureLoader.LoadRGB("Images\\container.jpg");
	GLuint blankTexture = textureLoader.LoadBlank();
	cout << "Blank texture status: " << blankTexture << endl;

	// Define camera component vectors
	float wallDistanceMargin = 0.2f;
	float currentX;
	float currentZ;

	glm::vec3 cameraPos = glm::vec3(0.0f, -0.5f, 6.0f);
	glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
	glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
	float yaw = -90.0f;
	glm::vec3 front(cos(glm::radians(yaw)), 0.0f, sin(glm::radians(yaw)));
	
	// Define model and view matrices and get shader locations
	GLuint modelLocation = glGetUniformLocation(defaultShaderProgram, "model");
	GLuint viewLocation = glGetUniformLocation(defaultShaderProgram, "view");
	GLuint projectionLocation = glGetUniformLocation(defaultShaderProgram, "projection");

	double currentTime = glfwGetTime();
	double delta;

	glm::mat4 view;
	glm::mat4 proj1;
	glm::mat4 idm  = glm::mat4();
	
	// Hard-coded virtual environment
	Square backWall;
	Square leftWall;
	Square rightWall;
	Square floorSquare;
	Square frontWall;
	Square rewardZone;

	float corridorDepth = 10.0f;
	float corridorWidth = 3.0f;
	float wallHeight = 2.0f;

	float rewardZoneDepth = 2.0f;
	float rewardZonePosition = -3.0f;

	float rewardZoneLowZ = rewardZonePosition - rewardZoneDepth;
	float rewardZoneHighZ = rewardZonePosition + rewardZoneDepth;
	bool inRewardZone = false;

	backWall.SetColor(0.5f, 0.5f, 0.9f);
	backWall.SetScaling(corridorWidth, wallHeight);
	backWall.SetPosition(0.0f, wallHeight/2, -corridorDepth);
	
	frontWall.SetColor(0.5f, 0.5f, 0.9f);
	frontWall.SetScaling(corridorWidth, wallHeight);
	frontWall.SetPosition(0.0f, wallHeight / 2.0f, corridorDepth);

	leftWall.SetColor(0.5f, 0.9f, 0.5f);
	leftWall.SetScaling(corridorDepth, wallHeight);
	leftWall.SetRotation(0.0f, 90.0f, 0.0f);
	leftWall.SetPosition(-corridorWidth, wallHeight/2, 0.0f);
	
	rightWall.SetColor(0.5f, 0.9f, 0.5f);
	rightWall.SetScaling(corridorDepth, wallHeight);
	rightWall.SetRotation(0.0f, 90.0f, 0.0f);
	rightWall.SetPosition(corridorWidth,wallHeight/2, 0.0f);
	
	floorSquare.SetColor(0.1f, 0.1f, 0.1f);
	floorSquare.SetScaling(corridorWidth, corridorDepth);
	floorSquare.SetRotation(-90.0f, 0.0f, 0.0f);
	floorSquare.SetPosition(0.0f, -wallHeight/2.0f, 0.0f);

	rewardZone.SetColor(0.2f, 0.9f, 0.2f);
	rewardZone.SetScaling(corridorWidth, rewardZoneDepth);
	rewardZone.SetRotation(-90.0f, 0.0f, 0.0f);
	rewardZone.SetPosition(0.0f, -wallHeight / 2.0f + 0.01f, rewardZonePosition);

	proj1 = glm::perspective(45.0f, (float)2.0f*initGlfw.windowInfo.width / initGlfw.windowInfo.height, 0.1f, 100.0f);
	glEnable(GL_DEPTH_TEST);

	// Create frame buffer for offscreen rendering, configured to draw to a texture buffer from which we sample
	// to draw on each window. 
	GLuint frameBufferObject;
	GLuint frameBufferTexture;
	GLuint renderBufferObject;
	
	int fullWidth =  2*initGlfw.windowInfo.width;
	glGenTextures(1, &frameBufferTexture);
	glBindTexture(GL_TEXTURE_2D, frameBufferTexture);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, fullWidth, initGlfw.windowInfo.height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glBindTexture(GL_TEXTURE_2D, 0);
	
	glGenRenderbuffers(1, &renderBufferObject);
	glBindRenderbuffer(GL_RENDERBUFFER, renderBufferObject);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, fullWidth, initGlfw.windowInfo.height);
	glBindRenderbuffer(GL_RENDERBUFFER, 0);

	glGenFramebuffers(1, &frameBufferObject);
	glBindFramebuffer(GL_FRAMEBUFFER, frameBufferObject);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, frameBufferTexture, 0);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBufferObject);
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
		cout << "Framebuffer completed" << endl;

	// Generate quads for left and right window
	GLfloat leftScreenVertices[] = {
		// Positions   // TexCoords
		-1.0f,  1.0f,  0.0f, 1.0f,
		-1.0f, -1.0f,  0.0f, 0.0f,
		1.0f, -1.0f,  0.5f, 0.0f,

		-1.0f,  1.0f,  0.0f, 1.0f,
		1.0f, -1.0f,  0.5f, 0.0f,
		1.0f,  1.0f,  0.5f, 1.0f
	};
	GLfloat rightScreenVertices[] = {
		// Positions   // TexCoords
		-1.0f,  1.0f,  0.5f, 1.0f,
		-1.0f, -1.0f,  0.5f, 0.0f,
		1.0f, -1.0f,  1.0f, 0.0f,

		-1.0f,  1.0f,  0.5f, 1.0f,
		1.0f, -1.0f,  1.0f, 0.0f,
		1.0f,  1.0f,  1.0f, 1.0f
	};
	GLuint leftScreenVBO;
	GLuint rightScreenVBO;
	glGenBuffers(1, &leftScreenVBO);
	glBindBuffer(GL_ARRAY_BUFFER, leftScreenVBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(leftScreenVertices), leftScreenVertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	
	glGenBuffers(1, &rightScreenVBO);
	glBindBuffer(GL_ARRAY_BUFFER, rightScreenVBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(rightScreenVertices), rightScreenVertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);


	
	// Game loop
	int updateTick = 0;

	while (!glfwWindowShouldClose(initGlfw.window))
	{
		// Get time
		delta = glfwGetTime() - currentTime;
		currentTime = glfwGetTime();
		std::string fpsString = "FPS: " + std::to_string(delta);

		// Update view matrix
		// sensor readings need to be plugged in here
		front = glm::vec3(cos(glm::radians(yaw)), 0.0f, sin(glm::radians(yaw)));
		currentX = cameraPos.x;
		currentZ = cameraPos.z;

		cameraPos += yVelocity * front;
		cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * xVelocity;

		// Collision detection, reset to previous position if wall boundary is crossed
		if ( (cameraPos.x-wallDistanceMargin) < -corridorWidth | (cameraPos.x + wallDistanceMargin)> corridorWidth)
			cameraPos.x = currentX;
		if ((cameraPos.z-wallDistanceMargin) < -corridorDepth | (cameraPos.z + wallDistanceMargin) > corridorDepth)
			cameraPos.z = currentZ;

		// Check reward zone entries
		if (!inRewardZone && (cameraPos.z > rewardZoneLowZ && cameraPos.z < rewardZoneHighZ))
		{
			inRewardZone = true;
			cout << "Reward zone ENTRY detected." << endl;
		}
		if (inRewardZone && (cameraPos.z < rewardZoneLowZ || cameraPos.z > rewardZoneHighZ))
		{
			inRewardZone = false;
			cout << "Reward zone EXIT detected." << endl;
		}

		view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);


		// Draw the complete screen to the offscreen framebuffer
		glfwMakeContextCurrent(initGlfw.window);
		glBindFramebuffer(GL_FRAMEBUFFER, frameBufferObject);
		glViewport(0, 0, fullWidth, initGlfw.windowInfo.height);
			glEnable(GL_DEPTH_TEST);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			
			if (showFPS)
				textRenderer.RenderText(textShaderProgram, fpsString, 0.0f, GLfloat(initGlfw.windowInfo.height - 20), 1.0, glm::vec3(0.8, 0.6, 0.6));

			glUseProgram(defaultShaderProgram);
			glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(view));
			glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(proj1));
			glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(idm));
			glBindTexture(GL_TEXTURE_2D, texture);
			frontWall.Draw();
			backWall.Draw();
			leftWall.Draw();
			rightWall.Draw();
			floorSquare.Draw();
			glBindTexture(GL_TEXTURE_2D, blankTexture);
			rewardZone.Draw();
			glBindTexture(GL_TEXTURE_2D, 0);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);


		// First monitor drawing calls
		//glfwMakeContextCurrent(initGlfw.window);
		glClear(GL_COLOR_BUFFER_BIT);
		glDisable(GL_DEPTH_TEST);
		glViewport(0, 0, initGlfw.windowInfo.width, initGlfw.windowInfo.height);
		glUseProgram(simpleShaderProgram);
		glBindTexture(GL_TEXTURE_2D, frameBufferTexture);
		glBindBuffer(GL_ARRAY_BUFFER, rightScreenVBO);
			glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
			glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat)));
			glEnableVertexAttribArray(0);
			glEnableVertexAttribArray(1);
			glDrawArrays(GL_TRIANGLES, 0, 6);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glfwSwapBuffers(initGlfw.window);

		// Second monitor drawing calls
		glfwMakeContextCurrent(initGlfw.window2);
		glClear(GL_COLOR_BUFFER_BIT);
		glDisable(GL_DEPTH_TEST);
		glUseProgram(simpleShaderProgram);
		glBindTexture(GL_TEXTURE_2D, frameBufferTexture);
		glBindBuffer(GL_ARRAY_BUFFER, leftScreenVBO);
			glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
			glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat)));
			glEnableVertexAttribArray(0);
			glEnableVertexAttribArray(1);
			glDrawArrays(GL_TRIANGLES, 0, 6);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glfwSwapBuffers(initGlfw.window2);

		// Check events
		glfwPollEvents();

		// Output information
		++updateTick;
		if (updateTick % 60 == 0)
		{
			cout << "Camera position: (" << cameraPos.x << ", " << cameraPos.y << ", " << cameraPos.z << ")" << endl;
			updateTick = 0;
		}
	}
	glfwTerminate();

	// Clean up after exiting
	glDeleteFramebuffers(1, &frameBufferObject);
	return 0;
}
Пример #16
0
// initialize basic geometry and shaders for this example
bool initialize( const char* filename)
{
    // define model with model loader
    /*bool geometryLoadedCorrectly;
    Mesh object;
    ShaderLoader programLoad;*/
    int index;
    std::vector<Mesh> meshes;
    ShaderLoader programLoad;

    // load the image info
    if( !loadInfo( filename, meshes, numImages ) )
    {
      return false;
    }


     // loop through each planet
      for( index = 0; index < numImages; index++ )
      {
        // Create a Vertex Buffer object to store this vertex info on the GPU
        glGenBuffers(1, &(images[index].vbo_geometry));
        glBindBuffer(GL_ARRAY_BUFFER, images[index].vbo_geometry);
        glBufferData(GL_ARRAY_BUFFER, meshes[index].geometry.size()* sizeof(Vertex), &(meshes[index].geometry[0]), GL_STATIC_DRAW);

        // Create Texture object
        glGenTextures(1, &(images[index].texture));
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, images[index].texture);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, images[index].imageCols, images[index].imageRows, 0, GL_RGBA, GL_UNSIGNED_BYTE, images[index].m_blob.data());
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);      

        glGenBuffers(1, &(images[index].normalbuffer));
        glBindBuffer(GL_ARRAY_BUFFER, images[index].normalbuffer);
        glBufferData(GL_ARRAY_BUFFER, meshes[index].geometry.size() * sizeof(Vertex), &(meshes[index].geometry[0]), GL_STATIC_DRAW);    
        //glBufferData(GL_ARRAY_BUFFER, meshes[index].geometry.size() * sizeof(Vertex), &(meshes[index].geometry[offsetof(Vertex,normals)]), GL_STATIC_DRAW);    

      }      

      //if( viewType == 0 )
      //{
        // loads shaders to program
        programLoad.loadShader( vsFileName, fsFileName1, program );
      //}
      /*
      else
      {
        // loads shaders to program
        programLoad.loadShader( vsFileName, fsFileName1, program );        
      }
*/
    // Get a handle for our "MVP" uniform
    loc_mvpmat = glGetUniformLocation(program, "mvpMatrix");
      if(loc_mvpmat == -1)
      {
        std::cerr << "[F] MVP MATRIX NOT FOUND" << std::endl;
        return false;
      }       

    viewMatrixID = glGetUniformLocation(program, "V");
      if(viewMatrixID == -1)
      {
        std::cerr << "[F] VIEW NOT FOUND" << std::endl;
        return false;
      }  

    modelMatrixID = glGetUniformLocation(program, "M");
      if(modelMatrixID == -1)
      {
        std::cerr << "[F] MODEL NOT FOUND" << std::endl;
        return false;
      }    
/*
    // Get a handle for our buffers
    loc_position = glGetAttribLocation(program, "v_position");
      if(loc_position == -1)
      {
        std::cerr << "[F] POSITION NOT FOUND" << std::endl;
        return false;
      }

    loc_texture = glGetAttribLocation(program, "v_color");
      if(loc_texture == -1)
      {
        std::cerr << "[F] COLOR NOT FOUND" << std::endl;
        return false;
      }    
*/  

    // Get a handle for our buffers
    loc_position = glGetAttribLocation(program, "v_position");
      if(loc_position == -1)
      {
        std::cerr << "[F] POSITION NOT FOUND" << std::endl;
        return false;
      }
    
    loc_texture = glGetAttribLocation(program, "v_color");
      if(loc_texture == -1)
      {
        std::cerr << "[F] UV NOT FOUND" << std::endl;
        return false;
      }

    vertexNormal_modelspaceID = glGetAttribLocation(program, "vertexNormal_modelspace");
      if(vertexNormal_modelspaceID == -1)
      {
        std::cerr << "[F] NORMAL NOT FOUND" << std::endl;
        return false;
      }



    //--Init the view and projection matrices
    //  if you will be having a moving camera the view matrix will need to more dynamic
    //  ...Like you should update it before you render more dynamic 
    //  for this project having them static will be fine
    view = glm::lookAt( glm::vec3(0.0, 7.0, -23.0), //Eye Position
                        glm::vec3(0.0, 0.0, 0.0), //Focus point
                        glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up

    projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to
                                   float(w)/float(h), //Aspect Ratio, so Circles stay Circular
                                   0.01f, //Distance to the near plane, normally a small value like this
                                   100.0f); //Distance to the far plane

    //enable depth testing
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //and its done
    return true;
}
Пример #17
0
//设置并使用着色器
void initShader(void)
{
    shaderLoader.load("/Users/wistoneqqx/Documents/opengl/opengl-study-records/triangel_index_gl9/triangel_index/triangel_index/simpleShader.vert",
                      "/Users/wistoneqqx/Documents/opengl/opengl-study-records/triangel_index_gl9/triangel_index/triangel_index/simpleShader.frag");
    shaderLoader.bind();
}