void Topology::flushCache() { #ifdef DEBUG_TFC StartupStore(TEXT("---flushCache() starts%s"),NEWLINE); int starttick = GetTickCount(); #endif #ifdef TOPOFASTCACHE switch (cache_mode) { case 0: // Original case 1: // Bounds array in memory for (int i=0; i<shpfile.numshapes; i++) { removeShape(i); } break; case 2: // Shapes in memory for (int i=0; i<shpfile.numshapes; i++) { shpCache[i] = NULL; } break; }//sw #else for (int i=0; i<shpfile.numshapes; i++) { removeShape(i); } #endif shapes_visible_count = 0; #ifdef DEBUG_TFC StartupStore(TEXT(" flushCache() ends (%dms)%s"),GetTickCount()-starttick,NEWLINE); #endif }
void ModifyActionList::createActions() { /*QAction* acStamp = new QAction(tr("Выдавливание"), this); connect(acStamp, SIGNAL(triggered()), this, SLOT(makePrism())); actionList->push_back(acStamp); QAction* acRotation = new QAction(tr("Вращение"), this); actionList->push_back(acRotation); QAction* acAddition = new QAction(tr("Сложение"), this); actionList->push_back(acAddition); QAction* acSubstract = new QAction(tr("Вычитание"), this); actionList->push_back(acSubstract);*/ QAction* acFusion = new QAction(tr("Fuse"), this); connect(acFusion, SIGNAL(triggered()), this, SLOT(shapesFusion())); actionList->push_back(acFusion); QAction* acCommon = new QAction(tr("Common"), this); connect(acCommon, SIGNAL(triggered()), this, SLOT(shapesCommon())); actionList->push_back(acCommon); QAction* acCut = new QAction(tr("Cut"), this); connect(acCut, SIGNAL(triggered()), this, SLOT(shapesCut())); actionList->push_back(acCut); QAction* acRemoveShape = new QAction(tr("Remove"), this); acRemoveShape->setShortcut(Qt::Key_Delete); connect(acRemoveShape, SIGNAL(triggered()), this, SLOT(removeShape())); actionList->push_back(acRemoveShape); }
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: openDocument(); break; case 1: saveDocument(); break; case 2: closeDocument(); break; case 3: newDocument(); break; case 4: addShape(); break; case 5: removeShape(); break; case 6: setShapeColor(); break; case 7: addSnowman(); break; case 8: addRobot(); break; case 9: about(); break; case 10: aboutQt(); break; case 11: updateActions(); break; default: ; } _id -= 12; } return _id; }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setupUi(this); QWidget *w = documentTabs->widget(0); documentTabs->removeTab(0); delete w; connect(actionOpen, SIGNAL(triggered()), this, SLOT(openDocument())); connect(actionClose, SIGNAL(triggered()), this, SLOT(closeDocument())); connect(actionNew, SIGNAL(triggered()), this, SLOT(newDocument())); connect(actionSave, SIGNAL(triggered()), this, SLOT(saveDocument())); connect(actionExit, SIGNAL(triggered()), this, SLOT(close())); connect(actionRed, SIGNAL(triggered()), this, SLOT(setShapeColor())); connect(actionGreen, SIGNAL(triggered()), this, SLOT(setShapeColor())); connect(actionBlue, SIGNAL(triggered()), this, SLOT(setShapeColor())); connect(actionAddCircle, SIGNAL(triggered()), this, SLOT(addShape())); connect(actionAddRectangle, SIGNAL(triggered()), this, SLOT(addShape())); connect(actionAddTriangle, SIGNAL(triggered()), this, SLOT(addShape())); connect(actionRemoveShape, SIGNAL(triggered()), this, SLOT(removeShape())); connect(actionAddRobot, SIGNAL(triggered()), this, SLOT(addRobot())); connect(actionAddSnowman, SIGNAL(triggered()), this, SLOT(addSnowman())); connect(actionAbout, SIGNAL(triggered()), this, SLOT(about())); connect(actionAboutQt, SIGNAL(triggered()), this, SLOT(aboutQt())); connect(undoLimit, SIGNAL(valueChanged(int)), this, SLOT(updateActions())); connect(documentTabs, SIGNAL(currentChanged(int)), this, SLOT(updateActions())); actionOpen->setShortcut(QString("Ctrl+O")); actionClose->setShortcut(QString("Ctrl+W")); actionNew->setShortcut(QString("Ctrl+N")); actionSave->setShortcut(QString("Ctrl+S")); actionExit->setShortcut(QString("Ctrl+Q")); actionRemoveShape->setShortcut(QString("Del")); actionRed->setShortcut(QString("Alt+R")); actionGreen->setShortcut(QString("Alt+G")); actionBlue->setShortcut(QString("Alt+B")); actionAddCircle->setShortcut(QString("Alt+C")); actionAddRectangle->setShortcut(QString("Alt+L")); actionAddTriangle->setShortcut(QString("Alt+T")); m_undoGroup = new QUndoGroup(this); undoView->setGroup(m_undoGroup); undoView->setCleanIcon(QIcon(":/icons/ok.png")); QAction *undoAction = m_undoGroup->createUndoAction(this); QAction *redoAction = m_undoGroup->createRedoAction(this); undoAction->setIcon(QIcon(":/icons/undo.png")); redoAction->setIcon(QIcon(":/icons/redo.png")); menuShape->insertAction(menuShape->actions().at(0), undoAction); menuShape->insertAction(undoAction, redoAction); toolBar->addAction(undoAction); toolBar->addAction(redoAction); newDocument(); updateActions(); };
void CustomGraphicsScene::removeShape(Shape* _shape) { if (m_shapes.contains(_shape)) { // // Удаляем детей // for (QGraphicsItem* childItem : _shape->childItems()) { if (Shape* childShape = dynamic_cast<Shape*>(childItem)) { removeShape(childShape); } } // // Определяем внешние элементы // Shape* previousCard = nullptr; Shape* nextCard = nullptr; if (CardShape* cardShape = dynamic_cast<CardShape*>(_shape)) { if (Flow* startFlow = cardFlow(cardShape, CARD_ON_FLOW_END)) { previousCard = startFlow->startShape(); } if (Flow* endFlow = cardFlow(cardShape, CARD_ON_FLOW_START)) { nextCard = endFlow->endShape(); } } // // Удаляем сам элемент // QList<Shape *> items; items.append(_shape); QList<Shape *> all = m_shapes; bool found; do { found = false; for (int i = 0; i < all.count(); ++i) { if (Flow* item=dynamic_cast<Flow *>(all[i])) { if ((items.contains(item->endShape()) || items.contains(item->startShape())) && !items.contains(item)) { items << item, found = true; } } } } while (found); for(int i = items.count()-1; i>=0; --i) { removeItem(items[i]); disconnect(_shape, SIGNAL(stateIsAboutToBeChangedByUser()), this, SIGNAL(stateChangedByUser())); m_shapes.removeAll(items[i]); delete items[i]; } // // Если надо добавляем связь между разорванными элементами // if (previousCard != nullptr && nextCard != nullptr) { appendShape(new ArrowFlow(previousCard, nextCard)); } } }
void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/) { for (auto& shape : _shapes) { if (shape->getTag() == tag) { removeShape(shape, reduceMassAndMoment); return; } } }
void PhysicsBody::removeShapeByTag(int tag) { for (auto shape : _shapes) { if (shape->getTag() == tag) { removeShape(shape); return; } } }
/** * Draw a bounding box centered at (0,0,0) and translate and rotate it accordingly */ void visualization::DetectionVisualizer::visualizeBox(const detection::BoundingBox &box, const string id, const Vec3f &translation, const Eigen::Quaternionf &rotation) { removeShape(id); addCube(translation, rotation, box.getSize3D()[0], box.getSize3D()[1], box.getSize3D()[2], id); }
//-------------------------------------------------------------- void ofxBulletBaseShape::remove() { if(_bUserDataCreatedInternally) { if(_userPointer != NULL) { delete ((ofxBulletUserData*)_userPointer); _userPointer = NULL; } } removeShape(); removeRigidBody(); }
int ShapeHandler::clear() { int returnCode; for(const std::pair<std::string,Shape*> & element:nameShapeMap) { returnCode = removeShape(element.second->getName(),true); if(returnCode!=0) { return returnCode; } } return 0; }
void CustomGraphicsScene::removeSelectedShapes() { QList<Shape*> selected = selectedShapes(); QList<Shape*> shapes; for (Shape* item : selected) { if (!dynamic_cast<Flow*>(item)) { shapes << dynamic_cast<Shape*>(item); } } for (int i = 0; i < shapes.count(); ++i) { removeShape(shapes[i]); } }
void PhysicsWorld::doRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); // remove shapes for (auto& shape : body->getShapes()) { removeShape(shape); } // remove body if (cpSpaceContainsBody(_cpSpace, body->_cpBody)) { cpSpaceRemoveBody(_cpSpace, body->_cpBody); } }
void ShrinkToFitShapeContainer::unwrapShape(KoShape *shape) { Q_ASSERT(shape->parent() == this); removeShape(shape); shape->setParent(parent()); QSet<KoShape*> delegates = toolDelegates(); delegates.remove(shape); setToolDelegates(delegates); shape->setPosition(position()); shape->setSize(size()); shape->rotate(rotation()); shape->setSelectable(true); }
void PhysicsWorld::doRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); // reset the gravity if (!body->isGravityEnabled()) { body->applyForce(-_gravity); } // remove shaps for (auto& shape : body->getShapes()) { removeShape(shape); } // remove body _info->removeBody(*body->_info); }
void Topology::updateCache(MapWindowProjection &map_projection, rectObj thebounds, bool purgeonly) { if (!triggerUpdateCache) return; if (!shapefileopen) return; in_scale = CheckScale(map_projection.GetMapScaleUser()); if (!in_scale) { // not visible, so flush the cache // otherwise we waste time on looking up which shapes are in bounds flushCache(); triggerUpdateCache = false; return; } if (purgeonly) return; triggerUpdateCache = false; msSHPWhichShapes(&shpfile, thebounds, 0); if (!shpfile.status) { // this happens if entire shape is out of range // so clear buffer. flushCache(); return; } shapes_visible_count = 0; for (int i=0; i<shpfile.numshapes; i++) { if (msGetBit(shpfile.status, i)) { if (shpCache[i]==NULL) { // shape is now in range, and wasn't before shpCache[i] = addShape(i); } shapes_visible_count++; } else { removeShape(i); } } }
void PhysicsWorld::doRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); // reset the gravity if (!body->isGravityEnabled()) { body->applyForce(-m_tGravity); } // remove shaps for (auto shape : *body->getShapes()) { removeShape(dynamic_cast<PhysicsShape*>(shape)); } // remove body m_pInfo->removeBody(body->m_pInfo->getBody()); }
void visualization::DetectionVisualizer::visualizeSampledGrasps() { if (obj().draw_sampled_grasps_) { Point middle; middle.getVector3fMap() = obj().obj_bounding_box_->position_base_kinect_frame_; removeShape(SUPPORT_PLANE); addPlane(*(obj().table_plane_), middle.x, middle.y, middle.z, SUPPORT_PLANE); CloudPtr side_grasps = obj().getSampledSideGrasps(); const pcl::PCLHeader &header = obj().world_obj_->header; transformPointCloud(FOOTPRINT_FRAME, header.frame_id, side_grasps, side_grasps,header.stamp,tf_listener_); visualizeCloud(SIDE_GRASPS, side_grasps, 255, 0, 0); CloudPtr top_grasps = obj().getSampledTopGrasps(); transformPointCloud(FOOTPRINT_FRAME, header.frame_id, top_grasps, top_grasps,header.stamp,tf_listener_); visualizeCloud(TOP_GRASPS, top_grasps, 255, 0, 0); //visualizePoint(middle, 0, 0, 255, CENTROID); obj().draw_sampled_grasps_ = false; } }
void Topology::flushCache() { #ifdef DEBUG_TFC StartupStore(TEXT("---flushCache() starts%s"),NEWLINE); Poco::Timestamp starttick;; #endif switch (cache_mode) { case 0: // Original case 1: // Bounds array in memory for (int i=0; i<shpfile.numshapes; i++) { removeShape(i); } break; case 2: // Shapes in memory for (int i=0; i<shpfile.numshapes; i++) { shpCache[i] = NULL; } break; }//sw shapes_visible_count = 0; #ifdef DEBUG_TFC StartupStore(TEXT(" flushCache() ends (%dms)%s"),Poco::Timespan(starttick.elapsed()).totalMilliseconds(),NEWLINE); #endif }
void Mainscene::update(float deltaTime){ if(enemiesToSpawn > 0 && !waveEnd){ spawnTimer += deltaTime; }else{ if(waveEnd){ spawnTimer = 0; waveTimer -= deltaTime; waveTimerText->color.a = 255; std::ostringstream wts; wts << (int)waveTimer; waveTimerText->setText(wts.str()); if(waveTimer <= 0){ wave ++; std::ostringstream ws; ws << "Wave: "; ws << wave; waveText->setText(ws.str()); waveTimerText->color.a = 0; waveTimer = 8; if(wave > 1){ enemiesToSpawn = 10+(2*wave); enemiesThisWave = enemiesToSpawn; } waveEnd = false; spawnEnemy(); enemiesToSpawn --; } } } if(spawnTimer >= 4.0f){ spawnEnemy(); spawnTimer = 0; enemiesToSpawn --; } if(!usedInit){ usedInit = true; init(); } if(enemies.size() == 0 ){ waveEnd = true; } handleMenuItems(); upgradeBtn->position = Vector2(740,toolbar->position.y); upgradetxt->position = upgradeBtn->position+Vector2(-upgradetxt->getWidth()/2,0); upgradePriceText->position = Vector2(200,toolbar->position.y+30); rangeText->position = Vector2(200,toolbar->position.y-30); damageText->position = Vector2(200,toolbar->position.y); cursor->position = input->getMouseToScreen()+(Vector2(3,cursor->height()*cursor->scale.y-15)); if(input->getMouseButton(1)){ cursor->setPng("assets/pointerClick.png"); }else{ cursor->setPng("assets/pointer.png"); } if(input->getMouseToScreen().y > 640 && !toolbar->mouseOver()){ camera->position.y += (((input->getMouseToScreen().y - 640)/100)*400)*deltaTime; } if(input->getMouseToScreen().y < 80){ camera->position.y -= (((80-input->getMouseToScreen().y)/100)*400)*deltaTime; } if(notenoughAlpha < 0){ notenoughAlpha = 0; } notenoughAlpha -= 150*deltaTime; if(notEnoughText->color.a > 0){ notEnoughText->position.y -= 10*deltaTime; } notEnoughText->color.a = notenoughAlpha; std::ostringstream ss; ss << "Available Workers: "; ss << readyWorkers.size(); availableWorkersText->setText(ss.str()); std::ostringstream cc; cc << "Coins: "; cc << coins; coinsText->setText(cc.str()); priceText->position = pricetag->position+Vector2(-80, 10); counter += deltaTime; if(counter >= 1.0f/60){ fixedUpdate(); counter = 0; } for(unsigned int i = 0; i < bullets.size(); i++){ if(bullets[i]->wantsTwinkle){ Particle* t; t = new Particle(bullets[i]->rotation); twinkles.push_back(t); addEntity(t); t->layer = 3; t->position = bullets[i]->position; bullets[i]->wantsTwinkle = false; } } for(unsigned int i = 0; i < twinkles.size(); i++){ if(twinkles[i]->color.a <= 0){ removeTwinkle(twinkles[i]); } } pricetag->position = Vector2(-1000, -1000); for(unsigned int i = 0; i < menuItems.size(); i++){ if(menuItems[i]->mouseOver() && lockedItem == NULL){ std::ostringstream ct; ct << menuItems[i]->price; ct << " coins"; priceText->setText(ct.str()); pricetag->position = Vector2(menuItems[i]->position.x-180, menuItems[i]->position.y); } } if(input->getKeyDown(SDLK_c)){ coins += 10; } for(unsigned int i = 0; i < bullets.size(); i++){ bool done = false; if(!bullets[i]->hasTarget && bullets[i]->disToTarget < 10){ removeBullet(bullets[i]); done = true; } if(!done){ if(bullets[i]->disToTarget < bullets[i]->target->collisionRadius && bullets[i]->hasTarget){ bullets[i]->target->health -= bullets[i]->damage; bullets[i]->target->slowness += bullets[i]->slowingDamage; coins += 2; bullets[i]->destroyMe = true; bullets[i]->explodeSound->play(); if(bullets[i]->target->health <= 0){ bullets[i]->target->dead = true; } if(bullets[i]->target->dead){ for(unsigned int b = 0; b < bullets.size(); b++){ if(bullets[i]->target->getEntityId() == bullets[b]->target->getEntityId()){ if(bullets[i]->getEntityId() != bullets[b]->getEntityId()){ bullets[b]->lastKnownPos = bullets[i]->lastKnownPos; bullets[b]->hasTarget = false; } } } } } } } int enemycounter = 0; for(unsigned int i = 0; i < enemies.size(); i ++){ if(enemies[i]->dead){ enemycounter ++; } if(enemies[i]->atTarget){ if(pathpoints.size()-1 > (unsigned)enemies[i]->currPathPoint){ enemies[i]->atTarget = false; enemies[i]->currPathPoint ++; enemies[i]->curtarget = pathpoints[enemies[i]->currPathPoint]; } } if(enemies[i]->atTarget ){ if(enemies[i]->dead){ dreamHealth += 3; }else{ dreamHealth -= 10; } removeEnemy(enemies[i]); } } if(enemycounter == enemiesThisWave && enemies.size() > 0){ for(unsigned int i = 0; i < enemies.size(); i ++){ if(enemies[i]->dead){ enemies[i]->speed = 400; } } } for(unsigned int i = 0; i < bullets.size(); i++){ if(bullets[i]->destroyMe){ removeBullet(bullets[i]); } } if(towers.size() > 0 && enemies.size() > 0){ Enemy* target = NULL; for(unsigned int i = 0; i < enemies.size(); i++){ if(!enemies[i]->dead){ target = enemies[i]; i = enemies.size(); } } for(unsigned int t = 0; t < towers.size(); t++){ for(unsigned int i = 0; i < enemies.size(); i ++){ if(!enemies[i]->dead ){ bool canpass = false; if(towers[t]->slowingDamage > 0 && towers[t]->damage == 0 && enemies[i]->slowness < 60){ canpass = true; } if(towers[t]->slowingDamage == 0){ canpass = true; } if(canpass){ Vector2 curdisvec = Vector2(target->position, towers[t]->position); Vector2 disvec = Vector2(enemies[i]->position, towers[t]->position); if(disvec.magnitude() < curdisvec.magnitude()){ target = enemies[i]; } } } } if((towers[t]->target == NULL || (towers[t]->target->dead ))&& towers[t]->ready){ towers[t]->target = target; } if(towers[t]->wantsToShoot && towers[t]->target != NULL && !towers[t]->target->dead){ towers[t]->shootcounter = 0; towers[t]->wantsToShoot = false; Bullet* b; b = towers[t]->shoot(); addEntity(b); b->layer = 4; b->hasTarget = true; bullets.push_back(b); towers[t]->shootSound->play(); } } } for(unsigned int i = 0; i < busyWorkers.size(); i++){ if(busyWorkers[i]->wantsCloud){ SimpleEntity* c; c = new SimpleEntity(); c->position = busyWorkers[i]->cloudpos; c->setPng("assets/Bouwwolkje.png"); c->scale = Vector2(0.5f, 0.5f); addEntity(c); c->layer = 4; clouds.push_back(c); busyWorkers[i]->wantsCloud = false; } if(!busyWorkers[i]->working){ clearWorker(busyWorkers[i]); } } for(unsigned int i = 0; i < clouds.size(); i++){ clouds[i]->rotation += 15*deltaTime; clouds[i]->color.a -= 50*deltaTime; if(clouds[i]->color.a < 0){ removeCloud(clouds[i]); } } if(camera->position.y < 0){ camera->position.y = 0; } if(camera->position.y > 1296-720){ camera->position.y = 1296-720; } if(toolbarMustPop){ if(toolbar->position.y > 720-60){ toolbar->position.y -= 300*deltaTime; } }else{ if(toolbar->position.y < 720+64){ toolbar->position.y += 300*deltaTime; } } if(input->getMouseButtonDown(1)){ if(!toolbar->mouseOver()){ for(unsigned int i = 0; i < towers.size(); i++){ removeShape(towers[i]->shootingRangeShape); } } if(upgradeBtn->mouseOver() && selectedTower->level < 5 && coins-selectedTower->upgradePrice >= 0){ coins -= selectedTower->upgradePrice; selectedTower->upgrade(); setToolBarContent(selectedTower->shootingRange, selectedTower->damage, selectedTower->upgradePrice); if(selectedTower->level < 5){ upgradeBtn->color = WHITE; }else{ upgradeBtn->color = GREY; upgradeBtn->color.a = 100; } }else{ if(upgradeBtn->mouseOver() && selectedTower->level < 5 && coins-selectedTower->upgradePrice <= 0){ notenoughAlpha = 255; notenoughAlpha = 255.0f; notEnoughText->position.y = 720/2; } } } if(dreamHealth == 200){ for(unsigned int i = 0; i < enemies.size(); i++){ enemies[i]->speed = 0; enemies[i]->health = 0; } wintimer += deltaTime; if(wintimer >= 1){ blackfader->color.a += deltaTime*100; if(blackfader->color.a >= 255){ reset(); this->nextScene = true; blackfader->color.a = 0; wintimer = 0; bgmusic->stop(); usedInit = false; } } }else if(dreamHealth == 0){ reset(); } upgradetxt->color = upgradeBtn->color; for(unsigned int i = 0; i < towers.size(); i++){ if(input->getMouseButtonDown(1)){ if(Vector2(input->getMouseToWorld(camera), towers[i]->position).magnitude() < 30 && towers[i]->ready){ towers[i]->shootingRangeShape->circle(towers[i]->shootingRange); addShape(towers[i]->shootingRangeShape); toolbarMustPop = true; setToolBarContent(towers[i]->shootingRange, towers[i]->damage, towers[i]->upgradePrice); selectedTower = towers[i]; if(selectedTower->level < 5){ upgradeBtn->color = WHITE; }else{ upgradeBtn->color = GREY; upgradeBtn->color.a = 100; } i = towers.size(); }else{ if(!toolbar->mouseOver()){ toolbarMustPop = false; } } } } if(lockedItem != NULL ){ if(canPlaceMenuItem(lockedItem)){ lockedItem->color.g = 255; lockedItem->color.b = 255; }else{ lockedItem->color.g = 50; lockedItem->color.b = 50; } } if(dreamHealth > 200){ dreamHealth = 200; } if(dreamHealth < 0){ dreamHealth = 0; } if(dreamHealth > 100.0f){ statusBarHappiness->uvOffset = Vector2(((1.0f/100)*(-(dreamHealth-100))+1), 0); statusBarAnger->uvOffset = Vector2(-1, 0); }else if(dreamHealth < 100.0f){ statusBarHappiness->uvOffset = Vector2(1, 0); statusBarAnger->uvOffset = Vector2(-(1.0f/100.0f)*dreamHealth, 0); }else{ statusBarHappiness->uvOffset = Vector2(1, 0); statusBarAnger->uvOffset = Vector2(-1, 0); } }
void CustomGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent* _event) { // // Обработку производим только после перемещения мыши // if (m_afterMoving) { // // 1. Перемещение карточки на связь // QList<Shape*> selected = selectedShapes(); CardShape* selectedCard = nullptr; ArrowFlow* selectedFlow = nullptr; if (selected.size() == 2) { if (dynamic_cast<CardShape*>(selected.first())) { selectedCard = dynamic_cast<CardShape*>(selected.first()); selectedFlow = dynamic_cast<ArrowFlow*>(selected.last()); } else { selectedCard = dynamic_cast<CardShape*>(selected.last()); selectedFlow = dynamic_cast<ArrowFlow*>(selected.first()); } // // Если это действительно перемещение карточки на связь // if (selectedCard != nullptr && selectedFlow != nullptr && selectedFlow->startShape() != selectedCard && selectedFlow->endShape() != selectedCard) { // // Изымаем карточку из сцены // takeShape(selectedCard); // // Определяем элементы к которым теперь будет присоединена карточка // CardShape* previousCard = dynamic_cast<CardShape*>(selectedFlow->startShape()); CardShape* nextCard = dynamic_cast<CardShape*>(selectedFlow->endShape()); // // Заменяем старую связь на новые // removeShape(selectedFlow); appendShape(new ArrowFlow(previousCard, selectedCard)); if (hasCards(selectedCard)) { appendShape(new ArrowFlow(lastCard(selectedCard), nextCard)); } else { appendShape(new ArrowFlow(selectedCard, nextCard)); } // // Меняем порядок следования фигур // insertShape(selectedCard, previousCard); // // Если предыдущая карточка вложена в группирующий элемент // QGraphicsItem* previousParentItem = previousCard->parentItem(); QGraphicsItem* nextParentItem = nextCard->parentItem(); bool handled = false; if (previousParentItem != nullptr) { const QRectF selectedCardRect = selectedCard->mapToScene(selectedCard->boundingRect()).boundingRect(); const QRectF parentCardRect = previousParentItem->mapToScene(previousParentItem->boundingRect()).boundingRect(); // // ... и если текущая карточка тоже помещена внутрь группирующего элемента // if (parentCardRect.contains(selectedCardRect)) { // // ... поместим её внутрь // const QPointF lastPos = selectedCard->scenePos(); selectedCard->setParentItem(previousParentItem); selectedCard->setPos(previousParentItem->mapFromScene(lastPos)); handled = true; } } // // Если следующая карточка вложена в группирующий элемент // if (!handled && nextParentItem != nullptr) { const QRectF selectedCardRect = selectedCard->mapToScene(selectedCard->boundingRect()).boundingRect(); const QRectF parentCardRect = nextParentItem->mapToScene(nextParentItem->boundingRect()).boundingRect(); // // ... и если текущая карточка тоже помещена внутрь группирующего элемента // if (parentCardRect.contains(selectedCardRect)) { // // ... поместим её внутрь // const QPointF lastPos = selectedCard->scenePos(); selectedCard->setParentItem(nextParentItem); selectedCard->setPos(nextParentItem->mapFromScene(lastPos)); handled = true; } } // // Если не удалось вложить, то убираем родителя у элемента // if (!handled && selectedCard->parentItem() != nullptr) { const QPointF lastPos = selectedCard->scenePos(); selectedCard->setParentItem(nullptr); selectedCard->setPos(lastPos); } } } // // 2. Обработка вложения и вытаскивания элементов из групп сцен и папок // selected = selectedShapes(); if (selected.size() == 1) { selectedCard = dynamic_cast<CardShape*>(selected.first()); if (selectedCard != nullptr) { // // Определим, есть ли группирующий элемент, помеченный на вложение // CardShape* parentCard = nullptr; for (Shape* shape : shapes()) { if (CardShape* card = dynamic_cast<CardShape*>(shape)) { if (card->isOnInstertionState()) { parentCard = card; break; } } } // // Если это перемещение карточки внутри своего родителя, просто снимем режим выделения // if (parentCard != nullptr && selectedCard->parentItem() == parentCard) { parentCard->setOnInstertionState(false); } // // В противном случае // else { // // Вложение // if (parentCard != nullptr) { // // Изымаем карточку из сцены // takeShape(selectedCard); // // Если у группирующего элемента есть дети, то связываем с последней карточкой // if (hasCards(parentCard)) { // // Определяем элементы к которым теперь будет присоединена карточка // CardShape* previousCard = dynamic_cast<CardShape*>(lastCard(parentCard)); Flow* previousCardFlow = cardFlow(previousCard, CARD_ON_FLOW_START); if (previousCardFlow != nullptr) { CardShape* nextCard = dynamic_cast<CardShape*>(previousCardFlow->endShape()); // // Заменяем старую связь на новые // removeShape(previousCardFlow); if (hasCards(selectedCard)) { appendShape(new ArrowFlow(lastCard(selectedCard), nextCard)); } else { appendShape(new ArrowFlow(selectedCard, nextCard)); } } appendShape(new ArrowFlow(previousCard, selectedCard)); // // Меняем порядок следования фигур // insertShape(selectedCard, previousCard); } // // Если детей нет, то связываем непосредственно с группирующим элементом // else { // // Определяем элементы к которым теперь будет присоединена карточка // CardShape* previousCard = parentCard; Flow* previousCardFlow = cardFlow(previousCard, CARD_ON_FLOW_START); if (previousCardFlow != nullptr) { CardShape* nextCard = dynamic_cast<CardShape*>(previousCardFlow->endShape()); // // Заменяем старую связь на новые // removeShape(previousCardFlow); if (hasCards(selectedCard)) { appendShape(new ArrowFlow(lastCard(selectedCard), nextCard)); } else { appendShape(new ArrowFlow(selectedCard, nextCard)); } } appendShape(new ArrowFlow(previousCard, selectedCard)); // // Меняем порядок следования фигур // insertShape(selectedCard, previousCard); } // // Назначаем нового родителя // const QPointF lastPos = selectedCard->scenePos(); selectedCard->setParentItem(parentCard); selectedCard->setPos(parentCard->mapFromScene(lastPos)); parentCard->setOnInstertionState(false); } // // Вытаскивание - соединяем с последней карточкой в сценарии // else if (selectedCard->parentItem() != nullptr) { // // Изымаем карточку из сцены // takeShape(selectedCard); // // Определяем элемент к которому теперь будет присоединена карточка // CardShape* previousCard = dynamic_cast<CardShape*>(lastCard()); // // Добавляем связь // appendShape(new ArrowFlow(previousCard, selectedCard)); // // Меняем порядок следования фигур // insertShape(selectedCard, previousCard); // // Убираем родителя // const QPointF lastPos = selectedCard->scenePos(); selectedCard->setParentItem(nullptr); selectedCard->setPos(lastPos); } } } } } update(); QGraphicsScene::mouseReleaseEvent(_event); m_afterMoving = false; }
void Topology::flushCache() { for (int i=0; i<shpfile.numshapes; i++) { removeShape(i); } shapes_visible_count = 0; }
void Topology::updateCache(rectObj thebounds, bool purgeonly) { if (!triggerUpdateCache) return; if (!shapefileopen) return; in_scale = CheckScale(); if (!in_scale) { // not visible, so flush the cache // otherwise we waste time on looking up which shapes are in bounds flushCache(); triggerUpdateCache = false; in_scale_last = false; return; } if (purgeonly) { in_scale_last = in_scale; return; } triggerUpdateCache = false; #ifdef DEBUG_TFC #ifdef TOPOFASTCACHE StartupStore(TEXT("---UpdateCache() starts, mode%d%s"),cache_mode,NEWLINE); #else StartupStore(TEXT("---UpdateCache() starts, original code%s"),NEWLINE); #endif int starttick = GetTickCount(); #endif #ifdef TOPOFASTCACHE if(msRectOverlap(&shpfile.bounds, &thebounds) != MS_TRUE) { // this happens if entire shape is out of range // so clear buffer. flushCache(); in_scale_last = in_scale; return; } bool smaller = false; bool bigger = false; bool in_scale_again = in_scale && !in_scale_last; int shapes_loaded = 0; shapes_visible_count = 0; in_scale_last = in_scale; switch (cache_mode) { case 0: // Original code plus one special case smaller = (msRectContained(&thebounds, &lastBounds) == MS_TRUE); if (smaller) { //Special case, search inside, we don't need to load additional shapes, just remove shapes_visible_count = 0; for (int i=0; i<shpfile.numshapes; i++) { if (shpCache[i]) { if(msRectOverlap(&(shpCache[i]->shape.bounds), &thebounds) != MS_TRUE) { removeShape(i); } else shapes_visible_count++; } }//for } else { //In this case we have to run the original algoritm msSHPWhichShapes(&shpfile, thebounds, 0); shapes_visible_count = 0; for (int i=0; i<shpfile.numshapes; i++) { if (msGetBit(shpfile.status, i)) { if (shpCache[i]==NULL) { // shape is now in range, and wasn't before shpCache[i] = addShape(i); shapes_loaded++; } shapes_visible_count++; } else { removeShape(i); } }//for } break; case 1: // Bounds array in memory bigger = (msRectContained(&lastBounds, &thebounds) == MS_TRUE); smaller = (msRectContained(&thebounds, &lastBounds) == MS_TRUE); if (bigger || in_scale_again) { //We don't need to remove shapes, just load, so skip loaded ones for (int i=0; i<shpfile.numshapes; i++) { if (shpCache[i]) continue; if(msRectOverlap(&shpBounds[i], &thebounds) == MS_TRUE) { // shape is now in range, and wasn't before shpCache[i] = addShape(i); shapes_loaded++; } }//for shapes_visible_count+=shapes_loaded; } else if (smaller) { //Search inside, we don't need to load additional shapes, just remove for (int i=0; i<shpfile.numshapes; i++) { if (shpCache[i]==NULL) continue; if(msRectOverlap(&shpBounds[i], &thebounds) != MS_TRUE) { removeShape(i); } else shapes_visible_count++; }//for } else { //Otherwise we have to search the all array for (int i=0; i<shpfile.numshapes; i++) { if(msRectOverlap(&shpBounds[i], &thebounds) == MS_TRUE) { if (shpCache[i]==NULL) { // shape is now in range, and wasn't before shpCache[i] = addShape(i); shapes_loaded++; } shapes_visible_count++; } else { removeShape(i); } }//for } break; case 2: // All shapes in memory XShape *pshp; shapes_visible_count = 0; for (int i=0; i<shpfile.numshapes; i++) { pshp = shps[i]; if(msRectOverlap(&(pshp->shape.bounds), &thebounds) == MS_TRUE) { shpCache[i] = pshp; shapes_visible_count++; } else { shpCache[i] = NULL; } }//for break; }//sw lastBounds = thebounds; #else msSHPWhichShapes(&shpfile, thebounds, 0); if (!shpfile.status) { // this happens if entire shape is out of range // so clear buffer. flushCache(); return; } shapes_visible_count = 0; for (int i=0; i<shpfile.numshapes; i++) { if (msGetBit(shpfile.status, i)) { if (shpCache[i]==NULL) { // shape is now in range, and wasn't before shpCache[i] = addShape(i); } shapes_visible_count++; } else { removeShape(i); } } #endif #ifdef DEBUG_TFC long free_size = CheckFreeRam(); StartupStore(TEXT(" UpdateCache() ends, shps_visible=%d ram=%li (%dms)%s"),shapes_visible_count, free_size, GetTickCount()-starttick,NEWLINE); #endif }
void CustomGraphicsScene::appendCard(int _cardType, const QString& _title, const QString& _description) { QPointF scenePosition = sceneRect().center(); // // Если выделена карточка // CardShape* selectedCard = nullptr; CardShape* previousCard = nullptr; CardShape* nextCard = nullptr; CardShape* parentCard = nullptr; if (!selectedItems().isEmpty() && selectedItems().size() == 1 && (selectedCard = dynamic_cast<CardShape*>(selectedItems().last()))) { // // Если карточка вложена в группирующую, то расширяем родителя и вкладываем карту в него // if (selectedCard->parentItem() != nullptr) { // // Запомним родителя // parentCard = dynamic_cast<CardShape*>(selectedCard->parentItem()); } // // Если выделен группирующий элемент, то соединять будем с последним из его детей // if (hasCards(selectedCard)) { selectedCard = dynamic_cast<CardShape*>(lastCard(selectedCard)); } // // Предыдущей будет выделенная // previousCard = selectedCard; // // Настроим позицию для добавления новой карточки // scenePosition = previousCard->scenePos(); scenePosition.setX(scenePosition.x() + previousCard->boundingRect().width() + SHAPE_MOVE_DELTA); scenePosition.setY(scenePosition.y() + previousCard->boundingRect().height() + SHAPE_MOVE_DELTA); // // Определим карточку, которая будет следовать за новой // Flow* flow = cardFlow(previousCard, CARD_ON_FLOW_START); if (flow != nullptr) { nextCard = dynamic_cast<CardShape*>(flow->endShape()); removeShape(flow); } } // // В противном случае добавляем карточку после самой последней карточки, если карточки уже есть // else if (hasCards()) { // // Определим последнюю карточку // Shape* lastCardShape = lastCard(); previousCard = dynamic_cast<CardShape*>(lastCardShape); // // Настроим позицию для добавления новой карточки // scenePosition = previousCard->scenePos(); scenePosition.setX(scenePosition.x() + previousCard->boundingRect().width() + SHAPE_MOVE_DELTA); scenePosition.setY(scenePosition.y() + previousCard->boundingRect().height() + SHAPE_MOVE_DELTA); } // // В противном случае добавляем карточку по середине видимой части сцены, если подключены представления // else if (!views().isEmpty()) { if (QGraphicsView* view = views().last()) { const QRect viewportRect(0, 0, view->viewport()->width(), view->viewport()->height()); const QRectF visibleSceneRect = view->mapToScene(viewportRect).boundingRect(); scenePosition = visibleSceneRect.center(); } } // // Добавляем карточку // CardShape* newCard = new CardShape((CardShape::CardType)_cardType, _title, _description, scenePosition, parentCard); insertShape(newCard, previousCard); // // ... корректируем позицию вкладываемой карточки // if (parentCard != nullptr) { const QPointF newPos = parentCard->mapFromScene(newCard->scenePos()); const QPointF newBottomRightPos = newPos + QPointF(newCard->boundingRect().width(), newCard->boundingRect().height()); // newCard->setParentItem(parentCard); newCard->setPos(newPos); // // ... и масштабируем родителя, если нужно // if (!parentCard->contains(newBottomRightPos)) { QSizeF newSize = parentCard->size(); if (newSize.width() <= newBottomRightPos.x()) { newSize.setWidth(newBottomRightPos.x() + SHAPE_MICROMOVE_DELTA); } if (newSize.height() <= newBottomRightPos.y()) { newSize.setHeight(newBottomRightPos.y() + SHAPE_MICROMOVE_DELTA); } parentCard->setSize(newSize); } } // // Соединяем с предыдущей // if (previousCard != nullptr) { appendShape(new ArrowFlow(previousCard, newCard, parentCard)); } // // Соединяем со следующей // if (nextCard != nullptr) { appendShape(new ArrowFlow(newCard, nextCard, parentCard)); } }
Shape* CustomGraphicsScene::takeShape(Shape* _shape, bool _removeCardFlows) { if (m_shapes.contains(_shape)) { // // При необходимости соединяем между собой окружающие карточку элементы // if (_removeCardFlows) { // // ... если это карточка, конечно // if (CardShape* cardShape = dynamic_cast<CardShape*>(_shape)) { // // Определяем элементы, с которыми соединена карточка, чтобы соеденить их между собой // Flow* startFlow = cardFlow(cardShape, CARD_ON_FLOW_END); Flow* endFlow = nullptr; if (hasCards(cardShape)) { endFlow = cardFlow(lastCard(cardShape), CARD_ON_FLOW_START); } else { endFlow = cardFlow(cardShape, CARD_ON_FLOW_START); } // // ... если есть связь в оба конца, соединяем карточки на концах этих связей // if (startFlow != nullptr && endFlow != nullptr) { startFlow->setEndShape(endFlow->endShape()); removeShape(endFlow); } // // ... если есть связь только в начале, просто уберём эту связь // else if (startFlow != nullptr) { removeShape(startFlow); } // // ... если есть связь только в конце, просто уберём эту связь // else { removeShape(endFlow); } } } // // Извлекаем фигуру // disconnect(_shape, SIGNAL(stateIsAboutToBeChangedByUser()), this, SIGNAL(stateChangedByUser())); m_shapes.removeAll(_shape); // // ... извлекаем все вложенные карточки // for (QGraphicsItem* childItem : _shape->childItems()) { if (CardShape* childCard = dynamic_cast<CardShape*>(childItem)) { const bool DONT_REMOVE_FLOWS = false; takeShape(childCard, DONT_REMOVE_FLOWS); } } return _shape; } return NULL; }
void Renderer::removeShapes(vector< Handle<Device::RTShape> >& shapes) { for (int i=0; i<shapes.size(); i++) { removeShape(shapes[i]); } }
//-------------------------------------------------------------- void ofxBulletTriMeshShape::create( btDiscreteDynamicsWorld* a_world, ofMesh& aMesh, btTransform &a_bt_tr, float a_mass, glm::vec3 aAAbbMin, glm::vec3 aAAbbMax ) { if( aMesh.getMode() != OF_PRIMITIVE_TRIANGLES ) { ofLogWarning() << " ofxBulletTriMeshShape :: create : mesh must be using triangles, not creating!!" << endl; return; } if( aMesh.getNumIndices() < 3 ) { ofLogWarning() << " ofxBulletTriMeshShape :: create : mesh must have indices, not creating!" << endl; return; } if( !_bInited || _shape == NULL ) { int vertStride = sizeof(btVector3); int indexStride = 3*sizeof(int); totalVerts = (int)aMesh.getNumVertices(); totalIndices = (int)aMesh.getNumIndices(); const int totalTriangles = totalIndices / 3; if( bullet_indices != NULL ) { removeShape(); } if( bullet_vertices != NULL ) { removeShape(); } if( bullet_indexVertexArrays != NULL ) { removeShape(); } if( _shape != NULL ) { removeShape(); } bullet_vertices = new btVector3[ totalVerts ]; bullet_indices = new int[ totalIndices ]; auto& tverts = aMesh.getVertices(); auto& tindices = aMesh.getIndices(); for( int i = 0; i < totalVerts; i++ ) { bullet_vertices[i].setValue( tverts[i].x, tverts[i].y, tverts[i].z ); } for( int i = 0; i < totalIndices; i++ ) { bullet_indices[i] = (int)tindices[i]; } bullet_indexVertexArrays = new btTriangleIndexVertexArray(totalTriangles, bullet_indices, indexStride, totalVerts, (btScalar*) &bullet_vertices[0].x(), vertStride); // if you are having trouble with objects falling through, try passing in smaller or larger aabbMin and aabbMax // to something closer to the size of your object // // btVector3 aabbMin(-10000,-10000,-10000),aabbMax(10000,10000,10000); if( aAAbbMin.length() > 0 && aAAbbMax.length() > 0 ) { btVector3 aabbMin( aAAbbMin.x, aAAbbMin.y, aAAbbMin.z ); btVector3 aabbMax( aAAbbMax.x, aAAbbMax.y, aAAbbMax.z ); _shape = new btBvhTriangleMeshShape(bullet_indexVertexArrays, true, aabbMin, aabbMax ); } else { _shape = new btBvhTriangleMeshShape(bullet_indexVertexArrays, true, true ); } } ofxBulletRigidBody::create( a_world, _shape, a_bt_tr, a_mass ); createInternalUserData(); updateMesh( a_world, aMesh ); }
void Mainscene::handleMenuItems(){ for(unsigned int i = 0; i < menuItems.size(); i++){ if(menuItems[i] != NULL){ if(input->getMouseToScreen().x < menuItems[i]->position.x + 50 && input->getMouseToScreen().x > menuItems[i]->position.x - 50 && input->getMouseToScreen().y < menuItems[i]->position.y + 50 && input->getMouseToScreen().y > menuItems[i]->position.y - 50){ if(input->getMouseButtonDown(1)){ addShape(hudRangeIndicator); hudRangeIndicator->circle(menuItems[i]->range); lockedItem = menuItems[i]; } if(menuItems[i]->hoverImgPath != ""){ menuItems[i]->setPng(menuItems[i]->hoverImgPath.c_str()); } }else{ if(menuItems[i]->notHoverImgPath != ""){ menuItems[i]->setPng(menuItems[i]->notHoverImgPath.c_str()); } } } menuItems[i]->scale = menuItems[i]->unselectedScale; menuItems[i]->position = Vector2(1280-menuItems[i]->offsetpos.x, chooseframe->position.y - menuItems[i]->offsetpos.y); } if(lockedItem != NULL){ lockedItem->scale = lockedItem->selectedScale; lockedItem->position = input->getMouseToScreen(); hudRangeIndicator->position = lockedItem->position; } if(input->getMouseButtonUp(1) && lockedItem != NULL ){ removeShape(hudRangeIndicator); Tower* tower; switch(lockedItem->spawnId){ case 1: tower = new BunnyTower(); break; case 2: tower = new DogTower(); break; case 3: tower = new IceTower(); break; case 4: tower = new TurtleTower(); break; case 5: tower = new RobotTower(); break; } addEntity(tower); tower->layer = 2; tower->position = input->getMouseToWorld(camera); if(lockedItem->position.x < (chooseframe->position.x-(chooseframe->width()/2)) && canPlaceMenuItem(lockedItem)){ if((coins-lockedItem->price) >= 0){ if(!assignWorker(tower)){ removeEntity(tower); delete tower; tower = NULL; }else{ towers.push_back(tower); coins -= lockedItem->price; } }else{ notEnoughText->setText("Not enough coins!!"); notenoughAlpha = 255.0f; notEnoughText->position.y = 720/2; removeEntity(tower); delete tower; tower = NULL; } lockedItem->color.g = 255; lockedItem->color.b = 255; lockedItem = NULL; }else{ notenoughAlpha = 255.0f; notEnoughText->setText("Tower can't be placed here!"); removeEntity(tower); delete tower; tower = NULL; lockedItem->color.g = 255; lockedItem->color.b = 255; lockedItem = NULL; } } }