void cancelCB(GoalHandle& gh) { boost::mutex::scoped_lock l(goals_mutex_); ROS_DEBUG("GoalHandle canceled"); // search for goal handle and remove it from active_goals_ list for(std::list<boost::shared_ptr<ClientGoalInfo> >::iterator it = active_goals_.begin(); it != active_goals_.end();) { ClientGoalInfo& info = **it; if(info.handle == gh) { it = active_goals_.erase(it); info.timer_.stop(); info.handle.setCanceled(); return; } else ++it; } }
extern "C" int tic_tac_toe_test2() { extern void init_Vnet(void); extern void load_Vnet(void); extern void save_Vnet(char *); extern double get_V(int x[9]); extern void train_V(int x[9], double v); extern void learn_V(int x[9], int y[9]); extern void beep(); // Build states for RL player 1 cout << "Loading player 1's V values...\n"; states1.clear(); int totalStates1 = loadVFromFile("ttt1.dat", states1, V1); cout << "Total read: " << to_string(totalStates1) << "\n"; //*** Train player1's V network cout << "[i] = init new net and train with end state values\n"; cout << "[o] = train with old V\n"; cout << "[t] = train with end state values\n"; cout << "[r] = init new net with random weights\n"; cout << "[-] = just load net\n"; char key; do key = getchar(); while (key == '\n'); if (key == 'i' || key == 'r') init_Vnet(); else load_Vnet(); if (key == 'o') { for (int t = 0; t < 10000; ++t) { // For all states for (std::list<State>::iterator itr = states1.begin(); itr != states1.end(); ++itr) { State s = *itr; double v = V1.at(s); train_V(s.x, v); } double absError = 0.0; // sum of abs(error) // Calculate error for (std::list<State>::iterator itr = states1.begin(); itr != states1.end(); ++itr) { State s = *itr; double v = V1.at(s); //cout << "v = " << to_string(v) << "\t"; double v2 = get_V(s.x); //cout << "v2 = " << to_string(v2) << "\t"; double error = v - v2; // ideal - actual //cout << "err = " << to_string(error) << "\n"; absError += fabs(error); } printf("(%05d) ", t); printf("∑ abs err = %.1f (avg = %.3f)\r", absError, absError / 8533.0); if (isnan(absError)) { init_Vnet(); t = 0; } } cout << "\n\n"; save_Vnet("v.net"); } else if (key == 't' || key == 'i') { for (int t = 0; t < 500; ++t) { // For all states for (std::list<State>::iterator itr = states1.begin(); itr != states1.end(); ++itr) { State s = *itr; board = s; int result = hasWinner(); double v; if (result == -2) v = 0.5; else if (result == -1) v = 0.0; else if (result == 1) v = 1.0; if (result != 0) train_V(s.x, v); } double absError = 0.0; // sum of abs(error) // Calculate error for (std::list<State>::iterator itr = states1.begin(); itr != states1.end(); ++itr) { State s = *itr; board = s; int result = hasWinner(); double v; double v2 = get_V(s.x); //cout << "v2 = " << to_string(v2) << "\t"; if (result == -2) v = 0.5; else if (result == -1) v = 0.0; else if (result == 1) v = 1.0; double error = v - v2; // ideal - actual //cout << "err = " << to_string(error) << "\n"; if (result == 0) error = 0.0; absError += fabs(error); } printf("(%05d) ", t); printf("∑ abs err = %.1f (avg = %.3f)\r", absError, absError / 8533.0); if (isnan(absError)) { init_Vnet(); t = 0; } } cout << "\n\n"; save_Vnet("v.net"); } // Build states for RL player 1 cout << "\n\nLoading player -1...\n"; states2.clear(); int totalStates2 = loadVFromFile("ttt2.dat", states2, V2); cout << "Total read: " << to_string(totalStates2) << "\n"; #define totalGames 500000 int playTimes = 0; int numPlayer1Won = 0; int numPlayer_1Won = 0; int numDraws = 0; int player = 1; while (true) // Loop over 1000 trials { initBoard(); player = ((rand() / (double) RAND_MAX) > 0.5) ? 1 : -1; cout << "Game # " << to_string(playTimes) << "\r"; // printState(board); State prev_s1 = State(); // initialized as state "0" State max_s1 = State(); State prev_s2 = State(); State max_s2 = State(); while (true) // Loop over 1 single game { std::list<int> nextMoves; getListOfBlankTiles(nextMoves); int countNextMoves = nextMoves.size(); // cout << "Move of player: " << to_string(player) << "\n"; double exploreRate = 0.1; double ex = (rand() / (double) RAND_MAX); // explore or not? // ************ Make 1 move int userMove; if (player == -1) // Old RL learner { if (ex <= exploreRate) { // generate random # within range of possible moves int move = (int) floor((rand() / (double) RAND_MAX) * countNextMoves); std::list<int>::iterator it = nextMoves.begin(); std::advance(it, move); userMove = *it; //cout << "Exploring move = " << to_string(userMove) << "\n"; updateBoard(player, userMove); prev_s1 = board; } else { userMove = greedyMove(V2, player); //cout << "Greedy move = " << to_string(userMove) << "\n"; // max_s2 should be the new state updateBoard(player, userMove); max_s2 = board; // cout << "V2(s) changed from " << to_string(V2[prev_s2]); BellmanUpdate(max_s2, prev_s2, V2); // cout << "to " << to_string(V2[prev_s2]); prev_s2 = max_s2; } } else // Player 1 (our NN learner) { if (ex <= exploreRate) { int move = (int) floor((rand() / (double) RAND_MAX) * countNextMoves); //cout << "Exploring move = " << to_string(move) << "\n"; std::list<int>::iterator it = nextMoves.begin(); std::advance(it, move); userMove = *it; updateBoard(player, userMove); prev_s1 = board; } else { userMove = computerMove(player); //cout << "Computer move = " << to_string(userMove) << "\n"; updateBoard(player, userMove); max_s1 = board; learn_V(max_s1.x, prev_s1.x); prev_s1 = max_s1; } } //printState(board); int won = hasWinner(); if (won == -2) // draw { numDraws++; train_V(board.x, 0.5); // cout << "It's a draw !\n\n"; break; } if (won != 0) { if (1 == player) // our NN learner wins { ++numPlayer1Won; max_s2 = board; BellmanUpdate(max_s2, prev_s2, V2); train_V(max_s2.x, 1.0); // cout << "V2(s) changed from " << to_string(V2[prev_s2]); // cout << "to " << to_string(V2[prev_s2]); } else // old RL player (-1) wins { ++numPlayer_1Won; max_s1 = board; train_V(max_s1.x, 0.0); learn_V(max_s1.x, prev_s1.x); } // cout << "Winner is: player " << to_string(player) << "\n\n"; break; } // continue with game.... player = switchPlayer(player); } // Next game... ++playTimes; if (playTimes > totalGames) break; //if (getchar() == 'q') // break; } // cout << "\n\nSaving RL values...\n"; // saveStatesToFile("ttt1.dat", states1, V1); // saveStatesToFile("ttt2.dat", states2, V2); cout << "Saving NN learner values...\n"; save_Vnet("v.net"); cout << "\n\nGame stats:\n"; printf("Player 1 Wins %d (%2.1f%%)\n", numPlayer1Won, ((float) numPlayer1Won) / totalGames * 100.0); printf("Player -1 Wins %d (%2.1f%%)\n", numPlayer_1Won, ((float) numPlayer_1Won) / totalGames * 100.0); printf(" Draws %d (%2.1f%%)\n", numDraws, ((float) numDraws) / totalGames * 100.0); beep(); return 0; }
/** * @function smoothPath */ void PathPlanner::smoothPath( int _robotId, const Eigen::VectorXi &_links, std::list<Eigen::VectorXd> &_path ) { // =========== YOUR CODE HERE ================== // HINT: Use whatever technique you like better, first try to shorten a path and then you can try to make it smoother std::cout << "Starting path shortening with simple search..." << _links.size() << std::endl; std::cout << "start path length: " << _path.size() << std::endl; std::list<Eigen::VectorXd>::iterator start_point=_path.begin(),end_point=_path.end(); end_point--; // loop while start has not reached the end of the path while (start_point != _path.end()) { if (start_point == end_point) { //std::cout << "End iteration\n"; ++start_point; end_point = _path.end(); end_point--; } else { //Eigen::VectorXd start_node=*start_point, end_node=*end_point; std::list<Eigen::VectorXd> segment = createPath(_robotId,_links,*start_point, *end_point); double curDist = countDist(start_point, end_point) * stepSize; double shortcutDist = segment.size() * stepSize; if (segment.size()>0 && shortcutDist < curDist) { std::cout << "Shortcut length: " << shortcutDist << std::endl; std::cout << "Current distance: " << curDist << std::endl; std::cout << "Found shortcut!" << std::endl; // reconstruct path // first segment std::list<Eigen::VectorXd> new_path(_path.begin(), start_point); // middle segment new_path.insert(new_path.end(), segment.begin(), segment.end()); // last segment new_path.insert(new_path.end(), end_point, _path.end()); std::cout << "New path length: " << new_path.size() << std::endl; // replace optimized _path = new_path; start_point = _path.begin(); end_point = _path.end(); end_point--; } else { --end_point; } } } std::cout << "Finished Optimizing! Final path length: " << _path.size() << std::endl; return; return; // ======================================== }
PluginGroupNodePtr GuiApplicationManagerPrivate::findPluginToolButtonOrCreateInternal(const std::list<PluginGroupNodePtr>& children, const PluginGroupNodePtr& parent, const PluginPtr& plugin, const QStringList& grouping, const QStringList& groupingIcon) { assert(plugin); assert(groupingIcon.size() == grouping.size() || groupingIcon.isEmpty() ); // On first call of this function, children are top-level toolbuttons // Otherwise this tree node has children // We ensure that the path in the tree leading to the plugin in parameter is created by recursing on the children // If there are no children that means we reached the wanted PluginGroupNode QString nodeIDToFind; if (grouping.empty()) { // Look for plugin ID nodeIDToFind = QString::fromUtf8(plugin->getPluginID().c_str()); } else { // Look for grouping menu item nodeIDToFind = grouping[0]; } for (std::list<PluginGroupNodePtr>::const_iterator it = children.begin(); it != children.end(); ++it) { // If we find a node with the same ID, then we found it already. if ( (*it)->getTreeNodeID() == nodeIDToFind ) { if (grouping.empty()) { // This is a leaf (plug-in), return it return *it; } else { // This is an intermidiate menu item, recurse QStringList newGrouping, newIconsGrouping; for (int i = 1; i < grouping.size(); ++i) { newGrouping.push_back(grouping[i]); } for (int i = 1; i < groupingIcon.size(); ++i) { newIconsGrouping.push_back(groupingIcon[i]); } return findPluginToolButtonOrCreateInternal( (*it)->getChildren(), *it, plugin, newGrouping, newIconsGrouping); } } } // Ok the PluginGroupNode does not exist yet, create it QString treeNodeName, iconFilePath; if (grouping.empty()) { // This is a leaf (plug-in), take the plug-in label and icon treeNodeName = QString::fromUtf8(plugin->getLabelWithoutSuffix().c_str()); iconFilePath = QString::fromUtf8(plugin->getProperty<std::string>(kNatronPluginPropIconFilePath).c_str()); } else { // For menu items, take from grouping treeNodeName = grouping[0]; iconFilePath = groupingIcon.isEmpty() ? QString() : groupingIcon[0]; } PluginGroupNodePtr ret(new PluginGroupNode(grouping.empty() ? plugin : PluginPtr(), treeNodeName, iconFilePath)); // If there is a parent, add it as a child if (parent) { parent->tryAddChild(ret); ret->setParent(parent); } else { // No parent, this is a top-level toolbutton _topLevelToolButtons.push_back(ret); } // If we still did not reach the desired tree node, find it, advancing (removing the first item) in the grouping if (!grouping.empty()) { QStringList newGrouping, newIconsGrouping; for (int i = 1; i < grouping.size(); ++i) { newGrouping.push_back(grouping[i]); } for (int i = 1; i < groupingIcon.size(); ++i) { newIconsGrouping.push_back(groupingIcon[i]); } return findPluginToolButtonOrCreateInternal(ret->getChildren(), ret, plugin, newGrouping, newIconsGrouping); } return ret; } // GuiApplicationManagerPrivate::findPluginToolButtonOrCreateInternal
void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; if (TreeForm_Timer <= diff) { Talk(SAY_TREE); if (me->IsNonMeleeSpellCast(false)) me->InterruptNonMeleeSpells(true); me->RemoveAllAuras(); DoCast(me, SPELL_SUMMON_FRAYER, true); DoCast(me, SPELL_TRANQUILITY, true); DoCast(me, SPELL_TREE_FORM, true); me->GetMotionMaster()->MoveIdle(); MoveFree = false; TreeForm_Timer = 75000; } else TreeForm_Timer -= diff; if (!MoveFree) { if (MoveCheck_Timer <= diff) { if (!Adds_List.empty()) { for (std::list<uint64>::iterator itr = Adds_List.begin(); itr != Adds_List.end(); ++itr) { if (Unit* temp = Unit::GetUnit(*me, *itr)) { if (!temp->IsAlive()) { Adds_List.erase(itr); ++DeadAddsCount; break; } } } } if (DeadAddsCount < 3 && TreeForm_Timer-30000 <= diff) DeadAddsCount = 3; if (DeadAddsCount >= 3) { Adds_List.clear(); DeadAddsCount = 0; me->InterruptNonMeleeSpells(true); me->RemoveAllAuras(); me->GetMotionMaster()->MoveChase(me->GetVictim()); MoveFree = true; } MoveCheck_Timer = 500; } else MoveCheck_Timer -= diff; return; } /*if (me->HasAura(SPELL_TREE_FORM, 0) || me->HasAura(SPELL_TRANQUILITY, 0)) return;*/ //one random seedling every 5 secs, but not in tree form if (SummonSeedling_Timer <= diff) { DoSummonSeedling(); SummonSeedling_Timer = 6000; } else SummonSeedling_Timer -= diff; DoMeleeAttackIfReady(); }
BOOL CALLBACK main_RCONDialogCallback( HWND hDlg, UINT Message, WPARAM wParam, LPARAM lParam ) { char szBuffer[128]; switch ( Message ) { case WM_CTLCOLORSTATIC: switch ( GetDlgCtrlID( (HWND) lParam )) { // Paint these two labels (and the disconnct button's background) white. case IDCANCEL: case IDC_STATUS: case IDC_SERVERSUBINFO: return (LRESULT) g_hWhiteBrush; // Ignore everything else. default: return NULL; } break; case WM_PAINT: { // Paint the top of the form white. PAINTSTRUCT Ps; RECT r; r.left = 0; r.top = 0; r.bottom = 48; r.right = 800; main_PaintRectangle( BeginPaint(hDlg, &Ps), &r, RGB(255, 255, 255)); } break; case WM_INITDIALOG: // Hide the old dialog, and take its place. ShowWindow( g_hDlg, SW_HIDE ); g_hDlg = hDlg; SendDlgItemMessage( hDlg, IDC_CONSOLEBOX, EM_SETLIMITTEXT, 4096, 0 ); SendDlgItemMessage( hDlg, IDC_INPUTBOX, EM_SETLIMITTEXT, 256, 0 ); SetWindowText( hDlg, g_szHostname ); main_SetState( STATE_CONNECTED ); Printf( "\nMap: %s\n", g_szMapname ); // Fill the console with the received history. sprintf( szBuffer, "Connected to \"%s\".", g_szHostname ); SetDlgItemText( hDlg, IDC_CONSOLEBOX, szBuffer ); SetDlgItemText( hDlg, IDC_STATUS, szBuffer ); main_UpdateTrayTooltip( szBuffer ); Printf_NoTimestamp( "\n" ); for( std::list<FString>::iterator i = g_RecentConsoleHistory.begin(); i != g_RecentConsoleHistory.end(); ++i ) Printf_NoTimestamp( "%s", *i ); g_RecentConsoleHistory.clear(); // Set up the top, white section. SendMessage( GetDlgItem( g_hDlg, IDC_STATUS ), WM_SETFONT, (WPARAM) CreateFont( 13, 0, 0, 0, 600, 0, 0, 0, 0, 0, 0, 0, 0, "Tahoma" ), (LPARAM) 1 ); LOGBRUSH LogBrush; LogBrush.lbStyle = BS_SOLID; LogBrush.lbColor = RGB( 255, 255, 255 ); g_hWhiteBrush = CreateBrushIndirect( &LogBrush ); main_UpdateServerStatus( ); // Set up the player list LVCOLUMN ColumnData; ColumnData.mask = LVCF_FMT|LVCF_TEXT|LVCF_WIDTH; ColumnData.fmt = LVCFMT_LEFT; ColumnData.cx = 192; ColumnData.pszText = "Name"; ColumnData.cchTextMax = 64; ColumnData.iSubItem = 0; SendDlgItemMessage( hDlg, IDC_PLAYERLIST, LVM_INSERTCOLUMN, COLUMN_NAME, (LPARAM)&ColumnData ); // Add the cached list of players. LVITEM Item; Item.mask = LVIF_TEXT; Item.iSubItem = COLUMN_NAME; Item.iItem = MAXPLAYERS; while ( g_InitialPlayers.size( ) ) { Item.pszText = (LPSTR) g_InitialPlayers.front( ).GetChars( ); g_InitialPlayers.pop_front( ); SendDlgItemMessage( g_hDlg, IDC_PLAYERLIST, LVM_INSERTITEM, 0, (LPARAM)&Item ) ; } // Load the icon. SendMessage( hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM) (HICON) LoadImage( g_hInst, MAKEINTRESOURCE( AAA_MAIN_ICON ), IMAGE_ICON, 16, 16, LR_SHARED )); SendMessage( hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)LoadIcon( g_hInst, MAKEINTRESOURCE( AAA_MAIN_ICON ))); // Set up the status bar. g_hDlgStatusBar = CreateStatusWindow(WS_CHILD | WS_VISIBLE, (LPCTSTR)NULL, hDlg, IDC_STATIC); g_bRCONDialogVisible = true; break; case WM_COMMAND: switch ( LOWORD( wParam )) { // This also occurs when esc is pressed. case IDCANCEL: main_Quit( ); break; // "Send" button. case IDC_SEND: char szCommand[256]; GetDlgItemText( hDlg, IDC_INPUTBOX, szCommand, sizeof( szCommand )); NETWORK_ClearBuffer( &g_MessageBuffer ); NETWORK_WriteByte( &g_MessageBuffer.ByteStream, CLRC_COMMAND ); if ( szCommand[0] == ':' ) // If the text in the send buffer begins with a :, the admin is just talking. { char szBuffer2[256 + 4]; sprintf( szBuffer2, "say %s", szCommand + 1 ); NETWORK_WriteString( &g_MessageBuffer.ByteStream, szBuffer2 ); break; } else if ( szCommand[0] == '/' ) // If the text in the send buffer begins with a slash, error out -- Skulltag used to require you to do this to send commands. { Printf( "You longer have to prefix commands with a / to send them.\n" ); SetDlgItemText( hDlg, IDC_INPUTBOX, szCommand + 1 ); SendMessage( GetDlgItem( hDlg, IDC_INPUTBOX ), EM_SETSEL, strlen( szCommand ) - 1, strlen( szCommand ) - 1 ); break; } else NETWORK_WriteString( &g_MessageBuffer.ByteStream, szCommand ); NETWORK_LaunchPacket( &g_MessageBuffer, g_ServerAddress ); time( &g_tLastSentCommand ); SetDlgItemText( hDlg, IDC_INPUTBOX, "" ); break; } break; case WM_SYSCOMMAND: // Hide the window when minimized. if ( wParam == SC_MINIMIZE ) ShowWindow( hDlg, SW_HIDE ); else DefWindowProc( hDlg, Message, wParam, lParam ); break; case WM_CLOSE: main_Quit( ); break; case WM_DESTROY: Shell_NotifyIcon( NIM_DELETE, &g_NotifyIconData ); PostQuitMessage( 0 ); break; case UWM_TRAY_TRAYID: return main_TrayIconClicked( hDlg, lParam ); default: return FALSE; } return TRUE; // If this is false, minimizing the window won't hide it. }
void extract_peers_from_bootstrap_nodes_dat(const unsigned char *buffer, std::list<Contact *>& bootstrap_list) { /* The header is so composed: uint32_t reserved0 set to zero uint32_t reserved1 set to 0x00000003 uint32_t bootstrap_edition nodes.dat bootstrap version uint32_t num_entries number of entries in the file */ if(!bootstrap_list.empty()) return; uint32_t reserved0 = *(uint32_t *)&(buffer[0]); uint32_t reserved1 = *(uint32_t *)&(buffer[4]); uint32_t num_entries = *(uint32_t *)&(buffer[12]); if(reserved0 != 0 || reserved1 != 3) // wow: this bootstrap nodes.dat is invalid return; unsigned char *peer = (unsigned char *)&(buffer[16]); /* The peer is so composed: uint64_t low_peer_id 128-bit peer identifier (MD4 of node ID) uint64_t high_peer_id uint32_t peer_ip IP address of the peer uint16_t udp_port peer UDP port number uint16_t tcp_port peer TCP port number unsigned char version peer contact version */ for(unsigned int i = 0; i < num_entries; i++, peer += 25) { uint32_t peer_ip = ntohl(*(uint32_t *)&(peer[16])); uint16_t udp_port = *(uint16_t *)&(peer[20]); uint16_t tcp_port = *(uint16_t *)&(peer[22]); unsigned char version = peer[24]; if(version > 7) { // Only the 50 closest nodes, please uint128_t distance(Kad::get_instance().get_client_id()); uint128_t peer_id = uint128_t::get_from_buffer(peer); distance ^= peer_id; if(bootstrap_list.size() < 50 || bootstrap_list.back()->get_distance() > distance) { Contact *new_peer = new Contact(uint128_t::get_from_buffer(peer), peer_ip, udp_port, tcp_port, version, 0, false); bool peer_added = false; for(std::list<Contact *>::iterator peerIt = bootstrap_list.begin(); peerIt != bootstrap_list.end(); peerIt++) { if((*peerIt)->get_distance() > distance) { bootstrap_list.insert(peerIt, new_peer); peer_added = true; break; } } if(!peer_added) { bootstrap_list.push_back(new_peer); } else if(bootstrap_list.size() > 50) { delete bootstrap_list.back(); bootstrap_list.pop_back(); } } } } }
void show() { std::list<Component*>::iterator i; for(i = list.begin(); i != list.end(); i++) (*i)->show(); }
// This function checks for bacteria to attach to the food nugget. // This is done here because the bacteria attaches to the food through // pointers in this class. void food::check_for_bacteria(std::list<bacteria> & bacteria_list) { std::list<bacteria>::iterator bacteria_iterator; vector food_location = vector(0, 0, x + food_image->get_width() / 2, y + food_image->get_height() / 2); // Iterate through the bacteria list: for(bacteria_iterator = bacteria_list.begin(); bacteria_iterator != bacteria_list.end(); bacteria_iterator++) { bacteria & temp = *bacteria_iterator; vector temp_center = vector(temp.get_vector()); coordinate_pair_t bacteria_dest = temp.get_destination(); float distance = vector::distance_between(temp_center, food_location); temp_center.set_xy(temp_center.get_x() + bacteria_image->get_width() / 2, temp_center.get_y() + bacteria_image->get_height() / 2); // Check if the bacteria is within "smelling distance" of the food: if(distance <= config_db::get().get_float_value("FoodSmellingDistance") && !temp.is_heading_for_food()) { coordinate_pair_t anchor_temp = this->closest_anchor(temp_center); if(!(anchor_temp.x == 0 && anchor_temp.y == 0)) temp.set_destination(anchor_temp); } else if(temp.is_heading_for_food()) { if(CMP_PAIR(bacteria_dest, ANCHOR_1) || CMP_PAIR(bacteria_dest, ANCHOR_2) || CMP_PAIR(bacteria_dest, ANCHOR_3) || CMP_PAIR(bacteria_dest, ANCHOR_4)) { if(AT_DESTINATION(temp_center.get_position(), ANCHOR_1)) { if(anchor_1 != 0 && anchor_1 != &temp) temp.release(); else { anchor_1 = &temp; anchor_1->stop(); } } if(AT_DESTINATION(temp_center.get_position(), ANCHOR_2)) { if(anchor_2 != 0 && anchor_2 != &temp) temp.release(); else { anchor_2 = &temp; anchor_2->stop(); } } if(AT_DESTINATION(temp_center.get_position(), ANCHOR_3)) { if(anchor_3 != 0 && anchor_3 != &temp) temp.release(); else { anchor_3 = &temp; anchor_3->stop(); } } if(AT_DESTINATION(temp_center.get_position(), ANCHOR_4)) { if(anchor_4 != 0 && anchor_4 != &temp) temp.release(); else { anchor_4 = &temp; anchor_4->stop(); } } } } } }
void FilterTargets(std::list<Unit*>& unitList) { if (!GetCaster()->ToPlayer()->GetGroup()) { unitList.clear(); unitList.push_back(GetCaster()); } else { unitList.remove(GetTargetUnit()); std::list<Unit*> tempTargets; for (std::list<Unit*>::const_iterator itr = unitList.begin(); itr != unitList.end(); ++itr) if ((*itr)->GetTypeId() == TYPEID_PLAYER && GetCaster()->IsInRaidWith(*itr)) tempTargets.push_back(*itr); if (tempTargets.empty()) { unitList.clear(); FinishCast(SPELL_FAILED_DONT_REPORT); return; } std::list<Unit*>::const_iterator it2 = tempTargets.begin(); std::advance(it2, urand(0, tempTargets.size() - 1)); unitList.clear(); unitList.push_back(*it2); } }
bool contains(OnlineFileRequest* request) const { return (std::find(queue.begin(), queue.end(), request) != queue.end()); }
void FilterTargets(std::list<WorldObject*>& targets) { if (Unit* caster = GetCaster()) { std::list<GameObject*> blockList; caster->GetGameObjectListWithEntryInGrid(blockList, GO_SARONITE_ROCK, 100.0f); if (!blockList.empty()) { for (std::list<WorldObject*>::iterator itrU = targets.begin(); itrU != targets.end(); ++itrU) if (WorldObject* target = (*itrU)) { bool valid = true; if (!caster->IsWithinMeleeRange(target->ToUnit())) for (std::list<GameObject*>::const_iterator itr = blockList.begin(); itr != blockList.end(); ++itr) if (!(*itr)->IsInvisibleDueToDespawn()) if ((*itr)->IsInBetween(caster, target, 4.0f)) { valid = false; break; } if (valid) { if (Aura* aur = target->ToUnit()->GetAura(70336)) if (aur->GetStackAmount() >= 10 && caster->GetTypeId() == TYPEID_UNIT) caster->ToCreature()->AI()->SetData(1, aur->GetStackAmount()); targetList.push_back(*itrU); } } } else { targetList = targets; return; } } targets = targetList; }
void WorldSession::BuildListAuctionItems(std::list<AuctionEntry*> &auctions, WorldPacket& data, std::wstring const& wsearchedname, uint32 listfrom, uint32 levelmin, uint32 levelmax, uint32 usable, uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, uint32& count, uint32& totalcount, bool isFull) { int loc_idx = _player->GetSession()->GetSessionDbLocaleIndex(); for (std::list<AuctionEntry*>::const_iterator itr = auctions.begin(); itr != auctions.end();++itr) { AuctionEntry *Aentry = *itr; if (Aentry->moneyDeliveryTime) continue; Item *item = sAuctionMgr.GetAItem(Aentry->itemGuidLow); if (!item) continue; if (isFull) { ++count; Aentry->BuildAuctionInfo(data); } else { ItemPrototype const *proto = item->GetProto(); if (itemClass != 0xffffffff && proto->Class != itemClass) continue; if (itemSubClass != 0xffffffff && proto->SubClass != itemSubClass) continue; if (inventoryType != 0xffffffff && proto->InventoryType != inventoryType) continue; if (quality != 0xffffffff && proto->Quality < quality) continue; if (levelmin != 0x00 && (proto->RequiredLevel < levelmin || (levelmax != 0x00 && proto->RequiredLevel > levelmax))) continue; if (usable != 0x00 && _player->CanUseItem(item) != EQUIP_ERR_OK) continue; std::string name = proto->Name1; if (name.empty()) continue; // local name if (loc_idx >= 0) { ItemLocale const *il = sObjectMgr.GetItemLocale(proto->ItemId); if (il) { if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty()) name = il->Name[loc_idx]; } } if (!wsearchedname.empty() && !Utf8FitTo(name, wsearchedname)) continue; if (count < 50 && totalcount >= listfrom) { ++count; Aentry->BuildAuctionInfo(data); } } ++totalcount; } }
void ViewCache::setRealizeViewList(std::list <ViewSpec> realizeViewList) { LOG4CXX_TRACE(mLogger, "setRealizeViewList"); list <ViewSpec> mReallyUnrealizeViewList; list <ViewSpec> mReallyRealizeViewList; // search all views that like to unrealize if maybe one of them is in the next // realize list and then don't unrealize it for (std::list <ViewSpec>::iterator v_it = mUnrealizeViewList.begin(); v_it != mUnrealizeViewList.end(); ++v_it) { ViewSpec &unrealizeViewSpec = *v_it; //View *unrealizeView = viewSpec.view; list <ViewSpec>::iterator found_view_it = find(realizeViewList.begin(), realizeViewList.end(), unrealizeViewSpec); // if view isn't longer in active list mark it to unrealize if (found_view_it == realizeViewList.end()) { LOG4CXX_TRACE(mLogger, "push back unrealize view"); mReallyUnrealizeViewList.push_back(unrealizeViewSpec); } } // search all views that like to realize which one are really new and add those to a realize list for (std::list <ViewSpec>::iterator v_it = realizeViewList.begin(); v_it != realizeViewList.end(); ++v_it) { ViewSpec &realizeViewSpec = *v_it; //View *realizeView = viewSpec.view; list <ViewSpec>::iterator found_view_it = find(mUnrealizeViewList.begin(), mUnrealizeViewList.end(), realizeViewSpec); // if view isn't in old list mark it to realize if (found_view_it == mUnrealizeViewList.end()) { LOG4CXX_TRACE(mLogger, "push back realize view"); mReallyRealizeViewList.push_back(realizeViewSpec); } } // unrealize all before really marked views for (std::list <ViewSpec>::iterator v_it = mReallyUnrealizeViewList.begin(); v_it != mReallyUnrealizeViewList.end(); ++v_it) { ViewSpec &reallyUnrealizeViewSpec = *v_it; View *reallyUnrealizeView = reallyUnrealizeViewSpec.view; LOG4CXX_TRACE(mLogger, "reallyUnrealizeView->unrealize ()"); reallyUnrealizeView->unrealize(); } // unrealize all before really marked views for (std::list <ViewSpec>::iterator v_it = mReallyRealizeViewList.begin(); v_it != mReallyRealizeViewList.end(); ++v_it) { ViewSpec &reallyRealizeViewSpec = *v_it; View *reallyRealizeView = reallyRealizeViewSpec.view; LOG4CXX_TRACE(mLogger, "reallyRealizeView->realize ()"); reallyRealizeView->setLayer(reallyRealizeViewSpec.layer); reallyRealizeView->realize(); } }
/*-----------------------------------------------------------------*/ bool NOMAD::strings_to_direction_type ( const std::list<std::string> & ls , NOMAD::direction_type & dt ) { dt = NOMAD::UNDEFINED_DIRECTION; if ( ls.empty() || ls.size() > 4 ) return false; std::list<std::string>::const_iterator it = ls.begin() , end = ls.end(); std::string s = *it; NOMAD::toupper ( s ); // no direction: if ( s == "NONE" ) { dt = NOMAD::NO_DIRECTION; return true; } // Ortho-MADS with 1, 2, n+1 (plus QUAD or NEG), or 2n directions: if ( s == "ORTHO" ) { ++it; if ( it == end ) { dt = NOMAD::ORTHO_NP1_QUAD; // Default for ORTHO return true; } if ( *it == "1" ) { dt = NOMAD::ORTHO_1; return true; } if ( *it == "2" ) { dt = NOMAD::ORTHO_2; return true; } s = *it; NOMAD::toupper ( s ); if ( s == "2N" ) { dt = NOMAD::ORTHO_2N; return true; } if ( s == "N+1" ) { ++it; if (it==end) { dt = NOMAD::ORTHO_NP1_QUAD; // Default for ORTHO N+1 return true; } s = *it; NOMAD::toupper ( s ); if ( s=="QUAD" ) { dt= NOMAD::ORTHO_NP1_QUAD; return true; } if ( s=="NEG" ) { dt=NOMAD::ORTHO_NP1_NEG; return true; } if ( s=="UNI" ) { dt=NOMAD::ORTHO_NP1_UNI; return true; } } return false; } // LT-MADS with 1, 2 or 2n directions: if ( s == "LT" ) { ++it; if ( it == end ) { dt = NOMAD::LT_2N; return true; } if ( *it == "1" ) { dt = NOMAD::LT_1; return true; } if ( *it == "2" ) { dt = NOMAD::LT_2; return true; } s = *it; NOMAD::toupper ( s ); if ( s == "N+1" ) { dt = NOMAD::LT_NP1; return true; } if ( s == "2N" ) { dt = NOMAD::LT_2N; return true; } return false; } // GPS: if ( s == "GPS" ) { ++it; if ( it == end ) { dt = NOMAD::GPS_2N_STATIC; return true; } s = *it; NOMAD::toupper ( s ); // GPS for binary variables: if ( s == "BINARY" || s == "BIN" ) { dt = NOMAD::GPS_BINARY; return true; } // GPS, n+1 directions: if ( s == "N+1" ) { ++it; if ( it == end ) { dt = NOMAD::GPS_NP1_STATIC; return true; } s = *it; NOMAD::toupper ( s ); // GPS, n+1, static: if ( s == "STATIC" ) { ++it; if ( it == end ) { dt = NOMAD::GPS_NP1_STATIC; return true; } s = *it; NOMAD::toupper ( s ); if ( s == "UNIFORM" ) { dt = NOMAD::GPS_NP1_STATIC_UNIFORM; return true; } return false; } // GPS, n+1, random: if ( s == "RAND" || s == "RANDOM" ) { ++it; if ( it == end ) { dt = NOMAD::GPS_NP1_RAND; return true; } s = *it; NOMAD::toupper ( s ); if ( s == "UNIFORM" ) { dt = NOMAD::GPS_NP1_RAND_UNIFORM; return true; } return false; } return false; } // 2n directions: if ( s == "2N" ) { ++it; if ( it == end ) { dt = NOMAD::GPS_2N_STATIC; return true; } s = *it; NOMAD::toupper ( s ); if ( s == "STATIC" ) { dt = NOMAD::GPS_2N_STATIC; return true; } if ( s == "RAND" || s == "RANDOM" ) { dt = NOMAD::GPS_2N_RAND; return true; } return false; } return false; } return false; }
cache_item(): item(), pos_in_locator_table(-1), position(dummy_list.end()) {}
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static DWORD st = 0; static DWORD dt = 0; static DWORD update_dt = 0; static DWORD update_delay = 20; static HDC hMainDC = NULL; static HDC hMemDC = NULL; static HBITMAP hMemBitmap = NULL; static HBITMAP hOldMemBitmap = NULL; static std::list<Ball*> marble; static bool bDrawLine = false; static Point ptStart; static Point ptEnd; if (uMsg == WM_CREATE) { Rect rc; ::GetClientRect(hWnd, &rc); hMainDC = ::GetDC(hWnd); hMemDC = ::CreateCompatibleDC(hMainDC); hMemBitmap = ::CreateCompatibleBitmap(hMainDC, rc.width(), rc.height()); hOldMemBitmap = ::Select(hMemDC, hMemBitmap); st = ::GetTickCount(); ::SetTimer(hWnd, 0, 10, NULL); return 0; } else if (uMsg == WM_DESTROY) { std::list<Ball*>::iterator it; for (it = marble.begin(); it != marble.end();) { delete *it; it = marble.erase(it); } ::KillTimer(hWnd, 0); ::Select(hMemDC, hOldMemBitmap); ::DeleteObject(hMemBitmap); ::DeleteDC(hMemDC); ::ReleaseDC(hWnd, hMainDC); ::PostQuitMessage(0); return 0; } else if (uMsg == WM_PAINT) { Rect rc; ::GetClientRect(hWnd, &rc); PAINTSTRUCT ps; HDC hdc = ::BeginPaint(hWnd, &ps); // TODO ::SetDCBrushColor(hMemDC, RGB(100,100,150)); ::FillRect(hMemDC, &rc, (HBRUSH)::GetStockObject(DC_BRUSH)); if (bDrawLine) { ::MoveToEx(hMemDC, ptStart.x, ptStart.y, NULL); ::LineTo(hMemDC, ptEnd.x, ptEnd.y); } std::list<Ball*>::iterator it; for (it = marble.begin(); it != marble.end(); it++) { (*it)->Draw(hMemDC); } ::BitBlt(hdc, 0, 0, rc.width(), rc.height(), hMemDC, 0, 0, SRCCOPY); ::EndPaint(hWnd, &ps); return 0; } else if (uMsg == WM_ERASEBKGND) { return 1; } else if (uMsg == WM_LBUTTONDOWN) { ::GetCursorPos(&ptStart); ptStart = ptStart.ToClient(hWnd); ptEnd = ptStart; bDrawLine = true; return 0; } else if (uMsg == WM_MOUSEMOVE) { if (bDrawLine) { ::GetCursorPos(&ptEnd); ptEnd = ptEnd.ToClient(hWnd); Rect rc; ::GetClientRect(hWnd, &rc); ::InvalidateRect(hWnd, &rc, TRUE); } return 0; } else if (uMsg == WM_LBUTTONUP) { bDrawLine = false; ::GetCursorPos(&ptEnd); ptEnd = ptEnd.ToClient(hWnd); Ball* pBall = new Ball; pBall->Attach(hWnd); pBall->SetDirection(Vector(ptEnd - ptStart)/10); pBall->SetSize(10); pBall->SetPosition(ptStart); marble.push_back(pBall); } else if (uMsg == WM_TIMER) { Rect rc; ::GetClientRect(hWnd, &rc); if (update_dt > update_delay) { int count = update_dt / update_delay; for (int i = 0; i < count; i++) { // TODO... std::list<Ball*>::iterator it; for (it = marble.begin(); it != marble.end(); it++) { (*it)->Input(dt); (*it)->Update(dt); } } update_dt %= update_delay; } update_dt += dt; dt = ::GetTickCount() - st; st = ::GetTickCount(); ::InvalidateRect(hWnd, &rc, TRUE); return 0; } return ::DefWindowProc(hWnd,uMsg,wParam,lParam); }
void UpdateAI(uint32 diff) { if (bKaddrakActivated) { if (uiKaddrakEncounterTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) if (!KaddrakGUIDList.empty()) for (std::list<uint64>::const_iterator itr = KaddrakGUIDList.begin(); itr != KaddrakGUIDList.end(); ++itr) { if (Creature* pKaddrak = Unit::GetCreature(*me, *itr)) { if (pKaddrak->isAlive()) pKaddrak->CastSpell(target, DUNGEON_MODE(SPELL_GLARE_OF_THE_TRIBUNAL, H_SPELL_GLARE_OF_THE_TRIBUNAL), true); } } uiKaddrakEncounterTimer = 1500; } else uiKaddrakEncounterTimer -= diff; } if (bMarnakActivated) { if (uiMarnakEncounterTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) { if (Creature* summon = me->SummonCreature(CREATURE_DARK_MATTER_TARGET, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN, 1000)) { summon->SetDisplayId(11686); summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); summon->CastSpell(target, DUNGEON_MODE(SPELL_DARK_MATTER, H_SPELL_DARK_MATTER), true); } } uiMarnakEncounterTimer = urand(30000, 31000); } else uiMarnakEncounterTimer -= diff; } if (bAbedneumActivated) { if (uiAbedneumEncounterTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) { if (Creature* summon = me->SummonCreature(CREATURE_SEARING_GAZE_TARGET, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN, 1000)) { summon->SetDisplayId(11686); summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); summon->CastSpell(target, DUNGEON_MODE(SPELL_SEARING_GAZE, H_SPELL_SEARING_GAZE), true); } } uiAbedneumEncounterTimer = urand(30000, 31000); } else uiAbedneumEncounterTimer -= diff; } }
int WMIRequest(IWbemServices* pSvc, IWbemLocator* pLoc, std::list<BSTR> requests, map<wstring, map<wstring, wstring>> &resultData, BSTR query) { if (pSvc == NULL || pLoc == NULL) { return status_query_failed; } HRESULT hres; IEnumWbemClassObject* pEnumerator = NULL; hres = pSvc->ExecQuery(L"WQL", query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hres)) { return status_query_failed; } // Get the data from the WQL sentence IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; resultData.clear(); int index = 0; while (pEnumerator) { HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn || FAILED(hr)) break; VARIANT vtProp; //get name hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0); // Uint32 wstring mapKey = L""; if (!FAILED(hr)) { if ((vtProp.vt == VT_NULL) || (vtProp.vt == VT_EMPTY)) { wchar_t szBuf[20]; wsprintf(szBuf, L"%Id", index++); mapKey.append(szBuf); } else mapKey = FromVariant(vtProp); } VariantClear(&vtProp); resultData.insert( std::pair<wstring, map<wstring, wstring>>(mapKey, map<wstring, wstring>())); for (std::list<BSTR>::const_iterator iterator = requests.begin(), end = requests.end(); iterator != end; ++iterator) { BSTR req = *iterator; hr = pclsObj->Get(req, 0, &vtProp, 0, 0); // Uint32 wstring value = L""; if (!FAILED(hr)) { if ((vtProp.vt == VT_NULL) || (vtProp.vt == VT_EMPTY)) { value = L"NULL"; } else { value = FromVariant(vtProp); } resultData[mapKey].insert( std::pair<wstring, wstring>(req, value)); } VariantClear(&vtProp); } pclsObj->Release(); pclsObj = NULL; } pEnumerator->Release(); if (pclsObj != NULL) pclsObj->Release(); return status_ok; }
void DespawnDwarf() { if (lDwarfGUIDList.empty()) return; for (std::list<uint64>::const_iterator itr = lDwarfGUIDList.begin(); itr != lDwarfGUIDList.end(); ++itr) { Creature* temp = Unit::GetCreature(*me, instance ? (*itr) : 0); if (temp && temp->isAlive()) temp->DespawnOrUnsummon(); } lDwarfGUIDList.clear(); }
/// Constructs a XMLTree with the specified list of attributes XMLTree::XMLTree(const std::string& name, const std::list<XMLAttrib>& attributes) { this->name = name; this->attribs = std::set<XMLAttrib>(attributes.begin(), attributes.end()); this->processed = false; }
void GraficoDeTorta::hallarNormalizacion(const std::list< Hecho >& datos) { normalizacion = 0; std::list< Hecho >::const_iterator itDatos = datos.begin(); for ( ; itDatos != datos.end(); ++itDatos) normalizacion += itDatos->getValor(); }
void ConstraintWriter::writeConstraintForces(const std::list<ConstraintPair*>& constraints){ #ifndef IS_MPI std::list<ConstraintPair*>::const_iterator i; for ( i = constraints.begin(); i != constraints.end(); ++i) { if ((*i)->getPrintForce()) { output_ << info_->getSnapshotManager()->getCurrentSnapshot()->getTime() << "\t" << (*i)->getConsElem1()->getGlobalIndex() <<"\t" << (*i)->getConsElem2()->getGlobalIndex() <<"\t" << (*i)->getConstraintForce() <<std::endl; } } #else const int masterNode = 0; int nproc; int myNode; MPI_Comm_size( MPI_COMM_WORLD, &nproc); MPI_Comm_rank( MPI_COMM_WORLD, &myNode); std::vector<int> nConstraints(nproc, 0); nConstraints[myNode] = constraints.size(); //do MPI_ALLREDUCE to exchange the total number of constraints: MPI_Allreduce(MPI_IN_PLACE, &nConstraints[0], nproc, MPI_INT, MPI_SUM, MPI_COMM_WORLD); MPI_Status ierr; int atom1, atom2, doPrint; RealType force; if (myNode == masterNode) { std::vector<ConstraintData> constraintData; ConstraintData tmpData; for(int i = 0 ; i < nproc; ++i) { if (i == masterNode) { std::list<ConstraintPair*>::const_iterator j; for ( j = constraints.begin(); j != constraints.end(); ++j) { tmpData.atom1 = (*j)->getConsElem1()->getGlobalIndex(); tmpData.atom2 = (*j)->getConsElem2()->getGlobalIndex(); tmpData.constraintForce= (*j)->getConstraintForce(); tmpData.printForce = (*j)->getPrintForce(); constraintData.push_back(tmpData); } } else { for(int k = 0; k < nConstraints[i]; ++k) { MPI_Recv(&atom1, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &ierr); MPI_Recv(&atom2, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &ierr); MPI_Recv(&force, 1, MPI_REALTYPE, i, 0, MPI_COMM_WORLD, &ierr); MPI_Recv(&doPrint, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &ierr); tmpData.atom1 = atom1; tmpData.atom2 = atom2; tmpData.constraintForce = force; tmpData.printForce = (doPrint == 0) ? false : true; constraintData.push_back(tmpData); } } } std::vector<ConstraintData>::iterator l; for (l = constraintData.begin(); l != constraintData.end(); ++l) { if (l->printForce) { output_ << info_->getSnapshotManager()->getCurrentSnapshot()->getTime() << "\t" << l->atom1 <<"\t" << l->atom2 <<"\t" << l->constraintForce << std::endl; } } } else { std::list<ConstraintPair*>::const_iterator j; for (j = constraints.begin(); j != constraints.end(); ++j) { int atom1 = (*j)->getConsElem1()->getGlobalIndex(); int atom2 = (*j)->getConsElem2()->getGlobalIndex(); RealType constraintForce= (*j)->getConstraintForce(); int printForce = (int) (*j)->getPrintForce(); MPI_Send(&atom1, 1, MPI_INT, masterNode, 0, MPI_COMM_WORLD); MPI_Send(&atom2, 1, MPI_INT, masterNode, 0, MPI_COMM_WORLD); MPI_Send(&constraintForce, 1, MPI_REALTYPE, masterNode, 0, MPI_COMM_WORLD); MPI_Send(&printForce, 1, MPI_INT, masterNode, 0, MPI_COMM_WORLD); } } #endif }
virtual void draw(cairo_t* cr, renderer* rnd) { for (std::list<view*>::iterator it = children.begin(); it != children.end(); it++) rnd->child(*it)->draw(cr); }
VectorFont::Glyph::Glyph( const std::list<std::string> &cxf_glyph_definition, const double word_space_percentage, const double character_space_percentage ) { m_word_space_percentage = word_space_percentage; m_character_space_percentage = character_space_percentage; for (std::list<std::string>::const_iterator l_itLine = cxf_glyph_definition.begin(); l_itLine != cxf_glyph_definition.end(); l_itLine++) { wxString line( Ctt(l_itLine->c_str()) ); wxString delimiters( _T(" \t\r\n,") ); std::vector<wxString> tokens = Tokens( line, delimiters ); if (tokens.size() == 0) { std::ostringstream l_ossError; l_ossError << "Expected tokens in glyph definition"; throw(std::runtime_error(l_ossError.str().c_str())); } // Replace dot (.) for comma (,) if the locale settings require it. for (std::vector<wxString>::iterator token = tokens.begin(); token != tokens.end(); token++) { *token = PrepareStringForConversion( *token ); } const wxChar * c_str = tokens[0].c_str(); switch (c_str[0]) { case 'L': if (tokens.size() != 5) { std::ostringstream l_ossError; l_ossError << "Expected 5 tokens when defining a line. We got " << tokens.size() << " tokens from '" << l_itLine->c_str() << "\n"; throw(std::runtime_error(l_ossError.str().c_str())); } else { GlyphLine *line = new GlyphLine( PointToMM(strtod( Ttc(tokens[1].c_str()), NULL )), PointToMM(strtod( Ttc(tokens[2].c_str()), NULL )), PointToMM(strtod( Ttc(tokens[3].c_str()), NULL )), PointToMM(strtod( Ttc(tokens[4].c_str()), NULL )) ); m_graphics_list.push_back( line ); m_bounding_box.Insert( line->BoundingBox() ); } break; case 'A': if (tokens.size() != 6) { std::ostringstream l_ossError; l_ossError << "Expected 6 tokens when defining an arc"; throw(std::runtime_error(l_ossError.str().c_str())); } else { if ((tokens[0].size() == 2) && (c_str[1] == 'R')) { // Reverse the starting and ending points. GlyphArc *arc = new GlyphArc( PointToMM(strtod( Ttc(tokens[1].c_str()), NULL )), PointToMM(strtod( Ttc(tokens[2].c_str()), NULL )), PointToMM(strtod( Ttc(tokens[3].c_str()), NULL )), strtod( Ttc(tokens[5].c_str()), NULL) , strtod( Ttc(tokens[4].c_str()), NULL )); m_graphics_list.push_back( arc ); m_bounding_box.Insert( arc->BoundingBox() ); } // End if - then else { GlyphArc *arc = new GlyphArc( PointToMM(strtod( Ttc(tokens[1].c_str()), NULL )), PointToMM(strtod( Ttc(tokens[2].c_str()), NULL )), PointToMM(strtod( Ttc(tokens[3].c_str()), NULL )), strtod( Ttc(tokens[4].c_str()), NULL ), strtod( Ttc(tokens[5].c_str()), NULL ) ); m_graphics_list.push_back( arc ); m_bounding_box.Insert( arc->BoundingBox() ); } } break; default: std::ostringstream l_ossError; l_ossError << "Unexpected graphics element type '" << c_str[0] << "'"; throw(std::runtime_error(l_ossError.str().c_str())); } // End switch } // End for } // End constructor
auto end() { return m_children.end(); }
bool CCurve::CheckForArc(const CVertex& prev_vt, std::list<const CVertex*>& might_be_an_arc, CArc &arc_returned) { // this examines the vertices in might_be_an_arc // if they do fit an arc, set arc to be the arc that they fit and return true // returns true, if arc added if(might_be_an_arc.size() < 2)return false; // find middle point int num = might_be_an_arc.size(); int i = 0; const CVertex* mid_vt = NULL; int mid_i = (num-1)/2; for(std::list<const CVertex*>::iterator It = might_be_an_arc.begin(); It != might_be_an_arc.end(); It++, i++) { if(i == mid_i) { mid_vt = *It; break; } } // create a circle to test Point p0(prev_vt.m_p); Point p1(mid_vt->m_p); Point p2(might_be_an_arc.back()->m_p); Circle c(p0, p1, p2); const CVertex* current_vt = &prev_vt; double accuracy = CArea::m_accuracy * 1.4 / CArea::m_units; for(std::list<const CVertex*>::iterator It = might_be_an_arc.begin(); It != might_be_an_arc.end(); It++) { const CVertex* vt = *It; if(!c.LineIsOn(current_vt->m_p, vt->m_p, accuracy)) return false; current_vt = vt; } CArc arc; arc.m_c = c.m_c; arc.m_s = prev_vt.m_p; arc.m_e = might_be_an_arc.back()->m_p; arc.SetDirWithPoint(might_be_an_arc.front()->m_p); arc.m_user_data = might_be_an_arc.back()->m_user_data; double angs = atan2(arc.m_s.y - arc.m_c.y, arc.m_s.x - arc.m_c.x); double ange = atan2(arc.m_e.y - arc.m_c.y, arc.m_e.x - arc.m_c.x); if(arc.m_dir) { // make sure ange > angs if(ange < angs)ange += 6.2831853071795864; } else { // make sure angs > ange if(angs < ange)angs += 6.2831853071795864; } if(arc.IncludedAngle() >= 3.15)return false; // We don't want full arcs, so limit to about 180 degrees for(std::list<const CVertex*>::iterator It = might_be_an_arc.begin(); It != might_be_an_arc.end(); It++) { const CVertex* vt = *It; double angp = atan2(vt->m_p.y - arc.m_c.y, vt->m_p.x - arc.m_c.x); if(arc.m_dir) { // make sure angp > angs if(angp < angs)angp += 6.2831853071795864; if(angp > ange)return false; } else { // make sure angp > ange if(angp < ange)angp += 6.2831853071795864; if(angp > angs)return false; } } arc_returned = arc; return true; }
void GLXConfigurator::SetRenderer(RenderSystem *r) { mRenderer = r; // Destroy each widget of GUI of previously selected renderer for(std::list<Widget>::iterator i=mRenderOptionWidgets.begin(); i!=mRenderOptionWidgets.end(); i++) XtDestroyWidget(*i); mRenderOptionWidgets.clear(); mConfigCallbackData.back(); // Create option GUI int cury = ystart + 1*rowh + 10; ConfigOptionMap options = mRenderer->getConfigOptions(); // Process each option and create an optionmenu widget for it for (ConfigOptionMap::iterator it = options.begin(); it != options.end(); it++) { // if the config option does not have any possible value, then skip it. // if we create a popup with zero entries, it will crash when you click // on it. if (it->second.possibleValues.empty()) continue; Widget lb1 = XtVaCreateManagedWidget("topLabel", labelWidgetClass, box, XtNlabel, it->second.name.c_str(), XtNborderWidth, 0, XtNwidth, col1w, // Fixed width XtNheight, 18, XtNleft, XawChainLeft, XtNtop, XawChainTop, XtNright, XawChainLeft, XtNbottom, XawChainTop, XtNhorizDistance, col1x, XtNvertDistance, cury, XtNjustify, XtJustifyLeft, NULL); mRenderOptionWidgets.push_back(lb1); Widget mb1 = XtVaCreateManagedWidget("Menu", menuButtonWidgetClass, box, XtNlabel, it->second.currentValue.c_str(), XtNresize, false, XtNresizable, false, XtNwidth, col2w, // Fixed width XtNheight, 18, XtNleft, XawChainLeft, XtNtop, XawChainTop, XtNright, XawChainLeft, XtNbottom, XawChainTop, XtNhorizDistance, col2x, XtNvertDistance, cury, NULL); mRenderOptionWidgets.push_back(mb1); Widget menu = XtVaCreatePopupShell("menu", simpleMenuWidgetClass, mb1, 0, NULL); // Process each choice StringVector::iterator opt_it; for (opt_it = it->second.possibleValues.begin(); opt_it != it->second.possibleValues.end(); opt_it++) { // Create callback data mConfigCallbackData.push_back(ConfigCallbackData(this, it->second.name, *opt_it, mb1)); Widget entry = XtVaCreateManagedWidget("menuentry", smeBSBObjectClass, menu, XtNlabel, (*opt_it).c_str(), 0, NULL); XtAddCallback(entry, XtNcallback, (XtCallbackProc)&GLXConfigurator::configOptionHandler, &mConfigCallbackData.back()); } cury += rowh; } }
void _scene_base::add_object ( std::list<std::shared_ptr<_object_base>>& object, const unsigned int shader_name ) { _shaders_and_objects_in_scene_iter = _shaders_and_objects_in_scene.find( shader_name );//->second.push_back( object ); if( _shaders_and_objects_in_scene_iter != _shaders_and_objects_in_scene.end() ) { if( !object.empty() ) { for( std::list<std::shared_ptr<_object_base>>::iterator obj = object.begin(); obj != object.end(); ++obj ){ _shaders_and_objects_in_scene_iter->second.push_back( (*obj) ); if( (*obj)->get_rigidbody() ) { _physics_world->addRigidBody( (*obj)->get_rigidbody() ); /* (*obj) = nullptr; */ /* _physics_world->addCollisionObject( object->get_rigidbody() ); */ } else { std::cerr<<"add_object object do not initilize the collision"<<std::endl; } } object.clear(); } else { std::cerr<<"add_object object's point is empty"<<std::endl; } } else { std::cerr<<"add_object can't find shader_name"<<std::endl; } std::cout<<"number objects: "<<_shaders_and_objects_in_scene_iter->second.size()<<"\n"; }
void FilterTargets(std::list<Unit*>& unitList) { if (!GetCaster()->ToPlayer()->GetGroup()) { unitList.clear(); unitList.push_back(GetCaster()); } else { unitList.remove(GetTargetUnit()); std::list<Unit*> tempTargets; for (std::list<Unit*>::const_iterator itr = unitList.begin(); itr != unitList.end(); ++itr) if ((*itr)->GetTypeId() == TYPEID_PLAYER && GetCaster()->IsInRaidWith(*itr)) tempTargets.push_back(*itr); if (tempTargets.empty()) { unitList.clear(); FinishCast(SPELL_FAILED_DONT_REPORT); return; } Unit* target = SelectRandomContainerElement(tempTargets); unitList.clear(); unitList.push_back(target); } }