Пример #1
0
int halfPlane(vector<line> l, vector<point> &poly) { //l:anti-clockwise
    int n = sz(l);
    sort(l.begin(), l.end());
    int first, last;
    q[first = last = 0] = l[0];
    for (int i = 1; i < n; i++) {
        while (first < last && !onLeft(l[i], p[last - 1])) last--;
        while (first < last && !onLeft(l[i], p[first])) first++;
        q[++last] = l[i];
        if (sgn(q[last].v * q[last - 1].v) == 0) {
            last--;
            if (onLeft(q[last], l[i].p)) q[last] = l[i];
        }
        if (first < last) p[last - 1] = getIntersection(q[last - 1], q[last]);
    } 
    while (first < last && !onLeft(q[first], p[last - 1])) last--;
    
    poly.clear();
    if (last - first <= 1) return 0;
    p[last] = getIntersection(q[last], q[first]);
    int m = 0; 
    for (int i = first; i <= last; i++) {
        poly.push_back(p[i]);
        m++;
    }
    return m;
}
Пример #2
0
bool G_segment::inRect(const QRect &r) const
{
  if(p1.getX() < r.right() && p1.getX() > r.left() &&
     p1.getY() < r.bottom() && p1.getY() > r.top()) return true;

  if(p2.getX() < r.right() && p2.getX() > r.left() &&
     p2.getY() < r.bottom() && p2.getY() > r.top()) return true;

  if(p1.getX() < r.left() && p2.getX() < r.left()) return false;
  if(p1.getX() > r.right() && p2.getX() > r.right()) return false;

  if(p1.getY() < r.top() && p2.getY() < r.top()) return false;
  if(p1.getY() > r.bottom() && p2.getY() > r.bottom()) return false;

  //the following could be optimized
  G_segment tmp;

  tmp = G_segment(r.topLeft(), r.bottomLeft());
  if(getIntersection(&tmp).isValid()) return true;

  tmp = G_segment(r.topRight(), r.bottomRight());
  if(getIntersection(&tmp).isValid()) return true;

  tmp = G_segment(r.bottomLeft(), r.bottomRight());
  if(getIntersection(&tmp).isValid()) return true;

  tmp = G_segment(r.topRight(), r.topLeft());
  if(getIntersection(&tmp).isValid()) return true;

  return false;
}
Пример #3
0
double Scene::getBrightness(Vec3f UL,Vec3f UR,Vec3f DR,Vec3f DL,Vec3f& p) const{
    Vec3f a,b,c;
    Material d;
    bool ul = getIntersection(Line(p,UL - p),a,b,c,d,Len(UL - p)- EPS);
    bool ur = getIntersection(Line(p,UR - p),a,b,c,d,Len(UR - p)- EPS);
    bool dr = getIntersection(Line(p,DR - p),a,b,c,d,Len(DR - p)- EPS);
    bool dl = getIntersection(Line(p,DL - p),a,b,c,d,Len(DL - p)- EPS);
    if (ul && ur && dr && dl)
        return 0;
    if (!(ul || ur || dr || dl))
        return 1;
    if ((UL - DR).Len() < dxy * 2.5)
        return 0.5;
    Vec3f M = (UL + DR) * 0.5;
    Vec3f U = (UL + UR) * 0.5;
    Vec3f D = (DL + DR) * 0.5;
    Vec3f R = (DR + UR) * 0.5;
    Vec3f L = (UL + DL) * 0.5;
    return 0.25 * (
                getBrightness(UL,U,M,L,p) +
                getBrightness(U,UR,R,M,p) +
                getBrightness(M,R,DR,D,p) +
                getBrightness(L,M,D,DL,p)
                );
}
bool FBUpdateNonSplit::preRotateExtDisplay(hwc_context_t *ctx,
                                            hwc_layer_1_t *layer,
                                            ovutils::Whf &info,
                                            hwc_rect_t& sourceCrop,
                                            ovutils::eMdpFlags& mdpFlags,
                                            int& rotFlags)
{
    int extOrient = getExtOrientation(ctx);
    ovutils::eTransform orient = static_cast<ovutils::eTransform >(extOrient);
    if(mDpy && (extOrient & HWC_TRANSFORM_ROT_90)) {
        mRot = ctx->mRotMgr->getNext();
        if(mRot == NULL) return false;
        ctx->mLayerRotMap[mDpy]->add(layer, mRot);
        // Composed FB content will have black bars, if the viewFrame of the
        // external is different from {0, 0, fbWidth, fbHeight}, so intersect
        // viewFrame with sourceCrop to avoid those black bars
        sourceCrop = getIntersection(sourceCrop, ctx->mViewFrame[mDpy]);
        //Configure rotator for pre-rotation
        if(configRotator(mRot, info, sourceCrop, mdpFlags, orient, 0) < 0) {
            ALOGE("%s: configRotator Failed!", __FUNCTION__);
            mRot = NULL;
            return false;
        }
        info.format = (mRot)->getDstFormat();
        updateSource(orient, info, sourceCrop);
        rotFlags |= ovutils::ROT_PREROTATED;
    }
    return true;
}
Пример #5
0
void Rec_Kin()
{
	double X[3]={1,0,430-370};
	getIntersection(X);
	Point2theta(X,Theta);
	catch_data.angle_B = Theta[0];
	catch_data.angle_A = Theta[1];
	pos_speed.pos_A = 180*catch_data.angle_A * MULTIPLY_A / pi / 360;
	pos_speed.pos_B = 180*catch_data.angle_B * MULTIPLY_B / pi / 360;
	//pos_speed.pos_C = 180*catch_data.angle_C * MULTIPLY_C / pi / 360;
}
Пример #6
0
void SightLightScene::onTouchMoved(cocos2d::Touch *touch,cocos2d::Event* event)
{
    Point tar(0,0); //光线的端点
    Point cur(0,0); //光线与线段的交点
    float distance = 0; //光源与交点的距离
    
    _touchDraw->clear();
    auto pos = touch->getLocation();
    //_touchDraw->drawDot(pos,5,Color4F::RED);
    
    //计算极角,并添加两个偏移1e-4的极角
    initAngles(pos);
    
    //极角排序
    std::sort(_angles.begin(), _angles.end(), [](float x,float y){
              return x < y;
              });
    
    std::vector<cocos2d::Vec2> vertex;
    //找最近的交点
//    std::vector<Point> vertex;
    for (auto angle:_angles) {
        Vec2 dlt(cos(angle),sin(angle));
        float closest = -1;
        for (auto s:_segments) {
            if (getIntersection(Line(pos,pos + dlt),s,cur,distance)) {
                if (closest == -1 || closest > distance) {
                    closest = distance;
                    tar = cur;
                }
            }
        }
        if (closest != -1) {
            vertex.push_back(tar);
        }
    }

    //画三角形
    //下面2个循环第3个参数可以写为vertex[(i+1) % vertex.size()],合并成1个循环
    //但是显然,取余操作效率太低,分开写更好一些
    int limit = vertex.size() - 1;
    for (int i = 0; i < limit; i++) {
        _touchDraw->drawTriangle(pos, vertex[i], vertex[i + 1], Color4F::WHITE);
    }
    if(limit > 0) {
        _touchDraw->drawTriangle(pos, vertex[limit], vertex[0], Color4F::WHITE);
    }
    
//   画三角形的边,Debug用
//    for(auto v : vertex) {
//        _touchDraw->drawSegment(pos, v, 0.5f, Color4F::RED);
//        _touchDraw->drawDot(v, 3, Color4F::RED);
//    }
}
Пример #7
0
double Scene::getBrightness(int U,int D,int L,int R,Vec3f& p,bools& Done,bools& Reach) const{
   // qDebug() << U << D << L << R;
    Vec3f a,b,c;
    Material d;
    Vec3f UL = _Light[U][L] - p;
    Vec3f UR = _Light[U][R] - p;
    Vec3f DL = _Light[D][L] - p;
    Vec3f DR = _Light[D][R] - p;
    bool ul = Done[U][L]?Reach[U][L]:getIntersection(Line(p,UL),a,b,c,d,Len(UL)- EPS);
    if (!Done[U][L]){
        Reach[U][L] = ul;
        Done[U][L] = true;
    }
    bool ur = Done[U][R]?Reach[U][R]:getIntersection(Line(p,UR),a,b,c,d,Len(UR)- EPS);
    if (!Done[U][R]){
        Reach[U][R] = ur;
        Done[U][R] = true;
    }
    bool dl = Done[D][L]?Reach[D][L]:getIntersection(Line(p,DL),a,b,c,d,Len(DL)- EPS);
    if (!Done[D][L]){
        Reach[D][L] = dl;
        Done[D][L] = true;
    }
    bool dr = Done[D][R]?Reach[D][R]:getIntersection(Line(p,DR),a,b,c,d,Len(DR)- EPS);
    if (!Done[D][R]){
        Reach[D][R] = dr;
        Done[D][R] = true;
    }
    if (ul && ur && dr && dl)
        return 0;
    if (!(ul || ur || dr || dl))
        return 1;
    if (D <= U + 1)
        return 0.5;
    return 0.25*(
                getBrightness(U,(U + D)/2,L,(L + R)/2,p,Done,Reach) +
                getBrightness((U + D)/2,D,(L + R)/2,R,p,Done,Reach) +
                getBrightness(U,(U + D)/2,(L + R)/2,R,p,Done,Reach) +
                getBrightness((U + D)/2,D,L,(L + R)/2,p,Done,Reach)
                );
}
Пример #8
0
Manifold::GeodesicPtr Manifold::Portal::teleport(Manifold::GeodesicPtr geodesic) {
	assert(exit);
	//std::cout << "Manifold.cpp teleport from " << getSpace()->getType() << std::endl;
	IntersectionPtr intersection = getIntersection(geodesic);
	if(rotate) {
		intersection->rotate(rotation);
	}
	if(invert ^ exit->getInvert()) {
		intersection->invert();
	}
	return exit->getGeodesic(intersection);
}
Пример #9
0
void Map::computeStreets()
{
	Point first, second;
	for (std::map<int, Node>::iterator it = this->nodes.begin(); it != this->nodes.end(); ++it)
	{

		Node currentNode = (*it).second;
		std::vector<int> destinations = currentNode.getDestinations();
		Street newStreet;
		for (int i = 0; i < destinations.size(); i++)
		{
			getIntersection(currentNode, nodes[destinations[i]], first, second);
			newStreet.corners[0] = first;
			newStreet.corners[1] = second;
			getIntersection(nodes[destinations[i]], currentNode, first, second);
			newStreet.corners[2] = second;
			newStreet.corners[3] = first;
			it->second.addStreet(newStreet);
		}
	}
}
void MaskFrame::findGhostPointIfCloseTo(int absoluteX, int absoluteY){
    int maskFrameX = absoluteX - this->getX();
    int maskFrameY = absoluteY - this->getY();
    this->hasAGhostPoint = false;
    for(int i = 0; i < maskPoints.size(); i++){
        int nextIndex = getNextIndex(i, maskPoints.size());
        this->hasAGhostPoint = getIntersection(maskFrameX, maskFrameY, maskPoints[i], maskPoints[nextIndex], &ghostPoint);
        if(this->hasAGhostPoint){
            ghostPointIndex = nextIndex;
            transposeToLiveCanvas();
            break;
        }
    }
}
LandsideVehicleInSim* LandsideIntersectLaneLinkInSim::CheckPathConflict( LandsideVehicleInSim* pVeh, const CPath2008& path,DistanceUnit& minDist )
{
	LandsideVehicleInSim* pConflict = NULL;

	LandsideIntersectionInSim* pIntersection = getIntersection();
	if(pIntersection)
	{
		for(int i=0;i<pIntersection->GetLinkageCount();i++)
		{
			LandsideIntersectLaneLinkInSim* pOtherLink = pIntersection->GetLinkage(i);
			if(pOtherLink==this)
				continue;

			for(int iV = 0; iV < pOtherLink->GetInResVehicleCount();iV++)
			{
				LandsideVehicleInSim* pOtherV = pOtherLink->GetInResVehicle(iV);
				if(pOtherV == pVeh )
					continue;

				if( !pVeh->bCanWaitFor(pOtherV) )
					continue;

				IntersectPathPath2D intersect;
				double dWidth = (pVeh->GetWidth()+pOtherV->GetWidth())*0.5;
				if(intersect.Intersects(path, pOtherV->getSpanPath(),dWidth)>0)
				{
					double dIntserctIndex = intersect.m_vIntersectPtIndexInPath1.front();
					double dOtherInterIndex = intersect.m_vIntersectPtIndexInPath2.front();

					double dist = path.GetIndexDist(dIntserctIndex);
					double dOtherDist = path.GetIndexDist(dOtherInterIndex);
					if(dist < dOtherDist)
						continue;

					if(!pConflict)
					{
						minDist = dist;
						pConflict = pOtherV;
					}
					else if(minDist > dist)
					{
						minDist = dist;
						pConflict = pOtherV;						
					}					
				}
			}
		}
	}		
	return pConflict;
}
Пример #12
0
node<T>* getIntersection(node<T>* a, node<T> * b)
{
    if ( !a->next && !b->next )
        return (a == b ? a : NULL);
    
    //lists should be the same size.
    if ( !a->next )
        return getIntersection(a, b->next);
    
    if ( !b->next )
        return getIntersection(a->next, b);
    
    node<T> *i = getIntersection(a->next, b->next);
    
    if ( !i ) return NULL;
    
    //are the lists still intersected?
    if ( a == b )
        return a;
    
    //return the last intersection;
    return i;
}
Пример #13
0
double getArea(const Point &a, const Point &b, const double &r) {
	double dA = dot(a, a), dB = dot(b, b), dC = getPointDist(a, b), ans = 0.0;
	if (dcmp(dA - r * r) <= 0 && dcmp(dB - r * r) <= 0) return det(a, b) / 2.0;
	Point tA = a / dist(a) * r;
	Point tB = b / dist(b) * r;
	if (dcmp(dC - r) > 0) return getSectorArea(tA, tB, r);
	std::pair<Point, Point> ret = getIntersection(a, b, r);
	if (dcmp(dA - r * r) > 0 && dcmp(dB - r * r) > 0) {
		ans += getSectorArea(tA, ret.first, r);
		ans += det(ret.first, ret.second) / 2.0;
		ans += getSectorArea(ret.second, tB, r);
		return ans;
	}
	if (dcmp(dA - r * r) > 0) return det(ret.first, b) / 2.0 + getSectorArea(tA, ret.first, r);
	else return det(a, ret.second) / 2.0 + getSectorArea(ret.second, tB, r);
}
Пример #14
0
// Descr: evident
TEST(GeometryTest, GetIntersection)
{
    vector<unsigned long> section1, section2;

    section1.push_back(1);
    section1.push_back(2);
    section1.push_back(3);
    section1.push_back(4);

    section2.push_back(2);
    section2.push_back(4);
    section2.push_back(6);
    section2.push_back(8);

    vector<unsigned long> intersection = getIntersection(section1, section2);

	EXPECT_TRUE(intersection[0] == 2 && intersection[1] == 4 && intersection.size() == 2);
}
Пример #15
0
bool BoundingBox::intersect(const Vec3f &segStart, const Vec3f &segEnd) const {
  if (!isValid())
    return false;

  if (segEnd[0] < (*this)[0][0] && segStart[0] < (*this)[0][0])
    return false;

  if (segEnd[0] > (*this)[1][0] && segStart[0] > (*this)[1][0])
    return false;

  if (segEnd[1] < (*this)[0][1] && segStart[1] < (*this)[0][1])
    return false;

  if (segEnd[1] > (*this)[1][1] && segStart[1] > (*this)[1][1])
    return false;

  if (segEnd[2] < (*this)[0][2] && segStart[2] < (*this)[0][2])
    return false;

  if (segEnd[2] > (*this)[1][2] && segStart[2] > (*this)[1][2])
    return false;

  if (segStart[0] > (*this)[0][0] && segStart[0] < (*this)[1][0] && segStart[1] > (*this)[0][1] &&
      segStart[1] < (*this)[1][1] && segStart[2] > (*this)[0][2] && segStart[2] < (*this)[1][2])
    return true;

  Vec3f hit;

  if ((getIntersection(segStart[0] - (*this)[0][0], segEnd[0] - (*this)[0][0], segStart, segEnd,
                       hit) &&
       contains(hit)) ||
      (getIntersection(segStart[1] - (*this)[0][1], segEnd[1] - (*this)[0][1], segStart, segEnd,
                       hit) &&
       contains(hit)) ||
      (getIntersection(segStart[2] - (*this)[0][2], segEnd[2] - (*this)[0][2], segStart, segEnd,
                       hit) &&
       contains(hit)) ||
      (getIntersection(segStart[0] - (*this)[1][0], segEnd[0] - (*this)[1][0], segStart, segEnd,
                       hit) &&
       contains(hit)) ||
      (getIntersection(segStart[1] - (*this)[1][1], segEnd[1] - (*this)[1][1], segStart, segEnd,
                       hit) &&
       contains(hit)) ||
      (getIntersection(segStart[2] - (*this)[1][2], segEnd[2] - (*this)[1][2], segStart, segEnd,
                       hit) &&
       contains(hit)))
    return true;

  return false;
}
Пример #16
0
int main(int argc, char** argv)
{
  // Check arguments
  if (argc != 3)
  {
    printf("Usage: %s <File> <File>\n", argv[0]);
    return -1;
  }

  // Load files
  StringArray* firstArray = createArrayFromFile(argv[1]);
  if (!firstArray)
    return -1;

  StringArray* secondArray = createArrayFromFile(argv[2]);
  if (!secondArray)
  {
    freeArray(firstArray, true);
    return -1;
  }

  // Compute intersection
  StringArray* intersection = getIntersection(firstArray, secondArray);
  if (!intersection)
  {
    printf("An error has occured while computing the files' intersection: \n");
    printf("- %s\n", argv[1]);
    printf("- %s\n", argv[2]);
    freeArray(firstArray, true);
    freeArray(secondArray, true);
    return 3;
  }

  printArray(intersection);

  // Free memory
  freeArray(firstArray, true);
  freeArray(secondArray, true);
  freeArray(intersection, false);

  return 0;
}
Пример #17
0
//this is the main function
int main(int argc,char **argv)
{

    FILE *intersectIPstream;
    Hash *mp1,*mp2;
    mp1=parseFileDataStream(INPUTSTREAM1);
    mp2=parseFileDataStream(INPUTSTREAM2);
    if(!mp1||!mp2)
    {
        perror("either of the file is not read properly");
        return -1;
    }
    intersectIPstream=getIntersection(mp1,mp2);
    hashDestroy(mp1);
    hashDestroy(mp2);
    mp1=mp2=NULL;
    fclose(intersectIPstream);

    return  0;
}
Пример #18
0
void testGetIntersection()
{
    cout<<"Testing GetIntersection"<<endl;
    vector<unsigned long> section1, section2;

    section1.push_back(1);
    section1.push_back(2);
    section1.push_back(3);
    section1.push_back(4);

    section2.push_back(2);
    section2.push_back(4);
    section2.push_back(6);
    section2.push_back(8);

    vector<unsigned long> intersection = getIntersection(section1, section2);

    assert(intersection[0] == 2 && intersection[1] == 4 && intersection.size() == 2);

    cout<<"Testing GetIntersection Completed\n"<<endl;
}
Пример #19
0
bool BoundingBox::isIn(float x1, float y1, float z1, float x2, float y2, float z2) const {
	if (_empty)
		return false;

	float minX, minY, minZ;
	getMin(minX, minY, minZ);

	float maxX, maxY, maxZ;
	getMax(maxX, maxY, maxZ);

	if ((x2 < minX) && (x1 < minX)) return false;
	if ((x2 > maxX) && (x1 > maxX)) return false;
	if ((y2 < minY) && (y1 < minY)) return false;
	if ((y2 > maxY) && (y1 > maxY)) return false;
	if ((z2 < minZ) && (z1 < minZ)) return false;
	if ((z2 > maxZ) && (z1 > maxZ)) return false;

	if ((x1 > minX) && (x1 < maxX) &&
	    (y1 > minY) && (y1 < maxY) &&
	    (z1 > minZ) && (z1 < maxZ))
		return true;

	float x, y, z;

	if (getIntersection(x1 - minX, x2 - minX, x1, y1, z1, x2, y2, z2, x, y, z) &&
	    inBox(x, y, z, minX, minY, minZ, maxX, maxY, maxZ, 1))
		return true;
	if (getIntersection(y1 - minY, y2 - minY, x1, y1, z1, x2, y2, z2, x, y, z) &&
	    inBox(x, y, z, minX, minY, minZ, maxX, maxY, maxZ, 2))
		return true;
	if (getIntersection(z1 - minZ, z2 - minZ, x1, y1, z1, x2, y2, z2, x, y, z) &&
	    inBox(x, y, z, minX, minY, minZ, maxX, maxY, maxZ, 3))
		return true;
	if (getIntersection(x1 - maxX, x2 - maxX, x1, y1, z1, x2, y2, z2, x, y, z) &&
	    inBox(x, y, z, minX, minY, minZ, maxX, maxY, maxZ, 1))
		return true;
	if (getIntersection(y1 - maxY, y2 - maxY, x1, y1, z1, x2, y2, z2, x, y, z) &&
	    inBox(x, y, z, minX, minY, minZ, maxX, maxY, maxZ, 2))
		return true;
	if (getIntersection(z1 - maxZ, z2 - maxZ, x1, y1, z1, x2, y2, z2, x, y, z) &&
	    inBox(x, y, z, minX, minY, minZ, maxX, maxY, maxZ, 3))
		return true;

	return false;
}
Пример #20
0
const Displays::Display& Displays::findDisplayForRect (Rectangle<int> rect, bool isPhysical) const noexcept
{
    int maxArea = -1;
    Display* retVal = nullptr;

    for (auto& display : displays)
    {
        auto displayArea = display.totalArea;

        if (isPhysical)
            displayArea = (displayArea.withZeroOrigin() * display.scale) + display.topLeftPhysical;

        displayArea = displayArea.getIntersection (rect);
        auto area = displayArea.getWidth() * displayArea.getHeight();

        if (area >= maxArea)
        {
            maxArea = area;
            retVal = &display;
        }
    }

    return *retVal;
}
Пример #21
0
int main() {
    for (int amtToAdvance = 0; amtToAdvance < 9; ++amtToAdvance) {
        printf("amt to advance: %d\n", amtToAdvance);
        List l;
        for (int i = 0; i < 10; ++i) {
            l.add(i);
        }
        List otherList;
        for (int i = 0; i < 5; ++i) {
            otherList.add(i);
        }
        // Temporarily connect otherList to a node in l
        Node * nodeToConnectTo = l.head;
        for (int i = 0; i < amtToAdvance; ++i) {
            nodeToConnectTo = nodeToConnectTo->next;
        }
        otherList.tail->next = nodeToConnectTo;
        l.print();
        otherList.print();
        assert(getIntersection(l.head, otherList.head) == nodeToConnectTo);
        otherList.tail->next = nullptr;
    }
    return 0;
}
Пример #22
0
node<T>* getIntersectingNode(node<T>* a, node<T>* b)
{
    int length_a = 0;
    int length_b = 0;
    node<T>* tail_a = getTail(a, length_a);
    node<T>* tail_b = getTail(b, length_b);
    
    if ( tail_a != tail_b )
        return NULL;
    
    while ( length_a > length_b )
    {
        a = a->next;
        length_a--;
    }
    
    while ( length_b > length_a )
    {
        b = b->next;
        length_b--;
    }
    
    return getIntersection(a, b);
}
Пример #23
0
bool Ray::checkLineBox( hpvec3 boxPointMin, hpvec3 boxPointMax, hpvec3 linePoint1, hpvec3 linePoint2, hpvec3 &hitPoint) {
    if (linePoint2.x < boxPointMin.x && linePoint1.x < boxPointMin.x) return false;
    if (linePoint2.x > boxPointMax.x && linePoint1.x > boxPointMax.x) return false;
    if (linePoint2.y < boxPointMin.y && linePoint1.y < boxPointMin.y) return false;
    if (linePoint2.y > boxPointMax.y && linePoint1.y > boxPointMax.y) return false;
    if (linePoint2.z < boxPointMin.z && linePoint1.z < boxPointMin.z) return false;
    if (linePoint2.z > boxPointMax.z && linePoint1.z > boxPointMax.z) return false;
    if (linePoint1.x > boxPointMin.x && linePoint1.x < boxPointMax.x &&
        linePoint1.y > boxPointMin.y && linePoint1.y < boxPointMax.y &&
        linePoint1.z > boxPointMin.z && linePoint1.z < boxPointMax.z)
        {hitPoint = linePoint1;
        return true;}
    if ( (getIntersection( linePoint1.x-boxPointMin.x, linePoint2.x-boxPointMin.x, linePoint1, linePoint2, hitPoint) && inBox( hitPoint, boxPointMin, boxPointMax, 1 ))
      || (getIntersection( linePoint1.y-boxPointMin.y, linePoint2.y-boxPointMin.y, linePoint1, linePoint2, hitPoint) && inBox( hitPoint, boxPointMin, boxPointMax, 2 ))
      || (getIntersection( linePoint1.z-boxPointMin.z, linePoint2.z-boxPointMin.z, linePoint1, linePoint2, hitPoint) && inBox( hitPoint, boxPointMin, boxPointMax, 3 ))
      || (getIntersection( linePoint1.x-boxPointMax.x, linePoint2.x-boxPointMax.x, linePoint1, linePoint2, hitPoint) && inBox( hitPoint, boxPointMin, boxPointMax, 1 ))
      || (getIntersection( linePoint1.y-boxPointMax.y, linePoint2.y-boxPointMax.y, linePoint1, linePoint2, hitPoint) && inBox( hitPoint, boxPointMin, boxPointMax, 2 ))
      || (getIntersection( linePoint1.z-boxPointMax.z, linePoint2.z-boxPointMax.z, linePoint1, linePoint2, hitPoint) && inBox( hitPoint, boxPointMin, boxPointMax, 3 )))
        return true;

    return false;
}
Пример #24
0
vector<LPEdge> mergeBasesFast(double beta1, vector<LPEdge> base1, double beta2, vector<LPEdge> base2, mt19937 &rg)
{
	//vector<vector<int>> adjsB2 = makeAdjs(base2);
	list<int> *adjs = new list<int>[base2.size() + 1];
	makeAdjs(base2, adjs);
	uniform_real_distribution<double> distr(0.0f, 1.0f);
	/*for (int i = 0; i < base2.size() + 1; i++)
	{
		cout << "Adjacent to " << i << ": ";
		for (auto it = adjs[i].begin(); it != adjs[i].end(); it++)
			cout << *it << ", ";
		cout << endl;
	}*/
	while (!basesEqual(base1, base2))
	{
		//LPEdge i = setDifFast(base1, base2)[0];
		vector<LPEdge> AminB = setDifFast(base1, base2);
		LPEdge i = LPEdge(AminB.back().end0, AminB.back().end1, AminB.back().weight);
		//LPEdge i = getEltFromDif(base1, base2);
		vector<LPEdge> intersect = getIntersection(getSTPath(base2, i, adjs), getEdgesInCut(base1, i, base2));
		//cout << "There are " << intersect.size() << " items in the intersection." << endl;
		//if (intersect.size() != 1)
		//{
			//cout << "Error! Bug in swapRound. There are " << intersect.size() << " items in the intersection" << endl;
			//throw invalid_argument("");
		//}
		LPEdge j = LPEdge(intersect.back().end0, intersect.back().end1, intersect.back().weight);


		double prob = beta1 / (beta1 + beta2);
		//int r = rand() % 1001;
		//double dr = (double)r / (1000.0);
		double dr = distr(rg);
		//cout << "Prob: " << prob << endl;
		if (dr <= prob)
		{
			//cout << "DOING" << endl;
			removeEdge(base2, j);
			base2.push_back(i);
			bool founda = false;
			bool foundb = false;
			for (auto it = adjs[j.end0].begin(); it != adjs[j.end0].end(); it++)
			{
				if (*it == j.end1)
				{
					adjs[j.end0].erase(it);
					founda = true;
					break;
				}
			}
			for (auto it = adjs[j.end1].begin(); it != adjs[j.end1].end(); it++)
			{
				if (*it == j.end0)
				{
					adjs[j.end1].erase(it);
					foundb = true;
					break;
				}
			}
			if (!founda || !foundb)
				cout << "Warning; couldn't erase edge fully from adj list" << endl;
			adjs[i.end0].push_back(i.end1);
			adjs[i.end1].push_back(i.end0);
		}
		else
		{
			removeEdge(base1, i);
			base1.push_back(j);
		}
		//string dummy;
		//cin >> dummy;

	}
	delete[] adjs;
	return base1;
}
Пример #25
0
// Returns the (x, y) coordinate where the two lines intersect, or (NO_INTERSECTION, NO_INTERSECTION)
// if they do not intersect.  (since we are only concerned  about 
// intersections that appear on the screen, this will not be a problem)
const point<int> Utility::getIntersection(const VisualLine& line1,
					  const VisualLine& line2) {
  return getIntersection(line1.start, line1.end,
                         line2.start, line2.end);
}
Пример #26
0
/**
 * Update position the edge
 */
void GuiEdge::updatePosition (bool original_run)
{
	GuiNode* pre = addGui (pred());
	GuiNode* suc = addGui (succ());

	edge_start_point_priv = mapFromItem( pre, pre->width()/2, pre->height()/2);
    edge_end_point_priv = mapFromItem( suc, suc->width()/2, suc->height()/2);//!!!rarely it not work

	if (pre == suc)//mesh edge
	{
		QPointF heigh (0, 2*pre->height());

		QPointF middle (pre->pos().x() - 10, pre->pos().y() + pre->height()/2);
		QPointF middleDirUp = middle + heigh;
		QPointF middleDirDown = middle - heigh;

		edge_start_dir_priv = edge_start_point_priv + heigh;
		edge_end_dir_priv = edge_end_point_priv - heigh;

		QPolygonF polygon = suc->polygon();
		polygon.translate (suc->pos());
		getIntersection (QLineF (edge_start_point_priv, edge_start_dir_priv), polygon, &edge_start_point_priv);
		getIntersection (QLineF (edge_end_point_priv, edge_end_dir_priv), polygon, &edge_end_point_priv);

		QPainterPath path;
		path.moveTo (edge_start_point_priv);
		path.cubicTo (edge_start_dir_priv, middleDirUp, middle);
		path.cubicTo (middleDirDown, edge_end_dir_priv, edge_end_point_priv);
		edge_curve_priv = path;
	}
	else
	{
		edge_valid_priv = true;
		
		QPolygonF headPolygon = suc->polygon();
		headPolygon.translate (suc->pos());
		QPolygonF tailPolygon = pre->polygon();
		tailPolygon.translate (pre->pos());


		if (suc->real())
			edge_valid_priv = edge_valid_priv && getIntersection (QLineF (edge_start_point_priv, edge_end_point_priv), headPolygon, &edge_end_point_priv) == QLineF::BoundedIntersection;
		if (pre->real()) 
			edge_valid_priv = edge_valid_priv && getIntersection (QLineF (edge_start_point_priv, edge_end_point_priv), tailPolygon, &edge_start_point_priv) == QLineF::BoundedIntersection;

		QPointF delta = edge_start_point_priv - edge_end_point_priv;
		delta.setX(0);

		if (pre->real()) 
			edge_start_dir_priv = (edge_start_point_priv + edge_end_point_priv)/2;
		else
		{
			if (pre->firstPred() != 0)
				edge_start_dir_priv = (suc->coor() - pre->firstPred()->pred()->coor())/8 + pre->coor();
			else
				edge_start_dir_priv = edge_start_point_priv - delta/2;
		}

		if (suc->real())
			edge_end_dir_priv = (edge_start_point_priv + edge_end_point_priv)/2;
		else
			if (suc->firstSucc() != 0)
				edge_end_dir_priv = (pre->coor() - suc->firstSucc()->succ()->coor())/8 + suc->coor();
			else
				edge_end_dir_priv = edge_end_point_priv + delta/2;

		QPainterPath path;
		path.moveTo (edge_start_point_priv);
		path.cubicTo (edge_start_dir_priv, edge_end_dir_priv, edge_end_point_priv);

		if (edge_valid_priv) edge_curve_priv = path;
	}

    edge_top_left_priv.setX( min< qreal>( edge_start_point_priv.x(), edge_end_point_priv.x()));
    edge_top_left_priv.setY( min< qreal>( edge_start_point_priv.y(), edge_end_point_priv.y()));
    edge_bottom_right_priv.setX( max< qreal>( edge_start_point_priv.x(), edge_end_point_priv.x()));
    edge_bottom_right_priv.setY( max< qreal>( edge_start_point_priv.y(), edge_end_point_priv.y())); 

	if (original_run)
	{
		if (Edge::succ() && !addAux (Edge::succ())->real() && Edge::succ()->firstSucc())
			addGui (Edge::succ()->firstSucc())->updatePosition (false);//avoidance sharp corners
		
		if (Edge::pred() && !addAux (Edge::pred())->real() && Edge::pred()->firstPred())
			addGui (Edge::pred()->firstPred())->updatePosition (false);//avoidance sharp corners
		
		GuiEdge* i = this;
		for (i; !i->startEdge(); i->pred()->firstPred() && (i = addGui (i->pred()->firstPred())));
		i->updateLabels();
	}
    prepareGeometryChange();
}
Пример #27
0
Vector2D Line::getPointOnLineClosestTo( Vector2D pos ){
  Line l2 = getTangentLine( pos );  // get tangent line
  return getIntersection( l2 );     // and intersection between the two lines
}
Пример #28
0
Eigen::Vector4d getColor(const Ray &ray, unsigned int recursionLevel, unsigned int transDepth,
                         std::array<int, MAX_DEPTH + 1> &objStack) {
    BOOST_ASSERT_MSG(std::abs(1 - ray.dir.norm()) < EPSILON, "Got ray with non-unit direction");
    const intersection_t isect = getIntersection(ray);
    int objId;
    if ((objId = isect.objId) < 0) return Eigen::Vector4d::Zero();

    auto &objects = scene.getObjects();
    auto &lights = scene.getLights();
    Eigen::Vector4d I = Eigen::Vector4d::Zero();

    Eigen::Vector4d pointOfIntersection = ray.origin + isect.dist * ray.dir;

    Eigen::Vector4d N = objects[objId]->getUnitNormal(pointOfIntersection);
    Eigen::Vector4d V = -1 * ray.dir;

    auto mat = scene.getMaterial(objects[objId]->matId);

    for (unsigned int i = 0 ; i < lights.size(); ++i) {
        if (lights[i]->isAmbient()) {
            I += mat.Ka * lights[i]->getAmountOfLight(pointOfIntersection).cwiseProduct(mat.rgb);
            continue;
        }
        Eigen::Vector4d L = lights[i]->getVectorToLight(pointOfIntersection);
        Ray rayToLight(pointOfIntersection, L, objId);

        bool lightVisible = true;
        if (lights[i]->getShadowOn()) {
            double distToBlockingObject = getIntersection(rayToLight).dist;
            double distToLight = (pointOfIntersection - lights[i]->getPosition()).norm();

            lightVisible = distToBlockingObject <= EPSILON ||
                distToBlockingObject >= distToLight;
        }
        if (lightVisible) {
            /* Diffuse Reflection */
            Eigen::Vector4d Il = lights[i]->getAmountOfLight(pointOfIntersection);
            // Amount of light visible on surface determined by angle to light source
            double lambertCos = L.dot(N);
            if (lambertCos > 0) {
                I += mat.Kd * lambertCos * mat.rgb.cwiseProduct(Il);
            } else {
                continue;
            }

            /* Specular Reflection */
            Eigen::Vector4d reflection = 2 * N.dot(rayToLight.dir) * N - rayToLight.dir;
            double specCoeff = reflection.dot(V);
            if (specCoeff > 0) {
                specCoeff = std::max(0.0, pow(specCoeff, mat.ns));
                I += specCoeff * mat.Ks * mat.rgb.cwiseProduct(Il);
            }
        }
    }

    if (recursionLevel < MAX_DEPTH) {
        // Work out where in material stack we are
        int nextTransDepth;
        int nextObjId;
        if (objStack[transDepth] == objId) {
            nextTransDepth = transDepth - 1;
            nextObjId = objStack[transDepth - 1];
        } else {
            nextTransDepth = transDepth + 1;
            objStack[nextTransDepth] = objId;
            nextObjId = objId;
        }

        // Compute intensity of reflected ray, if necessary
        if (reflect && mat.Kr > 0)	{
            Ray reflectionRay(pointOfIntersection,  ray.dir - (2 * N.dot(ray.dir)) * N, nextObjId);
            I += mat.Kr * getColor(reflectionRay, recursionLevel + 1, nextTransDepth, objStack);
        }

        // Compute intensity of transmission ray, if necessary
        if (refract && mat.Kt > 0) {
            const double etaIncident = (objStack[transDepth] == ID_AIR) ? 1.0 :
                scene.getMaterial(objects[objStack[transDepth]]->matId).Irefract;
            double cosThetaI, etaRefract;
            if (objStack[transDepth] == objId) { // Exiting a material
                cosThetaI = ray.dir.dot(N);
                etaRefract = (objStack[transDepth - 1] == ID_AIR) ? 1.0 :
                    scene.getMaterial(objects[objStack[transDepth - 1]]->matId).Irefract;
            } else {
                cosThetaI = V.dot(N);
                etaRefract = scene.getMaterial(objects[objId]->matId).Irefract;
            }
            const double n = etaIncident/etaRefract;
            const double cosThetaR = sqrt(1 - (n * n) * (1 - cosThetaI * cosThetaI));
            Ray T(pointOfIntersection, (n * ray.dir - (cosThetaR - n * cosThetaI) * N).normalized(), nextObjId);
            I += mat.Kt * getColor(T, recursionLevel + 1, nextTransDepth, objStack);
        }
    }

    return I;

}
Пример #29
0
bool RS_Information::hasIntersection(RS_Entity* e1, RS_Entity* e2, bool onEntities)
{
  RS_VectorSolutions sol = getIntersection(e1, e2, onEntities);
  RS_Vector p = sol.get(0);
  return p.valid;
}
Пример #30
0
int SocketList::getIntersection(fd_set* set, SOCKET* buffer, int bufsiz) {
  getIntersection(set, buffer, &bufsiz);
  return bufsiz;
}