Example #1
0
void TuioClientApp::setup()
{
	// Create your osc receiver with whatever configuration needed. In this case we'll open it up
	// with the Default Tuio Port - 3333.
	mOscReceiver = std::make_shared<osc::ReceiverUdp>( tuio::Receiver::DEFAULT_TUIO_PORT );

	// Create the Tuio Receiver passing the Osc Receiver's pointer. 
	mTuio = std::make_shared<tuio::Receiver>( mOscReceiver.get() );
	// Add your tuio callbacks.
	mTuio->setAddedFn<tuio::Cursor2d>( std::bind( &TuioClientApp::added, this, std::placeholders::_1 ) );
	mTuio->setUpdatedFn<tuio::Cursor2d>( std::bind( &TuioClientApp::updated, this, std::placeholders::_1 ) );
	mTuio->setRemovedFn<tuio::Cursor2d>( std::bind( &TuioClientApp::removed, this, std::placeholders::_1 ) );
	// Bind the Osc Receiver...
	try {
		mOscReceiver->bind();
	}
	catch( const ci::Exception &ex ) {
		CI_LOG_EXCEPTION( "OscReceiver bind", ex );
		quit();
	}
	// And listen for messages.
	mOscReceiver->listen( 
	[]( asio::error_code ec, asio::ip::udp::endpoint ep ) -> bool {
		if( ec ) {
			CI_LOG_E( "Error on listener: " << ec.message() << " Error Value: " << ec.value() );
			return false;
		}
		else
			return true;
	} );
}
Example #2
0
    virtual void draw() override {
//        float effTheta = theta + deltaSinceLastUpdate().in(Seconds);
        float effTheta = theta;
//        float effTheta = epochNanosSteady() * 1000000.0f;
//        float effTheta = glfwGetTime();
        AxGL::checkError();
        modelview = glm::lookAt(
                glm::vec3(0.0f,0.0f,-10.0f),
                glm::vec3(0.0f,0.0f,0.0f),
                glm::vec3(0.0f,1.0f,0.0f)
        );
        modelview = glm::rotate(modelview,effTheta,glm::vec3(0.0f,0.0f,-1.0f));

        projection = glm::perspective(45.0f,AxGL::aspectRatio(),0.5f,200.0f);

        glDisable(GL_DEPTH_TEST);

        texture->bind();
        AxGL::checkError();
        shader->bind();
        AxGL::checkError();
        shader->setUniform("ModelViewMatrix", modelview);
        shader->setUniform("ProjectionMatrix", projection);
        shader->setUniform("tex0",0);
        AxGL::checkError();
        vbo.drawElements();
        AxGL::checkError();
    }
Example #3
0
void GLES2Renderer::setRenderTarget(std::shared_ptr<IRenderTarget> target) {
	if (target == nullptr){
		glBindFramebuffer(GL_FRAMEBUFFER, 0); //Bind to default target (screen)
	} else {
		target->bind();
	}
	//TODO We need to store every render target that comes through here.
}
Example #4
0
void GeometryBatch::setIndices(const std::shared_ptr<Buffer>& ebo, GLenum type, size_t count) {
	m_ebo = ebo;
	m_elementsType = type;
	m_indexCount = count;

	m_vao.bind();
	ebo->bind(GL_ELEMENT_ARRAY_BUFFER);
}
Example #5
0
	void bind()
	{
		if(m_shaderAsset)
		{
			m_shaderAsset->bind();
		}

		if(m_colorTextureAsset)
		{
			m_colorTextureAsset->bind(0);
		}

		if(m_normalTextureAsset)
		{
			m_normalTextureAsset->bind(1);
		}
	}
Example #6
0
void readPngToTexture(const void * data, size_t size,
    std::shared_ptr<gl::Texture<TargetType> > & texture, glm::vec2 & textureSize) {
  std::vector<unsigned char> v(size);
  memcpy(&(v[0]), data, size);
  cv::Mat image = cv::imdecode(v, CV_LOAD_IMAGE_ANYDEPTH);
  texture = std::shared_ptr<gl::Texture<TargetType> >(new gl::Texture<TargetType>());
  GL_CHECK_ERROR;
  texture->bind();
  GL_CHECK_ERROR;
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, image.cols, image.rows, 0, GL_RGB,
  GL_UNSIGNED_BYTE, image.data);
  GL_CHECK_ERROR;
  gl::Texture<TargetType>::unbind();
  GL_CHECK_ERROR;
  }
Example #7
0
    void Scene::addFramebufferToTarget(glm::ivec2 targetSize, std::shared_ptr<NUGL::Framebuffer> target, float gridDim, float gridX, float gridY) {
        if (target == nullptr) {
            NUGL::Framebuffer::useDefault();
        } else {
            target->bind();
        }

//        glViewport(0, 0, targetSize.x, targetSize.y);
        glViewport(0, 0, framebufferSize.x, framebufferSize.y);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE);

        screen->setTexture(framebuffer->textureAttachments[GL_COLOR_ATTACHMENT0]);

        screen->render(gridDim, gridX, gridY);

        screen->removeTexture();
        glDisable(GL_BLEND);
    }
Example #8
0
// Display the ground plane
void displayGroundPlane()
{
  // Set the updated light positions
  gGroundPlane->setLightPosition0(gLightSphere[0]->getPosition());
  gGroundPlane->setLightPosition1(gLightSphere[1]->getPosition());
  gGroundPlane->setLightPosition2(gLightSphere[2]->getPosition());

  // Upload the new data to the GPU
  gGroundPlane->updateUniforms();

  // Bind model uniform buffer
  gGroundPlane->bind(gShaderProgram->handle(),1,"ub_Geometry");

  // Bind triangle geometry
  glBindVertexArray(gGroundPlane->handle());

  // Draw the indexed triangle set
  glDrawElements(GL_TRIANGLES, gGroundPlane->numIndices(),GL_UNSIGNED_INT, (void*)0);
}
Example #9
0
void Charts::Chart::renderImpl(const RenderArgs & renderArgs) const
{
	if (!TR_VERIFY(updated)) {
		return;
	}
	preRender();
	glClearColor(renderArgs.clearColor.x, renderArgs.clearColor.y, renderArgs.clearColor.z, renderArgs.clearColor.w);
	glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	if (fillColor.alpha > 0.0) {
		const std::shared_ptr<TR3DUtils::QuadRenderer> quadRenderer = renderContext->getQuadRenderer();
		quadRenderer->bind();
		quadRenderer->bindModelViewProjection(renderArgs.projection);
		quadRenderer->bindColor(Utils::colorToVec4(fillColor));
		quadRenderer->drawQuad(glm::vec3(renderArgs.areaStart, 0.0), renderArgs.areaSize);
	}
	for (const auto axis : axisList) {
		if (axis->isEnabled() && axis->isVisible()) {
			axis->renderGrid(*renderContext, renderArgs);
		}
	}
	std::vector<std::shared_ptr<ChartElement>> elements;
	elements.insert(elements.end(), seriesList.begin(), seriesList.end());
	elements.insert(elements.end(), decorationList.begin(), decorationList.end());
	std::stable_sort(elements.begin(), elements.end(), [](const std::shared_ptr<ChartElement> & a, const std::shared_ptr<ChartElement> & b) -> bool {
		return a->getDrawOrder() < b->getDrawOrder();
	});
	for (const auto element : elements) {
		if (element->isEnabled() && element->isVisible()) {
			element->render(*renderContext, renderArgs);
		}
	}
	for (const auto axis : axisList) {
		if (axis->isEnabled() && axis->isVisible()) {
			axis->renderAxis(*renderContext, renderArgs);
		}
	}
    glDisable(GL_BLEND);
}
Example #10
0
void Charts::LineDecoration::render(TR3DUtils::RenderContext & context, const RenderArgs & args) const
{
    if(TR_VERIFY(axis)) {
        beforeRender(context, args);
        const glm::float_t screenValue = axis->dataToScreen(this->value);
        if(axis->inScreenRange(screenValue)) {
            const glm::vec2 axisDirection = axis->getAxisDirection();
            const glm::vec2 gridDirection = axis->getGridDirection();
            const glm::float_t gridStart = axis->getGridStart();
            const glm::float_t gridLength = axis->getGridLength();
            const glm::vec2 start = (axisDirection * screenValue) + gridDirection * gridStart;
            const glm::vec2 end = (axisDirection * screenValue) + gridDirection * (gridStart + gridLength);
            const std::shared_ptr<TR3DUtils::LineRenderer> lineRenderer = context.getLineRenderer();
            glLineWidth(this->lineStyle.thickness * args.contentScaleFactor);
            lineRenderer->bind(TR3DUtils::LineRenderer::Mode(lineStyle.mode));
            lineRenderer->bindModelViewProjection(args.projection);
            lineRenderer->bindColor(Utils::colorToVec4(getColor()) * Utils::opacityToAlpha(getOpacity()));
            lineRenderer->drawLine(glm::vec3(start, 0.f), glm::vec3(end, 0.f));
        }
        afterRender(context, args);
    }
}
Example #11
0
void displayCB()
{
  // Set polygon mode to allow solid front and back-facing triangles
  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

  // Use the Phong shader
  glUseProgram(gShaderProgram->handle());

  // Upload possibly changed camera setup (e.g. camera eye) to GPU
  gCamera->updateUniforms();

  // Bind camera uniform buffer
  gCamera->bind(gShaderProgram->handle(),0,"ub_Camera");

  // Render the scene content
  displayLightSpheres();
  displayAxisArrows();
  displayGroundPlane();
  displayDice();

  // Unbind the Phong shader
  glUseProgram(0);
}
	void GLProgramData::setAttributeDataSource(
		const std::string & attrName,
		GLint size,
		GLenum type,
		GLboolean normalized,
		GLsizei stride,
		GLsizei offset,
		std::shared_ptr<GLBuffer> buffer)
	{
		glBindVertexArray(mVertexArrayId);
		CHECK_GL_ERROR();

		const GLint attrLoc = mProgram->getAttribLocation(attrName);
		
		if (!buffer)
		{
			glDisableVertexAttribArray(attrLoc);
			CHECK_GL_ERROR();

			mVertexBuffers.erase(attrName);
		}
		else
		{
			glEnableVertexAttribArray(attrLoc);
			CHECK_GL_ERROR();
			buffer->bind();
			glVertexAttribPointer(attrLoc, size, type, normalized, stride, (const GLvoid*)(offset));
			CHECK_GL_ERROR();
			buffer->unbind();

			mVertexBuffers[attrName] = buffer;
		}

		glBindVertexArray(0);
		CHECK_GL_ERROR();
	}
Example #13
0
void GLES2Renderer::render(Scene<float>& scene, Camera<float>* camera, std::shared_ptr<IRenderTarget> renderTarget, bool forceClear)  {

	glfwMakeContextCurrent(window);

	if (scene.autoUpdate) scene.updateMatrixWorld();

	if (camera->parent == nullptr) camera->updateMatrixWorld();

	camera->matrixWorldInverse.getInverse(camera->matrixWorld);

	projScreenMatrix = camera->projectionMatrix * camera->matrixWorldInverse;

	frustum.setFromMatrix(projScreenMatrix);

	if (renderTarget != nullptr){
		renderTarget->bind();
	}

	opaqueObjects.clear();
	transparentObjects.clear();

	projectObject(&scene, camera);

	if (sortObjects){
		std::stable_sort(opaqueObjects.begin(), opaqueObjects.end(), stablePainterSort);
		std::stable_sort(transparentObjects.begin(), transparentObjects.end(), reverseStablePainterSort);
	}

	//TODO Shadowmap goes here

	info.renderer.calls = 0;
	info.renderer.vertices = 0;
	info.renderer.faces = 0;
	info.renderer.points = 0;

	setRenderTarget(renderTarget);

	if (autoClear || forceClear){
		clear(this->autoClearColor, this->autoClearDepth, this->autoClearStencil);
	}

	if (scene.overrideMaterial != nullptr){

		renderObjects(opaqueObjects, scene, camera, scene.overrideMaterial.get());
		renderObjects(transparentObjects, scene, camera, scene.overrideMaterial.get());

	} else {

		renderObjects(opaqueObjects, scene, camera);
		renderObjects(transparentObjects, scene, camera);

	}

	glfwSwapBuffers(window);

	//TODO handle sprites and lensflares

	//This allows it to be cleared for the next render.
	setDepthTest(true);
	setDepthWrite(true);
	setColorWrite(true);

}
    void on_draw() override
    {
		glfwMakeContextCurrent(window);
        
		if (igm) igm->begin_frame();

		glEnable(GL_CULL_FACE);
		glEnable(GL_DEPTH_TEST);

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

		int width, height;
		glfwGetWindowSize(window, &width, &height);
		glViewport(0, 0, width, height);

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glClearColor(1.0f, 0.1f, 0.0f, 1.0f);

		const auto proj = camera.get_projection_matrix((float) width / (float) height);
		const float4x4 view = camera.get_view_matrix();
		const float4x4 viewProj = mul(proj, view);
        
		if (ImGui::SliderInt("Sun Theta", &sunPos.x, 0, 90)) skydome.set_sun_position(sunPos.x, sunPos.y);
		if (ImGui::SliderInt("Sun Phi", &sunPos.y, 0, 360)) skydome.set_sun_position(sunPos.x, sunPos.y);

        auto draw_cubes = [&](float3 eye, float4x4 vp)
        {
            simpleShader->bind();
            
            simpleShader->uniform("u_eye", eye); 
            simpleShader->uniform("u_viewProj", vp);
            
            simpleShader->uniform("u_emissive", float3(0, 0, 0));
            simpleShader->uniform("u_diffuse", float3(0.33f, 0.33f, 0.33f));
            
            for (int i = 0; i < 2; i++)
            {
                simpleShader->uniform("u_lights[" + std::to_string(i) + "].position", lights[i].position);
                simpleShader->uniform("u_lights[" + std::to_string(i) + "].color", lights[i].color);
            }
            
            for (const auto & model : regularModels)
            {
                simpleShader->uniform("u_modelMatrix", model.get_model());
                simpleShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model())));
                model.draw();
            }
            
            simpleShader->unbind();
        };

        // Render/Update cube camera
        cubeCamera->render = [&](float3 eyePosition, float4x4 viewMatrix, float4x4 projMatrix)
        {
            skydome.render(mul(projMatrix, viewMatrix), eyePosition, camera.farClip);
			draw_cubes(eyePosition, mul(projMatrix, viewMatrix));
        };

        cubeCamera->update(camera.get_eye_point()); // render from a camera positioned @ {0, 0, 0}

        glViewport(0, 0, width, height);
        skydome.render(viewProj, camera.get_eye_point(), camera.farClip);
        grid.render(proj, view);

        draw_cubes(camera.get_eye_point(), viewProj);
        
		// Glass material
        {
            glassMaterialShader->bind();
            
            glassMaterialShader->uniform("u_eye", camera.get_eye_point());
            glassMaterialShader->uniform("u_viewProj", viewProj);

			// Can set from either a pre-loaded cubemap, or one capured from the cubeCamera
            glassMaterialShader->texture("u_cubemapTex", 0, cubeCamera->get_cubemap_handle(), GL_TEXTURE_CUBE_MAP); // cubeTex.get_gl_handle()

            for (const auto & model : glassModels)
            {
                glassMaterialShader->uniform("u_modelMatrix", model.get_model());
                glassMaterialShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model())));
                model.draw();
            }

            glassMaterialShader->unbind();
            glDisable(GL_BLEND);
        }

        gl_check_error(__FILE__, __LINE__);
        if (igm) igm->end_frame();
        glfwSwapBuffers(window);
        frameCount++;
    }
Example #15
0
  void draw()
  {
    ++_frames;
    gpucast::gl::timer_guard full_frame("Frame total");

    float near_clip = 0.01f * _bbox.size().abs();
    float far_clip  = 2.0f  * _bbox.size().abs();

    gpucast::math::matrix4f view = gpucast::math::lookat(0.0f, 0.0f, float(_bbox.size().abs()),
      0.0f, 0.0f, 0.0f,
      0.0f, 1.0f, 0.0f);

    gpucast::math::vec3f translation = _bbox.center();

    gpucast::math::matrix4f model = gpucast::math::make_translation(shiftx(), shifty(), distance()) * rotation() *
      gpucast::math::make_translation(-translation[0], -translation[1], -translation[2]);

    gpucast::math::matrix4f proj = gpucast::math::perspective(50.0f, float(_width) / _height, near_clip, far_clip);

    auto mvp = proj * view * model;
    auto mvpi = gpucast::math::inverse(mvp);

    _renderer->set_nearfar(near_clip, far_clip);
    _renderer->set_resolution(_width, _height);
    _renderer->view_setup(view, model, proj);

    {
      //gpucast::gl::timer_guard t("renderer->begin_draw()");
      _renderer->begin_draw(); 
    }

    for (auto const& o : _objects)
    {
      //gpucast::gl::timer_guard t("Draw object");
      if (_renderer->inside_frustum(*o)) {
        o->draw(*_renderer);
      }
    }

    {
      //gpucast::gl::timer_guard t("renderer->end_draw()");
      _renderer->end_draw();
    }

    {
      gpucast::gl::timer_guard t("fxaa blit");
      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
      glClearColor(0.4, 0.0, 0.0, 1.0f);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

      _fxaa_program->begin();

      _fxaa_program->set_uniform_matrix4fv("modelviewprojectioninverse", 1, false, &mvpi[0]);
      _fxaa_program->set_uniform_matrix4fv("modelviewprojection", 1, false, &mvp[0]);

      _fxaa_program->set_texture2d("colorbuffer", *_colorattachment, 1);
      _fxaa_program->set_texture2d("depthbuffer", *_depthattachment, 2);

      _sample_linear->bind(1);
      _sample_linear->bind(2);

      _fxaa_program->set_uniform1i("fxaa_mode", int(_fxaa));
      _fxaa_program->set_uniform1i("width", GLsizei(_width));
      _fxaa_program->set_uniform1i("height", GLsizei(_height));
      _quad->draw();

      _fxaa_program->end();
    }
  }
Example #16
0
    void on_draw() override
    {
        glfwMakeContextCurrent(window);

        if (igm) igm->begin_frame();

        int width, height;
        glfwGetWindowSize(window, &width, &height);
        glViewport(0, 0, width, height);

        glEnable(GL_DEPTH_TEST);
        glEnable(GL_CULL_FACE);
        glDepthMask(GL_TRUE);

        float windowAspectRatio = (float) width / (float) height;

        const auto proj = camera.get_projection_matrix(windowAspectRatio);
        const float4x4 view = camera.get_view_matrix();
        const float4x4 viewProj = mul(proj, view);

        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        skydome.render(viewProj, camera.get_eye_point(), camera.farClip);

        float3 target = camera.pose.position;

        ////////////////////////////////////////////
        // Directional Light Shadowmap Pass (sun) //
        ////////////////////////////////////////////
        {
            shadowFramebuffer.bind_to_draw();
            shadowmapShader->bind();

            glClear(GL_DEPTH_BUFFER_BIT);
            glViewport(0, 0, shadowmapResolution, shadowmapResolution);

            shadowmapShader->uniform("u_lightViewProj", sunLight->get_view_proj_matrix(target));

            for (auto & object : sceneObjects)
            {
                if (object->castsShadow)
                {
                    shadowmapShader->uniform("u_modelMatrix", object->get_model());
                    object->draw();
                }
            }

            shadowmapShader->unbind();
            shadowFramebuffer.unbind();
        }


        ///////////////////////////////
        // Spot Light Shadowmap Pass //
        ///////////////////////////////
        {

            for (int i = 0; i < spotLightFramebuffers.size(); ++i)
            {
                spotLightFramebuffers[i]->shadowFramebuffer.bind_to_draw();
                shadowmapShader->bind();

                glClear(GL_DEPTH_BUFFER_BIT);
                glViewport(0, 0, shadowmapResolution, shadowmapResolution);

                shadowmapShader->uniform("u_lightViewProj", spotLights[0]->get_view_proj_matrix()); // only take the first into account for debugging

                for (auto & object : sceneObjects)
                {
                    if (object->castsShadow)
                    {
                        shadowmapShader->uniform("u_modelMatrix", object->get_model());
                        object->draw();
                    }
                }

                shadowmapShader->unbind();
                spotLightFramebuffers[i]->shadowFramebuffer.unbind();
            }

        }

        ////////////////////////////////
        // Point Light Shadowmap Pass //
        ////////////////////////////////
        {
            glViewport(0, 0, shadowmapResolution, shadowmapResolution);

            for (int i = 0; i < 6; ++i)
            {
                pointLightFramebuffer->bind(pointLightFramebuffer->faces[i].face);

                pointLightShader->bind();

                glClear(GL_DEPTH_BUFFER_BIT);

                pointLightFramebuffer->faces[i].faceCamera.set_position(pointLight->position); // set position from light data to camera for shadow fbo
                auto viewProj = mul(pointLightFramebuffer->get_projection(), pointLightFramebuffer->faces[i].faceCamera.get_view_matrix());

                pointLightShader->uniform("u_lightWorldPosition", pointLight->position);
                pointLightShader->uniform("u_lightViewProj", viewProj);

                for (auto & object : sceneObjects)
                {
                    if (object->castsShadow)
                    {
                        pointLightShader->uniform("u_modelMatrix", object->get_model());
                        object->draw();
                    }
                }

                pointLightShader->unbind();
                pointLightFramebuffer->unbind();
            }
        }

        // Blur applied to the directional light shadowmap only (others later)
        {
            shadowBlurFramebuffer.bind_to_draw();
            glDrawBuffer(GL_COLOR_ATTACHMENT0);

            gaussianBlurShader->bind();

            // Configured for a 7x7
            gaussianBlurShader->uniform("blurSize", 1.0f / shadowmapResolution);
            gaussianBlurShader->uniform("sigma", blurSigma);
            gaussianBlurShader->uniform("u_modelViewProj", Identity4x4);

            // Horizontal
            gaussianBlurShader->texture("s_blurTexure", 0, shadowDepthTexture);
            gaussianBlurShader->uniform("numBlurPixelsPerSide", 3.0f);
            gaussianBlurShader->uniform("blurMultiplyVec", float2(1.0f, 0.0f));
            fullscreen_post_quad.draw_elements();

            // Vertical
            gaussianBlurShader->texture("s_blurTexure", 0, shadowBlurTexture);
            gaussianBlurShader->uniform("numBlurPixelsPerSide", 3.0f);
            gaussianBlurShader->uniform("blurMultiplyVec", float2(0.0f, 1.0f));
            fullscreen_post_quad.draw_elements();

            gaussianBlurShader->unbind();

            shadowBlurFramebuffer.unbind();
        }

        {
            glViewport(0, 0, width, height);
            sceneShader->bind();

            sceneShader->uniform("u_viewProj", viewProj);
            sceneShader->uniform("u_eye", camera.get_eye_point());
            sceneShader->uniform("u_directionalLight.color", sunLight->color);
            sceneShader->uniform("u_directionalLight.direction", sunLight->direction);
            sceneShader->uniform("u_dirLightViewProjectionMat", sunLight->get_view_proj_matrix(target));

            int samplerIndex = 0;
            sceneShader->uniform("u_shadowMapBias", 0.01f / shadowmapResolution); // fixme
            sceneShader->uniform("u_shadowMapTexelSize", float2(1.0f / shadowmapResolution));
            sceneShader->texture("s_directionalShadowMap", samplerIndex++, shadowBlurTexture);

            sceneShader->uniform("u_spotLightViewProjectionMat[0]", spotLights[0]->get_view_proj_matrix());

            sceneShader->uniform("u_spotLights[0].color", spotLights[0]->color);
            sceneShader->uniform("u_spotLights[0].direction", spotLights[0]->direction);
            sceneShader->uniform("u_spotLights[0].position", spotLights[0]->position);
            sceneShader->uniform("u_spotLights[0].cutoff", spotLights[0]->get_cutoff());
            sceneShader->uniform("u_spotLights[0].constantAtten", spotLights[0]->attenuation.x);
            sceneShader->uniform("u_spotLights[0].linearAtten", spotLights[0]->attenuation.y);
            sceneShader->uniform("u_spotLights[0].quadraticAtten", spotLights[0]->attenuation.z);

            sceneShader->uniform("u_pointLights[0].color", pointLight->color);
            sceneShader->uniform("u_pointLights[0].position", pointLight->position);
            sceneShader->uniform("u_pointLights[0].constantAtten", pointLight->attenuation.x);
            sceneShader->uniform("u_pointLights[0].linearAtten", pointLight->attenuation.y);
            sceneShader->uniform("u_pointLights[0].quadraticAtten", pointLight->attenuation.z);

            // Update the spotlight 2D sampler
            for (int i = 0; i < spotLightFramebuffers.size(); ++i)
            {
                auto & fbo = spotLightFramebuffers[i];
                std::string uniformLocation = "s_spotLightShadowMap[" + std::to_string(i) + "]";
                sceneShader->texture(uniformLocation.c_str(), samplerIndex + i, fbo->shadowDepthTexture);
            }

            // Update the pointlight cube sampler
            for (int i = 0; i < 6; i++)
                sceneShader->texture("s_pointLightCubemap[0]", 2 + i, pointLightFramebuffer->cubeMapHandle, GL_TEXTURE_CUBE_MAP);

            for (auto & object : sceneObjects)
            {
                sceneShader->uniform("u_modelMatrix", object->get_model());
                sceneShader->uniform("u_modelMatrixIT", inv(transpose(object->get_model())));
                object->draw();
                gl_check_error(__FILE__, __LINE__);
            }

            sceneShader->unbind();
        }

        {
            ImGui::Separator();
            ImGui::SliderFloat("Near Clip", &camera.nearClip, 0.1f, 2.0f);
            ImGui::SliderFloat("Far Clip", &camera.farClip, 2.0f, 75.0f);
            ImGui::DragFloat3("Light Direction", &sunLight->direction[0], 0.1f, -1.0f, 1.0f);
            ImGui::Separator();
            ImGui::SliderFloat("Blur Sigma", &blurSigma, 0.05f, 9.0f);
            ImGui::Separator();
            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
        }

        viewA->draw(uiSurface.children[0]->bounds, int2(width, height));
        viewB->draw(uiSurface.children[1]->bounds, int2(width, height));
        viewC->draw(uiSurface.children[2]->bounds, int2(width, height));
        viewD->draw(uiSurface.children[3]->bounds, int2(width, height));

        gl_check_error(__FILE__, __LINE__);

        if (igm) igm->end_frame();

        glfwSwapBuffers(window);
    }
Example #17
0
void GeometryBatch::setVertices(const std::shared_ptr<Buffer>& vbo, size_t count, const std::vector<VertexElement>& layout) {
	m_vbo = vbo;
	m_vertexCount = count;
	m_vao.bind();

	size_t computedStride = computeStride(layout);

	size_t previousOffset = 0;

	vbo->bind(GL_ARRAY_BUFFER);
	for (size_t i = 0; i < layout.size(); ++i) {
		auto element = layout[i];

		size_t offset = element.offset;
		// if offset is 0 then compute it
		if (i != 0 && offset == 0)
			offset = previousOffset + layout[i - 1].numComponents * elementTypeSize(layout[i - 1].type);

		previousOffset = offset;

		size_t stride = element.stride;
		if (stride == 0)
			stride = computedStride;

		glEnableVertexAttribArray(i);
		switch (element.type)
		{
		case VertexElementType::Float:
			glVertexAttribPointer(i, element.numComponents, GL_FLOAT, GL_FALSE, 
				stride, reinterpret_cast<const void*>(offset));
			break;
		case VertexElementType::Double:
			glVertexAttribLPointer(i, element.numComponents, GL_DOUBLE, 
				stride, reinterpret_cast<const void*>(offset));
		case VertexElementType::Byte:
			glVertexAttribIPointer(i, element.numComponents, GL_BYTE, 
				stride, reinterpret_cast<const void*>(offset));
			break;
		case VertexElementType::UnsignedByte:
			glVertexAttribIPointer(i, element.numComponents, GL_UNSIGNED_BYTE, 
				stride, reinterpret_cast<const void*>(offset));
			break;
		case VertexElementType::Short:
			glVertexAttribIPointer(i, element.numComponents, GL_SHORT, 
				stride, reinterpret_cast<const void*>(offset));
			break;
		case VertexElementType::UnsignedShort:
			glVertexAttribIPointer(i, element.numComponents, GL_UNSIGNED_SHORT, 
				stride, reinterpret_cast<const void*>(offset));
			break;
		case VertexElementType::Int:
			glVertexAttribIPointer(i, element.numComponents, GL_INT, 
				stride, reinterpret_cast<const void*>(offset));
			break;
		case VertexElementType::UsignedInt:
			glVertexAttribIPointer(i, element.numComponents, GL_UNSIGNED_INT, 
				stride, reinterpret_cast<const void*>(offset));
			break;
		}
	}
}
    void on_draw() override
    {
        glfwMakeContextCurrent(window);

        if (igm) igm->begin_frame();

        glEnable(GL_CULL_FACE);
        glEnable(GL_DEPTH_TEST);

        int width, height;
        glfwGetWindowSize(window, &width, &height);
        glViewport(0, 0, width, height);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(1.0f, 0.1f, 0.0f, 1.0f);

        ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);

        ImGui::SliderFloat("Projectile Velocity", &turret.velocity, 0.f, 100.f);

        if (ImGui::Button("Fire"))
        {
            turret.projectile = BallisticProjectile();
            turret.projectile.p = turret.source.pose;
            turret.projectile.lastPos = turret.source.pose.position;
            turret.projectile.gravity = 0.0;

            /*
            float3 firingSolutionLow;
            float3 firingSolutionHigh;
            auto numSolutions = solve_ballistic_arc(turret.source.pose.position, turret.velocity, turret.target.pose.position, 9.8f, firingSolutionLow, firingSolutionHigh);
            */

            float3 fireVelocity;
            float gravity;
            auto canFire = solve_ballistic_arc_lateral(turret.source.pose.position, turret.velocity, turret.target.pose.position, 10.f, fireVelocity, gravity);

            //std::cout << "Num Solutions: " << numSolutions << std::endl;
            //std::cout << "Low Solution: " << firingSolutionLow << std::endl;
            std::cout << "Fire Velocity: " << fireVelocity << std::endl;

            if (canFire)
            {
                turret.projectile.gravity = gravity;
                turret.projectile.add_impulse(fireVelocity);
                turret.fired = true;
            }
        }

        ImGui::Spacing();

        if (ImGui::SliderInt("M", &ssM, 1, 30)) regeneratePointer = true;
        if (ImGui::SliderInt("N1", &ssN1, 1, 30)) regeneratePointer = true;
        if (ImGui::SliderInt("N2", &ssN2, 1, 30)) regeneratePointer = true;
        if (ImGui::SliderInt("N3", &ssN3, 1, 30)) regeneratePointer = true;

        ImGui::Spacing();

        ImGui::BeginGroup();

        if (ImGui::SliderFloat3("Position", &params.position.x, -5, 5))
            parabolicPointer = make_parabolic_pointer(worldSurface, params);

        if (ImGui::SliderFloat3("Velocity", &params.velocity.x, -1.f, 1.f))
            parabolicPointer = make_parabolic_pointer(worldSurface, params);

        if (ImGui::SliderFloat("Point Spacing", &params.pointSpacing, 0.5, 2.0))
            parabolicPointer = make_parabolic_pointer(worldSurface, params);

        if (ImGui::SliderFloat("Point Count", &params.pointCount, 16, 64))
            parabolicPointer = make_parabolic_pointer(worldSurface, params);

        ImGui::EndGroup();

        const auto proj = camera.get_projection_matrix((float) width / (float) height);
        const float4x4 view = camera.get_view_matrix();
        const float4x4 viewProj = mul(proj, view);

        glViewport(0, 0, width, height);

        skydome.render(viewProj, camera.get_eye_point(), camera.farClip);
        grid.render(proj, view);

        {
            simpleShader->bind();

            simpleShader->uniform("u_eye", camera.get_eye_point());
            simpleShader->uniform("u_viewProj", viewProj);

            simpleShader->uniform("u_emissive", float3(0, 0, 0));
            simpleShader->uniform("u_diffuse", float3(0.0f, 1.0f, 0.0f));

            for (int i = 0; i < 2; i++)
            {
                simpleShader->uniform("u_lights[" + std::to_string(i) + "].position", lights[i].position);
                simpleShader->uniform("u_lights[" + std::to_string(i) + "].color", lights[i].color);
            }

            for (const auto & model : shadedModels)
            {
                simpleShader->uniform("u_modelMatrix", model.get_model());
                simpleShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model())));
                model.draw();
            }

            {
                simpleShader->uniform("u_modelMatrix", turret.source.get_model());
                simpleShader->uniform("u_modelMatrixIT", inv(transpose(turret.source.get_model())));
                turret.source.draw();

                simpleShader->uniform("u_modelMatrix", turret.target.get_model());
                simpleShader->uniform("u_modelMatrixIT", inv(transpose(turret.target.get_model())));
                turret.target.draw();

                auto projectileMat = turret.projectile.p.matrix();
                simpleShader->uniform("u_modelMatrix", projectileMat);
                simpleShader->uniform("u_modelMatrixIT", inv(transpose(projectileMat)));
                turret.bullet.draw();
            }

            simpleShader->unbind();
        }

        {
            normalDebugShader->bind();
            normalDebugShader->uniform("u_viewProj", viewProj);

            // Some debug models
            for (const auto & model : debugModels)
            {
                normalDebugShader->uniform("u_modelMatrix", model.get_model());
                normalDebugShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model())));
                model.draw();
            }

            // Supershape
            {
                normalDebugShader->uniform("u_modelMatrix", supershape.get_model());
                normalDebugShader->uniform("u_modelMatrixIT", inv(transpose(supershape.get_model())));
                supershape.draw();
            }

            // Parabolic pointer
            {
                normalDebugShader->uniform("u_modelMatrix", parabolicPointer.get_model());
                normalDebugShader->uniform("u_modelMatrixIT", inv(transpose(parabolicPointer.get_model())));
                parabolicPointer.draw();
            }

            // Parallel transport boxes
            for (int i = 0; i < ptfBoxes.size(); ++i)
            {
                auto & model = ptfBoxes[i];
                auto modelMat = ptf[i];
                normalDebugShader->uniform("u_modelMatrix", mul(modelMat, make_scaling_matrix(0.01)));
                normalDebugShader->uniform("u_modelMatrixIT", inv(transpose(modelMat)));
                model.draw();
            }

            normalDebugShader->unbind();
        }

        gl_check_error(__FILE__, __LINE__);
        if (igm) igm->end_frame();
        glfwSwapBuffers(window);
        frameCount++;
    }
Example #19
0
std::vector<unsigned char> GLES2Renderer::readRenderTargetPixels(std::shared_ptr<IRenderTarget> target, int x, int y, unsigned width, unsigned height) {
	std::vector<unsigned char> data(width * height * 3);
	target->bind();
	glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, data.data());
	return data;
}
Example #20
0
void GLES2Renderer::clearTarget(std::shared_ptr<IRenderTarget> target, bool color, bool depth, bool stencil) {
	target->bind();
	clear(color, depth, stencil);
	glBindFramebuffer(GL_FRAMEBUFFER, 0); //Unbind
}