// // D_DoDefDehackedPatch // // [Russell] - Change the meaning, this will load multiple patch files if // specified void D_DoDefDehackedPatch (const std::vector<std::string> patch_files = std::vector<std::string>()) { DArgs files; BOOL noDef = false; BOOL chexLoaded = false; QWORD i; if (!patch_files.empty()) { std::string f; std::string ext; // we want the extension of the file for (i = 0; i < patch_files.size(); i++) { if (M_ExtractFileExtension(patch_files[i], ext)) { f = BaseFileSearch (patch_files[i], ext); if (f.length()) { DoDehPatch (f.c_str(), false); noDef = true; } } } } else // [Russell] - Only load if patch_files is empty { // try .deh files on command line files = Args.GatherFiles ("-deh", ".deh", false); if (files.NumArgs()) { for (i = 0; i < files.NumArgs(); i++) { std::string f = BaseFileSearch (files.GetArg (i), ".DEH"); if (f.length()) { DoDehPatch (f.c_str(), false); if (!strncmp(files.GetArg (i),"chex.deh",8)) chexLoaded = true; } } noDef = true; } if (gamemode == retail_chex && !multiplayer && !chexLoaded) Printf(PRINT_HIGH,"Warning: chex.deh not loaded, experience may differ from the original!\n"); // remove the old arguments files.FlushArgs(); // try .bex files on command line files = Args.GatherFiles ("-bex", ".bex", false); if (files.NumArgs()) { for (i = 0; i < files.NumArgs(); i++) { std::string f = BaseFileSearch (files.GetArg (i), ".BEX"); if (f.length()) DoDehPatch (f.c_str(), false); } noDef = true; } } // try default patches if (!noDef) DoDehPatch (NULL, true); // See if there's a patch in a PWAD }
Mat visionUtils::skinDetect(Mat captureframe, Mat3b *skinDetectHSV, Mat *skinMask, std::vector<int> adaptiveHSV, int minPixelSize, int imgBlurPixels, int imgMorphPixels, int singleRegionChoice, bool displayFaces) { if (adaptiveHSV.size()!=6 || adaptiveHSV.empty()) { adaptiveHSV.clear(); adaptiveHSV.push_back(5); adaptiveHSV.push_back(38); adaptiveHSV.push_back(51); adaptiveHSV.push_back(17); adaptiveHSV.push_back(250); adaptiveHSV.push_back(242); } //int step = 0; Mat3b frameTemp; Mat3b frame; // Forcing resize to 640x480 -> all thresholds / pixel filters configured for this size..... // Note returned to original size at end... Size s = captureframe.size(); cv::resize(captureframe,captureframe,Size(640,480)); if (useGPU) { GpuMat imgGPU, imgGPUHSV; imgGPU.upload(captureframe); cv::cvtColor(imgGPU, imgGPUHSV, CV_BGR2HSV); GaussianBlur(imgGPUHSV, imgGPUHSV, Size(imgBlurPixels,imgBlurPixels), 1, 1); imgGPUHSV.download(frameTemp); } else { cv::cvtColor(captureframe, frameTemp, CV_BGR2HSV); GaussianBlur(frameTemp, frameTemp, Size(imgBlurPixels,imgBlurPixels), 1, 1); } // Potential FASTER VERSION using inRange Mat frameThreshold = Mat::zeros(frameTemp.rows,frameTemp.cols, CV_8UC1); Mat hsvMin = (Mat_<int>(1,3) << adaptiveHSV[0], adaptiveHSV[1],adaptiveHSV[2] ); Mat hsvMax = (Mat_<int>(1,3) << adaptiveHSV[3], adaptiveHSV[4],adaptiveHSV[5] ); inRange(frameTemp,hsvMin ,hsvMax, frameThreshold); frameTemp.copyTo(frame,frameThreshold); /* BGR CONVERSION AND THRESHOLD */ Mat1b frame_gray; // send HSV to skinDetectHSV for return *skinDetectHSV=frame.clone(); cv::cvtColor(frame, frame_gray, CV_BGR2GRAY); // Adaptive thresholding technique // 1. Threshold data to find main areas of skin adaptiveThreshold(frame_gray,frame_gray,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY_INV,9,1); if (useGPU) { GpuMat imgGPU; imgGPU.upload(frame_gray); // 2. Fill in thresholded areas #if CV_MAJOR_VERSION == 2 gpu::morphologyEx(imgGPU, imgGPU, CV_MOP_CLOSE, Mat1b(imgMorphPixels,imgMorphPixels,1), Point(-1, -1), 2); gpu::GaussianBlur(imgGPU, imgGPU, Size(imgBlurPixels,imgBlurPixels), 1, 1); #elif CV_MAJOR_VERSION == 3 //TODO: Check if that's correct Mat element = getStructuringElement(MORPH_RECT, Size(imgMorphPixels, imgMorphPixels), Point(-1, -1)); Ptr<cuda::Filter> closeFilter = cuda::createMorphologyFilter(MORPH_CLOSE, imgGPU.type(), element, Point(-1, -1), 2); closeFilter->apply(imgGPU, imgGPU); cv::Ptr<cv::cuda::Filter> gaussianFilter = cv::cuda::createGaussianFilter(imgGPU.type(), imgGPU.type(), Size(imgMorphPixels, imgMorphPixels), 1, 1); gaussianFilter->apply(imgGPU, imgGPU); #endif imgGPU.download(frame_gray); } else { // 2. Fill in thresholded areas morphologyEx(frame_gray, frame_gray, CV_MOP_CLOSE, Mat1b(imgMorphPixels,imgMorphPixels,1), Point(-1, -1), 2); GaussianBlur(frame_gray, frame_gray, Size(imgBlurPixels,imgBlurPixels), 1, 1); // Select single largest region from image, if singleRegionChoice is selected (1) } if (singleRegionChoice) { *skinMask = cannySegmentation(frame_gray, -1, displayFaces); } else // Detect each separate block and remove blobs smaller than a few pixels { *skinMask = cannySegmentation(frame_gray, minPixelSize, displayFaces); } // Just return skin Mat frame_skin; captureframe.copyTo(frame_skin,*skinMask); // Copy captureframe data to frame_skin, using mask from frame_ttt // Resize image to original before return cv::resize(frame_skin,frame_skin,s); if (displayFaces) { imshow("Skin HSV (B)",frame); imshow("Adaptive_threshold (D1)",frame_gray); imshow("Skin segmented",frame_skin); } return frame_skin; waitKey(1); }
void sdl_event_handler::handle_event(const SDL_Event& event) { /** No dispatchers drop the event. */ if(dispatchers_.empty()) { return; } switch(event.type) { case SDL_MOUSEMOTION: mouse(SDL_MOUSE_MOTION, {event.motion.x, event.motion.y}); break; case SDL_MOUSEBUTTONDOWN: mouse_button_down({event.button.x, event.button.y}, event.button.button); break; case SDL_MOUSEBUTTONUP: mouse_button_up({event.button.x, event.button.y}, event.button.button); break; case SDL_MOUSEWHEEL: mouse_wheel(get_mouse_position(), event.wheel.x, event.wheel.y); break; case SHOW_HELPTIP_EVENT: mouse(SHOW_HELPTIP, get_mouse_position()); break; case HOVER_REMOVE_POPUP_EVENT: // remove_popup(); break; case DRAW_EVENT: draw(false); break; case DRAW_ALL_EVENT: draw(true); break; case TIMER_EVENT: execute_timer(reinterpret_cast<size_t>(event.user.data1)); break; case CLOSE_WINDOW_EVENT: { /** @todo Convert this to a proper new style event. */ DBG_GUI_E << "Firing " << CLOSE_WINDOW << ".\n"; window* window = window::window_instance(event.user.code); if(window) { window->set_retval(window::AUTO_CLOSE); } } break; case SDL_JOYBUTTONDOWN: button_down(event); break; case SDL_JOYBUTTONUP: break; case SDL_JOYAXISMOTION: break; case SDL_JOYHATMOTION: hat_motion(event); break; case SDL_KEYDOWN: key_down(event); break; case SDL_WINDOWEVENT: switch(event.window.event) { case SDL_WINDOWEVENT_EXPOSED: draw(true); break; case SDL_WINDOWEVENT_RESIZED: video_resize({event.window.data1, event.window.data2}); break; case SDL_WINDOWEVENT_ENTER: case SDL_WINDOWEVENT_FOCUS_GAINED: activate(); break; } break; case SDL_TEXTINPUT: text_input(event.text.text); break; #if(defined(_X11) && !defined(__APPLE__)) || defined(_WIN32) case SDL_SYSWMEVENT: /* DO NOTHING */ break; #endif // Silently ignored events. case SDL_KEYUP: case DOUBLE_CLICK_EVENT: break; default: #ifdef GUI2_SHOW_UNHANDLED_EVENT_WARNINGS WRN_GUI_E << "Unhandled event " << static_cast<Uint32>(event.type) << ".\n"; #endif break; } }
std::vector<PossiblePlate> detectCharsInPlates(std::vector<PossiblePlate> &vectorOfPossiblePlates) { int intPlateCounter = 0; // this is only for showing steps cv::Mat imgContours; std::vector<std::vector<cv::Point> > contours; cv::RNG rng; if (vectorOfPossiblePlates.empty()) { // if vector of possible plates is empty return(vectorOfPossiblePlates); // return } // at this point we can be sure vector of possible plates has at least one plate for (auto &possiblePlate : vectorOfPossiblePlates) { // for each possible plate, this is a big for loop that takes up most of the function preprocess(possiblePlate.imgPlate, possiblePlate.imgGrayscale, possiblePlate.imgThresh); // preprocess to get grayscale and threshold images #ifdef SHOW_STEPS cv::imshow("5a", possiblePlate.imgPlate); cv::imshow("5b", possiblePlate.imgGrayscale); cv::imshow("5c", possiblePlate.imgThresh); #endif // SHOW_STEPS // upscale size by 60% for better viewing and character recognition cv::resize(possiblePlate.imgThresh, possiblePlate.imgThresh, cv::Size(), 1.6, 1.6); // threshold again to eliminate any gray areas cv::threshold(possiblePlate.imgThresh, possiblePlate.imgThresh, 0.0, 255.0, CV_THRESH_BINARY | CV_THRESH_OTSU); #ifdef SHOW_STEPS cv::imshow("5d", possiblePlate.imgThresh); #endif // SHOW_STEPS // find all possible chars in the plate, // this function first finds all contours, then only includes contours that could be chars (without comparison to other chars yet) std::vector<PossibleChar> vectorOfPossibleCharsInPlate = findPossibleCharsInPlate(possiblePlate.imgGrayscale, possiblePlate.imgThresh); #ifdef SHOW_STEPS imgContours = cv::Mat(possiblePlate.imgThresh.size(), CV_8UC3, SCALAR_BLACK); contours.clear(); for (auto &possibleChar : vectorOfPossibleCharsInPlate) { contours.push_back(possibleChar.contour); } cv::drawContours(imgContours, contours, -1, SCALAR_WHITE); cv::imshow("6", imgContours); #endif // SHOW_STEPS // given a vector of all possible chars, find groups of matching chars within the plate std::vector<std::vector<PossibleChar> > vectorOfVectorsOfMatchingCharsInPlate = findVectorOfVectorsOfMatchingChars(vectorOfPossibleCharsInPlate); #ifdef SHOW_STEPS imgContours = cv::Mat(possiblePlate.imgThresh.size(), CV_8UC3, SCALAR_BLACK); contours.clear(); for (auto &vectorOfMatchingChars : vectorOfVectorsOfMatchingCharsInPlate) { int intRandomBlue = rng.uniform(0, 256); int intRandomGreen = rng.uniform(0, 256); int intRandomRed = rng.uniform(0, 256); for (auto &matchingChar : vectorOfMatchingChars) { contours.push_back(matchingChar.contour); } cv::drawContours(imgContours, contours, -1, cv::Scalar((double)intRandomBlue, (double)intRandomGreen, (double)intRandomRed)); } cv::imshow("7", imgContours); #endif // SHOW_STEPS if (vectorOfVectorsOfMatchingCharsInPlate.size() == 0) { // if no groups of matching chars were found in the plate #ifdef SHOW_STEPS std::cout << "chars found in plate number " << intPlateCounter << " = (none), click on any image and press a key to continue . . ." << std::endl; intPlateCounter++; cv::destroyWindow("8"); cv::destroyWindow("9"); cv::destroyWindow("10"); cv::waitKey(0); #endif // SHOW_STEPS possiblePlate.strChars = ""; // set plate string member variable to empty string continue; // go back to top of for loop } for (auto &vectorOfMatchingChars : vectorOfVectorsOfMatchingCharsInPlate) { // for each vector of matching chars in the current plate std::sort(vectorOfMatchingChars.begin(), vectorOfMatchingChars.end(), PossibleChar::sortCharsLeftToRight); // sort the chars left to right vectorOfMatchingChars = removeInnerOverlappingChars(vectorOfMatchingChars); // and eliminate any overlapping chars } #ifdef SHOW_STEPS imgContours = cv::Mat(possiblePlate.imgThresh.size(), CV_8UC3, SCALAR_BLACK); for (auto &vectorOfMatchingChars : vectorOfVectorsOfMatchingCharsInPlate) { int intRandomBlue = rng.uniform(0, 256); int intRandomGreen = rng.uniform(0, 256); int intRandomRed = rng.uniform(0, 256); contours.clear(); for (auto &matchingChar : vectorOfMatchingChars) { contours.push_back(matchingChar.contour); } cv::drawContours(imgContours, contours, -1, cv::Scalar((double)intRandomBlue, (double)intRandomGreen, (double)intRandomRed)); } cv::imshow("8", imgContours); #endif // SHOW_STEPS // within each possible plate, suppose the longest vector of potential matching chars is the actual vector of chars unsigned int intLenOfLongestVectorOfChars = 0; unsigned int intIndexOfLongestVectorOfChars = 0; // loop through all the vectors of matching chars, get the index of the one with the most chars for (unsigned int i = 0; i < vectorOfVectorsOfMatchingCharsInPlate.size(); i++) { if (vectorOfVectorsOfMatchingCharsInPlate[i].size() > intLenOfLongestVectorOfChars) { intLenOfLongestVectorOfChars = vectorOfVectorsOfMatchingCharsInPlate[i].size(); intIndexOfLongestVectorOfChars = i; } } // suppose that the longest vector of matching chars within the plate is the actual vector of chars std::vector<PossibleChar> longestVectorOfMatchingCharsInPlate = vectorOfVectorsOfMatchingCharsInPlate[intIndexOfLongestVectorOfChars]; #ifdef SHOW_STEPS imgContours = cv::Mat(possiblePlate.imgThresh.size(), CV_8UC3, SCALAR_BLACK); contours.clear(); for (auto &matchingChar : longestVectorOfMatchingCharsInPlate) { contours.push_back(matchingChar.contour); } cv::drawContours(imgContours, contours, -1, SCALAR_WHITE); cv::imshow("9", imgContours); #endif // SHOW_STEPS // perform char recognition on the longest vector of matching chars in the plate possiblePlate.strChars = recognizeCharsInPlate(possiblePlate.imgThresh, longestVectorOfMatchingCharsInPlate); #ifdef SHOW_STEPS std::cout << "chars found in plate number " << intPlateCounter << " = " << possiblePlate.strChars << ", click on any image and press a key to continue . . ." << std::endl; intPlateCounter++; cv::waitKey(0); #endif // SHOW_STEPS } // end for each possible plate big for loop that takes up most of the function #ifdef SHOW_STEPS std::cout << std::endl << "char detection complete, click on any image and press a key to continue . . ." << std::endl; cv::waitKey(0); #endif // SHOW_STEPS return(vectorOfPossiblePlates); }
/** * @brief IntegratePeaksCWSD::simplePeakIntegration * Purpose: * Integrate a single crystal peak with the simplest algorithm, i.e., * by adding all the signal with normalization to monitor counts * Requirements: * Valid MDEventWorkspace * Valid PeaksWorkspace * Guarantees: * A valid value is given */ void IntegratePeaksCWSD::simplePeakIntegration( const std::vector<detid_t> &vecMaskedDetID, const std::map<int, signal_t> &run_monitor_map) { // Check requirements if (!m_inputWS) throw std::runtime_error("MDEventWorkspace is not defined."); // Go through to get value API::IMDIterator *mditer = m_inputWS->createIterator(); size_t nextindex = 1; bool scancell = true; // size_t currindex = 0; // Assuming that MDEvents are grouped by run number, there is no need to // loop up the map for peak center and monitor counts each time int current_run_number = -1; signal_t current_monitor_counts = 0; Kernel::V3D current_peak_center = m_peakCenter; // signal_t total_signal = 0; double min_distance = 10000000; double max_distance = -1; while (scancell) { // Go through all the MDEvents in one cell. size_t numeventincell = mditer->getNumEvents(); for (size_t iev = 0; iev < numeventincell; ++iev) { // Get signal to add and skip if signal is zero signal_t signal = mditer->getInnerSignal(iev); if (signal <= THRESHOLD_SIGNAL) continue; uint16_t run_number = mditer->getInnerRunIndex(iev); int run_number_i = static_cast<int>(run_number); /* debug: record raw signals if (run_number_i % 1000 == testrunnumber) { total_signal += signal; ++ num_det; } // ... debug */ // Check whether this detector is masked if (!vecMaskedDetID.empty()) { detid_t detid = mditer->getInnerDetectorID(iev); std::vector<detid_t>::const_iterator it; it = find(vecMaskedDetID.begin(), vecMaskedDetID.end(), detid); if (it != vecMaskedDetID.end()) { // The detector ID is found among masked detector IDs // Skip this event and move to next /* debug: record masked detectors if (run_number_i % 1000 == testrunnumber) { num_masked_det += 1; g_log.warning() << "Masked detector ID = " << detid << ", Signal = " << signal << "\n"; } // ... debug */ continue; } } /* debug: record unmasked detectors if (run_number_i % 1000 == testrunnumber) num_unmasked_det += 1; // ... debug */ // Check whether to update monitor counts and peak center if (current_run_number != run_number_i) { // update run number current_run_number = run_number_i; // update monitor counts if (m_normalizeByMonitor) { std::map<int, signal_t>::const_iterator m_finder = run_monitor_map.find(current_run_number); if (m_finder != run_monitor_map.end()) current_monitor_counts = m_finder->second; else { std::stringstream errss; errss << "Unable to find run number " << current_run_number << " in monitor counts map"; throw std::runtime_error(errss.str()); } } else { current_monitor_counts = 1.; } // update peak center if (!m_useSinglePeakCenterFmUser) current_peak_center = m_runPeakCenterMap[current_run_number]; } // calculate distance float tempx = mditer->getInnerPosition(iev, 0); float tempy = mditer->getInnerPosition(iev, 1); float tempz = mditer->getInnerPosition(iev, 2); Kernel::V3D pixel_pos(tempx, tempy, tempz); double distance = current_peak_center.distance(pixel_pos); /* debug: record unmasked signal if (run_number_i % 1000 == testrunnumber) { total_unmasked_signal += signal; } // ... debug */ if (distance < m_peakRadius) { // FIXME - Is it very costly to use map each time??? // total_signal += signal/current_monitor_counts; m_runPeakCountsMap[run_number] += signal / current_monitor_counts; } else { g_log.debug() << "Out of radius " << distance << " > " << m_peakRadius << ": Center = " << current_peak_center.toString() << ", Pixel = " << pixel_pos.toString() << "\n"; } if (distance < min_distance) min_distance = distance; if (distance > max_distance) max_distance = distance; } // Advance to next cell if (mditer->next()) { // advance to next cell mditer->jumpTo(nextindex); ++nextindex; } else { // break the loop scancell = false; } } // END-WHILE (scan-cell) // Summarize g_log.notice() << "Distance range is " << min_distance << ", " << max_distance << "\n"; /* g_log.warning() << "Debug output: run 13: Number masked detectors = " << num_masked_det << ", Total signal = " << total_signal << "\n"; g_log.warning() << " Number of unmasked detectors = " << num_unmasked_det << ", Total unmasked signal = " << total_unmasked_signal << "\n"; g_log.warning() << " Number of total detectors = " << num_det << "\n"; */ }
registry load(const std::vector<char>& data) { registry result; // Hack for empty input (TODO) if (data.empty()) { return result; } // Check size CHECK_ASSERTION(data.size() >= sizeof(header_t)); CHECK_ASSERTION((std::uintptr_t)data.data() % 8 == 0); // Get header const header_t& header = reinterpret_cast<const header_t&>(data[0]); // Check magic and version CHECK_ASSERTION(header.magic == *(u32*)"\0PSF"); CHECK_ASSERTION(header.version == 0x101); CHECK_ASSERTION(sizeof(header_t) + header.entries_num * sizeof(def_table_t) <= header.off_key_table); CHECK_ASSERTION(header.off_key_table <= header.off_data_table); CHECK_ASSERTION(header.off_data_table <= data.size()); // Get indices (alignment should be fine) const def_table_t* indices = reinterpret_cast<const def_table_t*>(data.data() + sizeof(header_t)); // Load entries for (u32 i = 0; i < header.entries_num; ++i) { CHECK_ASSERTION(indices[i].key_off < header.off_data_table - header.off_key_table); // Get key name range const auto name_ptr = data.begin() + header.off_key_table + indices[i].key_off; const auto name_end = std::find(name_ptr , data.begin() + header.off_data_table, '\0'); // Get name (must be unique) std::string key(name_ptr, name_end); CHECK_ASSERTION(result.count(key) == 0); CHECK_ASSERTION(indices[i].param_len <= indices[i].param_max); CHECK_ASSERTION(indices[i].data_off < data.size() - header.off_data_table); CHECK_ASSERTION(indices[i].param_max < data.size() - indices[i].data_off); // Get data pointer const auto value_ptr = data.begin() + header.off_data_table + indices[i].data_off; if (indices[i].param_fmt == format::integer && indices[i].param_max == sizeof(u32) && indices[i].param_len == sizeof(u32)) { // Integer data result.emplace(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple(reinterpret_cast<const le_t<u32>&>(*value_ptr))); } else if (indices[i].param_fmt == format::string || indices[i].param_fmt == format::array) { // String/array data std::string value; if (indices[i].param_fmt == format::string) { // Find null terminator value.assign(value_ptr, std::find(value_ptr, value_ptr + indices[i].param_len, '\0')); } else { value.assign(value_ptr, value_ptr + indices[i].param_len); } result.emplace(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple(indices[i].param_fmt, indices[i].param_max, std::move(value))); } else { // Possibly unsupported format, entry ignored log.error("Unknown entry format (key='%s', fmt=0x%x, len=0x%x, max=0x%x)", key, indices[i].param_fmt, indices[i].param_len, indices[i].param_max); } } return result; }
SelectBoxAction IMGUI::doSelectbox(int id, const Vector2& pos1, const Vector2& pos2, const std::vector<std::string>& entries, unsigned int& selected, unsigned int flags) { int FontSize = (flags & TF_SMALL_FONT ? (FONT_WIDTH_SMALL+LINE_SPACER_SMALL) : (FONT_WIDTH_NORMAL+LINE_SPACER_NORMAL)); SelectBoxAction changed = SBA_NONE; QueueObject obj; obj.id = id; obj.pos1 = pos1; obj.pos2 = pos2; obj.type = SELECTBOX; obj.flags = flags; const int itemsPerPage = int(pos2.y - pos1.y - 10) / FontSize; int first = (int)(selected / itemsPerPage)*itemsPerPage; //the first visible element in the list if (!mInactive) { // M.W. : Activate cursorless object-highlighting once the up or down key is pressed. if (mActiveButton == -1) { switch (mLastKeyAction) { case DOWN: mActiveButton = 0; mLastKeyAction = NONE; break; case UP: mActiveButton = mLastWidget; mLastKeyAction = NONE; break; default: break; } } // Highlight first menu object for arrow key navigation. if (mActiveButton == 0 && !mButtonReset) mActiveButton = id; // React to keyboard input. if (id == mActiveButton) { obj.type = ACTIVESELECTBOX; switch (mLastKeyAction) { case DOWN: mActiveButton = 0; mLastKeyAction = NONE; break; case UP: mActiveButton = mLastWidget; mLastKeyAction = NONE; break; case LEFT: if (selected > 0) { selected--; changed = SBA_SELECT; } mLastKeyAction = NONE; break; case RIGHT: if (selected + 1 < entries.size()) { selected++; changed = SBA_SELECT; } mLastKeyAction = NONE; break; default: break; } } // React to mouse input. Vector2 mousepos = InputManager::getSingleton()->position(); if (mousepos.x > pos1.x && mousepos.y > pos1.y && mousepos.x < pos2.x && mousepos.y < pos2.y) { obj.type = ACTIVESELECTBOX; if (InputManager::getSingleton()->click()) mActiveButton = id; } //entries mouseclick: if (mousepos.x > pos1.x && mousepos.y > pos1.y+5 && mousepos.x < pos2.x-35 && mousepos.y < pos1.y+5+FontSize*itemsPerPage) { if (InputManager::getSingleton()->click()) { int tmp = (int)((mousepos.y - pos1.y - 5) / FontSize) + first; /// \todo well, it's not really a doulbe click... /// we need to do this in inputmanager if( selected == tmp && InputManager::getSingleton()->doubleClick() ) changed = SBA_DBL_CLICK; if (tmp >= 0 && static_cast<unsigned int>(tmp) < entries.size()) selected = tmp; mActiveButton = id; } if ((InputManager::getSingleton()->mouseWheelUp()) && (selected > 0)) { selected--; changed = SBA_SELECT; } if ((InputManager::getSingleton()->mouseWheelDown()) && (selected + 1 < entries.size())) { selected++; changed = SBA_SELECT; } } //arrows mouseclick: if (mousepos.x > pos2.x-30 && mousepos.x < pos2.x-30+24 && InputManager::getSingleton()->click()) { if (mousepos.y > pos1.y+3 && mousepos.y < pos1.y+3+24 && selected > 0) { selected--; changed = SBA_SELECT; } if (mousepos.y > pos2.y-27 && mousepos.y < pos2.y-27+24 && selected + 1 < entries.size()) { selected++; changed = SBA_SELECT; } } } doImage(GEN_ID, Vector2(pos2.x-15, pos1.y+15), "gfx/pfeil_oben.bmp"); doImage(GEN_ID, Vector2(pos2.x-15, pos2.y-15), "gfx/pfeil_unten.bmp"); first = (selected / itemsPerPage)*itemsPerPage; //recalc first if ( !entries.empty() ) { unsigned int last = first + itemsPerPage; if (last > entries.size()) last = entries.size(); obj.entries = std::vector<std::string>(entries.begin()+first, entries.begin()+last); } else obj.entries = std::vector<std::string>(); obj.selected = selected-first; mLastWidget = id; mQueue->push(obj); return changed; }
void Alert::processString(char* buf, std::vector<Widget*>& labels, std::vector<Widget*>& buttons) { Box* box1, *box2, *box3, *box4, *box5; Grid* grid; bool title = true; bool label = false; bool separator = false; bool button = false; int align = 0; char *beg; int c, chr; // Process buffer c = 0; beg = buf; for (; ; c++) { if ((!buf[c]) || ((buf[c] == buf[c+1]) && ((buf[c] == '<') || (buf[c] == '=') || (buf[c] == '>') || (buf[c] == '-') || (buf[c] == '|')))) { if (title || label || separator || button) { chr = buf[c]; buf[c] = 0; if (title) { setText(beg); } else if (label) { Label* label = new Label(beg); label->setAlign(align); labels.push_back(label); } else if (separator) { labels.push_back(new Separator("", HORIZONTAL)); } else if (button) { char buttonId[256]; Button* button_widget = new Button(beg); button_widget->setMinSize(gfx::Size(60*guiscale(), 0)); buttons.push_back(button_widget); sprintf(buttonId, "button-%lu", buttons.size()); button_widget->setId(buttonId); button_widget->Click.connect(Bind<void>(&Window::closeWindow, this, button_widget)); } buf[c] = chr; } /* done */ if (!buf[c]) break; /* next widget */ else { title = label = separator = button = false; beg = buf+c+2; align = 0; switch (buf[c]) { case '<': label=true; align=LEFT; break; case '=': label=true; align=CENTER; break; case '>': label=true; align=RIGHT; break; case '-': separator=true; break; case '|': button=true; break; } c++; } } } box1 = new Box(VERTICAL); box2 = new Box(VERTICAL); grid = new Grid(1, false); box3 = new Box(HORIZONTAL | HOMOGENEOUS); // To identify by the user box2->setId("labels"); box3->setId("buttons"); // Pseudo separators (only to fill blank space) box4 = new Box(0); box5 = new Box(0); m_progressPlaceholder = new Box(0); box4->setExpansive(true); box5->setExpansive(true); box4->noBorderNoChildSpacing(); box5->noBorderNoChildSpacing(); m_progressPlaceholder->noBorderNoChildSpacing(); // Setup parent <-> children relationship addChild(box1); box1->addChild(box4); // Filler box1->addChild(box2); // Labels box1->addChild(m_progressPlaceholder); box1->addChild(box5); // Filler box1->addChild(grid); // Buttons grid->addChildInCell(box3, 1, 1, CENTER | BOTTOM); for (std::vector<Widget*>::iterator it = labels.begin(); it != labels.end(); ++it) box2->addChild(*it); for (std::vector<Widget*>::iterator it = buttons.begin(); it != buttons.end(); ++it) box3->addChild(*it); // Default button is the last one if (!buttons.empty()) buttons[buttons.size()-1]->setFocusMagnet(true); }
static void buildKdTreeNode_ALT( KDTreeNode* Node, const std::vector<SCollisionFace> &Faces, s32 ForkLevel, const EKDTreeBuildingConcepts Concept) { if (!Node || Faces.empty()) return; /* Check if tree node is a leaf */ if (ForkLevel <= 0) { buildKdTreeNodeLeaf_ALT(Node, Faces); return; } const dim::aabbox3df BoundBox(Node->getBox()); /* Compute average vertex position */ dim::vector3df AvgVertPos; switch (Concept) { case KDTREECONCEPT_CENTER: { AvgVertPos = BoundBox.getCenter(); } break; case KDTREECONCEPT_AVERAGE: { #if 0 foreach (const SCollisionFace &Face, Faces) AvgVertPos += Face.Triangle.getCenter(); AvgVertPos /= dim::vector3df(static_cast<f32>(Faces.size())); #else /* Compute median position */ std::vector<f32> MedianPos[3]; for (s32 i = 0; i < 3; ++i) { MedianPos[i].resize(Faces.size()); u32 j = 0; foreach (const SCollisionFace &Face, Faces) (MedianPos[i])[j++] = Face.Triangle.getCenter()[i]; std::sort(MedianPos[i].begin(), MedianPos[i].end()); AvgVertPos[i] = (MedianPos[i])[MedianPos[i].size()/2]; } #endif } break; } /* Fill potentially sub triangle lists */ s32 PotFaceCountNear[3], PotFaceCountFar[3]; foreach (const SCollisionFace &Face, Faces) { for (s32 i = 0; i < 3; ++i) { if (Face.Triangle.PointA[i] < AvgVertPos[i] || Face.Triangle.PointB[i] < AvgVertPos[i] || Face.Triangle.PointC[i] < AvgVertPos[i]) { ++PotFaceCountNear[i]; } if (Face.Triangle.PointA[i] >= AvgVertPos[i] || Face.Triangle.PointB[i] >= AvgVertPos[i] || Face.Triangle.PointC[i] >= AvgVertPos[i]) { ++PotFaceCountFar[i]; } } } /* Search for optimal tree partitioning */ EKDTreeAxles Axis = KDTREE_XAXIS; switch (Concept) { case KDTREECONCEPT_CENTER: { const dim::vector3df BoxSize(BoundBox.getSize()); if (BoxSize.X >= BoxSize.Y && BoxSize.X >= BoxSize.Z) Axis = KDTREE_XAXIS; else if (BoxSize.Y >= BoxSize.X && BoxSize.Y >= BoxSize.Z) Axis = KDTREE_YAXIS; else Axis = KDTREE_ZAXIS; } break; case KDTREECONCEPT_AVERAGE: { const u32 ListSize[3] = { PotFaceCountNear[0] + PotFaceCountFar[0], PotFaceCountNear[1] + PotFaceCountFar[1], PotFaceCountNear[2] + PotFaceCountFar[2] }; if (ListSize[0] == ListSize[1] && ListSize[0] == ListSize[2]) { const dim::vector3df BoxSize(BoundBox.getSize()); if (BoxSize.X >= BoxSize.Y && BoxSize.X >= BoxSize.Z) Axis = KDTREE_XAXIS; else if (BoxSize.Y >= BoxSize.X && BoxSize.Y >= BoxSize.Z) Axis = KDTREE_YAXIS; else Axis = KDTREE_ZAXIS; } else if (ListSize[0] <= ListSize[1] && ListSize[0] <= ListSize[2]) Axis = KDTREE_XAXIS; else if (ListSize[1] <= ListSize[0] && ListSize[1] <= ListSize[2]) Axis = KDTREE_YAXIS; else Axis = KDTREE_ZAXIS; } break; } /* Create children tree nodes */ Node->setAxis(Axis); Node->setDistance(AvgVertPos[Axis]); /* Construct clipping plane */ dim::plane3df ClipPlane; switch (Axis) { case KDTREE_XAXIS: ClipPlane.Normal = dim::vector3df(1, 0, 0); break; case KDTREE_YAXIS: ClipPlane.Normal = dim::vector3df(0, 1, 0); break; case KDTREE_ZAXIS: ClipPlane.Normal = dim::vector3df(0, 0, 1); break; } ClipPlane.Distance = Node->getDistance(); /* Clip plolygons */ std::vector<SCollisionFace> FacesNear, FacesFar; foreach (const SCollisionFace &Face, Faces) { /* Clip current face's triangle */ dim::polygon3df Poly, PolyNear, PolyFar; Poly.push(Face.Triangle.PointA); Poly.push(Face.Triangle.PointB); Poly.push(Face.Triangle.PointC); math::CollisionLibrary::clipPolygon(Poly, ClipPlane, PolyFar, PolyNear); //!TODO! -> front or back side of cliped polygons is not working correctly!!! /* Fill new polygon into sub-lists */ for (u32 i = 2; i < PolyNear.getCount(); ++i) { FacesNear.push_back(SCollisionFace( Face.Mesh, Face.Surface, Face.Index, dim::triangle3df(PolyNear[0], PolyNear[i - 1], PolyNear[i]) )); } for (u32 i = 2; i < PolyFar.getCount(); ++i) { FacesFar.push_back(SCollisionFace( Face.Mesh, Face.Surface, Face.Index, dim::triangle3df(PolyFar[0], PolyFar[i - 1], PolyFar[i]) )); } }
ssh_add_options &get_current_options() { if(on_demand_keys.empty()) return global_options; else return on_demand_keys.back().options; }
/** * @brief publish vehicle */ static void create_vehicle_markers( int num_rotors, float arm_len, float body_width, float body_height ) { if ( num_rotors <= 0 ) num_rotors = 2; /** Create markers only once for efficiency * TODO use visualization_msgs::MarkerArray? */ if ( !vehicle_markers.empty() ) return; vehicle_markers.reserve( 2 * num_rotors + 1 ); /** Hexacopter marker code adapted from libsfly_viz * thanks to Markus Achtelik. */ // rotor marker template visualization_msgs::Marker rotor; rotor.header.stamp = ros::Time(); rotor.header.frame_id = child_frame_id; rotor.ns = "vehicle_rotor"; rotor.action = visualization_msgs::Marker::ADD; rotor.type = visualization_msgs::Marker::CYLINDER; rotor.scale.x = 0.2 * marker_scale; rotor.scale.y = 0.2 * marker_scale; rotor.scale.z = 0.01 * marker_scale; rotor.color.r = 0.4; rotor.color.g = 0.4; rotor.color.b = 0.4; rotor.color.a = 0.8; rotor.pose.position.z = 0; // arm marker template visualization_msgs::Marker arm; arm.header.stamp = ros::Time(); arm.header.frame_id = child_frame_id; arm.ns = "vehicle_arm"; arm.action = visualization_msgs::Marker::ADD; arm.type = visualization_msgs::Marker::CUBE; arm.scale.x = arm_len * marker_scale; arm.scale.y = 0.02 * marker_scale; arm.scale.z = 0.01 * marker_scale; arm.color.r = 0.0; arm.color.g = 0.0; arm.color.b = 1.0; arm.color.a = 1.0; arm.pose.position.z = -0.015 * marker_scale; float angle_increment = 2 * M_PI / num_rotors; for ( float angle = angle_increment / 2; angle <= (2 * M_PI); angle += angle_increment ) { rotor.pose.position.x = arm_len * cos(angle) * marker_scale; rotor.pose.position.y = arm_len * sin(angle) * marker_scale; rotor.id++; arm.pose.position.x = rotor.pose.position.x / 2; arm.pose.position.y = rotor.pose.position.y / 2; arm.pose.orientation = tf::createQuaternionMsgFromYaw(angle); arm.id++; vehicle_markers.push_back(rotor); vehicle_markers.push_back(arm); } // body marker template visualization_msgs::Marker body; body.header.stamp = ros::Time(); body.header.frame_id = child_frame_id; body.ns = "vehicle_body"; body.action = visualization_msgs::Marker::ADD; body.type = visualization_msgs::Marker::CUBE; body.scale.x = body_width * marker_scale; body.scale.y = body_width * marker_scale; body.scale.z = body_height * marker_scale; body.color.r = 0.0; body.color.g = 1.0; body.color.b = 0.0; body.color.a = 0.8; vehicle_markers.push_back(body); }
bool TQualityMetric::evaluate_with_gradient( PatchData& pd, size_t handle, double& value, std::vector<size_t>& indices, std::vector<Vector3D>& grad, MsqError& err ) { const Sample s = ElemSampleQM::sample( handle ); const size_t e = ElemSampleQM:: elem( handle ); MsqMeshEntity& elem = pd.element_by_index( e ); EntityTopology type = elem.get_element_type(); unsigned edim = TopologyInfo::dimension( type ); size_t num_idx = 0; const NodeSet bits = pd.non_slave_node_set( e ); bool rval; if (edim == 3) { // 3x3 or 3x2 targets ? const MappingFunction3D* mf = pd.get_mapping_function_3D( type ); if (!mf) { MSQ_SETERR(err)( "No mapping function for element type", MsqError::UNSUPPORTED_ELEMENT ); return false; } MsqMatrix<3,3> A, W, dmdT; mf->jacobian( pd, e, bits, s, mIndices, mDerivs3D, num_idx, A, err ); MSQ_ERRZERO(err); targetCalc->get_3D_target( pd, e, s, W, err ); MSQ_ERRZERO(err); const MsqMatrix<3,3> Winv = inverse(W); const MsqMatrix<3,3> T = A*Winv; rval = targetMetric->evaluate_with_grad( T, value, dmdT, err ); MSQ_ERRZERO(err); gradient<3>( num_idx, mDerivs3D, dmdT * transpose(Winv), grad ); #ifdef PRINT_INFO print_info<3>( e, s, A, W, A * inverse(W) ); #endif } else if (edim == 2) { MsqMatrix<2,2> W, A, dmdT; MsqMatrix<3,2> S_a_transpose_Theta; rval = evaluate_surface_common( pd, s, e, bits, mIndices, num_idx, mDerivs2D, W, A, S_a_transpose_Theta, err ); if (MSQ_CHKERR(err) || !rval) return false; const MsqMatrix<2,2> Winv = inverse(W); const MsqMatrix<2,2> T = A*Winv; rval = targetMetric->evaluate_with_grad( T, value, dmdT, err ); MSQ_ERRZERO(err); gradient<2>( num_idx, mDerivs2D, S_a_transpose_Theta*dmdT*transpose(Winv), grad ); #ifdef PRINT_INFO print_info<2>( e, s, J, Wp, A * inverse(W) ); #endif } else { assert(false); return false; } // pass back index list indices.resize( num_idx ); std::copy( mIndices, mIndices+num_idx, indices.begin() ); // apply target weight to value weight( pd, s, e, num_idx, value, grad.empty() ? 0 : arrptr(grad), 0, 0, err ); MSQ_ERRZERO(err); return rval; }
AsyncRPCOperation_mergetoaddress::AsyncRPCOperation_mergetoaddress( boost::optional<TransactionBuilder> builder, CMutableTransaction contextualTx, std::vector<MergeToAddressInputUTXO> utxoInputs, std::vector<MergeToAddressInputSproutNote> sproutNoteInputs, std::vector<MergeToAddressInputSaplingNote> saplingNoteInputs, MergeToAddressRecipient recipient, CAmount fee, UniValue contextInfo) : tx_(contextualTx), utxoInputs_(utxoInputs), sproutNoteInputs_(sproutNoteInputs), saplingNoteInputs_(saplingNoteInputs), recipient_(recipient), fee_(fee), contextinfo_(contextInfo) { if (fee < 0 || fee > MAX_MONEY) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee is out of range"); } if (utxoInputs.empty() && sproutNoteInputs.empty() && saplingNoteInputs.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "No inputs"); } if (std::get<0>(recipient).size() == 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Recipient parameter missing"); } if (sproutNoteInputs.size() > 0 && saplingNoteInputs.size() > 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot send from both Sprout and Sapling addresses using z_mergetoaddress"); } if (sproutNoteInputs.size() > 0 && builder) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Sprout notes are not supported by the TransactionBuilder"); } isUsingBuilder_ = false; if (builder) { isUsingBuilder_ = true; builder_ = builder.get(); } toTaddr_ = DecodeDestination(std::get<0>(recipient)); isToTaddr_ = IsValidDestination(toTaddr_); isToZaddr_ = false; if (!isToTaddr_) { auto address = DecodePaymentAddress(std::get<0>(recipient)); if (IsValidPaymentAddress(address)) { isToZaddr_ = true; toPaymentAddress_ = address; } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid recipient address"); } } // Log the context info i.e. the call parameters to z_mergetoaddress if (LogAcceptCategory("zrpcunsafe")) { LogPrint("zrpcunsafe", "%s: z_mergetoaddress initialized (params=%s)\n", getId(), contextInfo.write()); } else { LogPrint("zrpc", "%s: z_mergetoaddress initialized\n", getId()); } // Lock UTXOs lock_utxos(); lock_notes(); // Enable payment disclosure if requested paymentDisclosureMode = fExperimentalMode && GetBoolArg("-paymentdisclosure", false); }
std::vector<size_t> D_DoomWadReboot( const std::vector<std::string> &wadnames, const std::vector<std::string> &patch_files, std::vector<std::string> needhashes ) { std::vector<size_t> fails; size_t i; // already loaded these? if (lastWadRebootSuccess && !wadhashes.empty() && needhashes == std::vector<std::string>(wadhashes.begin()+1, wadhashes.end())) { // fast track if files have not been changed // denis - todo - actually check the file timestamps Printf (PRINT_HIGH, "Currently loaded WADs match server checksum\n\n"); return std::vector<size_t>(); } // assume failure lastWadRebootSuccess = false; if (modifiedgame && (gameinfo.flags & GI_SHAREWARE)) I_Error ("\nYou cannot switch WAD with the shareware version. Register!"); if(gamestate == GS_LEVEL) G_ExitLevel(0, 0); AM_Stop(); S_Stop(); DThinker::DestroyAllThinkers(); // Close all open WAD files W_Close(); // [ML] 9/11/10: Reset custom wad level information from MAPINFO et al. // I have never used memset, I hope I am not invoking satan by doing this :( if (wadlevelinfos) { for (i = 0; i < numwadlevelinfos; i++) if (wadlevelinfos[i].snapshot) { delete wadlevelinfos[i].snapshot; wadlevelinfos[i].snapshot = NULL; } memset(wadlevelinfos,0,sizeof(wadlevelinfos)); numwadlevelinfos = 0; } if (wadclusterinfos) { memset(wadclusterinfos,0,sizeof(wadclusterinfos)); numwadclusterinfos = 0; } // Restart the memory manager Z_Init(); gamestate_t oldgamestate = gamestate; gamestate = GS_STARTUP; // prevent console from trying to use nonexistant font wadfiles.clear(); modifiedgame = false; std::string custwad; if(wadnames.empty() == false) custwad = wadnames[0]; D_AddDefWads(custwad); for(i = 0; i < wadnames.size(); i++) { std::string tmp = wadnames[i]; // strip absolute paths, as they present a security risk FixPathSeparator(tmp); size_t slash = tmp.find_last_of(PATHSEPCHAR); if(slash != std::string::npos) tmp = tmp.substr(slash + 1, tmp.length() - slash); // [Russell] - Generate a hash if it doesn't exist already if (needhashes[i].empty()) needhashes[i] = W_MD5(tmp); std::string file = BaseFileSearch(tmp, ".wad", needhashes[i]); if(file.length()) wadfiles.push_back(file); else { Printf (PRINT_HIGH, "could not find WAD: %s\n", tmp.c_str()); fails.push_back(i); } } if(wadnames.size() > 1) modifiedgame = true; wadhashes = W_InitMultipleFiles (wadfiles); UndoDehPatch(); // [RH] Initialize localizable strings. GStrings.ResetStrings (); GStrings.Compact (); D_DoDefDehackedPatch(patch_files); //gotconback = false; //C_InitConsole(DisplayWidth, DisplayHeight, true); HU_Init (); if(!(DefaultPalette = InitPalettes("PLAYPAL"))) I_Error("Could not reinitialize palette"); V_InitPalette(); G_SetLevelStrings (); G_ParseMapInfo (); G_ParseMusInfo (); S_ParseSndInfo(); M_Init(); R_Init(); P_InitEffects(); // [ML] Do this here so we don't have to put particle crap in server P_Init(); S_Init (snd_sfxvolume, snd_musicvolume); ST_Init(); // preserve state lastWadRebootSuccess = fails.empty(); gamestate = oldgamestate; // GS_STARTUP would prevent netcode connecting properly return fails; }
void ApplyNonMaximumSuppresion(std::vector< LkTracker* >& in_out_source, float in_nms_threshold) { if (in_out_source.empty()) return; unsigned int size = in_out_source.size(); std::vector<float> area(size); std::vector<float> scores(size); std::vector<int> x1(size); std::vector<int> y1(size); std::vector<int> x2(size); std::vector<int> y2(size); std::vector<unsigned int> indices(size); std::vector<bool> is_suppresed(size); for(unsigned int i = 0; i< in_out_source.size(); i++) { ObjectDetection tmp = in_out_source[i]->GetTrackedObject(); area[i] = tmp.rect.width * tmp.rect.height; if (area[i]>0) is_suppresed[i] = false; else { is_suppresed[i] = true; in_out_source[i]->NullifyLifespan(); } indices[i] = i; scores[i] = tmp.score; x1[i] = tmp.rect.x; y1[i] = tmp.rect.y; x2[i] = tmp.rect.width + tmp.rect.x; y2[i] = tmp.rect.height + tmp.rect.y; } Sort(area, indices);//returns indices ordered based on scores for(unsigned int i=0; i< size; i++) { for(unsigned int j= i+1; j< size; j++) { if(is_suppresed[indices[i]] || is_suppresed[indices[j]]) continue; int x1_max = std::max(x1[indices[i]], x1[indices[j]]); int x2_min = std::min(x2[indices[i]], x2[indices[j]]); int y1_max = std::max(y1[indices[i]], y1[indices[j]]); int y2_min = std::min(y2[indices[i]], y2[indices[j]]); int overlap_width = x2_min - x1_max + 1; int overlap_height = y2_min - y1_max + 1; if(overlap_width > 0 && overlap_height>0) { float overlap_part = (overlap_width*overlap_height)/area[indices[j]]; if(overlap_part > in_nms_threshold) { is_suppresed[indices[j]] = true; in_out_source[indices[j]]->NullifyLifespan(); if (in_out_source[indices[j]]->GetFrameCount() > in_out_source[indices[i]]->GetFrameCount()) { in_out_source[indices[i]]->object_id = in_out_source[indices[j]]->object_id; } } } } } return ; }
unsigned CriticalAntiDepBreaker:: BreakAntiDependencies(const std::vector<SUnit>& SUnits, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned InsertPosIndex, DbgValueVector &DbgValues) { // The code below assumes that there is at least one instruction, // so just duck out immediately if the block is empty. if (SUnits.empty()) return 0; // Keep a map of the MachineInstr*'s back to the SUnit representing them. // This is used for updating debug information. // // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap DenseMap<MachineInstr*,const SUnit*> MISUnitMap; // Find the node at the bottom of the critical path. const SUnit *Max = 0; for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { const SUnit *SU = &SUnits[i]; MISUnitMap[SU->getInstr()] = SU; if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency) Max = SU; } #ifndef NDEBUG { DEBUG(dbgs() << "Critical path has total latency " << (Max->getDepth() + Max->Latency) << "\n"); DEBUG(dbgs() << "Available regs:"); for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) { if (KillIndices[Reg] == ~0u) DEBUG(dbgs() << " " << TRI->getName(Reg)); } DEBUG(dbgs() << '\n'); } #endif // Track progress along the critical path through the SUnit graph as we walk // the instructions. const SUnit *CriticalPathSU = Max; MachineInstr *CriticalPathMI = CriticalPathSU->getInstr(); // Consider this pattern: // A = ... // ... = A // A = ... // ... = A // A = ... // ... = A // A = ... // ... = A // There are three anti-dependencies here, and without special care, // we'd break all of them using the same register: // A = ... // ... = A // B = ... // ... = B // B = ... // ... = B // B = ... // ... = B // because at each anti-dependence, B is the first register that // isn't A which is free. This re-introduces anti-dependencies // at all but one of the original anti-dependencies that we were // trying to break. To avoid this, keep track of the most recent // register that each register was replaced with, avoid // using it to repair an anti-dependence on the same register. // This lets us produce this: // A = ... // ... = A // B = ... // ... = B // C = ... // ... = C // B = ... // ... = B // This still has an anti-dependence on B, but at least it isn't on the // original critical path. // // TODO: If we tracked more than one register here, we could potentially // fix that remaining critical edge too. This is a little more involved, // because unlike the most recent register, less recent registers should // still be considered, though only if no other registers are available. std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0); // Attempt to break anti-dependence edges on the critical path. Walk the // instructions from the bottom up, tracking information about liveness // as we go to help determine which registers are available. unsigned Broken = 0; unsigned Count = InsertPosIndex - 1; for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) { MachineInstr *MI = --I; if (MI->isDebugValue()) continue; // Check if this instruction has a dependence on the critical path that // is an anti-dependence that we may be able to break. If it is, set // AntiDepReg to the non-zero register associated with the anti-dependence. // // We limit our attention to the critical path as a heuristic to avoid // breaking anti-dependence edges that aren't going to significantly // impact the overall schedule. There are a limited number of registers // and we want to save them for the important edges. // // TODO: Instructions with multiple defs could have multiple // anti-dependencies. The current code here only knows how to break one // edge per instruction. Note that we'd have to be able to break all of // the anti-dependencies in an instruction in order to be effective. unsigned AntiDepReg = 0; if (MI == CriticalPathMI) { if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) { const SUnit *NextSU = Edge->getSUnit(); // Only consider anti-dependence edges. if (Edge->getKind() == SDep::Anti) { AntiDepReg = Edge->getReg(); assert(AntiDepReg != 0 && "Anti-dependence on reg0?"); if (!RegClassInfo.isAllocatable(AntiDepReg)) // Don't break anti-dependencies on non-allocatable registers. AntiDepReg = 0; else if (KeepRegs.test(AntiDepReg)) // Don't break anti-dependencies if an use down below requires // this exact register. AntiDepReg = 0; else { // If the SUnit has other dependencies on the SUnit that it // anti-depends on, don't bother breaking the anti-dependency // since those edges would prevent such units from being // scheduled past each other regardless. // // Also, if there are dependencies on other SUnits with the // same register as the anti-dependency, don't attempt to // break it. for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(), PE = CriticalPathSU->Preds.end(); P != PE; ++P) if (P->getSUnit() == NextSU ? (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) : (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) { AntiDepReg = 0; break; } } } CriticalPathSU = NextSU; CriticalPathMI = CriticalPathSU->getInstr(); } else { // We've reached the end of the critical path. CriticalPathSU = 0; CriticalPathMI = 0; } } PrescanInstruction(MI); // If MI's defs have a special allocation requirement, don't allow // any def registers to be changed. Also assume all registers // defined in a call must not be changed (ABI). if (MI->isCall() || MI->hasExtraDefRegAllocReq() || TII->isPredicated(MI)) // If this instruction's defs have special allocation requirement, don't // break this anti-dependency. AntiDepReg = 0; else if (AntiDepReg) { // If this instruction has a use of AntiDepReg, breaking it // is invalid. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { MachineOperand &MO = MI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (Reg == 0) continue; if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) { AntiDepReg = 0; break; } } } // Determine AntiDepReg's register class, if it is live and is // consistently used within a single class. const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0; assert((AntiDepReg == 0 || RC != NULL) && "Register should be live if it's causing an anti-dependence!"); if (RC == reinterpret_cast<TargetRegisterClass *>(-1)) AntiDepReg = 0; // Look for a suitable register to use to break the anti-depenence. // // TODO: Instead of picking the first free register, consider which might // be the best. if (AntiDepReg != 0) { std::pair<std::multimap<unsigned, MachineOperand *>::iterator, std::multimap<unsigned, MachineOperand *>::iterator> Range = RegRefs.equal_range(AntiDepReg); if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second, AntiDepReg, LastNewReg[AntiDepReg], RC)) { DEBUG(dbgs() << "Breaking anti-dependence edge on " << TRI->getName(AntiDepReg) << " with " << RegRefs.count(AntiDepReg) << " references" << " using " << TRI->getName(NewReg) << "!\n"); // Update the references to the old register to refer to the new // register. for (std::multimap<unsigned, MachineOperand *>::iterator Q = Range.first, QE = Range.second; Q != QE; ++Q) { Q->second->setReg(NewReg); // If the SU for the instruction being updated has debug information // related to the anti-dependency register, make sure to update that // as well. const SUnit *SU = MISUnitMap[Q->second->getParent()]; if (!SU) continue; for (DbgValueVector::iterator DVI = DbgValues.begin(), DVE = DbgValues.end(); DVI != DVE; ++DVI) if (DVI->second == Q->second->getParent()) UpdateDbgValue(DVI->first, AntiDepReg, NewReg); } // We just went back in time and modified history; the // liveness information for the anti-dependence reg is now // inconsistent. Set the state as if it were dead. Classes[NewReg] = Classes[AntiDepReg]; DefIndices[NewReg] = DefIndices[AntiDepReg]; KillIndices[NewReg] = KillIndices[AntiDepReg]; assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) && "Kill and Def maps aren't consistent for NewReg!"); Classes[AntiDepReg] = 0; DefIndices[AntiDepReg] = KillIndices[AntiDepReg]; KillIndices[AntiDepReg] = ~0u; assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) && "Kill and Def maps aren't consistent for AntiDepReg!"); RegRefs.erase(AntiDepReg); LastNewReg[AntiDepReg] = NewReg; ++Broken; } } ScanInstruction(MI, Count); } return Broken; }
void GetworkThread::Run() { while(!testCancel()) { uint32_t midstate[8]={0,0,0,0,0,0,0,0}, data[32]; unsigned int i; getwork gw; uint32_t mtime = time(NULL); static uint32_t ltime=0; // last download Json::Value query, answ; PutworkThread* pwt=(PutworkThread*)hosts[host].pwt; if(ltime==mtime){ // limit requests to 1 per second threads_sleep(100); continue;} gwmut.lock(); if(!getworks.empty()){ int h; for(h=0;h<MAXHOSTS;h++){ // check all getwork threads if any has current job GetworkThread* gwt=(GetworkThread*)hosts[h].gwt; if(gwt==NULL || gwt->getworks.empty()){ continue;} if(gwt->getworks.back().mtime==mtime) { break;}} // this should be a GOTO, I have to start using this if(h<MAXHOSTS){ gwmut.unlock(); threads_sleep(100); continue;} /*if(getworks.back().mtime==mtime) { gwmut.unlock(); threads_sleep(100); continue;}*/ for(i=0;i<getworks.size();i++){ if(getworks[i].mtime>mtime-MAXWORKAGE){ break;}} if(i>0){ getworks.erase(getworks.begin(),getworks.begin()+i);}} gwmut.unlock(); if(pwt==NULL){ threads_sleep(100); continue;} if(pwt->putworks.size()>MAXPUTWORK){ gwmut.lock(); getworks.clear(); // removes all jobs due to slow queue gwmut.unlock(); printf("GETWORK: queue full for host[%d]: %s \n",host,hosts[host].url); threads_sleep(1000); continue;} query["jsonrpc"] = "2.0"; query["id"] = 1; query["method"] = "getwork"; answ = make_rpc_req(query, false, host,2); if (answ.type() != Json::objectValue){ threads_sleep(500); continue; } if (answ["data"].type() != Json::stringValue || !parse_ulong(data, answ["data"].asCString(), 32, 0, 1)){ threads_sleep(500); continue; } if (answ["midstate"].type() != Json::stringValue || !parse_ulong(midstate, answ["midstate"].asCString(), 8, 0, 1)) { const unsigned sha_initial_state[8]={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}; SHA256_Full(midstate, data, sha_initial_state); } gwmut.lock(); if(!getworks.empty()){ if (memcmp( ((btc_block_t*)data)->hashPrevBlock, ((btc_block_t*)getworks.front().data)->hashPrevBlock, 32)) { // removes all jobs in last block //try clearing all queues int h; for(h=0;h<MAXHOSTS;h++){ GetworkThread* gwt=(GetworkThread*)hosts[h].gwt; if(gwt==NULL){ continue;} gwt->getworks.clear();} // clear our again just in case :-) getworks.clear(); gwmut.unlock(); pwmut.lock(); if (answ["target"].type() != Json::stringValue || !parse_ulong(hosts[host].target, answ["target"].asCString(), 8, 0, 1)) { bits2bn(hosts[host].target, ((btc_block_t*)data)->nBits ); } pwmut.unlock(); gwmut.lock(); } } else{ if(hosts[host].target[7]==0xFFFFFFFF){ gwmut.unlock(); pwmut.lock(); if (answ["target"].type() != Json::stringValue || !parse_ulong(hosts[host].target, answ["target"].asCString(), 8, 0, 1)) { bits2bn(hosts[host].target, ((btc_block_t*)data)->nBits ); } pwmut.unlock(); gwmut.lock(); } } gw.mtime=mtime; memcpy(gw.data,data,sizeof(data)); memcpy(gw.midstate,midstate,sizeof(midstate)); getworks.push_back(gw); gwmut.unlock(); ltime=mtime; //log(); } }
//============================================================================= // stop // Collision detection between Mega Man and solid surfaces //============================================================================= void Megaman::stop(std::vector<VECTOR2> collisionVector, std::vector<RECT> tileCoordinates) { if (collisionVector.size() == 1) { stop(tileCoordinates[0].left, tileCoordinates[0].top, tileCoordinates[0].right - tileCoordinates[0].left, tileCoordinates[0].bottom - tileCoordinates[0].top); } else { while (collisionVector.empty() == false) { VECTOR2 tempCV = collisionVector[0]; collisionVector.erase(collisionVector.begin()); RECT tempTC = tileCoordinates[0]; tileCoordinates.erase(tileCoordinates.begin()); bool blocksInLine = false; bool onTop = false; bool onBottom = false; bool onLeft = false; bool onRight = false; for (int i = 0; i < collisionVector.size(); i++) { if (!collisionVector.empty() && tempTC.top == tileCoordinates[i].top) { collisionVector.erase(collisionVector.begin() + i); tileCoordinates.erase(tileCoordinates.begin() + i); i--; blocksInLine = true; } } // If blocks lined up on the same y-coordinate (top y) if (blocksInLine) { //top/bottom collision if (tempCV.y > 0) { topCollision(tempTC.top); } else { bottomCollision(tempTC.top, tempTC.bottom - tempTC.top); } } else { for (int i = 0; i < collisionVector.size(); i++) { if (!collisionVector.empty() && tempTC.left == tileCoordinates[i].left) { collisionVector.erase(collisionVector.begin() + i); tileCoordinates.erase(tileCoordinates.begin() + i); i--; blocksInLine = true; } } // If blocks lined up on the same x-coordinate (left x) if (blocksInLine) { //left/right collision if (tempCV.x > 0) { leftCollision(tempTC.left); } else { rightCollision(tempTC.left, tempTC.right - tempTC.left); } } else { stop(tempTC.left, tempTC.top, tempTC.right - tempTC.left, tempTC.bottom - tempTC.top); } } if (collisionVector.size() == 1 || collisionVector.empty()) { if (!collisionVector.empty()) { stop(tileCoordinates[0].left, tileCoordinates[0].top, tileCoordinates[0].right - tileCoordinates[0].left, tileCoordinates[0].bottom - tileCoordinates[0].top); collisionVector.erase(collisionVector.begin()); tileCoordinates.erase(tileCoordinates.begin()); } } } } }
IGL_INLINE void igl::on_boundary( const std::vector<std::vector<IntegerT> > & T, std::vector<bool> & I, std::vector<std::vector<bool> > & C) { using namespace std; if(T.empty()) { I.clear(); C.clear(); return; } switch(T[0].size()) { case 3: { // Get a list of all faces vector<vector<IntegerT> > F(T.size()*3,vector<IntegerT>(2)); // Gather faces, loop over tets for(int i = 0; i< (int)T.size();i++) { assert(T[i].size() == 3); // get face in correct order F[i*3+0][0] = T[i][1]; F[i*3+0][1] = T[i][2]; F[i*3+1][0] = T[i][2]; F[i*3+1][1] = T[i][0]; F[i*3+2][0] = T[i][0]; F[i*3+2][1] = T[i][1]; } // Counts vector<int> FC; face_occurrences(F,FC); C.resize(T.size(),vector<bool>(3)); I.resize(T.size(),false); for(int i = 0; i< (int)T.size();i++) { for(int j = 0;j<3;j++) { assert(FC[i*3+j] == 2 || FC[i*3+j] == 1); C[i][j] = FC[i*3+j]==1; // if any are on boundary set to true I[i] = I[i] || C[i][j]; } } return; } case 4: { // Get a list of all faces vector<vector<IntegerT> > F(T.size()*4,vector<IntegerT>(3)); // Gather faces, loop over tets for(int i = 0; i< (int)T.size();i++) { assert(T[i].size() == 4); // get face in correct order F[i*4+0][0] = T[i][1]; F[i*4+0][1] = T[i][3]; F[i*4+0][2] = T[i][2]; // get face in correct order F[i*4+1][0] = T[i][0]; F[i*4+1][1] = T[i][2]; F[i*4+1][2] = T[i][3]; // get face in correct order F[i*4+2][0] = T[i][0]; F[i*4+2][1] = T[i][3]; F[i*4+2][2] = T[i][1]; // get face in correct order F[i*4+3][0] = T[i][0]; F[i*4+3][1] = T[i][1]; F[i*4+3][2] = T[i][2]; } // Counts vector<int> FC; face_occurrences(F,FC); C.resize(T.size(),vector<bool>(4)); I.resize(T.size(),false); for(int i = 0; i< (int)T.size();i++) { for(int j = 0;j<4;j++) { assert(FC[i*4+j] == 2 || FC[i*4+j] == 1); C[i][j] = FC[i*4+j]==1; // if any are on boundary set to true I[i] = I[i] || C[i][j]; } } return; } } }
/* Computing absolute transformations for given list of objects The goal is to compute absolute transformation only once for each object involved. Objects contained in the subtree specified by `object` list are divided into two groups: - "joints", which are either part of `object` list or they have more than one child in the subtree - "non-joints", i.e. paths between joints Then for all joints their transformation (relative to parent joint) is computed and recursively concatenated together. Resulting transformations for joints which were originally in `object` list is then returned. */ template<class Transformation> std::vector<typename Transformation::DataType> Object<Transformation>::transformations(std::vector<Object<Transformation>*> objects, const typename Transformation::DataType& initialTransformation) const { CORRADE_ASSERT(objects.size() < 0xFFFFu, "SceneGraph::Object::transformations(): too large scene", std::vector<typename Transformation::DataType>{}); /* Remember object count for later */ std::size_t objectCount = objects.size(); /* Mark all original objects as joints and create initial list of joints from them */ for(std::size_t i = 0; i != objects.size(); ++i) { CORRADE_INTERNAL_ASSERT(objects[i]); /* Multiple occurences of one object in the array, don't overwrite it with different counter */ if(objects[i]->counter != 0xFFFFu) continue; objects[i]->counter = UnsignedShort(i); objects[i]->flags |= Flag::Joint; } std::vector<Object<Transformation>*> jointObjects(objects); /* Scene object */ const Scene<Transformation>* scene = this->scene(); /* Nearest common ancestor not yet implemented - assert this is done on scene */ CORRADE_ASSERT(scene == this, "SceneGraph::Object::transformationMatrices(): currently implemented only for Scene", std::vector<typename Transformation::DataType>{}); /* Mark all objects up the hierarchy as visited */ auto it = objects.begin(); while(!objects.empty()) { /* Already visited, remove and continue to next (duplicate occurence) */ if((*it)->flags & Flag::Visited) { it = objects.erase(it); continue; } /* Mark the object as visited */ (*it)->flags |= Flag::Visited; Object<Transformation>* parent = (*it)->parent(); /* If this is root object, remove from list */ if(!parent) { CORRADE_ASSERT(*it == scene, "SceneGraph::Object::transformations(): the objects are not part of the same tree", std::vector<typename Transformation::DataType>{}); it = objects.erase(it); /* Parent is an joint or already visited - remove current from list */ } else if(parent->flags & (Flag::Visited|Flag::Joint)) { it = objects.erase(it); /* If not already marked as joint, mark it as such and add it to list of joint objects */ if(!(parent->flags & Flag::Joint)) { CORRADE_ASSERT(jointObjects.size() < 0xFFFFu, "SceneGraph::Object::transformations(): too large scene", std::vector<typename Transformation::DataType>{}); CORRADE_INTERNAL_ASSERT(parent->counter == 0xFFFFu); parent->counter = UnsignedShort(jointObjects.size()); parent->flags |= Flag::Joint; jointObjects.push_back(parent); } /* Else go up the hierarchy */ } else *it = parent; /* Cycle if reached end */ if(it == objects.end()) it = objects.begin(); } /* Array of absolute transformations in joints */ std::vector<typename Transformation::DataType> jointTransformations(jointObjects.size()); /* Compute transformations for all joints */ for(std::size_t i = 0; i != jointTransformations.size(); ++i) computeJointTransformation(jointObjects, jointTransformations, i, initialTransformation); /* Copy transformation for second or next occurences from first occurence of duplicate object */ for(std::size_t i = 0; i != objectCount; ++i) { if(jointObjects[i]->counter != i) jointTransformations[i] = jointTransformations[jointObjects[i]->counter]; } /* All visited marks are now cleaned, clean joint marks and counters */ for(auto i: jointObjects) { /* All not-already cleaned objects (...duplicate occurences) should have joint mark */ CORRADE_INTERNAL_ASSERT(i->counter == 0xFFFFu || i->flags & Flag::Joint); i->flags &= ~Flag::Joint; i->counter = 0xFFFFu; } /* Shrink the array to contain only transformations of requested objects and return */ jointTransformations.resize(objectCount); return jointTransformations; }
void IMGUI::doChatbox(int id, const Vector2& pos1, const Vector2& pos2, const std::vector<std::string>& entries, unsigned int& selected, const std::vector<bool>& local, unsigned int flags) { assert( entries.size() == local.size() ); int FontSize = (flags & TF_SMALL_FONT ? (FONT_WIDTH_SMALL+LINE_SPACER_SMALL) : (FONT_WIDTH_NORMAL+LINE_SPACER_NORMAL)); QueueObject obj; obj.id = id; obj.pos1 = pos1; obj.pos2 = pos2; obj.type = CHAT; obj.flags = flags; const unsigned int itemsPerPage = int(pos2.y - pos1.y - 10) / FontSize; if (!mInactive) { // M.W. : Activate cursorless object-highlighting once the up or down key is pressed. if (mActiveButton == -1) { switch (mLastKeyAction) { case DOWN: mActiveButton = 0; mLastKeyAction = NONE; break; case UP: mActiveButton = mLastWidget; mLastKeyAction = NONE; break; default: break; } } // Highlight first menu object for arrow key navigation. if (mActiveButton == 0 && !mButtonReset) mActiveButton = id; // React to keyboard input. if (id == mActiveButton) { switch (mLastKeyAction) { case DOWN: mActiveButton = 0; mLastKeyAction = NONE; break; case UP: mActiveButton = mLastWidget; mLastKeyAction = NONE; break; case LEFT: if (selected > 0) { selected--; } mLastKeyAction = NONE; break; case RIGHT: if (selected + 1 < entries.size()) { selected++; } mLastKeyAction = NONE; break; default: break; } } // React to mouse input. Vector2 mousepos = InputManager::getSingleton()->position(); if (mousepos.x > pos1.x && mousepos.y > pos1.y && mousepos.x < pos2.x && mousepos.y < pos2.y) { if (InputManager::getSingleton()->click()) mActiveButton = id; } //entries mouseclick: if (mousepos.x > pos1.x && mousepos.y > pos1.y+5 && mousepos.x < pos2.x-35 && mousepos.y < pos1.y+5+FontSize*itemsPerPage) { if ((InputManager::getSingleton()->mouseWheelUp()) && (selected > 0)) { selected--; } if ((InputManager::getSingleton()->mouseWheelDown()) && (selected + 1 < entries.size())) { selected++; } } //arrows mouseclick: if (mousepos.x > pos2.x-30 && mousepos.x < pos2.x-30+24 && InputManager::getSingleton()->click()) { if (mousepos.y > pos1.y+3 && mousepos.y < pos1.y+3+24 && selected > 0) { selected--; } if (mousepos.y > pos2.y-27 && mousepos.y < pos2.y-27+24 && selected + 1 < entries.size()) { selected++; } } } doImage(GEN_ID, Vector2(pos2.x-15, pos1.y+15), "gfx/pfeil_oben.bmp"); doImage(GEN_ID, Vector2(pos2.x-15, pos2.y-15), "gfx/pfeil_unten.bmp"); unsigned int first = (selected / itemsPerPage) * itemsPerPage; //recalc first if ( !entries.empty() ) { unsigned int last = selected + 1; /// \todo maybe we should adapt selected so we even can't scroll up further! // we don't want negative chatlog, so we just scroll upward without coming to negative // elements. if (last >= itemsPerPage) first = last - itemsPerPage; else first = 0; // check that we don't create out of bounds problems if(last > entries.size()) { last = entries.size(); } obj.entries = std::vector<std::string>(entries.begin()+first, entries.begin()+last); // HACK: we use taxt to store information which text is from local player and which from // remote player. obj.text = ""; for(unsigned int i = first; i < last; ++i) { obj.text += local[i] ? 'L' : 'R'; } } else obj.entries = std::vector<std::string>(); obj.selected = selected-first; mLastWidget = id; mQueue->push(obj); }
static void computeCalleeSaveRegisterPairs( MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI, const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs) { if (CSI.empty()) return; AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); MachineFrameInfo *MFI = MF.getFrameInfo(); CallingConv::ID CC = MF.getFunction()->getCallingConv(); unsigned Count = CSI.size(); (void)CC; // MachO's compact unwind format relies on all registers being stored in // pairs. assert((!MF.getSubtarget<AArch64Subtarget>().isTargetMachO() || CC == CallingConv::PreserveMost || (Count & 1) == 0) && "Odd number of callee-saved regs to spill!"); unsigned Offset = AFI->getCalleeSavedStackSize(); for (unsigned i = 0; i < Count; ++i) { RegPairInfo RPI; RPI.Reg1 = CSI[i].getReg(); assert(AArch64::GPR64RegClass.contains(RPI.Reg1) || AArch64::FPR64RegClass.contains(RPI.Reg1)); RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1); // Add the next reg to the pair if it is in the same register class. if (i + 1 < Count) { unsigned NextReg = CSI[i + 1].getReg(); if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) || (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg))) RPI.Reg2 = NextReg; } // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI // list to come in sorted by frame index so that we can issue the store // pair instructions directly. Assert if we see anything otherwise. // // The order of the registers in the list is controlled by // getCalleeSavedRegs(), so they will always be in-order, as well. assert((!RPI.isPaired() || (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) && "Out of order callee saved regs!"); // MachO's compact unwind format relies on all registers being stored in // adjacent register pairs. assert((!MF.getSubtarget<AArch64Subtarget>().isTargetMachO() || CC == CallingConv::PreserveMost || (RPI.isPaired() && ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) || RPI.Reg1 + 1 == RPI.Reg2))) && "Callee-save registers not saved as adjacent register pair!"); RPI.FrameIdx = CSI[i].getFrameIdx(); if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) { // Round up size of non-pair to pair size if we need to pad the // callee-save area to ensure 16-byte alignment. Offset -= 16; assert(MFI->getObjectAlignment(RPI.FrameIdx) <= 16); MFI->setObjectSize(RPI.FrameIdx, 16); } else Offset -= RPI.isPaired() ? 16 : 8; assert(Offset % 8 == 0); RPI.Offset = Offset / 8; assert((RPI.Offset >= -64 && RPI.Offset <= 63) && "Offset out of bounds for LDP/STP immediate"); RegPairs.push_back(RPI); if (RPI.isPaired()) ++i; } // Align first offset to even 16-byte boundary to avoid additional SP // adjustment instructions. // Last pair offset is size of whole callee-save region for SP // pre-dec/post-inc. RegPairInfo &LastPair = RegPairs.back(); assert(AFI->getCalleeSavedStackSize() % 8 == 0); LastPair.Offset = AFI->getCalleeSavedStackSize() / 8; }
void MPIRemoteNode::buildHostLists( int offset, int requestedHostNum, std::vector<std::string>& tokensParams, std::vector<std::string>& tokensHost, std::vector<int>& hostInstances) { std::string mpiHosts=nanos::ext::MPIProcessor::getMpiHosts(); std::string mpiHostsFile=nanos::ext::MPIProcessor::getMpiHostsFile(); /** Build current host list */ std::list<std::string> tmpStorage; //In case a host has no parameters, we'll fill our structure with this one std::string params="ompssnoparam"; //Store single-line env value or hostfile into vector, separated by ';' or '\n' if ( !mpiHosts.empty() ){ std::stringstream hostInput(mpiHosts); std::string line; while( getline( hostInput, line , ';') ){ if (offset>0) offset--; else tmpStorage.push_back(line); } } else if ( !mpiHostsFile.empty() ){ std::ifstream infile(mpiHostsFile.c_str()); fatal_cond0(infile.bad(),"DEEP_Booster alloc error, NX_OFFL_HOSTFILE file not found"); std::string line; while( getline( infile, line , '\n') ){ if (offset>0) offset--; else tmpStorage.push_back(line); } infile.close(); } while( !tmpStorage.empty() && (int)tokensHost.size() < requestedHostNum ) { std::string line=tmpStorage.front(); tmpStorage.pop_front(); //If not commented add it to hosts if (!line.empty() && line.find("#")!=0){ size_t posSep=line.find(":"); size_t posEnd=line.find("<"); if (posEnd==line.npos) { posEnd=line.size(); } else { params=line.substr(posEnd+1,line.size()); trim(params); } if (posSep!=line.npos){ std::string realHost=line.substr(0,posSep); int number=atoi(line.substr(posSep+1,posEnd).c_str()); trim(realHost); //Hosts with 0 instances in the file are ignored if (!realHost.empty() && number!=0) { hostInstances.push_back(number); tokensHost.push_back(realHost); tokensParams.push_back(params); } } else { std::string realHost=line.substr(0,posEnd); trim(realHost); if (!realHost.empty()) { hostInstances.push_back(1); tokensHost.push_back(realHost); tokensParams.push_back(params); } } } } bool emptyHosts=tokensHost.empty(); //If there are no hosts, that means user "wants" to spawn in localhost while (emptyHosts && (int)tokensHost.size() < requestedHostNum ){ tokensHost.push_back("localhost"); tokensParams.push_back(params); hostInstances.push_back(1); } if (emptyHosts) { warning("No hostfile or list was providen using NX_OFFL_HOSTFILE or NX_OFFL_HOSTS environment variables." " Deep_booster_alloc allocation will be performed in localhost (not recommended except for debugging)"); } }
inline bool Entry::hasChildren() const { return !m_children.empty(); }
umi::redis::CommandHMGet::CommandHMGet(const std::string &key, const std::vector<std::string> &fields) : umi::redis::CommandRedis("HMGET", {key}) { if (!fields.empty()) { m_parameters.insert(m_parameters.end(), fields.begin(), fields.end()); } }
inline bool Entry::hasPitEntries() const { return !m_pitEntries.empty(); }
RHO_GLOBAL int open(const char *path, int oflag, ...) { std::string fpath; if (path) fpath = path; if (fpath.empty()) { RHO_LOG("open: path is empty"); errno = EFAULT; return -1; } RHO_LOG("open: %s...", path); fpath = make_full_path(fpath); RHO_LOG("open: %s: fpath: %s", path, fpath.c_str()); bool emulate = need_emulate(fpath); RHO_LOG("open: %s: emulate: %d", path, (int)emulate); if (emulate && has_pending_exception()) { RHO_LOG("open: %s: has_pending_exception, return -1", path); errno = EFAULT; return -1; } if (emulate && (oflag & (O_WRONLY | O_RDWR))) { RHO_LOG("open: %s: copy from Android package", path); JNIEnv *env = jnienv(); jhstring relPathObj = rho_cast<jstring>(env, make_rel_path(fpath)); env->CallStaticBooleanMethod(clsFileApi, midCopy, relPathObj.get()); if (has_pending_exception()) { RHO_LOG("open: %s: has_pending_exception, return -1", path); errno = EFAULT; return -1; } emulate = false; } RHO_LOG("open: %s: emulate: %d", path, (int)emulate); int fd; if (emulate) { RHO_LOG("open: %s: emulate", path); JNIEnv *env = jnienv(); jhstring relPathObj = rho_cast<jstring>(env, make_rel_path(fpath)); jhobject is = env->CallStaticObjectMethod(clsFileApi, midOpen, relPathObj.get()); if (!is) { errno = EFAULT; fd = -1; } else { scoped_lock_t guard(rho_file_mtx); if (!rho_fd_free.empty()) { fd = rho_fd_free[0]; rho_fd_free.erase(rho_fd_free.begin()); } else fd = rho_fd_counter++; rho_fd_data_t d; d.type = rho_type_file; d.is = env->NewGlobalRef(is.get()); d.dirp = NULL; d.fpath = fpath; d.pos = 0; rho_fd_map[fd] = d; } } else { RHO_LOG("open: %s: native", path); mode_t mode = 0; if (oflag & O_CREAT) { va_list vl; va_start(vl, oflag); mode = va_arg(vl, int); va_end(vl); } fd = real_open(path, oflag, mode); }
//! Transform the supplied vector<OBInternalCoord*> into cartesian and update //! the OBMol accordingly. The size of supplied internal coordinate vector //! has to be the same as the number of atoms in molecule (+ NULL in the //! beginning). //! Implements <a href="http://qsar.sourceforge.net/dicts/blue-obelisk/index.xhtml#zmatrixCoordinatesIntoCartesianCoordinates">blue-obelisk:zmatrixCoordinatesIntoCartesianCoordinates</a> void InternalToCartesian(std::vector<OBInternalCoord*> &vic,OBMol &mol) { vector3 n,nn,v1,v2,v3,avec,bvec,cvec; double dst = 0.0, ang = 0.0, tor = 0.0; OBAtom *atom; vector<OBAtom*>::iterator i; unsigned int index; if (vic.empty()) return; if (vic[0] != NULL) { std::vector<OBInternalCoord*>::iterator it = vic.begin(); vic.insert(it, static_cast<OBInternalCoord*>(NULL)); } if (vic.size() != mol.NumAtoms() + 1) { string error = "Number of internal coordinates is not the same as"; error += " the number of atoms in molecule"; obErrorLog.ThrowError(__FUNCTION__, error, obError); return; } obErrorLog.ThrowError(__FUNCTION__, "Ran OpenBabel::InternalToCartesian", obAuditMsg); for (atom = mol.BeginAtom(i);atom;atom = mol.NextAtom(i)) { index = atom->GetIdx(); // make sure we always have valid pointers if (index >= vic.size() || !vic[index]) return; if (vic[index]->_a) // make sure we have a valid ptr { avec = vic[index]->_a->GetVector(); dst = vic[index]->_dst; } else { // atom 1 atom->SetVector(0.0, 0.0, 0.0); continue; } if (vic[index]->_b) { bvec = vic[index]->_b->GetVector(); ang = vic[index]->_ang * DEG_TO_RAD; } else { // atom 2 atom->SetVector(dst, 0.0, 0.0); continue; } if (vic[index]->_c) { cvec = vic[index]->_c->GetVector(); tor = vic[index]->_tor * DEG_TO_RAD; } else { // atom 3 cvec = VY; tor = 90. * DEG_TO_RAD; } v1 = avec - bvec; v2 = avec - cvec; n = cross(v1,v2); nn = cross(v1,n); n.normalize(); nn.normalize(); n *= -sin(tor); nn *= cos(tor); v3 = n + nn; v3.normalize(); v3 *= dst * sin(ang); v1.normalize(); v1 *= dst * cos(ang); v2 = avec + v3 - v1; atom->SetVector(v2); } // Delete dummy atoms vector<OBAtom*> for_deletion; FOR_ATOMS_OF_MOL(a, mol) if (a->GetAtomicNum() == 0) for_deletion.push_back(&(*a)); for(vector<OBAtom*>::iterator a_it=for_deletion.begin(); a_it!=for_deletion.end(); ++a_it) mol.DeleteAtom(*a_it); }
bool is_in_dialog() { return !open_window_stack.empty(); }
void CGUITextureManager::GetBundledTexturesFromPath(const CStdString& texturePath, std::vector<CStdString> &items) { m_TexBundle[0].GetTexturesFromPath(texturePath, items); if (items.empty()) m_TexBundle[1].GetTexturesFromPath(texturePath, items); }