Example #1
0
void OpenGLRenderer::setUniform(Renderer::ShaderProgram* p,
                                const std::string& name, const glm::vec2& m) {
    useProgram(p);

    glUniform2fv(currentProgram->getUniformLocation(name.c_str()), 1,
                 glm::value_ptr(m));
}
Example #2
0
void Renderer::setTextureUnits() {
  useProgram("textured");
  glUniform1i(uniformHandle("color_texture"), 0);

  useProgram("circles_screen_textured");
  glUniform1i(uniformHandle("color_texture"), 0);

  useProgram("textured_with_shadows");
  glUniform1i(uniformHandle("color_texture"), 0);
  glUniform1i(uniformHandle("shadow_texture"), 1);

  useProgram("shadows");
  glUniform1i(uniformHandle("occluder_texture"), 0);

  useProgram("particle_draw");
  glUniform1i(uniformHandle("color_texture"), 0);
}
Example #3
0
    //! SceneRenderer:: Draws scene
    void GLSLSceneRenderer::render()
    {
        // Clear framebuffer
        glClearColor(0.1f, 0.1f, 0.2f, 1.0f);

        //glDepthMask(GL_TRUE);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        
        // Setup viewport
        glViewport(0, 0, Application::get().getWindow().getWidth(), Application::get().getWindow().getHeight());
        
        // Get and update camera if window has been resized
        scene->getCamera().setAspectRatio(Application::get().getWindow().getWidth() / (float) Application::get().getWindow().getHeight());
        
        useProgram("BlinnPhongShader.shader");
        
        // Setup lights
        for(auto it : light_map) {
            Light * light = it.first;
            String light_tag = String("light_source[") + it.second + String("].");
            
            /* Get params ref */
            Light::LightSourceParameters & param = light->getParametersRef();
            
            /* Set up shader parameters */
            Mat4 model_view = light->getMover().getScene().getCamera().getTransform() * light->getMover().getCachedTransformRef();
            Mat4 normal_matrix = model_view.inverse().transpose();
            Vec4 position = model_view * param.position;
            Vec3 spotDirection = normal_matrix * param.spotDirection;
            Vec3 half_vector = light->getMover().getScene().getCamera().getMover().getDerivedPosition() - param.position;
            
            getProgram().setParamVec4(light_tag + "ambient", param.ambient);
            getProgram().setParamVec4(light_tag + "diffuse", param.diffuse);
            getProgram().setParamVec4(light_tag + "specular", param.specular);
            getProgram().setParamVec4(light_tag + "position", position);
            getProgram().setParamVec3(light_tag + "half_vector", half_vector);
            getProgram().setParamVec3(light_tag + "spot_direction", spotDirection);
            getProgram().setParamFloat(light_tag + "spot_exponent", param.spotExponent);
            getProgram().setParamFloat(light_tag + "spot_cutoff", param.spotCutoff);
            getProgram().setParamFloat(light_tag + "spot_cos_cutoff", param.spotCosCutoff);
            getProgram().setParamVec3(light_tag + "attenuation", param.attenuation);
        }
        
        // Setup scene parameters
        Vec4 ambient_color(0.1, 0.1, 0.1, 1.0);
        getProgram().setParamVec4("scene_ambient_color", ambient_color);
        getProgram().setParamInt("num_of_enabled_lights", (int)light_map.size());
        getProgram().setParamBool("need_local_viewer", 1);
        
        // Draw scene
        for (Drawable * drawable : drawable_list) {
            drawable->_drawOccurrences(*this);
        }
    }
Example #4
0
void ImageSprite::draw(SPRenderer renderer)
{
    auto context = renderer->getContext();
    context->useProgram(_program);
    // setUniform must after useProgram
    _program->setUniform(_program->getUniform("view"), Director::getInstance().getView());
    _program->setUniform(_program->getUniform("proj"), Director::getInstance().getProj());
    _program->setUniform(_program->getUniform("model"), getModel());
    context->bindTexture(_texture, 0);
    context->drawArrays(*_vao, cppgl::Primitive::Triangles, 0, 6);
}
void StateManagerGL::deleteProgram(GLuint program)
{
    if (program != 0)
    {
        if (mProgram == program)
        {
            useProgram(0);
        }

        mFunctions->deleteProgram(program);
    }
}
Example #6
0
 void Shader::setUniform<float>(const std::string& name, const float& data) {
   int prev_bound_program;
   glGetIntegerv(GL_CURRENT_PROGRAM, &prev_bound_program);
   if(name_to_location.count(name) == 0) {
     throw Exceptions::InvalidUniformNameException(name);
   }
   if(prev_bound_program != program_object)
     useProgram();
   glUniform1f(name_to_location[name], data);
   if(prev_bound_program != program_object)
     glUseProgram(prev_bound_program);
 }
Example #7
0
 void Shader::setUniform<glm::vec2>(const std::string& name, const glm::vec2& data) {
   int prev_bound_program;
   glGetIntegerv(GL_CURRENT_PROGRAM, &prev_bound_program);
   if(name_to_location.count(name) == 0) {
     throw Exceptions::InvalidUniformNameException(name);
   }
   if(prev_bound_program != program_object)
     useProgram();
   glUniform2fv(name_to_location[name], 1, glm::value_ptr(data));
   if(prev_bound_program != program_object)
     glUseProgram(prev_bound_program);
 }
	COGLES2Renderer2d::COGLES2Renderer2d( irr::video::COGLES2Driver *driver, irr::io::IFileSystem *fs )
			: COGLES2SLMaterialRenderer( driver, fs, 0, 0, sBuiltInShaderUniformNames, UNIFORM_COUNT )
	{
#ifdef _DEBUG
		setDebugName( "COGLES2Renderer2d" );
#endif
		s32 dummy = -1;
		if (!initFromFiles( dummy, vertexShaderFile, fragmentShaderFile, false))
			return;
		useProgram();
		int texUnit = 0;
		setUniform( TEXTURE_UNIT, &texUnit );
	}
	//! Constructor
	COGLES2ParallaxMapRenderer::COGLES2ParallaxMapRenderer( video::COGLES2Driver* driver,
															io::IFileSystem* fs, s32& outMaterialTypeNr, IMaterialRenderer* baseMaterial )
			: COGLES2SLMaterialRenderer( driver, fs, 0, baseMaterial, sBuiltInShaderUniformNames, UNIFORM_COUNT ), CompiledShaders( true )
	{

#ifdef _DEBUG
		setDebugName( "COGLES2ParallaxMapRenderer" );
#endif

		// set this as callback. We could have done this in
		// the initialization list, but some compilers don't like it.

		CallBack = this;

		// basically, this simply compiles the hard coded shaders if the
		// hardware is able to do them, otherwise it maps to the base material

		// check if already compiled normal map shaders are there.

		video::IMaterialRenderer* renderer = driver->getMaterialRenderer( EMT_PARALLAX_MAP_SOLID );

		if ( renderer )
		{
			// use the already compiled shaders
			video::COGLES2ParallaxMapRenderer* pmr = reinterpret_cast<video::COGLES2ParallaxMapRenderer*>( renderer );
			CompiledShaders = false;

			Program = pmr->Program;

			UniformInfo = pmr->UniformInfo;
			AttributeInfo = pmr->AttributeInfo;

			outMaterialTypeNr = driver->addMaterialRenderer( this );
		}
		else
		{
			// compile shaders on our own
			if (initFromFiles( outMaterialTypeNr, VertexShaderFile, FragmentShaderFile))
			{
				useProgram();
				int dummy = 0;
				setUniform( TEXTURE_UNIT0, &dummy );
				dummy = 1;
				setUniform( TEXTURE_UNIT1, &dummy );
			}
		}

		// fallback if compilation has failed
		if ( -1 == outMaterialTypeNr )
			outMaterialTypeNr = driver->addMaterialRenderer( this );
	}
Example #10
0
File: main.cpp Project: nyaxt/dmix
void GLDrawUI::Common::setUp(SetUpPhase phase) {
  switch (phase) {
    case SetUpPhase::CompileLinkProgram:
      compileLinkProgram();
    /* FALL THROUGH */
    case SetUpPhase::UseProgram:
      useProgram();
    /* FALL THROUGH */
    case SetUpPhase::UpdateMVPMatrix:
      updateMVPMatrix();
    /* FALL THROUGH */
    default:
      break;
  }
}
Example #11
0
		bool ShaderManager::loadUseProgram(const LoadUseProgramDescription &desc, vx::StackAllocator* scratchAllocator, std::string* error)
		{
			// check for not used shader stage
			if (strcmp(desc.id, "''") == 0)
			{
				return true;
			}

			auto fileHandle = FileHandle(desc.id);
			if (!loadProgram(fileHandle, desc.type, *desc.programDir, *desc.includeDir, scratchAllocator, error))
				return false;
			if (!useProgram(*desc.pipe, fileHandle))
				return false;

			return true;
		}
Example #12
0
void Renderer::init(int width, int height) {
  width_ = width;
  height_ = height;
  aspect_ = static_cast<float>(width)/height;

  // OpenGL settings.
  glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  glClearDepth(1.0f);
  glDepthFunc(GL_LESS);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  loadShaders();
  setupScreenQuad();
  setupFBOs();

  useProgram("shadows");
  glUniform1f(uniformHandle("density"), 2.0f);
  glUniform1f(uniformHandle("decay_rate"), 0.98f);
  glUniform1f(uniformHandle("constant_factor"), 0.85f);
  glUniform1f(uniformHandle("scale_factor"), 1.0f/160.0f);
}
	void VertexArrayObject::bind() const {
		useProgram();
		switch (vaoSupported_) {
			case VaoSupported::CHECK_SUPPORTED:
				if (mw::Window::getOpenGlMajorVersion() >= 3) {
					vaoSupported_ = VaoSupported::SUPPORTED;
					// Fall trough to next case.
				} else {
					vaoSupported_ = VaoSupported::NOT_SUPPORTED;
					bindBuffer();
					setVertexAttribPointer();
					break;
				}
			case VaoSupported::SUPPORTED:
				if (*vao_ == 0) { // Create the vertex array only the first time.
					glGenVertexArrays(1, &*vao_);
					glBindVertexArray(*vao_);
					checkGlError();
					// Remove the block to unneeded calls to buffer changes.
					VertexBufferObject::setIgnoreCurrentBind(true);
					bindBuffer();
					// Restore the block.
					VertexBufferObject::setIgnoreCurrentBind(false);
					currentVertexArrayObject = *vao_;
					setVertexAttribPointer();
				} else {
					glBindVertexArray(*vao_);
					checkGlError();
				}
				break;
			case VaoSupported::NOT_SUPPORTED:
				bindBuffer();
				setVertexAttribPointer();
				break;
		}
	}
Example #14
0
void SGLShaderProgram::setUniformMat4f(const char* name, glm::mat4& value)
{
	useProgram();
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, &value[0][0]);
}
Example #15
0
void OpenGLRenderer::setUniform(Renderer::ShaderProgram* p,
                                const std::string& name, float f) {
    useProgram(p);

    glUniform1fv(currentProgram->getUniformLocation(name.c_str()), 1, &f);
}
Example #16
0
gl::Error StateManagerGL::setGenericDrawState(const gl::Data &data)
{
    const gl::State &state = *data.state;
    const gl::Caps &caps = *data.caps;

    const gl::Program *program = state.getProgram();
    const ProgramGL *programGL = GetImplAs<ProgramGL>(program);
    useProgram(programGL->getProgramID());

    // TODO: Only apply textures referenced by the program.
    for (auto textureTypeIter = mTextures.begin(); textureTypeIter != mTextures.end(); textureTypeIter++)
    {
        GLenum textureType = textureTypeIter->first;

        // Determine if this texture type can exist in the source context
        bool validTextureType = (textureType == GL_TEXTURE_2D || textureType == GL_TEXTURE_CUBE_MAP ||
                                 (textureType == GL_TEXTURE_2D_ARRAY && data.clientVersion >= 3) ||
                                 (textureType == GL_TEXTURE_3D && data.clientVersion >= 3));

        const std::vector<GLuint> &textureVector = textureTypeIter->second;
        for (size_t textureUnitIndex = 0; textureUnitIndex < textureVector.size(); textureUnitIndex++)
        {
            const gl::Texture *texture = nullptr;

            bool validTextureUnit = textureUnitIndex < caps.maxCombinedTextureImageUnits;
            if (validTextureType && validTextureUnit)
            {
                texture = state.getSamplerTexture(textureUnitIndex, textureType);
            }

            if (texture != nullptr)
            {
                const TextureGL *textureGL = GetImplAs<TextureGL>(texture);
                textureGL->syncSamplerState(texture->getSamplerState());

                if (mTextures[textureType][textureUnitIndex] != textureGL->getTextureID())
                {
                    activeTexture(textureUnitIndex);
                    bindTexture(textureType, textureGL->getTextureID());
                }

                // TODO: apply sampler object if one is bound
            }
            else
            {
                if (mTextures[textureType][textureUnitIndex] != 0)
                {
                    activeTexture(textureUnitIndex);
                    bindTexture(textureType, 0);
                }
            }
        }
    }

    const gl::Framebuffer *framebuffer = state.getDrawFramebuffer();
    const FramebufferGL *framebufferGL = GetImplAs<FramebufferGL>(framebuffer);
    bindFramebuffer(GL_DRAW_FRAMEBUFFER, framebufferGL->getFramebufferID());

    setScissor(state.getScissor());
    setViewport(state.getViewport());

    const gl::BlendState &blendState = state.getBlendState();
    setColorMask(blendState.colorMaskRed, blendState.colorMaskGreen, blendState.colorMaskBlue, blendState.colorMaskAlpha);

    const gl::DepthStencilState &depthStencilState = state.getDepthStencilState();
    setDepthMask(depthStencilState.depthMask);
    setStencilMask(depthStencilState.stencilMask);

    return gl::Error(GL_NO_ERROR);
}
Example #17
0
void OpenGLRenderer::setUniformTexture(Renderer::ShaderProgram* p,
                                       const std::string& name, GLint tex) {
    useProgram(p);

    glUniform1i(currentProgram->getUniformLocation(name), tex);
}
Example #18
0
void Renderer::draw() {
  // 2D rendering modelview
  glm::mat3 view(1.0f);
  view = translate2D(view, glm::vec2(-1.0f, -1.0f));
  view = scale2D(view, glm::vec2(2.0f/aspect_, 2.0f));
  view = translate2D(view, glm::vec2(-left_of_window_, 0.0f));
  root_node_.setRelativeTransform(view);

  vector<SceneNode *> draw2D;
  root_node_.getSortedVisibleDescendants(&draw2D);

  // Draw occluders to texture.
  //glBindFramebuffer(GL_FRAMEBUFFER, 0);
  //glViewport(0,0,width_, height_);
  glBindFramebuffer(GL_FRAMEBUFFER, occluder_frame_buffer_);
  glViewport(0,0,width_/2, height_/2);
  glDepthMask(GL_TRUE);
  glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glDepthMask(GL_FALSE);
  for (vector<SceneNode *>::iterator it = draw2D.begin(); it != draw2D.end(); ++it) {
    if ((*it)->isOccluder()) (*it)->drawOccluder();
  }
  //return;
  
  //glBindFramebuffer(GL_FRAMEBUFFER, 0);
  //glViewport(0,0,width_, height_);
  glBindFramebuffer(GL_FRAMEBUFFER, shadow_frame_buffer_);
  glDepthMask(GL_TRUE);
  glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glDepthMask(GL_FALSE);
  useProgram("shadows");
  glm::vec3 transformed_light_position = view * glm::vec3(light_position_, 1.0f);
  glUniform2fv(uniformHandle("light_position"), 1, glm::value_ptr(transformed_light_position));
  glBindTexture(GL_TEXTURE_2D, shadow_texture_);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, occluder_texture_);
  glBindVertexArray(quad_array_object_);
  glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
  //return;

  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glViewport(0,0,width_, height_);
  glDepthMask(GL_TRUE);
  glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glDepthMask(GL_FALSE);
  glEnable(GL_MULTISAMPLE);
  glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, shadow_texture_);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  for (vector<SceneNode *>::iterator it = draw2D.begin(); it != draw2D.end(); ++it) {
    if ((*it)->isVisible()) (*it)->draw();
  }

  if (do_stencil_) {
    glEnable(GL_STENCIL_TEST);
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    glStencilFunc(GL_ALWAYS, 0, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
    for (vector<SceneNode *>::iterator it = draw2D.begin(); it != draw2D.end(); ++it) {
      if ((*it)->is3DStencil()) (*it)->draw();
    }
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glStencilFunc(GL_NOTEQUAL, 0, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  }
  glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  glEnable(GL_BLEND);
  for (vector<Drawable *>::iterator it = draw3D_.begin(); it != draw3D_.end(); ++it) {
    (*it)->draw();
  }
  glDisable(GL_BLEND);
  if (do_stencil_) {
    glDisable(GL_STENCIL_TEST);
  }
}
gl::Error StateManagerGL::setGenericDrawState(const gl::Data &data)
{
    const gl::State &state = *data.state;

    // If the context has changed, pause the previous context's transform feedback and queries
    if (data.context != mPrevDrawContext)
    {
        if (mPrevDrawTransformFeedback != nullptr)
        {
            mPrevDrawTransformFeedback->syncPausedState(true);
        }

        for (QueryGL *prevQuery : mPrevDrawQueries)
        {
            prevQuery->pause();
        }
    }
    mPrevDrawTransformFeedback = nullptr;
    mPrevDrawQueries.clear();

    mPrevDrawContext = data.context;

    // Sync the current program state
    const gl::Program *program = state.getProgram();
    const ProgramGL *programGL = GetImplAs<ProgramGL>(program);
    useProgram(programGL->getProgramID());

    for (size_t uniformBlockIndex = 0; uniformBlockIndex < program->getActiveUniformBlockCount();
         uniformBlockIndex++)
    {
        GLuint binding = program->getUniformBlockBinding(static_cast<GLuint>(uniformBlockIndex));
        const OffsetBindingPointer<gl::Buffer> &uniformBuffer =
            data.state->getIndexedUniformBuffer(binding);

        if (uniformBuffer.get() != nullptr)
        {
            BufferGL *bufferGL = GetImplAs<BufferGL>(uniformBuffer.get());

            if (uniformBuffer.getSize() == 0)
            {
                bindBufferBase(GL_UNIFORM_BUFFER, binding, bufferGL->getBufferID());
            }
            else
            {
                bindBufferRange(GL_UNIFORM_BUFFER, binding, bufferGL->getBufferID(),
                                uniformBuffer.getOffset(), uniformBuffer.getSize());
            }
        }
    }

    const std::vector<SamplerBindingGL> &appliedSamplerUniforms = programGL->getAppliedSamplerUniforms();
    for (const SamplerBindingGL &samplerUniform : appliedSamplerUniforms)
    {
        GLenum textureType = samplerUniform.textureType;
        for (GLuint textureUnitIndex : samplerUniform.boundTextureUnits)
        {
            const gl::Texture *texture = state.getSamplerTexture(textureUnitIndex, textureType);
            if (texture != nullptr)
            {
                const TextureGL *textureGL = GetImplAs<TextureGL>(texture);

                if (mTextures[textureType][textureUnitIndex] != textureGL->getTextureID())
                {
                    activeTexture(textureUnitIndex);
                    bindTexture(textureType, textureGL->getTextureID());
                }

                textureGL->syncState(textureUnitIndex, texture->getTextureState());
            }
            else
            {
                if (mTextures[textureType][textureUnitIndex] != 0)
                {
                    activeTexture(textureUnitIndex);
                    bindTexture(textureType, 0);
                }
            }

            const gl::Sampler *sampler = state.getSampler(textureUnitIndex);
            if (sampler != nullptr)
            {
                const SamplerGL *samplerGL = GetImplAs<SamplerGL>(sampler);
                samplerGL->syncState(sampler->getSamplerState());
                bindSampler(textureUnitIndex, samplerGL->getSamplerID());
            }
            else
            {
                bindSampler(textureUnitIndex, 0);
            }
        }
    }

    const gl::Framebuffer *framebuffer = state.getDrawFramebuffer();
    const FramebufferGL *framebufferGL = GetImplAs<FramebufferGL>(framebuffer);
    bindFramebuffer(GL_DRAW_FRAMEBUFFER, framebufferGL->getFramebufferID());
    framebufferGL->syncDrawState();

    // Seamless cubemaps are required for ES3 and higher contexts.
    setTextureCubemapSeamlessEnabled(data.clientVersion >= 3);

    // Set the current transform feedback state
    gl::TransformFeedback *transformFeedback = state.getCurrentTransformFeedback();
    if (transformFeedback)
    {
        TransformFeedbackGL *transformFeedbackGL =
            GetImplAs<TransformFeedbackGL>(transformFeedback);
        bindTransformFeedback(GL_TRANSFORM_FEEDBACK, transformFeedbackGL->getTransformFeedbackID());
        transformFeedbackGL->syncActiveState(transformFeedback->isActive(),
                                             transformFeedback->getPrimitiveMode());
        transformFeedbackGL->syncPausedState(transformFeedback->isPaused());
        mPrevDrawTransformFeedback = transformFeedbackGL;
    }
    else
    {
        bindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
        mPrevDrawTransformFeedback = nullptr;
    }

    // Set the current query state
    for (GLenum queryType : QueryTypes)
    {
        gl::Query *query = state.getActiveQuery(queryType);
        if (query != nullptr)
        {
            QueryGL *queryGL = GetImplAs<QueryGL>(query);
            queryGL->resume();

            mPrevDrawQueries.insert(queryGL);
        }
    }

    return gl::Error(GL_NO_ERROR);
}
Example #20
0
void SGLShaderProgram::setUniform1i(const char* name, int value)
{
	useProgram();
    glUniform1i(getUniformLocation(name), value);
}
Example #21
0
void SGLShaderProgram::setUniform4f(const char* name, glm::vec4& value)
{
	useProgram();
    glUniform4f(getUniformLocation(name), value[0], value[1], value[2], value[3]);
}