コード例 #1
0
 uint64_t gini_square_term(std::vector<uint64_t> const& frequencies) const 
 {
     return std::inner_product( frequencies.begin(), frequencies.end(), frequencies.begin(), uint64_t(0));
 }
コード例 #2
0
ファイル: main.cpp プロジェクト: 00liujj/trilinos
bool CompareMetric::evaluate_with_Hessian_diagonal( PatchData& pd,
                 size_t handle,
                 double& value,
                 std::vector<size_t>& indices,
                 std::vector<Vector3D>& gradient,
                 std::vector<SymMatrix3D>& diagonal,
                 MsqError& err )
{
  double m2val;
  bool r1, r2;
  m2Handles.clear();
  m2Grad.clear();
  m2Diag.clear();
  r1 = metric1->evaluate_with_Hessian_diagonal( pd, handle, value, indices, gradient, diagonal, err ); MSQ_ERRZERO(err);
  r2 = metric2->evaluate_with_Hessian_diagonal( pd, handle, m2val, m2Handles, m2Grad, m2Diag, err ); MSQ_ERRZERO(err);
  if (r1 != r2 || (r1 && fabs(value - m2val) > epsilon)) {
    MSQ_SETERR(err)(MsqError::INVALID_STATE,
                    "Metrics returned different values for handle %lu in "
                    "evaluate_with_Hessian_diagonal:\n"
                    "\t%s %f vs. %s %f\n", (unsigned long)handle,
                    r1?"true":"false",value,r2?"true":"false",m2val);
  }
  else {
    std::vector<size_t>::const_iterator i, j;
    std::vector<Vector3D>::const_iterator r, s;
    std::vector<SymMatrix3D>::const_iterator u, v;
    int grad_diff = 0, hess_diff = 0;
    bool same = (indices.size() == m2Handles.size());
    std::sort( m2Handles.begin(), m2Handles.end() );
    for (i = indices.begin(); i != indices.end(); ++i) {
      j = std::lower_bound( m2Handles.begin(), m2Handles.end(), *i );
      if (j == m2Handles.end() || *j != *i) {
        same = false;
        continue;
      }
      
      r = gradient.begin() + (i - indices.begin());
      s = m2Grad.begin() + (j - m2Handles.begin());
      if (!equal(*r,*s))
        ++grad_diff;
      
      u = diagonal.begin() + (i - indices.begin());
      v = m2Diag.begin() + (j - m2Handles.begin());
      if (!equal(*u,*v))
        ++hess_diff;
    }
      
    if (!same) {
      MSQ_SETERR(err)(MsqError::INVALID_STATE,
                      "Metrics returned incompatible lists of vertex indices"
                      " for handle %lu in evaluate_with_Hessian_diagonal\n.", 
                      (unsigned long)handle );
    }
    else if (grad_diff) {
      MSQ_SETERR(err)(MsqError::INVALID_STATE,
                      "Metrics returned different gradient vectors for "
                      " %d of %u vertices for handle %lu in "
                      "evaluate_with_Hessian_diagonal\n.", 
                      grad_diff, (unsigned)gradient.size(), 
                      (unsigned long)handle );
    }
    else if (hess_diff) {
      MSQ_SETERR(err)(MsqError::INVALID_STATE,
                      "Metrics returned different Hessian blocks for "
                      " %d of %u vertices for handle %lu in "
                      "evaluate_with_Hessian_diagonal\n.", 
                      hess_diff, (unsigned)diagonal.size(), 
                      (unsigned long)handle );
    }
  }
  
  return r1 && !err;
}
コード例 #3
0
ファイル: bound_cond.cpp プロジェクト: ClaB90/pacs
 void BCBase::set_entities(std::vector<int> const & e)const {
   this->entities_.assign(e.begin(),e.end());
 }
コード例 #4
0
void LootManager::checkLoot(std::vector<Event_Component> &loot_table, FPoint *pos) {
	if (hero == NULL) {
		logError("LootManager: checkLoot() failed, no hero.\n");
		return;
	}

	FPoint p;
	Event_Component *ec;
	ItemStack new_loot;
	std::vector<Event_Component*> possible_ids;

	int chance = rand() % 100;

	// first drop any 'fixed' (0% chance) items
	for (unsigned i = loot_table.size(); i > 0; i--) {
		ec = &loot_table[i-1];
		if (ec->z == 0) {
			Point src;
			if (pos) {
				src = floor(*pos);
			}
			else {
				src.x = ec->x;
				src.y = ec->y;
			}
			p = mapr->collider.get_random_neighbor(src, drop_radius);

			if (!mapr->collider.is_valid_position(p.x, p.y, MOVEMENT_NORMAL, false)) {
				p = hero->pos;
			}
			else {
				if (src.x == p.x && src.y == p.y)
					p = hero->pos;

				mapr->collider.block(p.x, p.y, false);
				tiles_to_unblock.push_back(floor(p));
			}

			new_loot.quantity = randBetween(ec->a,ec->b);

			// an item id of 0 means we should drop currency instead
			if (ec->c == 0 || ec->c == CURRENCY_ID) {
				new_loot.item = CURRENCY_ID;
				new_loot.quantity = new_loot.quantity * (100 + hero->get(STAT_CURRENCY_FIND)) / 100;
			}
			else {
				new_loot.item = ec->c;
			}

			addLoot(new_loot, p);

			loot_table.erase(loot_table.begin()+i-1);
		}
	}

	// now pick up to 1 random item to drop
	int threshold = hero->get(STAT_ITEM_FIND) + 100;
	for (unsigned i = 0; i < loot_table.size(); i++) {
		ec = &loot_table[i];

		int real_chance = ec->z;

		if (ec->c != 0 && ec->c != CURRENCY_ID) {
			real_chance = (int)((float)ec->z * (hero->get(STAT_ITEM_FIND) + 100) / 100.f);
		}

		if (real_chance >= chance) {
			if (real_chance <= threshold) {
				if (real_chance != threshold) {
					possible_ids.clear();
				}

				threshold = real_chance;
			}

			if (chance <= threshold) {
				possible_ids.push_back(ec);
			}
		}
	}

	if (!possible_ids.empty()) {
		// if there was more than one item with the same chance, randomly pick one of them
		int chosen_loot = rand() % possible_ids.size();

		ec = possible_ids[chosen_loot];

		Point src;
		if (pos) {
			src = floor(*pos);
		}
		else {
			src.x = ec->x;
			src.y = ec->y;
		}
		p = mapr->collider.get_random_neighbor(src, drop_radius);

		if (!mapr->collider.is_valid_position(p.x, p.y, MOVEMENT_NORMAL, false)) {
			p = hero->pos;
		}
		else {
			if (src.x == p.x && src.y == p.y)
				p = hero->pos;

			mapr->collider.block(p.x, p.y, false);
			tiles_to_unblock.push_back(floor(p));
		}

		new_loot.quantity = randBetween(ec->a,ec->b);

		// an item id of 0 means we should drop currency instead
		if (ec->c == 0 || ec->c == CURRENCY_ID) {
			new_loot.item = CURRENCY_ID;
			new_loot.quantity = new_loot.quantity * (100 + hero->get(STAT_CURRENCY_FIND)) / 100;
		}
		else {
			new_loot.item = ec->c;
		}

		addLoot(new_loot, p);
	}
}
コード例 #5
0
void key(unsigned char key, int /*x*/, int /*y*/)
{
	switch ( key )
	{
        case 'l':
        {
            loadAnim();
            break;
        }
        case 'c':
        {
            FILE *file=fopen(animName.c_str(),"w");
            fclose(file);
            animOri.clear();
            animPos.clear();
            frameCount = 0;
            animTime = 0;
            break;
        }
        case 's':
        {
            FILE *file=fopen(animName.c_str(),"a");
            OSG::Matrix m=cam_trans->getMatrix();
            OSG::Quaternion q(m);
            OSG::Real32 ax,ay,az,r;
            animPos.push_back(OSG::Vec3f(m[3][0],
                                         m[3][1],
                                         m[3][2]));
            animOri.push_back(q);
            q.getValueAsAxisRad(ax,ay,az,r);
            fprintf(file,"%f %f %f %f,%f %f %f\n",ax,ay,az,r,
                    m[3][0],
                    m[3][1],
                    m[3][2]);
            fclose(file);
            frameCount = 0;
            animTime = 0;
            break;
        }
        case 'S':
        {
            FILE *file=fopen((animName+".wrl").c_str(),"w");
            std::vector<OSG::Quaternion>::iterator qit;
            
            fprintf(file,"DEF OriInter OrientationInterpolator {\n\tkey [");
            for(size_t i = 0; i < animOri.size(); ++i)
            {               
                fprintf(file, "%f", i / OSG::Real32(animOri.size() - 1) );
                if(i < animOri.size() - 1)
                    fprintf(file,", ");
            }
            fprintf(file,"]\n\tkeyValue [");
            for(qit = animOri.begin(); qit != animOri.end(); ++qit)
            {
                OSG::Real32 ax,ay,az,r;
                (*qit).getValueAsAxisRad(ax,ay,az,r);
                
                fprintf(file, "%f %f %f %f", ax, ay, az, r );
                if(qit < animOri.end() - 1)
                    fprintf(file,", ");
            }
            fprintf(file,"]\n}\n\n");

            std::vector<OSG::Vec3f>::iterator vit;
            
            fprintf(file,"DEF PosInter PositionInterpolator {\n\tkey [");
            for(size_t i = 0; i < animPos.size(); ++i)
            {               
                fprintf(file, "%f", i / OSG::Real32(animPos.size() - 1) );
                if(i < animPos.size() - 1)
                    fprintf(file,", ");
            }
            fprintf(file,"]\n\tkeyValue [");
            for(vit = animPos.begin(); vit != animPos.end(); ++vit)
            {
                OSG::Vec3f v = *vit;
                
                fprintf(file, "%f %f %f, ", v[0], v[1], v[2] );
            }
            fprintf(file,"]\n}\n\n");

            fclose(file);
            break;
        }
        case 'j':
            if(sortfirst!=NULL)
            {
                sortfirst->setCompression("JPEG");
            }
            break;
        case 'r':
            if(sortfirst!=NULL)
            {
                sortfirst->setCompression("RLE");
            }
            break;
        case 'n':
            if(sortfirst!=NULL)
            {
                sortfirst->editCompression().erase();
            }
            break;
        case 'i':
            showInfo = !showInfo;
            break;
        case 'w':
            if(polygonChunk->getFrontMode() == GL_FILL)
                polygonChunk->setFrontMode(GL_LINE);
            else
                polygonChunk->setFrontMode(GL_FILL);

            if(polygonChunk->getBackMode() == GL_FILL)
                polygonChunk->setBackMode(GL_LINE);
            else
                polygonChunk->setBackMode(GL_FILL);
            break;
        case 'a':
            if(animate)
            {
                glutIdleFunc(NULL);       
                animate=false;
            }
            else
            {
                glutIdleFunc(display);       
                animate=true;
            }
            frameCount = 0;
            animTime = 0;
            break;
        case 'd':
            // remove tree
            while(root->getNChildren())
            {
                root->subChild(0u);
            }
            break;
        case '+':
            _dsFactor += 0.01f;
            if(_dsFactor > 1.0f)
                _dsFactor = 1.0f;
            setHEyeWallParameter(_dsFactor, _enablecc);
            break;
        case '-':
            _dsFactor -= 0.01f;
            if(_dsFactor <= 0.0f)
                _dsFactor = 0.01f;
            setHEyeWallParameter(_dsFactor, _enablecc);
            break;
        case 'f':
            if(_enablecc)
                _enablecc = false;
            else
                _enablecc = true;
            setHEyeWallParameter(_dsFactor, _enablecc);
            break;
        case 'B':
            if(bkgnd->getColor()[0] == 0.0)
                bkgnd->setColor( OSG::Color3f(1,1,1) );
            else
                bkgnd->setColor( OSG::Color3f(0,0,0) );
            break;
        case 27:	// should kill the clients here
            // exit
            cleanup();
            OSG::osgExit(); 
            exit(0);
	}
	
	glutPostRedisplay();
}
コード例 #6
0
void SudokuGenerator::removeFromValue (std::vector<char>& vector, int pos) const {
    vector.erase (vector.begin () + pos);
}
コード例 #7
0
ファイル: SGSpatialSort.cpp プロジェクト: 123woodman/minko
// ------------------------------------------------------------------------------------------------
// Returns an iterator for all positions close to the given position.
void SGSpatialSort::FindPositions( const aiVector3D& pPosition, 
	uint32_t pSG,
	float pRadius,
	std::vector<unsigned int>& poResults,
	bool exactMatch /*= false*/) const
{
	float dist = pPosition * mPlaneNormal;
	float minDist = dist - pRadius, maxDist = dist + pRadius;

	// clear the array in this strange fashion because a simple clear() would also deallocate
	// the array which we want to avoid
	poResults.erase( poResults.begin(), poResults.end());

	// quick check for positions outside the range
	if( mPositions.size() == 0)
		return;
	if( maxDist < mPositions.front().mDistance)
		return;
	if( minDist > mPositions.back().mDistance)
		return;

	// do a binary search for the minimal distance to start the iteration there
	unsigned int index = (unsigned int)mPositions.size() / 2;
	unsigned int binaryStepSize = (unsigned int)mPositions.size() / 4;
	while( binaryStepSize > 1)
	{
		if( mPositions[index].mDistance < minDist)
			index += binaryStepSize;
		else
			index -= binaryStepSize;

		binaryStepSize /= 2;
	}

	// depending on the direction of the last step we need to single step a bit back or forth
	// to find the actual beginning element of the range
	while( index > 0 && mPositions[index].mDistance > minDist)
		index--;
	while( index < (mPositions.size() - 1) && mPositions[index].mDistance < minDist)
		index++;

	// Mow start iterating from there until the first position lays outside of the distance range.
	// Add all positions inside the distance range within the given radius to the result aray

	float squareEpsilon = pRadius * pRadius;
	std::vector<Entry>::const_iterator it  = mPositions.begin() + index;
	std::vector<Entry>::const_iterator end = mPositions.end();

	if (exactMatch)
	{
		while( it->mDistance < maxDist)
		{
			if((it->mPosition - pPosition).SquareLength() < squareEpsilon && it->mSmoothGroups == pSG)
			{
				poResults.push_back( it->mIndex);
			}
			++it;
			if( end == it )break;
		}
	}
	else
	{
		// if the given smoothing group is 0, we'll return all surrounding vertices
		if (!pSG)
		{
			while( it->mDistance < maxDist)
			{
				if((it->mPosition - pPosition).SquareLength() < squareEpsilon)
					poResults.push_back( it->mIndex);
				++it;
				if( end == it)break;
			}
		}
		else while( it->mDistance < maxDist)
		{
			if((it->mPosition - pPosition).SquareLength() < squareEpsilon &&
				(it->mSmoothGroups & pSG || !it->mSmoothGroups))
			{
				poResults.push_back( it->mIndex);
			}
			++it;
			if( end == it)break;
		}
	}
}
コード例 #8
0
//recall that n_v is the number of vertices (not the number of tokens in a sentence such as in the previous case)
Graph::Graph(int n_v, std::vector<Edge>& vect) {
	no_of_vertices = n_v;
	for (std::vector<Edge>::iterator it = vect.begin(); it != vect.end(); it++) {
		arr_edge.push_back(*it); //deep copy
	}
}
コード例 #9
0
ファイル: MaterialData.C プロジェクト: AhmedAly83/moose
void
MaterialData::reinit(const std::vector<MooseSharedPointer<Material> > & mats)
{
  for (std::vector<MooseSharedPointer<Material> >::const_iterator it = mats.begin(); it != mats.end(); ++it)
    (*it)->computeProperties();
}
コード例 #10
0
std::vector<Blob> BlobCheck::CheckIfBlobIsLicensePlate(std::vector<Blob> &blobobjects, std::vector< std::vector<int> > blobMap) {

	std::vector<Blob> validBlobs;
	//check if blob of possible licenseplate
	for (std::vector<Blob>::iterator it = blobobjects.begin(); it != blobobjects.end(); ++it) {
		double ratio = it->getRatio();
		if (ratio >= 2.1 && ratio <= 5.5) {
			int edgeCounter = 0;
			int lastBlobId = 0;


			int smallY = it->getSmallestY();
			int smallX = it->getSmallestX();

			int bigY = it->getBiggestY();
			int bigX = it->getBiggestX();

			int y = ((bigY - smallY) / 2) + smallY;

			for (int x = smallX; x < bigX; x++){
				if (blobMap[y][x] != lastBlobId){
					edgeCounter++;
					lastBlobId = blobMap[y][x];
				}
			}
			if (edgeCounter >= 5)
				validBlobs.insert(validBlobs.end(), *it);
		}
	}

	//std::cout << "validBlobs: " << validBlobs.size() << std::endl;

	for (std::vector<Blob>::iterator it = validBlobs.begin(); it != validBlobs.end(); it++) {

		int blobId = it->getId();
		int h = it->getHeight();

		bool labelFound = false;

		int cornerTLY = -1;
		int cornerTLX = -1;

		int cornerTRY = -1;
		int cornerTRX = -1;

		int cornerBLY = -1;
		int cornerBLX = -1;

		int cornerBRY = -1;
		int cornerBRX = -1;


		int minFlatRate = 2;

		int lastY = -1;
		int flatCnt = 0;

		int smallY = it->getSmallestY();
		int smallX = it->getSmallestX();

		int bigY = it->getBiggestY();
		int bigX = it->getBiggestX();

		int halfX = smallX + ((bigX - smallX) / 2);
		int halfY = smallY + ((bigY - smallY) / 2);

		//Top Left
		for (int x = halfX; x > smallX; x--) {
			for (int y = smallY; y < bigY && labelFound == false; y++) {
				//We found the label we are looking for. 
				if (blobMap[y][x] == blobId) {
					labelFound = true;
					if (lastY == -1) lastY = y;
					if (y == lastY) {
						flatCnt++;
						if (flatCnt >= minFlatRate && y < halfY) {
							cornerTLY = y;
							cornerTLX = x;
						}
					}
					else {
						flatCnt = 0;
					}
					lastY = y;
				}
			}
			labelFound = false;
		}

		flatCnt = 0;
		lastY = -1;

		//Top right
		for (int x = halfX; x < bigX; x++) {
			for (int y = smallY; y < bigY && labelFound == false; y++) {
				//We found the label we are looking for. 
				if (blobMap[y][x] == blobId) {
					labelFound = true;
					if (lastY == -1) lastY = y;
					if (y == lastY) {
						flatCnt++;
						if (flatCnt >= minFlatRate && y < halfY) {
							cornerTRY = y;
							cornerTRX = x;
						}
					}
					else {
						flatCnt = 0;
					}
					lastY = y;
				}
			}
			labelFound = false;
		}

		flatCnt = 0;
		lastY = -1;

		// Bot left
		for (int x = halfX; x > smallX; x--) {
			for (int y = bigY; y > smallY && labelFound == false; y--) {
				//We found the label we are looking for. 
				if (blobMap[y][x] == blobId) {
					labelFound = true;
					if (lastY == -1) lastY = y;
					if (y == lastY) {
						flatCnt++;
						if (flatCnt >= minFlatRate && y > halfY) {
							cornerBLY = y;
							cornerBLX = x;
						}
					}
					else {
						flatCnt = 0;
					}
					lastY = y;
				}
			}
			labelFound = false;
		}

		flatCnt = 0;
		lastY = -1;

		//Bot right
		for (int x = halfX; x < bigX; x++) {
			for (int y = bigY; y > smallY && labelFound == false; y--) {
				//We found the label we are looking for. 
				if (blobMap[y][x] == blobId) {
					labelFound = true;
					if (lastY == -1) lastY = y;
					if (y == lastY) {
						flatCnt++;
						if (flatCnt >= minFlatRate && y > halfY) {
							cornerBRY = y;
							cornerBRX = x;
						}
					}
					else {
						flatCnt = 0;
					}
					lastY = y;
				}
			}
			labelFound = false;
		}

		std::vector<int> cornerPoints(8);
		cornerPoints[0] = cornerTLX;
		cornerPoints[1] = cornerTLY;
		cornerPoints[2] = cornerTRX;
		cornerPoints[3] = cornerTRY;
		cornerPoints[4] = cornerBLX;
		cornerPoints[5] = cornerBLY;
		cornerPoints[6] = cornerBRX;
		cornerPoints[7] = cornerBRY;

		it->setCornerPoints(cornerPoints);

	}

	return validBlobs;
}
コード例 #11
0
ファイル: chmain.cpp プロジェクト: e-h-j/freeorion
int mainConfigOptionsSetup(const std::vector<std::string>& args) {
    InitDirs((args.empty() ? "" : *args.begin()));

    // read and process command-line arguments, if any
    try {
        // add entries in options DB that have no other obvious place
        GetOptionsDB().AddFlag('h', "help",                 UserStringNop("OPTIONS_DB_HELP"),                  false);
        GetOptionsDB().AddFlag('g', "generate-config-xml",  UserStringNop("OPTIONS_DB_GENERATE_CONFIG_XML"),   false);
        GetOptionsDB().AddFlag('f', "fullscreen",           UserStringNop("OPTIONS_DB_FULLSCREEN"),            STORE_FULLSCREEN_FLAG);
        GetOptionsDB().Add("reset-fullscreen-size",         UserStringNop("OPTIONS_DB_RESET_FSSIZE"),          true);
        GetOptionsDB().Add<int>("fullscreen-monitor-id",    UserStringNop("OPTIONS_DB_FULLSCREEN_MONITOR_ID"), 0, RangedValidator<int>(0, 5));
        GetOptionsDB().AddFlag('q', "quickstart",           UserStringNop("OPTIONS_DB_QUICKSTART"),            false);
        GetOptionsDB().AddFlag("auto-advance-first-turn",   UserStringNop("OPTIONS_DB_AUTO_FIRST_TURN"),       false);
        GetOptionsDB().Add<std::string>("load",             UserStringNop("OPTIONS_DB_LOAD"),                  "", Validator<std::string>(), false);
        GetOptionsDB().Add("UI.sound.music-enabled",        UserStringNop("OPTIONS_DB_MUSIC_ON"),              true);
        GetOptionsDB().Add("UI.sound.enabled",              UserStringNop("OPTIONS_DB_SOUND_ON"),              true);
        GetOptionsDB().Add<std::string>("version-string",   UserStringNop("OPTIONS_DB_VERSION_STRING"),
                                        FreeOrionVersionString(),   Validator<std::string>(),                  true);
        GetOptionsDB().AddFlag('r', "render-simple",        UserStringNop("OPTIONS_DB_RENDER_SIMPLE"),         false);

        // Add the keyboard shortcuts
        Hotkey::AddOptions(GetOptionsDB());


        // read config.xml and set options entries from it, if present
        {
            XMLDoc doc;
            try {
                boost::filesystem::ifstream ifs(GetConfigPath());
                if (ifs) {
                    doc.ReadDoc(ifs);
                    // reject config files from out-of-date version
                    if (doc.root_node.ContainsChild("version-string") &&
                        doc.root_node.Child("version-string").Text() == FreeOrionVersionString())
                    {
                        GetOptionsDB().SetFromXML(doc);
                    }
                }
            } catch (const std::exception&) {
                std::cerr << UserString("UNABLE_TO_READ_CONFIG_XML") << std::endl;
            }
        }


        // override previously-saved and default options with command line parameters and flags
        GetOptionsDB().SetFromCommandLine(args);


        // Handle the case where the resource-dir does not exist anymore
        // gracefully by resetting it to the standard path into the
        // application bundle.  This may happen if a previous installed
        // version of FreeOrion was residing in a different directory.
        if (!boost::filesystem::exists(GetResourceDir()) ||
            !boost::filesystem::exists(GetResourceDir() / "credits.xml") ||
            !boost::filesystem::exists(GetResourceDir() / "data" / "art" / "misc" / "missing.png"))
        {
            Logger().debugStream() << "Resources directory from config.xml missing or does not contain expected files. Resetting to default.";

            GetOptionsDB().Set<std::string>("resource-dir", "");

            // double-check that resetting actually fixed things...
            if (!boost::filesystem::exists(GetResourceDir()) ||
                !boost::filesystem::exists(GetResourceDir() / "credits.xml") ||
                !boost::filesystem::exists(GetResourceDir() / "data" / "art" / "misc" / "missing.png"))
            {
                Logger().debugStream() << "Default Resources directory missing or does not contain expected files. Cannot start game.";

                std::string path_string;
#if defined(FREEORION_WIN32)
                boost::filesystem::path::string_type path_string_native = GetResourceDir().native();
                utf8::utf16to8(path_string_native.begin(), path_string_native.end(), std::back_inserter(path_string));
#else
                path_string = GetResourceDir().string();
#endif
                throw std::runtime_error("Unable to load game resources at default location: " +
                                         path_string + " : Install may be broken.");
            }
        }


        // did the player request generation of config.xml, saving the default (or current) options to disk?
        if (GetOptionsDB().Get<bool>("generate-config-xml")) {
            try {
                boost::filesystem::ofstream ofs(GetConfigPath());
                if (ofs) {
                    GetOptionsDB().GetXML().WriteDoc(ofs);
                } else {
                    std::cerr << UserString("UNABLE_TO_WRITE_CONFIG_XML") << std::endl;
#if defined(FREEORION_WIN32)
                    boost::filesystem::path::string_type path_string_native = GetConfigPath().native();
                    std::string path_string;
                    utf8::utf16to8(path_string_native.begin(), path_string_native.end(), std::back_inserter(path_string));
                    std::cerr << path_string << std::endl;
#else
                    std::cerr << GetConfigPath().string() << std::endl;
#endif
                }
            } catch (const std::exception&) {
                std::cerr << UserString("UNABLE_TO_WRITE_CONFIG_XML") << std::endl;
            }
        }

        if (GetOptionsDB().Get<bool>("render-simple")) {
            GetOptionsDB().Set<bool>("UI.galaxy-gas-background",false);
            GetOptionsDB().Set<bool>("UI.galaxy-starfields",    false);
            GetOptionsDB().Set<bool>("show-fps",                true);
        }

    } catch (const std::invalid_argument& e) {
        std::cerr << "main() caught exception(std::invalid_argument): " << e.what() << std::endl;
        boost::this_thread::sleep(boost::posix_time::seconds(3));
        return 1;
    } catch (const std::runtime_error& e) {
        std::cerr << "main() caught exception(std::runtime_error): " << e.what() << std::endl;
        boost::this_thread::sleep(boost::posix_time::seconds(3));
        return 1;
    } catch (const std::exception& e) {
        std::cerr << "main() caught exception(std::exception): " << e.what() << std::endl;
        boost::this_thread::sleep(boost::posix_time::seconds(3));
        return 1;
    } catch (...) {
        std::cerr << "main() caught unknown exception." << std::endl;
        return 1;
    }

    return 0;
}
コード例 #12
0
ファイル: Permutator.cpp プロジェクト: De117/PErmutator
void Permutator::_CreateGraph(BYTE* sectionData, _OffsetType blockOffset, DWORD dwSectionSize, _OffsetType parentOffset,
	std::vector<Block>& targets)
{
	_DecodeResult res;
	unsigned int decodedInstructionsCount = 0;
	_DecodeType dt = Decode32Bits;
	_OffsetType offset = blockOffset;
	_OffsetType offsetEnd;
	_DecodedInst decodedInstructions[MAX_INSTRUCTIONS];
	unsigned int i;
	QWORD tmpOffset = blockOffset;
	std::string mnemonic, operand;
	bool skipFlag;

	while (1)
	{
		res = distorm_decode(offset, (const unsigned char*)sectionData, dwSectionSize,
			dt, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount);
		if (res == DECRES_INPUTERR)
		{
			free(sectionData);
			return;
		}

		for (i = 0; i < decodedInstructionsCount; ++i)
		{ 
			mnemonic = (reinterpret_cast<char*>(decodedInstructions[i].mnemonic.p));
			if (IsJump(mnemonic) ||
				mnemonic.compare("RET") == 0 ||
				mnemonic.compare("RETN") == 0 ||
				mnemonic.substr(0, 2).compare("DB") == 0)
			{
				break;
			}

			if (mnemonic.compare("CALL") == 0)
			{
				std::string functionOperand = reinterpret_cast<char*> (decodedInstructions[i].operands.p);
				if (IsRegister(functionOperand) || !IsFunctionOperandValid(functionOperand))
					continue;

				QWORD functionOffset = std::stoll(functionOperand, nullptr, 0);
				graph.AddFunctionOffset(tmpOffset, functionOffset - tmpOffset);
			}

			tmpOffset += decodedInstructions[i].size;
		}

		// Main part of graph creation
		offsetEnd = decodedInstructions[i].offset;
		DWORD blockSize = (DWORD)(offsetEnd + decodedInstructions[i].size - offset);
		Node* node = new Node();

		// Set 1 to block places in dataBytes
		for (DWORD j = 0; j < blockSize; ++j)
		{
			dataBytes[blockOffset + j] = 1;
		}

		node->SetOffset((DWORD)offset);
		node->SetInstructions(sectionData, blockSize);

// Newly added code
		skipFlag = false;
		for (std::vector<Block>::iterator it = targets.begin(); it != targets.end(); ++it)
		{
			if (((*it).offset == node->GetOffset()) && (*it).parentOffset == parentOffset)
			{
				skipFlag = true;
				break;
			}
		}
		if (skipFlag)
			return;
		Block b;
		b.offset = node->GetOffset();
		b.parentOffset = parentOffset;
		targets.push_back(b);

		if (graph.AddNode(node, (DWORD)parentOffset))
		{
			return;
		}

		if (mnemonic.compare("RET") == 0 ||
			mnemonic.compare("RETN") == 0 ||
			mnemonic.substr(0, 2).compare("DB") == 0)
			return;

		operand = reinterpret_cast<char*>(decodedInstructions[i].operands.p);
		operand.resize(decodedInstructions[i].operands.length);
		if (IsRegister(operand))
			return;

		QWORD newOffset = std::stoll(operand, nullptr, 0);

		if (!CheckRange(newOffset))
		{
			std::cerr << "Offset out of CODE section!" << std::endl;
			return;
		}

		_CreateGraph(sectionData + blockSize + (newOffset - offsetEnd - decodedInstructions[i].size),
					 newOffset,
					 dwSectionSize - (DWORD)newOffset + (DWORD)offset,
					 node->GetOffset(),
					 targets);

		if (mnemonic.compare("JMP") == 0)
			return;

		QWORD jumpFalseOffset = offsetEnd + decodedInstructions[i].size;
		
		_CreateGraph(sectionData + jumpFalseOffset - offset,
			jumpFalseOffset,
			dwSectionSize - (DWORD)jumpFalseOffset + (DWORD)offset,
			node->GetOffset(),
			targets);

		break;
	}
}
コード例 #13
0
ファイル: top_k.cpp プロジェクト: FuckBaidu/FuckInterview
std::vector<int> TopK2(std::vector<int> &input, int k) {
    TopK(input, 0, (int)input.size() - 1, k);
    return std::vector<int>(input.begin(), input.begin() + k);
}
コード例 #14
0
void rgb_pcl::getTracker(std::vector<PointCloudPtr> object_clouds, Mat displayImage){
	
	
	//Assign tracker to the clouds
	for(unsigned int count1 = 0; count1 < trackerList.size(); count1++){
		cv::Point3d position(0, 0, 0);
		double maxScore = 0;
		int id_cloud = -1;
		cv::Point3d pos_tracker;
		int size_tracker;
		double hue_tracker;
		
		for(unsigned int count2 = 0; count2 < object_clouds.size(); count2 ++){
			int size = object_clouds[count2]->points.size();
			
			cv::Point3d position(0, 0, 0);
			double hue = 0;
			
			getCloudFeatures(position, hue, object_clouds[count2]);
			
			double score = trackerList[count1].isRecognized(position, 0, size);
			if(score > maxScore){
				maxScore = score;
				id_cloud = count2;
				pos_tracker = position;
				size_tracker = size;
				hue_tracker = hue;
			}
		}
		if(id_cloud != -1){
			trackerList[count1].updateTracker(pos_tracker, hue_tracker, size_tracker, object_clouds[id_cloud]);
			object_clouds.erase(object_clouds.begin()+id_cloud);
		}
	}
// 	cout<<trackerList.size()<<endl;
	//Create new tracker for the remaining clouds
	for(auto cloudCluster: object_clouds){
		int size = object_clouds[0]->points.size();
		
		cv::Point3d position(0, 0, 0);
		double hue = 0;
		
		getCloudFeatures(position, hue, cloudCluster);
		
		track_3d newTracker(position, hue, size);
		trackerList.push_back(newTracker);
	}
	
	//Delete lost tracker and display tracked clouds
	for(unsigned int count = 0; count < trackerList.size(); count ++){
		trackerList[count].step();
		if(!trackerList[count].isAlive()){
			trackerList.erase(trackerList.begin()+count);
			count --;
		}else if(trackerList[count].isFound() && !trackerList[count].isGone()){
#if DISPLAY
			drawTrackers(displayImage, trackerList[count], to_string(count));
#endif
		}
	}
}
コード例 #15
0
ファイル: Filters.cpp プロジェクト: johngalt131/Reports
void Filters::FilterList::TestElements(std::vector<GContainer::Container *> &test){
  std::vector< std::vector<GContainer::Container *> > masterList;
  std::vector<GContainer::Container *> originalList = test;
  std::vector<GContainer::Container *> newList;
  std::vector<FilterGroup *>::iterator gItr = _allFilters.begin();
  for(; gItr != _allFilters.end(); gItr++){
    std::vector<Filter *>::iterator fItr = (*gItr)->_filters.begin();
    for(; fItr != (*gItr)->_filters.end(); fItr++){
      GContainer::ContainerIterator * theFilter = (*fItr)->Container()->GetIterator();
      if(not theFilter->Begin()){
	std::cout << "There was a problem with the Filter." <<std::endl;
	exit(-4);
      }
      std::vector<GContainer::Container *>::iterator itr = test.begin();
      for( ; itr != test.end() ; itr++){
	bool testVal = false;
	GContainer::ContainerIterator * theRecord = (*itr)->GetIterator();
	if( not theRecord->Find(theFilter->iterator->first)){
	  std::cout << "This record has no field " << theFilter->iterator->first << std::endl;
	  continue;
	}
	switch((*fItr)->GetType()){
	case EQUAL:
	  testVal = (*(theRecord->iterator->second) == (theFilter->iterator->second));
	  break;
	case CONTAINS:
	  testVal = false;//(*(theRecord->iterator->second)->Contains(theFilter->iterator->second));
	  break;
	case LESS_THAN:
	  testVal = (*(theRecord->iterator->second) < (theFilter->iterator->second));
	  break;
	case LESS_THAN_OR_EQUAL:
	  testVal = (*(theRecord->iterator->second) <= (theFilter->iterator->second));
	  break;
	case GREATER_THAN:
	  testVal = (*(theRecord->iterator->second) > (theFilter->iterator->second));
	  break;
	case GREATER_THAN_OR_EQUAL:
	  testVal = (*(theRecord->iterator->second) >= (theFilter->iterator->second));
	  break;
	case NOT_EQUAL:
	  testVal = (*(theRecord->iterator->second) != (theFilter->iterator->second));
	  break;
	default:
	  std::cout << "Bad type. Check your filter file." << std::endl;
	  break;
	}
	if(testVal){
	  newList.push_back(*itr);
	}
      }
      test.clear();
      test = newList;
      newList.clear();
    }
    masterList.push_back(test);
    newList.clear();
    test = originalList;
    std::cout << " master List has " << masterList.size() << " elements" << std::endl;
  }
  test.clear();
  std::vector< std::vector<GContainer::Container *> >::iterator mItr = masterList.begin();
  for(; mItr != masterList.end(); mItr++){
    std::vector<GContainer::Container *>::iterator lItr = mItr->begin();
    for(; lItr != mItr->end(); lItr++){
      test.push_back(*lItr);
    }
  }
}
コード例 #16
0
void clang_registerCheckers(clang::ento::CheckerRegistry &registry) {
  for(std::vector<register_checker_callback_t>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) {
    (*it)(registry);
  }
}
コード例 #17
0
void SudokuGenerator::removeFromCell (std::vector<std::pair<int,int>>& vector, int pos) const {
    vector.erase (vector.begin () + pos);
}
コード例 #18
0
//===========================================================================
std::vector<std::vector<double> > 
TrimCrvUtils::splitCurvePointsInKinks(const std::vector<double>& trim_pts_2d,
				      double kink_tol)
//===========================================================================
{
  vector<vector<double> > segment_pts;

  // We must handle noise in the input data and can not use the direction between two consecutive points to define
  // the kinks in the boundary curve. We use the average of a certain number of points in both directions to
  // estimate the direction.
  const int num_avg_pts_both_dirs = 5; //10;//50;//10;//5;

  // @@sbr201410 Do not compare with previous direction, longer back!
  //MESSAGE("Check direction change vs pts[ki-num_avg_pts_both_dirs]");

  // const double kink_tol = 5e-01; // 0.1 deg => 5.7 degrees.
  // If the direction changes more than a certain tol after num_avg_pts, we define this as a kink and must
  // locate the point for which this change of direction is most prominent.
  double tol = 1.0e-4;
  const int num_pts = (int)trim_pts_2d.size()/2;
  double dd = Utils::distance_squared(trim_pts_2d.begin(),
				      trim_pts_2d.begin()+2,
				      trim_pts_2d.end()-2);
  bool closed = (dd < tol);
  if (num_pts <= 2*num_avg_pts_both_dirs)
    {
      segment_pts.push_back(trim_pts_2d);
      return segment_pts;
    }

  vector<int> segment_ind; // We store all kink indices.
  segment_ind.push_back(0);
  Point prev_dir = averageDirection(trim_pts_2d, 0, num_avg_pts_both_dirs);
  //MESSAGE("num_pts: " << num_pts);
  vector<Point> avg_dirs(num_pts, Point(0.0, 0.0));
  vector<double> angles(num_pts, 0.0);
  for (int ki = num_avg_pts_both_dirs; ki < num_pts - num_avg_pts_both_dirs; ++ki)
    {
      int from = std::max(0, ki - num_avg_pts_both_dirs);
      int to = std::min(ki + num_avg_pts_both_dirs, num_pts - 1);

      Point avg_dir = averageDirection(trim_pts_2d, from, to);
      avg_dir.normalize();
      avg_dirs[ki] = avg_dir;
      if (avg_dir.length() == 0)
	{ // Typically this means the we are turning around 180 degrees in the current point.
	  MESSAGE("Something strange with the input I suspect!");
	  continue;
	}
      //	    double angle = prev_dir.angle(avg_dir);
      if (avg_dirs[ki-num_avg_pts_both_dirs].length() > 0.0 && avg_dir.length() > 0.0)
	{
	  double angle = avg_dirs[ki-num_avg_pts_both_dirs].angle(avg_dir);
	  angles[ki] = angle;
	  if (angle > kink_tol)
	    {
	      //MESSAGE("ki = " << ki << ", angle = " << angle);
	      segment_ind.push_back(ceil(ki-0.5*num_avg_pts_both_dirs));
	    }
	}
      //	    prev_dir = avg_dir;
    }

  segment_ind.push_back(num_pts - 1);

#ifdef DEBUG
  { // We write to file the point and the segments surrounding it.
    vector<double> corner_pts;
    for (size_t ki = 0; ki < segment_ind.size(); ++ki)
      {
	corner_pts.push_back(trim_pts_2d[segment_ind[ki]*2]);
	corner_pts.push_back(trim_pts_2d[segment_ind[ki]*2+1]);
	corner_pts.push_back(0.0); // We place the pts in the z-plane.
      }

    LineCloud trim_pts;

    PointCloud3D end_pts(corner_pts.begin(), corner_pts.size()/3);
    std::ofstream fileout_debug("tmp/ptset_debug.g2");
    //MESSAGE("Writing to file the end pts of segments.");
    // end_pts.writeStandardHeader(fileout_debug);
    fileout_debug << "400 1 0 4 255 0 0 255" << endl;
    end_pts.write(fileout_debug);
    //MESSAGE("Done writing to file the end pts of segments.");
  }
#endif

  bool split_into_segments = true;
  if (split_into_segments)
    {
      // We run through and split based on segment_ind.
      // When there is a consecutive row of indices we choose the middle one.
      vector<int> thinned_segment_ind;
      int counter = 0;
      for (size_t ki = 0; ki < segment_ind.size(); ++ki)
	{
	  if ((ki < segment_ind.size() - 1) && (segment_ind[ki] + 1 == segment_ind[ki+1]))
	    {
	      ++counter;
	    }
	  else
	    {
	      if (counter > num_pts/4 && closed)
		{
		  // Split in both end points to avoid a too
		  // restricted loop
		  if (segment_ind[ki] > counter)
		    thinned_segment_ind.push_back(segment_ind[ki] - counter);
		  if (segment_ind[ki] < num_pts - 1)
		    thinned_segment_ind.push_back(segment_ind[ki]);
		  counter = 0;
		}
	      else if (counter > 1)
		{
		  vector<double> ang(counter);
		  for (size_t ka=0; ka<counter; ++ka)
		    {
		      int kb = segment_ind[ki] - counter + ka;
		      int from = std::max(0, kb - num_avg_pts_both_dirs);
		      int to = std::min(kb + num_avg_pts_both_dirs, num_pts - 1);

		      // Point avg_dir1 = averageDirection(trim_pts_2d, 
		      // 				    from, kb);
		      // Point avg_dir2 = averageDirection(trim_pts_2d, 
		      // 				    kb, to);
		      Point avg_dir1(trim_pts_2d[2*kb]-trim_pts_2d[2*from], 
				     trim_pts_2d[2*kb+1]-trim_pts_2d[2*from+1]);
		      Point avg_dir2(trim_pts_2d[2*to]-trim_pts_2d[2*kb], 
				     trim_pts_2d[2*to+1]-trim_pts_2d[2*kb+1]);
		      ang[ka] = avg_dir1.angle(avg_dir2);
		    }
		  int stop_break = 1;

		  // We are at the end of a consecutive stream of indices. 
		  // Picking the most significant one.
		  //int avg_ind = segment_ind[ki] - floor(0.5*counter);
		      
		  //cout << "avg_ind: " << avg_ind << endl;
		  double max_val = ang[0];
		  int max_ind = 0;
		  for (int kb=1; kb<(int)ang.size(); ++kb)
		    {
		      if (ang[kb] > max_val)
			{
			  max_val = ang[kb];
			  max_ind = kb;
			}
		    }
		  thinned_segment_ind.push_back(segment_ind[ki] - counter + max_ind);
		  counter = 0;
		}
	      else
		thinned_segment_ind.push_back(segment_ind[ki]);
	    }
	}

      // First and last point should be included, but we make sure anyway.
      if (thinned_segment_ind.front() != 0)
	{
	  thinned_segment_ind.insert(thinned_segment_ind.begin(), 0);
	}
      if (thinned_segment_ind.back() != num_pts - 1)
	{
	  thinned_segment_ind.push_back(num_pts - 1);
	}

#ifdef DEBUG
      { // We write to file the point and the segments surrounding it.
	vector<double> corner_pts;
	for (size_t ki = 0; ki < thinned_segment_ind.size(); ++ki)
	  {
	    corner_pts.push_back(trim_pts_2d[thinned_segment_ind[ki]*2]);
	    corner_pts.push_back(trim_pts_2d[thinned_segment_ind[ki]*2+1]);
	    corner_pts.push_back(0.0); // We place the pts in the z-plane.
	  }

	LineCloud trim_pts;

	PointCloud3D end_pts(corner_pts.begin(), corner_pts.size()/3);
	std::ofstream fileout_debug("tmp/ptset_debug2.g2");
	MESSAGE("Writing to file the end pts of segments.");
	// end_pts.writeStandardHeader(fileout_debug);
	fileout_debug << "400 1 0 4 0 255 0 255" << endl;
	end_pts.write(fileout_debug);
	MESSAGE("Done writing to file the end pts of segments.");
      }
#endif

      int num_segments = thinned_segment_ind.size() - 1;
      segment_pts.resize(num_segments);
      for (size_t ki = 0; ki < thinned_segment_ind.size() - 1; ++ki)
	{
	  int first = thinned_segment_ind[ki];
	  int last = thinned_segment_ind[ki+1];
	  segment_pts[ki].insert(segment_pts[ki].end(),
				 trim_pts_2d.begin() + 2*first, trim_pts_2d.begin() + 2*(last + 1));
	}

      //	MESSAGE("Returning the input for now ...");
      //	segment_pts.push_back(trim_pts_2d);
    }
  else
    {
      MESSAGE("Returning the input for now ...");
      segment_pts.push_back(trim_pts_2d);
    }

  return segment_pts;
}
コード例 #19
0
ファイル: NetFacHTTP.cpp プロジェクト: hackshields/antivirus
const std::vector<unsigned char> KLUPD::HttpProtocol::HTTPRequestBuilder::generateRequest(const Path &fileName, const Path &relativeUrlPath,
    const bool useProxy, const Address &serverAddress,
    const std::string &userAgent,
    const std::string &proxyAuthorizationHeader,
    const size_t regettingPosition,
    const std::vector<unsigned char> &postData)
{
    m_requestBuffer.clear();

    // 1. "GET ftp://user:[email protected]/path/file.xml HTTP/1.1"
    {
        std::ostringstream stream;
        stream.imbue(std::locale::classic());

        // request type
        stream << (m_method == get ? "GET " : "POST ");

        // request_protocol_prefix, request_host
        if(useProxy)
        {
            stream << toProtocolPrefix(serverAddress.m_protocol).toAscii();
            if((serverAddress.m_protocol == ftpTransport)
                && !serverAddress.m_credentials.empty())
            {
                // user:password@
                stream << serverAddress.m_credentials.userName().toAscii()
                    << ":" << serverAddress.m_credentials.password().toAscii() << "@";
            }
            stream << serverAddress.m_hostname.toAscii();
            if(serverAddress.m_protocol == ftpTransport)
            {
                if(serverAddress.m_service != L"21")
                    stream << ":" << serverAddress.m_service.toAscii();
            }
            else
            {
                if(serverAddress.m_service != L"80")
                    stream << ":" << serverAddress.m_service.toAscii();
            }
        }

        Path remotePath = serverAddress.m_path + relativeUrlPath;
        remotePath.correctPathDelimiters();
        stream << remotePath.toAscii() << fileName.toAscii();

        // HTTP version
        stream << " HTTP/1.0";

        addLine(stream.str());
    }


    // 2. "Host: downloads1.kaspersky-labs.com"
    {
        std::ostringstream stream;
        stream.imbue(std::locale::classic());
        stream << "Host: " << serverAddress.m_hostname.toAscii();
        addLine(stream.str());
    }

    if(m_method == get)
    {
        // 3. "Pragma: no-cache" & "Cache-Control: no-cache"
        addLine("Pragma: no-cache");
        addLine("Cache-Control: no-cache");
    }

    // 4. Keep connection
    if(useProxy)
    {
        addLine("Proxy-Connection: keep-alive");
        addLine("Connection: keep-alive");
    }
    else
        addLine("Connection: keep-alive");

    // 5. User-agent
    if(!userAgent.empty())
    {
        std::ostringstream stream;
        stream.imbue(std::locale::classic());
        stream << "User-Agent: " << userAgent;
        addLine(stream.str());
    }

    // 6. Proxy authorization
    if(useProxy && !proxyAuthorizationHeader.empty())
    {
        std::ostringstream stream;
        stream.imbue(std::locale::classic());
        stream << "Proxy-Authorization: " << proxyAuthorizationHeader;
        addLine(stream.str());
    }

    // 7. Regetting range
    if(regettingPosition)
    {
        std::ostringstream stream;
        stream.imbue(std::locale::classic());
        stream << "Range: bytes=" << regettingPosition << "-";
        addLine(stream.str());
    }

    if(m_method == post)
    {
        // 8. Content Length
        std::ostringstream stream;
        stream.imbue(std::locale::classic());
        stream << "Content-Length: " << postData.size();
        addLine(stream.str());

        // 9. post data
        m_requestBuffer.insert(m_requestBuffer.end(), postData.begin(), postData.end());
    }
    return m_requestBuffer;
}
コード例 #20
0
ファイル: SailfishUtils.hpp プロジェクト: WanyanW/salmon
TranscriptGeneMap transcriptToGeneMapFromFeatures( std::vector<GenomicFeature<T>> &feats ) {
    using std::unordered_set;
    using std::unordered_map;
    using std::vector;
    using std::tuple;
    using std::string;
    using std::get;

    using NameID = tuple<string, size_t>;

    IndexVector t2g;
    NameVector transcriptNames;
    NameVector geneNames;

    // holds the mapping from transcript ID to gene ID
    IndexVector t2gUnordered;
    // holds the set of gene IDs
    unordered_map<string, size_t> geneNameToID;

    // To read the input and assign ids
    size_t geneCounter = 0;
    string transcript;
    string gene;

    std::sort( feats.begin(), feats.end(),
    []( const GenomicFeature<T> & a, const GenomicFeature<T> & b) -> bool {
        return a.sattr.transcript_id < b.sattr.transcript_id;
    } );

    std::string currentTranscript = "";
    for ( auto & feat : feats ) {

        auto &gene = feat.sattr.gene_id;
        auto &transcript = feat.sattr.transcript_id;

        if ( transcript != currentTranscript ) {
            auto geneIt = geneNameToID.find(gene);
            size_t geneID = 0;

            if ( geneIt == geneNameToID.end() ) {
                // If we haven't seen this gene yet, give it a new ID
                geneNameToID[gene] = geneCounter;
                geneID = geneCounter;
                geneNames.push_back(gene);
                ++geneCounter;
            } else {
                // Otherwise lookup the ID
                geneID = geneIt->second;
            }

            transcriptNames.push_back(transcript);
            t2g.push_back(geneID);

            //++transcriptID;
            currentTranscript = transcript;
        }

    }

    return TranscriptGeneMap(transcriptNames, geneNames, t2g);
}
コード例 #21
0
ファイル: sort_desc.hpp プロジェクト: javaosos/stan
 inline
 std::vector< fvar<T> >
 sort_desc(std::vector< fvar<T> > xs) {
   std::sort(xs.begin(), xs.end(), std::greater< fvar<T> >());      
   return xs;      
 }
コード例 #22
0
ファイル: RegionFilter.cpp プロジェクト: bbferka/robosherlock
  TyErrorId processWithLock(CAS &tcas, ResultSpecification const &res_spec)
  {
    MEASURE_TIME;
    outInfo("process begins");
    rs::SceneCas cas(tcas);
    rs::Scene scene = cas.getScene();

    cas.get(VIEW_CLOUD, *cloud);
    cas.get(VIEW_COLOR_IMAGE, color);
    cas.get(VIEW_DEPTH_IMAGE, depth);
    cas.get(VIEW_CAMERA_INFO, cameraInfo);

    indices->clear();
    indices->reserve(cloud->points.size());

    camToWorld.setIdentity();
    if(scene.viewPoint.has())
    {
      rs::conversion::from(scene.viewPoint.get(), camToWorld);
    }
    else
    {
      outWarn("No camera to world transformation, no further processing!");
      throw rs::FrameFilterException();
    }
    worldToCam = tf::StampedTransform(camToWorld.inverse(), camToWorld.stamp_, camToWorld.child_frame_id_, camToWorld.frame_id_);
    computeFrustum();

    //default place to look for objects is counter tops except if we got queried for some different place
    //message comes from desigantor and is not the same as the entries from the semantic map so we need
    //to transform them
    rs::Query qs = rs::create<rs::Query>(tcas);
    std::vector<std::string> regionsToLookAt;
    regionsToLookAt.assign(defaultRegions.begin(),defaultRegions.end());
    regions.clear();
    if(cas.getFS("QUERY", qs))
    {
      outWarn("loaction set in query: " << qs.location());
      if(std::find(defaultRegions.begin(), defaultRegions.end(), qs.location()) == std::end(defaultRegions) && qs.location()!="")
      {
        regionsToLookAt.clear();
        regionsToLookAt.push_back(qs.location());
      }
    }

    if(regions.empty())
    {
      std::vector<rs::SemanticMapObject> semanticRegions;
      getSemanticMapEntries(cas, regionsToLookAt, semanticRegions);

      regions.resize(semanticRegions.size());
      for(size_t i = 0; i < semanticRegions.size(); ++i)
      {

        Region &region = regions[i];
        region.width = semanticRegions[i].width();
        region.depth = semanticRegions[i].depth();
        region.height = semanticRegions[i].height();
        region.name = semanticRegions[i].name();
        rs::conversion::from(semanticRegions[i].transform(), region.transform);
      }
    }

    for(size_t i = 0; i < regions.size(); ++i)
    {
      if(frustumCulling(regions[i]) || !frustumCulling_)
      {
        outInfo("region inside frustum: " << regions[i].name);
        filterRegion(regions[i]);
      }
      else
      {
        outInfo("region outside frustum: " << regions[i].name);
      }
    }

    pcl::ExtractIndices<PointT> ei;
    ei.setKeepOrganized(true);
    ei.setIndices(indices);
    ei.filterDirectly(cloud);

    cas.set(VIEW_CLOUD, *cloud);

    if(changeDetection && !indices->empty())
    {
      ++frames;
      if(lastImg.empty())
      {
        lastMask = cv::Mat::ones(color.rows, color.cols, CV_8U);
        lastImg = cv::Mat::zeros(color.rows, color.cols, CV_32FC4);
      }

      uint32_t secondsPassed = camToWorld.stamp_.sec - lastTime.sec;
      bool change = checkChange() || cas.has("QUERY") || secondsPassed > timeout;

      if(!change)
      {
        ++filtered;
      }
      else
      {
        lastTime = camToWorld.stamp_;
      }
      outInfo("filtered frames: " << filtered << " / " << frames << "(" << (filtered / (float)frames) * 100 << "%)");

      if(!change)
      {
        outWarn("no changes in frame detected, no further processing!");
        throw rs::FrameFilterException();
      }
    }

    return UIMA_ERR_NONE;
  }
コード例 #23
0
 // Performs the rellocation itself
 void ApplyPatches(void* ptr)
 {
     for(auto it = ptrs.begin(); it != ptrs.end(); ++it)
         injector::WriteMemory(it->first, (uintptr_t)(ptr) + it->second, true);
 }
コード例 #24
0
ファイル: inversions.cpp プロジェクト: alien43/misc
size_t findNumberOfInversions(std::vector<int> vector)
{
    return countInversions(vector.begin(), vector.end());
}
コード例 #25
0
ファイル: tutorial08.cpp プロジェクト: yofreke/CS452-PROJECT2
int main( void )
{
	// Initialise GLFW
	if( !glfwInit() )
	{
		fprintf( stderr, "Failed to initialize GLFW\n" );
		return -1;
	}

	glfwWindowHint(GLFW_SAMPLES, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);


	// Open a window and create its OpenGL context
	window = glfwCreateWindow( 1024, 768, "Tutorial 08 - Basic Shading", NULL, NULL);
	if( window == NULL ){
		fprintf( stderr, "Failed to open GLFW window.\n" );
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);

	// Initialize GLEW
	if (glewInit() != GLEW_OK) {
		fprintf(stderr, "Failed to initialize GLEW\n");
		return -1;
	}

	// Ensure we can capture the escape key being pressed below
	glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
	glfwSetCursorPos(window, 1024/2, 768/2);

	// Dark blue background
	glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

	// Enable depth test
	glEnable(GL_DEPTH_TEST);
	// Accept fragment if it closer to the camera than the former one
	glDepthFunc(GL_LESS); 

	// Cull triangles which normal is not towards the camera
	glDisable(GL_CULL_FACE);

	// Create and compile our GLSL program from the shaders
	GLuint programID = LoadShaders( "StandardShading.vertexshader", "StandardShading.fragmentshader" );

	// Get a handle for our "MVP" uniform
	GLuint MatrixID = glGetUniformLocation(programID, "MVP");
	GLuint ViewMatrixID = glGetUniformLocation(programID, "V");
	GLuint ModelMatrixID = glGetUniformLocation(programID, "M");

	// Get a handle for our buffers
	GLuint vertexPosition_modelspaceID = glGetAttribLocation(programID, "vertexPosition_modelspace");
	GLuint vertexUVID = glGetAttribLocation(programID, "vertexUV");
	GLuint vertexNormal_modelspaceID = glGetAttribLocation(programID, "vertexNormal_modelspace");

	// Load the texture
	// GLuint Texture = loadDDS("uvmap.DDS");
	GLuint Texture = loadBMP_custom("floor.bmp");
	
	// Get a handle for our "myTextureSampler" uniform
	GLuint TextureID  = glGetUniformLocation(programID, "myTextureSampler");

	// Read our .obj file
	bool res = loadOBJ("cube_floor.obj", cube_vertices, cube_uvs, cube_normals);

	// Load it into a VBO
	resetMap();

	// Get a handle for our "LightPosition" uniform
	glUseProgram(programID);
	GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace");
	// GLuint LightID2 = glGetUniformLocation(programID, "LightPosition2_worldspace");

	loadChest();


	float rotX = 0.f;

	do{

		// Clear the screen
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Use our shader
		glUseProgram(programID);

		// Compute the MVP matrix from keyboard and mouse input
		computeMatricesFromInputs(mapArray, mapSize);

		// Check for treasure!
		int foundChestId = findChest(spawnedChests, getCamPos());
		if(foundChestId >= 0){
			// printf("FOUND CHEST ID %d\n", foundChestId);
			spawnedChests.erase(spawnedChests.begin() + foundChestId);
			if(spawnedChests.size() > 0)
				printf("You have scored!  Only %d more chests to find!\n", (int) spawnedChests.size());
			else {
				mapSize += 2;
				printf("You have cleared this phase, new map size of %dx%d!!!\n", mapSize, mapSize);
				resetMap();
			}
		}

		glm::mat4 ProjectionMatrix = getProjectionMatrix();
		// glm::mat4 ProjectionMatrix = glm::mat4(1);
		// glm::mat4 ViewMatrix = glm::lookAt(
		// 						glm::vec3(0),           // Camera is here
		// 						chestPos, // and looks here : at the same position, plus "direction"
		// 						glm::vec3(0,1,0)                  // Head is up (set to 0,-1,0 to look upside-down)
		// 				   );
		glm::mat4 ViewMatrix = getViewMatrix();
		glm::mat4 ModelMatrix = glm::mat4(1);

		double xpos, ypos;
		glfwGetCursorPos(window, &xpos, &ypos);

		glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;

		// Send our transformation to the currently bound shader, 
		// in the "MVP" uniform
		glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
		glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
		glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);

		// glm::vec3 lightPos = glm::vec3(-15,-10,0);
		glm::vec3 lightPos = getCamPos();
		glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);

		// glm::vec3 lightPos2 = glm::vec3(0,0,10);
		// glUniform3f(LightID2, lightPos2.x, lightPos2.y, lightPos2.z);

		// Bind our texture in Texture Unit 0
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, Texture);
		// Set our "myTextureSampler" sampler to user Texture Unit 0
		glUniform1i(TextureID, 0);

		// 1rst attribute buffer : vertices
		glEnableVertexAttribArray(vertexPosition_modelspaceID);
		glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
		glVertexAttribPointer(
			vertexPosition_modelspaceID,  // The attribute we want to configure
			3,                            // size
			GL_FLOAT,                     // type
			GL_FALSE,                     // normalized?
			0,                            // stride
			(void*)0                      // array buffer offset
		);

		// 2nd attribute buffer : UVs
		glEnableVertexAttribArray(vertexUVID);
		glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
		glVertexAttribPointer(
			vertexUVID,                   // The attribute we want to configure
			2,                            // size : U+V => 2
			GL_FLOAT,                     // type
			GL_FALSE,                     // normalized?
			0,                            // stride
			(void*)0                      // array buffer offset
		);

		// 3rd attribute buffer : normals
		glEnableVertexAttribArray(vertexNormal_modelspaceID);
		glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
		glVertexAttribPointer(
			vertexNormal_modelspaceID,    // The attribute we want to configure
			3,                            // size
			GL_FLOAT,                     // type
			GL_FALSE,                     // normalized?
			0,                            // stride
			(void*)0                      // array buffer offset
		);

		// Draw the triangles !
		glDrawArrays(GL_TRIANGLES, 0, map_vertices.size() );
		// glDrawArrays(GL_TRIANGLES, 0, ChestNumVerts );

		///////////////////////////////////////////////
		for (std::vector<SpawnedChest>::iterator i = spawnedChests.begin(); i != spawnedChests.end(); ++i)
		{

			ModelMatrix = getChestMatrix(&(*i).rotation, (*i).position);
			MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;

			// Send our transformation to the currently bound shader, 
			// in the "MVP" uniform
			glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
			glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
			glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);

			renderChest(programID);	
		}
		//////////////////////////////////////////////

		glDisableVertexAttribArray(vertexPosition_modelspaceID);
		glDisableVertexAttribArray(vertexUVID);
		glDisableVertexAttribArray(vertexNormal_modelspaceID);

		// Swap buffers
		glfwSwapBuffers(window);
		glfwPollEvents();

	} // Check if the ESC key was pressed or the window was closed
	while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
		   glfwWindowShouldClose(window) == 0 );

	// Cleanup VBO and shader
	glDeleteBuffers(1, &vertexbuffer);
	glDeleteBuffers(1, &uvbuffer);
	glDeleteBuffers(1, &normalbuffer);
	glDeleteProgram(programID);
	glDeleteTextures(1, &Texture);

	// Close OpenGL window and terminate GLFW
	glfwTerminate();

	return 0;
}
コード例 #26
0
ファイル: head_based_subcluster.hpp プロジェクト: taketwo/pcl
template <typename PointT> void
pcl::people::HeadBasedSubclustering<PointT>::subcluster (std::vector<pcl::people::PersonCluster<PointT> >& clusters)
{
  // Check if all mandatory variables have been set:
  if (std::isnan(sqrt_ground_coeffs_))
  {
    PCL_ERROR ("[pcl::people::pcl::people::HeadBasedSubclustering::subcluster] Floor parameters have not been set or they are not valid!\n");
    return;
  }
  if (cluster_indices_.empty ())
  {
    PCL_ERROR ("[pcl::people::pcl::people::HeadBasedSubclustering::subcluster] Cluster indices have not been set!\n");
    return;
  }
  if (cloud_ == nullptr)
  {
    PCL_ERROR ("[pcl::people::pcl::people::HeadBasedSubclustering::subcluster] Input cloud has not been set!\n");
    return;
  }

  // Person clusters creation from clusters indices:
  for(std::vector<pcl::PointIndices>::const_iterator it = cluster_indices_.begin(); it != cluster_indices_.end(); ++it)
  {
    pcl::people::PersonCluster<PointT> cluster(cloud_, *it, ground_coeffs_, sqrt_ground_coeffs_, head_centroid_, vertical_);  // PersonCluster creation
    clusters.push_back(cluster);
  }

  // Remove clusters with too high height from the ground plane:
  std::vector<pcl::people::PersonCluster<PointT> > new_clusters;
  for(size_t i = 0; i < clusters.size(); i++)   // for every cluster
  {
    if (clusters[i].getHeight() <= max_height_)
      new_clusters.push_back(clusters[i]);
  }
  clusters = new_clusters;
  new_clusters.clear();

  // Merge clusters close in floor coordinates:
  mergeClustersCloseInFloorCoordinates(clusters, new_clusters);
  clusters = new_clusters;

  std::vector<pcl::people::PersonCluster<PointT> > subclusters;
  int cluster_min_points_sub = int(float(min_points_) * 1.5);
  //  int cluster_max_points_sub = max_points_;

  // create HeightMap2D object:
  pcl::people::HeightMap2D<PointT> height_map_obj;
  height_map_obj.setGround(ground_coeffs_);
  height_map_obj.setInputCloud(cloud_);
  height_map_obj.setSensorPortraitOrientation(vertical_);
  height_map_obj.setMinimumDistanceBetweenMaxima(heads_minimum_distance_);
  for(typename std::vector<pcl::people::PersonCluster<PointT> >::iterator it = clusters.begin(); it != clusters.end(); ++it)   // for every cluster
  {
    float height = it->getHeight();
    int number_of_points = it->getNumberPoints();
    if(height > min_height_ && height < max_height_)
    {
      if (number_of_points > cluster_min_points_sub) //  && number_of_points < cluster_max_points_sub)
      {
        // Compute height map associated to the current cluster and its local maxima (heads):
        height_map_obj.compute(*it);
        if (height_map_obj.getMaximaNumberAfterFiltering() > 1)        // if more than one maximum
        {
          // create new clusters from the current cluster and put corresponding indices into sub_clusters_indices:
          createSubClusters(*it, height_map_obj.getMaximaNumberAfterFiltering(), height_map_obj.getMaximaCloudIndicesFiltered(), subclusters);
        }
        else
        {  // Only one maximum --> copy original cluster:
          subclusters.push_back(*it);
        }
      }
      else
      {
        // Cluster properties not good for sub-clustering --> copy original cluster:
        subclusters.push_back(*it);
      }
    }
  }
  clusters = subclusters;    // substitute clusters with subclusters
}
コード例 #27
0
ファイル: main.cpp プロジェクト: 00liujj/trilinos
bool CompareMetric::evaluate_with_Hessian( PatchData& pd,
                 size_t handle,
                 double& value,
                 std::vector<size_t>& indices,
                 std::vector<Vector3D>& gradient,
                 std::vector<Matrix3D>& Hessian,
                 MsqError& err )
{
  double m2val;
  bool r1, r2;
  m2Handles.clear();
  m2Grad.clear();
  m2Hess.clear();
  r1 = metric1->evaluate_with_Hessian( pd, handle, value, indices, gradient, Hessian, err ); MSQ_ERRZERO(err);
  r2 = metric2->evaluate_with_Hessian( pd, handle, m2val, m2Handles, m2Grad, m2Hess, err ); MSQ_ERRZERO(err);
  if (r1 != r2 || fabs(value - m2val) > epsilon) {
    MSQ_SETERR(err)(MsqError::INVALID_STATE,
                    "Metrics returned different values for handle %lu in "
                    "evaluate_with_Hessian:\n"
                    "\t%s %f vs. %s %f\n", (unsigned long)handle,
                    r1?"true":"false",value,r2?"true":"false",m2val);
  }
  else {
    std::vector<size_t>::const_iterator i, j;
    std::vector<Vector3D>::const_iterator r, s;
    int grad_diff = 0, hess_diff = 0;
    bool same = (indices.size() == m2Handles.size());
    std::sort( m2Handles.begin(), m2Handles.end() );
    for (i = indices.begin(); i != indices.end(); ++i) {
      j = std::lower_bound( m2Handles.begin(), m2Handles.end(), *i );
      if (j == m2Handles.end() || *j != *i) {
        same = false;
        continue;
      }
      
      r = gradient.begin() + (i - indices.begin());
      s = m2Grad.begin() + (j - m2Handles.begin());
      if (!equal(*r,*s)) {
        ++grad_diff;
          // call again for so debugger can step into it after failure is found
        std::vector<size_t> i2;
        std::vector<Vector3D> g2;
        std::vector<Matrix3D> h2;
        metric2->evaluate_with_Hessian(pd, handle, m2val, i2, g2, h2, err );
      }
    }  
     
    if (!same) {
      MSQ_SETERR(err)(MsqError::INVALID_STATE,
                      "Metrics returned incompatible lists of vertex indices"
                      " for handle %lu in evaluate_with_Hessian\n.", 
                      (unsigned long)handle );
    }
    else if (grad_diff) {
      MSQ_SETERR(err)(MsqError::INVALID_STATE,
                      "Metrics returned different gradient vectors for "
                      " %d of %u vertices for handle %lu in "
                      "evaluate_with_Hessian\n.", 
                      grad_diff, (unsigned)gradient.size(), 
                      (unsigned long)handle );
    }
    else {
      size_t row, col, row2, col2, idx, idx2;
      for (row = idx = 0; row < indices.size(); ++row) {
        row2 = std::lower_bound( m2Handles.begin(), m2Handles.end(), indices[row] ) - m2Handles.begin();
        for (col = row; col < indices.size(); ++col, ++idx) {
          col2 = std::lower_bound( m2Handles.begin(), m2Handles.end(), indices[col] ) - m2Handles.begin();
          if (row2 <= col2) {
            idx2 = indices.size()*row2 - row2*(row2+1)/2 + col2;
            if (!equal(Hessian[idx], m2Hess[idx2]))
              ++hess_diff;
          }
          else {
            idx2 = indices.size()*col2 - col2*(col2+1)/2 + row2;
            if (!equal(Hessian[idx], transpose(m2Hess[idx2])))
              ++hess_diff;
          }
        }
      }

      if (hess_diff) {
        MSQ_SETERR(err)(MsqError::INVALID_STATE,
                        "Metrics returned different Hessian blocks for "
                        " %d of %u vertices for handle %lu in "
                        "evaluate_with_Hessian\n.", 
                        hess_diff, (unsigned)Hessian.size(), 
                        (unsigned long)handle );
      }
    }
  }
  
  return r1 && !err;
}
コード例 #28
0
ファイル: shader.cpp プロジェクト: haltakov/synthetic-dataset
bool SHADER_GLSL::Load(const std::string & vertex_filename, const std::string & fragment_filename, const std::vector <std::string> & preprocessor_defines, std::ostream & info_output, std::ostream & error_output)
{
	assert(GLEW_ARB_shading_language_100);

	Unload();

	string vertexshader_source = UTILS::LoadFileIntoString(vertex_filename, error_output);
	string fragmentshader_source = UTILS::LoadFileIntoString(fragment_filename, error_output);
	assert(!vertexshader_source.empty());
	assert(!fragmentshader_source.empty());

	//prepend #define values
	for (std::vector <std::string>::const_iterator i = preprocessor_defines.begin(); i != preprocessor_defines.end(); ++i)
	{
		vertexshader_source = "#define " + *i + "\n" + vertexshader_source;
		fragmentshader_source = "#define " + *i + "\n" + fragmentshader_source;
	}

	//prepend #version
	vertexshader_source = "#version 120\n" + vertexshader_source;
	fragmentshader_source = "#version 120\n" + fragmentshader_source;

	//create shader objects
	program = glCreateProgramObjectARB();
	vertex_shader = glCreateShaderObjectARB(GL_VERTEX_SHADER);
	fragment_shader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);

	//load shader sources
	GLcharARB * vertshad = new GLcharARB[vertexshader_source.length()+1];
	strcpy(vertshad, vertexshader_source.c_str());
	const GLcharARB * vertshad2 = vertshad;
	glShaderSource(vertex_shader, 1, &vertshad2, NULL);
	delete [] vertshad;

	GLcharARB * fragshad = new GLcharARB[fragmentshader_source.length()+1];
	strcpy(fragshad, fragmentshader_source.c_str());
	const GLcharARB * fragshad2 = fragshad;
	glShaderSource(fragment_shader, 1, &fragshad2, NULL);
	delete [] fragshad;

	//compile the shaders
	GLint vertex_compiled(0);
	GLint fragment_compiled(0);

	glCompileShader(vertex_shader);
	PrintShaderLog(vertex_shader, vertex_filename, info_output);
	glCompileShader(fragment_shader);
	PrintShaderLog(fragment_shader, fragment_filename, info_output);

	glGetObjectParameterivARB(vertex_shader, GL_OBJECT_COMPILE_STATUS_ARB, &vertex_compiled);
	glGetObjectParameterivARB(fragment_shader, GL_OBJECT_COMPILE_STATUS_ARB, &fragment_compiled);

	//attach shader objects to the program object
	glAttachObjectARB(program, vertex_shader);
	glAttachObjectARB(program, fragment_shader);

	//link the program
	glLinkProgram(program);
	GLint program_linked(0);
	glGetProgramiv(program, GL_LINK_STATUS, &program_linked);

	const bool success = (vertex_compiled && fragment_compiled && program_linked);

	//spit out any error info
	PrintProgramLog(program, vertex_filename + " and " + fragment_filename, info_output);

	if (!success)
	{
		error_output << "Shader compilation failure: " + vertex_filename + " and " + fragment_filename << endl << endl;
		error_output << "Vertex shader:" << endl;
		PrintWithLineNumbers(error_output, vertexshader_source);
		error_output << endl;
		error_output << "Fragment shader:" << endl;
		PrintWithLineNumbers(error_output, fragmentshader_source);
		error_output << endl;
	}
	else
	{
		//need to enable to be able to set passed variable info
		glUseProgramObjectARB(program);

		//set passed variable information for tus
		for (int i = 0; i < 16; i++)
		{
			stringstream tustring;
			tustring << "tu" << i;
			int tu_loc;
			tu_loc = glGetUniformLocation(program, (tustring.str()+"_2D").c_str());
			if (tu_loc >= 0) glUniform1i(tu_loc, i);

			tu_loc = glGetUniformLocation(program, (tustring.str()+"_2DRect").c_str());
			if (tu_loc >= 0) glUniform1i(tu_loc, i);

			tu_loc = glGetUniformLocation(program, (tustring.str()+"_cube").c_str());
			if (tu_loc >= 0)
			{
				glUniform1i(tu_loc, i);
			}
		}
	}

	loaded = success;

	return success;
}
コード例 #29
0
ファイル: molecule.cpp プロジェクト: andremirt/v_cond
/** @see molecule.h */
void Molecule_delete(int molecule) {
    molecules.erase(molecules.begin() + molecule - OFFSET);
}
コード例 #30
-16
ファイル: vector.hpp プロジェクト: Albermg7/boost
inline void save(
    Archive & ar,
    const STD::vector<bool, Allocator> &t,
    const unsigned int /* file_version */
){
    // record number of elements
    unsigned int count = t.size();
    ar << BOOST_SERIALIZATION_NVP(count);
    STD::vector<bool>::const_iterator it = t.begin();
    while(count-- > 0){
        bool tb = *it++;
        ar << boost::serialization::make_nvp("item", tb);
    }
}