DriftCorrect::DriftCorrect(const HiCalConf &conf) : NonLinearLSQ(), Component("DriftCorrect") { DbProfile prof = conf.getMatrixProfile(); _history.add("Profile["+ prof.Name()+"]"); _timet.setBin(ToInteger(prof("Summing"))); _timet.setLineTime(ToDouble(prof("ScanExposureDuration"))); _skipFit = IsEqual(ConfKey(prof, "ZdSkipFit", std::string("TRUE")), "TRUE"); _useLinFit = IsTrueValue(prof, "ZdOnFailUseLinear"); _absErr = ConfKey(prof, "AbsoluteError", 1.0E-4); _relErr = ConfKey(prof, "RelativeError", 1.0E-4); _sWidth = ConfKey(prof, "GuessFilterWidth", 17); _sIters = ConfKey(prof, "GuessFilterIterations", 1); if ( prof.exists("MaximumIterations") ) { setMaxIters(ToInteger(prof("MaximumIterations"))); } _maxLog = ConfKey(prof, "MaximumLog", 709.0); _badLines = ToInteger(prof("TrimLines"))/ToInteger(prof("Summing")); _minLines = ConfKey(prof,"ZdMinimumLines", 100); string histstr = "DriftCorrect(AbsErr[" + ToString(_absErr) + "],RelErr[" + ToString(_relErr) + "],MaxIter[" + ToString(maxIters()) + "])"; _history.add(histstr); }
ejsval _ejs_op_bitwise_or (ejsval lhs, ejsval rhs) { int lhs_int = ToInteger(lhs); int rhs_int = ToInteger(rhs); return NUMBER_TO_EJSVAL (lhs_int | rhs_int); }
ejsval _ejs_stream_end (ejsval env, ejsval _this, uint32_t argc, ejsval* args) { ejsval internal_fd = _ejs_object_getprop_utf8 (_this, "%internal_fd"); close (ToInteger(internal_fd)); return _ejs_undefined; }
ejsval _ejs_stream_write (ejsval env, ejsval _this, uint32_t argc, ejsval* args) { ejsval to_write = ToString(args[0]); ejsval internal_fd = _ejs_object_getprop_utf8 (_this, "%internal_fd"); int fd = ToInteger(internal_fd); int remaining = EJSVAL_TO_STRLEN(to_write); int offset = 0; char *buf = ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(to_write)); do { int num_written = write (fd, buf + offset, remaining); if (num_written == -1) { if (errno == EINTR) continue; perror ("write"); free (buf); return _ejs_false; } remaining -= num_written; offset += num_written; } while (remaining > 0); free (buf); return _ejs_true; }
bool String::ToBoolean() const { if(ToInteger() == 1 || !ICompare("true")) return true; return false; }
/// /// return success flag /// bool HuberPetiteFleur::SetCirculatorOn( void ) const { #ifdef __HUBERPETITEFLEUR_DEBUG std::cout << "[HuberPetiteFleur::SetCirculatorOn] -- DEBUG: Called." << std::endl; #endif char buffer[1000]; usleep( uDelay_ ); comHandler_->SendCommand( "CA@ +00001" ); usleep( uDelay_ ); comHandler_->ReceiveString( buffer ); StripBuffer( buffer ); int status = ToInteger(buffer); if( status != 1 ) { std::cerr << " [HuberPetiteFleur::SetCirculatorOn] ** ERROR: check failed." << std::endl; std::cerr << " > Expected: ON (1) but received (string):" << buffer << "." << std::endl; return false; } return true; }
/// /// returns success flag /// bool HuberPetiteFleur::SetWorkingTemperature( const float workingTemp ) const { #ifdef __HUBERPETITEFLEUR_DEBUG std::cout << "[HuberPetiteFleur::SetWorkingTemp] -- DEBUG: Called." << std::endl; #endif if( workingTemp > PetiteFleurUpperTempLimit || workingTemp < PetiteFleurLowerTempLimit ) { std::cerr << " [HuberPetiteFleur::SetWorkingTemp] ** ERROR: working temp T=" << workingTemp << " exceeds soft limits." << std::endl; std::cerr << " > (s. HuberPetiteFleur class definition)" << std::endl; return false; } char buffer[1000]; int iTemp = workingTemp * 100.; sprintf(buffer, "%+06d", iTemp); std::stringstream theCommand; theCommand << "SP@ " << buffer; comHandler_->SendCommand( theCommand.str().c_str() ); usleep( uDelay_ ); memset( buffer, 0, sizeof( buffer ) ); comHandler_->ReceiveString( buffer ); usleep( uDelay_ ); StripBuffer( buffer ); int oTemp = ToInteger( buffer ); if( iTemp != oTemp ) { std::cerr << " [HuberPetiteFleur::SetWorkingTemp] ** ERROR: check failed." << std::endl; if ( strlen( buffer ) == 0 ) std::cerr << " > Got no reply. (timeout?)" << std::endl; else std::cerr << " > Expected: T=" << workingTemp << " but received T=" << oTemp / 100 << std::endl; return false; } return true; }
/* ======================== idSWFScriptVar::PrintToConsole ======================== */ void idSWFScriptVar::PrintToConsole() const { idLib::Printf( "Object type: %s\n", TypeOf() ); if( IsObject() ) { GetObject()->PrintToConsole(); } else if( IsNumeric() ) { idLib::Printf( "%d\n", ToInteger() ); } else if( IsString() ) { idLib::Printf( "%s\n", ToString().c_str() ); } else { idLib::Printf( "unknown\n" ); } }
/// /// true = on / false = off /// bool HuberPetiteFleur::GetCirculatorStatus( void ) const { #ifdef __HUBERPETITEFLEUR_DEBUG std::cout << "[HuberPetiteFleur::GetCirculatorStatus] -- DEBUG: Called." << std::endl; #endif char buffer[1000]; usleep( uDelay_ ); comHandler_->SendCommand( "CA?" ); usleep( uDelay_ ); comHandler_->ReceiveString( buffer ); StripBuffer( buffer ); int status = ToInteger(buffer); //std::cout << buffer << std::endl; if( status>0 ) return true; else return false; }
PrimitiveTypeMapCache() { // if we create the TypeMap as a static function member, the constructor // is guarantueed to be called by only one thread (see C++11 standard sec 6.7) // while all other threads wait for completion. Thus no manual synchronization // is needed for the initialization. // create all type mappers /* convert primitive types */ #define CONVERT_NUMBER(NAME, TYPE, PRED, CONV) \ { \ func_t f = [](const Local<Value>& val) \ -> std::tuple<size_t, void*, cl_int> { \ if (!val->PRED()){ \ return std::tuple<size_t, void*,cl_int>(0, NULL, CL_INVALID_ARG_VALUE);\ } \ void* ptr_data = new TYPE; \ size_t ptr_size = sizeof(TYPE); \ *((TYPE *)ptr_data) = val->CONV(); \ return std::tuple<size_t, void*,cl_int>(ptr_size, ptr_data, 0); \ }; \ m_converters[NAME] = f; \ } CONVERT_NUMBER("char", cl_char, IsInt32, ToInt32()->Value); CONVERT_NUMBER("uchar", cl_uchar, IsInt32, ToUint32()->Value); CONVERT_NUMBER("short", cl_short, IsInt32, ToInt32()->Value); CONVERT_NUMBER("ushort", cl_ushort, IsInt32, ToUint32()->Value); CONVERT_NUMBER("int", cl_int , IsInt32, ToInt32()->Value); CONVERT_NUMBER("uint", cl_uint, IsInt32, ToUint32()->Value); CONVERT_NUMBER("long", cl_long, IsNumber, ToInteger()->Value); CONVERT_NUMBER("ulong", cl_ulong, IsNumber, ToInteger()->Value); CONVERT_NUMBER("float", cl_float, IsNumber, NumberValue); CONVERT_NUMBER("double", cl_double, IsNumber, NumberValue); CONVERT_NUMBER("half", cl_half, IsNumber, NumberValue); #undef CONVERT_NUMBER /* convert vector types (e.g. float4, int16, etc) */ #define CONVERT_VECT(NAME, TYPE, I, PRED, COND) \ { \ func_t f = [](const Local<Value>& val) \ -> std::tuple<size_t, void*, cl_int> { \ if (!val->IsArray()) { \ /*THROW_ERR(CL_INVALID_ARG_VALUE); */ \ return std::tuple<size_t,void*,cl_int>(0, NULL, CL_INVALID_ARG_VALUE);\ } \ Local<Array> arr = Local<Array>::Cast(val); \ if (arr->Length() != I) { \ /*THROW_ERR(CL_INVALID_ARG_SIZE);*/ \ return std::tuple<size_t,void*,cl_int>(0, NULL, CL_INVALID_ARG_SIZE); \ } \ TYPE * vvc = new TYPE[I]; \ size_t ptr_size = sizeof(TYPE) * I; \ void* ptr_data = vvc; \ for (unsigned int i = 0; i < I; ++ i) { \ if (!arr->Get(i)->PRED()) { \ /*THROW_ERR(CL_INVALID_ARG_VALUE);*/ \ /*THROW_ERR(CL_INVALID_ARG_VALUE);*/ \ return std::tuple<size_t,void*,cl_int>(0, NULL, CL_INVALID_ARG_VALUE);\ } \ vvc[i] = arr->Get(i)->COND(); \ } \ return std::tuple<size_t,void*,cl_int>(ptr_size, ptr_data, 0); \ }; \ m_converters["NAME ## I"] = f; \ } #define CONVERT_VECTS(NAME, TYPE, PRED, COND) \ CONVERT_VECT(NAME, TYPE, 2, PRED, COND);\ CONVERT_VECT(NAME, TYPE, 3, PRED, COND);\ CONVERT_VECT(NAME, TYPE, 4, PRED, COND);\ CONVERT_VECT(NAME, TYPE, 8, PRED, COND);\ CONVERT_VECT(MAME, TYPE, 16, PRED, COND); CONVERT_VECTS("char", cl_char, IsInt32, ToInt32()->Value); CONVERT_VECTS("uchar", cl_uchar, IsInt32, ToUint32()->Value); CONVERT_VECTS("short", cl_short, IsInt32, ToInt32()->Value); CONVERT_VECTS("ushort", cl_ushort, IsInt32, ToUint32()->Value); CONVERT_VECTS("int", cl_int, IsInt32, ToInt32()->Value); CONVERT_VECTS("uint", cl_uint, IsInt32, ToUint32()->Value); CONVERT_VECTS("long", cl_long, IsNumber, ToInteger()->Value); CONVERT_VECTS("ulong", cl_ulong, IsNumber, ToInteger()->Value); CONVERT_VECTS("float", cl_float, IsNumber, NumberValue); CONVERT_VECTS("double", cl_double, IsNumber, NumberValue); CONVERT_VECTS("half", cl_half, IsNumber, NumberValue); #undef CONVERT_VECT #undef CONVERT_VECTS // add boolean conversion m_converters["bool"] = [](const Local<Value>& val) { size_t ptr_size = sizeof(cl_bool); void* ptr_data = new cl_bool; *((cl_bool *)ptr_data) = val->BooleanValue() ? 1 : 0; return std::tuple<size_t,void*,cl_int>(ptr_size, ptr_data, 0); }; }
long GBStackBrain::PopInteger() { return ToInteger(Pop()); }
uint8_t Strings::ToU8(const UString &s) { return static_cast<uint8_t>(ToInteger(s)); }
/* ======================== idSWFScriptVar::AbstractEquals ======================== */ bool idSWFScriptVar::AbstractEquals( const idSWFScriptVar& other ) { if( type == other.type ) { switch( type ) { case SWF_VAR_STRINGID: return ( value.i == other.value.i ); case SWF_VAR_STRING: return ( *value.string == *other.value.string ); case SWF_VAR_FLOAT: return ( value.f == other.value.f ); case SWF_VAR_BOOL: return ( value.b == other.value.b ); case SWF_VAR_INTEGER: return ( value.i == other.value.i ); case SWF_VAR_NULL: return true; case SWF_VAR_UNDEF: return true; case SWF_VAR_OBJECT: return ( value.object == other.value.object ); case SWF_VAR_FUNCTION: return ( value.function == other.value.function ); default: assert( false ); return false; } } switch( type ) { case SWF_VAR_STRINGID: return ToString() == other.ToString(); case SWF_VAR_STRING: switch( other.type ) { case SWF_VAR_STRINGID: return *value.string == other.ToString(); case SWF_VAR_FLOAT: return ToFloat() == other.value.f; case SWF_VAR_BOOL: return ToBool() == other.value.b; case SWF_VAR_INTEGER: return ToInteger() == other.value.i; case SWF_VAR_OBJECT: return *value.string == other.ToString(); default: return false; } case SWF_VAR_FLOAT: return ( other.ToFloat() == value.f ); case SWF_VAR_BOOL: return ( other.ToBool() == value.b ); case SWF_VAR_INTEGER: return ( other.ToInteger() == value.i ); case SWF_VAR_NULL: return ( other.type == SWF_VAR_UNDEF ); case SWF_VAR_UNDEF: return ( other.type == SWF_VAR_NULL ); case SWF_VAR_OBJECT: switch( other.type ) { case SWF_VAR_STRING: return ToString() == *other.value.string; case SWF_VAR_FLOAT: return ToFloat() == other.value.f; case SWF_VAR_BOOL: return ToBool() == other.value.b; case SWF_VAR_INTEGER: return ToInteger() == other.value.i; default: return false; } case SWF_VAR_FUNCTION: return false; default: assert( false ); return false; } }
void GBStackBrain::WriteHardware(const GBSymbolIndex index, const GBStackDatum value, GBRobot * robot, GBWorld *) { switch ( index ) { case hvTime: case hvTimeLimit: case hvWorldWidth: case hvWorldHeight: case hvRadius: case hvMass: case hvSpeed: case hvProcessor: case hvRemaining: case hvSideID: case hvTypeID: case hvRobotID: case hvParentID: case hvPopulation: throw GBReadOnlyError(); case hvEnginePower: robot->hardware.SetEnginePower(value); break; case hvFlag: robot->flag = value; break; case hvEngineMaxPower: case hvCollision: case hvFriendlyCollision: case hvEnemyCollision: case hvFoodCollision: case hvShotCollision: case hvWallCollision: throw GBReadOnlyError(); // energy case hvEnergy: case hvMaxEnergy: case hvSolarCells: case hvEater: case hvEaten: case hvSyphonMaxRate: case hvSyphonRange: case hvSyphoned: throw GBReadOnlyError(); case hvSyphonDistance: robot->hardware.syphon.SetDistance(value); break; case hvSyphonDirection: robot->hardware.syphon.SetDirection(value); break; case hvSyphonRate: robot->hardware.syphon.SetRate(value); break; case hvEnemySyphonMaxRate: case hvEnemySyphonRange: case hvEnemySyphoned: throw GBReadOnlyError(); case hvEnemySyphonDistance: robot->hardware.enemySyphon.SetDistance(value); break; case hvEnemySyphonDirection: robot->hardware.enemySyphon.SetDirection(value); break; case hvEnemySyphonRate: robot->hardware.enemySyphon.SetRate(value); break; // constructor case hvConstructorType: { int index = ToInteger(value); robot->hardware.constructor.Start(index ? robot->Owner()->GetType(index) : nil); } break; case hvConstructorRate: robot->hardware.constructor.SetRate(value); break; case hvConstructorMaxRate: case hvConstructorProgress: case hvConstructorRemaining: case hvChildID: throw GBReadOnlyError(); // robot sensor case hvRobotSensorRange: case hvRobotSensorFiringCost: throw GBReadOnlyError(); case hvRobotSensorFocusDistance: robot->hardware.sensor1.SetDistance(value); break; case hvRobotSensorFocusDirection: robot->hardware.sensor1.SetDirection(value); break; case hvRobotSensorSeesFriends: robot->hardware.sensor1.SetSeesFriendly(value.Nonzero()); break; case hvRobotSensorSeesEnemies: robot->hardware.sensor1.SetSeesEnemy(value.Nonzero()); break; case hvRobotSensorTime: case hvRobotSensorFound: case hvRobotSensorRangeFound: case hvRobotSensorAngleFound: case hvRobotSensorSideFound: case hvRobotSensorRadiusFound: case hvRobotSensorMassFound: case hvRobotSensorEnergyFound: case hvRobotSensorTypeFound: case hvRobotSensorIDFound: case hvRobotSensorShieldFractionFound: case hvRobotSensorBombFound: case hvRobotSensorReloadingFound: case hvRobotSensorRangeOverall: case hvRobotSensorAngleOverall: throw GBReadOnlyError(); case hvRobotSensorCurrentResult: robot->hardware.sensor1.SetCurrentResult(ToInteger(value)); break; case hvRobotSensorNumResults: case hvRobotSensorMaxResults: throw GBReadOnlyError(); // food sensor case hvFoodSensorRange: case hvFoodSensorFiringCost: throw GBReadOnlyError(); case hvFoodSensorFocusDistance: robot->hardware.sensor2.SetDistance(value); break; case hvFoodSensorFocusDirection: robot->hardware.sensor2.SetDirection(value); break; case hvFoodSensorTime: case hvFoodSensorFound: case hvFoodSensorRangeFound: case hvFoodSensorAngleFound: case hvFoodSensorSideFound: case hvFoodSensorRadiusFound: case hvFoodSensorMassFound: case hvFoodSensorEnergyFound: case hvFoodSensorRangeOverall: case hvFoodSensorAngleOverall: throw GBReadOnlyError(); case hvFoodSensorCurrentResult: robot->hardware.sensor2.SetCurrentResult(ToInteger(value)); break; case hvFoodSensorNumResults: case hvFoodSensorMaxResults: throw GBReadOnlyError(); // shot sensor case hvShotSensorRange: case hvShotSensorFiringCost: throw GBReadOnlyError(); case hvShotSensorFocusDistance: robot->hardware.sensor3.SetDistance(value); break; case hvShotSensorFocusDirection: robot->hardware.sensor3.SetDirection(value); break; case hvShotSensorSeesFriendly: robot->hardware.sensor3.SetSeesFriendly(value.Nonzero()); break; case hvShotSensorSeesEnemy: robot->hardware.sensor3.SetSeesEnemy(value.Nonzero()); break; case hvShotSensorTime: case hvShotSensorFound: case hvShotSensorRangeFound: case hvShotSensorAngleFound: case hvShotSensorSideFound: case hvShotSensorRadiusFound: case hvShotSensorPowerFound: case hvShotSensorRangeOverall: case hvShotSensorAngleOverall: throw GBReadOnlyError(); case hvShotSensorCurrentResult: robot->hardware.sensor3.SetCurrentResult(ToInteger(value)); break; case hvShotSensorNumResults: case hvShotSensorMaxResults: throw GBReadOnlyError(); // defenses case hvRepairRate: robot->hardware.SetRepairRate(value); break; case hvShield: robot->hardware.SetShield(value); break; case hvArmor: case hvMaxArmor: case hvMaxRepairRate: case hvMaxShield: case hvShieldFraction: throw GBReadOnlyError(); // weapons case hvBlasterDamage: case hvBlasterRange: case hvBlasterSpeed: case hvBlasterLifetime: case hvBlasterReloadTime: case hvBlasterFiringCost: case hvBlasterCooldown: case hvGrenadesDamage: case hvGrenadesRange: case hvGrenadesSpeed: case hvGrenadesLifetime: case hvGrenadesReloadTime: case hvGrenadesFiringCost: case hvGrenadesCooldown: case hvGrenadesRadius: case hvForceFieldMaxPower: case hvForceFieldRange: throw GBReadOnlyError(); case hvForceFieldDistance: robot->hardware.forceField.SetDistance(value); break; case hvForceFieldDirection: robot->hardware.forceField.SetDirection(value); break; case hvForceFieldPower: robot->hardware.forceField.SetPower(value); break; case hvForceFieldAngle: robot->hardware.forceField.SetAngle(value); break; case hvForceFieldRadius: throw GBReadOnlyError(); // default: throw GBUnknownHardwareVariableError(); } }
ejsval _ejs_op_bitwise_not (ejsval val) { int val_int = ToInteger(val); return NUMBER_TO_EJSVAL (~val_int); }
//--------------------------------------------------------------------------- void GregorianDate::ParseOut(const wxString &str) { #if DEBUG_GREGORIAN_VALIDATE //MessageInterface::ShowMessage(wxT("==> GregorianDate::ParseOut() str=%s\n"), str.c_str()); #endif // Check if non-empty string then parse out; otherwise, nothing. if (str != wxT("")) { StringTokenizer dateToken(str, wxT(" ")); if (dateToken.CountTokens() == 4) { wxString issString = (dateToken.GetToken(0)); wxStringInputStream issStringStream(issString); wxTextInputStream iss(issStringStream); Integer dayNum, yearNum; // Get the number iss >> dayNum; // Get the year yearNum = ToInteger(dateToken.GetToken(2)); // Check validity for year if (dateToken.GetToken(2).length() != 4 || yearNum < 1950) return; // throw GregorianDateException(); // Check validity for month // std::vector<wxString>::iterator pos; // pos = find(monthName.begin(),monthName.end(), // dateToken.GetToken(1)); // if (pos == monthName.end()) // return; // // throw GregorianDateException(); bool monthFound = false; Integer monthNum = 0; for (int i=0; i<12; i++) { if (GmatTimeConstants::MONTH_NAME_TEXT[i] == dateToken.GetToken(1)) { monthFound = true; monthNum = i+1; break; } } if (!monthFound) return; // Integer monthNum; // monthNum = (Integer) distance(monthName.begin(),pos) + 1; wxString tempYMD; tempYMD = dateToken.GetToken(2) + NumToString(monthNum); if (dateToken.GetToken(0).length() == 1) tempYMD += wxT("0"); tempYMD += dateToken.GetToken(0) + wxT("."); // Start with time StringTokenizer timeToken(dateToken.GetToken(3),wxT(":")); if (timeToken.CountTokens() == 3) { // // Check length of time format // if (timeToken.GetToken(0).length() != 2 || // timeToken.GetToken(1).length() != 2 || // timeToken.GetToken(2).length() != 6) // { // MessageInterface::ShowMessage( // wxT("\nWarning: invalid Gregorian format with time")); // return; // } // Check length of the hour format if (timeToken.GetToken(0).length() != 2) { MessageInterface::ShowMessage( wxT("\nWarning: invalid Gregorian time for hours format(HH)\n")); return; } // Check length of the minute format if (timeToken.GetToken(1).length() != 2) { MessageInterface::ShowMessage( wxT("\nWarning: invalid Gregorian time for minutes format(MM)\n")); return; } if (timeToken.GetToken(2).length() != 6) { MessageInterface::ShowMessage( wxT("\nWarning: invalid Gregorian time for seconds format(SS.mmm)\n")); return; } // Get hour and minute Integer hour, minute; hour = ToInteger(timeToken.GetToken(0)); minute = ToInteger(timeToken.GetToken(1)); tempYMD += timeToken.GetToken(0) + timeToken.GetToken(1); // Finally start with seconds wxString strSeconds = timeToken.GetToken(2); timeToken.Set(strSeconds,wxT(".")); // Check time format in second if (timeToken.CountTokens() != 2 || timeToken.GetToken(0).length() != 2 || timeToken.GetToken(1).length() != 3) { MessageInterface::ShowMessage( wxT("\nWarning: invalid Gregorian format with seconds")); return; } tempYMD += timeToken.GetToken(0) + timeToken.GetToken(1); // Get real number in seconds Real second = ToReal(strSeconds); #if DEBUG_GREGORIAN_VALIDATE //MessageInterface::ShowMessage // (wxT("==> GregorianDate::ParseOut() second=%.10f\n"), second); #endif // Finally check validity for the date if (!IsValidTime(yearNum,monthNum,dayNum,hour,minute,second)) { MessageInterface::ShowMessage( wxT("\nWarning: invalid Gregorian format from DateUtil")); return; } stringYMDHMS = tempYMD; //MessageInterface::ShowMessage // (wxT("==> GregorianDate::ParseOut() stringYMDHMS=%s\n"), // stringYMDHMS.c_str()); } isValid = true; }
double FitFunc() const { int toIn = ToInteger(); return sin(toIn/10.0); }
void GBStackBrain::ExecutePrimitive(GBSymbolIndex index, GBRobot * robot, GBWorld * world) { GBStackDatum temp, temp2, temp3; long tempInt; switch ( index ) { case opNop: break; // stack manipulation case opDrop: Pop(); break; case op2Drop: Pop(); Pop(); break; case opNip: temp = Pop(); Pop(); Push(temp); break; case opRDrop: PopReturn(); break; case opDropN: { int n = PopInteger(); if ( n > stackHeight ) throw GBBadArgumentError(); stackHeight -= n; } break; case opSwap: temp = Pop(); temp2 = Pop(); Push(temp); Push(temp2); break; case op2Swap: { GBVector v1 = PopVector(); GBVector v2 = PopVector(); PushVector(v1); PushVector(v2); } break; case opRotate: temp = Pop(); temp2 = Pop(); temp3 = Pop(); Push(temp2); Push(temp); Push(temp3); break; case opReverseRotate: temp = Pop(); temp2 = Pop(); temp3 = Pop(); Push(temp); Push(temp3); Push(temp2); break; case opDup: temp = Peek(); Push(temp); break; case op2Dup: temp = Peek(2); temp2 = Peek(); Push(temp); Push(temp2); break; case opTuck: temp = Pop(); temp2 = Pop(); Push(temp); Push(temp2); Push(temp); break; case opOver: temp = Peek(2); Push(temp); break; case op2Over: temp = Peek(4); temp2 = Peek(3); Push(temp); Push(temp2); break; case opStackHeight: Push(stackHeight); break; case opStackLimit: Push(kStackLimit); break; case opPick: Push(Peek(PopInteger())); break; case opToReturn: PushReturn(ToAddress(Pop())); break; case opFromReturn: Push(PopReturn()); break; // branches case opJump: pc = ToAddress(Pop()); break; case opCall: ExecuteCall(ToAddress(Pop())); break; case opReturn: pc = PopReturn(); break; case opIfGo: temp = Pop(); if ( Pop().Nonzero() ) pc = ToAddress(temp); break; case opIfElseGo: temp = Pop(); temp2 = Pop(); if ( Pop().Nonzero() ) pc = ToAddress(temp2); else pc = ToAddress(temp); break; case opIfCall: temp = Pop(); if ( Pop().Nonzero() ) ExecuteCall(ToAddress(temp)); break; case opIfElseCall: temp = Pop(); temp2 = Pop(); if ( Pop().Nonzero() ) ExecuteCall(ToAddress(temp2)); else ExecuteCall(ToAddress(temp)); break; case opIfReturn: if ( Pop().Nonzero() ) pc = PopReturn(); break; case opNotIfGo: temp = Pop(); if ( ! Pop().Nonzero() ) pc = ToAddress(temp); break; case opNotIfReturn: if ( ! Pop().Nonzero() ) pc = PopReturn(); break; case opNotIfCall: temp = Pop(); if ( ! Pop().Nonzero() ) ExecuteCall(ToAddress(temp)); break; // arithmetic case opAdd: TwoNumberToNumberOp(&GBNumber::operator +); break; case opSubtract: TwoNumberToNumberOp(&GBNumber::operator -); break; case opNegate: NumberToNumberOp(&GBNumber::operator -); break; // mult and divide are written out because of MrCpp internal error case opMultiply: temp = Pop(); Push(Pop() * temp); break; case opDivide: temp = Pop(); Push(Pop() / temp); break; case opReciprocal: Push(GBNumber(1) / Pop()); break; case opMod: TwoNumberToNumberOp(&GBNumber::Mod); break; case opRem: TwoNumberToNumberOp(&GBNumber::Rem); break; case opSqrt: NumberToNumberOp(&GBNumber::Sqrt); break; case opExponent: TwoNumberToNumberOp(&GBNumber::Exponent); break; case opIsInteger: PushBoolean(Pop().IsInteger()); break; case opFloor: Push(Pop().Floor()); break; case opCeiling: Push(Pop().Ceiling()); break; case opRound: Push(Pop().Round()); break; case opMin: TwoNumberToNumberOp(&GBNumber::Min); break; case opMax: TwoNumberToNumberOp(&GBNumber::Max); break; case opAbs: NumberToNumberOp(&GBNumber::Abs); break; case opSignum: NumberToNumberOp(&GBNumber::Signum); break; case opReorient: NumberToNumberOp(&GBNumber::Reorient); break; case opSine: NumberToNumberOp(&GBNumber::Sin); break; case opCosine: NumberToNumberOp(&GBNumber::Cos); break; case opTangent: NumberToNumberOp(&GBNumber::Tan); break; case opArcSine: NumberToNumberOp(&GBNumber::ArcSin); break; case opArcCosine: NumberToNumberOp(&GBNumber::ArcCos); break; case opArcTangent: NumberToNumberOp(&GBNumber::ArcTan); break; case opRandom: temp = Pop(); Push(world->Randoms().InRange(Pop(), temp)); break; case opRandomAngle: Push(world->Randoms().Angle()); break; case opRandomInt: temp = Pop(); Push(world->Randoms().LongInRange(Pop().Ceiling(), temp.Floor())); break; case opRandomBoolean: PushBoolean(world->Randoms().Boolean(Pop())); break; // constants case opPi: Push(GBNumber::pi); break; case op2Pi: Push(GBNumber::pi * 2); break; case opPiOver2: Push(GBNumber::pi / 2); break; case opE: Push(GBNumber::e); break; case opEpsilon: Push(GBNumber::epsilon); break; case opInfinity: Push(GBNumber::infinity); break; // vector operations case opRectToPolar: { GBVector v = PopVector(); Push(v.Norm()); Push(v.Angle()); } break; case opPolarToRect: temp = Pop(); temp2 = Pop(); PushVector(GBFinePoint::MakePolar(temp2, temp)); break; case opVectorAdd: TwoVectorToVectorOp(&GBFinePoint::operator +); break; case opVectorSubtract: TwoVectorToVectorOp(&GBFinePoint::operator -); break; case opVectorNegate: VectorToVectorOp(&GBFinePoint::operator -); break; case opVectorScalarMultiply: temp = Pop(); PushVector(PopVector() * temp); break; case opVectorScalarDivide: temp = Pop(); PushVector(PopVector() / temp); break; case opVectorNorm: VectorToScalarOp(&GBFinePoint::Norm); break; case opVectorAngle: VectorToScalarOp(&GBFinePoint::Angle); break; case opDotProduct: TwoVectorToScalarOp(&GBFinePoint::DotProduct); break; case opProject: TwoVectorToVectorOp(&GBFinePoint::Projection); break; case opCross: TwoVectorToScalarOp(&GBFinePoint::Cross); break; case opUnitize: VectorToVectorOp(&GBFinePoint::Unit); break; case opDistance: Push((PopVector() - PopVector()).Norm()); break; case opInRange: temp = Pop(); PushBoolean(PopVector().InRange(PopVector(), temp)); break; case opRestrictPosition: { temp = Pop(); //wall distance GBVector pos = PopVector(); Push(pos.x.Max(temp).Min(world->Size().x - temp)); Push(pos.y.Max(temp).Min(world->Size().y - temp)); } break; case opVectorEqual: PushBoolean(PopVector() == PopVector()); break; case opVectorNotEqual: PushBoolean(PopVector() != PopVector()); break; // comparisons case opEqual: PushBoolean(Pop() == Pop()); break; case opNotEqual: PushBoolean(Pop() != Pop()); break; case opLessThan: temp = Pop(); PushBoolean(Pop() < temp); break; case opLessThanOrEqual: temp = Pop(); PushBoolean(Pop() <= temp); break; case opGreaterThan: temp = Pop(); PushBoolean(Pop() > temp); break; case opGreaterThanOrEqual: temp = Pop(); PushBoolean(Pop() >= temp); break; // booleans case opNot: PushBoolean(! Pop().Nonzero()); break; case opAnd: temp = Pop(); temp2 = Pop(); PushBoolean(temp.Nonzero() && temp2.Nonzero()); break; case opOr: temp = Pop(); temp2 = Pop(); PushBoolean(temp.Nonzero() || temp2.Nonzero()); break; case opXor: temp = Pop(); temp2 = Pop(); PushBoolean(temp.Nonzero() && ! temp2.Nonzero() || ! temp.Nonzero() && temp2.Nonzero()); break; case opNand: temp = Pop(); temp2 = Pop(); PushBoolean(! (temp.Nonzero() && temp2.Nonzero())); break; case opNor: temp = Pop(); temp2 = Pop(); PushBoolean(! (temp.Nonzero() || temp2.Nonzero())); break; case opValueConditional: temp = Pop(); temp2 = Pop(); if ( Pop().Nonzero() ) Push(temp2); else Push(temp); break; // misc external case opPrint: DoPrint(ToString(Pop())); if ( world->reportPrints ) NonfatalError(robot->Description() + " prints: " + *lastPrint); break; case opPrintVector: DoPrint(ToString(PopVector())); if ( world->reportPrints ) NonfatalError(robot->Description() + " prints: " + *lastPrint); break; case opBeep: StartSound(siBeep); break; case opStop: SetStatus(bsStopped); break; case opPause: if ( world->reportErrors ) world->running = false; break; case opSync: remaining = 0; break; // basic hardware case opSeekLocation: robot->EngineSeek(PopVector(), GBVector(0, 0)); break; case opSeekMovingLocation: { GBVector vel = PopVector(); robot->EngineSeek(PopVector(), vel); } break; case opDie: robot->Die(robot->Owner()); SetStatus(bsStopped); break; case opWriteLocalMemory: tempInt = PopInteger(); WriteLocalMemory(tempInt, Pop(), robot); break; case opReadLocalMemory: tempInt = PopInteger(); Push(ReadLocalMemory(tempInt, robot)); break; case opWriteLocalVector: tempInt = PopInteger(); WriteLocalMemory(tempInt + 1, Pop(), robot); WriteLocalMemory(tempInt, Pop(), robot); break; case opReadLocalVector: tempInt = PopInteger(); Push(ReadLocalMemory(tempInt, robot)); Push(ReadLocalMemory(tempInt + 1, robot)); break; case opWriteSharedMemory: tempInt = PopInteger(); robot->hardware.radio.Write(Pop(), tempInt, robot->Owner()); break; case opReadSharedMemory: Push(robot->hardware.radio.Read(PopInteger(), robot->Owner())); break; case opWriteSharedVector: tempInt = PopInteger(); robot->hardware.radio.Write(Pop(), tempInt + 1, robot->Owner()); robot->hardware.radio.Write(Pop(), tempInt, robot->Owner()); break; case opReadSharedVector: tempInt = PopInteger(); Push(robot->hardware.radio.Read(tempInt, robot->Owner())); Push(robot->hardware.radio.Read(tempInt + 1, robot->Owner())); break; case opMessagesWaiting: Push(robot->hardware.radio.MessagesWaiting(PopInteger(), robot->Owner())); break; case opSendMessage: { GBMessage sendee; tempInt = PopInteger(); //channel int numArgs = ToInteger(Pop()); //number of numbers for ( int i = 0; i < numArgs; i++ ) { sendee.AddDatum(Pop()); //higher indices in message correspond with earlier numbers in stack. :( } if ( numArgs <= 0 ) throw GBGenericError("Cannot send message of non-positive length"); robot->hardware.radio.Send(sendee, tempInt, robot->Owner()); } break; case opReceiveMessage: { tempInt = PopInteger(); const GBMessage * received = robot->hardware.radio.Receive(tempInt, robot->Owner()); if ( received == 0 ) { Push(0); } else { if ( received->Length() <= 0 ) { throw GBGenericError("non-positive length message received"); } for ( int i = received->Length() - 1; i >= 0; i-- ) Push(received->Datum(i)); Push(received->Length()); } } break; case opClearMessages: robot->hardware.radio.ClearChannel(PopInteger(), robot->Owner()); break; case opSkipMessages: tempInt = PopInteger(); robot->hardware.radio.SkipMessages(tempInt, PopInteger(), robot->Owner()); break; case opTypePopulation: { GBRobotType * theType = robot->Owner()->GetType(PopInteger()); if (theType) Push(theType->Population()); else Push(-1); } break; case opAutoConstruct: { GBConstructorState & ctor = robot->hardware.constructor; if ( robot->Energy() > robot->hardware.MaxEnergy() * .9 ) { if ( ! ctor.Type() ) ctor.Start(robot->Type()); ctor.SetRate(ctor.MaxRate()); } else ctor.SetRate(ctor.Type() && robot->Energy() > ctor.Remaining() + 10 ? ctor.MaxRate() : GBNumber(0)); } break; case opBalanceTypes: { // frac type -- GBRobotType * theType = robot->Owner()->GetType(PopInteger()); GBNumber fraction = Pop(); if (theType && GBNumber(theType->Population()) < fraction * robot->Owner()->Scores().Population()) robot->hardware.constructor.Start(theType); //FIXME don't abort? } break; // sensors case opFireRobotSensor: robot->hardware.sensor1.Fire(); break; case opFireFoodSensor: robot->hardware.sensor2.Fire(); break; case opFireShotSensor: robot->hardware.sensor3.Fire(); break; case opRobotSensorNext: Push(robot->hardware.sensor1.NextResult() ? 1 : 0); break; case opFoodSensorNext: Push(robot->hardware.sensor2.NextResult() ? 1 : 0); break; case opShotSensorNext: Push(robot->hardware.sensor3.NextResult() ? 1 : 0); break; case opPeriodicRobotSensor: FirePeriodic(robot->hardware.sensor1, world); break; case opPeriodicFoodSensor: FirePeriodic(robot->hardware.sensor2, world); break; case opPeriodicShotSensor: FirePeriodic(robot->hardware.sensor3, world); break; // weapons case opFireBlaster: robot->hardware.blaster.Fire(Pop()); break; case opFireGrenade: temp = Pop(); robot->hardware.grenades.Fire(Pop(), temp); break; case opLeadBlaster: { //pos vel -- GBVelocity vel = PopVector() - robot->Velocity(); GBPosition pos = PopVector() - robot->Position(); GBPosition target = LeadShot(pos, vel, robot->hardware.blaster.Speed(), robot->Radius()); if ( target.Nonzero() && target.Norm() <= robot->hardware.blaster.MaxRange() + robot->Radius() ) robot->hardware.blaster.Fire(target.Angle()); } break; case opLeadGrenade: { //pos vel -- GBVelocity vel = PopVector() - robot->Velocity(); GBPosition pos = PopVector() - robot->Position(); GBPosition target = LeadShot(pos, vel, robot->hardware.grenades.Speed(), robot->Radius()); if ( target.Nonzero() && target.Norm() <= robot->hardware.grenades.MaxRange() + robot->Radius() ) robot->hardware.grenades.Fire(target.Norm(), target.Angle()); //worry about short range? } break; case opSetForceField: { //pos angle -- temp = Pop(); GBPosition pos = PopVector() - robot->Position(); robot->hardware.forceField.SetDistance(pos.Norm()); robot->hardware.forceField.SetDirection(pos.Angle()); robot->hardware.forceField.SetAngle(temp); robot->hardware.forceField.SetPower(robot->hardware.forceField.MaxPower()); } break; // otherwise... default: throw GBUnknownInstructionError(); break; } }