Ejemplo n.º 1
0
FX_BOOL CTextBaseLine::CanMerge(CTextBaseLine* pOther)
{
    FX_FLOAT inter_top, inter_bottom;
    if (!GetIntersection(m_Bottom, m_Top, pOther->m_Bottom, pOther->m_Top,
                         inter_bottom, inter_top)) {
        return FALSE;
    }
    FX_FLOAT inter_h = inter_top - inter_bottom;
    if (inter_h < (m_Top - m_Bottom) / 2 && inter_h < (pOther->m_Top - pOther->m_Bottom) / 2) {
        return FALSE;
    }
    FX_FLOAT dy = (FX_FLOAT)FXSYS_fabs(m_BaseLine - pOther->m_BaseLine);
    for (int i = 0; i < m_TextList.GetSize(); i ++) {
        CTextBox* pText = (CTextBox*)m_TextList.GetAt(i);
        for (int j = 0; j < pOther->m_TextList.GetSize(); j ++) {
            CTextBox* pOtherText = (CTextBox*)pOther->m_TextList.GetAt(j);
            FX_FLOAT inter_left, inter_right;
            if (!GetIntersection(pText->m_Left, pText->m_Right,
                                 pOtherText->m_Left, pOtherText->m_Right, inter_left, inter_right)) {
                continue;
            }
            FX_FLOAT inter_w = inter_right - inter_left;
            if (inter_w < pText->m_SpaceWidth / 2 && inter_w < pOtherText->m_SpaceWidth / 2) {
                continue;
            }
            if (dy >= (pText->m_Bottom - pText->m_Top) / 2 ||
                    dy >= (pOtherText->m_Bottom - pOtherText->m_Top) / 2) {
                return FALSE;
            }
        }
    }
    return TRUE;
}
Ejemplo n.º 2
0
void LineClipping_Clip(const struct LineClipping_Rectangle *r,
	struct LineClipping_Segment *s, 
	int *done)
{
	const int maxIter = 4;
	int outcode0, outcode1, i;
	double x, y;
	
	/*Cohen-Sutherland line clipping algorithm*/
	outcode0 = Outcode(s->x0, s->y0, r);
	outcode1 = Outcode(s->x1, s->y1, r);
	i = 0;
	while (! Inside(outcode0, outcode1) && ! SameSide(outcode0, outcode1) && (i < maxIter)) {
		if (outcode0 != 0) {
			GetIntersection(r, s, outcode0, &x, &y);
			s->x0 = x;
			s->y0 = y;
			outcode0 = Outcode(x, y, r);
		} else {
			GetIntersection(r, s, outcode1, &x, &y);
			s->x1 = x;
			s->y1 = y;
			outcode1 = Outcode(x, y, r);
		}
		i++;
	}
	assert(i < maxIter);
	*done = Inside(outcode0, outcode1);
}
Ejemplo n.º 3
0
void TCliqueOverlap::Expand(const THashSet<TInt>& SUBG, THashSet<TInt>& CAND) {
	if (SUBG.Len()==0) { if (m_Q.Len() >= m_minMaxCliqueSize) { m_Q.Pack(); m_maxCliques->Add(m_Q); } return; }
	if (CAND.Len()==0) return;
	//Get u that maximaze CAND intersection with neighbours of vertex u
	int u = MaxNbrsInCANDNodeId(SUBG, CAND);
	//Get neighbours of node u
	THashSet<TInt> nbrsU;
	GetNbrs(u, nbrsU);
	//Get relative complement of nbrsU in CAND
	THashSet<TInt> EXT;
	GetRelativeComplement(CAND, nbrsU, EXT);
	while(EXT.Len() != 0) {
		int q = GetNodeIdWithMaxDeg(EXT);
		//
		m_Q.Add(q);
		//
		THashSet<TInt> nbrsQ;
		GetNbrs(q, nbrsQ);
		//
		THashSet<TInt> SUBGq;
		GetIntersection(SUBG, nbrsQ, SUBGq);
		//
		THashSet<TInt> CANDq;
		GetIntersection(CAND, nbrsQ, CANDq);
		//
		Expand(SUBGq, CANDq);
		//
 		CAND.DelKey(q);
		m_Q.DelLast();
		//
		EXT.Clr();
		GetRelativeComplement(CAND, nbrsU, EXT);
	}
}
Ejemplo n.º 4
0
inline FX_BOOL _IsIntersect(const CFX_FloatRect& rectA, const CFX_FloatRect& rectB)
{
    FX_FLOAT interlow = .0f, interhigh = .0f;
    if(GetIntersection(rectA.bottom, rectA.top, rectB.bottom, rectB.top, interlow, interhigh)) {
        if(GetIntersection(rectA.left, rectA.right, rectB.left, rectB.right, interlow, interhigh)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    return FALSE;
}
Ejemplo n.º 5
0
bool SoyPhysics::GetIntersection(const TCollisionShape& ShapeA,const TCollisionShape& ShapeB,TIntersection& Intersection)
{
	//	what do we have to work with...
	auto& PolygonA = ShapeA.GetPolygon();
	auto& CapsuleA = ShapeA.GetCapsule();
	auto& CircleA = ShapeA.GetCircle();

	if ( PolygonA.IsValid() )
		return GetIntersection( PolygonA, ShapeB, Intersection );

	if ( CapsuleA.IsValid() )
		return GetIntersection( CapsuleA, ShapeB, Intersection );

	if ( CircleA.IsValid() )
		return GetIntersection( CircleA, ShapeB, Intersection );

	return false;
}
Ejemplo n.º 6
0
//заносит результаты пересечений (отрезки) треугольников из g с треугольником tr (tr_bb - is a triangle's bounding box)
void GetCrTriangles(Geometry& g,Triangle& tr,Lines& res,std::vector<LineConf>* lines_conf,Line tr_bb,float*perimeter)
{
	if(!g.boxes.size())
	{
	for(int i=0;i<g.tr.size();i++)
		if(CrossBoxes(g.tr_bb[i].v[0],g.tr_bb[i].v[1],tr_bb.v[0],tr_bb.v[1]))
			GetIntersection(g.tr[i],tr,res,lines_conf,perimeter);
	}else
	for(int b=0;b<g.boxes.size();b++)
		if(CrossBoxes(g.boxes[b].v[0],g.boxes[b].v[1],tr_bb.v[0],tr_bb.v[1]))
			for(int i=0;i<g.boxes[b].boxes.size();i++)
			{
				int box_id = g.boxes[b].boxes[i];
				if(CrossBoxes(g.tr_bb[box_id].v[0],g.tr_bb[box_id].v[1],tr_bb.v[0],tr_bb.v[1]))
					GetIntersection(g.tr[box_id],tr,res,lines_conf,perimeter);
			}
			
}
Ejemplo n.º 7
0
//  
//  returns true if line (L1, L2) intersects with axis-aligned box (B1, B2) 
//  The point of intersection is returned in HitP
//
bool CheckLineBox( CVec3 L1, CVec3 L2, CVec3 B1, CVec3 B2, CVec3 &HitP )
{
// Check for a quick exit if the line is completely to one side of the box
if (L2.x < B1.x && L1.x < B1.x) return false;
if (L2.x > B2.x && L1.x > B2.x) return false;
if (L2.y < B1.y && L1.y < B1.y) return false;
if (L2.y > B2.y && L1.y > B2.y) return false;
if (L2.z < B1.z && L1.z < B1.z) return false;
if (L2.z > B2.z && L1.z > B2.z) return false;

// Check if the line originates in the box
if (L1.x > B1.x && L1.x < B2.x && L1.y > B1.y && L1.y < B2.y && L1.z > B1.z && L1.z < B2.z ) {
	HitP = L1; 
	return true;
	}
	
// Check for a line intersection with each side of the box
if ( GetIntersection( L1.x-B1.x, L2.x-B1.x, L1, L2, HitP) && InBox( HitP, B1, B2, 1 ) ) return true;
if ( GetIntersection( L1.y-B1.y, L2.y-B1.y, L1, L2, HitP) && InBox( HitP, B1, B2, 2 ) ) return true;
if ( GetIntersection( L1.z-B1.z, L2.z-B1.z, L1, L2, HitP) && InBox( HitP, B1, B2, 3 ) ) return true;
if ( GetIntersection( L1.x-B2.x, L2.x-B2.x, L1, L2, HitP) && InBox( HitP, B1, B2, 1 ) ) return true;
if ( GetIntersection( L1.y-B2.y, L2.y-B2.y, L1, L2, HitP) && InBox( HitP, B1, B2, 2 ) ) return true;
if ( GetIntersection( L1.z-B2.z, L2.z-B2.z, L1, L2, HitP) && InBox( HitP, B1, B2, 3 ) ) return true;

return false;
}
Ejemplo n.º 8
0
Intersection Cube::SampleLight( float a, float b, float c ){

    glm::vec3 ray_o( 0.f );
    glm::vec3 ray_d( 0.f );

    a -= .5f;
    b -= .5f;

    int hit_face( c * 6.f );

    switch ( hit_face ) {
    case 0:
        //--- x+ ---
        ray_o = glm::vec3( 1.f, a, b );
        ray_d = glm::vec3( -1.f, 0.f, 0.f );
        break;
    case 1:
        //--- x- ---
        ray_o = glm::vec3( -1.f, a, b );
        ray_d = glm::vec3( 1.f, 0.f, 0.f );
        break;
    case 2:
        //--- y+ ---
        ray_o = glm::vec3( a, 1.f, b );
        ray_d = glm::vec3( 0.f, -1.f, 0.f );
        break;
    case 3:
        //--- y- ---
        ray_o = glm::vec3( a, -1.f, b );
        ray_d = glm::vec3( 0.f, 1.f, 0.f );
        break;
    case 4:
        //--- z+ ---
        ray_o = glm::vec3( a, b, 1.f );
        ray_d = glm::vec3( 0.f, 0.f, -1.f );
        break;
    case 5:
        //--- z- ---
        ray_o = glm::vec3( a, b, -1.f );
        ray_d = glm::vec3( 0.f, 0.f, 1.f );
        break;
    }

    Ray ray( ray_o, ray_d );

    return GetIntersection( ray.GetTransformedCopy( transform.T() ) );
}
Ejemplo n.º 9
0
Intersection Sphere::SampleLight( float a, float b, float c ){

    float phi( PI * a );
    float u( cosf( phi ) );
    float theta( TWO_PI * b );

    float x( sqrt( 1 - u * u ) * cosf( theta ) );
    float y( sqrt( 1 - u * u ) * sinf( theta ) );
    float z( u );

    glm::vec3 ray_o( x * .6f, y * .6f, z * .6f );
    glm::vec3 ray_d( -x, -y, -z );

    Ray ray( ray_o, ray_d );

    return GetIntersection( ray.GetTransformedCopy( transform.T() ) );
}
Ejemplo n.º 10
0
void Jaccard::CalculateJaccard() {

    unsigned long U = GetUnion();
    delete _bedA;
    delete _bedB;
    unsigned long I = GetIntersection();
    
    // header
    cout << "intersection\t"
         << "union\t"
         << "jaccard"
         << endl;
    
    // result
    cout << I << "\t" 
         << U - I << "\t"
         << (float) I / ((float) U - (float) I)
         << endl;
}
Ejemplo n.º 11
0
float TofGeometry::PathLengthInAPaddle(int il, int ib, AMSPoint point, AMSDir dir) {
  if ( (il<0)||(il>3)||(ib<0)||(ib>9) ) return false;
  // check intersection with every surface 
  AMSPoint points[6];
  int      npoints = 0;
  for (int isurface=0; isurface<6; isurface++) {
    AMSPoint x[4] = {
      TofGeometry::GetPaddleSurfaceCorner(il,ib,isurface,0),
      TofGeometry::GetPaddleSurfaceCorner(il,ib,isurface,1),
      TofGeometry::GetPaddleSurfaceCorner(il,ib,isurface,2),
      TofGeometry::GetPaddleSurfaceCorner(il,ib,isurface,3)
    };
    AMSPoint intersection = GetIntersection(x,point,dir);
    if (!IsInsideRectangle(x,intersection)) continue;
    points[npoints].setp(intersection.x(),intersection.y(),intersection.z());
    npoints++;
  }
  // in the case of 2 intersection the particle is entering and exiting 
  if (npoints!=2) return 0.;
  return (points[1] - points[0]).norm();
}
Ejemplo n.º 12
0
int main (int argc, char **argv) {
    Collection *List1, *List2, *NewList;

    List1       = (Collection *) malloc (sizeof (Collection));
    List1->next = NULL;
    List2       = (Collection *) malloc (sizeof (Collection));
    List2->next = NULL;

    srandom (time (NULL));

    printf      ("Original lists:\n");
    CreateList  (List1, 10);
    DispList    (List1);
    CreateList  (List2, 6);
    DispList    (List2);
    printf      ("Sorted lists:\n");
    SortList    (&List1);
    DispList    (List1);
    SortList    (&List2);
    DispList    (List2);
    NewList =   MergeList (List1, List2);
    printf      ("Merged list:\n");
    DispList    (NewList);
    DestroyList (&NewList);
    NewList =   GetIntersection (List1, List2);
    printf      ("Intersection:\n");
    DispList    (NewList);
    DestroyList (&NewList);
    NewList =   GetDiffset (List1, List2);
    printf      ("Different set:\n");
    DispList    (NewList);
    DestroyList (&NewList);

    DestroyList (&List1);
    DestroyList (&List2);
    return 0;
}
Ejemplo n.º 13
0
BOOL CcdrawDoc::AddSegment(CComplex p0, CComplex p1, CSegment &segm, double tol)
{
	int i,j,k,n0,n1;
	double xi,yi,t;
	CComplex p[2];
	CArray< CComplex, CComplex&> newnodes;

	newnodes.RemoveAll();

	n0=ClosestNode(p0.re,p0.im);
	n1=ClosestNode(p1.re,p1.im);

	// don't add if line is degenerate
	if (n0==n1) return FALSE;
	
	// don't add if the line is already in the list;
	for(i=0;i<linelist.GetSize();i++){
		if ((linelist[i].n0==n0) && (linelist[i].n1==n1)) return FALSE;
		if ((linelist[i].n0==n1) && (linelist[i].n1==n0)) return FALSE;
	}

	segm.IsSelected=FALSE; segm.n0=n0; segm.n1=n1; 
	
	// check to see if there are intersections with segments
	for(i=0;i<linelist.GetSize();i++)
		if(GetIntersection(n0,n1,i,&xi,&yi)==TRUE)  newnodes.Add(CComplex(xi,yi));

	// check to see if there are intersections with arcs
	for(i=0;i<arclist.GetSize();i++){
		j=GetLineArcIntersection(segm,arclist[i],p);
		if (j>0) for(k=0;k<j;k++) newnodes.Add(p[k]);
	}

	// add nodes at intersections
	if(tol==0)
	{
		if (nodelist.GetSize()<2) t=1.e-08;
		else{
			CComplex p0,p1;
			p0=nodelist[0].CC();
			p1=p0;
			for(i=1;i<nodelist.GetSize();i++)
			{
				if(nodelist[i].x<p0.re) p0.re=nodelist[i].x;
				if(nodelist[i].x>p1.re) p1.re=nodelist[i].x;
				if(nodelist[i].y<p0.im) p0.im=nodelist[i].y;
				if(nodelist[i].y>p1.im) p1.im=nodelist[i].y;
			}
			t=abs(p1-p0)*CLOSE_ENOUGH;
		}
	}
	else t=tol;

	for(i=0;i<newnodes.GetSize();i++) 
		AddNode(newnodes[i].re,newnodes[i].im,t);
	
	// Add proposed line segment
	linelist.Add(segm);

	// check to see if proposed line passes through other points;
    // if so, delete line and create lines that link intermediate points;
    // does this by recursive use of AddSegment;
	double d,dmin;
    UnselectAll();
    if (tol==0) dmin=abs(nodelist[n1].CC()-nodelist[n0].CC())*1.e-05;
	else dmin=tol;

    k=(int) linelist.GetSize()-1;
    for(i=0;i<nodelist.GetSize();i++)
    {
        if( (i!=n0) && (i!=n1) )
        {
            d=ShortestDistance(nodelist[i].x,nodelist[i].y,k);
			// catch a special case...
			if (abs(nodelist[i].CC()-nodelist[n0].CC())<dmin) d=2.*dmin;
			if (abs(nodelist[i].CC()-nodelist[n1].CC())<dmin) d=2.*dmin;
	        if (d<dmin){
                linelist[k].ToggleSelect();
                DeleteSelectedSegments();
                AddSegment(n0,i,&segm,dmin);
                AddSegment(i,n1,&segm,dmin);
                i=(int) nodelist.GetSize();
            }

        }
    }

	return TRUE;
}
Ejemplo n.º 14
0
static VOID MainThreadProc (PVOID threadArg)
{
	EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg;
	PLIST_ENTRY listEntry;
	EncryptedIoQueueItem *item;

	LARGE_INTEGER fragmentOffset;
	ULONG dataRemaining;
	PUCHAR activeFragmentBuffer = queue->FragmentBufferA;
	PUCHAR dataBuffer;
	EncryptedIoRequest *request;
	uint64 intersectStart;
	uint32 intersectLength;
	ULONGLONG addResult;
	HRESULT hResult;

	if (IsEncryptionThreadPoolRunning())
		KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY);

	while (!queue->ThreadExitRequested)
	{
		if (!NT_SUCCESS (KeWaitForSingleObject (&queue->MainThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL)))
			continue;

		while ((listEntry = ExInterlockedRemoveHeadList (&queue->MainThreadQueue, &queue->MainThreadQueueLock)))
		{
			PIRP irp = CONTAINING_RECORD (listEntry, IRP, Tail.Overlay.ListEntry);
			PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp);
			
			if (queue->Suspended)
				KeWaitForSingleObject (&queue->QueueResumedEvent, Executive, KernelMode, FALSE, NULL);

			item = GetPoolBuffer (queue, sizeof (EncryptedIoQueueItem));
			if (!item)
			{
				TCCompleteDiskIrp (irp, STATUS_INSUFFICIENT_RESOURCES, 0);
				DecrementOutstandingIoCount (queue);
				IoReleaseRemoveLock (&queue->RemoveLock, irp);

				continue;
			}

			item->Queue = queue;
			item->OriginalIrp = irp;
			item->Status = STATUS_SUCCESS;

			IoSetCancelRoutine (irp, NULL);
			if (irp->Cancel)
			{
				CompleteOriginalIrp (item, STATUS_CANCELLED, 0);
				continue;
			}

			switch (irpSp->MajorFunction)
			{
			case IRP_MJ_READ:
				item->Write = FALSE;
				item->OriginalOffset = irpSp->Parameters.Read.ByteOffset;
				item->OriginalLength = irpSp->Parameters.Read.Length;
				break;

			case IRP_MJ_WRITE:
				item->Write = TRUE;
				item->OriginalOffset = irpSp->Parameters.Write.ByteOffset;
				item->OriginalLength = irpSp->Parameters.Write.Length;
				break;

			default:
				CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0);
				continue;
			}

#ifdef TC_TRACE_IO_QUEUE
			item->OriginalIrpOffset = item->OriginalOffset;
#endif

			// Handle misaligned read operations to work around a bug in Windows System Assessment Tool which does not follow FILE_FLAG_NO_BUFFERING requirements when benchmarking disk devices
			if (queue->IsFilterDevice
				&& !item->Write
				&& item->OriginalLength > 0
				&& (item->OriginalLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) == 0
				&& (item->OriginalOffset.QuadPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0)
			{
				byte *buffer;
				ULONG alignedLength;
				LARGE_INTEGER alignedOffset;
				hResult = ULongAdd(item->OriginalLength, ENCRYPTION_DATA_UNIT_SIZE, &alignedLength);
				if (hResult != S_OK)
				{
					CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0);
					continue;
				}

				alignedOffset.QuadPart = item->OriginalOffset.QuadPart & ~((LONGLONG) ENCRYPTION_DATA_UNIT_SIZE - 1);

				buffer = TCalloc (alignedLength);
				if (!buffer)
				{
					CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0);
					continue;
				}

				item->Status = TCReadDevice (queue->LowerDeviceObject, buffer, alignedOffset, alignedLength);

				if (NT_SUCCESS (item->Status))
				{
					UINT64_STRUCT dataUnit;

					dataBuffer = (PUCHAR) MmGetSystemAddressForMdlSafe (irp->MdlAddress, HighPagePriority);
					if (!dataBuffer)
					{
						TCfree (buffer);
						CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0);
						continue;
					}

					if (queue->EncryptedAreaStart != -1 && queue->EncryptedAreaEnd != -1)
					{
						GetIntersection (alignedOffset.QuadPart, alignedLength, queue->EncryptedAreaStart, queue->EncryptedAreaEnd, &intersectStart, &intersectLength);
						if (intersectLength > 0)
						{
							dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE;
							DecryptDataUnits (buffer + (intersectStart - alignedOffset.QuadPart), &dataUnit, intersectLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo);
						}
					}

					memcpy (dataBuffer, buffer + (item->OriginalOffset.LowPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)), item->OriginalLength);
				}

				TCfree (buffer);
				CompleteOriginalIrp (item, item->Status, NT_SUCCESS (item->Status) ? item->OriginalLength : 0);
				continue;
			}

			// Validate offset and length
			if (item->OriginalLength == 0
				|| (item->OriginalLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0
				|| (item->OriginalOffset.QuadPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0
				|| (	!queue->IsFilterDevice && 
						(	(S_OK != ULongLongAdd(item->OriginalOffset.QuadPart, item->OriginalLength, &addResult))
							||	(addResult > (ULONGLONG) queue->VirtualDeviceLength)
						)
					)
				)
			{
				CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0);
				continue;
			}

#ifdef TC_TRACE_IO_QUEUE
			Dump ("Q  %I64d [%I64d] %c len=%d\n", item->OriginalOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), item->Write ? 'W' : 'R', item->OriginalLength);
#endif

			if (!queue->IsFilterDevice)
			{
				// Adjust the offset for host file or device
				if (queue->CryptoInfo->hiddenVolume)
					hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->hiddenVolumeOffset, &addResult);
				else
					hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->volDataAreaOffset, &addResult); 

				if (hResult != S_OK)
				{
					CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0);
					continue;
				}
				else
					item->OriginalOffset.QuadPart = addResult;

				// Hidden volume protection
				if (item->Write && queue->CryptoInfo->bProtectHiddenVolume)
				{
					// If there has already been a write operation denied in order to protect the
					// hidden volume (since the volume mount time)
					if (queue->CryptoInfo->bHiddenVolProtectionAction)	
					{
						// Do not allow writing to this volume anymore. This is to fake a complete volume
						// or system failure (otherwise certain kinds of inconsistency within the file
						// system could indicate that this volume has used hidden volume protection).
						CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0);
						continue;
					}

					// Verify that no byte is going to be written to the hidden volume area
					if (RegionsOverlap ((unsigned __int64) item->OriginalOffset.QuadPart,
						(unsigned __int64) item->OriginalOffset.QuadPart + item->OriginalLength - 1,
						queue->CryptoInfo->hiddenVolumeOffset,
						(unsigned __int64) queue->CryptoInfo->hiddenVolumeOffset + queue->CryptoInfo->hiddenVolumeProtectedSize - 1))
					{
						Dump ("Hidden volume protection triggered: write %I64d-%I64d (protected %I64d-%I64d)\n", item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, queue->CryptoInfo->hiddenVolumeOffset, queue->CryptoInfo->hiddenVolumeOffset + queue->CryptoInfo->hiddenVolumeProtectedSize - 1);
						queue->CryptoInfo->bHiddenVolProtectionAction = TRUE;

						// Deny this write operation to prevent the hidden volume from being overwritten
						CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0);
						continue;
					}
				}
			}
			else if (item->Write
				&& RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET, TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET + TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE - 1))
			{
				// Prevent inappropriately designed software from damaging important data that may be out of sync with the backup on the Rescue Disk (such as the end of the encrypted area).
				Dump ("Preventing write to the system encryption key data area\n");
				CompleteOriginalIrp (item, STATUS_MEDIA_WRITE_PROTECTED, 0);
				continue;
			}
			else if (item->Write && IsHiddenSystemRunning()
				&& (RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, TC_SECTOR_SIZE_BIOS, TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS - 1)
				 || RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, GetBootDriveLength(), _I64_MAX)))
			{
				Dump ("Preventing write to boot loader or host protected area\n");
				CompleteOriginalIrp (item, STATUS_MEDIA_WRITE_PROTECTED, 0);
				continue;
			}

			dataBuffer = (PUCHAR) MmGetSystemAddressForMdlSafe (irp->MdlAddress, HighPagePriority);

			if (dataBuffer == NULL)
			{
				CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0);
				continue;
			}

			// Divide data block to fragments to enable efficient overlapping of encryption and IO operations

			dataRemaining = item->OriginalLength;
			fragmentOffset = item->OriginalOffset;

			while (dataRemaining > 0)
			{
				BOOL isLastFragment = dataRemaining <= TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE;
				
				ULONG dataFragmentLength = isLastFragment ? dataRemaining : TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE;
				activeFragmentBuffer = (activeFragmentBuffer == queue->FragmentBufferA ? queue->FragmentBufferB : queue->FragmentBufferA);

				InterlockedIncrement (&queue->IoThreadPendingRequestCount);

				// Create IO request
				request = GetPoolBuffer (queue, sizeof (EncryptedIoRequest));
				if (!request)
				{
					CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0);
					break;
				}
				request->Item = item;
				request->CompleteOriginalIrp = isLastFragment;
				request->Offset = fragmentOffset;
				request->Data = activeFragmentBuffer;
				request->OrigDataBufferFragment = dataBuffer;
				request->Length = dataFragmentLength;

				if (queue->IsFilterDevice)
				{
					if (queue->EncryptedAreaStart == -1 || queue->EncryptedAreaEnd == -1)
					{
						request->EncryptedLength = 0;
					}
					else
					{
						// Get intersection of data fragment with encrypted area
						GetIntersection (fragmentOffset.QuadPart, dataFragmentLength, queue->EncryptedAreaStart, queue->EncryptedAreaEnd, &intersectStart, &intersectLength);

						request->EncryptedOffset = intersectStart - fragmentOffset.QuadPart;
						request->EncryptedLength = intersectLength;
					}
				}
				else
				{
					request->EncryptedOffset = 0;
					request->EncryptedLength = dataFragmentLength;
				}

				AcquireFragmentBuffer (queue, activeFragmentBuffer);

				if (item->Write)
				{
					// Encrypt data
					memcpy (activeFragmentBuffer, dataBuffer, dataFragmentLength);

					if (request->EncryptedLength > 0)
					{
						UINT64_STRUCT dataUnit;
						ASSERT (request->EncryptedOffset + request->EncryptedLength <= request->Offset.QuadPart + request->Length);

						dataUnit.Value = (request->Offset.QuadPart + request->EncryptedOffset) / ENCRYPTION_DATA_UNIT_SIZE;

						if (queue->CryptoInfo->bPartitionInInactiveSysEncScope)
							dataUnit.Value += queue->CryptoInfo->FirstDataUnitNo.Value;
						else if (queue->RemapEncryptedArea)
							dataUnit.Value += queue->RemappedAreaDataUnitOffset;
								
						EncryptDataUnits (activeFragmentBuffer + request->EncryptedOffset, &dataUnit, request->EncryptedLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo);
					}
				}

				// Queue IO request
				ExInterlockedInsertTailList (&queue->IoThreadQueue, &request->ListEntry, &queue->IoThreadQueueLock);
				KeSetEvent (&queue->IoThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE);

				if (isLastFragment)
					break;

				dataRemaining -= TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE;
				dataBuffer += TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE;
				fragmentOffset.QuadPart += TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE;
			}
		}
	}

	PsTerminateSystemThread (STATUS_SUCCESS);
}
Ejemplo n.º 15
0
static NTSTATUS DumpFilterWrite (PFILTER_EXTENSION filterExtension, PLARGE_INTEGER diskWriteOffset, PMDL writeMdl)
{
	ULONG dataLength = MmGetMdlByteCount (writeMdl);
	uint64 offset = DumpPartitionOffset.QuadPart + diskWriteOffset->QuadPart;
	uint64 intersectStart;
	uint32 intersectLength;
	PVOID writeBuffer;
	CSHORT origMdlFlags;

	if (BootDriveFilterExtension->MagicNumber != TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER)
		TC_BUG_CHECK (STATUS_CRC_ERROR);

	if (BootDriveFilterExtension->Queue.EncryptedAreaEndUpdatePending)	// Hibernation should always abort the setup thread
		TC_BUG_CHECK (STATUS_INVALID_PARAMETER);

	if (BootDriveFilterExtension->Queue.EncryptedAreaStart == -1 || BootDriveFilterExtension->Queue.EncryptedAreaEnd == -1)
		return STATUS_SUCCESS;

	if (dataLength > WriteFilterBufferSize)
		TC_BUG_CHECK (STATUS_BUFFER_OVERFLOW);	// Bug check is required as returning an error does not prevent data from being written to disk

	if ((dataLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0)
		TC_BUG_CHECK (STATUS_INVALID_PARAMETER);

	if ((offset & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0)
		TC_BUG_CHECK (STATUS_INVALID_PARAMETER);

	writeBuffer = MmGetSystemAddressForMdlSafe (writeMdl, HighPagePriority);
	if (!writeBuffer)
		TC_BUG_CHECK (STATUS_INSUFFICIENT_RESOURCES);

	memcpy (WriteFilterBuffer, writeBuffer, dataLength);

	GetIntersection (offset,
		dataLength,
		BootDriveFilterExtension->Queue.EncryptedAreaStart,
		BootDriveFilterExtension->Queue.EncryptedAreaEnd,
		&intersectStart,
		&intersectLength);

	if (intersectLength > 0)
	{
		UINT64_STRUCT dataUnit;
		dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE;

		if (BootDriveFilterExtension->Queue.RemapEncryptedArea)
		{
			diskWriteOffset->QuadPart += BootDriveFilterExtension->Queue.RemappedAreaOffset;
			dataUnit.Value += BootDriveFilterExtension->Queue.RemappedAreaDataUnitOffset;
		}

		EncryptDataUnitsCurrentThread (WriteFilterBuffer + (intersectStart - offset),
			&dataUnit,
			intersectLength / ENCRYPTION_DATA_UNIT_SIZE,
			BootDriveFilterExtension->Queue.CryptoInfo);
	}

	origMdlFlags = writeMdl->MdlFlags;

	MmInitializeMdl (writeMdl, WriteFilterBuffer, dataLength);
	MmBuildMdlForNonPagedPool (writeMdl);

	// Instead of using MmGetSystemAddressForMdlSafe(), some buggy custom storage drivers may directly test MDL_MAPPED_TO_SYSTEM_VA flag,
	// disregarding the fact that other MDL flags may be set by the system or a dump filter (e.g. MDL_SOURCE_IS_NONPAGED_POOL flag only).
	// Therefore, to work around this issue, the original flags will be restored even if they do not match the new MDL.
	// MS BitLocker also uses this hack/workaround (it should be safe to use until the MDL structure is changed).

	writeMdl->MdlFlags = origMdlFlags;

	return STATUS_SUCCESS;
}
Ejemplo n.º 16
0
	void CollectNode(void *node, TArray<FCoverageVertex> &shape)
	{
		static TArray<FCoverageLine> lists[2];
		const double COVERAGE_EPSILON = 6.;	// same epsilon as the node builder

		if (!((size_t)node & 1))  // Keep going until found a subsector
		{
			node_t *bsp = (node_t *)node;

			int centerside = R_PointOnSide(center.x, center.y, bsp);

			lists[0].Clear();
			lists[1].Clear();
			for(unsigned i=0;i<shape.Size(); i++)
			{
				FCoverageVertex *v1 = &shape[i];
				FCoverageVertex *v2 = &shape[(i+1) % shape.Size()];
				FCoverageLine vl = {{*v1, *v2}};

				double dist_v1 = PartitionDistance(v1, bsp);
				double dist_v2 = PartitionDistance(v2, bsp);

				if(dist_v1 <= COVERAGE_EPSILON)
				{
					if (dist_v2 <= COVERAGE_EPSILON)
					{
						lists[centerside].Push(vl);
					}
					else
					{
						int side = PointOnSide(v2, bsp);
						lists[side].Push(vl);
					}
				}
				else if (dist_v2 <= COVERAGE_EPSILON)
				{
					int side = PointOnSide(v1, bsp);
					lists[side].Push(vl);
				}
				else 
				{
					int side1 = PointOnSide(v1, bsp);
					int side2 = PointOnSide(v2, bsp);

					if(side1 != side2)
					{
						// if the partition line crosses this seg, we must split it.

						FCoverageVertex vert;

						if (GetIntersection(v1, v2, bsp, &vert))
						{
							lists[0].Push(vl);
							lists[1].Push(vl);
							lists[side1].Last().v[1] = vert;
							lists[side2].Last().v[0] = vert;
						}
						else
						{
							// should never happen
							lists[side1].Push(vl);
						}
					}
					else 
					{
						// both points on the same side.
						lists[side1].Push(vl);
					}
				}
			}
			if (lists[1].Size() == 0)
			{
				CollectNode(bsp->children[0], shape);
			}
			else if (lists[0].Size() == 0)
			{
				CollectNode(bsp->children[1], shape);
			}
			else
			{
				// copy the static arrays into local ones
				TArray<FCoverageVertex> locallists[2];

				for(int l=0;l<2;l++)
				{
					for (unsigned i=0;i<lists[l].Size(); i++)
					{
						locallists[l].Push(lists[l][i].v[0]);
						unsigned i1= (i+1)%lists[l].Size();
						if (lists[l][i1].v[0] != lists[l][i].v[1])
						{
							locallists[l].Push(lists[l][i].v[1]);
						}
					}
				}

				CollectNode(bsp->children[0], locallists[0]);
				CollectNode(bsp->children[1], locallists[1]);
			}
		}
		else
		{
			// we reached a subsector so we can link the node with this subsector
			subsector_t *sub = (subsector_t *)((BYTE *)node - 1);
			collect.Push(int(sub-subsectors));
		}
	}
Ejemplo n.º 17
0
bool IntrTriangle2Triangle2<Real>::Find (Real tmax,
        const Vector2<Real>& velocity0, const Vector2<Real>& velocity1)
{
	// Process as if V0-triangle is stationary and V1-triangle is moving.
	Vector2<Real> W = velocity1 - velocity0;
	int side = 0;  // 0 = NONE, -1 = LEFT, +1 = RIGHT
	Real tfirst = (Real)0;
	Real tlast = Math<Real>::MAX_REAL;

	Configuration cfg0, cfg1, tcfg0, tcfg1;
	int i0, i1, i2;
	Vector2<Real> D;
	Real speed;

	// Process edges of V0-triangle.
	for (i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++)
	{
		// Test axis V0[i1] + t*perp(V0[i2]-V0[i1]), perp(x,y) = (y,-x).
		D.X() = mTriangle0->V[i2].Y() - mTriangle0->V[i1].Y();
		D.Y() = mTriangle0->V[i1].X() - mTriangle0->V[i2].X();
		speed = D.Dot(W);

		ComputeTwo(cfg0, mTriangle0->V, D, i0, i1, i2);
		ComputeThree(cfg1, mTriangle1->V, D, mTriangle0->V[i1]);

		if (NoIntersect(cfg0, cfg1, tmax, speed, side, tcfg0, tcfg1,
		                tfirst, tlast))
		{
			return false;
		}
	}

	// Process edges of V1-triangle.
	for (i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++)
	{
		// Test axis V1[i1] + t*perp(V1[i2]-V1[i1]), perp(x,y) = (y,-x).
		D.X() = mTriangle1->V[i2].Y() - mTriangle1->V[i1].Y();
		D.Y() = mTriangle1->V[i1].X() - mTriangle1->V[i2].X();
		speed = D.Dot(W);

		ComputeTwo(cfg1, mTriangle1->V, D, i0, i1, i2);
		ComputeThree(cfg0, mTriangle0->V, D, mTriangle1->V[i1]);

		if (NoIntersect(cfg0, cfg1, tmax, speed, side, tcfg0, tcfg1,
		                tfirst, tlast))
		{
			return false;
		}
	}

	// Move triangles to first contact.
	Vector2<Real> moveV0[3], moveV1[3];
	for (int i = 0; i < 3; ++i)
	{
		moveV0[i] = mTriangle0->V[i] + tfirst*velocity0;
		moveV1[i] = mTriangle1->V[i] + tfirst*velocity1;
	};

	GetIntersection(tcfg0, tcfg1, side, moveV0, moveV1, mQuantity, mPoint);

	mContactTime = tfirst;
	return mQuantity > 0;
}
Ejemplo n.º 18
0
//============================================================================
//		NGeometryUtilities::ClipPolygonToEdge : Clip a polygon to an edge.
//----------------------------------------------------------------------------
template<class T> void NGeometryUtilities::ClipPolygonToEdge(	const              NPointT<T>   &edgeStart,
																const              NPointT<T>   &edgeEnd,
																const std::vector< NPointT<T> > &theInput,
																	  std::vector< NPointT<T> > &theOutput)
{	NIndex			n, numPoints;
	NPointT<T>		s, p, i;



	// Get the state we need
	//
	// Since most polygons produce a similar size of output, we reserve space up front.
	theOutput.clear();

	numPoints = theInput.size();
	if (numPoints == 0)
		return;

	theOutput.reserve(numPoints);



	// Perform the clip
	//
	// Each segment is compared to the clipping edge, which gives four cases:
	//
	//	1) Both endpoints (s and p) are inside the clipping edge, so p is added.
	//	2) Both endpoints (s and p) are outside the clipping edge, so nothing is added.
	//	3) Vertex s is inside and p is outside, so the intersection (i) is added.
	//	4) Vertex p is inside and s is outside, so the intersection (i) and p are added.
	//
	s = theInput[numPoints - 1];
	for (n = 0; n < numPoints; n++)
		{
		p = theInput[n];


		// Cases 1 or 4
		if (IsInside(edgeStart, edgeEnd, p))
			{
			// Case 1
			if (IsInside(edgeStart, edgeEnd, s))
				theOutput.push_back(p);
			
			// Case 4
			else
				{
				i = GetIntersection(edgeStart, edgeEnd, s, p);
				
				theOutput.push_back(i);
				theOutput.push_back(p);
				}
			}


		// Cases 2 or 3
		else
			{
			// Case 3
			if (IsInside(edgeStart, edgeEnd, s))
				{
				i = GetIntersection(edgeStart, edgeEnd, s, p);
				theOutput.push_back(i);
				}
			
			
			// Case 2
			else
				{ }
			}
		
		s = p;
		}
}
Ejemplo n.º 19
0
TEST(intersection, triangle_tetrahedron) {
    TIntersectionType it;
    double area;

    // create tetrahedron
    TPoint point0(0.00, 0.00, 0.00);
    TPoint point1(3.00, 0.00, 0.00);
    TPoint point2(0.00, 3.00, 0.00);
    TPoint point3(0.00, 0.00, 3.00);
    TTetrahedron tetrahedron(point0, point1, point2, point3);

    // triangle is in tetrahedron
    TPoint pointA(0.50, 0.50, 0.50);
    TPoint pointB(0.50, 1.50, 0.50);
    TPoint pointC(1.50, 0.50, 0.50);
    TTriangle triangle(pointA, pointB, pointC);

    xprintf(Msg, "Test - triangle is in tetrahedron\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.5);

    // triangle is greater than tetrahedron, intersection is triangle
    pointA.SetCoord(-3.0, 2.0, 2.0);
    pointB.SetCoord(2.0, -3.0, 2.0);
    pointC.SetCoord(2.0, 2.0, 2.0);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - triangle is greater than tetrahedron, intersection is triangle\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.5);

    // intersection is tetragon
    pointA.SetCoord(-0.50, 0.50, 1.00);
    pointB.SetCoord(2.00, 0.50, 1.00);
    pointC.SetCoord(2.00, 3.00, 1.00);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is tetragon\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.875);

    // intersection is pentagon
    pointA.SetCoord(-1.0, 2.00, 1.00);
    pointB.SetCoord(1.50, 2.00, 1.00);
    pointC.SetCoord(1.50,-0.5 , 1.00);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is pentagon\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.5+0.5+0.5*3.0/4.0);

    // intersection is hexagon (plane parallel to x-y)
    pointA.SetCoord(2.00, 2.00, 0.50);
    pointB.SetCoord(2.00, -1.00, 0.50);
    pointC.SetCoord(-1.00, 2.00, 0.50);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is hexagon (plane parallel to x-y)\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 2.375);

    // intersection is hexagon
    pointA.SetCoord(0.25, 2.00, 1.00);
    pointB.SetCoord(2.25, 1.00, -1.00);
    pointC.SetCoord(0.25, -1.00, 3.00);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is hexagon\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 3.477919);
}