Пример #1
0
const nsCString
DOMStorageDBThread::DBOperation::Target() const
{
  switch (mType) {
    case opAddItem:
    case opUpdateItem:
    case opRemoveItem:
      return Origin() + NS_LITERAL_CSTRING("|") + NS_ConvertUTF16toUTF8(mKey);

    default:
      return Origin();
  }
}
Пример #2
0
Value* Procedure::addIntConstant(Type type, int64_t value)
{
    switch (type) {
    case Int32:
        return add<Const32Value>(Origin(), static_cast<int32_t>(value));
    case Int64:
        return add<Const64Value>(Origin(), value);
    case Double:
        return add<ConstDoubleValue>(Origin(), static_cast<double>(value));
    default:
        RELEASE_ASSERT_NOT_REACHED();
        return nullptr;
    }
}
Пример #3
0
void AiEntityPhysicsState::UpdateAreaNums() {
	const AiAasWorld *aasWorld = AiAasWorld::Instance();
	this->currAasAreaNum = ( decltype( this->currAasAreaNum ) )aasWorld->FindAreaNum( Origin() );
	// Use a computation shortcut when entity is on ground
	if( this->groundEntNum >= 0 ) {
		this->droppedToFloorOriginOffset = ( decltype( this->droppedToFloorOriginOffset ) )( -playerbox_stand_mins[2] );
		this->droppedToFloorOriginOffset += 4.0f;
		SetHeightOverGround( 0 );
		Vec3 droppedOrigin( Origin() );
		droppedOrigin.Z() -= this->droppedToFloorOriginOffset;
		this->droppedToFloorAasAreaNum = ( decltype( this->droppedToFloorAasAreaNum ) )aasWorld->FindAreaNum( droppedOrigin );
		return;
	}

	// Use a computation shortcut when the current area is grounded
	if( aasWorld->AreaSettings()[this->currAasAreaNum].areaflags & AREA_GROUNDED ) {
		float areaMinsZ = aasWorld->Areas()[this->currAasAreaNum].mins[2];
		float selfZ = Self()->s.origin[2];
		float heightOverGround_ = selfZ - areaMinsZ + playerbox_stand_maxs[2];
		clamp_high( heightOverGround_, GROUND_TRACE_DEPTH );
		SetHeightOverGround( heightOverGround_ );
		this->droppedToFloorOriginOffset = ( decltype( this->droppedToFloorOriginOffset ) )( heightOverGround_ - 4.0f );
		this->droppedToFloorAasAreaNum = this->currAasAreaNum;
		return;
	}

	// Try drop an origin from air to floor
	trace_t trace;
	edict_t *ent = const_cast<edict_t *>( Self() );
	Vec3 traceEnd( Origin() );
	traceEnd.Z() -= GROUND_TRACE_DEPTH;
	G_Trace( &trace, this->origin, ent->r.mins, ent->r.maxs, traceEnd.Data(), ent, MASK_PLAYERSOLID );
	// Check not only whether there is a hit but test whether is it really a ground (and not a wall or obstacle)
	if( trace.fraction != 1.0f && Origin()[2] - trace.endpos[2] > -playerbox_stand_mins[2] ) {
		float heightOverGround_ = trace.fraction * GROUND_TRACE_DEPTH + playerbox_stand_mins[2];
		this->droppedToFloorOriginOffset = ( decltype( this->droppedToFloorOriginOffset ) )( -playerbox_stand_mins[2] );
		this->droppedToFloorOriginOffset -= heightOverGround_ - 4.0f;
		SetHeightOverGround( heightOverGround_ );
		Vec3 droppedOrigin( Origin() );
		droppedOrigin.Z() -= this->droppedToFloorOriginOffset;
		this->droppedToFloorAasAreaNum = ( decltype( this->droppedToFloorAasAreaNum ) )aasWorld->FindAreaNum( droppedOrigin );
		return;
	}

	this->droppedToFloorOriginOffset = 0;
	SetHeightOverGround( std::numeric_limits<float>::infinity() );
	this->droppedToFloorAasAreaNum = this->currAasAreaNum;
}
Пример #4
0
Vector3 Drag::DeltaFromOrigin()
// ----------------------------------------------------------------------------
//   Return the difference between the first mouse position and current one
// ----------------------------------------------------------------------------
{
    return Current() - Origin();
}
Пример #5
0
bool CsgDisk::intersects(const Vec2f &vertice) const
{
    if(!intersectsBBox(vertice))
        return false;
    Vec2f transformedVertice = T_Inverted() * vertice;
    return transformedVertice.distance(Origin()) <= 0.5f;
}
Пример #6
0
/*
Creates the hyperboloid using a formula. 
TODO: Update this so the hyperboloid actually represents a proper parametric model. 
*/
TopoDS_Shape hyperboloid::create(double innerRadius, double height, double heightUnder, double angle)
{
		int detail = 40;
		gp_Pnt Origin(0,0,0);
		gp_Vec Dir(0,0,1);

		int uCount = detail;
		double a = innerRadius;
		double c = angle;
		double totalHeight = height + heightUnder;
		TColgp_Array1OfPnt array (0,uCount - 1);

		for (double u = 0; u < uCount; u++)
		{	
			double uValue = ((totalHeight * u / (uCount - 1)) - heightUnder) / c;
			double vValue = 0;

			double sqrMe = 1 + uValue * uValue;

			double x = a * sqrt(sqrMe) * cos(vValue);
			double y = a * sqrt(sqrMe) * sin(vValue);
			double z = c * uValue;
			gp_Pnt P1(x,y,z);   
			array.SetValue(u,P1); 
		}
	                          
		Handle(Geom_BSplineCurve) hyperbola = GeomAPI_PointsToBSpline(array).Curve();    
		TopoDS_Edge hyperbolaTopoDS = BRepBuilderAPI_MakeEdge(hyperbola); 

		gp_Ax1 axis = gp_Ax1(Origin,Dir); 
		TopoDS_Shape hyperboloid = BRepPrimAPI_MakeRevol(hyperbolaTopoDS, axis); 

		return hyperboloid;
}
Пример #7
0
int main() {

	launcher Steam("steam"), Origin("origin"), Skype("skype");

	Origin.Start();

	system("pause");
	return 0;
}
Пример #8
0
namespace CGAL {

const Translation             TRANSLATION = Translation();
const Rotation                ROTATION = Rotation();
const Scaling                 SCALING = Scaling();
const Reflection              REFLECTION = Reflection();
const Identity_transformation IDENTITY = Identity_transformation();

const Origin      ORIGIN = Origin();
const Null_vector NULL_VECTOR = Null_vector();

} //namespace CGAL
Пример #9
0
namespace CGAL {

Translation             TRANSLATION;
Rotation                ROTATION;
Scaling                 SCALING;
Reflection              REFLECTION;
Identity_transformation IDENTITY;

const Origin      ORIGIN = Origin();
const Null_vector NULL_VECTOR = Null_vector();

} //namespace CGAL
Пример #10
0
bool ON_Plane::GetDistanceToBoundingBox(const ON_BoundingBox& Box,
				                                double* min, double* max) const
{
  //min and max signed distance.  Returns false if plane normal has zero length.

  ON_3dVector UnitNormal = Normal();
  if (!UnitNormal.Unitize()) 
    return false;

  double mind, maxd;
  mind = maxd = (Box.Min() - Origin())*UnitNormal;
  int i0, i1, i2;
  for (i0=0;i0<2;i0++)
  {
    for(i1=0;i1<2;i1++) 
    {
      for (i2=0;i2<2;i2++) 
      {
        if (i0||i1||i2) 
        {
          ON_3dPoint P;
          P[0]=(i0)?Box.Max()[0]:Box.Min()[0];
          P[1]=(i1)?Box.Max()[1]:Box.Min()[1];
          P[2]=(i2)?Box.Max()[2]:Box.Min()[2];
          double d = (P - Origin())*UnitNormal;
          //double dd = P.DistanceTo(ClosestPointTo(P));
          if (d < mind) 
            mind=d;
          else if (d > maxd) 
            maxd=d;
        }
      }
    }
  }
  *min = mind;
  *max = maxd;
  return true;
}
Пример #11
0
//
// ExplosionObj::ProcessCycle
//
// Per-cycle processing
//
void ExplosionObj::ProcessCycle()
{
  PERF_S(("ExplosionObj"))

  // Apply damage
  ExplosionType()->Apply(Origin(), sourceUnit.GetPointer(), sourceTeam);

  // Has the persistence time expired ?
  if (GetBirthTime() + ExplosionType()->persist < GameTime::SimTotalTime())
  {
    MarkForDeletion();
  }

  PERF_E(("ExplosionObj"))
}
bool
nsHttpConnectionInfo::HostIsLocalIPLiteral() const
{
    PRNetAddr prAddr;
    // If the host/proxy host is not an IP address literal, return false.
    if (ProxyHost()) {
        if (PR_StringToNetAddr(ProxyHost(), &prAddr) != PR_SUCCESS) {
          return false;
        }
    } else if (PR_StringToNetAddr(Origin(), &prAddr) != PR_SUCCESS) {
        return false;
    }
    NetAddr netAddr;
    PRNetAddrToNetAddr(&prAddr, &netAddr);
    return IsIPAddrLocal(&netAddr);
}
Пример #13
0
//
// ProjectileObj::Detonate
//
// Projectile has been detonated
//
void ProjectileObj::Detonate()
{
  if (!detonated)
  {
    // Generate an explosion
    if (ProjectileType()->explosionType.Alive())
    {
      ProjectileType()->explosionType->Detonate(Origin(), source.GetPointer(), sourceTeam);
    }

    // Delete the projectile
    GameObjCtrl::MarkForDeletion(this);

    // Set the detonated flag
    detonated = TRUE;
  }
}
Пример #14
0
bool FMODAudioSystem::ProcessCommand( const SimpleString& Command )
{
	if( Command == "duckcategory" )
	{
		HashedString Category = ConsoleManager::GetString();
		float Volume = ConsoleManager::GetFloat();
		float InterpolationTime = ConsoleManager::GetFloat();
		SetCategoryVolume( Category, Volume, InterpolationTime );
		return true;
	}
	else if( Command == "playsound" )
	{
		SimpleString Definition = ConsoleManager::GetString();
		float X = ConsoleManager::GetFloat();
		float Y = ConsoleManager::GetFloat();
		float Z = ConsoleManager::GetFloat();
		Play( Definition, Vector( X, Y, Z ) );
		return true;
	}
	else if( Command == "setreverb" )
	{
		SetReverbParams( ConsoleManager::GetString() );
		return true;
	}
#if BUILD_DEV
	else if( Command == "testaudiolimits" )
	{
		SimpleString Definition = ConsoleManager::GetString();
		float X = ConsoleManager::GetFloat();
		float Y = ConsoleManager::GetFloat();
		float Z = ConsoleManager::GetFloat();
		int NumInstances = ConsoleManager::GetInt();
		Vector Origin( X, Y, Z );
		for( int SoundIndex = 0; SoundIndex < NumInstances; ++SoundIndex )
		{
			Play( Definition, Origin );
		}
		return true;
	}
#endif
	else
	{
		return false;
	}
}
Пример #15
0
void ExerimentSimple::DrawScatterPlot()
{
    for(int i=0;i<(int)Data.size();i++)
    {
        Point2D NewPoint(Data[i][0], Data[i][1]);
        NewPoint.color = makeVector4f(Data[i][0], Data[i][1], 0.5, 1);
        viewer->addPoint(NewPoint);
    }

    //Axes
    Point2D Origin(0, 0);
    Origin.color = makeVector4f(1,1,1,1);
    Origin.size = 10;
    const int idOrigin = viewer->addPoint(Origin);

    Point2D XOff(1.1, 0);
    XOff.color = makeVector4f(1,0,0,1);
    XOff.size = 10;
    const int idXOff = viewer->addPoint(XOff);

    Point2D YOff(0, 1.1);
    YOff.color = makeVector4f(0,1,0,1);
    YOff.size = 10;
    const int idYOff = viewer->addPoint(YOff);

    //X-Axis
    Line Axis;
    Axis.vertices[0] = idOrigin;
    Axis.vertices[1] = idXOff;
    Axis.color = makeVector4f(1,1,1,1);
    Axis.thickness = 3;
    viewer->addLine(Axis);

    //Y-Axis
    Axis.vertices[1] = idYOff;
    viewer->addLine(Axis);

    // display changes
    viewer->refresh();
}
Пример #16
0
// return true if channel implements nsIHttpPushListener
bool
Http2PushedStream::TryOnPush()
{
    nsHttpTransaction *trans = mAssociatedTransaction->QueryHttpTransaction();
    if (!trans) {
        return false;
    }

    nsCOMPtr<nsIHttpChannelInternal> associatedChannel = do_QueryInterface(trans->HttpChannel());
    if (!associatedChannel) {
        return false;
    }

    if (!(trans->Caps() & NS_HTTP_ONPUSH_LISTENER)) {
        return false;
    }

    mDeferCleanupOnPush = true;
    nsCString uri = Origin() + Path();
    NS_DispatchToMainThread(new CallChannelOnPush(associatedChannel, uri, this));
    return true;
}
Пример #17
0
void R3CoordSystem::
Draw(void) const
{
    // Draw three rays
    R3BeginLine();
    R3LoadPoint(Origin());
    R3LoadPoint((Origin() + Axes().Axis(RN_X)));
    R3EndLine();
    R3BeginLine();
    R3LoadPoint(Origin());
    R3LoadPoint((Origin() + Axes().Axis(RN_Y)));
    R3EndLine();
    R3BeginLine();
    R3LoadPoint(Origin());
    R3LoadPoint((Origin() + Axes().Axis(RN_Z)));
    R3EndLine();
}
Пример #18
0
//---------------------------------------------------------------------------
void __fastcall TRightsFrame::DropDown()
{
  TCustomForm * Form = GetParentForm(this);
  // due to lack of better idea, we clear "default" and "cancel" flags of respective
  // form buttons to prevent them to handle ESC/ENTER keys.
  for (int Index = 0; Index < Form->ControlCount; Index++)
  {
    TButton * Button = dynamic_cast<TButton *>(Form->Controls[Index]);
    if (Button != NULL)
    {
      if (Button->Default)
      {
        assert(FDefaultButton == NULL);
        FDefaultButton = Button;
        Button->Default = false;
      }

      if (Button->Cancel)
      {
        assert(FCancelButton == NULL);
        FCancelButton = Button;
        Button->Cancel = false;
      }
    }
  }

  TPoint Origin(PopupParent->Left, PopupParent->Top + PopupParent->Height);
  Origin = Parent->ScreenToClient(PopupParent->Parent->ClientToScreen(Origin));
  if (Origin.x + Width > Parent->ClientWidth)
  {
    Origin.x += PopupParent->Width - Width;
  }
  Left = Origin.x;
  Top = Origin.y;
  Show();
  SetFocus();
}
Пример #19
0
Bool Camera::SetupView( const Area<F32> & mirrorRect, F32 y, Area<F32> & mRect)
{
  mRect = mirrorRect;

  if (rect.Width() && rect.Height())
  {
    halfHeight = ((F32) rect.Height()) * 0.5f;
    halfWidth  = ((F32) rect.Width())  * 0.5f;
    aspectHW   = halfHeight / halfWidth;

    if (!isIso)
    {
      projMatrix.SetProjection( nearPlane, farPlane * zoom, fov / zoom, aspectHW);

      if (Vid::renderState.status.clipVis)
      {
        halfHeight -= (F32) 64 * aspectHW;
        halfWidth  -= (F32) 64;
      }
      aspectHW   = halfHeight / halfWidth;

      invProjX = aspectHW / ( projMatrix.right.x * halfHeight);
      invProjY = 1 / (-projMatrix.up.y * halfHeight);
    }
    else
    {
      if (Vid::renderState.status.clipVis)
      {
        halfHeight -= (F32) 64 * aspectHW;
        halfWidth  -= (F32) 64;
      }
      aspectHW   = halfHeight / halfWidth;

      invProjX = 1 / ( projMatrix.right.x * halfHeight);
      invProjY = 1 / (-projMatrix.up.y * halfHeight);
    }
    invDepth  = 1.0f / (farPlane - nearPlane);

    F32 proj23 = projMatrix.frontw == 0 ? 1 : projMatrix.frontw;
    invProjX *= proj23;
    invProjY *= proj23;

    VertexTL verts[4], clipV[88];
    verts[0].vv.x = mRect.p0.x;
    verts[0].vv.y = y;
    verts[0].vv.z = mRect.p0.z;

    verts[1].vv.x = mRect.p1.x;
    verts[1].vv.y = y;
    verts[1].vv.z = mRect.p0.z;

    verts[2].vv.x = mRect.p1.x;
    verts[2].vv.y = y;
    verts[2].vv.z = mRect.p1.z;

    verts[3].vv.x = mRect.p0.x;
    verts[3].vv.y = y;
    verts[3].vv.z = mRect.p1.z;

    VertexTL * v, * ve = verts + 4;
    for (v = verts; v < ve; v++)
    {
      viewMatrix.Transform( v->vv);
    }

    // generate on screen water verts
    U16 clipI[88];
    U32 vCount = 4, iCount = 6;
    Vid::Clip::ToBuffer( clipV, clipI, verts, vCount, Vid::rectIndices, iCount);

    // generate on screen water rectangle
    mRect.Set( F32_MAX, F32_MAX, -F32_MAX, -F32_MAX);
    ve = clipV + vCount;
    for (v = clipV; v < ve; v++)
    {
      v->vv.x -= Origin().x;
      v->vv.y -= Origin().y;

      mRect.p0.x = Min<F32>( mRect.p0.x, v->vv.x);
      mRect.p1.x = Max<F32>( mRect.p1.x, v->vv.x);

      // onscreen y's are sign reversed
      mRect.p0.y = Min<F32>( mRect.p0.y, v->vv.y);
      mRect.p1.y = Max<F32>( mRect.p1.y, v->vv.y);
    }

    // real planes
    //
    F32 kx, ky, z = nearPlane;
    if (isIso)
    {
      kx = 1.0f * invProjX;
      ky = 1.0f * invProjY;
    }
    else
    {
      kx = (z * projMatrix.frontw + projMatrix.positw) * invProjX;
      ky = (z * projMatrix.frontw + projMatrix.positw) * invProjY;
    }

    frustrum[0].x = (-halfWidth)  * kx;
    frustrum[0].y = (-halfHeight) * ky;
    frustrum[0].z = z;

    frustrum[2].x = ( halfWidth)  * kx;
    frustrum[2].y = ( halfHeight) * ky;
    frustrum[2].z = z;

    Area<F32> cRect( mRect.p0.x * kx, mRect.p0.y * ky, mRect.p1.x * kx, mRect.p1.y * ky);
    
    frustrum[0].x = Max<F32>( cRect.p0.x, frustrum[0].x);
    frustrum[2].x = Min<F32>( cRect.p1.x, frustrum[2].x);

    // onscreen y's are sign reversed
    frustrum[0].y = Max<F32>( cRect.p0.y, frustrum[0].y);
    frustrum[2].y = Min<F32>( cRect.p1.y, frustrum[2].y);

    frustrum[1].x = frustrum[2].x;
    frustrum[1].y = frustrum[0].y;
    frustrum[1].z = z;

    frustrum[3].x = frustrum[0].x;
    frustrum[3].y = frustrum[2].y;
    frustrum[3].z = z;

    z  = farPlane * zoom;
    if (isIso)
    {
      kx = 1.0f * invProjX;
      ky = 1.0f * invProjY;
    }
    else
    {
      kx = (z * projMatrix.frontw + projMatrix.positw) * invProjX;
      ky = (z * projMatrix.frontw + projMatrix.positw) * invProjY;
    }

    frustrum[4].x = (-halfWidth)  * kx;
    frustrum[4].y = (-halfHeight) * ky;
    frustrum[4].z = z;

    frustrum[6].x = ( halfWidth)  * kx;
    frustrum[6].y = ( halfHeight) * ky;
    frustrum[6].z = z;

    cRect.Set( mRect.p0.x * kx, mRect.p0.y * ky, mRect.p1.x * kx, mRect.p1.y * ky);

    frustrum[4].x = Max<F32>( cRect.p0.x, frustrum[4].x);
    frustrum[6].x = Min<F32>( cRect.p1.x, frustrum[6].x);

    // onscreen y's are sign reversed
    frustrum[4].y = Max<F32>( cRect.p0.y, frustrum[4].y);
    frustrum[6].y = Min<F32>( cRect.p1.y, frustrum[6].y);

    frustrum[5].x = frustrum[6].x;
    frustrum[5].y = frustrum[4].y;
    frustrum[5].z = z;

    frustrum[7].x = frustrum[4].x;
    frustrum[7].y = frustrum[6].y;
    frustrum[7].z = z;

    Vector origin( 0.0, 0.0, 0.0);

    // near
    planes[0].Set( frustrum[0], frustrum[1], frustrum[2]);
    planes[0].Normalize();

    // far
    planes[1].Set( frustrum[4], frustrum[5], frustrum[6]);
    planes[1].Normalize();

    // left
    planes[2].Set( origin, frustrum[4], frustrum[7]);
    planes[2].Normalize();

    // right
    planes[3].Set( origin, frustrum[5], frustrum[6]);
    planes[3].Normalize();

    // top
    planes[4].Set( origin, frustrum[4], frustrum[5]);
    planes[4].Normalize();

    // bottom
    planes[5].Set( origin, frustrum[6], frustrum[7]);
    planes[5].Normalize();

    // fixup direction of plane equations
    for (U32 i = 0 ; i < 8; i++)
    {
      origin += frustrum[i];
    }
    // all plane equation normals must point towards 'origin'
    // which is the center of all the frustrum points
    origin *= 0.125f;

    for (i = 0; i < 6 ; i++)
    {
      if (planes[i].Evalue( origin) < 0.0f)
      {
        // change sign of plane equation
        planes[i] *= -1.0f;
      }
    }
  }
  if (Vid::curCamera == this)
  {
    Vid::SetCamera( *this, TRUE);
  }

  mRect.p0.x += Origin().x;
  mRect.p0.y += Origin().y;
  mRect.p1.x += Origin().x;
  mRect.p1.y += Origin().y;

  return frustrum[6].x < frustrum[4].x
      || frustrum[4].x > frustrum[6].x
      || frustrum[6].y > frustrum[4].y
      || frustrum[4].y < frustrum[6].y ? FALSE : TRUE;
}
Пример #20
0
	    /** @brief Origin of this Binding.
	     *
	     * @return the Origin of this Binding.
	     */
	    Origin origin() const
	    {
		return Origin(m_origin);
	    }
void nsHttpConnectionInfo::BuildHashKey()
{
    //
    // build hash key:
    //
    // the hash key uniquely identifies the connection type.  two connections
    // are "equal" if they end up talking the same protocol to the same server
    // and are both used for anonymous or non-anonymous connection only;
    // anonymity of the connection is setup later from nsHttpChannel::AsyncOpen
    // where we know we use anonymous connection (LOAD_ANONYMOUS load flag)
    //

    const char *keyHost;
    int32_t keyPort;

    if (mUsingHttpProxy && !mUsingConnect) {
        keyHost = ProxyHost();
        keyPort = ProxyPort();
    } else {
        keyHost = Origin();
        keyPort = OriginPort();
    }

    // The hashkey has 4 fields followed by host connection info
    // byte 0 is P/T/. {P,T} for Plaintext/TLS Proxy over HTTP
    // byte 1 is S/. S is for end to end ssl such as https:// uris
    // byte 2 is A/. A is for an anonymous channel (no cookies, etc..)
    // byte 3 is P/. P is for a private browising channel
    // byte 4 is I/. I is for insecure scheme on TLS for http:// uris
    // byte 5 is X/. X is for disallow_spdy flag

    mHashKey.AssignLiteral("......");
    mHashKey.Append(keyHost);
    if (!mNetworkInterfaceId.IsEmpty()) {
        mHashKey.Append('(');
        mHashKey.Append(mNetworkInterfaceId);
        mHashKey.Append(')');
    }
    mHashKey.Append(':');
    mHashKey.AppendInt(keyPort);
    if (!mUsername.IsEmpty()) {
        mHashKey.Append('[');
        mHashKey.Append(mUsername);
        mHashKey.Append(']');
    }

    if (mUsingHttpsProxy) {
        mHashKey.SetCharAt('T', 0);
    } else if (mUsingHttpProxy) {
        mHashKey.SetCharAt('P', 0);
    }
    if (mEndToEndSSL) {
        mHashKey.SetCharAt('S', 1);
    }

    // NOTE: for transparent proxies (e.g., SOCKS) we need to encode the proxy
    // info in the hash key (this ensures that we will continue to speak the
    // right protocol even if our proxy preferences change).
    //
    // NOTE: for SSL tunnels add the proxy information to the cache key.
    // We cannot use the proxy as the host parameter (as we do for non SSL)
    // because this is a single host tunnel, but we need to include the proxy
    // information so that a change in proxy config will mean this connection
    // is not reused

    // NOTE: Adding the username and the password provides a means to isolate
    // keep-alive to the URL bar domain as well: If the username is the URL bar
    // domain, keep-alive connections are not reused by resources bound to
    // different URL bar domains as the respective hash keys are not matching.

    if ((!mUsingHttpProxy && ProxyHost()) ||
        (mUsingHttpProxy && mUsingConnect)) {
        mHashKey.AppendLiteral(" (");
        mHashKey.Append(ProxyType());
        mHashKey.Append(':');
        mHashKey.Append(ProxyHost());
        mHashKey.Append(':');
        mHashKey.AppendInt(ProxyPort());
        mHashKey.Append(')');
        mHashKey.Append('[');
        mHashKey.Append(ProxyUsername());
        mHashKey.Append(':');
        const char* password = ProxyPassword();
        if (strlen(password) > 0) {
            nsAutoCString digestedPassword;
            nsresult rv = SHA256(password, digestedPassword);
            if (rv == NS_OK) {
                mHashKey.Append(digestedPassword);
            }
        }
        mHashKey.Append(']');
    }

    if(!mRoutedHost.IsEmpty()) {
        mHashKey.AppendLiteral(" <ROUTE-via ");
        mHashKey.Append(mRoutedHost);
        mHashKey.Append(':');
        mHashKey.AppendInt(mRoutedPort);
        mHashKey.Append('>');
    }

    if (!mNPNToken.IsEmpty()) {
        mHashKey.AppendLiteral(" {NPN-TOKEN ");
        mHashKey.Append(mNPNToken);
        mHashKey.AppendLiteral("}");
    }

    nsAutoCString originAttributes;
    mOriginAttributes.CreateSuffix(originAttributes);
    mHashKey.Append(originAttributes);
}
Пример #22
0
bool Aimbot::ScanForTarget()
{
	AimpointInfo results[64];
	float fovToCheck = max(ImportExport::Variables[BOXFOV]->FloatValue(), this->FOV);
	std::find_if(begin(ImportExport::Entities->Players()), end(ImportExport::Entities->Players()), [&] (const IPlayer* p) -> bool {
		if(p->IsValid() && p->Health() > 0 && p->IsEnemyOf(ImportExport::User) && p->Id() != ImportExport::User->Id())
		{
			auto c = (p->Master() != nullptr ? p->Master() : p);
			auto prediction = Predict(c);
			if(!prediction.first) {
				return false;
			}
			idVec3 predictedOrigin = c->Origin() + prediction.second;
			if(IsInFov(predictedOrigin, fovToCheck) && ImportExport::User->Weapon().MaxRange() >= ImportExport::User->DistanceTo(predictedOrigin))
			{
				auto aimpoints = p->Aimpoints();
				for(vector<idVec3>::size_type j = 0; j < aimpoints.size(); ++j)
				{
					idVec3 testOrigin = predictedOrigin + aimpoints[j];
					if(ImportExport::User->CanSee(testOrigin, p->Id()))
					{
						results[p->Id()] = AimpointInfo(j, testOrigin, ImportExport::User->GetScore(testOrigin) + j / 2.0);
						return true;
					}
				}
			}
		}
		return false;
	});
	
	int bestTarget = -1;
	double bestScore;
	int boxBestTarget = -1;
	double boxBestScore;
	for (int i = 0; i < 64; ++i)
	{
		if(results[i].valid)
		{
			double curScore = results[i].score;
			if(boxBestTarget == -1 || curScore < boxBestScore)
			{
				boxBestTarget = i;
				boxBestScore = curScore;
			}
			if(IsInFov(results[i].v) && (bestTarget == -1 || curScore < bestScore))
			{
				bestTarget = i;
				bestScore = curScore;
			}
		}
	}

	if(boxBestTarget != -1)
	{
		_BoxTargetValid = true;
		_BoxTargetOrigin = results[boxBestTarget].v;
		_BoxTarget = ImportExport::Entities->GetPlayer(boxBestTarget);
	}
	else
		_BoxTargetValid = false;

	if(bestTarget != -1)
	{
		AimpointInfo& targetInfo = results[bestTarget];
		_CurrentTarget = ImportExport::Entities->GetPlayer(bestTarget);
		_TargetOrigin = targetInfo.v;
		//FIXME: doesn't consider if the target is a player or its master IAimable
		_TargetAimpoint = _CurrentTarget->Aimpoints()[targetInfo.idx];
		return true;
	}

	_CurrentTarget = nullptr;
	return false;
}
Пример #23
0
void Experiment1_1::DrawScatterPlot()
{
    max_Data = makeVector2f(Data[0][0], Data[0][1]);
    min_Data = makeVector2f(Data[0][0], Data[0][1]);
    for(int i=0;i<(int)Data.size();i++)
    {
        if(i>0)
        {
          if (Data[i][0] > max_Data [0])
          {
            max_Data[0]=Data[i][0];
          }
          if (Data[i][1] > max_Data [1])
          {
            max_Data[1]=Data[i][1];
          }
          if (Data[i][0] < min_Data [0])
          {
            min_Data[0]=Data[i][0];
          }
          if (Data[i][1] < min_Data [1])
          {
            min_Data[1]=Data[i][1];
          }

        }
    }
    DataColorRange = makeVector2f(max_Data[0]-min_Data[0], max_Data[1]-min_Data[1]);
    if (max_Data[0]<0)
        max_Data[0]=0;
    if (max_Data[1]<0)
        max_Data[1]=0;
    if (min_Data[0]>0)
        min_Data[0]=0;
    if (min_Data[1]>0)
        min_Data[1]=0;

    for(int i=0;i<(int)Data.size();i++)
    {
        Point2D NewPoint(Data[i][0], Data[i][1]);
        NewPoint.color = makeVector4f(Data[i][0]/DataColorRange[0], Data[i][1]/DataColorRange[1], 0.5 /*((float) i)/Data.size()*/, 1);
        viewer->addPoint(NewPoint);
    }
    //Axes
    Point2D Origin(0, 0);
    Origin.color = makeVector4f(1,1,1,1);
    Origin.size = 10;
    const int idOrigin = viewer->addPoint(Origin);

    Point2D XNeg(min_Data[0], 0);
    Point2D XPos(max_Data[0], 0);
    XNeg.color = makeVector4f(1,0,0,1);
    XPos.color = makeVector4f(1,0,0,1);
    XNeg.size = 10;
    XPos.size = 10;
    const int idXNeg = viewer->addPoint(XNeg);
    const int idXPos = viewer->addPoint(XPos);

    Point2D YNeg(0, min_Data[1]);
    Point2D YPos(0, max_Data[1]);
    YPos.color = makeVector4f(0,1,0,1);
    YNeg.color = makeVector4f(0,1,0,1);
    YPos.size = 10;
    YNeg.size = 10;
    const int idYPos = viewer->addPoint(YNeg);
    const int idYNeg = viewer->addPoint(YPos);

    //X-Axis
    Line Axis;
    Axis.vertices[0] = idXNeg;
    Axis.vertices[1] = idXPos;
    Axis.color = makeVector4f(1,1,1,1);
    Axis.thickness = 3;
    viewer->addLine(Axis);

    //Y-Axis
    Axis.vertices[0] = idYNeg;
    Axis.vertices[1] = idYPos;
    viewer->addLine(Axis);

    // display changes
    viewer->refresh();
}
Пример #24
0
void dx103DFluidRenderer::Draw(const dx103DFluidData &FluidData)
{
	//	We don't need ZB anyway
	RCache.set_ZB(0);

	const dx103DFluidData::Settings &VolumeSettings = FluidData.GetSettings();
	const bool bRenderFire = (VolumeSettings.m_SimulationType == dx103DFluidData::ST_FIRE);

	FogLighting  LightData;

	CalculateLighting(FluidData, LightData);


	const Fmatrix &transform = FluidData.GetTransform();

	RCache.set_xform_world( transform );

	//pColorTexVar->SetResource(pSourceTexSRV);

	//	Set shader element to set up all necessary constants to constant buffer
	//	If you change constant buffer layout make sure this hack works ok.
	RCache.set_Element(m_RendererTechnique[RS_CompRayData_Back]);

	// Set some variables required by the shaders:
	//=========================================================================

	// The near and far planes are used to unproject the scene's z-buffer values
	//pZNearVar->SetFloat(g_zNear);
	RCache.set_c(strZNear, VIEWPORT_NEAR);
	//pZFarVar->SetFloat(g_zFar);
	RCache.set_c(strZFar, g_pGamePersistent->Environment().CurrentEnv->far_plane);

	//D3DXMATRIX worldView = g_gridWorld * g_View;
	D3DXMATRIX gridWorld;
	//D3DXMatrixTranspose(&gridWorld, (D3DXMATRIX*)&transform);
	gridWorld = *(D3DXMATRIX*)&transform;
	D3DXMATRIX View;
	//D3DXMatrixTranspose(&View, (D3DXMATRIX*)&RCache.xforms.m_v);
	View = *(D3DXMATRIX*)&RCache.xforms.m_v;
	D3DXMATRIX WorldView = gridWorld * View;

	//	Modified later
	//Fmatrix	WorldView = RCache.xforms.m_wv;
	//RCache.set_xform_world( transform );

	// The length of one of the axis of the worldView matrix is the length of longest side of the box
	//  in view space. This is used to convert the length of a ray from view space to grid space.
	//D3DXVECTOR3 worldXaxis = D3DXVECTOR3(worldView._11, worldView._12, worldView._13);
	D3DXVECTOR3 worldXaxis = D3DXVECTOR3(WorldView._11, WorldView._12, WorldView._13);
	float worldScale = D3DXVec3Length(&worldXaxis);
	//pGridScaleFactorVar->SetFloat( worldScale );
	RCache.set_c(strGridScaleFactor, worldScale);

	// We prepend the current world matrix with this other matrix which adds an offset (-0.5, -0.5, -0.5)
	//  and scale factors to account for unequal number of voxels on different sides of the volume box. 
	// This is because we want to preserve the aspect ratio of the original simulation grid when 
	//  raytracing through it.
	//worldView = m_gridMatrix * worldView;
	WorldView = m_gridMatrix * WorldView;
	//WorldView.mulB_44(m_gridMatrix);

//	Fmatrix temp;
//	temp = transform;
//	temp.mulB_44(m_gridMatrix);

//	RCache.set_xform_world( temp );
//	return;
	

	// worldViewProjection is used to transform the volume box to screen space
	//D3DXMATRIX WorldViewProjection;
	D3DXMATRIX WorldViewProjection;
	//Fmatrix WorldViewProjection;
	//worldViewProjection = worldView * g_Projection;
	D3DXMATRIX Projection;
	//D3DXMatrixTranspose(&Projection, (D3DXMATRIX*)&RCache.xforms.m_p);
	Projection = *(D3DXMATRIX*)&RCache.xforms.m_p;
	WorldViewProjection = WorldView * Projection;
	//WorldViewProjection.mul(RCache.xforms.m_p, WorldView);
	//pWorldViewProjectionVar->SetMatrix( (float*)&worldViewProjection );
	//	NVidia used different matrix orientation
	//WorldViewProjection.transpose();
	//RCache.set_c(strWorldViewProjection, WorldViewProjection);
	RCache.set_c(strWorldViewProjection, *(Fmatrix*)&WorldViewProjection);
	//WorldViewProjection.transpose();

	// invWorldViewProjection is used to transform positions in the "near" plane into grid space
	//D3DXMATRIX invWorldViewProjection;
	D3DXMATRIX InvWorldViewProjection;
	//Fmatrix InvWorldViewProjection;
	//WorldViewProjection.transpose();
	D3DXMatrixInverse((D3DXMATRIX*)&InvWorldViewProjection, NULL, (D3DXMATRIX*)&WorldViewProjection);
	//WorldViewProjection.transpose();
	//pInvWorldViewProjectionVar->SetMatrix((float*)&invWorldViewProjection);
	//InvWorldViewProjection.transpose();
	//RCache.set_c(strInvWorldViewProjection, InvWorldViewProjection);
	RCache.set_c(strInvWorldViewProjection, *(Fmatrix*)&InvWorldViewProjection);
	//InvWorldViewProjection.transpose();

	// Compute the inverse of the worldView matrix 
	//D3DXMATRIX worldViewInv;
	D3DXMATRIX WorldViewInv;
	//Fmatrix WorldViewInv;
	D3DXMatrixInverse((D3DXMATRIX*)&WorldViewInv, NULL, (D3DXMATRIX*)&WorldView);
	// Compute the eye's position in "grid space" (the 0-1 texture coordinate cube)
	//D3DXVECTOR4 eyeInGridSpace;
	//D3DXVECTOR3 origin(0,0,0);
	D3DXVECTOR4 EyeInGridSpace;
	D3DXVECTOR3 Origin(0,0,0);
	//Fvector4 EyeInGridSpace;
	//Fvector3 Origin = Fvector3().set(0,0,0);
	//WorldViewInv.transpose();
	D3DXVec3Transform((D3DXVECTOR4*)&EyeInGridSpace, (D3DXVECTOR3*)&Origin, (D3DXMATRIX*)&WorldViewInv);
	//WorldViewInv.transpose();
	//pEyeOnGridVar->SetFloatVector((float*)&eyeInGridSpace);
	RCache.set_c(strEyeOnGrid, *(Fvector4*)&EyeInGridSpace);

	float color[4] = {0, 0, 0, 0 };


	// Ray cast and render to a temporary buffer
	//=========================================================================

	// Partial init of viewport struct used below
	//D3D10_VIEWPORT rtViewport;
	//rtViewport.TopLeftX = 0;
	//rtViewport.TopLeftY = 0;
	//rtViewport.MinDepth = 0;
	//rtViewport.MaxDepth = 1;


	// Compute the ray data required by the raycasting pass below.
	//  This function will render to a buffer of float4 vectors, where
	//  xyz is starting position of the ray in grid space
	//  w is the length of the ray in view space
	ComputeRayData();


	// Do edge detection on this image to find any 
	//  problematic areas where we need to raycast at higher resolution
	ComputeEdgeTexture();


	// Raycast into the temporary render target: 
	//  raycasting is done at the smaller resolution, using a fullscreen quad
	//m_pD3DDevice->ClearRenderTargetView( pRayCastRTV, color );
	HW.pDevice->ClearRenderTargetView( RT[RRT_RayCastTex]->pRT, color );
	//m_pD3DDevice->OMSetRenderTargets( 1, &pRayCastRTV , NULL ); 
	CRenderTarget* pTarget = RImplementation.Target;
	pTarget->u_setrt(RT[RRT_RayCastTex],0,0,0);		// LDR RT

	//rtViewport.Width = renderTextureWidth;
	//rtViewport.Height = renderTextureHeight;
	//m_pD3DDevice->RSSetViewports(1,&rtViewport);
	RImplementation.rmNormal();

	//pTechnique->GetPassByName("QuadRaycast")->Apply(0);
	if (bRenderFire)
		RCache.set_Element(m_RendererTechnique[RS_QuadRaycastFire]);
	else
		RCache.set_Element(m_RendererTechnique[RS_QuadRaycastFog]);

	//pRTWidthVar->SetFloat((float)renderTextureWidth);
	RCache.set_c(strRTWidth, (float)m_iRenderTextureWidth);
	//pRTHeightVar->SetFloat((float)renderTextureHeight);
	RCache.set_c(strRTHeight, (float)m_iRenderTextureHeight);

	//pRayDataSmallVar->SetResource(pRayDataSmallSRV);

	DrawScreenQuad();


	// Render to the back buffer sampling from the raycast texture that we just created
	//  If and edge was detected at the current pixel we will raycast again to avoid
	//  smoke aliasing artifacts at scene edges
	//ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView();
	//ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView();
	//m_pD3DDevice->OMSetRenderTargets( 1, &pRTV , pDSV ); 
	//	Restore render state
	if( !RImplementation.o.dx10_msaa )
		pTarget->u_setrt( pTarget->rt_Generic_0,0,0,HW.pBaseZB);		// LDR RT
	else
		pTarget->u_setrt( pTarget->rt_Generic_0,0,0,pTarget->rt_MSAADepth->pZRT);		// LDR RT

	if (bRenderFire)
		RCache.set_Element(m_RendererTechnique[RS_QuadRaycastCopyFire]);
	else
		RCache.set_Element(m_RendererTechnique[RS_QuadRaycastCopyFog]);

	//rtViewport.Width = g_Width;
	//rtViewport.Height = g_Height;
	//m_pD3DDevice->RSSetViewports(1,&rtViewport);
	RImplementation.rmNormal();

	//pRTWidthVar->SetFloat((float)g_Width);
	RCache.set_c(strRTWidth, (float)Device.dwWidth);
	//pRTHeightVar->SetFloat((float)g_Height);
	RCache.set_c(strRTHeight, (float)Device.dwHeight);

	RCache.set_c(strDiffuseLight, LightData.m_vLightIntencity.x, LightData.m_vLightIntencity.y, LightData.m_vLightIntencity.z, 1.0f);

	//pRayCastVar->SetResource(pRayCastSRV);
	//pEdgeVar->SetResource(pEdgeSRV);

	//pTechnique->GetPassByName("QuadRaycastCopy")->Apply(0);
	DrawScreenQuad();
}
void FThumbnailPreviewScene::GetView(FSceneViewFamily* ViewFamily, int32 X, int32 Y, uint32 SizeX, uint32 SizeY) const
{
    check(ViewFamily);

    FIntRect ViewRect(
        FMath::Max<int32>(X,0),
        FMath::Max<int32>(Y,0),
        FMath::Max<int32>(X+SizeX,0),
        FMath::Max<int32>(Y+SizeY,0));

    if (ViewRect.Width() > 0 && ViewRect.Height() > 0)
    {
        const float FOVDegrees = 30.f;
        const float HalfFOVRadians = FMath::DegreesToRadians<float>(FOVDegrees) * 0.5f;
        static_assert((int32)ERHIZBuffer::IsInverted != 0, "Check NearPlane and Projection Matrix");
        const float NearPlane = 1.0f;
        FMatrix ProjectionMatrix = FReversedZPerspectiveMatrix(
                                       HalfFOVRadians,
                                       1.0f,
                                       1.0f,
                                       NearPlane
                                   );

        FVector Origin(0);
        float OrbitPitch = 0;
        float OrbitYaw = 0;
        float OrbitZoom = 0;
        GetViewMatrixParameters(FOVDegrees, Origin, OrbitPitch, OrbitYaw, OrbitZoom);

        // Ensure a minimum camera distance to prevent problems with really small objects
        const float MinCameraDistance = 48;
        OrbitZoom = FMath::Max<float>(MinCameraDistance, OrbitZoom);

        const FRotator RotationOffsetToViewCenter(0.f, 90.f, 0.f);
        FMatrix ViewRotationMatrix = FRotationMatrix( FRotator(0, OrbitYaw, 0) ) *
                                     FRotationMatrix( FRotator(0, 0, OrbitPitch) ) *
                                     FTranslationMatrix( FVector(0, OrbitZoom, 0) ) *
                                     FInverseRotationMatrix( RotationOffsetToViewCenter );

        ViewRotationMatrix = ViewRotationMatrix * FMatrix(
                                 FPlane(0,	0,	1,	0),
                                 FPlane(1,	0,	0,	0),
                                 FPlane(0,	1,	0,	0),
                                 FPlane(0,	0,	0,	1));

        Origin -= ViewRotationMatrix.InverseTransformPosition( FVector::ZeroVector );
        ViewRotationMatrix = ViewRotationMatrix.RemoveTranslation();

        FSceneViewInitOptions ViewInitOptions;
        ViewInitOptions.ViewFamily = ViewFamily;
        ViewInitOptions.SetViewRectangle(ViewRect);
        ViewInitOptions.ViewOrigin = -Origin;
        ViewInitOptions.ViewRotationMatrix = ViewRotationMatrix;
        ViewInitOptions.ProjectionMatrix = ProjectionMatrix;
        ViewInitOptions.BackgroundColor = FLinearColor::Black;

        FSceneView* NewView = new FSceneView(ViewInitOptions);

        ViewFamily->Views.Add(NewView);

        NewView->StartFinalPostprocessSettings( ViewInitOptions.ViewOrigin );
        NewView->EndFinalPostprocessSettings(ViewInitOptions);

        FFinalPostProcessSettings::FCubemapEntry& CubemapEntry = *new(NewView->FinalPostProcessSettings.ContributingCubemaps) FFinalPostProcessSettings::FCubemapEntry;
        CubemapEntry.AmbientCubemap = GUnrealEd->GetThumbnailManager()->AmbientCubemap;
        const float AmbientCubemapIntensity = 1.69;
        CubemapEntry.AmbientCubemapTintMulScaleValue = FLinearColor::White * AmbientCubemapIntensity;

        // Tell the texture streaming system about this thumbnail view, so the textures will stream in as needed
        // NOTE: Sizes may not actually be in screen space depending on how the thumbnail ends up stretched by the UI.  Not a big deal though.
        // NOTE: Textures still take a little time to stream if the view has not been re-rendered recently, so they may briefly appear blurry while mips are prepared
        // NOTE: Content Browser only renders thumbnails for loaded assets, and only when the mouse is over the panel. They'll be frozen in their last state while the mouse cursor is not over the panel.  This is for performance reasons
        IStreamingManager::Get().AddViewInformation( Origin, SizeX, SizeX / FMath::Tan( FOVDegrees ) );
    }
}
Пример #26
0
nsresult
DOMStorageDBThread::DBOperation::Perform(DOMStorageDBThread* aThread)
{
  nsresult rv;

  switch (mType) {
  case opPreload:
  case opPreloadUrgent:
  {
    // Already loaded?
    if (mCache->Loaded()) {
      break;
    }

    StatementCache* statements;
    if (MOZ_UNLIKELY(NS_IsMainThread())) {
      statements = &aThread->mReaderStatements;
    } else {
      statements = &aThread->mWorkerStatements;
    }

    // OFFSET is an optimization when we have to do a sync load
    // and cache has already loaded some parts asynchronously.
    // It skips keys we have already loaded.
    nsCOMPtr<mozIStorageStatement> stmt = statements->GetCachedStatement(
        "SELECT key, value FROM webappsstore2 "
        "WHERE originAttributes = :originAttributes AND originKey = :originKey "
        "ORDER BY key LIMIT -1 OFFSET :offset");
    NS_ENSURE_STATE(stmt);
    mozStorageStatementScoper scope(stmt);

    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"),
                                    mCache->OriginSuffix());
    NS_ENSURE_SUCCESS(rv, rv);

    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"),
                                    mCache->OriginNoSuffix());
    NS_ENSURE_SUCCESS(rv, rv);

    rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("offset"),
                               static_cast<int32_t>(mCache->LoadedCount()));
    NS_ENSURE_SUCCESS(rv, rv);

    bool exists;
    while (NS_SUCCEEDED(rv = stmt->ExecuteStep(&exists)) && exists) {
      nsAutoString key;
      rv = stmt->GetString(0, key);
      NS_ENSURE_SUCCESS(rv, rv);

      nsAutoString value;
      rv = stmt->GetString(1, value);
      NS_ENSURE_SUCCESS(rv, rv);

      if (!mCache->LoadItem(key, value)) {
        break;
      }
    }

    mCache->LoadDone(NS_OK);
    break;
  }

  case opGetUsage:
  {
    nsCOMPtr<mozIStorageStatement> stmt = aThread->mWorkerStatements.GetCachedStatement(
      "SELECT SUM(LENGTH(key) + LENGTH(value)) FROM webappsstore2 "
      "WHERE (originAttributes || ':' || originKey) LIKE :usageOrigin"
    );
    NS_ENSURE_STATE(stmt);

    mozStorageStatementScoper scope(stmt);

    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("usageOrigin"),
                                    mUsage->OriginScope());
    NS_ENSURE_SUCCESS(rv, rv);

    bool exists;
    rv = stmt->ExecuteStep(&exists);
    NS_ENSURE_SUCCESS(rv, rv);

    int64_t usage = 0;
    if (exists) {
      rv = stmt->GetInt64(0, &usage);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    mUsage->LoadUsage(usage);
    break;
  }

  case opAddItem:
  case opUpdateItem:
  {
    MOZ_ASSERT(!NS_IsMainThread());

    nsCOMPtr<mozIStorageStatement> stmt = aThread->mWorkerStatements.GetCachedStatement(
      "INSERT OR REPLACE INTO webappsstore2 (originAttributes, originKey, scope, key, value) "
      "VALUES (:originAttributes, :originKey, :scope, :key, :value) "
    );
    NS_ENSURE_STATE(stmt);

    mozStorageStatementScoper scope(stmt);

    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"),
                                    mCache->OriginSuffix());
    NS_ENSURE_SUCCESS(rv, rv);
    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"),
                                    mCache->OriginNoSuffix());
    NS_ENSURE_SUCCESS(rv, rv);
    // Filling the 'scope' column just for downgrade compatibility reasons
    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("scope"),
                                    Scheme0Scope(mCache));
    NS_ENSURE_SUCCESS(rv, rv);
    rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"),
                                mKey);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = stmt->BindStringByName(NS_LITERAL_CSTRING("value"),
                                mValue);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = stmt->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    MonitorAutoLock monitor(aThread->mThreadObserver->GetMonitor());
    aThread->mOriginsHavingData.PutEntry(Origin());
    break;
  }

  case opRemoveItem:
  {
    MOZ_ASSERT(!NS_IsMainThread());

    nsCOMPtr<mozIStorageStatement> stmt = aThread->mWorkerStatements.GetCachedStatement(
      "DELETE FROM webappsstore2 "
      "WHERE originAttributes = :originAttributes AND originKey = :originKey "
        "AND key = :key "
    );
    NS_ENSURE_STATE(stmt);
    mozStorageStatementScoper scope(stmt);

    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"),
                                    mCache->OriginSuffix());
    NS_ENSURE_SUCCESS(rv, rv);
    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"),
                                    mCache->OriginNoSuffix());
    NS_ENSURE_SUCCESS(rv, rv);
    rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"),
                                mKey);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = stmt->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    break;
  }

  case opClear:
  {
    MOZ_ASSERT(!NS_IsMainThread());

    nsCOMPtr<mozIStorageStatement> stmt = aThread->mWorkerStatements.GetCachedStatement(
      "DELETE FROM webappsstore2 "
      "WHERE originAttributes = :originAttributes AND originKey = :originKey"
    );
    NS_ENSURE_STATE(stmt);
    mozStorageStatementScoper scope(stmt);

    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"),
                                    mCache->OriginSuffix());
    NS_ENSURE_SUCCESS(rv, rv);
    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"),
                                    mCache->OriginNoSuffix());
    NS_ENSURE_SUCCESS(rv, rv);

    rv = stmt->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    MonitorAutoLock monitor(aThread->mThreadObserver->GetMonitor());
    aThread->mOriginsHavingData.RemoveEntry(Origin());
    break;
  }

  case opClearAll:
  {
    MOZ_ASSERT(!NS_IsMainThread());

    nsCOMPtr<mozIStorageStatement> stmt = aThread->mWorkerStatements.GetCachedStatement(
      "DELETE FROM webappsstore2"
    );
    NS_ENSURE_STATE(stmt);
    mozStorageStatementScoper scope(stmt);

    rv = stmt->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    MonitorAutoLock monitor(aThread->mThreadObserver->GetMonitor());
    aThread->mOriginsHavingData.Clear();
    break;
  }

  case opClearMatchingOrigin:
  {
    MOZ_ASSERT(!NS_IsMainThread());

    nsCOMPtr<mozIStorageStatement> stmt = aThread->mWorkerStatements.GetCachedStatement(
      "DELETE FROM webappsstore2"
      " WHERE originKey GLOB :scope"
    );
    NS_ENSURE_STATE(stmt);
    mozStorageStatementScoper scope(stmt);

    rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("scope"),
                                    mOrigin + NS_LITERAL_CSTRING("*"));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = stmt->Execute();
    NS_ENSURE_SUCCESS(rv, rv);

    // No need to selectively clear mOriginsHavingData here.  That hashtable only
    // prevents preload for scopes with no data.  Leaving a false record in it has
    // a negligible effect on performance.
    break;
  }

  case opClearMatchingOriginAttributes:
  {
    MOZ_ASSERT(!NS_IsMainThread());

    // Register the ORIGIN_ATTRS_PATTERN_MATCH function, initialized with the pattern
    nsCOMPtr<mozIStorageFunction> patternMatchFunction(
      new OriginAttrsPatternMatchSQLFunction(mOriginPattern));

    rv = aThread->mWorkerConnection->CreateFunction(
      NS_LITERAL_CSTRING("ORIGIN_ATTRS_PATTERN_MATCH"), 1, patternMatchFunction);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<mozIStorageStatement> stmt = aThread->mWorkerStatements.GetCachedStatement(
      "DELETE FROM webappsstore2"
      " WHERE ORIGIN_ATTRS_PATTERN_MATCH(originAttributes)"
    );

    if (stmt) {
      mozStorageStatementScoper scope(stmt);
      rv = stmt->Execute();
    } else {
      rv = NS_ERROR_UNEXPECTED;
    }

    // Always remove the function
    aThread->mWorkerConnection->RemoveFunction(
      NS_LITERAL_CSTRING("ORIGIN_ATTRS_PATTERN_MATCH"));

    NS_ENSURE_SUCCESS(rv, rv);

    // No need to selectively clear mOriginsHavingData here.  That hashtable only
    // prevents preload for scopes with no data.  Leaving a false record in it has
    // a negligible effect on performance.
    break;
  }

  default:
    NS_ERROR("Unknown task type");
    break;
  }

  return NS_OK;
}
Пример #27
0
void GradientLayer::draw(Graphics* const TheGraphics, const Pnt2f& TopLeft, const Pnt2f& BottomRight, const Real32 Opacity) const
{
	if(getMFColors()->size() == getMFStops()->size())
	{
		if(getMFColors()->size() == 1)
		{
			TheGraphics->drawQuad(TopLeft, Pnt2f(BottomRight.x(), TopLeft.y()), BottomRight, Pnt2f(TopLeft.x(), BottomRight.y()), getColors(0), getColors(0), getColors(0), getColors(0), Opacity);
		}
		else
		{
			Pnt2f StartPosition= TopLeft;
			StartPosition[0] += getStartPosition()[0]*(BottomRight[0] - TopLeft[0]);
			StartPosition[1] += getStartPosition()[1]*(BottomRight[1] - TopLeft[1]);
			Pnt2f EndPosition= TopLeft;
			EndPosition[0] += getEndPosition()[0]*(BottomRight[0] - TopLeft[0]);
			EndPosition[1] += getEndPosition()[1]*(BottomRight[1] - TopLeft[1]);
			
			//Calculate the coordinate system
			Vec2f u(EndPosition-StartPosition);
			u.normalize();
			Vec3f v3D(Vec3f(u.x(), u.y(), 0.0f).cross(Vec3f(0.0,0.0,-1.0)));
			Vec2f v(v3D.x(), v3D.y());
			Matrix22<Real32> CoordinateSystem(u.x(), u.y(), v.x(), v.y());

			Pnt2f Min;
			Pnt2f Max;
			{
				//Calculate the bounding box in the new coordinate system
				Pnt2f UVTopLeft(CoordinateSystem*TopLeft), 
					UVBottomRight(CoordinateSystem*BottomRight), 
					UVTopRight(CoordinateSystem*Vec2f(BottomRight.x(), TopLeft.y())),
					UVBottomLeft(CoordinateSystem*Vec2f(TopLeft.x(), BottomRight.y()));


				Min.setValues( osgMin(UVTopLeft.x(), osgMin(UVBottomRight.x(), osgMin(UVTopRight.x(), UVBottomLeft.x()))),
							   osgMin(UVTopLeft.y(), osgMin(UVBottomRight.y(), osgMin(UVTopRight.y(), UVBottomLeft.y()))));
				Max.setValues( osgMax(UVTopLeft.x(), osgMax(UVBottomRight.x(), osgMax(UVTopRight.x(), UVBottomLeft.x()))),
							   osgMax(UVTopLeft.y(), osgMax(UVBottomRight.y(), osgMax(UVTopRight.y(), UVBottomLeft.y()))));
			}

			Pnt2f Origin(CoordinateSystem.inverse() * Min);
			Real32 PreStartLength(((CoordinateSystem*StartPosition).x()-Min.x())/(Max.x() - Min.x())),
				   PostEndLength((Max.x()- (CoordinateSystem*EndPosition).x())/(Max.x() - Min.x())),
				   GradientLength(1.0f-PostEndLength-PreStartLength);
			
			if(getSpreadMethod() == SPREAD_REFLECT||
			   getSpreadMethod() == SPREAD_REPEAT)
			{
				//Code for drawing the Gradient with Repeating/Reflection
					//Determine the Number of Repeats
					UInt32 RepeatCount = static_cast<UInt32>(osgCeil(1.0f/GradientLength));

					//Determine the relative location in the gradient that the Start left is at
					Real32 StartGradientLocation = PreStartLength - GradientLength * osgCeil(PreStartLength/GradientLength);

					//Determine whether the start is a reflection or normal
					bool isReflection = getSpreadMethod() == SPREAD_REFLECT && static_cast<UInt32>(osgCeil(PreStartLength/GradientLength))%2==1;

					for(UInt32 i(0) ; i<RepeatCount ; ++i)
					{
						if(isReflection)
						{
							drawGradient(TheGraphics, Origin, Max-Min,u,StartGradientLocation+GradientLength*(i+1),StartGradientLocation+GradientLength*i,Opacity);					
						}
						else
						{
							drawGradient(TheGraphics, Origin, Max-Min,u,StartGradientLocation+GradientLength*i,StartGradientLocation+GradientLength*(i+1),Opacity);					
						}

						if(getSpreadMethod() == SPREAD_REFLECT)
						{
							isReflection = !isReflection;
						}
					}
				
			}
			else
			{
				//Code for drawing the Gradient with Padding
				
				//Front Pad
				if(PreStartLength != 0.0f)
				{
					drawPad(TheGraphics, Origin,
                            Max-Min,u,0.0,PreStartLength,getMFColors()->front(),Opacity);
				}
				
				drawGradient(TheGraphics, Origin, Max-Min,u,PreStartLength,PreStartLength+GradientLength,Opacity);
				
				//End Pad
				if(PostEndLength != 0.0f)
				{
					drawPad(TheGraphics, Origin, Max-Min,u,PreStartLength+GradientLength,1.0,getMFColors()->back(),Opacity);
				}
			}
		}
	}
}
Пример #28
0
VOID DebugDraw::DrawScreenSpaceRect( const D3DRECT& Rect, FLOAT fLineWidth, D3DCOLOR Color )
{
    XMFLOAT2 Origin( ( FLOAT )Rect.x1, ( FLOAT )Rect.y1 );
    XMFLOAT2 Size( ( FLOAT )( Rect.x2 - Rect.x1 ), ( FLOAT )( Rect.y2 - Rect.y1 ) );
    DrawScreenSpaceRect( Origin, Size, fLineWidth, Color );
}
void UPaperSpriteThumbnailRenderer::DrawFrame(class UPaperSprite* Sprite, int32 X, int32 Y, uint32 Width, uint32 Height, FRenderTarget*, FCanvas* Canvas, FBoxSphereBounds* OverrideRenderBounds)
{
	if (const UTexture2D* SourceTexture = (Sprite != nullptr) ? Sprite->GetSourceTexture() : nullptr)
	{
		const bool bUseTranslucentBlend = SourceTexture->HasAlphaChannel();

		// Draw the grid behind the sprite
		if (bUseTranslucentBlend)
		{
			DrawGrid(X, Y, Width, Height, Canvas);
		}

		// Draw the sprite itself
		// Use the baked render data, so we don't have to care about rotations and possibly
		// other sprites overlapping in source, UV region, etc.
		const TArray<FVector4> &BakedRenderData = Sprite->BakedRenderData;
		TArray<FVector2D> CanvasPositions;
		TArray<FVector2D> CanvasUVs;

		for (int Vertex = 0; Vertex < BakedRenderData.Num(); ++Vertex)
		{
			new(CanvasPositions)FVector2D(BakedRenderData[Vertex].X, -BakedRenderData[Vertex].Y);
			new(CanvasUVs)FVector2D(BakedRenderData[Vertex].Z, BakedRenderData[Vertex].W);
		}

		// Determine the bounds to use
		FBoxSphereBounds* RenderBounds = OverrideRenderBounds;
		FBoxSphereBounds FrameBounds;
		if (RenderBounds == nullptr)
		{
			FrameBounds = Sprite->GetRenderBounds();
			RenderBounds = &FrameBounds;
		}

		const FVector MinPoint3D = RenderBounds->GetBoxExtrema(0);
		const FVector MaxPoint3D = RenderBounds->GetBoxExtrema(1);
		const FVector2D MinPoint(FVector::DotProduct(MinPoint3D, PaperAxisX), FVector::DotProduct(MinPoint3D, PaperAxisY));
		const FVector2D MaxPoint(FVector::DotProduct(MaxPoint3D, PaperAxisX), FVector::DotProduct(MaxPoint3D, PaperAxisY));

		float ScaleFactor = 1.0f;
		float UnscaledWidth = MaxPoint.X - MinPoint.X;
		float UnscaledHeight = MaxPoint.Y - MinPoint.Y;
		FVector2D Origin(X + Width / 2.0f, Y + Height / 2.0f);
		if ((UnscaledWidth > 0.0f) && (UnscaledHeight > 0.0f) && (UnscaledWidth > UnscaledHeight))
		{ 
			ScaleFactor = Width / UnscaledWidth;
		}
		else
		{
			ScaleFactor = Height / UnscaledHeight;
		}

		// Scale and recenter
		FVector2D CanvasPositionCenter = (MaxPoint + MinPoint) * 0.5f;
		for (int Vertex = 0; Vertex < CanvasPositions.Num(); ++Vertex)
		{
			CanvasPositions[Vertex] = (CanvasPositions[Vertex] - CanvasPositionCenter) * ScaleFactor + Origin;
		}

		// Draw triangles
		if (CanvasPositions.Num() > 0 && SourceTexture->Resource != nullptr)
		{
			TArray<FCanvasUVTri> Triangles;
			const FLinearColor SpriteColor(FLinearColor::White);
			for (int Vertex = 0; Vertex < CanvasPositions.Num(); Vertex += 3)
			{
				FCanvasUVTri* Triangle = new (Triangles) FCanvasUVTri();
				Triangle->V0_Pos = CanvasPositions[Vertex + 0]; Triangle->V0_UV = CanvasUVs[Vertex + 0]; Triangle->V0_Color = SpriteColor;
				Triangle->V1_Pos = CanvasPositions[Vertex + 1]; Triangle->V1_UV = CanvasUVs[Vertex + 1]; Triangle->V1_Color = SpriteColor;
				Triangle->V2_Pos = CanvasPositions[Vertex + 2]; Triangle->V2_UV = CanvasUVs[Vertex + 2]; Triangle->V2_Color = SpriteColor;
			}
			FCanvasTriangleItem CanvasTriangle(Triangles, SourceTexture->Resource);
			CanvasTriangle.BlendMode = bUseTranslucentBlend ? ESimpleElementBlendMode::SE_BLEND_Translucent : ESimpleElementBlendMode::SE_BLEND_Opaque;
			Canvas->DrawItem(CanvasTriangle);
		}
	}
	else
	{
		// Fallback for a bogus sprite
		DrawGrid(X, Y, Width, Height, Canvas);
	}
}
Пример #30
0
static int intersectConvexConvex_( const Point2f* P, int n, const Point2f* Q, int m,
                                   Point2f* result, float* _area )
{
    Point2f* result0 = result;
    // P has n vertices, Q has m vertices.
    int     a=0, b=0;       // indices on P and Q (resp.)
    Point2f Origin(0,0);
    tInFlag inflag=Unknown; // {Pin, Qin, Unknown}: which inside
    int     aa=0, ba=0;     // # advances on a & b indices (after 1st inter.)
    bool    FirstPoint=true;// Is this the first point? (used to initialize).
    Point2f p0;             // The first point.
    *result++ = Point2f(FLT_MAX, FLT_MAX);

    do
    {
        // Computations of key variables.
        int a1 = (a + n - 1) % n; // a-1, b-1 (resp.)
        int b1 = (b + m - 1) % m;

        Point2f A = P[a] - P[a1], B = Q[b] - Q[b1]; // directed edges on P and Q (resp.)

        int cross = areaSign( Origin, A, B );    // sign of z-component of A x B
        int aHB = areaSign( Q[b1], Q[b], P[a] ); // a in H(b).
        int bHA = areaSign( P[a1], P[a], Q[b] ); // b in H(A);

        // If A & B intersect, update inflag.
        Point2f p, q;
        int code = segSegInt( P[a1], P[a], Q[b1], Q[b], p, q );
        if( code == '1' || code == 'v' )
        {
            if( inflag == Unknown && FirstPoint )
            {
                aa = ba = 0;
                FirstPoint = false;
                p0 = p;
                *result++ = p;
            }
            inflag = inOut( p, inflag, aHB, bHA, result );
        }

        //-----Advance rules-----

        // Special case: A & B overlap and oppositely oriented.
        if( code == 'e' && A.ddot(B) < 0 )
        {
            addSharedSeg( p, q, result );
            return (int)(result - result0);
        }

        // Special case: A & B parallel and separated.
        if( cross == 0 && aHB < 0 && bHA < 0 )
            return (int)(result - result0);

        // Special case: A & B collinear.
        else if ( cross == 0 && aHB == 0 && bHA == 0 ) {
            // Advance but do not output point.
            if ( inflag == Pin )
                b = advance( b, &ba, m, inflag == Qin, Q[b], result );
            else
                a = advance( a, &aa, n, inflag == Pin, P[a], result );
        }

        // Generic cases.
        else if( cross >= 0 )
        {
            if( bHA > 0)
                a = advance( a, &aa, n, inflag == Pin, P[a], result );
            else
                b = advance( b, &ba, m, inflag == Qin, Q[b], result );
        }
        else
        {
            if( aHB > 0)
                b = advance( b, &ba, m, inflag == Qin, Q[b], result );
            else
                a = advance( a, &aa, n, inflag == Pin, P[a], result );
        }
        // Quit when both adv. indices have cycled, or one has cycled twice.
    }
    while ( ((aa < n) || (ba < m)) && (aa < 2*n) && (ba < 2*m) );

    // Deal with special cases: not implemented.
    if( inflag == Unknown )
    {
        // The boundaries of P and Q do not cross.
        // ...
    }

    int i, nr = (int)(result - result0);
    double area = 0;
    Point2f prev = result0[nr-1];
    for( i = 1; i < nr; i++ )
    {
        result0[i-1] = result0[i];
        area += (double)prev.x*result0[i].y - (double)prev.y*result0[i].x;
        prev = result0[i];
    }

    *_area = (float)(area*0.5);

    if( result0[nr-2] == result0[0] && nr > 1 )
        nr--;
    return nr-1;
}