Exemplo n.º 1
0
LocalCorePolPotential::Return_t
LocalCorePolPotential::evaluate(ParticleSet& P)
{
  if(FirstTime)
  {
    //index for attribute charge
    SpeciesSet& Species(IonConfig.getSpeciesSet());
    int iz = Species.addAttribute("charge");
    //calculate the Core-Core Dipole matrix
    for(int iat=0; iat<nCenters; iat++)
    {
      for(int nn=d_ii->M[iat]; nn<d_ii->M[iat+1]; nn++)
      {
        int jat(d_ii->J[nn]);
        RealType rinv3 = std::pow(d_ii->rinv(nn),3);//(1/R_{JI}^3) R_{JI} = R_J-R_I
        PosType dipole(rinv3*d_ii->dr(nn));//(\vec{R_{JI}}/R_{JI}^3)
        //Sign and the charge of the paired ion are taken into account here
        CoreCoreDipole[iat] -= dipole*Species(iz,IonConfig.GroupID[jat]);
        CoreCoreDipole[jat] += dipole*Species(iz,IonConfig.GroupID[iat]);
      }
    }
    RealType corecore(0.0);
    for(int iat=0; iat<nCenters; iat++)
    {
      //app_log() << "Checking CPP = " << Centers[iat] << endl;
      if(Centers[iat])
        corecore+= Centers[iat]->C*dot(CoreCoreDipole[iat],CoreCoreDipole[iat]);
    }
//      LOGMSG("Core-Core Dipole = " << corecore);
    FirstTime=false;
  }
  //calculate the Electron-Core Dipole matrix
  //CoreElDipole=0.0;
  RealType e = 0.0;
  for(int iat=0; iat<nCenters; iat++)
  {
    if(Centers[iat])
    {
      PosType cc(CoreCoreDipole[iat]);
      for(int nn=d_ie->M[iat]; nn<d_ie->M[iat+1]; nn++)
      {
        int eid(d_ie->J[nn]);
        RealType rinv3 = std::pow(d_ie->rinv(nn),3);//(1/r^3)
        PosType dipole = rinv3*d_ie->dr(nn);//(\vec{r}/r^3)
        //cc +=  dipole*fcpp(d_ie->r(nn)*r_binv);
        cc += dipole*((*Centers[iat])(d_ie->r(nn)));
      }
      e += Centers[iat]->C*dot(cc,cc);
    }
  }
  return Value=e;
}
Exemplo n.º 2
0
 OrbitalBase* PadeConstraints::createOneBody(ParticleSet& source) {
   app_log() << "  PadeBuilder::Adding Pade One-Body Jastrow with effective ionic charges." << endl;
   typedef OneBodyJastrow<FuncType> JneType;
   JneType* J1 = new JneType(source,targetPtcl);
   SpeciesSet& Species(source.getSpeciesSet());
   int ng=Species.getTotalNum();
   int icharge = Species.addAttribute("charge");
   for(int ig=0; ig<ng; ig++) {
     RealType zeff=Species(icharge,ig);
     app_log() << "    " << Species.speciesName[ig] <<  " Zeff = " << zeff << endl;
     FuncType *func=new FuncType(-zeff,B,std::pow(2*zeff,0.25));
     J1->addFunc(ig,func);
     FuncList.push_back(func);
   }
   return J1;
 }
Exemplo n.º 3
0
noAnimal::noAnimal(SerializedGameData* sgd, const unsigned obj_id) : noMovable(sgd, obj_id),
    species(Species(sgd->PopUnsignedChar())),
    state(State(sgd->PopUnsignedChar())),
    pause_way(sgd->PopUnsignedShort()),
    hunter(sgd->PopObject<nofHunter>(GOT_NOF_HUNTER)),
    sound_moment(0)
{
}
Exemplo n.º 4
0
 NumberLogger(const std::vector<std::string>& species)
 {
     targets.reserve(species.size());
     for (std::vector<std::string>::const_iterator i(species.begin());
         i != species.end(); ++i)
     {
         targets.push_back(Species(*i));
     }
 }
Exemplo n.º 5
0
    const Species& get_parameter(const Species::serial_type& name) const
    {
        parameter_container_type::const_iterator i(
            std::find(parameters_.begin(), parameters_.end(), Species(name)));
        if (i != parameters_.end())
        {
            return (*i);
        }

        throw NotFound("Parameter not found.");
    }
Exemplo n.º 6
0
void Phase::addSpecies(const std::string& name_, const doublereal* comp,
                       doublereal charge_, doublereal size_)
{
    compositionMap cmap;
    for (size_t i = 0; i < nElements(); i++) {
        if (comp[i]) {
            cmap[elementName(i)] = comp[i];
        }
    }
    Phase::addSpecies(Species(name_, cmap, 0, charge_, size_));
}
Exemplo n.º 7
0
int Database::saveSession(Sessions session)
{
    int decoderId = this->userExist(session.getDecoder());
    if(decoderId == 0){
        decoderId = this->insertUser(Users(session.getDecoder()));
        if(decoderId <= 0) return -1;
        this->cacheUserId.insert(session.getDecoder().toString(),decoderId);
    }
    int observerId = this->userExist(session.getObserver());
    if(observerId == 0){
        observerId = this->insertUser(Users(session.getObserver()));
        if(observerId <= 0) return -2;
        this->cacheUserId.insert(session.getObserver().toString(),observerId);
    }
    int specieId = this->specieExist(session.getSpecies());
    if (specieId == 0){
        specieId = this->insertSpecie(Species(session.getSpecies()));
        if (specieId <= 0) return -2;
    }
    int subjectId = this->subjectExist(session.getSubject());
    if (subjectId == 0){
        Subjects s;
        s.setName(session.getSubject());
        subjectId = this->insertSubject(s);
        if (subjectId <= 0) return -2;
    }

    int sessionId = this->insertSession(decoderId, session.getDateDecoding(),
                                        observerId, subjectId, specieId,
                                        session.getDateSession(), session.getDescription());
    if(sessionId <= 0) return -3;
    QList<Actions> sequence = session.getActions();
    for(int s=0; s < sequence.size(); s++){
        Actions action = sequence.at(s);
        int stateId = this->stateExist(action.getStateDescription());
        if(stateId == 0){
            stateId = this->insertState(States(action.getStateDescription()));
            if(stateId <= 0) return -4;
            this->cacheStateId.insert(action.getStateDescription(),stateId);
        }
        int eventId = this->eventExist(action.getEventDescription());
        if(eventId == 0){
            eventId = this->insertEvent(Events(action.getEventDescription()));
            if(eventId <= 0) return -5;
            this->cacheEventId.insert(action.getEventDescription(),eventId);
        }
        if(this->insertAction(action.getTimeAction(), sessionId, stateId, eventId) <= 0) return -6;
    }
//    qDebug() << this->query.lastQuery();
//    qDebug() << this->query.lastError();
//    qDebug() << sessionId;
    return sessionId;
}
Exemplo n.º 8
0
int Database::editSession(Sessions session)
{
    int observerId = this->userExist(session.getObserver());
    if(observerId == 0){
        observerId = this->insertUser(Users(session.getObserver()));
        if(observerId <= 0) return -2;
        this->cacheUserId.insert(session.getObserver().toString(),observerId);
    }
    QVariant specieId = session.getSpecies();
    if(session.getSpecies().type() == QVariant::String){
        specieId = this->specieExist(session.getSpecies());
        if (specieId==0){
            specieId = this->insertSpecie(Species(session.getSpecies()));
            if (specieId <=0) return -2;
        }
    }
    if(specieId <= 0) return -1;
    QVariant subjectId = session.getSubject();
    if(session.getSubject().type() == QVariant::String){
        subjectId = this->subjectExist(session.getSubject());
        if (subjectId==0){
            subjectId = this->insertSubject(session.getSubject());
            if (subjectId <=0) return -2;
        }
    }
    if(subjectId <= 0) return -1;
    this->query.prepare("UPDATE Sessions SET observer = :observer, subject = :subject, specie = :specie, description = :description "
                        "WHERE id = :id;");
    this->query.bindValue(":observer",observerId);
    this->query.bindValue(":subject",subjectId);
    this->query.bindValue(":specie",specieId);
    this->query.bindValue(":description",session.getDescription());
    this->query.bindValue(":id",session.getId());
    if(!this->query.exec()){
        this->showError(this->query.lastError());
        return -1;
    }
    return 0;
}
bool Manager::addSpeciesToList(string name, float initial_value){

    if(this->isSpeciesInList(name)){
        std::cerr<<"Species already exists in the list"<<std::endl;
        return false;
    }
    else{
        Species *new_tab= this->newTabAllocation(this->species_list_size+1);

        for(int i = 0; i<this->species_list_size; i++)
        {
            new_tab[i] = this->species_list[i];
        }
        new_tab[this->species_list_size] = Species(name,initial_value);
        this->species_list_size++;

        delete[] this->species_list;
        this->species_list = new_tab;
        return true;
    }

}
Exemplo n.º 10
0
OptionsFormDialogBox::OptionsFormDialogBox(FXComposite *parent) : 
    FXDialogBox(parent, "Sim Options", DECOR_TITLE | DECOR_BORDER)
{
    FXMatrix *LayoutMatrix = new FXMatrix(this, 1, MATRIX_BY_COLUMNS |
        LAYOUT_FILL_X | LAYOUT_FILL_Y | LAYOUT_FILL_ROW | LAYOUT_FILL_COLUMN,
        0,0,0,0,
        0,0,0,0);
    
    FXTabBook *tabbook=new FXTabBook(LayoutMatrix,NULL,0,
        LAYOUT_FILL_X | LAYOUT_FILL_Y | LAYOUT_FILL_ROW | LAYOUT_FILL_COLUMN);
    
    Species(tabbook);
    General(tabbook);
    Veggy(tabbook);
    PhysicsAndCosts(tabbook);
    CostsOptions(tabbook);
    Mutations(tabbook);
    //ReststartAndL(tabbook);
    //InternetOptions(tabbook);
    //Recording(tabbook);
    
    BottomToolbar(LayoutMatrix);
}
Exemplo n.º 11
0
// Takes a genome and assigns it to a different species (where it belongs)
void Population::ReassignSpecies(unsigned int a_genome_idx)
{
    ASSERT(a_genome_idx < m_Genomes.size());

    // first remember where is this genome exactly
    unsigned int t_species_idx = 0, t_genome_rel_idx = 0;
    unsigned int t_counter = 0;

    // to keep the genome
    Genome t_genome;

    // search for it
    bool t_f = false;
    t_species_idx = 0;
    for(unsigned int i=0; i<m_Species.size(); i++)
    {
        t_genome_rel_idx = 0;
        for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
        {
            if (t_counter == a_genome_idx)
            {
                // get the genome and break
                t_genome = m_Species[i].m_Individuals[j];
                t_f = true;
                break;
            }

            t_counter++;
            t_genome_rel_idx++;
        }

        if (!t_f)
        {
            t_species_idx++;
        }
        else
        {
            break;
        }
    }

    // Remove it from its species
    m_Species[t_species_idx].RemoveIndividual(t_genome_rel_idx);

    // If the species becomes empty, remove the species as well
    if (m_Species[t_species_idx].m_Individuals.size() == 0)
    {
        m_Species.erase(m_Species.begin() + t_species_idx);
    }

    // Find a new species for this genome
    bool t_found = false;
    std::vector<Species>::iterator t_cur_species = m_Species.begin();

    // No species yet?
    if (t_cur_species == m_Species.end())
    {
        // create the first species and place the baby there
        m_Species.push_back( Species(t_genome, GetNextSpeciesID()));
        IncrementNextSpeciesID();
    }
    else
    {
        // try to find a compatible species
        Genome t_to_compare = t_cur_species->GetRepresentative();

        t_found = false;
        while((t_cur_species != m_Species.end()) && (!t_found))
        {
            if (t_genome.IsCompatibleWith( t_to_compare, m_Parameters ))
            {
                // found a compatible species
                t_cur_species->AddIndividual(t_genome);
                t_found = true; // the search is over
            }
            else
            {
                // keep searching for a matching species
                t_cur_species++;
                if (t_cur_species != m_Species.end())
                {
                    t_to_compare = t_cur_species->GetRepresentative();
                }
            }
        }

        // if couldn't find a match, make a new species
        if (!t_found)
        {
            m_Species.push_back( Species(t_genome, GetNextSpeciesID()));
            IncrementNextSpeciesID();
        }
    }
}
Exemplo n.º 12
0
// Separates the population into species
// also adjusts the compatibility treshold if this feature is enabled
void Population::Speciate()
{
    // iterate through the genome list and speciate
    // at least 1 genome must be present
    ASSERT(m_Genomes.size() > 0);

    // first clear out the species
    m_Species.clear();


    bool t_added = false;

    // NOTE: we are comparing the new generation's genomes to the representatives from the previous generation!
    // Any new species that is created is assigned a representative from the new generation.
    for(unsigned int i=0; i<m_Genomes.size(); i++)
    {
        t_added = false;

        // iterate through each species and check if compatible. If compatible, then add to the species.
        // if not compatible, create a new species.
        for(unsigned int j=0; j<m_Species.size(); j++)
        {
            Genome tmp = m_Species[j].GetRepresentative();
            if (m_Genomes[i].IsCompatibleWith( tmp, m_Parameters ))
            {
                // Compatible, add to species
                m_Species[j].AddIndividual( m_Genomes[i] );
                t_added = true;

                break;
            }
        }

        if (!t_added)
        {
            // didn't find compatible species, create new species
            m_Species.push_back( Species(m_Genomes[i], m_NextSpeciesID));
            m_NextSpeciesID++;
        }
    }

    // Remove all empty species (cleanup routine for every case..)
    std::vector<Species>::iterator t_cs = m_Species.begin();
    while(t_cs != m_Species.end())
    {
        if (t_cs->NumIndividuals() == 0)
        {
            // remove the dead species
            t_cs = m_Species.erase( t_cs );

            if (t_cs != m_Species.begin()) // in case the first species are dead
                t_cs--;
        }

        t_cs++;
    }


    /*
        //////////////////
        // extensive test DEBUG
        // ////
        // check to see if compatible enough individuals are in different species

        // for each species
        for(int i=0; i<m_Species.size(); i++)
        {
            for(int j=0; j<m_Species.size(); j++)
            {
                // do not check individuals in the same species
                if (i != j)
                {
                    // now for each individual in species [i]
                    // compare it to all individuals in species [j]
                    // report if there is a distance smaller that CompatTreshold
                    for(int sp1=0; sp1<m_Species[i].m_Members.size(); sp1++)
                    {
                        for(int sp2=0; sp2<m_Species[j].m_Members.size(); sp2++)
                        {
                            double t_dist = m_Species[i].m_Members[sp1]->CompatibilityDistance( *(m_Species[j].m_Members[sp2]) );

                            if (t_dist <= GlobalParameters.CompatTreshold)
                            {
                                const string tMessage = "Compatible individuals in different species!";
                                m_MessageQueue.push(tMessage);
                            }
                        }
                    }
                }
            }
        }
    */
}
Exemplo n.º 13
0
void load_particle_space(const H5::Group& root, Tspace_* space)
{
    typedef ParticleSpaceHDF5Traits traits_type;
    typedef typename traits_type::h5_species_struct h5_species_struct;
    typedef typename traits_type::h5_particle_struct h5_particle_struct;

    Real3 edge_lengths;
    const hsize_t dims[] = {3};
    const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims);
    root.openAttribute("edge_lengths").read(lengths_type, &edge_lengths);
    space->reset(edge_lengths);

    double t;
    root.openAttribute("t").read(H5::PredType::IEEE_F64LE, &t);
    space->set_t(t);

    {
        H5::DataSet species_dset(root.openDataSet("species"));
        const unsigned int num_species(
            species_dset.getSpace().getSimpleExtentNpoints());
        boost::scoped_array<h5_species_struct> h5_species_table(
            new h5_species_struct[num_species]);
        species_dset.read(
            h5_species_table.get(), traits_type::get_species_comp_type());
        species_dset.close();

        H5::DataSet particle_dset(root.openDataSet("particles"));
        const unsigned int num_particles(
            particle_dset.getSpace().getSimpleExtentNpoints());
        boost::scoped_array<h5_particle_struct> h5_particle_table(
            new h5_particle_struct[num_particles]);
        particle_dset.read(
            h5_particle_table.get(), traits_type::get_particle_comp_type());
        particle_dset.close();

        typedef utils::get_mapper_mf<unsigned int, Species::serial_type>::type
            species_id_map_type;
        species_id_map_type species_id_map;
        for (unsigned int i(0); i < num_species; ++i)
        {
            species_id_map[h5_species_table[i].id] = h5_species_table[i].serial;
        }

        for (unsigned int i(0); i < num_particles; ++i)
        {
            space->update_particle(ParticleID(std::make_pair(h5_particle_table[i].lot, h5_particle_table[i].serial)), Particle(Species(species_id_map[h5_particle_table[i].sid]), Real3(h5_particle_table[i].posx, h5_particle_table[i].posy, h5_particle_table[i].posz), h5_particle_table[i].radius, h5_particle_table[i].D));
        }

        // boost::scoped_array<h5_particle_struct>
        //     h5_particle_table(new h5_particle_struct[num_particles]);
        // for (unsigned int i(0); i < num_particles; ++i)
        // {
        //     species_id_map_type::const_iterator
        //         it(species_id_map.find(particles[i].second.species_serial()));
        //     if (it == species_id_map.end())
        //     {
        //         species.push_back(particles[i].second.species());
        //         it = species_id_map.insert(
        //             std::make_pair(particles[i].second.species_serial(),
        //                            species.size())).first;
        //     }

        //     h5_particle_table[i].lot = particles[i].first.lot();
        //     h5_particle_table[i].serial = particles[i].first.serial();
        //     h5_particle_table[i].sid = (*it).second;
        //     h5_particle_table[i].posx = particles[i].second.position()[0];
        //     h5_particle_table[i].posy = particles[i].second.position()[1];
        //     h5_particle_table[i].posz = particles[i].second.position()[2];
        //     h5_particle_table[i].radius = particles[i].second.radius();
        //     h5_particle_table[i].D = particles[i].second.D();
        // }

        // boost::scoped_array<h5_species_struct>
        //     h5_species_table(new h5_species_struct[species.size()]);
        // for (unsigned int i(0); i < species.size(); ++i)
        // {
        //     h5_species_table[i].id = i + 1;
        //     std::strcpy(h5_species_table[i].serial,
        //                 species[i].serial().c_str());
        // }
    }
}
Exemplo n.º 14
0
// Reproduce mates & mutates the individuals of the species
// It may access the global species list in the population
// because some babies may turn out to belong in another species
// that have to be created.
// Also calls Birth() for every new baby
void Species::Reproduce(Population &a_Pop, Parameters& a_Parameters, RNG& a_RNG)
{
    Genome t_baby; // temp genome for reproduction

    int t_offspring_count = Rounded(GetOffspringRqd());

    // no offspring?! yikes.. dead species!
    if (t_offspring_count == 0)
    {
        // maybe do something else?
        return;
    }

    //////////////////////////
    // Reproduction

    // Spawn t_offspring_count babies
    bool t_champ_chosen = false;
    bool t_baby_exists_in_pop = false;
    while(t_offspring_count--)
    {
    	bool t_new_individual = true;

        // if the champ was not chosen, do it now..
        if (!t_champ_chosen)
        {
            t_baby = m_Individuals[0];
            t_champ_chosen = true;
            t_new_individual = false;
        }
        // or if it was, then proceed with the others
        else
        {
            do // - while the baby already exists somewhere in the new population
            {
                // this tells us if the baby is a result of mating
                bool t_mated = false;

                // There must be individuals there..
                ASSERT(NumIndividuals() > 0);

                // for a species of size 1 we can only mutate
                // NOTE: but does it make sense since we know this is the champ?
                if (NumIndividuals() == 1)
                {
                    t_baby = GetIndividual(a_Parameters, a_RNG);
                    t_mated = false;
                }
                // else we can mate
                else
                {
                    do // keep trying to mate until a good offspring is produced
                    {
                        Genome t_mom = GetIndividual(a_Parameters, a_RNG);

                        // choose whether to mate at all
                        // Do not allow crossover when in simplifying phase
                        if ((a_RNG.RandFloat() < a_Parameters.CrossoverRate) && (a_Pop.GetSearchMode() != SIMPLIFYING))
                        {
                            // get the father
                            Genome t_dad;
                            bool t_interspecies = false;

                            // There is a probability that the father may come from another species
                            if ((a_RNG.RandFloat() < a_Parameters.InterspeciesCrossoverRate) && (a_Pop.m_Species.size()>1))
                            {
                                // Find different species (random one) // !!!!!!!!!!!!!!!!!
                                int t_diffspec = a_RNG.RandInt(0, static_cast<int>(a_Pop.m_Species.size()-1));
                                t_dad = a_Pop.m_Species[t_diffspec].GetIndividual(a_Parameters, a_RNG);
                                t_interspecies = true;
                            }
                            else
                            {
                                // Mate within species
                                t_dad = GetIndividual(a_Parameters, a_RNG);

                                // The other parent should be a different one
                                // number of tries to find different parent
                                int t_tries = 32;
                                if (!a_Parameters.AllowClones)
                                    while(((t_mom.GetID() == t_dad.GetID()) || (t_mom.CompatibilityDistance(t_dad, a_Parameters) < 0.00001) ) && (t_tries--))
                                    {
                                        t_dad = GetIndividual(a_Parameters, a_RNG);
                                    }
                                else
                                    while(((t_mom.GetID() == t_dad.GetID()) ) && (t_tries--))
                                    {
                                        t_dad = GetIndividual(a_Parameters, a_RNG);
                                    }
                                t_interspecies = false;
                            }

                            // OK we have both mom and dad so mate them
                            // Choose randomly one of two types of crossover
                            if (a_RNG.RandFloat() < a_Parameters.MultipointCrossoverRate)
                            {
                                t_baby = t_mom.Mate( t_dad, false, t_interspecies, a_RNG);
                            }
                            else
                            {
                                t_baby = t_mom.Mate( t_dad, true, t_interspecies, a_RNG);
                            }

                            t_mated = true;
                        }
                        // don't mate - reproduce the mother asexually
                        else
                        {
                            t_baby = t_mom;
                            t_mated = false;
                        }

                    } while (t_baby.HasDeadEnds() || (t_baby.NumLinks() == 0));
                    // in case of dead ends after crossover we will repeat crossover
                    // until it works
                }


                // Mutate the baby
                if ((!t_mated) || (a_RNG.RandFloat() < a_Parameters.OverallMutationRate))
                    MutateGenome(t_baby_exists_in_pop, a_Pop, t_baby, a_Parameters, a_RNG);

                // Check if this baby is already present somewhere in the offspring
                // we don't want that
                t_baby_exists_in_pop = false;
                // Unless of course, we want
                if (!a_Parameters.AllowClones)
                {
                    for(unsigned int i=0; i<a_Pop.m_TempSpecies.size(); i++)
                    {
                        for(unsigned int j=0; j<a_Pop.m_TempSpecies[i].m_Individuals.size(); j++)
                        {
                            if (
                                (t_baby.CompatibilityDistance(a_Pop.m_TempSpecies[i].m_Individuals[j], a_Parameters) < 0.00001) // identical genome?
                               )

                            {
                                t_baby_exists_in_pop = true;
                                break;
                            }
                        }
                    }
                }
            }
            while (t_baby_exists_in_pop); // end do
        }

        // Final place to test for problems
        // If there is anything wrong here, we will just
        // pick a random individual and leave him unchanged
        if ((t_baby.NumLinks() == 0) || t_baby.HasDeadEnds())
        {
            t_baby = GetIndividual(a_Parameters, a_RNG);
            t_new_individual = false;
        }

        if (t_new_individual) {
			// We have a new offspring now
			// give the offspring a new ID
			t_baby.SetID(a_Pop.GetNextGenomeID());
			a_Pop.IncrementNextGenomeID();

			// sort the baby's genes
			t_baby.SortGenes();

			// clear the baby's fitness
			t_baby.SetFitness(0);
			t_baby.SetAdjFitness(0);
			t_baby.SetOffspringAmount(0);

			t_baby.ResetEvaluated();
        }

        //////////////////////////////////
        // put the baby to its species  //
        //////////////////////////////////

        // before Reproduce() is invoked, it is assumed that a
        // clone of the population exists with the name of m_TempSpecies
        // we will store results there.
        // after all reproduction completes, the original species will be replaced back

        bool t_found = false;
        std::vector<Species>::iterator t_cur_species = a_Pop.m_TempSpecies.begin();

        // No species yet?
        if (t_cur_species == a_Pop.m_TempSpecies.end())
        {
            // create the first species and place the baby there
            a_Pop.m_TempSpecies.push_back( Species(t_baby, a_Pop.GetNextSpeciesID()));
            a_Pop.IncrementNextSpeciesID();
        }
        else
        {
            // try to find a compatible species
            Genome t_to_compare = t_cur_species->GetRepresentative();

            t_found = false;
            while((t_cur_species != a_Pop.m_TempSpecies.end()) && (!t_found))
            {
                if (t_baby.IsCompatibleWith( t_to_compare, a_Parameters))
                {
                    // found a compatible species
                    t_cur_species->AddIndividual(t_baby);
                    t_found = true; // the search is over
                }
                else
                {
                    // keep searching for a matching species
                    t_cur_species++;
                    if (t_cur_species != a_Pop.m_TempSpecies.end())
                    {
                        t_to_compare = t_cur_species->GetRepresentative();
                    }
                }
            }

            // if couldn't find a match, make a new species
            if (!t_found)
            {
                a_Pop.m_TempSpecies.push_back( Species(t_baby, a_Pop.GetNextSpeciesID()));
                a_Pop.IncrementNextSpeciesID();
            }
        }
    }
}
Exemplo n.º 15
0
  /** reimplement simple table format used by NonLocalPPotential
   */
  void ECPotentialBuilder::useSimpleTableFormat() {

    SpeciesSet& Species(IonConfig.getSpeciesSet());
    int ng(Species.getTotalNum());
    int icharge(Species.addAttribute("charge"));

    for(int ig=0; ig<ng;ig++) {
      vector<RealType> grid_temp, pp_temp;
      string species(Species.speciesName[ig]);
      string fname = species+".psf";

      ifstream fin(fname.c_str(),ios_base::in);
      if(!fin){
	ERRORMSG("Could not open file " << fname)
        exit(-1);
      }      

      // Read Number of potentials (local and non) for this atom
      int npotentials;
      fin >> npotentials;
      RealType r, f1;

      int lmax=-1;
      int numnonloc=0;
      RealType rmax(0.0);

      app_log() << "  ECPotential for " << species << endl;
      NonLocalECPComponent* mynnloc=0;

      typedef OneDimCubicSpline<RealType> CubicSplineFuncType;
      for (int ij=0; ij<npotentials; ij++){
	int angmom,npoints;
	fin >> angmom >> npoints;

        OneDimNumGridFunctor<RealType> inFunc;
        inFunc.put(npoints,fin);

	if(angmom < 0) {//local potential, input is rescale by -r/z

          RealType zinv=-1.0/Species(icharge,ig);
          int ng=npoints-1;
          RealType rf=5.0;
          ng=static_cast<int>(rf*100)+1;//use 1e-2 resolution
          GridType * agrid= new LinearGrid<RealType>;
          agrid->set(0,rf,ng);
          vector<RealType> pp_temp(ng);
          pp_temp[0]=0.0;
          for (int j=1; j<ng; j++){
            RealType r((*agrid)[j]);
            pp_temp[j]=r*zinv*inFunc.splint(r);
          }
          pp_temp[ng-1]=1.0;
          RadialPotentialType *app = new RadialPotentialType(agrid,pp_temp);
	  app->spline();
          localPot[ig]=app;
          app_log() << "    LocalECP l=" << angmom << endl;
          app_log() << "      Linear grid=[0," << rf << "] npts=" << ng << endl;
          hasLocalPot=true; //will create LocalECPotential
        } else {
          hasNonLocalPot=true; //will create NonLocalECPotential
          if(mynnloc == 0) mynnloc = new NonLocalECPComponent;

          RealType rf=inFunc.rmax();

          GridType * agrid= new LinearGrid<RealType>;
          int ng=static_cast<int>(rf*100)+1;
          agrid->set(0.0,rf,ng);
          app_log() << "    NonLocalECP l=" << angmom << " rmax = " << rf << endl;
          app_log() << "      Linear grid=[0," << rf << "] npts=" << ng << endl;

          vector<RealType> pp_temp(ng);
          //get the value
          pp_temp[0]=inFunc(0);
          for (int j=1; j<ng; j++){
            pp_temp[j]=inFunc.splint((*agrid)[j]);
          }

          RadialPotentialType *app = new RadialPotentialType(agrid,pp_temp);
	  app->spline();

	  mynnloc->add(angmom,app);
	  lmax=std::max(lmax,angmom);
	  rmax=std::max(rmax,rf);
          numnonloc++;
	}

        if(mynnloc) {
          mynnloc->lmax=lmax; 
          mynnloc->Rmax=rmax;
          app_log() << "    Maximum cutoff of NonLocalECP " << rmax << endl;
        }
      } 
      fin.close();

      if(mynnloc) {
        nonLocalPot[ig]=mynnloc;
        int numsgridpts=0;

        string fname = species+".sgr";
        ifstream fin(fname.c_str(),ios_base::in);
        if(!fin){
          app_error() << "Could not open file " << fname << endl;
          exit(-1);
        }
        PosType xyz;
        RealType weight;
        while(fin >> xyz >> weight){
          mynnloc->addknot(xyz,weight);
          numsgridpts++;
        }
        //cout << "Spherical grid : " << numsgridpts << " points" <<endl;
        mynnloc->resize_warrays(numsgridpts,numnonloc,lmax);
      }
    }//species
  }
Exemplo n.º 16
0
Arquivo: ids.hpp Projeto: wushin/tmwa
namespace tmwa
{
class Species : public Wrapped<uint16_t> { public: explicit operator bool() const = delete; bool operator !() const = delete; constexpr Species() : Wrapped<uint16_t>() {} protected: constexpr explicit Species(uint16_t a) : Wrapped<uint16_t>(a) {} };

constexpr Species NEGATIVE_SPECIES = Species();

bool impl_extract(XString str, Species *w);


class AccountId : public Wrapped<uint32_t> { public: constexpr AccountId() : Wrapped<uint32_t>() {} protected: constexpr explicit AccountId(uint32_t a) : Wrapped<uint32_t>(a) {} };
class CharId : public Wrapped<uint32_t> { public: constexpr CharId() : Wrapped<uint32_t>() {} protected: constexpr explicit CharId(uint32_t a) : Wrapped<uint32_t>(a) {} };
// important note: slave mobs synthesize PartyId as -BlockId of master
class PartyId : public Wrapped<uint32_t> { public: constexpr PartyId() : Wrapped<uint32_t>() {} protected: constexpr explicit PartyId(uint32_t a) : Wrapped<uint32_t>(a) {} };
class ItemNameId : public Wrapped<uint16_t> { public: constexpr ItemNameId() : Wrapped<uint16_t>() {} protected: constexpr explicit ItemNameId(uint16_t a) : Wrapped<uint16_t>(a) {} };

class BlockId : public Wrapped<uint32_t> { public: constexpr BlockId() : Wrapped<uint32_t>() {} protected: constexpr explicit BlockId(uint32_t a) : Wrapped<uint32_t>(a) {} };
class QuestId : public Wrapped<uint16_t> { public: constexpr QuestId() : Wrapped<uint16_t>() {} protected: constexpr explicit QuestId(uint16_t a) : Wrapped<uint16_t>(a) {} };
class ClientVersion : public Wrapped<uint32_t>{ public: constexpr ClientVersion() : Wrapped<uint32_t>() {} protected: constexpr explicit ClientVersion(uint32_t a) : Wrapped<uint32_t>(a) {} };

bool impl_extract(XString str, GmLevel *lvl);
class GmLevel
{
    uint32_t bits;

    friend bool impl_extract(XString str, GmLevel *lvl);
    constexpr explicit
    GmLevel(uint32_t b) : bits(b) {}
    constexpr explicit
    operator uint32_t() const { return bits; }

    template<class T>
    explicit
    GmLevel(T) = delete;
    template<class T, typename=typename std::enable_if<!std::is_same<T, uint32_t>::value && !std::is_same<T, bool>::value>::type>
    explicit
    operator T() = delete;
public:
    constexpr
    GmLevel() : bits() {}
    constexpr static
    GmLevel from(uint32_t bits) { return GmLevel(bits); }
    template<class T>
    constexpr static
    GmLevel from(T) = delete;

    constexpr explicit
    operator bool() const { return bits; }
    constexpr
    bool operator !() const { return !bits; }

    // the argument is the level of a command
    constexpr
    bool satisfies(GmLevel perm) const { return bits >= perm.bits; }
    // the argument is another player's gm level, for info commands
    constexpr
    bool detects(GmLevel other) const { return bits >= other.bits; }
    // the argument is another player's gm level, for aggressive commands
    constexpr
    bool overwhelms(GmLevel other) const { return bits >= other.bits; }
    // the argument is another potential permission level
    constexpr
    bool obsoletes(GmLevel plvl) const { return bits >= plvl.bits; }

    constexpr
    uint16_t get_public_word() const
    {
        return (bits == 60 || bits == 99) ? 0x0080 : 0;
    }

    constexpr
    uint32_t get_all_bits() const
    {
        return bits;
    }

    friend constexpr
    bool operator == (GmLevel l, GmLevel r)
    {
        return l.bits == r.bits;
    }
    friend constexpr
    bool operator != (GmLevel l, GmLevel r)
    {
        return l.bits != r.bits;
    }

    friend
    bool native_to_network(Byte *network, GmLevel native)
    {
        network->value = native.bits;
        return true; // LIES. But this code is going away soon anyway
    }
    friend
    bool network_to_native(GmLevel *native, Byte network)
    {
        native->bits = network.value;
        return true; // LIES. But this code is going away soon anyway
    }

    // TODO kill this code too
    friend
    bool native_to_network(Little16 *network, GmLevel native)
    {
        uint16_t tmp = native.bits;
        return native_to_network(network, tmp);
    }
    friend
    bool network_to_native(GmLevel *native, Little16 network)
    {
        uint16_t tmp;
        bool rv = network_to_native(&tmp, network);
        native->bits = tmp;
        return rv;
    }

    friend
    bool native_to_network(Little32 *network, GmLevel native)
    {
        return native_to_network(network, native.bits);
    }
    friend
    bool network_to_native(GmLevel *native, Little32 network)
    {
        return network_to_native(&native->bits, network);
    }
};

inline
uint32_t convert_for_printf(GmLevel g)
{
    return g.get_all_bits();
}
} // namespace tmwa
Exemplo n.º 17
0
 bool has_parameter(const Species::serial_type& name) const
 {
     parameter_container_type::const_iterator i(
         std::find(parameters_.begin(), parameters_.end(), Species(name)));
     return (i != parameters_.end());
 }
Exemplo n.º 18
0
 Species create_species(const std::string& name) const
 {
     return apply_species_attributes(Species(name));
 }
Exemplo n.º 19
0
  bool PadeJastrowBuilder::put(xmlNodePtr cur) 
  {

    ReportEngine PRE(ClassName,"put()");

    string sourceOpt=targetPtcl.getName();
    string jname="PadeJastrow";
    string spin="no";
    string id_b="jee_b";
    RealType pade_b=1.0;
    OhmmsAttributeSet pattrib;
    pattrib.add(jname,"name");
    pattrib.add(spin,"spin");
    pattrib.add(sourceOpt,"source");
    pattrib.put(cur);

    cur=cur->children;
    while(cur != NULL)
    {
      {//just to hide this
        string pname="0";
        OhmmsAttributeSet aa;
        aa.add(pname,"name");
        aa.add(id_b,"id");
        aa.put(cur);
        if(pname[0]=='B') putContent(pade_b,cur);
      }

      xmlNodePtr cur1=cur->children;
      while(cur1!= NULL)
      {
        string pname="0";
        OhmmsAttributeSet aa;
        aa.add(pname,"name");
        aa.add(id_b,"id");
        aa.put(cur1);
        if(pname[0]=='B') putContent(pade_b,cur1);
        cur1=cur1->next;
      }
      cur=cur->next;
    }

    app_log() << "PadeJastrowBuilder " << id_b << " = " << pade_b << endl;

    typedef PadeFunctor<RealType> FuncType;

    typedef TwoBodyJastrowOrbital<FuncType> JeeType;
    JeeType *J2 = new JeeType(targetPtcl);

    SpeciesSet& species(targetPtcl.getSpeciesSet());
    RealType q=species(0,species.addAttribute("charge"));

    if(spin == "no") 
    {
      RealType cusp=-0.5*q*q;
      FuncType *func=new FuncType(cusp,pade_b);
      func->setIDs("jee_cusp",id_b);//set the ID's

      J2->addFunc("pade_uu",0,0,func);

      //DerivFuncType *dfunc=new DerivFuncType(cusp,B);
      //dJ2->addFunc("pade_uu",0,0,dfunc);
      //dFuncList.push_back(dfunc);
      app_log() << "    Adding Spin-independent Pade Two-Body Jastrow Cusp " << cusp<< "\n";
    } 
    else 
    {
      //build uu functor
      RealType cusp_uu=-0.25*q*q;
      FuncType *funcUU=new FuncType(cusp_uu,pade_b);
      funcUU->setIDs("pade_uu",id_b);//set the ID's

      //build ud functor
      RealType cusp_ud=-0.5*q*q;
      FuncType *funcUD=new FuncType(cusp_ud,pade_b);
      funcUD->setIDs("pade_ud",id_b);//set the ID's

      J2->addFunc("pade_uu",0,0,funcUU);

      //DerivFuncType *dfuncUU=new DerivFuncType(cusp_uu,B);
      //DerivFuncType *dfuncUD=new DerivFuncType(cusp_ud,B);
      //dJ2->addFunc("pade_uu",0,0,dfuncUU);
      //dJ2->addFunc("pade_ud",0,1,dfuncUD);
      app_log() << "    Adding Spin-dependent Pade Two-Body Jastrow " << "\n";
      app_log() << "      parallel spin     " << cusp_uu << "\n";
      app_log() << "      antiparallel spin " << cusp_ud << "\n";
    }

    targetPsi.addOrbital(J2,"J2_pade");

    if(sourceOpt != targetPtcl.getName())
    {
      map<string,ParticleSet*>::iterator pa_it(ptclPool.find(sourceOpt));
      if(pa_it == ptclPool.end()) 
      {
        PRE.warning("PadeJastrowBuilder::put failed. "+sourceOpt+" does not exist.");
        return true;
      }
      ParticleSet& sourcePtcl= (*(*pa_it).second);

      app_log() << "  PadeBuilder::Adding Pade One-Body Jastrow with effective ionic charges." << endl;
      typedef OneBodyJastrowOrbital<FuncType> JneType;
      JneType* J1 = new JneType(sourcePtcl,targetPtcl);

      //typedef OneBodyJastrowOrbital<DerivFuncType> DerivJneType;
      //DerivJneType* dJ1=new DerivJneType(sourcePtcl,targetPtcl);

      SpeciesSet& Species(sourcePtcl.getSpeciesSet());
      int ng=Species.getTotalNum();
      int icharge = Species.addAttribute("charge");
      for(int ig=0; ig<ng; ++ig) 
      {
        RealType zeff=Species(icharge,ig);
        ostringstream j1id;
        j1id<<"pade_"<<Species.speciesName[ig];

        RealType sc=std::pow(2*zeff,0.25);
        FuncType *func=new FuncType(-zeff,pade_b,sc);
        func->setIDs(j1id.str(),id_b);

        J1->addFunc(ig,func);

        //DerivFuncType *dfunc=new DerivFuncType(-zeff,B,sc);
        //dJ1->addFunc(ig,dfunc);
        //dFuncList.push_back(dfunc);

        app_log() << "    " << Species.speciesName[ig] <<  " Zeff = " << zeff << " B= " << pade_b*sc << endl;
      }
      targetPsi.addOrbital(J1,"J1_pade");
    }
    return true;
  }
Exemplo n.º 20
0
// Main realtime loop. We assume that the whole population was evaluated once before calling this.
// Returns a pointer to the baby in the population. It will be the only individual that was not evaluated.
// Set the m_Evaluated flag of the baby to true after evaluation! 
Genome* Population::Tick(Genome& a_deleted_genome)
{
    // Make sure all individuals are evaluated
    /*for(unsigned int i=0; i<m_Species.size(); i++)
        for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
            ASSERT(m_Species[i].m_Individuals[j].m_Evaluated);*/

    m_NumEvaluations++;

    // Find and save the best genome and fitness
    for(unsigned int i=0; i<m_Species.size(); i++)
    {
        m_Species[i].IncreaseGensNoImprovement();

        for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
        {
            if (m_Species[i].m_Individuals[j].GetFitness() <= 0.0)
            {
                m_Species[i].m_Individuals[j].SetFitness(0.00001);
            }

            const double  t_Fitness = m_Species[i].m_Individuals[j].GetFitness();
            if (t_Fitness > m_BestFitnessEver)
            {
                // Reset the stagnation counter only if the fitness jump is greater or equal to the delta.
                if (fabs(t_Fitness - m_BestFitnessEver) >= m_Parameters.StagnationDelta)
                {
                    m_GensSinceBestFitnessLastChanged = 0;
                }

                m_BestFitnessEver = t_Fitness;
                m_BestGenomeEver  = m_Species[i].m_Individuals[j];
            }
        }
    }

    double t_f = std::numeric_limits<double>::min();
    for(unsigned int i=0; i<m_Species.size(); i++)
    {
        for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
        {
            if (m_Species[i].m_Individuals[j].GetFitness() > t_f)
            {
                t_f = m_Species[i].m_Individuals[j].GetFitness();
                m_BestGenome = m_Species[i].m_Individuals[j];
            }

            if (m_Species[i].m_Individuals[j].GetFitness() >= m_Species[i].GetBestFitness())
            {
                m_Species[i].m_BestFitness = m_Species[i].m_Individuals[j].GetFitness();
                m_Species[i].m_GensNoImprovement = 0;
            }
        }
    }


    // adjust the compatibility treshold
    bool t_changed = false;
    if (m_Parameters.DynamicCompatibility == true)
    {
        if ((m_NumEvaluations % m_Parameters.CompatTreshChangeInterval_Evaluations) == 0)
        {
            if (m_Species.size() > m_Parameters.MaxSpecies)
            {
                m_Parameters.CompatTreshold += m_Parameters.CompatTresholdModifier;
                t_changed = true;
            }
            else if (m_Species.size() < m_Parameters.MinSpecies)
            {
                m_Parameters.CompatTreshold -= m_Parameters.CompatTresholdModifier;
                t_changed = true;
            }

            if (m_Parameters.CompatTreshold < m_Parameters.MinCompatTreshold) m_Parameters.CompatTreshold = m_Parameters.MinCompatTreshold;
        }
    }

    // If the compatibility treshold was changed, reassign all individuals by species
    if (t_changed)
    {
        for(unsigned int i=0; i<m_Genomes.size(); i++)
        {
            ReassignSpecies(i);
        }
    }

    // Sort individuals within species by fitness
    Sort();

    // Remove the worst individual
    a_deleted_genome = RemoveWorstIndividual();

    // Recalculate all averages for each species
    // If the average species fitness of a species is 0,
    // then there are no evaluated individuals in it.
    for(unsigned int i=0; i<m_Species.size(); i++)
        m_Species[i].CalculateAverageFitness();

    // Now spawn the new offspring
    unsigned int t_parent_species_index = ChooseParentSpecies();
    Genome t_baby = m_Species[t_parent_species_index].ReproduceOne(*this, m_Parameters, m_RNG);
    ASSERT(t_baby.NumInputs() > 0);
    ASSERT(t_baby.NumOutputs() > 0);
    Genome* t_to_return = NULL;


    // Add the baby to its proper species
    bool t_found = false;
    std::vector<Species>::iterator t_cur_species = m_Species.begin();

    // No species yet?
    if (t_cur_species == m_Species.end())
    {
        // create the first species and place the baby there
        m_Species.push_back( Species(t_baby, GetNextSpeciesID()));
        // the last one
        t_to_return = &(m_Species[ m_Species.size()-1 ].m_Individuals[ m_Species[ m_Species.size()-1 ].m_Individuals.size() - 1]);
        IncrementNextSpeciesID();
    }
    else
    {
        // try to find a compatible species
        Genome t_to_compare = t_cur_species->GetRepresentative();

        t_found = false;
        while((t_cur_species != m_Species.end()) && (!t_found))
        {
            if (t_baby.IsCompatibleWith( t_to_compare, m_Parameters))
            {
                // found a compatible species
                t_cur_species->AddIndividual(t_baby);
                t_to_return = &(t_cur_species->m_Individuals[ t_cur_species->m_Individuals.size() - 1]);
                t_found = true; // the search is over
            }
            else
            {
                // keep searching for a matching species
                t_cur_species++;
                if (t_cur_species != m_Species.end())
                {
                    t_to_compare = t_cur_species->GetRepresentative();
                }
            }
        }

        // if couldn't find a match, make a new species
        if (!t_found)
        {
            m_Species.push_back( Species(t_baby, GetNextSpeciesID()));
            // the last one
            t_to_return = &(m_Species[ m_Species.size()-1 ].m_Individuals[ m_Species[ m_Species.size()-1 ].m_Individuals.size() - 1]);
            IncrementNextSpeciesID();
        }
    }

    ASSERT(t_to_return != NULL);

    return t_to_return;
}
Exemplo n.º 21
0
void GameWorld::Scan(glArchivItem_Map *map)
{
	width = map->getHeader().getWidth();
	height = map->getHeader().getHeight();
	lt = LandscapeType(map->getHeader().getGfxSet());

	Init();

	// Dummy-Hafenpos für Index 0 einfügen // ask Oliverr why!
	// -> I just did, the dummy is so that the harbor "0" might be used for ships with no particular destination
	// poc: if you ever remove this dummy go to GameWorldBase::CalcDistanceToNearestHarbor and fix the loop to include the first harbor again (think Ive seen other instances of dummyadjusted loops as well...)
	GameWorldBase::HarborPos dummy = {0,0};
	harbor_pos.push_back(dummy);

	// Andere Sachen setzen
	for(unsigned y = 0;y<height;++y)
	{
		for(unsigned x = 0;x<width;++x)
		{
			MapNode& node = nodes[y*width+x];

			node.roads[2] = node.roads[1] = node.roads[0] = 0;
			node.roads_real[2] = node.roads_real[1] = node.roads_real[0] = false;
			node.altitude = map->GetMapDataAt(MAP_ALTITUDE, x, y);
			// Aufpassen, dass die Terrainindizes im Rahmen liegen, ansonsten 0 nehmen, unbekanntes Terrain (Bsp. 
			// Karte "Drachenebene")
			unsigned char t1 = map->GetMapDataAt(MAP_TERRAIN1, x, y), t2 = map->GetMapDataAt(MAP_TERRAIN2, x, y);
			
			// Hafenplatz?
			if(t1 >= 0x40 && t1 <= 0x54)
			{
				t1 -= 0x40;

				GameWorldBase::HarborPos p = {x,y};
				node.harbor_id = harbor_pos.size();
				harbor_pos.push_back(p);
			}
			else
				node.harbor_id = 0;
				
	

			node.t1 = (t1<20)?TERRAIN_INDIZES[t1]:0;
			node.t2 = (t2<20)?TERRAIN_INDIZES[t2]:0;

			node.resources = map->GetMapDataAt(MAP_RESOURCES, x, y);
			
			// Wasser?
			if(node.resources == 0x20 || node.resources == 0x21)
			{
				// TODO: Berge hatten komische Wasserbeeinflussung
				// ggf 0-4 Wasser setzen
				if( (node.t1 == TT_DESERT || node.t2 == TT_DESERT) ||
					(node.t1 == TT_WATER || node.t2 == TT_WATER) )
					node.resources = 0; // Kein Wasser, in der Wüste, da isses trocken!
				else if( (node.t1 == TT_STEPPE || node.t2 == TT_STEPPE) )
					node.resources = 0x23; // 2 Wasser
				else if( (node.t1 == TT_SAVANNAH || node.t2 == TT_SAVANNAH) )
					node.resources = 0x25; // 4 Wasser
				else
					node.resources = 0x27; // 7 Wasser
			}
			
			node.reserved = false;
			node.owner = 0;
			for(unsigned i = 0;i<4;++i)
				node.boundary_stones[i] = 0;
			node.sea_id = 0;
			
			// FOW-Zeug initialisieren
			for(unsigned i = 0;i<GameClient::inst().GetPlayerCount();++i)
			{
				switch(GameClient::inst().GetGGS().exploration)
				{
				case GlobalGameSettings::EXP_DISABLED:
					{
						node.fow[i].visibility = VIS_VISIBLE;
					} break;
				case GlobalGameSettings::EXP_CLASSIC:
					{
						node.fow[i].visibility = VIS_INVISIBLE;
					} break;
				case GlobalGameSettings::EXP_FOGOFWAR:
					{
						node.fow[i].visibility = VIS_INVISIBLE;
					} break;
				case GlobalGameSettings::EXP_FOGOFWARE_EXPLORED:
					{
						node.fow[i].visibility = VIS_FOW;
					} break;
				}
		
				node.fow[i].last_update_time = 0;
				node.fow[i].object = NULL;
				node.fow[i].roads[0] = node.fow[i].roads[1] =
					node.fow[i].roads[2] = 0;
				node.fow[i].owner = 0;
				for(unsigned z = 0;z<4;++z)
					node.fow[i].boundary_stones[z] = 0;
			}
		}
	}

	std::vector< Point<MapCoord> > headquarter_positions;

	// Objekte auslesen
	for(unsigned y = 0;y<height;++y)
	{
		for(unsigned x = 0;x<width;++x)
		{
			unsigned int pos = y*width+x;
			unsigned char lc = map->GetMapDataAt(MAP_LANDSCAPE, x, y);

			switch(map->GetMapDataAt(MAP_TYPE, x, y))
			{
			// Player Startpos (provisorisch)
			case 0x80:
				{
					headquarter_positions.push_back(Point<MapCoord>(x, y));

					if(lc < GAMECLIENT.GetPlayerCount())
					{
						GetPlayer(lc)->hqx = x;
						GetPlayer(lc)->hqy = y;
						nodes[pos].obj = NULL;
					}
				} break;

			// Baum 1-4
			case 0xC4:
				{
					if(lc >= 0x30 && lc <= 0x3D)
						nodes[pos].obj = new noTree(x,y,0,3);
					else if(lc >= 0x70 && lc <= 0x7D)
						nodes[pos].obj = new noTree(x,y,1,3);
					else if(lc >= 0xB0 && lc <= 0xBD)
						nodes[pos].obj = new noTree(x,y,2,3);
					else if(lc >= 0xF0 && lc <= 0xFD)
						nodes[pos].obj = new noTree(x,y,3,3);
					else
					{
						LOG.lprintf("Unbekannter Baum1-4 auf x=%d, y=%d: id=%d (0x%0X)\n", x, y, lc, lc);
						nodes[pos].obj = NULL;
					}
				} break;

			// Baum 5-8
			case 0xC5:
					{
					if(lc >= 0x30 && lc <= 0x3D)
						nodes[pos].obj = new noTree(x,y,4,3);
					else if(lc >= 0x70 && lc <= 0x7D)
						nodes[pos].obj = new noTree(x,y,5,3);
					else if(lc >= 0xB0 && lc <= 0xBD)
						nodes[pos].obj = new noTree(x,y,6,3);
					else if(lc >= 0xF0 && lc <= 0xFD)
						nodes[pos].obj = new noTree(x,y,7,3);
					else
					{
						LOG.lprintf("Unbekannter Baum5-8 auf x=%d, y=%d: id=%d (0x%0X)\n", x, y, lc, lc);
						nodes[pos].obj = NULL;
					}
				} break;

			// Baum 9
			case 0xC6:
				{
					if(lc >= 0x30 && lc <= 0x3D)
						nodes[pos].obj = new noTree(x,y,8,3);
					else
					{
						LOG.lprintf("Unbekannter Baum9 auf x=%d, y=%d: id=%d (0x%0X)\n", x, y, lc, lc);
						nodes[pos].obj = NULL;
					}
				} break;

			// Sonstiges Naturzeug ohne Funktion, nur zur Dekoration
			case 0xC8:
				{
					/// @todo mis0bobs unvollständig (dieses lagerzelt), 4 und 5 überhaupt nicht erwähnt
					// mis1bobs, 2 und 3 sind vollständig eingebaut

					// Objekte aus der map_?_z.lst
					if(lc <= 0x0A)
						nodes[pos].obj = new noEnvObject(x, y, 500+lc);

					// "wasserstein" aus der map_?_z.lst
					else if(lc == 0x0B)
						nodes[pos].obj = new noStaticObject(x, y, 500+lc);

					// Objekte aus der map_?_z.lst
					else if(lc >= 0x0C && lc <= 0x0F)
						nodes[pos].obj = new noEnvObject(x, y, 500+lc);

					// Objekte aus der map.lst
					else if(lc >= 0x10 && lc <= 0x14)
						nodes[pos].obj = new noEnvObject(x, y, 542+lc-0x10);

					// gestrandetes Schiff (mis0bobs, unvollständig)
					else if(lc == 0x15)
						nodes[pos].obj = new noStaticObject(x, y, (lc-0x15)*2, 0, 1);

					// das Tor aus der map_?_z.lst
					else if(lc == 0x16)
						nodes[pos].obj = new noStaticObject(x, y, 560, 0xFFFF, 2);

					// das geöffnete Tor aus map_?_z.lst
					else if(lc == 0x17)
						nodes[pos].obj = new noStaticObject(x, y, 561, 0xFFFF, 2);

					// Stalagmiten (mis1bobs)
					else if(lc >= 0x18 && lc <= 0x1E)
						nodes[pos].obj = new noStaticObject(x, y, (lc-0x18)*2, 1);

					// toter Baum (mis1bobs)
					else if(lc >= 0x1F && lc <= 0x20)
						nodes[pos].obj = new noStaticObject(x, y, 20+(lc-0x1F)*2, 1);

					// Gerippe (mis1bobs)
					else if(lc == 0x21)
						nodes[pos].obj = new noEnvObject(x, y, 30, 1);

					// Objekte aus der map.lst
					else if(lc >= 0x22 && lc <= 0x27)
						nodes[pos].obj = new noEnvObject(x, y, 550+lc-0x22);

					// Objekte aus der map.lst
					else if(lc >= 0x28 && lc <= 0x2B)
						nodes[pos].obj = new noEnvObject(x, y, 556+lc-0x28);

					// die "kaputten" Gebäuderuinen usw (mis2bobs)
					else if(lc >= 0x2C && lc <= 0x2D)
						nodes[pos].obj = new noStaticObject(x, y, (lc-0x2C)*2, 2);
					else if(lc == 0x2E)
						nodes[pos].obj = new noStaticObject(x, y, (lc-0x2C)*2, 2, 1);
					else if(lc == 0x2F)
						nodes[pos].obj = new noStaticObject(x, y, (lc-0x2C)*2, 2, 2);
					else if(lc == 0x30)
						nodes[pos].obj = new noEnvObject(x, y, (lc-0x2C)*2, 2);

					// der Wikinger (mis3bobs)
					else if(lc == 0x31)
						nodes[pos].obj = new noStaticObject(x, y, 0, 2);

					else
					{
						LOG.lprintf("Unbekanntes Naturzeug auf x=%d, y=%d: id=%d (0x%0X)\n", x, y, lc, lc);
						nodes[pos].obj = NULL;
					}

				} break;

			// Granit Typ 1
			case 0xCC:
				{
					if(lc >= 0x01 && lc <= 0x06)
						nodes[pos].obj = new noGranite(GT_1,lc-1);
					else
					{
						LOG.lprintf("Unbekannter Granit1 auf x=%d, y=%d: id=%d (0x%0X)\n", x, y, lc, lc);
						nodes[pos].obj = NULL;
					}
				} break;

			// Granit Typ 2
			case 0xCD:
				{
					if(lc >= 0x01 && lc <= 0x06)
						nodes[pos].obj = new noGranite(GT_2,lc-1);
					else
					{
						LOG.lprintf("Unbekannter Granit2 auf x=%d, y=%d: id=%d (0x%0X)\n", x, y, lc, lc);
						nodes[pos].obj = NULL;
					}
				} break;

				// Nichts
			case 0:
				{
					nodes[pos].obj = NULL;
				} break;

			default:
				{
					/*LOG.lprintf("Unbekanntes Objekt %d (0x%0X) auf x=%d, y=%d: id=%d (0x%0X)\n", map->map_type[y*width+x], map->map_type[y*width+x], x, y, lc, lc);
		*/			nodes[pos].obj = NULL;
				} break;
			}
		}
	}

	// BQ mit nichts erstmal inititalisieren (HQ-Setzen berechnet diese neu und braucht sie)
	for(unsigned y = 0;y<height;++y)
	{
		for(unsigned x = 0;x<width;++x)
		{
			SetBQ(x,y,BQ_NOTHING);
		}
	}

	//random locations? -> randomize them :)
	if (GameClient::inst().GetGGS().random_location)
	{
		ptrdiff_t (*p_myrandom)(ptrdiff_t) = myRandom;
		std::random_shuffle(headquarter_positions.begin(), headquarter_positions.end(), p_myrandom);

		for (unsigned i = 0; i < GAMECLIENT.GetPlayerCount(); ++i)
		{
			GetPlayer(i)->hqx = headquarter_positions.at(i).x;
			GetPlayer(i)->hqy = headquarter_positions.at(i).y;
		}
	}

	// HQ setzen
	for(unsigned i = 0;i<GAMECLIENT.GetPlayerCount();++i)
	{
		// Existiert überhaupt ein HQ?
		if(GetPlayer(i)->hqx != 0xFFFF)
		{
			if(GetPlayer(i)->ps == PS_OCCUPIED || GetPlayer(i)->ps == PS_KI)
			{
				nobHQ * hq = new nobHQ(GetPlayer(i)->hqx,GetPlayer(i)->hqy,i,GetPlayer(i)->nation);
				SetNO(hq,GetPlayer(i)->hqx,GetPlayer(i)->hqy);
				GetPlayer(i)->AddWarehouse(reinterpret_cast<nobBaseWarehouse*>(hq));
			}
			/*else
				GetNode(GetPlayer(i)->hqx,GetPlayer(i)->hqy).obj = 0;*/
		}
	}

	// Tiere auslesen
	for(unsigned y = 0;y<height;++y)
	{
		for(unsigned x = 0;x<width;++x)
		{
			// Tiere setzen
			Species species;
			switch(map->GetMapDataAt(MAP_ANIMALS, x, y))
			{
			// TODO: Welche ID ist Polarbär?
			case 1: species = Species(SPEC_RABBITWHITE+RANDOM.Rand(__FILE__,__LINE__,0,2)); break; // zufällige Hasenart nehmen
			case 2: species = SPEC_FOX; break;
			case 3: species = SPEC_STAG; break;
			case 4: species = SPEC_DEER; break;
			case 5: species = SPEC_DUCK; break;
			case 6: species = SPEC_SHEEP; break;
			default: species = SPEC_NOTHING; break;
			}

			if(species != SPEC_NOTHING)
			{
				noAnimal * animal = new noAnimal(species,x,y);
				AddFigure(animal,x,y);
				// Loslaufen
				animal->StartLiving();
			}

			/// 4 Fische setzen
			if(map->GetMapDataAt(MAP_RESOURCES,y*width+x) > 0x80 && map->GetMapDataAt(MAP_RESOURCES,y*width+x)  < 0x90)
				GetNode(x,y).resources = 0x84;
		}
	}

	/// Weltmeere vermessen
	for(unsigned y = 0;y<height;++y)
	{
		for(unsigned x = 0;x<width;++x)
		{
			// Noch kein Meer an diesem Punkt?
			if(!GetNode(x,y).sea_id)
			{
				// Aber trotzdem Teil eines noch nicht vermessenen Meeres?
				if(IsSeaPoint(x,y))
				{
					unsigned sea_size = MeasureSea(x,y,seas.size());
					seas.push_back(Sea(sea_size));
				}
			}
		}
	}

	/// Die Meere herausfinden, an die die Hafenpunkte grenzen
	for(unsigned i = 0;i<harbor_pos.size();++i)
	{
		for(unsigned z = 0;z<6;++z)
			harbor_pos[i].cps[z].sea_id = IsCoastalPoint(GetXA(harbor_pos[i].x,harbor_pos[i].y,z),
			GetYA(harbor_pos[i].x,harbor_pos[i].y,z));
	}

	// Nachbarn der einzelnen Hafenplätze ermitteln
	CalcHarborPosNeighbors();

	/// Schatten und BQ berechnen
	for(unsigned y = 0;y<height;++y)
	{
		for(unsigned x = 0;x<width;++x)
		{
			RecalcShadow(x,y);
			SetBQ(x,y,GAMECLIENT.GetPlayerID());
		}
	}

	/// Bei FoW und aufgedeckt müssen auch die ersten FoW-Objekte erstellt werden
	if(GameClient::inst().GetGGS().exploration == GlobalGameSettings::EXP_FOGOFWARE_EXPLORED)
	{
		for(unsigned y = 0;y<height;++y)
		{
			for(unsigned x = 0;x<width;++x)
			{
				// Alle Spieler durchgehen
				for(unsigned i = 0;i<GameClient::inst().GetPlayerCount();++i)
				{
					// An der Stelle FOW für diesen Spieler?
					if(GetNode(x,y).fow[i].visibility == VIS_FOW)
						SaveFOWNode(x,y,i);
				}
			}
		}
	}
		
}
Exemplo n.º 22
0
 const Species species() const
 {
     return Species(species_serial());
 }