void CTextureDx9::RenderWithoutTransform(LPD3DXSPRITE _lpDSpriteHandle, D3DXVECTOR2 position, D3DXVECTOR2 Center, D3DXVECTOR2 scale, float angle, D3DCOLOR color, RECT *srcRect, float deep) { D3DXVECTOR2 CamTransDistance; CamTransDistance.x = -Camera::getInstance()->GetMatrixTranslate()._41; CamTransDistance.y = Camera::getInstance()->GetMatrixTranslate()._42; position.y += Camera::getInstance()->getBound().bottom; Center.y += Camera::getInstance()->getBound().bottom; D3DXVECTOR3 currentPosition(position.x + CamTransDistance.x, position.y, deep); //toa do trong the gioi thuc D3DXMATRIX oldMatrix; //ma tran luu lai phep transform cua SpriteBatch _lpDSpriteHandle->GetTransform(&oldMatrix); D3DXVECTOR2 centerScale = D3DXVECTOR2(position.x, position.y);//lay vi tri cua vat the lam tam xoay(vi vi tri cua vat la vi tri chinh giua cua vat) D3DXMATRIX matrixScalingRotate; //ma tran rotate, scale D3DXMatrixTransformation2D(&matrixScalingRotate, ¢erScale, 0.0f, &scale, &Center, D3DXToRadian(angle), 0); D3DXMATRIX finalMatrix = matrixScalingRotate * oldMatrix; _lpDSpriteHandle->SetTransform(&finalMatrix); //ma tran chuyen toa do vi tri cua vat the tu the gioi thuc sang toa do trong directX de ve _lpDSpriteHandle->Draw( this->m_lpTexture, srcRect, &D3DXVECTOR3((float)(srcRect->right - srcRect->left)/2, (float)(srcRect->bottom - srcRect->top)/2, 0), ¤tPosition, color); _lpDSpriteHandle->SetTransform(&oldMatrix); }
void WPainterPath::addPath(const WPainterPath& path) { if (currentPosition() != path.beginPosition()) moveTo(path.beginPosition()); Utils::insert(segments_, path.segments_); }
void Scanner_Worker::runScan(int steps, int accuracy) { ScanRunning = true; for(int i = 0; i <= steps; i++) { if(ScanRunning == false) break; Data->mutex.lock(); if(Data->number >= accuracy) { qDebug() << "Current emitted data: Step: " << i << " and counts: " << Data->counts << " and current pos: " << ((qreal)i)/((qreal)steps)*100; emit currentData(qMakePair(i, Data->counts)); emit moveStep(); emit currentPosition(((qreal)i)/((qreal)steps)*100); Data->counts = 0; Data->number = 0; Data->mutex.unlock(); } else { Data->WaitCond.wait(&(Data->mutex)); Data->mutex.unlock(); i--; } } emit ScanFinished(); }
void WPainterPath::connectPath(const WPainterPath& path) { if (currentPosition() != path.beginPosition()) lineTo(path.beginPosition()); addPath(path); }
ScrollResultOneDimensional ScrollAnimator::userScroll( ScrollbarOrientation orientation, ScrollGranularity granularity, float step, float delta) { if (!m_scrollableArea->scrollAnimatorEnabled()) return ScrollAnimatorBase::userScroll(orientation, granularity, step, delta); TRACE_EVENT0("blink", "ScrollAnimator::scroll"); if (granularity == ScrollByPrecisePixel) return ScrollAnimatorBase::userScroll(orientation, granularity, step, delta); float usedPixelDelta = computeDeltaToConsume(orientation, step * delta); FloatPoint pixelDelta = (orientation == VerticalScrollbar ? FloatPoint(0, usedPixelDelta) : FloatPoint(usedPixelDelta, 0)); FloatPoint targetPos = desiredTargetPosition(); targetPos.moveBy(pixelDelta); if (m_animationCurve) { if ((targetPos - m_targetOffset).isZero()) { // Report unused delta only if there is no animation running. See // comment below regarding scroll latching. return ScrollResultOneDimensional(/* didScroll */ true, /* unusedScrollDelta */ 0); } m_targetOffset = targetPos; ASSERT(m_runState == RunState::RunningOnMainThread || m_runState == RunState::RunningOnCompositor || m_runState == RunState::RunningOnCompositorButNeedsUpdate); if (m_runState == RunState::RunningOnCompositor || m_runState == RunState::RunningOnCompositorButNeedsUpdate) { if (registerAndScheduleAnimation()) m_runState = RunState::RunningOnCompositorButNeedsUpdate; return ScrollResultOneDimensional(/* didScroll */ true, /* unusedScrollDelta */ 0); } // Running on the main thread, simply update the target offset instead // of sending to the compositor. m_animationCurve->updateTarget(m_timeFunction() - m_startTime, targetPos); return ScrollResultOneDimensional(/* didScroll */ true, /* unusedScrollDelta */ 0); } if ((targetPos - currentPosition()).isZero()) { // Report unused delta only if there is no animation and we are not // starting one. This ensures we latch for the duration of the // animation rather than animating multiple scrollers at the same time. return ScrollResultOneDimensional(/* didScroll */ false, delta); } m_targetOffset = targetPos; m_startTime = m_timeFunction(); if (registerAndScheduleAnimation()) m_runState = RunState::WaitingToSendToCompositor; return ScrollResultOneDimensional(/* didScroll */ true, /* unusedScrollDelta */ 0); }
void WPainterPath::addPolygon(const std::vector<WPointF>& points) { if (!points.empty()) { unsigned i = 0; if (currentPosition() != points[0]) moveTo(points[i++]); for (; i < points.size(); ++i) lineTo(points[i]); } }
//writing to port int Printer::writeToPort(QString command,int lineNum, bool calcCheckSum){ //analizing command for position tracking QStringList args=command.split(" "); if(command.contains("M104") || command.contains("M109")){ emit settingTemp1(command.mid(command.lastIndexOf("S")+1,command.length()-command.lastIndexOf("S")+1).toDouble()); } if(command.contains("M140") || command.contains("M190")){ emit settingTemp3(command.mid(command.lastIndexOf("S")+1,command.length()-command.lastIndexOf("S")+1).toDouble()); } if(command.contains("G1") || command.contains("G0")){ for(int i=0 ;i <args.size(); i++){ if(args.at(i).contains("X")) curr_pos.setX(args.at(i).mid(1).toDouble()); if(args.at(i).contains("Y")) curr_pos.setY(args.at(i).mid(1).toDouble()); if(args.at(i).contains("Z")){ curr_pos.setZ(args.at(i).mid(1).toDouble()); } } emit currentPosition(curr_pos); } if(this->isConnected()){ if(calcCheckSum){ command=QString("N")+QString::number(lineNum)+QString(" ")+command; command=command+QString("*")+checkSum(command); if(!command.contains("M110")){ this->sentLines.append(command); } else{ this->lineNum=0; } // int temp=rand()%10; // if(temp==0){ // command.replace(5,1,"b"); // qDebug() << "dodaje blad do" << command; // } } int bytes_written =portObj->write(command.toAscii()+"\n"); emit write_to_console(QString("Sending: "+command.toAscii()+"\n").replace("\n","\\n").replace("\r","\\r")); emit write_to_console("Written: "+QString::number(bytes_written)+" bytes"); writeNext=false; } else{ write_to_console(tr("Printer offline")); return -1; } return 0; }
PreviewBoard::PreviewBoard(DockPreviewBoard* dockPreviewBoard, QWidget *parent) : QWidget(parent), dockPreviewBoard_(dockPreviewBoard) { srand ( time(NULL) ); for (int x = 0; x < 19; x++) { for (int y = 0; y < 19; y++) { whiteStoneType_[x][y] = rand()%35; // between 0 and 35 board_[x][y] = 0; } } // boards.clear(); // resize(400, 400); // setMinimumSize ( 200, 200 ); //int minw, int minh // setMaximumSize ( 600, 600 ); // setSizeIncrement ( 0, 0 ); setMouseTracking (true); QString boardDir = Resources::path(); origBoardImage = QPixmap(boardDir + "Beige1.png"); QPalette palette; palette.setBrush(backgroundRole(), QBrush(origBoardImage)); setPalette(palette); setAutoFillBackground ( true ); //connect(this, SIGNAL(click()), this, SLOT(makeFocus())); previewBoardMenu = new QMenu("Preview board menu", this); // boardMenu->setTitle ("Preview board menu"); positionActions_ = new QActionGroup(this); positionActions_->setExclusive(true); currentPositionAct = new QAction(tr("&Current board position"), this); currentPositionAct->setCheckable(true); nextPositionAct = new QAction(tr("&Board next move"), this); nextPositionAct->setCheckable(true); endPositionAct = new QAction(tr("&End position"), this); endPositionAct->setCheckable(true); positionActions_->addAction (currentPositionAct); positionActions_->addAction (nextPositionAct); positionActions_->addAction (endPositionAct); previewBoardMenu->addActions(positionActions_->actions()); connect(currentPositionAct, SIGNAL(triggered()), this, SLOT(currentPosition())); connect(nextPositionAct, SIGNAL(triggered()), this, SLOT(nextPosition())); connect(endPositionAct, SIGNAL(triggered()), this, SLOT(endPosition())); }
void UndoCommand::onExecute(Context* context) { ContextWriter writer(context); Document* document(writer.document()); DocumentUndo* undo = document->getUndo(); Sprite* sprite = document->sprite(); if (context->settings()->undoGotoModified()) { SpritePosition spritePosition; SpritePosition currentPosition(writer.location()->layerIndex(), writer.location()->frame()); if (m_type == Undo) spritePosition = undo->getNextUndoSpritePosition(); else spritePosition = undo->getNextRedoSpritePosition(); if (spritePosition != currentPosition) { current_editor->setLayer(sprite->indexToLayer(spritePosition.layerIndex())); current_editor->setFrame(spritePosition.frameNumber()); // Draw the current layer/frame (which is not undone yet) so the // user can see the doUndo/doRedo effect. current_editor->drawSpriteClipped( gfx::Region(gfx::Rect(0, 0, sprite->width(), sprite->height()))); ui::dirty_display_flag = true; gui_feedback(); base::this_thread::sleep_for(0.01); } } StatusBar::instance() ->showTip(1000, "%s %s", (m_type == Undo ? "Undid": "Redid"), (m_type == Undo ? undo->getNextUndoLabel(): undo->getNextRedoLabel())); // Effectively undo/redo. if (m_type == Undo) undo->doUndo(); else undo->doRedo(); document->generateMaskBoundaries(); document->destroyExtraCel(); // Regenerate extras update_screen_for_document(document); set_current_palette(writer.palette(), false); }
Point AIInput::Private::findNearestTarget() { SPtr<ObjectContainer> objs = core.getObjects(); Point pos = currentPosition(); // Establish search region. Point topLeft = pos; topLeft.x -= radius; topLeft.y -= radius; Point bottomRight = pos; bottomRight.x += radius; bottomRight.y += radius; std::vector<int> potentialTargets = objs->getIdsIn(topLeft, bottomRight); int tgtId = GameObject::InvalidObject; int minDist = 0; for (auto x : potentialTargets) { if (!GameObject::idIsActor(x)) // Quick check. continue; auto tmp = objs->getObject(x); try { // Is it mage? auto tmp2 = std::dynamic_pointer_cast<ActorMage>(tmp); if (!tmp2) // No, it isn't continue; if (tgtId == GameObject::InvalidObject || // First target. dist2(pos, tmp->pos() < minDist)) { // .. or better than old one. minDist = dist2(pos, tmp->pos()); tgtId = tmp->getId(); } } catch (const std::bad_cast&) {}; } Point res; // Target not found. if (tgtId == GameObject::InvalidObject) { res = Point(-1, -1); } else { const auto tmp = objs->getObject(tgtId); res = tmp->pos(); } return res; }
void WPainterPath::moveTo(double x, double y) { /* * first close previous sub path */ if (!segments_.empty() && segments_.back().type() != Segment::MoveTo) { WPointF startP = getSubPathStart(); WPointF currentP = currentPosition(); if (startP != currentP) lineTo(startP.x(), startP.y()); } segments_.push_back(Segment(x, y, Segment::MoveTo)); }
void TransFuncWindowingEventListener::onEvent(cgt::Event* e) { if (_prop == nullptr) return; if (typeid(*e) != typeid(cgt::MouseEvent)) return; // this is only to be executed when the event was accepted, so the static cast is safe. cgt::MouseEvent* me = static_cast<cgt::MouseEvent*>(e); if (me->action() == cgt::MouseEvent::PRESSED) { _mousePressed = true; _mouseDownPosition = cgt::ivec2(me->x(), me->y()); _originalIntensityDomain = _prop->getTF()->getIntensityDomain(); e->ignore(); } else if (_mousePressed && me->action() == cgt::MouseEvent::RELEASED) { _mousePressed = false; e->ignore(); } else if (_mousePressed && me->action() == cgt::MouseEvent::MOTION) { cgt::ivec2 currentPosition(me->x(), me->y()); cgt::ivec2 delta = currentPosition - _mouseDownPosition; // apply shift float shift = static_cast<float>(delta.x) / 1000.f; cgt::vec2 newIntesityDomain = _originalIntensityDomain + shift; // compute and apply scaling float scale = delta.y < 0 ? 1.f + (delta.y / -10.f) : 1.f / (1.f + (delta.y / 10.f)); float length = newIntesityDomain.y - newIntesityDomain.x; float offset = (scale - 1.f) * (length / 2.f); // clamp to avoid scaling to empty interval offset = cgt::clamp(offset, -length/2.f + 0.001f, length/2.f - 0.001f); newIntesityDomain.x -= offset; newIntesityDomain.y += offset; // triple-check for rock solid safety ;) if (newIntesityDomain.x > newIntesityDomain.y) std::swap(newIntesityDomain.x, newIntesityDomain.y); _prop->getTF()->setIntensityDomain(cgt::clamp(newIntesityDomain, cgt::vec2(0.f), cgt::vec2(1.f))); e->ignore(); } }
void SimFilterWheel::select(size_t filterindex) { // make sure the index is legal if (filterindex >= 5) { throw BadParameter("filterindex may not exceed number " "of filters"); } // if we are already at the right position, return unsigned int currentposition = currentPosition(); if (filterindex == currentposition) { return; } // find out how far we have to move int timedelta = filterindex - currentposition; if (timedelta < 0) { timedelta = nFilters() + timedelta; } debug(LOG_DEBUG, DEBUG_LOG, 0, "filterwheel will stop in %d seconds", 2 * timedelta); _changetime = Timer::gettime() + 2 * timedelta; _currentstate = FilterWheel::moving; _currentposition = filterindex; }
void RenderSlider::setValueForPosition(int position) { if (!m_thumb || !m_thumb->renderer()) return; HTMLInputElement* element = static_cast<HTMLInputElement*>(node()); // Calculate the new value based on the position, and send it to the element. StepRange range(element); double fraction = static_cast<double>(position) / trackSize(); if (style()->appearance() == SliderVerticalPart || style()->appearance() == MediaVolumeSliderPart) fraction = 1 - fraction; double value = range.clampValue(range.valueFromProportion(fraction)); element->setValueFromRenderer(serializeForNumberType(value)); // Also update the position if appropriate. if (position != currentPosition()) { setNeedsLayout(true); // FIXME: It seems like this could send extra change events if the same value is set // multiple times with no layout in between. element->dispatchFormControlChangeEvent(); } }
void UndoCommand::onExecute(Context* context) { ContextWriter writer(context); Document* document(writer.document()); DocumentUndo* undo = document->undoHistory(); Sprite* sprite = document->sprite(); SpritePosition spritePosition; const bool gotoModified = Preferences::instance().undo.gotoModified(); if (gotoModified) { SpritePosition currentPosition(writer.site()->layerIndex(), writer.site()->frame()); if (m_type == Undo) spritePosition = undo->nextUndoSpritePosition(); else spritePosition = undo->nextRedoSpritePosition(); if (spritePosition != currentPosition) { current_editor->setLayer(sprite->indexToLayer(spritePosition.layerIndex())); current_editor->setFrame(spritePosition.frame()); // Draw the current layer/frame (which is not undone yet) so the // user can see the doUndo/doRedo effect. current_editor->drawSpriteClipped( gfx::Region(gfx::Rect(0, 0, sprite->width(), sprite->height()))); current_editor->manager()->flipDisplay(); base::this_thread::sleep_for(0.01); } } StatusBar* statusbar = StatusBar::instance(); if (statusbar) statusbar->showTip(1000, "%s %s", (m_type == Undo ? "Undid": "Redid"), (m_type == Undo ? undo->nextUndoLabel().c_str(): undo->nextRedoLabel().c_str())); // Effectively undo/redo. if (m_type == Undo) undo->undo(); else undo->redo(); // After redo/undo, we retry to change the current SpritePosition // (because new frames/layers could be added, positions that we // weren't able to reach before the undo). if (gotoModified) { SpritePosition currentPosition( writer.site()->layerIndex(), writer.site()->frame()); if (spritePosition != currentPosition) { current_editor->setLayer(sprite->indexToLayer(spritePosition.layerIndex())); current_editor->setFrame(spritePosition.frame()); } } document->generateMaskBoundaries(); document->setExtraCel(ExtraCelRef(nullptr)); update_screen_for_document(document); set_current_palette(writer.palette(), false); }
void ChromeClientQt::delegatedScrollRequested(const IntPoint& point) { QPoint currentPosition(m_webPage->mainFrame()->scrollPosition()); emit m_webPage->scrollRequested(point.x() - currentPosition.x(), point.y() - currentPosition.y(), QRect(QPoint(0, 0), m_webPage->viewportSize())); }
// calculates the node transformations for the scene // returns false of the animation is completed or if there is no animation bool Animator::UpdateAnimation(float time, bool loop) { if (currentAnimation && currentAnimation->mDuration > 0.0 && CurAnimation != NULL) { // map into animation's duration double timeInTicks = 0.0f; float dur = (CurAnimation->endFrame - CurAnimation->startFrame)/FPS; if(time == 0) { timeInTicks = 0; } else if (dur > 0.0) { timeInTicks = (CurAnimation->startFrame/FPS) + fmod(time-(1/FPS), dur); } else { timeInTicks = CurAnimation->startFrame/FPS; } if (boneTransforms.size() != currentAnimation->mNumChannels) { boneTransforms.resize(currentAnimation->mNumChannels); } //calculate the transformations for each animation channel for (unsigned int i = 0; i < currentAnimation->mNumChannels; i++) { const aiNodeAnim* channel = currentAnimation->mChannels[i]; //******** Position ***** aiVector3D currentPosition(0, 0, 0); if (channel->mNumPositionKeys > 0) { // Look for present frame number. Search from last position if time is after the last time, else from beginning unsigned int frame = (timeInTicks >= lastTime) ? lastFramePosition[i].x : 0; while (frame < channel->mNumPositionKeys - 1) { if (timeInTicks < channel->mPositionKeys[frame + 1].mTime) { break; } frame++; } // interpolate between this frame's value and next frame's value unsigned int nextFrame = (frame + 1) % channel->mNumPositionKeys; const aiVectorKey& key = channel->mPositionKeys[frame]; const aiVectorKey& nextKey = channel->mPositionKeys[nextFrame]; double dt = nextKey.mTime - key.mTime; if (dt < 0.0) { dt += dur; } if (dt > 0) { float interpolationFactor = (float) ((timeInTicks - key.mTime) / dt); currentPosition = key.mValue + (nextKey.mValue - key.mValue) * interpolationFactor; } else { currentPosition = key.mValue; } lastFramePosition[i].x = frame; } //******** Rotation ********* aiQuaternion currentRotation(1, 0, 0, 0); if (channel->mNumRotationKeys > 0) { unsigned int frame = (timeInTicks >= lastTime) ? lastFramePosition[i].y : 0; while (frame < channel->mNumRotationKeys - 1) { if (timeInTicks < channel->mRotationKeys[frame + 1].mTime) { break; } frame++; } // interpolate between this frame's value and next frame's value unsigned int nextFrame = (frame + 1) % channel->mNumRotationKeys; const aiQuatKey& key = channel->mRotationKeys[frame]; const aiQuatKey& nextKey = channel->mRotationKeys[nextFrame]; double dt = nextKey.mTime - key.mTime; if (dt < 0.0) { dt += dur; } if (dt > 0) { float interpolationFactor = (float) ((timeInTicks - key.mTime) / dt); aiQuaternion::Interpolate(currentRotation, key.mValue, nextKey.mValue, interpolationFactor); } else { currentRotation = key.mValue; } lastFramePosition[i].y = frame; } //******** Scaling ********** aiVector3D currentScaling(1, 1, 1); if (channel->mNumScalingKeys > 0) { unsigned int frame = (timeInTicks >= lastTime) ? lastFramePosition[i].z : 0; while (frame < channel->mNumScalingKeys - 1) { if (timeInTicks < channel->mScalingKeys[frame + 1].mTime) { break; } frame++; } currentScaling = channel->mScalingKeys[frame].mValue; lastFramePosition[i].z = frame; } // build a transformation matrix from the current position, rotation, and scale aiMatrix4x4& transformation = boneTransforms[i]; transformation = aiMatrix4x4(currentRotation.GetMatrix()); transformation.a1 *= currentScaling.x; transformation.b1 *= currentScaling.x; transformation.c1 *= currentScaling.x; transformation.a2 *= currentScaling.y; transformation.b2 *= currentScaling.y; transformation.c2 *= currentScaling.y; transformation.a3 *= currentScaling.z; transformation.b3 *= currentScaling.z; transformation.c3 *= currentScaling.z; transformation.a4 = currentPosition.x; transformation.b4 = currentPosition.y; transformation.c4 = currentPosition.z; } lastTime = timeInTicks; // update all node transformations with the results UpdateTransforms(rootNode, boneTransforms); if(time <= dur || loop) { if(CurAnimation != NULL) CurAnimation->isPlaying = true; return true; } } if(CurAnimation != NULL) CurAnimation->isPlaying = false; return false; }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //about window this->aboutWindow = new AboutWindow(); this->aboutWindow->hide(); this->aboutWindow->move(this->geometry().center()-this->aboutWindow->geometry().center()); //calibrate Dialog this->calibrateDialog = new CalibrateDialog(); this->calibrateDialog->hide(); this->calibrateDialog->move(this->geometry().center()-this->calibrateDialog->geometry().center()); //option Dialog this->optionDialog = new OptionDialog(); this->optionDialog->hide(); this->optionDialog->move(this->geometry().center()-this->optionDialog->geometry().center()); //slice dialog this->sliceDialog = new SliceDialog(ui->glWidget, this); this->sliceDialog->hide(); this->sliceDialog->move(this->geometry().center()-this->sliceDialog->geometry().center()); //macros window this->macrosWindow = new MacrosWindow(); this->macrosWindow->hide(); this->macrosWindow->move(this->geometry().center()-this->macrosWindow->geometry().center()); connect(this->macrosWindow, SIGNAL(buttonAdded(MacroButton*)), this, SLOT(addMacroBtn(MacroButton*))); connect(this->macrosWindow, SIGNAL(buttonRemoved(MacroButton*)), this, SLOT(removeMacroBtn(MacroButton*))); //sd card window this->sdCardWindow = new SDCardWindow(); this->sdCardWindow->hide(); this->sdCardWindow->move(this->geometry().center()-this->sdCardWindow->geometry().center()); connect(this->sdCardWindow, SIGNAL(sdFile_selected(QString)), this, SLOT(sdFile_selected(QString))); connect(this->optionDialog, SIGNAL(slicerPathChanged(QString)), this->sliceDialog, SLOT(updateSlicerPath(QString))); connect(this->optionDialog, SIGNAL(outputPathChanged(QString)), this->sliceDialog, SLOT(updateOutputPath(QString))); connect(this->optionDialog, SIGNAL(newSize(QVector3D)), this, SLOT(updatadeSize(QVector3D))); connect(this->optionDialog, SIGNAL(newList(QList<Material*>*)), this->sliceDialog, SLOT(setMaterialList(QList<Material*>*))); connect(this->sliceDialog, SIGNAL(fileSliced(QString)), this, SLOT(loadFile(QString))); //set version number this->setWindowTitle("YARRH v"+QString::number(VERSION_MAJOR)+"."+QString::number(VERSION_MINOR)+"."+QString::number(VERSION_REVISION)); this->aboutWindow->setVersion(VERSION_MAJOR,VERSION_MINOR,VERSION_REVISION); //setting up printer and its thread this->printerObj = new Printer(); QThread *qthread = new QThread(); //connecting ui to printer connect(printerObj, SIGNAL(write_to_console(QString)), ui->inConsole, SLOT(appendPlainText(QString)), Qt::QueuedConnection); connect(this->macrosWindow, SIGNAL(writeToPrinter(QString)), printerObj, SLOT(send_now(QString)),Qt::QueuedConnection); connect(ui->fanSpinBox, SIGNAL(valueChanged(int)), printerObj, SLOT(setFan(int)), Qt::QueuedConnection); ui->fanSpinBox->blockSignals(true); connect(this->printerObj, SIGNAL(SDFileList(QStringList)), this->sdCardWindow, SLOT(updateFileList(QStringList))); connect(this->printerObj, SIGNAL(uploadProgress(int,int)), this->sdCardWindow, SLOT(updateProgress(int,int))); this->sdCardWindow->setPrinter(this->printerObj); //connecting move btns connect(ui->homeX, SIGNAL(clicked()), printerObj, SLOT(homeX()), Qt::QueuedConnection); connect(ui->homeY, SIGNAL(clicked()), printerObj, SLOT(homeY()), Qt::QueuedConnection); connect(ui->homeAll, SIGNAL(clicked()), printerObj, SLOT(homeAll()), Qt::QueuedConnection); //connect monit temp checkbox connect(ui->graphGroupBox, SIGNAL(toggled(bool)), printerObj, SLOT(setMonitorTemperature(bool)),Qt::QueuedConnection); //connect printer to temp widget connect(printerObj, SIGNAL(currentTemp(double,double,double)), this, SLOT(drawTemp(double,double,double))); connect(printerObj, SIGNAL(progress(int,int)), this, SLOT(updateProgress(int,int))); connect(printerObj, SIGNAL(connected(bool)), this, SLOT(printerConnected(bool))); //setting ui temp from gcode connect(printerObj, SIGNAL(settingTemp1(double)), this, SLOT(setTemp1FromGcode(double))); connect(printerObj, SIGNAL(settingTemp3(double)), this, SLOT(setTemp3FromGcode(double))); //updating head position in ui connect(printerObj, SIGNAL(currentPosition(QVector3D)), this, SLOT(updateHeadPosition(QVector3D))); //print finished signal connect(printerObj, SIGNAL(printFinished(bool)), this, SLOT(printFinished(bool))); //connect calibration dialog to printer connect(calibrateDialog, SIGNAL(writeToPrinter(QString)), printerObj, SLOT(send_now(QString)),Qt::QueuedConnection); //connect z slider connect(ui->zSlider, SIGNAL(valueChanged(int)), this, SLOT(moveZ(int))); connect(ui->zSlider, SIGNAL(sliderMoved(int)), this, SLOT(updateZ(int))); //connect action load connect(ui->actionLoad, SIGNAL(triggered()), this, SLOT(loadFile())); printerObj->moveToThread(qthread); qthread->start(QThread::HighestPriority); this->portEnum = new QextSerialEnumerator(this); this->portEnum->setUpNotifications(); QList<QextPortInfo> ports = this->portEnum->getPorts(); //finding avalible ports foreach (QextPortInfo info, ports) { ui->portCombo->addItem(info.portName); }
void ofApp::drawContFinder(){ ofSetBackgroundAuto(bShowLabels); ofxCv::RectTracker& tracker = contFinder.getTracker(); if(bShowLabels) { ofSetColor(255); if(bBackgroundLearned){ grayDiffOfImage.draw(0,0); } else { grayImage.draw(0, 0); } contFinder.draw(); for(int i = 0; i < contFinder.size(); i++) { ofPoint center = ofxCv::toOf(contFinder.getCenter(i)); ofPushMatrix(); ofTranslate(center.x, center.y); int label = contFinder.getLabel(i); string msg = ofToString(label) + ":" + ofToString(tracker.getAge(label)); ofDrawBitmapString(msg, 0, 0); ofVec2f velocity = ofxCv::toOf(contFinder.getVelocity(i)); ofScale(5, 5); ofLine(0, 0, velocity.x, velocity.y); ofPopMatrix(); } } else { for(int i = 0; i < contFinder.size(); i++) { unsigned int label = contFinder.getLabel(i); // only draw a line if this is not a new label if(tracker.existsPrevious(label)) { // use the label to pick a random color ofSeedRandom(label << 24); ofSetColor(ofColor::fromHsb(ofRandom(255), 255, 255)); // get the tracked object (cv::Rect) at current and previous position const cv::Rect& previous = tracker.getPrevious(label); const cv::Rect& current = tracker.getCurrent(label); // get the centers of the rectangles ofVec2f previousPosition(previous.x + previous.width / 2, previous.y + previous.height / 2); ofVec2f currentPosition(current.x + current.width / 2, current.y + current.height / 2); ofLine(previousPosition, currentPosition); } } } // this chunk of code visualizes the creation and destruction of labels const vector<unsigned int>& currentLabels = tracker.getCurrentLabels(); const vector<unsigned int>& previousLabels = tracker.getPreviousLabels(); const vector<unsigned int>& newLabels = tracker.getNewLabels(); const vector<unsigned int>& deadLabels = tracker.getDeadLabels(); ofSetColor(ofxCv::cyanPrint); for(int i = 0; i < currentLabels.size(); i++) { int j = currentLabels[i]; ofLine(j, 0, j, 4); } ofSetColor(ofxCv::magentaPrint); for(int i = 0; i < previousLabels.size(); i++) { int j = previousLabels[i]; ofLine(j, 4, j, 8); } ofSetColor(ofxCv::yellowPrint); for(int i = 0; i < newLabels.size(); i++) { int j = newLabels[i]; ofLine(j, 8, j, 12); } ofSetColor(ofColor::white); for(int i = 0; i < deadLabels.size(); i++) { int j = deadLabels[i]; ofLine(j, 12, j, 16); } }
void current_update(time_t *timekeys, int count_timekeys) { time_t curr_timestamp=time(NULL)+localtime_offset; // текущее время + смещение по Иркутску //time_t curr_timestamp=57000; current_usable=gmtime(&curr_timestamp); // дневное timestamp-смещение момента "сейчас" current=(*current_usable).tm_hour*3600+(*current_usable).tm_min*60+(*current_usable).tm_sec; // если уже бросалось оповещение, то снимаем его if (is_notify==1) is_notify=0; // смотрим, где мы находимся относительно временных меток уроков или перемен int currPos=currentPosition(timekeys, count_timekeys, current); int diff=0; strcpy(textstring, ""); strcat(textstring, "Время: "); strcat(textstring, timeAppearance(current)); strcat(textstring, "\nСейчас: "); isbreak=currPos%2; numbreak=currPos/2+1; if (currPos==-1) { diff=timekeys[0]-current; strcat(textstring, "время до уроков\n"); strcat(textstring, "До начала уроков осталось: "); strcat(textstring, timeAppearance(diff)); strcat(textstring, "\n"); if (diff==notify_offset) is_notify=1; // если смещение искомое, бросаем уведомление } else { if (currPos==-2) strcat(textstring, "время после уроков\n"); else { if (isbreak) { diff=timekeys[currPos+1]-current; sprintf(buf, "%d\n", numbreak); strcat(textstring, "перемена "); strcat(textstring, buf); strcat(textstring, "До урока осталось: "); strcat(textstring, timeAppearance(diff)); strcat(textstring, "\n"); } else { sprintf(buf, "%d\n", numbreak); strcat(textstring, "урок "); strcat(textstring, buf); if (count_timekeys-currPos!=2) { diff=timekeys[currPos+1]-current; strcat(textstring, "До перемены осталось: "); strcat(textstring, timeAppearance(diff)); strcat(textstring, "\n"); } } if (diff==notify_offset) is_notify=1; // если смещение искомое, бросаем уведомление diff=timekeys[count_timekeys-1]-current; strcat(textstring, "\nДо конца уроков осталось: "); strcat(textstring, timeAppearance(diff)); if (diff==notify_offset) is_notify=1; // если смещение искомое, бросаем уведомление diff=current-timekeys[0]; strcat(textstring, "\nС начала уроков прошло: "); strcat(textstring, timeAppearance(diff)); } } }
void nebulaContourFinder::draw(int x, int y, int w, int h){ if(!enabled || blurred.size() == cv::Size(0,0)) return; ofxCv::RectTracker& tracker = finder.getTracker(); ofPushMatrix(); ofScale(w/blurred.cols, h/blurred.rows); ofTranslate(x,y); if(showLabels) { finder.draw(); for(int i = 0; i < finder.size(); i++) { ofPoint center = ofxCv::toOf(finder.getCenter(i)); ofPushMatrix(); ofTranslate(center.x, center.y); int label = finder.getLabel(i); string msg = ofToString(label) + ":" + ofToString(tracker.getAge(label)); ofDrawBitmapString(msg, 0, 0); ofDrawCircle(0,0,2); ofVec2f pt = ofxCv::toOf(finder.getCentroid(i)); pt.x /= blurred.cols; pt.y /= blurred.rows; msg = ofToString(pt); ofDrawBitmapString(msg, 0, 12); ofVec2f velocity = ofxCv::toOf(finder.getVelocity(i)); ofScale(5, 5); ofDrawLine(0, 0, velocity.x, velocity.y); ofPopMatrix(); } } else { for(int i = 0; i < finder.size(); i++) { unsigned int label = finder.getLabel(i); // only draw a line if this is not a new label if(tracker.existsPrevious(label)) { // use the label to pick a random color ofSeedRandom(label << 24); ofSetColor(ofColor::fromHsb(ofRandom(255), 255, 255)); // get the tracked object (cv::Rect) at current and previous position const cv::Rect& previous = tracker.getPrevious(label); const cv::Rect& current = tracker.getCurrent(label); // get the centers of the rectangles ofVec2f previousPosition(previous.x + previous.width / 2, previous.y + previous.height / 2); ofVec2f currentPosition(current.x + current.width / 2, current.y + current.height / 2); ofDrawLine(previousPosition, currentPosition); } } } ofTranslate(x,y); // this chunk of code visualizes the creation and destruction of labels const vector<unsigned int>& currentLabels = tracker.getCurrentLabels(); const vector<unsigned int>& previousLabels = tracker.getPreviousLabels(); const vector<unsigned int>& newLabels = tracker.getNewLabels(); const vector<unsigned int>& deadLabels = tracker.getDeadLabels(); ofSetColor(ofxCv::cyanPrint); for(int i = 0; i < currentLabels.size(); i++) { int j = currentLabels[i]; ofDrawLine(j, 0, j, 4); } ofSetColor(ofxCv::magentaPrint); for(int i = 0; i < previousLabels.size(); i++) { int j = previousLabels[i]; ofDrawLine(j, 4, j, 8); } ofSetColor(ofxCv::yellowPrint); for(int i = 0; i < newLabels.size(); i++) { int j = newLabels[i]; ofDrawLine(j, 8, j, 12); } ofSetColor(ofColor::white); for(int i = 0; i < deadLabels.size(); i++) { int j = deadLabels[i]; ofDrawLine(j, 12, j, 16); } ofPopMatrix(); ofPopStyle(); }
void Spectrometer::updatePosition(int steps, bool dir) { // QString debug = " (Spectrometer::updatePosition): Stepper moved for " + QString::number(steps) + " in direction " + QString::number(dir); // qDebug() << debug; emit currentPosition(steps, dir); }
DebuggerCallFrame::DebuggerCallFrame(CallFrame* callFrame, const ShadowChicken::Frame& frame) : m_validMachineFrame(callFrame) , m_shadowChickenFrame(frame) { m_position = currentPosition(); }
void ScrollAnimator::updateCompositorAnimations() { if (m_compositorAnimationId && m_runState != RunState::RunningOnCompositor && m_runState != RunState::RunningOnCompositorButNeedsUpdate) { // If the current run state is WaitingToSendToCompositor but we have a // non-zero compositor animation id, there's a currently running // compositor animation that needs to be removed here before the new // animation is added below. ASSERT(m_runState == RunState::WaitingToCancelOnCompositor || m_runState == RunState::WaitingToSendToCompositor); abortAnimation(); m_compositorAnimationId = 0; m_compositorAnimationGroupId = 0; if (m_runState == RunState::WaitingToCancelOnCompositor) { resetAnimationState(); return; } } if (m_runState == RunState::WaitingToSendToCompositor || m_runState == RunState::RunningOnCompositorButNeedsUpdate) { if (m_runState == RunState::RunningOnCompositorButNeedsUpdate) { // Abort the running animation before a new one with an updated // target is added. abortAnimation(); m_compositorAnimationId = 0; m_compositorAnimationGroupId = 0; m_animationCurve->updateTarget(m_timeFunction() - m_startTime, m_targetOffset); m_runState = RunState::WaitingToSendToCompositor; } if (!m_animationCurve) { m_animationCurve = adoptPtr(Platform::current()->compositorSupport() ->createScrollOffsetAnimationCurve( m_targetOffset, WebCompositorAnimationCurve::TimingFunctionTypeEaseInOut, m_lastGranularity == ScrollByPixel ? WebScrollOffsetAnimationCurve::ScrollDurationInverseDelta : WebScrollOffsetAnimationCurve::ScrollDurationConstant)); m_animationCurve->setInitialValue(currentPosition()); } bool sentToCompositor = false; if (!m_scrollableArea->shouldScrollOnMainThread()) { OwnPtr<WebCompositorAnimation> animation = adoptPtr( Platform::current()->compositorSupport()->createAnimation( *m_animationCurve, WebCompositorAnimation::TargetPropertyScrollOffset)); // Being here means that either there is an animation that needs // to be sent to the compositor, or an animation that needs to // be updated (a new scroll event before the previous animation // is finished). In either case, the start time is when the // first animation was initiated. This re-targets the animation // using the current time on main thread. animation->setStartTime(m_startTime); int animationId = animation->id(); int animationGroupId = animation->group(); sentToCompositor = addAnimation(animation.release()); if (sentToCompositor) { m_runState = RunState::RunningOnCompositor; m_compositorAnimationId = animationId; m_compositorAnimationGroupId = animationGroupId; } } if (!sentToCompositor) { if (registerAndScheduleAnimation()) m_runState = RunState::RunningOnMainThread; } } }
void Robot::moveTo(Location location) { Location target = getStageLocation(location); player_color cyan; cyan.red = 0; cyan.green = 255; cyan.blue = 255; cyan.alpha = 255; double biggestSize = getWidth() > getHeight() ? getWidthMeters() : getHeightMeters(); pp->SetMotorEnable(true); pp->SetSpeed(0, 0); double d; while((d = distanceTo(target)) > biggestSize/2) { pc->Read(); gp->Clear(); Position currentPosition(pp->GetXPos(), pp->GetYPos(), pp->GetYaw()); setPosition(currentPosition); drawPoint(target, cyan); player_point_2d points[2]; points[0].px = getX(); points[0].py = getY(); points[1].px = target.getX(); points[1].py = target.getY(); gp->Color(255, 0, 0, 255); gp->DrawPolyline(points, 2); double targetYaw = angleTo(target); double yawDiff = targetYaw - getYaw(); while(yawDiff < dtor(180)) yawDiff += dtor(360); while(yawDiff > dtor(180)) yawDiff -= dtor(360); double speed; if(abs(yawDiff) < 0.1) speed = maxSpeed; else if(abs(yawDiff) > dtor(45)) speed = 0; else speed = maxSpeed * (1 - (abs(yawDiff) / dtor(45))); if(speed > maxSpeed) speed = maxSpeed; double turnSpeed = yawDiff; if(abs(turnSpeed) > maxTurnSpeed) turnSpeed = (turnSpeed/abs(turnSpeed))*maxTurnSpeed; pp->SetSpeed(speed, turnSpeed); } pp->SetSpeed(0, 0); pp->SetMotorEnable(false); }
FloatPoint ScrollAnimator::desiredTargetPosition() const { return (m_animationCurve || m_runState == RunState::WaitingToSendToCompositor) ? m_targetOffset : currentPosition(); }
void UndoCommand::onExecute(Context* context) { ContextWriter writer(context); Doc* document(writer.document()); DocUndo* undo = document->undoHistory(); #ifdef ENABLE_UI Sprite* sprite = document->sprite(); SpritePosition spritePosition; const bool gotoModified = (Preferences::instance().undo.gotoModified() && context->isUIAvailable() && current_editor); if (gotoModified) { SpritePosition currentPosition(writer.site()->layer(), writer.site()->frame()); if (m_type == Undo) spritePosition = undo->nextUndoSpritePosition(); else spritePosition = undo->nextRedoSpritePosition(); if (spritePosition != currentPosition) { Layer* selectLayer = spritePosition.layer(); if (selectLayer) current_editor->setLayer(selectLayer); current_editor->setFrame(spritePosition.frame()); // Draw the current layer/frame (which is not undone yet) so the // user can see the doUndo/doRedo effect. current_editor->drawSpriteClipped( gfx::Region(gfx::Rect(0, 0, sprite->width(), sprite->height()))); current_editor->manager()->flipDisplay(); base::this_thread::sleep_for(0.01); } } // Get the stream to deserialize the document range after executing // the undo/redo action. We cannot yet deserialize the document // range because there could be inexistent layers. std::istream* docRangeStream; if (m_type == Undo) docRangeStream = undo->nextUndoDocRange(); else docRangeStream = undo->nextRedoDocRange(); StatusBar* statusbar = StatusBar::instance(); if (statusbar) { std::string msg; if (m_type == Undo) msg = "Undid " + undo->nextUndoLabel(); else msg = "Redid " + undo->nextRedoLabel(); if (Preferences::instance().undo.showTooltip()) statusbar->showTip(1000, msg.c_str()); else statusbar->setStatusText(0, msg.c_str()); } #endif // ENABLE_UI // Effectively undo/redo. if (m_type == Undo) undo->undo(); else undo->redo(); #ifdef ENABLE_UI // After redo/undo, we retry to change the current SpritePosition // (because new frames/layers could be added, positions that we // weren't able to reach before the undo). if (gotoModified) { Site newSite = context->activeSite(); SpritePosition currentPosition( newSite.layer(), newSite.frame()); if (spritePosition != currentPosition) { Layer* selectLayer = spritePosition.layer(); if (selectLayer) current_editor->setLayer(selectLayer); current_editor->setFrame(spritePosition.frame()); } } // Update timeline range. We've to deserialize the DocRange at // this point when objects (possible layers) are re-created after // the undo and we can deserialize them. if (docRangeStream) { Timeline* timeline = App::instance()->timeline(); if (timeline) { DocRange docRange; if (docRange.read(*docRangeStream)) timeline->setRange(docRange); } } #endif // ENABLE_UI document->generateMaskBoundaries(); document->setExtraCel(ExtraCelRef(nullptr)); #ifdef ENABLE_UI update_screen_for_document(document); #endif set_current_palette(writer.palette(), false); }