Exemplo n.º 1
0
 void obj_at_put(int which, oop contents, bool cs = true) {
   assert(which > 0 && which <= length(), "index out of bounds");
   assert(!is_symbol(), "shouldn't be modifying a canonical string");
   assert(contents->verify(), "check contents");
   if (cs) {
     STORE_OOP(objs(which), contents);
   } else {
     *objs(which) = contents;
   }
 }
Exemplo n.º 2
0
void Game::UpdateGameObjects()
{
  // To be safe, we should copy the container of game objects, so
  //  any updates which add or delete game objects do not invalidate the
  //  iterator. But if this is expensive, leave it to the game-specific code
  //  to sort out...

  if (m_updateCopy)
  {
    GameObjects objs(m_objects); // Yikes, but updating might remove or add objects

    for (GameObjects::iterator it = objs.begin(); it != objs.end(); ++it)
    {
      it->second->Update();
    }
  }
  else
  {
    // Updates won't add or delete elements, so iterate over original container 
    for (GameObjects::iterator it = m_objects.begin(); it != m_objects.end(); ++it)
    {
      it->second->Update();
    }
  }
}
Exemplo n.º 3
0
   INT32 _pmdDataProcessor::_onAggrReqMsg( MsgHeader *msg, INT64 &contextID )
   {
      INT32 rc    = SDB_OK ;
      CHAR *pObjs = NULL ;
      INT32 count = 0 ;
      INT32 flags = 0 ;
      CHAR *pCollectionName = NULL ;

      rc = msgExtractAggrRequest( (CHAR*)msg, &pCollectionName,
                                  &pObjs, count, &flags ) ;
      PD_RC_CHECK( rc, PDERROR, "Session[%s] extrace aggr msg failed, rc: %d",
                   getSession()->sessionName(), rc ) ;

      try
      {
         BSONObj objs( pObjs ) ;
         rc = rtnAggregate( pCollectionName, objs, count, flags, eduCB(),
                            _pDMSCB, contextID ) ;
      }
      catch( std::exception &e )
      {
         PD_LOG( PDERROR, "Session[%s] occurred exception in aggr: %s",
                 getSession()->sessionName(), e.what() ) ;
         rc = SDB_INVALIDARG ;
         goto error ;
      }

   done:
      return rc ;
   error:
      goto done ;
   }
// selfSetup is called when the visual system is first instantiated
// This will be called during a "loading" screen, so any big images or
// geometry should be loaded here
void CloudsVisualSystemLaplacianTunnel::selfSetup(){
	frameCount = 0;
	bUseExternalCamera = false;
	bPalindrome = false;
	lastFrameTime = 0;
	growthFPS = 0;
	currentGrowthIndex = 0;
	
	ofDirectory objs(GetCloudsMediaPath() + "assets/LaplacianTunnel/Meshes/");
	objs.allowExt("vbo");
	objs.listDir();
	
	clear();
	
	min.set(999999);
	max.set(-99999);
	center.set(14.000,5.900,-13.950);
	int numFiles = objs.numFiles();
	vbos.resize( numFiles );
	for(int i = 0; i < numFiles; i++){
		vbos[i].vbo = new ofVboByteColor();
		vbos[i].name = objs.getName(i);
		vbos[i].indexCount = loadMesh(*vbos[i].vbo, objs.getPath( i ) );
		//vbos[i].indexCount = loadMeshPLY(*vbos[i].vbo, objs.getPath( i ) );
	}
	
	sort(vbos.begin(), vbos.end(), meshsort);
	
	reloadShader();
	tunnelCam.setNearClip(.01);
	tunnelCam.setFov(70);
}
Exemplo n.º 5
0
void Workspace::setCurrentProject( Project *pro )
{
    if ( project == pro )
	return;
    if ( project ) {
	disconnect( project, SIGNAL( sourceFileAdded(SourceFile*) ), this, SLOT( sourceFileAdded(SourceFile*) ) );
	disconnect( project, SIGNAL( sourceFileRemoved(SourceFile*) ), this, SLOT( sourceFileRemoved(SourceFile*) ) );
	disconnect( project, SIGNAL( formFileAdded(FormFile*) ), this, SLOT( formFileAdded(FormFile*) ) );
	disconnect( project, SIGNAL( formFileRemoved(FormFile*) ), this, SLOT( formFileRemoved(FormFile*) ) );
	disconnect( project, SIGNAL( objectAdded(QObject*) ), this, SLOT( objectAdded(QObject*) ) );
	disconnect( project, SIGNAL( objectRemoved(QObject*) ), this, SLOT( objectRemoved(QObject*) ) );
	disconnect( project, SIGNAL( projectModified() ), this, SLOT( update() ) );
    }
    project = pro;
    connect( project, SIGNAL( sourceFileAdded(SourceFile*) ), this, SLOT( sourceFileAdded(SourceFile*) ) );
    connect( project, SIGNAL( sourceFileRemoved(SourceFile*) ), this, SLOT( sourceFileRemoved(SourceFile*) ) );
    connect( project, SIGNAL( formFileAdded(FormFile*) ), this, SLOT( formFileAdded(FormFile*) ) );
    connect( project, SIGNAL( formFileRemoved(FormFile*) ), this, SLOT( formFileRemoved(FormFile*) ) );
    connect( project, SIGNAL( destroyed(QObject*) ), this, SLOT( projectDestroyed(QObject*) ) );
    connect( project, SIGNAL( objectAdded(QObject*) ), this, SLOT( objectAdded(QObject*) ) );
    connect( project, SIGNAL( objectRemoved(QObject*) ), this, SLOT( objectRemoved(QObject*) ) );
    connect( project, SIGNAL( projectModified() ), this, SLOT( update() ) );
    clear();

    if ( bufferEdit )
	bufferEdit->clear();

    projectItem = new WorkspaceItem( this, project );

    projectItem->setOpen( TRUE );

    for ( QPtrListIterator<SourceFile> sources = project->sourceFiles();
	  sources.current(); ++sources ) {
	SourceFile* f = sources.current();
	(void) new WorkspaceItem( projectItem, f );
    }

    for ( QPtrListIterator<FormFile> forms = project->formFiles();
	  forms.current(); ++forms ) {
	FormFile* f = forms.current();
	if ( f->isFake() )
	    continue;

	(void) new WorkspaceItem( projectItem, f );
    }

    QObjectList l = project->objects();
    QObjectListIt objs( l );
    for ( ;objs.current(); ++objs ) {
	QObject* o = objs.current();
	(void) new WorkspaceItem( projectItem, o, project );
    }

    updateColors();
    completionDirty = TRUE;
}
Exemplo n.º 6
0
void appCopyPaste::CopyObject(const MenuObjC*     objData,
                              const AllocPageC*   objPageAllocator)
{
    if ((objData == 0) || (!objData->IsCopyable()))
        return;

    MenuObjArray objs(1);
    objs[0] = const_cast<MenuObjC*>(objData);
    CopyObjects(objs, objPageAllocator);
}
Exemplo n.º 7
0
void GLResources::Generate(GLsizei num, GLuint *objects, GenFunc func) {
	std::unique_ptr<GLuint> objs(new GLuint[num]);
	
	func(num, objs.get());

	for(int i = 0; i < num; i++) {
		gl_Objects.push_back(objs.get()[i]);
		objects[i] = objs.get()[i];
	}
}
Exemplo n.º 8
0
int32* objVectorOopClass::convertIntArray() {
  oop*   src    = objs();
  oop*   end    = src + length();
  int32* result = NEW_RESOURCE_ARRAY( int32, length());
  int32* dst    = result;
  while (src < end) {
    oop s = *src++;
    if (!s->is_smi())
      return NULL;
    *dst++ = smiOop(s)->value();
  }
  return result;
}
Exemplo n.º 9
0
pyarr_d
pdist(std::vector<pyarr_d> pyobjs, MatchHeuristic heur = MatchHeuristic::ISORANK)
{
	size_t N = pyobjs.size();
	arma::mat dists(N,N,arma::fill::zeros);
	std::vector<arma::mat> objs(N);
	for(size_t i = 0; i < N; ++i)
		objs.at(i) = py_to_mat(pyobjs.at(i));
// load balances by computing subdiagonal elements from the bottom of the matrix
#if defined(ENABLE_OPENMP)
		size_t n_rows = (N-1)/2;
	#pragma omp parallel for shared(dists)
		for(size_t i = 0; i < n_rows; ++i) 
		{
			for(size_t j = 0; j < N; ++j)
			{
				size_t idx_i = i, idx_j = j;
				if(idx_i >= idx_j)
				{
					idx_i = N - 2 - idx_i;
					idx_j = N - 1 - idx_j;
				}
				double d = dist_dfs(objs.at(idx_i), objs.at(idx_j), BRANCHES, heur);
				dists(idx_i, idx_j) = d;
				dists(idx_j, idx_i) = d;
			}
		}

		if(N % 2 == 0)
		{
		#pragma omp parallel for shared(dists)
			for(size_t j = n_rows+1; j < N; ++j)
			{
				double d = dist_dfs(objs.at(n_rows), objs.at(j), BRANCHES, heur);
				dists(n_rows, j) = d;
				dists(j, n_rows) = d;
			}
		}
#else	
	for(size_t i = 0; i < N; ++i)
	{
		for(size_t j=i+1; j < N; ++j)
		{
			dists(i,j) = dist_dfs(objs.at(i), objs.at(j), BRANCHES, heur);
			dists(j,i) = dists(i,j);
		}
	}
#endif
	return mat_to_py(dists);
}
Exemplo n.º 10
0
unsigned short* objVectorOopClass::convertUnsignedShortArray() {
  oop*   src    = objs();
  oop*   end    = src + length();
  unsigned short* result = NEW_RESOURCE_ARRAY( unsigned short, length());
  unsigned short* dst    = result;
  while (src < end) {
    oop s = *src++;
    if (!s->is_smi())
      return NULL;
    int32 v = smiOop(s)->value();
    if (int32((unsigned short)v) != v)
      return NULL;
    *dst++ = (unsigned short)v;
  }
  return result;
}
Exemplo n.º 11
0
float* objVectorOopClass::convertFloatArray() {
  oop*   src    = objs();
  oop*   end    = src + length();
  float* result = NEW_RESOURCE_ARRAY( float, length());
  float* dst    = result;
  while (src < end) {
    oop s = *src++;
    if (s->is_smi())
      *dst++ = float(smiOop(s)->value());
    else if (s->is_float())
      *dst++ = floatOop(s)->value();
    else
      return NULL;
  }
  return result;
}
void MultiObjectGrabStrategy::grabbableObjStateChanged(SceneObjectPtr obj)
{
   // If mChosenObjects is not empty, then we have a collection of objects to
   // grab that have not yet been grabbed. obj may be in mChosenObjects, and
   // if it is not grabbable, then it must be removed.
   if ( ! mChosenObjects.empty() )
   {
      std::vector<SceneObjectPtr>::iterator o =
         std::find(mChosenObjects.begin(), mChosenObjects.end(), obj);

      if ( o != mChosenObjects.end() && ! (*o)->isGrabbable() )
      {
         mObjConnections[*o].disconnect();
         mObjConnections.erase(*o);

         std::vector<SceneObjectPtr> objs(1, *o);
         mEventData->selectionListReduced(objs);

         mChosenObjects.erase(o);
      }
   }
   // If mGrabbedObjects is not empty, then we have grabbed objects, and obj
   // may be in that collection. If obj is no longer grabbable, it must be
   // removed from mGrabbedObjects.
   else if ( ! mGrabbedObjects.empty() )
   {
      std::vector<SceneObjectPtr>::iterator o =
         std::find(mGrabbedObjects.begin(), mGrabbedObjects.end(), obj);

      if ( o != mGrabbedObjects.end() && ! (*o)->isGrabbable() )
      {
         mObjConnections[*o].disconnect();
         mObjConnections.erase(*o);

         // Inform the code that is using us that we have released a grabbed
         // object.
         mReleaseCallback(std::vector<SceneObjectPtr>(1, *o));

         mGrabbedObjects.erase(o);

         // Keep the grabbing state up to date now that mGrabbedObjects has
         // changed.
         mGrabbing = ! mGrabbedObjects.empty();
      }
   }
}
Exemplo n.º 13
0
void* objVectorOopClass::convertProxyArray(const void* seal) {
  oop*   src    = objs();
  oop*   end    = src + length();
  void** result = NEW_RESOURCE_ARRAY( void*, length());
  void** dst    = result;
  while (src < end) {
    oop s = *src++;
    proxyOop p = proxyOop(s);
    if ( !s->is_proxy()  
    ||   !p->is_live()  
    ||    p->get_type_seal() != seal)
      return NULL;

    *dst++ = proxyOop(s)->get_pointer();
  }
  return result;
}
// selfSetup is called when the visual system is first instantiated
// This will be called during a "loading" screen, so any big images or
// geometry should be loaded here
void CloudsVisualSystemLaplacianTunnel::selfSetup(){
	frameCount = 0;
	fps = 15;
	
	ofDirectory objs(getVisualSystemDataPath() + "Meshes/");
	objs.allowExt("vbo");
	objs.listDir();
	
	clear();
	
	int numFiles = objs.numFiles();
	vbos.resize( numFiles );
	for(int i = 0; i < numFiles; i++){
		vbos[i].vbo = new ofVbo();
		vbos[i].name = objs.getName(i);
		vbos[i].indexCount = loadMesh(*vbos[i].vbo, objs.getPath( i ) );
	}
	
	sort(vbos.begin(), vbos.end(), meshsort);
	
}
Exemplo n.º 15
0
void FileHDF5::close() {

    if (!isOpen())
        return;

    data.close();
    metadata.close();
    root.close();

    unsigned types = H5F_OBJ_GROUP|H5F_OBJ_DATASET|H5F_OBJ_DATATYPE;

    ssize_t obj_count = H5Fget_obj_count(hid, types);

    if (obj_count < 0) {
        throw H5Exception("FileHDF5::close(): Could not get object count");
    }

    std::vector<hid_t> objs(static_cast<size_t>(obj_count));

    if (obj_count > 0) {
        obj_count = H5Fget_obj_ids(hid, types, objs.size(), objs.data());

        if (obj_count < 0) {
            throw H5Exception("FileHDF5::close(): Could not get objs");
        }
    }

    for (auto obj : objs) {
        int ref_count = H5Iget_ref(obj);

        for (int j = 0; j < ref_count; j++) {
            H5Oclose(obj);
        }
    }

    H5Object::close();
}
// ---------------------------------------------------------------------------
//
// -----------
void bXMapTopoCheck::check_events(){
//_bTrace_("bXMapTopoCheck::check_events",true);
bArray*				arr=_gapp->eventMgr()->events();
bGenericEvent*		evt;
bGenericType*		tp;
bGenericGeoElement	*mo,*o;
ivertices			*mvxs,*vxs;
long                i,j;
int					sign=GetSignature(this)/*,esign*/,cln='NtCl';
bArray				objs(sizeof(bGenericGeoElement*));

    
    for(i=1;i<=arr->count();i++){
        arr->get(i,&evt);
        //_tm_("Event "+evt->eid());
        //		esign=evt->creator();
        if(	(evt->creator()==sign)	||
            (evt->creator()==cln)	||
            (evt->is_undo())		||
            (evt->is_redo())		){
            //_tm_("pass");
            continue;
        }
        if(evt->kind()==kEventKindGeoElement){
            if(!_prm.activated){
                continue;
            }
            if(evt->action()==kEventActionModify){
                for(j=1;j<=evt->elements()->count();j++){
                    evt->elements()->get(j,&mo);
                    tp=_gapp->typesMgr()->get(mo->getType());
                    if(tp->kind()==kBaseKindPoint){
                        _types.get(mo->getType(),&tp);
                        if(tp==NULL){
                            continue;
                        }
                        o=mo->get_ref();
                        o->getVertices(&vxs);
                        mo->getVertices(&mvxs);
                        if(!mvxs){
                            continue;
                        }
                        if(vxs->nv==mvxs->nv){
                            objs.add(&mo);
                        }
                    }
                }
            }
        }
        else if(evt->kind()==kEventKindTypeElement){
            switch(evt->action()){
                case kEventActionCreate:
                    tp=NULL;
                    for(j=1;j<=evt->elements()->count();j++){
                        _types.add(&tp);
                    }
                    break;
                case kEventActionDestroy:
                    MMBeep();
                    break;
            }
        }
    }
    if(objs.count()>0){
        process_objects(objs);
    }
}
Exemplo n.º 17
0
LBMigrateMsg* NeighborCommLB::Strategy(NborBaseLB::LDStats* stats, int n_nbrs)
{
bool _lb_debug=0;
bool _lb_debug1=0;
bool _lb_debug2=0;
#if CMK_LBDB_ON
  //  CkPrintf("[%d] Strategy starting\n",CkMyPe());
  // Compute the average load to see if we are overloaded relative
  // to our neighbors
  double myload = myStats.total_walltime - myStats.idletime;
  double avgload = myload;
  int i;
  if (_lb_debug) 
    CkPrintf("[%d] Neighbor Count = %d\n", CkMyPe(), n_nbrs);
  
  for(i=0; i < n_nbrs; i++) {
    // Scale times we need appropriately for relative proc speeds
    const double scale =  ((double)myStats.pe_speed) 
      / stats[i].pe_speed;

    stats[i].total_walltime *= scale;
    stats[i].idletime *= scale;

    avgload += (stats[i].total_walltime - stats[i].idletime);
  }
  avgload /= (n_nbrs + 1);

  CkVec<MigrateInfo*> migrateInfo;

  if (_lb_debug) 
    CkPrintf("[%d] My load is %lf\n", CkMyPe(),myload);
  if (myload > avgload) {
    if (_lb_debug1) 
      CkPrintf("[%d] OVERLOAD My load is %lf average load is %lf\n", CkMyPe(), myload, avgload);

    // First of all, explore the topology and get dimension
    LBTopology* topo;
    {
      LBtopoFn topofn;
      topofn = LBTopoLookup(_lbtopo);
      if (topofn == NULL) {
        char str[1024];
        CmiPrintf("NeighborCommLB> Fatal error: Unknown topology: %s. Choose from:\n", _lbtopo);
        printoutTopo();
        sprintf(str, "NeighborCommLB> Fatal error: Unknown topology: %s", _lbtopo);
        CmiAbort(str);
      }
      topo = topofn(CkNumPes());
    }
    int dimension = topo->get_dimension();
    if (_lb_debug2) 
      CkPrintf("[%d] Topology dimension = %d\n", CkMyPe(), dimension);
    if (dimension == -1) {
      char str[1024];
      CmiPrintf("NeighborCommLB> Fatal error: Unsupported topology: %s. Only some of the following are supported:\n", _lbtopo);
      printoutTopo();
      sprintf(str, "NeighborCommLB> Fatal error: Unsupported topology: %s", _lbtopo);
      CmiAbort(str);
    }

    // Position of this processor
    int *myProc = new int[dimension];
    topo->get_processor_coordinates(myStats.from_pe, myProc);
    if (_lb_debug2) {
      char temp[1000];
      char* now=temp;
      sprintf(now, "[%d] Coordinates = [", CkMyPe());
      now += strlen(now);
      for(i=0;i<dimension;i++) {
        sprintf(now, "%d ", myProc[i]); 
        now +=strlen(now);
      }
      sprintf(now, "]\n");
      now += strlen(now);
      CkPrintf(temp);
    }

    // Then calculate the communication center of each object
    // The communication center is relative to myProc
    double **commcenter = new double*[myStats.n_objs];
    double *commamount = new double[myStats.n_objs];
    if(_lb_debug1) {
      CkPrintf("[%d] Number of Objs = %d \n", CkMyPe(), myStats.n_objs);
    }
    {
      memset(commamount, 0, sizeof(double)*myStats.n_objs);
      for(i=0; i<myStats.n_objs;i++) {
        commcenter[i] = new double[dimension];
        memset(commcenter[i], 0, sizeof(double)*dimension);
      }

      //coordinates of procs
      int *destProc = new int[dimension];
      int *diff = new int[dimension];
      
      //for each comm entry
      for(i=0; i<myStats.n_comm;i++) {
        int j;
        //for each object //TODO use hashtable to accelerate
        for(j=0; j<myStats.n_objs;j++) 
          if((myStats.objData[j].handle.omhandle.id == myStats.commData[i].sender.omId)
              && (myStats.objData[j].handle.id == myStats.commData[i].sender.objId)) {
            double comm=
              PER_MESSAGE_SEND_OVERHEAD * myStats.commData[i].messages 
              + PER_BYTE_SEND_OVERHEAD * myStats.commData[i].bytes;
            commamount[j] += comm;
            int dest_pe = myStats.commData[i].receiver.lastKnown();
            
            if(dest_pe==-1) continue;
            
              topo->get_processor_coordinates(dest_pe, destProc);
            topo->coordinate_difference(myProc, destProc, diff);
            int k;
            for(k=0;k<dimension;k++) {
              commcenter[j][k] += diff[k] * comm;
            }
          }
      }
      for(i=0; i<myStats.n_objs;i++) if (commamount[i]>0) {
        int k;
        double ratio = 1.0 /commamount[i];
        for(k=0;k<dimension;k++)
          commcenter[i][k] *= ratio;
      } else { //if no communication, set commcenter to myself
        int k;
        for(k=0;k<dimension;k++)
          commcenter[i][k] = 0;
      }
      
      delete [] destProc;
      delete [] diff;
    }
    
    if(_lb_debug2) {
      for(i=0;i<myStats.n_objs;i++) {
        char temp[1000];
        char* now=temp;
        sprintf(now, "[%d] Objs [%d] Load = %lf Comm Amount = %lf  ", 
          CkMyPe(), i, myStats.objData[i].wallTime, commamount[i] );
        now += strlen(now);
        sprintf(now, "Comm Center = [");
        now += strlen(now);
        int j;
        for(j=0;j<dimension;j++) {
          sprintf(now, "%lf ", commcenter[i][j]); 
          now += strlen(now);
        }
        sprintf(now, "]\n");
        now += strlen(now);
        CkPrintf(temp);
      }
    }
    
    // First, build heaps of my objects
    // Then assign objects to the least loaded other processors until either
    //   - The smallest remaining object would put me below average, or
    //   - I only have 1 object left, or
    //   - The smallest remaining object would put someone else 
    //     above average
    // Note: Object can only move towards its communication center!

    // My neighbors: 
    typedef struct _procInfo{
      int id;
      double load;
      int* difference;
    } procInfo;

    if(_lb_debug2) {
      CkPrintf("[%d] Querying neighborhood topology...\n", CkMyPe() );
    }

    procInfo* neighbors = new procInfo[n_nbrs];
    {
      int *destProc = new int[dimension];
      for(i=0; i < n_nbrs; i++) {
        neighbors[i].id = stats[i].from_pe;
        neighbors[i].load = stats[i].total_walltime - stats[i].idletime;
        neighbors[i].difference = new int[dimension];
        topo->get_processor_coordinates(neighbors[i].id, destProc);
        topo->coordinate_difference(myProc, destProc, neighbors[i].difference);
      }
      delete[] destProc;
    }
    
    if(_lb_debug2) {
      CkPrintf("[%d] Building obj heap...\n", CkMyPe() );
    }
    // My objects: build heaps
    maxHeap objs(myStats.n_objs);
    double totalObjLoad=0.0;
    for(i=0; i < myStats.n_objs; i++) {
      InfoRecord* item = new InfoRecord;
      item->load = myStats.objData[i].wallTime;
      totalObjLoad += item->load;
      item->Id = i;
      objs.insert(item);
    }

    if(_lb_debug2) {
      CkPrintf("[%d] Beginning distributing objects...\n", CkMyPe() );
    }

    // for each object
    while(objs.numElements()>0) {
      InfoRecord* obj;
      obj = objs.deleteMax();
      int bestDest = -1;
      for(i = 0; i < n_nbrs; i++)
	if(neighbors[i].load +obj->load < myload - obj->load && (bestDest==-1 || neighbors[i].load < neighbors[bestDest].load)) {
	  double dotsum=0;
	  int j;
	  for(j=0; j<dimension; j++) dotsum += (commcenter[obj->Id][j] * neighbors[i].difference[j]);
	  if(myload - avgload < totalObjLoad || dotsum>0.5 || (dotsum>0 && objs.numElements()==0) || commamount[obj->Id]==0) {
	    bestDest = i;
	  }
	}
      // Best place for the object
      if(bestDest != -1) {
        if(_lb_debug1) {
          CkPrintf("[%d] Obj[%d] will move to Proc[%d]\n", CkMyPe(), obj->Id, neighbors[bestDest].id);
        }
        //Migrate it
        MigrateInfo* migrateMe = new MigrateInfo;
        migrateMe->obj = myStats.objData[obj->Id].handle;
        migrateMe->from_pe = myStats.from_pe;
        migrateMe->to_pe = neighbors[bestDest].id;
        migrateInfo.insertAtEnd(migrateMe);
        //Modify loads
        myload -= obj->load;
        neighbors[bestDest].load += obj->load;
      }
      totalObjLoad -= obj->load;
      delete obj;
    }

    if(_lb_debug2) {
      CkPrintf("[%d] Clearing Up...\n", CkMyPe());
    }

    for(i=0; i<n_nbrs; i++) {
      delete[] neighbors[i].difference;
    }
    delete[] neighbors;
    
    delete[] myProc;

    for(i=0;i<myStats.n_objs;i++) {
      delete[] commcenter[i];
    }
    delete[] commcenter;
    delete[] commamount;        
  }  

  if(_lb_debug2) {
    CkPrintf("[%d] Generating result...\n", CkMyPe());
  }

  // Now build the message to actually perform the migrations
  int migrate_count=migrateInfo.length();
  //  if (migrate_count > 0) {
  //    CkPrintf("PE %d migrating %d elements\n",CkMyPe(),migrate_count);
  //  }
  LBMigrateMsg* msg = new(migrate_count,CkNumPes(),CkNumPes(),0) LBMigrateMsg;
  msg->n_moves = migrate_count;
  for(i=0; i < migrate_count; i++) {
    MigrateInfo* item = (MigrateInfo*) migrateInfo[i];
    msg->moves[i] = *item;
    delete item;
    migrateInfo[i] = 0;
  }

  return msg;
#else
  return NULL;
#endif
}
Exemplo n.º 18
0
bool LoaderIDE::load(const std::string &filename)
{
	std::ifstream str(filename);

	if ( ! str.is_open())
		return false;

	SectionTypes section = NONE;
	while( ! str.eof()) {
		std::string line;
		getline(str, line);
		line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end());

		if ( ! line.empty() && line[0] == '#')
			continue;

		if (line == "end") {
			section = NONE;
		} else if(section == NONE) {
			if (line == "objs") {
				section = OBJS;
			} else if (line == "tobj") {
				section = TOBJ;
			} else if (line == "peds") {
				section = PEDS;
			} else if (line == "cars") {
				section = CARS;
			} else if (line == "hier") {
				section = HIER;
			} else if (line == "2dfx") {
				section = TWODFX;
			} else if (line == "path") {
				section = PATH;
			}
		} else {
			// Remove ALL the whitespace!!
			line.erase(remove_if(line.begin(), line.end(), isspace), line.end());

			std::stringstream strstream(line);

			switch (section) {
			default: break;
			case OBJS:
			case TOBJ: { // Supports Type 1, 2 and 3
				std::shared_ptr<ObjectData> objs(new ObjectData);

				std::string id, numClumps, flags,
				            modelName, textureName;
				
				// Read the content of the line
				getline(strstream, id, ',');
				getline(strstream, modelName, ',');
				getline(strstream, textureName, ',');
				getline(strstream, numClumps, ',');

				objs->numClumps = atoi(numClumps.c_str());
				for (size_t i = 0; i < objs->numClumps; i++) {
					std::string drawDistance;
					getline(strstream, drawDistance, ',');
					objs->drawDistance[i] = atoi(drawDistance.c_str());
				}

				getline(strstream, flags, ',');
				
				// Keep reading TOBJ data
				if(section == LoaderIDE::TOBJ) {
					std::string buff;
					getline(strstream, buff, ',');
					objs->timeOn = atoi(buff.c_str());
					getline(strstream, buff, ',');
					objs->timeOff = atoi(buff.c_str());
				}
				else {
					objs->timeOff = objs->timeOn = 0;
				}

				// Put stuff in our struct
				objs->ID          = atoi(id.c_str());
				objs->flags       = atoi(flags.c_str());
				objs->modelName   = modelName;
				objs->textureName = textureName;
				objs->LOD         = false;

				if(modelName.find("LOD", 0,3) != modelName.npos
						&& modelName != "LODistancoast01") {
					objs->LOD = true;
				}

				objects.insert({objs->ID, objs});
				break;
			}
			case CARS: {
				std::shared_ptr<VehicleData> cars(new VehicleData);

				std::string id, type, classType, frequency, lvl,
				            comprules, wheelModelID, wheelScale;

				getline(strstream, id, ',');
				getline(strstream, cars->modelName, ',');
				getline(strstream, cars->textureName, ',');
				getline(strstream, type, ',');
				getline(strstream, cars->handlingID, ',');
				getline(strstream, cars->gameName, ',');
				getline(strstream, classType, ',');
				getline(strstream, frequency, ',');
				getline(strstream, lvl, ',');
				getline(strstream, comprules, ',');
				getline(strstream, wheelModelID, ',');
				getline(strstream, wheelScale, ',');

				cars->ID = atoi(id.c_str());
				cars->frequency = atoi(frequency.c_str());
				cars->lvl = atoi(lvl.c_str());
				cars->comprules = atoi(comprules.c_str());

				if (type == "car") {
					cars->type = VehicleData::CAR;
					cars->wheelModelID = atoi(wheelModelID.c_str());
					cars->wheelScale = atof(wheelScale.c_str());
				} else if (type == "boat") {
					cars->type = VehicleData::BOAT;
				} else if (type == "train") {
					cars->type = VehicleData::TRAIN;
					cars->modelLOD = atoi(wheelModelID.c_str());
				} else if (type == "plane") {
					cars->type = VehicleData::PLANE;
				} else if (type == "heli") {
					cars->type = VehicleData::HELI;
				}

				const std::map<VehicleData::VehicleClass, std::string> classTypes{
					{VehicleData::IGNORE,      "ignore"},
					{VehicleData::NORMAL,      "normal"},
					{VehicleData::POORFAMILY,  "poorfamily"},
					{VehicleData::RICHFAMILY,  "richfamily"},
					{VehicleData::EXECUTIVE,   "executive"},
					{VehicleData::WORKER,      "worker"},
					{VehicleData::BIG,         "big"},
					{VehicleData::TAXI,        "taxi"},
					{VehicleData::MOPED,       "moped"},
					{VehicleData::MOTORBIKE,   "motorbike"},
					{VehicleData::LEISUREBOAT, "leisureboat"},
					{VehicleData::WORKERBOAT,  "workerboat"},
					{VehicleData::BICYCLE,     "bicycle"},
					{VehicleData::ONFOOT,      "onfoot"},
				};
				for (auto &a : classTypes) {
					if (classType == a.second) {
						cars->classType = a.first;
						break;
					}
				}

				objects.insert({cars->ID, cars});
				break;
			}
			case PEDS: {
				std::shared_ptr<CharacterData> peds(new CharacterData);

				std::string id, driveMask;

				getline(strstream, id, ',');
				getline(strstream, peds->modelName, ',');
				getline(strstream, peds->textureName, ',');
				getline(strstream, peds->type, ',');
				getline(strstream, peds->behaviour, ',');
				getline(strstream, peds->animGroup, ',');
				getline(strstream, driveMask, ',');

				peds->ID = atoi(id.c_str());
				peds->driveMask = atoi(driveMask.c_str());

				objects.insert({peds->ID, peds});
				break;
			}
			case PATH: {
				PathData path;

				std::string type;
				getline(strstream, type, ',');
				if( type == "ped" ) {
					path.type = PathData::PATH_PED;
				}
				else if( type == "car") {
					path.type = PathData::PATH_CAR;
				}

				std::string id;
				getline(strstream, id, ',');
				path.ID = atoi(id.c_str());

				getline(strstream, path.modelName);

				std::string linebuff, buff;
				for( size_t p = 0; p < 12; ++p ) {
						PathNode node;

						getline(str, linebuff);
						std::stringstream buffstream(linebuff);

						getline(buffstream, buff, ',');
						switch(atoi(buff.c_str())) {
							case 0:
								node.type = PathNode::EMPTY;
								break;
							case 2:
								node.type = PathNode::INTERNAL;
								break;
							case 1:
								node.type = PathNode::EXTERNAL;
								break;
						}

						if( node.type == PathNode::EMPTY ) {
								continue;
						}

						getline(buffstream, buff, ',');
						node.next = atoi(buff.c_str());

						getline(buffstream, buff, ','); // "Always 0"

						getline(buffstream, buff, ',');
						node.position.x = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.position.y = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.position.z = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.size = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.other_thing = atoi(buff.c_str());

						getline(buffstream, buff, ',');
						node.other_thing2 = atoi(buff.c_str());

						path.nodes.push_back(node);
					}

					auto& object = objects[path.ID];
					auto instance = std::dynamic_pointer_cast<ObjectData>(object);
					instance->paths.push_back(path);

					break;
				}
			case HIER: {
				std::shared_ptr<CutsceneObjectData> cut(new CutsceneObjectData);

				std::string id;

				getline(strstream, id, ',');
				getline(strstream, cut->modelName, ',');
				getline(strstream, cut->textureName, ',');

				cut->ID = atoi(id.c_str());

				objects.insert({cut->ID, cut});
				break;
			}
			}
		}

	}

	return true;
}
Exemplo n.º 19
0
LSValue::~LSValue() {
	obj_deleted++;
	#if DEBUG_LEAKS
		objs().erase(this);
	#endif
}
Exemplo n.º 20
0
LBMigrateMsg* WSLB::Strategy(WSLB::LDStats* stats, int count)
{
#if CMK_LBDB_ON
  //  CkPrintf("[%d] Strategy starting\n",CkMyPe());
  // Compute the average load to see if we are overloaded relative
  // to our neighbors
  const double load_factor = 1.05;
  double objload;

  double myload = myStats.total_walltime - myStats.idletime;
  double avgload = myload;
  int unvacated_neighbors = 0;
  int i;
  for(i=0; i < count; i++) {
    // If the neighbor is vacating, skip him
    if (stats[i].vacate_me)
      continue;

    // Scale times we need appropriately for relative proc speeds
    double hisload = stats[i].total_walltime - stats[i].idletime;
    const double hisusage = stats[i].usage;

    const double scale =  (myStats.proc_speed * usage) 
      / (stats[i].proc_speed * hisusage);

    hisload *= scale;
    stats[i].total_walltime *= scale;
    stats[i].idletime *= scale;

    //    CkPrintf("PE %d %d hisload = %f hisusage = %f\n",
    //	     CkMyPe(),i,hisload,hisusage);
    avgload += hisload;
    unvacated_neighbors++;
  }
  if (vacate && unvacated_neighbors == 0)
    CkPrintf("[%d] ALL NEIGHBORS WANT TO VACATE!!!\n",CkMyPe());

  avgload /= (unvacated_neighbors+1);

  CkVec<MigrateInfo*> migrateInfo;

  // If we want to vacate, we always dump our load, otherwise
  // only if we are overloaded

  if (vacate || myload > avgload) {
    //    CkPrintf("[%d] OVERLOAD My load is %f, average load is %f\n",
    //	     CkMyPe(),myload,avgload);

    // First, build heaps of other processors and my objects
    // Then assign objects to other processors until either
    //   - The smallest remaining object would put me below average, or
    //   - I only have 1 object left, or
    //   - The smallest remaining object would put someone else 
    //     above average

    // Build heaps
    minHeap procs(count);
    for(i=0; i < count; i++) {
      // If all my neighbors vacate, I won't have anyone to give work 
      // to
      if (!stats[i].vacate_me) {
	InfoRecord* item = new InfoRecord;
	item->load = stats[i].total_walltime - stats[i].idletime;
	item->Id =  stats[i].from_pe;
	procs.insert(item);
      }
    }
      
    maxHeap objs(myStats.obj_data_sz);
    for(i=0; i < myStats.obj_data_sz; i++) {
      InfoRecord* item = new InfoRecord;
      item->load = myStats.objData[i].wallTime;
      item->Id = i;
      objs.insert(item);
    }

    int objs_here = myStats.obj_data_sz;
    do {
      //      if (objs_here <= 1) break;  // For now, always leave 1 object

      InfoRecord* p;
      InfoRecord* obj;

      // Get the lightest-loaded processor
      p = procs.deleteMin();
      if (p == 0) {
	//	CkPrintf("[%d] No destination PE found!\n",CkMyPe());
	break;
      }

      // Get the biggest object
      bool objfound = false;
      do {
	obj = objs.deleteMax();
	if (obj == 0) break;

	objload = load_factor * obj->load;

	double new_p_load = p->load + objload;
	double my_new_load = myload - objload;

	// If we're vacating, the biggest object is always good.
	// Otherwise, only take it if it doesn't produce overload
	if (vacate || new_p_load < my_new_load) {
	  objfound = true;
	} else {
	  // This object is too big, so throw it away
//	  CkPrintf("[%d] Can't move object w/ load %f to proc %d load %f %f\n",
//		   CkMyPe(),obj->load,p->Id,p->load,avgload);
	  delete obj;
	}
      } while (!objfound);

      if (!objfound) {
	//	CkPrintf("[%d] No suitable object found!\n",CkMyPe());
	break;
      }

      const int me = CkMyPe();
      // Apparently we can give this object to this processor
      if (_lb_args.debug())
      CkPrintf("[%d] Obj %d of %d migrating from %d to %d\n",
	       CkMyPe(),obj->Id,myStats.obj_data_sz,me,p->Id);

      MigrateInfo* migrateMe = new MigrateInfo;
      migrateMe->obj = myStats.objData[obj->Id].handle;
      migrateMe->from_pe = me;
      migrateMe->to_pe = p->Id;
      migrateInfo.insertAtEnd(migrateMe);

      objs_here--;
      
      // We may want to assign more to this processor, so lets
      // update it and put it back in the heap
      p->load += objload;
      myload -= objload;
      procs.insert(p);
      
      // This object is assigned, so we delete it from the heap
      delete obj;

    } while(vacate || myload > avgload);

    // Now empty out the heaps
    InfoRecord* p;
    while (NULL!=(p=procs.deleteMin()))
      delete p;
    InfoRecord* obj;
    while (NULL!=(obj=objs.deleteMax()))
      delete obj;
  }  

  // Now build the message to actually perform the migrations
  int migrate_count=migrateInfo.length();
  //  if (migrate_count) {
  //    CkPrintf("PE %d: Sent away %d of %d objects\n",
  //	     CkMyPe(),migrate_count,myStats.obj_data_sz);
  //  }
  LBMigrateMsg* msg = new(migrate_count,CkNumPes(),CkNumPes(),0) LBMigrateMsg;
  msg->n_moves = migrate_count;
  for(i=0; i < migrate_count; i++) {
    MigrateInfo* item = (MigrateInfo*) migrateInfo[i];
    msg->moves[i] = *item;
    delete item;
    migrateInfo[i] = 0;
  }

  return msg;
#else
  return NULL;
#endif
}
Exemplo n.º 21
0
 ByteArray Serializable::serialize() {
     beforeSerialization();
     
     int len = serial_objects.length();
     LinkedListState< Ref<SERIAL_OBJECT> > objs(&serial_objects);
     
     SERIAL_OBJECT *obj;
     ByteArray ret;
     ByteArray ba_obj;
     
     for (int i=0; i<len; i++) {
         ba_obj.clear();
         obj = objs.next().getPtr();
         
         if (obj->type != OBJECT_TYPE_SERIALIZABLE)
             ba_obj.append(ByteArray((const char*)&obj->type, 1));
         
         switch (obj->type) {
             case OBJECT_TYPE_OTHER:
                 {
                     ByteArray s = serializeOther(i, obj->object);
                     ssize_t len = s.length();
                     ba_obj.append(ByteArray((const char*)&len, 4));
                     ba_obj.append(s);
                 }
                 break;
                 
             case OBJECT_TYPE_SERIALIZABLE:
                 {
                     ByteArray s = reinterpret_cast<Serializable*>(obj->object)->serialize();
                     ssize_t len = s.length();
                     
                     if (len <= 0xFF)
                         obj->type = OBJECT_TYPE_TINY_SERIALIZABLE;
                     else if (len <= 0xFFFF)
                         obj->type = OBJECT_TYPE_MEDIUM_SERIALIZABLE;
                     
                     ba_obj.append(ByteArray((const char*)&obj->type, 1));
                     
                     if (obj->type == OBJECT_TYPE_TINY_SERIALIZABLE)
                         ba_obj.append(ByteArray((const char*)&len, 1));
                     else if (obj->type == OBJECT_TYPE_MEDIUM_SERIALIZABLE)
                         ba_obj.append(ByteArray((const char*)&len, 2));
                     else
                         ba_obj.append(ByteArray((const char*)&len, 4));
                     
                     ba_obj.append(s);
                 }
                 break;
                 
             case OBJECT_TYPE_TINY_BYTEARRAY:
                 ba_obj.append(ByteArray((const char*)&obj->len, 1));
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
                 break;
                 
             case OBJECT_TYPE_MEDIUM_BYTEARRAY:
                 ba_obj.append(ByteArray((const char*)&obj->len, 2));
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
                 break;
                 
             case OBJECT_TYPE_BYTEARRAY:
                 ba_obj.append(ByteArray((const char*)&obj->len, 4));
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
                 break;
                 
             default:
                 ba_obj.append(ByteArray((const char*)obj->object, (int)obj->len));
         }
         
         ret.append(ba_obj);
     }
     
     return ret;
 }
Exemplo n.º 22
0
int ShaderCompile_Subprocess_Main( char const *szSubProcessData )
{
	// Set our crash handler
	SetupToolsMinidumpHandler( ShaderCompile_Subprocess_ExceptionHandler );

	// Get our kernel objects
	SubProcessKernelObjects_Open objs( szSubProcessData );

	if ( !objs.IsValid() )
		return -1;

	// Enter the command pumping loop
	SubProcessKernelObjects_Memory shrmem( &objs );
	for (
		void *pvMemory = NULL;
		NULL != ( pvMemory = shrmem.Lock() );
		shrmem.Unlock()
		)
	{
		// The memory is actually a command
		char const *szCommand = ( char const * ) pvMemory;
		
		if ( !stricmp( "keepalive", szCommand ) )
		{
			ZeroMemory( pvMemory, 4 * sizeof( DWORD ) );
			continue;
		}

		if ( !stricmp( "quit", szCommand ) )
		{
			ZeroMemory( pvMemory, 4 * sizeof( DWORD ) );
			return 0;
		}

		CmdSink::IResponse *pResponse = NULL;
		if ( InterceptFxc::TryExecuteCommand( szCommand, &pResponse ) )
		{
			byte *pBytes = ( byte * ) pvMemory;
			
			// Result
			DWORD dwSucceededResult = pResponse->Succeeded() ? 1 : 0;
			* ( DWORD * ) pBytes = dwSucceededResult;
			pBytes += sizeof( DWORD );

			// Result buffer len
			DWORD dwBufferLength = pResponse->GetResultBufferLen();
			* ( DWORD * ) pBytes = dwBufferLength;
			pBytes += sizeof( DWORD );

			// Result buffer
			const void *pvResultBuffer = pResponse->GetResultBuffer();
			memcpy( pBytes, pvResultBuffer, dwBufferLength );
			pBytes += dwBufferLength;

			// Listing - copy string
			const char *szListing = pResponse->GetListing();
			if ( szListing )
			{
				while ( 0 != ( * ( pBytes ++ ) = * ( szListing ++ ) ) )
				{
					NULL;
				}
			}
			else
			{
				* ( pBytes ++ ) = 0;
			}
		}
		else
		{
			ZeroMemory( pvMemory, 4 * sizeof( DWORD ) );
		}
	}

	return -2;
}
Exemplo n.º 23
0
 oop obj_at(int which) const {
   assert(which > 0 && which <= length(), "index out of bounds");
   return *objs(which);
 }
Exemplo n.º 24
0
 // define the interval [begin .. end[ where the indexables are.
 oop* begin_indexables() const { return objs(1); }
Exemplo n.º 25
0
 void insertObject(const char *ns, const BSONObj &obj, uint64_t flags, bool logop) {
     vector<BSONObj> objs(1);
     objs[0] = obj;
     insertObjects(ns, objs, false, flags, logop);
 }
Exemplo n.º 26
0
LSValue::LSValue(LSValueType type) : type(type), refs(0) {
	obj_count++;
	#if DEBUG_LEAKS
		objs().insert({this, this});
	#endif
}
Exemplo n.º 27
0
LSValue::LSValue(const LSValue& o) : type(o.type), refs(0) {
	obj_count++;
	#if DEBUG_LEAKS
		objs().insert({this, this});
	#endif
}
void MultiObjectGrabStrategy::update(ViewerPtr viewer)
{
   if ( ! mGrabbing )
   {
      // The user has requested to add mCurIsectObject to the collection of
      // objects selected for later grabbing.
      if ( mCurIsectObject && mCurIsectObject->isGrabbable() && mChooseBtn() )
      {
         std::vector<SceneObjectPtr>::iterator o =
            std::find(mChosenObjects.begin(), mChosenObjects.end(),
                      mCurIsectObject);

         // Only choose mCurIsectObject for grabbing if it is not already in
         // mChosenObjcts.
         if ( o == mChosenObjects.end() )
         {
            mChosenObjects.push_back(mCurIsectObject);

            // Connect the grabbable object state change signal to our slot.
            mObjConnections[mCurIsectObject] =
               mCurIsectObject->grabbableStateChanged().connect(
                  boost::bind(
                     &MultiObjectGrabStrategy::grabbableObjStateChanged,
                     this, _1
                  )
               );

            std::vector<SceneObjectPtr> objs(1, mCurIsectObject);
            mEventData->selectionListExpanded(objs);

            // Use the intersection point of the most recently chosen object.
            mIntersectPoint = mCurIntersectPoint;
         }
      }
      // The user has requested to grab all the selected objects (those in
      // mChosenObjects).
      else if ( mGrabBtn() )
      {
         // If mChosenObjects is not empty, those objects are the ones that
         // we will grab.
         if ( ! mChosenObjects.empty() )
         {
            mGrabbedObjects = mChosenObjects;
            mChosenObjects.clear();
            mGrabbing = true;
         }
         // If mChosenObjects is empty but we are intersecting an object,
         // then that will be the one that we grab.
         else if ( mCurIsectObject )
         {
            mGrabbedObjects.resize(1);
            mGrabbedObjects[0] = mCurIsectObject;
            mGrabbing = true;
         }

         // If mGrabbing is false at this point, then there is nothing to
         // grab. Otherwise, invoke mGrabCallback to indicate that one or more
         // objects are now grabbed.
         if ( mGrabbing )
         {
            mGrabCallback(mGrabbedObjects, mIntersectPoint);
         }
      }
   }
   // If we are grabbing an object and the release button has just been
   // pressed, then release the grabbed object.
   else if ( mGrabbing && mReleaseBtn() )
   {
      // We no longer care about grabbable state changes because
      // mGrabbedObjects is about to be emptied.
      std::for_each(
         mObjConnections.begin(), mObjConnections.end(),
         boost::bind(&boost::signals::connection::disconnect,
                     boost::bind(&obj_conn_map_t::value_type::second, _1))
      );

      // Update our state to reflect that we are no longer grabbing an object.
      mGrabbing = false;
      mReleaseCallback(mGrabbedObjects);
      mGrabbedObjects.clear();
   }
}