void MotionMaster::MoveKnockbackFrom(float srcX, float srcY, float speedXY, float speedZ) { //this function may make players fall below map if (_owner->GetTypeId() == TYPEID_PLAYER) return; float x, y, z; float moveTimeHalf = speedZ / Movement::gravity; float dist = 2 * moveTimeHalf * speedXY; float max_height = -Movement::computeFallElevation(moveTimeHalf, false, -speedZ); _owner->GetNearPoint(_owner, x, y, z, _owner->GetObjectSize(), dist, _owner->GetAngle(srcX, srcY) + M_PI); Movement::MoveSplineInit init(*_owner); init.MoveTo(x, y, z); init.SetParabolic(max_height, 0); init.SetOrientationFixed(true); init.SetVelocity(speedXY); init.Launch(); Mutate(new EffectMovementGenerator(0), MOTION_SLOT_CONTROLLED); }
void MotionMaster::MoveFall(uint32 id/*=0*/) { // use larger distance for vmap height search than in most other cases float tz = _owner->GetMap()->GetHeight(_owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ(), true, MAX_FALL_DISTANCE); if (tz <= INVALID_HEIGHT) { sLog->outStaticDebug("MotionMaster::MoveFall: unable retrive a proper height at map %u (x: %f, y: %f, z: %f).", _owner->GetMap()->GetId(), _owner->GetPositionX(), _owner->GetPositionX(), _owner->GetPositionZ()); return; } // Abort too if the ground is very near if (fabs(_owner->GetPositionZ() - tz) < 0.1f) return; Movement::MoveSplineInit init(*_owner); init.MoveTo(_owner->GetPositionX(), _owner->GetPositionY(),tz); init.SetFall(); init.Launch(); Mutate(new EffectMovementGenerator(id), MOTION_SLOT_CONTROLLED); }
void MotionMaster::MoveFall() { // use larger distance for vmap height search than in most other cases float tz = m_owner->GetMap()->GetHeight(m_owner->GetPhaseMask(), m_owner->GetPositionX(), m_owner->GetPositionY(), m_owner->GetPositionZ(), true, MAX_FALL_DISTANCE); if (tz <= INVALID_HEIGHT) { sLog.outError("MotionMaster::MoveFall: unable retrive a proper height at map %u (x: %f, y: %f, z: %f).", m_owner->GetMap()->GetId(), m_owner->GetPositionX(), m_owner->GetPositionY(), m_owner->GetPositionZ()); return; } // Abort too if the ground is very near if (fabs(m_owner->GetPositionZ() - tz) < 0.1f) return; Movement::MoveSplineInit init(*m_owner); init.MoveTo(m_owner->GetPositionX(),m_owner->GetPositionY(),tz); init.SetFall(); init.Launch(); Mutate(new EffectMovementGenerator(0), UNIT_ACTION_EFFECT); }
void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) { if (_owner->GetTypeId() == TYPEID_PLAYER) { if (path < sTaxiPathNodesByPath.size()) { FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(sTaxiPathNodesByPath[path], pathnode); Mutate(mgen, MOTION_SLOT_CONTROLLED); } else { TC_LOG_ERROR("misc", "%s attempt taxi to (not existed Path %u node %u)", _owner->GetName().c_str(), path, pathnode); } } else { TC_LOG_ERROR("misc", "Creature (Entry: %u GUID: %u) attempt taxi to (Path %u node %u)", _owner->GetEntry(), _owner->GetGUIDLow(), path, pathnode); } }
void MotionMaster::MoveTargetedHome() { // if (m_owner->hasUnitState(UNIT_STAT_LOST_CONTROL)) // return; if (m_owner->GetTypeId() == TYPEID_UNIT && !((Creature*)m_owner)->GetCharmerOrOwnerGuid()) { // Manual exception for linked mobs if (m_owner->IsLinkingEventTrigger() && m_owner->GetMap()->GetCreatureLinkingHolder()->TryFollowMaster((Creature*)m_owner)) DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "MotionMaster: %s refollowed linked master", m_owner->GetGuidStr().c_str()); else { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "MotionMaster: %s targeted home", m_owner->GetGuidStr().c_str()); Mutate(new HomeMovementGenerator<Creature>(), UNIT_ACTION_HOME); } } else if (m_owner->GetTypeId() == TYPEID_UNIT && ((Creature*)m_owner)->GetCharmerOrOwnerGuid()) { if (Unit* target = ((Creature*)m_owner)->GetCharmerOrOwner()) { float angle = ((Creature*)m_owner)->IsPet() ? ((Pet*)m_owner)->GetPetFollowAngle() : PET_FOLLOW_ANGLE; DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "MotionMaster: %s follow to %s", m_owner->GetGuidStr().c_str(), target->GetGuidStr().c_str()); switch (((Creature*)m_owner)->GetCharmState(CHARM_STATE_COMMAND)) { case COMMAND_STAY: MoveIdle(); break; case COMMAND_FOLLOW: case COMMAND_ATTACK: default: MoveFollow(target, PET_FOLLOW_DIST, angle); break; } } else DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "%s attempt but fail to follow owner", m_owner->GetGuidStr().c_str()); } else sLog.outError("MotionMaster: %s attempt targeted home", m_owner->GetGuidStr().c_str()); }
void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) { if (m_owner->GetTypeId() == TYPEID_PLAYER) { if (path < sTaxiPathNodesByPath.size()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "%s taxi to (Path %u node %u)", m_owner->GetGuidStr().c_str(), path, pathnode); FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(sTaxiPathNodesByPath[path], pathnode); Mutate(mgen); } else { sLog.outError("%s attempt taxi to (nonexistent Path %u node %u)", m_owner->GetGuidStr().c_str(), path, pathnode); } } else { sLog.outError("%s attempt taxi to (Path %u node %u)", m_owner->GetGuidStr().c_str(), path, pathnode); } }
void MotionMaster::MovePath(uint32 path_id, bool repeatable) { if (!path_id) return; //We set waypoint movement as new default movement generator // clear ALL movement generators (including default) /*while (!empty()) { MovementGenerator *curr = top(); curr->Finalize(*_owner); pop(); if (!isStatic(curr)) delete curr; }*/ //_owner->GetTypeId() == TYPEID_PLAYER ? //Mutate(new WaypointMovementGenerator<Player>(path_id, repeatable)): Mutate(new WaypointMovementGenerator<Creature>(path_id, repeatable), MOTION_SLOT_IDLE); TC_LOG_DEBUG("misc", "%s start moving over path (Id:%u, repeatable: %s)", _owner->GetGUID().ToString().c_str(), path_id, repeatable ? "YES" : "NO"); }
void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) { if(i_owner->GetTypeId() == TYPEID_PLAYER) { if(path < sTaxiPathNodesByPath.size()) { sLog->outStaticDebug("%s taxi to (Path %u node %u)", i_owner->GetName(), path, pathnode); FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(sTaxiPathNodesByPath[path], pathnode); Mutate(mgen, MOTION_SLOT_CONTROLLED); } else { sLog->outError("%s attempt taxi to (not existed Path %u node %u)", i_owner->GetName(), path, pathnode); } } else { sLog->outError("Creature (Entry: %u GUID: %u) attempt taxi to (Path %u node %u)", i_owner->GetEntry(), i_owner->GetGUIDLow(), path, pathnode); } }
void MotionMaster::MoveWaypoint(int32 id /*=0*/, uint32 source /*=0==PATH_NO_PATH*/, uint32 initialDelay /*=0*/, uint32 overwriteEntry /*=0*/) { if (m_owner->GetTypeId() == TYPEID_UNIT) { if (GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE) { sLog.outError("%s attempt to MoveWaypoint() but is already using waypoint", m_owner->GetGuidStr().c_str()); return; } Creature* creature = (Creature*)m_owner; DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "%s start MoveWaypoint()", m_owner->GetGuidStr().c_str()); WaypointMovementGenerator<Creature>* newWPMMgen = new WaypointMovementGenerator<Creature>(*creature); Mutate(newWPMMgen); newWPMMgen->InitializeWaypointPath(*creature, id, (WaypointPathOrigin)source, initialDelay, overwriteEntry); } else { sLog.outError("Non-creature %s attempt to MoveWaypoint()", m_owner->GetGuidStr().c_str()); } }
int CONTROLLER::Mutate_Biased(double mutationProbability) { int mutationOccurred = false; for (int i=0; i<numTimeSteps; i++) { for (int j=0; j<numMotorGroups; j++) { if ( Rand(0,1) < mutationProbability ) { Mutate(i,j); mutationOccurred = true; } } } motors->Print(); printf("\n"); return( mutationOccurred ); }
//! Reproduce candidates to create the next generation. void CNE::Reproduce() { // Sort fitness values. Smaller fitness value means better performance. index = arma::sort_index(fitnessValues); // First parent. size_t mom; // Second parent. size_t dad; for (size_t i = numElite; i < populationSize - 1; i++) { // Select 2 different parents from elite group randomly [0, numElite). mom = mlpack::math::RandInt(0, numElite); dad = mlpack::math::RandInt(0, numElite); // Making sure both parents are not the same. if (mom == dad) { if (dad != numElite - 1) { dad++; } else { dad--; } } // Parents generate 2 children replacing the dropped-out candidates. // Also finding the index of these candidates in the population matrix. Crossover(index[mom], index[dad], index[i], index[i + 1]); } // Mutating the weights with small noise values. // This is done to bring change in the next generation. Mutate(); }
void MotionMaster::MoveJump(float x, float y, float z, float speedXY, float speedZ, uint32 id) { sLog->outDebug(LOG_FILTER_GENERAL, "Unit (GUID: %u) jump to point (X: %f Y: %f Z: %f)", _owner->GetGUIDLow(), x, y, z); if (speedXY <= 0.1f) return; float moveTimeHalf = speedZ / Movement::gravity; float max_height = -Movement::computeFallElevation(moveTimeHalf, false, -speedZ); int32 timerToDestination = 0; Movement::MoveSplineInit init(_owner); init.MoveTo(x, y, z, false); init.SetParabolic(max_height, 0); init.SetVelocity(speedXY); timerToDestination = init.Launch(); if (_owner->ToPlayer()) _owner->ToPlayer()->SetJumpTimerDestination(timerToDestination + 100); Mutate(new EffectMovementGenerator(id), MOTION_SLOT_CONTROLLED); }
void MotionMaster::MoveTargetedHome() { if(i_owner->hasUnitState(UNIT_STAT_FLEEING)) return; Clear(false); if(i_owner->GetTypeId()==TYPEID_UNIT && !((Creature*)i_owner)->GetCharmerOrOwnerGUID()) { DEBUG_LOG("Creature (Entry: %u GUID: %u) targeted home", i_owner->GetEntry(), i_owner->GetGUIDLow()); Mutate(new HomeMovementGenerator<Creature>()); } else if(i_owner->GetTypeId()==TYPEID_UNIT && ((Creature*)i_owner)->GetCharmerOrOwnerGUID()) { sLog.outError("Pet or controlled creature (Entry: %u GUID: %u) attempt targeted home", i_owner->GetEntry(), i_owner->GetGUIDLow() ); } else { sLog.outError("Player (GUID: %u) attempt targeted home", i_owner->GetGUIDLow() ); } }
void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) { if(i_owner->GetTypeId()==TYPEID_PLAYER) { if(path < sTaxiPathNodesByPath.size()) { DEBUG_LOG("Player (GUID: %u) taxi to (Path %u node %u)", i_owner->GetGUIDLow(), path, pathnode); FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(sTaxiPathNodesByPath[path],pathnode); Mutate(mgen); } else { sLog.outError("Creature (Entry: %u GUID: %u) attempt taxi to (Path %u node %u)", i_owner->GetEntry(), i_owner->GetGUIDLow(), path, pathnode ); } } else { sLog.outError("%u attempt taxi to (Path %u node %u)", i_owner->GetGUIDLow(), path, pathnode ); } }
void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) { if(i_owner->GetTypeId()==TYPEID_PLAYER) { if(path < sTaxiPathNodesByPath.size()) { DEBUG_LOG("%s taxi to (Path %u node %u)", i_owner->GetObjectGuid().GetString().c_str(), path, pathnode); FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(sTaxiPathNodesByPath[path],pathnode); Mutate(mgen); } else { sLog.outError("%s attempt taxi to (not existed Path %u node %u)", i_owner->GetObjectGuid().GetString().c_str(), path, pathnode ); } } else { sLog.outError("%s attempt taxi to (Path %u node %u)", i_owner->GetObjectGuid().GetString().c_str(), path, pathnode ); } }
void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) { if (_owner->GetTypeId() == TYPEID_PLAYER) { if (path < sTaxiPathNodesByPath.size()) { TC_LOG_DEBUG("misc", "%s taxi to (Path %u node %u).", _owner->GetName().c_str(), path, pathnode); FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(pathnode); mgen->LoadPath(_owner->ToPlayer()); Mutate(mgen, MOTION_SLOT_CONTROLLED); } else { TC_LOG_ERROR("misc", "%s attempted taxi to (non-existing Path %u node %u).", _owner->GetName().c_str(), path, pathnode); } } else { TC_LOG_ERROR("misc", "Creature (Entry: %u GUID: %u) attempted taxi to (Path %u node %u).", _owner->GetEntry(), _owner->GetGUID().GetCounter(), path, pathnode); } }
void MotionMaster::MovePath(uint32 path_id, bool repeatable) { if (!path_id) return; //We set waypoint movement as new default movement generator // clear ALL movement generators (including default) /*while (!empty()) { MovementGenerator *curr = top(); curr->Finalize(*i_owner); pop(); if (!isStatic(curr)) delete curr; }*/ //i_owner->GetTypeId() == TYPEID_PLAYER ? //Mutate(new WaypointMovementGenerator<Player>(path_id, repeatable)): Mutate(new WaypointMovementGenerator<Creature>(path_id, repeatable), MOTION_SLOT_IDLE); sLog->outStaticDebug("%s (GUID: %u) start moving over path(Id:%u, repeatable: %s)", _owner->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature", _owner->GetGUIDLow(), path_id, repeatable ? "YES" : "NO"); }
void MotionMaster::MoveFall(uint32 id/*=0*/) { // use larger distance for vmap height search than in most other cases float tz = _owner->GetMap()->GetHeight(_owner->GetPhaseMask(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ(), true, MAX_FALL_DISTANCE);; // try to find ground Z if (tz <= INVALID_HEIGHT) tz = _owner->GetMap()->GetHeight(_owner->GetPhaseMask(), _owner->GetPositionX(), _owner->GetPositionY(), MAX_HEIGHT, true, MAX_FALL_DISTANCE); if (tz <= INVALID_HEIGHT) { TC_LOG_DEBUG("misc", "MotionMaster::MoveFall: unable retrive a proper height at map %u (x: %f, y: %f, z: %f).", _owner->GetMap()->GetId(), _owner->GetPositionX(), _owner->GetPositionX(), _owner->GetPositionZ()); return; } // Abort too if the ground is very near if (fabs(_owner->GetPositionZ() - tz) < 0.1f) return; if (_owner->GetTypeId() == TYPEID_PLAYER) { _owner->AddUnitMovementFlag(MOVEMENTFLAG_FALLING); _owner->m_movementInfo.SetFallTime(0); } Position pos = _owner->GetPosition(); pos.m_positionZ = tz; _owner->GetFirstCollisionPosition(pos, fabs(_owner->GetPositionZ() - tz), 0); tz = pos.GetPositionZ(); Movement::MoveSplineInit init(_owner); init.MoveTo(_owner->GetPositionX(), _owner->GetPositionY(), tz); init.SetFall(); init.Launch(); Mutate(new EffectMovementGenerator(id), MOTION_SLOT_CONTROLLED); }
void MotionMaster::MoveCirclePath(float x, float y, float z, float radius, bool clockwise, uint8 stepCount) { float step = 2 * float(M_PI) / stepCount * (clockwise ? -1.0f : 1.0f); Position const& pos = { x, y, z, 0.0f }; float angle = pos.GetAbsoluteAngle(_owner->GetPositionX(), _owner->GetPositionY()); Movement::MoveSplineInit init(_owner); for (uint8 i = 0; i < stepCount; angle += step, ++i) { G3D::Vector3 point; point.x = x + radius * cosf(angle); point.y = y + radius * sinf(angle); if (_owner->IsFlying()) point.z = z; else point.z = _owner->GetMapHeight(point.x, point.y, z) + _owner->GetHoverOffset(); init.Path().push_back(point); } if (_owner->IsFlying()) { init.SetFly(); init.SetCyclic(); init.SetAnimation(Movement::ToFly); } else { init.SetWalk(true); init.SetCyclic(); } Mutate(new GenericMovementGenerator(std::move(init), EFFECT_MOTION_TYPE, 0), MOTION_SLOT_ACTIVE); }
void MotionMaster::MoveFall(uint32 id /*=0*/) { // use larger distance for vmap height search than in most other cases float tz = _owner->GetMap()->GetHeight(_owner->GetPhaseMask(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ(), true, MAX_FALL_DISTANCE); if (tz <= INVALID_HEIGHT) { TC_LOG_DEBUG("misc", "MotionMaster::MoveFall: unable retrive a proper height at map %u (x: %f, y: %f, z: %f).", _owner->GetMap()->GetId(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ()); return; } // Abort too if the ground is very near if (std::fabs(_owner->GetPositionZ() - tz) < 0.1f) return; if (_owner->GetTypeId() == TYPEID_PLAYER) _owner->SetFall(true); Movement::MoveSplineInit init(_owner); init.MoveTo(_owner->GetPositionX(), _owner->GetPositionY(), tz, false); init.SetFall(); init.Launch(); Mutate(new EffectMovementGenerator(id), MOTION_SLOT_CONTROLLED); }
void MP4ContentIdDescriptor::Read(MP4File* pFile) { ReadHeader(pFile); /* read the first property, 'compatiblity' */ ReadProperties(pFile, 0, 1); /* if compatiblity != 0 */ if (((MP4Integer8Property*)m_pProperties[0])->GetValue() != 0) { /* we don't understand it */ VERBOSE_READ(pFile->GetVerbosity(), printf("incompatible content id descriptor\n")); return; } /* read the next four properties */ ReadProperties(pFile, 1, 4); /* which allows us to reconfigure ourselves */ Mutate(); /* read the remaining properties */ ReadProperties(pFile, 5); }
void MotionMaster::MoveIdle() { //! Should be preceded by MovementExpired or Clear if there's an overlying movementgenerator active if (empty() || !isStatic(top())) Mutate(&si_idleMovement, MOTION_SLOT_IDLE); }
void MotionMaster::MoveIdle(MovementSlot slot) { if(!isStatic(Impl[slot])) Mutate(&si_idleMovement, slot); }
void PlayTest_Tune(unsigned int rollbacks, unsigned int plays, unsigned int population_size, unsigned int tournament_size, unsigned int latency) { std::mt19937 rng(RandomSeed()); // create initial population std::vector<TuneElement> population(population_size); for(unsigned int i = 0; i < population_size; ++i) { GetDefaultHeuristicParameters(&population[i].m_parameters); population[i].m_score = 20000; // guess, should be relatively low } // simulate plays std::vector<TuneElement> history(plays); std::vector<std::future<unsigned int> > futures(latency); for(unsigned int p = 0; p < plays + latency; ++p) { std::cout << "Tune progress: " << 100 * p / (plays + latency) << "%" << std::endl; // add completed play to the population if(p >= latency) { history[p - latency].m_score = futures[p % latency].get(); population[(p - latency) % population_size] = history[p - latency]; } // tournament selection TuneElement best1, best2; GetDefaultHeuristicParameters(&best1.m_parameters); GetDefaultHeuristicParameters(&best2.m_parameters); best1.m_score = 0; best2.m_score = 0; for(unsigned int t = 0; t < tournament_size; ++t) { unsigned int sel1 = rng() % population_size; if(population[sel1].m_score > best1.m_score) best1 = population[sel1]; unsigned int sel2 = rng() % population_size; if(population[sel2].m_score > best2.m_score) best2 = population[sel2]; } // create winner HeuristicParameters winner; std::cout << "Winner (" << best1.m_score << "|" << best2.m_score << "): "; for(unsigned int i = 0; i < PARAM_COUNT; ++i) { winner.m_values[i] = (best1.m_parameters.m_values[i] + best2.m_parameters.m_values[i] + (rng() & 1)) / 2; std::cout << winner.m_values[i] << " "; } std::cout << std::endl; if(p < plays) { // do some mutations for(unsigned int i = 0; i < PARAM_COUNT; ++i) { winner.m_values[i] = Mutate(winner.m_values[i], PARAMETERS_MIN[i], PARAMETERS_MAX[i], PARAMETERS_STEP[i], rng); } // start the job history[p].m_parameters = winner; futures[p % latency] = StartJob(PlayTest, winner, rollbacks, (BoardDB*) NULL, (std::mutex*) NULL); } } std::cout << "scores = array([\n\t"; for(unsigned int p = 0; p < plays; ++p) { std::cout << history[p].m_score; if(p != plays - 1) { if(p % 20 == 19) std::cout << ",\n\t"; else std::cout << ", "; } } std::cout << "])" << std::endl; // calculate population average HeuristicParameters population_average; std::cout << "Population average: "; for(unsigned int i = 0; i < PARAM_COUNT; ++i) { population_average.m_values[i] = 0; for(unsigned int p = 0; p < population_size; ++p) { population_average.m_values[i] += population[p].m_parameters.m_values[i]; } population_average.m_values[i] = (population_average.m_values[i] + population_size / 2) / population_size; std::cout << population_average.m_values[i] << " "; } std::cout << std::endl; }
Generate() { static int rsflag = 1; /* flag cleared after restart */ STRUCTURE *temp; /* for swapping population pointers */ register int i; /* for marking structures */ if (Traceflag) printf(" Gen %d\n",Gen); Trace("Generate entered"); /* create a new population */ if (Restartflag && rsflag) { /* this is a restart so read checkpoint file */ Restart(); rsflag = 0; /* disable local restart flag. */ Converge(); } else if (Gen == 0) /* this is a fresh experiment */ { Initialize(); /* form an initial population */ Spin++; } else /* form a new population from */ /* the old one via genetic operators */ { Select(); Mutate(); Crossover(); if (Eliteflag) Elitist(); if (Allflag) /* mark structures for evaluation */ for (i=0; i<Popsize; i++) New[i].Needs_evaluation = 1; Spin++; } /* evaluate the newly formed population */ Evaluate(); /* gather performance statistics */ Measure(); /* check termination condition for this experiment */ Doneflag = Done(); /* checkpoint if appropriate */ if (Num_dumps && Dump_freq && Gen % Dump_freq == 0) { if (Num_dumps > 1) { sprintf(Dumpfile, "dump.%d", Curr_dump); Curr_dump = (Curr_dump + 1) % Num_dumps; Checkpoint(Dumpfile); } Checkpoint(Ckptfile); } else { if (Doneflag) { if (Lastflag) Checkpoint(Ckptfile); else if (Savesize) Printbest(); } } /* swap pointers for next generation */ temp = Old; Old = New; New = temp; /* update generation counter */ Gen++; Trace("Generate completed"); }
void GA::Execute(){ std::cout << "Solving TSP\n"; SDL_Window *window = NULL; //SDL_Surface *surface; SDL_Init(SDL_INIT_VIDEO); const int wWidth = 640; const int wHeight = 480; window = SDL_CreateWindow("TSP Visualizer",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, wWidth,wHeight,SDL_WINDOW_OPENGL); //surface = SDL_GetWindowSurface(window); SDL_UpdateWindowSurface(window); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); std::vector<SDL_Rect> cityDots; for(const auto& c : baseCityVector){ SDL_Rect dot; dot.x = c.getX() * wWidth / maxXPosition - 2; dot.y = c.getY() * wHeight / maxYPosition - 2; dot.w = 4; dot.h = 4; cityDots.push_back(dot); } for(int g = 1; g < targetGenerationNumber; g++){ currentGeneration = g; std::cout << "Current generation: " << g << "\n"; SortCandidates(); //std::cout << "Sorted population\n"; parentsPopulation.clear(); SelectParents(populationBreadersPercentage); int childrenPopulationSize = populationSize * populationBreadersPercentage / 100; //std::cout << "Childrem population size: " << childrenPopulationSize << "\n"; while(newPopulation.size() < childrenPopulationSize){ //std::cout << "New pop size: " << newPopulation.size() << "\n"; auto parent1 = parentsPopulation.at( std::rand() % parentsPopulation.size() ); auto parent2 = parentsPopulation.at( std::rand() % parentsPopulation.size() ); //std::future<Candidate> fChild1 = std::async(GA::PMXCrossover,parent1,parent2); Candidate child1 = PMXCrossover(parent1,parent2); Candidate child2 = PMXCrossover(parent2,parent1); //if(std::find(newPopulation.begin(),newPopulation.end(),child) == newPopulation.end()) newPopulation.push_back ( child1 ); newPopulation.push_back ( child2 ); } //std::cout << "Created new population\n"; for(int m = 1; m <= newPopulation.size() * mutationPercentage / 100; m++){ //auto mutant = newPopulation[std::rand() % newPopulation.size()]; auto mutant = newPopulation[ (std::rand() * m) % newPopulation.size()]; Mutate(mutant, mutationPower); mutant.ReEvaluate(distances); } //std::cout << "Mutated population\n"; population.insert(population.end(), newPopulation.begin(), newPopulation.end()); newPopulation.clear(); NormalizeCandidates(); SortCandidates(); population = std::vector<Candidate>(population.begin(),population.begin()+populationSize); std::cout << "Best: " << population.at(0) << "\n"; SDL_SetRenderDrawColor(renderer, 255,255,255,255); SDL_RenderClear(renderer); std::vector<SDL_Point> cityPositions; /* int maxX; int maxY; for(const auto& city : getBest().getCandidate()){ maxX = 0; maxY = 0; if(city.getX() > maxX) maxX = city.getX(); if(city.getY() > maxY) maxY = city.getY(); } */ for(const auto& city : population[0].getCandidate()){ int posY = city.getY() * wHeight / maxYPosition; int posX = city.getX() * wWidth / maxXPosition; SDL_Point position; position.y = city.getY() * wHeight / maxYPosition; position.x = city.getX() * wWidth / maxXPosition; cityPositions.push_back(position); } SDL_SetRenderDrawColor(renderer, 255,0,0,255); SDL_RenderDrawLines(renderer, &cityPositions[0], cityPositions.size()); SDL_SetRenderDrawColor(renderer, 0,255,0,255); SDL_RenderFillRects(renderer, &cityDots[0], cityDots.size()); SDL_RenderPresent(renderer); /* if(renderer == NULL){ SDL_RenderDrawLine(renderer, g*10, g, 250, 250); } */ } SDL_DestroyWindow(window); SDL_Quit(); }
// set new default movement generator void MotionMaster::InitDefault() { Mutate(FactorySelector::SelectMovementGenerator(_owner), MOTION_SLOT_IDLE); }
void MotionMaster::MovePath(WaypointPath& path, bool repeatable) { TC_LOG_DEBUG("movement.motionmaster", "MotionMaster::MovePath: '%s', starts moving over path Id: %u (repeatable: %s)", _owner->GetGUID().ToString().c_str(), path.id, repeatable ? "YES" : "NO"); Mutate(new WaypointMovementGenerator<Creature>(path, repeatable), MOTION_SLOT_IDLE); }
void MotionMaster::MoveDistract(uint32 timer) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "%s distracted (timer: %u)", m_owner->GetGuidStr().c_str(), timer); DistractMovementGenerator* mgen = new DistractMovementGenerator(timer); Mutate(mgen); }
void MotionMaster::MoveAlongSplineChain(uint32 pointId, std::vector<SplineChainLink> const& chain, bool walk) { Mutate(new SplineChainMovementGenerator(pointId, chain, walk), MOTION_SLOT_ACTIVE); }