Exemple #1
0
void UGUITestBase::addTest(HI::GUITest *test, TestType testType) {

    if (test) {
        getMap(testType).insert(test->getFullName(), test);
    }
}
Exemple #2
0
VHostMap *SubIpMap::getMap(struct sockaddr *pAddr) const
{
    uint32_t ipv4 = addrConvert(pAddr);
    return getMap(ipv4);

}
Exemple #3
0
bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
  unsigned MatchCount = 0;

  for (auto &AST : QS.ASTs) {
    MatchFinder Finder;
    std::vector<BoundNodes> Matches;
    DynTypedMatcher MaybeBoundMatcher = Matcher;
    if (QS.BindRoot) {
      llvm::Optional<DynTypedMatcher> M = Matcher.tryBind("root");
      if (M)
        MaybeBoundMatcher = *M;
    }
    CollectBoundNodes Collect(Matches);
    if (!Finder.addDynamicMatcher(MaybeBoundMatcher, &Collect)) {
      OS << "Not a valid top-level matcher.\n";
      return false;
    }
    Finder.matchAST(AST->getASTContext());

    if (QS.PrintMatcher) {
      std::string prefixText = "Matcher: ";
      OS << "\n  " << prefixText << Source << "\n";
      OS << "  " << std::string(prefixText.size() + Source.size(), '=') << '\n';
    }

    for (auto MI = Matches.begin(), ME = Matches.end(); MI != ME; ++MI) {
      OS << "\nMatch #" << ++MatchCount << ":\n\n";

      for (auto BI = MI->getMap().begin(), BE = MI->getMap().end(); BI != BE;
           ++BI) {
        if (QS.DiagOutput) {
          clang::SourceRange R = BI->second.getSourceRange();
          if (R.isValid()) {
            TextDiagnostic TD(OS, AST->getASTContext().getLangOpts(),
                              &AST->getDiagnostics().getDiagnosticOptions());
            TD.emitDiagnostic(
                FullSourceLoc(R.getBegin(), AST->getSourceManager()),
                DiagnosticsEngine::Note, "\"" + BI->first + "\" binds here",
                CharSourceRange::getTokenRange(R), None);
          }
        }
        if (QS.PrintOutput) {
          OS << "Binding for \"" << BI->first << "\":\n";
          BI->second.print(OS, AST->getASTContext().getPrintingPolicy());
          OS << "\n";
        }
        if (QS.DetailedASTOutput) {
          OS << "Binding for \"" << BI->first << "\":\n";
          BI->second.dump(OS, AST->getSourceManager());
          OS << "\n";
        }
      }

      if (MI->getMap().empty())
        OS << "No bindings.\n";
    }
  }

  OS << MatchCount << (MatchCount == 1 ? " match.\n" : " matches.\n");
  return true;
}
Exemple #4
0
/*
This function sets the initial boundary conditions defined by function g in the exercise sheet 
*/
void GridUtil::setBCs()
{
//      //real x1,y1,x2,y2;
//      real x, y = h_*(numGrid_-1);              // Outer boundary
      
//      size_t size = numGrid_*numGrid_;
//      //for(size_t i=0, j=(numGrid_-1)*numGrid_; (i<numGrid_) && (j<size); ++i,++j)
//      for(size_t j=(numGrid_-1)*numGrid_; j<size; ++j)
//      {
//           // x1 = h_*(i%numGrid_);
//            x = h_*(j%numGrid_);
//            //y1 = 0.0;
//           // u_.data_[i] = sin(M_PI*x1)*sinh(M_PI*y1);
//            u_.data_[j] = sin(M_PI*x)*sinh(M_PI*y);
//      }


////////////////////////////////////////////////////////////////////////////////////////////////////////////////
          real x, y, r, phi, startX, endX, startY, endY, midVal;
          size_t size, startLoop, endLoop;
          
          startX = -1.;
          startY = -1.;
          endX = 1.;
          endY = 1.;
          
          r = 0.;
          phi = 0.;
          size = numGrid_*numGrid_;
          midVal = 0.5*(numGrid_ -1);
          
          //std::cout<<"numGrid_ is : " << numGrid_ << std::endl;
          //std::cout<<"size : " << size << std::endl;

          // Bottom wall
          for(size_t j=0; j<numGrid_; ++j)      
          {
                // x = startX + h_*(j%numGrid_);
                x = startX + h_*j;
                y = startY;
                r = calR(x,y);
                phi = cal_phi(x,y);
                
                // Negative x region
                if(j < midVal)
                        phi += M_PI;
                // Positive x region        
                else 
                        phi += (2*M_PI);        
                   
                u_.data_[j] = g(r, phi);
          }
          
          startLoop = getMap(midVal, midVal, numGrid_);
          endLoop = getMap(midVal+1, 0, numGrid_);
          
          // Mid slit initialization, initalize by 0 since phi is 0.
          for(size_t j=startLoop; j<endLoop; ++j)
          {
                u_.data_[j] = 0.;
          }
          

          // Top wall
          startLoop = (numGrid_-1)*numGrid_; 
          for(size_t j=startLoop; j<size; ++j) 
          {
              x = startX + h_*(j%numGrid_);
              y = endY;
              r = calR(x,y);
              phi = cal_phi(x,y);
              
              // Left top boundary
              if(j < (startLoop + midVal))
                        phi += M_PI;
                                                    
              u_.data_[j] = g(r, phi);
          }


          // BC on Right Vertical wall
          startLoop =  (numGrid_-1)+ numGrid_ ;
          for(size_t i=startLoop; i< (size-numGrid_); i+=numGrid_)
          {
              x = endX;
              y = startY + h_*(i/numGrid_);
              
              r = calR(x,y);
              phi = cal_phi(x,y);
              
              // Bottom Right
              if(i < (midVal*numGrid_) )
                        phi += (2*M_PI);
                        
              u_.data_[i] = g(r, phi);
          }
          
          
          // BC on Left Vertical wall
          for(size_t i=numGrid_; i<size-numGrid_; i+=numGrid_)
          {
              x = startX;
              y = startY + h_*(i/numGrid_);
              
              r = calR(x,y);
              phi = cal_phi(x,y)+ M_PI;
              
              u_.data_[i] = g(r, phi);
          }
          
}
Exemple #5
0
static void printSensors(Logging *log, bool fileFormat) {
	// current time, in milliseconds
	int nowMs = currentTimeMillis();
	float sec = ((float) nowMs) / 1000;
	reportSensorF(log, fileFormat, "time", "", sec, 3);

	int rpm = 0;
#if EFI_SHAFT_POSITION_INPUT || defined(__DOXYGEN__)
	rpm = getRpmE(engine);
	reportSensorI(log, fileFormat, "rpm", "RPM", rpm);

//	reportSensorF(log, fileFormat, "TRG_0_DUTY", "%", getTriggerDutyCycle(0), 2);
//	reportSensorF(log, fileFormat, "TRG_1_DUTY", "%", getTriggerDutyCycle(1), 2);
#endif

	if (hasMafSensor()) {
		reportSensorF(log, fileFormat, "maf", "V", getMaf(), 2);
		reportSensorF(log, fileFormat, "mafr", "kg/hr", getRealMaf(), 2);
	}

	reportSensorF(log, fileFormat, "ENGINE_LOAD", "x", getEngineLoadT(), 2);


#if EFI_ANALOG_SENSORS || defined(__DOXYGEN__)
	if (engineConfiguration->hasMapSensor) {
		reportSensorF(log, fileFormat, "MAP", "kPa", getMap(), 2);
//		reportSensorF(log, fileFormat, "map_r", "V", getRawMap(), 2);
	}
	if (hasBaroSensor()) {
		reportSensorF(log, fileFormat, "baro", "kPa", getBaroPressure(), 2);
	}
	if (engineConfiguration->hasAfrSensor) {
		reportSensorF(log, fileFormat, "afr", "AFR", getAfr(), 2);
	}
#endif

#if EFI_VEHICLE_SPEED || defined(__DOXYGEN__)
	if (engineConfiguration->hasVehicleSpeedSensor) {
		reportSensorF(log, fileFormat, "vss", "kph", getVehicleSpeed(), 2);
	}
#endif /* EFI_PROD_CODE */

	reportSensorF(log, fileFormat, "ks", "count", engine->knockCount, 0);
	reportSensorF(log, fileFormat, "kv", "v", engine->knockVolts, 2);


//	reportSensorF(log, fileFormat, "vref", "V", getVRef(engineConfiguration), 2);
	if (hasVBatt(PASS_ENGINE_PARAMETER_F)) {
		reportSensorF(log, fileFormat, "vbatt", "V", getVBatt(PASS_ENGINE_PARAMETER_F), 2);
	}

	reportSensorF(log, fileFormat, "TP", "%", getTPS(PASS_ENGINE_PARAMETER_F), 2);

	if (fileFormat) {
		reportSensorF(log, fileFormat, "tpsacc", "ms", engine->tpsAccelEnrichment.getTpsEnrichment(PASS_ENGINE_PARAMETER_F), 2);
		reportSensorF(log, fileFormat, "advance", "deg", engine->tpsAccelEnrichment.getTpsEnrichment(PASS_ENGINE_PARAMETER_F), 2);
		reportSensorF(log, fileFormat, "advance", "deg", getFuelMs(rpm PASS_ENGINE_PARAMETER), 2);
	}

	if (engineConfiguration->hasCltSensor) {
		reportSensorF(log, fileFormat, "CLT", "C", getCoolantTemperature(PASS_ENGINE_PARAMETER_F), 2);
	}

	reportSensorF(log, fileFormat, "MAT", "C", getIntakeAirTemperature(PASS_ENGINE_PARAMETER_F), 2);

//	debugFloat(&logger, "tch", getTCharge1(tps), 2);

}
/**
 * Load a Ruby file then run the function corresponding to the service by
 * passing the conf, inputs and outputs parameters by refernce as Ruby Hash.
 *
 * @param main_conf the conf maps containing the main.cfg settings
 * @param request the map containing the HTTP request
 * @param s the service structure
 * @param real_inputs the maps containing the inputs
 * @param real_outputs the maps containing the outputs
 * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1 
 *  if the service failed to load or throw error at runtime.
 */
int zoo_ruby_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
#if RUBY_API_VERSION_MAJOR >= 2 || RUBY_API_VERSION_MINOR == 9
  ruby_sysinit(&argc,&argv);
  RUBY_INIT_STACK;
#endif
  ruby_init();
  maps* m=*main_conf;
  maps* inputs=*real_inputs;
  maps* outputs=*real_outputs;
  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
  char *ntmp=tmp0->value;
  map* tmp=NULL;
  ruby_init_loadpath();
  ruby_script("ZOO_EMBEDDED_ENV");
  
  VALUE klass=rb_define_module("Zoo");
  rb_define_const(klass,"SERVICE_SUCCEEDED",INT2FIX(3));
  rb_define_const(klass,"SERVICE_FAILED",INT2FIX(4));
  typedef VALUE (*HOOK)(...);
  rb_define_module_function(klass,"Translate",reinterpret_cast<HOOK>(RubyTranslate),-1);
  rb_define_module_function(klass,"UpdateStatus",reinterpret_cast<HOOK>(RubyUpdateStatus),-1);

  int error = 0;
		
  ID rFunc=Qnil;
  tmp=getMap(s->content,"serviceProvider");
  if(tmp!=NULL){
#if RUBY_VERSION_MINOR == 8
    const char* script = ruby_sourcefile = rb_source_filename(tmp->value);
    rb_protect(LoadWrap, reinterpret_cast<VALUE>(script), &error);
#else
    rb_load_protect(rb_str_new2(tmp->value), 0, &error);
#endif
    if(error) {
      ruby_trace_error(m);
      return -1;
    }
#if RUBY_VERSION_MINOR == 8
    ruby_exec();
#else
    ruby_exec_node(NULL);
#endif
  }
  else{
    map* err=createMap("text","Unable to parse serviceProvider please check your zcfg file.");
    addToMap(err,"code","NoApplicableCode");
    printExceptionReportResponse(m,err);
    return -1;
  }
  int res=SERVICE_FAILED;
  rFunc=rb_intern(s->name);
  if(rFunc!=Qnil){
    VALUE arg1=RubyHash_FromMaps(m);
    VALUE arg2=RubyHash_FromMaps(inputs);
    VALUE arg3=RubyHash_FromMaps(outputs);
    VALUE rArgs[3]={arg1,arg2,arg3};
    if (!rArgs)
      return -1;
    struct my_callback data;
    data.obj=Qnil;
    data.method_id=rFunc;
    data.nargs=3;
    data.args[0]=rArgs[0];
    data.args[1]=rArgs[1];
    data.args[2]=rArgs[2];
    typedef VALUE (*HOOK)(VALUE);
    VALUE tres=rb_protect(reinterpret_cast<HOOK>(FunCallWrap),(VALUE)(&data),&error);
    if (TYPE(tres) == T_FIXNUM) {
      res=FIX2INT(tres);
      freeMaps(real_outputs);
      free(*real_outputs);
      freeMaps(main_conf);
      free(*main_conf);
      *main_conf=mapsFromRubyHash(arg1);
      *real_outputs=mapsFromRubyHash(arg3);
#ifdef DEBUG
      dumpMaps(*main_conf);
      dumpMaps(*real_outputs);
#endif
    }else{
      ruby_trace_error(m);
      res=-1;
    }
  }
  else{
    char tmpS[1024];
    sprintf(tmpS, "Cannot find the %s function in the %s file.\n", s->name, tmp->value);
    map* tmps=createMap("text",tmpS);
    printExceptionReportResponse(m,tmps);
    res=-1;
  }
  ruby_finalize();
  return res;
}
Exemple #7
0
int main(int argc, char *argv[])
{
  if (argc < 4){
    printf( "Usage: %s <servicename> <directory>|<definition_file> <REQUEST> [<functionname> <param_1>[...<param_n>]]\n", basename(argv[0]) );
    return 1;
  }
 
  map* outputs=NULL;
  /**
   * Parsing inputs (need a loop over all files in the service path !!)
   */
  maps* m;
  m=(maps*)malloc(MAP_SIZE);
  conf_read("main.cfg",m);
  map* tmpm=getMapFromMaps(m,"main","serverAddress");
  int toto=count(tmpm);
  //printf(" - %i \n",toto);

  if(tmpm!=NULL)
    SERVICE_URL=strdup(tmpm->value);
  else
    SERVICE_URL=DEFAULT_SERVICE_URL;

  service* s[100];
  service* s1;
  int scount=0;

  if(strcmp(argv[3],"GetCapabilities")==0){
    int i=0;
    struct dirent *dp;
    DIR *dirp = opendir(argv[1]);
    int t;
    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
    xmlNodePtr n = printGetCapabilitiesHeader(doc,argv[2],m);
    
    int saved_stdout = dup(fileno(stdout));
    stdout = freopen("/dev/null" , "w" , stdout);
    while ((dp = readdir(dirp)) != NULL)
      if(strstr(dp->d_name,".zcfg")!=0){
	char toto1[1024];
	sprintf(toto1,"%s%s",argv[1],dp->d_name);
	char *toto=toto1;
	s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
	//s[scount]=(service*)malloc(sizeof(service*));
	//#ifdef DEBUG
	fprintf(stderr,"#################\n%s\n#################\n",toto1);
	//printf("|(1)");
	//#endif
	t=getServiceFromFile(toto1,&s1);
	
	//printf("|(2)");
	printGetCapabilitiesForProcess(m,n,s1);
	/**
	 * Valgrind told us that there is an issue regarding a 
	 * "conditional jump or move depends on uninitialised value(s)" for
	 * freeIOType
	 */
	//freeService(&s1);
	scount++;
      }
    char buf[20];
    sprintf(buf, "/dev/fd/%d", saved_stdout);
    stdout = freopen(buf , "w" , stdout);

    printDocument(doc);
    fflush(stdout);
    free(m);
    return 0;
  }
  else{
    s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
    //s[0]=(service*)malloc(sizeof(service*));
    int t=getServiceFromFile(argv[1],&s1);
    if(strcmp(argv[3],"DescribeProcess")==0){
      printDescribeProcessResponse(s1,argv[2]);
      //dumpMaps(m);
      //free(s1);
      return 0;
    }
    else
      if(strcmp(argv[3],"Execute")!=0){
	fprintf(stderr,"");
	//free(s);
	return 0;
      }
  }
  //dumpService(s);
  s[0]=s1;
  map* inputs=NULL;
  elements* c_inputs=s1->inputs;
  int j;
  for(j=0;j<argc-5;j++){
    //dumpElements(c_inputs);
    if(inputs!=NULL)
      addToMap(inputs,c_inputs->name,argv[j+5]);
    else
      inputs=createMap(c_inputs->name,argv[j+5]);
    if(c_inputs->next!=NULL || j+1>=argc-5)
      c_inputs=c_inputs->next;
    else{
      map* tmps=createMap("text","ERROR you provided more inputs than requested.");
      printExceptionReportResponse(m,tmps);
      //printf("ERROR you provided more inputs than requested.");
      return -1;
    }
#ifdef DEBUG
    printf("ARGV1 %d %s\n",j,inputs->value);
#endif
  }

#ifdef DEBUG
  dumpMap(inputs);
#endif

  const struct tm *tm;
  size_t len;
  time_t now;
  char *sDate;
  
  now = time ( NULL );
  tm = localtime ( &now );

  sDate = new char[TIME_SIZE];

  len = strftime ( sDate, TIME_SIZE, "%d-%B-%YT%I:%M:%SZ", tm );

#ifdef DEBUG
  printf("Trying to load %s\n", argv[2]);
#endif
  void* so = dlopen(argv[2], RTLD_LAZY);
  char *errstr;
  errstr = dlerror();
  if( so != NULL ) {
    typedef int (*execute_t)(map**,map**);
#ifdef DEBUG
    printf("Library loaded %s \n",errstr);
#endif
    execute_t execute=(execute_t)dlsym(so,argv[4]);
#ifdef DEBUG
    errstr = dlerror();
    printf("Function loaded %s\n",errstr);
#endif	

    /**
     * Need to check if we need to fork to load a status enabled 
     */
    char _toto[10];
    sprintf(_toto,"input_%i",argc-5);
    map* toto=getMap(inputs,_toto);
    if(strcmp(argv[argc-1],"bg")!=0){
#ifdef DEBUG
      printf("RUN IN NORMAL MODE \n");
#endif
      int res=execute(&inputs,&outputs);
#ifdef DEBUG
      printf("RUNNED IN NORMAL MODE \n");
      dumpMap(inputs);
      dumpMap(outputs);
#endif
      printProcessResponse(m,getpid(),s[0],argv[2],res,inputs,outputs);
    }
    else{
      pid_t   pid;
      int cpid=getpid();
      pid = fork ();
      if (pid > 0) {
	/**
	 * dady :
	 * set status to SERVICE_ACCEPTED
	 */
	printProcessResponse(m,pid,s[0],argv[2],SERVICE_ACCEPTED,inputs,outputs);
      }else if (pid == 0) {
	/* son */
	if (signal(SIGINT, sigint_handler) == SIG_ERR) {
	  printf("signal");
	  map* tmps=createMap("text","father received sigint.");
	  printExceptionReportResponse(m,tmps);
	  exit(1);
	}
#ifdef DEBUG
	printf("RUN IN BACKGROUND MODE \n");
#endif
	char tmp1[256];
	sprintf(tmp1,"service/temp/%s_%d.xml",argv[2],getpid());
	stdout = freopen(tmp1 , "w+" , stdout);
	/**
	 * set status to SERVICE_STARTED
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],SERVICE_STARTED,inputs,outputs);
	fflush(stdout);
	rewind(stdout);
	int t=execute(&inputs,&outputs);
	/**
	 * set status to status code returned by the service function
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],t,inputs,outputs);
      } else {
	/* error */
      }
    }
#ifdef DEBUG
    errstr = dlerror();
    printf("Function successfully loaded %s, unloading now.\n",errstr);
#endif
    dlclose(so);
  }
  else {
#ifdef DEBUG
    printf("C Library can't be loaded %s \n",errstr);
#endif
    python_support(m,s[0],argc,argv,inputs,outputs);
  }
  return 0;
}
Exemple #8
0
float findC3RangeWithNetwork(MECH * mech, MECH * mechTarget,
							 float realRange, dbref * myNetwork,
							 int networkSize, dbref * c3Ref)
{
	float c3Range = 0.0;
	float bestRange = 0.0;
	int i;
	int inLOS = 0;
	int mapX, mapY;
	float hexX, hexY, hexZ;
	MECH *otherMech;
	MAP *map;

	bestRange = realRange;
	*c3Ref = 0;

	if(networkSize == 0)
		return realRange;

	for(i = 0; i < networkSize; i++) {
		otherMech = getMechInTempNetwork(i, myNetwork, networkSize);

		if(!otherMech)
			continue;

		if(!Good_obj(otherMech->mynum))
			continue;

		if(mechTarget) {
			if(otherMech == mechTarget)
				continue;

			debugC3(tprintf
					("C3RANGE-NETWORK (mech): Finding range from %d to %d.",
					 mech->mynum, mechTarget->mynum));

			c3Range = FaMechRange(otherMech, mechTarget);
			inLOS =
				InLineOfSight(otherMech, mechTarget, MechX(mechTarget),
							  MechY(mechTarget), c3Range);
		} else if((MechTargX(mech) > 0) && (MechTargY(mech) > 0)) {
			mapX = MechTargX(mech);
			mapY = MechTargY(mech);
			map = getMap(mech->mapindex);

			debugC3(tprintf
					("C3RANGE-NETWORK (hex): Finding range from %d to %d %d.",
					 mech->mynum, mapX, mapY));

			MechTargZ(mech) = Elevation(map, mapX, mapY);
			hexZ = ZSCALE * MechTargZ(mech);
			MapCoordToRealCoord(mapX, mapY, &hexX, &hexY);

			c3Range =
				FindRange(MechFX(otherMech), MechFY(otherMech),
						  MechFZ(otherMech), hexX, hexY, hexZ);
			inLOS = LOS_NB(otherMech, NULL, mapX, mapY, c3Range);
		} else {
			continue;
		}

		if(inLOS && (c3Range < bestRange)) {
			bestRange = c3Range;
			*c3Ref = otherMech->mynum;
		}
	}

	return bestRange;
}
void		Map::setBox(std::pair<int, int> pos, status stat)
{
  getMap()[pos] = stat;
}
Exemple #10
0
bool installSpecies(size_t k, const XML_Node& s, thermo_t& th,
                    SpeciesThermo* spthermo_ptr, int rule,
                    XML_Node* phaseNode_ptr,
                    VPSSMgr* vpss_ptr,
                    SpeciesThermoFactory* factory)
{
    std::string xname = s.name();
    if (xname != "species") {
        throw CanteraError("installSpecies",
                           "Unexpected XML name of species XML_Node: " + xname);
    }

    if (rule) {
        th.ignoreUndefinedElements();
    }

    // get the composition of the species
    const XML_Node& a = s.child("atomArray");
    map<string,string> comp;
    getMap(a, comp);

    // construct a vector of atom numbers for each element in phase th. Elements
    // not declared in the species (i.e., not in map comp) will have zero
    // entries in the vector.
    size_t nel = th.nElements();
    vector_fp ecomp(nel, 0.0);
    compositionMap comp_map = parseCompString(a.value());
    for (size_t m = 0; m < nel; m++) {
        std::string& es = comp[th.elementName(m)];
        if (!es.empty()) {
            ecomp[m] = fpValueCheck(es);
        }
    }

    // get the species charge, if any. Note that the charge need
    // not be explicitly specified if special element 'E'
    // (electron) is one of the elements.
    doublereal chrg = 0.0;
    if (s.hasChild("charge")) {
        chrg = getFloat(s, "charge");
    }

    // get the species size, if any. (This is used by surface
    // phases to represent how many sites a species occupies.)
    doublereal sz = 1.0;
    if (s.hasChild("size")) {
        sz = getFloat(s, "size");
    }

    if (vpss_ptr) {
        th.addUniqueSpecies(s["name"], &ecomp[0], chrg, sz);
        VPStandardStateTP* vp_ptr = dynamic_cast<VPStandardStateTP*>(&th);
        vp_ptr->createInstallPDSS(k, s, phaseNode_ptr);
    } else {
        SpeciesThermoInterpType* st = newSpeciesThermoInterpType(s);
        Species sp(s["name"], comp_map, st, chrg, sz);

        // Read gas-phase transport data, if provided
        if (s.hasChild("transport") &&
                s.child("transport")["model"] == "gas_transport") {
            XML_Node& tr = s.child("transport");

            string geometry, dummy;
            getString(tr, "geometry", geometry, dummy);

            double diam = getFloat(tr, "LJ_diameter");
            double welldepth = getFloat(tr, "LJ_welldepth");

            double dipole = 0.0;
            getOptionalFloat(tr, "dipoleMoment", dipole);

            double polar = 0.0;
            getOptionalFloat(tr, "polarizability", polar);

            double rot = 0.0;
            getOptionalFloat(tr, "rotRelax", rot);
            double acentric = 0.0;
            getOptionalFloat(tr, "acentric_factor", acentric);

            GasTransportData* gastran = new GasTransportData;
            gastran->setCustomaryUnits(sp.name, geometry, diam, welldepth,
                                       dipole, polar, rot, acentric);
            sp.transport.reset(gastran);
            gastran->validate(sp);
        }
        th.addSpecies(sp);
    }

    return true;
}
Exemple #11
0
void showNetworkTargets(dbref player, MECH * mech, int tIsC3)
{
	MAP *objMap = getMap(mech->mapindex);
	int i, j, wTemp, bearing;
	MECH *otherMech;
	float realRange, c3Range;
	char buff[100];
	char *mech_name;
	char move_type[30];
	char cStatus1, cStatus2, cStatus3, cStatus4, cStatus5;
	char weaponarc;
	int losFlag;
	int arc;
	int wSeeTarget = TARG_LOS_NONE;
	int wC3SeeTarget = TARG_LOS_NONE;
	int tShowStatusInfo = 0;
	char bufflist[MAX_MECHS_PER_MAP][120];
	float rangelist[MAX_MECHS_PER_MAP];
	int buffindex = 0;
	int sbuff[MAX_MECHS_PER_MAP];
	int networkSize;
	dbref myNetwork[C3_NETWORK_SIZE];
	dbref c3Ref;

	buildTempNetwork(mech, myNetwork, &networkSize, 1, 1, 0, tIsC3);

	/*
	 * Send then a 'contacts' style report. This is different from the
	 * normal contacts since it has a 'physical' range in it too.
	 */
	notify_printf(player, "%s Contacts:", tIsC3 ? "C3" : "C3i");

	for(i = 0; i < objMap->first_free; i++) {
		if(!(objMap->mechsOnMap[i] != mech->mynum &&
			 objMap->mechsOnMap[i] != -1))
			continue;

		otherMech = (MECH *) FindObjectsData(objMap->mechsOnMap[i]);

		if(!otherMech)
			continue;

		if(!Good_obj(otherMech->mynum))
			continue;

		tShowStatusInfo = 0;
		realRange = FlMechRange(objMap, mech, otherMech);
		losFlag =
			InLineOfSight(mech, otherMech, MechX(otherMech),
						  MechY(otherMech), realRange);

		/*
		 * If we do see them, let's make sure it's not just a 'something'
		 */
		if(losFlag) {
			if(InLineOfSight_NB(mech, otherMech, MechX(otherMech),
								MechY(otherMech), 0.0))
				wSeeTarget = TARG_LOS_CLEAR;
			else
				wSeeTarget = TARG_LOS_SOMETHING;
		} else
			wSeeTarget = TARG_LOS_NONE;

		/*
		 * If I don't see it, let's see if someone else in the network does
		 */
		if(wSeeTarget != TARG_LOS_CLEAR)
			wC3SeeTarget = mechSeenByNetwork(mech, otherMech, tIsC3);

		/* If noone sees it, we continue */
		if(!wSeeTarget && !wC3SeeTarget)
			continue;

		/* Get our network range */
		c3Range =
			findC3RangeWithNetwork(mech, otherMech, realRange, myNetwork,
								   networkSize, &c3Ref);

		/* Figure out if we show the info or not... ie, do we actually 'see' it */
		if((wSeeTarget != TARG_LOS_CLEAR) && (wC3SeeTarget != TARG_LOS_CLEAR)) {
			tShowStatusInfo = 0;
			mech_name = "something";
		} else {
			tShowStatusInfo = 1;
			mech_name = silly_atr_get(otherMech->mynum, A_MECHNAME);
		}

		bearing =
			FindBearing(MechFX(mech), MechFY(mech), MechFX(otherMech),
						MechFY(otherMech));
		strcpy(move_type, GetMoveTypeID(MechMove(otherMech)));

		/* Get our weapon arc */
		arc = InWeaponArc(mech, MechFX(otherMech), MechFY(otherMech));
		weaponarc = getWeaponArc(mech, arc);

		/* Now get our status chars */
		if(!tShowStatusInfo) {
			cStatus1 = ' ';
			cStatus2 = ' ';
			cStatus3 = ' ';
			cStatus4 = ' ';
			cStatus5 = ' ';
		} else {
			cStatus1 = getStatusChar(mech, otherMech, 1);
			cStatus2 = getStatusChar(mech, otherMech, 2);
			cStatus3 = getStatusChar(mech, otherMech, 3);
			cStatus4 = getStatusChar(mech, otherMech, 4);
			cStatus5 = getStatusChar(mech, otherMech, 5);
		}

		/* Now, build the string */
		sprintf(buff,
				"%s%c%c%c[%s]%c %-11.11s x:%3d y:%3d z:%3d r:%4.1f c:%4.1f b:%3d s:%5.1f h:%3d S:%c%c%c%c%c%s",
				otherMech->mynum == MechTarget(mech) ? "%ch%cr" :
				(tShowStatusInfo &&
				 !MechSeemsFriend(mech, otherMech)) ? "%ch%cy" : "",
				(losFlag & MECHLOSFLAG_SEESP) ? 'P' : ' ',
				(losFlag & MECHLOSFLAG_SEESS) ? 'S' : ' ', weaponarc,
				MechIDS(otherMech, MechSeemsFriend(mech, otherMech) ||
						!tShowStatusInfo), move_type[0], mech_name,
				MechX(otherMech), MechY(otherMech), MechZ(otherMech),
				realRange, c3Range, bearing, MechSpeed(otherMech),
				MechVFacing(otherMech), cStatus1, cStatus2, cStatus3,
				cStatus4, cStatus5, (otherMech->mynum == MechTarget(mech)
									 || !MechSeemsFriend(mech,
														 otherMech)) ? "%c" :
				"");

		rangelist[buffindex] = realRange;
		rangelist[buffindex] +=
			(MechStatus(otherMech) & DESTROYED) ? 10000 : 0;
		strcpy(bufflist[buffindex++], buff);
	}

	for(i = 0; i < buffindex; i++)
		sbuff[i] = i;

	/* print a sorted list of detected mechs */
	/* use the ever-popular bubble sort */
	for(i = 0; i < (buffindex - 1); i++)
		for(j = (i + 1); j < buffindex; j++)
			if(rangelist[sbuff[j]] > rangelist[sbuff[i]]) {
				wTemp = sbuff[i];
				sbuff[i] = sbuff[j];
				sbuff[j] = wTemp;
			}

	for(i = 0; i < buffindex; i++)
		notify(player, bufflist[sbuff[i]]);

	notify_printf(player, "End %s Contact List", tIsC3 ? "C3" : "C3i");
}
Exemple #12
0
HI::GUITest *UGUITestBase::takeTest(const QString &suite, const QString &name, TestType testType) {

    return getMap(testType).take(suite + ":" + name);
}
Exemple #13
0
HI::GUITest *UGUITestBase::findTest(const QString &name, TestType testType) {
    GUITestMap map = getMap(testType);
    return map.value(name);
}
Exemple #14
0
QString UGUITestBase::getNextTestName(TestType testType) {

    int testsCount = getMap(testType).size();
    return unnamedTestsPrefix + QString::number(testsCount);
}
void
SUMOVTypeParameter::write(OutputDevice& dev) const {
    if (onlyReferenced) {
        return;
    }
    dev.openTag(SUMO_TAG_VTYPE);
    dev.writeAttr(SUMO_ATTR_ID, id);
    if (wasSet(VTYPEPARS_LENGTH_SET)) {
        dev.writeAttr(SUMO_ATTR_LENGTH, length);
    }
    if (wasSet(VTYPEPARS_MINGAP_SET)) {
        dev.writeAttr(SUMO_ATTR_MINGAP, minGap);
    }
    if (wasSet(VTYPEPARS_MAXSPEED_SET)) {
        dev.writeAttr(SUMO_ATTR_MAXSPEED, maxSpeed);
    }
    if (wasSet(VTYPEPARS_PROBABILITY_SET)) {
        dev.writeAttr(SUMO_ATTR_PROB, defaultProbability);
    }
    if (wasSet(VTYPEPARS_SPEEDFACTOR_SET)) {
        dev.writeAttr(SUMO_ATTR_SPEEDFACTOR, speedFactor);
    }
    if (wasSet(VTYPEPARS_SPEEDDEVIATION_SET)) {
        dev.writeAttr(SUMO_ATTR_SPEEDDEV, speedDev);
    }
    if (wasSet(VTYPEPARS_VEHICLECLASS_SET)) {
        dev.writeAttr(SUMO_ATTR_VCLASS, toString(vehicleClass));
    }
    if (wasSet(VTYPEPARS_EMISSIONCLASS_SET)) {
        dev.writeAttr(SUMO_ATTR_EMISSIONCLASS, PollutantsInterface::getName(emissionClass));
    }
    if (wasSet(VTYPEPARS_IMPATIENCE_SET)) {
        if (impatience == -std::numeric_limits<SUMOReal>::max()) {
            dev.writeAttr(SUMO_ATTR_IMPATIENCE, "off");
        } else {
            dev.writeAttr(SUMO_ATTR_IMPATIENCE, impatience);
        }
    }
    if (wasSet(VTYPEPARS_SHAPE_SET)) {
        dev.writeAttr(SUMO_ATTR_GUISHAPE, getVehicleShapeName(shape));
    }
    if (wasSet(VTYPEPARS_WIDTH_SET)) {
        dev.writeAttr(SUMO_ATTR_WIDTH, width);
    }
    if (wasSet(VTYPEPARS_HEIGHT_SET)) {
        dev.writeAttr(SUMO_ATTR_HEIGHT, height);
    }
    if (wasSet(VTYPEPARS_COLOR_SET)) {
        dev.writeAttr(SUMO_ATTR_COLOR, color);
    }
    if (wasSet(VTYPEPARS_OSGFILE_SET)) {
        dev.writeAttr(SUMO_ATTR_OSGFILE, osgFile);
    }
    if (wasSet(VTYPEPARS_IMGFILE_SET)) {
        dev.writeAttr(SUMO_ATTR_IMGFILE, imgFile);
    }
    if (wasSet(VTYPEPARS_LANE_CHANGE_MODEL_SET)) {
        dev.writeAttr(SUMO_ATTR_LANE_CHANGE_MODEL, lcModel);
    }
    if (wasSet(VTYPEPARS_PERSON_CAPACITY)) {
        dev.writeAttr(SUMO_ATTR_PERSON_CAPACITY, personCapacity);
    }
    if (wasSet(VTYPEPARS_CONTAINER_CAPACITY)) {
        dev.writeAttr(SUMO_ATTR_CONTAINER_CAPACITY, containerCapacity);
    }
    if (wasSet(VTYPEPARS_BOARDING_DURATION)) {
        dev.writeAttr(SUMO_ATTR_BOARDING_DURATION, boardingDuration);
    }
    if (wasSet(VTYPEPARS_LOADING_DURATION)) {
        dev.writeAttr(SUMO_ATTR_LOADING_DURATION, loadingDuration);
    }

    if (cfParameter.size() != 0) {
        dev.openTag(cfModel);
        std::vector<SumoXMLAttr> attrs;
        for (CFParams::const_iterator i = cfParameter.begin(); i != cfParameter.end(); ++i) {
            attrs.push_back(i->first);
        }
        std::sort(attrs.begin(), attrs.end());
        for (std::vector<SumoXMLAttr>::const_iterator i = attrs.begin(); i != attrs.end(); ++i) {
            dev.writeAttr(*i, cfParameter.find(*i)->second);
        }
        dev.closeTag();
    }
    for (std::map<std::string, std::string>::const_iterator j = getMap().begin(); j != getMap().end(); ++j) {
        dev.openTag(SUMO_TAG_PARAM);
        dev.writeAttr(SUMO_ATTR_KEY, (*j).first);
        dev.writeAttr(SUMO_ATTR_VALUE, (*j).second);
        dev.closeTag();
    }
    dev.closeTag();
}
Exemple #16
0
void mech_c3i_join_leave(dbref player, void *data, char *buffer)
{
    MECH *mech = (MECH *) data, *target;
    MAP *objMap;
    char *args[2];
    dbref refTarget;
    int LOS = 1;
    float range = 0.0;

    cch(MECH_USUALO);

    DOCHECK(mech_parseattributes(buffer, args, 2) != 1,
	"Invalid number of arguments to function!");

    DOCHECK(!HasC3i(mech), "This unit is not equipped with C3i!");
    DOCHECK(C3iDestroyed(mech), "Your C3i system is destroyed!");
    DOCHECK(AnyECMDisturbed(mech),
	"Your C3i system is not currently operational!");

    validateC3iNetwork(mech);

    /* Clear our C3i Network */
    if (!strcmp(args[0], "-")) {
	if (MechC3iNetworkSize(mech) <= 0) {
	    mech_notify(mech, MECHALL,
		"You are not connected to a C3i network!");

	    return;
	}

	clearC3iNetwork(mech, 1);

	mech_notify(mech, MECHALL, "You disconnect from the C3i network.");

	return;
    }

    /* Well, if we're here then we wanna connect to a network */
    /* Let's check to see if we're already in one... can't be in two at the same time */
    DOCHECK(MechC3iNetworkSize(mech) > 0,
	"You are already in a C3i network!");

    objMap = getMap(mech->mapindex);

    /* Find who we're trying to connect to */
    refTarget = FindTargetDBREFFromMapNumber(mech, args[0]);
    target = getMech(refTarget);

    if (target) {
	LOS =
	    InLineOfSight(mech, target, MechX(target), MechY(target),
	    range);
    } else
	refTarget = 0;

    DOCHECK((refTarget < 1) ||
	!LOS, "That is not a valid targetID. Try again.");
    DOCHECK(MechTeam(mech) != MechTeam(target),
	"You can't use the C3i network of unfriendly units!");
    DOCHECK(mech == target, "You can't connect to yourself!");
    DOCHECK(Destroyed(target), "That unit is destroyed!");
    DOCHECK(!Started(target), "That unit is not started!");
    DOCHECK(!HasC3i(target),
	"That unit does not appear to be equipped with C3i!");

    /* validate the network of our target */
    validateC3iNetwork(target);
    DOCHECK(MechC3iNetworkSize(target) >= C3I_NETWORK_SIZE,
	"That unit's C3i network is operating at maximum capacity!");

    /* Connect us up */
    mech_notify(mech, MECHALL, tprintf("You connect to %s's C3i network.",
	    GetMechToMechID(mech, target)));

    addMechToC3iNetwork(target, mech);
}
/**
 * Convert a map to a Ruby Hash
 *
 * @param t the map to convert
 * @return a new Ruby Hash
 */
VALUE RubyHash_FromMap(map* t){
  VALUE res=rb_hash_new( );
  map* tmp=t;
  int hasSize=0;
  map* isArray=getMap(tmp,"isArray");
  map* size=getMap(tmp,"size");
  map* tmap=getMapType(tmp);
  while(tmp!=NULL){
    VALUE name= rb_str_new2(tmp->name);
    if(strcasecmp(tmp->name,"value")==0) {
      if(isArray!=NULL){
	map* len=getMap(tmp,"length");
	int cnt=atoi(len->value);
	VALUE value=rb_ary_new2(cnt);
	VALUE mvalue=rb_ary_new2(cnt);
	VALUE svalue=rb_ary_new2(cnt);

	for(int i=0;i<cnt;i++){
	  
	  map* vMap=getMapArray(tmp,"value",i);	    
	  map* sMap=getMapArray(tmp,"size",i);

	  if(vMap!=NULL){
	    
	    VALUE lvalue;
	    VALUE lsvalue;
	    if(sMap==NULL){
	      lvalue=rb_str_new2(vMap->value);
	      lsvalue=Qnil;
	    }
	    else{
	      lvalue=rb_str_new(vMap->value,atoi(sMap->value));
	      lsvalue=rb_str_new2(sMap->value);
	      hasSize=1;
	    }

	    rb_ary_push(value,lvalue);
	    rb_ary_push(svalue,lsvalue);
	  }
	  
	  map* mMap=getMapArray(tmp,tmap->name,i);

	  VALUE lmvalue;
	  if(mMap!=NULL){
	    lmvalue=rb_str_new2(mMap->value);
	  }else
	    lmvalue=Qnil;
	  rb_ary_push(mvalue,lmvalue);
	  
	}

	rb_hash_aset(res, name, mvalue);
	rb_hash_aset(res, rb_str_new2(tmap->name), mvalue);
      
	if(hasSize>0){
	  VALUE lname=rb_str_new2("size");
	  rb_hash_aset(res, lname, value);
	}
      }
      else if(size!=NULL){
	VALUE value=rb_str_new(tmp->value,atoi(size->value));
	rb_hash_aset(res, name, value);
      }
      else{
	VALUE value=rb_str_new2(tmp->value);
	rb_hash_aset(res, name, value);
      }
    }
    else{
      VALUE value=rb_str_new2(tmp->value);
      rb_hash_aset(res, name, value);
    }
    tmp=tmp->next;
  }
  return res;
}
Exemple #18
0
_InitD1::_InitD1(void) {
	std::map<std::string, CreateFun>& the_real_map = getMap();
	the_real_map["D1"] = &D1::makeD1;
}
// Register a panel map
void SpecifierPanelFactory::registerType(const std::string& name,
										 SpecifierPanelPtr cls)
{
	getMap().insert(PanelMap::value_type(name, cls));
}
Exemple #20
0
bool installSpecies(size_t k, const XML_Node& s, thermo_t& th,
                    SpeciesThermo* spthermo_ptr, int rule,
                    XML_Node* phaseNode_ptr,
                    VPSSMgr* vpss_ptr,
                    SpeciesThermoFactory* factory)
{
    std::string xname = s.name();
    if (xname != "species") {
        throw CanteraError("installSpecies",
                           "Unexpected XML name of species XML_Node: " + xname);
    }
    // get the composition of the species
    const XML_Node& a = s.child("atomArray");
    map<string,string> comp;
    getMap(a, comp);

    // check that all elements in the species exist in 'p'. If rule != 0,
    // quietly skip this species if some elements are undeclared; otherwise,
    // throw an exception
    map<string,string>::const_iterator _b = comp.begin();
    for (; _b != comp.end(); ++_b) {
        if (th.elementIndex(_b->first) == npos) {
            if (rule == 0) {
                throw CanteraError("installSpecies",
                                   "Species " + s["name"] +
                                   " contains undeclared element " + _b->first);
            } else {
                return false;
            }
        }
    }

    // construct a vector of atom numbers for each element in phase th. Elements
    // not declared in the species (i.e., not in map comp) will have zero
    // entries in the vector.
    size_t nel = th.nElements();
    vector_fp ecomp(nel, 0.0);
    for (size_t m = 0; m < nel; m++) {
        std::string& es = comp[th.elementName(m)];
        if (!es.empty()) {
            ecomp[m] = fpValueCheck(es);
        }
    }


    // get the species charge, if any. Note that the charge need
    // not be explicitly specified if special element 'E'
    // (electron) is one of the elements.
    doublereal chrg = 0.0;
    if (s.hasChild("charge")) {
        chrg = getFloat(s, "charge");
    }

    // get the species size, if any. (This is used by surface
    // phases to represent how many sites a species occupies.)
    doublereal sz = 1.0;
    if (s.hasChild("size")) {
        sz = getFloat(s, "size");
    }

    // add the species to phase th
    th.addUniqueSpecies(s["name"], &ecomp[0], chrg, sz);

    if (vpss_ptr) {
        VPStandardStateTP* vp_ptr = dynamic_cast<VPStandardStateTP*>(&th);
        factory->installVPThermoForSpecies(k, s, vp_ptr, phaseNode_ptr);
    } else {
        // install the thermo parameterization for this species into
        // the species thermo manager for phase th
        factory->installThermoForSpecies(k, s, &th, *spthermo_ptr, phaseNode_ptr);
    }

    return true;
}
static void showLine(lcd_line_e line, int screenY) {
	static char buffer[10];

	switch (line) {
	case LL_VERSION:
		lcdPrintf("version %s", VCS_VERSION);
		return;
	case LL_CONFIG:
		lcdPrintf("config %s", getConfigurationName(engineConfiguration->engineType));
		return;
	case LL_RPM:
		lcdPrintf("RPM %d", getRpmE(engine));
		{
			char sdState;
			if (boardConfiguration->isSdCardEnabled) {
				sdState = isSdCardAlive() ? 'L' : 'n';
			} else {
				sdState = 'D';
			}
			int seconds = getTimeNowSeconds();
			if (seconds < 10000) {
				lcdPrintf("  %d%c", seconds, sdState);
			}
		}
		return;
	case LL_CLT_TEMPERATURE:
		lcdPrintf("Coolant %f", getCoolantTemperature(PASS_ENGINE_PARAMETER_F));
		return;
	case LL_IAT_TEMPERATURE:
		lcdPrintf("Intake Air %f", getIntakeAirTemperature(PASS_ENGINE_PARAMETER_F));
		return;
	case LL_ALGORITHM:
		lcdPrintf(getEngine_load_mode_e(engineConfiguration->algorithm));
		return;
	case LL_INJECTION:
		lcdPrintf(getInjection_mode_e(engineConfiguration->injectionMode));
		return;
	case LL_ING_FLOW:
		lcdPrintf("Inj %fcc", engineConfiguration->injector.flow);
		return;
	case LL_IGNITION:
		lcdPrintf(getIgnition_mode_e(engineConfiguration->ignitionMode));
		return;
	case LL_TPS:
		getPinNameByAdcChannel(engineConfiguration->tpsAdcChannel, buffer);

		lcdPrintf("Throttle %s %f%%", buffer, getTPS());
		return;
	case LL_VBATT:
		lcdPrintf("Battery %fv", getVBatt(PASS_ENGINE_PARAMETER_F));
		return;
	case LL_KNOCK:
		getPinNameByAdcChannel(engineConfiguration->hipOutputChannel, buffer);
		lcdPrintf("Knock %s %fv", buffer, engine->knockVolts);
		return;

#if	EFI_ANALOG_SENSORS || defined(__DOXYGEN__)
	case LL_BARO:
		if (hasBaroSensor()) {
			lcdPrintf("Baro: %f", getBaroPressure());
		} else {
			lcdPrintf("Baro: none");
		}
		return;
#endif
	case LL_AFR:
		if (engineConfiguration->hasAfrSensor) {
			lcdPrintf("AFR: %f", getAfr());
		} else {
			lcdPrintf("AFR: none");
		}
		return;
	case LL_MAP:
		if (engineConfiguration->hasMapSensor) {
			lcdPrintf("MAP %f", getMap());
		} else {
			lcdPrintf("MAP: none");
		}
		return;
	case LL_MAF_V:
		if (hasMafSensor()) {
			lcdPrintf("MAF: %fv", getMaf());
		} else {
			lcdPrintf("MAF: none");
		}
		return;
	case LL_MAF_KG_HR:
		if (hasMafSensor()) {
			lcdPrintf("MAF: %f kg/hr", getRealMaf());
		} else {
			lcdPrintf("MAF: none");
		}
		return;
	case LL_TRIGGER_ERRORS:
		lcdPrintf("Errors");
		return;
	case LL_TRIGGER_DUTY:
		lcdPrintf("Duty");
		return;
	default:
		lcdPrintf("()");
	}
}
Exemple #22
0
void Player::save(){
	char sql[10000];
	sprintf_s(sql, 10000, "update keymap set ");
	for(int i=0; i<90; i++){
		char temp[100];
		if(i!=89)
			sprintf_s(temp, 100, "pos%d=%d, ", i, keys[i]);
		else
			sprintf_s(temp, 100, "pos%d=%d where charid=%d; ", i, keys[i], getPlayerid());
		strcat_s(sql, 10000, temp);
	}
	MySQL::insert(sql);
	sprintf_s(sql, 10000, "update characters set level=%d, job=%d, str=%d, dex=%d, intt=%d, luk=%d, chp=%d, mhp=%d, cmp=%d, mmp=%d, ap=%d, sp=%d, exp=%d, fame=%d, map=%d, gender=%d, skin=%d, eyes=%d, hair=%d, mesos=%d where id=%d", getLevel(), getJob(), getStr(), getDex(), getInt(), getLuk(), getHP(), getRMHP(), getMP(), getRMMP(), getAp(), getSp(), getExp(), getFame(), getMap(), getGender(), getSkin(), getEyes(), getHair(), inv->getMesos() ,getPlayerid());
	MySQL::insert(sql);
	char temp[1000];
	sprintf_s(sql, 10000, "delete from equip where charid=%d;", getPlayerid());
	MySQL::insert(sql);
	bool firstrun = true;
	for(int i=0; i<inv->getEquipNum(); i++){
		if(firstrun == true){
			sprintf_s(sql, 10000, "INSERT INTO equip VALUES (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)", inv->getEquip(i)->id, Drops::equips[inv->getEquip(i)->id].type ,getPlayerid(), inv->getEquipPos(i), inv->getEquip(i)->slots, inv->getEquip(i)->scrolls,
				inv->getEquip(i)->istr, inv->getEquip(i)->idex, inv->getEquip(i)->iint, inv->getEquip(i)->iluk, inv->getEquip(i)->ihp, inv->getEquip(i)->imp, inv->getEquip(i)->iwatk, inv->getEquip(i)->imatk, inv->getEquip(i)->iwdef, 
				inv->getEquip(i)->imdef, inv->getEquip(i)->iacc, inv->getEquip(i)->iavo, inv->getEquip(i)->ihand, inv->getEquip(i)->ijump, inv->getEquip(i)->ispeed);
			firstrun = false;
		}
		else{
			sprintf_s(temp, 1000, ",(%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)", inv->getEquip(i)->id, Drops::equips[inv->getEquip(i)->id].type ,getPlayerid(), inv->getEquipPos(i), inv->getEquip(i)->slots, inv->getEquip(i)->scrolls,
				inv->getEquip(i)->istr, inv->getEquip(i)->idex, inv->getEquip(i)->iint, inv->getEquip(i)->iluk, inv->getEquip(i)->ihp, inv->getEquip(i)->imp, inv->getEquip(i)->iwatk, inv->getEquip(i)->imatk, inv->getEquip(i)->iwdef, 
				inv->getEquip(i)->imdef, inv->getEquip(i)->iacc, inv->getEquip(i)->iavo, inv->getEquip(i)->ihand, inv->getEquip(i)->ijump, inv->getEquip(i)->ispeed);
			strcat_s(sql, 10000, temp);
		}
	}
	MySQL::insert(sql);
	sprintf_s(sql, 10000, "delete from skills where charid=%d;", getPlayerid());
	MySQL::insert(sql);
	firstrun = true;
	for(int i=0; i<skills->getSkillsNum(); i++){
		if(firstrun == true){
			sprintf_s(sql, 10000, "INSERT INTO skills VALUES (%d, %d, %d)", getPlayerid(), skills->getSkillID(i), skills->getSkillLevel(skills->getSkillID(i)));
			firstrun = false;
		}
		else{
			sprintf_s(temp, 1000, ",(%d, %d, %d)", getPlayerid(), skills->getSkillID(i), skills->getSkillLevel(skills->getSkillID(i)));
			strcat_s(sql, 10000, temp);
		}
	}
	MySQL::insert(sql);
	sprintf_s(sql, 10000, "DELETE FROM items WHERE charid=%d;", getPlayerid());
	MySQL::insert(sql);
	firstrun = true;
	for(int i=0; i<inv->getItemNum(); i++){
		if(firstrun == true){
			sprintf_s(sql, 10000, "INSERT INTO items VALUES (%d, %d, %d, %d, %d)", inv->getItem(i)->id, getPlayerid() ,inv->getItem(i)->inv, inv->getItem(i)->pos, inv->getItem(i)->amount);
			firstrun = false;
		}
		else{
			sprintf_s(temp, 1000, ",(%d, %d, %d, %d, %d)", inv->getItem(i)->id, getPlayerid() ,inv->getItem(i)->inv, inv->getItem(i)->pos, inv->getItem(i)->amount);
			strcat_s(sql, 10000, temp);
		}
	}
	MySQL::insert(sql);
}
Exemple #23
0
    Function::Register::Register(const char *name, FUNC func)
    {
	getMap()[name] = func;
    }
Exemple #24
0
 void Hasher::rememberHashValuePair(std::size_t hash, const std::string& value)
 {
   std::pair<std::map<std::size_t, std::string>::iterator, bool> ret;
   ret = getMap().insert(std::pair<std::size_t, std::string>(hash, value));
 }
Exemple #25
0
void testWriteMethod()
{
    getMap().insert(1,1); // Warning
    int a = getMap().take(1); // Warning
}
Exemple #26
0
 bool Hasher::hasValue(std::size_t hash)
 {
   std::map<std::size_t, std::string>::iterator it = getMap().find(hash);
 
   return it != getMap().end();
 }
Exemple #27
0
void EngineState::periodicFastCallback(DECLARE_ENGINE_PARAMETER_SIGNATURE) {
	efitick_t nowNt = getTimeNowNt();
	if (ENGINE(rpmCalculator).isCranking(PASS_ENGINE_PARAMETER_SIGNATURE)) {
		crankingTime = nowNt;
		timeSinceCranking = 0.0f;
	} else {
		timeSinceCranking = nowNt - crankingTime;
	}
	updateAuxValves(PASS_ENGINE_PARAMETER_SIGNATURE);

	int rpm = ENGINE(rpmCalculator).getRpm(PASS_ENGINE_PARAMETER_SIGNATURE);
	sparkDwell = getSparkDwell(rpm PASS_ENGINE_PARAMETER_SUFFIX);
	dwellAngle = sparkDwell / getOneDegreeTimeMs(rpm);
	if (hasAfrSensor(PASS_ENGINE_PARAMETER_SIGNATURE)) {
		engine->sensors.currentAfr = getAfr(PASS_ENGINE_PARAMETER_SIGNATURE);
	}

	// todo: move this into slow callback, no reason for IAT corr to be here
	iatFuelCorrection = getIatFuelCorrection(engine->sensors.iat PASS_ENGINE_PARAMETER_SUFFIX);
	// todo: move this into slow callback, no reason for CLT corr to be here
	if (boardConfiguration->useWarmupPidAfr && engine->sensors.clt < engineConfiguration->warmupAfrThreshold) {
		if (rpm < 200) {
			cltFuelCorrection = 1;
			warmupAfrPid.reset();
		} else {
			cltFuelCorrection = warmupAfrPid.getValue(warmupTargetAfr, engine->sensors.currentAfr, 1);
		}
#if ! EFI_UNIT_TEST || defined(__DOXYGEN__)
		if (engineConfiguration->debugMode == DBG_WARMUP_ENRICH) {
			tsOutputChannels.debugFloatField1 = warmupTargetAfr;
			warmupAfrPid.postState(&tsOutputChannels);
		}
#endif

	} else {
		cltFuelCorrection = getCltFuelCorrection(PASS_ENGINE_PARAMETER_SIGNATURE);
	}

	// update fuel consumption states
	fuelConsumption.update(nowNt PASS_ENGINE_PARAMETER_SUFFIX);

	// Fuel cut-off isn't just 0 or 1, it can be tapered
	fuelCutoffCorrection = getFuelCutOffCorrection(nowNt, rpm PASS_ENGINE_PARAMETER_SUFFIX);
	
	// post-cranking fuel enrichment.
	// for compatibility reasons, apply only if the factor is greater than zero (0.01 margin used)
	if (engineConfiguration->postCrankingFactor > 0.01f) {
		// convert to microsecs and then to seconds
		float timeSinceCrankingInSecs = NT2US(timeSinceCranking) / 1000000.0f;
		// use interpolation for correction taper
		postCrankingFuelCorrection = interpolateClamped(0.0f, engineConfiguration->postCrankingFactor, 
			engineConfiguration->postCrankingDurationSec, 1.0f, timeSinceCrankingInSecs);
	} else {
		postCrankingFuelCorrection = 1.0f;
	}

	cltTimingCorrection = getCltTimingCorrection(PASS_ENGINE_PARAMETER_SIGNATURE);

	engineNoiseHipLevel = interpolate2d("knock", rpm, engineConfiguration->knockNoiseRpmBins,
					engineConfiguration->knockNoise, ENGINE_NOISE_CURVE_SIZE);

	baroCorrection = getBaroCorrection(PASS_ENGINE_PARAMETER_SIGNATURE);

	injectionOffset = getinjectionOffset(rpm PASS_ENGINE_PARAMETER_SUFFIX);
	float engineLoad = getEngineLoadT(PASS_ENGINE_PARAMETER_SIGNATURE);
	timingAdvance = getAdvance(rpm, engineLoad PASS_ENGINE_PARAMETER_SUFFIX);

	if (engineConfiguration->fuelAlgorithm == LM_SPEED_DENSITY) {
		float coolantC = ENGINE(sensors.clt);
		float intakeC = ENGINE(sensors.iat);
		float tps = getTPS(PASS_ENGINE_PARAMETER_SIGNATURE);
		tChargeK = convertCelsiusToKelvin(getTCharge(rpm, tps, coolantC, intakeC PASS_ENGINE_PARAMETER_SUFFIX));
		float map = getMap();

		/**
		 * *0.01 because of https://sourceforge.net/p/rusefi/tickets/153/
		 */
		float rawVe = veMap.getValue(rpm, map);
		// get VE from the separate table for Idle
		if (CONFIG(useSeparateVeForIdle)) {
			float idleVe = interpolate2d("idleVe", rpm, config->idleVeBins, config->idleVe, IDLE_VE_CURVE_SIZE);
			// interpolate between idle table and normal (running) table using TPS threshold
			rawVe = interpolateClamped(0.0f, idleVe, boardConfiguration->idlePidDeactivationTpsThreshold, rawVe, tps);
		}
		currentVE = baroCorrection * rawVe * 0.01;
		targetAFR = afrMap.getValue(rpm, map);
	} else {
		baseTableFuel = getBaseTableFuel(rpm, engineLoad);
	}
}
Exemple #28
0
void EngineState::periodicFastCallback(DECLARE_ENGINE_PARAMETER_F) {
	int rpm = ENGINE(rpmCalculator.rpmValue);

	efitick_t nowNt = getTimeNowNt();
	if (isCrankingR(rpm)) {
		crankingTime = nowNt;
	} else {
		timeSinceCranking = nowNt - crankingTime;
	}

	sparkDwell = getSparkDwell(rpm PASS_ENGINE_PARAMETER);
	dwellAngle = sparkDwell / getOneDegreeTimeMs(rpm);

	// todo: move this into slow callback, no reason for IAT corr to be here
	iatFuelCorrection = getIatCorrection(iat PASS_ENGINE_PARAMETER);
	// todo: move this into slow callback, no reason for CLT corr to be here
	if (boardConfiguration->useWarmupPidAfr && clt < engineConfiguration->warmupAfrThreshold) {
		if (rpm < 200) {
			cltFuelCorrection = 1;
			warmupAfrPid.reset();
		} else {
			cltFuelCorrection = warmupAfrPid.getValue(warmupTargetAfr, getAfr(PASS_ENGINE_PARAMETER_F), 1);
		}
#if ! EFI_UNIT_TEST || defined(__DOXYGEN__)
		if (engineConfiguration->debugMode == WARMUP_ENRICH) {
			tsOutputChannels.debugFloatField1 = warmupTargetAfr;
			warmupAfrPid.postState(&tsOutputChannels);
		}
#endif

	} else {
		cltFuelCorrection = getCltFuelCorrection(clt PASS_ENGINE_PARAMETER);
	}

	cltTimingCorrection = getCltTimingCorrection(clt PASS_ENGINE_PARAMETER);

	engineNoiseHipLevel = interpolate2d(rpm, engineConfiguration->knockNoiseRpmBins,
					engineConfiguration->knockNoise, ENGINE_NOISE_CURVE_SIZE);

	baroCorrection = getBaroCorrection(PASS_ENGINE_PARAMETER_F);

	injectionOffset = getinjectionOffset(rpm PASS_ENGINE_PARAMETER);
	float engineLoad = getEngineLoadT(PASS_ENGINE_PARAMETER_F);
	timingAdvance = getAdvance(rpm, engineLoad PASS_ENGINE_PARAMETER);

	if (engineConfiguration->fuelAlgorithm == LM_SPEED_DENSITY) {
		float coolantC = ENGINE(engineState.clt);
		float intakeC = ENGINE(engineState.iat);
		float tps = getTPS(PASS_ENGINE_PARAMETER_F);
		tChargeK = convertCelsiusToKelvin(getTCharge(rpm, tps, coolantC, intakeC PASS_ENGINE_PARAMETER));
		float map = getMap();

		/**
		 * *0.01 because of https://sourceforge.net/p/rusefi/tickets/153/
		 */
		currentVE = baroCorrection * veMap.getValue(rpm, map) * 0.01;
		targetAFR = afrMap.getValue(rpm, map);
	} else {
		baseTableFuel = getBaseTableFuel(engineConfiguration, rpm, engineLoad);
	}

}
Exemple #29
0
int main(int argc, char* argv[]){
	char originalmap[SIZE][SIZE], mymap[SIZE][SIZE], enemymap[SIZE][SIZE], t, *msg, *req_name, ships[NSHIPS];
	char tosink, *cmd = NULL, *username = NULL, *opponent_name = NULL, turno = IDLE, fine = 0, ip[16];
	const int STDIN = fileno(stdin);
	int fdmax, server, udp, i = 1;
	sizetype len;
	unsigned short port;
	fd_set masterset,readset;
	struct sockaddr_in opponent, src;
	struct timeval timer;
	FD_ZERO(&masterset);
	memset(originalmap, WATER, SIZE * SIZE);
	if(argc != 3){
		printf("Usage: seafight_client <host remoto> <porta>\n");
		exit(EXIT_FAILURE);
	}
	system("clear");
	printf("SEAFIGHT CLIENT\n\n");
	//connessione al server
	if((server = socket(PF_INET, SOCK_STREAM, 0)) == -1){
		perror("errore nella creazione del socket TCP");
		exit(EXIT_FAILURE);
	}
	if(strcmp(argv[1], "localhost") == 0)
		strcpy(ip, "127.0.0.1");
	else
		strcpy(ip, argv[1]);
	memset(&opponent, 0, sizeof(struct sockaddr_in));
	opponent.sin_family = AF_INET;
	opponent.sin_port = htons(atoi(argv[2]));
	inet_pton(AF_INET, ip, &opponent.sin_addr.s_addr);
	if(connect(server, (struct sockaddr*)&opponent, sizeof(struct sockaddr_in)) == -1){
		perror("errore nella connessione al server");
		exit(EXIT_FAILURE);
	}
	//connessione avvenuta, richiesta ed invio di nome e porta
	printf("Connessione al server %s:%s effettuata con successo\n\n", argv[1], argv[2]);
	printf("Sono disponibili i seguenti comandi:\n * !help --> mostra l'elenco dei comandi disponibi");
	printf("li\n * !who --> mostra l'elenco dei client connessi al server\n * !connect nome_client -");
	printf("-> avvia una partita con l'utente nome_client\n * !disconnect --> disconnette il client ");
	printf("dall'attuale partita\n * !quit --> disconnette il client dal server\n * !show_enemy_map ");
	printf("--> mostra la mappa dell'avversario\n * !show_my_map --> mostra la propria mappa\n * !se");
	printf("t_map --> reimposta la mappa\n * !hit <coordinates> --> esegue un'attacco\n * !chat mess");
	printf("aggio> --> invia un messaggio di chat all'avversario\n\nInserisci il tuo nome: ");
	do
		len = readLine(&username);
	while(len == 0);
	printf("Inserisci la porta udp di ascolto: ");
	scanf("%hd", &port);
	flush();
	//creazione socket udp
	if((udp = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
		perror("errore nella creazione del socket udp");
		exit(EXIT_FAILURE);
	}
	memset(&opponent, 0, sizeof(struct sockaddr_in));
	opponent.sin_family = AF_INET;
	opponent.sin_port = htons(port);
	opponent.sin_addr.s_addr = htonl(INADDR_ANY);
	while(bind(udp, (struct sockaddr*) &opponent, sizeof(struct sockaddr_in)) == -1){
		switch(errno){
			case EADDRINUSE: //porta già in uso
				printf("La porta scelta è occupata, sceglierne un'altra: ");
				scanf("%hd", &port);
				flush();
				opponent.sin_port = htons(port);
				break;
			case EACCES:
				printf("Non hai i permessi per quella porta, prova una porta superiore a 1023: ");
				scanf("%hd", &port);
				flush();
				opponent.sin_port = htons(port);
				break;
			default:
				perror("errore non gestito nel bind del socket udp");
				exit(EXIT_FAILURE);
		}
	}
	getMap(originalmap);
	ships[0]=6;ships[1]=4;ships[2]=4;ships[3]=3;ships[4]=3;
	ships[5]=3;ships[6]=2;ships[7]=2;ships[8]=2;ships[9]=2;
/*	ships = (char[]){6,4,4,3,3,3,2,2,2,2};*/
	memcpy(mymap, originalmap, SIZE*SIZE);
	len += 1 + sizeof(unsigned short);
	msg = malloc(len);
	msg[0] = SETNAME;
	*(unsigned short*)(msg + 1) = port;
	strcpy(msg + 1 + sizeof(unsigned short), username);
	len = sendObject(server, msg, len, 0);
	if(len > 0)
		len = recvObject(server, (void**)&cmd);
	else{
		printf("Il server non e' piu' disponibile...\n");
		free(msg);
		free(cmd);
		free(username);
		close(server);
		return 0;
	}
	while(*cmd != NAMEOK){
		printf("Il nome e' gia' in uso, scegline un altro: ");
		do
			len = readLine(&username);
		while(len == 0);
		len += 1 + sizeof(unsigned short);
		msg = realloc(msg, len);
		strcpy(msg + 1 + sizeof(unsigned short), username);
		len = sendObject(server, msg, len, 0);
		if(len > 0)
			len = recvObject(server, (void**)&cmd);
		else{
			printf("Il server non e' piu' disponibile...\n");
			free(msg);
			free(cmd);
			free(username);
			close(server);
			return 0;
		}
	}
	free(cmd);
	free(msg);
	//preparazione dei fd_set per la select
	FD_SET(server, &masterset);
	FD_SET(STDIN, &masterset);
	if(server >= STDIN)
		fdmax = server;
	else
		fdmax = STDIN;

	while(!fine){
		if(turno == HISTURN || turno == MYTURN)
			printf("# ");
		else
			printf("> ");
		fflush(stdout);
		readset = masterset;
		if(turno == HISTURN || turno == MYTURN)
			i = select(fdmax+1, &readset, NULL, NULL, &timer);
		else
			i = select(fdmax+1, &readset, NULL, NULL, NULL);
		if(i == -1){
			perror("errore nella select");
			free(username);
			free(opponent_name);
			close(server);
			close(udp);
			exit(EXIT_FAILURE);
		}
		else if(i == 0){
			//è scaduto il timer
			if(turno == MYTURN)
				printf("\rE' passato un minuto dal tuo ultimo comando inviato... HAI PERSO!\n\n");
			else
				printf("\rL'avversario non risponde da piu' di un minuto... HAI VINTO!\n\n");
			turno = IDLE;
			memcpy(mymap, originalmap, SIZE*SIZE);
			FD_CLR(udp, &masterset);
			if(udp == fdmax){
				if(server >= STDIN)
					fdmax = server;
				else
					fdmax = STDIN;
			}
			cmd = malloc(2);
			cmd[0] = DISCONNECT;
			cmd[1] = '\0';
			if(sendObject(server, cmd, 2, 0) == -1){
				perror("!timeout_disconnect: errore nel contattare il server");
				free(cmd);
				free(username);
				free(opponent_name);
				close(server);
				close(udp);
				exit(EXIT_FAILURE);
			}
			free(cmd);
		}
		else
			for(i = 0; i <= fdmax; i++){
				if(FD_ISSET(i, &readset)){
					//ricevuto comando da tastiera
					if(i == STDIN && readLine(&cmd) != 0){
						t = parseCommand(&cmd);
						switch(t){
							case HELP:
								if(turno == IDLE){ //non sono impegnato in una partita
									printf("Sono disponibili i seguenti comandi:\n * !help --> mostr");
									printf("a l'elenco dei comandi disponibili\n * !who --> mostra l");
									printf("'elenco dei client connessi al server\n * !connect nome_");
									printf("client --> avvia una partita con l'utente nome_client\n ");
									printf("* !quit --> disconnette il client dal server\n * !set_ma");
									printf("p --> reimposta la mappa\n * !show_my_map --> mostra la ");
									printf("propria mappa\n");
								}
								else{
									printf("Sono disponibili i seguenti comandi:\n * !help --> mostr");
									printf("a l'elenco dei comandi disponibili\n * !who --> mostra l");
									printf("'elenco dei client connessi al server\n * !disconnect --");
									printf("> disconnette il client dall'attuale partita\n * !quit -");
									printf("-> disconnette il client dal server\n * !show_enemy_map ");
									printf("--> mostra la mappa dell'avversario\n * !show_my_map -->");
									printf(" mostra la propria mappa\n * !hit <coordinates> --> eseg");
									printf("ue un'attacco\n * !chat <messaggio> --> invia un messagg");
									printf("io di chat all'avversario\n");
								}
								break;
							case WHO: //invio WHO'\0'
								if(sendObject(server, cmd, 2, 0) == -1){
									perror("!who: errore nel contattare il server");
									free(cmd);
									free(username);
									free(opponent_name);
									close(server);
									close(udp);
									exit(EXIT_FAILURE);
								}
								break;
							case CONNECT: //invio CONNECT'<nome_client>\0'
								if(turno == IDLE){
									if(strcmp(username, cmd + 1) == 0)
										printf("Non puoi iniziare una partita con te stesso!\n");
									else{
										if(sendObject(server, cmd, strlen(cmd) + 1, 0) == -1){
											perror("!connect: errore nel contattare il server");
											free(cmd);
											free(username);
											free(opponent_name);
											close(server);
											close(udp);
											exit(EXIT_FAILURE);
										}
										turno = WFM;
									}
								}
								else{
									printf("Sei impegnato in una partita, se vuoi iniziarne un'altra");
									printf(" devi prima interrompere questa (!disconnect)\n");
								}
								break;
							case DISCONNECT: //invio DISCONNECT'\0'
								if(turno == MYTURN || turno == HISTURN){
									//sono in partita
									if(sendObjectTo(udp, opponent, cmd, 2) == -1)
										perror("!disconnect: errore nel contattare l'avversario.");
									if(sendObject(server, cmd, 2, 0) == -1){
										perror("!disconnect: errore nel contattare il server.");
										free(cmd);
										free(username);
										free(opponent_name);
										close(server);
										close(udp);
										exit(EXIT_FAILURE);
									}
									printf("Partita interrotta: HAI PERSO!\n\n");
									turno = IDLE;
									memcpy(mymap, originalmap, SIZE*SIZE);
								}
								else if(turno == WFM){
									//voglio annullare la richiesta di connessione
									if(sendObject(server, cmd, 2, 0) == -1){
										perror("!disconnect: errore nel contattare l'avversario.");
										free(cmd);
										free(username);
										free(opponent_name);
										close(server);
										close(udp);
										exit(EXIT_FAILURE);
									}
									printf("Richiesta annullata.\n");
									turno = IDLE;
								}
								else{
									printf("Non sei impegnato in nessuna partita, per disconnetterti");
									printf(" dal server usa !quit\n");
								}
								break;
							case QUIT: //invio QUIT'\0 oppure 'DISCONNECT'\0', DISCONNECT'\0', QUIT'\0'
								if(turno == IDLE){
									if(sendObject(server, cmd, 2, 0) == -1)
										perror("!quit: errore nel contattare il server");
								}
								else{ //se sono in una partita mando prima disconnect
									cmd[0] = DISCONNECT;
									if(sendObject(server, cmd, 2, 0) == -1)
										perror("!disconnect: errore nel contattare il server");
									if(sendObjectTo(udp, opponent, cmd, 2) == -1)
										perror("!disconnect: errore nel contattare l'avversario");
									cmd[0] = QUIT;
									if(sendObject(server, cmd, 2, 0) == -1)
										perror("!quit: errore nel contattare il server");
								}
								fine = 1;
								break;
							case ENEMYMAP:
								if(turno == HISTURN || turno == MYTURN)
									printMap(enemymap);
								else
									printf("Non sei impegnato in nessuna partita.\n");
								break;
							case MYMAP:
								printMap(mymap);
								break;
							case HIT:
								switch(turno){
									case IDLE: case WFM:
										printf("Non sei impegnato in nessuna partita.\n");
										break;
									case HISTURN:
										printf("Attendi il tuo turno...\n");
										break;
									case MYTURN:
										if(sendObjectTo(udp, opponent, cmd, 4) == -1)
											perror("!hit: errore nell'invio dell'attacco");
										break;
								}
								break;
							case CHAT:
								if(turno == IDLE || turno == WFM){
									printf("Non sei impegnato in nessuna partita, non puoi inviare");
									printf(" messaggi di chat.\n");
								}
								else
									if(sendObjectTo(udp, opponent, cmd, strlen(cmd) + 1) == -1)
										perror("errore durante l'invio di un messaggio di chat");
								break;
							case ERR:
								printf("Comando non valido, digita !help per la lista dei comandi.\n");
								break;
							case SETMAP:
								if(turno == IDLE){
									memset(originalmap, WATER, SIZE * SIZE);
									getMap(originalmap);
									memcpy(mymap, originalmap, SIZE*SIZE);
								}
								else
									printf("Non puoi cambiare la tua mappa mentre sei in partita.\n");
								break;
						}
						free(cmd);
					}//endif comandi da tastiera
					else if(i == server){ //ricevuto un messaggio dal server
						len = recvObject(i, (void**)&cmd); //richiesta da un giocatore
						if(len == 0){ //il server ha chiuso il socket
							printf("\rIl server non e' più disponibile...\n");
							free(username);
							free(opponent_name);
							close(udp);
							close(server);
							exit(EXIT_FAILURE);
						}
						switch(*cmd){
							case UNKNOWN: //nome utente non valido
								if(turno == WFM){
									printf("\rImpossibile connettersi a %s:", cmd + 1);
									printf(" utente inesistente.\n");
									turno = IDLE;
								}
								break;
							case BUSY: //utente occupato
								if(turno == WFM){
									printf("\rImpossibile connettersi a %s:", cmd +1);
									printf(" utente impegnato in un'altra partita.\n");
									turno = IDLE;
								}
								break;
							case ACCEPTED: //l'utente ha accettato la partita
								//salvo l'indirizzo e il nome
								if(turno == WFM){
									opponent = *(struct sockaddr_in*)(cmd + 1);
									free(opponent_name);
									opponent_name = malloc(strlen(cmd+1+sizeof(struct sockaddr_in))+1);
									strcpy(opponent_name, cmd + 1 + sizeof(struct sockaddr_in));
									printf("\r%s ha accettato la partita.\n", opponent_name);
									//inizializzo le variabili di partita e invio STARTMATCH
									free(cmd);
									cmd = malloc(2);
									ships[0]=6;ships[1]=4;ships[2]=4;ships[3]=3;ships[4]=3;
									ships[5]=3;ships[6]=2;ships[7]=2;ships[8]=2;ships[9]=2;
									cmd[0] = STARTMATCH;
									cmd[1] = '\0';
									sendObjectTo(udp, opponent, cmd, 2);
									printf("\rPartita avviata con %s.", opponent_name);
									printf("\n\nE' il tuo turno.\n");
									turno = MYTURN;
									tosink = NSHIPS;
									timer = TIMER;
									memset(enemymap, WATER, SIZE * SIZE);
									FD_SET(udp, &masterset);
									if(udp > fdmax)
										fdmax = udp;
								}
								break;
							case REQUEST://REQUEST<sockaddr_in><nome> l'utente ha richiesto una partita
								if(turno == IDLE){
									req_name = cmd + 1 + sizeof(struct sockaddr_in);
									printf("\rL'utente %s vuole avviare una partita con te", req_name);
									printf(", vuoi accettare? [s/n] ");
									do
										scanf(" %c", &t);
									while(t != 'S' && t != 's' && t != 'N' && t != 'n');
									flush();
									len = strlen(req_name) + 2;
									msg = malloc(len);
									strcpy(msg + 1, req_name);
									if(t == 'S' || t == 's'){ //partita accettata
										turno = WFM;
										*msg = ACCEPTED;
										if(sendObject(server, msg, len, 0) == -1){
											perror("accepted: errore nel contattare il server");
											free(msg);
											free(cmd);
											free(username);
											free(opponent_name);
											close(server);
											close(udp);
											exit(EXIT_FAILURE);
										}
										//salvo l'indirizzo e il nome
										opponent = *(struct sockaddr_in*)(cmd + 1);
										free(opponent_name);
										opponent_name = malloc(strlen(req_name) + 1);
										strcpy(opponent_name, req_name);
										//inizializzo le variabili di partita
										memset(enemymap, WATER, SIZE * SIZE);
										tosink = NSHIPS;
										FD_SET(udp, &masterset);
										if(udp > fdmax)
											fdmax = udp;
									}
									else{ //partita rifiutata
										printf("Partita rifiutata.\n");
										*msg = REFUSED;
										if(sendObject(server, msg, len, 0) == -1){
											perror("accepted: errore nel contattare il server");
											free(msg);
											free(cmd);
											free(username);
											free(opponent_name);
											close(server);
											close(udp);
											exit(EXIT_FAILURE);
										}
									}
									free(msg);
								}
								break;
							case DENIED: //l'utente ha rifiutato la partita
								if(turno == WFM){
									printf("\rImpossibile connettersi a %s:", cmd + 1);
									printf(" l'utente ha rifiutato la partita.\n");
									turno = IDLE;
								}
								break;
							case WHO: //ricevuta lista degli utenti
								printf("\rClient connessi al server:\n%s", cmd + 1);
								break;
							case QUIT:
								//stavo giocando
								printf("\r");
								if(turno == MYTURN || turno == HISTURN){
									printf("L'avversario ha chiuso il socket inaspettatamente...");
									printf("HAI VINTO\n\n");
									turno = IDLE;
									memcpy(mymap, originalmap, SIZE*SIZE);
									FD_CLR(udp, &masterset);
									if(udp == fdmax){
										if(server >= STDIN)
											fdmax = server;
										else
											fdmax = STDIN;
									}
									break;
								}
								//ero in fase di connessione
								else if(turno != IDLE){
									printf("\rIl server non riesce a contattare l'avversario\n");
									turno = IDLE;
									FD_CLR(udp, &masterset);
									if(udp == fdmax){
										if(server >= STDIN)
											fdmax = server;
										else
											fdmax = STDIN;
									}
								}
								break;
						}
						free(cmd);
					}//endif messaggio dal server
					else{ //ricevuto un messaggio dall'avversario
						len = recvObjectFrom(udp, &src, (void**)&cmd);
						if(src.sin_addr.s_addr != opponent.sin_addr.s_addr)
							printf("\rRicevuto messaggio da un giocatore che non e' l'avversario\n");
						else{
							switch(*cmd){
								case HIT:
									if(turno == HISTURN){
										printf("\rRicevuto attacco in %c%hhd: ", cmd[1] + 'A', cmd[2]);
										t = mymap[(int)cmd[1]][(int)cmd[2]];
										cmd = realloc(cmd, 5);
										*cmd = REPLY;
										cmd[4] = '\0';
										if(t != HITW && t != WATER){
											printf("colpita!\n");
											cmd[3] = mymap[(int)cmd[1]][(int)cmd[2]] = HITS;
											if(t >= 0 &&  t < NSHIPS){
												//ho preso una barca non già colpita
												if(--ships[(int)t] == 0){
													//l'ho affondata
													if(--tosink == 0)
													// se mi ha affondato tutte le navi lo comunico
														cmd[3] = WIN;
													else
														cmd[3] = SUNK;
													printf("La nave %hhd e' stata affondata.\n", t);
												}
											}
										}
										else{
											printf("acqua!\n");
											cmd[3] = mymap[(int)cmd[1]][(int)cmd[2]] = HITW;
										}
										sendObjectTo(udp, opponent, cmd, 5);
										if(tosink == 0){
											printf("La tua ultima nave e' stata affondata...");
											printf(" HAI PERSO!\n\n");
											msg = malloc(2);
											msg[0] = DISCONNECT;
											msg[1] = '\0';
											if(sendObject(server, msg, 2, 0) == -1){
												perror("!hit_lost: errore nel contattare il server");
												free(cmd);
												free(msg);
												free(username);
												free(opponent_name);
												close(server);
												close(udp);
												exit(EXIT_FAILURE);
											}
											free(msg);
											turno = IDLE;
											memcpy(mymap, originalmap, SIZE*SIZE);
										}
										else{
											turno = MYTURN;
											timer = TIMER;
											printf("\nE' il tuo turno.\n");
										}
									}
									break;
								case CHAT:
									if(turno != IDLE && turno != WFM)
										printf("\r%s: %s\n", opponent_name, cmd + 1);
									break;
								case REPLY:
									if(turno == MYTURN){
										turno = HISTURN;
										timer = TIMER;
										printf("\rAttacco in %c%hhd: ", cmd[1] + 'A', cmd[2]);
										switch(cmd[3]){
											case HITW:
												printf("acqua!\n");
												break;
											case HITS:
												printf("colpita!\n");
												break;
											case SUNK:
												printf("colpita e affondata!\n");
												break;
											case WIN:
												printf("colpita e affondata!\nHai affondato ");
												printf("l'ultima nave avversaria... HAI VINTO!\n\n");
												turno = IDLE;
												memcpy(mymap, originalmap, SIZE*SIZE);
												msg = malloc(2);
												msg[0] = DISCONNECT;
												msg[1] = '\0';
												if(sendObject(server, msg, 2, 0) == -1){
													perror("!win: errore nel contattare il server");
													free(cmd);
													free(msg);
													free(username);
													free(opponent_name);
													close(server);
													close(udp);
													exit(EXIT_FAILURE);
												}
												free(msg);
												break;
										}
										if(enemymap[(int)cmd[1]][(int)cmd[2]] == cmd[3])
											printf("Avevi gia' scelto quel bersaglio!\n");
										else if(cmd[3] == SUNK)
											enemymap[(int)cmd[1]][(int)cmd[2]] = HITS;
										else
											enemymap[(int)cmd[1]][(int)cmd[2]] = cmd[3];
										if(turno != IDLE)
											printf("\nE' il turno di %s\n", opponent_name);
									}
									break;
								case DISCONNECT:
									if(turno == MYTURN || turno == HISTURN){
										if(sendObject(server, cmd, 2, 0) == -1)
											perror("disconnect: errore nel contattare il server");
										turno = IDLE;
										memcpy(mymap, originalmap, SIZE*SIZE);
										printf("%s si e' arreso, HAI VINTO!\n\n", opponent_name);
										FD_CLR(udp, &masterset);
										if(udp == fdmax){
											if(server >= STDIN)
												fdmax = server;
											else
												fdmax = STDIN;
										}
									}
									break;
								//serve per evitare che mi dica partita avviata e poi partita conclusa
								//nel caso in cui lui faccia !connect, !disconnect
								case STARTMATCH:
									if(turno == WFM){
										printf("\rPartita avviata con %s.\n", opponent_name);
										printf("\nE' il turno di %s.\n", opponent_name);
										turno = HISTURN;
										timer = TIMER;
										memcpy(mymap, originalmap, SIZE*SIZE);
										ships[0]=6;ships[1]=4;ships[2]=4;ships[3]=3;ships[4]=3;
										ships[5]=3;ships[6]=2;ships[7]=2;ships[8]=2;ships[9]=2;
									}
									break;
							}
							free(cmd);
						}
					}//endif messaggio dall'avversario
				}
			}
	}
	free(opponent_name);
	free(username);
	close(udp);
	close(server);
	return 0;
}
Exemple #30
0
KeyMap::KeyMap(Model _keyModel, Layout _keyLayout) :
    _keys(getMap(_keyModel, _keyLayout)),
    keyWidth(_keyModel == K95 ? K95_WIDTH : _keyModel == K70 ? K70_WIDTH : _keyModel == K65 ? K65_WIDTH : _keyModel == M65 ? M65_WIDTH : 0),
    keyHeight(_keyModel == K95 || _keyModel == K70 || _keyModel == K65 ? K95_HEIGHT : _keyModel == M65 ? M65_HEIGHT : 0),
    keyModel(_keyModel), keyLayout(_keyLayout)
{}