bool startObject()
	{
		m_items.emplace_back(Item::StartObject);
		return true;
	}
Beispiel #2
0
void sounds::add_footstep( const tripoint &p, int volume, int, monster * )
{
    sounds_since_last_turn.emplace_back(
        std::make_pair( p, sound_event {volume, "", false, true, "", ""} ) );
}
Beispiel #3
0
void TextToViewSettings(const string& ColumnTitles,const string& ColumnWidths, std::vector<column>& Columns)
{
	// BUGBUG, add error checking

	const wchar_t *TextPtr=ColumnTitles.data();

	Columns.clear();

	for (;;)
	{
		string strArgName;

		if (!(TextPtr=GetCommaWord(TextPtr,strArgName)))
			break;

		Columns.emplace_back(VALUE_TYPE(Columns)());

		string strArgOrig = strArgName;
		ToUpper(strArgName);

		if (strArgName.front() == L'N')
		{
			unsigned __int64 &ColumnType = Columns.back().type;
			ColumnType = NAME_COLUMN;
			const wchar_t *Ptr = strArgName.data() + 1;

			while (*Ptr)
			{
				switch (*Ptr)
				{
				case L'M':
					ColumnType |= COLUMN_MARK;
					break;
				case L'O':
					ColumnType |= COLUMN_NAMEONLY;
					break;
				case L'R':
					ColumnType |= COLUMN_RIGHTALIGN;
					break;
				case L'F':
					ColumnType |= COLUMN_RIGHTALIGNFORCE;
					break;
				case L'N':
					ColumnType |= COLUMN_NOEXTENSION;
					break;
				}

				Ptr++;
			}
		}
		else if (strArgName.front() == L'S' || strArgName.front() == L'P' || strArgName.front() == L'G')
		{
			unsigned __int64 &ColumnType = Columns.back().type;
			ColumnType = (strArgName.front() == L'S') ? SIZE_COLUMN : (strArgName.front() == L'P') ? PACKED_COLUMN : STREAMSSIZE_COLUMN;
			const wchar_t *Ptr = strArgName.data() + 1;

			while (*Ptr)
			{
				switch (*Ptr)
				{
				case L'C':
					ColumnType |= COLUMN_COMMAS;
					break;
				case L'E':
					ColumnType |= COLUMN_ECONOMIC;
					break;
				case L'F':
					ColumnType |= COLUMN_FLOATSIZE;
					break;
				case L'T':
					ColumnType |= COLUMN_THOUSAND;
					break;
				}

				Ptr++;
			}
		}
		else if (!StrCmpN(strArgName.data(), L"DM", 2) || !StrCmpN(strArgName.data(), L"DC", 2) || !StrCmpN(strArgName.data(), L"DA", 2) || !StrCmpN(strArgName.data(), L"DE", 2))
		{
			unsigned __int64 &ColumnType = Columns.back().type;

			switch (strArgName[1])
			{
			case L'M':
				ColumnType = WDATE_COLUMN;
				break;
			case L'C':
				ColumnType = CDATE_COLUMN;
				break;
			case L'A':
				ColumnType = ADATE_COLUMN;
				break;
			case L'E':
				ColumnType = CHDATE_COLUMN;
				break;
			}

			const wchar_t *Ptr = strArgName.data() + 2;

			while (*Ptr)
			{
				switch (*Ptr)
				{
				case L'B':
					ColumnType |= COLUMN_BRIEF;
					break;
				case L'M':
					ColumnType |= COLUMN_MONTH;
					break;
				}

				Ptr++;
			}
		}
		else if (strArgName.front() == L'O')
		{
			unsigned __int64 &ColumnType = Columns.back().type;
			ColumnType = OWNER_COLUMN;

			if (strArgName.size() > 1 && strArgName[1] == L'L')
				ColumnType |= COLUMN_FULLOWNER;
		}
		else if (strArgName.front() == L'X')
		{
			unsigned __int64 &ColumnType = Columns.back().type;
			ColumnType = EXTENSION_COLUMN;

			if (strArgName.size() > 1 && strArgName[1] == L'R')
				ColumnType |= COLUMN_RIGHTALIGN;
		}
		else if (strArgOrig.size() > 2 && strArgOrig.front() == L'<' && strArgOrig.back() == L'>')
		{
			Columns.back().title = strArgOrig.substr(1, strArgOrig.size() - 2);
			Columns.back().type = CUSTOM_COLUMN0;
		}
		else
		{
			auto ItemIterator = std::find_if(CONST_RANGE(ColumnInfo, i) { return strArgName == i.Symbol; });
			if (ItemIterator != std::cend(ColumnInfo))
				Columns.back().type = ItemIterator->Type;
		}
	}
Beispiel #4
0
	WorkerThreads(size_t threadCount=1) : shouldStop(false)
	{
		threads.reserve(threadCount);
		for (size_t i=0; i<threadCount; i++)
			threads.emplace_back(std::thread(&WorkerThreads::runWorker, this));
	}
Beispiel #5
0
	void create_audio_frame() override
	{
		frames.emplace_back(new AudioFrame(*this, "Untitled Audio", wxPoint(50, 50), wxSize(450, 340)));
		frames.back()->Show(true);
	}
 void append(size_t size) {
     v_.emplace_back();
     v_.back().resize(size, false);
 }
Beispiel #7
0
 void Assign(std::future<void>&& future)
 {
   std::lock_guard<std::mutex> lock(mutex);
   futures.emplace_back(std::move(future));
   EraseReady();
 }
	bool boolean(const bool val)
	{
		m_items.emplace_back(val);
		return true;
	}
	bool integerNumber(const int64_t val)
	{
		m_items.emplace_back(val);
		return true;
	}
	bool endArray(const std::size_t size)
	{
		m_items.emplace_back(Item::EndArray, size);
		return true;
	}
	bool null()
	{
		m_items.emplace_back(Item::Null);
		return true;
	}
	bool startArray()
	{
		m_items.emplace_back(Item::StartArray);
		return true;
	}
	bool endObject(const std::size_t size)
	{
		m_items.emplace_back(Item::EndObject, size);
		return true;
	}
	bool key(const std::string &str)
	{
		m_items.emplace_back(Item::Key, str);
		return true;
	}
 inline void emplace(TArgs&&... mArgs)
 {
     particles.emplace_back(FWD(mArgs)...);
 }
	bool doubleNumber(const double val)
	{
		m_items.emplace_back(val);
		return true;
	}
void IfcElectricMotor::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
	IfcEnergyConversionDevice::getAttributes( vec_attributes );
	vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) );
}
	bool string(const std::string &str)
	{
		m_items.emplace_back(Item::String, str);
		return true;
	}
void Tracker::Visit(int node) {
    visited_nodes_.insert(node);
    walk.emplace_back(node);
}
Beispiel #20
0
		void addLightSource   (const sf::Vector2f & position, const oak::Tweener & tweener, const sf::Color & color = sf::Color::White, sf::Uint8 minAlpha = sf::Uint8(0))
		{
			lights.emplace_back(position, tweener, color, minAlpha);
		}
Beispiel #21
0
 void Push(const std::string& name, std::string&& arg)
 {
   args.emplace_back(arg);
   names.emplace_back(name);
 }
void IfcCableSegment::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
	IfcFlowSegment::getAttributes( vec_attributes );
	vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) );
}
Beispiel #23
0
void RequestWorkloadStats::enter(State to) {
  if (m_s.empty()) return;
  transition(m_s.back(), to);
  m_s.emplace_back(to);
  m_transitionCounts[to]++;
}
void EidosTypeInterpreter::_ProcessArgumentListTypes(const EidosASTNode *p_node, const EidosCallSignature *p_call_signature, std::vector<EidosASTNode *> &p_arguments)
{
	const std::vector<EidosASTNode *> &node_children = p_node->children_;
	
	// Run through the argument nodes, evaluate them, and put the resulting pointers into the arguments buffer,
	// interleaving default arguments and handling named arguments as we go.
	auto node_children_end = node_children.end();
	int sig_arg_index = 0;
	int sig_arg_count = (int)p_call_signature->arg_name_IDs_.size();
	//bool had_named_argument = false;
	
	for (auto child_iter = node_children.begin() + 1; child_iter != node_children_end; ++child_iter)
	{
		EidosASTNode *child = *child_iter;
		
		if (sig_arg_index < sig_arg_count)
		{
			if (child->token_->token_type_ != EidosTokenType::kTokenAssign)
			{
				// We have a non-named argument; it will go into the next argument slot from the signature
				// In EidosInterpreter it is an error if had_named_argument is set here; here, we ignore that
				
				// If this argument is the very last thing in the script string, then the user is trying to complete on it;
				// in that case, we add potential matches to the completion list, providing autocompletion of argument names.
				// We may be completing off an identifier (with partial typing), or off a bad token (with no typing).
				// That token should be at or after the script end (if it is a bad token it may be immediately after, since
				// it may have gotten its position from an EOF at the end of the token stream).
				// BCH 6 April 2019: We may also be completing off of what appears to be a language keyword, such as "for"
				// trying to complete to "format=".  We want to treat language keywords like identifiers here,
				if (argument_completions_ && (script_length_ <= (size_t)child->token_->token_end_ + 1))
				{
					if ((child->token_->token_type_ == EidosTokenType::kTokenIdentifier) || (child->token_->token_type_ == EidosTokenType::kTokenBad) || (child->token_->token_type_ >= EidosTokenType::kFirstIdentifierLikeToken))
					{
						// Check each argument in the signature as a possibility for completion
						for (int sig_arg_match_index = sig_arg_index; sig_arg_match_index < sig_arg_count; ++sig_arg_match_index)
						{
							EidosGlobalStringID arg_name_ID = p_call_signature->arg_name_IDs_[sig_arg_match_index];
							const std::string &arg_name = Eidos_StringForGlobalStringID(arg_name_ID);
							
							// To be a completion match, the name must not be private API ('_' prefix)
							// Whether it is an acceptable completion in other respects will be checked by the completion engine
							if (arg_name[0] != '_')
								argument_completions_->push_back(arg_name);
							
							// If the argument we just examined is non-optional, we don't want to offer any further suggestions
							// since they would not be legal to supply in this position in the function/method call.
							if (!(p_call_signature->arg_masks_[sig_arg_match_index] & kEidosValueMaskOptional))
								break;
						}
					}
				}
				
				// Advance to the next argument slot
				sig_arg_index++;
			}
			else
			{
				// We have a named argument; get information on it from its children
				const std::vector<EidosASTNode *> &child_children = child->children_;
				
				if (child_children.size() == 2)	// other than 2 should never happen; raises in EidosInterpreter
				{
					EidosASTNode *named_arg_name_node = child_children[0];
					EidosASTNode *named_arg_value_node = child_children[1];
					
					// Get the identifier for the argument name
					EidosGlobalStringID named_arg_nameID = named_arg_name_node->cached_stringID_;
					
					// Now re-point child at the value node
					child = named_arg_value_node;
					
					// While this argument's name doesn't match the expected argument, insert default values for optional arguments
					do 
					{
						EidosGlobalStringID arg_name_ID = p_call_signature->arg_name_IDs_[sig_arg_index];
						
						if (named_arg_nameID == arg_name_ID)
						{
							sig_arg_index++;
							break;
						}
						
						// In EidosInterpreter it is an error if a named argument skips over a required argument; here we ignore that
						// In EidosInterpreter it is an error if an optional argument has no default; here we ignore that
						
						// arguments that receive the default value are represented in the argument list here with nullptr, since we have no node for them
						p_arguments.emplace_back(nullptr);
						
						// Move to the next signature argument
						sig_arg_index++;
						if (sig_arg_index == sig_arg_count)
							break;		// this is an error in EidosInterpreter; here we just break out to add the named argument after all the signature args
					}
					while (true);
					
					//had_named_argument = true;
				}
			}
		}
		else
		{
			// We're beyond the end of the signature's arguments; in EidosInterpreter this is complicated because of ellipsis args, here we just let it go
		}
		
		// The child pointer is an argument node, so remember it
		p_arguments.emplace_back(child);
	}
	
	// Handle any remaining arguments in the signature
	while (sig_arg_index < sig_arg_count)
	{
		// In EidosInterpreter it is an error if a non-optional argument remains unmatched; here we ignore that
		// In EidosInterpreter it is an error if an optional argument has no default; here we ignore that
		
		// arguments that receive the default value are represented in the argument list here with nullptr, since we have no node for them
		p_arguments.emplace_back(nullptr);
		
		sig_arg_index++;
	}
}
Beispiel #25
0
int LoadTextures()
{

	int error_count = 0;

	GLint topology_uniform = gTexCubeShader->GetUniformLocation("topology_sampler");
	const char* topology_filename = "gray50.tga";
	if(topology_uniform >= 0)
	{
		gTextures.emplace_back(new akj::cGLTexture("topology texture"));
		gTextures.back()->CreateTexture2D(topology_filename, false/*is_srgb*/, -1);
		gTexCubeShader->Use();
		glUniform1i(topology_uniform, gTextures.back()->GetBoundTextureUnit());
		error_count += akj::glCheckAllErrors(__FILE__, __LINE__);
	}

	GLint diffuse_uniform = gTexCubeShader->GetUniformLocation("diffuse_sampler");
	const char* diffuse_filename = "coldcolors.tga";
	if(diffuse_uniform >= 0)
	{
		gTextures.emplace_back(new akj::cGLTexture("diffuse color texture"));
		gTextures.back()->CreateTexture2D(diffuse_filename, true/*is_srgb*/, -1);
		gTexCubeShader->Use();
		glUniform1i(diffuse_uniform, gTextures.back()->GetBoundTextureUnit());
		error_count += akj::glCheckAllErrors(__FILE__, __LINE__);
	}
	
	GLint light_params_uniform = gTexCubeShader->GetUniformLocation("light_params_sampler");
	const char* light_params_filename = "gray50.tga";
	if(light_params_uniform >= 0)
	{
		gTextures.emplace_back(new akj::cGLTexture("light mapping texture"));
		gTextures.back()->CreateTexture2D(light_params_filename, false/*is_srgb*/, -1);
		gTexCubeShader->Use();
		glUniform1i(light_params_uniform, gTextures.back()->GetBoundTextureUnit());
		error_count += akj::glCheckAllErrors(__FILE__, __LINE__);
	}

	GLint texcube_refl_cube_uniform = gTexCubeShader->GetUniformLocation("detailed_cubemap");
	GLint background_refl_cube_uniform = gBackgroundShader->GetUniformLocation("my_enviro_map");

	const char* detailed_cube_filename = "cube_map.jpg";
	if(texcube_refl_cube_uniform >= 0 || background_refl_cube_uniform >= 0)
	{
		gTextures.emplace_back(new akj::cGLTexture("detailed cube texture"));
		gTextures.back()->CreateCubeMap(detailed_cube_filename, true /*is_srgb*/);
		gTexCubeShader->Use();
		glUniform1i(texcube_refl_cube_uniform, gTextures.back()->GetBoundTextureUnit());
		gBackgroundShader->Use();
		glUniform1i(background_refl_cube_uniform, gTextures.back()->GetBoundTextureUnit());
		error_count += akj::glCheckAllErrors(__FILE__, __LINE__);
	}

	GLint diffuse_cube_uniform = gTexCubeShader->GetUniformLocation("diffuse_cubemap");
	const char* diffuse_cube_filename = "diffuse_map.jpg";
	if(diffuse_cube_uniform >= 0)
	{
		gTextures.emplace_back(new akj::cGLTexture("diffuse cube texture"));
		//want the ambient light to be lighter, hence no srgb
		gTextures.back()->CreateCubeMap(diffuse_cube_filename, false/*is_srgb*/);
		gTexCubeShader->Use();
		glUniform1i(diffuse_cube_uniform, gTextures.back()->GetBoundTextureUnit());
		error_count += akj::glCheckAllErrors(__FILE__, __LINE__);
	}
	
	return error_count;
}
Beispiel #26
0
bool
GenTestDocsApp::getOptions()
{
    int c;
    const char *optArgument = NULL;
    int longopt_index = 0;
    static struct option longopts[] = {
        { "basedir", 1, NULL, 0 },
        { "consttextfield", 1, NULL, 0 },
        { "prefixtextfield", 1, NULL, 0 },
        { "randtextfield", 1, NULL, 0 },
        { "modtextfield", 1, NULL, 0 },
        { "idtextfield", 1, NULL, 0 },
        { "randintfield", 1, NULL, 0 },
        { "docidlimit", 1, NULL, 0 },
        { "mindocid", 1, NULL, 0 },
        { "numwords", 1, NULL, 0 },
        { "doctype", 1, NULL, 0 },
        { "headers", 0, NULL, 0 }, 
        { "json", 0, NULL, 0 },
        { NULL, 0, NULL, 0 }
    };
    enum longopts_enum {
        LONGOPT_BASEDIR,
        LONGOPT_CONSTTEXTFIELD,
        LONGOPT_PREFIXTEXTFIELD,
        LONGOPT_RANDTEXTFIELD,
        LONGOPT_MODTEXTFIELD,
        LONGOPT_IDTEXTFIELD,
        LONGOPT_RANDINTFIELD,
        LONGOPT_DOCIDLIMIT,
        LONGOPT_MINDOCID,
        LONGOPT_NUMWORDS,
        LONGOPT_DOCTYPE,
        LONGOPT_HEADERS,
        LONGOPT_JSON
    };
    int optIndex = 2;
    while ((c = _app.GetOptLong("v",
                                optArgument,
                                optIndex,
                                longopts,
                                &longopt_index)) != -1) {
        FieldGenerator::SP g;
        switch (c) {
        case 0:
            switch (longopt_index) {
            case LONGOPT_BASEDIR:
                _baseDir = optArgument;
                break;
            case LONGOPT_CONSTTEXTFIELD:
                _fields.emplace_back(std::make_shared<ConstTextFieldGenerator>(splitArg(optArgument)));
                break;
            case LONGOPT_PREFIXTEXTFIELD:
                _fields.emplace_back(std::make_shared<PrefixTextFieldGenerator>(splitArg(optArgument)));
                break;
            case LONGOPT_RANDTEXTFIELD:
                g.reset(new RandTextFieldGenerator(optArgument,
                                                   _rnd,
                                                   _numWords,
                                                   20,
                                                   50));
                _fields.push_back(g);
                break;
            case LONGOPT_MODTEXTFIELD:
                g.reset(new ModTextFieldGenerator(optArgument,
                                                  _rnd,
                                                  _mods));
                _fields.push_back(g);
                break;
            case LONGOPT_IDTEXTFIELD:
                g.reset(new IdTextFieldGenerator(optArgument));
                _fields.push_back(g);
                break;
            case LONGOPT_RANDINTFIELD:
                g.reset(new RandIntFieldGenerator(optArgument,
                                                  _rnd,
                                                  0,
                                                  100000));
                _fields.push_back(g);
                break;
            case LONGOPT_DOCIDLIMIT:
                _docIdLimit = atoi(optArgument);
                break;
            case LONGOPT_MINDOCID:
                _minDocId = atoi(optArgument);
                break;
            case LONGOPT_NUMWORDS:
                _numWords = atoi(optArgument);
                break;
            case LONGOPT_DOCTYPE:
                _docType = optArgument;
                break;
            case LONGOPT_HEADERS:
                _headers = true;
                break;
            case LONGOPT_JSON:
                _json = true;
                break;
            default:
                if (optArgument != NULL) {
                    LOG(error,
                        "longopt %s with arg %s",
                        longopts[longopt_index].name, optArgument);
                } else {
                    LOG(error,
                        "longopt %s",
                        longopts[longopt_index].name);
                }
            }
            break;
        case 'v':
            _verbose = true;
            break;
        default:
            return false;
        }
    }
    _optIndex = optIndex;
    if (_optIndex >= _app._argc) {
        return false;
    }
    _outFile = _app._argv[optIndex];
    return true;
}
/// Recursively traverse the CFG of the function, renaming loads and
/// stores to the allocas which we are promoting.
///
/// IncomingVals indicates what value each Alloca contains on exit from the
/// predecessor block Pred.
void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
                                RenamePassData::ValVector &IncomingVals,
                                RenamePassData::LocationVector &IncomingLocs,
                                std::vector<RenamePassData> &Worklist) {
NextIteration:
  // If we are inserting any phi nodes into this BB, they will already be in the
  // block.
  if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
    // If we have PHI nodes to update, compute the number of edges from Pred to
    // BB.
    if (PhiToAllocaMap.count(APN)) {
      // We want to be able to distinguish between PHI nodes being inserted by
      // this invocation of mem2reg from those phi nodes that already existed in
      // the IR before mem2reg was run.  We determine that APN is being inserted
      // because it is missing incoming edges.  All other PHI nodes being
      // inserted by this pass of mem2reg will have the same number of incoming
      // operands so far.  Remember this count.
      unsigned NewPHINumOperands = APN->getNumOperands();

      unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
      assert(NumEdges && "Must be at least one edge from Pred to BB!");

      // Add entries for all the phis.
      BasicBlock::iterator PNI = BB->begin();
      do {
        unsigned AllocaNo = PhiToAllocaMap[APN];

        // Update the location of the phi node.
        updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
                                       APN->getNumIncomingValues() > 0);

        // Add N incoming values to the PHI node.
        for (unsigned i = 0; i != NumEdges; ++i)
          APN->addIncoming(IncomingVals[AllocaNo], Pred);

        // The currently active variable for this block is now the PHI.
        IncomingVals[AllocaNo] = APN;
        for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[AllocaNo])
          ConvertDebugDeclareToDebugValue(DII, APN, DIB);

        // Get the next phi node.
        ++PNI;
        APN = dyn_cast<PHINode>(PNI);
        if (!APN)
          break;

        // Verify that it is missing entries.  If not, it is not being inserted
        // by this mem2reg invocation so we want to ignore it.
      } while (APN->getNumOperands() == NewPHINumOperands);
    }
  }

  // Don't revisit blocks.
  if (!Visited.insert(BB).second)
    return;

  for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
    Instruction *I = &*II++; // get the instruction, increment iterator

    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
      AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
      if (!Src)
        continue;

      DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
      if (AI == AllocaLookup.end())
        continue;

      Value *V = IncomingVals[AI->second];

      // If the load was marked as nonnull we don't want to lose
      // that information when we erase this Load. So we preserve
      // it with an assume.
      if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
          !isKnownNonZero(V, SQ.DL, 0, AC, LI, &DT))
        addAssumeNonNull(AC, LI);

      // Anything using the load now uses the current value.
      LI->replaceAllUsesWith(V);
      BB->getInstList().erase(LI);
    } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
      // Delete this instruction and mark the name as the current holder of the
      // value
      AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
      if (!Dest)
        continue;

      DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
      if (ai == AllocaLookup.end())
        continue;

      // what value were we writing?
      unsigned AllocaNo = ai->second;
      IncomingVals[AllocaNo] = SI->getOperand(0);

      // Record debuginfo for the store before removing it.
      IncomingLocs[AllocaNo] = SI->getDebugLoc();
      for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[ai->second])
        ConvertDebugDeclareToDebugValue(DII, SI, DIB);
      BB->getInstList().erase(SI);
    }
  }

  // 'Recurse' to our successors.
  succ_iterator I = succ_begin(BB), E = succ_end(BB);
  if (I == E)
    return;

  // Keep track of the successors so we don't visit the same successor twice
  SmallPtrSet<BasicBlock *, 8> VisitedSuccs;

  // Handle the first successor without using the worklist.
  VisitedSuccs.insert(*I);
  Pred = BB;
  BB = *I;
  ++I;

  for (; I != E; ++I)
    if (VisitedSuccs.insert(*I).second)
      Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);

  goto NextIteration;
}
Beispiel #28
0
/** Import one and only one function vector input
 */
void GeneratePeaks::importPeakFromVector(
    std::vector<std::pair<double, API::IFunction_sptr>> &functionmap) {
  API::CompositeFunction_sptr compfunc =
      boost::make_shared<API::CompositeFunction>();

  // Set up and clone peak function
  if (m_useRawParameter) {
    // Input vector of values are for raw parameter name
    size_t numpeakparams = m_peakFunction->nParams();
    if (m_vecPeakParamValues.size() == numpeakparams) {
      for (size_t i = 0; i < numpeakparams; ++i)
        m_peakFunction->setParameter(i, m_vecPeakParamValues[i]);
    } else {
      // Number of input parameter values is not correct. Throw!
      std::stringstream errss;
      errss << "Number of input peak parameters' value ("
            << m_vecPeakParamValues.size() << ") is not correct (should be "
            << numpeakparams << " for peak of type " << m_peakFunction->name()
            << "). ";
      throw std::runtime_error(errss.str());
    }
  } else {
    // Input vector of values are for effective parameter names
    if (m_vecPeakParamValues.size() != 3)
      throw std::runtime_error("Input peak parameters must have 3 numbers for "
                               "effective parameter names.");

    m_peakFunction->setCentre(m_vecPeakParamValues[0]);
    m_peakFunction->setHeight(m_vecPeakParamValues[1]);
    m_peakFunction->setFwhm(m_vecPeakParamValues[2]);
  }
  compfunc->addFunction(m_peakFunction->clone());

  // Set up and clone background function
  if (m_genBackground) {
    size_t numbkgdparams = m_bkgdFunction->nParams();
    if (m_useRawParameter) {
      // Raw background parameters
      if (m_vecBkgdParamValues.size() != numbkgdparams)
        throw std::runtime_error(
            "Number of background parameters' value is not correct. ");
      else {
        for (size_t i = 0; i < numbkgdparams; ++i)
          m_bkgdFunction->setParameter(i, m_vecBkgdParamValues[i]);
      }
    } else {
      // Effective background parameters
      if (m_vecBkgdParamValues.size() < 3 &&
          m_vecBkgdParamValues.size() < numbkgdparams) {
        throw std::runtime_error(
            "There is no enough effective background parameter values.");
      }

      // FIXME - Assume that all background functions define parameter i for A_i
      for (size_t i = 0; i < numbkgdparams; ++i)
        m_bkgdFunction->setParameter(i, m_vecBkgdParamValues[i]);
    }

    compfunc->addFunction(m_bkgdFunction->clone());
  }

  // Set up function map
  functionmap.emplace_back(m_peakFunction->centre(), compfunc);
}
bool
OSLInput::open (const std::string &name, ImageSpec &newspec,
                const ImageSpec &config)
{
    // std::cout << "OSLInput::open \"" << name << "\"\n";
    setup_shadingsys ();

    std::vector<std::pair<string_view,string_view> > args;
    string_view shadername = deconstruct_uri (name, &args);
    if (shadername.empty())
        return false;
    if (! Strutil::ends_with (shadername, ".osl") &&
        ! Strutil::ends_with (shadername, ".oso") &&
        ! Strutil::ends_with (shadername, ".oslgroup") &&
        ! Strutil::ends_with (shadername, ".oslbody"))
        return false;

    m_filename = name;
    m_topspec = ImageSpec (1024, 1024, 4, TypeDesc::FLOAT);

    // std::cout << "  name = " << shadername << " args? " << args.size() << "\n";
    for (size_t i = 0; i < args.size(); ++i) {
        // std::cout << "    " << args[i].first << "  =  " << args[i].second << "\n";
        if (args[i].first == "RES") {
            parse_res (args[i].second, m_topspec.width, m_topspec.height, m_topspec.depth);
        } else if (args[i].first == "TILE" || args[i].first == "TILES") {
            parse_res (args[i].second, m_topspec.tile_width, m_topspec.tile_height,
                       m_topspec.tile_depth);
        } else if (args[i].first == "OUTPUT") {
            m_outputs.emplace_back(args[i].second);
        } else if (args[i].first == "MIP") {
            m_mip = Strutil::from_string<int>(args[i].second);
        } else if (args[i].first.size() && args[i].second.size()) {
            parse_param (args[i].first, args[i].second, m_topspec);
        }
    }
    if (m_outputs.empty()) {
        m_outputs.emplace_back("result");
        m_outputs.emplace_back("alpha");
    }

    m_topspec.full_x = m_topspec.x;
    m_topspec.full_y = m_topspec.y;
    m_topspec.full_z = m_topspec.z;
    m_topspec.full_width = m_topspec.width;
    m_topspec.full_height = m_topspec.height;
    m_topspec.full_depth = m_topspec.depth;

    bool ok = true;
    if (Strutil::ends_with (shadername, ".oslgroup")) { // Serialized group
        // No further processing necessary
        std::string groupspec;
        if (! OIIO::Filesystem::read_text_file (shadername, groupspec)) {
            // If it didn't name a disk file, assume it's the "inline"
            // serialized group.
            groupspec = groupspec.substr (0, groupspec.size()-9);
        }
        // std::cout << "Processing group specification:\n---\n"
        //           << groupspec << "\n---\n";
        OIIO::lock_guard lock (shading_mutex);
        m_group = shadingsys->ShaderGroupBegin ("", "surface", groupspec);
        if (! m_group)
            return false;   // Failed
        shadingsys->ShaderGroupEnd ();
    }
    if (Strutil::ends_with (shadername, ".oso")) { // Compiled shader
        OIIO::lock_guard lock (shading_mutex);
        shadername.remove_suffix (4);
        m_group = shadingsys->ShaderGroupBegin ();
        for (size_t p = 0, np = m_topspec.extra_attribs.size(); p < np; ++p) {
            const ParamValue &pv (m_topspec.extra_attribs[p]);
            shadingsys->Parameter (pv.name(), pv.type(), pv.data(),
                                   pv.interp() == ParamValue::INTERP_CONSTANT);
        }
        if (! shadingsys->Shader ("surface", shadername, "" /*layername*/ )) {
            error ("y %s", errhandler.haserror() ? errhandler.geterror() : std::string("OSL error"));
            ok = false;
        }
        shadingsys->ShaderGroupEnd ();
    }

    if (Strutil::ends_with (shadername, ".osl")) { // shader source
    }
    if (Strutil::ends_with (shadername, ".oslbody")) { // shader source
        OIIO::lock_guard lock (shading_mutex);
        shadername.remove_suffix (8);
        static int exprcount = 0;
        std::string exprname = OIIO::Strutil::format("expr_%d", exprcount++);
        std::string sourcecode =
            "shader " + exprname + " (\n"
            "    float s = u [[ int lockgeom=0 ]],\n"
            "    float t = v [[ int lockgeom=0 ]],\n"
            "    output color result = 0,\n"
            "    output float alpha = 1,\n"
            "  )\n"
            "{\n"
            "    " + std::string(shadername) + "\n"
            "    ;\n"
            "}\n";
        // std::cout << "Expression-based shader text is:\n---\n"
        //           << sourcecode << "---\n";
        std::string err;
        if (! compile_buffer (sourcecode, exprname, err)) {
            error ("%s", err);
            return false;
        }
        m_group = shadingsys->ShaderGroupBegin ();
        for (size_t p = 0, np = m_topspec.extra_attribs.size(); p < np; ++p) {
            const ParamValue &pv (m_topspec.extra_attribs[p]);
            shadingsys->Parameter (pv.name(), pv.type(), pv.data(),
                                   pv.interp() == ParamValue::INTERP_CONSTANT);
        }
        shadingsys->Shader ("surface", exprname, "" /*layername*/) ;
        shadingsys->ShaderGroupEnd ();
    }

    if (!ok || m_group.get() == NULL)
        return false;

    shadingsys->attribute (m_group.get(), "renderer_outputs",
                           TypeDesc(TypeDesc::STRING,m_outputs.size()),
                           &m_outputs[0]);

#if OIIO_PLUGIN_VERSION < 21
    return ok && seek_subimage (0, 0, newspec);
#else
    ok &= seek_subimage (0, 0);
    if (ok)
        newspec = spec();
    else
        close ();
    return ok;
#endif
}
Beispiel #30
0
void stitch::Vec3::equidistantVectors_IcosahedronBased(const size_t minimumNumVectors, std::vector<stitch::Vec3> &vectors, std::vector<size_t> &binIndices)
{
    vectors.clear();
    binIndices.clear();
    stitch::KDTree kdTree;//Keep a tame kd-tree on the side for efficient searching of duplicate vertices to be merged while sub-dividing.
    
    //======================================================
    //Start with icosahedron.
    //Note - For refinement of icosahedron:
    //  Faces_0 = 20, Edges_0 = 30, Vertices_0 = 12
    //  Faces_n = Faces_(n-1) * 4
    //  Edges_n = Edges_(n-1) * 2 + Faces_(t-1) * 3
    //  Vertices_n = Vertices_(n-1) + Edges_(n-1)
    
    const float phi=atanf(0.5f);
    
#ifdef USE_CXX11
    vectors.emplace_back(0.0f, 0.0f, 1.0f);
#else
    vectors.push_back(Vec3(0.0f, 0.0f, 1.0f));
#endif
    
    for (size_t i=0; i<5; ++i)
    {
#ifdef USE_CXX11
        vectors.emplace_back(cosf((i*72.0f/180.f) * ((float)M_PI))*cosf(phi),
                             sinf((i*72.0f/180.f) * ((float)M_PI))*cosf(phi),
                             (         1.0f          )*sinf(phi));
#else
        vectors.push_back(Vec3(cosf((i*72.0f/180.f) * ((float)M_PI))*cosf(phi),
                               sinf((i*72.0f/180.f) * ((float)M_PI))*cosf(phi),
                               (         1.0f          )*sinf(phi)));
#endif
        binIndices.push_back(0);
        binIndices.push_back(((i+0)%5) + 1);
        binIndices.push_back(((i+1)%5) + 1);
    }
    
    for (size_t i=0; i<5; ++i)
    {
#ifdef USE_CXX11
        vectors.emplace_back(cosf(((i+0.5f)*72.0f/180.f) * ((float)M_PI))*cosf(-phi),
                             sinf(((i+0.5f)*72.0f/180.f) * ((float)M_PI))*cosf(-phi),
                             (         1.0f          )*sinf(-phi));
#else
        vectors.push_back(Vec3(cosf(((i+0.5f)*72.0f/180.f) * ((float)M_PI))*cosf(-phi),
                               sinf(((i+0.5f)*72.0f/180.f) * ((float)M_PI))*cosf(-phi),
                               (         1.0f          )*sinf(-phi)));
#endif
        binIndices.push_back(((i+0)%5) + 1);
        binIndices.push_back(((i+0)%5) + 6);
        binIndices.push_back(((i+1)%5) + 1);
        
        binIndices.push_back(((i+0)%5) + 6);
        binIndices.push_back(((i+1)%5) + 6);
        binIndices.push_back(((i+1)%5) + 1);
    }
    
#ifdef USE_CXX11
    vectors.emplace_back(0.0f, 0.0f, -1.0f);
#else
    vectors.push_back(Vec3(0.0f, 0.0f, -1.0f));
#endif
    
    for (size_t i=0; i<5; ++i)
    {
        binIndices.push_back(((i+1)%5) + 6);
        binIndices.push_back(((i+0)%5) + 6);
        binIndices.push_back(11);
    }
    //======================================================
    
    
    //Subdivide the icosahedron until number of vertices>=minimumNumVertices.
    while (vectors.size()<minimumNumVectors)
    {
        size_t numBinIndices=binIndices.size();
        
        for (size_t indexNum=0; indexNum<numBinIndices; indexNum+=3)
        {
            size_t i0=binIndices[indexNum+0];
            size_t i1=binIndices[indexNum+1];
            size_t i2=binIndices[indexNum+2];
            
            const stitch::Vec3 v0=vectors[i0];
            const stitch::Vec3 v1=vectors[i1];
            const stitch::Vec3 v2=vectors[i2];
            
            stitch::Vec3 v01=(v0+v1);
            v01.normalise();
            stitch::Vec3 v12=(v1+v2);
            v12.normalise();
            stitch::Vec3 v20=(v2+v0);
            v20.normalise();
            
            int32_t i01=-1;
            int32_t i12=-1;
            int32_t i20=-1;
            
            //=== Check if any of the new vertices already exist ===
            {//Need to have distance epsilon?
                const float similarity_epsilon=0.00001f;
                
                float radius01=1.0f;
                stitch::BoundingVolume *bv01=kdTree.getNearest(v01, radius01);
                
                float radius12=1.0f;
                stitch::BoundingVolume *bv12=kdTree.getNearest(v12, radius12);
                
                float radius20=1.0f;
                stitch::BoundingVolume *bv20=kdTree.getNearest(v20, radius20);
                
                if (bv01)
                {
                    const uint32_t vertexNum01=bv01->userIndex_;
                    if ( Vec3::calcDistToPointSq(vectors[vertexNum01], v01) < similarity_epsilon )
                    {
                        i01=vertexNum01;
                    }
                }
                
                if (bv12)
                {
                    const uint32_t vertexNum12=bv12->userIndex_;
                    if ( Vec3::calcDistToPointSq(vectors[vertexNum12], v12) < similarity_epsilon )
                    {
                        i12=vertexNum12;
                    }
                }
                
                if (bv20)
                {
                    const uint32_t vertexNum20=bv20->userIndex_;
                    if ( Vec3::calcDistToPointSq(vectors[vertexNum20], v20) < similarity_epsilon )
                    {
                        i20=vertexNum20;
                    }
                }
            }
            //=== ===//
            
            if (i01<0)
            {//This is a new vertex, so add it.
                vectors.push_back(v01);
                i01=vectors.size()-1;
                kdTree.addItem(new stitch::BoundingVolume(vectors[vectors.size()-1], 0.0f, vectors.size()-1));
            }
            
            if (i12<0)
            {//This is a new vertex, so add it.
                vectors.push_back(v12);
                i12=vectors.size()-1;
                kdTree.addItem(new stitch::BoundingVolume(vectors[vectors.size()-1], 0.0f, vectors.size()-1));
            }
            
            if (i20<0)
            {//This is a new vertex, so add it.
                vectors.push_back(v20);
                i20=vectors.size()-1;
                kdTree.addItem(new stitch::BoundingVolume(vectors[vectors.size()-1], 0.0f, vectors.size()-1));
            }
            
            std::vector<stitch::Vec3> splitAxisVec;
            splitAxisVec.push_back(Vec3(1.0f, 0.0f, 0.0f));
            splitAxisVec.push_back(Vec3(0.0f, 1.0f, 0.0f));
            splitAxisVec.push_back(Vec3(0.0f, 0.0f, 1.0f));
            
            kdTree.build(KDTREE_DEFAULT_CHUNK_SIZE, 0, 1000, splitAxisVec);
            
            {
                binIndices[indexNum+0]=i0;
                binIndices[indexNum+1]=i01;
                binIndices[indexNum+2]=i20;
            }
            
            {
                binIndices.push_back(i01);
                binIndices.push_back(i12);
                binIndices.push_back(i20);
            }
            
            {
                binIndices.push_back(i20);
                binIndices.push_back(i12);
                binIndices.push_back(i2);
            }
            
            {
                binIndices.push_back(i01);
                binIndices.push_back(i1);
                binIndices.push_back(i12);
            }
        }
    }
}