Пример #1
0
bool collides(Entity* const entityOne, Entity* const entityTwo)
{//Function which  uses the separating axis theorem to detect for collisions between two entities
	//Projection getProjection(const sf::Vector2f&, const Square&);
	std::vector<sf::Vector2f> axes1(entityOne->getVertexCount());
	std::vector<sf::Vector2f> axes2(entityTwo->getVertexCount());

	for (int i(0); i < entityOne->getVertexCount(); ++i)
	{//Loop through the first shape and get all normals to each side
		int index(0);
		(i + 1) == entityOne->getVertexCount() ? index = 0 : index = i + 1;

		axes1[i] = entityOne->getNormal(i, index);
	}

	for (int i(0); i < entityTwo->getVertexCount(); ++i)
	{//Loop through the second shape and get all normals to each side
		int index(0);
		(i + 1) == entityTwo->getVertexCount() ? index = 0 : index = i + 1;

		axes2[i] = entityTwo->getNormal(i, index);
	}

	for (int i(0); i < axes1.size(); ++i)
	{//Project shape2 onto shape1's axis and determine if there's a gap
		sf::Vector2f normal(axes1[i]);

		SATProjection proj1(getProjection(normal, entityOne)); //max and minimum values of the first shape projection
		SATProjection proj2(getProjection(normal, entityTwo)); //max and minimum values of the second shape projection


		if (!overlaps(proj1, proj2))
			return false;
	}

	for (int i(0); i < axes2.size(); ++i)
	{
		sf::Vector2f normal(axes2[i]);

		SATProjection proj1(getProjection(normal, entityOne)); //max and minimum values of the first shape projection
		SATProjection proj2(getProjection(normal, entityTwo)); //max and minimum values of the second shape projection


		if (!overlaps(proj1, proj2))
			return false;
	}

	return(true);
}
/**
 * @brief FileProjections::findShortPaths finds paths between fromId and toId
 * nodes Functions returns all available paths same length.
 * @param fromId - node id for seach paths.
 * @param toId - node id for seatch paths
 * @param reverse - by default path order from root elem to find elem
 * @return nullptr if no paths else vector of paths. path is vector of ids.
 */
ProjShortPaths* FileProjections::findShortPaths(unsigned fromId, unsigned toId,
                                                bool reverse)
{
    if(isMemoryUsed())
    {
        return Projections::findShortPaths(fromId, toId, reverse);
    }
    if (loadedProjection)
    {
        if (loadedProjection->getId() == fromId)
        {
            return loadedProjection->findShortPaths(toId, reverse);
        }
        else if(loadedProjection->getId() == toId)
        {
            return loadedProjection->findShortPaths(fromId, !reverse);
        }
        else
        {
            loadedProjection->clear();
            loadedProjection = nullptr;
        }
    }
    auto pr = getProjection(fromId);
    if (!pr)
    {
        return nullptr;
    }
    return pr->findShortPaths(toId, reverse);
}
Пример #3
0
void WorldView::render(Window &window) {
    prgm.setUniform("perspective", getProjection(window).getMatrix());

    chunkmeshes.getBlockTex().bind(0);
    sampler.bind(0);

    const glm::mat4 view = camera.getMatrix();

    glm::ivec3 centerchunkpos =
        ChunkGrid::posToChunkBlock(glm::ivec3{camera.pos}).first;

    for (int x = centerchunkpos.x - 3; x <= centerchunkpos.x + 3; x++) {
        for (int y = centerchunkpos.y - 3; y <= centerchunkpos.y + 3; y++) {
            for (int z = centerchunkpos.z - 3; z <= centerchunkpos.z + 3; z++) {
                glm::ivec3 chunkpos{x, y, z};
                auto chunkptr = world.getChunks().getChunk(chunkpos);
                auto meshptr = chunkmeshes.updateMesh(chunkpos, chunkptr);
                if (!meshptr) {
                    continue;
                }
                
                glm::mat4 model{1};
                model = glm::translate(model, glm::vec3{32*chunkpos});
                prgm.setUniform("modelview", view*model);
                meshptr->draw(prgm);
            }
        }
    }

    chunkmeshes.freeUnusedMeshes();
}
Пример #4
0
void Camera::setup(      DrawActionBase *OSG_CHECK_ARG(action),
                   const Viewport       &port                 )
{
    Matrix m, t;

    // set the projection

    getProjection           (m, port.getPixelWidth(), port.getPixelHeight());
    getProjectionTranslation(t, port.getPixelWidth(), port.getPixelHeight());

    m.mult(t);

    //SDEBUG << "Projection matrix: " << m << std::endl;

    glMatrixMode (GL_PROJECTION);
    GLP::glLoadMatrixf(m.getValues());

    // set the viewing

    getViewing(m, port.getPixelWidth(), port.getPixelHeight());

    //SDEBUG << "Viewing matrix: " << m << std::endl;

    glMatrixMode (GL_MODELVIEW );
    GLP::glLoadMatrixf(m.getValues());
}
Пример #5
0
Matrix4d Light::getViewProjection(double aspect, int projection_nb)
{
	Matrix4d projection = getProjection(aspect, projection_nb);
	Matrix4d view = node()->getGlobalTransform().getInverse();
	debug("MATRIX_STACK", "get viewprojection : view" << QMatrix4x4(view.values));
	debug("MATRIX_STACK", "get viewprojection : viewprojection" << QMatrix4x4((projection*view).values));
	return projection*view;
}
Пример #6
0
void Camera::unproject(Point& point, double aspectRatio) const {
  Vertex v = Vertex::Ones();
  v.segment(0, 3) = point;
  v = (getProjection(aspectRatio)*getTransformation()).inverse()*v;

  point[0] = v[0]/v[3];
  point[1] = v[1]/v[3];
  point[2] = v[2]/v[3];
}
Пример #7
0
void StelCore::setCurrentProjectionType(ProjectionType type)
{
	currentProjectionType=type;
	const double savedFov = currentProjectorParams.fov;
	currentProjectorParams.fov = 0.0001;	// Avoid crash
	double newMaxFov = getProjection(StelProjector::ModelViewTranformP(new StelProjector::Mat4dTransform(Mat4d::identity())))->getMaxFov();
	movementMgr->setMaxFov(newMaxFov);
	currentProjectorParams.fov = qMin(newMaxFov, savedFov);
}
Пример #8
0
void ROrthoGrid::paintGridLines(const RVector& space, const RBox& box, bool meta) {
    if (!space.isValid()) {
        return;
    }

    // updates cache if necessary:
    getProjection();
    isIsometric();

    RVector min = box.getCorner1();
    RVector max = box.getCorner2();

    double deltaX = max.x - min.x;
    double deltaY = max.y - min.y;

    if (deltaX / space.x > 1e3 || deltaY / space.y > 1e3) {
        return;
    }

    double dx = deltaY / tan(M_PI/6);
    if (isometric) {
        min.x -= dx;
        max.x += dx;
    }
    int c;
    double x;
    for (x=min.x, c=0; x<max.x; x+=space.x, c++) {
        //int x2 = RMath::mround(x/space.x);
        //if (!isometric || c%2==0) {
        if (isometric) {
            if (projection==RS::IsoTop || projection==RS::IsoRight) {
                view.paintGridLine(RLine(RVector(x, min.y), RVector(x+dx, max.y)));
            }
            if (projection==RS::IsoTop || projection==RS::IsoLeft) {
                view.paintGridLine(RLine(RVector(x, min.y), RVector(x-dx, max.y)));
            }

            // vertical grid lines:
            if (projection==RS::IsoRight || projection==RS::IsoLeft) {
                view.paintGridLine(RLine(RVector(x, min.y), RVector(x, max.y)));
                view.paintGridLine(RLine(RVector(x-space.x/2, min.y), RVector(x-space.x/2, max.y)));
            }
        }
        else {
            view.paintGridLine(RLine(RVector(x, min.y), RVector(x, max.y)));
        }
        //}
    }

    // horizontal lines:
    if (!isometric) {
        for (double y=min.y; y<max.y; y+=space.y) {
            view.paintGridLine(RLine(RVector(min.x, y), RVector(max.x, y)));
        }
    }
}
	virtual void mainUpdate(double time)
	{
		static double totalTime = 0;
		unsigned int textureOffset = 0;
		auto &renderer = _scene->getEngine().getInstance<Renderer>();
		OpenGLTools::UniformBuffer *perFrameBuffer = _scene->getEngine().getInstance<Renderer>().getUniform("PerFrame");

		for (auto e : _collection)
		{
			auto camera = e->getComponent<Component::CameraComponent>();
			auto skybox = camera->getSkybox();
			auto lookAt = e->getGlobalTransform();
			lookAt = glm::translate(lookAt, glm::vec3(0, 0, 1));

			auto cameraPosition = camera->getLookAtTransform();

			if (skybox.get())
			{
				OpenGLTools::Shader *s = _scene->getEngine().getInstance<Renderer>().getShader(camera->getSkyboxShader());
				assert(s != NULL && "Skybox does not have a shader associated");

				_scene->getEngine().getInstance<Renderer>().getUniform("cameraUniform")->setUniform("projection", camera->getProjection());

				glm::mat4 t = cameraPosition;
				t[3][0] = 0;
				t[3][1] = 0;
				t[3][2] = 0;
				t[3][3] = 1;

				_scene->getEngine().getInstance<Renderer>().getUniform("cameraUniform")->setUniform("view", t);
				_scene->getEngine().getInstance<Renderer>().getUniform("cameraUniform")->flushChanges();

//				_engine.getInstance<Renderer>().getFbo().bindDrawTargets(s->getTargets(), s->getTargetsNumber());

				s->use();

				glActiveTexture(GL_TEXTURE0);
				glBindTexture(GL_TEXTURE_CUBE_MAP, skybox->getId());
				glDepthMask(0);
				skybox->draw();
				glDepthMask(1);
				glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
			}

			totalTime += time;



			// Set les uniforms du block PerFrame
			perFrameBuffer->setUniform("projection", camera->getProjection());
			perFrameBuffer->setUniform("view", cameraPosition);
			perFrameBuffer->setUniform("time", (float)totalTime);
			perFrameBuffer->flushChanges();
			_scene->getSystem<MeshRendererSystem>()->render(time);
		}
	}
Пример #10
0
string QMerge::toString() {
  string r = "";

  r = "MERGE ";

  Projection* p = getProjection();
  r += p->toString();

  return r;
}
Пример #11
0
Vec3 Camera::screenNormToRay(Vec2 screen_pos) {
	Vec4 ray_clip = Vec4(screen_pos.x, screen_pos.y, 1.0f, 1.0f);
	Mat4 projection = getProjection();
	Mat4 my_inv_p = Mat4::invPerspective(projection);
	Vec4 ray_eye = Mat4::transform(my_inv_p, ray_clip);
	
	Vec3 ray_wor = Mat4::transform(Mat4::transpose(getView()), Vec4(ray_eye.x, ray_eye.y, 1.0f, 0.0f)).xyz;
	ray_wor = Vec3::normalize(ray_wor);
	return ray_wor;
}
Пример #12
0
void Camera::getWorldToScreen(Matrix &result, const Viewport& p)
{
    Matrix mv,prt,pr;

    getProjection           (result, p.getPixelWidth(), p.getPixelHeight());
    getProjectionTranslation(prt   , p.getPixelWidth(), p.getPixelHeight());
    getViewing              (mv    , p.getPixelWidth(), p.getPixelHeight());

    result.mult(prt);
    result.mult(mv );
}
Пример #13
0
void Camera::loadViewFrustum(ViewFrustum& frustum) const {
    // We will use these below, from either the camera or head vectors calculated above
    frustum.setProjection(getProjection());

    // Set the viewFrustum up with the correct position and orientation of the camera
    frustum.setPosition(getPosition());
    frustum.setOrientation(getOrientation());

    // Ask the ViewFrustum class to calculate our corners
    frustum.calculate();
}
Пример #14
0
bool Camera::calcViewRay(      Line    &line, 
                               Int32     x, 
                               Int32     y, 
                         const Viewport &port,
                               Real32   *t   )
{
    if(port.getPixelWidth() <= 0 || port.getPixelHeight() <= 0)
    {
        return false;
    }

    Matrix proj, projtrans, view;

    getProjection(proj,
                  port.getPixelWidth(),
                  port.getPixelHeight());

    getProjectionTranslation(projtrans,
                             port.getPixelWidth(),
                             port.getPixelHeight());

    getViewing(view,
               port.getPixelWidth(),
               port.getPixelHeight());

    Matrix wctocc = proj;

    wctocc.mult(projtrans);
    wctocc.mult(view);

    Matrix cctowc;

    cctowc.invertFrom(wctocc);

    Real32 rx(0.f), ry(0.f);
    port.getNormalizedCoordinates(rx, ry, x, y);

    Pnt3f from, at;

    cctowc.multFull(Pnt3f(rx, ry, -1), from);
    cctowc.multFull(Pnt3f(rx, ry,  1), at  );

	Vec3f dir = at - from;
	
	if(t != NULL)
	{
		*t = dir.length();
	}

    line.setValue(from, dir);

    return true;
}
Пример #15
0
QString StelCore::projectionNameI18nToTypeKey(const QString& nameI18n) const
{
	const QMetaEnum& en = metaObject()->enumerator(metaObject()->indexOfEnumerator("ProjectionType"));
	for (int i=0;i<en.keyCount();++i)
	{
		if (getProjection(StelProjector::ModelViewTranformP(new StelProjector::Mat4dTransform(Mat4d::identity())), (ProjectionType)i)->getNameI18()==nameI18n)
			return en.valueToKey(i);
	}
	// Unknown translated name
	Q_ASSERT(0);
	return en.valueToKey(ProjectionStereographic);
}
Пример #16
0
void ObjectFromObj::renderImpl()
{
	if (shader_)
	{
		shader_->use();

		M_.setValue(getModel());
		V_.setValue(getCameraView());
		P_.setValue(getProjection());
	}

	int lastBuf = -1;
	glEnableVertexAttribArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, vertexesBuffer_);
	glVertexAttribPointer(++lastBuf, 4, GL_FLOAT, GL_FALSE, 0, (void*)0 );

	if (indicesBuffer_ == -1)
	{
		if (texturesBuffer_ != -1)
		{
			glEnableVertexAttribArray(2);
			glBindBuffer(GL_ARRAY_BUFFER, texturesBuffer_);
			glVertexAttribPointer(++lastBuf, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );
		}

		if (normalsBuffer_ != -1)
		{
			glEnableVertexAttribArray(1);
			glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer_);
			glVertexAttribPointer(++lastBuf, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );
		}

		if (fragNormalsBuffer_ != -1)
		{
			glEnableVertexAttribArray(1);
			glBindBuffer(GL_ARRAY_BUFFER, fragNormalsBuffer_);
			glVertexAttribPointer(++lastBuf, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );
		}

		glDrawArrays(GL_TRIANGLES, 0, vertexesSize_);
	}
	else
	{
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer_);
		glDrawElements(GL_TRIANGLES, indicesSize_, GL_UNSIGNED_INT, (void*)(0));
	}

	for (int i = 0; i <= lastBuf; ++i)
		glDisableVertexAttribArray(i);
	
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
Пример #17
0
void Camera::getFrustum(FrustumVolume& result, const Viewport& p)
{
    Matrix mv,prt,pr;

    getProjection           (pr , p.getPixelWidth(), p.getPixelHeight());
    getProjectionTranslation(prt, p.getPixelWidth(), p.getPixelHeight());
    getViewing              (mv , p.getPixelWidth(), p.getPixelHeight());

    pr.mult(prt);
    pr.mult(mv );

    result.setPlanes(pr);
}
Пример #18
0
void Sculpture::addTrianglesToZbuffer(vector<Triangle>& triangles, Zbuffer& zBuff, ImageData& imgData) {
    for(int i = 0; i < triangles.size(); ++i) {
        for (int j = 0 ; j < 3 ; ++j) {
            double x = (triangles[i].p)[j][0], y = (triangles[i].p)[j][1], z = (triangles[i].p)[j][2];
            getProjection(x, y, z, imgData.P);
            if (x >= imgData.image.cols || x < 0 || y >= imgData.image.rows || y < 0 || pointOffSilhouette(imgData.silhouette, x, y)) {
                continue;
            }
            Vec3f voxel((triangles[i].p)[j][0],(triangles[i].p)[j][1],(triangles[i].p)[j][2]);
            zBuff.addVertex(x, y, voxel, imgData.rt);
        }
    }
}
Пример #19
0
/*! Calculate the frustum of this camera's visible area (w,h instead port). 
*/
void Camera::getFrustum(FrustumVolume& result, 
                        UInt32  width, UInt32  height)
{
    Matrix mv,prt,pr;
    
    getProjection           (pr , width, height);
    getProjectionTranslation(prt, width, height);
    getViewing              (mv , width, height);

    pr.mult(prt);
    pr.mult(mv );
    
    result.setPlanes(pr);
}
Пример #20
0
bool CMapRmap::setProjection(const QString& projection, const QString& datum)
{

    QString projstr;
    if(projection.startsWith("0,UTM"))
    {
        QStringList vals    = projection.split(",");
        int  zone           = vals[2].toInt();
        bool isSouth        = vals[3] != "N";

        projstr += QString("+proj=utm +zone=%1 %2").arg(zone).arg(isSouth ? "+south" : "");

    }
    if(projection.startsWith("1,"))
    {
        projstr += "+proj=longlat";
    }
    else if(projection.startsWith("2,"))
    {
        projstr += "+proj=merc";
    }
    else if(projection.startsWith("114,"))
    {
        projstr += "+proj=tmerc +lat_0=0 +lon_0=12 +k=1 +x_0=4500000 +y_0=0";
    }
    else if(projection.startsWith("117,"))
    {
        projstr += "+proj=tmerc +lat_0=0 +lon_0=9  +k=1 +x_0=3500000 +y_0=0";
    }

    if(datum == "WGS 84")
    {
        projstr += " +datum=WGS84 +units=m +no_defs";
    }
    else if(datum  == "Potsdam Rauenberg DHDN")
    {
        projstr += " +ellps=bessel +towgs84=606,23,413,0,0,0,0 +units=m +no_defs";
    }

    pjsrc = pj_init_plus(projstr.toLatin1().data());
    if(pjsrc == 0)
    {
        return false;
    }
    oSRS.importFromProj4(getProjection());
    char * ptr = pj_get_def(pjsrc,0);
    qDebug() << "rmap:" << ptr;

    return true;
}
Пример #21
0
bool CollisionSystem::intersects(sf::VertexArray aBounds, sf::VertexArray bBounds)
{
    for(sf::Vector2f& axis : getAxes(aBounds))
    {
        sf::Vector2f proj1 = getProjection(aBounds, axis);
        sf::Vector2f proj2 = getProjection(bBounds, axis);
        
        //If they DON'T overlap, a separating axis was found! No collision!
        if(!(proj1.x < proj2.y && proj1.y > proj2.x))
            return false;
    }

    for(sf::Vector2f& axis : getAxes(bBounds))
    {
        sf::Vector2f proj1 = getProjection(aBounds, axis);
        sf::Vector2f proj2 = getProjection(bBounds, axis);
        
        //If they DON'T overlap, a separating axis was found! No collision!
        if(!(proj1.x < proj2.y && proj1.y > proj2.x))
            return false;
    }
    
    return true;
}
Пример #22
0
template <typename PointNT> void
pcl::GridProjection<PointNT>::storeVectAndSurfacePoint (int index_1d,
                                                        const Eigen::Vector3i &index_3d,
                                                        std::vector <int> &pt_union_indices,
                                                        const Leaf &cell_data)
{
  // Get point on grid
  Eigen::Vector4f grid_pt (cell_data.pt_on_surface.x () - leaf_size_ / 2.0,
                           cell_data.pt_on_surface.y () + leaf_size_ / 2.0,
                           cell_data.pt_on_surface.z () + leaf_size_ / 2.0, 0);

  // Save the vector and the point on the surface
  getVectorAtPoint (grid_pt, pt_union_indices, cell_hash_map_[index_1d].vect_at_grid_pt);
  getProjection (cell_data.pt_on_surface, pt_union_indices, cell_hash_map_[index_1d].pt_on_surface);
}
Пример #23
0
void Game::Draw3dLab()
{
	db3D.clear();
	db3D.setBgColor(WHITE);
	db3D.setTxtColor(BLACK);
	db3DP.clear();
	db3DP.setBgColor(WHITE);
	db3DP.setTxtColor(BLACK);

	int wall_num = 0, middle_wall_type=0;
	int leftWalls[8], rightWalls[8];
	pixel tmpPx = {0,0,0};
	getProjection(middle_wall_type,wall_num, leftWalls, rightWalls);
	drawEdge(0, &db3D);
	drawEdge(0, &db3DP);
	for (int i = 0; i < wall_num; i++) {
		if (leftWalls[i] == BLOCK_EMPTY){
			if (leftWalls[i + 1]!=BLOCK_EMPTY){
			fillWall(i + 1, true, Game::block_types[leftWalls[i + 1]], &db3D);
			drawTopEdge(i + 1, true, &db3D);
			drawBottomEdge(i + 1, true, &db3D);
			}
		}
		else {
			fillWall(i + 1, false, Game::block_types[leftWalls[i]], &db3D);
			drawTopEdge(i+1, false, &db3D);
			drawBottomEdge(i+1, false, &db3D);
		}
		drawEdge(i+1, &db3D);

		if (rightWalls[i] == BLOCK_EMPTY) {
			if (rightWalls[i + 1]!=BLOCK_EMPTY){
			fillWall(i + 1, true, Game::block_types[rightWalls[i + 1]], &db3DP);
			drawTopEdge(i + 1, true, &db3DP);
			drawBottomEdge(i + 1, true, &db3DP);
			}
		}
		else {
			fillWall(i + 1, false, Game::block_types[rightWalls[i]], &db3DP);
			drawTopEdge(i + 1, false, &db3DP);
			drawBottomEdge(i + 1, false, &db3DP);
		}
		drawEdge(i + 1, &db3DP);
	}
    db3DP.flip();
	db3D.paintFrom(db3DP);
	drawFrontWall(wall_num, middle_wall_type);
}
Пример #24
0
void GLView::updateDesignResolutionSize()
{
    if (_screenSize.width > 0 && _screenSize.height > 0
        && _designResolutionSize.width > 0 && _designResolutionSize.height > 0)
    {
        _scaleX = (float)_screenSize.width / _designResolutionSize.width;
        _scaleY = (float)_screenSize.height / _designResolutionSize.height;
        
        if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
        {
            _scaleX = _scaleY = MAX(_scaleX, _scaleY);
        }
        
        else if (_resolutionPolicy == ResolutionPolicy::SHOW_ALL)
        {
            _scaleX = _scaleY = MIN(_scaleX, _scaleY);
        }
        
        else if ( _resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
            _scaleX = _scaleY;
            _designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
        }
        
        else if ( _resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
            _scaleY = _scaleX;
            _designResolutionSize.height = ceilf(_screenSize.height/_scaleY);
        }
        
        // calculate the rect of viewport
        float viewPortW = _designResolutionSize.width * _scaleX;
        float viewPortH = _designResolutionSize.height * _scaleY;
        
        _viewPortRect.setRect((_screenSize.width - viewPortW) / 2, (_screenSize.height - viewPortH) / 2, viewPortW, viewPortH);


        // reset director's member variables to fit visible rect
        auto director = Director::getInstance();
        director->_winSizeInPoints = getDesignResolutionSize();
        director->_isStatusLabelUpdated = true;
        director->setProjection(director->getProjection());

        // Github issue #16139
        // A default viewport is needed in order to display the FPS,
        // since the FPS are rendered in the Director, and there is no viewport there.
        // Everything, including the FPS should renderer in the Scene.
        glViewport(0, 0, _screenSize.width, _screenSize.height);
    }
}
Пример #25
0
void JitterSample::run(const render::RenderContextPointer& renderContext) {
    auto& current = _sampleSequence.currentIndex;
    if (!_freeze) {
        if (current >= 0) {
            current = (current + 1) % SEQUENCE_LENGTH;
        } else {
            current = -1;
        }
    }
    auto args = renderContext->args;
    auto viewFrustum = args->getViewFrustum();

    auto jit = _sampleSequence.offsets[(current < 0 ? SEQUENCE_LENGTH : current)];
    auto width = (float)args->_viewport.z;
    auto height = (float)args->_viewport.w;

    auto jx = 2.0f * jit.x / width;
    auto jy = 2.0f * jit.y / height;

    if (!args->isStereo()) {
        auto projMat = viewFrustum.getProjection();

        projMat[2][0] += jx;
        projMat[2][1] += jy;

        viewFrustum.setProjection(projMat);
        viewFrustum.calculate();
        args->pushViewFrustum(viewFrustum);
    } else {
        mat4 projMats[2];
        args->_context->getStereoProjections(projMats);

        jx *= 2.0f;

        for (int i = 0; i < 2; i++) {
            auto& projMat = projMats[i];
            projMat[2][0] += jx;
            projMat[2][1] += jy;
        }

        args->_context->setStereoProjections(projMats);
    }
}
Пример #26
0
Vector2 Camera::worldToScreenPoint(const Vector3& worldPos)
{
	Vector3 eyeSpace = getView() * worldPos;

	Vector2 res;

	if (eyeSpace.z_ < 0.0f)
	{
		Vector3 screenSpace = getProjection() * eyeSpace;
		res.x_ = screenSpace.x_;
		res.y_ = screenSpace.y_;
	}
	else
		res = Vector2();

	res.x_ = (res.x_ * 0.5f) + 0.5f;
	res.y_ = 1.0f - ((res.y_ * 0.5f) + 0.5f);

	return res;
}
Пример #27
0
void GLView::updateDesignResolutionSize()
{
    if (_screenSize.width > 0 && _screenSize.height > 0
        && _designResolutionSize.width > 0 && _designResolutionSize.height > 0)
    {
        _scaleX = (float)_screenSize.width / _designResolutionSize.width;
        _scaleY = (float)_screenSize.height / _designResolutionSize.height;
        
        if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
        {
            _scaleX = _scaleY = MAX(_scaleX, _scaleY);
        }
        
        else if (_resolutionPolicy == ResolutionPolicy::SHOW_ALL)
        {
            _scaleX = _scaleY = MIN(_scaleX, _scaleY);
        }
        
        else if ( _resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
            _scaleX = _scaleY;
            _designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
        }
        
        else if ( _resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
            _scaleY = _scaleX;
            _designResolutionSize.height = ceilf(_screenSize.height/_scaleY);
        }
        
        // calculate the rect of viewport
        float viewPortW = _designResolutionSize.width * _scaleX;
        float viewPortH = _designResolutionSize.height * _scaleY;
        
        _viewPortRect.setRect((_screenSize.width - viewPortW) / 2, (_screenSize.height - viewPortH) / 2, viewPortW, viewPortH);
        
        // reset director's member variables to fit visible rect
        auto director = Director::getInstance();
        director->_winSizeInPoints = getDesignResolutionSize();
        director->_isStatusLabelUpdated = true;
        director->setProjection(director->getProjection());
    }
}
Пример #28
0
void Sculpture::addColorToTrianglesWithZbufferAndImage(vector<Triangle>& triangles, Zbuffer& zBuff, ImageData& imgData) {
    for(int i = 0; i < triangles.size(); ++i) {
        for (int j = 0 ; j < 3 ; ++j) {
            double x = (triangles[i].p)[j][0], y = (triangles[i].p)[j][1], z = (triangles[i].p)[j][2];
            getProjection(x, y, z, imgData.P);
            if (x >= imgData.image.cols || x < 0 || y >= imgData.image.rows || y < 0 || pointOffSilhouette(imgData.silhouette, x, y)) {
                continue;
            }
            float ownZ =    (triangles[i].p)[j][0] * imgData.rt.at<float>(2,0) +
                            (triangles[i].p)[j][1] * imgData.rt.at<float>(2,1) +
                            (triangles[i].p)[j][2] * imgData.rt.at<float>(2,2) +
                            1                      * imgData.rt.at<float>(2,3);
            float bufferZ = zBuff.getVertex(x, y);
            if (abs(bufferZ - ownZ) < zThresh * abs(bufferZ)) {
                Vec4i color = imgData.image.at<Vec4b>(y,x);
                (triangles[i].color)[j] += color;
                ++(triangles[i].cameras)[j];
            }
        }
    }
}
Пример #29
0
void Scene::spotLightPass(RenderTarget * target)
{
    if(!this->spotLights.empty ())
    {
        for(int i =0;i<spotLights.size ();i++)
        {
            PointLight * light = this->spotLights[i];
            light->shadowFBO ()->BindForReading(GL_TEXTURE3);
            ShaderProgram * shader = ShaderPool::getInstance ()->get("spot_light_pass");
            shader->use ();
            light->shadowFBO ()->applyShadowMapTexture (shader,3);

            light->apply (shader,0);
            m_quad->setShaderProgram (shader);
            QMatrix4x4 m;
            m.setToIdentity ();
            auto camera = target->camera ();
            shader->setUniformMat4v ("g_MVP_matrix",m.data ());
            shader->setUniform2Float ("g_screen_size",1024,768);
            shader->setUniformInteger ("g_color_map",0);
            shader->setUniformInteger ("g_position_map",1);
            shader->setUniformInteger ("g_normal_map",2);
            shader->setUniform3Float ("g_eye_position",
                                      camera->pos ().x(),
                                      camera->pos ().y(),
                                      camera->pos ().z());
            QMatrix4x4 lightView;
            lightView.setToIdentity();
            lightView.lookAt(spotLights[0]->getPos(),this->spotLights[0]->getPos()+this->spotLights[0]->getDirection(),QVector3D(0,1,0));
            QMatrix4x4 light_vp;
            light_vp = camera->getProjection () * lightView ;
            shader->setUniformMat4v ("g_light_vp_matrix",light_vp.data ());
            m_quad->draw (true);
        }
    }
}
bool parallelPlanning(bool output, enum SPACE_TYPE space, std::vector<enum PLANNER_TYPE> &planners, unsigned int links,
                      unsigned int chains, struct ConstrainedOptions &c_opt, struct AtlasOptions &a_opt, bool bench)
{
    // Create a shared pointer to our constraint.
    auto constraint = std::make_shared<ParallelConstraint>(links, chains);

    ConstrainedProblem cp(space, constraint->createSpace(), constraint);
    cp.setConstrainedOptions(c_opt);
    cp.setAtlasOptions(a_opt);

    cp.css->registerProjection("parallel", constraint->getProjection(cp.css));

    Eigen::VectorXd start, goal;
    constraint->getStart(start);
    constraint->getGoal(goal);

    cp.setStartAndGoalStates(start, goal);
    cp.ss->setStateValidityChecker(std::bind(&ParallelConstraint::isValid, constraint, std::placeholders::_1));

    if (!bench)
        return parallelPlanningOnce(cp, planners[0], output);
    else
        return parallelPlanningBench(cp, planners);
}