void HipparcosTest::testWindowIterator() { debug(LOG_DEBUG, DEBUG_LOG, 0, "testWindowIterator() begin"); RaDec center(0, 0); center.ra().hours(6.75247702777777777777); center.dec().degrees(-16.71611583333333333333); Angle width; width.hours(1); Angle height; height.degrees(15); SkyWindow window(center, width, height); CatalogIterator i = catalog->findIter(window, MagnitudeRange(-30, 4.5)); unsigned long long counter = 0; for (; !i.isEnd(); ++i) { counter++; Star s = *i; debug(LOG_DEBUG, DEBUG_LOG, 0, "%s", s.toString().c_str()); } CPPUNIT_ASSERT(counter == 10); debug(LOG_DEBUG, DEBUG_LOG, 0, "testWindowIterator() end"); }
void constructEdgeStarMap(EdgeStarMap& esmap, StarSet& stars, bool low){ esmap.clear(); for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){ Star* s = *it; if (low) { for (HyperGraph::EdgeSet::iterator it = s->lowLevelEdges().begin(); it!=s->lowLevelEdges().end(); it++){ HyperGraph::Edge* e=*it; esmap.insert(make_pair(e,s)); } } else { for (HyperGraph::EdgeSet::iterator it = s->starEdges().begin(); it!=s->starEdges().end(); it++){ HyperGraph::Edge* e=*it; esmap.insert(make_pair(e,s)); } } } }
void PopStar::onUpdate(float delta) { for (int row = 0; row < ROW_NUM; ++row) { for (int col = 0; col < COL_NUM; ++col) { Star* star = stars[row][col]; if (star) { star->onUpdate(delta); } } } if (currentState) { currentState->execute(delta); } }
//产生炸弹的消除队列 void StarMatrix::genBombList(Star* s){ selectedList.clear(); selectedList.push_back(s); Star* linkStar = nullptr; int index_i = s->getIndexI(); int index_j = s->getIndexJ(); //上 if(index_i-1 >= 0 && (linkStar = stars[index_i-1][index_j]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i-1][index_j]); } //左上 if(index_i-1 >= 0 && index_j-1 >= 0&& (linkStar = stars[index_i-1][index_j-1]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i-1][index_j-1]); } //右上 if(index_i-1 >= 0 && index_j+1 <= COL_NUM && (linkStar = stars[index_i-1][index_j+1]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i-1][index_j+1]); } //下 if(index_i+1 < ROW_NUM && (linkStar = stars[index_i+1][index_j]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i+1][index_j]); } //左下 if(index_i+1 < ROW_NUM && index_j-1 >= 0 && (linkStar = stars[index_i+1][index_j-1]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i+1][index_j-1]); } //右下 if(index_i+1 < ROW_NUM && index_j+1 <= COL_NUM && (linkStar = stars[index_i+1][index_j+1]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i+1][index_j+1]); } //左 if(index_j-1 >= 0 && (linkStar = stars[index_i][index_j-1]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i][index_j-1]); } //右 if(index_j+1 < COL_NUM && (linkStar = stars[index_i][index_j+1]) ){ if(!linkStar->isSelected()) selectedList.push_back(stars[index_i][index_j+1]); } }
//-------------------------------------------------------------- void testApp::setup(){ ofSetFrameRate(60); ofBackground(0, 0, 0); //blink speed for(int i=0; i<10; i++){ Star blink; blink.init(); stars.push_back(blink); } //stars for (int i = 0; i <10; i++) { Star dead; dead.init(); stars.push_back(dead); } }
void printStars() { if(linkList.GetListLength() == 0) //if no file is open, do nothing. { cout << "No stars have been read.\n"; return; } Star *star = 0; Node *curNode = linkList.GetFirstNode(); //Set curNode to the first node in list while(true) { star = (Star*)(curNode->data_); //cast void pointer as Star star->PrintToConsole(); if(curNode->next_ == 0) //next_ == 0 implies curNode == last_, prevents program from trying to read outside the linked list { break; } curNode = curNode->next_; //Go to next node } }
void readFromFile() { ifstream inFile; char name[NAME_SZ] = ""; long temp = 0, starCount = 0; double lumin = 0, mass = 0, radius = 0; Star *newStar; clearStars(); //clear any residual data cout << "Please enter the file path.\n"; cin >> Star::filePath_; inFile.open(Star::filePath_); while(inFile >> name) { name[strlen(name)-1] = '\0'; //strips comma from name. newStar = new Star(name); if(newStar == 0) //Abort if memory allocation fails. { cout << "Memory allocation failed.\n"; break; } inFile.ignore(); //ignore coma, name entry actually grabs first comma, all others are caught by ignore() inFile >> temp; //read temperature newStar->SetTemperature(temp); inFile.ignore(); inFile >> lumin; //read luminosity newStar->SetLuminosity(lumin); inFile.ignore(); inFile >> mass; //read mass newStar->SetMass(mass); inFile.ignore(); inFile >> radius; //read radius newStar->SetRadius(radius); inFile.ignore(); starCount++; linkList.AddLinkToBack(newStar); } inFile.close(); inFile.clear(std::ios_base::goodbit); //reset flags to prevent errors on certain compilers cout << "Successfully loaded " << starCount << " star entries.\n"; }
void SolarSystemBrowser::slotRefreshTree() { Simulation* sim = appCore->getSimulation(); // Update the browser with the solar system closest to the active observer SolarSystem* solarSys = sim->getUniverse()->getNearestSolarSystem(sim->getActiveObserver()->getPosition()); // Don't update the solar system browser if no solar system is nearby if (!solarSys) return; Star* rootStar = solarSys->getStar(); // We want to show all gravitationally associated stars in the // browser; follow the chain up the parent star or barycenter. while (rootStar->getOrbitBarycenter() != NULL) { rootStar = rootStar->getOrbitBarycenter(); } bool groupByClass = groupCheckBox->checkState() == Qt::Checked; solarSystemModel->buildModel(rootStar, groupByClass); treeView->resizeColumnToContents(SolarSystemTreeModel::NameColumn); treeView->clearSelection(); // Automatically expand stars in the model (to a max depth of 2) QModelIndex primary = solarSystemModel->index(0, 0, QModelIndex()); if (primary.isValid() && solarSystemModel->objectAtIndex(primary).star() != NULL) { treeView->setExpanded(primary, true); QModelIndex secondary = solarSystemModel->index(0, 0, primary); if (secondary.isValid() && solarSystemModel->objectAtIndex(secondary).star() != NULL) { treeView->setExpanded(secondary, true); } } }
bool StarMatrix::init_matrix() { // make matrix auto width = m_nWidth / 10; auto height = m_nHeight / 13; srand(static_cast<unsigned int>(time(nullptr))); for (int i = 0; i != 10; ++i) { for (int j = 0; j != 13; ++j) { auto t = random(0, 4); Star* child = Star::create(t, width, height); child->setAnchorPoint(Vec2(0, 0)); child->setPosition(Vec2(i*width, j*height)); this->addChild(child); } } // callback auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(StarMatrix::OnTouchBegin, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); return true; }
Star StarMap::nearestNeighbor(const Star& star, double threshold) const { auto c = star.getCoords(); int index[2] = { 0 }; double dist[2] = { 0 }; flann::Matrix<int> i = toMatrix(index, 1, 2); flann::Matrix<double> d = toMatrix(dist, 1, 2); spatial_index_->knnSearch(toMatrix(&c), i, d, 2, flann::SearchParams()); return (dist[1] < threshold*threshold) ? byIndex().at(index[1]) : Star(); }
/** * @brief Draws all of the outbound edges from this star. * * @warning Internal use only. Call only in GL_BEGIN context in * GL_LINES mode! */ void Star::drawEdges() { #ifndef NO_GFX std::vector<Star *>::iterator i; for(i = this->edges.begin(); i != this->edges.end(); i++) { Star * other = *i; if(other->getID() < this->getID()) { if(other == this->path_next || other->path_next == this) this->glColor4d(0.8); else if(std::count(this->mst_edges.begin(), this->mst_edges.end(), other)) ::glColor4d(0.0,0.33,0.66,0.6); else ::glColor4d(0.2,0.2,0.2,0.5); this->glVertex3d(); if(other == this->path_next || other->path_next == this) other->glColor4d(0.8); other->glVertex3d(); } } for(i = this->mst_edges.begin(); i != this->mst_edges.end(); i++) { Star * other = *i; if(other->getID() < this->getID()) { if(other == this->path_next || other->path_next == this) this->glColor4d(0.8); else ::glColor4d(0.66,0.0,0.66,0.6); if(!std::count(this->edges.begin(), this->edges.end(), other)) this->glVertex3d(); if(other == this->path_next || other->path_next == this) other->glColor4d(0.8); if(!std::count(this->edges.begin(), this->edges.end(), other)) other->glVertex3d(); } } #endif }
void StarMatrix::deleteSelectedList(){ //播放消除音效 Audio::getInstance()->playPop(); for(auto it = selectedList.begin();it != selectedList.end();it++){ Star* star = *it; m_layer->showEveryScore(selectedListSize,5+(selectedListSize-selectedList.size())*5,selectedListSize-selectedList.size(),star->getPosition(),touchLeft); selectedList.pop_front(); //粒子效果 showStarParticleEffect(star->getColor(),star->getPosition(),this); stars[star->getIndexI()][star->getIndexJ()] = nullptr; star->removeFromParentAndCleanup(true); return; } clearOneByOne =false; //COMBO效果 showComboEffect(selectedListSize,this); m_layer->showLinkNum(selectedListSize); selectedListSize=0; acceptTouch =true; adjustMatrix(); if(isEnded()){ acceptTouch=false; m_layer->hideProps(); m_layer->floatLeftStarMsg(getLeftStarNum());//通知layer弹出剩余星星的信息 CCLOG("ENDED"); } }
void StarMatrix::deleteSelectedList() { if(selectedList.size() <= 1) { m_layer->hideLinkNum(); selectedList.at(0)->setSelected(false); return; } for(auto it = selectedList.begin();it != selectedList.end();it++) { Star* star = *it; showStarParticleEffect(star->getColor(),star->getPosition(),this); stars[star->getIndexI()][star->getIndexJ()] = nullptr; star->removeFromParentAndCleanup(true); Audio::getInstance()->playPop(); } showComboEffect(selectedList.size(),this); Audio::getInstance()->playCombo(selectedList.size()); refreshScore(); m_layer->showLinkNum(selectedList.size()); adjustMatrix(); if(isEnded()) { m_layer->floatLeftStarMsg(getLeftStarNum()); CCLOG("ENDED"); } }
void addStar() { char name[NAME_SZ] = ""; long temp = 0; double lumin = 0, mass = 0, radius = 0; Star *newStar; if(strcmp(Star::filePath_, "") == 0) //if no file is open, do nothing. { cout << "No file to write to, please load a file.\n"; return; } cout << "Please enter the following information: \nName: "; cin >> name; newStar = new Star(name); //instantiate star with name if(newStar == 0) //Abort if memory allocation fails. { cout << "Memory allocation failed.\n"; return; } cout << "Temperature: "; cin >> temp; newStar->SetTemperature(temp); cout << "Luminosity: "; cin >> lumin; newStar->SetLuminosity(lumin); cout << "Mass: "; cin >> mass; newStar->SetMass(mass); cout << "Radius: "; cin >> radius; newStar->SetRadius(radius); linkList.AddLinkToBack(newStar); //add star to linked list newStar->AppendToFile(); }
StringPimpl Person2::getString() const throw(InternalProgrammerErrorException &) { try { if(m_pimpl->m_atomic) { //This is an atomic element shortcut Star star; StringPimpl returnString = star.getString(); return FrameworkFactory::getInstance()->getGraphBuilderFramework()->person2Substitute(returnString); } else { return FrameworkFactory::getInstance()->getGraphBuilderFramework()->person2Substitute(InnerTemplateListImpl::getString()); } } catch(Exception &) { //Fatal exception occured" return StringPimpl(); } }
void StarList::saveMap(const QString& filename) { QFile data(filename); if (data.open(QFile::WriteOnly | QFile::Truncate)) { Star *star; QTextStream out(&data); double d = 1000.00; QString sCode; out << _listName << "\n"; foreach (star, _stars) { sCode.sprintf("%04.2f",d++); out << sCode << "/" << star->x() << "/" << star->y() << "/" << star->z() << "/" << star->starName << "/" << star->starName << "/" << star->starName << "//" << star->starFullType() << "/" << "//" << star->starName << "\n"; }
void Visit(const Star &s) { s.GetNode()->Accept(*this); std::sort(words_.begin(), words_.end()); std::stringstream ss; ss << "("; bool first = true; for (const auto &word : words_) { if (!first) { ss << "+"; } else { first = false; } ss << word; } ss << ")*"; words_ = { ss.str() }; }
void StarMatrix::adjustMatrix(){ //垂直方向调整 for(int i = ROW_NUM-1;i>=0;i--){ for(int j = COL_NUM-1;j>=0;j--){ if(stars[i][j] == nullptr){ int up = i; int dis = 0; while(stars[up][j] == nullptr){ dis++; up--; if(up<0){ break; } } for(int begin_i = i - dis;begin_i >= 0;begin_i--){ if(stars[begin_i][j] == nullptr) continue; Star* s = stars[begin_i + dis][j] = stars[begin_i][j]; s->setIndex_ij(begin_i + dis,j); s->setDesPosition(getPositionByIndex(begin_i + dis,j)); stars[begin_i][j] = nullptr; } }else{ continue; } } } //水平方向调整 for(int j = 0;j < COL_NUM;j++){ if(stars[ROW_NUM-1][j] == nullptr){ int des = 0; int right = j; while(stars[ROW_NUM-1][right] == nullptr){ des++; right++; } for(int begin_i = 0;begin_i<ROW_NUM;begin_i++){ for(int begin_j = j + des;begin_j < COL_NUM;begin_j++){ if(stars[begin_i][begin_j] == nullptr) continue; Star* s = stars[begin_i][begin_j - des] = stars[begin_i][begin_j]; s->setIndex_ij(begin_i,begin_j - des); s->setDesPosition(getPositionByIndex(begin_i,begin_j - des)); stars[begin_i][begin_j] = nullptr; } } } } }
// A less convenient version of getStarName that writes to a char // array instead of a string. The advantage is that no memory allocation // will every occur. void StarDatabase::getStarName(const Star& star, char* nameBuffer, unsigned int bufferSize, bool i18n) const { assert(bufferSize != 0); uint32 catalogNumber = star.getCatalogNumber(); if (namesDB != NULL) { StarNameDatabase::NumberIndex::const_iterator iter = namesDB->getFirstNameIter(catalogNumber); if (iter != namesDB->getFinalNameIter() && iter->first == catalogNumber) { if (i18n && iter->second != _(iter->second.c_str())) strncpy(nameBuffer, _(iter->second.c_str()), bufferSize); else strncpy(nameBuffer, iter->second.c_str(), bufferSize); nameBuffer[bufferSize - 1] = '\0'; return; } } catalogNumberToString(catalogNumber, nameBuffer, bufferSize); }
bool PopStar::isLevelEnd() { for (int row = 0; row < ROW_NUM; ++row) { for (int col = 0; col < COL_NUM; ++col) { Star* star = stars[row][col]; if (star == NULL) { continue; } int checkRow = row + 1; if (checkRow < ROW_NUM) { Star* checkStar = stars[checkRow][col]; if ( checkStar && (star->getIndex() == checkStar->getIndex()) ) { return false; } } int checkCol = col + 1; if (checkCol < COL_NUM) { Star* checkStar = stars[row][checkCol]; if ( checkStar && (star->getIndex() == checkStar->getIndex()) ) { return false; } } } } return true; }
void StarMatrix::deleteBombList(){ //播放消除音效 Audio::getInstance()->playPropBomb(); for(auto it = selectedList.begin();it != selectedList.end();it++){ Star* star = *it; //粒子效果 showStarParticleEffect(star->getColor(),star->getPosition(),this); stars[star->getIndexI()][star->getIndexJ()] = nullptr; star->removeFromParentAndCleanup(true); } selectedList.clear(); //COMBO效果 selectedListSize=0; acceptTouch =true; adjustMatrix(); if(isEnded()){ acceptTouch=false; m_layer->hideProps(); m_layer->floatLeftStarMsg(getLeftStarNum()); } }
void StarList::createRandomMap(double radius = 50, double density = 750) { double dFactor = radius/50; dFactor = pow(dFactor, 3); int starCount = (int)(1000 * dFactor) + SSGX::d100()-SSGX::d100(); Onomastikon* names = Onomastikon::instancePtr(); Star *starToDelete; foreach (starToDelete,_stars) delete starToDelete; _stars.clear(); Star *newStar = 0; for (int idx = 0; idx < starCount; idx++) { newStar = new Star(radius); int die = SSGX::d10(); if (die < 3) newStar->starName = names->greekName(); else if (die >=3 && die <= 8) newStar->starName = names->sigla(); else { QString nomen; do { nomen = names->pseudoNomen()+"'s star"; } while (nomen.length() == 0); newStar->starName = nomen; } _stars.append(newStar); if (idx == 0) { newStar->starName = "(CORE) "+newStar->starName; newStar->setX(0); newStar->setY(0); newStar->setZ(0); newStar->setStarFullType("G2V"); newStar->setReference(); } } }
void GameLayer::clearStarAt(CCPoint point) { int col = (int) point.x / TILE; int row = (int) (_screenSize.height - point.y) / TILE; if (row < 0 || col < 0 || row >= _manager->getRows() || col >= _manager->getColumns() || row * _manager->getColumns() + col >= STARS_IN_POOL) { return; } //identify cell in array Star * star = _manager->starFromPool(row * _manager->getColumns() + col); //CCLOG ("COL: %i ROW: %i", col, row); if (star->isVisible()) { float diffx = _moon->getPositionX() - star->getPositionX(); float diffy = _moon->getPositionY() - star->getPositionY(); if ((diffx * diffx + diffy * diffy) <= _moon->getSquaredRadius()) { int starsCollected = _manager->getCollectedStars(); int totalStarsCollected = _manager->getTotalCollectedStars(); starsCollected++; totalStarsCollected++; _manager->setCollectedStars(starsCollected); _manager->setTotalCollectedStars(totalStarsCollected); star->setVisible(false); int totalStars = _manager->getTotalStars(); //did we hit a boost? if (star->getIsBoost()) { _manager->setBoosting(true); if (starsCollected != totalStars) { _boostHitParticles->setPosition(star->getPosition()); _boostHitParticles->resetSystem(); } } //if last star on screen, show particles, show Moon Perch... if (starsCollected == totalStars) { SimpleAudioEngine::sharedEngine()->playEffect("last_star_hit.wav"); _starHitParticles->setPosition(star->getPosition()); _starHitParticles->resetSystem(); _starsCollected = true; if (_sun->isVisible()) { _moonPerch->setOpacity(100); } else { _moonPerch->setOpacity(200); } } else { if (star->getIsBoost()) { SimpleAudioEngine::sharedEngine()->playEffect("boost_hit.wav"); } else { SimpleAudioEngine::sharedEngine()->playEffect("star_hit.wav"); } } } } }
vector float fTest(const Star & val) { vector float vf = val.foo(); return vf; }
void GameLayer::update (float dt) { if (_gameState == kGameStatePlay) { //if running game logic if (_running) { _manager->update(dt); dt *= DT_RATE; //update elements _moon->update(dt); if (_sun->isVisible()) { _sun->update(dt); if (_sun->checkCollisionWithMoon(_moon)) { SimpleAudioEngine::sharedEngine()->playEffect("sun_hit.wav"); } } //check collision with lines, update, draw Line * line; int len = _manager->getLines()->count(); bool collisionDetected = false; for (int i = len-1; i >= 0; i--) { line = (Line *) _manager->getLines()->objectAtIndex(i); if (!collisionDetected && line->getActive()) { if (line->collidesWithMoon(_moon)) { collisionDetected = true; SimpleAudioEngine::sharedEngine()->playEffect("line_hit.wav"); _lineHitParticles->setPosition(line->getCollisionPoint()); _lineHitParticles->resetSystem(); } } if (line->getTrashme()) { _manager->getLines()->removeObjectAtIndex(i); } else { line->update(dt); } } _moon->place(); //if moon off screen to the top, make screen darker as moons gets farther and farther away if (_moon->getPositionY() > _screenSize.height) { if (!_sun->isVisible()) { float opacity = fabs((255 * (_moon->getPositionY() - _screenSize.height))/_screenSize.height); if (opacity > 200) opacity = 200; if (!_sun->isVisible()) _bgDark->setOpacity ( 255 - opacity ); } } else { if (!_sun->isVisible()) { if (_bgDark->getOpacity() != 255) _bgDark->setOpacity ( 255 ); } } //track collision with MOON and STAR (usign grid logic) float range = _moon->getRadius(); float posX = _moon->getPositionX(); float posY = _moon->getPositionY(); //I decided to check 9 cells for precision sake clearStarAt(ccp(posX, posY)); clearStarAt(ccp(posX, posY + range)); clearStarAt(ccp(posX, posY - range)); clearStarAt(ccp(posX + range, posY)); clearStarAt(ccp(posX + range, posY + range)); clearStarAt(ccp(posX + range, posY - range)); clearStarAt(ccp(posX - range, posY)); clearStarAt(ccp(posX - range, posY - range)); clearStarAt(ccp(posX - range, posY + range)); //update bars //check timer if (_manager->getTime() <= 0.65f && !_sun->isVisible()) { SimpleAudioEngine::sharedEngine()->playEffect("sun_rise.wav"); _sun->setVisible(true); _sun->setHasRisen(false); } else if (_manager->getTime() <= 0.25f && _sun->isVisible() && !_sun->getHasGrown()) { SimpleAudioEngine::sharedEngine()->playEffect("sun_grow.wav"); _sun->highNoon(); } else if (_manager->getTime() <= 0.0f) { //if you want game over once time runs out. //game; } if (_sun->isVisible()) { if (!_bgLight->isVisible()) { _bgLight->setVisible(true); } //when sun is added to screen, fade out dark bg if (_bgLight->getOpacity() + 5 < 255) { _bgLight->setOpacity(_bgLight->getOpacity() + 5 ); _bgDark->setOpacity (_bgDark->getOpacity() - 5); } else { _bgDark->setVisible(false); _bgDark->setOpacity(255); _bgLight->setOpacity(255); } _sun->place(); } //check power if (_manager->getLineEnergy() <= 0) { if (!_moon->getIsOff()) { _moon->turnOnOff(false); } } //track collision between Moon and Moon's perch if (_starsCollected) { if (pow (_moonStartPoint.x - _moon->getPositionX(), 2) + pow (_moonStartPoint.y - _moon->getPositionY(), 2) < _moon->getSquaredRadius()) { _moon->setPosition(_moonStartPoint); _moon->setNextPosition(_moonStartPoint); _moon->setActive(false); newLevel(); } } if (_moon->getPositionY() < _moon->getRadius() && _moon->getActive()) { _groundHitParticles->setPosition(_moon->getPosition()); _groundHitParticles->resetSystem(); SimpleAudioEngine::sharedEngine()->playEffect("ground_hit.wav"); _moon->setActive(false); gameOver(); } //make stars blink if (!_sun->isVisible()) { _starsUpdateTimer += dt; int stars_count = _numStars; if (_starsUpdateTimer > _starsUpdateInterval) { if (stars_count - _starsUpdateIndex < _starsUpdateRange) { _starsUpdateIndex = 0; } else if (_starsUpdateIndex + _starsUpdateRange > stars_count - 1) { _starsUpdateIndex += stars_count - _starsUpdateIndex - 1; } else { _starsUpdateIndex += _starsUpdateRange; } _starsUpdateTimer = 0; _starsUpdateInterval = ((float)rand() / RAND_MAX) * 5; } //update stars within update range Star * star; for (int i = _starsUpdateIndex; i < _starsUpdateIndex + _starsUpdateRange; i++) { if (i < stars_count) { CCPoint point = _manager->starPosition(i); int index = point.y * _manager->getColumns() + point.x; if (index >= STARS_IN_POOL) index = STARS_IN_POOL - 1; //identify cell in array star = _manager->starFromPool(index); if (star->isVisible() && !star->getIsBoost()) star->update(dt); } } } } } }
void StarMatrix::genSelectedList(Star* s) { selectedList.clear(); deque<Star*> travelList; travelList.push_back(s); deque<Star*>::iterator it; for(it= travelList.begin();it != travelList.end();) { Star* star = *it; Star* linkStar = nullptr; int index_i = star->getIndexI(); int index_j = star->getIndexJ(); if(index_i-1 >= 0 && (linkStar = stars[index_i-1][index_j]) ) { if(!linkStar->isSelected() && linkStar->getColor() == star->getColor()) travelList.push_back(stars[index_i-1][index_j]); } if(index_i+1 < ROW_NUM && (linkStar = stars[index_i+1][index_j]) ) { if(!linkStar->isSelected() && linkStar->getColor() == star->getColor()) travelList.push_back(stars[index_i+1][index_j]); } if(index_j-1 >= 0 && (linkStar = stars[index_i][index_j-1]) ) { if(!linkStar->isSelected() && linkStar->getColor() == star->getColor()) travelList.push_back(stars[index_i][index_j-1]); } if(index_j+1 < COL_NUM && (linkStar = stars[index_i][index_j+1])) { if(!linkStar->isSelected() && linkStar->getColor() == star->getColor()) travelList.push_back(stars[index_i][index_j+1]); } if(!star->isSelected()) { star->setSelected(true); selectedList.push_back(star); } travelList.pop_front(); it = travelList.begin(); } }
void computeSimpleStars(StarSet& stars, SparseOptimizer* optimizer, EdgeLabeler* labeler, EdgeCreator* creator, OptimizableGraph::Vertex* gauge_, std::string edgeTag, std::string vertexTag, int level, int step, int backboneIterations, int starIterations, double rejectionThreshold, bool debug){ cerr << "preforming the tree actions" << endl; HyperDijkstra d(optimizer); // compute a spanning tree based on the types of edges and vertices in the pool EdgeTypesCostFunction f(edgeTag, vertexTag, level); d.shortestPaths(gauge_, &f, std::numeric_limits< double >::max(), 1e-6, false, std::numeric_limits< double >::max()/2); HyperDijkstra::computeTree(d.adjacencyMap()); // constructs the stars on the backbone BackBoneTreeAction bact(optimizer, vertexTag, level, step); bact.init(); cerr << "free edges size " << bact.freeEdges().size() << endl; // perform breadth-first visit of the visit tree and create the stars on the backbone d.visitAdjacencyMap(d.adjacencyMap(),&bact,true); stars.clear(); for (VertexStarMultimap::iterator it=bact.vertexStarMultiMap().begin(); it!=bact.vertexStarMultiMap().end(); it++){ stars.insert(it->second); } cerr << "stars.size: " << stars.size() << endl; cerr << "size: " << bact.vertexStarMultiMap().size() << endl; // for each star // for all vertices in the backbone, select all edges leading/leaving from that vertex // that are contained in freeEdges. // mark the corresponding "open" vertices and add them to a multimap (vertex->star) // select a gauge in the backbone // push all vertices on the backbone // compute an initial guess on the backbone // one round of optimization backbone // lock all vertices in the backbone // push all "open" vertices // for each open vertex, // compute an initial guess given the backbone // do some rounds of solveDirect // if (fail) // - remove the vertex and the edges in that vertex from the star // - make the structures consistent // pop all "open" vertices // pop all "vertices" in the backbone // unfix the vertices in the backbone int starNum=0; for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){ Star* s =*it; HyperGraph::VertexSet backboneVertices = s->_lowLevelVertices; HyperGraph::EdgeSet backboneEdges = s->_lowLevelEdges; if (backboneEdges.empty()) continue; // cerr << "optimizing backbone" << endl; // one of these should be the gauge, to be simple we select the fisrt one in the backbone OptimizableGraph::VertexSet gauge; gauge.insert(*backboneVertices.begin()); s->gauge()=gauge; s->optimizer()->push(backboneVertices); s->optimizer()->setFixed(gauge,true); s->optimizer()->initializeOptimization(backboneEdges); s->optimizer()->computeInitialGuess(); s->optimizer()->optimize(backboneIterations); s->optimizer()->setFixed(backboneVertices, true); // cerr << "assignind edges.vertices not in bbone" << endl; HyperGraph::EdgeSet otherEdges; HyperGraph::VertexSet otherVertices; std::multimap<HyperGraph::Vertex*, HyperGraph::Edge*> vemap; for (HyperGraph::VertexSet::iterator bit=backboneVertices.begin(); bit!=backboneVertices.end(); bit++){ HyperGraph::Vertex* v=*bit; for (HyperGraph::EdgeSet::iterator eit=v->edges().begin(); eit!=v->edges().end(); eit++){ OptimizableGraph::Edge* e = (OptimizableGraph::Edge*) *eit; HyperGraph::EdgeSet::iterator feit=bact.freeEdges().find(e); if (feit!=bact.freeEdges().end()){ // edge is admissible otherEdges.insert(e); bact.freeEdges().erase(feit); for (size_t i=0; i<e->vertices().size(); i++){ OptimizableGraph::Vertex* ve= (OptimizableGraph::Vertex*)e->vertices()[i]; if (backboneVertices.find(ve)==backboneVertices.end()){ otherVertices.insert(ve); vemap.insert(make_pair(ve,e)); } } } } } // RAINER TODO maybe need a better solution than dynamic casting here?? OptimizationAlgorithmWithHessian* solverWithHessian = dynamic_cast<OptimizationAlgorithmWithHessian*>(s->optimizer()->solver()); if (solverWithHessian) { s->optimizer()->push(otherVertices); // cerr << "optimizing vertices out of bbone" << endl; // cerr << "push" << endl; // cerr << "init" << endl; s->optimizer()->initializeOptimization(otherEdges); // cerr << "guess" << endl; s->optimizer()->computeInitialGuess(); // cerr << "solver init" << endl; s->optimizer()->solver()->init(); // cerr << "structure" << endl; if (!solverWithHessian->buildLinearStructure()) cerr << "FATAL: failure while building linear structure" << endl; // cerr << "errors" << endl; s->optimizer()->computeActiveErrors(); // cerr << "system" << endl; solverWithHessian->updateLinearSystem(); // cerr << "directSolove" << endl; } else { cerr << "FATAL: hierarchical thing cannot be used with a solver that does not support the system structure construction" << endl; } // // then optimize the vertices one at a time to check if a solution is good for (HyperGraph::VertexSet::iterator vit=otherVertices.begin(); vit!=otherVertices.end(); vit++){ OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)(*vit); v->solveDirect(); // cerr << " " << d; // if a solution is found, add a vertex and all the edges in //othervertices that are pointing to that edge to the star s->_lowLevelVertices.insert(v); for (HyperGraph::EdgeSet::iterator eit=v->edges().begin(); eit!=v->edges().end(); eit++){ OptimizableGraph::Edge* e = (OptimizableGraph::Edge*) *eit; if (otherEdges.find(e)!=otherEdges.end()) s->_lowLevelEdges.insert(e); } } //cerr << endl; // relax the backbone and optimize it all // cerr << "relax bbone" << endl; s->optimizer()->setFixed(backboneVertices, false); //cerr << "fox gauge bbone" << endl; s->optimizer()->setFixed(s->gauge(),true); //cerr << "opt init" << endl; s->optimizer()->initializeOptimization(s->_lowLevelEdges); optimizer->computeActiveErrors(); double initialChi = optimizer->activeChi2(); int starOptResult = s->optimizer()->optimize(starIterations); //cerr << starOptResult << "(" << starIterations << ") " << endl; double finalchi=-1.; cerr << "computing star: " << starNum << endl; int vKept=0, vDropped=0; if (!starIterations || starOptResult > 0 ){ optimizer->computeActiveErrors(); finalchi = optimizer->activeChi2(); #if 1 s->optimizer()->computeActiveErrors(); // cerr << "system" << endl; if (solverWithHessian) solverWithHessian->updateLinearSystem(); HyperGraph::EdgeSet prunedStarEdges = backboneEdges; HyperGraph::VertexSet prunedStarVertices = backboneVertices; for (HyperGraph::VertexSet::iterator vit=otherVertices.begin(); vit!=otherVertices.end(); vit++){ //discard the vertices whose error is too big OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)(*vit); MatrixXd h(v->dimension(), v->dimension()); for (int i=0; i<v->dimension(); i++){ for (int j=0; j<v->dimension(); j++) h(i,j)=v->hessian(i,j); } EigenSolver<Eigen::MatrixXd> esolver; esolver.compute(h); VectorXcd ev= esolver.eigenvalues(); double emin = std::numeric_limits<double>::max(); double emax = -std::numeric_limits<double>::max(); for (int i=0; i<ev.size(); i++){ emin = ev(i).real()>emin ? emin : ev(i).real(); emax = ev(i).real()<emax ? emax : ev(i).real(); } double d=emin/emax; // cerr << " " << d; if (d>rejectionThreshold){ // if a solution is found, add a vertex and all the edges in //othervertices that are pointing to that edge to the star prunedStarVertices.insert(v); for (HyperGraph::EdgeSet::iterator eit=v->edges().begin(); eit!=v->edges().end(); eit++){ OptimizableGraph::Edge* e = (OptimizableGraph::Edge*) *eit; if (otherEdges.find(e)!=otherEdges.end()) prunedStarEdges.insert(e); } //cerr << "K( " << v->id() << "," << d << ")" ; vKept ++; } else { vDropped++; //cerr << "R( " << v->id() << "," << d << ")" ; } } s->_lowLevelEdges=prunedStarEdges; s->_lowLevelVertices=prunedStarVertices; #endif //cerr << "addHedges" << endl; //now add to the star the hierarchical edges std::vector<OptimizableGraph::Vertex*> vertices(2); vertices[0]= (OptimizableGraph::Vertex*) *s->_gauge.begin(); for (HyperGraph::VertexSet::iterator vit=s->_lowLevelVertices.begin(); vit!=s->_lowLevelVertices.end(); vit++){ OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)*vit; vertices[1]=v; if (v==vertices[0]) continue; OptimizableGraph::Edge* e=creator->createEdge(vertices); //rr << "creating edge" << e << Factory::instance()->tag(vertices[0]) << "->" << Factory::instance()->tag(v) <endl; if (e) { e->setLevel(level+1); optimizer->addEdge(e); s->_starEdges.insert(e); } else { cerr << "HERE" << endl; cerr << "FATAL, cannot create edge" << endl; } } } cerr << " gauge: " << (*s->_gauge.begin())->id() << " kept: " << vKept << " dropped: " << vDropped << " edges:" << s->_lowLevelEdges.size() << " hedges" << s->_starEdges.size() << " initial chi " << initialChi << " final chi " << finalchi << endl; if (debug) { char starLowName[100]; sprintf(starLowName, "star-%04d-low.g2o", starNum); ofstream starLowStream(starLowName); optimizer->saveSubset(starLowStream, s->_lowLevelEdges); } bool labelOk=false; if (!starIterations || starOptResult > 0) labelOk = s->labelStarEdges(0, labeler); if (labelOk) { if (debug) { char starHighName[100]; sprintf(starHighName, "star-%04d-high.g2o", starNum); ofstream starHighStream(starHighName); optimizer->saveSubset(starHighStream, s->_starEdges); } } else { cerr << "FAILURE: " << starOptResult << endl; } starNum++; //label each hierarchical edge s->optimizer()->pop(otherVertices); s->optimizer()->pop(backboneVertices); s->optimizer()->setFixed(s->gauge(),false); } StarSet stars2; // now erase the stars that have 0 edges. They r useless for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){ Star* s=*it; if (s->lowLevelEdges().size()==0) { delete s; } else stars2.insert(s); } stars=stars2; }
bool GuiderOneStar::AutoSelect(void) { bool bError = false; usImage *pImage = CurrentImage(); try { if (!pImage || !pImage->ImageData) { throw ERROR_INFO("No Current Image"); } // If mount is not calibrated, we need to chose a star a bit farther // from the egde to allow for the motion of the star during // calibration // int edgeAllowance = 0; if (pMount && pMount->IsConnected() && !pMount->IsCalibrated()) edgeAllowance = wxMax(edgeAllowance, pMount->CalibrationTotDistance()); if (pSecondaryMount && pSecondaryMount->IsConnected() && !pSecondaryMount->IsCalibrated()) edgeAllowance = wxMax(edgeAllowance, pSecondaryMount->CalibrationTotDistance()); Star newStar; if (!newStar.AutoFind(*pImage, edgeAllowance, m_searchRegion)) { throw ERROR_INFO("Unable to AutoFind"); } m_massChecker->Reset(); if (!m_star.Find(pImage, m_searchRegion, newStar.X, newStar.Y, Star::FIND_CENTROID)) { throw ERROR_INFO("Unable to find"); } if (SetLockPosition(m_star)) { throw ERROR_INFO("Unable to set Lock Position"); } if (GetState() == STATE_SELECTING) { // immediately advance the state machine now, rather than waiting for // the next exposure to complete. Socket server clients are going to // try to start guiding after selecting the star, but guiding will fail // to start if state is still STATE_SELECTING Debug.AddLine("AutoSelect: state = %d, call UpdateGuideState", GetState()); UpdateGuideState(NULL, false); } UpdateImageDisplay(); pFrame->pProfile->UpdateData(pImage, m_star.X, m_star.Y); } catch (wxString Msg) { if (pImage && pImage->ImageData) { SaveAutoSelectFailedImg(pImage); } POSSIBLY_UNUSED(Msg); bError = true; } return bError; }
float Body::getLuminosity(const Star& sun, float distanceFromSun) const { return getLuminosity(sun.getLuminosity(), distanceFromSun); }
// on "init" you need to initialize your instance bool GameScene::init() { CCLOG("GAME SCENE START"); srand((int)std::time(NULL)); if (!MainScene::init()) { return false; } world = new b2World(b2Vec2(0.f, 0.f)); // HERE STARTS THE MAGIC scheduleUpdate(); mState = States::S_GAME; Vec2 origin = Director::getInstance()->getVisibleOrigin(); Size visibleSize = Director::getInstance()->getVisibleSize(); // Background mBackground = Sprite::create("backgrounds/gameBackground.png"); mBackground->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)); this->addChild(mBackground, Layers::BACKGROUND); // Player mPlayer = Player::create(Vec2(400.f, 400.f), world); this->addChild(mPlayer, Layers::PLAYER); mapKeysPressed[EventKeyboard::KeyCode::KEY_UP_ARROW] = false; mapKeysPressed[EventKeyboard::KeyCode::KEY_RIGHT_ARROW] = false; mapKeysPressed[EventKeyboard::KeyCode::KEY_LEFT_ARROW] = false; mapKeysPressed[EventKeyboard::KeyCode::KEY_DOWN_ARROW] = false; // Create starry background which moves for (unsigned int i = 0; i < 100; ++i) { Star * star = Star::create(cocos2d::Vec2(50.f + rand() % (int)(visibleSize.width), 50.f + rand() % (int)(visibleSize.height * 0.9f))); star->setScale(0.2f + (rand() % 6) / 10.f); star->setOpacity(50 + (rand() % 200)); this->addChild(star, Layers::SECOND_PLAN); vecStars.push_back(star); } // Assign Box2D contact listener to world CL = new ContactListener; world->SetContactListener(CL); // Points pointsLabel = Label::createWithTTF("Score: " + std::to_string(points), "fonts/DKCoolCrayon.ttf", 25.f); pointsLabel->setPosition(10 + pointsLabel->getBoundingBox().size.width / 2, 20); this->addChild(pointsLabel, Layers::GUI); mGameOverInfo = Label::createWithTTF("Game Over\nScore: " + std::to_string(points), "fonts/DKCoolCrayon.ttf", 50.f); mGameOverInfo->setPosition(visibleSize.width / 2.f, visibleSize.height / 2.f); mGameOverInfo->setAlignment(cocos2d::TextHAlignment::CENTER); mGameOverInfo->setOpacity(0); this->addChild(mGameOverInfo, Layers::GUI); // Bars mHpBarBorder = Sprite::create("gui/BarBorder.png"); mRageBarBorder = Sprite::create("gui/BarBorder.png"); mHpBarFill = Sprite::create("gui/HpBarFill.png"); mRageBarFill = Sprite::create("gui/RageBarFill.png"); mRageBarFill->setTextureRect(cocos2d::Rect(0.f, 0.f, 0.f, mRageBarFill->getBoundingBox().size.height)); mRageBarFill->setAnchorPoint(Vec2(0.f, 0.5f)); mRageBarBorder->setAnchorPoint(Vec2(0.f, 0.5f)); mHpBarBorder->setAnchorPoint(Vec2(0.f, 0.5f)); mHpBarFill->setAnchorPoint(Vec2(0.f, 0.5f)); mHpBarBorder->setPosition(100.f, visibleSize.height - 30.f); mRageBarBorder->setPosition(350.f, visibleSize.height - 30.f); mHpBarFill->setPosition(100.f, visibleSize.height - 30.f); mRageBarFill->setPosition(350.f, visibleSize.height - 30.f); this->addChild(mHpBarFill, Layers::GUI); this->addChild(mRageBarFill, Layers::GUI); this->addChild(mHpBarBorder, Layers::GUI); this->addChild(mRageBarBorder, Layers::GUI); time = 0.f; return true; }