Ejemplo n.º 1
0
//04
void sto()
{
    stack[getBase(ir.l, bp) + ir.m] = stack[sp];
    sp = sp-1;
}
Ejemplo n.º 2
0
std::string empathy::getAssetPath(std::string dir)
{
    return join_path(getBase(),join_path("assets",dir));
}
Ejemplo n.º 3
0
void WalkerPrefect::onMidTile()
{
  ReachedBuildings reachedBuildings;
  TilePos firePos;
  bool haveBurningRuinsNear = _looks4Fire( reachedBuildings, firePos );  
  bool isDestination = _getPathway().isDestination();

  switch( _d->action )
  {
  case Impl::doNothing:
  break;

  case Impl::patrol:
  {
    if( haveBurningRuinsNear )
    {
      //tell our prefecture that need send prefect with water to fight with fire
      //on next deliverService

      //found fire, no water, go prefecture
      getBase().as<Prefecture>()->fireDetect( firePos );
      _back2Prefecture();

      Walker::onNewDirection();
    }
    else
    {
      foreach( BuildingPtr building, reachedBuildings )
      {
        building->applyService( ServiceWalkerPtr( this ) );

        HousePtr house = building.as<House>();
        if( house.isValid() && house->getHealthLevel() < 1 )
        {
          house->deleteLater();

          GameEventMgr::append( DisasterEvent::create( house->getTilePos(), DisasterEvent::plague ) );
        }
      }
    }

    if( isDestination )
    {
      _back2Prefecture();
    }

    Walker::onMidTile();
  }
  break;

  case Impl::back2Prefecture:
  {
    if( haveBurningRuinsNear )
    {
      //tell our prefecture that need send prefect with water to fight with fire
      //on next deliverService
      getBase().as<Prefecture>()->fireDetect( firePos );
    }

    if( isDestination )
    {
      deleteLater();
      _d->action = Impl::doNothing;
    }

    Walker::onMidTile();
  }
  break;

  case Impl::gotoFire:
  {
    if( _getPathway().getDestination().getIJ().distanceFrom( getIJ() ) < 1.5f )
    {
      LandOverlayPtr overlay = _getPathway().getDestination().getOverlay();
      if( overlay.isValid() && overlay->getType() == B_BURNING_RUINS )
      {
        _d->action = Impl::fightFire;
        _setGraphic( WG_PREFECT_FIGHTS_FIRE );
        Walker::onNewDirection();
        isDestination = false;
      }
    }

    if( isDestination )
    {
      if( !haveBurningRuinsNear || _d->water == 0 )
      {
        _back2Prefecture();
      }
      else
      {
        _setGraphic( WG_PREFECT_DRAG_WATER );
        _d->action = Impl::gotoFire;

        _checkPath2NearestFire( reachedBuildings );
        Walker::onNewDirection();
      }
    }

    Walker::onMidTile();
  }
  break;

  case Impl::fightFire:
  break;
  }
Ejemplo n.º 4
0
uint32 ReduceParams::cflInit(const SharedContext& ctx) const {
	return cflSched.disabled() ? 0 : getLimit(getBase(ctx), fInit, initRange);
}
Ejemplo n.º 5
0
void RenderMathMLRoot::layoutBlock(bool relayoutChildren, LayoutUnit)
{
    ASSERT(needsLayout());

    if (!relayoutChildren && simplifiedLayout())
        return;

    updateStyle();
    m_radicalOperatorTop = 0;
    m_baseWidth = 0;

    if (!isValid()) {
        setLogicalWidth(0);
        setLogicalHeight(0);
        clearNeedsLayout();
        return;
    }

    // We layout the children, determine the vertical metrics of the base and set the logical width.
    // Note: Per the MathML specification, the children of <msqrt> are wrapped in an inferred <mrow>, which is the desired base.
    LayoutUnit baseAscent, baseDescent;
    recomputeLogicalWidth();
    if (m_kind == SquareRoot) {
        baseAscent = baseDescent;
        RenderMathMLRow::computeLineVerticalStretch(baseAscent, baseDescent);
        RenderMathMLRow::layoutRowItems(baseAscent, baseDescent);
        m_baseWidth = logicalWidth();
    } else {
        getBase().layoutIfNeeded();
        m_baseWidth = getBase().logicalWidth();
        baseAscent = ascentForChild(getBase());
        baseDescent = getBase().logicalHeight() - baseAscent;
        getIndex().layoutIfNeeded();
    }

    // Stretch the radical operator to cover the base height.
    // We can then determine the metrics of the radical operator + the base.
    m_radicalOperator.stretchTo(style(), baseAscent + baseDescent);
    LayoutUnit radicalOperatorHeight = m_radicalOperator.ascent() + m_radicalOperator.descent();
    LayoutUnit indexBottomRaise = m_degreeBottomRaisePercent * radicalOperatorHeight;
    LayoutUnit radicalAscent = baseAscent + m_verticalGap + m_ruleThickness + m_extraAscender;
    LayoutUnit radicalDescent = std::max<LayoutUnit>(baseDescent, radicalOperatorHeight + m_extraAscender - radicalAscent);
    LayoutUnit descent = radicalDescent;
    LayoutUnit ascent = radicalAscent;

    // We set the logical width.
    if (m_kind == SquareRoot)
        setLogicalWidth(m_radicalOperator.width() + m_baseWidth);
    else {
        ASSERT(m_kind == RootWithIndex);
        setLogicalWidth(m_kernBeforeDegree + getIndex().logicalWidth() + m_kernAfterDegree + m_radicalOperator.width() + m_baseWidth);
    }

    // For <mroot>, we update the metrics to take into account the index.
    LayoutUnit indexAscent, indexDescent;
    if (m_kind == RootWithIndex) {
        indexAscent = ascentForChild(getIndex());
        indexDescent = getIndex().logicalHeight() - indexAscent;
        ascent = std::max<LayoutUnit>(radicalAscent, indexBottomRaise + indexDescent + indexAscent - descent);
    }

    // We set the final position of children.
    m_radicalOperatorTop = ascent - radicalAscent + m_extraAscender;
    LayoutUnit horizontalOffset = m_radicalOperator.width();
    if (m_kind == RootWithIndex)
        horizontalOffset += m_kernBeforeDegree + getIndex().logicalWidth() + m_kernAfterDegree;
    LayoutPoint baseLocation(mirrorIfNeeded(horizontalOffset, m_baseWidth), ascent - baseAscent);
    if (m_kind == SquareRoot) {
        for (auto* child = firstChildBox(); child; child = child->nextSiblingBox())
            child->setLocation(child->location() + baseLocation);
    } else {
        ASSERT(m_kind == RootWithIndex);
        getBase().setLocation(baseLocation);
        LayoutPoint indexLocation(mirrorIfNeeded(m_kernBeforeDegree, getIndex()), ascent + descent - indexBottomRaise - indexDescent - indexAscent);
        getIndex().setLocation(indexLocation);
    }

    setLogicalHeight(ascent + descent);
    clearNeedsLayout();
}
Ejemplo n.º 6
0
QString SimpleType::generateSetter(QString inputString,
                                   QString outputVariable) {
    return ((SimpleType*) getBase())->generateSetter(inputString,
            outputVariable);
}
Ejemplo n.º 7
0
void CANMessageObject::clear()
{
	CANMessageClear(getBase(), _mob_num);
	get(false);
}
Ejemplo n.º 8
0
	void LevelCalculator::getTradeRequestFromSynthSymbol(
			MultuSymbolRequestEntryList& reqList, 
			CppUtils::String const& synthSymbol, 
			BrkLib::TradeDirection const td,
			int const volume
		)
	{
		reqList.clear();
		LOG(MSG_DEBUG, SOLVERIMPL, "Evaluating volume coefficients for synth symbol: " << synthSymbol );


		map<CppUtils::String, CppUtils::Parser*>::iterator it = parsers_m.find(synthSymbol);
		if (it == parsers_m.end())
			THROW(CppUtils::OperationFailed, "exc_ParserNotRegistered", "ctx_getTradeRequestFromSynthSymbol", synthSymbol );

		CppUtils::StringMap const& smartcom_symbols_reverse = getBase().getSmartcomSymbolsReverse();

		CppUtils::Parser & parser = *it->second;
		
		// need to get cooeficients in formula 
		//

		
		

		// iterate through all reverse symbols
		for( CppUtils::StringMap::const_iterator it = smartcom_symbols_reverse.begin(); it != smartcom_symbols_reverse.end(); it++) {
			CppUtils::String const& symbol_pseudonym = it->first;
			CppUtils::String const& symbol_real = it->second;

			
			parser.ClearBind();
			for( CppUtils::StringMap::const_iterator it2 = smartcom_symbols_reverse.begin(); it2 != smartcom_symbols_reverse.end(); it2++) {
				CppUtils::String const& symbol_pseudonym_2 = it2->first;

				if (symbol_pseudonym == symbol_pseudonym_2)
					parser[symbol_pseudonym_2]  = 1;
				else
					parser[symbol_pseudonym_2]  = 0;

			}

			// evaluate here
			try {
				double volume_coeff = parser.Evaluate();
				

				// setup
				MultuSymbolRequestEntry reqEntry;
				reqEntry.symbol_m = symbol_real;
				reqEntry.direction_m = td;
				
				reqEntry.volume_m = abs(volume * (int)volume_coeff);

				if (td == BrkLib::TD_LONG) {
					if (volume_coeff < 0) 
						reqEntry.direction_m = BrkLib::TD_SHORT;
					else if (volume_coeff > 0) 
						reqEntry.direction_m = BrkLib::TD_LONG;		  
					else
						THROW(CppUtils::OperationFailed, "exc_VolumeCannotBeZero", "ctx_getTradeRequestFromSynthSymbol", "");
				}
				else if (td == BrkLib::TD_SHORT) {
					if (volume_coeff < 0) 
						reqEntry.direction_m = BrkLib::TD_LONG;
					else if (volume_coeff > 0) 
						reqEntry.direction_m = BrkLib::TD_SHORT;		  
					else
						THROW(CppUtils::OperationFailed, "exc_VolumeCannotBeZero", "ctx_getTradeRequestFromSynthSymbol", "");
				}													     
				else
					THROW(CppUtils::OperationFailed, "exc_DirectionTradeInvalid", "ctx_getTradeRequestFromSynthSymbol", "");

				reqList.push_back(reqEntry);
				LOG(MSG_DEBUG, SOLVERIMPL, "Added request entry: " << reqEntry.toString() << "for synthetic symbol: " << synthSymbol << "( pseudonym: " << symbol_pseudonym << ")");

			}
			catch(std::exception& e)
			{
				THROW(CppUtils::OperationFailed, "exc_ParserError", "ctx_getTradeRequestFromSynthSymbol", e.what());
			}
																	  
			// resolve

			
		}


	}
Ejemplo n.º 9
0
	void LevelCalculator::onRtData(HlpStruct::RtData const& rtdata,CalcContext* ctx)
	{
		// need to extract symbols
		// calculate synthetic if any

		
		if (getBase().getBase().getBarDataProvider_Smartcom() != rtdata.getProvider2())
			return;


		CppUtils::StringMap const& smartcom_symbols = getBase().getSmartcomSymbols();
		CppUtils::StringSet const& synthetic_symbols = getBase().getSyntheticSmartcomSymbols();

		if (!initialized_m) {
			
			// iterate through all synbols and cache them
			for(CppUtils::StringMap::const_iterator it = smartcom_symbols.begin(); it != smartcom_symbols.end(); it++) {
				CppUtils::String const& symbol_i = it->first;

				int id = ctx->historyaccessorPtr->cacheSymbol( getBase().getBase().getBarDataProvider_Smartcom(), symbol_i, HlpStruct::AP_Minute, getBase().getTradeParam().tradePeriodMinutes_m);
				cache_ids_m[ symbol_i ] = id;
				dataset_m.registerSymbol( symbol_i );

			}

			LOG(MSG_INFO, SOLVERIMPL, "Initialized all" );
			initialized_m =  true;

			//flag_m = 0;
		}

		
		int fastPer = getBase().getTradeParam().maFastPeriod_m;
		int slowPer = getBase().getTradeParam().maSlowPeriod_m;
		int cachePer = max(fastPer, slowPer);

		// will raise on each symbol arrival
		map<CppUtils::String, int>::const_iterator it2 = cache_ids_m.find(rtdata.getSymbol2()); 
		if (it2 == cache_ids_m.end())
			return;

		int cache_id = it2->second;
		HlpStruct::PriceData const& unclosed = ctx->historyaccessorPtr->getUnclosedCandle(cache_id);

		if (unclosed.isNewPeriod()) {
			//LOG(MSG_INFO, SOLVERIMPL, "Unclosed symbol: " << rtdata.getSymbol() << " - " << unclosed.toString());
			Inqueue::DataRowPtr rptr =  ctx->historyaccessorPtr->dataRowLast();
			
			int total_idx = cachePer*2; 

			// clear dataset because we could chaise symbol from the past and need to recalculate everything
			dataset_m.clearData();
			
			// iterate through all rows
			while( ctx->historyaccessorPtr->dataRowPrev(rptr)) {
				// get current price data
				

				if (total_idx-- < 0)
					break;

				// iterate through all symbols
				double ttime = ctx->historyaccessorPtr->getCurrentDataRowTime(rptr);
				for( map<CppUtils::String, int>::const_iterator it2 = cache_ids_m.begin(); it2 != cache_ids_m.end(); it2 ++) {
					
					CppUtils::String const& symbol_i = it2->first;
					HlpStruct::PriceData const& pdata = ctx->historyaccessorPtr->getCurrentDataRow(it2->second, rptr );

					//LOG(MSG_INFO, SOLVERIMPL, "time: " << CppUtils::getGmtTime(ttime) << " symbol: " << symbol_i << " data: " << pdata.toString() );
						
					if (pdata.isValid()) {
						dataset_m.addPriceData(symbol_i, pdata);
					} else {
						HlpStruct::PriceData pdata_prev = ctx->historyaccessorPtr->getCurrentDataRowTryLocatePrevValid( it2->second, rptr );
						if (pdata_prev.isValid())	 {
							//LOG(MSG_INFO, SOLVERIMPL, "time: " << CppUtils::getGmtTime(ttime) << " symbol: " << symbol_i << " Found prev data: " << pdata_prev.toString() );
							dataset_m.addPriceDataAsImportedFromPast(ttime, symbol_i, pdata_prev.close2_m);
						} else {
							LOG(MSG_INFO, SOLVERIMPL, "time: " << CppUtils::getGmtTime(ttime) << " symbol: " << symbol_i << " Cannot find prev data" );
						}

					}
	

				} // end iterating through symbols

				
				
																  
			} // end loop	through rows
			
			// log
			/*
			CppUtils::UnsignedLongLong tm_stamp  = CppUtils::UnsignedLongLong(CppUtils::getTime() * 1000.0);
			CppUtils::String file = "c:\\temp\\data\\content_raw_i_" + CppUtils::long64ToString(tm_stamp) + ".txt";
			CppUtils::saveContentInFile2(file, dataset_m.dump());

			// debug dump
			file = "c:\\temp\\data\\content_debug_i_" + CppUtils::long64ToString(tm_stamp) + ".txt";
			CppUtils::saveContentInFile2(file, ctx->historyaccessorPtr->makeDebugDump(true));
			*/

			
			// because this stuff below is calculated for finished candles - time is contained in thel last row
			double row_ttime = -1;
			if (dataset_m.last()) {
				row_ttime = dataset_m.getTimeKey();
			}
			
			typedef Math::MovAverMathEngineNoNegativePrice<Math::MultiSymbolCacheSeriesProvider> MaEngineType;

			// iterate through synthetic symbols
			for( set<CppUtils::String>::const_iterator i3 = synthetic_symbols.begin(); i3 != synthetic_symbols.end(); i3++) {
				CppUtils::String const& symbol_i3 = *i3;
				MaEngineType ma_channel_fast(fastPer);
				MaEngineType::Result res_ma_channel_fast = 
					ctx->historyaccessorPtr->callMathEngineWithMultiSymbolCacheSeries< MaEngineType::Result, Math::P_CloseBid, MaEngineType >(dataset_m, *i3, ma_channel_fast);

				MaEngineType ma_channel_slow(slowPer);
				MaEngineType::Result res_ma_channel_slow = 
					ctx->historyaccessorPtr->callMathEngineWithMultiSymbolCacheSeries< MaEngineType::Result, Math::P_CloseBid, MaEngineType >(dataset_m, *i3, ma_channel_slow);

				
				if (!res_ma_channel_slow.isValid_m) {
					//LOG(MSG_INFO, SOLVERIMPL, "Trading symbol: " << symbol_i3 << " time:" << CppUtils::getGmtTime(row_ttime) <<  " MA slow is invalid");
					continue;
				}

				if (!res_ma_channel_fast.isValid_m) {
					//LOG(MSG_INFO, SOLVERIMPL, "Trading symbol: " << symbol_i3 << " time:" << CppUtils::getGmtTime(row_ttime) << " MA fast is invalid");
				
					continue;
				}


				BrkLib::TradeDirection td = signalContextMap_m[symbol_i3].update(row_ttime, res_ma_channel_slow.result_m, res_ma_channel_fast.result_m);

				//LOG(MSG_INFO, SOLVERIMPL, "symbol: " << symbol_i3 << " time:" << CppUtils::getGmtTime(row_ttime) << " MA slow: " << res_ma_channel_slow << " MA fast: " << res_ma_channel_fast << ", result: " << BrkLib::tradeDirection2String(td));

				// main notification
				DRAWOBJ_LINEINDIC_4(
					getBase().getBase().getRunName(), 
					CppUtils::getTime(), 
					"MA", 
					symbol_i3, getBase().getBase().getBarDataProvider_Smartcom(), 
					"MASLOW", res_ma_channel_slow.result_m, -1, 
					"MAFAST", res_ma_channel_fast.result_m, -1,
					"ROW_TTIME", row_ttime, -1,
					"SIGNAL",td, -1
				);

				if (getBase().getTradeParam().synthSymbolToTrade_m.get() != symbol_i3)
					continue;
	

				LOG(MSG_INFO, SOLVERIMPL, "Trading symbol: " << symbol_i3 << " time:" << CppUtils::getGmtTime(row_ttime) << " MA slow: " << res_ma_channel_slow.result_m << " MA fast: " << res_ma_channel_fast.result_m << ", result: " << BrkLib::tradeDirection2String(td));
				
				
				// make trading solution
				if (td == BrkLib::TD_LONG && (
					getBase().getGlobalTradeContext().get().allowTrading_m == BrkLib::TD_BOTH ||
					getBase().getGlobalTradeContext().get().allowTrading_m == BrkLib::TD_LONG
					)
				) {

					TE_Signal_Long e;
					getBase().getTradingMachine().processEvent<TE_Signal_Long>(e);	

				}
				else if (td == BrkLib::TD_SHORT	 && (
					getBase().getGlobalTradeContext().get().allowTrading_m == BrkLib::TD_BOTH ||
					getBase().getGlobalTradeContext().get().allowTrading_m == BrkLib::TD_SHORT
					)
				) {

					TE_Signal_Short e;
					getBase().getTradingMachine().processEvent<TE_Signal_Short>(e);
				}
				

				
				/*
				if (flag_m == 0) {
					flag_m = 1;

					TE_Signal_Long e;
					getBase().getTradingMachine().processEvent<TE_Signal_Long>(e);	
				}
				else {
					flag_m = 0;

					TE_Signal_Short e;
					getBase().getTradingMachine().processEvent<TE_Signal_Short>(e);
				}
				*/
				
				
			} // loop through suymbols
			


				
			



			/*
			CppUtils::UnsignedLongLong tm_stamp  = CppUtils::UnsignedLongLong(CppUtils::getTime() * 1000.0);
			CppUtils::String file = "c:\\temp\\data\\content_allrows_i_" + CppUtils::long64ToString(tm_stamp) + ".txt";
			CppUtils::String data = ctx->historyaccessorPtr->dumpAllRows();
			CppUtils::saveContentInFile2(file, data);

			
			file = "c:\\temp\\data\\content_debug_i_" + CppUtils::long64ToString(tm_stamp) + ".txt";
			CppUtils::saveContentInFile2(file, ctx->historyaccessorPtr->makeDebugDump(true));
			*/
			
			
						

			/*
			HlpStruct::MultiSymbolCache dataset_fixed = dataset_m;
			fixGapsInDataset(dataset_fixed, -1);
			file = "c:\\temp\\data\\content_fixed_i_" + CppUtils::long64ToString(tm_stamp) + ".txt";
			CppUtils::saveContentInFile2(file, dataset_fixed.dump());

			// calculate data

			HlpStruct::MultiSymbolCache synthetic_dataset;
			calculateSynthetic(dataset_fixed, synthetic_dataset);
			file = "c:\\temp\\data\\synthetic_i_" + CppUtils::long64ToString(tm_stamp) + ".txt";
			CppUtils::saveContentInFile2(file, synthetic_dataset.dump());
			*/

			
		
		} // if new period


		
	}
Ejemplo n.º 10
0
//this function is simply a store function
void sto (int levels, int offset)
{
    int base = getBase(levels, bp);
    stack [base + offset] = stack[sp];
    sp --;
}
Ejemplo n.º 11
0
		BFSMultiVertex() {
			//vertices.assign(N / ckGetArraySize(), BFSVertex());
			for(CmiUInt8 i = 0; i < N / ckGetArraySize(); i++)
				vertices.push_back(BFSVertex(getBase() + i));
		}
Ejemplo n.º 12
0
//lod function will do 3 things
//get the base value L levels down
//grab the number at offset M
//push that number
void lod (int levels, int offset)
{
    int base = getBase(levels, bp);
    int value = stack[base + offset];
    lit(value);
}
Ejemplo n.º 13
0
/* This task is responsible for gesture recognition. */
void gesture_recognition_task(void *pdata)
{
	INT8U err;

	double end_time = 0.0;
	double start_time = OSTimeGet();
	double frame_rate = 0.0;
	double time_passed = 0.0;

	int frame_count = 0;
	int x = 0;
	int y = 0;
	int direction_code = 0;
    int mode = SEARCH_MODE;

	struct SearchNode *storage_base = getBase();
	printStorage(storage_base->next);

	struct DirectionNode *incoming_node, *last_incoming_node, *base;
    last_incoming_node = getDummyBase();

	while (1) {
		int centroid = (int) OSQPend(position_queue, 0, &err);
		if (err == OS_NO_ERR) {
			end_time = OSTimeGet();
			frame_count += 1;
			time_passed = (end_time - start_time) / OS_TICKS_PER_SEC;

			x = centroid & 1023;
			y = centroid >> 16;
			frame_rate = frame_count / time_passed;
;
			incoming_node = createDirectionNode(x, y, NO_GESTURE);

			/* We ignore position information that falls within the same grid */
			if (compareTwoDirectionNodes(incoming_node, last_incoming_node) == NODES_DIFFERENT) {

                if (mode == SEARCH_MODE) {
			        base = firstDirectionNode(incoming_node, last_incoming_node);
                } else {
				    base = nextDirectionNode(incoming_node, base, last_incoming_node, &direction_code);
                }

				if (base) {
					// Leaf node
					if (base->gesture_code != NO_GESTURE) {
                        mode = SEARCH_MODE;
                        handleGestureCommands(base->gesture_code);

					} else {
                        mode = FOLLOW_MODE;
					}
				} else {
                    mode = SEARCH_MODE;
				}

		        free(last_incoming_node);
		        last_incoming_node = incoming_node;

			} else {
			}
		} else {
Ejemplo n.º 14
0
void pcode(Tinstruction inst[], int stack[], FILE *output){
	int base = 1;				// Points to the base address in the stack for the current invocation of a given procedure
    int top = 0; 				// Points to the current top of the stack
    int counter = 0;  			// Points to an instruction in the program area
	
	int aux;
	int stop = 0;
	
	do{
    	Tinstruction instruction = inst[counter];
    	counter++;
    	switch (instruction.operation){
    		case LIT:
    			top++;
    			stack[top] = instruction.argument;
    			break;
    		case OPR:
    			switch(instruction.argument){
    				case RTN:
    					top = base - 1;
    					counter = stack[top+3];
    					base = stack[top+2];
    					break;
    				case NEG:
    					stack[top]= -1*stack[top];
    					break;
    				case ADD:
    					top--;
    					stack[top] += stack[top+1];
    					break;
    				case SUB:
    					top--;
    					stack[top] -= stack[top+1];
    					break;
    				case MUL:
    					top--;
    					stack[top] *= stack[top+1];
    					break;
    				case DIV:
    					top--;
    					stack[top] /= stack[top+1];
    					break;
    				case MOD:
    					top--;
    					stack[top] %= stack[top+1]; 
    					break;
    				case ODD:
    					stack[top] = (stack[top]%2 == 1);
    					break;
    				case EQL:
    					top--;
    					stack[top] = (stack[top] == stack[top+1]);
    					break;
    				case NEQ:
    					top--;
    					stack[top] = (stack[top] != stack[top+1]);
    					break;
    				case LSS:
    					top--;
    					stack[top] = (stack[top] < stack[top+1]);
    					break;
    				case LEQ:
    					top--;
    					stack[top] = (stack[top] <= stack[top+1]);
    					break;
    				case GTR:
    					top--;
    					stack[top] = (stack[top] > stack[top+1]);
    					break;
    				case GEQ:
    					top--;
    					stack[top] = (stack[top] >= stack[top+1]);
    					break;
    				default:
    					printf("Unknown OPR subfunction");
    					break;
    				}
    			break;
    		case LOD:
    			top++;
    			stack[top] = stack[ getBase(instruction.level, base, stack) + instruction.argument ];
    			stack[ getBase(instruction.level, base, stack) + instruction.argument ] = -10;
    			break;
    		case STO:
    			stack[ getBase(instruction.level, base, stack) + instruction.argument ] = stack[top];
    			top--;
    			break;
    		case CAL:
    			stack[top+1] = getBase(instruction.level, base, stack);
    			stack[top+2] = base;
    			stack[top+3] = counter;
    			base = top+1;
    			counter = instruction.argument;
    			break;
    		case INT:
    			top += instruction.argument;
    			break;
    		case JMP:
    			counter = instruction.argument-1;
    			break;
    		case JPC:
    			if (stack[top] == 0){
    				counter = instruction.argument-1;
    			}
    			top--;	
    			break;
    		default:
    			printf("Unknown function");
    	}
    		
    	// PrintStackTrace
    	fprintf(output,"%-10s %-7d %-7d %-7d %-7d %-15d", getInstructionName(instruction.operation),instruction.level, instruction.argument, top, counter, base);
    
    	for (aux = base; aux<top+1 && top > 0;aux++){
    		if(stack[aux] == -10){
    			fprintf(output,"_ ");	
    		}else{
    			fprintf(output,"%d ", stack[aux]);
    		}
    	}
    	fprintf(output,"\n");
    	
    	// If RTN, stop
    	stop = (instruction.operation == 1 && instruction.argument == 0);
	}while(stop == 0);
}
Ejemplo n.º 15
0
QString SimpleType::getDataType() {
    return ((SimpleType*) getBase())->getDataType();
}
Ejemplo n.º 16
0
void pkCU::evaluateMove_script()
{
	assert(getStackStage() == STAGE_MOVEBASE);
	assert(getTPKV().isAlive() && getPKV().isAlive());

	const pokemon_nonvolatile& cPKNV = getPKNV();
	const pokemon_nonvolatile& tPKNV = getTPKNV();
	const move_nonvolatile& cMNV = cPKNV.getMove(getICAction());
	const move& cMove = cMNV.getBase();

	// the floor of the stack: everything below this stack value has been evaluated
	size_t baseFloor = iBase, baseCeil = getStack().size();

	// calculate probability to hit, miss:
	//for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		//if (getStackStage() != STAGE_MOVEBASE) { continue; }
		stackStage[iBase] = STAGE_MODIFYHITCHANCE;

		fpType& probabilityToHit = getDamageComponent().tProbability;

		// TODO: take target into account when calculating probability to hit!
		/* probability to hit enemy pokemon */
		if (cMove.targetsEnemy())
		{
			probabilityToHit = 
					getTMV().cGetAccuracy_boosted(FV_ACCURACY) // lowest is 33% or 3333 / 10000
					* getTTMV().cGetAccuracy_boosted(FV_EVASION) // highest is 300% or 3
					* cMove.getPrimaryAccuracy(); // lowest is 30% or 30 / 100
		}
		else
		{
			probabilityToHit = cMove.getPrimaryAccuracy();
		}

		// to-hit modifying values:
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYHITPROBABILITY, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), probabilityToHit);
	}

	// evaluate miss(1), hit(0),
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYHITCHANCE) { continue; }
		stackStage[iBase] = STAGE_PREDAMAGE;

		fpType& probabilityToHit = getDamageComponent().tProbability;

		// bound at MIN 0.033~ ... MAX 1.0
		probabilityToHit = std::max(std::min(probabilityToHit, (fpType)1.0), (fpType)0.0);

		boost::array<size_t, 2> iHEnv = {{ getIBase(), SIZE_MAX }};
		// did the move hit its target? Is it possible for the move to miss?
		if (mostlyGT(probabilityToHit, 0.0))
		{
			// if there's a chance the primary effect will not occur:
			if (mostlyLT(probabilityToHit, 1.0))
			{
				// duplicate the environment (duplicated environment is the miss environment):
				duplicateState(iHEnv, (1.0 - probabilityToHit));
			}

			// modify bitmask as the hit effect occuring:
			getStack()[iHEnv[0]].setHit(getICTeam());

		} // end of primary attack hits, and secondary attack is not assured
		else
		{
			// pass-through: no chance to hit
			stackStage[iBase] = STAGE_POSTDAMAGE;
		}
	}

	// perform script:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_PREDAMAGE) { continue; }
		advanceStackStage();

		if (!getBase().hasHit(getICTeam())) { continue; }

		// parse alternative move plugins:
		int result = getPKNV().getMove_base(getICAction()).isImplemented()?1:0; // TODO: this check isn't working!
		CALLPLUGIN(result, PLUGIN_ON_EVALUATEMOVE, onEvaluateMove_rawType, 
			*this, getPKNV().getMove(getICAction()), getPKNV(), getTPKNV(), getTMV(), getTTMV(), getPKV(), getTPKV());
	}

	return;
}
Ejemplo n.º 17
0
// save if inputString can be assigned to previously defined variable ok
QString SimpleType::generateControl(QString inputString) {
    return ((SimpleType*) getBase())->generateControl(inputString);
}
Ejemplo n.º 18
0
size_t pkCU::combineSimilarEnvironments()
{
	std::vector<environment_possible>& stack = getStack();
	size_t numUnique = stack.size();

#ifndef NDEBUG
#ifndef _DISABLEPROBABILITYCHECK
	fpType probabilityAccumulator = 0.0;
#endif
#endif

	// hash environments (and summate probabilities for check):
	for (iBase = 0; iBase != numUnique; ++iBase)
	{
		environment_possible& cEnvironment = getBase();

		// assert that each of these environments is getting hashed:
		assert(getStackStage() == STAGE_FINAL);
		advanceStackStage();

		// WARNING: EXPENSIVE!
		cEnvironment.generateHash();
	}

	// compare environment hashes:
	for (size_t iOEnv = 0, iSize = numUnique; iOEnv != iSize; iOEnv++)
	{
		environment_possible& oEnv = stack[iOEnv];
		fpType& oProbability = damageComponents[iOEnv].cProbability;

		// don't attempt to merge pruned environments
		if (oEnv.isPruned()) { continue; }

		for (size_t iIEnv = iOEnv + 1; iIEnv != iSize; iIEnv++)
		{
			environment_possible& iEnv = stack[iIEnv];
			fpType& iProbability = damageComponents[iIEnv].cProbability;

			// don't re-prune already pruned environments
			if (iEnv.isPruned()) { continue; }
			
			// don't merge non-identical environments
#ifdef _PKCUCHECKSIGNATURE
			assert((oEnv.hash == iEnv.hash) == (oEnv.env == iEnv.env));
#endif
			if (oEnv.getHash() != iEnv.getHash()) { continue; }

			// combine the two environments by adding their probabilities and deleting the second
			oProbability += iProbability;
			
			// this is probably not representative of the current environment now
			oEnv.getBitmask() &= iEnv.getBitmask();
			
			// flag this environment as merged with another environment
			oEnv.setMerged();

			// flag the inner environment as pruned by another environment
			iEnv.setPruned();

			// decrement number of unique values in vector
			numUnique--;

		} //endOf iInner

		// assign the collected probability to envP's smaller fixed point variable
		oEnv.getProbability() = fixedpoint::create<30>(oProbability);

#ifndef NDEBUG
#ifndef _DISABLEPROBABILITYCHECK
		probabilityAccumulator += oProbability;
#endif
#endif
		assert(mostlyGT(oProbability, 0.0) && mostlyLTE(oProbability, 1.0));
	} // endOf iOuter

#ifndef _DISABLEPROBABILITYCHECK
	assert(mostlyEQ(probabilityAccumulator, 1.0));
#endif

	return numUnique;
} //endOf combineSimilarEnvironments
Ejemplo n.º 19
0
QString SimpleType::generateInit(QString varName) {
    return ((SimpleType*) getBase())->generateInit(varName);
}
Ejemplo n.º 20
0
const pokemon_nonvolatile& pkCU::getTPKNV()
{
	return getNV().getTeam(getIOTeam()).getPKNV(getBase().getEnv().getTeam(getIOTeam()));
}
Ejemplo n.º 21
0
// Objects have simple paths /container/object-key
// If the object is of type iop a vfile can also be mapped to represent
// the columns inside the record
// The /container/.inetfs_schema can be used to determine visible or
// invisible columns
// Container names and keys are sha256'ed and readdir is disabled
string
ObjectServer::encodePath(ServerContext& ctxt, const char *path, string& vfile)
{
	string_list_t in, out;
	string_list_t::iterator it;
	string tmp;
	string root = getBase();
	bool fix = false;
	int pos = 0;
	vfile.clear();

#if 0	
	//_STDERR("encode: in path = %s", path);
	if (strncmp(base_name(path), ".inetfs_", 8) == 0)
	{
		//_STDERR("encode: out path = %s", path);
		return path;
	}
	//else
#endif
	if (strncmp(root.c_str(), path, root.length()) == 0)
	{
		path += root.length();
		fix = true;
	}
	
	if (path == NULL || *path == 0 || SEPSTR == path)
	{
		//_STDERR("encode: out path = %s", fix ? root.c_str() : "/");
		return fix ? root : SEPSTR;
	}
	
	path_to_list(path, in);
	bool is_control = false;
	for (it = in.begin(); it != in.end(); it++)
	{
		is_control = strncmp(it->c_str(), ".inetfs_", 8) == 0;
		tmp = *it;

		switch (pos)
		{
		case 0:
			if (!is_control)
			{
				make_hash16("sha256", *it, tmp);
			}
			out.push_back(tmp);
			break;
			
		case 1:
			if (!is_control)
			{
				make_hash16("sha256", *it, tmp);
			}
#if 1
			out.push_back(tmp);
#else
			out.push_back(string(tmp.c_str(), 3));
			out.push_back(string(tmp.c_str() + 3) + string(".dir"));
#endif
			break;
			
		case 2:
			vfile = *it;
			break;
			
		default:
			vfile += SEPSTR + *it;
		}
		pos++;
	}
	tmp = implode(out, SEPCSTR);
	if (tmp.empty())
	{
		tmp = SEPSTR;
	}
	if (tmp.c_str()[0] != SEPARATOR)
	{
		tmp = SEPSTR + tmp;
	}
	string pp = root + tmp;
	//_STDERR("encode: out path = %s", pp.c_str());

	return root + tmp;
}
Ejemplo n.º 22
0
void pkCU::setCPluginSet()
{
	size_t iCPokemon = getBase().getEnv().getTeam(getICTeam()).getICPKV();
	size_t iOPokemon = getBase().getEnv().getTeam(getIOTeam()).getICPKV();
	cPluginSet = &pluginSets[getICTeam() * 6 + iCPokemon][iOPokemon];
}
Ejemplo n.º 23
0
void WalkerPrefect::onMidTile()
{
  ReachedBuildings reachedBuildings;
  TilePos firePos;
  bool haveBurningRuinsNear = _looks4Fire( reachedBuildings, firePos );  
  bool isDestination = _pathWay.isDestination();

  switch( _d->action )
  {
  case Impl::patrol:
    {
      if( haveBurningRuinsNear )
      {
        //tell our prefecture that need send prefect with water to fight with fire
        //on next deliverService

        //found fire, no water, go prefecture
        getBase().as<BuildingPrefect>()->fireDetect( firePos );         
        _back2Prefecture();

        Walker::onNewDirection();
      }
      else
      {
        for( ReachedBuildings::iterator itBuilding = reachedBuildings.begin(); 
             itBuilding != reachedBuildings.end(); ++itBuilding)
        {
          (*itBuilding)->applyService( ServiceWalkerPtr( this ) );
        }
      }

      if( isDestination )
      {
        _back2Prefecture();
      }

      Walker::onMidTile();
    }
  break;

  case Impl::back2Prefecture:
    {
      if( haveBurningRuinsNear )
      {
        //tell our prefecture that need send prefect with water to fight with fire
        //on next deliverService
        getBase().as<BuildingPrefect>()->fireDetect( firePos );        
      }

      if( isDestination )
      {
        deleteLater();
        _d->action = Impl::doNothing;
      }

      Walker::onMidTile();
    }
  break;

  case Impl::gotoFire:
    {
      if( _pathWay.getDestination().getIJ().distanceFrom( getIJ() ) < 1.5f )
      {
        LandOverlayPtr overlay = _pathWay.getDestination().get_terrain().getOverlay();
        BurningRuinsPtr bruins = overlay.as<BurningRuins>();
        if( bruins.isValid() )
        {
          _d->action = Impl::fightFire;     
          _walkerGraphic = WG_PREFECT_FIGHTS_FIRE;
          Walker::onNewDirection();
          isDestination = false;
        }
      }
      
      if( isDestination )
      {
        if( !haveBurningRuinsNear || _d->water == 0 ) 
        {
          _back2Prefecture();
        }
        else
        {
          _walkerGraphic = WG_PREFECT_DRAG_WATER;
          _d->action = Impl::gotoFire;

          _checkPath2NearestFire( reachedBuildings );
          Walker::onNewDirection();
        }
      }
     
      Walker::onMidTile();
    }
  break;

  case Impl::fightFire:
  break;
  }
}
Ejemplo n.º 24
0
void pkCU::evaluateMove()
{
	// NOTE: ONLY ONE stage is set to preturn at a time
	assert(getStackStage() == STAGE_PRETURN);
	size_t iCAction = getICAction();
	size_t iCTeam = getICTeam();
	// the floor of the stack: everything below this stack value has been evaluated
	size_t baseFloor = iBase, baseCeil = getStack().size(), iNBase;

	// TODO: does this model the actual game?
	// if either pokemon is dead at this point, the only valid moves are switching and waiting
	if ( (!getPKV().isAlive() || !getTPKV().isAlive()) && isMoveAction(iCAction) )
	{
		iCAction = AT_MOVE_NOTHING;
	}


	// does this move require a switch-out?
	if (isSwitchAction(iCAction))
	{
		stackStage[iBase] = STAGE_PRESWITCH;
		evaluateMove_switch();
	} // end of is Switch type action

	// is this pokemon doing nothing?
	else if (iCAction == AT_MOVE_NOTHING)
	{
		stackStage[iBase] = STAGE_POSTSECONDARY;

		// set that the current team did nothing this turn:
		getBase().setWaited(iCTeam);
		// pokemon performs no action, no update to the state is needed
	} // end of is Wait type action

	// is the pokemon moving normally?
	else if (isMoveAction(iCAction))
	{
		assert(getPKV().isAlive() && getTPKV().isAlive());

		// this is the first function which may generate more than one state of STAGE_STATUS type
		{
			stackStage[iBase] = STAGE_STATUS;
			evaluateMove_preMove();
		}

		// POSSIBLE THAT POKEMON MIGHT HAVE DIED IN PREVIOUS STEP

		const move& cMove = getPKNV().getMove_base(iCAction);
		void (pkCU::*evaluate_t)();
		if ( cMove.damageType == ATK_PHYSICAL || cMove.damageType == ATK_SPECIAL)
		{ evaluate_t = &pkCU::evaluateMove_damage;}
		else
		{ evaluate_t = &pkCU::evaluateMove_script;}

		// evaluate either move or plugin move: (increment with iNBase, as evaluateMove_damage will manipulate stack)
		for (iNBase = baseFloor, iBase = iNBase, baseCeil = getStack().size(); iNBase != baseCeil; ++iNBase, iBase = iNBase)
		{
			if (getStackStage() != STAGE_STATUS) { continue; }
			advanceStackStage();

			// was this move blocked by a status?
			// did this pokemon die from the last pokemon's action?
			if (getBase().wasBlocked(iCTeam) || !getPKV().isAlive()) { stackStage[iBase] = STAGE_POSTTURN; continue; }

			// evaluate either evaluateMove_damage from stackstage movebase, or evaluateMove_script from stackstage postmove
			(this->*evaluate_t)();
		}

		// for all worlds: (increment with iNBase, as evaluateMove_postMove will manipulate stack)
		for (iNBase = baseFloor, iBase = iNBase, baseCeil = getStack().size(); iNBase != baseCeil; ++iNBase, iBase = iNBase)
		{	
			if (getStackStage() != STAGE_POSTDAMAGE) { continue; }
			advanceStackStage();

			evaluateMove_postMove();
		} // endOf forEach environment
	} // endOf isMove

	// POSSIBLE THAT POKEMON MIGHT HAVE DIED IN PREVIOUS STEP

	// end of turn occurences:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_POSTSECONDARY) { continue; }
		stackStage[iBase] = STAGE_POSTTURN;

		evaluateMove_postTurn();
	}
	
	return;
} // end of evaluateMove
Ejemplo n.º 25
0
QString Scene_polyhedron_transform_item::toolTip() const {
    return QObject::tr("<p>Affine transformation of <b>%1</b></p>"
                       "<p>Keep <b>Ctrl</b> pressed and use the arcball to define an affine transformation.<br />"
                       "Press <b>S</b> to apply the affine transformation to a copy of <b>%1</b>.</p>")
            .arg(getBase()->name());
}
Ejemplo n.º 26
0
void pkCU::evaluateMove_postMove()
{
	assert(getStackStage() == STAGE_POSTMOVE);

	// the floor of the stack: everything below this stack value has been evaluated
	size_t baseFloor = iBase, baseCeil = getStack().size();

	// the current environment we are evaluating upon. Will be copied, modified and pushed back eventually
	const pokemon_nonvolatile& cPKNV = getPKNV();
	const pokemon_nonvolatile& tPKNV = getTPKNV();
	const move_nonvolatile& cMNV = cPKNV.getMove(getICAction());
	const move& cMove = cMNV.getBase();
	size_t iCTeam = getICTeam();

	// effects which occur regardless of a secondary effect occuring, but only if the move hit:
	//for (/*iBase = baseFloor, baseCeil = getStack().size()*/; iBase != baseCeil; ++iBase)
	{
		//if (getStackStage() != STAGE_POSTMOVE) { continue; }
		advanceStackStage();

		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_ENDOFMOVE, onEvaluateMove_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV());
	}

	// POSSIBLE THAT POKEMON MIGHT HAVE DIED IN PREVIOUS STEP

	// calculate probability to perform secondary:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_PRESECONDARY) { continue; }
		advanceStackStage();

		// special behavior if the teammate is dead: (cannot compute secondary effects)
		if (!getPKV().isAlive()) { stackStage[iBase] = STAGE_POSTTURN; continue; }

		// does this move even have a secondary effect? (this check is in-loop because multiple environments could arise from previous call)
		if (!mostlyGT(cMove.getSecondaryAccuracy(), 0.0)) { stackStage[iBase] = STAGE_POSTSECONDARY; continue; }

		fpType& secondaryHitProbability = getDamageComponent().tProbability;

		/* probability to inflict secondary condition*/
		secondaryHitProbability = cMove.getSecondaryAccuracy(); // lowest is 10%

		// to-hit modifying values:
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYSECONDARYPROBABILITY, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), secondaryHitProbability);
	} // endOf calculate secondary probability

	// split environments based on their secondary chance:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYSECONDARYHITCHANCE) { continue; }
		advanceStackStage();

		boost::array<size_t, 2> iREnv = {{ getIBase() , SIZE_MAX }};

		fpType& secondaryHitProbability = getDamageComponent().tProbability;

		secondaryHitProbability = std::max(std::min(secondaryHitProbability, (fpType)1.0), (fpType)0.0);

		// did the ability hit its target? Is it possible for the secondary ability to miss?
		if (getBase().hasHit(iCTeam) && (mostlyGT(secondaryHitProbability, 0.0)))
		{
			// if there's a chance the secondary effect will not occur:
			if (mostlyLT(secondaryHitProbability, 1.0))
			{
				// duplicate the environment (duplicated environment is the secondary effect missed):
				duplicateState(iREnv, (1.0 - secondaryHitProbability));
			}

			// modify bitmask as secondary effect occuring:
			getStack()[iREnv[0]].setSecondary(iCTeam);

		} // end of primary attack hits, and secondary attack is not assured
		else
		{
			// pass-through: no chance to secondary
			stackStage[iBase] = STAGE_POSTSECONDARY;
			continue;
		}
	}

	// calculate effect of secondary, if it occured:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_SECONDARY) { continue; }
		advanceStackStage();

		// add extra effects to the move, such as secondaries and trigger effects
		if (!getBase().hasSecondary(iCTeam)) { continue; }

		// parse secondary effect plugins:
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_SECONDARYEFFECT, onEvaluateMove_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV());
	} // endOf if primary and secondary attacks hit
} // endOf evaluateMove_postMove
Ejemplo n.º 27
0
bool DomConvenience::elementToVariant(const QDomElement& e,
                                      QVariant& v)
{
    bool ok = false;

    if (e.tagName() == "string")
    {
        if (e.hasAttribute("value"))
        {
            v = QVariant(e.attribute("value"));
            ok = true;
        }
        else
            qWarning("%s element without value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "int")
    {
        int base = getBase(e);

        if (e.hasAttribute("value"))
            v = QVariant(e.attribute("value").toInt(&ok, base));
        else
            qWarning("%s element without value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "uint")
    {
        int base = getBase(e);

        if (e.hasAttribute("value"))
            v = QVariant(e.attribute("value").toUInt(&ok, base));
        else
            qWarning("%s element without value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "double")
    {
        if (e.hasAttribute("value"))
            v = QVariant(e.attribute("value").toDouble(&ok));
        else
            qWarning("%s element without value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "bool")
    {
        if (e.hasAttribute("value"))
        {
            QString val = e.attribute("value");
            v = QVariant(getBoolFromString(val, ok), 0);

            if (!ok)
                qWarning("%s element with bogus value '%s'!",
                         (const char*)e.tagName(), (const char*)val);
        }
        else
            qWarning("%s element without value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "color")
    {
        QColor color = getColor(e);

        ok = color.isValid();

        v = color;

        if (!ok)
            qWarning("%s element without valid value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "pen")
    {
        int base = getBase(e);
        uint w = 0;
        Qt::PenStyle s = Qt::SolidLine;
        Qt::PenCapStyle c = Qt::SquareCap;
        Qt::PenJoinStyle j = Qt::BevelJoin;
        QColor color = getColor(e);

        if (e.hasAttribute("style"))
            s = (Qt::PenStyle)e.attribute("style").toInt(0, base);
        if (e.hasAttribute("cap"))
            c = (Qt::PenCapStyle)e.attribute("cap").toInt(0, base);
        if (e.hasAttribute("join"))
            j = (Qt::PenJoinStyle)e.attribute("join").toInt(0, base);

        ok = color.isValid();

        v = QPen(color, w, s, c, j);

        if (!ok)
            qWarning("%s element without valid value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "brush")
    {
        int base = getBase(e);
        QColor color = getColor(e);
        Qt::BrushStyle s = Qt::SolidPattern;
        if (e.hasAttribute("style"))
            s = (Qt::BrushStyle)e.attribute("style").toInt(0, base);

        ok = color.isValid();

        v = QBrush(color, s);

        if (!ok)
            qWarning("%s element without valid value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "point")
    {
        int base = getBase(e);
        bool coordOk;

        int x = 0, y = 0;
        if (e.hasAttribute("x"))
            x = e.attribute("x").toInt(&coordOk, base);

        if (e.hasAttribute("y"))
            y = e.attribute("y").toInt(&coordOk, base);

        v = QVariant(QPoint(x, y));
        ok = true;
    }
    else if (e.tagName() == "rect")
    {
        int base = getBase(e);
        bool coordOk;

        int x = 0, y = 0, width = 0, height = 0;
        if (e.hasAttribute("x"))
            x = e.attribute("x").toInt(&coordOk, base);

        if (e.hasAttribute("y"))
            y = e.attribute("y").toInt(&coordOk, base);

        if (e.hasAttribute("width"))
            width = e.attribute("width").toInt(&coordOk, base);

        if (e.hasAttribute("height"))
            height = e.attribute("height").toInt(&coordOk, base);

        v = QVariant(QRect(x, y, width, height));
        ok = true;
    }
    else if (e.tagName() == "size")
    {
        int base = getBase(e);
        bool coordOk;

        int width = 0, height = 0;
        if (e.hasAttribute("width"))
            width = e.attribute("width").toInt(&coordOk, base);

        if (e.hasAttribute("height"))
            height = e.attribute("height").toInt(&coordOk, base);

        v = QVariant(QSize(width, height));
        ok = true;
    }
    else if (e.tagName() == "key")
    {
        int key;
        if (e.hasAttribute("sequence"))
        {
            key = QAccel::stringToKey(e.attribute("sequence"));

            // fix the key code (deal with Qt brain death)
            key &= ~Qt::UNICODE_ACCEL;

            v = QVariant(QKeySequence(key));
            ok = true;
        }
    }
    else if (e.tagName() == "font")
    {
        QFont f;
        bool boolOk;

        if (e.hasAttribute("family"))
            f.setFamily(e.attribute("family"));
        if (e.hasAttribute("pointsize"))
            f.setPointSize(e.attribute("pointsize").toInt());
        if (e.hasAttribute("bold"))
            f.setBold(getBoolFromString(e.attribute("bold"), boolOk));
        if (e.hasAttribute("italic"))
            f.setItalic(getBoolFromString(e.attribute("italic"), boolOk));
        if (e.hasAttribute("strikeout"))
            f.setStrikeOut(getBoolFromString(e.attribute("strikeout"), boolOk));

        v = QVariant(f);
        ok = true;
    }
    else if (e.tagName() == "sizepolicy")
    {
        QSizePolicy sp;

        if (e.hasAttribute("hsizetype"))
            sp.setHorData((QSizePolicy::SizeType)e.attribute("hsizetype").toInt());
        if (e.hasAttribute("vsizetype"))
            sp.setVerData((QSizePolicy::SizeType)e.attribute("vsizetype").toInt());
        if (e.hasAttribute("horstretch"))
            sp.setHorStretch(e.attribute("horstretch").toInt());
        if (e.hasAttribute("verstretch"))
            sp.setHorStretch(e.attribute("verstretch").toInt());
        v = QVariant(sp);
        ok = true;
    }
    else if (e.tagName() == "cursor")
    {
        if (e.hasAttribute("shape"))
            v = QVariant(QCursor(e.attribute("shape").toInt(&ok, 10)));
        else
            qWarning("%s element without value!", (const char*)e.tagName());
    }
    else if (e.tagName() == "stringlist")
    {
        QDomNodeList stringNodeList = e.elementsByTagName("string");
        QStringList stringList;
        QDomElement stringElement;

        for (uint i = 0; i < stringNodeList.length(); i++)
        {
            stringElement = stringNodeList.item(i).toElement();
            if (!stringElement.hasAttribute("value"))
            {
                qWarning("%s element in %s without value! Ignoring!",
                         (const char*)stringElement.tagName(),
                         (const char*)e.tagName());
                continue;
            }

            stringList.append(e.attribute("value"));
        }

        v = stringList;

        ok = true;
    }
    else if (e.tagName() == "uint64")
    {
        QString value = e.attribute("value");

        // borrowed more or less from Qt 3.2 (since we have to support older)
        uint64_t val = 0;
        const QChar* p = value.unicode();
        int l = value.length();
        const uint64_t max_mult = UINT64_MAX / 16;

        if (!p)
        {
            qWarning("Invalid value for tag: %s", (const char*)e.tagName());
            return false;
        }

        while ( l && p->isSpace() )                 // skip leading space
            l--,p++;
        if ( !l )
            return false;
        if ( *p == '+' )
            l--,p++;

        if ( !l || !ok_in_hex(*p) )
            return false;
        while ( l && ok_in_hex(*p) )
        {
            l--;
            uint dv;
            if ( p->isDigit() )
                dv = p->digitValue();
            else
            {
                if ( *p >= 'a' && *p <= 'f' )
                    dv = *p - 'a' + 10;
                else
                    dv = *p - 'A' + 10;
            }
            if ( val > max_mult || (val == max_mult && dv > UINT64_MAX % 16) )
                return false;
            val = 16 * val + dv;
            p++;
        }

        QByteArray ba;
        ba.duplicate((const char*)&val, sizeof(uint64_t));

        v = ba;
        ok = true;
    }
    else if (e.tagName() == "list")
    {
        qWarning("Unimplemented tag: %s", (const char*)e.tagName());
    }
    else if (e.tagName() == "map")
    {
        qWarning("Unimplemented tag: %s", (const char*)e.tagName());
    }
    else
    {
        qWarning("Unknown tag: %s", (const char*)e.tagName());
    }

    return ok;
}
Ejemplo n.º 28
0
void pkCU::evaluateMove_damage()
{
	assert(getStackStage() == STAGE_MOVEBASE);
	assert(getTPKV().isAlive() && getPKV().isAlive());

	// the floor of the stack: everything below this stack value has been evaluated
	size_t baseFloor = iBase, baseCeil = getStack().size();

	const pokemon_nonvolatile& cPKNV = getPKNV();
	const pokemon_nonvolatile& tPKNV = getTPKNV();
	const move_nonvolatile& cMNV = cPKNV.getMove(getICAction());
	const pokemon_base& cPKB = cPKNV.getBase();
	const pokemon_base& tPKB = tPKNV.getBase();
	const move& cMove = cMNV.getBase();
	
	//Source: http://www.smogon.com/dp/articles/damage_formula

	/*BasePower = HH × BP × IT × CHG × (MS × WS) × UA × FA*/
	// set basePower:
	//for (/*iBase = baseFloor, baseCeil = getStack().size()*/; iBase != baseCeil; ++iBase)
	{
		//if (getStackStage() != STAGE_MOVEBASE) { continue; }
		advanceStackStage();

		uint32_t& basePower = getDamageComponent().damage;
		basePower = cMove.getPower();

		int result = (basePower != UINT8_MAX)?1:0;
		CALLPLUGIN(result, PLUGIN_ON_SETBASEPOWER, onSetPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), basePower);

		assert(result > 0 && basePower > 0);
	}

	// calculate this move's type:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_SETBASEPOWER) { continue; }
		advanceStackStage();

		const type*& cType = getDamageComponent().mType;
		cType = &cMove.getType();

		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_SETMOVETYPE, onModifyMoveType_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), cType);
	}

	// modify basePower:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_SETMOVETYPE) { continue; }
		advanceStackStage();

		uint32_t& basePower = getDamageComponent().damage;
		fpType baseModifier = 1.0;

		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYBASEPOWER, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), baseModifier);

		basePower = (uint32_t)(basePower * baseModifier);
	}

	// calculate attack and damage modifiers:
	uint32_t levelModifier = ((cPKNV.getLevel() * 2) / 5) + 2;
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYBASEPOWER) { continue; }
		advanceStackStage();

		damageComponents_t& cDamage = getDamageComponent();

		size_t attackType;
		size_t defenseType;
		if (cMove.getDamageType() == ATK_PHYSICAL)
		{ attackType = FV_ATTACK; defenseType = FV_DEFENSE; }
		else
		{ attackType = FV_SPATTACK; defenseType = FV_SPDEFENSE; }

		uint32_t attackPower = getTMV().cGetFV_boosted(cPKNV, attackType);
		uint32_t attackPowerCrit = std::max(cPKNV.getFV_base(attackType), attackPower);

		uint32_t defensePower = getTTMV().cGetFV_boosted(tPKNV, defenseType);
		uint32_t defensePowerCrit = std::min(tPKNV.getFV_base(defenseType), defensePower);

		// calculate crit first:
		cDamage.damageCrit = ((levelModifier * cDamage.damage * attackPowerCrit) / 50) / defensePowerCrit;
		// and regular damage:
		cDamage.damage = ((levelModifier * cDamage.damage * attackPower) / 50) / defensePower;


		/* Mod1 = BRN × RL × TVT × SR × FF */
		// modifier1:
		fpType attackPowerModifier = 1.0;

		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYATTACKPOWER, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), attackPowerModifier);

		// incorporate attack power modifier:
		cDamage.damage = (uint32_t)(cDamage.damage * attackPowerModifier) + 2;
		cDamage.damageCrit = (uint32_t)(cDamage.damageCrit * attackPowerModifier) + 2;
	}

	// calculate critical hit modifiers:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYATTACKPOWER) { continue; }
		advanceStackStage();

		damageComponents_t& cDamage = getDamageComponent();

		/* CH - Critical Hit modifier
			3 if has sniper ability AND critical hit (mult 1.5)
			2 if critical hit (mult 1.0)
			1 else
		 */
		fpType criticalHitModifier = 2.0;
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYCRITICALPOWER, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), criticalHitModifier);

		// incorporate critical power modifier:
		cDamage.damageCrit = (uint32_t)(cDamage.damageCrit * criticalHitModifier);
	}

	// calculate raw damage modifiers:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYCRITICALPOWER) { continue; }
		advanceStackStage();

		damageComponents_t& cDamage = getDamageComponent();

		/* Mod2 = Other modifier
			1.3 if item = life orb
			1+.1*n if item = metronome and used the same move n previous times, to a max of n=10
			1.5 if attacking with Me First and attacks first (NOTE: SPECIAL BEHAVIOR with life orb / metronome!)
			1 else
		 */
		fpType rawDamageMultiplier = 1.0;
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYRAWDAMAGE, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), rawDamageMultiplier);

		// incorporate critical power modifier:
		cDamage.damage = (uint32_t)(cDamage.damage * rawDamageMultiplier);
		cDamage.damageCrit = (uint32_t)(cDamage.damageCrit * rawDamageMultiplier);
	}

	// calculate this move's STAB:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYRAWDAMAGE) { continue; }
		advanceStackStage();

		damageComponents_t& cDamage = getDamageComponent();

		bool hasStab = ((&cPKB.getType(0) == cDamage.mType) || (&cPKB.getType(1) == cDamage.mType));
		fpType STABMultiplier = hasStab?1.5:1.0;
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYSTAB, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), STABMultiplier);

		// incorporate STAB modifier:
		cDamage.damage = (uint32_t)(cDamage.damage * STABMultiplier);
		cDamage.damageCrit = (uint32_t)(cDamage.damageCrit * STABMultiplier);
	}

	// calculate the enemy pokemon's type resistance:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYSTAB) { continue; }
		advanceStackStage();

		damageComponents_t& cDamage = getDamageComponent();

		fpType typeModifier = 1.0;
		{
			// type1:
			typeModifier *= cDamage.mType->getModifier(tPKB.getType(0));
			// type 2:
			typeModifier *= cDamage.mType->getModifier(tPKB.getType(1));
		}
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_SETDEFENSETYPE, onModifyTypePower_rawType, 
			*this, cMNV, cPKNV, tPKNV, *cDamage.mType, getTMV(), getTTMV(), getPKV(), getTPKV(), typeModifier);

		// incorporate type modifier:
		cDamage.damage = (uint32_t)(cDamage.damage * typeModifier);
		cDamage.damageCrit = (uint32_t)(cDamage.damageCrit * typeModifier);
	}

	// calculate item resistance modifiers:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYTYPERESISTANCE) { continue; }
		advanceStackStage();

		damageComponents_t& cDamage = getDamageComponent();

		/* Mod3 = SRF × EB × TL × TRB */
		fpType itemModifier = 1.0;
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYITEMPOWER, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), itemModifier);

		// incorporate type modifier:
		cDamage.damage = (uint32_t)(cDamage.damage * itemModifier);
		cDamage.damageCrit = (uint32_t)(cDamage.damageCrit * itemModifier);
	}

	/* Damage Formula = (((((((Level × 2 ÷ 5) + 2) × BasePower × [Sp]Atk ÷ 50) ÷ [Sp]Def) × Mod1) + 2) × CH × Mod2 × R ÷ 100) × STAB × Type1 × Type2 × Mod3 */

	// calculate probability to hit, miss:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYITEMPOWER) { continue; }
		advanceStackStage();

		fpType& probabilityToHit = getDamageComponent().tProbability;

		/* probability to hit enemy pokemon */
		probabilityToHit = 
				getTMV().cGetAccuracy_boosted(FV_ACCURACY) // lowest is 33% or 1/3
				* getTTMV().cGetAccuracy_boosted(FV_EVASION) // highest is 300% or 3
				* cMove.getPrimaryAccuracy(); // lowest is 30%

		// to-hit modifying values:
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYHITPROBABILITY, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), probabilityToHit);

	}

	// evaluate miss(1), hit(0):
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYHITCHANCE) { continue; }
		advanceStackStage();

		fpType& probabilityToHit = getDamageComponent().tProbability;

		// bound at MIN 0.033~ ... MAX 1.0
		probabilityToHit = std::max(std::min(probabilityToHit, (fpType)1.0), (fpType)0.0);

		boost::array<size_t, 2> iHEnv = {{ getIBase(), SIZE_MAX }};
		// did the move hit its target? Is it possible for the move to miss?
		if (mostlyGT(probabilityToHit, 0.0))
		{
			// if there's a chance the primary effect will not occur:
			if (mostlyLT(probabilityToHit, 1.0))
			{
				// duplicate the environment (duplicated environment is the miss environment):
				duplicateState(iHEnv, (1.0 - probabilityToHit));
			}

			// modify bitmask as the hit effect occuring:
			getStack()[iHEnv[0]].setHit(getICTeam());

		} // end of primary attack hits, and secondary attack is not assured
		else
		{
			// pass-through: no chance to hit or crit
			stackStage[iBase] = STAGE_POSTDAMAGE;
		}
	}

	// calculate probability to crit:
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_EVALUATEHITCHANCE) { continue; }
		advanceStackStage();

		// don't continue to evaluate a stage that has not hit the enemy team:
		if (!getBase().hasHit(getICTeam())) { stackStage[iBase] = STAGE_POSTDAMAGE; continue; }

		fpType& probabilityToCrit = getDamageComponent().tProbability;

		/* Probability to critical hit, if the move has already hit */
		probabilityToCrit = 
			getTMV().cGetAccuracy_boosted(FV_CRITICALHIT);

		// to-crit modifying values:
		int result = 0;
		CALLPLUGIN(result, PLUGIN_ON_MODIFYCRITPROBABILITY, onModifyPower_rawType, 
			*this, cMNV, cPKNV, tPKNV, getTMV(), getTTMV(), getPKV(), getTPKV(), probabilityToCrit);
	}

	// evaluate crit(2):
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_MODIFYCRITCHANCE) { continue; }
		advanceStackStage();

		fpType& probabilityToCrit = getDamageComponent().tProbability;

		// determine the possibility that the move crit:
		boost::array<size_t, 2> iCEnv = {{ SIZE_MAX, getIBase() }};
		
		if (mostlyGT(probabilityToCrit, 0.0) )
		{
			if (mostlyLT(probabilityToCrit, 1.0))
			{
				// duplicate the environment (duplicated environment is the crit environment):
				duplicateState(iCEnv, probabilityToCrit);
			}

			// modify bitmask as the crit effect occuring:
			getStack()[iCEnv[1]].setCrit(getICTeam());
		}
		// even with no chance to crit there's still the possibility of damage
	}

	// perform actual damage calculation
	for (iBase = baseFloor, baseCeil = getStack().size(); iBase != baseCeil; ++iBase)
	{
		if (getStackStage() != STAGE_PREDAMAGE) { continue; }
		advanceStackStage();

		if (!getBase().hasHit(getICTeam())) { continue; }

		calculateDamage(getBase().hasCrit(getICTeam()));
	}
} // end of evaluateMove_damage
Ejemplo n.º 29
0
Atom Stubs::do_abc_callproplex(MethodFrame* f, const Multiname* name, int argc,
                               Atom* args) {
  Atom base = getBase(args);
  Toplevel* t = toplevel(f);
  return t->callproperty(base, name, argc - 1, args, toVTable(t, base));
}
Ejemplo n.º 30
0
//03
void lod ()
{
    sp++;
    stack[sp] = stack[getBase(ir.l, bp) + ir.m];
}