コード例 #1
0
ファイル: func.cpp プロジェクト: lukaswilkeer/hiphop-php
const FPIEnt* Func::findFPI(Offset o) const {
  ASSERT(o >= base() && o < past());
  const FPIEnt* fe = NULL;
  unsigned int i;

  const FPIEntVec& fpitab = shared()->m_fpitab;
  for (i = 0; i < fpitab.size(); i++) {
    /*
     * We consider the "FCall" instruction part of the FPI region, but
     * the corresponding push is not considered part of it.  (This
     * means all offsets in the FPI region will have the partial
     * ActRec on the stack.)
     */
    if (fpitab[i].m_fpushOff < o && o <= fpitab[i].m_fcallOff) {
      fe = &fpitab[i];
    }
  }
  return fe;
}
コード例 #2
0
ファイル: func.cpp プロジェクト: lokeshguddu/hiphop-php
Offset Func::findFaultPCFromEH(Offset o) const {
  ASSERT(o >= base() && o < past());
  unsigned int i = 0;
  int max = -1;

  const EHEntVec& ehtab = shared()->m_ehtab;
  for (i = 0; i < ehtab.size(); i++) {
    if (ehtab[i].m_ehtype == EHEnt::EHType_Catch) {
      continue;
    }
    if (ehtab[i].m_fault < o &&
        (max == -1 ||
         ehtab[i].m_fault > ehtab[max].m_fault)) {
      max = i;
    }
  }
  ASSERT(max != -1);
  return ehtab[max].m_past;
}
コード例 #3
0
ファイル: main.cpp プロジェクト: henic/pyramids
// --------------------------------------------------------------------
int main(int argc, char *argv[])
{
    if (argc > 1) {
        int rc = Proceed_Arguments (argc, argv);
        if (rc) {
            qCritical() << "Proceed_Arguments returned" << rc;
            return 1;
        }
    }

    if (Execution_Directory[0]!='\0' &&
        Execution_Directory != Execution_Directory_Default) {
        //QString CurrentDir = QApplication::applicationDirPath();
        //qDebug() << "CurrentDir " << CurrentDir;
        QDir::setCurrent(Execution_Directory);

    }

    QFile::remove (Debug_File_Name);

    if (Use_Debug_File)
        qInstallMessageHandler(customMessageHandler);

    // check that no another copy of the application is running
    QSharedMemory shared(Shared_Memory_Unique_Label);
    if( !shared.create( 512, QSharedMemory::ReadWrite) )
        return 0;

#if HTTPGET_MODULE==1
    HttpGet http_request (Quotes_Http_Server); //test, TBD
#endif

    QApplication app(argc, argv);
    app.setApplicationVersion(Version_String);
    app.setApplicationName   (Application_Name);
    app.setOrganizationDomain("henic.livejournal.com");
    app.setOrganizationName  ("Tigers Ltd");

    MainWindow w;
    w.show();
    return app.exec();
}
コード例 #4
0
ファイル: string.cpp プロジェクト: rougecardinal/rubinius
String* String::append(STATE, const char* other, native_int length) {
    native_int current_size = size();
    native_int data_size = as<CharArray>(data_)->size();

    // Clamp the string size the maximum underlying byte array size
    if(unlikely(current_size > data_size)) {
        current_size = data_size;
    }

    native_int new_size = current_size + length;
    native_int capacity = data_size;

    if(capacity < new_size + 1) {
        // capacity needs one extra byte of room for the trailing null
        do {
            // @todo growth should be more intelligent than doubling
            capacity *= 2;
        } while(capacity < new_size + 1);

        // No need to call unshare and duplicate a CharArray
        // just to throw it away.
        if(shared_ == Qtrue) shared(state, Qfalse);

        CharArray* ba = CharArray::create(state, capacity);
        memcpy(ba->raw_bytes(), byte_address(), current_size);
        data(state, ba);
    } else {
        if(shared_ == Qtrue) unshare(state);
    }

    // Append on top of the null byte at the end of s1, not after it
    memcpy(byte_address() + current_size, other, length);

    // The 0-based index of the last character is new_size - 1
    byte_address()[new_size] = 0;

    num_bytes(state, Fixnum::from(new_size));
    hash_value(state, nil<Fixnum>());

    return this;
}
コード例 #5
0
ファイル: PhysicsMgr.cpp プロジェクト: tangziwen/Cube-Engine
PhysicsRigidBody * PhysicsMgr::createRigidBodyCylinder(float massValue, float topRadius, float bottomRadius, float height, Matrix44 transform)
{
	auto rig = new PhysicsRigidBody();
	btScalar	mass(massValue);
	btTransform startTransform;
	startTransform.setIdentity();
	bool isDynamic = (mass != 0.f);
	btCylinderShape* colShape = new btCylinderShapeZ(btVector3(topRadius, bottomRadius, height * 0.5));
	btVector3 localInertia(0, 0, 0);
	if (isDynamic)
	{
		colShape->calculateLocalInertia(mass, localInertia);
	}	
	startTransform.setFromOpenGLMatrix(transform.data());
	auto btRig = shared()->createRigidBodyInternal(mass, startTransform, colShape, btVector4(1, 0, 0, 1));
	rig->setRigidBody(btRig);
	rig->genUserIndex();
	btRig->setUserIndex(rig->userIndex());
	btRig->setUserPointer(rig);
	return rig;
}
コード例 #6
0
ファイル: func.cpp プロジェクト: mediaprojects/hiphop-php
void Func::appendParam(bool ref, const Func::ParamInfo& info) {
  int qword = m_numParams / kBitsPerQword;
  int bit   = m_numParams % kBitsPerQword;
  // Grow args, if necessary.
  if ((m_numParams++ & (kBitsPerQword - 1)) == 0) {
    ASSERT(shared()->m_refBitVec == m_refBitVec);
    shared()->m_refBitVec = m_refBitVec = (uint64_t*)
      realloc(shared()->m_refBitVec,
              // E.g., 65th m_numParams -> 2 qwords
              (1 + m_numParams / kBitsPerQword) * sizeof(uint64_t));

    // The new word is either zerod or set to 1, depending on whether
    // we are one of the special builtins that takes variadic
    // reference arguments.  This is for use in the translator.
    shared()->m_refBitVec[m_numParams / kBitsPerQword] =
      (m_attrs & AttrVariadicByRef) ? -1ull : 0;
  }
  ASSERT(!!(shared()->m_refBitVec[qword] & (uint64(1) << bit)) ==
    !!(m_attrs & AttrVariadicByRef));
  shared()->m_refBitVec[qword] &= ~(1ull << bit);
  shared()->m_refBitVec[qword] |= uint64(ref) << bit;
  shared()->m_params.push_back(info);
}
コード例 #7
0
ファイル: subset.hpp プロジェクト: celikpence/gecode
  ExecStatus
  Subset<View0,View1>::propagate(Space& home, const ModEventDelta&) {
    bool oneassigned = x0.assigned() || x1.assigned();
    unsigned int x0glbsize;
    do {
      GlbRanges<View0> x0lb(x0);
      GECODE_ME_CHECK ( x1.includeI(home,x0lb) );
      GECODE_ME_CHECK ( x1.cardMin(home,x0.cardMin()) );
      LubRanges<View1> x1ub(x1);
      x0glbsize = x0.glbSize();
      GECODE_ME_CHECK ( x0.intersectI(home,x1ub) );
      GECODE_ME_CHECK ( x0.cardMax(home,x1.cardMax()) );
    } while (x0.glbSize() > x0glbsize);

    if (x0.cardMin() == x1.cardMax())
      GECODE_REWRITE(*this,(Eq<View0,View1>::post(home(*this),x0,x1)));

    if (shared(x0,x1)) {
      return oneassigned ? home.ES_SUBSUMED(*this) : ES_NOFIX;
    }
    return (x0.assigned() || x1.assigned()) ? home.ES_SUBSUMED(*this) : ES_FIX;
  }
コード例 #8
0
ファイル: testbundleutils1.cpp プロジェクト: 0-wiz-0/CMake
int main(int, char**)
{
  framework();
  shared();

#if defined(WIN32)
  HANDLE lib = LoadLibraryA("module1.dll");
  if(!lib)
  {
    printf("Failed to open module1\n");
  }
#else
  void* lib = dlopen("module1.so", RTLD_LAZY);
  if(!lib)
  {
    printf("Failed to open module1\n%s\n", dlerror());
  }
#endif


  return lib == 0 ? 1 : 0;
}
コード例 #9
0
	void Cylinder::generateGeometry()
	{
		std::vector<Line> lines;
		std::vector<vector3f> bottom, top;
		float angle = 0;
		float angleStep = 2 * pi / count;
		for (uint i = 0; i < count; ++i, angle += angleStep)
		{
			bottom.push_back(vector3f(radius * sin(angle), 0, radius * cos(angle)));
			top.push_back(vector3f(radius * sin(angle), height, radius * cos(angle)));
		}
		for (uint i = 0; i < count; ++i)
		{
			lines.push_back(Line(bottom[i], bottom[(i+1)%count]));
			lines.push_back(Line(top[i], top[(i+1)%count]));
			lines.push_back(Line(bottom[i], top[i]));
		}

		geometry.shaderType = ShaderType::Lines;
		geometry.shaderArgs = shared(new ShaderArgs<Line>(lines.data(), lines.size()));
		geometry.useLights = false;
	}
コード例 #10
0
ファイル: main.cpp プロジェクト: manikk/ekalappai
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(ekalappai);

    QApplication app(argc, argv);

    app.setApplicationName("eKalappai");
    app.setApplicationVersion("3.1");   

    //Allow only one instance of eKalappai at any time
    //This solution is based on solution provided in this article http://stackoverflow.com/questions/4087235/how-to-force-my-application-to-open-one-exe-only-qt-linux
    QSharedMemory shared("59698760-43bb-44d9-8121-181ecbb70e4d");
    if( !shared.create( 512, QSharedMemory::ReadWrite) )
    {
      qWarning() << "Cannot start more than one instance of eKalappai any time.";
      exit(0);
    }

    QPixmap pix(":/images/intro.png");

    QSplashScreen splash(pix);
    splash.show();
    Sleep(2000);
    splash.hide();

    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        return 1;
    }
    QApplication::setQuitOnLastWindowClosed(false);

    Window window;

    EKEventFilter* const ekEventFilter = new EKEventFilter;
    ekEventFilter->window = &window;
    app.installNativeEventFilter(ekEventFilter);
    return app.exec();

}
コード例 #11
0
ファイル: poll_socket.cpp プロジェクト: GrovoLearning/mesos
Future<Nothing> PollSocketImpl::connect(const Address& address)
{
  // Need to hold a copy of `this` so that the underlying socket
  // doesn't end up getting reused before we return.
  auto self = shared(this);

  return windows::connect(self->get(), address)
    .then([self]() -> Future<Nothing> {
      // After the async connect (`ConnectEx`) is called, the socket is in a
      // "default" state, which means it doesn't have the previously set
      // properties or options set. We need to set `SO_UPDATE_CONNECT_CONTEXT`
      // so that it regains its properties. For more information, see
      // https://msdn.microsoft.com/en-us/library/windows/desktop/ms737606(v=vs.85).aspx // NOLINT(whitespace/line_length)
      int res = ::setsockopt(
          self->get(), SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, nullptr, 0);

      if (res != 0) {
        WindowsError error;
        return Failure("Failed to set connected socket: " + error.message);
      }

      return Nothing();
    });
}
コード例 #12
0
ファイル: ssort.hpp プロジェクト: outpaddling/blasr_libcpp
inline int
ssort(SAIndex a[], SAIndex s[]) 
{
    SAIndex h, i, j, l, n, t;
    SAIndex k = 0;				/* initialized for lint */
    SAIndex *p = 0;
    int result = 0;
    SAIndex *q = 0;
#	define al a
#	define pl p
#	define finish(r)  if(1){result=r; goto out;}else

    for(j=n=0; a[n]>0; n++)			/* find n */
        if(a[n] > j)
            j = a[n];		/* and max element */
    if(a[n++]<0 || j>=n)
        finish(2);
    //	p = malloc(n*sizeof(int));
    p = new SAIndex[n];
    if(p == 0)
        finish(1);

    for(i=0; i<n; i++)			/* (0) initialize */
        p[i] = i | ORIG;

    if(s) {					/* shared lengths */
        //		q = malloc(n*sizeof(int));
        q = new SAIndex[n];
        if(q == 0)
            finish(1);
    }

    for(h = 0; ; h = h==0? 1: 2*h) {
        for(i=0; i<n; i++) {		/* (1) link */
            for(j=p[i]; !(j&ORIG); j=al[j]);
            j = pred(j&~ORIG, h);
            l = a[j];
            al[j] = pl[l];
            pl[l] = j;
        }

        if(h == 0) {			/* find k */
            for(k=0; k<n; k++)
                if(pl[k]&ORIG)
                    break;

            for(i=k; i<n; i++)	/* check input */
                if(!(pl[i]&ORIG))
                    finish(2);
        }

        for(i=n; --k>=0; ) {		/* (2) order */
            j = pl[k];
            do
                p[--i] = j;
            while(!((j=al[j]) & ORIG));
            p[i] |= BUCK;
        }

        for(i=0; i<n; i++) {		/* (3) reconstruct */
            if(p[i] & BUCK)
                k++;
            a[p[i]&~BUCK] = k;
        }

        for(i=0, j=-1; i<n; i++, j=l) {	/* (4) refine */
            l = a[succ(p[i]&~BUCK, h)];
            if(l != j)
                p[i] |= BUCK;

        }
        if(s)
            shared(a, n, p, q, s, h);

        for(i=0, k=-1; i<n; i++) {	/* (5) recode */
            if(p[i] & BUCK)
                k++;
            a[p[i]&~BUCK] = k;
            p[i] |= ORIG;		/* (0b) reinitialize */
        }
        if(++k >= n)
            break;
    }

    for(i=0; i<n; i++)
        a[i] = p[i] & ~ORIG;

out:
    delete [] p;
    delete [] q;
    return result;
}
コード例 #13
0
ファイル: test2.c プロジェクト: jimmy-zhao-tainio/project.m
int test2 (void)
{
	return 0 + shared ();
}
コード例 #14
0
ファイル: string.cpp プロジェクト: dbalatero/rubinius
 void String::unshare(STATE) {
   data(state, as<ByteArray>(data_->duplicate(state)));
   shared(state, Qfalse);
 }
コード例 #15
0
ファイル: stack_share.c プロジェクト: 8l/ucc-c-compiler
main()
{
	f(1, 1);
	shared();
	f(0, 0);
}
コード例 #16
0
ファイル: memory_protection.cpp プロジェクト: Ethon/Berry
bool berry::memory_protection::is_private() const
{
    return !shared();
}
コード例 #17
0
void EPSignalsController::pushSignal(EPSignal *signal)
{
    shared()->appendSignal(signal);
}
コード例 #18
0
ファイル: Transform.cpp プロジェクト: ydm/TemplateRays
Transform::Transform(const glm::mat4& m)
: m_(shared(m))
, inv_(inverse(m))
{
}
コード例 #19
0
ファイル: Transform.cpp プロジェクト: ydm/TemplateRays
Transform::Transform(const glm::mat4& m, const glm::mat4& inv)
: m_(shared(m))
, inv_(shared(inv))
{
}
コード例 #20
0
ファイル: test.cpp プロジェクト: fgroen/zxtune
int main()
{
  try
  {
  std::cout << "sizeof(int_t)=" << sizeof(int_t) << std::endl;
  std::cout << "sizeof(uint_t)=" << sizeof(uint_t) << std::endl;
  std::cout << "---- Test for byteorder working ----" << std::endl;
  TestOrder<int16_t>(-30875, 0x6587);
  TestOrder<uint16_t>(0x1234, 0x3412);
  //0x87654321
  TestOrder<int32_t>(-2023406815, 0x21436587);
  TestOrder<uint32_t>(0x12345678, 0x78563412);
  //0xfedcab9876543210
  TestOrder<int64_t>(-INT64_C(81985529216486896), UINT64_C(0x1032547698badcfe));
  TestOrder<uint64_t>(UINT64_C(0x123456789abcdef0), UINT64_C(0xf0debc9a78563412));

  std::cout << "---- Test for ranges map ----" << std::endl;
  {
    std::cout << "  test for simple range checker" << std::endl;
    RangeChecker::Ptr checker(RangeChecker::Create(100));
    Test("Adding too big range", !checker->AddRange(0, 110));
    Test("Adding range to begin", checker->AddRange(30, 10));//30..40
    Test("Adding range to lefter", checker->AddRange(20, 10));//=>20..40
    Test("Check result", checker->GetAffectedRange() == std::pair<std::size_t, std::size_t>(20, 40));
    Test("Adding range to end", checker->AddRange(70, 10));//70..80
    Test("Adding range to righter", checker->AddRange(80, 10));//=>70..90
    Test("Check result", checker->GetAffectedRange() == std::pair<std::size_t, std::size_t>(20, 90));
    Test("Adding wrong range from left", !checker->AddRange(30, 30));
    Test("Adding wrong range to right", !checker->AddRange(50, 30));
    Test("Adding wrong range to both", !checker->AddRange(30, 50));
    Test("Adding merged to left", checker->AddRange(40, 10));//40..50 => 20..50
    Test("Adding merged to right", checker->AddRange(60, 10));//60..70 => 6..90
    Test("Adding merged to mid", checker->AddRange(50, 10));
    Test("Adding zero-sized to free", checker->AddRange(0, 0));
    Test("Adding zero-sized to busy", !checker->AddRange(30, 0));
    Test("Check result", checker->GetAffectedRange() == std::pair<std::size_t, std::size_t>(20, 90));
    std::cout << "  test for shared range checker" << std::endl;
    RangeChecker::Ptr shared(RangeChecker::CreateShared(100));
    Test("Adding too big range", !shared->AddRange(0, 110));
    Test("Adding zero-sized to free", shared->AddRange(20, 0));
    Test("Adding range to begin", shared->AddRange(20, 20));//20..40
    Test("Check result", shared->GetAffectedRange() == std::pair<std::size_t, std::size_t>(20, 40));
    Test("Adding range to end", shared->AddRange(70, 20));//70..90
    Test("Check result", shared->GetAffectedRange() == std::pair<std::size_t, std::size_t>(20, 90));
    Test("Adding wrong range from left", !shared->AddRange(30, 30));
    Test("Adding wrong range to right", !shared->AddRange(50, 30));
    Test("Adding wrong range to both", !shared->AddRange(30, 50));
    Test("Adding shared to left", shared->AddRange(20, 20));
    Test("Adding invalid shared to left", !shared->AddRange(20, 30));
    Test("Adding shared to right", shared->AddRange(70, 20));
    Test("Adding invalid shared to right", !shared->AddRange(60, 20));
    Test("Adding zero-sized to busy valid", shared->AddRange(70, 0));
    Test("Adding zero-sized to busy invalid", !shared->AddRange(80, 0));
    Test("Check result", shared->GetAffectedRange() == std::pair<std::size_t, std::size_t>(20, 90));
  }
  std::cout << "---- Test for area controller ----" << std::endl;
  {
    {
      AreaController areas;
      areas.AddArea(BEGIN, 0);
      areas.AddArea(SECTION1, 10);
      areas.AddArea(SECTION2, 20);
      areas.AddArea(END, 30);
      TestAreaSizes("Ordered", areas, 10, 10, 10, AreaController::Undefined);
    }
    {
      AreaController areas;
      areas.AddArea(BEGIN, 40);
      areas.AddArea(SECTION1, 30);
      areas.AddArea(SECTION2, 20);
      areas.AddArea(END, 10);
      TestAreaSizes("Reversed", areas, AreaController::Undefined, 10, 10, 10);
    }
    {
      AreaController areas;
      areas.AddArea(BEGIN, 0);
      areas.AddArea(SECTION1, 30);
      areas.AddArea(SECTION2, 30);
      areas.AddArea(END, 10);
      TestAreaSizes("Duplicated", areas, 10, 0, 0, 20);
    }
  }
  std::cout << "---- Test for iterators ----" << std::endl;
  {
    const uint8_t DATA[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    CycledIterator<const uint8_t*> it(DATA, DATA + 10);
    Test<uint_t>("Cycled iterator init", *it, 0);
    Test<uint_t>("Cycled iterator forward", *++it, 1);
    Test<uint_t>("Cycled iterator backward", *--it, 0);
    Test<uint_t>("Cycled iterator underrun", *--it, 9);
    Test<uint_t>("Cycled iterator overrun", *++it, 0);
    Test<uint_t>("Cycled iterator positive delta", *(it + 15), 5);
    Test<uint_t>("Cycled iterator negative delta", *(it - 11), 9);
  }
  }
  catch (int code)
  {
    return code;
  }
}
コード例 #21
0
ファイル: occRasterizer_core.cpp プロジェクト: 2asoft/xray-16
// Rasterize a scan line between given X point values, corresponding Z values and current color
void i_scan		(int curY, float leftX, float lhx, float rightX, float rhx, float startZ, float endZ)
{
	// calculate span(s)
	float	start_c	= leftX+lhx;
	float	end_c	= rightX+rhx;
	
	float	startR	= leftX-lhx;
	float	endR	= rightX-rhx;
	
	float	startT	=startR,	endT	=end_c;
	float	startX	=start_c,	endX	=endR;
	if (start_c<startR)		{startT	= start_c;	startX	= startR;	}
	if (end_c<endR)			{endT	= endR;		endX	= end_c;	}
	
	// guard-banding and clipping
	int minT		= iFloor(startT)-1, maxT = iCeil(endT)+1;
	Vclamp			(minT,1,occ_dim-1);
	Vclamp			(maxT,1,occ_dim-1);
	if (minT >= maxT)		return;
	
	int minX		= iCeil(startX), maxX = iFloor(endX);
	Vclamp			(minX,0,occ_dim);
	Vclamp			(maxX,0,occ_dim);
	int limLeft,limRight;
	if (minX >  maxX)	{ limLeft=maxX; limRight=minX;	}
	else				{ limLeft=minX; limRight=maxX;	}
	
	// interpolate
	float lenR		= endR - startR;
	float Zlen		= endZ - startZ;
	float Z			= startZ + (minT - startR)/lenR * Zlen;		// interpolate Z to the start
	float Zend		= startZ + (maxT - startR)/lenR * Zlen;		// interpolate Z to the end
	float dZ		= (Zend-Z)/(maxT-minT);						// increment in Z / pixel wrt dX

	// Move to far my dz/5 to place the pixel at the center of face that it covers. 
	// This will make sure that objects will not be clipped for just standing next to the home from outside.
	Z				+= 0.5f*_abs(dZ);

	// gain access to buffers
	occTri** pFrame	= Raster.get_frame();
	float*	pDepth	= Raster.get_depth();
	
	// left connector
	int	i_base		= curY*occ_dim;
	int i			= i_base+minT;
	int limit		= i_base+limLeft;
	for (; i<limit; i++, Z+=dZ)
	{
		if (shared(currentTri,pFrame[i-1])) 
		{
			//float ZR = (Z+2*pDepth[i-1])*one_div_3;
			if (Z<pDepth[i])	{ pFrame[i]	= currentTri; pDepth[i]	= __max(Z,pDepth[i-1]); dwPixels++; }
		}
	}

	// compute the scanline 
	limit				= i_base+maxX;
	for (; i<limit; i++, Z+=dZ) 
	{
		if (Z<pDepth[i])		{ pFrame[i]	= currentTri; pDepth[i] = Z;  dwPixels++; }
	}
	
	// right connector
	i				= i_base+maxT-1;
	limit			= i_base+limRight;
	Z				= Zend-dZ;
	for (; i>=limit; i--, Z-=dZ)
	{
		if (shared(currentTri,pFrame[i+1])) 
		{
			//float ZR = (Z+2*pDepth[i+1])*one_div_3;
			if (Z<pDepth[i])	{ pFrame[i]	= currentTri; pDepth[i]	= __max(Z,pDepth[i+1]); dwPixels++; }
		}
	}
}
コード例 #22
0
ファイル: func-emitter.cpp プロジェクト: swtaarrs/hhvm
Func* FuncEmitter::create(Unit& unit, PreClass* preClass /* = NULL */) const {
  bool isGenerated = isdigit(name->data()[0]) || needsStripInOut(name);

  Attr attrs = this->attrs;
  if (preClass && preClass->attrs() & AttrInterface) {
    attrs |= AttrAbstract;
  }
  if (!RuntimeOption::RepoAuthoritative) {
    if (RuntimeOption::EvalJitEnableRenameFunction) {
      attrs |= AttrInterceptable;
    } else {
      attrs = Attr(attrs & ~AttrInterceptable);
    }
  }
  if (attrs & AttrPersistent && !preClass) {
    if ((RuntimeOption::EvalJitEnableRenameFunction ||
         attrs & AttrInterceptable ||
         (!RuntimeOption::RepoAuthoritative && SystemLib::s_inited))) {
      if (attrs & AttrBuiltin) {
        SystemLib::s_anyNonPersistentBuiltins = true;
      }
      attrs = Attr(attrs & ~AttrPersistent);
    }
  } else {
    assertx(preClass || !(attrs & AttrBuiltin));
  }
  if (!RuntimeOption::RepoAuthoritative) {
    // In non-RepoAuthoritative mode, any function could get a VarEnv because
    // of evalPHPDebugger.
    attrs |= AttrMayUseVV;
  } else if ((attrs & AttrInterceptable) &&
             !name->empty() &&
             !Func::isSpecial(name) &&
             !isClosureBody) {
    // intercepted functions need to pass all args through
    // to the interceptee
    attrs |= AttrMayUseVV;
  }
  if (isVariadic()) {
    attrs |= AttrVariadicParam;
    if (isVariadicByRef()) {
      attrs |= AttrVariadicByRef;
    }
  }

  assertx(!m_pce == !preClass);
  auto f = m_ue.newFunc(this, unit, name, attrs, params.size());

  f->m_isPreFunc = !!preClass;

  bool const needsExtendedSharedData =
    isNative ||
    line2 - line1 >= Func::kSmallDeltaLimit ||
    past - base >= Func::kSmallDeltaLimit ||
    m_numClsRefSlots > 3;

  f->m_shared.reset(
    needsExtendedSharedData
      ? new Func::ExtendedSharedData(preClass, base, past, line1, line2,
                                     top, !containsCalls, docComment)
      : new Func::SharedData(preClass, base, past,
                             line1, line2, top, !containsCalls, docComment)
  );

  f->init(params.size());

  if (auto const ex = f->extShared()) {
    ex->m_hasExtendedSharedData = true;
    ex->m_arFuncPtr = nullptr;
    ex->m_nativeFuncPtr = nullptr;
    ex->m_line2 = line2;
    ex->m_past = past;
    ex->m_returnByValue = false;
    ex->m_isMemoizeWrapper = false;
    ex->m_isMemoizeWrapperLSB = false;
    ex->m_actualNumClsRefSlots = m_numClsRefSlots;
  }

  std::vector<Func::ParamInfo> fParams;
  for (unsigned i = 0; i < params.size(); ++i) {
    Func::ParamInfo pi = params[i];
    if (pi.isVariadic()) {
      pi.builtinType = RuntimeOption::EvalHackArrDVArrs
        ? KindOfVec : KindOfArray;
    }
    f->appendParam(params[i].byRef, pi, fParams);
  }

  auto const originalFullName =
    (!originalFilename ||
     !RuntimeOption::RepoAuthoritative ||
     FileUtil::isAbsolutePath(originalFilename->slice())) ?
    originalFilename :
    makeStaticString(RuntimeOption::SourceRoot +
                     originalFilename->toCppString());

  f->shared()->m_localNames.create(m_localNames);
  f->shared()->m_numLocals = m_numLocals;
  f->shared()->m_numIterators = m_numIterators;
  f->m_maxStackCells = maxStackCells;
  f->shared()->m_staticVars = staticVars;
  f->shared()->m_ehtab = ehtab;
  f->shared()->m_fpitab = fpitab;
  f->shared()->m_isClosureBody = isClosureBody;
  f->shared()->m_isAsync = isAsync;
  f->shared()->m_isGenerator = isGenerator;
  f->shared()->m_isPairGenerator = isPairGenerator;
  f->shared()->m_userAttributes = userAttributes;
  f->shared()->m_retTypeConstraint = retTypeConstraint;
  f->shared()->m_retUserType = retUserType;
  f->shared()->m_originalFilename = originalFullName;
  f->shared()->m_isGenerated = isGenerated;
  f->shared()->m_repoReturnType = repoReturnType;
  f->shared()->m_repoAwaitedReturnType = repoAwaitedReturnType;
  f->shared()->m_isMemoizeWrapper = isMemoizeWrapper;
  f->shared()->m_isMemoizeWrapperLSB = isMemoizeWrapperLSB;
  f->shared()->m_numClsRefSlots = m_numClsRefSlots;

  if (isNative) {
    auto const ex = f->extShared();

    ex->m_hniReturnType = hniReturnType;

    auto const info = getNativeInfo();

    Attr dummy = AttrNone;
    auto nativeAttributes = parseNativeAttributes(dummy);
    Native::getFunctionPointers(
      info,
      nativeAttributes,
      ex->m_arFuncPtr,
      ex->m_nativeFuncPtr
    );
    ex->m_takesNumArgs = !!(nativeAttributes & Native::AttrTakesNumArgs);

    if (ex->m_nativeFuncPtr) {
      if (info.sig.ret == Native::NativeSig::Type::MixedTV) {
        ex->m_returnByValue = true;
      }
      int extra =
        (nativeAttributes & Native::AttrTakesNumArgs ? 1 : 0) +
        (isMethod() ? 1 : 0);
      assertx(info.sig.args.size() == params.size() + extra);
      for (auto i = params.size(); i--; ) {
        switch (info.sig.args[extra + i]) {
          case Native::NativeSig::Type::ObjectArg:
          case Native::NativeSig::Type::StringArg:
          case Native::NativeSig::Type::ArrayArg:
          case Native::NativeSig::Type::ResourceArg:
          case Native::NativeSig::Type::OutputArg:
          case Native::NativeSig::Type::MixedTV:
            fParams[i].nativeArg = true;
            break;
          default:
            break;
        }
      }
    }
  }

  f->finishedEmittingParams(fParams);
  return f;
}
コード例 #23
0
		Habanero::DLODSkinnedMesh::InitInfo loadFromFile(const char *fileName,
															Resource::Mapping &materials,
															Resource::Mapping &textures,
															Resource::Mapping &skeletons)
		{			
			// TODO: burdel, zrobiæ ¿eby dzia³a³o

			uint64 size;
                        // kolejne Kuflowe obejœcie buga gcc
			std::unique_ptr<File, MappingDeleter> file((File*)Habanero::File::map(fileName, Habanero::File::Read, &size).release());
			if (file->signature != signature)
				RAISE(Exception, "Invalid Discrete LOD TMF signature");
			if (size < sizeof(File))
				RAISE(Exception, "Incomplete file");

			Habanero::DLODSkinnedMesh::InitInfo result;

			if (file->mesh.skeletonId != 0)
			{
				result.skeleton = SkeletonManager::getInstance().getResource(skeletons[file->mesh.skeletonId].c_str());
				result.skeleton->load();
			}

			result.dlodLevels.resize(file->mesh.numLODLevels);

			Habanero::MF2::LODLevel * fileLODLevel = file->mesh.getFirstLODLevel();
			for(int i = 0; i < file->mesh.numLODLevels; i++)
			{
				// ka¿dy LODLevel dostaje inn¹ iloœæ vertexów
				DLODLevel<SkinVertex>::InitInfo& lodLevel = result.dlodLevels[i];

				lodLevel.geometry.vertices.resize(fileLODLevel->numVertices);
				std::copy(file->mesh.getVertices(), file->mesh.getVertices() + fileLODLevel->numVertices, lodLevel.geometry.vertices.begin());

				lodLevel.geometry.subMeshes.resize(fileLODLevel->numSubMeshes);
				Habanero::MF2::SubMesh * fileSubMesh = fileLODLevel->getFirstSubMesh();
				for(int j = 0; j < fileLODLevel->numSubMeshes; j++)
				{
					Habanero::SubMesh::InitInfo &subMesh = lodLevel.geometry.subMeshes[j];	// weŸmy no sobie adresik initinfo submesha
					if(fileSubMesh->materialId != 0)
						subMesh.material = shared(MTF2::loadFromFile(materials[fileSubMesh->materialId].c_str(), textures));
					else
						subMesh.material = shared(new Material());
					subMesh.indices.insert(subMesh.indices.begin(), fileSubMesh->indices, fileSubMesh->indices + fileSubMesh->numIndices);

					fileSubMesh = fileSubMesh->getNext();
				}

				fileLODLevel = fileLODLevel->getNext();
			}

			// czytamy BV
			size_t bvSize;
			BoundingVolumeType *bvType = file->mesh.getBoundingVolumeType();
			result.boundingVolume = Habanero::MF::createBoundingVolume(bvType, &bvSize);

			if ((char*)file.get() + size != (char*)bvType + bvSize)
				RAISE(Exception, "Invalid file size");

			return result;
		}
コード例 #24
0
ファイル: main.cpp プロジェクト: elfakyn/ColorShifter-qt
int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);

    // check windows version
    if (!(osvi.dwMajorVersion > 6 || osvi.dwMajorVersion == 6 && osvi.dwMinorVersion >= 1))  {
        QMessageBox msgBox;
        msgBox.setText(QObject::tr("Unsupported windows version."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();

#ifdef QT_DEBUG
        std::cout<<"ERR: unsupported windows version"<<std::endl;
#endif

        exit(EXIT_UNSUPPORTED_WINDOWS_VERSION);
    }

    // attempt to load the wm dll
    if (!loadDwmDll(getDwmStatus, setDwmColors, getDwmColors)) {
        QMessageBox msgBox;
        msgBox.setText(QObject::tr("Could not load dwmapi.dll."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();

#ifdef QT_DEBUG
        std::cout<<"ERR: could not load dwmapi.dll"<<std::endl;
#endif

        exit(EXIT_DLL_LOAD_FAIL);
    }

    BOOL ok;
    getDwmStatus(&ok);
    if (!ok) {
        // TODO: replace with a warning inside the window
        exit(EXIT_COMPOSITION_DISABLED);
    }

    QSharedMemory shared("075fa67f-eefe-43de-91dd-9c2ec23def4b");

    if(!shared.create(512, QSharedMemory::ReadWrite)) {
        QMessageBox msgBox;
        msgBox.setText(QObject::tr("Can't start more than one instance of ColorShifter."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();

#ifdef QT_DEBUG
        std::cout<<"ERR: can't start multiple instances"<<std::endl;
#endif
        exit(EXIT_MULTIPLE_INSTANCES);
    }

    MainWindow w;
    QApplication::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(on_quitButton_clicked()));

    // check if starts minimized
    bool minimized = false;
    for (int i = 0; i < argc; i++) {
        if (!(strcmp(argv[i], "--minimized"))) {
            minimized = true;
        }
    }

    if (!minimized) {
        w.show();
    } else {
#ifdef QT_DEBUG
        std::cout<<"Starting minimized"<<std::endl;
#endif
    }

    return a.exec();

    /*
    Color color1, color2;
    DwmColor crt = { 0 };

    color1.SetMerged(0xFFFF0000);
    color2.SetMerged(0xFF0000FF);
    crt = exportColor(color1);
    setDwmColors(&crt, 0);

    for (int i = 0; i < 100; i++) {
        crt = exportColor(interpolate(color1, color2, i * 1.0 / 100));
        setDwmColors(&crt, 0);
        Sleep(60);
    }
    */

    exit(EXIT_A_EXEC_DID_NOT_RETURN);
}
コード例 #25
0
ファイル: state.cpp プロジェクト: d4rky-pl/rubinius
  void LLVMState::run(STATE) {
    GCTokenImpl gct;
    JITCompileRequest* compile_request = nil<JITCompileRequest>();
    OnStack<1> os(state, compile_request);

    metrics().init(metrics::eJITMetrics);

    state->gc_dependent(gct, 0);

    bool show_machine_code_ = jit_dump_code() & cMachineCode;

    while(!thread_exit_) {

      current_compiler_ = 0;

      {
        GCIndependent guard(state, 0);

        {
          utilities::thread::Mutex::LockGuard lg(compile_lock_);

          while(compile_list_.get()->empty_p()) {
            compile_cond_.wait(compile_lock_);

            if(thread_exit_) break;
          }
        }
      }

      if(thread_exit_) break;

      {
        utilities::thread::Mutex::LockGuard guard(request_lock_);

        compile_request = try_as<JITCompileRequest>(compile_list_.get()->shift(state));
        if(!compile_request || compile_request->nil_p()) continue;
      }

      utilities::thread::Condition* cond = compile_request->waiter();

      // Don't proceed until requester has reached the wait_cond
      if(cond) wait_mutex.lock();

      Context ctx(this);
      jit::Compiler jit(&ctx);

      current_compiler_ = &jit;

      uint32_t class_id = 0;
      uint32_t serial_id = 0;
      void* func = 0;

      try {
        if(compile_request->receiver_class() &&
            !compile_request->receiver_class()->nil_p()) {
          // Apparently already compiled, probably some race
          if(compile_request->method()->find_specialized(
                compile_request->receiver_class())) {
            if(config().jit_show_compiling) {
              CompiledCode* code = compile_request->method();
              llvm::outs() << "[[[ JIT already compiled "
                        << enclosure_name(code) << "#" << symbol_debug_str(code->name())
                        << (compile_request->is_block() ? " (block)" : " (method)")
                        << " ]]]\n";
            }

            // If someone was waiting on this, wake them up.
            if(cond) {
              wait_mutex.unlock();
              cond->signal();
            }

            current_compiler_ = 0;

            continue;
          }

          class_id = compile_request->receiver_class()->class_id();
          serial_id = compile_request->receiver_class()->serial_id();
        }

        {
          timer::StopWatch<timer::microseconds> timer(
              metrics().m.jit_metrics.time_last_us,
              metrics().m.jit_metrics.time_total_us);

          jit.compile(compile_request);

          bool indy = !config().jit_sync;
          func = jit.generate_function(indy);
        }

        // We were unable to compile this function, likely
        // because it's got something we don't support.
        if(!func) {
          if(config().jit_show_compiling) {
            CompiledCode* code = compile_request->method();
            llvm::outs() << "[[[ JIT error background compiling "
                      << enclosure_name(code) << "#" << symbol_debug_str(code->name())
                      << (compile_request->is_block() ? " (block)" : " (method)")
                      << " ]]]\n";
          }
          // If someone was waiting on this, wake them up.
          if(cond) {
            wait_mutex.unlock();
            cond->signal();
          }

          current_compiler_ = 0;

          continue;
        }
      } catch(LLVMState::CompileError& e) {
        utilities::logger::warn("JIT: compile error: %s", e.error());

        metrics().m.jit_metrics.methods_failed++;

        // If someone was waiting on this, wake them up.
        if(cond) {
          wait_mutex.unlock();
          cond->signal();
        }
        current_compiler_ = 0;

        continue;
      }

      if(show_machine_code_) {
        jit.show_machine_code();
      }

      // If the method has had jit'ing request disabled since we started
      // JIT'ing it, discard our work.
      if(!compile_request->machine_code()->jit_disabled()) {

        jit::RuntimeDataHolder* rd = ctx.runtime_data_holder();

        atomic::memory_barrier();
        start_method_update();

        if(!compile_request->is_block()) {
          if(class_id) {
            compile_request->method()->add_specialized(state,
                class_id, serial_id, reinterpret_cast<executor>(func), rd);
          } else {
            compile_request->method()->set_unspecialized(reinterpret_cast<executor>(func), rd);
          }
        } else {
          compile_request->method()->set_unspecialized(reinterpret_cast<executor>(func), rd);
        }

        compile_request->machine_code()->clear_compiling();

        end_method_update();

        rd->run_write_barrier(shared().om, compile_request->method());

        if(config().jit_show_compiling) {
          CompiledCode* code = compile_request->method();
          llvm::outs() << "[[[ JIT finished background compiling "
                    << enclosure_name(code) << "#" << symbol_debug_str(code->name())
                    << (compile_request->is_block() ? " (block)" : " (method)")
                    << " ]]]\n";
        }
      }

      // If someone was waiting on this, wake them up.
      if(cond) {
        wait_mutex.unlock();
        cond->signal();
      }

      current_compiler_ = 0;
      metrics().m.jit_metrics.methods_compiled++;
    }
  }
コード例 #26
0
static int
copy_term(Word from, Word to, int flags ARG_LD)
{ term_agendaLR agenda;
  int rc = TRUE;

  initTermAgendaLR(&agenda, 1, from, to);
  while( nextTermAgendaLR(&agenda, &from, &to) )
  {
  again:

    switch(tag(*from))
    { case TAG_REFERENCE:
      { Word p2 = unRef(*from);

	if ( *p2 == VAR_MARK )		/* reference to a copied variable */
	{ *to = makeRef(p2);
	} else
	{ from = p2;			/* normal reference */
	  goto again;
	}

	continue;
      }
      case TAG_VAR:
      { if ( shared(*from) )
	{ *to = VAR_MARK;
	  *from = makeRef(to);
	  TrailCyclic(from PASS_LD);
	} else
	{ setVar(*to);
	}

	continue;
      }
      case TAG_ATTVAR:
	if ( flags&COPY_ATTRS )
	{ Word p = valPAttVar(*from);

	  if ( isAttVar(*p) )		/* already copied */
	  { *to = makeRefG(p);
	  } else
	  { Word attr;

	    if ( !(attr = alloc_attvar(PASS_LD1)) )
	    { rc = GLOBAL_OVERFLOW;
	      goto out;
	    }
	    TrailCyclic(p PASS_LD);
	    TrailCyclic(from PASS_LD);
	    *from = consPtr(attr, STG_GLOBAL|TAG_ATTVAR);
	    *to = makeRefG(attr);

	    from = p;
	    to = &attr[1];
	    goto again;
	  }
	} else
	{ if ( shared(*from) )
	  { Word p = valPAttVar(*from & ~BOTH_MASK);

	    if ( *p == VAR_MARK )
	    { *to = makeRef(p);
	    } else
	    { *to = VAR_MARK;
	      *from = consPtr(to, STG_GLOBAL|TAG_ATTVAR)|BOTH_MASK;
	      TrailCyclic(p PASS_LD);
	      TrailCyclic(from PASS_LD);
	    }
	  } else
	  { setVar(*to);
	  }
	}
	continue;
      case TAG_COMPOUND:
      { Functor ff = valueTerm(*from);

	if ( isRef(ff->definition) )
	{ *to = consPtr(unRef(ff->definition), TAG_COMPOUND|STG_GLOBAL);
	  continue;
	}

	if ( ground(ff->definition) )
	{ *to = *from;
	  continue;
	}

	if ( shared(ff->definition) )
	{ int arity = arityFunctor(ff->definition);
	  Functor ft;

	  if ( !(ft = (Functor)allocGlobalNoShift(arity+1)) )
	  { rc = GLOBAL_OVERFLOW;
	    goto out;
	  }
	  ft->definition = ff->definition & ~BOTH_MASK;
	  ff->definition = makeRefG((Word)ft);
	  TrailCyclic(&ff->definition PASS_LD);
	  *to = consPtr(ft, TAG_COMPOUND|STG_GLOBAL);

	  if ( pushWorkAgendaLR(&agenda, arity, ff->arguments, ft->arguments) )
	    continue;
	  rc = MEMORY_OVERFLOW;
	  goto out;
	} else				/* unshared term */
	{ int arity = arityFunctor(ff->definition);
	  Functor ft;

	  if ( !(ft = (Functor)allocGlobalNoShift(arity+1)) )
	  { rc = GLOBAL_OVERFLOW;
	    goto out;
	  }
	  ft->definition = ff->definition & ~BOTH_MASK;
	  *to = consPtr(ft, TAG_COMPOUND|STG_GLOBAL);

	  if ( pushWorkAgendaLR(&agenda, arity, ff->arguments, ft->arguments) )
	    continue;
	  rc = MEMORY_OVERFLOW;
	  goto out;
	}
      }
      default:
	*to = *from;
        continue;
    }
  }

out:
  clearTermAgendaLR(&agenda);
  return rc;
}
コード例 #27
0
  ExecStatus
  SuperOfInter<View0,View1,View2>::propagate(Space& home, const ModEventDelta& med) {

    bool allassigned = x0.assigned() && x1.assigned() && x2.assigned();

    ModEvent me0 = View0::me(med);
    ModEvent me1 = View1::me(med);
    ModEvent me2 = View2::me(med);

    bool modified = false;

    do {
      // glb(x2) >= glb(x0) ^ glb(x1)
      if ( modified || Rel::testSetEventLB(me0,me1)) {
        GlbRanges<View0> lb0(x0);
        GlbRanges<View1> lb1(x1);
        Iter::Ranges::Inter<GlbRanges<View0>,GlbRanges<View1> >
          is(lb0, lb1);

        GECODE_ME_CHECK_MODIFIED(modified,x2.includeI(home,is));
      }

      // lub(x0) -= glb(x1)-lub(x2)
      // lub(x1) -= glb(x0)-lub(x2)
      if ( modified || Rel::testSetEventAnyB(me0,me1,me2)) {
         modified = false;
        GlbRanges<View1> lb12(x1);
        LubRanges<View2> ub22(x2);
        Iter::Ranges::Diff<GlbRanges<View1>, LubRanges<View2> >
          diff1(lb12, ub22);

        GECODE_ME_CHECK_MODIFIED(modified, x0.excludeI(home,diff1));

        GlbRanges<View0> lb01(x0);
        LubRanges<View2> ub23(x2);
        Iter::Ranges::Diff<GlbRanges<View0>, LubRanges<View2> >
          diff2(lb01, ub23);

        GECODE_ME_CHECK_MODIFIED(modified, x1.excludeI(home,diff2));
      } else {
         modified = false;
      }

      // Cardinality propagation
      if ( modified ||
            Rel::testSetEventCard(me0,me1,me2) ||
           Rel::testSetEventUB(me0,me1)
           ) {

        LubRanges<View0> ub0(x0);
        LubRanges<View1> ub1(x1);
        Iter::Ranges::Union<LubRanges<View0>, LubRanges<View1> > u(ub0,ub1);

        unsigned int m = Iter::Ranges::size(u);

        if (m < x0.cardMin() + x1.cardMin()) {
          GECODE_ME_CHECK_MODIFIED(modified,
                            x2.cardMin( home,
                                        x0.cardMin()+x1.cardMin() - m ) );
        }
        if (m + x2.cardMax() > x1.cardMin()) {
          GECODE_ME_CHECK_MODIFIED(modified,
                            x0.cardMax( home,
                                        m+x2.cardMax()-x1.cardMin() )  );
        }
        if (m + x2.cardMax() > x0.cardMin()) {
          GECODE_ME_CHECK_MODIFIED(modified,
                            x1.cardMax( home,
                                        m+x2.cardMax()-x0.cardMin() )  );
        }
      }
    } while (modified);


    if (shared(x0,x1,x2)) {
      if (allassigned) {
        return home.ES_SUBSUMED(*this);
      } else {
        return ES_NOFIX;
      }
    } else {
      if (x0.assigned() + x1.assigned() + x2.assigned() >= 2) {
         return home.ES_SUBSUMED(*this);
      } else {
        return ES_FIX;
      }
    }

  }
コード例 #28
0
ファイル: HMF.cpp プロジェクト: Xanewok/habanero3d-current
		Habanero::HeightMapMesh::InitInfo loadFromFile(const char *fileName, Resource::Mapping &materials, Resource::Mapping &textures)
		{
			uint64 size;
                        // kolejne Kuflowe obej�cie buga gcc
			std::unique_ptr<File, MappingDeleter> file((File*)Habanero::File::map(fileName, Habanero::File::Read, &size).release());
			if (file->signature != signature)
				RAISE(Exception, "Invalid HMF signature");
			
			if (size < sizeof(File))
				RAISE(Exception, "Incomplete file");

			HeightMap hmInfo = file->mesh;
			uint width = hmInfo.width;
			uint height = hmInfo.height;
			float maxY = hmInfo.maxHeight;
			float repX = hmInfo.texRepX;
			float repY = hmInfo.texRepY;
			ref<Texture> heightMap = ResourceManager::getInstance().getTexture(textures[hmInfo.textureId]);
			heightMap->load();

			HASSERT(width >= 2 && height >= 2);

			GenericGeometry<StaticVertex>::InitInfo initInfo;
			std::vector<StaticVertex> &vertices = initInfo.vertices;
			vertices.reserve(width * height);

			float sxy = 1.0f / (width - 1);
			maxY /= 255.0f;
			repX /= width - 1;
			repY /= height - 1;
			for (uint z = 0; z < height; z++)
			{
				byte *line = (byte*)heightMap->getRawDataPtr() + z * (heightMap->getHeight() - 1) / (height - 1) * heightMap->getWidth() * 4;
				for (uint x = 0; x < width; x++)
				{
					StaticVertex v;
					v.position.x = x * sxy;
					v.position.y = line[x * (heightMap->getWidth() - 1) / (width - 1) * 4] * maxY;
					v.position.z = z * sxy;
					v.texCoord.x = x * repX;
					v.texCoord.y = z * repY;
					v.normal = vector3f::zero;
					vertices.push_back(v);
				}
			}

			auto normal = [&](uint x, uint y) -> vector3f&
			{
				return vertices[y * width + x].normal;
			};
			auto position = [&](uint x, uint y) -> vector3f&
			{
				return vertices[y * width + x].position;
			};
			uint c;
			auto triangle = [&](uint x, uint y, uint x1, uint y1, uint x2, uint y2)
			{
				c++;
				normal(x, y) += cross(position(x2, y2) - position(x, y), position(x1, y1) - position(x, y));
			};
			for (uint y = 0; y < height; y++)
				for (uint x = 0; x < width; x++)
				{
					c = 0;
					if (x + 1 < width && y + 1 < height)
						triangle(x, y, x + 1, y, x, y + 1);
					if (x > 0 && y + 1 < height)
						triangle(x, y, x, y + 1, x - 1, y + 1);
					if (x > 0 && y > 0)
						triangle(x, y, x - 1, y, x, y - 1);
					if (x + 1 < width && y > 0)
						triangle(x, y, x, y - 1, x + 1, y - 1);
					normal(x, y) /= (float)c;
				}
			SubMesh::InitInfo subMeshInitInfo;
			subMeshInitInfo.material = shared(MTF2::loadFromFile(materials[hmInfo.materialId].c_str(), textures));
			for (uint y = 0; y + 1 < height; y++)
				for (uint x = 0; x + 1 < width; x++)
				{
					subMeshInitInfo.indices.push_back(y * width + x);				
					subMeshInitInfo.indices.push_back((y + 1) * width + x);
					subMeshInitInfo.indices.push_back(y * width + x + 1);

					subMeshInitInfo.indices.push_back(y * width + x + 1);
					subMeshInitInfo.indices.push_back((y + 1) * width + x);
					subMeshInitInfo.indices.push_back((y + 1) * width + x + 1);
				}
			initInfo.subMeshes.push_back(std::move(subMeshInitInfo));
			Habanero::HeightMapMesh::InitInfo hmInitInfo;
			hmInitInfo.geometry = new GenericGeometry<StaticVertex>(initInfo);
			hmInitInfo.height= height;
			hmInitInfo.width = width;
			hmInitInfo.maxY = hmInfo.maxHeight;
			hmInitInfo.terrainTex = textures[hmInfo.textureId];
			//hmInitInfo.boundingVolume = 

			return hmInitInfo;
		}
コード例 #29
0
ファイル: union.hpp プロジェクト: Gecode/gecode
  ExecStatus
  Union<View0,View1,View2>::propagate(Space& home, const ModEventDelta& med) {
    // This propagator implements the constraint
    // x2 = x0 u x1

    bool x0ass = x0.assigned();
    bool x1ass = x1.assigned();
    bool x2ass = x2.assigned();

    ModEvent me0 = View0::me(med);
    ModEvent me1 = View1::me(med);
    ModEvent me2 = View2::me(med);

    bool x0ubmod = false;
    bool x1ubmod = false;
    bool modified = false;

    do {

      modified = false;
      do {
        // 4) lub(x2) <= lub(x0) u lub(x1)
        {
          LubRanges<View0> x0ub(x0);
          LubRanges<View1> x1ub(x1);
          Iter::Ranges::Union<LubRanges<View0>, LubRanges<View1> > u2(x0ub,x1ub);
          GECODE_ME_CHECK_MODIFIED(modified, x2.intersectI(home,u2) );
        }

        if (modified || Rel::testSetEventUB(me2) )
          {
            modified = false;
            // 5) x0 <= x2
            LubRanges<View2> x2ub1(x2);
            GECODE_ME_CHECK_MODIFIED(modified, x0.intersectI(home,x2ub1) );
            x0ubmod |= modified;

            // 6) x1 <= x2
            bool modified2=false;
            LubRanges<View2> x2ub2(x2);
            GECODE_ME_CHECK_MODIFIED(modified2, x1.intersectI(home,x2ub2) );
            x1ubmod |= modified2;
            modified |= modified2;
          }

      } while (modified);

      modified = false;
      do {
        bool modifiedOld = modified;
        modified = false;

        if (Rel::testSetEventLB(me2) || Rel::testSetEventUB(me0)
             || x0ubmod || modifiedOld)
          {
            // 1) glb(x0) \ lub(x1) <= glb(x2)
            GlbRanges<View2> x2lb(x2);
            LubRanges<View0> x0ub(x0);
            Iter::Ranges::Diff<GlbRanges<View2>, LubRanges<View0> >
              diff(x2lb, x0ub);
            GECODE_ME_CHECK_MODIFIED(modified, x1.includeI(home,diff) );
          }

        if (Rel::testSetEventLB(me2) || Rel::testSetEventUB(me1)
            || x1ubmod || modifiedOld)
          {
            // 2) glb(x0) \ lub(x2) <= glb(x1)
            GlbRanges<View2> x2lb(x2);
            LubRanges<View1> x1ub(x1);
            Iter::Ranges::Diff<GlbRanges<View2>, LubRanges<View1> >
              diff(x2lb, x1ub);
            GECODE_ME_CHECK_MODIFIED(modified, x0.includeI(home,diff) );
          }

         if (Rel::testSetEventLB(me0,me1) || modified)
          {
            //            modified = false;
            // 3) glb(x1) u glb(x2) <= glb(x0)
            GlbRanges<View0> x0lb(x0);
            GlbRanges<View1> x1lb(x1);
            Iter::Ranges::Union<GlbRanges<View0>, GlbRanges<View1> >
              u1(x0lb,x1lb);
            GECODE_ME_CHECK_MODIFIED(modified, x2.includeI(home,u1) );
          }

      } while(modified);

      modified = false;
      {
        // cardinality
        ExecStatus ret = unionCard(home,modified, x0, x1, x2);
        GECODE_ES_CHECK(ret);
      }

      if (x2.cardMax() == 0) {
        GECODE_ME_CHECK( x0.cardMax(home, 0) );
        GECODE_ME_CHECK( x1.cardMax(home, 0) );
        return home.ES_SUBSUMED(*this);
      }

      if (x0.cardMax() == 0)
        GECODE_REWRITE(*this,(Rel::Eq<View1,View2>::post(home(*this),x1,x2)));
      if (x1.cardMax() == 0)
        GECODE_REWRITE(*this,(Rel::Eq<View0,View2>::post(home(*this),x0,x2)));

    } while(modified);

    if (shared(x0,x1,x2)) {
      return (x0ass && x1ass && x2ass) ? home.ES_SUBSUMED(*this) : ES_NOFIX;
    } else {
      if (x0ass && x1ass && x2ass)
        return home.ES_SUBSUMED(*this);
      if (x0ass != x0.assigned() ||
          x1ass != x1.assigned() ||
          x2ass != x2.assigned()) {
        return ES_NOFIX;
      } else {
         return ES_FIX;
      }
    }
  }
コード例 #30
0
 T move_if_unshared(size_t pos) {
   if (shared())
     return get_as<T>(pos);
   return std::move(get_mutable_as<T>(pos));
 }